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
e8b1082d12a5cf2c57dc194de3fc7fabcd2986c2
C++
ghas-results/ALIA
/audio/common/Semantic/jhcTripleLink.cpp
UTF-8
5,486
2.5625
3
[ "Apache-2.0" ]
permissive
// jhcTripleLink.cpp : properties of entities and relations between them // // Written by Jonathan H. Connell, jconnell@alum.mit.edu // /////////////////////////////////////////////////////////////////////////// // // Copyright 2015 IBM Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////// #include <string.h> #include "Semantic/jhcTripleLink.h" /////////////////////////////////////////////////////////////////////////// // Creation and Configuration // /////////////////////////////////////////////////////////////////////////// //= Default constructor initializes certain values. // assumes n and fcn are non-NULL and point to valid items jhcTripleLink::jhcTripleLink (jhcTripleNode *n, const char *fcn) { jhcTripleLink *t, *t0 = NULL; // basic information topic = n; strcpy_s(slot, fcn); filler = NULL; *txt = '\0'; // list defaults alist = NULL; plist = NULL; prev = NULL; next = NULL; multi = 0; if (n != NULL) { // find END of argument list of topic t = n->args; while (t != NULL) { t0 = t; t = t->alist; } // add new item if (t0 == NULL) n->args = this; else t0->alist = this; } } //= Default destructor does necessary cleanup. jhcTripleLink::~jhcTripleLink () { // remove from argument and property lists rem_arg(); rem_prop(); // remove from double-linked history if (prev != NULL) prev->next = next; if (next != NULL) next->prev = prev; } //= Remove link from argument list of topic and set topic to NULL. void jhcTripleLink::rem_arg () { jhcTripleLink *t, *t0 = NULL; if (topic == NULL) return; // find predecessor in list of arguments t = topic->args; while (t != NULL) { if (t == this) break; t0 = t; t = t->alist; } // splice out of argument list if (t0 == NULL) topic->args = alist; else t0->alist = alist; // locally invalidate topic node (still exists) topic = NULL; alist = NULL; } //= Remove link from property list of filler and set filler to NULL. void jhcTripleLink::rem_prop () { jhcTripleLink *t, *t0 = NULL; if (filler == NULL) return; // find predecessor in list of properties for filler node t = filler->props; while (t != NULL) { if (t == this) break; t0 = t; t = t->plist; } // splice link out of property list for filler node if (t0 == NULL) filler->props = plist; else t0->plist = plist; // locally invalidate filler node (still exists) filler = NULL; plist = NULL; } /////////////////////////////////////////////////////////////////////////// // Main Functions // /////////////////////////////////////////////////////////////////////////// //= Set the value of the slot to be the given node (overwrites old). // returns 1 if changed, 0 if not needed int jhcTripleLink::SetFill (jhcTripleNode *n2) { jhcTripleLink *t, *t0 = NULL; // check given and previous values if (filler == n2) return 0; rem_prop(); // set basic information filler = n2; *txt = '\0'; // find END of property list of new value node t = filler->props; while (t != NULL) { t0 = t; t = t->plist; } // add new item if (t0 == NULL) filler->props = this; else t0->plist = this; return 1; } //= Set the value of the slot to be the given text (overwrites old). // returns 1 if changed, 0 if not needed int jhcTripleLink::SetTag (const char *tag) { // check given and previous values if ((filler == NULL) && (_stricmp(txt, tag) == 0)) return 0; rem_prop(); // set basic information filler = NULL; strcpy_s(txt, tag); return 1; } /////////////////////////////////////////////////////////////////////////// // Debugging Functions // /////////////////////////////////////////////////////////////////////////// //= Print a nice representation of the triple to the console. // can optional prefix with tag string void jhcTripleLink::Print (const char *tag) const { char tail = ((multi > 0) ? '+' : '-'); if (topic == NULL) return; if (tag != NULL) jprintf("%s ", tag); if (filler != NULL) jprintf("%s %c-%s--> %s\n", topic->Name(), tail, slot, filler->Name()); else jprintf("%s %c-%s--> %s\n", topic->Name(), tail, slot, txt); } //= Save a version of the triple with tabs between components to a file. // returns 1 if something written, 0 for problem int jhcTripleLink::Tabbed (FILE *out) const { char post[10] = "++"; if ((out == NULL) || (topic == NULL)) return 0; if (multi <= 0) *post = '\0'; if (filler != NULL) fprintf(out, "%s\t%s\t%s\t%s\n", topic->Name(), slot, filler->Name(), post); else fprintf(out, "%s\t%s\t%s\t%s\n", topic->Name(), slot, txt, post); return 1; }
true
db326695adb8f375352ae62c50814b952fed289e
C++
WhosJohnGault/2018_Fall_17a_JordanJames
/Assignments/Review Homework 1/Gaddis_8th_Edition_5_11_Population/main.cpp
UTF-8
1,877
3.4375
3
[]
no_license
/* * */ /* * File: main.cpp * Author: James Jordan * * Created on August 15, 2018, 8:35 PM */ #include <iostream> #include <cmath> #include <iomanip> using namespace std; // Name global Constants here Pi //function names go here int main(int argc, char** argv) { //initialize variables float p; //number of organisms float r; //average increase in the number of organisms int t; //number of days organisms spent multiplying int i=1; //starting increment float y; //y is a place holder in the exponent float e=2.71828183;//eulurs number //assign values to variables cout<<"This program will predict the population changes in a species of organisms"<<endl; cout<<"Please enter the number of starting organisms"<<endl; cin>>p; while(p<2){ //this loop mill ensure a valid population is entered cout<<"Please enter a number equal or greater to 2"<<endl; cin>>p; } cout<<"Please enter the average daily increase as a percentage"<<endl; cin>>r; while(r<0){ //this loop will terminate once a positive number is entered cout<<"Please enter a number equal to or greater than 0"<<endl; cin>>r; } cout<<"How many days should the organisms be allowed to multiply?"<<endl; cin>>t; while(t<1){ //this loop will terminate once t is equal to or greater than 1 cout<<"Cmon man stop wasting my time put in a number greater than 1 atleast"<<endl; cin>>t; } y=r*i; //this will simply the exponent for easier computation //calculations go here while(i<=t){ //this loop will calculate the daily population of some organisms and will loop until the user inputed number of //days has passed p=p*pow(e,y); //equation for exponential population increase cout<<setprecision(0)<<fixed<<p<<endl; //this will ensure population estimate is accurate i++; //increment for the counter } return 0; }
true
7194375063dba10afeba2ea4d7526a1d4f40982f
C++
mwlazlo/slugger
/slugger/log.cpp
UTF-8
5,185
2.765625
3
[ "Apache-2.0" ]
permissive
#include <cstdlib> #include <fcntl.h> #include <unistd.h> #include <assert.h> #include <pthread.h> #include <iostream> #include <string> #include <map> #include <algorithm> #include <stdexcept> #include <slugger/slugger.h> #include "scope_guard.h" using namespace slugger; // a bit better than global variables static struct log_data { logging_level level_default; #if defined(PER_THREAD_LEVEL) typedef std::map<pthread_t, logging_level> levels_type; levels_type levels; pthread_mutex_t levels_mux; log_data(): level_default(debug_t) { pthread_mutex_init(&levels_mux, 0); init(); } ~log_data() { pthread_mutex_destroy(&levels_mux); } #else log_data(): level_default(debug_t) { init(); } #endif /** * The syslog facility (when using syslog target) */ syslog_facility facility; /** * The program's name */ std::string program_name; /** * User defined stream id prefix */ stream_prefix_func stream_op; void init() { facility = local0_t; program_name = "Untitled Application"; stream_op = 0; } } priv_data; // In the absence of boost::shared_ptr, this class will ensure the destination // is freed. struct singleton_guard { destination *singleton; singleton_guard(): singleton(0) { } virtual ~singleton_guard() { replace(0); } void replace(destination *dest) { if(singleton) delete singleton; singleton = dest; } }; static singleton_guard guard; void slugger::register_stream(const destination::pointer ls) { guard.replace(ls); } static bool has_no_control_tty() { int fd = open("/dev/tty", O_RDONLY); if(fd >= 0) { close(fd); return false; } return true; } destination& slugger::get_singleton() { destination *ptr = guard.singleton; if (!ptr) { if(has_no_control_tty()) ptr = stream::sys_log::create(); else ptr = stream::std_err::create(); assert(ptr); guard.replace(ptr); } return *ptr; } const char* slugger::level_to_string(logging_level level) { switch(level) { case debug_t: return "debug"; case info_t: return "info"; case notice_t: return "notice"; case warning_t: return "warning"; case err_t: return "err"; case crit_t: return "crit"; case alert_t: return "alert"; case emerg_t: return "emerg"; default: return "unknown"; } } std::ostream& slugger::operator<<(std::ostream& o, const slugger::logging_level& ll) { o << slugger::level_to_string(ll); return o; } struct _log_parse_table_t { std::string name; logging_level level; bool operator==(const std::string &str) { return name == str; } }; logging_level slugger::string_to_level(const std::string& level) { static _log_parse_table_t table[] = { { "debug", debug_t }, { "info", info_t }, { "notice", notice_t }, { "warning", warning_t }, { "err", err_t }, { "crit", crit_t }, { "alert", alert_t }, { "emerg", emerg_t }, { "INVALID", debug_t } }; static _log_parse_table_t* table_end = table + ((sizeof(table) / sizeof(table[0])) - 1); _log_parse_table_t* t = std::find(table, table_end, level); if(t == table_end) { throw std::invalid_argument("Invalid log level"); } else { return t->level; } } std::istream& slugger::operator>>(std::istream& i, slugger::logging_level& l) { std::string buf; i >> buf; l = slugger::string_to_level(buf); return i; } void slugger::set_facility(syslog_facility f) { priv_data.facility = f; } syslog_facility slugger::get_facility() { return priv_data.facility; } void slugger::set_program_name(const std::string &p) { priv_data.program_name = p; } const std::string& slugger::get_program_name() { return priv_data.program_name; } void slugger::set_logging_level_default(logging_level level) { priv_data.level_default = level; } void slugger::set_logging_level(logging_level level) { #if defined(PER_THREAD_LEVEL) priv_lock_guard guard(&priv_data.levels_mux); priv_data.levels[pthread_self()] = level; #else priv_data.level_default = level; #endif } logging_level slugger::get_logging_level() { #if defined(PER_THREAD_LEVEL) priv_lock_guard guard(&priv_data.levels_mux); log_data::levels_type::iterator i = priv_data.levels.find(pthread_self()); if(i == priv_data.levels.end()) return priv_data.level_default; else return i->second; #else return priv_data.level_default; #endif } void slugger::set_stream_prefix(stream_prefix_func fn) { priv_data.stream_op = fn; } stream_prefix_func slugger::get_stream_prefix() { return priv_data.stream_op; } // vim: set ts=4 sw=4 et :
true
31a23211e39ce694e47e4e5c2db75fcbcbb92277
C++
dpw901e17/vulkan-application
/Vulkan/Main.cpp
UTF-8
1,443
2.8125
3
[ "MIT" ]
permissive
#include <iostream> #include <sstream> #include <stdexcept> #include <string> #include "../../scene-window-system/TestConfiguration.h" #include "../scene-window-system/Scene.h" #include "VulkanApplication.h" const int WIDTH = 800; const int HEIGHT = 600; // Called from main(). Runs this example. int runVulkanTest(const TestConfiguration& configuration) { auto cubeCountPerDim = configuration.cubeDimension; auto paddingFactor = configuration.cubePadding; Window win = Window(GetModuleHandle(nullptr), "VulkanTest", "Vulkan Test", WIDTH, HEIGHT); Camera camera = Camera::Default(); auto heightFOV = camera.FieldOfView() / win.aspectRatio(); auto base = (cubeCountPerDim + (cubeCountPerDim - 1) * paddingFactor) / 2.0f; auto camDistance = base / std::tan(heightFOV / 2); float z = camDistance + base + camera.Near(); camera.SetPosition({ 0.0f, 0.0f, z, 1.0f }); auto magicFactor = 2; camera.SetFar(magicFactor * (z + base + camera.Near())); auto scene = Scene(camera, cubeCountPerDim, paddingFactor); VulkanApplication app(scene, win); try { app.run(); } catch (const std::runtime_error& e) { std::cerr << e.what() << std::endl; exit(EXIT_FAILURE); } } int main(int argc, char *argv[]) { std::stringstream arg; for (auto i = 0; i < argc; ++i) { arg << argv[i] << " "; } TestConfiguration::SetTestConfiguration(arg.str().c_str()); auto& conf = TestConfiguration::GetInstance(); runVulkanTest(conf); }
true
9b794c03bb8abe9db04babcd8bd357fad8fdea3f
C++
ladycharliy/C-Assignments
/Math Tutor.cpp
WINDOWS-1252
4,290
3.984375
4
[]
no_license
/// Math Tutor.cpp : This file contains the 'main' function. Program execution begins and ends there. //Charlotte Martin //ITSE 1307 C++ //07FEB2019 //The program will be used as a math tutor for a young student. Will display 2 random numbers #include "pch.h" #include <math.h> #include <iostream> #include <iomanip> #include <string> #include <cstdlib> #include <ctime> using namespace std; int main() { int num1, // The first random number num2, // The second random number choice, // The user's choice of problem temp; string studentAnswer, // The student's answer correctAnswer; // The correct answer srand(time(0)); // Seed the random number generator. do { //Display a choice of math problems cout << "\tMath Tutor Menu\n"; cout << "------------------------------\n"; cout << "1. Addition Problems\n"; cout << "2. Subtraction Problems\n"; cout << "3. Multiplication Problems\n"; cout << "4. Division Problems\n"; cout << "5. Quit the Math Tutor\n"; cout << "------------------------------\n"; cout << "Enter your choice (1-5): "; cin >> choice; // Validate the choice. while (choice < 1 || choice > 5) { cout << "The valid choices are 1, 2, 3, " << "4, and 5. Please choose: "; cin >> choice; } // Produce a problem. switch (choice) { case 1: //Addition Problem //will generate 2 random numbers within the range of 1-500 num1 = 1 + rand() % 500; num2 = 1 + rand() % 500; // Calculate the correct answer. correctAnswer = to_string(num1 + num2); // Display the problem. cout << "\n\n"; cout << " " << setw(4) << num1 << endl; cout << " +" << setw(4) << num2 << endl; cout << " " << "----" << endl; cout << " "; break; case 2: //Subtraction Problem //will generate 2 random numbers within the range of 1-999 num1 = 1 + rand() % 999; num2 = 1 + rand() % 999; // Make sure num2 <= num1... while (num2 > num1) num2 = 1 + rand() % 999; // Calculate the correct answer. correctAnswer = to_string(num1 - num2); // Display the problem. cout << "\n\n"; cout << " " << setw(4) << num1 << endl; cout << " -" << setw(4) << num2 << endl; cout << " " << "----" << endl; cout << " "; break; case 3: //Multiplication Problem //will generate 2 random numbers, the 1st within the range of 1-100 //and the 2nd within the range of 1-9. This keeps the numbers from becoming to large. num1 = 1 + rand() % 100; num2 = 1 + rand() % 9; // Calculate the correct answer. correctAnswer = to_string(num1 * num2); // Display the problem. cout << "\n\n"; cout << " " << setw(4) << num1 << endl; cout << " x" << setw(4) << num2 << endl; cout << " " << "----" << endl; cout << " "; break; case 4: //Division Problem with no remainder //generate a single digit divisor num2 = 1 + rand() % 9; //generate a number that is a multiple of num2 num1 = num2 *(rand() % 50+1); // Calculate the correct answer. correctAnswer = to_string(num1 / num2); // Display the problem. cout << "\n\n"; //cout << " " << setw(4) << num1 << endl; //cout << " " << setw(4) << num2 << endl; //cout << " " << "----" << endl; //I can not get this too display correctly but the math works cout<< " " <<setw(4)<< num1<< " /" << setw(4) <<num2 << " = "; // most answers will be 0 or whole numbers instead of using decimals break; case 5: // The user chose to quit the program. cout << "Thank you for using The Math Tutor. Goodbye.\n\n"; break; } // If student selected a problem, get and evaluate the answer. if (choice >= 1 && choice <= 4) { if (choice == 1) { //Get Answer from user cin >> temp; studentAnswer = to_string(temp); } else { cin >> studentAnswer; } if (studentAnswer == correctAnswer) cout << "\n\nCongratulations! That's right.\n\n"; else cout << "\n\nSorry, the correct answer is " << correctAnswer << ".\n\n"; } } while (choice != 5); // Loop again if student did not choose to quit. return 0; }
true
4effddb038fc9e86a78abad05eee78ad41507af4
C++
pChochura/Nonogram
/Nonogram/src/Models/Game.h
UTF-8
741
2.75
3
[]
no_license
#pragma once #include "Screens/Screen.h" //////////////////////////////////////////////////////////// // Class descrining game state //////////////////////////////////////////////////////////// class Game { public: Game(Screen* firstScreen, std::string title, int width = 1080, int height = 720); //////////////////////////////////////////////////////////// // It's used to change displayed screen //////////////////////////////////////////////////////////// void changeScreen(Screen*); //////////////////////////////////////////////////////////// // Method used to show current screen. //////////////////////////////////////////////////////////// void show(); private: int width, height; Screen* screen; Context* context; };
true
6fcee980c918f800fe87e2f81d1f76878af9015b
C++
novaua/qt-chess
/ChessCore/Move.h
UTF-8
679
2.8125
3
[]
no_license
#pragma once #include "Board.h" namespace Chess { struct Move { BoardPosition From; BoardPosition To; bool Capturing; Piece PromotedTo; std::string ToString()const; static Move Parse(const std::string& strMove); }; struct PositionPiece { BoardPosition Position; Piece Piece; size_t GetHashCode() const; }; struct HistoryMove { int Id; PositionPiece From; PositionPiece To; Piece PromotedTo; bool IsCapturingMove() const; bool IsPawnPromotionMove() const; Move ToMove() const; std::string ToUciString() const; }; typedef std::vector<HistoryMove> MovesHistory; typedef std::shared_ptr<MovesHistory> MovesHistoryAptr; }
true
0b0a2711d2b02aac6685c478ad24b9152926532e
C++
Itchibon777/PowerToys
/src/modules/fancyzones/tests/UnitTests/RegistryHelpers.Spec.cpp
UTF-8
1,145
2.59375
3
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
#include "pch.h" #include "lib\RegistryHelpers.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace FancyZonesUnitTests { TEST_CLASS(RegistryHelpersUnitTests) { public: TEST_METHOD(GetDefaultKey) { // Test the path to the key is the same string. wchar_t key[256]; Assert::AreEqual(0, wcscmp(RegistryHelpers::GetKey(nullptr, key, ARRAYSIZE(key)), L"Software\\SuperFancyZones")); } TEST_METHOD(GetKeyWithMonitor) { // Test the path to the key is the same string. wchar_t key[256]; Assert::AreEqual(0, wcscmp(RegistryHelpers::GetKey(L"Monitor1", key, ARRAYSIZE(key)), L"Software\\SuperFancyZones\\Monitor1")); } TEST_METHOD(OpenKey) { // The default key should exist. wil::unique_hkey key{ RegistryHelpers::OpenKey({}) }; Assert::IsNotNull(key.get()); // The Monitor1 key shouldn't exist. wil::unique_hkey key2{ RegistryHelpers::OpenKey(L"Monitor1") }; Assert::IsNull(key2.get()); } }; }
true
467fa1f27fc91c6a5b6e8ced6a2e7eeeb0b82d58
C++
hieulag15/21110448-lv7
/lv7-08.cpp
UTF-8
941
3.34375
3
[]
no_license
#include<iostream> #include<math.h> void Nhapmang(int arr[], int &n); void Xuatmang(int arr[], int n); bool Kiemtra(int n); float Avg(int arr[], int n); using namespace std; #define Max_Size 100 int main() { int arr[Max_Size]; int n; Nhapmang(arr,n); cout<<"trung binh cong: "<<Avg(arr,n); return 0; } void Nhapmang(int arr[], int &n){ do { cout<<"Nhap Do dai cua mang: "; cin>>n; } while ((n < 1 ) or (n > Max_Size)); for (int i =0; i < n; i++) { cout<<"Arr["<<i<<"]= "; cin >> arr[i]; } } void Xuatmang(int arr[], int n){ for (int i = 0; i < n; i++) cout<<arr[i]<<" "; } bool Kiemtra(int n){ if (n < 2 ) return false; for (int i = 2; i <= sqrt(n); i++){ if (n % i == 0) { return false; } } return true; } float Avg(int arr[], int n) { int count = 0; float sum = 0; for (int i = 0; i < n; i++) { if(Kiemtra(arr[i])) { sum += arr[i]; count++; } } float avg = sum / count; return avg; }
true
1649ec25aee8a57eea2834ac7e1e52b543bafe53
C++
NikitaEvs/WildHack
/src/Engine/Handler/MoveHandler.cpp
UTF-8
301
2.75
3
[]
no_license
#include "MoveHandler.h" void MoveHandler::change() { if (xPos == -1 || yPos == -1) { throw std::runtime_error("Position to move to was not chosen"); } else { population->move(xPos, yPos); } } void MoveHandler::setXYPos(int32_t x_pos, int32_t y_pos) { xPos = x_pos; yPos = y_pos; }
true
d2ae3b2e6d022ab96c1b46b22b4378867cd532f9
C++
harrituononen/winged-tanks
/airb/src/network/socket/client_socket_win.cpp
UTF-8
5,423
2.5625
3
[]
no_license
#include "client_socket_win.hpp" #include <cstdio> #include <thread> #include "../player.hpp" #include "../utilities/functions.hpp" namespace network { ClientSocket::ClientSocket(std::string server_address, unsigned short server_port) : m_listener_running(false) , m_keepalive_running(false) , m_id { '\0' } , m_server_addr(server_address) , m_queue() { memset(reinterpret_cast<char *>(&m_server_sockaddr), 0, sizeof m_server_sockaddr); m_server_sockaddr.sin_family = AF_INET; m_server_sockaddr.sin_port = htons(server_port); m_server_sockaddr.sin_addr.S_un.S_addr = inet_addr(m_server_addr.c_str()); open(); } ClientSocket::~ClientSocket() { close(); } void ClientSocket::open() { WSAData wsa; // Initialise winsock print_time(); printf("Initialising Winsock... "); if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { printf("Failed. Error Code : %d\n", WSAGetLastError()); throw std::runtime_error("WSAStartup() failed."); } printf("Initialised.\n"); // Create socket m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (m_socket == INVALID_SOCKET) { print_time(); printf("socket() failed with error code : %d\n", WSAGetLastError()); throw std::runtime_error("Socket creation failed."); } struct sockaddr_in listener; listener.sin_family = AF_INET; listener.sin_port = htons(8887); listener.sin_addr.s_addr = INADDR_ANY; if (bind(m_socket, reinterpret_cast<struct sockaddr *>(&listener), sizeof listener) == SOCKET_ERROR) { printf("Bind failed with error code : %d\n", WSAGetLastError()); throw std::runtime_error("Socket bind() failed."); } } void ClientSocket::close() const { shutdown(m_socket, SD_BOTH); closesocket(m_socket); WSACleanup(); } void ClientSocket::init_connect() { print_time(); printf("Attempting to connect...\n"); send(UdpPacket(UDP_H_CONNECT)); } void ClientSocket::start_listener_routine() { char buffer[UDP_MAX_PACKET_SIZE]; int slen = sizeof m_server_sockaddr; int recv_data; m_listener_running = true; while (m_listener_running) { memset(buffer, UDP_H_NULL, UDP_MAX_PACKET_SIZE); recv_data = recvfrom(m_socket, buffer, sizeof buffer, 0, reinterpret_cast<struct sockaddr *>(&m_server_sockaddr), &slen); if (recv_data == SOCKET_ERROR) { print_time(); printf("recvfrom() failed with error code : %d\n", WSAGetLastError()); std::this_thread::sleep_for(std::chrono::milliseconds(PING_FREQUENCY_MS)); continue; } process_packet(UdpPacket(buffer)); } } void ClientSocket::start_keepalive_routine() { m_keepalive_running = true; while (m_keepalive_running) { while(m_id[0] == '\0') { std::this_thread::sleep_for(std::chrono::milliseconds(PING_FREQUENCY_MS/4)); // Debug window closed if (!m_keepalive_running) return; } send(UdpPacket(UDP_H_KEEPALIVE | UDP_H_DATABLOCK, m_id)); std::this_thread::sleep_for(std::chrono::milliseconds(PING_FREQUENCY_MS)); } } void ClientSocket::end_listener_routine() { m_listener_running = false; } void ClientSocket::end_keepalive_routine() { m_keepalive_running = false; } void ClientSocket::send(UdpPacket packet) { int slen = sizeof m_server_sockaddr; if (sendto(m_socket, packet.to_char_array(), packet.get_size(), 0, reinterpret_cast<struct sockaddr *>(&m_server_sockaddr), slen) == SOCKET_ERROR) { print_time(); printf("sendto() failed with error code : %d\n", WSAGetLastError()); } if (!packet.header_contains(UDP_H_KEEPALIVE) && !packet.header_contains(UDP_H_INPUT)) { print_time(); printf("Packet sent to server.\n"); packet.print(); } } void ClientSocket::set_client_id(char const* id) { auto i = 0; while (id[i] != '\0') m_id[i] = id[i++]; } bool ClientSocket::has_packets() const { return !m_queue.empty(); } char* ClientSocket::get_client_id() const { return const_cast<char*>(&m_id[0]); } UdpPacket ClientSocket::get_packet() { return m_queue.dequeue(); } std::string ClientSocket::get_server_addr() const { return m_server_addr; } void ClientSocket::process_packet(UdpPacket const packet) { if (!packet.header_contains(UDP_H_INPUT) && !packet.header_contains(UDP_H_POS)) { print_time(); printf("Received packet from server\n"); packet.print(); } if (packet.header_contains(UDP_H_CONNECT) && packet.header_contains(UDP_H_OK) && packet.header_contains(UDP_H_DATABLOCK)) { // First connect, server returns unique id strcpy_s(m_id, packet.get_data_block()); print_time(); printf("Connected. My id is %s\n", m_id); } if (packet.header_contains(UDP_H_CONNECT) && packet.header_contains(UDP_H_ERROR)) { print_time(); printf("Server refused connection...\n"); //close(); } m_queue.enqueue(packet); } } // namespace network
true
6727e8d235f56401289cadebff9f4d336f60e811
C++
VinyPinheiro/EA_PIBIC
/src/solo.cpp
UTF-8
1,264
2.703125
3
[]
no_license
/* * Implementação da classe Solo. * * Autor: Edson Alves * Data: 11/06/2015 * Licença: LGPL. Sem copyright. */ #include "solo.h" #include <ijengine/core/text.h> #include <ijengine/core/font.h> #include <ijengine/core/image.h> #include <ijengine/core/environment.h> #include <ijengine/util/button.h> Solo::Solo(const string& next) : Level("solo", next) { Environment *env = Environment::get_instance(); set_dimensions(env->canvas->w(), env->canvas->h()); shared_ptr<Font> font = env->resources_manager->get_font("res/fonts/AjarSans-Regular.ttf"); font->set_size(90); font->set_style(Font::BOLD); env->canvas->set_font(font); Image *image = new Image(this, "res/images/background.png"); add_child(image); vector<pair<string, string> > button; button.emplace_back("Sim","trator"); button.emplace_back("Não","gameover"); question = new Question(this, "Preparando Solo", "Colocar fertilizantes e calcário?" , button); add_child(question); } void Solo::draw_self() { Environment *env = Environment::get_instance(); env->canvas->clear(Color::WHITE); } void Solo::update_self(unsigned long) { if(question->finished()) { this->set_next(question->next()); this->finish(); } }
true
0b793ed4493939f4307fa81b6798842f42be1158
C++
BlackNapalm/Codingame
/Code of Kutulu.cpp
UTF-8
18,442
2.71875
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <tuple> #include <math.h> using namespace std; //enum State {SPAWNING = 0, WANDERING}; const char WALL = '#', SPAWN = 'w', SHELTER = 'U'; const double DEFDANGER = 9999; vector<int> yelledat; class Tile { private: int x, y; char tiletype; double baseDanger = DEFDANGER, turnDanger = baseDanger; public: Tile () {} Tile (int x, int y, char t) : x(x), y(y), tiletype(t) {} int get_x() {return x;} int get_y() {return y;} char get_type() {return tiletype;} double get_baseDanger() {return baseDanger;} double get_turnDanger() {return turnDanger;} void set_baseDanger(double d) {baseDanger = d;} void set_turnDanger(double d) {turnDanger = d;} void adj_turnDanger(double d) {turnDanger += d;} int get_distance(Tile other) { return abs(this->x - other.x) + abs(this->y - other.y); } }; class Unit { protected: int x, y, id; public: Unit (int c, int r, int i) : x(c), y(r), id(i) {} int get_distance(Unit other) { return abs(this->x - other.x) + abs(this->y - other.y); } int get_distance(Tile other) { return abs(this->x - other.get_x()) + abs(this->y - other.get_y()); } int get_x() {return x;} int get_y() {return y;} int get_id() {return id;} bool same(Unit other) { return this->id == other.id; } bool samepos(Unit other) { if (x == other.get_x() and y == other.get_y()) { return true; } else {return false;} } }; class Effect: public Unit { private: int turns, trigger_id, target_id; public: Effect (int c, int r, int i, int t, int sid, int tid) : Unit(c, r, i), turns(t), trigger_id(sid), target_id(tid) {} }; class Shelter: public Unit { private: int energy; public: Shelter (int c, int r, int i, int e) : Unit(c, r, i), energy(e) {} int get_energy() {return energy;} }; class Plan: public Unit { private: int turns; public: Plan (int c, int r, int i, int e) : Unit(c, r, i), turns(e) {} int get_turns() {return turns;} }; class Wanderer: public Unit { private: int turns, state, target; public: Wanderer (int x, int y, int id, int turn, int state, int target) : Unit(x, y, id), turns(turn), state(state), target(target) {} int get_state() {return state;} int get_target() {return target;} int get_turns() {return turns;} }; class Explorer: public Unit { private: int sanity, plans, lights; public: Explorer (int x, int y, int id, int san, int plan, int light) : Unit(x, y, id), sanity(san), plans(plan), lights(light) {} int get_sanity() {return sanity;} bool yell_check(vector<Explorer> e, vector<Wanderer> w) { bool canyell = false; for (Wanderer y : w) { if (get_distance(y) == 1) { return false; } } for (Explorer x : e) { if (same(x)) {continue;} bool yellat = false; for (int i : yelledat) { if (x.get_id() == i) { yellat = true; } } if (yellat) {continue;} if (get_distance(x) > 1) {continue;} bool closewanderer = false; for (Wanderer y : w) { if (y.get_state() == 0) {continue;} if (x.get_distance(y) > 2) {continue;} closewanderer = true; } if (!closewanderer) {return false;} if (e.back().get_id() == x.get_id()) { canyell = true; } } return canyell; } bool light_check(vector<Explorer> e, vector<Wanderer> w) { if (lights < 1) {return false;} for (Explorer x : e) { if (same(x)) {continue;} if (samepos(x)) {continue;} for (Wanderer y : w) { if (get_distance(y) == 1) {return false;} if (y.get_target() != id) {continue;} if (get_distance(x) < x.get_distance(y)) {continue;} if (get_distance(x) > 6) {continue;} if (get_distance(y) + 4 > x.get_distance(y)) { return true; } } } } bool plan_check(vector<Explorer> e, vector<Wanderer> w) { if (plans < 1) {return false;} if (sanity > 250 - e.size() * 15) {return false;} for (Wanderer x : w) { if (get_distance(x) == 1) {return false;} } int ecount = 0; for (Explorer x : e) { if (get_distance(x) < 3 ) {ecount++;} } if (ecount == e.size()) {return true;} return false; } }; class Slasher: public Unit { private: int turns, state, target; public: Slasher (int x, int y, int id, int turn, int state, int target) : Unit(x, y, id), turns(turn), state(state), target(target) {} int get_turns() {return turns;} int get_state() {return state;} }; class GameBoard { private: int width, height, sanityLossLonely, sanityLossGroup, wandererSpawnTime, wandererLifeTime; vector<vector<Tile>> board; vector<Tile> spawns; vector<Tile> shelters; public: GameBoard(int w, int h) : width(w), height(h) {} void set_BaseDanger() { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { char type = board[j][i].get_type(); if (type == WALL) {continue;} double danger = sanityLossLonely; for (Tile t : spawns) { int dist = t.get_distance(board[j][i]); danger += (width * height - dist) / (width + height); board[j][i].set_baseDanger(danger); } } } } void set_Board(vector<string> map) { for (int i = 0; i < width; i++) { vector<Tile> line; for (int j = 0; j < height; j++) { Tile foo(i, j, map[j][i]); line.push_back(foo); if (foo.get_type() == SPAWN) { spawns.push_back(foo); } else if (foo.get_type() == SHELTER) { shelters.push_back(foo); } } board.push_back(line); } } void set_BoardParam(int sll, int slg, int wst, int wlt) { sanityLossLonely = sll; sanityLossGroup = slg; wandererSpawnTime = wst; wandererLifeTime = wlt; this->set_BaseDanger(); } void print_Board() { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { cerr << board[j][i].get_type() << "(" << board[j][i].get_turnDanger() << ")"; } cerr << endl; } } vector<Tile> get_safeTiles(Explorer e) { vector<Tile> safeTiles; double lowDanger = DEFDANGER; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { double danger = board[j][i].get_turnDanger() + (e.get_distance(board[j][i]) / 7); // sqrt(width + height)); if (danger < lowDanger) { lowDanger = danger; safeTiles.clear(); } if (danger == lowDanger) { safeTiles.push_back(board[j][i]); } } } return safeTiles; } string pathfind (Explorer e, Tile t) { if (e.get_x() == t.get_x() and e.get_y() == t.get_y()) {return "WAIT";} //return "WAIT" vector<tuple<Tile, string, double>> myqueue; tuple<Tile, string, double> foo (board[e.get_x()][e.get_y()], "", board[e.get_x()][e.get_y()].get_turnDanger()); myqueue.push_back(foo); vector<Tile> checkedTiles; while (!myqueue.empty()) { int queuepos = 0, minDanger = get<2>(myqueue.front()); for (int i = 0; i < myqueue.size(); i++){ if (get<2>(myqueue[i]) < minDanger) { queuepos = i; minDanger = get<2>(myqueue[i]); } } Tile check; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { if (abs(i) + abs(j) != 1) {continue;} check = board[get<0>(myqueue[queuepos]).get_x() + i][get<0>(myqueue[queuepos]).get_y() + j]; if (check.get_type() != WALL) { bool checked = false; for (Tile t : checkedTiles) { if (t.get_x() == check.get_x() and t.get_y() == check.get_y()) {checked = true;} } if (!checked) { string dir = ""; if (get<1>(myqueue[queuepos]) == "") { if (i == -1) { dir = "LEFT"; } else if (i == 1) { dir = "RIGHT"; } else if (j == -1) { dir = "UP"; } else if (j == 1) { dir = "DOWN"; } } else {dir = get<1>(myqueue[queuepos]);} if (check.get_x() == t.get_x() and check.get_y() == t.get_y()) {return dir;} get<0>(foo) = check; get<1>(foo) = dir; get<2>(foo) = check.get_turnDanger() / e.get_distance(check) + get<2>(myqueue[queuepos]); myqueue.push_back(foo); checkedTiles.push_back(check); } } } } myqueue.erase(myqueue.begin()); } return "WAIT"; } string get_movement(Explorer e) { vector<Tile> safeTiles; safeTiles = get_safeTiles(e); Tile safeTile; int lowDist = width + height; for (Tile t : safeTiles) { int dist = e.get_distance(t); if (dist < lowDist) { safeTile = t; lowDist = dist; } } return pathfind(e, safeTile); } void adjDanger(Unit u, int dist, double adjust) { for (int i = -dist; i < dist + 1; i++) { for (int j = -dist; j < dist + 1; j++) { if (abs(i) + abs(j) > dist) {continue;} if (u.get_x() + i < 0 or u.get_x() + i >= width) {continue;} if (u.get_y() + j < 0 or u.get_y() + j >= height) {continue;} board[u.get_x() + i][u.get_y() + j].adj_turnDanger(adjust); } } } void adjDanger(Unit u, double adjust) { board[u.get_x()][u.get_y()].adj_turnDanger(adjust); bool up = true, down = true, left = true, right = true; for (int i = 1; i < max(width, height); i++) { if (u.get_x() - i >= 0 and left) { if (board[u.get_x() - i][u.get_y()].get_type() != WALL) { board[u.get_x() - i][u.get_y()].adj_turnDanger(adjust); } else {left = false;} } if (u.get_x() + i < width and right) { if (board[u.get_x() + i][u.get_y()].get_type() != WALL) { board[u.get_x() + i][u.get_y()].adj_turnDanger(adjust); } else {right = false;} } if (u.get_y() - i >= 0 and up) { if (board[u.get_x()][u.get_y() - i].get_type() != WALL) { board[u.get_x()][u.get_y() - i].adj_turnDanger(adjust); } else {up = false;} } if (u.get_y() + i < height and down) { if (board[u.get_x()][u.get_y() + i].get_type() != WALL) { board[u.get_x()][u.get_y() + i].adj_turnDanger(adjust); } else {down = false;} } } } void set_turnDanger(vector<Explorer> e, vector<Wanderer> w, vector<Slasher> s, vector<Shelter> u, vector<Plan> p) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { board[j][i].set_turnDanger(board[j][i].get_baseDanger()); } } for (Explorer x : e) { if (x.same(e.front())) {continue;} double danAdj = sanityLossGroup - sanityLossLonely; adjDanger(x, 2, danAdj/2); adjDanger(x, 1, danAdj/2); } for (Wanderer x : w) { double danAdj = 20;//x.get_turns(); //for (int i = x.get_turns(); i > 0; i--) { //} adjDanger(x, 2, danAdj); } for (Slasher x : s) { double danAdj = 10; if (x.get_state() == 0 or x.get_state() == 4) {danAdj *= (6-x.get_turns())/6;} adjDanger(x, 2, danAdj); adjDanger(x, danAdj); } for (Shelter x : u) { double danAdj = -5 + -5 * (x.get_energy()/(e.front().get_distance(x)+1)); adjDanger(x, 0, danAdj); } for (Plan x : p) { double danAdj = -3 * x.get_turns(); adjDanger(x, 2, danAdj); } } }; int main() { int width; cin >> width; cin.ignore(); int height; cin >> height; cin.ignore(); GameBoard board (width, height); vector<string> map; for (int i = 0; i < height; i++) { string line; getline(cin, line); map.push_back(line); } int sanityLossLonely; // how much sanity you lose every turn when alone, always 3 until wood 1 int sanityLossGroup; // how much sanity you lose every turn when near another player, always 1 until wood 1 int wandererSpawnTime; // how many turns the wanderer take to spawn, always 3 until wood 1 int wandererLifeTime; // how many turns the wanderer is on map after spawning, always 40 until wood 1 cin >> sanityLossLonely >> sanityLossGroup >> wandererSpawnTime >> wandererLifeTime; cin.ignore(); board.set_Board(map); board.set_BoardParam(sanityLossLonely, sanityLossGroup, wandererSpawnTime, wandererLifeTime); // game loop while (1) { int entityCount; // the first given entity corresponds to your explorer cin >> entityCount; cin.ignore(); vector<Explorer> explorers; vector<Wanderer> wanderers; vector<Slasher> slashers; vector<Shelter> shelters; vector<Plan> plans; //Explorer * myexplorer; for (int i = 0; i < entityCount; i++) { string entityType; int id; int x; int y; int param0; int param1; int param2; cin >> entityType >> id >> x >> y >> param0 >> param1 >> param2; cin.ignore(); if (entityType == "EXPLORER") { Explorer foo (x, y, id, param0, param1, param2); explorers.push_back(foo); //if (i == 0) {myexplorer = &explorers.front();} } else if (entityType == "WANDERER") { Wanderer foo (x, y, id, param0, param1, param2); wanderers.push_back(foo); } else if (entityType == "SLASHER") { Slasher foo (x, y, id, param0, param1, param2); slashers.push_back(foo); } else if (entityType == "EFFECT_SHELTER") { Shelter foo(x, y, id, param0); shelters.push_back(foo); } else if (entityType == "EFFECT_PLAN") { Plan foo(x, y, id, param0); plans.push_back(foo); } } board.set_turnDanger(explorers, wanderers, slashers, shelters, plans); //board.print_Board(); //logic string str = ""; if (explorers.front().yell_check(explorers, wanderers)) { str = "YELL BEHIND YOU!"; for (Explorer e : explorers) { if (explorers.front().get_distance(e) < 2) { yelledat.push_back(e.get_id()); } } } else if (explorers.front().plan_check(explorers, wanderers)) { str = "PLAN Lets work together."; } else if (explorers.front().light_check(explorers, wanderers)) { str = "LIGHT A light in the darkness"; } else { str = board.get_movement(explorers.front()); } cout << str << endl; } }
true
4b3d7fc5578bbe3cad7a7770552e8cce84f8b11e
C++
parthpankajtiwary/spoj
/eights.cpp
UTF-8
349
2.984375
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main() { vector <long long int> numbers; int t; cin>>t; for(int i = 0; i < t; i++) { long long int temp; cin>>temp; numbers.push_back(temp); } for(int i = 0; i < numbers.size(); i++) { cout<<((numbers[i]-1)*250)+192<<endl; } }
true
228115911ff09f233dd4bf869057d8640cababbb
C++
Moe2Code/STM32F407xx_Drivers_and_Apps
/supporting_arduino_sketches/sketches/SPI/001SPISlaveRxString/001SPISlaveRxString.ino
UTF-8
2,391
2.8125
3
[]
no_license
/* * Project: SPISlaveRxString * Description: Sketch to demo SPI slave (Arduino Uno) receiving a message from SPI master (ST Discovery board). * The following used: * + Arduino Uno * + SPI SCK Pin 13 (Serial Clock) * + SPI MISO Pin 12 (Master In Slave Out) * + SPI MOSI Pin 11 (Master Out Slave In) * + SPI SS Pin 10 (Slave Select . Arduino SPI pins respond only if SS pulled low by the master) * Author: niekiran * https://github.com/niekiran/MasteringMCU/tree/master/Resources/Arduino */ #include <SPI.h> #include<stdint.h> #define SPI_SCK 13 #define SPI_MISO 12 #define SPI_MOSI 11 #define SPI_SS 10 char dataBuff[500]; //Initialize SPI slave. void SPI_SlaveInit(void) { #if 0 // Initialize SPI pins. pinMode(SPI_SCK, INPUT); pinMode(SPI_MOSI, INPUT); pinMode(SPI_MISO, OUTPUT); pinMode(SPI_SS, INPUT); // Enable SPI as slave. SPCR = (1 << SPE); #endif // Initialize SPI pins. pinMode(SCK, INPUT); pinMode(MOSI, INPUT); pinMode(MISO, OUTPUT); pinMode(SS, INPUT); //make SPI as slave // Enable SPI as slave. SPCR = (1 << SPE); } //This function returns SPDR Contents uint8_t SPI_SlaveReceive(void) { /* Wait for reception complete */ while(!(SPSR & (1<<SPIF))); /* Return Data Register */ return SPDR; } //sends one byte of data void SPI_SlaveTransmit(char data) { /* Start transmission */ SPDR = data; /* Wait for transmission complete */ while(!(SPSR & (1<<SPIF))); } // The setup() function runs right after reset. void setup() { // Initialize serial communication Serial.begin(9600); // Initialize SPI Slave. SPI_SlaveInit(); Serial.println("Slave Initialized"); } uint16_t dataLen = 0; uint32_t i = 0; // The loop function runs continuously after setup(). void loop() { Serial.println("Slave waiting for ss to go low"); while(digitalRead(SS) ); // Serial.println("start"); //1. read the length // dataLen = (uint16_t)( SPI_SlaveReceive() | (SPI_SlaveReceive() << 8) ); //Serial.println(String(dataLen,HEX)); i = 0; dataLen = SPI_SlaveReceive(); for(i = 0 ; i < dataLen ; i++ ) { dataBuff[i] = SPI_SlaveReceive(); } // Serial.println(String(i,HEX)); dataBuff[i] = '\0'; Serial.println("Rcvd:"); Serial.println(dataBuff); Serial.print("Length:"); Serial.println(dataLen); }
true
8bc389f470c5ced1cc6935ef1b58a589eb46a69b
C++
ria28/Data-Structures-And-Algorithms
/DP/Advanced_Dp/MaximalSquare.cpp
UTF-8
1,318
2.75
3
[]
no_license
#include <iostream> #include <string> #include <unordered_set> #include <unordered_map> #include <vector> #include <algorithm> #include <queue> #include <climits> #define ll long long using namespace std; #define f_loop(i, s, e) for (int i = s; i < e; i++) #define f_long(i, s, e) for (long long i = s; i < e; i++) #define vi vector<int> #define vii vector<vector<int>> // https://leetcode.com/problems/maximal-square/ int maximalSquare(vector<vector<int>> &matrix) { if (matrix.size() == 0) return 0; int rows = matrix.size(); int cols = matrix[0].size(); vector<vector<int>> dp(rows + 1, vector<int>(cols + 1, 0)); int max_sq = 0; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= cols; j++) { if (matrix[i - 1][j - 1] == 1) { dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1; max_sq = max(max_sq, dp[i][j]); } } } return max_sq * max_sq; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); vii arr = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; cout << maximalSquare(arr); return 0; }
true
2bfa557a8e5c1910578cd42c83f660a05782192c
C++
josimarribeiro1/projetounib
/Processamento_Paralelo_LED.ino
UTF-8
1,859
3.125
3
[]
no_license
#include "ctimer.h" #define LED0 13 //DEFININDO A VARIAVEL PARA O LED NO CONECTOR 13 #define LED1 12 //DEFININDO A VARIAVEL PARA O LED NO CONECTOR 12 #define LED2 11 //DEFININDO A VARIAVEL PARA O LED NO CONECTOR 11 cTimer g_Timer0(true); //INICIAR OS CONTADORES cTimer g_Timer1(true); //INICIAR OS CONTADORES cTimer g_Timer2(true); //INICIAR OS CONTADORES // Defina aqui os tempos em MS para cada LED piscar: #define TEMPO_0 3000 //AMARELO #define TEMPO_1 3050 //VERDE #define TEMPO_2 3100 //VERMELHO bool gLed0 = false; //BOOLEANO - LIGA/DESLIGA bool gLed1 = false; //BOOLEANO - LIGA/DESLIGA bool gLed2 = false; //BOOLEANO - LIGA/DESLIGA void setup() { pinMode(LED0, OUTPUT); //CONFIGURA O PINO digitalWrite(LED0, 0); //ATIVA O PINO pinMode(LED1, OUTPUT); //CONFIGURA O PINO digitalWrite(LED1, 0); //ATIVA O PINO pinMode(LED2, OUTPUT); //CONFIGURA O PINO digitalWrite(LED2, 0); //ATIVA O PINO g_Timer0.SetTimeOut(TEMPO_0); //RECEBE O TEMPO EM MS g_Timer1.SetTimeOut(TEMPO_1); //RECEBE O TEMPO EM MS g_Timer2.SetTimeOut(TEMPO_2); //RECEBE O TEMPO EM MS } void loop() { //Ou seja, se o timer já atingiu o tempo limite (IsTimeOut() retorna verdadeiro), //inverta o estado do LED e reinicie o contador novamente (parâmetro true no IsTimeOut) . //AMARELO if(g_Timer0.IsTimeOut(true)) //Se o timer esgotar (true), reinicia o contador, assim o LED acende. { digitalWrite(LED0, gLed0); //LED é ativo gLed0 = !gLed0; //Liga/Desliga } //VERDE if(g_Timer1.IsTimeOut(true)) { digitalWrite(LED1, gLed1); //LED é ativo gLed1 = !gLed1; //Liga/Desliga } //VERMELHO if(g_Timer2.IsTimeOut(true)) { digitalWrite(LED2, gLed2); //LED é ativo gLed2 = !gLed2; //Liga/Desliga } }
true
1c6d950846f3ec267fac8d44333fb3b85eb6e35f
C++
Keranos/WebProblems
/UVA/p974.cpp
UTF-8
888
3.015625
3
[]
no_license
#include <iostream> #include <vector> #include <iterator> #include <functional> #include <algorithm> using namespace std; int main(){ int storage[19] = {9, 45, 55, 99, 297, 703, 999 , 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999, 17344, 22222, 38962}; vector<int> v; copy(storage, storage+19, std::back_inserter(v)); int n, lower, upper, count = 0; cin >> n; vector<int>::iterator l_iter, u_iter; while(n--){ cin >> lower >> upper; l_iter = find_if(v.begin(), v.end(), bind2nd(greater<int>(), lower-1)); u_iter = find_if(v.begin(), v.end(), bind2nd(greater<int>(), upper+1)); cout << "case #" << ++count << endl; if(l_iter != u_iter) for(;l_iter != u_iter; ++l_iter) cout << *l_iter << endl; else std::cout << "no kaprekar numbers" << endl; cout << endl; } }
true
f1f53e4bfc88bd8b695cc9484329b0d9c3b15e29
C++
basimkhajwal/ProgrammingChallenges
/Project Euler/problem348.cpp
UTF-8
579
2.921875
3
[]
no_license
#include <iostream> #include <map> using namespace std; #define MAX 1000000000 inline bool isPalindrome(int n) { int x = 0; for (int i = n; i; i /= 10) x = x*10+(i%10); return x == n; } char cnt[MAX]; int main() { for (int i = 2; i*i < MAX; i++) { for (int j = 2;; j++) { int x = i*i+j*j*j; if (x >= MAX) break; cnt[x]++; } } long long ans = 0; int needed = 5; for (int i = 0; i < MAX; i++) { if (cnt[i] == 4 && isPalindrome(i)) { ans += i; if (--needed == 0) break; } } cout << ans << endl; return 0; }
true
a2d8ce4b36238e6b0f3d198a3b6b0440fc339b5b
C++
eelcohn/FileStore
/src/platforms/kbhit.cpp
UTF-8
854
2.96875
3
[ "MIT" ]
permissive
#include <cstdlib> // NULL, tv, fd_set, read_fd, FD_ZERO, FD_SET, select, FD_ISSET bool kbhit(void) { struct timeval tv; fd_set read_fd; /* Do not wait at all, not even a microsecond */ tv.tv_sec = 0; tv.tv_usec = 0; /* Must be done first to initialize read_fd */ FD_ZERO(&read_fd); /* Makes select() ask if input is ready: 0 is the file descriptor for stdin */ FD_SET(0,&read_fd); /* The first parameter is the number of the largest file descriptor to check + 1. */ if(select(1, &read_fd,NULL, /*No writes*/NULL, /*No exceptions*/&tv) == -1) return(false); /* An error occured */ /* read_fd now holds a bit map of files that are * readable. We test the entry for the standard * input (file 0). */ if(FD_ISSET(0,&read_fd)) /* Character pending on stdin */ return(true); /* no characters were pending */ return(false); }
true
10a8a14a587f9db2470c729cba98d3b7833509c8
C++
robintux/2daCharlaLimaEducacion
/Ejemplo03.cpp
UTF-8
1,268
3.765625
4
[]
no_license
/* Conteo de la cantidad de letras (las que estan en el alfabeto) getline para almacenar la cadena */ #include<iostream> #include<string> using namespace std; int main(){ string str; // Entrada (input) de la informacion cout<< "Ingresa una cadena " << endl; getline(cin, str); /* Funciones extras : strlen : funcion que cuente la cantidad de elementos en una variable string isalpha : dado un caracter, esta funcion debe verificar que dicho caracter pertenece al alfabeto */ /* cout << "La cadena ingresada es : " << str << endl; cout << "Numero de elementos : " << str.length() << endl; str : variable de tipo string (objeto) length : es un metodo de este objeto (string) str.lenght : aplicar el metodo lenght al objeto str */ int num = 0 ;// num sirve para contar los elementos ( de mi variable str ) que pertenecen al alfacebo // Operaciones : for(int i = 0 ; i <= str.length() ; i++){ if(isalpha(str[i])){ num = num +1 ; } } // mostramos la salida cout << "La cadena ingresada es : " << str << endl; cout << "La cantidad de elementos del alfabeto es : " << num << endl; system("pause"); return 1; }
true
45c001166a85a0895b427b200a1a48643a4759b6
C++
marcosrodriigues/ufop
/conteudo/Introdução à Programação (Prática)/Exercicios/P6_1424341_Marcos_Rodrigues/exe4.cpp
UTF-8
714
3.453125
3
[]
no_license
#include <string> #include <iostream> using namespace std; string str_replace (string phrase, char first_character, char second_character); int main() { string phrase; char ch_01, ch_02; getline(cin, phrase); while (!phrase.empty()) { cin >> ch_01 >> ch_02; cin.ignore(); size_t position = phrase.find(ch_01); while (position != string::npos) { phrase = str_replace(phrase, ch_01, ch_02); position = phrase.find(ch_01); } cout << phrase << endl; getline(cin, phrase); } return 0; } string str_replace (string phrase, char first_character, char second_character) { return phrase.replace(phrase.find(first_character), 1, 1, second_character); }
true
35139ea7cb63f19cd9d5d6df669fd0c6c246e47e
C++
windynips/ESP8266-Ajax-Jquery
/PWM_ESP8266_Ajax_Demo/PWM_ESP8266_Ajax_Demo.ino
UTF-8
3,623
2.5625
3
[ "MIT" ]
permissive
/* * ESP8266 SPIFFS HTML Web Page with JPEG, PNG Image * https://circuits4you.com */ #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #include <FS.h> //Include File System Headers const char* htmlfile = "/index.html"; //WiFi Connection configuration const char *ssid = "Genesis"; const char *password = "BonnieBoss"; #define LED 2 ESP8266WebServer server(80); void handlePWM(){ String PWM = server.arg("pwm"); int p = 1024 - (PWM.toInt())*10; Serial.println(p); analogWrite(LED,p); server.send(200, "text/plane",""); } void handleRoot(){ server.sendHeader("Location", "/index.html",true); //Redirect to our html web page server.send(302, "text/plane",""); } void handleWebRequests(){ if(loadFromSpiffs(server.uri())) return; String message = "File Not Detected\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET)?"GET":"POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i=0; i<server.args(); i++){ message += " NAME:"+server.argName(i) + "\n VALUE:" + server.arg(i) + "\n"; } server.send(404, "text/plain", message); Serial.println(message); } void setup() { delay(1000); Serial.begin(115200); Serial.println(); pinMode(LED,OUTPUT); //Initialize File System SPIFFS.begin(); Serial.println("File System Initialized"); //Connect to wifi Network WiFi.begin(ssid, password); //Connect to your WiFi router Serial.println(""); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } //If connection successful show IP address in serial monitor Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); //IP address assigned to your ESP if(WiFi.status() == WL_CONNECTED) //If WiFi connected to hot spot then start mDNS { if (MDNS.begin("kwcube")) { //Start mDNS with name esp8266 Serial.println("MDNS started"); } } //Initialize Webserver server.on("/",handleRoot); server.on("/setLED",handlePWM); //Reads ADC function is called from out index.html server.onNotFound(handleWebRequests); //Set setver all paths are not found so we can handle as per URI server.begin(); } void loop() { server.handleClient(); } bool loadFromSpiffs(String path){ String dataType = "text/plain"; if(path.endsWith("/")) path += "index.htm"; if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf(".")); else if(path.endsWith(".html")) dataType = "text/html"; else if(path.endsWith(".htm")) dataType = "text/html"; else if(path.endsWith(".css")) dataType = "text/css"; else if(path.endsWith(".js")) dataType = "application/javascript"; else if(path.endsWith(".png")) dataType = "image/png"; else if(path.endsWith(".gif")) dataType = "image/gif"; else if(path.endsWith(".jpg")) dataType = "image/jpeg"; else if(path.endsWith(".ico")) dataType = "image/x-icon"; else if(path.endsWith(".xml")) dataType = "text/xml"; else if(path.endsWith(".pdf")) dataType = "application/pdf"; else if(path.endsWith(".zip")) dataType = "application/zip"; File dataFile = SPIFFS.open(path.c_str(), "r"); if (server.hasArg("download")) dataType = "application/octet-stream"; if (server.streamFile(dataFile, dataType) != dataFile.size()) { } dataFile.close(); return true; }
true
5c3b430b5e92738f8cb958139f60b3fbb16cff0c
C++
jayakrishna-g/Interviewbit
/AmazingSubarrays.cpp
UTF-8
701
3.5
4
[]
no_license
/*Question: Amazing Subarrays You are given a string S, and you have to find all the amazing substrings of S. Amazing Substring is one that starts with a vowel (a, e, i, o, u, A, E, I, O, U). Input Only argument given is string S. Output Return a single integer X mod 10003, here X is number of Amazing Substrings in given string. */ bool foo(char ch) { return ch=='A'||ch=='a'||ch=='E'||ch=='e'||ch=='I'||ch=='i'||ch=='o'||ch=='O'||ch=='u'||ch=='U'; } int Solution::solve(string A) { int ans=0; int mod=10003; int count=0; for(int i=0;i<A.size();i++) { if(foo(A[i])) { ans=(ans%mod+(A.size()-i)%mod)%mod; } } return ans%mod; }
true
a3077e1e3b3ec224f386bfd40696743b9ac8e391
C++
Zeta611/baekjoon-solutions
/7576-토마토.cpp
UTF-8
1,558
2.875
3
[]
no_license
#include <cstring> #include <iostream> #include <queue> #include <utility> constexpr int WIDTH{1'000}; constexpr std::pair<int, int> DIRS[]{{0, 1}, {-1, 0}, {0, -1}, {1, 0}}; int box[WIDTH][WIDTH]; int dist[WIDTH][WIDTH]; std::queue<std::pair<int, int>> q; int bfs(int m, int n) { while (!q.empty()) { const auto [y, x]{q.front()}; q.pop(); for (const auto [dy, dx] : DIRS) { const int ny{y + dy}; const int nx{x + dx}; if (nx < 0 || nx >= m || ny < 0 || ny >= n || box[ny][nx] || dist[ny][nx] > 0) { continue; } if (dist[ny][nx] == -1) { dist[ny][nx] = dist[y][x] + 1; } else { dist[ny][nx] = std::min(dist[ny][nx], dist[y][x] + 1); } q.emplace(ny, nx); } } int max{0}; for (int i{0}; i < n; ++i) { for (int j{0}; j < m; ++j) { if (box[i][j] == 0 && dist[i][j] == -1) { return -1; } max = std::max(max, dist[i][j]); } } return max; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); memset(dist, -1, sizeof dist); int m, n; std::cin >> m >> n; for (int i{0}; i < n; ++i) { for (int j{0}; j < m; ++j) { std::cin >> box[i][j]; if (box[i][j] == 1) { q.emplace(i, j); dist[i][j] = 0; } } } std::cout << bfs(m, n) << '\n'; }
true
af9db79de80a6df37452178a58b6f6ef819fa250
C++
knnth3/GameEngine
/SEF Model Converter/SceneElementConverter/SceneElementConverter/include/SEStream.h
UTF-8
10,764
2.859375
3
[]
no_license
#pragma once //Scene Element File #include "Animation.h" #include <fstream> #include <queue> #define FILE_EXTENSION ".sef" #define CURRENT_SEF_VERSION 4 #define MAX_SEF_HEADER_STR 16 namespace SEF { struct SEF_HEADER { uint16_t Version; char Name[MAX_SEF_HEADER_STR]; char Author[MAX_SEF_HEADER_STR]; bool bHasSkeleton; bool bHasMesh; uint16_t AnimCount; }; struct SEF_MESH_HEADER { uint32_t Indices; uint32_t Vertices; uint16_t NameLength; }; struct SEF_SKELETON_HEADER { uint32_t Joints; uint16_t NameLength; }; struct SEF_ANIMATION_HEADER { uint32_t Joints; uint32_t Timestamps; }; inline SEF_HEADER CreateHeader(uint16_t version = -1, uint16_t animCount = 0, bool hasMesh = false, bool hasSkeleton = false, const char* name = nullptr, const char* author = nullptr); inline std::string GetExtension(const std::string& filepath); inline int GetStrSize(const char* str); class SEStream { public: void AddAnimation(const Animation& anim); int WriteFile(const std::string& filename, const MeshData* mesh, const Skeleton* skeleton); int ReadFile(const std::string& filename, MeshData* mesh, Skeleton* skeleton, std::vector<Animation>* animation)const; private: std::queue<Animation> m_animations; }; inline SEF_HEADER CreateHeader(uint16_t version, uint16_t animCount, bool hasMesh, bool hasSkeleton, const char* name, const char* author) { SEF_HEADER header; header.Version = version; header.bHasMesh = hasMesh; header.bHasSkeleton = hasSkeleton; header.AnimCount = animCount; int nameSize = GetStrSize(name); int range = (nameSize > MAX_SEF_HEADER_STR - 1) ? MAX_SEF_HEADER_STR - 1 : nameSize; for (int x = 0; x < MAX_SEF_HEADER_STR; x++) { if (x >= range) header.Name[x] = '\0'; else header.Name[x] = name[x]; } int authorSize = GetStrSize(author); range = (authorSize > MAX_SEF_HEADER_STR - 1) ? MAX_SEF_HEADER_STR - 1 : authorSize; for (int x = 0; x < MAX_SEF_HEADER_STR; x++) { if (x >= range) header.Author[x] = '\0'; else header.Author[x] = author[x]; } return header; } inline std::string GetExtension(const std::string& filepath) { auto result = filepath.find_last_of('.'); if (result == std::string::npos) return std::string(); return filepath.substr(result, std::string::npos); } inline int GetStrSize(const char * str) { int size = 0; if (str) { char current = str[size]; while (current != '\0') { size++; current = str[size]; } } return size; } void SEStream::AddAnimation(const Animation & anim) { m_animations.push(anim); } inline int SEStream::WriteFile(const std::string & filename, const MeshData * mesh, const Skeleton * skeleton) { int bytesWritten = 0; std::ofstream myFile(filename.c_str(), std::ios::out | std::ios::binary); SEF_HEADER header = CreateHeader(CURRENT_SEF_VERSION, (uint16_t)m_animations.size(), mesh, skeleton, "Model", "Online Author"); try { myFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); //Write file header first myFile.write((char*)&header, sizeof(header)); bytesWritten += sizeof(header); if (mesh) { //Header SEF_MESH_HEADER meshInfo = {}; meshInfo.Indices = (uint32_t)mesh->Indices.size(); meshInfo.Vertices = (uint32_t)mesh->Vertices.size(); meshInfo.NameLength = (uint16_t)mesh->Name.length(); myFile.write((char*)&meshInfo, sizeof(meshInfo)); bytesWritten += sizeof(meshInfo); //Name std::string name = mesh->Name; myFile.write(name.data(), sizeof(char) * meshInfo.NameLength); bytesWritten += sizeof(char) * meshInfo.NameLength; //Vertices for (const auto& vert : mesh->Vertices) { myFile.write((char*)&vert, sizeof(vert)); bytesWritten += sizeof(vert); } //Indices for (const auto& index : mesh->Indices) { myFile.write((char*)&index, sizeof(index)); bytesWritten += sizeof(index); } } if (skeleton) { //Header SEF_SKELETON_HEADER skeletonInfo = {}; skeletonInfo.NameLength = (uint16_t)skeleton->SkinName.size(); skeletonInfo.Joints = (uint32_t)skeleton->Joints.size(); myFile.write((char*)&skeletonInfo, sizeof(skeletonInfo)); bytesWritten += sizeof(skeletonInfo); //Name std::string name = skeleton->SkinName; myFile.write(name.data(), sizeof(char) * skeletonInfo.NameLength); bytesWritten += sizeof(char) * skeletonInfo.NameLength; //Joints for (const auto& joint : skeleton->Joints) { //Joint name length uint16_t nameLength = (uint16_t)joint.Name.size(); myFile.write((char*)&nameLength, sizeof(nameLength)); bytesWritten += sizeof(nameLength); //Joint name std::string jname = joint.Name; myFile.write(jname.data(), sizeof(char) * nameLength); bytesWritten += sizeof(char) * nameLength; //Joint matrix myFile.write((char*)&joint.GlobalBindPoseInverse, sizeof(joint.GlobalBindPoseInverse)); bytesWritten += sizeof(joint.GlobalBindPoseInverse); //Joint children count uint32_t ccount = (uint32_t)joint.Children.size(); myFile.write((char*)&ccount, sizeof(ccount)); bytesWritten += sizeof(ccount); //Joint children for (const auto& child : joint.Children) { myFile.write((char*)&child, sizeof(child)); bytesWritten += sizeof(child); } } } while(!m_animations.empty()) { auto animation = m_animations.front(); m_animations.pop(); SEF_ANIMATION_HEADER animInfo; animInfo.Timestamps = (uint32_t)animation.TimeStampCount(); animInfo.Joints = (uint32_t)animation.JointCount(); myFile.write((char*)&animInfo, sizeof(animInfo)); bytesWritten += sizeof(animInfo); for (const auto& name : animation.JointNames()) { uint16_t size = (uint16_t)name.size(); myFile.write((char*)&size, sizeof(size)); bytesWritten += sizeof(size); myFile.write(name.data(), sizeof(char) * size); bytesWritten += sizeof(char) * size; } for (int index = 0; index < (int)animInfo.Joints; index++) { auto* cluster = animation.At(index); for (int keyIndex = 0; keyIndex < (int)animInfo.Timestamps; keyIndex++) { const auto& key = cluster->at(keyIndex); myFile.write((char*)&key, sizeof(key)); bytesWritten += sizeof(key); } } } myFile.close(); } catch (const std::exception e) { std::string error = "Unable to write to file " + filename + "\nReason: " + e.what(); throw std::runtime_error(error); } return bytesWritten; } inline int SEStream::ReadFile(const std::string & filename, MeshData * mesh, Skeleton * skeleton, std::vector<Animation>* animation) const { int bytesRead = 0; std::string ext = GetExtension(filename); if (ext.compare(FILE_EXTENSION)) { return false; } std::ifstream myFile(filename.c_str(), std::ios::in | std::ios::binary); SEF_HEADER header; try { myFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); //Read file header first myFile.read((char*)&header, sizeof(header)); bytesRead += sizeof(header); if (header.bHasMesh && mesh) { //Header SEF_MESH_HEADER meshInfo = {}; myFile.read((char*)&meshInfo, sizeof(meshInfo)); bytesRead += sizeof(meshInfo); //Name mesh->Name.resize(meshInfo.NameLength); myFile.read(&mesh->Name[0], sizeof(char) * meshInfo.NameLength); bytesRead += sizeof(char) * meshInfo.NameLength; //Vertices for (uint32_t x = 0; x < meshInfo.Vertices; x++) { VertexData vert = {}; myFile.read((char*)&vert, sizeof(vert)); bytesRead += sizeof(vert); mesh->Vertices.push_back(vert); } //Index for (uint32_t x = 0; x < meshInfo.Indices; x++) { unsigned int index; myFile.read((char*)&index, sizeof(index)); bytesRead += sizeof(index); mesh->Indices.push_back(index); } } if (header.bHasSkeleton && skeleton) { //Header SEF_SKELETON_HEADER skeletonInfo = {}; skeletonInfo.NameLength = (uint16_t)skeleton->SkinName.size(); skeletonInfo.Joints = (uint32_t)skeleton->Joints.size(); myFile.read((char*)&skeletonInfo, sizeof(skeletonInfo)); bytesRead += sizeof(skeletonInfo); //Name skeleton->SkinName.resize(skeletonInfo.NameLength); myFile.read(&skeleton->SkinName[0], sizeof(char) * skeletonInfo.NameLength); bytesRead += sizeof(char) * skeletonInfo.NameLength; //Joints for (uint32_t x = 0; x < skeletonInfo.Joints; x++) { Joint joint = {}; //Joint name length uint16_t nameLength = 0; myFile.read((char*)&nameLength, sizeof(nameLength)); bytesRead += sizeof(nameLength); //Joint name joint.Name.resize(nameLength); myFile.read(&joint.Name[0], sizeof(char) * nameLength); bytesRead += sizeof(char) * nameLength; //Joint matrix myFile.read((char*)&joint.GlobalBindPoseInverse, sizeof(joint.GlobalBindPoseInverse)); bytesRead += sizeof(joint.GlobalBindPoseInverse); //Joint children count uint32_t ccount = 0; myFile.read((char*)&ccount, sizeof(ccount)); bytesRead += sizeof(ccount); //Joint children joint.Children.resize(ccount); for (auto& child : joint.Children) { myFile.read((char*)&child, sizeof(child)); bytesRead += sizeof(child); } skeleton->Joints.push_back(joint); } } while (header.AnimCount && animation) { header.AnimCount--; animation->emplace_back(); auto& anim = animation->back(); SEF_ANIMATION_HEADER animInfo; myFile.read((char*)&animInfo, sizeof(animInfo)); bytesRead += sizeof(animInfo); anim.SetTimestampCount(animInfo.Timestamps); std::vector<std::string> jointNames; jointNames.resize(animInfo.Joints); for (auto& name : jointNames) { uint16_t size = 0; myFile.read((char*)&size, sizeof(size)); bytesRead += sizeof(size); name.resize(size); myFile.read(&name[0], sizeof(char) * size); bytesRead += sizeof(char) * size; } for (int index = 0; index < (int)animInfo.Joints; index++) { std::vector<AnimationKey> cluster; cluster.resize(animInfo.Timestamps); for (int keyIndex = 0; keyIndex < (int)animInfo.Timestamps; keyIndex++) { const auto& key = cluster.at(keyIndex); myFile.read((char*)&key, sizeof(key)); bytesRead += sizeof(key); } anim.AddCluster(jointNames[index], cluster); } } myFile.close(); } catch (const std::exception e) { std::string error = "Unable to read file " + filename + "\nReason: " + e.what(); throw std::runtime_error(error); } return bytesRead; } }
true
59f86a3a1594a3fd6be22ee54770e14b494ad853
C++
jventura1738/COSC220
/AllLabs/Lab11/ex6_15.cpp
UTF-8
1,541
3.25
3
[]
no_license
#include "time24.h" #include <iostream> #include <list> #include <iterator> #include <cstdlib> #include <ctime> int main () { srand(time(NULL)); int num; std::cout << "enter an integer: "; std::cin >> num; std::list<int> intList; std::list<int>::iterator intIter; for (int i = 0; i < 10; i++) { int random_number = (std::rand() % 100); intList.push_front(random_number); } std::cout << "Numbers bigger than entry...\n"; for (intIter = intList.begin(); intIter != intList.end(); intIter++) { if (*intIter > num) std::cout << *intIter << " "; } std::cout << "\n"; std::list<Time24> tList, amList, pmList; std::list<Time24>::iterator iter; tList.push_back(Time24(8, 30)); tList.push_back(Time24(13, 45)); tList.push_back(Time24(7, 25)); tList.push_back(Time24(11, 15)); tList.push_back(Time24(18, 20)); tList.push_back(Time24(21, 50)); std::cout << "\ntList\n"; for (iter = tList.begin(); iter != tList.end(); iter++) { std::cout << *iter << " "; if (iter->getHour() < 12) amList.push_back(*iter); else pmList.push_back(*iter); } std::cout << "\namList:\n"; for (iter = amList.begin(); iter != amList.end(); iter++) { std::cout << *iter << " "; } std::cout << "\npmList:\n"; for (iter = pmList.begin(); iter != pmList.end(); iter++) { std::cout << *iter << " "; } std::cout << "\n"; return 0; }
true
31663a5e13f3a5f6f740c91c1b5bcc3952605c80
C++
WangYuming1/systemC_fft_miniprojet
/fft_caba/FFT8.cpp
UTF-8
7,144
2.734375
3
[]
no_license
#include "FFT8.h" #include<stdio.h> #include"fft.h" using std::cout; using std::endl; #define L 23 sc_int<27> W[4][2]={ 67108863, 0, 47453133, -47453133, 0, -67108864, -47453133, -47453133}; // #define W {\ // {67108863, 0}, \ // {47453133, -47453133}, \ // {0, -67108864}, \ // {-47453133, -47453133}\ // } void FFT8::COMPORTEMENT(){ sc_int < L > data_in[16]; //to store the data received from the source sc_int < L+4 > data_out[16]; //to send out the data calculated complex_s in[8]; //store the data received with the format complex_s complex_t out[8]; //store the result by fft to send out data_valid_out=false; //initialize the signal valid and req data_req_out=false; while(1){ data_valid_out=false; //in each tranfer of 8 samples, initialize the signal valid to 0 and req to 1. data_req_out=true; int i=0; while(i<15){ if(data_valid_in && data_req_out){ //when the src has data valid and fft is available for the data, store the data in the data_in data_in[i]=in_real.read(); i++; data_in[i]=in_imag.read(); i++; } wait(); } data_req_out=false; //after reading a set of 8 samples, set req to 0 for(i=0;i<8;i++){ // store the data to complex format in[i].real=data_in[i*2]; in[i].imag=data_in[i*2+1]; } fft(in,out); for(i=0;i<8;i++){ //store the complex result to send out data_out[i*2]=out[i].real; data_out[i*2+1]=out[i].imag; } i=0; while(i<15){ if(!data_valid_out&&(data_req_in)){ //when data is valid and the sink can read data, write the data to the port out_real.write(data_out[i]); i++; out_imag.write(data_out[i]); data_valid_out=true; //set valid to true after writing 2 data to the port i++; } wait(); data_valid_out=false; //set the valid to 0 after the next pos_clk } } } template <unsigned int N> void papillon( sc_int<N> Wr, sc_int<N> Wi, //ar+brWr-biWi, if the ar is 23 bits, brWr is 23 bits, ar+brWr can reach 24 bits, if the sc_int<N> ar, sc_int<N> ai, // biWi is regarded as a plus, the result can reach 25 bits. sc_int<N> br, sc_int<N> bi, sc_int<N+2> &new_ar, sc_int<N+2> &new_ai, sc_int<N+2> &new_br, sc_int<N+2> &new_bi) // le papillon sur 2 echantillons complexes peut ramener l'energie // des 2 echantillons sur une seule composante (reelle ou imaginaire) // d'un seul echantillon en sortie, // donc si entree sur N bits, sortie sur N+2 // Mais si l'on cascade S etages, si entree sur N bits, // sortie sur N+S+1 bits (2^S entrees combinent au pire toute leur // energie sur une unique composante d'un echantillon de sortie, // donc il faudra recadrer! { sc_int<2*N> mult_brr; sc_int<2*N> mult_bri; sc_int<2*N> mult_bir; sc_int<2*N> mult_bii; sc_int<N> mult_brr_trunc; sc_int<N> mult_bri_trunc; sc_int<N> mult_bir_trunc; sc_int<N> mult_bii_trunc; mult_brr = (br * Wr); mult_bri = (br * Wi); mult_bir = (bi * Wr); mult_bii = (bi * Wi); mult_brr_trunc = mult_brr.range(2*N-2,N-1)+mult_brr[N-2]; // car les W sont codes sur 1 bit de signe et N-1 bits pour la partie fractionnaire // et ont rajoute le bit de precision pour l'arrondi mult_bri_trunc = mult_bri.range(2*N-2,N-1)+mult_bri[N-2]; mult_bir_trunc = mult_bir.range(2*N-2,N-1)+mult_bir[N-2]; mult_bii_trunc = mult_bii.range(2*N-2,N-1)+mult_bii[N-2]; new_ar = (ar + ((mult_brr_trunc) - (mult_bii_trunc))); new_ai = (ai + ((mult_bri_trunc) + (mult_bir_trunc))); new_br = (ar - ((mult_brr_trunc) - (mult_bii_trunc))); new_bi = (ai - ((mult_bri_trunc) + (mult_bir_trunc))); } void fft(complex_s in[8], complex_t out[8]) { sc_int<L+2> stage1_real[8]; sc_int<L+2> stage1_imag[8]; sc_int<L+4> stage2_real[8]; sc_int<L+4> stage2_imag[8]; sc_int<L+6> stage3_real[8]; sc_int<L+6> stage3_imag[8]; // First stage papillon<23> ( W[0][0].range(26,4), W[0][1].range(26,4), in[0].real, in[0].imag, in[4].real, in[4].imag, stage1_real[0], stage1_imag[0], stage1_real[1], stage1_imag[1]); papillon<23> (W[0][0].range(26,4), W[0][1].range(26,4), in[2].real, in[2].imag, in[6].real, in[6].imag, stage1_real[2], stage1_imag[2], stage1_real[3], stage1_imag[3]); papillon<23> (W[0][0].range(26,4), W[0][1].range(26,4), in[1].real, in[1].imag, in[5].real, in[5].imag, stage1_real[4], stage1_imag[4], stage1_real[5], stage1_imag[5]); papillon<23> (W[0][0].range(26,4), W[0][1].range(26,4), in[3].real, in[3].imag, in[7].real, in[7].imag, stage1_real[6], stage1_imag[6], stage1_real[7], stage1_imag[7]); // Second stage papillon<25> (W[0][0].range(26,2), W[0][1].range(26,2), stage1_real[0], stage1_imag[0], stage1_real[2], stage1_imag[2], stage2_real[0], stage2_imag[0], stage2_real[2], stage2_imag[2]); papillon<25> (W[2][0].range(26,2), W[2][1].range(26,2), stage1_real[1], stage1_imag[1], stage1_real[3], stage1_imag[3], stage2_real[1], stage2_imag[1], stage2_real[3], stage2_imag[3]); papillon<25> (W[0][0].range(26,2), W[0][1].range(26,2), stage1_real[4], stage1_imag[4], stage1_real[6], stage1_imag[6], stage2_real[4], stage2_imag[4], stage2_real[6], stage2_imag[6]); papillon<25> (W[2][0].range(26,2), W[2][1].range(26,2), stage1_real[5], stage1_imag[5], stage1_real[7], stage1_imag[7], stage2_real[5], stage2_imag[5], stage2_real[7], stage2_imag[7]); // Etape 3 papillon<27> (W[0][0], W[0][1], stage2_real[0], stage2_imag[0], stage2_real[4], stage2_imag[4], stage3_real[0], stage3_imag[0], stage3_real[4], stage3_imag[4]); papillon<27> (W[1][0], W[1][1], stage2_real[1], stage2_imag[1], stage2_real[5], stage2_imag[5], stage3_real[1], stage3_imag[1], stage3_real[5], stage3_imag[5]); papillon<27> (W[2][0], W[2][1], stage2_real[2], stage2_imag[2], stage2_real[6], stage2_imag[6], stage3_real[2], stage3_imag[2], stage3_real[6], stage3_imag[6]); papillon<27> (W[3][0], W[3][1], stage2_real[3], stage2_imag[3], stage2_real[7], stage2_imag[7], stage3_real[3], stage3_imag[3], stage3_real[7], stage3_imag[7]); for (int i=0; i<8; i++){ out[i].real=stage3_real[i].range(26,0); out[i].imag=stage3_imag[i].range(26,0); } }
true
ab520a729c49cdd295acef3e9c72ba94ec0bef11
C++
saifullah3396/team-nust-robocup-v2
/src/TNRSModules/UserCommModule/include/UserCommRequest.h
UTF-8
1,880
2.65625
3
[ "BSD-3-Clause" ]
permissive
/** * @file UserCommModule/include/UserCommRequest.h * * This file defines the class UserCommRequest * * @author <A href="mailto:saifullah3396@gmail.com">Saifullah</A> * @date 04 Feb 2017 */ #pragma once #include <opencv2/core/core.hpp> #include "TeamNUSTSPL/include/TNSPLModuleIds.h" #include "TNRSBase/include/ModuleRequest.h" #include "UserCommModule/include/CommMessage.h" #include "Utils/include/EnumUtils.h" using namespace cv; /** * Types of request valid for UserCommModule * * @enum UserCommRequestIds */ enum class UserCommRequestIds { SEND_MSG_REQUEST, SEND_IMAGE_REQUEST }; /** * @class UserCommRequest * @brief A module request that can be handled by UserCommModule */ class UserCommRequest : public ModuleRequest { public: /** * Constructor * * @param id: Id of the control request */ UserCommRequest(const UserCommRequestIds& id) : ModuleRequest(toUType(TNSPLModules::userComm), toUType(id)) { } }; typedef boost::shared_ptr<UserCommRequest> UserCommRequestPtr; /** * @class SendMsgRequest * @brief A request that holds a message to be sent over the network */ struct SendMsgRequest : public UserCommRequest { /** * Constructor * * @param cMsg: The comm message associated with this request */ SendMsgRequest(const CommMessage& cMsg) : UserCommRequest(UserCommRequestIds::SEND_MSG_REQUEST), cMsg(cMsg) { } CommMessage cMsg; }; /** * @class SendImageRequest * @brief A request that holds an image to be sent over the network */ struct SendImageRequest : public UserCommRequest { /** * Constructor * * @param cMsg: The comm message associated with this request */ SendImageRequest(const cv::Mat& image) : UserCommRequest(UserCommRequestIds::SEND_IMAGE_REQUEST), image(image) { } cv::Mat image; }; typedef boost::shared_ptr<SendMsgRequest> SendMsgRequestPtr;
true
6c35a0c02aff99fcc7ba7a1f49a772d318048415
C++
REPOSC/compiler
/yacc.h
GB18030
22,992
2.703125
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <set> #include <map> #include <stack> #include "token.h" #include "grammar.h" //#define Yacc_DEBUG #define Abstract_TREE #ifndef YACC__32 #define YACC__32 typedef std::vector<token> receivers; typedef std::set<token> first_set; typedef struct { char action; int index; } movement; typedef std::map<token, std::vector<movement> > table_item; typedef struct { int grammar_index; int pointer; token forward_word; } project; bool operator <(const project & p1, const project & p2) { if (p1.grammar_index > p2.grammar_index) return true; else if (p1.grammar_index < p2.grammar_index) return false; if (p1.pointer > p2.pointer) return true; else if (p1.pointer < p2.pointer) return false; if (p1.forward_word < p2.forward_word) return true; return false; } bool operator == (const project & p1, const project & p2) { return p1.grammar_index == p2.grammar_index && p1.pointer == p2.pointer && p1.forward_word == p2.forward_word; } typedef struct { std::vector<project> projects; std::map<token, int> convert_to; /* Accept a token, and convert to the statement index */ } statement; bool operator == (statement & p1, statement & p2) { std::sort(p1.projects.begin(), p1.projects.end()); std::sort(p2.projects.begin(), p2.projects.end()); return p1.projects == p2.projects; } template <class T> std::ostream & operator << (std::ostream & os, const std::vector<T> & arr) { os << "["; if (arr.size()) { for (int i = 0; i < arr.size() - 1; ++i) { os << arr[i] << ","; } os << arr[arr.size() - 1]; } os << "]"; return os; } struct newNode { token onetoken; std::vector<newNode *> children; }; struct newWord { token onetoken; std::vector<newNode *> children; }; void write_table_item_to_file(const table_item & ti, std::ofstream & ofs) { ofs << ti.size() << std::endl; for (auto it : ti) { write_token_to_file(it.first, ofs); ofs << it.second.size() << " "; for (auto mvt : it.second) { ofs << mvt.action << mvt.index << " "; } ofs << std::endl; } } table_item read_table_item_from_file(std::ifstream & ifs) { table_item ti; int token_size; ifs >> token_size; for (int i = 0; i < token_size; ++i) { token tk = read_token_from_file(ifs); int vec_size; ifs >> vec_size; std::vector<movement> mvmts; for (int j = 0; j < vec_size; ++j) { ifs.get(); movement mvmt; mvmt.action = ifs.get(); ifs >> mvmt.index; mvmts.push_back(mvmt); } ti[tk] = mvmts; } return ti; } class Yacc { private: token m_start_word; std::set<token> m_terminators, m_unterminators; std::vector<grammar> m_grammars; std::map<token, receivers> m_signal_table; std::map<token, first_set> m_firsts; std::vector<statement> m_statements; std::vector<table_item> m_movement_table; void yacc_output_failure(std::string error, grammar gra) { std::ofstream outfile; outfile.open("error.txt"); // ٴļдû outfile << error << " "; outfile << gra.before_word << "->" << gra.after_words << std::endl; // رմ򿪵ļ outfile.close(); } grammar agm_grammars() { /* Augment to current m_grammars */ grammar agm_g; agm_g.after_words.push_back(m_start_word); agm_g.before_word = m_start_word = BEGIN_TOKEN; agm_g.move = same; agm_g.strange_token = EOFLINE_TOKEN; return agm_g; } void get_first(token & current_str, first_set & current_first) { /* Reach first set of current_str, and insert them into current_first */ if (current_str.type == UNTERMINATOR) { for (auto first_word : m_firsts[current_str]) { current_first.insert(first_word); } } else current_first.insert(current_str); } void complete_stmt(statement & stmt) { /* Complete a statement by deploy projects recursively */ for (int i = 0; i < stmt.projects.size(); ++i) { if (stmt.projects[i].pointer < m_grammars[stmt.projects[i].grammar_index].after_words.size()) { token point_token = m_grammars[stmt.projects[i].grammar_index].after_words[stmt.projects[i].pointer]; if (point_token.type == UNTERMINATOR) { /* źǷս */ /* ӵźַһַʼһֱʽַ */ std::vector<token> after_pointer; for (int j = stmt.projects[i].pointer + 1; j < m_grammars[stmt.projects[i].grammar_index].after_words.size(); ++j) after_pointer.push_back(m_grammars[stmt.projects[i].grammar_index].after_words[j]); after_pointer.push_back(stmt.projects[i].forward_word); first_set current_first; for (int i = 0; i < after_pointer.size(); ++i) { get_first(after_pointer[i], current_first); auto find_pos = find(current_first.begin(), current_first.end(), SPC_TOKEN); /* пհַ */ if (find_pos == current_first.end()) { break; } else { current_first.erase(find_pos); } }; /* еԸ÷սΪʼIJʽ */ for (int i = 0; i < m_grammars.size(); ++i) { if (m_grammars[i].before_word == point_token) { for (auto current_forward : current_first) { project current_project; current_project.grammar_index = i; current_project.pointer = 0; current_project.forward_word = current_forward; if (find(stmt.projects.begin(), stmt.projects.end(), current_project) == stmt.projects.end()) { stmt.projects.push_back(current_project); } } } } } } } fflush(stmt); } void rr_get_first(const token & unterminator_token) { /* Get first set of unterminator_token, and put it into array m_firsts */ bool changed = false; for (auto current_grammar : m_grammars) { if (current_grammar.before_word == unterminator_token) { token first_word = current_grammar.after_words[0]; if (first_word.type != UNTERMINATOR) { if (std::find(m_firsts[unterminator_token].begin(), m_firsts[unterminator_token].end(), first_word) == m_firsts[unterminator_token].end()) { changed = true; m_firsts[unterminator_token].insert(first_word); } } else { for (auto word : m_firsts[first_word]) { if (std::find(m_firsts[unterminator_token].begin(), m_firsts[unterminator_token].end(), word) == m_firsts[unterminator_token].end()) { changed = true; m_firsts[unterminator_token].insert(word); } } } } } if (changed) { for (auto signal_receiver : m_signal_table[unterminator_token]) { rr_get_first(signal_receiver); } } } void fflush(statement & current_statement) { for (project & proj : current_statement.projects) { while (proj.pointer < m_grammars[proj.grammar_index].after_words.size() && m_grammars[proj.grammar_index].after_words[proj.pointer] == SPC_TOKEN) { ++proj.pointer; } } } project get_next_proj(const project & proj) { /* Get project of current project with pointer moved forward */ project new_proj = proj; if (proj.pointer < m_grammars[proj.grammar_index].after_words.size()) { ++new_proj.pointer; } return new_proj; } void stmt_walk(int current_index) { /* Looking for new states that can be reached in one step under the current state, then deploy the new states */ typedef struct { /* A group with the same next recognize_str */ std::set<project> projects_set; token recognize_str; } same_set; std::vector<same_set> sets; for (auto current_project : m_statements[current_index].projects) { /* For each project in the statement */ bool recognized = false; if (current_project.pointer < m_grammars[current_project.grammar_index].after_words.size()) { for (same_set & current_set : sets) { /* See if there is a set with the same recognize_str, if so, add to it */ if (current_set.recognize_str == m_grammars[current_project.grammar_index].after_words[current_project.pointer]) { current_set.projects_set.insert(current_project); recognized = true; break; } } if (!recognized) { /* If not, create a new set */ same_set new_set; new_set.recognize_str = m_grammars[current_project.grammar_index].after_words[current_project.pointer]; new_set.projects_set.insert(current_project); sets.push_back(new_set); } } else { /* A new same_set containing useless projects(cannot go next step) */ for (same_set & current_set : sets) { if (current_set.recognize_str == EOFLINE_TOKEN) { current_set.projects_set.insert(current_project); recognized = true; break; } } if (!recognized) { same_set new_set; new_set.recognize_str = EOFLINE_TOKEN; new_set.projects_set.insert(current_project); sets.push_back(new_set); } } } for (same_set & current_set : sets) { /* For each same_set, create a statement */ if (current_set.recognize_str != EOFLINE_TOKEN) { statement new_stmt; for (auto current_project : current_set.projects_set) { project next_project = get_next_proj(current_project); new_stmt.projects.push_back(next_project); } complete_stmt(new_stmt); int equal_pos = -1; for (int i = 0; i < m_statements.size(); ++i) { /* See if the new statement already exists in the m_statements */ if (new_stmt == m_statements[i]) { equal_pos = i; break; } } if (equal_pos >= 0) m_statements[current_index].convert_to[current_set.recognize_str] = equal_pos; else { /* If not, push_back the new statement */ m_statements[current_index].convert_to[current_set.recognize_str] = m_statements.size(); m_statements.push_back(new_stmt); } } } } void build_table() { /* Build state transition table by current m_statements, and store it in m_movement_table */ for (auto statement : m_statements) { table_item current_item; for (auto cvrt_item : statement.convert_to) { token step_token = cvrt_item.first; if (step_token.type == UNTERMINATOR) { current_item[step_token].push_back({ ' ', cvrt_item.second }); } else { current_item[step_token].push_back({ 's', cvrt_item.second }); } } for (auto current_proj : statement.projects) { if (current_proj.pointer == m_grammars[current_proj.grammar_index].after_words.size()) { current_item[current_proj.forward_word].push_back({ 'r', current_proj.grammar_index }); } } m_movement_table.push_back(current_item); } } #ifdef Yacc_DEBUG void proj_prt(const project & proj) { /* Print a project */ std::cout << m_grammars[proj.grammar_index].before_word << "->"; for (int i = 0; i < m_grammars[proj.grammar_index].after_words.size(); ++i) { if (i == proj.pointer) { std::cout << "."; } std::cout << m_grammars[proj.grammar_index].after_words[i] << " "; } if (m_grammars[proj.grammar_index].after_words.size() == proj.pointer) std::cout << "."; std::cout << "[" << proj.forward_word << "]" << std::endl; } void print_status(const std::vector<int> & status_stk, const std::vector<token> & word_stk, const std::vector<token> & word_seq, int pointer, movement now_movement) { std::cout << "Status: " << status_stk << " "; std::cout << std::endl; std::cout << "Word_stk: " << word_stk << " "; std::cout << std::endl; std::vector<token> part_word_seq; for (int i = pointer; i < word_seq.size(); ++i) part_word_seq.push_back(word_seq[i]); std::cout << "InputStream: " << part_word_seq << " "; std::cout << now_movement.action << now_movement.index << std::endl; std::cout << std::endl; } #endif public: Yacc(const std::vector<grammar> & grammars, const token & start_word) { /* Initialize terminators, un_terminators and start word */ m_start_word = start_word; grammar begin_grammar = agm_grammars(); m_grammars.push_back(begin_grammar); for (const grammar & current_grammar : grammars) { m_grammars.push_back(current_grammar); } /* Build m_terminators & m_unterminators (Optional) */ for (auto current_grammar : m_grammars) { m_unterminators.insert(current_grammar.before_word); for (auto word : current_grammar.after_words) { if (word.type != UNTERMINATOR) { m_terminators.insert(word); } } } } void build_LR1() { /* Build LR1 table by grammars */ for (auto current_grammar : m_grammars) { m_signal_table[current_grammar.before_word] = receivers(); } for (auto current_grammar : m_grammars) { if (current_grammar.after_words[0].type == UNTERMINATOR) { m_signal_table[current_grammar.after_words[0]].push_back(current_grammar.before_word); } } for (auto current_grammar : m_grammars) { rr_get_first(current_grammar.before_word); } /* Build the first project */ project begin_project; begin_project.grammar_index = 0; begin_project.pointer = 0; begin_project.forward_word = EOFLINE_TOKEN; statement begin_stmt; begin_stmt.projects.push_back(begin_project); complete_stmt(begin_stmt); m_statements.push_back(begin_stmt); /* Build All statements */ for (int i = 0; i < m_statements.size(); ++i) { stmt_walk(i); } build_table(); } void write_table(std::ofstream & ofs) { /* Write built table to file */ ofs << m_movement_table.size() << std::endl; for (auto current_tb_item : m_movement_table) { write_table_item_to_file(current_tb_item, ofs); } } void read_table(std::ifstream & ifs) { /* Read built table from file */ m_movement_table.clear(); int all_size; ifs >> all_size; for (int i = 0; i < all_size; ++i) { table_item ti = read_table_item_from_file(ifs); m_movement_table.push_back(ti); } } void clear_LR1() { /* Delete built LR1 table and interim status information */ m_signal_table.clear(); m_statements.clear(); m_grammars.clear(); m_firsts.clear(); m_movement_table.clear(); } bool check() { /* Check if the grammar's not ambigious */ for (int i = 0; i < m_movement_table.size(); ++i) { for (auto j : m_movement_table[i]) { if (j.second.size() > 1) return false; } } return true; } #ifdef Abstract_TREE bool judge_null(newNode *root, int i) { for (int j = i + 1; j < root->children.size(); j++) { if (root->children[j]->onetoken.type != NULL_TOKEN) { return false; } } return true; } void print_tree(newNode * root, std::string s, bool last) { if (!root) { return; } else { if (root->onetoken.type != NULL_TOKEN) std::cout << s + " |---" << root->onetoken << std::endl; int len = root->children.size(); for (int i = 0; i < len; i++) { if (last) { if (judge_null(root, i)) { print_tree(root->children[i], s + " ", true); } else { print_tree(root->children[i], s + " ", false); } } else { if (judge_null(root, i)) { print_tree(root->children[i], s + " | ", true); } else { print_tree(root->children[i], s + " | ", false); } } } return; } } #endif //Abstract_TREE newNode* analyze1(const std::vector<token> & readin_seq) { /* Output the process of LR1 derivation */ //check(); std::vector<int> status_stk; std::vector<token> cout_word_stk; std::vector<newWord> word_stk;//ջ std::string now_str; std::vector<newNode *> nodes;//﷨ڵ int now_status; newNode * root = new newNode; int pointer = 0; status_stk.push_back(0); bool finished = false; while (!finished) { token reserved_str = readin_seq[pointer]; token now_str; if (reserved_str.type == VARNAME) now_str.type = ABSTRACT_VAR; else if (reserved_str.type == INT_NUM || reserved_str.type == REAL_NUM) now_str.type = ABSTRACT_NUM; else now_str = reserved_str; int now_status = status_stk.back(); if (m_movement_table[now_status].find(now_str) != m_movement_table[now_status].end()) { movement now_movement = m_movement_table[now_status][now_str][0]; #ifdef Yacc_DEBUG print_status(status_stk, cout_word_stk, readin_seq, pointer, now_movement); #endif switch (now_movement.action) { case 's': status_stk.push_back(now_movement.index); token onetoken; onetoken.type = reserved_str.type; onetoken.value = reserved_str.value; word_stk.push_back(newWord{ onetoken, }); cout_word_stk.push_back(reserved_str); ++pointer; break; case 'r': const grammar & current_grammar = m_grammars[now_movement.index]; int check_index = current_grammar.after_words.size(); std::vector<newWord> new_child; for (; !status_stk.empty() && !word_stk.empty() && check_index > 0; --check_index) { token expected_string = current_grammar.after_words[check_index - 1]; if (expected_string != SPC_TOKEN) { new_child.push_back(word_stk.back()); status_stk.pop_back(); word_stk.pop_back(); cout_word_stk.pop_back(); } } if (check_index) { yacc_output_failure("ERROR4:", current_grammar); std::cerr << std::endl; std::cerr << "ERROR occur!" << std::endl; exit(-1); /*std::cout << "444444 error" << std::endl; throw 3;*/ } //reverse(new_child.begin(), new_child.end()); int child_len = new_child.size(); now_str = current_grammar.before_word; now_status = status_stk.back(); token temp_token; temp_token.type = now_str.type; temp_token.value = now_str.value; newWord left_word; left_word.onetoken = temp_token; newNode * temp_node = new newNode; switch (current_grammar.move) { case makeleaf: temp_node->onetoken = new_child.back().onetoken; nodes.push_back(temp_node); left_word.children.push_back(temp_node); break; case makenode: temp_node->onetoken = current_grammar.strange_token; for (int n = 0; n < child_len; n++) { if (new_child.back().onetoken.type == UNTERMINATOR) { for (auto i : new_child.back().children) { temp_node->children.push_back(i); } } new_child.pop_back(); } nodes.push_back(temp_node); left_word.children.push_back(temp_node); break; case same: for (int n = 0; n < child_len; n++) { if (new_child.back().onetoken.type == UNTERMINATOR) { for (auto i : new_child.back().children) { left_word.children.push_back(i); } } new_child.pop_back(); } break; case null: temp_node->onetoken = token{ NULL_TOKEN, }; nodes.push_back(temp_node); left_word.children.push_back(temp_node); break; } if (now_str == m_start_word && status_stk.size() == 1 && status_stk.back() == 0) { root = left_word.children[0]; finished = true; } else { word_stk.push_back(left_word); cout_word_stk.push_back(left_word.onetoken); if (m_movement_table[now_status].find(now_str) != m_movement_table[now_status].end()) { now_movement = m_movement_table[now_status][now_str][0]; if (now_movement.action != ' ') { yacc_output_failure("ERROR2:", current_grammar); std::cerr << std::endl; std::cerr << "ERROR occur!" << std::endl; exit(-1); /*std::cout << "222222 error" << std::endl; throw 3;*/ } else status_stk.push_back(now_movement.index); } else { yacc_output_failure("ERROR3:", current_grammar); std::cerr << std::endl; std::cerr << "ERROR occur!" << std::endl; exit(-1); /*std::cout << "333333 error" << std::endl; throw 3;*/ } } break; } } else { yacc_output_failure("ERROR1:", m_grammars[0]); std::cerr << std::endl; std::cerr << "ERROR occur!" << std::endl; exit(-1); /*std::cout << "111111 error" << std::endl; std::cout << now_status << " " << now_str; throw 1;*/ } } #ifdef Abstract_TREE std::cout << std::endl; std::cout << "Abstract Tree:" << std::endl; print_tree(root, "", true); #endif // Abstract_TREE return root; } #ifdef Yacc_DEBUG void print() { /* Output some useful information */ std::cout << "signals:" << std::endl; for (auto i : m_signal_table) { std::cout << i.first << ":" << std::endl; for (auto j : i.second) { std::cout << j << std::endl; } } std::cout << "grammar:" << std::endl; for (auto i : m_grammars) { std::cout << i.before_word << "->"; for (auto j : i.after_words) { std::cout << j << " "; } std::cout << std::endl; } std::cout << "first:" << std::endl; for (auto i : m_firsts) { std::cout << i.first << ":" << std::endl; for (auto j : i.second) { std::cout << j << std::endl; } std::cout << std::endl; } std::cout << "statement:" << m_statements.size() << std::endl; for (int i = 0; i < m_statements.size(); ++i) { std::cout << "I" << i << std::endl; for (auto current_proj : m_statements[i].projects) { proj_prt(current_proj); } } std::cout << "Table:" << std::endl; std::cout << " ,"; std::vector<token> all_word; for (auto word : m_terminators) { std::cout << word << ","; } for (auto word : m_unterminators) { std::cout << word << ","; } std::cout << std::endl; for (int i = 0; i < m_statements.size(); ++i) { std::cout << "I" << i << ","; for (auto word : m_terminators) { if (m_movement_table[i].find(word) != m_movement_table[i].end()) { for (int j = 0; j < m_movement_table[i][word].size(); ++j) { std::cout << m_movement_table[i][word][j].action << m_movement_table[i][word][j].index; if (j != m_movement_table[i][word].size() - 1) std::cout << "/"; } std::cout << ","; } else { std::cout << " ,"; } } for (auto word : m_unterminators) { if (m_movement_table[i].find(word) != m_movement_table[i].end()) { for (int j = 0; j < m_movement_table[i][word].size(); ++j) { std::cout << m_movement_table[i][word][j].action << m_movement_table[i][word][j].index; } std::cout << ","; } else { std::cout << " ,"; } } std::cout << std::endl; } } #endif }; #endif // YACC__32
true
9016228ad5212d63ce243f22f9a5e7495dc89617
C++
alex-lab11/3
/jornal.cpp
UTF-8
748
3.25
3
[]
no_license
#include "jornal.h" #include <iostream> using namespace std; jornal::jornal(string const nameIN, int const yearIN, int const numberIN):Izdanie(nameIN, yearIN){ number = numberIN; } jornal::jornal():Izdanie() { number = 0; } jornal::jornal(const jornal &life):Izdanie(life){ number = life.number; } void jornal::SetNumber(int const numberIN) { number = numberIN; } int jornal::GetNumber() const{ return number; } void jornal::print() const{ cout << "name: " << name << endl; cout << "year: " << year << endl; cout << "number: " << number << endl; } jornal &jornal::operator = (const jornal &life) { Izdanie::operator =(life); this->number = life.number; return *this; }
true
9fd420735a38fa9d8032f6d2adcbd00faba6c58d
C++
POSTED26/POSTED
/code/win32_posted.cpp
UTF-8
7,749
2.796875
3
[]
no_license
/* ========================================================= Author: Jacob Tillett Date: 8/5/2018 This is the entry point. So far this file has an entry point, it creates a window that processes a few messages with a callback function. This file also creates a buffer to fill and them paint to screen. =========================================================*/ #include <windows.h> #include <stdint.h> // Definitions. #define internal static #define local_persist static #define global_var static global_var bool isRunning; // TODO: this is a global for now. global_var BITMAPINFO BitmapInfo; global_var void *BitmapMemory; global_var int BitmapWidth; global_var int BitmapHeight; global_var int BytesPerPixel = 4; internal void RenderGradient(int XOffset, int YOffset) { int Width = BitmapWidth; int Height = BitmapHeight; int Pitch = Width * BytesPerPixel; uint8_t *Row = (uint8_t *)BitmapMemory; for(int Y = 0; Y < BitmapHeight; ++Y) { uint32_t *Pixel = (uint32_t *)Row; for(int X = 0; X < BitmapWidth; ++X) { // Pixels in memory BB GG RR XX uint8_t Blue = (X + XOffset); uint8_t Green = (Y + YOffset); uint8_t Red = ((uint8_t)(X + XOffset) / 2) + ((uint8_t)(Y + -YOffset) / 2); *Pixel++ = ((Red << 16) | (Green << 8) | Blue); } Row += Pitch; } } internal void Win32ResizeDIBSection(int Width, int Height) { //TODO: maybe free first , free after, then free first if fails if(BitmapMemory) { VirtualFree(BitmapMemory, 0, MEM_RELEASE); } BitmapWidth = Width; BitmapHeight = Height; // Filling out BitmapInfo header with important information BitmapInfo.bmiHeader.biSize = sizeof(BitmapInfo.bmiHeader); BitmapInfo.bmiHeader.biWidth = BitmapWidth; BitmapInfo.bmiHeader.biHeight = -BitmapHeight; BitmapInfo.bmiHeader.biPlanes = 1; BitmapInfo.bmiHeader.biBitCount = 32; BitmapInfo.bmiHeader.biCompression = BI_RGB; //int BytesPerPixel = 4; int BitmapMemorySize = (Width * Height) * BytesPerPixel; BitmapMemory = VirtualAlloc(0, BitmapMemorySize, MEM_COMMIT, PAGE_READWRITE); //TODO: Possibly clear to black. It kind of seem like it does already but who knows. } // Called in the paint message in the callback, used to take what is in our buffer and // put it on the screen. internal void Win32UpdateWindow(HDC DeviceContext, RECT *ClientRect, int X, int Y, int Width, int Height) { int WindowWidth = ClientRect->right - ClientRect->left; int WindowHeight = ClientRect->bottom - ClientRect->top; StretchDIBits(DeviceContext, // X, Y, Width, Height, // Destination // X, Y, Width, Height, // Source 0, 0, BitmapWidth, BitmapHeight, 0, 0, WindowWidth, WindowHeight, BitmapMemory, &BitmapInfo, DIB_RGB_COLORS, SRCCOPY); } // Processes the messages sent to the window LRESULT CALLBACK Win32MainWindowCallback(HWND Window, UINT Message, WPARAM WParam, LPARAM LParam) { LRESULT Result = 0; switch(Message) { case WM_SIZE: { RECT ClientRect; GetClientRect(Window, &ClientRect); int Width = ClientRect.right - ClientRect.left; int Height = ClientRect.bottom - ClientRect.top; Win32ResizeDIBSection(Width, Height); //OutputDebugStringA("WM_SIZE\n"); } break; case WM_DESTROY: { isRunning = false; // TODO: handle with and error recreate window?? //OutputDebugStringA("WM_DESTROY\n"); } break; case WM_CLOSE: { isRunning = false; // TODO: handle with a message to user?? //OutputDebugStringA("WM_CLOSE\n"); } break; case WM_ACTIVATEAPP: { OutputDebugStringA("WM_ACTIVATEAPP\n"); } break; case WM_PAINT: { PAINTSTRUCT Paint; HDC DeviceContext = BeginPaint(Window, &Paint); int X = Paint.rcPaint.left; int Y = Paint.rcPaint.top; int Width = Paint.rcPaint.right - Paint.rcPaint.left; int Height = Paint.rcPaint.bottom - Paint.rcPaint.top; local_persist DWORD Operation = WHITENESS; RECT ClientRect; GetClientRect(Window, &ClientRect); Win32UpdateWindow(DeviceContext, &ClientRect, X, Y, Width, Height); EndPaint(Window, &Paint); } break; default: { // OutputDebugStringA("default\n"); Result = DefWindowProc(Window, Message, WParam, LParam); } break; } return(Result); } // Entry point into the program int CALLBACK WinMain(HINSTANCE Instance, HINSTANCE PrevInstance, LPSTR CommandLine, int ShowCode) { /* Creating a window class struct and filling out the fields that we need to use. The empty curly braces set all the values to 0 */ WNDCLASS WindowClass = {}; // Telling the window to redraw on horizontal and vertical resizing WindowClass.style = CS_OWNDC|CS_HREDRAW|CS_VREDRAW; // Passing the window callback WindowClass.lpfnWndProc = Win32MainWindowCallback; // Passing our instance WindowClass.hInstance = Instance; // WindowClass.hIcon; // we do not need a icon yet // Gicing the window class a name WindowClass.lpszClassName = "PostedWindowClass"; if(RegisterClassA(&WindowClass)) { HWND Window = CreateWindowExA(0, WindowClass.lpszClassName, "POSTED", WS_OVERLAPPEDWINDOW|WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, Instance, 0); if(Window) { isRunning = true; int XOffset = 0; int YOffset = 0; while(isRunning) //loop forever till we get a positve message from reuslt { MSG Message; while(PeekMessageA(&Message, 0, 0, 0, PM_REMOVE)) { if(Message.message == WM_QUIT) { isRunning = false; } TranslateMessage(&Message); DispatchMessageA(&Message); } RenderGradient(XOffset, YOffset); HDC DeviceContext = GetDC(Window); RECT ClientRect; GetClientRect(Window, &ClientRect); int WindowWidth = ClientRect.right - ClientRect.left; int WindowHeight = ClientRect.bottom - ClientRect.top; Win32UpdateWindow(DeviceContext, &ClientRect, 0, 0, WindowWidth, WindowHeight); ReleaseDC(Window, DeviceContext); ++XOffset; --YOffset; } } else { // TODO: LOGGING } } else { // TODO: Log } return(0); }
true
b4495079c3710d0d5946d6394c9af500c763c1da
C++
AnkitaTarole/Bootcamp1
/Bootcamp9.cpp
UTF-8
235
2.890625
3
[]
no_license
#include<iostream> #include<string.h> using namespace std; int main() { string s; cin>>s; int t=1; for(int i=0;i<s.length();i++) { if(isupper(s[i])) { t++; } } cout<<t<<endl; return 0; }
true
80a8fc13205865f6398ced6281c775a8f26fc415
C++
mattshrago/Track-and-Control
/tacs_project/SleepManager.cpp
UTF-8
781
2.78125
3
[]
no_license
#include <set> #include <iostream> #include <windows.h> #include <ctime> using namespace std; const int resolutionX = GetSystemMetrics(SM_CXSCREEN); //Screen Resulution x const int resolutionY = GetSystemMetrics(SM_CYSCREEN); //Screen Resulution y time_t away_time; time_t last_visible_time; //Will determine if the user has left the field of view and will put the computer to sleep. void putToSleep()//POINT pos) { SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) 2); } void sleep(int x, int y, int delay) { if(x == 0 && y == 0) { time(&away_time); int counting_time = away_time - last_visible_time; if(counting_time == delay) { putToSleep(); SetCursorPos(resolutionX/2, resolutionY/2); } } else { time(&last_visible_time); } }
true
bd5d95a599456e8e7e4751e71cce24a9e9a1486c
C++
arielstolerman/tau-cs-spring-2010-advanced-topics-in-programming-ariel-shay
/advanced_programming_ex05/advanced_programming_ex05_b/MobilePhoneOwner.cpp
UTF-8
796
2.546875
3
[]
no_license
/****************************************************************************** * Exercise 05 - Advanced Programming 2010b, TAU. * Authors: Ariel Stolerman (-) and Shay Davidson (-). * MobilePhoneOwner: Source file *****************************************************************************/ #pragma once #include "stdafx.h" #include "MobilePhoneOwner.h" using namespace std; void MobilePhoneOwner::update(Subject* theChangeSubject, SubjectMessages message){ if (theChangeSubject == company){ if (message == TC_PRICE_CHANGE){ cout << name << " has recieved a notification for price change." << endl; } else if (message == TC_UPGRADE){ cout << name << " has recieved a notification for an upgrade." << endl; } else { cout << name << ": unknown notification recieved!" << endl; } } }
true
32555eea2c1340e021f98d2f235dd1c1ca53aeb6
C++
LEECHHE/acmicpc
/solved/6600.cpp
UTF-8
695
3.078125
3
[]
no_license
#include <cstdio> #include <cmath> using namespace std; const double PI = 3.141592653589793; double dist(double x1, double y1, double x2, double y2 ){ return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } double square(double a, double b, double c){ double s = (a+b+c)/2; return sqrt(s*(s-a)*(s-b)*(s-c)); } int main(){ double x1,y1,x2,y2,x3,y3; while (scanf("%lf",&x1) != -1) { scanf("%lf%lf%lf%lf%lf",&y1,&x2,&y2,&x3,&y3); double a = dist(x1, y1, x2, y2); double b = dist(x2, y2, x3, y3); double c = dist(x3, y3, x1, y1); double S = square(a, b, c); double r = (a*b*c)/(4*S); printf("%.2lf\n",2*r*PI); } return 0; }
true
39b846dec0c80e7a5bf2425a2e9deddb0aca4641
C++
kupihleba/TEP
/src/Crypton.cpp
UTF-8
3,089
2.75
3
[]
no_license
#include "Crypton.h" #include <iostream> #include <iomanip> #include <aes.h> #include <filters.h> #include <modes.h> #include <osrng.h> #include <hex.h> #include <files.h> #include "Exception.h" #undef DEBUG /** * @warning Using vectors for sensitive data is considered bad practice */ std::vector<std::byte> Crypton::encrypt(const vector<std::byte> &plain, const vector<std::byte> &key) { auto encrypted = apply(plain, key, CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption()); #if DEBUG CryptoPP::HexEncoder encoder(new CryptoPP::FileSink(std::cout)); encoder.Put(reinterpret_cast<CryptoPP::byte *>(encrypted.data()), encrypted.size()); encoder.MessageEnd(); std::cout << std::endl; #endif return encrypted; } std::vector<std::byte> Crypton::decrypt(const vector<std::byte> &encrypted, const vector<std::byte> &key) { auto decrypted = apply(encrypted, key, CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption()); #if DEBUG CryptoPP::HexEncoder encoder(new CryptoPP::FileSink(std::cout)); encoder.Put(reinterpret_cast<CryptoPP::byte *>(decrypted.data()), decrypted.size()); encoder.MessageEnd(); std::cout << std::endl; #endif return decrypted; } template<class Op> std::vector<std::byte> Crypton::apply(const vector<std::byte> &data, const vector<std::byte> &key, Op operation) { return apply(data.data(), data.size(), key.data(), key.size(), operation); } template<class Op> std::vector<std::byte> Crypton::apply(const std::byte *data, size_t data_len, const std::byte *key, size_t key_len, Op operation) { // CryptoPP::AutoSeededRandomPool random; CryptoPP::SecByteBlock iv(CryptoPP::AES::BLOCKSIZE); // random.GenerateBlock(iv, iv.size()); memset(iv.data(), 0x00, iv.size()); // iv is included in protocol if (key_len != CryptoPP::AES::DEFAULT_KEYLENGTH) { throw Exception("Wrong key length!"); } operation.SetKeyWithIV(reinterpret_cast<const CryptoPP::byte *>(key), key_len, reinterpret_cast<const CryptoPP::byte *>(iv.data()), iv.size()); std::vector<CryptoPP::byte> product(data_len + CryptoPP::AES::BLOCKSIZE); CryptoPP::ArraySink sink(product.data(), product.size()); CryptoPP::ArraySource(reinterpret_cast<const CryptoPP::byte *>(data), data_len, true, new CryptoPP::StreamTransformationFilter(operation, new CryptoPP::Redirector(sink))); product.resize(sink.TotalPutLength()); return std::vector(reinterpret_cast<std::byte *>(&product.begin()[0]), reinterpret_cast<std::byte *>(&product.end()[0])); } std::vector<std::byte> Crypton::encrypt(const std::byte *plain, size_t plain_len, const std::byte *key, size_t key_len) { return apply(plain, plain_len, key, key_len, CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption()); } std::vector<std::byte> Crypton::decrypt(const std::byte *plain, size_t plain_len, const std::byte *key, size_t key_len) { return apply(plain, plain_len, key, key_len, CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption()); }
true
4e7c3ccb078d8183b3923707485ba468b23f9c38
C++
SurajBichkunde39/DS_Algo_Practice
/006_union_intersection.cpp
UTF-8
2,659
3.40625
3
[]
no_license
// Find the union and intersection of two sorted arrays #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> interseciton(vector<int> ar1, vector<int> ar2); vector<int> union_(vector<int> ar1, vector<int> ar2); }; vector<int> Solution::interseciton(vector<int> ar1, vector<int> ar2) { vector<int> result; int len1 = ar1.size(); int len2 = ar2.size(); int fp = 0; int sp = 0; int res_len = 0; while (fp < len1 && sp < len2) { if (ar1[fp] == ar2[sp]) { result.push_back(ar1[fp]); int val = ar1[fp]; while (fp < len1 && ar1[fp] == val) fp++; while (sp < len2 && ar2[sp] == val) sp++; } while (fp < len1 && sp < len2 && ar1[fp] < ar2[sp]) fp++; while (fp < len1 && sp < len2 && ar2[sp] < ar1[fp]) sp++; } return result; } vector<int> Solution::union_(vector<int> ar1, vector<int> ar2) { vector<int> result; int len1 = ar1.size(); int len2 = ar2.size(); int fp = 0; int sp = 0; while (fp < len1 && sp < len2) { if (ar1[fp] == ar2[sp]) { result.push_back(ar1[fp]); int val = ar1[fp]; while (ar1[fp] == val) fp++; while (ar2[sp] == val) sp++; } while (fp < len1 && sp < len2 && ar1[fp] < ar2[sp]) { result.push_back(ar1[fp]); fp++; } while (fp < len1 && sp < len2 && ar2[sp] < ar1[fp]) { result.push_back(ar2[sp]); fp++; } } while (fp < len1) { result.push_back(ar1[fp]); fp++; } while (sp < len2) { result.push_back(ar2[sp]); sp++; } return result; } int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<int> ar1, ar2; int temp; for (int i = 0; i < n; i++) { cin >> temp; ar1.push_back(temp); } for (int i = 0; i < m; i++) { cin >> temp; ar2.push_back(temp); } Solution a; vector<int> u = a.union_(ar1, ar2); vector<int> i = a.interseciton(ar1, ar2); cout << "union of the sorted arrays" << endl; for (int x : u) cout << x << " "; cout << endl << "intersection of the sorted arrays" << endl; for (int x : i) cout << x << " "; } getchar(); getchar(); return 0; }
true
d7bf8c5b516bc33b256c895bded8e8301b8b3a29
C++
debroejm/SwarmEngine
/engine/api/Render.h
UTF-8
59,001
2.9375
3
[ "Apache-2.0" ]
permissive
#pragma once // *************** // STD Libraries // *************** #include <map> #include <set> #include <unordered_map> #include <vector> // *************** // Common Header // *************** #define SWARM_REQUEST_BOOST_MUTEX #include "common_header.h" #undef SWARM_REQUEST_BOOST_MUTEX // *********** // API Begin // *********** namespace Swarm { namespace Texture { namespace Type { //! Class-Enum used to represent GLenum Texture Target types. /*! * The TargetType class is used as a manual enumeration to represent different Texture Target types in * OpenGL. The TargetType constructor is private, and it cannot be created other than by the static Types * defined in the TargetType namespace. This Class-Enum is essentially used to represent an OpenGL type * w/o using 3rd party libraries/loaders (e.g. GLEW), but will return a GLenum if \ref SWARM_INCLUDE_GLEW * is defined. */ class TargetType { private: TargetType(SWMenum type) : _type(type) {}; SWMenum _type; public: //! TEX_1D maps to the GLenum GL_TEXTURE_1D static TargetType TEX_1D; //! TEX_1D_ARRAY maps to the GLenum GL_TEXTURE_1D_ARRAY static TargetType TEX_1D_ARRAY; //! TEX_2D maps to the GLenum GL_TEXTURE_2D static TargetType TEX_2D; //! TEX_2D_ARRAY maps to the GLenum GL_TEXTURE_2D_ARRAY static TargetType TEX_2D_ARRAY; //! TEX_3D maps to the GLenum GL_TEXTURE_3D static TargetType TEX_3D; //! TEX_RECTANGLE maps to the GLenum GL_TEXTURE_RECTANGLE static TargetType TEX_RECTANGLE; //! TEX_CUBE_MAP maps to the GLenum GL_TEXTURE_CUBE_MAP static TargetType TEX_CUBE_MAP; //! TEX_CUBE_MAP_ARRAY maps to the GLenum GL_TEXTURE_CUBE_MAP_ARRAY static TargetType TEX_CUBE_MAP_ARRAY; //! TEX_BUFFER maps to the GLenum GL_TEXTURE_BUFFER static TargetType TEX_BUFFER; //! TEX_2D_MULTISAMPLE maps to the GLenum GL_TEXTURE_2D_MULTISAMPLE static TargetType TEX_2D_MULTISAMPLE; //! TEX_2D_MULTISAMPLE_ARRAY maps to the GLenum GL_TEXTURE_2D_MULTISAMPLE_ARRAY static TargetType TEX_2D_MULTISAMPLE_ARRAY; SWMenum type() const { return _type; } operator SWMenum() const { return _type; } bool operator==(const TargetType &rhs) const { return _type == rhs._type; } bool operator!=(const TargetType &rhs) const { return !this->operator==(rhs); } bool operator< (const TargetType &rhs) const { return _type < rhs._type; } bool operator> (const TargetType &rhs) const { return _type > rhs._type; } bool operator<=(const TargetType &rhs) const { return !this->operator>(rhs); } bool operator>=(const TargetType &rhs) const { return !this->operator<(rhs); } }; //! Class used to represent a Texture Map type. /*! * The MapType class is used to represent different types of Texture Maps, as well as store data such as * what kind of OpenGL Texture Target to use and what Active Texture ID to use for the Texture Map. The Engine * provides definitions for these static MapTypes by default: * * \ref DIFFUSE * \ref SPECULAR * \ref NORMAL * \ref EMISSIVE */ class MapType { public: //! MapType main Constructor /*! * Creates a custom MapType using the given TargetType and Active Texture ID. * * \param active a \ref SWMuint describing the texture unit to bind to * \sa TargetType */ MapType(SWMuint active) : _active(active) {} //! MapType Copy Constructor /*! * Creates a copy of a MapType. * * \param other MapType to copy */ MapType(const MapType &other) { *this = other; } //! MapType assignment operator /*! * Assigns this MapType to be equivalent to another MapType. All equivalent MapType objects are * considered equivalent for identification (i.e. has the same hash). * * \param other MapType to copy * \return a reference to the current Maptype */ MapType &operator=(const MapType &other); // Comparison Operators bool operator==(const MapType &other) const { return hash() == other.hash(); } bool operator!=(const MapType &other) const { return hash() != other.hash(); } bool operator< (const MapType &other) const { return hash() < other.hash(); } bool operator<=(const MapType &other) const { return hash() <= other.hash(); } bool operator> (const MapType &other) const { return hash() > other.hash(); } bool operator>=(const MapType &other) const { return hash() >= other.hash(); } SWMuint active() const { return _active; } operator SWMuint() const { return _active; } //! Hashing function /*! * Returns a hash representation of a MapType. In general, the hash will be equivalent to a hash * of the MapType's Active Texture ID. * * \return size_t hash */ size_t hash() const { return hasher(_active); } protected: SWMuint _active; static std::hash<SWMuint> hasher; }; //! Standard Diffuse Texture Map that describes the RGBA look of a texture. static const MapType DIFFUSE (0); //! Specular Texture Map that describes the 'shininess' of a texture. static const MapType SPECULAR (1); //! Normal Texture Map that describes the physical direction parts of a texture face. static const MapType NORMAL (2); //! Emissive Texture Map that describes any light that is emitted from the texture. static const MapType EMISSIVE (3); } } } namespace std { // Hashing Structure so that MapTypes can be used in an std::unordered_map template<> struct hash<Swarm::Texture::Type::MapType> { size_t operator() (const Swarm::Texture::Type::MapType &var) const { return var.hash(); } }; } namespace Swarm { namespace Texture { void cleanup(); struct TexMap { TexMap() : _target(Type::TargetType::TEX_2D), _id(0) {} TexMap(const Type::TargetType target, SWMuint id) : _target(target), _id(id) {} const Type::TargetType target() const { return _target; } SWMuint id() const { return _id; } void bind(SWMuint active) const; bool operator==(const TexMap &rhs) const; bool operator!=(const TexMap &rhs) const { return !operator==(rhs); } bool operator< (const TexMap &rhs) const; bool operator<=(const TexMap &rhs) const { return operator<(rhs) || operator==(rhs); } bool operator> (const TexMap &rhs) const { return !operator<=(rhs); } bool operator>=(const TexMap &rhs) const { return !operator<(rhs); } protected: Type::TargetType _target; SWMuint _id; }; enum FileType { PNG }; TexMap loadTexFromFile(const std::string &path, FileType type); class Texture { public: void bind() const; void put(const Type::MapType &type, const TexMap &tex) { put(type.active(), tex); } void put(SWMuint active, const TexMap &tex); TexMap at(const Type::MapType &type) const { return at(type.active()); } TexMap at(SWMuint active) const; TexMap &operator[](const Type::MapType &type) { return operator[](type.active()); }; TexMap &operator[](SWMuint active); // Comparison Operators bool operator==(const Texture &rhs) const; bool operator!=(const Texture &rhs) const { return !operator==(rhs); } bool operator< (const Texture &rhs) const; bool operator<=(const Texture &rhs) const { return operator<(rhs) || operator==(rhs); } bool operator> (const Texture &rhs) const { return !operator<=(rhs); } bool operator>=(const Texture &rhs) const { return !operator<(rhs); } protected: std::map<SWMuint, TexMap> _data; }; } namespace Model { //! Enum representation of vector dimensionality /*! * This enumeration represents how many dimensions a vector can have, from 1 to 4. * Used in raw Model data loading. */ enum VecType { ONE = 1, TWO = 2, THREE = 3, FOUR = 4 }; //! Structure representing a single vector point. /*! * This structure contains float data for a single vector point, of dimension between 1 and 4. Internally, * it is represented as a union of types v1 through v4, each representing the dimensionality. Ideally, an * instance of this structure should be accessed as the same type it was created with - which can be accessed * with the identifier \ref type - or possibly with a lower dimensionality. Undefined behaviour can result * when attempting to access a higher dimensionality than a VecVar has been created with. */ struct VecVar { union Val { struct { float x; #if defined(SWARM_INCLUDE_GLM) float vec() { return x; } #endif } v1; struct { float x; float y; #if defined(SWARM_INCLUDE_GLM) glm::vec2 vec() { return glm::vec2(x, y); } #endif } v2; struct { float x; float y; float z; #if defined(SWARM_INCLUDE_GLM) glm::vec3 vec() { return glm::vec3(x, y, z); } #endif } v3; struct { float x; float y; float z; float w; #if defined(SWARM_INCLUDE_GLM) glm::vec4 vec() { return glm::vec4(x, y, z, w); } #endif } v4; explicit Val(float x) { v1.x = x; } explicit Val(float x, float y) { v2.x = x; v2.y = y; } explicit Val(float x, float y, float z) { v3.x = x; v3.y = y; v3.z = z; } explicit Val(float x, float y, float z, float w) { v4.x = x; v4.y = y; v4.z = z; v4.w = w; } } val; VecType type; explicit VecVar() : type(ONE), val(0.0f) {} explicit VecVar(float x) : type(ONE), val(x) {} explicit VecVar(float x, float y) : type(TWO), val(x, y) {} explicit VecVar(float x, float y, float z) : type(THREE), val(x, y, z) {} explicit VecVar(float x, float y, float z, float w) : type(FOUR), val(x, y, z, w) {} #if defined(SWARM_INCLUDE_GLM) explicit VecVar(glm::vec2 in) : type(TWO), val(in.x, in.y) {} explicit VecVar(glm::vec3 in) : type(THREE), val(in.x, in.y, in.z) {} explicit VecVar(glm::vec4 in) : type(FOUR), val(in.x, in.y, in.z, in.w) {} #endif }; //! An array-based implementation of the \ref VecVar data type. /*! * This class is a collection of VecVar data points in a single array. The size of the array is set at object * creation, and cannot be changed later. The object can, however, be set equal to another VecArray with a * different size. */ class VecArray { public: //! VecArray Default Constructor /*! * Creates a VecArray with a size of '0'; effectively empty. */ VecArray(); //! VecArray Main Constructor /*! * Creates a VecArray of a specific size and allocates space for its contents. * * \param type a \ref VecType of data to store * \param size the size of this VecArray */ VecArray(VecType type, size_t size); ~VecArray(); VecArray(const VecArray &other) { *this = other; } VecArray &operator=(const VecArray &other); const VecVar &at(size_t index) const; VecVar &operator[](size_t index); size_t size() { return _size; } VecType type() { return _type; } protected: VecVar* data = nullptr; size_t _size; VecType _type = ONE; }; namespace Type { //! Class used to represent a model Data Point type /*! * The DataType class is used to represent different types of Data Points, as well as store default values. * All DataType objects with the same Attribute ID are considered equivalent for the purposes of hashing * and identification. The Engine provides definitions for these static DataTypes by default: * * \ref VERTEX * \ref UV * \ref NORMAL * \ref COLOR * \ref TANGENT * \ref BITANGENT */ class DataType { public: //! DataType main Constructor /*! * \param type a \ref VecType to use * \param attribID a GLuint (or unsigned int, if not using GL headers) describing the attribute to bind to * \param defaultVal a \ref VecVar value to use as a default value for this DataType * \sa VecType, VecVar */ DataType(VecType type, SWMuint attribID, VecVar defaultVal); //! DataType Copy Constructor /*! * Creates a copy of a DataType. Sets the copy equivalent to the original. * * \param other DataType to copy */ DataType(const DataType &other); //! DataType assignment operator /*! * Assigns this DataType to be equivalent to another DataType. * * \param other DataType to copy * \return a reference to the current DataType */ DataType &operator=(const DataType &rhs); bool operator==(const DataType &rhs) const; bool operator!=(const DataType &rhs) const { return !operator==(rhs); } bool operator< (const DataType &rhs) const; bool operator<=(const DataType &rhs) const { return operator<(rhs) || operator==(rhs); } bool operator> (const DataType &rhs) const { return !operator<=(rhs); } bool operator>=(const DataType &rhs) const { return !operator<(rhs); } VecType type() const { return _type; } VecVar defaultValue() const { return _default_val; } SWMuint attribID() const { return _attrib_id; } void setAttribID(unsigned int attrib_id) { _attrib_id = attrib_id; } private: VecType _type; VecVar _default_val; SWMuint _attrib_id; }; //! Standard Vertex positional data. static const DataType VERTEX ( THREE, 1, VecVar(0.0f, 0.0f, 0.0f)); //! Texture coordinate data. static const DataType UV ( TWO, 2, VecVar(0.0f, 0.0f)); //! Physical directional data. static const DataType NORMAL ( THREE, 3, VecVar(0.0f, 1.0f, 0.0f)); //! Color description data. static const DataType COLOR ( FOUR, 4, VecVar(1.0f, 1.0f, 1.0f, 1.0f)); //! Tangential directional data. static const DataType TANGENT ( THREE, 5, VecVar(0.0f, 1.0f, 0.0f)); //! Bi-Tangential directional data. static const DataType BITANGENT ( THREE, 6, VecVar(0.0f, 1.0f, 0.0f)); } } } namespace std { template<> struct hash<Swarm::Model::Type::DataType> { size_t operator() (const Swarm::Model::Type::DataType &var) const { return hash<unsigned int>()((var.type()-1) + 4*var.attribID()); } }; } namespace Swarm { namespace Model { void cleanup(); class RawModelDataIndexed; //! Storage object for a raw collection of model data points /*! * A RawModelData object is a raw collection of data points that make up a model. The exact type and * count of data points is dynamic and depends on the RawModelData object instance, but in general * should contain at least a basic positional vertex format. */ class RawModelData { public: //! Default RawModelData Constructor /*! * Constructs an empty RawModelData collection. */ RawModelData() {} //! RawModelData Copy Constructor /*! * Constructs a new RawModelData collection and gives it equivalent data to another. * * \param other RawModelData collection to copy */ RawModelData(const RawModelData &other); //! RawModelData Assignment Operator /*! * Assigns this RawModelData collection as equivalent to another. * * \param other RawModelData collection to copy * \return a reference to this RawModelData collection */ RawModelData &operator=(const RawModelData &other); //! Set the raw point data associated with a \ref DataType /*! * Adds a selection of raw point data to this RawModelData collection under the \ref DataType given. * If the new data's size is different than the current collection's size, the current collection is * first resized to match. * * \param type a \ref DataType to store the given point data under * \param data a \ref VecArray of point data to store * \return a reference to this RawModelData collection, for chaining put() commands * \sa DataType, VecArray, resize() */ RawModelData &put(const Type::DataType &type, VecArray data); //! Set the raw point data associated with a \ref DataType /*! * Adds a selection of raw point data to this RawModelData collection under the \ref DataType given, after * compacting the given data into a \ref VecArray object. If the new data's size is different than the * current collection's size, the current collection is first resized to match. * * \param type a \ref DataType to store the given point data under * \param data an array of float values; the stride of said values is determined by the given \ref DataType * \param size the count of data points given * \return a reference to this RawModelData collection, for chaining put() commands * \sa DataType, VecArray, resize() */ RawModelData &put(const Type::DataType &type, float *data, size_t size); //! Does this RawModelData collection have data points associated with the given \ref DataType bool exists(const Type::DataType &type) const; //! Get the data points associated with the given \ref DataType /*! * Attempts to retrieve the data point group that is associated with the given \ref DataType. If this * RawModelData collection does not have a data point group associated with the given \ref DataType, * returns a new \ref VecArray of size '0'. * * \param type a \ref DataType associated with a data point group * \return the \ref VecArray associated with the given \ref DataType, or a new \ref VecArray of size '0' * \sa DataType, VecArray */ const VecArray &at(const Type::DataType &type) const; //! Get the data points associated with the given \ref DataType /*! * Attempts to retrieve the data point group that is associated with the given \ref DataType. If this * RawModelData collection does not have a data point group associated with the given \ref DataType, * constructs a new \ref VecArray of size '0' with the given \ref DataType and returns it. * * \param type a \ref DataType associated with a data point group * \return the \ref VecArray associated with the given \ref DataType * \sa DataType, VecArray */ VecArray &operator[](const Type::DataType &type); std::unordered_map<Type::DataType, VecArray>::iterator begin() { return data_map.begin(); } std::unordered_map<Type::DataType, VecArray>::const_iterator begin() const { return data_map.begin(); } std::unordered_map<Type::DataType, VecArray>::iterator end() { return data_map.end(); } std::unordered_map<Type::DataType, VecArray>::const_iterator end() const { return data_map.end(); } size_t size() const { return _size; }; //! Resize this RawModelData collection /*! * Resizes this RawModelData collection to the given size. If this RawModelData collection's current size * is larger than the given size, this collection's size is truncated to match, clipping off excess data. * If this RawModelData collection's current size is smaller than the given size, this collection's size * is extended to match, filling in the new space with default values determined by the stored data's * \ref DataType. If the size given matches this RawModelData collection's size, nothing happens. * * \param size a new size * \sa DataType */ void resize(size_t size); //! Indexes this RawModelData collection into a \ref RawModelDataIndexed collection /*! * Runs through the stored data point groups, and indexes them so that lateral copies of data points * (i.e. data points at index 3 and 8 have the same vertex, uv, AND normal, in a RawModelData collection * that contains data points for vertices, uvs, and normals) are removed, resulting in only one copy a * point for each set of duplicates. The \a epsilon_factor determines how exact the floating point * comparison is when determining equality. Floating point comparison happens on the scale of * \f$10^{-1*epsilonfactor}\f$, and defaults to an \a epsilon_factor of '5', or on the scale of 0.00001f. * * \param epsilon_factor The scale of floating point comparison * \return a \ref RawModelDataIndexed collection that stores the indexed data points * \sa RawModelDataIndexed */ virtual RawModelDataIndexed index(short epsilon_factor = 5); protected: std::unordered_map <Type::DataType, VecArray> data_map; size_t _size = 0; }; //! Computes Tangent data for a \ref RawModelData collection /*! * Computes the Tangent data for a given \ref RawModelData collection, using a given selection of \ref DataType * values. If the given \ref DataType values for vertex, uv, and normal types do not exist for the given * \ref RawModelData collection, or if the given \ref DataType values don't have the right dimensionality (see * parameters), this function does nothing and returns false. For a function that performs the * same functionality, but with default \ref DataType values, see \ref computeTangents(RawModelData&). * * \param raw_model_data \ref RawModelData collection to compute Tangents for * \param vertex_type \ref DataType that represents vertex positions; must have at least 3 dimensions * \param uv_type \ref DataType that represents texture coordinates; must have at least 2 dimensions * \param normal_type \ref DataType that represents normal directions; must have at least 3 dimensions * \param tangent_type \ref DataType that represents the produced tangents; must have exactly 3 dimensions * \param bitangent_type \ref DataType that represents the produced bitangents; must have exactly 3 dimensions * \return True upon a successful computation, false otherwise * \sa RawModelData, DataType, computeTangents(RawModelData&) */ bool computeTangents(RawModelData &raw_model_data, const Type::DataType &vertex_type, const Type::DataType &uv_type, const Type::DataType &normal_type, const Type::DataType &tangent_type, const Type::DataType &bitangent_type); //! Computes Tangent data for a \ref RawModelData collection /*! * Performs the same functionality as \ref computeTangents(RawModelData&, Type::DataType&, Type::DataType&, * Type::DataType&, Type::DataType&, Type::DataType&), but with the standard defaults for the available * \ref DataType values as follows: * * vertex_type: \ref Type::VERTEX * uv_type: \ref Type::UV * normal_type: \ref Type::NORMAL * tangent_type: \ref Type::TANGENT * bitangent_type: \ref Type::BITANGENT * * \param raw_model_data \ref RawModelData collection to compute Tangents for * \return True upon a successful computation, false otherwise * \sa RawModelData, DataType, computeTangents(RawModelData&, Type::DataType&, Type::DataType&, Type::DataType&, Type::DataType&, Type::DataType&) */ static inline bool computeTangents(RawModelData &raw_model_data) { return computeTangents(raw_model_data, Type::VERTEX, Type::UV, Type::NORMAL, Type::TANGENT, Type::BITANGENT); } //! Storage object for a raw collection of indexed model data points /*! * A RawModelDataIndexed object is a raw collection of data points that make up a model. Unlike a \ref RawModelData * object - which a RawModelDataIndexed object inherits from - the stored points are indexed such that * duplicate sets of lateral point data are removed (i.e. when index 3 and 8 have the same vertex, uv, AND * normal point data for an object that has data for vertices, uvs, and normals) and indices are added to the * data collection in replacement. */ class RawModelDataIndexed : public RawModelData { public: //! Default RawModelDataIndexed Constructor /*! * Constructs an empty RawModelDataIndexed collection. */ RawModelDataIndexed() {} ~RawModelDataIndexed(); //! RawModelDataIndexed Copy Constructor /*! * Constructs a new RawModelDataIndexed collection and gives it equivalent data to another. * * \param other RawModelDataIndexed collection to copy */ RawModelDataIndexed(const RawModelDataIndexed &other); //! RawModelDataIndexed Assignment Operator /*! * Assigns this RawModelDataIndexed collection as equivalent to another. * * \param other RawModelDataIndexed collection to copy * \return a reference to this RawModelDataIndexed collection */ RawModelDataIndexed &operator=(const RawModelDataIndexed &other); //! Set the index data /*! * Sets this RawModelDataIndexed collection's indices to the given indices. Index values must fall within * the collection's data size, otherwise undefined behaviour occurs. * * \param indices an array of short values representing indices * \param size the count of indices given * \return a reference to this RawModelDataIndexed collection, for chaining put() commands */ RawModelDataIndexed &putIndices(unsigned int *indices, size_t size); //! Get the indices for this RawModelDataIndexed /*! * Retrieves the collection of indices stored for this RawModelDataIndexed collection. * * \return the stored array of indices, or \a nullptr if no indices are stored */ unsigned int *indices() const { return _indices; }; size_t indexSize() const { return _index_size; }; //! Further indexes this RawModelDataIndexed collection into another RawModelDataIndexed collection /*! * Attempts to further refine and index this RawModelDataIndexed collection using the same method of * indexing as \ref RawModelData::index(). Unless data has been manually altered, usually results in no * change between the old and new RawModelDataIndexed collections. * * \param epsilon_factor The scale of floating point comparison * \return a new RawModelDataIndexed collection * \sa RawModelData::index() */ virtual RawModelDataIndexed index(short epsilon_factor = 5); protected: unsigned int *_indices = nullptr; size_t _index_size; }; //! Loads an OBJ file as a \ref RawModelData collection /*! * Attempts to open a given OBJ file and parse its contents. Contents are parsed into a \ref RawModelData * collection, with the vertices, uvs, and normals of the OBJ file stored under the given \ref DataType values. * For a function that does the same thing, but with default \ref DataType values, see \ref loadFromOBJ(const char*). * OBJ file loading currently supports the following features: * * - Parsing Vertices, UVs, Normals, and Faces * - UVs may be omitted from Face declarations, but if omitted once they must be omitted for the entirety of the object * - Faces may be Triangles or Quads * * \param path location of the OBJ file to be read; path may be relative or absolute * \param vertex_type \ref DataType that represents the vertex positions; must have exactly 3 dimensions * \param uv_type \ref DataType that represents the texture coordinates; must have exactly 2 dimensions * \param normal_type \ref DataType that represents the normal directions; must have exactly 3 dimensions * \return \ref RawModelData collection that stores the read data * \throw ModelLoadingException Throws a \ref ModelLoadingException when there is a problem opening the given OBJ file, * or when there is a structural problem with the given OBJ file, causing an error in parsing. * \throw FileParseException Throws a \ref FileParseException when there is a read error in the file beyond a * structural problem. * \sa RawModelData, DataType, loadFromOBJ(const char*) */ RawModelData loadFromOBJ(const char *path, const Type::DataType &vertex_type, const Type::DataType &uv_type, const Type::DataType &normal_type); //! Loads an OBJ file as a \ref RawModelData collection /*! * Performs the same functionality as \ref loadFromOBJ(const char*, Type::DataType&, Type::DataType&, Type::DataType&), * but with the standard defaults for the available \ref DataType values as follows: * * vertex_type: \ref Type::VERTEX * uv_type: \ref Type::UV * normal_type: \ref Type::NORMAL * * \param path location of the OBJ file to be read; path may be relative or absolute * \return \ref RawModelData collection that stores the read data * \throw ModelLoadingException Throws a \ref ModelLoadingException when there is a problem opening the given OBJ file, * or when there is a structural problem with the given OBJ file, causing an error in parsing. * \throw FileParseException Throws a \ref FileParseException when there is a read error in the file beyond a * structural problem. * \sa RawModelData, DataType, loadFromOBJ(const char*, Type::DataType&, Type::DataType&, Type::DataType&) */ static inline RawModelData loadFromOBJ(const char *path) { return loadFromOBJ(path, Type::VERTEX, Type::UV, Type::NORMAL); } //! Storage object for OpenGL Buffer and VAO IDs /*! * A Model object stores a collection of Buffer IDs representing OpenGL Data Buffers. The IDs are created with * data from a \ref RawModelDataIndexed collection; only one Model needs to be created for each unique * \ref RawModelDataIndexed collection. Models can be rendered by binding their Vertex Array Object (VAO) IDs, * which can be retrieved with \ref ::vao(), and are generated on an as needed basis for each OpenGL context, * depending on which one is active in the current thread. */ class Model { public: //! Default Model Constructor /*! * Creates a default empty Model object; cannot be used for rendering. */ Model() {}; //! Model Creation Constructor /*! * Creates a loaded Model object with Buffer IDs dependent on the passed \ref RawModelDataIndexed collection. * * \param data \ref RawModelDataIndexed collection to use */ Model(const RawModelDataIndexed &data); //! Model Copy Constructor /*! * Copies another Model object, making both Model objects have the same Buffer and VAO IDs. * * \param other Model to copy */ Model(const Model &other); //! Assignment Operator /*! * Assigns this Model object equal to another, making both Model objects have the same Buffer and VAO IDs. * * \param other Model to copy * \return reference to the current Model, for chaining statements */ Model &operator=(const Model &other); //! Get this Model's VAO ID /*! * Retrieves a VAO ID for the current model, based on which OpenGL context is active in the current thread. * If a VAO has not yet been generated for this Model and OpenGL context combination, generate a new VAO * before retrieving. * * \return VAO ID for this Model */ SWMuint vao(); //! Get this Model's number of Elements (Indices) size_t elementCount() const { return _element_count; } //! Has this Model been properly loaded yet? (Either from Creation or Copy/Assignment) bool loaded() const { return _loaded; } bool operator==(const Model &rhs) const; bool operator!=(const Model &rhs) const { return !operator==(rhs); } bool operator< (const Model &rhs) const; bool operator<=(const Model &rhs) const { return operator<(rhs) || operator==(rhs); } bool operator> (const Model &rhs) const { return !operator<=(rhs); } bool operator>=(const Model &rhs) const { return !operator<(rhs); } //! Cleanup all Model Objects /*! * Releases all Buffers and VAOs created by the construction of new Models. Generally called by * \ref Swarm::Model::cleanup(). */ static void cleanup(); protected: void genBuffers(const RawModelDataIndexed &data); void genVAO(); struct BufferEntry { SWMuint buffer; SWMuint attrib; VecType type; friend bool operator<(const BufferEntry &lhs, const BufferEntry &rhs) { return lhs.buffer < rhs.buffer; } }; bool _loaded = false; std::set<BufferEntry> _data_buffers; SWMuint _element_buffer = 0; size_t _element_count = 0; }; } namespace Render { void init(); void cleanup(); class Renderer; //! Representation of a GL Uniform /*! * The Uniform object is a representation of a GL Uniform. Changing a Uniform object will not change the Uniform * data bound to the GPU until \ref ::bind() is called, which is usually done internally by a \ref Renderer * object. * \sa ::bind() */ class Uniform { public: friend class Renderer; //! Uniform Constructor /*! * Create a new Uniform object with a specified name ID. * * \param name name used to represent the Uniform in a GLSL shader * \sa ::name, ::setName() */ Uniform(const std::string &name) : _name(name) {} //! Gets the Uniform's name /*! * Gets the name ID associated with this Uniform. * * \return name name used to represent the Uniform in a GLSL shader * \sa ::setName() */ std::string name() { return _name; } void setf (SWMsizei count, SWMsizei stride, SWMfloat *data); void seti (SWMsizei count, SWMsizei stride, SWMint *data); void setui(SWMsizei count, SWMsizei stride, SWMuint *data); void setm (SWMsizei count, SWMsizei width, SWMsizei height, SWMfloat *data); //! Binds the Uniform /*! * Binds the current data associated with this Uniform to the \ref Program used by the specified * \ref Renderer. Usually only called internally by a \ref Renderer object. Empty Uniform objects are not * valid to bind with. * * \param render \ref Renderer object to bind to * \sa ::empty(), ::clear() */ void bind(const Renderer &render); //! Clear this Uniform /*! * Clears the data that this Uniform object has stored and sets it to empty. * \sa ::bind(), ::empty() */ void clear(); //! Is this Uniform empty? /*! * Determines if this Uniform object is 'empty' and has no data. Empty Uniform objects are not valid to * bind with. * * \return true if empty, false otherwise * \sa ::bind(), ::clear() */ bool empty() { return _has_data; } protected: const std::string _name; bool _has_data = false; enum { F, I, UI, M } type; union { struct { SWMsizei count; SWMsizei stride; SWMfloat* data; } f; struct { SWMsizei count; SWMsizei stride; SWMint* data; } i; struct { SWMsizei count; SWMsizei stride; SWMuint* data; } ui; struct { SWMsizei count; SWMsizei width; SWMsizei height; SWMfloat* data; } m; } data; #if defined(SWARM_BOOST_AVAILABLE) void clear(boost::lock_guard<boost::mutex>&); #endif }; //! Object representing a collection of Render data /*! * A RenderObject object is a pure virtual class interface used for rendering. Each virtual method has certain * constraints that must be followed when they are implemented, as describes in the respective method * documentation. In addition, a simple 'static' position RenderObject can be created with the * \ref createStaticRenderObject() static method. * * \sa ::createStaticRenderObject() */ class RenderObject { public: virtual ~RenderObject() {} //! Get the \ref Model::Model associated with this RenderObject virtual Model::Model &model() const = 0; //! Get the \ref Texture::Texture associated with this RenderObject virtual Texture::Texture &texture() const = 0; //! Render this render object using the given \ref Renderer /*! * This method uses the given \ref Renderer to render this RenderObject. * * Implementation Constraints: Assumed to bind a \ref Model's VAO and use a glDraw call (most likely * glDrawElements), though could do nothing. Also a good idea to bind a model matrix. * * Multithreading: Rendering runs in its own thread, so any data that a RenderObject uses to render must * be sufficiently mutually excluded. Renderers are not accessed simultaneously by the rendering thread, * and neither are individual RenderObjects, so constant data is fine. * * \param renderer \ref Renderer object to render with */ virtual void render(const Renderer &renderer) const = 0; //! Create a new statically positioned RenderObject /*! * Constructs and returns a new statically positioned RenderObject. The RenderObject has a position, scale, * and rotation, but they cannot be changed after creation. The engine owns the pointer that is returned. * * \param model \ref Model::Model to use * \param texture \ref Texture::Texture to use * \param position_x Float representing X-Position * \param position_y Float representing Y-Position * \param position_z Float representing Z-Position * \param scale_x Float representing X-Scale * \param scale_y Float representing Y-Scale * \param scale_z Float representing Z-Scale * \param rotate_x Float representing X-Rotate * \param rotate_y Float representing Y-Rotate * \param rotate_z Float representing Z-Rotate * \return pointer to new RenderObject */ static RenderObject* createStaticRenderObject(Model::Model &model, Texture::Texture &texture, float position_x, float position_y, float position_z, float scale_x, float scale_y, float scale_z, float rotate_x, float rotate_y, float rotate_z); #if defined(SWARM_INCLUDE_GLM) static RenderObject* createStaticRenderObject(Model::Model &model, Texture::Texture &texture, glm::vec3 position, glm::vec3 scale, glm::vec3 rotate); #endif protected: RenderObject() {} }; //! A Collection of \ref RenderObject pointers /*! * A RenderObjectCollection is a complex, thread-safe collection of \ref RenderObject pointers. * \ref RenderObject objects that have the same \ref Texture::Texture are mapped together under that * \ref Texture::Texture. Internally, \ref RenderObject pointers are stored in a set, so only one pointer to * each actual \ref RenderObject can be stored. In addition, any inserts or erases of RenderObjects in the * collection are only applied after \ref ::flush() is called. Normally, this is called automatically by the * Window system. */ class RenderObjectCollection { public: RenderObjectCollection(); ~RenderObjectCollection(); //! Insert a \ref RenderObject to this collection /*! * Queues an insert on the next \ref ::flush() for the given \ref RenderObject pointer into this * collection, if it hasn't already been inserted. If a nullptr is given, does nothing. * * \param object \ref RenderObject pointer to insert */ void insert(RenderObject* object); //! Erase a \ref RenderObject from this collection /*! * Queues an erase on the next \ref ::flush() for the given \ref RenderObject pointer from this collection * if it exists. If the given pointer is null, or it does not exist in this collection, does nothing. * Erasing a \ref RenderObject pointer does delete the object, only remove the pointer from this collection. * * \param object \ref RenderObject pointer to erase */ void erase(RenderObject* object); //! Flushes all changes /*! * Applies any \ref ::insert() and \ref ::erase() changes that have been queued. This is done automatically * by the Window system during the Render cycle, so there is no need to manually call it in most cases. */ void flush(); //! Clears this collection /*! * Clears this collection, and erases all \ref RenderObject pointers. * * \sa erase() */ void clear(); void render(const Renderer &renderer); //! Gets a set of \ref RenderObject pointers /*! * Retrieves the set of \ref RenderObject pointers that are mapped to a specific \ref Texture::Texture, or * an empty set if there are none for the specified \ref Texture::Texture. * * \param tex \ref Texture::Texture to use as a key * \return a set of \ref RenderObject pointers */ std::set<RenderObject*> &get(const Texture::Texture &tex) { return _data[tex]; } //! Gets the set of \ref RenderObject pointers /*! * Retrieves the set of \ref RenderObject pointers that are mapped to a specific \ref Texture::Texture, or * an empty set if there are none for the specified \ref Texture::Texture. * Alias for \ref ::get(). * * \param tex \ref Texture::Texture to use as a key * \return a set of \ref RenderObject pointers * \sa get() */ std::set<RenderObject*> &operator[](const Texture::Texture &tex) { return _data[tex]; } std::map<Texture::Texture, std::set<RenderObject*>>::iterator begin() { return _data.begin(); } std::map<Texture::Texture, std::set<RenderObject*>>::const_iterator begin() const { return _data.begin(); } std::map<Texture::Texture, std::set<RenderObject*>>::iterator end() { return _data.end(); } std::map<Texture::Texture, std::set<RenderObject*>>::const_iterator end() const { return _data.end(); } protected: std::map<Texture::Texture, std::set<RenderObject*>> _data; std::set<RenderObject*> _queue_insert; std::set<RenderObject*> _queue_erase; size_t _uid; }; //! Class-Enum used to represent GLenum Shader types. /*! * The ShaderType class is used as a manual enumeration to represent different Shader types in OpenGL. The * ShaderType constructor is private, and it cannot be created other than by the static Types defined in the * ShaderType namespace. This Class-Enum is essentially used to represent an OpenGL type * w/o using 3rd party libraries/loaders (e.g. GLEW), but will return a GLenum if \ref SWARM_INCLUDE_GLEW * is defined. */ class ShaderType { private: ShaderType(SWMenum type, const std::string &name) : _type(type), _name(name) {}; SWMenum _type; std::string _name; public: //! VERTEX maps to the GLenum GL_VERTEX_SHADER static ShaderType VERTEX; //! GEOMETRY maps to the GLenum GL_GEOMETRY_SHADER static ShaderType GEOMETRY; //! FRAGMENT maps to the GLenum GL_FRAGMENT_SHADER static ShaderType FRAGMENT; SWMenum type() const { return _type; } operator SWMenum() const { return _type; } std::string name() const { return _name; } ShaderType(const ShaderType &other) { operator=(other); } ShaderType &operator=(const ShaderType &rhs); }; class Shader { public: virtual ~Shader() {} virtual SWMuint ID() const = 0; virtual operator SWMuint() const = 0; virtual const ShaderType &type() const = 0; static Shader* compileFromSource(const std::string &src, const ShaderType &type); static Shader* compileFromFile(const std::string &path, const ShaderType &type); private: Shader() {} friend class ShaderInternal; }; class Program { public: virtual ~Program() {} //! Get the GLuint ID representing this linked shader Program. virtual SWMuint ID() const = 0; //! Get the ID for a specified shader Uniform variable. /*! * Scans the linked Program for the specified shader Uniform and returns its ID. * If the Uniform is found, it is cached in an internal map for fast future lookup. */ virtual SWMint uniform(const std::string &name) = 0; //! Clears the Uniform Cache. /*! * Clears the internal map used for caching Uniforms. Should be done once in the beginning of each * render cycle. Usually done in the start phase of a \ref Renderer; */ virtual void clearUniformCache() = 0; static Program* compile(Shader* shaders[], size_t count); private: Program() {} friend class ProgramInternal; }; struct CameraPosition { struct CPos { float x; float y; float z; #if defined(SWARM_INCLUDE_GLM) CPos &operator=(const glm::vec3 &rhs) { x = rhs.x; y = rhs.y; z = rhs.z; } CPos &operator=(const CPos &rhs) { x = rhs.x; y = rhs.y; z = rhs.z; } operator glm::vec3() const { return glm::vec3(x, y, z); } glm::vec3 vec() const { return glm::vec3(x, y, z); } #endif bool operator==(const CPos &rhs) { return x == rhs.x && y == rhs.y && z == rhs.z; } bool operator!=(const CPos &rhs) { return !operator==(rhs); } } position, look_at, up; CameraPosition() : position(CPos{0.0f, 0.0f, 0.0f}), look_at(CPos{0.0f, 0.0f, 1.0f}), up(CPos{0.0f, 1.0f, 0.0f}) {} CameraPosition(float pos_x, float pos_y, float pos_z, float look_x, float look_y, float look_z, float up_x, float up_y, float up_z) : position(CPos{pos_x, pos_y, pos_z}), look_at(CPos{look_x, look_y, look_z}), up(CPos{up_x, up_y, up_z}) {} #if defined(SWARM_INCLUDE_GLM) CameraPosition(glm::vec3 pos, glm::vec3 look, glm::vec3 up) : position(CPos{pos.x, pos.y, pos.z}), look_at(CPos{look.x, look.y, look.z}), up(CPos{up.x, up.y, up.z}) {} #endif bool operator==(const CameraPosition &rhs) { return position == rhs.position && look_at == rhs.look_at && up == rhs.up; } bool operator!=(const CameraPosition &rhs) { return !operator==(rhs); } friend std::ostream &operator<<(std::ostream &stream, const CameraPosition &pos) { stream << std::string("{ (") << std::to_string(pos.position.x) << std::string(", ") << std::to_string(pos.position.y) << std::string(", ") << std::to_string(pos.position.z) << std::string("), (") << std::to_string(pos.look_at.x) << std::string(", ") << std::to_string(pos.look_at.y) << std::string(", ") << std::to_string(pos.look_at.z) << std::string("), (") << std::to_string(pos.up.x) << std::string(", ") << std::to_string(pos.up.y) << std::string(", ") << std::to_string(pos.up.z) << std::string(") }"); return stream; } }; class Camera { public: enum MoveType { INSTANT, SMOOTH, LERP }; virtual MoveType moveType() const = 0; virtual void setMoveType(MoveType type) = 0; virtual float speed() const = 0; virtual void setSpeed(float speed) = 0; virtual float fov() const = 0; virtual void setFOV(float fov) = 0; virtual float viewDistance() const = 0; virtual void setViewDistance(float distance) = 0; virtual void setPosition(const CameraPosition &pos, bool instant = false) = 0; virtual CameraPosition position(bool instant = false) = 0; virtual void update(double delta_time) = 0; static void printBuffers(); static Camera* create(float speed = 1.0f, MoveType type = INSTANT); static Camera* create(const CameraPosition &pos, float speed = 1.0f, MoveType type = INSTANT); #if defined(SWARM_INCLUDE_GLM) virtual glm::mat4 viewMatrix() const = 0; virtual glm::mat4 projectionMatrix(int width, int height) const = 0; #endif private: Camera() {} friend class CameraInternal; }; #if defined(SWARM_BOOST_AVAILABLE) boost::mutex &getWindowContextMutex(); #endif class WindowInternal; class RendererInternal; class Window { public: Window(); Window(unsigned int width, unsigned int height, const std::string &name = "Swarm Engine Instance"); Window(const Window &rhs); Window &operator=(const Window &rhs); bool operator==(const Window &rhs) const; bool operator!=(const Window &rhs) const { return !operator==(rhs); } int width() const; int height() const; int posX() const; int posY() const; std::string name() const; bool focused() const; void setVisible(bool visible); bool visible() const; void setCamera(Camera* camera); Camera* camera() const; void cursorPos(double &pos_x, double &pos_y); void attachRenderer(const Renderer* renderer, RenderObjectCollection &collection, bool reverse = false); void setClearColor(float r, float g, float b, float a = 1.0f); #if defined(SWARM_INCLUDE_GLFW) GLFWwindow* window() const; operator GLFWwindow*() const; #endif protected: friend class WindowInternal; friend class RendererInternal; Window(WindowInternal* window); WindowInternal* _window; }; class Renderer { public: typedef void (*RenderCycleFunc)(const Renderer&, const Window&); virtual ~Renderer() {} virtual Program* program() const = 0; enum RenderCyclePhase { START, END }; virtual void setRenderCycleFunction(RenderCyclePhase phase, RenderCycleFunc function) = 0; enum MatrixUniformType { MODEL, VIEW, PROJECTION }; virtual void setUniformName(MatrixUniformType type, const std::string &name) = 0; virtual std::string uniformName(MatrixUniformType type) const = 0; virtual void setTextureName(SWMuint active, const std::string &name) = 0; virtual void setTextureName(const Texture::Type::MapType &type, const std::string &name) = 0; virtual std::string textureName(SWMuint active) const = 0; virtual std::string textureName(const Texture::Type::MapType &type) const = 0; virtual void insertUniform(Uniform &uniform) = 0; virtual void bindUniformsMatrix(const Window &window) const = 0; virtual void bindUniformsTexture() const = 0; virtual void bindUniformsCustom() const = 0; static Renderer* create(Program* program); private: Renderer() {} friend class RendererInternal; }; } }
true
0f9762c0b4aff329f77d182d00540d3786ec13a6
C++
NII-APP/NPO
/Program/source/CGL/cparallelepiped.h
UTF-8
3,788
2.65625
3
[]
no_license
#ifndef CPARALLELEPIPED_H #define CPARALLELEPIPED_H #include <QtGlobal> #include <cmath> #include <QVector3D> #include <QRectF> #include <QDebug> class QRectF; class QVector3D; class CParallelepiped { qreal xP; qreal yP; qreal zP; qreal xL; qreal yL; qreal zL; void testBumpy(qreal& min, qreal& max) { qreal d(max - min); if (d == 0) { if (min) { max += 0.1 * d; min -= 0.1 * d; } else { min = -1.0; max = 1.0; } } } public: CParallelepiped(); CParallelepiped(qreal x1, qreal x2, qreal y1, qreal y2, qreal z1, qreal z2); CParallelepiped(qreal l, qreal r, qreal b, qreal t, qreal n); CParallelepiped(qreal l, qreal r, qreal b, qreal t); CParallelepiped(qreal l, qreal r, qreal b); explicit CParallelepiped(const QVector3D&); inline qreal xMin() const { return xL; } inline qreal xMax() const { return xP; } inline qreal yMin() const { return yL; } inline qreal yMax() const { return yP; } inline qreal zMin() const { return zL; } inline qreal zMax() const { return zP; } inline qreal width() const { return xP - xL; } inline qreal height() const { return yP - xL; } inline qreal length() const { return zP - zL; } inline qreal size() const { qreal w(width()), h(height()), l(length()); return sqrt(w * w + h * h + l * l); } void move(const QVector3D& v); inline void xTo(qreal v) { xL = xP = v; } inline void yTo(qreal v) { yL = yP = v; } inline void zTo(qreal v) { zL = zP = v; } inline void multX(qreal k) { xL *= k; xP *= k; } inline void multY(qreal k) { yL *= k; yP *= k; } inline void multZ(qreal k) { zL *= k; zP *= k; } inline QVector3D center() const { return QVector3D((xP + xL) / 2., (yP + yL) / 2., (zL + zP) / 2.); } inline void includeX(qreal v) { if (!(v <= xP)) { xP = v; } if (!(v >= xL)) xL = v; } inline void includeY(qreal v) { if (!(v <= yP)) { yP = v; } if (!(v >= yL)) yL = v; } inline void includeZ(qreal v) { if (!(v <= zP)) { zP = v; } if (!(v >= zL)) zL = v; } inline void include(const QVector3D& v) { includeX(v.x()); includeY(v.y()); includeZ(v.z()); } inline void include(const double* v) { includeX(*v); includeY(v[1]); includeZ(v[2]); } inline void include(const float* v) { includeX(*v); includeY(v[1]); includeZ(v[2]); } inline void setFlatY(qreal v) { yP = yL = v; } inline void setFlatZ(qreal v) { zP = yL = v; } inline void setFlatY() { yP = yL; } inline void setFlatZ() { zP = yL; } inline void testBumpy() { testBumpyX(); testBumpyY(); testBumpyZ(); } inline void testBumpyX() { testBumpy(xL, xP); } inline void testBumpyY() { testBumpy(yL, yP); } inline void testBumpyZ() { testBumpy(zL, zP); } operator QRectF() const { return QRectF(xMin(),yMax(),width(), height()); } CParallelepiped& operator +=(const CParallelepiped& e); CParallelepiped operator + (const CParallelepiped& e) const; CParallelepiped& operator |=(const CParallelepiped& e) { return *this += e; } bool operator ==(const QVector3D& v) const; bool operator !=(const QVector3D& v) const; friend QDataStream& operator >> (QDataStream& in, CParallelepiped& p); }; inline bool operator ==(const QVector3D& a, const CParallelepiped& b) { return b == a; } inline bool operator !=(const QVector3D& a, const CParallelepiped& b) { return b != a; } QDebug operator << (QDebug out, const CParallelepiped& p); QTextStream& operator << (QTextStream& out, const CParallelepiped& p); QDataStream& operator << (QDataStream& out, const CParallelepiped& p); QDataStream& operator >> (QDataStream& in, CParallelepiped& p); #endif // CPARALLELEPIPED_H
true
22f330e91a0edbc96a3769701593a1df66c48651
C++
dongfeng86/DataStructures-Practice
/如何查看运行时间/main.cpp
GB18030
826
3.28125
3
[]
no_license
#include<iostream> #include <vector> #include <windows.h> int main() { using std::endl; using std::cout; using std::cin; std::vector<int> ar; DWORD start_time = GetTickCount(); for (int i = 0; i < 1000000; i++) { ar.push_back(i); } DWORD end_time = GetTickCount(); cout << "ѹ1000000õʱΪ" << (end_time - start_time) *1.0 / 1000 << "s!" << endl; double iCount = 10000; for (iCount = 10000; iCount < 1000000; iCount += 50000) { start_time = GetTickCount(); int i; for (i = 0; i < ar.size(); i++) { if (iCount == ar[i]) { break; } } end_time = GetTickCount(); cout << "\nҵˣ200000֣ڵ" << i << "" <<"ҵ" <<i<<"ʱΪ"<< (end_time - start_time)*1.0 / 1000 << "s!" << endl; } return 0; }
true
83560799802af59de521ab2b726b97f65f8d1588
C++
nunottlopes/feup-prog
/Bus.h
UTF-8
644
2.796875
3
[]
no_license
#pragma once #include <iostream> #include <vector> #include "Shift.h" using namespace std; class Bus { public: Bus(unsigned int orderInLine, unsigned int driver, unsigned int line); Bus(unsigned int orderInLine); // get methods unsigned int getBusOrderInLine() const; unsigned int getDriverId() const; unsigned int getLineId() const; vector<Shift> getSchedule() const; // set methods unsigned int setDriverId() const; unsigned int setLineId() const; // other methods private: unsigned int orderInLine; unsigned int driverId; unsigned int lineId; vector<Shift> schedule; };
true
e49faa0b2adfe9a47d27b068722fd0fd75dec55d
C++
microsoft/IIS.Compression
/iiszlib/iiszlib.cxx
UTF-8
14,802
2.53125
3
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "stdafx.h" class ZLIB_CONTEXT { public: ZLIB_CONTEXT() : _fInitialized(FALSE), _fGzip(FALSE), _windowBits(ZLIB_DEF_WINDOW_BITS), _memLevel(ZLIB_DEF_MEM_LEVEL), _flushMode(Z_NO_FLUSH) { _strm.zalloc = Z_NULL; _strm.zfree = Z_NULL; _strm.opaque = Z_NULL; _strm.next_in = Z_NULL; _strm.avail_in = 0; _strm.total_in = 0; _strm.next_out = Z_NULL; _strm.avail_out = 0; _strm.total_out = 0; } BOOL _fInitialized; BOOL _fGzip; // zlib parameters z_stream _strm; INT _windowBits; INT _memLevel; INT _flushMode; }; HRESULT HresultFromZlib(INT zlibErrCode); INT ConvertFlushMode(INT operation); HRESULT ReportCompressionLevelOutOfBounds(INT currentLevel, INT maxLevel); // // Initialize global compression // HRESULT WINAPI InitCompression( VOID ) { g_hEventLog = RegisterEventSource(NULL, IISZLIB_EVENT_SOURCE_NAME); // Ignore the failure from RegisterEventSource return S_OK; } // // De-init global compression // VOID WINAPI DeInitCompression( VOID ) { if (g_hEventLog != NULL) { DeregisterEventSource(g_hEventLog); g_hEventLog = NULL; } return; } // // Reset compression context // HRESULT WINAPI ResetCompression( IN OUT PVOID context ) { return S_OK; } // // Create a compression context // HRESULT WINAPI CreateCompression( OUT PVOID * context, IN ULONG flags ) { HRESULT hr = S_OK; ZLIB_CONTEXT* pContext = NULL; if (flags == COMPRESSION_FLAG_INVALID) { DBGERROR((DBG_CONTEXT, "Invalid flags\n")); hr = E_INVALIDARG; goto Finished; } pContext = new ZLIB_CONTEXT(); if (pContext == NULL) { DBGERROR((DBG_CONTEXT, "Failed to create ZLIB_CONTEXT\n")); hr = E_OUTOFMEMORY; goto Finished; } // window bits if (g_intWindowBits != ZLIB_PARAMETER_UNSET) { pContext->_windowBits = g_intWindowBits; } // mem level if (g_intMemLevel != ZLIB_PARAMETER_UNSET) { pContext->_memLevel = g_intMemLevel; } // flush mode if (g_intFlushMode != ZLIB_PARAMETER_UNSET) { pContext->_flushMode = g_intFlushMode; } // compressed data format if (flags & COMPRESSION_FLAG_GZIP) { // gzip content-encoding: // Add 16 to windowBits to ask zlib to write gzip format header & trailer. // By default zlib write zlib format header & trailer used by deflate content encoding. pContext->_fGzip = TRUE; pContext->_windowBits |= 16; } else { // deflate content-encoding: if (g_fEnableZlibDeflate == FALSE) { // default mode: raw deflate for IE compatibility // Flip the sign of windowBits to force zlib to produce raw deflate // without zlib header and checksum pContext->_windowBits = - pContext->_windowBits; } } DBGINFO((DBG_CONTEXT, "ZLIB_CONTEXT initialized\n" "- ptr: %p\n" "- scheme: %s\n" "- windowBits: %d\n" "- memLevel: %d\n" "- flush mode: %d\n", pContext, pContext->_fGzip ? "gzip" : "deflate", pContext->_windowBits, pContext->_memLevel, pContext->_flushMode)); Finished: *context = (PVOID)pContext; return hr; } // // Destroy a compression context // VOID WINAPI DestroyCompression( IN PVOID context ) { ZLIB_CONTEXT* pContext = static_cast<ZLIB_CONTEXT *>(context); if (pContext != NULL) { if (pContext->_fInitialized == TRUE) { deflateEnd(&pContext->_strm); } delete pContext; } } // // Compress data // HRESULT WINAPI Compress( IN OUT PVOID context, IN CONST BYTE * input_buffer, IN LONG input_buffer_size, IN PBYTE output_buffer, IN LONG output_buffer_size, OUT PLONG input_used, OUT PLONG output_used, IN INT compression_level ) { ZLIB_CONTEXT* pContext = static_cast<ZLIB_CONTEXT *>(context); HRESULT hr = S_OK; INT ret = Z_OK; INT flushMode = input_buffer_size ? pContext->_flushMode : Z_FINISH; if (pContext == NULL) { hr = E_INVALIDARG; goto Finished; } // IIS schema specifies staticCompressionLevel and dynamicCompressionLevel as uint, // so only the upper bound needs to be checked. if (compression_level > Z_BEST_COMPRESSION) { // Ignore any failure from event reporting ReportCompressionLevelOutOfBounds(compression_level, Z_BEST_COMPRESSION); compression_level = Z_BEST_COMPRESSION; } if (pContext->_fInitialized == FALSE) { ret = deflateInit2(&pContext->_strm, // strm compression_level, // level Z_DEFLATED, // method pContext->_windowBits, // windowBits pContext->_memLevel, // memLevel Z_DEFAULT_STRATEGY); // strategy if (FAILED(hr = HresultFromZlib(ret))) { DBGERROR((DBG_CONTEXT, "deflateInit2 failed: %d\n", ret)); deflateEnd(&pContext->_strm); goto Finished; } pContext->_fInitialized = TRUE; } pContext->_strm.next_in = (z_const Bytef *) input_buffer; pContext->_strm.avail_in = input_buffer_size; pContext->_strm.next_out = output_buffer; pContext->_strm.avail_out = output_buffer_size; DBGINFO((DBG_CONTEXT, "Start deflate\n" "- input buffer: %p\n" "- input buffer size: %d\n" "- output buffer: %p\n" "- output buffer size: %d\n" "- compression level: %d\n" "- flush mode: %d\n", input_buffer, input_buffer_size, output_buffer, output_buffer_size, compression_level, flushMode)); ret = deflate(&pContext->_strm, flushMode); if (ret == Z_OK || ret == Z_BUF_ERROR) { DBGINFO((DBG_CONTEXT, "Need to call Compress again\n")); hr = S_OK; } else if (ret == Z_STREAM_END) { DBGINFO((DBG_CONTEXT, "End of stream\n")); hr = S_FALSE; } else { hr = HresultFromZlib(ret); DBGERROR((DBG_CONTEXT, "deflate failed: %d\n", ret)); goto Finished; } *input_used = input_buffer_size - pContext->_strm.avail_in; *output_used = output_buffer_size - pContext->_strm.avail_out; DBGINFO((DBG_CONTEXT, "End deflate\n" "- input bytes consumed: %d\n" "- output bytes produced: %d\n", *input_used, *output_used)); Finished: return hr; } // // Compress data with a specified flush mode // HRESULT WINAPI Compress2( IN OUT PVOID context, IN CONST BYTE * input_buffer, IN LONG input_buffer_size, IN PBYTE output_buffer, IN LONG output_buffer_size, OUT PLONG input_used, OUT PLONG output_used, IN INT compression_level, IN INT operation ) { ZLIB_CONTEXT* pContext = static_cast<ZLIB_CONTEXT *>(context); HRESULT hr = S_OK; INT ret = Z_OK; INT flushMode = ConvertFlushMode(operation); if (pContext == NULL) { hr = E_INVALIDARG; goto Finished; } // IIS schema specifies staticCompressionLevel and dynamicCompressionLevel as uint, // so only the upper bound needs to be checked. if (compression_level > Z_BEST_COMPRESSION) { // Ignore any failure from event reporting ReportCompressionLevelOutOfBounds(compression_level, Z_BEST_COMPRESSION); compression_level = Z_BEST_COMPRESSION; } if (pContext->_fInitialized == FALSE) { ret = deflateInit2(&pContext->_strm, // strm compression_level, // level Z_DEFLATED, // method pContext->_windowBits, // windowBits pContext->_memLevel, // memLevel Z_DEFAULT_STRATEGY); // strategy if (FAILED(hr = HresultFromZlib(ret))) { DBGERROR((DBG_CONTEXT, "deflateInit2 failed: %d\n", ret)); deflateEnd(&pContext->_strm); goto Finished; } pContext->_fInitialized = TRUE; } pContext->_strm.next_in = (z_const Bytef *) input_buffer; pContext->_strm.avail_in = input_buffer_size; pContext->_strm.next_out = output_buffer; pContext->_strm.avail_out = output_buffer_size; DBGINFO((DBG_CONTEXT, "Start deflate\n" "- input buffer: %p\n" "- input buffer size: %d\n" "- output buffer: %p\n" "- output buffer size: %d\n" "- compression level: %d\n" "- flush mode: %d\n", input_buffer, input_buffer_size, output_buffer, output_buffer_size, compression_level, flushMode)); ret = deflate(&pContext->_strm, flushMode); if (ret == Z_OK) { if (flushMode == Z_SYNC_FLUSH && input_buffer_size == 0 && pContext->_strm.avail_out > 0) // sufficient output buffer size { DBGINFO((DBG_CONTEXT,"End of flush\n")); hr = S_FALSE; } else { DBGINFO((DBG_CONTEXT, "Need to call Compress2 again\n")); hr = S_OK; } } else if (ret == Z_BUF_ERROR) { DBGINFO((DBG_CONTEXT, "Need to call Compress2 again\n")); hr = S_OK; } else if (ret == Z_STREAM_END) { DBGINFO((DBG_CONTEXT, "End of stream\n")); hr = S_FALSE; } else { hr = HresultFromZlib(ret); DBGERROR((DBG_CONTEXT, "deflate failed: %d\n", ret)); goto Finished; } *input_used = input_buffer_size - pContext->_strm.avail_in; *output_used = output_buffer_size - pContext->_strm.avail_out; DBGINFO((DBG_CONTEXT, "End deflate\n" "- input bytes consumed: %d\n" "- output bytes produced: %d\n", *input_used, *output_used)); if (*output_used == 0 && *input_used == 0 && ret == Z_BUF_ERROR && flushMode == Z_SYNC_FLUSH) { // If this function (Compress2) is called twice with zero input data and the same operation value (IIS_COMPRESSION_OPERATION_PROCESS), // the deflate() function will return Z_BUF_ERROR for the second call. DBGINFO((DBG_CONTEXT, "Compress2 was called twice with zero input data with Z_SYSNC_FLUSH. Compress2 should not be called again\n")); hr = S_FALSE; } Finished: return hr; } HRESULT HresultFromZlib( INT zlibErrCode ) { HRESULT hr = S_OK; switch (zlibErrCode) { case Z_OK: case Z_BUF_ERROR: // output buffer full, not a real error hr = S_OK; break; case Z_STREAM_END: // all input consumed, all output generated hr = S_FALSE; // S_FALSE is required by IIS to indicate final block done break; case Z_MEM_ERROR: hr = E_OUTOFMEMORY; break; case Z_DATA_ERROR: hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); break; case Z_VERSION_ERROR: hr = HRESULT_FROM_WIN32(ERROR_INVALID_DLL); break; case Z_STREAM_ERROR: hr = E_INVALIDARG; break; case Z_ERRNO: default: hr = HRESULT_FROM_WIN32(zlibErrCode); break; } return hr; } INT ConvertFlushMode( INT operation ) { INT flushMode = Z_NO_FLUSH; if (g_intFlushMode != ZLIB_PARAMETER_UNSET) { flushMode = g_intFlushMode; } switch (operation) { case IIS_COMPRESSION_OPERATION_PROCESS: break; case IIS_COMPRESSION_OPERATION_FLUSH: flushMode = Z_SYNC_FLUSH; break; case IIS_COMPRESSION_OPERATION_FINISH: flushMode = Z_FINISH; break; default: break; } return flushMode; } HRESULT ReportCompressionLevelOutOfBounds( INT currentLevel, INT maxLevel ) { WCHAR bufCurrentLevel[COMPRESSION_LEVEL_BUFFER_LENGTH]; WCHAR bufMaxLevel[COMPRESSION_LEVEL_BUFFER_LENGTH]; PCWSTR apsz[2]; HRESULT hr = S_OK; BOOL fReport = TRUE; if (g_fEventRaised == TRUE) { hr = S_OK; goto Finished; } if (g_hEventLog == NULL) { hr = E_HANDLE; goto Finished; } if (_itow_s(currentLevel, bufCurrentLevel, COMPRESSION_LEVEL_BUFFER_LENGTH, 10) != 0 || _itow_s(maxLevel, bufMaxLevel, COMPRESSION_LEVEL_BUFFER_LENGTH, 10) != 0) { hr = E_UNEXPECTED; goto Finished; } apsz[0] = bufCurrentLevel; apsz[1] = bufMaxLevel; fReport = ReportEvent(g_hEventLog, // hEventLog EVENTLOG_WARNING_TYPE, // wType 0, // wCategory ZLIB_COMPRESSION_LEVEL_OUT_OF_BOUNDS, // dwEventID NULL, // lpUserSid 2, // wNumStrings 0, // dwDataSize apsz, // lpStrings NULL); // lpRawData if (fReport == FALSE) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } g_fEventRaised = TRUE; Finished: return hr; }
true
d3c0655359df45387020303048f8f29d9efd9a81
C++
Lucaslpena/TimeComplexityThroughDataStructures
/doublylinkedlist.h
UTF-8
1,451
3.046875
3
[]
no_license
#ifndef DOUBLYLINKEDLIST_H #define DOUBLYLINKEDLIST_H #include <iostream> #include "plays.h" using namespace std; struct Node { Plays data; Node *Nxt,*Prv; Node(Plays y) { data = y; Nxt = Prv = NULL; } }; class doublylinkedlist { public: void print(int n) { iterator = front; for (int l = 0; l != n; ++l) { if (iterator->data.returndesc() == "Null") iteratorInc(); cout << iterator->data.returndesc() << " " << iterator->data.returnMin() << " " << iterator->data.returnOff() << " " << iterator->data.returnDeff() << " " << iterator->data.returnTogo() << " " << iterator->data.returnydline() << " " << endl; iteratorInc(); } } void iteratorInc() { if (iterator == back) iterator = NULL; else iterator = iterator->Nxt; } void iteratorDec() { if (iterator == front) iterator = NULL; else iterator = iterator->Prv; } void iteratorDEL() { iterator->Prv->Nxt = iterator->Nxt; iterator->Nxt->Prv = iterator->Prv; } void iteratorM2F() { iteratorDEL(); front->Nxt->Prv = iterator; iterator->Prv = front; iterator->Nxt = front->Prv; front->Nxt = iterator; } Node *front,* back, *iterator; doublylinkedlist() { front = NULL; back = NULL; } void storeback(Plays entered) { Node *n = new Node(entered); n->data = entered; if( back == NULL) { front = n; back = n; } else { back->Nxt = n; n->Prv = back; back = n; } } }; #endif
true
62f2b86327891add6c0e64ec3bff9683495cc6d0
C++
DorianHawkmoon/betaglo
/ProcessCommands.cpp
UTF-8
7,337
3
3
[ "MIT" ]
permissive
#include "Arduino.h" #include "ProcessCommands.h" #include "Enumerations.h" SoftwareSerial mySerial(13,12); // RX, TX States stateHand; unsigned long timerMouse; StatesKeyboard stateKeyboard; unsigned long timerKeys; int finger; int timesFinger; unsigned long previousTimerKeys; int limitTimeFinger=500; char keyboardLettersMayus[][7]={ { 'S','D','U','G','H','Ñ' }, {'O','I','T','B','Q','J','K' }, {'A','N','C','P','Y','Z','W' }, {'E','R','L','M','V','F','X' } }; char numbers[][7]={ { '1','5','9' }, { '2','6','0' }, { '3','7' }, { '4','8' } }; char keyboardLettersMinus[][7]={ { 's','d','u','g','h','ñ' }, { 'o','i','t','b','q','j','k' }, { 'a','n','c','p','y','z','w' }, { 'e','r','l','m','v','f','x' } }; char symbols[][7]={ { ' ','!',')',':' }, { '.','?','¡',';' }, { ',','(','¿','\'' }, { '\n','\b','"' } }; //por cada dedo(4), el numero de caracteres que tiene para saber que modulo hacer, //ordenados segun la enumeracion int numberChars[][4]={ { 6,7,7,7 }, { 6,7,7,7 }, { 3,3,2,2 }, { 4,4,4,3 } }; void setupCommand(){ mySerial.begin(9600); stateHand=mouse; timerMouse=0; finger=-1; timesFinger=-1; timerKeys=-1; stateKeyboard=minusculas; } /* * Condicion imprescindible que la cadena termine con \n */ void sendBluetooth(String value){ Serial.println(value); // Length (with one extra character for the null terminator and \n) int strLen = value.length() + 2; // Prepare the character array (the buffer) char charArray[strLen]; // Copy it over value.toCharArray(charArray, strLen); charArray[strLen-2]='\n'; charArray[strLen-1]='\0'; if (mySerial.available()) { mySerial.write(charArray); } } void sendKey(){ String key="tecla:"; char charToAppend; if(timerKeys!=-1 && timesFinger!=-1){ switch(stateKeyboard){ case minusculas: charToAppend=keyboardLettersMinus[finger][timesFinger]; break; case mayusculas: charToAppend=keyboardLettersMayus[finger][timesFinger]; break; case simbolos: charToAppend=symbols[finger][timesFinger]; //vigilo caracteres especiales dificiles if(charToAppend=='\n'){ key=key+"PK_Enter"; }else if(charToAppend=='\b'){ key=key+"BackSpace"; }else if(charToAppend==' '){ key=key+"space"; }else{ key=key+charToAppend; } break; case numeros: charToAppend=numbers[finger][timesFinger]; break; } if(stateKeyboard!=simbolos){ key=key+charToAppend; } } timerKeys=-1; timesFinger=-1; sendBluetooth(key); } void processButtonMouse(int value){ switch(value){ //click normal del indice case 64: sendBluetooth("click"); break; //click fuerte del indice case 128: sendBluetooth("apretar"); break; //click normal corazon case 16: sendBluetooth("clickderecho"); break; //click fuerte corazon case 32: sendBluetooth("soltar"); break; //anular normal case 4: //control C sendBluetooth("tecla:ctrl+c"); break; //click fuerte anular case 8: Serial.println("changed state patterns"); stateHand=patterns; break; //click normal meñique case 1: //control v sendBluetooth("tecla:ctrl+v"); break; //click fuerte meñique case 2: Serial.println("changed state keyboard"); stateHand=keyboard; stateKeyboard=minusculas; break; } } void processButtonKeyboard(int value){ //lo primero mirar si queda por escribir alguna letra por espera del tiempo if(timerKeys!=-1 && (millis()-timerKeys)>limitTimeFinger){ sendKey(); } int numberFinger=-1; switch(value){ //click fuerte meñique case 2: Serial.println("changed state mouse"); stateHand=mouse; break; //anular fuerte case 8: Serial.println("changed state numbers"); stateKeyboard=numeros; break; //dedo corazon fuerte case 32: if(stateKeyboard==minusculas){ Serial.println("changed state mayusculas"); stateKeyboard=mayusculas; } else{ Serial.println("changed state minusculas"); stateKeyboard=minusculas; } break; //click fuerte indice case 128: Serial.println("changed state simbolos"); stateKeyboard=simbolos; break; //indice case 64: numberFinger=0; break; //corazon case 16: numberFinger=1; break; //anular case 4: numberFinger=2; break; //meñique case 1: numberFinger=3; break; } if(numberFinger!=-1){ if(finger!=numberFinger){ sendKey(); finger=numberFinger; } timesFinger=(timesFinger+1)%(numberChars[0][finger]); timerKeys=millis(); } } void processButtonPatterns(int value){ switch(value){ //click normal del indice case 64: sendBluetooth("tecla:ctrl+z"); break; //click fuerte del indice case 128: break; //click normal corazon case 16: sendBluetooth("comando:firefox"); break; //click fuerte corazon case 32: break; //anular normal case 4: break; //click fuerte anular case 8: Serial.println("changed state initial"); stateHand=mouse; break; //click normal meñique case 1: break; //click fuerte meñique case 2: break; } } //guardo una lista de variables que me permite saber el estado actual del guante //es decir, por ejemplo estoy actualmente controlando el raton. Un toque largo del meñique cambiaria al estado de teclado //por lo que los botones pasarian a hacer otras acciones void processCommands(ClickButton buttons[],boolean flexorActived[], int flexor[], int DEDOS){ int processButton=0; int result=0; //variable con 8 bits, cada dos bits es un dedo for(int i=0; i<DEDOS; i++){ processButton=(int)buttons[i]; //enumeracion convertida a int int desplazamiento=2*i; int resultDesplazamiento=(processButton<<desplazamiento); result= result | resultDesplazamiento; } //preferencia a los botones para procesar el estado if(stateHand==mouse){ processButtonMouse(result); } else if(stateHand==keyboard){ processButtonKeyboard(result); } else if(patterns){ processButtonPatterns(result); } if(stateHand==mouse){ //procesamos los flexores cuando estamos en modo raton if(stateHand==mouse){ for(int i=0; i<DEDOS; i++){ int delay=millis()-timerMouse; if(flexorActived[i]==true && delay>50){ int value=flexor[i]; value = map(value, 0, 100, 1, 20); String command="raton:"; switch(i){ case 0: command=command+value; command=command+":0"; sendBluetooth(command); break; case 1: value=value*(-1); command=command+value; command=command+":0"; sendBluetooth(command); break; case 2: value=value*(-1); command=command+"0:"; command=command+value; sendBluetooth(command); break; case 3: command=command+"0:"; command=command+value; sendBluetooth(command); break; } timerMouse=millis(); } } } } }
true
373c4c84abec4c6322ea6ae2b8cf64f142e71868
C++
devfahad/Codeforces
/144A - Arrival of the General.cpp
UTF-8
651
2.71875
3
[]
no_license
//not completed #include<bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; int h[n+10],min=1111,max=0,c1,c2; for(int i = 0; i < n; i++){ cin >> h[i]; if(min>h[i]) min=h[i]; if(max<h[i]) max=h[i]; } //cout << min << " " << max << endl; for(int i = 0; i < n; i++){ if(max==h[i]){ c1=i; //cout << c1 << endl; break; } } for(int i = n-1; i >= 0; i--){ if(min==h[i]){ c2=n-i-1; //cout << c2 << endl; break; } } if(c1>=(n-c2-1)) cout << c1+c2-1 << endl; // here if max index >= min index,swapping will be 1 less; else cout << c1+c2 << endl; return 0; }
true
82c35551783842518f137611a939295f739016ad
C++
Tzivia-Sofer/Zoo-Polymorphism
/shark.h
UTF-8
1,672
3.0625
3
[]
no_license
#ifndef __SHARK_H__ #define __SHARK_H__ #include "seaCreation.h" class Shark:public SeaCreation{ public: Shark(std::string name): SeaCreation(name) {}; /*virtual*/ short int getSpeed() const ; /*virtual*/ std::vector <Econtinants> getContinents() const ; /*virtual*/ int getFood() const ; /*virtual*/ short int getLifeExpectancy() const ; /*virtual*/ std::string getSpecies() const ; /*virtual*/ int getLowestDepth() const ; protected: /*virtual*/ std::ostream& print(std::ostream& os) const ; private: static const short int m_speed; static const int m_lowestDepth; static const std::vector <Econtinants> m_continents; static const int m_food; static const short int m_lifeExpectancy; static const std::string m_specie; }; std::ostream& Shark::print(std::ostream& os) const { Animal::print(os); SeaCreation::print(os); os << "-----------" <<std::endl; return os; } inline short int Shark::getSpeed() const { return m_speed; } inline std::vector<Econtinants> Shark::getContinents() const { return m_continents; } inline int Shark::getFood() const { return m_food; } inline short int Shark::getLifeExpectancy() const { return m_lifeExpectancy; } inline std::string Shark::getSpecies() const { return m_specie; } inline int Shark::getLowestDepth() const { return m_lowestDepth; } const short int Shark::m_speed = 80; const int Shark::m_food = Spawn; const short int Shark::m_lifeExpectancy = 10; const std::string Shark::m_specie = "Shark"; const std::vector <Econtinants> Shark::m_continents = {Europe,America}; const int Shark::m_lowestDepth = -100; #endif
true
9c581d144b93290b00850c4df16db9a7f7f8a56b
C++
CODARcode/MGARD
/tests/src/test_CompressedDataset.cpp
UTF-8
3,829
2.71875
3
[ "Apache-2.0" ]
permissive
#include "catch2/catch_test_macros.hpp" #include <algorithm> #include <random> #include <sstream> #include "CompressedDataset.hpp" #include "compress.hpp" #include "testing_random.hpp" TEST_CASE("data buffers and sizes", "[CompressedDataset]") { { const mgard::TensorMeshHierarchy<2, float> hierarchy({6, 3}); const float s = 0.25; const float tolerance = 1.2; const std::size_t size = 11; void const *const data = new unsigned char[size]; const mgard::pb::Header header; const mgard::CompressedDataset<2, float> compressed(hierarchy, header, s, tolerance, data, size); REQUIRE(compressed.data() == data); REQUIRE(compressed.size() == size); } { const mgard::TensorMeshHierarchy<3, double> hierarchy({5, 4, 5}); const double s = -0.1; const double tolerance = 0.025; const std::size_t size = 78; double const *const u = new double[hierarchy.ndof()]; void const *const data = new unsigned char[size]; const mgard::pb::Header header; const mgard::CompressedDataset<3, double> compressed(hierarchy, header, s, tolerance, data, size); const mgard::DecompressedDataset<3, double> decompressed(compressed, u); REQUIRE(decompressed.data() == u); } } namespace { template <std::size_t N, typename Real> void test_serialization(const mgard::TensorMeshHierarchy<N, Real> &hierarchy, const Real s, const Real tolerance, std::default_random_engine &gen, const Real s_gen) { const std::size_t ndof = hierarchy.ndof(); // We wouldn't need to make two datasets if `decompress` didn't modify the // compressed buffer. Real *const u = new Real[ndof]; Real *const v = new Real[ndof]; generate_reasonable_function(hierarchy, s_gen, gen, u); std::copy(u, u + ndof, v); const mgard::CompressedDataset<N, Real> u_compressed = mgard::compress(hierarchy, u, s, tolerance); const mgard::CompressedDataset<N, Real> v_compressed = mgard::compress(hierarchy, u, s, tolerance); delete[] u; delete[] v; const mgard::DecompressedDataset<N, Real> u_decompressed = mgard::decompress(u_compressed); std::ostringstream v_ostream(std::ios_base::binary); v_compressed.write(v_ostream); const std::string v_serialization = v_ostream.str(); mgard::MemoryBuffer<const unsigned char> v_decompressed = mgard::decompress(v_serialization.c_str(), v_serialization.size()); Real const *const p = reinterpret_cast<Real const *>(u_decompressed.data()); Real const *const q = reinterpret_cast<Real const *>(v_decompressed.data.get()); REQUIRE(std::equal(p, p + ndof, q)); } } // namespace TEST_CASE("compressed dataset (de)serialization", "[CompressedDataset]") { std::default_random_engine gen(534393); { const mgard::TensorMeshHierarchy<1, float> hierarchy({381}); const float s = -1; const float tolerance = 0.01; const float s_gen = 0; test_serialization(hierarchy, s, tolerance, gen, s_gen); } { const mgard::TensorMeshHierarchy<2, double> hierarchy({72, 72}); const double s = 0.25; const double tolerance = 0.5; const double s_gen = 1; test_serialization(hierarchy, s, tolerance, gen, s_gen); } { const mgard::TensorMeshHierarchy<3, float> hierarchy({19, 31, 5}); const float s = std::numeric_limits<float>::infinity(); const float tolerance = 0.05; const float s_gen = 0.25; test_serialization(hierarchy, s, tolerance, gen, s_gen); } { const mgard::TensorMeshHierarchy<4, double> hierarchy({5, 5, 5, 7}); const double s = 0; const double tolerance = 0.0001; const double s_gen = 1.25; test_serialization(hierarchy, s, tolerance, gen, s_gen); } }
true
e35b9db42b54d83c8a65ef153d23bcd6d625b126
C++
kamrann/workbase
/code/neuroevo/common/OLD_systems/ship_and_thrusters/genetic_mappings/fixednn_sln.h
UTF-8
5,426
2.515625
3
[]
no_license
// fixednn_sln.h #ifndef __SAT_FIXED_NN_SLN_H #define __SAT_FIXED_NN_SLN_H #include "../../fixed_neural_net.h" #include <doublefann.h> #include <fann_cpp.h> #include <vector> namespace sat { template < typename System > struct fixednn_solution_base { typedef System system_t; typedef typename system_t::solution_result result_t; enum { NumNNOutputs = 4, // TODO: !!!!!!!!!!!!!!!!!!! }; inline result_t process(std::vector< double > const& nn_inputs) { double* nn_outputs = nn.run((double*)&nn_inputs[0]); result_t result(NumNNOutputs); for(size_t i = 0; i < NumNNOutputs; ++i) { result[i] = nn_outputs[i] > 0.0; } return result; } FANN::neural_net nn; }; template < typename System, typename Input > struct full_stop_fixednn_solution: public fixednn_solution_base< System > { typedef System system_t; typedef Input input_t; typedef typename system_t::dim_traits_t dim_traits_t; typedef typename system_t::solution_result result_t; enum { NumNNOutputs = 4, // TODO: !!!!!!!!! Depends on thruster config !!!!!!!!!!!!!! NumNNInputs = num_components< dim_traits_t::velocity_t >::val + num_components< dim_traits_t::angular_velocity_t >::val + num_components< dim_traits_t::orientation_t >::val, NumNNLayers = 4, NumNNHidden = (NumNNInputs + NumNNOutputs) / 2, }; full_stop_fixednn_solution() { std::vector< unsigned int > layer_neurons((size_t)NumNNLayers, (unsigned int)NumNNHidden); layer_neurons[0] = NumNNInputs; layer_neurons[NumNNLayers - 1] = NumNNOutputs; nn.create_standard_array(NumNNLayers, &layer_neurons[0]); nn.set_activation_steepness_hidden(1.0); nn.set_activation_steepness_output(1.0); nn.set_activation_function_hidden(FANN::SIGMOID_SYMMETRIC_STEPWISE); nn.set_activation_function_output(FANN::THRESHOLD); } static inline std::vector< double > map_inputs(input_t const& input) { std::vector< double > nn_inputs(NumNNInputs); std::vector< double >::iterator it = nn_inputs.begin(); get_components(input.lin_vel, it); get_components(input.ang_vel, it); get_components(input.orient, it); assert(it == nn_inputs.end()); return nn_inputs; } inline result_t operator() (input_t const& input) { return process(map_inputs(input)); } }; template < typename System, typename Input > struct angular_full_stop_fixednn_solution: public fixednn_solution_base< System > { typedef System system_t; typedef Input input_t; typedef typename system_t::dim_traits_t dim_traits_t; typedef typename system_t::solution_result result_t; enum { NumNNOutputs = 4, // TODO: !!!!!!!!! Depends on thruster config !!!!!!!!!!!!!! NumNNInputs = num_components< dim_traits_t::angular_velocity_t >::val, NumNNLayers = 3, NumNNHidden = (NumNNInputs + NumNNOutputs) / 2, }; angular_full_stop_fixednn_solution() { std::vector< unsigned int > layer_neurons((size_t)NumNNLayers, (unsigned int)NumNNHidden); layer_neurons[0] = NumNNInputs; layer_neurons[NumNNLayers - 1] = NumNNOutputs; nn.create_standard_array(NumNNLayers, &layer_neurons[0]); nn.set_activation_steepness_hidden(1.0); nn.set_activation_steepness_output(1.0); nn.set_activation_function_hidden(FANN::SIGMOID_SYMMETRIC_STEPWISE); nn.set_activation_function_output(FANN::THRESHOLD); } static inline std::vector< double > map_inputs(input_t const& input) { std::vector< double > nn_inputs(NumNNInputs); std::vector< double >::iterator it = nn_inputs.begin(); get_components(input.ang_vel, it); assert(it == nn_inputs.end()); return nn_inputs; } inline result_t operator() (input_t const& input) { return process(map_inputs(input)); } }; template < typename System, typename Input > struct target_orientation_fixednn_solution: public fixednn_solution_base< System > { typedef System system_t; typedef Input input_t; typedef typename system_t::dim_traits_t dim_traits_t; typedef typename system_t::solution_result result_t; enum { NumNNOutputs = 4, // TODO: !!!!!!!!! Depends on thruster config !!!!!!!!!!!!!! NumNNInputs = num_components< dim_traits_t::orientation_t >::val + num_components< dim_traits_t::angular_velocity_t >::val, NumNNLayers = 4, NumNNHidden = (NumNNInputs + NumNNOutputs) / 2, }; target_orientation_fixednn_solution() { std::vector< unsigned int > layer_neurons((size_t)NumNNLayers, (unsigned int)NumNNHidden); layer_neurons[0] = NumNNInputs; layer_neurons[NumNNLayers - 1] = NumNNOutputs; nn.create_standard_array(NumNNLayers, &layer_neurons[0]); nn.set_activation_steepness_hidden(1.0); nn.set_activation_steepness_output(1.0); nn.set_activation_function_hidden(FANN::SIGMOID_SYMMETRIC_STEPWISE); nn.set_activation_function_output(FANN::THRESHOLD); } static inline std::vector< double > map_inputs(input_t const& input) { std::vector< double > nn_inputs(NumNNInputs); std::vector< double >::iterator it = nn_inputs.begin(); get_components(input.orient, it); get_components(input.ang_vel, it); assert(it == nn_inputs.end()); return nn_inputs; } inline result_t operator() (input_t const& input) { return process(map_inputs(input)); } }; // template < typename System > // using fixed_nn_mapping = fixed_neural_net< System, fixednn_solution< System, > >; } #endif
true
bc653afbace3ee472dd704403c1599530b6435a8
C++
ottersome/Judge-1
/ZeroJudge/ZJ d432(Simple, Tree-traversal, Recursive).cpp
UTF-8
594
3.046875
3
[]
no_license
#include <stdio.h> #include <iostream> #include <string> using namespace std; string preorder(string in, string post) { if (in.size() <= 1) return in; int pivot, len, left, right; len = in.size(); for (pivot = 0; pivot < len; pivot++) if (in[pivot] == post[len - 1]) break; left = pivot; right = len - pivot - 1; return post[len - 1] + preorder(in.substr(0, left), post.substr(0, left)) + preorder(in.substr(pivot + 1, right), post.substr(pivot, right)); } int main() { string in, post; while (cin >> in >> post) cout << preorder(in, post) << endl; }
true
2f8e753259a5f541fa3b89efe404112e7ba95a42
C++
parisbre56/devel_part_1
/src/FilterSameTable.cpp
UTF-8
1,196
2.703125
3
[]
no_license
/* * FilterSameTable.cpp * * Created on: 9 Δεκ 2018 * Author: parisbre56 */ #include "FilterSameTable.h" using namespace std; FilterSameTable::FilterSameTable(uint32_t table, size_t col, size_t colB) : Filter(table, col), colB(colB) { } FilterSameTable::~FilterSameTable() { //Do nothing } size_t FilterSameTable::getColB() const { return colB; } bool FilterSameTable::passesFilter(const Table& table, uint64_t rownum) const { if (col == colB) { return true; //We don't have the possibility of null, so this is always true } return table.getValue(rownum, col) == table.getValue(rownum, colB); } MultipleColumnStats FilterSameTable::applyFilter(const MultipleColumnStats& stat) const { return stat.filterSame(col, colB); } Filter* FilterSameTable::mergeIfPossible(const Filter* const toMergeWith) const { //Never merge return nullptr; } void FilterSameTable::write(ostream& os) const { os << "[FilterLesser table=" << table << ", col=" << col << ", colB=" << colB << "]"; } std::ostream& operator<<(std::ostream& os, const FilterSameTable& toPrint) { toPrint.write(os); return os; }
true
1129fd20c5a0e896fa431564003b70cbddb0dae5
C++
AVBelyy/ADS-ITMO-HW
/term4/04/rainbow/checker.cpp
UTF-8
1,854
3.265625
3
[]
no_license
#include <iostream> #include <cstdio> #include <vector> const int NMAX = 100; const int MMAX = 5000; const int COLMAX = 100; struct edge_t { int u, v, col; bool operator<(edge_t other) const { return u == other.u ? v < other.v : u < other.u; } }; struct dsu_t { int rank; int parent; }; using namespace std; int n, m; dsu_t dsu[NMAX + 1]; vector<edge_t> edges; int dsu_get(int x) { if (dsu[x].parent == x) { return x; } else { return dsu[x].parent = dsu_get(dsu[x].parent); } } void dsu_union(int x, int y) { x = dsu_get(x); y = dsu_get(y); if (x != y) { if (dsu[x].rank == dsu[y].rank) { dsu[x].rank++; } if (dsu[x].rank < dsu[y].rank) { dsu[x].parent = y; } else { dsu[y].parent = x; } } } void dsu_build() { for (int i = 1; i <= n; i++) { dsu[i].rank = 0; dsu[i].parent = i; } } int main() { freopen("rainbow.in", "r", stdin); cin >> n >> m; cout << "Testing " << n << " " << m << endl; edges.resize(m + 1); for (int i = 1; i <= m; i++) { edge_t e; cin >> e.u >> e.v >> e.col; edges[i] = e; } dsu_build(); freopen("rainbow.out", "r", stdin); int k; cin >> k; vector<int> J(k); for (int i = 0; i < k; i++) { cin >> J[i]; } for (int i : J) { if (dsu_get(edges[i].u) == dsu_get(edges[i].v)) { cout << "Not a tree" << endl; return 1; } dsu_union(edges[i].u, edges[i].v); } vector<bool> used(COLMAX + 1); for (int i : J) { if (used[edges[i].col]) { cout << "Same colors" << endl; return 1; } used[edges[i].col] = true; } cout << "OK" << endl; return 0; }
true
6840959004dfb31f4af981e5c26c9687c654a551
C++
EYE657318/github-upload
/cs2400/cs2401/Project2/backup/fbfriends.cc
UTF-8
4,738
3.328125
3
[]
no_license
#include<iostream> #include<string> #include<fstream> #include "friend.h" #include "fbfriends.h" using namespace std; /////////////////////////////////////Default Constructor FBFriends::FBFriends(){ //array of five friends data = new unsigned long[5]; used = 0; capacity = 5; current_index = 0; } ///////////////////////////////////////Big Three FBFriends::~FBFriends(){ delete [] data; cout << "Get out >:(" << endl; } FBFriends::FBFriends(const FBFriends& other){ data = new unsigned long[5]; used = other.used; capacity = other.capacity; current_index = other.current_index; copy(other.data, other.data + used, data); } void FBFriends::operator = (const FBFriends& other){ if(&other == this){ return; } unsigned long *temp; temp = new unsigned long[capacity]; used = other.used; copy(other.data, other.data + used, temp); delete [] data; data = temp; } //////////////////////////////////////// sequence class allows application programmer to choose order void FBFriends::start(){ //puts iterator at beginning, 0 current_index = 0; cout << "Index set to start." << endl; } void FBFriends::advance(){ //increases iterator by 1 current_index++; cout << "The index is now set to friend #" << current_index + 1 << endl; } bool FBFriends::is_item(){ //returns true if iterator is a valid item (if it's within the used) return (current_index < used); } Friend FBFriends::current(){ //returns friend at current location return data[current_index]; } //////////////////////////////////////////////////actually editing the array void FBFriends::remove_current(){ //removes selected, pulls others back for(size_t i = 0; i < used; i++){ data[i] = data[i+1]; } used--; } void FBFriends::insert(const Friend& f){ //add to current location for(size_t i = used; i > current_index; i++){ if(used == capacity){ resize(); } data[i] = data[i - 1]; } data[current_index] = f; } void FBFriends::attach(const Friend& f){ //adds after current location? 14:00-ish in the video for(size_t i = used; i > current_index + 1; i++){ if(used == capacity){ resize(); } data[i] = data[i - 1]; } data[current_index + 1] = f; } void FBFriends::bday_sort(){ //data[i].get_bday() < data[i+1].getbday() bool finished = false; Friend temp; while(!finished){ finished = true; for(size_t i = used - 1; i > 0; i--){ Friend datai = data[i]; Friend dataiminus = data[i - 1]; if(data[i].get_bday() < data[i - 1].get_bday()){ finished = false; temp = data[i]; data[i] = data[i - 1]; data[i - 1] = temp; } } } } ////////////////////////////////////////////////////////////////////searching/printing void FBFriends::show_all(std::ostream& outs)const{ //display for(size_t i = 0; i < used; i++){ outs << data[i] << endl; } } Friend FBFriends::find_friend(const std::string& name)const{ //search for string, return the friend for(size_t i = 0; i < used; i++){ string searching = data[i].get_name(); if(searching.find(name) > 0 && searching.find(name) < string::npos){ return data[i]; } } Friend junk; return junk; } bool FBFriends::is_friend(const Friend& f) const{ //tests if they are in list for(size_t i = 0; i < used; i++){ if(data[i] == f){ return true; } } cout << "No such friend found." << endl; return false; } //////////////////////////////////////////////////////////////////////////////files void FBFriends::load(std::istream& ins){ //load le file string toName; string toMonth; string toDay; string toYear; while(!ins.eof()){ getline(ins, toName, '\n'); if(ins.peek() == '\n'){ ins.ignore(); } getline(ins, toMonth, '/'); getline(ins, toDay, '/'); getline(ins, toYear, '\n'); if(ins.peek() == '\n'){ ins.ignore(); } } } void FBFriends::save(std::ostream& outs){ //save to le file for(size_t i = 0; i < used; i++){ outs << data[i]; } } //////////////////////////////////////////////resizer void FBFriends::resize(){ //the resizer unsigned long *temp; temp = new unsigned long[capacity+5]; copy(data, data + used, temp); delete [] data; capacity += 5; data = temp; }
true
2432f0895f90778524dac4f66200f7b7dc23bcd2
C++
m-irigoyen/pages
/shared/sfmltemplate/include/sfmltemplate/gui/radiobuttongroup.hpp
UTF-8
1,596
3
3
[]
no_license
//#pragma once // //#include <sfmltemplate/hud/baseradiobutton.hpp> // //namespace sfmltemplate //{ // /* // Manages a group of radio buttons. The group does not have ownership of the buttons : they must // be deleted somewhere else in the program. // */ // class RadioButtonGroup // { // public: // RadioButtonGroup(); // ~RadioButtonGroup(); // // //! Adds button to group. Returns true if button was added, false otherwise. // //! The button must have a label unique within the group. Otherwise, it won't be added. // bool addButton(BaseRadioButton* button); // // //! Clears the group, deleting all buttons of the group // void clear(); // // //! Returns true if button is part of the group // bool contains(BaseRadioButton* button) const; // //! Returns true if there is a button with this label, and found is a pointer to this button // //! Else, returns false // bool contains(std::string label) const; // bool contains(std::string label, BaseRadioButton*& found) const; // // //! Returns the group's label // std::string getLabel() const; // // BaseRadioButton* getSelected() const; // // //! Change the currently selected button // bool changeSelected(std::string selected); // bool changeSelected(BaseRadioButton* selected); // // //! Removes button from the group. Returns true if button was removed, false otherwise. // bool removeButton(BaseRadioButton* button); // // //! Sets the group's label // void setLabel(std::string label); // // protected: // std::string label_; // std::vector<BaseRadioButton*> group_; // BaseRadioButton* selected_; // }; //}
true
27a0d9a3c20ea8ff5f4e0205d1d3645e9f62c1a7
C++
gaoming95/Algo
/DP/coin.cpp
UTF-8
1,304
3.171875
3
[]
no_license
#include<stdio.h> #include<iostream> #include<algorithm> #include<vector> using namespace std; class Solution { public: //编辑距离 int minDistance(string word1,string word2){ int m = word1.length(); int n = word2.length(); vector<vector<int>> dp(m+1,vector<int>(n+1,0)); //初始化数组 for(int i = 0;i<=m;i++){ dp[i][0] = i; } for(int j = 0;j<=n;j++){ dp[0][j] = j; } for(int i = 1;i<=m;i++){ for(int j = 1;j<=n;j++){ if(word1[i-1] == word2[j-1]){ dp[i][j] = dp[i-1][j-1]; } else{ dp[i][j] = min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]})+1; } } } return dp[m][n]; } // 硬币找零 int coinChange(vector<int>& coins, int amount) { vector<int> dp(amount+1,amount+1); dp[0] = 0; for(auto c:coins){ for(int i=c;i<=amount;i++){ dp[i] = min(dp[i-c]+1,dp[i]); } } return dp[amount] < (amount+1) ? dp[amount]:-1; } }; int main(){ string a1 = "horse"; string a2 = "ros"; Solution s; int res = s.minDistance(a1,a2); cout<<res; return 0; }
true
ed9164458b434f39535ab9e99efad7e1c3c8e07b
C++
FrankiALVarado/Programacion-II-Francisco-Alvarado
/Proyecto Parcial III/cPathFinding.cpp
ISO-8859-1
14,146
3.09375
3
[]
no_license
#include "cPathFinding.h" constexpr float pi = 3.14159265; // pi constexpr float r = 6371; //radio de la tierra en kilometros float zero = 0.0; cPathFinding::cPathFinding() { } cPathFinding::cPathFinding(std::vector<cNode> _open, std::vector<cNode> _closed, cNode _buffer) { m_open = _open; m_closed = _closed; m_buffer = _buffer; } /*std::string & cPathFinding::setInitialNodeLabel() // prompt del nodo inicial { std::string label; std::cout << "Desde que nodo quiere iniciar?" << std::endl; std::cin >> label; return label; } std::string & cPathFinding::setLastNodeLabel() // prompt del nodo final { std::string label; std::cout << "Hasta que nodo quiere buscar?" << std::endl; std::cin >> label; return label; }*/ void cPathFinding::quicksort(std::vector<cNode>& vector, int min_index, int max_index) { if (min_index < max_index) { int pivot = subarray(vector, min_index, max_index); quicksort(vector, min_index, pivot - 1); quicksort(vector, pivot + 1, max_index); } } int cPathFinding::subarray(std::vector<cNode>& vector, int & min_index, int & max_index) { double pivot = vector[max_index].getDistance(); int index = min_index - 1; for (int i = min_index; i <= max_index - 1; i++) { if (vector[i].getDistance() <= pivot) { index++; swap(vector[index], vector[i]); } } swap(vector[index + 1], vector[max_index]); return ++index; } void cPathFinding::swap(cNode & node1, cNode & node2) { m_buffer = node1; node1 = node2; node2 = m_buffer; } bool cPathFinding::isInVector(cNode & node, std::vector<cNode> vector) // funcion para checar en vectores para todos los algoritmos menos para primero mejor { for (int i = 0; i < vector.size(); i++) { if (node.getLabel() == vector[i].getLabel()) return true; } return false; } void cPathFinding::freeVector() { m_closed.clear(); m_closed.resize(0); m_closed.shrink_to_fit(); m_open.clear(); m_open.resize(0); m_open.shrink_to_fit(); } void cPathFinding::winnerRoute(std::vector<cNode>& nodes, cNode & last) { for (int i = 0; i < nodes.size(); i++) { if (nodes[i].getIATACode() == last.getIATACode()) { printRoute(nodes[i]); break; } } } void cPathFinding::printRoute(cNode & node) { if (node.getPointer() != nullptr) { std::cout << std::endl; std::cout << "ruta ganadora: " << std::endl; printRoute(*node.getPointer()); } node.printNodePM(); std::cout << "\n"; } void cPathFinding::printClosed() { for (int i = 0; i < m_closed.size(); i++) { m_closed[i].printLabel(); } } void cPathFinding::pushBackFirstNode(cNode & node) { m_open.push_back(node); } void cDepthFirstSearch::pathFind(int & counter, cNode & lastLabel, bool & arrive, std::vector<cEdge> & edges) { while (m_open.size() > 0) { int max = m_open.size() - 1; if (m_open[max].getLabel() == lastLabel.getLabel()) { m_closed[counter] = m_open[max]; arrive = true; break; } else{ if (!isInVector(m_open[max], m_closed)) { std::cout << "agregando a cerrados: " << m_open[max].getLabel() << std::endl; m_closed[counter] = m_open[max]; // si el nodo actual no est en el vector de cerrados, lo agrega. std::cout << "lista de nodos cerrados " << std::endl; for (int i = 0; i < m_closed.size(); i++) { m_closed[i].printLabel(); } std::cout << std::endl; counter++; std::cout << "numero de nodos recorridos: " << counter << std::endl; for (int i = 0; i < edges.size(); i++) { // ciclo para agregar a abiertos a los que apunta if (m_open[max].getLabel() == edges[i].getFirstNodeLabel()) { // si el actual y un nodo i tienen la misma etiqueta m_buffer = edges[i].getSecondNode(); if (!isInVector(m_buffer, m_closed)) { // si el nodo al que apunta no est en cerrados, lo pone en abiertos std::cout << "agregando a abiertos: " << m_buffer.getLabel() << std::endl; m_open.push_back(m_buffer); //agregar a abiertos todos los nodos que apunta. } } } } m_open.erase(m_open.begin() + max); } } } cDepthFirstSearch::~cDepthFirstSearch() { freeVector(); } void cBreadthFirstSearch::pathFind(int & counter, cNode & lastLabel, bool & arrive, std::vector<cEdge>& edge) { while (m_open.size() > 0) { if (m_open[0].getLabel() == lastLabel.getLabel()) { m_closed[counter] = m_open[0]; arrive = true; break; } else { if (!isInVector(m_open[0], m_closed)) { std::cout << "agregando a cerrados: " << m_open[0].getLabel() << std::endl; m_closed[counter] = m_open[0]; // si el nodo actual no est en el vector de cerrados, lo agrega. std::cout << "lista de nodos cerrados " << std::endl; for (int i = 0; i < m_closed.size(); i++) { m_closed[i].printLabel(); } std::cout << std::endl; counter++; std::cout << "numero de nodos recorridos: " << counter << std::endl; for (int i = 0; i < edge.size(); i++) { // ciclo para agregar a abiertos a los que apunta if (m_open[0].getLabel() == edge[i].getFirstNodeLabel()) { // si el actual y un nodo i tienen la misma etiqueta m_buffer = edge[i].getSecondNode(); if (!isInVector(m_buffer, m_closed)) { // si el nodo al que apunta no est en cerrados, lo pone en abiertos std::cout << "agregando a abiertos: " << m_buffer.getLabel() << std::endl; m_open.push_back(m_buffer); //agregar a abiertos todos los nodos que apunta. } } } } m_open.erase(m_open.begin()); } } } cBreadthFirstSearch::~cBreadthFirstSearch() { freeVector(); } void cBestFirst::pathFind(int & counter, cNode & lastLabel, bool & arriv, std::vector<cEdge>& edges) { while(m_open.size() > 0) { std::cout << "nodopm actual: " << std::endl; m_open[0].printNodePM(); if (!isInVector(m_open[0], m_closed)) { // si este nodo est en cerrados m_closed[counter] = m_open[0]; counter++; for (int j = 0; j < edges.size(); j++) { // ciclo para ir agregando a abiertos if (m_open[0].getIATACode() == edges[j].getFirstNodeIATACode() && m_open[0].getLabel() != lastLabel.getLabel()) { if (m_closed[counter].getLabel() == lastLabel.getLabel()) { // si el nodo al que apunta es el mismo que el que buscamos arriv = true; } if (m_open[0].getLabel2() != edges[j].getSecondNodeLabel()) { // si es diferente de donde viene, para los casos de bidireccionalidad m_buffer = edges[j].getSecondNode(); // le damos informacion al buffer para un pushback m_buffer.setDistance(0); // reset de la distancia como es por referencia el buffer sigue sumando a no ser que se regrese a 0 m_buffer.setDistance(edges[j].getWeight(), m_open[0].getDistance()); // le va sumando la distancia recorrida; m_buffer.setPointer(m_closed[counter - 1]); // le da un puntero de donde viene que es el mismo nodopm actual if (!isInVector(m_buffer, m_closed)) { //si este nodo el nodo que se va a abrir no se ha evaluado anteriormente std::cout << "agregando a abiertos: " << std::endl; m_buffer.printNodePM(); m_open.push_back(m_buffer); } } } } m_open.erase(m_open.begin()); // eliminar el nodo que ya analizamos if (m_open.size() > 1) { quicksort(m_open, 0, m_open.size() - 1); // quicksort } } else { // si el nodo ya se ha evaluado solo lo cerramos m_closed[counter] = m_open[0]; counter++; m_open.erase(m_open.begin()); } } winnerRoute(m_closed, lastLabel); } bool cBestFirst::isInVector(cNode & node, std::vector<cNode>& vector) { for (int i = 0; i < vector.size(); i++) { if (vector[i].getIATACode() == node.getIATACode()) { return true; } if (vector[i].getLabel() == "") { // este ciclo solo lo lleva cerrados que en sus primeras iteraciones va a tener string vacio return false; } } return false; } cBestFirst::~cBestFirst() { freeVector(); } void cDijkstra::Radians(cNode & node) { node.setCoordX((node.getCoordX() * pi) / 180); node.setCoordY((node.getCoordY() * pi) / 180); } float & cDijkstra::haversine(cNode & node1, cNode & node2) { Radians(node1); Radians(node2); float x1 = sin((node2.getCoordY() - node1.getCoordY()) / 2); x1 *= x1; // seno cuadrado de la diferencia de latitudes sobre dos float x2 = cos(node1.getCoordY()) * cos(node2.getCoordY()); float x3 = sin((node2.getCoordX() - node1.getCoordX()) / 2); // seno cuadrado de la diferencia de sus longitudes sobre dos x3 *= x3; float a = x1 + (x2 * x3); float c = asin(sqrt(a)); float d = (2 * r) * c; return d; } void cDijkstra::lessTravel(cNode & actual, std::vector<cNode> vector) { for (int i = 0; i < vector.size(); i++) { if (vector[i].getLabel() == actual.getLabel()) { if (actual.getDistance() < vector[i].getDistance()) vector[i] = actual; } } } void cDijkstra::pathFind(int & counter, cNode & lastLabel, bool & arriv, std::vector<cEdge>& edges) { while (m_open.size() > 0) { if (arriv) { break; } if (!isInVector(m_open[0], m_closed)) { // si el nodopm actual no se encuentra en cerrados std::cout << "agregando a cerrados: " << std::endl; m_open[0].printNodePM(); std::cout << std::endl; m_closed[counter] = m_open[0]; for (int i = 0; i < edges.size(); i++) { // ciclo que checa todas las aristas if (m_open[0].getLabel() == edges[i].getFirstNodeLabel()) { // si sus etiquetas son iguales if (edges[i].getSecondNodeLabel() == lastLabel.getLabel()) { arriv = true; } m_buffer = edges[i].getSecondNode(); // le da un valor a su nodo, al que apunta m_buffer.setDistance(0); m_buffer.setDistance(edges[i].getWeight(), m_closed[counter].getDistance()); m_buffer.setPointer(m_closed[counter]); // le da un puntero de donde viene que es el mismo nodopm actual dentro del vector if (!isInVector(m_buffer, m_closed)) { // si dicho nodo ya se encuentra cerrado no lo va a agregar a abiertos if (isInVector(m_buffer, m_open)) { // si no se encuentra en abiertos lo aade directamente a cerrados, si no analiza si tiene una distancia menor lessTravel(m_buffer, m_open); } else { std::cout << "agregando a abiertos: " << std::endl; m_buffer.printNodePM(); std::cout << std::endl; m_open.push_back(m_buffer); } } } } counter++; // crecimiento de nodos para la posible siguiente recursin m_open.erase(m_open.begin()); quicksort(m_open, 0, m_open.size() - 1); // ordenamiento por quicksort del vector de abiertos } else { // si llega a estar dentro del vector, checar que abiertos no est vacio para realizar siguientes recursiones m_open.erase(m_open.begin()); } } if (arriv) { std::cout << std::endl << "Recorrido exitoso" << std::endl; std::cout << "Recorrido: " << std::endl; winnerRoute(m_closed, lastLabel); } else { std::cout << std::endl << "El recorrido no se pudo completar, no existe tal nodo" << std::endl; } } cDijkstra::~cDijkstra() { freeVector(); } void caStar::Radians(cNode & node) // funcion que convierte las coordenadas de un nodo a radianes { node.setCoordX((node.getCoordX() * pi) / 180); node.setCoordY((node.getCoordY() * pi) / 180); } float & caStar::haversine(cNode & node1, cNode & node2) { Radians(node1); Radians(node2); float x1 = sin((node2.getCoordY() - node1.getCoordY()) / 2); x1 *= x1; // seno cuadrado de la diferencia de latitudes sobre dos float x2 = cos(node1.getCoordY()) * cos(node2.getCoordY()); float x3 = sin((node2.getCoordX() - node1.getCoordX()) / 2); // seno cuadrado de la diferencia de sus longitudes sobre dos x3 *= x3; float a = x1 + (x2 * x3); float c = asin(sqrt(a)); float d = (2 * r) * c; return d; } void caStar::lessTravel(cNode & actual, std::vector<cNode> vector) { for (int i = 0; i < vector.size(); i++) { if (vector[i].getLabel() == actual.getLabel()) { if (actual.getDistance() < vector[i].getDistance()) vector[i] = actual; } } } void caStar::pathFind(int & counter, cNode & lastLabel, bool & arriv, std::vector<cEdge>& edges) { while (m_open.size() > 0) { if (!isInVector(m_open[0], m_closed)) { // si el nodopm actual no se encuentra en cerrados std::cout << "agregando a cerrados: " << std::endl; m_open[0].printNodePM(); std::cout << std::endl; m_closed[counter] = m_open[0]; for (int i = 0; i < edges.size(); i++) { // ciclo que checa todas las aristas if (m_open[0].getLabel() == edges[i].getFirstNodeLabel()) { // si sus etiquetas son iguales if (m_closed[counter].getLabel() == lastLabel.getLabel()) { arriv = true; break; } m_buffer = edges[i].getSecondNode(); // le da un valor a su nodo, al que apunta m_buffer.setDistance(0); float d = haversine(m_buffer, lastLabel); m_buffer.setDistance(edges[i].getWeight(), d); m_buffer.setDistance(m_buffer.getDistance(), m_closed[counter].getDistance()); m_buffer.setPointer(m_closed[counter]); // le da un puntero de donde viene que es el mismo nodopm actual dentro del vector if (!isInVector(m_buffer, m_closed)) { // si dicho nodo ya se encuentra cerrado no lo va a agregar a abiertos if (!isInVector(m_buffer, m_open)) { // si no se encuentra en abiertos lo aade directamente a cerrados, si no analiza si tiene una distancia menor std::cout << "agregando a abiertos: " << std::endl; m_buffer.printNodePM(); std::cout << std::endl; m_open.push_back(m_buffer); } } } } counter++; // crecimiento de nodos para la posible siguiente recursin m_open.erase(m_open.begin()); quicksort(m_open, 0, m_open.size() - 1); // ordenamiento por quicksort del vector de abiertos } else { // si llega a estar dentro del vector, checar que abiertos no est vacio para realizar siguientes recursiones m_open.erase(m_open.begin()); } } if (arriv) { std::cout << std::endl << "Recorrido exitoso" << std::endl; std::cout << "Recorrido: " << std::endl; winnerRoute(m_closed, lastLabel); } else { std::cout << std::endl << "El recorrido no se pudo completar, no existe tal nodo" << std::endl; } } caStar::~caStar() { freeVector(); }
true
d847caca3b347d09bedda43e8937f77d7e0609b7
C++
lzhudson/Lista-de-Exercicios-C-
/Lista de Exercicios 2 C++/questao5.cpp
WINDOWS-1252
263
2.828125
3
[]
no_license
#include <stdio.h> int main(){ int n,m,soma,multi,sub,divi; n = 20; m = 40; soma = n + m; multi = n*m; sub = n-m; divi = n/m; printf("A soma %d, a multiplicacao %d, a subtracao %d, a divisao %d",soma,multi,sub,divi); }
true
e2557b9c3a28520592dba386c94cd98bad026591
C++
ChrSacher/MyEngine
/AudioListener.h
UTF-8
3,840
2.703125
3
[ "Apache-2.0" ]
permissive
#pragma once #include "Camera3d.h" #include "Audio.h" #include "ServiceLocator.h" class Camera3d; class AudioListener : Camera3d::Listener { public: public: /** * Gets the single instance of the audio listener. * * @return The single instance of the audio listener. */ static AudioListener* getInstance(); /** * Gets the current position of the audio listener. * * @return The position of the audio listener */ const Vector3& getPosition() const; /** * Sets the position of the audio source. * * @param position The position to set the listener to. */ void setPosition(const Vector3& position); /** * Sets the position of the audio source. * * @param x The x coordinate of the position. * @param y The y coordinate of the position. * @param z The z coordinate of the position. */ void setPosition(float x, float y, float z); /** * Returns the gain of the audio listener. * * @return The gain of the audio listener. */ float getVolume() const; /** * Sets the gain/volume of the audio listener. * * @param gain The gain/volume of the listener. */ void setVolume(float gain); /** * Gets the velocity of the audio source. * * @return The velocity as a vector. */ const Vector3& getVelocity() const; /** * Sets the velocity of the audio source * * @param velocity A vector representing the velocity. */ void setVelocity(const Vector3& velocity); /** * Sets the velocity of the audio source * * @param x The x coordinate of the velocity. * @param y The y coordinate of the velocity. * @param z The z coordinate of the velocity. */ void setVelocity(float x, float y, float z); /** * Gets the forward orientation vector of the audio listener. * * @return The forward vector. */ const Vector3& getOrientationForward() const; /** * Gets the up orientation vector of the audio listener. * * @return The up vector. */ const Vector3& getOrientationUp() const; /** * Sets the orientation of the audio listener. * * @param forward The forward vector. * @param up The up vector. */ void setOrientation(const Vector3& forward, const Vector3& up); /** * Sets the orientation of the audio listener. * Vector3(forwardX,forwardY,forwardZ). * @param forwardX The x coordinate of the forward vector. * @param forwardY The y coordinate of the forward vector. * @param forwardZ The z coordinate of the forward vector. */ void setDir(const Vector3 &Dir); /** * Sets the orientation of the audio listener. * * Vector3(upX,upY,upZ) * @param upX The x coordinate of the up vector. * @param upY The y coordinate of the up vector. * @param upZ The z coordinate of the up vector. */ void setUP(const Vector3 &Up); /** * Gets the camera currently associated with the audio listener. * * @return camera The camera currently associated with the audio listener. */ Camera3d* getCamera() const; /** * Sets the camera that is associated with the audio listener. This should usually be the current camera. * * @param camera The camera that is associated with the audio listener */ void setCamera(Camera3d* camera); private: /** * Constructor. */ AudioListener(); /** * Destructor. */ ~AudioListener(); /** * @see Camera::Listener::cameraChanged */ void cameraChanged(Camera3d* camera); float _volume; Vector3 _position; Vector3 _velocity; Vector3 _up; Vector3 _dir; Camera3d* _camera; };
true
092a277cfce848be25f2ce80121978aeb17cdcfe
C++
DrabbyPage/EGP-410
/GameAI/pathfinding/game/AStar.cpp
UTF-8
6,308
2.75
3
[]
no_license
#include "AStar.h" #include "Path.h" #include "Connection.h" #include "GridGraph.h" #include "Game.h" #include <PerformanceTracker.h> #include <list> #include <vector> #include <algorithm> #include "GridPathfinder.h" #include "Heuristic.h" AStarPath::AStarPath(Graph* pGraph) : GridPathfinder(dynamic_cast<GridGraph*>(pGraph)) { #ifdef VISUALIZE_PATH mpPath = NULL; #endif } AStarPath::~AStarPath() { #ifdef VISUALIZE_PATH delete mpPath; #endif } Path* AStarPath::findPath(Node* start, Node* end) { //make sure to delete the path when you are done! #ifdef VISUALIZE_PATH if (mpPath != NULL) { delete mpPath; mVisitedNodes.clear(); } #endif Heuristic* heur = new Heuristic(end); // initialize the record for the start node StarNodeRecord startRecord = StarNodeRecord(); startRecord.node = start; startRecord.recordConnection = nullptr; startRecord.costSoFar = 0; startRecord.estiTotalCost = heur->estimate(start); // initialize the open and closed list std::vector<StarNodeRecord> openList; std::vector<StarNodeRecord> closedList; openList.push_back(startRecord); StarNodeRecord current; //iterate through processing each node while (openList.size() > 0) { //find the smallest element in the open list current = openList.front(); // if it is the goal node then terminate if (current.node == end) { break; } // otherwise get its outgoing connections else { // connections= graph.getConnections(current) std::vector<Connection*> connections; connections = mpGraph->getConnections(current.node->getId()); // loop through each connection in turn for (unsigned int i = 0; i < connections.size(); i++) { // get the cost estimate for the end node Node* endNode = connections[i]->getToNode(); float endNodeCost = current.costSoFar + connections[i]->getCost(); StarNodeRecord endNodeRecord; float endNodeHeuristic; bool inClosedList = false; bool inOpenList = false; // if the node is closed we may have to skip or remove it from the close list for (auto nodeRecord = closedList.begin(); nodeRecord != closedList.end(); nodeRecord++) { // here we find the record in the closed list corresponding to the end node if (nodeRecord->node == endNode) { inClosedList = true; endNodeRecord.node = nodeRecord->node; } // if we didnt find a shorter route, skip if (endNodeRecord.costSoFar <= endNodeCost) { // continue; continue; } // otherwise remove it from the closed list; else { closedList.erase(nodeRecord); // we can use the node's old cost values to calculate its heuristic without // calling the possibly expensive heuristic function endNodeHeuristic = endNodeRecord.estiTotalCost - endNodeRecord.costSoFar; } } if (!inClosedList) { // skip if the node is open and we've not found a better route for (auto record = openList.begin(); record != openList.end(); record++) { if (record->node == endNode) { inOpenList = true; // here we find the record in the open list corresponding to the endNode endNodeRecord.node = record->node; // if our route is no better, then skip if (endNodeRecord.costSoFar <= endNodeCost) { // continue continue; } else { // we can use the node's old cost values to calculate its heuristic without // calling the possibly expensive heuristic function endNodeHeuristic = endNodeRecord.recordConnection->getCost() - endNodeRecord.costSoFar; } break; } } } // otherwise we know we've got an unvisited node so make a record for it if (!inClosedList && !inOpenList) { endNodeRecord = StarNodeRecord(); endNodeRecord.node = endNode; // we'll need to calculate the heuristic value using the function, since // we dont have an existing record to use endNodeHeuristic = heur->estimate(endNode); // we're here if we need to update the node // update the cost, estimate, and connection endNodeRecord.costSoFar = endNodeCost; endNodeRecord.recordConnection = connections[i]; endNodeRecord.estiTotalCost = endNodeCost + endNodeHeuristic; } // and add it to the openList if (!inClosedList) { bool inOpen = false; for (auto record = openList.begin(); record < openList.end(); record++) { if (record->node == endNodeRecord.node) { inOpen = true; break; } } if (!inOpen) { openList.push_back(endNodeRecord); } } } // we've finished looking at the connections for the current node so add it to the closed // list and remove it from the open list openList.erase(openList.begin()); closedList.push_back(current); mVisitedNodes.push_back(current.node); } } // we're here if we found a goal or if we have no more nodes to search find which one if(current.node != end) { // we've run out of nodes without finding the goal, so theres no solution // return none std::cout << "did not end on goal node" << std::endl; return nullptr; } // else: else { // compile the list of connections in the path Path* a_Star_Path = new Path(); // work back along the path, accumulating connections while(current.node != start) { // path+= current.connection // current = current.connection.getFromNode() // FYI Update the current's connection as well a_Star_Path->addNode(current.node); current.node = current.recordConnection->getFromNode(); for (auto node = closedList.begin(); node < closedList.end(); node++) { if (node->node == current.node) { current.recordConnection = node->recordConnection; } } } // reverse the path, and return it Path* reversePath = new Path(); for (int i = 0; i < a_Star_Path->getNumNodes(); i++) { Node* newNode; int lastNodeIndex; lastNodeIndex = a_Star_Path->getNumNodes() - (i + 1); newNode = a_Star_Path->peekNode(lastNodeIndex); reversePath->addNode(newNode); } #ifdef VISUALIZE_PATH mpPath = reversePath; #endif delete heur; delete a_Star_Path; // return reverse path return reversePath; } }
true
98dc8e04086376365460fef016cfccc251ef199a
C++
simonadel/simo012
/inher1/src/Derived.cpp
UTF-8
512
3
3
[]
no_license
#include <iostream> #include "Derived.h" using namespace std; Derived::Derived() { w=0; cout<<"Default Constructor derived"<<endl; } Derived::Derived(int w) { w=w; cout<<"One Parameter derived"<<endl; } Derived:: Derived(int w,int x,int y):Base(x,y){ w=w; } void Derived::setW(int w){ w=w; } int Derived:: getW() { return w; } int Derived:: sum() { return(w+Base ::sum()); } Derived::~Derived() { //dtor }
true
0a7e4dfae3266816163c1a3e4a0583a38137ea7f
C++
ethz-asl/ouster_lidar
/ouster_client/include/ouster/os1.h
UTF-8
5,317
2.734375
3
[ "BSD-3-Clause" ]
permissive
/** * @file * @brief OS-1 sample client */ #pragma once #include <cstdint> #include <memory> #include <string> #include <vector> namespace ouster { namespace OS1 { const size_t lidar_packet_bytes = 12608; const size_t imu_packet_bytes = 48; struct client; enum client_state { TIMEOUT = 0, ERROR = 1, LIDAR_DATA = 2, IMU_DATA = 4, EXIT = 8 }; enum class lidar_mode { MODE_512x10 = 1, MODE_512x20, MODE_1024x10, MODE_1024x20, MODE_2048x10, MODE_INVALID }; struct version { int16_t major; int16_t minor; int16_t patch; }; const version invalid_version = {0, 0, 0}; /** * Minimum supported version */ const OS1::version min_version = {1, 9, 0}; inline bool operator==(const version& u, const version& v) { return u.major == v.major && u.minor == v.minor && u.patch == v.patch; } inline bool operator<(const version& u, const version& v) { return (u.major < v.major) || (u.major == v.major && u.minor < v.minor) || (u.major == v.major && u.minor == v.minor && u.patch < v.patch); } inline bool operator<=(const version& u, const version& v) { return u < v || u == v; } struct sensor_info { std::string hostname; std::string sn; std::string fw_rev; lidar_mode mode; std::vector<double> beam_azimuth_angles; std::vector<double> beam_altitude_angles; std::vector<double> imu_to_sensor_transform; std::vector<double> lidar_to_sensor_transform; }; /** * Get string representation of a version * @param version * @return string representation of the version */ std::string to_string(version v); /** * Get lidar mode from string * @param string * @return lidar mode corresponding to the string, or invalid_version on error */ version version_of_string(const std::string& s); /** * Get string representation of a lidar mode * @param lidar_mode * @return string representation of the lidar mode, or "UNKNOWN" */ std::string to_string(lidar_mode mode); /** * Get lidar mode from string * @param string * @return lidar mode corresponding to the string, or 0 on error */ lidar_mode lidar_mode_of_string(const std::string& s); /** * Get number of columns in a scan for a lidar mode * @param lidar_mode * @return number of columns per rotation for the mode */ int n_cols_of_lidar_mode(lidar_mode mode); /** * Listen for OS1 data on the specified ports * @param lidar_port port on which the sensor will send lidar data * @param imu_port port on which the sensor will send imu data * @return pointer owning the resources associated with the connection */ std::shared_ptr<client> init_client(int lidar_port = 7502, int imu_port = 7503); /** * Connect to and configure the sensor and start listening for data * @param hostname hostname or ip of the sensor * @param udp_dest_host hostname or ip where the sensor should send data * @param lidar_port port on which the sensor will send lidar data * @param imu_port port on which the sensor will send imu data * @return pointer owning the resources associated with the connection */ std::shared_ptr<client> init_client(const std::string& hostname, const std::string& udp_dest_host, lidar_mode mode = lidar_mode::MODE_1024x10, const uint16_t lidar_port = 7502u, const uint16_t imu_port = 7503u); /** * Block for up to timeout_sec until either data is ready or an error occurs. * @param cli client returned by init_client associated with the connection * @param timeout_sec seconds to block while waiting for data * @return client_state s where (s & ERROR) is true if an error occured, (s & * LIDAR_DATA) is true if lidar data is ready to read, and (s & IMU_DATA) is * true if imu data is ready to read */ client_state poll_client(const client& cli, int timeout_sec = 1); /** * Read lidar data from the sensor. Will not block. * @param cli client returned by init_client associated with the connection * @param buf buffer to which to write lidar data. Must be at least * lidar_packet_bytes + 1 bytes * @return true if a lidar packet was successfully read */ bool read_lidar_packet(const client& cli, uint8_t* buf); /** * Read imu data from the sensor. Will not block. * @param cli client returned by init_client associated with the connection * @param buf buffer to which to write imu data. Must be at least * imu_packet_bytes + 1 bytes * @return true if an imu packet was successfully read */ bool read_imu_packet(const client& cli, uint8_t* buf); /** * Get metadata text blob from the sensor * @param cli client returned by init_client associated with the connection * @return a text blob of metadata parseable into a sensor_info struct */ std::string get_metadata(const client& cli); /** * Parse metadata text blob from the sensor into a sensor_info struct. String * and vector fields will have size 0 if the parameter cannot be found or * parsed, * while lidar_mode will be set to 0 (invalid). * @throw runtime_error if the text is not valid json * @param metadata a text blob returned by get_metadata above * @return a sensor_info struct populated with a subset of the metadata */ sensor_info parse_metadata(const std::string& metadata); } }
true
31b42cd5b36441c73ffbc524bb4b528dc61fae08
C++
nimamg/Business-social-network
/database.cpp
UTF-8
4,559
2.890625
3
[]
no_license
#include "database.hpp" Database::Database () { } void Database::addUser (std::string firstName, std::string lastName, std::string emailAddress, std::string biography) { if (findUser(emailAddress) == NOTFOUND) { User newUser(firstName,lastName,emailAddress,biography); userList.push_back(newUser); } } void Database::addCompany (std::string name, std::string address, std::string description) { if (findCompany(name) == NOTFOUND) { Company newCompany(name,address,description); companyList.push_back(newCompany); } } void Database::addExperience(std::string userId, std::string companyId, std::string title, std::string startAt , std::string endsAt) { if (findCompany(companyId) != NOTFOUND && companyList[findCompany(companyId)].isJobRepeated(title) == false && findUser(userId) != NOTFOUND) { userList[findUser(userId)].addExperience(companyId, title, startAt, endsAt); companyList[findCompany(companyId)].addJob(userList[findUser(userId)].getFullName(), title, startAt, endsAt); } } void Database::addExperienceByBestApp(std::string userId, std::string companyId, std::string title, std::string startAt , std::string endsAt) { userList[findUser(userId)].addExperience(companyId, title, startAt, endsAt); companyList[findCompany(companyId)].addJob(userList[findUser(userId)].getFullName(), title, startAt, endsAt); } void Database::addJobRequest(std::string companyName, std::string title, std::map<std::string, float> conditions) { if (findCompany(companyName) != NOTFOUND) { companyList[findCompany(companyName)].addJobRequest (title, conditions); } } void Database::assignSkill(std::string userId, std::string skillName) { if (findUser(userId) != NOTFOUND) userList[findUser(userId)].assignSkill(skillName); } void Database::endorseSkill(std::string endorserUserId, std::string skilledUserId, std::string skillName) { if (findUser(endorserUserId) != NOTFOUND && findUser(skilledUserId) != NOTFOUND) { userList[findUser(skilledUserId)].endorseSkill(userList[findUser(endorserUserId)].getID(),userList[findUser(endorserUserId)].calculateEndorseScore(skillName) , skillName); } } void Database::follow(std::string followerId, std::string followingId) { if (findUser(followingId) != NOTFOUND && findUser(followerId) != NOTFOUND && followingId != followerId) { userList[findUser(followingId)].addFollower(followerId); userList[findUser(followerId)].addFollower(followingId); } } void Database::applyForJob(std::string userId, std::string companyId, std::string jobTitle) { if (findUser(userId) != NOTFOUND && findCompany(companyId) != NOTFOUND) { companyList[findCompany(companyId)].addApplicant(userList[findUser(userId)], jobTitle); } } void Database::hireBestApplicant(std::string companyId, std::string jobTitle, std::string startsAt) { if (findCompany(companyId) != NOTFOUND) { std::string bestApplicantID = companyList[findCompany(companyId)].hireBestApplicant(jobTitle); if (bestApplicantID != NOJOBREQ && bestApplicantID != NOAPPLICANT) { addExperienceByBestApp(bestApplicantID, companyId, jobTitle, startsAt); } } } void Database::printUserProfile(std::string userId) { if (findUser(userId) != NOTFOUND) { userList[findUser(userId)].printProfile(); std::cout << std::endl; } } void Database::printCompanyProfile(std::string companyName) { if (findCompany(companyName) != NOTFOUND) { companyList[findCompany(companyName)].printCompanyProfile(); std::cout << std::endl; } } void Database::printSuggestedJobs(std::string userId) { int counter = 1; User user = userList[findUser(userId)]; for (int i = 0 ; i < companyList.size() ; i++){ std::vector<JobRequest> suggestedJobs = companyList[i].getSuggestedJobs(user); for (int j = 0 ; j < suggestedJobs.size() ; j++) { std::cout << counter << DOT << SPACE; suggestedJobs[j].printJobReq(companyList[i].getID()); counter++; } } } void Database::printSuggestedUsers(std::string companyName, std::string jobTitle) { int counter = 1; for (int i = 0 ; i < userList.size() ; i++) if (companyList[findCompany(companyName)].isUserQualified (userList[i], jobTitle)) { std::cout << counter << DOT << std::endl; userList[i].printProfile(); std::cout << std::endl; counter++; } } int Database::findCompany (std::string ID) { for (int i = 0 ; i < companyList.size() ; i++) if (companyList[i].getID() == ID) return i; return NOTFOUND; } int Database::findUser (std::string ID) { for (int i = 0 ; i < userList.size() ; i++) if (userList[i].getID() == ID) return i; return NOTFOUND; }
true
a1bda4ddbce6abd698a91465d67d3534ec9adbf9
C++
vincatzero/AFT2
/main.cpp
UTF-8
1,621
3.125
3
[]
no_license
/* Project: NAME OF PROJECT GOES HERE Name: YOUR NAME GOES HERE Partner: PARTNER'S NAME IF ANY Class: example: CSC 1810 - Section 1 */ #include <iostream> #include "Gene.h" #include "GeneSequencer.h" #include "Chromosome.h" #include "Allele.h" using namespace std; void runMenu() { GeneSequencer GeneSequencers; string UserOption; string userFile; Chromosome newChromosome; while (UserOption != "6") { cout << endl << " * MENU *" << endl << endl << "1 - Create Chromosome" << endl << "2 - Analyze Chromosome" << endl << "3 - Output Chromosome to File" << endl << "4 - Input Chromosome from File" << endl << "5 - Combine Chromosomes" << endl << "6 - Exit" << endl << endl << "Please Enter your Choice (1-6): "; getline(cin, UserOption); cout << endl; while ((UserOption > "6") || (UserOption < "1") || (UserOption.length() > 1)) { cout << "Please enter a valid choice: "; getline(cin, UserOption); } int userChoice = stoi(UserOption); switch (userChoice) { case 1: newChromosome = GeneSequencers.CreateChromosome(); break; case 2: newChromosome.AnalyzeGenotype(); break; case 3: break; case 4: cout << "Enter the file would you like to import from:" << endl; getline(cin, userFile); newChromosome = GeneSequencers.ImportChromosome(userFile); break; case 5: break; case 6: break; } } }; int main(int argc, char *argv[]) { runMenu(); // This causes the program to pause at its completion. { char c; cout << "Hit enter to exit:"; cin.get(c); } return 0; }
true
443633a79ed2eabcb434079a7d1f7017b7dda38a
C++
plusminus34/Interactive_thin_shells_Bachelor_thesis
/Apps/Plush/CubicHermiteSpline_v2.cpp
UTF-8
3,717
2.5625
3
[]
no_license
#include "CubicHermiteSpline_v2.h" CubicHermiteSpline_v2::CubicHermiteSpline_v2(const dVector &X, const dVector &S) { if (X.size() > S.size()) { error("ArgumentOrderError"); } if ((!IS_EQUAL(X[0], S[0])) || (!IS_EQUAL(X[X.size() - 1], S[S.size() - 1]))) { error("Knot and data ranges don't meet at the ends."); } this->X = X; this->S = S; populate_KT(); } void CubicHermiteSpline_v2::draw(const dVector &Y, const dVector &M) { glMasterPush(); { glTranslated(0., 0., .33); // -- set_color(SPEC_COLOR); glPointSize(5.); glBegin(GL_POINTS); { glvecP3D(zip_vec_dVector2vecP3D({ X, Y })); } glEnd(); // -- glLineWidth(2.); glPointSize(2.); for (auto &GL_PRIMITIVE : { GL_LINE_STRIP, GL_POINTS }) { glBegin(GL_PRIMITIVE); { glvecP3D(zip_vec_dVector2vecP3D({ S, calculate_U(Y, M) })); } glEnd(); } } glMasterPop(); } void CubicHermiteSpline_v2::populate_KT() { K.clear(); vector<double> T_vec; for (int i = 0; i < S.size(); ++i) { auto kt = calculate_kt(S[i]); int &k = kt.first; double &t = kt.second; // -- K.push_back(k); T_vec.push_back(t);; } T = vecDouble2dVector(T_vec); } pair<int, double> CubicHermiteSpline_v2::calculate_kt(const double &s) { int k = -1; double t = 0.; { if ((s < X[0]) || (s > X[X.size() - 1])) { error("[t_of_x] : IOError"); } for (int i = 0; i < X_SIZE() - 1; ++i) { int ip1 = i + 1; // -- double &xi = X[i]; double &xip1 = X[ip1]; if ((s >= xi) && (s <= xip1)) { k = i; t = interval_fraction(s, xi, xip1); return make_pair(k, t); } } } error("Failed to find kt."); return make_pair(k, t); } dVector CubicHermiteSpline_v2::calculate_U(const dVector &Y, const dVector &M) { dVector U; U.setZero(S_SIZE()); for (int i = 0; i < U.size(); ++i) { int &k = K[i]; double &t = T[i]; // -- double dx = X[k + 1] - X[k]; // -- U[i] = h00(t)*Y[k] + h10(t)*dx*M[k] + h01(t)*Y[k + 1] + h11(t)*dx*M[k + 1]; } return U; } SparseMatrix CubicHermiteSpline_v2::calculate_dUdY_() { vector<MTriplet> triplets; SparseMatrix dUdY_; dUdY_.resize(S_SIZE(), X_SIZE()); for (int i = 0; i < dUdY_.rows(); ++i) { // U[i] int &k = K[i]; double &t = T[i]; triplets.push_back(MTriplet(i, k, h00(t))); triplets.push_back(MTriplet(i, k + 1, h01(t))); } dUdY_.setFromTriplets(triplets.begin(), triplets.end()); return dUdY_; } SparseMatrix CubicHermiteSpline_v2::calculate_dUdM_() { vector<MTriplet> triplets; SparseMatrix dUdY_; dUdY_.resize(S_SIZE(), X_SIZE()); for (int i = 0; i < dUdY_.rows(); ++i) { // U[i] int &k = K[i]; double &t = T[i]; // -- double dx = X[k + 1] - X[k]; // -- triplets.push_back(MTriplet(i, k, h10(t)*dx)); triplets.push_back(MTriplet(i, k + 1, h11(t)*dx)); } dUdY_.setFromTriplets(triplets.begin(), triplets.end()); return dUdY_; } // TODO: calculate_dUDM // TODO: calculate_dUDYM // NOTE: Should just stack bool CubicHermiteSpline_v2::checkJacobian(const dVector &Y, const dVector &M) { auto &U_wrapper = [this](const dVector &YM) {return calculate_U(YM.head(S_SIZE()), YM.tail(S_SIZE())); }; return matrix_equality_check(mat_FD(stack_vec_dVector({ Y, M }), U_wrapper), calculate_dUdY_().toDense()); } dVector CubicHermiteSpline_v2::randY() { dVector Y; Y.setZero(X_SIZE()); for (int k = 0; k < Y.size(); ++k) { Y[k] = .33*random_double(); } return Y; } dVector CubicHermiteSpline_v2::CFD_M(dVector &Y) { dVector M; M.setZero(S_SIZE()); auto F = [&](const int &k) { return (Y[k] - Y[k - 1]) / (X[k] - X[k - 1]); }; for (int k = 0; k < X_SIZE(); ++k) { if (k == 0) { M[k] = F(k + 1); } else if (k == X_SIZE() - 1) { M[k] = F(k); } else { M[k] = .5*(F(k + 1) + F(k)); } } return M; }
true
b8f4488ab592a205519f5812122819f6e942a682
C++
zsq001/oi-code
/8.4/test/0804test/source/牛彦哲/b/b.cpp
UTF-8
885
2.578125
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #define min(a,b) a<b?a:b #define max(a,b) a>b?a:b #define minn -0x7fffffff int color[4000010],n,m,p,q; void change(int l,int r,int x,int y,int v,int k) { if(l>y||r<x) { return; } if(l>=x&&r<=y) { color[k]=v; return; } color[k]=-1; int mid=(l+r)/2; change(l,mid,x,y,v,k*2); change(mid+1,r,x,y,v,k*2+1); } int ask(int l,int r,int num,int k) { if(l>num||r<num) { return minn; } if(color[k]!=-1) { return color[k]; } int mid=(l+r)/2; return max(ask(l,mid,num,k*2),ask(mid+1,r,num,k*2+1)); } int main() { freopen("b.in","r",stdin); freopen("b.out","w",stdout); scanf("%d%d%d%d",&n,&m,&p,&q); int a,b,i; for(i=1;i<=m;i++) { a=(i*p+q)%n+1; b=(i*q+p)%n+1; change(1,n,min(a,b),max(a,b),i,1); } for(i=1;i<=n;i++) { printf("%d\n",ask(1,n,i,1)); } return 0; }
true
887ebbe361e8e6d14aeb9d5477a1991fe7ee3f50
C++
MOXCOOT/PlaneShootBall
/ai_pve.cpp
UTF-8
22,439
2.9375
3
[]
no_license
#include"DataStruct.h" #include "math.h" #include "plane.h" #include <ctime> #include <cstdlib> #include <iostream> #include <windows.h> #include <QDebug> #define SIGN(x) ((x < 0 ) ? 1 : 0 ) #define Pai 3.1415926 //角度坐标系转换 inline double angleConver(double angle) { return -90 - angle; } //抽取向量点乘 inline double PointMul(double x0, double y0, double x1, double y1) { return x0 * x1 + y0 * y1; } //抽取向量取模 inline double vecMod(double x, double y) { return sqrt(x * x + y * y); } /* * 找到最容易射中的球 */ int FindBall(DataStruct *data){ for(int i=data->ball_size - 1;i>=0;i--) { //求得飞机与球之间的直线方程 double px=data->plane1.x; double py=data->plane1.y; double bx=data->ball[i].x; double by=data->ball[i].y; double kb=(py-by)/(px-bx); double kp=angleConver(data->plane1.angle); if(kb > kp && data->ball[i].v_x >0 || kb<kp &&data->ball[i].v_x<0) return i; } float vm=0; int num; for(int i=0;i<data->ball_size;i++) { float vx=data->ball->v_x; float vy=data->ball->v_y; float v=vecMod(vx,vy); if(v>vm) { vm=v; num=i; } } return num; } /* * 同时躲避两个球 */ int Hideball(DataStruct *data, BallStruct &ball,KeyStruct*key) { //获取当前球的坐标和速度 float ball_x = ball.x, ball_y = ball.y, ball_v_x = ball.v_x, ball_v_y = ball.v_y; float ballx=data->ball->x; float bally=data->ball->y; for(int i=0;i<data->ball_size;i++) { if(data->ball[i].r<10) { continue; } else { key->shoot=true; if(key->shield) { int w=data->ball_size-1; return w; } } float vx=data->ball[i].v_x; float vy=data->ball[i].v_y; return vecMod(vx,vy); } for(int x=0;x<10;x++) { int a=FindBall(data); if(a) { if(data->ball[a].r<10) { continue; } else { key->shoot=true; if(key->shield) { int w=data->ball_size-1; return w; } } float vx=data->ball[a].v_x; float vy=data->ball[a].v_y; } } } /* * 瞄准某个球 * 参数:data:游戏数据,ball_x、ball_y:球当前位置,ball_v_x、ball_v_y:球当前速度,leftward、rightward:返回动作 * 返回值:0:瞄准成功,-1:瞄准失败 */ int ShootBall(DataStruct *data, BallStruct &ball, int &leftward, int &rightward) { float ball_x = ball.x, ball_y = ball.y, ball_v_x = ball.v_x, ball_v_y = ball.v_y; //瞄准的角度 double angleTo, angleDiff; //球运动方向和飞机与球位置向量的夹角余弦 double cosPosV; //两向量点乘除以两向量的模 cosPosV = PointMul(ball_v_x, ball_v_y, data->plane1.x - ball_x, data->plane1.y - ball_y) / vecMod(ball_v_x, ball_v_y) / vecMod(data->plane1.x - ball_x, data->plane1.y - ball_y); //根据正弦定理(a/sinA=b/sinB)求出sin值再求得所需度数 angleTo = angleConver( //BETA (asin(sqrt(1 - cosPosV * cosPosV) * vecMod(ball_v_x, ball_v_y) / 2000) //ALPHA + atan2(ball_y - data->plane1.y, ball_x - data->plane1.x)) * 180 / Pai); //计算飞机朝向与该角度之差 angleDiff = fmod(fmod(data->plane1.angle - angleTo, 360) + 360, 360); //根据角度差选择更优旋转方向 if (angleDiff < 3.6 || angleDiff > 356.4) { return 0; } else if (angleDiff < 180 ) { leftward = false; rightward = true; return -1; } else { leftward = true; rightward = false; return 1; } return 0; } int HideBall(DataStruct *data, BallStruct &ball, int &leftward, int &rightward) { float des_x,des_y,cross_x,cross_y,ball_y; float ball_v_x,ball_v_y; data->ball->x=des_x; data->ball->y=des_y; des_y=data->plane1.y; if(ball_v_x*ball_v_y>0) { des_y=data->plane1.y; if(ball_y>cross_y) { des_x+=data->ball->r+data->plane1.r; } else { des_x-=data->ball->r+data->plane1.r; } } else { des_y=data->plane1.y; if(ball_y>cross_y) { des_x-=data->ball->r+data->plane1.r; } else { des_x+=data->ball->r+data->plane1.r; } } } /* * 预测飞机位置 * 参数:data:游戏数据,x、y:返回位置,time:给定时间 * 返回值:0:预测成功,-1:预测失败 */ int AftPlanePos(DataStruct *data, int time, float &x, float &y) { double v_x0, v_y0, v_x1, v_y1, a_x, a_y; //获取初速度 v_x0 = data->plane1.v_x; v_y0 = data->plane1.v_y; //无速度则无需预测 if (v_x0 == 0 && v_y0 == 0) { x = data->plane1.x; y = data->plane1.y; return 0; } //计算加速度 a_x = -v_x0 / vecMod(v_x0, v_y0) * 4000; a_y = -v_y0 / vecMod(v_x0, v_y0) * 4000; //计算末速度 v_x1 = v_x0 + a_x * time / 100; if (SIGN(v_x1) != SIGN(v_x0)) { v_x1 = 0; } v_y1 = v_y0 + a_y * time / 100; if (SIGN(v_y1) != SIGN(v_y0)) { v_y1 = 0; } //计算位置 x = data->plane1.x + (v_x1 * v_x1 - v_x0 * v_x0) / 2 / a_x; y = data->plane1.y + (v_y1 * v_y1 - v_y0 * v_y0) / 2 / a_y; return 0; } /* * 转向某点 * 参数:data:游戏数据,x、y:目标点,leftward、rightward:返回动作 * 返回值:0:正在转向,1:完成转向,-1:转向失败 */ int turnAt(DataStruct *data, float x, float y, int &leftward, int &rightward) { //飞机到目的地的角度 double angleTo, angleDiff; //计算飞机到目的地的角度并改变坐标系 angleTo = angleConver(atan2(y - data->plane1.y, x - data->plane1.x) * 180 / Pai); //计算飞机朝向与该角度之差 angleDiff = fmod(fmod(data->plane1.angle - angleTo, 360) + 360, 360); //根据角度差选择更优旋转方向 if (angleDiff < 3.6 || angleDiff > 356.4) { return 1; } else if (angleDiff < 180) { leftward = false; rightward = true; } else { leftward = true; rightward = false; } return 0; } /* * 移动至某点 * 参数:data:游戏数据,x、y:目标点,forward、leftward、rightward:返回动作 * 返回值:0:正在移动,1:完成移动,-1:移动失败 */ int moveAt(DataStruct *data, float x, float y, int &forward, int &leftward, int &rightward, int precision = 1) { //计算当前点到终点距离 double dis = vecMod(y - data->plane1.y, x - data->plane1.x); //已到达目标点则终止动作 if (dis < precision) { return 1; } //预测飞机位置 float pre_x, pre_y; AftPlanePos(data, 1000, pre_x, pre_y); //正在转向则不加速 if (!turnAt(data, data->plane1.x + x - pre_x, data->plane1.y + y - pre_y, leftward, rightward)) { forward = false; return 0; } dis = vecMod(y - pre_x, x - pre_y); //停下时未到达目标点 if (dis >= precision) { forward = true; leftward = false; rightward = false; } return 0; } void move(time_t lastFetch,time_t fetch) { //飞机在xy方向的速度位移正负量,角度的正负量 double v_x_plus=0; double v_x_minus=0; double x_plus=0; double x_minus=0; double v_y_plus=0; double v_y_minus=0; double y_plus=0; double y_minus=0; double v_y_slowDown=0; double y_slownDown=0; double angle_plus=0; double angle_minus=0; } void resetKeyPressed() { double a[10]; for(int i=RAND_MAX;i>=0;i--) { a[i]=false; } return ; } /* * 判断是否需要移动 * 参数:data:游戏数据、des_x:目标点横坐标、des_y:目标点纵坐标 * 返回值:0:无需移动,1:需要移动 */ int needmove(DataStruct *data, float &des_x, float &des_y, KeyStruct*key,int preTime = 200) { float min_t = INT_MAX; //预测每一个球的移动 for (int i = 0; i < data->ball_size; i++) { //获取当前球的引用 BallStruct &ball = data->ball[i]; //获取当前球的坐标和速度 float ball_x = ball.x, ball_y = ball.y, ball_v_x = ball.v_x, ball_v_y = ball.v_y; float v=vecMod(ball_v_x,ball_v_y); // qDebug() <<v; //补充 //计算出2.5s后球的位置 double ball_x_aft = ball_x + ball_v_x * 500; double ball_y_aft = ball_y + ball_v_y * 500; int rectflagxup = 0; int rectflagxbo = 0; int rectflagyri = 0; int rectflagyle = 0; int rect = 0; if(ball_y_aft < 0 ) rectflagxup = 1; if(ball_x_aft < 0 ) rectflagyle= 1; if(ball_y_aft > 1500 )rectflagxbo = 1; if(ball_x_aft > 2000 )rectflagyri = 1; float a; float b; float c; //计算球运动直线方程 float A, B, C; A = -1; //Y前的系数 B = ball_v_y / ball_v_x; //X前的系数 C = ball_y - ball_x * ball_v_y / ball_v_x; //常数项 int k =0; //x向下越界 if(rectflagxbo) { rect =1; float a = A; float b = -B; float c = -C + 3000 - 2 * data->ball->r; } //x方向向上越界 if(rectflagxup) { rect = 1; float a = A; float b = -B; float c = -C; } //y向左越界 if(rectflagyle) { rect = 1; float a = A; float b = -B; float c =C + 4000 * B; } //y向右越界 if(rectflagyri) { rect = 1; float a = A; float b = -B; float c = C; } stop1: if(k) { if(rectflagxup) { ball_x = (A*data->ball->r - C) / B; ball_y = data->ball->r; ball_v_y = - ball_v_y; } if(rectflagyle) { ball_x = ball.r; ball_y = (B*ball.r + C) / A; ball_x = -ball_v_x; } if(rectflagyri) { ball_x = 2000 - ball.r; ball_y = C + (2000 - data->ball->r) * B; ball_v_x = -ball_v_x; } if(rectflagxbo) { ball_y = 1500 - data->ball->r; ball_x = (1500 - data->ball->r - C) / B; ball_v_y = - ball_v_y; } } //计算飞机到直线距离 float dis = fabs((A * data->plane1.y + B * data->plane1.x + C) / vecMod(A, B)); //计算垂点坐标 float cross_x = (data->plane1.y - ball_y + ball_v_y / ball_v_x * ball_x + ball_v_x / ball_v_y * data->plane1.x) / (ball_v_x / ball_v_y + ball_v_y / ball_v_x); float cross_y = (ball_v_y / ball_v_x) * (cross_x - ball_x) + ball_y; //计算到垂点的时间 float t = (cross_x - ball_x) / ball_v_x * 100; // if(k) { // t-=30; // qDebug() <<t; // goto stop2; // } //反向运动或时间过久则忽略该球 if (t < 0 || t > preTime) { continue; } stop2: // if(t < aftmin_t) aftmin_t = t; //判断该球是否有威胁 if (dis < data->plane1.r + ball.r + 10 && t < min_t) { //设置最紧迫威胁 min_t = t; if(ball_v_y > 0) { des_y = data->plane1.y - ball.r * qAbs(data->plane1.y - cross_y) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); if(des_y < 50) { des_y = data->plane1.y + ball.r * qAbs(data->plane1.y - cross_y) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); } } else { des_y = data->plane1.y + ball.r * qAbs(data->plane1.y - cross_y) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); if(des_y > 1400) { des_y = data->plane1.y - ball.r * qAbs(data->plane1.y - cross_y) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); } } if(ball_v_x > 0) { des_x = data->plane1.x + ball.r * qAbs(data->plane1.x - cross_x) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); if(des_x > 1400) { des_x = data->plane1.x - ball.r * qAbs(data->plane1.x - cross_x) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); } } else { des_x = data->plane1.x - ball.r * qAbs(data->plane1.x - cross_x) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); if(des_x < 100) { des_x = data->plane1.x + ball.r * qAbs(data->plane1.x - cross_x) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); } } if(key->shield) { if(ball_v_x>0) { des_x+=3 * data->ball->r+data->plane1.r; } else { des_x-=3 * data->ball->r+data->plane1.r; } // des_y=data->plane1.y; // if(ball_v_x*ball_v_y>0) // { // des_y=data->plane1.y; // if(ball_y>cross_y) // { // des_x+=data->ball->r+data->plane1.r; // } // else // { // des_x-=data->ball->r+data->plane1.r; // } // } // else // { // des_y=data->plane1.y; // if(ball_y>cross_y) // { // des_x-=data->ball->r+data->plane1.r; // } // else // { // des_x+=data->ball->r+data->plane1.r; // } // } } // if (des_x < data->plane1.r || des_x > 1500 - data->plane1.r) // { // des_x = data->plane1.x; // if (data->plane1.y - cross_y > 0) // des_y = cross_y + ball.r + data->plane1.r; // else // des_y = cross_y - ball.r - data->plane1.r; // } // //如果y越界 // if (des_y < data->plane1.r || des_y > 1500 - data->plane1.r) // { // des_y = data->plane1.y; // if (data->plane1.x - cross_x > 0) // des_x = cross_x + ball.r + data->plane1.r; // else // des_x = cross_x - ball.r - data->plane1.r; // } // //向相反方向移动球半径的距离 // des_x = data->plane1.x + ball.r * qAbs(data->plane1.x - cross_x) // / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); // des_y = data->plane1.y + ball.r * qAbs(data->plane1.y - cross_y) // / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); // //如果x越界 // if (des_x < data->plane1.r || des_x > 1500 - data->plane1.r) // { // des_x = data->plane1.x; // if (data->plane1.y - cross_y > 0) // des_y = cross_y + ball.r + data->plane1.r; // else // des_y = cross_y - ball.r - data->plane1.r; // } // //如果y越界 // if (des_y < data->plane1.r || des_y > 1500 - data->plane1.r) // { // des_y = data->plane1.y; // if (data->plane1.x - cross_x > 0) // des_x = cross_x + ball.r + data->plane1.r; // else // des_x = cross_x - ball.r - data->plane1.r; // } } if(!rect)continue; else{ rect = 0; A = a; B = b; C = c; k = 1; goto stop1; } } for(int i=0;i<data->bullet2_size;i++) { BulletStruct &bullet=data->bullet2[i]; float bullet_v_x=bullet.v_x,bullet_v_y=bullet_v_y,bullet_x=bullet.x,bullet_y=bullet.y; //计算子弹运动直线方程 float A, B, C; A = -1; //Y前的系数 B = bullet_v_y / bullet_v_x; //X前的系数 C = bullet_y - bullet_x * bullet_v_y / bullet_v_x; //常数项 //计算飞机到直线距离 float dis = fabs((A * data->plane1.y + B * data->plane1.x + C) / vecMod(A, B)); //计算垂点坐标 float cross_x = (data->plane1.y - bullet_y + bullet_v_y / bullet_v_x * bullet_x + bullet_v_x / bullet_v_y * data->plane1.x) / (bullet_v_x / bullet_v_y + bullet_v_y / bullet_v_x); float cross_y = (bullet_v_y / bullet_v_x) * (cross_x - bullet_x) + bullet_y; //计算到垂点的时间 float t = (cross_x - bullet_x) / bullet_v_x * 100; //反向运动或时间过久则忽略该球 if (t < 0 || t > preTime) { continue; } //判断该子弹是否有威胁 if (dis < data->plane1.r + bullet.r + 5 && t < min_t) { //设置最紧迫威胁 min_t = t; if(bullet_v_y > 0) { des_y = data->plane1.y - qAbs(data->plane1.y - cross_y) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); if(des_y < 50) { des_y = data->plane1.y + bullet.r * qAbs(data->plane1.y - cross_y) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); } } else { des_y = data->plane1.y + bullet.r * qAbs(data->plane1.y - cross_y) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); if(des_y > 1400) { des_y = data->plane1.y - bullet.r * qAbs(data->plane1.y - cross_y) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); } } if(bullet_v_x > 0) { des_x = data->plane1.x + bullet.r * qAbs(data->plane1.x - cross_x) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); if(des_x > 1900) { des_x = data->plane1.x - bullet.r * qAbs(data->plane1.x - cross_x) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); } } else { des_x = data->plane1.x - bullet.r * qAbs(data->plane1.x - cross_x) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); if(des_x < 50) { des_x = data->plane1.x + bullet.r * qAbs(data->plane1.x - cross_x) / vecMod(data->plane1.x - cross_x, data->plane1.y - cross_y); } } } } if (min_t != INT_MAX) { return 1; } //给定时间内无危险 return 0; } void ai_pve(DataStruct*data,KeyStruct*key){ //默认不移动且恒发射子弹 key->forward = false; key->rotate_left = false; key->rotate_right = false; key->shoot = true; static int cnt = 0; for(int i=0;i<data->ball_size;i++) { if(qAbs(data->ball->x - data->plane1.x) < 200 && qAbs(data->ball->y - data->plane1.y) < 300) cnt++; } if(cnt >= 3) { cnt = 0; key->shield = true; } else { key->shield = false; } //创建静态移动标志 static float moveFlag = 1, des_x, des_y; //标志为0则正在移动或检查发现需要移动 if (needmove(data, des_x, des_y,key) || moveFlag == 0) { //进行移动并返回移动结果 moveFlag = moveAt(data, des_x, des_y, key->forward, key->rotate_left, key->rotate_right); //返回标志为-1则发生错误 if (moveFlag == -1) { std::cout << "移动发生错误" << std::endl; } //结束函数执行 return; } //如果球个数不为零 if (data->ball_size) { ShootBall(data, data->ball[FindBall(data)], key->rotate_left, key->rotate_right); } }
true
597db77cd160136d1c16cb84f3ee5de39eacebc9
C++
mnmz81/Smart-pointer-And-move-semantics
/Edge.h
UTF-8
1,199
3.0625
3
[]
no_license
#ifndef CLION_EDGE_H #define CLION_EDGE_H #include <iostream> #include "Vertex.h" #include "Shipping.h" #include <memory> #include <vector> class Vertex; //this class is Edge in the Graph using namespace std; class Edge { string from; shared_ptr<Vertex> dest; int weightBoxs; double weightTime; vector<Shipping> allShiping; public: friend class Graph; friend class Vertex; //ctor and dtor Edge(shared_ptr<Vertex>& d,Shipping& temp); Edge(const Edge& temp); Edge(Edge&& temp); //getter and setter string getFom(){return from;}; vector<Shipping> getAllShiping(){return allShiping;}; int getWeightBoxs(){return weightBoxs;}; string getDest(); double getWeightTime(){return allShiping.size()==0 ? 0:(weightTime/allShiping.size());}; //fun void upDateShipping(Shipping& newShiping); //operator Edge& operator=(const Edge& rhs); Edge& operator=(Edge&& rhs); friend bool operator==(const Edge& lhs,const Edge& rhs); friend bool operator==(const Edge& lhs,const string& rhs); friend ostream& operator<<(ostream& out,const Edge& temp); }; #endif //CLION_EDGE_H
true
53af35a8a944a5db213383b945d61d74c6624b66
C++
NikolaTotev/Object-Oriented-Programing-Course
/Exam_2_Back_Up/Exma_2/Exam_2_Back_Up_Proj/OnlineService.h
UTF-8
1,244
3.125
3
[]
no_license
#pragma once #include <iostream> class OnlineService { int port; int numberOfConnectedDevices; int maxNumberOfDevices; public: OnlineService(); OnlineService(int _maxDevices, int port =0, int numberOfConnDevices = 0); bool operator==(const OnlineService& rhs); ~OnlineService(); void setNewPort(int newPort) { port = newPort; } int getPort() { return port; } //======================================================== int number_of_connected_devices() const { return numberOfConnectedDevices; } void set_number_of_connected_devices(int number_of_connected_devices) { numberOfConnectedDevices = number_of_connected_devices; } //======================================================== int max_number_of_devices() const { return maxNumberOfDevices; } void set_max_number_of_devices(int max_number_of_devices) { maxNumberOfDevices = max_number_of_devices; } //======================================================== void plugInDevice() { if(numberOfConnectedDevices!= maxNumberOfDevices) { std::cout << "Device connected successfully" << std::endl; return; } std::cout << "Failed to connect device" << std::endl; } void turnOffDevice() { numberOfConnectedDevices--; } };
true
bdb734371ffbe1758a02eaabc1225a8b4730df7d
C++
xfmeng17/leetcode
/cpp/1019.cpp
UTF-8
1,261
3.390625
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector<int> nextLargerNodes(ListNode *head) { // return func1(head); return func2(head); } // ** straight forward O(N^2) vector<int> func1(ListNode *head) { vector<int> res; while (head) { int larger = 0; ListNode *next = head->next; while (next) { if (next->val > head->val) { larger = next->val; break; } else { next = next->next; } } res.push_back(larger); head = head->next; } return res; } vector<int> func2(ListNode *head) { // int N = 0; // ListNode* temp = head; // while (temp) { // N++; // temp = temp->next; // } // vector<int> res(N, 0); vector<int> res; stack<ListNode *> stk; stack<int> idx; int cnt = 0; while (head) { res.push_back(0); while (!stk.empty() && head->val > stk.top()->val) { res[idx.top()] = head->val; stk.pop(); idx.pop(); } stk.push(head); idx.push(cnt++); head = head->next; } return res; } };
true
0c784690b757ee9a4abb327a9b6beba62f443f67
C++
shfranc/abstract_vm
/incs/Int8.hpp
UTF-8
860
2.84375
3
[]
no_license
#ifndef INT8_HPP # define INT8_HPP # include "Token.hpp" # include "IOperand.hpp" class Int8 : public IOperand { public: Int8( eOperandType type, std::string value ); virtual ~Int8( void ); virtual int getPrecision( void ) const; virtual eOperandType getType( void ) const; virtual std::string const & toString( void ) const; // virtual IOperand const * operator+( IOperand const & rhs ) const; // virtual IOperand const * operator-( IOperand const & rhs ) const; // virtual IOperand const * operator*( IOperand const & rhs ) const; // virtual IOperand const * operator/( IOperand const & rhs ) const; // virtual IOperand const * operator%( IOperand const & rhs ) const; private: eOperandType _type; int _precision; std::string _value; Int8( void ); Int8( Int8 const & src ); Int8 & operator=( Int8 const & rhs ); }; #endif
true
92227e772bb20865ed9d8e546a2756c3c8de17c7
C++
kahavi/PokerikasiVaiEi
/deckofcards.cpp
UTF-8
912
3.734375
4
[]
no_license
#include "deckofcards.h" DeckOfCards::DeckOfCards() { //Generate the deck string faces[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}; string suits[] = {"Hearts", "Diamonds", "Clubs", "Spades"}; for(int i = 0; i < NUMBER_OF_CARDS; i++) { deck[i] = Card(suits[i / 13], faces[i % 13]); } //Shuffle the deck of cards this->shuffle(); } DeckOfCards::~DeckOfCards(){} //Returns a card at index value of cardIndex Card DeckOfCards::draw() { Card cardToDraw = deck[cardIndex]; cardIndex++; //if we reach the end of the deck, shuffle if(cardIndex >= NUMBER_OF_CARDS) this->shuffle(); return cardToDraw; } //Shuffle the deck void DeckOfCards::shuffle() { //Change the random seed so we don't get the same deck every time srand(time(0)); random_shuffle(std::begin(deck), std::end(deck)); cardIndex = 0; }
true
b24503b97c88331ed5237a1b88ca968f2b0ee7a8
C++
federicoorsili/C-plus-plus
/cpp05/ex03/Intern.cpp
UTF-8
2,025
2.734375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Intern.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: forsili <forsili@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/04 18:36:15 by forsili #+# #+# */ /* Updated: 2021/05/10 18:00:51 by forsili ### ########.fr */ /* */ /* ************************************************************************** */ #include "Intern.hpp" Intern::Intern(void) { names[0] = "shrubbery request"; names[1] = "robotomy request"; names[2] = "pardon request"; funcptr[0] = Intern::newShrubbery; funcptr[1] = Intern::newRobotomy; funcptr[2] = Intern::newPardon; } Intern::Intern(const Intern& src) { (void)src; } Intern::~Intern(void) {} Intern& Intern::operator=(const Intern& src) { (void)src; return *this; } Form* Intern::newShrubbery(std::string _target) { return new ShrubberyCreationForm(_target); } Form* Intern::newRobotomy(std::string _target) { return new RobotomyRequestForm(_target); } Form* Intern::newPardon(std::string _target) { return new PresidentialPardonForm(_target); } Form* Intern::makeForm(std::string _form, std::string _target) { for (size_t i = 0; i < 3; i++) { if (!_form.compare(names[i])) { std::cout << "Intern creates " << _form << " target: " << _target << std::endl; return this->funcptr[i](_target); } } throw Intern::NotFoundException(); } Intern::NotFoundException::NotFoundException() {} const char* Intern::NotFoundException::what() const throw() { return ("Exception: Form not found!"); }
true
d7193e368a7b6e7356e211ade3aef127e3e82a28
C++
marcusbfs/AletasFT
/code/include/GeratrizesTask.hpp
UTF-8
13,354
2.875
3
[]
no_license
#ifndef GERATRIZES_TASK_HPP #define GERATRIZES_TASK_HPP #include "Aletas.hpp" #include "AletaTask.hpp" #include "FunDer.hpp" // ========== Altere aqui! ========== // F(z) = D/2 class GeratrizA : public AletaTaskInput { // Returns F(z) virtual double F(const double& z) { return .5 * ft_D; } // Returns dF(z)/dz virtual double dFdz(const double& z) { return 0.0; } // Returns dAs(z)/dz virtual double dAsdz(const double& z) { // As = PI * D * z return PI * ft_D; } // Return ID virtual std::string ID() { return "A"; } }; // F(z) = a + b*z class GeratrizB : public AletaTaskInput { // Par�metros!! (se houver) double a = ft_D / 2.0; double b = ft_D / (2 * ft_L); // Returns F(z) virtual double F(const double& z) { return a + b * z; } // Returns dF(z)/dz virtual double dFdz(const double& z) { return b; } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2.0 * PI * std::sqrt(1.0 + std::pow(b, 2)) * (a + b * z); //} // Return ID virtual std::string ID() { return "B"; } }; // F(z) = a - b*z class GeratrizC : public AletaTaskInput { // Par�metros!! (se houver) double a = ft_D / 2.0; double b = ft_D / (2 * ft_L); // Returns F(z) virtual double F(const double& z) { return a - b * z; } // Returns dF(z)/dz virtual double dFdz(const double& z) { return -b; } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2.0 * PI * std::sqrt(1.0 + std::pow(b, 2)) * (a - b * z); //} // Return ID virtual std::string ID() { return "C"; } }; // F(z) = a + b*z*z class GeratrizD : public AletaTaskInput { // Par�metros!! (se houver) double a = ft_D / 2.0; double b = (1.0 / 2.0) * ft_D / std::pow(ft_L, 2); // Returns F(z) virtual double F(const double& z) { return a + b * std::pow(z, 2); } // Returns dF(z)/dz virtual double dFdz(const double& z) { return 2 * b * z; } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2 * M_PI * (2 * a * std::pow(b, 2) * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a * std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) - 4 * std::pow(b, 5) * std::pow(z, 6) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) + 5 * std::pow(b, 3) * std::pow(z, 4) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) - 3.0 / 2.0 * std::pow(b, 3) * std::pow(z, 4) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) + (9.0 / 8.0) * b * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) - 1.0 / 8.0 * b * std::pow(z, 2) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0)); //} // Return ID virtual std::string ID() { return "D"; } }; // F(z) = a - b*z*z class GeratrizE : public AletaTaskInput { // Par�metros!! (se houver) double a = ft_D / 2.0; double b = a/(ft_L*ft_L); // Returns F(z) virtual double F(const double& z) { return a - b * std::pow(z, 2); } // Returns dF(z)/dz virtual double dFdz(const double& z) { return -2 * b * z; } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2 * M_PI * (2 * a * std::pow(b, 2) * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a * std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + 4 * std::pow(b, 5) * std::pow(z, 6) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 5 * std::pow(b, 3) * std::pow(z, 4) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (3.0 / 2.0) * std::pow(b, 3) * std::pow(z, 4) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 9.0 / 8.0 * b * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 8.0) * b * std::pow(z, 2) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0)); //} // Return ID virtual std::string ID() { return "E"; } }; // F(z) = a + b*z*z*z class GeratrizF : public AletaTaskInput { // Par�metros!! (se houver) double a = ft_D / 2.0; double b = (1.0 / 2.0) * ft_D / std::pow(ft_L, 3); // Returns F(z) virtual double F(const double& z) { return a + b * std::pow(z, 3); } // Returns dF(z)/dz virtual double dFdz(const double& z) { return 3 * b * std::pow(z, 2); } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2 * M_PI * (2 * a * std::pow(b, 2) * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a * std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + 4 * std::pow(b, 5) * std::pow(z, 6) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 5 * std::pow(b, 3) * std::pow(z, 4) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (3.0 / 2.0) * std::pow(b, 3) * std::pow(z, 4) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 9.0 / 8.0 * b * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 8.0) * b * std::pow(z, 2) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0)); //} // Return ID virtual std::string ID() { return "F"; } }; // F(z) = a - b*z*z*z class GeratrizG : public AletaTaskInput { // Par�metros!! (se houver) double a = ft_D / 2.0; double b = (1.0 / 2.0) * ft_D / std::pow(ft_L, 3); // Returns F(z) virtual double F(const double& z) { return a - b * std::pow(z, 3); } // Returns dF(z)/dz virtual double dFdz(const double& z) { return -3 * b * std::pow(z, 2); } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2 * M_PI * (2 * a * std::pow(b, 2) * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a * std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + 4 * std::pow(b, 5) * std::pow(z, 6) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 5 * std::pow(b, 3) * std::pow(z, 4) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (3.0 / 2.0) * std::pow(b, 3) * std::pow(z, 4) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 9.0 / 8.0 * b * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 8.0) * b * std::pow(z, 2) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0)); //} // Return ID virtual std::string ID() { return "G"; } }; // F(z) = a + b*sin(z) class GeratrizH : public AletaTaskInput { // Par�metros!! (se houver) double a = ft_D / 2.0; double b = (1.0 / 2.0) * ft_D / std::sin(ft_L); // Returns F(z) virtual double F(const double& z) { return a + b * std::sin(z); } // Returns dF(z)/dz virtual double dFdz(const double& z) { return b * std::cos(z); } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2 * M_PI * (2 * a * std::pow(b, 2) * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a * std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + 4 * std::pow(b, 5) * std::pow(z, 6) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 5 * std::pow(b, 3) * std::pow(z, 4) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (3.0 / 2.0) * std::pow(b, 3) * std::pow(z, 4) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 9.0 / 8.0 * b * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 8.0) * b * std::pow(z, 2) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0)); //} // Return ID virtual std::string ID() { return "H"; } }; // F(z) = a - b*sin(z) class GeratrizI : public AletaTaskInput { // Par�metros!! (se houver) double a = ft_D / 2.0; double b = (1.0 / 2.0) * ft_D / std::sin(ft_L); // Returns F(z) virtual double F(const double& z) { return a - b * std::sin(z); } // Returns dF(z)/dz virtual double dFdz(const double& z) { return -b * std::cos(z); } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2 * M_PI * (2 * a * std::pow(b, 2) * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a * std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + 4 * std::pow(b, 5) * std::pow(z, 6) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 5 * std::pow(b, 3) * std::pow(z, 4) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (3.0 / 2.0) * std::pow(b, 3) * std::pow(z, 4) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 9.0 / 8.0 * b * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 8.0) * b * std::pow(z, 2) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0)); //} // Return ID virtual std::string ID() { return "I"; } }; // F(z) = a + b*cosh(z) class GeratrizJ : public AletaTaskInput { // Par�metros!! (se houver) double a = (1.0 / 2.0) * ft_D * (std::cosh(ft_L) - 2) / (std::cosh(ft_L) - 1); double b = (1.0 / 2.0) * ft_D / (std::cosh(ft_L) - 1); // Returns F(z) virtual double F(const double& z) { return a + b * std::cosh(z); } // Returns dF(z)/dz virtual double dFdz(const double& z) { return b * std::sinh(z); } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2 * M_PI * (2 * a * std::pow(b, 2) * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a * std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + 4 * std::pow(b, 5) * std::pow(z, 6) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 5 * std::pow(b, 3) * std::pow(z, 4) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (3.0 / 2.0) * std::pow(b, 3) * std::pow(z, 4) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 9.0 / 8.0 * b * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 8.0) * b * std::pow(z, 2) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0)); //} // Return ID virtual std::string ID() { return "J"; } }; // F(z) = a - b*cosh(z) class GeratrizK : public AletaTaskInput { // Par�metros!! (se houver) double a = (1.0 / 2.0) * ft_D * std::cosh(ft_L) / (std::cosh(ft_L) - 1); double b = (1.0 / 2.0)* ft_D / (std::cosh(ft_L) - 1); // Returns F(z) virtual double F(const double& z) { return a - b * std::cosh(z); } // Returns dF(z)/dz virtual double dFdz(const double& z) { return - b * std::sinh(z); } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2 * M_PI * (2 * a * std::pow(b, 2) * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a * std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + 4 * std::pow(b, 5) * std::pow(z, 6) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 5 * std::pow(b, 3) * std::pow(z, 4) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (3.0 / 2.0) * std::pow(b, 3) * std::pow(z, 4) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 9.0 / 8.0 * b * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 8.0) * b * std::pow(z, 2) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0)); //} // Return ID virtual std::string ID() { return "K"; } }; // F(z) = a + b*exp(z) class GeratrizL : public AletaTaskInput { // Par�metros!! (se houver) double a = (1.0 / 2.0) * ft_D * (std::exp(ft_L) - 2) / (std::exp(ft_L) - 1); double b = (1.0 / 2.0) * ft_D / (std::exp(ft_L) - 1); // Returns F(z) virtual double F(const double& z) { return a + b * std::exp(z); } // Returns dF(z)/dz virtual double dFdz(const double& z) { return b * std::exp(z); } // Returns dAs(z)/dz //virtual double dAsdz(const double& z) { // return 2 * M_PI * (2 * a * std::pow(b, 2) * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a * std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 2.0) * a / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + 4 * std::pow(b, 5) * std::pow(z, 6) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 5 * std::pow(b, 3) * std::pow(z, 4) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (3.0 / 2.0) * std::pow(b, 3) * std::pow(z, 4) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0) - 9.0 / 8.0 * b * std::pow(z, 2) / std::sqrt(4 * std::pow(b, 2) * std::pow(z, 2) + 1) + (1.0 / 8.0) * b * std::pow(z, 2) / std::pow(4 * std::pow(b, 2) * std::pow(z, 2) + 1, 3.0 / 2.0)); //} // Return ID virtual std::string ID() { return "L"; } }; // F(z) = a - b*exp(z) class GeratrizM : public AletaTaskInput { // Par�metros!! (se houver) double a = (1.0 / 2.0) * ft_D * std::exp(ft_L) / (std::exp(ft_L) - 1); double b = (1.0 / 2.0) * ft_D / (std::exp(ft_L) - 1); // Returns F(z) virtual double F(const double& z) { return a - b * std::exp(z); } // Returns dF(z)/dz virtual double dFdz(const double& z) { return - b * std::exp(z); } // Return ID virtual std::string ID() { return "M"; } }; // ==== n�o altere mais! ======= ! #endif // GERATRIZES_TASK_HPP
true
97821edf892384f786d26ae4b9a1ce0b5b77481a
C++
pravincesingh/DSA-C-CPP-CP
/competitive coding/17 rectangle.cpp
UTF-8
424
2.78125
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { int T;cin>>T; while(T--) { vector<int> r1; for(int i=0;i<4;i++) { int n;cin>>n; r1.push_back(n); } sort(r1.begin(),r1.end()); if(r1[0]==r1[1]&&r1[2]==r1[3]) cout<<"YES\n"; else cout<<"NO\n"; } return 0; }
true
357c47d28699a57a932f49d9f08b66dfe0fe2eb8
C++
chenghu17/Algorithm
/Routine/Zero_Number_N_Factorial.cpp
UTF-8
1,264
3.6875
4
[]
no_license
// // Created by Mr.Hu on 2018/4/2. // // Q:给定数字n,计算其n!的结果末尾有多少个0? // 阶乘的结果一般都特别大,所以如果直接算,n稍微大一点就会overflow // 所以观察发现,n!结果中尾数0的个数,来源于2x5 // 所以只需要观察有多少个n!中有多少个2x5即可 // 但是判断2x5也不是一件容易的事情,对于2和5而言,将数字分解为因数包含2,和将数字分解为因数包含5; // 很明显含2的多,所以我们只需要判断,n!中,可以提取出多少个5就可以了,因为一定存在相对数量的2,来与5相乘。 // 所以我就对每个数进行判断,判断其模5后余数为不为0,为0则结果+1,然后判断剩下的因数是否还包含; // 不包含则对下一个乘数进行上述判断。 // #include <iostream> using namespace std; int zeroNumber(int n); int main() { int n = 20; int zero_Number = zeroNumber(n); cout << zero_Number << endl; return 0; } int zeroNumber(int n) { int result = 0; if (n <= 0) return result; for (int i = 1; i <= n; i++) { int m = i; while (m % 5 == 0) { result++; m /= 5; } } return result; }
true
b521fc0603644f0c0c2fd7622345ca66e03594e4
C++
SamyPolcher/CMP
/lec14/examples/SimpleBody.cc
UTF-8
1,271
3.21875
3
[]
no_license
#include "SimpleBody.h" #include<iostream> #include<cmath> SimpleBody::SimpleBody(const std::string& name, const double mass, const Vector3D& x0) : Body(name) { mass_ = mass; pos_ = x0; } void SimpleBody::move(const Vector3D& F, double dt) { pos_ += vel_ * dt; Vector3D acc = F/mass_; vel_ += acc * dt; } Vector3D SimpleBody::forceOn(const Body* obj) const { const double Grav_Const = 6.673e-11; // Newton's constant Vector3D dr = position() - obj->position(); Vector3D force = Grav_Const * mass() * obj->mass() * dr / pow(dr.mod(),3); return force; } Vector3D SimpleBody::forceFrom(const Body* source) const { const double Grav_Const = 6.673e-11; // Newton's constant Vector3D dr = source->position() - position(); Vector3D force = Grav_Const * source->mass() * mass() * dr / pow(dr.mod(),3); return force; } void SimpleBody::print() const { std::cout << "===== class: SimpleBody name: " << name() << "\t mass: " << mass_ << " kg" << " ===== " << std::endl << "current position " << pos_ << "\t distance from origin: " << pos_.mod() << " m" << std::endl << "current velocity " << vel_ << "\t " << vel_.mod() << " m/s" << std::endl; }
true
27ec362fdb629ddb0d6fef730008de7ef1382176
C++
allenc4/quadrotor_autonav
/src/State.h
UTF-8
578
3.234375
3
[]
no_license
#ifndef _STATE_ #define _STATE_ #include <vector> #include <iostream> #include <cstddef> /** * Small class to hold various data about a state. Used during problem search. */ class State{ public: State(){}; State(int x, int y, float value); ~State(); int x; int y; float value; float cost; int priority; bool obstacle; State * parent; bool operator< (const State& rhs) const { return this->priority > rhs.priority; //have to switch the signs because //priority queue sorts largest to smallest //we want it in reverse } private: }; #endif
true
342b4ecaef41ac84d1fe763adf262fbf4eabbe47
C++
serberoth/Raytracer
/src/matrix.h
UTF-8
11,316
2.796875
3
[ "MIT" ]
permissive
#ifndef __MATRIX_H_ #define __MATRIX_H_ #pragma once /*---------------------------------------------------------------------------*/ class Matrix : public gc { private: union { struct { double a[16]; }; struct { double m[4][4]; }; struct { double m00, m01, m02, m03; double m10, m11, m12, m13; double m20, m21, m22, m23; double m30, m31, m32, m33; }; }; inline double Minor (const size_t r0, const size_t r1, const size_t r2, const size_t c0, const size_t c1, const size_t c2) const { return m[r0][c0] * (m[r1][c1] * m[r2][c2] - m[r2][c1] * m[r1][c2]) - m[r0][c1] * (m[r1][c0] * m[r2][c2] - m[r2][c0] * m[r1][c2]) + m[r0][c2] * (m[r1][c0] * m[r2][c1] - m[r2][c0] * m[r1][c1]); } public: static const Matrix ZERO; static const Matrix IDENTITY; inline Matrix () : m00 (1.0), m01 (0.0), m02 (0.0), m03 (0.0), m10 (0.0), m11 (1.0), m12 (0.0), m13 (0.0), m20 (0.0), m21 (0.0), m22 (1.0), m23 (0.0), m30 (0.0), m31 (0.0), m32 (0.0), m33 (1.0) { } inline Matrix (double _m00, double _m01, double _m02, double _m03, double _m10, double _m11, double _m12, double _m13, double _m20, double _m21, double _m22, double _m23, double _m30, double _m31, double _m32, double _m33) : m00 (_m00), m01 (_m01), m02 (_m02), m03 (_m03), m10 (_m10), m11 (_m11), m12 (_m12), m13 (_m13), m20 (_m20), m21 (_m21), m22 (_m22), m23 (_m23), m30 (_m30), m31 (_m31), m32 (_m32), m33 (_m33) { } inline Matrix (const Vector &a, const Vector &b, const Vector &c, const Vector &d) : m00 (a[0]), m01 (a[1]), m02 (a[2]), m03 (0.0), m10 (b[0]), m11 (b[1]), m12 (b[2]), m13 (0.0), m20 (c[0]), m21 (c[1]), m22 (c[2]), m23 (0.0), m30 (d[0]), m31 (d[1]), m32 (d[2]), m33 (1.0) { } virtual ~Matrix () { } inline const double * const operator [] (size_t i) const { assert (i < 4); return m[i]; } inline double *operator [] (size_t i) { assert (i < 4); return m[i]; } inline Matrix operator = (const Matrix &m) { m00 = m.m00, m01 = m.m01, m02 = m.m02, m03 = m.m03; m10 = m.m10, m11 = m.m11, m12 = m.m12, m13 = m.m13; m20 = m.m20, m21 = m.m21, m22 = m.m22, m23 = m.m23; m30 = m.m30, m31 = m.m31, m32 = m.m32, m33 = m.m33; return *this; } inline Matrix operator + () const { return *this; } inline Matrix operator - () const { return *this; } inline friend Matrix operator + (const Matrix &a, const Matrix &b) { return Matrix (a.m[0][0] + b.m[0][0], a.m[0][1] + b.m[0][1], a.m[0][2] + b.m[0][2], a.m[0][3] + b.m[0][3], a.m[1][0] + b.m[1][0], a.m[1][1] + b.m[1][1], a.m[1][2] + b.m[1][2], a.m[1][3] + b.m[1][3], a.m[2][0] + b.m[2][0], a.m[2][1] + b.m[2][1], a.m[2][2] + b.m[2][2], a.m[2][3] + b.m[2][3], a.m[3][0] + b.m[3][0], a.m[3][1] + b.m[3][1], a.m[3][2] + b.m[3][2], a.m[3][3] + b.m[3][3]); } inline friend Matrix operator - (const Matrix &a, const Matrix &b) { return Matrix (a.m[0][0] - b.m[0][0], a.m[0][1] - b.m[0][1], a.m[0][2] - b.m[0][2], a.m[0][3] - b.m[0][3], a.m[1][0] - b.m[1][0], a.m[1][1] - b.m[1][1], a.m[1][2] - b.m[1][2], a.m[1][3] - b.m[1][3], a.m[2][0] - b.m[2][0], a.m[2][1] - b.m[2][1], a.m[2][2] - b.m[2][2], a.m[2][3] - b.m[2][3], a.m[3][0] - b.m[3][0], a.m[3][1] - b.m[3][1], a.m[3][2] - b.m[3][2], a.m[3][3] - b.m[3][3]); } inline friend Matrix operator * (const Matrix &a, const Matrix &b) { return a.Concatenate (b); } inline friend Vector operator * (const Matrix &m, const Vector &v) { double inverse_w = 1.0 / (v[0] * m.m[3][0] + v[1] * m.m[3][1] + v[2] * m.m[3][2] + m.m[3][3]); return Vector ((v[0] * m.m[0][0] + v[1] * m.m[0][1] + v[2] * m.m[0][2] + m.m[0][3]) * inverse_w, (v[0] * m.m[1][0] + v[1] * m.m[1][1] + v[2] * m.m[1][2] + m.m[1][3]) * inverse_w, (v[0] * m.m[2][0] + v[1] * m.m[2][1] + v[2] * m.m[2][2] + m.m[2][3]) * inverse_w); } inline friend Vector operator * (const Vector &v, const Matrix &m) { double inverse_w = 1.0 / (v[0] * m.m[0][3] + v[1] * m.m[1][3] + v[2] * m.m[2][3] + m.m[3][3]); return Vector ((v[0] * m.m[0][0] + v[1] * m.m[1][0] + v[2] * m.m[2][0] + m.m[3][0]) * inverse_w, (v[0] * m.m[0][1] + v[1] * m.m[1][1] + v[2] * m.m[2][1] + m.m[3][1]) * inverse_w, (v[0] * m.m[0][2] + v[1] * m.m[1][2] + v[2] * m.m[2][2] + m.m[3][2]) * inverse_w); } inline friend Matrix operator * (const Matrix &m, const double s) { return Matrix (m.m[0][0] * s, m.m[0][1] * s, m.m[0][2] * s, m.m[0][3] * s, m.m[1][0] * s, m.m[1][1] * s, m.m[1][2] * s, m.m[1][3] * s, m.m[2][0] * s, m.m[2][1] * s, m.m[2][2] * s, m.m[2][3] * s, m.m[3][0] * s, m.m[3][1] * s, m.m[3][2] * s, m.m[3][3] * s); } inline friend Matrix operator * (const double s, const Matrix &m) { return Matrix (m[0][0] * s, m.m[0][1] * s, m.m[0][2] * s, m.m[0][3] * s, m.m[1][0] * s, m.m[1][1] * s, m.m[1][2] * s, m.m[1][3] * s, m.m[2][0] * s, m.m[2][1] * s, m.m[2][2] * s, m.m[2][3] * s, m.m[3][0] * s, m.m[3][1] * s, m.m[3][2] * s, m.m[3][3] * s); } inline Matrix Concatenate (const Matrix &m) const { Matrix r; r.m[0][0] = m[0][0] * m.m[0][0] + m[0][1] * m.m[1][0] + m[0][2] * m.m[2][0] + m[0][3] * m.m[3][0]; r.m[0][1] = m[0][0] * m.m[0][1] + m[0][1] * m.m[1][1] + m[0][2] * m.m[2][1] + m[0][3] * m.m[3][1]; r.m[0][2] = m[0][0] * m.m[0][2] + m[0][1] * m.m[1][2] + m[0][2] * m.m[2][2] + m[0][3] * m.m[3][2]; r.m[0][3] = m[0][0] * m.m[0][3] + m[0][1] * m.m[1][3] + m[0][2] * m.m[2][3] + m[0][3] * m.m[3][3]; r.m[1][0] = m[1][0] * m.m[0][0] + m[1][1] * m.m[1][0] + m[1][2] * m.m[2][0] + m[1][3] * m.m[3][0]; r.m[1][1] = m[1][0] * m.m[0][1] + m[1][1] * m.m[1][1] + m[1][2] * m.m[2][1] + m[1][3] * m.m[3][1]; r.m[1][2] = m[1][0] * m.m[0][2] + m[1][1] * m.m[1][2] + m[1][2] * m.m[2][2] + m[1][3] * m.m[3][2]; r.m[1][3] = m[1][0] * m.m[0][3] + m[1][1] * m.m[1][3] + m[1][2] * m.m[2][3] + m[1][3] * m.m[3][3]; r.m[2][0] = m[2][0] * m.m[0][0] + m[2][1] * m.m[1][0] + m[2][2] * m.m[2][0] + m[2][3] * m.m[3][0]; r.m[2][1] = m[2][0] * m.m[0][1] + m[2][1] * m.m[1][1] + m[2][2] * m.m[2][1] + m[2][3] * m.m[3][1]; r.m[2][2] = m[2][0] * m.m[0][2] + m[2][1] * m.m[1][2] + m[2][2] * m.m[2][2] + m[2][3] * m.m[3][2]; r.m[2][3] = m[2][0] * m.m[0][3] + m[2][1] * m.m[1][3] + m[2][2] * m.m[2][3] + m[2][3] * m.m[3][3]; r.m[3][0] = m[3][0] * m.m[0][0] + m[3][1] * m.m[1][0] + m[3][2] * m.m[2][0] + m[3][3] * m.m[3][0]; r.m[3][1] = m[3][0] * m.m[0][1] + m[3][1] * m.m[1][1] + m[3][2] * m.m[2][1] + m[3][3] * m.m[3][1]; r.m[3][2] = m[3][0] * m.m[0][2] + m[3][1] * m.m[1][2] + m[3][2] * m.m[2][2] + m[3][3] * m.m[3][2]; r.m[3][3] = m[3][0] * m.m[0][3] + m[3][1] * m.m[1][3] + m[3][2] * m.m[2][3] + m[3][3] * m.m[3][3]; return r; } inline Matrix Transpose () const { return Matrix (m[0][0], m[1][0], m[2][0], m[3][0], m[0][1], m[1][1], m[2][1], m[3][1], m[0][2], m[1][2], m[2][2], m[3][2], m[0][3], m[1][3], m[2][3], m[3][3]); } inline Matrix SetTranslation (const Vector &v) { m[3][0] = v[0], m[3][1] = v[1], m[3][2] = v[2]; return *this; } inline Vector GetTranslation () const { return Vector (m[3][0], m[3][1], m[3][2]); } inline Matrix SetScale (const Vector &v) { m[0][0] = v[0], m[1][1] = v[1], m[2][2] = v[2]; return *this; } inline Vector GetScale () const { return Vector (m[0][0], m[1][1], m[2][2]); } inline Matrix Adjoint () const { return Matrix (Minor (1, 2, 3, 1, 2, 3), -Minor (0, 2, 3, 1, 2, 3), Minor (0, 1, 3, 1, 2, 3), -Minor (0, 1, 2, 1, 2, 3), -Minor (1, 2, 3, 0, 2, 3), Minor (0, 2, 3, 0, 2, 3), -Minor (0, 1, 3, 0, 2, 3), Minor (0, 1, 2, 0, 2, 3), Minor (1, 2, 3, 0, 1, 3), -Minor (0, 2, 3, 0, 1, 3), Minor (0, 1, 3, 0, 1, 3), -Minor (0, 1, 2, 0, 1, 3), -Minor (1, 2, 3, 0, 1, 2), Minor (0, 2, 3, 0, 1, 2), -Minor (0, 1, 3, 0, 1, 2), Minor (0, 1, 2, 0, 1, 2)); } inline double Determinant () const { return m[0][0] * Minor (1, 2, 3, 1, 2, 3) - m[0][1] * Minor (1, 2, 3, 0, 2, 3) + m[0][2] * Minor (1, 2, 3, 0, 1, 3) - m[0][3] * Minor (1, 2, 3, 0, 1, 2); } inline Matrix Inverse () const { return Adjoint () * (1.0 / Determinant ()); } Matrix Orthonormal () const { Matrix r = *this; double inverse_length = 1.0 / sqrt (r.m[0][0] * r.m[0][0] + r.m[1][0] * r.m[1][0] + r.m[2][0] * r.m[2][0]); r.m[0][0] *= inverse_length; r.m[1][0] *= inverse_length; r.m[2][0] *= inverse_length; double dot0 = r.m[0][0] * r.m[0][1] + r.m[1][0] * r.m[1][1] + r.m[2][0] * r.m[2][1]; r.m[0][1] -= dot0 * r.m[0][0]; r.m[1][1] -= dot0 * r.m[1][0]; r.m[2][1] -= dot0 * r.m[2][0]; inverse_length = 1.0 / sqrt (r.m[0][1] * r.m[0][1] + r.m[1][1] * r.m[1][1] + r.m[2][1] * r.m[2][1]); r.m[0][1] *= inverse_length; r.m[1][1] *= inverse_length; r.m[2][1] *= inverse_length; double dot1 = r.m[0][1] * r.m[0][2] + r.m[1][1] * r.m[1][2] + r.m[2][1]* r.m[2][2]; dot0 = r.m[0][0] * r.m[0][2] + r.m[1][0] * r.m[1][2] + r.m[2][0]* r.m[2][2]; r.m[0][2] -= dot0 * r.m[0][0] + dot1 * r.m[0][1]; r.m[1][2] -= dot0 * r.m[1][0] + dot1 * r.m[1][1]; r.m[2][2] -= dot0 * r.m[2][0] + dot1 * r.m[2][1]; inverse_length = 1.0 / sqrt (r.m[0][2] * r.m[0][2] + r.m[1][2] * r.m[1][2] + r.m[2][2] * r.m[2][2]); r.m[0][2] *= inverse_length; r.m[1][2] *= inverse_length; r.m[2][2] *= inverse_length; return r; } inline static Matrix Translation (const Vector &v) { return Matrix (1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, v[0], v[1], v[2], 1.0); } inline static Matrix Translation (const double x, const double y, const double z) { return Matrix (1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0); } inline static Matrix Scale (const Vector &v) { return Matrix (v[0], 0.0, 0.0, 0.0, 0.0, v[1], 0.0, 0.0, 0.0, 0.0, v[2], 0.0, 0.0, 0.0, 0.0, 1.0); } inline static Matrix Scale (const double x, const double y, const double z) { return Matrix (x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0); } inline static Matrix Skew (const Vector &v) { return Matrix (0.0, -v[2], v[1], 0.0, v[2], 0.0, -v[0], 0.0, -v[1], v[0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); } inline static Matrix Skew (const double x, const double y, const double z) { return Matrix (0.0, -z, y, 0.0, z, 0.0, -x, 0.0, -y, x, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); } inline static Matrix RotateYaw (const double angle) { double c = cos (angle); double s = sin (angle); return Matrix (1.0, 0.0, 0.0, 0.0, 0.0, c, -s, 0.0, 0.0, s, c, 0.0, 0.0, 0.0, 0.0, 1.0); } inline static Matrix RotatePitch (const double angle) { double c = cos (angle); double s = sin (angle); return Matrix (c, 0.0, s, 0.0, 0.0, 1.0, 0.0, 0.0, -s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0); } inline static Matrix RotateRoll (const double angle) { double c = cos (angle); double s = sin (angle); return Matrix (c, -s, 0.0, 0.0, s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); } inline static Matrix Rotation (const Vector &v) { return RotateRoll (v[2]) * RotatePitch (v[1]) * RotateYaw (v[0]); } inline static Matrix Rotation (const double y, const double p, const double r) { return RotateRoll (r) * RotatePitch (p) * RotateYaw (y); } }; /* class Matrix */ /*---------------------------------------------------------------------------*/ #endif /* __MATRIX_H_ */
true
62fa7b2b264b5d3edbd71132098d3566371b6cff
C++
103174/doudizhuAI
/doudizhuAI/CCard/CardSeries_TriSeriesCard.cpp
UTF-8
1,250
3.0625
3
[]
no_license
#include <algorithm> using namespace std; #include "Card.h" #include "CardSeries_TriSeriesCard.h" CCardSeries_TriSeriesCard::CCardSeries_TriSeriesCard() { } CCardSeries_TriSeriesCard::~CCardSeries_TriSeriesCard() { } BYTE CCardSeries_TriSeriesCard::type() { m_CardType = CardSeries_Type_DoubleSeries; return CardSeries_Type_DoubleSeries; } void CCardSeries_TriSeriesCard::sort() { std::sort(m_Cards.begin(), m_Cards.end(), Lower); } bool CCardSeries_TriSeriesCard::operator <(CCardSeries&p) { CCardSeries_TriSeriesCard *pp = (CCardSeries_TriSeriesCard*)&p; sort(); p.sort(); return m_Cards[0] < pp->m_Cards[0] ; } bool CCardSeries_TriSeriesCard::operator >(CCardSeries&p) { CCardSeries_TriSeriesCard *pp = (CCardSeries_TriSeriesCard*)&p; sort(); p.sort(); return m_Cards[0] > pp->m_Cards[0] ; } bool CCardSeries_TriSeriesCard::operator ==(CCardSeries &p) { CCardSeries_TriSeriesCard *pp = (CCardSeries_TriSeriesCard*)&p; sort(); p.sort(); return m_Cards[0] == pp->m_Cards[0] ; } CCardSeries* CCardSeries_TriSeriesCard::clone() { CCardSeries_TriSeriesCard *p = new(CCardSeries_TriSeriesCard); p->m_CardType = this->m_CardType; for(int i=0; i < m_Cards.size(); i++) { p->m_Cards.push_back(m_Cards[i]); } return p; }
true
728e540992cb80b5bf9928a93a605da669b35b90
C++
HGD-CodeMe/c_or_cpp
/My Procedure/c++/6.cpp
WINDOWS-1252
271
2.90625
3
[]
no_license
#include<iostream> using namespace std; #include<iomanip> main() { int a,b,c,t; cout<<""<<endl; cin>>a>>b>>c; if(a>b) t=a,a=b,b=t; if(a>c) t=a,a=c,c=t; if(b>c) t=b,b=c,c=t; cout<<a<<setw(3)<<b<<setw(3)<<c<<setw(3)<<endl; }
true
115170a76e69a00309fdfff6cd2e84b5ed3b6e3f
C++
zdugi/Pistonics
/src/GameObject2D.cpp
UTF-8
3,682
2.8125
3
[]
no_license
#include "GameObject2D.h" Graphics::GameObject2D::GameObject2D(SDL_Texture *gTexture, Geometry::Shape *shape, Collisions::BoundBox *topBox, Collisions::BoundBox *leftBox, Collisions::BoundBox *botBox, Collisions::BoundBox *rightBox) { this->gTexture = gTexture; this->shape = shape; // move relevant to real positions if (topBox != NULL) { topBox->setX(shape->getX() + topBox->getX()); topBox->setY(shape->getY() + topBox->getY()); } if (leftBox != NULL) { leftBox->setX(shape->getX() + leftBox->getX()); leftBox->setY(shape->getY() + leftBox->getY()); } if (botBox != NULL) { botBox->setX(shape->getX() + botBox->getX()); botBox->setY(shape->getY() + botBox->getY()); } if (rightBox != NULL) { rightBox->setX(shape->getX() + rightBox->getX()); rightBox->setY(shape->getY() + rightBox->getY()); } boxes[Object2DSide::TOP] = topBox; boxes[Object2DSide::LEFT] = leftBox; boxes[Object2DSide::BOT] = botBox; boxes[Object2DSide::RIGHT] = rightBox; velX = 0; velY = 0; } Graphics::GameObject2D::GameObject2D(GameObject2D& go2d) { printf("Calling"); gTexture = go2d.getTexture(); shape = go2d.getShape(); boxes[Object2DSide::TOP] = go2d.getBoxes()[0]; boxes[Object2DSide::LEFT] = go2d.getBoxes()[1]; boxes[Object2DSide::BOT] = go2d.getBoxes()[2]; boxes[Object2DSide::RIGHT] = go2d.getBoxes()[3]; velX = go2d.getVelX(); velY = go2d.getVelY(); } Graphics::GameObject2D::GameObject2D(const GameObject2D& go2d) { printf("Called."); } Graphics::GameObject2D::~GameObject2D() { // @uncoment //printf("[GO2D] Calling destructor.\n"); if (gTexture != NULL) { SDL_DestroyTexture(gTexture); gTexture = NULL; } if (shape != NULL) { delete shape; shape = NULL; } for (int i = 0; i < OBJECT_2D_SIDES; i++) { if (boxes[i] == NULL) continue; delete boxes[i]; } } void Graphics::GameObject2D::render(SDL_Renderer *gRenderer) { SDL_Rect renderQuad = shape->getRenderQuad(); if (gTexture != NULL) SDL_RenderCopy(gRenderer, gTexture, NULL, &renderQuad); for (int i = 0; i < OBJECT_2D_SIDES; i++) { if (boxes[i] == NULL) continue; boxes[i]->render(gRenderer); } } void Graphics::GameObject2D::move() { // move main presentation shape shape->setX(shape->getX() + velX); shape->setY(shape->getY() + velY); // now move boxes for (int i = 0; i < OBJECT_2D_SIDES; i++) { if (boxes[i] == NULL) continue; boxes[i]->setX(boxes[i]->getX() + velX); boxes[i]->setY(boxes[i]->getY() + velY); } } void Graphics::GameObject2D::move(int x, int y) { // move main presentation shape shape->setX(shape->getX() + x); shape->setY(shape->getY() + y); // now move boxes for (int i = 0; i < OBJECT_2D_SIDES; i++) { if (boxes[i] == NULL) continue; boxes[i]->setX(boxes[i]->getX() + x); boxes[i]->setY(boxes[i]->getY() + y); } } void Graphics::GameObject2D::setVelX(int velX) { this->velX = velX; } void Graphics::GameObject2D::setVelY(int velY) { this->velY = velY; } int Graphics::GameObject2D::getVelX() { return velX; } int Graphics::GameObject2D::getVelY() { return velY; } Collisions::BoundBox** Graphics::GameObject2D::getBoxes() { return boxes; // valjda ce raditi } Geometry::Shape* Graphics::GameObject2D::getShape() { return shape; } SDL_Texture* Graphics::GameObject2D::getTexture() { return gTexture; } void Graphics::GameObject2D::setPosition(int x, int y) { // now move boxes for (int i = 0; i < OBJECT_2D_SIDES; i++) { if (boxes[i] == NULL) continue; boxes[i]->setX(boxes[i]->getX() - shape->getX() + x); boxes[i]->setY(boxes[i]->getY() - shape->getY() + y); } // move main presentation shape shape->setX(x); shape->setY(y); }
true
5c0138eaf051a4835cd2a2bdc51fff8b1eab71e0
C++
Pkotova/Object-Oriented-IS-2019-2020---Practice
/game-of-thrones/game-of-thrones/LoginView.cpp
UTF-8
449
2.75
3
[]
no_license
#include "LoginView.h" #include<iostream> void LoginView::run() { char* username = new char[32]; std::cout << "Username:"; std::cin.get(); std::cin.getline(username, 32); char* password = new char[32]; std::cout << "Password:"; std::cin.getline(password, 32); system("cls"); AutheticationService::Authenticate(username, password); if (AutheticationService::getLoggedUser() != nullptr) return; delete[] username; delete[] password; }
true
89253d953f0809e09e89f624a8a88cffd404dff8
C++
ioxgd/GCTRL-Firmware
/GCTRL_Firmware/Stepper.ino
UTF-8
9,600
2.71875
3
[]
no_license
#define STEPX_STEP_PIN 10 #define STEPX_DIR_PIN 11 #define STEPX_EN_PIN 12 #define STEPY_STEP_PIN 8 #define STEPY_DIR_PIN 9 #define STEPY_EN_PIN 12 void stepperEnable(bool en) { digitalWrite(STEPX_EN_PIN, en ? LOW : HIGH); digitalWrite(STEPY_EN_PIN, en ? LOW : HIGH); } int runStepX = 0; int ruSpeedX = 0; int runStepY = 0; int ruSpeedY = 0; void setupStepper() { pinMode(STEPX_STEP_PIN, OUTPUT); pinMode(STEPX_DIR_PIN, OUTPUT); pinMode(STEPX_EN_PIN, OUTPUT); pinMode(STEPY_STEP_PIN, OUTPUT); pinMode(STEPY_DIR_PIN, OUTPUT); pinMode(STEPY_EN_PIN, OUTPUT); stepperEnable(false); } void moveMotorX(int speed, int dir, int step) { digitalWrite(STEPX_EN_PIN, LOW); digitalWrite(STEPX_DIR_PIN, dir); while (step--) { digitalWrite(STEPX_STEP_PIN, HIGH); delayMicroseconds(speed); digitalWrite(STEPX_STEP_PIN, LOW); delayMicroseconds(speed); } digitalWrite(STEPX_EN_PIN, HIGH); } void moveMotorY(int speed, int dir, int step) { digitalWrite(STEPY_EN_PIN, LOW); digitalWrite(STEPY_DIR_PIN, dir); while (step--) { digitalWrite(STEPY_STEP_PIN, HIGH); delayMicroseconds(speed); digitalWrite(STEPY_STEP_PIN, LOW); delayMicroseconds(speed); } digitalWrite(STEPY_EN_PIN, HIGH); } #define STEP_DELAY 100 void moveMotorXOneStep(int dir) { // digitalWrite(STEPX_DIR_PIN, dir); digitalWrite(STEPX_STEP_PIN, HIGH); delayMicroseconds(STEP_DELAY); digitalWrite(STEPX_STEP_PIN, LOW); delayMicroseconds(STEP_DELAY); } void moveMotorYOneStep(int dir) { // digitalWrite(STEPY_DIR_PIN, dir); digitalWrite(STEPY_STEP_PIN, HIGH); delayMicroseconds(STEP_DELAY); digitalWrite(STEPY_STEP_PIN, LOW); delayMicroseconds(STEP_DELAY); } #define LINE_BUFFER_LENGTH 512 // Servo position for Up and Down const int penZUp = 65; const int penZDown = 90; /* Structures, global variables */ struct point { float x; float y; float z; }; // Current position of plothead struct point actuatorPos; // Drawing settings, should be OK int StepDelay = 0; int LineDelay = 0; int penDelay = 50; // Motor steps to go 1 millimeter. // Use test sketch to go 100 steps. Measure the length of line. // Calculate steps per mm. Enter here. float StepsPerMillimeterX = 80.0; float StepsPerMillimeterY = 80.0; // Drawing robot limits, in mm // OK to start with. Could go up to 50 mm if calibrated well. float Xmin = 0; float Xmax = 300; float Ymin = 0; float Ymax = 300; float Zmin = 0; float Zmax = 1; float Xpos = Xmin; float Ypos = Ymin; float Zpos = Zmax; // Set to true to get debug output. boolean verbose = false; // Needs to interpret // G1 for moving // G4 P300 (wait 150ms) // M300 S30 (pen down) // M300 S50 (pen up) // Discard anything with a ( // Discard any other command! /********************** void setup() - Initialisations ***********************/ void processIncomingLine( char* line, int charNB ) { int currentIndex = 0; char buffer[ 64 ]; // Hope that 64 is enough for 1 parameter struct point newPos; newPos.x = 0.0; newPos.y = 0.0; // Needs to interpret // G1 for moving // G4 P300 (wait 150ms) // G1 X60 Y30 // G1 X30 Y50 // M300 S30 (pen down) // M300 S50 (pen up) // Discard anything with a ( // Discard any other command! while ( currentIndex < charNB ) { switch ( line[ currentIndex++ ] ) { // Select command, if any case 'U': penUp(); break; case 'D': penDown(); break; case 'G': buffer[0] = line[ currentIndex++ ]; // /!\ Dirty - Only works with 2 digit commands // buffer[1] = line[ currentIndex++ ]; // buffer[2] = '\0'; buffer[1] = '\0'; switch ( atoi( buffer ) ) { // Select G command case 0: // G00 & G01 - Movement or fast movement. Same here case 1: // /!\ Dirty - Suppose that X is before Y char* indexX = strchr( line + currentIndex, 'X' ); // Get X/Y position in the string (if any) char* indexY = strchr( line + currentIndex, 'Y' ); if ( indexY <= 0 ) { newPos.x = atof( indexX + 1); newPos.y = actuatorPos.y; } else if ( indexX <= 0 ) { newPos.y = atof( indexY + 1); newPos.x = actuatorPos.x; } else { newPos.y = atof( indexY + 1); // indexY = '\0'; newPos.x = atof( indexX + 1); } // drawLine(newPos.x, newPos.y ); moveTo(newPos.x, newPos.y); // Serial.println("ok"); actuatorPos.x = newPos.x; actuatorPos.y = newPos.y; break; } break; case 'M': buffer[0] = line[ currentIndex++ ]; // /!\ Dirty - Only works with 3 digit commands buffer[1] = line[ currentIndex++ ]; buffer[2] = line[ currentIndex++ ]; buffer[3] = '\0'; switch ( atoi( buffer ) ) { case 300: { char* indexS = strchr( line + currentIndex, 'S' ); float Spos = atof( indexS + 1); // Serial.println("ok"); if (Spos == 30) { penDown(); } if (Spos == 50) { penUp(); } break; } case 114: // M114 - Repport position Serial.print( "Absolute position : X = " ); Serial.print( actuatorPos.x ); Serial.print( " - Y = " ); Serial.println( actuatorPos.y ); break; default: Serial.print( "Command not recognized : M"); Serial.println( buffer ); } } } } /********************************* Draw a line from (x0;y0) to (x1;y1). int (x1;y1) : Starting coordinates int (x2;y2) : Ending coordinates **********************************/ void drawLine(float x1, float y1) { if (verbose) { Serial.print("fx1, fy1: "); Serial.print(x1); Serial.print(","); Serial.print(y1); Serial.println(""); } // Bring instructions within limits if (x1 >= Xmax) { x1 = Xmax; } if (x1 <= Xmin) { x1 = Xmin; } if (y1 >= Ymax) { y1 = Ymax; } if (y1 <= Ymin) { y1 = Ymin; } if (verbose) { Serial.print("Xpos, Ypos: "); Serial.print(Xpos); Serial.print(","); Serial.print(Ypos); Serial.println(""); } if (verbose) { Serial.print("x1, y1: "); Serial.print(x1); Serial.print(","); Serial.print(y1); Serial.println(""); } // Convert coordinates to steps x1 = (int)(x1 * StepsPerMillimeterX); y1 = (int)(y1 * StepsPerMillimeterY); float x0 = Xpos; float y0 = Ypos; // Let's find out the change for the coordinates long dx = abs(x1 - x0); long dy = abs(y1 - y0); /* int sx = x0 < x1 ? StepInc : -StepInc; int sy = y0 < y1 ? StepInc : -StepInc; */ int sx = x0 < x1 ? 1 : 0; int sy = y0 < y1 ? 1 : 0; long i; long over = 0; stepperEnable(true); digitalWrite(STEPX_DIR_PIN, sx); digitalWrite(STEPY_DIR_PIN, sy); if (dx > dy) { for (i = 0; i < dx; ++i) { // myStepperX.onestep(sx, STEP); moveMotorXOneStep(sx); over += dy; if (over >= dx) { over -= dx; // myStepperY.onestep(sy, STEP); moveMotorYOneStep(sy); } // delay(StepDelay); } } else { for (i = 0; i < dy; ++i) { // myStepperY.onestep(sy, STEP); moveMotorYOneStep(sy); over += dx; if (over >= dy) { over -= dy; // myStepperX.onestep(sx, STEP); moveMotorXOneStep(sx); } // delay(StepDelay); } } // stepperEnable(false); if (verbose) { Serial.print("dx, dy:"); Serial.print(dx); Serial.print(","); Serial.print(dy); Serial.println(""); } if (verbose) { Serial.print("Going to ("); Serial.print(x0); Serial.print(","); Serial.print(y0); Serial.println(")"); } // Delay before any next lines are submitted delay(LineDelay); // Update the positions Xpos = x1; Ypos = y1; } // Raises pen void penUp() { servoWrite(penZUp); delay(penDelay); Zpos = Zmax; if (verbose) { Serial.println("Pen up!"); } } // Lowers pen void penDown() { servoWrite(penZDown); delay(penDelay); Zpos = Zmin; if (verbose) { Serial.println("Pen down."); } } void moveTo(float x, float y) { static float beforeX = 0; static float beforeY = 0; x = x > Xmax ? Xmax : x; x = x < Xmin ? Xmin : x; y = y > Ymax ? Ymax : y; y = y < Ymin ? Ymin : y; int stepX = abs(beforeX - x) * StepsPerMillimeterX; int stepY = abs(beforeY - y) * StepsPerMillimeterY; int sx = beforeX < x ? 1 : 0; int sy = beforeY < y ? 1 : 0; stepperEnable(true); digitalWrite(STEPX_DIR_PIN, sx); digitalWrite(STEPY_DIR_PIN, sy); taskENTER_CRITICAL(); if (stepX > stepY) { for (int i=0;i<stepX;i++) { moveMotorXOneStep(sx); if (i < stepY) { moveMotorYOneStep(sy); } // delay(StepDelay); } } else { for (int i=0;i<stepY;i++) { moveMotorYOneStep(sy); if (i < stepX) { moveMotorXOneStep(sx); } // delay(StepDelay); } } taskEXIT_CRITICAL(); // stepperEnable(false); // Delay before any next lines are submitted delay(LineDelay); // Update the positions beforeX = x; beforeY = y; }
true
6c466ba0d2b8c3e74092aaf5b3f1df4c60527297
C++
sheriby/DandAInLeetCode
/Daily_Problem/2012/Beginning/201208_Split_Array_Into_Fibonacci_Sequence/method1/solution.cc
UTF-8
1,575
3.375
3
[ "MIT" ]
permissive
#include <string> #include <vector> using std::string; using std::vector; class Solution { public: // 使用回溯解决此问题 vector<int> splitIntoFibonacci(string S) { vector<int> result; backTrack(result, S, 0, 0, 0); return result; } private: bool backTrack(vector<int>& result, string str, int index, int prev, long long sum) { // 此时已经完全遍历完字符串 if (index == str.size()) { // 列表当中至少要有三个元素 return result.size() >= 3; } long long cur = 0; for (size_t i = index; i < str.size(); i++) { // 数字不能以0开头 if (i > index && str[index] == '0') break; cur = 10 * cur + str[i] - '0'; // 数字超过了上限 if (cur > INT32_MAX) break; // 列表当中已经有了两个元素 if (result.size() >= 2) { // 现在的值还没有前两个元素的总和大 if (cur < sum) continue; // 超过了前两个数的总和 else if (cur > sum) break; } // 此时刚好等于前两个数的总和 result.push_back(cur); // 回溯寻找下一个数 if (backTrack(result, str, i + 1, cur, cur + prev)) { return true; } // 寻找失败将之前的元素去除 result.pop_back(); } return false; } };
true
c345c66c39883a06e3d83e56b5c256ed708e9206
C++
miro-kostadinov/tmos
/tmos/services/tmos_tl_v2/ttl_string.h
UTF-8
46,368
3.015625
3
[]
no_license
/* * ttl_string.h * * Created on: Apr 3, 2013 * Author: miro */ #ifndef TTL_STRING_H_ #define TTL_STRING_H_ #include <tmos.h> #include <tmos_string.h> #include <tmos_stdio.h> #include <tmos_stdlib.h> #include <stdarg.h> #include <ttl_config.h> #include <ttl_atomic.h> #include <ttl_iterator.h> #include <ttl_cpp_type_traits.h> #include <ttl_initializer_list.h> #include <ttl_move.h> namespace ttl { /******************************************************************************* * string and memory headers ******************************************************************************/ /** * In the TMOS memory pool each memory allocation has hidden header. * We can use it when we need the allocation size. */ struct alloc_header { unsigned short alloc_size; //!< memory chunk size unsigned short alloc_prev; //!< reserved, never use this !! }; /** * The string data starts with reference counter and element count */ struct data_header { atomic_short m_refcount; //!< reference counter unsigned short m_length; //!< number of elements }; struct string_header : public alloc_header, public data_header { }; /******************************************************************************* * basic_string ******************************************************************************/ template <typename CharT> class basic_string { public: //----------------------------- types -----------------------------------// typedef CharT value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef pointer iterator; typedef const_pointer const_iterator; typedef ttl::size_t size_type; typedef ttl::ptrdiff_t difference_type; typedef ttl::reverse_iterator<iterator> reverse_iterator; typedef ttl::reverse_iterator<const_iterator> const_reverse_iterator; static const size_type npos = static_cast<size_type>(-1); static CharT dummy_char; //!< dummy char returned as reference for out of bounds /// allocate storage for n chars + 1 terminator space, and set length public: static pointer m_allocate(size_t n, size_t len=0) { void* p; if(n++) { p = ::operator new(sizeof(data_header) + n * sizeof(value_type) ); if(!p) TTL_THROW(EXCEPT_OUT_OF_MEMORY); static_cast<data_header*>(p)->m_refcount =1; static_cast<data_header*>(p)->m_length = len; p = static_cast<data_header*>(p) + 1; static_cast<pointer>(p)[len] =0; } else { p = nullptr; } return static_cast<pointer>(p); } void m_set_size(size_type n) { m_data[n] = 0; string_head()->m_length = n; } protected: pointer m_data; /// return pointer to the full header (alloc_size, refs, size) static string_header* string_head(pointer p) { return reinterpret_cast<string_header*>(reinterpret_cast<void*>(p)) - 1; } string_header* string_head() { return reinterpret_cast<string_header*>(reinterpret_cast<void*>(m_data)) - 1; } const string_header* string_head() const { return reinterpret_cast<const string_header*>(reinterpret_cast<void*>(m_data)) - 1; } /// return pointer for memory free() and realloc() static data_header* mem_head(pointer p) { return reinterpret_cast<data_header*>(reinterpret_cast<void*>(p)) - 1; } /// capacity of memory allocated string static size_type m_capacity(const_pointer p) { size_type n=0; const string_header* head; if(p) { head = reinterpret_cast<const string_header*>( reinterpret_cast<const void*>(p)) - 1; n = ((head->alloc_size-2)*4)/sizeof(CharT); if(n) n--; //terminating 0 } return n; } // size_type m_add_size(size_type n) // { // size_type old_size; // string_header* head; // // head = string_head(); // old_size = head->m_length; // n= old_size+n; // head->m_length = n; // m_data[n] = 0; // return old_size; // } void m_memcpy(const_pointer s, size_type n, size_type pos) { pointer p = m_data + pos; while(n--) p[n] = s[n]; } void m_memmove(const_pointer s, size_type n, size_type pos) { pointer p = m_data + pos; if(p >= s) { //move to right while(n--) p[n] = s[n]; } else { while(n--) { p[0] = s[0]; ++p; ++s; } } } void m_memset(value_type c, size_type n, size_type pos) { pointer p = m_data + pos; while(n--) p[n] = c; } void m_append(const CharT*s, size_type n) { m_make_editable_copy(n); if(m_data) { pointer p = m_data + string_head()->m_length; string_head()->m_length += n; p[n] = 0; while(n--) p[n] = s[n]; } } void m_append(size_type sz, const CharT*s, size_type n) { if(m_reserve(sz, sz+n)) { m_set_size(sz+n); pointer p = m_data + sz; while(n--) p[n] = s[n]; } } static const_pointer m_find(const_pointer s, size_type n, reference __a) { for (size_type i = 0; i < n; ++i) if (s[i] == __a) return s + i; return 0; } static int m_compare(const_pointer s1, const_pointer s2, size_type n) { int res = 0; for (size_type i = 0; i < n; ++i) { res = s1[i] - s2[i]; if(res) break; } return res; } size_type m_limit(size_type pos, size_type n) const { size_type sz = size(); if(pos > sz) { TTL_THROW(EXCEPT_OUT_OF_RANGE); return 0; } sz -= pos; return (n < sz) ? n : sz; } protected: void m_grab() { if (is_ram_ptr(m_data)) string_head()->m_refcount++; } void m_dispose() { if (is_ram_ptr(m_data)) { if( --string_head()->m_refcount <= 0) { ::operator delete(mem_head(m_data)); } } } size_type m_reserve(size_type old_len, size_type res) { pointer new_data; if(is_ram_ptr(m_data)) { string_header* head = string_head(); if ( head->m_refcount != 1 || res >= ((head->alloc_size - 2) * 4) / sizeof(CharT)) { new_data = m_allocate(res, old_len); if(new_data) memcpy(new_data, m_data, old_len*sizeof(CharT)); else res =0; m_dispose(); m_data = new_data; } } else { new_data = m_allocate(res, old_len); if (new_data) memcpy(new_data, m_data, old_len * sizeof(CharT)); else res = 0; m_data = new_data; } return res; } void m_make_editable_copy(size_type res=0, bool forse_realloc=false) { pointer new_data; if(is_ram_ptr(m_data)) { string_header* head = string_head(); res += head->m_length; if (forse_realloc || head->m_refcount != 1 || res >= ((head->alloc_size - 2) * 4) / sizeof(CharT)) { new_data = m_allocate(res, head->m_length); if(new_data) memcpy(new_data, m_data, head->m_length*sizeof(CharT)); m_dispose(); m_data = new_data; } } else { size_type old_len = strlen(m_data); res += old_len; new_data = m_allocate(res, old_len); if(new_data) memcpy(new_data, m_data, old_len*sizeof(CharT)); m_data = new_data; } } template<class _InIterator> static CharT* m_construct_aux(_InIterator __beg, _InIterator __end, __false_type) { typedef typename iterator_traits<_InIterator>::iterator_category _Tag; return m_construct(__beg, __end, _Tag()); } template<class _Integer> static CharT* m_construct_aux(_Integer __beg, _Integer __end, __true_type) { return m_construct(static_cast<size_type>(__beg), __end); } template<class _InIterator> static CharT* m_construct(_InIterator __beg, _InIterator __end) { typedef typename ttl::__is_integer<_InIterator>::__type _Integral; return m_construct_aux(__beg, __end, _Integral()); } template<class _InIterator> static CharT* m_construct(_InIterator __beg, _InIterator __end, input_iterator_tag) { pointer p = nullptr; if (__beg != __end ) { size_type len = 0; p = m_allocate(4); if(p == nullptr) return p; while (__beg != __end) { if(len == m_capacity(p)) { data_header* old_p; old_p = mem_head(p); p = static_cast<pointer>(tsk_realloc(old_p, sizeof(data_header) + len * sizeof(CharT) + 8)); if(p == nullptr) { ::operator delete(old_p); return p; } } p[len++] = *__beg; ++__beg; } string_head(p)->m_length = len; } return p; } // For forward_iterators up to random_access_iterators, used for // string::iterator, CharT*, etc. template<class _FwdIterator> static CharT* m_construct(_FwdIterator __beg, _FwdIterator __end, forward_iterator_tag) { pointer p = nullptr; if (__beg != __end ) { if (__beg == 0) TTL_THROW(EXCEPT_RANGE_CONSTRUCT); else { size_type n; n = static_cast<size_type>(ttl::distance(__beg, __end)); p = m_allocate(n, n); if(p) { while(n--) { p[n] = *__beg; ++__beg; } } } } return p; } static CharT* m_construct(size_type n, CharT c) { pointer p = m_allocate(n, n); if(p) while(n--) p[n] = c; return p; } template<class _Integer> basic_string& m_replace_dispatch(size_type pos1, size_type n1, _Integer n2, _Integer val, __true_type) { return m_replace_aux(pos1, n1, n2, val);} template<class _InputIterator> basic_string& m_replace_dispatch(size_type pos1, size_type n1, _InputIterator k1, _InputIterator k2, __false_type) { const basic_string s(k1, k2); return replace(pos1, n1, s); } basic_string& m_replace_aux(size_type pos1, size_type n1, size_type n2, CharT c); public: //------------------------ construct & destruct --------------------------// /// default constructor basic_string() : m_data(nullptr) { } /// copy constructor basic_string(const basic_string& str); /// from c-string constructor basic_string(const CharT* s); /// substring constructor basic_string(const basic_string& str, size_t pos, size_t len = npos); /// from buffer basic_string(const char* s, size_t n); /// fill constructor basic_string(size_type n, CharT c); /// range constructor template <class InputIterator> basic_string(InputIterator first, InputIterator last); /// initializer list basic_string(std::initializer_list<CharT> il); /// move constructor basic_string(basic_string&& str) noexcept : m_data(str.m_data) { str.m_data = nullptr; } /// destructor ~basic_string() { m_dispose(); } //----------------------------- operator = -------------------------------// /// copy operator basic_string& operator= (const basic_string& str) { return this->assign(str); } /// = c-string basic_string& operator= (const CharT* s) { return this->assign(s); } /// = character basic_string& operator= (CharT c) { this->assign(1, c); return *this; } /// = initializer list basic_string& operator= (std::initializer_list<CharT> il) { this->assign(il.begin(), il.size()); return *this; } /// move operator basic_string& operator= (basic_string&& str) noexcept { // NB: DR 1204. this->swap(str); return *this; } //----------------------------- iterators --------------------------------// iterator begin() noexcept { m_make_editable_copy(); return iterator(m_data); } const_iterator begin() const noexcept { return const_iterator(m_data); } iterator end() noexcept { m_make_editable_copy(); return iterator(m_data + this->size()); } const_iterator end() const noexcept { return const_iterator(m_data + this->size()); } reverse_iterator rbegin() noexcept { return reverse_iterator(this->end()); } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(this->end()); } reverse_iterator rend() noexcept { return reverse_iterator(this->begin()); } const_reverse_iterator rend() const noexcept { return const_reverse_iterator(this->begin()); } const_iterator cbegin() const noexcept { return const_iterator(m_data); } const_iterator cend() const noexcept { return const_iterator(m_data + this->size()); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(this->end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(this->begin()); } //----------------------------- capacity ---------------------------------// size_type size() const noexcept { return is_ram_ptr(m_data)? string_head()->m_length: ::strlen(m_data); } size_type length() const noexcept { return size(); } size_type max_size() const noexcept { return 0x8000; } void resize(size_type n, CharT c); void resize(size_type n) { this->resize(n, CharT()); } void shrink_to_fit() { if (capacity() > size()) { __try { m_make_editable_copy(0, true); //force re-alloc } __catch(...) {} } } size_type capacity() const noexcept { return is_ram_ptr(m_data)? m_capacity(m_data): 0; } size_type reserve(size_type res = 0); void clear() noexcept { if(is_ram_ptr(m_data)) { if(string_head()->m_refcount == 1) { m_set_size(0); return; } m_dispose(); } m_data=nullptr; } bool empty() const noexcept { return m_data? !m_data[0]: 1; } //-------------------------- element access ------------------------------// reference operator[](size_type pos) { return at(pos); } const_reference operator[] (size_type pos) const { return at(pos); } CharT& at(size_type n); const CharT& at(size_type n) const; reference front() { return at(0); } const_reference front() const { return at(0); } reference back() { return at(size()-1);} const_reference back() const { return at(size() - 1); } //----------------------------- modifiers --------------------------------// basic_string& operator+=(const basic_string& str) { return this->append(str); } basic_string& operator+=(const CharT* s) { return this->append(s); } basic_string& operator+=(CharT c) { this->push_back(c); return *this; } basic_string& operator+=(std::initializer_list<CharT> il) { return this->append(il.begin(), il.size()); } /// Appends string str basic_string& append(const basic_string& str); /// Appends a substring [pos, pos+n) of str basic_string& append(const basic_string& str, size_type pos, size_type n); /// Appends the first count characters of character string pointed to by s basic_string& append(const CharT* s, size_type n); /// Appends the null-terminated character string pointed to by s. basic_string& append(const CharT* s) { return this->append(s, strlen(s)); } /// Appends count copies of character c basic_string& append(size_type n, CharT c); /// Appends characters in the initializer list ilist. basic_string& append(std::initializer_list<CharT> il) { return this->append(il.begin(), il.size()); } /// Appends characters in the range [first, last) template<class _InputIterator> basic_string& append(_InputIterator k1, _InputIterator k2) { typedef typename ttl::__is_integer<_InputIterator>::__type _Integral; return m_replace_dispatch(size(), 0, k1, k2, _Integral()); } void push_back(CharT c) { size_type sz = size(); if(m_reserve(sz, sz+1)) { m_data[sz++] = c; m_set_size(sz); } } basic_string& assign(const basic_string& str) { if(this != &str) { m_dispose(); m_data = str.m_data; m_grab(); } return *this; } basic_string& assign(basic_string&& str) { this->swap(str); return *this; } basic_string& assign(const basic_string& str, size_type pos, size_type n) { return this->assign(str.m_data + pos, str.m_limit(pos, n)); } basic_string& assign(const CharT* s, size_type n) { return assign(basic_string(s, n)); } basic_string& assign(const CharT* s) { return this->assign(s, strlen(s)); } basic_string& assign(size_type n, CharT c) { return m_replace_aux(size_type(0), this->size(), n, c); } template<class _InputIterator> basic_string& assign(_InputIterator __first, _InputIterator __last) { return this->replace(m_data, m_data + size(), __first, __last); } basic_string& assign(std::initializer_list<CharT> il) { return this->assign(il.begin(), il.size()); } void insert(iterator p, size_type n, CharT c) { this->replace(p, p, n, c); } template<class _InputIterator> void insert(iterator p, _InputIterator k1, _InputIterator k2) { this->replace(p, p, k1, k2); } void insert(iterator __p, std::initializer_list<CharT> il) { this->insert(__p - m_data, il.begin(), il.size()); } basic_string& insert(size_type pos1, const basic_string& str) { return this->insert(pos1, str, size_type(0), str.size()); } basic_string& insert(size_type pos1, const basic_string& str, size_type pos2, size_type n) { return this->insert(pos1, str.m_data + pos2, str.m_limit(pos2, n)); } basic_string& insert(size_type pos, const CharT* s, size_type n); basic_string& insert(size_type pos, const CharT* s) { return this->insert(pos, s, strlen(s)); } basic_string& insert(size_type pos, size_type n, CharT c) { return m_replace_aux(pos, size_type(0), n, c); } iterator insert(iterator p, CharT c) { const size_type pos = p - m_data; m_replace_aux(pos, size_type(0), size_type(1), c); return iterator(m_data + pos); } basic_string& erase(size_type pos = 0, size_type n = npos); iterator erase(iterator p) { return erase(p-m_data, 1); } iterator erase(iterator i1, iterator i2) { return erase(i1 - m_data, i2 - i1); } basic_string& replace(size_type pos, size_type n, const basic_string& str) { return this->replace(pos, n, str.m_data, str.size()); } basic_string& replace(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2) { return this->replace(pos1, n1, &str.m_data[pos2], str.m_limit(pos2, n2)); } basic_string& replace(size_type pos, size_type n1, const CharT* s, size_type n2); basic_string& replace(size_type pos, size_type n1, const CharT* s) { return this->replace(pos, n1, s, strlen(s)); } basic_string& replace(size_type pos, size_type n1, size_type n2, CharT c) { return m_replace_aux(pos, m_limit(pos, n1), n2, c); } basic_string& replace(iterator i1, iterator i2, const basic_string& str) { return this->replace(i1, i2, str.m_data, str.size()); } basic_string& replace(iterator i1, iterator i2, const CharT* s, size_type n) { return this->replace(i1 - m_data, i2 - i1, s, n); } basic_string& replace(iterator i1, iterator i2, const CharT* s) { return this->replace(i1, i2, s, strlen(s)); } basic_string& replace(iterator i1, iterator i2, size_type n, CharT c) { return m_replace_aux(i1 - m_data, i2 - i1, n, c); } template<class _InputIterator> basic_string& replace(iterator i1, iterator i2, _InputIterator k1, _InputIterator k2) { typedef typename ttl::__is_integer<_InputIterator>::__type _Integral; return m_replace_dispatch(i1 - m_data, i2 - i1, k1, k2, _Integral()); } basic_string& replace(iterator i1, iterator i2, iterator k1, iterator k2) { return this->replace(i1 - m_data, i2 - i1, k1, k2 - k1); } basic_string& replace(iterator i1, iterator i2, const_iterator k1, const_iterator k2) { return this->replace(i1 - m_data, i2 - i1, k1, k2 - k1); } basic_string& replace(iterator i1, iterator i2, std::initializer_list<CharT> il) { return this->replace(i1, i2, il.begin(), il.end()); } size_type copy(CharT* s, size_type n, size_type pos = 0) const; void swap(basic_string& s); const CharT* c_str() const { return m_data; } //---------------------------- search ------------------------------------// size_type find(const CharT* s, size_type pos, size_type n) const; size_type find(const basic_string& str, size_type pos = 0) const noexcept { return this->find(str.m_data, pos, str.size()); } size_type find(const CharT* s, size_type pos = 0) const { return this->find(s, pos, strlen(s)); } size_type find(CharT c, size_type pos = 0) const noexcept; size_type rfind(const basic_string& str, size_type pos = npos) const noexcept { return this->rfind(str.m_data, pos, str.size()); } size_type rfind(const CharT* s, size_type pos, size_type n) const; size_type rfind(const CharT* s, size_type pos = npos) const { return this->rfind(s, pos, strlen(s)); } size_type rfind(CharT c, size_type pos = npos) const noexcept; size_type find_first_of(const basic_string& str, size_type pos = 0) const noexcept { return this->find_first_of(str.m_data, pos, str.size()); } size_type find_first_of(const CharT* s, size_type pos, size_type n) const; size_type find_first_of(const CharT* s, size_type pos = 0) const { return this->find_first_of(s, pos, strlen(s)); } size_type find_first_of(CharT c, size_type pos = 0) const noexcept { return this->find(c, pos); } size_type find_last_of(const basic_string& str, size_type pos = npos) const noexcept { return this->find_last_of(str.m_data, pos, str.size()); } size_type find_last_of(const CharT* s, size_type pos, size_type n) const; size_type find_last_of(const CharT* s, size_type pos = npos) const { return this->find_last_of(s, pos, strlen(s)); } size_type find_last_of(CharT c, size_type pos = npos) const noexcept { return this->rfind(c, pos); } size_type find_first_not_of(const basic_string& str, size_type pos = 0) const noexcept { return this->find_first_not_of(str.m_data, pos, str.size()); } size_type find_first_not_of(const CharT* s, size_type pos, size_type n) const; size_type find_first_not_of(const CharT* s, size_type pos = 0) const { return this->find_first_not_of(s, pos, strlen(s)); } size_type find_first_not_of(CharT c, size_type pos = 0) const noexcept; size_type find_last_not_of(const basic_string& str, size_type pos = npos) const noexcept { return this->find_last_not_of(str.m_data, pos, str.size()); } size_type find_last_not_of(const CharT* s, size_type pos, size_type n) const; size_type find_last_not_of(const CharT* s, size_type pos = npos) const { return this->find_last_not_of(s, pos, strlen(s)); } size_type find_last_not_of(CharT c, size_type pos = npos) const noexcept; // basic_string substr(size_type pos = 0, size_type n = npos) const // { return basic_string(*this, _M_check(pos, "basic_string::substr"), n); } int compare(const basic_string& str) const { pointer p1, p2; p1 = m_data; p2 = str.m_data; if(p1 && p2) { int res; while(!(res = *p1 - *p2) && *p1 ) { ++p1; ++p2; } return res; } return p1 - p2; } int compare(size_type pos, size_type n, const basic_string& str) const; int compare(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2) const; int compare(const CharT* s) const; int compare(size_type pos, size_type n1, const CharT* s) const; int compare(size_type pos, size_type n1, const CharT* s, size_type n2) const; //-------------------------- depreciated ---------------------------------// basic_string substr( size_type pos, size_type n ) const { return basic_string(*this, pos, n); } int atoi() const; long long atoll() const; int itoa(int num); size_type find_in_list(STR_LIST sl, size_type* dwRead) const; void free(); int compare( const CharT* s, unsigned int n ) const { return (strncmp(m_data, s, n)); } int start_with( const CharT* str ) const; int start_casewith( const CharT* str ) const; int format(const CharT *fmt, ...); int appendf(const CharT *fmt, ...); }; template<typename CharT> CharT basic_string<CharT>::dummy_char; typedef basic_string<char> string; template <typename CharT> basic_string<CharT>& basic_string<CharT>::m_replace_aux(size_type pos, size_type n1, size_type n2, CharT c) { size_type sz = size(); if(pos > sz) { TTL_THROW(EXCEPT_OUT_OF_RANGE); } else { sz -= pos; if(n1 > sz) n1 = sz; if(n2) { // we have something to replace with... size_type new_sz; sz -= n1; // size of rightmost (c) new_sz = pos + sz + n2; if((capacity() >= new_sz) && (string_head()->m_refcount == 1)) { // work in place if(n2 != n1) { m_memmove(m_data+pos+n1, sz, pos+n2); m_set_size(new_sz); } m_memset(c, n2, pos); } else { pointer p = m_allocate(new_sz, new_sz); if(p) { if(pos) memcpy(p, m_data, pos*sizeof(CharT)); if(sz) memcpy(p+pos+n2, m_data+pos+n1, sz*sizeof(CharT)); while(n2--) p[pos+n2] = c; } m_dispose(); m_data = p; } } else { // no replace if(n1) erase(pos, n1); } } return *this; } template <typename CharT> basic_string<CharT>::basic_string(const basic_string& str) : m_data(str.m_data) { m_grab(); } template <typename CharT> basic_string<CharT>::basic_string(const basic_string& str, size_t pos, size_t len) :m_data(nullptr) { size_type sz = str.size(); if(pos > sz) { TTL_THROW(EXCEPT_OUT_OF_RANGE); } else { sz -= pos; if(len>sz) len = sz; if(len) { m_data = m_allocate(len, len); if(m_data) m_memcpy(str.c_str(), len, 0); } } } template <typename CharT> basic_string<CharT>::basic_string (const char* s, size_t n) :m_data(const_cast<pointer>(s)) { if (is_ram_ptr(m_data) || (strlen(s) > n)) { m_data = m_allocate(n, n); if(m_data) memcpy(m_data, s, n*sizeof(CharT)); } } template <typename CharT> basic_string<CharT>::basic_string(const CharT* s) :m_data(const_cast<pointer>(s)) { if (is_ram_ptr(m_data)) { size_t n = strlen(s); m_data = m_allocate(n, n); if(m_data) memcpy(m_data, s, n*sizeof(CharT)); } } template <typename CharT> basic_string<CharT>::basic_string(size_type n, CharT c) :m_data(m_construct(n, c)) { } template <typename CharT> template <class InputIterator> basic_string<CharT>::basic_string (InputIterator first, InputIterator last) :m_data(m_construct(first, last)) { } template <typename CharT> basic_string<CharT>::basic_string(std::initializer_list<CharT> il) :m_data(m_construct(il.begin(), il.end(), random_access_iterator_tag())) { } template<typename CharT> void basic_string<CharT>::resize(size_type n, CharT c) { const size_type sz = this->size(); if (sz < n) this->append(n - sz, c); else if (n < sz) this->erase(n); } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::reserve(size_type res) { size_type sz = this->size(); if(res < sz) res = sz; return m_reserve(sz, res); } template<typename CharT> CharT& basic_string<CharT>::at(size_type n) { pointer new_data; if(is_ram_ptr(m_data)) { string_header* head = string_head(); if(n > head->m_length) { TTL_THROW(EXCEPT_OUT_OF_RANGE); return (dummy_char); } if(head->m_refcount != 1 ) { new_data = m_allocate(head->m_length, head->m_length); if(!new_data) return (dummy_char); if(head->m_length) memcpy(new_data, m_data, head->m_length*sizeof(CharT)); m_dispose(); m_data = new_data; } } else { size_type old_len = strlen(m_data); if(n > old_len) { TTL_THROW(EXCEPT_OUT_OF_RANGE); return (dummy_char); } new_data = m_allocate(old_len, old_len); if(!new_data) return (dummy_char); memcpy(new_data, m_data, old_len*sizeof(CharT)); m_data = new_data; } return m_data[n]; } template<typename CharT> const CharT& basic_string<CharT>::at(size_type n) const { if(n > size()) { TTL_THROW(EXCEPT_OUT_OF_RANGE); return (dummy_char); } return m_data[n]; } template<typename CharT> basic_string<CharT>& basic_string<CharT>::append(const basic_string& str) { m_append(str.m_data, str.size()); return *this; } template<typename CharT> basic_string<CharT>& basic_string<CharT>::append(const basic_string& str, size_type pos, size_type n) { if(n) { size_type sz = str.size(); if(pos < sz) { if(n > sz-pos) n= sz-pos; m_append(sz, str.m_data + pos, n); }else if(pos > sz) TTL_THROW(EXCEPT_OUT_OF_RANGE); } return *this; } template<typename CharT> basic_string<CharT>& basic_string<CharT>::append(const CharT* s, size_type n) { if(n && s) { size_type sz = size(); if(m_data <= s && s<= m_data+sz) { size_type off = s-m_data; if(m_reserve(sz, sz+n)) { m_set_size(n +sz); m_memcpy(m_data+off, n, sz); } } else { m_append(sz, s, n); } } return *this; } template<typename CharT> basic_string<CharT>& basic_string<CharT>::append(size_type n, CharT c) { if(n) { size_type sz = size(); if(m_reserve(sz, sz+n)) { m_set_size(n +sz); m_memset(c, n, sz); } } return *this; } template<typename CharT> basic_string<CharT>& basic_string<CharT>::insert(size_type pos, const CharT* s, size_type n) { if(n) { size_type sz = size(); if(pos > sz || !s) { TTL_THROW(EXCEPT_OUT_OF_RANGE); } else { if(m_data <= s && s<= m_data+sz) { const size_type off = s - m_data; if(m_reserve(sz, sz+n)) { this->m_set_size(sz+n); s = m_data + off; CharT* p = m_data + pos; m_memcpy(p, sz-pos, pos+n); if (s >= p) { m_memcpy(s+n, n, pos); // s moved +n } else { m_memcpy(s, n, pos); } } } else { if(m_reserve(sz, sz+n)) { m_set_size(sz+n); m_memcpy(m_data + pos, sz-pos, pos+n); m_memcpy(s, n, pos); } } } } return *this; } template<typename CharT> basic_string<CharT>& basic_string<CharT>::erase(size_type pos, size_type n) { size_type sz = size(); if(pos > sz) { TTL_THROW(EXCEPT_OUT_OF_RANGE); } else { if(n > sz-pos) n = sz-pos; if(n) { if(m_reserve(sz, sz)) { pointer dst, src; sz -= pos+ n; // chars to move dst = m_data + pos; src = dst+n; for (n = 0; n < sz; ++n) dst[n] = src[n]; m_set_size(pos + sz); } } } return *this; } /* * Legend * a -> pos * b -> n1 * c -> size - pos - n1 * x -> this is rom or referenced or no space * - -> this is ram, ref=1, space is OK * * a b c ? s * 0 0 0 * * s - replacing empty with s * * 0 * * 0 this - replace nothing * * 1 * * 0 erase b * * 0 0 1 x 1 new(s+c) * 0 0 1 - 1 c >> n2, copy s * 1 0 0 x 1 new(a+s) * 1 0 0 - 1 copy s * 1 0 1 x 1 new(a,s,c) * 1 0 1 - 1 c>> n2, copy s * * 0 1 1 x 1 new(s+c) * 0 1 1 - 1 c >> (n2-n1), copy s * 1 1 0 x 1 new(a+s) * 1 1 0 - 1 copy s * 1 1 1 x 1 new(a,s,c) , copy a,s c * 1 1 1 - 1 c>> (n2-n1), copy s * */ template<typename CharT> basic_string<CharT>& basic_string<CharT>::replace(size_type pos, size_type n1, const CharT* s, size_type n2) { size_type sz = size(); if(pos > sz) { TTL_THROW(EXCEPT_OUT_OF_RANGE); } else { sz -= pos; if(n1 > sz) n1 = sz; if(n2 && s) { // we have something to replace with... size_type new_sz; pointer p; sz -= n1; // size of rightmost (c) new_sz = pos + sz + n2; if((capacity() >= new_sz) && (string_head()->m_refcount == 1)) { // work in place if(n2 >= n1) { // expanding, so make room first and then copy // we have aaaaaabbbbcccc // it will become aaaaaabbbb cccc // it will become aaaaaabbbbssscccc if(n2 != n1) { p = m_data+pos+n1; m_memcpy(p, sz, pos+n2); if((s >= p) && (s< p+sz)) { s += n2-n1; // s was moved too } } m_memmove(s, n2, pos); } else { // shrinking we have aaaaaa1112222cccc // it will become aaaaaasss2222cccc // it will become aaaaaassscccc m_memmove(s, n2, pos); m_memmove(m_data + pos+n1, sz, pos+n2); } m_set_size(new_sz); } else { p = m_allocate(new_sz, new_sz); if(p) { if(pos) memcpy(p, m_data, pos*sizeof(CharT)); memcpy(p + pos, s, n2*sizeof(CharT)); if(sz) memcpy(p+pos+n2, m_data+pos+n1, sz*sizeof(CharT)); } m_dispose(); m_data = p; } } else { // no replace if(n1) erase(pos, n1); } } return *this; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::copy(CharT* s, size_type n, size_type pos) const { const_pointer p = m_data + pos; size_type i; n = m_limit(pos, n); if(s >= p) { //move to right for(i=n; i--; ) s[i] = p[i]; } else { for(i=0; i<n; ++i) s[i] = p[i]; } return n; } template<typename CharT> void basic_string<CharT>::swap(basic_string& s) { pointer p = m_data; m_data = s.m_data; s.m_data = p; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::find(const CharT* s, size_type pos, size_type n) const { const size_type sz = this->size(); if (n == 0) return pos <= sz ? pos : npos; if (n <= sz) { for (; pos <= sz - n; ++pos) if (m_data[pos] == s[0] && memcmp(m_data + pos + 1, s + 1, n - 1) == 0) return pos; } return npos; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::find(CharT c, size_type pos) const noexcept { size_type sz = this->size(); while(pos < sz) { if(m_data[pos] == c) return pos; ++pos; } return npos; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::rfind(const CharT* s, size_type pos, size_type n) const { size_type sz = this->size(); if (n <= sz) { sz -= n; if(pos > sz) pos = sz; if(n == 0) return pos; do { if (memcmp(m_data + pos, s, n) == 0) return pos; } while (pos-- > 0); } return npos; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::rfind(CharT c, size_type pos ) const noexcept { size_type sz = this->size(); if (sz) { if (pos > --sz) pos = sz; do { if (m_data[pos] == c) return pos; } while(pos--); } return npos; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::find_first_of(const CharT* s, size_type pos, size_type n) const { if(n) { size_type sz = this->size(); for (; pos < sz; ++pos) { if (m_find(s, n, m_data[pos])) return pos; } } return npos; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::find_last_of(const CharT* s, size_type pos, size_type n) const { size_type sz = this->size(); if (sz && n) { if (pos > --sz) pos = sz; do { if (m_find(s, n, m_data[pos])) return pos; } while (pos--); } return npos; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::find_first_not_of(const CharT* s, size_type pos, size_type n) const { size_type sz = this->size(); for (; pos < sz; ++pos) { if (!m_find(s, n, m_data[pos])) return pos; } return npos; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::find_first_not_of(CharT c, size_type pos) const noexcept { size_type sz = this->size(); while(pos < sz) { if (m_data[pos] == c) return pos; ++pos; } return npos; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::find_last_not_of(const CharT* s, size_type pos, size_type n) const { size_type sz = this->size(); if (sz) { if (pos > --sz) pos = sz; do { if (!m_find(s, n, m_data[pos])) return pos; } while (pos--); } return npos; } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::find_last_not_of(CharT c, size_type pos) const noexcept { size_type sz = this->size(); if (sz) { if (pos > --sz) pos = sz; do { if ( m_data[pos] != c) return pos; } while (pos--); } return npos; } template<typename CharT> int basic_string<CharT>::compare(size_type pos, size_type n, const basic_string& str) const { n = m_limit(pos, n); const size_type osz = str.size(); int res = m_compare(m_data + pos, str.m_data, min(n, osz)); if (!res) res = n - osz; return res; } template<typename CharT> int basic_string<CharT>::compare(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2) const { n1 = m_limit(pos1, n1); n2 = str.m_limit(pos2, n2); int res = m_compare(m_data + pos1, str.m_data + pos2, min(n1, n2)); if (!res) res = n1 - n2; return res; } template<typename CharT> int basic_string<CharT>::compare(const CharT* s) const { // const size_type sz = this->size(); // const size_type osz = strlen(s); // // int res = m_compare(m_data, s, min(sz, osz)); // if (!res) // res = sz - osz; // return res; return strcmp(m_data, s); } template<typename CharT> int basic_string<CharT>::compare(size_type pos, size_type n1, const CharT* s) const { n1 = m_limit(pos, n1); const size_type osz = strlen(s); int res = m_compare(m_data + pos, s, min(n1, osz)); if (!res) res = n1 - osz; return res; } template<typename CharT> int basic_string<CharT>::compare(size_type pos, size_type n1, const CharT* s, size_type n2) const { n1 = m_limit(pos, n1); int res = m_compare(m_data + pos, s, min(n1, n2)); if (!res) res = n1 - n2; return res; } template<typename CharT> int basic_string<CharT>::atoi() const { int res=0; if(m_data) { tmos_sscanf(m_data, "%d", &res); } return (res); } template<typename CharT> long long basic_string<CharT>::atoll() const { long long res=0; if(m_data) { tmos_sscanf(m_data, "%ld", &res); } return (res); } template<typename CharT> int basic_string<CharT>::itoa(int num) { return format("%d", num); } template<typename CharT> typename basic_string<CharT>::size_type basic_string<CharT>::find_in_list(STR_LIST sl, size_type* dwRead) const { const_pointer buf; buf = m_data; if(dwRead) buf += *dwRead; return (::find_in_list(buf, sl, dwRead)); } template<typename CharT> void basic_string<CharT>::free() { m_dispose(); m_data = const_cast<CharT*>(""); } template<typename CharT> int basic_string<CharT>::start_with( const CharT* str ) const { unsigned int len; len = strlen(str); if(length() >= len) { if(!strncmp(c_str(), str, len)) return len; } return 0; } template<typename CharT> int basic_string<CharT>::start_casewith( const CharT* str ) const { unsigned int len; len = strlen(str); if(length() >= len) { if(!strncasecmp(c_str(), str, len)) return len; } return 0; } template<typename CharT> int basic_string<CharT>::format(const CharT *fmt, ...) { va_list args; int len; va_start(args, fmt); clear(); len = tmos_vprintf_len(fmt, args); if(m_reserve(0, len)) { len = tmos_vsprintf(m_data, fmt, args); m_set_size(len); } else { len = 0; } va_end(args); return len; } template<typename CharT> int basic_string<CharT>::appendf(const CharT *fmt, ...) { va_list args; int len1, len2; va_start(args, fmt); len1 = size(); len2 = tmos_vprintf_len(fmt, args); //Approximate size if(m_reserve(len1, len1+len2)) { len2 = tmos_vsprintf(m_data + len1, fmt, args) + len1; m_set_size(len2); } else { len2 = 0; } va_end(args); return len2; } //--------------------------- operator + -------------------------------------// template<typename CharT> basic_string<CharT> operator+(const basic_string<CharT>& lhs, const basic_string<CharT>& rhs) { basic_string<CharT> str(lhs); str.append(rhs); return str; } template<typename CharT> basic_string<CharT> operator+(const CharT* lhs, const basic_string<CharT>& rhs) { typedef basic_string<CharT> __string_type; typedef typename __string_type::size_type __size_type; __size_type l1 = strlen(lhs); __size_type sz = l1 + rhs.size(); CharT* p = __string_type::m_allocate(sz, sz); if(p) { CharT* pp = p; sz -= l1; while(l1) { *pp++ = *lhs++; --l1; } lhs = rhs.c_str(); while(sz--) { *pp++ = *lhs++; } } return static_cast<__string_type>(p); } template<typename CharT> basic_string<CharT> operator+(CharT lhs, const basic_string<CharT>& rhs) { typedef basic_string<CharT> __string_type; typedef typename __string_type::size_type __size_type; __size_type sz = 1 + rhs.size(); CharT* p = __string_type::m_allocate(sz, sz); if(p) { *p = lhs; while(--sz) { p[sz] = rhs[sz-1]; } } return static_cast<__string_type>(p); } template<typename CharT> inline basic_string<CharT> operator+(const basic_string<CharT>& lhs, const CharT* rhs) { basic_string<CharT> str(lhs); str.append(rhs); return str; } template<typename CharT> inline basic_string<CharT> operator+(const basic_string<CharT>& lhs, CharT rhs) { typedef basic_string<CharT> __string_type; typedef typename __string_type::size_type __size_type; __string_type str(lhs); str.append(__size_type(1), rhs); return str; } template<typename CharT> inline basic_string<CharT> operator+(basic_string<CharT>&& lhs, const basic_string<CharT>& rhs) { return ttl::move(lhs.append(rhs)); } template<typename CharT> inline basic_string<CharT> operator+(const basic_string<CharT>& lhs, basic_string<CharT>&& rhs) { return ttl::move(rhs.insert(0, lhs)); } template<typename CharT> inline basic_string<CharT> operator+(basic_string<CharT>&& lhs, basic_string<CharT>&& rhs) { const auto sz = lhs.size() + rhs.size(); const bool __cond = (sz > lhs.capacity() && sz <= rhs.capacity()); return __cond ? ttl::move(rhs.insert(0, lhs)) : ttl::move(lhs.append(rhs)); } template<typename CharT> inline basic_string<CharT> operator+(const CharT* lhs, basic_string<CharT>&& rhs) { return ttl::move(rhs.insert(0, lhs)); } template<typename CharT> inline basic_string<CharT> operator+(CharT lhs, basic_string<CharT>&& rhs) { return ttl::move(rhs.insert(0, 1, lhs)); } template<typename CharT> inline basic_string<CharT> operator+(basic_string<CharT>&& lhs, const CharT* rhs) { return ttl::move(lhs.append(rhs)); } template<typename CharT> inline basic_string<CharT> operator+(basic_string<CharT>&& lhs, CharT rhs) { return ttl::move(lhs.append(1, rhs)); } //--------------------------- operator == ------------------------------------// template<typename CharT> inline bool operator==(const basic_string<CharT>& lhs, const basic_string<CharT>& rhs) { return lhs.compare(rhs) == 0; } template<typename CharT> inline bool operator==(const CharT* lhs, const basic_string<CharT>& rhs) { return rhs.compare(lhs) == 0; } template<typename CharT> inline bool operator==(const basic_string<CharT>& lhs, const CharT* rhs) { return lhs.compare(rhs) == 0; } //--------------------------- operator != ------------------------------------// template<typename CharT> inline bool operator!=(const basic_string<CharT>& lhs, const basic_string<CharT>& rhs) { return !(lhs == rhs); } template<typename CharT> inline bool operator!=(const CharT* lhs, const basic_string<CharT>& rhs) { return !(lhs == rhs); } template<typename CharT> inline bool operator!=(const basic_string<CharT>& lhs, const CharT* rhs) { return !(lhs == rhs); } //--------------------------- operator < -------------------------------------// template<typename CharT> inline bool operator<(const basic_string<CharT>& lhs, const basic_string<CharT>& rhs) { return lhs.compare(rhs) < 0; } template<typename CharT> inline bool operator<(const basic_string<CharT>& lhs, const CharT* rhs) { return lhs.compare(rhs) < 0; } template<typename CharT> inline bool operator<(const CharT* lhs, const basic_string<CharT>& rhs) { return rhs.compare(lhs) > 0; } //--------------------------- operator > -------------------------------------// template<typename CharT> inline bool operator>(const basic_string<CharT>& lhs, const basic_string<CharT>& rhs) { return lhs.compare(rhs) > 0; } template<typename CharT> inline bool operator>(const basic_string<CharT>& lhs, const CharT* rhs) { return lhs.compare(rhs) > 0; } template<typename CharT> inline bool operator>(const CharT* lhs, const basic_string<CharT>& rhs) { return rhs.compare(lhs) < 0; } //--------------------------- operator <= ------------------------------------// template<typename CharT> inline bool operator<=(const basic_string<CharT>& lhs, const basic_string<CharT>& rhs) { return lhs.compare(rhs) <= 0; } template<typename CharT> inline bool operator<=(const basic_string<CharT>& lhs, const CharT* rhs) { return lhs.compare(rhs) <= 0; } template<typename CharT> inline bool operator<=(const CharT* lhs, const basic_string<CharT>& rhs) { return rhs.compare(lhs) >= 0; } //--------------------------- operator >= ------------------------------------// template<typename CharT> inline bool operator>=(const basic_string<CharT>& lhs, const basic_string<CharT>& rhs) { return lhs.compare(rhs) >= 0; } template<typename CharT> inline bool operator>=(const basic_string<CharT>& lhs, const CharT* rhs) { return lhs.compare(rhs) >= 0; } template<typename CharT> inline bool operator>=(const CharT* lhs, const basic_string<CharT>& rhs) { return rhs.compare(lhs) <= 0; } template<typename CharT> inline void swap(basic_string<CharT>& lhs, basic_string<CharT>& rhs) { lhs.swap(rhs); } } // namespace ttl typedef ttl::basic_string<char> string; #endif /* TTL_STRING_H_ */
true
a5fc73a878ae3e9e23a816bda07e4fb2012c02e3
C++
Riankao/-
/百钱百鸡.cpp
GB18030
460
2.71875
3
[]
no_license
#include <stdio.h> void main() { int cocks=0, hens,chicks; while(cocks<=19) { hens=0; while(hens<=33) { chicks=100 - cocks - hens; if(5.0*cocks + 3.0*hens + chicks/3.0 == 100.0) printf("%d %d %d\n",cocks,hens,chicks); hens++; } cocks++; } } /*ʹԸһָ LΪضдȷЧij ԣдõ
true
ade9a869e5eca5b14ec090f4ac10321afeac83de
C++
goTJ/tj
/practice/acm/A/10200.cpp
WINDOWS-1252
733
2.921875
3
[]
no_license
/* @JUDGE_ID: 10319NX 10200 C++ "̯S^^" */ #include<stdio.h> int prime[1400]; int lim; int win[10002]; int is_prime(int n) { int i; for(i=0; i<lim&&prime[i]*prime[i]<=n; i++) if(!(n%prime[i])) return 0; return 1; } void make_tab(void) { int i, n=11000; lim = 1; prime[0] = 2; for(i=3; i<=n; i+=2){ if(is_prime(i)) prime[lim++] = i; } } void make_win(void) { int i; win[0] = 0; for(i=0; i<=10000; i++){ if(is_prime(i*i+i+41)) win[i+1] = win[i]+1; else win[i+1] = win[i]; } } int main(void) { int from, to; make_tab(); make_win(); while(scanf("%d%d", &from, &to) != EOF){ to++; printf("%.2lf\n", 100.0*(win[to]-win[from])/(to-from)); } return 0; } /* @END_OF_SOURCE_CODE */
true
96c6ea9efd4692fafc1922e4e3ec58bc2211f080
C++
tlegen-k/cpp-white-belt
/week-2/palindrom/main.cpp
UTF-8
391
3.515625
4
[]
no_license
#include <iostream> #include <string> using namespace std; bool IsPalindrom (string word) { string second; int size = word.size(); for ( int i=size; i>0; --i) { second += word[i-1]; } if (!second.compare(word)) { // cout << "true"; return true; } else { // cout << "false"; return false; } } int main() { string word ; cin >> word; IsPalindrom(word); return 0; }
true
8d2aa3dedde4bab6eca77c638a97284345c3aa3e
C++
aimene/SimulatedAnnealing
/SA/Statistics.cpp
UTF-8
1,149
3.609375
4
[]
no_license
#include"Statistics.h" #include<cmath> /** * \brief constructeur par defaut de la classe Statistics * \details Initialise un tableau contenant des données à traiter * * \param v \e vector tableau contenant les données */ /** * \brief constructeur par defaut de la classe Statistics * \details Initialise un tableau contenant des données à traiter * * \param v \e vector tableau contenant les données */ Statistics::Statistics(std::vector<double>& v) : _data(v) { } /** * \brief renvoie la moyenne * \return \e double la moyenne */ double Statistics::get_moyenne() const { double sum = 0.0; for(int i=0;i<_data.size();i++) { sum += _data.at(i); } return sum/_data.size(); } /** * \brief renvoie l'écart type * \param mean \e double moyenne pour éviter de la recalculer * \return \e double l'écart type */ double Statistics::get_ecart_type(double mean) const { double temp = 0.0; for(int i=0;i<_data.size();i++) { temp += (mean - _data.at(i))*(mean - _data.at(i)); } return sqrt(temp/_data.size()); }
true
ed2653a138d7dde19888b36d5d6da61793fd7978
C++
yfuxzpskbr/BeautifulAlgorithm
/05边界为1的最大子方阵优化(上)/边界为1的最大子方阵优化.cpp
GB18030
1,510
3.34375
3
[]
no_license
#include <iostream> using namespace std; void init(int arr[5][5], int help[5][5][2]); bool check(int help[5][5][2], int lefti, int leftj, int n); int max1Arr(int arr[5][5], int help[5][5][2]); int main(int argc, char* argv[]) { int arr[5][5] = { {0,1,1,1,1}, {0,1,0,1,1}, {0,1,1,1,1}, {0,1,1,1,1}, {0,0,0,0,0} }; int help[5][5][2]; cout << "߽Ϊ1ӾΪ: " << max1Arr(arr, help) << "" << endl; return 0; } //ʼ㷨 void init(int arr[5][5], int help[5][5][2]) { for (int i = 4; i >= 0; i--) { for (int j = 4; j >= 0; j--) { help[i][j][0] = 0; help[i][j][1] = 0; if (arr[i][j] == 1) { if (i + 1 >= 5)help[i][j][1] = 1;//1ʾ else help[i][j][1] = help[i + 1][j][1] + 1; if (j + 1 >= 5)help[i][j][0] = 1;//0ʾұ else help[i][j][0] = help[i][j + 1][0] + 1; } } } } //㷨 bool check(int help[5][5][2], int lefti, int leftj, int n) { int righti = lefti + n - 1; int rightj = leftj + n - 1; if (righti >= 5 || rightj >= 5)return false; if (help[lefti][leftj][0] >= n //ϱ && help[lefti][leftj][1] >= n// && help[righti][leftj][0] >= n//± && help[lefti][rightj][1] >= n)//ұ return true; return false; } //Ӿ int max1Arr(int arr[5][5], int help[5][5][2]) { init(arr, help); int ans = 5; while (ans) { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (check(help, i, j, ans))return ans; continue; } } ans--; } return 0; }
true
68babf166949f854249371817e43e64e87c89f85
C++
DracoNick0/Dungeons_and_Dragons_TextGame_Tom-s_and_Nick
/Dungeons_and_Dragons_TextGame_Tomás_and_Nick/Player.cpp
UTF-8
10,929
3.03125
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <time.h> #include <stdio.h> #include "Story.h" #include "Player.h" using namespace std; string choice2; void EnemyAttackSystem() { tempplayer Player = PlayerManager::GetPlayerManager().GetPlayer(); tempenemy Enemy = EnemyManager::GetEnemyManager().GetEnemy(); int hitchance = (rand() % 100) + 1; if (hitchance > 0 && hitchance < Enemy.EnemyHitChance) { int hitdamage = (rand() % Enemy.EnemyHitDamage) + Enemy.EnemyAddHitDamage; int critchance = (rand() % 100) + 1; if (critchance > 0 && critchance < Enemy.EnemyCritChance) { int critdamage = (rand() % Enemy.EnemyCritDamage) + Enemy.EnemyAddCritDamage; cout << "Crit! " << critdamage << "!" << endl; cout << "The enemy dealt " << hitdamage + critdamage << " damage to you." << endl; Player.PlayerHP -= hitdamage + critdamage; PlayerManager::GetPlayerManager().SetPlayer(Player); EnemyManager::GetEnemyManager().SetEnemy(Enemy); if (Player.PlayerHP <= 0) { Player.PlayerHP = 0; cout << "You take a step back and look into the enemies eyes, then fall over!" << endl << endl; cout << "Your health has reached zero... GAME OVER" << endl; Player.PlayerSkillCharge = 0; Player.PlayerisDead = true; exit(0); } if (Player.PlayerHP > 0) { cout << "You take a step back in pain." << endl; cout << "You now have " << Player.PlayerHP << " HP." << endl; } } else { cout << "The enemy dealt " << hitdamage << " damage to You." << endl; cout << "You take the hit and stunt back." << endl; Player.PlayerHP -= hitdamage; PlayerManager::GetPlayerManager().SetPlayer(Player); EnemyManager::GetEnemyManager().SetEnemy(Enemy); if (Player.PlayerHP <= 0) { Player.PlayerHP = 0; cout << "You take a step back and look into the enemies eyes, then fall over!" << endl << endl; cout << "Your health has reached zero... GAME OVER" << endl; Player.PlayerSkillCharge = 0; Player.PlayerisDead = true; exit(0); } if (Player.PlayerHP > 0) { cout << "You take a step back in pain." << endl; cout << "You now have " << Player.PlayerHP << " HP." << endl; } } } else { cout << "The enemy missed thier attack!" << endl; cout << "You still have " << Player.PlayerHP << " HP." << endl; } } void AttackSystem() { tempplayer Player = PlayerManager::GetPlayerManager().GetPlayer(); tempenemy Enemy = EnemyManager::GetEnemyManager().GetEnemy(); int i = 0; while (Player.PlayerHP > 0 || Enemy.EnemyHP > 0) { if (Player.PlayerHP <= 0) { exit(0); } if (i > 0) { cout << endl << "The enemy stands unguarded, what do you do?" << endl; } cout << "1. Attack" << endl; cout << "2. Special Attack" << endl; i++; float choice; cin >> choice; if (choice == 1) { Player.PlayerSkillCharge++; if (Player.PlayerSkillCharge > 10) { Player.PlayerSkillCharge = 10; } cout << endl << "You chose to Attack." << endl; int hitchance = (rand() % 100) + 1; if (hitchance > 0 && hitchance < Player.PlayerHitChance) { int hitdamage = (rand() % Player.PlayerHitDamage) + Player.PlayerAddHitDamage; int critchance = (rand() % 100) + 1; if (critchance > 0 && critchance < Player.PlayerCritChance) { int critdamage = (rand() % Player.PlayerCritDamage) + Player.PlayerAddCritDamage; cout << "Crit! " << critdamage << "!" << endl; cout << "You dealt " << hitdamage + critdamage << " damage to the enemy." << endl; Enemy.EnemyHP -= hitdamage + critdamage; if (Enemy.EnemyHP <= 0) { Enemy.EnemyHP = 0; cout << "The enemy takes a step back, looks into your eyes, then falls down dead... You WIN!" << endl << endl; Player.PlayerSkillCharge = 0; Enemy.EnemyisDead = true; break; } if (Enemy.EnemyHP > 0) { cout << "The enemy takes a step back in pain." << endl; cout << "The enemy now has " << Enemy.EnemyHP << " HP." << endl; cout << "Your skill charge is now " << Player.PlayerSkillCharge << endl << endl; } } else { cout << "You dealt " << hitdamage << " damage to the enemy." << endl; Enemy.EnemyHP -= hitdamage; if (Enemy.EnemyHP <= 0) { Enemy.EnemyHP = 0; cout << "The enemy takes a step back, looks into your eyes, then falls down dead... You WIN!" << endl << endl; Player.PlayerSkillCharge = 0; Enemy.EnemyisDead = true; break; } if (Enemy.EnemyHP > 0) { cout << "The enemy flinches at your attack." << endl; cout << "The enemy now has " << Enemy.EnemyHP << " HP." << endl; cout << "Your skill charge is now " << Player.PlayerSkillCharge << endl << endl; } } } else { cout << "You miss your attack, the enemy scoffs at your puny arm swing!" << endl; cout << "The enemy still has " << Enemy.EnemyHP << " HP left." << endl; cout << "Your skill charge is now " << Player.PlayerSkillCharge << endl << endl; } } else if (choice == 2) { if (Player.PlayerSkillCharge >= 2) { cout << endl << "Which skill you like to use?" << endl; cout << "1. " << Player.PlayerSkill1 << endl; cout << "2. " << Player.PlayerSkill2 << endl; cout << "3. " << Player.PlayerSkill3 << endl; if (Player.PlayerSkillCharge > 10) { Player.PlayerSkillCharge = 10; } int temp = 0; while (temp == 0) { cin >> choice2; if (choice2 == Player.PlayerSkill1 && Player.PlayerSkillCharge >= 2) { temp = 1; Player.PlayerSkillCharge -= 2; cout << endl << "You chose " << Player.PlayerSkill1 << "." << endl; cout << "You dealt " << Player.PlayerSkill1Damage << endl; Enemy.EnemyHP -= Player.PlayerSkill1Damage; if (Enemy.EnemyHP <= 0) { Enemy.EnemyHP = 0; cout << "The enemy takes a step back, looks into your eyes, then falls down dead... You WIN!" << endl; Player.PlayerSkillCharge = 0; Enemy.EnemyisDead = true; break; } if (Enemy.EnemyHP > 0) { temp = 1; cout << "The enemy takes a step back in deep pain. " << endl; cout << "The enemy now has " << Enemy.EnemyHP << " HP." << endl; cout << "Your skill charge is now " << Player.PlayerSkillCharge << endl << endl; } } else if (choice2 == Player.PlayerSkill2 && Player.PlayerSkillCharge >= 3) { temp = 1; Player.PlayerSkillCharge -= 3; cout << endl << "You chose " << Player.PlayerSkill2 << "." << endl; cout << "You dealt " << Player.PlayerSkill2Damage << endl; Enemy.EnemyHP -= Player.PlayerSkill2Damage; if (Enemy.EnemyHP <= 0) { Enemy.EnemyHP = 0; cout << "The enemy takes a step back, looks into your eyes, then falls down dead... You WIN!" << endl; Player.PlayerSkillCharge = 0; Enemy.EnemyisDead = true; break; } if (Enemy.EnemyHP > 0) { temp = 1; cout << "The enemy takes a step back in deep pain. " << endl; cout << "The enemy now has " << Enemy.EnemyHP << " HP." << endl; cout << "Your skill charge is now " << Player.PlayerSkillCharge << endl << endl; } } else if (choice2 == Player.PlayerSkill3 && Player.PlayerSkillCharge >= 4) { temp = 1; Player.PlayerSkillCharge -= 4; cout << endl << "You chose " << Player.PlayerSkill3 << "." << endl; cout << "You dealt " << Player.PlayerSkill3Damage << endl; Enemy.EnemyHP -= Player.PlayerSkill3Damage; if (Enemy.EnemyHP <= 0) { Enemy.EnemyHP = 0; cout << "The enemy takes a step back, looks into your eyes, then falls down dead... You WIN!" << endl; Player.PlayerSkillCharge = 0; Enemy.EnemyisDead = true; break; } if (Enemy.EnemyHP > 0) { temp = 1; cout << "The enemy takes a step back stunned... " << endl; cout << "The enemy now has " << Enemy.EnemyHP << " HP." << endl; cout << "Your skill charge is now " << Player.PlayerSkillCharge << endl << endl; } } else { temp = 0; cout << "This is not a skill, please pick again." << endl; } if (Enemy.EnemyHP <= 0) { break; } } if (Enemy.EnemyHP <= 0) { break; } } else { cout << "This is not an option, please recharge your skills before using them." << endl; } } else { cout << endl << "You wasted your attack." << endl; } EnemyAttackSystem(); } PlayerManager::GetPlayerManager().SetPlayer(Player); EnemyManager::GetEnemyManager().SetEnemy(Enemy); } PlayerManager::PlayerManager() { player = new tempplayer; } PlayerManager::~PlayerManager() { if (player != nullptr) { //delete player; } } PlayerManager PlayerManager::GetPlayerManager() { static PlayerManager manager; return manager; } tempplayer PlayerManager::GetPlayer() { return *player; } void PlayerManager::SetPlayer(tempplayer newPlayer) { if (player != nullptr) { player->playerType = newPlayer.playerType; player->PlayerisDead = newPlayer.PlayerisDead; player->PlayerHP = newPlayer.PlayerHP; player->PlayerArmor = newPlayer.PlayerArmor; player->PlayerHitChance = newPlayer.PlayerHitChance; player->PlayerHitDamage = newPlayer.PlayerHitDamage; player->PlayerAddHitDamage = newPlayer.PlayerAddHitDamage; player->PlayerCritChance = newPlayer.PlayerCritChance; player->PlayerCritDamage = newPlayer.PlayerCritDamage; player->PlayerAddCritDamage = newPlayer.PlayerAddCritDamage; player->PlayerDodge = newPlayer.PlayerDodge; player->PlayerSkillCharge = newPlayer.PlayerSkillCharge; player->PlayerSkill1 = newPlayer.PlayerSkill1; player->PlayerSkill2 = newPlayer.PlayerSkill2; player->PlayerSkill3 = newPlayer.PlayerSkill3; player->PlayerSkill1Damage = newPlayer.PlayerSkill1Damage; player->PlayerSkill2Damage = newPlayer.PlayerSkill2Damage; player->PlayerSkill3Damage = newPlayer.PlayerSkill3Damage; } } //Enemy EnemyManager::EnemyManager() { enemy = new tempenemy; } EnemyManager::~EnemyManager() { if (enemy != nullptr) { //delete enemy; } } EnemyManager EnemyManager::GetEnemyManager() { static EnemyManager manager; return manager; } tempenemy EnemyManager::GetEnemy() { return *enemy; } void EnemyManager::SetEnemy(tempenemy newEnemy) { if (enemy != nullptr) { enemy->EnemyArmor = newEnemy.EnemyArmor; enemy->EnemyCritChance = newEnemy.EnemyCritChance; enemy->EnemyCritDamage = newEnemy.EnemyCritDamage; enemy->EnemyDodge = newEnemy.EnemyDodge; enemy->EnemyHitChance = newEnemy.EnemyHitChance; enemy->EnemyHitDamage = newEnemy.EnemyHitDamage; enemy->EnemyHP = newEnemy.EnemyHP; enemy->EnemyisDead = newEnemy.EnemyisDead; enemy->enemyType = newEnemy.enemyType; enemy->EnemyAddHitDamage = newEnemy.EnemyAddHitDamage; enemy->EnemyAddCritDamage = newEnemy.EnemyAddCritDamage; } }
true
8c01382a3eb13e9fadd6bac293b0bb0956d178df
C++
ankithans/leetcode-submissions
/trees/236. Lowest Common Ancestor of a Binary Tree.cpp
UTF-8
1,348
3.03125
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; void inputOutput() { #ifndef ONLINE_JUDGE freopen("../input.txt", "r", stdin); freopen("../output.txt", "w", stdout); #endif } class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == NULL) return NULL; if (root -> val == p -> val || root -> val == q -> val) return root; TreeNode *leftLCA = lowestCommonAncestor(root -> left, p, q); TreeNode *rightLCA = lowestCommonAncestor(root -> right, p, q); if (leftLCA == NULL) return rightLCA; if (rightLCA == NULL) return leftLCA; return root; } }; class Solution { public: bool findPath(TreeNode *root, vector<TreeNode *> &v, int n) { if (root == NULL) return false; v.push_back(root); if (root -> val == n) return true; if (findPath(root -> left, v, n) || findPath(root -> right, v, n)) return true; v.pop_back(); return false; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { vector<TreeNode *> path1, path2; if (findPath(root, path1, p -> val) == false || findPath(root, path2, q -> val) == false) return NULL; for (int i = 0; i < path1.size() - 1 && i < path2.size() - 1; i++) { if (path1[i + 1] != path2[i + 1]) return path1[i]; } return NULL; } }; int main() { inputOutput(); return 0; }
true
752c1e4a236ca884ac726dac7811c3370ab4084e
C++
tudb/Bka_exercises
/Geometry/Polygon.h
WINDOWS-1258
936
2.890625
3
[]
no_license
#pragma once #include "PointBase.h" //----------------------------------------------------------------- // Name: Polygon // Description: Biu din lp a giac, k tha cac phng thc cua // lp PointBase, gm 2 thuc tinh la m_byAmuont: s im // cua a giac, con tro m_pPolygon tro ti mang gm m_byAmount // im la i tng cua lp PointBase //----------------------------------------------------------------- class Polygon : public PointBase{ private : int m_byAmount; PointBase *m_pPolygon; public : Polygon(); Polygon(int m_byAmount, PointBase *m_pPolygon); ~Polygon(); int getAmount(); void setAmount(int m_byAmount); void setPolygon(PointBase *m_pPolygon); PointBase* getPolygon(); void import(); void display(); Polygon translatinal(Vector vector); Polygon turn(float fAlpha); Polygon zoom(float fCoefficient); };
true
601da09f2464fbba588265de15f6f7d30c70a015
C++
SimonMederer/saiga
/src/saiga/core/util/BinaryFile.h
UTF-8
1,413
3.1875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/** * Copyright (c) 2017 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #pragma once #include "saiga/config.h" #include <fstream> #include <vector> namespace Saiga { /** * Usage Reading: * * BinaryFile bf(file, std::ios_base::in); * int id; * bf >> id; * * Usage Writing: * * BinaryFile bf(file, std::ios_base::out); * bf << id; */ struct BinaryFile { BinaryFile(const std::string& file, std::ios_base::openmode __mode = std::ios_base::in) : strm(file, std::ios::binary | __mode) { } template <typename T> void write(const T& v) { strm.write(reinterpret_cast<const char*>(&v), sizeof(T)); } template <typename T> void write(const std::vector<T>& vec) { write((size_t)vec.size()); for (auto& v : vec) write(v); } template <typename T> void read(std::vector<T>& vec) { size_t s; read(s); vec.resize(s); for (auto& v : vec) read(v); } template <typename T> void read(T& v) { strm.read(reinterpret_cast<char*>(&v), sizeof(T)); } template <typename T> BinaryFile& operator<<(const T& v) { write(v); return *this; } template <typename T> BinaryFile& operator>>(T& v) { read(v); return *this; } std::fstream strm; }; } // namespace Saiga
true
082226f427df6b83cc2bdab812720b3f490621f8
C++
kdbohne/pt
/src/sampling.cpp
UTF-8
3,022
2.5625
3
[ "MIT", "BSD-2-Clause" ]
permissive
#include "sampling.h" #include "math.h" float uniform_float() { // TODO: improve? return (float)drand48(); } Vector3f uniform_sample_sphere(const Point2f &u) { float z = 1 - 2 * u[0]; float r = std::sqrt(std::max((float)0, (float)1 - z * z)); float phi = 2 * PI * u[1]; return Vector3f(r * std::cos(phi), r * std::sin(phi), z); } Point2f uniform_sample_triangle(const Point2f &u) { float su0 = std::sqrt(u[0]); return Point2f(1 - su0, u[1] * su0); } Point2f concentric_sample_disk(const Point2f &u) { Point2f u_offset = (float)2 * u - Vector2f(1, 1); if ((u_offset.x == 0) && (u_offset.y == 0)) return Point2f(0, 0); float r, theta; if (std::abs(u_offset.x) > std::abs(u_offset.y)) { r = u_offset.x; theta = PI_OVER_4 * (u_offset.y / u_offset.x); } else { r = u_offset.y; theta = PI_OVER_2 - PI_OVER_4 * (u_offset.x / u_offset.y); } return r * Point2f(std::cos(theta), std::sin(theta)); } Vector3f cosine_sample_hemisphere(const Point2f &u) { Point2f d = concentric_sample_disk(u); float z = std::sqrt(std::max((float)0, 1 - d.x * d.x - d.y * d.y)); return Vector3f(d.x, d.y, z); } float uniform_cone_pdf(float cos_theta_max) { return 1 / (2 * PI * (1 - cos_theta_max)); } Distribution1d::Distribution1d(const float *f, int n) : func(f, f + n), cdf(n + 1) { cdf[0] = 0; for (int i = 1; i < n + 1; ++i) cdf[i] = cdf[i - 1] + func[i - 1] / n; func_int = cdf[n]; if (func_int == 0) { for (int i = 1; i < n + 1; ++i) cdf[i] = (float)i / (float)n; } else { for (int i = 1; i < n + 1; ++i) cdf[i] /= func_int; } } float Distribution1d::sample_continuous(float u, float *pdf, int *offset) const { int off = find_interval((int)cdf.size(), [&](int index) { return cdf[index] <= u; }); if (offset) *offset = off; float du = u - cdf[off]; if ((cdf[off + 1] - cdf[off]) > 0) { assert(cdf[off + 1] > cdf[off]); du /= (cdf[off + 1] - cdf[off]); } assert(!std::isnan(du)); if (pdf) *pdf = (func_int > 0) ? func[off] / func_int : 0; int count = (int)func.size(); return (off + du) / count; } Distribution2d::Distribution2d(float *func, int nu, int nv) { p_conditional_v.reserve(nv); for (int v = 0; v < nv; ++v) p_conditional_v.emplace_back(new Distribution1d(&func[v * nu], nu)); std::vector<float> marginal_func; marginal_func.reserve(nv); for (int v = 0; v < nv; ++v) marginal_func.push_back(p_conditional_v[v]->func_int); p_marginal = new Distribution1d(&marginal_func[0], nv); } Point2f Distribution2d::sample_continuous(const Point2f &u, float *pdf) const { float pdfs[2]; int v; float d1 = p_marginal->sample_continuous(u[1], &pdfs[1], &v); float d0 = p_conditional_v[v]->sample_continuous(u[0], &pdfs[0]); *pdf = pdfs[0] * pdfs[1]; return Point2f(d0, d1); }
true
7704bdb5db10fb0516b2e5df8fb54361c872da96
C++
pingsoli/cpp
/basics/final_keyword.cpp
UTF-8
790
3.390625
3
[]
no_license
// Avoid inherited from my class ? // add final specifier behind base class name. // // Avoid derived class override member function ? // add final specifier to member function of base class. // // Note: put `final` specifier behind function name or class name. #include <iostream> // struct ForbidInheriteFrom final { // }; // // struct Test : public ForbidInheriteFrom { // won't compile // }; struct Base { virtual void foo() final { std::cout << "Base::foo()" << '\n'; } }; struct Derived : public Base { // virtual void foo() { std::cout << "Derived::foo()" << '\n'; } }; int main(int argc, char *argv[]) { { // forbid inherited from base class } { // forbid derived class override member function Base *p = new Derived; p->foo(); } return 0; }
true
a62059df13ead08eead707075953cc87d85dec2d
C++
electronicvisions/tutorial-bss2
/code/spike_counter_loop.cc
UTF-8
1,312
2.84375
3
[]
no_license
#include <stddef.h> #include <stdint.h> extern "C" { #include "libnux/counter.h" #include "libnux/dls.h" #include "libnux/spr.h" #include "libnux/time.h" } extern uint8_t ram_end; // This program reads out neuron-local spike counters in a loop. The per-neuron accumulation is // stored to a defined memory address range after reading for a defined timeframe for readout from // the host. // Program entry point extern "C" int start() { // Spike count accumulator storage uint32_t spike_counts[dls_num_columns]; for (uint32_t& count: spike_counts) { count = 0; } // Timeframe of spike count measurement time_base_t constexpr timeframe = 10000000; // Sleep period [cycles] between consecutive readouts uint32_t constexpr sleep_period = 10000; // Reset counters to only measure spikes emitted during the loop below reset_all_neuron_counters(); // Read spike count and accumulate while (get_time_base() < timeframe) { for (size_t nrn = 0; nrn < dls_num_columns; ++nrn) { uint32_t count = get_neuron_counter(nrn); spike_counts[nrn] += count; } sleep_cycles(sleep_period); } // Write results to end of RAM uint32_t* pos = reinterpret_cast<uint32_t*>(&ram_end) - dls_num_columns; for (size_t i = 0; i < dls_num_columns; ++i) { *pos = spike_counts[i]; pos++; } return 0; }
true
ebb45b41ff7f9d6f8ad8ea7bc4ce53080fb3ea00
C++
ShuyiLU/leetcode
/leetcode-algorithms/560. Subarray Sum Equals/560. Subarray Sum Equals K.cpp
UTF-8
2,074
3.390625
3
[]
no_license
#include<iostream> #include<vector> #include<map> using namespace std; /* class Solution { public: int subarraySum(vector<int>& nums, int k) { int n = nums.size(); if(n == 0) return 0; if(n == 1){ if(nums[0] == k) return 1; else return 0; } int cnt = 0; vector<vector<int> > v; //v[i][j]: i~j's sum v.resize(n); for(int i=0; i<n; i++) v[i].resize(n); for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ // cout << i << " " << j << endl; if(i>j) v[i][j] = -1; else if(i == j) { v[i][j] = nums[i]; if(v[i][j] == k) cnt++; } else{ v[i][j] = v[i][j-1] + nums[j]; if(v[i][j] == k) cnt++; } } } return cnt; } }; */ /* class Solution { public: int subarraySum(vector<int>& nums, int k) { int n = nums.size(); if(n == 0) return 0; if(n == 1){ if(nums[0] == k) return 1; else return 0; } int cnt = 0; vector<int> sum(n); //sum[i]: 0~i th's sum for(int i=0; i<n; i++){ if(i == 0) sum[i] = nums[0]; else sum[i] = sum[i-1] + nums[i]; } for(int i=0; i<n; i++){ for(int j=i; j<n; j++){ if(j<j){ continue; //3cout << "a" << endl; } else if(i == j){ if(sum[i] == k){ // cout << i << " " << j << endl; cnt++; } } else{ if(sum[j] - sum[i] == k) { // cout << i << " " << j << endl; cnt++; } } } } return cnt; } }; */ class Solution { public: int subarraySum(vector<int>& nums, int k) { int n = nums.size(); if(n == 0) return 0; if(n == 1){ if(nums[0] == k) return 1; else return 0; } int cnt = 0; int sum = 0; map<int, int> m; m[0] = 1; for(int i=0; i<n; i++){ sum += nums[i]; cnt += m[sum-k]; m[sum] += 1; } return cnt; } }; int main(){ int n; int k; cin >> n >> k; int a; vector<int> v; for(int i=0; i<n; i++){ cin >> a; v.push_back(a); } Solution sol; cout << sol.subarraySum(v, k) << endl; }
true
042e11069da61ced9aeb8f7ff9db12450cbbdb10
C++
yuebaixiao/cpp_template
/lambda01.cpp
UTF-8
1,749
3.84375
4
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ //test1 值捕获 /* int i = 1; auto f = [i]{return i;}; i = 10; int j = f(); cout << j << endl; */ //test2 引用捕获 /* int i = 1; auto f = [&i]{return i;}; i = 10; int j = f(); cout << j << endl;//3 */ //test3 隐式值捕获 /* int i = 1; int j = 2; auto f = [=]{return i + j;}; i = 3; int m = f(); cout << m << endl; */ //test4 隐式引用捕获 /* int i = 1; int j = 2; auto f = [&]{return i + j;}; i = 3; int m = f(); cout << m << endl;//5 */ //test5 隐式,显式混合1 /* int i = 1; int j = 2; //i为值捕获,j为引用捕获 auto f = [=,&j]{return i + j;}; i = 3; int m = f(); cout << m << endl;//3 */ //test5 隐式,显式混合2 /* int i = 1; int j = 2; //i为引用捕获,j为值捕获 auto f = [&,j]{return i + j;}; i = 3; int m = f(); cout << m << endl;//5 */ //test6 可变lambda /* int i = 10; auto f = [i] () mutable{return ++i;}; int j = f(); cout << j << endl; */ /* const int i = 10; //编译错误,因为i为const auto f = [i] () mutable{return ++i;}; int j = f(); cout << j << endl; */ //test7 lambda的返回类型 vector<int> ivec{-12,2,-22,3,0}; //改变ivec里的值,负数变成整数 //此lambda不写返回类型没有问题. //transform(ivec.begin(),ivec.end(),ivec.begin(), // [](int i){return i < 0 ? -i : i;}); //此lambda不写返回类型也没有问题. transform(ivec.begin(),ivec.end(),ivec.begin(), [](int i){if(i < 0) return -i; else return i;}); for(const auto &s : ivec){ cout << s << " "; } cout << endl; }
true
a184466eb3445fa44216794051f7dc6cd208c49c
C++
makut/MIPT-hw
/Tuple/Tuple.h
UTF-8
9,592
3.140625
3
[]
no_license
# include <utility> # include <cstddef> # include <type_traits> template<typename... TArgs> class Tuple; template<size_t Ind, typename TFirst, typename... TEnd> struct getByInd { typedef typename getByInd<Ind - 1, TEnd...>::type type; }; template<typename TFirst, typename... TEnd> struct getByInd<0, TFirst, TEnd...> { typedef TFirst type; }; template<size_t Ind, typename... Types> using IndType = typename getByInd<Ind, Types...>::type; template<size_t Ind, typename... Types> using NonZeroIndType = typename std::enable_if<Ind != 0, IndType<Ind, Types...> >::type; template<size_t Ind, typename... Types> using ZeroIndType = typename std::enable_if<Ind == 0, IndType<Ind, Types...> >::type; template<typename T1, typename T2> using CheckSame = typename std::enable_if<std::is_same<T1, T2>::value, T1>::type; template<typename T1, typename T2> using CheckDiff = typename std::enable_if<!std::is_same<T1, T2>::value, T1>::type; template<typename T1, typename T2> struct Join {}; template<typename... TFirst, typename... TSecond> struct Join<Tuple<TFirst...>, Tuple<TSecond...> > { using type = Tuple<TFirst..., TSecond...>; }; template<typename T> using DelRef = typename std::remove_reference<T>::type; template<typename Tuple1, typename Tuple2> using JoinedTuple = typename Join<DelRef<Tuple1>, DelRef<Tuple2> >::type; template<typename TFirst, typename... TEnd> class Tuple<TFirst, TEnd...> { public: Tuple() : val_(), end_() {} Tuple(const Tuple&) = default; Tuple(Tuple&&) = default; Tuple& operator=(const Tuple&) = default; Tuple& operator=(Tuple&&) = default; Tuple(const TFirst &first, const TEnd&... end) : val_(first), end_(end...) {} template<typename TOtherFirst, typename... TOtherEnd, typename = typename std::enable_if< !std::is_same<typename std::decay<TOtherFirst>::type, Tuple>::value || sizeof...(TOtherEnd) >::type > explicit Tuple(TOtherFirst&& first, TOtherEnd&&... end): val_(std::forward<TOtherFirst>(first)), end_(std::forward<TOtherEnd>(end)...) {} ~Tuple() = default; void swap(Tuple &other) { Tuple tmp = std::move(other); other = std::move(*this); *this = std::move(tmp); } template<size_t Ind, typename... Types> friend constexpr ZeroIndType<Ind, Types...>& get(Tuple<Types...>&); template<size_t Ind, typename... Types> friend constexpr NonZeroIndType<Ind, Types...>& get(Tuple<Types...>&); template<size_t Ind, typename... Types> friend constexpr const ZeroIndType<Ind, Types...>& get(const Tuple<Types...>&); template<size_t Ind, typename... Types> friend constexpr const NonZeroIndType<Ind, Types...>& get(const Tuple<Types...>&); template<size_t Ind, typename... Types> friend constexpr ZeroIndType<Ind, Types...>&& get(Tuple<Types...>&&); template<size_t Ind, typename... Types> friend constexpr NonZeroIndType<Ind, Types...>&& get(Tuple<Types...>&&); template<typename T, typename TStart, typename... TFinish> friend constexpr CheckSame<T, TStart>& get(Tuple<TStart, TFinish...>&); template<typename T, typename TStart, typename... TFinish> friend constexpr CheckDiff<T, TStart>& get(Tuple<TStart, TFinish...>&); template<typename T, typename TStart, typename... TFinish> friend constexpr const CheckSame<T, TStart>& get(const Tuple<TStart, TFinish...>&); template<typename T, typename TStart, typename... TFinish> friend constexpr const CheckDiff<T, TStart>& get(const Tuple<TStart, TFinish...>&); template<typename T, typename TStart, typename... TFinish> friend constexpr CheckSame<T, TStart>&& get(Tuple<TStart, TFinish...>&&); template<typename T, typename TStart, typename... TFinish> friend constexpr CheckDiff<T, TStart>&& get(Tuple<TStart, TFinish...>&&); template<typename T1, typename... Tail1, typename T2, typename... Tail2> friend constexpr bool operator==(const Tuple<T1, Tail1...>&, const Tuple<T2, Tail2...>&); template<typename T1, typename... Tail1, typename T2, typename... Tail2> friend constexpr bool operator<(const Tuple<T1, Tail1...>&, const Tuple<T2, Tail2...>&); template<typename Tuple1, typename Tuple2> constexpr typename std::enable_if<!DelRef<Tuple1>::empty_, JoinedTuple<Tuple1, Tuple2> >::type friend concatenateTwo(Tuple1&&, Tuple2&&); private: TFirst val_; Tuple<TEnd...> end_; constexpr static const bool empty_ = false; }; template<> class Tuple<> { public: Tuple() = default; Tuple(const Tuple&) = default; Tuple(Tuple&&) = default; Tuple& operator=(const Tuple&) = default; Tuple& operator=(Tuple&&) = default; ~Tuple() = default; void swap(Tuple&) {} template<typename Tuple2> constexpr DelRef<Tuple2> concatenateTwo(const Tuple<>&, Tuple2&& tuple2); private: constexpr static const bool empty_ = true; }; template<class T> struct UnwrapRefwrapper { using type = T; }; template<class T> struct UnwrapRefwrapper<std::reference_wrapper<T> > { using type = T&; }; template<class T> using SpecialDecay = typename UnwrapRefwrapper<typename std::decay<T>::type>::type; template <class... Types> auto makeTuple(Types&&... args) { return Tuple<SpecialDecay<Types>...>(std::forward<Types>(args)...); } template<size_t Ind, typename... Types> constexpr NonZeroIndType<Ind, Types...>& get(Tuple<Types...> &tuple) { return get<Ind - 1>(tuple.end_); } template<size_t Ind, typename... Types> constexpr ZeroIndType<Ind, Types...>& get(Tuple<Types...> &tuple) { return tuple.val_; } template<size_t Ind, typename... Types> constexpr const NonZeroIndType<Ind, Types...>& get(const Tuple<Types...> &tuple) { return get<Ind - 1>(tuple.end_); } template<size_t Ind, typename... Types> constexpr const ZeroIndType<Ind, Types...>& get(const Tuple<Types...> &tuple) { return tuple.val_; } template<size_t Ind, typename... Types> constexpr NonZeroIndType<Ind, Types...>&& get(Tuple<Types...>&& tuple) { return std::move(get<Ind - 1>(std::move(tuple.end_))); } template<size_t Ind, typename... Types> constexpr ZeroIndType<Ind, Types...>&& get(Tuple<Types...>&& tuple) { return std::move(tuple.val_); } template<typename T, typename TFirst, typename... TEnd> constexpr CheckDiff<T, TFirst>& get(Tuple<TFirst, TEnd...> &tuple) { return get<T>(tuple.end_); } template<typename T, typename TFirst, typename... TEnd> constexpr CheckSame<T, TFirst>& get(Tuple<TFirst, TEnd...> &tuple) { return tuple.val_; } template<typename T, typename TFirst, typename... TEnd> constexpr const CheckDiff<T, TFirst>& get(const Tuple<TFirst, TEnd...> &tuple) { return get<T>(tuple.end_); } template<typename T, typename TFirst, typename... TEnd> constexpr const CheckSame<T, TFirst>& get(const Tuple<TFirst, TEnd...> &tuple) { return tuple.val_; } template<typename T, typename TFirst, typename... TEnd> constexpr CheckDiff<T, TFirst>&& get(Tuple<TFirst, TEnd...> &&tuple) { return std::move(get<T>(std::move(tuple.end_))); } template<typename T, typename TFirst, typename... TEnd> constexpr CheckSame<T, TFirst>&& get(Tuple<TFirst, TEnd...> &&tuple) { return std::move(tuple.val_); } constexpr bool operator==(const Tuple<>&, const Tuple<>&) { return true; } template<typename T1, typename... Tail1, typename T2, typename... Tail2> constexpr bool operator==(const Tuple<T1, Tail1...> &first, const Tuple<T2, Tail2...> &second) { return (first.val_ == second.val_ && first.end_ == second.end_); } constexpr bool operator<(const Tuple<>&, const Tuple<>&) { return false; } template<typename T1, typename... Tail1, typename T2, typename... Tail2> constexpr bool operator<(const Tuple<T1, Tail1...> &first, const Tuple<T2, Tail2...> &second) { static_assert(sizeof...(Tail1) == sizeof...(Tail2), "Different sizes tuples are incomparable"); return (first.val_ < second.val_ || (first.val_ == second.val_ && first.end_ < second.end_)); } template<typename... Types1, typename... Types2> constexpr bool operator!=(const Tuple<Types1...> &first, const Tuple<Types2...> &second) { return !(first == second); } template<typename... Types1, typename... Types2> constexpr bool operator>(const Tuple<Types1...> &first, const Tuple<Types2...> &second) { return second < first; } template<typename... Types1, typename... Types2> constexpr bool operator<=(const Tuple<Types1...> &first, const Tuple<Types2...> &second) { return (first < second || first == second); } template<typename... Types1, typename... Types2> constexpr bool operator>=(const Tuple<Types1...> &first, const Tuple<Types2...> &second) { return (first > second || first == second); } template<typename Tuple1, typename Tuple2> constexpr typename std::enable_if<!DelRef<Tuple1>::empty_, JoinedTuple<Tuple1, Tuple2> >::type concatenateTwo(Tuple1&& tuple1, Tuple2&& tuple2) { return JoinedTuple<Tuple1, Tuple2>(std::forward<decltype(tuple1.val_)>(tuple1.val_), concatenateTwo(std::forward<decltype(tuple1.end_)>(tuple1.end_), std::forward<Tuple2>(tuple2))); } template<typename Tuple2> constexpr DelRef<Tuple2> concatenateTwo(const Tuple<>&, Tuple2&& tuple2) { return std::forward<Tuple2>(tuple2); } template<typename Tuple1> DelRef<Tuple1> tupleCat(Tuple1&& tuple1) { return std::forward<Tuple1>(tuple1); } template<typename Tuple, typename... Tail> auto tupleCat(Tuple&& tuple, Tail... tail) { return concatenateTwo(std::forward<Tuple>(tuple), tupleCat(tail...)); }
true