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
92867096c6c83417789e18f6d9b4ae45f601dad3
C++
CocoMelon/HalfEdge
/Brep/HE.h
UTF-8
1,405
3.21875
3
[]
no_license
#pragma once #include<vector> class Face; class Loop; class HalfEdge; class Edge; class Vertex; class Solid { public: Solid *prevs, *nexts; Face *sfaces; Edge *sedges; Solid() :prevs(nullptr), nexts(nullptr), sfaces(nullptr), sedges(nullptr) { } void AddFace(Face *f); bool RemoveFace(Face *f); void AddEdge(Edge *edge); bool RemoveEdge(Edge *edge); }; class Face { public: static int num; static std::vector<Face *> fList; Face *prevf, *nextf; Solid *fsolid; Loop *floops; int id; Face() :prevf(nullptr), nextf(nullptr), fsolid(nullptr), floops(nullptr) { id = num++; fList.push_back(this); } void AddLoop(Loop *lp); bool RemoveLoop(Loop *lp); }; class Loop { public: Loop *prevl, *nextl; Face *lface; HalfEdge *ledg; bool inner; Loop() :prevl(nullptr), nextl(nullptr), lface(nullptr), ledg(nullptr), inner(false) { }; }; class HalfEdge { public: HalfEdge *prev, *next; Loop *wloop; Edge *edg; Vertex *vtx;//start vertex of halfedge HalfEdge() :prev(nullptr), next(nullptr), wloop(nullptr), edg(nullptr), vtx(nullptr) { } }; class Edge { public: Edge *preve, *nexte; HalfEdge *he1, *he2; Edge() :preve(nullptr), nexte(nullptr), he1(nullptr), he2(nullptr) { } }; class Vertex { public: static int num; static std::vector<Vertex *> vList; float x, y, z; int id; Vertex(float point[3]) :x(point[0]), y(point[1]), z(point[2]) { id = num++; vList.push_back(this); } };
true
0b2fc6e62c15ec924bb1b18719a13f3f9b5b8543
C++
RamiroRD/sensor-tpiid
/src/common/Log.cpp
UTF-8
7,505
3.296875
3
[]
no_license
#include "common/Log.h" #include <iostream> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <sys/file.h> #include <cstring> #include <cassert> #include "common/paths.h" static constexpr size_t HEADER_SIZE = sizeof(Count)+sizeof(Index); static constexpr size_t RECORD_SIZE = sizeof(Temperature) + sizeof(Humidity) + sizeof(Pressure) + 2*sizeof(Velocity) + sizeof(time_t); static const char * LOCK_FILENAME="lock"; Log::Log(bool readOnly) : readOnlyMode(readOnly),storageFD(-1),lockFD(-1) { /* * Tamaño que debería tener el archivo si esta todo bien. Se cuentan los dos * primeros campos más la cantidad de records direccionables según * sizeof(Index). */ const size_t MIN_SIZE = 2*sizeof(Index); const size_t MAX_SIZE = MIN_SIZE + RECORD_SIZE*(1<<(sizeof(Index)*8)); /* Nos movemos al directorio donde está el log */ if(chdir(LOG_PATH) == -1) { std::cerr << "<1>No se puede acceder al directorio " << LOG_PATH << ". Razón: " << strerror(errno) << std::endl; exit(-1); } /* Abrimos el archivo en el modo que corresponda */ if(readOnlyMode) storageFD = open(LOG_FILENAME, O_RDONLY); else storageFD = open(LOG_FILENAME, O_CREAT | O_RDWR); /* * Reportar el caso en que no se puede abrir ni crear el archivo. */ if(storageFD == -1) { std::cerr << "<1>No se pudo abrir log. Razón: " << strerror(errno) << std::endl; exit(-1); } /* * Verificamos que el tamaño del archivo esté dentro de los límites como * primera medida de integridad. Caso contrario creamos un log nuevo. */ const size_t SIZE_AT_OPEN = lseek(storageFD,0,SEEK_END); if(SIZE_AT_OPEN < MIN_SIZE || SIZE_AT_OPEN>MAX_SIZE-1) { std::cerr << "<2>Log tiene tamaño inválido. " << std::endl; create(); }else{ /* * Hay que verificar que el espacio donde están los registros sea * múltiplos del tamaño del registro */ if((SIZE_AT_OPEN-HEADER_SIZE)%RECORD_SIZE != 0) std::cerr << "<2>Espacio de records tiene tamaño incorrecto." << std::endl; } /* * A esta altura debería estar garantizado que están los dos primeros campos * del archivo están presentes y está todo usable. */ std::cerr << "Log abierto con éxito "; if(readOnlyMode) std::cerr << "en modo de sólo lectura." << std::endl; else std::cerr << "en modo de lectura y escritura." << std::endl; std::cerr << "Cantidad de registros: " << getCount() << std::endl; std::cerr << "Índice del último escrito (base cero): " << getLastIndex() << std::endl; } Count Log::getCount() { Count aux; lseek(storageFD,0,SEEK_SET); if(read(storageFD,&aux,sizeof(Count)) == -1) { std::cerr << "<1>No se pudo conseguir cantidad de entradas. Saliendo..." << std::endl; exit(-1); } return aux; } Index Log::getLastIndex() { Index aux; lseek(storageFD,sizeof(Count),SEEK_SET); if(read(storageFD,&aux,sizeof(Index)) == -1) { std::cerr << "<1>No se pudo conseguir índice de último record. Saliendo..." << std::endl; exit(-1); } return aux; } void Log::setCount(Count count) { lseek(storageFD,0,SEEK_SET); if(write(storageFD,&count,sizeof(Count)) == -1) { std::cerr << "<1>No se pudo escribir campo de cantidad. Saliendo..." << std::endl; exit(-1); } } void Log::setLastIndex(Index index) { lseek(storageFD,sizeof(Count),SEEK_SET); if(write(storageFD,&index,sizeof(Index)) == -1) { std::cerr << "<1>No se pudo escribir índice de último record. Saliendo..." << std::endl; exit(-1); } } /* * Crea un log vacío bien formado. Se asume que ya esta seteado el working * directory. Este método deja el archivo abierto! */ void Log::create() { if(!readOnlyMode) { std::cerr << "Creando log..." << std::endl; close(storageFD); storageFD = open(LOG_FILENAME, O_CREAT | O_RDWR); if(storageFD == -1) { std::cerr << "<1>No se pudo crear log. Razón: " << strerror(errno) << std::endl; exit(-1); } lseek(storageFD,0,SEEK_SET); setCount(0); setLastIndex(-1); }else{ std::cerr << "<1>Estamos en modo lectura, saliendo..." << std::endl; exit(-1); } } bool Log::isEmpty() { return (getCount()==0); } bool Log::isFull() { return (getCount()==((1<<sizeof(Count))-1)); } void Log::insert(const Record &record) { if(!readOnlyMode) { const Count count = getCount()+1; // Se hace el incremento aca para que se de el overflow naturalmente const Index last = getLastIndex()+1; const size_t writePos = HEADER_SIZE + last*RECORD_SIZE; errno = 0; lseek(storageFD,writePos,SEEK_SET); write(storageFD, &record.temp, sizeof(record.temp)); write(storageFD, &record.hum, sizeof(record.hum)); write(storageFD, &record.pres, sizeof(record.pres)); write(storageFD, &record.windX, sizeof(record.windX)); write(storageFD, &record.windY, sizeof(record.windY)); write(storageFD, &record.timestamp, sizeof(record.timestamp)); assert(errno==0); auto currPos = lseek(storageFD,0,SEEK_CUR); assert(currPos-writePos == RECORD_SIZE); /* * Actualizamos la cabezera del archivo. Esto forma una sección critica */ lock(); setCount(count); setLastIndex(last % (1<<(8*sizeof(Index)))); fsync(storageFD); unlock(); /* Fin de sección crítica */ if(count==0) std::cerr << "Overflow en campo de cantidad de registros!"; }else{ std::cerr << "<2>Se está tratando de insertar en modo de sólo lectura!" << std::endl; } } Record Log::getLast() { return get(getLastIndex()); } int Log::lock() { if(!readOnlyMode) { chdir(LOG_PATH); lockFD = open(LOCK_FILENAME, O_CREAT | O_RDWR); if(lockFD == -1) { std::cerr << "<1>No se pudo poner lock. Saliendo..." << std::endl; perror("<1>"); return -1; } if(flock(lockFD,LOCK_EX) == -1) { perror("<1>No se pudo flockear el lock. Razón"); return -1; } return 0; }else{ std::cerr << "No se puede poner lock. Estamos en modo sólo lectura." << std::endl; return -1; } } int Log::unlock() { if(!readOnlyMode) { flock(lockFD,LOCK_UN); close(lockFD); if(unlink(LOCK_FILENAME) == -1) { perror("<1> No se pudo sacar lock. Razón"); return -1; }else return 0; }else{ std::cerr << "No se puede sacar lock. Estamos en modo sólo lectura." << std::endl; return -1; } } int Log::waitForLock() { int count = 0; const int MAX_COUNT = 5; while(access(LOCK_FILENAME, F_OK) == 0 && count < MAX_COUNT) { perror(""); sleep(1); count++; } if (count == 5) { std::cerr << "No se pudo acceder al archivo." << std::endl; std::cerr << "Se intentaron " << count << " veces." << std::endl; return -1; }else return 0; } Record Log::get(const Index index) { if(waitForLock() == -1) exit(-1); Temperature temp; Humidity hum; Pressure pres; Velocity windX; Velocity windY; time_t timestamp; if(index < getCount()) { const size_t readPos = HEADER_SIZE + index*RECORD_SIZE; errno=0; lseek(storageFD,readPos,SEEK_SET); read(storageFD, &temp ,sizeof(temp)); read(storageFD, &hum, sizeof(hum)); read(storageFD, &pres, sizeof(pres)); read(storageFD, &windX, sizeof(windX)); read(storageFD, &windY, sizeof(windY)); read(storageFD, &timestamp,sizeof(timestamp)); assert(errno==0); }else{ std::cerr << "<1>Se está tratando de leer un registro no existente!" << std::endl; exit(-1); } return Record(temp,hum,pres,windX,windY,timestamp); } Log::~Log() { close(storageFD); if(!readOnlyMode) unlock(); std::cerr << "Log cerrado!" << std::endl; }
true
f836f46c8f2e2d953d8904135af6483c1b4a0c17
C++
L33TT12/gra
/Mapa.h
UTF-8
844
2.578125
3
[]
no_license
#ifndef MAPA_H_INCLUDED #define MAPA_H_INCLUDED #include <iostream> using std::cout; using std::endl; using std::cin; using std::ostream; class Mapa { private: int CurrentPlace; char** Map; bool** IsEmpty; bool WIN; bool* XX; bool* OO; int NextPrzedzial(int,int); int Przedzial(int,int); int Wprowadz(); bool CheckSmallWin(const char); bool EmptyPrzedzial(int,int); bool CheckWin(); void MoveCurrent(int&,int&,int,const char); void UpdateMap(const char); void ChangePlace(int,int); void Ruch(const char); void Zamien(); void Bot(); void RuchBot(const char); void Reset(); bool Remis(); friend ostream& operator<<(ostream&,Mapa&); public: Mapa(); ~Mapa(); void Start(); }; #endif // MAPA_H_INCLUDED
true
d1994138c38432311fde9e41cb27b0774f1e5148
C++
shadowplay7/KalkulatorQt
/KalkulatorQt/KalkulatorQt/Kalkulator.cpp
UTF-8
584
3.140625
3
[]
no_license
#include "Kalkulator.h" double Kalkulator::getA() { return a; } double Kalkulator::getB() { return b; } void Kalkulator::setA(double &x) { a = x; } void Kalkulator::setB(double &y) { b = y; } double Kalkulator::sumElements() { return getA() + getB(); } double Kalkulator::subElements() { return getA() - getB(); } double Kalkulator::multiElements() { return getA() * getB();; } double Kalkulator::doCalc(char &c) { switch (c) { case '+': return sumElements(); break; case '-': return subElements(); break; case '*': return multiElements(); break; } }
true
4b8c81383297506597871152b97962a6b738c579
C++
sumimim33/URIOJ
/1022 TDA Rational/main.cpp
UTF-8
1,190
2.890625
3
[]
no_license
#include <bits/stdc++.h> typedef long long int ll; using namespace std; void make_small(ll a, ll b) { ll s, t; bool flag = false; ll c; ll mini = abs(min(a,b)); for(ll i=mini; i>=2; i--) { if(a%i==0&&b%i==0) { c = i; flag = true; break; } } if(flag) { s = a/c; t = b/c; cout<<a<<"/"<<b<<" = "<<s<<"/"<<t<<endl; } else cout<<a<<"/"<<b<<" = "<<a<<"/"<<b<<endl; } int main() { int t; char c1,c2,o; ll n1,d1,n2,d2; cin>>t; while(t--) { ll a,b; cin>>n1>>c1>>d1>>o>>n2>>c1>>d2; switch(o) { case '+': a = n1*d2+n2*d1; b = d1*d2; make_small(a,b); break; case '-': a = n1*d2-n2*d1; b = d1*d2; make_small(a,b); break; case '/': a = n1*d2; b = n2*d1; make_small(a,b); break; case '*': a = n1*n2; b = d2*d1; make_small(a,b); break; } } return 0; }
true
917204f658cfbf0bc512c81ded4ce0884c1c05d2
C++
danielwboyce/cpp-learning
/08 -- Real Estate/Property.h
UTF-8
826
3.0625
3
[]
no_license
#pragma once #include <iostream> #include <string> #include <sstream> using namespace std; class Property { protected: string address; bool is_rental; double value; static int property_id; int id; public: //Constructor and destructor Property(string address_in, bool is_rental_in, double value_in); virtual ~Property(); //These will return the address, is_rental, value, and id. string getAddress(); bool getIsRental(); double getValue(); int getID(); //This will return a single string with useful information about the property virtual string toString() = 0; //This will set up the id number data member static int id_counter; static void resetID(); static void addOneID(); //This will return this property's tax rate virtual double getTaxes() = 0; };
true
0b6a599d2e610a79ff8f40fdd737fd1e96c87f1d
C++
ComanValentin/OOP-Laboratory-Projects
/Delivery_Project_2/Delivery_Project_2/CEO.h
UTF-8
796
2.96875
3
[]
no_license
#ifndef MANAGER_H_ #define MANAGER_H_ #include "DeliveryCompany.h" class CEO { public: CEO(){ } CEO(string name, DeliveryCompany deliveryCompany) :name(name), deliveryCompany(deliveryCompany) { } CEO(const CEO& val) :name(val.name), deliveryCompany(val.deliveryCompany) { } ~CEO() { } CEO& operator=(const CEO& val); friend ostream& operator<<(std::ostream& out, const CEO& val); friend istream& operator>>(std::istream& in, CEO& val); void startDay(); void updateCurrentTime(); private: DeliveryCompany deliveryCompany; vector<float> currentTimers; //each driver will have their own timer since the program isnt parallelized float currentTime=0.0f; //will be updated with the current highest timer of a driver string name; }; #endif
true
d1fd04419a301f7c9ce0d30bafc609385794906e
C++
Tim-Paik/cpp
/oj/1.4/15.cpp
UTF-8
158
2.921875
3
[]
no_license
//15:最大数输出 #include <iostream> using namespace std; int main() { int a, b, c; cin >> a >> b >> c; cout << (a>b?(a>c?a:c):(b>c?b:c)); return 0; }
true
eb5dca46060dad0ba6be87dd05abd6c698361c99
C++
hans2004516/taiko
/taiko/note.h
UTF-8
837
3.015625
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include <iostream> #include "texture_manager.h" enum class Note_Type { INNER, OUTER }; /* * Note class used by note_generator.cpp * Creates a CircleShape and associated Note_Type, velocity, and texture * and provides draw and move functions */ struct Note : public sf::Drawable { Note_Type type; Note(float velocity, unsigned int radius, sf::Vector2f& pos, Note_Type type, Texture_Manager& tex_mgr); virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; sf::CircleShape model; // the speed at which the notes move float velocity; // moves the note across the screen void move(sf::Time t); //tex_mgr stores all possible textures; tex is needed to store the right texture for the entire life of the note Texture_Manager tex_mgr; sf::Texture tex; };
true
ce18722a2c9e2197f1cd49a3cb9cbe6acf9e6ab2
C++
atul337/Line_Following
/fine_rotation/LSA_fine_rotation.ino
UTF-8
2,684
2.8125
3
[]
no_license
const byte analogPinF = 1; // Connect AN output of LSA1 to analog pin 0 const byte junctionPulseF = 28; // Connect JPULSE of LSA1 to pin 28 const byte analogPinR = 2; // Connect AN output of LSA2 to analog pin 1 const byte junctionPulseR = 29; // Connect JPULSE of LSA2 to pin 29 const byte analogPinL = 0; // Connect AN output of LSA3 to analog pin 2 const byte junctionPulseL = 30; // Connect JPULSE of LSA3 to pin 30 int dirF = 12; //Forward int dirB = 4; int pwmF = 13; int pwmB = 5; int dirR = 10; //RIGHT int dirL = 6; int pwmR = 11; int pwmL = 3; int readValueF, readValueR, readValueL, lsa_F, lsa_R, lsa_L; // Variables to store analog and line position value unsigned int junctionCount = 0; // Variable to store junction count value void setup() { pinMode(junctionPulseF, INPUT); pinMode(junctionPulseR, INPUT); pinMode(junctionPulseL, INPUT); pinMode(dirR , OUTPUT); pinMode(pwmR , OUTPUT); pinMode(dirL , OUTPUT); pinMode(pwmL , OUTPUT); pinMode(dirF , OUTPUT); pinMode(pwmF , OUTPUT); pinMode(dirB , OUTPUT); pinMode(pwmB , OUTPUT); Serial.begin(9600); digitalWrite(dirF , LOW); digitalWrite(dirR , HIGH); digitalWrite(dirB , LOW); digitalWrite(dirL , HIGH); analogWrite(pwmF , 0); analogWrite(pwmR , 0); analogWrite(pwmB , 0); analogWrite(pwmL , 0); Serial.begin(9600); Serial.println("\nReading LSA values\n"); Serial.println("LSA_F\tLSA_R\tLSA_L\tDirection"); } void loop() { readValueF = analogRead(analogPinF); // Read value from analog pin A0 (of LSA1) readValueR = analogRead(analogPinR); // Read value from analog pin A1 (of LSA1) readValueL = analogRead(analogPinL); // Read value from analog pin A2 (of LSA1) lsa_F = ((float)readValueF / 921) * 70; //forward lsa_R = ((float)readValueR / 921) * 70; //right lsa_L = ((float)readValueL / 921) * 70; //left Serial.print(lsa_F + String("\t") + lsa_R + String("\t") + lsa_L + String("\t")); balanceLR(); } void balanceLR() { if (hasLine(lsa_R) && lsa_R <= 28) { // nudge forward digitalWrite(dirF , LOW); analogWrite(pwmF , 60); } else if (hasLine(lsa_R) && lsa_R >= 42) { // nudge backward digitalWrite(dirF , HIGH); analogWrite(pwmF , 60); } else { analogWrite(pwmF, 0); } if (hasLine(lsa_L) && lsa_L <= 28) { digitalWrite(dirB, HIGH); analogWrite(pwmB, 60); } else if (hasLine(lsa_L) && lsa_L >= 42) { digitalWrite(dirB, LOW); analogWrite(pwmB, 60); } else { analogWrite(pwmB,0); } } inline boolean hasLine(int val) { return (val >= 0) && (val <= 70); }
true
1745aafddf3a1ba0afecc001fb334373a7c915a7
C++
bfogerty/RayTracer
/src/time/StopWatch.h
UTF-8
642
2.78125
3
[]
no_license
#include <windows.h> class StopWatch { public: StopWatch() { QueryPerformanceFrequency(&countsPerSecond); invCountsPerSecond = 1.0f / countsPerSecond.QuadPart; } inline void Start() { QueryPerformanceCounter(&beginCounts); } inline float Stop() { QueryPerformanceCounter(&endCounts); float delta = float(endCounts.QuadPart - beginCounts.QuadPart); float elapsedTimeInSeconds = delta * invCountsPerSecond; float elapsedTimeInMS = elapsedTimeInSeconds * 1000.0f; return elapsedTimeInMS; } private: LARGE_INTEGER countsPerSecond; float invCountsPerSecond; LARGE_INTEGER beginCounts; LARGE_INTEGER endCounts; };
true
a4bd93ed032371abcc1c038850d7584f4dfb753e
C++
akincam/Object-Oriented-Programming--Cpp
/HW5/151044007/cell.cpp
UTF-8
345
2.671875
3
[]
no_license
#include <iostream> #include <string> #include "cell.h" using namespace std; namespace ConnectFour { Cell::Cell() : return_row(0), return_column(0), cell(0) { /*Body intentionally empty*/ } Cell::Cell(char cell) { setCell(cell); } Cell::Cell(int cell_row ,int cell_column) { setRow(cell_row); setColumn(cell_column); } }
true
53b3a2f68d873a0220f992f2b6d4941b37686b33
C++
AsderYork/ShortGame1
/GameSimulation/GameSimulation.h
UTF-8
2,878
2.65625
3
[]
no_license
#pragma once #include "EntitiesBase.h" #include "GS_PlayerController.h" #include "GS_EntityController.h" #include "Mixin_Controller.h" #include "EntityGenerator.h" #include "GameTime.h" #include "GamePhysics.h" #include "GameObject.h" //Mixins #include "Mixin_Movable.h" #include "Mixin_Health.h" #include "Mixin_Objecttype.h" #include <queue> namespace GEM::GameSim { class GameSimulation { private: std::queue<std::pair<MixinCommandRetranslator, ENTITY_ID_TYPE>> m_commandBuffer; /**! Used to generate entity ID when needed. */ ENTITY_ID_TYPE m_lastAddedEntity = 0; protected: GameTime m_simulationTime = 0; float m_simulationTimeScle = 1.0f; public: EntityController m_entities; EntityGenerator<Mixin_Health, Mixin_Movable, Mixin_Objecttype> m_generator; PlayerController m_players; GamePhysics m_physics; inline const GameTime& getGameTime() { return m_simulationTime; } inline float getGameTimeScale() { return m_simulationTimeScle; } inline void setGameTime(GameTime NewTime) { m_simulationTime = NewTime; } inline void setGameTimeScale(float NewTimeScle) { m_simulationTimeScle = NewTimeScle; } inline GameSimulation() { m_physics.Initialize(); } /**! Insert a command in a simulation, to be applied on the upcoming tick; \param[in] Entity ID of entity that should recive a command \param[in] Command A command, that should be applied to an entity \note At the moment of writing, behaviour is undefined, if ID command and id is ill-formed */ void InsertCommand(ENTITY_ID_TYPE Entity, MixinCommandRetranslator&& Command); /**! Performs one tick of a simulation \returns true if everything is ok. If false is returned, simulation is broken and should be terminated */ bool Tick(float delta); /**! Adds entity with some valid id. \returns a pair with first value - pointer to newly created entity and second - ID of that entity */ std::pair<std::weak_ptr<EntityBase>, ENTITY_ID_TYPE> AddEntity(std::vector<MIXIN_ID_TYPE> mixins); /**! Adds entity with a given ID. Returns a pointer to the entity, if it was created or nullptr, if entity wasn't created */ std::weak_ptr<EntityBase> AddEntity(ENTITY_ID_TYPE ID, std::vector<MIXIN_ID_TYPE> mixins); /**! Adds entity with a given ID. Returns a pointer to the entity, if it was created or nullptr, if entity wasn't created */ std::weak_ptr<EntityBase> AddEntity(ENTITY_ID_TYPE ID, std::unique_ptr<EntityBase> ent); /**! Adds entity with some valid id. \returns a pair with first value - pointer to newly created entity and second - ID of that entity */ std::pair<std::weak_ptr<EntityBase>, ENTITY_ID_TYPE> AddEntity(std::unique_ptr<EntityBase> ent); /**! Adds new object with given type */ std::pair<std::weak_ptr<EntityBase>, ENTITY_ID_TYPE> AddObject(GAMEOBJECT_TYPE_ID TypeID); }; }
true
f1b32f3f9d71c00ff50870e9a79e72dd218f499c
C++
orbenda1905/SmartCompany
/Project.h
UTF-8
2,483
2.53125
3
[]
no_license
/* * Project.h * * Created on: May 23, 2015 * Author: Benda */ #ifndef PROJECT_H_ #define PROJECT_H_ #include "Headers.h" #include "Manager.h" #include "Employee.h" #include "Client.h" #include "SmartPtr.h" #include "WriteToFile.h" class Project : public WriteToFile { private: string projId; int totalHours; int hoursLeft; string projectName; int programmersNumber; int artistsNumber; string managerId = ""; bool fullyRecruit = false; bool needToRemove = false; bool managerOccupied = false; vector<string> progWorkField; vector<string> progLangs; vector<string> artWorkField; SmartPtr<Employee> manager; map<string, SmartPtr<Employee>> artists; map<string, SmartPtr<Employee>> programmers; map<string, SmartPtr<Employee>> finishedWorkers; SmartPtr<Client> client; public: Project(string name, string prId, int ttlHrs, int hrsLft, string mangr, int progCnt, int artCnt, vector<string> pFld,vector<string> aFld); ~Project(); int getArtistsNumber() const; void setArtistsNumber(int artistsNumber); const vector<string>& getArtWorkField() const; void setArtWorkField(vector<string> artWorkField); const SmartPtr<Client>& getClient() const; void setClient(const SmartPtr<Client> client); int getHoursLeft() const; void setHoursLeft(int hoursLeft); SmartPtr<Employee>& getManager(); void setManager(SmartPtr<Employee> manager); int getProgrammersNumber() const; void setProgrammersNumber(int programmersNumber); const vector<string>& getProgWorkField() const; void setProgWorkField(vector<string> progWorkField); const string& getProjectName() const; void setProjectName(const string projectName); string& getProjId(); int getTotalHours() const; void setTotalHours(int totalHours); void speedUp(); void checkFinish(); bool checkExistProg(SmartPtr<Employee>& emp); bool checkExistArtist(SmartPtr<Employee>& emp); bool checkIfNeedingProg(SmartPtr<Employee>& emp); bool checkIfNeedingArt(SmartPtr<Employee>& emp); bool addProgrammer(SmartPtr<Employee>& emp); bool addArtist(SmartPtr<Employee>& emp); void beginTheProject(); void finishProject(); void dismissEmployee(SmartPtr<Employee>& emp); bool getNeedToRemove(); bool getManagerOccupied(); string getManagerId(); void setManagerOccupied(bool status); void boost10Days(SmartPtr<Employee>& emp); void print(); bool removeEmployee(string empId); }; #endif /* PROJECT_H_ */
true
4824f96397fd2ed07457059ee094e58f454bf644
C++
bobodaye/myWorkSpace
/Algorithm/剑指offer/面试题7:用两个队列实现栈(拓展)/面试题7:用两个队列实现栈(拓展)/TestStack.cpp
UTF-8
253
2.640625
3
[]
no_license
#include <iostream> #include "QueueImpStack.h" int main() { CStack<int> s; s.push(1); s.push(2); std::cout << s.pop() << std::endl; s.push(3); std::cout << s.pop() << std::endl; std::cout << s.pop() << std::endl; return 0; }
true
cc00d02973d8f55e57d57053a7a9103187667cd3
C++
dangerrangerous/2-3-4-Tree
/2-3-4_B_Tree.h
UTF-8
2,040
3.25
3
[]
no_license
// 2-3-4_B_Tree.h // Brian Keppinger #pragma once class DataItem { public: // should the data be private? long data; // Default constructor DataItem(void); // Default destructor ~DataItem(void); void DisplayItem(); // void DestroyDI(); private: // void DestroyDataItem(DataItem* &dataItemPointer); }; class TwoThreeFourNode { public: // Default constructor TwoThreeFourNode(void); // Default destructor ~TwoThreeFourNode(void); void ConnectChild(int childNum, TwoThreeFourNode* child); TwoThreeFourNode* DisconnectChild(int childNum); TwoThreeFourNode* GetChild(int childNum); TwoThreeFourNode* GetParent(); int InsertItem(DataItem* newItem); DataItem* RemoveItem(); int GetNumItems(); int FindItem(long key); int FindIndex(long key); void DisplayNode(); bool b_IsLeaf(); bool b_IsFull(); void Remove(long key); void RemoveFromLeaf(int index); void RemoveFromNonLeaf(int index); void BorrowFromPrevious(int index); void BorrowFromNext(int index); void Merge(int index); void Fill(int index); int GetPredecessor(int index); int GetSuccessor(int index); int FindKey(int key); DataItem* GetItem(int index); private: static const int ORDER = 4; int numItems; TwoThreeFourNode* parent; DataItem* dataItemArray[ORDER - 1]; TwoThreeFourNode* childArray[ORDER]; }; class Tree234 { public: // Default constructor Tree234(void); // Default destructor ~Tree234(void); int Find(long key); void Insert(long dataValue); void Split(TwoThreeFourNode* inNode); TwoThreeFourNode* GetNextChild(TwoThreeFourNode* inNode, long inValue); bool IsEmpty(); void DisplayPreOrder(); void DisplayInOrder(); void DisplayPostOrder(); void RemoveFromTree(long key); private: // Recursive PreOrder Traversal void RecursivePreOrderTraversal(TwoThreeFourNode* inNode, int level, int childNumber); void RecursiveInOrderTraversal(TwoThreeFourNode* inNode, int level, int childNumber); void RecursivePostOrderTraversal(TwoThreeFourNode* inNode, int level, int childNumber); TwoThreeFourNode* root; };
true
f8eed153fe57c8eba148f61f5cc427343d5c17ac
C++
i05nagai/programming_contest_challenge_book
/src/algorithm/dynamic_programming/traveling_by_stagecoach_test.cc
UTF-8
1,012
3.21875
3
[]
no_license
#include <gtest/gtest.h> #include "algorithm/dynamic_programming/traveling_by_stagecoach.h" namespace algorithm { namespace dynamic_programming { TEST(traveling_by_stagecoach, simple1) { const int num_ticket = 2; const int num_city = 4; const int start_v = 2; const int end_v = 1; int tickets[] = { 3, 1, }; std::vector<int> d[num_city]; for (int i = 0; i < num_city; ++i) { d[i].resize(num_city); for (int j = 0; j < num_city; ++j) { d[i][j] = 0; } } // fill upper right triangular matrix d[0][1] = -1; d[0][2] = 3; d[0][3] = 2; d[1][2] = 3; d[1][3] = 5; d[2][3] = -1; // copy to left-lower triangular for (int i = 1; i < num_city; ++i) { for (int j = 0; j < i; ++j) { d[i][j] = d[j][i]; } } const double actual = solve_traveling_by_stagecoach( d, num_ticket, num_city, start_v, end_v, tickets); EXPECT_NEAR(3.667, actual, 1e-3); } } // namespace dynamic_programming } // namespace algorithm
true
be53cbd72a54dbcc703e200c4c8c0390a4df9654
C++
rouman321/code-practice
/0938-rangeSumofBST.cpp
UTF-8
1,580
3.453125
3
[]
no_license
/* Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values. */ #include <iostream> #include "../LCInput/treeVector.h" class Solution { public: int rangeSumBST(Node* root, int L, int R) { int ret = 0; if(root == 0) { return ret; } if(root->val <= R&&root->val >= L) { ret += root->val; } ret += rangeSumBST(root->right,L,R)+rangeSumBST(root->left,L,R); return ret; } }; int main() { ifstream in; in.open("in.txt"); vector<int> nums; vector<int> nullIndex; string str; getline(in,str); int i; for(i = 0;i < str.size();i++) { if(isNum(str[i])) { int tmp = 0; while(isNum(str[i])) { tmp *= 10; tmp += str[i]-'0'; i++; } nums.push_back(tmp); } else if(str[i] == 'n') { nullIndex.push_back(nums.size()); nums.push_back(0); } } Node* head = NULL; head = constructTree(nums,nullIndex,0); nums.clear(); int L = 0; getline(in,str); for(i = 0;i < str.size();i++) { L *= 10; L += str[i]-'0'; } int R = 0; getline(in,str); for(i = 0;i < str.size();i++) { R *= 10; R += str[i]-'0'; } Solution s; cout<<s.rangeSumBST(head,L,R)<<endl; return 0; }
true
1b33c50cf67e4293e0f3d5f8b77f0f09efffdb01
C++
hoangsadn/castlevania
/CaslteVania/CaslteVania/Animations.cpp
UTF-8
1,701
3.015625
3
[]
no_license
#include "Animations.h" #include <cmath> void CAnimation::Add(int spriteId, DWORD time) { int t = time; if (time == 0) t = this->defaultTime; LPSPRITE sprite = CSprites::GetInstance()->Get(spriteId); LPANIMATION_FRAME frame = new CAnimationFrame(sprite, t); frames.push_back(frame); } void CAnimation::Render(float x, float y, int alpha) { DWORD now = GetTickCount(); if (currentFrame <= -1) { currentFrame = 0; lastFrameTime = now; } else { DWORD t = frames[currentFrame]->GetTime(); if (now - lastFrameTime > t) { currentFrame++; lastFrameTime = now; if (currentFrame == frames.size()) { currentFrame = 0; isLastFrame = true; } } else { isLastFrame = false; t += now - lastFrameTime; } } frames[currentFrame]->GetSprite()->Draw(x, y, alpha); } CAnimations * CAnimations::__instance = NULL; CAnimations * CAnimations::GetInstance() { if (__instance == NULL) __instance = new CAnimations(); return __instance; } void CAnimations::LoadResources() { ifstream File; File.open(L"text\\animations.txt"); vector<int> ParaAni; ParaAni.clear(); vector<int>::iterator it; int reader; int time; while (!File.eof()) { File >> reader; if (reader > -1) { ParaAni.push_back(reader); } else { LPANIMATION ani; if (reader < -1) ani = new CAnimation(abs(reader)); else ani = new CAnimation(100); for (auto it = ParaAni.begin(); it != ParaAni.end()-1; ++it) ani->Add(*it); it = ParaAni.end() - 1; Add(*it, ani); ParaAni.clear(); } } File.close(); } void CAnimations::Add(int id, LPANIMATION ani) { animations[id] = ani; } LPANIMATION CAnimations::Get(int id) { return animations[id]; }
true
f479a51dc15c0b600c584fd483de8a233a3e08d6
C++
cyyself/OILife
/ECNU/3269 - 爱吃糖果的 Pokémon.cpp
UTF-8
990
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; const int inf = 0x0fffffff; struct candy{ int type; int time; friend bool operator < (const candy &a,const candy &b) { if (a.time > b.time) return true; if (a.time == b.time && a.type > b.type) return true; return false; } candy(int _type,int _time) { type = _type; time = _time; } }; priority_queue <candy> q; queue <int> ans_type; int main() { int n,r,m; scanf("%d%d%d",&n,&r,&m); for (int i=1;i<=n;i++) q.push(candy(i,-inf)); int lastcandy_type = -1; int ans = 0; for (int t=0;t<m;t++) { if (!q.empty()) { candy cur = q.top(); if (t - cur.time > r || lastcandy_type == -1) { if (!q.empty() && t - cur.time > r) ans ++; if (!q.empty()) q.pop(); if (lastcandy_type != -1) q.push(candy(lastcandy_type,t-1)); lastcandy_type = cur.type; } } ans_type.push(lastcandy_type); } printf("%d\n",ans); while (!ans_type.empty()) { printf("%d ",ans_type.front()); ans_type.pop(); } return 0; }
true
2fcf67f1083798c0d314f650078f618b986b99ba
C++
jasonblog/note
/ds_algo/src/leetcode_v2/algorithms/MinimumPathSum/solve.cpp
UTF-8
1,795
3.140625
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <vector> #include <algorithm> #include <iostream> using namespace std; class Solution { public: int minPathSum(vector<vector<int>>& grid) { return minPathSum1(grid); } private: int minPathSum1(vector<vector<int>>& grid) { if (grid.size() < 1) { return 0; } int n = grid.size(); int m = grid[0].size(); vector<vector<int>> dp(n, vector<int>(m, 0)); dp[0][0] = grid[0][0]; for (int i = 1; i < n; ++i) { dp[i][0] = dp[i - 1][0] + grid[i][0]; } for (int j = 1; j < m; ++j) { dp[0][j] = dp[0][j - 1] + grid[0][j]; } for (int i = 1; i < n; ++i) for (int j = 1; j < m; ++j) { dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; } return dp[n - 1][m - 1]; } int minPathSum2(vector<vector<int>>& grid) { if (grid.size() < 1) { return 0; } int n = grid.size(); int m = grid[0].size(); vector<int> dp(n, 0); dp[0] = grid[0][0]; for (int i = 1; i < n; ++i) { dp[i] = dp[i - 1] + grid[i][0]; } for (int i = 1; i < n; ++i) for (int j = 1; j < n; ++j) { dp[j] = min(dp[j], dp[j - 1]) + grid[i][j]; } return dp[n - 1]; } }; int main(int argc, char** argv) { Solution solution; int n, m; while (scanf("%d%d", &n, &m) != EOF) { vector<vector<int>> v(n, vector<int>(m, 0)); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { cin >> v[i][j]; } cout << solution.minPathSum(v) << endl; } return 0; }
true
e367a6caa14e5613f3d7b709066d183fbe2c708d
C++
matt-han/ba_gui1
/IniFileHandler.h
UTF-8
2,804
2.5625
3
[]
no_license
/* * Opens, reads and closes cfg/ini files for automated testing */ #ifndef _INIFILEHANDLER_H #define _INIFILEHANDLER_H #include "Constants.h" #include "Tools.h" #include <string> #include <vector> #include <Windows.h> #include <stdlib.h> #include <fstream> using namespace std; class IniFileHandler { public: IniFileHandler(void); ~IniFileHandler(void); //------------------------------------------------------------------------------ //Methods //write methods void writeINIfile(string sMasterPort, string sSlavePort, int iBaud, int iBaudMax, int iTestMode, int iParity, int iProtocol, int iStopbits, int iDatabits, int iTransfer, int iTextMode, string sTextToTransfer, string sRepeater, bool bLogger, bool bStopOnError, string sPath); int readINIFile(string sFilePath, string sPort); vector<TestStruct> getTestStructure(); private: //------------------------------------------------------------------------------ //Variables int _iError; DWORD _dwExists; TestStruct comPortStruct; Tools tools; int index; char szValue[MAX_PATH]; string sFilePath; string substr; vector<TestStruct> vComPorts; //------------------------------------------------------------------------------ //Methods //write void writeINItransferSettings(string sMasterPort, string sSlavePort, int iTransfer, string sPath); void writeTextTransferSettings(string sMasterPort, int iTextMode, string sTextToTransfer, string sPath); //read int readPortConfig(string sPort, string sFilePath, int index); int readTransferMode(string sPort, string sFilePath, int index); int readSlave(string sPort, string sFilePath, int index); int readSettings(string sPort, string sFilePath, int index); int readParity(string sPort, string sFilePath, int index); int readProtocol(string sPort, string sFilePath, int index); int readStopbits(string sPort, string sFilePath, int index); int readDatabits(string sPort, string sFilePath, int index); int readBaudRate(string sPort, string sFilePath, int index); int readTextToTransfer(string sPort, string sFilePath, int index); int readLogger(string sPort, string sFilePath); int readStopOnError(string sPort, string sFilePath); int readRepeater(string sPort, string sFilePath); //Parse from GUI to INI file string parseParityToIni(int iParity); string parseProtocolToIni(int iProtocol); string parseStopbitsToIni(int iStopbits); string parseDatabitsToIni(int iDatabits); //Parse from INI file to GUI int parseBaud(string, int); int parseTestMode(string); int parseParity(string, int); int parseProtocol(string); int parseStopbits(string); int parseDatabits(string); int parseTransfer(string); string parsePort(string); int parseTextToTransfer(string, string, string, int); }; #endif
true
395e42300e8fa2b41d3de56dfb7f3b8ffcc4ecc8
C++
polygontwist/ESP8266_WebServer_i2c
/i2c_sht21.cpp
UTF-8
2,085
2.671875
3
[ "MIT" ]
permissive
/* SHT2x - Digitaler Feuchte- & Temperatursensor (RH/T) http://www.sensirion.com/de/produkte/feuchte-und-temperatur/feuchte-temperatursensor-sht2x/ SHT21 - Standard Ausführung, +/-2% RH Genauigkeit Grösse: 3 x 3 x 1.1 mm Schnittstelle: I²C digital, PWM, SDM Betriebsspannung: 2.1 bis 3.6 V Energieverbrauch: 3.2µW (bei 8 bit, 1 Messung / s) Messbereich (RH): 0 - 100% relative Feuchte Messbereich (T): -40 bis +125°C (-40 bis +257°F) Ansprechzeit (RH): 8 Sekunden (tau63%) ~4€ breakout ~13€ http://shop.emsystech.de/themes/kategorie/detail.php?artikelid=9&kategorieid=5&source=1&refertype=9 */ #include "Arduino.h" #include <Wire.h> #include "i2c_sht21.h" i2c_sht21::i2c_sht21() { // /* pin 2 gpio2 SDA (data) pin 0 gpio1 SCL (clock) */ // Wire.begin(_devid); // Wire.pins(0, 2); //0=SDA, 2=SCL } void i2c_sht21::init(int i2c_devid=sht21_DEVID) { _devid=i2c_devid; Softreset(); } //SHT21 void i2c_sht21::Softreset(void) { Wire.beginTransmission(_devid); //begin transmitting Wire.write(0xFE); //Softreset Wire.endTransmission(); delay(100); } int i2c_sht21::readData(int befehl){ Wire.beginTransmission(_devid); //begin transmitting Wire.write(befehl); Wire.endTransmission(); delay(100);//(500) min 20u Wire.requestFrom(_devid, 3); while(Wire.available() < 3) { ; //wait } byte msb,lsb,Checksum;//data(MSB),data(LSB), Checksum //LSB 1&2 bit=Stat msb= Wire.read(); lsb = Wire.read(); //lsb &= ~((1<<0)|(1<<1)));//bit 0 und 1 löschen lsb &= ~(0b00000011);//bit 0 und 1 löschen Checksum= Wire.read(); Wire.endTransmission(); return (msb<<8)+lsb; } float i2c_sht21::readTemp(void) {//-40..+125°C int re=readData(0xF3); //TRIGGER_TEMPERATURE_NO_HOLD temperatur= ( ( (175.72/65536.0) * (float)re) - 46.85 ); return temperatur; } float i2c_sht21::readHumidity(void) {//0..100% Luftfeuchte % int re=readData(0xF5);//TRIGGER_HUMIDITY_NO_HOLD humidity=( ((125.0/65536.0) * (float)re) - 6.0); return humidity; }
true
f58e98ea73d8ee57deeecddfd269fe1627459cfd
C++
NoClay/C-Code
/自定义异常处理.cpp
UTF-8
243
2.75
3
[]
no_license
#include<iostream> using namespace std; void myterm() { cout << "This is my terminater ." << endl; exit(1); } int main(){ try{ set_terminate(myterm); throw "Exception ...";// }catch(int i){ cout << "test" << endl; } return 0; }
true
2e8ae4e66926e0414ae0065bdaa3d4d6857fc225
C++
imkiva/KiVM
/include/sparsepp/spp_smartptr.h
UTF-8
2,131
2.875
3
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
#if !defined(spp_smartptr_h_guard) #define spp_smartptr_h_guard /* ----------------------------------------------------------------------------------------------- * quick version of intrusive_ptr * ----------------------------------------------------------------------------------------------- */ #include <cassert> #include "spp_config.h" // ------------------------------------------------------------------------ class spp_rc { public: spp_rc() : _cnt(0) {} spp_rc(const spp_rc &) : _cnt(0) {} void increment() const { ++_cnt; } void decrement() const { assert(_cnt); if (--_cnt == 0) delete this; } unsigned count() const { return _cnt; } protected: virtual ~spp_rc() {} private: mutable unsigned _cnt; }; // ------------------------------------------------------------------------ template <class T> class spp_sptr { public: spp_sptr() : _p(0) {} spp_sptr(T *p) : _p(p) { if (_p) _p->increment(); } spp_sptr(const spp_sptr &o) : _p(o._p) { if (_p) _p->increment(); } #ifndef SPP_NO_CXX11_RVALUE_REFERENCES spp_sptr(spp_sptr &&o) : _p(o._p) { o._p = (T *)0; } spp_sptr& operator=(spp_sptr &&o) { if (_p) _p->decrement(); _p = o._p; o._p = (T *)0; } #endif ~spp_sptr() { if (_p) _p->decrement(); } spp_sptr& operator=(const spp_sptr &o) { reset(o._p); return *this; } T* get() const { return _p; } void swap(spp_sptr &o) { T *tmp = _p; _p = o._p; o._p = tmp; } void reset(const T *p = 0) { if (p == _p) return; if (_p) _p->decrement(); _p = (T *)p; if (_p) _p->increment(); } T* operator->() const { return const_cast<T *>(_p); } bool operator!() const { return _p == 0; } private: T *_p; }; // ------------------------------------------------------------------------ namespace std { template <class T> inline void swap(spp_sptr<T> &a, spp_sptr<T> &b) { a.swap(b); } } #endif // spp_smartptr_h_guard
true
de5a538865052798d4f382055fc47af752cbf404
C++
lucky-rydar/OpenLL
/OpenLL/main.cpp
UTF-8
404
2.609375
3
[ "MIT" ]
permissive
#include <iostream> #include <string> #include <vector> #include <Windows.h> #include "DLLImport.h" #pragma warning(disable: 4996) using namespace std; DLLImport<int, int, int> sum("dll_learning.dll", "any_name"); //DLLImport<int, int, int> mult("dll_learning.dll", "mult"); int main(int argc, char** argv) { cout << sum(3, 2) << endl; //cout << mult(10, 10) << endl; return 0; }
true
efa643d50f7484deb9edf21cf18ffc66ef2698bc
C++
momons/hateru_cocos2dx
/Classes/Util/Base64Util.h
UTF-8
818
2.71875
3
[]
no_license
// // Base64Util.h // hateru // // Created by HaraKazunari on 2016/08/21. // // #ifndef Base64Util_h #define Base64Util_h #include <string> #include <vector> using namespace std; /// Base64ユーティリティ class Base64Util final { public: /** * 変換 * * @param src 入力バッファ * @param length 入力バッファ長 * * @return 変換後文字列 */ static string encode(const unsigned char* src, const size_t length); /** * 復号 * * @param src src 入力文字列 * @param dst dst 出力バッファ * * @return 変換可否 */ static bool decode(const string &src, vector<unsigned char>& dst); private: /** * コンストラクタ */ Base64Util() {} /** * デストラクタ */ ~Base64Util() {} }; #endif /* Base64Util_h */
true
6f381328da3a08c02358ed7c0ad0da86a36e5749
C++
ishaandhamija/LP-Fasttrack-Summer18
/07-char-arr/use-tool.cc
UTF-8
479
3.0625
3
[]
no_license
// Deepak Aggarwal, Coding Blocks // deepak@codingblocks.com #include <iostream> using namespace std; int cntChar(char arr[]){ int cnt = 0; int cur = 0; while(arr[cur] != '\0'){ switch(arr[cur]){ case ' ': case '\n': case '\t': break; default : cnt++; } ++cur; } return cnt; } int main(){ char arr[1000]; cin.getline(arr, 990, '$'); int ans = cntChar(arr); cout << ans; }
true
98914bf36b6c3995b3afa140e2a8626152dd2c0d
C++
yardstick17/UVA_Solutions
/uva11286.cpp
UTF-8
600
2.578125
3
[]
no_license
#include<iostream> #include<map>4 using namespace std; int main() { int t,count,i,j,k,x; int f1,f2; map<int, map<int,int> >m; while(1) { m.clear(); cin>>t; count=t; if(t==0) break; for(i=0;i<t;i++) { for(j=0;j<5;j++) { cin>>x; m[i][x]++; } //f1=-100000; //f2=0; for(k=0;k<i;k++) { if(m[i]!=m[k]) f1=-1; else {f1=0; break; } } //if(f1<f2) count=count+f1; //else //count= count +f2; } cout<<count<<endl; } return 0; }
true
59250dca2c94c613d6a357df4d8e271204762d2c
C++
ObjectFICT/Christmas-Tree
/ChristmasTree.cpp
UTF-8
2,263
3.265625
3
[]
no_license
#include "christmasTree.h" christmasTree::christmasTree(int heightTree) { this->heightTree = heightTree; this->widthTree = heightTree * 2; } void christmasTree::buildBlockTree(double sizeFactor, int color) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); int left{heightTree}, right{heightTree}; for (size_t i = 0; i < (int)(heightTree / sizeFactor); i++) { for (size_t j = 0; j < widthTree; j++) { if(j < left || j > right) { Tree = Tree + " "; cout << " "; } else { if(i % 2 == 0) { setColor(2, 0); printf("^"); Tree = Tree + '^'; } else { setColor(color, 0); printf("*"); Tree = Tree + '*'; } } } left--; right++; cout << endl; Tree = Tree + "\n"; } } void christmasTree::buildStemTree() { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); setColor(8, 0); for(size_t i = 0; i < heightTree / 2; i++) { for (size_t j = 0; j < widthTree; j++) { if(j > 2*widthTree/3 || j < widthTree/3) { cout << " "; } else { cout << "^"; } } cout << endl; } } void christmasTree::buildTree(int color) { buildBlockTree(2, color); buildBlockTree(1.3,color); buildBlockTree(1, color); buildStemTree(); } void christmasTree::setColor(int text, int background) { HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hStdOut, (WORD)((background << 4) | text)); } void christmasTree::doTree(int NumberOfFlickeringCycles) { while (NumberOfFlickeringCycles > 0) { system("cls"); buildTree(3); Sleep(1000); system("cls"); buildTree(4); Sleep(1000); system("cls"); buildTree(6); Sleep(1000); NumberOfFlickeringCycles--; } }
true
ca1801063151e548d2fff933518ad7edc5ffab97
C++
sanjeet724/CMPT_880
/Term Project/test_cases/working_case_set.cpp
UTF-8
1,566
3.25
3
[]
no_license
#include <iostream> #include <cstdint> #include <set> #include <random> #include <algorithm> using namespace std; std::string random_string() { auto randchar = []() -> char { const char charset[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; const size_t max_index = (sizeof(charset) - 1); return charset[ rand() % max_index ]; }; std::string str(30,0); std::generate_n( str.begin(), 30, randchar ); return str; } string* createRandomString() { string *s = new string(random_string()); return s; } uint64_t* createRandomId() { std::default_random_engine generator; std::uniform_int_distribution<int> distribution(1,6); int dice_roll = distribution(generator); uint64_t* ptr = new uint64_t[10000*dice_roll]; return ptr; } class complexObject { public: string *name; uint64_t id; uint64_t someArray[1000]; public: complexObject(int j){ name = createRandomString(); id = j; for (int i = 0; i < 1000000; i++){ someArray[i] = i; } } }; set<complexObject*> ptrSet; int main(int argc, char* argv[]) { for (int i = 0; i < 100; i++) { complexObject *c = new complexObject(i); ptrSet.insert(c); } for(auto B = ptrSet.begin(), E = ptrSet.end(); B != E; B++) { cout << *((*B)->name) << ": " ; cout << (*B)->id << "\n"; } ptrSet.clear(); return 0; } // issue seen when there are 100 objects in the map - in mac
true
ba19b1a6bb412b4178f6d9ac079412291438c021
C++
cgrimes91/CS2-Assembler
/assembler/test_push_pop.cpp
UTF-8
3,839
3.671875
4
[]
no_license
// Chris Grimes // cs23001 // test.cpp push() pop() for stack #include"stack.hpp" int main(){ { //Setup stack<int> test; //Test test.push(8); test.push(6); test.push(7); test.push(5); test.push(3); test.push(0); test.push(9); //Verify std::cout<<test.top()<<"==9"<<std::endl; assert(test.pop()==9); std::cout<<test.top()<<"==0"<<std::endl; assert(test.pop()==0); std::cout<<test.top()<<"==3"<<std::endl; assert(test.pop()==3); std::cout<<test.top()<<"==5"<<std::endl; assert(test.pop()==5); std::cout<<test.top()<<"==7"<<std::endl; assert(test.pop()==7); std::cout<<test.top()<<"==6"<<std::endl; assert(test.pop()==6); std::cout<<test.top()<<"==8"<<std::endl; assert(test.pop()==8); std::cout<<test.empty()<<"== True"<<std::endl; assert(!(test.empty()==0)); } { //Setup stack<char> test; //Test test.push('a'); test.push('b'); test.push('c'); test.push('d'); test.push('e'); test.push('f'); test.push('g'); //Verify std::cout<<test.top()<<"==g"<<std::endl; assert(test.pop()=='g'); std::cout<<test.top()<<"==f"<<std::endl; assert(test.pop()=='f'); std::cout<<test.top()<<"==e"<<std::endl; assert(test.pop()=='e'); std::cout<<test.top()<<"==d"<<std::endl; assert(test.pop()=='d'); std::cout<<test.top()<<"==c"<<std::endl; assert(test.pop()=='c'); std::cout<<test.top()<<"==b"<<std::endl; assert(test.pop()=='b'); std::cout<<test.top()<<"==a"<<std::endl; assert(test.pop()=='a'); std::cout<<test.empty()<<"== True"<<std::endl; assert(!(test.empty()==0)); } { //Setup stack<double> test; //Test test.push(8.5); test.push(6.5); test.push(7.5); test.push(5.5); test.push(3.5); test.push(0.5); test.push(9.5); //Verify std::cout<<test.top()<<"==9.5"<<std::endl; assert(test.pop()==9.5); std::cout<<test.top()<<"==0.5"<<std::endl; assert(test.pop()==0.5); std::cout<<test.top()<<"==3.5"<<std::endl; assert(test.pop()==3.5); std::cout<<test.top()<<"==5.5"<<std::endl; assert(test.pop()==5.5); std::cout<<test.top()<<"==7.5"<<std::endl; assert(test.pop()==7.5); std::cout<<test.top()<<"==6.5"<<std::endl; assert(test.pop()==6.5); std::cout<<test.top()<<"==8.5"<<std::endl; assert(test.pop()==8.5); std::cout<<test.empty()<<"== True"<<std::endl; assert(!(test.empty()==0)); } { //Setup stack<int> test; //Test for(int i=0; i<100; ++i) test.push(i); //Verify for(int j=99; j>=0; --j){ std::cout<<test.top()<<"=="<<j<<std::endl; assert(test.pop()==j); } std::cout<<test.empty()<<"== True"<<std::endl; assert(!(test.empty()==0)); } { //Setup stack<String> test; String a; //Test a="help"; test.push(a); //Verify std::cout<<test.top()<<"=="<<a<<std::endl; assert(test.pop()==a); std::cout<<test.empty()<<"== True"<<std::endl; assert(!(test.empty()==0)); } { //Setup stack<String> test; String a; String b; String c; String d; //Test a="help"; b="another girl"; c="she loves you"; d="don't let me down"; test.push(a); test.push(b); test.push(c); test.push(d); //Verify std::cout<<test.top()<<"=="<<d<<std::endl; assert(test.pop()==d); std::cout<<test.top()<<"=="<<c<<std::endl; assert(test.pop()==c); std::cout<<test.top()<<"=="<<b<<std::endl; assert(test.pop()==b); std::cout<<test.top()<<"=="<<a<<std::endl; assert(test.pop()==a); std::cout<<test.empty()<<"== True"<<std::endl; assert(!(test.empty()==0)); } std::cout<<" passed push() and pop() methods, success"<<std::endl; }
true
329ff4fb36d741f1877ae1f7e355c8a25e19df08
C++
yinzm/LeetCodeSolution
/Array/easy/840_Magic Squares In Grid.cpp
UTF-8
1,406
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class Solution { public: bool check(vector<vector<int>>& grid, int x, int y) { int row = grid.size(), col = grid[0].size(); if (x+2 >= row || y+2 >= col) return false; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (grid[x+i][y+j] > 9 || grid[x+i][y+j] < 1) return false; } } int ans = 0; for (int i = 0; i < 3; ++i) { int sum = 0; for (int j = 0; j < 3; ++j) { sum += grid[x+i][y+j]; } if (i == 0) { ans = sum; } else { if (sum != ans) return false; } sum = 0; for (int j = 0; j < 3; ++j) { sum += grid[x+j][y+i]; } if (sum != ans) return false; } if (grid[x][y]+grid[x+1][y+1]+grid[x+2][y+2] != ans) return false; if (grid[x+2][y]+grid[x+1][y+1]+grid[x][y+2] != ans) return false; return true; } int numMagicSquaresInside(vector<vector<int>>& grid) { int ans = 0; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { if (check(grid, i, j)) ans++; } } return ans; } }; int main() { return 0; }
true
7f153677fe9456ae6e17d26f9582314bc665c297
C++
SourDumplings/CodeSolutions
/Book practices/《C++primer》 5th 练习代码/chapter3/Exercise3.32.cpp
UTF-8
421
2.734375
3
[]
no_license
/* @Date : 2017-12-15 20:14:14 @Author : 酸饺子 (changzheng300@foxmail.com) @Link : https://github.com/SourDumplings @Version : $Id$ */ /* p107 */ #include <iostream> #include <cstdio> #include <string> #include <vector> using namespace std; int main() { vector<int> v; for (int i = 0; i < 10; i++) { v.push_back(i); } for (auto j : v) { cout << j << endl; } return 0; }
true
68ca383824b68d47d7b3eee438f6a0c394813b87
C++
rkurdyumov/cs225b
/project2/global_planner/src/global_planner.cpp
UTF-8
13,608
2.53125
3
[]
no_license
#include <ros/ros.h> #include <stdio.h> #include <tf/transform_listener.h> #include <tf/transform_broadcaster.h> #include <iostream> #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <nav_msgs/OccupancyGrid.h> #include <nav_msgs/GridCells.h> #include "../../../include/search.h" #include "global_planner/GlobalPath.h" #include "global_planner/NavFunction.h" #include <visualization_msgs/Marker.h> #include <std_msgs/ColorRGBA.h> #include <std_msgs/String.h> using namespace std; #define ROBOT_RADIUS 0.157 // Robot's radius in meters #define WALL_VALUE 100 #define INITIALIZER_LARGE 100000 #define INITIALIZER_SMALL -INITIALIZER_LARGE float METERS_PER_CELL = 0; Matrix<int> occupancyGrid; // Stores walls (WALL_VALUE) and empty (0) cells Matrix<float> distancesToObstacles; // Stores distances from each cell to nearest obstacle Matrix<float> I; // Stores intrinsic cost of each cell due to nearest obstacle list<State> objectStates; // (x,y) locations where objects are present Matrix<float> h; // Heuristic distances // ros::Publisher pubGlobalPath; ros::Publisher pubNavFn; //ros::Publisher pubObstacleLocs; //ros::Publisher pubIdisp; //ros::Publisher pubhdisp; // Robot and goal poses State robotState = State(0,0); State goalState = State(0,0); // Given a distance away from object, r, this function returns the intrinsic // object cost at this location float objectCostCalculatorFn(float r) { if(METERS_PER_CELL <= 0) throw("global_planner.cpp::objectCostCalculatorFn(): Invalid METERS_PER_CELL"); float epsilon_distance = 2*ROBOT_RADIUS/METERS_PER_CELL; float epsilon = 1; // Value we should be at or below at epsilon_distance float sigma = log(4/epsilon)/(epsilon_distance); float f = 0; if(r <= ROBOT_RADIUS/METERS_PER_CELL) f = WALL_VALUE; else if(r >= epsilon_distance) f = 0; else f = WALL_VALUE*exp(-sigma*(r-ROBOT_RADIUS/METERS_PER_CELL)); return f; } // Successor retrievers list<State>& get4Successors(State state) { State successor; list<State>* successorStates = new list<State>(); float cellWidth = 1; for(int i = -1; i <= 1; i++) { for(int j = -1; j <= 1; j++) { if(abs(i) != abs(j)) { successor = state; successor.x += i*cellWidth; successor.y += j*cellWidth; // Check to make sure the successor isn't off the grid and isn't // another obstacle if( (successor.x >= 0 && successor.x < occupancyGrid.maxX()) && (successor.y >= 0 && successor.y < occupancyGrid.maxY()) && !occupancyGrid.equals(successor.x,successor.y,WALL_VALUE) ) { successorStates->push_back(successor); } } } } return *successorStates; } list<State>& get8Successors(State state) { State successor; list<State>* successorStates = new list<State>(); float cellWidth = 1; for(int i = -1; i <= 1; i++) { for(int j = -1; j <= 1; j++) { if(i!=0 || j!=0) { successor = state; successor.x += i*cellWidth; successor.y += j*cellWidth; // Check to make sure the successor isn't off the grid and isn't // another obstacle if( (successor.x >= 0 && successor.x < occupancyGrid.maxX()) && (successor.y >= 0 && successor.y < occupancyGrid.maxY()) && !occupancyGrid.equals(successor.x,successor.y,WALL_VALUE) ) { successorStates->push_back(successor); } } } } return *successorStates; } // Goal conditions bool farEnoughAwayFromStartState(Node currNode) { if(METERS_PER_CELL <= 0) throw("global_planner.cpp::farEnoughAwayFromStartState(): Invalid METERS_PER_CELL"); Node* tempNode = NULL; Node* nextNode = &currNode; do { tempNode = nextNode; nextNode = nextNode->parent; }while(nextNode); float distance = Utility::euclideanDistance(tempNode->state,currNode.state); bool result = distance > 2.0*ROBOT_RADIUS/METERS_PER_CELL; return result; } bool isRobotState(Node currNode) { return (currNode.state == robotState); } bool isGoalState(Node currNode) { return (currNode.state == goalState); } bool nullGoal(Node currNode) { return false; } void updateH() { Search search; // With I, compute potential at each cell by starting at the goal h.resize(I.maxX(),I.maxY(),INITIALIZER_LARGE); search.wavefrontPotential(goalState,&get4Successors,&isRobotState,I,h); /*ValueIndexPair<float> vip = h.max(INITIALIZER_LARGE); float hmax = vip.value; visualization_msgs::Marker hdisp; hdisp.header.frame_id = "/map"; hdisp.header.stamp = ros::Time::now(); hdisp.ns = "Idisp"; hdisp.action = visualization_msgs::Marker::ADD; hdisp.pose.orientation.w = 1.0; hdisp.scale.x = 0.05; hdisp.scale.y = 0.05; hdisp.id = 0; hdisp.type = visualization_msgs::Marker::POINTS; hdisp.color.a = 1; hdisp.color.r = 1; for(int x = 0; x < h.maxX(); x++) { for(int y = 0; y < h.maxY(); y++) { if(h(x,y) < INITIALIZER_LARGE) { geometry_msgs::Point pt; pt.x = x*METERS_PER_CELL; pt.y = y*METERS_PER_CELL; std_msgs::ColorRGBA color; color.a = 1; float color_set = h(x,y); int max_color = 40; color_set = (color_set > max_color)?0:color_set/max_color; color.r = color_set; color.g = color_set; color.b = color_set; //color.b = h(x,y)/hmax; hdisp.colors.push_back(color); hdisp.points.push_back(pt); } } } pubhdisp.publish(hdisp); cout << "Published hdisp with " << hdisp.points.size() << " points with hmax=" << hmax << endl;*/ } // Responds to the send_global_path request void sendGlobalPath() { // Case there is no goalState and/or robotState if(robotState.isNull() || goalState.isNull() || h.isEmpty()) return; geometry_msgs::PointStamped nextPoint; global_planner::GlobalPath msg; msg.resolution = METERS_PER_CELL; // Start at robotState, move a short distance in direction of gradient // (interpolate at this location), then stop and repeat process float h_orientation; float step_size = 0.5; float distance_from_goal = 1.0; State state = robotState; // Keep doing this movement until we're within distance_from_goal // of the goalState int i = 0; while(Utility::euclideanDistance(state,goalState) > distance_from_goal && i < 5000) { // Compute the gradient of the potential function at every point h_orientation = h.gradient_orientation(state); state.x -= step_size*cos(h_orientation); Utility::bound(state.x,0,h.maxX()-1); state.y -= step_size*sin(h_orientation); Utility::bound(state.y,0,h.maxY()-1); nextPoint.header.stamp = ros::Time::now(); nextPoint.header.frame_id = "map"; nextPoint.point.x = state.x*METERS_PER_CELL; nextPoint.point.y = state.y*METERS_PER_CELL; try { msg.points.push_back(nextPoint); } catch (const bad_alloc &) { cout << "got bad alloc" << endl; //pubGlobalPath.publish(msg); return; } } pubGlobalPath.publish(msg); cout << "Published GlobalPath with numSteps=" << msg.points.size() << endl; } // Responds to the send_nav_fn request void sendNavFn() { if(robotState.isNull() || goalState.isNull() || h.isEmpty()) return; //cout << "In sendNavFnCallback()" << endl; global_planner::NavFunction nav_msg; nav_msg.header.stamp = ros::Time::now(); nav_msg.header.frame_id = "map"; nav_msg.resolution = METERS_PER_CELL; nav_msg.height = h.maxX(); nav_msg.width = h.maxY(); for(int x = 0; x < h.maxX(); x++) { for(int y = 0; y < h.maxY(); y++) { float value = h(x,y); if(value < INITIALIZER_LARGE) { // Only send values that are less than the initialized INITIALIZER_LARGE value nav_msg.h_val.push_back(value); nav_msg.h_x.push_back(x); nav_msg.h_y.push_back(y); } } } // Also send the max value in the potential field for display purposes ValueIndexPair<float> valueIndexPair = h.max(INITIALIZER_LARGE); nav_msg.maxValue = valueIndexPair.value; pubNavFn.publish(nav_msg); cout << "Published NavFunction" << endl; } // Robot position (x,y,theta) void robotPoseCallback(const geometry_msgs::PoseWithCovarianceStamped amcl_pose) { robotState.x = round(float(amcl_pose.pose.pose.position.x)/METERS_PER_CELL); robotState.y = round(float(amcl_pose.pose.pose.position.y)/METERS_PER_CELL); robotState.theta = tf::getYaw(amcl_pose.pose.pose.orientation); cout << "robotState=(" << robotState.x << "," << robotState.y << ")" << endl; } // Obstacle locations (x,y) void goalPoseCallback(const geometry_msgs::PoseStamped goalPose) { goalState.x = round(float(goalPose.pose.position.x)/METERS_PER_CELL); goalState.y = round(float(goalPose.pose.position.y)/METERS_PER_CELL); goalState.theta = tf::getYaw(goalPose.pose.orientation); cout << "goalState=(" << goalState.x << "," << goalState.y << ")" << endl; updateH(); sendNavFn(); sendGlobalPath(); } // Wall locations (x,y) - will only get called once on startup of this .exe or on startup of map_server void occupancyGridCallback(const nav_msgs::OccupancyGrid occupancy_grid) { // For the object wavefront calculation occupancyGrid = Matrix<int>::initMatrixWithValue(occupancy_grid.info.width,occupancy_grid.info.height,0); distancesToObstacles = Matrix<float>::initMatrixWithValue(occupancyGrid.maxX(),occupancyGrid.maxY(),INITIALIZER_LARGE); METERS_PER_CELL = occupancy_grid.info.resolution; objectStates.clear(); /*nav_msgs::GridCells obstacles; obstacles.header.frame_id = "/map"; obstacles.header.stamp = ros::Time::now(); obstacles.cell_width = METERS_PER_CELL; obstacles.cell_height = METERS_PER_CELL;*/ // Copy object information from occupancy_grid.data to occupancyGrid for(int x = 0; x < occupancyGrid.maxX(); x++) { for(int y = 0; y < occupancyGrid.maxY(); y++) { int data = (int)occupancy_grid.data[y*occupancyGrid.maxX()+x]; if(data != 0) { // Set the object wavefront at this location to 0 (bc it is an object) occupancyGrid.assign(x,y,WALL_VALUE); distancesToObstacles.assign(x,y,0); objectStates.push_back(State(x,y)); /*geometry_msgs::Point pt; pt.x = x*METERS_PER_CELL; pt.y = y*METERS_PER_CELL; pt.z = 0; obstacles.cells.push_back(pt);*/ } } } //pubObstacleLocs.publish(obstacles); //cout << "Published obstacleLocs with " << obstacles.cells.size() << " points" << endl; Search search; // Run a wavefront from each object to the surrounding cells. distancesToObstacles will be // filled out with the distances to the nearest object from each cell search.ucs(objectStates,&get4Successors,&farEnoughAwayFromStartState,distancesToObstacles); // For all the values in the occupancyGridInvertedCopy that are still very large (>WALL_VALUE), // reset them to 0, signifying that they aren't very close to any objects. Also, // pass the distances from objects to the cost calculator function. I.resize(distancesToObstacles.maxX(),distancesToObstacles.maxY(),INITIALIZER_LARGE); for(int x = 0; x < distancesToObstacles.maxX(); x++) { for(int y = 0; y < distancesToObstacles.maxY(); y++) { if(distancesToObstacles(x,y) > WALL_VALUE) I.assign(x,y,0); else I.assign(x,y,objectCostCalculatorFn(distancesToObstacles(x,y))); } } /*ValueIndexPair<float> vip = I.max(INITIALIZER_LARGE); float Imax = vip.value; visualization_msgs::Marker Idisp; Idisp.header.frame_id = "/map"; Idisp.header.stamp = ros::Time::now(); Idisp.ns = "Idisp"; Idisp.action = visualization_msgs::Marker::ADD; Idisp.pose.orientation.w = 1.0; Idisp.scale.x = 0.05; Idisp.scale.y = 0.05; Idisp.id = 0; Idisp.type = visualization_msgs::Marker::POINTS; Idisp.color.r = 1; Idisp.color.a = 1; for(int x = 0; x < I.maxX(); x++) { for(int y = 0; y < I.maxY(); y++) { if(I(x,y) < INITIALIZER_LARGE) { geometry_msgs::Point pt; pt.x = x*METERS_PER_CELL; pt.y = y*METERS_PER_CELL; std_msgs::ColorRGBA color; color.r = I(x,y)/Imax; color.a = 1; Idisp.colors.push_back(color); Idisp.points.push_back(pt); } } } pubIdisp.publish(Idisp); cout << "Published Idisp with " << Idisp.points.size() << " points with Imax=" << Imax << endl;*/ } #define BUFFER_SIZE 1 int main(int argc, char** argv) { ros::init(argc, argv, "global_planner"); ros::NodeHandle nh; // pubGlobalPath = nh.advertise<global_planner::GlobalPath>("/global_path",BUFFER_SIZE,true); pubNavFn = nh.advertise<global_planner::NavFunction>("/nav_fn",BUFFER_SIZE,true); //pubObstacleLocs = nh.advertise<nav_msgs::GridCells>("/obstacle_locs",BUFFER_SIZE,true); //pubIdisp = nh.advertise<visualization_msgs::Marker>("/Idisp",BUFFER_SIZE,true); //pubhdisp = nh.advertise<visualization_msgs::Marker>("/hdisp",BUFFER_SIZE,true); // ros::Subscriber sub = nh.subscribe("/amcl_pose", BUFFER_SIZE, robotPoseCallback); ros::Subscriber sub1 = nh.subscribe("/map", BUFFER_SIZE, occupancyGridCallback); ros::Subscriber sub2 = nh.subscribe<geometry_msgs::PoseStamped>("/move_base_simple/goal", BUFFER_SIZE, goalPoseCallback); ros::spin(); return(0); }
true
9b628845cca8c0c1363a712e08997244e33d15bd
C++
gitpackage/MohammedShafiuddin_Cplusplus
/mshafi2Proj7/Creature.h
UTF-8
596
2.5625
3
[]
no_license
#ifndef CREATURE_H #define CREATURE_H #include "Enums.h" #include <stdio.h> #include <stdlib.h> class Island; class Creature { protected: int row; int col; Island* isl; int daysElapsed; private: bool isAnt; int index; public: Creature(bool isant, Island* island, int index); bool getIsAnt(); void setLocation(int r, int c); Creature* spawn(int maxDays, int openArrayPosition); void move(); int getXLocation(); int getYLocation(); void setIndex(int newIndex); int getIndex(); void incrementDaysElapsed(); }; #endif
true
bdd2cc3256033ef23815cad1530ddb3e345d2a12
C++
TigNerkararyan/Data_Structures_Cpp
/BineryTree/bineryTree.hpp
UTF-8
516
2.640625
3
[]
no_license
#ifndef BINERYTREE_H #define BINERYTREE_H struct BineryNode { int data; BineryNode *left; BineryNode *right; }; class SearchTree { public: SearchTree(); ~SearchTree(); void InsertBineryNode(int data); void destroy_tree(); BineryNode* SearchInBineryTree(int data); void DeleteBineryNode(int data); private: void destroy_tree(BineryNode *list); void DeleteBineryNode(int data, BineryNode* list); BineryNode *root; }; #endif
true
ca2cc2cdf0a6a81f2e826107ea873450129cb45a
C++
charles-pku-2013/CodeRes_Cpp
/read_file_seperated_by_space.cpp
UTF-8
542
2.96875
3
[]
no_license
#include <string> #include <iostream> #include <fstream> using namespace std; int main(int argc, char **argv) { std::ifstream ifs(argv[1], std::ios::in); std::string val; ifs >> val; if (ifs) { cout << val << endl; cout << val.length() << endl; } else { cout << "read val fail!" << endl; } std::string line; if (std::getline(ifs, line)) { cout << line << endl; cout << line.length() << endl; } else { cout << "getline fail!" << endl; } return 0; }
true
308a29c3511bfebf5774a73266e087b737760e2f
C++
Mindhunter26/LabAndPr
/Lab3/Labb3.cpp
UTF-8
1,097
2.796875
3
[]
no_license
#include "pch.h" #include "libbmp.h" #include <iostream> int main() { BmpImg img; img.read("pic9.bmp"); const int width = img.get_width() - 1; const int height = img.get_height() - 1; char pix[4000]; char y = 0; int pos = 0; int k = 0; int bit; bool isEnd = false; for (int i = height; i >= 0; i--) { for (int j = width; j >= 0; j--) { bit = img.blue_at(j, i); y = y << 1; if (bit % 2 == 1) y++; k++; if (k == 8) { pix[pos] = y; pos++; k = 0; if (y == '\0') { isEnd = true; break; } } bit = img.green_at(j, i); y = y << 1; if (bit % 2 == 1) y++; k++; if (k == 8) { pix[pos] = y; pos++; k = 0; if (y == '\0') { isEnd = true; break; } } bit = img.red_at(j, i); y = y << 1; if (bit % 2 == 1) y++; k++; if (k == 8) { pix[pos] = y; pos++; k = 0; if (y == '\0') { isEnd = true; break; } } } if (isEnd) break; } std::cout << pix; }
true
6391d2f45a6ab0e5aade70e31b1faa6b4cacc568
C++
Svalburg/TypeSystemImplementation
/include/ValueString.h
UTF-8
270
2.671875
3
[]
no_license
#ifndef VALUESTRING_H #define VALUESTRING_H #include "Value.h" #include <string> class ValueString : public Value { public: ValueString(std::string value); std::string getValue(); virtual ~ValueString(); private: std::string value; }; #endif //VALUESTRING_H
true
929a7f9b6aef2de1652a0fa061c2ac6baca253c8
C++
abilkht/ds
/HashMap/map.cpp
UTF-8
4,091
3.171875
3
[]
no_license
#include "map.h" // From previous task: bool equal(const std::string& s1, const std::string& s2) { if (s1.size() == s2.size()) { for (size_t i = 0; i < s1.size(); ++i) { if (tolower(s1[i]) != tolower(s2[i])) return false; } return true; } return false; } // Hash function size_t hash(const std::string& s) { size_t h = 0; for (char c : s) { h = h * 349 + tolower(c); } return h; } // Finding element by key in const list of pairs map::listofpairs::const_iterator map::find(const listofpairs& lst, const std::string& key) { auto p = lst.begin(); while (p != lst.end() && !equal(p->first, key)) ++p; return p; } // Finding element by key in list of pairs map::listofpairs::iterator map::find(listofpairs& lst, const std::string& key) { auto p = lst.begin(); while (p != lst.end() && !equal(p->first, key)) ++p; return p; } #if 1 // Searching element by key in map bool map::contains_key(const std::string& key) const { auto ls = getbucket(key); return find(ls, key) != ls.end(); } // Element insertion into map bool map::insert(const std::string& key, unsigned int val) { if (!contains_key(key)) { getbucket(key).push_back({key, val}); map_size += 1; check_rehash(); return true; } return false; } // Element access and/or modification and/or creation in map unsigned int& map::operator[] (const std::string& key) { unsigned int val = 0; listofpairs::iterator el; if (insert(key, val) || !insert(key, val)) el = find(getbucket(key), key); return el->second; } // Element access and/or modification in map unsigned int& map::at(const std::string& key) { auto& ls = getbucket(key); auto el = find(ls, key); if (el == ls.end()) throw std::out_of_range("at(): string not found"); return el->second; } // Element access in map unsigned int map::at(const std::string& key) const { auto ls = getbucket(key); auto el = find(ls, key); if (el == ls.end()) throw std::out_of_range("at(): string not found"); return el->second; } // Rehashing function void map::rehash(size_t newbucketsize) { size_t index = 0; if (newbucketsize < 4) newbucketsize = 4; std::vector<listofpairs> newbuckets{newbucketsize}; for (auto& i : buckets) { for (auto& el : i) { index = hash(el.first) % newbucketsize; newbuckets[index].push_back(el); } } buckets = newbuckets; } // Checking for necessity of rehash void map::check_rehash() { if (loadfactor() > max_load_factor) rehash(buckets.size() * 2); } // Element removal from map bool map::remove(const std::string& key) { auto& ls = getbucket(key); auto el = find(ls, key); if (el != ls.end()) { ls.remove(*el); map_size -= 1; return true; } return false; } #endif // Stdev calculation double map::standarddev() const { double sum = 0.0; double lf = loadfactor(); for (const auto& l : buckets) { double dif = l.size() - lf; sum += dif * dif; } return sqrt(sum / buckets. size()); } // Clearing map content void map::clear() { for (auto& l : buckets) l.clear(); map_size = 0; } #if 1 // Printing content of map std::ostream& map::print( std::ostream& out ) const { for (size_t i = 0; i < buckets.size(); ++i) { out << "bucket[" << i << "]:\t{"; for (auto el = buckets[i].begin(); el != buckets[i].end(); ++el) { if (el != buckets[i].begin()) out << ","; out << " " << el->first << "/" << el->second; } out << " }\n"; } return out; } #endif // Printing statistics std::ostream& map::printstatistics(std::ostream& out) const { out << "set size = " << size( ) << "\n"; out << "load factor = " << loadfactor( ) << " ( max = " << max_load_factor << " )\n"; out << "standard deviation = " << standarddev( ) << "\n"; return out; }
true
0e33aa2ed32a3630ee7f3e1c5f6ce39a03909bcf
C++
Ball-Man/GOP
/src/card_best_forward.cpp
UTF-8
724
2.78125
3
[]
no_license
#include "card_best_forward.h" #include "gameboard.h" #include "screen.h" CardBestForward::CardBestForward(const String& text, int steps) : Card(text) { steps_ = steps; } void CardBestForward::Do(Gameboard& gameboard) const { int max = gameboard.Players()[0].Coins(); for(int i = 1; i < gameboard.Players().Length(); i++) { Player& player = gameboard.Players()[i]; if(player.Coins() > max) max = player.Coins(); } // Check again cause ALL the bests(on equal merit) have to go forward for(int i = 0; i < gameboard.Players().Length(); i++) { Player& player = gameboard.Players()[i]; if(gameboard.Players()[i].Coins() == max) player.StepForward(steps_); } screen::Wait(); }
true
049e0b9d266fd41f10b2f98bbd11d0b6249083a2
C++
watermantle/CPP_Financial_Engineering
/Homework/6 HW submission/4.2b/4.2b.1/Excercise4.2b.1.cpp
UTF-8
1,021
3.59375
4
[]
no_license
// Implement templated version of Array class // To test static variable for array default size #include <iostream> #include "Array.hpp" #include "Exception.hpp" // Declaration for a complete namespace using namespace YuBai::Containers; using namespace std; int main() { // Decalre three objects with default size of 10 Array<int> intArray1; Array<int> intArray2; Array<double> doubleArray; cout << intArray1.DefaultSize() << endl; // 10 cout << intArray2.DefaultSize() << endl; // 10 cout << doubleArray.DefaultSize() << endl; // 10 intArray1.DefaultSize(15); cout << intArray1.DefaultSize() << endl; // 15 cout << intArray2.DefaultSize() << endl; // 15 cout << doubleArray.DefaultSize() << endl; // 10 /*All objects will share the same static variables. For templated version, static variables will share within a typename. Since intArray1 and intArray2 have the same typename, they will print 15 when static varibale have been changed but double type's object stays the unchanged*/ return 0; }
true
9f9cef4cb492b4cf7d366b85568163a0244d6e39
C++
heyshb/Competitive-Programming
/CodeForces/PastContest/787/C.cpp
UTF-8
1,026
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long LL; int N; int K[2]; int S[2][7010]; int v[2][7010];//1 win -1 lose 0 ?? bool vis[2][7010]; int pre(int X,int step) { X-=step; if (X<=0) X+=N; } void print(int V) { if (V==0) printf("Loop "); else if (V==1) printf("Win "); else printf("Lose "); } int dfs(int pos,int nowplayer) { //printf("%d %d\n",pos,nowplayer); if (pos==1) return -1; if (vis[nowplayer][pos]) return v[nowplayer][pos]; vis[nowplayer][pos] = true; int next, sg = 1; for (int i=1;i<=K[nowplayer];i++) { next = pos + S[nowplayer][i]; if (next > N) next -= N; //printf("%d %d--> %d\n",pos,nowplayer,next); sg = min(sg, dfs(next, nowplayer^1)); } v[nowplayer][pos] = -sg; return v[nowplayer][pos]; //printf("RT"); } int main() { scanf("%d",&N); for (int i=0;i<2;i++) { scanf("%d",&K[i]); for (int j=1;j<=K[i];j++) scanf("%d",&S[i][j]); } memset(v,0,sizeof(v)); for (int i=2;i<=N;i++)print(dfs(i,0)); puts(""); for (int i=2;i<=N;i++)print(dfs(i,1)); }
true
9bbdc0745c2c5518e6fcf5e835d6f819e6210f19
C++
HunterKonoha/MathExpression
/src/MathExpression/ExpValue/Derive/Function/ExtendFunction.cpp
UTF-8
12,082
2.59375
3
[]
no_license
#include "ExtendFunction.h" #include "../../\ArrayEval.h" #include "../../Functions.h" #include <boost\multiprecision\cpp_dec_float.hpp> #include <boost\limits.hpp> template<typename T, int ArgumentSize> paf::MathExpression::ExpValueClass::ExtendFunction::Sum<T, ArgumentSize>::Sum(TreeType Node, NodeType Func) try :ArrayValue<T>(Functions::CheckArgumentSize<ArgumentSize>(Node), Func) { } catch (MathExpessionException& e) { e.ReplaceMessage("{Function}", "Sum"); throw; } template<typename T, int ArgumentSize> paf::MathExpression::ExpValueClass::ExtendFunction::Sum<T,ArgumentSize>::~Sum() { } template<typename T, int ArgumentSize> T paf::MathExpression::ExpValueClass::ExtendFunction::Sum<T, ArgumentSize>::ExpEval(ArgumentType Argument, VectorArgumentType VecArgument) { T result(0); if (this->GetNodeSize() != 0) { for (int i = 0, max = this->GetNodeSize(); i < max; ++i) { result += this->GetNode(i)->ExpEval(Argument, VecArgument); } } else { auto vec = this->GetArrayFunc()->VecEval(Argument, VecArgument); for (auto val : vec) { result += val; } } return result; } template paf::MathExpression::ExpValueClass::ExtendFunction::Sum<int,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Sum<int,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Sum<double,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Sum<double,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Sum<boost::multiprecision::cpp_dec_float_100,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Sum<boost::multiprecision::cpp_dec_float_100,0>; template<typename T, int ArgumentSize> paf::MathExpression::ExpValueClass::ExtendFunction::Average<T,ArgumentSize>::Average(TreeType Node,NodeType Func)try :ArrayValue<T>(Functions::CheckArgumentSize<ArgumentSize>(Node), Func) { } catch (MathExpessionException& e) { e.ReplaceMessage("{Function}", "Average"); throw; } template<typename T, int ArgumentSize> paf::MathExpression::ExpValueClass::ExtendFunction::Average<T,ArgumentSize>::~Average() { } template<typename T, int ArgumentSize> T paf::MathExpression::ExpValueClass::ExtendFunction::Average<T, ArgumentSize>::ExpEval(ArgumentType Argument, VectorArgumentType VecArgument) { T result(0); if (this->GetNodeSize() != 0) { int max = this->GetNodeSize(); for (int i = 0; i < max; ++i) { result += this->GetNode(i)->ExpEval(Argument, VecArgument); } result /= max; } else { auto vec = this->GetArrayFunc()->VecEval(Argument, VecArgument); for (auto val : vec) { result += val; } result /= vec.size(); } return result; } template paf::MathExpression::ExpValueClass::ExtendFunction::Average<int,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Average<int,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Average<double,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Average<double,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Average<boost::multiprecision::cpp_dec_float_100,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Average<boost::multiprecision::cpp_dec_float_100,0>; template<typename T, int ArgumentSize> paf::MathExpression::ExpValueClass::ExtendFunction::Min<T,ArgumentSize>::Min(TreeType Node,NodeType Func)try :ArrayValue<T>(Functions::CheckArgumentSize<ArgumentSize>(Node), Func) { } catch (MathExpessionException& e) { e.ReplaceMessage("{Function}", "Min"); throw; } template<typename T, int ArgumentSize> paf::MathExpression::ExpValueClass::ExtendFunction::Min<T,ArgumentSize>::~Min() { } template<typename T, int ArgumentSize> T paf::MathExpression::ExpValueClass::ExtendFunction::Min<T, ArgumentSize>::ExpEval(ArgumentType Argument, VectorArgumentType VecArgument) { T result(std::numeric_limits<T>::max()); if (this->GetNodeSize() != 0) { for (int i = 0, max = this->GetNodeSize(); i < max; ++i) { if (result > this->GetNode(i)->ExpEval(Argument, VecArgument))result = this->GetNode(i)->ExpEval(Argument, VecArgument); } } else { auto vec = this->GetArrayFunc()->VecEval(Argument, VecArgument); for (auto val : vec) { if (result > val)result = val; } } return result; } template paf::MathExpression::ExpValueClass::ExtendFunction::Min<int,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Min<int,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Min<double,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Min<double,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Min<boost::multiprecision::cpp_dec_float_100,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Min<boost::multiprecision::cpp_dec_float_100,0>; template<typename T, int ArgumentSize> paf::MathExpression::ExpValueClass::ExtendFunction::Max<T,ArgumentSize>::Max(TreeType Node,NodeType Func)try :ArrayValue<T>(Functions::CheckArgumentSize<ArgumentSize>(Node), Func) { } catch (MathExpessionException& e) { e.ReplaceMessage("{Function}", "Max"); throw; } template<typename T, int ArgumentSize> paf::MathExpression::ExpValueClass::ExtendFunction::Max<T,ArgumentSize>::~Max() { } template<typename T, int ArgumentSize> T paf::MathExpression::ExpValueClass::ExtendFunction::Max<T, ArgumentSize>::ExpEval(ArgumentType Argument, VectorArgumentType VecArgument) { T result(0); if (this->GetNodeSize() != 0) { for (int i = 0, max = this->GetNodeSize(); i < max; ++i) { if (result < this->GetNode(i)->ExpEval(Argument, VecArgument))result = this->GetNode(i)->ExpEval(Argument, VecArgument); } } else { auto vec = this->GetArrayFunc()->VecEval(Argument, VecArgument); for (auto val : vec) { if (result < val)result = val; } } return result; } template paf::MathExpression::ExpValueClass::ExtendFunction::Max<int,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Max<int,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Max<double,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Max<double,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Max<boost::multiprecision::cpp_dec_float_100,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Max<boost::multiprecision::cpp_dec_float_100,0>; template<typename T> paf::MathExpression::ExpValueClass::ExtendFunction::RealRand<T>::RealRand(TreeType Node)try :ExpValue<T>(Functions::CheckArgumentSize<2>(Node)),gen_(std::random_device()()){ } catch (MathExpessionException& e) { e.ReplaceMessage("{Function}", "Realrand"); throw; } template<typename T> paf::MathExpression::ExpValueClass::ExtendFunction::RealRand<T>::~RealRand() { } template<typename T> T paf::MathExpression::ExpValueClass::ExtendFunction::RealRand<T>::ExpEval(ArgumentType Argument,VectorArgumentType VecArgument) { return std::uniform_real_distribution<>(this->GetNode(0)->ExpEval(Argument, VecArgument), this->GetNode(1)->ExpEval(Argument, VecArgument))(this->gen_); } template<> boost::multiprecision::cpp_dec_float_100 paf::MathExpression::ExpValueClass::ExtendFunction::RealRand<boost::multiprecision::cpp_dec_float_100>::ExpEval(ArgumentType Argument, VectorArgumentType VecArgument) { return std::uniform_real_distribution<>(this->GetNode(0)->ExpEval(Argument, VecArgument).convert_to<double>(), this->GetNode(1)->ExpEval(Argument, VecArgument).convert_to<double>())(this->gen_); } template paf::MathExpression::ExpValueClass::ExtendFunction::RealRand<int>; template paf::MathExpression::ExpValueClass::ExtendFunction::RealRand<double>; template paf::MathExpression::ExpValueClass::ExtendFunction::RealRand<boost::multiprecision::cpp_dec_float_100>; template<typename T> paf::MathExpression::ExpValueClass::ExtendFunction::IntRand<T>::IntRand(TreeType Node)try :ExpValue<T>(Functions::CheckArgumentSize<2>(Node)), gen_(std::random_device()()) { } catch (MathExpessionException& e) { e.ReplaceMessage("{Function}", "Intrand"); throw; } template<typename T> paf::MathExpression::ExpValueClass::ExtendFunction::IntRand<T>::~IntRand() { } template<typename T> T paf::MathExpression::ExpValueClass::ExtendFunction::IntRand<T>::ExpEval(ArgumentType Argument,VectorArgumentType VecArgument) { return std::uniform_int_distribution<>(this->GetNode(0)->ExpEval(Argument, VecArgument), this->GetNode(1)->ExpEval(Argument, VecArgument))(this->gen_); } template<> boost::multiprecision::cpp_dec_float_100 paf::MathExpression::ExpValueClass::ExtendFunction::IntRand<boost::multiprecision::cpp_dec_float_100>::ExpEval(ArgumentType Argument, VectorArgumentType VecArgument) { return std::uniform_int_distribution<>(this->GetNode(0)->ExpEval(Argument, VecArgument).convert_to<int>(), this->GetNode(1)->ExpEval(Argument, VecArgument).convert_to<int>())(this->gen_); } template paf::MathExpression::ExpValueClass::ExtendFunction::IntRand<int>; template paf::MathExpression::ExpValueClass::ExtendFunction::IntRand<double>; template paf::MathExpression::ExpValueClass::ExtendFunction::IntRand<boost::multiprecision::cpp_dec_float_100>; template<typename T, int ArgumentSize> paf::MathExpression::ExpValueClass::ExtendFunction::Std<T,ArgumentSize>::Std(TreeType Node,NodeType Func)try :ArrayValue<T>(Functions::CheckArgumentSize<ArgumentSize>(Node), Func) { } catch (MathExpessionException& e) { e.ReplaceMessage("{Function}", "Std"); throw; }template<typename T, int ArgumentSize> paf::MathExpression::ExpValueClass::ExtendFunction::Std<T,ArgumentSize>::~Std() { } template<typename T, int ArgumentSize> T paf::MathExpression::ExpValueClass::ExtendFunction::Std<T, ArgumentSize>::ExpEval(ArgumentType Argument, VectorArgumentType VecArgument) { T result(0); T result2(0); if (this->GetNodeSize() != 0) { for (int i = 0, max = this->GetNodeSize(); i < max; ++i) { auto val = this->GetNode(i)->ExpEval(Argument, VecArgument); result += val*val; result2 += val; } result /= this->GetNodeSize(); result2 /= this->GetNodeSize(); } else { auto vec = this->GetArrayFunc()->VecEval(Argument, VecArgument); for (auto val : vec) { result += val*val; result2 += val; } result /= vec.size(); result2 /= vec.size(); } return std::sqrt(result - result2*result2); } template<> boost::multiprecision::cpp_dec_float_100 paf::MathExpression::ExpValueClass::ExtendFunction::Std<boost::multiprecision::cpp_dec_float_100, -1>::ExpEval(ArgumentType Argument, VectorArgumentType VecArgument) { boost::multiprecision::cpp_dec_float_100 result(0); boost::multiprecision::cpp_dec_float_100 result2(0); for (int i = 0, max = this->GetNodeSize(); i < max; ++i) { auto val = this->GetNode(i)->ExpEval(Argument, VecArgument); result += val*val; result2 += val; } result /= this->GetNodeSize(); result2 /= this->GetNodeSize(); return boost::multiprecision::sqrt(result - result2*result2); } template<> boost::multiprecision::cpp_dec_float_100 paf::MathExpression::ExpValueClass::ExtendFunction::Std<boost::multiprecision::cpp_dec_float_100, 0>::ExpEval(ArgumentType Argument, VectorArgumentType VecArgument) { boost::multiprecision::cpp_dec_float_100 result(0); boost::multiprecision::cpp_dec_float_100 result2(0); auto vec = this->GetArrayFunc()->VecEval(Argument, VecArgument); for (auto val : vec) { result += val*val; result2 += val; } result /= vec.size(); result2 /= vec.size(); return boost::multiprecision::sqrt(result - result2*result2); } template paf::MathExpression::ExpValueClass::ExtendFunction::Std<int,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Std<int,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Std<double,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Std<double,-1>; template paf::MathExpression::ExpValueClass::ExtendFunction::Std<boost::multiprecision::cpp_dec_float_100,0>; template paf::MathExpression::ExpValueClass::ExtendFunction::Std<boost::multiprecision::cpp_dec_float_100,-1>;
true
cb8355af83bc9623a5edb248eb8da5dd6235d996
C++
Wlain/graphic_demo
/cross_platform_demo/src/utils/basic_timer.h
UTF-8
3,066
2.953125
3
[ "Apache-2.0" ]
permissive
// // Created by william on 2020/9/21. // #ifndef CPP_DEMO_BASIC_TIMER_H #define CPP_DEMO_BASIC_TIMER_H #pragma once #if defined(_WIN32_) || defined(WIN32) || defined(_WIN64_) || defined(WIN64) #include <windows.h> #elif !defined(__ANDROID__) && defined(__linux__) || defined(__APPLE__) #include <sys/time.h> #endif #include <ctime> // 用于基本计时的帮助器类。 class BasicTimer { public: // 初始化内部计时器值。 BasicTimer() { #if defined(_WIN32_) || defined(WIN32) || defined(_WIN64_) || defined(WIN64) if (!QueryPerformanceFrequency(&m_frequency)) { exit(0); } #endif Reset(); } // 将计时器重置为初始值。 void Reset() { Update(); m_startTime = m_currentTime; m_total = 0.0f; m_delta = 1000.0f / 60.0f; } // 更新计时器的内部值。 void Update() { #if defined(_WIN32_) || defined(WIN32) || defined(_WIN64_) || defined(WIN64) if (!QueryPerformanceCounter(&m_currentTime)) { exit(0); } m_total = static_cast<float>(static_cast<double>(m_currentTime.QuadPart - m_startTime.QuadPart) / static_cast<double>(m_frequency.QuadPart)) * 1000.0f; m_delta = static_cast<float>(static_cast<double>(m_currentTime.QuadPart - m_lastTime.QuadPart) / static_cast<double>(m_frequency.QuadPart)) * 1000.0f; #else gettimeofday(&m_currentTime, nullptr); double timeuse = 1000000.0 * (double)(m_currentTime.tv_sec - m_startTime.tv_sec) + m_currentTime.tv_usec - m_startTime.tv_usec; m_total = static_cast<float>(timeuse * 0.001); timeuse = 1000000.0 * (double)(m_currentTime.tv_sec - m_lastTime.tv_sec) + m_currentTime.tv_usec - m_lastTime.tv_usec; m_delta = static_cast<float>(timeuse * 0.001); #endif m_lastTime = m_currentTime; } // 在最后一次调用 Reset()与最后一次调用 Update()之间的持续时间(毫秒)。 [[nodiscard]] float GetTotal() const { return m_total; } // 在对 Update()的前两次调用之间的持续时间(毫秒)。 [[nodiscard]] float GetDelta() const { return m_delta; } [[maybe_unused]] float UpdateAndGetDelta() { this->Update(); return GetDelta(); } [[maybe_unused]] float UpdateAndGetTotal() { this->Update(); return GetTotal(); } private: #if defined(_WIN32_) || defined(WIN32) || defined(_WIN64_) || defined(WIN64) LARGE_INTEGER m_frequency; LARGE_INTEGER m_currentTime; LARGE_INTEGER m_startTime; LARGE_INTEGER m_lastTime; #else struct timeval m_startTime {}; struct timeval m_currentTime {}; struct timeval m_lastTime {}; #endif float m_total{}; float m_delta{}; }; #endif // CPP_DEMO_BASIC_TIMER_H
true
e34f686a201e447adff78a3cf4d11c2e502b985d
C++
zungry/leetcodeCode
/Letter Combinations of a Phone Number.cpp
UTF-8
918
3.015625
3
[]
no_license
class Solution { private: string num[10]; public: vector<string> letterCombinations(string digits) { vector<string> ret; ret.clear(); creatDict(); //string ans; //ans.clear(); dfs(digits,0,digits.size(),"",ret); return ret; } void dfs(string &digits,int depth, int maxDep,string ans,vector<string> &ret){ if(depth == maxDep){ ret.push_back(ans); // ans.clear(); return; } for(int i = 0 ; i < num[digits[depth]-'0'].size();i++){ dfs(digits,depth+1,maxDep,ans + num[digits[depth]-'0'][i],ret); } } void creatDict(){ num[2] = "abc"; num[3] = "def"; num[4] = "ghi"; num[5] = "jkl"; num[6] = "mno"; num[7] = "pqrs"; num[8] = "tuv"; num[9] = "wxyz"; } };
true
72f91494b5eec33fb097cba7a902ef1d2d243234
C++
shenhuashan/SysResourceMonitor
/VSSysResourceMonitor/SysResourceMonitor/Source/main.cpp
GB18030
1,711
2.578125
3
[]
no_license
#include <windows.h> #include <QtWidgets/QApplication> #include <QMessageBox> #include <QDir> #include "SRMError.h" #include "SRMScopeOnExit.h" #include "SysResourceMonitor.h" // жϳ֮Ļ, ֻܴһ bool checkUnique() { std::wstring sTitle = L"ʾ"; std::wstring sMessage = L"SysResourceMonitor Ѿ"; std::wstring sMutex = L"VS_SysResourceMonitor"; HANDLE hMutex = CreateMutex(NULL, TRUE, sMutex.c_str()); if (!hMutex){ MessageBox(NULL, sMessage.c_str(), sTitle.c_str(), S_OK); return false; } if (GetLastError() == ERROR_ALREADY_EXISTS){ MessageBox(NULL, sMessage.c_str(), sTitle.c_str(), S_OK); CloseHandle(hMutex); return false; }; return true; } bool initCOM() { if (S_OK != CoInitializeEx(nullptr, COINIT_MULTITHREADED)) return false; if (S_OK != CoInitializeSecurity(nullptr, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE, 0)) return false; return true; } void unInitCOM() { CoUninitialize(); } int main(int argc, char* argv[]) { // 1. comͳһʼطҪٳʼ if (!initCOM()) return -1; SCOPE_EXIT{ unInitCOM(); }; // 2. ֶ֧ if (!checkUnique()){ return 0; } // 3. QApplication a(argc, argv); QDir::setCurrent(qApp->applicationDirPath()); try{ SysResourceMonitor w; w.setWindowIcon(QIcon(":/Images/SysResourceMonitor.png")); w.hide(); // 岻ʾ w.doWork(); return a.exec(); } catch (SRMError & e){ QMessageBox::critical(nullptr, QString::fromStdWString(L"д"), QString::fromStdWString(L":%1").arg(e.errorCode()), QMessageBox::Ok); return -1; } }
true
dc03600c88e703b5837d346d078fa931478b9e4e
C++
cahnz1/CMSC-435
/proj2/trace.h
UTF-8
3,030
2.515625
3
[]
no_license
#ifndef TRACE_H #define TRACE_H //#include "slVector.H" #include <vector> #include <Eigen/Dense> class Ray { public: Eigen::Vector3d e; Eigen::Vector3d d; int depth; Ray(const Eigen::Vector3d &_e, const Eigen::Vector3d &_d, int _depth = 0) : e(_e), d(_d), depth(_depth) {}; }; class Fill { public: Eigen::Vector3d color; double kd, ks, shine, transmittance, ior; }; class HitRecord { public: double t, alpha, beta, gamma; Eigen::Vector3d p, n, v; Fill f; int raydepth; }; class Light { public: Eigen::Vector3d p, c; }; class Surface { public: virtual bool intersect(const Ray &r, double t0, double t1, HitRecord &hr) const = 0; //virtual Eigen::Vector3d normal(const Eigen::Vector3d &x) const = 0; virtual ~Surface() {}; }; class Triangle : public Surface { protected: Eigen::Vector3d a,b,c; public: Triangle(const Eigen::Vector3d &_a, const Eigen::Vector3d &_b, const Eigen::Vector3d &_c) : a(_a), b(_b), c(_c) {}; virtual bool intersect(const Ray &r, double t0, double t1, HitRecord &hr) const; // virtual Eigen::Vector3d normal(const Eigen::Vector3d &x) const; }; class TrianglePatch : public Triangle { Eigen::Vector3d n1, n2, n3; public: TrianglePatch(const Eigen::Vector3d &_a, const Eigen::Vector3d &_b, const Eigen::Vector3d &_c, const Eigen::Vector3d &_n1, const Eigen::Vector3d &_n2, const Eigen::Vector3d &_n3) : Triangle(_a,_b,_c), n1(_n1), n2(_n2), n3(_n3) {}; // virtual Eigen::Vector3d normal(const Eigen::Vector3d &x) const; }; class Poly : public Surface { std::vector<Eigen::Vector3d> verts; public: Poly(const std::vector<Eigen::Vector3d> &_verts) : verts(_verts) {}; virtual bool intersect(const Ray &r, double t0, double t1, HitRecord &hr) const; // virtual Eigen::Vector3d normal(const Eigen::Vector3d &x) const; }; class PolyPatch : public Poly { std::vector<Eigen::Vector3d> normals; public: PolyPatch(const std::vector<Eigen::Vector3d> &_verts, const std::vector<Eigen::Vector3d> &_normals) : Poly(_verts), normals(_normals) {}; }; class Sphere : public Surface { Eigen::Vector3d c; double rad; public: Sphere(const Eigen::Vector3d &_c, double _r) : c(_c), rad(_r) {}; virtual bool intersect(const Ray &r, double t0, double t1, HitRecord &hr) const; // virtual Eigen::Vector3d normal(const Eigen::Vector3d &x) const; }; class Tracer { Eigen::Vector3d bcolor, eye, at, up; double angle, hither; unsigned int res[2]; std::vector<std::pair<Surface *, Fill> > surfaces; std::vector<Light> lights; double shadowbias; Eigen::Vector3d *im; public: Tracer(const std::string &fname); ~Tracer(); void createImage(); Eigen::Vector3d castRay(const Ray &ray, double t0, double t1) const; Eigen::Vector3d shade(const HitRecord &hr,const Light &l, Fill &f,const Ray &ray, int bounceLimits) const; void writeImage(const std::string &fname); bool color; bool phong; bool stratified; bool reflections; bool shadows; bool verbose; int samples; double aperture; int maxraydepth; }; #endif
true
c3a05bbf682fec8565dc4df902f4c9cc7468883a
C++
adarsxh/Data-structure-in-C
/tree/BT to DLL.cpp
UTF-8
913
3.171875
3
[]
no_license
#include<iostream> #include<bits/stdc++.h> #include<stack> #include<queue> using namespace std; struct node{ int key; node *right; node *left; node(int x){ key = x; right = NULL; left = NULL; } }; node *prevv=NULL; node *btd(node *root){ if(root==NULL) return root; node *head=btd(root->left); if(prevv==NULL) head = root; else{ root->left=prevv; prevv->right=root; } prevv = root; btd(root->right); return head; } node *printll(node *head){ if(head==NULL) return head; while(head!=NULL){ cout<<head->key<<" "; head = head->right; } } int main(){ node *root = new node(10); root->left = new node(20); root->right = new node (30); root->right->left = new node(40); root->right->right = new node(50); root->left->right = new node(60); root->left->left = new node(70); node *head = btd(root); printll(head); }
true
4965b8b28cb0635d10d66a92078c362fb16ae39c
C++
shu7bh/SnakeGameGraphical
/Engine/Entity.cpp
UTF-8
580
3.25
3
[]
no_license
#include "Entity.h" Entity::Entity(int x, int y, int r, int g, int b, int width, int height) : x(x), y(y), r(r), g(g), b(b), width(width), height(height) {} void Entity::draw(Graphics& gfx) const { for(int i = x; i < x + width; ++i) for(int j = y; j < y + height; ++j) gfx.PutPixel(i, j, r, g, b); } bool Entity::checkCollision(const Entity& one, const Entity& two) { return one.x < two.x + two.width && // left <= right one.x + one.width > two.x && // right >= left one.y < two.y + two.height && // top <= bottom one.y + one.height > two.y; // bottom >= top }
true
908587321daf471d7ea3ce5b7e756dcb5466c885
C++
xzben/openGLStudy
/source/editor/source/view/EditorWindow_Menu.cpp
UTF-8
2,072
2.53125
3
[]
no_license
#include "EditorWindow.h" #include "EditorMenu.h" #include "EditorMenuBar.h" #include "DefineId.h" #include "EditorFrame.h" #include "event/EditorEventMgr.h" BEGIN_EDITOR_NAMESPACE struct MenuDefineItem { IDMainMenu id; const char* name; const char* shortcuts; std::vector<MenuDefineItem> items; }; static MenuDefineItem MainMenuConfig[] = { { IDMainMenu::File, "File", nullptr, { { IDMainMenu::FILE_EXIT, "Exit", "Alt+F4", {}}, } }, {IDMainMenu::Edit, "Edit", nullptr, { } }, {IDMainMenu::Window, "Window", nullptr, { } }, {IDMainMenu::View, "View", nullptr, { } }, {IDMainMenu::Help, "Help", nullptr, { } }, }; static EditorMenu* CreateMenuByConfig(const MenuDefineItem& config) { EditorMenu* menu = new EditorMenu(config.id, config.name, config.shortcuts == nullptr ? "" : config.shortcuts); for (auto sub : config.items) { EditorMenu* submenu = CreateMenuByConfig(sub); menu->addMenu(submenu); } return menu; } void EditorWindow::createFrameWindowSubMenu(int index, EditorFrame* frame) { IDMainMenu subid = IDMainMenu((int)IDMainMenu::Window + frame->getMainFrameId()); EditorMenu* submenu = new EditorMenu(subid, frame->getTitle().c_str(), ""); submenu->setItemCheckable(true); submenu->setClickCallback([=](bool ischeck) { frame->setVisible(ischeck); }); submenu->setChecked(frame->isVisible()); m_windowmenu->addMenu(submenu); } void EditorWindow::handleFrameEvent(EventData* event) { auto evframe = static_cast<EventDataFrame*>(event); int menuid = IDMainMenu::Window + event->sourceId; auto menu = m_windowmenu->getSubMenuById((IDMainMenu)menuid); if (menu) { menu->setChecked(evframe->evt == EditorFrameEvent::FRAME_OPEN); } } void EditorWindow::setupMenuBar() { m_menubar = new EditorMenuBar(); int size = sizeof(MainMenuConfig) / sizeof(MenuDefineItem); for (int i = 0; i < size; i++) { EditorMenu* menu = CreateMenuByConfig(MainMenuConfig[i]); m_menubar->addMenu(menu); if (menu->getMenuId() == IDMainMenu::Window) { m_windowmenu = menu; } } } END_EDITOR_NAMESPACE
true
bd3816078e8f875f1817f86ef88053bf7f6109a9
C++
anlaneg/test
/tool/easyweb/src/lib/libxml/interface/tinyxml_sxpath_adapter.cpp
UTF-8
5,377
2.6875
3
[]
no_license
/* * tinyxml_sxpath_adapter.cpp * * Created on: Oct 12, 2013 * Author: along */ #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include "libxml.h" #include "libsxpath.h" #include "tinyxml_private.h" /** * 子节点获取 * @param[in] parent 父节点 * @param[in] child_node_name 子节点名 注意,此节点名并不一定以'\0'结尾 * @param[in] child_node_name_length 子节点名长度 * @param[in] number 子节点索引 注意,此索引自1开始编号 * @return NULL 获取失败 * @return !NULL 获取成功 */ static inline libxml_node_t* sxpath_get_child_node(libxml_node_t*parent, const char* child_node_name, uint32_t child_node_name_length, uint32_t number) { assert(parent); assert(child_node_name); assert(child_node_name_length > 0); TiXmlElement*child; uint32_t find = 0; for (child = ((TiXmlElement*) parent)->FirstChildElement(); child; child = child->NextSiblingElement()) { assert(child->Value()); if (!strncmp(child->Value(), child_node_name, child_node_name_length)) { find++; if (find == number) { break; } } } return (libxml_node_t*) child; } /** * 子节点获取 * @param[in] parent 父节点 * @param[in] child_node_name 子节点名 注意,此节点名并不一定以'\0'结尾 * @param[in] child_node_name_length 子节点名长度 * @param[in] number 子节点索引 注意,此索引自1开始编号 * @return NULL 获取失败 * @return !NULL 获取成功 */ static inline libxml_node_t* sxpath_get_child_node(libxml_node_t*parent, const char* child_node_name, uint32_t child_node_name_length) { assert(parent); assert(child_node_name); assert(child_node_name_length > 0); uint32_t i = 0; for (i = 0; i < child_node_name_length; ++i) { assert(child_node_name[i]); if (child_node_name[i] == '[' || child_node_name[i] == '@') { assert(child_node_name[i + 1]); unsigned long number = 1; if (child_node_name[i] == '[') { char* endptr = NULL; number = strtoul(&child_node_name[i + 1], &endptr, 10); if (endptr == NULL || *endptr != ']' || number == 0) { return NULL; } } return sxpath_get_child_node(parent, child_node_name, i, number); } } return sxpath_get_child_node(parent, child_node_name, child_node_name_length, 1); } /** * 父节点获取 * @param[in] node 要获取父节点的节点 * @return NULL 获取失败或者此节点无父节点 * @return !NULL 获取成功 */ static inline libxml_node_t* sxpath_get_parent_node(libxml_node_t*node) { //暂不支持,直接返回NULL return NULL; } static const char* sxpath_get_next_level(const char*sxpath, uint32_t*offset, uint32_t* match_text_length) { assert(sxpath); assert(offset); assert(match_text_length); //assert(sxpath[0]=='/' || assert(sxpath[0]=='.')); //发现 . .. if (sxpath[0] == '.') { if (sxpath[1] == '/') { *offset += 2; //skip "./" return sxpath_get_next_level(&sxpath[2], offset, match_text_length); } else if (sxpath[1] == '.' && sxpath[2] == '/') { *match_text_length = 2; return &sxpath[3]; } } //发现'/' if (sxpath[0] == '/') { //maybe '.' or '..' *offset += 1; //skip '/' return sxpath_get_next_level(&sxpath[1], offset, match_text_length); } #if 0 //不需要考虑,下列代码可处理 if(sxpath[0] =='\0') { match_text_length=0; return NULL; } #endif const char* separate = strchr(sxpath, '/'); if (separate) { *match_text_length = (uint32_t) (separate - sxpath); return separate + 1; //skip '/' } *match_text_length = strlen(sxpath); return NULL; } /** * 获取符合sxpath要求的node * @param[in] node 父节点 * @param[in] sxpath sxpath语法 * @return NULL 没有找到符合要求的节点 * @return !NULL 找到符合要求的节点 */ libxml_node_t* libxml_sxpath_get_child(libxml_node_t* node, const char*sxpath) { uint32_t match_text_length; const char* current_level = sxpath; while (current_level && node) { uint32_t offset = 0; const char* next_level = sxpath_get_next_level(current_level, &offset, &match_text_length); if (!match_text_length) { assert(!next_level); break; } if (match_text_length == 2 && strncmp("..", &current_level[offset], match_text_length)) { node = sxpath_get_parent_node(node); } else { node = sxpath_get_child_node(node, &current_level[offset], match_text_length); } } return node; } /** * 获取指定node的属性值 * @param[in] node 节点 * @param[in] sxpath sxpath串 * @return NULL 没有找到符合要求的属性 * @return !NULL 返回此属性对应的字符串属性值 */ const char* libxml_sxpath_get_attribute_value(libxml_node_t*node, const char* sxpath) { const char* attribute = strrchr(sxpath, '@'); if (!attribute) { return NULL; } node = libxml_sxpath_get_child(node, sxpath); if (!node) { return NULL; } return ((TiXmlElement*) node)->Attribute(attribute); } /** * 获取指定node的内部text * @param[in] node 节点 * @param[in] sxpath sxpath串 * @return NULL node 没有inner text * @return !NULL 返回此inner text */ const char* libxml_sxpath_get_tag_inner_text(libxml_node_t*node, const char*sxpath) { node = libxml_sxpath_get_child(node, sxpath); if (!node) { return NULL; } return ((TiXmlElement*) node)->GetText(); }
true
4b6543ac2fe80318fab5bfb7f6d9fda08ed7ce88
C++
Tang1001/Airsim_Drones_TT
/Demo417/src/PathPlaningController/BEM/BEMMathUtil.hpp
UTF-8
1,050
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#pragma once #include "BEMCommon.hpp" namespace sxc { namespace bem { class BEMMathUtil{ public: template <class F> static double unitIntegrate(F f){ //return gauss<double, 4>::integrate(f, -1, 1); return 0; } static double cross(const Eigen::Vector2d& a, const Vector2d& b) { return a.x()*b.y() - b.x()*a.y(); } static bool isPointOnLine(const Vector2d& p1, const Vector2d& p2, const Vector2d& p){ return sxc::bem::almost_zero(cross(p2 - p1, p1 - p)) && sxc::bem::almost_equal((p1 - p).norm() + (p2 - p).norm(),(p1 - p2).norm()); } /* static double distLP(const Vector2d& p1, const Vector2d& p2, const Vector2d& p) { return abs(cross(p2 - p1, p1 - p)) / (p2 - p1).norm(); } static double distLPSign(const Vector2d& p1, const Vector2d& p2, const Vector2d& p) { return signbit(cross(p1 - p, p2 - p)) * distLP(p1, p2, p); } static double distLPNormalSign(const Vector2d& x, const Vector2d& y, const Vector2d& normal) { return distLPSign(y, y + Vector2d(-normal.y(), normal.x()), x); } */ }; }} //namespace
true
c0aa11ac21635d9cda38761788f192db5ca11a7a
C++
neoking123/Study
/C++/OperatorOverloading/main.cpp
UHC
2,519
3.421875
3
[]
no_license
#include <iostream> using namespace std; class Point { int x; int y; public: explicit Point(int _x = 0, int _y = 0) :x(_x), y(_y) { } int GetX() const { return x; } int GetY() const { return y; } void SetX(int _x) { x = _x; } void SetY(int _y) { y = _y; } void Print() const { cout << x << ',' << y << endl; } const Point operator+(const Point& arg) const { Point pt; pt.x = this->x + arg.x; pt.y = this->y + arg.y; return pt; } const Point operator++() // { x++; y++; return *this; } const Point operator++(int) // { } bool operator==(const Point& arg) const { return this->x == arg.x && this->y == arg.y ? true : false; } bool operator!= (const Point& arg) const { return !(*this == arg); } int operator[](int idx) const { if (idx == 0) return x; else if (idx == 1) return y; else throw "̷ ž!"; } operator int() const { return x; } }; const Point operator-(const Point& argL, const Point& argR) { return Point(argL.GetX() - argR.GetX(), argL.GetY() - argR.GetY()); } struct FuncObject { public: void operator()(int arg) const { cout << " : " << arg << endl; } }; void Print1(int arg) { cout << " : " << arg << endl; } class Array { int *arr; int size; int capacity; public: Array(int cap = 100) :arr(0), size(0), capacity(0) { arr = new int[capacity]; } ~Array() { delete[] arr; } void Add(int data) { if (size < capacity) arr[size++] = data; } int Size() const { return size; } int operator[](int idx) const { return arr[idx]; } int operator[](int idx) { return arr[idx]; } }; class PointPtr { Point *ptr; public: PointPtr(Point *p) :ptr(p) {} ~PointPtr() { delete ptr; } Point* operator->() const { return ptr; } Point& operator*() const { return *ptr; } }; class A { }; class B { public: operator A() { cout << "operator A() ȣ" << endl; return A(); } operator int() { cout << "operator int() ȣ" << endl; return 10; } operator double() { cout << "operator double() ȣ" << endl; return 5.5f; } }; class String { public: const char* sz; explicit String(const char* _sz) { sz = new char(sizeof(_sz)); } ~String() { delete sz; } operator const char*() const { return sz; } const String& operator=(const char* _sz) const { return *this; } }; int main() { String s("Hello!"); const char* sz = "Hi~!"; s = sz; return 0; }
true
4748cc4a33490c3190b629cab340ebab15cf8968
C++
hicotton02/BeverageController
/src/network_wrapper.cpp
UTF-8
2,324
2.734375
3
[ "MIT" ]
permissive
#include "network_wrapper.h" #include <HardwareSerial.h> #include <WiFi.h> #include <ArduinoOTA.h> #include "time.h" NetworkWrapper::NetworkWrapper() {} void NetworkWrapper::begin(CONFIG_T config) { Serial2.println("Setting up WiFi"); char localIp[16]; if (config.ssid && config.pass) { WiFi.mode(WIFI_STA); WiFi.begin(config.ssid, config.pass); while (WiFi.status() != WL_CONNECTED) { vTaskDelay(pdMS_TO_TICKS(500)); Serial2.print("."); } strncpy(localIp, WiFi.localIP().toString().c_str(), 16); Serial2.print("IP Address: "); Serial2.println(localIp); //Get NTP Time getNTPTime(config.timeZone); startOTA(); } } void NetworkWrapper::startOTA() { ArduinoOTA.onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) { type = "sketch"; } else { // U_SPIFFS type = "filesystem"; } // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial2.println("Start updating " + type); }); ArduinoOTA.onEnd([]() { Serial2.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial2.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial2.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) { Serial2.println("Auth Failed"); } else if (error == OTA_BEGIN_ERROR) { Serial2.println("Begin Failed"); } else if (error == OTA_CONNECT_ERROR) { Serial2.println("Connect Failed"); } else if (error == OTA_RECEIVE_ERROR) { Serial2.println("Receive Failed"); } else if (error == OTA_END_ERROR) { Serial2.println("End Failed"); } }); ArduinoOTA.begin(); Serial2.println("OTA Ready"); } void NetworkWrapper::getNTPTime(char * timeZone) { int timeZoneOffsetH = 0; int timeZoneOffsetS = 0; sscanf(timeZone, "%d", &timeZoneOffsetH); timeZoneOffsetS = timeZoneOffsetH * 60 * 60; configTime(timeZoneOffsetS, 3600, "us.pool.ntp.org"); struct tm timeinfo; if (!getLocalTime(&timeinfo)) { Serial2.println("Failed to get time"); return; } Serial2.println(&timeinfo, "%I:%M:%S"); display->setDisplayRTCTime(&timeinfo); }
true
e8bc6a24b671f155199144dff33c71e0db13f7f9
C++
kerwinzxc/AOFramework
/AOFramework/Utility/MsTime.hpp
SHIFT_JIS
2,954
3.0625
3
[]
no_license
/************************************************************* * @file MsTime.hpp * @brief MsTimeNXwb_[ * @author Tatsunori Aoyama * @date 2015/01/01 *************************************************************/ #ifndef _Include_MsTime_hpp_ // CN[hK[h #define _Include_MsTime_hpp_ //------------------------------------------------------------ // CN[h //------------------------------------------------------------ #include"BezierCurve.hpp" #include"../System/FpsController.hpp" namespace ao { /*!----------------------------------------------------------- // @class MsTime // @brief ԕԃNX // @author Tatsunori Aoyama // @date 2015/01/01 ------------------------------------------------------------*/ class MsTime { public: MsTime() : nowTime(0), maxTime(1), normalizeTime(0){}; ~MsTime(){}; /*!----------------------------------------------------------- // @brief p[^[ݒ // @param[in] _setTime ݒ^C // @param[in] _initTime [ȗ] // @author Tatsunori Aoyama // @date 2015/01/01 ------------------------------------------------------------*/ void SetParameter(float _setTime,float _initTime=0) { this->nowTime = _initTime; this->maxTime = _setTime; this->normalizeTime = this->nowTime / this->maxTime; } /*!----------------------------------------------------------- // @brief XV // @param[in] _limitDelta f^^C̐l(2.0f=30FEj // @author Tatsunori Aoyama // @date 2015/01/01 ------------------------------------------------------------*/ void Update(float _limitDelta = 0.032f) { float d = min(_limitDelta, ao::FpsController::GetInstance()->GetDeltaTime()); this->nowTime = min(this->nowTime + d, this->maxTime); this->normalizeTime = this->nowTime / this->maxTime; } /*!----------------------------------------------------------- // @brief KꂽԎ擾 // @return Kꂽԁi0~1.0fj // @author Tatsunori Aoyama // @date 2015/01/01 ------------------------------------------------------------*/ const float GetNormalizedTime() const { return this->normalizeTime; } /*!----------------------------------------------------------- // @brief Iǂ // @return TRUEFI@FALSEFIĂȂ // @author Tatsunori Aoyama // @date 2015/01/01 ------------------------------------------------------------*/ const BOOL IsEnd() const { return (this->nowTime >= this->maxTime); } /*!----------------------------------------------------------- // @brief Zbg // @author Tatsunori Aoyama // @date 2015/01/01 ------------------------------------------------------------*/ void Reset() { this->nowTime = 0; this->normalizeTime = 0; } public: float nowTime; float maxTime; float normalizeTime; }; } #endif // _Include_MsTime_hpp_
true
8f624b26a2c3877b7f2e09b10c5648e767ee7851
C++
Haxrox/ClawRetrievalSystem
/ClawRetrievalSystem.ino
UTF-8
7,546
2.5625
3
[]
no_license
// Libraries #include <NewPing.h> // include the NewPing library for this program #include <Servo.h> // Constants // // States #define CALIBRATE 0 #define GROUNDED 1 #define SENSE 2 #define GRABBED 3 #define RELEASE 4 // Symbolic constants // #define TRUE 1 #define FALSE 0 // Modes #define SONAR 0 #define JOYSTICK 1 // Sonar #define OPEN 0 // open position of servo #define CLOSED 180 // close position of servo #define HEIGHT 25 // - legit height #define GRAB_DELAY 1000 // length to wait after grabbing an object before attempting to release the object #define RELEASE_DELAY 1000 // length to wait after releasing an object before attempting to grab another object #define GRAB_THRESHOLD 9 // distance on the sonar sensor to close the claw #define RELEASE_THRESHOLD 10 // distance on the sonar sensor to open the claw #define DISTANCES_SIZE 10 // number of distances to measure to prevent outliers // Joystick #define JOYSTICK_DELAY 1000 // Blink #define BLINK_DELAY 500 // Components // // Sonar #define VCC_PIN 12 // 13 - Original // sonar vcc pin attached to pin 13 #define TRIGGER_PIN 11 // 12 - Original // sonar trigger pin will be attached to Arduino pin 12 #define ECHO_PIN 10 // 11 - Original // sonar echo pint will be attached to Arduino pin 11 #define GROUND_PIN 9 // 10 - Original // sonar ground pin attached to pin 10 #define MAX_DISTANCE 200 // fmaximum distance set to 200 cm // Joystick #define GROUND_JOY_PIN A3 // joystick ground pin will connect to Arduino analog pin A3 #define VOUT_JOY_PIN A2 // joystick +5 V pin will connect to Arduino analog pin A2 #define XJOY_PIN A1 // X axis reading from joystick will go into analog pin A1 // Servo #define SERVO_PIN 8 // Variables // int mode = SONAR; int state = CALIBRATE; unsigned long target = 0; int distances[DISTANCES_SIZE] = {0}; int calibrateCount = 0; // Sonar NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // initialize NewPing // Servo Servo myservo; // create servo object to control a servo // Blink int blinkLED = FALSE; int blinkCount = 0; unsigned long blinkTarget = 0; // Functions // // printArray void printArray(int* data, int arraySize) { Serial.print("["); for (int index = 0; index < arraySize - 1; index ++) { Serial.print(data[index]); Serial.print(", "); } Serial.print(data[arraySize-1]); Serial.println("]"); } // Push into distances array int push(int value) { int average = value; for (int index = 1; index < DISTANCES_SIZE; index ++) { average += distances[index]; distances[index - 1] = distances[index]; } distances[DISTANCES_SIZE - 1] = value; // printArray(distances, DISTANCES_SIZE); return average / DISTANCES_SIZE; } // Sonar sensor void sonarSensor() { unsigned long currentTime = millis(); int distance = push(sonar.ping_cm()); /* Serial.print("State - "); Serial.print(state); Serial.print(" | Distance - "); Serial.print(distance); Serial.print(" | Current Time - "); Serial.print(currentTime); Serial.print(" | Target - "); Serial.println(target); */ if (currentTime >= target) { switch (state) { case CALIBRATE: calibrateCount++; if (calibrateCount >= DISTANCES_SIZE) { Serial.println("Calibration complete"); if (distance >= HEIGHT) { state = SENSE; } else { state = GROUNDED; } for (int index = 0; index < 6; index ++) { if (index % 2 == 0) { digitalWrite(LED_BUILTIN, HIGH); } else { digitalWrite(LED_BUILTIN, LOW); } delay(BLINK_DELAY / 5); } } break; case GROUNDED: blinkLED = FALSE; if (distance >= HEIGHT) { Serial.println("Sensing ..."); state = SENSE; } break; case SENSE: blinkLED = TRUE; if (distance <= GRAB_THRESHOLD) { Serial.println("Grabbing object"); blinkLED = FALSE; digitalWrite(LED_BUILTIN, LOW); state = GRABBED; delay(500); myservo.write(CLOSED); target = currentTime + GRAB_DELAY; } break; case GRABBED: blinkLED = FALSE; if (distance >= HEIGHT) { Serial.println("Object lifted"); digitalWrite(LED_BUILTIN, HIGH); state = RELEASE; } break; case RELEASE: blinkLED = FALSE; if (distance <= RELEASE_THRESHOLD) { Serial.println("Releasing object"); digitalWrite(LED_BUILTIN, LOW); state = GROUNDED; myservo.write(OPEN); target = currentTime + RELEASE_DELAY; } break; } } } // Joystick void joystick() { unsigned long currentTime = millis(); if (currentTime >= target) { int joystickXVal = analogRead(XJOY_PIN) ; //read joystick input on pin A1. Will return a value between 0 and 1023. if (joystickXVal > 1000) { Serial.println("Closing claw"); digitalWrite(LED_BUILTIN, LOW); myservo.write(CLOSED); target = currentTime + JOYSTICK_DELAY; } else if (joystickXVal < 100) { Serial.println("Opening claw"); digitalWrite(LED_BUILTIN, HIGH); myservo.write(OPEN); target = currentTime + JOYSTICK_DELAY; } // int servoVal = map(joystickXVal, 0, 1023, 0, 180) ; //changes the value to a raneg of 0 to 180. See "map" function for further details. // myservo.write(servoVal); } } // Blink void blink() { unsigned long currentTime = millis(); if (currentTime >= blinkTarget) { blinkCount ++; if (blinkCount % 2 == 0) { digitalWrite(LED_BUILTIN, HIGH); } else { digitalWrite(LED_BUILTIN, LOW); } blinkTarget += BLINK_DELAY; } } // Setup void setup() { Serial.begin(9600); // set data transmission rate to communicate with computer Serial.print("Initializing mode - "); // LED pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); switch(mode) { case SONAR: Serial.println("Sonar"); // Sonar pinMode(ECHO_PIN, INPUT) ; pinMode(TRIGGER_PIN, OUTPUT) ; pinMode(GROUND_PIN, OUTPUT); // tell pin 10 it is going to be an output pinMode(VCC_PIN, OUTPUT); // tell pin 13 it is going to be an output digitalWrite(GROUND_PIN,LOW); // tell pin 10 to output LOW (OV, or ground) digitalWrite(VCC_PIN, HIGH) ; // tell pin 13 to output HIGH (+5V) break; case JOYSTICK: Serial.println("Joystick"); // Joystick pinMode(VOUT_JOY_PIN, OUTPUT); //pin A3 shall be used as output pinMode(GROUND_JOY_PIN, OUTPUT) ; //pin A2 shall be used as output digitalWrite(VOUT_JOY_PIN, HIGH) ; //set pin A3 to high (+5) digitalWrite(GROUND_JOY_PIN,LOW) ; //set pin Ad to low (ground) break; } // Servo myservo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object myservo.write(OPEN); Serial.println("Claw Retrival System setup complete."); } // Loop void loop() { switch(mode) { case SONAR: sonarSensor(); break; case JOYSTICK: joystick(); break; } if (blinkLED) { blink(); } }
true
59ac74ece197d180049574a84c465dee17c161db
C++
tombom66/Computer-science
/labex04-tombom66/prob02/test/unittest.cpp
UTF-8
3,038
3.140625
3
[ "MIT" ]
permissive
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "gtest_ext.h" TEST(TuffyPrinter, OutputFormat) { std::string unittest_output = "Welcome to Tuffy Printing services.\n" "How many pages do you need printed? " "Select a printing quality from the list:\n" " D - draft, $0.10 per page\n" " M - medium quality, $0.15 per page\n" " H - high quality, $0.20 per page\n" "Quality: Total cost: $9.00\n"; ASSERT_EXECIO_EQ("main", "45 h", unittest_output); } TEST(TuffyPrinter, ValidQuality) { srand (time(NULL)); for(int i = 0; i < 10; i++) { int num_pages = rand() % 5000 + 1; char quality_types[6] = {'D', 'd', 'M', 'm', 'H', 'h'}; char quality = quality_types[rand() %6]; double cost = 0; std::string input = std::to_string(num_pages) + " " + std::string(1, quality); switch(quality) { case 'd': case 'D': cost = num_pages * 0.10; break; case 'm': case 'M': cost = num_pages * 0.15; break; case 'h': case 'H': cost = num_pages * 0.20; break; } std::string unittest_output = "Welcome to Tuffy Printing services.\n" "How many pages do you need printed? " "Select a printing quality from the list:\n" " D - draft, $0.10 per page\n" " M - medium quality, $0.15 per page\n" " H - high quality, $0.20 per page\n" "Quality: "; unittest_output += "Total cost: $" + to_string_double(cost) + "\n"; ASSERT_EXECIO_EQ("main", input, unittest_output); } } TEST(TuffyPrinter, InValidQuality) { srand (time(NULL)); for(int i = 0; i < 10; i++) { int num_pages = rand() % 100 + 1; char quality; // Ensure special characters that need escaping are not used. do { quality = (char)(rand()%93+33); } while (quality == 34 || quality == 92 || quality == 96 || quality == 68 || quality == 100 || quality == 77 || quality == 109 || quality == 72 || quality == 104); std::string input = std::to_string(num_pages) + " " + std::string(1, quality); std::string unittest_output = "Welcome to Tuffy Printing services.\n" "How many pages do you need printed? " "Select a printing quality from the list:\n" " D - draft, $0.10 per page\n" " M - medium quality, $0.15 per page\n" " H - high quality, $0.20 per page\n" "Quality: "; unittest_output += "Invalid quality. Please try again.\n"; ASSERT_EXECIO_EQ("main", input, unittest_output); } } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
799cde887973495b460c32e7afaaae0eb1597905
C++
prem-pratap/C-Programs-DSA
/circular_queue.cpp
UTF-8
1,333
3.796875
4
[]
no_license
//CIRCULAR QUEUE #include<stdio.h> #include<stdlib.h> typedef struct node{ int data; struct node *next; }node; node *last; void enqueue(); void dequeue(); void display(); int main(){ int ch; while(1){ printf("\nEnter your choice\n1.Enqueue\n2.Dequeue\n3.Display"); scanf("%d",&ch); switch(ch){ case 1: enqueue(); break; case 2: dequeue(); break; case 3: display(); break; default: exit(0); } } scanf("%d"); return 0; } void enqueue(){ node *temp; temp=(node *)malloc(sizeof(node)); if(temp==NULL) printf("\nOVERFLOW"); else{ printf("\nEnter new element:"); scanf("%d",&temp->data); temp->next=NULL; if(last==NULL){ last=temp; last->next=last; } else{ temp->next=last->next; last->next=temp; last=temp; } } } void dequeue(){ node *temp; if(last==NULL) printf("\nUNDERFLOW"); else{ temp=last->next; if(temp==last){ free(temp); last=NULL; temp=NULL; } else{ last->next=temp->next; free(temp); } } } void display(){ node *temp; if(last==NULL) printf("\nUNDERFLOW"); else{ temp=last->next; printf("\nData is:"); do{ printf("%d ",temp->data); temp=temp->next; }while(temp!=last->next); } }
true
2dfa2114b0b7468902c0ab1d62d3662a8b2c0538
C++
bog2k3/bugs
/bugs/entities/WorldConst.h
UTF-8
1,326
2.546875
3
[]
no_license
/* * WorldConst.h * * Created on: Jan 20, 2015 * Author: bog */ #ifndef OBJECTS_WORLDCONST_H_ #define OBJECTS_WORLDCONST_H_ #include "../math/constants.h" #include <glm/vec2.hpp> class WorldConst { public: static constexpr float FoodChunkDensity = 7.f; // [kg/m^2] static constexpr float FoodChunkDensityInv = 1.f/FoodChunkDensity; // [m^2/kg] static constexpr float FoodChunkDecaySpeed = 1.5e-3f; // [kg/s] how much mass it loses in a second static constexpr float FoodChunkSensorRatio = 1.5f; // [*] static constexpr float FoodDispenserPeriod = 2.f; // [s] static constexpr float FoodDispenserSize = PI*0.625e-1f; // [m^2] static constexpr float FoodDispenserSpawnVelocity = 0.3f; // [m/s] static constexpr float FoodDispenserSpawnMass = 60.e-3f; // [kg] static constexpr float FoodDispenserSpreadAngleHalf = PI; // [rad] static constexpr float GameteAttractRadius = 10; // [m] static constexpr float GameteAttractForceFactor = 30; // force between 2 1kg gametes [N] static constexpr unsigned MaxGenomeLengthDifference = 10; // max length difference that is still compatible static constexpr float BodyDecaySpeed = 2.e-3f; // [kg/s] speed at which mass is lost from dead bodies }; #endif /* OBJECTS_WORLDCONST_H_ */
true
4c8d282cfe51098970c050aa4e8033a48ac65ec0
C++
Tahsib/Codeforces-Solves
/1005-A.cpp
UTF-8
432
2.5625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define MAX 1000 int main() { vector<int>v; int n,a[MAX]; cin>>n; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } for(int i=0;i<n-1;i++) { if(a[i+1]==1) { v.push_back(a[i]); } } v.push_back(a[n-1]); cout<<v.size()<<endl; for(auto it=v.begin();it!=v.end();it++) { cout<<*it<<" "; } }
true
1081db087f860d43e9a8f163ffe24e764e617494
C++
dwmkFD/AtCoderSubmit
/ProconLibrary/UnionFind.cpp
UTF-8
566
2.671875
3
[]
no_license
template<typename T = ll> struct UnionFind { vector<T> par; UnionFind( T n ) : par( n, -1 ) {} void init( T n ) { par.assign( n, -1 ); } T find( T x ) { if ( par[x] < 0 ) return ( x ); else return ( par[x] = find( par[x] ) ); } bool isSame( T x, T y ) { return ( find( x ) == find( y ) ); } bool unite( T x, T y ) { x = find( x ); y = find( y ); if ( x == y ) return ( false ); if ( par[x] > par[y] ) swap( x, y ); par[x] += par[y]; par[y] = x; return ( true ); } T size( T x ) { return ( -par[find( x )] ); } };
true
5225126d9d442507efb127d97038138dca2910eb
C++
SaumilShah66/ENPM808X-PID
/test/test.cpp
UTF-8
2,180
3.09375
3
[]
no_license
// Copyright 2019 Saumil Shah and Shantam Bajpai /** * * @file test.cpp * @brief Test source file for PID controller. * Contains the required headers and methods. * @author Saumil Shah (Driver) and Shantam Bajpai (Navigator) * @date 26th September 2019 * @version 1.0 * */ #include <gtest/gtest.h> #include <PIDControl.hpp> // Class instance is created here which will be used for the test PIDControl PID(0.1, 0.1, 0.1, 0.1); double val = 1.1; /** * @brief Test for setKp() function of the PidControl class. * It checks whether the values set by the user and the values obtained by * getKp() function are same or not. */ TEST(checkGetterSetter, checkKp) { PID.setKp(val); EXPECT_EQ(PID.getKp(), val); } /** * @brief Test for setKd() function of the PidControl class. * It checks whether the values set by the user and the values obtained by * getKd() function are same or not. */ TEST(checkGetterSetter, checkKd) { PID.setKd(val); EXPECT_EQ(PID.getKd(), val); } /** * @brief Test for setKi() function of the PidControl class. * It checks whether the values set by the user and the values obtained by * getKi() function are same or not. */ TEST(checkGetterSetter, checkKi) { PID.setKi(val); EXPECT_EQ(PID.getKi(), val); } /** * @brief Test for setDt() function of the PidControl class. * It checks whether the values set by the user and the values obtained by * getDt() function are same or not. */ TEST(checkGetterSetter, checkDi) { PID.setDt(val); EXPECT_EQ(PID.getDt(), val); } /** * @brief Test for computeNewVelocity() function of the PidControl class. * It verifies that the new velocity computed by the function matches * expected values or not. */ TEST(checkComputeVelocity, checkValues) { PID.setKi(1); PID.setKp(1); PID.setKd(1); PID.setDt(1); EXPECT_EQ(PID.computeNewVelocity(1, 0), 3.0); EXPECT_EQ(PID.computeNewVelocity(1, 3), -6.0); } /** * @brief Test for calculateError() function of the PidControl class. * It verifies that the computed error between set velocity and current * velocity is correct or not. */ TEST(checkCalculateError, checkErrorValues) { EXPECT_EQ(PID.calculateError(1, 0), 1.0); }
true
06100deb785baa507c66c4fc89bd112ec78e5f7f
C++
xuchong/LeetCode
/ValidPalindrome/main.cpp
UTF-8
1,260
3.25
3
[]
no_license
#include<iostream> #include<cstring> #include<string> using namespace std; class Solution { private: bool isNumberOrChr(char a) { if((a>='0'&&a<='9')||(a>='a'&&a<='z')||(a>='A'&&a<='Z')) { return true; } return false; } int isNumber(char a) { if((a>='0'&&a<='9')) { return a-'0'; } return -1; } int isChar(char a) { if((a>='a'&&a<='z')) { return a-'a'; }else if(a>='A'&&a<='Z') { return a-'A'; } return -1; } public: bool isPalindrome(string s) { if(s.length()==0) return true; int start,end; start=0; end=s.length()-1; while(start<end) { if(!isNumberOrChr(s[start])) { start++; continue; } if(!isNumberOrChr(s[end])) { end--; continue; } if((isNumber(s[start])!=-1&&isNumber(s[end])!=-1&&isNumber(s[start])==isNumber(s[end]))||(isChar(s[start])!=-1&&isChar(s[end])!=-1&&isChar(s[start])==isChar(s[end]))) { start++; end--; }else{ return false; } } return true; } }; int main() { return 0; }
true
291a647cce8854b522361f136c7f8d5d31bee179
C++
qgzang/DNest4
/code/Examples/RJObject_SineWaves/MyConditionalPrior.cpp
UTF-8
1,337
2.734375
3
[ "MIT" ]
permissive
#include "MyConditionalPrior.h" #include "DNest4/code/DNest4.h" #include <cmath> using namespace DNest4; MyConditionalPrior::MyConditionalPrior(double x_min, double x_max, double mu_min, double mu_max) :x_min(x_min) ,x_max(x_max) ,mu_min(mu_min) ,mu_max(mu_max) { } void MyConditionalPrior::from_prior(RNG& rng) { mu = exp(log(mu_min) + log(mu_max/mu_min)*rng.rand()); } double MyConditionalPrior::perturb_hyperparameters(RNG& rng) { double logH = 0.; mu = log(mu); mu += log(mu_max/mu_min)*rng.randh(); mu = mod(mu - log(mu_min), log(mu_max/mu_min)) + log(mu_min); mu = exp(mu); return logH; } // vec[0] = "position" (log-period) // vec[1] = amplitude // vec[2] = phase double MyConditionalPrior::log_pdf(const std::vector<double>& vec) const { if(vec[0] < x_min || vec[0] > x_max || vec[1] < 0. || vec[2] < 0. || vec[2] > 2.*M_PI) return -1E300; return -log(mu) - vec[1]/mu; } void MyConditionalPrior::from_uniform(std::vector<double>& vec) const { vec[0] = x_min + (x_max - x_min)*vec[0]; vec[1] = -mu*log(1. - vec[1]); vec[2] = 2.*M_PI*vec[2]; } void MyConditionalPrior::to_uniform(std::vector<double>& vec) const { vec[0] = (vec[0] - x_min)/(x_max - x_min); vec[1] = 1. - exp(-vec[1]/mu); vec[2] = vec[2]/(2.*M_PI); } void MyConditionalPrior::print(std::ostream& out) const { out<<mu<<' '; }
true
b3070a9e4fa4a1b4afc3eb6f8cdd99c2a4ea5d9b
C++
The-Team-7/The-KU-Journey
/Game/StateMachine.h
UTF-8
566
2.65625
3
[]
no_license
#pragma once #include<memory> #include<stack> #include "State.h" namespace sg { typedef std::unique_ptr<State> StateRef; ////// STATE MACHINE CLASS STORES AND MANAGES THE STATES USED IN THE GAME ///// ////// IT HELPS IN TRANSITION BEWTEEN DIFFERENT STATES ///// class StateMachine { public: void AddState(StateRef newState, bool isReplaing); void RemoveState(); StateRef& GetActiveState(); void ProcessStateChanges(); private: std::stack<StateRef> _state; StateRef newState; bool isReplacing; bool isAdding; bool isRemoving; }; }
true
8b1c42a3da4a6979bca0dc1fb53350716d956ad0
C++
237K/ProblemSolving
/SAMSUNG_SWEA#6959_ver2.cpp
UHC
3,790
3.5
4
[]
no_license
// // OS Windows // 2019.02.18 // // [Algorithm Problem Solving] // // SAMSUNG SW Expert Academy [#6959] <̻ > (D4) // // ( Ǯ ) // 1. 1ڸ ̸ B ¸ // 2. ־ ¦ ڸ ڵ 10̸̸ A ¸, 10̸̻ B ¸, 19̸̻ A ¸, 28̸̻ ٽ B ¸...... // 3. ־ Ȧ ڸ ڵ 10̸̸ B ¸, 10̸̻ A ¸, 19̸̻ B ¸, 28̸̻ ٽ A ¸...... // Answer) 5678 , // 1) ־ Ʈ( 10 == Count 0 ) ڸ (5678 ڰ ¦ ̹Ƿ Ʈ ڴ A) // 2) ڸ ڵ ( : 26) // 3) 10 ŭ ڰ ٲ ( : 2, A -> B -> A̹Ƿ A) // 4) 10 ̶ ( : 8) // 5) 10 ŭ ڰ ٲ ( : 0, ״ A) // 6) 10 10 ũ 10 ݺ // // // (*ֿ 帧) // 1. 1000 оͼ char迭 (getline ϴ ä ڲ ϳ оͼ scanf ) // 2. ڰ  Ȯ // 3. char迭 ڸ ϳ int ȯؼ Ͽ Sum // 4. Sum Լ(DFS Լ) ǵ, ¦̸ cnt 0 ؼ , Ȧ̸ 1 ؼ // 5. Sum 10 ŭ cnt // 6. Sum ڸ (Accumulate Լ) // 7. Sum ڸ Ѱ 10 cnt // 8. 10̸̻ ٽ DFS // 9. 10 ŭ cnt ϰ.. ٽ ڸ ؼ 10 ϰ 10̸̻ ݺ... // #define _CRT_SECURE_NO_WARNINGS #include <cstdio> using namespace std; int Accumulate(int Num) // ڸ ڸ ϴ Լ { int Temp = 0; int Quotient = 0, Remainder = 0; while (1) { Quotient = Num / 10; Remainder = Num % 10; Temp += Remainder; Num /= 10; if (Num == 0) break; } return Temp; } void DFS(int Num, int cnt) { int Acc = 0; cnt += Num / 10; Acc = Accumulate(Num); if (Acc < 10) { if (cnt % 2 == 0) printf("A\n"); else printf("B\n"); return; } else if (Acc >= 10) { DFS(Acc, cnt); } } int StoI(char ch) { switch (ch) { case 48: return 0; break; case 49: return 1; break; case 50: return 2; break; case 51: return 3; break; case 52: return 4; break; case 53: return 5; break; case 54: return 6; break; case 55: return 7; break; case 56: return 8; break; case 57: return 9; break; default: return -1; break; } } int main(int argc, char** argv) { int Sum; int Length; int test_case; int T; char Input[1001]; freopen("s_input6959.txt", "r", stdin); scanf("%d", &T); for (test_case = 1; test_case <= T; ++test_case) { for (int init = 0; init < 1001; ++init) Input[init] = NULL; Length = 0; Sum = 0; scanf("%1000s", &Input); while (Input[Length] != NULL) { Sum += StoI(Input[Length]); Length++; } printf("#%d ", test_case); if (Length == 1) printf("B\n"); else if (Length % 2 == 0) //־ ¦̸ { DFS(Sum, 0); } else { //־ Ȧ̸ DFS(Sum, 1); } } return 0; }
true
5be2ef7b674499ad4090fce2cce092f784d33c16
C++
chenzhengchen200821109/simple-log
/slog/logging.h
UTF-8
4,958
2.859375
3
[]
no_license
#ifndef LOGGING_H #define LOGGING_H #include <string> enum LogLevel { LOGLEVEL_INFO = 0, // Informational. This is never actually used by libprotobuf. LOGLEVEL_WARNING, // Warns about issues that, although not technically a // problem now, could cause problems in the future. For // example, a warning will be printed when parsing a // message that is near the message size limit. LOGLEVEL_ERROR, // An error occurred which should never happen during // normal use. LOGLEVEL_FATAL, // An error occurred from which the library cannot // recover. This usually indicates a programming error // in the code which calls the library, especially when // compiled in debug mode. }; //class StringPiece; namespace internal { class StringPiece; class LogFinisher; class LogMessage { public: LogMessage(LogLevel level, const char* filename, int line); ~LogMessage(); LogMessage& operator<<(const std::string& value); LogMessage& operator<<(const char* value); LogMessage& operator<<(char value); LogMessage& operator<<(int value); LogMessage& operator<<(unsigned int value); LogMessage& operator<<(long value); LogMessage& operator<<(unsigned long value); LogMessage& operator<<(long long value); LogMessage& operator<<(unsigned long long value); LogMessage& operator<<(double value); LogMessage& operator<<(void* value); LogMessage& operator<<(const StringPiece& value); private: friend class LogFinisher; void Finish(); LogLevel level_; const char* filename_; int line_; std::string message_; }; // Used to make the entire "LOG(BLAH) << etc." expression have a void return // type and print a newline after each message. class LogFinisher { public: void operator=(LogMessage& other); }; } // namespace internal #define SLOG(LEVEL) \ internal::LogFinisher() = \ internal::LogMessage( \ LOGLEVEL_##LEVEL, __FILE__, __LINE__) #define SLOG_IF(LEVEL, CONDITION) \ !(CONDITION) ? (void)0 : SLOG(LEVEL) #define SLOG_CHECK(EXPRESSION) \ SLOG_IF(FATAL, !(EXPRESSION)) << "CHECK failed: " #EXPRESSION ": " #define SLOG_CHECK_EQ(A, B) SLOG_CHECK((A) == (B)) #define SLOG_CHECK_NE(A, B) SLOG_CHECK((A) != (B)) #define SLOG_CHECK_LT(A, B) SLOG_CHECK((A) < (B)) #define SLOG_CHECK_LE(A, B) SLOG_CHECK((A) <= (B)) #define SLOG_CHECK_GT(A, B) SLOG_CHECK((A) > (B)) #define SLOG_CHECK_GE(A, B) SLOG_CHECK((A) >= (B)) namespace internal { template<typename T> T* CheckNotNull(const char* /* file */, int /* line */, const char* name, T* val) { if (val == NULL) { SLOG(FATAL) << name; } return val; } } // namespace internal #define SLOG_CHECK_NOTNULL(A) \ internal::CheckNotNull( \ __FILE__, __LINE__, "'" #A "' must not be NULL", (A)) typedef void LogHandler(LogLevel level, const char* filename, int line, const std::string& message); // The protobuf library sometimes writes warning and error messages to // stderr. These messages are primarily useful for developers, but may // also help end users figure out a problem. If you would prefer that // these messages be sent somewhere other than stderr, call SetLogHandler() // to set your own handler. This returns the old handler. Set the handler // to NULL to ignore log messages (but see also LogSilencer, below). // // Obviously, SetLogHandler is not thread-safe. You should only call it // at initialization time, and probably not from library code. If you // simply want to suppress log messages temporarily (e.g. because you // have some code that tends to trigger them frequently and you know // the warnings are not important to you), use the LogSilencer class // below. LogHandler* SetLogHandler(LogHandler* new_func); // Create a LogSilencer if you want to temporarily suppress all log // messages. As long as any LogSilencer objects exist, non-fatal // log messages will be discarded (the current LogHandler will *not* // be called). Constructing a LogSilencer is thread-safe. You may // accidentally suppress log messages occurring in another thread, but // since messages are generally for debugging purposes only, this isn't // a big deal. If you want to intercept log messages, use SetLogHandler(). //namespace internal //{ // class LogSilencer // { // public: // LogSilencer(); // ~LogSilencer(); // }; //} #endif // LOGGING_H
true
8bd456d84f478be12abd831405e5d4c2da69663a
C++
hoklavat/beginner-algorithms
/MORE/Greedy(HuffmanCoding).cpp
UTF-8
3,940
3.703125
4
[]
no_license
//Greedy(HuffmanCoding) //Task: generate huffman codes for given array of unique characters where each character has specific frequency of occurence. //each binary code is unique for single character and may be of variable length. //bitstream code should only be expressed in one single combination of characters. //Reference: greedy, prefix code, huffman coding, huffman tree, heap, priority queue, bitstream. //Time Complexity: O(nlogn). n number of characters. #include <iostream> using namespace std; #define MAX_TREE_HT 100 //maximum tree height. struct MinHeapNode{ char data; unsigned freq; MinHeapNode *left; MinHeapNode *right; }; struct MinHeap{ unsigned size; unsigned capacity; MinHeapNode** arr; }; MinHeapNode* newNode(char data, unsigned freq){ MinHeapNode* temp = (MinHeapNode*)malloc(sizeof(MinHeapNode)); temp->left = NULL; temp->right = NULL; temp->data = data; temp->freq = freq; return temp; } MinHeap* createMinHeap(unsigned capacity){ MinHeap* minHeap = (MinHeap*)malloc(sizeof(MinHeap)); minHeap->size = 0; minHeap->capacity = capacity; minHeap->arr = (MinHeapNode**)malloc(minHeap->capacity * sizeof(MinHeapNode*)); return minHeap; } void swapMinHeapNode(MinHeapNode** a, MinHeapNode** b){ MinHeapNode* t = *a; *a = *b; *b = t; } void minHeapify(MinHeap* minHeap, int idx){ int smallest = idx; int left = 2*idx + 1; int right = 2*idx + 2; if(left < minHeap->size && minHeap->arr[left]->freq < minHeap->arr[smallest]->freq) smallest = left; if(right < minHeap->size && minHeap->arr[right]->freq < minHeap->arr[smallest]->freq) smallest = right; if(smallest != idx){ swapMinHeapNode(&minHeap->arr[smallest], &minHeap->arr[idx]); minHeapify(minHeap, smallest); } } int isSizeOne(MinHeap* minHeap){ return(minHeap->size == 1); } MinHeapNode* extractMin(MinHeap* minHeap){ MinHeapNode* temp = minHeap->arr[0]; minHeap->arr[0] = minHeap->arr[minHeap->size - 1]; --minHeap->size; minHeapify(minHeap, 0); return temp; } void insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode){ ++minHeap->size; int i = minHeap->size - 1; while(i && minHeapNode->freq < minHeap->arr[(i-1)/2]->freq){ minHeap->arr[i] = minHeap->arr[(i-1)/2]; i =(i - 1) / 2; } minHeap->arr[i] = minHeapNode; } void buildMinHeap(struct MinHeap* minHeap){ int n = minHeap->size - 1; int i; for(i =(n - 1) / 2; i >= 0; --i) minHeapify(minHeap, i); } void printArr(int arr[], int n){ int i; for(i = 0; i < n; ++i) cout << arr[i]; cout << endl; } int isLeaf(MinHeapNode* root){ return !(root->left) && !(root->right); } struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size){ MinHeap* minHeap = createMinHeap(size); for(int i = 0; i < size; ++i) minHeap->arr[i] = newNode(data[i], freq[i]); minHeap->size = size; buildMinHeap(minHeap); return minHeap; } struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size){ MinHeapNode *left, *right, *top; MinHeap* minHeap = createAndBuildMinHeap(data, freq, size); while(!isSizeOne(minHeap)){ left = extractMin(minHeap); right = extractMin(minHeap); top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; insertMinHeap(minHeap, top); } return extractMin(minHeap); } void printCodes(struct MinHeapNode* root, int arr[], int top){ if(root->left){ arr[top] = 0; printCodes(root->left, arr, top + 1); } if(root->right){ arr[top] = 1; printCodes(root->right, arr, top + 1); } if(isLeaf(root)){ std::cout << root->data << ": "; printArr(arr, top); } } void HuffmanCodes(char data[], int freq[], int size){ struct MinHeapNode* root = buildHuffmanTree(data, freq, size); int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top); } int main(){ char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; int freq[] = {5, 9, 12, 13, 16, 45}; int size = sizeof(arr)/sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0; }
true
93fdd633b7e05663fde119154133bda7807e6f96
C++
laru1288/LostLight
/Lampara.cpp
UTF-8
685
2.59375
3
[]
no_license
#include "Lampara.h" Lampara::Lampara(){ _textura.loadFromFile("imagenes/Lamparita/Lamparita_triste.png"); _lampara.setTexture(_textura); set_position(1 + rand() % 6); } sf::Sprite& Lampara::get_draw_Lampara() { return _lampara; } void Lampara::update() { } void Lampara::set_position(int num) { switch (num) { case 1:_lampara.setPosition(780, 500); break; case 2:_lampara.setPosition(0, 100); break; case 3:_lampara.setPosition(430, 400); break; case 4:_lampara.setPosition(430, 100); break; case 5:_lampara.setPosition(0, 500); break; case 6:_lampara.setPosition(780, 50); break; } } void Lampara::cmd() { }
true
e07dd4d076181121db66cb8dada87e4bb790bb92
C++
dwikiriswanda/eS-Teh-Dek
/TP/TP 5/circulardll-first/circulardll-first.h
UTF-8
926
2.6875
3
[]
no_license
#ifndef CIRCULARDLL-FIRST_H_INCLUDED #define CIRCULARDLL-FIRST_H_INCLUDED #include <iostream> #define first(L) L.first #define prev(P) P->prev #define info(P) P->info #define next(P) P->next /* Name : Muhamad Dwiki Riswanda NIM : 1302194015 */ using namespace std; typedef char infotype; typedef struct elmList *address; struct elmList { infotype info; address prev; address next; }; struct list { address first; }; bool isEmpty(list L); //1 void createList(list &L); //2 void createNewElmt(address &P, infotype X); //3 void insertFirst(list &L, address P); // 4 void insertAfter(list &L, address &P, address Prec); //5 void deleteFirst(list &L, address &P); //6 void deleteAfter(list &L, address &P, address Prec); //7 int countWord(char data[], list L); //8 void printInfo(list L); //9 void insertLast(list &L, address P); //10 address cariElmt(list L, infotype X); //11 #endif // CIRCULARDLL-FIRST_H_INCLUDED
true
518f45e04e17ecc3576e80278241d1e05ff07737
C++
juhyun-nam/expression-inserter
/include/expression_inserter/value_type.h
UTF-8
606
3.171875
3
[ "MIT" ]
permissive
/// \file value_type.h /// \brief value expression을 담는 구조체 정의 /// \author juhyun-nam /// #ifndef EXPRESSION_INSERTER_VALUE_TYPE_H_ #define EXPRESSION_INSERTER_VALUE_TYPE_H_ #include <functional> namespace detail { /// LEVEL과 int의 arithmetic operation 동작을 담는 구조체 class Value { public: Value() { expr_ = [](int v) { return v; }; } explicit Value(std::function<int(int)> fn) : expr_(fn) {} int operator()(int v) const { return expr_(v); } private: std::function<int(int)> expr_; }; } // namespace detail #endif // EXPRESSION_INSERTER_VALUE_TYPE_H_
true
0e91b258d7af1e8b023ca7143f6ed7777a315295
C++
taketakeyyy/atcoder
/abc/065/a.cpp
UTF-8
290
3.015625
3
[]
no_license
#include <iostream> using namespace std; int main(void){ int X, A, B; cin >> X >> A >> B; // implements if(B <= A){ printf("delicious\n"); } else if(B > (A+X)){ printf("dangerous\n"); } else{ printf("safe\n"); } return 0; }
true
694e578028e2aa728d656ee283fb5dd172fc13b3
C++
Ricardo-py/learn_opencv-for-C
/直方图.cpp
UTF-8
4,715
2.671875
3
[]
no_license
#include<opencv2/imgproc/imgproc.hpp> #include<opencv2/highgui/highgui.hpp> #include<iostream> #define INPUT_TITLE "input image" #define OUTPUT_TITLE "直方图计算" using namespace cv; using namespace std; int main() { Mat srcImage = imread("C:/Users/Richard/Desktop/timg.jpg"); if (srcImage.empty()) { cout << "图像加载失败" << endl; return -1; } //imshow("原始图像", srcImage); Mat hsvImage; cvtColor(srcImage, hsvImage, CV_BGR2HSV_FULL); //imshow("hsv色彩图像", hsvImage); //测试:得到BGR某个通道的图像 vector<Mat> mv; split(srcImage, mv); mv[0] = Scalar(0); //蓝色通道为0 mv[1] = Scalar(0); //绿色通道为0 Mat bgr_planes[3]; merge(mv, bgr_planes[2]); //得到红色通道的图像 split(srcImage, mv); mv[0] = Scalar(0); mv[2] = Scalar(0); merge(mv, bgr_planes[1]); split(srcImage, mv); mv[2] = Scalar(0); mv[1] = Scalar(0); merge(mv, bgr_planes[0]); imshow("1", bgr_planes[0]); imshow("2", bgr_planes[1]); imshow("3", bgr_planes[2]); Mat planes0 = bgr_planes[0]; Mat planes1 = bgr_planes[1]; Mat planes2 = bgr_planes[2]; //测试:得到HSV某个通道的图像 /*split(hsvImage, mv); Mat H = mv.at(0); Mat S = mv.at(1); Mat V = mv.at(2); imshow("outputH", H); imshow("outputS", S); imshow("outputV", V);*/ /*Mat srcimg = imread("C:/Users/Richard/Desktop/timg.jpg"); Mat Hsvimg; cvtColor(srcimg, Hsvimg, COLOR_BGR2HSV); int huebinnum = 30;//色调量化 int saturationbinnum = 32; //饱和度量化 int histsize[] = { huebinnum,saturationbinnum }; float hueRange[] = { 0,180 };//色调的变化范围 float saturationRange[] = { 0,256 };//饱和度的变化范围 const float* ranges[] = { hueRange,saturationRange }; MatND dstHist; //MatND 储存直方图的一种数据结构 int channels[] = { 0,1 };//计算第0,1通道的直方图 calcHist(&Hsvimg, 1, channels, Mat(), dstHist, 2, histsize, ranges, true, false); //进行直方图计算 //为绘制直方图准备参数 double maxVaule = 0; minMaxLoc(dstHist, 0, &maxVaule, 0, 0);//查找dstHist全局最大最小值后存入maxVaule int scale = 10; Mat histImg = Mat::zeros(saturationbinnum * scale, huebinnum * 10, CV_8UC3); for (int hue = 0; hue < huebinnum; hue++) for (int saturation = 0; saturation < saturationbinnum; saturation++) { float binValue = dstHist.at<float>(hue, saturation);//直方图直条的值 int intensity = cvRound(binValue * 255 / maxVaule); //强度 rectangle(histImg, Point(hue * scale, saturation * scale), Point((hue + 1) * scale - 1, (saturation + 1) * scale - 1), Scalar::all(intensity), CV_FILLED); } cvtColor(histImg, histImg, COLOR_HSV2BGR); imshow("hist", histImg);*/ //可以对每个通道分别计算直方图后画出来 //vector<Mat> v; //split(srcImage, v); //imshow("B", v[0]); namedWindow(INPUT_TITLE, CV_WINDOW_AUTOSIZE); namedWindow(OUTPUT_TITLE, CV_WINDOW_AUTOSIZE); imshow(INPUT_TITLE, srcImage); //分通道显示 //vector<Mat> bgr_planes; //split(src, bgr_planes); //设定像素取值范围 int histSize = 256; float range[] = { 0,256 }; const float* histRanges = { range }; cout << "执行" << endl; //三个通道分别计算直方图 Mat b_hist, g_hist, r_hist; int channels[] = {0}; //calcHist(&planes0, 1, Mat(), b_hist, &histSize, &range, true); calcHist(&planes0, 1, channels, Mat(), b_hist, 1, &histSize, &histRanges, true, false); //cout << "执行2" << endl; calcHist(&planes1, 1, channels, Mat(), g_hist, 1, &histSize, &histRanges, true, false); calcHist(&planes2, 1, channels, Mat(), r_hist, 1, &histSize, &histRanges, true, false); //创建直方图画布并归一化处理 int hist_h = 400; int hist_w = 512; int bin_w = hist_w / histSize; Mat histImage(hist_w, hist_h, CV_8UC3, Scalar(0, 0, 0)); normalize(b_hist, b_hist, 0, hist_h, NORM_MINMAX, -1, Mat()); normalize(g_hist, g_hist, 0, hist_h, NORM_MINMAX, -1, Mat()); normalize(r_hist, r_hist, 0, hist_h, NORM_MINMAX, -1, Mat()); //render histogram chart 在直方图画布上画出直方图 for (int i = 1; i < histSize; i++) { line(histImage, Point((i - 1) * bin_w, hist_h - cvRound(b_hist.at<float>(i - 1))), Point((i)* bin_w, hist_h - cvRound(b_hist.at<float>(i))), Scalar(255, 0, 0), 2, LINE_AA); line(histImage, Point((i - 1) * bin_w, hist_h - cvRound(g_hist.at<float>(i - 1))), Point((i)* bin_w, hist_h - cvRound(g_hist.at<float>(i))), Scalar(0, 255, 0), 2, LINE_AA); line(histImage, Point((i - 1) * bin_w, hist_h - cvRound(r_hist.at<float>(i - 1))), Point((i)* bin_w, hist_h - cvRound(r_hist.at<float>(i))), Scalar(0, 0, 255), 2, LINE_AA); } imshow(OUTPUT_TITLE, histImage); waitKey(); return 0; }
true
ff02f8cc571506bfc04adb3a820cc9f7db53a41a
C++
Danvil/Darwin
/Candy/src/Candy/Cubes/Generator/CornellBox.h
UTF-8
2,181
3.0625
3
[]
no_license
/* * CornellBox.h * * Created on: May 2, 2011 * Author: david */ #ifndef CORNELLBOX_H_ #define CORNELLBOX_H_ namespace Generators { /** * Preferred size: x1=-4, x2=+4, y1=-4, y2=+4, z1=-4, z2=+4; */ struct CornellBox { private: int cBoxSize; int cLightSize; double cSphereRadius; int cSphereZOffset; public: CornellBox(unsigned int r=4) { cBoxSize = Properties::CellSize * r - 2; cLightSize = Properties::CellSize * r / 2; cSphereRadius = 0.70 * double(Properties::CellSize * r); cSphereZOffset = cBoxSize - std::floor(cSphereRadius); } CubeType operator()(const CoordI& cw) { const CubeType t_sides = CubeTypes::DebugWhite; const CubeType t_sides_red = CubeTypes::DebugRed; const CubeType t_sides_green = CubeTypes::DebugGreen; const CubeType t_sides_blue = CubeTypes::DebugBlue; const CubeType t_sphere = CubeTypes::DebugWhite; const CubeType t_light = CubeTypes::LightWhite; int x = cw.x; int y = cw.y; int z = cw.z; // back side if(y == +cBoxSize && -cBoxSize < x && x < cBoxSize && -cBoxSize < z && z < cBoxSize) { return t_sides; } // ceiling if(z == cBoxSize - 1 && -cBoxSize < x && x < cBoxSize && -cBoxSize < y && y < cBoxSize) { if(-cLightSize < x && x < cLightSize && -cLightSize < y && y < cLightSize) { return t_light; } else { return t_sides; } } // doubled layered ceiling to avoid unnecessary light loss to the top if(z == cBoxSize && -cBoxSize < x && x < cBoxSize && -cBoxSize < y && y < cBoxSize) { return t_sides; } // bottom side if(z == -cBoxSize && -cBoxSize < x && x < cBoxSize && -cBoxSize < y && y < cBoxSize) { return t_sides_blue; } // left side if(x == -cBoxSize && -cBoxSize < y && y < cBoxSize && -cBoxSize < z && z < cBoxSize) { return t_sides_red; } // right side if(x == +cBoxSize && -cBoxSize < y && y < cBoxSize && -cBoxSize < z && z < cBoxSize) { return t_sides_green; } // sphere Vec3f pos = Properties::WorldToPositionCenter(x, y, z + cSphereZOffset); if(pos.norm() < cSphereRadius) { return t_sphere; } return CubeTypes::Empty; } }; } #endif
true
af7b9269cdd13b66a73947c2c47db715076a96a9
C++
doctorbigtime/cxx17
/variant.cpp
UTF-8
1,394
3.609375
4
[]
no_license
#include <variant> #include <iostream> #include <iostream> auto main(int argc, char** argv) -> int { using variant = std::variant<int, double, std::string>; auto print_visitor = [](auto const& v) { std::cout << v << std::endl; }; variant v = 123; // contains int int i = std::get<int>(v); std::visit(print_visitor, v); v = 999.99e-9; try { std::string d = std::get<std::string>(v); } catch(std::bad_variant_access const& e) { std::cout << "Not a string: " << e.what() << std::endl; } v = "foobar"; std::visit([](auto const& v) { using T = std::decay_t<decltype(v)>; if constexpr(std::is_same_v<T, int>) std::cout << "int: " << v << std::endl; else if constexpr(std::is_same_v<T, double>) std::cout << "double: " << v << std::endl; else if constexpr(std::is_same_v<T, std::string>) std::cout << "std::string: " << v << std::endl; }, v); struct static_visitor { void operator()(int i) { std::cout << "sv: int: " << i << std::endl; } void operator()(double i) { std::cout << "sv: double: " << i << std::endl; } void operator()(std::string i) { std::cout << "sv: std::string: " << i << std::endl; } }; v = 12345; std::visit(static_visitor(), v); return 0; }
true
60d9cc9d612d63041f05b7cfc2b7870a3ca08b55
C++
ik15151/etf-2010-rpr-internet-accounting
/DZ3/DZ3/trunk/InternetAccounting/KontrolaTimer.h
UTF-8
2,761
2.59375
3
[]
no_license
#pragma once using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; namespace InternetAccounting { /// <summary> /// Summary for KontrolaTimer /// </summary> public ref class KontrolaTimer : public System::Windows::Forms::UserControl { public: KontrolaTimer(void) { InitializeComponent(); // //TODO: Add the constructor code here // } KontrolaTimer(String ^izdat) { InitializeComponent(); // //TODO: Add the constructor code here // time = izdat; } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~KontrolaTimer() { if (components) { delete components; } } private: String ^time; private: System::Windows::Forms::Label^ vrijeme; protected: private: System::Windows::Forms::Timer^ timer1; private: System::ComponentModel::IContainer^ components; protected: private: /// <summary> /// Required designer variable. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); this->vrijeme = (gcnew System::Windows::Forms::Label()); this->timer1 = (gcnew System::Windows::Forms::Timer(this->components)); this->SuspendLayout(); // // vrijeme // this->vrijeme->AutoSize = true; this->vrijeme->Location = System::Drawing::Point(3, 7); this->vrijeme->Name = L"vrijeme"; this->vrijeme->Size = System::Drawing::Size(0, 13); this->vrijeme->TabIndex = 0; // // timer1 // this->timer1->Enabled = true; this->timer1->Interval = 1000; this->timer1->Tick += gcnew System::EventHandler(this, &KontrolaTimer::timer1_Tick); // // KontrolaTimer // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->Controls->Add(this->vrijeme); this->Name = L"KontrolaTimer"; this->Size = System::Drawing::Size(208, 25); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion public: String ^getVrijeme () { return time; } void setVrijeme () { time = vrijeme->Text; } private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) { vrijeme->Text = Convert::ToString (System::DateTime::Now::get ()); } }; }
true
05b407360fbaa1bf943f8aa3642b87063112cc24
C++
jonathondgebhardt/AOC-2020
/solutions/day04/part2/main.cpp
UTF-8
1,921
2.78125
3
[]
no_license
#include <day04/Utilities.ipp> #include <cassert> #include <iostream> // File auto-generated by StartNewDay struct Credential_Part2 : public util::day04::Credential { explicit Credential_Part2(const std::vector<std::string>& x) : util::day04::Credential(x) {} bool isValid() override { if(util::day04::Credential::isValid()) { const auto validBYR = util::day04::ValidateBirthYear(this->credentials["byr"]); const auto validIYR = util::day04::ValidateIssueYear(this->credentials["iyr"]); const auto validEYR = util::day04::ValidateExpirationYear(this->credentials["eyr"]); const auto validHGT = util::day04::ValidateHeight(this->credentials["hgt"]); const auto validHCL = util::day04::ValidateHairColor(this->credentials["hcl"]); const auto validECL = util::day04::ValidateEyeColor(this->credentials["ecl"]); const auto validPassportID = util::day04::ValidatePassportID(this->credentials["pid"]); return validBYR && validIYR && validEYR && validHGT && validHCL && validECL && validPassportID; } return false; } }; int main(int argc, char* argv[]) { const auto inputFile = util::GetInputFile("day04.txt"); const auto contents = util::Parse(inputFile); std::vector<std::string> credentialLines; std::vector<Credential_Part2> credentials; for(const auto& line : contents) { if(!line.empty()) { credentialLines.push_back(line); } else { credentials.emplace_back(credentialLines); credentialLines.clear(); } } if(!credentialLines.empty()) { credentials.emplace_back(credentialLines); credentialLines.clear(); } const auto validCredentials = std::count_if(credentials.begin(), credentials.end(), [](Credential_Part2& x) { return x.isValid(); }); std::cout << validCredentials << "\n"; return EXIT_SUCCESS; }
true
08ae7275aff87de3677592f71c96479ed30e6ac4
C++
zhouxindong/rola
/drop/lambdas.h
UTF-8
815
2.90625
3
[]
no_license
// inheriting from a lambda (C++11) template <typename TCall, typename UCall> class SimpleOverloaded : public TCall, UCall { public: SimpleOverloaded(TCall tf, UCall uf) : TCall(tf), UCall(uf) {} using TCall::operator(); using UCall::operator(); }; template <typename TCall, typename UCall> SimpleOverloaded<TCall, UCall> MakeOverloaded(TCall&& tf, UCall&& uf) { return SimpleOverloaded<TCall, UCall>(tf, uf); } // inheriting from a lambda (C++17) template <class ... Ts> struct overloaded17 : Ts... { using Ts::operator()...; }; template <class ... Ts> overloaded17(Ts...)->overloaded17<Ts...>; #define LIFT(foo) \ [](auto&& ... x) \ noexcept(noexcept(foo(std::forward<decltype(x)>(x)...))) \ -> decltype(foo(std::forward<decltype(x)>(x)...)) \ { return foo(std::forward<decltype(x)>(x)...); }
true
a4e5fcdd68ed2338b1fb6338228f83afe985ab4c
C++
rehno-lindeque/osi-qparser
/src/tokenregistry.inl
UTF-8
7,370
2.84375
3
[]
no_license
#ifdef __QPARSER_TOKENREGISTRY_H__ #ifndef __QPARSER_TOKENREGISTRY_INL__ #define __QPARSER_TOKENREGISTRY_INL__ ////////////////////////////////////////////////////////////////////////////// // // TOKENREGISTRY.INL // // Copyright © 2009, Rehno Lindeque. All rights reserved. // ////////////////////////////////////////////////////////////////////////////// namespace QParser { INLINE TokenRegistry::TokenRegistry() : nextTerminalToken(TOKEN_TERMINAL_FIRST), nextNonterminalToken(TOKEN_NONTERMINAL_FIRST), nextTemporaryToken(~1) { } INLINE ParseToken TokenRegistry::GetNextAvailableTerminal() const { return nextTerminalToken; } INLINE ParseToken TokenRegistry::GetNextAvailableNonterminal() const { return nextNonterminalToken; } INLINE ParseToken TokenRegistry::GetNextAvailableTemporaryToken() const { return nextTemporaryToken; } INLINE ParseToken TokenRegistry::GenerateTerminal(const_cstring terminalName) { // Try to find an existing terminal token with this name TokenValues::const_iterator i = terminalTokens.find(terminalName); if(i != terminalTokens.end()) return i->second; // Generate a new token for this terminal ParseToken token = nextTerminalToken; ++nextTerminalToken; // Insert the terminal into the token name registries terminalTokens[terminalName] = token; terminalNames[token] = terminalName; return token; } INLINE ParseToken TokenRegistry::GenerateNonterminal(const_cstring nonterminalName) { // Try to find an existing terminal token with this name TokenValues::const_iterator i = nonterminalTokens.find(nonterminalName); if(i != nonterminalTokens.end() && !IsTemporaryToken(i->second)) return i->second; // Generate a new token for this nonterminal ParseToken token = nextNonterminalToken; ++nextNonterminalToken; // If token is in the range of dummy tokens, this will not work. // (Then we've run out of token values to use for forward declarations and we'll need to think of a new strategy...) OSI_ASSERT(token <= nextTemporaryToken); // Insert the nonterminal into the token name registries nonterminalTokens[nonterminalName] = token; nonterminalNames[token] = nonterminalName; return token; } INLINE ParseToken TokenRegistry::GenerateTemporaryToken(const_cstring nonterminalName) { ParseToken token = nextTemporaryToken; nextTemporaryToken--; // If the temporary token is in the range of valid nonterminal tokens, this will not work. // (Then we've run out of token values to use for forward declarations and we'll need to think of a new strategy...) OSI_ASSERT(token >= nextNonterminalToken); // Insert the nonterminal into the token name registries // (don't add it to the nonterminalNames yet: it will be added when the token is resolved to a nonterminal) nonterminalTokens[nonterminalName] = token; return token; } INLINE ParseToken TokenRegistry::ResolveTemporaryToken(const_cstring nonterminalName) { // Generate a new nonterminal corresponding to the temporary token's name // This automatically replaces its entries in the registry (see GenerateTemporaryToken, GenerateNonterminal) return GenerateNonterminal(nonterminalName); } INLINE ParseToken TokenRegistry::GetToken(const_cstring tokenName) const { // Try to find a terminal token with this name TokenValues::const_iterator i = terminalTokens.find(tokenName); if(i != terminalTokens.end()) return i->second; // Try to find a non-terminal token with this name i = nonterminalTokens.find(tokenName); if(i != nonterminalTokens.end()) return i->second; return ParseToken(-1); // no matching token found } INLINE ParseToken TokenRegistry::GetTerminal(const_cstring terminalName) const { // Try to find a terminal token with this name TokenValues::const_iterator i = terminalTokens.find(terminalName); if(i != terminalTokens.end()) return i->second; return ParseToken(-1); // no matching terminal token found } INLINE ParseToken TokenRegistry::GetNonterminal(const_cstring nonterminalName) const { // Try to find a non-terminal token with this name TokenValues::const_iterator i = nonterminalTokens.find(nonterminalName); if(i != nonterminalTokens.end()) return i->second; return ParseToken(-1); // no matching non-terminal token found } INLINE const std::string& TokenRegistry::GetTokenName(ParseToken token) const { using std::string; static const string tokenUnknownTerminal("[Unknown Terminal]"); static const string tokenUnknownNonterminal("[Unknown Nonterminal]"); static const string tokenEOF("[Special (EOF)]"); static const string tokenIdentifier("[Identifier]"); //static const string tokenIdentifierDecl("[Identifier Decl]"); //static const string tokenIdentifierRef("[Identifier Ref]"); static const string tokenLiteral("[Literal]"); // Lookup terminal token names if(IsTerminal(token)) { switch(token) { case TOKEN_TERMINAL_IDENTIFIER: return tokenIdentifier; case TOKEN_TERMINAL_LITERAL: return tokenLiteral; case TOKEN_SPECIAL_EOF: return tokenEOF; //case ID_IDENTIFIER_DECL: return tokenIdentifierDecl; //case ID_IDENTIFIER_REF: return tokenIdentifierRef; } TokenNames::const_iterator i = terminalNames.find(token); if(i != terminalNames.end() && i->first == token) return i->second; return tokenUnknownTerminal; } // Look up non-terminal token names TokenNames::const_iterator i = nonterminalNames.find(token); if(i != nonterminalNames.end() && i->first == token) return i->second; return tokenUnknownNonterminal; } INLINE ParseToken TokenRegistry::FindOrGenerateTemporaryNonterminal(const_cstring nonterminalName) { ParseToken token = -1; // Try to find existing an production producing this token name TokenValues::const_iterator i = nonterminalTokens.find(nonterminalName); if(i == nonterminalTokens.end()) { // Generate a temporary token value for this non-terminal token = GenerateTemporaryToken(nonterminalName); } else { // Return the existing non-terminal token token = i->second; } return token; } INLINE bool TokenRegistry::IsTerminal(ParseToken token) { return (token & TOKEN_FLAG_SHIFT) == TOKEN_FLAG_SHIFT; } INLINE bool TokenRegistry::IsNonterminal(ParseToken token) { return !IsTerminal(token); } INLINE bool TokenRegistry::IsTemporaryToken(ParseToken token) { return token > nextNonterminalToken; } INLINE bool TokenRegistry::IsTokenValid(ParseToken token) const { return IsTerminal(token)? token < nextTerminalToken : token < nextNonterminalToken; } INLINE bool TokenRegistry::IsTerminalValid(ParseToken terminal) const { return IsTerminal(terminal) && terminal < nextTerminalToken; } INLINE bool TokenRegistry::IsNonterminalValid(ParseToken nonterminal) const { return !IsTerminal(nonterminal) && nonterminal < nextNonterminalToken; } } #endif #endif
true
9ac51e659171cb77235d516660c3cf44bdfdf5b5
C++
brandmaier/bnnlib
/src/ensembles/LSTMForgetEnsemble.cpp
UTF-8
8,239
2.515625
3
[ "LicenseRef-scancode-public-domain" ]
permissive
#include "LSTMForgetEnsemble.h" int LSTMForgetEnsemble::LSTM_COUNTER = 0; Node* LSTMForgetEnsemble::get_inputgate() {return nodes[1];} Node* LSTMForgetEnsemble::get_outputgate(){return nodes[3];} Node* LSTMForgetEnsemble::get_forgetgate() { return nodes[2];} Node* LSTMForgetEnsemble::get_cec(){return nodes[7];} Node* LSTMForgetEnsemble::get_output(){return nodes[9];} Node* LSTMForgetEnsemble::get_input(){return nodes[4];} LSTMForgetEnsemble::LSTMForgetEnsemble(std::vector<Node*>* nodes) : Ensemble(nodes) { name = "LSTMForgetEnsemble"; // TODO set references to weights! BUG } LSTMForgetEnsemble::LSTMForgetEnsemble(bool peepholes, nodetype cec_activation) { init(peepholes, Node::TANH_NODE, cec_activation,0,0,0); //init(peepholes, cec_activation,+1,-3,+2,0,0,0); //init(peepholes, cec_activation,-0.2,+.5,-0.2,0,0,0); } LSTMForgetEnsemble::LSTMForgetEnsemble(bool peepholes,nodetype input_activation, nodetype cec_activation, weight_t bias_input_weight, weight_t bias_forget_weight, weight_t bias_output_weight) { init(peepholes, input_activation,cec_activation,bias_input_weight, bias_forget_weight, bias_output_weight); } LSTMForgetEnsemble::LSTMForgetEnsemble(bool peepholes, nodetype cec_activation, weight_t bias_input_weight, weight_t bias_forget_weight, weight_t bias_output_weight) { init(peepholes, Node::TANH_NODE,cec_activation,bias_input_weight, bias_forget_weight, bias_output_weight); } void LSTMForgetEnsemble::init(bool peepholes, nodetype input_activation, nodetype cec_activation, weight_t bias_input_weight, weight_t bias_forget_weight, weight_t bias_output_weight ) { name = "LSTMForgetEnsemble"; this->cec_activation = cec_activation; // Gers - Grammar Learning // all nodes: input -1.0, forget +2.0, output -2.0 /* bias_discount_input = -1; andys guess bias_discount_forget = +3; bias_discount_output = -2; */ this->peepholes = peepholes; Node* bias = new BiasNode(); Node* inputgate = new SigmoidNode(); Node* outputgate = new SigmoidNode(); Node* forgetgate = new SigmoidNode(); //new ScaledSigmoidNode(2.0); //SteepSigmoidNode(1.0); Node* input; if (input_activation == Node::TANH_NODE) { input = new TanhNode(); } else if (input_activation == Node::LINEAR_NODE) { input = new LinearNode(); } else { error("LSTMForgetEnsemble: not all input activations implemented!"); } Node* input_mult = new PiNode(); Node* forget_mult = new PiNode(); Node* cell = new LinearNode(); Node* cell_act; if (cec_activation == Node::TANH_NODE) { cell_act = new TanhNode(); } else if (cec_activation == Node::LINEAR_NODE) { cell_act = new LinearNode(); } else { error("Invalid Activation function given for LSTM Forget Ensemble"); } Node* output_mult = new PiNode(); bias->name = "lstmbias"; inputgate->name = "ingate"; outputgate->name ="outgate"; forgetgate->name = "forgetgate"; cell->name = "CEC"; output_mult->name = "out"; input->name = "input"; input_mult->name = "in_mult"; forget_mult->name = "f_mult"; output_mult->name = "o_mult"; inputgate->functional_type = Node::LSTM_INPUT_GATE; forgetgate->functional_type = Node::LSTM_FORGET_GATE; outputgate->functional_type = Node::LSTM_OUTPUT_GATE; cell->functional_type = Node::LSTM_CEC; nodes.push_back(bias); //#0 nodes.push_back(inputgate); //#1 nodes.push_back(forgetgate); //#2 nodes.push_back(outputgate); //#3 nodes.push_back(input); //#4 nodes.push_back(input_mult); //#5 nodes.push_back(forget_mult); //#6 nodes.push_back(cell); //#7 nodes.push_back(cell_act); //#8 nodes.push_back(output_mult); //#9 bool dir = true; bool graves_style = true; c1 = Network::connect(inputgate, input_mult, dir); c2 = Network::connect(input, input_mult, dir); c3 = Network::connect(input_mult, cell, dir); f1 = Network::connect(cell, forget_mult, !graves_style); f2 = Network::connect(forgetgate, forget_mult, dir); f3 = Network::connect(forget_mult, cell, graves_style); c4 = Network::connect(cell, cell_act, dir); c5 = Network::connect(cell_act, output_mult, dir); c6 = Network::connect(outputgate, output_mult, dir); /* cout << "BIAS LSTM: " << (bias_offset_input + bias_discount_input*LSTM_COUNTER)<<" " << (bias_offset_forget + bias_discount_forget*LSTM_COUNTER) << +(bias_offset_output + bias_discount_output*LSTM_COUNTER) << " " << endl; */ if (abs(bias_input_weight) > 10e-9) b1 = Network::connect(bias, inputgate, true, bias_input_weight ); if (abs(bias_forget_weight) > 10e-9) b2 = Network::connect(bias, forgetgate, true, bias_forget_weight ); if (abs(bias_output_weight) > 10e-9) b3 = Network::connect(bias, outputgate, true, bias_output_weight ); inputs.push_back( input ); inputs.push_back( inputgate ); inputs.push_back( forgetgate ); inputs.push_back( outputgate ); outputs.push_back( output_mult ); // self-recurrent connection is constant //self->set_identity_and_freeze(); c1->set_identity_and_freeze(); c2->set_identity_and_freeze(); c3->set_identity_and_freeze(); c4->set_identity_and_freeze(); c5->set_identity_and_freeze(); c6->set_identity_and_freeze(); f1->set_identity_and_freeze(); f2->set_identity_and_freeze(); f3->set_identity_and_freeze(); if (peepholes) { cp1 = Network::connect(cell, inputgate, false); cp2 = Network::connect(cell, outputgate, true); cp3 =Network::connect(cell, forgetgate, false); //cp1->set_identity_and_freeze(); //cp2->set_identity_and_freeze(); } bool gated_bias = false; if (gated_bias) { Node* bias = new BiasNode(); Node* bias_mult = new PiNode(); Node* bias_gate = new SigmoidNode(); nodes.push_back(bias); nodes.push_back(bias_mult); nodes.push_back(bias_gate); Connection* gb1 = Network::connect(bias, bias_mult, true); Connection* gb2 = Network::connect(bias_gate, bias_mult, true); Connection* gb3 = Network::connect(bias_mult, cell, true); gb1->set_identity_and_freeze(); gb2->set_identity_and_freeze(); gb3->set_identity_and_freeze(); inputs.push_back(bias_gate); } //open_mults_to_public(); LSTM_COUNTER++; } LSTMForgetEnsemble::~LSTMForgetEnsemble() { } std::vector<Node*>* LSTMForgetEnsemble::get_inputs() { return &this->inputs; } std::vector<Node*>* LSTMForgetEnsemble::get_outputs() { return &this->outputs; } void LSTMForgetEnsemble::set_frozen(bool state) { for (unsigned int i=0; i < nodes.size(); i++) { for (unsigned int j=0; j < nodes[i]->outgoing_connections.size(); j++) { nodes[i]->outgoing_connections[j]->freeze_weight = state; } } //self->set_identity_and_freeze(); c1->set_identity_and_freeze(); c2->set_identity_and_freeze(); c3->set_identity_and_freeze(); c4->set_identity_and_freeze(); c5->set_identity_and_freeze(); c6->set_identity_and_freeze(); f1->set_identity_and_freeze(); f2->set_identity_and_freeze(); f3->set_identity_and_freeze(); } string LSTMForgetEnsemble::to_string() { stringstream out; out << (peepholes==true?"1":"0"); out << ";" << get_cec()->get_type(); return out.str(); } LSTMForgetEnsemble* LSTMForgetEnsemble::from_string(string parameters) { vector<string> tokens; string sep = std::string(";"); split(parameters,sep,tokens); bool peepholes = (atoi(tokens[0].c_str())==1); int cec_type = atoi(tokens[1].c_str()); LSTMForgetEnsemble* ensemble = new LSTMForgetEnsemble(peepholes, cec_type); return ensemble; } LSTMForgetEnsemble* LSTMForgetEnsemble::from_string(string parameters, vector<Node*>* nodes) { vector<string> tokens; string sep = std::string(";"); split(parameters,sep,tokens); bool peepholes = (atoi(tokens[0].c_str())==1); int cec_type = atoi(tokens[1].c_str()); if (cec_type != (*nodes)[7]->get_type() ) { cout << "CEC: " << cec_type <<endl; cout << "is : " << (*nodes)[7]->get_type() << endl; error("CEC type mismatch when creating LSTM from string!"); } LSTMForgetEnsemble* ensemble = new LSTMForgetEnsemble(nodes); ensemble->peepholes = peepholes; return ensemble; } void LSTMForgetEnsemble::open_mults_to_public() { // add the multiplicative units to the public outputs.push_back( nodes[5] ); outputs.push_back( nodes[6] ); outputs.push_back( nodes[9] ); }
true
006c81766fe262b1a37fd2d2db433d733430fd0b
C++
hallsamuel90/BarbarianInHell
/Character.cpp
UTF-8
1,711
3.28125
3
[]
no_license
/** * @author Samuel Hall * @date 02/19/2018 * @file Character.cpp * @brief This file contains the Character class methods */ #include <cstdlib> #include <iostream> #include "Character.hpp" //#define _CRTDBG_MAP_ALLOC //#include<iostream> //#include <crtdbg.h> //#ifdef _DEBUG //#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) //#define new DEBUG_NEW //#endif /** * Constructs a new Character object */ Character::Character() { mStrength = 0; mArmor = 0; mCharType = "NONE"; mCharName = "NONE"; mDie1 = NULL; mDie2 = NULL; } /** * Destrcuts a Character object */ Character::~Character() { mDie1 = NULL; mDie2 = NULL; } /** * Returns the attack points of a character */ int Character::attack() { return 0; } /** * Returns the defense points of a character */ int Character::defense() { return 0; } /** * Receives the attack of another character */ void Character::receiveAttack(int attack) { mStrength = mStrength - attack; } /** * Returns the strength of the character */ int Character::getStrength() { return mStrength; } /** * Returns the armor of the character */ int Character::getArmor() { return mArmor; } /** * Returns the type of the character */ std::string Character::getCharType() { return mCharType; } /** * Returns the name of the character */ std::string Character::getCharName() { return mCharName; } /** * Checks the strength of a character to see if he/she is dead */ bool Character::checkStrength() { bool status = false; if (mStrength <= 0) { status = true; } return status; } /** * Recovers a percentage of characters strenght if the character won a round */ void Character::setStrength(int strength) { mStrength = strength; }
true
a7164fe96a086050db73e944b6a35db8a5b91e57
C++
ITI/OpenSCADA
/src/pc_emulator/include/functions_registry.h
UTF-8
1,109
2.6875
3
[]
no_license
#ifndef __PC_EMULATOR_INCLUDE_PC_FUNCTIONS_REGISTRY_H__ #define __PC_EMULATOR_INCLUDE_PC_FUNCTIONS_REGISTRY_H__ #include <iostream> #include <unordered_map> #include "pc_configuration.h" #include "pc_resource.h" #include "pc_variable.h" #include "pc_datatype.h" using namespace std; namespace pc_emulator{ //! Class which registers and tracks all valid Functions with a Code Body class FunctionsRegistry { private: std::unordered_map<std::string, std::unique_ptr<PCVariable>> __FunctionsRegistry; /*!< Hash map of function name, variable obj */ PCResourceImpl * __AssociatedResource; /*!< Resource associated with this registry */ public: //! Constructor FunctionsRegistry(PCResourceImpl * AssociatedResource); //! Retrieve Function variable object with the specified name /*! \param FnName Name of the Function \return Function variable object */ PCVariable* GetFunction(string FnName); }; } #endif
true
08f1349909851391eb666102823a1c0704c93a8d
C++
Rumiao/DataStructure
/Sort/insertSort.cpp
UTF-8
489
3.625
4
[]
no_license
/* Insert sort implementation */ template <typename T> bool prior(T arg1, T arg2) { if (arg1 < arg2) { return true; } return false; } template <typename T> inline void Swap(T A[], int i, int j) { T temp = A[i]; A[i] = A[j]; A[j] = temp; } template <typename T> void insertSort(T A[], int length) { for (int i = 1; i < length; ++i) { for (int j = i; (j > 0) && (prior(A[j], A[j - 1])); --j) { Swap(A, j, j - 1); } } }
true
40ab8fa6f13cdc696c01a8f61c8d97fe589a4467
C++
kks227/BOJ
/1000/1045.cpp
UTF-8
1,233
2.703125
3
[]
no_license
#include <cstdio> #include <vector> #include <utility> #include <algorithm> using namespace std; const int MAX = 50; const int MAX_M = 1000; typedef pair<int, int> P; struct UnionFind{ int p[MAX]; UnionFind(){ fill(p, p+MAX, -1); } int f(int a){ if(p[a] < 0) return a; return p[a] = f(p[a]); } bool u(int a, int b){ a = f(a); b = f(b); if(a == b) return false; if(p[a] < p[b]){ p[a] += p[b]; p[b] = a; } else{ p[b] += p[a]; p[a] = b; } return true; } }; int main(){ int N, M, r1 = 0, r2[MAX] = {0,}; bool used[MAX_M] = {false,}; scanf("%d %d\n", &N, &M); vector<P> edge; for(int i = 0; i < N; ++i){ for(int j = 0; j < N; ++j) if(getchar() == 'Y' && j > i) edge.push_back(P(i, j)); getchar(); } UnionFind UF; for(int i = 0; i < edge.size() && r1 < N-1; ++i){ int u = edge[i].first, v = edge[i].second; if(UF.u(u, v)){ used[i] = true; ++r1; ++r2[u]; ++r2[v]; } } if(r1 < N-1){ puts("-1"); return 0; } for(int i = 0; i < edge.size() && r1 < M; ++i){ int u = edge[i].first, v = edge[i].second; if(!used[i]){ used[i] = true; ++r1; ++r2[u]; ++r2[v]; } } if(r1 < M) puts("-1"); else{ for(int i = 0; i < N; ++i) printf("%d ", r2[i]); } }
true
f6546a80da774b6a20966531e6dd16aaf0a4aab5
C++
Stephen1993/ACM-code
/hdu4710.cpp
GB18030
1,959
2.921875
3
[]
no_license
/*i%a - i%b,ÿμϴiʼֵ(i%a - i%b)ȵһ, iͲÿ+1,ÿμһ,na,bС ֻҪa,bСȵܺͣȻsum*=n/per + p;//pʾǰi,p=n%per; ⷴ˼:տʼԼ룬뵽a,bСܴܺ,nҲܴ պn<pernܴ;//perʾa,bСn>perperܴ ʹһζεҲܳʱһֱ֣һֱѰ򵥵ۡһֱûҵ ´ӦԣҲĸ򵥵ķԼ뵽ķ ʱ临ӶȺ:O((a/b * min(per,n)/a));//a>=b */ #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<string> #include<queue> #include<algorithm> #include<map> #include<cmath> #include<math.h> #include<iomanip> #define INF 99999999 using namespace std; const int MAX=10; __int64 p; __int64 Gcd(__int64 a,__int64 b){ if(b == 0)return a; return Gcd(b,a%b); } __int64 calculate(__int64 n,__int64 a,__int64 b,__int64 num){ p=0; __int64 la=a,lb=b,sum=0,l; for(__int64 i=0;i<n;){ l=min(la,min(lb,n-i)); if(i+l>num && i<num)p=sum+abs((int)(i%a - i%b))*(num-i); sum+=abs((int)(i%a - i%b))*l; i+=l; la=(la-l+a-1)%a+1; lb=(lb-l+b-1)%b+1; } return sum; } int main(){ __int64 n,a,b,t; scanf("%I64d",&t); while(t--){ scanf("%I64d%I64d%I64d",&n,&a,&b); __int64 gcd=Gcd(a,b),per=a*b/gcd,k=min(per,n);//С __int64 sum=calculate(k,a,b,n%k); if(n>per)sum=(n/per)*sum+p;//pʾǰn%ki%a-i%bĺ printf("%I64d\n",sum); } return 0; }
true
101f66596421fe53721a403108dddd6932606544
C++
ben-natan/raytracing_cpu
/src/tools.hpp
UTF-8
4,382
2.90625
3
[]
no_license
#ifndef TOOLS_H #define TOOLS_H #include <math.h> #include <algorithm> #include <random> // #include "light.hpp" // #include "sphere.hpp" // #include "plane.hpp" class Tools { public: static bool solveQuadratic(float a, float b, float c, float &x0, float &x1) { float discr = b*b - 4*a*c; if (discr < 0) { return false; } else if ( discr == 0 ) { x0 = x1 = -0.5 * b / a; return true; } else { float q = sqrt(discr); x0 = (-b + q)/(2*a); x1 = (-b - q)/(2*a); if (x0 > x1) { std::swap(x0,x1); // x1 plus grand que x0 } return true; }; } static double random_double() { static std::uniform_real_distribution<double> distribution(0.0, 1.0); static std::mt19937 generator; return distribution(generator); } // static void parseObjectsAndLights(std::string filename, // std::vector<std::unique_ptr<Object>>& objects, // std::vector<std::unique_ptr<Light>>& lights, // int& n_obj, int& n_lig) // { // rapidxml::xml_document<> doc; // rapidxml::xml_node<> * root_node; // std::ifstream theFile(filename); // std::vector<char> buffer((std::istreambuf_iterator<char>(theFile)), std::istreambuf_iterator<char>()); // buffer.push_back('\0'); // std::cout << &buffer[0] <<std::endl; // doc.parse<0>(&buffer[0]); // root_node = doc.first_node("World"); // rapidxml::xml_node<> * objects_root = root_node->first_node("Objects"); // rapidxml::xml_node<> * lights_root = root_node->first_node("Lights"); // // Load objects // rapidxml::xml_node<> * spheres_root = objects_root->first_node("Spheres"); // for (rapidxml::xml_node<> * sphere = spheres_root->first_node("Sphere"); sphere; sphere = sphere->next_sibling()) { // std::cout << "Sphere" << " " << n_obj << std::endl; // float cx, cy, cz, r; // cx = atof(sphere->first_attribute("cx")->value()); // cy = atof(sphere->first_attribute("cy")->value()); // cz = atof(sphere->first_attribute("cz")->value()); // r = atof(sphere->first_attribute("r")->value()); // objects.emplace_back(std::make_unique<Sphere>(Sphere(vec3(cx,cy,cz), r, vec3(123,20,50)))); // n_obj++; // } // rapidxml::xml_node<> * planes_root = objects_root->first_node("Planes"); // for (rapidxml::xml_node<> * plane = planes_root->first_node("Plane"); plane; plane = plane->next_sibling()) { // std::cout << "Plane" << " " << n_obj << std::endl; // float px, py, pz; // float nx, ny, nz; // px = atof(plane->first_attribute("px")->value()); // py = atof(plane->first_attribute("py")->value()); // pz = atof(plane->first_attribute("pz")->value()); // nx = atof(plane->first_attribute("nx")->value()); // ny = atof(plane->first_attribute("ny")->value()); // nz = atof(plane->first_attribute("nz")->value()); // objects.emplace_back(std::make_unique<Plane>(Plane(vec3(px,py,pz),vec3(nx,ny,nz), vec3(50,0,50)))); // n_obj++; // } // // Load lights // rapidxml::xml_node<> * pLights_root = lights_root->first_node("PointLights"); // for (rapidxml::xml_node<> * light = pLights_root->first_node("PointLight"); light; light = light->next_sibling()) { // std::cout << "PointLight" << " " << n_lig << std::endl; // float px, py, pz; // px = atof(light->first_attribute("px")->value()); // py = atof(light->first_attribute("py")->value()); // pz = atof(light->first_attribute("pz")->value()); // lights.emplace_back(std::make_unique<PointLight>(PointLight(mat4(), vec3(px,py,pz)))); // n_lig++; // } // } }; #endif
true
78f1a8ad524ec1b662a90fa6ed0dbb080251ffb7
C++
WEEEMAKE/Weeemake_Libraries_for_Arduino
/Weeemake/src/TempOneWire.cpp
UTF-8
7,800
2.75
3
[]
no_license
#include "TempOneWire.h" TempOneWire::TempOneWire(void) { } TempOneWire::TempOneWire(uint8_t pin) { bitmask = WePIN_TO_BITMASK(pin); baseReg = WePIN_TO_BASEREG(pin); } void TempOneWire::reset(uint8_t pin) { bitmask = WePIN_TO_BITMASK(pin); baseReg = WePIN_TO_BASEREG(pin); } bool TempOneWire::readIO(void) { WeIO_REG_TYPE mask = bitmask; volatile WeIO_REG_TYPE *reg WeIO_REG_ASM = baseReg; uint8_t r; WeDIRECT_MODE_INPUT(reg, mask); // allow it to float delayMicroseconds(10); r = WeDIRECT_READ(reg, mask); return(r); } uint8_t TempOneWire::reset(void) { WeIO_REG_TYPE mask = bitmask; volatile WeIO_REG_TYPE *reg WeIO_REG_ASM = baseReg; uint8_t r; uint8_t retries = 125; noInterrupts(); WeDIRECT_MODE_INPUT(reg, mask); interrupts(); /* wait until the wire is high... just in case */ do { if (--retries == 0) { return(0); } delayMicroseconds(2); } while (!WeDIRECT_READ(reg, mask)); noInterrupts(); WeDIRECT_WRITE_LOW(reg, mask); WeDIRECT_MODE_OUTPUT(reg, mask); /* drive output low */ interrupts(); delayMicroseconds(480); noInterrupts(); WeDIRECT_MODE_INPUT(reg, mask); /* allow it to float */ delayMicroseconds(70); r = !WeDIRECT_READ(reg, mask); interrupts(); delayMicroseconds(410); return(r); } void TempOneWire::write_bit(uint8_t v) { WeIO_REG_TYPE mask = bitmask; volatile WeIO_REG_TYPE *reg WeIO_REG_ASM = baseReg; if (v & 1) { noInterrupts(); WeDIRECT_WRITE_LOW(reg, mask); WeDIRECT_MODE_OUTPUT(reg, mask); /* drive output low */ delayMicroseconds(10); WeDIRECT_WRITE_HIGH(reg, mask); /* drive output high */ interrupts(); delayMicroseconds(55); } else { noInterrupts(); WeDIRECT_WRITE_LOW(reg, mask); WeDIRECT_MODE_OUTPUT(reg, mask); /* drive output low */ delayMicroseconds(65); WeDIRECT_WRITE_HIGH(reg, mask); /* drive output high */ interrupts(); delayMicroseconds(5); } } uint8_t TempOneWire::read_bit(void) { WeIO_REG_TYPE mask = bitmask; volatile WeIO_REG_TYPE *reg WeIO_REG_ASM = baseReg; uint8_t r; noInterrupts(); WeDIRECT_MODE_OUTPUT(reg, mask); WeDIRECT_WRITE_LOW(reg, mask); delayMicroseconds(3); WeDIRECT_MODE_INPUT(reg, mask); /* let pin float, pull up will raise */ delayMicroseconds(10); r = WeDIRECT_READ(reg, mask); interrupts(); delayMicroseconds(53); return(r); } void TempOneWire::write(uint8_t v, uint8_t power) { uint8_t bitMask; for (bitMask = 0x01; bitMask; bitMask <<= 1) { TempOneWire::write_bit((bitMask & v) ? 1 : 0); } if (!power) { noInterrupts(); WeDIRECT_MODE_INPUT(baseReg, bitmask); WeDIRECT_WRITE_LOW(baseReg, bitmask); interrupts(); } } void TempOneWire::write_bytes(const uint8_t *buf, uint16_t count, bool power) { for (uint16_t i = 0; i < count; i++) { write(buf[i]); } if (!power) { noInterrupts(); WeDIRECT_MODE_INPUT(baseReg, bitmask); WeDIRECT_WRITE_LOW(baseReg, bitmask); interrupts(); } } uint8_t TempOneWire::read() { uint8_t bitMask; uint8_t r = 0; for (bitMask = 0x01; bitMask; bitMask <<= 1) { if (TempOneWire::read_bit()) { r |= bitMask; } } return(r); } void TempOneWire::read_bytes(uint8_t *buf, uint16_t count) { for (uint16_t i = 0; i < count; i++) { buf[i] = read(); } } void TempOneWire::select(const uint8_t rom[8]) { uint8_t i; write(0x55); /* Choose ROM */ for (i = 0; i < 8; i++) { write(rom[i]); } } void TempOneWire::skip(void) { write(0xCC); /* Skip ROM */ } void TempOneWire::depower(void) { noInterrupts(); WeDIRECT_MODE_INPUT(baseReg, bitmask); interrupts(); } void TempOneWire::reset_search(void) { /* reset the search state */ LastDiscrepancy = 0; LastDeviceFlag = false; LastFamilyDiscrepancy = 0; for (int16_t i = 7;; i--) { ROM_NO[i] = 0; if (i == 0) { break; } } } void TempOneWire::target_search(uint8_t family_code) { /* set the search state to find SearchFamily type devices */ ROM_NO[0] = family_code; for (uint8_t i = 1; i < 8; i++) { ROM_NO[i] = 0; } LastDiscrepancy = 64; LastFamilyDiscrepancy = 0; LastDeviceFlag = false; } uint8_t TempOneWire::search(uint8_t *newAddr) { uint8_t id_bit_number; uint8_t last_zero, rom_byte_number, search_result; uint8_t id_bit, cmp_id_bit; uint8_t rom_byte_mask, search_direction; /* initialize for search */ id_bit_number = 1; last_zero = 0; rom_byte_number = 0; rom_byte_mask = 1; search_result = 0; /* if the last call was not the last one */ if (!LastDeviceFlag) { /* 1-Wire reset */ if (!reset()) { /* reset the search */ LastDiscrepancy = 0; LastDeviceFlag = false; LastFamilyDiscrepancy = 0; return(false); } /* issue the search command */ write(0xF0); /* loop to do the search */ do { /* read a bit and its complement */ id_bit = read_bit(); cmp_id_bit = read_bit(); /* check for no devices on 1-wire */ if ((id_bit == 1) && (cmp_id_bit == 1)) { break; } else { /* all devices coupled have 0 or 1 */ if (id_bit != cmp_id_bit) { search_direction = id_bit; /* bit write value for search */ } else { /* if this discrepancy if before the Last Discrepancy on a previous next then pick the same as last time */ if (id_bit_number < LastDiscrepancy) { search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0); } else { /* if equal to last pick 1, if not then pick 0 */ search_direction = (id_bit_number == LastDiscrepancy); } /* if 0 was picked then record its position in LastZero */ if (search_direction == 0) { last_zero = id_bit_number; /* check for Last discrepancy in family */ if (last_zero < 9) { LastFamilyDiscrepancy = last_zero; } } } /* set or clear the bit in the ROM byte rom_byte_number with mask rom_byte_mask */ if (search_direction == 1) { ROM_NO[rom_byte_number] |= rom_byte_mask; } else { ROM_NO[rom_byte_number] &= ~rom_byte_mask; } /* serial number search direction write bit */ write_bit(search_direction); /* increment the byte counter id_bit_number and shift the mask rom_byte_mask */ id_bit_number++; rom_byte_mask <<= 1; /* if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask */ if (rom_byte_mask == 0) { rom_byte_number++; rom_byte_mask = 1; } } } while (rom_byte_number < 8); /* loop until through all ROM bytes 0-7 */ /* if the search was successful then */ if (!(id_bit_number < 65)) { /* search successful so set LastDiscrepancy,LastDeviceFlag,search_result */ LastDiscrepancy = last_zero; /* check for last device */ if (LastDiscrepancy == 0) { LastDeviceFlag = true; } search_result = true; } } /* if no device found then reset counters so next 'search' will be like a first */ if (!search_result || !ROM_NO[0]) { LastDiscrepancy = 0; LastDeviceFlag = false; LastFamilyDiscrepancy = 0; search_result = false; } for (int16_t i = 0; i < 8; i++) { newAddr[i] = ROM_NO[i]; } return(search_result); }
true
f5667a768e09af53e7bcd15f05f678fd58863f76
C++
paulot/interview
/Google/anagram.cpp
UTF-8
532
3.359375
3
[]
no_license
#include <iostream> #include <string> using namespace std; bool isAnagram(string &a, string &b) { int c[26] = { 0 }; for (int i = 0; i < a.size(); i++) { if (a[i] == ' ') continue; c[a[i]-'a']++; } for (int i = 0; i < b.size(); i++) { if (b[i] == ' ') continue; c[b[i]-'a']--; } for (int i = 0; i < 26; i++) if (c[i] != 0) return false; return true; } int main() { string a = "cofiers", b = "fir cones"; cout << isAnagram(a,b) << endl; return 0; }
true
450b79109482d2d1c4f430ec026eb9425797d703
C++
ggyool/study-alone
/ps/boj_cpp/제곱ㄴㄴ수 (1016).cpp
UTF-8
962
2.578125
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <cmath> #define N 1000000 using namespace std; typedef long long int lld; lld A, B; vector<lld> sv; lld svlen; bool notPrime[(int)1e6 + 1]; //false 이면 제곱ㄴㄴ수 bool notSqn[(int)1e6 + 1]; bool inRange(lld num) { if (num<A || num>B) return false; return true; } int main(void) { // 1~100만까지 소수 for (lld i = 2; i*i <= N;++i) { if (notPrime[i]) continue; for (lld j = 2 * i; j <= N; j+=i) { notPrime[j] = true; } } for (lld i = 2; i <= N; ++i) { if (notPrime[i] == false) sv.push_back(i*i); } svlen = sv.size(); // 78498 cin >> A >> B; for (int i = 0; i < svlen; ++i) { lld sqn = sv[i]; if (sqn > B) continue; lld div = A / sqn; if (A%sqn != 0) ++div; for(lld j=div*sqn; j<=B; j+=sqn) { notSqn[j-A] = true; } } int ans = 0; for (int i = 0; i <= B-A; ++i) { if (notSqn[i] == false) ++ans; } cout << ans; return 0; }
true
ec344081364cc151bb961fb684409a3687007060
C++
piyush-jaiswal/College-Work
/C++/lab experiment 2/LAB_Experiment 2 1).cpp
UTF-8
1,469
4.1875
4
[]
no_license
/* LAB_Experiment 2 Do all these questions by applying concept of static data member, static member function, const member function, inline function( Explicit , Implicit), nesting member function and Default Arguments: 1. Create a class employee that includes firstname( type String), lastname(type String) and a monthly salary. Create two employee objects and display each object's yearly salary. Give each employee a 10% raise and display each employee‟s yearly salary. */ #include<iostream> #include<conio.h> using namespace std; class employee { string firstname, lastname; static int msal; public: void getdata(); static int cal(); void display(); void raise(); }; int employee :: msal = 25000; inline void employee :: getdata() { cout<<"Enter the firstname and lastname"<<endl; cin>>firstname>>lastname; } inline int employee :: cal() { return msal*12; } inline void employee :: display() { cout<<endl<<firstname<<" "<<lastname<<endl; cout<<"Yearly salary "<<cal()<<endl; } inline void employee :: raise() { cout<<"Salarty after 10 % raise = "<<cal()+.1*cal()<<endl; } int main() { employee ob1, ob2; cout<<"Enter details of first employee"<<endl; ob1.getdata(); ob1.display(); ob1.raise(); cout<<endl; cout<<"Enter details of second employee"<<endl; ob2.getdata(); ob2.display(); ob2.raise(); }
true
8e458c479ddf166f285b5f219ef4f5182bab7013
C++
Dante3085/OldCppTutorials
/C++Tutorial 109 list/C++Tutorial 109 list/Quelle.cpp
ISO-8859-1
1,500
3.625
4
[]
no_license
#include <iostream> #include <list> /*"list"(Allgemein: "linked list" oder "double linked list"): Verhlt sich auf den ersten Blick hnlich wie der Vektor. Neue Elemente knnen mit "push_back()" hinzugefgt werden. Es knnen auch neue Elemente auf der anderen Seite mit "push_front()" hinzugefgt werden. quivalent knnen diese Elemente mit "pop_back()" und "pop_front()" wieder gelscht werden. Eine list kopiert jedoch niemals Daten. Jedes Element hat einen Pointer auf das Element vor sich und auf das Element nach sich. Wenn wir neue Elemente in die list packen wollen, nehmen wir einfach den nach vorne zeigenden Pointer des vorletzten Elements und richten ihn auf das neue Element. Die Zeit fr das Einfgen und Entfernen von Elementen einer list ist !konstant! Nachteil: Mchte man ber alle Elemente der list drbergehen, bentigt man deutlich mehr Zeit relativ zum Vektor. Grund 1: Man muss immer ber die Pointer "hpfen". Grund 2: "Cache Misses". CPU "vermutet" bei einem Datenzugriff, welche Daten denn wohl als nchstes kommen knnten, und ldt vom RAM ganze Datenblcke in den Cache. Bei einem Vektor ist dies simpel und schnell. Bei der list kann die CPU vorher nicht ahnen, was kommen knnte. => Beim "Einfgen" und "Lschen" von Elementen ist die list schneller als der Vektor. Beim drbergehen ber die Elemente ist jedoch der Vektor wieder schneller als die list. */ int main() { std::list<int> l; system("pause"); return 0; }
true
58f7b076447af209c263084348908e4788b0c9bf
C++
rayfill/cpplib
/Socket/Win32SocketImpl.hpp
UTF-8
2,718
2.65625
3
[]
no_license
#ifndef WIN32SOCKETIMPL_HPP_ #define WIN32SOCKETIMPL_HPP_ #include <winsock2.h> #include <ws2tcpip.h> #include <string> #include <Socket/NativeSocket.hpp> struct Win32SocketImpl { typedef enum { read = SD_RECEIVE, write = SD_SEND, both = SD_BOTH } ShutdownTarget; static int shutdown(SocketHandle handle, ShutdownTarget target) { return ::shutdown(handle, target); } /** * ハンドルの正当性検査 */ static bool isValidHandle(SocketHandle handle) { return handle != reinterpret_cast<SocketHandle>(INVALID_HANDLE_VALUE); } /** * socketのlast errorを取得 */ static int getLastError() { return WSAGetLastError(); } /** * acceptエラー時のリトライ可能かどうかの判定 */ static bool isRetry(int code) { switch (code) { case WSAENETDOWN: case WSAEHOSTDOWN: case WSAEHOSTUNREACH: case WSAEOPNOTSUPP: case WSAENETUNREACH: return true; default: return false; } } /** * ホスト名(文字列表現)からipAddressを返す * */ static u_long getAddrByName(const char* addrName) { #if WINNT_VER>=0x0501 addrinfo hints; addrinfo* result = NULL; u_long addr; try { memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; if (getaddrinfo(addrName, NULL, &hints, &result)) return 0; addr = reinterpret_cast<sockaddr_in*> (result->ai_addr)->sin_addr.s_addr; } catch (...) { freeaddrinfo(result); throw; } freeaddrinfo(result); return addr; #else hostent* entry = gethostbyname(addrName); if (entry) return reinterpret_cast<in_addr*>(entry->h_addr)->s_addr; return 0UL; #endif } static std::string getNameByAddr(unsigned long ipAddress) { #if WINNT_VER>=0x0501 /** * @see http://www.nic.ad.jp/ja/dom/system.html * ドメイン名長さは256文字以下 * @todo 日本語ドメインの場合UTF-8だよな・・・その場合は * x3 でいいんだっけか・・・ */ char result[256*3]; sockaddr_in addr; memset(result, 0, sizeof(result)); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = static_cast<u_long>(ipAddress); if (getnameinfo(reinterpret_cast<const sockaddr*>(&addr), sizeof(addr), result, sizeof(result), NULL, 0, NI_NAMEREQD)) return ""; return std::string(result); #else hostent* entry = gethostbyaddr(reinterpret_cast<const char*>(&ipAddress), 4, AF_INET); if (entry) return std::string(entry->h_name); return ""; #endif } static void socketClose(SocketHandle socketHandle) { ::closesocket(socketHandle); } }; typedef u_long in_addr_t; typedef Win32SocketImpl SocketImpl; #endif /* WIN32SOCKETIMPL_HPP_ */
true
35350276c6ada221f2f04968a420a99eb1ed07f0
C++
lhwnova/ecs40spring2016
/p3/p3_handin_files/flight.h
UTF-8
472
2.765625
3
[]
no_license
#ifndef FLIGHT_H #define FLIGHT_H #include <iostream> #include "plane.h" #define MAX_CITY_LENGTH 20 using namespace std; class Flight { private: int flightNum; char origin[MAX_CITY_LENGTH]; char destination[MAX_CITY_LENGTH]; Plane *plane; public: ~Flight(); void construcFlight(ifstream &inf); void printFlightInfo() const; void writeFlight(ofstream &outf) const; int getFlightNumber(); void addPassenger(); }; // Flight class #endif // FLIGHT_H
true
bd78902039049cf37569c33fa18d5ceb71aabe71
C++
subacc23/third_time
/electrical/electrical/Source/Stage/Stage.cpp
SHIFT_JIS
3,356
2.796875
3
[]
no_license
#include "DxLib.h" #include "Stage.h" #include "../Resource/Graphic.h" #include "../Resource/CSV.h" int Stage::mapData[MAP_COUNT_Y][MAP_COUNT_X] = { 0 }; Stage::Stage() { graphIndex = 0; } // bool Stage::Initialize() { // ǂݍރt@Ci[ char fileName[512]; sprintf_s(fileName, sizeof(fileName), "Resource/Data/Stage/stage%d.csv", 1); // t@Cǂݍ߂ȂꍇAfalse int *p = (int *)mapData; if ( !CSV::LoadFile(fileName, MAP_COUNT_X, MAP_COUNT_Y, p) ) { return false; } return true; } // }bv` void Stage::MapDraw(int x, int y, float shakeX, float shakeY, int scrollX, int scrollY, int displaceX, int displaceY) { switch ( mapData[y][x] ) { case e_MAP_NONE: // Ȃ graphIndex = e_MAP_NONE; break; case e_MAP_BLOCK: // ubN graphIndex = e_MAP_BLOCK; break; case e_MAP_GOAL_LEFT_BOTTOM: // S[ graphIndex = e_MAP_GOAL_LEFT_BOTTOM; break; case e_MAP_GOAL_RIGHT_BOTTOM: // S[E graphIndex = e_MAP_GOAL_RIGHT_BOTTOM; break; case e_MAP_GOAL_LEFT_TOP: // S[ graphIndex = e_MAP_GOAL_LEFT_TOP; break; case e_MAP_GOAL_RIGHT_TOP: // S[E graphIndex = e_MAP_GOAL_RIGHT_TOP; break; default: graphIndex = e_MAP_NONE; break; } if ( graphIndex != e_MAP_NONE ) { DrawGraph(x * CHIP_SIZE + (int)shakeX - scrollX + displaceX, y * CHIP_SIZE + (int)shakeX - scrollY + displaceY, Graphic::GetInstance()->GetMapChip(graphIndex), true); } } // `揈 void Stage::Draw(float shakeX, float shakeY, int scrollX, int scrollY, int screenX, int screenY, int displaceX, int displaceY) { // XN[ɉfĂ镔(2ubN)` int mapChipLeft = (screenX - WIN_WIDTH / 2 - displaceX + DISPLACE_X) / CHIP_SIZE - 2; int mapChipRight = (screenX + WIN_WIDTH / 2 - displaceX - DISPLACE_X) / CHIP_SIZE + 2; int mapChipTop = (screenY - WIN_HEIGHT / 2 - displaceY + DISPLACE_Y) / CHIP_SIZE - 2; int mapChipBottom = (screenY + WIN_HEIGHT / 2 - displaceY - DISPLACE_Y) / CHIP_SIZE + 2; if ( mapChipLeft < 0 ) { mapChipLeft = 0; } if ( mapChipRight > MAP_COUNT_X ) { mapChipRight = MAP_COUNT_X; } if ( mapChipTop < 0 ) { mapChipTop = 0; } if ( mapChipBottom > MAP_COUNT_Y ) { mapChipBottom = MAP_COUNT_Y; } for ( int y = mapChipTop; y < mapChipBottom; y++ ) { for ( int x = mapChipLeft; x < mapChipRight; x++ ) { MapDraw(x, y, shakeX, shakeY, scrollX, scrollY, displaceX, displaceY); } } } // }bv`bv̒l擾 int Stage::GetMapParam(float x, float y) { // }bv`bvz̓Y int mapX = (int)x / CHIP_SIZE; int mapY = (int)y / CHIP_SIZE; // }bvoĂꍇANONEԂ if ( mapX < 0 || mapY < 0 || mapX >= MAP_COUNT_X || mapY >= MAP_COUNT_Y ) { return e_MAP_NONE; } // S[̃}bv`bv͂܂Ƃ߂ăS[ƕԂ if ( mapData[mapY][mapX] == e_MAP_GOAL_LEFT_BOTTOM || mapData[mapY][mapX] == e_MAP_GOAL_RIGHT_BOTTOM || mapData[mapY][mapX] == e_MAP_GOAL_LEFT_TOP || mapData[mapY][mapX] == e_MAP_GOAL_RIGHT_TOP ) { return e_MAP_GOAL; } // }bv`bvz̒lԂ return mapData[mapY][mapX]; }
true
957110f0c7b2f85ce23435b63d6bb2b77b9d4e8e
C++
IluyaSmith/DefendTwitchCastle
/ChatGame/Command.h
UTF-8
782
3
3
[]
no_license
#pragma once #include <string> #include <vector> #include <memory> class Command { public: Command() : m_playername("NA"), m_commandname("NA"), m_args({}) {}; Command(std::string _plname, std::string _cname, std::vector<std::string> _args) : m_playername(_plname), m_commandname(_cname), m_args(_args) {}; static std::shared_ptr<Command> cmdFactory(std::string& _plname, std::string& _cname, std::vector<std::string>& _args) { return std::make_shared<Command>(_plname, _cname, _args); } ~Command() {}; std::string getPlayername() { return m_playername; } std::string getCommandname() { return m_commandname; } std::vector<std::string> getArgs() { return m_args; } private: std::string m_playername; std::string m_commandname; std::vector<std::string> m_args; };
true
9601940dca39c11c9033bc33fa8b11818fa077fd
C++
AymanM92/Algorithms_ToolBox_Coursera_Cpp
/Week6/1_maximum_amount_of_gold/Dummy.cpp
UTF-8
578
2.8125
3
[]
no_license
/* * Dummy.cpp * * Created on: Apr 21, 2018 * Author: Ayman.mohamed */ int knapSack(int W, int wt[], int val[], int n) { int i, j; int K[n + 1][W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= W; j++) { if (i == 0 || j == 0) K[i][j] = 0; else if (wt[i - 1] <= j) K[i][j] =1;//max(val[i - 1] + K[i - 1][j - wt[i - 1]], K[i - 1][j]); else K[i][j] = K[i - 1][j]; } } return K[n][j]; }
true
11a0cb2349652a256dfed7152f750d25568d36ca
C++
wagner-group/geoadex
/archived/cpp/test_Cgal.cpp
UTF-8
2,668
2.546875
3
[ "MIT" ]
permissive
// #include <iostream> // #include <CGAL/Simple_cartesian.h> // typedef CGAL::Simple_cartesian<double> Kernel; // typedef Kernel::Point_2 Point_2; // typedef Kernel::Segment_2 Segment_2; // int main() // { // Point_2 p(1,1), q(10,10); // std::cout << "p = " << p << std::endl; // std::cout << "q = " << q.x() << " " << q.y() << std::endl; // std::cout << "sqdist(p,q) = " // << CGAL::squared_distance(p,q) << std::endl; // // Segment_2 s(p,q); // Point_2 m(5, 9); // // std::cout << "m = " << m << std::endl; // std::cout << "sqdist(Segment_2(p,q), m) = " // << CGAL::squared_distance(s,m) << std::endl; // std::cout << "p, q, and m "; // switch (CGAL::orientation(p,q,m)){ // case CGAL::COLLINEAR: // std::cout << "are collinear\n"; // break; // case CGAL::LEFT_TURN: // std::cout << "make a left turn\n"; // break; // case CGAL::RIGHT_TURN: // std::cout << "make a right turn\n"; // break; // } // std::cout << " midpoint(p,q) = " << CGAL::midpoint(p,q) << std::endl; // return 0; // } #include <CGAL/config.h> #if defined(BOOST_GCC) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) #include <iostream> int main() { std::cerr << "NOTICE: This test requires G++ >= 4.4, and will not be compiled." << std::endl; } #else #define CGAL_EIGEN3_ENABLED #include <CGAL/Epick_d.h> #include <CGAL/Delaunay_triangulation.h> int main() { double pointsIn[][7] = { { 42.89, 0, 60.55, 30.72, 0, 0, 0 }, { 45.65, 50.83, 50.37, 16.13, 0, 0, 0 }, { 79.06, 57.84, 61.59, 2.52, 0, 0, 0 }, { 44.47, 39.46, 39.53, 28.72, 0, 0, 0 }, { 0, 100, 0, 0, 100, 0, 53.47 }, { 66.95, 100, 33.6, 0, 0, 0, 0 }, { 42.89, 0, 0, 30.72, 100, 0, 53.47 }, { 100, 100, 100, 100, 100, 100, 100 } }; typedef CGAL::Delaunay_triangulation<CGAL::Epick_d< CGAL::Dimension_tag<7> > > T; T dt(7); std::vector<T::Point> points; points.reserve(8); for (int j = 0; j < 8; ++j) { T::Point p(&pointsIn[j][0], &pointsIn[j][7]); points.push_back(p); } T::Vertex_handle hint; int i = 0; for (std::vector<T::Point>::iterator it = points.begin(); it != points.end(); ++it) { if (T::Vertex_handle() != hint) { hint = dt.insert(*it, hint); } else { hint = dt.insert(*it); } printf("Processing: %d/%d\n", ++i, (int)points.size()); } return 0; } #endif
true
0f41d79a2772b520e63eed9058a36cd3ec8601e9
C++
ekaterin17/Coursera-cpp
/2 Yellow/Final 2/Final 2/node.cpp
UTF-8
701
2.953125
3
[]
no_license
#include "node.h" bool DateComparisonNode::Evaluate(const Date &date, const string &event) const { return compare(comparison_, date, date_); } bool EventComparisonNode::Evaluate(const Date &date, const string &event) const { return compare(comparison_, event, event_); } bool LogicalOperationNode::Evaluate(const Date& date, const string& event) const { switch(op_) { case LogicalOperation::Or: return left_->Evaluate(date, event) || right_->Evaluate(date, event); case LogicalOperation::And: return left_->Evaluate(date, event) && right_->Evaluate(date, event); } throw invalid_argument("Invalid logical operation"); }
true