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
1b0bde8213f11ee478549718cb224c89be6890fd
C++
Zaladim/Tek2_OOP
/OOP_arcade/lib/sdl/SDL.cpp
UTF-8
6,750
2.578125
3
[]
no_license
/* ** EPITECH PROJECT, 2019 ** ARCADE ** File description: ** SDL lib */ #include "SDL.hpp" extern "C" ILib *start() { return new SDL; } SDL::SDL() : ALib(), _run(false), _textColor({0, 255, 0}), _playerName("") { } SDL::~SDL() { } int SDL::run(std::vector<std::string> libs, std::vector<std::vector<int>> board, int score) { if (_main) { SDL_Event event; SDL_RenderClear (_mainRenderer); displayGame(board); _libs.render(_mainRenderer, 0, 5); if (score >= 0) _score = score; printScore(_score); printName(); SDL_RenderPresent(_mainRenderer); while(SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_ESCAPE: return (COMMAND_EXIT); case SDLK_LEFT: return (COMMAND_PREV_LIB); case SDLK_RIGHT: return (COMMAND_NEXT_LIB); case SDLK_UP: return COMMAND_NEXT_GAME; case SDLK_DOWN: return COMMAND_PREV_GAME; case SDLK_RETURN: return setName(); case SDLK_r: return COMMAND_PLAY; case SDLK_z: return COMMAND_UP; case SDLK_s: return COMMAND_DOWN; case SDLK_q: return COMMAND_LEFT; case SDLK_d: return COMMAND_RIGHT; case SDLK_SPACE: return COMMAND_ACTION; } } } } return COMMAND_CONTINUE; } int SDL::open(std::vector<std::string> libs) { if (TTF_Init() == -1) { fprintf(stderr,"Unable to initialize TTF (%s)\n",TTF_GetError()); return COMMAND_ERROR; } if (SDL_Init(SDL_INIT_VIDEO) != 0 ) { fprintf(stderr,"Unable to initialize SDL (%s)\n",SDL_GetError()); return COMMAND_ERROR; } _font = TTF_OpenFont("lib/sdl/font.ttf", 40); if (_font == NULL) { fprintf(stderr,"Unable to initialize TTF_font (%s)\n",TTF_GetError()); return COMMAND_ERROR; } SDL_GetCurrentDisplayMode(0, &_dm); _main = SDL_CreateWindow("Arcade", SDL_WINDOWPOS_UNDEFINED, \ SDL_WINDOWPOS_UNDEFINED, \ _dm.w, \ _dm.h, \ SDL_WINDOW_FULLSCREEN_DESKTOP); _mainRenderer = SDL_CreateRenderer(_main, -1, SDL_RENDERER_ACCELERATED); SDL_SetRenderDrawColor( _mainRenderer , 0, 0, 0, 0); printLib(libs); return (COMMAND_CONTINUE); } void SDL::close() { SDL_DestroyWindow(_main); SDL_Quit(); TTF_CloseFont(_font); TTF_Quit(); } void SDL::printLib(std::vector<std::string> libs) { std::string text; for (std::string &elem : libs) { elem = elem.erase(0, 13); elem = elem.substr(0, elem.size() - 3); text += "Thy Olde "; text += elem; text += " "; } _libs.loadFromText(_font, text, _textColor, _mainRenderer); } void SDL::printScore(int score) { _textScore = "Thy Olde Scoring : "; _textScore += std::to_string(score); _scoring.loadFromText(_font, _textScore, _textColor, _mainRenderer); _scoring.render(_mainRenderer, _dm.w - (_textScore.length() * 15), _dm.h - 40); _score = score; } int SDL::setName() { bool writing = true; SDL_Event event; SDL_StartTextInput(); while (writing) { while (SDL_PollEvent(&event) != 0) { if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_BACKSPACE && _playerName.length() > 0) { _playerName.pop_back(); } else if (event.key.keysym.sym == SDLK_RETURN) { writing = false; }else if (event.key.keysym.sym == SDLK_ESCAPE) { return COMMAND_EXIT; } } else if (event.type == SDL_TEXTINPUT) { _playerName += event.text.text; } } SDL_RenderClear(_mainRenderer); _libs.render(_mainRenderer, 0, 5); printScore(_score); printName(); displayPause(); SDL_RenderPresent(_mainRenderer); } return COMMAND_CONTINUE; } void SDL::printName() { _name.loadFromText(_font, "Thy Olde Name : " + _playerName, _textColor, _mainRenderer); _name.render(_mainRenderer, 0, _dm.h - 40); } void SDL::displayGame(std::vector<std::vector<int>> board) { SDL_Rect gTileClips[TOTAL_TILE_SPRITES]; //Tiles Texture Texture tileTexture; //Tile offsets int x = 0; int y = 0; //Tiles number int tilesNB = board.size() * board[0].size(); Tile *tiles[board.size()][board[0].size()]; for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[0].size(); j++) { tiles[i][j] = new Tile(x, y, board[i][j]); x += TILE_WIDTH; } x = 0; y += TILE_HEIGHT; } gTileClips[ TILE_RED ].x = 0; gTileClips[ TILE_RED ].y = 0; gTileClips[ TILE_RED ].w = TILE_WIDTH; gTileClips[ TILE_RED ].h = TILE_HEIGHT; gTileClips[ TILE_GREEN ].x = 0; gTileClips[ TILE_GREEN ].y = 40; gTileClips[ TILE_GREEN ].w = TILE_WIDTH; gTileClips[ TILE_GREEN ].h = TILE_HEIGHT; gTileClips[ TILE_BLUE ].x = 0; gTileClips[ TILE_BLUE ].y = 80; gTileClips[ TILE_BLUE ].w = TILE_WIDTH; gTileClips[ TILE_BLUE ].h = TILE_HEIGHT; gTileClips[ TILE_TOPLEFT ].x = 40; gTileClips[ TILE_TOPLEFT ].y = 0; gTileClips[ TILE_TOPLEFT ].w = TILE_WIDTH; gTileClips[ TILE_TOPLEFT ].h = TILE_HEIGHT; gTileClips[ TILE_LEFT ].x = 40; gTileClips[ TILE_LEFT ].y = 40; gTileClips[ TILE_LEFT ].w = TILE_WIDTH; gTileClips[ TILE_LEFT ].h = TILE_HEIGHT; gTileClips[ TILE_BOTTOMLEFT ].x = 40; gTileClips[ TILE_BOTTOMLEFT ].y = 80; gTileClips[ TILE_BOTTOMLEFT ].w = TILE_WIDTH; gTileClips[ TILE_BOTTOMLEFT ].h = TILE_HEIGHT; gTileClips[ TILE_TOP ].x = 80; gTileClips[ TILE_TOP ].y = 0; gTileClips[ TILE_TOP ].w = TILE_WIDTH; gTileClips[ TILE_TOP ].h = TILE_HEIGHT; gTileClips[ TILE_CENTER ].x = 80; gTileClips[ TILE_CENTER ].y = 40; gTileClips[ TILE_CENTER ].w = TILE_WIDTH; gTileClips[ TILE_CENTER ].h = TILE_HEIGHT; gTileClips[ TILE_BOTTOM ].x = 80; gTileClips[ TILE_BOTTOM ].y = 80; gTileClips[ TILE_BOTTOM ].w = TILE_WIDTH; gTileClips[ TILE_BOTTOM ].h = TILE_HEIGHT; gTileClips[ TILE_TOPRIGHT ].x = 120; gTileClips[ TILE_TOPRIGHT ].y = 0; gTileClips[ TILE_TOPRIGHT ].w = TILE_WIDTH; gTileClips[ TILE_TOPRIGHT ].h = TILE_HEIGHT; gTileClips[ TILE_RIGHT ].x = 120; gTileClips[ TILE_RIGHT ].y = 40; gTileClips[ TILE_RIGHT ].w = TILE_WIDTH; gTileClips[ TILE_RIGHT ].h = TILE_HEIGHT; gTileClips[ TILE_BOTTOMRIGHT ].x = 120; gTileClips[ TILE_BOTTOMRIGHT ].y = 80; gTileClips[ TILE_BOTTOMRIGHT ].w = TILE_WIDTH; gTileClips[ TILE_BOTTOMRIGHT ].h = TILE_HEIGHT; tileTexture.loadFromFile("lib/sdl/tiles.png", _mainRenderer); for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[0].size(); j++) { tiles[i][j]->render(_mainRenderer, &tileTexture, _dm, gTileClips, board.size()*TILE_WIDTH, board[0].size()*TILE_HEIGHT); } } } void SDL::displayPause() { std::string pause = "Thy Olde Pause"; _name.loadFromText(_font, pause, _textColor, _mainRenderer); _name.render(_mainRenderer, (_dm.w - (pause.length() * 15)) / 2, (_dm.h / 2)); }
true
b97241a252d1e675fcf374531bc54b4d062485f5
C++
woosungkim/Memgorithm
/MEMGORITHM/331_Gseries.cpp
UHC
656
2.859375
3
[]
no_license
///* // //VCPP, GPP // //*/ // //#include <iostream> //using namespace std; //int main() //{ // // int nCount; /* ׽Ʈ ̽ */ // // cin >> nCount; /* ׽Ʈ ̽ Է */ // // for (int itr = 0; itr<nCount; itr++) // { // // cout << "#testcase" << (itr + 1) << endl; // // /* // // ˰  κ // // */ // int n; // cin >> n; // // int sum = 0; // int cnt = 1; // int goonNum = 1; // // for (int i = 1; i <= n; i++) // for (int j = 1; j <= i; j++) // sum += j; // // cout << sum << endl; // // } // // return 0; /* ݵ return 0 ּžմϴ. */ // //}
true
9064fcc0576e8ff942a622ba77c2064b3710aeb8
C++
garrettbolen/CPSC350_A3
/GenStack.h
UTF-8
550
3.171875
3
[]
no_license
#include <iostream> using namespace std; //ensures that the header file is only included once at runtime #pragma once template <typename type> class GenStack{ public: GenStack(); // default constructor GenStack(int maxSize); // overloaded constructor ~GenStack(); // destructor //core funtions void push(type data); // insert an item type pop(); // remove //auxiliary/helper functions type peek(); // aka, top() bool isEmpty(); bool isFull(); int top; int mSize; type* myArray; //memory address of the first block };
true
27bfee2a246d4cfd2ed008bb1c69f45ceee37261
C++
takata-daiki/algorithms
/monoids/affine.hpp
UTF-8
358
2.84375
3
[ "MIT" ]
permissive
#pragma once #include <bits/stdc++.h> using namespace std; template <typename T> struct affine_monoid { using P = pair<T, T>; using value_type = P; P identity() { return make_pair(T(1), T(0)); } P merge(P a, P b) { T fst = a.first * b.first; T snd = a.second * b.first + b.second; return make_pair(fst, snd); } };
true
9daf3cc438bd14854d688189ef52f89dfe0a32a8
C++
pilgujeong10/Programmers
/DFS1.cpp
UTF-8
465
2.6875
3
[]
no_license
#include<iostream> using namespace std; int map[30][30]; int ch[30]; int cnt=0,n; void DFS(int v) { int i; if (v == n) { cnt++; } else { for (i = 1; i <= n; i++) { if (map[v][i] == 1 && ch[i] == 0) { ch[i] = 1; DFS(i); ch[i] = 0; } } } } int main() { int m, i, a, b; cin >> n >> m; for (i = 0; i < m; i++) { cin >> a >> b; map[a][b] = 1; } ch[1] = 1; DFS(1); cout << cnt; return 0; }
true
5396174ca68e933c3560d029caed308adcc057fd
C++
olga-kuriatnyk/CSS342
/Exercises/MyCasino/CardDeck.h
UTF-8
400
2.671875
3
[]
no_license
#pragma once #include "Card.h" const int kCardsInDeck = 52; class CardDeck { public: CardDeck(); void Shuffle(); bool Cut(int num_cards); int CardsRemaing() const; Card Deal(); bool ReturnCard(const Card& the_card); bool Contains(const Card& the_card) const; // cost because no change bool RemoveCard(const Card& the_card); private: Card deck[kCardsInDeck]; };
true
258ddc568034024c64c736537f05030603a62ded
C++
sksingh55/code
/algorithms/largest_power.cpp
UTF-8
1,298
2.984375
3
[]
no_license
//largest power of number with is greater than n #include <bits/stdc++.h> #define vec vector< long long int> #define vecp vector < pair< long long int ,long long int> > #define pb push_back #define f(i,a,b) for(long long int i=a;i<b;i++) #define tc long long int t; cin>>t; while(t--) #define mp make_pair using namespace std; typedef long long int ll; void SieveOfEratosthenes(int n,bool prime[]) { memset(prime, true, n); for (int p=2; p*p<=n; p++) { if (prime[p] == true) { for (int i=p*2; i<=n; i += p) prime[i] = false; } } } ll xorPairCount(ll arr[], ll n, ll x)//xor pair count with value x { int result = 0; unordered_map<ll, ll> m; for (ll i=0; i<n ; i++) { ll curr_xor = x^arr[i]; if (m.find(curr_xor) != m.end()) result += m[curr_xor]; m[arr[i]]++; } return result; } ll gcd(ll a, ll b) { if(a==0) return b; return gcd(b%a, a); } ll lcm(ll a, ll b) { return (a*b)/gcd(a, b); } ll largest_power(ll n) { n = n|(n>>1); n = n|(n>>2); n = n|(n>>4); n = n|(n>>8); return ((n+1)>>1); } int main() { ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); ll n; cin >>n; cout<<largest_power(n); }
true
c28e4c844e83297826e199caa4d6424ce4cbbcd3
C++
dchudik/GuapPractice2019
/Lab1/Task1/mainwindow.cpp
UTF-8
775
2.59375
3
[]
no_license
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_printResult_clicked() { QString distance = ui->distance->text(); QString time = ui->time->text(); QString speed; float Fdistance = distance.toFloat(); float Ftime = time.toFloat(); float Fspeed; Fspeed = Fdistance/Ftime; QString result; distance.setNum(Fdistance); time.setNum(Ftime); speed.setNum(Fspeed); result = "Дистанция: " + distance + " м" + "\n" + "Время: " + time + " с" + "\n" + "Скорость: " + speed + " м/c"; ui->resultLabel->setText(result); }
true
ba367060a1d7c4620e91a7b269b82c39000e10d4
C++
qiminglu/s2-mini
/src/synergia/foundation/reference_particle.h
UTF-8
4,167
3.140625
3
[]
no_license
#ifndef REFERENCE_PARTICLE_H_ #define REFERENCE_PARTICLE_H_ #include "synergia/utils/multi_array_typedefs.h" #include "synergia/foundation/four_momentum.h" /// Reference_particle stores the four momentum of the reference frame /// with respect to the lab frame (defined to be along the axis of the /// accelerator) as well as the six-dimensional state vector of the the /// reference particle in the reference frame. Reference particle /// also keeps track of the total path length of the reference particle /// trajectory. class Reference_particle { private: int charge; Four_momentum four_momentum; MArray1d state; int repetition; double s; double s_n; public: /// Default constructor for internal use only Reference_particle(); /// Construct a Reference_particle with a given mass and total energy. /// @param mass in GeV/c^2 /// @param charge in units of e /// @param total_energy in GeV in the lab frame Reference_particle(int charge, double mass, double total_energy); /// Construct a Reference_particle with a given four momentum. /// @param charge in units of e /// @param four_momentum in the lab frame Reference_particle(int charge, Four_momentum const& four_momentum); /// Construct a Reference_particle with a given four momentum and state /// in the reference frame. /// @param charge in units of e /// @param four_momentum in the lab frame /// @param state is a six-dimensional state vector Reference_particle(int charge, Four_momentum const& four_momentum, Const_MArray1d_ref state); /// Set the four momentum. /// @param four_momentum in the lab frame void set_four_momentum(Four_momentum const& four_momentum); /// Set the state vector in the reference frame. /// @param state is a six-dimensional state vector void set_state(Const_MArray1d_ref state); /// Set the state vector in the reference frame. /// @param x /// @param xp /// @param y /// @param yp /// @param cdt /// @param dpop void set_state(double x, double xp, double y, double yp, double cdt, double dpop); /// Set the total energy. /// @param total_energy in GeV in the lab frame void set_total_energy(double total_energy); /// Increment the trajectory length. /// @param length in m void increment_trajectory(double length); /// Start a new repetition void start_repetition(); /// Manually set trajectory parameters /// @param repetition starting at 0 /// @param repetition_length in m /// @param s in m void set_trajectory(int repetition, double repetition_length, double s); /// Return the Reference_particle charge in units of e int get_charge() const; /// Return the Reference_particle mass in units of GeV/c double get_mass() const; /// Get the four momentum in the lab frame. Four_momentum const & get_four_momentum() const; /// Get the six-dimensional state vector in the reference frame. Const_MArray1d_ref get_state() const; /// Get the relativistic beta in the lab frame. double get_beta() const; /// Get the relativistic gamma in the lab frame. double get_gamma() const; /// Get the momentum in GeV/c in the lab frame. double get_momentum() const; /// Get the total energy in GeV in the lab frame. double get_total_energy() const; /// Get the total path length in m of the reference /// particle trajectory double get_s() const; /// Get the distance traveled in m since the beginning /// of the current repetition. double get_s_n() const; /// Get the number of repetition. int get_repetition() const; /// Get the repetition length in m. double get_repetition_length() const; /// Check equality to the given tolerance /// @param reference_particle another Reference_particle /// @param tolerance fractional accuracy bool equal(Reference_particle const& reference_particle, double tolerance) const; }; #endif /* REFERENCE_PARTICLE_H_ */
true
bfbc11ebe7cb522fece60e655c3bc3b0f4646b4b
C++
TheSilverCrow/Face_Recogintion_Arduino
/feb9.ino
UTF-8
443
2.6875
3
[]
no_license
void setup() { Serial.begin(9600); //initialize serial COM at 9600 baudrate pinMode(13, OUTPUT); //make the LED pin (13) as output digitalWrite (13, HIGH); } void loop() { if (Serial.available()) { Serial.print(Serial.read()); switch( Serial.read()) { case 0 : digitalWrite(13,HIGH); break; default: digitalWrite(13,LOW); break; } } }
true
e2a6f1fa056df96a7fca6b9d27606dc22221742a
C++
vaddya/operating-systems
/lab4/src/task5/task5.cpp
UTF-8
1,473
2.921875
3
[]
no_license
#include <windows.h> #include <iostream> using std::cout; using std::endl; DWORD WINAPI threadHandler(LPVOID); struct Params { int num; bool *runFlag; }; void printTime() { SYSTEMTIME now; GetSystemTime(&now); cout << "System Time " << now.wHour << ":" << now.wMinute << ":" << now.wSecond << endl; } int main(int argc, char *argv[]) { int threads = argc < 3 ? 2 : atoi(argv[1]); int stop = argc < 3 ? 5000 : atoi(argv[2]); DWORD targetThreadId; bool runFlag = true; __int64 end_time = -1 * stop * 10000000; LARGE_INTEGER end_time2; end_time2.LowPart = (DWORD) (end_time & 0xFFFFFFFF); end_time2.HighPart = (LONG) (end_time >> 32); HANDLE tm1 = CreateWaitableTimer(NULL, false, NULL); SetWaitableTimer(tm1, &end_time2, 0, NULL, NULL, false); for (int i = 0; i < threads; i++) { Params *param = (Params *) malloc(sizeof(Params)); param->num = i; param->runFlag = &runFlag; HANDLE t1 = CreateThread(NULL, 0, threadHandler, param, 0, &targetThreadId); CloseHandle(t1); } printTime(); WaitForSingleObject(tm1, INFINITE); runFlag = false; CloseHandle(tm1); printTime(); return 0; } DWORD WINAPI threadHandler(LPVOID arg) { Params params = *((Params *) arg); while (true) { Sleep(1000); cout << params.num << " "; if (!*(params.runFlag)) { break; } } cout << endl; return 0; }
true
bc50d56c3700a4c7feda629f803bd9db7794526b
C++
olvap/cellphone_alarm
/cellphone.ino
UTF-8
1,174
2.703125
3
[]
no_license
#include <SoftwareSerial.h> #define RX 8 #define TX 9 #define LED 13 #define SENSOR 12 const char* cellphone_number = "543425091329"; SoftwareSerial mySerial(RX, TX); void EnviaSMS(const char* message){ mySerial.println("AT+CMGF=1"); // Activamos la funcion de envio de SMS delay(100); mySerial.print("AT+CMGS=\""); mySerial.print(cellphone_number); // Definimos el numero del destinatario en formato internacional mySerial.println("\""); delay(100); mySerial.print(message); delay(500); mySerial.print(char(26)); // Enviamos el equivalente a Control+Z delay(100); mySerial.println(""); delay(100); } void llamar(){ digitalWrite(LED,0); mySerial.print("ATD+"); //Comando AT para realizar una llamada mySerial.print(cellphone_number); mySerial.println(";"); delay(15000); mySerial.println("ATH"); // Cuelga la llamada delay(60000); digitalWrite(LED,1); } void setup(){ pinMode(LED, OUTPUT); pinMode(SENSOR, INPUT); digitalWrite(LED,0); mySerial.begin(9600); delay(10000); digitalWrite( LED,1); } void loop(){ if(digitalRead(SENSOR) == LOW){ llamar(); } }
true
96bd89ecb388b6810cccec6183b2c4f6e0382fa8
C++
lizhengdao/Eliminate_Pests
/Classes/QSprite.cpp
GB18030
572
2.5625
3
[]
no_license
#include "QSprite.h" QE_SINGLETON_CPP(QSprite); Sprite* QSprite::createBgSprite() { return createBgSprite("bg.png"); } Sprite* QSprite::createBgSprite(const std::string& filename) { //ȡڴС Size size = Director::getInstance()->getWinSize(); // Sprite* bg = Sprite::create(filename); // float scaleX = size.width / bg->getContentSize().width; float scaleY = size.height / bg->getContentSize().height; bg->setScale(scaleX, scaleY); //λ bg->setPosition(Vec2(size.width / 2, size.height / 2)); return bg; }
true
88eb2e3a8d00bcfecd0c8cd9eba78603b425687b
C++
sym233/leetcode_problems
/41. First Missing Positive/41. First Missing Positive.cpp
UTF-8
877
2.9375
3
[]
no_license
auto indexOf = [](vector<int>& v, int val, int from = 0) -> int { for (int i = from; i < v.size(); i++) { if (v[i] == val) { return i; } } return -1; }; class Solution { public: int firstMissingPositive(vector<int>& nums) { int l = nums.size(); int comp = 0; while (comp < l) { if (nums[comp] == comp + 1) { comp++; continue; } int ind = indexOf(nums, comp + 1, comp); if (ind == -1) { return comp + 1; } swap(nums[ind], nums[comp]); while (comp < ind && ind < l && nums[ind] != ind && nums[comp] < nums[ind] && nums[ind] < l) { swap(nums[ind], nums[nums[ind]]); ind = nums[ind]; } } return l + 1; } };
true
0b804b3cfd54e2192d36ffb3c67108b59066da39
C++
nesjett/TheEricsJourney
/src/private/Actor.cpp
UTF-8
4,354
2.671875
3
[ "MIT" ]
permissive
#include "Actor.h" #include <game.h> Actor::Actor() { //std::cout << "New actor created" << std::endl; setActorLocation(Vector2f(0.f,0.f)); //setBoundingBox( sf::IntRect( 0, 0, 0, 0 ) ); // Init bounding box to 0 oType = worldstatic; asleep = false; debug = false; if(debug){ font.loadFromFile("./resources/arial.ttf"); } } void Actor::Init(){ } void Actor::Update(float delta){ // Check for collisions here in the parent? game *gi = game::Instance(); // CHECK PENDING DESTROY if(lifeSpan >= 0.f && gi->getTime() >= lifeSpan) { pendingDelete = true; } } void Actor::Draw(double percent, double delta ){ if(!sprite) { return; } if(asleep) { currentLoc = getActorLocation(); // we have to draw the collision debuggin, but without moving } else { currentLoc = sprite->Draw(getActorLocation(), getActorLastLocation(), percent); // Location of sprite during interpolation } if(currentLoc.x == location.x && currentLoc.y == location.y) { setActorLocation(location); } if(!debug){ return; } FloatRect globalBounds = getBoundingBox(); sf::RectangleShape rect( Vector2f(globalBounds.width,globalBounds.height) ); // Show actor bounding box rect.setPosition(globalBounds.left,globalBounds.top); rect.setFillColor(sf::Color(0,0,0,0)); rect.setOutlineThickness(1.3); rect.setOutlineColor(sf::Color(250, 0, 0)); // Show actor location sf::CircleShape circ( 6.0, 10.0 ); circ.setPosition(currentLoc.x-6,currentLoc.y-6); circ.setFillColor(sf::Color(0,250,0)); circ.setOutlineColor(sf::Color(0, 250, 0)); // Show actor location coords sf::Text text; text.setString("(" + std::to_string(currentLoc.x) + "x, " + std::to_string(currentLoc.y) + "y)"); text.setFont(font); text.setCharacterSize(12); text.setColor(sf::Color::Green); text.setStyle(sf::Text::Regular); text.setPosition(currentLoc.x+10, currentLoc.y+10); // We add a small offset // Show actor bounding box data sf::Text text_bounding; text_bounding.setString("(" + std::to_string(globalBounds.left) + "x, " + std::to_string(globalBounds.top) + "y, " + std::to_string(globalBounds.width) + "w, " + std::to_string(globalBounds.height) +"h)"); text_bounding.setFont(font); text_bounding.setCharacterSize(12); text_bounding.setColor(sf::Color::Red); text_bounding.setStyle(sf::Text::Regular); text_bounding.setPosition(globalBounds.left, globalBounds.top-15); // We add a small offset // Show actor bounding bottom right corner sf::Text text_bounding_corner; text_bounding_corner.setString("(" + std::to_string(globalBounds.left+globalBounds.width) + "x, " + std::to_string(globalBounds.top+globalBounds.height) + "y)"); text_bounding_corner.setFont(font); text_bounding_corner.setCharacterSize(12); text_bounding_corner.setColor(sf::Color::Red); text_bounding_corner.setStyle(sf::Text::Regular); text_bounding_corner.setPosition(globalBounds.left+globalBounds.width, globalBounds.top+globalBounds.height); // We add a small offset // Show bounding bottom right corner location sf::CircleShape circ_bounding( 4.0, 7.0 ); circ_bounding.setPosition(globalBounds.left+globalBounds.width-4,globalBounds.top+globalBounds.height-4); circ_bounding.setFillColor(sf::Color::Red); circ_bounding.setOutlineColor(sf::Color::Red); Engine *eng = Engine::Instance(); eng->getApp().draw(rect); // bounding box eng->getApp().draw(circ); // actor location if(debug_coords) { eng->getApp().draw(text); // actor location eng->getApp().draw(text_bounding); // actor bounding box data eng->getApp().draw(text_bounding_corner); // actor bounding box corner location eng->getApp().draw(circ_bounding); // actor bounding box corner location point } } void Actor::TakeDamage(float damage, Actor* dmgCauser, string damage_type){ } void Actor::OnActorOverlap(Actor *otherActor){ } Actor::~Actor(){ delete sprite; } Vector2f Actor::getInterpolatedPos() { return currentLoc; } void Actor::setLifespan(float secs) { sf::Time t1 = sf::seconds(secs); game *gi = game::Instance(); long gameTime = gi->getTime(); lifeSpan = gi->getTime() + t1.asMilliseconds(); // Define exact time at which the actor should be destroyed //std::cout << "Game time: " << gameTime << " Destroy time: " << lifeSpan << std::endl; }
true
96dfa661464b3f32ec940ed227ff9f03a6d98f4c
C++
NickLennonLiu/cpp
/qt/snake/snake.h
UTF-8
936
2.65625
3
[]
no_license
#ifndef SNAKE_H #define SNAKE_H #include <QObject> #include "utils.h" class SnakePart { public: SnakePart(); SnakePart(coord pos, SnakePart *next = 0); //int getX() const {return pos.x;} //int getY() const {return pos.y;} coord getPos() const { return pos; } SnakePart *nextPart() const { return next; } void setNext(SnakePart *next); private: coord pos; SnakePart *next; }; class Snake : public QObject { Q_OBJECT public: explicit Snake(coord bodycoord[], int len, QObject *parent = nullptr, int dir = 0); ~Snake(); int getGrowStatus() const { return growStatus; } signals: void snakeMoved(coord); void snakeRetracted(coord); public slots: coord retract(); coord move(); void chgDirection(int); void setGrowStatus(int); private: SnakePart *body[1601], *tail, *head; int direction; int length; int growStatus; }; #endif // SNAKE_H
true
065494b7ccb6034e1d9fc03a80cc748e42073de9
C++
evga7/Practice_Algorithm_01
/BOJ_5430.cpp
UTF-8
1,295
2.59375
3
[]
no_license
#include <iostream> #include <string> #include <stack> #include <algorithm> #include <vector> #include <list> #include <queue> #include<deque> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int T; cin >> T; int i, N; while (T--) { string p; cin >> p >> N; int num=0; int flag = 0; string str; cin >> str; int R_cnt = 0; deque<int>dq; int len = str.size(); for (i =1; i < len; i++) { if (str[i] == ','||str[i]==']') { if (num!=0) dq.push_back(num); num = 0; } if (num > 0) num = num * 10 + (str[i] - '0'); else num = str[i] -'0'; } len = p.size(); for (i = 0; i <len; i++) { if (p[i] == 'R') { R_cnt++; } else { if (dq.empty()) { flag = 1; break; } else { if (R_cnt > 0 && R_cnt % 2) dq.pop_back(); else dq.pop_front(); } } } if (flag) cout << "error\n"; else if (dq.empty()) { cout << "[]\n"; } else { cout << '['; len = dq.size(); if (R_cnt % 2 == 1) { for (i=len-1;i>0;i--) cout << dq[i] << ','; cout << dq[i] << "]\n"; } else { for (i = 0; i < len - 1; i++) cout << dq[i] << ','; cout << dq[i] << "]\n"; } } } }
true
b4760dcd1e66a11751ee53cc8ff5202ebd9ab2f2
C++
catboost/catboost
/util/generic/serialized_enum_ut.cpp
UTF-8
4,960
2.578125
3
[ "Apache-2.0" ]
permissive
#include "serialized_enum.h" #include <library/cpp/testing/unittest/registar.h> #include <util/generic/deque.h> #include <util/generic/map.h> #include <util/generic/typelist.h> #include <util/generic/vector.h> Y_UNIT_TEST_SUITE(TestSerializedEnum) { Y_UNIT_TEST(RepresentationTypes) { using namespace NEnumSerializationRuntime::NDetail; static_assert(TIsPromotable<int, int>::value, "int -> int"); static_assert(TIsPromotable<char, int>::value, "char -> int"); static_assert(TIsPromotable<unsigned short, unsigned long>::value, "unsigned short -> unsigned long"); static_assert(TIsPromotable<i64, long long>::value, "i64 -> long long"); static_assert(!TIsPromotable<ui64, ui8>::value, "ui64 -> ui8"); static_assert(!TIsPromotable<i64, short>::value, "i64 -> short"); enum EEmpty { }; UNIT_ASSERT_C((TTypeList<int, unsigned>::THave<typename TSelectEnumRepresentationType<EEmpty>::TType>::value), "empty enum using signed or unsigned integer underlying type"); using TRepresentationTypeList = TTypeList<int, unsigned, long long, unsigned long long>; enum class ERegular { One = 1, Two = 2, Five = 5, }; UNIT_ASSERT(TRepresentationTypeList::THave<typename TSelectEnumRepresentationType<ERegular>::TType>::value); enum class ESmall: unsigned char { Six = 6, }; UNIT_ASSERT(TRepresentationTypeList::THave<typename TSelectEnumRepresentationType<ESmall>::TType>::value); enum class EHugeUnsigned: ui64 { Value = 0, }; UNIT_ASSERT(TRepresentationTypeList::THave<typename TSelectEnumRepresentationType<EHugeUnsigned>::TType>::value); enum class EHugeSigned: i64 { Value = -2, }; UNIT_ASSERT(TRepresentationTypeList::THave<typename TSelectEnumRepresentationType<EHugeSigned>::TType>::value); } Y_UNIT_TEST(MappedArrayView) { enum class ETestEnum: signed char { Zero = 0, One = 1, Two = 2, Three = 3, Four = 4, Eleven = 11, }; const TVector<int> values = {1, 2, 3, 0, 0, 0, 11, 0, 0, 0, 0, 0, 2}; const auto view = ::NEnumSerializationRuntime::TMappedArrayView<ETestEnum>{values}; UNIT_ASSERT_VALUES_EQUAL(view.size(), values.size()); UNIT_ASSERT_VALUES_EQUAL(view.empty(), false); UNIT_ASSERT_EQUAL(*view.begin(), ETestEnum::One); UNIT_ASSERT_EQUAL(view[6], ETestEnum::Eleven); UNIT_ASSERT_EXCEPTION(view.at(-1), std::out_of_range); UNIT_ASSERT_VALUES_EQUAL(sizeof(view[4]), sizeof(signed char)); UNIT_ASSERT_VALUES_EQUAL(sizeof(values[4]), sizeof(int)); for (const ETestEnum e : view) { UNIT_ASSERT_UNEQUAL(e, ETestEnum::Four); } const TVector<ETestEnum> typedValues = {ETestEnum::One, ETestEnum::Two, ETestEnum::Three, ETestEnum::Zero, ETestEnum::Zero, ETestEnum::Zero, ETestEnum::Eleven, ETestEnum::Zero, ETestEnum::Zero, ETestEnum::Zero, ETestEnum::Zero, ETestEnum::Zero, ETestEnum::Two}; UNIT_ASSERT_EQUAL(typedValues, view.Materialize()); const TDeque<ETestEnum> typedValuesDeque{typedValues.begin(), typedValues.end()}; UNIT_ASSERT_EQUAL(typedValuesDeque, view.Materialize<TDeque>()); } Y_UNIT_TEST(MappedDictView) { enum class ETestEnum: unsigned short { Zero = 0, One = 1, Two = 2, Three = 3, Four = 4, Eleven = 11, Fake = (unsigned short)(-1), }; const TMap<unsigned, unsigned> map = {{0, 1}, {1, 2}, {2, 4}, {3, 8}, {4, 16}, {11, 2048}}; const auto view = ::NEnumSerializationRuntime::NDetail::TMappedDictView<ETestEnum, unsigned, unsigned, decltype(map)>{map}; UNIT_ASSERT_VALUES_EQUAL(view.size(), map.size()); UNIT_ASSERT_VALUES_EQUAL(map.empty(), false); UNIT_ASSERT_EQUAL(view.begin()->first, ETestEnum::Zero); UNIT_ASSERT_VALUES_EQUAL(view.begin()->second, 1u); UNIT_ASSERT_VALUES_EQUAL(view.contains(ETestEnum::Fake), false); UNIT_ASSERT_VALUES_EQUAL(view.contains(ETestEnum::Four), true); UNIT_ASSERT_EXCEPTION(view.at(ETestEnum::Fake), std::out_of_range); UNIT_ASSERT_NO_EXCEPTION(view.at(ETestEnum::Eleven)); UNIT_ASSERT_VALUES_EQUAL(view.at(ETestEnum::Three), 8u); unsigned mask = 0; unsigned sum = 0; for (const auto e : view) { mask |= e.second; sum += e.second; } UNIT_ASSERT_VALUES_EQUAL(mask, 2079); UNIT_ASSERT_VALUES_EQUAL(sum, 2079); const TMap<ETestEnum, unsigned> materialized = view.Materialize<TMap>(); UNIT_ASSERT_VALUES_EQUAL(materialized.size(), map.size()); UNIT_ASSERT_VALUES_EQUAL(materialized.at(ETestEnum::Four), 16); } }
true
477926489d42afbd34cd87be8496a0b294a07c67
C++
hisyamsk/tlx-toki
/pemrogaman-dasar/11 Pendalaman String/11_f.cpp
UTF-8
390
2.984375
3
[]
no_license
#include <iostream> #include <string> #include <cmath> using namespace std; int main() { string s; cin >> s; for (int i = 0; i < s.length(); i++) { if ((int) s[i] == 95) { s.erase(i, 1); s[i] = (char) ((int) s[i] - 32); } else if ((int) s[i] > 64 && (int) s[i] < 91) { s[i] = (char) ((int) s[i] + 32); s.insert(i, "_"); } } cout << s << endl; }
true
2299e711e2a35faa1677761e7578fcb001833237
C++
WIEQLI/stratton-chu-cpp
/cpp/stratton-chu-library/src/distorted-surface.cpp
UTF-8
3,738
2.9375
3
[ "BSD-2-Clause" ]
permissive
#include "stratton-chu/distorted-surface.hpp" #include <boost/math/special_functions/legendre.hpp> using namespace boost::math; double legendre(int num, double arg) { if (arg > 1.0) return legendre_p(num, 1.0); if (arg < -1.0) return legendre_p(num, -1.0); return legendre_p(num, arg); } double legendre_derivative(int num, double arg) { if (arg > 1.0) return 0.0; if (arg < -1.0) return 0.0; return legendre_p_prime(num, arg); } SurfaceDistortionHarmonic::SurfaceDistortionHarmonic( const ISurface& pure_surface, const Vector& v, const std::vector<DistortionHarmonic>& harmonics) : // v - unit vector m_pure_surface(pure_surface), m_harmonics(harmonics), m_v(v) {} Position SurfaceDistortionHarmonic::point(const Vector2D& pos) const { Position result = m_pure_surface.point(pos); for (size_t i = 0; i < m_harmonics.size(); i++) { double shift = m_harmonics[i].ampl * cos(m_harmonics[i].kx * pos[0] + m_harmonics[i].ky * pos[1]); Vector delta = m_v * shift; result += delta; } return result; } Vector SurfaceDistortionHarmonic::tau1(const Vector2D& pos) const { Vector result = m_pure_surface.tau1(pos); for (size_t i = 0; i < m_harmonics.size(); i++) { double shift = - m_harmonics[i].ampl * m_harmonics[i].kx * sin(m_harmonics[i].kx * pos[0] + m_harmonics[i].ky * pos[1]); Vector delta = m_v * shift; result += delta; } return result; } Vector SurfaceDistortionHarmonic::tau2(const Vector2D& pos) const { Vector result = m_pure_surface.tau2(pos); for (size_t i = 0; i < m_harmonics.size(); i++) { double shift = - m_harmonics[i].ampl * m_harmonics[i].ky * sin(m_harmonics[i].kx * pos[0] + m_harmonics[i].ky * pos[1]); Vector delta = m_v * shift; result += delta; } return result; } SurfaceDistortionLegendre::DistortionPolinom::DistortionPolinom(double ampl, double alpha, int number) : ampl(ampl), direction(cos(alpha), sin(alpha)), number(number) { } SurfaceDistortionLegendre::SurfaceDistortionLegendre( const ISurface& pure_surface, const Vector& v, double radius, Vector2D center, const std::vector<DistortionPolinom>& harmonics) : // v - unit vector m_pure_surface(pure_surface), m_harmonics(harmonics), m_v(v), m_center(center), m_radius(radius) { } Position SurfaceDistortionLegendre::point(const Vector2D& pos) const { Position result = m_pure_surface.point(pos); for (size_t i = 0; i < m_harmonics.size(); i++) { double shift = m_harmonics[i].ampl * legendre(m_harmonics[i].number, m_harmonics[i].direction * (pos - m_center) / m_radius); Vector delta = m_v * shift; result += delta; } return result; } Vector SurfaceDistortionLegendre::tau1(const Vector2D& pos) const { Vector result = m_pure_surface.tau1(pos); for (size_t i = 0; i < m_harmonics.size(); i++) { double shift = m_harmonics[i].ampl * m_harmonics[i].direction[0] / m_radius * legendre_derivative(m_harmonics[i].number, m_harmonics[i].direction * (pos - m_center) / m_radius); Vector delta = m_v * shift; result += delta; } return result; } Vector SurfaceDistortionLegendre::tau2(const Vector2D& pos) const { Vector result = m_pure_surface.tau2(pos); for (size_t i = 0; i < m_harmonics.size(); i++) { double shift = m_harmonics[i].ampl * m_harmonics[i].direction[1] / m_radius * legendre_derivative(m_harmonics[i].number, m_harmonics[i].direction * (pos - m_center) / m_radius); Vector delta = m_v * shift; result += delta; } return result; }
true
626110d9d8eb77fed20cae6745aa15c0958e3ff0
C++
kammitama5/AdvancedCpp
/Midterm_V2/Midterm_v2/Semester.h
UTF-8
636
2.5625
3
[]
no_license
#ifndef SEMESTER_ #define SEMESTER_ #include "Date.h" #include "Course.h" #include "CourseSchedule.h" #include "Semester.h" using std::ostream; using std::istream; class Semester{ friend istream &operator>>(istream &, const Semester &); // overload >> private: std::string semesterName; Date startDate; Date endDate; public: // not sure if this is correct, but... //SA, Date dateStart, Date dateEnd; void printSemester(); std::string getSemesterName(); Date getStartDate; std::string setSemesterName(); void setStartDate(int, int, int); void setEndDate(int, int, int); }; #endif
true
5face6c3f87d211bbb2a9f047e336c1dff974e04
C++
Spicy-Noodles-Studio/Ultimate-Ghost-Punch
/UltimateGhostPunch/Src/CameraEffects.h
UTF-8
820
2.578125
3
[ "CC-BY-4.0" ]
permissive
#pragma once #ifndef CAMERA_EFFECTS_H #define CAMERA_EFFECTS_H #include <UserComponent.h> class Transform; class CameraEffects : public UserComponent { private: float max, min, current; enum State { IDLE, FADEIN, FADEOUT, SHAKE }; State state; Transform* mainCameraTransform; Vector3 shakeDir; Vector3 rotationDir; Vector3 initialRotation; Vector3 initialPosition; float dirX; float dirY; float dirZ; float moves; float time; float vel; float minRange; float maxRange; float duration; protected: virtual void start(); virtual void update(float deltaTime); virtual void handleData(ComponentData* data); public: CameraEffects(GameObject* gameObject); virtual ~CameraEffects(); void fadeOut(); void fadeIn(); void setDarkness(); bool isFading(); void shake(Vector3 rotDir); }; #endif
true
bda76e39fa75812aa37c56a2063bf6494bc0fab3
C++
MaximeEmonnot/TCP_Project
/ServeurChatRoom/TicTacToe/TicTacToe/MinMax.h
UTF-8
508
2.625
3
[]
no_license
#pragma once #include <vector> #include <iostream> #define HIGHNUMBER 1000000000 class Node { public: Node(); ~Node(); void UpdateBoard(int board[3][3]); bool CheckVictory(); bool CheckDefeat(); public: int value; int coordonates[2]; int board[3][3]; bool finishingNode; std::vector<Node> children; }; class NodeTree { public: NodeTree(); ~NodeTree(); void Init(Node& currentNode, bool isComputer); int MinMax(Node& currentNode, bool maximazingPlayer); void Clear(Node& currentNode); };
true
ca7caa5308735ccb95708cbba6b5c0035ef82817
C++
FaizBShah/Mission-Coding
/Rishika/695. Max Area of Island.cpp
UTF-8
1,014
3.328125
3
[]
no_license
/*You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the island. Return the maximum area of an island in grid. If there is no island, return 0. */ class Solution { public: int area(int i, int j, vector<vector<int>>&grid){ if(i<0||i>=grid.size()||j<0||j>=grid[i].size()||grid[i][j]==0) return 0; grid[i][j]=0; return 1+area(i+1,j,grid)+area(i-1,j,grid)+area(i,j+1,grid)+area(i,j-1,grid); } int maxAreaOfIsland(vector<vector<int>>& grid) { int ans=0; int valcurr=0; for(int i=0;i<grid.size();i++){ for(int j=0;j<grid[i].size();j++){ if(grid[i][j]==1){ ans=max(area(i,j,grid),ans); } } } return ans; } };
true
915829871c0b7ecdf922adccd4a65d2f24d336dd
C++
antonxuanquang/ShellLab_OS
/tcush.cpp
UTF-8
1,837
3.28125
3
[]
no_license
//********************************************************* // // PUT YOUR NAME HERE!!!! // Operating Systems // Project #1: Writing Your Own Shell: tcush // //********************************************************* //********************************************************* // // Includes and Defines // //********************************************************* #include <cstdlib> #include <cstring> #include <errno.h> #include <iostream> #include <signal.h> #include <sys/types.h> #include <unistd.h> #define STRMYQUIT "myquit" //********************************************************* // // Type Declarations // //********************************************************* using namespace std; //********************************************************* // // Extern Declarations // //********************************************************* using namespace std; extern "C" { extern char **gettoks(); } //********************************************************* // // Function Prototypes // //********************************************************* //********************************************************* // // Main Function // //********************************************************* int main( int argc, char *argv[] ) { // local variables int ii; char **toks; int retval; // initialize local variables ii = 0; toks = NULL; retval = 0; // put signal catching function calls here // main (infinite) loop while( true ) { // get arguments toks = gettoks(); if( toks[0] != NULL ) { // simple loop to echo all arguments for( ii=0; toks[ii] != NULL; ii++ ) { cout << "Argument " << ii << ": " << toks[ii] << endl; } if( !strcmp( toks[0], STRMYQUIT )) break; } } // return to calling environment return( retval ); }
true
2d35ff504cfde3941f07befd710c92d229502e91
C++
Eunno-An/acmicpc.net
/1181 단어 정렬.cpp
UTF-8
891
3.046875
3
[]
no_license
#include<iostream> #include<string> #include<queue> #include<functional> using namespace std; struct forQ { int stringSize; string word; }; bool operator<(const forQ& a, const forQ& b) { if (a.stringSize == b.stringSize) { return a.word > b.word; } return a.stringSize > b.stringSize; } int main() { int N; forQ input; priority_queue<forQ, vector<forQ>> pq; vector<string> testRedundant; cin >> N; while (N--) { cin >> input.word; bool flag = false; for (int i = 0; i < testRedundant.size(); i++) { if (testRedundant[i] == input.word) { flag = true; break; } } if (flag) { continue; } input.stringSize = input.word.size(); pq.push(input); testRedundant.push_back(input.word); } int pqSize = pq.size(); for (int i = 0; i < pqSize; i++) { cout << pq.top().word << '\n'; pq.pop(); } return 0; }
true
87e3a4cdc1d3c7abf6b03ef6485b7ddbd1586964
C++
AnTAVR/Kleos
/src/renderer/vulkan/instance.cpp
UTF-8
888
2.53125
3
[]
no_license
void VulkanSetInstance( VkInstance *inst, VkInstanceCreateInfo *instInfo) { VkResult err; err = vkCreateInstance(instInfo, nullptr, inst); if (err == VK_ERROR_INCOMPATIBLE_DRIVER) { PAUSE_HERE("Cannot find a compatible Vulkan installable client driver " "(ICD).\n\nPlease look at the Getting Started guide for " "additional information.\n" "vkCreateInstance Failure"); } else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) { PAUSE_HERE("Cannot find a specified extension library" ".\nMake sure your layers path is set appropriately\n" "vkCreateInstance Failure"); } else if (err) { PAUSE_HERE("vkCreateInstance failed.\n\nDo you have a compatible Vulkan " "installable client driver (ICD) installed?\nPlease look at " "the Getting Started guide for additional information.\n" "vkCreateInstance Failure"); } }
true
02f80a393c554d5716644031c4eae41e01faffdb
C++
KhanAjmal007/Data-Structures-and-Algorithms-Specialization-Coursera
/Course_1-Algorithmic_Toolbox/Week-1/Excercise_Challenges/1_sum_of_two_digits/APlusB.cpp
UTF-8
255
3.609375
4
[]
no_license
#include <iostream> using namespace std; int sum_of_two_digits(int first_digit, int second_digit) { return first_digit + second_digit; } int main(void) { int a, b; cin >> a >> b; cout << sum_of_two_digits(a, b) << "\n"; return 0; }
true
9093999aa41d2154f93a22ffbec035159406a2df
C++
Augustinetharakan12/My-Interview-Preps
/competitive-programming/arrays/2_find_missing_element_in_array_containing_numbers_from_1_to_n-1.cpp
UTF-8
1,007
3.421875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int limit, arr[100], i, front, half, end, loc, max, sum; cout << "Enter the limit"; cin >> limit; cout << "Enter "<<limit<<" numbers"; // Input the elements for(i=0; i<limit-1; i++) { cin >> arr[i]; } //Method 1 - O(n) for(i=1; i<=limit; i++) { if(i != arr[i - 1]) { cout << "The number is" << i; break; } } //Method 2 - O(log(n)) - Algorithm similar to binary search front = 0; end = limit-1; half = (end - front)/2; loc = half; while(front < end-1) { if(loc+1 == arr[loc]) { front = front + half; half = (end-front)/2; } else { end = end - half; half = (end - front)/2; } loc = front + half; } cout << "The number is " << "\n" << loc+2; // Method 3 - Most efficient method ... doesn't require the array to be sorted max = 0; sum = 0; for(i=0; i<limit-1; i++) { if(arr[i] > max) max = arr[i]; sum += arr[i]; } cout << "The number is " << "\n" << limit*(limit+1)/2 - sum; }
true
843bec59b46241394dd63224a6d2cfc15beb7525
C++
vjacquet/praxis
/xp/algebra.h
UTF-8
2,223
3.15625
3
[ "MIT" ]
permissive
#ifndef __ALGEBRA_H__ #define __ALGEBRA_H__ #include "functional.h" #include "fakeconcepts.h" namespace xp { template<typename T, BinaryOperation Plus, BinaryOperation Multiplies> struct semiring { typedef T value_type; T value; // conversion semiring(const T& v) : value(v) {} // Semiregular semiring() : value() {} semiring(const semiring& x) : value(x.value) {} semiring(semiring&& x) noexcept : value(std::move(x.value)) {} semiring& operator=(const semiring& x) { value = x.value; return *this; } semiring& operator=(semiring&& x) { value = std::move(x.value); return *this; } explicit operator T&() { return value; } explicit operator const T&() const { return value; } // Regular inline friend bool operator==(const semiring& x, const semiring& y) { return x.value == y.value; } inline friend bool operator!=(const semiring& x, const semiring& y) { return !(x == y); } // TotallyOrdered inline friend bool operator<(const semiring& x, const semiring& y) { return x.value < y.value; } inline friend bool operator <=(const semiring& x, const semiring& y) { return !(y < x); } inline friend bool operator >(const semiring& x, const semiring& y) { return y < x; } inline friend bool operator >=(const semiring& x, const semiring& y) { return !(x < y); } // arithmetic semiring& operator+=(const semiring& x) { value = Plus()(value, x.value); return *this; } semiring& operator*=(const semiring& x) { value = Multiplies()(value, x.value); return *this; } semiring& operator-=(const semiring& x) { value = inverse_operation(Plus())(value, x.value); return *this; } semiring& operator/=(const semiring& x) { value = inverse_operation(Multiplies())(value, x.value); return *this; } inline friend semiring operator+(semiring x, const semiring& y) { return x += y; } inline friend semiring operator*(semiring x, const semiring& y) { return x *= y; } inline friend semiring operator-(semiring x, const semiring& y) { return x -= y; } inline friend semiring operator/(semiring x, const semiring& y) { return x /= y; } }; } #endif __ALGEBRA_H__
true
e4456a4f08f997f7f06be24ed684bbd63910fd4e
C++
xehoth/OnlineJudgeCodes
/BZOJ/BZOJ1137-Wsp岛屿-单调栈.cpp
UTF-8
3,599
2.65625
3
[ "Apache-2.0" ]
permissive
/** * Copyright (c) 2016-2018, xehoth * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * 「BZOJ 1137」Wsp 岛屿 24-02-2018 * 单调栈 * @author xehoth */ #include <cctype> #include <cmath> #include <cstdio> #include <iostream> #include <vector> struct InputStream { enum { SIZE = 1 << 18 | 1 }; char ibuf[SIZE], *s, *t; InputStream() : s(), t() {} inline char read() { return (s == t) && (t = (s = ibuf) + fread(ibuf, 1, SIZE, stdin)), s == t ? -1 : *s++; } template <typename T> inline InputStream &operator>>(T &x) { static char c; static bool iosig; for (c = read(), iosig = false; !isdigit(c); c = read()) { if (c == -1) return *this; iosig |= c == '-'; } for (x = 0; isdigit(c); c = read()) x = x * 10 + (c ^ '0'); iosig && (x = -x); return *this; } } io; struct Point { double x, y; Point() {} Point(const double x, const double y) : x(x), y(y) {} inline Point operator-(const Point &p) const { return Point(x - p.x, y - p.y); } inline Point operator+(const Point &p) const { return Point(x + p.x, y + p.y); } inline double operator*(const Point &p) const { return x * p.y - y * p.x; } inline Point operator*(double p) const { return Point(x * p, y * p); } inline void read() { static int v; io >> v; x = v; io >> v; y = v; } inline double norm() const { return sqrt(x * x + y * y); } }; struct Line { Point s, t; Line() {} Line(const Point &s, const Point &t) : s(s), t(t) {} inline Point intersect(const Line &l) const { return s + (t - s) * (((l.s - s) * (l.t - s)) / ((t - s) * (l.t - l.s))); } }; std::vector<Point> p; std::vector<Line> q; inline void add(int i, int j) { Line tmp(p[i], p[j]); while ((int)q.size() > 1 && (p[j] - p[i]) * (q[(int)q.size() - 1].intersect( q[(int)q.size() - 2]) - p[i]) > 0) q.pop_back(); q.push_back(tmp); } int main() { int n, m; io >> n >> m; std::vector<std::vector<int> > g(n + 1); p.resize(n + 1); for (int i = 1; i <= n; i++) p[i].read(); for (int i = 0, u, v; i < m; i++) { io >> u >> v; if (u < v) g[u].push_back(v); else g[v].push_back(u); } std::vector<int> vis(n + 1); int now = 0; for (int i = 1, j; i < n; i++) { for (j = 0; j < (int)g[i].size(); j++) vis[g[i][j]] = i; for (j = n; j > 0 && vis[j] == i; j--) ; if (j > now) add(i, now = j); } Point tmp, last = p[1]; double ans = 0; for (int i = 0; i < (int)q.size() - 1; i++) { tmp = q[i].intersect(q[i + 1]); ans += (tmp - last).norm(); last = tmp; } ans += (p[n] - last).norm(); printf("%.9f", ans); return 0; }
true
f2323cef7456bad477220b3347569c30ecae57c0
C++
SilverHL/Leetcode
/376.摆动序列.cpp
UTF-8
831
2.90625
3
[]
no_license
#include <vector> using namespace std; /* * @lc app=leetcode.cn id=376 lang=cpp * * [376] 摆动序列 */ // @lc code=start class Solution { public: int wiggleMaxLength(vector<int>& nums) { vector<int> vec; if (nums.empty()) return 0; vec.push_back(nums[0]); for (int i = 1; i < nums.size(); i++) if (vec.back() != nums[i]) vec.push_back(nums[i]); int n = vec.size(); if (n <= 2) { return n; } vector<int> dp(n, 0); dp[0] = 1; dp[1] = 2; for (int i = 2; i < n; ++i) { if ((vec[i-1] - vec[i-2]) * (vec[i] - vec[i-1]) < 0) dp[i] = dp[i-1] + 1; else dp[i] = dp[i-1]; } return dp[n-1]; } }; // @lc code=end
true
1470762d579c1f6e7a7e5b6e6537cbf3361480f9
C++
danielmonr/Estructura-de-datos
/EjercicioOrdenamiento1/EjercicioOrdenamiento1/main.cpp
UTF-8
2,121
3.4375
3
[]
no_license
// // main.cpp // EjercicioOrdenamiento1 // // Created by Daniel on 04/09/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #include <iostream> #define N 10000 void print(int []); void ordenamientoBurbuja(int v[], int n); void ordenamientoInsercion(int numbers[], int n); void ordenamientoSeleccion(int x[], int n); int main(int argc, const char * argv[]) { srand((int)time(NULL)); //creacion de arreglos int arreglo[N] = {}; for(int i = 0; i< N; i++){ arreglo[i] = rand() %100; } print(arreglo); std::cout<<"Escoja un método de ordenamiento:"<<std::endl<<"1) Burbuja"<<std::endl<<"2) Inserción"<<std::endl<<"3) Seleccion"<<std::endl; int opcion; std::cin>>opcion; switch (opcion) { case 1: ordenamientoBurbuja(arreglo, N); print(arreglo); break; default: std::cout<<"no es valida la opcion"<<std::endl; break; } return 0; } void print(int a[]){ for(int i = 0; i<N; i++){ std::cout<<a[i]<<" "; } std::cout<<std::endl; } //nunca usarlo void ordenamientoBurbuja(int v[], int n) { int temp; for (int i = 0; i < n; i++) { for (int j = n-1; j > i; j--) { if (v[j-1] > v[j]) { temp = v[j-1]; v[j-1] = v[j]; v[j] = temp; } } } } //funciona con desplasamiento de numeros void ordenamientoInsercion(int numbers[], int n){ int i, j, index; for(i = 1; i<n; i++){ index = numbers[1]; j = i-1; while(j>= 0 && numbers[j] < index){ numbers[j+1] = numbers [j]; j--; } numbers[j+1] = index; } } void ordenamientoSeleccion(int x[], int n){ int minimo = 0; int temp; for(int i = 0; i<n-1;i++){ minimo = i; for(int j = i+1; j<n; j++){ if (x[minimo] > x[j]){ minimo = j; } temp = x[minimo]; x[minimo] = x[i]; x[i] = temp; } } }
true
518accf1142de4104a7dec93520e87b47011148f
C++
comexdll/skrt-skrt-kr
/skrrt-rust-external-main/classes/game_object_manager.hpp
UTF-8
2,006
2.875
3
[]
no_license
#ifndef _GOM_HPP #define _GOM_HPP // includes for this header #include "../utils/memory/memory.hpp" // class for interacting with the gameobjectmanager class GameObjectManager { public: // constructor for this cssssslass GameObjectManager() { if (!rust->mem) return; this->gom_addr = rust->mem->Read<uint64_t>(rust->mem->up_addy + offsets->gameObjectManager); } // used to get the "camera" address uint64_t GetCamera() { // read into the first entry in the list if (this == nullptr) return 0; uint64_t address = rust->mem->Read<uint64_t>(this->gom_addr + 0x8); // loop until we hit tag 5, which is camera while (true) { // read into the GameObject uint64_t game_object = rust->mem->Read<uint64_t>(address + 0x10); // read this object's tag int16_t tag = rust->mem->Read<int16_t>(game_object + 0x54); if (tag == 5) { return rust->mem->ReadChain<uint64_t>(game_object, { 0x30, 0x18 }); } // read into the next entry address = rust->mem->Read<uint64_t>(address + 0x8); } return address; } // used to get the "sky" address uint64_t GetSky() { if (this == nullptr) return 0; // read into the first entry in the list uint64_t address = rust->mem->Read<uint64_t>(this->gom_addr + 0x8); // loop until we hit tag 20011, which is sky dome while (true) { // read into the GameObject uint64_t game_object = rust->mem->Read<uint64_t>(address + 0x10); // read this object's tag int16_t tag = rust->mem->Read<int16_t>(game_object + 0x54); // check for sky dome tag if (tag == 20011) { // camera was found, return the address return game_object; } // read into the next entry address = rust->mem->Read<uint64_t>(address + 0x8); } return address; } public: // The GameObjectManager address uint64_t gom_addr = 0; }; // gameobjectmanager extern extern GameObjectManager* gom; #endif // _GOM_HPP
true
d799d18e4592c96d05647b39ce8582f21ef6cba5
C++
Dyachuk2023/CPP-Learn
/Smart Pointers/Smart Pointers/Smart Pointer.cpp
ISO-8859-15
317
3.265625
3
[]
no_license
#include <iostream> #include <string> using namespace std; template<typename T> class SmartPointr { public: SmartPointr(T *ptr) { this->ptr = ptr; } ~SmartPointr() { delete ptr; } T& operator*() { return *ptr; } private: T *ptr; }; int main(void) { SmartPointr<int> pointer = new int(5); return 0; }
true
4bfe290e46a0e0afec6271f81893b357de1eb1ae
C++
Jack-Punter/Learning-OpenGL
/Learning OpenGL/src/test/Test.cpp
UTF-8
399
2.734375
3
[]
no_license
#include "Test.h" #include "imgui/imgui.h" namespace test { Test::Test(Renderer* renderer) : renderer(renderer) {} TestMenu::TestMenu(Test*& currentTestPtr, Renderer* renderer) : CurrentTest(currentTestPtr), renderer(renderer) {} void TestMenu::OnImGuiRender() { for (auto& test : Tests) { if (ImGui::Button(test.first.c_str())) CurrentTest = test.second(renderer); } } }
true
d1f73278b1416d02c925ca5162450d2decf4f0dc
C++
Karunika/Taxi_Agency_OODB
/include/Shift.hpp
UTF-8
1,673
2.875
3
[ "MIT" ]
permissive
#pragma once #include <iostream> #include <cmath> using namespace std; class Shift{ private: string customer_uuid; string driver_in_charge_uuid; string car_id; int taxi_fare_amount; int waiting_charges; unordered_map<string, int> history_stats = { {"running_kms", 0}, {"waiting_hours", 0}, {"total_cost", 0}, }; public: static int ShiftAttributesCount; static int HistoryShiftAttributesCount; Shift(){}; Shift(string customer_uuid, string driver_in_charge_uuid, string taxi_id, int taxi_fare_amount, int waiting_charges); Shift(string customer_uuid, string driver_in_charge_uuid, string taxi_id, int taxi_fare_amount, int waiting_charges, int running_hours, int waiting_hours, int total_cost); const string& getCustomerUUID() const; const string& getDriverUUID() const; const string& getCarID() const; const int& getFareAmount() const; const int& getWaitingCharges() const; const int& getRunningKms() const; const int& getWaitingHours() const; const int& getTotalCost() const; void setRunningKms(int running_kms); void setWaitingHours(int waiting_hours); void setTotalCost(int total_cost); void updateRunningKms(int del_running_kms); void updateWaitingHours(int del_waiting_hours); void updateTotalCost(int del_total_cost); void extend_tenure(int del_running_kms, int del_waiting_hours); friend ostream& operator<<(ostream& output, const Shift& S); void print_shift(); };
true
322a52e9274b3875581ebbb95afb1620002855aa
C++
blockspacer/CIS505PennCloud
/PennCloud/FE_server/SMTP_external_to_bigtables.cc
UTF-8
27,202
2.65625
3
[]
no_license
//----------------------------------------------------------------------- // SMTP_EXTERNAL_TO_BIGTABLE #include "SMTP_external_to_bigtables.h" // global variables vector<int> Client_fds; //vector<FILE *> Read_Write_fds; vector<pthread_t> Threads; // vector<BigTable *> BIGTABLE_pts; // something wrong with string char PARENTdir[MAX_LEN_PARENTdir]; bool DEBUG_flag = true; MasterServiceClient masterServer(grpc::CreateChannel("localhost:50080", grpc::InsecureChannelCredentials())); int main() { unsigned short port_id = 2500;//HANDOUT: but the default port number should now be 2500 (The default is 25, but port numbers below 1024 require root privileges to access.) // char ch; // control symbol // while (( ch = getopt( argc, argv, "p:v")) != -1) // refers to https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html#Example-of-Getopt // switch (ch) { // case 'p': // port_id = atoi(optarg); // break; // case 'v': // DEBUG_flag = true; // break; // } // if (0 == argc - optind ){cerr << "Please provide DIRECTORY for mailboxes\n";exit(1);} // // void import_bigtables(const char *); // vector<string> BIGTABLE_names; // for (int i = optind; i <argc; i++) { // string DIR(argv[optind]); // // import_bigtables(DIR); // if( find(BIGTABLE_names.begin(), BIGTABLE_names.end(), DIR) == BIGTABLE_names.end() ) // {BIGTABLE_pts.push_back(new BigTable(DIR)); BIGTABLE_names.push_back(DIR); } // } // // lecture 6 page 25 // open a TCP port // get a tcp/ip socket int listen_fd = socket(PF_INET, SOCK_STREAM, 0); if (listen_fd <0) {cerr << "Error connecting to socket):\t" << strerror(errno); exit(1);} void SignalHandler(int arg); signal(SIGINT,SignalHandler); const int enable = 1; if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {cerr << "setsockopt(SO_REUSEADDR) failed:\t" << strerror(errno); exit(1);} // SETSOCKOPT suggested by PIAZZA // https://stackoverflow.com/questions/24194961/how-do-i-use-setsockoptso-reuseaddr struct sockaddr_in servaddr; bzero(&servaddr, sizeof(servaddr));// this is an actual function servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port_id); bind(listen_fd, (struct sockaddr*)&servaddr, sizeof(servaddr)); // page 25 uses CONNECT; page 41 uses BIND // slide 6 page 29, 41 listen(listen_fd, MAX_connection); // puts a socket into the listening state Client_fds.push_back(listen_fd); void *worker(void *arg); // DECLARATION while (true) { // what is the use of this loop? struct sockaddr_in clientaddr; socklen_t clientaddrlen = sizeof(clientaddr); int comm_fd = accept(listen_fd, (struct sockaddr*)&clientaddr, &clientaddrlen); pthread_t thread; pthread_create(&thread, NULL, &worker, &comm_fd); Client_fds.push_back(comm_fd); if (DEBUG_flag) {// REQUIRED cout << '[' << comm_fd << "] New connection" << "\n";} Threads.push_back(thread); // after pthread_create -- otherwise first thread has a problem } return 0; } //reply words seem can be arbitrary //https://tools.ietf.org/html/rfc821 (APPENDIX F) // according to /test/smtp-test.cc char Welcome220[] = "220 localhost Service Ready\r\n"; char ServiceClosing[]="221 localhost Service closing transmission channel\r\n"; char OKsuccess250[]= "250 OK\r\n"; char StartInput[] = "354 Start mail input; end with <CRLF>.<CRLF>\r\n"; char RequrestdActionAbortedMboxOpening[] = "451 Requested action aborted: error in processing: MBOX opening error\r\n"; char RequrestdActionAbortedMboxLocked[] = "451 Requested action aborted: error in processing: MBOX already locked\r\n"; char Unrecogn500[] = "500 Syntax error, command unrecognized\r\n"; char SyntaxErrPara501[]="501 Syntax error in parameters or arguments\r\n"; //reply words seem can be arbitrary //https://tools.ietf.org/html/rfc821 char BadSeq503[] ="503 Bad sequence of commands\r\n"; char NoSuchUser550[] = "550 No such user here\r\n"; void *worker(void *arg) { void SignalHandler_thread(int arg); // DECLARATION signal(SIGUSR1,SignalHandler_thread); // SIGALRM //PIAZZA 147: since an interrupt will only be sent to an arbitrary thread ... sigset_t set; int sig; sigemptyset(&set);sigaddset(&set,SIGINT); if(pthread_sigmask(SIG_SETMASK, &set, NULL)) {cerr << "empty TH: error pthread sigmask (SIGINT):" << strerror(errno); exit(2);} // block SIGINT signal const int comm_fd = *(int*) arg; EmailDTO email_to_insert; char MessContent[MAX_LEN_MESS]; // send a simple message ---------------------- char SenderName_AT_domain[MAX_USER_NAME]; vector <string> ReceiverNameMboxes; //linhphan.mbox int STATE_this_mail_client = STATE_INITI;// keep commands in correct orders write(comm_fd, Welcome220, strlen(Welcome220)); if (DEBUG_flag) cout << Welcome220 << '\n'; char commd[LEN_MAX_CMD]; char buff[LEN_MAX_CMD], mess2[2*LEN_MAX_CMD]; //message[2*LEN_MAX_CMD], memset(commd, 0, sizeof(char) * LEN_MAX_CMD); char HEAD[10], * LastPt; // LastPt is the pointer to an end of buff, in order to give COMMD correct command memset(buff, 0, sizeof(char) * LEN_MAX_CMD); memset(HEAD,0,sizeof(char) *20); bool TransmittingData = false; while(0 !=strcasecmp(HEAD, "QUIT") ){// handout: the command should be case -insensitive memset(commd, 0, sizeof(commd) ); //cout << "(AT the beginning) commd:" <<commd << "\tbuff:" << buff; while(NULL == (LastPt = strstr(buff,"\r\n") ) ) { strcat(commd, buff); memset(buff, 0, sizeof(buff) ); read(comm_fd, &buff, LEN_MAX_CMD - strlen(commd)); } LastPt +=2; memset(mess2, 0, sizeof(mess2) ); strncpy(mess2, buff, LastPt - buff); strcat(commd, mess2 ); strcpy(buff,LastPt); if (DEBUG_flag) cout << '[' <<comm_fd <<"] C: " << commd; // REQUIRED // finish dealing with COMMD and BUFF -- possibly BUFF still has the beginning of next message if (strlen(commd) >=4) memcpy(HEAD,commd,sizeof(char)*4); if (TransmittingData) { void Transmission_DATA(int &STATE_this_mail_client, const char *commd,const int comm_fd, bool &, EmailDTO &email, char *mess_content,vector <string> &); Transmission_DATA(STATE_this_mail_client,commd,comm_fd, TransmittingData, email_to_insert, MessContent,ReceiverNameMboxes); } else if (0 == strcasecmp(HEAD, "HELO") ) { if (STATE_INITI ==STATE_this_mail_client){ bool have_parameter_separated_by_backspace = false; if (6 <strlen(commd)){ if (' ' != commd[4])// '' is different from '\b' { write(comm_fd,Unrecogn500, strlen(Unrecogn500) ); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << Unrecogn500; }else{int idx=4; for(; idx <strlen(commd) -2; idx++) if(' ' != commd[idx]) break; if ( (strlen(commd)-2) !=idx) {have_parameter_separated_by_backspace = true; } else{// 501 failure-- should have words following write(comm_fd, SyntaxErrPara501 ,strlen(SyntaxErrPara501) );//strcat(message,mess2); // according to smtp-test -- I do not need mess2 if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << SyntaxErrPara501; } } }else{// 501 failure -- should have words following write(comm_fd, SyntaxErrPara501 ,strlen(SyntaxErrPara501) );//strcat(message,mess2); // according to smtp-test -- I do not need mess2 if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << SyntaxErrPara501; } if (have_parameter_separated_by_backspace) {void handle_helo(int &STATE_this_mail_client, const char * commd,const int comm_fd,char *SenderName_AT_domain, vector <string> &ReceiverNameMboxes); // DECLARATION handle_helo(STATE_this_mail_client,commd, comm_fd,SenderName_AT_domain,ReceiverNameMboxes); } }else{// BAD sequence comands write(comm_fd,BadSeq503, strlen(BadSeq503) ); // not pointed out by RFC if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << BadSeq503; // REQUIRED } } else if (0 ==strcasecmp(HEAD, "MAIL") ) { void ParseMailFrom(int &STATE_this_mail_client,const char*commd,char *SenderName_AT_domain,const int comm_fd ); ParseMailFrom(STATE_this_mail_client,commd, SenderName_AT_domain,comm_fd ); } else if (0 ==strcasecmp(HEAD, "RCPT") ) { void ParseRcptTo(int &STATE_this_mail_client, const char *commd,vector <string> &ReceiverNameMboxes,const int comm_fd); ParseRcptTo(STATE_this_mail_client,commd,ReceiverNameMboxes,comm_fd); } else if (0 == strcasecmp(HEAD, "DATA") ) { bool rest_are_backspaces_or_null = false; if (6 ==strlen(commd)) // commd is only "DATA\r\n" rest_are_backspaces_or_null = true; else if (' ' != commd[4]) {write(comm_fd,Unrecogn500, strlen(Unrecogn500) ); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << Unrecogn500; }else{int idx=4; for(; idx <strlen(commd) -2; idx++) if(' ' != commd[idx]) break; if ( (strlen(commd)-2) ==idx) {rest_are_backspaces_or_null = true; } else{// 501 failure write(comm_fd, SyntaxErrPara501 ,strlen(SyntaxErrPara501) );//strcat(message,mess2); // according to smtp-test -- I do not need mess2 if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << SyntaxErrPara501; } } if (rest_are_backspaces_or_null) {void WhetherStartData(int &STATE_this_mail_client,const char *SenderName_AT_domain,vector <string>&ReceiverNameMboxes, const int comm_fd, bool &, EmailDTO &email, char *mess_content); WhetherStartData(STATE_this_mail_client, SenderName_AT_domain,ReceiverNameMboxes, comm_fd, TransmittingData, email_to_insert, MessContent); } } else if (0 == strcasecmp(HEAD, "QUIT") ) {bool correctHEAD = false; if (6 ==strlen(commd)) // commd is only "QUIT\r\n" {correctHEAD = true;} else if (' ' != commd[4]) { write(comm_fd,Unrecogn500, strlen(Unrecogn500) ); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << Unrecogn500; }// no 501 failure if (correctHEAD) {memset(SenderName_AT_domain,0,sizeof(SenderName_AT_domain)); ReceiverNameMboxes.clear(); write(comm_fd,ServiceClosing, strlen(ServiceClosing) ); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << ServiceClosing; // REQUIRED } } else if (0 == strcasecmp(HEAD, "RSET") ) { bool rest_are_backspaces_or_null = false; if (6 ==strlen(commd)) // commd is only "RSET\r\n" rest_are_backspaces_or_null = true; else if (' ' != commd[4]) { write(comm_fd,Unrecogn500, strlen(Unrecogn500) ); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << Unrecogn500; }else{int idx=4; for(; idx <strlen(commd) -2; idx++) if(' ' != commd[idx]) break; if ( (strlen(commd)-2) ==idx) {rest_are_backspaces_or_null = true; } else{// 501 failure -- should have no parameter/ argument write(comm_fd, SyntaxErrPara501 ,strlen(SyntaxErrPara501) );//strcat(message,mess2); // according to smtp-test -- I do not need mess2 if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << SyntaxErrPara501; } } if (rest_are_backspaces_or_null) { STATE_this_mail_client = 0; void handle_helo(int &STATE_this_mail_client, const char * commd,const int comm_fd,char *SenderName_AT_domain, vector <string> &ReceiverNameMboxes); // DECLARATION handle_helo(STATE_this_mail_client, commd, comm_fd,SenderName_AT_domain, ReceiverNameMboxes); // HEAD RSET, HELO will not be distinguished } } else if (0 == strcasecmp(HEAD, "NOOP") ) { bool rest_are_backspaces_or_null = false; if (6 ==strlen(commd)) rest_are_backspaces_or_null = true;// commd is only "NOOP\r\n" else if (' ' != commd[4]) { write(comm_fd,Unrecogn500, strlen(Unrecogn500) ); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << Unrecogn500; }// no need to check 501 parameter failure if (rest_are_backspaces_or_null){ write(comm_fd, OKsuccess250, strlen(OKsuccess250)); // failure 500 is hard to realize here if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << OKsuccess250; // REQUIRED } } else {write(comm_fd,Unrecogn500, strlen(Unrecogn500) ); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << Unrecogn500; // REQUIRED } } int pos_thread = 0; for (;pos_thread< Threads.size(); pos_thread ++)// use Client_fds to locate it if (comm_fd == Client_fds[pos_thread+1]) break; if ( Threads.size() == pos_thread) {cerr << "Error locating pos_thread within Client_fds\n";exit(1);} else { Threads.erase(Threads.begin() + pos_thread ); Client_fds.erase(Client_fds.begin() + pos_thread + 1) ; } close(comm_fd); if (DEBUG_flag) cout<< '['<< comm_fd << "] Connection closed\n"; //REQUIRED pthread_exit(NULL); // the server shold also properly clean up its resources by terminating pthreads when their connection closes pthread_detach(pthread_self() ); } void SignalHandler(int arg) {// once SIGINT is received char Err_ShutDown421[] = "421 Service unavailable\r\n"; if (0== Threads.size()) { if (DEBUG_flag) cout << "No client at all\n"; exit(1); } else { vector <bool> pthread_kill_success_flag; for(int i =0;i<Threads.size();i++) { write(Client_fds[i+1], Err_ShutDown421, strlen(Err_ShutDown421)); close(Client_fds[i+1]);// close the file descriptor -- if you forget this PTHREAD_KILL may cause segmentation default // // blog.csdn.net/yusiguyuan/article/details/14230719 // // This is suggested by Yuding Ai int rc = pthread_kill(Threads[i], SIGUSR1); // SIGALRM if (0 == rc) //pthread_ kill successfully send the signal pthread_kill_success_flag.push_back(true); else pthread_kill_success_flag.push_back(false); } for(int i =0;i<Threads.size();i++) if (pthread_kill_success_flag[i]) {int rc = pthread_join(Threads[i], NULL);} close(Client_fds[0]); // close listen_fd // for(int i=0; i< BIGTABLE_pts.size(); i++) // delete BIGTABLE_pts[i]; exit(1); } } void SignalHandler_thread(int arg){ // for (int i =0; i< FD_pts_to_UNLOCK.size(); i++) // does not work // if (NULL != FD_pts_to_UNLOCK[i]) // {flock(FD_pts_to_UNLOCK[i],LOCK_UN);fclose(FD_pts_to_UNLOCK[i]); FD_pts_to_UNLOCK[i] =NULL;} pthread_exit(NULL); } void handle_helo(int &STATE_this_mail_client, const char * commd,const int comm_fd,char *SenderName_AT_domain, vector <string> &ReceiverNameMboxes) { if (STATE_INITI ==STATE_this_mail_client){ bool have_parameter_separated_by_backspace = false; if (6 <strlen(commd)){ if (' ' != commd[4])// '' is different from '\b' { write(comm_fd,Unrecogn500, strlen(Unrecogn500) ); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << Unrecogn500; }else{int idx=4; for(; idx <strlen(commd) -2; idx++) if(' ' != commd[idx]) break; if ( (strlen(commd)-2) !=idx) {have_parameter_separated_by_backspace = true; } else{// 501 failure-- should have words following write(comm_fd, SyntaxErrPara501 ,strlen(SyntaxErrPara501) );//strcat(message,mess2); // according to smtp-test -- I do not need mess2 if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << SyntaxErrPara501; } } }else{// 501 failure -- should have words following write(comm_fd, SyntaxErrPara501 ,strlen(SyntaxErrPara501) );//strcat(message,mess2); // according to smtp-test -- I do not need mess2 if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << SyntaxErrPara501; } if (have_parameter_separated_by_backspace) { STATE_this_mail_client =1; memset(SenderName_AT_domain,0,sizeof(SenderName_AT_domain)); ReceiverNameMboxes.clear(); char temp[]="250 localhost\r\n"; // at least \r\n // according to smtp-test -- I do not need mess2 PIAZZA @149 write(comm_fd, temp ,strlen(temp) );//strcat(message,mess2); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << temp; // REQUIREDs } } else{write(comm_fd,BadSeq503, strlen(BadSeq503) ); // not pointed out by RFC if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << BadSeq503; // REQUIRED } } //---------------------------------------------- void ParseMailFrom(int &STATE_this_mail_client,const char *commd, char *SenderName_AT_domain ,const int comm_fd) { char HEAD[20]; memset(HEAD,0,sizeof(HEAD)); memcpy(HEAD,commd,sizeof(char)*10); if (0 == strcasecmp(HEAD, "MAIL FROM:") ) { if (STATE_HELO_MAIL == STATE_this_mail_client) { STATE_this_mail_client = 2; char mess2[LEN_MAX_CMD]; memset(mess2,0,sizeof(mess2)); strncpy(mess2,commd+10,strlen(commd)-10); char * pch = strchr(mess2, '<'); // I did not debug this one pch ++; int lengName = strchr(mess2, '>') - pch; if (0 < lengName){ // PIAZZA @184 I should case 0 is acceptable == length -- recall default of SenderName_AT_domain = '\0' memset(SenderName_AT_domain,0,sizeof(SenderName_AT_domain)); strncpy(SenderName_AT_domain,pch, lengName*sizeof(char)); } write(comm_fd,OKsuccess250,strlen(OKsuccess250)); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << OKsuccess250 ; } else {write(comm_fd, BadSeq503,strlen(BadSeq503)); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << BadSeq503; // REQUIRED } } else {//strcpy(message, Unrecogn500);strcat(message, mess2); write(comm_fd,Unrecogn500, strlen(Unrecogn500) ); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << Unrecogn500; // REQUIRED } } void ParseRcptTo(int &STATE_this_mail_client, const char *commd, vector <string> &ReceiverNameMboxes,const int comm_fd) { char OKsuccess[]= "250 OK\r\n"; char HEAD[20]; memset(HEAD,0,sizeof(HEAD)); memcpy(HEAD,commd,sizeof(char)*8); if (0 == strcasecmp(HEAD, "RCPT TO:")) { if (STATE_MAIL_RCPT == STATE_this_mail_client || STATE_RCPT_DATA == STATE_this_mail_client) // Possible to have many RCPT TO: {STATE_this_mail_client = STATE_RCPT_DATA; char mess2[LEN_MAX_CMD]; memset(mess2,0,sizeof(mess2)); strncpy(mess2,commd+8,strlen(commd)-8); char * pch = strchr(mess2, '<'); // EACH LINE only one receipt pch ++; int lengName = strchr(mess2, '>') - pch; // PIAZZA @184 I should consider case 0 == length if (0 < lengName) // INTIAL { char RCPTName[MAX_USER_NAME]; strncpy(RCPTName,pch, lengName*sizeof(char)); int lenRCName = strchr(RCPTName, '@') - RCPTName; // I have not DEBUG this one char RCPTMbox1[MAX_USER_NAME]; memset(RCPTMbox1,0,sizeof(RCPTMbox1)); strncpy(RCPTMbox1,RCPTName,lenRCName*sizeof(char)); ReceiverNameMboxes.push_back(string(RCPTMbox1)); write(comm_fd,OKsuccess250,strlen(OKsuccess250)); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << OKsuccess250; // ---------------------------------- } else{ //PIAZZA @184 I should consider case 0 == length if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: EmptySender \n"; // REQUIRED exit(1); } }else {write(comm_fd, BadSeq503,strlen(BadSeq503)); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << BadSeq503; // REQUIRED } } else {// 500 failure write(comm_fd,Unrecogn500, strlen(Unrecogn500) ); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << Unrecogn500; // REQUIRED } } void WhetherStartData(int &STATE_this_mail_client,const char *SenderName_AT_domain, vector <string>&ReceiverNameMboxes, const int comm_fd, bool &TransmittingData, EmailDTO &email, char *mess_content) { if (STATE_RCPT_DATA == STATE_this_mail_client) {// 5 is included due to example on page 37 of RFC 821 ?? However, according to PIAZZA STATE_this_mail_client = STATE_DATA; TransmittingData = true; // write first line -- it is required and it related with uniqueness of MD5 ID POP3 char RequiredLine[LEN_MAX_CMD]; memset(RequiredLine,0,sizeof(RequiredLine)); strcpy(RequiredLine,"From <"); strcat(RequiredLine, SenderName_AT_domain); strcat(RequiredLine,"> "); time_t CurrT = time(0); string timestamp = ctime(&CurrT); // end with \n\0 strcat(RequiredLine,timestamp.c_str()); RequiredLine[strlen(RequiredLine)-1] = '\r'; RequiredLine[strlen(RequiredLine)] = '\n'; char MD5_id_mess[2*MD5_DIGEST_LENGTH+1]; memset(MD5_id_mess,0,sizeof(MD5_id_mess)); unsigned char digest[2*MD5_DIGEST_LENGTH+1]; computeDigest(RequiredLine,strlen(RequiredLine),digest); //------------------------------------- // PIAZZA @252: You should convert MD5 hash to a string for UIDL in whatever way you like. // A hex string might be the easiest one and satisfies the range requirements. //https://stackoverflow.com/questions/5661101/how-to-convert-an-unsigned-character-array-into-a-hexadecimal-string-in-c char BUFF[32]; for (int j=0; j < MD5_DIGEST_LENGTH; j++){ sprintf(BUFF, "%02x", digest[j]);// *2 == cannot connect to Thunderbird strcat(MD5_id_mess,BUFF); } email.set_uid(MD5_id_mess); memset(mess_content,0,sizeof(mess_content)); write(comm_fd,StartInput, strlen(StartInput)); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << StartInput; // REQUIRED }else{write(comm_fd, BadSeq503, strlen(BadSeq503)); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << BadSeq503; // REQUIREDs } } void Transmission_DATA(int &STATE_this_mail_client, const char *commd,const int comm_fd, bool &TransmittingData,EmailDTO &email,char *mess_content,vector <string> &ReceiverNameMboxes) { if (4 == STATE_this_mail_client) { char inputline[LEN_MAX_CMD]; // Give a new name for variable COMMD -- a protection memset(inputline,0,sizeof(inputline)); strcpy(inputline,commd); if ( 0 == strcasecmp(inputline, ".\r\n")) { TransmittingData = false; // finishing transmitting data STATE_this_mail_client = 1; // According to PIAZZA @208, return to HELO state, but I think this is not consistent with SCENARIO 10 on page 38 of RFC email.set_message(mess_content); //------------------ // for (int bt_pt_id=0; bt_pt_id <BIGTABLE_pts.size(); bt_pt_id ++) for (int rec_id =0; rec_id < ReceiverNameMboxes.size(); rec_id ++) { email.set_receiver(ReceiverNameMboxes[rec_id].c_str()); // string uid = HttpService::gen_rand_string(15); // email.set_uid(uid); // put it global variable -- MasterServer WriteResponse response = masterServer.RequestWrite(email.receiver(), email.uid(), email.SerializeAsString(), WriteType::PUT, FileType::EMAIL); // string serializedEmail = email.SerializeAsString(); // if (DEBUG_flag)printf("[%d] #########################################\n%s#########################################3333\n",,commd_fd,email.message().c_str()); // BIGTABLE_pts[bt_pt_id]->put(email.receiver(), email.uid(),"email", serializedEmail.size(),serializedEmail.c_str()); } //------------------ write(comm_fd,OKsuccess250,strlen(OKsuccess250)); if (DEBUG_flag) cout << '[' <<comm_fd <<"] S: " << OKsuccess250; // REQUIRED }else{ // printf("#################################333333"); char TempLine[MAX_LEN_MESS]; strcpy(TempLine, commd); char *token = strtok(TempLine, ":"); if (0 ==strcmp("Subject",token)){ token = strtok(NULL,":"); email.set_subject(token); // Elements_collected++; }else if (0 ==strcmp("From", token)){ token = strtok(NULL,":"); printf("sender::%s---------------------\n",token); email.set_sender(token); // Elements_collected++; }else if (0 ==strcmp("Date", token)){ token = strtok(NULL,":"); printf("Date::%s---------------------\n",token+4); email.set_date(token); // Elements_collected++; }else if (0 ==strncmp("Date", token,4)){ // token = strtok(NULL,":"); printf("Date::%s---------------------\n",token+4); email.set_date(token+4); // Elements_collected++; } else if (0 == strcmp("Message-ID", token)){} else if (0 == strcmp("X-Forwarded-Message-Id", token)){} else if (0 == strcmp("To", token)){} else if (0 == strcmp("User-Agent", token)){} else if (0 == strcmp("MIME-Version", token)){} else if (0 == strcmp("In-Reply-To", token)){} else if (0 == strcmp("Content-Type", token)){} else if (0 == strcmp("Content-Language", token)){} else if (0 == strcmp("Content-Transfer-Encoding", token)){} else if (0 == strcmp("ContenTrsfer-Encoding", token)){} else {strcat(mess_content,inputline);} } } else{// I think this part is never implemented } }
true
d69cadd07aaa865c5803dcaa56c38ccd17a4daf1
C++
ivchenko094/sse-math-lib
/math/src/Matrix.cpp
UTF-8
5,402
2.703125
3
[]
no_license
#include "Matrix.h" #include <stdio.h> mathLib::Matrix3x3::Matrix3x3() { mmval[0] = _mm_setzero_ps(); mmval[1] = _mm_setzero_ps(); mmval[2] = _mm_setzero_ps(); } mathLib::Matrix3x3::Matrix3x3(const __m128& _row0, const __m128& _row1, const __m128& _row2) { mmval[0] = _row0; mmval[1] = _row1; mmval[2] = _row2; } mathLib::Matrix3x3::Matrix3x3(const float * _row0, const float * _row1, const float * _row2) { val[0][0] = _row0[0]; val[0][1] = _row0[1]; val[0][2] = _row0[2]; val[1][0] = _row1[0]; val[1][1] = _row1[1]; val[1][2] = _row1[2]; val[2][0] = _row2[0]; val[2][1] = _row2[1]; val[2][2] = _row2[2]; } mathLib::Matrix3x3::Matrix3x3(const float x1, const float y1, const float z1, const float x2, const float y2, const float z2, const float x3, const float y3, const float z3) { val[0][0] = x1; val[0][1] = y1; val[0][2] = z1; val[1][0] = x2; val[1][1] = y2; val[1][2] = z2; val[2][0] = x3; val[2][1] = y3; val[2][2] = z3; } mathLib::Matrix3x3::Matrix3x3(const vector3 & _vec0, const vector3& _vec1, const vector3& _vec2) { mmval[0] = _vec0.mmval; mmval[1] = _vec1.mmval; mmval[2] = _vec2.mmval; } void mathLib::Matrix3x3::operator+=(const Matrix3x3 & _mat) { mmval[0] = _mm_add_ps(mmval[0], _mat.mmval[0]); mmval[1] = _mm_add_ps(mmval[1], _mat.mmval[1]); mmval[2] = _mm_add_ps(mmval[2], _mat.mmval[2]); } void mathLib::Matrix3x3::operator-=(const Matrix3x3 & _mat) { mmval[0] = _mm_sub_ps(mmval[0], _mat.mmval[0]); mmval[1] = _mm_sub_ps(mmval[1], _mat.mmval[1]); mmval[2] = _mm_sub_ps(mmval[2], _mat.mmval[2]); } void mathLib::Matrix3x3::operator*=(const Matrix3x3 & _mat) { __m128 row0, row1, row2; __m128 rowT0 = mmval[0]; __m128 rowT1 = mmval[1]; __m128 rowT2 = mmval[2]; _MM_TRANSPOSE4_PS(rowT0, rowT1, rowT2, _mm_setzero_ps()); row0 = _mm_add_ps( _mm_add_ps( _mm_dp_ps(_mat.mmval[0], rowT0, 0x71), _mm_dp_ps(_mat.mmval[1], rowT0, 0x72)), _mm_dp_ps(_mat.mmval[2], rowT0, 0x74)); row1 = _mm_add_ps( _mm_add_ps( _mm_dp_ps(_mat.mmval[0], rowT1, 0x71), _mm_dp_ps(_mat.mmval[1], rowT1, 0x72)), _mm_dp_ps(_mat.mmval[2], rowT1, 0x74)); row2 = _mm_add_ps( _mm_add_ps( _mm_dp_ps(_mat.mmval[0], rowT2, 0x71), _mm_dp_ps(_mat.mmval[1], rowT2, 0x72)), _mm_dp_ps(_mat.mmval[2], rowT2, 0x74)); _MM_TRANSPOSE4_PS(row0, row1, row2, _mm_setzero_ps()); mmval[0] = row0; mmval[1] = row1; mmval[2] = row2; } float mathLib::Matrix3x3::Determinant() const { __m128 Minor1 = _mm_mul_ps( _mm_shuffle_ps(mmval[1], mmval[1], _MM_SHUFFLE(1, 2, 0, 2)), _mm_shuffle_ps(mmval[2], mmval[2], _MM_SHUFFLE(2, 1, 2, 0)) ); __m128 Minor2 = _mm_mul_ps( _mm_shuffle_ps(mmval[1], mmval[1], _MM_SHUFFLE(0, 1, 3, 3)), _mm_shuffle_ps(mmval[2], mmval[2], _MM_SHUFFLE(1, 0, 3, 3)) ); ShuffleBySign(Minor1, Minor2); __m128 maskedRow0 = _mm_mul_ps(mmval[0], NanMask); Minor1 = _mm_dp_ps(Minor1, maskedRow0, 0x77); Minor2 = _mm_dp_ps(Minor2, maskedRow0, 0x77); return _mm_cvtss_f32(_mm_sub_ps(Minor1, Minor2));; } __m128 mathLib::operator*(const Matrix3x3 & _mat, const vector3 & _vec) { __m128 result = _mm_setzero_ps(); result = _mm_add_ps(result, _mm_dp_ps(_mat.mmval[0], _vec.mmval, 0x71)); result = _mm_add_ps(result, _mm_dp_ps(_mat.mmval[1], _vec.mmval, 0x72)); result = _mm_add_ps(result, _mm_dp_ps(_mat.mmval[2], _vec.mmval, 0x74)); return result; } __m128 mathLib::operator*(const vector3 & _vec, const Matrix3x3 & _mat) { __m128 x1x2x3 = _mat.mmval[0]; __m128 y1y2y3 = _mat.mmval[1]; __m128 z1z2z3 = _mat.mmval[2]; __m128 result = _mm_setzero_ps(); _MM_TRANSPOSE4_PS(x1x2x3, y1y2y3, z1z2z3, result); result = _mm_add_ps(result, _mm_dp_ps(_vec.mmval, x1x2x3, 0x71)); result = _mm_add_ps(result, _mm_dp_ps(_vec.mmval, y1y2y3, 0x72)); result = _mm_add_ps(result, _mm_dp_ps(_vec.mmval, z1z2z3, 0x74)); return result; } mathLib::Matrix3x3 mathLib::operator*(const Matrix3x3 & _mat1, const Matrix3x3 & _mat2) { __m128 row0, row1, row2; __m128 rowT0 = _mat1.mmval[0]; __m128 rowT1 = _mat1.mmval[1]; __m128 rowT2 = _mat1.mmval[2]; _MM_TRANSPOSE4_PS(rowT0, rowT1, rowT2, _mm_setzero_ps()); row0 = _mm_add_ps( _mm_add_ps( _mm_dp_ps(_mat2.mmval[0], rowT0, 0x71), _mm_dp_ps(_mat2.mmval[1], rowT0, 0x72)), _mm_dp_ps(_mat2.mmval[2], rowT0, 0x74)); row1 = _mm_add_ps( _mm_add_ps( _mm_dp_ps(_mat2.mmval[0], rowT1, 0x71), _mm_dp_ps(_mat2.mmval[1], rowT1, 0x72)), _mm_dp_ps(_mat2.mmval[2], rowT1, 0x74)); row2 = _mm_add_ps( _mm_add_ps( _mm_dp_ps(_mat2.mmval[0], rowT2, 0x71), _mm_dp_ps(_mat2.mmval[1], rowT2, 0x72)), _mm_dp_ps(_mat2.mmval[2], rowT2, 0x74)); _MM_TRANSPOSE4_PS(row0, row1, row2, _mm_setzero_ps()); return Matrix3x3(row0, row1,row2); } mathLib::Matrix3x3 mathLib::operator+(const Matrix3x3 & _mat1, const Matrix3x3 & _mat2) { __m128 row0 = _mm_add_ps(_mat1.mmval[0], _mat2.mmval[0]); __m128 row1 = _mm_add_ps(_mat1.mmval[1], _mat2.mmval[1]); __m128 row2 = _mm_add_ps(_mat1.mmval[2], _mat2.mmval[2]); return Matrix3x3(row0,row1,row2); } mathLib::Matrix3x3 mathLib::operator-(const Matrix3x3 & _mat1, const Matrix3x3 & _mat2) { __m128 row0 = _mm_sub_ps(_mat1.mmval[0], _mat2.mmval[0]); __m128 row1 = _mm_sub_ps(_mat1.mmval[1], _mat2.mmval[1]); __m128 row2 = _mm_sub_ps(_mat1.mmval[2], _mat2.mmval[2]); return Matrix3x3(row0, row1, row2); }
true
950a1f1875da6f49014d3a84e2ddef39f4b64467
C++
dtn9797/myCourses
/Spring 2018/CSE1315/Lectures/lecture_06/06/month.h
UTF-8
378
2.84375
3
[]
no_license
#ifndef __MONTH_H #define __MONTH_H #include <iostream> using namespace std; enum class Month {jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec}; std::string month_to_string(Month m); Month& operator++(Month& m); Month operator++(Month& m, int); ostream& operator<<(ostream& os, const Month& month); #endif
true
3f7a5314b5831fe7f80177e58c3cea95b52a9e69
C++
SwiftlyAside/JustC
/200317/Quiz.cpp
UTF-8
9,064
3.5625
4
[]
no_license
#include <cstdio> #include <cstdlib> #include <conio.h> // 두 수중 최댓값반환. int evaluate(int su1, int su2) { int max = su2; if (su1 > su2) max = su1; return max; } // 두 수중 최솟값반환. int min_evaluate(int su1, int su2) { int min = su1; if (su1 > su2) min = su2; return min; } void show_absolute_value(int su) { if (su >= 0) printf("Absolute : %d", su); else printf("Absolute : %d", -su); } void is_even_or_odd(int su) { if (su % 2 == 0) printf("Even : %d", su); else printf("Odd : %d", su); } void evaluate_three(int su1, int su2, int su3) { int max = 0, min = 0; max = evaluate(evaluate(su1, su2), su3); min = min_evaluate(min_evaluate(su1, su2), su3); printf("%d is max\n", max); printf("%d is min\n", min); } void print_max_number(int su1, int su2) { int max = evaluate(su1, su2); printf("Max value: %d", max); } void print_sixth(int su1, int su2) { int sum = su1 + su2; if (sum % 6 == 0) printf("%d is OK", sum); } void print_even(int su1, int su2) { int max = evaluate(su1, su2); if (max % 2 == 0) printf("%d is Even.\n", max); } int main(int argc, char* argv[]) { /* float su1 = 3.01, su2 = 3.0; printf("변수 su1과 su2의 크기 비교 결과 : \n"); int num; printf("Ay, Enter the score..."); scanf_s("%d", &num); if (!((num > 0) && (num <= 100))) { printf("Out of range.\n"); } int su1; float su2; // 전부 변경후의 값으로 출력됨. su1 = 5; ++su1; printf("++su1 = %d\n", su1); su1 = 5; su1++; printf("su1++ = %d\n", su1); su2 = 12.3; ++su2; printf("++su2 = %f\n", su2); su2 = 12.3; su2++; printf("su2++ = %f\n", su2); int su1, su2, su3; su1 = 10; su2 = ++su1; su1 = 10; su3 = su1++; printf("su2 = %d\n", su2); printf("su3 = %d\n", su3); int su; printf("Enter any number :"); scanf_s("%d", &su); su % 2 == 0 ? printf("%d : 짝수\n", su) : printf("%d : 홀수\n", su); printf("Enter any number again :"); scanf_s("%d", &su); su % 2 == 0 ? printf("%d : 짝수\n", su) : printf("%d : 홀수\n", su); // 비트연산은 안합니다. int su; printf("Enter any number :"); scanf_s("%d", &su); su % 3 == 0 ? printf("%d : 3의 배수\n", su) : printf("%d : 그냥 숫자\n", su); int su1, su2; printf("Enter two numbers :"); scanf_s("%d%d", &su1, &su2); su1 > su2 ? printf("%d > %d\n", su1, su2) : printf("%d < %d\n", su1, su2); int su1, su2, su3; printf("Enter three numbers :"); scanf_s("%d%d%d", &su1, &su2, &su3); su1 > su2 ? su1 > su3 ? printf("%d is the biggest number.\n", su1) : printf("%d is the biggest number.\n", su3) : su2 > su3 ? printf("%d is the biggest number.\n", su2) : printf("%d is the biggest number.\n", su3); int su1, su2, max; printf("Enter two numbers :"); scanf_s("%d%d", &su1, &su2); su1 > su2 ? su1 % 2 == 0 ? max = su1 : max = 0 : su2 % 2 == 0 ? max = su2 : max = 0; printf("%d is the biggest even number. Zero means neither two numbers are satisfied conditions.\n", max) int su1, su2; printf("Enter two numbers :"); scanf_s("%d%d", &su1, &su2); int sum = su1 + su2; sum % 6 == 0 ? printf("Yes\n") : printf("No"); int num1 = 1, num2 = 0; if (num1 == 1) printf("True"); if (num2 != 0) printf("False"); int su; printf("Enter any number : "); scanf_s("%d", &su); if (su % 3 == 0) printf("%d : 3의 배수\n", su); int su; printf("Enter any number : "); scanf_s("%d", &su); is_even_or_odd(su); int su; printf("Enter any number : "); scanf_s("%d", &su); show_absolute_value(su); int su1, su2; printf("Enter two numbers :"); scanf_s("%d%d", &su1, &su2); print_max_number(su1, su2); int su1, su2; printf("Enter two numbers :"); scanf_s("%d%d", &su1, &su2); print_even(su1, su2); int su1, su2; printf("Enter two numbers :"); scanf_s("%d%d", &su1, &su2); print_sixth(su1, su2); int su1, su2, su3; printf("Enter two numbers :"); scanf_s("%d%d%d", &su1, &su2, &su3); evaluate_three(su1, su2, su3); int su1, su2, max, min; printf("Enter two numbers :"); scanf_s("%d%d", &su1, &su2); if (su1 > su2) { max = su1; min = su2; } else { max = su2; min = su1; } printf("\n max = %d min = %d", max, min); int su; printf("NUMBER: "); scanf_s("%d", &su); if (su >= 0) { if ((su % 2) == 0) printf("%d : Even Positive", su); else printf("%d : Odd Positive", su); } else printf("%d : Negative", su); printf("\n===END==="); // 홀짝검사 int su; printf("NUMBER: "); scanf_s("%d", &su); if (su % 2 == 0) printf("%d is Even Number.", su); else printf("%d is Odd Number.", su); */ /*// 도시락 요금 int total_pay, ea; const int default_ea = 10; printf("도시락 개수: "); scanf_s("%d", &ea); total_pay = ea * 2500; if (ea > default_ea) total_pay -= (ea - default_ea) * 100; printf("\nTotal Pay: %d WON!", total_pay);*/ /*// 디스켓 int total_pay, ea; printf("디스켓 통 개수: "); scanf_s("%d", &ea); total_pay = ea * 5000; if (ea >= 100) total_pay *= 0.88; else if (ea >= 10) total_pay *= 0.9; printf("\nTotal Pay: %d WON!", total_pay);*/ /*// 성적평가하기 int one, two, three; printf("점수를 입력: "); scanf_s("%d%d%d", &one, &two, &three); const float avg = (float)(one + two + three) / 3; if (avg >= 90) printf("A"); else if (avg >= 80) printf("B"); else if (avg >= 70) printf("C"); else if (avg >= 60) printf("D"); else printf("F");*/ /*// 요금계산 (분단위) int totalPay = 3000, man, useTime; const int default_time = 30; printf("몇 명?: "); scanf_s("%d", &man); printf("말을 얼마나 탔는지 입력하쇼 (minutes): "); scanf_s("%d", &useTime); if (useTime > default_time) totalPay += (useTime - default_time) * 50; printf("\nYour charge is: %d WON!", totalPay * man);*/ /*// 요금계산 (올림) int totalPay = 3000, man, useTime; const int default_time = 30; printf("몇 명?: "); scanf_s("%d", &man); printf("말을 얼마나 탔는지 입력하쇼 (minutes): "); scanf_s("%d", &useTime); if (useTime > default_time) totalPay += (useTime - default_time + 9) / 10 * 500; printf("\n%d Peoples, Your charge is: %d WON!", man, totalPay * man);*/ /*// 요금계산 (반올림) int total_pay = 3000, man, use_time; const int default_time = 30; printf("몇 명?: "); scanf_s("%d", &man); printf("말을 얼마나 탔는지 입력하쇼 (minutes): "); scanf_s("%d", &use_time); if (use_time > default_time) total_pay += (use_time - default_time + 5) / 10 * 500; printf("\n%d Peoples, Your charge is: %d WON!", man, total_pay * man);*/ /*// 요금계산 (버림, 분당 계산) int total_pay = 3000, man, use_time; const int default_time = 30; printf("몇 명?: "); scanf_s("%d", &man); printf("말을 얼마나 탔는지 입력하쇼 (minutes): "); scanf_s("%d", &use_time); if (use_time > default_time) total_pay += (use_time - default_time) / 10 * 500; printf("\n%d Peoples, Your charge is: %d WON!", man, total_pay * man);*/ /*int num; scanf_s("%d", &num); switch (num) { case 1: printf("1입력"); break; case 2: printf("2입력"); break; default: printf("1, 2가 아닌 나머지 입력"); }*/ /*int num, data; while(true) { printf("========================\n"); printf("1. 데이터 입력\n"); printf("2. 데이터 출력\n"); printf("3. 종료\n"); printf("========================\n"); scanf_s("%d", &num); switch (num) { case 1: printf("데이터를 입력하세요.\n"); scanf_s("%d", &data); break; case 2: printf("%d", data); _getch(); break; case 3: exit(1); } system("cls"); }*/ /*int num; scanf_s("%d", &num); switch (num) { case 1: printf("one"); break; case 2: printf("two"); break; case 3: printf("three"); break; default: printf("error"); }*/ /*// 달력 int num; printf("Value: "); scanf_s("%d", &num); num = (num + 6) / 7; switch (num) { case 1: printf("첫째주"); break; case 2: printf("둘째주"); break; case 3: printf("셋째주"); break; case 4: printf("넷째주"); break; case 5: printf("다섯째주"); break; }*/ /*// 선풍기... int num, data = 0; while(true) { switch (data) { case 1 : printf("선풍기 - 미풍\n"); break; case 2: printf("선풍기 - 약풍\n"); break; case 3: printf("선풍기 - 강풍\n"); break; default: printf("선풍기 - 정지\n"); } printf("========================\n"); printf("1. 미풍;\n"); printf("2. 약풍\n"); printf("3. 강풍\n"); printf("4. 정지\n"); printf("?. 프로그램 종료\n"); printf("========================\n"); scanf_s("%d", &num); switch (num) { case 1: data = 1; printf("미풍으로 전환했습니다!"); _getch(); break; case 2: data = 2; printf("약풍으로 전환했습니다!"); _getch(); break; case 3: data = 3; printf("강풍으로 전환했습니다!"); _getch(); break; case 4: data = 0; printf("선풍기를 껐습니다!"); _getch(); break; default: exit(1); } system("cls"); }*/ }
true
d48f28c8857f956357169771edddd5e0f6fab56b
C++
Seretsi/Pencil_Rigger
/src/radiosity.cpp
UTF-8
13,517
2.703125
3
[]
no_license
#include "glCanvas.h" #include "radiosity.h" #include "mesh.h" #include "face.h" #include "glCanvas.h" #include "sphere.h" #include "raytree.h" #include "raytracer.h" #include "utils.h" // ================================================================ // CONSTRUCTOR & DESTRUCTOR // ================================================================ Radiosity::Radiosity(Mesh *m, ArgParser *a) { mesh = m; args = a; num_faces = -1; formfactors = NULL; area = NULL; undistributed = NULL; absorbed = NULL; radiance = NULL; max_undistributed_patch = -1; total_area = -1; Reset(); } Radiosity::~Radiosity() { Cleanup(); cleanupVBOs(); } void Radiosity::Cleanup() { delete [] formfactors; delete [] area; delete [] undistributed; delete [] absorbed; delete [] radiance; num_faces = -1; formfactors = NULL; area = NULL; undistributed = NULL; absorbed = NULL; radiance = NULL; max_undistributed_patch = -1; total_area = -1; } void Radiosity::Reset() { delete [] area; delete [] undistributed; delete [] absorbed; delete [] radiance; // create and fill the data structures num_faces = mesh->numFaces(); area = new float[num_faces]; undistributed = new glm::vec3[num_faces]; absorbed = new glm::vec3[num_faces]; radiance = new glm::vec3[num_faces]; for (int i = 0; i < num_faces; i++) { Face *f = mesh->getFace(i); f->setRadiosityPatchIndex(i); setArea(i,f->getArea()); glm::vec3 emit = f->getMaterial()->getEmittedColor(); setUndistributed(i,emit); setAbsorbed(i,glm::vec3(0,0,0)); setRadiance(i,emit); } // find the patch with the most undistributed energy findMaxUndistributed(); } // ======================================================================================= // ======================================================================================= void Radiosity::findMaxUndistributed() { // find the patch with the most undistributed energy // don't forget that the patches may have different sizes! max_undistributed_patch = -1; total_undistributed = 0; total_area = 0; float max = -1; for (int i = 0; i < num_faces; i++) { float m = glm::length(getUndistributed(i)) * getArea(i); total_undistributed += m; total_area += getArea(i); if (max < m) { max = m; max_undistributed_patch = i; } } assert (max_undistributed_patch >= 0 && max_undistributed_patch < num_faces); } void Radiosity::ComputeFormFactors() { assert (formfactors == NULL); assert (num_faces > 0); formfactors = new float[num_faces*num_faces]; // ===================================== // ASSIGNMENT: COMPUTE THE FORM FACTORS // ===================================== } // ================================================================ // ================================================================ float Radiosity::Iterate() { if (formfactors == NULL) ComputeFormFactors(); assert (formfactors != NULL); // ========================================== // ASSIGNMENT: IMPLEMENT RADIOSITY ALGORITHM // ========================================== // return the total light yet undistributed // (so we can decide when the solution has sufficiently converged) return 0; } // ======================================================================================= // VBO & DISPLAY FUNCTIONS // ======================================================================================= // for interpolation void CollectFacesWithVertex(Vertex *have, Face *f, std::vector<Face*> &faces) { for (unsigned int i = 0; i < faces.size(); i++) { if (faces[i] == f) return; } if (have != (*f)[0] && have != (*f)[1] && have != (*f)[2] && have != (*f)[3]) return; faces.push_back(f); for (int i = 0; i < 4; i++) { Edge *ea = f->getEdge()->getOpposite(); Edge *eb = f->getEdge()->getNext()->getOpposite(); Edge *ec = f->getEdge()->getNext()->getNext()->getOpposite(); Edge *ed = f->getEdge()->getNext()->getNext()->getNext()->getOpposite(); if (ea != NULL) CollectFacesWithVertex(have,ea->getFace(),faces); if (eb != NULL) CollectFacesWithVertex(have,eb->getFace(),faces); if (ec != NULL) CollectFacesWithVertex(have,ec->getFace(),faces); if (ed != NULL) CollectFacesWithVertex(have,ed->getFace(),faces); } } // different visualization modes glm::vec3 Radiosity::setupHelperForColor(Face *f, int i, int j) { assert (mesh->getFace(i) == f); assert (j >= 0 && j < 4); if (args->render_mode == RENDER_MATERIALS) { return f->getMaterial()->getDiffuseColor(); } else if (args->render_mode == RENDER_RADIANCE && args->interpolate == true) { std::vector<Face*> faces; CollectFacesWithVertex((*f)[j],f,faces); float total = 0; glm::vec3 color = glm::vec3(0,0,0); glm::vec3 normal = f->computeNormal(); for (unsigned int i = 0; i < faces.size(); i++) { glm::vec3 normal2 = faces[i]->computeNormal(); float area = faces[i]->getArea(); if (glm::dot(normal,normal2) < 0.5) continue; assert (area > 0); total += area; color += float(area) * getRadiance(faces[i]->getRadiosityPatchIndex()); } assert (total > 0); color /= total; return color; } else if (args->render_mode == RENDER_LIGHTS) { return f->getMaterial()->getEmittedColor(); } else if (args->render_mode == RENDER_UNDISTRIBUTED) { return getUndistributed(i); } else if (args->render_mode == RENDER_ABSORBED) { return getAbsorbed(i); } else if (args->render_mode == RENDER_RADIANCE) { return getRadiance(i); } else if (args->render_mode == RENDER_FORM_FACTORS) { if (formfactors == NULL) ComputeFormFactors(); float scale = 0.2 * total_area/getArea(i); float factor = scale * getFormFactor(max_undistributed_patch,i); return glm::vec3(factor,factor,factor); } else { assert(0); } exit(0); } void Radiosity::initializeVBOs() { // create a pointer for the vertex & index VBOs glGenBuffers(1, &mesh_tri_verts_VBO); glGenBuffers(1, &mesh_tri_indices_VBO); glGenBuffers(1, &mesh_textured_tri_indices_VBO); } void Radiosity::setupVBOs() { HandleGLError("enter radiosity setupVBOs()"); mesh_tri_verts.clear(); mesh_tri_indices.clear(); mesh_textured_tri_indices.clear(); // initialize the data in each vector int num_faces = mesh->numFaces(); assert (num_faces > 0); for (int i = 0; i < num_faces; i++) { Face *f = mesh->getFace(i); Edge *e = f->getEdge(); glm::vec3 normal = f->computeNormal(); double avg_s = 0; double avg_t = 0; glm::vec3 avg_color(0,0,0); int start = mesh_tri_verts.size(); // wireframe is normally black, except when it's the special // patch, then the wireframe is red glm::vec4 wireframe_color(0,0,0,0.5); if (args->render_mode == RENDER_FORM_FACTORS && i == max_undistributed_patch) { wireframe_color = glm::vec4(1,0,0,1); } // add the 4 corner vertices for (int j = 0; j < 4; j++) { glm::vec3 pos = ((*f)[j])->get(); double s = (*f)[j]->get_s(); double t = (*f)[j]->get_t(); glm::vec3 color = setupHelperForColor(f,i,j); color = glm::vec3(linear_to_srgb(color.r), linear_to_srgb(color.g), linear_to_srgb(color.b)); avg_color += 0.25f * color; mesh_tri_verts.push_back(VBOPosNormalColor(pos,normal, glm::vec4(color.r,color.g,color.b,1.0), wireframe_color, s,t)); avg_s += 0.25 * s; avg_t += 0.25 * t; e = e->getNext(); } // the centroid (for wireframe rendering) glm::vec3 centroid = f->computeCentroid(); mesh_tri_verts.push_back(VBOPosNormalColor(centroid,normal, glm::vec4(avg_color.r,avg_color.g,avg_color.b,1), glm::vec4(1,1,1,1), avg_s,avg_t)); if (f->getMaterial()->hasTextureMap()) { mesh_textured_tri_indices.push_back(VBOIndexedTri(start+0,start+1,start+4)); mesh_textured_tri_indices.push_back(VBOIndexedTri(start+1,start+2,start+4)); mesh_textured_tri_indices.push_back(VBOIndexedTri(start+2,start+3,start+4)); mesh_textured_tri_indices.push_back(VBOIndexedTri(start+3,start+0,start+4)); } else { mesh_tri_indices.push_back(VBOIndexedTri(start+0,start+1,start+4)); mesh_tri_indices.push_back(VBOIndexedTri(start+1,start+2,start+4)); mesh_tri_indices.push_back(VBOIndexedTri(start+2,start+3,start+4)); mesh_tri_indices.push_back(VBOIndexedTri(start+3,start+0,start+4)); } } assert ((int)mesh_tri_verts.size() == num_faces*5); assert ((int)mesh_tri_indices.size() + (int)mesh_textured_tri_indices.size() == num_faces*4); // copy the data to each VBO glBindBuffer(GL_ARRAY_BUFFER,mesh_tri_verts_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(VBOPosNormalColor) * num_faces * 5, &mesh_tri_verts[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mesh_tri_indices_VBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(VBOIndexedTri) * mesh_tri_indices.size(), &mesh_tri_indices[0], GL_STATIC_DRAW); if (mesh_textured_tri_indices.size() > 0) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mesh_textured_tri_indices_VBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(VBOIndexedTri) * mesh_textured_tri_indices.size(), &mesh_textured_tri_indices[0], GL_STATIC_DRAW); } HandleGLError("radiosity setupVBOs() just before texture"); // WARNING: this naive VBO implementation only allows a single texture // FIXME: something still buggy about textures int num_textured_materials = 0; for (unsigned int mat = 0; mat < mesh->materials.size(); mat++) { Material *m = mesh->materials[mat]; if (m->hasTextureMap()) { // FIXME: old gl... //glBindTexture(GL_TEXTURE_2D,m->getTextureID()); num_textured_materials++; } } assert (num_textured_materials <= 1); HandleGLError("leave radiosity setupVBOs()"); } void Radiosity::drawVBOs() { // ===================== // DRAW ALL THE POLYGONS assert ((int)mesh_tri_indices.size() + (int)mesh_textured_tri_indices.size() == num_faces*4); // render with Phong lighting? if (args->render_mode == RENDER_MATERIALS) { // yes glUniform1i(GLCanvas::colormodeID, 1); } else { // no glUniform1i(GLCanvas::colormodeID, 0); } // render untextured faces glBindBuffer(GL_ARRAY_BUFFER,mesh_tri_verts_VBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mesh_tri_indices_VBO); glEnableVertexAttribArray(0); glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(VBOPosNormalColor),(void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,sizeof(VBOPosNormalColor),(void*)sizeof(glm::vec3) ); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT,GL_FALSE,sizeof(VBOPosNormalColor), (void*)(sizeof(glm::vec3)*2)); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT,GL_FALSE,sizeof(VBOPosNormalColor), (void*)(sizeof(glm::vec3)*2 + sizeof(glm::vec4))); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT,GL_FALSE,sizeof(VBOPosNormalColor), (void*)(sizeof(glm::vec3)*2 + sizeof(glm::vec4)*2)); glDrawElements(GL_TRIANGLES, mesh_tri_indices.size()*3,GL_UNSIGNED_INT, 0); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); glDisableVertexAttribArray(4); // render faces with textures if (mesh_textured_tri_indices.size() > 0) { // FIXME: there is something buggy with textures still //glUniform1i(GLCanvas::colormodeID, 2); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, GLCanvas::textureID); GLCanvas::mytexture = glGetUniformLocation(GLCanvas::programID, "mytexture"); glUniform1i(GLCanvas::mytexture, /*GL_TEXTURE*/0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mesh_textured_tri_indices_VBO); glEnableVertexAttribArray(0); glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(VBOPosNormalColor),(void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,sizeof(VBOPosNormalColor),(void*)sizeof(glm::vec3) ); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT,GL_FALSE,sizeof(VBOPosNormalColor), (void*)(sizeof(glm::vec3)*2)); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT,GL_FALSE,sizeof(VBOPosNormalColor), (void*)(sizeof(glm::vec3)*2 + sizeof(glm::vec4))); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT,GL_FALSE,sizeof(VBOPosNormalColor), (void*)(sizeof(glm::vec3)*2 + sizeof(glm::vec4)*2)); glDrawElements(GL_TRIANGLES, mesh_textured_tri_indices.size()*3, GL_UNSIGNED_INT, 0); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); glDisableVertexAttribArray(4); //glUniform1i(GLCanvas::colormodeID, 1); } HandleGLError(); } void Radiosity::cleanupVBOs() { glDeleteBuffers(1, &mesh_tri_verts_VBO); glDeleteBuffers(1, &mesh_tri_indices_VBO); glDeleteBuffers(1, &mesh_textured_tri_indices_VBO); glDeleteTextures(1, &GLCanvas::textureID); }
true
4df7a6f5594792488693730da08b0d3e00cfcb53
C++
timothywangdev/Programming-Contests
/notebook/Math/Number Theory/ModularExponentiation.cpp
UTF-8
545
3.765625
4
[]
no_license
/* Modular Exponentiation Computes (base^exp)MOD mod */ // O(log2(N)) LL pow_mod_base2(LL base, LL exp, LL mod){ LL rv=1; base=base%mod; while(exp>0){ if(exp&1){ rv=(rv*base)%mod; } exp>>=1; base=(base*base)%mod; } return rv; } // O(log10(N)) // Useful when 'exp' is a big number LL pow_mod_base10(LL base,string exp,LL mod){ LL rv=1; base=base%mod; for(LL i=exp.length()-1;i>=0;i--){ rv=(rv*pow_mod_base2(base,(int)(exp[i]-'0'),mod))%mod; base=pow_mod_base2(base,10,mod); } return rv; }
true
c66b5f42358dada51b613e093146ebd0428bb996
C++
BlinkingStar7/Problem_Solving
/Study/JongMan_Book/JON1/jlis.cc
UTF-8
945
2.578125
3
[]
no_license
#include <iostream> #include <algorithm> #include <string> #include <vector> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <utility> #include <limits> using namespace std; int C, N, M, Memo[102][102]; long long A[101], B[101]; int Solve (int a, int b) { int &ret = Memo[a+1][b+1]; if (ret != -1) return ret; ret = 2; long long m = numeric_limits<long long>::min(); if (a != -1) m = A[a]; if (b != -1) m = max (m, B[b]); for (int next = a+1; next<N; ++next) if (A[next] > m) ret = max (ret, 1 + Solve(next, b)); for (int next = b+1; next<M; ++next) if (B[next] > m) ret = max (ret, 1 + Solve(a, next)); return ret; } int main () { cin >> C; while (C--) { cin >> N >> M; for (int i=0; i<N; ++i) scanf("%lld", A+i); for (int i=0; i<M; ++i) scanf("%lld", B+i); memset(Memo, -1, sizeof(Memo)); cout << Solve (-1, -1) - 2 << endl; } return 0; }
true
a298037ebdf2dadd8af0e56b371a900fa5178b3f
C++
MichalRuminski/jippCw
/Cwiczenie2/tablica.cpp
UTF-8
2,270
2.96875
3
[]
no_license
#include <cstdlib> #include <ctime> #include <iostream> #include <cmath> #include "tablica.h" Tablica::Tablica() : Tablica::Tablica(10){ /* this->n = 10; this->wsk = new int[10]; if(this->wsk){ int i = 0; while(i < this->n){ this->wsk[i] = 0; i++; } } */ } Tablica::Tablica(int n){ this->n = n; this->wsk = new int[n]; if(this->wsk){ int i = 0; while(i < this->n){ this->wsk[i] = 0; i++; } } } Tablica::Tablica(const Tablica &t){ this->n = t.n; this->wsk = new int[this->n]; if(this->wsk){ int i = 0; while(i < t.n){ this->wsk[i] = t.wsk[i]; i++; }} } Tablica::~Tablica(){ delete[] wsk; } int Tablica::get(int i){ if(i < n) return this->wsk[i]; } void Tablica::set(int i, int value){ if(i < n) this->wsk[i] = value; } void Tablica::losuj(){ int i = 0; while (i < n) { this->wsk[i] = rand() % 10 + 1; i++; } } void Tablica::wypisz(){ for(int i = 0; i < n; i++){ std::cout << "Element " << i << ": " << wsk[i] << " "; } std::cout << std::endl; } float Tablica::avg(){ int s = 0; for(int i = 0; i < n; i++){ s +=wsk[i]; } return s/(float)n; } double Tablica::geom(){ int il = 1; for(int i = 0; i < n; i++){ il *= wsk[i]; } return pow(il, 1.0f/n); } int Tablica::minimum(){ int min = wsk[0]; for(int i = 1; i < n; i++){ if(min > wsk[i]){ min = wsk[i]; } } return min; } int Tablica::maksimum(){ int max = wsk[0]; for(int i = 1; i < n; i++){ if(max < wsk[i]){ max = wsk[i]; } } return max; } void Tablica::sortuj(){ int max = 0; int tmp; for(int i = 0; i < n; i++){ max = i; for(int j = i +1; j < n; j++){ if(wsk[i] > wsk[j]){ tmp = wsk[i]; wsk[i] = wsk[j]; wsk[j] = tmp; } } } } float Tablica::mediana(){ this->sortuj(); if(n%2 > 0){ return wsk[n/2]; } return (wsk[n/2] + wsk[n/2 -1])/2.0f; }
true
37a23e1548078e9e33cc424f0ec8024aa6b03144
C++
ziyuhuang/BankingSystem
/CheckingAccount.cpp
UTF-8
994
2.96875
3
[]
no_license
// // CheckingAccount.cpp // BankingSystem // // Created by ZIYU HUANG on 11/27/16. // Copyright © 2016 ZIYU HUANG. All rights reserved. // #include <stdio.h> #include "CheckingAccount.h" using namespace InvalidInput; using namespace NotEnoughBalance; CheckingAccount::CheckingAccount(int theId, float theBalance, string thePassword, Customer theCustomer) :Account(theId, theBalance, thePassword, theCustomer){} bool CheckingAccount::withdraw(WithdrawTransaction transaction){ try{ if(transaction.getAmount() < 0) throw InputError(); if(transaction.getAmount() > getBalance()) throw BalanceError(); } catch(InputError e){ cout << "Amount can not be negative. Invaild transaction." << endl; return false; }catch(BalanceError e){ cout << "Not enough balance. Invaild transaction." << endl; return false; } setBalance(getBalance() - transaction.getAmount()); addWithdrawTransaction(transaction); return true; }
true
e7152eb281b3b753985cde9f33ac9b8e798a86c6
C++
TheLastGimbus/cpu-fan-driver-arduino
/src/main.cpp
UTF-8
734
2.96875
3
[]
no_license
#include <Arduino.h> #define FAN_PIN 13 #define CYCLE_MS 1000 byte currentVal = 127; void slowPWM(byte pin, byte value) { int on = float(CYCLE_MS) * (value / 255.0); int off = CYCLE_MS - on; if (on > 0) { digitalWrite(pin, 1); delay(on); } if (off > 0) { digitalWrite(pin, 0); delay(off); } } void setup() { Serial.begin(9600); pinMode(FAN_PIN, OUTPUT); } void loop() { while (Serial.available()) { int newVal = Serial.read(); if (newVal >= 0 && newVal < 256) { Serial.print(1); currentVal = newVal; } else { Serial.print(0); } Serial.flush(); } slowPWM(FAN_PIN, currentVal); }
true
9419c6f3d0e8444898483a444bc3258191c53cff
C++
ttrebuchon/BareBonesOS
/Utils/detail/BinaryTree.hh
UTF-8
3,151
2.96875
3
[]
no_license
#ifndef INCLUDED_BINARYTREE_HH #define INCLUDED_BINARYTREE_HH namespace Utils { namespace detail { namespace binary_tree { template <class = void> class _NodeBase { public: size_t size; mutable _NodeBase *left, *right, *parent; _NodeBase(); }; typedef _NodeBase<void> NodeBase; template <class T, class Comp> class Node : public NodeBase { private: typedef Node<T, Comp> Self; public: T value; Node() = default; template <class... Args> Node(Args... args) : NodeBase(), value(Utils::forward<Args>(args)...) {} template <class NAlloc> void destroyChildren(NAlloc&); Node* sibling() noexcept { if (parent) { if (parent->left == this) { return (Node*)parent->right; } else if (parent->right == this) { return (Node*)parent->left; } } return nullptr; } const Node* sibling() const noexcept { if (parent) { if (parent->left == this) { return (Node*)parent->right; } else if (parent->right == this) { return (Node*)parent->left; } } return nullptr; } bool is_left() const noexcept { return (parent && parent->left == this); } bool is_right() const noexcept { return (parent && parent->right == this); } __attribute__((__always_inline__)) Node* r() noexcept { return ((Node*)right); } __attribute__((__always_inline__)) const Node* r() const noexcept { return ((const Node*)right); } __attribute__((__always_inline__)) Node* l() noexcept { return ((Node*)left); } __attribute__((__always_inline__)) const Node* l() const noexcept { return ((const Node*)left); } __attribute__((__always_inline__)) Node* p() noexcept { return ((Node*)parent); } __attribute__((__always_inline__)) const Node* p() const noexcept { return ((const Node*)parent); } }; template <class T, class Comp, class Alloc = Allocator<T>> class BinaryTree { protected: typedef Node<T, Comp> _Node; typedef typename Alloc::template rebind<_Node>::other node_allocator_type; typedef Alloc allocator_type; _Node* root; Comp comp; allocator_type alloc; node_allocator_type nalloc; public: typedef _Node node; BinaryTree(const allocator_type& = allocator_type()); ~BinaryTree(); template <class Key> _Node* find(const Key&) const; template <class Key> _Node** findCreate(const Key&, _Node** parent = nullptr); template <class... Args> void create(_Node* parent, _Node*& branch, Args&&...); BinaryTree* clone() const; void destroy(allocator_type&); size_t size() const; _Node* root_node() noexcept { return root; } const _Node* root_node() const noexcept { return root; } const node_allocator_type& get_node_allocator() const noexcept { return nalloc; } const allocator_type& get_allocator() const noexcept { return alloc; } }; } } } #endif
true
e8b637e549e47d03b1224923a3b2432aa78cd556
C++
PLaceBos/Lab3.2
/Journal.cpp
UTF-8
639
3.53125
4
[]
no_license
#include "Journal.h" Journal::Journal(string name1, int year1, int number1):Edition(name1, year1){ if(!SetNumber(number1)) number = 0; } Journal::Journal(){ number = 0; } Journal::Journal(const Journal &b){ name = b.name; year = b.year; number = b.number; } bool Journal::SetNumber(int number1){ if (number1 < 0) return false; else number = number1; return true; } int Journal::GetNumber() const{ return number; } void Journal::print() const{ cout << "Name: " << name << endl; cout << "Year: " << year << endl; cout << "Number: " << number << endl; }
true
77cdbfbfb83ffeead0851dcd837cc423bef981fe
C++
nreynoldson/Text-Based-Survival-Game
/Beach.cpp
UTF-8
2,576
3.359375
3
[]
no_license
/****************************************************************************** * Program Name: Final Project - Marooned - Beach Class Implementation File * Date: 8/13/19 * Name: Nicole Reynoldson * Description: Beach class allows strings to be passed in as parameters so * that each beach space can be initialized with a different item and a new * prompt for exploring that item. Has unique space action that allows fishing. * An int is passed in as a parameter to initialize the probability of catching * a fish. * ****************************************************************************/ #include "Beach.hpp" using std::cout; using std::endl; using std::string; /******************************************************************************* * Description: Constructor allows for placement of items on the square and * varying levels of fishing probability. Initializes all space specific * attributes. * ****************************************************************************/ Beach::Beach(Player* survivor, string item, string prompt, int fishProb): Space(survivor) { this->item = item; this->fishProb = fishProb; actionItem = "Fishing pole"; actionDesc = "Fish"; spaceType = "Beach"; explorePrompt = prompt; } /******************************************************************************* * Description: Outputs a description of the square whenever the player enters. * ****************************************************************************/ void Beach::enterSpace() { printStars(); cout << "You find yourself on a beautiful pristine sandy beach. Palm trees" " shade you,\nsoft waves lap the shore and you see fish jumping in" " the distance."; printStars(); } /******************************************************************************* * Description: Attempts to allow the user to fish. If the action causes the * user health to dip below 0, the user will be prompted. * ****************************************************************************/ void Beach::spaceAction() { survivor->updateHealth(ACTION); if(!(survivor->isDead())) { printStars(); cout << "You cast your line out into the ocean and wait..."; int N = randomNumber(1, 100); //Catch a fish and add to bag if(N <= fishProb) { cout << "You caught a fish!\n"; bag->addItem("Fish"); printStars(); } //No fish have been caught else { cout << "\nLooks like they aren't biting much."; printStars(); } } else { printStars(); cout << "You tried to fish and you died from overexertion!"; } }
true
318466618f6ba1fd304add2e5e54c490813a30c7
C++
felixb/ardor
/ardor.ino
UTF-8
2,286
2.859375
3
[ "MIT" ]
permissive
// inputs const int BUTTON = 10; const int GATE = 11; const int GATE_OPEN = HIGH; // outputs const int LED_BUTTON = 13; const int RELAY_CTRL = 8; const int RELAY_OFF = HIGH; const int RELAY_ON = LOW; // consts const int STATE_OFF = 0; const int STATE_INIT = 1; const int STATE_READY = 2; const int STATE_OPEN = 3; const unsigned long STATE_READY_DURATION = 60000; const unsigned long LOOP_DELAY = 100; const unsigned long RING_DELAY = 500; const unsigned long BLINK_SLOW_FREQ = 2000; const unsigned long BLINK_FAST_FREQ = 1000; // variables int state = STATE_OFF; unsigned long initStart = 0; void setup() { Serial.begin(9600); pinMode(BUTTON, INPUT); pinMode(GATE, INPUT); pinMode(LED_BUTTON, OUTPUT); pinMode(RELAY_CTRL, OUTPUT); digitalWrite(LED_BUTTON, LOW); digitalWrite(RELAY_CTRL, RELAY_OFF); } void loop() { delay(LOOP_DELAY); if (digitalRead(BUTTON) == LOW) { if (state != STATE_OFF) { stateChangeOff(); } } else { if (state == STATE_OFF) { stateChangeInit(); } if (state == STATE_INIT) { unsigned long t = millis(); if (t - initStart > STATE_READY_DURATION) { stateChangeReady(); } else { blinkButton(BLINK_SLOW_FREQ); } } if (state == STATE_READY or state == STATE_OPEN) { blinkButton(BLINK_FAST_FREQ); } if (state == STATE_READY and digitalRead(GATE) == GATE_OPEN) { stateChangeOpen(); } if (state == STATE_OPEN and digitalRead(GATE) != GATE_OPEN) { stateChangeReady(); } } } void stateChangeOff() { Serial.println("State OFF"); state = STATE_OFF; digitalWrite(LED_BUTTON, LOW); } void stateChangeInit() { Serial.println("State INIT"); state = STATE_INIT; initStart = millis(); } void stateChangeReady() { Serial.println("State READY"); state = STATE_READY; digitalWrite(LED_BUTTON, HIGH); } void stateChangeOpen() { Serial.println("State OPEN"); state = STATE_OPEN; ringBell(); } void blinkButton(unsigned long freq) { if (millis() % freq > freq >> 1) { digitalWrite(LED_BUTTON, HIGH); } else { digitalWrite(LED_BUTTON, LOW); } } void ringBell() { Serial.println("RING RING"); digitalWrite(RELAY_CTRL, RELAY_ON); delay(RING_DELAY); digitalWrite(RELAY_CTRL, RELAY_OFF); }
true
63ab55f7bf365e9e957fd609d710084939e99af5
C++
ChristopherBric/PROYECTO-01_Programaci-n_Orientada_a_Objetos_I
/main.cpp
UTF-8
1,524
2.578125
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <ctime> #include <cstdlib> #include <ctime> #include <cstdlib> #include <typeinfo> #include "Funciones.h" using namespace std; int main() { int Selec; char M_ingles[7][7] = { {' ',' ','O','O','O',' ',' '}, {' ',' ','O','O','O',' ',' '}, {'O','O','O','O','O','O','O'}, {'O','O','O','+','O','O','O'}, {'O','O','O','O','O','O','O'}, {' ',' ','O','O','O',' ',' '}, {' ',' ','O','O','O',' ',' '}}; char M_aleman[9][9] = { {' ',' ',' ','O','O','O',' ',' ',' '}, {' ',' ',' ','O','O','O',' ',' ',' '}, {' ',' ',' ','O','O','O',' ',' ',' '}, {'O','O','O','O','O','O','O','O','O'}, {'O','O','O','O','+','O','O','O','O'}, {'O','O','O','O','O','O','O','O','O'}, {' ',' ',' ','O','O','O',' ',' ',' '}, {' ',' ',' ','O','O','O',' ',' ',' '}, {' ',' ',' ','O','O','O',' ',' ',' '}}; char M_frances[7][7] = {{' ',' ','O','O','O',' ',' '}, {' ','O','O','O','O','O',' '}, {'O','O','O','+','O','O','O'}, {'O','O','O','O','O','O','O'}, {'O','O','O','O','O','O','O'}, {' ','O','O','O','O','O',' '}, {' ',' ','O','O','O',' ',' '} }; Selec = Menu(); switch (Selec) { case 1: Juego_Frances(M_frances); break; case 2: Juego_Aleman(M_aleman); break; case 3: Juego_Ingles(M_ingles); break; case 0: return 0; break; } }
true
749bae957cb09f24a944d2b6aa2a52c775ace9e3
C++
kimgibaam/Algorithm
/Baekjoon Online Judge/브루트 포스(n과m)/15666. n과m(12).cpp
UTF-8
656
2.796875
3
[]
no_license
#include<iostream> #include<algorithm> #include<vector> #include<string> #include<map> using namespace std; int N, M; vector<int> v; vector<int> picked; map<int, int> m; void solve(int cnt, int idx) { if (cnt == M) { for (int i = 0; i < M; i++) { cout << picked[i] << " "; } cout << "\n"; return; } for (int i = idx; i < v.size(); i++) { picked.push_back(v[i]); solve(cnt + 1, i); picked.pop_back(); } } int main() { cin >> N >> M; for (int i = 0; i < N; i++) { int temp; cin >> temp; if (m[temp] == 0) { m[temp] = 1; v.push_back(temp); } else m[temp]++; } sort(v.begin(), v.end()); solve(0,0 ); return 0; }
true
9d2bbc65d8e8eb024744ff479663a05da42a1cff
C++
xuyouchun/skyever
/SkyJs/DBLLIST.CPP
UTF-8
3,462
3.09375
3
[]
no_license
#include "DblList.h" DblList::DblList() { this->Begin = NULL; this->Point = NULL; this->Count = 0; } DblList::~DblList() { ListItem *p = Begin; while(p!=NULL) { ListItem *p0 = p->next; delete p; p = p0; } } void DblList::Delete(void *ptr) { ListItem *p = this->Begin; while(p!=NULL) { if(p->Content==ptr) { ListItem *previous = p->previous; ListItem *next = p->next; if(p==this->Begin) { this->Begin = next; next->previous = this->Begin; } else { previous->next = next; if(next!=NULL) next->previous = previous; } if(p==this->Point) this->Point = this->Begin; delete p; this->Count --; break; } p = p->next; } } DblList::ListItem * DblList::CreateItem(void *ptr) { return new ListItem(ptr); } DblList::ListItem *DblList::Insert(void *ptr, void *pos) { ListItem *item = NULL; if(Begin==NULL) { item = CreateItem(ptr); Begin = item; Count ++; } else if(pos==NULL) { item = CreateItem(ptr); ListItem *p0 = Begin; while(p0->next!=NULL) p0 = p0->next; p0->next = item; item->previous = p0; Count ++; } else { ListItem *p0 = Begin; while(p0!=NULL) { if(p0->Content==pos) { item = CreateItem(ptr); ListItem *p1 = p0->next; if(p1!=NULL) { p1->previous = item; item->next = p1; } p1->next = item; item->previous = p1; Count ++; break; } p0 = p0->next; } } if(this->Point==NULL && this->Begin!=NULL) this->Point = this->Begin; return item; } BOOL DblList::Move(int pos) { if(pos>=this->Count) return FALSE; if(pos<0) return FALSE; this->Point = this->Begin; for(register int k=0; k<pos; k++) Point = Point->next; return TRUE; } BOOL DblList::Move(void *pos) { ListItem *p = this->Begin; while(p!=NULL) { if(p->Content==pos) { this->Point = p; return TRUE; } p = p->next; } return FALSE; } BOOL DblList::MoveNext() { if(this->Point==NULL) return FALSE; if(this->Point->next==NULL) return FALSE; this->Point = this->Point->next; return TRUE; } BOOL DblList::MovePrevious() { if(this->Point==NULL) return FALSE; if(this->Point->previous==NULL) return FALSE; this->Point = this->Point->previous; return TRUE; } void *DblList::GetContent(int Index) { if((unsigned int)Index==0xFFFF) { if(this->Point==NULL) return NULL; else return this->Point->Content; } else { ListItem *p = this->Begin; if(p==NULL) return NULL; for(register int k=0; k<Index; k++) { if(p==NULL) return NULL; else p = p->next; } if(p==NULL) return NULL; else return p->Content; } } int DblList::GetCursor() { if(this->Begin==NULL) return 0xFFFF; ListItem *p = this->Begin; int Cursor = 0; while(p!=NULL) { if(p==this->Point) return Cursor; Cursor ++; p = p->next; } return 0xFFFF; } int DblList::GetIndex(void *ptr) { if(this->Begin==NULL) return 0xFFFF; ListItem *p = this->Begin; int Index = 0; while(p!=NULL) { if(p->Content==ptr) return Index; Index ++; p = p->next; } return 0xFFFF; } //////////////////////////// struct ListItem /////////////////////////// DblList::ListItem::ListItem(void *Content) { this->Content = Content; this->previous = NULL; this->next = NULL; }
true
a39c61ec8a566a383a5844ea7ea893fed5bf5b0a
C++
Falcons-Robocup/code
/tools/multiCamCalibrate/src/optiCalMain.cpp
UTF-8
2,086
2.8125
3
[ "Apache-2.0" ]
permissive
/* * optiCalMain.cpp * * Optical Calibration. * Command-line utility to calibrate a multiCam assembly (camera 0,1,2,3 in sequence). * Result is a set of binary calibration files in the data repo, which should then be configured to load from multiCam at init time. * * Created on: May 2018 * Author: Jan Feitsma */ #include "optiCal.hpp" #include <string> bool hasEnding (std::string const &fullString, std::string const &ending) { if (fullString.length() >= ending.length()) { return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending)); } else { return false; } } int main(int argc, char **argv) { // setup video source multiCamVideoFeed m; opticalCalibrator optiCal; // arg parsing for (int it = 1; it < argc; ++it) { std::string arg = argv[it]; if (arg.size() > 2) { if (hasEnding(arg, ".bin")) { // select camera for landmarks int camId = (arg[arg.size()-5] - '0'); optiCal.selectCamera(camId); optiCal.load(arg); } if (hasEnding(arg, ".jpg") || hasEnding(arg, ".png")) { m.setStill(arg); } if (hasEnding(arg, "usb") || hasEnding(arg, "USB")) { m.setUsb(2); // webcam on HP Zbook G3 available through /dev/video2 } if (hasEnding(arg, "usb0") || hasEnding(arg, "USB0")) { m.setUsb(0); } if (hasEnding(arg, "usb1") || hasEnding(arg, "USB1")) { m.setUsb(1); } if (hasEnding(arg, "usb2") || hasEnding(arg, "USB2")) { m.setUsb(2); } if (hasEnding(arg, "pylon") ) { optiCal.setPylon(); m.setPylon(); } } } // connect and run optiCal.connectVideo(&m); optiCal.run(); return 0; }
true
8d0aab7bd7c98da0584aa2db2ca5fd3b70065f6d
C++
finnff/se
/week4/match.hpp
UTF-8
519
3.15625
3
[]
no_license
#ifndef _MATCH_HPP #define _MATCH_HPP #include <iostream> // a match found in the previously processed characters: // the start offset (negative), and the number of characters struct match { int offset; int length; match(int offset = 0, int length = 0) : offset(offset), length(length) {} friend std::ostream& operator<<(std::ostream& lhs, const match& m) { return lhs << "[" << m.offset << ";" << m.length << "]"; } bool operator<(const match& rhs) const { return length < rhs.length; } }; #endif
true
f121f8b5c3397593624a1bcff05aac8d4386097e
C++
waynehpc/SWCompiler
/src/codegen/utils/image.h
UTF-8
2,988
3.21875
3
[]
no_license
/************************************************************************* > File Name: image.h > Author: wayne > Mail: > Created Time: 四 1/24 15:15:53 2019 ************************************************************************/ #include <algorithm> #include <fstream> #include <iostream> #include <vector> unsigned load(float *data, size_t size, size_t offset, std::string inputFile) { std::ifstream input(inputFile, std::ios::binary); if (!input.is_open()) { std::cout << "Error loading " << inputFile << "\n"; std::exit(EXIT_FAILURE); } std::vector<char> binData((std::istreambuf_iterator<char>(input)), (std::istreambuf_iterator<char>())); float *dataAsFloatPtr = reinterpret_cast<float *>(&binData[0]); dataAsFloatPtr += offset; for (size_t i = 0; i < size; i++) { data[i] = dataAsFloatPtr[i]; } input.close(); return size; } template <typename T> void store(T *data, size_t size, std::string outFile) { std::ofstream output(outFile, std::ios::binary); if (!output.is_open()) { std::cout << "Error opening " << outFile << "\n"; std::exit(EXIT_FAILURE); } char *dataAsCharPtr = reinterpret_cast<char *>(data); std::vector<char> tmpVector(dataAsCharPtr, dataAsCharPtr + sizeof(T) * size); std::copy(tmpVector.begin(), tmpVector.end(), std::ostreambuf_iterator<char>(output)); output.close(); } template <typename T> unsigned loadLabel(T *data, size_t size, size_t offset, std::string inputFile) { std::ifstream input(inputFile, std::ios::binary); if (!input.is_open()) { std::cout << "Error loading " << inputFile << "\n"; std::exit(EXIT_FAILURE); } std::vector<char> binData((std::istreambuf_iterator<char>(input)), (std::istreambuf_iterator<char>())); char *dataAsCharPtr = reinterpret_cast<char *>(&binData[0]); dataAsCharPtr += offset; for (size_t i = 0; i < size; i++) { data[i] = dataAsCharPtr[i]; } return size; } template <class ElemTy> static char valueToChar(ElemTy val) { char ch = ' '; if (val > 0.2) { ch = '.'; } if (val > 0.4) { ch = ','; } if (val > 0.6) { ch = ':'; } if (val > 0.8) { ch = 'o'; } if (val > 1.0) { ch = 'O'; } if (val > 1.5) { ch = '0'; } if (val > 2.0) { ch = '@'; } if (val < -0.1) { ch = '-'; } if (val < -0.2) { ch = '~'; } if (val < -0.4) { ch = '='; } if (val < -1.0) { ch = '#'; } return ch; } void dumpAscii(float *data, int h, int w) { for (size_t x = 0; x < h; x++) { for (size_t y = 0; y < w; y++) { float val = data[x * w + y]; std::cout << valueToChar(val); } std::cout << "\n"; } }
true
80ae7ae71e02e7f51da914d3e8b0b13e19da2a0c
C++
Alburgerto/ECS
/CCollider.h
UTF-8
1,238
2.765625
3
[]
no_license
#pragma once #include "Component.h" class SystemManager; enum class Direction { Left, Right, Up, Down }; // Holds information about AABB (collision box) of entity to have collision with other entities with collider components. // Intersection checking happens @ SCollider class CCollider : public Component { public: CCollider(); CCollider(SystemManager* l_systemManager); sf::IntRect& getAABB(); void setPosition(const sf::Vector2f& l_position); void setCollision(Direction l_direction, bool l_collision); void resetCollisions(); // Disables all collisions bool getCollision(Direction l_direction); bool isDebug(); sf::RectangleShape& getDebugRect(); void readComponent(std::stringstream& l_line, std::shared_ptr<Entity> l_entity = nullptr); private: void initialize(); bool m_debug; int m_yOffset; sf::RectangleShape m_debugRect; sf::IntRect m_AABB; // will hold (x, y) + (width, length) of collision box. sf::Vector2i m_size; // Size of AABB box, kept as member of the class as it won't change (position will) std::unordered_map<Direction, bool> m_collisions; // int = number of overlapping pixels. If 0 -> no collision in that direction SystemManager* m_systemManager; };
true
6af1d62caafa5c3584132bba30e39b9727b3af3e
C++
pnyennhi/arduino
/wifi_station.ino
UTF-8
2,644
2.625
3
[]
no_license
#include "FirebaseESP8266.h" #include <ESP8266WiFi.h> #include <SoftwareSerial.h> #define FIREBASE_HOST "arduino-8c50c.firebaseio.com" #define FIREBASE_AUTH "J7zkUrrpTavPoK2JohrHWx2x6YGdOqeSOpNn0q5j" #define WIFI_SSID "Dong123" #define WIFI_PASSWORD "123456777" SoftwareSerial NodeMCU(D2,D3); //Define FirebaseESP8266 data object FirebaseData firebaseData; float temp_setup,humi_setup, h, t; byte hour, minute; void setup() { // Thiết lập truyền dữ liệu nối tiếp ở tốc độ 115200 bits/s Serial.begin(115200); NodeMCU.begin(115200); pinMode(D2,INPUT); pinMode(D3,OUTPUT); delay(10); Serial.print("Connecting to "); // Thiết lập ESP8266 ở chế độ station và kết nối đến mạng wifi đã chỉ định WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // Đoạn code in ra dấu . nếu ESP8266 chưa được kết nối while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // In ra dòng "WiFi connected" và địa chỉ IP của ESP8266 Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); Firebase.reconnectWiFi(true); } void loop() { Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); //Lay nhiet do do am tu arduino if(NodeMCU.available()<=0)Serial.println("Ko duoc"); if(NodeMCU.available()>0) { h = NodeMCU.parseFloat(); t = NodeMCU.parseFloat(); hour = NodeMCU.parseInt(); minute = NodeMCU.parseInt(); Serial.println(h); Serial.println(t); Serial.println(hour); Serial.println(minute); } delay(1000); // Lay du lieu tu Firebase if (Firebase.getFloat(firebaseData, "/setup/temperature")) { Serial.println("----------Get result-----------"); temp_setup = firebaseData.floatData(); } else { Serial.println("----------Can't get data--------"); Serial.println("REASON: " + firebaseData.errorReason()); Serial.println("--------------------------------"); Serial.println(); } if (Firebase.getFloat(firebaseData, "/setup/humidity")) { Serial.println("----------Get result-----------"); humi_setup = firebaseData.floatData(); } else { Serial.println("----------Can't get data--------"); Serial.println("REASON: " + firebaseData.errorReason()); Serial.println("--------------------------------"); Serial.println(); } //Serial.println(temp_setup); //Serial.println(humi_setup); }
true
86b6d157271c59bd8f3fa0b007c3a605031812a7
C++
CGSkill/workbook
/TestV4L2/videodevice.cpp
UTF-8
7,256
2.859375
3
[]
no_license
#include "videodevice.h" videodevice::videodevice() { this->fd = -1; this->iCount = 4; this->iIndex = -1; this->buffers = nullptr; } videodevice::~videodevice() { } int videodevice::open_device() { this->fd = open(DEVICE_NAME,O_RDWR,0); if (-1 == this->fd){ perror("open error"); return -1; } return 0; } int videodevice::close_device() { if (-1 == close(this->fd)) { return -1; } return 0; } int videodevice::init_device() { //查询v4l2设备驱动的功能,例如设备驱动名,总线信息,版本信息等 struct v4l2_capability cap; //V4L2 驱动功能 memset(&cap, 0, sizeof (cap)); if (-1 == ioctl(this->fd, VIDIOC_QUERYCAP, &cap)) //查询驱动功能 { perror("ioctl VIDIOC_QUERYCAP error !"); return -1; } if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) return -1; if (!(cap.capabilities & V4L2_CAP_STREAMING)) return -1; //可以打印v4l2设备的相关信息 printf("Capability inframtions: \n"); printf("driver: %s \n", cap.driver); printf("card: %s \n", cap.card); printf("bus_info: %s \n", cap.bus_info); printf("version: %08X \n", cap.version); printf("capability: %08X \n",cap.capabilities); //设置视频捕获格式,设置视频图像数据长,宽,图像格式(如 JPEG, YUYV等) struct v4l2_format fmt; //设置获取视频的格式 memset(&fmt, 0 , sizeof (fmt)); //将结构体清空 //视频数据流类型,永远都是V4L2_BUF_TYPE_VIDEO_CAPTURE fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV; //视频源的格式为JPEG或YUYV或RGB fmt.fmt.pix.width = 320; //设置视频宽度 fmt.fmt.pix.height = 240; //设置视频高度 fmt.fmt.pix.field = V4L2_FIELD_INTERLACED; //设置区域 if ( -1 == ioctl(this->fd, VIDIOC_S_FMT, &fmt)) //设置视频捕捉格式 { perror("ioctl VIDIOC_S_FMT ERROR"); return -1; } return 0; } int videodevice::init_mmap() { //申请内核帧缓存 struct v4l2_requestbuffers req; //向内核申请帧缓冲的请求 memset(&req, 0, sizeof (req)); req.count = this->iCount; //缓存数量,既可保存的图片数量 //数据类型,永远都是 V4L2_BUF_TYPE_VIDEO_CAPTURE req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; /*存储类型:V4L2_MEMORY_MMAP 或 V4L2_MEMORY_USERPTR *这里采用内存映射的方式 */ req.memory = V4L2_MEMORY_MMAP; //VIDIOC_REQBUFS 表示分配内存,调用ioctl使用配置生效 if ( -1 == ioctl(this->fd, VIDIOC_REQBUFS, &req)) { perror("ioctl VIDIOC_REQBUFS error"); exit(-1); } //到这里,我们已经有了内核帧缓存 if (req.count < 2) //起检测的作用,保证帧缓存数量大于1(实际测试过程中1个好像不行) { return -1; } /*在用户空间申请count个 VideoBuffer 数据类型的空间,每一个都是由起始地址和空间长度组成,其中start保存等下内存之后返回的 * 内存首地址 */ this->buffers = (VideoBuffer *)calloc(req.count, sizeof (VideoBuffer)); unsigned int numBufs = 0; for (numBufs = 0; numBufs < req.count; numBufs++) //映射所有的缓存 { struct v4l2_buffer buf; //驱动中的一帧,保存内核中缓冲帧的相关信息结构体 memset(&buf, 0 , sizeof (buf)); //数据流类型,永远都是V4L2_BUG_TYPE_VIDEO_CAPTURE buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; //存储类型:V4L2_MEMORY_MMAP(内存映射)或 V4L2_MEMORY_USERPTR (用户指针) buf.memory = V4L2_MEMORY_MMAP; buf.index = numBufs; //帧号 //获得相应帧号的缓冲帧信息,并保存在v4l2_buf结构体变量buf中 if (-1 == ioctl(fd, VIDIOC_QUERYBUF, &buf)) { perror("ioctl VIDIOC_QUERYBUF error"); return -1; } buffers[numBufs].length = buf.length; //用户空间的长度 //使用mmap函数将申请的缓存帧地址映射到用户空间 buffers[numBufs].start = (unsigned char *)mmap(nullptr,buf.length,PROT_READ | PROT_WRITE, MAP_SHARED,fd,buf.m.offset); if (buffers[numBufs].start == MAP_FAILED) { perror("mmap error \n"); return -1; } } return 0; } int videodevice::init_v4l2() //初始化 v4l2 设备 { if (-1 == init_device()) return -1; //初始化设备 if (-1 == init_mmap()) return -1; //初始化内存 return 0; } int videodevice::start_capturing() //开始视频采集 { unsigned int i; for ( i = 0; i< iCount; ++i) { struct v4l2_buffer buf; memset(&buf, 0, sizeof (buf)); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = i; //将申请到的帧缓冲入队列,以便存储采集到的数据 if (-1 == ioctl(fd,VIDIOC_QBUF,&buf)) { perror("ioctl VIDIOC_QBUF error"); return -1; } } enum v4l2_buf_type type; //开始视频采集 //数据流类型,永远都是 V4L2_BUF_TYPE_VIDEO_CAPTURE type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (ioctl(fd, VIDIOC_STREAMON,&type) < 0) //采集视频 { perror("ioctl VIDIOC_STREAMON error"); return -1; } return 0; } int videodevice::stopt_capturing() //停止视频采集 { enum v4l2_buf_type type; //数据流类型,永远都是 V4L2_BUF_TYPE_VIDEO_CAPTURE type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (ioctl(fd, VIDIOC_STREAMOFF, &type) < 0) { perror("ioctl VIDIOC_STREAMOFF error"); return -1; } return 0; } int videodevice::get_frame(void **frame_buf, int * len) { struct v4l2_buffer buf; memset(&buf, 0, sizeof (buf)); //数据流类型,永远都是 V4L2_BUF_TYPE_VIDEO_CAPTURE buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; //存储类型:V4L2_MEMORY_MMAP(内存映射)或 V4L2_MEMORY_USERPTR (用户指针) buf.memory = V4L2_MEMORY_MMAP; if (ioctl(fd,VIDIOC_DQBUF,&buf) < 0) //从缓存队列取出一个已经保存有一个帧视频数据的缓冲区 { perror("ioctl VIDIOC_DQBUF failed"); return -1; } *frame_buf = buffers[buf.index].start; *len = buffers[buf.index].length; iIndex = buf.index; return 0; } int videodevice::unget_frame() { if (iIndex != -1) { struct v4l2_buffer buf; memset(&buf, 0, sizeof (buf)); //数据流类型,永远都是 V4L2_BUF_TYPE_VIDEO_CAPTURE buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; //存储类型:V4L2_MEMORY_MMAP(内存映射)或 V4L2_MEMORY_USERPTR (用户指针) buf.memory = V4L2_MEMORY_MMAP; buf.index = iIndex; if (ioctl(fd, VIDIOC_QBUF, &buf) < 0) { return -1; } return 0; } return -1; }
true
14ec9da0a20f3b352c654ff1af9d05fc564b2f84
C++
Life75/DSA2-Project2-AWashington
/main.cpp
UTF-8
4,616
3.140625
3
[]
no_license
#include "Customer.hpp" #include "Heap.hpp" #include "Statistics.hpp" #include<sstream> #include<ctime> #include <queue> #include <cstdlib> #include <cmath> double getNextRandomInterval(double avg); /************************************************************************************* Main is the combination of all 3 classes creating the actual simulation. This will create the queue and heap and process the statistics of the given information. The function getNextRandomInterval is here to actual get the random interval and placed simply in main as a function. The analytical and simulation model with both appear at the end with the results. **************************************************************************************/ int main() { std::queue < Customer * > holder; std::queue < Customer * > fifo; Customer * newNode = new Customer(); Heap heap; int sizeArray = 1000; double serviceChannel = 4; double mu = 2; double lambda =0; std::cout << "Please enter lambda: "; std::cin >> lambda; std::cout << "Please enter mu: "; std::cin >> mu; std::cout << "Please enter amount of service channels: "; std::cin >> serviceChannel; std::cout << "Please enter amount of customers: "; std::cin >> sizeArray; double time = 0; Customer * customers[sizeArray]; for (int i = 0; i < sizeArray; i++) { time += getNextRandomInterval(mu); customers[i] = new Customer(); customers[i]->setArrivalTime(time); holder.push(customers[i]); } for (int i = 0; i < sizeArray; i++) { customers[i] = nullptr; } //testing int size = 200; double currentTime = 0; double Po =0; double Rho =0; double totalServiceTime=0; int j = 0; while (!holder.empty()) { for (int i = 0; i < size; i++) { customers[i] = holder.front(); holder.pop(); } int size = 200; j++; Po += customers[0]->getArrivalTime() - currentTime; while (size > 0) { if (serviceChannel > 0) { if (fifo.empty()) { newNode = heap.pop(customers, size); } else { newNode = fifo.front(); fifo.pop(); } Rho += newNode->getTime() - currentTime; if (newNode->getDepartureTime() == -1) { currentTime = newNode->getTime(); newNode->setStartOfServiceTime(currentTime); double randomNum = getNextRandomInterval(mu); totalServiceTime += randomNum; newNode->setDepartureTime(newNode->getStartOfServiceTime() + randomNum); heap.insertNode(customers, size, newNode); heap.buildHeap(customers, size); // std::cout << newNode->getDepartureTime() << "\n"; --serviceChannel; } else { //heap.pop(customers, size); ++serviceChannel; } } else { newNode = heap.pop(customers, size); //currentTime = newNode->getTime(); if (newNode->getDepartureTime() == -1) { fifo.push(newNode); } else { ++serviceChannel; } } } } //calculate stats Rho = Rho/totalServiceTime; std::cout << "Analytical Model: \n"; double sizeOfArray = sizeArray; Statistics stats(sizeOfArray, lambda, mu, serviceChannel); std::cout << "Po = " << stats.Po() << std::endl; std::cout << "L = " << stats.L() << std::endl; std::cout << "W = " << stats.W() << std::endl; std::cout << "Lq = " << stats.Lq() << std::endl; std::cout << "Wq = " << stats.Wq() << std::endl; std::cout << "\n"; std::cout << "Simulation Results: \n"; stats.setPo(Po); std::cout << "Po = " << Po << std::endl; std::cout << "W = " << stats.W() << std::endl; std::cout << "Wq = " << stats.Wq() << std::endl; std::cout << "Rho = " << Rho << std::endl; } double getNextRandomInterval(double avg) { srand((unsigned int) time(0)); double a = 1.0; double randomNum = (double(rand())/double((RAND_MAX)) * a); double intervalTime = -1 * (1.0/avg) * std::log(randomNum); return intervalTime; }
true
e2bf5379892a50d364b5213b98768c0bae0bc695
C++
bergendenton/MyFirstCplus
/While-HW3.cpp
UTF-8
190
2.953125
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; main(){ int x=1; int z=0; while (x<41){ z=z+x; x++; } cout << "count the sum of numbers from 1 to 40 is " << z << endl; return 0; }
true
2581809efc622f4e0168e706530671e8982132a7
C++
Izidorf/EMBEDDED-Projects
/Mouse/src/main.cpp
UTF-8
2,381
2.65625
3
[]
no_license
#include "USBDevice.h" #include "USBMouse.h" #include "MMA8451Q.h" #include "TSISensor.h" PinName const SDA = PTE25; PinName const SCL = PTE24; #define MMA8451_I2C_ADDRESS (0x1d<<1) DigitalOut led_red(LED_RED); DigitalOut led_green(LED_GREEN); DigitalIn left(SW1); DigitalIn right(SW3); Serial pc(USBTX, USBRX); MMA8451Q acc(SDA, SCL, MMA8451_I2C_ADDRESS); TSISensor touch; USBMouse mouse; struct touch_struct{ float curr; float prev; }touch_val; void init() { pc.baud(115200); touch_val.curr = touch.readPercentage(); led_green = 1; led_red = 1; return; } void check_right(void) { if (right == 0) { mouse.press(MOUSE_RIGHT); pc.printf("Mouse press right \n"); led_green = 0; led_red = 1; } else { led_green = 1; led_red = 1; mouse.release(MOUSE_RIGHT); } } void check_left(void) { if (left == 0) { led_green = 1; led_red = 0; mouse.press(MOUSE_LEFT); pc.printf("Mouse press left \n"); } else { led_green = 1; led_red = 1; mouse.release(MOUSE_LEFT); } } void check_move() { int n_samples = 10; float x; float y; float thresh = 0.1; float sensitivity = 0.75; for(int i = 0; i<n_samples; i++) { x += acc.getAccX(); y += acc.getAccY(); } x /= n_samples; y /= n_samples; if(x >= thresh || x <= -thresh) { for(int i = 0; i<(sensitivity*10); i++) mouse.move((x*10*sensitivity),(0)); } if(y >= thresh || y <= -thresh) { for(int i = 0; i<(sensitivity*10); i++) mouse.move(0,(y*10*sensitivity)); } return; } void check_scroll() { float diff; float sensitivity = 1.0; touch_val.prev = touch_val.curr; touch_val.curr = touch.readPercentage(); diff = touch_val.prev - touch_val.curr; mouse.scroll(diff*100*sensitivity); } int main() { init(); while(true) { check_right(); check_left(); check_move(); check_scroll(); // wait(0.005); } }
true
07dfb805f5149253284b360f154f380f40d42fa1
C++
hackerxj007/Confidential-Laboratory
/Virtualization/zjc/code/MacDetect.cpp
GB18030
2,563
2.5625
3
[]
no_license
#include "stdafx.h" #include<wtypes.h> #include<nb30.h> #include<wincon.h> #pragma comment(lib,"netapi32.lib") using namespace std; typedef struct _ASTAT_ //ϢĽṹ { ADAPTER_STATUS adapt; //״̬ NAME_BUFFER NameBuff[30]; //ֱ } ASTAT, *PASTAT; void get_3part_mac(string &mac) { NCB Ncb; //һNCBƿ飩͵ĽṹNcb ASTAT Adapter; UCHAR uRetCode; //ִNetbios()ķֵ LANA_ENUM lenum; //ṹ壬macַ memset(&Ncb, 0, sizeof(Ncb)); Ncb.ncb_command = NCBENUM; //ͳϵͳ Ncb.ncb_buffer = (UCHAR *)&lenum; //ncb_bufferָLANA_ENUMṹĻ Ncb.ncb_length = sizeof(lenum); uRetCode = Netbios(&Ncb); //ȡк for (int i = 0; i < lenum.length; i++) //ÿһΪţȡmacַ { memset(&Ncb, 0, sizeof(Ncb)); Ncb.ncb_command = NCBRESET; //NCBRESETгʼ Ncb.ncb_lana_num = lenum.lana[i]; //ָ uRetCode = Netbios(&Ncb); memset(&Ncb, 0, sizeof(Ncb)); Ncb.ncb_command = NCBASTAT; //NCBSTATȡϢ Ncb.ncb_lana_num = lenum.lana[i]; strcpy_s((char *)Ncb.ncb_callname,10, "*"); //ԶϵͳֵΪ* Ncb.ncb_buffer = (unsigned char *)&Adapter; //ָصϢŵı Ncb.ncb_length = sizeof(Adapter); uRetCode = Netbios(&Ncb); //ŷNCBSTATԻȡϢ //MACַʽתΪ16ƣַmac if (uRetCode == 0) { char tmp[128]; sprintf_s(tmp,128, "%02x-%02x-%02x", Adapter.adapt.adapter_address[0], Adapter.adapt.adapter_address[1], Adapter.adapt.adapter_address[2] ); mac = tmp; } } } bool CheckVMWare() { string mac; get_3part_mac(mac); if (mac == "00-05-69" || mac == "00-0c-29" || mac == "00-50-56") { return false; } else { return true; } } bool CheckVirtualPC() { string mac; get_3part_mac(mac); if (mac == "00-03-ff") { return false; } else { return true; } } bool CheckVirtualBox() { string mac; get_3part_mac(mac); if (mac == "08-00-27") { return false; } else { return true; } } bool CheckVirtualMachine() { printf("MacDetect......"); bool answer1 = CheckVirtualPC(); bool answer2 = CheckVMWare(); bool answer3 = CheckVirtualBox(); printf(" Done.\n"); if (answer1 == false || answer2 == false || answer3 == false) return false; else return true; }
true
16d5aab1794f799e1c0123d89a0bf556ba0bed52
C++
ongxx107/FlashPhoto
/PROJ/src/imagetools/convolution_filter_edge.h
UTF-8
1,053
2.625
3
[]
no_license
/** This file is part of the CSCI-3081W Project Support Code, which was developed at the University of Minnesota. This code is to be used for student coursework. It is not an open source project. Copyright (c) 2015-2018 Daniel Keefe, TAs, & Regents of the University of Minnesota. Original Author(s) of this File: Seth Johnson, 4/4/2015, University of Minnesota Author(s) of Significant Updates/Modifications to the File: Ren Jeik Ong */ #ifndef IMAGETOOLS_CONVOLUTION_FILTER_EDGE_H_ #define IMAGETOOLS_CONVOLUTION_FILTER_EDGE_H_ #include <string> #include "imagetools/float_matrix.h" #include "imagetools/convolution_filter.h" namespace image_tools { /** @brief This subclass creates a kernel that detect edges in all directions. */ class ConvolutionFilterEdge : public ConvolutionFilter { public: ConvolutionFilterEdge(); virtual ~ConvolutionFilterEdge(); static const std::string name() { return "Convolution Filter Edge"; } FloatMatrix* CreateKernel() override; }; } // namespace image_tools #endif // IMAGETOOLS_CONVOLUTION_FILTER_EDGE_H_
true
463463d8e7a5595a07bebcfaafb375e4d5c96aea
C++
paulgraydon/Qt2048
/game.h
UTF-8
584
2.921875
3
[]
no_license
#ifndef GAME_H #define GAME_H #define WIN_VALUE 2048 // Define macro for winning value #include "board.h" class Game { public: Game(int rowCount = 4, int colCount = 4); ~Game(); void restartGame(); // Reset the whole game Board* getGameBoard() const {return gameBoard;} void move(Direction dir); // Perform a move in given direction UP, DOWN, LEFT or RIGHT int getGameScore() const {return gameScore;} bool isGameOver(){return gameOver;} bool isGameWon(); private: Board* gameBoard; int gameScore; bool gameOver; }; #endif // GAME_H
true
8c79487eada32096c13234383489ab3e02f53a04
C++
exced/dataStructures
/channel_test2.cc
UTF-8
942
2.890625
3
[]
no_license
// // channel_test.cc // channel // // Created by Thomas BARRAS on 17-05-04. // Copyright © 2017 Exced. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <iostream> #include <string> #include <future> #include <thread> #include "channel.h" static const int kQuit = 0; Channel<int> out(1), in(1); void sendInts() { for (int i = 1; i < 5; i++) { out << i; int rcvd; in >> rcvd; } out << kQuit; } int sum() { int res = 0; while (true) { int reply; out >> reply; if (reply == kQuit) { return res; } res += reply; in << 1; } return res; } int main(int argc, const char *argv[]) { std::thread t1(sendInts); int s = 0; std::thread t2([&] { s = sum(); }); t1.join(); t2.join(); std::cout << "sum: " << s << std::endl; return 0; }
true
b6ab1502258b5691267649935288175094cf18a2
C++
edelkas/opengl
/src/Texture.cpp
UTF-8
2,624
3.109375
3
[]
no_license
#include "Texture.h" #include "stb_image/stb_image.h" Texture::Texture(const std::string& filepath) : m_FilePath(filepath), m_LocalBuffer(nullptr), m_Height(0), m_Width(0), m_BPP(0) { /** * Load image. * * - Flip because OpenGL expects origin to be at the bottom. * - stbi_load will also set the member variables whose address we specify. * - The last parameter is the number of desired channels (4: RGBA). */ stbi_set_flip_vertically_on_load(1); m_LocalBuffer = stbi_load(filepath.c_str(), &m_Width, &m_Height, &m_BPP, 4); /** * Generate and bind texture */ GLCall(glGenTextures(1, &m_RendererID)); // Create texture, index is saved in pointer GLCall(glBindTexture(GL_TEXTURE_2D, m_RendererID)); // Bind texture and establish type /** * Configure basic parameters of the texture * * - Minification filter: What to do when the texture is minimized. * - Maximization filter: What to do when the texture is maximized. * - Horizontal wrapping: What to do when the texture is done horizontally. * - Vertical wrapping: What to do when the texture is done vertically. */ GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); // Linear interpolation GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); // Linear interpolation GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); // Clamping (instead of tiling) GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); // Clamping (instead of tiling) /** * Provide OpenGL with the texture data. * * - Texture type. * - Texture levels. * - Internal format in which OpenGL will save the texture data. * - Width of the image in pixels. * - Height of the image in pixels. * - Borders of the texture. * - External format of the data we are providing. * - Format of each of the channels in said data. * - Pointer to start of data (can be nullptr to only allocate). */ GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_LocalBuffer)); /** * Unbind texture and free memory */ GLCall(glBindTexture(GL_TEXTURE_2D, 0)); if (m_LocalBuffer) stbi_image_free(m_LocalBuffer); } Texture::~Texture(){ GLCall(glDeleteTextures(1, &m_RendererID)); } void Texture::Bind(unsigned int slot/*= 0*/) const { GLCall(glActiveTexture(GL_TEXTURE0 + slot)); // Select slot to bind texture GLCall(glBindTexture(GL_TEXTURE_2D, m_RendererID)); } void Texture::Unbind() const { GLCall(glBindTexture(GL_TEXTURE_2D, 0)); }
true
f03d9517e65c3c17fb6b62f352ffb43a32f8a892
C++
inql/OnePass
/src/field.cpp
UTF-8
3,013
3.125
3
[ "Unlicense" ]
permissive
#include "onepass/field.hpp" #include <iostream> #include "onepass/no_property_set_exception.hpp" namespace onepass { namespace core { std::ostream &operator<<(std::ostream &os, const Field &field) { if (field.history_.empty()) throw no_property_set_exception(); os << field.history_.back().val_.type_name_ << ":" << field.history_.back().val_.val_; return os; } bool operator==(const Field &first, const Field &second) { return ( first.getFieldType() == second.getFieldType() && first.getValue() == second.getValue() && first.getName() == second.getName()); } bool operator!=(const Field &first, const Field &second) { return !(first == second); } } // namespace core } // namespace onepass using namespace onepass::core; Field::Field() { } Field::Field(FieldType fieldType, std::string value) { if (fieldType == FieldType::other) throw std::invalid_argument("Property type cannot be \"other\" without a name"); history_.push_back({ 0, { fieldType, "", value } }); } Field::Field(std::string name, std::string value) { history_.push_back({ 0, { typeFromString(name), name, value } }); } FieldType Field::getFieldType() const { if (history_.empty()) throw no_property_set_exception(); const_cast<Field *>(this)->history_.back().seen(); return history_.back().val_.type_; } std::string Field::getValue() const { if (history_.empty()) throw no_property_set_exception(); const_cast<Field *>(this)->history_.back().seen(); return history_.back().val_.val_; } std::string Field::getName() const { if (history_.empty()) throw no_property_set_exception(); const_cast<Field *>(this)->history_.back().seen(); return history_.back().val_.type_name_; } void Field::setValue(const std::string newValue) { if (history_.empty()) throw no_property_set_exception(); // if newValue == old, skip setting the value if (newValue == history_.back().val_.val_) return; unsigned id = static_cast<unsigned>(history_.size()); Trackable<FieldRecord> newRecord{ id }; newRecord.val_.type_ = history_.back().val_.type_; newRecord.val_.type_name_.assign(history_.back().val_.type_name_); newRecord.val_.val_.assign(newValue); history_.push_back(newRecord); } void Field::printChanges() { for (auto value : history_) { std::cout << "\t\tId: " << value.getId() << " Accessed: " << value.toString(value.getAccessed()) << " Created: " << value.toString(value.getCreated()) << " Name: " << value.val_.type_name_ << " Value: " << value.val_.val_ << std::endl; } } void Field::printBack() { if (history_.empty()) throw no_property_set_exception(); std::cout << "Name: " << history_.back().val_.val_ << " Type: " << history_.back().val_.type_name_ << std::endl; } size_t Field::getChangesCount() const { return history_.size(); } Field &Field::operator=(Field &other) { history_ = other.history_; return *this; }
true
e4a1ef55a3a131a89d327195ef428649c1f3efee
C++
wrxcode/primer
/16.6.cpp
UTF-8
688
3.1875
3
[]
no_license
/************************************************************************* > File Name: 16.6.cpp > Author: > Mail: > Created Time: 2016年03月11日 星期五 19时33分18秒 ************************************************************************/ #include<iostream> #include<vector> #include<list> #include<string> using namespace std; template <typename T, unsigned size> T* begin_def(T(&arr)[size]) { return arr; } template <typename T, unsigned size> T* end_def(T (&arr)[size]) { return arr + size; } int main() { string str[] = {"abcde", "ha", "ha", "efgh"}; cout << *(begin_def(str) + 1) << endl; cout << *(end_def(str) - 1) << endl; return 0; }
true
1f53bf8d2b56c46c38b54f86c6ab64e3d4d54661
C++
WhalesAreNice/IGME309-2196
/E05_TranslationAndScale/AppClass.cpp
UTF-8
3,262
2.515625
3
[ "MIT" ]
permissive
#include "AppClass.h" void Application::InitVariables(void) { //init the mesh m_pMesh = new MyMesh(); m_pMesh->GenerateCube(1.0f, C_YELLOW); //m_pMesh->GenerateSphere(1.0f, 5, C_WHITE); } void Application::Update(void) { //Update the system so it knows how much time has passed since the last call m_pSystem->Update(); //Is the arcball active? ArcBall(); //Is the first person camera active? CameraRotation(); } void Application::Display(void) { // Clear the screen ClearScreen(); matrix4 m4View = m_pCameraMngr->GetViewMatrix(); matrix4 m4Projection = m_pCameraMngr->GetProjectionMatrix(); matrix4 m4Scale = glm::scale(IDENTITY_M4, vector3(1.0f,1.0f,1.0f)); static float value = 0.0f; matrix4 m4Translate = glm::translate(IDENTITY_M4, vector3(value, 2.0f, 3.0f)); value += 0.01f; //matrix4 m4Model = m4Translate * m4Scale; matrix4 m4Model = m4Scale * m4Translate; //m_pMesh->Render(m4Projection, m4View, m4Model); //my added stuff //making a pac man for (float i = -1.0f; i < 2.0f; i+=1.0f) { m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(-6.0f, i, 0.0f))); } for (float i = -3.0f; i < 4.0f; i += 1.0f) { m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(-5.0f, i, 0.0f))); } for (float i = -4.0f; i < 5.0f; i += 1.0f) { m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(-4.0f, i, 0.0f))); } for (float i = -5.0f; i < 6.0f; i += 1.0f) { m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(-3.0f, i, 0.0f))); } for (float i = -5.0f; i < 6.0f; i += 1.0f) { m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(-2.0f, i, 0.0f))); } for (float i = -6.0f; i < 7.0f; i += 1.0f) { if(i != 0.0f) m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(-1.0f, i, 0.0f))); } for (float i = -6.0f; i < 7.0f; i += 1.0f) { if (i != 0.0f && i != 4.0f) m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(0.0f, i, 0.0f))); } for (float i = -6.0f; i < 7.0f; i += 1.0f) { if (i > 1.0f || i < -1.0f) m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(1.0f, i, 0.0f))); } for (float i = -5.0f; i < 6.0f; i += 1.0f) { if (i > 1.0f || i < -1.0f) m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(2.0f, i, 0.0f))); } for (float i = -5.0f; i < 6.0f; i += 1.0f) { if (i > 1.0f || i < -1.0f) m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(3.0f, i, 0.0f))); } for (float i = -4.0f; i < 5.0f; i += 1.0f) { if (i > 2.0f || i < -2.0f) m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(4.0f, i, 0.0f))); } for (float i = -3.0f; i < 4.0f; i += 1.0f) { if (i > 2.0f || i < -2.0f) m_pMesh->Render(m4Projection, m4View, glm::translate(m4Model, vector3(5.0f, i, 0.0f))); } // draw a skybox m_pMeshMngr->AddSkyboxToRenderList(); //render list call m_uRenderCallCount = m_pMeshMngr->Render(); //clear the render list m_pMeshMngr->ClearRenderList(); //draw gui DrawGUI(); //end the current frame (internally swaps the front and back buffers) m_pWindow->display(); } void Application::Release(void) { SafeDelete(m_pMesh); //release GUI ShutdownGUI(); }
true
3397e4b2e9f9fe57dcfea70ce33fada09a738857
C++
capcaz99/EncuentroANUIES
/funcionesEnviar/funcionesEnviar.ino
UTF-8
1,704
2.53125
3
[]
no_license
//Función que envía datos al OCB void enviarDatos(int magnitud){ Process p; p.begin("curl"); p.addParameter("-H"); p.addParameter("\"Content-Type: application/json\""); p.addParameter("-X"); p.addParameter("PUT"); p.addParameter("-d"); json = "\"{\"value\":"+(String)magnitud+"}\""; Serial.println(json); p.addParameter(json); p.addParameter("-k"); p.addParameter("\"http://localhost:1026/v2/entities/"+id+"/attrs/temperatura\""); p.run(); while (p.available() > 0) { char c = p.read(); Serial.print(c); } Serial.println("Terminé enviar datos"); Serial.flush(); p.close(); } //Función que registra al sensor en el servidor void registrarSensor(){ Process p; Serial.println("Registro de sensor"); p.begin("curl"); p.addParameter("-H"); p.addParameter("\"Content-Type: application/json\""); p.addParameter("-X"); p.addParameter("POST"); p.addParameter("-d"); //p.addParameter("{\"id\": "+id+",\"type\":\"SensorSismico\",\"temblor\":{\"value\":0},\"zona\":{\"value\":"+zona+"}}"); p.addParameter("\"{\"id\":\"SensorTermico1\",\"type\":\"SensorTermico\",\"temperatura\":{\"value\":0},\"zona\":{\"value\":1}}\""); p.addParameter("-k"); p.addParameter("\"http://localhost:1026/v2/entities\""); p.run(); while (p.available() > 0) { char c = p.read(); Serial.print(c); } Serial.println("Terminé regsitro"); Serial.flush(); p.close(); return; }
true
ffb95c603bd805cf36683bec2043c55cc4b3becd
C++
maniSHarma7575/Code_Mystery
/codeforces/894a.cpp
UTF-8
375
2.640625
3
[]
no_license
#include <iostream> using namespace std; int main() { string str; cin>>str; int n=str.length(); int dp[n]; if(str[0]=='Q')dp[0]=1; else dp[0]=0; for(int i=1;i<n;i++){ if(str[i]=='Q'){ dp[i]=dp[i-1]+1; } else{ dp[i]=dp[i-1]; } } int count=0; for(int i=1;i<n-1;i++){ if(str[i]=='A'){ count+=dp[i]*(dp[n-1]-dp[i]); } } cout<<count; return 0; }
true
98de0cfdd909a3b2f508869270634f82979c062f
C++
huangwei0/20_cs325
/hw1/mergesort.cpp
UTF-8
1,676
3.328125
3
[]
no_license
/************************************ Project: mergesort.cpp hw1 Name : Wei Huang Course: cs 325 Data:winter 2020 *************************************/ #include <iostream> #include <cstdio> #include <cstdlib> #include <fstream> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string> using namespace std; //mergesort algorithms void merge(int arr[], int left, int mid, int right){ int i, j, lower_half, upper_half; int temp[(right-left)+1]; lower_half=left; upper_half=mid+1; for(i=0; (lower_half<=mid)&&(upper_half<=right); i++){ if(arr[lower_half]<=arr[upper_half]){ temp[i]=arr[lower_half]; lower_half++; } else{ temp[i]=arr[upper_half]; upper_half++; } } if(lower_half>mid) for(j=upper_half;j<=right;j++, i++) temp[i]=arr[j]; else for(j=lower_half;j<=mid;j++, i++) temp[i]=arr[j]; for(j=0,i=left;i<=right;i++,j++) arr[i]=temp[j]; } void merge_sort(int arr[], int left, int right) { int mid; if(left<right) { mid=(right+left)/2; merge_sort(arr, left, mid); merge_sort(arr, mid+1, right); merge(arr, left, mid, right); } } int main(){ int arr_size = 0; int num; int arr[100]; ifstream fp; fp.open("data.txt"); ofstream fpw; fpw.open("merge.out"); fp >> num; while(fp >>arr[arr_size] ){ if(arr_size>num){ break; } arr_size++; } fp.close(); merge_sort(arr,0,arr_size-1); if (fpw.is_open()) { for(int i = 0; i < arr_size; i ++){ fpw << arr[i] << " " ; } fpw.close(); } return 0; }
true
2f00c3aa15580017ed10d13871601b93dc2fb4cf
C++
HoangNam666/Nam
/baitap9(1).cpp
UTF-8
704
2.796875
3
[]
no_license
#include <stdio.h> #include <string.h> bool ktchuoi(char a[][100],unsigned int c,char b[]){ for (int i=0;i<c;i++){ int z=0,max=0; for (int j=0;j<strlen(a[i]);j++){ if (a[i][j]==b[z]){ z++; if (z>max){ max=z; } } else { z=0; } } if (max==strlen(b)){ return true; } } return false; } int main (){ int n; printf("Nhap so luong chuoi n: "); scanf("%d",&n); char a[n][100]; for (int i=0;i<n;i++){ printf("Nhap chuoi thu %d: ",i+1); scanf("%s",a[i]); } char s[100]; printf("Nhap chuoi s can kiem tra: "); scanf("%s",s); if (ktchuoi(a,n,s)){ printf("Chuoi s co nam trong mang."); } else { printf("chuoi s khong nam trong mang."); } return 0; }
true
01d05839e32cf690ee78f9edce034c4ac37714e2
C++
morishitamakoto0330/AtCoder
/AtCoderBeginnerContest/049/b.cpp
UTF-8
697
3.03125
3
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; int main(void) { int i, index; int H, W, new_H; string s_tmp; vector<string> C, new_C; // get input --------------------------------- cin >> H >> W; new_H = H*2; for(i = 0; i < H; i++) { cin >> s_tmp; C.push_back(s_tmp); } // extend C ---------------------------------- for(i = 1; i <= new_H; i++) { index = (i+1)/2; index--; new_C.push_back(C[index]); } // disp answer ------------------------------ for(i = 0; i < new_H; i++) { cout << new_C[i] << endl; } return 0; }
true
f053dd5168c52022d5136bd9ecf09b5d2872f554
C++
bobzhw/question
/question/reorderlist.cpp
GB18030
1,274
3.25
3
[]
no_license
#include<iostream> #include<vector> //L0->L1->L2->L3->...->Ln-1->Ln //L0->Ln->L1->Ln-1->L2->Ln-2->... using namespace std; //Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: void reorderList(ListNode *head) { if (head == nullptr || head->next == nullptr) return; ListNode* slow = head; ListNode* fast = head->next; while (fast->next != nullptr && fast->next->next != nullptr) { fast = fast->next->next; slow = slow->next; } ListNode* before = slow->next; //벿 slow->next = nullptr; ListNode* tmp = new ListNode(0); ListNode* pHead = nullptr; while (before != nullptr) { ListNode* ptr = before->next; tmp->next = before; before->next = pHead; pHead = before; before = ptr; } //tmpΪϲͷڵ pHead = tmp->next; tmp->next = nullptr; ListNode* current = tmp; //ϲhead,pHead; while (head != nullptr && pHead != nullptr) { current->next = head; head = head->next; current->next->next = pHead; pHead = pHead->next; current = current->next->next; } head = tmp->next; if (tmp != nullptr) { delete(tmp); tmp = nullptr; } } };
true
68b459d65c877a35c383d9f99ea48db18d6e5384
C++
gabrieltaets/Competitive-Programming
/uri/1259.cpp
UTF-8
426
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int N; vector<int> par, impar; scanf("%d",&N); while(N--){ int x; scanf("%d",&x); if(x&1) impar.push_back(-x); else par.push_back(x); } sort(par.begin(),par.end()); sort(impar.begin(),impar.end()); for(int i = 0; i < par.size(); i++) printf("%d\n",par[i]); for(int i = 0; i < impar.size(); i++) printf("%d\n",-impar[i]); return 0; }
true
42e0a557d23068bda11b3ed90ccc86599651197b
C++
vilashkardate/DSA_Sheet
/Array/29_Trapping_Rain_Water.cpp
UTF-8
1,250
3.921875
4
[]
no_license
#include <iostream> using namespace std; int max(int x, int y) { return (x > y) ? x : y; } int min(int x, int y) { return (x < y) ? x : y; } // Function to find the amount of water that can be trapped within // a given set of bars in linear time and extra space int trap(int bars[], int n) { // base case if (n <= 2) { return 0; } int water = 0; // `left[i]` stores the maximum height of a bar to the left // of the current bar int left[n-1]; left[0] = INT_MIN; // process bars from left to right for (int i = 1; i < n - 1; i++) { left[i] = max(left[i-1], bars[i-1]); } int right = INT_MIN; // process bars from right to left for (int i = n - 2; i >= 1; i--) { right = max(right, bars[i+1]); // check if it is possible to store water in the current bar if (min(left[i], right) > bars[i]) { water += min(left[i], right) - bars[i]; } } return water; } int main(void) { int heights[] = { 7, 0, 4, 2, 5, 0, 6, 4, 0, 5 }; int n = sizeof(heights) / sizeof(heights[0]); cout<<"The maximum amount of water that can be trapped is "<< trap(heights, n)<<endl; return 0; }
true
5225c8b670d217034c6eda2f2838dba79e19786d
C++
Maciej3206/university-db-1
/Menu.cpp
UTF-8
6,811
3.203125
3
[]
no_license
#include "Menu.hpp" void Menu::showMenu() const { std::cout << "*************************************" << '\n'; std::cout << "****** UNIVERSITY-DB DATABASE *******" << '\n'; std::cout << "*************************************" << '\n'; int lp = 0; for (const auto& option : options_) { std::cout << lp++ << ". " << option.optionDescription << '\n'; } } void Menu::run() { std::string chosedOption; Menu::showMenu(); auto runOption = [this](size_t index) { if (index >= 0 and index < options_.size()) { (this->*options_[index].calledMethod)(); //ugly i know } else { std::cout << "Wrong option!\n"; } }; while (!menuQuit) { std::cout << "Select Option: "; std::cin >> chosedOption; size_t indexOption = 0; try { indexOption = std::stoi(chosedOption); } catch (...) { } runOption(indexOption); } } void Menu::printStudent(const Student& student) const { std::cout << "*******************************************\n"; std::cout << "FirstName: " << student.getFirstName() << '\n'; std::cout << "SurName: " << student.getSurName() << '\n'; std::cout << "Address: " << student.getAddress() << '\n'; std::cout << "Index: " << student.getIndexNumber() << '\n'; std::cout << "Pesel: " << student.getPesel() << '\n'; std::cout << "*******************************************\n"; } void Menu::printAllRecords() { std::cout << "---------PRINT RECORDS FROM FILE-----------\n"; db_.printAll(); } void Menu::loadRecords() { std::cout << "---------LOAD RECORD FROM FILE-----------\n"; db_.loadFromFile("db.txt"); } void Menu::addStudent() { std::string firstName; std::string surName; std::string city; std::string street; std::string numberOfStreet; std::string pesel; std::string indexNumber; std::string genderInput; size_t index; Gender gender = Gender::Undefined; std::cout << "\n First Name: "; std::cin >> firstName; std::cout << " Surname: "; std::cin >> surName; std::cout << " Address (city): "; std::cin >> city; std::cout << " Address (street): "; std::cin >> street; std::cout << " Address (numberOfStreet): "; std::cin >> numberOfStreet; std::cout << " Index Number: "; std::cin >> indexNumber; index = std::stoi(indexNumber); std::cout << " Gender [Male][Female][Undefined] : "; std::cin >> genderInput; std::vector sexes{Gender::Male, Gender::Female, Gender::Undefined}; for (const auto& sex : sexes) { if (translateGender[sex] == genderInput) { std::cout << " Gender selected: " << translateGender[sex] << '\n'; gender = sex; } } int incorrectPeselTries = 3; while (true) { std::cout << " Pesel: "; std::cin >> pesel; if (checkPesel(pesel)) { Student s{firstName, surName, city, street, numberOfStreet, index, pesel, gender}; auto isSuccess = db_.addStudent(s); if (isSuccess) { std::cout << "Student added.\n"; } else { std::cout << "Student NOT added.\n"; } return; } std::cout << "\nError: wrong PESEL number!\n"; --incorrectPeselTries; char letter = 0; std::cout << " Try insert PESEL again (y/n)\n"; std::cin >> letter; std::cout << letter << '\n'; if (letter == 'n' or incorrectPeselTries == 0) { std::cout << "\nStudent NOT added!\n"; return; } } } void Menu::sortBySurname() { std::cout << "---------SORT BY SURNAME (AFTER)-----------\n"; db_.sortBySurName(); db_.printAll(); } void Menu::sortByPesel() { std::cout << "---------SORT BY PESEL (AFTER)-----------\n"; db_.sortByPesel(); db_.printAll(); } void Menu::searchOption() { std::vector<Student> result; std::string what; std::cout << "Enter the search type: firstname / surname / city / street" << what << ":"; std::cin >> what; if (what == "surname") { std::string sn; std::cout << "enter the search " << what << ": "; std::cin >> sn; result = db_.searchBySurName(sn); } else if (what == "firstname") { std::string fn; std::cout << "enter the search " << what << ": "; std::cin >> fn; result = db_.searchByFirstName(fn); } else if (what == "city") { std::string ct; std::cout << "enter the search " << what << ": "; std::cin >> ct; result = db_.searchByCity(ct); } else if (what == "street") { std::string st; std::cout << "enter the search " << what << ": "; std::cin >> st; result = db_.searchByStreet(st); } else { std::cout << "Error. Unknown option, please choose from : surname, firstname, city, street\n"; return; } if (!result.empty()) { for (const auto& el : result) { Menu::printStudent(el); } } else { std::cout << "Not found Student with this " << what << '\n'; } } void Menu::searchByPesel() { std::string p; std::cout << "enter the search pesel: "; std::cin >> p; auto result = db_.searchByPesel(p); if (!result.empty()) { for (const auto& el : result) { Menu::printStudent(el); } } else { std::cout << "Not found Student with this pesel\n"; } } void Menu::deleteByPesel() { std::string p; std::cout << "enter the pesel to be remove: "; std::cin >> p; std::cout << "---------DELETE BY PESEL (AFTER)-----------\n"; db_.deleteByPesel(p); db_.printAll(); } void Menu::deleteByIndexNumber() { size_t index; std::cout << "enter the index number to be remove: "; std::cin >> index; std::cout << "---------DELETE BY INDEX (AFTER)-----------\n"; db_.deleteByIndex(index); db_.printAll(); } void Menu::validatePeselNumber() { std::string p; std::cout << "enter the pesel to be check: "; std::cin >> p; std::cout << "---------CHECK PESEL-----------\n"; bool peselValid = checkPesel(p); if (peselValid) { std::cout << "Pesel valid\n"; } else { std::cout << "Pesel not valid\n"; } } void Menu::saveRecords() { std::cout << "---------SAVE RECORD TO FILE-----------\n"; db_.saveToFile("db.txt"); } void Menu::endProgram() { menuQuit = true; }
true
b3313393e90551860e8efabe930259101ab814cf
C++
rishup132/My-Codes
/spoj/MAXSC.cpp
UTF-8
645
2.53125
3
[]
no_license
#include <bits/stdc++.h> #define ll long long using namespace std; int main() { int t; cin >> t; while(t--) { int n,x; cin >> n; vector <int> v[n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cin >> x; v[i].push_back(x); } sort(v[i].begin(),v[i].end(),greater<int>()); } ll int sum = 0,max=1000000007; bool flag; x = n; while(x--) { flag = true; for(int i=0;i<n;i++) { if(v[x][i] < max) { sum += v[x][i]; max = v[x][i]; flag = false; break; } } if(flag) break; } if(flag) cout << -1 << endl; else cout << sum << endl; } }
true
6a6105fb03183a25065a5753cd19582fd2359638
C++
whocloud/start
/EP/EP205.cpp
UTF-8
526
2.734375
3
[]
no_license
/************************************************************************* > File Name: EP205.cpp > Author: > Mail: > Created Time: 2018年11月24日 星期六 09时38分31秒 ************************************************************************/ #include<stdio.h> int gcd (int a, int b) { return (b ? gcd(b, a % b) : a); } int main () { int sum = 1; for (int i = 1; i <= 20; i++) { if (sum % i == 0) continue; sum = i * sum / gcd(sum, i); } printf("%d\n",sum); return 0; }
true
c691fe65c720f8b9701ccdc0ccbd6629a2f1c589
C++
mdyang/oj-solutions
/nyist/52/main.my.cpp
UTF-8
598
2.546875
3
[]
no_license
#include <iostream> #include <map> using namespace std; typedef unsigned long long ull; int ten[6] = {1,10,100,1000,10000,100000}; int mulmod(ull a, ull b, int c){ return (a*b)%c; } int main(){ ull c; cin>>c; while(c--){ int n,k; map<int,int> s; cin>>n>>k; n%=ten[k]; if (n==1){ cout<<1<<endl; continue; } int len=1; s[n]=len; int next=n; while(s[next=mulmod(next,n,ten[k])]==0){ s[next]=++len; } cout<<len-s[next]+1<<endl; } return 0; }
true
1712a4a65c008668d5e006ce02d64bc51dc356ef
C++
jetzoc/Portenta-Tests
/ADC_DAC_Tests/dac_to_adc_loopback_ramp_test/dac_to_adc_loopback_ramp_test.ino
UTF-8
2,094
3.125
3
[]
no_license
/* * DAC to ADC loop test for the Portenta board * - 12 bit resolution for DAC * - 12 bit resolution for ADC * - Uses a software generated signal that outputs the full 12-bit range of DAC - Ramp with a step size * - Has AREF pin connected to 3.3V * * Hardware set-up: * A0 = analog input of ADC * A6 = analog output from DAC (scope ch. 1) * * D6 = digital input connected to analog input of ADC * D7 = digital output of ADC (scope ch. 2) * * D0 = digital timing pin for operation * * Connections: * Tie A6 to A0 * * For schematic and notes see: https://github.com/jetzoc/Portenta-Tests.git * * March 1, 2021 */ #include <stdlib.h> void setup() { /* DAC @ 12-bits */ analogWriteResolution(12); /* ADC @ 12-bits */ analogWriteResolution(12); /* Set up the DAC output pin * This pin is probed on oscilloscope */ pinMode(DAC, OUTPUT); // pin A6 (analog) /* Set up the ADC input pin */ pinMode(A0, INPUT_PULLDOWN); /* Set up the ADC output pin (digital) */ pinMode(6, INPUT); // pin D6 /* Digital wave form from ADC */ pinMode(7, OUTPUT); // pin D7 /* Set up a digital pin as an output to toggle it (for timing purposes) */ pinMode(0, OUTPUT); // pin D0 /* Serial terminal baud rate (if needed) */ Serial.begin(9600); Serial.println("*** DAC to ADC ramp loop test on Portenta Board ***"); } void loop() { /* Toggle digital pin before writing */ digitalWrite(0, HIGH); float a_val[4096]; float d_val[4096]; /* Write and read back multiple values */ for (int dac_val = 0; dac_val < 4096; dac_val+=32) // writes 128x { /* Write value to DAC output */ analogWrite(DAC, dac_val); // writing to A6 //Serial.println(dac_val); /* Digital read of ADC output */ d_val[dac_val] = digitalRead(6); } /* To view the digital ramp */ for (int idx = 0; idx < 4096; idx+=32) { digitalWrite(7, d_val[idx]); //Serial.println(d_val[idx]); } /* Toggle digital pin after writings */ digitalWrite(0, LOW); }
true
8562048487e6ffad993514ea22e527ec53a1b1e9
C++
mmarkiewicz/sequenceLibrary
/Sequence/Callbacks/Smap.h
UTF-8
717
2.71875
3
[]
no_license
#ifndef _SEQUENCE_CALLBACK_SMAP_H_ #define _SEQUENCE_CALLBACK_SMAP_H_ #include <utility> #include <memory> #include "Sequence/Sequence.h" namespace seq { template <typename S, typename T> class Smap : public Type<T>::SimpleCallback { public: typedef std::function<T(S)> fType; typename Type<T>::SequencePair operator() (void); Smap (const fType f, Sequence<S>* const s) : _s(s), _f(f) {} protected: std::shared_ptr<Sequence<S>> _s; const fType _f; }; template <typename S, typename T> typename Type<T>::SequencePair Smap<S,T>::operator() (void) { Smap<S,T> cb(_f,_s->tail()); return std::make_pair(_f(_s->head()), new Sequence<T>(cb)); } } #endif
true
1afcff74e9ec782d08e933542e6f44e8b3398da4
C++
yaominzh/CodeLrn2019
/mooc40-bobo-Interview/Play-with-Algorithm-Interview-master/03-Using-Array/cpp/05-Sort-Colors/main.cpp
UTF-8
1,155
3.671875
4
[ "Apache-2.0" ]
permissive
#include <iostream> #include <vector> #include <cassert> using namespace std; // 75. Sort Colors // https://leetcode.com/problems/sort-colors/description/ // // 计数排序的思路 // 对整个数组遍历了两遍 // 时间复杂度: O(n) // 空间复杂度: O(k), k为元素的取值范围 class Solution { public: void sortColors(vector<int> &nums) { int count[3] = {0}; // 存放0, 1, 2三个元素的频率 for(int i = 0 ; i < nums.size() ; i ++){ assert(nums[i] >= 0 && nums[i] <= 2); count[nums[i]] ++; } int index = 0; for(int i = 0 ; i < count[0] ; i ++) nums[index++] = 0; for(int i = 0 ; i < count[1] ; i ++) nums[index++] = 1; for(int i = 0 ; i < count[2] ; i ++) nums[index++] = 2; // 小练习: 自学编写计数排序算法 } }; int main() { int nums[] = {2, 2, 2, 1, 1, 0}; vector<int> vec = vector<int>(nums, nums + sizeof(nums)/sizeof(int)); Solution().sortColors(vec); for(int i = 0 ; i < vec.size() ; i ++) cout << vec[i] << " "; cout << endl; return 0; }
true
bd3172b61901b9728a70f4f6bc9b46f542e31a53
C++
LiunxPaisley/Cpp_Primer
/Chapter 17. Specialized Library Facilities/17.3. Regular Expressions/regular_expression.cpp
UTF-8
2,579
3.09375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <regex> using namespace std; bool valid(const smatch& m) { if (m[1].matched) { return m[3].matched && (m[4].matched == 0 || m[4].str() == " "); } else { return !m[3].matched && m[4].str() == m[6].str(); } } int main() { /*regex使用*/ cout << "regex使用 : "; string pattern("[^c]ei"); pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*"; regex r1(pattern); smatch results; string test_str = "receipt freind theif receive"; if (regex_search(test_str, results, r1)) { cout << results.str(); } /*忽略大小写*/ cout << "\n忽略大小写 : "; regex r2("[[:alnum:]]+\\.(cpp|cxx|cc)$", regex::icase); smatch results_; string filename = "regular_expression.cpp"; if (regex_search(filename, results, r2)) cout << results.str(); /*指出正则表达式的错误*/ cout << "\n指出正则表达式的错误 : "; try { regex r3("[[:alnum:]+\\.(cpp|cxx|cc)$", regex::icase); } catch (regex_error e) { cout << e.what() << "\ncode: " << e.code() << endl; } /*char*匹配*/ cout << "char*匹配 : "; cmatch cresults; if (regex_search("myfile.cc", cresults, r2)) cout << results.str(); /*使用sregex_iterator*/ cout << "\n使用sregex_iterator : "; string file = "receipt freind theif receive"; regex r4(pattern, regex::icase); for (sregex_iterator it(file.begin(), file.end(), r4), end_it; it != end_it; ++it) { cout << it->str() << " "; } cout << "\n使用匹配数据 : " << endl; for (sregex_iterator it(file.begin(), file.end(), r4), end_it; it != end_it; ++it) { auto pos = it->prefix().length(); pos = pos > 40 ? pos - 40 : 0; cout << it->prefix().str().substr(pos) << "\n\t\t>>> " << it->str() << " <<<\n" << it->suffix().str().substr(0, 40) << endl; } /*使用子表达式*/ cout << "使用子表达式: "; string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ]?)(\\d{4})"; regex r(phone); smatch m; string s; while (getline(cin, s)) { cout << s << endl; for (sregex_iterator it(s.begin(), s.end(), r), end_it; it != end_it; ++it) { if (valid(*it)) { cout << "valid: " << it->str() << endl; } else { cout << "not valid: " << it->str() << endl; } } } /*使用regex_replace*/ cout << "使用regex_replace: "; string fmt = "$2.$5.$7"; string number = "(908) 555-1800"; cout << regex_replace(number, r, fmt) << endl; /*用来控制匹配和格式的标志*/ string fmt2 = "$2.$5.$7 "; using namespace std::regex_constants; cout << regex_replace(s, r, fmt2, format_no_copy) << endl; }
true
5f68bdf90e5a08f3cabc91a41ffacdadb01cd570
C++
cnrkaya/EGUI-21L-Kaya-Caner
/lab1/mainwindow.cpp
UTF-8
8,139
2.5625
3
[]
no_license
#include "mainwindow.h" #include "ui_mainwindow.h" #include "recipedialog.h" #include "recipe.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); this->setWindowTitle("Recipe Planner"); initializeRecipeTableView(); initializeNeedListView(); //initializeCookingList cookingListModel = new QStringListModel(this); ui->cookingListView->setModel(cookingListModel); } MainWindow::~MainWindow() { delete ui; } void MainWindow::initializeRecipeTableView(){ //initialize model recipesModel = new QStandardItemModel(0,2,this); recipesModel->setHeaderData(0,Qt::Horizontal,QStringLiteral("Name")); recipesModel->setHeaderData(1,Qt::Horizontal,QStringLiteral("Description")); //initializeRecipeTableView QHeaderView *verticalHeader = ui->recipiesTableView->verticalHeader(); verticalHeader->setSectionResizeMode(QHeaderView::Fixed); verticalHeader->setDefaultSectionSize(verticalHeader->defaultSectionSize()*4); ui->recipiesTableView->setSelectionBehavior(QAbstractItemView::SelectionBehavior::SelectRows); ui->recipiesTableView->horizontalHeader()->setStretchLastSection(true); ui->recipiesTableView->setModel(recipesModel); } void MainWindow::initializeNeedListView(){ needListmodel = new QStandardItemModel(0,3,this); needListmodel->setHeaderData(0,Qt::Horizontal,QStringLiteral("Ingredient")); needListmodel->setHeaderData(1,Qt::Horizontal,QStringLiteral("Amount")); needListmodel->setHeaderData(2,Qt::Horizontal,QStringLiteral("Unit")); ui->needsTableView->horizontalHeader()->setStretchLastSection(true); ui->needsTableView->setModel(needListmodel); } void MainWindow::setRecipeTableView(){ QStringList recipe_names = recipes->objects.keys(); recipesModel->setRowCount(recipe_names.size()); for( int row= 0; row < recipe_names.size() ; row++) { for( int col=0; col < 2; col ++) { QModelIndex index = recipesModel->index(row,col,QModelIndex()); if(col == 0){ recipesModel->setData(index,recipe_names[row]); }else{ // get description array QJsonValue description = recipes->objects.value(recipe_names[row])["recipe"]; QString desc_string = Recipes::jsonValueArrayToString(description); recipesModel->setData(index,desc_string); } } } } void MainWindow::updateNeedTableView(QMap<QString,float> * ingredients_map,QStandardItemModel * needListmodel ){ //allocate new rows int newRowsCount = ingredients_map->size() - needListmodel->rowCount(); if(newRowsCount < 0 ) needListmodel->removeRows(0,-newRowsCount); else needListmodel->insertRows(0,newRowsCount); //update rows int row = 0; for(QString & key : ingredients_map->keys()){ float value = ingredients_map->value(key); //column1 ingredient QModelIndex index = needListmodel->index(row,0,QModelIndex()); needListmodel->setData(index,key.split("_")[0]); //column2 amount index = needListmodel->index(row,1,QModelIndex()); needListmodel->setData(index,value); //column3 unit index = needListmodel->index(row,2,QModelIndex()); needListmodel->setData(index,key.split("_")[1]); row ++; } } void MainWindow::on_editRecipeButton_clicked() { QModelIndexList indexes = ui->recipiesTableView->selectionModel()->selectedRows(); if(indexes.size()>1){ qDebug() << "Multi index selection is not allowed on edit mode"; return; } if(indexes.size()<=0){ qDebug() << "Choose an item"; return; } //open recipe dialog with edit mode QString recipeToEdit = recipesModel->data(indexes[0]).toString(); Dialog *dlg = new Dialog(this,recipeToEdit,recipes); int result = dlg->exec(); if(result==QDialog::Accepted) setRecipeTableView(); } void MainWindow::on_addButton_clicked() { if(recipes == nullptr) return; //open recipe dialog with NewRecipe mode Dialog *dlg = new Dialog(this,"NewRecipe",recipes); int result = dlg->exec(); if(result==QDialog::Accepted) setRecipeTableView(); } void MainWindow::on_deleteButton_clicked() { //delete selected rows QModelIndexList indexes = ui->recipiesTableView->selectionModel()->selectedRows(); for (int i = 0; i < indexes.count(); ++i) { QModelIndex index = indexes.at(i); QString recipteToDelete = recipesModel->data(index).toString(); recipes->removeJsonObject(recipteToDelete); recipesModel->removeRows(index.row(),1); } } void MainWindow::calculateNeedList(QString recipeToCook){ QStringList ingredients = recipes->objects.value(recipeToCook).toObject().keys(); for(int i = 0; i< ingredients.size(); i++){ if(ingredients[i] != "recipe" ){ QStringList amount_and_unit = recipes->objects.value(recipeToCook)[ingredients[i]].toString().split(" "); float value = amount_and_unit[0].toFloat(); amount_and_unit.removeFirst(); QString key = ingredients[i] ; key += "_" + amount_and_unit.join(" "); if(ingredients_map.contains(key)){ //add amount of units ingredients_map.insert(key,ingredients_map.value(key) + value); }else{ ingredients_map.insert(key,value); } } } updateNeedTableView(&ingredients_map, needListmodel); ui->needsTableView->sortByColumn(0,Qt::AscendingOrder); } void MainWindow::on_cookButton_clicked() { // Get all selections QModelIndexList indexes = ui->recipiesTableView->selectionModel()->selectedRows(); if(indexes.size()<=0) return; QStringList recipe_names = recipes->objects.keys(); for (int i = 0; i < indexes.count(); i++) { QModelIndex index = indexes.at(i); cookingList.append(recipesModel->data(index).toString()); QString recipeToCook = recipe_names[index.row()]; calculateNeedList(recipeToCook); } cookingListModel->setStringList(cookingList); } void MainWindow::on_removeCookingListBtn_clicked() { QModelIndex index= ui->cookingListView->selectionModel()->currentIndex(); QString recipteToDelete = cookingListModel->data(index).toString(); qDebug() << recipteToDelete; cookingListModel->removeRows(index.row(),1); cookingList.removeAt(index.row()); qDebug() << cookingList; QStringList ingredients = recipes->objects.value(recipteToDelete).toObject().keys(); //hashmapin keyi ingredients for(int i = 0; i< ingredients.size(); i++){ if(ingredients[i] != "recipe" ){ QStringList amount_and_unit = recipes->objects.value(recipteToDelete)[ingredients[i]].toString().split(" "); float value = amount_and_unit[0].toFloat(); QString key = ingredients[i]; amount_and_unit.removeFirst(); key += "_" +amount_and_unit.join(" "); if(ingredients_map.contains(key)){ float currentAmount = ingredients_map.value(key) -value; if(currentAmount <= 0) ingredients_map.remove(key); else ingredients_map.insert(key,currentAmount); } } } qDebug()<< ingredients_map; updateNeedTableView(&ingredients_map, needListmodel); } void MainWindow::on_actionOpen_triggered() { QString fileName = QFileDialog::getOpenFileName(this,"Browse File",qApp->applicationDirPath(),"*.json"); this->recipes = new Recipes(fileName); this->recipes->readJsonFromFile(); setRecipeTableView(); } void MainWindow::on_actionCreate_triggered() { QString fileName = QFileDialog::getSaveFileName(this,"Browse File",qApp->applicationDirPath(),"*.json"); this->recipes = new Recipes(fileName); this->recipes->readJsonFromFile(); setRecipeTableView(); }
true
e0cfe4e92cd200cfc996b91759e2d006dad69462
C++
sarainigo/Chess_Game_Project
/pieza.hpp
UTF-8
3,160
2.5625
3
[]
no_license
// pieza.hpp // trabajo ajedrez prueba // // Created by Sara Íñigo on 10/5/16. // Copyright © 2016 Sara Íñigo. All rights reserved. // #ifndef pieza_hpp #define pieza_hpp #include <stdio.h> class Casilla; /* pieza_hpp */ #include<string> #include <stdlib.h> #include <stdio.h> #include<iostream> using namespace std; class Pieza{ protected: int jugador; static int turno; Casilla** tablero; public: Pieza(int,Casilla**); //constructor virtual ~Pieza(void); virtual char tipo(); int getjugador();//1-blancas 2-negras virtual bool mover(int, int, int, int); virtual bool comer(int, int, int, int); virtual bool puedoMover(int, int, int, int); virtual bool puedoComer(int, int, int, int); virtual int * posicionposible(int, int); }; int Pieza::turno=0; class Rey: public Pieza{ bool hamovido; public: Rey(int,Casilla**); ~Rey(void); char tipo(){return 'k';} bool mover(int, int, int, int); bool puedoComer(int, int, int, int); bool comer(int, int, int, int); bool puedoMover(int, int, int, int); int * posicionposible(int, int); bool getmovido(); void enrocar(bool); }; class Reina: public Pieza{ public: Reina(int,Casilla**); ~Reina(void); char tipo(){return 'q';} bool mover(int, int, int, int); bool puedoMover(int, int, int, int); bool comer(int, int, int, int); bool puedoComer(int, int, int, int); int * posicionposible(int, int); }; class Torre: public Pieza{ bool hamovido; public: Torre(int,Casilla**); ~Torre(void); char tipo(){return 't';} bool mover(int, int, int, int); bool puedoMover(int, int, int, int); bool comer(int, int, int, int); bool puedoComer(int, int, int, int); int * posicionposible(int, int); bool getmovido(); void enrocar(); }; class Alfil: public Pieza{ public: Alfil(int,Casilla**); ~Alfil(void); char tipo(){return 'a';} bool puedoMover(int, int, int, int); bool mover(int, int, int, int); bool puedoComer(int, int, int, int); bool comer(int, int, int, int); int * posicionposible(int, int); }; class Caballo: public Pieza{ public: Caballo(int,Casilla**); ~Caballo(void); char tipo(){return 'c';} bool mover(int, int, int, int); bool puedoComer(int, int, int, int); bool comer(int, int, int, int); bool puedoMover(int, int, int, int); int * posicionposible(int, int); }; class Peon: public Pieza{ int haavanzado; public: Peon(int,Casilla**); ~Peon(void); char tipo(){return 'p';} bool mover(int, int, int, int); bool puedoComer(int, int, int, int); bool comer(int, int, int, int); bool puedoMover(int, int, int, int); int * posicionposible(int, int); //Pieza promocion(char); int getavanzado(); }; #endif
true
022e6f05eea045fd0a86dc1cb0b692a7094e6b61
C++
ChoiWooCheol/LaneChange-Manager
/lanechange_manager/include/lanechange_manager_state.hpp
UTF-8
5,061
2.84375
3
[]
no_license
#ifndef __LANECHANGE_MANAGER_STATE__ #define __LANECHANGE_MANAGER_STATE__ #include <map> #include <vector> #include <string> enum STATE { FOLLOW, NEED_LANE_CHANGE, CHECK_NEXT_LANE, EXCUTE_LANE_CHANGE, LANE_CHANGE_DONE }; /* transition * not_need_lane_change * received_global_path * lane_change_is_done * can_not_excute_lane_change * can_excute_lane_change * received_multi_global_path * is_target_lane_yes * is_target_lane_no * current_lane_is_main * lanes_are_overlaped */ class LaneChangeStateMachine{ public: LaneChangeStateMachine(){ transition_map_follow.insert(std::make_pair("received_global_path", STATE::NEED_LANE_CHANGE)); // follow -> need_lane_change transition_map_follow.insert(std::make_pair("lanes_are_not_overlaped", STATE::NEED_LANE_CHANGE)); // follow -> need_lane_change transition_map_follow.insert(std::make_pair("current_lane_is_main", STATE::FOLLOW)); // follow -> follow transition_map_need_lane_chanege.insert(std::make_pair("not_need_lane_change", STATE::FOLLOW)); // need_lane_change -> follow transition_map_need_lane_chanege.insert(std::make_pair("received_multi_global_path", STATE::CHECK_NEXT_LANE)); // need_lane_change -> check_next_lane transition_map_check_next_lane.insert(std::make_pair("can_not_excute_lane_change", STATE::CHECK_NEXT_LANE)); // check_next_lane -> check_next_lane transition_map_check_next_lane.insert(std::make_pair("can_excute_lane_change", STATE::EXCUTE_LANE_CHANGE)); // check_next_lane -> excute_lane_change transition_map_check_next_lane.insert(std::make_pair("current_lane_is_main", STATE::FOLLOW)); // check_next_lane -> follow transition_map_check_next_lane.insert(std::make_pair("lanes_are_overlaped", STATE::FOLLOW)); // check_next_lane -> follow transition_map_excute_lane_change.insert(std::make_pair("is_target_lane_no", STATE::EXCUTE_LANE_CHANGE)); // excute_lane_change -> excute_lane_change transition_map_excute_lane_change.insert(std::make_pair("is_target_lane_yes", STATE::LANE_CHANGE_DONE)); // excute_lane_change -> lane_change_done transition_map_lane_change_done.insert(std::make_pair("lane_change_is_done", STATE::NEED_LANE_CHANGE)); // lane_change_done -> need_lane_change transition_map.emplace_back(transition_map_follow); transition_map.emplace_back(transition_map_need_lane_chanege); transition_map.emplace_back(transition_map_check_next_lane); transition_map.emplace_back(transition_map_excute_lane_change); transition_map.emplace_back(transition_map_lane_change_done); state = STATE::FOLLOW; } ~LaneChangeStateMachine(){} void onUpdate(){ // stateCallBack() } /* void stateCallBack(){ // state 마다 수행해야하는 별도의 동작 정의 // ex) lane change 하는 state 일 때 replanning 못하도록 global planner에 메세지전송 } */ void tryNextState(std::string transition){ uint prev_state = state; if (transition_map[state].count(transition) == 0){ state = state; } else{ // onUpdate(); state = transition_map[state].at(transition); if(prev_state != state){ std::string prev, curr; if (prev_state == STATE::FOLLOW) prev = "FOLLOW"; else if (prev_state == STATE::NEED_LANE_CHANGE) prev = "NeedLaneChange"; else if (prev_state == STATE::CHECK_NEXT_LANE) prev = "CheckNextLane"; else if (prev_state == STATE::EXCUTE_LANE_CHANGE) prev = "ExcuteLaneChange"; else if (prev_state == STATE::LANE_CHANGE_DONE) prev = "LaneChangeDone"; if (state == STATE::FOLLOW) curr = "FOLLOW"; else if (state == STATE::NEED_LANE_CHANGE) curr = "NeedLaneChange"; else if (state == STATE::CHECK_NEXT_LANE) curr = "CheckNextLane"; else if (state == STATE::EXCUTE_LANE_CHANGE) curr = "ExcuteLaneChange"; else if (state == STATE::LANE_CHANGE_DONE) curr = "LaneChangeDone"; ROS_WARN("Changed State [%s]->[%s]", prev.c_str(), curr.c_str()); } } // onUpdate(); 여기에 있어도 되고, 외부에서 불러줘도됨. } void getCurrentState(){ return state; } bool isCurrentState(uint state_){ return state_ == state; } private: uint state; std::map<std::string, uint> transition_map_follow; std::map<std::string, uint> transition_map_need_lane_chanege; std::map<std::string, uint> transition_map_check_next_lane; std::map<std::string, uint> transition_map_excute_lane_change; std::map<std::string, uint> transition_map_lane_change_done; std::vector<std::map<std::string, uint>> transition_map; }; #endif
true
3e5b1e7e3790048d4118a0a7d4b56e803e802461
C++
schets/fast_rng
/bench.cpp
UTF-8
3,014
2.875
3
[]
no_license
#include <iostream> #include <time.h> #include "xorshift.hpp" constexpr static size_t num_loop = 1e8; constexpr static int num_work = num_loop; using namespace std; template<class seeder> void seed_rn(seeder &rn) { rn.seed(0xdeadbeef, 0xcafebabe); } //this forces the compiler to actually //do the full rng execution //when inside of the inner loop, //if this call is inlined, //then the compiler can optimize away a bunch of stuff in each case //for the first one, some of the reads/writes to memory it generally incurs //for the second two, probably can unroll the if statement, //and the write to the index //small loop to remove some cost of function call template<class rng> void __attribute__ ((noinline)) call_rn (rng &rn) { rn.rand(); } template<class rng> void __attribute__ ((noinline)) work_rn(rng &rn) { rn.do_heavy_work(); } template<class rng> void grab_many(rng& rn) { for (size_t i = 0; i < num_loop; i++) { call_rn(rn); } } template<class rng> void heavy_work(rng& rn) { for (size_t i = 0; i < num_work; i++) { work_rn(rn); } } template<class FN> uint64_t time_call(const FN& f, double &total) { clock_t t = clock(); f(); t = clock() - t; total = t * 1.0/CLOCKS_PER_SEC; return 0; } int main() { cout << "timing rngs" << std::endl; double time; double lat_time; uint64_t junk_val = 0; junk_val += time_call([]() { xorshift<uint64_t> rn; seed_rn(rn); return grab_many(rn); }, time); cout << "The plain rng took " << time << " seconds, "; cout << (num_loop * 1.0/time) << " rngs per second " << endl << endl; junk_val += time_call([]() { xorshift_bulk<uint16_t, 8> rn; seed_rn(rn); return grab_many(rn); }, time); cout << "The bulk rng took " << time << " seconds, "; cout << (num_work * 1.0/time) << " rngs per second " << endl; junk_val += time_call([]() { xorshift_bulk<uint16_t, 8> rn; seed_rn(rn); heavy_work (rn); }, time); cout << "The bulk rng took " << time << " seconds for refilling, "; cout << (num_work * 1.0/time) << " refills per second "; cout << "and " << (1e9 * time / num_work) << "ns per refill" << endl << endl; junk_val += time_call([]() { alignas(64) xorshift_sse2<uint16_t, 4> rn; seed_rn(rn); return grab_many(rn); }, time); cout << "The vector rng took " << time << " seconds, "; cout << (num_loop * 1.0/time) << " rngs per second " << endl; junk_val += time_call([]() { alignas(64) xorshift_sse2<uint64_t, 4> rn; seed_rn(rn); heavy_work (rn); }, time); cout << "The vector rng took " << time << " seconds for refilling, "; cout << (num_work * 1.0/time) << " refills per second "; cout << "and " << (1e9 * time / num_work) << "ns per refill" << endl << endl; cout << "Caveat - all these numbers are in a hot loop" << endl; }
true
5a3b4b46c66d39b4aacead306d141c7d05851eaf
C++
dlsyj/AlgoPrac
/CiCT/C++/align_malloc.cpp
UTF-8
737
3.0625
3
[]
no_license
// // align_malloc.cpp // Algorithms // // Created by WangJZ on 14-3-20. // Copyright (c) 2014年 WangJZ. All rights reserved. // /* 13.9编写支持对其分配的 malloc和free函数,分配内存时,malloc函数返回的地址必须能被2的n次方整出。 */ #include "cict_c++.h" void *align_malloc(size_t alignment,size_t byte_needed){ void *p1;//申请的指针 void **p2;//返回的指针 size_t offset = alignment - 1 + sizeof(void*); if((p1 = (void *)malloc(byte_needed + offset)) == NULL){ return NULL; }; p2 = (void **)(((size_t)(p1) + offset) & ~(alignment - 1)); p2[-1] = p1; return p2; } void align_free(void *p2){ void *p1 = ((void**)p2)[-1]; free(p1); }
true
e035790c22a269cfb7b80208627a8ce16b5739ce
C++
dev-embedded/juequ
/cpp_primer5/ch1/1-10.cc
UTF-8
289
3.03125
3
[]
no_license
// <<C++ Primer 5th Edition>> by Stanley B. Lippman - Aug2012 // Page 39 (pdf, -25), Chapter 1, // Exe. 1.10 #include <iostream> int main() { std::cout << "Print the numbers from ten down to zero: " <<std::endl; int i=10; while(i>=0) std::cout << i-- <<", "; std::cout << std::endl; return 0; }
true
1f849b5e461b13d25ed38e4ff84c3860d7982ac8
C++
AnYelg/Tienda_digital
/Dog.cpp
UTF-8
662
3.171875
3
[]
no_license
#include "Dog.h" Dog::Dog() { setSize(12); setAge(2); setColor(color); setType("corgi"); setPrecio(10); } Dog::Dog(int theSize, int theAge, Color theColor, string theType) { setSize(theSize); setAge(theAge); setColor(theColor); setType(theType); setPrecio(10); } void Dog::setType (string theType) { type = theType; } string Dog::getType () { return type; } void Dog::soyperro() { cout<<"El tipo de perro es "<< type << endl; cout<<"El tamaño de perro es "<< size << "cm" << endl; cout<<"La edad de perro es "<< age << endl; //cout<<"El color de perro es " << color.imprimircolor()<< endl; }
true
8b8afd334a21461ceec9596d35caf1e88470126a
C++
mhyeun/simon-says
/code/simonsays.cpp
UTF-8
6,204
2.890625
3
[]
no_license
#include "PC_FileIO.c" const int MAX_SIZE = 30; //welcome message void welcomeMessage() { displayCenteredBigTextLine(2, "WELCOME"); displayCenteredBigTextLine(4, "TO"); displayCenteredBigTextLine(6, "SIMON SAYS!"); displayCenteredBigTextLine(8, "860"); displayString(14, " PRESS ANY BUTTON TO BEGIN..."); while(!getButtonPress(buttonAny)) {} while(getButtonPress(buttonAny)) {} eraseDisplay(); } //displays current level void levelCompletion(int level) { eraseDisplay(); displayCenteredBigTextLine(5,"Level: %d",level); } //updates mistake counter void isGameStillGoingOn (int * input, int * output, int & mistakeCounter) { for (int index = 0; index < MAX_SIZE && mistakeCounter == 0; index++) { if(input[index] == output[index]) mistakeCounter = 0; else mistakeCounter = 1; } } //returns which button the user pressed int touchInput(tSensors port1, tSensors port2, tSensors port3, tSensors port4) { wait1Msec(150); int x = -1; while (SensorValue[port1] == 0 && SensorValue[port2] == 0 && SensorValue [port3] == 0 && SensorValue [port4] == 0) {} if(SensorValue[port1] == 1) x = 0; else if (SensorValue[port2] == 1) x = 1; else if (SensorValue[port3] == 1) x = 2; else x = 3; while (SensorValue[port1] == 1 || SensorValue[port2] == 1 || SensorValue [port3] == 1 || SensorValue [port4] == 1) {} return x; } //raises respective flag void raiseFlag(int outputNumber) { const int ENC_LIMIT = 30; const int MOTORSPEED = 10; if(outputNumber == 0) { nMotorEncoder[motorA] = 0; wait1Msec(50); motor[motorA] = MOTORSPEED; while (nMotorEncoder[motorA] < ENC_LIMIT) {} motor[motorA] = 0; wait1Msec(1000); motor[motorA] = -MOTORSPEED; while(nMotorEncoder[motorA] > 0) {} motor[motorA] = 0; } else if(outputNumber == 3) { nMotorEncoder[motorD] = 0; wait1Msec(50); motor[motorD] = MOTORSPEED; while (nMotorEncoder[motorD] < ENC_LIMIT) {} motor[motorD] = 0; wait1Msec(1000); motor[motorD] = -MOTORSPEED; while(nMotorEncoder[motorD] > 0) {} motor[motorD] = 0; } else if(outputNumber == 1) { nMotorEncoder[motorA] = 0; wait1Msec(50); motor[motorA] = -MOTORSPEED; while (nMotorEncoder[motorA] > -ENC_LIMIT) {} motor[motorA] = 0; wait1Msec(1000); motor[motorA] = MOTORSPEED; while(nMotorEncoder[motorA] < 0) {} motor[motorA] = 0; } else if(outputNumber == 2) { nMotorEncoder[motorD] = 0; wait1Msec(50); motor[motorD] = -MOTORSPEED; while (nMotorEncoder[motorD] > -ENC_LIMIT) {} motor[motorD] = 0; wait1Msec(1000); motor[motorD] = MOTORSPEED; while(nMotorEncoder[motorD] < 0) {} motor[motorD] = 0; } } //highscore update void makesHighscore(int userScore) { TFileHandle fin; bool fileOpened = openReadPC(fin, "scores.txt"); if (!fileOpened) { displayString(5, "Cannot open scores"); wait1Msec(5000); } int playerNumber[5]={0,0,0,0,0}; int topScores[5]={0,0,0,0,0}; int index = 0; int currentPlayerNumber = 0; readIntPC(fin,currentPlayerNumber); for (int count = 0; count <=4; count++) { readIntPC(fin, playerNumber[count]); readIntPC(fin, topScores[count]); } while ((index<5)&&(userScore < topScores[index])) { index++; } if (userScore >= topScores[index]) { for(int count = 4; count > index; count--) { topScores[count] = topScores[count-1]; playerNumber[count] = playerNumber[count-1]; } topScores[index] = userScore; playerNumber[index] = currentPlayerNumber+1; } closeFilePC(fin); TFileHandle fout; bool okay = openWritePC(fout, "scores.txt"); if (!okay) { displayString(5, "Cannot write scores"); wait1Msec(5000); } writeLongPC(fout,currentPlayerNumber+1); writeTextPC(fout, " "); for (int count = 0; count <=4; count++) { writeLongPC(fout, playerNumber[count]); writeTextPC(fout, " "); writeLongPC(fout, topScores[count]); writeTextPC(fout, " "); } closeFilePC(fout); } //shutdown procedure void shutDown(int userScore) { eraseDisplay(); TFileHandle fin; bool fileOpened = openReadPC(fin, "scores.txt"); if (!fileOpened) { displayString(5, "Cannot open scores"); wait1Msec(5000); } int playerNumber[5] = {0,0,0,0,0}; int topScores[5] = {0,0,0,0,0}; int currentPlayerNumber = 0; readIntPC(fin, currentPlayerNumber); for (int count = 0; count <=4; count++) { readIntPC(fin, playerNumber[count]); readIntPC(fin, topScores[count]); } displayCenteredBigTextLine(2, "Your score: %d", userScore); displayCenteredBigTextLine(4, "Player#: %d", currentPlayerNumber); int count = 0; displayString(count+7, " PLAYER SCORE"); for (count = 0; count<=4; count++) displayString(count+8, " %d %d", playerNumber[count], topScores[count]); displayString(14, " PRESS ANY BUTTON TO CONTINUE..."); while(!getButtonPress(buttonAny)) {} while(getButtonPress(buttonAny)) {} eraseDisplay(); } task main() { SensorType[S1] = sensorEV3_Touch; wait1Msec(50); SensorType[S2] = sensorEV3_Touch; wait1Msec(50); SensorType[S3] = sensorEV3_Touch; wait1Msec(50); SensorType[S4] = sensorEV3_Touch; wait1Msec(50); int input[MAX_SIZE] = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,}; int output[MAX_SIZE] = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,}; welcomeMessage(); int mistakeCounter = 0, counter = 0; while(mistakeCounter == 0) { levelCompletion(counter + 1); output[counter] = random(3); for (int index0 = 0; index0 <= counter; index0++) raiseFlag(output[index0]); for (int index1 = 0; index1 <= counter; index1++) { input[index1] = touchInput(S1, S2, S3, S4); } isGameStillGoingOn(input, output, mistakeCounter); wait1Msec(1000); counter++; } makesHighscore(--counter); shutDown(counter); }
true
e262b8e592d65edabb8207bb2436c77c68e791f0
C++
Taoaoxiang/PracticeLeetCode
/Problems/0KXXX/0K0XX/0K07X/No_70_Climbing-Stairs.cpp
UTF-8
950
3.734375
4
[]
no_license
//You are climbing a stair case.It takes n steps to reach to the top. // //Each time you can either climb 1 or 2 steps.In how many distinct ways can you climb to the top ? // //Note : Given n will be a positive integer. // // Example 1 : // // Input : 2 // Output : 2 // Explanation : There are two ways to climb to the top. // 1. 1 step + 1 step // 2. 2 steps // // Example 2 : // // Input : 3 // Output : 3 // Explanation : There are three ways to climb to the top. // 1. 1 step + 1 step + 1 step // 2. 1 step + 2 steps // 3. 2 steps + 1 step // //Runtime: 4 ms, faster than 100.00% of C++ online submissions for Climbing Stairs. //Memory Usage : 8.5 MB, less than 55.44% of C++ online submissions for Climbing Stairs. class Solution { public: int climbStairs(int n) { vector<int> vec(n + 1, 0); for (int i = 0; i <= n; ++i) { if (i == 0 || i == 1) { vec[i] = 1; } else { vec[i] = vec[i - 1] + vec[i - 2]; } } return vec[n]; } };
true
9341f21ced0e3a2e5415ae2f0c36e3b385439fcb
C++
nnard1616/HackerRankSolutions
/cpp/Custom_Datastructures/Priority_Deque.hpp
UTF-8
2,344
3.15625
3
[]
no_license
// // Created by Nathan Nard on 12/19/18. // #ifndef CPP_PRIORITY_DEQUE_HPP #define CPP_PRIORITY_DEQUE_HPP #include <bits/stdc++.h> #include "../common/common.hpp" namespace common { template<class Comparable> class Priority_Deque { private: int maxSize; deque<Comparable> unsortedOrder; vector<Comparable> sortedOrder; public: Priority_Deque(int maxSize){ this->maxSize = maxSize; } void enqueue (Comparable in) { if (unsortedOrder.size() < maxSize) { // insert at back unsortedOrder.push_back(in); sortedOrder.insert(common::binary_search_for_insertion_point(in, sortedOrder), in); } else { // erase head dequeue(); // insert at back unsortedOrder.push_back(in); sortedOrder.insert(common::binary_search_for_insertion_point(in, sortedOrder), in); } } bool dequeue () { Comparable toBeErased = unsortedOrder[0]; sortedOrder.erase(common::binary_search_for_insertion_point(toBeErased, sortedOrder)); // next line causes a segfault?? // SIGILL (signal SIGILL: illegal instruction operand) // Process finished with exit code 132 (interrupted by signal 4: SIGILL) unsortedOrder.pop_front(); // <-- this fucker! } typename deque<Comparable>::iterator begin() { return unsortedOrder.begin(); } typename deque<Comparable>::iterator end() { return unsortedOrder.end(); } typename deque<Comparable>::iterator rbegin() { return unsortedOrder.rbegin(); } typename deque<Comparable>::iterator rend() { return unsortedOrder.rend(); } Comparable operator[] (int i) { return unsortedOrder[i]; } float median() { float result; if (sortedOrder.size() % 2 == 0){ result = (sortedOrder[sortedOrder.size()/2] + sortedOrder[sortedOrder.size()/2-1])/2.0; } else{ result = sortedOrder[sortedOrder.size()/2]; } return result; } }; } #endif //CPP_PRIORITY_DEQUE_HPP
true
7aea40ffba2816a45a7883e8e145f8712c03b200
C++
OMWi/oaip-1sem
/Лабы/LR5/dop2(ne nado)/File1.cpp
UTF-8
1,497
2.921875
3
[]
no_license
#pragma hdrstop #pragma argsused #include <iostream> #include <conio.h> #include <ctime> using namespace std; float **Create(int line, int col) { float **arr = new float *[line]; for (int i = 0; i < line; i++) { arr[i] = new float [col]; } return arr; } void Delete(float **arr, int line) { for (int i = 0; i < line; i++) { delete arr[i]; } delete []arr; } void Print(float **arr, int line, int col) { for (int i = 0; i < line; i++) { for (int j = 0; j < col; j++) { cout << arr[i][j] << '\t'; } cout << endl; } cout << endl; } void Fill(float **arr, int line, int col) { srand(time(0)); for (int i = 0; i < line; i++) { for (int j = 0; j < col; j++) { arr[i][j] = (rand()%1001-500)/10; } } } int Check (float **arr, int line, int col) { for (int i = 0, check = 0; i < line; i++) { for (int j = 0; j < col; j++) { if (!arr[i][j]) { check++; } } } } int _tmain(int argc, _TCHAR* argv[]) { int line, col; cout << "Line "; cin >> line; cout << "Column "; cin >> col; float **arr = Create(line, col); Fill(arr, line, col); Print(arr, line, col); int size = Check(arr, line, col); float *arr1 = new float [size]; for (int i = 0, c = 0; i < line; i++) { for (int j = 0; j < col; j++) { if (!arr[i][j]) { arr1[c++] = arr[i][j]; } } } for (int i = 0; i < size; i++) { cout << arr1[i] << '\t'; } Delete(arr, line); getch(); return 0; }
true
314e55d194b869297acd64891c99f05d3e0707cf
C++
kunhuicho/crawl-tools
/codecrawler/_code/hdu1040/16207629.cpp
UTF-8
1,394
2.828125
3
[]
no_license
/* * hdu-1040 * mike-w * 2012-4-14 */ #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_SIZE 1024 #define HEAP_SIZE 2048 #define LC(X) (2*(X)) #define RC(X) (2*(X)+1) #ifndef true #define true 1 #endif int heap[HEAP_SIZE]; int N,T; int swap(int *e1, int *e2) { int tmp=*e1; *e1=*e2; *e2=tmp; return 0; } int heap_in(int e) { if(heap[0]==HEAP_SIZE) return -1; heap[++heap[0]]=e; int x=heap[0]; int p=x/2; while(p>0 && heap[p]>heap[x]) swap(heap+p,heap+x),x=p,p/=2; return 0; } int heap_out(void) { if(heap[0]==0) return -1; int ret=heap[1]; swap(heap+1,heap+heap[0]); heap[0]--; int p=1,x; int lc,rc; while(true) { lc=LC(p); rc=RC(p); x=p; if(lc<=heap[0] && heap[lc]<heap[x]) x=lc; if(rc<=heap[0] && heap[rc]<heap[x]) x=rc; if(x==p) break; swap(heap+x,heap+p); p=x; } return ret; } int main(void) { #ifndef ONLINE_JUDGE freopen("in","r",stdin); #endif int e; scanf("%d",&T); while(T-->0) { heap[0]=0; scanf("%d",&N); while(N-->0) scanf("%d",&e), heap_in(e); while(heap[0]>0) printf("%d",heap_out()),putchar(heap[0]==0?'\n':' '); /* 注意副作用 */ } return 0; }
true
0a0e522feeda560d2a81f2f1e03d1259894526d3
C++
MarDPop/rocket
/project/SingleStage/src/proto/src/WindHistory.cpp
UTF-8
1,866
2.921875
3
[]
no_license
#include "../include/WindHistory.h" #include <iostream> #include <fstream> #include <string> #include "../../common/include/util.h" WindHistory::WindHistory() { this->wind.zero(); } WindHistory::~WindHistory() {} void WindHistory::load(std::string fn) { std::ifstream file(fn); if(!file.is_open()) { throw std::invalid_argument("could not open file."); } std::string line; while(std::getline(file, line)) { std::vector<std::string> data = util::split(line); this->times.push_back(std::stod(data[0])); this->speed.emplace_back(std::stod(data[1]),std::stod(data[2]),std::stod(data[3])); } file.close(); this->reset(); this->constant = this->times.size() < 2; if(this->constant){ if(this->times.size() == 1) { this->wind = this->speed[0]; } else { this->wind.zero(); } } } void WindHistory::reset() { this->titer = times.data(); this->siter = speed.data(); this->tend = this->titer + times.size() - 1; this->constant = times.size() == 1; if(!this->constant) { double dt = 1.0/(*(titer + 1) - *titer); this->dvdt = (*(siter + 1) - *siter)*dt; } } void WindHistory::set(double altitude, double time) { if(this->constant){ return; } if(titer < tend && time > *(titer+1)) { titer++; siter++; if(titer == tend) { this->dvdt.zero(); this->constant = true; } else { double dt = 1.0/(*(titer + 1) - *titer); this->dvdt = (*(siter + 1) - *siter)*dt; } } double dt = time - *titer; this->wind.data[0] = siter->data[0] + this->dvdt.data[0]*dt; this->wind.data[1] = siter->data[1] + this->dvdt.data[1]*dt; this->wind.data[2] = siter->data[2] + this->dvdt.data[2]*dt; }
true