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
5455af0fa5c623c2e5b275984ade5405b5d780b1
C++
rzolotuhin/arduino-config-esp
/examples/for/for.ino
UTF-8
668
2.875
3
[]
no_license
#include <config-esp.h> void setup() { Serial.begin(115200); config.begin(); // creating config variables with default values config.add("test_var1", "001"); config.add("test_var2", "002"); config.add("test_var3", "003"); // reading values from flash memory // if a variable is found, its value will be overwritten in RAM config.read(); // config size output // it can change if the config contains more parameters in the Flash memory Serial.printf("size: %d\n", config.list().size()); // getting all config data for(auto &cfg: config.list()) { Serial.printf("var: %s, val: %s\n", cfg.first, cfg.second); } } void loop() { }
true
bae3e57f59e5d04dd269c692e631838065a5de58
C++
MuneebRe/BattleAtDawn-Developer-Edition
/Developer Edition/map.h
UTF-8
1,503
2.828125
3
[]
no_license
//map class using Parallax technique. class map { //This class creates the layer objects that the environment is composed of int id_layer; //id of the layer object that is set when constructor is called double layer_x; //layer object's x position double layer_y; //layer object's y position double last_x; //start position of layer, used for draw_coin double last_y; //start position of layer, used for draw_coin double layer_scale; double df; //depth factor, the depth of the layer will influence scroll rate double max_pos_x; //furthest layer will displace right as drone moves LEFT double max_neg_x; //furthest layer will displace left as drone moves RIGHT double max_pos_y; //furthest layer will displace up as drone moves DOWN double max_neg_y; //furthest layer will displace down as drone moves UP public: map(char layer_file_name[], double depth_factor, double layerX, double layerY, double scale, double _max_pos_x, double _max_neg_x, double _max_pos_y, double _max_neg_y); //constructor to initialize the layer object, called outside of the infinite draw loop void reset(double layerX, double layerY); void draw_layer(Drone& name1); //this will contain "draw_sprite()" and manipulate x and y of layer to track drone object properly.Called inside infinite draw loop double get_layerX(); double get_layerY(); double get_lastX(); double get_lastY(); double get_max_pos_x(); double get_max_pos_y(); double get_max_neg_x(); double get_max_neg_y(); ~map() { ; } };
true
4bf02e0812a612a4152c136f8f4f3c01d126d757
C++
uvbs/AnpanMMO
/Client/AnpanMMO/Source/AnpanMMO/Packet/AnpanData.h
SHIFT_JIS
1,508
3.03125
3
[]
no_license
/** * @file AnpanData.h * @brief Apf[^pPbg * @author NativePacketGenerator */ #ifndef __ANPANDATA_H__ #define __ANPANDATA_H__ #include "PacketBase.h" #include "MemoryStream/MemoryStreamInterface.h" /** * @brief Apf[^pPbg */ class AnpanData { public: /** * @fn u8 GetPacketID() const * @brief pPbghc擾. * @return pPbghc */ //! UUID u32 Uuid; //! }X^hc u32 MasterId; //! XW float X; //! YW float Y; //! ZW float Z; //! ] float Rotation; //! HP s32 Hp; //! őHP s32 MaxHp; /** * @brief RXgN^ */ AnpanData() { } /** * @brief RXgN^ */ AnpanData(u32 InUuid, u32 InMasterId, float InX, float InY, float InZ, float InRotation, s32 InHp, s32 InMaxHp) { Uuid = InUuid; MasterId = InMasterId; X = InX; Y = InY; Z = InZ; Rotation = InRotation; Hp = InHp; MaxHp = InMaxHp; } /** * @fn bool Serialize(MemoryStreamInterface *pStream) * @brief VACY * @param[in] pStream Xg[ * @return trueԂB */ bool Serialize(MemoryStreamInterface *pStream) { pStream->Serialize(&Uuid); pStream->Serialize(&MasterId); pStream->Serialize(&X); pStream->Serialize(&Y); pStream->Serialize(&Z); pStream->Serialize(&Rotation); pStream->Serialize(&Hp); pStream->Serialize(&MaxHp); return true; } }; #endif // #ifndef __ANPANDATA_H__
true
e17a2f9d62139a369a7f8ef7b7cd4d5ba2604686
C++
GuilhermeCstr/TAC-IDJ-JE
/T2/src/GameObject.cpp
UTF-8
1,159
2.921875
3
[ "MIT" ]
permissive
#include "../include/GameObject.h" GameObject::GameObject() : box(0, 0, 0, 0), isDead(false) { } GameObject::~GameObject() { components.clear(); } void GameObject::Update(float dt) { for (int i = components.size() - 1; i >= 0; --i) { components[i]->Update(dt); } } void GameObject::Render() { for (int i = components.size() -1; i >= 0; --i) { components[i]->Render(); } } bool GameObject::IsDead() { return isDead; } void GameObject::RequestDelete() { isDead = true; } void GameObject::AddComponent(std::shared_ptr<Component> cpt) { components.emplace_back(cpt); } void GameObject::RemoveComponent(std::shared_ptr<Component> cpt) { for (int i = components.size() - 1; i >= 0; i--) { if (components[i] == cpt) { components.erase(components.begin()+i); } } } std::shared_ptr<Component> GameObject::GetComponent(std::string type) { for (int i = components.size() - 1; i >= 0; i--) { if (components[i]->Is(type)) { return components[i]; } } return nullptr; }
true
a8c71cbd84d4c0c194b3f64314ad1a3126306544
C++
CeKey/PixelFighters
/PixelFighters_Final/ImageControl.cpp
UTF-8
2,595
3.046875
3
[]
no_license
#include "ImageControl.h" #include "macros.h" //loads the spritesheet and returns the rect SDL_Rect* ImageControl::LoadAnimation(char* path, int line, int width, int height,int nrSprites, SDL_Texture** texture, SDL_Renderer* renderer) { //get line with animation int spriteLine = line * height; //create SDL_Rect for clips SDL_Rect *spriteClips = new SDL_Rect[nrSprites]; //load Spritesheet bmp if (*texture == nullptr) { SDL_Surface* loadedSurface = SDL_LoadBMP(path); if (loadedSurface == NULL) { printf("Failed to load char: %s", SDL_GetError()); } //Set colorkey for transparence SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, c_r, c_g, c_b)); //create Texture from surface *texture = SDL_CreateTextureFromSurface(renderer, loadedSurface); } //For the nr of clips in animation for (int i = 0; i < nrSprites; i++) { spriteClips[i].x = i * width; //set Startpoint horizontal spriteClips[i].y = spriteLine; //set Startpoint vertical spriteClips[i].w = width; //set width spriteClips[i].h = height; //set height } //retrun SDL_Rects return spriteClips; } SDL_Rect* ImageControl::LoadAnimation(char* path, float pos, int width, int height, int nrSprites, SDL_Texture** texture, SDL_Renderer* renderer) { //get line with animation int spriteLine = pos; //create SDL_Rect for clips SDL_Rect* spriteClips = new SDL_Rect[nrSprites]; //load Spritesheet bmp if (*texture == nullptr) { SDL_Surface* loadedSurface = SDL_LoadBMP(path); if (loadedSurface == NULL) { printf("Failed to load bmp: %s", SDL_GetError()); } //Set colorkey for transparence SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, c_r, c_g, c_b)); //create Texture from surface *texture = SDL_CreateTextureFromSurface(renderer, loadedSurface); SDL_FreeSurface(loadedSurface); loadedSurface = nullptr; } //For the nr of clips in animation for (int i = 0; i < nrSprites; i++) { spriteClips[i].x = i * width; //set Startpoint horizontal spriteClips[i].y = spriteLine; //set Startpoint vertical spriteClips[i].w = width; //set width spriteClips[i].h = height; //set height } //retrun SDL_Rects return spriteClips; } //render objects new void ImageControl::Render(SDL_Rect* position,SDL_Texture* texture, SDL_Renderer* renderer, SDL_Rect* spriteClip,double angle, SDL_RendererFlip flip) { /*position->w *= scale; position->h *= scale;*/ //Copy Texture to destination inclusive rotation and flipping SDL_RenderCopyEx(renderer, texture, spriteClip, position,angle,NULL,flip); }
true
c41533850a60850cb0cf379ee2fb01c33dee96fa
C++
Ereimei/COMP345-Risky-Business
/dice/Diepool.h
UTF-8
1,173
2.90625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Diepool.h * Author: James * * Created on September 25, 2017, 9:20 PM */ #ifndef DIEPOOL_H #define DIEPOOL_H class Diepool{ private: //dice array, set of 3 dice int dice[3]; //counters for each number value, and total dice rolls int num1, num2, num3, num4, num5, num6, numt; public: int getNum1(){return num1;} int getNum2(){return num2;} int getNum3(){return num3;} int getNum4(){return num4;} int getNum5(){return num5;} int getNum6(){return num6;} int getNumt(){return numt;} int getDie1(){return dice[0];} int getDie2(){return dice[1];} int getDie3(){return dice[2];} void setDie1(int d6){dice[0] = d6;} void setDie2(int d6){dice[1] = d6;} void setDie3(int d6){dice[2] = d6;} void roll(int n); void showPercentage(); void sortDice(int numDice); Diepool(); }; #endif /* DICE_H */
true
08223b86e1d08e566eea8960cf68a44e18c02921
C++
amsiljak/c9-Projects
/Programming-Techniques/T1/Z3/main.cpp
UTF-8
857
3.1875
3
[]
no_license
//TP 2016/2017: Tutorijal 1, Zadatak 3 #include <iostream> #include <cmath> #include <iomanip> int main () { int a,b; std::cout<<"Unesite pocetnu i krajnju vrijednost: "; std::cin>>a>>b; std::cout<<std::endl<<"+---------+----------+----------+-----------+"<<std::endl; std::cout<<"| Brojevi | Kvadrati | Korijeni | Logaritmi |"<<std::endl<<"+---------+----------+----------+-----------+"<<std::endl; while(a<=b) { std::cout<<"| "<<std::left<<std::setw(8)<<a<<"|"<<std::right<<std::setw(9)<<a*a; std::cout<<" |"<<std::setw(9)<<std::fixed<<std::setprecision(3)<<std::sqrt(a)<<" |"<<std::setw(10)<<std::fixed<<std::setprecision(5)<<std::log(a)<<" |"<<std::endl; a++; } std::cout<<"+---------+----------+----------+-----------+"<<std::endl; return 0; }
true
b5cf3ae654ba833563ce08fd37835a01fae8c7b2
C++
BaldPulse/word_stemming_and_matching
/core/Worddata.h
UTF-8
1,804
2.609375
3
[]
no_license
#ifndef WORDDATA_H #define WORDDATA_H #include <iostream> #include <fstream> #include <string> #include <vector> #include <cmath> #include <unordered_set> #include <iterator> #include "language.h" #include "Wordgraph.h" #include "files.h" #include "colors.h" class Worddata{ public: Worddata(); ~Worddata(); void testWorddata(); void storemeta();//store data to meta file void fetchmeta();//retrieve data from meta file void findmatch();//finds possible matches void reviewMatch();//lets operator decide for certain matches void fetchdata(bool print = false, std::string wordfilename ="/home/ztang/Documents/words_barron/processeddata/barron.tsv", std::string textfilename="/home/ztang/Documents/words_barron/processeddata/wonders.csv");//get data from file private: int fetchword(std::string filename = "/home/ztang/Documents/words_barron/processeddata/barron.tsv", bool print = false); int fetchtext(std::string filename ="/home/ztang/Documents/words_barron/processeddata/wonders.csv", bool print = false); void processword(const std::string& word, stdwordUnit* parent, Wordgraph* data, bool print = false); int checkforvocab(std::pair<std::string, int> word, std::pair<std::string, int> text); int checkparent(int wordN, int textN); Wordgraph* words; Wordgraph* texts; language* lang; std::unordered_set<int>* possibleMatches; //list of possible matches std::string* existingMatches; //array of existing matches int nExistingMatches; std::vector<std::pair<stdwordUnit*, stdwordUnit*>>* unresolved; std::vector<std::pair<stdwordUnit*, stdwordUnit*>>* addedWords; }; #endif std::pair<int, int> match(std::string wordA, std::string wordB);//returns the max number of consecutive matches and the location of the first matching string
true
634fb5849de2839dfaf2ddbd6928ccf209c990df
C++
carlosv5/MasterMind
/models/proposedCombination.cpp
UTF-8
1,503
3.03125
3
[]
no_license
#include <iostream> #include <cstdlib> #include <set> #include <assert.h> #include "proposedCombination.hpp" ProposedCombination::ProposedCombination() { } void ProposedCombination::createCombination() { combination = new char[SIZE_COMBINATION]; results = new int[SIZE_RESULTS]; } void ProposedCombination::calculateResult(SecretCombination secretCombination) { int black = 0; int white = 0; std::set<char> setColors; char *copyOfCombination = new char[SIZE_COMBINATION]; for (int i = 0; i < SIZE_COMBINATION; i++) { copyOfCombination[i] = combination[i]; } for (int i = 0; i < SIZE_COMBINATION; i++) { if (secretCombination.getCombination()[i] == copyOfCombination[i]) { black++; copyOfCombination[i] = (char)NULL; } else { setColors.insert(secretCombination.getCombination()[i]); } } for (int i = 0; i < SIZE_COMBINATION; i++) { if (setColors.count(copyOfCombination[i]) > 0) { white++; } } delete copyOfCombination; results[INDEX_BLACK_RESULT] = black; results[INDEX_WHITE_RESULT] = white; } bool ProposedCombination::isWinner() { if (results[INDEX_BLACK_RESULT] == SIZE_COMBINATION) { return true; } return false; } void ProposedCombination::clear() { delete combination; delete results; } int * ProposedCombination::getResults(){ return this->results; }
true
49bbbc00b54efaea661fa23718d7aa9b8cafa3d3
C++
wlsvy/TIL
/Document/C++/Effective Modern C++/EffectiveModernCpp/Item31.h
UHC
6,735
3.265625
3
[]
no_license
#pragma once #include <iostream> #include <vector> #include <string> #include <array> #include <functional> //⺻ 带 ϶ namespace Item31 { /* ǥ(lambda expression) ̸ ״ ϳ ǥ, ҽ ڵ Ϻ̴ Ŭ(closure) ٿ ü̴. (capture mode) , Ŭ 纻 ְ Ϳ ִ. ڵ std::find_if ȣ⿡ Ŭ std::find_if ° μ ޵Ǵ ü̴. Ŭ Ŭ Ŭ Ŭ Ѵ. ٿ Ϸ Ŭ Ŭ . ش Ŭ Ŭ Լ ɵ ȴ. */ using FilterContainer = std::vector<std::function<bool(int)>>; FilterContainer filters; namespace Case0 { /* ⺻ ĸĴ ִ. ⺻ ٿ Ŭ , ĸĵ Ű ӵǸ, Ŭ Ҵ´. */ template <typename C> void workWithContainer(const C& container) { auto divisor = 5; if (std::all_of(std::begin(container), std::end(container), [&](const auto& value) { return value % divisor == 0; })) { //... } else { //... } } /* ƿ ȿ ٸ ƿ ϴٰ . ĸĴ ٰ ȿ ̴, static ƴ (Ű ) ȴ. */ inline void RunSample() { auto divisor = 5; filters.emplace_back( [&](int value) { return value % divisor == 0; } // ! divisor ִ. ); /* addDivisorFilter Լ , divisor ȯȴ. */ filters.emplace_back( [&divisor](int value) { return value % divisor == 0; } // ! divisor ִ. ); /* , ĸĴ ǥ ȿ divisor Ѵٴ Ȯ Ÿٴ ִ. */ } class Widget { public: void f() { auto divisor = 5; filters.emplace_back( [&](int value) { return value % divisor == 0; } ); filters.back()(3); } private: int m_Val = 3; }; } namespace Case1 { class Gadget { public: Gadget() { std::cout << "default ctor" << std::endl; } Gadget(const Gadget& rhs) { std::cout << "copy ctor" << std::endl; } Gadget(Gadget&& rhs) { std::cout << "move ctor" << std::endl; } }; class Widget { public: void f() { Gadget gadget; filters.emplace_back( [gadget](int value) // ߻ { auto g = gadget; return value % 5 == 0; } ); } }; inline void RunSample() { Widget w; w.f(); } } namespace Case2 { /* ⺻ (Ư this) , ٰ ڱ ϰ̶ ظ θ ִ. */ class Widget { public: void f() { /*filters.emplace_back( [divisor](int value) { return value % divisor == 0; } );*/ // , divisor ĸ . filters.emplace_back( [=](int value) { return value % divisor == 0; } ); /* ĸ divisor Ǵ, Widgetü ֱⰡ divisor ? => ƴϴ ٰ ȿ ̴, static ƴ (Ű ) ȴ. Widget::f divisor ƴ϶ Ŭ ̹Ƿ ĸĵ . ǥĿ [=] ϰ ִ Widget this ̴. */ auto thisObj = this; filters.emplace_back( [thisObj](int value) { return value % thisObj->divisor == 0; } ); /* ٲ. ü ıǰ this Ͱ Ҹ ü ȣѴٸ ൿ Ѵ. */ filters.emplace_back( [divisor = this->divisor](int value) { return value % divisor == 0; } ); /* c++14 ؼ(Ϲȭ ĸ) ϰ . */ } private: int divisor = 5; }; inline void RunSample() { Widget w; w.f(); } } namespace Case3 { /* ⺻ ĸ ٸ , ش Ŭ ڱ ϰ̰ Ŭ ٱ Ͼ ȭκ ݸǾ ִٴ ظ θ ִٴ ̴. ֳϸ ٰ Ű (ĸİ )Ӹ ƴ϶ Ⱓ(static storage duration) ü ֱ ̴. Ⱓ ü ȿ , ĸ . ׷ ⺻ ĸ ǥ ġ ׷ ü ĸĵȴٴ ش. */ void RunSample(void) { static auto divisor = 5; // filters.emplace_back( [=](int value) { return value % divisor == 0; } // ƹ͵ ĸ ʴ´. ĪѴ. ); /* RunSample ȣ divisor ϸ, Լ ؼ filters ߰ ٴ ٸ ൿ(divisor ϴ) ̰ ȴ. ʿ ⺻ 带 ʴ´ٸ ó ū ڵ尡 赵 . */ ++divisor; } } }
true
748fc6080c5334f0d75446025e86d7f3827b7b71
C++
parthparikh02/health-monitoring-system
/IOT CODE/MAX30100_Receiver/MAX30100_Receiver.ino
UTF-8
3,827
2.546875
3
[]
no_license
#include <ESP8266WiFi.h> #include <espnow.h> #include <Wire.h> // Structure example to receive data // Must match the sender structure typedef struct struct_message { int id; float x; float y; } struct_message; float spo2,hrate; // Create a struct_message called myData struct_message myData; WiFiClient client; // Create a structure to hold the readings from each board struct_message board1; //struct_message board2; const int httpPort = 80; const char* ssid = "warrior1232"; const char* password = "123456789@"; const char* host = "healthmonitoring.tech"; // Create an array with all the structures struct_message boardsStruct[1] = {board1}; // Callback function that will be executed when data is received void OnDataRecv(uint8_t * mac_addr, uint8_t *incomingData, uint8_t len) { char macStr[18]; Serial.print("Packet received from: "); snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); Serial.println(macStr); memcpy(&myData, incomingData, sizeof(myData)); Serial.printf("Board ID %u: %u bytes\n", myData.id, len); // Update the structures with the new incoming data boardsStruct[myData.id-1].x = myData.x; boardsStruct[myData.id-1].y = myData.y; //Serial.printf("x value: %d \n", boardsStruct[myData.id-1].x); //Serial.printf("y value: %d \n", boardsStruct[myData.id-1].y); Serial.println(); } void cwifi(){ // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); WiFi.disconnect(); // Init ESP-NOW if (esp_now_init() != 0) { Serial.println("Error initializing ESP-NOW"); return; } // Once ESPNow is successfully Init, we will register for recv CB to // get recv packer info esp_now_set_self_role(ESP_NOW_ROLE_SLAVE); esp_now_register_recv_cb(OnDataRecv); } void wifi(){ WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); Serial.print("Netmask: "); Serial.println(WiFi.subnetMask()); Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP()); if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } String url_oxygen = "/authentication/oxygen.php?oxygen="+String(spo2); Serial.print("Requesting URL: "); Serial.println(url_oxygen); client.print(String("GET ") + url_oxygen + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); while(client.available()){ String line = client.readStringUntil('\r'); Serial.print(line); } if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } String url_pulse = "/authentication/pulse.php?pulse="+String(hrate); Serial.print("Requesting URL: "); Serial.println(url_pulse); client.print(String("GET ") + url_pulse + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); while(client.available()){ String line = client.readStringUntil('\r'); Serial.print(line); } Serial.println(); Serial.println("closing connection"); } void setup() { // Initialize Serial Monitor Serial.begin(115200); cwifi(); } void loop(){ // Access the variables for each board float board1X = boardsStruct[0].x; float board1Y = boardsStruct[0].y; Serial.print("spo2:"); spo2 = board1X; Serial.println(spo2); Serial.print("hrate:"); hrate = board1Y; Serial.println(hrate); wifi(); delay(1000); cwifi(); delay(1000); }
true
1a2b40cbc325eb0b05638579e509b59a27e39e1b
C++
alen0216056/Computer_Graphic_Final_Project
/main.cpp
UTF-8
13,645
2.5625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <stddef.h> /* offsetof */ #include <string> #include <math.h> #include <time.h> #include "../GL/glew.h" #include "../GL/glut.h"" #include "../shader_lib/shader.h" #include "glm/glm.h" #include "parameter.h" extern "C" { #include "glm_helper.h" } void init(void); void display(void); void reshape(int width, int height); void keyboard(unsigned char key, int x, int y); void mouse(int button, int state, int x, int y); void idle(void); bool gluInvertMatrix(const float m[16], float invOut[16]); void sleepcp(int milliseconds); /*global variables*/ struct my_vertex { float position[3]; float normal[3]; float face_normal[3]; float texture[2]; }; GLMmodel *model; GLfloat light_pos[] = { 10.0, 10.0, 0.0 }; float eye_pos[] = { 0.0, 0.0, 3.0 }; bool timer_mode[10], show_center = true; int timer[10], center_index = 0; parameter* parameter_ptr; my_vertex* vertices; GLuint vertex_shader, fragment_shader, program, vbo_name; int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutCreateWindow("Final Project"); glutReshapeWindow(800, 800); glewInit(); parameter_ptr = new parameter(argc, argv); init(); glutReshapeFunc(reshape); glutDisplayFunc(display); glutIdleFunc(idle); glutKeyboardFunc(keyboard); glutMouseFunc(mouse); glutMainLoop(); free(vertices); glmDelete(model); return 0; } void init(void) { //Initialize model model = glmReadOBJ(parameter_ptr->model_name().c_str()); glmUnitize(model); glmFacetNormals(model); glmVertexNormals(model, 90.0, GL_FALSE); print_model_info(model); //Compute the number of all triangles int triangle_num = 0; for (GLMgroup* group = model->groups; group; group = group->next) { triangle_num += group->numtriangles; } //Initialize vertex structure array vertices = (my_vertex*)malloc(triangle_num * 3 * sizeof(my_vertex)); triangle_num = 0; for (GLMgroup* group = model->groups; group; group = group->next) { for (int i = 0; i < group->numtriangles; i++) { GLMtriangle* triangle_tmp = &model->triangles[group->triangles[i]]; for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { vertices[3 * (i + triangle_num) + j].position[k] = model->vertices[3 * triangle_tmp->vindices[j] + k]; vertices[3 * (i + triangle_num) + j].normal[k] = model->normals[3 * triangle_tmp->nindices[j] + k]; vertices[3 * (i + triangle_num) + j].face_normal[k] = model->facetnorms[3 * triangle_tmp->findex + k]; } for (int k = 0; k < 2; k++) { vertices[3 * (i + triangle_num) + j].texture[k] = model->texcoords[2 * triangle_tmp->tindices[j] + k]; } } } triangle_num += group->numtriangles; } //Generate vertex buffer object and pass data into GPU memory glGenBuffers(1, &vbo_name); glBindBuffer(GL_ARRAY_BUFFER, vbo_name); glBufferData(GL_ARRAY_BUFFER, triangle_num * 3 * sizeof(my_vertex), vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); //0 is GLindex glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(my_vertex), (void*)(offsetof(my_vertex, position))); //first 0 is GLindex glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(my_vertex), (void*)(offsetof(my_vertex, normal))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(my_vertex), (void*)(offsetof(my_vertex, face_normal))); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(my_vertex), (void*)(offsetof(my_vertex, texture))); //compile vertex shader, fragment shader, and create program vertex_shader = createShader(parameter_ptr->vertex_shader_name().c_str(), "vertex"); fragment_shader = createShader(parameter_ptr->fragment_shader_name().c_str(), "fragment"); program = createProgram(vertex_shader, fragment_shader); //initial timer for (int i = 0; i < 10; i++) { timer[i] = 1; timer_mode[i] = true; } } void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, 1.0, 1e-2, 1e2); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(eye_pos[0], eye_pos[1], eye_pos[2], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); // Write your code here glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); GLfloat projection_matrix[16]; glGetFloatv(GL_PROJECTION_MATRIX, projection_matrix); GLfloat modelview_matrix[16]; glGetFloatv(GL_MODELVIEW_MATRIX, modelview_matrix); GLfloat inverse_modelview_matrix[16]; gluInvertMatrix(modelview_matrix, inverse_modelview_matrix); GLint texture_location = glGetUniformLocation(program, "texture"); GLint ambient_location = glGetUniformLocation(program, "ambient"); GLint diffuse_location = glGetUniformLocation(program, "diffuse"); GLint specular_location = glGetUniformLocation(program, "specular"); GLint shininess_location = glGetUniformLocation(program, "shininess"); GLint use_texture_location = glGetUniformLocation(program, "use_texture"); glUseProgram(program); glUniformMatrix4fv(glGetUniformLocation(program, "Projection"), 1, GL_FALSE, projection_matrix); glUniformMatrix4fv(glGetUniformLocation(program, "Modelview"), 1, GL_FALSE, modelview_matrix); glUniformMatrix4fv(glGetUniformLocation(program, "Inverse_Modelview"), 1, GL_FALSE, inverse_modelview_matrix); glUniform3f(glGetUniformLocation(program, "eye_pos"), eye_pos[0], eye_pos[1], 3.0); glUniform3fv(glGetUniformLocation(program, "light_pos"), 1, light_pos); glUniform1iv(glGetUniformLocation(program, "timer"), 10, timer); glUniform1i(glGetUniformLocation(program, "center_num"), parameter_ptr->get_center_number()); for (int i = 0; i < 10; i++) { string str = "center[" + to_string(i) + "]"; glUniform3fv(glGetUniformLocation(program, str.c_str()), 1, parameter_ptr->get_center_position(i)); str = "center_normal[" + to_string(i) + "]"; glUniform3fv(glGetUniformLocation(program, str.c_str()), 1, parameter_ptr->get_center_normal(i)); str = "radius[" + to_string(i) + "]"; glUniform1f(glGetUniformLocation(program, str.c_str()), parameter_ptr->get_radius(i)); } int triangle_num = 0; for (GLMgroup* group = model->groups; group; group = group->next) { glUniform4fv(ambient_location, 1, model->materials[group->material].ambient); glUniform4fv(diffuse_location, 1, model->materials[group->material].diffuse); glUniform4fv(specular_location, 1, model->materials[group->material].specular); glUniform1f(shininess_location, model->materials[group->material].shininess); if (model->materials[group->material].map_diffuse != GLuint(-1)) { glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, model->textures[model->materials[group->material].map_diffuse].id); glUniform1i(texture_location, 0); glUniform1i(use_texture_location, 1); } else { glUniform1i(use_texture_location, 0); } glDrawArrays(GL_TRIANGLES, triangle_num * 3, group->numtriangles * 3); glBindTexture(GL_TEXTURE_2D, NULL); triangle_num += group->numtriangles; } glUseProgram(0); if (show_center) { glColor3f(1, 1, 1); glPointSize(10); glBegin(GL_POINTS); for (int i = 0; i<parameter_ptr->get_center_number(); i++) glVertex3fv(parameter_ptr->get_center_position(i)); glEnd(); } for (int i = 0; i < 10; i++) { if (timer_mode[i]) { timer[i]++; if (timer[i] == 120) timer_mode[i] = false; } else { timer[i]--; if (timer[i] == 1) timer_mode[i] = true; } } glDisable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glutSwapBuffers(); sleepcp(10); } void reshape(int width, int height) { glViewport(0, 0, width, height); } void keyboard(unsigned char key, int x, int y) { switch (key) { case 27://ESC exit(0); break; case 'd': eye_pos[0] += 0.1; break; case 'a': eye_pos[0] -= 0.1; break; case 'w': eye_pos[1] += 0.1; break; case 's': eye_pos[1]-= 0.1; break; case 9: //tab show_center = !show_center; break; default: if ('0' <= key && key <= '9') { if (key - '0' < parameter_ptr->get_center_number()) { center_index = key - '0'; printf("center index %d\n", center_index); } } break; } } void mouse(int button, int state, int x, int y) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { GLdouble modelview[16]; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); GLdouble projection[16]; glGetDoublev(GL_PROJECTION_MATRIX, projection); GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); GLfloat z; y = viewport[3] - y - 1; glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); //printf("x: %d y: %d z: %f\n", x, y, z); double center[3]; gluUnProject(x, y, z, modelview, projection, viewport, &center[0], &center[1], &center[2]); parameter_ptr->set_center_position(center_index, center); //printf("%lf %lf %lf\n", parameter_ptr->get_center_position(0)[0], parameter_ptr->get_center_position(0)[1], parameter_ptr->get_center_position(0)[2]); double distance, min_distance = 0xffffffff; for (int i = 0; i < model->numvertices; i++) { distance = pow((model->vertices[i * 3] - center[0]) * (model->vertices[i * 3] - center[0]) + (model->vertices[i * 3 + 1] - center[1]) * (model->vertices[i * 3 + 1] - center[1]) + (model->vertices[i * 3 + 2] - center[2]) * (model->vertices[i * 3 + 2] - center[2]), 0.5); if (distance < min_distance) { parameter_ptr->set_center_normal(center_index, &model->normals[i * 3]); min_distance = distance; } } timer[center_index] = 1; timer_mode[center_index] = true; parameter_ptr->set_radius(center_index, 0.0f); printf("center normal:%f %f %f\n", parameter_ptr->get_center_normal(center_index)[0], parameter_ptr->get_center_normal(center_index)[1], parameter_ptr->get_center_normal(center_index)[2]); } break; case GLUT_RIGHT_BUTTON: if (state == GLUT_DOWN) { GLdouble modelview[16]; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); GLdouble projection[16]; glGetDoublev(GL_PROJECTION_MATRIX, projection); GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); GLfloat z; y = viewport[3] - y - 1; glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); //printf("x: %d y: %d z: %f\n", x, y, z); double center[3]; gluUnProject(x, y, z, modelview, projection, viewport, &center[0], &center[1], &center[2]); parameter_ptr->set_radius(center_index, center); printf("radius %f\n", parameter_ptr->get_radius(center_index)); } break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { } break; default: break; } } void idle(void) { glutPostRedisplay(); } bool gluInvertMatrix(const float m[16], float invOut[16]) { double inv[16], det; int i; inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10]; inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10]; inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9]; inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9]; inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10]; inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10]; inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9]; inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9]; inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6]; inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6]; inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5]; inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5]; inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6]; inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6]; inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5]; inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]; det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12]; if (det == 0) return false; det = 1.0 / det; for (i = 0; i < 16; i++) invOut[i] = inv[i] * det; return true; } void sleepcp(int milliseconds) //sleep 10^-3 second { clock_t time_end; time_end = clock() + milliseconds * CLOCKS_PER_SEC / 1000; while (clock() < time_end) { } }
true
b6a5de81da80e55f2b4c69ad1d862677acb3ddb3
C++
AlexBolotsin/simple_event_manager
/textevent.cpp
UTF-8
218
2.5625
3
[]
no_license
#include "textevent.h" #include <iostream> TextEvent::TextEvent() { } void TextEvent::execute() { std::cout << text << std::endl; } void TextEvent::setText(std::string text) { this->text = text; }
true
60a3f29745d37fb796a0a6722c0a1afc0af0da88
C++
ccmccooey/Game_Physics
/Assignment3/PhysicsProject/GroundForceGenerator.h
UTF-8
523
2.671875
3
[]
no_license
#ifndef _GROUND_FORCE_GENERATOR_H #define _GROUND_FORCE_GENERATOR_H #define DEFAULT_GROUND_FORCE 2.0f #include "Vector3f.h" #include "ForceGenerator.h" class GroundForceGenerator :public ForceGenerator { private: float mGravity; //amount of gravity public: GroundForceGenerator(); GroundForceGenerator(float gravity); ~GroundForceGenerator(); float GetGravity() const; void SetGravity(float gravity); void ApplyForce(Particle* particle, double t); void ApplyForce(RigidBody* rigidBody, double t); }; #endif
true
6c05ba76b5243de85c29a587899d2bf38fb20852
C++
OpenRobotX/Lernkurs
/Lösungen/Loesung_04_-_Einfacher_Taschenrechner/Loesung_04_-_Einfacher_Taschenrechner.ino
UTF-8
903
2.890625
3
[]
no_license
/* * OpenRobotX Schullernkurs * Lösung zum Projekt aus Lektion 04 - Einfacher Taschenrechner */ void setup() { Serial.begin(9600); } void loop() { // Es wird eine float benötigt, da wir die Zahlen miteinander teilen float ersteZahl = 5; float zweiteZahl = 7; float ergebnis; // 1. Lösungsweg Serial.println("5 + 7 = 12"); // 2. Lösungsweg Serial.print(ersteZahl); Serial.print(" - "); Serial.print(zweiteZahl); Serial.print(" = "); Serial.println(ersteZahl - zweiteZahl); // 3. Lösungsweg ergebnis = ersteZahl * zweiteZahl; Serial.print(ersteZahl); Serial.print(" * "); Serial.print(zweiteZahl); Serial.print(" = "); Serial.println(ergebnis); // 4. Lösungsweg ergebnis = ersteZahl / zweiteZahl; Serial.print("5 / 7 = "); Serial.println(ergebnis); // Leerzeile Serial.println(""); }
true
0e9702946b7b441a3d8de95c44cfa45cd6bf7817
C++
chhetri28/September-challenge-Leetcode
/Day 29.cpp
UTF-8
1,482
3.453125
3
[]
no_license
// Word Break /* Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. Note: The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not contain duplicate words. Example 1: Input: s = "leetcode", wordDict = ["leet", "code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code". Example 2: Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: true Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word. Example 3: Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] Output: false */ class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { int n=s.length(); int dp[n+1]; memset(dp,0,sizeof dp); dp[n]=1; unordered_set<string>dict; for(auto w:wordDict){ dict.insert(w); } for(int i=n-1;i>=0;i--){ string word; for(int j=i;j<n;j++){ word.push_back(s[j]); if(dict.find(word)!=dict.end()){ if(dp[j+1]){ dp[i]=1; } } } } return dp[0]; } };
true
c9584f2688adbaef828dd29025759136a974b401
C++
nogsp/UVa-solved-problems
/10684 The jackpot.cpp
UTF-8
489
2.5625
3
[]
no_license
#include <bits/stdc++.h> #define ll long long #define pb push_back #define endl '\n' using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll t; while(cin >> t, t != 0) { ll n = t; ll sum = 0, resp = -1; for(ll i = 1; i <= n; i++) { ll val; cin >> val; sum += val; resp = max(resp, sum); if(sum < 0) sum = 0; } if(resp <= 0) cout << "Losing streak." << endl; else cout << "The maximum winning streak is " << resp << "." << endl; } }
true
f855bbce17a2045cd33cfae487c0de57fde67d91
C++
SangeethaPrabhu2021/Algorithms-For-Software-Developers
/Largest Number.cpp
UTF-8
517
3.0625
3
[ "BSD-2-Clause" ]
permissive
class Solution { public: static bool comp(string a,string b){ string ab=a.append(b); string ba=b.append(a); bool res=(ab>ba)? true: false; return res; } string largestNumber(vector<int>& nums) { vector<string>s; for(int i:nums){ s.push_back(to_string(i)); } sort(s.begin(),s.end(),comp); string str=""; for(int i=0;i<s.size();i++){ str+=s[i]; } return str[0]=='0'? "0" : str; } };
true
187a76d6d4319e813c5a0d72459f30a6a785d1a9
C++
andrii-venher/TicTacToe
/TicTacToe/Constants.h
UTF-8
1,438
2.609375
3
[]
no_license
#pragma once #include <iostream> #include <Windows.h> #include <string> using namespace std; const HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); const int FIELD_SIZE = 3; const int IMAGE_HEIGHT = 7; const int IMAGE_WIDTH = 13; const string X_IMAGE[IMAGE_HEIGHT] = { "* *" , " * * " , " * * " , " * " , " * * " , " * * " , "* *" }; const string O_IMAGE[IMAGE_HEIGHT] = { " *********** " , "* *" , "* *" , "* *" , "* *" , "* *" , " *********** " }; static const string EMPTY_IMAGE[IMAGE_HEIGHT] = { " " , " " , " " , " " , " " , " " , " " }; static const int FIELD_HEIGHT = FIELD_SIZE * (IMAGE_HEIGHT + 1) + 1; static const int FIELD_WIDTH = FIELD_SIZE * (IMAGE_WIDTH + 1) + 1; enum Colors { FULL_WHITE = 255, WHITE = 7, RED = 12, BLUE = 9, GREEN = 10, YELLOW = 14, FULL_YELLOW = 238 }; enum Scores { PLAYER_SCORE = -100, COMP_SCORE = 100, DRAW_SCORE = 0 }; enum Signs { EMPTY_SIGN = -1, O_SIGN = 0, X_SIGN = 1, HINT = 2 }; enum States { PLAYER_WON = 1, COMP_WON = 2, DRAW_STATE = 3, NOT_END = 4 }; enum Turns { PLAYER_TURN = true, COMP_TURN = false }; enum Difficulties { EASY = 1, MID = 2, HARD = 3 };
true
8a6df21d06d8e8f3d47638920cb1f82b5c9c6ad6
C++
moyanez/laba4
/main.cpp
UTF-8
2,043
3.203125
3
[]
no_license
#include <iostream> #include <stdint.h> using namespace std; char nibble_to_hex(uint8_t i) { switch (i) { case 0: return '0'; break; case 1: return '1'; break; case 2: return '2'; break; case 3: return '3'; break; case 4: return '4'; break; case 5: return '5'; break; case 6: return '6'; break; case 7: return '7'; break; case 8: return '8'; break; case 9: return '9'; break; case 10: return 'a'; break; case 11: return 'b'; break; case 12: return 'c'; break; case 13: return 'd'; break; case 14: return 'e'; break; case 15: return 'f'; break; } } void print_in_hex(uint8_t byte) { cout<<nibble_to_hex (byte>>4); cout<<nibble_to_hex (byte&0xf); } const uint8_t* as_bytes (const void* data) { return reinterpret_cast <const uint8_t*>(data); } void print_in_hex(const void* data, size_t size) { const uint8_t* bytes = as_bytes(data); for (size_t i = 0; i < size; i++) { print_in_hex(bytes[i]); if ((i + 1) % 16 == 0) { cout << '\n'; } else { cout << ' '; }; } } char bit_digit (uint8_t byte, uint8_t bit) { if (byte && (0x1<<bit)) { return '1'; } return '0'; } void print_in_binary(uint8_t byte) { for (int i=8;i<0;i--) cout<<bit_digit(byte,i); } int main () { uint8_t u8=42; uint16_t u16=42; uint32_t u32=42; print_in_hex(&u8, sizeof(u8)); print_in_hex(&u16, sizeof(u16)); print_in_hex(&u32, sizeof(u32)); return 0; }
true
ab5ee868241f93fba47a2fac8fb3a6aa8830fba0
C++
DesertFoxee/HandleInputSFML
/InputProcess/Random.cpp
UTF-8
826
3.359375
3
[]
no_license
#include "Random.h" float Random::floatUniform(float min, float max) { std::random_device dv; std::mt19937 rd(dv()); std::uniform_real_distribution<float> dist(min, max); return dist(rd); } int Random::intUniform(int min, int max) { std::random_device dv; std::mt19937 rd(dv()); std::uniform_int_distribution<> dis(min, max); return dis(rd); } template <typename T> T Random::normal(T min, T max) { if (std::is_same<int, T>::value || std::is_same<float, T>::value || std::is_same<double, T>::value) { std::random_device dv; std::mt19937 rd(dv()); std::normal_distribution<> dis((max + min) / 2, (max - min) / 2); return (T)dis(rd); } return (T)0; } template int Random::normal<int>(int, int); template float Random::normal<float>(float, float); template double Random::normal<double>(double, double);
true
f0300e295460d6b304ddbdb28e46eea36df77219
C++
wwojtas/MyWallet
/FileWithUsers.h
UTF-8
581
2.65625
3
[]
no_license
#ifndef FILEWITHUSERS_H #define FILEWITHUSERS_H #include <iostream> #include <vector> #include "User.h" #include "AuxiliaryMethods.h" #include "Markup.h" using namespace std; class FileWithUsers { vector <User> users; const string NAME_OF_FILE_WITH_USERS; int loggedInUserId; string getNameOfFileWithUsers(); public: FileWithUsers( string nameOfFileWithUsers ) : NAME_OF_FILE_WITH_USERS( nameOfFileWithUsers ) { }; void addUserToFile( User user ); vector <User> loadUsersFromFile(); void changePassword( int, string ); }; #endif
true
e8c4c6b42acfb1e8c31ab4dd2aaa1f8e14017531
C++
gochev99/Cplusplus
/Data Structures/Circular Linked List/CircularLinkedList.inl
UTF-8
2,988
3.84375
4
[]
no_license
#pragma once template <typename T> void CircularList<T>::copy(const CircularList& other) { Node<T>* it = other.first; if(it != nullptr) { do { push_back(it->data); it = it->next; } while(it != other.first); } } template <typename T> void CircularList<T>::erase() { while(!isEmpty()) { pop_front(); } } template <typename T> CircularList<T>::CircularList() : first(nullptr), last(nullptr), size(0) {} template <typename T> CircularList<T>::CircularList(const CircularList& other) { copy(other); } template <typename T> CircularList<T>& CircularList<T>::operator=(const CircularList& other) { if(this != &other) { erase(); copy(other); } return *this; } template <typename T> CircularList<T>::~CircularList() { erase(); } template <typename T> void CircularList<T>::push_back(const T& data) { Node<T>* newNode = new Node<T>(data); if(isEmpty()) { first = last = newNode; last->next = first; } else { last->next = newNode; last = newNode; newNode->next = first; } size++; } template <typename T> void CircularList<T>::pop_front() { if(isEmpty()) { throw std::runtime_error("Cannot pop from an empty list"); } if(first->next == first) { delete first; first = last = nullptr; } else { Node<T>* tmp = first; first = first->next; last->next = first; delete tmp; } size--; } template <typename T> void CircularList<T>::pop_after(Node<T>* iter) { if(iter == nullptr) { throw std::invalid_argument("Invalid node to pop after!"); } if(size == 1) { delete first; first = nullptr; last = nullptr; size--; return; } if(iter->next == first) { first = first->next; } if(iter->next == last) { last = iter; } Node<T>* tmp = iter->next; iter->next = iter->next->next; delete tmp; size--; } template <typename T> bool CircularList<T>::isEmpty() const { return size == 0; } template <typename T> size_t CircularList<T>::getSize() const { return size; } template <typename T> Node<T>*& CircularList<T>::getFirst() { if(isEmpty()) { throw std::runtime_error("List is empty, cannot get first!"); } return first; } template <typename T> Node<T>*& CircularList<T>::getLast() { if(isEmpty()) { throw std::runtime_error("List is empty, cannot get last!"); } return last; } template <typename T> void CircularList<T>::print() const { if(isEmpty()) std::cout << "Empty list printed."; Node<T>* it = first; if(first != nullptr) { std::cout << "-> "; do { std::cout << it->data << " -> "; it = it->next; } while(it != first); } }
true
539ed9f416893c1d5d388aacea8d620aa1c8ba35
C++
zymethyang/Hardware-RFID
/sketch_apr26a.ino
UTF-8
4,140
2.546875
3
[]
no_license
#include <SPI.h> #include <MFRC522.h> #include <ESP8266HTTPClient.h> #include <ESP8266WiFi.h> #define SS_PIN 2 //D4 #define RST_PIN 0 //D3 MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance. MFRC522::MIFARE_Key key; /** * Initialize. */ void setup() { Serial.begin(9600); // Initialize serial communications with the PC while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4) SPI.begin(); // Init SPI bus mfrc522.PCD_Init(); // Init MFRC522 card // Prepare the key (used both as key A and as key B) // using FFFFFFFFFFFFh which is the default at chip delivery from the factory // Khai báo key A và key B for (byte i = 0; i < 6; i++) { key.keyByte[i] = 0x11; } Serial.println(F("Mời quét thẻ")); Serial.print(F("Using key (for A and B):")); dump_byte_array(key.keyByte, MFRC522::MF_KEY_SIZE); Serial.println(); WiFi.begin("Temp", "987654321"); while (WiFi.status() != WL_CONNECTED) { //Khởi tạo kết nối WIFI delay(500); Serial.println("Đang chờ kết nối"); } pinMode(16, OUTPUT); } /** * Main loop. */ void loop() { // Look for new cards if ( ! mfrc522.PICC_IsNewCardPresent()) return; // Select one of the cards if ( ! mfrc522.PICC_ReadCardSerial()) return; // Show some details of the PICC (that is: the tag/card) //In ra UID thẻ Serial.print(F("Card UID:")); dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size); Serial.println(); //In ra loại thẻ Serial.print(F("PICC type: ")); MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak); Serial.println(mfrc522.PICC_GetTypeName(piccType)); // Check for compatibility if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K && piccType != MFRC522::PICC_TYPE_MIFARE_4K) { Serial.println(F("Chỉ sử dụng được với loại thẻ Mifare Classic.")); return; } byte sector = 1; //Chọn sector 1 byte blockAddr = 4; //Block chứa mã số sinh viên byte trailerBlock = 7; //Chứa key a key b.... MFRC522::StatusCode status; byte buffer[18]; byte size = sizeof(buffer); // Xác nhận sử dụng key A Serial.println(F("Đang xác nhận sử dụng key A...")); status = (MFRC522::StatusCode) mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid)); if (status != MFRC522::STATUS_OK) { Serial.print(F("PCD_Authenticate() failed: ")); Serial.println(mfrc522.GetStatusCodeName(status)); return; } // Đọc dữ liệu từ Block Serial.print(F("Đọc dữ liệu từ block ")); Serial.print(blockAddr); Serial.println(F(" ...")); status = (MFRC522::StatusCode) mfrc522.MIFARE_Read(blockAddr, buffer, &size); if (status != MFRC522::STATUS_OK) { Serial.print(F("MIFARE_Read() failed: ")); Serial.println(mfrc522.GetStatusCodeName(status)); } String item = String("http://backend-rfid.herokuapp.com/student/add/"); for(int k=0; k<8; k++){ item += String(buffer[k]); } Serial.println(item); HTTPClient http; //Khai báo đối tượng của class HTTPClient http.begin(item); //Chuẩn bị gửi dữ liệu http.addHeader("Content-Type", "text/plain"); //Specify content-type header int httpCode = http.GET(); String payload = http.getString(); //Get the response payload Serial.println(httpCode); //Print HTTP return code Serial.println(payload); //Print request response payload if(payload=="true"){ digitalWrite(16, HIGH); delay(3000); digitalWrite(16, LOW); } // Halt PICC mfrc522.PICC_HaltA(); // Stop encryption on PCD mfrc522.PCD_StopCrypto1(); } void dump_byte_array(byte *buffer, byte bufferSize) { for (byte i = 0; i < bufferSize; i++) { Serial.print(buffer[i], HEX); } }
true
a3aff628a271cc5f15d8c4344398b91ed14f8eb0
C++
YosysHQ/mcy
/gui/3rdparty/scintilla/src/UniqueString.h
UTF-8
802
3.015625
3
[ "ISC", "LicenseRef-scancode-scintilla" ]
permissive
// Scintilla source code edit control /** @file UniqueString.h ** Define UniqueString, a unique_ptr based string type for storage in containers ** and an allocator for UniqueString. **/ // Copyright 2017 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #ifndef UNIQUESTRING_H #define UNIQUESTRING_H namespace Scintilla { using UniqueString = std::unique_ptr<const char[]>; /// Equivalent to strdup but produces a std::unique_ptr<const char[]> allocation to go /// into collections. inline UniqueString UniqueStringCopy(const char *text) { if (!text) { return UniqueString(); } const size_t len = strlen(text); char *sNew = new char[len + 1]; std::copy(text, text + len + 1, sNew); return UniqueString(sNew); } } #endif
true
f4e1be5f1bc5a647f0a4fb4a8303446250a51dc8
C++
frozenca/PPP-CPP
/src/21/21-5.cpp
UTF-8
404
2.90625
3
[]
no_license
#include <iterator> template <typename InputIterator, typename T> [[nodiscard]] inline constexpr InputIterator find(InputIterator first, InputIterator last, const T& value) { typename std::iterator_traits<InputIterator>::difference_type r (0); for (; first != last; ++first) { if (*first == value) { break; } } return first; } int main() { }
true
71313983ee83f7656edfa6dd0563b09a8c4e3d55
C++
HackEduca/Mixly_Arduino
/mixly_arduino/arduino/portable/sketchbook/libraries/SevenSegmentTM1637/src/SevenSegmentFun.h
UTF-8
2,294
2.546875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only" ]
permissive
#ifndef SevenSegmentFun_H #define SevenSegmentFun_H #if ARDUINO >= 100 #include <Arduino.h> #else #include <WProgram.h> #endif #include "SevenSegmentTM1637.h" #include "SevenSegmentExtended.h" // COMPILE TIME USER CONFIG //////////////////////////////////////////////////// #define TM1637_SNAKE_DEFAULT_DELAY 50 // Snake step delay ms #define TM1637_BOUNCH_BALL_DEFAULT_DELAY 100 // Bounching ball delay ms #define TM1637_NIGHTRIDER_DEFAULT_DELAY 200 // Nightrider delay ms // // A // --- // * F | | B // X -G- // * E | | C // --- // D // X defines the colon (dots) and only applies to byte 1 (second from left) // BXGFEDCBA #define TM1637_CHAR_VERT_LEVEL B00110110 // || #define TM1637_CHAR_HOR_LEVEL_0 B00000000 #define TM1637_CHAR_HOR_LEVEL_1 B00001000 #define TM1637_CHAR_HOR_LEVEL_2 B01001000 #define TM1637_CHAR_HOR_LEVEL_3 B01001001 #define TM1637_CHAR_SNAKE_0 B00000001 #define TM1637_CHAR_SNAKE_1 B00000010 #define TM1637_CHAR_SNAKE_2 B00000100 #define TM1637_CHAR_SNAKE_3 B00001000 #define TM1637_CHAR_SNAKE_4 B00010000 #define TM1637_CHAR_SNAKE_5 B00100000 #define TM1637_CHAR_BALL_HIGH B01100011 #define TM1637_CHAR_BALL_LOW B01011100 class SevenSegmentFun : public SevenSegmentExtended { public: SevenSegmentFun(uint8_t pinClk, uint8_t pinDIO); void printLevelVertical(uint8_t level, bool leftToRight = true, uint8_t symbol = TM1637_CHAR_VERT_LEVEL); void printLevelVertical(uint8_t levels[TM1637_MAX_LINES*3], bool leftToRight = true); void printLevelHorizontal(uint8_t levels[4]); void scrollingText(const char* str, uint8_t repeats); void snake(uint8_t repeats = 1, uint16_t d = TM1637_SNAKE_DEFAULT_DELAY); void nightrider(uint8_t repeats = 10, uint16_t d = TM1637_NIGHTRIDER_DEFAULT_DELAY, uint8_t symbol = TM1637_CHAR_VERT_LEVEL); void bombTimer(uint8_t hours, uint8_t min, uint16_t speed = 60); void bombTimer(uint8_t hours, uint8_t min, uint16_t speed, char* str); void bouchingBall(uint16_t moves, uint16_t d, bool runForever = false); void printBall(const int8_t x, const int8_t y); void print4Bit(const uint8_t x, const uint8_t y, uint8_t symbol); private: }; #endif
true
72b9cdc424d05c4d4a685f9b4aa98c0cdb76a278
C++
fons/presentations
/20130226/functor.hpp
UTF-8
478
2.671875
3
[]
no_license
#ifndef H__FUNCTOR__H #define H__FUNCTOR__H template <template<typename T1> class F> struct functor { template<typename A, typename B> static std::function < F<B> (F<A>)> fmap(std::function <B (A)> f);; }; template <template<typename T1> class F> struct applicative_functor : public functor <F> { template <typename A> static F<A> pure(A val); template<typename A, typename B> static std::function < F<B> (F<A>)> apply(F <std::function<B(A)>> f ); }; #endif
true
17cff792cfb1d15ee93702bbdbda34eca84a2218
C++
btcup/sb-admin
/exams/2558/02204111/1/final/4_2_712_5520501670.cpp
UTF-8
933
3.109375
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; int main() { int i,j; double day1,day2,day3,day4,day5,total_pass,avg_num,largest_num; double A[4][5]; int sum=0; for(i=0;i<4;i++) { for(j=0;j<5;j++) { cin>> A[i][j]; } } cout<<"Give the number of passengers of day 1:"; cin>> day1; cout<<"Give the number of passengers of day 2:"; cin>> day2; cout<<"Give the number of passengers of day 3:"; cin>> day3; cout<<"Give the number of passengers of day 4:"; cin>> day4; cout<<"Give the number of passengers of day 5:"; cin>> day5; cout<<"Total passenger for air asia is :"; cin>>total_pass; cout<<"The average number of passengers for all days and all flights is :"; cin>>avg_num; cout<<"The largest number of passengers is :"; cin>>largest_num; system("pause"); return 0; }
true
6a7e77363b50e8f35aac08044ecb35a5bf053df2
C++
Brunoute25/Brunoute25
/C++/exercicios de repetição/impar.cpp
ISO-8859-1
358
2.65625
3
[]
no_license
#include<stdio.h> #include<locale.h> main(){ setlocale(LC_ALL,""); int res,i,par; while(i<=30){ i++; res=i%2; printf("\nResto da diviso: %i",res); if(res==0){ printf("\nO numero digitado par: %i",i); par++; } else{ printf("\nO numero digitado impar: %i",i); } } printf("\no total de numero pares so: %i",par); }
true
350fd218bf140ab78918ea7e3ad62b7f30a92c9f
C++
y-shindoh/algorithms_and_data_structure_for_pc
/c_05/q_119.cpp
UTF-8
1,211
3.625
4
[]
no_license
/* -*- coding: utf-8; tab-width: 4 -*- */ /** * @file q_119.cpp * @brief プログラミングコンテストのためのアルゴリズムとデータ構造p.119の問題の回答 * @author Yasutaka SHINDOH / 新堂 安孝 * @note see http://www.amazon.co.jp/dp/4839952957 . */ /* 問題: n個の整数を含む数列Sと、q個の異なる整数を含む数列Tを読み込み、 Tに含まれる整数の中でSに含まれるものの個数Cを出力するプログラムを作成してください。 */ #include <cstdio> #include <cassert> /** * 問題の回答 * @param[in] n 配列 @a S の要素数 * @param[in] S 探索対象の配列 * @param[in] q 配列 @a C の要素数 * @param[in] C 探索元の配列 * @return 一致した要素数 */ template<typename TYPE> size_t count(size_t n, const TYPE* S, size_t q, const TYPE* C) { assert(S); assert(C); size_t r(0); for (size_t i(0); i < n; ++i) { for (size_t j(0); j < q; ++j) { r += (size_t)(S[i] == C[j]); } } return r; } #define N 5 #define Q 3 /** * サンプル・コマンド */ int main() { int S[N] = {1, 2, 3, 4, 5}; int C[Q] = {3, 4, 1}; std::printf("%lu\n", count(N, S, Q, C)); return 0; }
true
0633ac9854b5ff8067064ee392ace6b9d3eb3d01
C++
akzk/algorithm
/buildTree.cpp
UTF-8
1,371
3.65625
4
[]
no_license
/* 剑指offer 7, lintcode 73, 重建二叉树 */ #include <vector> using namespace std; // Definition of TreeNode: class TreeNode { public: int val; TreeNode *left, *right; TreeNode(int val) { this->val = val; this->left = this->right = NULL; } } class Solution { /** *@param preorder : A list of integers that preorder traversal of a tree *@param inorder : A list of integers that inorder traversal of a tree *@return : Root of a tree */ public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { // write your code here return buildTreeHelper(preorder, inorder, 0, preorder.size()-1, 0, inorder.size()-1); } TreeNode* buildTreeHelper(vector<int> &preorder, vector<int> &inorder, int i1, int j1, int i2, int j2) { if (i1 > j1) return NULL; int val = preorder[i1]; TreeNode* node = new TreeNode(val); if (i1 < j1) { int middle = i2; while (inorder[middle] != val) middle++; int left_size = middle-i2; int right_size = j2-middle; node->left = buildTreeHelper(preorder, inorder, i1+1, i1+left_size, i2, i2+left_size-1); node->right = buildTreeHelper(preorder, inorder, i1+left_size+1, j1, i2+left_size+1, j2); } return node; } };
true
7217e9d99e78be33890cd54eee608dc333d643c0
C++
mycppfeed/Leetmap
/all_problems/Done/475_Heaters.cpp
UTF-8
4,306
3.671875
4
[]
no_license
/* Problem Description * Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses. Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters. So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters. Note: Numbers of houses and heaters you are given are non-negative and will not exceed 25000. Positions of houses and heaters you are given are non-negative and will not exceed 10^9. As long as a house is in the heaters' warm radius range, it can be warmed. All the heaters follow your radius standard and the warm radius will the same. Example 1: Input: [1,2,3],[2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. Example 2: Input: [1,2,3,4],[1,4] Output: 1 Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed. Solution: for each house find the nearest heater Find the max among those nearest heaters Also while doing the binary search in heaters this should not be done first = mid +1 because house is not a member of heaters array so heaters[mid] < house < heaters[mid+1] Tags Sort */ #include"header.h" class Solution { public: int find_nearest_heater(vector<int> &heaters, int first, int last, int k) { while(first < last) { if(last == first +1) { return abs(k - heaters[first]) < abs(heaters[last] - k) ? heaters[first] : heaters[last]; } int mid = first + (last - first)/2; if(heaters[mid] == k) { return heaters[mid]; } else if(heaters[mid] > k) { last = mid; } else { first = mid; } } return heaters[first]; } int findRadius(vector<int>& houses, vector<int>& heaters) { int house_sz = houses.size(); int heater_sz = heaters.size(); vector<int> min_dist_of_houses_from_heaters(house_sz); sort(heaters.begin(), heaters.end()); int start_pos = 0; for(int i = 0 ; i < house_sz; i++) { auto house = houses[i]; int nearest_h = find_nearest_heater(heaters, 0, heater_sz-1, house); min_dist_of_houses_from_heaters[i] = abs(house - nearest_h); } int res = INT_MIN; for(auto dist : min_dist_of_houses_from_heaters) { res = max(res, dist); } return res; } int findRadius2(vector<int>& houses, vector<int>& heaters) { int house_sz = houses.size(); int heater_sz = heaters.size(); vector<int> min_dist_of_houses_from_heaters(house_sz); sort(houses.begin(), houses.end()); sort(heaters.begin(), heaters.end()); int start_pos = 0; for(int i = 0 ; i < house_sz; i++) { auto house = houses[i]; // int nearest_h ; if(house <= heaters[0]) { nearest_h = heaters[0]; } else if(house > heaters[heater_sz-1]) { nearest_h = heaters[heater_sz-1]; } else { for(int j = start_pos ; j < heater_sz-1; j++) { if(house <= heaters[j+1]) { nearest_h = (house - heaters[j]) < (heaters[j+1] - house) ? heaters[j] : heaters[j+1]; start_pos = j; break; } } } min_dist_of_houses_from_heaters[i] = abs(house - nearest_h); } int res = INT_MIN; for(auto dist : min_dist_of_houses_from_heaters) { res = max(res, dist); } return res; } }; int main() { Solution S; //vector<int> houses({282475249,622650073,984943658,144108930,470211272,101027544,457850878,458777923}); //vector<int> heaters({823564440,115438165,784484492,74243042,114807987,137522503,441282327,16531729,823378840,143542612}); vector<int> houses({1,2,3}); vector<int> heaters({2}); cout << S.findRadius(houses, heaters); return 0; }
true
5ea82e9d6a517140f0908f034812db695557fc98
C++
guithin/BOJ
/3830/Main.cpp
UTF-8
967
2.828125
3
[]
no_license
#include<stdio.h> #include<memory.h> struct pos { int n, m; int ver[100010]; int val[100010]; int find(int x) { if (ver[x] == x)return x; int temp = ver[x]; ver[x] = find(ver[x]); val[x] += val[temp]; return ver[x]; } int main() { scanf("%d %d", &n, &m); if (n == 0 && m == 0)return 1; for (int i = 1; i <= n; i++)ver[i] = i; for (int cur = 1; cur <= m; cur++) { char temp[3] = { 0 }; scanf("%s", temp); if (temp[0] == '?') { int a, b; scanf("%d %d", &a, &b); if (find(a) != find(b)) { printf("UNKNOWN\n"); } else { printf("%d\n", val[a] - val[b]); } } else { int a, b, c; scanf("%d %d %d", &a, &b, &c); if (find(a) == find(b))continue; int t = find(a); ver[t] = b; val[t] = c - val[a]; } } return 0; } pos() { memset(ver, 0, sizeof(ver)); memset(val, 0, sizeof(val)); } }; int main() { while (1) { pos temp; if (temp.main())break; } return 0; }
true
456f1f92c2b570614664ee5fb4099e2c7583a5b0
C++
sexybear/Cpp_concurrency_in_practice
/test_and_set_TEST.cpp
UTF-8
526
3.328125
3
[]
no_license
#include <iostream> #include <atomic> #include <thread> #include <vector> #include <sstream> std::atomic_flag lock_stream = ATOMIC_FLAG_INIT; std::stringstream stream; void append_number(int x) { while(lock_stream.test_and_set()) { } stream << "thread#"<< x <<'\n'; lock_straem.clear(); } int main() { std::vector <std::thread> threads; for(int i = 1;i<=10;++i) { threads.push_back(std::thread(append_number,i)); } for(auto & th:threads) { th.join(); } std::cout << stream.str() << std::endl; return 0; }
true
f94b23fb4bd312c0b52e95a04acda60d4aca1c6a
C++
ssdemajia/LeetCode
/SudokuSolver.cpp
UTF-8
2,993
3.28125
3
[]
no_license
#include "inc.h" class Solution { public: void solveSudoku(vector<vector<char>>& board) { vector<vector<int> >row(9, vector<int>(9,0));//数i是否出现在行j中 vector<vector<int> >col(9, vector<int>(9,0));//数i是否出现在列j中 vector<vector<int> >box(9, vector<int>(9,0));//用于储存数i是否在宫j中 for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] != '.'){ int temp = board[i][j]-'0'-1;//temp需要减1,因为行列的范围是0~8 int b = i / 3 * 3 + j / 3;//i/3得到这是在以三行为一大行中的第几大行,加上列数则为宫数 row[temp][i]=col[temp][j]=box[temp][b]=1; } } } helper(board, row, col, box, 0, 0); } bool helper(vector<vector<char>>& board, vector<vector<int> > &row, vector<vector<int> >&col, vector<vector<int> >&box, int r,int c){ if (r == 9) return true;//到达最终结果,返回 if (c == 9) return helper(board, row, col, box, r+1, 0);//一行满了,那么将其换行 if (board[r][c] != '.') return helper(board, row, col, box, r, c+1); for (int k = 0; k < 9; k++){ int b = r / 3 * 3 + c / 3; if (!row[k][r] && !col[k][c] && !box[k][b]){ row[k][r]=col[k][c]=box[k][b]=1;//如果访问了,那么就把这个数的标记打上 board[r][c] = '0'+1+k; if (helper(board, row, col, box, r, c+1)) return true; row[k][r]=col[k][c]=box[k][b]=0;//如果这个k不对,那么把这个数标记清空 board[r][c] = '.'; } } } }; int main(int argc, char const *argv[]) { Solution so; vector<vector<char> > board1 = { {'5','3','.','.','7','.','.','.','.'}, {'6','.','.','1','9','5','.','.','.'}, {'.','9','8','.','.','.','.','6','.'}, {'8','.','.','.','6','.','.','.','3'}, {'4','.','.','8','.','3','.','.','1'}, {'7','.','.','.','2','.','.','.','6'}, {'.','6','.','.','.','.','2','8','.'}, {'.','.','.','4','1','9','.','.','5'}, {'.','.','.','.','8','.','.','7','9'} }; //".2.1.9...","..7...24.",".64.1.59.",".98...3..","...8.3.2.","........6","...2759.."] vector<vector<char> > board = { {'.','.','9','7','4','8','.','.','.'}, {'7','.','.','.','.','.','.','.','.'}, {'.','2','.','1','.','9','.','.','.'}, {'.','.','7','.','.','.','2','4','.'}, {'.','6','4','.','1','.','5','9','.'}, {'.','9','8','.','.','.','3','.','.'}, {'.','.','.','8','.','3','.','2','.'}, {'.','.','.','.','.','.','.','.','6'}, {'.','.','.','2','7','5','9','.','.'} }; displayVec2d(board); cout << endl; so.solveSudoku(board); displayVec2d(board); return 0; }
true
2af509fe61cedeb8539fa5e8c35c35146e013b06
C++
akhilbommu/C-Programs
/Testing functions albert example/Testing functions albert example/Testing functions albert example.cpp
UTF-8
286
3.28125
3
[]
no_license
#include<stdio.h> void Increment(int *p) { *p = *p + 1; printf("Address of variable x in invrement = %d\n",&p); printf("x in function is %d\n", *p); } int main() { int a=10; Increment(&a); printf("Address of variable a in invrement = %d\n", &a); printf("a in main is %d\n", a); }
true
6176756fc8f1df31c450d2927b9b5e3095d4f978
C++
rihardsbelinskis/CodeForces_problems
/HittheLottery.cpp
UTF-8
432
2.84375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ vector<long> bills; bills.push_back(100); bills.push_back(20); bills.push_back(10); bills.push_back(5); bills.push_back(1); long money; long cnt(0); cin >> money; for(long i = 0; i < bills.size(); i++) { cnt += (money / bills[i]); money %= bills[i]; } cout << cnt << endl; return 0; }
true
b898dce2260fd775b5f5d8abfddfad415eed1971
C++
shubhampathak09/codejam
/30 days training for beginners/Problem_Bank_adhoc/N_queen_minor_tweak.cpp
UTF-8
1,198
3.0625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define N 4 int board[N][N]; bool isvalid(int row,int col,int board[N][N]) { // asumming left side queens have been placed ,if possiblw to place a queen at current row,col // check this row int i,j; for(int i=0;i<col;i++) if(board[row][i]==1) return false; for(i=row-1,j=col-1;i>=0&&j>=0;i--,j-- ) if(board[i][j]) return false; for(i=row+1,j=col-1;i<N&&j>=0;i++,j--) if(board[i][j]) return false; return true; } void printboard(int board[N][N]) { for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { cout<<board[i][j]<<" "; } cout<<"\n"; } cout<<"\n"; } bool solveNqueens(int board[N][N],int col) { if(col>=N) { printboard(board); return true; } bool res=false; for(int i=0;i<=N;i++) { if(isvalid(i,col,board)) { board[i][col]=1; res=solveNqueens(board,col+1)||res; board[i][col]=0; // backtrack } } return res; } void solve() { // int board[N][N]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; // memset(board,0,sizeof(board)); if(solveNqueens(board,0)==false) { cout<<"No solution"; } return; } int main() { solve(); }
true
7914d328ed626542e44c229d0a7bae00e29481fd
C++
NAV1RAIN/Algorithm_template
/Barricade(bai)/main.cpp
UTF-8
2,699
2.6875
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int INF = 0x3f3f3f3f; const int MAXN = 1010; const int SIZE = 1e4+5; struct Node { int from, to, w; }Edge[SIZE]; struct edge { int to, cap, rev; }; vector<edge> G[MAXN]; int cost[MAXN][MAXN]; int dis[MAXN]; bool used[MAXN]; int n, m; void dijkstra(int s) { memset(dis, INF, sizeof(dis)); memset(used, 0, sizeof(used)); dis[s] = 0; while(true) { int v = -1; for(int u = 1; u <= n; u++) { if(!used[u] && (v == -1 || dis[u] < dis[v])) v = u; } if(v == -1) break; used[v] = true; for(int u = 1; u <= n; u++) { dis[u] = min(dis[u], dis[v]+cost[v][u]); } } } void addEdge(int from, int to, int cap) { int lenf = G[from].size(); int lent = G[to].size(); edge t1, t2; t1.to = to, t1.cap = cap, t1.rev = lent; t2.to = from, t2.cap = 0, t2.rev = lenf; G[from].push_back(t1); G[to].push_back(t2); } int dfs(int v, int t, int f) { if(v == t) return f; used[v] = true; int len = G[v].size(); for(int i = 0; i < len; i++) { edge &e = G[v][i]; if(!used[e.to] && e.cap > 0) { int d = dfs(e.to, t, min(f, e.cap)); if(dis[e.to]-dis[v] == 1 && d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } int max_flow(int s, int t) { int flow = 0; while(true) { memset(used, 0, sizeof(used)); int f = dfs(s, t, INF); if(f == 0) return flow; flow += f; } } int main() { int T; scanf("%d", &T); while(T--) { memset(cost, INF, sizeof(cost)); memset(Edge, 0, sizeof(Edge)); for(int i = 0; i < MAXN; i++) { G[i].clear(); } scanf("%d%d", &n, &m); for(int i = 0; i < m; i++) { int u, v, w; scanf("%d%d%d", &u, &v, &w); Edge[i].from = u, Edge[i].to = v, Edge[i].w = w; cost[u][v] = 1; cost[v][u] = 1; } dijkstra(n); if(dis[1] == INF) { printf("0\n"); continue; } for(int i = 0; i < m; i++) { int u, v, w; u = Edge[i].from; v = Edge[i].to; w = Edge[i].w; if(dis[v]-dis[u] == 1) { addEdge(u, v, w); } if(dis[u]-dis[v] == 1) { addEdge(v, u, w); } } int ans = max_flow(n, 1); printf("%d\n", ans); } return 0; }
true
2564fc5997d8793a40540f5a80ecc61a5891d3bd
C++
Amyh1608/ARA
/Arduino/robotic_arm/robotic_arm.ino
UTF-8
1,023
3.25
3
[ "MIT" ]
permissive
#include <Servo.h> const int SERVO_0_PIN = 3; const int SERVO_1_PIN = 5; const int SERVO_2_PIN = 6; const int SERVO_3_PIN = 9; Servo servo_0; // create servo object to control a servo Servo servo_1; Servo servo_2; Servo servo_3; int pos = 0; // variable to store the servo position void setup() { servo_0.attach(SERVO_0_PIN); // attaches the servo on pin 9 to the servo object servo_1.attach(SERVO_1_PIN); servo_2.attach(SERVO_2_PIN); servo_3.attach(SERVO_3_PIN); Serial.begin(9600); } void loop() { String msg; if (Serial.available() > 0) { // read the incoming string: msg = Serial.readString(); // Parse string and convert into ints int angle_0 = msg.substring(0,3).toInt(); int angle_1 = msg.substring(3,6).toInt(); int angle_2 = msg.substring(6,9).toInt(); int angle_3 = msg.substring(9,12).toInt(); // Write to servos incoming angles servo_0.write(angle_0); servo_1.write(angle_1); servo_2.write(angle_2); servo_3.write(angle_3); } }
true
7c9f40f049bdae70f31bc6cdd38ed0175b520081
C++
CreRecombinase/beachmat
/src/Csparse_output.h
UTF-8
7,704
3.03125
3
[]
no_license
#ifndef BEACHMAT_CSPARSE_OUTPUT_H #define BEACHMAT_CSPARSE_OUTPUT_H #include "beachmat.h" #include "utils.h" #include "any_matrix.h" namespace beachmat { /*** Class definition ***/ template<typename T, class V> class Csparse_output : public any_matrix { public: Csparse_output(size_t, size_t); ~Csparse_output(); template <class Iter> void set_row(size_t, Iter, size_t, size_t); template <class Iter> void set_col(size_t, Iter, size_t, size_t); void set(size_t, size_t, T); template <class Iter> void get_col(size_t, Iter, size_t, size_t); template <class Iter> void get_row(size_t, Iter, size_t, size_t); T get(size_t, size_t); Rcpp::RObject yield(); matrix_type get_matrix_type() const; private: typedef std::pair<size_t, T> data_pair; std::vector<std::deque<data_pair> > data; T get_empty() const; template <class Iter> Iter find_matching_row(Iter, Iter, const data_pair&); }; /*** Constructor definition ***/ template<typename T, class V> Csparse_output<T, V>::Csparse_output(size_t nr, size_t nc) : any_matrix(nr, nc), data(nc) {} template<typename T, class V> Csparse_output<T, V>::~Csparse_output() {} /*** Setter methods ***/ template<typename T, class V> template<class Iter> void Csparse_output<T, V>::set_col(size_t c, Iter in, size_t first, size_t last) { check_colargs(c, first, last); std::deque<data_pair>& current=data[c]; std::deque<data_pair> new_set; // Filling in all elements before start. auto cIt=current.begin(); while (cIt!=current.end() && cIt->first < first) { new_set.push_back(*cIt); ++cIt; } // Filling in all non-empty elements. for (size_t index=first; index<last; ++index, ++in) { if ((*in)!=get_empty()) { new_set.push_back(data_pair(index, *in)); } } // Jumping to the end. while (cIt!=current.end() && cIt->first < last) { ++cIt; } // Filling in remaining elements. while (cIt!=current.end()) { new_set.push_back(*cIt); ++cIt; } current.swap(new_set); return; } template<typename T, class V> template <class Iter> Iter Csparse_output<T, V>::find_matching_row(Iter begin, Iter end, const data_pair& incoming) { return std::lower_bound(begin, end, incoming, [](const data_pair& lhs, const data_pair& rhs) -> bool { return lhs.first < rhs.first; }); // Using a lambda to only compare first value. } template<typename T, class V> template<class Iter> void Csparse_output<T, V>::set_row(size_t r, Iter in, size_t first, size_t last) { check_rowargs(r, first, last); for (size_t c=first; c<last; ++c, ++in) { if ((*in)==get_empty()) { continue; } std::deque<data_pair>& current=data[c]; if (current.size()) { if (r < current.front().first) { current.push_front(data_pair(r, *in)); } else if (r==current.front().first) { current.front().second=*in; } else if (r > current.back().first) { current.push_back(data_pair(r, *in)); } else if (r==current.back().first) { current.back().second=*in; } else { data_pair incoming(r, *in); auto insert_loc=find_matching_row(current.begin(), current.end(), incoming); if (insert_loc!=current.end() && insert_loc->first==r) { insert_loc->second=*in; } else { current.insert(insert_loc, incoming); } } } else { current.push_back(data_pair(r, *in)); } } return; } template<typename T, class V> void Csparse_output<T, V>::set(size_t r, size_t c, T in) { check_oneargs(r, c); set_row(r, &in, c, c+1); return; } /*** Getter methods ***/ template<typename T, class V> template<class Iter> void Csparse_output<T, V>::get_row(size_t r, Iter out, size_t first, size_t last) { check_rowargs(r, first, last); std::fill(out, out+last-first, get_empty()); for (size_t col=first; col<last; ++col, ++out) { const std::deque<data_pair>& current=data[col]; if (current.empty() || r>current.back().first || r<current.front().first) { continue; } if (r==current.back().first) { (*out)=current.back().second; } else if (r==current.front().first) { (*out)=current.front().second; } else { auto loc=find_matching_row(current.begin(), current.end(), data_pair(r, *out)); // Equivalent to get_empty(), due to fill. if (loc!=current.end() && loc->first==r) { (*out)=loc->second; } } } return; } template<typename T, class V> template<class Iter> void Csparse_output<T, V>::get_col(size_t c, Iter out, size_t first, size_t last) { check_colargs(c, first, last); const std::deque<data_pair>& current=data[c]; // Jumping forwards. auto cIt=current.begin(); if (first) { cIt=find_matching_row(current.begin(), current.end(), data_pair(first, get_empty())); } std::fill(out, out+last-first, get_empty()); while (cIt!=current.end() && cIt->first < last) { *(out + (cIt->first - first)) = cIt->second; ++cIt; } return; } template<typename T, class V> T Csparse_output<T, V>::get(size_t r, size_t c) { check_oneargs(r, c); const std::deque<data_pair>& current=data[c]; auto cIt=find_matching_row(current.begin(), current.end(), data_pair(r, get_empty())); if (cIt!=current.end() && cIt->first==r) { return cIt->second; } else { return get_empty(); } } /*** Output function ***/ template<typename T, class V> Rcpp::RObject Csparse_output<T, V>::yield() { const int RTYPE=V().sexp_type(); std::string classname; switch (RTYPE) { case LGLSXP: classname="lgCMatrix"; break; case REALSXP: classname="dgCMatrix"; break; default: std::stringstream err; err << "unsupported sexptype '" << RTYPE << "' for sparse output"; throw std::runtime_error(err.str().c_str()); } Rcpp::S4 mat(classname); // Setting dimensions. if (!mat.hasSlot("Dim")) { throw_custom_error("missing 'Dim' slot in ", classname, " object"); } mat.slot("Dim") = Rcpp::IntegerVector::create(this->nrow, this->ncol); // Setting 'p'. if (!mat.hasSlot("p")) { throw_custom_error("missing 'p' slot in ", classname, " object"); } Rcpp::IntegerVector p(this->ncol+1, 0); auto pIt=p.begin()+1; size_t total_size=0; for (auto dIt=data.begin(); dIt!=data.end(); ++dIt, ++pIt) { total_size+=dIt->size(); (*pIt)=total_size; } mat.slot("p")=p; // Setting 'i' and 'x'. Rcpp::IntegerVector i(total_size); V x(total_size); if (!mat.hasSlot("i")) { throw_custom_error("missing 'i' slot in ", classname, " object"); } if (!mat.hasSlot("x")) { throw_custom_error("missing 'x' slot in ", classname, " object"); } auto xIt=x.begin(); auto iIt=i.begin(); for (size_t c=0; c<this->ncol; ++c) { auto current=data[c]; for (auto cIt=current.begin(); cIt!=current.end(); ++cIt, ++xIt, ++iIt) { (*iIt)=cIt->first; (*xIt)=cIt->second; } } mat.slot("i")=i; mat.slot("x")=x; return SEXP(mat); } template<typename T, class V> matrix_type Csparse_output<T, V>::get_matrix_type() const { return SPARSE; } } #endif
true
e7531f5dc46043a8216580ff7aa09365c76d1fa1
C++
meonBot/cvmfs
/cvmfs/receiver/lease_path_util.cc
UTF-8
913
2.921875
3
[]
permissive
/** * This file is part of the CernVM File System. */ #include "lease_path_util.h" namespace receiver { bool IsPathInLease(const PathString& lease, const PathString& path) { // If lease is "", any path falls within item if (!strcmp(lease.c_str(), "")) { return true; } // Is the lease string is the prefix of the path string and the next // character of the path string is a "/". if (path.StartsWith(lease) && path.GetChars()[lease.GetLength()] == '/') { return true; } // The lease is a prefix of the path and the last char of the lease is a "/" if (path.StartsWith(lease) && lease.GetChars()[lease.GetLength() - 1] == '/') { return true; } // If the path string is exactly the lease path return true (allow the // creation of the leased directory during the lease itself) if (lease == path) { return true; } return false; } } // namespace receiver
true
045c54e812f1561f4f3590f30e22f5294a4a1707
C++
ricardojrloureiro/condominium-management
/corporation.cpp
UTF-8
26,524
2.984375
3
[]
no_license
#include "corporation.h" // constructor Corporation::Corporation(): specializedCompanies(SpecializedCompany()){ loadWorkers("workers.csv"); loadOwners("owners.csv"); loadCondominiums("condominiums.csv"); loadReports("reports.csv"); loadSpecializedCompanies("specializedCompanies.csv"); fillPossibleOwners(); if(reports.size()==0){ time_t now = time(0); tm *ltm = localtime(&now); stringstream datess; datess << 1900 + ltm->tm_year; datess << 1 + ltm->tm_mon; date = atoi(datess.str().c_str()); } else { date = getLastDate(); incDate(); } } void Corporation::incDate() { if(date%100 == 12){ date = ((date / 100) + 1) * 100 + 1; } else { date++; } } /* get functions*/ int Corporation::getLastDate() { return reports[reports.size()-1].getDate(); } int Corporation::getYear() { return date/100; } int Corporation::getMonth() { return date%100; } Worker* Corporation::getWorker(int id) { for(unsigned int i=0; i<workers.size(); i++) { if(workers[i].getId() == id) { return &workers[i]; break; } } return 0; } Owner* Corporation::getOwner(int id) { for(unsigned int i=0; i<owners.size(); i++) { if(owners[i].getId() == id) { return &owners[i]; break; } } return 0; } vector <Worker*> Corporation::getWorkersList() { vector <Worker*> tempvector; for(unsigned int i=0; i<workers.size(); i++) { tempvector.push_back(&workers[i]); } return tempvector; } vector <Owner*> Corporation::getOwnersList() { vector <Owner*> tempvector; for(unsigned int i=0; i<owners.size(); i++) { tempvector.push_back(&owners[i]); } return tempvector; } // remove/add functions void Corporation::removeCondominium(Condominium cond){ int id = cond.getId(); for(unsigned int i=0;i<condominiums.size();i++){ if(condominiums[i].getId() == id){ condominiums.erase(condominiums.begin()+i); } } } void Corporation::addCondominium(Condominium cond){ condominiums.push_back(cond); } void Corporation::addWorker() { string name = ""; float wage=0; name = Menu::promptString("Insert Worker's name: "); wage = Menu::promptFloat("Insert Worker's wage: "); Worker worker(name,wage); addWorker(worker); saveWorkers(); } void Corporation::addOwner() { string name = ""; int contractType=0; name = Menu::promptString("Insert Owner's name: "); Menu subMenu("Which type of contract will this owner have?"); subMenu.addMenuItem("Monthly Payment"); subMenu.addMenuItem("Trimestral Payment"); subMenu.addMenuItem("Annually Payment"); contractType = subMenu.showMenu(); Owner owner(name,(contractType- 1)); addOwner(owner); addToPossibleOwners(owner); saveOwners(); } void Corporation::addReport(Report report) { reports.push_back(report); } void Corporation::addWorker(Worker w1) { workers.push_back(w1); } void Corporation::addOwner(Owner w1) { owners.push_back(w1); } void Corporation::createCondominium() { string name; name = Menu::promptString("Name: "); float areaMultiplier = Menu::promptFloat("Cost per Square Meter: "); float floorMultiplier = Menu::promptFloat("Floor Multiplier: "); float baseApartmentCost = Menu::promptFloat("Base Apartment Cost: "); float baseOfficeCost = Menu::promptFloat("Base Office Cost: "); float baseStoreCost = Menu::promptFloat("Base Store Cost: "); Condominium condominium(name, areaMultiplier, floorMultiplier, baseApartmentCost, baseOfficeCost, baseStoreCost); addCondominium(condominium); saveCondominiums("condominiums.csv"); } /* load functions */ void Corporation::loadWorkers(string filename){ ifstream file; string line; long id; float wage; string name; vector <string> workersInfo; file.open(filename.c_str()); int lineNumber = 0; while (file.good()) { getline(file,line); if (lineNumber > 0) { istringstream iss(line); do { string sub; getline(iss, sub , ','); workersInfo.push_back(sub); } while (iss); id = atol(workersInfo[0].c_str()); name = workersInfo[1]; wage = atof(workersInfo[2].c_str()); Worker wtemp(id,wage,name); workers.push_back(wtemp); workersInfo.clear(); } lineNumber++; } file.close(); } void Corporation::loadOwners(string filename){ ifstream file; string line; long id; int contractType; string name; vector <string> ownersInfo; file.open(filename.c_str()); int lineNumber = 0; while (file.good()) { getline(file,line); if (lineNumber > 0) { istringstream iss(line); do { string sub; getline(iss, sub , ','); ownersInfo.push_back(sub); } while (iss); id = atol(ownersInfo[0].c_str()); name = ownersInfo[1]; contractType = atoi(ownersInfo[2].c_str()); Owner otemp(id,name,contractType); owners.push_back(otemp); ownersInfo.clear(); } lineNumber++; } file.close(); } void Corporation::loadCondominiums(string filename) { ifstream file; string line; int id; vector <string> condominiumInfo; file.open(filename.c_str()); int lineNumber = 0; while (file.good()) { getline(file,line); if (lineNumber > 0) { istringstream iss(line); do { string sub; getline(iss, sub , ','); condominiumInfo.push_back(sub); } while (iss); id = atol(condominiumInfo[0].c_str()); if(id>0) { Condominium condominium(id, condominiumInfo[1], atof(condominiumInfo[2].c_str()), atof(condominiumInfo[3].c_str()), atof(condominiumInfo[4].c_str()), atof(condominiumInfo[5].c_str()), atof(condominiumInfo[6].c_str())); condominiums.push_back(condominium); loadProperties(id); loadMaintenance(id); loadMeetings(id); } condominiumInfo.clear(); } lineNumber++; } file.close(); } void Corporation::loadMeetings(int id) { stringstream ssfilename; ssfilename << "meetingCond" << id << ".csv"; string filename = ssfilename.str(); ifstream file(filename.c_str()); string line; int lineNumber = 0; vector<string> maintenanceInfo; while (file.good()) { getline(file,line); if (lineNumber > 0) { istringstream iss(line); do { string sub; getline(iss, sub , ','); maintenanceInfo.push_back(sub); } while (iss); int date = atoi(maintenanceInfo[0].c_str()); maintenanceInfo.erase(maintenanceInfo.begin()); string subject = maintenanceInfo[0].c_str(); maintenanceInfo.erase(maintenanceInfo.begin()); vector<int> ids; for(unsigned int i=0;i<maintenanceInfo.size();i++){ ids.push_back(atoi(maintenanceInfo[i].c_str())); } Meeting m1(date,ids,subject); condominiums[searchCondominiumId(id)].addMeeting(m1); maintenanceInfo.clear(); } lineNumber++; } file.close(); } void Corporation::loadReports(string filename) { ifstream file; string line; int date, profitLoss; vector <string> reportsInfo; vector < vector <string > > maintenanceReport, propertiesReport; file.open(filename.c_str()); int lineNumber = 0; while (file.good()) { getline(file,line); if (lineNumber > 0) { istringstream iss(line); do { string sub; getline(iss, sub , ','); reportsInfo.push_back(sub); } while (iss); date = atoi(reportsInfo[0].c_str()); profitLoss = atof(reportsInfo[1].c_str()); maintenanceReport = loadMaintenanceReport(date); propertiesReport = loadPropertiesReport(date); Report tempreport(date,profitLoss,maintenanceReport,propertiesReport); if(date>0) { reports.push_back(tempreport); } reportsInfo.clear(); } lineNumber++; } file.close(); } void Corporation::loadSpecializedCompanies(string filename) { ifstream file; string line; string name; float price; vector <string> companiesInfo; file.open(filename.c_str()); int lineNumber = 0; while (file.good()) { getline(file,line); if (lineNumber > 0) { istringstream iss(line); do { string sub; getline(iss, sub , ','); companiesInfo.push_back(sub); } while (iss); name = companiesInfo[0]; price = atof(companiesInfo[1].c_str()); SpecializedCompany tempCompany(name,price); if(price>0) { specializedCompanies.insert(tempCompany); } companiesInfo.clear(); } lineNumber++; } file.close(); } vector < vector <string> > Corporation::loadMaintenanceReport(int date) { stringstream ssfilename; ssfilename << date << "maintenance" << ".csv"; string filename = ssfilename.str(); ifstream file(filename.c_str()); string line; vector <string> maintenanceInfo, maintenanceInfoFiltered; int lineNumber = 0; vector < vector <string> > result; while (file.good()) { getline(file,line); if (lineNumber > 0) { istringstream iss(line); do { string sub; getline(iss, sub , ','); maintenanceInfo.push_back(sub); } while (iss); if(maintenanceInfo.size()==5) { for(unsigned int i = 0; i<4; i++) { maintenanceInfoFiltered.push_back(maintenanceInfo[i]); } result.push_back(maintenanceInfoFiltered); } maintenanceInfoFiltered.clear(); maintenanceInfo.clear(); } lineNumber++; } return result; } vector < vector <string> > Corporation::loadPropertiesReport (int date) { stringstream ssfilename; ssfilename << date << "properties" << ".csv"; string filename = ssfilename.str(); ifstream file(filename.c_str()); string line; vector <string> propertiesInfo, propertiesInfoFiltered; int lineNumber = 0; vector < vector <string> > result; while (file.good()) { getline(file,line); if (lineNumber > 0) { istringstream iss(line); do { string sub; getline(iss, sub , ','); propertiesInfo.push_back(sub); } while (iss); if(propertiesInfo.size()==5) { for(unsigned int i = 0; i<4; i++) { propertiesInfoFiltered.push_back(propertiesInfo[i]); } result.push_back(propertiesInfoFiltered); } propertiesInfoFiltered.clear(); propertiesInfo.clear(); } lineNumber++; } return result; } void Corporation::loadProperties(int condominiumid) { stringstream ssfilename; ssfilename << "properties" << condominiumid << ".csv"; string filename = ssfilename.str(), address; ifstream file(filename.c_str()); string line; int type, propertyFloor,Id, monthsLeft; float area, totalDue; vector <string> propertyInfo; int lineNumber = 0; while (file.good()) { getline(file,line); if (lineNumber > 0) { istringstream iss(line); do { string sub; getline(iss, sub , ','); propertyInfo.push_back(sub); } while (iss); if(propertyInfo.size() == 8){ type = atol(propertyInfo[0].c_str()); address = propertyInfo[1]; area = atof(propertyInfo[2].c_str()); propertyFloor = atof(propertyInfo[3].c_str()); Id= atoi(propertyInfo[4].c_str()); totalDue = atof(propertyInfo[5].c_str()); monthsLeft = atoi(propertyInfo[6].c_str()); if (type==1) { condominiums[searchCondominiumId(condominiumid)].addProperty(new Apartment(address,area,propertyFloor,getOwner(Id),totalDue,monthsLeft)); } else if (type==2) { condominiums[searchCondominiumId(condominiumid)].addProperty(new Office(address,area,propertyFloor,getOwner(Id),totalDue,monthsLeft)); } else if (type==3) { condominiums[searchCondominiumId(condominiumid)].addProperty(new Store(address,area,propertyFloor,getOwner(Id),totalDue,monthsLeft)); } propertyInfo.clear(); } } lineNumber++; } } void Corporation::loadMaintenance(int condominiumid) { stringstream ssfilename; ssfilename << "maintenance" << condominiumid << ".csv"; string filename = ssfilename.str(), name; ifstream file(filename.c_str()); string line; int monthsLeft, type, workerid; float duration; vector <string> maintenanceInfo; int lineNumber = 0; while (file.good()) { getline(file,line); if (lineNumber > 0) { istringstream iss(line); do { string sub; getline(iss, sub , ','); maintenanceInfo.push_back(sub); } while (iss); if(maintenanceInfo.size() == 6){ monthsLeft = atoi(maintenanceInfo[0].c_str()); type = atoi(maintenanceInfo[1].c_str()); name = maintenanceInfo[2]; workerid = atoi(maintenanceInfo[3].c_str()); duration = atof(maintenanceInfo[4].c_str()); condominiums[searchCondominiumId(condominiumid)].addMaintenance(new Maintenance(monthsLeft,duration, type, name, getWorker(workerid))); maintenanceInfo.clear(); } } lineNumber++; } } int Corporation::searchCondominiumId(int condominiumdid) { for(unsigned int i = 0; i<condominiums.size(); i++) { if(condominiums[i].getId() == condominiumdid) { return i; } } return 0; } void Corporation::showAllCondominiums() { int i= 0; cout << endl; Menu showMenu("Condominiums List"); showMenu.addMenuItem("List all properties information"); showMenu.addMenuItem("Go to the NEXT condominium"); showMenu.addMenuItem("Go to the PREVIOUS condominium"); showMenu.addMenuItem("Go BACK to the PREVIOUS menu"); while(showMenu.isActive()) { condominiums[i].showCondominium(); switch(showMenu.showMenu()) { case 1: condominiums[i].showProperties(); break; case 2: i = (i+1) % condominiums.size(); break; case 3: i = (i-1) % condominiums.size(); break; default: showMenu.toggleMenu(); break; } } } /* save functions */ void Corporation::saveCondominiums(string filename){ ofstream file(filename.c_str()); file << "id,name,areaMultiplier,floorMultiplier,baseApartmentCost,baseOfficeCost,baseStoreCost" << endl; for(unsigned int i = 0; i < condominiums.size(); i++) { file << condominiums[i].getId() << "," << condominiums[i].getName() << "," << condominiums[i].getAreaMultiplier() << "," << condominiums[i].getFloorMultiplier() << "," << condominiums[i].getBaseApartmentCost() << "," << condominiums[i].getBaseOfficeCost() << "," << condominiums[i].getBaseStoreCost(); if (i < (condominiums.size() -1)) file << endl; condominiums[i].saveProperties(); } file.close(); } void Corporation::saveWorkers() { ofstream file("workers.csv"); file << "id,name,wage" << endl; for(unsigned int i = 0; i < workers.size(); i++) { file << workers[i].getId() << "," << workers[i].getName() << "," << workers[i].getWage(); if (i < (workers.size() -1)) file << endl; } file.close(); } void Corporation::saveOwners() { ofstream file("owners.csv"); file << "id,name,contractType" << endl; for(unsigned int i = 0; i < owners.size(); i++) { file << owners[i].getId() << "," << owners[i].getName() << "," << owners[i].getContractType(); if (i < (owners.size() -1)) file << endl; } file.close(); } void Corporation::manageWorkers(int id){ stringstream topic; topic << "Managing " << workers[id].getName() << ", wage: " << workers[id].getWage() << endl; string topic2 = topic.str(); Menu showMenu(topic2.c_str()); showMenu.addMenuItem("Edit Workers Name"); showMenu.addMenuItem("Edit Workers Wage"); showMenu.addMenuItem("Go BACK to the PREVIOUS Menu"); while(showMenu.isActive()) { switch(showMenu.showMenu()) { case 1:{ string name = Menu::promptString("New Name: "); workers[id].setName(name); saveWorkers(); showMenu.toggleMenu(); break; } case 2:{ float wage = Menu::promptFloat("Set New Wage: "); workers[id].setWage(wage); saveWorkers(); showMenu.toggleMenu(); break; } case 3: showMenu.toggleMenu(); break; } } } void Corporation::manageOwners(int id){ stringstream topic; topic << "Managing " << owners[id].getName() << " - Contract: " << owners[id].printType() << endl; string topic2 = topic.str(); Menu showMenu(topic2.c_str()); showMenu.addMenuItem("Edit Owner's Name"); showMenu.addMenuItem("Edit Owner's Contract Type"); showMenu.addMenuItem("Go BACK to the PREVIOUS Menu"); while(showMenu.isActive()) { switch(showMenu.showMenu()) { case 1:{ string name = Menu::promptString("New Name: "); owners[id].setName(name); saveOwners(); addToPossibleOwners(owners[id]); showMenu.toggleMenu(); break; } case 2:{ Menu subMenu("Which type of contract will this owner have?"); subMenu.addMenuItem("Monthly Payment"); subMenu.addMenuItem("Trimestral Payment"); subMenu.addMenuItem("Annually Payment"); int type = subMenu.showMenu(); owners[id].setType(type-1); saveOwners(); addToPossibleOwners(owners[id]); showMenu.toggleMenu(); break; } case 3: showMenu.toggleMenu(); break; } } } void Corporation::manageCondominium() { int i= 0; Menu showMenu("Condominium Management"); showMenu.addMenuItem("Choose this condominium to manage"); showMenu.addMenuItem("Go to the NEXT condominium"); showMenu.addMenuItem("Go to the PREVIOUS condominium"); showMenu.addMenuItem("Go BACK to the PREVIOUS Menu"); while(showMenu.isActive()) { condominiums[i].showCondominium(); switch(showMenu.showMenu()) { case 1: condominiums[i].manageCond(getWorkersList(),getOwnersList(),date); break; case 2: i = (i+1) % condominiums.size(); break; case 3: i = (i-1) % condominiums.size(); break; default: showMenu.toggleMenu(); break; } } } void Corporation::financeReports() { Menu showMenu("Finance Reports"); showMenu.addMenuItem("Browse through all reports"); showMenu.addMenuItem("Fast Forward time "); showMenu.addMenuItem("Go to the MAIN menu"); while(showMenu.isActive()){ switch (showMenu.showMenu()) { case 1: if(reports.size()!=0){ browseReports(); } else { cout << "There aren't any reports so far." << endl; } break; case 2: if(condominiums.size() != 0){ fastForward(); } else { cout << "There aren't any condominiuns so far." << endl; } break; case 3: showMenu.toggleMenu(); break; default: // going back break; } } } void Corporation::browseReports() { int i= 0; cout << endl; Menu showMenu("Reports List"); showMenu.addMenuItem("List all maintenance performed"); showMenu.addMenuItem("List all properties that paid"); showMenu.addMenuItem("Go to the NEXT report"); showMenu.addMenuItem("Go to the PREVIOUS report"); showMenu.addMenuItem("Go BACK to the PREVIOUS menu"); while(showMenu.isActive()) { reports[i].showInfo(); switch(showMenu.showMenu()) { case 1: reports[i].showMaintenance(); break; case 2: reports[i].showProperties(); break; case 3: i = (i+1) % reports.size(); break; case 4: i = (i-1) % reports.size(); break; default: showMenu.toggleMenu(); break; } } } void Corporation::saveReports(string filename) { ofstream file(filename.c_str()); file << "date,totalProfitLoss" << endl; for(unsigned int i = 0; i < reports.size(); i++) { file << reports[i].getDate() << "," << reports[i].getProfitLoss(); if (i < (reports.size() -1)) file << endl; reports[i].saveMaintenanceReport(); reports[i].savePropertiesReport(); } file.close(); } void Corporation::saveSpecializedCompanies(string filename) { ofstream file(filename.c_str()); file << "name,price" << endl; BSTItrIn<SpecializedCompany> itr(specializedCompanies); while ( ! itr.isAtEnd() ) { file << itr.retrieve().getName() << "," << itr.retrieve().getPrice(); if(!itr.isAtEnd()) file << endl; itr.retrieve().saveMaintenanceReport(); itr.advance(); } file.close(); } void Corporation::fastForward() { vector <int> fixedCosts; vector <float> profitlosses; vector <string> negativeCondominiums; vector < vector <string> > maintenanceReportVec, propertiesReportVec, tempMaintenance, tempProperties; unsigned int monthsToAdvance; stringstream message; float profitlosssum = 0, fixed, profitloss; monthsToAdvance = Menu::promptInt("How many months would you like to advance? "); for(unsigned int i=0;i<monthsToAdvance;i++){ for(unsigned int j=0;j<condominiums.size();j++){ cout << endl; message << condominiums[j].getName() << " electrity/water/other costs for " << getMonth() << "/" << getYear() << ": "; fixed = Menu::promptFloat(message.str()); fixedCosts.push_back(fixed); message.str(""); message.clear(); profitloss = (condominiums[j].getProfitLoss() - fixed); profitlosses.clear(); profitlosses.push_back(profitloss); // get a float vector with the all profitloss profitlosssum += profitloss; if(profitloss<0) { message << condominiums[j].getName() << " - Month " << getMonth() << "/" << getYear(); negativeCondominiums.push_back(message.str()); message.str(""); message.clear(); } cout << endl << condominiums[j].getName() << " generated a total profit/loss of " << profitloss << " euros" << endl; tempMaintenance = condominiums[j].getMaintenanceReport(); tempProperties = condominiums[j].getPropertiesReport(); for(unsigned int w=0; w<tempMaintenance.size(); w++) { maintenanceReportVec.push_back(tempMaintenance[w]); } for(unsigned int w=0; w<tempProperties.size(); w++) { propertiesReportVec.push_back(tempProperties[w]); } condominiums[j].advanceOneMonth(); } // passes the information of the current month to the report Report report(date,profitloss, maintenanceReportVec, propertiesReportVec); addReport(report); saveReports("reports.csv"); maintenanceReportVec.clear(); propertiesReportVec.clear(); incDate(); } cout << endl << "Months Fast Forwarded: " << monthsToAdvance << endl; cout << "Total Profit/Loss: " << profitlosssum << " euros" << endl; cout << "Average Profit/Loss per month: " << profitlosssum/monthsToAdvance << " euros " << endl; cout << "List of condominius with a monthly loss: " << endl; for(unsigned int i=0; i<negativeCondominiums.size(); i++) { cout << negativeCondominiums[i] << endl; } cout << endl; saveCondominiums("condominiums.csv"); } bool Corporation::isEmpty() { if(condominiums.size() > 0) { return false; } else { return true; } } void Corporation::showWorker() { if(workers.size()==0){ cout << "There are no workers in this corporation, please add one first" << endl; }else { int i= 0; Menu showMenu("Workers Management"); showMenu.addMenuItem("Choose this worker to manage"); showMenu.addMenuItem("Go to the NEXT worker"); showMenu.addMenuItem("Go to the PREVIOUS worker"); showMenu.addMenuItem("Go BACK to the PREVIOUS Menu"); while(showMenu.isActive()) { cout << "Name: " << workers[i].getName() << ", wage: " << workers[i].getWage() << endl; switch(showMenu.showMenu()) { case 1: manageWorkers(i); break; case 2: i = (i+1) % workers.size(); break; case 3: i = (i-1) % workers.size(); break; default: showMenu.toggleMenu(); break; } } } } void Corporation::showOwner() { if(owners.size()==0){ cout << "There are no owners in this corporation, please add one first" << endl << endl; }else { int i= 0; Menu showMenu("Owners Management"); showMenu.addMenuItem("Choose this owner to manage"); showMenu.addMenuItem("Go to the NEXT owner"); showMenu.addMenuItem("Go to the PREVIOUS owner"); showMenu.addMenuItem("Go BACK to the PREVIOUS Menu"); while(showMenu.isActive()) { cout << "Name: " << owners[i].getName() << " - Contract: " << owners[i].printType() << endl; switch(showMenu.showMenu()) { case 1: manageOwners(i); break; case 2: i = (i+1) % owners.size(); break; case 3: i = (i-1) % owners.size(); break; default: showMenu.toggleMenu(); break; } } } } void Corporation::showPossibleOwners() { if(possibleOwners.size()==0){ cout << "There are no past/new owners that have no properties in this corporation" << endl << endl; }else { Menu showMenu("Owners Management"); showMenu.addMenuItem("Go to the NEXT owner"); showMenu.addMenuItem("Go BACK to the PREVIOUS Menu"); while(showMenu.isActive()) { HashOwners::const_iterator it=possibleOwners.begin(); cout << "Name: " << it->getName() << " - Type of contract:" << it->printType() << endl; switch(showMenu.showMenu()) { case 1: it++; if(it==possibleOwners.end()){ it = possibleOwners.begin(); } break; case 2: showMenu.toggleMenu(); break; } } } } void Corporation::condEvents(int date) { if(condominiums.size()==0){ cout << "There are no condominiums in this corporation, please add one first" << endl << endl; }else { int i=0; Menu showMenu("Condominium list"); showMenu.addMenuItem("Choose this condominium to create an event"); showMenu.addMenuItem("Go to the NEXT condominium"); showMenu.addMenuItem("Go to the PREVIOUS condominium"); showMenu.addMenuItem("Go BACK to the PREVIOUS Menu"); while(showMenu.isActive()) { cout << "Name: " << condominiums[i].getName() << " | Properties# " << condominiums[i].getPropertiesSize() << endl; switch (showMenu.showMenu()) { case 1: condominiums[i].arrangeMeeting(date); break; case 2: i = (i+1) % condominiums.size(); break; case 3: i = (i-1) % condominiums.size(); break; default: showMenu.toggleMenu(); break; } } } } void Corporation::addToPossibleOwners(Owner o1) { HashOwners::const_iterator it = possibleOwners.find(o1); if(it == possibleOwners.end()){ possibleOwners.insert(o1); } else { possibleOwners.erase(*it); possibleOwners.insert(o1); } } void Corporation::fillPossibleOwners() { if(owners.size()==0){ return; } possibleOwners.clear(); for(unsigned int i=0;i<owners.size();i++){ bool temCasa=false; for(unsigned int j=0;j<condominiums.size();j++) { vector<Property*> atual=condominiums[j].getProperties(); for(unsigned int z=0;z<atual.size();z++) { if(atual[z]->getOwnerId() == owners[i].getId()) { temCasa=true; } } } if(temCasa==true){ temCasa=false; } else { possibleOwners.insert(owners[i]); } } } void Corporation::manageSpecializedCompanies() { Menu companiesMenu("Manage Specialized Companies"); companiesMenu.addMenuItem("Add new company"); companiesMenu.addMenuItem("List all companies"); companiesMenu.addMenuItem("Go Back"); while(companiesMenu.isActive()) { switch(companiesMenu.showMenu()) { case 1: this->addSpecializedCompany(); break; case 2: this->listSpecializedCompanies(); break; default: companiesMenu.toggleMenu(); break; } } } void Corporation::listSpecializedCompanies() { BSTItrIn<SpecializedCompany> itr(specializedCompanies); while ( ! itr.isAtEnd() ) { cout << itr.retrieve(); itr.advance(); cout << endl; } } void Corporation::addSpecializedCompany() { string name = Menu::promptString("Specialized Company Name: "); float price = Menu::promptFloat("Price Per Service: "); SpecializedCompany newCompany(name, price); specializedCompanies.insert(newCompany); saveSpecializedCompanies("specializedCompanies.csv"); }
true
c9e8ace506a7746160da39e210412f2a38a7fbe5
C++
labelette91/ook_rpi
/print.h
UTF-8
4,118
2.90625
3
[]
no_license
//file simulate Arduino Serial Print #ifndef Print_h #define Print_h #include <stdio.h> // for int #include <string.h> // for int #include <stdarg.h> #include "deftype.h" #include <unistd.h> #include <errno.h> #define DEC 10 #define HEX 16 #define OCT 8 #define BIN 2 int serialAvailable(int fd); static int writestd(int fildes, const void *buf, int nbytes) { return write( fildes, buf, nbytes); } static int readstd(int fildes, void *buf, int nbytes) { return read(fildes, buf, nbytes); } class Print { public: static int out; static int DomoticOut; static int PRINT (unsigned long mes , int base , bool lf) { int nb = 1; switch (base) { case BIN : nb= dprintf(out,"%d",mes) ; break; case OCT: nb = dprintf(out, "%o",mes) ; break; case DEC : nb = dprintf(out, "%d",mes) ; break; case HEX : nb = dprintf(out, "%X",mes) ; break; default : nb = dprintf(out, "%d",mes) ; break; } if (lf)dprintf(out,"\n") ; return nb; } static int write(void* pbuffer, int size) { uint8_t* buffer = (uint8_t*)pbuffer; //log ascii //dprintf(out, "WR:");for (int i = 0; i < size; i++) dprintf(out, "%02X", buffer[i] ); dprintf(out, "\n"); int err = writestd(DomoticOut, pbuffer, size ); if (err <= 0) { dprintf(out,"error %d writing TTY : %d \n", err, strerror(errno)); } return size; } static int write(char c ) { //log ascii dprintf(out, "%c",c); return 1 ; } static int print(const char mes [] ) {return dprintf(out, "%s",mes) ; }; static int print(char mes ) {return dprintf(out, "%c",mes) ; }; static int print(unsigned char mes , int base = DEC) {return PRINT(mes,base,false) ; }; static int print(int mes , int base = DEC) {return PRINT(mes,base,false) ; }; static int print(unsigned int mes, int base = DEC) {return PRINT(mes,base,false) ; }; static int print(long mes , int base = DEC) {return PRINT(mes,base,false) ; }; static int print(unsigned long mes , int base = DEC) {return PRINT(mes,base,false) ; }; static int print(double mes , int base = 2) {return dprintf(out, "%f",mes) ; }; static int println(const char mes[]) {return dprintf(out, "%s\n",mes) ; }; static int println(char mes ) {return dprintf(out, "%c\n",mes) ; }; static int println(unsigned char mes , int base = DEC) {return PRINT(mes,base,true) ; }; static int println(int mes , int base = DEC) {return PRINT(mes,base,true) ; }; static int println(unsigned int mes , int base = DEC) {return PRINT(mes,base,true) ; }; static int println(long mes , int base = DEC) {return PRINT(mes,base,true) ; }; static int println(unsigned long mes , int base = DEC) {return PRINT(mes,base,true) ; }; static int println(double mes , int base = 2) {return dprintf(out, "%f\n",mes) ; }; static int println(void) {return dprintf(out, "\n") ; }; static int printf(const char *fmt,...) { va_list argList; char cbuffer[1024]; va_start(argList, fmt); int nb = vsnprintf(cbuffer, sizeof(cbuffer), fmt, argList); va_end(argList); print(cbuffer); return nb; }; static int available() { int nb = serialAvailable(DomoticOut) ; // if (nb) dprintf(out, "NB:%d ", nb ); return nb; } static char read() { char inputbyte; readstd(DomoticOut, &inputbyte, 1); // dprintf(out, "%02X ", inputbyte); return inputbyte ; } static int read(void* const pbuffer, unsigned const buffer_size) { int psize = readstd(DomoticOut, pbuffer, buffer_size); char* buffer = (char*)pbuffer; // for (int i = 0; i < psize; i++) dprintf(out, "%02X", buffer[i]); dprintf(out, "\n"); return psize; } static char Read() { char inputbyte; readstd(out, &inputbyte, 1); // dprintf(out, "%02X ", inputbyte); return inputbyte ; } void begin(long){ }; }; extern Print Serial ; #endif
true
b5a302e143de7c3700321589af9839b1e1b09825
C++
mmackay8/CS236
/lab3/Rule.cpp
UTF-8
380
2.5625
3
[]
no_license
#include "Rule.h" Rule::Rule(Predicate h) { head = h; } void Rule::addBodyPred(Predicate b) { bodyPredicates.push_back(b); } string Rule::toString() { string str; str = head.toString() + " :- "; str += bodyPredicates[0].toString(); for (unsigned int i = 1; i < bodyPredicates.size(); i++) { str += "," + bodyPredicates[i].toString(); } return str; } Rule::~Rule() { }
true
4b94475fe5318de7cc463685c595bac9e80cedfb
C++
cosocaf/Pick
/compiler/bundler/symbol.cpp
UTF-8
1,827
2.6875
3
[ "MIT" ]
permissive
#include "symbol.h" #include <cassert> namespace pickc::bundler { Symbol::Symbol(pcir::FunctionSection* pcirFn) : initType(SymbolInitType::PCIR), pcirFn(pcirFn) {} Symbol::Symbol(const BinaryVec& imm) : initType(SymbolInitType::Immediate), imm(imm) {} Symbol::Symbol(SymbolInitType type, Function* fn) : initType(type), fn(fn) { assert(type == SymbolInitType::Function || type == SymbolInitType::Runtime); } Symbol::Symbol(const Symbol& symbol) : initType(symbol.initType) { switch(initType) { case SymbolInitType::_NONE: break; case SymbolInitType::PCIR: pcirFn = symbol.pcirFn; break; case SymbolInitType::Immediate: new (&imm) BinaryVec(symbol.imm); break; case SymbolInitType::Function: case SymbolInitType::Runtime: fn = symbol.fn; break; default: assert(false); } } Symbol::~Symbol() { clear(); } Symbol& Symbol::operator=(const Symbol& symbol) { clear(); initType = symbol.initType; switch(initType) { case SymbolInitType::_NONE: break; case SymbolInitType::PCIR: pcirFn = symbol.pcirFn; break; case SymbolInitType::Immediate: new (&imm) BinaryVec(symbol.imm); break; case SymbolInitType::Function: case SymbolInitType::Runtime: fn = symbol.fn; break; default: assert(false); } return *this; } void Symbol::clear() { switch(initType) { case SymbolInitType::_NONE: break; case SymbolInitType::PCIR: break; case SymbolInitType::Immediate: imm.~vector(); break; case SymbolInitType::Function: case SymbolInitType::Runtime: break; } initType = SymbolInitType::_NONE; } }
true
a3867d88fcaea95afb7fc716f80997d093f41cd3
C++
scottrick/opengl
/GLCamera.cpp
UTF-8
2,242
2.9375
3
[]
no_license
#include "GLCamera.h" #include "Input.h" #include "glm/gtx/rotate_vector.hpp" #include <iostream> using namespace std; GLCamera::GLCamera() { fov = 60.f; pos = glm::vec3(0.0f, 0.0f, 0.0f); lookDir = glm::vec3(0.0f, 0.0f, 1.0f); upDir = glm::vec3(0.0f, 1.0f, 0.0f); speed = 100.0f; } GLCamera::~GLCamera() { } void GLCamera::update(GLdouble time, GLdouble deltaTime) { GLulong input = Input::sharedInput()->getKeyboardAlphaFlags(); GLulong modifiers = Input::sharedInput()->getKeyboardModifierFlags(); glm::ivec2 mouse = Input::sharedInput()->getMouseMovement(); GLfloat speedToUse = speed; if (mouse.x || mouse.y) { cout << "Mouse (" << mouse.x << ", " << mouse.y << ")" << endl; cout << "LookDir (" << lookDir.x << ", " << lookDir.y << ", " << lookDir.z << ")" << endl; if (mouse.x) { lookDir = glm::rotate(lookDir, -0.2f * (GLfloat)mouse.x, upDir); } if (mouse.y) { glm::vec3 crossVec = glm::cross(lookDir, upDir); lookDir = glm::rotate(lookDir, -0.2f * (GLfloat)mouse.y, crossVec); upDir = glm::rotate(upDir, -0.2f * (GLfloat)mouse.y, crossVec); } cout << "LookDir (" << lookDir.x << ", " << lookDir.y << ", " << lookDir.z << ")" << endl; } if (modifiers & INPUT_MODIFIER_ALT) { speedToUse /= 12.0f; } if (input & INPUT_CHAR_W) { //moving forwards pos += lookDir * (speedToUse * (GLfloat)deltaTime); } if (input & INPUT_CHAR_S) { //moving backwards pos -= lookDir * (speedToUse * (GLfloat)deltaTime); } if (input & INPUT_CHAR_A) { //moving left glm::vec3 cross = glm::cross(lookDir, upDir); pos -= cross * (speedToUse * (GLfloat)deltaTime); } if (input & INPUT_CHAR_D) { //moving right glm::vec3 cross = glm::cross(lookDir, upDir); pos += cross * (speedToUse * (GLfloat)deltaTime); } if (input & INPUT_SPACE) { if (modifiers & INPUT_MODIFIER_SHIFT) { //moving down pos -= upDir * (speedToUse * (GLfloat)deltaTime); } else { //moving up pos += upDir * (speedToUse * (GLfloat)deltaTime); } } } const char *GLCamera::getClassName() const { return "GLCamera"; }
true
52cd8f9892d2f6edc6a3c5021fe9684da28e2453
C++
ldhapple/SDLGame
/Timer.h
UHC
1,598
3.515625
4
[]
no_license
#pragma once #include <SDL.h> class Timer { public: Timer(); ~Timer(); void setInterval(int interval); // Ÿ̸ ֱ⸦ void start(); // Ÿ̸Ӹ void pause(); // Ÿ̸Ӹ void resume(); // Ÿ̸Ӹ bool done(); // Ÿ̸ ð Ǿ private: int interval; // Ÿ̸ ֱ int startTicks; // Ÿ̸Ӱ ۵ tick int pauseTicks; // Ÿ̸Ӹ Ͻ tick }; Timer::Timer() { // ʱȭ interval = 0; startTicks = 0; pauseTicks = 0; } Timer::~Timer() { } void Timer::setInterval(int interval) { this->interval = interval; } void Timer::start() { startTicks = SDL_GetTicks(); // startTicks Ÿ̸Ӱ ۵ tick } void Timer::pause() { if (pauseTicks == 0) pauseTicks = SDL_GetTicks(); // pauseTicks Ÿ̸Ӱ Ͻ tick } void Timer::resume() { if (pauseTicks != 0) { startTicks += SDL_GetTicks() - pauseTicks; // startTicks Ͻ Ⱓ( tick Ͻ tick ) // ؼ Ͻ Ⱓŭ Ÿ̸Ӹ ڷ ̷. pauseTicks = 0; // pauseTicks 0 } } bool Timer::done() { if (pauseTicks == 0 && // ǻ ƴϰ SDL_GetTicks() - startTicks >= interval) { // tick Ÿ̸Ӱ ۵ tick ֱ⸦ Ѿ start(); // Ÿ̸Ӹ return true; // trueȯ } return false; }
true
6055e7958784f6c7c29f601aec072ebd8d5b32bf
C++
Dixit6054/Linked-List
/mid element.cpp
UTF-8
1,449
3.921875
4
[]
no_license
//this will find you the middle element of a linked list #include<iostream> using namespace std; struct node { int data; node* link; }; void insert(int data , node** head , node** last, int key) { if(key==1) { node* temp = new node; (*temp).data = data; node* c; c = *head; *head = temp; temp->link = c; if(*last == NULL) *last = temp; } else { node* temp = new node; temp->data = data; temp->link= NULL; if(*last == NULL) *last = temp;//(*last)->link = temp; else { (*last)->link = temp; *last = temp; } if(*head==NULL) *head=temp; } } void print (node* head) { while(head != NULL) { cout << head->data <<" "; head = head->link; } cout<<endl; } void middle(node* head) { node *slow=head,*fast=head,*back_mid; while(fast && fast->link) { fast = fast->link->link; back_mid = slow; slow = slow->link; } if(fast==NULL) //for even list { cout << "I have got a even sting. thus two middles are: " << back_mid->data <<" and "<<slow->data; } else cout << "your middle element is: " << slow->data; } main() { node* head = NULL; node* last = NULL; insert(1,&head,&last,0); insert(2,&head,&last,0); insert(3,&head,&last,0); insert(4,&head,&last,0); insert(3,&head,&last,0); insert(2,&head,&last,0);//2 0 5 7 12 21 insert(1,&head,&last,0); print(head); middle(head); }
true
da0c9bf5406ecc53fa171f7049b84135b99c5b23
C++
sryanyuan/bmfragments
/bmtilemap.h
UTF-8
2,722
2.515625
3
[ "MIT" ]
permissive
#ifndef _INC_TILEMAP_ #define _INC_TILEMAP_ #include <stdint.h> struct BMMapInfo { int nRow; int nCol; int nWidth; int nHeight; }; struct BMMapHeader { // 48*32 Col Row uint16_t bCol; uint16_t bRow; char szTitle[16]; uint8_t UpdateTime[8]; uint8_t Reserve[24]; }; struct BMMapTile { // 96*64 image -> Index of Tiles, the highest bit is movable uint32_t wBkImg; uint16_t wBkIndex; // 48*32 small image -> Index of SmTiles uint32_t wMidImg; uint16_t wMidIndex; // Groud object, -> Index of Objects, the highest bit is movable uint32_t wFrImg; uint16_t wFrIndex; // Has a door or not, the highest bit represents has or not, the other are // door index uint8_t bDoorIndex; // Door open or close uint8_t bDoorOffset; // Animation uint8_t bFrAniFrame; // Animation tick uint8_t bFrAniTick; uint8_t bMidAniFrame; uint8_t bMidAniTick; uint16_t wBkAniImg; uint16_t wBkAniOffset; uint8_t bBkAniFrames; uint8_t bLight; uint8_t bUnknown; // Object index uint8_t bArea; }; class BMTileMap { public: BMTileMap(); ~BMTileMap(); public: bool CreateMap(int row, int col); void DestroyMap(); bool LoadMap(const char *filename); bool GetMapSnapShot(const char *filename, uint32_t **out, BMMapInfo *info); bool IsDataInside() { return nullptr != tile_data_; } int GetResIndex() { return *(int *)&header_.Reserve[0]; } void SetResIndex(int index) { *(int *)&header_.Reserve[0] = index; } const BMMapTile *GetTileData() { return tile_data_; } const BMMapHeader *GetMapHeader() { return &header_; } const BMMapTile *GetMapTile(int x, int y) const { if (x < 0 || x >= header_.bCol) { return nullptr; } if (y < 0 || y >= header_.bRow) { return nullptr; } return &tile_data_[y * header_.bCol + x]; } BMMapTile *GetMapTile(int x, int y) { if (x < 0 || x >= header_.bCol) { return nullptr; } if (y < 0 || y >= header_.bRow) { return nullptr; } return &tile_data_[y * header_.bCol + x]; } public: static bool MergeOne(const char *mapname, const char *destmapname, int resid, const char *datadir); private: bool loadMap100(uint8_t *data); bool loadMap5(uint8_t *data); bool loadMap6(uint8_t *data); bool loadMap4(uint8_t *data); bool loadMap1(uint8_t *data); bool loadMap3(uint8_t *data); bool loadMap2(uint8_t *data); bool loadMap7(uint8_t *data); bool loadMap0(uint8_t *data); private: BMMapTile *tile_data_; BMMapHeader header_; }; #endif
true
72ca09413a1be178db18c2e5e90f6d16aa530bb1
C++
palainp/esp8266_maze
/src/Teleport.hpp
UTF-8
2,090
2.8125
3
[ "MIT" ]
permissive
#ifndef TELEPORT_H #define TELEPORT_H #include "Item.hpp" class Teleport:public Item { public: Teleport(int32_t x, int32_t y):Item(x,y){ cell_text = { "Something buuzzzz in the ", }; cell_distance = {4}; cell_show_direction = {true}; }; std::string display_text(Player &p) { std::string str = ""; if (distance(p)==0) { str += SSTR(" .-'''-. .-'''-. \r\n"); str += SSTR(" ' _ \\ ' _ \\ \r\n"); str += SSTR(" / /` '. \\ / /` '. \\ . \r\n"); str += SSTR(" _ _. | \\ ' . | \\ ' .'| \r\n"); str += SSTR(" /\\ \\ //| ' | '| ' | ' < | \r\n"); str += SSTR(" `\\ //\\ // \\ \\ / / \\ \\ / / | | \r\n"); str += SSTR(" \\`// \'/ `. ` ..' / `. ` ..' / _ | | .'''-. \r\n"); str += SSTR(" \\| |/ '-...-'` '-...-'`.' | | |/.'''. \\ \r\n"); str += SSTR(" ' . | /| / | | \r\n"); str += SSTR(" .'.'| |//| | | | \r\n"); str += SSTR(" .'.'.-' / | | | | \r\n"); str += SSTR(" .' \\_.' | '. | '. \r\n"); str += SSTR(" '---' '---' \r\n"); // we must have random teleport as unfortunatly one can be on the only way to the exit... p.teleport(x+rand()%20-10,y+rand()%20-10); } else { return Item::display_text(p); } return str; }; std::string display_cell(Player &p) { #ifdef DEBUG std::string str = " Teleport: "; str += SSTR(x << ","<< y); return str; #else return ""; #endif }; }; #endif
true
00ecdc4f3ea11451223f999c6fba0e77f462ca2c
C++
amychou/cs166-project
/TangoTree.cpp
UTF-8
5,712
3.453125
3
[]
no_license
#include "TangoTree.h" #include <iostream> using namespace std; /** * Given a list of the future access probabilities of the elements 0, 1, 2, * ..., weights.size() - 1, constructs a new splay tree holding those * elements. * * Because splay trees rearrange their elements in response to queries, you * can safely ignore the assigned probabilities here and just build a BST * storing the elements 0, 1, 2, ..., weights.size() - 1 however you'd like. */ TangoTree::TangoTree(const std::vector<double>& weights) { //cout << "Building tree for " << weights.size() << " elements"<< endl; root = treeFor(0, weights.size()); } /** * Constructs a perfectly balanced tree for the values in the range * [low, high). */ TangoTree::Node* TangoTree::treeFor(size_t low, size_t high) { // TODO : FIX with a constructor for Node /* Base Case: The empty range is represented by an empty tree. */ if (low == high) return nullptr; /* Otherwise, pull out the middle, then recursively construct trees for the * left and right ranges. */ size_t mid = low + (high - low) / 2; return new Node { mid, treeFor(low, mid), treeFor(mid + 1, high) }; } /** * Frees all memory used by this tree. */ TangoTree::~TangoTree() = default; /** * Determines whether the specified key is present in the splay tree. Your * implementation should use only O(1) memory. We recommend looking up the * top-down splaying approach described in Sleator and Tarjan's paper, * tracing through it, and coding it up. */ bool TangoTree::contains(size_t key) const { Node* curr = root; while (curr != NULL) { if (key < curr->key) { curr = curr->left; } else if (key > curr->key) { curr = curr->right; } else { break; } if (curr->marked) curr = cutAndJoin(curr); } Node *top_path = curr; while (!top_path->marked) { top_path = top_path->parent; } Node *node = cut(top_path, curr->depth); Node *pred = findMarkedPredecessor(node, curr->key); if (pred) { join(node, pred, curr->depth); } return curr and (curr->key == key); } TangoTree::Node* TangoTree::cutAndJoin(TangoTree::Node *node) const { Node *top_path = node->parent; while (!top_path->marked) { top_path = top_path->parent; } int cut_depth = node->min_depth - 1; top_path = cut(top_path, cut_depth); top_path = join(top_path, node, cut_depth); return top_path; } TangoTree::Node* TangoTree::cut(TangoTree::Node *v_root, int depth) const { Node* l = findMinWithDepth(v_root, depth); Node* r = findMaxWithDepth(v_root, depth); Node* lp = l ? getPredecessorByNode(l) : NULL; Node* rp = r ? getSuccessorByNode(r) : NULL; Node* n_root = NULL; if (!lp and !rp) { n_root = v_root; } else if (!rp) { split(lp, v_root); lp->right->marked = true; updateMinMaxPath(lp); n_root = merge(lp); } else if (!lp) { split(rp, v_root); rp->left->marked = true; updateMinMaxPath(rp); n_root = merge(rp); } else { split(lp, v_root); split(rp, lp->right); rp->left->marked = true; updateMinMaxPath(rp); merge(rp); n_root = merge(lp); } return n_root; } TangoTree::Node* TangoTree::join(TangoTree::Node *top_path, TangoTree::Node *n, int depth) const { Node* n_root = NULL; Node* lp = NULL; Node* rp = NULL; Node* curr = top_path; while (curr != n) { if (curr->key > n->key) { rp = curr; curr = curr->left; } else { lp = curr; curr = curr->right; } } if (!rp) { split(lp, top_path); lp->right->marked = false; updateMinMaxPath(lp->right); n_root = merge(lp); } else if (!lp) { split(rp, top_path); rp->left->marked = false; updateMinMaxPath(rp->left); n_root = merge(rp); } else { split(lp, top_path); split(rp, lp->right); rp->left->marked = false; updateMinMaxPath(rp->left); merge(rp); n_root = merge(lp); } return n_root; } TangoTree::Node* TangoTree::findMinWithDepth(TangoTree::Node *n, int depth) const { while (true) { Node *nl = n->left, *nr = n->right; if (!isLeaf(nl) and nl->max_depth > depth) { n = nl; } else if (n->depth > depth) { return n; } else if (!isLeaf(nr)) { n = nr; } else { return NULL; } } } TangoTree::Node* TangoTree::findMaxWithDepth(TangoTree::Node *n, int depth) const { while (true) { Node *nl = n->left, *nr = n->right; if (!isLeaf(nr) and nr->max_depth > depth) { n = nr; } else if (n->depth > depth) { return n; } else if (!isLeaf(nl)) { n = nl; } else { return NULL; } } } TangoTree::Node* TangoTree::findMarkedPredecessor(TangoTree::Node *node, size_t key) const { Node *curr = node; key--; while (curr and curr->key) { if (key < curr->key) { curr = curr->left; } else if (key > curr->key) { curr = curr->right; } else { return NULL; } if (curr->marked) { return curr; } } return NULL; } void TangoTree::updateMinMaxPath(TangoTree::Node *n) const { // updateMinMax(n); while (!n->parent) { n = n->parent; updateMinMaxPath(n); } }
true
66990939792eb3c04642f7d48519dc4da678f7b8
C++
ngohoa/rstartree
/src/rstartree.h
UTF-8
2,984
2.5625
3
[]
no_license
/* Copyright (C) 2010 by The Regents of the University of California Redistribution of this file is permitted under the terms of the BSD license. Date: 11/01/2009 Author: Sattam Alsubaiee <salsubai (at) ics.uci.edu> */ #include "storage.h" #include "util.h" #include <vector> #include <stack> #include <map> #include <tr1/unordered_set> typedef unsigned char byte; const unsigned BRANCH_FACTOR = 32; const double REINSERT_FACTOR = 0.3; const double SPLIT_FACTOR = 0.4; const unsigned NEAR_MINIMUM_OVERLAP_FACTOR = 32; class Node: public Buffer { public: // the node's level in the tree, level 0 is the leaf level unsigned level; // number of entries in the node unsigned numChildren; Rectangle mbr; // node's entries Object objects[BRANCH_FACTOR]; // check whether the node is a leaf node or not bool isLeaf() const { return level == 0; }; }; class RTree { protected: Storage *storage; size_t nodeSize; unsigned branchFactor; double fillFactor; // the implementation of the r*-tree insert function void insertData(const Object &obj, unsigned desiredLevel, byte *overflowArray); // the implementation of the r*-tree delete function bool deleteData(const Object &obj, stack<unsigned> &path, unsigned id); // r*-tree reinsert function void reinsert(Node *node, stack<Node *> path, unsigned desiredLevel, unsigned position, byte *overflowArray); // r*-tree split function void split(Node *node, Object &a, Object &b); // delete an object from a node void deleteObject(Node *node, unsigned id); // condense the tree after a deletetion void condenseTree(Node* node, stack<unsigned> &path, stack<unsigned> &needReinsertion); // adjust the MBR for a node after r*-tree split void adjustNode(Node *node, Object &a, vector <EntryValue> &entries, unsigned startIndex, unsigned endIndex); // adjust the MBR for a node after r*-tree split void adjustNode(Node *node); // the implementation of range query function for both r-tree and r*-tree void rangeQuery(vector<Object> &objects, const Rectangle &range, unsigned id); bool retrieve(unordered_set<unsigned> &ids, unsigned oid, unsigned id); public: unsigned nodeNum; RTree(Storage *storage); // create r*-tree void create(unsigned bf, double ff); // r*-tree insert function void insertData(const Object &obj); // r*-tree delete function void deleteData(const Object &obj); // range query function for both r-tree and r*-tree void rangeQuery(vector<Object> &objects, const Rectangle &range); // top k nearest neighbour function for both r-tree and r*-tree void kNNQuery(multimap<double, Object> &objects, const Point &point, unsigned k); void retrieve(unordered_set<unsigned> &ids, unsigned oid); };
true
d9fae577d58e4dd748f25884a41cebb0768d885e
C++
mzorro/poj-cpp
/1005 -- I Think I Need a Houseboat/main.cpp
UTF-8
427
2.90625
3
[]
no_license
#include <iostream> using namespace std; #define PI 3.1415f #pragma warning(disable:4996) int main() { //freopen("..\\test.txt", "r", stdin); int N; cin >> N; for (int i = 1; i <= N; i++) { cout << "Property " << i; cout << ": This property will begin eroding in year "; float x, y; cin >> x >> y; int year = int((x*x + y*y) * PI / 100) + 1; cout << year << '.' << endl; } cout << "END OF OUTPUT." << endl; }
true
dcbe8c4676a1a89cef2134f283977cd942265294
C++
fermi-lat/observationSim
/observationSim/ScData.h
UTF-8
2,620
2.640625
3
[ "BSD-3-Clause" ]
permissive
/** * @file ScData.h * @brief Simple data structure to hold ScData data. * @author J. Chiang * $Header: /nfs/slac/g/glast/ground/cvs/observationSim/observationSim/ScData.h,v 1.8 2005/08/26 15:55:49 jchiang Exp $ */ #ifndef observationSim_ScData_h #define observationSim_ScData_h #include "astro/SkyDir.h" namespace observationSim { /** * @class ScData * @brief Simple data structure to hold ScData data. * @author J. Chiang * * $Header: /nfs/slac/g/glast/ground/cvs/observationSim/observationSim/ScData.h,v 1.8 2005/08/26 15:55:49 jchiang Exp $ */ class ScData { public: ScData(double time, double RAz, double Decz, double lon, double lat, const astro::SkyDir &zAxis, const astro::SkyDir &xAxis, bool inSAA, const std::vector<double> & position, double raZenith, double decZenith, double livetimeFrac) : m_time(time), m_RAz(RAz), m_Decz(Decz), m_lon(lon), m_lat(lat), m_zAxis(zAxis), m_xAxis(xAxis), m_inSaa(inSAA), m_position(position), m_raZenith(raZenith), m_decZenith(decZenith), m_livetimeFrac(livetimeFrac) {} /// Time in seconds (referenced to the zero time of the orbit /// calculation in astro::EarthOrbit). double time() const {return m_time;} /// The RA of the instrument z-axis in degrees. double raz() const {return m_RAz;} /// The Dec of the instrument z-axis in degrees. double decz() const {return m_Decz;} /// The Earth longitude of the spacecraft in degrees. double lon() const {return m_lon;} /// The Earth latitude of the spacecraft in degrees. double lat() const {return m_lat;} /// The spacecraft z-axis in "Celestial" (J2000?) coordinates. astro::SkyDir zAxis() const {return m_zAxis;} /// The spacecraft x-axis in "Celestial" (J2000?) coordinates. astro::SkyDir xAxis() const {return m_xAxis;} /// Flag to indicate if the spacecraft is in the SAA. bool inSaa() const {return m_inSaa;} /// The spacecraft position in geocentric coordinates (m). const std::vector<double> & position() const {return m_position;} double raZenith() const {return m_raZenith;} double decZenith() const {return m_decZenith;} // Live-time fraction for the current interval double livetimeFrac() const {return m_livetimeFrac;} private: double m_time; double m_RAz; double m_Decz; double m_lon; double m_lat; astro::SkyDir m_zAxis; astro::SkyDir m_xAxis; bool m_inSaa; std::vector<double> m_position; double m_raZenith; double m_decZenith; double m_livetimeFrac; }; } // namespace observationSim #endif // observationSim_ScData_h
true
aac7359ed25f95966465d86b4cfeb3ba62750cbb
C++
juejian/Data-Structures-and-Algorithm-Analysis-in-Cpp-4th
/01-src-code/part1/matrix.h
UTF-8
1,365
3.5
4
[]
no_license
/// @file matrix.h /// @date 2019-02-24 17:38:08 #ifndef __MATRIX_H__ #define __MATRIX_H__ #include <iostream> #include <vector> #include <initializer_list> template <typename Object> class Matrix { public: Matrix(int rows, int cols) :array_(rows, std::vector<Object>(cols, Object{})) {} Matrix(std::initializer_list<std::vector<Object>> lst) :array_(lst.size()) { int i = 0; for(auto& v : lst) array_[i++] = std::move(v); } Matrix(const std::vector<std::vector<Object>>& v) :array_{v} {} Matrix(std::vector<std::vector<Object>>&& v) :array_{std::move(v)} {} ~Matrix() = default; const std::vector<Object>& operator[] (int row) const { return array_[row]; } std::vector<Object>& operator[] (int row) { return array_[row]; } std::size_t numrows() const { return array_.size(); } std::size_t numcols() const { return numrows() ? array_[0].size() : 0; } private: std::vector<std::vector<Object>> array_; }; template <typename Object> std::ostream& operator<< (std::ostream& os, const Matrix<Object>& mat) { os << '[' << std::endl; for(std::size_t row = 0; row < mat.numrows(); ++row) { os << " " << '['; for(std::size_t col = 0; col < mat.numcols(); ++col) { os << mat[row][col] << ' '; } os << ']' << std::endl; } os << ']'; return os; } #endif
true
7839029b91e11c41539c9f2e1ade262e6935feff
C++
Ebyy/Cplusplus
/product_AidManagement_app/Perishable.h
UTF-8
606
2.5625
3
[]
no_license
/* ------------------------------------------- Name:Eberechi Ogunedo Student number: 117277160 Email: eokengwu@myseneca.ca Section: I Date:03/28/2019 ---------------------------------------------- Assignment: 1 Milestone: 5 ---------------------------------------------- */ #ifndef _PERISHABLE_H_ #define _PERISHABLE_H_ #include "Product.h" #include "Date.h" using namespace std; namespace ama { class Perishable : public Product { Date expiryDate; public: Perishable(char tag = 'P'); istream& read(istream&, bool interractive); ostream& write(ostream& out, int writeMode) const; }; } #endif // !_PERISHABLE_H
true
f15df1af54190981b2cf7647315f5c2986bdb2cc
C++
Jeanmilost/Demos
/Dev-Cpp/DirectX/Collisions 3D/Sources/e_polygon.cpp
ISO-8859-1
4,165
3.171875
3
[ "MIT" ]
permissive
/***************************************************************************** * ==> Classe E_Polygon -----------------------------------------------------* * *************************************************************************** * Description : Cette classe reprsente un polygone 3 sommets. * * Version : 1.0 * * Dveloppeur : Jean-Milost Reymond * *****************************************************************************/ #include "e_polygon.h" // Constructeur de la classe E_Polygon. E_Polygon::E_Polygon() { p_Vertex[0] = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); p_Vertex[1] = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); p_Vertex[2] = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); } // Deuxime constructeur de la classe E_Polygon. E_Polygon::E_Polygon( D3DXVECTOR3 Vertex1, D3DXVECTOR3 Vertex2, D3DXVECTOR3 Vertex3 ) { p_Vertex[0] = Vertex1; p_Vertex[1] = Vertex2; p_Vertex[2] = Vertex3; } // Destructeur de la classe E_Polygon. E_Polygon::~E_Polygon() { } // Obtient le sommet l'index spcifi. D3DXVECTOR3 E_Polygon::GetVertex( int Index ) { // On applique un masque binaire de 3 sur l'index (valeur binaire 0011), // ceci afin de garantir que l'utilisateur ne pourra jamais dpasser les // valeurs limites du tableau de sommets. C'est ce que l'on appelle un // tableau circulaire. return p_Vertex[Index&3]; } // Dfinit le sommet l'index spcifi. void E_Polygon::SetVertex( int Index, D3DXVECTOR3 Vertex ) { // On applique un masque binaire de 3 sur l'index (valeur binaire 0011), // ceci afin de garantir que l'utilisateur ne pourra jamais dpasser les // valeurs limites du tableau de sommets. C'est ce que l'on appelle un // tableau circulaire. p_Vertex[Index&3] = Vertex; } // Obtient la coordonne du premier sommet du polygone. D3DXVECTOR3 E_Polygon::GetVertex1() { return p_Vertex[0]; } // Dfinit la coordonne du premier sommet du polygone. void E_Polygon::SetVertex1( D3DXVECTOR3 Value ) { p_Vertex[0] = Value; } // Obtient la coordonne du deuxime sommet du polygone. D3DXVECTOR3 E_Polygon::GetVertex2() { return p_Vertex[1]; } // Dfinit la coordonne du deuxime sommet du polygone. void E_Polygon::SetVertex2( D3DXVECTOR3 Value ) { p_Vertex[1] = Value; } // Obtient la coordonne du troisime sommet du polygone. D3DXVECTOR3 E_Polygon::GetVertex3() { return p_Vertex[2]; } // Dfinit la coordonne du troisime sommet du polygone. void E_Polygon::SetVertex3( D3DXVECTOR3 Value ) { p_Vertex[2] = Value; } // Obtient le plan du polygone. D3DXPLANE E_Polygon::GetPlane() { D3DXPLANE thePlane; // On calcule le plan partir des valeurs des 3 sommets du polygone. D3DXPlaneFromPoints( &thePlane, &p_Vertex[0], &p_Vertex[1], &p_Vertex[2] ); // Puis, on retourne le plan. return thePlane; } // Obtient le point central du polygone. D3DXVECTOR3 E_Polygon::GetCenter() { // On calcule, puis on retourne la valeur du point central du polygone. return D3DXVECTOR3 ( ( ( p_Vertex[0].x + p_Vertex[1].x + p_Vertex[2].x ) / 3.0f ), ( ( p_Vertex[0].y + p_Vertex[1].y + p_Vertex[2].y ) / 3.0f ), ( ( p_Vertex[0].z + p_Vertex[1].z + p_Vertex[2].z ) / 3.0f ) ); } // Obtient un clone du polygone. E_Polygon E_Polygon::GetClone() { // On copie le polygone, puis on retourne la copie. return E_Polygon( p_Vertex[0], p_Vertex[1], p_Vertex[2] ); } // Obtient un clone du polygone transform selon une matrice donne. E_Polygon E_Polygon::ApplyMatrix( D3DXMATRIXA16 Matrix ) { D3DXVECTOR3 TVertex[3]; // On transforme chacun des sommets du polygone avec la matrice donne. D3DXVec3TransformCoord( &TVertex[0], &p_Vertex[0], &Matrix ); D3DXVec3TransformCoord( &TVertex[1], &p_Vertex[1], &Matrix ); D3DXVec3TransformCoord( &TVertex[2], &p_Vertex[2], &Matrix ); // Puis, on retourne une copie du polygone, avec les nouvelles valeurs. return E_Polygon( TVertex[0], TVertex[1], TVertex[2] ); }
true
3a4b4656f7c23247078284ff3ab649ea38617587
C++
jiez/advent-of-code-2020
/07/haversacks.cc
UTF-8
2,922
3.265625
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <map> #include <unordered_set> #include <iterator> #include <algorithm> #include <regex> int solution_for_puzzle_1(std::vector<std::vector<int>> &bags, int start_bag) { std::unordered_set<int> bag_set; std::unordered_set<int> working_set{start_bag}; while (working_set.size() > 0) { std::unordered_set<int> new_set; for (auto b: working_set) { bag_set.insert(b); for (int i = 0; i < bags.size(); i++) if (bags[i][b] > 0) new_set.insert(i); } working_set = std::move(new_set); } return bag_set.size() - 1; } static int required_bags(std::vector<std::vector<int>> &bags, int bag) { int count = 1; for (int i = 0; i < bags[bag].size(); i++) { int b = bags[bag][i]; if (b > 0) count += required_bags(bags, i) * b; } return count; } int solution_for_puzzle_2(std::vector<std::vector<int>> &bags, int start_bag) { return required_bags(bags, start_bag) - 1; } int main() { std::ifstream input_file{"input"}; if (!input_file) { std::cout << "input file is missing\n"; return -1; } std::string line; std::vector<std::vector<int>> bags; std::map<std::string, int> color2index; std::vector<std::string> colors; std::regex bag_color{"([a-z]+ [a-z]+) bags contain "}; int color_index = 0; while (getline(input_file, line)) { //std::cout << line << "\n"; std::smatch m; std::regex_search(line, m, bag_color); std::string color = m[1]; colors.push_back(color); color2index.insert({color, color_index}); color_index++; } int num_of_colors = color_index; input_file.clear(); input_file.seekg(0, input_file.beg); std::regex bag_color2{"([0-9]+) ([a-z]+ [a-z]+) bag"}; color_index = 0; while (getline(input_file, line)) { //std::cout << line << "\n"; std::vector<int> containing_bags(num_of_colors, 0); std::smatch m; std::regex_search(line, m, bag_color); std::string s = m.suffix().str(); while(std::regex_search(s, m, bag_color2)) { //std::cout << m[2] << ":" << color2index[m[2]] << ":" << m[1] << "\n"; containing_bags[color2index[m[2]]] = std::stoi(m[1]); s = m.suffix().str(); } bags.push_back(std::move(containing_bags)); } int how_many; how_many = solution_for_puzzle_1(bags, color2index["shiny gold"]); std::cout << "The number of bags containing shiny gold: " << how_many << " (378 expected)\n"; how_many = solution_for_puzzle_2(bags, color2index["shiny gold"]); std::cout << "The number of bags required inside shiny gold bag: " << how_many << " (27526 expected)\n"; return 0; }
true
a3a5920aca1eda90f8c2591ea4eee8befd7cfb31
C++
ucpu/cage
/sources/libcore/geometry/shapes.cpp
UTF-8
8,276
2.796875
3
[ "MIT" ]
permissive
#include <cage-core/geometry.h> namespace cage { Line Line::operator*(const Mat4 &other) const { CAGE_ASSERT(normalized()); const auto &tr = [&](const Vec3 &p) { Vec4 t = other * Vec4(p, 1); return Vec3(t) / t[3]; }; if (isPoint()) return Line(tr(a()), Vec3(1, 0, 0), 0, 0); if (isLine()) return makeLine(tr(origin), tr(origin + direction)); if (isRay()) return makeRay(tr(origin), tr(origin + direction)); if (isSegment()) return makeSegment(tr(a()), tr(b())); CAGE_THROW_CRITICAL(Exception, "geometry"); } bool Line::normalized() const { if (isPoint()) { if (minimum != 0) return false; if (direction != Vec3(1, 0, 0)) return false; } else if (isLine()) { if (minimum != -Real::Infinity() || maximum != Real::Infinity()) return false; } else if (isRay()) { if (minimum != 0 || maximum != Real::Infinity()) return false; } else if (isSegment()) { if (minimum != 0 || maximum <= 0) return false; } else return false; return abs(lengthSquared(direction) - 1) < 1e-5; } Line Line::normalize() const { Line r = *this; if (r.isPoint() || lengthSquared(r.direction) < 1e-5) { r.origin = r.a(); r.direction = Vec3(1, 0, 0); r.minimum = r.maximum = 0; } else { if (r.minimum > r.maximum) std::swap(r.minimum, r.maximum); r.direction = cage::normalize(r.direction); Real l = length(direction); r.minimum *= l; r.maximum *= l; if (r.minimum.finite()) { if (r.minimum != 0) { r.origin = r.a(); r.maximum -= r.minimum; r.minimum = 0; } } else if (r.maximum.finite()) r = Line(r.b(), -r.direction, 0, Real::Infinity()); if (r.isLine()) { //real d = distance(vec3(), r); // todo } } CAGE_ASSERT(r.normalized()); return r; } Line makeSegment(const Vec3 &a, const Vec3 &b) { return Line(a, b - a, 0, 1).normalize(); } Line makeRay(const Vec3 &a, const Vec3 &b) { return Line(a, b - a, 0, Real::Infinity()).normalize(); } Line makeLine(const Vec3 &a, const Vec3 &b) { return Line(a, b - a, -Real::Infinity(), Real::Infinity()).normalize(); } Triangle Triangle::operator*(const Mat4 &other) const { Triangle r = *this; for (uint32 i = 0; i < 3; i++) { Vec4 t = other * Vec4(r[i], 1); r[i] = Vec3(t) / t[3]; } return r; } bool Triangle::degenerated() const { return area() < 1e-5; } Triangle Triangle::flip() const { Triangle r = *this; std::swap(r[1], r[2]); return r; } Plane::Plane(const Vec3 &point, const Vec3 &normal) : normal(normal), d(-dot(point, normal)) {} Plane::Plane(const Vec3 &a, const Vec3 &b, const Vec3 &c) : Plane(Triangle(a, b, c)) {} Plane::Plane(const Triangle &other) : Plane(other[0], other.normal()) {} Plane::Plane(const Line &a, const Vec3 &b) : Plane(a.origin, a.origin + a.direction, b) {} Plane Plane::operator*(const Mat4 &other) const { Vec3 p3 = normal * d; Vec4 p4 = Vec4(p3, 1) * other; p3 = Vec3(p4) / p4[3]; return Plane(p3, normal * Mat3(other)); } bool Plane::normalized() const { return abs(lengthSquared(normal) - 1) < 1e-5; } Plane Plane::normalize() const { const Real l = length(normal); return Plane(normal / l, d * l); // d times or divided by l ? } Sphere::Sphere(const Line &other) { if (!other.valid()) *this = Sphere(); else if (other.isPoint()) *this = Sphere(other.a(), 0); else if (other.isSegment()) { const Vec3 a = other.a(); const Vec3 b = other.b(); *this = Sphere((a + b) * 0.5, distance(a, b) * 0.5); } else *this = Sphere(Vec3(), Real::Infinity()); } Sphere::Sphere(const Triangle &other) { Vec3 a = other[0]; Vec3 b = other[1]; Vec3 c = other[2]; Real dotABAB = dot(b - a, b - a); Real dotABAC = dot(b - a, c - a); Real dotACAC = dot(c - a, c - a); Real d = 2.0f * (dotABAB * dotACAC - dotABAC * dotABAC); Vec3 referencePt = a; if (abs(d) <= 1e-5) { Aabb bbox = Aabb(other); center = bbox.center(); referencePt = bbox.a; } else { Real s = (dotABAB * dotACAC - dotACAC * dotABAC) / d; Real t = (dotACAC * dotABAB - dotABAB * dotABAC) / d; if (s <= 0.0f) center = 0.5f * (a + c); else if (t <= 0.0f) center = 0.5f * (a + b); else if (s + t >= 1.0f) { center = 0.5f * (b + c); referencePt = b; } else center = a + s * (b - a) + t * (c - a); } radius = distance(center, referencePt); } Sphere::Sphere(const Cone &other) { // https://bartwronski.com/2017/04/13/cull-that-cone/ modified if (other.halfAngle > Rads(Real::Pi() / 4)) { *this = Sphere(other.origin + cos(other.halfAngle) * other.length * other.direction, sin(other.halfAngle) * other.length); } else { const Real ca2 = 1 / (2 * cos(other.halfAngle)); *this = Sphere(other.origin + other.length * ca2 * other.direction, other.length * ca2); } } Sphere Sphere::operator*(const Mat4 &other) const { Real sx2 = lengthSquared(Vec3(other[0], other[1], other[2])); Real sy2 = lengthSquared(Vec3(other[4], other[5], other[6])); Real sz2 = lengthSquared(Vec3(other[8], other[9], other[10])); Real s = sqrt(max(max(sx2, sy2), sz2)); Vec4 p4 = Vec4(center, 1) * other; return Sphere(Vec3(p4) / p4[3], radius * s); } Aabb::Aabb(const Line &other) { if (!other.valid()) *this = Aabb(); else if (other.isSegment() || other.isPoint()) { Vec3 a = other.a(); Vec3 b = other.b(); *this = Aabb(a, b); } else *this = Aabb::Universe(); } Aabb::Aabb(const Plane &other) { CAGE_ASSERT(other.normalized()); *this = Aabb::Universe(); const Vec3 o = other.origin(); for (uint32 a = 0; a < 3; a++) { if (abs(abs(other.normal[a]) - 1) < 1e-5) this->a[a] = this->b[a] = o[a]; } } // todo optimize Aabb::Aabb(const Cone &other) : Aabb(Sphere(other)) {} Aabb::Aabb(const Frustum &other) { Aabb box; Frustum::Corners corners = other.corners(); for (const Vec3 &v : corners.data) box += Aabb(v); *this = box; } Aabb Aabb::operator+(const Aabb &other) const { if (other.empty()) return *this; if (empty()) return other; return Aabb(min(a, other.a), max(b, other.b)); } Aabb Aabb::operator*(const Mat4 &other) const { Vec3 tmp[8]; tmp[0] = Vec3(b.data[0], a.data[1], a.data[2]); tmp[1] = Vec3(a.data[0], b.data[1], a.data[2]); tmp[2] = Vec3(a.data[0], a.data[1], b.data[2]); tmp[3] = Vec3(a.data[0], b.data[1], b.data[2]); tmp[4] = Vec3(b.data[0], a.data[1], b.data[2]); tmp[5] = Vec3(b.data[0], b.data[1], a.data[2]); tmp[6] = a; tmp[7] = b; Aabb res; for (uint32 i = 0; i < 8; i++) { Vec4 r = other * Vec4(tmp[i], 1); res += Aabb(Vec3(r) * (1.0 / r.data[3])); } return res; } Real Aabb::volume() const { return empty() ? 0 : (b.data[0] - a.data[0]) * (b.data[1] - a.data[1]) * (b.data[2] - a.data[2]); } Real Aabb::surface() const { Real wx = b[0] - a[0]; Real wy = b[1] - a[1]; Real wz = b[2] - a[2]; return (wx * wy + wx * wz + wy * wz) * 2; } Cone Cone::operator*(const Mat4 &other) const { CAGE_THROW_CRITICAL(Exception, "geometry"); } Frustum::Frustum(const Transform &camera, const Mat4 &proj) : Frustum(proj * Mat4(inverse(camera))) {} Frustum::Frustum(const Mat4 &viewProj) : viewProj(viewProj) { const auto &column = [&](uint32 index) { return Vec4(viewProj[index], viewProj[index + 4], viewProj[index + 8], viewProj[index + 12]); }; const Vec4 c0 = column(0); const Vec4 c1 = column(1); const Vec4 c2 = column(2); const Vec4 c3 = column(3); planes[0] = c3 + c0; planes[1] = c3 - c0; planes[2] = c3 + c1; planes[3] = c3 - c1; planes[4] = c3 + c2; planes[5] = c3 - c2; } Frustum Frustum::operator*(const Mat4 &other) const { return Frustum(viewProj * other); } Frustum::Corners Frustum::corners() const { const Mat4 invVP = inverse(viewProj); static constexpr const Vec3 clipCorners[8] = { Vec3(-1, -1, -1), Vec3(-1, -1, +1), Vec3(-1, +1, -1), Vec3(-1, +1, +1), Vec3(+1, -1, -1), Vec3(+1, -1, +1), Vec3(+1, +1, -1), Vec3(+1, +1, +1), }; Frustum::Corners res; int i = 0; for (const Vec3 &v : clipCorners) { const Vec4 p = invVP * Vec4(v, 1); res.data[i++] = Vec3(p) / p[3]; } return res; } }
true
7af7edbc24346b24df1d85f8e6ea93ac924df6f7
C++
jowoeber/cominterface
/example/example-cominterface.cpp
ISO-8859-1
4,862
3.34375
3
[ "MIT" ]
permissive
//============================================================================ // Name : example-cominterface.cpp // Author : Juan Manuel Fernndez Muoz // Date : January, 2017 // Description : Example for the Serial Port and Socket (server) interfaces //============================================================================ #include <iostream> #include <string> #include <stdlib.h> #include "cominterface/comserial.hpp" #include "cominterface/comsocket.hpp" int main() { ComInterface *interface; // Interface handler std::string sel_interface; // User interface selection std::string sel_port; // User port selection std::string description = "Program options:\n"\ "- Interface:\n"\ " + serial: use of the serial port.\n"\ " + socket: create a socket server waiting for incoming connections.\n"\ "- Port:\n"\ " + If Interface is serial, it is the name of the serial port to use, e.g. COM1.\n"\ " + If Interface is socket, it is the TCP port to use.\n"\ "Note: You can use a terminal program to test this program.\n"; // Print the program options description std::cout << description << std::endl; // User interface selection std::cout << "Interface = "; std::getline(std::cin, sel_interface); // User port selection std::cout << "Port = "; std::getline(std::cin, sel_port); // Create the selected interface with the given port if (sel_interface == "serial") interface = new ComSerial(sel_port, 38400, 8, 1, 'n', 'h', 1000); else if (sel_interface == "socket") { interface = new ComSocket("", atoi(sel_port.c_str()), 1000); // Give it 10 seconds to accept incoming connections static_cast<ComSocket*>(interface)->SetOpenTimeout(10000); } else { std::cout << "Invalid interface.\n" << "Press Enter for exit." << std::endl; // Wait until enter is pressed std::cin.ignore(); return 0; } // Try to open the interface if (interface->Open()) { std::string command; // Command to send char receive_buffer[128]; // Buffer for the received data int transmitted, received; // Number of bytes transmitted or received std::cout << "\nEnter your command or just press Enter without any input for exit.\n" << std::endl; while (true) { // Wait for the user input std::cout << "Tx: "; std::getline(std::cin, command); // if the user inputs Enter, the loop finishes if (command.empty()) break; // Send data through the interface transmitted = interface->Write(command.c_str(), command.length()); // Check the transmission if (transmitted == -1) { std::cout << "\nError transmitting data.\n" << "Press Enter for exit." << std::endl; // Wait until enter is pressed std::cin.ignore(); break; } else if (transmitted != static_cast<int>(command.length())) std::cout << "Incomplete data transmission." << std::endl; received = 0; std::cout << "Rx: "; // Receive data from the interface do { // In case of an event driven GUI you better use a non blocking // ReadSome(...) in your idle function. Here we have to wait for // the response before we send another user command received = interface->Read(receive_buffer, sizeof(receive_buffer) - 1); // Something received? if(received > 0) { // Null terminate the received string receive_buffer[received] = '\0'; // Print the received string std::cout << receive_buffer; } } while (received > 0); std::cout << std::endl; // Check the reception if (received == -1) { std::cout << "\nError receiving data.\n" << "Press Enter for exit." << std::endl; // Wait until enter is pressed std::cin.ignore(); break; } } // Close the interface interface->Close(); } else { std::cout << "\nError opening.\n" << "Press Enter for exit." << std::endl; // Wait until enter is pressed std::cin.ignore(); } // Free the interface resources delete interface; return 0; }
true
1809c6d95fbcd17e485d72f9f38d157dcaab36ca
C++
Neelabh-Dubey/Construct-O-Bot
/4_sensors_handeler/4_sensors_handeler.ino
UTF-8
1,425
2.90625
3
[]
no_license
/* * Author list: Neelabh Dubey * Filename: 4_sensors_handeler * Theme:Construct-o-bot * Functions: sensors_init(),read_line(),read_boxes() * Global variables: int ir_1,int ir_2 , int ir_3,String line, int left_sh,int right_sh * /* * Function name:sensors_init * input:void * output:void * Logic:function for initiliztion of pins for the sensors and line variable * Example call:sensors_init(); */ void sensors_init(){ line = ""; } /* * function: read_line * input: void * output: void * logic: This function updates the value of the global variable "line" with current values * read by the white line sensors and conveys the bot whether the line is black or white * Example call: read_line(); */ void read_line(){ ir_l = analogRead(A0); ir_m = analogRead(A1); ir_r = analogRead(A2); // Serial.print(ir_l); // Serial.print(" "); // Serial.print(ir_m); // Serial.print(" "); // Serial.println(ir_r); line = ""; if(ir_l > 50) line += 'B'; else line += 'W'; if(ir_m > 50) line += 'B'; else line += 'W'; if(ir_r > 50) line += 'B'; else line += 'W'; } /*Function:read_boxes *Input:void *Outut:void *Logic:This function is used to read values from the front sharp sensors when it faces a CM *Example call: read_boxes(); */ void read_boxes(){ left_sh = analogRead(A3);//F3 right_sh = analogRead(A4);//F4 Serial.print(left_sh); Serial.print(" "); Serial.println(right_sh); }
true
ee2a38d14ca551cb7e1bb8f44507e65a8631e776
C++
Ryanel/Blazar
/src/Blazar/Blazar/Renderer/Primitives/Texture.h
UTF-8
1,394
2.71875
3
[]
no_license
#pragma once #include <vector> #include "imgui.h" #include "Blazar/Assets/Resource.h" #include "Blazar/Memory.h" namespace Blazar { /// Determines whether a texture's U or V axis will repeat or clamp enum class TextureWrappingMode { Clamp, Repeat }; /// The texture filtering mode, how smooth or pixilated the texture is enum class TextureFilterMode { None, Bilinear }; enum class TextureSourceType { RAW_32BIT_RGBA, PNG }; struct TextureProperties { TextureWrappingMode wrap_x = TextureWrappingMode::Clamp; TextureWrappingMode wrap_y = TextureWrappingMode::Clamp; TextureFilterMode filtering = TextureFilterMode::Bilinear; TextureSourceType source_type = TextureSourceType::PNG; }; class Texture { public: virtual ~Texture() {} virtual uint32_t GetWidth() const = 0; virtual uint32_t GetHeight() const = 0; virtual void Bind(uint32_t slot = 0) const = 0; virtual uint32_t GetId() const = 0; virtual ImTextureID imgui_id() const = 0; std::string path; }; class Texture2D : public Texture { public: // Factory method static Ref<Texture> Create(const std::string& path, const TextureProperties& properties = TextureProperties()); static Ref<Resource<Texture2D>> Load(const std::string& path, TextureProperties props = TextureProperties()); }; }; // namespace Blazar
true
4c149a23dbe84cb21245850f8742abd0499d3e42
C++
lovelybigduck/note
/代码练习/刷题/2016天梯赛模拟题 查验身份证.cpp
GB18030
740
2.609375
3
[]
no_license
//2016ģ ֤ #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <vector> #include <queue> #include <stack> using namespace std; typedef long long ll; int main(){ int W[17]={7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2}; char M[11]={'1' ,'0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}; int n; cin>>n; string a[n]; vector<string> v; for(int i=0;i<n;i++){ cin>>a[i]; } for(int i=0;i<n;i++){ int sum=0; for(int j=0;j<17;j++){ sum+=(a[i][j]-'0')*W[j]; } int mod=sum%11; if(a[i][17]!=M[mod]) v.push_back(a[i]); } if(v.empty()) cout<<"All passed"<<endl; else{ for(vector<string>::iterator it=v.begin();it!=v.end();it++) cout<<*it<<endl; } return 0; }
true
404305cf7790887eeb38a6f42ea6908d13e17f7a
C++
xujie-nm/Leetcode
/103_Binary_Tree_Zigzag_level_Order_Traversal.cpp
UTF-8
1,808
3.453125
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; vector<vector<int> > zigzagLevelOrder(TreeNode *root){ vector<vector<int> > res; if(root == NULL) return res; int levelNumber = 1; int levelN = 1; queue<TreeNode*> level; level.push(root); while(!level.empty()){ vector<int> temp; for (int i = 0; i < levelNumber; i++) { TreeNode* node = level.front(); level.pop(); temp.push_back(node->val); if(node->left != NULL) level.push(node->left); if(node->right != NULL) level.push(node->right); } if(!temp.empty()){ if(levelN%2 == 0){ int low = 0; int high = temp.size()-1; while(low < high){ int temp_num = temp[low]; temp[low] = temp[high]; temp[high] = temp_num; low++; high--; } } levelNumber = level.size(); res.push_back(temp); } levelN++; } return res; } int main(int argc, const char *argv[]) { TreeNode n1(3); TreeNode n2(9); TreeNode n3(20); TreeNode n6(15); TreeNode n7(7); n1.left = &n2; n1.right = &n3; n3.left = &n6; n3.right = &n7; vector<vector<int> > res; res = zigzagLevelOrder(&n1); for (int i = 0; i < res.size(); i++) { for (int j = 0; j < res[i].size(); j++) { cout << res[i][j] << " "; } cout << endl; } return 0; }
true
1912da79497ea03c44287b18730e770d8026f9e4
C++
Gxsghsn/acm
/c8/11/p.h
UTF-8
3,218
3.296875
3
[]
no_license
#include <iostream> using namespace std; struct Node { int data; Node *Leftchild=NULL, *Rightchild=NULL; }; class Ttree { private: public: Node *root; Ttree(int *a,int n) { Node **p; p = new Node*[n]; root=p[0] = new Node; root->data = a[0]; for (int i = 1; i < n;i++) { if (a[i]!=0&&i%2==1) { p[(i-1)/2]->Leftchild = p[i] = new Node; p[i]->data = a[i]; } if (a[i] != 0 && i % 2 == 0) { p[(i - 2)/2]->Rightchild = p[i] = new Node; p[i]->data = a[i]; } } }; void ITra(Node *root) //ÖÐÐò±éÀúÏÔʾ { if (root!=NULL) { ITra(root->Leftchild); cout << root->data << " "; ITra(root->Rightchild); } }; //11 int flag=1; int pre=-1,next=-1; int pd(Node *root) { // if(root!=NULL){ // int a=root->data; // if(root->Leftchild!=NULL && root->Leftchild->data > root->data){ return 0;} // if(root->Rightchild!=NULL && root->Rightchild->data < root->data){return 0;} // flag=pd(root->Leftchild); // flag=pd(root->Rightchild); // } // int n[len]; // int ptr=0; // int pre=-1; // int next; if (root!=NULL) { pd(root->Leftchild); if(pre==-1){ pre=root->data; }else{ if(root->data < pre) return 0; pre=root->data; } if(root->data<pre) return 0; pd(root->Rightchild); } // for(int i=0;i<len-1;i++) if(n[i]>n[i+1]) return 0; return 1; }; //12 // int search(int x,Node *root){ // if(x>root->data) // } //18 void Insert(Node *root,int *b,int i) { int s = 1; cout<<"b"<<endl; while (s!=0) { if (b[i] < root->data&&root->Leftchild != NULL) root = root->Leftchild; if (b[i] < root->data&&root->Leftchild == NULL) { root->Leftchild = new Node; root->Leftchild->data = b[i]; s = 0; } if (b[i] >root->data&&root->Rightchild != NULL) root = root->Rightchild; if (b[i] >root->data&&root->Rightchild == NULL) { root->Rightchild = new Node; root->Rightchild->data = b[i]; s = 0; } } cout<<"c"<<endl; }; int ITra1(Node *root, int i, int *b) { if (root != NULL) { b[i] = root->data; i++; if (root == NULL) i--; i = ITra1(root->Leftchild, i, b); i = ITra1(root->Rightchild, i, b); } return i; }; Ttree *MTree(Node *root1, Node *root2, int n1, int n2) { Ttree *shu; int *b, i = 0; b = new int[n1 + n2]; i = ITra1(root1, i, b); i = ITra1(root2, i, b); cout << endl; int a[1]; a[0] = b[0]; shu = new Ttree(a, 1); for (int i = 1; i < n1 + n2; i++) { cout<<"a"<<endl; Insert(shu->root,b,i); } ITra(shu->root); return shu; }; //12 // int flag=1; // int pre=-1,next=-1; int pre1=-1; int pd1(Node *root,int num) { if (root!=NULL) { pd1(root->Leftchild,num); if(pre1==-1){ pre1=root->data; }else{ if(root->data >= num){cout<<pre1<<endl;cout<<root->data<<endl;} pre1=root->data; } if(root->data<pre1) return 0; pd1(root->Rightchild,num); } // for(int i=0;i<len-1;i++) if(n[i]>n[i+1]) return 0; return 1; }; };
true
f644fb9614b6f523b7d0076f48ad44f83d7a96ae
C++
TermanEmil/cursus42
/piscinecpp/rush00/src/GameController.cpp
UTF-8
1,960
2.890625
3
[]
no_license
#include "GameController.hpp" #include <fstream> #include "Enemy.hpp" GameController::GameController (void) { for (int i = 0; i < MAXNBOBJS; i++) gos[i] = NULL; score = 0; } void GameController::Instantiate (GameObject * go) { gos[_GetEmptySlot()] = go; } void GameController::DestroyGO (GameObject * go) { for (int i = 0; i < MAXNBOBJS; i++) if (go == gos[i]) gos[i] = NULL; if (go) delete go; } int GameController::_GetEmptySlot (void) const { for (int i = 0; i < MAXNBOBJS; i++) if (gos[i] == NULL) return i; return -1; } void GameController::UpdateAll (void) const { for (int i = 0; i < MAXNBOBJS; i++) if (gos[i]) gos[i]->Update(); } void GameController::ClearAll (void) const { for (int i = 0; i < MAXNBOBJS; i++) if (gos[i] && gos[i]->renderer) gos[i]->renderer->Clear(); } int GameController::Count (void) const { int n = 0; for (int i = 0; i < MAXNBOBJS; i++) if (gos[i]) n++; return n; } int GameController::CountEnemy(void) const { int n = 0; for (int i = 0; i < MAXNBOBJS; i++) if (gos[i] && gos[i]->GetName() == "Enemy") n++; return n; } void GameController::LoadLevel (int lvl) { int enemyType; int x; int y; if (lvl > MAX_LEVEL) { return; } std::ifstream inFile; std::stringstream stream; stream << "maps/level_" << lvl; inFile.open(stream.str().c_str()); if (!inFile) { endwin(); std::cout << "Couldnt find maps" << std::endl; exit(0); } stream.str(""); stream << inFile; while (inFile >> enemyType >> x >> y) { SpawnEnemy(enemyType, x, y); } } void GameController::SpawnEnemy (int enemyType, int x, int y) { x *= XCELSIZE; y *= YCELSIZE; x = COLS / 2 + x; switch (enemyType) { case 1: Instantiate(new Enemy(Vector2(x, y))); break; } } void GameController::PrintScore (void) const { std::stringstream s; s << "Score: " << score; attron(A_BOLD | COLOR_PAIR(7)); mvprintw(0, 0, s.str().c_str()); attroff(A_BOLD | COLOR_PAIR(7)); }
true
af23f6103fa3673724ada9884693c923d6e9f2df
C++
mattfischer/raytrace
/Math/Point.cpp
UTF-8
1,726
3.34375
3
[]
no_license
#include "Math/Point.hpp" #include "Math/Vector.hpp" #include "Math/Transformation.hpp" namespace Math { Point::Point() { mX = mY = mZ = 0; } Point::Point(float x, float y, float z) { mX = x; mY = y; mZ = z; } Point::Point(const Vector &c) { mX = c.x(); mY = c.y(); mZ = c.z(); } float Point::x() const { return mX; } float Point::y() const { return mY; } float Point::z() const { return mZ; } Point Point::operator+(const Vector &b) const { return Point(x() + b.x(), y() + b.y(), z() + b.z()); } Point Point::operator-(const Vector &b) const { return Point(x() - b.x(), y() - b.y(), z() - b.z()); } Vector Point::operator-(const Point &b) const { return Vector(x() - b.x(), y() - b.y(), z() - b.z()); } Point operator*(const BaseTransformation &transformation, const Point &point) { return Point(transformation.matrix() * point); } Point operator*(const Matrix &matrix, const Point &point) { if (matrix.identity()) return point; float x = matrix(0, 0) * point.x() + matrix(1, 0) * point.y() + matrix(2, 0) * point.z() + matrix(3, 0); float y = matrix(0, 1) * point.x() + matrix(1, 1) * point.y() + matrix(2, 1) * point.z() + matrix(3, 1); float z = matrix(0, 2) * point.x() + matrix(1, 2) * point.y() + matrix(2, 2) * point.z() + matrix(3, 2); return Point(x, y, z); } void Point::writeProxy(PointProxy &proxy) const { proxy.coords[0] = x(); proxy.coords[1] = y(); proxy.coords[2] = z(); } }
true
39fa8853de7086f4ccb369d18d6f51ef7ace293a
C++
DEEZZU/College-Backup
/Algo and Ds/BFS.CPP
UTF-8
4,801
3.4375
3
[]
no_license
//IMPLEMENTING BFS #include<iostream> using namespace std; //THE NODE FOR QUEUE CLASS...................................................... template<class T> class qnode { public: T info; qnode *next; qnode(T x, qnode *n=NULL) { info=x; next=n; } }; //THE QUEUE CLASS......................................................... template<class T> class queue { qnode<T> *front,*rear; public: queue() { front=rear=NULL; } void enqueue(T); T dequeue(); int isempty(); }; template<class T> void queue<T>::enqueue(T x) { qnode<T> *temp=new qnode<T>(x); if(isempty()) { front=rear=temp; } else { rear->next=temp; rear=temp; } } template<class T> int queue<T>::isempty() { if(front==NULL) return 1; else return 0; } template<class T> T queue<T>::dequeue() { qnode<T> *temp; T x; x=front->info; if(front==rear) { delete front; front=rear=NULL; } else { temp=front; front=front->next; delete temp; } return x; } //THE VERTEX NODE........................................................................... class node { public: int key,d; node *next, *p; char color; node() { key=0; d=999; p=0; next=0; color='W'; } }; //THE LIST OF SUCH NODES..................................................................... class list { public: node *head; list() { head=0; } void addnode(int); }; void list ::addnode(int x) { node *temp=new node(); temp->key=x; node *temp1=head; while(temp1->next!=0) { temp1=temp1->next; } temp1->next=temp; temp->p=head; } //THE GRAPH CLASS............................................................................ class graph { int v; list *a; public: graph(int x) { v=x; a=new list[v]; for (int i = 0; i < v; ++i) { a[i].head = new node(); a[i].head->key=i+1; } } void insert(); void display(); void bfs(int s); void print_path(int s, int v); void view_shortpath(); }; void graph::insert() { int z; char ch='y'; for(int i=0;i<v;i++) { ch='y'; while(ch=='y') { cout<<"\n Enter the edge of "<<a[i].head->key<<"="; cin>>z; if(z>0&&z<=v) a[i].addnode(z); else cout<<"Vertex not in graph\n"; cout<<"more edges : "; cin>>ch; } } } void graph::display() { node *temp; for(int i=0;i<v;i++) { cout<<"\n\n Vertex "<<a[i].head->key<<" : "; temp=a[i].head; while(temp->next!=0) { cout<<temp->key<<"->"; temp=temp->next; } cout<<temp->key; } } void graph::bfs(int s) { int u,v1; for(u=0;u<v;u++) { a[u].head->color='W'; a[u].head->d=999; a[u].head->p=0; if(u==s-1) { a[u].head->color='G'; a[u].head->d=0; a[u].head->p=0; } } queue<int> Q; Q.enqueue(s); node *temp; while(!Q.isempty()) { u=Q.dequeue(); u=u-1; temp=a[u].head; while(temp->next!=0) { temp=temp->next; v1=temp->key; cout<<v1-1<<" "; v1--; if(a[v1].head->color=='W') { a[v1].head->color='G'; a[v1].head->d=a[u].head->d+1; a[v1].head->p=a[u].head; Q.enqueue(v1+1); } } a[u].head->color='B'; } } void graph::print_path(int s, int v) { if(v==s) { s=s-1; cout<<a[s].head->key<<" "; } else if(a[v-1].head->p==0) { cout<<"\n No path from "<<v<<" to "<<s <<" exists"; } else { print_path(s,a[v-1].head->p->key); cout<<v<<" "; } } void graph::view_shortpath() { int s; cout<<"\n Enter the source vertex:"; cin>>s; bfs(s); cout<<"\n Shortest path of each vertex from "<<s<<" is....."; for(int i=1; i<=v; i++) { cout<<"\n For vertex["<<i<<"]:"; print_path(s,i); cout<<endl; } } void main() { int op,n; char ch; cout<<"\n Enter the no. of vertices :: "; cin>>n; graph G(n); do { cout<<"\n MENU"; cout<<"\n INPUT EDGES :"; cout<<"\n VIEW ADJACENCY "; cout<<"\n VIEW SHORTEST PATH OF VERTICES FROM A SOURCE VERTEX:"; cout<<"\n Enter your choice"; cin>>op; switch(op) { case 1:cout<<"\n INSERTING EDGES..............."; G.insert(); break; case 2:cout<<"\n VIEW ADJACENCY ................"; G.display(); break; case 3:cout<<"\n VIEW SHORTEST PATH OF VERTICES FROM A SOURCE VERTEX:"; G.view_shortpath(); break; default:cout<<"\n Wrong Choice "; } cout<<"\n Do you want to continue:"; cin>>ch; } while(ch=='y' || ch=='Y'); }
true
4828a94783ab88c1edcabebcd2bbc71e37cfb9f0
C++
DevashishPrasad/BE-IT-assignments
/SE/2nd sem/CG/newshape.cpp
UTF-8
4,277
2.984375
3
[]
no_license
#include <GL/freeglut.h> #include <GL/gl.h> #include <iostream> #include <cstdlib> using namespace std; typedef struct Point { int x; int y; }Point; int rx1, ry1, rx2, ry2, rx3, ry3, rx4, ry4; void init() { // making background color black as first // 3 arguments all are 0.0 glClearColor(1.0, 1.0, 1.0, 1.0); // making picture color white (in RGB mode), glColor3f(0.5, 0.5, 0.5); // breadth of picture boundary is 1 pixel glPointSize(2.5); // coordinate system glMatrixMode(GL_PROJECTION); // setting window dimension in X- and Y- direction gluOrtho2D(0.0, 1024.0, 0.0, 750.0); } // Custom Function for drawing a line void drawLine(int x1, int y1, int x2, int y2) { glLineWidth(2.5); glColor3f(0.0, 0.0, 1.0); glBegin(GL_LINES); glVertex3f(x1, y1, 0); glVertex3f(x2, y2, 0); glEnd(); } /*void drawLine(int x1, int y1, int x2, int y2) { //DDA Function for line generation // calculate dx & dy int dx = abs(x1 - x2); int dy = abs(y1 - y2); // calculate steps required for generating pixels int steps = dx > dy ? dx : dy; // calculate increment in x & y for each steps float Xinc = dx / (float) steps; float Yinc = dy / (float) steps; // Put pixel for each step float X = x1; float Y = y1; glBegin(GL_POINTS); for (int i = 0; i <= steps; i++) { glVertex2i(X,Y); X += Xinc; // increment in x at each step Y += Yinc; // increment in y at each step //delay(100); } glEnd(); }*/ void drawShape() { // Getting max window sizes Point Max, SMax; SMax.x = glutGet(GLUT_WINDOW_WIDTH); SMax.y = glutGet(GLUT_WINDOW_HEIGHT); Max.x = rx3; Max.y = ry3; // Getting center of axes Point AxisCenter; AxisCenter.x = (Max.x - rx1)/2 + rx1; AxisCenter.y = (Max.y - ry1)/2 + ry1; // Setting the origin point Point Origin; Origin.x = rx1; Origin.y = ry1; // drawing the lines // Rectangle Shape drawLine(Origin.x, Origin.y, Max.x, Origin.y); drawLine(Origin.x, Origin.y, Origin.x, Max.y); drawLine(Origin.x, Max.y, Max.x, Max.y); drawLine(Max.x, Origin.y, Max.x, Max.y); // Quadrant Lines drawLine(0, SMax.y/2, SMax.x, SMax.y/2); drawLine(SMax.x/2, 0, SMax.x/2, SMax.y); // Outer Shape drawLine(Origin.x, AxisCenter.y, AxisCenter.x, Origin.y); drawLine(Origin.x, AxisCenter.y, AxisCenter.x, Max.y); drawLine(AxisCenter.x, Max.y, Max.x, AxisCenter.y); drawLine(Max.x, AxisCenter.y, AxisCenter.x, Origin.y); //// Inner Shape old method //drawLine(Max.x/4, Max.y/4, Max.x/4 , Max.y - Max.y/4); //drawLine(Max.x/4, Max.y/4, Max.x - Max.x/4 , Max.y/4); //drawLine(Max.x - Max.x/4, Max.y/4, Max.x - Max.x/4 , Max.y - Max.y/4); //drawLine(Max.x/4 , Max.y - Max.y/4, Max.x - Max.x/4 , Max.y - Max.y/4); //Easy way Inner shape using mid points drawLine((AxisCenter.x - Origin.x)/2 + Origin.x, (AxisCenter.y - Origin.y)/2 + Origin.y, (AxisCenter.x - Origin.x)/2 + Origin.x, (AxisCenter.y - Origin.y)/2 + AxisCenter.y); drawLine((AxisCenter.x - Origin.x)/2 + Origin.x, (AxisCenter.y - Origin.y)/2 + AxisCenter.y, (AxisCenter.x - Origin.x)/2 + AxisCenter.x, (AxisCenter.y - Origin.y)/2 + AxisCenter.y); drawLine((AxisCenter.x - Origin.x)/2 + AxisCenter.x, (AxisCenter.y - Origin.y)/2 + AxisCenter.y, (AxisCenter.x - Origin.x)/2 + AxisCenter.x, (AxisCenter.y - Origin.y)/2 + Origin.y); drawLine((AxisCenter.x - Origin.x)/2 + AxisCenter.x, (AxisCenter.y - Origin.y)/2 + Origin.y, (AxisCenter.x - Origin.x)/2 + Origin.x, (AxisCenter.y - Origin.y)/2 + Origin.y); } void start() { init(); drawShape(); glFlush(); } int main(int argc, char **argv) { cout<<"\n\n Please enter the coordinates for a rectangle or square - "; cout<<"\n Point 1 (x,y) - "; cin>>rx1>>ry1; cout<<"\n Point 2 (x,y) - "; cin>>rx2>>ry2; cout<<"\n Point 3 (x,y) - "; cin>>rx3>>ry3; cout<<"\n Point 4 (x,y) - "; cin>>rx4>>ry4; // OpenGL Glut Init glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Set the window size glutInitWindowSize(1024, 750); glutInitWindowPosition(0, 0); int winid = glutCreateWindow("OpenGL - Creating a line"); // Start with the program glutDisplayFunc(start); glutMainLoop(); return 0; }
true
e39a39fc5b0c9f2e191f57931db67cae822772bd
C++
ras2244/Portifolio
/C++/CicleRotation/CicleRotation/Rotate.h
UTF-8
271
2.53125
3
[]
no_license
#pragma once #include <string> #include <array> #include <iostream> #include <vector> namespace cicle { class Cicle { unsigned int index; Cicle* a; unsigned int k; Cicle() { a = new int*[index]; } Cicle& operator=(const Cicle& rhs) { } }; }
true
9c5965d9f45ebf1235c84acb4d4e5dbe7a2ce464
C++
azalac/VulkanGame
/include/VulkanShader.hpp
UTF-8
2,342
3.109375
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <stdio.h> #include <vector> #include "VulkanDevice.hpp" // Represents a single shader module // Can load from multiple sources class VulkanShader { private: vk::ShaderModule shader; std::string name; vk::ShaderStageFlagBits type; std::vector<uint32_t> data; public: /** * Loads a shader from compiled SPIR-V bytecode * @param device The device * @param filename The file * @param type The shader stage * @param shader_name The shader entry point */ VulkanShader(VulkanDevice & device, const std::string & filename, vk::ShaderStageFlagBits type = vk::ShaderStageFlagBits::eVertex, const std::string shader_name = "main"); /** * Loads a shader from a SPIR-v bytecode vector * @param device The device * @param data The bytecode vector * @param type The shader stage * @param shader_name The shader entry point */ VulkanShader(VulkanDevice & device, std::vector<uint32_t> data, vk::ShaderStageFlagBits type = vk::ShaderStageFlagBits::eVertex, const std::string shader_name = "main"); /** * Loads a shader from a SPIR-v bytecode array * @param device The device * @param data The bytecode buffer * @param count The buffer size in bytes * @param type The shader stage * @param shader_name The shader entry point */ VulkanShader(VulkanDevice & device, const uint32_t * data, size_t count, vk::ShaderStageFlagBits type = vk::ShaderStageFlagBits::eVertex, const std::string shader_name = "main"); operator vk::PipelineShaderStageCreateInfo() { return vk::PipelineShaderStageCreateInfo(vk::PipelineShaderStageCreateFlags(), type, shader, name.c_str()); } /** * Dumps this shader's bytecode to stdout * @param words_per_row The number of 4-byte words per row */ void dumpBytecode(int words_per_row = 8); private: static std::vector<uint32_t> LoadShader(const std::string & filename); void init(VulkanDevice & device, const uint32_t * data, size_t count) { vk::ShaderModuleCreateInfo createInfo; createInfo.codeSize = count; createInfo.pCode = data; shader = device->createShaderModule(createInfo); } };
true
6914fc12afb337e6fb757a1be5716a567a5cc8a3
C++
rk-92/google-code-sample
/cpp/src/main.cpp
UTF-8
1,498
3.0625
3
[]
no_license
#include <algorithm> #include <fstream> #include <iostream> #include <sstream> #include <unordered_map> #include <utility> #include <vector> #include "commandparser.h" #include "helper.h" #include "videolibrary.h" #include "videoplayer.h" int main() { std::cout << "Hello and welcome to YouTube, what would you like to do? " "Enter HELP for list of available commands or EXIT to terminate." << std::endl; std::string userInput; std::string command; std::vector<std::string> commandList; VideoPlayer vp; CommandParser cp = CommandParser(std::move(vp)); for (;;) { std::cout << "YT> "; if (!std::getline(std::cin, userInput)) { break; } if (userInput.empty()) { std::cout << "Please enter a valid command, type HELP for a list of " "available commands." << std::endl; } else { std::stringstream test(userInput); while (std::getline(test, command, ' ')) { command = trim(command); commandList.push_back(command); } std::transform(commandList[0].begin(), commandList[0].end(), commandList[0].begin(), [](char c) { return static_cast<char>(std::toupper(c)); }); if (commandList[0] == "EXIT") { break; } cp.executeCommand(commandList); commandList.clear(); } } std::cout << "YouTube has now terminated it's execution. Thank you and goodbye!" << std::endl; }
true
2247aa5b1b7aae223872c3728d237cce38729aa9
C++
fjorge/pg-sdk-marmalade
/src/model/phune/phune_user.cpp
UTF-8
2,129
2.8125
3
[ "MIT" ]
permissive
#include "phune_user.h" int32 PhuneUser::Deserialize(std::string jsonSrc) { if (jsonSrc.length() == 0) return 0; Reader reader; Value value; reader.parse(jsonSrc, value, false); return DeserializeFromValue(value); } int32 PhuneUser::DeserializeFromValue(Json::Value src){ if (!src["id"].empty()) id = src["id"].asUInt64(); if (!src["registerDate"].empty()) registerDate = src["registerDate"].asInt64(); if (!src["avatar"].empty()) avatar = src["avatar"].asString(); if (!src["type"].empty()) { std::string typeStr = src["type"].asString(); if (typeStr.compare("REGISTERED") == 0) type = REGISTERED; else type = UNREGISTERED; } if (!src["credits"].empty()) credits = src["credits"].asUInt64(); if (!src["gender"].empty()) { std::string genderStr = src["gender"].asString(); if (genderStr.compare("MALE") == 0) gender = MALE; else if (genderStr.compare("FEMALE") == 0) gender = FEMALE; else gender = G_UNKNOWN; } if (!src["name"].empty()) name = src["name"].asString().c_str(); if (!src["nickname"].empty()) nickname = src["nickname"].asString(); if (!src["xmppPassword"].empty()) xmppPassword = src["xmppPassword"].asString(); if (!src["xmppJID"].empty()) xmppJID = src["xmppJID"].asString(); if (!src["progress"].empty()) progress = src["progress"].asFloat(); return 0; } std::string PhuneUser::Serialize(){ FastWriter writer; return writer.write(SerializeToValue()); } Value PhuneUser::SerializeToValue(){ Value root; root["id"] = id; root["registerDate"] = registerDate; root["avatar"] = avatar; switch (type){ case REGISTERED: root["type"] = "REGISTERED"; break; default: case UNREGISTERED: root["type"] = "UNREGISTERED"; break; } root["credits"] = credits; switch (gender) { case MALE: root["gender"] = "MALE"; break; case FEMALE: root["gender"] = "FEMALE"; break; case G_UNKNOWN: default: root["gender"] = "UNKNOWN"; break; } root["name"] = name; root["nickname"] = nickname; root["xmppPassword"] = xmppPassword; root["xmppJID"] = xmppJID; root["progress"] = progress; return root; }
true
fe416a6d1f9355c8c2e8335fb24f49ecd58cc2e7
C++
Tmejs/mario
/enemy.h
UTF-8
1,580
2.765625
3
[]
no_license
#ifndef ENEMY_H #define ENEMY_H #include "Collision.h" #include "Direction.h" // Movement constants (the higher the faster) #define ENEMY_X_AXIS_VELOCITY 1 #define ENEMY_Y_AXIS_VELOCITY 30 #define RELATIVE_ENEMY_VELOCITY_Y_AXIS _velY / ENEMY_GRAVITY struct SDL_Rect; class Enemy { public: // Counts for each animation static const int WALK_ANIMATION_FRAMES = 2; static const int DEATH_ANIMATION_FRAMES = 1; // The lower the faster static const int WALK_ANIMATION_SPEED = 6; // Movement constants (the higher the faster) static const int X_AXIS_VELOCITY = ENEMY_X_AXIS_VELOCITY; static const int Y_AXIS_VELOCITY = ENEMY_Y_AXIS_VELOCITY; // The higher the more slows Mario y axis velocity static const int ENEMY_GRAVITY = 5; // SDL_Rect defining where specific frames are in the sprite sheet SDL_Rect frames[WALK_ANIMATION_FRAMES + DEATH_ANIMATION_FRAMES]; Enemy(int x, int y); ~Enemy(); // Utility functions void initFrames(); void render(); void update(); Collision collisionCheck(); // Returns SDL_Rect of current frame SDL_Rect currentFrame(); // Handles walking movement and animation void walk(); void animateWalk(); // Handles jumping movement and animation void jump(); void animateJump(); void kill(); // Getters int posX(); int posY(); SDL_Rect getRect(); bool isAlive(); // Setters void posX(int); void posY(int); private: Collision _collisionInfo; Direction _lastDirection; int _currentFrame; int _posX; int _posY; int _velX; int _velY; unsigned int _animationCount; bool _isAlive; }; #endif // !ENEMY_H
true
ab2709fa4d100c03ac5151c1aad2b4c9c6c2dd6b
C++
JFulweber/hw4
/main.cpp
UTF-8
1,503
2.515625
3
[]
no_license
#include <iostream> #include "Image.h" #include "Scene.h" #include "Sphere.h" #include "Rectangle.h" #include "Constant.h" using namespace std; using namespace Raytracer148; using namespace Eigen; int problemNumber; int main(int argc, char** argv) { problemNumber = atoi(argv[1]); cout << "set problem number to" << argv[1] << endl; Image im(400, 400); Scene scene; Vector3d center; //center[0] = 0; //center[1] = 0; //center[2] = 4; //scene.addShape(new Sphere(center, 2)); //center[0] = -.5; //center[1] = 1; //center[2] = 2.5; //scene.addShape(new Sphere(center, .5)); center[0] = -.5; center[1] = 0; center[2] = 2.5; scene.addShape(new Sphere(center, .5, Material(Vector3d(0, 1, 0), 1, true))); center[0] = .5; center[1] = 0; center[2] = 2.5; scene.addShape(new Sphere(center, .5, Material(Vector3d(1, 0, 0), 1, true))); scene.addShape(new Rectangle(Vector3d(-.5, 0, 2.5), Vector3d(.5, 5, 2.5), Material(Vector3d(1, 1, .2), 2))); Vector3d offset; offset[0] = -5; offset[1] = -1; offset[2] = 0; Vector3d minBound; minBound[0] = minBound[1] = minBound[2] = 0; Vector3d maxBound; maxBound[0] = 10; maxBound[1] = .5; maxBound[2] = 10; minBound += offset; maxBound += offset; Rectangle *r = new Rectangle(minBound, maxBound, Material(Vector3d(.8, 0, .5), 3)); scene.addShape(r); scene.render(im); im.writePNG("test.png"); return 0; }
true
0a794b38be419523e9c2aadc323decb4e394696f
C++
ehacinom/Cpp
/Years.cpp
UTF-8
574
2.953125
3
[]
no_license
#include <iostream> int main() { int year = 2010; std::cout << "The year " << ++year << " passes.\n"; std::cout << "The year " << ++year << " passes.\n"; std::cout << "The year " << ++year << " passes.\n"; std::cout << "it's now " << year << "."; std::cout << " Have the Seattle Mariners won the World Series yet?\n"; std::cout << "The year " << year++ << " passes.\n"; std::cout << "The year " << year++ << " passes.\n"; std::cout << "The year " << year++ << " passes.\n"; std::cout << year << "\n\n"; return 0; }
true
b8ffb91cb1efdd8b694c33022a538c3571a78142
C++
Brother-Five/four-axis-aircraft
/MySrc/motor.cpp
GB18030
7,625
2.53125
3
[]
no_license
#include "bsp.h" #include "filter.h" #include "cpid.h" #include "mpu6050.h" /** * [Motor_Aguest description] * @param Ax [ңصһֵͨ] * @param Ay [ңصһֵͨ] * @param Az [CarFramePID.AdjustPID()CarFramePID.Out] * @param _mAngle [ѡǰĽǶ] */ void Motor_Aguest(u16 Ax,u16 Ay,float Az,float _mAngle) { // static u8 count; int MotorData[4]={0}; float xpower,ypower,zpower; float AxChange,AyChange; AxChange = ((float)Ax - 1024.0f)*No1; AyChange = ((float)Ay - 1024.0f)*No1; xpower = ((float)AyChange*arm_sin_f32(_mAngle*0.0174532f)+(float)AxChange*arm_cos_f32(_mAngle*0.0174532f)); ypower = ((float)AyChange*arm_cos_f32(_mAngle*0.0174532f)-(float)AxChange*arm_sin_f32(_mAngle*0.0174532f)); zpower = Az; // zpower = (int)(((float)Az - 1024.0f)*No1);//(Az - 1024)*No1; X_Axic(MotorData,xpower); Y_Axic(MotorData,ypower); Z_Axic(MotorData,zpower); Motor_DataScale(MotorData,5000); // u1_printf("%d\t%d\t%d\t%d\r\n\r\n",MotorData[Motor1],MotorData[Motor2],MotorData[Motor3],MotorData[Motor4]); Motor_CarFrame(MotorData[Motor1],MotorData[Motor2],MotorData[Motor3],MotorData[Motor4]);//Can4͵Ӻֵ } void X_Axic(int *MotorData,int power) { Motor(MotorData,Motor1,-power); Motor(MotorData,Motor2,-power); Motor(MotorData,Motor3,power); Motor(MotorData,Motor4,power); } void Y_Axic(int *MotorData,int power) { Motor(MotorData,Motor1,-power); Motor(MotorData,Motor2,power); Motor(MotorData,Motor3,power); Motor(MotorData,Motor4,-power); } void Z_Axic(int *MotorData,int power) { Motor(MotorData,Motor1,-power); Motor(MotorData,Motor2,-power); Motor(MotorData,Motor3,-power); Motor(MotorData,Motor4,-power); } void Motor_DataScale(int *MotorData,int max) { int TempBuf[4]={0}; u8 k; float scale; for ( k = 0; k < 4; k++) { TempBuf[k] = myabs(MotorData[k]); } // u1_printf("%d\t%d\t%d\t%d\r\n",TempBuf[0],TempBuf[1],TempBuf[2],TempBuf[3]); bubble_sort(TempBuf,4); // u1_printf("%d\t%d\t%d\t%d\r\n",TempBuf[0],TempBuf[1],TempBuf[2],TempBuf[3]); if(TempBuf[3] >= max) scale = ((float)max)/((float)TempBuf[3]); else scale = 1.0f; // u1_printf("%d\t%d\t%d\t%d\r\n",(int)(((float)TempBuf[0])*scale),(int)(((float)TempBuf[1])*scale),(int)(((float)TempBuf[2])*scale),(int)(((float)TempBuf[3])*scale)); MotorData[Motor1] = (int)(((float)MotorData[Motor1]) * scale); MotorData[Motor2] = (int)(((float)MotorData[Motor2]) * scale); MotorData[Motor3] = (int)(((float)MotorData[Motor3]) * scale); MotorData[Motor4] = (int)(((float)MotorData[Motor4]) * scale); } void Motor(int *MotorData,u8 motorx,int power) { MotorData[motorx] += power; } void Motor_CarFrame(int16_t current_201,int16_t current_202,int16_t current_203,int16_t current_204) { CanTxMsg msg_send = { 0x110, 0x110, CAN_Id_Standard, CAN_RTR_Data, 0x08, {0, 0, 0, 0, 0, 0, 0, 0}}; // msg_send.StdId = 0x110 + 0; msg_send.Data[0] = (unsigned char)(current_201 >> 8); msg_send.Data[1] = (unsigned char)current_201; msg_send.Data[2] = (unsigned char)(current_202 >> 8); msg_send.Data[3] = (unsigned char)current_202; msg_send.Data[4] = (unsigned char)(current_203 >> 8); msg_send.Data[5] = (unsigned char)current_203; msg_send.Data[6] = (unsigned char)(current_204 >> 8); msg_send.Data[7] = (unsigned char)current_204; while(CAN_Transmit(CAN1,&msg_send) == CAN_TxStatus_NoMailBox); // CAN_send(CAN1, &msg_send); } void Motor_Power(u16 id,u16 current,u16 volate) { CanTxMsg msg_send = { 0, 0, CAN_Id_Standard, CAN_RTR_Data, 0x08, {0, 0, 0, 0, 0, 0, 0, 0}}; msg_send.StdId = 0x131; msg_send.Data[0] = 0x55; msg_send.Data[1] = 0xaa; msg_send.Data[2] = (u8)((id>>8)&0xff); msg_send.Data[3] = (u8)(id&0xff); msg_send.Data[4] = (u8)((volate>>8)&0xff); msg_send.Data[5] = (u8)((current>>8)&0xff); msg_send.Data[6] = (u8)(current&0xff); msg_send.Data[7] = (u8)(volate); CAN_Transmit(CAN1,&msg_send); // while(CAN_Transmit(CAN1,&msg_send) == CAN_TxStatus_NoMailBox); } void Motor_Other(int16_t current_201,int16_t current_202,int16_t current_203,int16_t current_204) { CanTxMsg msg_send = { 0x02, 0x02, CAN_Id_Standard, CAN_RTR_Data, 0x08, {0, 0, 0, 0, 0, 0, 0, 0}}; msg_send.Data[0] = (unsigned char)(current_201 >> 8); msg_send.Data[1] = (unsigned char)current_201; msg_send.Data[2] = (unsigned char)(current_202 >> 8); msg_send.Data[3] = (unsigned char)current_202; msg_send.Data[4] = (unsigned char)(current_203 >> 8); msg_send.Data[5] = (unsigned char)current_203; msg_send.Data[6] = (unsigned char)(current_204 >> 8); msg_send.Data[7] = (unsigned char)current_204; while(CAN_Transmit(CAN1,&msg_send) == CAN_TxStatus_NoMailBox); } void Motor_GetMassage(u16 index) { CanTxMsg msg_send = { 0x130, 0x130, CAN_Id_Standard, CAN_RTR_Data, 0x08, {0, 0, 0, 0, 0, 0, 0, 0}}; msg_send.Data[0] = 0x55; msg_send.Data[1] = 0xaa; msg_send.Data[2] = (index>>8)&0xff; msg_send.Data[3] = index&0xff; while(CAN_Transmit(CAN1,&msg_send) == CAN_TxStatus_NoMailBox); } void MOTOR_SetPWM(short pwm,short id) { CanTxMsg msg_send = { 0, 0, CAN_Id_Standard, CAN_RTR_Data, 0x08, {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55}}; if(pwm < -5000) pwm = -5000; if(pwm > 5000) pwm = 5000; // msg_send.StdId = id<<4 | 4; // msg_send.Data[0] = (unsigned char)((5000>>8)&0xff); // msg_send.Data[1] = (unsigned char)(5000&0xff); // msg_send.Data[2] = (unsigned char)((pwm/10>>8)&0xff); // msg_send.Data[3] = (unsigned char)(pwm/10&0xff); // CAN_send(CAN1,&msg_send); msg_send.StdId = id<<4 | 2; msg_send.Data[0] = (pwm>>8)&0xff; msg_send.Data[1] = (unsigned char)(pwm&0xff); while(CAN_Transmit(CAN1,&msg_send) == CAN_TxStatus_NoMailBox); // CAN_send(CAN1,&msg_send); } void Motor_PwrAdd(float throttle,float controlout[],float motorout[],float addout) { motorout[0]=throttle- controlout[0]+0*controlout[1]-controlout[2]; motorout[1]=throttle+0*controlout[0]+ controlout[1]+controlout[2]; motorout[2]=throttle+ controlout[0]-0*controlout[1]-controlout[2]; motorout[3]=throttle-0*controlout[0]- controlout[1]+controlout[2]; motorout[4]=0.0f; motorout[5]=0.0f; // u1_printf("%7.3f\t%7.3f\t%7.3f\t%7.3f\t\r\n",motorout[3],motorout[2],motorout[1],motorout[0]); } void Motor_PwmValSet(float motorout[]) { unsigned char i=0; float thr[6]={0.0f}; for(i=0;i<6;i++) { thr[i]=motorout[i]*55; } PWM1=1300+thr[0]; PWM2=1300+thr[1]; PWM3=1300+thr[2];//30 PWM4=1300+thr[3]; if(PWM1>_FLY_MAX_OUT) PWM1=_FLY_MAX_OUT+30; if(PWM1<1200.0f) PWM1=1200.0f; if(PWM2>_FLY_MAX_OUT) PWM2=_FLY_MAX_OUT; if(PWM2<1200.0f) PWM2=1200.0f; if(PWM3>_FLY_MAX_OUT) PWM3=_FLY_MAX_OUT; if(PWM3<1200.0f) PWM3=1200.0f; if(PWM4>_FLY_MAX_OUT) PWM4=_FLY_MAX_OUT; if(PWM4<1200.0f) PWM4=1200.0f; // u1_printf("PWM1:%d\tPWM2:%d\tPWM3:%d\tPWM4:%d\t\r\n",PWM1,PWM2,PWM3,PWM4); } float ControlOut[3]={0},MotorOut[6]={0.5,0.5,0.5,0.5};//{0.5,0.5,0.5,0.5} extern float RC_control; extern float addout; extern int pwm_flag; void controlnormalmode_update(float dt) { if(pwm_flag) { Pidcontrol_Altitude_VEL(&Target,&Eulla,&velocity,ControlOut,dt); extern float RC_control; Motor_PwrAdd_Control(RC_control,addout); Motor_PwmValSet(MotorOut); } } void Motor_PwrAdd_Control(float DR16_Control,float addout) { Motor_PwrAdd(DR16_Control,ControlOut,MotorOut,addout); }
true
78992b7c9495afcbc97aaa0d976115ed91e9e15f
C++
burekichevapi/CPP_Library
/Tests/ArrayLinkedList_Tests.cpp
UTF-8
3,874
3.359375
3
[]
no_license
// // Created by amer on 1/3/19. // #include <gtest/gtest.h> #include <gmock/gmock.h> #include "ILinkedList.h" #include "../src/LinkedLists/ArrayLinkedList.cpp" class ArrayLinkedList_Tests : public testing::Test { public: ILinkedList<long long int> *arrayLinkedList = nullptr; virtual void SetUp() { arrayLinkedList = new ArrayLinkedList<long long int>(); arrayLinkedList->AddFirst(new LinkedNode<long long int>(1)); } virtual void TearDown() { arrayLinkedList = nullptr; delete arrayLinkedList; } }; TEST_F(ArrayLinkedList_Tests, ClearAll_Assert_Linked_List_Size_Is_0) { arrayLinkedList->Clear(); ASSERT_THAT(arrayLinkedList->GetSize(), 0); } TEST_F(ArrayLinkedList_Tests, GetSize_Assert_Linked_List_Has_One_Value) { ASSERT_THAT(arrayLinkedList->GetSize(), 1); } TEST_F(ArrayLinkedList_Tests, AddFirst_Assert_Head_Is_2) { arrayLinkedList->AddFirst(2); ASSERT_THAT(arrayLinkedList->GetHeadValue(), 2); } TEST_F(ArrayLinkedList_Tests, AddLast_Assert_Tail_Is_3) { arrayLinkedList->AddFirst(2); arrayLinkedList->AddLast(3); ASSERT_THAT(arrayLinkedList->GetTailValue(), 3); } TEST_F(ArrayLinkedList_Tests, RemoveFirst_Assert_Head_Is_1) { arrayLinkedList->AddFirst(2); arrayLinkedList->RemoveFirst(); ASSERT_THAT(arrayLinkedList->GetHeadValue(), 1); } TEST_F(ArrayLinkedList_Tests, RemoveFirst_Remove_From_Empty_List_Assert_Throws_Out_Of_Range) { arrayLinkedList->RemoveLast(); ASSERT_THROW(arrayLinkedList->RemoveFirst(), std::out_of_range); } TEST_F(ArrayLinkedList_Tests, RemoveLast_Assert_Tail_Is_2) { arrayLinkedList->AddFirst(2); arrayLinkedList->RemoveLast(); ASSERT_THAT(arrayLinkedList->GetTailValue(), 2); } TEST_F(ArrayLinkedList_Tests, RemoveLast_Remove_From_Empty_List_Assert_Is_Empty) { arrayLinkedList->RemoveFirst(); arrayLinkedList->RemoveLast(); ASSERT_THAT(arrayLinkedList->GetSize(), 0); } TEST_F(ArrayLinkedList_Tests, Contains_Assert_List_Contains_One) { ASSERT_THAT(arrayLinkedList->Contains(1), true); } TEST_F(ArrayLinkedList_Tests, Contains_Assert_List_Does_Not_Contain_2) { ASSERT_THAT(arrayLinkedList->Contains(2), false); } TEST_F(ArrayLinkedList_Tests, Contains_When_Empty_Assert_List_Does_Not_Contain_1) { arrayLinkedList->Clear(); ASSERT_THAT(arrayLinkedList->Contains(1), false); } TEST_F(ArrayLinkedList_Tests, Remove_By_Value_First_Value_Assert_List_Does_Not_Contain_1) { arrayLinkedList->AddFirst(2); arrayLinkedList->AddFirst(3); arrayLinkedList->RemoveByValue(1); ASSERT_THAT(arrayLinkedList->Contains(1), false); } TEST_F(ArrayLinkedList_Tests, Remove_By_Value_Middel_Value_Assert_List_Does_Not_Contain_2) { arrayLinkedList->AddFirst(2); arrayLinkedList->AddFirst(3); arrayLinkedList->RemoveByValue(2); ASSERT_THAT(arrayLinkedList->Contains(2), false); } TEST_F(ArrayLinkedList_Tests, RemoveByValue_Last_Value_Assert_List_Does_Not_Contain_3) { arrayLinkedList->AddFirst(2); arrayLinkedList->AddFirst(3); arrayLinkedList->RemoveByValue(3); ASSERT_THAT(arrayLinkedList->Contains(3), false); } TEST_F(ArrayLinkedList_Tests, Remove_By_Value_When_List_Does_Not_Contain_Value_Assert_List_Is_Same_Size) { arrayLinkedList->AddFirst(2); arrayLinkedList->AddFirst(3); arrayLinkedList->RemoveByValue(4); ASSERT_THAT(arrayLinkedList->GetSize(), 3); } TEST_F(ArrayLinkedList_Tests, Get_Head_Value_When_List_Empty_Assert_Throws_OutOfRange) { arrayLinkedList->Clear(); ASSERT_THROW(arrayLinkedList->GetHeadValue(), std::out_of_range); } TEST_F(ArrayLinkedList_Tests, GetTailValue_When_List_Empty_Assert_Throws_OutOfRange) { arrayLinkedList->Clear(); ASSERT_THROW(arrayLinkedList->GetTailValue(), std::out_of_range); }
true
eebee85382f6ebf19811f9f06b47fe2077b44c9f
C++
NiNjA-CodE/itsumo
/itsumo/src/trafficAgents/opportune/stateRecord.cpp
UTF-8
8,945
2.625
3
[]
no_license
/************************************************************************ stateRecord.h.cpp - Copyright denise Here you can write a license for your code, some comments or any other information you want to have in your generated code. To to this simply configure the "headings" directory in uml to point to a directory where you have your heading files. or you can just replace the contents of this file with your own. If you want to do this, this file is located at /usr/share/apps/umbrello/headings/heading.cpp -->Code Generators searches for heading files based on the file extension i.e. it will look for a file name ending in ".h" to include in C++ header files, and for a file name ending in ".java" to include in all generated java code. If you name the file "heading.<extension>", Code Generator will always choose this file even if there are other files with the same extension in the directory. If you name the file something else, it must be the only one with that extension in the directory to guarantee that Code Generator will choose it. you can use variables in your heading files which are replaced at generation time. possible variables are : author, date, time, filename and filepath. just write %variable_name% This file was generated on Thu Dec 11 2008 at 11:11:49 The original location of this file is /home/gauss/denise/uml-generated-code/stateRecord.cpp **************************************************************************/ #include "stateRecord.h" // Constructors/Destructors // const double stateRecord::NOVALUE = std::numeric_limits<double>::min(); stateRecord::stateRecord ( ) { initAttributes(); } stateRecord::stateRecord (vector<SAComponent*> state , vector< CQValue * > values) { setCState(state); setPossibleValues(values); initAttributes(); } stateRecord::~stateRecord ( ) { vector <SAComponent*>::iterator it; for (it = ( m_cState).begin(); it != (m_cState).end(); it++) (*it)->~SAComponent(); vector <CQValue*>::iterator it2; for (it2 = ( m_possibleValues).begin(); it2 != ( m_possibleValues).end(); it2++) (*it2)->~CQValue(); } // // Methods // unsigned int stateRecord::size(){ return m_possibleValues.size(); } /** * Set the value of m_possibleValues * @param new_var the new value of m_possibleValues */ void stateRecord::setPossibleValues ( vector< CQValue * > new_var ) { m_possibleValues = new_var; } /** * Get the value of m_possibleValues * @return the value of m_possibleValues */ vector< CQValue * > stateRecord::getPossibleValues ( ) { return m_possibleValues; } /** * Set the value of * @param new_var the new value of m_cState */ void stateRecord::setCState( vector<SAComponent*> new_var ) { sort(new_var.begin(),new_var.end(),saCompare); m_cState = new_var; } /** * Get the value of m_cState * @return the value of m_cState */ vector<SAComponent*> stateRecord::getCState( ) { sort(m_cState.begin(),m_cState.end(),saCompare); return m_cState; } /** * @return int */ int stateRecord::numStates( ) { return m_cState.size(); } double stateRecord::getActionValue(vector<SAComponent*> action){ vector<CQValue*>::const_iterator cii = getEntry(action); if (cii!=m_possibleValues.end()){ return (*cii)->getValue(); } return NOVALUE; } double stateRecord::getBestActionValue(){ vector<CQValue*>::const_iterator cii; double val = m_possibleValues[0]->getValue(); for(cii=m_possibleValues.begin(); cii!=m_possibleValues.end(); ++cii){ if ((*cii)->getValue()>val){ val = (*cii)->getValue(); } } return val; } vector<SAComponent*> stateRecord::getBestAction(){ vector<CQValue*>::const_iterator cii; double val = 0; bool allzero = true; vector<SAComponent*> ac; for(cii=m_possibleValues.begin(); cii!=m_possibleValues.end(); ++cii){ if ((*cii)->getValue()>val){ val = (*cii)->getValue(); ac = (*cii)->getCAction(); allzero = false; } } if(allzero){ // if all actions have the same value returns a random action return getRandomAction(); } return ac; } vector<SAComponent*> stateRecord::getBestSingleAction(){ vector<CQValue*>::const_iterator cii; double val = 0; bool allzero = true; vector<SAComponent*> ac; for(cii=m_possibleValues.begin(); cii!=m_possibleValues.end(); cii++){ if (((*cii)->isSingle())&&((*cii)->getValue()>val)){ val = (*cii)->getValue(); ac = (*cii)->getCAction(); allzero = false; } } if(allzero){ // if all actions have the same value returns a random action return getRandomSingleAction(); } return ac; } vector<SAComponent*> stateRecord::getRandomAction(){ if (!m_possibleValues.empty()) return m_possibleValues[rand()%m_possibleValues.size()]->getCAction(); } vector<SAComponent*> stateRecord::getRandomSingleAction(){ if (!m_possibleValues.empty()){ unsigned int r =0; do{ r = rand()%m_possibleValues.size(); }while(!m_possibleValues[r]->isSingle()); return m_possibleValues[r]->getCAction(); } vector<SAComponent*> ac; return ac; } vector<CQValue*>::iterator stateRecord::getEntry(vector<SAComponent*> action){ vector<CQValue*>::iterator cii; for(cii=m_possibleValues.begin(); cii!=m_possibleValues.end(); cii++){ if((*cii)->equals(action)){ return cii; } } return m_possibleValues.end(); } vector<CQValue*>::iterator stateRecord::getActionsEnd(){ return m_possibleValues.end(); } /** * Returns the error for the best possible action * (with the highest value) in a given state. * */ double stateRecord::getBestActionError(){ vector<CQValue*>::const_iterator cii; double val = stateRecord::NOVALUE;; bool allzero = true; double error = stateRecord::NOVALUE; for(cii=m_possibleValues.begin(); cii!=m_possibleValues.end(); cii++){ if ((*cii)->getValue()>val){ val = (*cii)->getValue(); error = (*cii)->getError(); } } return error; } /** * * Returns the error for the given action the state. * */ double stateRecord::getActionError(vector<SAComponent*> action){ vector<CQValue*>::const_iterator ac = getEntry(action); if (ac!=m_possibleValues.end()){ double r = (*ac)->getError(); //if(r>0) cout<<r<<endl; return r; } return NOVALUE; } bool stateRecord::addAction(vector<SAComponent*> action, double value){ vector<CQValue*>::const_iterator ac = getEntry(action); if (ac==m_possibleValues.end()){ sort(action.begin(),action.end(),saCompare); m_possibleValues.push_back( new CQValue(action,value) ); return true; } return false; } string stateRecord::print(){ ostringstream ret; string tmp; vector<SAComponent*>::const_iterator ci; ret<<"["; for(ci=m_cState.begin(); ci!=m_cState.end(); ci++){ ret<<(*ci)->print()<<","; } tmp = ret.str().erase(ret.str().length()-1); ret.str(""); ret<<tmp<<"] "; vector<CQValue*>::const_iterator cii; for(cii=m_possibleValues.begin(); cii!=m_possibleValues.end(); cii++){ ret<<(*cii)->print()<<" "; } return ret.str(); } bool stateRecord::operator==(const stateRecord &cqval) const{ unsigned int size = m_cState.size(); if(size!=cqval.m_cState.size()) return false; for(int i=0; i<size;i++) if (*(m_cState.at(i))== *(cqval.m_cState.at(i))) continue; else return false; return true; } vector<CQValue*>::iterator stateRecord::getBestActionEntry(){ return getEntry(getBestAction()); } bool stateRecord::equals( stateRecord* cqval){ unsigned int size = m_cState.size(); if(size!=cqval->getCState().size()) return false; for(int i=0; i<size;i++) if (*(m_cState.at(i))== *(cqval->getCState().at(i))) continue; else return false; return true; } bool stateRecord::equalState( vector<SAComponent*> state){ unsigned int size = m_cState.size(); if(size!=state.size()) return false; sort(state.begin(),state.end(),saCompare); //ensure the same order for(int i=0; i<size;i++) if (*(m_cState.at(i))== *(state.at(i))) continue; else return false; return true; } bool stateRecord::containsState( vector<SAComponent*> state){ sort(state.begin(),state.end(),saCompare); //ensure the same order return includes(m_cState.begin(), m_cState.end(), state.begin(), state.end(), saCompare); } bool stateRecord::testConvergence(double threshold){ vector<CQValue*>::iterator cii; for(cii=m_possibleValues.begin(); cii!=m_possibleValues.end(); cii++){ if ( (*cii)->getLastDifference() > threshold){ return false; } } return true; } // Other methods // void stateRecord::initAttributes ( ) { }
true
ae61f3aa7dd84520cef667d6733457425b9b270d
C++
tlouwers/STM32F4-DISCOVERY
/TiltExample/target/Src/Application.hpp
UTF-8
3,600
2.609375
3
[]
no_license
/** * \file Application.hpp * * \licence "THE BEER-WARE LICENSE" (Revision 42): * <terry.louwers@fourtress.nl> wrote this file. As long as you retain * this notice you can do whatever you want with this stuff. If we * meet some day, and you think this stuff is worth it, you can buy me * a beer in return. * Terry Louwers * * \brief Main application file for FreeRTOS demo. * * \note https://github.com/tlouwers/STM32F4-DISCOVERY/tree/develop/FreeRTOSProject/target/Src * * \details Intended use is to provide an example how to read the accelerometer. * * \author T. Louwers <terry.louwers@fourtress.nl> * \version 1.0 * \date 12-2021 */ #ifndef APPLICATION_HPP_ #define APPLICATION_HPP_ /************************************************************************/ /* Includes */ /************************************************************************/ #include <atomic> #include "config.h" #include "components/HI-M1388AR/HI-M1388AR.hpp" #include "components/HI-M1388AR/FakeHI-M1388AR.hpp" #include "components/LIS3DSH/LIS3DSH.hpp" #include "components/LIS3DSH/FakeLIS3DSH.hpp" #include "drivers/DMA/DMA.hpp" #include "drivers/Pin/Pin.hpp" #include "drivers/SPI/SPI.hpp" #include "drivers/Usart/Usart.hpp" /************************************************************************/ /* Structs */ /************************************************************************/ /** * \struct MotionSampleRaw * \brief Raw motion sensor values. */ struct MotionSampleRaw { int16_t X; ///< Raw sensor X value int16_t Y; ///< Raw sensor Y value int16_t Z; ///< Raw sensor Z value }; /** * \struct MotionSample * \brief Motion sensor values in G's (m/s2), pitch and roll in degrees. */ struct MotionSample { float X; ///< Sensor value X in G (m/s2) float Y; ///< Sensor value Y in G (m/s2) float Z; ///< Sensor value Z in G (m/s2) float pitch; ///< Sensor pitch value in degrees float roll; ///< Sensor roll value in degrees }; /************************************************************************/ /* Class declaration */ /************************************************************************/ /** * \brief Main application class. */ class Application { public: Application(); virtual ~Application() {}; bool Init(); void Error(); bool CreateTasks(); void StartTasks(); private: Pin mLedGreen; Pin mLedOrange; Pin mLedRed; Pin mLedBlue; Pin mChipSelectMatrix; Pin mChipSelectMotion; Pin mMotionInt1; Pin mMotionInt2; SPI mSPIMotion; SPI mSPIMatrix; Usart mUsart; DMA mDMA_SPI_Tx; DMA mDMA_SPI_Rx; #if (HI_M1388AR_DISPLAY == REAL_HI_M1388AR) HI_M1388AR mMatrix; #else FakeHI_M1388AR mMatrix; #endif #if (LIS3DSH_ACCELEROMETER == REAL_LIS3DSH) LIS3DSH mLIS3DSH; #else FakeLIS3DSH mLIS3DSH; #endif std::atomic<uint8_t> mMotionLength; void MotionDataReceived(uint8_t length); MotionSample CalculateMotionSample(const MotionSampleRaw &sampleRaw); void CalculatePixel(uint8_t *dest, const MotionSample &sample, bool invert = false); void CallbackMotionDataReceived(); void CallbackUpdateDisplay(const MotionSample &sample); void CallbackSendSampleViaUsart(const MotionSampleRaw &sample); }; #endif // APPLICATION_HPP_
true
7786f024223d948220d560c054919b7ced28356f
C++
meuter/ray
/include/ray/math/Rectangle.hpp
UTF-8
4,340
2.796875
3
[]
no_license
#pragma once #include <ray/math/Scalar.hpp> namespace ray { namespace math { template<template<typename U> class Vector, typename S> struct Rectangle { using vector = Vector<S>; using scalar = Scalar<S>; using rectangle = Rectangle<Vector,S>; vector min, max; constexpr auto operator+=(const vector &shift) { min+=shift; max+=shift; return (*this); } constexpr auto operator-=(const vector &shift) { min-=shift; max-=shift; return (*this); } constexpr auto operator*=(const vector &factor) { max = min + size()*factor; return (*this); } constexpr auto operator/=(const vector &factor) { max = min + size()/factor; return (*this); } constexpr auto operator*=(const scalar &factor) { max = min + size()*factor; return (*this); } constexpr auto operator/=(const scalar &factor) { max = min + size()/factor; return (*this); } vector size() const { return max - min; } }; template<typename T, template<typename U> class Vector, typename F> constexpr auto rect_cast(const Rectangle<Vector,F> &r) { return Rectangle<Vector,T>{ vector_cast<T>(r.min), vector_cast<T>(r.max) }; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator+(const Rectangle<Vector,S1> &r, const Vector<S2> &v) { return Rectangle<Vector, widest<S1,S2>>{ r.min+v, r.max+v}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator-(const Rectangle<Vector,S1> &r, const Vector<S2> &v) { return Rectangle<Vector, widest<S1,S2>>{ r.min-v, r.max-v}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator+(const Vector<S2> &v, const Rectangle<Vector,S1> &r) { return Rectangle<Vector, widest<S1,S2>>{ r.min+v, r.max+v}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator-(const Vector<S2> &v, const Rectangle<Vector,S1> &r) { return Rectangle<Vector, widest<S1,S2>>{ r.min-v, r.max-v}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator*(const Rectangle<Vector,S1> &a, const Scalar<S2> &b) { return Rectangle<Vector,widest<S1,S2>>{ S2(1)*a.min,a.min+a.size()*b}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator/(const Rectangle<Vector,S1> &a, const Scalar<S2> &b) { return Rectangle<Vector,widest<S1,S2>>{ S2(1)*a.min,a.min+a.size()/b}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator*(const Scalar<S2> &b, const Rectangle<Vector,S1> &a) { return Rectangle<Vector,widest<S1,S2>>{ S2(1)*a.min,a.min+b*a.size()}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator/(const Scalar<S2> &b, const Rectangle<Vector,S1> &a) { return Rectangle<Vector,widest<S1,S2>>{ S2(1)*a.min,a.min+b/a.size()}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator*(const Rectangle<Vector,S1> &r, const Vector<S2> &v) { return Rectangle<Vector, widest<S1,S2>>{ S2(1)*r.min, r.min+r.size()*v}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator/(const Rectangle<Vector,S1> &r, const Vector<S2> &v) { return Rectangle<Vector, widest<S1,S2>>{ S2(1)*r.min, r.min+r.size()/v}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator*(const Vector<S2> &v, const Rectangle<Vector,S1> &r) { return Rectangle<Vector, widest<S1,S2>>{ S2(1)*r.min, r.min+v*r.size()}; } template<template<typename U> class Vector, typename S1, typename S2> constexpr auto operator/(const Vector<S2> &v, const Rectangle<Vector,S1> &r) { return Rectangle<Vector, widest<S1,S2>>{ S2(1)*r.min, r.min+v/r.size()}; } template<template<typename U> class Vector, typename S1> auto &operator<<(std::ostream &out, const Rectangle<Vector,S1> &r) { return (out << "[" << r.min << "->" << r.max << "]"); } template<typename S1, typename S2, template<typename U> class Vector> constexpr auto widen_cast(const Rectangle<Vector,S1> &source) { return Rectangle<Vector,widest<S1,S2>>{ widest<S1,S2>(source.min), widest<S1,S2>(source.min) }; } }}
true
b47ac15652a1a94911c396bea469f1f829856d28
C++
pablogadhi/DecafCompiler
/structs/symb_table.h
UTF-8
4,484
2.796875
3
[]
no_license
#ifndef SYMB_TABLE_H #define SYMB_TABLE_H #include "error_item.h" #include <functional> #include <memory> #include <string> #include <unordered_map> #include <vector> using namespace std; class TableRow { private: string row_name = ""; string row_type = ""; public: TableRow(string, string); TableRow(); ~TableRow(); string name() const; string type(); }; class Symbol : public TableRow { private: int s_size = -1; int s_offset = -1; public: Symbol(string, string, int, int); Symbol(); ~Symbol(); int size(); int offset(); }; class Type : public TableRow { private: int t_size = -1; public: Type(string, string, int); Type(); ~Type(); int size(); }; class Method : public TableRow { private: vector<string> m_param_signature; string m_alias = ""; public: Method(string, string, vector<string> param_signature = vector<string>{}, string alias = ""); Method(); ~Method(); vector<string> param_signature() const; void set_alias(string); string alias(); }; struct MethodHasher { hash<string> str_hash; size_t operator()(const Method &key) const { size_t hashed_args = 0; for (auto &arg : key.param_signature()) { hashed_args += str_hash(arg); } return str_hash(key.name()) + hashed_args; } }; struct MethodComparator { bool operator()(const Method &lmeth, const Method &rmeth) const { return lmeth.name() == rmeth.name() && lmeth.param_signature() == rmeth.param_signature(); } }; class SymbolTable : public enable_shared_from_this<SymbolTable> { private: Method t_id; vector<Symbol> t_symbols; vector<Type> t_types; vector<Method> t_methods; shared_ptr<SymbolTable> t_parent; unordered_map<Method, shared_ptr<SymbolTable>, MethodHasher, MethodComparator> t_children; int base_offset = 0; public: SymbolTable(); SymbolTable(Method); SymbolTable(Method, shared_ptr<SymbolTable>, int b_offset = 0); ~SymbolTable(); void init_basic_types(); Method &id(); string name(); vector<Symbol> &symbols(); vector<Type> &types(); vector<Method> &methods(); int next_symbol_offset(); void add_symbol( string, string, int, function<void()> = [] {}); void add_type( string, string, int, function<void()> = [] {}); void add_method( string, string, vector<string>, string alias = "", function<void()> = [] {}); shared_ptr<SymbolTable> parent(); void add_child(shared_ptr<SymbolTable>); unordered_map<Method, shared_ptr<SymbolTable>, MethodHasher, MethodComparator> &children(); pair<SymbolTable, vector<vector<string>>> flatten(); }; template <class InfoType> bool get_where(vector<InfoType> &table_vector, function<bool(InfoType &)> predicate, InfoType *out = nullptr) { auto iter = find_if(table_vector.begin(), table_vector.end(), predicate); if (iter != table_vector.end()) { if (out != nullptr) { *out = *iter; } return true; } return false; } // TODO Figure something out without overloading template <class InfoType> bool recursive_lookup( shared_ptr<SymbolTable> table, function<vector<InfoType>(shared_ptr<SymbolTable>)> vector_lambda, function<bool(InfoType &)> predicate, InfoType *out = nullptr) { vector<InfoType> vector_to_search = vector_lambda(table); if (!get_where(vector_to_search, predicate, out)) { if (table->parent() != nullptr) { return recursive_lookup(table->parent(), vector_lambda, predicate, out); } else { return false; } } return true; } template <class InfoType> bool recursive_lookup( shared_ptr<SymbolTable> table, function<vector<InfoType>(shared_ptr<SymbolTable>)> vector_lambda, function<bool(InfoType &)> predicate, shared_ptr<SymbolTable> &found_in, InfoType *out = nullptr) { vector<InfoType> vector_to_search = vector_lambda(table); if (!get_where(vector_to_search, predicate, out)) { if (table->parent() != nullptr) { return recursive_lookup(table->parent(), vector_lambda, predicate, found_in, out); } else { return false; } } found_in = table; return true; } template <class InfoType> vector<InfoType> get_all_where(vector<InfoType> &table_vector, function<bool(InfoType &)> predicate) { vector<InfoType> output_vec; copy_if(table_vector.begin(), table_vector.end(), back_inserter(output_vec), predicate); return output_vec; } #endif
true
62c49bbd4705215f0c5cfd98a3dd93c799c8bc98
C++
Universe-Liu/STUDY
/OJ/有理数类.cpp
UTF-8
1,514
3.546875
4
[]
no_license
#include<iostream> using namespace std; class Rational { public: Rational(int a=0,int b=1) { int c; c=Common_Divisor(a,b); X=a/c; Y=b/c; } Rational Add(Rational &r); Rational Sub(Rational &r); Rational Div(Rational &r); Rational Mul(Rational &r); void Print() {cout<<"X/Y="<<X<<"/"<<Y<<endl;} void PrintPoint() { if(Y==0) exit(0); cout<<"X/Y="<<double(X)<<"/"<<Y<<endl; } private: int X,Y; int Common_Divisor(int a,int b); }; Rational Rational::Add(Rational &r) { int a,b,c; a=X*r.Y+Y*r.X; b=Y*r.Y; c=Common_Divisor(a,b); return Rational(a/c,b/c); } Rational Rational::Sub(Rational &r) { int a,b,c; a=X*r.Y-Y*r.X; b=Y*r.Y; c=Common_Divisor(a,b); return Rational(a/c,b/c); } Rational Rational::Mul(Rational &r) { int a,b,c; a=X*r.X; b=Y*r.Y; c=Common_Divisor(a,b); return Rational(a/c,b/c); } Rational Rational::Div(Rational &r) { int a,b,c; a=X*r.Y; b=Y*r.X; c=Common_Divisor(a,b); return Rational(a/c,b/c); } int Rational::Common_Divisor(int a,int b) { int c; do { c=a*b; a=b; b=c; } while (c!=0); return a; } int main() { Rational x(3,4),y(6,7); x.Add(y).Print(); x.Sub(y).Print(); x.Mul(y).Print(); x.Div(y).Print(); x.Add(y).PrintPoint(); return 0; }
true
862acc5cc787aa3d4920ae72422ce8a8f05116cc
C++
Tug/RayTracer
/test/Screen.cpp
UTF-8
379
2.875
3
[]
no_license
#include "stdafx.h" #include "Screen.h" Screen::Screen(int width, int height) { this->width = width; this->height = height; } Screen::~Screen() { } int Screen::getWidth() { return width; } int Screen::getHeight() { return height; } void Screen::fillBackground(RGBColor & c) { for(int y=0; y<height; y++) { for(int x=0; x<width; x++) { setPixel(x, y, c); } } }
true
7e6476b553c664925756ead2b969ef63c90bc9f1
C++
allebacco/compressed_streams
/lib/tests/test_zstd_stream.cpp
UTF-8
1,923
2.78125
3
[ "MIT" ]
permissive
#include "../include/compressed_streams/zstd_stream.h" #include "common.h" using namespace compressed_streams; using ZstdIOStreamTypes = ::testing::Types<std::tuple<ZstdOStream, ZstdIStream>>; INSTANTIATE_TYPED_TEST_CASE_P(ZstdIOStreamTest, IOStreamTest, ZstdIOStreamTypes); /* #include <algorithm> #include <numeric> #include <vector> #include <sstream> #include <strstream> #include <gtest/gtest.h> #include <zstd.h> #include "../include/compressed_streams/zstd_stream.h" std::vector<char> generate_data_range(const size_t count) { std::vector<char> data(count); for(size_t i=0; i<count; ++i) data[i] = static_cast<char>(i & 0xFF); return data; } TEST(ZstdStream, Compression) { std::vector<char> data = generate_data_range(10); std::ostringstream ostream(std::ios_base::out|std::ios_base::binary); { compressed_streams::ZstdOStream zstd_ostream(ostream, 1); zstd_ostream.write(data.data(), data.size()); } std::string result = ostream.str(); std::vector<char> test_data(data.size()); size_t decompressed_bytes = ZSTD_decompress(test_data.data(), test_data.size(), result.data(), result.size()); EXPECT_EQ(decompressed_bytes, data.size()); EXPECT_EQ(data, test_data); } TEST(ZstdStream, Decompress) { std::vector<char> data = generate_data_range(10); std::vector<char> compressed_data(data.size() + 5000); size_t compressed_bytes = ZSTD_compress(compressed_data.data(), compressed_data.size(), data.data(), data.size(), ZSTD_CLEVEL_DEFAULT); std::vector<char> test_data(data.size()); std::istrstream istream(compressed_data.data(), compressed_bytes); { compressed_streams::ZstdIStream zstd_istream(istream); zstd_istream.read(test_data.data(), test_data.size()); std::streamsize read_count = zstd_istream.gcount(); EXPECT_EQ(data.size(), read_count); EXPECT_EQ(data, test_data); } } */
true
c529397465f5286154879796eede6795a37ffe8b
C++
MattKD/x86_kernel
/timer.cpp
UTF-8
1,156
2.640625
3
[ "MIT" ]
permissive
#include <stdint.h> #include "isr_irqs.h" #include "ioport.h" #include "stdio.h" #include "kb.h" extern "C" { void kernel_halt(); } namespace { // Total ticks system has been running. Incremented every IRQ 0 unsigned timer_ticks = 0; // IRQ 0 // Increment timer_ticks 1000x per sec void IRQ_timerHandler() { timer_ticks++; } } // unnamed namespace namespace kernel { void timerInit() { const int PIT_CMD = 0x43; const int CHANNEL0 = 0x40; uint16_t divisor = 1193; // 1193180 Hz / 1000 Ticks Per Sec // 0x36 = channel 0, Send lo then hi byte of divisor, Square Root Mode kernel_outport(PIT_CMD, 0x36); kernel_outport(CHANNEL0, divisor & 0xFF); // send low byte of divisor kernel_outport(CHANNEL0, divisor >> 8); // send high byte of divisor IRQ_addHandler(0, IRQ_timerHandler); } void sleep(unsigned ms) { bool kb_was_disabled = isKeyboardDisabled(); disableKeyboardInput(); unsigned end_ticks = timer_ticks + ms; while(timer_ticks < end_ticks) { kernel_halt(); } // reenable keyboard if it wasn't disabled before sleep if (!kb_was_disabled) { enableKeyboardInput(); } } } // namespace kernel
true
f79d8b4c3f44a9b0eca2acf4a8c0f16a62f97e2d
C++
fbobee/Alpenglow
/cpp/src/main/filters/AvailabilityFilter.h
UTF-8
1,907
2.59375
3
[ "Apache-2.0" ]
permissive
#ifndef AVAILABILITY_FILTER_H #define AVAILABILITY_FILTER_H //SIP_AUTOCONVERT #include "ModelFilter.h" #include <queue> #include <set> #include <gtest/gtest_prod.h> #include <tuple> #include <functional> class AvailabilityFilter : public ModelFilter { /** This is the docstring for AvailabilityFilter. This filter filters the set of available items based on (time,itemId,duration) triplets. These have to be preloaded before using this filter. Sample code .. code-block:: python :emphasize-lines: 3,5 def some_function(): interesting = False print 'This line is highlighted.' print 'This one is not...' print '...but this one is.' .. code-block:: python :linenos: # this is python code f = rs.AvailabilityFilter() f.add_availability(10,1,10) #item 1 is available in the time interval (10,20) */ public: virtual void run(RecDat* rec_dat) override; /** run(rec_dat) Summary line. Extended description of function. Parameters ---------- arg1 : int Description of arg1 arg2 : str Description of arg2 Returns ------- bool Description of return value */ virtual vector<pair<int,double>>* get_global_items() override; virtual bool active(RecDat*) override; bool self_test(){ bool OK = ModelFilter::self_test(); return OK; } void add_availability(double time, int id, int duration); protected: priority_queue<tuple<double, int, int>, vector<tuple<double, int, int>>, greater<tuple<double,int,int>>> availabilites_; priority_queue<pair<double, int>, vector<pair<double, int>>, greater<pair<double,int>>> availability_ends_; set<pair<int, double>> available_items_set_; vector<pair<int, double>> available_items_; FRIEND_TEST(TestAvailabilityFilter, test); }; #endif /* AVAILABILITY_FILTER_H */
true
4fda1953246a31452e050475270c05614024b82b
C++
reedhong/lotus
/Lotus/Lotus/ResourceManage/ResourceManager.h
GB18030
1,153
2.921875
3
[]
no_license
/* * ӦԴĹ * created by reedhong 2012.08.06 */ #ifndef __Lotus_ResourceManager_H__ #define __Lotus_ResourceManager_H__ #include "Resource.h" namespace Lotus { class ResourceManager { public: ResourceManager(); virtual ~ResourceManager(); virtual ResourcePtr create(const String& name, const String& path); virtual Resource* createImpl(const String& name, const String& path) = 0; typedef std::pair<ResourcePtr, bool> ResourceCreateOrRetrieveResult; virtual ResourceCreateOrRetrieveResult createOrRetrieve(const String& name, const String& path); virtual ResourcePtr load(const String& name, const String& path); virtual void unload(const String& name); virtual void unloadAll(); virtual void remove(const String& name); virtual void removeAll(void); virtual bool resourceExists(const String& name); virtual ResourcePtr getByName(const String& name); const String& getResourceType(void) const { return mResourceType; } public: // TODO: ʱmap typedef map< String, ResourcePtr > ResourceMap; protected: ResourceMap mResources; String mResourceType; }; } #endif
true
4c369c20fdcea08029478cd73728afec2d97b031
C++
XiuyeXYE/cpp
/algorithm/separate_chaining_hash_ST.cpp
UTF-8
2,463
3.28125
3
[]
no_license
#include"../common" #define ZERO(T) static_cast<T>(0); template<class K,class V> struct node{ K key; V val; node<K,V> *next; node(K key,V value,node<K,V>*next):key(key),val(val),next(next){} }; template<class K,class V> class sequential_search_ST{ node<K,V> *first; public: V get(K key){ for(node<K,V> *x=first;x != nullptr;x=x->next){ if(key == x->key){ return x->val; } } return ZERO(V); } void put(K key,V val){ for(node<K,V> *x = first;x != nullptr;x=x->next){ if(key == x->key){ x->val = val; return; } } //头部插入 first = new node<K,V>(key,val,first); } }; //哈希链表解决冲突! template<class K,class V> class separate_chaining_hash_ST{ int n; int m; sequential_search_ST<K,V> **st; int hash(K key){ //key native hash from memory address return (ssize_t(&key) & 0x7fffffff) % m; } public: // separate_chaining_hash_ST():separate_chaining_hash_ST(1997){ // } separate_chaining_hash_ST(int m=1997){ this->m = m; st = new sequential_search_ST<K,V>*[m]; for(int i=0;i<m;i++){ st[i] = new sequential_search_ST<K,V>(); } } V get(K key){ return st[hash(key)]->get(); } void put(K key,V value){ st[hash(key)]->put(key,value); } //iterator 迭代器 实现? virtual ~separate_chaining_hash_ST(){ for(int i=0;i<m;i++){ log("delete element():"); delete st[i]; } log("delete elements array[]:"); delete []st; } }; int main(){ int **a = new int*[8];//指针数组 / No:数组指针 for(int i=0;i<10;i++){ int j=rand()%10; log(j); a[i] = new int[j]; a[i] = new int(123); } separate_chaining_hash_ST<int,int> st; for(int i=0;i<100;i++){ int j = rand()%10000; st.put(j,i); } return 0; }
true
cb44de263464ce8ce9a05918011c9aa187e685bb
C++
xeon2007/DuiFramework
/DuiFramework/event/event_listener.h
UTF-8
1,249
2.546875
3
[]
no_license
#pragma once #include "event/event_forward.h" #include <vector> #include <unordered_map> namespace ui { class EventListener : public RefCounted<EventListener> { public: enum Type { //JSEventListenerType, ImageEventListenerType, CPPEventListenerType, ConditionEventListenerType, NativeEventListenerType, }; virtual ~EventListener() { } virtual void HandleEvent(Event*) = 0; Type type() const { return type_; } protected: explicit EventListener(Type type) : type_(type) { } private: Type type_; }; typedef scoped_refptr<EventListener> RegisteredEventListener; typedef std::vector<RegisteredEventListener> EventListenerVector; class EventListenerMap { public: EventListenerMap(); ~EventListenerMap(); bool isEmpty() const { return entries_.empty(); } bool contains(EventType eventType) const; //bool containsCapturing(const AtomicString& eventType) const; void clear(); bool add(EventType eventType, EventListener*); bool remove(EventType eventType, EventListener*, size_t& indexOfRemovedListener); EventListenerVector* find(EventType eventType); std::vector<EventType> eventTypes() const; private: std::unordered_map<EventType, EventListenerVector> entries_; }; }
true
20ea48ac412d9412c222760ddd004bec8b671595
C++
robin1987z/telekyb
/telekyb_main/telekyb_interface/include/telekyb_interface/Option.hpp
UTF-8
2,926
2.6875
3
[]
no_license
/* * Option.hpp * * Created on: Nov 15, 2011 * Author: mriedel */ #ifndef INTERFACE_OPTION_HPP_ #define INTERFACE_OPTION_HPP_ #include <string> #include <ros/ros.h> #include <telekyb_defines/telekyb_defines.hpp> #include <telekyb_base/Tools/XmlRpcConversion.hpp> #include <telekyb_base/Tools/YamlHelper.hpp> #include <telekyb_srvs/StringInput.h> #include <telekyb_srvs/StringOutput.h> namespace TELEKYB_INTERFACE_NAMESPACE { class Option { private: // only created by OptionController or Optioncontainer Option(const ros::NodeHandle& optionNSNodehandle_, const std::string& optionName_); protected: // reference to NodeHandle ros::NodeHandle optionNSNodehandle; std::string optionName; public: // Option(); virtual ~Option(); // exists? bool exists(); // setter and getter template <class _T> bool get(_T& optionValue) { ros::NodeHandle optionServiceNodehandle(optionNSNodehandle, optionName); ros::ServiceClient client = optionServiceNodehandle.serviceClient<telekyb_srvs::StringOutput>(OPTION_GETSERVICE_NAME); telekyb_srvs::StringOutput soService; if (!client.call(soService)) { ROS_ERROR_STREAM("Unable to get Option. Failed to call: " << client.getService()); return false; } // Error print should be in here return telekyb::YamlHelper::parseStringToValue(soService.response.output, optionValue); } template <class _T> bool set(const _T& optionValue) { ros::NodeHandle optionServiceNodehandle(optionNSNodehandle, optionName); ros::ServiceClient client = optionServiceNodehandle.serviceClient<telekyb_srvs::StringInput>(OPTION_SETSERVICE_NAME); telekyb_srvs::StringInput siService; if (! telekyb::YamlHelper::parseValueToString(optionValue, siService.request.input) ) { return false; } // everything ok. if (!client.call(siService)) { ROS_ERROR_STREAM("Unable to set Option. Failed to call: " << client.getService()); return false; } return true; } // async uses Paramter server template <class _T> bool getAsync(_T& optionValue) { XmlRpc::XmlRpcValue value; optionNSNodehandle.getParam(optionName, value); // Conversion try { value >> optionValue; } catch (XmlRpc::XmlRpcException &e) { // value On Ros is invalid! Revert to Optionvalue. ROS_ERROR_STREAM("Could not convert Option " << optionName << " FROM XmlRpcValue! " << e.getMessage()); return false; } return true; } template <class _T> bool setAsync(const _T& optionValue) { XmlRpc::XmlRpcValue value; try { optionValue >> value; optionNSNodehandle.setParam(optionName, value); } catch (XmlRpc::XmlRpcException &e) { ROS_ERROR_STREAM("Could not convert Option " << optionName << " to XmlRpcValue! " << e.getMessage()); return false; } return true; } // allowed to create Options friend class OptionController; friend class OptionContainer; }; } /* namespace telekyb_interface */ #endif /* OPTION_HPP_ */
true
db3e6c1b8c2c82d7869ed7b9604b52f7cfb8fd89
C++
waddlin-penguin/maze
/maze/graph/graph.cpp
UTF-8
1,769
3.296875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: graph.cpp * Author: jonathan * * Created on June 1, 2017, 6:39 AM */ #include "graph.h" Node::Node(int arg_x, int arg_y) { x = arg_x; y = arg_y; } Node::Node(const Node& orig) { } Node::~Node() { } Graph::Graph(int width, int length) { all_nodes.reserve(length); // Keep track of last made row. vector<Node> previous_row = CreateOneRow(width, 0); all_nodes[0] = previous_row; for (int vertical = 1; vertical < length; vertical++) { // Create one row vector<Node> current_row = CreateOneRow(width, vertical); all_nodes[vertical] = current_row; // Stitch together the last row and this row. for (int horizontal = 0; horizontal < width; horizontal++) { current_row[horizontal].down_neighbor = &previous_row[horizontal]; previous_row[horizontal].up_neighbor = &current_row[horizontal]; } previous_row = current_row; } } vector<Node> Graph::CreateOneRow(int width, int vertical_index) { vector<Node> row; row.reserve(width); // Make row of nodes without neighbors. for (int horizontal = 0; horizontal < width; horizontal++) { row[horizontal] = Node(horizontal, vertical_index); } // Give everyone their right neighbor. for (int horizontal = 0; horizontal < width - 1; horizontal++) { row[horizontal].right_neighbor = &row[horizontal + 1]; } // Give everyone their left neighbor. for (int horizontal = 1; horizontal < width; horizontal++) { row[horizontal].left_neighbor = &row[horizontal - 1]; } return row; } Graph::Graph(const Graph& orig) { } Graph::~Graph() { }
true
676a93610e1bfcc3e00bf9f22d538c73bdd50ef4
C++
HalfCorgi23/SH_Technical_Compitition
/Transfrom_String.cpp
UTF-8
755
2.90625
3
[]
no_license
#include "stdafx.h" #include "Transfrom_String.h" Transfrom_String::Transfrom_String() { } Transfrom_String::~Transfrom_String() { } string Transfrom_String::int_to_string(int input) { char temp[8]; string output; _itoa_s(input, temp, 10); output = temp; return output; } string Transfrom_String::float_to_string(float input) { stringstream temp_sstream; temp_sstream << input; string out_put; temp_sstream >> out_put; temp_sstream.clear(); return out_put; } /*doubleתstring*/ string Transfrom_String::double_to_string(double input) { string out_put; char temp[20]; sprintf_s(temp, "%f", input); out_put = temp; return out_put; } //char转int int Transfrom_String::char_to_int(char input) { int s; s = input - 48; return s; }
true
3cabe66fca6d6e13d16888d68e0c1451f495bd76
C++
rushikhot05/Data-Structures
/Array/reversion.cpp
UTF-8
838
4.25
4
[]
no_license
//Recursive approach to reverse the array #include<bits/stdc++.h> using namespace std; //Function to reverse the arr[] from start to end void reverseArray(int arr[], int start, int end){ if(start >= end){ return; } int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; //Recursive function calling reverseArray(arr, start + 1, end - 1); } //Printing the array void printArray(int arr[], int size){ for(int i=0; i<size; i++){ cout << arr[i] << " "; } cout << endl; } //Driver Code int main(){ int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; //Printing Original Array printArray(arr, 10); //Calling reverse function reverseArray(arr, 0, 9); cout << "Reversed array is " << endl; printArray(arr, 10); return 0; }
true
2d5f8c8ea53dc4362a4841013e7fe7c17b80d558
C++
rahulssheth/CS-32
/Project 1/Rats.h
UTF-8
536
2.53125
3
[]
no_license
// // Rats.hpp // Project 1 CS 32 // // Created by Rahul Sheth on 1/10/17. // Copyright © 2017 Rahul Sheth. All rights reserved. // using namespace std; #ifndef Rats//.h #define Rats.h #include "Arena.h" class Rat { public: // Constructor Rat(Arena* ap, int r, int c); // Accessors int row() const; int col() const; bool isDead() const; // Mutators void move(); private: Arena* m_arena; int m_row; int m_col; int m_health; int m_idleTurnsRemaining; }; #endif
true
ff3dd92e3874dea0e6a1f4588607a443eee950da
C++
meeree/Pool
/SGV3D/src/runtimeOptions.h
UTF-8
1,188
2.921875
3
[]
no_license
#ifndef __RUNTIME_OPTIONS_H__ #define __RUNTIME_OPTIONS_H__ #include <string> enum OptionsEnum { UNI_COLOR_SCHEME=0, UNI_CAMERA_POSITION, UNI_CAMERA_DIRECTION, UNI_MAXIMUM, UNI_MINIMUM, UNI_MODEL_MATRIX, UNI_VIEW_MATRIX, UNI_PROJECTION_MATRIX, OPTIONS_COUNT }; class RuntimeOptions { private: struct OptLookupPair { std::string optName; std::string optVal; }; OptLookupPair m_optCache[OptionsEnum::OPTIONS_COUNT]; std::string m_configPath; ///\brief Parse config file into m_options void ParseConfig (); ///\brief Setup m_options by parsing config file. /// Note that this is private because RuntimeOptions is a singleton ///\param [in] optionsPath path to config file RuntimeOptions (const char* configPath="../config/config.txt"); public: ///\brief Get const singleton instance static RuntimeOptions& Get (); ///\brief Get string value defined in config std::string GetString (OptionsEnum const& lookup) const {return m_optCache[lookup].optVal;} inline std::string GetConfigPath () const {return m_configPath;} }; #endif //__RUNTIME_OPTIONS_H__
true
f9860f26c8d47cee7e456a0e44b3eb0f91aa17a7
C++
untrobotics/IEEE-R5-2019
/ArduinoCode/Stepper_Test/Stepper_Test.ino
UTF-8
1,287
3.09375
3
[ "MIT" ]
permissive
/************************* Joel Bartlett SparkFun Electronics December 27, 2012 This code controls a stepper motor with the EasyDriver board. It spins forwards and backwards ***************************/ int dirpin = 30; int steppin = 6; void setup() { pinMode(dirpin, OUTPUT); pinMode(steppin, OUTPUT); } void loop() { int i; digitalWrite(dirpin, HIGH); // Set the direction. delay(100); for (i = 0; i<400000; i++) // Iterate for 4000 microsteps. { digitalWrite(steppin, LOW); // This LOW to HIGH change is what creates the digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step. delayMicroseconds(500); // This delay time is close to top speed for this } // particular motor. Any faster the motor stalls. /*digitalWrite(dirpin, HIGH); // Change direction. delay(100); for (i = 0; i<4000; i++) // Iterate for 4000 microsteps { digitalWrite(steppin, LOW); // This LOW to HIGH change is what creates the digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step. delayMicroseconds(500); // This delay time is close to top speed for this } // particular motor. Any faster the motor stalls. */ }
true
515fb9cd5bc7d75b41f5566e3555e84553df39ca
C++
Tekktronic/QTBattleshipCIS17B-48597
/Battleship_source_code_Ezra_Guinmapang/Player.cpp
UTF-8
10,924
3.1875
3
[]
no_license
/* * File: Player.cpp * Author: Ezra Guinmapang * * Created on April 28, 2014, 11:24 PM */ #include "Player.h" //Player class Player::Player(){ //initializing code here } Player::Player(string Name){ P_Name = Name; //set the Player name FleetCT = 5; //initialize the Fleet Count SunkCT = 0; //initialize the Sunk Count to zero //create the fleet of Ships p_Fleet.push_back(new Ship("Aircraft Carrier")); p_Fleet.push_back(new Ship("Battleship")); p_Fleet.push_back(new Ship("Destroyer")); p_Fleet.push_back(new Ship("Submarine")); p_Fleet.push_back(new Ship("Patrol Boat")); //initialize the placement grid and shots grid for(int row = 0; row < 10; row++){ for(int col = 0; col < 10; col++){ p_Grid[row][col] = '_'; s_Grid[row][col] = '_'; } } } Player::~Player(){ //cleanup code here } grid Player::P_Grid(){ return p_Grid; } grid Player::S_Grid(){ return s_Grid; } string Player::Shot(){ return Coords; } string Player::Name(){ return P_Name; } short Player::FleetSize(){ return FleetCT; } short Player::SunkSize(){ return SunkCT; } vector<Ship *> Player::Fleet(){ return p_Fleet; } //Populate the board with your ships void Player::C_Ships(){ char s_type = '0'; short ac_left = 1, bs_left = 1, ds_left = 1, sb_left = 1, pb_left = 1; short hp = 0, n_Ships = 1; short ctr; vector<string> anchor; do{ cout << "Enter the type of ship to place:\n"; cout << "A. Aircraft Carrier (" << ac_left << " available)\n"; cout << "B. Battleship (" << bs_left << " available)\n"; cout << "C. Destroyer (" << ds_left << " available)\n"; cout << "D. Submarine (" << sb_left << " available)\n"; cout << "E. Patrol boat (" << pb_left << " available)\n"; cout << "Enter your choice: "; cin >> s_type; switch(toupper(s_type)){ case 'A':{ if(ac_left > 0){ hp = 5; c_Ship = p_Fleet.at(0); PlaceIt(hp); ac_left--; n_Ships++; break; } else{ cout << "None available! Pick again.\n"; break; } } case 'B':{ if(bs_left > 0){ hp = 4; c_Ship = p_Fleet.at(1); PlaceIt(hp); bs_left--; n_Ships++; break; } else{ cout << "None available! Pick again.\n"; break; } } case 'C':{ if(ds_left > 0){ hp = 3; c_Ship = p_Fleet.at(2); PlaceIt(hp); ds_left--; n_Ships++; break; } else{ cout << "None available! Pick again.\n"; break; } } case 'D':{ if(sb_left > 0){ hp = 3; c_Ship = p_Fleet.at(3); PlaceIt(hp); sb_left--; n_Ships++; break; } else{ cout << "None available! Pick again.\n"; break; } } case 'E':{ if(pb_left > 0){ hp = 2; c_Ship = p_Fleet.at(4); PlaceIt(hp); pb_left--; n_Ships++; break; } else{ cout << "None available! Pick again.\n"; break; } } default: cout << "Invalid choice! Try again.\n"; } }while(n_Ships <= 5); } //Display Board void Player::Display(grid Grid){ char x_Coord; cout << "**********************\n"; cout << "| " << P_Name << " >>>\n"; cout << "**********************\n"; cout << " 0 1 2 3 4 5 6 7 8 9" << endl; for(short ctr = 0; ctr < 10; ctr++){ switch(ctr){ case 0: x_Coord = 'A'; break; case 1: x_Coord = 'B'; break; case 2: x_Coord = 'C'; break; case 3: x_Coord = 'D'; break; case 4: x_Coord = 'E'; break; case 5: x_Coord = 'F'; break; case 6: x_Coord = 'G'; break; case 7: x_Coord = 'H'; break; case 8: x_Coord = 'I'; break; case 9: x_Coord = 'J'; break; default: cout << "Err..\n"; break; } cout << x_Coord << "|"; for(short ctr2 = 0; ctr2 < 10; ctr2++){ cout << Grid[ctr][ctr2] << "|"; } cout << endl; } cout << endl; } bool Player::GetCoord(){ bool isValid = false; cin >> Coords; switch(toupper(Coords[0])){ case 'A': posx = 0; break; case 'B': posx = 1; break; case 'C': posx = 2; break; case 'D': posx = 3; break; case 'E': posx = 4; break; case 'F': posx = 5; break; case 'G': posx = 6; break; case 'H': posx = 7; break; case 'I': posx = 8; break; case 'J': posx = 9; break; default: break; } switch(Coords[1]){ case '0': posy = 0; break; case '1': posy = 1; break; case '2': posy = 2; break; case '3': posy = 3; break; case '4': posy = 4; break; case '5': posy = 5; break; case '6': posy = 6; break; case '7': posy = 7; break; case '8': posy = 8; break; case '9': posy = 9; break; default: break; } if((toupper(Coords[0]) >= 'A')&&(toupper(Coords[0]) <= 'J')&&(Coords[1] >= '0')&&(Coords[1] <= '9') && Coords.size() == 2){ isValid = true; } else{ cout << "Invalid coordinates! Try again.\n"; } return isValid; } //Resolve hits short Player::Impact(string x_y, USS o_Fleet){ short f_Size = 0; bool isHit = false; for(int ctr = 0; ctr < o_Fleet.size(); ctr++){ if(o_Fleet.at(ctr)->PollRange(x_y)){ //allows each Ship instance to check its Range to see if it is hit isHit = true; cout << "A direct HIT, Admiral! Well Done!\n\n"; break; } } if(!isHit) cout << "The shot was a MISS, Admiral!\n"; for(int ctr2 = 0; ctr2 < o_Fleet.size(); ctr2++){ if(o_Fleet.at(ctr2)->Sunk()){ f_Size++; } } SunkCT = f_Size; } //Place your ships void Player::PlaceIt(short hp){ bool isValid = false, isFinal = false; char choice, pos; string x_y; vector<string> Chkpos; do{ cout << "Place vertically or horizontally(V/H)? "; cin >> pos; if(toupper(pos) != 'H' && toupper(pos) != 'V') cout << "Invalid placement! Try again.\n"; }while(toupper(pos) != 'H' && toupper(pos) != 'V'); do{ do{ cout << "Enter the coordinates to place your ship: "; isValid = GetCoord(); int ctr = 0; for(char x = Coords[0], y = Coords[1]; ctr < hp; ctr++){ x_y = x; x_y = x_y + y; Chkpos.push_back(x_y); if(toupper(pos) == 'V'){ if(posx > 10 - hp) x--; else x++; } else if(toupper(pos) == 'H'){ if(posy > 10 - hp) y--; else y++; } } for(int ctr = 0; ctr < Filled.size(); ctr++){ x_y = Filled.at(ctr); for(int ctr2 = 0; ctr2 < Chkpos.size(); ctr2++){ if(x_y.compare(Chkpos.at(ctr2)) == 0){ isValid = false; cout << "Position occupied! Try again.\n"; Chkpos.clear(); } } } }while(!isValid); Chkpos.clear(); char peg; cout << "Final choice? "; cin >> choice; if(toupper(choice) == 'Y') isFinal = true; for(short p_Ship = 0; p_Ship < hp; p_Ship++){ if(isFinal){ peg = '@'; } else peg = '_'; if(toupper(pos) == 'V'){ if(posx > 10 - hp) p_Grid[posx - p_Ship][posy] = peg; else p_Grid[posx + p_Ship][posy] = peg; } else if(toupper(pos) == 'H'){ if(posy > 10 - hp) p_Grid[posx][posy - p_Ship] = peg; else p_Grid[posx][posy + p_Ship] = peg; } } Display(p_Grid); }while(!isFinal); c_Ship->SetHits(posx, posy, hp, toupper(pos), Coords); Chkpos = c_Ship->Occupy(); for(int ctr = 0; ctr < hp; ctr++){ Filled.push_back(Chkpos.at(ctr)); } Chkpos.clear(); } //Shoot at coordinates void Player::Volley(grid Grid){ bool isValid = false, isFinal = false; char choice; do{ do{ cout << "Enter the coordinates to shoot at: "; isValid = GetCoord(); for(int ctr = 0; ctr < Shots.size(); ctr++){ if(Coords.compare(Shots.at(ctr)) == 0){ cout << "Shot has been fired previously! Try again.\n"; isValid = false; } } }while(!isValid); s_Grid[posx][posy] = 'o'; Display(s_Grid); cout << "Final choice? "; cin >> choice; if(toupper(choice) == 'Y'){ isFinal = true; if(Grid[posx][posy] == '@'){ Grid[posx][posy] = 'X'; s_Grid[posx][posy] = 'X'; Display(s_Grid); } else if(Grid[posx][posy] == '_'){ Grid[posx][posy] = 'O'; s_Grid[posx][posy] = '-'; Display(s_Grid); } } else{ s_Grid[posx][posy] = '_'; Display(s_Grid); } }while(!isFinal); Shots.push_back(Coords); } //Checks for the victory conditions. returns TRUE if all 5 Ships are sunk bool Player::Victory(short s_Sunk, grid c_Grid){ if(SunkCT == s_Sunk){ cout << "The enemy fleet has been DECIMATED!!!\n"; cout << "You have achieved a NAVAL VICTORY! Conratulations,"; cout << "Admiral " << P_Name << endl; Display(c_Grid); return true; } return false; }
true