blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
a6e65ffc225fb692d69df3f809b46a926b0634b3
C++
JJEllacopulos/pru
/main.cpp
ISO-8859-3
3,374
2.703125
3
[]
no_license
/*Comentarios: */ #include<iostream> #include<cstdlib> #include<string.h> #include <cstdio> #include <cstring> #include<clocale> using namespace std; struct caracteristicas{ char nombre[30]; char descripcion[90]; char genero[20]; int edad; char titulo[20]; }; struct principales{ int recistencia; int fuerza; int destreza; int persepcion; int calculo; int abstraccion; int carisma; int templanza; int sigilo; int suerte; }; struct secundarias{ int vitalidad; int estamina; ///Aptitudes fisicas: int correr; int esquivar; int parkour; ///Aptitudes: int medicina; int ingenieria; int cerrajeria; int informatica; int quimica; int historia; int cocina; int cultura; ///Combate: int cuerpo_a_cuerpo; int arma_blanca; int armas_contundentes; int armas_de_precicion; int arrojables; ///Tolerancias: int veneno; int enfermedad; int hipotermia; int quemaduras; int alcohol; ///Subterfugio: int robar; int discrecion; int elocuencia; ///Psicologia: int cordura; int autocontrol; }; #include "rlutil.h" ///#include "administrador.h" #include "menus.h" int main (){ struct caracteristicas pj_car; struct principales pj_pri; struct secundarias pj_sec; bool key = true; bool flag = true; char opcion; cout<< "Bienvenido la editor de fichas de rol."<< endl<< "Espero que los disfruten."<< endl; system("pause"); system("cls"); while(key){ pj_car = Ingresar_caracteristicas(); pj_pri = Menu_admi_principales(); pj_sec = administrar_secundarias(pj_pri); Menu_elegir_titulo(pj_car, pj_pri, pj_sec); cout<< "Tu ficha se esta armando..."<< endl; system("pause"); system("cls"); cout<< "0%"<< endl; system("pause"); system("cls"); cout<< "25%"<< endl; system("pause"); system("cls"); cout<< "50%"<< endl; system("pause"); system("cls"); cout<< "75%"<< endl; system("pause"); system("cls"); cout<< "100%"<< endl; system("pause"); system("cls"); cout<< "Listo!!!"<< endl; system("pause"); system("cls"); Mostrar_ficha_completa(pj_car, pj_pri, pj_sec); system("pause"); system("cls"); while(flag){ cout<< "Estas satisfecho con tus deciciones? (S/N)"<< endl; cin>> opcion; switch(opcion){ case 'S': key = false; flag = false; break; case 'N': flag = false; break; default: cout<< "Opcion invalida."<< endl; system("pause"); system("cls"); break; } } flag = true; } cout<< "Gracias por su tiempo."<< endl; cout<< "Si encuentra algun problema comuniqueselo al Jonathan mas cercano."<< endl; system("pause"); system("cls"); return 0; }
true
92b6e3a1feb0719edfe901cf5c59e6c3c0efdfe8
C++
PanchenkoYehor/NumericalMethods
/laba5.cpp
UTF-8
4,223
3.015625
3
[]
no_license
#include <vector> #include <math.h> #include <cstdio> #include <assert.h> using namespace std; namespace Laba5 { double f(double x) { return (x + 8.0 / (1 + exp(x / 4))); } } double gnLangrange(double x, vector < double > points) { double res = 0; for (int i = 0; i < points.size(); i++) { double mlt = 1; for (int j = 0; j < points.size(); j++) { if (i == j) { continue; } mlt *= (x - points[j]) / (points[i] - points[j]); } res += Laba5::f(points[i]) * mlt; } return res; } void PolLangrange() { printf("Interval is [-10, 10]\n"); printf("Langrange\n"); vector < double > points = {-4, -2, 0, 2, 4}; vector < double > another_points = {-10, -5, -3, -1, 1, 3, 5, 10}; printf("Values in points: f g\n"); for (auto i : points) { printf("\t%10.5lf %10.5lf %10.5lf\n", i, Laba5::f(i), gnLangrange(i, points)); } printf("Values in another_points: f g\n"); for (auto i : another_points) { printf("\t%10.5lf %10.5lf %10.5lf\n", i, Laba5::f(i), gnLangrange(i, points)); } } double diff(vector < double > x) { double res = 0; for (int j = 0; j < x.size(); j++) { double dn = 1; for (int i = 0; i < x.size(); i++) { if (i == j) { continue; } dn *= x[j] - x[i]; } res += Laba5::f(x[j]) / dn; } return res; } double delta_y(double i, double k, vector < double > &points) { if (k == 0 /*&& i >= 0 && i < points.size()*/) { return Laba5::f(points[i]); } /*if (i < 0 || i >= points.size()) { return 0; }*/ return (delta_y(i + 1, k - 1, points) - delta_y(i, k - 1, points)); } double gnNewtonLection(double x, vector < double > points) { /*for (int i = 0; i <= 5; i++) { printf("%lf\n", delta_y(0, i, points)); }*/ double res = 0; double mlt = 1; for (int i = 0; i < points.size(); i++) { res += mlt * delta_y(0, i, points); if (i + 1 == points.size()) { break; } mlt *= x - points[i]; mlt /= i + 1; mlt /= 2; } return res; } double gnNewtonLectionSecond(double x, vector < double > points) { /*for (int i = 0; i <= 5; i++) { printf("%lf\n", delta_y(0, i, points)); }*/ double res = 0; double mlt = 1; for (int i = 0; i < points.size(); i++) { res += mlt * delta_y(points.size() - 1 - i, i, points); if (i + 1 == points.size()) { break; } mlt *= x - points[points.size() - 1 - i]; mlt /= i + 1; mlt /= 2; } return res; } double gnNewton(double x, vector < double > points) { double res = 0; vector < double > curr; double mlt = 1; for (int i = 0; i < points.size(); i++) { curr.push_back(points[i]); res += diff(curr) * mlt; if (i == points.size()) { break; } mlt *= x - points[i]; } return res; } void PolNewtonFirst() { printf("Interval is [-10, 10]\n"); printf("Newton\n"); vector < double > points = {-4, -2, 0, 2, 4}; vector < double > another_points = {-10, -5, -3, -1, 1, 3, 5, 10}; printf("Values in points: f g\n"); for (auto i : points) { printf("\t%10.5lf %10.5lf %10.5lf\n", i, Laba5::f(i), gnNewtonLection(i, points)); } printf("Values in another_points: f g\n"); for (auto i : another_points) { printf("\t%10.5lf %10.5lf %10.5lf\n", i, Laba5::f(i), gnNewtonLection(i, points)); } } void PolNewtonSecond() { printf("Interval is [-10, 10]\n"); printf("Newton\n"); vector < double > points = {-4, -2, 0, 2, 4}; vector < double > another_points = {-10, -5, -3, -1, 1, 3, 5, 10}; printf("Values in points: f g\n"); for (auto i : points) { printf("\t%10.5lf %10.5lf %10.5lf\n", i, Laba5::f(i), gnNewtonLectionSecond(i, points)); } printf("Values in another_points: f g\n"); for (auto i : another_points) { printf("\t%10.5lf %10.5lf %10.5lf\n", i, Laba5::f(i), gnNewtonLectionSecond(i, points)); } }
true
6cafbfca427c505d29aaa29c7a2fe55534613266
C++
cseri/elte-cpp-lesson-binsearchtree
/BinarySearchTree/main.cpp
UTF-8
1,334
3.546875
4
[ "MIT" ]
permissive
#include <cstdlib> #include <iostream> #include "binsearchtree.h" void print(int value) { std::cout << value << ", "; } class printer { std::ostream& o; public: printer(std::ostream& o) : o(o) {} template <typename T> void operator()(const T& value) { o << value << ", "; } }; int main() { const int demoitems[] = { 5, 3, 9, 4, 11, 4, 1 }; // Test insert and do_for_each. binsearchtree<int> t; for (int i = 0; i < sizeof(demoitems) / sizeof(demoitems[0]); ++i) { t.insert(demoitems[i]); // It should be sorted after each insert. t.do_for_each(print); std::cout << std::endl; } // Also works with function object (aka. functor). t.do_for_each(printer(std::cout)); std::cout << std::endl; // Test copy constructor. printer p(std::cout); binsearchtree<int> s(t); t.insert(2); t.do_for_each(p); std::cout << std::endl; s.do_for_each(p); std::cout << std::endl; // Test operator=. s = t; s.do_for_each(p); std::cout << std::endl; // Test clear. t.clear(); t.do_for_each(p); std::cout << std::endl; s.do_for_each(p); std::cout << std::endl; // TODO Test iterator. /*for (binsearchtree<int>::iterator it = s.begin(); it != s.end(); ++it) { p(*it); }*/ return 0; }
true
b7ba2d3c8133b32f75c05f09024ef8a363d1e3e2
C++
techtronics/treacherous-terrain
/src/client/Client.cc
UTF-8
22,705
2.5625
3
[]
no_license
#include <algorithm> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include <math.h> #include "Client.h" #include "Types.h" #include "GameParams.h" using namespace std; Client::Client(const string & exe_path) { m_client_has_focus = true; m_exe_path = exe_path; m_server_pid = 0; } Client::~Client() { } void Client::connect(int port, const char *host) { sf::Packet connect_packet; sf::Uint16 players_port; sf::Uint8 packet_type; m_net_client = new Network(); m_net_client->Create(port, host); m_players.clear(); m_current_player = 0; m_left_button_pressed = false; m_drawing_shot = false; m_shot_fired = false; m_map = Map(); // Send the player connect message to the server players_port = m_net_client->getLocalPort(); packet_type = PLAYER_CONNECT; connect_packet.clear(); connect_packet << packet_type; connect_packet << m_current_player; connect_packet << m_current_player_name; // Send the players port. This will serve as a unique // identifier and prevent users with the same name from controlling // each other. connect_packet << players_port; m_net_client->sendData(connect_packet, true); } void Client::disconnect() { // Send disconnect message bool connection_closed = false; sf::Packet client_packet; sf::Uint8 packet_type = PLAYER_DISCONNECT; sf::Clock timeout_clock; client_packet.clear(); client_packet << packet_type; client_packet << m_current_player; m_net_client->sendData(client_packet, true); // No time out needed here, since the // message will timeout after a couple of attempts // then exit anyway. while(!connection_closed) { m_net_client->Receive(); while(m_net_client->getData(client_packet)) { sf::Uint8 packet_type; client_packet >> packet_type; switch(packet_type) { case PLAYER_DISCONNECT: { sf::Uint8 player_index; // This completely removes the player from the game // Deletes member from the player list client_packet >> player_index; if(player_index == m_current_player) { connection_closed = true; } break; } } } m_net_client->Transmit(); // temporary for now. otherwise this thread consumed way too processing sf::sleep(sf::seconds(0.005)); // 5 milli-seconds // If the server does not respond within one second just close // and the server can deal with the problems. if(timeout_clock.getElapsedTime().asSeconds() > 1.0) { connection_closed = true; } } m_net_client->Destroy(); m_net_client = NULL; } void Client::run(bool fullscreen, int width, int height, std::string pname) { m_current_player_name = pname; if (!create_window(fullscreen, width, height)) return; m_clock.restart(); recenter_cursor(); bool in_game = true; while (in_game) { run_main_menu(); switch (m_menu_action) { case MAIN_MENU_SINGLE: start_server(); connect(DEFAULT_PORT, "127.0.0.1"); run_client(); stop_server(); disconnect(); break; case MAIN_MENU_HOST: run_host_menu(); break; case MAIN_MENU_JOIN: run_join_menu(); switch (m_menu_action) { case JOIN_MENU_JOIN: connect(DEFAULT_PORT, m_server_hostname.c_str()); run_client(); disconnect(); break; } break; case MAIN_MENU_EXIT: in_game = false; break; } } } void Client::play_single_player_game_button_clicked() { m_menu_action = MAIN_MENU_SINGLE; } void Client::exit_button_clicked() { m_menu_action = MAIN_MENU_EXIT; } void Client::join_game_button_clicked() { m_menu_action = MAIN_MENU_JOIN; } void Client::run_main_menu() { m_window->setMouseCursorVisible(true); m_window->resetGLStates(); m_menu_action = MAIN_MENU_NONE; sfg::Box::Ptr box = sfg::Box::Create(sfg::Box::VERTICAL, 10.0f); sfg::Button::Ptr btn_singleplayer = sfg::Button::Create("Play Single Player Game"); btn_singleplayer->GetSignal(sfg::Widget::OnLeftClick).Connect( &Client::play_single_player_game_button_clicked, this); sfg::Button::Ptr btn_hostgame = sfg::Button::Create("Host a Network Game"); sfg::Button::Ptr btn_joingame = sfg::Button::Create("Join a Network Game"); btn_joingame->GetSignal(sfg::Widget::OnLeftClick).Connect( &Client::join_game_button_clicked, this); sfg::Button::Ptr btn_exit = sfg::Button::Create("Exit"); btn_exit->GetSignal(sfg::Widget::OnLeftClick).Connect( &Client::exit_button_clicked, this); box->Pack(btn_singleplayer); box->Pack(btn_hostgame); box->Pack(btn_joingame); box->Pack(btn_exit); sfg::Window::Ptr gui_window(sfg::Window::Create(sfg::Window::TITLEBAR | sfg::Window::BACKGROUND)); gui_window->SetTitle("Treacherous Terrain"); gui_window->Add(box); gui_window->SetPosition(sf::Vector2f( m_width / 2 - gui_window->GetAllocation().width / 2, m_height / 2 - gui_window->GetAllocation().height / 2)); sfg::Desktop desktop; desktop.Add(gui_window); sf::Event event; bool in_menu = true; while (in_menu && m_window->isOpen()) { while (m_window->pollEvent(event)) { desktop.HandleEvent(event); switch (event.type) { case sf::Event::Closed: m_window->close(); in_menu = false; break; case sf::Event::KeyPressed: switch (event.key.code) { case sf::Keyboard::Escape: m_menu_action = MAIN_MENU_EXIT; break; default: break; } break; case sf::Event::Resized: m_width = event.size.width; m_height = event.size.height; gui_window->SetPosition(sf::Vector2f( m_width / 2 - gui_window->GetAllocation().width / 2, m_height / 2 - gui_window->GetAllocation().height / 2)); break; default: break; } } desktop.Update(m_clock.restart().asSeconds()); m_window->clear(); m_sfgui.Display(*m_window); m_window->display(); if (m_menu_action != MAIN_MENU_NONE) break; } } void Client::run_host_menu() { /* TODO */ } void Client::join_button_clicked() { m_menu_action = JOIN_MENU_JOIN; m_server_hostname = m_entry_hostname->GetText(); } void Client::join_menu_cancel_button_clicked() { m_menu_action = JOIN_MENU_CANCEL; } void Client::run_join_menu() { m_window->setMouseCursorVisible(true); m_window->resetGLStates(); m_menu_action = JOIN_MENU_NONE; sfg::Box::Ptr box = sfg::Box::Create(sfg::Box::VERTICAL, 10.0f); sfg::Button::Ptr btn_join = sfg::Button::Create("Join"); btn_join->GetSignal(sfg::Widget::OnLeftClick).Connect( &Client::join_button_clicked, this); sfg::Button::Ptr btn_cancel = sfg::Button::Create("Cancel"); btn_cancel->GetSignal(sfg::Widget::OnLeftClick).Connect( &Client::join_menu_cancel_button_clicked, this); sfg::Box::Ptr addr_box = sfg::Box::Create(sfg::Box::HORIZONTAL, 10.0f); addr_box->Pack(sfg::Label::Create("Host:")); m_entry_hostname = sfg::Entry::Create("localhost"); m_entry_hostname->SetRequisition(sf::Vector2f(200, 0)); addr_box->Pack(m_entry_hostname); box->Pack(addr_box); sfg::Box::Ptr btn_box = sfg::Box::Create(sfg::Box::HORIZONTAL, 10.0f); btn_box->Pack(btn_cancel); btn_box->Pack(btn_join); box->Pack(btn_box); sfg::Window::Ptr gui_window(sfg::Window::Create(sfg::Window::TITLEBAR | sfg::Window::BACKGROUND)); gui_window->SetTitle("Treacherous Terrain - Join Game"); gui_window->Add(box); gui_window->SetPosition(sf::Vector2f( m_width / 2 - gui_window->GetAllocation().width / 2, m_height / 2 - gui_window->GetAllocation().height / 2)); sfg::Desktop desktop; desktop.Add(gui_window); sf::Event event; bool in_menu = true; while (in_menu && m_window->isOpen()) { while (m_window->pollEvent(event)) { desktop.HandleEvent(event); switch (event.type) { case sf::Event::Closed: m_window->close(); in_menu = false; break; case sf::Event::KeyPressed: switch (event.key.code) { case sf::Keyboard::Escape: m_menu_action = JOIN_MENU_CANCEL; break; default: break; } break; case sf::Event::Resized: m_width = event.size.width; m_height = event.size.height; gui_window->SetPosition(sf::Vector2f( m_width / 2 - gui_window->GetAllocation().width / 2, m_height / 2 - gui_window->GetAllocation().height / 2)); break; default: break; } } desktop.Update(m_clock.restart().asSeconds()); m_window->clear(); m_sfgui.Display(*m_window); m_window->display(); if (m_menu_action != JOIN_MENU_NONE) break; } m_entry_hostname.reset(); } bool Client::start_server() { string server_exe_path = m_exe_path; int length = server_exe_path.length(); if (length > 4) { string ext = server_exe_path.substr(length - 4); transform(ext.begin(), ext.end(), ext.begin(), ::tolower); if (ext == ".exe") server_exe_path = server_exe_path.substr(0, length - 4); } server_exe_path += "-server"; pid_t pid = fork(); if (pid < 0) return false; if (pid > 0) { m_server_pid = pid; return true; } execl(server_exe_path.c_str(), "treacherous-terrain-server", NULL); exit(-1); } void Client::stop_server() { if (m_server_pid > 0) { kill(m_server_pid, SIGINT); m_server_pid = 0; waitpid(-1, NULL, 0); } } void Client::run_client() { m_window->setMouseCursorVisible(false); double last_time = 0.0; bool in_game = true; while (in_game && m_window->isOpen()) { double current_time = m_clock.getElapsedTime().asSeconds(); double elapsed_time = current_time - last_time; sf::Event event; while (m_window->pollEvent(event)) { switch (event.type) { case sf::Event::Closed: m_window->close(); break; case sf::Event::KeyPressed: switch (event.key.code) { case sf::Keyboard::Escape: in_game = false; break; case sf::Keyboard::F1: grab_mouse(!m_mouse_grabbed); break; default: break; } break; case sf::Event::MouseButtonPressed: if((event.mouseButton.button == sf::Mouse::Left) && (m_shot_fired == false) && // Don't allow shots ontop of each other // The server needs to allow player to shoot, so that // multiple shots cannot be fired at the same time (m_players[m_current_player]->m_shot_allowed) && (!m_players[m_current_player]->m_is_dead) && (m_client_has_focus)) { m_left_button_pressed = true; } break; case sf::Event::MouseButtonReleased: if((event.mouseButton.button == sf::Mouse::Left) && // Prevents a shot from being fired upon release // while another shot is currently being fired. (m_players[m_current_player]->m_shot_allowed) && (!m_players[m_current_player]->m_is_dead) && (m_left_button_pressed) && (m_client_has_focus)) { m_drawing_shot = false; m_left_button_pressed = false; m_shot_fired = true; create_shot(); } break; case sf::Event::Resized: resize_window(event.size.width, event.size.height); break; case sf::Event::LostFocus: m_client_has_focus = false; break; case sf::Event::GainedFocus: m_client_has_focus = true; break; default: break; } } update(elapsed_time); redraw(); last_time = current_time; // temporary for now. otherwise this thread consumed way too processing sf::sleep(sf::seconds(0.005)); // 5 milli-seconds } } void Client::recenter_cursor() { if (m_mouse_grabbed) sf::Mouse::setPosition(sf::Vector2i(m_width / 2, m_height / 2), *m_window); } void Client::grab_mouse(bool grab) { m_mouse_grabbed = grab; m_window->setMouseCursorVisible(!grab); recenter_cursor(); } void Client::update(double elapsed_time) { sf::Packet client_packet; m_net_client->Receive(); client_packet.clear(); // Handle all received data (only really want the latest) while(m_net_client->getData(client_packet)) { sf::Uint8 packet_type; client_packet >> packet_type; switch(packet_type) { case PLAYER_CONNECT: { sf::Uint16 players_port = sf::Socket::AnyPort; sf::Uint8 pindex; std::string name = ""; client_packet >> pindex; client_packet >> name; client_packet >> players_port; // Should be a much better way of doing this. // Perhaps generate a random number if((name == m_current_player_name) && (players_port == m_net_client->getLocalPort())) { m_current_player = pindex; } // Create a new player if one does not exist. if(m_players.end() == m_players.find(pindex)) { refptr<Player> p = new Player(); p->name = name; client_packet >> p->direction; client_packet >> p->x; client_packet >> p->y; m_players[pindex] = p; } break; } case PLAYER_UPDATE: { sf::Uint8 player_index; // Update player position as calculated from the server. client_packet >> player_index; if(m_players.end() != m_players.find(player_index)) { client_packet >> m_players[player_index]->direction; client_packet >> m_players[player_index]->x; client_packet >> m_players[player_index]->y; client_packet >> m_players[player_index]->hover; } break; } case PLAYER_DISCONNECT: { sf::Uint8 player_index; // This completely removes the player from the game // Deletes member from the player list client_packet >> player_index; m_players.erase(player_index); break; } case PLAYER_DEATH: { // This will set a death flag in the player struct. sf::Uint8 player_index; // This completely removes the player from the game // Deletes member from the player list client_packet >> player_index; if(m_players.end() != m_players.find(player_index)) { m_players[player_index]->m_is_dead = true; } break; } case PLAYER_SHOT: { sf::Uint8 pindex; double x,y; double direction; double distance; client_packet >> pindex; client_packet >> x; client_packet >> y; client_packet >> direction; client_packet >> distance; // Ensure that the player who shot exists if(m_players.end() != m_players.find(pindex)) { // Perhaps sometime in the future, the shots will // be different colors depending on the player // or different power ups and what not. refptr<Shot> shot = new Shot(sf::Vector2f(x, y), direction, distance); m_players[pindex]->m_shot = shot; } break; } case TILE_DAMAGED: { float x; float y; sf::Uint8 pindex; client_packet >> x; client_packet >> y; client_packet >> pindex; // Damage the tile if it exists if((!m_map.get_tile_at(x, y).isNull())) { m_map.get_tile_at(x, y)->shot(); } // Allow player to shoot again if(m_players.end() != m_players.find(pindex)) { m_players[pindex]->m_shot_allowed = true; m_players[pindex]->m_shot = NULL; if(pindex == m_current_player) { m_shot_fired = false; } } break; } default : { // Eat the packet break; } } } // For now, we are going to do a very crude shove data into // packet from keyboard and mouse events. // TODO: Clean this up and make it more robust if(m_players.size() > 0) { refptr<Player> player = m_players[m_current_player]; sf::Uint8 w_pressed = KEY_NOT_PRESSED; sf::Uint8 a_pressed = KEY_NOT_PRESSED; sf::Uint8 s_pressed = KEY_NOT_PRESSED; sf::Uint8 d_pressed = KEY_NOT_PRESSED; sf::Int32 rel_mouse_movement = 0; // This is a fix so that the mouse will not move outside the window and // cause the user to click on another program. // Note: Does not work well with fast movement. if(m_client_has_focus) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { a_pressed = KEY_PRESSED; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { d_pressed = KEY_PRESSED; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { w_pressed = KEY_PRESSED; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { s_pressed = KEY_PRESSED; } if (m_mouse_grabbed) { rel_mouse_movement = sf::Mouse::getPosition(*m_window).x - m_width / 2; recenter_cursor(); } if (m_left_button_pressed) { if (m_drawing_shot) { m_drawing_shot_distance += SHOT_EXPAND_SPEED * elapsed_time; if (m_drawing_shot_distance > MAX_SHOT_DISTANCE) m_drawing_shot_distance = MAX_SHOT_DISTANCE; } else { m_drawing_shot = true; m_drawing_shot_distance = 0.0f; } } } m_player_dir_x = cos(player->direction); m_player_dir_y = sin(player->direction); // Send an update to the server if something has changed if((player->w_pressed != w_pressed) || (player->a_pressed != a_pressed) || (player->s_pressed != s_pressed) || (player->d_pressed != d_pressed) || (player->rel_mouse_movement != rel_mouse_movement)) { sf::Uint8 packet_type = PLAYER_UPDATE; client_packet.clear(); client_packet << packet_type; client_packet << m_current_player; client_packet << w_pressed; client_packet << a_pressed; client_packet << s_pressed; client_packet << d_pressed; client_packet << rel_mouse_movement; m_net_client->sendData(client_packet); player->w_pressed = w_pressed; player->a_pressed = a_pressed; player->s_pressed = s_pressed; player->d_pressed = d_pressed; player->rel_mouse_movement = rel_mouse_movement; } } m_net_client->Transmit(); } void Client::create_shot() { if (m_players.size() == 0) return; sf::Packet client_packet; double shot_distance = m_drawing_shot_distance + SHOT_RING_WIDTH / 2.0; sf::Uint8 packet_type = PLAYER_SHOT; client_packet.clear(); client_packet << packet_type; client_packet << m_current_player; client_packet << shot_distance; m_net_client->sendData(client_packet, true); m_drawing_shot_distance = 0; m_players[m_current_player]->m_shot_allowed = false; }
true
415faad334ce9b4e1c38fd441d9487dd059d66d1
C++
taobear/tbSTL
/allocator/tb_uninitialized.h
UTF-8
4,367
3.09375
3
[]
no_license
#ifndef __TB_UNITIALIZED_H_ #define __TB_UNITIALIZED_H_ #include <cstring> #include <cstdlib> #include "tb_type_traits.h" #include "allocator/tb_construct.h" #include "algorithm/tb_algobase.h" /* * unitialized_copy --> copy, memmove * unitialized_fill --> fill * unitialized_copy_n --> copy_n, memove * unitialized_fill_n --> fill_n */ namespace tbSTL { template <class InputIter, class ForwardIter> inline ForwardIter __uninitialized_copy_aux(InputIter first, InputIter last, ForwardIter result, true_type) { return tbSTL::copy(first, last, result); } template <class InputIter, class ForwardIter> inline ForwardIter __uninitialized_copy_aux(InputIter first, InputIter last, ForwardIter result, false_type) { ForwardIter cur = result; for ( ; first != last; ++first, ++cur) { tbSTL::construct(&*cur, *first); } return cur; } template <class InputIter, class ForwardIter, class Tp> inline ForwardIter __uninitialized_copy(InputIter first, InputIter last, ForwardIter result, Tp *) { return __uninitialized_copy_aux(first, last, result, tbSTL::is_trivally_copy_constructible<Tp>()); } template <class InputIter, class ForwardIter> inline ForwardIter uninitialized_copy(InputIter first, InputIter last, ForwardIter result) { return __uninitialized_copy(first, last, result, value_type(result)); } template <class ForwardIter, class Tp> inline void __uninitialized_fill_aux(ForwardIter first, ForwardIter last, const Tp &value, true_type) { tbSTL::fill(first, last, value); } template <class ForwardIter, class Tp> inline void __uninitialized_fill_aux(ForwardIter first, ForwardIter last, const Tp &value, false_type) { for ( ; first != last; ++first) { tbSTL::construct(&*first, value); } } template <class ForwardIter, class InTp, class OutTp> inline void __uninitialized_fill(ForwardIter first, ForwardIter last, const InTp &value, OutTp *) { return __uninitialized_fill_aux(first, last, value, tbSTL::is_trivally_default_constructible<OutTp>()); } template <class ForwardIter, class Tp> inline void uninitialized_fill(ForwardIter first, ForwardIter last, const Tp &value) { return __uninitialized_fill(first, last, value, value(first)); } template <class InputIter, class Size, class ForwardIter> ForwardIter __uninitialized_copy_n_aux(InputIter first, Size count, ForwardIter result, true_type) { for ( ; count > 0; --count) { tbSTL::construct(&*first, *result); ++first; ++result; } return result; } template <class InputIter, class Size, class ForwardIter> ForwardIter __uninitialized_copy_n_aux(InputIter first, Size count, ForwardIter result, false_type) { return copy_n(first, count, result); } template <class InputIter, class Size, class ForwardIter, class Tp> ForwardIter __uninitialized_copy_n(InputIter first, Size count, ForwardIter result, Tp *) { return __uninitialized_copy_n_aux(first, count, result, tbSTL::is_trivally_default_constructible<Tp>(result)); } template <class InputIter, class Size, class ForwardIter> ForwardIter uninitialized_copy_n(InputIter first, Size count, ForwardIter result) { return __uninitialized_copy_n(first, count, result, value_type(result))); } template <class ForwardIter, class Size, class Tp> ForwardIter __uninitialized_fill_n_aux(ForwardIter first, Size count, const Tp &value, true_type) { return fill_n(first, count, value); } template <class ForwardIter, class Size, class Tp> ForwardIter __uninitialized_fill_n_aux(ForwardIter first, Size count, const Tp &value, false_type) { for ( ; count > 0; --count) { tbSTL::construct(&*first, value); ++first; } return first; } template <class ForwardIter, class Size, class InTp, class OutTp> ForwardIter __uninitialized_fill_n(ForwardIter first, Size count, const InTp &value, OutTp *) { return __uninitialized_fill_n_aux(first, count, value, tbSTL::is_trivally_default_constructible<OutTp>(first)); } template <class ForwardIter, class Size, class Tp> ForwardIter uninitialized_fill_n(ForwardIter first, Size count, const Tp &value) { return __uninitialized_fill_n(first, count, value, value_type(first)); } } // namespace tbSTL #endif // __TB_UNITIALIZED_H_
true
09770d5338e3c48cdd7892231b4d4bfaefb79d19
C++
wallingtonbandeira/arduino-autofarm-prjct
/MainScript.ino
UTF-8
2,376
3.09375
3
[]
no_license
/**Para obtener el valor de VALOR EN AIRE y VALOR EN AGUA es necesario hacer pruebas * antes, cada sensor puede dar valores distintos */ const int VALOR_EN_AIRE = 620; //valor maximo que da el sensor en aire const int VALOR_EN_AGUA = 310; //valor maximo que da el sensor totalmente submergido const int PIN_SENSOR_HUMEDAD = A0; const int PIN_RELE = 10; const int TIEMPO_ENTRE_LECTURAS = 3600; //3600 = 1H | Cada hora se hace una lectura int valorSensorHumedad = 0; int porcentajeValorSensorHumedad = 0; long ultimoRiego = 0; long ultimaLectura = 0; void setup() { Serial.begin(9600); //abre el puerto serial pinMode(PIN_RELE, OUTPUT); } //En estas funcion es donde se estara ejecutando el codigo de la placa en bucle void loop() { if (millis() - ultimaLectura > TIEMPO_ENTRE_LECTURAS) { ultimaLectura = millis(); leerHumedadSuelo(); if (porcentajeValorSensorHumedad < 20) { ultimoRiego = millis(); activarRele(12000); } //Este 'if' previene que el sistema se quede bloqueado si llegamos al maximo //valor que guarda el reloj de la placa --> 4294967295 (49 dias) if (4294967295 - TIEMPO_ENTRE_LECTURAS >= ultimaLectura) { ultimaLectura = 0; ultimoRiego = 0; } } } //Actualiza las variables con una lectura del sensor void leerHumedadSuelo() { valorSensorHumedad = analogRead(PIN_SENSOR_HUMEDAD); porcentajeValorSensorHumedad = map(valorSensorHumedad, VALOR_EN_AIRE, VALOR_EN_AGUA, 0, 100); } int getValorSensorHumedad() { leerHumedadSuelo(); //actualiza variables return valorSensorHumedad; //devuelve el valor del sensor sin transformar } int getPorcentajeHumedad() { leerHumedadSuelo(); //actualiza variables return porcentajeValorSensorHumedad; //devuelve el porcentaje de humedad } /** * Deja activo el rele durante el tiempo que le pasemos en millisegundos * (1000 = 1 segundo) */ void activarRele(long tiempo) { bool salir = false; long horaActivada = millis(); digitalWrite(PIN_RELE, HIGH); //activa el relé while (salir == false) { if (millis() - horaActivada > tiempo) //si el tiempo activo es mayor que el pasado { digitalWrite(PIN_RELE, LOW); //desactiva el relé salir = true; } } }
true
cd289a2009eafb7879ce43edeb184204d3fac629
C++
atvfool/TipSensorNotifier
/TipSensorNotifier.ino
UTF-8
3,615
2.625
3
[]
no_license
/* * Author: Andrew Hayden * Github: https://github.com/atvfool * * The idea behind this project is to notify 1 or more numbers via text with coordinators with the device tips. * The real world use case is to strap this thing to an ATV and to notify other if it flips over * The circuit: * -Arduino MKRGSM1400 board * -Arduino MKR IMU Shield attached * -Arduino MKR GPS Shield connected via I2C */ // includes #include <MKRIMU.h> #include <MKRGSM.h> #include <Arduino_MKRGPS.h> #include "arduino_secrets.h" // constants const float rollLimits[2] = {-50, 50}; const float pitchLimits[2] = {-80, 80}; const char PINNUMBER[] = SECRET_PINNUMBER; // variables float eulerAngleRollOffset = 0; float eulerAnglePitchOffset = 0; GSMLocation location; GPRS gprs; GSM gsmAccess; GSM_SMS sms; void setup() { pinMode(LED_BUILTIN, OUTPUT); Serial.begin(9600); while(!Serial); Serial.println("Numbers to notify in case of an incident:"); for( int i=0;i<sizeof(NUMBER_LIST_LENGTH)-1; i++){ Serial.println(NUMBERS_TO_NOTIFY[i]); } // IMU Initialization if(!IMU.begin()){ Serial.println("Failed to initialize IMU!"); binkIMUError(); } if(IMU.eulerAnglesAvailable()){ float temp; IMU.readEulerAngles(temp, eulerAngleRollOffset, eulerAnglePitchOffset); eulerAngleRollOffset *= -1; eulerAnglePitchOffset *= -1; } // GMS Initialization Serial.println("SMS Messages Sender"); // connection state bool connected = false; // Start GSM shield // If your SIM has PIN, pass it as a parameter of begin() in quotes while (!connected) { if (gsmAccess.begin(PINNUMBER) == GSM_READY) { connected = true; } else { Serial.println("Not connected"); delay(1000); } } Serial.println("GSM initialized"); Serial.print("Roll Offset:"); Serial.println(eulerAngleRollOffset); Serial.print("Pitch Offset:"); Serial.println(eulerAnglePitchOffset); Serial.print('\t'); Serial.print("Roll"); Serial.print('\t'); Serial.println("Pitch"); } void loop() { // put your main code here, to run repeatedly: float heading, roll, pitch; if(IMU.eulerAnglesAvailable()) IMU.readEulerAngles(heading, roll, pitch); Serial.print('\t'); Serial.print(roll); Serial.print('\t'); Serial.println(pitch); float adjustedRoll = roll + eulerAngleRollOffset; float adjustedPitch = pitch + eulerAnglePitchOffset; Serial.print("offset"); Serial.print('\t'); Serial.print(adjustedRoll); Serial.print('\t'); Serial.println(adjustedPitch); // Seems like roll limits should be around 50 & -50 // Seems like pitch limits should be around 80 & -80 if(adjustRoll < rollLimits[0] || adjustedRoll > rollLimits[1] || adjustedPitch < pitchLimits[0] || adjustedPitch > pitchLimits[1]){ Serial.println("-------------EVENT RECORDED-------------"); Serial.println("SENDING MESSAGE"); } delay(3000); } void SendMessage(char[20] number, char[200] message){ Serial.println("SENDING"); Serial.println(); Serial.println("Message:"); Serial.println(message); // send the message sms.beginSMS(number); sms.print(message); sms.endSMS(); Serial.println("\nCOMPLETE!\n"); } void binkIMUError(){ while(1){ blinkError(); blinkError(); blinkError(); delay(2000); } } void blinkError(){ digitalWrite(LED_BUILTIN, HIGH); delay(500); digitalWrite(LED_BUILTIN, LOW); delay(500); }
true
bac80504127a39609fa22314c5101099ed372741
C++
AbbyBounty/Data-Structure-Assignment-
/07Aug/Stack using template/Stack using template/main.cpp
UTF-8
1,112
3.265625
3
[]
no_license
// // main.cpp // Stack using template // // Created by ABHILASH on 07/08/20. // Copyright © 2020 ABHILASH . All rights reserved. // #include <iostream> #include "Stack.hpp" int main(int argc, const char * argv[]) { cstack <int> s(5); int ch; int n; do { cout<<"1.push"<<endl; cout<<"2.pop"<<endl; cout<<"3.display"<<endl; cout<<"0.Exit"<<endl; cout<<"Enter your choice"<<endl; cin>>ch; switch(ch) { case 1: cout<<"enter no to be pushed :: "; cin>>n; s.push(n); cout<<endl; break; case 2: s.pop(); cout<<"No deleted....."<<endl; cout<<endl; break; case 3: cout<<endl; s.display(); cout<<endl; break; default: cout<<"enter valid choice"<<endl; break; } }while(ch!=0); cout<<endl; return 0; }
true
cbfcdf54418347cc078ef8b05514926204b9f7d9
C++
Dwarf-Planet-Project/SpaceDesignTool
/thirdparty/vesta/PlanarProjection.h
UTF-8
2,898
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "IJG" ]
permissive
/* * $Revision: 421 $ $Date: 2010-08-11 14:35:48 -0700 (Wed, 11 Aug 2010) $ * * Copyright by Astos Solutions GmbH, Germany * * this file is published under the Astos Solutions Free Public License * For details on copyright and terms of use see * http://www.astos.de/Astos_Solutions_Free_Public_License.html */ #ifndef _VESTA_PLANAR_PROJECTION_H_ #define _VESTA_PLANAR_PROJECTION_H_ #include "Frustum.h" #include <Eigen/Core> namespace vesta { class PlanarProjection { public: enum ProjectionType { Perspective = 0, Orthographic = 1, }; enum Chirality { LeftHanded = 0, RightHanded = 1, }; PlanarProjection(ProjectionType type, float left, float right, float bottom, float top, float nearDistance, float farDistance); /** Get the projection type (either Perspective or Orthographic) */ ProjectionType type() const { return m_type; } /** Get the coordinate of the left vertical clipping plane. */ float left() const { return m_left; } /** Get the coordinate of the right vertical clipping plane. */ float right() const { return m_right; } /** Get the coordinate of the bottom horizontal clipping plane. */ float bottom() const { return m_bottom; } /** Get the coordinate of the top horizontal clipping plane. */ float top() const { return m_top; } /** Get the distance to the front clipping plane. */ float nearDistance() const { return m_nearDistance; } /** Get the distance to the rear clipping plane. */ float farDistance() const { return m_farDistance; } Chirality chirality() const { if ((m_right < m_left) ^ (m_top < m_bottom)) { return LeftHanded; } else { return RightHanded; } } Eigen::Matrix4f matrix() const; Frustum frustum() const; float fovY() const; float fovX() const; float fovDiagonal() const; float aspectRatio() const; PlanarProjection slice(float nearDistance, float farDistance) const; static PlanarProjection CreatePerspective(float fovY, float aspectRatio, float nearDistance, float farDistance); static PlanarProjection CreatePerspectiveLH(float fovY, float aspectRatio, float nearDistance, float farDistance); static PlanarProjection CreateOrthographic(float left, float right, float bottom, float top, float nearDistance, float farDistance); static PlanarProjection CreateOrthographic2D(float left, float right, float bottom, float top); private: ProjectionType m_type; float m_left; float m_right; float m_bottom; float m_top; float m_nearDistance; float m_farDistance; }; }; #endif // _VESTA_PLANAR_PROJECTION_H_
true
bffbdad42db11f58235c8025e5fd8306c725f7c0
C++
zhuzhenxxx/CFrame
/db/oracle/createtable.cpp
GB18030
1,293
2.90625
3
[]
no_license
// // ʾһڴƷϢ // #include "_ooci.h" int main(int argc,char *argv[]) { // ݿӳ connection conn; // ݿ⣬ֵ0-ɹ-ʧ // ʧܴconn.m_cda.rcУʧconn.m_cda.messageС if (conn.connecttodb("scott/tiger@orcl11g_127.0.0.1","Simplified Chinese_China.ZHS16GBK") != 0) { printf("connect database failed.\n%s\n",conn.m_cda.message); return -1; } // SQLԲ sqlstatement stmt(&conn); // ׼SQLƷƷidƷname۸sal // ʱbtimeƷ˵memoƷͼƬpic // prepareҪжϷֵ stmt.prepare("\ create table goods(id number(10),\ name varchar2(30),\ sal number(10,2),\ btime date,\ memo clob,\ pic blob,\ primary key (id))"); // ִSQL䣬һҪжϷֵ0-ɹ-ʧܡ if (stmt.execute() != 0) { printf("stmt.execute() failed.\n%s\n%s\n",stmt.m_sql,stmt.m_cda.message); return -1; } printf("create table goods ok.\n"); return 0; }
true
9d0867e1eaf90f6628d735ddcdc862901fc249df
C++
PetrFlajsingr/PGR_project
/misc/GeoUtils.h
UTF-8
1,162
2.671875
3
[ "Unlicense" ]
permissive
// // Created by Petr Flajsingr on 2018-12-07. // #ifndef PGR_PROJECT_GEOUTILS_H #define PGR_PROJECT_GEOUTILS_H #include <glm/glm.hpp> namespace PGRutils { /** * Convert barymetric coordinates to cartesian * @param baryCoords barycentric coordinates on triangle * @param vertexA first triangle vertex * @param vertexB second triangle vertex * @param vertexC third triangle vertex * @return cartesian coordinates on a triangle */ glm::vec3 baryToCartesian(glm::vec3 &baryCoords, glm::vec3 &vertexA, glm::vec3 &vertexB, glm::vec3 &vertexC) { return baryCoords.x * vertexA + baryCoords.y * vertexB + baryCoords.z * vertexC; } /** * Convert barymetric coordinates to cartesian * @param baryCoords barycentric coordinates on triangle * @param vertexA first triangle vertex * @param vertexB second triangle vertex * @param vertexC third triangle vertex * @return cartesian coordinates on a triangle */ glm::vec3 baryToCartesian(glm::vec2 &baryCoords, glm::vec3 &vertexA, glm::vec3 &vertexB, glm::vec3 &vertexC) { return (1 - baryCoords.x - baryCoords.y) * vertexA + baryCoords.x * vertexB + baryCoords.y * vertexC; } } #endif //PGR_PROJECT_GEOUTILS_H
true
b839d98c86dbdcf700eb0afba484f50af4da12b6
C++
6alk1n/ThrashGen
/ThrashGen/Engine/Sprite.cpp
UTF-8
1,643
2.65625
3
[]
no_license
#include "Sprite.hpp" namespace ThrashEngine { Sprite::Sprite() { m_texture = nullptr; m_pos = m_textureUV=0; m_kill = true; __virtualization_level=VirtualLevelSprite; } Sprite::~Sprite() { } void Sprite::SetTexture(SDL_Texture* texture) { m_texture = texture; int u, v; u = v = 0; SDL_QueryTexture(m_texture, NULL, NULL, &u,&v); m_textureUV.w = u; m_textureUV.h = v; } ResultState Sprite::Draw(Graphics* graphics, double offx, double offy) { SDL_Rect dest; dest.x = (int)m_pos.x+ (int)offx; dest.y = (int)m_pos.y+ (int)offy; dest.w = (int)m_pos.w; dest.h = (int)m_pos.h; SDL_Rect src; src.x = m_textureUV.x; src.y = m_textureUV.y; src.w = m_textureUV.w; src.h = m_textureUV.h; return graphics->DrawTexture(m_texture, &dest, &src); } ResultState Sprite::Update(Sprite* spr, int) { return ResultState::Success; } ResultState Sprite::Update(double) { return ResultState::Success; } void Sprite::Move(double x, double y) { m_pos.x += x; m_pos.y += y; } void Sprite::Move(Vector mov) { m_pos += mov; } void Sprite::Move(VectorFull vec) { m_pos += Vector(vec.x,vec.y); } void Sprite::Move(Rectangle rect) { m_pos += rect; } void Sprite::SetSize(double w, double h) { m_pos.w = w; m_pos.h = h; } Rectangle Sprite::GetRect() { return m_pos; } Vector Sprite::GetPos() { return Vector(m_pos.x, m_pos.y); } void Sprite::GetUV(int& u, int& v, int& uend, int& vend) { u = m_textureUV.x; v = m_textureUV.y; uend = m_textureUV.w; vend = m_textureUV.h; } unsigned int Sprite::GetVirtualState() { return __virtualization_level; } }
true
3a68f627d4630f8984157e46d9966446b798ee92
C++
greenfox-zerda-sparta/korompaidani
/week-02/day-2/04/04.cpp
UTF-8
310
3.421875
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { int d[] = {1, 2, 3, 8, 5, 6}; // change 8 to 4, than print all the elements of the array for(int i=0; i<sizeof(d)/sizeof(int); i++){ if(d[i]==8){ d[i]=4; } cout << d[i] << endl; } return 0; }
true
4d5e0691976959c202f1203ebd5d0c84dad93acd
C++
xiaoge585059/algorithms
/shell_sort.cpp
GB18030
865
3.5625
4
[]
no_license
#include <iostream> #include "tools.h" using namespace std; class ShellSort { private: static bool is_less(int x, int y) { return x < y; } static void exchange(int a[], int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } public: static void sort(int a[], int a_len) { int h = 1; while (h < a_len / 3) { h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ... } while (h >= 1) { // Ϊ h for (int i = h; i < a_len; ++i) { // a[i] 뵽 a[i - h], a[i - 2 * h], a[i - 3 * h] ... ֮ for (int j = i; j >= h && is_less(a[j], a[j - h]); j -= h) { exchange(a, j, j - h); } } h = h / 3; } } static void test() { int a[10] = { 3, 0, 1, 8, 9, 2, 4, 5, 7, 6 }; sort(a, 10); print_array(a, 10); } }; /* */ /* int main() { ShellSort::test(); return 0; } //*/
true
9013a08e9725b997f65eb82f8dc9348931149019
C++
khomkas-itstep/ITStep_Lesson_01
/Homework_1_11.cpp
WINDOWS-1251
400
2.8125
3
[]
no_license
#include <stdio.h> #include <iostream> #include <locale.h> using std::cout; using std::endl; using std::cin; int main(void) { int X; setlocale(LC_ALL,"Rus"); cout << " \n"; cin >> X; if ( X % 4 == 0) cout << X << " " << " " << endl; else cout << X << " " << " " << endl; return 0; }
true
0a58bfb893ae58eb6e13494f90bfcd0c2838feac
C++
da-bao-jian/Algorithms
/greedy_algorithms/minimum_waiting_time.cpp
UTF-8
1,381
3.71875
4
[]
no_license
// You are given a non empty array of positive integers representing the amounts of time that specific queries take // to execute. Only one query can be executed at a time, but the queties can be executed in any order. // A query's waiting time is defined as the amount of time that it must wait before its execution starts. In other words, // if a query is executed second, then its waiting time is the duration of the first query; if a query is executed third, then its waiting time is the sum of // the durations of the first two queries. // write a function that returns the minimum amount of total waiting time for all of the queries. For example, if you are given the queties of durations [1,4,5] // then the total waiting time if the queries were executed in the order of [5,1,4] would be 0 + 5 + (5+1) = 11. The first query duration 5 would be executed immediately, so its // waiting time would be 0, the second query of duration 1 would have to wait 5 seconds to be executed, and the last query would have to wait the duration of the first // two queries before being executed. // // // queries = [3,2,1,2,6] // output = 17 // using namespace std; #include <vector> int minimumWaitingTime(vector<int> array){ sort(array.begin(),array.end()); int totalTime = 0; for(int i=0; i< array.size(); i++){ totalTime += array[i]*(array.size()-(i+1)); }; return totalTime; }
true
4cd873d9bbf64fb26cd48966d9c28c76b8c2940a
C++
AdityaGattu/Leetcode
/Google/Battle ships using dfs.cpp
UTF-8
777
3.1875
3
[]
no_license
class Solution { public: int countBattleships(vector<vector<char>>& board) { int numships=0; for(int i=0;i<board.size();i++) { for(int j=0;j<board[0].size();j++) { if(board[i][j]=='X') { numships++; sink(board,i,j); } } } return numships; } void sink(vector<vector<char>>& board,int i,int j) { if(i<0 || i>=board.size() || j<0 || j>=board[0].size() || board[i][j]=='.'){return;} board[i][j]='.'; sink(board,i-1,j); sink(board,i+1,j); sink(board,i,j-1); sink(board,i,j+1); } };
true
e7c6d58e4a74c19bf745405af60229f5f2a61167
C++
Opti213/myLabs
/DSA/sem4/Labs/Lab_01/main.cpp
UTF-8
2,789
3.609375
4
[]
no_license
#include <iostream> #include "vector" #include <bits/stdc++.h> class mList{ public: class Node { public: int data; Node *next; Node(int num) { data = num; } }; int size; Node *head; Node *first; Node *last; Node *EOL; void add(int num) { Node *tmp = new Node(num); if (size == 0) { first = last = head = tmp; size++; } else { last->next = tmp; last = tmp; size++; } } mList() { size = 0; first = last = head = EOL = nullptr; } mList(std::vector<int> array) { size = 0; for (int i = 0; i < array.size(); i++){ add(array[i]); } } int get(int num){ head = first; for (int i = 0; i < num; ++i) { head = head->next; } return head->data; } std::vector<int> allPositive(){ head = first; std::vector<int> res; for (int i = 0; i < size; ++i) { if (head->data > 0) res.push_back(head->data); head = head->next; } return res; } std::vector<int> allEven(){ head = first; std::vector<int> res; for (int i = 0; i < size; ++i) { if (head->data%2==0) res.push_back(head->data); head = head->next; } return res; } std::vector<int> allEvenAndPositive(){ head = first; std::vector<int> res; for (int i = 0; i < size; ++i) { if ((head->data%2==0) || (head->data > 0)) res.push_back(head->data); head = head->next; } return res; } void print(){ head = first; for (int i = 0; i < size; ++i) { std::cout << head->data; head = head->next; } } void task1(){ std::vector<int> tmp = this->allPositive(); std::sort(tmp.begin(), tmp.end()); mList res(tmp); res.print(); } void task2(){ std::vector<int> tmp = this->allEven(); std::sort(tmp.begin(), tmp.end()); mList res(tmp); res.print(); } void task3(){ std::vector<int> tmp = this->allEvenAndPositive(); std::sort(tmp.begin(), tmp.end()); mList res(tmp); res.print(); } }; using namespace std; int main() { vector<int> v = {0,1,2,3,4,5,6,7,8,9,-1,-2,-3,-4}; reverse(v.begin(), v.end()); for (int i = 0; i < v.size(); ++i) { cout << v[i]; } cout << endl; mList list(v); list.task1(); cout << endl; list.task2(); cout << endl; list.task3(); cout << endl; vector<int> v2 = list.allEven(); return 0; }
true
ca4386642758286a76aacf708943168a0cbcc430
C++
iceknif/Arduino
/sonia-3.ino
UTF-8
828
3.0625
3
[]
no_license
/* This sketch file is to add distance judgement and light the LED when the distance is lower than 30cm */ /* Add the function of adjusting the led blink frequence base on distance change */ long duration,cm; const int echo = 12; int frequence; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); } void loop() { //Read the time of high pulse of sonia duration = pulseIn(echo, HIGH); cm = duration * 0.1; //EZ Series accuracy is 1 us/mm. Serial.print(cm); Serial.println("cm"); delay(100); frequence = cm * 3; //the distance longer, the led blink slower ledblink(frequence); } void ledblink(int frequence){ digitalWrite(LED_BUILTIN, HIGH); delay(frequence); digitalWrite(LED_BUILTIN, LOW); delay(frequence); }
true
bacc2cff86071292de2418396f0a50351d7dc025
C++
MarcoMoinho/AdventOfCode2017
/4.cpp
UTF-8
1,574
3.609375
4
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> using namespace std; vector<string> string_split (const string &input, const char separator, const bool sort = false) { vector<string> result; if (input.empty()) return result; string temp; for (const auto c : input) { if (c != separator) { temp += c; continue; } if (!temp.empty()) { if (sort) { std::sort(temp.begin(), temp.end()); } result.push_back(temp); } temp.clear(); } if (!temp.empty()) { if (sort) { std::sort(temp.begin(), temp.end()); } result.push_back(temp); } result.shrink_to_fit(); return std::move(result); } // check if there are duplicate words in the phrase bool contains_duplicates(const string &input, const char separator, const bool sort) { const auto items = string_split(input, separator, sort); for (auto i = items.cbegin(); i != items.cend(); ++i) { if (std::count(items.cbegin(), items.cend(), *i) > 1) { return true; } } return false; } int main() { int p1_valid {0}, p2_valid {0}; ifstream input ("4.txt"); string line; while (getline(input, line)) { if (!contains_duplicates(line,' ',false)) ++p1_valid; // if we sort the component we don't need to check for anagrams if (!contains_duplicates(line,' ',true)) ++p2_valid; } cout << "Part 1: " << p1_valid << endl; cout << "Part 2: " << p2_valid << endl; return 0; }
true
668de0efa8874d5f9127d2651130f014aec29286
C++
IanFennell/Stuff
/LongDivRemain/remainderLongDiv.cpp
UTF-8
359
3.078125
3
[]
no_license
#include <iostream> using namespace std; int main(){ int n; int m; int div; int rem; while(cin>>n>>m){ if(m==0){ printf("Division by 0 error!\n"); } else{ div=n/m; rem=n%m; if(rem==0){ printf("%d divided by %d is %d\n",n,m,div); } else{ printf("%d divided by %d is %d with a remainder of %d\n",n,m,div,rem); } } } }
true
752a3cded468249756c76cc4a4e9bf55f50e247f
C++
olk/P0876
/code/static_current.cpp
UTF-8
409
2.765625
3
[]
no_license
int main(){ int a; fiber_context m=fiber_context::current(); // get active fiber fiber_context f{[&]{ a=0; int b=1; for(;;){ m=m.resume(); // switch to `main()` int next=a+b; a=b; b=next; } }}; for(int j=0; j<10; ++j) { f=f.resume(); // resume `f` std::cout << a << " "; } return 0; }
true
3bc9433fa083edc84dab34a82140306328917fad
C++
HH-LFY/HH
/CPP/电话簿管理系统.cpp
GB18030
9,653
2.859375
3
[]
no_license
#include<iostream> #include<string> #include<iomanip> #include<fstream> using namespace std; int count=0; class CData { public: CData(){}; virtual int Compare(CData &,int)=0; virtual void Show()=0; virtual ~CData(){}; }; class CNode { private: CData *pData; CNode *pNext; public: CNode(){pData=0;pNext=0;}; CNode(CNode &node) { pData=node.pData; pNext=node.pNext; } void InputData(CData *pdata){pData=pdata;} void ShowNode(){pData->Show();} CData *GetData(){return pData;} friend class CList; }; class CList { CNode *pHead; public: CList(){pHead=0;}; ~CList(){DeleteList();} void AddNode(CNode *pnode); CNode *DeleteNode(CNode *); CNode *LookUp(CData &); bool LookUpF(CData &); void ShowList(); void DeleteList(); CNode *GetListHead(){return pHead;} CNode *GetListNextNode(CNode *pnode); }; CNode *CList::GetListNextNode(CNode *pnode) { CNode *p1=pnode; return p1->pNext; }; void CList::AddNode(CNode *pnode) { if (pHead==0) { pHead=pnode; pnode->pNext=0; return; } else { pnode->pNext=pHead; pHead=pnode; } }; CNode *CList::DeleteNode(CNode *pnode) { CNode *p1,*p2; p1=pHead; while(p1!=pnode&&p1->pNext!=0) { p2=p1; p1=p1->pNext; } if (p1==pHead) { pHead=pHead->pNext; return pnode; } p2->pNext=p1->pNext; return pnode; } CNode *CList::LookUp(CData &data) { CNode *p1=pHead; while(p1) { if (p1->pData->Compare(data,1)==0) return p1; p1=p1->pNext; } return 0; } bool CList::LookUpF(CData &data) { bool f1=false; CNode *p1=pHead; while(p1) { if (p1->pData->Compare(data,0)==0) { p1->ShowNode(); f1=true; } p1=p1->pNext; } return f1; } void CList::ShowList() { CNode *p1=pHead; while(p1) { p1->pData->Show(); p1=p1->pNext; } } void CList::DeleteList() { CNode *p1,*p2; p1=pHead; while(p1) { delete p1->pData; p2=p1; p1=p1->pNext; delete p2; } } class CTelRecord:public CData { private : char szName[20]; char szNumber[20]; char szF; public: CTelRecord(){strcpy(szName,"\0");strcpy(szNumber,"\0");} CTelRecord(char *name,char *number) { strcpy(szName,name); strcpy(szNumber,number); szF=name[0]; } void SetRecord(char *name, char *number) { strcpy(szName,name); strcpy(szNumber,number); szF=name[0]; } int Compare(CData &,int); void Show(); }; int CTelRecord::Compare(CData&data,int choice) { CTelRecord &temp=(CTelRecord &)data; if(choice==1) return strcmp(szName,temp.szName); else return (szF==temp.szF ? 0:1); } void CTelRecord::Show() { cout<<setw(15)<<szName<<setw(15)<<szNumber<<endl; } void AddRecord(CList &TelList) { CNode *pNode; CTelRecord *pTel; char szName[20],szNumber[20]; cout<<"0˳ϵͳ˵)"<<endl; cin.getline(szName,20); while(strcmp(szName,"0")) { cout<<"绰: "<<endl; cin.getline(szNumber,20); pTel=new CTelRecord; pTel->SetRecord(szName,szNumber); pNode=new CNode; pNode->InputData(pTel); TelList.AddNode(pNode); count++; cout<<"0˳ϵͳ˵ "<<endl; cin.getline(szName,20); } cout<<endl<<endl; } void DisplayRecord(CList&TelList) { cout<<"Ŀǰ "<<count<<" ¼¼£"<<endl; cout<<setw(15)<<""<<setw(15)<<"绰롿"<<endl; TelList.ShowList(); cout<<endl<<endl; system("pause"); } void LookUpRecord(CList&TelList) { CNode *pLook; char szName[20]; cout<<"Ҫҵ0˳ϵͳ˵"<<endl; cin.getline(szName,20); while (strcmp(szName,"0")) { CTelRecord tele(szName,"0"); pLook=TelList.LookUp(tele); if (pLook) { cout<<"ڵ绰ҵ"<<szName<<",ǣ"<<endl; cout<<setw(15)<<""<<setw(15)<<"绰롿"<<endl; pLook->ShowNode(); } else cout<<"ڵ绰Ҳ"<<szName<<","<<endl; cout<<"Ҫҵ0˳ϵͳ˵"<<endl; cin.getline(szName,20); } cout<<endl<<endl; } void DeleteRecord(CList&TelList) { CNode *pLook; char szName[20]; cout<<"Ҫɾ0˳ϵͳ˵"<<endl; cin.getline(szName,20); while(strcmp(szName,"0")) { CTelRecord tel(szName,"0"); pLook=TelList.LookUp(tel); if (pLook) { cout<<"ڵ绰ҵ"<<szName<<",ǣ"<<endl; pLook->ShowNode(); cout<<"ȷǷɾ˼¼Y/N)ȷɾYy,ȡɾNn:"<<endl; char ok; cin>>ok; cin.ignore(); if (ok=='Y'||ok=='y') { TelList.DeleteNode(pLook); cout<<szName<<"ɾɹ"<<endl; delete pLook; count--; } else if(ok=='N'||ok=='n') cout<<szName<<"ɾʧ"<<endl; } else cout<<"ڵ绰Ҳ"<<szName<<","<<endl; cout<<"Ҫɾ0˳ϵͳ˵"<<endl; cin.getline(szName,20); } cout<<endl<<endl; } void ModifyRecord(CList &TelList) { CNode *pLook; CTelRecord *pTel; char szName[20],szNumber[20]; cout<<"Ҫ޸ĵ0˳ϵͳ˵"<<endl; cin.getline(szName,20); while(strcmp(szName,"0")) { CTelRecord tel(szName,"0"); pLook=TelList.LookUp(tel); if (pLook) { cout<<"ڵ绰ҵ"<<szName<<",ǣ"<<endl; pLook->ShowNode(); cout<<"-----濪ʼ޸-----"<<endl<<"޸ĺ: "<<endl; cin.getline(szName,20); cout<<"޸ĺĵ绰:"<<endl; cin.getline(szNumber,20); cout<<"ȷǷ޸Ĵ˼¼Y/N)ȷ޸Yy,ȡ޸Nn:"<<endl; char ok; cin>>ok; cin.ignore(); if (ok=='Y'||ok=='y') { pTel=new CTelRecord; *pTel=tel; pTel->SetRecord(szName,szNumber); pLook->InputData(pTel); cout<<szName<<"޸ijɹ"<<endl; } else if(ok=='N'||ok=='n') cout<<szName<<"޸ʧܣ"<<endl; } else cout<<" ڵ绰Ҳ"<<szName<<","<<endl; cout<<" Ҫ޸ĵ0˳ϵͳ˵"; cin.getline(szName,20); } } void StoreFile(CList&TelList) { ofstream outfile("TELEPHONE.DAT",ios::binary); if (!outfile) { cout<<" ݿļ򿪴ûнݴļ!\n"; return; } CNode *pnode; CTelRecord *pTel; string strName,strNumber; pnode=TelList.GetListHead(); while(pnode) { pTel=(CTelRecord *)pnode->GetData(); outfile.write((char *)pTel,sizeof(CTelRecord)); pnode=TelList.GetListNextNode(pnode); } outfile.close(); } void Operate(string &strChoice,CList&TelList) { if (strChoice=="1") AddRecord(TelList); else if (strChoice=="5") DisplayRecord(TelList); else if (strChoice=="3") LookUpRecord(TelList); else if (strChoice=="4") DeleteRecord(TelList); else if(strChoice=="2") ModifyRecord(TelList); else if (strChoice=="6") StoreFile(TelList); else cout<<"Բѡ: "<<endl; } void LoadFile(CList &TelList) { fstream infile("TELEPHONE.DAT",ios::binary); if (!infile) { cout<<"ûļ!\n\n"; return; } CNode *pNode; CTelRecord *pTel; while (!infile.eof()) { pTel=new CTelRecord; infile.read((char*)pTel,sizeof(CTelRecord)); pNode=new CNode; pNode->InputData(pTel); TelList.AddNode(pNode); } TelList.DeleteNode(pNode); infile.close(); } int main() { CList TelList; system("cls"); cout<<"*******************************************************************"<<endl; cout<<" --------------******ӭ绰ϵͳ******-------------\n"; cout<<"*******************************************************************"<<endl; LoadFile(TelList); string strChoice; do { cout<<"-------------ӭϵͳ˵------------- "<<endl; cout<<" 1. "<<endl; cout<<" 2. "<<endl; cout<<" 3.ѯ "<<endl; cout<<" 4.ɾ "<<endl; cout<<" 5.ȫ "<<endl; cout<<" 6. "<<endl; cout<<"ѡ񡿣"<<endl; cin>>strChoice; cin.ignore(); Operate(strChoice,TelList); }while(strChoice!="6"); StoreFile(TelList); cout<<"*******************************************************************"<<endl; cout<<" ------------******ӭٴʹõ绰ϵͳ******---------- "<<endl; cout<<"*******************************************************************"<<endl; system("pause"); return 0; }
true
a0c92706d2803d96f5cba7bcd2b5df14f32413c0
C++
LionelAuroux/MathFun
/primegen.cc
UTF-8
3,469
3.015625
3
[]
no_license
#include <iostream> #include <vector> #include <math.h> #include <sys/time.h> using namespace std; bool isrelatprime(int64_t prod, int64_t cnt) { int64_t res = prod % cnt; if (res == 1) return true; if (res == 0) return false; return isrelatprime(cnt, res); } vector<int64_t> get_prime_list(int64_t maxval) { vector<int64_t> prime_list; prime_list.push_back(2); prime_list.push_back(3); int64_t prod = 2 * 3; int64_t cnt = 5; while (true) { if (cnt >= maxval) break; if (isrelatprime(prod, cnt)) { prime_list.push_back(cnt); prod *= cnt; } cnt += 2; } return prime_list; } vector<int64_t> get_prime_list0(int64_t maxval) { int64_t sqrt_max = (int64_t) sqrt((double)maxval) + 1; char *ary = new char[maxval]; vector<int64_t> prime_list; cout << "SQRT MAX:" << sqrt_max << endl; struct timeval tv; suseconds_t usec; gettimeofday(&tv, NULL); usec = tv.tv_usec; for (int64_t i = 3; i < sqrt_max; i += 2) { if (!ary[i]) { int64_t j = i * 2; while (j < maxval) { ary[j] = 1; j += i; } } } gettimeofday(&tv, NULL); usec = tv.tv_usec - usec; cout << "list0 " << usec << endl; prime_list.push_back(2); for (int64_t i = 3; i < maxval; i += 2) { if (!ary[i]) prime_list.push_back(i); } return prime_list; } vector<int64_t> get_prime_list2(int64_t maxval) { vector<int64_t> prime_list; auto ary = new int64_t[maxval]; auto prime_rest = new int64_t[maxval]; ary[0] = 2; int64_t len = 1; prime_rest[0] = 1; int64_t cnt = 3; struct timeval tv; suseconds_t usec; gettimeofday(&tv, NULL); usec = tv.tv_usec; while (true) { bool is_prime = true; int64_t idx = 0; cout << "compo:" << cnt << endl; uint64_t next = ~0; for (int64_t it = 0; it < len; it += 1) { prime_rest[idx] += 2; if (prime_rest[idx] != 1 && prime_rest[idx] < next) next = prime_rest[idx]; if (prime_rest[idx] >= ary[it]) prime_rest[idx] -= ary[it]; cout << ary[it] << ": " << prime_rest[idx]; if (it + 1 < len) cout << ", "; if (!prime_rest[idx]) is_prime = false; idx += 1; } cout << endl; if (is_prime) { cout << "next: " << (cnt + next) << endl; ary[len] = cnt; prime_rest[idx] = 0; len += 1; } if (cnt >= maxval) break; cnt += 2; } gettimeofday(&tv, NULL); usec = tv.tv_usec - usec; cout << "list1 " << usec << endl; for (int64_t i = 0; i < len; i += 1) prime_list.push_back(ary[i]); return prime_list; } ostream &operator<<(ostream &o, vector<int64_t> &ls) { for (auto it: ls) { o << it << endl; } return o; } int main(int ac, char *av[]) { int64_t maxval = 1000000; if (ac >= 2) maxval = atoi(av[1]); auto ls1 = get_prime_list0(maxval); auto ls2 = get_prime_list2(maxval); int64_t idx = 0; for (auto it: ls1) { cout << it << " -- " << ls2[idx] << endl; idx += 1; } return 0; }
true
8ce9961a09e60fee1d2df617cc9db7603293bfe7
C++
ShaharAviv/OOP-1
/OOP1/EX1/EX1/EquilateralTriangle.h
UTF-8
1,324
3
3
[]
no_license
#pragma once #include "Vertex.h" #include "Board.h" #include "Utilities.h" #include "macros.h" #include "Rectangle.h" class EquilateralTriangle { public: //-------------- Constructors Area --------------------------------------// EquilateralTriangle(const Vertex vertices[3]); //-----------------------------------------------------------------------// // returns vertex in place index Vertex getVertex(int index) const; // draw the shape on a board void draw(Board& board) const; // returns the rectangle thats bounds the shape Rectangle getBoundingRectangle() const; // return the shape's area double getArea() const; // return the shape's perimeter double getPerimeter() const; // return the shape's center vertex Vertex getCenter() const; // return the shape's edge double getLength() const; // try the scale the shape bool scale(double factor); private: Vertex m_vertices[3]; // sets new vertexes to the shape bool set(const Vertex & v1, const Vertex & v2, const Vertex & v3); // returns if the shape is valid and compile the conditions bool isShapeValid(const Vertex & v1, const Vertex & v2, const Vertex & v3); // returns if 2 edges are equal bool isEqual(double edgeA, double edgeB) const; // return if the shape is upwards bool isUp() const; };
true
8dae60b0c71039488f9197ce76eefbfe53c458f7
C++
thinkoid/openspace
/src/util/HeapAllocator.hh
UTF-8
2,314
3.171875
3
[]
no_license
// -*- mode: c++; -*- #ifndef FREESPACE2_UTIL_HEAPALLOCATOR_HH #define FREESPACE2_UTIL_HEAPALLOCATOR_HH #include "defs.hh" #include <functional> namespace util { /** * @brief A generic heap manager * * This class does not allocate memory! It only keeps track of where memory is * stored and which memory ranges may be reused later. This needs some kind of * underlying memory manager before it can do anything. */ class HeapAllocator { public: /** * @brief A function that can resize a generic heap structure. * * This takes the new size of the heap as its only parameter. */ typedef std::function< void(size_t) > HeapResizer; private: struct MemoryRange { size_t offset = 0; size_t size = 0; bool operator<(const MemoryRange &other) const; bool operator==(const MemoryRange &other) const; }; size_t _heapSize = 0; size_t _lastSizeIncraese = 0; HeapResizer _heapResizer; std::vector< MemoryRange > _freeRanges; std::vector< MemoryRange > _allocatedRanges; void addFreeRange(const MemoryRange &range); void addAllocatedRange(const MemoryRange &range); /** * @brief Checks if all free ranges are merged properly. */ void checkRangesMerged(); static bool check_connected_range(const MemoryRange &left, const MemoryRange &right); public: explicit HeapAllocator(const HeapResizer &creatorFunction); ~HeapAllocator() = default; /** * @brief Allocates the specified amount of memory * @param size The size of the memory block to allocate * @return The offset at which the specified amount of memory can be used */ size_t allocate(size_t size); /** * @brief Frees the memory starting at the specified offset. * @param offset The offset at which to free memory. This value must have * been returned by allocate previously! */ void free(size_t offset); /** * @brief Retrieves the amount of allocations currently active * @return The active allocations in this heap. */ size_t numAllocations() const; }; } // namespace util #endif // FREESPACE2_UTIL_HEAPALLOCATOR_HH
true
4ed0783d305ac1f81098885bd79ee60064521676
C++
HTL2018/cpp_primer
/chap10/test10_20_21.cpp
UTF-8
710
3.203125
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> using std::vector; using std::count_if; using std::string; std::size_t bigerThan6(vector<string> const& v) { return count_if(v.cbegin(), v.end(), [](string const& s){ return s.size() > 6; }); } int main() { vector<string> v{ "alan", "moophy", "1234567", "1234567", "1234567", "1234567" }; std::cout << "test10_20: " << bigerThan6(v) << std::endl; int i = 7; auto check_and_decrement = [&i]() { return i > 0 ? !--i : !i;}; std::cout << "test_10_21: " ; while(!check_and_decrement()) std::cout << i << " "; std::cout << i << std::endl; return 0; }
true
09c13ea96a6f571b8740569afea547b8b1298721
C++
Grandez/Q1
/BERT/BERT/UtilityContainers.h
UTF-8
2,959
2.8125
3
[]
no_license
/* * Basic Excel R Toolkit (BERT) * Copyright (C) 2014-2017 Structured Data, LLC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef __UTILITY_CONTAINERS_H #define __UTILITY_CONTAINERS_H #include <deque> #include <string> using namespace std; /** * locked deque for threads. we don't overload base functions; * all protected functions are explicitly named. */ template < class T > class locked_deque : public deque < T > { protected: HANDLE hmutex; public: locked_deque() { hmutex = ::CreateMutex(NULL, FALSE, NULL); } ~locked_deque() { ::CloseHandle(hmutex); } public: void locked_push_back(T elt) { lock(); push_back(elt); unlock(); } T locked_pop_front() { lock(); T elt = this->operator[](0); pop_front(); unlock(); return elt; } size_t locked_size() { size_t count; lock(); count = size(); unlock(); return count; } void locked_consume(deque < T > &target) { lock(); target = (deque<T>)(*this); clear(); unlock(); } public: inline void lock() { ::WaitForSingleObject(hmutex, INFINITE); } inline void unlock() { ::ReleaseMutex(hmutex); } }; /** * utility for appending strings. you would think that stringstreams were more efficient, * but it's not clear that's the case. in any event using a wrapper class means we can * switch if desired. */ class locked_string_buffer { public: locked_string_buffer( int reserve = 4096 ) { str.reserve(reserve); hmutex = ::CreateMutex(NULL, FALSE, NULL); } ~locked_string_buffer() { ::CloseHandle(hmutex); } public: void append(const char *s) { lock(); str.append(s); unlock(); } void append(std::string s) { lock(); str.append(s); unlock(); } size_t size() { size_t count = 0; lock(); count = str.size(); unlock(); return count; } void clear() { lock(); str.clear(); // does this impact the reserved size? unlock(); } string take() { lock(); string s(str); str.clear(); unlock(); return s; } string& take(string &s) { lock(); s = str; str.clear(); unlock(); return s; } public: inline void lock() { ::WaitForSingleObject(hmutex, INFINITE); } inline void unlock() { ::ReleaseMutex(hmutex); } protected: string str; HANDLE hmutex; }; #endif // #ifndef __UTILITY_CONTAINERS_H
true
eec61064ccb33d75ec229c6bb34f5415dc565c47
C++
huannd0101/OOP_HaUI
/O2/NguyenDinhHuan_Bai2.cpp
UTF-8
2,518
3.34375
3
[]
no_license
#include<iostream> #include<string.h> using namespace std; class FACULTY; class STUDENT; class SCHOOL { private: char Name[30], Date[15]; public: friend class FACULTY; friend void PatchNameOfSchool(STUDENT &a); }; class FACULTY { private: char Name[30], Date[15]; SCHOOL x; public: void input(); void output(); friend class STUDENT; friend void PatchNameOfSchool(STUDENT &a); }; void FACULTY::input(){ cout << "Nhap name of faculty: "; fflush(stdin); gets(Name); cout << "Nhap date of faculty: "; fflush(stdin); gets(Date); cout << "Nhap name of school : "; fflush(stdin); gets(x.Name); cout << "Nhap date of school : "; fflush(stdin); gets(x.Date); } void FACULTY::output(){ cout << "Name of faculty: " << Name << endl; cout << "Date of faculty: " << Date << endl; cout << "Name of school : " << x.Name << endl; cout << "Date of school : " << x.Date << endl; } class PERSON { private: char Name[30], Birth[15], Address[30]; public: void input(); void output(); PERSON(); }; PERSON::PERSON(){ strcpy(Name, ""); strcpy(Birth, ""); strcpy(Address, ""); } void PERSON::input(){ cout << "Nhap name of person: "; fflush(stdin); gets(Name); cout << "Nhap birth of person: "; fflush(stdin); gets(Birth); cout << "Nhap address of person: "; fflush(stdin); gets(Address); } void PERSON::output(){ cout << "Name of person: " << Name << endl; cout << "Birth of person: " << Birth << endl; cout << "Address of person: " << Address << endl; } class STUDENT : public PERSON{ private: FACULTY y; char Class[15]; double Score; public: void input(); void output(); STUDENT(); friend void PatchNameOfSchool(STUDENT &a); }; STUDENT::STUDENT() : PERSON() { strcpy(Class, ""); Score = 0; } void STUDENT::input(){ PERSON::input(); y.input(); cout << "Nhap class: "; fflush(stdin); gets(Class); cout << "Nhap score: "; cin >> Score; } void STUDENT::output(){ PERSON::output(); y.output(); cout << "Class: " << Class << endl; cout << "Score: " << Score << endl; } void PatchNameOfSchool(STUDENT &a){ strcpy(a.y.x.Name, "DHCNHN"); } int main(){ STUDENT a; a.input(); cout << "\n--------------------Thong tin student---------------------" << endl; a.output(); PatchNameOfSchool(a); cout << "\n-------------Thong tin student sau khi sua----------------" << endl; a.output(); return 0; }
true
fe31954989299d95a6f57e8c93d97757727a7d7d
C++
StanfordAHA/Halide-to-Hardware
/src/ParallelRVar.h
UTF-8
712
2.703125
3
[ "MIT" ]
permissive
#ifndef HALIDE_PARALLEL_RVAR_H #define HALIDE_PARALLEL_RVAR_H /** \file * * Method for checking if it's safe to parallelize an update * definition across a reduction variable. */ #include "Function.h" namespace Halide { namespace Internal { /** Returns whether or not Halide can prove that it is safe to * parallelize an update definition across a specific variable. If * this returns true, it's definitely safe. If this returns false, it * may still be safe, but Halide couldn't prove it. */ bool can_parallelize_rvar(const std::string &rvar, const std::string &func, const Definition &r); } // namespace Internal } // namespace Halide #endif
true
6c93f8df9896b7bd5d339827f7e17734a707c824
C++
hchaozhe/Algorithms_course_codes
/Course2_GraphSearch/Dijkstra_CRH.cpp
UTF-8
2,707
2.984375
3
[]
no_license
#include "binary_heap_CRH.hpp" #include "Graph_Directed_CRH_DJ.hpp" #include <math.h> void CreateHeap(Graph &graph, MinHeap &heap){ for(int i = 0;i<graph.V;i++){ heap.insertKey(INT_MAX,i); } } void CreatHeap(Graph &graph, MinHeap &heap){ for(int i = 0;i<graph.V;i++){ // heap.insertKey(INT_MAX,i); heap.insertKey(i+1,i); } } void dijkstra(Graph &graph, int src, vector<int> &dist){ MinHeap heap(graph.V); CreateHeap(graph,heap); // make src the smallest value dist[src] = 0; heap.decreaseKey(src,dist[src]); while(!heap.empty()){ // Extract the vertex with minimum distance value int u = heap.getMinv(); // extracted vertex heap.extractMin(); // dist[u] it should not be INT_MAX // Traverse all the adjacent vertex of u and update their distance // note that this is undirected graph, so one may have repeated edge for (int i =0;i<graph.adjList[u].size();i++){ int w = graph.adjList[u][i]; if (heap.isInMinHeap(w) && dist[u] != INT_MAX && dist[u] + graph.valueList[u][i] < dist[w] ){ // update the new distance to v dist[w] = dist[u] + graph.valueList[u][i]; // and update its key in the heap // and this by definition would trigger the heapify and thus move the // current minimum one to the top // REMARK, this first index should not be the vertex, but its // position on the vertex heap.decreaseKey(heap.getpos(w),dist[w]); } } } } void printDistance(vector<int> &dist, vector<int> &n) { printf("Vertex Distance from Source\n"); for (int i = 0; i < n.size(); ++i){ if(n[i]<dist.size()) printf("%d \t\t %d\n", n[i]+1, dist[n[i]]); } for (int i = 0; i < n.size(); ++i){ if(n[i]<dist.size()) cout << dist[n[i]] <<","; } } int main(int argc, char *argv[]){ // load graph string path = ""; string filename; if (argc>1){ filename = argv[1]; }else{ filename = "dijkstraData.txt"; } string Name = path + filename; // absolute path Graph graph; loadtxt2Graph(Name, graph); if (graph.V<100){ printGraph(graph); } int src = 0; vector<int> dist(graph.V,INT_MAX); // intiallly all are maximum dijkstra(graph,src, dist); vector<int> posplot = {6,36,58,81,98,114,132,164,187,196}; printDistance(dist, posplot); // My answer is 2599,2610,2947,2052,2367,2399,2029,2442,2505,3068, return 0; }
true
d8a9a8249cb3dbad4151f46e54780a84967871cf
C++
glewtimo/chess_ai
/pieces.hpp
UTF-8
2,757
3.140625
3
[]
no_license
/********************************************************************************** * Program name: pieces.hpp * Author: Tim Glew * Date: 12/18/2019 * Desription: This is the declaration of the parent class piece and children * chess pieces. See below for member variables and member functions. *********************************************************************************/ #ifndef PIECES_HPP #define PIECES_HPP /* Forward Declarations */ class Board; class Square; /********************************************************************************** ************************* SECTION: Piece (Parent Class) ************************** **********************************************************************************/ class Piece { protected: bool white; bool dead; bool king; bool pawn; char symbol; int row; int col; int value; public: Piece(int, int); bool isWhite(); bool isDead(); bool isKing(); bool isPawn(); void setWhite(); void setDead(); void setAlive(); void setKing(); void setPawn(); void setSymbol(char); void setRow(int); void setCol(int); void setValue(int); void invertValue(); int getRow(); int getCol(); int getValue(); char getSymbol(); virtual bool validMove(Board*, Square*, Square*) = 0; virtual void getPossibleMoves(int*, int*, int&, Board*) = 0; }; /********************************************************************************** ************************* SECTION: Children of Piece ***************************** **********************************************************************************/ class Pawn : public Piece { private: bool hasMoved; public: Pawn(int, int); bool isHasMoved(); void setHasMoved(bool); bool validMove(Board*, Square*, Square*); void getPossibleMoves(int*, int*, int&, Board*); }; class King : public Piece { public: King(int, int); bool validMove(Board*, Square*, Square*); void getPossibleMoves(int*, int*, int&, Board*); }; class Queen : public Piece { public: Queen(int, int); bool validMove(Board*, Square*, Square*); void getPossibleMoves(int*, int*, int&, Board*); }; class Rook : public Piece { public: Rook(int, int); bool validMove(Board*, Square*, Square*); void getPossibleMoves(int*, int*, int&, Board*); }; class Knight : public Piece { public: Knight(int, int); bool validMove(Board*, Square*, Square*); void getPossibleMoves(int*, int*, int&, Board*); }; class Bishop : public Piece { public: Bishop(int, int); bool validMove(Board*, Square*, Square*); void getPossibleMoves(int*, int*, int&, Board*); }; #endif
true
8e70f7d8b400795e06b87fa3dd6598ce938a38b8
C++
cckk4467/DO_Vector
/Vector.cpp
GB18030
1,369
3.6875
4
[]
no_license
#include<iostream> #include<math.h> class Vec { public: Vec(double X,double Y):x(X),y(Y){} double x,y; //basic Vec operator+(Vec c); Vec operator-(Vec c); Vec operator+(double c);//cλȼ|V|=|V|+c; Vec operator-(double c);//ϼcλȼ|V|=|V|-c; double operator^(Vec c);//Ĥ Vec operator*(double c); Vec operator/(double c); double operator*(Vec c);// double mo();//ȡĤ void setLength(double c); double operator|(Vec c);//Ӱ //Debug void print(){std::cout<<x<<" "<<y<<" "<<mo()<<std::endl;} }; Vec Vec::operator+(Vec c) { return Vec(x+c.x,y+c.y); } Vec Vec::operator-(Vec c) { return Vec(x-c.x,y-c.y); } Vec Vec::operator+(double c) { double m=mo(); return Vec(x+c/m*x,y+c/m*y); } Vec Vec::operator-(double c) { double m=mo(); return Vec(x-c/m*x,y-c/m*y); } double Vec::operator^(Vec c) { return x*c.y-c.x*y; } Vec Vec::operator*(double c) { return Vec(x*c,y*c); } Vec Vec::operator/(double c) { return Vec(x/c,y/c); } double Vec::operator*(Vec c) { return c.x*x+c.y*y; } double Vec::mo() { return hypot(x,y); } void Vec::setLength(double c) { double m=mo(); x=c/m*x; y=c/m*y; } double Vec::operator|(Vec c) { return (c.x*x+c.y*y)/c.mo(); } int main() { Vec i(100,100); i.setLength(320); std::cout<<""<<std::endl; i.print(); return 0; }
true
3d40db92121917abd8f51f72f5f5b1db8a5093fa
C++
mohabouje/Polyhedrus
/Polyhedrus.Native/Vca.cpp
UTF-8
744
2.578125
3
[]
no_license
#include "Vca.h" namespace Polyhedrus { Vca::Vca() { ControlVoltage = 0.0f; currentCv = 0.0f; buffer = 0; } Vca::~Vca() { delete buffer; } void Vca::Initialize(int samplerate, int bufferSize, int modulationUpdateRate) { buffer = new float[bufferSize](); this->modulationUpdateRate = modulationUpdateRate; this->samplerate = samplerate; } void Vca::Process(float* input, int len) { // smooth linear interpolation of CV float diff = (ControlVoltage - currentCv) / modulationUpdateRate; for (int i = 0; i < len; i++) { if (i < modulationUpdateRate) // ripe for optimization currentCv = currentCv + diff; buffer[i] = input[i] * currentCv; } } float* Vca::GetOutput() { return buffer; } }
true
ca3450aa7f7a2dde320c70f67d3b0847edef480a
C++
zli34/pursuit-evasion
/src/main/utilities.cpp
UTF-8
4,171
2.578125
3
[]
no_license
#include "utilities.hpp" #include <queue> #include <glog/logging.h> namespace coopPE { bool next_move(std::vector<proto::Unit_Action> & moves) { const uint32_t num_units(moves.size()); // increment action and return, if can't increment (already at // RIGHT) then reset (set to NOTHING) and move to next pursuer // (don't return immediately) for (uint32_t i = 0; i < num_units; ++i) { if (moves.at(i) == proto::Unit_Action_NOTHING) { moves.at(i) = proto::Unit_Action_UP; return true; } else if (moves.at(i) == proto::Unit_Action_UP) { moves.at(i) = proto::Unit_Action_DOWN; return true; } else if (moves.at(i) == proto::Unit_Action_DOWN) { moves.at(i) = proto::Unit_Action_LEFT; return true; } else if (moves.at(i) == proto::Unit_Action_LEFT) { moves.at(i) = proto::Unit_Action_RIGHT; return true; } else if (moves.at(i) == proto::Unit_Action_RIGHT) { moves.at(i) = proto::Unit_Action_NOTHING; } else { LOG(FATAL) << "Unknown value for action: " << moves.at(i); } } // all pursuers were already set to RIGHT, this is the last set of // actions, thus return false to indicate no more moves, return false; } std::vector<uint32_t> find_peaks( const std::vector<double> & probs, const uint32_t & num_peaks, const std::shared_ptr<const Network> & network) { std::vector<uint32_t> peaks; std::vector<std::pair<double, uint32_t> > coverages; for (uint32_t i = 0; i < network->size(); ++i) { double c(probs.at(i)); std::for_each(network->neigh(i).begin(), network->neigh(i).end(), [&c, &probs] (const uint32_t & n_) { c += probs.at(n_); }); coverages.emplace_back(std::move(c), i); } // sort coverage pairs for (uint32_t i = 0; i < num_peaks; ++i) { auto pk(std::max_element(coverages.begin(), coverages.end())); if (pk->first > 1e-6) { peaks.push_back(pk->second); pk->first = 0.0; if (i < (num_peaks - 1)) { auto neigh_it(network->neigh(pk->second).begin()); const auto neigh_end(network->neigh(pk->second).end()); for (; neigh_it != neigh_end; ++neigh_it) { // zero out neighbor coverage coverages.at(*neigh_it).first = 0.0; auto second_neigh_it( network->neigh(*neigh_it).begin()); const auto second_neigh_end( network->neigh(*neigh_it).end()); for (; second_neigh_it != second_neigh_end; ++second_neigh_it) { // subtract neighbor probability from second neighbors coverages.at(*second_neigh_it).first -= probs.at(*neigh_it); } } } } else { CHECK_GT(i, 0); peaks.push_back(peaks.at(0)); } } return peaks; } std::vector<uint32_t> assign_peaks( const std::vector<uint32_t> & locs, const std::vector<uint32_t> & peaks, const std::shared_ptr<const Network> & network) { const uint32_t num_peaks(peaks.size()); CHECK_EQ(locs.size(), num_peaks); std::vector<uint32_t> assignments; for (uint32_t i = 0; i < num_peaks; ++i) { assignments.push_back(i); } std::vector<uint32_t> best_assignments; double best_dist = std::numeric_limits<double>::infinity(); do { double dist = 0.0; for (uint32_t i = 0; i < num_peaks; ++i) { dist += network->dist(peaks.at(assignments.at(i)), locs.at(i)); } if (dist < best_dist) { best_assignments = assignments; best_dist = dist; } } while (std::next_permutation(assignments.begin(), assignments.end())); return best_assignments; } } // namespace coopPE
true
af73ee05d1af2743b0cb4ae4cd679010e7085c6a
C++
ZectorJay/CPP_MODULE_04
/ex01/Enemy.cpp
UTF-8
1,547
2.84375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Enemy.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hmickey <hmickey@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/15 11:11:03 by hmickey #+# #+# */ /* Updated: 2021/07/01 10:58:08 by hmickey ### ########.fr */ /* */ /* ************************************************************************** */ #include "Enemy.hpp" Enemy::Enemy(){}; Enemy::~Enemy(){}; Enemy::Enemy( int hp, std::string const & type ) : _hp(hp), _type(type){} std::string Enemy::getType() const { return (_type); } int Enemy::getHP() const { return (_hp); } Enemy & Enemy::operator=( Enemy const & src ){ if (this != &src){ _hp = src.getHP(); _type = src.getType(); } return (*this); } void Enemy::takeDamage( int amount ){ if (_hp - amount < 0){ _hp = 0; } else{ _hp -= amount; } } std::ostream & operator << (std::ostream & o, Enemy const & src){ o << "\033[1;38;2;20;255;20m"; o << src.getType() << " HP: " << src.getHP() << std::endl; o << "\033[0m"; return (o); }
true
f6d244743e918a7caba0f631a5d5328287af2677
C++
Jyah42/R-Type
/Client/SFMLDisplay.cpp
UTF-8
2,210
2.5625
3
[]
no_license
#include "SFMLDisplay.h" #include "EventGeneric.h" #include "SFMLDrawable.h" SFMLDisplay::SFMLDisplay(std::list<Obj *>& objs, std::string const& username) : game_(0), menu_(0), window_(0), objs_(objs), username_(username), event_(0), pause_(false) { } SFMLDisplay::~SFMLDisplay(void) { if (this->window_) this->window_->Close(); if (this->game_) delete this->game_; if (this->event_) delete this->event_; delete this->window_; delete this->menu_; } void SFMLDisplay::init() { this->window_ = new sf::RenderWindow(); this->menu_ = new MenuManager(this->window_, this->username_); this->window_->Create(sf::VideoMode(800, 600, 32), "R-Type"); this->window_->SetFramerateLimit(60); this->menu_->draw(); this->window_->Display(); this->menu_->init(); } void SFMLDisplay::initGame(int idPlayer) { this->game_ = new Game(this->window_, this->objs_, idPlayer); this->game_->init(); } void SFMLDisplay::destroyGame() { } void SFMLDisplay::update() { if (this->game_) this->game_->update(); if (!this->game_ || this->pause_) this->menu_->update(); } void SFMLDisplay::draw() { this->window_->Clear(); if (this->game_) this->game_->draw(); if (!this->game_ || this->pause_) this->menu_->draw(); this->window_->Display(); } AEvent *SFMLDisplay::getEvent() { AEvent *tmp; if (this->game_) { tmp = this->game_->getEvent(); if (tmp && tmp->getType() == RTCP::GAME_PAUSE) { this->pause_ = true; this->menu_->setEvent(tmp); return 0; } } if (!this->game_ || this->pause_) { tmp = this->menu_->getEvent(); if (tmp && tmp->getType() == RTCP::LAUNCH_GAME) this->initGame(dynamic_cast<EventGeneric*>(tmp)->getChar()); else if (tmp && tmp->getType() == RTCP::GAME_RESUME) { this->pause_ = false; this->game_->setPause(false); delete tmp; return 0; } } return tmp; } void SFMLDisplay::setEvent(AEvent* event) { if ((event->getType() == RTCP::NETWORK_DISCONNECTED || event->getType() == RTCP::GAME_NOTIFY_END) && this->game_) { delete this->game_; this->game_ = 0; } if (this->game_) delete event; else this->menu_->setEvent(event); } bool SFMLDisplay::isOpened() const { return this->window_->IsOpened(); }
true
5a77ea65978eb7c24dd7aeeaa4976608d05f7f42
C++
breezy1812/MyCodes
/LeetCodeR3/486-Predict the Winner/solution.cpp
UTF-8
507
2.8125
3
[]
no_license
class Solution { public: bool PredictTheWinner(vector<int>& nums) { int n = nums.size(); vector<vector<int>> dp(n, vector<int>(n, 0)); for (int i = 0; i < n; i++) { dp[i][i] = nums[i]; } for (int len = 2; len <= n; len++) { for (int i = 0; i + len <= n; i++) { int j = i + len - 1; dp[i][j] = max(nums[i] - dp[i+1][j], nums[j] - dp[i][j-1]); } } return dp[0][n-1] >= 0; } };
true
b3ce4332640f1014d59cfd5d6acd72e5baf46485
C++
frankkon/ConvertMailToMessage
/ConvertMailToMessage/mail.h
GB18030
1,303
2.6875
3
[]
no_license
//--------------------------------------------------------------------- //ʼģhļ //--------------------------------------------------------------------- #ifndef _MAIL_H #define _MAIL_H #include <string> using namespace std; enum EContentType { TEXT_PLAIN = 0, TEXT_HTML, APPLICATION_OCTETSTREAM, NEXT_FREE_MIME_CODE }; enum EContentTransferEncoding { _7BIT = 0, _8BIT, BINARY, QUOTED_PRINTABLE, BASE64, NEXT_FREE_ENCODING_CODE }; class CMail { public: CMail(); CMail(char* sMailInfo); virtual ~CMail(); string getFrom(); string getTo(); string getSubject(); EContentType getContentType(); EContentTransferEncoding getContentTransferEncoding(); string getContent(); void setFrom(); void setTo(); void setSubject(); void setContentType(); void setContentTransferEncoding(); void setContent(); void setAllField(); void setAllField(char* sMailInfo); void setMailInfo(char* sMailInfo); private: string m_sFrom; string m_sTo; string m_sSubject; EContentType m_eContentType; EContentTransferEncoding m_eContentTransferEncoding; string m_sContent; //ʼ string m_sMailInfo;//ӷ˽ܵݡ }; #endif //_MAIL_H
true
3b926ecfca136cf433ced97bbb669a778cbc17d5
C++
yourWaifu/sleepy-discord
/sleepy_discord/cpr_session.cpp
UTF-8
1,326
2.59375
3
[ "MIT" ]
permissive
#include "cpr_session.h" #ifndef NONEXISTENT_CPR namespace SleepyDiscord { void CPRSession::setHeader(const std::vector<HeaderPair>& header) { cpr::Header head; for (HeaderPair pair : header) head.insert({ pair.name, pair.value }); session.SetHeader(head); } void CPRSession::setMultipart(const std::vector<Part>& parts) { std::vector<cpr::Part> cprParts; for (Part const & m : parts) { if (m.isFile) cprParts.push_back(cpr::Part(m.name, cpr::File(m.value))); else cprParts.push_back(cpr::Part(m.name, m.value)); } muiltpart.parts = cprParts; session.SetMultipart(muiltpart); } Response CPRSession::request(RequestMethod method) { return perform(method); } Response CPRSession::perform(RequestMethod method) { cpr::Response response; switch (method) { case Post : response = session.Post (); break; case Patch : response = session.Patch (); break; case Delete: response = session.Delete(); break; case Get : response = session.Get (); break; case Put : response = session.Put (); break; default : return Response(); break; } Response target; target.statusCode = response.status_code; target.text = response.text; for (std::pair<std::string, std::string> i : response.header) { target.header.insert(i); } return target; } } #endif
true
ba55f863d7bb13e11f5022862df2cdd0229416b4
C++
dekorlp/RayTracer
/src/IPrimitive.h
UTF-8
558
2.734375
3
[ "Apache-2.0" ]
permissive
#pragma once #include "Vector3.h" #include "Ray.h" struct hit_record { float t; Vector3 p; Vector3 normal; }; class IPrimitive { public: // vertices Vector3 mV0; Vector3 mV1; Vector3 mV2; Vector3 normal; Vector3 surfaceColor, emissionColor; /// surface color and emission (light) float mReflection; /// surface transparency and reflectivity // physical based rendering float mMetallic; float mRroughness; float mAmbientOcclusion; virtual bool intersect(Ray& ray, float t_min, float t_max, hit_record &rec) const = 0; };
true
0a6dffb00632f1a159e87829f1b42eca4a5098e6
C++
migueldingli1997/CPS2004-Object-Oriented-Programming-Assignment
/Implementation/Task 2/src/spaces/EmptySpace.h
UTF-8
679
2.96875
3
[ "MIT" ]
permissive
#ifndef TASK2_EMPTYSPACE_H #define TASK2_EMPTYSPACE_H #include "Space.h" namespace spaces { using namespace core; class EmptySpace final : public Space { public: /** * @param id space ID * @param name space name */ EmptySpace(uint id, const std::string &name); /** * Simply returns a message stating that no change * was made to any player. * ~Refer to superclass for parameter and return description. */ const std::string applyEffect(Player &player, std::vector<Player *> &allPlayers, const GameBoard &board) override; }; } #endif //TASK2_EMPTYSPACE_H
true
9d349d772c605dbbf101219c7813ef2102d5d119
C++
greenfox-zerda-sparta/Judo3579
/week4/Tuesday/4.6/4.6.main.cpp
UTF-8
770
3.9375
4
[]
no_license
#include <iostream> #include <string> #include "Circle.h" using namespace std; /*class Circle { private: double radius; double area; double circumference; public: Circle(int radius) { this->radius = radius; } double get_area() { this->area = 2 * this->radius * 3.14; } double get_circumference() { this->circumference = this->radius * this->radius * 3.14; } }; */ int main() { // Create a `Circle` class that takes it's radius as constructor parameter // It should have a `get_circumference` method that returns it's circumference // It should have a `get_area` method that returns it's area Circle circle(7); cout << circle.get_area() << endl; cout << circle.get_circumference() << endl; return 0; }
true
150ee414615944a48a1d415c42b2f0391c0f2be6
C++
sanghoon23/Algorithm
/QBaekJoon_210107_특정한최단경로/ConsoleApplication1_Test/ConsoleApplication1_Test.cpp
UTF-8
1,305
2.828125
3
[]
no_license
#include "pch.h" #include <iostream> #include <vector> #include <queue> #include <string.h> using namespace std; #define MMAX 800001 #define PII pair<int, int> int N = 0, E = 0, A = 0, B = 0; vector<int> Dijkstra(vector<vector<PII>>& Board, int Start) { vector<int> Dist(N + 1, MMAX); Dist[Start] = 0; //@ 0 으로 갱신 잊지말자. priority_queue<PII> Que; Que.push({ 0, Start }); while (!Que.empty()) { int Cost = -(Que.top().first), Idx = Que.top().second; Que.pop(); for (int k = 0; k < Board[Idx].size(); ++k) { int Next = Board[Idx][k].first, NC = Cost + Board[Idx][k].second; if (Dist[Next] > NC) { Dist[Next] = NC; Que.push({ -(NC), Next }); } } } return Dist; } int main() { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); cin >> N >> E; vector<vector<PII>> Board(N + 1, vector<PII>()); for (int i = 0; i < E; ++i) { int F, S, W; cin >> F >> S >> W; Board[F].push_back({ S, W }); Board[S].push_back({ F, W }); } cin >> A >> B; int Answer = 0; vector<int> Root = Dijkstra(Board, 1); vector<int> ANode = Dijkstra(Board, A); vector<int> BNode = Dijkstra(Board, B); Answer = min((Root[A] + ANode[B] + BNode[N]), (Root[B] + BNode[A] + ANode[N])); if (Answer >= MMAX) cout << -1 << '\n'; else cout << Answer << '\n'; return 0; }
true
6a418d41b0e2a32c9e3c92e9a8fed1418952240e
C++
tariqul87/coding-practice
/leetcode/max_area_of_island.cpp
UTF-8
1,778
3.421875
3
[]
no_license
#include "./array.cpp" class Solution { public: int getGridArea(int i, int j, vector<vector<int>> &grid) { int row = grid.size(), column = grid[0].size(); if (0 <= i && i < row && 0 <= j && j < column && grid[i][j]) { grid[i][j] = 0; return 1 + getGridArea(i - 1, j, grid) + getGridArea(i, j - 1, grid) + getGridArea(i, j + 1, grid) + getGridArea(i + 1, j, grid); } return 0; } int maxAreaOfIsland(vector<vector<int>> &grid) { int row = grid.size(), column = grid[0].size(), maxArea = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { int currentArea = getGridArea(i, j, grid); maxArea = max(currentArea, maxArea); } } return maxArea; } }; int main(void) { Solution solution; // vector<vector<int>> grid = {{0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, // {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, // {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, // {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0}, // {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0}, // {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, // {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, // {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}}; vector<vector<int>> grid; for (int i = 0; i < 5; i++) { vector<int> row; for (int j = 0; j < 5; j++) { row.push_back(1); } grid.push_back(row); } cout << solution.maxAreaOfIsland(grid) << endl; }
true
1b37a23a43b9b3a6c36a6c19d8983f7f95aedb23
C++
elsypinzonv/cpp_problems
/trainning-escom/problems/MaratonI/prime_factorizacion.cpp
UTF-8
1,261
2.78125
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; #define optimizar_io ios_base::sync_with_stdio(0);cin.tie(0); long long const MAXN=100; long long sieve[MAXN + 1]; long long expp[MAXN + 1]; long long n; string getFormat(long long n){ string s = to_string(n); while(s.size()<3){ s=" "+s; } return s; } void printPrimes(){ cout<<getFormat(n); cout<<'!'<<" ="; long long cont=0LL; for(long long i=1LL; i<=n; i++){ if(expp[i]!=0){ if(cont>14){ cont=0; cout<<'\n'<<" "; } cout<<getFormat(expp[i]); cont++; } } } void acumuladoFactorial(){ fill(expp+2, expp + n + 1, 1); //duda: mi libreta tiene exp+2 for(long long i=n; i>3LL; --i){ if(!sieve[i]) continue; //Si es primo. expp[sieve[i]]+=expp[i]; expp[i/sieve[i]]+=expp[i]; expp[i]=0; } } void sieveMark(){ sieve[1]=1; for(long long i=2LL*2LL; i<=MAXN; i+=2LL){ sieve[i]=2LL; } long long root = sqrt(MAXN); for(long long i=3LL; i<=root; i+=2LL){ if(sieve[i]) continue; for(long long j=i*i; j<=MAXN; j+=i){ if (!sieve[j]) sieve[j]=i; } } } void solve(){ sieveMark(); cin>>n; while(n != 0){ acumuladoFactorial(); printPrimes(); fill(expp,expp+n,0); cout<<'\n'; cin>>n; } } int main(){ optimizar_io solve(); return 0; }
true
d7737b78c9552fa1bd014a2cc37df05ec0f0b98a
C++
rakshaa2000/LeetCode
/0001_Two_Sum/0001_Two_Sum.cpp
UTF-8
609
3.3125
3
[ "MIT" ]
permissive
class TwoSum { private: unordered_map<int, int> nums; public: //O(1) add void add(int number) { nums[number]++; } //O(n) find bool find(int value) { int one, two; for(auto it = nums.begin(); it != nums.end(); it++){ one = it->first; two = value - one; if ( (one == two && it->second > 1) || (one != two && nums.find(two) != nums.end() ) ){ return true; } } return false; } };
true
314dd3dbd23473f35e4b74831abc50b6159d4395
C++
emoy-kim/GimbalLock
/source/Shader.cpp
UTF-8
3,662
2.765625
3
[]
no_license
#include "Shader.h" ShaderGL::ShaderGL() : ShaderProgram( 0 ) { } ShaderGL::~ShaderGL() { if (ShaderProgram != 0) glDeleteProgram( ShaderProgram ); } void ShaderGL::readShaderFile(std::string& shader_contents, const char* shader_path) { std::ifstream file( shader_path, std::ios::in ); if (!file.is_open()) { std::cerr << "Cannot open shader file: " << shader_path << "\n"; return; } std::string line; while (!file.eof()) { getline( file, line ); shader_contents.append( line + "\n" ); } file.close(); } std::string ShaderGL::getShaderTypeString(GLenum shader_type) { switch (shader_type) { case GL_VERTEX_SHADER: return "Vertex Shader"; case GL_FRAGMENT_SHADER: return "Fragment Shader"; default: return ""; } } bool ShaderGL::checkCompileError(GLenum shader_type, const GLuint& shader) { GLint compiled = 0; glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled ); if (compiled == GL_FALSE) { GLint max_length = 0; glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &max_length ); std::cerr << " ======= " << getShaderTypeString( shader_type ) << " log ======= \n"; std::vector<GLchar> error_log(max_length); glGetShaderInfoLog( shader, max_length, &max_length, &error_log[0] ); for (const auto& c : error_log) std::cerr << c; std::cerr << "\n"; glDeleteShader( shader ); } return compiled == GL_TRUE; } GLuint ShaderGL::getCompiledShader(GLenum shader_type, const char* shader_path) { if (shader_path == nullptr) return 0; std::string shader_contents; readShaderFile( shader_contents, shader_path ); const GLuint shader = glCreateShader( shader_type ); const char* shader_source = shader_contents.c_str(); glShaderSource( shader, 1, &shader_source, nullptr ); glCompileShader( shader ); if (!checkCompileError( shader_type, shader )) { std::cerr << "Could not compile shader\n"; return 0; } return shader; } void ShaderGL::setShader(const char* vertex_shader_path, const char* fragment_shader_path) { const GLuint vertex_shader = getCompiledShader( GL_VERTEX_SHADER, vertex_shader_path ); const GLuint fragment_shader = getCompiledShader( GL_FRAGMENT_SHADER, fragment_shader_path ); ShaderProgram = glCreateProgram(); glAttachShader( ShaderProgram, vertex_shader ); glAttachShader( ShaderProgram, fragment_shader ); glLinkProgram( ShaderProgram ); glDeleteShader( vertex_shader ); glDeleteShader( fragment_shader ); } void ShaderGL::setBasicTransformationUniforms() { Location.World = glGetUniformLocation( ShaderProgram, "WorldMatrix" ); Location.View = glGetUniformLocation( ShaderProgram, "ViewMatrix" ); Location.Projection = glGetUniformLocation( ShaderProgram, "ProjectionMatrix" ); Location.ModelViewProjection = glGetUniformLocation( ShaderProgram, "ModelViewProjectionMatrix" ); Location.Color = glGetUniformLocation( ShaderProgram, "Color" ); } void ShaderGL::transferBasicTransformationUniforms(const glm::mat4& to_world, const CameraGL* camera, const glm::vec4& color) const { const glm::mat4 view = camera->getViewMatrix(); const glm::mat4 projection = camera->getProjectionMatrix(); const glm::mat4 model_view_projection = projection * view * to_world; glUniformMatrix4fv( Location.World, 1, GL_FALSE, &to_world[0][0] ); glUniformMatrix4fv( Location.View, 1, GL_FALSE, &view[0][0] ); glUniformMatrix4fv( Location.Projection, 1, GL_FALSE, &projection[0][0] ); glUniformMatrix4fv( Location.ModelViewProjection, 1, GL_FALSE, &model_view_projection[0][0] ); glUniform4fv( Location.Color, 1, &color[0] ); }
true
89571992bf83760995b215f44c80ced8a83a8d13
C++
a21lfa/hmwk
/prog_2308/main.cpp
UTF-8
327
2.96875
3
[]
no_license
#include <iostream> using namespace std; int main(){ int fahr, celsius; int step, lower, upper; lower=0; upper=30; step=20; fahr=lower; while(fahr<=upper){ celsius =5*(fahr-32)/9; cout << fahr<<"\t"<<celsius<<endl; fahr = fahr+step; } return 0; }
true
9a874cbfb4982b547df0dbaeb4e933f2123eb738
C++
ziszis/zg
/no-keys.h
UTF-8
935
2.734375
3
[ "MIT" ]
permissive
#ifndef GITHUB_ZISZIS_ZG_NO_KEY_INCLUDED #define GITHUB_ZISZIS_ZG_NO_KEY_INCLUDED #include <optional> #include "table.h" template <class Aggregator> class NoKeyTable : public Table { public: NoKeyTable(Aggregator aggregator, std::unique_ptr<OutputTable> output) : aggregator_(std::move(aggregator)), output_(std::move(output)) {} void PushRow(const InputRow& row) override { if (value_) { aggregator_.Update(row, *value_); } else { value_ = aggregator_.Init(row); } } void Finish() override { if (value_) { aggregator_.Print(*value_, *output_); output_->EndLine(); value_.reset(); aggregator_.Reset(); output_->Finish(); } else { Fail("No data to aggregate"); } } private: std::optional<typename Aggregator::State> value_; Aggregator aggregator_; std::unique_ptr<OutputTable> output_; }; #endif // GITHUB_ZISZIS_ZG_NO_KEY_INCLUDED
true
a1e22f7e7aa1b34ed65932d9310f55711ff14fe9
C++
npetersen2/airis
/src/sqlitedb.h
UTF-8
1,546
3.171875
3
[]
no_license
#ifndef SQLITEDB_H #define SQLITEDB_H #include <iostream> #include <string> #include <sqlite3.h> class SQLiteDB { public: SQLiteDB(const std::string &dbFile) { this->dbFile = dbFile; open_db(); } ~SQLiteDB() { close_db(); } void close() { close_db(); } void beginTransaction() { sqlite3_exec(db, "BEGIN TRANSACTION;", NULL, NULL, NULL); } void endTransaction() { sqlite3_exec(db, "END TRANSACTION;", NULL, NULL, NULL); } void vacuum() { std::cout << "Compressing database file: " << dbFile << "..." << std::endl; sqlite3_exec(db, "VACUUM;", NULL, NULL, NULL); } void rollback() { std::cout << "Rolling back database file: " << dbFile << "..." << std::endl; sqlite3_exec(db, "ROLLBACK;", NULL, NULL, NULL); } private: std::string dbFile; void open_db() { if (sqlite3_open(dbFile.c_str(), &(this->db))) { std::cout << "Error opening database '" << dbFile << "'... " << sqlite3_errmsg(this->db) << std::endl; exit(0); } exec_query("PRAGMA journal_mode=WAL", nullptr, nullptr); } void close_db() { sqlite3_close(this->db); } protected: sqlite3 *db; void exec_query(const std::string sql, int (*callback)(void*, int, char**, char**), void *ptr) { if (sqlite3_exec(this->db, sql.c_str(), callback, ptr, nullptr) != SQLITE_OK) { std::cout << "Error executing SQL command: " << sqlite3_errmsg(this->db) << std::endl; std::cout << "SQL statement:" << std::endl; std::cout << sql << std::endl; close_db(); exit(0); } } }; #endif // SQLITEDB_H
true
f68c5c04640f1a77b6b771d27eee13616502df72
C++
1im2/dev_libs
/cpp/util_facker.hpp
UTF-8
2,569
2.734375
3
[]
no_license
#ifndef __LIME_UTIL_FAKER_HPP__ #define __LIME_UTIL_FAKER_HPP__ #include <iostream> #include <random> #include <map> #include <vector> namespace lime { class someGenerate { public: static const std::string basestr; static void generateString(std::string & strGen_, long wantLength_) { std::random_device rd; std::uniform_int_distribution<long> dist(0, someGenerate::basestr.size()-1); strGen_.clear(); for (long i = 0 ; i < wantLength_; i++ ) { strGen_ += basestr.at(dist(rd)); } } static std::string generateString(long wantLength_) { std::string strGen; generateString(strGen, wantLength_); return strGen; } static bool generateRandomMap( std::map<std::string, std::string> &rltMap_, long genCount_, long genStrLength_, long keyLength = 0, long keyBeginIndex = 0, std::vector<std::string> * vecKeyPrefix = NULL ) { std::string key; std::string str_index; long key_id = 0; long len = 0; static unsigned long inc = 0; std::random_device rd; std::uniform_int_distribution<long> dist(0, (vecKeyPrefix == NULL ? 1 : vecKeyPrefix->size())); if (keyLength) { for (long l = 0; l < genCount_; l++) { if (vecKeyPrefix && 0 < vecKeyPrefix->size()) { key_id = (inc++); key_id += dist(rd); key_id %= (*vecKeyPrefix).size(); key = vecKeyPrefix->at(key_id); } else { key.clear(); } str_index = std::to_string(l+keyBeginIndex); len = keyLength - str_index.size(); if (len > (long)key.size()) { for (long i = len - key.size(); i > 0; i--) { key += '0'; } } key += str_index; rltMap_[key] = someGenerate::generateString(genStrLength_); // std::cout << key << "] " << std::endl; } } else { for (long l = 0; l < genCount_; l++) { if (vecKeyPrefix) { key_id = (inc++); key_id += dist(rd); key_id %= (*vecKeyPrefix).size(); key = vecKeyPrefix->at(key_id); } else { key.clear(); } key += std::to_string(l+keyBeginIndex); rltMap_[key] = someGenerate::generateString(genStrLength_); // std::cout << key << "] " << std::endl; } } return true; } }; } #endif
true
f99b497e6567b77b6e67e71f473f64876275fab6
C++
EnoahNetzach/fourFs
/View/terminalinterface.cpp
UTF-8
3,475
2.703125
3
[]
no_license
///* // * terminal.cpp // * // * Created on: Apr 5, 2013 // * Author: Enoah Netzach // */ // //#include "terminalinterface.h" // //#include <iostream> // //#include "../logger.h" //#include "../Logic/map.h" //#include "../Logic/matrix.h" //#include "../Logic/pixel.h" // //using namespace fourFs; //using namespace logic; //using namespace view; // //TerminalInterface::TerminalInterface() // : Interface_base("terminal") //{ //} // //TerminalInterface::~TerminalInterface() //{ //} // //void TerminalInterface::initializeImpl() //{ // m_good = std::cout.good(); //} // //void TerminalInterface::showImpl(sharedConstMatrix matrix) //{ // m_matrix = matrix; // // if (good()) // { // m_loopThread = boost::thread(& TerminalInterface::runLoop, this); // } //} // //void TerminalInterface::runLoop() //{ // bool shouldReturn = false; // while (! shouldReturn) // { // std::cout << "[Term interface] What would you like to show? (Map, Units, Quit) " << std::flush; // std::string input; // // do // { // std::cin >> input; // // if (input == "m") // { // showMap(m_matrix.lock()); // } // else if (input == "u") // { // showUnits(m_matrix.lock()); // } // else if (input == "q") // { // shouldReturn = true; // break; // } // } while (std::cin.peek() != '\n'); // // std::cin.clear(); // } //} // //void TerminalInterface::showMap(sharedConstMatrix matrix) //{ // std::cout << "_MAP" << std::string(matrix->width() * 2 - 2, '_') << "\n"; // for (unsigned y = 0; y < matrix->height(); y++) // { // std::cout << "|"; // for (unsigned x = 0; x < matrix->width(); x++) // { // sharedConstPixel pixel = matrix->pixelAtPosition(x, y); // double height = pixel->height(); // // char c; // switch(int(height * 10)) // { // case 0: // c = ' '; // break; // case 1: // c = '.'; // break; // case 2: // c = ':'; // break; // case 3: // c = '*'; // break; // case 4: // c = 'o'; // break; // case 5: // c = 'g'; // break; // case 6: // c = '&'; // break; // case 7: // c = '8'; // break; // case 8: // c = '#'; // break; // default: // c = '@'; // break; // } // std::cout << c << c; // } // std::cout << "|" << std::endl; // } // std::cout << std::string(matrix->width() * 2 + 2, '^') << std::endl; //} // //void TerminalInterface::showUnits(sharedConstMatrix matrix) //{ // std::cout << "_UNITS" << std::string(matrix->width() * 2 - 4, '_') << "\n"; // for (unsigned y = 0; y < matrix->height(); y++) // { // std::cout << "|"; // for (unsigned x = 0; x < matrix->width(); x++) // { // sharedConstPixel pixel = matrix->pixelAtPosition(x, y); // // char c; // if (pixel->isUnitsEmpty()) // { // c = '.'; // } // else // { // c = 48 + pixel->nOfUnits(); // } // std::cout << " " << c; // } // std::cout << "|\n"; // } // std::cout << std::string(matrix->width() * 2 + 2, '^') << std::endl; //}
true
972e91c31185845ceee3a453e1b22e3e8f73bf71
C++
TNorbury/Chess-OO
/Chess/Rook.cpp
UTF-8
1,751
3.53125
4
[]
no_license
/** * 1851366 * Assignment 9 * 2017-04-22 */ #include "Rook.h" #include "Square.h" /** * Rook implementation */ Rook::Rook(Square* location, string color) : RestrictedPiece(location, color) { } int Rook::getValue() { // Value for chess pieces taken from http://chess.stackexchange.com/a/4218 return 5; } bool Rook::canMoveTo(Square* location) { bool pathClear = false; bool canMoveTo = false; // Determine if the destination square is to the side, or above/below the // current piece // If the piece and destination square are on the same file, then they are // above/below one another if (_location->getFile() == location->getFile()) { pathClear = Board::getInstance()->isClearFile(_location, location); } // Otherwise, if the piece and destination square are on the same rank, // then they are to the side of one another else if (_location->getRank() == location->getRank()) { pathClear = Board::getInstance()->isClearRank(_location, location); } // If neither of those are true, then we can't move to the given square // If the rank or file is clear, then check if this piece can actually // move onto the destination square if (pathClear) { // If the square isn't occupied, or it's occupied by an opponent's // piece, then we can move there canMoveTo = (!location->isOccupied()) || (location->getOccupant()->getColor() != _color); } return canMoveTo; } void Rook::display(ostream & os) { // Print out something different depending on the color of the piece if (_color == WHITE_COLOR) { os << WHITE_ROOK; } else { os << BLACK_ROOK; } }
true
4f64d810997654ad33770a035cd7d528a3d839fb
C++
icc-tips/flutter_native_channel
/android/src/main/jni/finalizer.h
UTF-8
1,514
2.625
3
[ "Apache-2.0" ]
permissive
/** * Copyright 2020 Jason C.H <ctrysbita@outlook.com> * * 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. */ #pragma once #include <jni.h> #include <unordered_map> /** * @brief Finalizer that handling the lifecycle of object transmit using shared memory. */ class Finalizer { private: static std::unordered_map<uint8_t *, jobject> global_references_; public: /** * @brief Associate the inner pointer with global reference of java object. * * @param ptr The inner pointer of object. (e.g. java.nio.DirectByteBuffer) * @param ref The global reference of object. */ static inline void AssociatePointerWithGlobalReference(uint8_t *ptr, jobject ref) { global_references_[ptr] = ref; } /** * Release the global reference of jobject associated with pointer. * * @param ptr Inner pointer of object. */ static void ReleaseGlobalReferenceByPointer(uint8_t *ptr); /** * @brief Finalizer for dart VM. */ static void DartFinalizer(void *isolate_callback_data, void *peer); };
true
817315b1b30d6e3ea16a4f93f5455784f9cd0d86
C++
djwide/proofOfLangCompetency
/EEProgramming/CompArchitecture/Project 5/sketch_apr28a/sketch_apr28a.ino
UTF-8
1,768
3.046875
3
[]
no_license
/* Temperature Sensor sketch Arthor: MAJ Abbott-McCune Date: 13 Mar 2015 Referances: Ladyada TMP36 */ // TO DO: #include <Wire.h> #define aref_voltage 3.3 // we tie 3.3V to ARef and measure it with a multimeter! //TMP36 Pin Variables int tempPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to float temperatureF = 0; //the resolution is 10 mV / degree centigrade with a //500 mV offset to allow for negative temperatures int tempReading; // the analog reading from the sensor void setup(void) { // TO DO: Wire.begin(2); Wire.onReceive(receiveEvent); Wire.onRequest(requestEvent); // We'll send debugging information via the Serial monitor Serial.begin(9600); // If you want to set the aref to something other than 5v analogReference(EXTERNAL); } void requestEvent(){ Wire.write((int)temperatureF); } void receiveEvent(int howMany){ while(1<Wire.available()){ char c = Wire.read(); Serial.print(c); } int x= Wire.read(); Serial.println(x); } void loop(void) { tempReading = analogRead(tempPin); //Serial.print("Temp reading = "); //Serial.print(tempReading); // the raw analog reading // converting that reading to voltage, which is based off the reference voltage float voltage = tempReading * aref_voltage; voltage /= 1024.0; // print out the voltage //Serial.print(" - "); //Serial.print(voltage); Serial.println(" volts"); // now print out the temperature float temperatureC = (voltage - 0.5) * 100 ; //converting from 10 mv per degree wit 500 mV offset //to degrees ((volatge - 500mV) times 100) //Serial.print(temperatureC); Serial.println(" degrees C"); // now convert to Fahrenheight temperatureF = (temperatureC * 9.0 / 5.0) + 32.0; //Serial.print(temperatureF); Serial.println(" degrees F"); delay(1000); } // TO DO:
true
67b2e5fb409d8b26995d0e32f0cb9d71a30e557d
C++
zapw/miscellaneous
/asd1.cpp
UTF-8
1,892
4
4
[]
no_license
// C++ program without declaring the // move constructor #include <iostream> #include <vector> using namespace std; // Move Class class Move { private: // Declaring the raw pointer as // the data member of the class int* data; public: // Constructor Move(int d) { // Declare object in the heap data = new int; *data = d; cout << "Constructor is called for " << d << endl; }; // Copy Constructor to delegated // Copy constructor Move(const Move& source) : Move{ *source.data } { // Copying constructor copying // the data by making deep copy cout << "Copy Constructor is called - " << "Deep copy for " << *source.data << endl; } // Destructor ~Move() { if (data != nullptr) // If the pointer is not // pointing to nullptr cout << "Destructor is called for " << *data << endl; else // If the pointer is // pointing to nullptr cout << "Destructor is called" << " for nullptr" << endl; // Free the memory assigned to // data member of the object delete data; } }; template<class T> struct A { A(T,T){ }; }; template <typename ReturnType, typename ArgumentType> ReturnType Foo(ArgumentType arg){ return 'H';} //template <typename ArgumentType> //std::string Foo(ArgumentType arg) { return "Return1"; } // Driver Code int main() { const int& rca2 = 5; std::cout << Foo<char>('c'); // Create vector of Move Class // int&& rra = 5; // rca2 = 3; vector<Move> vec; // Inserting object of Move class vec.push_back(Move{ 10 }); //vec.push_back(Move{ 20 }); // A<int>{1, 2}; return 0; }
true
796c770a14d931e0cc3843d2f3b393e496bc1d2c
C++
MaxGGx/Algoritmos-2020-2
/Tarea 1/Iñaki/Tarea1/cqueue.h
UTF-8
937
3.390625
3
[]
no_license
#ifndef QUEUE_H #define QUEUE_H #define SIZE 80 /* Clase cqueue: Cola circular que almacena par de coordenadas (x, y) basada en arreglo de largo SIZE (redefinible en casos de prueba grandes) Private: int front: posicion de cabeza de la cola int rear: posicion de fin de la cola int **items: arreglo donde se guardan las coordenadas Public: cqueue(): constructor de la clase, pide memoria en el heap para arreglo items (SIZE * 2) ~cqueue(): destructor de la clase, libera la memoria pedida bool isFull(): chequea si la cola esta llena bool isEmpty(): cheque si la cola esta vacia void enQueue(int, int): recibe la coordenadas y las encola void deQueue(int *): recibe un arreglo de 2 enteros y guarda las coordenadas desencoladas */ class cqueue { private: int front; int rear; int **items; public: cqueue(); ~cqueue(); bool isFull(); bool isEmpty(); void enQueue(int, int); void deQueue(int *); }; #endif
true
6f2adcda5d9ff4103665ed72a1658bddf2092e89
C++
fjimenez81/PISCINA_CPP
/MODULE_00/ex01/main.cpp
UTF-8
2,132
3.03125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fjimenez <fjimenez@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/04 11:28:39 by fjimenez #+# #+# */ /* Updated: 2020/11/09 11:29:11 by fjimenez ### ########.fr */ /* */ /* ************************************************************************** */ #include "Contact.hpp" void add(Contact *contact) { std::string info[11] = {"First name: ", "Last name: ", "Nickname: ", "Login: ", "Postal address: ", "Email address: ", "Phone number: ", "Birthday date: ", "Favourite meal: ", "Underwear color: ", "Darkest secret: "}; std::string line; std::cout << "Adding a new contact..." << std::endl; for (int i = 0; i < 11; i++) { std::cout << info[i] << std::endl; getline(std::cin, line); contact->add_contact(i, line); } std::cout << "Contact added, you have room for "; } int main() { int i; std::string line; Contact contacts[8]; std::cout << "Hello!! This is your little phonebook" << std::endl; i = 0; while (1) { std::cout << "Introduce: ADD, SEARCH, EXIT" << std::endl; getline(std::cin, line); if (!line.compare("EXIT")) { std::cout << "Exit program..." << std::endl; return (0); } else if (!line.compare("ADD")) { if (i == 8) std::cout << "Your phonebook is full!" << std::endl; else { add(&contacts[i]); std::cout << (7 - i++) << " more contacts" << std::endl; } } else if (!line.compare("SEARCH")) { search(contacts, i); std::cout << "End of search\n" << std::endl; } else std::cout << "ERROR: "; } }
true
f47eb5e675fe49a48f2ab155b692f61272cf4d3e
C++
u35s/epoll
/src/base/conn.h
UTF-8
482
2.578125
3
[]
no_license
#ifndef CONN_H #define CONN_H #include <netinet/in.h> #include <string> class Conn { public: Conn(const int sockfd); ~Conn(); int write(const void *data,int len); int read(void *data,int len); int sockfd(); void close(); std::string local_addr(); std::string remote_addr(); private: sockaddr_in remote_addr_; sockaddr_in local_addr_; std::string remote_addr_str_; std::string local_addr_str_; int sockfd_; }; #endif
true
a1aef8cb5b810e57810be80e61ce3ad05b63c684
C++
CarstenZarbock/HotlineMiamiTemplate
/Source/WhiteNoise/public/WNStageHandle.h
UTF-8
2,015
2.53125
3
[ "MIT" ]
permissive
// Copyright 2016 Carsten Zarbock / Rebound-Software #include "WNNPC.h" #include "WNWeapon.h" #include "WNStageHandle.generated.h" #pragma once /** * */ struct FSaveGameArchive : public FObjectAndNameAsStringProxyArchive { FSaveGameArchive(FArchive& InInnerArchive) : FObjectAndNameAsStringProxyArchive(InInnerArchive, true) { ArIsSaveGame = true; } }; /** * Serialization of each actor, SaveGame properties are used */ USTRUCT() struct FActorSaveData { GENERATED_BODY() FString ActorClass; FName ActorName; FTransform ActorTransform; TArray<uint8> ActorData; /** Reference to existing actor for clean up purpose */ AActor* LastActor; friend FArchive& operator<<(FArchive& Ar, FActorSaveData& ActorData) { Ar << ActorData.ActorClass; Ar << ActorData.ActorName; Ar << ActorData.ActorTransform; Ar << ActorData.ActorData; Ar << ActorData.LastActor; return Ar; } }; /** Object content for each stage */ struct FStage { int32 StageID; TArray<FActorSaveData> SpawnEntity; FStage(int32 StageID) { this->StageID = StageID; } }; class WHITENOISE_API StageHandle { private: /** Contains map placed actor objects of old and the current stage */ TArray<FStage> Stages; /** Checks if given Stage ID does exist, creates one if it doesnt. Returns Array Index of the Stage */ int32 CheckStageArraySize(int32 StageID); /** Contains all dynamic spawned actors while playing a stage, excludes actors placed on map. */ TArray<AActor*> GarbageActors; /** Cleans up GarbageActors on the current stage */ void EraseGarbage(); public: /** */ StageHandle(); /** */ ~StageHandle(); /** Adds an actor to the given stage */ bool Register(AActor* TargetActor, int32 StageID, bool bIsGarbage); /** Spawns all registered actors for this stage */ void RespawnEntities(UWorld* World, int32 StageID); /** Destroys all registered actors for this stage */ void EraseStage(UWorld* World, int32 StageID); /** Called by GameMode when next stage is starting */ void IncreaseStage(); };
true
6f17456be1f617aa3cc7e23178cfcbf6edf50c93
C++
craft-coder/Softwareentwicklung-2021
/test/Vec3Tests.cpp
UTF-8
433
2.625
3
[ "MIT" ]
permissive
#include "gtest/gtest.h" #include "Vec3.h" TEST(Vec3, DefaultConstructor_XisZero) { raytracer::Vec3 vec{}; double x = vec.x(); EXPECT_NEAR(x, 0.0, 0.00001); } TEST(Vec3, DefaultConstructor_YisZero) { raytracer::Vec3 vec{}; double y = vec.y(); EXPECT_NEAR(y, 0.0, 0.00001); } TEST(Vec3, DefaultConstructor_ZisZero) { raytracer::Vec3 vec{}; double z = vec.z(); EXPECT_NEAR(z, 0.0, 0.00001); }
true
80fc2e2df703cdebe0f4f16f5e2db3c5a0f50f81
C++
AlexShii1995/cpp-primer-plus
/chapter4/tmp.cpp
UTF-8
575
3.03125
3
[]
no_license
#include<iostream> #include<typeinfo> #include<stdio.h> using namespace std; int main() { int i = 6; int c[3] = {1,2,3}; int * k = c; cout << "This is C!" << k[0] << endl; char b[5]; int * j = &i; //b[0] = i + '0'; //cout << "This is: " << b[0] << endl; //cout << "It\'s type is: " << typeid(i).name() << endl; //printf("%d\n",~i); int ** p = &j; cout << "**p = " << **p << endl; cout << "*p = " << *p << endl; cout << "p = " << p << endl; cout << "&i = " << &i << endl; cout << "&p = " << &p << endl; cout << (int *) "Home of the jolly bytes"; return 0; }
true
5d6c157286e3c48cbd78739740c9544c3281e960
C++
kkobylin/ZPR
/chess_engine/test/FigureLogicTest.cc
UTF-8
27,578
3.21875
3
[]
no_license
/** * @file FigureLogicTest.cc * @author Krzysztof Kobyliński (k.kobylinski98@gmail.com) * @brief Boost auto test, testing possible moves of each Piece * in many cases * @version 1.0 * @date 2020-01-15 */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE ChessTest #include <boost/test/included/unit_test.hpp> #include "../lib/Pawn.h" #include "../lib/Bishop.h" #include <memory> #include "../lib/Piece.h" #include "../lib/BaseBoard.h" #include "../lib/Knight.h" #include "../lib/Queen.h" #include "../lib/Rook.h" #include "../lib/King.h" #include <vector> #include <algorithm> /** * Function comparing vector of correct possible positions * with positions from GetPossibleMoves method */ void compareVectors(std::vector<Position> pos, std::vector<std::string> correct_positions) { std::vector <std::string> positions; for(auto p : pos){ positions.push_back(p.toString()); } std::sort(positions.begin(), positions.end()); std::sort(correct_positions.begin(), correct_positions.end()); BOOST_CHECK(positions == correct_positions); } BOOST_AUTO_TEST_CASE(PawnCase) { /* --------------------------------------------------------------- Pawn -----------------------------------------------------------------------------------------------*/ /* 1st case - beginning of the game */ Piece *p = new Pawn(0, 1, WHITE); std::shared_ptr<BaseBoard> board_ptr(new BaseBoard(INITIAL_BOARD)); auto pos = p->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 2); std::vector<std::string> correct_positions; correct_positions.push_back("02"); correct_positions.push_back("03"); compareVectors(pos, correct_positions); std::vector<std::vector<std::string>> case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "WP", "BP", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete p; p = new Pawn(2, 3, WHITE); pos = p->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 0); case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "WP", "NN", "BP", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete p; p = new Pawn(2, 6, BLACK); pos = p->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 1); correct_positions.clear(); correct_positions.push_back("25"); compareVectors(pos, correct_positions); case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "WP", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "BP", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "WP", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete p; p = new Pawn(3, 5, BLACK); p->setMoved(true); pos = p->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 3); correct_positions.clear(); correct_positions.push_back("24"); correct_positions.push_back("34"); correct_positions.push_back("44"); compareVectors(pos, correct_positions); case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "WP", "BP", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "BP", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete p; p = new Pawn(0, 2, WHITE); p->setMoved(true); pos = p->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 1); correct_positions.clear(); correct_positions.push_back("13"); compareVectors(pos, correct_positions); case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "WP", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "BP", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "NN", "WP", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete p; p = new Pawn(1, 6, BLACK); pos = p->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 4); correct_positions.clear(); correct_positions.push_back("05"); correct_positions.push_back("15"); correct_positions.push_back("14"); correct_positions.push_back("25"); compareVectors(pos, correct_positions); case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "WP", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "WP"}, /* B */ {"NN", "NN", "NN", "NN", "NN", "WP", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete p; p = new Pawn(1, 7, WHITE); pos = p->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 0); //todo /* 7th case - King Defending - avoid King from check*/ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "BP", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "WK", "WP", "NN", "NN", "NN", "BR"}, /* D */ {"NN", "NN", "NN", "NN", "BP", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete p; p = new Pawn(3, 3, WHITE); p->setMoved(true); pos = p->getPossibleMoves(board_ptr); compareVectors(pos, correct_positions); /* 8th case - King Defending - stop king checking*/ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "BP", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "WP", "BQ", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "BB", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "WK", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete p; p = new Pawn(2, 2, WHITE); pos = p->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 1); correct_positions.clear(); correct_positions.push_back("33"); compareVectors(pos, correct_positions); } BOOST_AUTO_TEST_CASE(BishopCase) { /* --------------------------------------------------------------- Bishop -----------------------------------------------------------------------------------------------*/ /* 1st case - beginning of the game */ Piece *b = new Bishop(2, 0, WHITE); std::shared_ptr<BaseBoard> board_ptr(new BaseBoard(INITIAL_BOARD)); board_ptr.reset(new BaseBoard(INITIAL_BOARD)); auto pos = b->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 0); /* 2nd case */ std::vector<std::vector<std::string>> case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "BB", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete b; b = new Bishop(3, 3, BLACK); pos = b->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 13); /* 3rd case */ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"WB", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete b; b = new Bishop(7, 0, WHITE); pos = b->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 7); /* 4th case */ case_board = { /* 1 2 3 4 5 6 7 8 */ {"WR", "NN", "BR", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "WB", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"WR", "NN", "BR", "NN", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete b; b = new Bishop(1, 1, WHITE); pos = b->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 2); std::vector<std::string> correctPositions; correctPositions.clear(); correctPositions.push_back("02"); correctPositions.push_back("22"); compareVectors(pos, correctPositions); /* 5th case */ case_board = { /* 1 2 3 4 5 6 7 8 */ {"BR", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "WR", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "WR"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "WB", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "BR", "NN", "WR"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete b; b = new Bishop(6, 6, WHITE); pos = b->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 5); /* 6th case - King Defending - avoid King from check*/ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "BK", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "BB", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "WQ", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete b; b = new Bishop(2, 3, BLACK); pos = b->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 1); correctPositions.clear(); correctPositions.push_back("34"); compareVectors(pos, correctPositions); /* 6th case - King Defending - stop king checking*/ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "WK", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "WB", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "BB", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete b; b = new Bishop(3, 2, WHITE); pos = b->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 1); correctPositions.clear(); correctPositions.push_back("23"); compareVectors(pos, correctPositions); } BOOST_AUTO_TEST_CASE(KnightCase) { /* --------------------------------------------------------------- Knight -----------------------------------------------------------------------------------------------*/ /* 1st case - beginning of the game */ Piece *n = new Knight(1, 0, WHITE); std::shared_ptr<BaseBoard> board_ptr(new BaseBoard(INITIAL_BOARD)); board_ptr.reset(new BaseBoard(INITIAL_BOARD)); auto pos = n->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 2); /* 2nd case */ std::vector<std::vector<std::string>> case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "WP", "BP", "WP", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "BP", "BN", "BP", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "WP", "BP", "WP", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete n; n = new Knight(3, 3, BLACK); pos = n->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 8); /* 3rd case */ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"BR", "NN", "BN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "BR", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "WN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete n; n = new Knight(7, 1, WHITE); pos = n->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 3); std::vector<std::string> correctPositions; correctPositions.clear(); correctPositions.push_back("50"); correctPositions.push_back("52"); correctPositions.push_back("63"); compareVectors(pos, correctPositions); } BOOST_AUTO_TEST_CASE(QueenCase) { /* --------------------------------------------------------------- Queen -----------------------------------------------------------------------------------------------*/ /* 1st case - beginning of the game */ Piece *q = new Queen(3, 0, WHITE); std::shared_ptr<BaseBoard> board_ptr(new BaseBoard(INITIAL_BOARD)); board_ptr.reset(new BaseBoard(INITIAL_BOARD)); auto pos = q->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 0); /* 2nd case */ std::vector<std::vector<std::string>> case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "BP", "BP", "BP", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "BP", "WQ", "BP", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "BP", "BP", "BP", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete q; q = new Queen(3, 3, WHITE); pos = q->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 8); /* 3rd case */ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "BP", "NN", "BQ", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "BP", "NN", "BP", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete q; q = new Queen(0, 6, BLACK); pos = q->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 5); } BOOST_AUTO_TEST_CASE(RookCase) { /* --------------------------------------------------------------- Rook -----------------------------------------------------------------------------------------------*/ /* 1st case - beginning of the game */ Piece *r = new Rook(0, 0, WHITE); std::shared_ptr<BaseBoard> board_ptr(new BaseBoard(INITIAL_BOARD)); board_ptr.reset(new BaseBoard(INITIAL_BOARD)); auto pos = r->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 0); /* 2nd case */ std::vector<std::vector<std::string>> case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "BR", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete r; r = new Rook(3, 3, BLACK); pos = r->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 14); /* 3rd case */ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* B */ {"WR", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* C */ {"BR", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"WR", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete r; r = new Rook(3, 0, BLACK); pos = r->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 9); /* 4th case */ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN", "NN", "NN", "NN", "NN", "NN", "WP", "WR"}, /* A */ {"NN", "NN", "NN", "NN", "NN", "NN", "BR", "WP"}, /* B */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* C */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* D */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* E */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* F */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"}, /* G */ {"NN", "NN", "NN", "NN", "NN", "NN", "NN", "NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete r; r = new Rook(0, 7, WHITE); pos = r->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 0); } BOOST_AUTO_TEST_CASE(KingCase) { /* --------------------------------------------------------------- King -----------------------------------------------------------------------------------------------*/ /* 1st case - beginning of the game */ Piece *k = new King(4, 0, WHITE); std::shared_ptr<BaseBoard> board_ptr(new BaseBoard(INITIAL_BOARD)); board_ptr.reset(new BaseBoard(INITIAL_BOARD)); auto pos = k->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 0); /* 2nd case*/ std::vector<std::vector<std::string>> case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN","NN","NN","NN","NN","NN","NN","WK"}, /* A */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* B */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* C */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* D */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* E */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* F */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* G */ {"NN","NN","NN","NN","NN","NN","NN","NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete k; k = new King(0, 7, WHITE); pos = k->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 3); /* 3rd case*/ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN","NN","BR","NN","BR","NN","NN","NN"}, /* A */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* B */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* C */ {"NN","NN","NN","WK","NN","NN","NN","NN"}, /* D */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* E */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* F */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* G */ {"NN","NN","NN","NN","NN","NN","NN","NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete k; k = new King(3, 3, WHITE); pos = k->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 2); /* 4th case*/ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN","NN","BR","NN","BR","NN","NN","NN"}, /* A */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* B */ {"NN","NN","NN","NN","NN","NN","BR","NN"}, /* C */ {"NN","NN","NN","WK","NN","NN","NN","NN"}, /* D */ {"NN","NN","NN","NN","NN","NN","BR","NN"}, /* E */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* F */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* G */ {"NN","NN","NN","NN","NN","NN","NN","NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete k; k = new King(3, 3, WHITE); pos = k->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 0); /* 5th case*/ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* A */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* B */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* C */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* D */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* E */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* F */ {"NN","NN","BP","WP","BP","NN","NN","NN"}, /* G */ {"NN","NN","NN","BK","NN","NN","NN","WR"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete k; k = new King(7, 3, BLACK); pos = k->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 1); std::vector<std::string> correctPositions; correctPositions.clear(); correctPositions.push_back("63"); compareVectors(pos, correctPositions); /* 6th case*/ case_board = { /* 1 2 3 4 5 6 7 8 */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* A */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* B */ {"NN","NN","NN","NN","BQ","BB","NN","NN"}, /* C */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* D */ {"NN","NN","NN","WK","NN","NN","NN","NN"}, /* E */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* F */ {"NN","NN","NN","NN","NN","NN","NN","NN"}, /* G */ {"NN","NN","NN","NN","NN","NN","NN","NN"} /* H */ }; board_ptr.reset(new BaseBoard(case_board)); delete k; k = new King(4, 3, WHITE); pos = k->getPossibleMoves(board_ptr); BOOST_CHECK(pos.size() == 2); correctPositions.clear(); correctPositions.push_back("32"); correctPositions.push_back("53"); compareVectors(pos, correctPositions); }
true
9e7cc12856c5f8668e100e8ac4371d97db37f82d
C++
ashish25-bit/data-structure-algorithms
/DP/Minimum-Del-Ins-To-Form-B.cc
UTF-8
1,469
3.09375
3
[]
no_license
// https://practice.geeksforgeeks.org/problems/minimum-number-of-deletions-and-insertions0209/1/ #include <bits/stdc++.h> using namespace std; auto minOperations(string str1, string str2) { int n = str1.length(); int m = str2.length(); int t[m+1][n+1]; for (int i=0; i <= m; i++) { for (int j=0; j <= n; j++) { if (i == 0 || j == 0) t[i][j] = 0; else if (str2[i-1] == str1[j-1]) t[i][j] = 1 + t[i-1][j-1]; else t[i][j] = max(t[i-1][j], t[i][j-1]); } } string res = ""; int row = m; int col = n; while (row > 0 && col > 0) { if (str2[row-1] == str1[col-1]) { res = str1[col-1] + res; row = row - 1; col = col - 1; } else { if (t[row-1][col] >= t[row][col-1]) row = row - 1; else col = col - 1; } } int deletions = m - res.length(); int insertions = 0; int index1 = 0; int index2 = 0; while (index1 < n && index2 < res.length()) { if (str1[index1] == res[index2]) { index1++; index2++; } else { insertions++; index1++; } } if (index2 == res.length() && index1 != n) insertions = insertions + n - index1; return deletions + insertions; } int main() { // string str1 = "leetcode"; // string str2 = "etco"; string str1 = "geeksforgeeks"; string str2 = "geeks"; // string str1 = "heap"; // string str2 = "pea"; cout << minOperations(str1, str2); return 0; }
true
d430ce78af4a65333f11c52c866f29216e051ee3
C++
jjallaire/readr
/src/TokenizerCsv.h
UTF-8
4,715
3.078125
3
[]
no_license
#ifndef FASTREAD_TOKENIZERDELIMITED_H_ #define FASTREAD_TOKENIZERDELIMITED_H_ #include <Rcpp.h> #include "Token.h" #include "Tokenizer.h" enum CsvState { STATE_DELIM, STATE_FIELD, STATE_STRING, STATE_QUOTE }; class TokenizerCsv : public Tokenizer { char delim_; std::string NA_; int NA_size_; SourceIterator begin_, cur_, end_; CsvState state_; int row_, col_; bool moreTokens_; public: TokenizerCsv(char delim = ',', std::string NA = "NA"): delim_(delim), NA_(NA), NA_size_(NA.size()), moreTokens_(false) { } void tokenize(SourceIterator begin, SourceIterator end) { cur_ = begin; begin_ = begin; end_ = end; row_ = 0; col_ = 0; state_ = STATE_DELIM; moreTokens_ = true; } double proportionDone() { return (cur_ - begin_) / (double) (end_ - begin_); } Token nextToken() { // Capture current position int row = row_, col = col_; if (!moreTokens_) return Token(TOKEN_EOF, row, col); SourceIterator token_begin = cur_; bool hasEscape = false; while (cur_ != end_) { // Increments cur on destruct, ensuring that we always move on to the // next character Advance advance(&cur_); if ((row_ + 1) % 100000 == 0 || (col_ + 1) % 100000 == 0) Rcpp::checkUserInterrupt(); switch(state_) { case STATE_DELIM: if (*cur_ == '\r') { // Ignore \r, expect will be followed by \n } else if (*cur_ == '\n') { newRecord(); return Token(TOKEN_EMPTY, row, col); } else if (*cur_ == delim_) { newField(); return Token(TOKEN_EMPTY, row, col); } else if (*cur_ == '"') { state_ = STATE_STRING; } else { state_ = STATE_FIELD; } break; case STATE_FIELD: if (*cur_ == '\r') { // ignore } else if (*cur_ == '\n') { newRecord(); return fieldToken(token_begin, cur_, row, col); } else if (*cur_ == delim_) { newField(); return fieldToken(token_begin, cur_, row, col); } break; case STATE_QUOTE: if (*cur_ == '"') { hasEscape = true; state_ = STATE_STRING; } else if (*cur_ == '\r') { // ignore } else if (*cur_ == '\n') { newRecord(); return stringToken(token_begin + 1, cur_ - 1, hasEscape, row, col); } else if (*cur_ == delim_) { newField(); return stringToken(token_begin + 1, cur_ - 1, hasEscape, row, col); } else { Rcpp::stop("Expecting delimiter or quote at (%i, %i) but found '%s'", row, col, *cur_); } break; case STATE_STRING: if (*cur_ == '"') state_ = STATE_QUOTE; break; } } // Reached end of Source: cur_ == end_ moreTokens_ = false; switch (state_) { case STATE_DELIM: if (col_ == 0) { return Token(TOKEN_EOF, row, col); } else { return Token(TOKEN_EMPTY, row, col); } case STATE_QUOTE: return stringToken(token_begin + 1, end_ - 1, hasEscape, row, col); case STATE_STRING: Rf_warning("Unterminated string at end of file"); return stringToken(token_begin + 1, end_, hasEscape, row, col); case STATE_FIELD: return fieldToken(token_begin, end_, row, col); } return Token(TOKEN_EOF, row, col); } private: void newField() { col_++; state_ = STATE_DELIM; } void newRecord() { row_++; col_ = 0; state_ = STATE_DELIM; } Token fieldToken(SourceIterator begin, SourceIterator end, int row, int col) { if ((end - begin) == NA_size_ && strncmp(begin, &NA_[0], NA_size_) == 0) return Token(TOKEN_MISSING, row, col); return Token(begin, end, row, col); } Token stringToken(SourceIterator begin, SourceIterator end, bool hasEscape, int row, int col) { if (begin == end) return Token(TOKEN_EMPTY, row, col); if (hasEscape) return Token(begin, end, TokenizerCsv::unescapeDoubleQuote, row, col); return Token(begin, end, row, col); } public: static void unescapeDoubleQuote(SourceIterator begin, SourceIterator end, boost::container::string* pOut) { pOut->reserve(end - begin); bool inEscape = false; for (SourceIterator cur = begin; cur != end; ++cur) { if (*cur == '"') { if (inEscape) { pOut->push_back(*cur); inEscape = false; } else { inEscape = true; } } else { pOut->push_back(*cur); } } } }; #endif
true
c83f3288f2bb7312e0ffa9e4bc270415049f077e
C++
HackerDom/ructfe-2019
/checkers/engine/src/fuel/state.hpp
UTF-8
3,028
3.03125
3
[ "MIT" ]
permissive
#ifndef HPP_STATE #define HPP_STATE #include <boost/serialization/access.hpp> #include <boost/serialization/set.hpp> #include <boost/serialization/map.hpp> #include <set> #include <map> #include <vector> #include <utility> class state { private: size_t d_depth; state* d_root; std::map<char, state*> d_success; state* d_failure; std::set<std::pair<unsigned int, unsigned int>> d_pieces; public: state(): state(0) {} explicit state(size_t depth) : d_depth(depth) , d_root(depth == 0 ? this : nullptr) , d_success() , d_failure(nullptr) , d_pieces() {} state* next(char character) const { return next(character, false); } state* next_without_root(char character) const { return next(character, true); } state* add(char character) { auto next = next_without_root(character); if (next == nullptr) { next = new state(d_depth + 1); d_success[character] = next; } return next; } size_t depth() const { return d_depth; } void add_piece(unsigned int size, unsigned int index) { d_pieces.insert(std::make_pair(size, index)); } void add_piece(const std::set<std::pair<unsigned int, unsigned int>>& pieces) { for (const auto& p : pieces) { add_piece(p.first, p.second); } } std::set<std::pair<unsigned int, unsigned int>> pieces() const { return d_pieces; } state* failure() const { return d_failure; } void failure(state* fail_state) { d_failure = fail_state; } std::vector<state*> states() const { std::vector<state*> result; for (auto it = d_success.cbegin(); it != d_success.cend(); ++it) { result.push_back(it->second); } return std::vector<state*>(result); } std::vector<char> transitions() const { std::vector<char> result; for (auto it = d_success.cbegin(); it != d_success.cend(); ++it) { result.push_back(it->first); } return std::vector<char>(result); } private: state* next(char character, bool ignore_root_state) const { state* result = nullptr; auto found = d_success.find(character); if (found != d_success.end()) { result = found->second; } else if (!ignore_root_state && d_root != nullptr) { result = d_root; } return result; } private: friend class boost::serialization::access; template <typename Archive> void serialize(Archive &ar, const unsigned int version) { ar & d_depth; ar & d_root; ar & d_success; ar & d_failure; ar & d_pieces; } }; #endif
true
a6e394b0a8c582c75f2475eb2b004974835f7743
C++
kaushik27mishra/Daily_Practice_CP-DSA
/DynamicProgramming/0_1_knapsack_problem.cpp
UTF-8
1,372
3
3
[]
no_license
/* #include <bits/stdc++.h> using namespace std; #define deb(x) cout<<#x<<" "<<x<<endl; int t[102][1002]; int knapsack(int wt[],int val[],int w,int n) { if(n==0 || w==0) { return 0; } if(t[n][w]!=-1) { return t[n][w]; } if(wt[n-1]<=w) { return t[n][w]=max(val[n-1]+knapsack(wt,val,w-wt[n-1],n-1),knapsack(wt,val,w,n-1)); } else { return t[n][w]=knapsack(wt,val,w,n-1); } } int main() { int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; memset(t,-1,sizeof(t)); cout << knapsack(wt, val,W, 3)<<endl; return 0; } */ #include <bits/stdc++.h> using namespace std; #define deb(x) cout<<#x<<" "<<x<<endl; int t[102][1002]; int knapsack(int wt[],int val[],int w,int n) { for(int i=0;i<n+1;i++) { for(int j=0;j<w+1;j++) { if(i==0 || j==0) { t[i][j]=0; } } } for(int i=1;i<n+1;i++) { for(int j=1;j<w+1;j++) { if(wt[i-1]<=j) { t[i][j]=max(val[i-1]+t[i-1][j-wt[i-1]],t[i-1][j]); } else { t[i][j]=t[i-1][j]; } } } return t[n][w]; } int main() { int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; cout << knapsack(wt, val,W, 3)<<endl; return 0; }
true
78edfc254083bee8975ff887577a06e3f99d5959
C++
Sad7Dayz/c-
/11.cpp
UHC
688
3.796875
4
[]
no_license
//11. bool //12. string //#include <iostream> //using namespace std; // //bool IsEvenNumber(int num) //{ // return num % 2 == 0; //} // //int main() //{ // bool check = false; // int num = 0; // // // cout << ":"; // cin >> num; // // check = IsEvenNumber(num); // // if (check) // { // cout << "¦" << endl; // } // // else // { // cout << "Ȧ" << endl; // } // return 0; //} //------------------------------------- #include <iostream> #include <string> using namespace std; int main() { string s = "hello"; string s2; s2 = s; if (s == s2) { cout << "ƿ." << endl; } else { cout << "޶" << endl; } return 0; }
true
3d8d53ae6a1fd6d9138cb37b363ae77591227cc9
C++
minhaz007/C-Plus-Plus-Labs
/Lab 012/Appendix J/Appendix J/Lab_01.cpp
UTF-8
788
3.734375
4
[]
no_license
/*// Program Shell3 reads miles and hours and prints miles // per hour. #include <iostream> #include <iomanip> using namespace std; void GetData(float&, float&); int main () { float miles; float hours; float milesPerHour; cout << fixed << showpoint; GetData(miles,hours); milesPerHour = miles / hours; cout << setw(10) << miles << setw(10) << hours << setw(10) << milesPerHour << endl; return 0; } //***************************************************** void GetData(float& first, float& second) { // Pre: None // Post: first and second will have values read in from keyboard cout << "Please input miles then hours then press return" << endl; cin >> first >> second; } */
true
189e89d8931df9b4c49c6b849a2b95fb73757c4e
C++
vacstudy2017/C_Lang
/[엄상인]_1_1.cpp
UHC
213
2.96875
3
[]
no_license
#include <stdio.h> int mul(int i); int main() { int i; printf(" ԷϽÿ : "); scanf("%d", &i); mul(i); } int mul(int i) { int j; for (j = 1; j <= 9; j++) printf("%d*%d=%d\n", i, j, i*j); }
true
1590b892a355dd914429d04cb29790c180d794c4
C++
uwydoc/cppfunc
/Triple.h
UTF-8
1,432
3.15625
3
[ "MIT" ]
permissive
// Triple.h // // Generate int triples lazily // #ifndef CPPFUNC_TRIPLE_INCLUDED #define CPPFUNC_TRIPLE_INCLUDED #include <iostream> #include <tuple> #include <type_traits> #include "Stream.h" using Triple = std::tuple<int,int,int>; template<typename F, typename std::enable_if<std::is_convertible<F, std::function<bool(int,int,int)> >::value>::type* = nullptr> Stream<Triple> triples(int maxz, F f) { return mbind(range(1, maxz+1), [f](int z) { return mbind(range(1, z), [z,f](int y) { return mbind(range(1, y+1), [y,z,f](int x) { if (f(x, y, z)) return mreturn(std::make_tuple(x, y, z)); else return Stream<Triple>(); }); }); }); } template<typename F, typename std::enable_if<std::is_convertible<F, std::function<bool(Triple)> >::value>::type* = nullptr> Stream<Triple> triples(int maxz, F f) { return triples(maxz, [f](int x, int y, int z) { return f(std::make_tuple(x, y, z)); }); } Stream<Triple> triples(int maxz=INT_MAX-1) { return triples(maxz, [](int,int,int) { return true; }); } std::ostream& operator<<(std::ostream& os, const Triple& t) { int x, y, z; std::tie(x, y, z) = t; return (os << '(' << x << ',' << y << ',' << z << ')'); } #endif // CPPFUNC_TRIPLE_INCLUDED
true
e0c554f923583d7326759cc0f06f9854cee417aa
C++
fabianishere/traceur
/traceur-core/include/traceur/core/scene/graph/node.hpp
UTF-8
2,964
2.640625
3
[ "MIT" ]
permissive
/* * The MIT License (MIT) * * Copyright (c) 2017 Traceur authors * * 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. */ #ifndef TRACEUR_CORE_SCENE_GRAPH_NODE_H #define TRACEUR_CORE_SCENE_GRAPH_NODE_H #include <traceur/core/scene/graph/visitor.hpp> #include <traceur/core/kernel/ray.hpp> #include <traceur/core/kernel/hit.hpp> namespace traceur { /** * A node in the {@link SceneGraph} which could be a primitive or a * collection of primitives. */ class Node { public: /** * The position of the node in the scene. */ glm::vec3 origin; /** * Construct a {@link Node} instance. */ Node() : origin(glm::vec3()) {} /** * Construct a {@link Node} instance. * * @param[in] The position of the node. */ Node(const glm::vec3 &origin) : origin(origin) {} /** * Deconstruct the {@link Node} instance. */ virtual ~Node() {} /** * Determine whether the given ray intersects a shape in the geometry * of this graph. * * @param[in] ray The ray to intersect with a shape. * @param[in] hit The intersection structure to which the details will * be written to. * @return <code>true</code> if a shape intersects the ray, otherwise * <code>false</code>. */ inline virtual bool intersect(const traceur::Ray &, traceur::Hit &) const = 0; /** * Accept a {@link SceneGraphVisitor} instance to visit this node in * the graph of the scene. * * @param[in] visitor The visitor to accept. */ virtual void accept(traceur::SceneGraphVisitor &) const = 0; /** * Return the midpoint of this node. * * @return The midpoint of this node. */ virtual glm::vec3 midpoint() const { return origin; } /** * Return the bounding {@link Box} which encapsulates the whole node. * * @return A bounding {@link Box} of the node. */ virtual const Box & bounding_box() const = 0; }; } #endif /* TRACEUR_CORE_SCENE_GRAPH_NODE_H */
true
d7e4c8437936873a6a5a507cf85aafd15ccadfdd
C++
tiandada/Cpp_Primer_Notes
/code/10.1.cpp
UTF-8
247
2.984375
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using std::cout; using std::endl; using std::vector; int main() { vector<int> iv = {1,2,3,3,3,3,3,5,6,7,8,9}; auto c = count(iv.begin(), iv.end(), 3); cout << c << endl; return 0; }
true
44517e94226c1a024b4af9ee9d3a44aa7fae543e
C++
Conhan93/JustC
/justcpp/interfaces/accountstorage/mapstorage/MapAccountStorage.cpp
UTF-8
925
3.375
3
[]
no_license
#include "MapAccountStorage.h" #include <algorithm> MapAccountStorage::~MapAccountStorage() { // alias using mapIter = mapStorage::const_iterator; for (mapIter it = accounts.begin(); it != accounts.end(); it++) delete it->second; /* Deconstructor called at end of object lifetime. this one loops through all accounts and frees the allocated memory for them(since they're created using new) */ } void MapAccountStorage::AddAccount(std::string id) { Account *account = new Account(id); accounts[id] = account; /* Maps work just like dictionaries in Python, except that you have to declare types for keys and values when declaring a map. here string ID is used as a key and account is saved as value */ } Account* MapAccountStorage::GetAccount(std::string id) { // fetches, value at key - the account with the ID key return accounts[id]; }
true
a6a76b26dbea4727e5b40e8516193918ba087286
C++
rod08018/ARM-FRDMKL25Z
/RGB Control/main.cpp
UTF-8
1,400
2.671875
3
[]
no_license
#include "mbed.h" #include "TSISensor.h" Serial device(PTA2, PTA1); // tx, rx Ticker tick; float percent = 0; float percent1 = 0; int opt = 0; void send() { device.putc(percent); } void read() { percent1 = device.getc(); } int main(void) { PwmOut led(LED_GREEN); PwmOut led1(LED_BLUE); PwmOut led2(LED_RED); TSISensor tsi; tick.attach(&send,0.01); device.attach(&read); float valor; float valorant; float x; float y; float z; while (true) { percent = tsi.readPercentage()*10; if(percent1 != 0) { valor = percent1/10; } if(valor > 0.80 && valorant < 0.80) { opt++; if(opt > 3) { opt = 0; } } else { if(opt == 0) { x = 1.1 - valor; led = x; led2 = 1; led1 = 1; } if(opt == 1) { y = 1.1 - valor; led1 = y; led2 = 1; led = 1; } if(opt == 2) { z = 1.1 - valor; led2 = z; led1 = 1; led = 1; } if(opt == 3) { led2 = z; led1 = y; led = x; } } wait(0.1); valorant = valor; } }
true
4c6793ca07fd71691004e03da996bb1b07dff95f
C++
xt9852/TestSet
/08.TestSet/src/00.Finger/FingerImageProcess.cpp
GB18030
42,745
2.609375
3
[]
no_license
#include "stdafx.h" #include "FingerImageProcess.h" #include <math.h> // ݷ12, // 12ȡ7,ÿλ static const int g_DDSite[12][7][2] = { -3, 0, -2, 0, -1, 0, 0, 0, 1, 0, 2, 0, 3, 0, -3,-1, -2,-1, -1, 0, 0, 0, 1, 0, 2, 1, 3, 1, -3,-2, -2,-1, -1,-1, 0, 0, 1, 1, 2, 1, 3, 2, -3,-3, -2,-2, -1,-1, 0, 0, 1, 1, 2, 2, 3, 3, -2,-3, -1,-2, -1,-1, 0, 0, 1, 1, 1, 2, 2, 3, -1,-3, -1,-2, 0,-1, 0, 0, 0, 1, 1, 2, 1, 3, 0,-3, 0,-2, 0,-1, 0, 0, 0, 1, 0, 2, 0, 3, -1, 3, -1, 2, 0, 1, 0, 0, 0,-1, 1,-2, 1,-3, -2, 3, -1, 2, -1, 1, 0, 0, 1,-1, 1,-2, 2,-3, -3, 3, -2, 2, -1, 1, 0, 0, 1,-1, 2,-2, 3,-3, -3, 2, -2, 1, -1, 1, 0, 0, 1,-1, 2,-1, 3,-2, -3, 1, -2, 1, -1, 0, 0, 0, 1, 0, 2,-1, 3,-1 }; /** *\fn void zoomout(uint8 *input, uint8 *output, int cx, int cy) *\brief ͼСΪԭ1/4 *\param[in] uint8 * input ԭͼ *\param[in] uint8 * output Сͼ *\param[in] int cx ԭͼ *\param[in] int cy ԭͼ *\return void */ void zoomout(uint8 *input, uint8 *output, int cx, int cy) { int x = 0; int y = 0; int sum = 0; int temp1 = 0; int temp2 = 0; int SiteD8[8] = {cx-1, cx, cx+1, 1, -cx+1, -cx, -cx-1, -1}; uint8 *src = NULL; uint8 *dst = NULL; // Ե temp2 = cx / 2; for (y = 0; y < cy; y += 2) { src = input + y*cx; dst = output + (y/2)*temp2; *dst = *src; src = input + y*cx + cx - 1; dst = output + (y/2)*temp2 + (temp2 - 1); *dst = *src; } temp1 = (cy-1)*cx; temp2 = (cy/2-1)*(cx/2); for (x = 0; x < cx; x += 2) { src = input + x; dst = output + x/2; *dst = *src; src = input + x + temp1; dst = output + x/2 + temp2; *dst = *src; } // DZԵø˹ģȡƵϢ for (y = 2; y < cy-2; y += 2) { for (x = 2; x < cx-2; x += 2) { src = input + y*cx + x; dst = output + (y/2)*(cx/2) + x/2; // ˹ģ // 1 2 1 // 2 4 2 // 1 2 1 sum = *src*4 + *(src + SiteD8[0]) + *(src + SiteD8[1])*2 + *(src + SiteD8[2]) + *(src + SiteD8[3])*2 + *(src + SiteD8[4]) + *(src + SiteD8[5])*2 + *(src + SiteD8[6]) + *(src + SiteD8[7])*2; *dst = (uint8)(sum >> 4); } } } /** *\fn void getGrads(uint8* input, uint8* output, int cx, int cy, long r) *\brief õݶȳ *\param[in] uint8 * input ,Ϊԭͼ1/4ͼ *\param[out] uint8 * output ,ݶȳ *\param[in] int cx ͼ *\param[in] int cy ͼ *\param[in] long r 뾶 *\return void */ void getGradsFromZoomout(uint8* input, uint8* output, int cx, int cy, long r) { long x = 0; long y = 0; long i = 0; long j = 0; long vx = 0; long vy = 0; long lvx = 0; long lvy = 0;; uint8 *src = NULL; // ԭ uint8 *dst = NULL; // Ŀ¼ int grad = 0; // ݶ int gradSum = 0; // ݶȺ int gradNum = 0; // ݶȼ for (y = 0; y < cy / 2; y++) { for (x = 0; x < cx / 2; x++) { lvx = 0; lvy = 0; gradNum = 0; gradSum = 0; for (i = -r; i <= r; i++) // ΪٶȣΪ2 { if ((y+i) < 1 || (y+i) >= (cy/2-1)) continue; for (j = -r; j <= r; j++) // ΪٶȣΪ2 { if ((x+j) < 1 || (x+j) >= (cx/2-1)) continue; src = input + (y+i)*(cx/2) + x+j; // xƫ // -1 0 1 // -2 0 2 // -1 0 1 vx = *(src + cx/2 + 1) - *(src + cx/2 - 1) + *(src + 1)*2 - *(src - 1)*2 + *(src - cx/2 + 1) - *(src - cx/2 - 1); // yƫ // -1 -2 -1 // 0 0 0 // 1 2 -1 vy = *(src + cx/2 - 1) - *(src - cx/2 - 1) + *(src + cx/2)*2 - *(src - cx/2)*2 + *(src + cx/2 + 1) - *(src - cx/2 + 1); gradSum += (abs(vx)+abs(vy)); gradNum++; } } if (gradNum == 0) gradNum = 1; grad = gradSum / gradNum; if (grad > 255) grad = 255; dst = output + 2*y*cx + 2*x; *(dst) = (uint8)grad; *(dst + 1) = (uint8)grad; *(dst + cx) = (uint8)grad; *(dst + cx + 1) = (uint8)grad; } } } void getGrads(uint8* input, uint8* output, int cx, int cy, long r) { } /** *\fn void getOrient(uint8* input, uint8* output, int cx, int cy, long r) *\brief õ *\param[in] uint8 * input ,Ϊԭͼ1/4ͼ *\param[out] uint8 * output ,ݶȳ *\param[in] int cx ͼ *\param[in] int cy ͼ *\param[in] long r 뾶 *\return void */ void getOrientFromZoomout(uint8 *input, uint8* output, int cx, int cy, long r) { int x = 0; int y = 0; int i = 0; int j = 0; long vx = 0; long vy = 0; long lvx = 0; long lvy = 0; long num = 0; long angle = 0; double fAngle = 0.0; uint8 *src = NULL; uint8 *dst = NULL; for (y = 0; y < cy / 2; y++) { for (x = 0; x < cx / 2; x++) { lvx = 0; lvy = 0; num = 0; for (i = -r; i <= r; i++) // ΪٶȣΪ2 { if ((y+i) < 1 || (y+i) >= (cy/2-1)) continue; for (j = -r; j <= r; j++) // ΪٶȣΪ2 { if ((x+j) < 1 || (x+j) >= (cx/2-1)) continue; src = input + (y+i)*(cx/2) + x+j; //xƫ // -1 0 1 // -2 0 2 // -1 0 1 vx = *(src + cx/2 + 1) - *(src + cx/2 - 1) + *(src + 1)*2 - *(src - 1)*2 + *(src - cx/2 + 1) - *(src - cx/2 - 1); //yƫ // -1 -2 -1 // 0 0 0 // 1 2 -1 vy = *(src + cx/2 - 1) - *(src - cx/2 - 1) + *(src + cx/2)*2 - *(src - cx/2)*2 + *(src + cx/2 + 1) - *(src - cx/2 + 1); lvx += vx * vy * 2;//sin(2sita) lvy += vx*vx - vy*vy;//cos(2sita) num++; } } if (num == 0) num = 1; // 󻡶(-pi - pi) fAngle = atan2((double)lvy, (double)lvx); // 任(0 - 2*pi) if(fAngle < 0) fAngle += 2*PI; // ɻתɽǶ,߽Ƕ angle = (long)(fAngle*EPI*0.5 + 0.5); // ΪsobelӣԽǶƫת˶ȣҪתõĽǶ angle -= 135; // Ƕȱ任-180 if(angle <= 0) angle += 180; angle = 180-angle; // ߽Ƕ dst = output + 2 * y * cx + 2 * x; *(dst) = (uint8)angle; *(dst + 1) = (uint8)angle; *(dst + cx) = (uint8)angle; *(dst + cx + 1) = (uint8)angle; } } } void getOrient(uint8 *input, uint8* output, int cx, int cy, long r) { int x = 0; int y = 0; int i = 0; int j = 0; long vx = 0; long vy = 0; long lvx = 0; long lvy = 0; long num = 0; long angle = 0; double fAngle = 0.0; uint8 *src = NULL; uint8 *dst = NULL; for (y = 0; y < cy; y++) { for (x = 0; x < cx; x++) { lvx = 0; lvy = 0; num = 0; for (i = -r; i <= r; i++) { if ((y+i) < 1 || (y+i) >= (cy-1)) continue; for (j = -r; j <= r; j++) { if ((x+j) < 1 || (x+j) >= (cx-1)) continue; src = input + (y+i)*cx + x+j; //xƫ // -1 0 1 // -2 0 2 // -1 0 1 vx = *(src + cx + 1) - *(src + cx - 1) + *(src + 1)*2 - *(src - 1)*2 + *(src - cx + 1) - *(src - cx - 1); //yƫ // -1 -2 -1 // 0 0 0 // 1 2 -1 vy = *(src + cx - 1) - *(src - cx - 1) + *(src + cx)*2 - *(src - cx)*2 + *(src + cx + 1) - *(src - cx + 1); lvx += vx * vy * 2;//sin(2sita) lvy += vx*vx - vy*vy;//cos(2sita) num++; } } if (num == 0) num = 1; // 󻡶(-pi - pi) fAngle = atan2((double)lvy, (double)lvx); // 任(0 - 2*pi) if(fAngle < 0) fAngle += 2*PI; // ɻתɽǶ,߽Ƕ angle = (long)(fAngle*EPI*0.5 + 0.5); // ΪsobelӣԽǶƫת˶ȣҪתõĽǶ angle -= 135; // Ƕȱ任-180 if(angle <= 0) angle += 180; angle = 180-angle; // ߽Ƕ dst = output + y * cx + x; *(dst) = (uint8)angle; // *(dst + 1) = (uint8)angle; // *(dst + cx) = (uint8)angle; // *(dst + cx + 1) = (uint8)angle; } } } /** *\fn int getBackgroundTemplate(uint8 *input, uint8 *output, int r, int threshold, int cx, int cy) *\brief ɱģ *\param[in] uint8 * input ԭͼ *\param[in] uint8 * output ģ:255Ϊ,0Ϊǰ *\param[in] int r Էֵͼ߶ƽ˲˲뾶 *\param[in] int threshold ֵָ *\param[in] int cx ͼ *\param[in] int cy ͼ *\return int 0ɹ,ʧ */ int getBackgroundTemplate(uint8 *input, uint8 *output, int r, int threshold, int cx, int cy) { int x = 0; int y = 0; int num = 0; int lineBegin= 0; uint8 *src = NULL; // Է򳡷ֵͼи߶ƽ˲ smooth(input, output, cx, cy, r, 2); // ͼԵΪ num = cx - 1; for (y = 0; y < cy; y++) { src = output + y*cx; *(src) = 255; *(src + num) = 255; } num = (cy-1)*cx; for (x = 0; x < cx; x++) { src = output + x; *(src) = 255; *(src + num) = 255; } num = 0; lineBegin = cx; for (y = 1; y < cy-1; y++) { for (x = 1; x < cx-1; x++) { src = output + lineBegin + x; // ݷֵֵСжǷΪ if (*src < threshold) { *src = 0; } else { *src = 255; num++; } } lineBegin += cx; } // ǰСʮ֮һʾǰ̫Сش return ((num < (cx * cy / 10)) ? 1 : 0); } /** *\fn void clearBackground(uint8 *input, uint8 *output, uint8* mask, int cx, int cy) *\brief *\param[in] uint8 * input ԭͼ *\param[out] uint8 * output ͼ *\param[in] uint8 * mask ģ *\param[in] int cx ͼ *\param[in] int cy ͼ *\return void */ void clearBackground(uint8 *input, uint8 *output, uint8* mask, int cx, int cy) { int x = 0; int y = 0; int pos = 0; int lineBegin = 0; for (y = 0; y < cy; y++) { for (x = 0; x < cx; x++) { pos = lineBegin + x; // DZøõΪ׵ if (*(mask + pos) == 0) { *(output + pos) = 255; } else { *(output + pos) = *(input + pos); } } lineBegin += cx; } } /** *\fn void equalize(uint8 *input, uint8 *output, int cx, int cy) *\brief ͼ *\param[in] uint8 * input ԭͼ *\param[out] uint8 * output ͼ *\param[in] int cx ͼ *\param[in] int cy ͼ *\return void */ void equalize(uint8 *input, uint8 *output, int cx, int cy) { // Ҷȼ int lCount[256] = {0}; // Ҷӳ uint8 bMap[256] = {0}; // ָԴͼָ uint8* src = NULL; uint8* dst = NULL; // ʱ int lTemp = 0; int lineBegin = 0; // ѭ int i = 0; int j = 0; int x = 0; int y = 0; // Ҷֵļ for (y = 0; y < cy; y++) { for (x = 0; x < cx; x++) { src = input + lTemp + x; // 1 lCount[*(src)]++; } lineBegin += cx; } // Ҷӳ for (i = 0; i < 256; i++) { // ʼΪ0 lTemp = 0; for (j = 0; j <= i; j++) { lTemp += lCount[j]; } // Ӧ»Ҷֵ bMap[i] = (uint8)(lTemp * 255 / cy / cx); } lineBegin = 0; // µͼ for (y = 0; y < cy; y++) { for (x = 0; x < cx; x++) { src = input + lineBegin + x; dst = output + lineBegin + x; // µĻҶֵ *dst = bMap[*src]; } lineBegin += cx; } } /** *\fn int getGaussWindowSize(double sigma) *\brief õһά˹ģ崰ڴС *\n һһάĸ˹ݣϸ˹ݵijӦ *\n ޳ģΪ˼ļ򵥺ٶȣʵʵĸ˹ֻ޳ *\n 鳤ȣݸ۵֪ʶѡȡ[-3*sigma, 3*sigma]ڵݡ *\n ЩݻḲǾ󲿷ֵ˲ϵ *\param[in] double sigma ˹ı׼ *\return int ˹ģ崰ڴС */ int getGaussWindowSize(double sigma) { return (int)(1 + 2 * ceil(3 * sigma)); } /** *\fn void makeGauss(double sigma, int nWindowSize, double *output) *\brief ɸ˹ģ *\param[in] double sigma ˹ı׼ *\param[in] int nWindowSize ڴС *\param[out] double * output ˹ģ *\return void */ void makeGauss(double sigma, int nWindowSize, double *output) { // ĵ int nCenter = nWindowSize / 2; // ijһ㵽ĵľ double dDis = 0.0; // м double dSum = 0.0; double dValue = 0.0; // ʱ int i = 0; // һά˹ģ for (i = 0; i < nWindowSize; i++) { dDis = (double)(i - nCenter); dValue = exp(-(1/2)*dDis*dDis/(sigma*sigma)) / (sqrt(2 * PI) * sigma); output[i] = dValue; dSum += dValue; } // һ for (i = 0; i < nWindowSize; i++) { output[i] /= dSum; } } /** *\fn void gaussSmooth(uint8 *input, uint8 *output, int cx, int cy, double sigma) *\brief ˹ƽ *\param[in] uint8 * input ԭͼ *\param[out] uint8 * output *\param[in] int cx ͼ *\param[in] int cy ͼ *\param[in] double sigma ˹ı׼ *\return void */ void gaussSmooth(uint8 *input, uint8 *output, int cx, int cy, double sigma) { // ˹˲鳤 int nWindowSize = getGaussWindowSize(sigma); // ڳȵ1/2 int nHalfLen = nWindowSize / 2; // һά˹˲ double *pdKernel = new double[nWindowSize]; // ˹ϵͼݵĵ double dDotMul = 0.0; // ˹˲ϵܺ double dWeightSum = 0.0; // м double *pdTmp = new double[cx*cy]; // ʱ int x = 0; int y = 0; int i = 0; // һά˹˲ makeGauss(sigma, nWindowSize, pdKernel); // x˲ for (y = 0; y < cy; y++) { for (x = 0; x < cx; x++) { dDotMul = 0; dWeightSum = 0; for (i = (-nHalfLen); i <= nHalfLen; i++) { // жǷͼⲿ if ((x+i) < 0 || (x+i) >= cx) continue; dDotMul += (double)input[y*cx + (x+i)] * pdKernel[nHalfLen+i]; dWeightSum += pdKernel[nHalfLen+i]; } pdTmp[y*cx + x] = dDotMul/dWeightSum; } } // y˲ for (x = 0; x < cx; x++) { for (y = 0; y < cy; y++) { dDotMul = 0; dWeightSum = 0; for (i = (-nHalfLen); i <= nHalfLen; i++) { // жǷͼⲿ if ((y+i) < 0 || (y+i) >= cy) continue; dDotMul += (double)pdTmp[(y+i)*cx + x] * pdKernel[nHalfLen+i]; dWeightSum += pdKernel[nHalfLen+i]; } output[y*cx + x] = (BYTE)(int)(dDotMul / dWeightSum); } } // ͷڴ delete[] pdKernel; pdKernel = NULL; delete[] pdTmp; pdTmp = NULL; } /** *\fn void smooth(uint8 *input, uint8 *output, int cx, int cy, int r, int d) *\brief ֵƽ˲ *\param[in] uint8 * input Ҫƽͼݻ *\param[out] uint8 * output ƽͼݻ *\param[in] int cx ͼ *\param[in] int cy ͼ *\param[in] int r ƽ˲뾶 *\param[in] int d ƽ˲ *\return void */ void smooth(uint8 *input, uint8 *output, int cx, int cy, int r, int d) { int x = 0; int y = 0; int i = 0; int j = 0; int sum = 0; int num = 0; uint8 *src = NULL; uint8 *dst = NULL; for (y = 0; y < cy; y++) { for (x = 0; x < cx; x++) { sum = 0; num = 0; src = input + y*cx + x; dst = output + y*cx + x; for (i = -r; i <= r; i += d) { if ((y+i) < 0 || (y+i) >= cy) continue; for (j = -r; j <= r; j += d) { if ((x+j) < 0 || (x+j) >= cx) continue; sum += *(src + i*cx + j); num++; } } *dst = (uint8)(sum/num); } } } /** *\fn int DDIndex(int angle) *\brief Ҷֵ12ֵ *\param[in] int angle Ƕ 0 - 180 *\return int 12ֵ(0-11) */ int DDIndex(int angle) { if (angle >= 173 || angle < 8) { return 0; } else { return ((angle-8)/15 + 1); } } /** *\fn void orientEnhance(uint8 *input, uint8 *output, uint8 *orient, int cx, int cy) *\brief ͨǿͼ *\param[in] uint8 * input ԭͼ *\param[out] uint8 * output ǿͼ *\param[in] uint8 * orient *\param[in] int cx ͼ *\param[in] int cy ͼ *\return void */ void orientEnhance(uint8 *input, uint8 *output, uint8 *orient, int cx, int cy) { int Hw[7] = {1, 1, 1, 1, 1, 1, 1}; // ߷Ͻƽ˲ƽ˲ int Vw[7] = {-3, -1, 3, 9, 3, -1, -3}; // ߷ĴֱϽ˲˲ uint8 *src = NULL; uint8 *dst = NULL; int x = 0; int y = 0; int i = 0; int d = 0; int sum = 0; int hsum = 0; int vsum = 0; int lineBegin = 0; uint8 *temp = new uint8[cx * cy]; // ߷Ͻƽ˲ for (y = 0; y < cy; y++) { for (x = 0; x < cx; x++) { sum = 0; hsum = 0; src = input + lineBegin + x; d = DDIndex(*(orient + lineBegin + x)); // ߷ for (i = 0; i < 7; i++) { if (y+g_DDSite[d][i][1] < 0 || y+g_DDSite[d][i][1] >= cy || x+g_DDSite[d][i][0] < 0 || x+g_DDSite[d][i][0] >= cx) { continue; } sum += Hw[i] * (*(src + g_DDSite[d][i][1]*cx + g_DDSite[d][i][0])); hsum += Hw[i]; } if (hsum != 0) { *(temp + lineBegin + x) = (uint8)(sum / hsum); } else { *(temp + lineBegin + x) = 255; } } lineBegin += cx; } // ߷ĴֱϽ˲ lineBegin = 0; for (y = 0; y < cy; y++) { for (x = 0; x < cx; x++) { sum = 0; vsum = 0; src = temp + lineBegin + x; d = (DDIndex(*(orient + lineBegin + x))+6) % 12; // ߷Ĵֱ for (i = 0; i < 7; i++) { if (y+g_DDSite[d][i][1] < 0 || y+g_DDSite[d][i][1] >= cy || x+g_DDSite[d][i][0] < 0 || x+g_DDSite[d][i][0] >= cx) { continue; } sum += Vw[i] * (*(src + g_DDSite[d][i][1]*cx + g_DDSite[d][i][0])); vsum += Vw[i]; } if (vsum > 0) { sum /= vsum; if (sum > 255) { *(output + lineBegin + x) = 255; } else if (sum < 0) { *(output + lineBegin + x) = 0; } else { *(output + lineBegin + x) = (uint8)sum; } } else { *(output + lineBegin + x) = 255; } } lineBegin += cx; } delete[] temp; } /** *\fn void binary(uint8 *input, uint8 *output, uint8 *orient, int cx, int cy) *\brief ֵͼ *\param[in] uint8 * input ԭͼ *\param[out] uint8 * output ֵͼ *\param[in] uint8 * orient 뷽 *\param[in] int cx ͼ *\param[in] int cy ͼ *\return void */ void binary(uint8 *input, uint8 *output, uint8 *orient, int cx, int cy) { int Hw[7] = {2, 2, 3, 4, 3, 2, 2}; // ߷ϵ7Ȩֵ int Vw[7] = {1, 1, 1, 1, 1, 1, 1}; // ߷Ĵֱϵ7Ȩֵ int hsum = 0; // ߷ϵ7ļȨ int vsum = 0; // ߷Ĵֱϵ7ļȨ int Hv = 0; // ߷ϵ7ļȨƽֵ int Vv = 0; // ߷Ĵֱϵ7ļȨƽֵ uint8 *src = NULL; // ָͼصָ uint8 *dst = NULL; // ߷ָ int x = 0; int y = 0; int i = 0; int d = 0; int sum = 0; int lineBegin = 0; for (y = 0; y < cy; y++) { for (x = 0; x < cx; x++) { src = input + lineBegin + x; // õdzڣʱøõΪڵ㣬ֵΪ0 if (*src < 4) { *(output + lineBegin + x) = 0; continue; } // 㷽Ϊ12 d = DDIndex(*(orient + lineBegin + x)); // 㵱ǰ߷ϵļȨƽֵ sum = 0; hsum = 0; for (i = 0; i < 7; i++) { // ǷԽ if (y+g_DDSite[d][i][1] < 0 || y+g_DDSite[d][i][1] >= cy || x+g_DDSite[d][i][0] < 0 || x+g_DDSite[d][i][0] >= cx) { continue; } sum += Hw[i] * (*(src + g_DDSite[d][i][1]*cx + g_DDSite[d][i][0])); hsum += Hw[i]; } Hv = (hsum != 0) ? (sum / hsum) : 255; // ߷Ĵֱ d = (d+6)%12; // 㵱ǰ߷ĴֱϵļȨƽֵ sum = 0; vsum = 0; for (i = 0; i < 7; i++) { if (y+g_DDSite[d][i][1] < 0 || y+g_DDSite[d][i][1] >= cy || x+g_DDSite[d][i][0] < 0 || x+g_DDSite[d][i][0] >= cx) { continue; } sum += Vw[i] * (*(src + g_DDSite[d][i][1]*cx + g_DDSite[d][i][0])); vsum += Vw[i]; } Vv = (vsum != 0) ? (sum / vsum) : 255; dst = output + lineBegin + x; // ߷ϼȨƽֵСõǰΪڵ,ϴõǰΪ׵ *dst = (Hv < Vv) ? 0 : 255; } lineBegin += cx; } } /** *\fn void binaryClear(uint8 *input, uint8 *output, uint8 *mask, int cx, int cy) *\brief Զֵָͼȥ,ȥ *\param[in] uint8 * input ԭͼ *\param[in] uint8 * output ȥͼ *\param[in] uint8 * mask ģ *\param[in] int cx ͼ *\param[in] int cy ͼ *\return void */ void binaryClear(uint8 *input, uint8 *output, uint8 *mask, int cx, int cy) { int x = 0; int y = 0; int i = 0; int n = 0; int num = 0; int lineBegin = 0; bool working = true; uint8 *src = NULL; uint8 *dst = NULL; // ijΧ8ĵַƫ int SiteD8[8] = {cx-1, cx, cx+1, 1, -cx+1, -cx, -cx-1, -1}; // ʼʱ memset(output, 0xFF, cx*cy); // ѭֱϻߴ8 while (working && n < 8) { n++; working = false; lineBegin = cx; for (y = 1; y < cy-1; y++) { for (x = 1; x < cx-1; x++) { // ĵ㲻 if ((NULL != mask) && (*(mask + lineBegin + x) == 0)) continue; // ͳƵǰΧͬ͵ĸ num = 0; src = input + lineBegin + x; for (i = 0; i < 8; i++) { if (*(src+SiteD8[i]) == *src) { num++; } } // ͬСڶı䵱ǰ dst = output + lineBegin + x; if (num < 2) { *dst = 255 - *src; working = true; } else { *dst = *src; } } lineBegin += cx; } } } /** *\fn void thin(uint8 *input, uint8 *output, int cx, int cy) *\brief ͼϸ *\param[in] uint8 * input ԭͼ *\param[in] uint8 * output ϸͼ *\param[in] int cx ͼ *\param[in] int cy ͼ *\return void */ void thin(uint8 *input, uint8 *output, int cx, int cy) { uint8 eraseTable[256] = { 0,0,1,1,0,0,1,1, 1,1,0,1,1,1,0,1, 1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,1, 0,0,1,1,0,0,1,1, 1,1,0,1,1,1,0,1, 1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,1, 1,1,0,0,1,1,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 1,1,0,0,1,1,0,0, 1,1,0,1,1,1,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,0,0,1,1, 1,1,0,1,1,1,0,1, 1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,1, 0,0,1,1,0,0,1,1, 1,1,0,1,1,1,0,1, 1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 1,1,0,0,1,1,0,0, 0,0,0,0,0,0,0,0, 1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 1,1,0,0,1,1,0,0, 1,1,0,1,1,1,0,0, 1,1,0,0,1,1,1,0, 1,1,0,0,1,0,0,0 }; int x = 0; int y = 0; int num = 0; int lineBegin = cx; bool finished = false; uint8 nw,n,ne,w,e,sw,s,se; uint8 *src = NULL; uint8 *dst = NULL; uint8 *buffer = new uint8[cx*cy]; memcpy(buffer, input, cx*cy); memcpy(output, input, cx*cy); while (!finished) // ûн { // ־óɼ finished = true; lineBegin = 0; // Ƚˮƽϸ for (y = 1; y < (cy-1); y++) //עΪֹԽ磬yķΧ1߶-2 { for (x = 1; x < (cx-1); ) // עΪֹԽ磬xķΧ1-2 { src = buffer + lineBegin + x; dst = output + lineBegin + x; if (*src == 0) // Ǻڵ { w = *(src - 1); // ڵ e = *(src + 1); // ڵ if ((w == 255)|| (e == 255)) // ھһǰ׵Ŵ { nw = *(src+cx-1); // ڵ n = *(src+cx); // ڵ ne = *(src+cx+1); // ڵ sw = *(src-cx-1); // ڵ s = *(src-cx); // ڵ se = *(src-cx+1); // ڵ // num = nw/255+n/255*2+ne/255*4+w/255*8+e/255*16+ sw/255*32+s/255*64+se/255*128; if (eraseTable[num] == 1) // ɾ { *src = 255; // ԭͼнúڵɾ *dst = 255; // ͼиúڵҲɾ finished = false; // иĶ־óɼ x++; // ˮƽһ } } } x++; // ɨһ } lineBegin += cx; } lineBegin = 0; // ٽдֱϸ for (x = 1; x < (cx-1); x++) { for (y = 1; y < (cy-1);) { src = buffer + lineBegin + x; dst = output + lineBegin + x; if (*src == 0) // Ǻڵ { n = *(src + cx); // ڵ s = *(src - cx); // ڵ if ((n == 255) || (s == 255)) // ھһǰ׵Ŵ { nw = *(src+cx-1); // ڵ ne = *(src+cx+1); // ڵ w = *(src-1); // ڵ e = *(src+1); // ڵ sw = *(src-cx-1); // ڵ se = *(src-cx+1); // ڵ // num = nw/255+n/255*2+ne/255*4+w/255*8+e/255*16+ sw/255*32+s/255*64+se/255*128; if (eraseTable[num] == 1) // ɾ { *src = 255; // ԭͼнúڵɾ *dst = 255; // ͼиúڵҲɾ finished = false; // иĶ־óɼ y++; // ֱһ } } } y++; // ɨһ } lineBegin += cy; } } delete[] buffer; } /** *\fn void thinClear(uint8 *input, uint8 *output, int cx, int cy, int len) *\brief ϸͼж̰ë *\param[in] uint8 * input ԭͼ *\param[in] uint8 * output ͼ *\param[in] int cx ͼ *\param[in] int cy ͼ *\param[in] int len ̰ë̵󳤶 *\return void */ void thinClear(uint8 *input, uint8 *output, int cx, int cy, int len) { int SiteD8[8] = {cx-1, cx, cx+1, 1, -cx+1, -cx, -cx-1, -1}; int x = 0; int y = 0; int i = 0; int n = 0; int lineBegin = 0; uint8 *linePt[25] = {0}; // ߸ uint8 *temp[8] = {0}; // ijڵ uint8 *pt = NULL; uint8 *last = NULL; uint8 *next = NULL; uint8 *src = NULL; memcpy(output, input, cx*cy); for (y = 0; y < cy; y++) { for (x = 0; x < cx; x++) { src = output + lineBegin + x; if (*src != 0) continue; n = 0; linePt[0] = src; // ͳƵǰΧڵ for (i = 0; i < 8; i++) { pt = src + SiteD8[i]; if (*pt == 0) { temp[n] = pt; n++; } } // ڵΪ㣬ʾǰǹµ㣬Ϊɫ if (n == 0) { *src = 255; continue; } else if (n == 1) // ڵΪ1ʾΪ˵ { n = 0; last = src; pt = temp[0]; // ߸len for (i = 0; i < len; i++) { // ѭ if (isFork(pt, cx)) { break; } n++; linePt[n] = pt; if (getNextPt(pt, last, &next, cx, cy)) { last = pt; pt = next; } else // 쳣ѭ { break; } } // ߽϶̣ʾΪ̰ë if (n < len) { for(i = 0; i <= n; i++) { *linePt[i] = 255; } } } } lineBegin += cx; } } /** *\fn bool isEnd(uint8 *input, int cx) *\brief жϵǰǷΪ˵ *\param[in] uint8 * input ǰ *\param[in] int cx ͼ *\return bool ǷΪ˵ */ bool isEnd(uint8 *input, int cx) { int i = 0; int sum = 0; int siteD8[8] = {cx-1, cx, cx+1, 1, -cx+1, -cx, -cx-1, -1};// ijΧ8ĵַƫ // 8IJľֵĺΪ2*255Ϊ˵ for(i = 0; i < 8; i++) { sum += abs(*(input + siteD8[(i+1)%8]) - *(input + siteD8[i])); } return (sum == 255*2); } /** *\fn bool isFork(uint8 *input, int cx) *\brief ǰǷΪ *\param[in] uint8 * input ǰ *\param[in] int cx ͼ *\return bool ǷΪ */ bool isFork(uint8 *input, int cx) { int i = 0; int sum = 0; int siteD8[8] = {cx-1, cx, cx+1, 1, -cx+1, -cx, -cx-1, -1}; // ijΧ8ĵַƫ // 8IJľֵĺΪ6*255Ϊ for (i = 0; i < 8; i++) { sum += abs(*(input + siteD8[(i+1)%8]) - *(input + siteD8[i])); } return (sum == 255*6); } /** *\fn int getNextPt(uint8 *pt, uint8 *last, uint8 **next, int cx, int cy) *\brief õߵһ *\param[in] uint8 * pt ǰĵַ *\param[in] uint8 * last ǰĵַ *\param[in] uint8 * * next һĵַָ *\param[in] int cx ͼ *\param[in] int cy ͼ *\return bool Ƿҵ̵ */ bool getNextPt(uint8 *pt, uint8 *last, uint8 **next, int cx, int cy) { int siteD8[8] = {cx-1, cx, cx+1, 1, -cx+1, -cx, -cx-1, -1}; int i = 0; int n = 0; uint8 *src = NULL; uint8 *temp[8] = {0}; // ijΧ8ĵַ *next = NULL; // ҵǰΧǺڵ㲢Ҳǰĺڵ㣬浽 for (i = 0; i < 8; i++) { src = pt + siteD8[i]; if (*src == 0 && src != last) { temp[n] = src; n++; } } if (n == 1) // ҵһΪ̵ { *next = temp[0]; return true; } // ûҵڵʾûк̵ // ҵ򷵻ش return false; } /* *\fn int loadBitmap(const char *filename, uint8 *data, BITMAPFILEHEADER *bfh, BITMAPINFOHEADER *bih, int *cx, int *cy) *\brief ͼļ *\param[in] const char * filename ļ *\param[out] uint8 * data ļ *\param[out] BITMAPFILEHEADER * bfh ͼļͷ *\param[out] BITMAPINFOHEADER * bih ͼϢͷ *\param[out] int * cx ͼ *\param[out] int * cy ͼ *\return int 0ɹ,ʧ */ int loadBitmap(const char *filename, uint8 *data, BITMAPFILEHEADER *bfh, BITMAPINFOHEADER *bih, int *cx, int *cy) { if (NULL == filename || NULL == bfh || NULL == bih || NULL == cx || NULL == cy) return -1; // ļ FILE *fp = fopen(filename, "rb"); if (NULL == fp) return -2; // ļͷ fread((void*)bfh, sizeof(BITMAPFILEHEADER), 1, fp); fread((void*)bih, sizeof(BITMAPINFOHEADER), 1, fp); // ǷΪBMPļ if (bfh->bfType != 19778) { fclose(fp); return -3; } // ǷΪ256ɫҶͼ if (bih->biBitCount != 8 && bih->biClrUsed != 256) { fclose(fp); return -4; } // õͼС *cx = bih->biWidth; *cy = bih->biHeight; // õһеֽ,4ֽڶ int lineBytes = (bih->biWidth + 3) / 4 * 4; // ָ벻Ϊȡͼݵ if (NULL == data) { fclose(fp); return -5; } // жȡÿֻȡcxֽ for (int i = 0; i < bih->biHeight; i++) { fseek(fp, 1078+lineBytes*i, SEEK_SET); fread((void*)(data+i*bih->biWidth), 1, bih->biWidth, fp); } fclose(fp); return 0; } /** *\fn int saveBitmap(const char *filename, const uint8 *data, BITMAPFILEHEADER *bfh, BITMAPINFOHEADER *bih, int cx, int cy, bool color) *\brief ͼļ *\param[in] const char * filename ļ *\param[in] const uint8 * data *\param[in] BITMAPFILEHEADER * bfh ͼļͷ *\param[in] BITMAPINFOHEADER * bih ͼϢͷ *\param[in] int cy ͼ *\param[in] int cy ͼ *\param[in] int color ǷDzɫ *\return int 0ɹ,ʧ */ int saveBitmap(const char *filename, const uint8 *data, BITMAPFILEHEADER *bfh, BITMAPINFOHEADER *bih, int cx, int cy, bool color) { if (NULL == filename || NULL == data || NULL == bfh || NULL == bih || NULL == cx || NULL == cy) return -1; // õһеֽ,4ֽڶ int lineBytes = (cx + 3) / 4 * 4; // ļͷ BITMAPFILEHEADER bfh_temp = *bfh; BITMAPINFOHEADER bih_temp = *bih; bfh_temp.bfSize = lineBytes * cy + 1078; bih_temp.biWidth = cx; bih_temp.biHeight = cy; bih_temp.biSizeImage = lineBytes * cy; // ɫ uint8 palatte[1024]; for(int i = 0; i < 256; i++) { if (1 == i && color) { palatte[i*4] =(unsigned char)255; palatte[i*4+1] =(unsigned char)0; palatte[i*4+2] =(unsigned char)0; palatte[i*4+3] =0; } else if (2 == i && color) { palatte[i*4] =(unsigned char)0; palatte[i*4+1] =(unsigned char)255; palatte[i*4+2] =(unsigned char)0; palatte[i*4+3] =0; } else if (3 == i && color) { palatte[i*4] =(unsigned char)0; palatte[i*4+1] =(unsigned char)0; palatte[i*4+2] =(unsigned char)255; palatte[i*4+3] =0; } else { palatte[i*4] =(unsigned char)i; palatte[i*4+1] =(unsigned char)i; palatte[i*4+2] =(unsigned char)i; palatte[i*4+3] =0; } } // ļ FILE *fp = fopen(filename, "wb"); if (NULL == fp) return -2; // дļͷ fwrite((void*)&bfh_temp, sizeof(bfh_temp), 1, fp); fwrite((void*)&bih_temp, sizeof(bih_temp), 1, fp); fwrite((void*)&palatte, sizeof(palatte), 1, fp); // жȡÿlineBytesֽ for (int i = 0; i < cy; i++) { fwrite((void*)(data+i*cx), 1, lineBytes, fp); } fclose(fp); return 0; }
true
f70a991159c8c740d4a091016d792387c61e1415
C++
Flkalas/configThreeLight
/src/portControl.cpp
UTF-8
5,766
2.671875
3
[]
no_license
/* * gpioControl.cpp * * Created on: Jul 29, 2015 * Author: odroid */ #include "portControl.h" int testGPIO(void){ initGPIO(); // Print GPX1 configuration register. printf("GPX1CON register : 0x%08x\n",*(unsigned int *)(gpioGPX + (0x0c20 >> 2))); // Set direction of GPX1.2 configuration register as out. configGPIO(PERIPHEREL_GPX,1,2,MODE_OUTPUT); printf("GPX1CON register : 0x%08x\n",*(unsigned int *)(gpioGPX + (0x0c20 >> 2))); while(1){ // GPX1.2 High writeGPIO(PERIPHEREL_GPX,1,2,GPIO_SET); printf("GPX1DAT register : 0x%08x\n",*(unsigned int *)(gpioGPX + (0x0c24 >> 2))); usleep(100); // GPX1.2 Low writeGPIO(PERIPHEREL_GPX,1,2,GPIO_RESET); printf("GPX1DAT register : 0x%08x\n",*(unsigned int *)(gpioGPX + (0x0c24 >> 2))); usleep(100); } return 0; } int testADC(void){ while(1){ cout << getADCvalue(0) << endl; usleep(500); } return 0; } int initGPIO(void){ int fd = openFileDiscriptor(); if(fd == -1){ return -1; } gpioGPX = mapMemory(fd,GPIO_GPX_CONFIG_BASE_ADDR); gpioGPA = mapMemory(fd,GPIO_GPA_CONFIG_BASE_ADDR); gpioGPB = mapMemory(fd,GPIO_GPB_CONFIG_BASE_ADDR); return 0; } int configGPIO(int peripherel, int indexMain, int indexSub, int mode){ if(int errorNo = checkGPIOIndex(peripherel,indexMain,indexSub)){ printf("Error: configGPIO Out of Index 0x%1X\n",errorNo); return -1; } if(checkGPIOMode(mode)){ printf("Error: configGPIO no mode like 0x%1X\n",mode); return -1; } volatile uint32_t* gpio = getAddrGPIO(peripherel); int offset = getConfigAddrOffset(peripherel, indexMain, indexSub); forceMemory(gpio,offset,GPIO_CONFIG_NUM_BITS,indexSub,mode); return 0; } int writeGPIO(int peripherel, int indexMain, int indexSub, int bit){ if(int errorNo = checkGPIOIndex(peripherel,indexMain,indexSub)){ printf("Error: setGPIO Out of Index 0x%1X\n",errorNo); return -1; } if(bit == 0){ bit = 0; } else{ bit = 1; } volatile uint32_t* gpio = getAddrGPIO(peripherel); int offset = getDataAddrOffset(peripherel, indexMain, indexSub); forceMemory(gpio,offset,GPIO_DATA_NUM_BITS,indexSub,bit); return 0; } int getADCvalue(int index){ if(checkADCIndex(index)){ cout << "Error: getADCvalue Out of Index " << index << endl; } char path[MAX_STR_LEN]; sprintf(path,"/sys/bus/iio/devices/iio:device0/in_voltage%d_raw",index); char result[MAX_STR_LEN]; int fd = open(path, O_RDONLY); read(fd,result,MAX_STR_LEN); close(fd); return atoi(result); } int openFileDiscriptor(void){ int fd; if((fd = open ("/dev/mem", O_RDWR | O_SYNC) ) < 0){ printf("Unable to open /dev/mem\n"); return -1; } return fd; } unsigned int* mapMemory(int fd, int addrBase){ // int addrBase = 0; // // switch(peripherel){ // case PERIPHEREL_GPX: // addrBase = GPIO_GPX_CONFIG_BASE_ADDR; // break; // case PERIPHEREL_GPA: // addrBase = GPIO_GPA_CONFIG_BASE_ADDR; // break; // case PERIPHEREL_GPB: // addrBase = GPIO_GPB_CONFIG_BASE_ADDR; // break; // default: // return NULL; // } unsigned int* gpio = (unsigned int*)mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, addrBase); if(gpio < 0){ printf("Mmap failed.\n"); return NULL; } return gpio; } int forceMemory(volatile uint32_t* base,int offset,int numbits,int indexSub,int data){ ResetRegister(base,offset,numbits,indexSub); SetRegister(base,offset,numbits,indexSub,data); return 0; } int getConfigAddrOffset(int peripherel, int indexMain, int indexSub){ switch(peripherel){ case PERIPHEREL_GPX: switch(indexMain){ case 1: return GPIO_GPX_1_CONFIG_ADDR_OFFSET; case 2: return GPIO_GPX_2_CONFIG_ADDR_OFFSET; case 3: return GPIO_GPX_3_CONFIG_ADDR_OFFSET; } break; case PERIPHEREL_GPA: return GPIO_GPA_2_CONFIG_ADDR_OFFSET; case PERIPHEREL_GPB: return GPIO_GPB_3_CONFIG_ADDR_OFFSET; } return 0; } int getDataAddrOffset(int peripherel, int indexMain, int indexSub){ switch(peripherel){ case PERIPHEREL_GPX: switch(indexMain){ case 1: return GPIO_GPX_1_DATA_ADDR_OFFSET; case 2: return GPIO_GPX_2_DATA_ADDR_OFFSET; case 3: return GPIO_GPX_3_DATA_ADDR_OFFSET; } break; case PERIPHEREL_GPA: return GPIO_GPA_2_DATA_ADDR_OFFSET; case PERIPHEREL_GPB: return GPIO_GPB_3_DATA_ADDR_OFFSET; } return 0; } volatile uint32_t* getAddrGPIO(int peripherel){ switch(peripherel){ case PERIPHEREL_GPX: return gpioGPX; case PERIPHEREL_GPA: return gpioGPA; case PERIPHEREL_GPB: return gpioGPB; default: return NULL; } } int checkADCIndex(int index){ return (index != 0 && index != 3); } int checkGPIOIndex(int peripherel, int indexMain, int indexSub){ switch(peripherel){ case PERIPHEREL_GPX: if(indexMain > 0 && indexMain < 4){ switch(indexMain){ case 1: if(indexSub > 1 && indexSub < 8 && indexSub != 4){ return 0; } else{ return OUT_OF_INDEX_SUB; } case 2: if(indexSub > -1 && indexSub < 2 && indexSub > 3 && indexSub < 8){ return 0; } else{ return OUT_OF_INDEX_SUB; } case 3: if(indexSub == 1){ return 0; } else{ return OUT_OF_INDEX_SUB; } } } return OUT_OF_INDEX_MAIN; case PERIPHEREL_GPA: if(indexMain == 2){ if(indexSub > 5 && indexSub < 8){ return 0; } else{ return OUT_OF_INDEX_SUB; } } return OUT_OF_INDEX_MAIN; case PERIPHEREL_GPB: if(indexMain == 3){ if(indexSub > 1 && indexSub < 4){ return 0; } else{ return OUT_OF_INDEX_SUB; } } return OUT_OF_INDEX_MAIN; default: return OUT_OF_INDEX_PERIPHEREL; } } int checkGPIOMode(int mode){ if(mode == MODE_INPUT){ return 0; } else if(mode == MODE_OUTPUT){ return 0; } else if(mode == MODE_TRACE_DATA){ return 0; } else if(mode == MODE_EXTERNAL_INTERRUPT){ return 0; } return NONE_MODE; }
true
0e3efd0579769df481007c919a8eb0a031ed5ed1
C++
ayushbansal07/ACM
/resources/extended_euclid.cpp
UTF-8
487
3.109375
3
[]
no_license
#include<bits/stdc++.h> #define F first #define S second #define mp make_pair using namespace std; pair<int,int> extendedEuclid(int a,int b) { if(b==0) return mp(1,0); else { pair<int,int> p = extendedEuclid(b,a%b); int temp = p.F; p.F=p.S; p.S=temp-(a/b)*p.S; return p; } } int main() { int a,b; cin>>a>>b; pair<int,int> res = extendedEuclid(a,b); cout<<res.F<<' '<<res.S<<endl; }
true
9353cbbd82856b3855f6fb68d35b9c78fc39bc87
C++
nealwu/UVa
/volume008/846 - Steps.cpp
UTF-8
376
2.65625
3
[]
no_license
#include <stdio.h> #include <math.h> int main() { int t, x, y, L; scanf("%d", &t); while(t--) { scanf("%d %d", &x, &y); L = y-x; int steps = 0, n = (int)sqrt(L); steps = n; L -= n*(n+1)/2; while(L > 0) { while(n*(n+1)/2 > L) n--; if(n*(n+1)/2 == L) L = 0, steps += n; else L -= n, steps ++; } printf("%d\n", steps); } return 0; }
true
f96de8e396a4635eaac126d14474f2b3e4c15306
C++
RoboticsLabURJC/2017-tfm-jorge_vela
/obj_detect/include/channels/ChannelsExtractorACF.h
UTF-8
3,368
2.78125
3
[]
no_license
/** ------------------------------------------------------------------------ * * @brief Agregated Channel Features (ACF) Extractor * @author Jose M. Buenaposada (josemiguel.buenaposada@urjc.es) * @date 2020/09/25 * * ------------------------------------------------------------------------ */ #ifndef CHANNELS_EXTRACTOR_ACF #define CHANNELS_EXTRACTOR_ACF #include <opencv2/opencv.hpp> #include <detectors/ClassifierConfig.h> #include <channels/ChannelsExtractorLUV.h> #include <channels/ChannelsExtractorGradMag.h> #include <channels/ChannelsExtractorGradHist.h> #include <vector> #include <string> /** ------------------------------------------------------------------------ * * @brief Class for ACF extraction: LUV, Gradient and HOG. * @author Jose M. Buenaposada (josemiguel.buenaposada@urjc.es) * @date 2020/09/03 * * ------------------------------------------------------------------------ */ class ChannelsExtractorACF { public: /** * This constructor sets the parameters for computing the ACF features. * * @param clf Configuration variables for ACF computation. * @param postprocess_channels postprocess or not the ACF channels (to be used in ChannelsPyramid). * @param impl_type By now the implementations are "pdollar" and "opencv". */ ChannelsExtractorACF ( ClassifierConfig clf, bool postprocess_channels = true, std::string impl_type = "pdollar" ); /** * This method computes all the Piotr Dollar's Aggregated Channels Features as cv::Mat from an input image: * - 3 color chanels in the LUV color space * - 1 Gradient Magnitude channel * - 6 HOG channels (6 orientations). * * @param src input image * @return std::vector<cv::Mat> vector with all the channels as cv:Mat. */ std::vector<cv::Mat> extractFeatures ( cv::Mat img ); /** * This method computes all the Piotr Dollar's Aggregated Channels Features as cv::Mat from an input image: * - 3 color chanels in the LUV color space * - 1 Gradient Magnitude channel * - 6 HOG channels (6 orientations). * * @param src input image as UMat * @return std::vector<cv::UMat> vector with all the channels as cv:Mat. */ std::vector<cv::UMat> extractFeatures ( cv::UMat img ); int getNumChannels() { return 10; } void postProcessChannels ( const std::vector<cv::Mat>& acf_channels_no_postprocessed, // input std::vector<cv::Mat>& postprocessedChannels // output ); void postProcessChannels ( const std::vector<cv::UMat>& acf_channels_no_postprocessed, // input std::vector<cv::UMat>& postprocessedChannels // output ); private: void processChannel ( cv::Mat& img, cv::BorderTypes, int x, int y ); void processChannel ( cv::UMat& img, cv::BorderTypes, int x, int y ); std::string m_impl_type; int m_shrink; std::string m_color_space; cv::Size m_padding; bool m_postprocess_channels; int m_gradientMag_normRad; float m_gradientMag_normConst; int m_gradientHist_binSize; int m_gradientHist_nOrients; int m_gradientHist_softBin; int m_gradientHist_full; ClassifierConfig m_clf; std::shared_ptr<ChannelsExtractorGradMag> m_pGradMagExtractor; std::shared_ptr<ChannelsExtractorGradHist> m_pGradHistExtractor; std::shared_ptr<ChannelsExtractorLUV> m_pLUVExtractor; }; #endif
true
354b0bd0f6b356a281e4a951d7fda94267544b3c
C++
MatejFranceskin/UDPRelay
/main.cpp
UTF-8
986
2.78125
3
[ "MIT" ]
permissive
#include "UDPRelay.h" #include <iostream> #include <signal.h> #include <unistd.h> #include <sys/signalfd.h> static void wait_for_termination_signal() { sigset_t sigs; sigemptyset(&sigs); sigaddset(&sigs, SIGINT); sigaddset(&sigs, SIGTERM); int sigfd = ::signalfd(-1, &sigs, SFD_CLOEXEC); struct signalfd_siginfo si; while (::read(sigfd, &si, sizeof(si)) == 0) {} } int main(int argc, char *argv[]) { if (argc == 4) { } else { std::cout << "Usage: UDPRelay \"source port\" \"destination ip\" \"destination port\"" << std::endl; return -1; } uint16_t source_port = std::stoi(argv[1]); std::string dest_ip = argv[2]; uint16_t dest_port = std::stoi(argv[3]); UDPRelay relay(dest_ip, dest_port, source_port); if (relay.start()) { wait_for_termination_signal(); relay.stop(); } else { std::cout << "Failed to start UDP relay" << std::endl; return -1; } return 0; }
true
1c2e7601bc5b3f6b385c008d9a6a81740efd8035
C++
Mumsfilibaba/3D-Programming-Project
/Assignment3(Project)/Source/OpenGL/GLTextureCube.cpp
UTF-8
7,851
2.640625
3
[]
no_license
#include <iostream> #include "..\Core\Parsing\LoadTexture.h" #include "GLTextureCube.h" namespace Graphics { GLTextureCube::GLTextureCube(const GLDeviceContext* const context) : m_Context(context), m_Filenames(nullptr), m_Sampler(), m_VSSlot(0), m_PSSlot(0), m_HSSlot(0), m_DSSlot(0), m_GSSlot(0), m_Texture(0), m_FileCount(0), m_Width(0), m_Height(0), m_MipLevels(0), m_CrossType(TEXTURECROSS_UNKNOWN), m_Format(TEXTUREFORMAT_UNKNOWN), m_Filepath() { } GLTextureCube::GLTextureCube(const GLDeviceContext* const context, const std::string filenames[6], const std::string& filepath, TEXTUREFORMAT format) : m_Context(context), m_Filenames(nullptr), m_Sampler(), m_VSSlot(0), m_PSSlot(0), m_HSSlot(0), m_DSSlot(0), m_GSSlot(0), m_Texture(0), m_FileCount(0), m_Width(0), m_Height(0), m_MipLevels(0), m_CrossType(TEXTURECROSS_UNKNOWN), m_Format(TEXTUREFORMAT_UNKNOWN), m_Filepath() { Create(filenames, filepath, format); } GLTextureCube::GLTextureCube(const GLDeviceContext* const context, const std::string* const filenames, uint32 len, const std::string& filepath, TEXTURECROSS cross, TEXTUREFORMAT format) : m_Context(context), m_Filenames(nullptr), m_Sampler(), m_VSSlot(0), m_PSSlot(0), m_HSSlot(0), m_DSSlot(0), m_GSSlot(0), m_Texture(0), m_FileCount(0), m_Width(0), m_Height(0), m_MipLevels(0), m_CrossType(TEXTURECROSS_UNKNOWN), m_Format(TEXTUREFORMAT_UNKNOWN), m_Filepath() { Create(filenames, len, filepath, cross, format); } GLTextureCube::~GLTextureCube() { Release(); } bool GLTextureCube::Create(const std::string filenames[6], const std::string& filepath, TEXTUREFORMAT format) { //Width and height uint16 width = 0; uint16 height = 0; //Set miplevels m_MipLevels = 1; //Miplevels * 6 is the amount of faces void** faces = new void*[6]; //Set filenames and path m_Filenames = new std::string[6]; m_FileCount = 6; m_Filepath = filepath; //Load files for (int32 i = 0; i < 6; i++) { m_Filenames[i] = filenames[i]; faces[i] = nullptr; faces[i] = load_image(m_Filenames[i], m_Filepath, width, height, format); if (faces[i] == nullptr) { std::cout << "ERROR: Could not load file '" << m_Filepath << '/' << m_Filenames[i] << '\n'; return false; } } //Create bool result = Create(faces, width, height, format); //Release Data for (uint32 i = 0; i < 6; i++) { ReleaseBuffer_S(faces[i]); } ReleaseBuffer_S(faces); return result; } bool GLTextureCube::Create(const std::string* const filenames, uint32 len, const std::string& filepath, TEXTURECROSS cross, TEXTUREFORMAT format) { //Set miplevels m_MipLevels = len; //Set filenames and path m_FileCount = len; m_Filenames = new std::string[m_FileCount]; m_Filepath = filepath; //Width and height uint16 width = 0; uint16 height = 0; uint16 srcWidth = 0; uint16 srcHeight = 0; //Set crosstype m_CrossType = cross; //Allocate array for the faces, (Miplevels * 6) is the amount of faces void** faces = new void*[m_MipLevels * 6u]; //Set all faces to zero for (uint32 i = 0; i < (m_MipLevels * 6u); i++) faces[i] = nullptr; //Load files byte* crossTexture = nullptr; byte** iter = (byte**)faces; for (uint32 i = 0; i < m_FileCount; i++) { //Set filename m_Filenames[i] = filenames[i]; //Load crossTexture = load_image(m_Filenames[i], m_Filepath, srcWidth, srcHeight, format); if (crossTexture == nullptr) { std::cout << "ERROR: Could not load file '" << m_Filepath << '/' << m_Filenames[i] << '\n'; return false; } //Extract faces cubemap_to_faces(crossTexture, &iter, srcWidth, srcHeight, width, height, m_CrossType, format); //Release crosstexture ReleaseBuffer_S(crossTexture); //Move to next set of faces iter += 6; } //Get the first mips size for (int32 i = 0; i < (int32)(m_MipLevels - 1); i++) { width = width * 2; height = height * 2; } //Create bool result = Create(faces, width, height, format); //Release Data for (uint32 i = 0; i < (m_MipLevels * 6u); i++) { ReleaseBuffer_S(faces[i]); } ReleaseBuffer_S(faces); return result; } bool GLTextureCube::Create(const void* const * const faces, uint16 width, uint16 height, TEXTUREFORMAT format) { //Set size m_Width = width; m_Height = height; //Create and bind texture GL_Call(glGenTextures(1, &m_Texture)); GL_Call(glBindTexture(GL_TEXTURE_CUBE_MAP, m_Texture)); //Set format m_Format = format; uint32 gltype = gl_convert_texturetype(m_Format); uint32 glformat = gl_convert_textureformat(m_Format); uint32 glinternalFormat = gl_convert_textureinternalformat(m_Format); //To store the new size for the different mips uint16 wi = m_Width; uint16 he = m_Height; //Set mipelevel-count in OpenGL GL_Call(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0)); GL_Call(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, m_MipLevels - 1)); //Set data for (int32 i = 0; i < (int32)m_MipLevels; i++) { GL_Call(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, i, glinternalFormat, wi, he, 0, glformat, gltype, faces[(i * 6) + 0])); GL_Call(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, i, glinternalFormat, wi, he, 0, glformat, gltype, faces[(i * 6) + 1])); GL_Call(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, i, glinternalFormat, wi, he, 0, glformat, gltype, faces[(i * 6) + 2])); GL_Call(glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, i, glinternalFormat, wi, he, 0, glformat, gltype, faces[(i * 6) + 3])); GL_Call(glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, i, glinternalFormat, wi, he, 0, glformat, gltype, faces[(i * 6) + 4])); GL_Call(glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, i, glinternalFormat, wi, he, 0, glformat, gltype, faces[(i * 6) + 5])); wi = wi / 2; he = he / 2; } //Set samplersettings SetSamplerSettings(SamplerSettings()); GL_Call(glBindTexture(GL_TEXTURE_CUBE_MAP, 0)); return true; } void GLTextureCube::Bind(uint8 slot, SHADER shader) const { GL_Call(glActiveTexture(gl_active_textureslot(slot, shader))); GL_Call(glBindTexture(GL_TEXTURE_CUBE_MAP, m_Texture)); } void GLTextureCube::Unbind(uint8 slot, SHADER shader) const { GL_Call(glActiveTexture(gl_active_textureslot(slot, shader))); GL_Call(glBindTexture(GL_TEXTURE_CUBE_MAP, 0)); } void GLTextureCube::BindVS(uint32 slot) const { m_VSSlot = slot; Bind(m_VSSlot, SHADER_VERTEX); } void GLTextureCube::BindPS(uint32 slot) const { m_PSSlot = slot; Bind(m_PSSlot, SHADER_PIXEL); } void GLTextureCube::BindHS(uint32 slot) const { m_HSSlot = slot; Bind(m_HSSlot, SHADER_HULL); } void GLTextureCube::BindDS(uint32 slot) const { m_DSSlot = slot; Bind(m_DSSlot, SHADER_DOMAIN); } void GLTextureCube::BindGS(uint32 slot) const { m_GSSlot = slot; Bind(m_GSSlot, SHADER_GEOMETRY); } void GLTextureCube::UnbindVS() const { Unbind(m_VSSlot, SHADER_VERTEX); m_VSSlot = 0; } void GLTextureCube::UnbindPS() const { Unbind(m_PSSlot, SHADER_PIXEL); m_PSSlot = 0; } void GLTextureCube::UnbindGS() const { Unbind(m_GSSlot, SHADER_GEOMETRY); m_GSSlot = 0; } void GLTextureCube::UnbindDS() const { Unbind(m_DSSlot, SHADER_DOMAIN); m_DSSlot = 0; } void GLTextureCube::UnbindHS() const { Unbind(m_HSSlot, SHADER_HULL); m_HSSlot = 0; } void GLTextureCube::SetSamplerSettings(const SamplerSettings& setting) const { GL_Call(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS)); gl_set_sampler(m_Texture, GL_TEXTURE_CUBE_MAP, setting, (m_MipLevels > 1)); } void GLTextureCube::Release() { //Release GLTexture if (glIsTexture(m_Texture)) { GL_Call(glDeleteTextures(1, &m_Texture)); } //Release filenames ReleaseBuffer_S(m_Filenames); } }
true
faa34fe04a7a02c8c7db77cd0e12f1b50b952443
C++
ficusss/Toxic-Comment-Classification
/src/Cores/Core.h
UTF-8
2,185
2.8125
3
[ "MIT" ]
permissive
#include "../../includes/json.hpp" #include "../Classification/Classifyer.h" #include "../Classification/BOW.h" #define LABELS_COUNT 5 using json = nlohmann::json; using labels = std::array<bool, 5>; using labeledText = std::vector<std::pair<textVec, labels>>; /** namespace tcc @brief Пространство имен tcc */ namespace tcc { /** @brief Интерфейс классов ядра для классификации "недоброжелательности" текста */ class Core { public: /** @brief Виртуальная функция классификации "недоброжелательности" текста @param t текст в виде вектора слов */ virtual std::vector<double> run(textVec& t) const = 0; /** @brief Запуск обучения */ virtual void trainLoop() = 0; virtual ~Core() {}; }; /** @brief Класс - ядро для классификации "недоброжелательности" текста */ class RandomCore : public Core { private: std::vector<std::shared_ptr<Classifyer>> _model; public: /** @brief Конструктор класса @param model вектор классификаторов, задающих используемую модель */ RandomCore(std::vector<std::shared_ptr<Classifyer>> model) { _model = model; } /** @brief Конструктор класса @param b мешок слов, на основе которого будет построен классификатор @param tags_count количество категорий в тексте */ RandomCore(std::shared_ptr<BOW> b, int tags_count) { for (auto i = 0; i < tags_count; i++) { _model.push_back(std::shared_ptr<Classifyer>(new NaiveBayesClassifyer(b, i))); } } RandomCore() = default; ~RandomCore() override = default; /** @brief Функция классификации "недоброжелательности" текста @param t текст для анализа */ std::vector<double> run(textVec& t) const override; void trainLoop() override { for (auto el : _model) el->train(); } }; }
true
9553c27aae04a45680da85efc294ba820c4d3e1d
C++
ereret2/leetcode-answer
/subset/22.cpp
UTF-8
1,136
3.3125
3
[]
no_license
class parenthesesString { public: string str; int openCount = 0; // open parentheses count int closeCount = 0; // close parentheses count parenthesesString(const string &s, int openCount, int closeCount) { this->str = s; this->openCount = openCount; this->closeCount = closeCount; } }; class Solution { public: vector<string> generateParenthesis(int n) { vector<string> res; queue<parenthesesString> queue; queue.push(parenthesesString("(", 1, 0)); while (!queue.empty()) { parenthesesString tmp = queue.front(); queue.pop(); if (tmp.openCount == n && tmp.closeCount == n) { res.push_back(tmp.str); } else { if (tmp.openCount < n) { queue.push(parenthesesString(tmp.str + "(", tmp.openCount + 1, tmp.closeCount)); } if (tmp.openCount > tmp.closeCount) { queue.push(parenthesesString(tmp.str + ")", tmp.openCount, tmp.closeCount + 1)); } } } return res; } };
true
bc867672b5dad2ccbaff3e608be50dd0be9c9aa4
C++
Hao-zy/Spike-Masq
/VS/Spike-DataSet-LIB/VariableState.hpp
UTF-8
4,300
3.09375
3
[ "MIT" ]
permissive
//filename: DataSet/DataSetLib2/VariableState.hpp #pragma once #include <string> #include <set> #include <map> #include <iterator> #include "DataSetTypes.hpp" #include "Variable.hpp" namespace spike { namespace dataset { class VariableState { public: VariableState() = default; // simple constructor VariableState(const VariableState& other) = default; // copy constructor VariableState(VariableState&& other) = delete; // move constructor VariableState& operator=(const VariableState& rhs) = default; // copy assignment operator VariableState& operator=(VariableState&& rhs) = delete; // move assignment operator void setVariableValue(const VariableId variableId, const Variable::PropertyName propertyName, const std::string& propertyValue) { if (this->hasVariableId(variableId)) { // std::cout << " VariableState::setVariableValue() updating existing variableId " << variableId << std::endl; this->variables_.at(variableId).setVariableValue(propertyName, propertyValue); } else { // std::cout << " VariableState::setVariableValue() inserting new variableId " << variableId << std::endl; this->createVariableId(variableId, propertyName, propertyValue); } } const std::string getVariableValue(const VariableId variableId, const Variable::PropertyName propertyName) const { if (this->hasVariableId(variableId)) { return this->variables_.at(variableId).getVariableValue(propertyName); } throw std::runtime_error("variableId not present"); } bool hasVariableValue(const VariableId variableId, const Variable::PropertyName propertyName) const { if (this->hasVariableId(variableId)) { return this->variables_.at(variableId).hasVariableValue(propertyName); } throw std::runtime_error("variableId not present"); } unsigned int getNumberOfVariables() const { return static_cast<unsigned int>(this->variables_.size()); } const std::set<VariableId> getVariableIds() const { //Speed consideration: create a member field with the returning set instead of creating it on the fly std::set<VariableId> s; for (std::map<VariableId, Variable>::const_iterator it = this->variables_.begin(); it != this->variables_.end(); ++it) { s.insert(it->first); } return s; } bool hasVariableId(const VariableId variableId) const { return (this->variables_.find(variableId) != this->variables_.end()); } std::string toString() const { std::ostringstream oss; const std::set<VariableId> variableIds = this->getVariableIds(); oss << "----------------"; for (int i = 0; i < static_cast<int>(variableIds.size()); i++) { oss << "--------"; } oss << std::endl << "variableId:\t"; for (const VariableId& variableId : variableIds) { oss << variableId << "\t"; } oss << std::endl << "Used:\t\t"; for (const VariableId& variableId : variableIds) { oss << this->getVariableValue(variableId, Variable::PropertyName::Used) << "\t"; } oss << std::endl << "Description:\t"; for (const VariableId& variableId : variableIds) { oss << this->getVariableValue(variableId, Variable::PropertyName::Description) << "\t"; } oss << std::endl << "VariableType:\t"; for (const VariableId& variableId : variableIds) { oss << this->getVariableValue(variableId, Variable::PropertyName::VariableType) << "\t"; } oss << std::endl << "VariableGroup:\t"; for (const VariableId& variableId : variableIds) { oss << this->getVariableValue(variableId, Variable::PropertyName::VariableGroup) << "\t"; } oss << std::endl; return oss.str(); } protected: virtual ~VariableState() = default; private: std::map<VariableId, Variable> variables_; void createVariableId(const VariableId variableId, const Variable::PropertyName propertyName, const std::string& propertyValue) { Variable variableTmp; variableTmp.setVariableValue(propertyName, propertyValue); // tell make_pair that variableTmp is indeed temporary (with move) such that make_pair can use swap semantics this->variables_.insert(std::make_pair(variableId, std::move(variableTmp))); } }; } }
true
4a1fca0c96b533238e55c8ef63cdb4b16709d0d3
C++
chfeder/turbulence_generator
/HDFIO.h
UTF-8
43,430
2.890625
3
[]
no_license
#ifndef HDFIO_H #define HDFIO_H #include <hdf5.h> #include <iostream> #include <vector> #include <map> #include <algorithm> #include <string> #include <cstring> #include <cassert> // we use H5_HAVE_PARALLEL defined in hdf5.h to signal whether we have MPI support or not #ifdef H5_HAVE_PARALLEL #include <mpi.h> #else #ifndef MPI_Comm #define MPI_Comm int #endif #ifndef MPI_COMM_NULL #define MPI_COMM_NULL 0 #endif #ifndef MPI_COMM_WORLD #define MPI_COMM_WORLD 0 #endif #endif namespace NameSpaceHDFIO { static const unsigned int flash_str_len = 79; // string length for FLASH scalars and runtime parameters I/O template<typename> struct FlashScalarsParametersStruct; // structure for FLASH scalars and runtime parameters I/O template<> struct FlashScalarsParametersStruct<int> { char name[flash_str_len]; int value; }; template<> struct FlashScalarsParametersStruct<double> { char name[flash_str_len]; double value; }; template<> struct FlashScalarsParametersStruct<bool> { char name[flash_str_len]; bool value; }; template<> struct FlashScalarsParametersStruct<std::string> { char name[flash_str_len]; char value[flash_str_len]; }; // FLASHPropAssign template function; applies to string case (so we do a string-copy from string to c_str) template<typename T, typename Td> inline void FLASHPropAssign(T val, Td * data) { strcpy(*data, val.c_str()); }; // FLASHPropAssign template functions that apply to int, double, bool cases template<> inline void FLASHPropAssign<int> (int val, int * data) { *data = val; }; // simply assign template<> inline void FLASHPropAssign<double> (double val, double * data) { *data = val; }; // simply assign template<> inline void FLASHPropAssign<bool> (bool val, bool * data) { *data = val; }; // simply assign } /** * HDFIO class * * This class represents an HDF5 object/file and provides basic HDF operations like opening a file, * reading data form a dataset of that file, creating new HDF files and datasets and writing datasets into a file. * There are also some functions for getting and setting different attributes, like the dimensionaltity of the HDF * dataset to be written or the datasetnames inside an HDF5 file. * * @author Christoph Federrath * @version 2007-2022 */ class HDFIO { private: std::string ClassSignature, Filename; // class signature and HDF5 filename int Rank; // dimensionality of the field hid_t File_id, Dataset_id, Dataspace_id; // HDF5 stuff hsize_t HDFSize, HDFDims[4]; // HDF5 stuff; can maximally handle 4D datasets (but who would ever want more?) herr_t HDF5_status, HDF5_error; // HDF5 stuff int Verbose; // verbose level for printing to stdout /// Constructors public: HDFIO(void) { // empty constructor, so we can define a global HDFIO object in application code Constructor("", 'r', MPI_COMM_NULL, 0); }; public: HDFIO(const int verbose) { Constructor("", 'r', MPI_COMM_NULL, verbose); }; public: HDFIO(const std::string filename) { Constructor(filename, 'r', MPI_COMM_NULL, 1); }; public: HDFIO(const std::string filename, const int verbose) { Constructor(filename, 'r', MPI_COMM_NULL, verbose); }; public: HDFIO(const std::string filename, const char read_write_char) { if (read_write_char == 'w') Constructor(filename, read_write_char, MPI_COMM_WORLD, 1); else Constructor(filename, read_write_char, MPI_COMM_NULL, 1); }; public: HDFIO(const std::string filename, const char read_write_char, const int verbose) { if (read_write_char == 'w') Constructor(filename, read_write_char, MPI_COMM_WORLD, verbose); else Constructor(filename, read_write_char, MPI_COMM_NULL, verbose); }; /// Destructor public: ~HDFIO() { if (Verbose > 1) std::cout<<"HDFIO: destructor called."<<std::endl; }; private: void Constructor(const std::string filename, const char read_write_char, MPI_Comm comm, const int verbose) { Filename = filename; // HDF5 filename Verbose = verbose; // verbose (can be 0: no stdout, 1: default output, 2: more output) ClassSignature = "HDFIO: "; // class signature, when this class is printing to stdout Rank = 1; // dimensionality 1 (e.g., x only) File_id = 0; // HDF5 file id 0 Dataset_id = 0; // HDF5 dataset id 0 Dataspace_id = 0; // HDF5 data space id 0 HDFSize = 0; // HDF5 buffer size 0 HDF5_status = 0; // HDF5 status 0 HDF5_error = -1; // HDF5 error -1 for (unsigned int i = 0; i < 4; i++) HDFDims[i] = 0; // set Dimensions to (0,0,0,0) if (Filename != "") this->open(Filename, read_write_char, comm); // open file if provided in constructor }; // get function signature for printing to stdout private: std::string FuncSig(const std::string func_name) { return ClassSignature+func_name+": "; }; /** * open an HDF5 file in serial mode * @param Filename HDF5 filename * @param read_write_char 'r': read only flag, 'w': write flag */ public: void open(const std::string Filename, const char read_write_char) { this->open(Filename, read_write_char, MPI_COMM_NULL); // open in serial mode }; /** * open an HDF5 file (overloaded) * @param Filename HDF5 filename * @param read_write_char 'r': read only flag, 'w': write flag * @param comm: MPI communicator for parallel file I/O */ public: void open(const std::string Filename, const char read_write_char, MPI_Comm comm) { this->Filename = Filename; hid_t plist_id = H5P_DEFAULT; #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { plist_id = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fapl_mpio(plist_id, comm, MPI_INFO_NULL); assert( HDF5_status != HDF5_error ); } #endif switch (read_write_char) { case 'r': { // open HDF5 file in read only mode File_id = H5Fopen(Filename.c_str(), H5F_ACC_RDONLY, plist_id); assert( File_id != HDF5_error ); break; } case 'w': { // open HDF5 file in write mode File_id = H5Fopen(Filename.c_str(), H5F_ACC_RDWR, plist_id); assert( File_id != HDF5_error ); break; } default: { // open HDF5 file in read only mode File_id = H5Fopen(Filename.c_str(), H5F_ACC_RDONLY, plist_id); assert( File_id != HDF5_error ); break; } } #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) H5Pclose(plist_id); #endif }; /** * close HDF5 file */ public: void close(void) { // close HDF5 file HDF5_status = H5Fclose(File_id); assert( HDF5_status != HDF5_error ); }; /** * read data from a dataset * @param *DataBuffer pointer to double/float/int array to which data is to be written * @param Datasetname datasetname * @param DataType (i.e. H5T_STD_I32LE) */ public: void read(void* const DataBuffer, const std::string Datasetname, const hid_t DataType) { this->read(DataBuffer, Datasetname, DataType, MPI_COMM_NULL); // serial mode }; /** * read data from a dataset * @param *DataBuffer pointer to double/float/int array to which data is to be written * @param Datasetname datasetname * @param DataType (i.e. H5T_STD_I32LE) * @param comm: MPI communicator for parallel file I/O */ public: void read(void* const DataBuffer, const std::string Datasetname, const hid_t DataType, MPI_Comm comm) { // get dimensional information from dataspace and update HDFSize this->getDims(Datasetname); // open dataset Dataset_id = H5Dopen(File_id, Datasetname.c_str(), H5P_DEFAULT); assert( Dataset_id != HDF5_error ); // open dataspace (to get dimensions) Dataspace_id = H5Dget_space(Dataset_id); assert( Dataspace_id != HDF5_error ); /// create property list for collective dataset i/o hid_t plist_id = H5P_DEFAULT; #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { plist_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE); } #endif // read buffer /memspaceid //filespaceid HDF5_status = H5Dread(Dataset_id, DataType, H5S_ALL, H5S_ALL, plist_id, DataBuffer); assert( HDF5_status != HDF5_error ); #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { HDF5_status = H5Pclose(plist_id); assert( HDF5_status != HDF5_error ); } #endif HDF5_status = H5Sclose(Dataspace_id); assert( HDF5_status != HDF5_error ); HDF5_status = H5Dclose(Dataset_id); assert( HDF5_status != HDF5_error ); }; // read /** * read attribute from a dataset * @param *DataBuffer pointer to double/float/int array to which data is to be written * @param Datasetname name of dataset * @param Attributename name of attribute to be read * @param DataType (i.e. H5T_STD_I32LE) */ public: void read_attribute(void* const DataBuffer, const std::string Datasetname, const std::string Attributename, const hid_t DataType) { this->read_attribute(DataBuffer, Datasetname, Attributename, DataType, MPI_COMM_NULL); // serial mode }; /** * read attribute from a dataset * @param *DataBuffer pointer to double/float/int array to which data is to be written * @param Datasetname name of dataset * @param Attributename name of attribute to be read * @param DataType (i.e. H5T_STD_I32LE) * @param comm: MPI communicator for parallel file I/O */ public: void read_attribute(void* const DataBuffer, const std::string Datasetname, const std::string Attributename, const hid_t DataType, MPI_Comm comm) { // open dataset Dataset_id = H5Dopen(File_id, Datasetname.c_str(), H5P_DEFAULT); assert( Dataset_id != HDF5_error ); /// create property list for collective dataset i/o hid_t plist_id = H5P_DEFAULT; #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { plist_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE); } #endif /// open attribute hid_t attr_id = H5Aopen(Dataset_id, Attributename.c_str(), plist_id); /// read attribute HDF5_status = H5Aread(attr_id, DataType, DataBuffer); assert( HDF5_status != HDF5_error ); #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { HDF5_status = H5Pclose(plist_id); assert( HDF5_status != HDF5_error ); } #endif HDF5_status = H5Aclose(attr_id); assert( HDF5_status != HDF5_error ); HDF5_status = H5Dclose(Dataset_id); assert( HDF5_status != HDF5_error ); }; // read_attribute /** * read a slab of data from a dataset (overloaded) * @param *DataBuffer pointer to double/float/int array to which data is to be written * @param Datasetname datasetname * @param DataType (i.e. H5T_STD_I32LE) * @param offset (offset array) * @param count (count array, i.e. the number of cells[dim] to be selected) * @param out_rank (rank of the output array selected) * @param out_offset (output offset array) * @param out_count (output count array, i.e. the number of cells[dim] in output) */ public: void read_slab( void* const DataBuffer, const std::string Datasetname, const hid_t DataType, const hsize_t offset[], const hsize_t count[], const hsize_t out_rank, const hsize_t out_offset[], const hsize_t out_count[]) { /// simply set total_out_count = out_count, in which case we selected a hyperslab that fits completely into the /// total size of the output array. Use the overloaded function below, if output goes into an offset hyperslab this->read_slab(DataBuffer, Datasetname, DataType, offset, count, out_rank, out_offset, out_count, out_count); }; /** * read a slab of data from a dataset (overloaded) * @param *DataBuffer pointer to double/float/int array to which data is to be written * @param Datasetname datasetname * @param DataType (i.e. H5T_STD_I32LE) * @param offset (offset array) * @param count (count array, i.e. the number of cells[dim] to be selected) * @param out_rank (rank of the output array selected) * @param out_offset (output offset array) * @param out_count (output count array, i.e. the number of cells[dim] in output) * @param comm: MPI communicator for parallel file I/O */ public: void read_slab( void* const DataBuffer, const std::string Datasetname, const hid_t DataType, const hsize_t offset[], const hsize_t count[], const hsize_t out_rank, const hsize_t out_offset[], const hsize_t out_count[], MPI_Comm comm) { /// simply set total_out_count = out_count, in which case we selected a hyperslab that fits completely into the /// total size of the output array. Use the overloaded function below, if output goes into an offset hyperslab this->read_slab(DataBuffer, Datasetname, DataType, offset, count, out_rank, out_offset, out_count, out_count, comm); }; /** * read a slab of data from a dataset * @param *DataBuffer pointer to double/float/int array to which data is to be written * @param Datasetname datasetname * @param DataType (i.e. H5T_STD_I32LE) * @param offset (offset array) * @param count (count array, i.e. the number of cells[dim] to be selected) * @param out_rank (rank of the output array selected) * @param out_offset (output offset array) * @param out_count (output count array, i.e. the number of cells[dim] in output) * @param total_out_count (total output count array, i.e. the total number of cells[dim] in output) */ public: void read_slab( void* const DataBuffer, const std::string Datasetname, const hid_t DataType, const hsize_t offset[], const hsize_t count[], const hsize_t out_rank, const hsize_t out_offset[], const hsize_t out_count[], const hsize_t total_out_count[]) { this->read_slab(DataBuffer, Datasetname, DataType, offset, count, out_rank, out_offset, out_count, total_out_count, MPI_COMM_NULL); // serial mode }; /** * read a slab of data from a dataset * @param *DataBuffer pointer to double/float/int array to which data is to be written * @param Datasetname datasetname * @param DataType (i.e. H5T_STD_I32LE) * @param offset (offset array) * @param count (count array, i.e. the number of cells[dim] to be selected) * @param out_rank (rank of the output array selected) * @param out_offset (output offset array) * @param out_count (output count array, i.e. the number of cells[dim] in output) * @param total_out_count (total output count array, i.e. the total number of cells[dim] in output) * @param comm: MPI communicator for parallel file I/O */ public: void read_slab( void* const DataBuffer, const std::string Datasetname, const hid_t DataType, const hsize_t offset[], const hsize_t count[], const hsize_t out_rank, const hsize_t out_offset[], const hsize_t out_count[], const hsize_t total_out_count[], MPI_Comm comm) { // get dimensional information from dataspace and update HDFSize this->getDims(Datasetname); // open dataset Dataset_id = H5Dopen(File_id, Datasetname.c_str(), H5P_DEFAULT); assert( Dataset_id != HDF5_error ); // open dataspace (to get dimensions) Dataspace_id = H5Dget_space(Dataset_id); assert( Dataspace_id != HDF5_error ); // select hyperslab HDF5_status = H5Sselect_hyperslab(Dataspace_id, H5S_SELECT_SET, offset, NULL, count, NULL); assert( HDF5_status != HDF5_error ); // create memspace hid_t Memspace_id = H5Screate_simple(out_rank, total_out_count, NULL); HDF5_status = H5Sselect_hyperslab(Memspace_id, H5S_SELECT_SET, out_offset, NULL, out_count, NULL); assert( HDF5_status != HDF5_error ); /// create property list for collective dataset i/o hid_t plist_id = H5P_DEFAULT; #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { plist_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE); } #endif // read buffer HDF5_status = H5Dread(Dataset_id, DataType, Memspace_id, Dataspace_id, plist_id, DataBuffer ); assert( HDF5_status != HDF5_error ); #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { HDF5_status = H5Pclose(plist_id); assert( HDF5_status != HDF5_error ); } #endif HDF5_status = H5Sclose(Memspace_id); assert( HDF5_status != HDF5_error ); HDF5_status = H5Sclose(Dataspace_id); assert( HDF5_status != HDF5_error ); HDF5_status = H5Dclose(Dataset_id); assert( HDF5_status != HDF5_error ); }; // read_slab /** * overwrite a slab of data from a dataset * @param *DataBuffer pointer to double/float/int array to which data is to be written * @param Datasetname datasetname * @param DataType (i.e. H5T_STD_I32LE) * @param offset (offset array) * @param count (count array, i.e. the number of cells[dim] to be selected) * @param out_rank (rank of the output array selected) * @param out_offset (output offset array) * @param out_count (output count array, i.e. the number of cells[dim] in output) */ public: void overwrite_slab(void* const DataBuffer, const std::string Datasetname, const hid_t DataType, const hsize_t offset[], const hsize_t count[], const hsize_t out_rank, const hsize_t out_offset[], const hsize_t out_count[]) { this->overwrite_slab(DataBuffer, Datasetname, DataType, offset, count, out_rank, out_offset, out_count, MPI_COMM_NULL); // serial mode }; /** * overwrite a slab of data from a dataset * @param *DataBuffer pointer to double/float/int array to which data is to be written * @param Datasetname datasetname * @param DataType (i.e. H5T_STD_I32LE) * @param offset (offset array) * @param count (count array, i.e. the number of cells[dim] to be selected) * @param out_rank (rank of the output array selected) * @param out_offset (output offset array) * @param out_count (output count array, i.e. the number of cells[dim] in output) * @param comm: MPI communicator for parallel file I/O */ public: void overwrite_slab(void* const DataBuffer, const std::string Datasetname, const hid_t DataType, const hsize_t offset[], const hsize_t count[], const hsize_t out_rank, const hsize_t out_offset[], const hsize_t out_count[], MPI_Comm comm) { // get dimensional information from dataspace and update HDFSize this->getDims(Datasetname); // open dataset Dataset_id = H5Dopen(File_id, Datasetname.c_str(), H5P_DEFAULT); assert( Dataset_id != HDF5_error ); // open dataspace (to get dimensions) Dataspace_id = H5Dget_space(Dataset_id); assert( Dataspace_id != HDF5_error ); // select hyperslab HDF5_status = H5Sselect_hyperslab(Dataspace_id, H5S_SELECT_SET, offset, NULL, count, NULL); assert( HDF5_status != HDF5_error ); // create memspace hid_t Memspace_id = H5Screate_simple(out_rank, out_count, NULL); HDF5_status = H5Sselect_hyperslab(Memspace_id, H5S_SELECT_SET, out_offset, NULL, out_count, NULL); assert( HDF5_status != HDF5_error ); /// create property list for collective dataset i/o hid_t plist_id = H5P_DEFAULT; #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { plist_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE); } #endif // overwrite dataset HDF5_status = H5Dwrite(Dataset_id, DataType, Memspace_id, Dataspace_id, plist_id, DataBuffer); assert( HDF5_status != HDF5_error ); #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { HDF5_status = H5Pclose(plist_id); assert( HDF5_status != HDF5_error ); } #endif HDF5_status = H5Sclose(Memspace_id); assert( HDF5_status != HDF5_error ); HDF5_status = H5Sclose(Dataspace_id); assert( HDF5_status != HDF5_error ); HDF5_status = H5Dclose(Dataset_id); assert( HDF5_status != HDF5_error ); }; // overwrite_slab /** * overwrite data of an existing dataset (serial mode) * @param *DataBuffer pointer to double/float/int array containing data to be written * @param Datasetname datasetname * @param DataType (i.e. H5T_STD_I32LE) */ public: void overwrite(const void* const DataBuffer, const std::string Datasetname, const hid_t DataType) { this->overwrite(DataBuffer, Datasetname, DataType, MPI_COMM_NULL); }; /** * overwrite data of an existing dataset (overloaded) * @param *DataBuffer pointer to double/float/int array containing data to be written * @param Datasetname datasetname * @param DataType (i.e. H5T_STD_I32LE) * @param comm: MPI communicator for parallel file I/O */ public: void overwrite(const void* const DataBuffer, const std::string Datasetname, const hid_t DataType, MPI_Comm comm) { // get dimensional information from dataspace and update HDFSize this->getDims(Datasetname); // open dataset Dataset_id = H5Dopen(File_id, Datasetname.c_str(), H5P_DEFAULT); assert( Dataset_id != HDF5_error ); // open dataspace (to get dimensions) Dataspace_id = H5Dget_space(Dataset_id); assert( Dataspace_id != HDF5_error ); /// create property list for collective dataset i/o hid_t plist_id = H5P_DEFAULT; #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { plist_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE); } #endif // overwrite dataset HDF5_status = H5Dwrite(Dataset_id, DataType, H5S_ALL, H5S_ALL, plist_id, DataBuffer); assert( HDF5_status != HDF5_error ); #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { HDF5_status = H5Pclose(plist_id); assert( HDF5_status != HDF5_error ); } #endif HDF5_status = H5Sclose(Dataspace_id); assert( HDF5_status != HDF5_error ); HDF5_status = H5Dclose(Dataset_id); assert( HDF5_status != HDF5_error ); }; // overwrite /** * create new HDF5 file (serial mode) * @param Filename HDF5 filename */ public: void create(const std::string Filename) { this->create(Filename, MPI_COMM_NULL); }; /** * create new HDF5 file (overloaded) * @param Filename HDF5 filename * @param comm: MPI communicator for parallel file I/O */ public: void create(const std::string Filename, MPI_Comm comm) { this->Filename = Filename; hid_t plist_id = H5P_DEFAULT; #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { plist_id = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fapl_mpio(plist_id, comm, MPI_INFO_NULL); } #endif // create HDF5 file (overwrite) File_id = H5Fcreate(Filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, plist_id); assert( File_id != HDF5_error ); #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) H5Pclose(plist_id); #endif }; /** * write HDF5 dataset (serial mode) * @param DataBuffer int/float/double array containing the data * @param Datasetname datasetname * @param Dimensions dataset dimensions * @param DataType (i.e. H5T_STD_I32LE) */ public: void write( const void* const DataBuffer, const std::string Datasetname, const std::vector<int> Dimensions, const hid_t DataType) { this->write(DataBuffer, Datasetname, Dimensions, DataType, MPI_COMM_NULL); }; /** * write HDF5 dataset (overloaded) * @param DataBuffer int/float/double array containing the data * @param Datasetname datasetname * @param Dimensions dataset dimensions * @param DataType (i.e. H5T_STD_I32LE) * @param comm: MPI communicator for parallel file I/O */ public: void write( const void* const DataBuffer, const std::string Datasetname, const std::vector<int> Dimensions, const hid_t DataType, MPI_Comm comm) { this->setDims(Dimensions); // set dimensions this->write(DataBuffer, Datasetname, DataType, comm); // call write }; /** * write HDF5 dataset (serial mode) * @param *DataBuffer pointer to int/float/double array containing the data * @param Datasetname datasetname * @param DataType (i.e. H5T_IEEE_F32BE, H5T_STD_I32LE, ...) */ public: void write(const void* const DataBuffer, const std::string Datasetname, const hid_t DataType) { this->write(DataBuffer, Datasetname, DataType, MPI_COMM_NULL); }; /** * write HDF5 dataset (overloaded) * @param *DataBuffer pointer to int/float/double array containing the data * @param Datasetname datasetname * @param DataType (i.e. H5T_IEEE_F32BE, H5T_STD_I32LE, ...) * @param comm: MPI communicator for parallel file I/O */ public: void write(const void* const DataBuffer, const std::string Datasetname, const hid_t DataType, MPI_Comm comm) { // -------------- create dataspace Dataspace_id = H5Screate_simple(Rank, HDFDims, NULL); assert( Dataspace_id != HDF5_error ); // -------------- create dataset Dataset_id = H5Dcreate(File_id, Datasetname.c_str(), DataType, Dataspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); assert( Dataset_id != HDF5_error ); /// create property list for collective dataset i/o hid_t plist_id = H5P_DEFAULT; #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { plist_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE); } #endif // -------------- write dataset HDF5_status = H5Dwrite(Dataset_id, DataType, H5S_ALL, H5S_ALL, plist_id, DataBuffer); assert( HDF5_status != HDF5_error ); #ifdef H5_HAVE_PARALLEL if (comm != MPI_COMM_NULL) { HDF5_status = H5Pclose(plist_id); assert( HDF5_status != HDF5_error ); } #endif // -------------- close dataset HDF5_status = H5Dclose(Dataset_id); assert( HDF5_status != HDF5_error ); // -------------- close dataspace HDF5_status = H5Sclose(Dataspace_id); assert( HDF5_status != HDF5_error ); }; // write /** * create empty HDF5 dataset * @param Datasetname datasetname * @param Dimensions dataset dimensions * @param DataType (i.e. H5T_IEEE_F32BE, H5T_STD_I32LE, ...) * @param comm: MPI communicator for parallel file I/O */ public: void create_dataset(const std::string Datasetname, const std::vector<int> Dimensions, const hid_t DataType, MPI_Comm comm) { this->setDims(Dimensions); // set dimensions // -------------- create dataspace Dataspace_id = H5Screate_simple(Rank, HDFDims, NULL); assert( Dataspace_id != HDF5_error ); // -------------- create dataset Dataset_id = H5Dcreate(File_id, Datasetname.c_str(), DataType, Dataspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); assert( Dataset_id != HDF5_error ); // -------------- close dataset HDF5_status = H5Dclose(Dataset_id); assert( HDF5_status != HDF5_error ); // -------------- close dataspace HDF5_status = H5Sclose(Dataspace_id); assert( HDF5_status != HDF5_error ); }; /** * delete HDF5 dataset * @param Datasetname datasetname */ public: void delete_dataset(const std::string Datasetname) { std::vector<std::string> dsets_in_file = getDatasetnames(); bool dset_in_file = false; // see if the Datasetname exists in the file for (unsigned int i = 0; i < dsets_in_file.size(); i++) { if (dsets_in_file[i] == Datasetname) { dset_in_file = true; break; } } if (dset_in_file) { // if the Datasetname is in the file, delete it HDF5_status = H5Ldelete(File_id, Datasetname.c_str(), H5P_DEFAULT); // delete dataset assert( HDF5_status != HDF5_error ); } }; /** * delete all HDF5 datasets */ public: void delete_datasets(void) { std::vector<std::string> dsets_in_file = getDatasetnames(); for (unsigned int i = 0; i < dsets_in_file.size(); i++) { this->delete_dataset(dsets_in_file[i]); } }; /** * set the rank of a dataset * @param Rank the rank, dimensionality (0,1,2) */ public: void setRank(const int Rank) { this->Rank = Rank; }; /** * set array dimension in different directions * @param dim dimension of the array */ public: void setDimX(const int dim_x) { HDFDims[0] = static_cast<hsize_t>(dim_x); }; public: void setDimY(const int dim_y) { HDFDims[1] = static_cast<hsize_t>(dim_y); }; public: void setDimZ(const int dim_z) { HDFDims[2] = static_cast<hsize_t>(dim_z); }; public: void setDims(const std::vector<int> Dimensions) { Rank = Dimensions.size(); for(int i = 0; i < Rank; i++) HDFDims[i] = static_cast<hsize_t>(Dimensions[i]); }; /** * get the rank of the current dataset * @return int dimensionality */ public: int getRank(void) const { return Rank; }; /** * get the rank of a dataset with name datasetname * @param Datasetname datasetname * @return int dimensionality */ public: int getRank(const std::string Datasetname) { // get dimensional information from dataspace and update HDFSize this->getDims(Datasetname); return Rank; }; /** * get array dimension in different directions * @return dimension of the array */ public: int getDimX(void) const { return static_cast<int>(HDFDims[0]); }; public: int getDimY(void) const { return static_cast<int>(HDFDims[1]); }; public: int getDimZ(void) const { return static_cast<int>(HDFDims[2]); }; /** * get dataset size of dataset with datasetname * @param Datasetname datasetname * @return size of the dataset */ public: int getSize(const std::string Datasetname) { // open dataset Dataset_id = H5Dopen(File_id, Datasetname.c_str(), H5P_DEFAULT); if (Dataset_id == HDF5_error) { std::cout << "HDFIO: getSize(): CAUTION: Datasetname '" << Datasetname << "' does not exists in file '" <<this->getFilename()<<"'. Continuing..." << std::endl; return 0; } assert( Dataset_id != HDF5_error ); // open dataspace Dataspace_id = H5Dget_space(Dataset_id); assert( Dataspace_id != HDF5_error ); // get dimensional information from dataspace hsize_t HDFxdims[4], HDFmaxdims[4]; Rank = H5Sget_simple_extent_dims(Dataspace_id, HDFxdims, HDFmaxdims); // from the dimensional info, calculate the size of the buffer. HDFSize = 1; for (int i = 0; i < Rank; i++) { HDFDims[i] = HDFxdims[i]; HDFSize *= HDFDims[i]; } HDF5_status = H5Sclose(Dataspace_id); assert( HDF5_status != HDF5_error ); HDF5_status = H5Dclose(Dataset_id); assert( HDF5_status != HDF5_error ); return static_cast<int>(HDFSize); }; // getSize /** * get array dimension in different directions and update HDFSize * @param Datasetname datasetname for which dimensional info is read * @return dimension of the array */ public: std::vector<int> getDims(const std::string Datasetname) { // open dataset Dataset_id = H5Dopen(File_id, Datasetname.c_str(), H5P_DEFAULT); assert( Dataset_id != HDF5_error ); // open dataspace Dataspace_id = H5Dget_space(Dataset_id); assert( Dataspace_id != HDF5_error ); // get dimensional information from dataspace hsize_t HDFxdims[4], HDFmaxdims[4]; Rank = H5Sget_simple_extent_dims(Dataspace_id, HDFxdims, HDFmaxdims); // from the dimensional info, calculate the size of the buffer. HDFSize = 1; for (int i = 0; i < Rank; i++) { HDFDims[i] = HDFxdims[i]; HDFSize *= HDFDims[i]; } HDF5_status = H5Sclose(Dataspace_id); assert( HDF5_status != HDF5_error ); HDF5_status = H5Dclose(Dataset_id); assert( HDF5_status != HDF5_error ); std::vector<int> ReturnDims(Rank); for(int i = 0; i < Rank; i++) ReturnDims[i] = static_cast<int>(HDFDims[i]); return ReturnDims; }; // getDims /** * get HDF5 file ID * @return File_id */ public: hid_t getFileID(void) { return File_id; }; /** * get HDF5 filename * @return filename */ public: std::string getFilename(void) { return Filename; }; /** * get number of datasets in HDF5 file * @return the number of datasets */ public: int getNumberOfDatasets(void) { hsize_t *NumberofObjects = new hsize_t[1]; H5Gget_num_objs(File_id, NumberofObjects); int returnNumber = static_cast<int>(NumberofObjects[0]); delete [] NumberofObjects; return returnNumber; }; /** * get HDF5 datasetname * @param datasetnumber integer number identifying the dataset * @return datasetname */ public: std::string getDatasetname(const int datasetnumber) { char *Name = new char[256]; H5Gget_objname_by_idx(File_id, datasetnumber, Name, 256); std::string returnName = static_cast<std::string>(Name); delete [] Name; return returnName; }; /** * getDatasetnames * @return vector<string> datasetnames */ public: std::vector<std::string> getDatasetnames(void) { int nsets = this->getNumberOfDatasets(); std::vector<std::string> ret(nsets); for (int i=0; i<nsets; i++) { ret[i] = this->getDatasetname(i); if (Verbose > 1) std::cout << "dataset in file: " << ret[i] << std::endl; } return ret; }; // ************************************************************************* // // ************** reading FLASH scalars or runtime parameters ************** // // ************************************************************************* // /// returns FLASH integer, real, logical, string scalars or runtime parameters as maps public: std::map<std::string, int> ReadFlashIntegerScalars() { return GetFLASHProps<int>("integer scalars"); }; public: std::map<std::string, int> ReadFlashIntegerParameters() { return GetFLASHProps<int>("integer runtime parameters"); }; public: std::map<std::string, double> ReadFlashRealScalars() { return GetFLASHProps<double>("real scalars"); }; public: std::map<std::string, double> ReadFlashRealParameters() { return GetFLASHProps<double>("real runtime parameters"); }; public: std::map<std::string, bool> ReadFlashLogicalScalars() { return GetFLASHProps<bool>("logical scalars"); }; public: std::map<std::string, bool> ReadFlashLogicalParameters() { return GetFLASHProps<bool>("logical runtime parameters"); }; public: std::map<std::string, std::string> ReadFlashStringScalars() { return GetFLASHProps<std::string>("string scalars"); }; public: std::map<std::string, std::string> ReadFlashStringParameters() { return GetFLASHProps<std::string>("string runtime parameters"); }; // returns map of FLASH integer, real, logical, string scalars or runtime parameters private: template<typename T> std::map<std::string, T> GetFLASHProps(std::string dsetname) { std::map<std::string, T> ret; // return object int nProps = this->getDims(dsetname)[0]; hid_t h5string = H5Tcopy(H5T_C_S1); H5Tset_size(h5string, NameSpaceHDFIO::flash_str_len); hid_t dtype; if (typeid(T) == typeid(int)) dtype = H5T_NATIVE_INT; if (typeid(T) == typeid(double)) dtype = H5T_NATIVE_DOUBLE; if (typeid(T) == typeid(bool)) dtype = H5T_NATIVE_HBOOL; if (typeid(T) == typeid(std::string)) dtype = H5Tcopy(h5string); hid_t datatype = H5Tcreate(H5T_COMPOUND, sizeof(NameSpaceHDFIO::FlashScalarsParametersStruct<T>)); H5Tinsert(datatype, "name", HOFFSET(NameSpaceHDFIO::FlashScalarsParametersStruct<T>, name), h5string); H5Tinsert(datatype, "value", HOFFSET(NameSpaceHDFIO::FlashScalarsParametersStruct<T>, value), dtype); NameSpaceHDFIO::FlashScalarsParametersStruct<T> * data = new NameSpaceHDFIO::FlashScalarsParametersStruct<T>[nProps]; this->read(data, dsetname, datatype); for (int i = 0; i < nProps; i++) { std::string pname = Trim((std::string)data[i].name); ret[pname] = (T)data[i].value; if (Verbose > 1) std::cout<<FuncSig(__func__)<<"name, value = '"<<pname<<"', '"<<ret[pname]<<"'"<<std::endl; } delete [] data; return ret; }; // clear whitespace and/or terminators at the end of a string private: std::string Trim(const std::string input) { std::string ret = input; return ret.erase(input.find_last_not_of(" \n\r\t")+1); }; // ************************************************************************* // // ************ overwriting FLASH scalars or runtime parameters ************ // // ************************************************************************* // public: void OverwriteFlashIntegerScalars(std::map<std::string, int> props) { for (std::map<std::string, int>::iterator it = props.begin(); it != props.end(); it++) OverwriteFLASHProp("integer scalars", it->first, it->second); }; public: void OverwriteFlashIntegerParameters(std::map<std::string, int> props) { for (std::map<std::string, int>::iterator it = props.begin(); it != props.end(); it++) OverwriteFLASHProp("integer runtime parameters", it->first, it->second); }; public: void OverwriteFlashRealScalars(std::map<std::string, double> props) { for (std::map<std::string, double>::iterator it = props.begin(); it != props.end(); it++) OverwriteFLASHProp("real scalars", it->first, it->second); }; public: void OverwriteFlashRealParameters(std::map<std::string, double> props) { for (std::map<std::string, double>::iterator it = props.begin(); it != props.end(); it++) OverwriteFLASHProp("real runtime parameters", it->first, it->second); }; public: void OverwriteFlashLogicalScalars(std::map<std::string, bool> props) { for (std::map<std::string, bool>::iterator it = props.begin(); it != props.end(); it++) OverwriteFLASHProp("logical scalars", it->first, it->second); }; public: void OverwriteFlashLogicalParameters(std::map<std::string, bool> props) { for (std::map<std::string, bool>::iterator it = props.begin(); it != props.end(); it++) OverwriteFLASHProp("logical runtime parameters", it->first, it->second); }; public: void OverwriteFlashStringScalars(std::map<std::string, std::string> props) { for (std::map<std::string, std::string>::iterator it = props.begin(); it != props.end(); it++) OverwriteFLASHProp("string scalars", it->first, it->second); }; public: void OverwriteFlashStringParameters(std::map<std::string, std::string> props) { for (std::map<std::string, std::string>::iterator it = props.begin(); it != props.end(); it++) OverwriteFLASHProp("string runtime parameters", it->first, it->second); }; // overwrite FLASH integer, real, logical, string scalars or runtime parameters private: template<typename T> void OverwriteFLASHProp(std::string datasetname, std::string fieldname, T fieldvalue) { hid_t dsetId = H5Dopen(File_id, datasetname.c_str(), H5P_DEFAULT); hid_t spaceId = H5Dget_space(dsetId); hsize_t locDims[1]; H5Sget_simple_extent_dims(spaceId, locDims, NULL); int num = locDims[0]; hid_t h5string = H5Tcopy(H5T_C_S1); H5Tset_size(h5string, NameSpaceHDFIO::flash_str_len); hid_t dtype; if (typeid(T) == typeid(int)) dtype = H5T_NATIVE_INT; if (typeid(T) == typeid(double)) dtype = H5T_NATIVE_DOUBLE; if (typeid(T) == typeid(bool)) dtype = H5T_NATIVE_HBOOL; if (typeid(T) == typeid(std::string)) dtype = H5Tcopy(h5string); hid_t datatype = H5Tcreate(H5T_COMPOUND, sizeof(NameSpaceHDFIO::FlashScalarsParametersStruct<T>)); H5Tinsert(datatype, "name", HOFFSET(NameSpaceHDFIO::FlashScalarsParametersStruct<T>, name), h5string); H5Tinsert(datatype, "value", HOFFSET(NameSpaceHDFIO::FlashScalarsParametersStruct<T>, value), dtype); NameSpaceHDFIO::FlashScalarsParametersStruct<T> *data = new NameSpaceHDFIO::FlashScalarsParametersStruct<T>[num]; H5Dread(dsetId, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, data); for (int i = 0; i < num; i++) if (strncmp(data[i].name, fieldname.c_str(), fieldname.size()) == 0) { if (Verbose > 1) std::cout<<FuncSig(__func__)<<": Overwriting "<<fieldname<<" of "<<data[i].value <<" with "<<fieldvalue<<" in '"<<datasetname<<"'"<<std::endl; NameSpaceHDFIO::FLASHPropAssign<T>(fieldvalue, &data[i].value); } H5Dwrite(dsetId, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, data); delete [] data; H5Tclose(datatype); H5Tclose(h5string); H5Sclose(spaceId); H5Dclose(dsetId); }; }; // end: HDFIO #endif
true
a5d726da3737ff600e35e91d4e516becb15b517c
C++
YuDe95/mcplayer
/src/base/database/schema/Column.h
UTF-8
1,826
2.59375
3
[ "MIT" ]
permissive
#ifndef COLUMN_H #define COLUMN_H #include <QMetaType> #include <QVariant> #include <QString> #include <QDebug> class ColumnPrivate; class Column { public: explicit Column(const QString& name = QString(), int type = QMetaType::Char); Column(const QString& name, int typeId, const QString &table); Column(const Column &other); ~Column(); Column &operator=(const Column& other); bool operator==(const Column& other) const; inline bool operator!=(const Column &other) const { return !operator==(other); } void setValue(const QVariant& value); inline QVariant value() const; void setName(const QString& name); QString name() const; void setTableName(const QString &tableName); QString tableName() const; void setType(int type); int type() const; QString typeName() const; void setReadOnly(bool readOnly); bool isReadOnly() const; void setAutoIncreament(bool autoVal); bool isAutoIncreament() const; void setAutoValue(bool autoVal); bool isAutoValue() const; void setRequired(bool required); bool isRequired() const; void setDefaultValue(const QVariant &value); QVariant defaultValue() const; void setLength(int fieldLength); int length() const; void setPrecision(int precision); int precision() const; void setTotal(int total); int total() const; void setPlaces(int places); int places() const; // void setAllowed(const QStringList &allowed); // QStringList allowed() const; void setNullable(bool nullable = true); bool nullable() const; void setNull(); bool isNull() const; bool isValid() const; private: QVariant val; ColumnPrivate *d; }; #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug, const Column &); #endif #endif // COLUMN_H
true
b8ad7f0e7ad372e3aaad6c692e753727f4e89d1a
C++
schildmeijer/project-euler
/34.cc
UTF-8
1,740
2.796875
3
[]
no_license
#include <iostream> #include <vector> #include <NTL/ZZ.h> #include <sstream> #include <math.h> #include <fstream> #include <iterator> #include <algorithm> #include <map> #include <set> #include <bitset> #include <utility> //for std::make_pair #include <boost/lambda/lambda.hpp> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <boost/shared_ptr.hpp> #include <gmpxx.h> //for c++ using namespace std; using namespace NTL; using namespace boost; // g++ -I/usr/local/include -I/usr/local/include/boost-1_33_1 -I/usr/local/include/gmp-4.2.1 -L/usr/local/lib 27.cc -o main -lntl -lm -lgmpxx -lgmp //145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. //Find the sum of all numbers which are equal to the sum of the factorial of their digits. template <int N> struct factorial{ enum {value = N * factorial<N-1>::value }; }; template <> struct factorial<0> { enum {value = 1 }; }; template <typename T> bool check_fac(long nbr, const vector<T> & fac) { long origin = nbr; long sum = 0; do { int digit = nbr % 10; nbr = nbr / 10; sum += fac[digit]; } while (nbr != 0); return sum == origin; } int main (int argc, char *const argv[]) { vector<int> fac; fac.reserve(9); fac.push_back(factorial<0>::value); fac.push_back(factorial<1>::value); fac.push_back(factorial<2>::value); fac.push_back(factorial<3>::value); fac.push_back(factorial<4>::value); fac.push_back(factorial<5>::value); fac.push_back(factorial<6>::value); fac.push_back(factorial<7>::value); fac.push_back(factorial<8>::value); fac.push_back(factorial<9>::value); int sum = 0; for (int i = 3; i <= 100000 ; ++i) if (check_fac(i, fac)) { sum += i; cout << i << endl; } cout << "sum: " << sum << endl; }
true
627f0f2a69644728996c228378af8c30554cc6c7
C++
Luiz1996/Fundamentos_de_Algoritmos
/listas 1ª prova/lista 1/exe22_lista1.cpp
UTF-8
481
3.28125
3
[]
no_license
#include <stdio.h> #include <math.h> int main(void){ float deposito, juros, rendimento, valor_total; printf("Digite o valor do deposito a ser realizado: "); scanf("%f", &deposito); printf("Digite o valor do juros/rendimento em porcentagem[%%]: "); scanf("%f", &juros); rendimento = (deposito / 100) * juros; valor_total = deposito + rendimento; printf("\nO valor do rendimento foi de R$%.2f e o valor total apos 1 mes foi de R$%.2f .", rendimento, valor_total); }
true
14f185810d40b50d9ee218070f18150c2d42b7c4
C++
Kr4w4r/citygame-engine
/3DMap/3DMap/3DMapData.h
UTF-8
889
2.671875
3
[]
no_license
#ifndef _3DMAP_H #define _3DMAP_H #define WIN32_LEAN_AND_MEAN #include "IMap.h" class C3DMapData : public IMap { public: C3DMapData(GLuint horizontalCellCount, GLuint verticalCellCount, GLfloat maxHeight); C3DMapData(GLuint horizontalCellCount, GLuint verticalCellCount, GLfloat width, GLfloat height, GLfloat maxHeight); C3DMapData(GLuint horizontalCellCount, GLuint verticalCellCount, MAP_DATA mapData); ~C3DMapData(); void render(); GLuint getWidth(); GLuint getHeight(); GLfloat getMaxHeight() { return mMaxHeight; }; MAP_CORNER* getMapCorner(GLuint x, GLuint y); private: void generateFlatMap(GLuint gridWidth, GLuint gridHeight, GLfloat width, GLfloat height); CVector3f getColor(GLfloat height); protected: GLuint mWidth; GLuint mHeight; GLfloat mMaxHeight; // 2D Array auf ein MAP_CORNER* MAP_DATA mMapData; }; #endif
true
46cbef6ccb2f97e9db641782e7978a19c2c95cc2
C++
DepthDeluxe/DCPU-16
/DCPU-16/InterruptQueue.h
UTF-8
599
2.875
3
[]
no_license
// File: InterruptQueue.h // // Author: Colin Heinzmann // Description: This is a class that creates an interrupt queue for use in the DCPU #ifndef INTERRUPT_QUEUE_H #define INTERRUPT_QUEUE_H #include <windows.h> #define INTERRUPT_QUEUE_MAX_SIZE 256 class InterruptQueue { // members private: UINT head; UINT count; UINT16 messages[INTERRUPT_QUEUE_MAX_SIZE]; public: // constructor InterruptQueue(); public: // standard queue functions BOOL EnQueue(UINT16 item); UINT16 DeQueue(); // accessor functions public: BOOL isEmpty(); UINT Length(); }; #endif
true
32f123c95125a71b796903ec18509fd8daefc4ec
C++
TheCodingKansan66212/C-Samples
/Lab8Part3.cpp
UTF-8
1,339
3.875
4
[]
no_license
/* @NAME: Hannah Robinow @DATE: 5 April 2018 @DESCRIPTION: Use four functions to reverse an array generated by user input. */ #include <iostream> #include <cmath> #include <fstream> #include <iomanip> using namespace::std; //function headers. void inputData(istream &, int[], int); void printData(ostream &, const int[], int); void copyArray(const int orig[], int dup[], int); void revCopy(const int orig[], int rev[], int); void main() { int size = 0; int original[60]; cout << "Enter array elements: " << endl; for (int i = 0; i < size; i++) { cout << "Enter array # " << i << " element: " << endl; cin >> original[size]; } cout << "Data stored in array!" << endl; } //input an array. void inputData(istream &, int original[], int a) { for (int i = 0; i < a; i++) { cin >> original[i]; } } //display the array. void printData(ostream &, int original[], int b) { for (int i = 0; i < b; i++) { cout << original[i] << endl; } } //make a copy of the array. void copyArray(int original[], int dup[], int a) { for (int i = 0; i < a; i++) { dup[i] = original[i]; } } void revCopy(int original[], int rev[], int size) { int temp; size--; for (int i = 0; size >= i; i++) { temp = original[i]; original[i] = rev[size]; rev[size] = temp; } }
true
c1a2b27219ea4645f95cfd9ab1b2754093c6f02c
C++
PrashantThakurNitP/cpp-code
/chef and code final.cpp
UTF-8
1,038
2.890625
3
[]
no_license
#include<iostream> #include <vector> #include<algorithm> using namespace std; int main() { int t; cin>>t; for(int i=0;i<t;i++) { int n,m,k,l,r; cin>>n>>m>>k>>l>>r; // vector<int>v1; vector<int>v2; int price =100000; for(int j=0;j<n;j++) { int a; int b; cin>>a; cin>>b; if(a>k && max(a-m,k)<=r && max(a-m,k)>=l) { // max(a-m,k) // //if(b) price=b; // temp=a-m; v2.push_back(price); } else if(a<k && min(a+m,k)<=r && min(a+m,k)>=l) { price=b; //temp=a+m; // v1.push_back(temp); v2.push_back(price); // cout<<"else if 0"<<endl; } }//outer if cout<<endl; if(v2.size()>0) cout<< *min_element(v2.begin(), v2.end()); else cout<<"-1"; }//for for t }//main ends //n m k l r
true
62dbf5929600978d1f44e2b3a920482c21b5e638
C++
cmw666547/homework3
/03.cpp
UTF-8
6,565
3.140625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <iostream> #define MAX 1000 using namespace std; typedef char elemtype;//任务类型 typedef struct node//建立项目任务结点,因为涉及到项目的删除所以我先用链表存储项目任务 { elemtype project; struct node *next; }node; typedef struct arc//图中的弧 { int tailvex,headvex;//弧尾和弧头结点的位置 struct arc *next;//指向下一个弧 }arc; typedef struct vex//图中的顶点 { elemtype data; int rudu; arc *firstin,*firstout;//和该顶点相连的第一条入弧和第一条出弧 }vex; typedef struct//以十字链表为存储结构的图 { vex xlist[MAX];//图中的每个表头结点 int vexnum,arcnum;//图中的顶点数和边数 }Graph; typedef struct//建立一个栈存储图中入度为0的点 { vex *base; vex *top; int stacksize; }stack; void initstack(stack &s)//栈的初始化 { s.base=(vex *)malloc(MAX*sizeof(vex)); if(!s.base) return ; s.top=s.base; s.stacksize=MAX; } void push(stack &s,vex e)//入栈 { if(s.top-s.base>=s.stacksize) return ; *s.top++=e; } int pop(stack &s,vex &e)//出栈 { if(s.top==s.base) return 0; e=*--s.top; return 1; } node *luru()//项目任务录入函数 { int i,n; node *head=NULL,*p1=NULL,*p2=NULL; head=(node *)malloc(sizeof(node)); head->next=NULL; p2=head; printf("录入项目任务数量n:\n"); cin>>n; printf("录入n个项目任务:\n"); for(i=0;i<=n-1;i++) { p1=(node *)malloc(sizeof(node)); p1->next=NULL; cin>>p1->project; p2->next=p1; p2=p1; } return head; } void xiugaishanchu(elemtype changeremove,node * &p1,node * &p2)//修改和删除都可以用这个函数 { while(p1!=NULL) { if(p1->project==changeremove) break; p2=p2->next; p1=p2->next; }//p1是要找查找或者删除的项目任务,p2是所找项目任务的前一个为了方便删除 } void jiancha(node *p1)//检查自己代码是否满足更改项目任务的要求 { while(p1!=NULL) { cout<<p1->project; p1=p1->next; } } void zheban(elemtype a[MAX],int low,int high,elemtype chazhao,int &e)//折半查找 { int mid; mid=(low+high)/2; if(a[mid]==chazhao) e=mid; else { if(chazhao<a[mid]) { high=mid-1; zheban(a,low,high,chazhao,e); } else { low=mid+1; zheban(a,low,high,chazhao,e); } } } int locate(Graph &G,elemtype u)//找到项目任务在图中对应的位置下标 { int i; for(i=0;i<=G.vexnum-1;i++) { if(G.xlist[i].data==u) break; } return i; } void create(Graph &G,elemtype a[MAX],int m)//输入项目任务c[i]的先决条件b[i]和c[i]构造图,每组对应一条边 { elemtype b[MAX],c[MAX]; int i,j,k; arc *p=NULL; G.vexnum=m; for(i=0;i<=G.vexnum-1;i++) { G.xlist[i].data=a[i];//把项目任务的值赋值给对应图的顶点 G.xlist[i].firstin=NULL; G.xlist[i].firstout=NULL; G.xlist[i].rudu=0; } printf("\n输入图的边的数量:\n"); cin>>G.arcnum; printf("输入项目任务先决条件和项目任务:\n"); for(i=0;i<=G.arcnum-1;i++) { cin>>b[i]>>c[i]; j=locate(G,b[i]); k=locate(G,c[i]); p=(arc *)malloc(sizeof(arc)); p->headvex=k; p->next=G.xlist[j].firstout; G.xlist[j].firstout=p;//所有以j为弧尾结点的弧 p=(arc *)malloc(sizeof(arc)); p->tailvex=j; p->next=G.xlist[k].firstin; G.xlist[k].firstin=p;//所有以k为弧头结点的弧 } } void tuopu(Graph &G)//对项目任务进行拓扑排序 { arc *p; int i,v; stack s; vex e; initstack(s); for(i=0;i<=G.vexnum-1;i++) { p=G.xlist[i].firstin; while(p!=NULL) { G.xlist[i].rudu++; p=p->next; } if(G.xlist[i].rudu==0) push(s,G.xlist[i]); } for(i=0;i<=G.vexnum-1;i++) { pop(s,e); printf("%c",e);//输出一个入度为0的结点并且删除以他为尾的弧 p=e.firstout; while(p!=NULL) { v=p->headvex; G.xlist[v].rudu--; if(G.xlist[v].rudu==0) push(s,G.xlist[v]); p=p->next; } } } int main() { int i,j,m,k,e,on; Graph G; elemtype a[MAX],change,changea,remove,t,chazhao; node *head=NULL,*p1=NULL,*p2=NULL; printf("系统主要功能如下\n"); printf("1 项目任务的录入和修改\n2 项目任务的录入和删除\n3 折半查找项目任务\n4 实现项目任务拓扑排序\n请输入你的选择\n"); cin>>on; head=luru(); p1=head->next; printf("录入后项目任务为:\n"); jiancha(p1);//检查项目录入是否成功 if(on==1) { printf("\n输入要修改的项目任务:\n"); cin>>change; p2=head; p1=p2->next; xiugaishanchu(change,p1,p2); //此刻p1所指的就是想要修改的项目任务,把p1的project域改成想要修改成任务完成了项目的修改 printf("输入想要改成的项目任务:\n"); cin>>changea;//举个例子,把项目任务修改成任务changea p1->project=changea;//此时p1所指的项目任务已修改 p1=head->next; printf("修改后项目为:\n"); jiancha(p1);//检查项目任务是否修改,输出修改后项目任务 } else if(on==2) { p2=head; p1=p2->next; printf("\n输入要删除的项目任务:\n"); cin>>remove;//remove是想要删除的项目任务 xiugaishanchu(remove,p1,p2); //此刻p1是要删除项目任务的位置,p2是为了保证删除 p1=p1->next; p2->next=p1;//此时想要删除的项目任务已经删除 p1=head->next; printf("删除后项目为:\n"); jiancha(p1);//检查项目任务是否删除,输出删除后的项目任务 } else if(on==3) { p1=head->next; for(m=0;;m++)//把项目任务放到数组里以便升序后的折半查找 { if(p1==NULL) break; a[m]=p1->project; p1=p1->next; } for(i=0;i<=m-2;i++)//选择排序对项目任务升序排序为折半查找准备 { k=i; for(j=i+1;j<=m-1;j++) { if(a[j]<a[k]) k=j; } t=a[i]; a[i]=a[k]; a[k]=t; } printf("\n输出对项目任务升序排序后的结果:\n"); for(i=0;i<=m-1;i++) { printf("%c",a[i]); } printf("\n输入要查找的项目任务:\n"); cin>>chazhao; zheban(a,0,m-1,chazhao,e); printf("输出查找到的项目任务位置对应数组下标和项目任务:\n%d %c",e,a[e]); } else if(on==4) { p1=head->next; for(m=0;;m++)//把项目任务放到数组里以便赋值给图中的结点 { if(p1==NULL) break; a[m]=p1->project; p1=p1->next; } create(G,a,m); printf("拓扑排序后的结果为:\n"); tuopu(G); } system("pause"); return 0; }
true
0eeae712a892c3a3a829fefb806fc96d73739539
C++
listenviolet/Point_to_Offer
/46_sum_n-virtual.cpp
UTF-8
637
2.90625
3
[]
no_license
class A; A* Array[2]; class A { public: virtual unsigned int Sum(unsigned int n) { return 0; } }; class B:public A { public: virtual unsigned int Sum(unsigned int n) { return Array[!!n] -> Sum(n - 1) + n; } }; class Solution { public: int Sum_Solution(int n) { A a; B b; Array[0] = &a; Array[1] = &b; int value = Array[1] -> Sum(n); return value; } }; // 求1+2+3+...+n,要求不能使用乘除法、 // for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。 // 运行时间:4ms // 占用内存:480k
true
91c8aa04ca09eb83693c6cb90f885867ce6be216
C++
sinaaghli/socket_test
/SendNode.h
UTF-8
2,272
2.765625
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <netdb.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #define BUFLEN 2048 #define MSGS 5 /* number of messages to send */ class SendNode { public: SendNode(char* server_ip__ip, unsigned int port){ service_port_ = port; server_ip_ = server_ip__ip; slen_ = sizeof(remaddr); } ~SendNode(){ close(fd_); } bool ConnectToServer(){ /* create a socket */ if ((fd_=socket(AF_INET, SOCK_DGRAM, 0))==-1) printf("socket created\n"); /* bind it to all local addresses and pick any port number */ memset((char *)&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(0); if (bind(fd_, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) { perror("bind failed"); return false; } memset((char *) &remaddr, 0, sizeof(remaddr)); remaddr.sin_family = AF_INET; remaddr.sin_port = htons(service_port_); if (inet_aton(server_ip_, &remaddr.sin_addr)==0) { fprintf(stderr, "inet_aton() failed\n"); return false; } return true; } bool SendPose(double x, double y, double yaw){ PoseMsg msg; msg.x = x; msg.y = y; msg.yaw = yaw; // printf("Sending packet to %s port %d\n", server_ip_, service_port_); if (sendto(fd_, &msg, sizeof(PoseMsg), 0, (struct sockaddr *)&remaddr, slen_)==-1){ return false; } return true; } bool SendObstacleLocation(double x, double y){ ObsMsg msg; msg.x = x; msg.y = y; // printf("Sending packet to %s port %d\n", server_ip_, service_port_); if (sendto(fd_, &msg, sizeof(ObsMsg), 0, (struct sockaddr *)&remaddr, slen_)==-1){ return false; } return true; } private: struct sockaddr_in myaddr, remaddr; int fd_, slen_; char *server_ip_; char buf[BUFLEN]; unsigned int service_port_; #pragma pack(1) struct PoseMsg { PoseMsg(){ x = 0; y = 0; yaw = 0; } const unsigned char id = 1; float x; float y; float yaw; }; #pragma pack() #pragma pack(1) struct ObsMsg { ObsMsg(){ x = 0; y = 0; } const unsigned char id = 2; float x; float y; }; #pragma pack() };
true
9df6538f86621e1255fb8ee6672a2121a454b69d
C++
minghz/ece1387-2015
/ass2/helpers.cpp
UTF-8
670
2.546875
3
[]
no_license
#include <iostream> #include <cstdlib> #include <vector> #include <list> #include <boost/tokenizer.hpp> #include "lab.h" using namespace std; bool net_number_exists(list<Net> net_list, int n){ list<Net>::iterator iterator; for (iterator = net_list.begin(); iterator != net_list.end(); ++iterator) { if ((*iterator).number == n){ //found it return true; } } return false; } Net* get_net(list<Net>* net_list, int n){ list<Net>::iterator iterator; for (iterator = net_list->begin(); iterator != net_list->end(); ++iterator) { if ((*iterator).number == n){ //found it return &(*iterator); } } return NULL; }
true
a8e8f9531f32ff0f639354ff0248a85bb7a4bf51
C++
casperwang/OJproblems
/UVa judge/#10341_Solve It.cpp
UTF-8
687
2.96875
3
[]
no_license
#include <iostream> #include <cmath> #include <cstdio> using namespace std; double L, R, mid; double p, q, r, s, t, u; double caculate(double x) { return p*exp(-x) + q*sin(x) + r*cos(x) + s*tan(x) + t*x*x + u; } int main() { while (cin >> p >> q >> r >> s >> t >> u) { L = 0; R = 1; mid = (L+R)/2; while (R > L && abs(caculate(mid)) > 0.000001 && mid < 1 && mid > 0) { if (caculate(mid) > 0) L = mid; else R = mid; mid = (L+R)/2; } if (!caculate(0)) printf("0.0000\n"); else if (!caculate(1)) printf("1.0000\n"); else if (abs(caculate(mid)) < 0.00001 && mid >= 0 && mid <= 1) printf("%.4lf\n",mid); else cout << "No solution" << endl; } }
true
adb0982fa66901c833dda7f8ee79c4fba7fc70e9
C++
ellaineeurriele/EXPERIMENT2
/CHUA_EXPERIMENT2.4.cpp
UTF-8
326
2.59375
3
[]
no_license
#include <iostream> #include <conio.h> #include <iomanip> using namespace std; int main() { int count, counter; counter = 1; for (count = 1; count <= 10; count++) { cout << counter << ","; counter++; } for (counter = 12; counter <= 30;) { cout << counter << ","; counter += 2; } _getch(); return 0; }
true