blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
5b92ba3410cc40821061f8b587030a4e266fd2b6
4de4a3e634a736766b2f2667a34af142ef33fdc6
/Simple Battleship Game/Main.cpp
c1c7d7fa24f4b29fbc94ac536b369512878ecc33
[]
no_license
Jesse-Richman/CPlusPlus_Examples
1ed0813b89921c4f27eacb2ebff0db266e118ff4
4bf7eecb6ea8e611429d302c273e11593628780a
refs/heads/master
2023-01-27T13:34:54.324572
2020-05-01T17:27:09
2020-05-01T17:27:09
260,484,294
0
0
null
null
null
null
UTF-8
C++
false
false
1,904
cpp
Main.cpp
#include <iostream> #include <fstream> #include <string> using namespace std; const int MAP_SIZE = 25; const char SHIP = '#'; const char WATER = '~'; const char HIT = 'H'; const char MISS = 'M'; char map[MAP_SIZE][MAP_SIZE]; // Method prototypes void fire(int, int); bool checkForWin(); void printMap(); int main() { // load game map ifstream inFile("./GameBoard.txt"); for (int i = 0; i < MAP_SIZE; ++i) { for (int j = 0; j < MAP_SIZE; ++j) { inFile >> map[i][j]; } } // Main game loop string strX, strY; while (!checkForWin()) { cout << "Enter the cooridnates that you want to attack (i.e 2 2): "; cin >> strX >> strY; fire(stoi(strX), stoi(strY)); printMap(); } cout << "Congrats! You sunk all the enemy ships." << endl; printMap(); return 0; } void fire(int x, int y) { char* coordPtr = &map[x][y]; // check for out of bounds if (x < 0 || x >= MAP_SIZE) { cout << "X-coordinate must be 0-" << MAP_SIZE << endl; return; } else if (y < 0 || y >= MAP_SIZE) { cout << "Y-coordinate must be 0-" << MAP_SIZE << endl; return; } if (*coordPtr == SHIP) { cout << "Hit!" << endl; *coordPtr = HIT; } else if (*coordPtr == HIT) { cout << "Hit again!" << endl; } else if (*coordPtr == WATER){ cout << "Miss" << endl; *coordPtr = 'M'; } else { cout << "Miss again!" << endl; } } bool checkForWin() { for (int i = 0; i < MAP_SIZE; ++i) { for (int j = 0; j < MAP_SIZE; ++j) { if (map[i][j] == SHIP) return false; } } return true; } void printMap() { for (int i = 0; i < MAP_SIZE; ++i) { for (int j = 0; j < MAP_SIZE; ++j) { cout << map[i][j]; } cout << endl; } }
50231747d4e91feea3f043bb173bbe0929dc5d8b
5df2f7664f98e3f670cdd475d9b30739c8a31a3e
/CYOA/rpcp2p.cc
7b6b48672112c163732c14d94d3a558b4f2a3fbe
[]
no_license
heroicbran/games
b7512edd59777aaf91a369cc96df91c2b77f8420
5439a38e36ccb1616f38a716d30d60c45f2414b1
refs/heads/master
2021-05-25T10:02:57.536173
2020-06-05T17:48:31
2020-06-05T17:48:31
127,050,884
0
0
null
null
null
null
UTF-8
C++
false
false
8,037
cc
rpcp2p.cc
#include <string> #include <fstream> #include <iostream> #include <vector> #include <list> #include "rpc/client.h" #include "rpc/server.h" #include "rpc/this_session.h" #include "rpc/this_server.h" #include <dirent.h> #include <chrono> using namespace std; //A few globals needed because of RPC setup int pcount = 0; //Keeps track of the number of peers. struct file_entry //An entry in the indexing server file index { string name; int id; }; vector<file_entry> file_index; //Does the registry RPC call void registry(int peer, vector<string> file_list) { file_entry fe; for (int i = 0; i < file_list.size(); i++) { fe.name = file_list[i]; fe.id = peer; cout << "Updating file index, adding: " << fe.name << endl; file_index.push_back(fe); } cout << endl << "***NEW INDEX***" <<endl; for(int i = 0; i < file_index.size(); i++) { cout << file_index[i].name <<endl; } cout << "**************" <<endl <<endl; } //Searches for a file and returns the peers with the file int search_file(int peer, string file_name) { vector<int> matches; //Search vector for file for(int i = 0; i < file_index.size(); i++) { if (file_index[i].name == file_name) matches.push_back(file_index[i].id); } //Print matching entry peer ID #. if (matches.size() > 0) { cout <<"The peer ID(s) with " <<file_name << ": "; for (int i=0; i <matches.size(); i++) { cout <<"Peer "<< matches[i]; } cout <<endl <<endl; return matches[0]; } else { cout << "No matches found!" <<endl <<endl; } return 0; } //Returns a string vector for file copying vector<string> copy_file(string input) { vector<string> file_content; ifstream file_stream; string line_in; file_stream.open(input); while (getline(file_stream, line_in)) { //cout << line_in <<endl; file_content.push_back(line_in); } file_stream.close(); return file_content; } //Gives a peer the port of another peer int obtain_peer(int peer, string file_name) { return 9000 + search_file(peer, file_name); } //Run val searches for testing purposes. int test_search(int val) { int count = val; ifstream file_stream; string line_in; file_stream.open("1000_words"); std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); while (getline(file_stream, line_in) && count > 0) { search_file(1,line_in); count--; } file_stream.close(); std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); std::cout << "The searches took this much time (in ms) = " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() <<std::endl; return 0; } //Used to select the type of process int type_select() { int sel; cout << "Select operation mode (Server = 1, Peer = 2): "; cin >> sel; return sel; } int convert_input(string input) { if (input == "?") { return 0; } else if (input == "r" || input == "registry") { return 1; } else if (input == "s" || input == "search") { return 2; } else if (input == "o" || input == "obtain") { return 3; } else if (input == "t" || input == "test") { return 4; } else if (input == "q" || input == "quit") { return 5; } else if (input == "c" || input == "close" || input == "close_server") { return 6; } else { return 9; } } //Gives a peer their ID int get_id() { cout << "Peer " <<++pcount <<" has connected!" <<endl; return pcount; } //Gets list of a peer's files vector<string> get_files() { vector<string> files; cout <<"Adding file information to indexing server..." <<endl; DIR *fdir = opendir("./"); dirent *file_direc = readdir(fdir); while (file_direc = readdir(fdir)) { if (strlen(file_direc->d_name) > 3) //Removes unnecessary extras { cout << "Updating file index, adding: " <<file_direc->d_name <<endl; files.push_back(file_direc->d_name); } } cout << "Operation complete." <<endl <<endl; return files; } int main() { string ip; int port; int select = 0; int peer_id = 0; select = type_select(); //Process for server if (select == 1) { cout << "This process will operate as the Server." <<endl <<endl; cout << "Select the port that will be used for listening: "; cin >> port; cout << endl; cout << "The server is now active." <<endl; //Set up server, bind each of the commands for peer rpc::server server(port); server.bind("registry", &registry); //server.bind("quit", &quit); server.bind("search", &search_file); server.bind("obtain", &obtain_peer); server.bind("test_search", &test_search); server.bind("get_id", &get_id); server.bind("exit", []() { rpc::this_session().post_exit(); // post exit to the queue }); server.bind("stop_server", []() { rpc::this_server().stop(); }); server.run(); } //Process for the peer else if (select == 2) { cout << "This process will operate as a Peer." <<endl <<endl; cout << "Select the IP address to connect to: "; cin >> ip; cout << "Select the port: "; cin >> port; rpc::client client(ip, port); //get peer id peer_id = client.call("get_id").as<int>(); //Set up peer server int peer_port = peer_id + 9000; rpc::server pserver("127.0.0.1", peer_port); pserver.bind("copy_file", &copy_file); pserver.bind("exit", []() { rpc::this_session().post_exit(); // post exit to the queue }); //Spawns thread to handle P2P operations and have it listen pserver.async_run(1); int status = 1; string input; int int_in; cout << "Connection Established!" <<endl <<endl; //Determines what call is sent to the server while (status == 1) { cout << "Please enter a command (Use ? for help): "; cin >> input; int_in = convert_input(input); switch(int_in) { case 0: cout << "The following commands can be used: registry, search, obtain, exit, stop_server, test" <<endl; break; case 1: cout <<endl; client.call("registry",peer_id, get_files()); break; case 2: cout << "Enter the file you are searching for: "; cin >>input; cout << "Peer ID(s) with file: Peer with ID # " <<client.call("search", peer_id, input).as<int>() <<endl; break; case 3: cout << "Enter the file you are trying to obtain: "; cin >>input; //Cannot use the rpc::client code here due to the scope of the case statement. break; //Do file transfer outside of case statement. case 4: cout << "How many iterations?: "; cin >> int_in; client.call("test_search", int_in); break; case 5: client.call("exit", 1); break; case 6: client.call("stop_server", 1); break; default: cout << "Please enter a valid command." <<endl; } //Copies the file for the peer who requests it if (int_in == 3) { vector<string> file_content; ofstream output_file (input); rpc::client pclient("127.0.0.1", client.call("obtain", peer_id, input).as<int>()); file_content = pclient.call("copy_file",input).as<vector<string>>(); cout <<endl <<endl; for (int i=0; i < file_content.size(); i++) { output_file << file_content[i]; if (i < 10) cout << file_content[i]; if (i == 11) cout << "..........." <<endl <<endl; } cout << input << " has been copied." <<endl; output_file.close(); //close file stream pclient.call("exit"); //close session with other peer } } } else { cout << "Please select 1 for Server or 2 for Peer." <<endl; } cout << "The process has ended." <<endl <<endl; return 0; }
97f358f12619d78aa6f20d8379b6e44dbb29de52
ee2034f4bc89cd0a3631e9fc804860290ec6d869
/src/Group.cpp
2f9e1b02b6c16c9c1e5bea7fbc8ebfd141072fd4
[]
no_license
nancynh/Organ-Trail
5630a871d95403a1addb3949b587790139f1db21
0189bb0ad80ce861b20807cee17a28364b042421
refs/heads/master
2020-03-15T09:08:11.567963
2018-05-04T01:26:35
2018-05-04T01:26:35
132,067,833
0
0
null
null
null
null
UTF-8
C++
false
false
4,090
cpp
Group.cpp
// // Group.cpp // final-project-nancynh // // Created by Nancy Hong on 4/17/18. // #include "Group.hpp" Group::Group() { this->current_vehicle_ = nullptr; this->food_amount_ = 0; this->water_amount_ = 0; this->medicine_amount_ = 0; this->money_ = 0; } Group::Group(Vehicle* current_vehicle, int food_amount, int water_amount, int medicine_amount, int money) { this->current_vehicle_ = current_vehicle; this->food_amount_ = food_amount; this->water_amount_ = water_amount; this->medicine_amount_ = medicine_amount; this->money_ = money; } std::string Group::StatInfo() { return "Food: " + std::to_string(food_amount_) + " Water: " + std::to_string(water_amount_) + "\nMedicine: " + std::to_string(medicine_amount_) + " Money: " + std::to_string(money_); } void Group::RemoveEquipment(Equipment item) { for (int i = 0; i < inventory_.size(); i++) { if (item == inventory_[i]) { inventory_.erase(inventory_.begin() + i); break; } } } void Group::AddEquipment(Equipment item) { inventory_.push_back(item); } bool Group::InInventory(Equipment item) { for (int i = 0; i < inventory_.size(); i++) { if (item == inventory_[i]) { return true; } } return false; } void Group::AddPlayer(Player* player) { players_in_group_.push_back(player); } void Group::RemovePlayer(Player *player) { for (int i = 0; i < players_in_group_.size(); i++) { if (*player == *players_in_group_[i]) { players_in_group_.erase(players_in_group_.begin() + i); delete(player); break; } } } void Group::RemoveAllGroupMembers() { for (int i = 1; i < players_in_group_.size(); i++) { players_in_group_.erase(players_in_group_.begin() + i); delete(players_in_group_[i]); } } void Group::Eat(int amount) { for (int i = 0; i < players_in_group_.size(); i++) { if (food_amount_ <= 0) { food_amount_ = 0; break; } players_in_group_[i]->Eat(amount); food_amount_ -= amount; } } void Group::Drink(int amount) { for (int i = 0; i < players_in_group_.size(); i++) { if (water_amount_ <= 0) { water_amount_ = 0; break; } players_in_group_[i]->Drink(amount); water_amount_ -= amount; } } void Group::AddFood(int amount) { food_amount_ += amount; } void Group::AddWater(int amount) { water_amount_ += amount; } void Group::AddMedicine(int amount) { medicine_amount_ += amount; } void Group::AddMoney(int amount) { money_ += amount; } void Group::RemoveFood(int amount) { food_amount_ -= amount; } void Group::RemoveWater(int amount) { water_amount_ -= amount; } void Group::RemoveMedicine(int amount) { medicine_amount_ -= amount; } void Group::RemoveMoney(int amount) { money_ -= amount; } void Group::DecreaseHealth(int index, int amount) { players_in_group_[index]->set_health(players_in_group_[index]->get_health() - amount); } Vehicle* Group::get_current_vehicle() { return current_vehicle_; } Player* Group::get_main_player() { return players_in_group_[0]; } std::vector<Player*> Group::get_players_in_group() { return players_in_group_; } std::vector<Equipment> Group::get_inventory() { return inventory_; } int Group::get_food_amount() { return food_amount_; } int Group::get_water_amount() { return water_amount_; } int Group::get_medicine_amount() { return medicine_amount_; } int Group::get_money() { return money_; } void Group::set_current_vehicle(Vehicle* vehicle) { current_vehicle_ = vehicle; } void Group::set_food_amount(int amount) { food_amount_ = amount; } void Group::set_water_amount(int amount) { water_amount_ = amount; } void Group::set_meicine_amount(int amount) { medicine_amount_ = amount; } void Group::set_money(int amount) { money_ = amount; }
cdb5e14df1a0b2e244c78d7aa26147fc7bd76197
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/codeforce/edu/061-080/077/d.cpp
57f8bd22249ad15fda8eb20b2584562f2c1fe58f
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
1,398
cpp
d.cpp
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) //------------------------------------------------------- int M,N,K,T; int A[202020]; int L[202020],R[202020],D[202020]; int ok(int v) { if(v>M) return 0; int S=A[v-1]; vector<pair<int,int>> V; int i; FOR(i,K) if(D[i]>S) V.push_back({L[i],R[i]}); sort(ALL(V)); int ret=N+1; int PL=0,PR=0; FORR(v,V) { if(v.first<=PR) { PR=max(PR,v.second); } else { if(PL) ret+=(PR-PL+1)*2; PL=v.first; PR=v.second; } } if(PL) ret+=(PR-PL+1)*2; return ret<=T; } void solve() { int i,j,k,l,r,x,y; string s; cin>>M>>N>>K>>T; FOR(i,M) cin>>A[i]; sort(A,A+M); reverse(A,A+M); FOR(i,K) cin>>L[i]>>R[i]>>D[i]; int ret=0; for(i=20;i>=0;i--) if(ok(ret+(1<<i))) ret+=1<<i; cout<<ret<<endl; } int main(int argc,char** argv){ string s;int i; if(argc==1) ios::sync_with_stdio(false), cin.tie(0); FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin); cout.tie(0); solve(); return 0; }
17106414649dcdaf8708b0800ba5623fb1ed8ba8
530162df7eb8871928e6b86787e51caca7617e1c
/escena_basica/src/wavesManager.h
495ed7932f8330e381ddd00f7e5c197764a7396b
[]
no_license
serman/muncyt
11b61989eb7fce3d94fa8ad06657c6c0381464d3
c62c0042048d673f61d723bb18d449ab646707fa
refs/heads/master
2021-03-12T22:51:41.764670
2017-09-11T10:14:11
2017-09-11T10:14:11
18,833,902
1
0
null
null
null
null
UTF-8
C++
false
false
6,597
h
wavesManager.h
// // wavesManager.h // escena_basica // // Created by Sergio Galan on 7/13/14. // // #ifndef escena_basica_wavesManager_h #define escena_basica_wavesManager_h #include "waves.h" #include "tangibleObject.h" #include "cheapComm.h" #define MAX_ONDAS 6 struct trIndices{ int n_wave; int new_index; }; class wavesManager : public tangibleObject{ public: vector<waves> waveslist; waves *singleWave; // int waves_id_counter; int howManyWaves(){ return num_waves; } void countWaves(){ int count=0; for(int i=0; i<waveslist.size(); i++){ if(waveslist[i].isCompleted()) count++; } num_waves= count; } void setup(){ singleWave= new waves(0); singleWave->setup(); for(int i=0; i<waveslist.size(); i++){ waveslist[i].setup(); // esta funcion descarta el id si no lo tiene } } void reset(){ waveslist.clear(); delete singleWave; singleWave=NULL; setup(); countWaves(); } void draw(){ for(int i=0; i<waveslist.size(); i++){ waveslist[i].draw(); // esta funcion descarta el id si no lo tiene } } void update(){ countWaves(); for(int i=0; i<waveslist.size(); i++){ waveslist[i].update(); // esta funcion descarta el id si no lo tiene } puntos_ondas=0; //va a almacenar la cantidad de puntos totales que hay para asignar a las distintas particulas for(int i=0; i<howManyWaves(); i++){ puntos_ondas+=waveslist[i].points.size(); } }; void touch(float x, float y, int s_id){ //if(singleWave->isCompleted==false ){ //creamos una onda singleWave->addPoint(x,y,s_id); if(singleWave->isCompleted()==true){ waveslist.push_back(*singleWave); cheapComm::getInstance()->sendAudio1("/audio/electromagnetism/create_wave_event",singleWave->waveID); cheapComm::getInstance()->sendSync0("/sync/electromagnetism/create_wave_event"); singleWave= new waves(getAvailableId()); //esta onda se queda como incompleta hasta que se le añadan 2 puntos } //} } void slide(float x, float y, int s_id, int acc){ for(int i=0; i<waveslist.size(); i++){ waveslist[i].updateCursor(s_id,x,y); // esta funcion descarta el id si no lo tiene } } void touchUp(int s_id){ if(singleWave->contains(s_id)) singleWave->remove_id(s_id); for(int i=0; i<waveslist.size(); i++){ if(waveslist[i].contains(s_id)){ cheapComm::getInstance()->sendAudio1("/audio/electromagnetism/destroy_wave_event", waveslist[i].waveID); cheapComm::getInstance()->sendSync0("/sync/electromagnetism/destroy_wave_event"); waveslist[i].remove_id(s_id); if(singleWave->isHalf() ){// si hay otro cursor soltero los uno y creo una onda entre ellos waveslist[i].addPoint(singleWave->getSinglePoint().x,singleWave->getSinglePoint().y,singleWave->getSinglePointID()); singleWave->clear(); } else{ //Si no hay otro cursor la onda actual es la soltera if( singleWave != NULL) //delete singleWave; singleWave->p1= waveslist[i].p1; singleWave->p2= waveslist[i].p2; singleWave->p2_id= waveslist[i].p2_id; singleWave->p1_id= waveslist[i].p1_id; singleWave->p1set= waveslist[i].p1set; singleWave->p2set= waveslist[i].p2set; waveslist.erase(waveslist.begin()+i); } break; } } } void touchUpAll(){ } /* ind es el numero de onda al que tiene que ir un punto devuelve una onda a la que ir y un indice dentro de esa onda */ trIndices num_onda(int ind,int i){ // i siempre va a ser un multiplo de ind int onda_asignada=ind; if(ind>=howManyWaves()){ onda_asignada=ind%howManyWaves(); } int npuntos=waveslist[onda_asignada].points.size(); // tengo npuntos que asignar a un cierto numero de particulas. Los asigno en orden trIndices trindex; int indicereal=i/(ind+1); int puntoAsignado=indicereal%npuntos; trindex.n_wave=onda_asignada; trindex.new_index=puntoAsignado; return trindex; /* int counter=0; for(int i=0; i<howManyWaves(); i++){ //recorro cada onda La condicion para asignarle el punto a la onda es que esté if(ind>=counter && (ind < (counter+waveslist[i].points.size() )) ){ trindex.n_wave=i; trindex.new_index=ind-counter; return trindex; } counter += waveslist[i].points.size(); } trindex.n_wave=-1; return trindex;*/ } void debugInfo(){ if(ofGetFrameNum()%30==0){ ofLogNotice() << "Numero de ondas" << ofToString(howManyWaves()) ; ofLogNotice() << "onda single half: " << ofToString(singleWave->isHalf()) ; if(singleWave->p1set){ ofLogNotice() << "p1 " << ofToString(singleWave->p1_id) ; } if(singleWave->p2set){ ofLogNotice() << "___ p2: " << ofToString(singleWave->p2_id) << endl; } for(int i; i<waveslist.size(); i++){ ofLogNotice() << "onda "<< ofToString(i) << ": " << ofToString(waveslist[i].p1_id ) << "p2: " << ofToString( waveslist[i].p2_id )<< endl; } } } int getSingleWaveId(){ if(singleWave->isHalf()==true){ return singleWave->getSinglePointID(); } else return -1; } int getAvailableId(){ for(int idToCheck=0; idToCheck<8; idToCheck++){ int i=0; for(i=0; i<waveslist.size(); i++){ if(waveslist[i].waveID==idToCheck) break; } if(i==waveslist.size()){ return idToCheck; } } return -1; } private: int puntos_ondas; int num_waves; }; #endif
37473df0f680600581973c9b96d9e8cba4a5fe79
1adb91f53169165ce62788c74f81028614517ea1
/data_2d/camera_sequence.hpp
9634d3feda14d1f46ec0bd9f38a609f69d88b93b
[]
no_license
bebuch/tools
7b389d9da0122a3d1c0b6af0811b0666469a8122
5107ab0f2ab51594896226d9a96f8d6c7dd10c01
refs/heads/master
2021-01-13T04:27:39.053388
2017-01-23T21:04:11
2017-01-23T21:04:11
79,848,028
1
0
null
null
null
null
UTF-8
C++
false
false
1,209
hpp
camera_sequence.hpp
#ifndef _tools_camera_sequence_hpp_INCLUDED_ #define _tools_camera_sequence_hpp_INCLUDED_ #include "bitmap_sequence.hpp" namespace tools { /// \brief List of tools::bitmap_sequence< T > template < typename T > using camera_sequence = std::vector< bitmap_sequence< T > >; /// \brief List of tools::bitmap_pointer_sequence< T > template < typename T > using camera_pointer_sequence = std::vector< std::shared_ptr< bitmap_pointer_sequence< T > > >; /// \brief List of tools::bitmap_pointer_sequence< T > template < typename T > using camera_const_pointer_sequence = std::vector< std::shared_ptr< bitmap_const_pointer_sequence< T > const > >; template < typename T > camera_const_pointer_sequence< T > make_const(camera_pointer_sequence< T >&& data){ camera_const_pointer_sequence< T > result; result.reserve(data.size()); for(auto& v: data){ result.push_back(make_const(std::move(v))); } return result; } template < typename T > std::shared_ptr< camera_const_pointer_sequence< T > const > make_const(std::shared_ptr< camera_pointer_sequence< T > >&& data){ return std::make_shared< camera_const_pointer_sequence< T > const >(make_const(std::move(*data))); } } #endif
4f06b6cabc45de1aae1d2dd8f66ed57fa29e242e
52dc9080af88c00222cc9b37aa08c35ff3cafe86
/0100/60/165a.cpp
1364f6f1c46742ce17ff7377c3c1ebdb4b5a86f6
[ "Unlicense" ]
permissive
shivral/cf
1c1acde25fc6af775acaeeb6b5fe5aa9bbcfd4d2
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
refs/heads/master
2023-03-20T01:29:25.559828
2021-03-05T08:30:30
2021-03-05T08:30:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,441
cpp
165a.cpp
#include <algorithm> #include <iostream> #include <unordered_map> #include <vector> void answer(size_t v) { std::cout << v << '\n'; } int main() { using point_t = std::pair<int, int>; size_t n; std::cin >> n; std::unordered_map<int, std::vector<point_t>> groups_by_x; std::unordered_map<int, std::vector<point_t>> groups_by_y; for (size_t i = 0; i < n; ++i) { int x, y; std::cin >> x >> y; groups_by_x[x].emplace_back(x, y); groups_by_y[y].emplace_back(x, y); } size_t count = 0; for (auto& entry : groups_by_x) { auto& group_by_x = entry.second; if (group_by_x.size() < 3) continue; std::sort(group_by_x.begin(), group_by_x.end()); for (size_t i = 1; i < group_by_x.size() - 1; ++i) { const point_t& candidate = group_by_x[i]; const auto& group_by_y = groups_by_y[candidate.second]; if (group_by_y.size() < 3) continue; size_t lesser = 0, greater = 0; for (const point_t& p : group_by_y) { if (p.first < candidate.first) ++lesser; if (p.first > candidate.first) ++greater; if (lesser > 0 && greater > 0) break; } count += (lesser > 0 && greater > 0); } } answer(count); return 0; }
0ac676fd39cf2dd51a323316c2e5ddaaff2c9781
0a61edcca49c1000616b71cdaf99e332621f06e5
/src/Nodes/PulseCounter.hpp
ae2048435390f7700eba6367ed55adb5c6861062
[ "MIT" ]
permissive
yves-ledermann/homie-esp8266-supplements
d954a0522e5fd46757f26b74c85490fea1a75ba9
fd295c5a44e3aa44c6c13ba540c45e6356a8d9b6
refs/heads/master
2021-01-22T01:54:42.989203
2017-11-21T10:19:40
2017-11-21T10:19:40
81,017,058
6
0
null
null
null
null
UTF-8
C++
false
false
5,326
hpp
PulseCounter.hpp
#pragma once #include <Homie.hpp> /** * PulseSensorProperties * * Structure that holds essential information about a sensor. * Stores general sensor properties and calibration points. * */ typedef struct { double capacity; //!< capacity, upper limit of flow rate (in l/min) double kFactor; //!< "k-factor" (in (pulses/s) / (l/min)), e.g.: 1 pulse/s = kFactor * l/min double mFactor[10]; //!< multiplicative correction factor near unity, "meter factor" (per decile of flow) } PulseSensorProperties; extern PulseSensorProperties UncalibratedSensor; //!< default sensor extern PulseSensorProperties G1; //!< see documentation about extern PulseSensorProperties FS300A; //!< see documentation about FS300A/SEN02141B extern PulseSensorProperties FS400A; //!< see documentation about FS400A/USN-HS10TA class Node_PulseCounter: public HomieNode { public: Node_PulseCounter(const char* name, const uint8_t PinNumber, const char* unit = "l", const char* period = "min", PulseSensorProperties prop = UncalibratedSensor); void setup(); void handleInterrupt(); void loop(); void setDebug(bool debug); void setInterval(uint16_t interval); double getCurrentRate(); //!< Returns the current flow rate since last reset (in l/min). double getCurrentQuantity(); //!< Returns the current volume since last reset (in l). double getTotalRate(); //!< Returns the (linear) average flow rate in this flow meter instance (in l/min). double getTotalQuantity(); //!< Returns the total volume flown trough this flow meter instance (in l). /** * The tick method updates all internal calculations at the end of a measurement period. * * We're calculating flow and volume data over time. * The actual pulses have to be sampled using the count method (i.e. via an interrupt service routine). * * Flow sensor formulae: * * Let K: pulses per second per unit of measure (i.e. (1/s)/(l/min)), * f: pulse frequency (1/s), * Q: flow rate (l/min), * p: sensor pulses (no dimension/unit), * t: time since last measurements (s). * * K = f / Q | units: (1/s) / (l/min) = (1/s) / (l/min) * <=> | Substitute p / t for f in order to allow for different measurement intervals * K = (p / t) / Q | units: ((1/s)/(l/min)) = (1/s) / (l/min) * <=> | Solve for Q: * Q = (p / t) / K | untis: l/min = 1/s / (1/s / (l/min)) * <=> | Volume in l: * V = Q / 60 | units: l = (l/min) / (min) * * The property K is sometimes stated in pulses per liter or pulses per gallon. * In these cases the unit of measure has to be converted accordingly (e.g. from gal/s to l/min). * See file G34_Flow_rate_to_frequency.jpg for reference. * * @param duration The tick duration (in ms). */ void tick(unsigned long duration = 1000); void count(); //!< Increments the internal pulse counter. Serves as an interrupt callback routine. void reset(); //!< Prepares the flow meter for a fresh measurement. Resets all current values. /* * convenience methods and calibration helpers */ unsigned int getPin(); //!< Returns the Arduino pin number that the flow sensor is connected to. unsigned long getCurrentDuration(); //!< Returns the duration of the current tick (in ms). double getCurrentFrequency(); //!< Returns the pulse rate in the current tick (in 1/s). double getCurrentError(); //!< Returns the error resulting from the current measurement (in %). unsigned long getTotalDuration(); //!< Returns the total run time of this flow meter instance (in ms). double getTotalError(); //!< Returns the (linear) average error of this flow meter instance (in %). private: String _name; uint8_t _PinNumber; String _unit; String _period; PulseSensorProperties _properties; //!< sensor properties (including calibration data) bool _debug = true; void update(); uint16_t _Interval = 1000UL; uint32_t _lastLoopUpdate = 0; unsigned long _currentDuration; //!< current tick duration (convenience, in ms) double _currentFrequency; //!< current pulses per second (convenience, in 1/s) double _currentRate = 0.0f; //!< current flow rate (in l/tick), e.g.: 1 l / min = 1 pulse / s / (pulses / s / l / min) double _currentQuantity = 0.0f; //!< current volume (in l), e.g.: 1 l = 1 (l / min) / (60 * s) double _currentCorrection; //!< currently applied correction factor unsigned long _totalDuration = 0.0f; //!< total measured duration since begin of measurement (in ms) double _totalQuantity = 0.0f; //!< total volume since begin of measurement (in l) double _totalCorrection = 0.0f; //!< accumulated correction factors volatile unsigned long _currentPulses = 0; //!< pulses within current sample period };
bb95fe1d35bc9b3ba5da7eebbfbaae3f030a1b84
f4dc1073def4c95a19d4183475405c439cfc0aff
/Source/Editors/AStudio/lightmass/ConfigMgr.cpp
3bd318dce4d7aaf66ee4f3a3df776232c472ed4e
[]
no_license
timi-liuliang/aresengine
9cf74e7137bb11cd8475852b8e4c9d51eda62505
efd39c6ef482b8d50a8eeaa5009cac5d5b9f41ee
refs/heads/master
2020-04-15T15:06:41.726469
2019-01-09T05:09:35
2019-01-09T05:09:35
164,779,995
1
0
null
null
null
null
GB18030
C++
false
false
4,978
cpp
ConfigMgr.cpp
//#include <algorithm> //#include "ConfigMgr.h" //#include <boost/lexical_cast.hpp> //#include <Core/3rdParty/RapidXml/rapidxml_utils.hpp> //#include <Core/3rdParty/RapidXml/rapidxml_print.hpp> // //using namespace boost; // //namespace Ares //{ // template<> ConfigMgr* Singleton<ConfigMgr>::m_singleton = new ConfigMgr; // // // 构造函数 // ConfigMgr::ConfigMgr() // : m_tabIdx( 0) // { // m_fileName = "config\\lightmass.xml"; // } // // // 析构函数 // ConfigMgr::~ConfigMgr() // { // // } // // // 加载 // void ConfigMgr::Load() // { // try // { // file<> fdoc( m_fileName.c_str()); // xml_document<> doc; // doc.parse<0>( fdoc.data()); // // LoadRencentlyFiles( doc); // // LoadProgramState( doc); // } // catch ( ...) // { // // } // } // // // 保存 // void ConfigMgr::Save() // { // xml_document<> doc; // xml_node<>* xmlNode = doc.allocate_node(rapidxml::node_pi,doc.allocate_string("xml version='1.0' encoding='utf-8'")); // xml_node<>* rootNode = doc.allocate_node(node_element,"config"); // // doc.append_node( xmlNode); // doc.append_node( rootNode); // // SaveRencentlyFiles( doc, rootNode); // // SaveProgramState( doc, rootNode); // // // 写文件 // std::ofstream out( m_fileName.c_str()); // out << doc; // } // // // 添加到文件列表 // void ConfigMgr::AddToRecentlyFile( const char* fileName) // { // if( fileName) // { // // 1.若已存在于列表 交换 // FileList::iterator it = std::find( m_recentlyFiles.begin(), m_recentlyFiles.end(), fileName); // if( it != m_recentlyFiles.end()) // { // m_recentlyFiles.erase( it); // // // 保证最近文件数目不超过10 // while( m_recentlyFiles.size()>=10) // m_recentlyFiles.pop_back(); // } // // m_recentlyFiles.push_front( fileName); // } // // // 触发信号 // Signal_OnRencentFilesChanged( m_recentlyFiles); // // Save(); // } // // // 加载最近打开文件列表 // void ConfigMgr::LoadRencentlyFiles( xml_document<>& doc) // { // m_recentlyFiles.clear(); // // // 主节点, 势力结点 // xml_node<>* pRootNode = doc.first_node("config"); // xml_node<>* pRencentFilesNode = pRootNode->first_node( "rencent_files"); // xml_node<>* pRencentFileNode = pRencentFilesNode->first_node( "file"); // for ( ; pRencentFileNode ;pRencentFileNode=pRencentFileNode->next_sibling( "file")) // { // m_recentlyFiles.push_back( pRencentFileNode->first_attribute("path")->value()); // } // // // 触发信号 // Signal_OnRencentFilesChanged( m_recentlyFiles); // } // // // 保存最近打开文件列表 // void ConfigMgr::SaveRencentlyFiles( xml_document<>& doc, xml_node<>* rootNode) // { // if( rootNode) // { // xml_node<>* rencentFilesNode = doc.allocate_node(node_element,"rencent_files"); // rootNode->append_node( rencentFilesNode); // // for( FileList::iterator it=m_recentlyFiles.begin(); it!=m_recentlyFiles.end(); it++) // { // xml_node<>* tNode = doc.allocate_node(node_element, "file"); // xml_attribute<>* pAttribute = doc.allocate_attribute( "path", it->c_str()); // // tNode->append_attribute(pAttribute); // rencentFilesNode->append_node( tNode); // } // } // } // // // 设置程序状态 // void ConfigMgr::SetProgramState( const char* pbrt, const char* img, int tabIdx) // { // m_lastFileOpen = pbrt; // m_lastImgOpen = img; // m_tabIdx = tabIdx; // } // // // 加载上次关闭时状态 // void ConfigMgr::LoadProgramState( xml_document<>& doc) // { // m_recentlyFiles.clear(); // // // 主节点, 势力结点 // xml_node<>* pRootNode = doc.first_node("config"); // xml_node<>* stateNode = pRootNode->first_node( "program_states"); // // try // { // if( stateNode) // { // m_lastFileOpen = stateNode->first_attribute("pbrt_open")->value(); // m_lastImgOpen = stateNode->first_attribute("img_open")->value(); // m_tabIdx = lexical_cast<int>(stateNode->first_attribute("tab_index")->value()); // } // } // catch(...) // { // int a = 10; // } // // // 触发信号 // Signal_OnRestoreState( m_lastFileOpen.c_str(), m_lastImgOpen.c_str(), m_tabIdx); // } // // // 保存程序状态 // void ConfigMgr::SaveProgramState( xml_document<>& doc, xml_node<>* rootNode) // { // if( rootNode) // { // xml_node<>* stateNode = doc.allocate_node(node_element,"program_states"); // rootNode->append_node( stateNode); // // try // { // // 属性 // xml_attribute<>* pAttributeFileOpen = doc.allocate_attribute( "pbrt_open", m_lastFileOpen.c_str()); // xml_attribute<>* pAttributeImgOpen = doc.allocate_attribute( "img_open", m_lastImgOpen.c_str()); // xml_attribute<>* pAttributeTabIdx = doc.allocate_attribute( "tab_index", lexical_cast<string>(m_tabIdx).c_str()); // stateNode->append_attribute(pAttributeFileOpen); // stateNode->append_attribute(pAttributeImgOpen); // stateNode->append_attribute(pAttributeTabIdx); // } // catch(...) // { // int a= 10; // } // } // } //}
363ad26a03d108898b51aa7d18262f34cf876dd0
04705b9a957c9c34e0b9a7c5b514e5a0220ccec7
/graphic_lib.h
27077ccb06efce3d15af667c7a85f7b7537cd4d7
[]
no_license
shizhonghao/graphic_lib
abf97aa2f763cfa9b6eb0fad15f73e8ee24af2fb
6eb88328975b1da8bc08e40df4ad837b16ee79c4
refs/heads/master
2021-01-19T23:40:15.489639
2017-06-23T17:34:02
2017-06-23T17:34:02
89,006,084
0
0
null
null
null
null
UTF-8
C++
false
false
9,925
h
graphic_lib.h
#include <windows.h> #include <iostream> #include <algorithm> #include <math.h> #include <vector> using namespace std; const int INF = 0x3f3f3f3f; void draw_line(HDC hdc,int x0,int y0,int x1,int y1,COLORREF color) { int i; //printf("%d\n",hdc); if(x0>x1) { swap(x0,x1); swap(y0,y1); } int dx = x1 - x0; int dy = y1 - y0; if(dx>=abs(dy)) { int pos = dy>0 ? 1 : -1; int e = 2*pos*dy - dx; int x = x0; int y = y0; for(i=0;i<=dx;i++) { SetPixel(hdc,x,y,color); x++; if(e>=0) { y += pos; e += 2*pos*dy - 2*dx; } else { e += 2*pos*dy; } } } else { if(y0>y1) { swap(x0,x1); swap(y0,y1); } dx = x1 - x0; dy = y1 - y0; int pos = dx>0 ? 1 : -1; int e = 2*pos*dx - dy; int x = x0; int y = y0; for(i=0;i<=dy;i++) { SetPixel(hdc,x,y,color); y++; if(e>=0) { x += pos; e += 2*pos*dx - 2*dy; } else { e += 2*pos*dx; } } } } void circle_points(HDC hdc,int x,int y,int x0,int y0,COLORREF color) { //cout << x << ' ' << y << endl; SetPixel(hdc,x+x0,y+y0,color); SetPixel(hdc,-x+x0,y+y0,color); SetPixel(hdc,x+x0,-y+y0,color); SetPixel(hdc,-x+x0,-y+y0,color); SetPixel(hdc,y+y0,x+x0,color); SetPixel(hdc,-y+y0,x+x0,color); SetPixel(hdc,y+y0,-x+x0,color); SetPixel(hdc,-y+y0,-x+x0,color); } void draw_circle(HDC hdc,int x0,int y0,int r,COLORREF color) { int x = 0; int y = r; int e = 1-r; circle_points(hdc,x,y,x0,y0,color); while(x<=y) { if(e<0) { e += 2*x+3; } else { e += 2*(x-y) + 5; y--; } x++; circle_points(hdc,x,y,x0,y0,color); } } struct point { int x,y; bool operator < (const point &p) const { if(x*p.x<0) { return x<p.x; } return x*p.y < y*p.x; } }; vector<point> circ; void add_points(int x0,int y0,int x,int y) { point p; int i,j; for(i=-1;i<2;i+=2) { for(j=-1;j<2;j+=2) { p.x = i*x; p.y = j*y; circ.push_back(p); } } for(i=-1;i<2;i+=2) { for(j=-1;j<2;j+=2) { p.x = i*y; p.y = j*x; circ.push_back(p); } } } void draw_arc(HDC hdc,int x0,int y0,int r,double ang1,double ang2,COLORREF color) { int i = 0; int x = 0; int y = r; int e = 1-r; int x1,y1,x2,y2; x1 = round(r*sin(ang1/180.0*M_PI)); y1 = round(r*cos(ang1/180.0*M_PI)); x2 = round(r*sin(ang2/180.0*M_PI)); y2 = round(r*cos(ang2/180.0*M_PI)); add_points(x0,y0,x,y); while(x<=y) { if(e<0) { e += 2*x+3; } else { e += 2*(x-y) + 5; y--; } x++; add_points(x0,y0,x,y); } //cout << circ.size(); sort(circ.begin(),circ.end()); for(int i=0;i<circ.size();i++) { //cout << circ[i].x << ' ' << circ[i].y << endl; } bool draw = false; while(true) { //cout << i << ' ' << circ[i].x << ' ' << circ[i].y << endl; i = (i+1) % circ.size(); if(x1==circ[i].x && y1==circ[i].y) { draw = true; } if(draw) { SetPixel(hdc,x0+circ[i].x,y0+circ[i].y,color); } if(circ[i].x==x2 && circ[i].y==y2 && draw==true) { break; } } circ.clear(); } vector<point> ecli; void add_ecli_point(int x,int y) { point p; int i,j; for(i=-1;i<2;i+=2) { for(j=-1;j<2;j+=2) { p.x = i*x; p.y = j*y; ecli.push_back(p); } } } void draw_eclipse(HDC hdc,int x0,int y0,int a,int b,double ang1,double ang2, COLORREF color) { int aa = a*a,bb = b*b; int twoaa = 2*aa, twobb = 2*bb; int x = 0,y = b; int d; int dx = 0; int dy = twoaa*y; d = int(bb+aa*(-b+0.25)+0.5); add_ecli_point(x,y); while(dx<dy) { x++; dx += twobb; if(d<0) { d += bb + dx; } else { dy -= twoaa; d += bb + dx - dy; y--; } add_ecli_point(x,y); } d = int(bb*(x+0.5)*(x+0.5) + aa*(y-1)*(y-1) - aa*bb + 0.5); while(y>0) { y--; dy -= twoaa; if(d>0) { d += aa - dy; } else { x++; dx += twobb; d += aa - dy + dx; } add_ecli_point(x,y); } sort(ecli.begin(),ecli.end()); int x1,y1,x2,y2; x1 = round(a*cos(ang1/180.0*M_PI)); y1 = round(b*sin(ang1/180.0*M_PI)); x2 = round(a*cos(ang2/180.0*M_PI)); y2 = round(b*sin(ang2/180.0*M_PI)); //cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl; bool draw = false; int i = 0; while(true) { //cout << i << ' ' << ecli[i].x << ' ' << ecli[i].y << endl; i = (i+1) % ecli.size(); if(x1==ecli[i].x && y1==ecli[i].y) { draw = true; } if(draw) { SetPixel(hdc,x0+ecli[i].x,y0+ecli[i].y,color); } if(ecli[i].x==x2 && ecli[i].y==y2 && draw==true) { break; } } ecli.clear(); } struct EDGE { double x1; double dx; int ymax; bool operator < (const EDGE &e) const { return x1<e.x1; } }; class polygon { private: vector<point> p; vector<int> AET[1080]; vector<EDGE> NET[1080]; int ymax,ymin; int M,N; int pattern[1080][1920]; public: polygon() { //cout << "new polygon" << endl; } void add_point(int x,int y) { point pnt; pnt.x = x; pnt.y = y; p.push_back(pnt); } void build(HDC hdc,COLORREF color) { EDGE e; int i,j; ymax = ymin = p[p.size()-1].y; for(i=0;i<p.size()-1;i++) { draw_line(hdc,p[i].x,p[i].y,p[i+1].x,p[i+1].y,color); ymax = max(ymax,p[i].y); ymin = min(ymin,p[i].y); if(p[i].y>p[i+1].y) { e.x1 = p[i+1].x; e.ymax = p[i].y; e.dx = 1.0*(p[i].x - p[i+1].x)/(p[i].y - p[i+1].y); NET[p[i+1].y].push_back(e); } else if(p[i].y<p[i+1].y) { e.x1 = p[i].x; e.ymax = p[i+1].y; e.dx = 1.0*(p[i].x - p[i+1].x)/(p[i].y - p[i+1].y); NET[p[i].y].push_back(e); } } draw_line(hdc,p[0].x,p[0].y,p[i].x,p[i].y,color); if(p[i].y>p[0].y) { e.x1 = p[0].x; e.ymax = p[i].y; e.dx = 1.0*(p[i].x - p[0].x)/(p[i].y - p[0].y); NET[p[0].y].push_back(e); } else if(p[i].y<p[i+1].y) { e.x1 = p[i].x; e.ymax = p[0].y; e.dx = 1.0*(p[i].x - p[0].x)/(p[i].y - p[0].y); NET[p[i].y].push_back(e); } /* for(i=0;i<1080;i++) { for(j=0;j<NET[i].size();j++) { cout << NET[i].size() << "x: " << NET[i][j].x1 << "ymax: " << NET[i][j].ymax << "dx: " << NET[i][j].dx << endl; } } */ vector<EDGE> temp; for(i=ymin;i<ymax;i++) { //cout << i << " "; for(j=0;j<NET[i].size();j++) { temp.push_back(NET[i][j]); } for(j=0;j<temp.size();j++) { if(temp[j].ymax==i) { temp.erase(temp.begin()+j); j--; } } for(j=0;j<temp.size();j++) { temp[j].x1 += temp[j].dx; AET[i+1].push_back(temp[j].x1); } sort(AET[i].begin(),AET[i].end()); } } void clear() { p.clear(); } void fill_color(HDC hdc,COLORREF color) { int i,j,k; for(i=ymin+1;i<ymax;i++) { for(j=0;j<AET[i].size();j+=2) { for(k=AET[i][j]+1;k<AET[i][j+1];k++) { SetPixel(hdc,k,i,color); } } } } void set_pattern(int m,int n,int *pat) { int i,j; M = m; N = n; for(i=0;i<n;i++) { for(j=0;j<m;j++) { pattern[i][j] = *(pat+i*m+n); } } } void fill_shade(HDC hdc,COLORREF color) { int i,j,k; for(i=ymin+1;i<ymax;i++) { for(j=0;j<AET[i].size();j+=2) { for(k=AET[i][j]+1;k<AET[i][j+1];k++) { if(pattern[k%M][i%N]) { SetPixel(hdc,k,i,color); } } } } } };
3650426606fdbddb13ad3c3cc7873c59075ed546
28f18e6b5ec90ecbe68272ef1572f29c3e9b0a53
/include/boost/geometry/extensions/gis/io/wkb/read_wkb.hpp
fdcf9cd0d513dca593d6f7d16f69d41c2aea58c6
[ "BSL-1.0" ]
permissive
boostorg/geometry
24efac7a54252b7ac25cd2e9154e9228e53b40b7
3755fab69f91a5e466404f17f635308314301303
refs/heads/develop
2023-08-19T01:14:39.091451
2023-07-28T09:14:33
2023-07-28T09:14:33
7,590,021
400
239
BSL-1.0
2023-09-14T17:20:26
2013-01-13T15:59:29
C++
UTF-8
C++
false
false
3,240
hpp
read_wkb.hpp
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // This file was modified by Oracle on 2020. // Modifications copyright (c) 2020, Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_IO_WKB_READ_WKB_HPP #define BOOST_GEOMETRY_IO_WKB_READ_WKB_HPP #include <iterator> #include <type_traits> #include <boost/static_assert.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/extensions/gis/io/wkb/detail/parser.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template <typename Tag, typename G> struct read_wkb {}; template <typename Geometry> struct read_wkb<point_tag, Geometry> { template <typename Iterator> static inline bool parse(Iterator& it, Iterator end, Geometry& geometry, detail::wkb::byte_order_type::enum_t order) { return detail::wkb::point_parser<Geometry>::parse(it, end, geometry, order); } }; template <typename Geometry> struct read_wkb<linestring_tag, Geometry> { template <typename Iterator> static inline bool parse(Iterator& it, Iterator end, Geometry& geometry, detail::wkb::byte_order_type::enum_t order) { geometry::clear(geometry); return detail::wkb::linestring_parser<Geometry>::parse(it, end, geometry, order); } }; template <typename Geometry> struct read_wkb<polygon_tag, Geometry> { template <typename Iterator> static inline bool parse(Iterator& it, Iterator end, Geometry& geometry, detail::wkb::byte_order_type::enum_t order) { geometry::clear(geometry); return detail::wkb::polygon_parser<Geometry>::parse(it, end, geometry, order); } }; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH template <typename Iterator, typename Geometry> inline bool read_wkb(Iterator begin, Iterator end, Geometry& geometry) { // Stream of bytes can only be parsed using random access iterator. BOOST_STATIC_ASSERT(( std::is_convertible < typename std::iterator_traits<Iterator>::iterator_category, const std::random_access_iterator_tag& >::value)); detail::wkb::byte_order_type::enum_t byte_order; if (detail::wkb::byte_order_parser::parse(begin, end, byte_order)) { return dispatch::read_wkb < typename tag<Geometry>::type, Geometry >::parse(begin, end, geometry, byte_order); } return false; } template <typename ByteType, typename Geometry> inline bool read_wkb(ByteType const* bytes, std::size_t length, Geometry& geometry) { BOOST_STATIC_ASSERT((std::is_integral<ByteType>::value)); BOOST_STATIC_ASSERT((sizeof(boost::uint8_t) == sizeof(ByteType))); ByteType const* begin = bytes; ByteType const* const end = bytes + length; return read_wkb(begin, end, geometry); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_IO_WKB_READ_WKB_HPP
9514ca396893557933cd7466a75a5e69a60b821f
347334f675bc31ecab5d74ca6388827b13097ed9
/src/gui-qml/src/loaders/tag-search-loader.h
a3e818203640c1f82f2675235745fd88008bd37b
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
Bionus/imgbrd-grabber
442108d9663a06a848ef49837943d5950bca9d8c
4ab008d5d0f62ab2bc34aff7de02e05d598e058a
refs/heads/master
2023-08-20T21:50:37.649081
2023-08-17T22:54:55
2023-08-17T22:54:55
32,276,615
2,226
301
Apache-2.0
2023-08-12T16:31:57
2015-03-15T18:26:31
HTML
UTF-8
C++
false
false
510
h
tag-search-loader.h
#ifndef TAG_SEARCH_LOADER_H #define TAG_SEARCH_LOADER_H #include "search-loader.h" #include <QString> class TagSearchLoader : public SearchLoader { Q_OBJECT Q_PROPERTY(QString query READ query WRITE setQuery NOTIFY queryChanged) public: explicit TagSearchLoader(QObject *parent = nullptr); const QString &query() const; void setQuery(const QString &query); public slots: void load() override; signals: void queryChanged(); private: QString m_query; }; #endif // TAG_SEARCH_LOADER_H
4d44806a9dba3d893207c7653bf65b8552368835
5470aee46382fec6e51c36c1e041185cd070566c
/todo_list/constructors.cpp
d910a7849a64d1ac44ba865fa4bf0832d2e094f8
[]
no_license
Joker-Jerome/cpp
c4167e137cddc7e6681c1f356083373daa770d67
d48fbad4d66a0d949232ba21262368beffe821d4
refs/heads/master
2021-09-10T08:41:16.514455
2018-03-23T03:53:33
2018-03-23T03:53:33
106,119,653
1
0
null
null
null
null
UTF-8
C++
false
false
1,723
cpp
constructors.cpp
#include <iostream> #include <string> #include "todolist.h" #include "task.h" using todo::Task; using todo::ToDoList; ToDoList morningList(const std::string&); int main(int argc, char *argv[]) { Task coffee("make coffee", 10); Task drink("drink coffee", 30); Task walk("walk to office", 20); Task prep("prepare for class", 60); Task teach("teach class", 75); std::cout << "Making Monday" << std::endl; ToDoList monday; monday.add(coffee).add(drink); std::cout << "Making Wednesday" << std::endl; // = in initialization is not assignment; it passes rhs to constructor -- // the copy constructor in this case since monday is an lvalue ToDoList wednesday = monday; wednesday.add(walk).add(prep).add(teach); std::cout << "Making Thursday" << std::endl; // g++ in this case elides one call to the move constructor, bypassing // the temporary created as the return value from morningList // (compilers may optionally elide copy/move constructors) ToDoList thursday = morningList("tea"); //ToDoList thursday(morningList("tea")); // equivalent std::cout << "Making Friday" << std::endl; // the below uses copy constructor for friday since add returns an lvalue ToDoList friday = morningList("tea").add(Task("make more tea", 5)); std::cout << "Copying Monday" << std::endl; // move assignment since morning list returns a rvalue monday = morningList("coffee"); } ToDoList morningList(const std::string& drink) { ToDoList tea; tea.add(Task("make tea", 10)).add(Task("drink tea", 30)); ToDoList coffee; coffee.add(Task("make coffee", 10)).add(Task("drink coffee", 30)); if (drink == "tea") { return tea; } else { return coffee; } }
d2e0d1fd85d9379385ad59e78bca3a7c38d29847
63db2a4036ba87e5da35bca4925464002c3c19d6
/big_exercise/qt/mvc/moc_teamleadersdialog.cpp
b4af8ffe26e6ea1f8984bc380057e47e2c5c17a9
[]
no_license
gicsfree/exercise_aka
6c6ae3ef737e1a3da23001871a3b8c4dea9e7713
d831bc14d719fcd90a06e29d1832c5ea20abb988
refs/heads/master
2022-05-09T11:29:33.265928
2011-09-23T11:48:10
2011-09-23T11:48:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,221
cpp
moc_teamleadersdialog.cpp
/**************************************************************************** ** Meta object code from reading C++ file 'teamleadersdialog.h' ** ** Created: Wed Aug 31 20:30:29 2011 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "teamleadersdialog.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'teamleadersdialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_TeamLeadersDialog[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 2, 12, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors // slots: signature, parameters, type, tag, flags 19, 18, 18, 18, 0x08, 28, 18, 18, 18, 0x08, 0 // eod }; static const char qt_meta_stringdata_TeamLeadersDialog[] = { "TeamLeadersDialog\0\0insert()\0del()\0" }; const QMetaObject TeamLeadersDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_TeamLeadersDialog, qt_meta_data_TeamLeadersDialog, 0 } }; const QMetaObject *TeamLeadersDialog::metaObject() const { return &staticMetaObject; } void *TeamLeadersDialog::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_TeamLeadersDialog)) return static_cast<void*>(const_cast< TeamLeadersDialog*>(this)); return QDialog::qt_metacast(_clname); } int TeamLeadersDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: insert(); break; case 1: del(); break; default: ; } _id -= 2; } return _id; } QT_END_MOC_NAMESPACE
45b3a5e5c3bbc09bb4562f9c438ce2adfb32cedd
2fbb03a0dcdc873935178f03b99027ad1298bf96
/plugin/platforms/reference/tests/TestReferenceFeedInForce.cpp
99acdeb65c87aef72fbf8fbc76dea6f90d169507
[]
no_license
YevChern/FeedInForce_openmm
55dced4f4554d67bbebaafe8527475bf3ce1c879
c3f06bb421285e01758c773de3ddea780f30c3b0
refs/heads/master
2022-04-21T20:47:19.450372
2020-04-16T22:41:53
2020-04-16T22:41:53
255,616,104
0
0
null
null
null
null
UTF-8
C++
false
false
4,121
cpp
TestReferenceFeedInForce.cpp
/* -------------------------------------------------------------------------- * * OpenMM * * -------------------------------------------------------------------------- * * This is part of the OpenMM molecular simulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2014 Stanford University and the Authors. * * Authors: Peter Eastman * * Contributors: * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * * THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * * USE OR OTHER DEALINGS IN THE SOFTWARE. * * -------------------------------------------------------------------------- */ /** * This tests the Reference implementation of FeedInForce. */ #include "FeedInForce.h" #include "openmm/internal/AssertionUtilities.h" #include "openmm/Context.h" #include "openmm/Platform.h" #include "openmm/System.h" #include "openmm/VerletIntegrator.h" #include <cmath> #include <iostream> #include <vector> using namespace FeedInPlugin; using namespace OpenMM; using namespace std; extern "C" OPENMM_EXPORT void registerFeedInReferenceKernelFactories(); void testForce() { int numParticles = 200; System system; vector<Vec3> positions(numParticles); for (int i = 0; i < numParticles; i++) { system.addParticle(1.0); positions[i] = Vec3(i, 0.1*i, i); } FeedInForce* force = new FeedInForce(); system.addForce(force); VerletIntegrator integ(1.0); Platform& platform = Platform::getPlatformByName("Reference"); Context context(system, integ, platform); context.setPositions(positions); context.setTime(0.0); vector< vector<double> > expectedForce; for (int i=0; i<numParticles; ++i){ expectedForce.push_back(vector<double>{0.1*i, 0.3/(i+1), 1.1+i}); } force->updateForceInContext(context, expectedForce); State state = context.getState(State::Energy | State::Forces); for (int i=0; i<expectedForce.size(); ++i){ for (int j=0; j<3; ++j) ASSERT_EQUAL_TOL(expectedForce[i][j], state.getForces()[i][j], 1e-8); } } int main() { try { registerFeedInReferenceKernelFactories(); testForce(); } catch(const std::exception& e) { std::cout << "exception: " << e.what() << std::endl; return 1; } std::cout << "Done" << std::endl; return 0; }
4ba17c9aff8eccf08b9b6178ea8ebad5bb729f75
fb940dcfeb23c04e7d41b472bf5079c4d35ec5c4
/KeyboardAndMouseHandle.cpp
1ef32c760a2d2a02b766765c2481f0d022fcc047
[]
no_license
U-NV/SoftRenderer
9ffb29885efb9c9de28d99d46ffe0b8c46d8e3fd
61024826c0c524a5d00a9904e4af60c0254aa506
refs/heads/master
2022-11-30T19:43:43.596039
2020-08-17T08:58:22
2020-08-17T08:58:22
280,355,394
4
2
null
null
null
null
UTF-8
C++
false
false
3,151
cpp
KeyboardAndMouseHandle.cpp
#include "KeyboardAndMouseHandle.h" KeyboardAndMouseHandle::KeyboardAndMouseHandle(int SCREEN_WIDTH, int SCREEN_HEIGHT, Camera* camera, float* gamma, float* exposure) { MousePosNow = Vec2f((float)SCREEN_WIDTH / 2.0f, (float)SCREEN_HEIGHT / 2.0f); MousePosNow = Vec2f((float)SCREEN_WIDTH / 2.0f, (float)SCREEN_HEIGHT / 2.0f); controlCamera = camera; this->gamma = gamma; this->exposure = exposure; } void KeyboardAndMouseHandle::handlerKeyboardEvent(float deltaTime) { float cameraSpeed = 2.0f * deltaTime; if (keysEvent[SDLK_ESCAPE]) { SDL_Runing = false; } if (keysEvent[SDLK_w]) { controlCamera->moveStraight(cameraSpeed); } if (keysEvent[SDLK_s]) { controlCamera->moveStraight(-cameraSpeed); } if (keysEvent[SDLK_a]) { controlCamera->moveTransverse(-cameraSpeed); } if (keysEvent[SDLK_d]) { controlCamera->moveTransverse(cameraSpeed); } if (keysEvent[SDLK_e]) { controlCamera->moveVertical(cameraSpeed); } if (keysEvent[SDLK_q]) { controlCamera->moveVertical(-cameraSpeed); } if (keysEvent[SDLK_COMMA]) { //< *gamma -= 0.05f; std::cout << "Gamma:" << *gamma << std::endl; }if (keysEvent[SDLK_PERIOD]) {//> *gamma += 0.05f; std::cout << "Gamma:" << *gamma << std::endl; } if (keysEvent[SDLK_LEFTBRACKET]) { //"[" *exposure -= 0.05f; std::cout << "exposure:" << *exposure << std::endl; }if (keysEvent[SDLK_RIGHTBRACKET]) {//']' *exposure += 0.05f; std::cout << "exposure:" << *exposure << std::endl; } if (rightKeyPress || leftKeyPress) { Vec2f offset = MousePosNow - MousePosPre; MousePosPre = MousePosNow; float sensitivity = 10; offset.x *= sensitivity; offset.y *= sensitivity; if (rightKeyPress) { controlCamera->rotateCamera(offset * deltaTime); } if (leftKeyPress) { } } if (mouseWheelAmount != 0) { controlCamera->changeFov(-mouseWheelAmount * cameraSpeed); mouseWheelAmount = 0; } } int KeyboardAndMouseHandle::getMouseKeyEven(void* opaque, float deltaTime) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym < 1024) keysEvent[event.key.keysym.sym] = true; break; case SDL_KEYUP: if (event.key.keysym.sym < 1024) keysEvent[event.key.keysym.sym] = false; break; case SDL_MOUSEMOTION: MousePosNow.x = (float)event.motion.x; MousePosNow.y = SCREEN_HEIGHT - (float)event.motion.y; //printf("x, y %d %d ...............\n", MousePosNow.x, MousePosNow.y); break; case SDL_MOUSEWHEEL: mouseWheelAmount = event.wheel.y; break; case SDL_MOUSEBUTTONDOWN: switch (event.button.button) { case SDL_BUTTON_LEFT: leftKeyPress = true; break; case SDL_BUTTON_RIGHT: MousePosPre = MousePosNow; rightKeyPress = true; break; default: break; } break; case SDL_MOUSEBUTTONUP: switch (event.button.button) { case SDL_BUTTON_LEFT: leftKeyPress = false; break; case SDL_BUTTON_RIGHT: rightKeyPress = false; break; default: break; } break; case SDL_QUIT: SDL_Runing = false; break; default: break; } } handlerKeyboardEvent(deltaTime); return 0; }
68417b4c5a6fbf9a6f0f132ecb4e878dc2126ade
171939de0a904c90f9af198b8e5d65f8349429d7
/CQ-00088/airport/airport.cpp
32429de4f719abd0b9e7d78750b534b4ae868846
[]
no_license
LittleYang0531/CQ-CSP-S-2021
2b1071bbbf0463e65bfc177f86a44b7d3301b6a9
1d9a09f8fb6bf3ba22962969a2bac18383df4722
refs/heads/main
2023-08-26T11:39:42.483746
2021-10-23T14:45:45
2021-10-23T14:45:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,188
cpp
airport.cpp
#include<bits/stdc++.h> using namespace std; struct times{ int a,g; }; bool cmp(times a,times b) { return a.a<b.a; } int main() { freopen("airport.in","r",stdin); freopen("airport.out","w",stdout); int ld,gn,gw; cin>>ld>>gn>>gw; times p[gn],p1[gw]; int dl[100000]={0},last[100000]={-1},t1=0,t2=0,lasts[100000]={-1},dl1[100000]={0},tot=0; for(int a=0;a<gn;a++) { cin>>p[a].a>>p[a].g; } sort(p,p+gn,cmp); for(int a=0;a<gw;a++) { cin>>p1[a].a>>p1[a].g; } sort(p1,p1+gw,cmp); for(int g=0;g<gn;g++) { int a=p[g].a,b=p[g].g,tag=0; for(int c=0;c<=t1;c++) { if(last[c]<a) { tag=1; last[c]=b; dl[c]++; if(c<ld) { tot++; } break; } } if(!tag) { if(t1>=ld-1) { continue; } t1++; dl[t1]=1; last[t1]=b; tot++; } } for(int g=0;g<gw;g++) { int a=p1[g].a,b=p1[g].g,tag=0; for(int c=0;c<=t2;c++) { if(lasts[c]<a) { tag=1; lasts[c]=b; dl1[c]++; break; } } if(!tag) { t2++; dl1[t2]=1; lasts[t2]=b; } } int m=-1; for(int a=0;a<ld;a++) { if(tot>m) { m=tot; } if(t1>=ld-1)tot-=dl[t1-a]; else t1++; tot+=dl1[a]; } cout<<m; return 0; }
f99fc405325868425208e04fd01495f3fa7f87e5
d4e42338394b03b2b3a66073ad15128f7b7805a6
/source/loader/cios.cpp
0ca8e26463e82ccba760409c4d04957f80832ef4
[]
no_license
rosendael/wiiflow-plus
ebb95564682ce1d83bc24928cd2efa43e22c1025
3db58aada86bc48eb52f6ee3ee68c13e4665c42d
refs/heads/master
2021-04-29T01:31:36.753218
2012-04-25T10:41:31
2012-04-25T10:41:31
77,750,528
1
0
null
2016-12-31T17:49:21
2016-12-31T17:49:20
null
UTF-8
C++
false
false
2,892
cpp
cios.cpp
/*************************************************************************** * Copyright (C) 2011 * by Dimok * Modifications by xFede * Wiiflowized and heavily improved by Miigotu * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any * damages arising from the use of this software. * * Permission is granted to anyone to use this software for any * purpose, including commercial applications, and to alter it and * redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you * must not claim that you wrote the original software. If you use * this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and * must not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. ***************************************************************************/ #include <gctypes.h> #include <malloc.h> #include <cstdio> #include <cstring> #include "cios.hpp" #include "utils.h" #include "mem2.hpp" #include "fs.h" #define ARRAY_SIZE(a) (sizeof a / sizeof a[0]) static u32 allowedBases[] = { 37, 38, 53, 55, 56, 57, 58 }; /* Check if the cIOS is a D2X. */ bool cIOSInfo::D2X(u8 ios, u8 *base) { iosinfo_t *info = GetInfo(ios); if(!info) return false; *base = (u8)info->baseios; SAFE_FREE(info); return true; } /* * Reads the ios info struct from the .app file. * @return pointer to iosinfo_t on success else NULL. The user is responsible for freeing the buffer. */ iosinfo_t *cIOSInfo::GetInfo(u8 ios) { u32 TMD_Length; if (ES_GetStoredTMDSize(TITLE_ID(1, ios), &TMD_Length) < 0) return NULL; signed_blob *TMD = (signed_blob*) MEM2_alloc(ALIGN32(TMD_Length)); if (!TMD) return NULL; if (ES_GetStoredTMD(TITLE_ID(1, ios), TMD, TMD_Length) < 0) { SAFE_FREE(TMD); return NULL; } char filepath[ISFS_MAXPATH] ATTRIBUTE_ALIGN(32); sprintf(filepath, "/title/00000001/%08x/content/%08x.app", ios, *(u8 *)((u32)TMD+0x1E7)); SAFE_FREE(TMD); u32 size = 0; u8 *buffer = ISFS_GetFile((u8 *) filepath, &size, sizeof(iosinfo_t)); if(!buffer || size <= 0) return NULL; iosinfo_t *iosinfo = (iosinfo_t *) buffer; bool baseMatch = false; for(u8 i = 0; i < ARRAY_SIZE(allowedBases); i++) if(iosinfo->baseios == allowedBases[i]) { baseMatch = true; break; } if(iosinfo->magicword != 0x1ee7c105 /* Magic Word */ || iosinfo->magicversion != 1 /* Magic Version */ || iosinfo->version < 6 /* Version */ || !baseMatch /* Base */ || strncasecmp(iosinfo->name, "d2x", 3) != 0) /* Name */ { SAFE_FREE(buffer); return NULL; } SAFE_FREE(buffer); return iosinfo; }
2044b6415eaf4a4785b6478045dbf7856fa0c77f
a06d2f37314a37b6038d46f8deda98b2af2530a2
/Grafos/kruskal.cpp
9f92c17f775cda6545b06718fcd4b1f70aa7879e
[]
no_license
CarlosAlberto1x9/code
40bea88605b543b98c8b58bdaafca008159c9ccd
c5161356d2bc868f0b22f5ba0e7f330fc5a6e2d7
refs/heads/master
2023-02-01T05:13:57.878134
2020-12-17T03:54:28
2020-12-17T03:54:28
171,583,412
0
0
null
null
null
null
UTF-8
C++
false
false
1,317
cpp
kruskal.cpp
#include <iostream> #include <tuple> #include <utility> #include <numeric> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int vertices = 8; int lider[vertices]; int tam[vertices]; int findSet(int x) { return lider[x] == x ? lider[x] : lider[x] = findSet(lider[x]); } bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } void unionSetBySize(int i, int j) { int x = findSet(i); int y = findSet(j); if (x != y) { if (tam[y] < tam[x]) { swap(x, y); } lider[x] = y; tam[y] += tam[x]; } } int main() { ios::sync_with_stdio(false); cin.tie(0); int v, e; cin >> v >> e; iota(lider+1, lider+v+1, 1); fill(tam+1, tam+v+1, 1); vector< tuple<int,int,int> > edges; int x, y, w; int num_subsets = v; for (int i = 0; i < e; i++) { cin >> x >> y >> w; edges.push_back( { w, x, y } ); } sort(edges.begin(), edges.end() ); long long costo = 0; for (int i = 0; i < e; i++) { tie(w, x, y) = edges[i]; if ( ! isSameSet(x, y) ) { costo += w; unionSetBySize(x, y); num_subsets-=1; } } cout << "MST kruskal: " << costo <<" subsets: "<< num_subsets << '\n'; if ( num_subsets == 1) cout << "Grafo Completo" << '\n'; else cout << "Grafo Incompleto" << '\n'; return 0; }
fc62d99ebf90750b2efbf2612b52a615209961ba
9d620b9e689309911c64b3818f2b7aab0c9bc571
/src/ListableGamePgn.h
77923879c7a993226f573e87f1608ba702c9de40
[ "MIT" ]
permissive
billforsternz/tarrasch-chess-gui
a1c26710c5ce99214e694cc20b24d54c1b31e06b
6c05ffe1b1567c2aeb9c425657e61752dde8482b
refs/heads/master
2023-07-20T15:40:32.003138
2023-05-07T03:25:41
2023-05-07T03:25:41
16,636,998
97
28
MIT
2023-05-07T03:25:44
2014-02-08T05:45:44
C
UTF-8
C++
false
false
4,173
h
ListableGamePgn.h
/**************************************************************************** * A ListableGame that was originally created for the list in the PgnDialog * Author: Bill Forster * License: MIT license. Full text of license is in associated file LICENSE * Copyright 2010-2015, Bill Forster <billforsternz at gmail dot com> ****************************************************************************/ #ifndef LISTABLE_GAME_PGN_H #define LISTABLE_GAME_PGN_H #include "GameDocument.h" #include "CompactGame.h" #include "PackedGame.h" #include "CompressMoves.h" void ReadGameFromPgn( int pgn_handle, long fposn, GameDocument &gd ); void *ReadGameFromPgnInLoop( int pgn_handle, long fposn, CompactGame &pact, void *context, bool end=true ); class ListableGamePgn : public ListableGame { private: int pgn_handle; long fposn; PackedGame pack; bool in_memory; public: ListableGamePgn( int pgn_handle, long fposn ) { this->pgn_handle=pgn_handle, this->fposn = fposn; in_memory=false; } virtual long GetFposn() { return fposn; } virtual void SetFposn( long posn ) { fposn=posn; } virtual bool GetPgnHandle( int &pgn_handle_ ) { pgn_handle_=this->pgn_handle; return true; } virtual void SetPgnHandle( int pgn_handle_ ) { this->pgn_handle = pgn_handle_; } virtual void *LoadIntoMemory( void *context, bool end ) { if( pack.Empty() ) { CompactGame pact; context = ReadGameFromPgnInLoop( pgn_handle, fposn, pact, context, end ); pack.Pack(pact); } in_memory = true; return context; } virtual void GetCompactGame( CompactGame &pact ) { if( pack.Empty() ) LoadIntoMemory( NULL, true ); pack.Unpack(pact); pact.game_id = game_id; } // For editing the roster virtual void SetRoster( Roster &r ) { CompactGame pact; if( pack.Empty() ) LoadIntoMemory( NULL, true ); pack.Unpack(pact); pact.r = r; pack.Pack(pact); } virtual void ConvertToGameDocument(GameDocument &gd) { ReadGameFromPgn(pgn_handle, fposn, gd); gd.game_id = game_id; } virtual Roster &RefRoster() { static CompactGame pact; GetCompactGame( pact ); return pact.r; } virtual std::vector<thc::Move> &RefMoves() { static CompactGame pact; GetCompactGame( pact ); return pact.moves; } virtual thc::ChessPosition &RefStartPosition() { static CompactGame pact; GetCompactGame( pact ); return pact.start_position; } // For now at least, the following are used for fast sorting on column headings // (only available after LoadInMemory() called - games are loaded from file // when user clicks on a column heading virtual const char *White() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.White(); } virtual const char *Black() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.Black(); } virtual const char *Event() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.Event(); } virtual const char *Site() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.Site(); } virtual const char *Result() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.Result(); } virtual const char *Round() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.Round() ; } virtual const char *Date() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.Date(); } virtual const char *Eco() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.Eco(); } virtual const char *WhiteElo() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.WhiteElo(); } virtual const char *BlackElo() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.BlackElo(); } virtual const char *Fen() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.Fen(); } virtual const char *CompressedMoves() { if(!in_memory) LoadIntoMemory(NULL,true); return pack.Blob(); } }; #endif // LISTABLE_GAME_PGN_H
3ec43c937fef650069ca423466ffad25c1ee35c0
012e5d8fb86785c6c75a0d7b6c96e05e373ff3bd
/DiskSchedulingProject/Fcfs_algorithm.cpp
bd36bbaf494644d3dc5d628c9ea5695629fc497f
[]
no_license
minhbac333shopus/DiskScheduling-OS-with-StrategyPattern
59222f7bbdc85ca0f7d2461dd1eb7b73ae5f5e6f
00abca7f5f751d6ad2d162b8442d9ad699490a38
refs/heads/main
2023-04-19T00:47:59.199843
2021-04-26T15:46:08
2021-04-26T15:46:08
361,806,754
0
0
null
2021-04-26T15:48:38
2021-04-26T15:48:37
null
UTF-8
C++
false
false
28
cpp
Fcfs_algorithm.cpp
#include "Fcfs_algorithm.h"
d66d3c23dc3620034b47d51ba73f45a04fa708cf
b86738ab71ba59705aa932b32a59be69c3fd1eac
/Num/Source.cpp
ebf14dd15599f7a3a18422695fbcf9361383efab
[]
no_license
techtainer/Algorithm-Test
ee894004c5c33f13178d7b5756669de1791b63e2
05c5f2b8a321fc52af636315adb916df1a0ef810
refs/heads/master
2020-04-13T23:33:17.529704
2019-01-05T12:56:15
2019-01-05T12:56:15
163,509,679
0
0
null
null
null
null
UHC
C++
false
false
1,193
cpp
Source.cpp
//연속된 자연수 합으로 어떤 숫자를 표현하는 방법이 여러가지 입니다. // //예를들어 자연수 15는 //1 + 2 + 3 + 4 + 5 = 15 //4 + 5 + 6 = 15 //7 + 8 = 15 //15 = 15 //로 표현이 가능합니다. // //숫자를 입력받아 연속된 수로 표현할 수 있는 케이스의 개수를 // //반환하는 expression 함수를 완성하면 됩니다. // //15가 들어오면 4를 반환하면 됩니다. #include<iostream> #include<string> using namespace std; int function(const string &input) { int result = 0; int tmpNum = stoi(input); int tmpTarget=1; int tmpAdder = tmpTarget; int tmpAdder2 = tmpTarget; while (true) { if (tmpAdder > tmpNum) { tmpTarget++; tmpAdder = tmpTarget; tmpAdder2 = tmpTarget; } if (tmpAdder == tmpNum) { result++; tmpTarget++; tmpAdder = tmpTarget; tmpAdder2 = tmpTarget; cout << "----------------" << endl; } if (tmpTarget >= tmpNum) { break; } tmpAdder2++; cout << tmpAdder << "+" << tmpAdder2 << " " << tmpTarget << endl; tmpAdder = tmpAdder + tmpAdder2; } return result; } int main() { string input; cin >> input; cout << function(input) << endl; return 0; }
84c51d1ec9b6c0934aa5de2ceaa87fb4a7946053
3ee7772953abc7088ef37c91d1c9a5be4cc31163
/string/151.翻转字符串里的单词.cpp
d718bb1b48b311465da4c61df398691b451d1550
[]
no_license
hahlw/leetcode
3814e384b4fb55b5ea6a78e68f2600ffdc32008d
c78f67faa6d5b77173a3805a896fb3446e0241c4
refs/heads/master
2020-06-07T18:15:34.493281
2019-08-21T11:54:20
2019-08-21T11:54:20
193,069,732
1
0
null
null
null
null
UTF-8
C++
false
false
1,139
cpp
151.翻转字符串里的单词.cpp
/* * @lc app=leetcode.cn id=151 lang=cpp * * [151] 翻转字符串里的单词 */ #include <algorithm> #include <iostream> #include <string> using namespace std; class Solution { public: string reverseWords(string s) { if (s.empty()) return ""; int lo = 0, hi = s.size() - 1; while (lo <= hi && s[lo] == ' ') lo++; while (lo <= hi && s[hi] == ' ') hi--; if (lo > hi) return ""; int left = lo, flag = 0; for (int i = lo; i <= hi; i++) { if (s[i] != ' ' || (s[i] == ' ' && flag == 0)) { s[left++] = s[i]; if (s[i] == ' ') flag++; if (s[i] != ' ') flag = 0; } } s = s.substr(lo, left - lo); reverse(s.begin(), s.end()); lo = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == ' ') { reverse(s.begin() + lo, s.begin() + i); lo = i + 1; } } reverse(s.begin() + lo, s.end()); return s; } };
2993bbed97c955769c6075d840e0b0f04e7663c1
dfeb7c8e2fd4a18ee93b26fc98e0559ab492d1f6
/BaekJoon/2021/10757.cpp
421d231467c9e196f35c4c3a51ca6ed19606448a
[]
no_license
ParkHeeseung/Algorithm
3d1c4f9f90009213efd7e4dd1794b18c01583b2b
512117b1c2adbd3481c135fdf01e7f065d42799a
refs/heads/master
2021-11-26T07:34:17.390768
2021-11-14T05:04:04
2021-11-14T05:04:04
138,491,976
0
0
null
null
null
null
UTF-8
C++
false
false
823
cpp
10757.cpp
#include <iostream> #include <string> using namespace std; string func(string& a, string& b) { int aSize = a.length(); int bSize = b.length(); string rans = ""; int c = 0; while (aSize > 0 || bSize > 0) { int k1 = 0; if(aSize>0){ k1 = a[--aSize] - '0'; } int k2 = 0; if (bSize > 0) { k2 = b[--bSize] - '0'; } int ret = k1 + k2 + c; c = ret / 10; ret %= 10; char cur = ret + '0'; rans += cur; } if (c > 0) { rans += c + '0'; } string ans = ""; for (int i = (int)rans.length()-1; i >= 0; --i) { ans += rans[i]; } return ans; } int main(void) { string a; string b; cin >> a >> b; cout << func(a, b) << "\n"; return 0; }
c253b3858d6db9401a03a3b1b5925294b391a0ab
6b2c596adad1eed4ee1237e1dc1c84e5e401f8ab
/src/Database/OpenDBHandler.cpp
fbaef8a987c84665813c7e67a3267f4901f4d686
[ "BSD-3-Clause" ]
permissive
ahmed-agiza/OpenPhySyn
76253ca03aeb70e53e170d9be76e1018ac78fe7b
51841240e5213a7e74bc6321bbe4193323378c8e
refs/heads/master
2020-09-26T06:42:07.214499
2019-12-14T03:42:56
2019-12-14T03:42:56
226,192,119
0
0
BSD-3-Clause
2019-12-05T21:28:39
2019-12-05T21:28:38
null
UTF-8
C++
false
false
16,994
cpp
OpenDBHandler.cpp
// BSD 3-Clause License // Copyright (c) 2019, SCALE Lab, Brown University // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifdef USE_OPENDB_DB_HANDLER #include <OpenPhySyn/Database/OpenDBHandler.hpp> #include <OpenPhySyn/PsnLogger/PsnLogger.hpp> #include <set> namespace psn { OpenDBHandler::OpenDBHandler(sta::DatabaseSta* sta) : sta_(sta), db_(sta->db()) { } std::vector<InstanceTerm*> OpenDBHandler::pins(Net* net) const { std::vector<InstanceTerm*> terms; InstanceTermSet term_set = net->getITerms(); for (InstanceTermSet::iterator itr = term_set.begin(); itr != term_set.end(); itr++) { InstanceTerm* inst_term = (*itr); terms.push_back(inst_term); } return terms; } std::vector<InstanceTerm*> OpenDBHandler::pins(Instance* inst) const { std::vector<InstanceTerm*> terms; InstanceTermSet term_set = inst->getITerms(); for (InstanceTermSet::iterator itr = term_set.begin(); itr != term_set.end(); itr++) { InstanceTerm* inst_term = (*itr); terms.push_back(inst_term); } return terms; } Net* OpenDBHandler::net(InstanceTerm* term) const { return term->getNet(); } std::vector<InstanceTerm*> OpenDBHandler::connectedPins(Net* net) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, connectedPins) return std::vector<InstanceTerm*>(); } std::set<BlockTerm*> OpenDBHandler::clockPins() const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, clockPins) return std::set<BlockTerm*>(); } std::vector<InstanceTerm*> OpenDBHandler::inputPins(Instance* inst) const { auto inst_pins = pins(inst); PinDirection dir = PinDirection::INPUT; return filterPins(inst_pins, &dir); } std::vector<InstanceTerm*> OpenDBHandler::outputPins(Instance* inst) const { auto inst_pins = pins(inst); PinDirection dir = PinDirection::OUTPUT; return filterPins(inst_pins, &dir); } std::vector<InstanceTerm*> OpenDBHandler::fanoutPins(Net* net) const { auto inst_pins = pins(net); PinDirection dir = PinDirection::INPUT; return filterPins(inst_pins, &dir); } std::vector<InstanceTerm*> OpenDBHandler::levelDriverPins() const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, levelDriverPins) return std::vector<InstanceTerm*>(); } InstanceTerm* OpenDBHandler::faninPin(Net* net) const { InstanceTermSet terms = net->getITerms(); for (InstanceTermSet::iterator itr = terms.begin(); itr != terms.end(); itr++) { InstanceTerm* inst_term = (*itr); Instance* inst = itr->getInst(); if (inst) { if (inst_term->getIoType() == PinDirection::OUTPUT) { return inst_term; } } } return nullptr; } std::vector<Instance*> OpenDBHandler::fanoutInstances(Net* net) const { std::vector<Instance*> insts; std::vector<InstanceTerm*> pins = fanoutPins(net); for (auto& term : pins) { insts.push_back(term->getInst()); } return insts; } std::vector<Instance*> OpenDBHandler::driverInstances() const { std::set<Instance*> insts_set; for (auto& net : nets()) { InstanceTerm* driverPin = faninPin(net); if (driverPin) { Instance* inst = driverPin->getInst(); if (inst) { insts_set.insert(inst); } } } return std::vector<Instance*>(insts_set.begin(), insts_set.end()); } unsigned int OpenDBHandler::fanoutCount(Net* net) const { return fanoutPins(net).size(); } std::vector<InstanceTerm*> OpenDBHandler::criticalPath() const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, criticalPath) return std::vector<InstanceTerm*>(); } std::vector<InstanceTerm*> OpenDBHandler::bestPath() const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, bestPath) return std::vector<InstanceTerm*>(); } bool OpenDBHandler::isCommutative(InstanceTerm* first, InstanceTerm* second) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isCommutative) return false; } Point OpenDBHandler::location(InstanceTerm* term) { int x, y; term->getInst()->getOrigin(x, y); return Point(x, y); } Point OpenDBHandler::location(BlockTerm* term) { int x, y; if (term->getFirstPinLocation(x, y)) return Point(x, y); return Point(0, 0); } Point OpenDBHandler::location(Instance* inst) { int x, y; inst->getOrigin(x, y); return Point(x, y); } float OpenDBHandler::area(Instance* inst) { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, area) return 0; } float OpenDBHandler::area() { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, area) return 0; } void OpenDBHandler::setLocation(Instance* inst, Point pt) { inst->setPlacementStatus(odb::dbPlacementStatus::PLACED); inst->setLocation(pt.getX(), pt.getY()); } LibraryTerm* OpenDBHandler::libraryPin(InstanceTerm* term) const { return term->getMTerm(); } std::vector<LibraryTerm*> OpenDBHandler::libraryPins(Instance* inst) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, libraryPins); return std::vector<LibraryTerm*>(); } std::vector<LibraryTerm*> OpenDBHandler::libraryPins(LibraryCell* cell) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, libraryPins); return std::vector<LibraryTerm*>(); } std::vector<LibraryTerm*> OpenDBHandler::libraryInputPins(LibraryCell* cell) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, libraryInputPins); return std::vector<LibraryTerm*>(); } std::vector<LibraryTerm*> OpenDBHandler::libraryOutputPins(LibraryCell* cell) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, libraryOutputPins); return std::vector<LibraryTerm*>(); } bool OpenDBHandler::isClocked(InstanceTerm* term) const { return term->isClocked(); } bool OpenDBHandler::isPrimary(Net* net) const { return net->getBTerms().size() > 0; } LibraryCell* OpenDBHandler::libraryCell(InstanceTerm* term) const { LibraryTerm* lterm = libraryPin(term); if (lterm) { return lterm->getMaster(); } return nullptr; } LibraryCell* OpenDBHandler::libraryCell(Instance* inst) const { return inst->getMaster(); } LibraryCell* OpenDBHandler::libraryCell(const char* name) const { auto lib = library(); if (!lib) { return nullptr; } return lib->findMaster(name); } LibraryCell* OpenDBHandler::largestLibraryCell(LibraryCell* cell) { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, largestLibraryCell) return nullptr; } double OpenDBHandler::dbuToMeters(uint dist) const { return dist * 1E-9; } bool OpenDBHandler::isPlaced(InstanceTerm* term) const { odb::dbPlacementStatus status = term->getInst()->getPlacementStatus(); return status == odb::dbPlacementStatus::PLACED || status == odb::dbPlacementStatus::LOCKED || status == odb::dbPlacementStatus::FIRM || status == odb::dbPlacementStatus::COVER; } bool OpenDBHandler::isPlaced(BlockTerm* term) const { odb::dbPlacementStatus status = term->getFirstPinPlacementStatus(); return status == odb::dbPlacementStatus::PLACED || status == odb::dbPlacementStatus::LOCKED || status == odb::dbPlacementStatus::FIRM || status == odb::dbPlacementStatus::COVER; } bool OpenDBHandler::isPlaced(Instance* inst) const { odb::dbPlacementStatus status = inst->getPlacementStatus(); return status == odb::dbPlacementStatus::PLACED || status == odb::dbPlacementStatus::LOCKED || status == odb::dbPlacementStatus::FIRM || status == odb::dbPlacementStatus::COVER; } bool OpenDBHandler::isDriver(InstanceTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isDriver) return false; } float OpenDBHandler::pinCapacitance(InstanceTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, pinCapacitance) return 0.0; } float OpenDBHandler::pinCapacitance(LibraryTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, pinCapacitance) return 0.0; } float OpenDBHandler::targetLoad(LibraryCell* cell) { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, targetLoad) return 0.0; } float OpenDBHandler::maxLoad(LibraryCell* cell) { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, maxLoad) return 0.0; } float OpenDBHandler::maxLoad(LibraryTerm* term) { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, maxLoad) return 0.0; } bool OpenDBHandler::isInput(InstanceTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isInput) return false; } bool OpenDBHandler::isOutput(InstanceTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isOutput) return false; } bool OpenDBHandler::isAnyInput(InstanceTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isAnyInput) return false; } bool OpenDBHandler::isAnyOutput(InstanceTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isAnyOutput) return false; } bool OpenDBHandler::isBiDirect(InstanceTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isBiDirect) return false; } bool OpenDBHandler::isTriState(InstanceTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isTriState) return false; } OpenDBHandler::isInput(BlockTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isInput) return false; } bool OpenDBHandler::isOutput(BlockTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isOutput) return false; } bool OpenDBHandler::isAnyInput(BlockTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isAnyInput) return false; } bool OpenDBHandler::isAnyOutput(BlockTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isAnyOutput) return false; } bool OpenDBHandler::isBiDirect(BlockTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isBiDirect) return false; } bool OpenDBHandler::isTriState(BlockTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isTriState) return false; } bool OpenDBHandler::isInput(LibraryTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isInput) return false; } bool OpenDBHandler::isOutput(LibraryTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isOutput) return false; } bool OpenDBHandler::isAnyInput(LibraryTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isAnyInput) return false; } bool OpenDBHandler::isAnyOutput(LibraryTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isAnyOutput) return false; } bool OpenDBHandler::isBiDirect(LibraryTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isBiDirect) return false; } bool OpenDBHandler::isTriState(LibraryTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, isTriState) return false; } bool OpenDBHandler::hasMaxCapViolation(InstanceTerm* term) const { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, hasMaxCapViolation) return false; } Instance* OpenDBHandler::instance(const char* name) const { Block* block = top(); if (!block) { return nullptr; } return block->findInst(name); } Instance* OpenDBHandler::instance(InstanceTerm* term) const { return term->getInst(); } Net* OpenDBHandler::net(const char* name) const { Block* block = top(); if (!block) { return nullptr; } return block->findNet(name); } LibraryTerm* OpenDBHandler::libraryPin(const char* cell_name, const char* pin_name) const { LibraryCell* cell = libraryCell(cell_name); if (!cell) { return nullptr; } return libraryPin(cell, pin_name); } LibraryTerm* OpenDBHandler::libraryPin(LibraryCell* cell, const char* pin_name) const { return cell->findMTerm(top(), pin_name); } std::vector<InstanceTerm*> OpenDBHandler::filterPins(std::vector<InstanceTerm*>& terms, PinDirection* direction) const { std::vector<InstanceTerm*> inst_terms; for (auto& term : terms) { Instance* inst = term->getInst(); if (inst) { if (term && term->getIoType() == *direction) { inst_terms.push_back(term); } } } return inst_terms; } void OpenDBHandler::del(Net* net) const { Net::destroy(net); } int OpenDBHandler::disconnectAll(Net* net) const { int count = 0; InstanceTermSet net_set = net->getITerms(); for (InstanceTermSet::iterator itr = net_set.begin(); itr != net_set.end(); itr++) { InstanceTerm::disconnect(*itr); count++; } return count; } void OpenDBHandler::connect(Net* net, InstanceTerm* term) const { return InstanceTerm::connect(term, net); } void OpenDBHandler::disconnect(InstanceTerm* term) const { InstanceTerm::disconnect(term); } Instance* OpenDBHandler::createInstance(const char* inst_name, LibraryCell* cell) { return Instance::create(top(), cell, inst_name); } Net* OpenDBHandler::createNet(const char* net_name) { return Net::create(top(), net_name); } InstanceTerm* OpenDBHandler::connect(Net* net, Instance* inst, LibraryTerm* port) const { return InstanceTerm::connect(inst, net, port); } std::vector<Net*> OpenDBHandler::nets() const { std::vector<Net*> nets; Block* block = top(); if (!block) { return std::vector<Net*>(); } NetSet net_set = block->getNets(); for (NetSet::iterator itr = net_set.begin(); itr != net_set.end(); itr++) { nets.push_back(*itr); } return nets; } std::string OpenDBHandler::topName() const { Block* block = top(); if (!block) { return ""; } return name(block); } std::string OpenDBHandler::name(Block* object) const { return std::string(object->getConstName()); } std::string OpenDBHandler::name(Net* object) const { return std::string(object->getConstName()); } std::string OpenDBHandler::name(Instance* object) const { return std::string(object->getConstName()); } std::string OpenDBHandler::name(BlockTerm* object) const { return std::string(object->getConstName()); } std::string OpenDBHandler::name(Library* object) const { return std::string(object->getConstName()); } std::string OpenDBHandler::name(LibraryCell* object) const { return std::string(object->getConstName()); } std::string OpenDBHandler::name(LibraryTerm* object) const { return std::string(object->getConstName()); } Library* OpenDBHandler::library() const { LibrarySet libs = db_->getLibs(); if (!libs.size()) { return nullptr; } Library* lib = *(libs.begin()); return lib; } bool OpenDBHandler::dontUse(LibraryCell* cell) const { return false; } void OpenDBHandler::resetDelays() { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, resetDelays); } void OpenDBHandler::resetDelays(InstanceTerm* term) { HANDLER_UNSUPPORTED_METHOD(OpenDBHandler, resetDelays); } LibraryTechnology* OpenDBHandler::technology() const { Library* lib = library(); if (!lib) { return nullptr; } LibraryTechnology* tech = lib->getTech(); return tech; } Block* OpenDBHandler::top() const { Chip* chip = db_->getChip(); if (!chip) { return nullptr; } Block* block = chip->getBlock(); return block; } void OpenDBHandler::clear() const { db_->clear(); } OpenDBHandler::~OpenDBHandler() { } } // namespace psn #endif
65c705d616c4ba507317272e9c67ac0f6972a078
0d50b947a9051f29ab28b73c0e7bfbecd4f2421e
/classes/debug.cpp
6379abbdeb3bc674067f7680d2cfd206cf8162b3
[]
no_license
tomijuarez/YAVT
8e8409a94fe849a46bb3dd794022caceacb6f2af
aa86edf8cadf82a26ca0399ccaff11249a766a61
refs/heads/Actualización
2021-11-23T10:10:05.661911
2018-01-26T13:51:10
2018-01-26T13:51:10
31,529,384
0
0
null
2021-11-10T03:27:36
2015-03-02T08:00:54
C
UTF-8
C++
false
false
2,147
cpp
debug.cpp
#include "debug.h" Debug::Debug(TreeAux Tree) { this->_Tree = Tree; } void Debug::StardDebug(QMap<int, QQueue<std::string> > & result){ QList<QString> branch; this->_Tree.getBranches(branch); unsigned int num = 1; bool close; std::string formulaOne; std::string formulaTwo; QQueue<std::string> OpForm; std::cout<<std::endl<<"***********Verificacion formal del algoritmo****************"<<std::endl; while( !branch.empty() ) { if(close == true) { OpForm.enqueue(formulaOne); OpForm.enqueue(formulaTwo); result[num] = OpForm; this->_Tree.closeBranch(); } else { OpForm.enqueue("Rama abierta"); result[num] = OpForm; } num++; branch.clear(); OpForm.clear(); this->_Tree.getBranches(branch); } } void Debug::printResult(QMap<int,QQueue<std::string> > result) { QMap<int,QQueue<std::string> >::iterator it = result.begin(); std::string aux1; std::string aux2; std::cout<<std::endl<<"****************RESULTADOS***************"<<std::endl; while(it != result.end()) { std::cout<<"Rama numero: "<<it.key()<<std::endl; if(it.value().size() == 2) { std::cout<<"Rama cerrada"<<std::endl; aux1 = it.value().dequeue(); std::cout<<aux1<<std::endl; aux2 = it.value().dequeue(); if(aux2 != "empty") { std::cout<<aux2<<std::endl; } std::cout<<std::endl; } else { aux1 = it.value().dequeue(); std::cout<<aux1<<std::endl; std::cout<<std::endl; } it++; } if(this->_Tree.closeTree() == true) { std::cout<<"El arbol es CERRADO, por lo que podemos afirmar que la prueba correspondiente es satisfactoria"<<std::endl; } else { std::cout<<"El arbol es ABIERTO, por lo que podemos afirmar que la prueba correspondiente es NO satisfactoria"<<std::endl; } } Debug::~Debug() { }
4e0ebe779a02fa5c50b5798b40ac911baaec2842
6407a249c0b8ffa7fee2c8958a14e73f1740d5bb
/Exp.cpp
23047cf32726a2b949c052f09cd5709f7077ef8a
[]
no_license
emilia08/hello
1a8db198c9bc5144c4b35fbe4f3587781b3ab24a
2da4d92ea92d6a3091dd8907382036effcacbaea
refs/heads/master
2020-03-21T05:12:48.464332
2018-06-21T09:38:08
2018-06-21T09:38:08
138,149,315
0
0
null
null
null
null
UTF-8
C++
false
false
1,620
cpp
Exp.cpp
#include <iostream> #include <stdexcept> #include <vector> using std::runtime_error; /* int sub(int a, int b) { if (a < 0 || b < 0) { throw std::invalid_argument("received negative value"); } int c = a + b; std::cout << c << std::endl; return c; } int main() { try { sub(3, -1); } catch (const std::invalid_argument& ia) { std::cerr << "Invalid argument: " << ia.what() << '\n'; } getchar(); return 0; } */ /* int main() { std::vector<int> v(5); try { v.at(20) = 100; } catch (const std::out_of_range& oor){ std::cerr << "Out of Range error: " << oor.what() << '\n'; } getchar(); return 0; } */ /* double division(int a, int b) { if (b == 0) { throw "Division by zero condition!"; } return (a / b); } int main() { int x = 50; int y = 0; double z = 0; try { z = division(x, y); std::cout << z << std::endl; } catch (const char* msg) { std::cerr << msg << std::endl; } getchar(); return 0; }*/ class DivideByZero : public runtime_error { public: DivideByZero::DivideByZero() :runtime_error("divided by zero"){} }; double sub(int a, int b) { if (b == 0) { throw DivideByZero(); } return static_cast<double>(a / b); } int main() { int num1; int num2; double result; while (std::cin >> num1 >> num2) { try { result = sub(num1, num2); std::cout << "The result of dividing is: " << result << std::endl; } catch(DivideByZero &DivideByZero){ std::cout << "Exception occurred: " << DivideByZero.what() << std::endl; } } getchar(); return 0; }
6bf4759535f0c8fe7faedd28732c0e5b1e017d99
dc926d42247cda887a02fc2aec37086144ace386
/Act. 2.1 LinkedList/list.h
5556ab18a448efa154b00941016038a6f69a60a5
[]
no_license
KevDP/Actividades-Formativas
49c0d57c42289af347e10dd6c6ae527f44a3a05f
f9f608c88d134c3052b7bf4bfcfe3e26d271c2a0
refs/heads/master
2023-01-29T06:13:37.093134
2020-12-04T08:41:40
2020-12-04T08:41:40
294,279,946
0
1
null
null
null
null
UTF-8
C++
false
false
2,585
h
list.h
#ifndef LIST_H_ #define LIST_H_ #include <sstream> #include <cstring> #include <string> using namespace std; template <class T> class List; template <class T> class Link { private: Link(T); Link(T, Link<T>*); T value; Link<T> *next; friend class List<T>; }; template <class T> Link<T>::Link(T val) : value(val), next(0) {} template <class T> Link<T>::Link(T val, Link* nxt) : value(val), next(nxt) {} template <class T> class List{ public: List(); List(const List<T>&); ~List(); void clear(); bool empty() const; void addFirst(T); void add(T); T find(T); void update(T,T); T remove(int); T removeFirst(); string toString() const; private: Link<T> *head; int size; }; template <class T> List<T>::List() : head(0), size(0) {} template <class T> List<T>::~List() { clear(); } template <class T> void List<T>::clear() { Link<T> *p, *q; p = head; while (p != 0) { q = p->next; delete p; p = q; } head = 0; size = 0; } template <class T> bool List<T>::empty() const { return (head == 0); } template <class T> void List<T>::addFirst(T val) { Link<T> *newLink; newLink = new Link<T>(val); newLink->next = head; head = newLink; size++; } template <class T> void List<T>::add(T val) { Link<T> *newLink, *p; newLink = new Link<T>(val); if(empty()){ addFirst(val); return; } p = head; while (p->next != 0) { p = p->next; } newLink->next = 0; p->next = newLink; size++; } template <class T> T List<T>::find(T val) { int pos = 0; Link<T> *p; p = head; while(p != 0){ if (p->value == val) { return pos; } p = p->next; pos++; } return -1; } template <class T> void List<T>::update(T pos,T val) { Link<T> *p; int cont = 0; p = head; while (p != 0){ if (cont == pos){ p->value = val; } p = p->next; cont++; } } template <class T> T List<T>::remove(int index) { T val; int pos; Link<T> *p, *aux; aux = 0; p = head; if (index == 0) { return removeFirst(); } for (int i=0;i<size;i++) { if(i == index){ aux->next = p->next; val = p->value; delete p; break; } aux = p; p = p->next; } return val; } template <class T> T List<T>::removeFirst() { T val; Link<T> *p; p = head; head = p->next; val = p->value; delete p; size--; return val; } template <class T> string List<T>::toString() const { stringstream aux; Link<T> *p; p = head; aux << "["; while (p != 0) { aux << p->value; if (p->next != 0) { aux << ", "; } p = p->next; } aux << "]"; return aux.str(); } #endif
4c6b6058c139cd1f4faef30ada240b55ade201ef
23b3aa151a0c411d047baffaf2e43092507e9d89
/projects/project 3/Project 3/Project 3/main.cpp
6f8b75bd77ba3574a12e077251359f44bd551a3c
[]
no_license
davidmednikov/CS-162
8046c1160b4b9cd5d8f5abbe9ee840205a4a1721
9e2f1e83ec972667c542a203046f924d4f37fcfe
refs/heads/master
2021-05-14T19:08:23.726405
2018-01-03T06:34:22
2018-01-03T06:34:22
116,101,050
0
0
null
null
null
null
UTF-8
C++
false
false
18,069
cpp
main.cpp
/**************************************************************************** ** Program name: CS162 Project 3 ** Author: David Mednikov ** Date: 02/13/17 ** Description: This program simulates a fantasy combat game. There are ** 5 creatures in this game: Vampire, Barbarian, Blue Men, Medusa, and ** Harry Potter. Each creature has its own attributes, including an attack, ** defense, armor, and strength points. Some creatures also have special ** charactertics for their attack/defense/health. A game involves 2 characters ** taking turns attacking one another, using their attack, defense, and armor to ** determine how much damage the defending player takes. When a player has 0 ** strength points left (except Harry Potter...) they lose and the other player ** is declared the winner of the match. This program randomly decides who goes ** first and randomly generates the attack and defense values for each player. ****************************************************************************/ #include "Creature.h" // Creature header #include "Vampire.h" // Vampire header #include "Barbarian.h" // Barbarian header #include "BlueMen.h" // Blue Men header #include "Medusa.h" // Medusa header #include "HarryPotter.h" // Harry Potter header #include "getInt.h" // getInt() header #include "showMenu.h" // showMenu() header #include <iostream> // input and output #include <string> // string #include <stdlib.h> // seed for rand() #include <time.h> // time() #include <vector> // vectors using std::string; // clean up code using std::vector; using std::endl; using std::cout; using std::cin; using std::getline; using std::move; int main() { cout << "\n\nWelcome to the Ultimate Fantasy Combat Tournament!\n\n"; // its the ultimate fantasy combat game vector<string> creatures = { "Vampire", "Barbarian", "Blue Men", "Medusa", "Harry Potter" }; srand(time(NULL)); // seed CPU time bool playAgain = true; // to keep playing while (playAgain) // loop until user wants to stop playing { cout << "How many players will each team have: "; int players = getInt(1); int round = 1; int p1Score = 0; int p2Score = 0; vector<Creature*> p1Team; vector<Creature*> p2Team; vector<Creature*> deadPile; cout << "\nSelect your team.\n"; for (int player = 0; player < players; ++player) { cout << "\nPick creature #" << player + 1 << " for your team:\n\n"; int choice = showMenu(creatures, 1); cout << "\nEnter a name for this creature: "; string name; getline(cin, name); Creature* teamMember; switch (choice) { case 1: teamMember = new Vampire(name); break; case 2: teamMember = new Barbarian(name); break; case 3: teamMember = new BlueMen(name); break; case 4: teamMember = new Medusa(name); break; case 5: teamMember = new HarryPotter(name); break; default: break; } p1Team.push_back(teamMember); } cout << "\n\nSelect player 2's team.\n"; for (int player = 0; player < players; ++player) { cout << "\nPick creature #" << player + 1 << " for the other team:\n\n"; int choice = showMenu(creatures, 1); cout << "\nEnter a name for this creature: "; string name; getline(cin, name); Creature* teamMember; switch (choice) { case 1: teamMember = new Vampire(name); break; case 2: teamMember = new Barbarian(name); break; case 3: teamMember = new BlueMen(name); break; case 4: teamMember = new Medusa(name); break; case 5: teamMember = new HarryPotter(name); break; default: break; } p2Team.push_back(teamMember); } bool seeRoundResults = false; string seeRound; cout << "\nDo you want to see the score after each round? y for yes, n for no: "; getline(cin, seeRound); bool valid = false; while (!valid) // loop until valid input { if (seeRound == "y" || seeRound == "Y") // see score at end of each round { seeRoundResults = true; valid = true; // break out of loop } else if (seeRound == "n" || seeRound == "N") // don't see score at end of each round { valid = true; // break out of loop } else // invalid input { cout << "You did not enter y or n. Try again: "; cin.clear(); // clear input stream cin >> seeRound; // loop back to top } } bool p1GoesFirst = false; // initialize bool for who goes first if (rand() % 2) // 50/50 to see who goes first { cout << "\nPlayer 1's team will go first.\n"; // player1 goes first p1GoesFirst = true; // set bool to true } else { cout << "\nPlayer 2's team will go first.\n"; // don't do anything } if (p1GoesFirst) // if player 1 goes first, use while loop to alternate turns beginning with p1 { bool gameActive = true; // game is still active while (gameActive) // while both teams have players left { Creature* player1 = p1Team[0]; Creature* player2 = p2Team[0]; int p1Attack = player1->attack(); // calculate p1's attack int p2Defense = player2->defense(); // calculate p2's defense // cout << endl << player1->getName() << "'s attack: " << p1Attack << endl << player2->getName() << "'s defense: " << p2Defense << endl; // debug int damage = p1Attack - p2Defense - player2->getArmor(); // calculate damage to p2 if (p1Attack == 0) // Medusa Glare { // cout << "\nMGlare!\n"; damage = player2->getStrengthPoints(); // set damage to kill player 2 } if (p2Defense == 0) // Vampire Charm { // cout << "\nCharm!\n"; damage = 0; // attack missed } if (damage < 0) // if damage is negative (defense > attack) set damage to 0 { damage = 0; } // cout << "\nTotal damage to " << player2->getName() << ": " << damage << endl; // debug player2->removePoints(damage); // damage player 2's strength points // cout << endl << player2->getName() << " has " << player2->getStrengthPoints() << " strength points left.\n\n"; // debug if (player2->getStrengthPoints() == 0) // check if p2 is dead after attack { // cout << endl << player2->getName() << " has died.\n"; cout << "\nRound " << round << ": " << "Player 1's " << player1->getName() << " (" << player1->getType() << ") vs. Player 2's " << player2->getName() << " (" << player2->getType() << ")\n"; cout << endl << player1->getName() << " won this round!\n"; ++round; p1Score += 2; p2Score -= 1; if (p2Score < 0) { p2Score = 0; } if (seeRoundResults) { cout << "\nCurrent Score:\n"; cout << "Player 1's team: " << p1Score << " points\n"; cout << "Player 2's team: " << p2Score << " points\n"; } Creature* dead = player2; deadPile.push_back(dead); player1->restoreHealth(); Creature* temp = player1; p1Team.erase(p1Team.begin()); p1Team.push_back(temp); // cout << "\nRestored some health to " << player1->getName() << " and moved to the back of the queue.\n"; p2Team.erase(p2Team.begin()); // cout << endl << player2->getName() << " has been added to the dead pile.\n"; if (p2Team.size() == 0) { // Player 2 is out of players gameActive = false; } } else { int p2Attack = player2->attack(); // calculate p2's attack int p1Defense = player1->defense(); // calculate p1's attack // cout << endl << player2->getName() << "'s attack: " << p2Attack << endl << player1->getName() << "'s defense: " << p1Defense << endl; int damage = p2Attack - p1Defense - player1->getArmor(); // calculate total damage to p1 if (p2Attack == 0) // Medusa Glare { // cout << "\nGlare!\n"; damage = player1->getStrengthPoints(); // set damage to kill p1 } if (p1Defense == 0) // Vampire Charm { // cout << "\nCharm!\n"; damage = 0; // attack missed } if (damage < 0) // if damage is negative, set to 0 { damage = 0; } player1->removePoints(damage); // remove damage points from player 1 // cout << "\nTotal damage to " << player1->getName() << ": " << damage << endl; // cout << endl << player1->getName() << " has " << player1->getStrengthPoints() << " strength points left.\n\n"; // debug if (player1->getStrengthPoints() == 0) // if player1 died { // cout << endl << player1->getName() << " has died.\n"; cout << "\nRound " << round << ": " << "Player 1's " << player1->getName() << " (" << player1->getType() << ") vs. Player 2's " << player2->getName() << " (" << player2->getType() << ")\n"; cout << endl << player2->getName() << " won this round!\n"; ++round; p2Score += 2; p1Score -= 1; if (p1Score < 0) { p1Score = 0; } if (seeRoundResults) { cout << "\nCurrent Score:\n"; cout << "Player 1's team: " << p1Score << " points\n"; cout << "Player 2's team: " << p2Score << " points\n"; } Creature* dead = player1; deadPile.push_back(dead); player2->restoreHealth(); Creature* temp = player2; p2Team.erase(p2Team.begin()); p2Team.push_back(temp); // cout << "\nRestored some health to " << player2->getName() << " and moved to the back of the queue.\n"; p1Team.erase(p1Team.begin()); // cout << endl << player1->getName() << " has been added to the dead pile.\n"; if (p1Team.size() == 0) { // Player 1 is out of players gameActive = false; } } } } } else // Player 2 goes first { bool gameActive = true; // keep game running while (gameActive) // while both teams have players left { Creature* player1 = p1Team[0]; Creature* player2 = p2Team[0]; int p2Attack = player2->attack(); // calculate p2's attack int p1Defense = player1->defense(); // calculate p1's attack // cout << endl << player2->getName() << "'s attack: " << p2Attack << endl << player1->getName() << "'s defense: " << p1Defense << endl; int damage = p2Attack - p1Defense - player1->getArmor(); // calculate total damage to p1 if (p2Attack == 0) // Medusa Glare { // cout << "\nGlare!\n"; damage = player1->getStrengthPoints(); // set damage to kill p1 } if (p1Defense == 0) // Vampire Charm { // cout << "\nCharm!\n"; damage = 0; // attack missed } if (damage < 0) // if damage is negative, set to 0 { damage = 0; } player1->removePoints(damage); // remove damage points from player 1 // cout << "\nTotal damage to " << player1->getName() << ": " << damage << endl; // cout << endl << player1->getName() << " has " << player1->getStrengthPoints() << " strength points left.\n\n"; // debug if (player1->getStrengthPoints() == 0) // if player1 died { // cout << endl << player1->getName() << " has died.\n"; cout << "\nRound " << round << ": " << "Player 1's " << player1->getName() << " (" << player1->getType() << ") vs. Player 2's " << player2->getName() << " (" << player2->getType() << ")\n"; cout << endl << player2->getName() << " won this round!\n"; ++round; p2Score += 2; p1Score -= 1; if (p1Score < 0) { p1Score = 0; } if (seeRoundResults) { cout << "\nCurrent Score:\n"; cout << "Player 1's team: " << p1Score << " points\n"; cout << "Player 2's team: " << p2Score << " points\n"; } Creature* dead = player1; deadPile.push_back(dead); player2->restoreHealth(); Creature* temp = player2; p2Team.erase(p2Team.begin()); p2Team.push_back(temp); // cout << "\nRestored some health to " << player2->getName() << " and moved to the back of the queue.\n"; p1Team.erase(p1Team.begin()); // cout << endl << player1->getName() << " has been added to the dead pile.\n"; if (p1Team.size() == 0) { // Player 1 is out of players gameActive = false; } } else { int p1Attack = player1->attack(); // calculate p1's attack int p2Defense = player2->defense(); // calculate p2's defense // cout << endl << player1->getName() << "'s attack: " << p1Attack << endl << player2->getName() << "'s defense: " << p2Defense << endl; // debug int damage = p1Attack - p2Defense - player2->getArmor(); // calculate damage to p2 if (p1Attack == 0) // Medusa Glare { // cout << "\nMGlare!\n"; damage = player2->getStrengthPoints(); // set damage to kill player 2 } if (p2Defense == 0) // Vampire Charm { // cout << "\nCharm!\n"; damage = 0; // attack missed } if (damage < 0) // if damage is negative (defense > attack) set damage to 0 { damage = 0; } // cout << "\nTotal damage to " << player2->getName() << ": " << damage << endl; // debug player2->removePoints(damage); // damage player 2's strength points // cout << endl << player2->getName() << " has " << player2->getStrengthPoints() << " strength points left.\n\n"; // debug if (player2->getStrengthPoints() == 0) // check if p2 is dead after attack { // cout << endl << player2->getName() << " has died.\n"; cout << "\nRound " << round << ": " << "Player 1's " << player1->getName() << " (" << player1->getType() << ") vs. Player 2's " << player2->getName() << " (" << player2->getType() << ")\n"; cout << endl << player1->getName() << " won this round!\n"; ++round; p1Score += 2; p2Score -= 1; if (p2Score < 0) { p2Score = 0; } if (seeRoundResults) { cout << "\nCurrent Score:\n"; cout << "Player 1's team: " << p1Score << " points\n"; cout << "Player 2's team: " << p2Score << " points\n"; } Creature* dead = player2; deadPile.push_back(dead); player1->restoreHealth(); Creature* temp = player1; p1Team.erase(p1Team.begin()); p1Team.push_back(temp); // cout << "\nRestored some health to " << player1->getName() << " and moved to the back of the queue.\n"; p2Team.erase(p2Team.begin()); // cout << endl << player2->getName() << " has been added to the dead pile.\n"; if (p2Team.size() == 0) { // Player 2 is out of players gameActive = false; } } } } } bool p1Won = false; // initialize bool for who won bool tie = false; if (p1Score > p2Score) { p1Won = true; } else if (p1Score == p2Score) { tie = true; } if (p1Won) // player1 won { cout << "\nPlayer 1's team (you) won the tournament!\n"; // print out winner } else if (tie) { cout << "\nWe have an unlikely tie!\n"; // print out that it was a tie } else // player 2 won { cout << "\nPlayer 2's team (not you) won the tournament!\n"; // print out winner } cout << "\nWould you like to see the dead pile? Enter y for yes or n for no: "; // ask user if they want to see the dead pile string showDead; // initialize input variable cin >> showDead; // assign input to variable bool validInput = false; while (!validInput) // loop until valid input { if (showDead == "y" || showDead == "Y") // play again { cout << "\nHere is the dead pile, beginning with the most recent to die.\n"; for (int index = deadPile.size() - 1; index >= 0; --index) { cout << deadPile[index]->getName() << endl; } validInput = true; // break out of loop } else if (showDead == "n" || showDead == "N") // don't play again { cout << "\nOk, I guess I won't show you then!\n"; validInput = true; // break out of loop } else // invalid input { cout << "You did not enter y or n. Try again: "; cin.clear(); // clear input stream cin >> showDead; // loop back to top } } bool validString = false; // for input to play again cout << "\nWould you like to play again? Enter y for yes or n for no: "; // ask user if they want to play again string again; // initialize input variable cin >> again; // assign input to variable while (!validString) // loop until valid input { if (again == "y" || again == "Y") // play again { cout << "\nYou are wise beyond your years.\n"; // (for continuing to use such a glorious program) for (int index = 0; index < p1Team.size(); ++index) { delete p1Team[index]; } for (int index = 0; index < p2Team.size(); ++index) { delete p2Team[index]; } for (int index = 0; index < deadPile.size(); ++index) { delete deadPile[index]; } validString = true; // break out of loop } else if (again == "n" || again == "N") // don't play again { cout << "\nToo bad. See you next time.\n\n"; // don't come back. nobody wants you here for (int index = 0; index < p1Team.size(); ++index) { delete p1Team[index]; } for (int index = 0; index < p2Team.size(); ++index) { delete p2Team[index]; } for (int index = 0; index < deadPile.size(); ++index) { delete deadPile[index]; } return 0; } /************************************************************************* VALGRIND Summary ==17044== HEAP SUMMARY: ==17044== in use at exit: 0 bytes in 0 blocks ==17044== total heap usage: 35 allocs, 35 frees, 1,007 bytes allocated ==17044== ==17044== All heap blocks were freed -- no leaks are possible ==17044== ==17044== For counts of detected and suppressed errors, rerun with: -v ==17044== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1) flip2 ~/162/projects/proj3 182% **************************************************************************/ else // invalid input { cout << "You did not enter y or n. Try again: "; cin.clear(); // clear input stream cin >> again; // loop back to top } } } }
813f77bf35760e3b7ad302f75f73f25a9325fe15
b71f91fa26bfb764dae051311237b45aef5f62da
/main1.cpp
706ca68795947620a9f35efb4999a43c659ef679
[]
no_license
jimarathomas2021/Binary-Search-Tree-Project
49990bea1d818bd547bdf68cb47839d2f29fd5bc
13e296e581c141276cc97a96d217d082bac85cb7
refs/heads/master
2020-07-20T21:30:25.981027
2019-09-15T04:07:10
2019-09-15T04:07:10
206,712,409
0
0
null
null
null
null
UTF-8
C++
false
false
764
cpp
main1.cpp
#include<iostream> #include <string> #include <fstream> #include<vector> #include <time.h> #include "bst.h" #include "songdata.h" //#include "songdata.cpp" using namespace std; int main(){ string filename = "songs.txt"; vector<Song> V; Song s1; s1.readData( &V, filename); s1.displayAllSong(V); srand(time(NULL)); BinaryTree<Song> tree; while(V.size() != 0){ int r = rand() % V.size(); tree.insertNode(V[r]); int i = 0; for(auto it = V.begin(); it != V.end(); ++it){ if(i == r){ V.erase(it); break; } i++; } } cout << "in order transversal" << endl; tree.print(); cout << endl; cout << "Searching an element" << endl; tree.searchNode(5); system("pause"); return 0; }
2b469817c10d156417aacc6b44647c33803a0660
6c67b633d5cfde6a2b0c71c21fdeeb8b83fe69fb
/TextSimilarity/TextSimilarity/test.cpp
5925bbc5b4d2243bcb65165e468f8343a0119c84
[]
no_license
18292677162/TextSimilarity
c08ccbbf2a37645dc7c4713ef8f359f54ea4caf7
b3af3774e33bc824f592ea75596a324a6a9b9ad1
refs/heads/master
2020-05-29T13:19:17.092160
2019-05-29T05:45:10
2019-05-29T05:45:10
189,157,087
1
0
null
null
null
null
UTF-8
C++
false
false
2,301
cpp
test.cpp
#include "TextSimilarity.h" #include <fstream> #include <cassert> #include <string> #include <Windows.h> using namespace std; //const char* const DICT_PATH = "jieba.dict.utf8"; //const char* const HMM_PATH = "hmm_model.utf8"; //const char* const USER_DICT_PATH = "user.dict.utf8"; //const char* const IDF_PATH = "idf.utf8"; //const char* const STOP_WORD_PATH = "stop_words.utf8"; int main() { TextSimilarity test("dict"); TextSimilarity::wordFreq exWF1; TextSimilarity::wordFreq exWF2; exWF1 = test.getWordFreq("test1.txt"); exWF2 = test.getWordFreq("test2.txt"); vector<pair<string, int>> wfVec1 = test.sortByValueReverse(exWF1); vector<pair<string, int>> wfVec2 = test.sortByValueReverse(exWF2); cout << "wfVec1:" << endl; for (int i = 0; i < 10; i++){ cout << test.UTF8ToGBK(wfVec1[i].first) << ":" << wfVec1[i].second << " , "; } cout << endl; cout << "wfVec2:" << endl; for (int i = 0; i < 10; i++){ cout << test.UTF8ToGBK(wfVec2[i].first) << ":" << wfVec2[i].second << " , "; } cout << endl; /* TestSimilarity::wordFreq::const_iterator map_it; for (map_it = wf.begin(); map_it != wf.end(); map_it++) { cout << "(\"" << test.UTF8ToGBK(map_it->first) << "\"," << map_it->second << ")" << endl; } */ /* TestSimilarity::wordSet wSet1; TestSimilarity::wordSet wSet2; test.selectAimWords(wfVec1, wSet1); cout << "wSet1:" << endl; for (const auto& e : wSet1){ cout << test.UTF8ToGBK(e) << ", "; } cout << endl; test.selectAimWords(wfVec2, wSet2); cout << "wSet2:" << endl; for (const auto& e : wSet2){ cout << test.UTF8ToGBK(e) << ", "; } cout << endl; */ TextSimilarity::wordSet wSet; test.selectAimWords(wfVec1, wSet); cout << "wSet:" << endl; test.selectAimWords(wfVec2, wSet); for (const auto& e : wSet){ cout << test.UTF8ToGBK(e) << ", "; } cout << endl; vector<double> exVec1; vector<double> exVec2; exVec1 = test.getOneHot(wSet, exWF1); exVec2 = test.getOneHot(wSet, exWF2); cout << "exVec1:" << endl; for (const auto& v : exVec1){ cout << v << ", "; } cout << endl; cout << "exVec2:" << endl; for (const auto& v : exVec2){ cout << v << ", "; } cout << endl; double db = 0; db = test.cosine(exVec1, exVec2); cout << "文本相似度为:" << db * 100 <<"%"<< endl; system("pause"); return 0; }
b3f7088d16b25bc2fcf3a9be86e9d93418ba6744
993aa53a358c968d1c7409af9fa63d20bee5cfec
/DynamicObject.hpp
baef4f776962b0cc22a4567fd1b199e9feb64ad5
[]
no_license
MemoryDealer/Cornea
49c6bdad0f935e69fa6ad05d7dd7f244d40495a9
aa8d1b077d198f6c2b40b8017f88001ebb9294ad
refs/heads/master
2023-07-06T02:31:05.035853
2023-06-22T03:21:19
2023-06-22T03:21:19
30,774,425
2
0
null
null
null
null
UTF-8
C++
false
false
6,849
hpp
DynamicObject.hpp
//================================================// #ifndef __DYNAMICOBJECT_HPP__ #define __DYNAMICOBJECT_HPP__ #define USE_KINEMATIC_GROUND 1 //================================================// #include "stdafx.h" #include "Base.hpp" #include "Sparks.hpp" #include "Camera.hpp" #include "Sound.hpp" //================================================// class Switch; class Trigger; //================================================// /* A class for interactive/moving objects in the world */ class DynamicObject{ public: // Data structures for dynamic objects typedef struct{ struct{ Ogre::Real step; Ogre::Real length; btScalar friction; bool spline; bool loop; bool active; std::vector<Ogre::Vector3> vectors; } animation; struct{ bool enabled; unsigned int type; unsigned int actionCode; bool loop; Ogre::Real timeout; Ogre::String str; int x; bool hasNext; Ogre::String next; bool invisible; Ogre::Real range; } trigger; Ogre::ColourValue colour; Ogre::Vector3 offset; Ogre::Quaternion rotationOffset; unsigned int buffer; } DYNAMIC_OBJECT_DATA, *PDYNAMIC_OBJECT_DATA; typedef struct{ int type; Ogre::Real range; Ogre::Real inner, outer; Ogre::ColourValue colour; bool shadows; bool hideNode; Ogre::Real buffer; } LIGHT_DATA, *PLIGHT_DATA; enum{ STATE_IDLE = 0, STATE_ACTIVATED = 1 }; enum{ ARG_NULL = 0, ARG_ACTION = 1, ARG_ACTIVATE, ARG_DEACTIVATE, ARG_OVERRIDE }; enum{ TYPE_MOVING_OBJECT = 0, TYPE_MOVING_KINEMATIC_OBJECT, TYPE_ELEVATOR, TYPE_ROTATING_DOOR, TYPE_SLIDING_DOOR, TYPE_SWITCH, TYPE_NPC, TYPE_STATIC_LIGHT, TYPE_PULSE_LIGHT, TYPE_FLICKER_LIGHT, TYPE_MAGIC_CUBE, TYPE_TRIGGER, END }; // --- // DynamicObject(void); virtual ~DynamicObject(void); virtual void init(Ogre::SceneNode* node, btCollisionObject* colObj); virtual void init(Ogre::SceneManager* mgr, Physics* physics, Ogre::SceneNode* node, btCollisionObject* colObj); virtual void initTrigger(Ogre::SceneManager* mgr, Ogre::SceneNode* node, Sparks::Camera* camera){} virtual void initLight(Ogre::SceneManager* mgr, Ogre::SceneNode* node){} virtual void initSound(const char* file, bool loop = false); virtual unsigned send(unsigned arg); // send a command virtual unsigned recv(void); virtual unsigned recv(unsigned arg); // Data functions virtual DYNAMIC_OBJECT_DATA* getData(void) const; virtual void deleteData(void); void setUserData(int n, void* data); void freeUserData(void); // Misc. functions virtual void retrieve(void); // Some virtual functions to be used by children virtual void setupAnimation(void){} virtual void setTriggerData(DYNAMIC_OBJECT_DATA* data){} virtual void setLinkedObject(DynamicObject* obj){} virtual void setLinkedObject(void* obj){} virtual void setTimeout(Ogre::Real timeout){} virtual void attachSwitch(Switch* _switch){} virtual void setNextTrigger(Trigger* next){} // Getter functions const bool isActive(void) const; const unsigned getState(void) const; Ogre::SceneNode* getSceneNode(void) const; const bool isRetrievable(void) const; const bool isRetrieved(void) const; static int findType(Ogre::SceneNode* node); static unsigned int getTier(int type); // Setter functions void setState(const unsigned state){ m_state = state; } void activate(void); bool needsUpdate(void); virtual void update(double timeSinceLastFrame) = 0; protected: #define USERDATA_SIZE 10 // This data is used for misc. values needed for certain dynamic objects struct{ void* data[USERDATA_SIZE]; bool flags[USERDATA_SIZE]; } m_userData; Ogre::SceneManager* m_pSceneMgr; Ogre::SceneNode* m_pSceneNode; btCollisionObject* m_collisionObject; bool m_retrievable; bool m_retrieved; bool m_needsUpdate; Ogre::Real m_updateRange; unsigned m_state; Sound* m_pSound; bool m_hasSound; Physics* m_physics; }; //================================================// typedef DynamicObject::DYNAMIC_OBJECT_DATA DynamicObjectData; typedef DynamicObject::LIGHT_DATA LightData; //================================================// inline const bool DynamicObject::isActive(void) const { return (m_state > STATE_IDLE) ? true : false; } inline const unsigned DynamicObject::getState(void) const { return m_state; } inline Ogre::SceneNode* DynamicObject::getSceneNode(void) const { return m_pSceneNode; } inline const bool DynamicObject::isRetrievable(void) const { return m_retrievable; } inline const bool DynamicObject::isRetrieved(void) const { return m_retrieved; } inline void DynamicObject::activate(void) { m_state = STATE_ACTIVATED; } //================================================// /* Here the inherited classes will be defined, such as door, elevator, lever, etc. */ //================================================// //================================================// /* Moving object, moves along a track of points in an infinite loop */ class MovingObject : public DynamicObject{ public: MovingObject(void); virtual ~MovingObject(void); virtual void setupAnimation(void); virtual void update(double timeSinceLastFrame); protected: Ogre::AnimationState* m_pAnimState; bool m_loop; }; //================================================// //================================================// /* Moving kinematic object, same as MovingObject, but applies friction to rigid bodies, e.g. a moving platform that holds the player */ class MovingKinematicObject : public MovingObject{ public: MovingKinematicObject(void); void setupAnimation(void); void update(double timeSinceLastFrame); protected: btRigidBody* m_rigidBody; }; //================================================// //================================================// class Elevator : public MovingObject { public: Elevator(void); unsigned send(unsigned arg); void update(double timeSinceLastFrame); protected: }; //================================================// //================================================// /* Switch that can be turned on or off */ class Switch : public DynamicObject { public: Switch(void); void init(Ogre::SceneManager* mgr, Physics* physics, Ogre::SceneNode* node, btCollisionObject* colObj); unsigned send(unsigned arg); void setLinkedObject(DynamicObject* obj); void deleteData(void); void update(double timeSinceLastFrame); protected: DynamicObject* m_linkedObject; bool m_linked; }; //================================================// inline void Switch::setLinkedObject(DynamicObject* obj) { m_linkedObject = obj; m_linked = true; } //================================================// //================================================// #endif //================================================//
d36f6c09ad411c2106b8386db7560706e81034ff
46dc33f6c0a8e4f6698a75e3ae6e98c597124f16
/openhaptics_3.4-0-developer-edition-amd64/opt/OpenHaptics/Developer/3.4-0/examples/HL/graphics/SimpleDeformableSurface/Surface.h
4069e4aed41b4c26cb6859b70bf8b71781cf1cb1
[]
no_license
PolarisYxh/phantomOmniRos
a621fd1671e85ada8eda0dc9bc00f02fe5579d3d
d745e2466d869777982971383efdb98387e4b038
refs/heads/main
2023-01-13T17:13:41.817751
2020-11-16T08:24:53
2020-11-16T08:24:53
300,486,277
1
0
null
null
null
null
UTF-8
C++
false
false
2,349
h
Surface.h
/***************************************************************************** Copyright (c) 2004 SensAble Technologies, Inc. All rights reserved. OpenHaptics(TM) toolkit. The material embodied in this software and use of this software is subject to the terms and conditions of the clickthrough Development License Agreement. For questions, comments or bug reports, go to forums at: http://dsc.sensable.com Module Name: Surface.h Description: Deformable surface implemented using particle system. *******************************************************************************/ #ifndef Surface_H_ #define Surface_H_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "ParticleSystem.h" class Surface { public: Surface(); virtual ~Surface(); void SetParticleSystem(ParticleSystem *inPs) { ps = inPs; } void ConstructSurface(const int inSurfaceParticles, const double inSurfaceSize); void DrawSurface(void); void DrawSurfaceNormals(void); void InvalidateVertexCache(void); void SetSpecularColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a); void SetAmbientColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a); void SetDiffuseColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a); void SetShininess(GLfloat s); void SetMassProportion(double inMass); double GetMassProportion(void) { return massProportion; } private: ParticleSystem *ps; std::vector<bool> vertexNormalsCached; std::vector<hduVector3Dd> vertexNormals; GLfloat matSpecular[4]; GLfloat matAmbient[4]; GLfloat matDiffuse[4]; GLfloat matShininess[1]; int surfaceParticlesX; int surfaceParticlesZ; double surfaceSizeX; double surfaceSizeZ; float surfaceSpacingX; float surfaceSpacingZ; double massProportion; void CalculateNormal(hduVector3Dd &normal, const hduVector3Dd &v1, const hduVector3Dd &v2, const hduVector3Dd &v3); const hduVector3Dd& GetSurfaceVertexNormal(int i, int k); void CalculateSurfaceVertexNormal(hduVector3Dd &normVertex, int i, int k); Particle *GetSurfaceParticle(int i, int j); const hduVector3Dd& GetSurfacePosition(int i, int j); }; #endif // Surface_H_ /******************************************************************************/
62e056a06f28f6ad51e44f477cc110e28993f204
a866fd05fe85765b7c5e82aa308390aa8e275020
/src/mdb.hpp
67bff4acf4d9b0580a33a1c72f398550730b945b
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
info-infoman/FeedBackCoin
be6b7a31d6a04821fac15d1dbfbbe64018d13f71
d986c293f6a2c11bba00ba001cb3093b22f951f9
refs/heads/master
2019-06-27T19:41:21.145462
2018-06-13T11:34:17
2018-06-13T11:34:17
119,961,827
3
0
null
null
null
null
UTF-8
C++
false
false
17,483
hpp
mdb.hpp
#ifndef _GLIM_MDB_HPP_INCLUDED #define _GLIM_MDB_HPP_INCLUDED /** * A C++ wrapper around MDB (http://www.symas.com/mdb/). * @code Copyright 2012 Kozarezov Artem Aleksandrovich 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. * @endcode * @file */ #include "liblmdb/lmdb.h" #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/serialization/serialization.hpp> #include <boost/noncopyable.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/range/iterator_range.hpp> #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(_WIN64) #include <winsock2.h> #else #include <arpa/inet.h> #endif /* !WIN */ #include "gstring.hpp" namespace glim { struct MdbEx: public std::runtime_error {MdbEx (std::string message): std::runtime_error (message) {}}; template <typename T> inline void mdbSerialize (gstring& bytes, const T& data) { gstring_stream stream (bytes); boost::archive::binary_oarchive oa (stream, boost::archive::no_header); oa << data; } template <typename V> inline void mdbDeserialize (const gstring& bytes, V& data) { gstring_stream stream (const_cast<gstring&> (bytes)); boost::archive::binary_iarchive ia (stream, boost::archive::no_header); ia >> data; } /** uint32_t keys are stored big-endian (network byte order) in order to be compatible with lexicographic ordering. */ template <> inline void mdbSerialize<uint32_t> (gstring& bytes, const uint32_t& ui) { uint32_t nui = htonl (ui); bytes.append ((const char*) &nui, sizeof (uint32_t));} /** Deserialize uint32_t from big-endian (network byte order). */ template <> inline void mdbDeserialize<uint32_t> (const gstring& bytes, uint32_t& ui) { if (bytes.size() != sizeof (uint32_t)) throw MdbEx ("Not uint32_t, wrong number of bytes"); uint32_t nui = * (uint32_t*) bytes.data(); ui = ntohl (nui);} /** If the data is `gstring` then use the data's buffer directly, no copy. */ template <> inline void mdbSerialize<gstring> (gstring& bytes, const gstring& data) { bytes = gstring (0, (void*) data.data(), false, data.length());} /** Deserializing into `gstring` copies the bytes into it, reusing its buffer. */ template <> inline void mdbDeserialize<gstring> (const gstring& bytes, gstring& data) { data.clear() << bytes;} /** * Header-only C++ wrapper around OpenLDAP-MDB.\n * Uses Boost Serialization to pack keys and values (glim::gstring can be used for raw bytes).\n * Allows semi-automatic indexing with triggers.\n * Known issues: http://www.openldap.org/its/index.cgi?findid=7448 */ struct Mdb { std::shared_ptr<MDB_env> _env; MDB_dbi _dbi = 0; typedef std::unique_ptr<MDB_txn, void(*)(MDB_txn*)> Transaction; /** Holds the current key and value of the Iterator. */ struct IteratorEntry { MDB_val _key = {0, 0}, _val = {0, 0}; /** Zero-copy view of the current key bytes. Should *not* be used after the Iterator is changed or destroyed. */ const gstring keyView() const {return gstring (0, _key.mv_data, false, _key.mv_size, true);} // Zero copy. /** Zero-copy view of the current value bytes. Should *not* be used after the Iterator is changed or destroyed. */ const gstring valueView() const {return gstring (0, _val.mv_data, false, _val.mv_size, true);} // Zero copy. /** Deserialize into `key`. */ template <typename T> void getKey (T& key) const {mdbDeserialize (keyView(), key);} /** Deserialize the key into a temporary and return it. */ template <typename T> T getKey() const {T key; getKey (key); return key;} /** Deserialize into `value`. */ template <typename T> void getValue (T& value) const {mdbDeserialize (valueView(), value);} /** Deserialize the value into a temporary and return it. */ template <typename T> T getValue() const {T value; getValue (value); return value;} }; /** Holds the Iterator's unique transaction and cursor, allowing the Iterator to be copied. */ struct IteratorImpl: boost::noncopyable { Mdb* _mdb; Transaction _txn; MDB_cursor* _cur; IteratorImpl (Mdb* mdb, Transaction&& txn, MDB_cursor* cur): _mdb (mdb), _txn (std::move (txn)), _cur (cur) {} ~IteratorImpl() { if (_cur) {::mdb_cursor_close (_cur); _cur = nullptr;} if (_mdb && _txn) {_mdb->commitTransaction (_txn); _mdb = nullptr;} } }; /** Wraps MDB cursor and cursor's transaction. */ struct Iterator: public boost::iterator_facade<Iterator, IteratorEntry, boost::bidirectional_traversal_tag> { std::shared_ptr<IteratorImpl> _impl; // Iterator might be copied around, thus we keep the unique things in IteratorImpl. IteratorEntry _entry; bool _stayInKey = false; Iterator (const Iterator&) = default; Iterator (Iterator&&) = default; /** Iterate from the beginning or the end of the database. * @param position can be MDB_FIRST or MDB_LAST */ Iterator (Mdb* mdb, int position = 0): _stayInKey (false) { Transaction txn (mdb->beginTransaction()); MDB_cursor* cur = nullptr; int rc = ::mdb_cursor_open (txn.get(), mdb->_dbi, &cur); if (rc) throw MdbEx ("mdb_cursor_open"); _impl = std::make_shared<IteratorImpl> (mdb, std::move (txn), cur); if (position == ::MDB_FIRST || position == ::MDB_LAST) { rc = ::mdb_cursor_get (cur, &_entry._key, &_entry._val, (MDB_cursor_op) position); if (rc) throw MdbEx ("mdb_cursor_get"); } } /** Iterate over `key` values. * @param stayInKey if `false` then iterator can go farther than the `key`. */ Iterator (Mdb* mdb, const gstring& key, bool stayInKey = true): _stayInKey (stayInKey) { Transaction txn (mdb->beginTransaction()); MDB_cursor* cur = nullptr; int rc = ::mdb_cursor_open (txn.get(), mdb->_dbi, &cur); if (rc) throw MdbEx ("mdb_cursor_open"); _impl = std::make_shared<IteratorImpl> (mdb, std::move (txn), cur); _entry._key = {key.size(), (void*) key.data()}; rc = ::mdb_cursor_get (cur, &_entry._key, &_entry._val, ::MDB_SET_KEY); if (rc == MDB_NOTFOUND) {_entry._key = {0, 0}; _entry._val = {0, 0};} else if (rc) throw MdbEx ("mdb_cursor_get"); } struct EndIteratorFlag {}; /** The "end" iterator does not open an MDB transaction (this is essential for having a pair of iterators without a deadlock). */ Iterator (EndIteratorFlag): _stayInKey (false) {} /** True if the iterator isn't pointing anywhere. */ bool end() const {return _entry._key.mv_size == 0;} bool equal (const Iterator& other) const { IteratorImpl* impl = _impl.get(); if (mdb_cmp (impl->_txn.get(), impl->_mdb->_dbi, &_entry._key, &other._entry._key)) return false; if (mdb_dcmp (impl->_txn.get(), impl->_mdb->_dbi, &_entry._val, &other._entry._val)) return false; return true; } IteratorEntry& dereference() const { // NB: Boost iterator_facade expects the `dereference` to be a `const` method. // I guess Iterator is not modified, so the `dereference` is `const`, even though the Entry can be modified. return const_cast<IteratorEntry&> (_entry);} void increment() { int rc = ::mdb_cursor_get (_impl->_cur, &_entry._key, &_entry._val, _stayInKey ? ::MDB_NEXT_DUP : ::MDB_NEXT); if (rc) {_entry._key = {0,0}; _entry._val = {0,0};} } void decrement() { int rc = ::mdb_cursor_get (_impl->_cur, &_entry._key, &_entry._val, _stayInKey ? ::MDB_PREV_DUP : ::MDB_PREV); if (rc) {_entry._key = {0,0}; _entry._val = {0,0};} } }; Iterator begin() {return Iterator (this, ::MDB_FIRST);} const Iterator end() {return Iterator (Iterator::EndIteratorFlag());} /** Position the cursor at the first `key` record.\n * The iterator increment will use `MDB_NEXT_DUP`, staying withing the `key`.\n * See also the `all` method. */ template <typename K> Iterator values (const K& key) { char kbuf[64]; // Allow up to 64 bytes to be serialized without heap allocations. gstring kbytes (sizeof (kbuf), kbuf, false, 0); mdbSerialize (kbytes, key); return Iterator (this, kbytes); } /** Range over the `key` values.\n * See also the `all` method. */ template <typename K> boost::iterator_range<Iterator> valuesRange (const K& key) {return boost::iterator_range<Iterator> (values (key), end());} struct Trigger { virtual gstring getTriggerName() const {return C2GSTRING ("defaultTriggerName");}; virtual void add (Mdb& mdb, void* key, gstring& kbytes, void* value, gstring& vbytes, Transaction& txn) = 0; virtual void erase (Mdb& mdb, void* key, gstring& kbytes, Transaction& txn) = 0; virtual void eraseKV (Mdb& mdb, void* key, gstring& kbytes, void* value, gstring& vbytes, Transaction& txn) = 0; }; std::map<gstring, std::shared_ptr<Trigger>> _triggers; void setTrigger (std::shared_ptr<Trigger> trigger) { _triggers[trigger->getTriggerName()] = trigger; } /** `flags` can be `MDB_RDONLY` */ Transaction beginTransaction (unsigned flags = 0) { MDB_txn* txn = 0; int rc = ::mdb_txn_begin (_env.get(), nullptr, flags, &txn); if (rc) throw MdbEx (std::string ("mdb_txn_begin: ") + ::strerror (rc)); return Transaction (txn, ::mdb_txn_abort); } void commitTransaction (Transaction& txn) { int rc = ::mdb_txn_commit (txn.get()); txn.release(); // Must prevent `mdb_txn_abort` from happening (even if rc != 0). if (rc) throw MdbEx (std::string ("mdb_txn_commit: ") + ::strerror (rc)); } virtual unsigned envFlags (uint8_t sync) { unsigned flags = MDB_NOSUBDIR; if (sync < 1) flags |= MDB_NOSYNC; else if (sync < 2) flags |= MDB_NOMETASYNC; return flags; } /** Used before `mdb_env_open`. By default sets the number of database to 32. */ virtual void envConf (MDB_env* env) { int rc = ::mdb_env_set_maxdbs (env, 32); if (rc) throw MdbEx (std::string ("envConf: ") + ::strerror (rc)); } virtual void dbFlags (unsigned& flags) {} protected: void open (const char* dbName, bool dup) { auto txn = beginTransaction(); unsigned flags = MDB_CREATE; if (dup) flags |= MDB_DUPSORT; dbFlags (flags); int rc = ::mdb_open (txn.get(), dbName, flags, &_dbi); if (rc) throw MdbEx (std::string ("mdb_open (") + dbName + "): " + ::strerror (rc)); commitTransaction (txn); } public: /** Opens MDB environment and MDB database. */ Mdb (const char* path, size_t maxSizeMb = 1024, const char* dbName = "main", uint8_t sync = 0, bool dup = true, mode_t mode = 0660) { MDB_env* env = 0; int rc = ::mdb_env_create (&env); if (rc) throw MdbEx (std::string ("mdb_env_create: ") + ::strerror (rc)); _env.reset (env, ::mdb_env_close); rc = ::mdb_env_set_mapsize (env, maxSizeMb * 1024 * 1024); if (rc) throw MdbEx (std::string ("mdb_env_set_mapsize: ") + ::strerror (rc)); envConf (env); rc = ::mdb_env_open (env, path, envFlags (sync), mode); _dbi = 0; open (dbName, dup); } /** Opens MDB database in the provided environment. */ Mdb (std::shared_ptr<MDB_env> env, const char* dbName, bool dup = true): _env (env), _dbi (0) { open (dbName, dup); } template <typename K, typename V> void add (const K& key, const V& value, Transaction& txn) { char kbuf[64]; // Allow up to 64 bytes to be serialized without heap allocations. gstring kbytes (sizeof (kbuf), kbuf, false, 0); mdbSerialize (kbytes, key); MDB_val mkey = {kbytes.size(), (void*) kbytes.data()}; char vbuf[64]; // Allow up to 64 bytes to be serialized without heap allocations. gstring vbytes (sizeof (vbuf), vbuf, false, 0); mdbSerialize (vbytes, value); MDB_val mvalue = {vbytes.size(), (void*) vbytes.data()}; for (auto& trigger: _triggers) trigger.second->add (*this, (void*) &key, kbytes, (void*) &value, vbytes, txn); int rc = ::mdb_put (txn.get(), _dbi, &mkey, &mvalue, 0); if (rc) throw MdbEx (std::string ("mdb_put: ") + ::strerror (rc)); } template <typename K, typename V> void add (const K& key, const V& value) { Transaction txn (beginTransaction()); add (key, value, txn); commitTransaction (txn); } template <typename K, typename V> bool first (const K& key, V& value, Transaction& txn) { char kbuf[64]; // Allow up to 64 bytes to be serialized without heap allocations. gstring kbytes (sizeof (kbuf), kbuf, false, 0); mdbSerialize (kbytes, key); MDB_val mkey = {kbytes.size(), (void*) kbytes.data()}; MDB_val mvalue; int rc = ::mdb_get (txn.get(), _dbi, &mkey, &mvalue); if (rc == MDB_NOTFOUND) return false; if (rc) throw MdbEx (std::string ("mdb_get: ") + ::strerror (rc)); gstring vstr (0, mvalue.mv_data, false, mvalue.mv_size); mdbDeserialize (vstr, value); return true; } template <typename K, typename V> bool first (const K& key, V& value) { Transaction txn (beginTransaction (MDB_RDONLY)); bool rb = first (key, value, txn); commitTransaction (txn); return rb; } /** Iterate over `key` values until `visitor` returns `false`. Return the number of values visited. */ template <typename K, typename V> int32_t all (const K& key, std::function<bool(const V&)> visitor, Transaction& txn) { char kbuf[64]; // Allow up to 64 bytes to be serialized without heap allocations. gstring kbytes (sizeof (kbuf), kbuf, false, 0); mdbSerialize (kbytes, key); MDB_val mkey = {kbytes.size(), (void*) kbytes.data()}; MDB_cursor* cur = 0; int rc = ::mdb_cursor_open (txn.get(), _dbi, &cur); if (rc) throw MdbEx (std::string ("mdb_cursor_open: ") + ::strerror (rc)); std::unique_ptr<MDB_cursor, void(*)(MDB_cursor*)> curHolder (cur, ::mdb_cursor_close); MDB_val mval = {0, 0}; rc = ::mdb_cursor_get (cur, &mkey, &mval, ::MDB_SET_KEY); if (rc == MDB_NOTFOUND) return 0; if (rc) throw MdbEx (std::string ("mdb_cursor_get: ") + ::strerror (rc)); V value; gstring vstr (0, mval.mv_data, false, mval.mv_size); mdbDeserialize (vstr, value); bool goOn = visitor (value); int32_t count = 1; while (goOn) { rc = ::mdb_cursor_get (cur, &mkey, &mval, ::MDB_NEXT_DUP); if (rc == MDB_NOTFOUND) return count; if (rc) throw MdbEx (std::string ("mdb_cursor_get: ") + ::strerror (rc)); gstring vstr (0, mval.mv_data, false, mval.mv_size); mdbDeserialize (vstr, value); goOn = visitor (value); ++count; } return count; } /** Iterate over `key` values until `visitor` returns `false`. Return the number of values visited. */ template <typename K, typename V> int32_t all (const K& key, std::function<bool(const V&)> visitor) { Transaction txn (beginTransaction (MDB_RDONLY)); int32_t count = all (key, visitor, txn); commitTransaction (txn); return count; } template <typename K, typename V> bool eraseKV (const K& key, const V& value, Transaction& txn) { char kbuf[64]; // Allow up to 64 bytes to be serialized without heap allocations. gstring kbytes (sizeof (kbuf), kbuf, false, 0); mdbSerialize (kbytes, key); if (kbytes.empty()) throw MdbEx ("eraseKV: key is empty"); MDB_val mkey = {kbytes.size(), (void*) kbytes.data()}; char vbuf[64]; // Allow up to 64 bytes to be serialized without heap allocations. gstring vbytes (sizeof (vbuf), vbuf, false, 0); mdbSerialize (vbytes, value); MDB_val mvalue = {vbytes.size(), (void*) vbytes.data()}; for (auto& trigger: _triggers) trigger.second->eraseKV (*this, (void*) &key, kbytes, (void*) &value, vbytes, txn); int rc = ::mdb_del (txn.get(), _dbi, &mkey, &mvalue); if (rc == MDB_NOTFOUND) return false; if (rc) throw MdbEx (std::string ("mdb_del: ") + ::strerror (rc)); return true; } template <typename K, typename V> bool eraseKV (const K& key, const V& value) { Transaction txn (beginTransaction()); bool rb = eraseKV (key, value, txn); commitTransaction (txn); return rb; } /** Erase all values of the `key`. */ template <typename K> bool erase (const K& key, Transaction& txn) { char kbuf[64]; // Allow up to 64 bytes to be serialized without heap allocations. gstring kbytes (sizeof (kbuf), kbuf, false, 0); mdbSerialize (kbytes, key); if (kbytes.empty()) throw MdbEx ("erase: key is empty"); MDB_val mkey = {kbytes.size(), (void*) kbytes.data()}; for (auto& trigger: _triggers) trigger.second->erase (*this, (void*) &key, kbytes, txn); int rc = ::mdb_del (txn.get(), _dbi, &mkey, nullptr); if (rc == MDB_NOTFOUND) return false; if (rc) throw MdbEx (std::string ("mdb_del: ") + ::strerror (rc)); return true; } /** Erase all values of the `key`. */ template <typename K> bool erase (const K& key) { Transaction txn (beginTransaction()); bool rb = erase (key, txn); commitTransaction (txn); return rb; } virtual ~Mdb() { _triggers.clear(); // Destroy triggers before closing the database. if (_dbi) {::mdb_close (_env.get(), _dbi); _dbi = 0;} } }; } // namespace glim #endif // _GLIM_MDB_HPP_INCLUDED
08f58cd5e00912a077db44123d007bb18228704a
7aab5715b0a8e846914dfa24dcc5b994e92e947f
/vsProject/paint3D/RenderableObject.cpp
6c151c664828250cf5c04ed8c4a8197b24406bfc
[]
no_license
AmesianX/Paint3D-QT
24e0fa193d83ee226d8eef814a402c97cafb7a5d
52de149f7d9cbc051780c8dde060df1603b1e435
refs/heads/master
2021-02-07T18:20:39.472451
2019-06-28T05:42:12
2019-06-28T05:42:12
null
0
0
null
null
null
null
GB18030
C++
false
false
3,275
cpp
RenderableObject.cpp
#include "StdAfx.h" #include "RenderableObject.h" #include "Paint3DFrame.h" unsigned RenderableObject::currNewObjectID = 1; QHash<QString,int> RenderableObject::nameMap; RenderableObject::RenderableObject(void): isObjSelected(false), isObjVisible(true), localBBox(QVector3D(0,0,0),QVector3D(0,0,0)), alphaForAppearance(0.5f) { objectID = currNewObjectID++; setName(QString("Object") + QString::number(objectID)); } RenderableObject::~RenderableObject(void) { nameMap.remove(this->name); } float RenderableObject::getApproSize() { QVector3D wMin = transform.getTransformMatrix() * localBBox.pMin; QVector3D wMax = transform.getTransformMatrix() * localBBox.pMax; return (wMax - wMin).length(); } void RenderableObject::setTransform( const ObjectTransform& trans ) { transform =trans; } void RenderableObject::setName( const QString& newName ) { QString finalName = newName; QHash<QString,int>::iterator i = nameMap.find(newName); if (i != nameMap.end() && name != newName) { // 新名字与其他物体的名字冲突 while(nameMap.contains(finalName)) { finalName = finalName + QString("_1"); } } nameMap.remove(this->name); this->name = finalName; nameMap.insert(finalName, objectID); } void ObjectTransform::updateTransformMatrix() { m_rotMatrix.setToIdentity(); m_rotMatrix.rotate(m_rotation); m_transformMatrix.setToIdentity(); m_transformMatrix.translate(m_translation); m_transformMatrix *= m_rotMatrix; m_norTransformMatrix = m_transformMatrix; m_transRotMatrix = m_transformMatrix; m_transformMatrix.scale(m_scale); m_norTransformMatrix.scale(1 / m_scale.x(), 1 / m_scale.y(), 1 / m_scale.z()); m_invTransformMatrix.setToIdentity(); m_invTransformMatrix.scale(1 / m_scale.x(), 1 / m_scale.y(), 1 / m_scale.z()); QMatrix4x4 transposeRot = m_rotMatrix; m_invTransformMatrix *= transposeRot.transposed(); m_invTransformMatrix.translate(-m_translation); // 还要更新场景的GeometryImage Paint3DFrame::getInstance()->scene->updateGeometryImage(); } QDataStream& operator<<(QDataStream& out, const QSharedPointer<RenderableObject>&pObj) { out << pObj->type; out << pObj->name; out << pObj->transform; if (pObj->type == RenderableObject::OBJ_MESH) { Mesh* mesh = (Mesh*)pObj.data(); out << *mesh; } else if (pObj->type == RenderableObject::OBJ_PICKER_OBJECT) { PlanePicker* picker = (PlanePicker*)pObj.data(); out << *picker; } return out; } QDataStream& operator>>(QDataStream& in, QSharedPointer<RenderableObject>&pObj) { quint32 type; QString name; ObjectTransform trans; in >> type; in >> name; in >> trans; if (type == RenderableObject::OBJ_MESH) { QSharedPointer<Mesh> pM(new Mesh); pObj = pM; in >> *pM; } else if (type == RenderableObject::OBJ_PICKER_OBJECT) { QSharedPointer<PlanePicker> pM(new PlanePicker); pObj = pM; in >> *pM; } pObj->setName(name); pObj->transform = trans;; return in; } QDataStream& operator<<(QDataStream& out, const ObjectTransform& trans) { out << trans.m_translation << trans.m_rotation << trans.m_scale; return out; } QDataStream& operator>>(QDataStream& in , ObjectTransform& trans) { in >> trans.m_translation >> trans.m_rotation >> trans.m_scale; trans.updateTransformMatrix(); return in; }
f82739749fff5d0c1b69d8575a5f3ba9ffecc5aa
eb8d36a89dbaeffeedd8584d970aa2b33a8b2c6e
/CQ-0080/variance/variance.cpp
3727622cb4868f4ea5e1be5737857976f1671d4e
[]
no_license
mcfx0/CQ-NOIP-2021
fe3f3a88c8b0cd594eb05b0ea71bfa2505818919
774d04aab2955fc4d8e833deabe43e91b79632c2
refs/heads/main
2023-09-05T12:41:42.711401
2021-11-20T08:59:40
2021-11-20T08:59:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,036
cpp
variance.cpp
#include <ctime> #include <cstdio> #include <algorithm> #define ll long long using namespace std; ll Sum,QSum,Ans=1e18; int n,arr[10005]; bool cho[10005]; void dfs(int t) { if(QSum*n-Sum*Sum<Ans) { Ans=QSum*n-Sum*Sum; // for(int i=1;i<=n;i++) printf("%d ",arr[i]); // puts(""); } if(t>=20) return; if(clock()>=950) { printf("%lld",Ans); exit(0); } for(int i=2;i<n;i++) { if(cho[i]) continue; ll Tmp=arr[i]; ll TmpSum=Sum,TmpQSum=QSum; if(arr[i-1]+arr[i+1]-arr[i]==arr[i]) continue; ll NewSum=Sum-arr[i]-arr[i]+arr[i-1]+arr[i+1],NewQSum=QSum-arr[i]*arr[i]+(arr[i-1]+arr[i+1]-arr[i])*(arr[i-1]+arr[i+1]-arr[i]); if(NewQSum*n-NewSum*NewSum<=Ans+100000) { Sum=NewSum; QSum=NewQSum; arr[i]=arr[i-1]+arr[i+1]-arr[i]; dfs(t+1); arr[i]=Tmp; Sum=TmpSum; QSum=TmpQSum; } } } int main() { freopen("variance.in","r",stdin); freopen("variance.out","w",stdout); scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&arr[i]),Sum+=arr[i],QSum+=arr[i]*arr[i]; dfs(1); printf("%lld",Ans); return 0; }
66638484f0a624bf92a4f9ab43f87e46062f138d
884eff6ef759e342ad226b9404d934b52d5f13e2
/routines.h
ef78326f99a324745cf10a2b387d0665417df274
[]
no_license
henhans/IPT_real_axis
a7470e57293ae60d520370308cd4c4c4ea3f3ed4
a969a495a539d5bf00ace57f8a929463fe6532af
refs/heads/master
2020-03-25T07:27:56.317334
2014-07-19T02:52:55
2014-07-19T02:52:55
21,870,604
0
1
null
null
null
null
UTF-8
C++
false
false
2,465
h
routines.h
#include <complex> #include <vector> using namespace std; //======================== CONSTANTS ===============================// const double pi = 3.14159265358979323846; const double e = 2.71; const complex<double> ii = complex<double>(0.0,1.0); //======================= ROUTINES ==================================// double sign(double x); int int_sign(double x); double sqr(double x); int pow(int base, int exp); complex<double> sqr(complex<double> x); /*double abs(double x);*/ /*double abs(complex<double> x);*/ //--- integral ---// double TrapezIntegral(int N, double Y[], double X[]); complex<double> TrapezIntegral(int N, complex<double> Y[], double X[]); double TrapezIntegralMP(int N, double Y[], double X[]); complex<double> TrapezIntegralMP(int N, complex<double> Y[], double X[]); //double TrapezIntegral(std::vector< double > Y, std::vector<double> X); complex<double> TrapezIntegral(std::vector< complex<double> > Y, std::vector<double> X); double EllipticIntegralFirstKind(double x); double SI(double x); complex<double> EllipticIntegralFirstKind(complex<double> x); double interpl(int N, double* Y, double* X, double x); complex<double> Hilbert(int N, complex<double> z, double w[], double d[]); void KramarsKronig(int N, double w[], double imf[], double ref[]); //======================== IO =======================================// void PrintFunc(const char* FileName, int N, int M, double** Y, double* X); void PrintFunc(const char* FileName, int N, complex<double>* Y, double* X); void PrintFunc(const char* FileName, int N, complex<double>* Y); void PrintFunc(const char* FileName, int N, double* Y); void PrintFunc(const char* FileName, int N, double* Y, double* X); void PrintFunc(const char* FileName, std::vector< complex<double> > Y, std::vector<double> X); void PrintFunc3D(const char* FileName, int N, complex<double>** Y, double* X); void ReadFunc(const char* FileName, int &N, int &M, double** &X); //===================vectors and matrices=============================// void MultiplyByMatrix(int N, double* v, double** m); void CreateRotationMatrix(double** m, int N, double angle, int* plane); void RotateVector(int N, double* v, double angle, int* plane); void RotateVector2D(double* v, double angle); void InvertMatrix(int N, double** A, double** invA, double &det); //==================== Init DOSes and Fermi ========================// double FermiFunction(double x, double T); double SemiCircleDOS(double x );
d56766408ff66ef59e79bdc2ce71fcc97fe55360
b46f65355d9a79e8d7ea7bd473a7d559ee601a1b
/src/test/test_util.hpp
41158af83c854700a993b853a76ca26763f92219
[]
no_license
ekuiter/bsdl
8c50eba05f43a789fc58c2e92aa3cd0a6d62d52b
1f9d9cf5f1f55dab3480023456e244001a6a9eae
refs/heads/master
2020-04-05T15:16:29.337225
2018-10-16T19:40:46
2018-10-16T19:40:46
68,543,822
0
0
null
null
null
null
UTF-8
C++
false
false
787
hpp
test_util.hpp
#pragma once #include <boost/test/unit_test.hpp> #include "fixtures.hpp" #undef timeout #define MOCK_THROW(return_type, fn, signature) \ return_type fn signature override { \ throw mock_error(#fn); \ } #define MOCK_EMPTY(return_type, fn, signature) \ return_type fn signature override {} #define LONG_RUNNING_TEST_SUITE(type, ...) \ BOOST_##type##_TEST_SUITE(long_running, __VA_ARGS__ * utf::label("long_running")) namespace utf = boost::unit_test; namespace tt = boost::test_tools; string executable_file(); string resource_file(const string& resource); vector<string> test_arguments(); void check_file_type(const string& file_name, const string& file_type); default_random_engine& random_engine();
1e92e62d19e81ec146345d9ae3a93c686eddf4d9
898aa4f8b4d0892919502c42b1e48137c812d866
/battle.h
2516946cdfe3df4a472f6800e24cc7c8db1971c1
[]
no_license
jlagun/jnp_zad4
62e77680b62222fa43702342901cee03dede2f9b
f52cc657623c8eaa317f9589c1ac43eb410c04c9
refs/heads/master
2020-04-08T23:56:59.795633
2018-12-04T17:55:31
2018-12-04T17:55:31
159,846,557
0
0
null
null
null
null
UTF-8
C++
false
false
2,800
h
battle.h
#pragma once #include <array> #include <algorithm> #include <tuple> #include "imperialfleet.h" #include "rebelfleet.h" template<typename T, T t0, T t1, typename... S> class SpaceBattle { static_assert(std::is_arithmetic<T>::value, "T should be arithmetic"); static_assert(t0 <= t1 && t0 >= 0, "invalid start or end time"); static_assert(((is_rebelship<S>::value || is_imperialship<S>::value) && ...), "S should contain only spaceship types"); template<T i = 0, T... vals> static constexpr auto calcSquares() { if constexpr (i != 0 && i > t1 / i) return std::array<T, sizeof...(vals)> {{vals...}}; else return calcSquares<i + 1, vals..., i * i>(); } static constexpr auto attackMoments = calcSquares(); static constexpr size_t shipsNum = sizeof...(S); mutable size_t rebelAlive, imperialAlive; T curTime; std::tuple<S&...> ships; template<typename S1, typename S2> void battleHelper(S1 &a, S2 &b) { if constexpr (is_imperialship<S1>::value && is_rebelship<S2>::value) if (a.getShield() > 0 && b.getShield() > 0) attack(a, b); } // iteruje sie po kazdej parze statkow i przeprowadza bitwe miedzy nimi template<size_t id1 = 0, size_t id2 = 0> void battle() { if constexpr (id1 < shipsNum) battleHelper(std::get<id1>(ships), std::get<id2>(ships)); if constexpr (id1 + 1 < shipsNum) battle<id1 + 1, id2>(); else if constexpr (id2 + 1 < shipsNum) battle<0, id2 + 1>(); } template<typename SH> void countHelper(const SH& ship, size_t &rebelCnt, size_t &imperialCnt) const { if constexpr (is_rebelship<SH>::value) rebelCnt += ship.getShield() > 0; else if constexpr (is_imperialship<SH>::value) imperialCnt += ship.getShield() > 0; } // liczy liczbe statkow rebelii i imperium template<size_t id = 0> std::pair<size_t, size_t> count(size_t rebelCnt = 0, size_t imperialCnt = 0) const { if constexpr (id < shipsNum) countHelper(std::get<id>(ships), rebelCnt, imperialCnt); if constexpr (id + 1 < shipsNum) return count<id + 1>(rebelCnt, imperialCnt); return {rebelCnt, imperialCnt}; } void updateCounts() const { std::tie(rebelAlive, imperialAlive) = count(); } public: SpaceBattle(S&... spaceships) : curTime(t0), ships(spaceships...) { updateCounts(); } size_t countRebelFleet() const { updateCounts(); return rebelAlive; } size_t countImperialFleet() const { updateCounts(); return imperialAlive; } void tick(T timeStep) { updateCounts(); if (imperialAlive == 0) { puts(rebelAlive == 0 ? "DRAW" : "REBELLION WON"); return; } else if (rebelAlive == 0) { puts("IMPERIUM WON"); return; } if (std::binary_search(std::begin(attackMoments), std::end(attackMoments), curTime)) battle(); curTime = (curTime + timeStep) % (t1 + 1); } };
eb53afa11391bfe5e29adfeb93e56a6f16e9517a
27b59918321718e333c5ae2643c9cb3947036f3d
/MeOpenGLScratchPad2/DebugTools/Menu/DebugMenu.h
2af8824734cb92639677715605953f3137f9596c
[]
no_license
ansem571/Game-Engine
5436fe865726ec376c676b7a9ee0294328195192
d19bae19e6dcdefa3cfa699e5735b454ac71c083
refs/heads/master
2021-03-12T21:48:19.981998
2015-08-26T15:13:51
2015-08-26T15:13:51
41,431,400
0
0
null
null
null
null
UTF-8
C++
false
false
1,182
h
DebugMenu.h
#ifndef DEBUG_MENU_H #define DEBUG_MENU_H #include <DebugTools\Menu\Infos\WatchInfo.h> #include <DebugTools\Sliders\SliderInfo.h> #include <DebugTools\CheckBox\CheckBoxInfo.h> #include <Qt\qlist.h> #include <Qt\qtabwidget.h> class QVBoxLayout; class DebugMenu { static DebugMenu instance; DebugMenu() {} DebugMenu(const DebugMenu&); DebugMenu& operator=(const DebugMenu&); public: static DebugMenu& getInstance() { return instance;} QList<WatchInfo> watchInfos; QList<SliderInfo> sliderInfos; QList<CheckBoxInfo> checkBoxInfos; #if DEBUGMENU_ON void watch(const char* text, const float& value); QVBoxLayout* theLayout; QVBoxLayout* otherLayout; bool initialize(); void update(); void addSlider(const char* text, float min, float max, float val); void addCheckBox(const char* text, QWidget* widg); #else void watch(const char* text, const float& value) {text; value;} QVBoxLayout* theLayout; bool initialize(){return true;} void update(){} void addSlider(const char* text, float min, float max, float val) {text; min; max; val;} void addCheckBox(const char* text, QWidget* widg) {text; widg;} #endif }; #define debugMenu DebugMenu::getInstance() #endif
9a218ebc66c1656a8a1b3565c0db97a03f4f6a8b
3a70e041b704a9a2a992be5b3787e2b7110262c9
/MiniJumball/Jumball/JumballEngine/JumballEngine.cpp
457034ed6e0c201376f7f282e24dd3079d5ef8fb
[]
no_license
lixu1918/chinesecheckers
bb7a1dfea6883deee4713074f81aee48712df356
d1b44479df4faa1bf31872420734f03cbdccf9d6
refs/heads/master
2021-01-15T16:57:47.255605
2015-05-27T10:28:33
2015-05-27T10:28:33
35,824,987
0
0
null
null
null
null
UTF-8
C++
false
false
10,409
cpp
JumballEngine.cpp
// // JumballEngine.cpp // Jumball // // Created by Li Xu on 10/6/12. // Copyright (c) 2012 Li Xu. All rights reserved. // #include "JumballEngine.h" #include "JumballData.h" #include "ModifiedSquareDistance.h" #include <assert.h> #include <vector> const short* kJBEModifiedSquareDistanceTables[kJBECornerMax] = {kJBEModifiedSquareDistanceToSouth, kJBEModifiedSquareDistanceToSouthEast, kJBEModifiedSquareDistanceToNorthEast, kJBEModifiedSquareDistanceToNorth, kJBEModifiedSquareDistanceToNorthWest, kJBEModifiedSquareDistanceToSouthWest}; const short* kJBEMiniModifiedSquareDistanceTables[kJBECornerMax] = {kJBEMiniModifiedSquareDistanceToSouth, kJBEMiniModifiedSquareDistanceToSouthEast, kJBEMiniModifiedSquareDistanceToNorthEast, kJBEMiniModifiedSquareDistanceToNorth, kJBEMiniModifiedSquareDistanceToNorthWest, kJBEMiniModifiedSquareDistanceToSouthWest}; const short* kJBESquareDistanceTables[kJBECornerMax] = {kJBESquareDistanceToSouth, kJBESquareDistanceToSouthEast, kJBESquareDistanceToNorthEast, kJBESquareDistanceToNorth, kJBESquareDistanceToNorthWest, kJBESquareDistanceToSouthWest}; const short* kJBEMiniSquareDistanceTables[kJBECornerMax] = {kJBEMiniSquareDistanceToSouth, kJBEMiniSquareDistanceToSouthEast, kJBEMiniSquareDistanceToNorthEast, kJBEMiniSquareDistanceToNorth, kJBEMiniSquareDistanceToNorthWest, kJBEMiniSquareDistanceToSouthWest}; // 名称不能随意改动,即使是要改大小写或者加空格,请用户在用户代码中重新定义并设计变量 const char* kJBECornerName[kJBECornerMax] = {"South", "SouthEast", "NorthEast", "North", "NorthWest", "SouthWest"}; const int kJBEPieceCount = 10; const int kJBEUnitStep[kJBEDirectionMax] = {2, -31, -33, -2, 31, 33}; const char kJBECornerCharacter[kJBECornerMax] = {'A', 'B', 'C', 'D', 'E', 'F'}; const short kJBEHomeCornerIndex[kJBECornerMax] = {783, 667, 411, 271, 387, 643}; const short kJBEMiniHomeCornerIndex[kJBECornerMax] = {719, 632, 440, 335, 422, 614}; const short kJBESouthPieceId[kJBEPieceCount] = {783, 750, 752, 717, 719, 721, 684, 686, 688, 690}; const short kJBESouthEastPieceId[kJBEPieceCount] = {667, 665, 634, 663, 632, 601, 661, 630, 599, 568}; const short kJBENorthEastPieceId[kJBEPieceCount] = {411, 442, 409, 473, 440, 407, 504, 471, 438, 405}; const short kJBENorthPieceId[kJBEPieceCount] = {271, 302, 304, 333, 335, 337, 364, 366, 368, 370}; const short kJBENorthWestPieceId[kJBEPieceCount] = {387, 389, 420, 391, 422, 453, 393, 424, 455, 486}; const short kJBESouthWestPieceId[kJBEPieceCount] = {643, 612, 645, 581, 614, 647, 550, 583, 616, 649}; const short* kJBEPieceIdTables[kJBECornerMax] = {kJBESouthPieceId, kJBESouthEastPieceId, kJBENorthEastPieceId, kJBENorthPieceId, kJBENorthWestPieceId, kJBESouthWestPieceId}; const short kJBEMiniSouthPieceId[kJBEPieceCount] = {719, 686, 688, 653, 655, 657, 620, 622, 624, 626}; const short kJBEMiniSouthEastPieceId[kJBEPieceCount] = {632, 630, 599, 628, 597, 566, 626, 595, 564, 533}; const short kJBEMiniNorthEastPieceId[kJBEPieceCount] = {440, 471, 438, 502, 469, 436, 533, 500, 467, 434}; const short kJBEMiniNorthPieceId[kJBEPieceCount] = {335, 368, 366, 401, 399, 397, 434, 432, 430, 428}; const short kJBEMiniNorthWestPieceId[kJBEPieceCount] = {422, 455, 424, 488, 457, 426, 521, 490, 459, 428}; const short kJBEMiniSouthWestPieceId[kJBEPieceCount] = {614, 583, 616, 552, 585, 618, 521, 554, 587, 620}; const short* kJBEMiniPieceIdTables[kJBECornerMax] = {kJBEMiniSouthPieceId, kJBEMiniSouthEastPieceId, kJBEMiniNorthEastPieceId, kJBEMiniNorthPieceId, kJBEMiniNorthWestPieceId, kJBEMiniSouthWestPieceId}; void JBEInitCorner(JumballBoard board, JumballCorner corner, const bool mini) { assert(board); assert(corner < kJBECornerMax); const char character = kJBECornerCharacter[corner]; const short* indexes = NULL; if (!mini) indexes = kJBEPieceIdTables[corner]; else indexes = kJBEMiniPieceIdTables[corner]; for (int i = 0; i < kJBEPieceCount; ++i) { board[indexes[i]] = character; } } bool JBEIndexToRowColumn(short index, int* row, int* column) { assert(row); assert(column); // 不管是大棋盘还是小棋盘,中央位置的索引都是 527 const short center = 527; const short row_base = center / 32; const short column_base = center % 32; if (0 <= index && 1024 > index) { //*row = row_base - index/32; //*column = index%32 - column_base; *row = row_base - (index >> 5); *column = (index & 31) - column_base; return true; } return false; } short JBERowColumnToIndex(int row, int column) { static const short center = 527; if (-15 <= row && 16 >= row && -15 <= column && 16 >= column) { short offset = ((- row) << 5) + column; return offset + center; } return -1; } JumballDirection JBEDirectionByRowColumn(int from_row, int from_column, int to_row, int to_column) { JumballDirection direction = kJBEDirectionMax; // 求斜率 if (from_row != to_row) { int delta_column = to_column - from_column; int delta_row = to_row - from_row; if (delta_column == delta_row) { // 东北 西南方向 if (to_row > from_row) { direction = kJBEDirectionNorthEast; } else { direction = kJBEDirectionSouthWest; } } else if (delta_column == -delta_row) { // 西北 东南方向 if (to_row > from_row) { direction = kJBEDirectionNorthWest; } else { direction = kJBEDirectionSouthEast; } } } else { // 在同一水平位置 if (to_column > from_column) { direction = kJBEDirectionEast; } else if (to_column < from_column) { direction = kJBEDirectionWest; } } return direction; } bool JBEOneStepBetween(const JumballBoard board, short from, short to, JumballRule rule, const bool mini) { assert(0 <= from && 1024 > from); assert(0 <= to && 1024 > to); // to处有棋子 if (board[to]) return false; const char* bool_board; if (!mini) bool_board = kJBEBoolBoard; else bool_board = kJBEMiniBoolBoard; // 规则检查 short delta = to - from; for (int i = 0; i < kJBEDirectionMax; ++i) { int unit_step = kJBEUnitStep[i]; int two_unit_step = unit_step + unit_step; if (rule & kJBEScroll && delta == unit_step) { if (bool_board[to]) return true; } else if (rule & kJBEShortJump && delta == two_unit_step) { short bridge = from + unit_step; if (board[bridge] && bool_board[bridge] && bool_board[to]) { return true; } } else if (rule & kJBELongJump && delta == two_unit_step + two_unit_step) { short bridge = from + two_unit_step; if (board[bridge] && !board[bridge - unit_step] && !board[bridge + unit_step] && bool_board[bridge] && bool_board[to]) { return true; } } else if (rule & kJBELongLongJump && delta == ((two_unit_step + unit_step) << 1 )/* 6 unit_step */) { short bridge = from + two_unit_step + unit_step; if (board[bridge] && !board[bridge - unit_step] && !board[bridge + unit_step] && !board[bridge - two_unit_step] && !board[bridge + two_unit_step] && bool_board[bridge] && bool_board[to] ) { return true; } } } return false; } int JBEMinSumSquareDistance(bool mini) { static int sum = 0; static int sum_mini = 0; if (sum == 0 && !mini) { // 南到南 const short* indexes = kJBEPieceIdTables[kJBECornerSouth]; for (int i = 0; i < kJBEPieceCount; ++i) { short index = indexes[i]; //sum += kJBESquareDistanceToSouth[index]; sum += kJBEModifiedSquareDistanceToSouth[index]; } } if (sum_mini == 0 && mini) { // 南到南 const short* indexes = kJBEMiniPieceIdTables[kJBECornerSouth]; for (int i = 0; i < kJBEPieceCount; ++i) { short index = indexes[i]; //sum_mini += kJBEMiniSquareDistanceToSouth[index]; sum_mini += kJBEMiniModifiedSquareDistanceToSouth[index]; } } if (mini) return sum_mini; else return sum; } int JBEMaxSumSquareDistance(bool mini) { static int sum = 0; static int sum_mini = 0; if (sum == 0 && !mini) { // 南到北 const short* indexes = kJBEPieceIdTables[kJBECornerSouth]; for (int i = 0; i < kJBEPieceCount; ++i) { short index = indexes[i]; //sum += kJBESquareDistanceToNorth[index]; sum += kJBEModifiedSquareDistanceToNorth[index]; } } if (sum_mini == 0 && mini) { // 南到北 const short* indexes = kJBEMiniPieceIdTables[kJBECornerSouth]; for (int i = 0; i < kJBEPieceCount; ++i) { short index = indexes[i]; //sum += kJBEMiniSquareDistanceToNorth[index]; sum += kJBEMiniModifiedSquareDistanceToNorth[index]; } } if (mini) return sum_mini; else return sum; } int JBESumSquareDistance(JumballCorner to_coner, short *indexes, int piece_count, bool mini) { int sum = 0; const short* square_distances = NULL; if (mini) //square_distances = kJBEMiniSquareDistanceTables[to_coner]; square_distances = kJBEMiniModifiedSquareDistanceTables[to_coner]; else //square_distances = kJBESquareDistanceTables[to_coner]; square_distances = kJBEModifiedSquareDistanceTables[to_coner]; for (int i = 0; i < piece_count; ++i) { sum += square_distances[indexes[i]]; } return sum; }
04893f09064ff73fc91ff5aac2836441ab2118e6
0567c3f864c268e91c44bf68f7f9468893efc7e7
/gasDetector/gasDetector.ino
75c149c58e0b3c57986acb0d067bb359c67c24f7
[]
no_license
dancps/EUII_DetectorDeGas
a0d2029955eedd1e97f2361e4047a2a6eb5fb297
5c6cebc26d7f5c4bc50d33dd686ca32ed621cf86
refs/heads/master
2020-05-09T19:07:34.963382
2019-04-14T21:12:52
2019-04-14T21:12:52
181,367,685
0
0
null
null
null
null
UTF-8
C++
false
false
2,476
ino
gasDetector.ino
#define MQ_analog A2 #define MQ_dig 7 #include <LiquidCrystal_I2C.h> int valor_analog; int valor_dig; /* * SDA = A4 * SCL = A5 * * * */ LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3, POSITIVE); const int buzzer = 6; const int amarelo = 9; const int verde = 10; const int vermelho = 11; const int startupTime = 20; //180 const int prepareTime = 40; //86400 unsigned long initTime = 0,actTime; void setup() { // Inicializa comunicacao serial Serial.begin(9600); // Define o modo dos pinos de LED pinMode(amarelo,OUTPUT); pinMode(verde,OUTPUT); pinMode(vermelho,OUTPUT); // Define o pino do Buzzer como Saida pinMode(buzzer,OUTPUT); // Define o modo dos pinos do Sensor de gas pinMode(MQ_analog, INPUT); pinMode(MQ_dig, INPUT); // Inicializa o LCD lcd.begin (16,2); lcd.backlight(); //liga a luz de fundo // Grava o inicio da contagem de tempo initTime = millis(); } void loop() { valor_analog = analogRead(MQ_analog); valor_dig = digitalRead(MQ_dig); actTime = millis(); Serial.print(valor_analog); Serial.print(" || "); if(((actTime-initTime)/1000)<=(20)){ digitalWrite(amarelo,LOW); digitalWrite(verde,HIGH); digitalWrite(vermelho,HIGH); lcd.setCursor(0,0); lcd.print("Ligando..."); lcd.setCursor(1,1); lcd.print((actTime-initTime)/1000); } else{ if(((actTime-initTime)/1000)<=prepareTime){ digitalWrite(amarelo,LOW); } else{ digitalWrite(amarelo,HIGH); } if(valor_dig == 0){ lcd.setCursor(0,0); lcd.print("Gas detectado "); lcd.setCursor(0,1); lcd.print(valor_analog); digitalWrite(vermelho,LOW); digitalWrite(verde,HIGH); tone(buzzer,110); } else{ //Serial.println(""); lcd.setCursor(0,0); lcd.print("Gas ausente "); lcd.setCursor(0,1); lcd.print(valor_analog); digitalWrite(vermelho,HIGH); digitalWrite(verde,LOW); noTone(buzzer); } } if((actTime-initTime)%1000==0) lcd.clear(); } /* * https://www.fernandok.com/2017/12/arduino-e-esp8266-com-display-i2c-lcd.html * https://portal.vidadesilicio.com.br/sensor-de-gas-mq-135/ * * MQ-135: * https://img.filipeflop.com/files/download/Sensor_de_gas_MQ-135.pdf * */
0b619016b9f9eaf78452df191d004eb0d83b0347
3f6a6ffac2cc896d5e8c3474d5147ef493c2eebe
/app/src/snake.h
07733fc3790b16ecdfe8af43e4610cfc7f97684c
[]
no_license
N-911/snake
11c8658caf33655d529eaaf356a3ee70291a0853
453bd31fdbd79d33a227109eb7fdd3b3971fc472
refs/heads/master
2022-12-06T18:34:16.493140
2020-08-30T19:58:21
2020-08-30T19:58:21
289,906,168
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
h
snake.h
#pragma once #include <iostream> #include <map> #include <list> #include <deque> #include "functional.h" #include "menu.h" #define BOX_SIZE 40 class Block { public : Block(sf::Vector2<int> new_pos, sf::Color color); sf::Vector2<int> GetPosition(); sf::RectangleShape GetBox(); private: sf::Vector2<int> position; sf::RectangleShape box; }; class Snake { public: Snake(sf::RenderWindow *window, sf::Color colorH, sf::Color colorB, Fruit &fruit_); void DrawSnake(); bool MoveSnake(sf::Vector2<int> direction); bool DiedSnake(); void AddBoxToTail(sf::Vector2<int> direction); sf::Vector2<int> GetNextLocationForFood(); bool AteFood(); int GetSnakeSize(); void DeleteBox(); void DrawFruit(Player& player); Fruit& GetFruit(); private: int FramerateLimit = 60; sf::RenderWindow *screen; float movementScale; int snake_length; Fruit fruit; std::deque<Block> body; sf::Color colorBody; sf::Color colorHead; };
9e6f13bfbe4f6f2da879fb5f33b586a30dab8d2a
50821fe4361ec5da927995c0276821caf87e7a9d
/IronsightRessourcePacker/RessourcePackage/AssetPacker.h
88a927c9df256582334221b517a8e9ef36739164
[]
no_license
Laupetin/IronsightRessourcePacker
bab0495e7256c9378a4df2eef5033b1b5d9e8960
7554fc567fb297ee55f65a52313238c40bd8bb5e
refs/heads/master
2020-03-07T18:43:01.378952
2018-04-05T09:47:35
2018-04-05T09:47:35
127,649,353
3
1
null
null
null
null
UTF-8
C++
false
false
229
h
AssetPacker.h
#pragma once #ifndef _ASSETPACKER_H #define _ASSETPACKER_H #include "RessourcePackage.h" namespace IronsightRessourcePacker { bool PackAsset(FILE* fp_in, FILE* fp_out, uint32_t* length, RessourcePackageFlags flags); } #endif
114fc6abc17ed1f6140a5e9f70052a6e38cbbdf4
81b4392e197f69f55649635609ed186e8c8a1962
/cross_detector.h
a77ea6759a89982192591184eb98f239977ec82f
[]
no_license
DmitriiTunikov/cross_detect_growing_up
4b471e5416604f8ffc29e568357b48661e8a55c0
f0a73191b4fa9bf596817c1a040fc33f6b41b1ab
refs/heads/master
2021-03-24T16:44:46.999128
2020-03-23T10:28:47
2020-03-23T10:28:47
247,549,121
0
0
null
null
null
null
UTF-8
C++
false
false
1,601
h
cross_detector.h
#pragma once #ifndef CROSS_DETECTOR #define CROSS_DETECTOR #include <opencv2/imgproc/imgproc.hpp> #include <vector> #include <algorithm> #include "cv_supp.h" class CrossDetector { public: class Cell { public: Cell() {} Cell(const cv::Point2i& p_, const cv::Point2i& grid_coord_, const int& size_) : p(p_), size(size_), accum_value(0), grid_coord(grid_coord_) {} cv::Point2i p; cv::Point2i grid_coord; int size; int accum_value; cv_supp::hog_vec_t hog_vec; std::vector<int> growing_points_sets_idxs; //neighbours std::vector<std::shared_ptr<Cell>> neighs; std::vector<std::shared_ptr<Cell>> nearest_neighs; }; using grid_t = std::vector<std::vector<shared_ptr<Cell>>>; using growing_point_sets_t = std::vector<std::vector<std::shared_ptr<Cell>>>; CrossDetector(const cv::Mat& img_gray, const cv::Mat& image_color) : m_img(img_gray), m_img_color(image_color) {} std::vector<Point> detect_crosses(bool need_to_draw_grid = false); private: cv::Mat m_img; cv::Mat m_img_color; grid_t m_grid; std::vector<cv::Mat> m_integral_images; //drawing functions void draw_grid(); void draw_growing_point_sets(const growing_point_sets_t grow_point_sets); void draw_crosses(const std::vector<Point>& crosses); //algo functions void generate_grid(int min_size, int max_size); std::vector<Point> get_cross_result(); void get_intersection_point(std::vector<Point>& res, std::vector<std::pair<int, int>>& big_vec, std::vector<std::pair<int, int>>& small_vec, std::shared_ptr<Cell> cell, bool from_big_to_small_count); growing_point_sets_t growing_up(); }; #endif
2424aca3f752cf00409dbbf679d99c7e29793587
c747bd80366464011f303a5d55bc14c273c2d390
/test/zmdp-master/src/search/LRTDP.h
aa5dc9045611ef84a710927fd9b21752d9373c71
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
preet021/POMDP-Solver
54c44317b7705e59d3853c171ddca0d3feccea21
9b2dd238ea8eb62203c632b8470c123688dcb5ec
refs/heads/master
2023-05-29T23:08:14.892022
2021-05-31T12:09:01
2021-05-31T12:09:01
190,997,795
2
0
null
null
null
null
UTF-8
C++
false
false
2,468
h
LRTDP.h
/********** tell emacs we use -*- c++ -*- style comments ******************* $Revision: 1.9 $ $Author: trey $ $Date: 2006-10-20 04:55:49 $ @file LRTDP.h @brief Implementation of Bonet and Geffner's LRTDP algorithm. Copyright (c) 2006, Trey Smith. 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. ***************************************************************************/ #ifndef INCLRTDP_h #define INCLRTDP_h #include "RTDPCore.h" namespace zmdp { struct LRTDPExtraNodeData { bool isSolved; }; struct LRTDP : public RTDPCore { LRTDP(void); void getNodeHandler(MDPNode& cn); static void staticGetNodeHandler(MDPNode& cn, void* handlerData); static bool& getIsSolved(const MDPNode& cn); void cacheQ(MDPNode& cn); double residual(MDPNode& cn); bool checkSolved(MDPNode& cn); void updateInternal(MDPNode& cn); bool trialRecurse(MDPNode& cn, int depth); bool doTrial(MDPNode& cn); void derivedClassInit(void); }; }; // namespace zmdp #endif /* INCLRTDP_h */ /*************************************************************************** * REVISION HISTORY: * $Log: not supported by cvs2svn $ * Revision 1.8 2006/04/28 17:57:41 trey * changed to use apache license * * Revision 1.7 2006/04/07 19:41:45 trey * removed initLowerBound, initUpperBound arguments to constructor * * Revision 1.6 2006/04/04 17:24:52 trey * modified to use IncrementalBounds methods * * Revision 1.5 2006/02/27 20:12:36 trey * cleaned up meta-information in header * * Revision 1.4 2006/02/19 18:35:09 trey * targetPrecision now stared as a field rather than passed around recursively * * Revision 1.3 2006/02/14 19:34:34 trey * now use targetPrecision properly * * Revision 1.2 2006/02/13 20:20:33 trey * refactored some common code from RTDP and LRTDP * * Revision 1.1 2006/02/13 19:09:24 trey * initial check-in * * ***************************************************************************/
3566cb64cbd0ca7c77edf457119663fe9396d439
9b79cd60651629a65dbc05ad55e5153929af1eee
/coppy.cpp
dbe54a60545bf9d46f21c4118c499976fb6c146b
[]
no_license
SmetanaAlex/lab-1
7f6ce98deefff0287325a15e033dd4331f6e1775
47edb35fc041537d8700a98edb60d5d5d930cefd
refs/heads/master
2022-09-02T04:26:59.051648
2020-05-30T09:56:51
2020-05-30T09:56:51
268,045,533
0
0
null
null
null
null
UTF-8
C++
false
false
10,753
cpp
coppy.cpp
#pragma once #define _CRT_SECURE_NO_WARNINGS_ #include <iostream> #include <cmath> #include <algorithm> #include <iomanip> #include <fstream> #include <vector> #include <bitset> #include <string> #include <conio.h> #include "Header.h" using namespace std; enum Role { client, admin }; struct User { int id; char login[20] = {}; int password; Role role; }; struct Results { int rez_id; char res[20] = {}; char logins[20] = {}; int ids; }; int read_adm(User user); int read_user(User user); int add(Results simple,int ustp); int menu_add(int ustp); int Admin(User user); int Client(User user); int menu_admin(); int menu_client(); int Registration(); int Authorization(); int Add_ress(User user); int Creator(); int Authentication(User user); //int global_user_id = 0; int menu_start(); int write(Results simple ,int ustp); int main() { bool isRunning = true; while (isRunning) { int answer = 0; setlocale(LC_ALL, "Russian"); answer = menu_start(); switch (answer) { case 0:Authorization(); break; case 1:Registration(); break; case 2: system("cls"); cout << "Goodbye!\n__________________"; isRunning = false; } } /*ofstream w; w.open("users.dat", ios::binary); w.close();*/ } int Authentication(User user) { if (user.role == admin) { Admin(user); } if (user.role == client) { Client(user); } return 0; } int Admin(User user) { bool isRunning = true; while (isRunning) { system("cls"); cout << "Hello, admin!\n"; cout << "Choose the option:\n"; cout << "__________________\n"; int tmp = menu_admin(); switch (tmp) { case 0: Creator(); return 0; break; case 1:; read_adm( user);isRunning = 0; return 0; break; case 2: Creator(); isRunning = 0; return 0; break; case 3: /*Delete(user);*/ system("pause"); isRunning = 0; return 0; break; case 4: Add_ress( user); isRunning = 0; return 0; break; case 5: system("cls"); isRunning = 0; return 0; break; } } return 0; } int Client(User user) { bool isRunning = true; while (isRunning) { system("cls"); int tmp = menu_client(); switch (tmp) { case 0: {cout << "Hello, client!\n"; cout << read_user(user); isRunning = 0; break; } case 1: system("cls"); isRunning = 0; return 0; } } return 0; } int Registration() { cin.clear();// while (cin.get() != '\n'); User iteruser; int cnt = 0; ifstream f1("users.dat", ios::binary); while (f1.read((char*)&iteruser, sizeof(User))) { cnt++; } f1.close(); bool isFirst = 1; if (cnt > 0)isFirst = 0; User cur; if (isFirst)cur.id = 1; else cur.id = cnt + 1; bool isRepeated = 0; while (!isRepeated) { system("cls"); cout << "\n" << "Id = " << cur.id << "\n\n"; cout << "Enter login: "; cin.getline(cur.login, 19); f1.open("users.dat", ios::binary); if (isFirst == 1)isRepeated = 1; else { while (f1.read((char*)&iteruser, sizeof(User))) { if (strcmp(cur.login, iteruser.login) == 0) { cout << "Login is taken!\n"; system("pause"); isRepeated = 0; break; } isRepeated = 1; } } f1.close(); } cout << "Enter password: "; char password[20]; cin.getline(password, 19); cout << "Choose your role:\n"; cout << "1 ---> client\n2 ---> admin\n"; int tmp = 0; cin >> tmp; switch (tmp) { case 1: cur.role = client; break; case 2: cur.role = admin; break; } cur.password = md5(password, strlen(password)); ofstream f("users.dat", ios::app, ios::binary); f.write((char*)&cur, sizeof(User)); f.close(); return 0; } int Authorization() { User iteruser; int cnt = 0; ifstream f1("users.dat", ios::binary); while (f1.read((char*)&iteruser, sizeof(User))) { cnt++; } f1.close(); if (cnt > 0) { char strpassword[20] = {}; bool isOk = 0; while (!isOk) { system("cls"); ifstream f("users.dat", ios::binary); char login[20] = {}; cout << "Enter login: "; //while (cin.get() == '\n')continue; cin.getline(login, 19); cin.clear(); while (f.read((char*)&iteruser, sizeof(User))) { if (strcmp(iteruser.login, login) == 0) { isOk = 1; break; } } f.close(); if (isOk == 1) { int passwordmd5; do { system("cls"); cout << "Current login: " << login << '\n'; cout << "Enter password: "; cin.getline(strpassword, 19); passwordmd5 = md5(strpassword, strlen(strpassword)); } while (iteruser.password != passwordmd5); } } system("cls"); Authentication(iteruser); return 0; } else { cout << "There are no Users, registrate first!\n"; system("pause"); system("cls"); return 0; } } int menu_start() { int key = 0; int code; do { system("cls"); key = (key + 3) % 3; if (key == 0) cout << "-> I'd like to sign in" << endl; else cout << " I'd like to sign in" << endl; if (key == 1) cout << "-> I'm new user, let me create a new account" << endl; else cout << " I'm new user, let me create a new account" << endl; if (key == 2) cout << "-> Exit" << endl; else cout << " Exit" << endl; code = _getch(); if (code == 224) { code = _getch(); if (code == 80) key++; if (code == 72) key--; } } while (code != 13); system("cls"); return key; } int menu_admin() { int key = 0; int code; do { system("cls"); cout << "Hello, admin!\n"; cout << "Choose the option:\n"; cout << "__________________\n"; key = (key + 6) % 6; if (key == 0) cout << "-> Create" << endl; else cout << " Create" << endl; if (key == 1) cout << "-> Read" << endl; else cout << " Read" << endl; if (key == 2) cout << "-> Update" << endl; else cout << " Update" << endl; if (key == 3) cout << "-> Delete" << endl; else cout << " Delete" << endl; if (key == 4) cout << "-> Update results" << endl; else cout << " Update results" << endl; if (key == 5) cout << "-> Exit" << endl; else cout << " Exit" << endl; code = _getch(); if (code == 224) { code = _getch(); if (code == 80) key++; if (code == 72) key--; } } while (code != 13); system("cls"); return key; } int menu_client() { int key = 0; int code; do { system("cls"); cout << "Hello, client!\n"; cout << "Choose the option:\n"; cout << "__________________\n"; key = (key + 2) % 2; if (key == 0) cout << "-> Results" << endl; else cout << " Results" << endl; if (key == 1) cout << "-> Exit" << endl; else cout << " Exit" << endl; code = _getch(); if (code == 224) { code = _getch(); if (code == 80) key++; if (code == 72) key--; } } while (code != 13); system("cls"); return key; } int Add_ress (User user) { cin.clear(); while (cin.get() != '\n'); Results iteruser; int cnt = 0; ifstream f1("results.dat", ios::binary); while (f1.read((char*)&iteruser, sizeof(User))) { cnt++; } f1.close(); bool isFirst = 1; if (cnt > 0)isFirst = 0; Results cur; if (isFirst)cur.rez_id = 1; else cur.rez_id = cnt + 1; bool isRepeated = 0; while (!isRepeated) { system("cls"); cout << "\n" << "Id = " << cur.rez_id << "\n\n"; cout << "Enter result: "; cin.clear(); cin.getline(cur.res, 19); f1.open("results.dat", ios::binary); if (isFirst == 1)isRepeated = 1; else { while (f1.read((char*)&iteruser, sizeof(User))) { if (strcmp(cur.res, iteruser.res) == 0) { cout << "Login is taken!\n"; system("pause"); isRepeated = 0; break; } isRepeated = 1; } } f1.close(); } ofstream f("results.dat", ios::app, ios::binary); f.write((char*)&cur, sizeof(User)); f.close(); Admin(user); return 0; } int Creator() { ////////////////////////////////////////////////////////////////////////////////////////////////////// cout << "patient login\n"; Results simple; cin.clear(); cin.getline(simple.logins,20); User cuc; cout << "1" << endl; /////////////////// ifstream k1("users.dat", ios::binary); k1.open ("users.dat", ios::binary); while (k1.read((char*)&cuc, sizeof(User))) { if (strcmp(cuc.login, simple.logins)==0 ) { cout << "Login is taken!\n"; system("pause"); break; } else cout << "2" << endl; } k1.close();//////////////////////// Results iteruser; int cnt = 0; ifstream f1("amigos.dat", ios::binary); while (f1.read((char*)&iteruser, sizeof(User))) { cnt++; } f1.close(); bool isFirst = 1; if (cnt > 0)isFirst = 0; if (isFirst)simple.rez_id = 1; else simple.rez_id =cnt+1 ; int ustp = 1; /////////////////////// cout << cnt << endl; system("pause");///// add( simple ,ustp); return 0; } int add(Results simple, int ustp) { bool isRunning = true; while (isRunning) { int tmp = menu_add( ustp); switch (tmp) { case 0: write( simple,ustp); return 0; break; case 1: ustp++; add( simple, ustp); isRunning = 0; return 0; break; case 2: ustp--; add(simple, ustp); isRunning = 0; return 0; break; case 3: menu_admin(); system("pause"); isRunning = 0; return 0; break; } } return 0; } int menu_add(int ustp){ int key = 0; Results rr; int code; do { system("cls"); ifstream k1("results.dat",ios::binary); while (k1.read((char*)&rr, sizeof(User))) { if (rr.rez_id == ustp) { cout << rr.res<<endl; } } k1.close() ; cout << "Choose the option:\n"; cout << "__________________\n"; key = (key + 4) % 4; if (key == 0) cout << "-> Yes" << endl; else cout << " Yes" << endl; if (key == 1) cout << "-> Next" << endl; else cout << " Next" << endl; if (key == 2) cout << "-> Previus (i know about mistake)" << endl; else cout << " Previus" << endl; if (key == 3) cout << "-> Exit" << endl; else cout << " Exit" << endl; code = _getch(); if (code == 224) { code = _getch(); if (code == 80) key++; if (code == 72) key--; } } while (code != 13); system("cls"); return key; } int write(Results simple, int ustp) { Results rr; ifstream k1("results.dat", ios::binary); while (k1.read((char*)&rr, sizeof(Results))) { if (rr.rez_id == ustp) { strcpy_s(simple.res, rr.res); } } k1.close(); ofstream f("amigos.dat", ios::app, ios::binary); f.write((char*)&simple, sizeof(User)); f.close(); return 0; } int read_adm(User user) { User ded; Results k1; ifstream f("amigos.dat", ios::binary); cout << "Enter login: "; cin.getline(ded.login, 19); while (f.read((char*)&k1, sizeof(Results))) { if (!strcmp(k1.logins, ded.login) == 0) { cout << k1.res << endl; } } system("pause"); f.close(); Admin(user); return 0; } int read_user(User user){ Results k1; ifstream f("results.dat", ios::binary); cout <<"Glad that you have chosen my DDDDDDDDD : " << user.login << " :)\n"; while (f.read((char*)&k1, sizeof(Results))) { if (!strcmp(k1.logins, user.login) ) { cout << k1.res/*rez_id*/ << endl; } } system("pause"); f.close(); Client( user); return 0; }
2086e2e11051713f299009e009efb974b00c799f
bb09b5aed9a4a1ad0e22655152e9e50af59c9367
/Mult.h
4ab8631dbffe1016f4d8b1c1dd8d87c75bd00173
[]
no_license
Jarv1s10/longint-lab
b5391d784fa4beb965596211af0fa916d71c2138
63ba77fbc79eee2134e4d0c81944d7731d385878
refs/heads/master
2023-03-05T18:08:22.272265
2019-10-07T17:24:18
2019-10-07T17:24:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,340
h
Mult.h
#pragma once #define _USE_MATH_DEFINES #include "Longint.h" #include <cmath> #include <stdlib.h> #include <stdio.h> #include <complex> #include <algorithm> class Mult { public: virtual LongInt multiply(LongInt, LongInt); }; //1st algorithm class Karatsuba : public Mult { public: LongInt multiply(LongInt, LongInt) override; }; //2nd algoritm class ToomCook : public Mult { public: LongInt multiply(LongInt, LongInt) override; }; //3rd algorithm - empty class Modular : public Mult { public: LongInt multiply(LongInt, LongInt) override; }; //4th algorithm class Strassen : public Mult { public: LongInt multiply(LongInt, LongInt) override; }; //5th algorithm class Reverse { public: LongInt rev(LongInt); }; //6th algorithm - empty class Division { Reverse r; public: LongInt divide(LongInt, LongInt); }; //7th algorthm class Fermat { int k=20; LongInt power(LongInt a, LongInt n, LongInt p); LongInt gcd(LongInt a, LongInt b); public: bool isprime(LongInt); }; //8th algorithm class MilRab { int k = 20; LongInt power(LongInt a, LongInt n, LongInt p); bool millerTest(LongInt d, LongInt n); public: bool isprime(LongInt n); }; //9th algorithm class SolStr { int iterations = 20; LongInt modulo(LongInt, LongInt, LongInt); LongInt calculateJacodian(LongInt, LongInt); public: bool isprime(LongInt); };
13f86fefe9e4d47ec8f48f7ce37867599415e843
ef03cf1a39b6fa45d656dbec1f3f358183e609ad
/patchmatchwindow.h
a4e5eaa64b1f1766f48b29bc4643d0ec84a0b84e
[]
no_license
ethercrow/unseeit
ffd7acdcc8abec16f3a6ac56f0630e9a18d2c9e0
13496957369975c0faf6c36227495867871e669c
refs/heads/master
2021-01-13T01:29:05.457169
2011-06-22T17:22:45
2011-06-22T17:22:45
1,633,936
1
1
null
null
null
null
UTF-8
C++
false
false
1,039
h
patchmatchwindow.h
#ifndef PATCHMATCHWINDOW_H_NKL1CREY #define PATCHMATCHWINDOW_H_NKL1CREY #include <QWidget> #include <QLabel> #include <QImage> #include "cowmatrix.h" class SimilarityMapper; class PatchMatchWindow: public QWidget { Q_OBJECT public: PatchMatchWindow(QWidget* parent=0); ~PatchMatchWindow(); void loadDst(QString filename); void loadSrc(QString filename); protected: void keyReleaseEvent(QKeyEvent* evt); private slots: void onIterationComplete(COWMatrix<QPoint> offsetMap, COWMatrix<qreal> reliabilityMap); private: void launch(); QImage applyOffsetsWeighted(const COWMatrix<QPoint>& offsetMap, const COWMatrix<qreal>& relMap); QImage applyOffsetsUnweighted(const COWMatrix<QPoint>& offsetMap); QImage* dstImage_; QImage* srcImage_; QLabel* dstLabel_; QLabel* srcLabel_; QLabel* offsetLabel_; QLabel* errorLabel_; QLabel* resultLabel_; SimilarityMapper* sm_; }; #endif /* end of include guard: PATCHMATCHWINDOW_H_NKL1CREY */
161ad45b21e96145b6c45b1b28dcdeb52c506462
bf47471549a62d0a8d7ae5259728248e8a3e5862
/Leetcode/Tree/Merge Two 2 BST.cpp
719ff547a5e8172a3c9340278b721ed68526ee28
[]
no_license
VipulKhandelwal1999/Data-Structures-Algorithms
f0139cf4cd5e54f1a2341b1d5a88dc2598f6f757
4443ffcf816ae0825706a961ac307497c61d8afe
refs/heads/master
2022-11-20T01:52:46.227774
2020-07-14T08:08:56
2020-07-14T08:08:56
279,553,263
1
0
null
2020-07-14T10:23:48
2020-07-14T10:23:47
null
UTF-8
C++
false
false
3,108
cpp
Merge Two 2 BST.cpp
/* TC: O(m+n) and Space: O(height of the first tree + height of the second tree) The idea is to use iterative inorder traversal. We use two auxiliary stacks for two BSTs. Since we need to print the elements in sorted form, whenever we get a smaller element from any of the trees, we print it. If the element is greater, then we push it back to stack for the next iteration. */ void merge(node *root1, node *root2) { snode *s1 = NULL; node *current1 = root1; snode *s2 = NULL; node *current2 = root2; if (root1 == NULL) { inorder(root2); return; } if (root2 == NULL) { inorder(root1); return ; } while (current1 != NULL || !isEmpty(s1) || current2 != NULL || !isEmpty(s2)) { // Following steps follow iterative Inorder Traversal if (current1 != NULL || current2 != NULL ) { // Reach the leftmost node of both BSTs and push ancestors of // leftmost nodes to stack s1 and s2 respectively if (current1 != NULL) { push(&s1, current1); current1 = current1->left; } if (current2 != NULL) { push(&s2, current2); current2 = current2->left; } } else { // If we reach a NULL node and either of the stacks is empty, // then one tree is exhausted, ptint the other tree if (isEmpty(s1)) { while (!isEmpty(s2)) { current2 = pop (&s2); current2->left = NULL; // So instead of modifying structure of tree we can go for current2=current2->right inorder(current2); } return ; } if (isEmpty(s2)) { while (!isEmpty(s1)) { current1 = pop (&s1); current1->left = NULL; inorder(current1); } return ; } // Pop an element from both stacks and compare the // popped elements current1 = pop(&s1); current2 = pop(&s2); // If element of first tree is smaller, then print it // and push the right subtree. If the element is larger, // then we push it back to the corresponding stack. if (current1->data < current2->data) { cout<<current1->data<<" "; current1 = current1->right; push(&s2, current2); current2 = NULL; } else { cout<<current2->data<<" "; current2 = current2->right; push(&s1, current1); current1 = NULL; } } } }
159c545c74db132f18eae298ac97398774cd8fdd
c564ca17835940e084143930338e4e6790614e82
/1. NODEMCU 12E Sketchs - code/dht11_humidity_and_temp_sensor_wifi_infuxdata/dht11_humidity_and_temp_sensor_wifi_infuxdata.ino
439c4ab1bc7785ad03029acd36dfd7a38b3279a4
[]
no_license
IsaacMontero/Arduino
837092233f2f28afc26359cab61cbb96b86d1913
86d0777275d971ccaaca3f85f48fc6c1e05a2ee5
refs/heads/master
2020-03-14T06:21:42.224507
2019-02-01T16:15:11
2019-02-01T16:15:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,664
ino
dht11_humidity_and_temp_sensor_wifi_infuxdata.ino
#include <SPI.h> #include <ESP8266WiFi.h> #include <WiFiUDP.h> #include <DHT11.h> DHT11 dht11(2); const char* ssid = "vodafoneN1D0"; // your network SSID (name) const char* pass = "oras.clCo3"; // your network password int status = WL_IDLE_STATUS; // the Wifi radio's status // the IP address of your InfluxDB host IPAddress host(192, 168, 0, 200); // the HostName of your InfluxDB host const char* onlineHost = "kirometep.ddns.net"; // the port that the InfluxDB UDP plugin is listening on int port = 8888; WiFiUDP udp; void setup() { Serial.begin(115200); //note DHT11 need 1 sec to get data delay(1000); WiFi.mode(WIFI_STA); WiFi.begin(ssid, pass); Serial.print("Connecting to a:\t"); Serial.println(ssid); while (WiFi.status() != WL_CONNECTED) { delay(200); Serial.print('.'); } Serial.println("Connected to network"); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); // Gestión de la conexión // WiFi.reconnect(); // WiFi.disconnect(true); // WiFi.isConnected(); // WiFi.setAutoConnect(autoConnect); // WiFi.status(); // // Devuelven el valor indicado (no sirven para reescribir el valor) // WiFi.SSID(); // WiFi.hostname(); // WiFi.localIP(); // WiFi.subnetMask() // WiFi.gatewayIP(); // WiFi.dnsIP(dns_no); // WiFi.macAddress(); } void sendUdpPacket(String line){ // send the packet Serial.println("Sending UDP packet..."); if(udp.beginPacket(host, port) == 1) { udp.print(line); if(udp.endPacket() == 1) Serial.println("endPacket local ok"); else Serial.println("endPacket local fail"); } else if(udp.beginPacket(onlineHost, port) == 1) { udp.print(line); if(udp.endPacket() == 1) Serial.println("endPacket online ok"); else Serial.println("endPacket online fail"); } else{ Serial.println("beginPacket fail"); } } void loop() { String line; float temperature, humidity; // wait 1 second delay(1000); // get the current temperature from the sensor, to 2 decimal places if(dht11.read(humidity, temperature) == 0){ // concatenate the temperature into the line protocol line = String("temperature,Station=S1 value="); line += temperature; Serial.println(line); sendUdpPacket(line); line = String("humidity,Station=S1 value="); line += humidity; Serial.println(line); sendUdpPacket(line); } Serial.println(); }
e1d29f5abd472805b7d77c57ae281b546442ab8c
3cbf01fc0b185c50d9c4f4798cad96e26f804fee
/main.cpp
c1f273f796f0525104765568aba87f07332dd487
[]
no_license
Oran-G/Car-Project
d9f24ffee0481d98501523a4243bea9cf89776ec
abce286f5f19809686a9d10ea6060a675f2beee1
refs/heads/master
2023-02-17T06:30:20.408699
2020-12-28T20:42:23
2020-12-28T20:42:23
323,968,902
0
0
null
null
null
null
UTF-8
C++
false
false
2,406
cpp
main.cpp
#include <Arduino.h> void setup() { Car mechs = Car(5, 6, 9, 10, 48, 15, 9); } void loop() { mechs.forward(10); mechs.right(90); } // car basic movements class // will prob make much better and not use long delays in V2 class Car { public: // prf, prb, plf, plb, - Pins // w_radius - radius of wheels // c_delay - the delay to make the car move 1 centimeter // db - distance beetween wheels // dbc - cicumference of the circle created when using db as the diameter // circum - circumference of the wheels int prf, prb, plf, plb, w_radius, c_delay, db, d_delay; float circum, dbc; // constructor // rf - right forward pin, rd, right backwards pin // lf - left forward pin, ld, left backwards pin // w_radius - radius radius of wheel, might be depreceated in a future version, using diameter instead - mm // rate - revolutions of the motor per second // b_w_distance - distance beetween the wheels - cm Car (int rf, int rb, int lf, int lb, int w_radius, int rate, int b_w_distance) { prf = rf; prb = rb; plf = lf; plb = lb; w_radius = w_radius; circum = w_radius * 3 / 10; c_delay = 1000 / (rate * circum); db = b_w_distance; dbc = (db/2) * 3; d_delay = (dbc * c_delay) / 360; pinMode(prf, OUTPUT); pinMode(prb, OUTPUT); pinMode(plf, OUTPUT); pinMode(plb, OUTPUT); } // move forward centimeters amount of centimeters void forward(int centimeters) { analogWrite(prb, 0); analogWrite(plb, 0); analogWrite(prf, 256); analogWrite(plf, 256); delay(c_delay * centimeters); analogWrite(prf, 0); analogWrite(plf, 0); } // turn left degrees amount of degrees void left(int degrees) { analogWrite(prb, 0); analogWrite(plf, 0); analogWrite(prf, 256); analogWrite(plb, 256); delay(d_delay * degrees); analogWrite(plf, 0); analogWrite(prb, 0); } // turn right degrees amount of degrees void right(int degrees) { analogWrite(prf, 0); analogWrite(plb, 0); analogWrite(prb, 256); analogWrite(plf, 256); delay(d_delay * degrees); analogWrite(prb, 0); analogWrite(plf, 0); } // move backwards centimeters amount of centimeters void backwards(int centimeters) { analogWrite(prf, 0); analogWrite(plf, 0); analogWrite(prb, 256); analogWrite(plb, 256); delay(c_delay * centimeters); analogWrite(prb, 0); analogWrite(plb, 0); } };
67819109c193160616a1dcc5b22d9fd15b13bf0d
5f596af703fd0cae3dcdcade47c906ce3446c68d
/Tests/Test7/Administration1.cpp
b6780c10212269238661c41bbeae616919d3f246
[]
no_license
StoyanYanev/Data-Structures-and-Algorithms
d62cb2fc1e3353f4a5c568630154f71c07816a23
8b9a6e8ae7392db46821564030d8d4077d77c992
refs/heads/master
2020-04-19T10:53:20.104624
2019-02-03T11:10:33
2019-02-03T11:10:33
168,152,532
0
0
null
null
null
null
UTF-8
C++
false
false
1,207
cpp
Administration1.cpp
#include<iostream> #include<list> #include<vector> #include<algorithm> using namespace std; int main() { /**************************************FAST SOLUTION**************************************/ ios_base::sync_with_stdio(false); long long n; cin >> n; vector<long long> countNumbers(n + 1); list<long long> numbers; long long currentNumber; for (int i = 0; i < n; i++) { cin >> currentNumber; countNumbers[currentNumber] += 1; //count how many times every number repeats numbers.push_back(currentNumber); } list<long long>::iterator it; vector<long long> repeatedNumbers; for (it = numbers.begin(); it != numbers.end(); ++it) { if (countNumbers[*it] != 0) { if (countNumbers[*it] == 1) // if the number occurs 1 time than print it and mark it as not occured { cout << *it << " "; countNumbers[*it] = 0; } else { // if the number repeats more than 1 time than save it in the other vector repeatedNumbers.push_back(*it); countNumbers[*it] = 0; // and mark it as not occured } } } for (int i = 0; i < repeatedNumbers.size(); i++) { cout << repeatedNumbers[i] << " "; } return 0; }
aee98e652ddeab8b83e31ea590bd4b69cd68bc1b
fe18c0717d9a4e4000021b05c3b342d2eaf692c1
/src/search_local/index_storage/rocksdb_helper/rocksdb_direct_process.cc
c4e43df9e86778afea9e1fc320d97e1c3a52cf52
[ "OML", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
jdisearch/isearch
0c29c972650c36774d58cc10d5dc906deb5bbf18
272bd4ab0dc82d9e33c8543474b1294569947bb3
refs/heads/master
2023-08-12T10:10:13.850970
2021-09-18T08:43:05
2021-09-18T08:43:05
397,084,210
3
1
null
null
null
null
UTF-8
C++
false
false
2,282
cc
rocksdb_direct_process.cc
/* * ===================================================================================== * * Filename: rocksdb_direct_process.cc * * Description: * * Version: 1.0 * Created: 09/08/2020 10:02:05 PM * Revision: none * Compiler: gcc * * Author: zhuyao, zhuyao28@jd.com * Company: JD.com, Inc. * * ===================================================================================== */ #include "rocksdb_direct_process.h" #include "rocksdb_direct_listener.h" #include "common/poll_thread.h" #include "log.h" #include <assert.h> RocksdbDirectProcess::RocksdbDirectProcess( const std::string &name, HelperProcessBase *processor) : mDomainSocketPath(name), mRocksdbProcess(processor), mRocksDirectPoll(new PollThread("RocksdbDirectAccessPoll")), mListener(NULL) { } int RocksdbDirectProcess::init() { assert(mRocksDirectPoll); int ret = mRocksDirectPoll->initialize_thread(); if (ret < 0) { log_error("initialize thread poll failed."); return -1; } // add listener to poll ret = add_listener_to_poll(); if (ret != 0) return -1; // add worker to poll // ret = addRocksdbWorkToPoll(); // if ( ret != 0 ) return -1; return 0; } int RocksdbDirectProcess::add_listener_to_poll() { mListener = new RocksdbDirectListener(mDomainSocketPath, mRocksdbProcess, mRocksDirectPoll); if (!mListener) { log_error("create listener instance failed"); return -1; } int ret = mListener->Bind(); if (ret < 0) { log_error("bind address failed."); return -1; } ret = mListener->attach_thread(); if (ret < 0) { log_error("add listener to poll failed."); return -1; } return 0; } /* int RocksdbDirectProcess::addRocksdbWorkToPoll() { mDirectWorker = new RocksdbDirectWorker(mRocksDirectPoll); if ( !mDirectWorker ) { log_error("create rocksdb direct worker failed."); return -1; } int ret = mDirectWorker->attach_thread(); if ( ret < 0 ) { log_error("add rocksdb direct worker to poll failed."); return -1; } return true; }*/ int RocksdbDirectProcess::run_process() { mRocksDirectPoll->running_thread(); log_error("start rocksdb direct process!"); return 0; }
bf2c1c07dfc90bf7b9b5625b21082c41447dacf3
916bfdd514df96266b813f8742b5a66dc90ef331
/libstomp-src/main.cpp
d6d28a3c313daccfd3f0b1d9224415b456b4923b
[]
no_license
rthomas/mcollective-cpp-agents
4144891c9dd3a21d25e0ac3c75445a5982052cce
50de822360e51cf691f80f80147d7258e08e10d8
refs/heads/master
2020-04-08T21:54:00.626952
2012-04-25T18:08:09
2012-04-25T18:08:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
185
cpp
main.cpp
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include "listener.h" int main(int argc, char *argv[]) { Mcollective::Listener a; a.StartThreads(); sleep(101010100); }
db2035d443a2fad862e1e8e6526d8e515b719eaa
b442899b19a966d59dc60f9270f5b2d7d8261ca0
/lib/parser/include/parser.h
80ec04cc56bc2744df13debc62e71ec971bdc323
[ "Apache-2.0" ]
permissive
UsatiyNyan/ledmusicreworkembedded
17ea3ad6077cb7c8a07afb9ac3879d333bef1e92
c41b7b5efdfa595111965ba5de1f5506792d90d0
refs/heads/master
2022-06-09T23:23:15.600157
2020-05-08T18:42:01
2020-05-08T18:42:01
259,804,331
3
0
null
null
null
null
UTF-8
C++
false
false
809
h
parser.h
#ifndef __LIB_UART__ #define __LIB_UART__ #include "serial.h" #include "config.h" #include "job_thread.h" #include "rgb.h" #include "fixed_queue.h" #include <string> namespace parser { class Parser : public executor::JobThread { public: explicit Parser(container::FixedQueue<clr::RGB> &rgb_queue, Config &config); private: void retrieve_data(); void check_sum(); void parse_basic(); void parse_rgb(); void parse_circle(); void parse_polygon(); void parse_bpm(); void parse_rotation(); void parse_length_and_width(); void job() override; container::FixedQueue<clr::RGB> &_rgb_queue; Config &_config; serial::Connection _connection; std::vector<uint8_t> _read_buf{128}; std::mutex _mutex; }; } // namespace parser #endif // __LIB_UART__
26b647f2209456d6718c363a5986cd12fbe60374
c7e7b005786eca5066e31d547aff4efdbd76950c
/src/client/gl/Image.cpp
244c75503a70eaeb645395286b4dbc6055e8e876
[]
no_license
QualityHammer/LearnOpenGL
442f5d4031877c40353f3d0a161a82ae41625d85
9075474c85352a14354bc8cf9b7fc83a571a1785
refs/heads/master
2023-01-12T04:57:25.473771
2020-04-03T01:43:49
2020-04-03T01:43:49
251,726,401
0
0
null
null
null
null
UTF-8
C++
false
false
333
cpp
Image.cpp
#include "client/gl/Image.hpp" #include <utils/stb_image.h> namespace gl { Image loadImage(const std::string& filename) { Image img; stbi_set_flip_vertically_on_load(true); img.data = stbi_load(filename.c_str(), &img.width, &img.height, &img.nrChannels, 0); return img; } }
ee354c8016def397109247dc7cd8fef07fc2cc8b
70738bd1ec6444b1dafe1c3877b82dd2d1c7d8a3
/main.cpp
819486ac3699ca49a38cfe1d6298d6abd581a89d
[]
no_license
raven91/spr_approximate_bayesian_computation
816db3611baf8021816866457ab9f807159b6785
d5d635c849a2590f4097ffa7609a250449445528
refs/heads/master
2021-10-15T08:43:52.663535
2019-02-05T15:29:47
2019-02-05T15:29:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,177
cpp
main.cpp
#include "Engines/AbcRejectionEngine.hpp" #include "Engines/AbcSmcEngineSynthetic.hpp" #include "Engines/AbcSmcEngineExperimental.hpp" #include "Engines/SimulationEngineForSyntheticData.hpp" #include "ParameterSets/SyntheticParameterSet.hpp" #include "Other/PeriodicBoundaryConditionsConfiguration.hpp" #include "Parallelization/Parallelization.hpp" int main(int argc, char **argv) { LaunchParallelSession(argc, argv); Thread thread(argc, argv); SyntheticParameterSet parameter_set; PeriodicBoundaryConditionsConfiguration pbc_config(parameter_set.Get_L(), parameter_set.Get_L()); SimulationEngineForSyntheticData simulation_engine(parameter_set, pbc_config); simulation_engine.GenerateSyntheticDataWithArbitraryStationaryVelocity(); // AbcRejectionEngine abc_rejection_engine; // abc_rejection_engine.PrepareSyntheticData(); // abc_rejection_engine.RunAbcTowardsSyntheticData(); // AbcSmcEngineSynthetic abc_smc_engine; // abc_smc_engine.PrepareSyntheticData(); // abc_smc_engine.RunAbcTowardsSyntheticData(); // AbcSmcEngineExperimental abc_smc_engine; // abc_smc_engine.RunAbcTowardsExperimentalData(); FinalizeParallelSession(); return 0; }
22d57f185d5b4799e9aee3fdf1b3e767c9fc1c6c
cd14901440b31b5d4657ac688e53126dee3cb5d7
/casa/vart/refsystem.h
6209ffca7a7f67434d160c244f4cacca23eda68e
[]
no_license
samurai-753/thuza_cg
1f9c57d742c69965e8d69c03887f29af58e7949d
464376ecc6ddf75aaec1eea86cd9b456eff152c8
refs/heads/master
2020-03-30T09:27:05.746642
2018-10-01T11:24:24
2018-10-01T11:24:24
151,076,047
1
1
null
null
null
null
UTF-8
C++
false
false
584
h
refsystem.h
#ifndef VART_REFSYSTEM_H #define VART_REFSYSTEM_H #include "graphicobj.h" #include "scenenode.h" namespace VART { class RefSystem : public GraphicObj { public: // PUBLIC METHODS RefSystem(); // hide the axis Z void HideZ(); virtual VART::SceneNode * Copy(); virtual void ComputeBoundingBox(); private: // PRIVATE METHODS virtual bool DrawInstanceOGL() const; protected: // PROTECTED ATRIBUTES static double axisLength; Arrow axisX; Arrow axisY; Arrow axisZ; }; // end class declaration } // end namespace #endif
e38a206faf78b49fb6745ac174fabaa5cc96c93e
2a88cc31069099e1c223f0049f8d9ff27703938b
/code/engine/gkCommon/ISystemProfiler.h
e00b92b0d8db5c0df8c520ba5a8e83084514a1e2
[]
no_license
longlongwaytogo/gkEngine
ffd4aff126095b7798fdb5a8cafde75a11b77fb5
c308a5f7a9900dcb40c3cd37b9f2fd0829b246b5
refs/heads/master
2020-11-27T11:37:55.587685
2019-12-21T12:31:05
2019-12-21T12:31:05
229,424,018
0
0
null
2019-12-21T12:25:51
2019-12-21T12:25:50
null
UTF-8
C++
false
false
3,665
h
ISystemProfiler.h
////////////////////////////////////////////////////////////////////////// /* Copyright (c) 2011-2015 Kaiming Yi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Name: ISystemProfiler.h // Desc: // // Author: Kaiming-Desktop // Date: 2011 /8/14 // Modify: 2011 /8/14 // ////////////////////////////////////////////////////////////////////////// #ifndef ISYSTEMPROFILER_H_ #define ISYSTEMPROFILER_H_ #pragma once #include "gkPlatform.h" /** @brief Profile项目 @remark */ enum EProfileElement { ePe_Triangle_Total = 0, ///! 总三角面数 ePe_Triangle_Fwd, ///! 非阴影,三角面数 ePe_Triangle_Shadow, ///! 阴影,三角面数 ePe_Batch_Total, ///! 总批次数 ePe_Batch_Fwd, ///! 非阴影,批次数 ePe_Batch_Shadow, ///! 阴影,批次数 ePe_GpuTick_GPUTime, ePe_GpuTick_ReflectGen, ePe_GpuTick_ShadowMapGen, ePe_GpuTick_Zpass, ePe_GpuTick_SSAO, ePe_GpuTick_ShadowMaskGen, ePe_GpuTick_DeferredLighting, ePe_GpuTick_OpaquePass, ePe_GpuTick_TransparentPass, ePe_GpuTick_HDR, ePe_GpuTick_PostProcess, ePe_Font_Cost, ePe_Physic_Cost, ePe_TrackBus_Cost, ePe_Input_Cost, ePe_3DEngine_Cost, ePe_ThreadSync_Cost, ePe_SThread_Cost, ePe_MThread_Cost, ePe_MT_Part1, ePe_MT_Part2, ePe_MT_Part3, ePe_Count, }; /** @ingroup CoreModuleAPI @brief Profiler系统的性能监控器 @remark 通过EProfilerElement来获取监控项目的数据 @sa EProfileElement */ struct ISystemProfiler { public: virtual ~ISystemProfiler(void) {} virtual uint32 getElementCount(EProfileElement element) =0; virtual void increaseElementCount(EProfileElement element, int count = 1) =0; virtual float getElementTime(EProfileElement element) =0; virtual void setElementTime(EProfileElement element, float elapsedTime) =0; virtual void setGpuTimerElement( const TCHAR* elementName, float elpasedTime ) =0; virtual float getGpuTimerElement( const TCHAR* elementName ) =0; virtual void setStartRendering() =0; virtual void setEndRendering() =0; virtual void setStartWaiting() =0; virtual void setEndWaiting() =0; virtual void setStartSceneManage() =0; virtual void setEndSceneManage() =0; virtual void setStartCommit() =0; virtual void setEndCommit() =0; virtual int getFrameCount() =0; virtual void displayInfo() =0; virtual void setFrameBegin() =0; virtual void setFrameEnd() =0; virtual void setElementStart(EProfileElement element ) =0; virtual void setElementEnd(EProfileElement element ) =0; }; #endif
859216e55f305f2a104c3c861587f867ef0da00b
83cce1dd075980ce3b9ffed7205272b9bf534e88
/code_embarque/main_Envoi_Vers_Avion.ino
b25c2e2502b2fbc536eb18b918a2cfddf3df75d6
[ "LicenseRef-scancode-public-domain" ]
permissive
Tati76/Backup-Arduino-Avion
ea484d4e3734b05aef09a6069b95fd38f1e97b87
484500cc97e03df20de9c2e3d70808f6edf14aa0
refs/heads/master
2021-05-01T19:55:58.430973
2018-06-13T08:32:35
2018-06-13T08:32:35
120,955,205
0
0
null
null
null
null
UTF-8
C++
false
false
2,962
ino
main_Envoi_Vers_Avion.ino
// ************* La Radio ************* #include <SPI.h> #include <RF24.h> // voir http://tmrh20.github.io/RF24/ // ************* La Manette ************* #include <PS4USB.h> // Satisfy the IDE, which needs to see the include statment in the ino too. #ifdef dobogusinclude #include <spi4teensy3.h> #endif #include "fonctions_obtenir_donnees_usb.h" #include "structures.h" #include "fonctions_print.h" #include "fonctions_radio.h" // Configurer vos radio nRF24L01+ sur le bus SPI et mettre CE sur D7 et CSN sur D8 RF24 radio(7, 8); // Le nom des "pipes" de communication, un en lecture, un en écriture const byte adresses[][6] = {"0pipe", "1pipe"}; // Pipes 1-5 should share the same address, except the first byte. Only the first byte in the array should be unique // A CONFIGURER sur la pin A0 // si A0 est à GND alors rôle = 0 --> le premier Arduino // si A0 est à 3.3V ou 5V alors rôle = 1 --> pour le second const byte configurationPin = A0; uint8_t role; // ************* Deux Leds avec résitances de limiation de courant ************* const byte pinLed0 = 9; const byte pinLed1 = 10; USB Usb; PS4USB PS4(&Usb); uint8_t ancienEtatL3; bool decollage; void setup() { Serial.begin(115200); role = 0 ; Serial.print(F("\nMon Role = ")); Serial.println(role); // On configure la radio radio.begin(); // pour le test on règle le niveau d'énergie à RF24_PA_LOW pour éviter les interférences // mettre à RF24_PA_MAX si on veut la puissance d'émission max radio.setPALevel(RF24_PA_HIGH); // On ouvre un pipe de lecture et un d'écriture avec des noms opposés en fonction du rôle // comme ça un parle sur "pipe0" et l'autre écoute sur "pipe0" // et l'autre parle sur "pipe1" tandisque Le premier écoute sur "pipe1" radio.openWritingPipe(adresses[0]); // role doit être 0 ou 1 radio.openReadingPipe(1, adresses[1]); // 1 - role = l'autre adresse // Start the radio listening for data //radio.startListening(); // INIT Manette #if !defined(__MIPSEL__) while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection #endif if (Usb.Init() == -1) { Serial.println(F("\r\nOSC did not start")); while (1); // Halt } Serial.println(F("\r\nPS4 USB Library Started")); // VARIABLES pour le programme ancienEtatL3 = 0; decollage = true; } // ------------------------------------------------------------------ uint8_t valeurAccelerateurs; uint8_t L1Press; uint8_t R1Press; uint8_t L3Press; uint8_t angleTangage; uint8_t angleRoulis; long compteur(0); DONNEES msg; void loop() { Usb.Task(); if (PS4.connected()) { msg = obtenirDonneesUsb(); // ON FAIT UN PRINT DU MESSAGE printMessageRadio(msg); // ENVOI DU MESSAGE PAR LE MODULE NRF24L01+ envoyerMessage(msg); delay(25); } }
c7250ee03a74424230982f7f471fe512bfa28ec6
a37c0ccadb02af2877c4be9bad863d7ba8a1a390
/client/Game2/LocaleSelectScene.cpp
37da19c521e46d5f61e3486e0f591c558fe22239
[]
no_license
johnsie/HoverNet
9dec639cdb6471f98ffc357d5f9d1b089eba1336
05ac3afbd8edfc6301eff352f1ae467c7e930f43
refs/heads/master
2022-02-23T15:37:50.754976
2020-03-03T16:13:31
2020-03-03T16:13:31
145,713,174
1
0
null
null
null
null
UTF-8
C++
false
false
2,483
cpp
LocaleSelectScene.cpp
// LocaleSelectScene.cpp // // Copyright (c) 2015-2016 Michael Imamura. // // Licensed under GrokkSoft HoverRace SourceCode License v1.0(the "License"); // you may not use this file except in compliance with the License. // // A copy of the license should have been attached to the package from which // you have taken this file. If you can not find the license you can not use // this file. // // // The author makes no representations about the suitability of // this software for any purpose. It is provided "as is" "AS IS", // 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. #include <boost/algorithm/string/predicate.hpp> #include "../../engine/Display/Button.h" #include "../../engine/Display/Container.h" #include "../../engine/Util/Locale.h" #include "LocaleSelectScene.h" using namespace HoverRace::Util; namespace HoverRace { namespace Client { LocaleSelectScene::LocaleSelectScene(Display::Display &display, GameDirector &director, const std::string &parentTitle, const Util::Locale &locale, const std::string&) : SUPER(display, director, parentTitle, _("SELECT LANGUAGE"), "Locale Select") { using namespace Display; using Alignment = UiViewModel::Alignment; SupportCancelAction(); auto root = GetContentRoot(); localeList = root->NewChild<PickList<std::string>>(display, BasePickList::Mode::LIST, Vec2(260, 520)); localeList->SetPos(640, 0); localeList->SetAlignment(Alignment::N); localeList->Add(_("Auto-detect"), ""); // Produce a list sorted by user-friendly name, instead of by locale ID. using item_t = const Util::Locale::value_type*; std::vector<item_t> sorted; for (const auto &loc : locale) { sorted.push_back(&loc); } std::sort(sorted.begin(), sorted.end(), [](const item_t &a, const item_t &b) { return boost::algorithm::ilexicographical_compare( a->second, b->second); }); for (const auto &loc : sorted) { localeList->Add(loc->second, loc->first); } localeList->GetValueChangedSignal().connect( std::bind(&LocaleSelectScene::OnLocaleSelected, this)); localeList->RequestFocus(); } std::string LocaleSelectScene::GetLocaleId() const { if (auto id = localeList->GetValue()) { return *id; } else { return ""; } } void LocaleSelectScene::OnLocaleSelected() { confirmSignal(); director.RequestPopScene(); } } // namespace Client } // namespace HoverRace
3a835b5c9970b87131f1ac251d39e62fb2f67efb
8163ae43641d9acc6341809c6c1e0959563e55f0
/src/MasterSlave.cpp
1d3d96ce0aa3ce805336cc59b72b7e43d7eb0154
[]
no_license
jimgoo/hfrisk
f1faf10ab3235e95fc05923ecdceee0f355844bc
defc1cea1c25504bac5c7d2c8cc943814868d7db
refs/heads/master
2022-11-06T09:46:27.944632
2022-10-26T16:33:27
2022-10-26T16:33:27
7,532,778
6
3
null
null
null
null
UTF-8
C++
false
false
4,685
cpp
MasterSlave.cpp
/* Author: Jimmie Goode Created: 2013-01-10 A dynamically load balanced master/slave application based on: http://www.lam-mpi.org/tutorials/one-step/ezstart.php */ #include "MasterSlave.hpp" // MPI #define WORKTAG 1 #define DIETAG 2 //------------------------------------------------------------------------------- // <MASTER> bool MasterSlave::get_next_work_item(double* work) { return false; } //------------------------------------------------------------------------------- // <SLAVE> void MasterSlave::do_work(double *work, double *result, int size_work, int size_res) { } //------------------------------------------------------------------------------- // <MASTER> void MasterSlave::onWorkComplete(double *result) { } //------------------------------------------------------------------------------- // <MASTER> void MasterSlave:: onAllWorkComplete() { } //------------------------------------------------------------------------------- // <MASTER> void MasterSlave::master(int size_work, int size_res) { iters = 0; double work[size_work]; double result[size_res]; int myrank, ntasks, rank; MPI_Status status; MPI_Comm_size(MPI_COMM_WORLD, &ntasks); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); // Initialize the processor map int procMap[ntasks]; for (int i = 0; i < ntasks; i++) { procMap[i] = -1; } // Seed the slaves; send one unit of work to each slave. for (rank = 1; rank < ntasks; ++rank) { // Find the next item of work to do get_next_work_item(work); MPI_Send(&work, // message buffer size_work, // size of data item MPI_DOUBLE, // data item type is double rank, // destination process rank WORKTAG, // user chosen message tag MPI_COMM_WORLD); // default communicator } // Loop over getting new work requests until there is no more work to be done bool hasData = get_next_work_item(work); while (hasData) { // Receive results from a slave MPI_Recv(&result, size_res, MPI_DOUBLE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); onWorkComplete(result); MPI_Send(&work, size_work, MPI_DOUBLE, status.MPI_SOURCE, WORKTAG, MPI_COMM_WORLD); // Get the next unit of work to be done hasData = get_next_work_item(work); } // There's no more work to be done, so receive all the outstanding results from the slaves. for (rank = 1; rank < ntasks; ++rank) { MPI_Recv(&result, size_res, MPI_DOUBLE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); onWorkComplete(result); } // Tell all the slaves to exit by sending an empty message with the DIETAG. for (rank = 1; rank < ntasks; ++rank) { MPI_Send(0, 0, MPI_DOUBLE, rank, DIETAG, MPI_COMM_WORLD); } // Do the copula estimation now that we've got the marginals onAllWorkComplete(); } //------------------------------------------------------------------------------- // <SLAVE> void MasterSlave::slave(int size_work, int size_res) { iters++; double work[size_work]; double result[size_res]; MPI_Status status; while (1) { // Receive a message from the master MPI_Recv(&work, size_work, MPI_DOUBLE, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); // Check the tag of the received message. if (status.MPI_TAG == DIETAG) { return; } do_work(work, result, size_work, size_res); // Send the result back MPI_Send(&result, size_res, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); } } //------------------------------------------------------------------------------- // <MASTER> void MasterSlave::distribute(int rank) { // MPI_Bcast(&rows, 1, MPI_INT, 0, MPI_COMM_WORLD); // MPI_Bcast(&cols, 1, MPI_INT, 0, MPI_COMM_WORLD); // MPI_Bcast(&size_work, 1, MPI_INT, 0, MPI_COMM_WORLD); // MPI_Bcast(&size_res , 1, MPI_INT, 0, MPI_COMM_WORLD); // MPI_Bcast(&vnRet, SIZE_RET, MPI_DOUBLE, 0, MPI_COMM_WORLD); } //------------------------------------------------------------------------------- // /* //------------------------------------------------------------------------------- // <MAIN> int main(int argc, char **argv) { cout << "\n\nMain for MasterSlave.cpp\n\n"; int myrank, ntasks; int size_work = 5; int size_res = 3; MasterSlave ms; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); MPI_Comm_size(MPI_COMM_WORLD, &ntasks); ms.distribute(myrank); if (myrank == 0) { ms.master(size_work, size_res); } else { ms.slave(size_work, size_res); } MPI_Finalize(); return 0; } */
86b498f91b83a1decfaf44993ea9e3f4a758d2ab
6e2e8592b602ac36de770ad101eed05405c982cc
/modules/perception/camera/lib/traffic_light/detector/recognition/proto/recognition.pb.h
382b148c1c58dfb249f2d88c82ed3e22616dbe1b
[]
no_license
sxhxliang/Apollo-Lite
6060dc361fd22b90fa2c986ee4dbbb6cf38d50ec
b59e1c6a9a88aa421e72fa709a80c10e868531f8
refs/heads/main
2023-04-09T19:04:15.275450
2021-04-17T18:25:22
2021-04-17T18:25:22
356,549,140
2
3
null
null
null
null
UTF-8
C++
false
true
55,705
h
recognition.pb.h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: modules/perception/camera/lib/traffic_light/detector/recognition/proto/recognition.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto #define GOOGLE_PROTOBUF_INCLUDED_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3008000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3008000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[2] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto; namespace apollo { namespace perception { namespace camera { namespace traffic_light { namespace recognition { class ClassifyParam; class ClassifyParamDefaultTypeInternal; extern ClassifyParamDefaultTypeInternal _ClassifyParam_default_instance_; class RecognizeBoxParam; class RecognizeBoxParamDefaultTypeInternal; extern RecognizeBoxParamDefaultTypeInternal _RecognizeBoxParam_default_instance_; } // namespace recognition } // namespace traffic_light } // namespace camera } // namespace perception } // namespace apollo PROTOBUF_NAMESPACE_OPEN template<> ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* Arena::CreateMaybeMessage<::apollo::perception::camera::traffic_light::recognition::ClassifyParam>(Arena*); template<> ::apollo::perception::camera::traffic_light::recognition::RecognizeBoxParam* Arena::CreateMaybeMessage<::apollo::perception::camera::traffic_light::recognition::RecognizeBoxParam>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace apollo { namespace perception { namespace camera { namespace traffic_light { namespace recognition { // =================================================================== class ClassifyParam : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:apollo.perception.camera.traffic_light.recognition.ClassifyParam) */ { public: ClassifyParam(); virtual ~ClassifyParam(); ClassifyParam(const ClassifyParam& from); ClassifyParam(ClassifyParam&& from) noexcept : ClassifyParam() { *this = ::std::move(from); } inline ClassifyParam& operator=(const ClassifyParam& from) { CopyFrom(from); return *this; } inline ClassifyParam& operator=(ClassifyParam&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const ClassifyParam& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const ClassifyParam* internal_default_instance() { return reinterpret_cast<const ClassifyParam*>( &_ClassifyParam_default_instance_); } static constexpr int kIndexInFileMessages = 0; void Swap(ClassifyParam* other); friend void swap(ClassifyParam& a, ClassifyParam& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline ClassifyParam* New() const final { return CreateMaybeMessage<ClassifyParam>(nullptr); } ClassifyParam* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<ClassifyParam>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const ClassifyParam& from); void MergeFrom(const ClassifyParam& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; #else bool MergePartialFromCodedStream( ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ClassifyParam* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "apollo.perception.camera.traffic_light.recognition.ClassifyParam"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto); return ::descriptor_table_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional string model_name = 1; bool has_model_name() const; void clear_model_name(); static const int kModelNameFieldNumber = 1; const std::string& model_name() const; void set_model_name(const std::string& value); void set_model_name(std::string&& value); void set_model_name(const char* value); void set_model_name(const char* value, size_t size); std::string* mutable_model_name(); std::string* release_model_name(); void set_allocated_model_name(std::string* model_name); // optional string model_type = 2 [default = "CaffeNet"]; bool has_model_type() const; void clear_model_type(); static const int kModelTypeFieldNumber = 2; const std::string& model_type() const; void set_model_type(const std::string& value); void set_model_type(std::string&& value); void set_model_type(const char* value); void set_model_type(const char* value, size_t size); std::string* mutable_model_type(); std::string* release_model_type(); void set_allocated_model_type(std::string* model_type); // optional string input_blob = 3; bool has_input_blob() const; void clear_input_blob(); static const int kInputBlobFieldNumber = 3; const std::string& input_blob() const; void set_input_blob(const std::string& value); void set_input_blob(std::string&& value); void set_input_blob(const char* value); void set_input_blob(const char* value, size_t size); std::string* mutable_input_blob(); std::string* release_input_blob(); void set_allocated_input_blob(std::string* input_blob); // optional string output_blob = 4; bool has_output_blob() const; void clear_output_blob(); static const int kOutputBlobFieldNumber = 4; const std::string& output_blob() const; void set_output_blob(const std::string& value); void set_output_blob(std::string&& value); void set_output_blob(const char* value); void set_output_blob(const char* value, size_t size); std::string* mutable_output_blob(); std::string* release_output_blob(); void set_allocated_output_blob(std::string* output_blob); // optional string weight_file = 5; bool has_weight_file() const; void clear_weight_file(); static const int kWeightFileFieldNumber = 5; const std::string& weight_file() const; void set_weight_file(const std::string& value); void set_weight_file(std::string&& value); void set_weight_file(const char* value); void set_weight_file(const char* value, size_t size); std::string* mutable_weight_file(); std::string* release_weight_file(); void set_allocated_weight_file(std::string* weight_file); // optional string proto_file = 6; bool has_proto_file() const; void clear_proto_file(); static const int kProtoFileFieldNumber = 6; const std::string& proto_file() const; void set_proto_file(const std::string& value); void set_proto_file(std::string&& value); void set_proto_file(const char* value); void set_proto_file(const char* value, size_t size); std::string* mutable_proto_file(); std::string* release_proto_file(); void set_allocated_proto_file(std::string* proto_file); // optional float classify_threshold = 7; bool has_classify_threshold() const; void clear_classify_threshold(); static const int kClassifyThresholdFieldNumber = 7; float classify_threshold() const; void set_classify_threshold(float value); // optional int32 classify_resize_width = 8; bool has_classify_resize_width() const; void clear_classify_resize_width(); static const int kClassifyResizeWidthFieldNumber = 8; ::PROTOBUF_NAMESPACE_ID::int32 classify_resize_width() const; void set_classify_resize_width(::PROTOBUF_NAMESPACE_ID::int32 value); // optional int32 classify_resize_height = 9; bool has_classify_resize_height() const; void clear_classify_resize_height(); static const int kClassifyResizeHeightFieldNumber = 9; ::PROTOBUF_NAMESPACE_ID::int32 classify_resize_height() const; void set_classify_resize_height(::PROTOBUF_NAMESPACE_ID::int32 value); // optional float scale = 10; bool has_scale() const; void clear_scale(); static const int kScaleFieldNumber = 10; float scale() const; void set_scale(float value); // optional float mean_b = 12 [default = 95]; bool has_mean_b() const; void clear_mean_b(); static const int kMeanBFieldNumber = 12; float mean_b() const; void set_mean_b(float value); // optional float mean_g = 13 [default = 99]; bool has_mean_g() const; void clear_mean_g(); static const int kMeanGFieldNumber = 13; float mean_g() const; void set_mean_g(float value); // optional float mean_r = 14 [default = 96]; bool has_mean_r() const; void clear_mean_r(); static const int kMeanRFieldNumber = 14; float mean_r() const; void set_mean_r(float value); // optional bool is_bgr = 15 [default = true]; bool has_is_bgr() const; void clear_is_bgr(); static const int kIsBgrFieldNumber = 15; bool is_bgr() const; void set_is_bgr(bool value); // @@protoc_insertion_point(class_scope:apollo.perception.camera.traffic_light.recognition.ClassifyParam) private: class HasBitSetters; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr model_name_; public: static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> _i_give_permission_to_break_this_code_default_model_type_; private: ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr model_type_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr input_blob_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr output_blob_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr weight_file_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr proto_file_; float classify_threshold_; ::PROTOBUF_NAMESPACE_ID::int32 classify_resize_width_; ::PROTOBUF_NAMESPACE_ID::int32 classify_resize_height_; float scale_; float mean_b_; float mean_g_; float mean_r_; bool is_bgr_; friend struct ::TableStruct_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto; }; // ------------------------------------------------------------------- class RecognizeBoxParam : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam) */ { public: RecognizeBoxParam(); virtual ~RecognizeBoxParam(); RecognizeBoxParam(const RecognizeBoxParam& from); RecognizeBoxParam(RecognizeBoxParam&& from) noexcept : RecognizeBoxParam() { *this = ::std::move(from); } inline RecognizeBoxParam& operator=(const RecognizeBoxParam& from) { CopyFrom(from); return *this; } inline RecognizeBoxParam& operator=(RecognizeBoxParam&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const RecognizeBoxParam& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const RecognizeBoxParam* internal_default_instance() { return reinterpret_cast<const RecognizeBoxParam*>( &_RecognizeBoxParam_default_instance_); } static constexpr int kIndexInFileMessages = 1; void Swap(RecognizeBoxParam* other); friend void swap(RecognizeBoxParam& a, RecognizeBoxParam& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline RecognizeBoxParam* New() const final { return CreateMaybeMessage<RecognizeBoxParam>(nullptr); } RecognizeBoxParam* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<RecognizeBoxParam>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const RecognizeBoxParam& from); void MergeFrom(const RecognizeBoxParam& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; #else bool MergePartialFromCodedStream( ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final; #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final; ::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray( ::PROTOBUF_NAMESPACE_ID::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(RecognizeBoxParam* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto); return ::descriptor_table_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional .apollo.perception.camera.traffic_light.recognition.ClassifyParam vertical_model = 1; bool has_vertical_model() const; void clear_vertical_model(); static const int kVerticalModelFieldNumber = 1; const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam& vertical_model() const; ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* release_vertical_model(); ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* mutable_vertical_model(); void set_allocated_vertical_model(::apollo::perception::camera::traffic_light::recognition::ClassifyParam* vertical_model); // optional .apollo.perception.camera.traffic_light.recognition.ClassifyParam quadrate_model = 2; bool has_quadrate_model() const; void clear_quadrate_model(); static const int kQuadrateModelFieldNumber = 2; const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam& quadrate_model() const; ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* release_quadrate_model(); ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* mutable_quadrate_model(); void set_allocated_quadrate_model(::apollo::perception::camera::traffic_light::recognition::ClassifyParam* quadrate_model); // optional .apollo.perception.camera.traffic_light.recognition.ClassifyParam horizontal_model = 3; bool has_horizontal_model() const; void clear_horizontal_model(); static const int kHorizontalModelFieldNumber = 3; const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam& horizontal_model() const; ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* release_horizontal_model(); ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* mutable_horizontal_model(); void set_allocated_horizontal_model(::apollo::perception::camera::traffic_light::recognition::ClassifyParam* horizontal_model); // @@protoc_insertion_point(class_scope:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam) private: class HasBitSetters; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* vertical_model_; ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* quadrate_model_; ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* horizontal_model_; friend struct ::TableStruct_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // ClassifyParam // optional string model_name = 1; inline bool ClassifyParam::has_model_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void ClassifyParam::clear_model_name() { model_name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000001u; } inline const std::string& ClassifyParam::model_name() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_name) return model_name_.GetNoArena(); } inline void ClassifyParam::set_model_name(const std::string& value) { _has_bits_[0] |= 0x00000001u; model_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_name) } inline void ClassifyParam::set_model_name(std::string&& value) { _has_bits_[0] |= 0x00000001u; model_name_.SetNoArena( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_name) } inline void ClassifyParam::set_model_name(const char* value) { GOOGLE_DCHECK(value != nullptr); _has_bits_[0] |= 0x00000001u; model_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_name) } inline void ClassifyParam::set_model_name(const char* value, size_t size) { _has_bits_[0] |= 0x00000001u; model_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_name) } inline std::string* ClassifyParam::mutable_model_name() { _has_bits_[0] |= 0x00000001u; // @@protoc_insertion_point(field_mutable:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_name) return model_name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline std::string* ClassifyParam::release_model_name() { // @@protoc_insertion_point(field_release:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_name) if (!has_model_name()) { return nullptr; } _has_bits_[0] &= ~0x00000001u; return model_name_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline void ClassifyParam::set_allocated_model_name(std::string* model_name) { if (model_name != nullptr) { _has_bits_[0] |= 0x00000001u; } else { _has_bits_[0] &= ~0x00000001u; } model_name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), model_name); // @@protoc_insertion_point(field_set_allocated:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_name) } // optional string model_type = 2 [default = "CaffeNet"]; inline bool ClassifyParam::has_model_type() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void ClassifyParam::clear_model_type() { model_type_.ClearToDefaultNoArena(&::apollo::perception::camera::traffic_light::recognition::ClassifyParam::_i_give_permission_to_break_this_code_default_model_type_.get()); _has_bits_[0] &= ~0x00000002u; } inline const std::string& ClassifyParam::model_type() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_type) return model_type_.GetNoArena(); } inline void ClassifyParam::set_model_type(const std::string& value) { _has_bits_[0] |= 0x00000002u; model_type_.SetNoArena(&::apollo::perception::camera::traffic_light::recognition::ClassifyParam::_i_give_permission_to_break_this_code_default_model_type_.get(), value); // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_type) } inline void ClassifyParam::set_model_type(std::string&& value) { _has_bits_[0] |= 0x00000002u; model_type_.SetNoArena( &::apollo::perception::camera::traffic_light::recognition::ClassifyParam::_i_give_permission_to_break_this_code_default_model_type_.get(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_type) } inline void ClassifyParam::set_model_type(const char* value) { GOOGLE_DCHECK(value != nullptr); _has_bits_[0] |= 0x00000002u; model_type_.SetNoArena(&::apollo::perception::camera::traffic_light::recognition::ClassifyParam::_i_give_permission_to_break_this_code_default_model_type_.get(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_type) } inline void ClassifyParam::set_model_type(const char* value, size_t size) { _has_bits_[0] |= 0x00000002u; model_type_.SetNoArena(&::apollo::perception::camera::traffic_light::recognition::ClassifyParam::_i_give_permission_to_break_this_code_default_model_type_.get(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_type) } inline std::string* ClassifyParam::mutable_model_type() { _has_bits_[0] |= 0x00000002u; // @@protoc_insertion_point(field_mutable:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_type) return model_type_.MutableNoArena(&::apollo::perception::camera::traffic_light::recognition::ClassifyParam::_i_give_permission_to_break_this_code_default_model_type_.get()); } inline std::string* ClassifyParam::release_model_type() { // @@protoc_insertion_point(field_release:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_type) if (!has_model_type()) { return nullptr; } _has_bits_[0] &= ~0x00000002u; return model_type_.ReleaseNonDefaultNoArena(&::apollo::perception::camera::traffic_light::recognition::ClassifyParam::_i_give_permission_to_break_this_code_default_model_type_.get()); } inline void ClassifyParam::set_allocated_model_type(std::string* model_type) { if (model_type != nullptr) { _has_bits_[0] |= 0x00000002u; } else { _has_bits_[0] &= ~0x00000002u; } model_type_.SetAllocatedNoArena(&::apollo::perception::camera::traffic_light::recognition::ClassifyParam::_i_give_permission_to_break_this_code_default_model_type_.get(), model_type); // @@protoc_insertion_point(field_set_allocated:apollo.perception.camera.traffic_light.recognition.ClassifyParam.model_type) } // optional string input_blob = 3; inline bool ClassifyParam::has_input_blob() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void ClassifyParam::clear_input_blob() { input_blob_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000004u; } inline const std::string& ClassifyParam::input_blob() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.input_blob) return input_blob_.GetNoArena(); } inline void ClassifyParam::set_input_blob(const std::string& value) { _has_bits_[0] |= 0x00000004u; input_blob_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.input_blob) } inline void ClassifyParam::set_input_blob(std::string&& value) { _has_bits_[0] |= 0x00000004u; input_blob_.SetNoArena( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:apollo.perception.camera.traffic_light.recognition.ClassifyParam.input_blob) } inline void ClassifyParam::set_input_blob(const char* value) { GOOGLE_DCHECK(value != nullptr); _has_bits_[0] |= 0x00000004u; input_blob_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.perception.camera.traffic_light.recognition.ClassifyParam.input_blob) } inline void ClassifyParam::set_input_blob(const char* value, size_t size) { _has_bits_[0] |= 0x00000004u; input_blob_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.perception.camera.traffic_light.recognition.ClassifyParam.input_blob) } inline std::string* ClassifyParam::mutable_input_blob() { _has_bits_[0] |= 0x00000004u; // @@protoc_insertion_point(field_mutable:apollo.perception.camera.traffic_light.recognition.ClassifyParam.input_blob) return input_blob_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline std::string* ClassifyParam::release_input_blob() { // @@protoc_insertion_point(field_release:apollo.perception.camera.traffic_light.recognition.ClassifyParam.input_blob) if (!has_input_blob()) { return nullptr; } _has_bits_[0] &= ~0x00000004u; return input_blob_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline void ClassifyParam::set_allocated_input_blob(std::string* input_blob) { if (input_blob != nullptr) { _has_bits_[0] |= 0x00000004u; } else { _has_bits_[0] &= ~0x00000004u; } input_blob_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), input_blob); // @@protoc_insertion_point(field_set_allocated:apollo.perception.camera.traffic_light.recognition.ClassifyParam.input_blob) } // optional string output_blob = 4; inline bool ClassifyParam::has_output_blob() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void ClassifyParam::clear_output_blob() { output_blob_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000008u; } inline const std::string& ClassifyParam::output_blob() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.output_blob) return output_blob_.GetNoArena(); } inline void ClassifyParam::set_output_blob(const std::string& value) { _has_bits_[0] |= 0x00000008u; output_blob_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.output_blob) } inline void ClassifyParam::set_output_blob(std::string&& value) { _has_bits_[0] |= 0x00000008u; output_blob_.SetNoArena( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:apollo.perception.camera.traffic_light.recognition.ClassifyParam.output_blob) } inline void ClassifyParam::set_output_blob(const char* value) { GOOGLE_DCHECK(value != nullptr); _has_bits_[0] |= 0x00000008u; output_blob_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.perception.camera.traffic_light.recognition.ClassifyParam.output_blob) } inline void ClassifyParam::set_output_blob(const char* value, size_t size) { _has_bits_[0] |= 0x00000008u; output_blob_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.perception.camera.traffic_light.recognition.ClassifyParam.output_blob) } inline std::string* ClassifyParam::mutable_output_blob() { _has_bits_[0] |= 0x00000008u; // @@protoc_insertion_point(field_mutable:apollo.perception.camera.traffic_light.recognition.ClassifyParam.output_blob) return output_blob_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline std::string* ClassifyParam::release_output_blob() { // @@protoc_insertion_point(field_release:apollo.perception.camera.traffic_light.recognition.ClassifyParam.output_blob) if (!has_output_blob()) { return nullptr; } _has_bits_[0] &= ~0x00000008u; return output_blob_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline void ClassifyParam::set_allocated_output_blob(std::string* output_blob) { if (output_blob != nullptr) { _has_bits_[0] |= 0x00000008u; } else { _has_bits_[0] &= ~0x00000008u; } output_blob_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), output_blob); // @@protoc_insertion_point(field_set_allocated:apollo.perception.camera.traffic_light.recognition.ClassifyParam.output_blob) } // optional string weight_file = 5; inline bool ClassifyParam::has_weight_file() const { return (_has_bits_[0] & 0x00000010u) != 0; } inline void ClassifyParam::clear_weight_file() { weight_file_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000010u; } inline const std::string& ClassifyParam::weight_file() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.weight_file) return weight_file_.GetNoArena(); } inline void ClassifyParam::set_weight_file(const std::string& value) { _has_bits_[0] |= 0x00000010u; weight_file_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.weight_file) } inline void ClassifyParam::set_weight_file(std::string&& value) { _has_bits_[0] |= 0x00000010u; weight_file_.SetNoArena( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:apollo.perception.camera.traffic_light.recognition.ClassifyParam.weight_file) } inline void ClassifyParam::set_weight_file(const char* value) { GOOGLE_DCHECK(value != nullptr); _has_bits_[0] |= 0x00000010u; weight_file_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.perception.camera.traffic_light.recognition.ClassifyParam.weight_file) } inline void ClassifyParam::set_weight_file(const char* value, size_t size) { _has_bits_[0] |= 0x00000010u; weight_file_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.perception.camera.traffic_light.recognition.ClassifyParam.weight_file) } inline std::string* ClassifyParam::mutable_weight_file() { _has_bits_[0] |= 0x00000010u; // @@protoc_insertion_point(field_mutable:apollo.perception.camera.traffic_light.recognition.ClassifyParam.weight_file) return weight_file_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline std::string* ClassifyParam::release_weight_file() { // @@protoc_insertion_point(field_release:apollo.perception.camera.traffic_light.recognition.ClassifyParam.weight_file) if (!has_weight_file()) { return nullptr; } _has_bits_[0] &= ~0x00000010u; return weight_file_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline void ClassifyParam::set_allocated_weight_file(std::string* weight_file) { if (weight_file != nullptr) { _has_bits_[0] |= 0x00000010u; } else { _has_bits_[0] &= ~0x00000010u; } weight_file_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), weight_file); // @@protoc_insertion_point(field_set_allocated:apollo.perception.camera.traffic_light.recognition.ClassifyParam.weight_file) } // optional string proto_file = 6; inline bool ClassifyParam::has_proto_file() const { return (_has_bits_[0] & 0x00000020u) != 0; } inline void ClassifyParam::clear_proto_file() { proto_file_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); _has_bits_[0] &= ~0x00000020u; } inline const std::string& ClassifyParam::proto_file() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.proto_file) return proto_file_.GetNoArena(); } inline void ClassifyParam::set_proto_file(const std::string& value) { _has_bits_[0] |= 0x00000020u; proto_file_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.proto_file) } inline void ClassifyParam::set_proto_file(std::string&& value) { _has_bits_[0] |= 0x00000020u; proto_file_.SetNoArena( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:apollo.perception.camera.traffic_light.recognition.ClassifyParam.proto_file) } inline void ClassifyParam::set_proto_file(const char* value) { GOOGLE_DCHECK(value != nullptr); _has_bits_[0] |= 0x00000020u; proto_file_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:apollo.perception.camera.traffic_light.recognition.ClassifyParam.proto_file) } inline void ClassifyParam::set_proto_file(const char* value, size_t size) { _has_bits_[0] |= 0x00000020u; proto_file_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:apollo.perception.camera.traffic_light.recognition.ClassifyParam.proto_file) } inline std::string* ClassifyParam::mutable_proto_file() { _has_bits_[0] |= 0x00000020u; // @@protoc_insertion_point(field_mutable:apollo.perception.camera.traffic_light.recognition.ClassifyParam.proto_file) return proto_file_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline std::string* ClassifyParam::release_proto_file() { // @@protoc_insertion_point(field_release:apollo.perception.camera.traffic_light.recognition.ClassifyParam.proto_file) if (!has_proto_file()) { return nullptr; } _has_bits_[0] &= ~0x00000020u; return proto_file_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline void ClassifyParam::set_allocated_proto_file(std::string* proto_file) { if (proto_file != nullptr) { _has_bits_[0] |= 0x00000020u; } else { _has_bits_[0] &= ~0x00000020u; } proto_file_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), proto_file); // @@protoc_insertion_point(field_set_allocated:apollo.perception.camera.traffic_light.recognition.ClassifyParam.proto_file) } // optional float classify_threshold = 7; inline bool ClassifyParam::has_classify_threshold() const { return (_has_bits_[0] & 0x00000040u) != 0; } inline void ClassifyParam::clear_classify_threshold() { classify_threshold_ = 0; _has_bits_[0] &= ~0x00000040u; } inline float ClassifyParam::classify_threshold() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.classify_threshold) return classify_threshold_; } inline void ClassifyParam::set_classify_threshold(float value) { _has_bits_[0] |= 0x00000040u; classify_threshold_ = value; // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.classify_threshold) } // optional int32 classify_resize_width = 8; inline bool ClassifyParam::has_classify_resize_width() const { return (_has_bits_[0] & 0x00000080u) != 0; } inline void ClassifyParam::clear_classify_resize_width() { classify_resize_width_ = 0; _has_bits_[0] &= ~0x00000080u; } inline ::PROTOBUF_NAMESPACE_ID::int32 ClassifyParam::classify_resize_width() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.classify_resize_width) return classify_resize_width_; } inline void ClassifyParam::set_classify_resize_width(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000080u; classify_resize_width_ = value; // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.classify_resize_width) } // optional int32 classify_resize_height = 9; inline bool ClassifyParam::has_classify_resize_height() const { return (_has_bits_[0] & 0x00000100u) != 0; } inline void ClassifyParam::clear_classify_resize_height() { classify_resize_height_ = 0; _has_bits_[0] &= ~0x00000100u; } inline ::PROTOBUF_NAMESPACE_ID::int32 ClassifyParam::classify_resize_height() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.classify_resize_height) return classify_resize_height_; } inline void ClassifyParam::set_classify_resize_height(::PROTOBUF_NAMESPACE_ID::int32 value) { _has_bits_[0] |= 0x00000100u; classify_resize_height_ = value; // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.classify_resize_height) } // optional float scale = 10; inline bool ClassifyParam::has_scale() const { return (_has_bits_[0] & 0x00000200u) != 0; } inline void ClassifyParam::clear_scale() { scale_ = 0; _has_bits_[0] &= ~0x00000200u; } inline float ClassifyParam::scale() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.scale) return scale_; } inline void ClassifyParam::set_scale(float value) { _has_bits_[0] |= 0x00000200u; scale_ = value; // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.scale) } // optional float mean_b = 12 [default = 95]; inline bool ClassifyParam::has_mean_b() const { return (_has_bits_[0] & 0x00000400u) != 0; } inline void ClassifyParam::clear_mean_b() { mean_b_ = 95; _has_bits_[0] &= ~0x00000400u; } inline float ClassifyParam::mean_b() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.mean_b) return mean_b_; } inline void ClassifyParam::set_mean_b(float value) { _has_bits_[0] |= 0x00000400u; mean_b_ = value; // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.mean_b) } // optional float mean_g = 13 [default = 99]; inline bool ClassifyParam::has_mean_g() const { return (_has_bits_[0] & 0x00000800u) != 0; } inline void ClassifyParam::clear_mean_g() { mean_g_ = 99; _has_bits_[0] &= ~0x00000800u; } inline float ClassifyParam::mean_g() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.mean_g) return mean_g_; } inline void ClassifyParam::set_mean_g(float value) { _has_bits_[0] |= 0x00000800u; mean_g_ = value; // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.mean_g) } // optional float mean_r = 14 [default = 96]; inline bool ClassifyParam::has_mean_r() const { return (_has_bits_[0] & 0x00001000u) != 0; } inline void ClassifyParam::clear_mean_r() { mean_r_ = 96; _has_bits_[0] &= ~0x00001000u; } inline float ClassifyParam::mean_r() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.mean_r) return mean_r_; } inline void ClassifyParam::set_mean_r(float value) { _has_bits_[0] |= 0x00001000u; mean_r_ = value; // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.mean_r) } // optional bool is_bgr = 15 [default = true]; inline bool ClassifyParam::has_is_bgr() const { return (_has_bits_[0] & 0x00002000u) != 0; } inline void ClassifyParam::clear_is_bgr() { is_bgr_ = true; _has_bits_[0] &= ~0x00002000u; } inline bool ClassifyParam::is_bgr() const { // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.ClassifyParam.is_bgr) return is_bgr_; } inline void ClassifyParam::set_is_bgr(bool value) { _has_bits_[0] |= 0x00002000u; is_bgr_ = value; // @@protoc_insertion_point(field_set:apollo.perception.camera.traffic_light.recognition.ClassifyParam.is_bgr) } // ------------------------------------------------------------------- // RecognizeBoxParam // optional .apollo.perception.camera.traffic_light.recognition.ClassifyParam vertical_model = 1; inline bool RecognizeBoxParam::has_vertical_model() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void RecognizeBoxParam::clear_vertical_model() { if (vertical_model_ != nullptr) vertical_model_->Clear(); _has_bits_[0] &= ~0x00000001u; } inline const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam& RecognizeBoxParam::vertical_model() const { const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* p = vertical_model_; // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.vertical_model) return p != nullptr ? *p : *reinterpret_cast<const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam*>( &::apollo::perception::camera::traffic_light::recognition::_ClassifyParam_default_instance_); } inline ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* RecognizeBoxParam::release_vertical_model() { // @@protoc_insertion_point(field_release:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.vertical_model) _has_bits_[0] &= ~0x00000001u; ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* temp = vertical_model_; vertical_model_ = nullptr; return temp; } inline ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* RecognizeBoxParam::mutable_vertical_model() { _has_bits_[0] |= 0x00000001u; if (vertical_model_ == nullptr) { auto* p = CreateMaybeMessage<::apollo::perception::camera::traffic_light::recognition::ClassifyParam>(GetArenaNoVirtual()); vertical_model_ = p; } // @@protoc_insertion_point(field_mutable:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.vertical_model) return vertical_model_; } inline void RecognizeBoxParam::set_allocated_vertical_model(::apollo::perception::camera::traffic_light::recognition::ClassifyParam* vertical_model) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete vertical_model_; } if (vertical_model) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { vertical_model = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, vertical_model, submessage_arena); } _has_bits_[0] |= 0x00000001u; } else { _has_bits_[0] &= ~0x00000001u; } vertical_model_ = vertical_model; // @@protoc_insertion_point(field_set_allocated:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.vertical_model) } // optional .apollo.perception.camera.traffic_light.recognition.ClassifyParam quadrate_model = 2; inline bool RecognizeBoxParam::has_quadrate_model() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void RecognizeBoxParam::clear_quadrate_model() { if (quadrate_model_ != nullptr) quadrate_model_->Clear(); _has_bits_[0] &= ~0x00000002u; } inline const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam& RecognizeBoxParam::quadrate_model() const { const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* p = quadrate_model_; // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.quadrate_model) return p != nullptr ? *p : *reinterpret_cast<const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam*>( &::apollo::perception::camera::traffic_light::recognition::_ClassifyParam_default_instance_); } inline ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* RecognizeBoxParam::release_quadrate_model() { // @@protoc_insertion_point(field_release:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.quadrate_model) _has_bits_[0] &= ~0x00000002u; ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* temp = quadrate_model_; quadrate_model_ = nullptr; return temp; } inline ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* RecognizeBoxParam::mutable_quadrate_model() { _has_bits_[0] |= 0x00000002u; if (quadrate_model_ == nullptr) { auto* p = CreateMaybeMessage<::apollo::perception::camera::traffic_light::recognition::ClassifyParam>(GetArenaNoVirtual()); quadrate_model_ = p; } // @@protoc_insertion_point(field_mutable:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.quadrate_model) return quadrate_model_; } inline void RecognizeBoxParam::set_allocated_quadrate_model(::apollo::perception::camera::traffic_light::recognition::ClassifyParam* quadrate_model) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete quadrate_model_; } if (quadrate_model) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { quadrate_model = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, quadrate_model, submessage_arena); } _has_bits_[0] |= 0x00000002u; } else { _has_bits_[0] &= ~0x00000002u; } quadrate_model_ = quadrate_model; // @@protoc_insertion_point(field_set_allocated:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.quadrate_model) } // optional .apollo.perception.camera.traffic_light.recognition.ClassifyParam horizontal_model = 3; inline bool RecognizeBoxParam::has_horizontal_model() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void RecognizeBoxParam::clear_horizontal_model() { if (horizontal_model_ != nullptr) horizontal_model_->Clear(); _has_bits_[0] &= ~0x00000004u; } inline const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam& RecognizeBoxParam::horizontal_model() const { const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* p = horizontal_model_; // @@protoc_insertion_point(field_get:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.horizontal_model) return p != nullptr ? *p : *reinterpret_cast<const ::apollo::perception::camera::traffic_light::recognition::ClassifyParam*>( &::apollo::perception::camera::traffic_light::recognition::_ClassifyParam_default_instance_); } inline ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* RecognizeBoxParam::release_horizontal_model() { // @@protoc_insertion_point(field_release:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.horizontal_model) _has_bits_[0] &= ~0x00000004u; ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* temp = horizontal_model_; horizontal_model_ = nullptr; return temp; } inline ::apollo::perception::camera::traffic_light::recognition::ClassifyParam* RecognizeBoxParam::mutable_horizontal_model() { _has_bits_[0] |= 0x00000004u; if (horizontal_model_ == nullptr) { auto* p = CreateMaybeMessage<::apollo::perception::camera::traffic_light::recognition::ClassifyParam>(GetArenaNoVirtual()); horizontal_model_ = p; } // @@protoc_insertion_point(field_mutable:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.horizontal_model) return horizontal_model_; } inline void RecognizeBoxParam::set_allocated_horizontal_model(::apollo::perception::camera::traffic_light::recognition::ClassifyParam* horizontal_model) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete horizontal_model_; } if (horizontal_model) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { horizontal_model = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, horizontal_model, submessage_arena); } _has_bits_[0] |= 0x00000004u; } else { _has_bits_[0] &= ~0x00000004u; } horizontal_model_ = horizontal_model; // @@protoc_insertion_point(field_set_allocated:apollo.perception.camera.traffic_light.recognition.RecognizeBoxParam.horizontal_model) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace recognition } // namespace traffic_light } // namespace camera } // namespace perception } // namespace apollo // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_modules_2fperception_2fcamera_2flib_2ftraffic_5flight_2fdetector_2frecognition_2fproto_2frecognition_2eproto
0952703e709fe309bdfb796c853865099fbe3f91
8034c3f9f500d3d150529b8098f3013b4afced56
/Leetcode 30 Days June/Week 3/PermutationSequence.cpp
35e19e7e43e1b6349059d0aac250c7bebeef0621
[]
no_license
jumbagenii/CP-DSA-Cpp-C
e6b6c366d77cbab4fc5002275da662c9948c14ba
7c816d35b964c1e69197652067aed08555064b7f
refs/heads/master
2023-08-12T13:52:58.846452
2021-10-01T20:14:29
2021-10-01T20:14:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
610
cpp
PermutationSequence.cpp
class Solution { public: string getPermutation(int n, int k) { int fact_n = 1; string s = ""; for (int i = 1; i <= n; i++) { fact_n *= i; s += (char)(i + 48); } int k_index = k - 1; string ans = ""; while (k_index) { int n = s.size(); fact_n /= n; int index = (k_index / fact_n); ans += s[index]; k_index -= (index * fact_n); s = s.substr(0, index) + s.substr(index + 1); } ans += s; return ans; } };
ad5c03dab164f3081a04e09ec7fe749fd98d72c6
5d06523d5c6da5f877e209d6d6dbfe45f5900f87
/ConApp7_Test_edge/ConApp7_Test_edge/ConApp7_Test_edge.cpp
0872dda6cb0fe994725c463f1c7d62591a47c0db
[]
no_license
snandi76/Beautiful_CPP
9b889eb82ee8db687237a2eefa0f1fbccc826fa2
6f3107ade910c7a98106c027468db929f55ee678
refs/heads/master
2020-04-16T15:26:28.155375
2019-01-20T11:56:04
2019-01-20T11:56:04
165,702,829
0
0
null
null
null
null
UTF-8
C++
false
false
1,440
cpp
ConApp7_Test_edge.cpp
//perfect power #include "stdafx.h" #include<iostream> #include<map> using namespace std; void ListPrimefactor(map<int, int> &mapPower, int &num) { int iResult = num; while (iResult % 2 == 0) { auto it = mapPower.find(2); if (it == mapPower.end()) { mapPower.insert(pair<int, int>(2, 1)); } else { mapPower[2] = mapPower[2] + 1; } iResult = iResult / 2; } for (int i = 3; i <= sqrt(iResult); i++) { while (iResult%i == 0) { auto it = mapPower.find(i); if (it == mapPower.end()) { mapPower.insert(pair<int, int>(i, 1)); } else { mapPower[i] = mapPower[i] + 1; } iResult = iResult / i; } } if (iResult > 2) { auto it = mapPower.find(iResult); if (it == mapPower.end()) { mapPower.insert(pair<int, int>(iResult, 1)); } else { mapPower[iResult] = mapPower[iResult] + 1; } } } int gcd(int n1, int n2) { while (n1 != n2) { if (n1 > n2) n1 = n2 - n1; else n2 = n2 - n1; } return n1; } int GetGcd(map<int, int> &mapPower) { int iResult = mapPower.begin()->second; if (mapPower.size() == 1) return iResult; for (auto i : mapPower) { iResult = gcd(i.second, iResult); } return iResult; } int main() { map<int, int> mapPower; int num = 256; ListPrimefactor(mapPower, num); if (GetGcd(mapPower) > 1) cout << "perfect power"; for (auto i : mapPower) cout << i.first << "^+" << i.second << "^+"; return 0; }
45cb169ff89f24867ec5e586c8a96f0dcf9791d8
2b8e237170f3ff77ad18cb7234b1005e7f52f2ca
/test_catch/tests/test_lib.cpp
69b93342b54edb482f89f28f3e0411d2ce90e600
[]
no_license
niosus/c-tests
59b735b417cb7d45deeca42d274da26e051aa38d
f319ed4121043da21c97901396086004c4d890f5
refs/heads/master
2021-01-21T01:50:18.439197
2016-06-14T14:54:57
2016-06-14T14:54:57
55,141,919
0
0
null
null
null
null
UTF-8
C++
false
false
168
cpp
test_lib.cpp
#include "catch.hpp" #include "../lib.h" TEST_CASE("one", "[lib]") { REQUIRE(get_me_one() == 1); } TEST_CASE("hello", "[lib]") { REQUIRE(get_me_hello() == "hello"); }
8c033bb01bd817a12063a86aeeafe2b0f31a8181
17a41dcec3b1678d99a5113dbe69ff7e64830c5a
/XeytanWxPPClient/XeytanWxPPClient/main.cpp
1f02bc7ce5c0e8e0e71b15edf0d85eb7eb7217e1
[]
no_license
morole/XeytanWxCpp-RAT
a0e018355700e2de45d1b7437135d330316f52e1
4d608efca127bc2c922839a075753fd2b07c770d
refs/heads/master
2022-04-09T06:41:17.494698
2019-09-13T08:28:48
2019-09-13T08:28:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
961
cpp
main.cpp
#include "Application.h" #include "appdefs.h" #ifdef XEYTAN_WINDOWS #pragma comment(lib, "comctl32.lib") #pragma comment(lib, "Rpcrt4.lib") #pragma comment(lib, "ws2_32.lib") #endif wxIMPLEMENT_APP_NO_MAIN(Application); void test() { /* std::shared_ptr<PacketProcess> packet = std::make_shared<PacketProcess>(); Process process; process.path = "C:/Windows/System32/calc.exe"; process.pid = 3210; process.title = "Calculator"; packet->processes.push_back(process); std::ostringstream oss; { cereal::BinaryOutputArchive oarchive(oss); oarchive(packet); } std::string serializedStr = oss.str(); std::shared_ptr<PacketProcess> restored; { std::istringstream is(serializedStr); cereal::BinaryInputArchive iarchive(is); iarchive(restored); } */ } int main(int argc, char** argv) { test(); wxEntryStart(argc, argv); wxTheApp->CallOnInit(); ((Application*)wxTheApp)->run(); wxTheApp->OnExit(); wxEntryCleanup(); return 0; }
f8bbe5e34c59aca91015533b45c95131709928b4
7fccb87e0640df7f9bfc33ae123a99f723a3411a
/OrderBook/types.h
608a22243eea2b03db99e28b6785c784d1143a8f
[]
no_license
hmunjuluri/MyOrderBook
729383e5ea94c2498b5429f4657aed72189bc3f2
4c1678f83bb46b360e99ca392fecfc9bcc087553
refs/heads/master
2021-04-28T13:35:34.644193
2018-02-19T21:18:48
2018-02-19T21:18:48
122,107,626
1
0
null
null
null
null
UTF-8
C++
false
false
559
h
types.h
// // Created by Hanuma Munjuluri on 2/19/18. // #pragma once #include <boost/serialization/strong_typedef.hpp> #include <limits> #include <string> #include <stdint.h> typedef unsigned long OrderId; typedef unsigned long Size; typedef unsigned short Price; typedef std::string Symbol; enum class Side {ASK,BID}; typedef struct { Side side; Price price; Size size; } Order; typedef struct { Symbol symbol; OrderId orderId; } SymbolOrderId; const Price MAX_PRICE = std::numeric_limits<Price>::max(); const Price MIN_PRICE = Price(1);
22972465557576d795119475f73d58e9918abdb5
83b8a9e0ba13a792f44fca455ba01043b9a81c78
/201910/201910/BOJ_2056.cpp
d247efddde2f3a6a21dcef3a067794804388f634
[]
no_license
BoGyuPark/VS_BOJ
0799a0c62fd72a6fc1e6f7e34fc539a742c0782b
965973600dedbd5f3032c3adb4b117cc43c62a8f
refs/heads/master
2020-04-14T12:45:53.930735
2019-12-04T03:06:44
2019-12-04T03:06:44
163,849,994
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
928
cpp
BOJ_2056.cpp
/* BOJ 2056 ÀÛ¾÷*/ #include<iostream> #include<queue> #include<algorithm> #include<vector> using namespace std; int n, wight, w[10001], m, t, indegree[10001], ans; int accW[10001]; vector<vector<int>> v; queue<int> q; void topologicalSort() { for (int i = 1; i <= n; i++) { if (indegree[i] == 0) q.push(i); accW[i] = w[i]; ans = max(ans, accW[i]); } while (!q.empty()) { int now = q.front(); q.pop(); for (int i = 0; i < v[now].size(); i++) { int next = v[now][i]; indegree[next]--; accW[next] = max(accW[next], accW[now] + w[next]); ans = max(accW[next], ans); if (indegree[next] == 0) { q.push(next); } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n; v.resize(n + 1); for (int i = 1; i <= n; i++) { cin >> w[i]; cin >> m; indegree[i] += m; for (int j = 0; j < m; j++) { cin >> t; v[t].push_back(i); } } topologicalSort(); cout << ans; }
1a063449b0830bb5ec584609cd8631580ea5cf2a
d9cda09d3a23309d1f6c72a3c934986a40408ee1
/datamahasiswa/Form2.h
54a82ea9d8858b316ee7df0e93b7330c020231a7
[]
no_license
guntur10/datamahasiswa
88e523602ebe3ffc1f24f7c293de4fc99f0ad011
1a47387ee978d4612bce785ac3db063c9e978ee1
refs/heads/master
2022-11-19T14:53:29.916557
2020-07-24T17:41:52
2020-07-24T17:41:52
282,276,243
0
0
null
null
null
null
UTF-8
C++
false
false
33,870
h
Form2.h
#pragma once #include "Form1.h" #include "Form2.h" #include "Form3.h" namespace datamahasiswa { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace MySql::Data::MySqlClient; /// <summary> /// Summary for Form2 /// </summary> public ref class Form2 : public System::Windows::Forms::Form { public: Form2(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Form2() { if (components) { delete components; } } String^ kelamin; private: System::Windows::Forms::Label^ label1; protected: private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::Label^ label4; private: System::Windows::Forms::Label^ label5; private: System::Windows::Forms::Label^ label6; private: System::Windows::Forms::TextBox^ textBox1; private: System::Windows::Forms::TextBox^ textBox2; private: System::Windows::Forms::TextBox^ textBox3; private: System::Windows::Forms::ComboBox^ comboBox1; private: System::Windows::Forms::Button^ button1; private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::Button^ button3; private: System::Windows::Forms::Button^ button4; private: System::Windows::Forms::GroupBox^ groupBox1; private: System::Windows::Forms::GroupBox^ groupBox2; private: System::Windows::Forms::TextBox^ textBox4; private: System::Windows::Forms::ComboBox^ comboBox2; private: System::Windows::Forms::Label^ label8; private: System::Windows::Forms::Label^ label7; private: System::Windows::Forms::TextBox^ textBox10; private: System::Windows::Forms::Label^ label14; private: System::Windows::Forms::TextBox^ textBox9; private: System::Windows::Forms::Label^ label13; private: System::Windows::Forms::TextBox^ textBox8; private: System::Windows::Forms::Label^ label12; private: System::Windows::Forms::TextBox^ textBox6; private: System::Windows::Forms::Label^ label10; private: System::Windows::Forms::TextBox^ textBox5; private: System::Windows::Forms::Label^ label9; private: System::Windows::Forms::DataGridView^ dataGridView1; private: System::Windows::Forms::RadioButton^ radioButton1; private: System::Windows::Forms::Button^ button6; private: System::Windows::Forms::Button^ button5; private: System::Windows::Forms::TextBox^ textBox7; private: System::Windows::Forms::Label^ label11; private: System::Windows::Forms::RadioButton^ radioButton2; private: System::Windows::Forms::Button^ button7; private: System::Windows::Forms::Button^ button8; private: System::Windows::Forms::TextBox^ textBox11; private: System::Windows::Forms::DateTimePicker^ dateTimePicker1; private: System::Windows::Forms::BindingSource^ bindingSource1; private: System::Windows::Forms::Button^ button9; private: System::ComponentModel::IContainer^ components; private: /// <summary> /// Required designer variable. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); this->label1 = (gcnew System::Windows::Forms::Label()); this->label2 = (gcnew System::Windows::Forms::Label()); this->label3 = (gcnew System::Windows::Forms::Label()); this->label4 = (gcnew System::Windows::Forms::Label()); this->label5 = (gcnew System::Windows::Forms::Label()); this->label6 = (gcnew System::Windows::Forms::Label()); this->textBox1 = (gcnew System::Windows::Forms::TextBox()); this->textBox2 = (gcnew System::Windows::Forms::TextBox()); this->textBox3 = (gcnew System::Windows::Forms::TextBox()); this->comboBox1 = (gcnew System::Windows::Forms::ComboBox()); this->button1 = (gcnew System::Windows::Forms::Button()); this->button2 = (gcnew System::Windows::Forms::Button()); this->button3 = (gcnew System::Windows::Forms::Button()); this->button4 = (gcnew System::Windows::Forms::Button()); this->groupBox1 = (gcnew System::Windows::Forms::GroupBox()); this->dateTimePicker1 = (gcnew System::Windows::Forms::DateTimePicker()); this->radioButton2 = (gcnew System::Windows::Forms::RadioButton()); this->radioButton1 = (gcnew System::Windows::Forms::RadioButton()); this->groupBox2 = (gcnew System::Windows::Forms::GroupBox()); this->button6 = (gcnew System::Windows::Forms::Button()); this->button5 = (gcnew System::Windows::Forms::Button()); this->textBox7 = (gcnew System::Windows::Forms::TextBox()); this->label11 = (gcnew System::Windows::Forms::Label()); this->textBox10 = (gcnew System::Windows::Forms::TextBox()); this->label14 = (gcnew System::Windows::Forms::Label()); this->textBox9 = (gcnew System::Windows::Forms::TextBox()); this->label13 = (gcnew System::Windows::Forms::Label()); this->textBox8 = (gcnew System::Windows::Forms::TextBox()); this->label12 = (gcnew System::Windows::Forms::Label()); this->textBox6 = (gcnew System::Windows::Forms::TextBox()); this->label10 = (gcnew System::Windows::Forms::Label()); this->textBox5 = (gcnew System::Windows::Forms::TextBox()); this->label9 = (gcnew System::Windows::Forms::Label()); this->textBox4 = (gcnew System::Windows::Forms::TextBox()); this->comboBox2 = (gcnew System::Windows::Forms::ComboBox()); this->label8 = (gcnew System::Windows::Forms::Label()); this->label7 = (gcnew System::Windows::Forms::Label()); this->dataGridView1 = (gcnew System::Windows::Forms::DataGridView()); this->button7 = (gcnew System::Windows::Forms::Button()); this->button8 = (gcnew System::Windows::Forms::Button()); this->textBox11 = (gcnew System::Windows::Forms::TextBox()); this->bindingSource1 = (gcnew System::Windows::Forms::BindingSource(this->components)); this->button9 = (gcnew System::Windows::Forms::Button()); this->groupBox1->SuspendLayout(); this->groupBox2->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dataGridView1))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->bindingSource1))->BeginInit(); this->SuspendLayout(); // // label1 // this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(22, 43); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(82, 13); this->label1->TabIndex = 0; this->label1->Text = L"No Pendaftaran"; // // label2 // this->label2->AutoSize = true; this->label2->Location = System::Drawing::Point(22, 77); this->label2->Name = L"label2"; this->label2->Size = System::Drawing::Size(80, 13); this->label2->TabIndex = 1; this->label2->Text = L"Nama Lengkap"; // // label3 // this->label3->AutoSize = true; this->label3->Location = System::Drawing::Point(22, 111); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(69, 13); this->label3->TabIndex = 2; this->label3->Text = L"Tempat Lahir"; // // label4 // this->label4->AutoSize = true; this->label4->Location = System::Drawing::Point(22, 145); this->label4->Name = L"label4"; this->label4->Size = System::Drawing::Size(72, 13); this->label4->TabIndex = 3; this->label4->Text = L"Tanggal Lahir"; // // label5 // this->label5->AutoSize = true; this->label5->Location = System::Drawing::Point(22, 179); this->label5->Name = L"label5"; this->label5->Size = System::Drawing::Size(40, 13); this->label5->TabIndex = 4; this->label5->Text = L"Agama"; // // label6 // this->label6->AutoSize = true; this->label6->Location = System::Drawing::Point(22, 214); this->label6->Name = L"label6"; this->label6->Size = System::Drawing::Size(71, 13); this->label6->TabIndex = 5; this->label6->Text = L"Jenis Kelamin"; this->label6->Click += gcnew System::EventHandler(this, &Form2::label6_Click); // // textBox1 // this->textBox1->Location = System::Drawing::Point(127, 40); this->textBox1->Name = L"textBox1"; this->textBox1->Size = System::Drawing::Size(192, 20); this->textBox1->TabIndex = 7; // // textBox2 // this->textBox2->Location = System::Drawing::Point(127, 74); this->textBox2->Name = L"textBox2"; this->textBox2->Size = System::Drawing::Size(192, 20); this->textBox2->TabIndex = 8; this->textBox2->TextChanged += gcnew System::EventHandler(this, &Form2::textBox2_TextChanged); // // textBox3 // this->textBox3->Location = System::Drawing::Point(127, 108); this->textBox3->Name = L"textBox3"; this->textBox3->Size = System::Drawing::Size(192, 20); this->textBox3->TabIndex = 9; // // comboBox1 // this->comboBox1->FormattingEnabled = true; this->comboBox1->Items->AddRange(gcnew cli::array< System::Object^ >(6) { L"Islam", L"Kristen Protestan", L"Katolik", L"Hindu", L"Buddha", L"Kong Hu Cu" }); this->comboBox1->Location = System::Drawing::Point(127, 176); this->comboBox1->Name = L"comboBox1"; this->comboBox1->Size = System::Drawing::Size(192, 21); this->comboBox1->TabIndex = 11; this->comboBox1->Text = L"Agama Anda"; this->comboBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &Form2::comboBox1_SelectedIndexChanged); // // button1 // this->button1->Location = System::Drawing::Point(566, 344); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(75, 23); this->button1->TabIndex = 0; this->button1->Text = L"Simpan"; this->button1->UseVisualStyleBackColor = true; this->button1->Click += gcnew System::EventHandler(this, &Form2::button1_Click); // // button2 // this->button2->Location = System::Drawing::Point(647, 344); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(75, 23); this->button2->TabIndex = 31; this->button2->Text = L"Hapus"; this->button2->UseVisualStyleBackColor = true; this->button2->Click += gcnew System::EventHandler(this, &Form2::button2_Click); // // button3 // this->button3->Location = System::Drawing::Point(728, 344); this->button3->Name = L"button3"; this->button3->Size = System::Drawing::Size(75, 23); this->button3->TabIndex = 32; this->button3->Text = L"Ubah"; this->button3->UseVisualStyleBackColor = true; this->button3->Click += gcnew System::EventHandler(this, &Form2::button3_Click); // // button4 // this->button4->Location = System::Drawing::Point(809, 344); this->button4->Name = L"button4"; this->button4->Size = System::Drawing::Size(75, 23); this->button4->TabIndex = 33; this->button4->Text = L"Keluar"; this->button4->UseVisualStyleBackColor = true; this->button4->Click += gcnew System::EventHandler(this, &Form2::button4_Click); // // groupBox1 // this->groupBox1->Controls->Add(this->dateTimePicker1); this->groupBox1->Controls->Add(this->radioButton2); this->groupBox1->Controls->Add(this->radioButton1); this->groupBox1->Controls->Add(this->comboBox1); this->groupBox1->Controls->Add(this->textBox3); this->groupBox1->Controls->Add(this->textBox2); this->groupBox1->Controls->Add(this->textBox1); this->groupBox1->Controls->Add(this->label6); this->groupBox1->Controls->Add(this->label5); this->groupBox1->Controls->Add(this->label4); this->groupBox1->Controls->Add(this->label3); this->groupBox1->Controls->Add(this->label2); this->groupBox1->Controls->Add(this->label1); this->groupBox1->Location = System::Drawing::Point(30, 25); this->groupBox1->Name = L"groupBox1"; this->groupBox1->Size = System::Drawing::Size(359, 285); this->groupBox1->TabIndex = 35; this->groupBox1->TabStop = false; this->groupBox1->Text = L"Data Mahasiswa"; // // dateTimePicker1 // this->dateTimePicker1->CustomFormat = L"yyyy-MM-dd"; this->dateTimePicker1->Format = System::Windows::Forms::DateTimePickerFormat::Custom; this->dateTimePicker1->Location = System::Drawing::Point(127, 143); this->dateTimePicker1->Name = L"dateTimePicker1"; this->dateTimePicker1->Size = System::Drawing::Size(192, 20); this->dateTimePicker1->TabIndex = 49; // // radioButton2 // this->radioButton2->AutoSize = true; this->radioButton2->Location = System::Drawing::Point(240, 212); this->radioButton2->Name = L"radioButton2"; this->radioButton2->Size = System::Drawing::Size(79, 17); this->radioButton2->TabIndex = 29; this->radioButton2->TabStop = true; this->radioButton2->Text = L"Perempuan"; this->radioButton2->UseVisualStyleBackColor = true; this->radioButton2->CheckedChanged += gcnew System::EventHandler(this, &Form2::radioButton2_CheckedChanged_1); // // radioButton1 // this->radioButton1->AutoSize = true; this->radioButton1->Location = System::Drawing::Point(127, 212); this->radioButton1->Name = L"radioButton1"; this->radioButton1->Size = System::Drawing::Size(68, 17); this->radioButton1->TabIndex = 28; this->radioButton1->TabStop = true; this->radioButton1->Text = L"Laki-Laki"; this->radioButton1->UseVisualStyleBackColor = true; this->radioButton1->CheckedChanged += gcnew System::EventHandler(this, &Form2::radioButton1_CheckedChanged_1); // // groupBox2 // this->groupBox2->Controls->Add(this->button6); this->groupBox2->Controls->Add(this->button5); this->groupBox2->Controls->Add(this->textBox7); this->groupBox2->Controls->Add(this->label11); this->groupBox2->Controls->Add(this->textBox10); this->groupBox2->Controls->Add(this->label14); this->groupBox2->Controls->Add(this->textBox9); this->groupBox2->Controls->Add(this->label13); this->groupBox2->Controls->Add(this->textBox8); this->groupBox2->Controls->Add(this->label12); this->groupBox2->Controls->Add(this->textBox6); this->groupBox2->Controls->Add(this->label10); this->groupBox2->Controls->Add(this->textBox5); this->groupBox2->Controls->Add(this->label9); this->groupBox2->Controls->Add(this->textBox4); this->groupBox2->Controls->Add(this->comboBox2); this->groupBox2->Controls->Add(this->label8); this->groupBox2->Controls->Add(this->label7); this->groupBox2->Location = System::Drawing::Point(412, 25); this->groupBox2->Name = L"groupBox2"; this->groupBox2->Size = System::Drawing::Size(737, 285); this->groupBox2->TabIndex = 36; this->groupBox2->TabStop = false; this->groupBox2->Text = L"Pembayaran"; // // button6 // this->button6->Location = System::Drawing::Point(574, 140); this->button6->Name = L"button6"; this->button6->Size = System::Drawing::Size(75, 23); this->button6->TabIndex = 38; this->button6->Text = L"Bayar"; this->button6->UseVisualStyleBackColor = true; this->button6->Click += gcnew System::EventHandler(this, &Form2::button6_Click); // // button5 // this->button5->Location = System::Drawing::Point(181, 208); this->button5->Name = L"button5"; this->button5->Size = System::Drawing::Size(75, 23); this->button5->TabIndex = 38; this->button5->Text = L"Hitung"; this->button5->UseVisualStyleBackColor = true; this->button5->Click += gcnew System::EventHandler(this, &Form2::button5_Click); // // textBox7 // this->textBox7->Location = System::Drawing::Point(127, 174); this->textBox7->Name = L"textBox7"; this->textBox7->ReadOnly = true; this->textBox7->Size = System::Drawing::Size(192, 20); this->textBox7->TabIndex = 48; // // label11 // this->label11->AutoSize = true; this->label11->Location = System::Drawing::Point(22, 177); this->label11->Name = L"label11"; this->label11->Size = System::Drawing::Size(101, 13); this->label11->TabIndex = 47; this->label11->Text = L"SPP Variabel / SKS"; // // textBox10 // this->textBox10->Location = System::Drawing::Point(515, 106); this->textBox10->Name = L"textBox10"; this->textBox10->ReadOnly = true; this->textBox10->Size = System::Drawing::Size(192, 20); this->textBox10->TabIndex = 46; // // label14 // this->label14->AutoSize = true; this->label14->Location = System::Drawing::Point(411, 109); this->label14->Name = L"label14"; this->label14->Size = System::Drawing::Size(62, 13); this->label14->TabIndex = 45; this->label14->Text = L"Keterangan"; // // textBox9 // this->textBox9->Location = System::Drawing::Point(515, 72); this->textBox9->Name = L"textBox9"; this->textBox9->Size = System::Drawing::Size(192, 20); this->textBox9->TabIndex = 44; // // label13 // this->label13->AutoSize = true; this->label13->Location = System::Drawing::Point(411, 75); this->label13->Name = L"label13"; this->label13->Size = System::Drawing::Size(61, 13); this->label13->TabIndex = 43; this->label13->Text = L"Uang Anda"; // // textBox8 // this->textBox8->Location = System::Drawing::Point(515, 37); this->textBox8->Name = L"textBox8"; this->textBox8->ReadOnly = true; this->textBox8->Size = System::Drawing::Size(192, 20); this->textBox8->TabIndex = 42; // // label12 // this->label12->AutoSize = true; this->label12->Location = System::Drawing::Point(411, 40); this->label12->Name = L"label12"; this->label12->Size = System::Drawing::Size(61, 13); this->label12->TabIndex = 41; this->label12->Text = L"Total Bayar"; // // textBox6 // this->textBox6->Location = System::Drawing::Point(127, 140); this->textBox6->Name = L"textBox6"; this->textBox6->ReadOnly = true; this->textBox6->Size = System::Drawing::Size(192, 20); this->textBox6->TabIndex = 40; // // label10 // this->label10->AutoSize = true; this->label10->Location = System::Drawing::Point(22, 143); this->label10->Name = L"label10"; this->label10->Size = System::Drawing::Size(59, 13); this->label10->TabIndex = 39; this->label10->Text = L"SPP Tetap"; // // textBox5 // this->textBox5->Location = System::Drawing::Point(127, 106); this->textBox5->Name = L"textBox5"; this->textBox5->ReadOnly = true; this->textBox5->Size = System::Drawing::Size(192, 20); this->textBox5->TabIndex = 38; this->textBox5->TextChanged += gcnew System::EventHandler(this, &Form2::textBox5_TextChanged); // // label9 // this->label9->AutoSize = true; this->label9->Location = System::Drawing::Point(22, 109); this->label9->Name = L"label9"; this->label9->Size = System::Drawing::Size(73, 13); this->label9->TabIndex = 37; this->label9->Text = L"Biaya Sarana "; // // textBox4 // this->textBox4->Location = System::Drawing::Point(127, 72); this->textBox4->Name = L"textBox4"; this->textBox4->Size = System::Drawing::Size(192, 20); this->textBox4->TabIndex = 36; this->textBox4->TextChanged += gcnew System::EventHandler(this, &Form2::textBox8_TextChanged); // // comboBox2 // this->comboBox2->FormattingEnabled = true; this->comboBox2->Items->AddRange(gcnew cli::array< System::Object^ >(10) { L"S1 - Sistem Informasi", L"S1 - Informatika", L"S1 - Teknik Komputer", L"S1 - Arsitektur", L"S1 - Geografi", L"S1 - Akuntansi", L"S1 - Ekonomi", L"S1 - Kewirausahaan", L"S1 - Hubungan Internasional", L"S1 - Ilmu Komunikasi" }); this->comboBox2->Location = System::Drawing::Point(127, 37); this->comboBox2->Name = L"comboBox2"; this->comboBox2->Size = System::Drawing::Size(192, 21); this->comboBox2->TabIndex = 35; this->comboBox2->Text = L"Pilih Jurusan"; this->comboBox2->SelectedIndexChanged += gcnew System::EventHandler(this, &Form2::comboBox2_SelectedIndexChanged_1); // // label8 // this->label8->AutoSize = true; this->label8->Location = System::Drawing::Point(22, 75); this->label8->Name = L"label8"; this->label8->Size = System::Drawing::Size(28, 13); this->label8->TabIndex = 2; this->label8->Text = L"SKS"; // // label7 // this->label7->AutoSize = true; this->label7->Location = System::Drawing::Point(22, 40); this->label7->Name = L"label7"; this->label7->Size = System::Drawing::Size(44, 13); this->label7->TabIndex = 1; this->label7->Text = L"Jurusan"; // // dataGridView1 // this->dataGridView1->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; this->dataGridView1->Location = System::Drawing::Point(30, 400); this->dataGridView1->Name = L"dataGridView1"; this->dataGridView1->Size = System::Drawing::Size(1119, 199); this->dataGridView1->TabIndex = 37; // // button7 // this->button7->Location = System::Drawing::Point(30, 371); this->button7->Name = L"button7"; this->button7->Size = System::Drawing::Size(75, 23); this->button7->TabIndex = 38; this->button7->Text = L"Cari"; this->button7->UseVisualStyleBackColor = true; this->button7->Click += gcnew System::EventHandler(this, &Form2::button7_Click); // // button8 // this->button8->Location = System::Drawing::Point(251, 371); this->button8->Name = L"button8"; this->button8->Size = System::Drawing::Size(75, 23); this->button8->TabIndex = 39; this->button8->Text = L"Refresh"; this->button8->UseVisualStyleBackColor = true; this->button8->Click += gcnew System::EventHandler(this, &Form2::button8_Click); // // textBox11 // this->textBox11->Location = System::Drawing::Point(111, 373); this->textBox11->Name = L"textBox11"; this->textBox11->Size = System::Drawing::Size(134, 20); this->textBox11->TabIndex = 49; // // button9 // this->button9->Location = System::Drawing::Point(412, 344); this->button9->Name = L"button9"; this->button9->Size = System::Drawing::Size(75, 23); this->button9->TabIndex = 50; this->button9->Text = L"Info"; this->button9->UseVisualStyleBackColor = true; this->button9->Click += gcnew System::EventHandler(this, &Form2::button9_Click); // // Form2 // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(1179, 692); this->Controls->Add(this->button9); this->Controls->Add(this->textBox11); this->Controls->Add(this->button8); this->Controls->Add(this->button7); this->Controls->Add(this->dataGridView1); this->Controls->Add(this->groupBox2); this->Controls->Add(this->groupBox1); this->Controls->Add(this->button4); this->Controls->Add(this->button3); this->Controls->Add(this->button2); this->Controls->Add(this->button1); this->Name = L"Form2"; this->Text = L"Data Mahasiswa & Pembayaran"; this->Load += gcnew System::EventHandler(this, &Form2::Form2_Load); this->groupBox1->ResumeLayout(false); this->groupBox1->PerformLayout(); this->groupBox2->ResumeLayout(false); this->groupBox2->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dataGridView1))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->bindingSource1))->EndInit(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void textBox2_TextChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void radioButton1_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void radioButton2_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void comboBox2_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { String^ constr = "Server=127.0.0.1;Uid=root;Pwd=;Database=datamahasiswa"; MySqlConnection^ con = gcnew MySqlConnection(constr); int no_pendaftaran = Int32::Parse(textBox1->Text); MySqlCommand^ cmd = gcnew MySqlCommand("delete from mahasiswa WHERE no_pendaftaran=" + no_pendaftaran + "", con); con->Open(); MySqlDataReader^ dr = cmd->ExecuteReader(); MessageBox::Show("Data Berhasil Dihapus"); con->Close(); } private: System::Void backgroundWorker1_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) { } private: System::Void listBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void groupBox1_Enter(System::Object^ sender, System::EventArgs^ e) { } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { try { String^ constr = "Server=127.0.0.1;Uid=root;Pwd=;Database=datamahasiswa"; MySqlConnection^ con = gcnew MySqlConnection(constr); int no_pendaftaran = Int32::Parse(textBox1->Text); String^ nama_lengkap = textBox2->Text; String^ tempat_lahir = textBox3->Text; String^ tanggal_lahir = dateTimePicker1->Text; String^ agama = comboBox1->Text; String^ jenis_kelamin = kelamin; String^ jurusan = comboBox2->Text; String^ sks = textBox4->Text; String^ biaya_sarana = textBox5->Text; String^ spp_tetap = textBox6->Text; String^ spp_variabel = textBox7->Text; String^ total_bayar = textBox8->Text; String^ uang_anda = textBox9->Text; String^ keterangan = textBox10->Text; MySqlCommand^ cmd = gcnew MySqlCommand("insert into mahasiswa values(" + no_pendaftaran + ",'" + nama_lengkap + "','" + tempat_lahir + "','" + tanggal_lahir + "','" + agama + "','" + jenis_kelamin + "','" + jurusan + "','" + sks + "','" + biaya_sarana + "','" + spp_tetap + "','" + spp_variabel + "','" + total_bayar + "','" + uang_anda + "','" + keterangan + "')", con); MySqlDataReader^ dr; con->Open(); dr = cmd->ExecuteReader(); MessageBox::Show("Data Berhasil Disimpan"); } catch (Exception^ ex) { MessageBox::Show(ex->Message); } } private: System::Void label9_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void Form2_Load(System::Object^ sender, System::EventArgs^ e) { } private: System::Void comboBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { } int biayasarana; int spptetap; int sppvariabel; double total; private: System::Void comboBox2_SelectedIndexChanged_1(System::Object^ sender, System::EventArgs^ e) { if (comboBox2->Text == "S1 - Sistem Informasi") { biayasarana = 19000000; textBox5->Text = biayasarana.ToString(); spptetap = 2000000; textBox6->Text = spptetap.ToString(); sppvariabel = 120000; textBox7->Text = sppvariabel.ToString(); } else if (comboBox2->Text == "S1 - Informatika") { biayasarana = 19000000; textBox5->Text = biayasarana.ToString(); spptetap = 2000000; textBox6->Text = spptetap.ToString(); sppvariabel = 120000; textBox7->Text = sppvariabel.ToString(); } else if (comboBox2->Text == "S1 - Teknik Komputer") { biayasarana = 19000000; textBox5->Text = biayasarana.ToString(); spptetap = 1700000; textBox6->Text = spptetap.ToString(); sppvariabel = 120000; textBox7->Text = sppvariabel.ToString(); } else if (comboBox2->Text == "S1 - Arsitektur") { biayasarana = 11000000; textBox5->Text = biayasarana.ToString(); spptetap = 1700000; textBox6->Text = spptetap.ToString(); sppvariabel = 120000; textBox7->Text = sppvariabel.ToString(); } else if (comboBox2->Text == "S1 - Geografi") { biayasarana = 11000000; textBox5->Text = biayasarana.ToString(); spptetap = 1500000; textBox6->Text = spptetap.ToString(); sppvariabel = 120000; textBox7->Text = sppvariabel.ToString(); } else if (comboBox2->Text == "S1 - Akuntansi") { biayasarana = 11000000; textBox5->Text = biayasarana.ToString(); spptetap = 1500000; textBox6->Text = spptetap.ToString(); sppvariabel = 120000; textBox7->Text = sppvariabel.ToString(); } else if (comboBox2->Text == "S1 - Ekonomi") { biayasarana = 11000000; textBox5->Text = biayasarana.ToString(); spptetap = 1500000; textBox6->Text = spptetap.ToString(); sppvariabel = 120000; textBox7->Text = sppvariabel.ToString(); } else if (comboBox2->Text == "S1 - Kewirausahaan") { biayasarana = 11000000; textBox5->Text = biayasarana.ToString(); spptetap = 1500000; textBox6->Text = spptetap.ToString(); sppvariabel = 120000; textBox7->Text = sppvariabel.ToString(); } else if (comboBox2->Text == "S1 - Hubungan Internasional") { biayasarana = 11000000; textBox5->Text = biayasarana.ToString(); spptetap = 1500000; textBox6->Text = spptetap.ToString(); sppvariabel = 120000; textBox7->Text = sppvariabel.ToString(); } else { biayasarana = 19000000; textBox5->Text = biayasarana.ToString(); spptetap = 2000000; textBox6->Text = spptetap.ToString(); sppvariabel = 1200000; textBox7->Text = sppvariabel.ToString(); } } private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) { int sks; if (textBox4->Text == "") { MessageBox::Show("Data SKS Masih Kosong"); } else { sks = int::Parse(textBox4->Text); total = Convert::ToDouble((sks*sppvariabel) + spptetap + biayasarana); textBox8->Text = total.ToString(); } } private: System::Void label6_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void textBox8_TextChanged(System::Object^ sender, System::EventArgs^ e) { } int ket; private: System::Void button6_Click(System::Object^ sender, System::EventArgs^ e) { double bayar, kembali; if (textBox9->Text == "") { MessageBox::Show("Data Uang Anda Masih Kosong"); } else { bayar = double::Parse(textBox9->Text); if (total > bayar) { kembali = double(bayar - total); textBox10->Text = "Belum Lunas" ; } else { textBox10->Text = "Lunas"; } } } private: System::Void textBox5_TextChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void radioButton1_CheckedChanged_1(System::Object^ sender, System::EventArgs^ e) { kelamin = "Laki-Laki"; } private: System::Void radioButton2_CheckedChanged_1(System::Object^ sender, System::EventArgs^ e) { kelamin = "Perempuan"; } private: System::Void button7_Click(System::Object^ sender, System::EventArgs^ e) { try { int no_pendaftaran = Int32::Parse(textBox11->Text); String^ constr = "Server=127.0.0.1;Uid=root;Pwd=;Database=datamahasiswa"; MySqlConnection^ con = gcnew MySqlConnection(constr); MySqlCommand^ cmd = gcnew MySqlCommand("select * from mahasiswa WHERE no_pendaftaran=" + no_pendaftaran + "", con); con->Open(); MySqlDataReader^ dr = cmd->ExecuteReader(); while (dr->Read()) { textBox1->Text = dr->GetString(0); textBox2->Text = dr->GetString(1); textBox3->Text = dr->GetString(2); dateTimePicker1->Text = dr->GetString(3); comboBox1->Text = dr->GetString(4); kelamin = dr->GetString(5); comboBox2->Text = dr->GetString(6); textBox4->Text = dr->GetString(7); textBox5->Text = dr->GetString(8); textBox6->Text = dr->GetString(9); textBox7->Text = dr->GetString(10); textBox8->Text = dr->GetString(11); textBox9->Text = dr->GetString(12); textBox10->Text = dr->GetString(13); } con->Close(); } catch(Exception^ ex) { MessageBox::Show(ex->Message); } } private: System::Void dateTimePicker1_ValueChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void button8_Click(System::Object^ sender, System::EventArgs^ e) { String^ constr = "Server=127.0.0.1;Uid=root;Pwd=;Database=datamahasiswa"; MySqlConnection^ con = gcnew MySqlConnection(constr); MySqlDataAdapter^ sda = gcnew MySqlDataAdapter("select * from mahasiswa", con); DataTable^ dt = gcnew DataTable(); sda->Fill(dt); bindingSource1->DataSource = dt; dataGridView1->DataSource = bindingSource1; } private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { String^ constr = "Server=127.0.0.1;Uid=root;Pwd=;Database=datamahasiswa"; MySqlConnection^ con = gcnew MySqlConnection(constr); int no_pendaftaran = Int32::Parse(textBox1->Text); String^ nama_lengkap = textBox2->Text; String^ tempat_lahir = textBox3->Text; String^ tanggal_lahir = dateTimePicker1->Text; String^ agama = comboBox1->Text; String^ jenis_kelamin = kelamin; String^ jurusan = comboBox2->Text; String^ sks = textBox4->Text; String^ biaya_sarana = textBox5->Text; String^ spp_tetap = textBox6->Text; String^ spp_variabel = textBox7->Text; String^ total_bayar = textBox8->Text; String^ uang_anda = textBox9->Text; String^ keterangan = textBox10->Text; MySqlCommand^ cmd = gcnew MySqlCommand("update mahasiswa set nama_lengkap='" + nama_lengkap + "',tempat_lahir='" + tempat_lahir + "',tanggal_lahir='" + tanggal_lahir + "',agama='" + agama + "',jenis_kelamin='" + jenis_kelamin + "',jurusan='" + jurusan + "',sks='" + sks + "',biaya_sarana='" + biaya_sarana + "',spp_tetap='" + spp_tetap + "',spp_variabel='" + spp_variabel + "',total_bayar='" + total_bayar + "',uang_anda='" + uang_anda + "',keterangan='" + keterangan + "' WHERE no_pendaftaran=" + no_pendaftaran + "", con); con->Open(); MySqlDataReader^ dr = cmd->ExecuteReader(); MessageBox::Show("Data Berhasil Diubah"); con->Close(); } private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) { this->Close(); } private: System::Void button9_Click(System::Object^ sender, System::EventArgs^ e) { Form3^ f3 = gcnew Form3(); f3->ShowDialog(); } }; }
0163d7278cbef9c4491c8b6417ce43949f73b34a
4afd8f383a9548ddece248bd7c08246e8ce62fce
/gcf/maker/cpp/src/CppSerialize.cpp
d02b0665a826b8d54288540852973803e2dbf228
[]
no_license
xuantao/small-idea
4f161ae77eadf846e50a3ba8e50f38428cb014d6
a421668bee717bd07880aa6606ebf0d9fd7d867f
refs/heads/master
2020-06-22T06:29:39.837841
2020-05-20T15:43:44
2020-05-20T15:43:44
74,754,319
2
0
null
null
null
null
UTF-8
C++
false
false
7,080
cpp
CppSerialize.cpp
#include "CppSerialize.h" #include "CppUtil.h" #include "utility/Utility.h" #include <iostream> #include <fstream> #define _TAB(ex) std::string((_tab + ex) * 4, ' ') GCF_NAMESPACE_BEGIN namespace cpp { Serialize::Serialize() { } Serialize::~Serialize() { Clear(); } Serialize* Serialize::Create() { return new Serialize(); } void Serialize::Release() { delete this; } bool Serialize::OnBegin(const IScope* global, const char* path, const char* name) { std::string fileName = utility::ContactPath(path, name) + "_Ser"; std::ofstream* file = new std::ofstream(fileName + ".h"); if (file->is_open()) _header = file; else _header = &std::cout; *_header << _TAB(0) << "/*" << std::endl << _TAB(0) << " * this file is auto generated." << std::endl << _TAB(0) << " * please does not edit it manual!" << std::endl << _TAB(0) << "*/" << std::endl << _TAB(0) << "#pragma once" << std::endl << std::endl << _TAB(0) << "#include \"" << name << ".h\"" << std::endl << _TAB(0) << "#include \"gcf/gcf.h\"" << std::endl << std::endl << _TAB(0) << "namespace serialize" << std::endl << _TAB(0) << "{" << std::endl << _TAB(1) << "namespace utility" << std::endl << _TAB(1) << "{" << std::endl; file = new std::ofstream(fileName + ".cpp"); if (file->is_open()) _cpp = file; else _cpp = &std::cout; *_cpp << _TAB(0) << "/*" << std::endl << _TAB(0) << " * this file is auto generated." << std::endl << _TAB(0) << " * please does not edit it manual!" << std::endl << _TAB(0) << "*/" << std::endl << _TAB(0) << "#include \"" << name << "_Ser.h\"" << std::endl << std::endl << _TAB(0) << "namespace serialize" << std::endl << _TAB(0) << "{" << std::endl << _TAB(1) << "namespace utility" << std::endl << _TAB(1) << "{" << std::endl; _tab = 2; return true; } void Serialize::OnType(const IType* type) { if (type->TypeCat() != TypeCategory::Enum && type->TypeCat() != TypeCategory::Struct) return; // process inner types do { if (type->TypeCat() != TypeCategory::Struct) break; const IStructType* sTy = static_cast<const IStructType*>(type); if (sTy->OwnScope() == nullptr) break; ITypeSet* tySet = sTy->OwnScope()->TypeSet(); if (tySet == nullptr) break; for (int i = 0; i < tySet->Size(); ++i) OnType(tySet->Get(i)); } while (false); if (!_isFirst) *_header << std::endl; DeclRead(*_header, type, true) << std::endl; DeclWrite(*_header, type, true) << std::endl; if (!_isFirst) *_cpp << std::endl; ImplRead(type); *_cpp << std::endl; ImplWrite(type); _isFirst = false; } void Serialize::OnEnd() { _tab = 0; *_header << _TAB(1) << "}" << std::endl << _TAB(0) << "}" << std::endl; *_cpp << _TAB(1) << "}" << std::endl << _TAB(0) << "}" << std::endl; Clear(); } std::ostream& Serialize::DeclRead(std::ostream& stream, const IType* type, bool isDecl) { stream << _TAB(0) << "bool Read(IReader* reader, " << cpp_util::TypeName(type) << "& val, const char* name"; if (isDecl) stream << " = nullptr);"; else stream << "/* = nullptr*/)"; return stream; } std::ostream& Serialize::DeclWrite(std::ostream& stream, const IType* type, bool isDecl) { stream << _TAB(0) << "bool Write(IWriter* writer, "; if (type->TypeCat() == TypeCategory::Enum) stream << cpp_util::TypeName(type) << " val, const char* name"; else if (type->TypeCat() == TypeCategory::Struct) stream << "const " << cpp_util::TypeName(type) << "& val, const char* name"; else assert(false); if (isDecl) stream << " = nullptr);"; else stream << "/* = nullptr*/)"; return stream; } void Serialize::ImplRead(const IType* type) { DeclRead(*_cpp, type, false) << std::endl << _TAB(0) << "{" << std::endl; if (type->TypeCat() == TypeCategory::Enum) { *_cpp << _TAB(1) << "return reader->Read((int&)val, name);" << std::endl; } else if (type->TypeCat() == TypeCategory::Struct) { *_cpp << _TAB(1) << "if (!reader->StructBegin(" << cpp_util::TypeName(type) << "::HASH_CODE, name)) return false;" << std::endl << std::endl; IVarSet* varSet = ((const IStructType*)type)->Scope()->VarSet(); for (int i = 0; i < varSet->Size(); ++i) { IVariate* var = varSet->Get(i); if (var->IsConst()) continue; *_cpp << _TAB(1) << "if (!Read(reader, val." << var->Name() << ", \"" << var->Name() << "\")) return false;" << std::endl; } *_cpp << std::endl << _TAB(1) << "return reader->StructEnd();" << std::endl; } else { assert(false); } *_cpp << _TAB(0) << "}" << std::endl; } void Serialize::ImplWrite(const IType* type) { DeclWrite(*_cpp, type, false) << std::endl << _TAB(0) << "{" << std::endl; if (type->TypeCat() == TypeCategory::Enum) { *_cpp << _TAB(1) << "return writer->Write((int)val, name);" << std::endl; } else if (type->TypeCat() == TypeCategory::Struct) { *_cpp << _TAB(1) << "if (!writer->StructBegin(" << cpp_util::TypeName(type) << "::HASH_CODE, name)) return false;" << std::endl << std::endl; IVarSet* varSet = ((const IStructType*)type)->Scope()->VarSet(); for (int i = 0; i < varSet->Size(); ++i) { IVariate* var = varSet->Get(i); if (var->IsConst()) continue; *_cpp << _TAB(1) << "if (!Write(writer, val." << var->Name() << ", \"" << var->Name() << "\")) return false;" << std::endl; } *_cpp << std::endl << _TAB(1) << "return writer->StructEnd();" << std::endl; } else { assert(false); } *_cpp << _TAB(0) << "}" << std::endl; } void Serialize::Clear() { if (_header != &std::cout) delete _header; if (_cpp != &std::cout) delete _cpp; _header = nullptr; _cpp = nullptr; _tab = 0; } } GCF_NAMESPACE_END
511e3efb18f0ec85fbc24852e1690695f409feb8
701ed3e5acc702c92c5d04eed94635146fc883cd
/observable.h
d2048a8c81a8e5b861e8158b7a04b6bf278d8cc9
[]
no_license
aldoshkind/treeipc
d5fecdeb6cd44b70c71d9d476a19c61fd855e0ec
5c4c2a54fa90e0bdb66da0ec6b6ffb9b10c70239
refs/heads/master
2021-07-09T15:49:31.584310
2020-04-14T09:56:38
2020-04-14T09:56:38
92,615,350
1
0
null
null
null
null
UTF-8
C++
false
false
1,354
h
observable.h
#pragma once #include <mutex> template <class RV, class ... ARGS> class one_to_one_observable { public: class listener { std::mutex mut; one_to_one_observable *obs; public: listener() { obs = nullptr; } virtual ~listener() { set_observable(nullptr); } virtual RV process_notification(ARGS ...) = 0;/* { return RV(); }*/ void set_observable(one_to_one_observable *o) { std::lock_guard<std::mutex> lg(mut); if(obs != nullptr) { obs->remove_listener(); } obs = o; } void remove_observable() { std::lock_guard<std::mutex> lg(mut); obs = nullptr; } }; public: RV notify(ARGS ... a) { std::lock_guard<std::mutex> lg(mut); if(l != nullptr) { return l->process_notification(a ...); } } private: std::mutex mut; listener *l; public: one_to_one_observable() { l = nullptr; } ~one_to_one_observable() { std::lock_guard<std::mutex> lg(mut); if(l != nullptr) { l->remove_observable(); } } void set_listener(listener *l) { std::lock_guard<std::mutex> lg(mut); if(this->l != nullptr) { this->l->remove_observable(); } this->l = l; if(l != nullptr) { l->set_observable(this); } } void remove_listener() { std::lock_guard<std::mutex> lg(mut); l = nullptr; } protected: listener *get_listener() { return l; } };
62bd6599c9e5987f83723fae5ec25b8758e5d253
d7ab63dc487611d19fb6ab75e9ebc7123373d5d2
/RayTracer/Mesh.h
22147033827f3e9980b36b72ba46a9e5c5b1c938
[]
no_license
exaequo/Fotorealistyczna
c5a049b513d2ec2ca68b598b6308d5bfe3c5babd
b29250e553ca46429fb63f73e5a84b2a9c36a05e
refs/heads/master
2021-01-23T01:08:47.321280
2017-04-04T22:24:55
2017-04-04T22:24:55
85,880,880
0
0
null
null
null
null
UTF-8
C++
false
false
1,070
h
Mesh.h
#pragma once #include "Vector3.h" #include "Primitive.h" #include "Triangle.h" class Mesh : public Primitive { public: Mesh(); Mesh(const std::string &fileName); Mesh(const std::string &fileName, const Color &material); ~Mesh(); void LoadMesh(const std::string &fileName); std::vector<Triangle *> Polygons() const { return polygons; } void Polygons(std::vector<Triangle *> val) { polygons = val; } std::vector<Vector3> Vertices() const { return vertices; } void Vertices(std::vector<Vector3> val) { vertices = val; } std::vector<Vector3> TextureCoord() const { return textureCoord; } void TextureCoord(std::vector<Vector3> val) { textureCoord = val; } std::vector<Vector3> Normals() const { return normals; } void Normals(std::vector<Vector3> val) { normals = val; } virtual bool Intersect(Ray &ray) override; virtual void IntersectionOutput(const Ray &ray) override; private: std::vector<Triangle *> polygons; std::vector<Vector3> vertices; std::vector<Vector3> textureCoord; std::vector<Vector3> normals; std::vector<Material> materials; };
bff18f47f56367c42cfe03ed1772b78c12fb33ce
a2dcf3df78c81208c844f4389ba3b07dd6e81474
/resiprocate-1.10.1/apps/ws-server-self/server.cxx
0e3e2b5b397ada7030cec6ffc745732410f21654
[ "BSD-3-Clause", "VSL-1.0", "BSD-2-Clause" ]
permissive
tempbottle/SurfWebRTC
637b43142fcc8a18459efaf43c03f9cf0a2e248c
55ae8a0122503db99c76545ccd1e792089bb8a5c
refs/heads/master
2021-01-18T07:37:02.223609
2016-02-19T11:12:15
2016-02-19T11:12:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,553
cxx
server.cxx
#include <signal.h> #include "WsServer.hxx" #include "/usr/local/include/rutil/Log.hxx" #include "/usr/local/include/rutil/Time.hxx" #include "/usr/local/include/rutil/Logger.hxx" #define RESIPROCATE_SUBSYSTEM resip::Subsystem::REPRO using namespace server; using namespace resip; using namespace std; static bool finished = false; static bool receivedHUP = false; static void signalHandler(int signo) { if (signo == SIGHUP) { Log::reset(); receivedHUP = true; return; } std::cerr << "Shutting down" << endl; finished = true; } int main(int argc, char** argv) { // Install signal handlers if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { cerr << "Couldn't install signal handler for SIGPIPE" << endl; exit(-1); } if (signal(SIGHUP, signalHandler) == SIG_ERR) { cerr << "Couldn't install signal handler for SIGHUP" << endl; exit(-1); } if (signal(SIGINT, signalHandler) == SIG_ERR) { cerr << "Couldn't install signal handler for SIGINT" << endl; exit(-1); } if (signal(SIGTERM, signalHandler) == SIG_ERR) { cerr << "Couldn't install signal handler for SIGTERM" << endl; exit(-1); } WsServer wsServer; if(!wsServer.run(argc, argv)) { cerr << "Failed to start wsServer, exiting..." << endl; exit(-1); } // Main program thread, just waits here for a signal to shutdown while (!finished) { sleepMs(1000); if (receivedHUP) { receivedHUP = false; } } wsServer.shutdown(); return 0; }
1a342c631d130322bd5ec1dc4371574b052dae15
f59955d436b58db8608b4591975d76883cd23084
/source/sender.h
2b3283b3b740a62702fe1a5a678d241acd037f4f
[ "Apache-2.0" ]
permissive
Verch/mirror_sync
6dde8dfb544741771eef7af0c1640ff98ad7324b
9b85ad9e0d52dea8cad7c720947c866f69d68243
refs/heads/master
2021-01-17T06:52:44.369786
2017-04-24T16:50:35
2017-04-24T16:50:35
50,615,945
0
0
null
null
null
null
UTF-8
C++
false
false
328
h
sender.h
#pragma once #include "boost/asio.hpp" #include <string> class Sender { public: explicit Sender(); void send_for(boost::asio::ip::udp::endpoint& ep, const std::string& msg); private: boost::asio::io_service _service; boost::asio::ip::udp::endpoint _endpoint; boost::asio::ip::udp::socket _socket; };
bc6f1ee2f4f64339df0506b685aa8a658b1a95a5
d7db098f4b1d1cd7d32952ebde8106e1f297252e
/CodeForces/0864/d.cpp
3490bdb917fd52f4e2d2c1fbcb8f7b8bfb3e8530
[]
no_license
monman53/online_judge
d1d3ce50f5a8a3364a259a78bb89980ce05b9419
dec972d2b2b3922227d9eecaad607f1d9cc94434
refs/heads/master
2021-01-16T18:36:27.455888
2019-05-26T14:03:14
2019-05-26T14:03:14
25,679,069
0
0
null
null
null
null
UTF-8
C++
false
false
1,337
cpp
d.cpp
// header {{{ #include <bits/stdc++.h> using namespace std; // {U}{INT,LONG,LLONG}_{MAX,MIN} #define ALPHABET (26) #define INF INT_MAX #define MOD (1000000007LL) #define EPS (1e-10) #define EQ(a, b) (abs((a)-(b)) < EPS) using P = pair<int, int>; using LL = long long; // }}} int main() { std::ios::sync_with_stdio(false); int n;cin >> n; vector<int> a(n); map<int, int> m; for(int i=0;i<n;i++){ cin >> a[i]; m[a[i]]++; } priority_queue<int, vector<int>, greater<int>> pq; for(int i=1;i<=n;i++){ if(m.find(i) == m.end()){ pq.push(i); } } int count = 0; vector<int> ans(n); vector<bool> next(n+1, false); for(int i=0;i<n;i++){ if(m[a[i]] == 1){ ans[i] = a[i]; }else{ int top = pq.top(); if(!next[a[i]]){ if(a[i] < top){ next[a[i]] = true; ans[i] = a[i]; continue; } } count++; ans[i] = top; pq.pop(); m[a[i]]--; } } cout << count << endl; for(int i=0;i<n;i++){ cout << ans[i]; if(i != n-1){ cout << " "; } } cout << endl; return 0; }
b3be5e47341ff7ee66a2ea7201ed08d28677bbcd
b61d8bbae7e830329eff55cf6105d45c167033f9
/Source/examples/fwex/2D3DRegistrationFrameworkExtended/itkMattesMutualInformationImageToImageMetricComplete.h
27c022166f1d5622f56837376963c082efa25aea
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
fwzhuangCg/midas-journal-776
5b67062c22d62cc7e2c4fdef479c52b3bfc2f0b6
a4f2039d0ac2497fcee25bd64ab34a8ba776004f
refs/heads/master
2021-05-26T15:17:34.645160
2011-08-22T13:47:42
2011-08-22T13:47:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,617
h
itkMattesMutualInformationImageToImageMetricComplete.h
// // <b>NOTE:</b> // <p><i>This class is an extension of the original // itkMattesMutualInformationImageToImageMetric. Unfortunately it is not // possible to derive from the class and then override Initialize() (in the // context of doing what we want to do - overriding bounds) or make the // internal joint PDF accessible. There are too much private attributes and // methods. So we decided to copy the class and postfix its name. // Changes are marked with "//CHNG". </i></p> /*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMattesMutualInformationImageToImageMetricComplete.h,v $ Language: C++ Date: $Date: 2008-03-14 16:26:01 $ Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __itkMattesMutualInformationImageToImageMetricComplete_h #define __itkMattesMutualInformationImageToImageMetricComplete_h // First make sure that the configuration is available. // This line can be removed once the optimized versions // gets integrated into the main directories. #include "itkConfigure.h" //CHNG // --> forget multithreaded mode in this context //#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS //#include "itkOptMattesMutualInformationImageToImageMetricComplete.h" //#else #include "itkImageToImageMetric.h" #include "itkCovariantVector.h" #include "itkPoint.h" #include "itkIndex.h" #include "itkBSplineKernelFunction.h" #include "itkBSplineDerivativeKernelFunction.h" #include "itkCentralDifferenceImageFunction.h" #include "itkBSplineInterpolateImageFunction.h" #include "itkBSplineDeformableTransform.h" #include "itkArray2D.h" namespace itk { /** \class MattesMutualInformationImageToImageMetricComplete * \brief Computes the mutual information between two images to be * registered using the method of Mattes et al. <i>This class is an extension * of the original MattesMutualInformationImageToImageMetric.</i> * * MattesMutualInformationImageToImageMetricComplete computes the mutual * information between a fixed and moving image to be registered. * * This class is templated over the FixedImage type and the MovingImage * type. * * The fixed and moving images are set via methods SetFixedImage() and * SetMovingImage(). This metric makes use of user specified Transform and * Interpolator. The Transform is used to map points from the fixed image to * the moving image domain. The Interpolator is used to evaluate the image * intensity at user specified geometric points in the moving image. * The Transform and Interpolator are set via methods SetTransform() and * SetInterpolator(). * * If a BSplineInterpolationFunction is used, this class obtain * image derivatives from the BSpline interpolator. Otherwise, * image derivatives are computed using central differencing. * * \warning This metric assumes that the moving image has already been * connected to the interpolator outside of this class. * * The method GetValue() computes of the mutual information * while method GetValueAndDerivative() computes * both the mutual information and its derivatives with respect to the * transform parameters. * * The calculations are based on the method of Mattes et al [1,2] * where the probability density distribution are estimated using * Parzen histograms. Since the fixed image PDF does not contribute * to the derivatives, it does not need to be smooth. Hence, * a zero order (box car) BSpline kernel is used * for the fixed image intensity PDF. On the other hand, to ensure * smoothness a third order BSpline kernel is used for the * moving image intensity PDF. * * On Initialize(), the FixedImage is uniformly sampled within * the FixedImageRegion. The number of samples used can be set * via SetNumberOfSpatialSamples(). Typically, the number of * spatial samples used should increase with the image size. * * The option UseAllPixelOn() disables the random sampling and uses * all the pixels of the FixedImageRegion in order to estimate the * joint intensity PDF. * * During each call of GetValue(), GetDerivatives(), * GetValueAndDerivatives(), marginal and joint intensity PDF's * values are estimated at discrete position or bins. * The number of bins used can be set via SetNumberOfHistogramBins(). * To handle data with arbitray magnitude and dynamic range, * the image intensity is scale such that any contribution to the * histogram will fall into a valid bin. * * One the PDF's have been contructed, the mutual information * is obtained by doubling summing over the discrete PDF values. * * * Notes: * 1. This class returns the negative mutual information value. * 2. This class in not thread safe due the private data structures * used to the store the sampled points and the marginal and joint pdfs. * * References: * [1] "Nonrigid multimodality image registration" * D. Mattes, D. R. Haynor, H. Vesselle, T. Lewellen and W. Eubank * Medical Imaging 2001: Image Processing, 2001, pp. 1609-1620. * [2] "PET-CT Image Registration in the Chest Using Free-form Deformations" * D. Mattes, D. R. Haynor, H. Vesselle, T. Lewellen and W. Eubank * IEEE Transactions in Medical Imaging. Vol.22, No.1, January 2003. pp.120-128. * [3] "Optimization of Mutual Information for MultiResolution Image * Registration" * P. Thevenaz and M. Unser * IEEE Transactions in Image Processing, 9(12) December 2000. * * \ingroup RegistrationMetrics * \ingroup ThreadUnSafe */ template <class TFixedImage,class TMovingImage > class ITK_EXPORT MattesMutualInformationImageToImageMetricComplete : public ImageToImageMetric< TFixedImage, TMovingImage > { public: /** Standard class typedefs. */ typedef MattesMutualInformationImageToImageMetricComplete Self; typedef ImageToImageMetric< TFixedImage, TMovingImage > Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(MattesMutualInformationImageToImageMetricComplete, ImageToImageMetric); /** Types inherited from Superclass. */ typedef typename Superclass::TransformType TransformType; typedef typename Superclass::TransformPointer TransformPointer; typedef typename Superclass::TransformJacobianType TransformJacobianType; typedef typename Superclass::InterpolatorType InterpolatorType; typedef typename Superclass::MeasureType MeasureType; typedef typename Superclass::DerivativeType DerivativeType; typedef typename Superclass::ParametersType ParametersType; typedef typename Superclass::FixedImageType FixedImageType; typedef typename Superclass::MovingImageType MovingImageType; typedef typename Superclass::FixedImageConstPointer FixedImageConstPointer; typedef typename Superclass::MovingImageConstPointer MovingImageCosntPointer; typedef typename Superclass::InputPointType InputPointType; typedef typename Superclass::OutputPointType OutputPointType; typedef typename Superclass::CoordinateRepresentationType CoordinateRepresentationType; /** Index and Point typedef support. */ typedef typename FixedImageType::IndexType FixedImageIndexType; typedef typename FixedImageIndexType::IndexValueType FixedImageIndexValueType; typedef typename MovingImageType::IndexType MovingImageIndexType; typedef typename TransformType::InputPointType FixedImagePointType; typedef typename TransformType::OutputPointType MovingImagePointType; // CHNG: now public! typedef float PDFValueType; typedef Image<PDFValueType,2> JointPDFType; /** The moving image dimension. */ itkStaticConstMacro( MovingImageDimension, unsigned int, MovingImageType::ImageDimension ); /** * Initialize the Metric by * (1) making sure that all the components are present and plugged * together correctly, * (2) uniformly select NumberOfSpatialSamples within * the FixedImageRegion, and * (3) allocate memory for pdf data structures. */ virtual void Initialize(void) throw ( ExceptionObject ); /** Get the derivatives of the match measure. */ void GetDerivative( const ParametersType& parameters, DerivativeType & Derivative ) const; /** Get the value. */ MeasureType GetValue( const ParametersType& parameters ) const; /** Get the value and derivatives for single valued optimizers. */ void GetValueAndDerivative( const ParametersType& parameters, MeasureType& Value, DerivativeType& Derivative ) const; /** Number of spatial samples to used to compute metric */ itkSetClampMacro( NumberOfSpatialSamples, unsigned long, 1, NumericTraits<unsigned long>::max() ); itkGetConstReferenceMacro( NumberOfSpatialSamples, unsigned long); /** Number of bins to used in the histogram. Typical value is 50. */ itkSetClampMacro( NumberOfHistogramBins, unsigned long, 1, NumericTraits<unsigned long>::max() ); itkGetConstReferenceMacro( NumberOfHistogramBins, unsigned long); /** Reinitialize the seed of the random number generator that selects the * sample of pixels used for estimating the image histograms and the joint * histogram. By nature, this metric is not deterministic, since at each run * it may select a different set of pixels. By initializing the random number * generator seed to the same value you can restore determinism. On the other * hand, calling the method ReinitializeSeed() without arguments will use the * clock from your machine in order to have a very random initialization of * the seed. This will indeed increase the non-deterministic behavior of the * metric. */ void ReinitializeSeed(); void ReinitializeSeed(int); /** Select whether the metric will be computed using all the pixels on the * fixed image region, or only using a set of randomly selected pixels. */ itkSetMacro(UseAllPixels,bool); itkGetConstReferenceMacro(UseAllPixels,bool); itkBooleanMacro(UseAllPixels); /** This variable selects the method to be used for computing the Metric * derivatives with respect to the Transform parameters. Two modes of * computation are available. The choice between one and the other is a * trade-off between computation speed and memory allocations. The two modes * are described in detail below: * * UseExplicitPDFDerivatives = True * will compute the Metric derivative by first calculating the derivatives of * each one of the Joint PDF bins with respect to each one of the Transform * parameters and then accumulating these contributions in the final metric * derivative array by using a bin-specific weight. The memory required for * storing the intermediate derivatives is a 3D array of doubles with size * equals to the product of (number of histogram bins)^2 times number of * transform parameters. This method is well suited for Transform with a small * number of parameters. * * UseExplicitPDFDerivatives = False will compute the Metric derivative by * first computing the weights for each one of the Joint PDF bins and caching * them into an array. Then it will revisit each one of the PDF bins for * computing its weighted contribution to the full derivative array. In this * method an extra 2D array is used for storing the weights of each one of * the PDF bins. This is an array of doubles with size equals to (number of * histogram bins)^2. This method is well suited for Transforms with a large * number of parameters, such as, BSplineDeformableTransforms. */ itkSetMacro(UseExplicitPDFDerivatives,bool); itkGetConstReferenceMacro(UseExplicitPDFDerivatives,bool); itkBooleanMacro(UseExplicitPDFDerivatives); /** This boolean flag is only relevant when this metric is used along * with a BSplineDeformableTransform. The flag enables/disables the * caching of values computed when a physical point is mapped through * the BSplineDeformableTransform. In particular it will cache the * values of the BSpline weights for that points, and the indexes * indicating what BSpline-grid nodes are relevant for that specific * point. This caching is made optional due to the fact that the * memory arrays used for the caching can reach large sizes even for * moderate image size problems. For example, for a 3D image of * 256^3, using 20% of pixels, these arrays will take about 1 * Gigabyte of RAM for storage. The ratio of computing time between * using the cache or not using the cache can reach 1:5, meaning that * using the caching can provide a five times speed up. It is * therefore, interesting to enable the caching, if enough memory is * available for it. The caching is enabled by default, in order to * preserve backward compatibility with previous versions of ITK. */ itkSetMacro(UseCachingOfBSplineWeights,bool); itkGetConstReferenceMacro(UseCachingOfBSplineWeights,bool); itkBooleanMacro(UseCachingOfBSplineWeights); //CHNG: getter for joint PDF (can be very helpful when tuning registrations) itkGetObjectMacro(JointPDF, JointPDFType); //CHNG: /** Set/get lower and upper intensity bounds for the PDF and MI calculation. * This is important for 2D/3D registration in order to override the sampled * intensities (this is done in Initialize()). In general the moving image is * a summed image whose intensity range is significantly different from the * moving volume's intensity range. Therefore, to have an effect, * the setters must be called before Initialize(). The bounds are expected to * have one or two elements where the first item is the lower/upper * intensity bound for the moving image and the second for fixed image. **/ void SetLowerBound(const std::vector<double> lb) { m_LowerBound.clear(); for (unsigned int i = 0; i < lb.size(); ++i) m_LowerBound.push_back(lb[i]); this->Modified(); }; void GetLowerBound(std::vector<double> &lb) { lb.clear(); for (unsigned int i = 0; i < m_LowerBound.size(); ++i) lb.push_back(m_LowerBound[i]); return; }; void SetUpperBound(const std::vector<double> ub) { m_UpperBound.clear(); for (unsigned int i = 0; i < ub.size(); ++i) m_UpperBound.push_back(ub[i]); this->Modified(); }; void GetUpperBound(std::vector<double> &ub) { ub.clear(); for (unsigned int i = 0; i < m_UpperBound.size(); ++i) ub.push_back(m_UpperBound[i]); return; }; protected: MattesMutualInformationImageToImageMetricComplete(); virtual ~MattesMutualInformationImageToImageMetricComplete() {}; void PrintSelf(std::ostream& os, Indent indent) const; /** * A fixed image spatial sample consists of the fixed domain point * and the fixed image value at that point. */ /// @cond class FixedImageSpatialSample { public: FixedImageSpatialSample():FixedImageValue(0.0) { FixedImagePointValue.Fill(0.0); } ~FixedImageSpatialSample() {}; FixedImagePointType FixedImagePointValue; double FixedImageValue; unsigned int FixedImageParzenWindowIndex; }; /// @endcond /** FixedImageSpatialSample typedef support. */ typedef std::vector<FixedImageSpatialSample> FixedImageSpatialSampleContainer; //CHNG: bounds-overrides /** lower bound (1st item: moving image, 2nd item: fixed image) **/ std::vector<double> m_LowerBound; /** upper bound (1st item: moving image, 2nd item: fixed image) **/ std::vector<double> m_UpperBound; /** Container to store a set of points and fixed image values. */ FixedImageSpatialSampleContainer m_FixedImageSamples; /** Uniformly select a sample set from the fixed image domain. */ virtual void SampleFixedImageDomain( FixedImageSpatialSampleContainer& samples); /** Gather all the pixels from the fixed image domain. */ virtual void SampleFullFixedImageDomain( FixedImageSpatialSampleContainer& samples); /** Transform a point from FixedImage domain to MovingImage domain. * This function also checks if mapped point is within support region. */ virtual void TransformPoint( unsigned int sampleNumber, const ParametersType& parameters, MovingImagePointType& mappedPoint, bool& sampleWithinSupportRegion, double& movingImageValue ) const; private: //purposely not implemented MattesMutualInformationImageToImageMetricComplete(const Self&); //purposely not implemented void operator=(const Self&); /** The marginal PDFs are stored as std::vector. */ //CHNG: -> now public //typedef float PDFValueType; typedef std::vector<PDFValueType> MarginalPDFType; /** The fixed image marginal PDF. */ mutable MarginalPDFType m_FixedImageMarginalPDF; /** The moving image marginal PDF. */ mutable MarginalPDFType m_MovingImageMarginalPDF; /** Helper array for storing the values of the JointPDF ratios. */ typedef double PRatioType; typedef Array2D< PRatioType > PRatioArrayType; mutable PRatioArrayType m_PRatioArray; /** Helper variable for accumulating the derivative of the metric. */ mutable DerivativeType m_MetricDerivative; /** Typedef for the joint PDF and PDF derivatives are stored as ITK Images. */ //typedef Image<PDFValueType,2> JointPDFType; //CHNG: -> now public typedef JointPDFType::IndexType JointPDFIndexType; typedef JointPDFType::PixelType JointPDFValueType; typedef JointPDFType::RegionType JointPDFRegionType; typedef JointPDFType::SizeType JointPDFSizeType; typedef Image<PDFValueType,3> JointPDFDerivativesType; typedef JointPDFDerivativesType::IndexType JointPDFDerivativesIndexType; typedef JointPDFDerivativesType::PixelType JointPDFDerivativesValueType; typedef JointPDFDerivativesType::RegionType JointPDFDerivativesRegionType; typedef JointPDFDerivativesType::SizeType JointPDFDerivativesSizeType; /** The joint PDF and PDF derivatives. */ typename JointPDFType::Pointer m_JointPDF; typename JointPDFDerivativesType::Pointer m_JointPDFDerivatives; unsigned long m_NumberOfSpatialSamples; unsigned long m_NumberOfParameters; /** Variables to define the marginal and joint histograms. */ unsigned long m_NumberOfHistogramBins; double m_MovingImageNormalizedMin; double m_FixedImageNormalizedMin; double m_MovingImageTrueMin; double m_MovingImageTrueMax; double m_FixedImageBinSize; double m_MovingImageBinSize; /** Typedefs for BSpline kernel and derivative functions. */ typedef BSplineKernelFunction<3> CubicBSplineFunctionType; typedef BSplineDerivativeKernelFunction<3> CubicBSplineDerivativeFunctionType; /** Cubic BSpline kernel for computing Parzen histograms. */ typename CubicBSplineFunctionType::Pointer m_CubicBSplineKernel; typename CubicBSplineDerivativeFunctionType::Pointer m_CubicBSplineDerivativeKernel; /** Precompute fixed image parzen window indices. */ virtual void ComputeFixedImageParzenWindowIndices( FixedImageSpatialSampleContainer& samples ); /** * Types and variables related to image derivative calculations. * If a BSplineInterpolationFunction is used, this class obtain * image derivatives from the BSpline interpolator. Otherwise, * image derivatives are computed using central differencing. */ typedef CovariantVector< double, itkGetStaticConstMacro(MovingImageDimension) > ImageDerivativesType; /** Compute image derivatives at a point. */ virtual void ComputeImageDerivatives( const MovingImagePointType& mappedPoint, ImageDerivativesType& gradient ) const; /** Boolean to indicate if the interpolator BSpline. */ bool m_InterpolatorIsBSpline; /** Typedefs for using BSpline interpolator. */ typedef BSplineInterpolateImageFunction<MovingImageType, CoordinateRepresentationType> BSplineInterpolatorType; /** Pointer to BSplineInterpolator. */ typename BSplineInterpolatorType::Pointer m_BSplineInterpolator; /** Typedefs for using central difference calculator. */ typedef CentralDifferenceImageFunction<MovingImageType, CoordinateRepresentationType> DerivativeFunctionType; /** Pointer to central difference calculator. */ typename DerivativeFunctionType::Pointer m_DerivativeCalculator; /** Compute PDF derivative contribution for each parameter. */ virtual void ComputePDFDerivatives( unsigned int sampleNumber, int movingImageParzenWindowIndex, const ImageDerivativesType& movingImageGradientValue, double cubicBSplineDerivativeValue ) const; /** * Types and variables related to BSpline deformable transforms. * If the transform is of type third order BSplineDeformableTransform, * then we can speed up the metric derivative calculation by * only inspecting the parameters within the support region * of a mapped point. */ /** Boolean to indicate if the transform is BSpline deformable. */ bool m_TransformIsBSpline; /** The number of BSpline parameters per image dimension. */ long m_NumParametersPerDim; /** * The number of BSpline transform weights is the number of * of parameter in the support region (per dimension ). */ unsigned long m_NumBSplineWeights; /** The fixed image dimension. */ itkStaticConstMacro( FixedImageDimension, unsigned int, FixedImageType::ImageDimension ); /** * Enum of the deformabtion field spline order. */ enum { DeformationSplineOrder = 3 }; /** * Typedefs for the BSplineDeformableTransform. */ typedef BSplineDeformableTransform< CoordinateRepresentationType, ::itk::GetImageDimension<FixedImageType>::ImageDimension, DeformationSplineOrder> BSplineTransformType; typedef typename BSplineTransformType::WeightsType BSplineTransformWeightsType; typedef typename BSplineTransformType::ParameterIndexArrayType BSplineTransformIndexArrayType; /** * Variables used when transform is of type BSpline deformable. */ typename BSplineTransformType::Pointer m_BSplineTransform; /** * Cache pre-transformed points, weights, indices and * within support region flag. */ typedef typename BSplineTransformWeightsType::ValueType WeightsValueType; typedef Array2D<WeightsValueType> BSplineTransformWeightsArrayType; typedef typename BSplineTransformIndexArrayType::ValueType IndexValueType; typedef Array2D<IndexValueType> BSplineTransformIndicesArrayType; typedef std::vector<MovingImagePointType> MovingImagePointArrayType; typedef std::vector<bool> BooleanArrayType; BSplineTransformWeightsArrayType m_BSplineTransformWeightsArray; BSplineTransformIndicesArrayType m_BSplineTransformIndicesArray; MovingImagePointArrayType m_PreTransformPointsArray; BooleanArrayType m_WithinSupportRegionArray; typedef FixedArray<unsigned long, ::itk::GetImageDimension<FixedImageType>::ImageDimension> ParametersOffsetType; ParametersOffsetType m_ParametersOffset; bool m_UseAllPixels; virtual void PreComputeTransformValues(); bool m_ReseedIterator; int m_RandomSeed; // Selection of explicit or implicit computation of PDF derivatives // with respect to Transform parameters. bool m_UseExplicitPDFDerivatives; // Variables needed for optionally caching values when using a BSpline transform. bool m_UseCachingOfBSplineWeights; mutable BSplineTransformWeightsType m_Weights; mutable BSplineTransformIndexArrayType m_Indices; }; } // end namespace itk //CHNG #include "itkMattesMutualInformationImageToImageMetricComplete.txx" //CHNG //#endif #endif
ecf29530bcd26677bec9c17ad0ddc3e539180793
f8959d663bba888709824a7890a62768f80c116a
/src/calculators/WorkItemCalculator.h
025f4273bdda365995238a73c04547f071670694
[ "LicenseRef-scancode-public-domain" ]
permissive
dqshen/cwdsim
620dd0e8b7283634d2d0c7d54aad760171d324b0
b773300c980ff5a9680c3b3e73fd4a2a1821446f
refs/heads/master
2021-01-22T17:14:26.017585
2013-07-30T07:45:29
2013-07-30T07:45:29
11,733,912
0
1
null
null
null
null
UTF-8
C++
false
false
1,053
h
WorkItemCalculator.h
#ifndef WORKITEMCALCULATOR_H_ #define WORKITEMCALCULATOR_H_ #include <CL/cl.h> #define GL3_PROTOTYPES 1 #include "../graphics/gl3.h" #include "../graphics/BufferTexture.h" #include "../computation/Program.h" #include "SharedBufferCalculator.h" class WorkItemCalculator : public SharedBufferCalculator { public: WorkItemCalculator( const Logger* logger, Profiler* profiler, const Context* context, size_t threadCount, size_t workGroupSize, cl_uint bufferSideLength, GLsizeiptr bufferByteSize, cl_uint workGroupSideLength); virtual ~WorkItemCalculator(); void compute(); const BufferTexture* getWorkItems() const; private: cl_kernel kernelWorkItems; }; #endif /* WORKITEMCALCULATOR_H_ */
9e80f11542ce828d9aa73a366e924776f9569cce
250101ffb5bd6c4bcfe328854284338772e9aab5
/gate_server/communicate/BroadUnit.h
2d3ca6365d8f31a15d14ea2cd964c14c4fb4eaf5
[]
no_license
MENGJIANGTAO/GameServer-2
aa1299e9442e221a1a2d26457c18396d5e4c54bd
be261b565a1f823d8d17235a21dd1f2431c0a30d
refs/heads/master
2021-09-17T22:45:10.621608
2018-07-06T05:15:47
2018-07-06T05:15:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
532
h
BroadUnit.h
/* * BroadUnit.h * * Created on: 2014-09-26 10:49 * Author: lyz */ #ifndef _BROADUNIT_H_ #define _BROADUNIT_H_ #include "BaseUnit.h" class BroadUnit : public BaseUnit { public: virtual int type(void); protected: virtual UnitMessage *pop_unit_message(void); virtual int push_unit_message(UnitMessage *msg); virtual int process_block(UnitMessage *unit_msg); bool dispatch_by_broad_in_gate(UnitMessage *unit_msg); bool dispatch_by_broad_client(UnitMessage *unit_msg); }; #endif //_BROADUNIT_H_
3545a23de73b18b863eefd0a20b3d17b453a2c49
4fa9c944984bdd7b9439a2d27f7f93b7c5ebfc10
/app/sys/sys_cli/src/commands/helpers.cpp
f0679a65d567b824f1fbb8e2911919021737f046
[ "Apache-2.0", "BSD-3-Clause", "MIT", "LicenseRef-scancode-protobuf", "LicenseRef-scancode-proprietary-license", "BSL-1.0", "LGPL-3.0-only", "LGPL-2.0-only", "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-only" ]
permissive
continental/ecal
99f58902e01c791a8b5f7a72699631c179569062
cb11fbef1b394d6d4336ff0e6e187f45799811b6
refs/heads/master
2022-08-14T23:34:39.725494
2022-07-28T17:39:27
2022-07-28T17:39:27
518,888,778
6
4
Apache-2.0
2022-07-28T17:39:28
2022-07-28T14:56:12
null
UTF-8
C++
false
false
10,168
cpp
helpers.cpp
/* ========================= eCAL LICENSE ================================= * * Copyright (C) 2016 - 2020 Continental Corporation * * 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. * * ========================= eCAL LICENSE ================================= */ #include "helpers.h" #include <vector> #include <string> #include <sys_error.h> #include <memory> #include <ecalsys/ecal_sys.h> #include <ecalsys/proto_helpers.h> namespace eCAL { namespace sys { namespace command { Error ToTaskList(const std::shared_ptr<EcalSys> ecalsys_instance, const std::vector<std::string>& argv, std::list<std::shared_ptr<EcalSysTask>>& output_tasklist) { if (argv.empty()) { output_tasklist = ecalsys_instance->GetTaskList(); } else { output_tasklist.clear(); auto complete_task_list = ecalsys_instance->GetTaskList(); for (const std::string& arg : argv) { bool match_found = false; // Try matching the argument as task ID try { unsigned long id = std::stoul(arg); auto task_ptr = ecalsys_instance->GetTask(static_cast<uint32_t>(id)); if (task_ptr) { output_tasklist.push_back(task_ptr); match_found = true; } } catch (const std::exception&) {} // Try matching the argument as task Name if (!match_found) { for (const auto& task : complete_task_list) { if (task->GetName() == arg) { output_tasklist.push_back(task); match_found = true; break; } } } // Return error if unable to find task if (!match_found) { return eCAL::sys::Error(eCAL::sys::Error::ErrorCode::TASK_DOES_NOT_EXIST, arg); } } } return eCAL::sys::Error::ErrorCode::OK; } Error ToRunnerList(const std::shared_ptr<EcalSys> ecalsys_instance, const std::vector<std::string>& argv, std::list<std::shared_ptr<EcalSysRunner>>& output_runnerlist) { if (argv.empty()) { output_runnerlist = ecalsys_instance->GetRunnerList(); } else { output_runnerlist.clear(); auto complete_runner_list = ecalsys_instance->GetRunnerList(); for (const std::string& arg : argv) { bool match_found = false; // Try matching the argument as runner ID try { unsigned long id = std::stoul(arg); auto runner_ptr = ecalsys_instance->GetRunner(static_cast<uint32_t>(id)); if (runner_ptr) { output_runnerlist.push_back(runner_ptr); match_found = true; } } catch (const std::exception&) {} // Try matching the argument as runner Name if (!match_found) { for (const auto& runner : complete_runner_list) { if (runner->GetName() == arg) { output_runnerlist.push_back(runner); match_found = true; break; } } } // Return error if unable to find runner if (!match_found) { return eCAL::sys::Error(eCAL::sys::Error::ErrorCode::RUNNER_DOES_NOT_EXIST, arg); } } } return eCAL::sys::Error::ErrorCode::OK; } Error ToGroupList(const std::shared_ptr<EcalSys> ecalsys_instance, const std::vector<std::string>& argv, std::list<std::shared_ptr<TaskGroup>>& output_grouplist) { if (argv.empty()) { output_grouplist = ecalsys_instance->GetGroupList(); } else { output_grouplist.clear(); auto complete_group_list = ecalsys_instance->GetGroupList(); for (const std::string& arg : argv) { bool match_found = false; // Try matching the argument as group ID try { unsigned long id = std::stoul(arg); for (const auto& group_ptr : complete_group_list) { if (group_ptr->GetId() == static_cast<uint32_t>(id)) { output_grouplist.push_back(group_ptr); match_found = true; } } } catch (const std::exception&) {} // Try matching the argument as group Name if (!match_found) { for (const auto& group : complete_group_list) { if (group->GetName() == arg) { output_grouplist.push_back(group); match_found = true; break; } } } // Return error if unable to find group if (!match_found) { return eCAL::sys::Error(eCAL::sys::Error::ErrorCode::GROUP_DOES_NOT_EXIST, arg); } } } return eCAL::sys::Error::ErrorCode::OK; } Error GetCompleteTaskList(const eCAL::pb::sys::State& state_pb, std::list<std::shared_ptr<EcalSysTask>>& output_tasklist) { output_tasklist.clear(); for (const auto& task_pb : state_pb.tasks()) { output_tasklist.push_back(eCAL::sys::proto_helpers::FromProtobuf(task_pb)); } return Error::OK; } Error GetCompleteGroupList(const eCAL::pb::sys::State& state_pb, std::list<std::shared_ptr<TaskGroup>>& output_grouplist) { output_grouplist.clear(); for (const auto& group_pb : state_pb.groups()) { output_grouplist.push_back(eCAL::sys::proto_helpers::FromProtobuf(group_pb)); } return Error::OK; } Error ToTaskList(const eCAL::pb::sys::State& state_pb, const std::vector<std::string>& argv, std::list<std::shared_ptr<EcalSysTask>>& output_tasklist) { if (argv.empty()) { return GetCompleteTaskList(state_pb, output_tasklist); } else { output_tasklist.clear(); std::list<std::shared_ptr<EcalSysTask>> complete_task_list; GetCompleteTaskList(state_pb, complete_task_list); for (const std::string& arg : argv) { bool match_found = false; // Try matching the argument as task ID try { unsigned long id = std::stoul(arg); for (const auto& task : complete_task_list) { if (task->GetId() == id) { output_tasklist.push_back(task); match_found = true; break; } } } catch (const std::exception&) {} // Try matching the argument as task Name if (!match_found) { for (const auto& task : complete_task_list) { if (task->GetName() == arg) { output_tasklist.push_back(task); match_found = true; break; } } } // Return error if unable to find task if (!match_found) { return eCAL::sys::Error(eCAL::sys::Error::ErrorCode::TASK_DOES_NOT_EXIST, arg); } } } return eCAL::sys::Error::ErrorCode::OK; } Error ToGroupList(const eCAL::pb::sys::State& state_pb, const std::vector<std::string>& argv, std::list<std::shared_ptr<TaskGroup>>& output_grouplist) { if (argv.empty()) { return GetCompleteGroupList(state_pb, output_grouplist); } else { output_grouplist.clear(); std::list<std::shared_ptr<TaskGroup>> complete_grouplist; GetCompleteGroupList(state_pb, complete_grouplist); for (const std::string& arg : argv) { bool match_found = false; // Try matching the argument as group ID try { unsigned long id = std::stoul(arg); for (const auto& group : complete_grouplist) { if (group->GetId() == id) { output_grouplist.push_back(group); match_found = true; break; } } } catch (const std::exception&) {} // Try matching the argument as group Name if (!match_found) { for (const auto& group : complete_grouplist) { if (group->GetName() == arg) { output_grouplist.push_back(group); match_found = true; break; } } } // Return error if unable to find group if (!match_found) { return eCAL::sys::Error(eCAL::sys::Error::ErrorCode::GROUP_DOES_NOT_EXIST, arg); } } return eCAL::sys::Error::ErrorCode::OK; } } } } }
548e5045f459ded659369155a1e4479e4c66201d
8cf32b4cbca07bd39341e1d0a29428e420b492a6
/contracts/libc++/upstream/test/std/localization/locale.categories/category.ctype/facet.ctype.special/facet.ctype.char.members/ctor.pass.cpp
e7a08edb5a37d3a5eb8598b70e351fe4ac95fc19
[ "NCSA", "MIT" ]
permissive
cubetrain/CubeTrain
e1cd516d5dbca77082258948d3c7fc70ebd50fdc
b930a3e88e941225c2c54219267f743c790e388f
refs/heads/master
2020-04-11T23:00:50.245442
2018-12-17T16:07:16
2018-12-17T16:07:16
156,970,178
0
0
null
null
null
null
UTF-8
C++
false
false
1,279
cpp
ctor.pass.cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <locale> // template <class charT> class ctype; // explicit ctype(const mask* tbl = 0, bool del = false, size_t refs = 0); #include <locale> #include <cassert> class my_facet : public std::ctype<char> { public: static int count; explicit my_facet(const mask* tbl = 0, bool del = false, std::size_t refs = 0) : std::ctype<char>(tbl, del, refs) {++count;} ~my_facet() {--count;} }; int my_facet::count = 0; int main() { { std::locale l(std::locale::classic(), new my_facet); assert(my_facet::count == 1); } assert(my_facet::count == 0); { my_facet f(0, false, 1); assert(my_facet::count == 1); { std::locale l(std::locale::classic(), &f); assert(my_facet::count == 1); } assert(my_facet::count == 1); } assert(my_facet::count == 0); }
c8dc02fcde65eb4c6d30ae953623591887b60fc9
e467945d5b3b8f80da3e4fac9fd52d5c50b9f035
/MicroWorld/Vector2.cpp
ae8e7096ef58600bee97ae21d743cb0e34962c93
[]
no_license
vistoriel/MicroWorld
460abd2e669d22caa2248f16533905ac0e22d0c6
f1126bb2af11c2072e368dab4e3a0d6bf1901c56
refs/heads/master
2022-08-16T16:28:13.145150
2020-04-24T20:11:26
2020-04-24T20:11:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
464
cpp
Vector2.cpp
#include "Vector2.h" Vector2::Vector2() { x = 0; y = 0; } Vector2::Vector2(int _x, int _y) { x = _x; y = _y; } const Vector2 operator+(const Vector2& left, const Vector2& right) { return Vector2(left.x + right.x, left.y + right.y); } bool operator==(const Vector2& left, const Vector2& right) { return left.x == right.x && left.y == right.y; } bool operator!=(const Vector2& left, const Vector2& right) { return left.x != right.x && left.y != right.y; }
7522e7284eb99612faef5f8ce1c464a8f57acf9a
7e97b46635bc9f28b7102845192a2938313a21f3
/other/bipartite graph.cpp
38072501912219816441e53ec68a43d371ed75e6
[]
no_license
ittsu-code/Atcoder_ittsucode
3a8f609c649cfd8357c829c3f4aa787c41543211
3294babf5d6e25f80a74a77fd49ae535d252d4da
refs/heads/master
2022-11-06T03:41:55.136071
2020-06-16T14:53:34
2020-06-16T14:53:34
249,254,658
0
0
null
null
null
null
UTF-8
C++
false
false
695
cpp
bipartite graph.cpp
#include <bits/stdc++.h> using namespace std; using Graph = vector<vector<int>>; int main() { int N, M; cin >> N >> M; Graph G(N); for (int i = 0; i < M; i++) { int a, b; G[a].push_back(b); G[b].push_back(a); } bool is_bipartite = true; vector<int> dist(N, -1); queue<int> que; for (int v = 0; v < N; v++) { if (dist[v] != -1) continue; dist[v] = 0, que.push(v); while (!que.empty()) { int v = que.front(); que.pop(); for (auto nv : G[v]) { if (dist[nv] == -1) { dist[nv] = dist[v] + 1; que.push(nv); } else { if (dist[v] == dist[nv]) is_bipartite = false; } } } } }
4e7e2ce7f397fcba74d76505cd5424985dfee3a8
c58114b733908235624ba5b9627a9d3dc5edd023
/A#3/TriangleSoup.cpp
e5386b12c0ab9f334154a3b4e26de6050a11576a
[]
no_license
microshadow/Computer-Graphics
e3c76e5d411ed28ed7e89456bdd0c24d2d036bb0
673813ed5676aeb6da631bd96f34caf98091fe5a
refs/heads/master
2022-09-19T20:32:18.171704
2022-09-16T19:52:12
2022-09-16T19:52:12
109,928,150
0
0
null
null
null
null
UTF-8
C++
false
false
934
cpp
TriangleSoup.cpp
#include "TriangleSoup.h" #include "Triangle.h" #include "first_hit.h" bool TriangleSoup::intersect( const Ray & ray, const double min_t, double & t, Eigen::Vector3d & n) const { //////////////////////////////////////////////////////////////////////////// // Replace with your code here: double min_t_final = 999999999; int hit_id = -1, size = (this->triangles).size(); Eigen::Vector3d n_final; for(auto i = 0; i < size; ++i){ if((this->triangles)[i]->intersect(ray, min_t, t,n) && t >= min_t){ if(t < min_t_final){ min_t_final = t; hit_id = i; n_final = n; } } } if(hit_id >= 0 && hit_id < size){ t = min_t_final; n = n_final; return true; }else{ return false; } //////////////////////////////////////////////////////////////////////////// }
b7013f4ecdc27555ccc82ef6960fdf1880c7944e
af87b94591c8965856dede8449b6592310fcfb80
/server/main.cpp
046252d427d23a38a6501d8381fb838fdb811609
[]
no_license
ArenGorman/RumChat
9812ced46b4971a3aa6026ab0a9bb7d78b1b7654
81411ec5957072595dc00b731ee18b020e7c525e
refs/heads/master
2020-04-30T06:06:25.614112
2019-03-20T03:18:37
2019-03-20T03:18:37
176,642,553
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
15,123
cpp
main.cpp
#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #include <stdlib.h> #include <stdio.h> #include <string> #include <map> #include <ctime> #include "Packet.h" #pragma comment (lib, "Ws2_32.lib") #define DEFAULT_BUFLEN 512 #define DEFAULT_PORT "27015" #define DEFAULT_USER "anonimous" struct IoOperationData { OVERLAPPED overlapped; WSABUF wsaBuf; CHAR buffer[DEFAULT_BUFLEN]; DWORD bytesSent; DWORD bytesRecv; }; struct ConnectionData { SOCKET socket; Packet *lastPacket; string userName; }; struct ClientData { IoOperationData *ioData; ConnectionData *cData; }; DWORD WINAPI ServerWorkerThread(LPVOID pCompletionPort); void HandleClientState(ConnectionData *conData, IoOperationData *pIoData); bool SendChatMessage(string from, string to, string text, string &error); void prntWT(const char * str) { time_t current_time; struct tm time_info; char timeString[9]; time(&current_time); localtime_s(&time_info, &current_time); strftime(timeString, sizeof(timeString), "%H:%M:%S", &time_info); printf_s("[%s] %s", timeString, str); } int __cdecl main(void) { int error; WSADATA wsaData; error = WSAStartup(MAKEWORD(2, 2), &wsaData); if (error != 0) { printf("WSAStartup failed with error: %d\n", error); return EXIT_FAILURE; } // Создаем порт завершения HANDLE hCompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); if (hCompletionPort == NULL) { printf("CreateIoCompletionPort failed with error %d\n", GetLastError()); WSACleanup(); return EXIT_FAILURE; } // Определяеи количество процессоров в системе SYSTEM_INFO systemInfo; GetSystemInfo(&systemInfo); // Создаем рабочие потоки в зависимости от количества процессоров, по два потока на процессор for (int i = 0; i < (int)systemInfo.dwNumberOfProcessors * 2; ++i) { // Создаем поток и передаем в него порт завершения DWORD threadId; HANDLE hThread = CreateThread(NULL, 0, ServerWorkerThread, hCompletionPort, 0, &threadId); if (hThread == NULL) { printf("CreateThread() failed with error %d\n", GetLastError()); WSACleanup(); CloseHandle(hCompletionPort); return EXIT_FAILURE; } // Закрываем дескриптор потока, поток при этом не завершается CloseHandle(hThread); } struct addrinfo hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Преобразуем адрес и номер порта struct addrinfo *localAddr = NULL; error = getaddrinfo(NULL, DEFAULT_PORT, &hints, &localAddr); if (error != 0) { printf("getaddrinfo failed with error: %d\n", error); WSACleanup(); return EXIT_FAILURE; } SOCKET listenSocket = WSASocketW(localAddr->ai_family, localAddr->ai_socktype, 0, NULL, 0, WSA_FLAG_OVERLAPPED); if (listenSocket == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); freeaddrinfo(localAddr); WSACleanup(); return EXIT_FAILURE; } // Привязываем сокет TCP к адресу и ждем подключения error = bind(listenSocket, localAddr->ai_addr, (int)localAddr->ai_addrlen); if (error == SOCKET_ERROR) { printf("bind failed with error: %d\n", WSAGetLastError()); freeaddrinfo(localAddr); closesocket(listenSocket); WSACleanup(); return EXIT_FAILURE; } freeaddrinfo(localAddr); error = listen(listenSocket, SOMAXCONN); if (error == SOCKET_ERROR) { printf("listen failed with error: %d\n", WSAGetLastError()); closesocket(listenSocket); WSACleanup(); return EXIT_FAILURE; } printf("Server listen port: %s\n", DEFAULT_PORT); // Принимаем соединения и связывкем их с портом завершения for ( ; ; ) { SOCKET clientSocket = WSAAccept(listenSocket, NULL, NULL, NULL, 0); if (clientSocket == SOCKET_ERROR) { printf("WSAAccept failed with error %d\n", WSAGetLastError()); return EXIT_FAILURE; } ConnectionData *pConnData = new ConnectionData; pConnData->socket = clientSocket; pConnData->lastPacket = NULL; //TODO: add unique id pConnData->userName = DEFAULT_USER; printf("New client connected: %s\n", pConnData->userName.c_str()); // Связываем клиентский сокет с портом завершения if (CreateIoCompletionPort((HANDLE)clientSocket, hCompletionPort, (ULONG_PTR)pConnData, 0) == NULL) { printf("CreateIoCompletionPort failed with error %d\n", GetLastError()); return EXIT_FAILURE; } // Создаем структуру для операций ввода-вывода и запускаем обработку IoOperationData *pIoData = new IoOperationData; ZeroMemory(&(pIoData->overlapped), sizeof(OVERLAPPED)); pIoData->bytesSent = 0; pIoData->bytesRecv = 0; pIoData->wsaBuf.len = DEFAULT_BUFLEN; pIoData->wsaBuf.buf = pIoData->buffer; DWORD flags = 0; DWORD bytesRecv; if (WSARecv(clientSocket, &(pIoData->wsaBuf), 1, &bytesRecv, &flags, &(pIoData->overlapped), NULL) == SOCKET_ERROR) { if (WSAGetLastError() != ERROR_IO_PENDING) { printf("WSARecv failed with error %d\n", WSAGetLastError()); return EXIT_FAILURE; } } } } DWORD WINAPI ServerWorkerThread(LPVOID pCompletionPort) { HANDLE hCompletionPort = (HANDLE)pCompletionPort; for ( ; ; ) { DWORD bytesTransferred; ConnectionData *pConnectionData; IoOperationData *pIoData; if (GetQueuedCompletionStatus(hCompletionPort, &bytesTransferred, (PULONG_PTR)&pConnectionData, (LPOVERLAPPED *)&pIoData, INFINITE) == 0) { if (GetLastError() == 64) { printf_s("ERROR_NETNAME_DELETED 64 (0x40) - Client disconnected\n"); } else { printf_s("GetQueuedCompletionStatus() failed with error %d\n", GetLastError()); } return 0; } // Проверим, не было ли проблем с сокетом и не было ли закрыто соединение if (bytesTransferred == 0) { printf_s("Client disconnected: %s\n", pConnectionData->userName.c_str()); closesocket(pConnectionData->socket); delete pConnectionData; delete pIoData; continue; } // Если bytesRecv равно 0, то мы начали принимать данные от клиента // с завершением вызова WSARecv() if (pIoData->bytesRecv == 0) { pIoData->bytesRecv = bytesTransferred; string rawPacket = string(pIoData->wsaBuf.buf, (size_t)pIoData->bytesRecv); printf_s("<in(%s) %s", pConnectionData->userName.c_str(), rawPacket.c_str()); Packet * recvPacket = new Packet(pIoData->wsaBuf.buf); if (recvPacket->Command != PacketTypeEnum::INVALID) { //HandlePacket pConnectionData->lastPacket = recvPacket; HandleClientState(pConnectionData, pIoData); } pIoData->bytesSent = 0; } else { pIoData->bytesSent += bytesTransferred; } if (pIoData->bytesRecv > pIoData->bytesSent) { DWORD bytesSent; // Посылаем очередно запрос на ввод-вывод WSASend() // Так как WSASend() может отправить не все данные, то мы отправляем // оставшиеся данные из буфера пока не будут отправлены все ZeroMemory(&(pIoData->overlapped), sizeof(OVERLAPPED)); pIoData->wsaBuf.buf = pIoData->buffer + pIoData->bytesSent; pIoData->wsaBuf.len = pIoData->bytesRecv - pIoData->bytesSent; if (WSASend(pConnectionData->socket, &(pIoData->wsaBuf), 1, &bytesSent, 0, &(pIoData->overlapped), NULL) == SOCKET_ERROR) { if (WSAGetLastError() != ERROR_IO_PENDING) { printf_s("WSASend failed with error %d\n", WSAGetLastError()); return 0; } } } else { DWORD bytesRecv; pIoData->bytesRecv = 0; // Когда все данные отправлены, посылаем запрос ввода-вывода на чтение WSARecv() DWORD flags = 0; ZeroMemory(&(pIoData->overlapped), sizeof(OVERLAPPED)); pIoData->wsaBuf.len = DEFAULT_BUFLEN; pIoData->wsaBuf.buf = pIoData->buffer; if (WSARecv(pConnectionData->socket, &(pIoData->wsaBuf), 1, &bytesRecv, &flags, &(pIoData->overlapped), NULL) == SOCKET_ERROR) { if (WSAGetLastError() != ERROR_IO_PENDING) { printf_s("WSARecv failed with error %d\n", WSAGetLastError()); return 0; } } } } } map<string, ClientData*> UsersList; map<string, vector<string>> ChannelsToUsersTable; vector<string> GetUsersList() { vector<string> v; v.reserve(UsersList.size()); for (auto const &imap : UsersList) v.push_back(imap.first); return v; } vector<string> GetChannels() { vector<string> v; v.reserve(ChannelsToUsersTable.size()); for (auto const &imap : ChannelsToUsersTable) v.push_back(imap.first); return v; } vector<string> GetUsersListFromChannel(string channelName) { if (ChannelsToUsersTable.count(channelName) != 0) { return ChannelsToUsersTable[channelName]; } return vector<string>{"#-404"}; } bool JoinUserToChannel(string userName, string channelName, bool &created) { created = false; if (ChannelsToUsersTable.count(channelName) == 0) { created = true; ChannelsToUsersTable[channelName] = vector<string>(); } vector<string> &v = ChannelsToUsersTable[channelName]; if (find(v.begin(), v.end(), userName) != v.end()) { return false; } v.push_back(userName); if (!created) { string t; SendChatMessage("", "@" + channelName, userName + " join to channel", t); } return true; } bool LeaveUserFromChannel(string userName, string channelName, bool &deleted) { deleted = false; if (ChannelsToUsersTable.count(channelName) == 0) { return false; } vector<string> &v = ChannelsToUsersTable[channelName]; vector<string>::iterator it = find(v.begin(), v.end(), userName); if (it == v.end()) { return false; } v.erase(it, it + 1); if (v.size() == 0 && channelName != "global") { deleted = true; ChannelsToUsersTable.erase(channelName); } if (!deleted) { string t; SendChatMessage("", "@" + channelName, userName + " left channel", t); } return true; } string vector_to_string(vector<string> v) { string res = ""; for (const auto &s : v) res += s + " "; return res; } bool InternalSendMessage(string from, string to, string channel, string text, string &error) { WSABUF wsaBuf; char buffer[DEFAULT_BUFLEN]; DWORD bytesSent = 0; DWORD bytesLen; Packet *newPacket = new Packet(PacketTypeEnum::MSGIN, from, text, channel); string encode = newPacket->Encode(); strncpy_s(buffer, encode.c_str(), 512); bytesLen = encode.length(); printf_s("out(%s)> %s", to.c_str(), buffer); wsaBuf.buf = buffer + bytesSent; wsaBuf.len = bytesLen - bytesSent; if (WSASend(UsersList[to]->cData->socket, &(wsaBuf), 1, &bytesSent, 0, NULL, NULL) == SOCKET_ERROR) { if (WSAGetLastError() != ERROR_IO_PENDING) { printf_s("WSASend failed with error %d\n", WSAGetLastError()); error = "Network error"; return false; } } return true; } bool SendChatMessage(string from, string to, string text, string &error) { error = ""; if (to.rfind("@", 0) != 0) { //Is direct message to user if (UsersList.count(to) == 0) { error = "Reciever not found"; return false; } return InternalSendMessage(from, to, "", text, error); } //Is message to channel to.erase(0, 1); vector<string> v = GetUsersListFromChannel(to); if (!v.empty() && v[0] == "#-404") { error = "Channel not found"; return false; } string t; for (string& usrName : v) { if (usrName == from) { continue; } InternalSendMessage(from, usrName, to, text, t); } return true; } void HandleClientState(ConnectionData *conData, IoOperationData *pIoData) { SOCKET socket = conData->socket; Packet *packet = conData->lastPacket; Packet *newPacket = NULL; string encode = ""; string s; vector<string> v; bool flag; ClientData *tclData; PacketTypeEnum type = PacketTypeEnum::INVALID; string status = "404"; string res = "Wrong Command"; string info = ""; switch (packet->Command) { case PacketTypeEnum::ID: type = PacketTypeEnum::ID; if (conData->userName != DEFAULT_USER) { status = "REJECT"; res = "REJECT"; info = "Already sign in."; break; } if (packet->FirstArgument == "") { status = "EMPTY"; res = "EMPTY"; info = "Username can't be an empty string"; break; } if (UsersList.count(packet->FirstArgument) != 0 || packet->FirstArgument == DEFAULT_USER) { status = "BUSY"; res = packet->FirstArgument; break; } conData->userName = packet->FirstArgument; tclData = new ClientData; tclData->ioData = pIoData; tclData->cData = conData; UsersList[conData->userName] = tclData; JoinUserToChannel(conData->userName, "global", flag); status = "OK"; res = conData->userName; break; case PacketTypeEnum::MSGT: type = PacketTypeEnum::MSGT; if (packet->FirstArgument.empty()) { status = "REJECT"; res = "REJECT"; info = "Reciever not specified"; break; } if (packet->SecondArgument.empty()) { status = "REJECT"; res = "REJECT"; info = "Text not specified"; break; } if (!SendChatMessage(conData->userName, packet->FirstArgument, packet->SecondArgument, info)) { status = "REJECT"; res = "REJECT"; break; } status = "OK"; res = "OK"; break; case PacketTypeEnum::USERS: type = PacketTypeEnum::USERS; if (packet->FirstArgument.empty()) { status = "OK"; res = vector_to_string(GetUsersList()); break; } v = GetUsersListFromChannel(packet->FirstArgument); if (!v.empty() && v[0] == "#-404") { status = "REJECT"; break; } status = "OK"; res = v.empty() ? "---" : vector_to_string(v); info = packet->FirstArgument; break; case PacketTypeEnum::CHANNELS: type = PacketTypeEnum::CHANNELS; status = "OK"; res = vector_to_string(GetChannels()); break; case PacketTypeEnum::JOIN: type = PacketTypeEnum::JOIN; res = packet->FirstArgument; if (res.empty()) { status = "REJECT"; info = "Channel not specified"; break; } if (!JoinUserToChannel(conData->userName, res, flag)) { status = "REJECT"; info = "Already in channel"; break; } status = "OK"; info = flag ? "Create" : "Join"; break; case PacketTypeEnum::LEAVE: type = PacketTypeEnum::LEAVE; res = packet->FirstArgument; if (res.empty()) { status = "REJECT"; info = "Channel not specified"; break; } if (!LeaveUserFromChannel(conData->userName, res, flag)) { status = "REJECT"; info = "Not in channel or channel not exist"; break; } status = "OK"; info = flag ? "Delete" : "Left"; break; default: pIoData->bytesRecv = 0; break; } newPacket = new Packet(type, status, res, info); encode = newPacket->Encode(); strncpy_s(pIoData->buffer, encode.c_str(), 512); pIoData->bytesRecv = encode.length(); printf_s("out(%s)> %s", conData->userName.c_str(), pIoData->buffer); }
e487856695bb0b7bd9f2dea3dbd755aae6e07071
626155e8aa7cda396b5bf320c13821d641213214
/yaf_opengl_engine/src/YafAnimation.cpp
bc2b08a333590b12fa5f3d6ef46460c723091392
[]
no_license
DDuarte/yaf-opengl-engine
cc8f750790177523e4a4a62bc7c076cc417eebb1
337afacc1068688c3e8e22e02acfc735634773dd
refs/heads/master
2021-01-02T08:39:26.635377
2014-01-06T20:32:24
2014-01-06T20:32:24
12,918,872
0
1
null
null
null
null
ISO-8859-3
C++
false
false
3,999
cpp
YafAnimation.cpp
#include "YafAnimation.h" #define _USE_MATH_DEFINES // for M_PI #define SPEED 5.0f #include <math.h> #include <cassert> #include <iostream> void YafLinearAnimation::ApplyAnimation() { Node->Position = _currentPoint; Node->Yaw = _currentAngle; } void YafPieceAnimation::ApplyAnimation() { Node->Position.X = _animation->GetCurrentPoint().X; Node->Position.Y = _animation->GetCurrentPoint().Y; // Node->Position.Z = _animation->GetCurrentPoint().Z; } int YafLinearAnimation::Position(unsigned long diff, float& path) { float distance = _speed * diff; for(int i = 0; i < _controlPointsDistance.size(); ++i) { float compare = 0; for (int j = i; j >= 0; --j) compare += _controlPointsDistance[j]; if (distance <= compare) { path = _controlPointsDistance[i] - (compare - distance); return i; } } return static_cast<int>(_controlPointsDistance.size()); } void YafLinearAnimation::Update(unsigned long millis) { if (_firstMillis == 0) _firstMillis = millis; unsigned long diff = millis - _firstMillis; float path; int position = Position(diff, path); _currentPoint = _controlPoints[position]; // ponto inicial do troço if (position != _controlPoints.size() - 1) { YafXYZ<> vector(_controlPoints[position + 1].X - _controlPoints[position].X, _controlPoints[position + 1].Y - _controlPoints[position].Y, _controlPoints[position + 1].Z - _controlPoints[position].Z); vector = vector.GetNormalized(); _currentPoint.X += vector.X * path; _currentPoint.Y += vector.Y * path; _currentPoint.Z += vector.Z * path; if (vector.Z != 0.0f) { _currentAngle = atan(vector.X / vector.Z) * 180.0f / static_cast<float>(M_PI); if (_currentAngle == 0.0f && vector.Z < 0.0f) _currentAngle = 180.0f; } else if (vector.X != 0.0f) _currentAngle = 90.0f * vector.X / abs(vector.X); } } YafLinearAnimation::YafLinearAnimation(const std::string& id, YafNode* node, float time, const std::vector<YafXYZ<>>& controlPoints) : YafAnimation(id, node), _time(static_cast<unsigned long>(time * 1000)), _controlPoints(controlPoints), _firstMillis(0), _currentPoint(controlPoints[0]), _currentAngle(0) { float distance = 0; for (int i = 0; i < _controlPoints.size() - 1; ++i) { auto dist = YafXYZ<>::GetDistance(_controlPoints[i], _controlPoints[i + 1]); distance += dist; _controlPointsDistance.push_back(dist); } _speed = distance / _time; } YafPieceAnimation::YafPieceAnimation(const std::string& id, YafNode* node, int x1, int y1, int x2, int y2) : YafAnimation(id, node) { MoveTo(x1, y1, x2, y2); } void YafPieceAnimation::Update(unsigned long millis) { _animation->Update(millis); } void YafPieceAnimation::MoveTo(int x1, int y1, int x2, int y2) { assert(x1 <= 7 && x1 >= 0 && y1 <= 6 && y1 >= 0 && "Invalid src coordinates in MoveTo"); assert(x2 <= 7 && x2 >= 0 && y2 <= 6 && y2 >= 0 && "Invalid dest coordinates in MoveTo"); auto moveFrom = BoardIndexesToXY(x1, y1); auto moveTo = BoardIndexesToXY(x2, y2); std::vector<YafXYZ<>> points(2); points[0] = YafXYZ<>(moveFrom.X, moveFrom.Y, 0.0f); points[1] = YafXYZ<>(moveTo.X, moveTo.Y, 0.0f); auto dist = sqrt(pow(moveTo.X - moveFrom.X, 2.0f) + pow(moveTo.Y - moveFrom.Y, 2.0f)); _animation = new YafLinearAnimation(Id + "In", Node, dist / SPEED, points); } YafPieceAnimation::~YafPieceAnimation() { delete _animation; } YafXY<> YafPieceAnimation::BoardIndexesToXY(int xi, int yi) { if (xi == 0) yi *= 2; YafXY<> move; move.Y = (6.0f - yi) * -2.35f; if (yi % 2 == 0) move.X = (7.0f - xi) * 2.7f; else move.X = (7.0f - (xi - 1.0f)) * 2.7f - 1.35f; move.X += -9.45f; move.Y += 7.05f; return move; }
466d4a149254071c754f137fcd7e80ab9ecfef51
a7ff96e37278abb16d03890cae1e6c932b4c9705
/Design pattern/Bridge Pattern/ShapeColor/RedCircle.h
3b7f55ff411fe3ef653b0e3a2a6f8bf73637e304
[]
no_license
vectormars/CPP
c42b2b4812b44935bd02cc2c0e22be1777b45228
20e8347a1ec50f75acead3d55bf1209dd01714cf
refs/heads/master
2021-09-18T20:39:52.055912
2018-07-19T17:45:02
2018-07-19T17:45:02
106,834,183
0
3
null
null
null
null
UTF-8
C++
false
false
256
h
RedCircle.h
#ifndef REDCIRCLE_H #define REDCIRCLE_H #include "DrawAPI.h" class RedCircle : public DrawAPI { public: RedCircle(); virtual ~RedCircle(); void drawCircle(int radius, int x, int y); }; #endif // REDCIRCLE_H
8da8c617542d05519038bde01e7c089ed04d31f4
76c634da5d112ee73eae99e2ab264ab89288becb
/src/pdm/core/intern.cc
919c0245be5e918b7c596543d2bffb64df238147
[]
no_license
tsnl/pdm
ff3fa060507af11750084773c082add571b99acf
e5ab16df612b2fda9fc0b85a0a25631be086af85
refs/heads/master
2023-04-16T18:01:28.665742
2021-03-03T05:27:48
2021-03-03T05:27:50
286,868,703
4
0
null
null
null
null
UTF-8
C++
false
false
1,023
cc
intern.cc
extern "C" { #include <intern/strings.h> } #include "intern.hh" namespace pdm::intern { // // Static String Manager: // String::Manager String::s_manager; String::Manager::Manager() : m_strings_repository(nullptr) {} void String::Manager::ensure_init() { if (m_strings_repository == nullptr) { m_strings_repository = strings_new(); } } String::Manager::~Manager() { if (s_manager.m_strings_repository != nullptr) { strings_free(s_manager.m_strings_repository); } s_manager.m_strings_repository = nullptr; } // // String: // String::String(char const* str_content) : m_id(0) { m_id = strings_intern(s_manager.m_strings_repository, str_content); } char const* String::content() const { return strings_lookup_id(s_manager.m_strings_repository, m_id); } void String::ensure_init() { s_manager.ensure_init(); } } // namespace pdm::intern
f274eb6ec4e4f58e1fb5674ce690ba1c800f4c04
b0494ca4b386fdd71323a7a15126fe2e2200a86f
/src/base/object.cpp
b4d8f2bc7d835f15b247cb85ecc877b92e1ce727
[]
no_license
3dem/emcore
c0a37f9feb1dee088c0fc66da93c195445972451
6189d4e9f9bb4b05ff41bc0bd72204283b93957a
refs/heads/master
2021-03-27T15:46:16.680917
2020-03-23T13:44:28
2020-03-23T13:44:28
93,826,644
5
0
null
2020-03-23T13:44:29
2017-06-09T06:31:38
C++
UTF-8
C++
false
false
2,690
cpp
object.cpp
// // Created by josem on 12/4/16. // #include <sstream> #include "emc/base/object.h" using namespace emcore; namespace emc = emcore; Object::Object(const Object &other) { *this = other; } // Ctor Object Object::Object(Object &&other) noexcept { swap(std::move(other)); } // Move ctor Object::Object(const Type & type, void *memory): TypedContainer(type, 1, memory) { } // Ctor from type and memory void Object::setType(const Type & newType) { if (newType != getType()) { Object o(newType); o.set(*this); swap(std::move(o)); } } // function Object.setType Object Object::getView() { return Object(getType(), getData()); } // function Object.getView void Object::toStream(std::ostream &ostream) const { auto& type = getType(); if (!type.isNull()) type.toStream(getData(), ostream, 1); } // function Object.toStream void Object::fromStream(std::istream &istream) { auto& type = getType(); ASSERT_ERROR(type.isNull(), "Null type object can not be parsed. "); type.fromStream(istream, getData(), 1); } // function Object.fromStream std::string Object::toString() const { std::stringstream ss; toStream(ss); return ss.str(); } // function Object.toString void Object::fromString(const std::string &str) { std::stringstream ss(str); fromStream(ss); } // function Object.fromString bool Object::operator==(const Object &other) const { auto& type = getType(); if (type != other.getType() || type.isNull()) return false; return type.equals(getData(), other.getData(), 1); } // function Object.operator== bool Object::operator!=(const Object &other) const { return ! (*this == other); } // function Object.operator!= bool Object::operator>(const Object &other) const { auto& type = getType(); if (type != other.getType() || type.isNull()) return false; return type.compare(getData(), other.getData()) > 0; } // function Object.operator> bool Object::operator<(const Object &other) const { auto& type = getType(); if (type != other.getType() || type.isNull()) return false; return type.compare(getData(), other.getData()) < 0; } // function Object.operator< std::ostream& emc::operator<< (std::ostream &ostream, const Object &object) { object.toStream(ostream); return ostream; } Object& Object::operator=(const Object &other) { allocate(other.getType(), 1); copyOrCast(other, 1); return *this; } Object& Object::operator=(Object &&other) noexcept { swap(std::move(other)); return *this; } void Object::set(const Object &other) { copyOrCast(other, 1); } // function Object.set
96084e2506d2e2b1b3b5dbd7365e463892f88136
bdc132b6fd4b693d56e093b55b99af2a7fad2c46
/leetcode/merge-intervals.cc
6a629964a6fc18e1d35320388537e6bacc48db77
[]
no_license
ailyanlu/my-acm-solutions
8f76b8e9898ec8c97463bb619c7fbc72a662ec7e
fc79e6284ea57ce561e7c8c9c0e5c08e06e1c36b
refs/heads/master
2017-10-07T16:14:45.706176
2016-04-30T06:38:26
2016-04-30T06:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,022
cc
merge-intervals.cc
#include <algorithm> #include <iostream> #include <vector> using std::vector; /** * Definition for an interval. */ struct Interval { int start; int end; Interval() : start(0), end(0) { } Interval(int s, int e) : start(s), end(e) { } }; inline bool intervalCompare(const Interval& lhs, const Interval& rhs) { if (lhs.start != rhs.start) { return lhs.start < rhs.start; } return lhs.end < rhs.end; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { std::sort(intervals.begin(), intervals.end(), intervalCompare); vector<Interval> result; int size = intervals.size(); int i = 0, j; while (i < size) { Interval curr = intervals[i]; for (j = i + 1; j < size; ++j) { if (curr.end < intervals[j].start) { break; } else { curr.end = std::max(curr.end, intervals[j].end); } } i = j; result.push_back(curr); } return result; } }; Solution solu; int main() { vector<Interval> intervals, merged; intervals.push_back(Interval(1, 3)), intervals.push_back(Interval(2, 6)); intervals.push_back(Interval(8, 10)), intervals.push_back(Interval(15, 18)); merged = solu.merge(intervals); for (int i = 0; i < merged.size(); ++i) { std::cout << merged[i].start << ' ' << merged[i].end << std::endl; } std::cout << std::endl; intervals.clear(); intervals.push_back(Interval(1, 3)), intervals.push_back(Interval(2, 6)); intervals.push_back(Interval(6, 12)), intervals.push_back(Interval(8, 10)); intervals.push_back(Interval(8, 10)), intervals.push_back(Interval(15, 18)); merged = solu.merge(intervals); for (int i = 0; i < merged.size(); ++i) { std::cout << merged[i].start << ' ' << merged[i].end << std::endl; } std::cout << std::endl; return 0; }
618ea2134c9b041a2e7329f62875a7d8ff76d3d9
86c02e6e90c3df298008ad4034d746ddc77442fe
/player/src/main/cpp/common/CallBackJava.cpp
6dfe70997eaa758e53a967a44ab2cd400107aa63
[]
no_license
huozhenpeng/re_study_av
00f5e4ec0443d53dec05ae339842cb1f616a3543
847f7433966b3f9d83c57cea3a3047b13546f22e
refs/heads/master
2020-11-28T00:07:26.327521
2020-01-07T10:46:07
2020-01-07T10:46:07
229,655,055
0
0
null
null
null
null
UTF-8
C++
false
false
3,722
cpp
CallBackJava.cpp
// // Created by 霍振鹏 on 2019-12-24. // #include "CallBackJava.h" #include "../head/log.h" CallBackJava::CallBackJava(JavaVM *vm, JNIEnv *env, jobject job) { javaVm=vm; jniEnv=env; instance=job; jclass jcl=env->GetObjectClass(job); //现在的androidstudio好智能,java端不写这个方法也会报错 jmd=env->GetMethodID(jcl,"callBackJava","(ILjava/lang/String;)V"); jmd_complete=env->GetMethodID(jcl,"onPlayComplete","(ILjava/lang/String;)V"); jmd_time=env->GetMethodID(jcl,"onShowTime","(III)V"); jmid_valumedb = env->GetMethodID(jcl, "onCallValumeDB", "(II)V"); jmid_pcmtoaac = env->GetMethodID(jcl, "encodecPcmToAAc", "(I[B)V"); } void CallBackJava::onCallBack(int type, int code, const char *msg) { if(type==CHILD_THREAD) { //重新给jniEnv赋值 javaVm->AttachCurrentThread(&jniEnv,0); //构造返回给java的字符串 jstring jsr=jniEnv->NewStringUTF(msg); jniEnv->CallVoidMethod(instance,jmd,code,jsr); //释放jstring jniEnv->DeleteLocalRef(jsr); javaVm->DetachCurrentThread(); } else if(type==MAIN_THREAD) { jstring jsr=jniEnv->NewStringUTF(msg); jniEnv->CallVoidMethod(instance,jmd,code,jsr); //释放jstring jniEnv->DeleteLocalRef(jsr); } } CallBackJava::~CallBackJava() { LOGI("CallBackJava 析构函数执行了"); } void CallBackJava::onShowTime(int type, int code, int total, int current) { if(type==CHILD_THREAD) { //重新给jniEnv赋值 javaVm->AttachCurrentThread(&jniEnv,0); jniEnv->CallVoidMethod(instance,jmd_time,code,total,current); javaVm->DetachCurrentThread(); } else if(type==MAIN_THREAD) { jniEnv->CallVoidMethod(instance,jmd_time,code,total,current); } } void CallBackJava::onPlayComplete(int type, int code, const char *msg) { if(type==CHILD_THREAD) { //重新给jniEnv赋值 javaVm->AttachCurrentThread(&jniEnv,0); //构造返回给java的字符串 jstring jsr=jniEnv->NewStringUTF(msg); jniEnv->CallVoidMethod(instance,jmd_complete,code,jsr); //释放jstring jniEnv->DeleteLocalRef(jsr); javaVm->DetachCurrentThread(); } else if(type==MAIN_THREAD) { jstring jsr=jniEnv->NewStringUTF(msg); jniEnv->CallVoidMethod(instance,jmd_complete,code,jsr); javaVm->DetachCurrentThread(); } } void CallBackJava::onCallValumeDB(int type, int db,int currentTime) { if(type == MAIN_THREAD) { jniEnv->CallVoidMethod(instance, jmid_valumedb, db,currentTime); } else if(type == CHILD_THREAD) { //重新给jniEnv赋值 javaVm->AttachCurrentThread(&jniEnv,0); //构造返回给java的字符串 jniEnv->CallVoidMethod(instance,jmid_valumedb,db,currentTime); javaVm->DetachCurrentThread(); } } void CallBackJava::onCallPcmToAAC(int type, int size, void *buffer) { if(type==MAIN_THREAD) { jbyteArray jbuffer=jniEnv->NewByteArray(size); jniEnv->SetByteArrayRegion(jbuffer, 0, size, static_cast<const jbyte *>(buffer)); jniEnv->CallVoidMethod(instance,jmid_pcmtoaac,size,jbuffer); jniEnv->DeleteLocalRef(jbuffer); } else if(type==CHILD_THREAD) { //重新给jniEnv赋值 javaVm->AttachCurrentThread(&jniEnv,0); jbyteArray jbuffer=jniEnv->NewByteArray(size); jniEnv->SetByteArrayRegion(jbuffer, 0, size, static_cast<const jbyte *>(buffer)); jniEnv->CallVoidMethod(instance,jmid_pcmtoaac,size,jbuffer); jniEnv->DeleteLocalRef(jbuffer); javaVm->DetachCurrentThread(); } }
fd656fbd95e60764056fe6331d6a256407fdfc68
260a986070c2092c2befabf491d6a89b43b8c781
/coregame/claim.h
2f8bc1224f89781e5b3b02e8665d094ccffb1b6b
[]
no_license
razodactyl/darkreign2
7801e5c7e655f63c6789a0a8ed3fef9e5e276605
b6dc795190c05d39baa41e883ddf4aabcf12f968
refs/heads/master
2023-03-26T11:45:41.086911
2020-07-10T22:43:26
2020-07-10T22:43:26
256,714,317
11
2
null
2020-04-20T06:10:20
2020-04-18T09:27:10
C++
UTF-8
C++
false
false
7,662
h
claim.h
/////////////////////////////////////////////////////////////////////////////// // // Copyright 1997-1999 Pandemic Studios, Dark Reign II // // Region Claiming System // // 17-AUG-1999 // #ifndef __CLAIM_H #define __CLAIM_H // // Includes // #include "bitarray.h" #include "unitobjdec.h" /////////////////////////////////////////////////////////////////////////////// // // Namespace Claim - Region Claiming System // namespace Claim { // Each claim layer enum LayerId { LAYER_LOWER, LAYER_UPPER, // Number of layers LAYER_COUNT }; // Forward declarations class Row; class Layer; class Manager; /////////////////////////////////////////////////////////////////////////////// // // Struct ProbeInfo - Results of a probe // struct ProbeInfo { // Number of obstacles U8 owned; // Number of claims of unowned (footprints) U8 unowned; // Array of obstacles UnitObj* obstacles[4]; }; /////////////////////////////////////////////////////////////////////////////// // // Struct Block - A block of claimed grains in a single row // struct Block { // The start and end positions of this block (inclusive) S32 x0, z0, x1; // The layer this block is within Layer& layer; // The manager this block belongs to Manager& manager; // The arbitrary key assigned to this block U32 key; // Next/previous blocks in the group Block* nextInGroup; Block* prevInGroup; // Node for the row NList<Block>::Node rowNode; // Node for the manager NList<Block>::Node managerNode; // Constructor and destructor Block(S32 x0, S32 z0, S32 x1, Layer& layer, Manager& manager, U32 key); ~Block(); // Returns the next/previous block in the row, or NULL Block* NextInRow(); Block* PrevInRow(); // Returns the row this block is within Row& GetRow(); // Adds the block to a group void AddToGroupPrev(Block* prev); void AddToGroupNext(Block* next); // Removes the block from a group void RemoveFromGroup(); // Get the first block in this group Block& GroupHead(); // Get the last block in this group Block& GroupTail(); // Validate the position of this block void Validate(); }; /////////////////////////////////////////////////////////////////////////////// // // Class Row - A list of blocks claimed for each row // class Row : public NList<Block> { // The sliding pointer NList<Block>::Node* slider; // Slides to the first block infront of the given grain void Slide(S32 x); public: // Constructor and destructor Row(); ~Row(); // Insert the given block void InsertBlock(Block* block); // Remove the given block void RemoveBlock(Block* block); // Probe to see if the given grains are available (inclusive) Bool Probe(S32 x0, S32 x1); // Validate each block in this row void Validate(); }; /////////////////////////////////////////////////////////////////////////////// // // Class Layer - A single map layer holding rows // class Layer { // Bit array for probes BitArray2d claimed; // Rows for this layer Row* rows; // Layer id LayerId id; // Probe the given region using the row data Bool ProbeRows(S32 x0, S32 z0, S32 x1, S32 z1); public: // Constructor and destructor Layer(); ~Layer(); // Returns the given row Row& GetRow(S32 z); // Set the claimed bits for the given region void Set(S32 x0, S32 z0, S32 x1, S32 z1); // Clear the claimed bits for the given region void Clear(S32 x0, S32 z0, S32 x1, S32 z1); void Clear(S32 x0, S32 z0, S32 x1); // Probes the given row for any claimed bits Bool Probe(S32 z, S32 x0, S32 x1); // Probes the given region for any claimed bits Bool Probe(S32 x0, S32 z0, S32 x1, S32 z1); // Validate each row in this layer void Validate(); // Get the bit array of claimed grains BitArray2d& GetClaimed() { return (claimed); } // Set the id of the layer void SetId(LayerId i) { id = i; } // Get the id of the layer LayerId GetId() { return (id); } }; /////////////////////////////////////////////////////////////////////////////// // // Class Manager - The interface to block claiming // class Manager : public NList<Block> { // The layer used for claims Layer* layer; // The object that owns this claim UnitObj* owner; public: // Constructor and destructor Manager(UnitObj* unitObj, LayerId id = LAYER_LOWER); ~Manager(); // Change the default layer to be used for claiming LayerId ChangeDefaultLayer(LayerId id); // Probe the given region using bit array Bool Probe(S32 x0, S32 z0, S32 x1, S32 z1, ProbeInfo* probeInfo = NULL); // Probe the given region using bit array, but ignoring our own region Bool ProbeIgnore(S32 x0, S32 z0, S32 x1, S32 z1, U32 key, ProbeInfo* probeInfo = NULL); // Claim using the default layer void Claim(S32 x0, S32 z0, S32 x1, S32 z1, U32 key = 0); // Release all blocks with the given key void Release(U32 key = 0, Layer* l = NULL); // Finds the closest movable/claimable grain Bool FindClosestGrain(S32& xPos, S32& zPos, U32 grainSize, U8 tractionType, U32 range = 8); // Return owner of this manager UnitObj* GetOwner() { return (owner); } // Return the layer that this manager is currently using LayerId GetLayer() { ASSERT(layer) return (layer->GetId()); } // Return layer pointer Layer* GetLayerPtr() { ASSERT(layer) return (layer); } #ifdef DEVELOPMENT // Debugging void RenderDebug(); #endif }; /////////////////////////////////////////////////////////////////////////////// // // System Functions // // Initialize and shutdown system void Init(); void Done(); // Probe a region Bool Probe(S32 x0, S32 z0, S32 x1, S32 z1, LayerId layer = LAYER_LOWER, UnitObj* filter = NULL); // Probe a game cell Bool ProbeCell(S32 x, S32 z, LayerId layer = LAYER_LOWER, UnitObj* filter = NULL); // Find the first available grain in the given cell Bool FindGrainInCell(S32 x, S32 z, S32& gx, S32& gz, U32 grains, LayerId layer = LAYER_LOWER, UnitObj* filter = NULL); // Return the owner of a given grain UnitObj* GetOwner(S32 x, S32 z, LayerId layer); // Validate all current layers void Validate(); #ifdef DEVELOPMENT // Debugging void RenderDebug(); #endif } #endif
a408378d65339dd71d3a1ce9a7bf10f2612a7f41
a8b0807cc7f93d5d343142a9b5b5a81dde3ca396
/Order/OrderItem/OrderItemButton.cpp
aea2a146c36b49425f7f069dc863281dc28a0bec
[]
no_license
QtWorks/wsr_pos_qt
a63e7b23edd216f78d519f01485bfb5353428406
2a83d793c29b4be1c795220c922b1f69d8eac684
refs/heads/master
2021-01-25T04:58:28.142221
2016-01-02T07:52:48
2016-01-02T07:52:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,143
cpp
OrderItemButton.cpp
#include <QStyleOption> #include <QPainter> #include "OrderItemButton.h" #include "StyleSheet.h" OrderItemButton::OrderItemButton(QWidget *parent, OrderItem *order_item) : QWidget(parent), mOrderItem(order_item) { mLabelTitle = new QLabel(this); mLabelUnitPrice = new QLabel(this); mButtonAmountDecrease = new QToolButton(this); mLabelAmount = new QLabel(this); mButtonAmountIncrease = new QToolButton(this); mLabelSubTotalPrice = new QLabel(this); mButtonDiscount = new QPushButton(this); mLabelTotalPrice = new QLabel(this); mButtonAmountDecrease->setStyleSheet(PUSH_BUTTON_STYLE_SHEET_1(GRASS, GRASS_DARK)); mButtonDiscount->setStyleSheet(PUSH_BUTTON_STYLE_SHEET_1(GRASS, GRASS_DARK)); setStyleSheet(PUSH_BUTTON_STYLE_SHEET_2(3, SHOPKEEP_ORDER_ITEM, SHOPKEEP_ORDER_ITEM)); mLabelTitle->setGeometry(LABEL_TITLE_X, LABEL_TITLE_Y, LABEL_TITLE_W, LABEL_TITLE_H); mButtonAmountDecrease->setGeometry(BUTTON_AMOUNT_DECREASE_X, BUTTON_AMOUNT_DECREASE_Y, BUTTON_AMOUNT_DECREASE_W, BUTTON_AMOUNT_DECREASE_H); mLabelAmount->setGeometry(LABEL_AMOUNT_X, LABEL_AMOUNT_Y, LABEL_AMOUNT_W, LABEL_AMOUNT_H); mButtonAmountIncrease->setGeometry(BUTTON_AMOUNT_INCREASE_X, BUTTON_AMOUNT_INCREASE_Y, BUTTON_AMOUNT_INCREASE_W, BUTTON_AMOUNT_INCREASE_H); mLabelUnitPrice->setGeometry(LABEL_UNIT_PRICE_X, LABEL_UNIT_PRICE_Y, LABEL_UNIT_PRICE_W, LABEL_UNIT_PRICE_H); mLabelSubTotalPrice->setGeometry(LABEL_SUB_TOTAL_PRICE_X, LABEL_SUB_TOTAL_PRICE_Y, LABEL_SUB_TOTAL_PRICE_W, LABEL_SUB_TOTAL_PRICE_H); mButtonDiscount->setGeometry(LABEL_DISCOUNT_X, LABEL_DISCOUNT_Y, LABEL_DISCOUNT_W, LABEL_DISCOUNT_H); mLabelTotalPrice->setGeometry(LABEL_TOTAL_PRICE_X, LABEL_TOTAL_PRICE_Y, LABEL_TOTAL_PRICE_W, LABEL_TOTAL_PRICE_H); qDebug("BUTTON_AMOUNT_DECREASE_X:%d", BUTTON_AMOUNT_DECREASE_X); qDebug("BUTTON_AMOUNT_DECREASE_W:%d", BUTTON_AMOUNT_DECREASE_W); qDebug("LABEL_AMOUNT_X:%d", LABEL_AMOUNT_X); qDebug("LABEL_AMOUNT_W:%d", LABEL_AMOUNT_W); qDebug("BUTTON_AMOUNT_INCREASE_X:%d", BUTTON_AMOUNT_INCREASE_X); qDebug("BUTTON_AMOUNT_INCREASE_W:%d", BUTTON_AMOUNT_INCREASE_W); QFont font; font.setFamily(QString("맑은 고딕")); font.setPointSize(12); mLabelTitle->setFont(font); mLabelAmount->setFont(font); mLabelUnitPrice->setFont(font); mLabelSubTotalPrice->setFont(font); mButtonDiscount->setFont(font); mLabelTotalPrice->setFont(font); mLabelTitle->setStyleSheet("background-color: rgba(10,0,0,50%)"); mButtonAmountDecrease->setText("<"); mLabelAmount->setStyleSheet("qproperty-alignment: 'AlignCenter'; background-color: rgba(0,20,0,50%)"); mButtonAmountIncrease->setText(">"); mButtonAmountIncrease->setStyleSheet(TOOL_BUTTON_STYLE_SHEET_2()); mLabelUnitPrice->setStyleSheet("qproperty-alignment: 'AlignCenter | AlignRight'; background-color: rgba(0,0,30,50%)"); mLabelSubTotalPrice->setStyleSheet("qproperty-alignment: 'AlignCenter | AlignRight'; background-color: rgba(50,0,0,50%)"); // mLabelDiscount->setStyleSheet("qproperty-alignment: 'AlignCenter | AlignRight'; background-color: rgba(0,50,0,50%)"); mLabelTotalPrice->setStyleSheet("qproperty-alignment: 'AlignCenter | AlignRight'; background-color: rgba(0,0,50,50%)"); refreshData(); connect(mButtonAmountDecrease, SIGNAL(clicked()), this, SLOT(decreaseAmount())); connect(mButtonAmountIncrease, SIGNAL(clicked()), this, SLOT(increaseAmount())); connect(mButtonDiscount, SIGNAL(clicked()), this, SLOT(showDiscountPanel())); } void OrderItemButton::refreshData() { mLabelTitle->setText(mOrderItem->getItem()->getName()); mLabelAmount->setText(QString::number(mOrderItem->getAmount())); mLabelUnitPrice->setText(QLocale(QLocale::Korean).toString(mOrderItem->getItem()->getPrice())); mLabelSubTotalPrice->setText(QLocale(QLocale::Korean).toString(mOrderItem->getSubTotalPrice())); mButtonDiscount->setText(QLocale(QLocale::Korean).toString(mOrderItem->getDiscountPercent())); mLabelTotalPrice->setText(QLocale(QLocale::Korean).toString(mOrderItem->getTotalPrice())); update(); emit changeOrderItem(this); } bool OrderItemButton::compareItem(Item* item) { if(mOrderItem->getItem() == item) { return true; } return false; } void OrderItemButton::increaseAmount(uint amount) { mOrderItem->increaseItem(amount); refreshData(); } void OrderItemButton::decreaseAmount(uint amount) { mOrderItem->decreaseItem(amount); refreshData(); } void OrderItemButton::showDiscountPanel() { DiscountPanel *dp = new DiscountPanel(this, DiscountPanel::DISCOUNT); dp->show(); connect(dp, SIGNAL(discount(TabButton::TYPE,uint)), this, SLOT(setDiscount(TabButton::TYPE,uint))); } void OrderItemButton::setDiscount(TabButton::TYPE type, uint value) { switch(type) { case TabButton::PRICE: { getOrderItem()->setDiscountPrice(value); break; } case TabButton::PERCENT: { getOrderItem()->setDiscountPercent(value); break; } case TabButton::CUSTOM: { break; } } refreshData(); } OrderItem* OrderItemButton::getOrderItem() { return mOrderItem; } void OrderItemButton::paintEvent(QPaintEvent *) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); }
29c48ecf85ed54a9608a1ef24575d4fd36e6a329
6d7dee5d230d6912478dc53d726679c8f429fa45
/src/hashing/SimHasher.h
006ce976ebd72c99f8e672a9603a6f9b89f1a31b
[]
no_license
scivey/libtexty
8b9a4f2c6611a0bdd57d2df36f66144a2c7af2dd
5c7c6c925afaed13e5d0b6c4ecae41f07c7c2ab2
refs/heads/master
2021-01-21T13:21:03.396060
2016-02-01T11:51:40
2016-02-01T11:51:40
50,074,918
0
1
null
null
null
null
UTF-8
C++
false
false
1,477
h
SimHasher.h
#pragma once #include <functional> #include <bitset> #include <array> namespace texty { namespace hashing { template<typename TValue> class SimHasher { public: static const size_t N = 64; using value_type = TValue; using hashed_type = uint64_t; using HashFunc = std::function<hashed_type (const value_type&, hashed_type)>; protected: using HashArray = std::array<int32_t, N>; HashFunc hashFunc_; hashed_type seed_; void addToHash(HashArray &data, const value_type &item) { std::bitset<N> hashBits = hashFunc_(item, seed_); for (size_t i = 0; i < N; i++) { if (hashBits[i] == 0) { data[i] -= 1; } else { data[i] += 1; } } } public: SimHasher(HashFunc hashFunc, hashed_type seed) : hashFunc_(hashFunc), seed_(seed) {} template<typename TCollection> hashed_type hash(const TCollection &valueCollection) { HashArray hashAccumulator; for (size_t i = 0; i < N; i++) { hashAccumulator[i] = 0; } for (auto &item: valueCollection) { addToHash(hashAccumulator, item); } std::bitset<N> hashBits; for (size_t i = 0; i < N; i++) { if (hashAccumulator[i] >= 0) { hashBits[i] = 1; } } return hashBits.to_ullong(); } template<template<class...> class TTmpl, typename ...Types> hashed_type hash(const TTmpl<TValue, Types...> &valueCollection) { return hash<TTmpl<TValue, Types...>>(valueCollection); } }; }} // texty::hashing
22a51da2ee33c8fd93a89d8179954636c97b86ef
03a323afc3de87da472ed62fd6a30e66395953d3
/src/stripserver.cpp
8934a67422ae33163383adeaccc4d5e7832507ae
[]
no_license
olyd/st
a0a7c026295a8e736449c93f8927eac2c0ea5dbc
be10bf5be80f05a03b8c467f4120746d12ef8611
refs/heads/master
2020-05-17T19:29:32.789338
2015-01-08T01:18:55
2015-01-08T01:18:55
20,402,661
0
0
null
null
null
null
UTF-8
C++
false
false
17,737
cpp
stripserver.cpp
#include "stripserver.h" #include <pthread.h> #include <sys/socket.h> #include <sys/epoll.h> #include <cstdlib> #include <cstring> #include <cassert> #include <sstream> #include <cmath> #include "utils.h" #include "message.h" #include "timer.h" #include "dataserverthreadsafe.h" #include "dbufferthreadsafe.h" #include "log.h" #include "diskmgr.h" void *ThreadPerClient_(void *arg) { Pthread_detach(pthread_self()); struct RequestArgs *ptr = (struct RequestArgs *)arg; ptr->server->ThreadPerClient(ptr); free(ptr); return (void *)NULL; } void *ThreadEvent_(void *arg) { Pthread_detach(pthread_self()); ((StripServer *)arg)->ThreadEvent(); return (void *)NULL; } StripServer::StripServer(int serverid, ConfigStrip *config) : Server(serverid), m_config(config) { m_take_sample_frequency = config->sampleFrequency; // 采样周期,秒 m_server_band = config->serverBand; // 服务器带宽 m_client_band = config->clientBand; // 客户端带宽 m_p2p = config->isP2POpen; // p2p是否开启 m_real_device = config->isUseRealDevice; // 是否读取真实磁盘 m_port = config->serverPort; // 服务器端口 m_clientport = config->clientPort; // 客户端端口 m_place_strategy = config->placeStrategy; // 分块仿真策略 m_disk_band = config->diskBand; // 不同分片大小下的磁盘带宽,单线程 assert(m_place_strategy == "rr" || m_place_strategy == "ram" || m_place_strategy == "fdrr"); m_block_size = config->blockSize; // 分块大小,MB m_block_num = config->serverBlockNum; // 服务器端缓冲块数目 m_period = config->period; // 算法周期 m_lrfulambda = config->lrfuLambda; // lrfu算法的lambda m_buffer = new DBufferThreadSafe(m_block_size, m_block_num, m_period, m_lrfulambda, config->serverStrategy); m_filenum = config->sourceNums; // 资源数目 m_min_length = config->minLength; // 文件最小长度 m_max_length = config->maxLength; // 文件最大长度 m_min_bitrate = config->minBitRate; // 文件最小码率 m_max_bitrate = config->maxBitRate; // 文件最大码率 m_diskNum = config->diskNumber; // 磁盘数目 m_data_server = new DataServerThreadSafe(m_filenum, m_min_length, m_max_length, m_block_size, m_min_bitrate, m_max_bitrate, m_diskNum); m_total_request = 0; m_read_from_server = 0; m_buffer_hit = 0; m_buffer_miss = 0; m_linkcount = 0; m_current_load = 0; // m_real_load = 0; Pthread_mutex_init(&m_facktran_mutex, NULL); pthread_cond_init(&m_facktran_cond, NULL); for(int i = 0;i <= MAX_CLIENT_NUM;i++){ m_clientinfo[i].recvFd = -1; } m_diskMgr = new DiskMgr(config); m_buffer_ofs.open("data/buffer.log", ios::out); m_access_balance_degree_ofs.open("data/balance_degree.log", ios::out); } void StripServer::Run() { int socketid = Socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in serveraddr; TimerEvent timer_event; pthread_t tid; m_event_fd = epoll_create(MAX_LISTEN_NUM); epoll_event ev; // 初始化 m_buffer_reset_fd Socketpair(AF_UNIX, SOCK_STREAM, 0, m_buffer_reset_fd); ev.data.fd = m_buffer_reset_fd[0]; ev.events = EPOLLIN; epoll_ctl(m_event_fd, EPOLL_CTL_ADD, m_buffer_reset_fd[0], &ev); // 初始化 m_facktran_fd // Socketpair(AF_UNIX, SOCK_STREAM, 0, m_facktran_fd); // ev.data.fd = m_facktran_fd[0]; // ev.events = EPOLLIN; // epoll_ctl(m_event_fd, EPOLL_CTL_ADD, m_facktran_fd[0], &ev); // 初始化 m_take_sample_fd Socketpair(AF_UNIX, SOCK_STREAM, 0, m_take_sample_fd); ev.data.fd = m_take_sample_fd[0]; ev.events = EPOLLIN; epoll_ctl(m_event_fd, EPOLL_CTL_ADD, m_take_sample_fd[0], &ev); Pthread_create(&tid, NULL, ThreadEvent_, this); // 注册第一次buffer reset事件 timer_event.sockfd = m_buffer_reset_fd[1]; timer_event.left_time = m_period * TIMER_SCALE; Timer::GetTimer()->RegisterTimer(timer_event); // 注册第一次take sample事件 timer_event.sockfd = m_take_sample_fd[1]; timer_event.left_time = m_take_sample_frequency * TIMER_SCALE; Timer::GetTimer()->RegisterTimer(timer_event); // 监听服务器端口,开始服务客户端 bzero(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons(m_port); // 设置套接字选项,避免出现地址正在使用而无法绑定的错误 int val = 1; setsockopt(socketid,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(val)); Bind(socketid, (struct sockaddr *)&serveraddr, sizeof(serveraddr)); Listen(socketid, 3); struct RequestArgs* args; int connfd; socklen_t clilen; while (true) { args = (struct RequestArgs *)Malloc(sizeof(struct RequestArgs)); bzero(&args->cliaddr, sizeof(args->cliaddr)); clilen = sizeof(args->cliaddr); connfd = Accept(socketid, (struct sockaddr *)&(args->cliaddr), &clilen); args->server = this; args->connfd = connfd; Pthread_create(&tid, NULL, ThreadPerClient_, args); } } StripServer::~StripServer() { for(int i = 0;i <= MAX_CLIENT_NUM;i++) { if(m_clientinfo[i].recvFd != -1){ close(m_clientinfo[i].recvFd); } } delete m_buffer; delete m_data_server; m_buffer_ofs.close(); m_access_balance_degree_ofs.close(); Pthread_mutex_destroy(&m_facktran_mutex); pthread_cond_destroy(&m_facktran_cond); } void StripServer::ThreadPerClient(struct RequestArgs *arg) { int length; char buffer[MESSAGELEN]; char response[MESSAGELEN]; int *ptr; int * const resptr = (int *)response; int clientid; int fileid, ofileid; int segid, osegid; int linkednum; double delay; int best_clientid; int connfd = arg->connfd; struct sockaddr_in cliaddr = arg->cliaddr; int port; double bitrate; int segnum; //long long left_time; //long long sleep_time; //timeval begin_time, end_time; //timespec tm; int total_request, read_from_server, buffer_hit, buffer_miss; //int ret; //pthread_mutex_t facktran_mutex_temp; //pthread_cond_t facktran_cond_temp; while (true) { length = read(connfd, buffer, MESSAGELEN); //assert(length == MESSAGELEN); ptr = (int *)buffer; switch(ptr[0]) { case MSG_CLIENT_JOIN: clientid = ptr[1]; LOG_INFO("server receive MSG_CLIENT_JOIN from " << clientid << " and response MSG_JOIN_ACK"); m_clientinfo[clientid].address.sin_addr = cliaddr.sin_addr; port = m_clientport + clientid - 1; m_clientinfo[clientid].address.sin_port = htons(port); m_clientinfo[clientid].recvFd = connfd; ++m_linkcount; resptr[0] = MSG_JOIN_ACK; resptr[1] = 0; length = send(connfd, response, MESSAGELEN, 0); assert(length == MESSAGELEN); break; case MSG_CLIENT_LEAVE: clientid = ptr[1]; LOG_INFO("server receive MSG_CLIENT_LEAVE from " << clientid); break; case MSG_DELETE_SEG: //客户端缓冲区删除某一缓存块 clientid = ptr[1]; fileid = ptr[2]; segid = ptr[3]; LOG_INFO("server receive MSG_DELETE_SEG from " << clientid << " and delete the fileId:" << fileid << ",segId:" << segid << " from database"); m_data_server->DeleteFromIndex(fileid,segid,clientid); break; case MSG_ADD_SEG: clientid = ptr[1]; fileid = ptr[2]; segid = ptr[3]; linkednum = ptr[4]; LOG_INFO("server receive MSG_ADD_SEG from " << clientid << " and add the fileId:" << fileid << ",segId:" << segid << " into database"); m_data_server->InsertIntoIndex(fileid,segid,clientid,linkednum); break; case MSG_CLIENT_DELAY: clientid = ptr[1]; ptr += 2; delay = *((double *)ptr); LOG_INFO("server receive MSG_CLIENT_DELAY from " << clientid << " delay time: " << delay); break; case MSG_SEG_ASK: clientid = ptr[1]; fileid = ptr[2]; segid = ptr[3]; ++m_total_request; m_data_server->IncreaseTotalRequest(); LOG_INFO("server receive MSG_SEG_ASK from " << clientid << " ask file: " << fileid << " seg: " << segid); if (m_p2p) { // P2P开启 best_clientid = m_data_server->SearchBestClient(fileid, segid); LOG_INFO("server find best client " << best_clientid); if(best_clientid != -1){ resptr[0] = MSG_REDIRECT; resptr[1] = 0; resptr[2] = best_clientid; resptr[3] = m_clientinfo[best_clientid].address.sin_addr.s_addr; resptr[4] = m_clientinfo[best_clientid].address.sin_port; m_buffer->DeleteVistors(fileid, clientid); length = send(connfd, response, MESSAGELEN, 0); assert(length == MESSAGELEN); LOG_INFO("server response MSG_REDIRECT to " << best_clientid); break; } } // 此时表示没有找到合适的P2P服务客户端,因此从服务器直接读取文件块 ++m_read_from_server; m_data_server->IncreaseReadFromServer(); m_buffer->AddVistors(fileid, clientid); m_data_server->GetFileInfo(fileid, &bitrate, &segnum); if(segid > segnum){ LOG_INFO("client " << clientid << " read segid " << segid << " while segnum is " << segnum); assert(0); } // 如果命中,则不需要读取磁盘 if (m_buffer->Read(fileid, segid)) { // 命中缓冲区 ++m_buffer_hit; m_data_server->IncreaseBufferHit(); } else { // 读取磁盘,增加相应磁盘访问计数,磁盘id从0开始计数 int diskId = m_data_server->GetDiskId(fileid, segid, m_place_strategy); m_data_server->IncreaseDiskAccessCount(diskId); LOG_INFO("server read fileid " << fileid << " segid " << segid << " for client " << clientid << " start"); LOG_INFO("server read diskid " << diskId << " start"); if(m_real_device) { // 读取真实磁盘 // 因为Readseg接口的文件id和段id是从0开始的 m_diskMgr->ReadSeg(fileid - 1, segid -1); }else{ // 模拟读取磁盘,需要提供磁盘id m_diskMgr->ReadSeg(fileid - 1, segid - 1, diskId); } LOG_INFO("server read diskid " << diskId << " end"); LOG_INFO("server read fileid " << fileid << " segid " << segid << " for client " << clientid << " end"); m_buffer->Write(fileid, segid, ofileid, osegid); ++m_buffer_miss; m_data_server->IncreaseBufferMiss(); LOG_INFO("server DELETE " << ofileid << "," << osegid << " and ADD " << fileid << "," << segid); } resptr[0] = MSG_SEG_ACK; resptr[1] = 0; resptr[2] = segnum; *((double *)(resptr + 3)) = bitrate; send(connfd, response, MESSAGELEN, 0); total_request = m_data_server->GetTotalRequest(); read_from_server = m_data_server->GetReadFromServer(); buffer_hit = m_data_server->GetBufferHit(); buffer_miss = m_data_server->GetBufferMiss(); LOG_INFO("server response MSG_SEG_ACK segnum: " << segnum << " total: " << m_total_request << " fromServer: " << m_read_from_server << " bufMiss: " << m_buffer_miss << " bufHit: " << m_buffer_hit); LOG_INFO("server response MSG_SEG_ACK segnum: " << segnum << " total: " << total_request << " fromServer: " << read_from_server << " bufMiss: " << buffer_miss << " bufHit: " << buffer_hit); LOG_WRITE(clientid << "\t" << fileid << "\t" << segid << "\t" << m_total_request << "\t" << m_read_from_server << "\t" << m_buffer_hit << "\t" << m_buffer_miss, m_buffer_ofs); LOG_WRITE(clientid << "\t" << fileid << "\t" << segid << "\t" << total_request << "\t" << read_from_server << "\t" << buffer_hit << "\t" << buffer_miss, m_buffer_ofs); break; case MSG_REQUEST_SEG: // config->isSpecial 为false时下面才运行 clientid = ptr[1]; fileid = ptr[2]; segid = ptr[3]; LOG_INFO("server receive MSG_REQUEST_SEG from " << clientid << " fileid: " << fileid << " segid: " << segid); // 向客户端发送传送完毕消息 resptr[0] = MSG_SEG_FIN; resptr[1] = 0; resptr[2] = fileid; resptr[3] = segid; length = send(m_clientinfo[clientid].recvFd, response, MESSAGELEN, 0); LOG_INFO("server send MSG_SEG_FIN to " << clientid << " fileid: " << fileid << " segid: " << segid); //LOG_INFO("server receive MSG_REQUEST_SEG from " << clientid << " fileid: " << fileid << " segid: " << segid); //m_data_server->IncreaseRealLoad(); //LOG_INFO("current_load: " << m_current_load << ", real_load: " << m_data_server->GetRealLoad()); //// 加锁 //Pthread_mutex_lock(&m_facktran_mutex); //// m_real_load++; //while(m_current_load >= m_server_band / m_client_band){ // // LOG_INFO("current_load: " << m_current_load << ", real_load: " << m_data_server->GetRealLoad()); // LOG_INFO("pthread_cond_wait start. current_load: " << m_current_load << ", real_load: " << m_data_server->GetRealLoad()); // pthread_cond_wait(&m_facktran_cond, &m_facktran_mutex); // LOG_INFO("pthread_cond_wait wake."); //} //LOG_INFO("server for " << clientid << " now."); //m_current_load++; //LOG_INFO("current_load: " << m_current_load << ", real_load: " << m_data_server->GetRealLoad()); //// 此处计算时间时,忽略服务器负载,只考虑客户端负载 //left_time = (long long)(m_block_size * 1.0 * 1024 * 1024 / 1000 / 1000 / (m_client_band * 1.0 / 8 ) * TIMER_SCALE);// 0.8s //// Pthread_mutex_init(&facktran_mutex_temp, NULL); //pthread_cond_init(&facktran_cond_temp, NULL); //gettimeofday(&begin_time, NULL); //tm.tv_nsec = (left_time % TIMER_SCALE + begin_time.tv_usec) * 1000; //tm.tv_sec = left_time / TIMER_SCALE + begin_time.tv_sec; //tm.tv_sec = tm.tv_nsec / 1000000000 + tm.tv_sec; //tm.tv_nsec = tm.tv_nsec % 1000000000; //ret = pthread_cond_timedwait(&facktran_cond_temp, &m_facktran_mutex, &tm); //if(ret == ETIMEDOUT){ // m_current_load--; // // m_real_load--; // pthread_cond_signal(&m_facktran_cond); // Pthread_mutex_unlock(&m_facktran_mutex); // m_data_server->DecreaseRealLoad(); // LOG_INFO("current_load: " << m_current_load << ", real_load: " << m_data_server->GetRealLoad()); // // 向客户端发送传送完毕消息 // resptr[0] = MSG_SEG_FIN; // resptr[1] = 0; // resptr[2] = fileid; // resptr[3] = segid; // length = send(m_clientinfo[clientid].recvFd, response, MESSAGELEN, 0); // LOG_INFO("server send MSG_SEG_FIN to " << clientid << " fileid: " << fileid << " segid: " << segid); // assert(length == MESSAGELEN); // break; //}else{ // // 即pthread_cond_timedwait返回时必定是超时返回,否则认为出错 // LOG_INFO("pthread_cond_timedwait error"); // cout << "pthread_cond_timedwait error" << endl; // assert(0); //} break; case MSG_SEG_FIN: clientid = ptr[1]; fileid = ptr[2]; segid = ptr[3]; LOG_INFO("server receive MSG_SEG_FIN from " << clientid << " fileid: " << fileid << " segid: " << segid); break; default: LOG_INFO("server receive unknow message"); //assert(0); } // switch } // while } void StripServer::ThreadEvent() { epoll_event events[MAX_LISTEN_NUM]; int nfds; int i; char buffer[MESSAGELEN]; int length; while(true) { nfds = epoll_wait(m_event_fd, events, MAX_LISTEN_NUM, -1); for(i = 0; i < nfds; ++i) { if (events[i].data.fd == m_buffer_reset_fd[0]) { length = recv(events[i].data.fd, buffer, MESSAGELEN, 0); assert(length == MESSAGELEN); BufferReset(); } else if(events[i].data.fd == m_facktran_fd[0]){ // 表示一个段传输完毕 // 1.更新负载(加锁) // 2.向客户端发送消息 // 加锁 // Pthread_mutex_lock(&m_facktran_mutex); // m_current_load--; // Pthread_mutex_unlock(&m_facktran_mutex); // // 释放锁 // Timer::GetTimer()->ModifyTimers(m_current_load); // length = recv(events[i].data.fd, buffer, MESSAGELEN, 0); // assert(length == MESSAGELEN); // int *ptr = (int *)buffer; // int clientid = ptr[0]; // int fileid = ptr[1]; // int sedid = ptr[2]; // ptr[0] = MSG_SEG_FIN; // ptr[1] = 0; // ptr[2] = fileid; // ptr[3] = sedid; // length = send(m_clientinfo[clientid].recvFd, buffer, MESSAGELEN, 0); // assert(length == MESSAGELEN); } else if(events[i].data.fd == m_take_sample_fd[0]){ length = recv(events[i].data.fd, buffer, MESSAGELEN, 0); assert(length == MESSAGELEN); TakeSample(); } else { assert(0); } } } } void StripServer::BufferReset() { LOG_INFO("Buffer reset"); TimerEvent event; event.sockfd = m_buffer_reset_fd[1]; event.left_time = m_period * TIMER_SCALE; Timer::GetTimer()->RegisterTimer(event); m_buffer->BlockReset(); } void StripServer::TakeSample() { //int real_load = m_data_server->GetRealLoad(); //LOG_INFO("Take Sample, current_load: " << m_current_load << ", real_load: " << real_load); //list<int> accessCountList; //double balance_degree_variance = m_data_server->GetAccessBalanceDegree(accessCountList); //double balance_degree_standard_deviation = sqrt(balance_degree_variance); //stringstream sstreambalance; //string balanceString; //sstreambalance.str(); //list<int>::iterator iter; //for(iter=accessCountList.begin(); iter!=accessCountList.end(); iter++){ // sstreambalance << *iter << "\t"; //} //sstreambalance << balance_degree_variance << "\t" << balance_degree_standard_deviation; //balanceString = sstreambalance.str(); //LOG_INFO("access balance degress: " << balanceString); //LOG_WRITE(balanceString, m_access_balance_degree_ofs); m_diskMgr->PrintDiskInfo(); TimerEvent event; event.sockfd = m_take_sample_fd[1]; event.left_time = m_take_sample_frequency * TIMER_SCALE; Timer::GetTimer()->RegisterTimer(event); }
35850cb030abd4fd39c355a5a9da6f66d783be35
c984856ca33bd52c5712407aba22dd7a098b02c6
/gazebo/rendering/OrthoViewController.cc
b3a255b09cdc5a75d624b86f4b4b01886a3e8331
[ "Apache-2.0" ]
permissive
siconos/gazebo-siconos
f7f97dd8d9ccbdf128e43373a77637970553b14e
612f6a78184cb95d5e7a6898c42003c4109ae3c6
refs/heads/master
2021-01-01T04:53:39.749180
2016-05-23T18:49:47
2016-05-23T19:11:56
97,266,911
5
0
null
null
null
null
UTF-8
C++
false
false
9,878
cc
OrthoViewController.cc
/* * Copyright (C) 2015-2016 Open Source Robotics Foundation * * 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. * */ #include "gazebo/rendering/ogre_gazebo.h" #include "gazebo/common/MouseEvent.hh" #include "gazebo/rendering/Conversions.hh" #include "gazebo/rendering/Scene.hh" #include "gazebo/rendering/Visual.hh" #include "gazebo/rendering/UserCamera.hh" #include "gazebo/rendering/OrbitViewController.hh" #include "gazebo/rendering/OrthoViewControllerPrivate.hh" #include "gazebo/rendering/OrthoViewController.hh" #define TYPE_STRING "ortho" using namespace gazebo; using namespace rendering; ////////////////////////////////////////////////// OrthoViewController::OrthoViewController(UserCameraPtr _camera) : OrbitViewController(_camera, "OrthoViewController"), dataPtr(new OrthoViewControllerPrivate) { this->typeString = TYPE_STRING; this->init = false; } ////////////////////////////////////////////////// OrthoViewController::~OrthoViewController() { delete this->dataPtr; this->dataPtr = NULL; this->refVisual.reset(); } ////////////////////////////////////////////////// void OrthoViewController::Init() { this->dataPtr->scale = 100; this->distance = 1000.0/this->dataPtr->scale; int width = this->camera->ViewportWidth(); int height = this->camera->ViewportHeight(); if (width > 0 && height > 0) { // set up the view projection this->Zoom(1.0); } OrbitViewController::Init(); } ////////////////////////////////////////////////// void OrthoViewController::Init(const math::Vector3 &_focalPoint, double _yaw, double _pitch) { this->dataPtr->scale = 100; int width = this->camera->ViewportWidth(); int height = this->camera->ViewportHeight(); if (width > 0 && height > 0) { // set up the view projection this->Zoom(1.0); } OrbitViewController::Init(_focalPoint, _yaw, _pitch); } ////////////////////////////////////////////////// std::string OrthoViewController::GetTypeString() { return TYPE_STRING; } ////////////////////////////////////////////////// void OrthoViewController::HandleMouseEvent(const common::MouseEvent &_event) { if (!this->enabled) return; math::Vector2i drag = _event.Pos() - _event.PrevPos(); math::Vector3 directionVec(0, 0, 0); int width = this->camera->ViewportWidth(); int height = this->camera->ViewportHeight(); double orthoWidth = width/this->dataPtr->scale; double orthoHeight = height/this->dataPtr->scale; // If the event is the initial press of a mouse button, then update // the focal point and distance. if (_event.PressPos() == _event.Pos()) { if (!this->camera->GetScene()->FirstContact( this->camera, _event.PressPos(), this->focalPoint)) { ignition::math::Vector3d origin, dir; this->camera->CameraToViewportRay( _event.PressPos().X(), _event.PressPos().Y(), origin, dir); this->focalPoint = origin + dir * 10.0; } // pseudo distance this->distance = 1000.0/this->dataPtr->scale; this->yaw = this->camera->WorldRotation().Euler().Z(); this->pitch = this->camera->WorldRotation().Euler().Y(); } // Turn on the reference visual. this->refVisual->SetVisible(true); // Middle mouse button or Shift + Left button is used to Orbit. if (_event.Dragging() && (_event.Buttons() & common::MouseEvent::MIDDLE || (_event.Buttons() & common::MouseEvent::LEFT && _event.Shift()))) { // Compute the delta yaw and pitch. double dy = this->NormalizeYaw(drag.x * _event.MoveScale() * -0.4); double dp = this->NormalizePitch(drag.y * _event.MoveScale() * 0.4); // Limit rotation to pitch only if the "y" key is pressed. if (!this->key.empty() && this->key == "y") dy = 0.0; // Limit rotation to yaw if the "z" key is pressed. else if (!this->key.empty() && this->key == "z") dp = 0.0; this->Orbit(dy, dp); } // The left mouse button is used to translate the camera. else if ((_event.Buttons() & common::MouseEvent::LEFT) && _event.Dragging()) { math::Vector3 translation; double factor = 1.0; // The control key increases zoom speed by a factor of two. if (_event.Control()) factor *= 2.0; // If the "x", "y", or "z" key is pressed, then lock translation to the // indicated axis. if (!this->key.empty()) { if (this->key == "x") translation.Set((drag.y / static_cast<float>(height)) * orthoHeight * factor, 0.0, 0.0); else if (this->key == "y") translation.Set(0.0, (drag.x / static_cast<float>(width)) * orthoWidth * factor, 0.0); else if (this->key == "z") translation.Set(0.0, 0.0, (drag.y / static_cast<float>(height)) * orthoHeight * factor); else gzerr << "Unable to handle key [" << this->key << "] in orbit view " << "controller.\n"; // Translate in the global coordinate frame this->TranslateGlobal(translation); } else { // Translate in the "y" "z" plane. translation.Set(0.0, (drag.x / static_cast<float>(width)) * orthoWidth * factor, (drag.y / static_cast<float>(height)) * orthoHeight * factor); // Translate in the local coordinate frame this->TranslateLocal(translation); } } // The right mouse button is used to zoom the camera. else if ((_event.Buttons() & common::MouseEvent::RIGHT) && _event.Dragging()) { double amount = 1.0 + (drag.y / static_cast<float>(height)); this->Zoom(amount, _event.PressPos()); } // The scroll wheel controls zoom. else if (_event.Type() == common::MouseEvent::SCROLL) { if (!this->camera->GetScene()->FirstContact( this->camera, _event.Pos(), this->focalPoint)) { ignition::math::Vector3d origin, dir; this->camera->CameraToViewportRay( _event.Pos().X(), _event.Pos().Y(), origin, dir); this->focalPoint = origin + dir * 10.0; } // pseudo distance this->distance = 1000.0/this->dataPtr->scale; double factor = 1.0; // The control key increases zoom speed by a factor of two. if (_event.Control()) factor *= 2; // This assumes that _event.scroll.y is -1 or +1 double zoomFactor = 10; double amount = 1.0 + _event.Scroll().Y() * factor * _event.MoveScale() * zoomFactor; this->Zoom(amount, _event.Pos()); } else this->refVisual->SetVisible(false); } ////////////////////////////////////////////////// void OrthoViewController::Zoom(const float _amount, const math::Vector2i &_screenPos) { // Zoom to mouse cursor position // Three step process: // Translate mouse point to center of screen // Zoom by changing the orthographic window size // Translate back to mouse cursor position math::Vector3 translation; int width = this->camera->ViewportWidth(); int height = this->camera->ViewportHeight(); double orthoWidth = width / this->dataPtr->scale; double orthoHeight = height / this->dataPtr->scale; translation.Set(0.0, ((width/2.0 - _screenPos.x) / static_cast<float>(width)) * orthoWidth, ((height/2.0 - _screenPos.y) / static_cast<float>(height)) * orthoHeight); this->TranslateLocal(translation); this->dataPtr->scale /= _amount; // build custom projection matrix from custom near and far clipping planes, // had to set a negative near clippping plane to workaround a camera // culling issue in orthographic view. Ogre::Matrix4 proj; proj = this->BuildScaledOrthoMatrix( -width / this->dataPtr->scale / 2.0, width / this->dataPtr->scale / 2.0, -height / this->dataPtr->scale / 2.0, height / this->dataPtr->scale / 2.0, -500, 500); this->camera->OgreCamera()->setCustomProjectionMatrix(true, proj); double newOrthoWidth = width / this->dataPtr->scale; double newOrthoHeight = height / this->dataPtr->scale; translation.Set(0.0, ((_screenPos.x - width/2.0) / static_cast<float>(width)) * newOrthoWidth, ((_screenPos.y - height/2.0) / static_cast<float>(height)) * newOrthoHeight); this->TranslateLocal(translation); this->UpdateRefVisual(); } ////////////////////////////////////////////////// void OrthoViewController::Resize( const unsigned int _width, const unsigned int _height) { Ogre::Matrix4 proj = this->BuildScaledOrthoMatrix( _width / this->dataPtr->scale / -2.0, _width / this->dataPtr->scale / 2.0, _height / this->dataPtr->scale / -2.0, _height / this->dataPtr->scale / 2.0, -500, 500); this->camera->OgreCamera()->setCustomProjectionMatrix(true, proj); } ////////////////////////////////////////////////// Ogre::Matrix4 OrthoViewController::BuildScaledOrthoMatrix( const float _left, const float _right, const float _bottom, const float _top, const float _near, const float _far) const { float invw = 1.0f / (_right - _left); float invh = 1.0f / (_top - _bottom); float invd = 1.0f / (_far - _near); Ogre::Matrix4 proj = Ogre::Matrix4::ZERO; proj[0][0] = 2.0f * invw; proj[0][3] = -(_right + _left) * invw; proj[1][1] = 2.0f * invh; proj[1][3] = -(_top + _bottom) * invh; proj[2][2] = -2.0f * invd; proj[2][3] = -(_far + _near) * invd; proj[3][3] = 1.0f; return proj; }
22664f8a85c76da05a517b6abb2c2f7580199a09
77ccc95277a71d682c0575553806f13de87d5a0d
/providers - zen-fire/libzenfire-1.0.14/include/zenfire/debug.hpp
cb8eb895b10b0c594b762171fa3135a525e5947a
[]
no_license
gaoxiaojun/tx.link.incoming
93912bfc0dba821a87a8ba418a6e5edffb5cdba9
3804e94207f8d29c2b0c1c69e1bb4a0bed6372e7
refs/heads/master
2021-01-22T17:17:47.919031
2011-09-20T19:18:13
2011-09-20T19:18:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,583
hpp
debug.hpp
/****************************************************************************** ******************************************************************************/ /** \file debug.hpp * \brief helper debug functions for printing objects * * $Id: debug.hpp 2804 2010-04-30 03:36:35Z grizz $ */ #ifndef ZENFIRE_DEBUG_HPP__ #define ZENFIRE_DEBUG_HPP__ //############################################################################// // L I C E N S E #############################################################// //############################################################################// /* * (C) 2008 BigWells Technology (Zen-Fire). All rights reserved. * Confidential and proprietary information of BigWells Technology. */ //############################################################################// // I N C L U D E S ###########################################################// //############################################################################// #include <zenfire/zenfire.hpp> #include <iostream> #include <sstream> #include <ctime> //############################################################################// #if defined(_MSC_VER) # define LOCALTIME_R(tp, tm) localtime_s((tm), (tp)) #else # define LOCALTIME_R(tp, tm) localtime_r((tp), (tm)) #endif namespace zenfire { namespace debug { //############################################################################// //! dump tick to stream template <typename T> T& dump(T& s, const tick_t& m) { s << *m.product << " " << m.ts << "." << m.usec / 1000 << " " << m.size << " @ " << m.price << " (" << m.type() << ")"; return(s); } template <typename T> T& operator<<(T& s, const tick_t& m) { return(dump(s, m)); } //############################################################################// //! dump tick type to stream inline std::string tick_type_to_string(const tick::type_t& t) { switch(t) { case tick::ASK: return("ASK"); case tick::BEST_ASK: return("BEST_ASK"); case tick::BID: return("BID"); case tick::BEST_BID: return("BEST_BID"); case tick::TRADE: return("TRADE"); case tick::LOW: return("LOW"); case tick::HIGH: return("HIGH"); case tick::OPEN: return("OPEN"); case tick::CLOSE: return("CLOSE"); case tick::VOLUME: return("VOLUME"); case tick::MODE: return("mode"); default: return(""); } } template <typename T> T& operator<<(T& s, const tick::type_t& m) { s << tick_type_to_string(m); return(s); } //############################################################################// //! order status template <typename T> T& operator<< (T& s, const zenfire::order::status_t& status) { switch(status) { case PREPARED: s << "prepared"; break; case SENT: s << "sent"; break; case PENDING: s << "pending"; break; case OPEN: s << "open"; break; case UPDATING: s << "updating"; break; case COMPLETE: s << "complete"; break; case NO_STATUS: s << "none"; break; } return(s); } //############################################################################// //! order completion reason template <typename T> T& operator<< (T& s, const zenfire::order::reason_t& reason) { switch(reason) { case FILLED: s << "filled"; break; case PARTIAL: s << "partial"; break; case CANCELED: s << "canceled"; break; case FAILED: s << "failed"; break; case REJECTED: s << "rejected"; break; case BUSTED: s << "busted"; break; case NO_REASON: s << "none"; break; } return(s); } //############################################################################// //! order type template <typename T> T& operator<< (T& s, const zenfire::order::type_t& typ) { switch(typ) { case MARKET: s << "market"; break; case LIMIT: s << "limit"; break; case STOP_MARKET: s << "stop market"; break; case STOP_LIMIT: s << "stop limit"; break; case NO_TYPE: s << "none"; break; } return(s); } //############################################################################// //! order action template <typename T> T& operator<< (T& s, const zenfire::order::action_t& action) { switch(action) { case BUY: s << "buy"; break; case SELL: s << "sell"; break; case NO_ACTION: s << "unknown"; break; } return(s); } //############################################################################// //! order duration template <typename T> T& operator<< (T& s, const zenfire::order::duration_t& duration) { switch(duration) { case DAY: s << "day"; break; case FOK: s << "fok"; break; case GTC: s << "gtc"; break; case NO_DURATION: s << "unknown"; break; } return(s); } //############################################################################// //! inline std::string mode_to_string(const zenfire::mode::mode_t typ) { std::string rv; switch(typ) { case mode::OPEN: return("open"); case mode::CLOSED: return("closed"); case mode::PRE_OPEN: return("closed:pre-open"); case mode::HALTED: return("closed:halted"); } return(rv); } //############################################################################// //! dump order //T& operator<< (T& s, const zenfire::order_t& o) template <typename T> T& operator<< (T& s, zenfire::order_t& o) { std::stringstream str; switch(o.type()) { case order::LIMIT: str << "@ " << o.price() << " "; break; case order::STOP_LIMIT: str << "@ " << o.price() << " (trigger @ " << o.trigger() << ") " ; break; case order::STOP_MARKET: str << "(trigger @ " << o.trigger() << ") " ; break; default: break; } if(o.qty_filled()) str << "(filled @ " << o.fill_price() << ") "; s << o.type() << " order " << o.number() << " " << o.product() << " " << o.action() << " " << o.qty() << " (" << o.qty_open() << " / " << o.qty_filled() << " / " << o.qty_canceled() << ") " << str.str() << o.duration() << " " << o.status() << ":" << o.reason() << " " << o.message(); //<< "trig" << o.trigger(); return(s); } //############################################################################// //! order report type template <typename T> T& operator<< (T& s, const zenfire::report::type_t& typ) { switch(typ) { case report::BUST: s << "BUST"; break; case report::CANCEL: s << "CANCEL"; break; case report::FAIL: s << "FAIL"; break; case report::FILL: s << "FILL"; break; case report::MODIFY: s << "MODIFY"; break; case report::CANCEL_FAIL: s << "CANCEL_FAIL"; break; case report::UPDATE_FAIL: s << "UPDATE_FAIL"; break; case report::OPEN: s << "OPEN"; break; case report::REJECT: s << "REJECT"; break; case report::TRIGGER: s << "TRIGGER"; break; case report::REPLAY: s << "REPLAY"; break; case report::END_OF_REPLAY: s << "END_OF_REPLAY"; break; case report::UNKNOWN: s << "UNKNOWN"; break; } return(s); } //############################################################################// //! dump product position to stream template <typename T> T& operator<< (T& s, const zenfire::position_t& m) { s << "[" << m.acctno << "] " << m.product << ": " << m.size << " " << ": open P&L $" << m.open_pl << " | closed P&L $" << m.closed_pl << " fill at " << m.avg_fill_price(); return(s); } //############################################################################// //! dump account level profit/loss to stream template <typename T> T& operator<< (T& s, const zenfire::profitloss_t& m) { s << "[" << m.acctno << "] " << "open P&L $" << m.open << " | closed P&L $" << m.closed << " | balance $" << m.balance << " | margin $" << m.margin; return(s); } //############################################################################// //! dump product to stream template <typename T> T& operator<< (T& s, const zenfire::product_t& m) { s << m.symbol << "." << exchange::to_string(m.exchange); return(s); } }} // namespace zenfire::debug //############################################################################// #endif // end ZENFIRE_DEBUG_HPP__ /****************************************************************************** ******************************************************************************/
b41341df5e6af9db0469c3284feaa475589313ea
6cc2994eb6ed4e4c0d967856c6083f45b5baf056
/source/Server.cpp
3f1d0656fbc6b91aeac98bd76440cbe149df4994
[]
no_license
lisa-bella97/HighLoadWebServer
63d99b7f0175d9557cb3c4ae6ab33ea906dd25de
ae5e9f24efc2cdb1dca313f99ec79cd019277eea
refs/heads/master
2021-02-10T19:28:42.853215
2020-03-24T18:09:52
2020-03-24T18:09:52
244,412,940
0
0
null
null
null
null
UTF-8
C++
false
false
2,987
cpp
Server.cpp
#include "Server.h" #include "boost/bind.hpp" #include <iostream> #include <wait.h> Server::Server(ServerConfig *config) : acceptor_( io_service_, boost::asio::ip::tcp::endpoint( boost::asio::ip::tcp::v4(), config->getPort() )), signal_(io_service_, SIGCHLD), connection_(), document_root_(config->getDocumentRoot()) { startSignalWait(); startAccept(); } Server::~Server() { acceptor_.close(); } void Server::run() { io_service_.run(); } void Server::startSignalWait() { signal_.async_wait(boost::bind(&Server::handleSignalWait, this)); } void Server::handleSignalWait() { // Only the parent process should check for this signal. We can determine // whether we are in the parent by checking if the acceptor is still open. if (acceptor_.is_open()) { // Reap completed child processes so that we don't end up with zombies. int status = 0; while (waitpid(-1, &status, WNOHANG) > 0) {} startSignalWait(); } } void Server::startAccept() { connection_.reset(new ServerConnection(io_service_, document_root_)); acceptor_.async_accept( connection_->getSocket(), boost::bind(&Server::handleAccept, this, _1) ); } void Server::handleAccept(const boost::system::error_code &ec) { if (!ec) { // Inform the io_service that we are about to fork. The io_service cleans // up any internal resources, such as threads, that may interfere with // forking. io_service_.notify_fork(boost::asio::io_service::fork_prepare); if (fork() == 0) { // Inform the io_service that the fork is finished and that this is the // child process. The io_service uses this opportunity to create any // internal file descriptors that must be private to the new process. io_service_.notify_fork(boost::asio::io_service::fork_child); // The child won't be accepting new connections, so we can close the // acceptor. It remains open in the parent. //acceptor_.cancel(); acceptor_.close(); // The child process is not interested in processing the SIGCHLD signal. signal_.cancel(); connection_->startRead(); } else { // Inform the io_service that the fork is finished (or failed) and that // this is the parent process. The io_service uses this opportunity to // recreate any internal resources that were cleaned up during // preparation for the fork. io_service_.notify_fork(boost::asio::io_service::fork_parent); //socket_.cancel(); connection_->getSocket().close(); startAccept(); } } else { std::cerr << "Accept error: " << ec.message() << std::endl; startAccept(); } }
b5d2a303f43b52bd456bd98409f30ff65632e064
a3f72034cf1a0b06dabec808b1e0044997f65fa1
/include/core/Stopwatch.hpp
f763e553302475f0cde58d70d56e8537c3998017
[ "Zlib" ]
permissive
choiip/fui
560fe641d4a616ec53e2a6084fd8427ba220af24
dc54b2d29c423a5b257dd7d812e5d5f52a10ba8a
refs/heads/master
2022-06-30T17:37:46.919078
2020-01-14T06:37:30
2020-01-14T06:37:30
263,242,191
0
0
null
null
null
null
UTF-8
C++
false
false
2,302
hpp
Stopwatch.hpp
// CC0 Public Domain: https://codereview.stackexchange.com/questions/114532/simple-stopwatch-class #pragma once #include <chrono> #include <utility> namespace fui { template <typename TimeUnit = std::chrono::milliseconds, typename Clock = std::chrono::high_resolution_clock> class Stopwatch { public: explicit Stopwatch(bool startStopwatch = false) noexcept; void start() noexcept; void stop() noexcept; TimeUnit elapsed() noexcept; void reset() noexcept; template <typename F, typename... FArgs> inline static TimeUnit measure(F&&, FArgs&&...); private: bool stopped_; std::chrono::time_point<Clock> stop_; bool started_; std::chrono::time_point<Clock> start_; }; template <typename TimeUnit, typename Clock> inline Stopwatch<TimeUnit, Clock>::Stopwatch(bool startStopwatch) noexcept : stopped_{false} , stop_{TimeUnit{0}} , started_{startStopwatch} , start_{startStopwatch ? Clock::now() : stop_} {} template <typename TimeUnit, typename Clock> inline void Stopwatch<TimeUnit, Clock>::start() noexcept { if (started_) { return; // throw std::logic_error( "stopwatch: already called start()" ); } start_ = Clock::now(); started_ = true; } template <typename TimeUnit, typename Clock> inline void Stopwatch<TimeUnit, Clock>::stop() noexcept { if (!started_) { return; // throw std::logic_error( "stopwatch: called stop() before start()" ); } stop_ = Clock::now(); stopped_ = true; } template <typename TimeUnit, typename Clock> inline TimeUnit Stopwatch<TimeUnit, Clock>::elapsed() noexcept { if (!started_) { return TimeUnit{0}; } if (stopped_) { return std::chrono::duration_cast<TimeUnit>(stop_ - start_); } return std::chrono::duration_cast<TimeUnit>(Clock::now() - start_); } template <typename TimeUnit, typename Clock> inline void Stopwatch<TimeUnit, Clock>::reset() noexcept { started_ = false; stop_ = start_; stopped_ = false; } template <typename TimeUnit, typename Clock> template <typename F, typename... FArgs> inline TimeUnit Stopwatch<TimeUnit, Clock>::measure(F&& f, FArgs&&... f_args) { auto start_time = Clock::now(); std::forward<F>(f)(std::forward<FArgs>(f_args)...); auto stop_time = Clock::now(); return std::chrono::duration_cast<TimeUnit>(stop_time - start_time); } } // namespace fui