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
0d119f5f447af20f2cbd2b4db4cec216541e305b
C++
Acka1357/ProblemSolving
/BeakjoonOJ/16000/16115_팬이에요.cpp
UTF-8
1,119
2.890625
3
[]
no_license
#include <stdio.h> #include <math.h> #include <algorithm> using namespace std; const double eps = 1e-13; const double PI = acos(0.0) * 2.0; struct Point{ long long x, y; Point(){}; Point(long long x, long long y): x(x), y(y){} long long operator * (const Point &o)const{ return (x * o.x) + (y * o.y); } Point operator - (const Point &o)const{ return Point(x - o.x, y - o.y); } long long sqlen(){ return x * x + y * y; } double len(){ return sqrt(sqlen()); } }; double angle(Point &l, Point &c, Point &r){ return acos(min(1.0, max(-1.0, (l * r) / (l.len() * r.len())))) * 180 / PI; } Point o(0, 0); Point p[300001]; int main() { int N, idx = 0; scanf("%d", &N); long long maxl = 0; for(int i = 0; i < N; i++){ scanf("%lld %lld", &p[i].x, &p[i].y); if(maxl < p[i].sqlen()){ maxl = p[i].sqlen(); idx = i; } } int past = idx; double ans = 0; for(int i = 1; i <= N; i++) if(p[(idx + i) % N].sqlen() == maxl){ ans = max(ans, angle(p[past], o, p[(idx + i) % N])); past = (idx + i) % N; printf("%.10lf\n", ans); } printf("%.10lf\n", ans < eps ? 360 : ans); return 0; }
true
bf62bc237998fe9004ae0aca1764c988a0ce35f5
C++
invrev/hello_world_ints
/linked_list/reorder_linked_list.cpp
UTF-8
2,257
3.859375
4
[]
no_license
#include<iostream> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode (int x) : val(x),next (NULL) {} }; //L : l0->l1->l2->.....->ln-1->ln //l0->ln->l1->ln-1 //In place w/o altering the node values //1. break the list into half //2. reverse the second half //3. merge the linked list alternatively. void print_list (ListNode* head) { while (head != NULL) { cout << head->val << ","; head = head->next; } cout << endl; } ListNode *reverseList (ListNode *head) { if (head == 0) { return head; } ListNode* current = head; ListNode* prev = 0; ListNode* front = 0; while (current != 0) { front = current->next; current->next = prev; prev = current; current = front; } return prev; } ListNode *reorderList (ListNode* head) { int len = 0; if (head == 0 || head->next == 0) { return head; } ListNode *tmp = head; while (tmp != 0) { tmp = tmp->next; len ++; } int half_len = len / 2; //cout << "half_len " << half_len << endl; ListNode *h1 = head; while (half_len > 0) { h1 = h1->next; half_len -= 1; } ListNode *h2 = h1->next; h1->next = NULL; ListNode* h2_rev = reverseList (h2); //print_list (head); //print_list (h2_rev); half_len = len / 2; ListNode* tmp_head = head; while (half_len > 0 ) { ListNode* tmp_next = tmp_head->next; tmp_head->next = h2_rev; ListNode* h2_next = h2_rev->next; h2_rev->next = tmp_next; tmp_head = tmp_next; h2_rev = h2_next; half_len -= 1; } //print_list (head); return head; } ListNode* create_list (int a[] , int n) { ListNode *head = NULL; for (int i=0;i<n;i++) { ListNode *tmp = new ListNode(a[i]); if (head == NULL) { head = tmp; } else { tmp->next = head; head = tmp; } } return head; } int main () { int a[] = { 5,4,3,2,1 }; int len = sizeof(a)/sizeof(a[0]); ListNode* head = create_list (a,len); print_list (head); ListNode* new_head = reorderList (head); //print_list (new_head); }
true
12e695040b1adc802b28a78e95ebb62a485c78b7
C++
KVSG-Keerthika/Smart-Door-Lock-System-During-Covid-19-Pandemic
/Smart-Door-Lock-System-During-Covid-19-Pandemic.ino
UTF-8
4,281
2.984375
3
[]
no_license
//smartdoorlock system #include <LiquidCrystal.h> #include <Servo.h> #include <Keypad.h> Servo myservo; int pos=0; // position of servo motor LiquidCrystal lcd(13,12,11,10,8,7); const byte rows=4; const byte cols=3; int temp; char key[rows][cols]={ {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'*','0','#'} }; byte rowPins[rows]={0,1,2,3}; byte colPins[cols]={4,5,6}; Keypad keypad= Keypad(makeKeymap(key),rowPins,colPins,rows,cols); char* password="0123"; int currentposition=0; void setup() { //displayscreen(); //Serial.begin(9600); myservo.attach(9); //Servo motor connection lcd.begin(16,2); pinMode(A1,INPUT); } void loop() { // lcd.print("Welcome"); // delay(500); // lcd.clear(); temp=analogRead(A1); if(currentposition==0 && temp<90) { lcd.print("normal person"); delay(500); displayscreen(); } if(currentposition==0 && temp>90){ lcd.print("Not Allowed"); delay(500); lcd.clear(); exit; } int l ; char code=keypad.getKey(); if(code!=NO_KEY) { lcd.clear(); lcd.setCursor(0,0); lcd.print("PASSWORD:"); lcd.setCursor(7,1); lcd.print(" "); lcd.setCursor(7,1); for(l=0;l<=currentposition;++l) { lcd.print("*"); //keypress(); } if (code==password[currentposition]) { ++currentposition; if(currentposition==4) { unlockdoor(); currentposition=0; } } else { incorrect(); currentposition=0; } } } //------------------ Function 1- OPEN THE DOOR--------------// void unlockdoor() { delay(900); lcd.setCursor(0,0); lcd.println(" "); lcd.setCursor(1,0); lcd.print("Access Granted"); lcd.setCursor(4,1); lcd.println("WELCOME!!"); lcd.setCursor(15,1); lcd.println(" "); lcd.setCursor(16,1); lcd.println(" "); lcd.setCursor(14,1); lcd.println(" "); lcd.setCursor(13,1); lcd.println(" "); for(pos = 180; pos>=0; pos-=5) // open the door { myservo.write(pos); delay(5); } delay(2000); delay(1000); counterbeep(); delay(1000); for(pos = 0; pos <= 180; pos +=5) // close the door { // in steps of 1 degree myservo.write(pos); delay(15); currentposition=0; lcd.clear(); displayscreen(); } } //--------------------Function 2- Wrong code--------------// void incorrect() { delay(500); lcd.clear(); lcd.setCursor(1,0); lcd.print("CODE"); lcd.setCursor(6,0); lcd.print("INCORRECT"); lcd.setCursor(15,1); lcd.println(" "); lcd.setCursor(4,1); lcd.println("GET AWAY!!!"); lcd.setCursor(13,1); lcd.println(" "); //Serial.println("CODE INCORRECT YOU ARE UNAUTHORIZED"); delay(3000); lcd.clear(); displayscreen(); } //-------Function 3 - CLEAR THE SCREEN--------------------/ void clearscreen() { lcd.setCursor(0,0); lcd.println(" "); lcd.setCursor(0,1); lcd.println(" "); lcd.setCursor(0,2); lcd.println(" "); lcd.setCursor(0,3); lcd.println(" "); } //------------Function 4 - DISPLAY FUNCTION--------------------// void displayscreen() { //lcd.print("Normal Person"); //delay(500); //lcd.clear(); lcd.setCursor(0,0); lcd.println("*ENTER THE CODE*"); lcd.setCursor(1 ,1); lcd.println("TO OPEN DOOR!!"); } //--------------Function 5 - Count down------------------// void counterbeep() { delay(1200); lcd.clear(); lcd.setCursor(2,15); lcd.println(" "); lcd.setCursor(2,14); lcd.println(" "); lcd.setCursor(2,0); delay(200); lcd.println("GET IN WITHIN:::"); lcd.setCursor(4,1); lcd.print("5"); delay(200); lcd.clear(); lcd.setCursor(2,0); lcd.println("GET IN WITHIN:"); delay(1000); lcd.setCursor(2,0); lcd.println("GET IN WITHIN:"); lcd.setCursor(4,1); //2 lcd.print("4"); delay(100); lcd.clear(); lcd.setCursor(2,0); lcd.println("GET IN WITHIN:"); delay(1000); lcd.setCursor(2,0); lcd.println("GET IN WITHIN:"); lcd.setCursor(4,1); lcd.print("3"); delay(100); lcd.clear(); lcd.setCursor(2,0); lcd.println("GET IN WITHIN:"); delay(1000); lcd.setCursor(2,0); lcd.println("GET IN WITHIN:"); lcd.setCursor(4,1); lcd.print("2"); delay(100); lcd.clear(); lcd.setCursor(2,0); lcd.println("GET IN WITHIN:"); delay(1000); lcd.setCursor(4,1); lcd.print("1"); delay(100); lcd.clear(); lcd.setCursor(2,0); lcd.println("GET IN WITHIN::"); delay(1000); delay(40); lcd.clear(); lcd.setCursor(2,0); lcd.print("RE-LOCKING"); delay(500); lcd.setCursor(12,0); lcd.print("."); delay(500); lcd.setCursor(13,0); lcd.print("."); delay(500); lcd.setCursor(14,0); lcd.print("."); delay(400); lcd.clear(); lcd.setCursor(4,0); lcd.print("LOCKED!"); delay(440); }
true
b3c6de5cc46f549c5105297bfc630e3781ae33b3
C++
D000M/Games
/UnderWorldRun2/engine/Window.h
UTF-8
3,425
3.09375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Window.h * Author: DooM * * Created on July 28, 2018, 8:41 PM */ #ifndef WINDOW_H #define WINDOW_H #pragma once #include <string> #include <SFML/Window.hpp> #include <SFML/System.hpp> #include <SFML/Graphics.hpp> #include "EventManager.h" class Window { public: /** * Default Constructor */ Window(); /** * User defined constructor * @param title - const std::string& window title. * @param size - const sf::Vector2u& window size. */ Window(const std::string& title, const sf::Vector2u& size); /** * Destructor */ ~Window(); // ################### METHODS ####################### // /** * Clear contents on the window */ void clearWindow(); /** * Draw Stuff on the window. */ void drawWindow(); /** * Update stuff on the window. Using the EventManager. */ void update(); /** * Method to check if window is closed * @return - true window is closed, false if window is open. */ bool isClosed(); /** * Method to set full screen on, off * @return - true if window is full screen, false if window is not full screen. */ bool isFullscreen(); /** * Method to provide information if window is on focus. * @return - true if window is on focus, false if window is not on focus. */ bool isFocused(); /** * Callback function to turn on, off fullscreen mode. * Provided from keys.cfg file. * @param details buttons information for EventDetails. */ void toggleFullscreen(EventDetails* details); /** * Callback function to close the program. * @param details */ void close(EventDetails* details = nullptr); /** * Get Method for the sf::RenderWindow. * @return the adress of the m_renderWindow; */ sf::RenderWindow* getRenderWindow(); /** * Get Method for the game EventManager. * @return the adress of the m_eventManager; */ EventManager* getEventManager(); /** * Method to get the m_gameWindow size; * @return sf::Vector2u size. */ sf::Vector2u getWindowSize(); private: //Helper Methods. /** * Method to setup the m_gameWindow member variable. * @param title set the member variable: std::string& m_windowTitle. * @param size set the member variable: sf::Vector2u& m_windowSize; */ void setupWindow(const std::string& title, const sf::Vector2u& size); void createWindow(); /** * sf::RenderWindow to draw */ sf::RenderWindow m_renderWindow; /** * EventManager object. */ EventManager m_eventManager; /** * The sf::RenderWindow size. */ sf::Vector2u m_windowSize; /** * The sf::RenderWindow title */ std::string m_windowTitle; /** * Flag to check if window is open/closed */ bool m_isClose; /** * Flag to check if window is full/not-full screen */ bool m_isFullscreen; /** * Flag to check if window is on-focus/not-on-focus */ bool m_isFocused; }; #endif /* WINDOW_H */
true
beeb6132b3fb1f9a6cd64c6b88fe7b5d5ca66f2f
C++
TaintedGear/MiniLD-RTS
/MiniLD_RTS Source/miniLD_RTS/healthBarObject.cpp
UTF-8
773
2.734375
3
[]
no_license
#include "HealthBarObject.h" HealthBarObject::~HealthBarObject() { } void HealthBarObject::Update( float dt, float _posX, float _posY, float offset, float maxHealth, float currHealth ) { mPosX = _posX; mPosY = _posY - offset; if (currHealth >= PercentageOf(maxHealth, 75.0f)) { mFrame = 0; } else if (currHealth <= PercentageOf(maxHealth, 75.0f) && (currHealth >= PercentageOf(maxHealth, 50.0f))) { mFrame = 1; } else if (currHealth <= PercentageOf(maxHealth, 50.0f) && (currHealth >= PercentageOf(maxHealth, 25.0f))) { mFrame = 2; } else if(currHealth <= PercentageOf(maxHealth, 25.0f)) { mFrame = 3; } GameObject::Update( dt ); } void HealthBarObject::Draw( SDL_Surface* buffer, Camera *camera) { GameObject::Draw( buffer, camera ); }
true
e61a67929bb92e91ca7273cc2b19340f9f5304f9
C++
dnvtmf/ACM
/DataStruct/数据结构经典题目.cpp
UTF-8
2,517
3.28125
3
[]
no_license
/*区间的rmq问题 * 在一维数轴上,添加或删除若干区间[l,r], 询问某区间[ql, qr]内覆盖了多少个完整的区间 * 做法:离线,按照右端点排序,然后按照左端点建立线段树保存左端点为l的区间个数, * 接着按排序结果从小到大依次操作,遇到询问时,查询比ql大的区间数 * 遇到不能改变查询顺序的题,应该用可持久化线段树 */ /*数组区间颜色数查询 问题: 给定一个数组,要求查询某段区间内有多少种数字 解决: 将查询离线, 按右端点排序; 从左到右依次扫描, 扫描到第i个位置时, 将该位置加1, 该位置的前驱(上一个出现一样数字的位置)减1, 然后查询所有右端点为i的询问的一个区间和[l, r]. */ /*数组区间数字种类数查询(带修改, 在线) 问题: 给定一个数组, 查询某区间内有多少种数字, 要求在线, 并且带修改操作 解决: 利用该数字上一次出现的位置pre, 将问题转化为求该区间[L, R]内有多少个数字的pre小于区间左端点L. 然后用树套树解决. $O(|Q|\log^2{n})$ */ /*求$b_{lr} = \sum_{i=l}^{r}{(i - l + 1) \cdot a_i}~(1 \leq l \leq r \leq n)$的最大值 令$s1_k = \sum_{i=1}^{k}{a_i}, s2_k = \sum_{i=1}^{k}{ia_i}$, 则$b_{lr} = s2_r - s2_{l-1} - (l - 1) \cdot (s1_r - s1_{l-1})$, 若r为确定, 则$b_{lr} = s2_r - (s2_{l-1} - (l-1) \cdot s1_{l-1} + (l-1) \cdot s1_r) = s2_r - (y_l + s1_r * x_l)$, 其中$y_l = s2_{l-1} - (l-1)\cdot s1_{l-1}, x_l = l - 1$. 问题转化为求$y_l + s1_r \cdot x_l$的最小值.(见下) */ /*平面点集, 最大化(最小化)目标函数 问题: 给n个点(x, y)和k, 求$z = x + k \cdot y$的最大(小)值. 解决: 维护一个上(下)凸壳(单调队列), 在凸壳上二分查找最大值, 即对于上凸壳, 其边的斜率是严格递减的, 而求得最大值的点恰好是斜率大于等于-k的线段的中点. */ double get_min(double k, Point stk[], int top) { double kk = -k; if(top == 1) return x[0] + k * y[0]; if(kk < get_k(x[0], y[0], x[1], y[1])) return x[0] + k * y[0]; int l = 1, r = top - 1, mid, ans = 0; while(l <= r) { mid = (l + r) >> 1; if((x[mid - 1] - x[mid])/ (y[mid - 1], y[mid]) <= kk) { ans = mid; l = mid + 1; } else { r = mid - 1; } } return x[ans] + k * y[ans]; }
true
d1f80a390973bfd98e019278de83626e4a2bf952
C++
kmnj951/study
/Baekjoon-OJ/11729_hanoi.cpp
UTF-8
459
3.109375
3
[]
no_license
#include <iostream> #include <sstream> using namespace std; stringstream ss; int tower(int num, int src, int dst) { if( num == 1 ) { ss << src << " " << dst << "\n"; return 1; } int count = 0; int pre_dst = 6-src-dst; count += tower(num-1, src, pre_dst); ss << src << " " << dst << "\n"; count += tower(num-1, pre_dst, dst); return ++count; } int main(void) { int N; cin >> N; cout << tower(N,1,3) << "\n"; cout << ss.str(); return 0; }
true
e0c799406274af19811562a13bb08c9c6b08d4d5
C++
KohlDeng/livox_hikrobot_fusion
/map_to_cloud/include/map_to_cloud/common.h
UTF-8
6,038
2.8125
3
[]
no_license
#ifndef COMMON_H #define COMMON_H #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <stdio.h> #include <Eigen/Core> #include <chrono> using namespace std; string float2str(float num); float str2float(string str); double str2double(string str); string double2str(double num); int str2int(string str); string int2str(int num); string long2str(long num); void getIntrinsic(const string path, vector<float> &intrinsic); void getDistortion(const string path, vector<float> &distortion); void getExtrinsic(const string path, vector<float> &extrinsic); void rotation2angle(Eigen::Matrix4d rot); string configPath = "config"; // convert a int to a string string int2str(int num) { ostringstream oss; if (oss << num) { string str(oss.str()); return str; } else { cout << "[float2str] - Code error" << endl; exit(0); } } int str2int(string str) { int d; stringstream sin(str); if(sin >> d) { return d; } cout << str << endl; cout << "Can not convert a string to int" << endl; exit(0); } string float2str(float num) { ostringstream oss; if (oss << num) { string str(oss.str()); return str; } else { cout << "[float2str] - Code error" << endl; exit(0); } } float str2float(string str) { float d; stringstream sin(str); if(sin >> d) { return d; } cout << str << endl; cout << "Can not convert a string to float" << endl; exit(0); } string double2str(double num) { ostringstream oss; if (oss << num) { string str(oss.str()); return str; } else { cout << "[double2str] - Code error" << endl; exit(0); } } double str2double(string str) { double d; stringstream sin(str); if(sin >> d) { return d; } cout << str << endl; cout << "Can not convert a string to double" << endl; exit(0); } string long2str(long num) { ostringstream oss; if (oss << num) { string str(oss.str()); return str; } else { cout << "[long2str] - Code error" << endl; exit(0); } } void getIntrinsic(const string path, vector<float> &intrinsic) { ifstream inFile; inFile.open(path); if (!inFile.is_open()) { cout << "Can not open file " << path << endl; exit(1); } string lineStr; getline(inFile, lineStr); for (uint i = 0; i < 3; ++i) { getline(inFile, lineStr); stringstream line(lineStr); string str; line >> str; intrinsic.push_back(str2double(str)); line >> str; intrinsic.push_back(str2double(str)); line >> str; intrinsic.push_back(str2double(str)); } } void getDistortion(const string path, vector<float> &distortion) { ifstream inFile; inFile.open(path); if (!inFile.is_open()) { cout << "Can not open file " << path << endl; exit(1); } string lineStr; for (uint i = 0; i < 6; ++i) { getline(inFile, lineStr); } getline(inFile, lineStr); stringstream line(lineStr); string str; line >> str; distortion.push_back(str2double(str)); line >> str; distortion.push_back(str2double(str)); line >> str; distortion.push_back(str2double(str)); line >> str; distortion.push_back(str2double(str)); line >> str; distortion.push_back(str2double(str)); } void getExtrinsic(const string path, vector<float> &extrinsic) { ifstream inFile; inFile.open(path); if (!inFile.is_open()) { cout << "Can not open file " << path << endl; exit(1); } string lineStr; getline(inFile, lineStr); for (uint i = 0; i < 3; ++i) { getline(inFile, lineStr); stringstream line(lineStr); string str; line >> str; extrinsic.push_back(str2double(str)); line >> str; extrinsic.push_back(str2double(str)); line >> str; extrinsic.push_back(str2double(str)); line >> str; extrinsic.push_back(str2double(str)); } } void rotation2angle(Eigen::Matrix4d rot) { double sy = sqrt(rot(0,0)*rot(0,0) + rot(1,0)*rot(1,0)); bool singular = sy < 1e-6; double x, y, z; if(!singular) { x = atan2(rot(2, 1), rot(2, 2)) * 180 / M_PI; y = atan2(-rot(2, 0), sy) * 180 / M_PI; z = atan2(rot(1, 0), rot(0, 0)) * 180 / M_PI; } else { x = atan2(-rot(1, 2), rot(1, 1)) * 180 / M_PI; y = atan2(-rot(2, 0), sy) * 180 / M_PI; z = 0; } cout << x << " " << y << " " << z << endl << endl; // roll pitch yaw } class livox_lidar_color { public: livox_lidar_color(ros::NodeHandle* nh); void CalibrationData(); void printMat(); void getColor(int &result_r, int &result_g, int &result_b, float cur_depth); void getParameters(); void pointCloudProcess(const sensor_msgs::PointCloud2ConstPtr &laserCloudMsg); void imageProcess(const sensor_msgs::ImageConstPtr &msg); void imagePub(); private: ros::NodeHandle* nodehandle_; image_transport::Publisher pub_; string intrinsic_path_, extrinsic_path_; cv::Mat imageMat_; cv::Mat processedImage_; bool protect_; const int threshold_lidar_ = 15000; float max_depth_; float min_depth_; cv::Mat distCoeffs_ = cv::Mat(5, 1, cv::DataType<double>::type); // 畸变向量 cv::Mat intrinsic_ = cv::Mat::eye(3, 3, CV_64F); cv::Mat intrinsicMat_ = cv::Mat(3, 4, cv::DataType<double>::type); // 内参3*4的投影矩阵,最后一列是三个零 cv::Mat extrinsicMat_RT_ = cv::Mat(4, 4, cv::DataType<double>::type); // 外参旋转矩阵3*3和平移向量3*1 pcl::PointCloud<pcl::PointXYZI>::Ptr raw_pcl_ptr_ = pcl::PointCloud<pcl::PointXYZI>::Ptr(new pcl::PointCloud<pcl::PointXYZI>); //livox点云消息包含xyz和intensity }; #endif // COMMON_H
true
2d30952c1d49a8f3b959f975ee3444fb6b053030
C++
bmjoy/teleports
/sisyphus/VulkanRenderer/src/Components/VulkanComponent.h
UTF-8
442
2.75
3
[]
no_license
#pragma once #include "ECS/Component.h" namespace Sisyphus::Rendering::Vulkan { template<typename VulkanType> class IVulkanComponent : public ECS::IComponent { public: virtual VulkanType GetVulkanObject() const = 0; operator VulkanType() const { return GetVulkanObject(); } }; template<typename T, typename VulkanType> concept VulkanComponent = ECS::Component<T> && std::derived_from<T, IVulkanComponent<VulkanType>>; }
true
c3585e246d8062ef9c1ba0c36f443651245df484
C++
njusegzyf/AtgProjs
/CallCPP-CLFF/Programs_FSE14/dart_power_ray_sine_stat_tcas_tsafe/MathSin.cpp
UTF-8
10,983
2.609375
3
[]
no_license
/* * MathSin.cpp * * Created on: Feb 12, 2015 * Author: zy */ //class MathSin { //public: static int IEEE_MAX = 2047; static int IEEE_BIAS = 1023; static int IEEE_MANT = 52; static double sixth = 1.0/6.0; static double half = 1.0/2.0; static double mag52 = 1024.*1024.*1024.*1024.*1024.*4.;/*2**52*/ static double magic = 1024.*1024.*1024.*1024.*1024.*4.;/*2**52*/ static double P[] = { -0.64462136749e-9, 0.5688203332688e-7, -0.359880911703133e-5, 0.16044116846982831e-3, -0.468175413106023168e-2, 0.7969262624561800806e-1, -0.64596409750621907082, 0.15707963267948963959e1 }; static double _2_pi_hi; // = 2.0/Math.PI ; static double _2_pi_lo; static double pi2_lo; static double pi2_hi_hi; static double pi2_hi_lo; static double pi2_lo_hi; static double pi2_lo_lo; static double pi2_hi; // = Math.PI/2; static double pi2_lo2; static double X_EPS = (double)1e-4; double longBitsToDouble(long value){ double result; memcpy(&result, &value, sizeof result); return result; } long doubleToRawLongBits(double value){ long bits; memcpy(&bits, &value, sizeof bits); return bits; } double mysin(double x){ double retval; double x_org; double x2; int md_b_sign; int xexp; int sign=0; int md_b_m1; int md_b_m2; // convert into the different parts // // x is symbolic. We have to call // {@code doubleToRawLongBits} via the helper to build // a {@code FunctionExpressio} in the // {@code ConcreteExecutionListener}. //long l_x = Double.doubleToRawLongBits(x); long l_x = helperdoubleToRawBits(x); // <32> <20> <11> <1> // sign md_b_sign = (int) ((l_x >> 63) & 1); // exponent: xexp = (int)((l_x >> 52) & 0x7FF); int xexp0 = (int)((l_x >> 52) & 0x7FF); md_b_m2 = (int)(l_x & 0xFFFFFFFF); md_b_m1 = (int)((l_x >> 31) & 0xFFFFF); printf("input="+x); //printf("raw="+l_x); printf("sign="+md_b_sign); printf("exp="+xexp); printf("exp_raw="+xexp0); printf("exp (unbiased)="+(xexp-IEEE_BIAS)); printf("m1="+md_b_m1); printf("m2="+md_b_m2); //----------end-of-conversion------------ if (IEEE_MAX == xexp){ printf("NAN-on-INF"); if( md_b_m1 >0 || md_b_m2 >0 ){ printf("unnormalized"); retval = x; }else{ printf("NaN"); retval = nan; } return retval; } else if (0 == xexp){ printf("+-0, denormal"); if( md_b_m1>0 || md_b_m2>0 ){ /* denormal */ printf("denormal"); x2 = x*x; /* raise underflow */ return x - x2; /* compute x */ } else{ /* +/-0.0 */ printf("+-0"); return x; /* => result is argument */ } } else if( xexp <= (IEEE_BIAS - IEEE_MANT - 2) ){ /* very small; */ printf("very small"); return x; }else if( xexp <= (IEEE_BIAS - IEEE_MANT/4) ){ /* small */ printf("small"); return x*(1.0-x*x*sixth); /* x**4 < epsilon of x */ } if (md_b_sign == 1){ x = -x; sign = 1; } x_org = x; printf("CURRENT\n\n"); if (xexp < IEEE_BIAS){ printf("less-than pi/2"); ; }else if (xexp <= (IEEE_BIAS + IEEE_MANT)){ printf("must bring into range..."); double xm; double x3 =0.0; double x4 =0.0; double x5 =0.0; double x6 =0.0; double a1=0.0; double a2=0.0; int bot2; double xn_d; double md; // should be bit union xm = floor(x * _2_pi_hi + half); printf("xm (int) = " + xm); xn_d = xm + mag52; printf("xn_d = " + xn_d); // C: bot2 = xn.b.m2 & 3u; // bot2 is the lower 3 bits of M2 long l_xn = doubleToRawLongBits(xn_d); int xn_m2 = (int)(l_xn & 0xFFFFFFFF); bot2 = xn_m2 & 3; printf("bot2 = " + bot2); /* * Form xm * (pi/2) exactly by doing: * (x3,x4) = xm * pi2_hi * (x5,x6) = xm * pi2_lo */ //>>>>>>>>>>>>>>>>>>>>> split(a1,a2,xm); printf("splitting: "+xm); long l_x1 = doubleToRawLongBits(xm); // <32> <20> <11> <1> // sign int md_b_sign1 = (int) ((l_x1 >> 63) & 1); // exponent: int xexp1 = (int)((l_x1 >> 52) & 0x7FF); int md_b_m21 = (int)(l_x1 & 0xFFFFFFFF); int md_b_m11 = (int)((l_x1 >> 31) & 0xFFFFF); printf("raw="+l_x1); printf("sign="+md_b_sign1); printf("exp="+xexp1); printf("exp (unbiased)="+(xexp1-IEEE_BIAS)); printf("m1="+md_b_m11); printf("m2="+md_b_m21); // md.b.m2 &= 0xfc000000u; \ // md_b_m2 = (int)(l_x1 & 0xFFFFFFFF); l_x1 &= (long)0xFC000000L; a1 = longBitsToDouble(l_x1); // lo = (v) - hi; /* bot 26 bits */ a2 = xm - a1; printf("in split: a1="+a1); printf("in split: a2="+a2); //>>>>>>>>>>> exactmul2(x3,x4, xm,a1,a2, pi2_hi,pi2_hi_hi,pi2_hi_lo); x3 = (xm)*(pi2_hi); x4 = (((a1*pi2_hi_hi-x3)+a1*pi2_hi_lo)+pi2_hi_hi*a2)+a2*pi2_hi_lo;; //>>>>>>>>>>> exactmul2(x5,x6, xm,a1,a2, pi2_lo,pi2_lo_hi,pi2_lo_lo); x5 = (xm)*(pi2_lo); x6 = (((a1*pi2_lo_hi-x5)+a1*pi2_lo_lo)+pi2_lo_hi*a2)+a2*pi2_lo_lo;; x = ((((x - x3) - x4) - x5) - x6) - xm*pi2_lo2; //++++++++++++++++++++++++++++++++++++++++++++++ if(bot2==0){ if (x < 0.0) { x = -x; //sign ^= 1; if (sign ==1) sign = 0; else sign = 1; } }else if(bot2==1){ if( x < 0.0 ){ x = pi2_hi + x; }else{ x = pi2_hi - x; } }else if(bot2==2){ if (x < 0.0) { x = -x; }else{ //sign ^= 1; if (sign ==1) sign = 0; else sign = 1; } }else if(bot2==3){ // sign ^= 1; if (sign ==1) sign = 0; else sign = 1; if( x < 0.0 ){ x = pi2_hi + x; }else{ x = pi2_hi - x; } } }else { printf("T_LOSS "); retval = 0.0; if (sign == 1) retval = -retval; return retval; } //---------everything between 0..pi/2 x = x * _2_pi_hi; if (x > X_EPS){ printf("x > EPS"); x2 = x*x; x *= ((((((((P)[0]*(x2) + (P)[1])*(x2) + (P)[2])*(x2) + (P)[3])*(x2) + (P)[4])*(x2) + (P)[5])*(x2) + (P)[6])*(x2) + (P)[7]); }else { printf("x <= EPS"); x *= pi2_hi; /* x = x * (pi/2) */ } if (sign==1) x = -x; printf("final return"); return x; } void MathSin(){ //#define MD(v,hi,lo) md.i.i1 = hi; md.i.i2 = lo; v = md.d; // MD( pi_hi, 0x400921FBuL,0x54442D18uL);/* top 53 bits of PI */ // pi_hi = Double.longBitsToDouble((long)0x400921FB54442D18L); // printf("pi_hi = " + pi_hi); // MD( pi_lo, 0x3CA1A626uL,0x33145C07uL);/* next 53 bits of PI*/ // pi_lo = Double.longBitsToDouble((long)0x3CA1A62633145C07L); // printf("pi_lo = " + pi_lo); // MD( pi2_hi, 0x3FF921FBuL,0x54442D18uL);/* top 53 bits of PI/2 */ pi2_hi = longBitsToDouble((long)0x3FF921FB54442D18L); printf("pi2_hi = " + pi2_hi); // MD( pi2_lo, 0x3C91A626uL,0x33145C07uL);/* next 53 bits of PI/2*/ pi2_lo = longBitsToDouble((long)0x3C91A62633145C07L); printf("pi2_lo = " + pi2_lo); // MD( pi2_lo2, 0xB91F1976uL,0xB7ED8FBCuL);/* next 53 bits of PI/2*/ pi2_lo2 = longBitsToDouble((long)0xB91F1976B7ED8FBCL); printf("pi2_lo2 = " + pi2_lo2); // MD( _2_pi_hi, 0x3FE45F30uL,0x6DC9C883uL);/* top 53 bits of 2/pi */ _2_pi_hi = longBitsToDouble((long)0x3FE45F306DC9C883L); printf("_2_pi_hi = " + _2_pi_hi); // MD( _2_pi_lo, 0xBC86B01EuL,0xC5417056uL);/* next 53 bits of 2/pi*/ _2_pi_lo = longBitsToDouble((long)0xBC86B01EC5417056L); printf("_2_pi_lo = " + _2_pi_lo); //>>>>> split(pi2_hi_hi,pi2_hi_lo,pi2_hi); double a1,a2; double xm; xm=pi2_hi; printf("splitting: "+xm); long l_x1 = doubleToRawLongBits(xm); // <32> <20> <11> <1> // sign int md_b_sign1 = (int) ((l_x1 >> 63) & 1); // exponent: int xexp1 = (int)((l_x1 >> 52) & 0x7FF); int md_b_m21 = (int)(l_x1 & 0xFFFFFFFF); int md_b_m11 = (int)((l_x1 >> 31) & 0xFFFFF); printf("raw="+l_x1); printf("sign="+md_b_sign1); printf("exp="+xexp1); printf("exp (unbiased)="+(xexp1-IEEE_BIAS)); printf("m1="+md_b_m11); printf("m2="+md_b_m21); // md.b.m2 &= 0xfc000000u; \ // md_b_m2 = (int)(l_x1 & 0xFFFFFFFF); l_x1 &= (long)0xFC000000L; a1 = longBitsToDouble(l_x1); // lo = (v) - hi; /* bot 26 bits */ a2 = xm - a1; printf("in split: a1="+a1); printf("in split: a2="+a2); pi2_hi_hi=a1; pi2_hi_lo=a2; //>>>>> split(pi2_lo_hi,pi2_lo_lo,pi2_lo); xm=pi2_lo; printf("splitting: "+xm); // xm is a concrete value; no need to invoke the helper (pdinges) l_x1 = doubleToRawLongBits(xm); //l_x1 = MathSin.helperdoubleToRawBits(xm); // <32> <20> <11> <1> // sign md_b_sign1 = (int) ((l_x1 >> 63) & 1); // exponent: xexp1 = (int)((l_x1 >> 52) & 0x7FF); md_b_m21 = (int)(l_x1 & 0xFFFFFFFF); md_b_m11 = (int)((l_x1 >> 31) & 0xFFFFF); printf("raw="+l_x1); printf("sign="+md_b_sign1); printf("exp="+xexp1); printf("exp (unbiased)="+(xexp1-IEEE_BIAS)); printf("m1="+md_b_m11); printf("m2="+md_b_m21); // md.b.m2 &= 0xfc000000u; \ // md_b_m2 = (int)(l_x1 & 0xFFFFFFFF); l_x1 &= (long)0xFC000000L; a1 = longBitsToDouble(l_x1); // lo = (v) - hi; /* bot 26 bits */ a2 = xm - a1; printf("in split: a1="+a1); printf("in split: a2="+a2); pi2_lo_hi=a1; pi2_lo_lo=a2; } long helperdoubleToRawBits(double xm) { return doubleToRawLongBits(xm); } //==================================================== void TESTIT(double arg){ double ms = mysin(arg); printf("SIN("+arg+"):\t"+sin(arg) +"\tmysin: "+ms); } // void main() { // // TODO Auto-generated method stub // MathSin sin = new MathSin(); // if(sin.mysin(0.0) == 0.0) { // printf("it is zero"); // } // } //};
true
0ebba7a2bafa17721db8bf53a062a4357e641b46
C++
csyezheng/LeetCode
/292. Nim Game/nimGame.cpp
UTF-8
251
2.65625
3
[]
no_license
#include "NimGame.h" #include <iostream> using namespace std; int main() { Solution instance; bool result = instance.canWinNim(10); if (result) cout << "Nim will win" << endl; else cout << "Nim can't win" << endl; }
true
16d4bd0943d6ede898d627cc137dd413cee587b3
C++
aliverobotics/Pumas-SmallSize
/PUMA_Vision/StillCapFjrg_2503_prueba/VisionEntrenamiento/draw.h
UTF-8
814
2.921875
3
[]
no_license
/** * \file draw.h * \author fjrg76 * \date 29-09-05 */ /** * This class implements the methods needed to draw into the working area */ /* RGB --> ColorDefs.h Point --> PointDefs.h byte --> GeneralDefs */ class Draw { public: Draw( int resx, int resy, int bsize ); void Blob( int x0, int y0, int x1, int y1, unsigned char *b, RGB rgb ); void Blob( Point p, unsigned char *b, RGB rgb ); void Blob( int x0, int y0, int x1, int y1, unsigned char *b, int color); void Line( int x0, int y0, int d, float angle, unsigned char *b, int color); void Circle( int x0, int y0, int r, unsigned char *b, int color); private: int m_X0, m_Y0, m_X1, m_Y1; byte *m_Pix; int m_Radius; float m_Angle; int m_Color; RGB m_RGB int m_BlobSize; int m_ResX, m_ResY; };
true
931b4e06b1c958a69a3655ad8117500a203f1c11
C++
ThisIsRWTH/CPP_Tutorial
/Project4.6.1/Vector.h
ISO-8859-1
2,015
3.390625
3
[]
no_license
////////////////////////////////////////////////////////////////////////////// // Praktikum Informatik 1 // Versuch 04: Einfhrung in die Klasse // // Datei: Vektor.h // Inhalt: Headerdatei der Klasse Vektor ////////////////////////////////////////////////////////////////////////////// /** * @file Vector.h * * Provides a Vector object with mathematical functionalities */ #ifndef Vektor_H #define Vektor_H /*! * @brief A Vector object with mathematical functionalities */ class Vector { public: /*! * @brief The constructor of the vector class * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ Vector(double x, double y, double z); ~Vector(); private: //member double x; double y; double z; public: /*! * @brief prints the vector coordinates to the console */ void print(); /*! * @return The X coordinate of the Vector */ double getX(); /*! * @return The Y coordinate of the Vector */ double getY(); /*! * @return The Z coordinate of the Vector */ double getZ(); /*! * @return The length of the Vector */ double getLength(); /*! * @brief substracts the given vector from the this vector * @return The new Vector after the substraction */ Vector* substract(Vector* v); /*! * @brief Rotates the Vector on the Z axis with the given angle * @param rad The angle at which the Vector should be rotated on the Z axis */ void rotateOnZAxis(double rad); /*! * @brief Adds to Vector and returns the resulting vector * @param v1 The first vector * @param v2 The second vector * @return The result of adding two vectors */ static Vector* add(Vector* v1, Vector* v2); /*! * @brief Checks if two vectors are orthogonal to each other * @param v1 The first vector * @param v2 The second vector * @return True, if the two vectors are orthogonal, false if not */ static bool isOrthogonal(Vector* v1, Vector* v2); double scalarProduct(Vector* inputVector); double angleBetweenVector(Vector* inputVector); }; #endif
true
093a9ea9bd7a140745bff5565f36d69fe260873b
C++
tokar-t-m/lippman
/Part_1/Chapter_7/learn_7_5/Person.h
UTF-8
153
2.671875
3
[]
no_license
#include <string> struct Person{ std::string name; std::string adress; std::string get_name() const; std::string get_adress() const; };
true
92b4d09ce09b23c9b9bf9faea03acfe22c9c96b7
C++
romanbelowski/op-lab4cpp
/decompressor.cpp
UTF-8
2,150
3.09375
3
[]
no_license
#include "decompressor.hpp" #define EOF_CODE 256 using namespace std; // Збергіає зжатий алгоритмом LZW файл in в файл out void DecompressorLZW::decompress(const char *in, const char *out) { ifstream input(in, ios::in | ios::binary); ofstream output(out, ios::out | ios::binary); if (!input || !output) { cerr << "Cannot open file!" << endl; exit(1); } pending_in = pending_size = 0; code_size = 9; code_threshold = pow(2, code_size); clog << "Decompressing file " << in; lzw_decode(input, output); cout << " Done.\nResult written to " << out << endl; input.close(); output.close(); } // Записує файл з потоку input в потік output використовуючи алгоритм LZW void DecompressorLZW::lzw_decode(istream &input, ostream &output) { unordered_map<int, string> dict; for (int i = 0; i < 256; i++) { dict[i] = string(1, i); } string str; int code; int next_code = 257; int progress_bar_counter; while (input_code(input, &code, next_code)) { if (!dict.count(code)) { dict[code] = str + str[0]; } output << dict[code]; if (!str.empty() && next_code <= MAX_CODE) { dict[next_code++] = str + dict[code][0]; } str = dict[code]; // Індикатор прогресу if (++progress_bar_counter % 1000000 == 0) { clog << "."; } } } // Функція для відладки bool DecompressorLZW::debug_code(istream &input, int *code, int dict_size) { input >> *code; return (*code != EOF_CODE); } bool DecompressorLZW::input_code(istream &input, int *code, int dict_size) { unsigned char in; while (pending_size < code_size) { input.read((char *)&in, 1); pending_in = pending_in | (in << pending_size); pending_size += 8; } int mask = (1 << code_size) - 1; // Маска на молодші code_size біт *code = pending_in & mask; pending_in >>= code_size; pending_size -= code_size; if (dict_size == code_threshold - 1 && dict_size < MAX_CODE) { code_threshold *= 2; code_size++; } return (*code != EOF_CODE); }
true
db242c412547e54e8881185184f0f2ee7660e248
C++
kancve/mr4c
/native/src/cpp/impl/keys/DataKeyBuilder.cpp
UTF-8
2,587
2.59375
3
[ "Apache-2.0" ]
permissive
/** * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "keys/keys_api.h" #include <set> #include <mutex> namespace MR4C { class DataKeyBuilderImpl { friend class DataKeyBuilder; private: std::set<DataKeyElement> m_elements; mutable std::mutex m_mutex; DataKeyBuilderImpl() { init(); } DataKeyBuilderImpl(const DataKeyBuilderImpl& builder) { initFrom(builder); } void init() { m_elements.clear(); } void initFrom(const DataKeyBuilderImpl& builder) { initFrom(builder.m_elements); } void initFrom(const std::set<DataKeyElement>& elements) { init(); addElements(elements); } void addElement(const DataKeyElement& element) { std::unique_lock<std::mutex> lock(m_mutex); m_elements.insert(element); lock.unlock(); } void addElements(const std::set<DataKeyElement>& elements) { std::unique_lock<std::mutex> lock(m_mutex); m_elements.insert(elements.begin(), elements.end()); lock.unlock(); } void addAllElements(const DataKey& key) { addElements(key.getElements()); } DataKey toKey() const { std::unique_lock<std::mutex> lock(m_mutex); // Released when out of scope return DataKey(m_elements); } ~DataKeyBuilderImpl() {} }; DataKeyBuilder::DataKeyBuilder() { m_impl = new DataKeyBuilderImpl(); } DataKeyBuilder::DataKeyBuilder(const DataKeyBuilder& builder) { m_impl = new DataKeyBuilderImpl(*builder.m_impl); } void DataKeyBuilder::addElement(const DataKeyElement& element) { m_impl->addElement(element); } void DataKeyBuilder::addElements(const std::set<DataKeyElement>& elements) { m_impl->addElements(elements); } void DataKeyBuilder::addAllElements(const DataKey& key) { m_impl->addAllElements(key); } DataKey DataKeyBuilder::toKey() const { return m_impl->toKey(); } DataKeyBuilder::~DataKeyBuilder() { delete m_impl; } DataKeyBuilder& DataKeyBuilder::operator=(const DataKeyBuilder& builder) { m_impl->initFrom(*builder.m_impl); return *this; } }
true
5051eb9874f13273f893f90e49368a506ebdb507
C++
evanmkim/TX2_QT_UI1
/utils/qtpreviewconsumer.h
UTF-8
2,452
2.828125
3
[]
no_license
#ifndef QTPREVIEWCONSUMER #define QTPREVIEWCONSUMER #include <Argus/Argus.h> #include "EGLGlobal.h" #include "GLContext.h" #include "Thread.h" #include "Window.h" namespace ArgusSamples { using namespace Argus; /******************************************************************************* * Preview consumer thread: * Uses an on-screen window and and OpenGL EGLStream consumer to render a live * preview of an OutputStream to the display. ******************************************************************************/ class QtPreviewConsumerThread : public Thread { public: enum RenderLayout { /// Streams divide the window horizontally, first on the left, last on the right. /// Expected window size is (height, width * streams.size()) LAYOUT_HORIZONTAL, /// Streams divide the window vertically, first at the top, last at the bottom. /// Expected window size is (height * streams.size(), width) LAYOUT_VERTICAL, /// Streams are tiled evenly (eg. 2x2, 3x3, etc.) to maintain window aspect ratio. LAYOUT_TILED, /// Streams are divided horizontally to render to a single region. LAYOUT_SPLIT_HORIZONTAL, /// Streams are divided vertically to render to a single region. LAYOUT_SPLIT_VERTICAL, }; explicit QtPreviewConsumerThread(EGLDisplay display, EGLStreamKHR stream); explicit QtPreviewConsumerThread(EGLDisplay display, const std::vector<EGLStreamKHR>& streams, RenderLayout layout = LAYOUT_TILED, bool syncStreams = false); ~QtPreviewConsumerThread(); /** * Sets the width of the line to render between streams. */ void setLineWidth(uint32_t width); /** * Sets the line color. */ void setLineColor(float r, float g, float b); private: /** @name Thread methods */ /**@{*/ virtual bool threadInitialize(); virtual bool threadExecute(); virtual bool threadShutdown(); /**@}*/ void renderStreams(); EGLDisplay m_display; GLContext m_context; std::vector<EGLStreamKHR> m_streams; std::vector<GLuint> m_textures; GLuint m_program; GLint m_textureUniform; Size2D<uint32_t> m_windowSize; RenderLayout m_layout; bool m_syncStreams; uint32_t m_lineWidth; float m_lineColor[3]; }; } // namespace ArgusSamples #endif // QTPREVIEWCONSUMER
true
6e4fa8d7543730cbbb6f99e5327744c9809c1498
C++
jadenpadua/Data-Structures-and-Algorithms
/C++/concepts/intro/sameAscii.cpp
UTF-8
276
3.046875
3
[]
no_license
bool sameAscii(std::string a, std::string b) { int ascii_a = 0; int ascii_b = 0; for(int i = 0; i < a.length(); i++) { ascii_a += int(a[i]); } for(int i = 0; i < b.length(); i++) { ascii_b += int(b[i]); } if(ascii_a == ascii_b) { return true; } return false; }
true
3db915117e006f16663fc22aa9360bf9f0b61bee
C++
Sejdii/library_project
/mainwindow.cpp
UTF-8
9,952
2.59375
3
[]
no_license
#include "mainwindow.h" #include <lib/dbmanager.h> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { DBManager::initial_database(DATABASE_PATH); // INITIAL THE DATABASE FILE IF NOT EXIST DBManager database(DATABASE_PATH); this->setWindow(); this->setStage("homepage"); } void MainWindow::setWindow() { setMinimumSize(500, 400); resize(800, 600); setWindowTitle("Baza danych biblioteki"); this->create_actions(); this->create_menu(); this->setStyleSheet(Color::get_window_style()); } void MainWindow::setStage(QString stage) { if(stage == "homepage") { this->stage_homepage(); } if(stage == "login_client") { this->stage_login_client(); } if(stage == "login_worker") { this->stage_login_worker(); } if(stage == "register_client") { this->stage_register_client(); } } void MainWindow::create_menu() { loginMenu = menuBar()->addMenu(tr("&Zaloguj się")); loginMenu->addAction(loginAsClient); loginMenu->addAction(loginAsWorker); registerMenu = menuBar()->addMenu(tr("&Zarejestruj")); registerMenu->addAction(registerAsClient); } void MainWindow::create_actions() { loginAsClient = new QAction(tr("&Jako klient"), this); connect(loginAsClient, &QAction::triggered, this, &MainWindow::loginAsClientSlot); loginAsWorker = new QAction(tr("&Jako pracownik"), this); connect(loginAsWorker, &QAction::triggered, this, &MainWindow::loginAsWorkerSlot); registerAsClient = new QAction(tr("&Konto klienta"), this); connect(registerAsClient, &QAction::triggered, this, &MainWindow::registerAsClientSlot); } // ################################# // # SLOTS # // ################################# void MainWindow::registerClientSlot() { User user_data(register_login->text(), register_password->text()); Client new_client(register_pesel->text(), register_name->text(), register_surname->text(), register_email->text()); new_client.set_user(user_data); Address address_data(register_city->text(), register_post_code->text(), register_street->text(), register_house_nr->value(), register_flat_nr->value()); if(user_data.validate()) { if(new_client.validate()) { if(address_data.validate()) { if(user_data.compare_passwords(register_password_repeat->text(), true)) { // VALIDATION SUCCESS if(address_data.push() >= 0) { new_client.set_addr(address_data.getID()); new_client.password_hash(); if(new_client.push() >= 0) { MainWindow::setStage("login_client"); } } } } } } } void MainWindow::loginClientSlot() { User user_data(login_login->text(), login_password->text()); user_data.password_hash(); if(user_data.verify(ACCOUNT_CLIENT)) { ClientWindow* cwindow = new ClientWindow(user_data.getID()); // CREATING NEW WINDOW - CLIENT WINDOW cwindow->show(); close(); } } void MainWindow::loginAsClientSlot() { MainWindow::setStage("login_client"); } void MainWindow::loginAsWorkerSlot() { MainWindow::setStage("login_worker"); } void MainWindow::registerAsClientSlot() { MainWindow::setStage("register_client"); } void MainWindow::loginWorkerSlot() { Worker worker(User(login_login->text(), login_password->text())); worker.password_hash(); if(worker.verify(ACCOUNT_WORKER)) { //worker.fetch_worker_data(); WorkerWindow* workerwindow = new WorkerWindow(worker.getID()); // CREATING NEW WINDOW - WORKER WINDOW workerwindow->show(); close(); } } // ################################# // # STAGES # // ################################# void MainWindow::stage_login_worker() { setWindowTitle("Zaloguj się"); QLabel* login_text = new QLabel(tr("<h1>Zaloguj się jako pracownik</h1>")); login_login = new QLineEdit; login_login->setPlaceholderText("Login"); login_password = new QLineEdit; login_password->setPlaceholderText("Hasło"); login_password->setEchoMode(QLineEdit::Password); QFormLayout* form = new QFormLayout; form->addRow(tr("&Login"), login_login); form->addRow(tr("&Hasło"), login_password); QPushButton* login_button = new QPushButton(tr("&Zaloguj się")); login_button->setStyleSheet(Color::get_button_style()); connect(login_button, SIGNAL(released()), this, SLOT(loginWorkerSlot())); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(login_text); layout->addLayout(form); layout->addWidget(login_button); layout->setAlignment(Qt::AlignTop); qDeleteAll(widget->children()); widget->setLayout(layout); } void MainWindow::stage_homepage() { widget = new QWidget; setCentralWidget(widget); widget->setStyleSheet(Color::get_widget_style()); QLabel* hello_label = new QLabel(tr("<b style='font-size:24px'>Witaj w bibliotecznej bazie danych</b>")); hello_label->setAlignment(Qt::AlignCenter); QLabel* info_label = new QLabel(tr("<i>Zaloguj się lub zarejestruj, jeżeli nie posiadasz jeszcze konta aby rozpocząć korzystanie z bazy bibliotecznej</i>")); info_label->setAlignment(Qt::AlignCenter); QHBoxLayout* buttons = new QHBoxLayout; QPushButton* button_login = new QPushButton("&Zaloguj się", this); button_login->setStyleSheet(Color::get_button_style()); QPushButton* button_register = new QPushButton("&Zarejestruj się", this); button_register->setStyleSheet(Color::get_button_style()); connect(button_login, SIGNAL(released()), this, SLOT(loginAsClientSlot())); connect(button_register, SIGNAL(released()), this, SLOT(registerAsClientSlot())); buttons->addWidget(button_login); buttons->addWidget(button_register); buttons->setAlignment(Qt::AlignVCenter); QVBoxLayout *layout = new QVBoxLayout; layout->setContentsMargins(5, 5, 5, 5); layout->addWidget(hello_label); layout->addWidget(info_label); layout->addLayout(buttons); widget->setLayout(layout); } void MainWindow::stage_login_client() { setWindowTitle("Zaloguj się"); QLabel* login_text = new QLabel(tr("<h1>Zaloguj się jako klient</h1>")); login_login = new QLineEdit; login_login->setPlaceholderText("Login"); login_password = new QLineEdit; login_password->setPlaceholderText("Hasło"); login_password->setEchoMode(QLineEdit::Password); QFormLayout* form = new QFormLayout; form->addRow(tr("&Login"), login_login); form->addRow(tr("&Hasło"), login_password); QPushButton* login_button = new QPushButton(tr("&Zaloguj się")); login_button->setStyleSheet(Color::get_button_style()); connect(login_button, SIGNAL(released()), this, SLOT(loginClientSlot())); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(login_text); layout->addLayout(form); layout->addWidget(login_button); layout->setAlignment(Qt::AlignTop); qDeleteAll(widget->children()); widget->setLayout(layout); } void MainWindow::stage_register_client() { setWindowTitle("Zarejestruj się"); register_login = new QLineEdit; register_login->setPlaceholderText("Login"); register_password = new QLineEdit; register_password->setPlaceholderText("Hasło"); register_password->setEchoMode(QLineEdit::Password); register_password_repeat = new QLineEdit; register_password_repeat->setPlaceholderText("Powtórz hasło"); register_password_repeat->setEchoMode(QLineEdit::Password); register_pesel = new QLineEdit; register_pesel->setPlaceholderText("PESEL"); register_name = new QLineEdit; register_name->setPlaceholderText("Imię"); register_surname = new QLineEdit; register_surname->setPlaceholderText("Nazwisko"); register_email = new QLineEdit; register_email->setPlaceholderText("Adres E-mail"); register_city = new QLineEdit; register_city->setPlaceholderText("Miasto"); register_post_code = new QLineEdit; register_post_code->setPlaceholderText("Kod pocztowy"); register_street = new QLineEdit; register_street->setPlaceholderText("Ulica"); register_house_nr = new QSpinBox; register_house_nr->setMinimum(0); register_house_nr->setSingleStep(1); register_flat_nr = new QSpinBox; register_flat_nr->setMinimum(0); register_flat_nr->setSingleStep(1); QFormLayout* form = new QFormLayout; form->addRow(tr("&Login"), register_login); form->addRow(tr("&Hasło"), register_password); form->addRow(tr("&Powtórz hasło"), register_password_repeat); form->addRow(tr("&PESEL"), register_pesel); form->addRow(tr("&Imię"), register_name); form->addRow(tr("&Nazwisko"), register_surname); form->addRow(tr("&E-mail"), register_email); QFormLayout* address = new QFormLayout; address->addRow(tr("&Miasto"), register_city); address->addRow(tr("&Kod pocztowy"), register_post_code); address->addRow(tr("&Ulica"), register_street); address->addRow(tr("&Numer domu"), register_house_nr); address->addRow(tr("&Numer mieszkania (pozostaw 0 jeżeli nie posiadasz)"), register_flat_nr); QHBoxLayout* forms_layout = new QHBoxLayout; forms_layout->addLayout(form); forms_layout->addLayout(address); QPushButton* register_button = new QPushButton(tr("&Zarejestruj się")); register_button->setStyleSheet(Color::get_button_style()); connect(register_button, SIGNAL(released()), this, SLOT(registerClientSlot())); QVBoxLayout* layout = new QVBoxLayout; layout->addLayout(forms_layout); layout->addWidget(register_button); layout->setAlignment(Qt::AlignTop); qDeleteAll(widget->children()); widget->setLayout(layout); }
true
e08ef39d39bba810f5184c9df9ee2b6296615d40
C++
manaswinibehera1/mana.lab5
/lab5_q2.cpp
UTF-8
423
3.859375
4
[]
no_license
//using library #include<iostream> using namespace std; //using main function int main (){ //declaring variables int a,b,c; cout << "Enter three numbers : " << endl; cin >> a >> b >> c; //condition if ((a > b) && (a > c)){ cout << a << "is the maximum number." << endl; } else if ((b > a) && (b > c)){ cout << b << "is the maximum number." << endl; } else { cout << c << "is the maximum number." << endl; } }
true
92f886f4974ffae10362f2572120dc894376d7d2
C++
tdm1223/Algorithm
/programmers/source/2-12.cpp
UTF-8
445
3.1875
3
[ "MIT" ]
permissive
// 구명보트 // 2019.06.28 #include<vector> #include<algorithm> using namespace std; int solution(vector<int> people, int limit) { int answer = 0; // 오름차순 정렬 후 탐욕법으로 풀이 sort(people.begin(), people.end(), greater<int>()); int size = people.size(); for (int i = 0; i < size; i++) { if (people[i] + people[size - 1] <= limit) { size--; answer++; } else { answer++; } } return answer; }
true
d046d05e0bb61e18f520536107915005eae69265
C++
LuanQBarbosa/ray-tracer-university-project
/scene.cpp
UTF-8
4,632
2.890625
3
[ "MIT" ]
permissive
#include "scene.h" Scene::Scene( void ) {} Scene::~Scene( void ) { if ( bvh_ ) { delete bvh_; bvh_ = nullptr; } } // bool Scene::intersect( const Ray &ray, // IntersectionRecord &intersection_record ) const // { // bool intersection_result = false; // IntersectionRecord tmp_intersection_record; // std::size_t num_primitives = primitives_.size(); // // Loops over the list of primitives, testing the intersection of each primitive against the given ray // for ( std::size_t primitive_id = 0; primitive_id < num_primitives; primitive_id++ ) // if ( primitives_[primitive_id]->intersect( ray, tmp_intersection_record ) ) // if ( ( tmp_intersection_record.t_ < intersection_record.t_ ) && ( tmp_intersection_record.t_ > 0.0 ) ) // { // intersection_record = tmp_intersection_record; // intersection_result = true; // the ray intersects a primitive! // } // return intersection_result; // } bool Scene::intersect( const Ray &ray, IntersectionRecord &intersection_record ) const { bool intersection_result = false; IntersectionRecord tmp_intersection_record; intersection_result = bvh_->intersect( ray, intersection_record); return intersection_result; } void Scene::buildBVH( void ) { bvh_ = new BVH( primitives_ ); std::clog << std::endl; } void Scene::load( void ) { Material m1{ new Diffuse{ glm::vec3{ 0.5f, 0.5f, 0.5f } }, glm::vec3{ 0.0f, 0.0f, 0.0f } }; Material m2{ new Diffuse{ glm::vec3{ 0.0f, 0.0f, 0.0f } }, glm::vec3{ 40.0f, 40.0f, 40.0f } }; Material m3{ new Diffuse{ glm::vec3{ 0.0f, 0.0f, 1.0f } }, glm::vec3{ 12.5f, 12.5f, 12.5f } }; // Spheres // Sphere *s1 = new Sphere(glm::vec3(-1.5f, -1.0f, 1.0f), 0.75f, Material{ new SmoothDieletric{ glm::vec3{ 69.0f, 74.0f, 208.0f } / 255.0f }, glm::vec3{ 0.0f, 0.0f, 0.0f } }); // primitives_.push_back(Primitive::PrimitiveUniquePtr(s1)); // Sphere *s2 = new Sphere(glm::vec3(0.0f, -1.0f, 0.0f), 0.75f, Material{ new CookTorrance{ glm::vec3{ 44.0f, 242.0f, 97.0f } / 255.0f }, glm::vec3{ 0.0f, 0.0f, 0.0f } }); // primitives_.push_back(Primitive::PrimitiveUniquePtr(s2)); // Sphere *s3 = new Sphere(glm::vec3(1.5f, -1.0f, 1.0f), 0.75f, Material{ new PerfectReflector{ glm::vec3{ 15.0f, 210.0f, 8.0f } / 255.0f }, glm::vec3{ 0.0f, 0.0f, 0.0f } }); // primitives_.push_back(Primitive::PrimitiveUniquePtr(s3)); // Sphere *s1 = new Sphere(glm::vec3(0.0f, 0.0f, 0.0f), 1.0f, Material{ new SmoothDieletric{ glm::vec3{ 69.0f, 74.0f, 208.0f } / 255.0f }, glm::vec3{ 0.0f, 0.0f, 0.0f } }); // primitives_.push_back(Primitive::PrimitiveUniquePtr(s1)); // Sphere *s2 = new Sphere(glm::vec3(0.0f, 0.0f, 0.0f), 0.99f, Material{ new Diffuse{ glm::vec3{ 255.0f, 0.0f, 0.0f } / 255.0f }, glm::vec3{ 0.0f, 0.0f, 0.0f } }); // primitives_.push_back(Primitive::PrimitiveUniquePtr(s2)); // Lights // Sphere *s4 = new Sphere(glm::vec3(-0.35f, 3.5f, 0.0f), 1.0f, m3); // primitives_.push_back(Primitive::PrimitiveUniquePtr(s4)); Sphere *s4 = new Sphere(glm::vec3(-0.95f, 1.0f, 0.75f), 0.15f, m3); primitives_.push_back(Primitive::PrimitiveUniquePtr(s4)); // Sphere *s5 = new Sphere(glm::vec3(0.0f, 4.0f, -0.75f), 1.5f, m3); // primitives_.push_back(Primitive::PrimitiveUniquePtr(s5)); // Sphere *s6 = new Sphere(glm::vec3(0.0f, 4.0f, -2.5f), 1.5f, m3); // primitives_.push_back(Primitive::PrimitiveUniquePtr(s6)); // Sphere *s7 = new Sphere(glm::vec3(0.0f, 4.0f, -4.25f), 1.5f, m3); // primitives_.push_back(Primitive::PrimitiveUniquePtr(s7)); } void Scene::loadObj( const char* obj, glm::vec3 position, float size, Material material ) { Assimp::Importer importer; const aiScene *scene = importer.ReadFile(obj, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); for (unsigned int j = 0; j < scene->mNumMeshes; j++) { auto mesh = scene->mMeshes[j]; for (unsigned int i = 0; i < mesh->mNumFaces; i++) { auto face = mesh->mFaces[i]; auto v1 = mesh->mVertices[face.mIndices[0]]; auto v2 = mesh->mVertices[face.mIndices[1]]; auto v3 = mesh->mVertices[face.mIndices[2]]; Triangle *triangle = new Triangle((glm::vec3(v1.x, v1.y, v1.z)) * size + position, (glm::vec3(v2.x, v2.y, v2.z)) * size + position, (glm::vec3(v3.x, v3.y, v3.z)) * size + position, material); primitives_.push_back( Primitive::PrimitiveUniquePtr(triangle)); } } }
true
00fb61a4af100b6dffbcc5aadac81eeac868929b
C++
Olesenka18/LAB_OP
/11/11.2/11.2/11.2.cpp
UTF-8
497
2.71875
3
[]
no_license
#include <stdio.h> #include <locale.h> int main(void) { setlocale(LC_ALL, "Russian"); int A, B, C, S; printf("Введите значение A \n"); scanf("%i", &A); printf("Введите значение B \n"); scanf("%i", &B); printf("Введите значение C \n"); scanf("%i", &C); if (A >= B) { if (B >= C) { S = A + B; } else { S = A + C; } } else { if (A >= C) { S = A + B; } else { S = B + C; } } printf("S = %i", S); return 0; }
true
06710a33d5c403510f7824c3f66a1b50355ec4cd
C++
GPUOpen-Tools/qt_common
/custom_widgets/colored_legend_scene.h
UTF-8
2,206
2.703125
3
[ "MIT" ]
permissive
//============================================================================= /// Copyright (c) 2016-2020 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file /// \brief Headerfor a class that contains colored legends //============================================================================= #ifndef QTCOMMON_CUSTOM_WIDGETS_COLORED_LEGEND_SCENE_H_ #define QTCOMMON_CUSTOM_WIDGETS_COLORED_LEGEND_SCENE_H_ #include <QGraphicsScene> #include "graphics_scene.h" class QGraphicsView; /// An item in the colored legend. struct ColorLegendItem { /// Constructor ColorLegendItem() : rect_item_(nullptr) , text_item_() { } /// The colored rect associated with this item. QGraphicsRectItem* rect_item_; /// The text name of this item. QGraphicsTextItem* text_item_; }; enum LegendMode { kColor, kText }; /// Support for colored legends. class ColoredLegendScene : public QGraphicsScene { Q_OBJECT public: /// Explicit constructor /// \param parent The view displaying this widget. explicit ColoredLegendScene(QWidget* parent = nullptr); /// Virtual Destructor virtual ~ColoredLegendScene(); /// Add a new box with a description beside it. /// \param color The color of the box /// \param description The legend description void AddColorLegendItem(const QColor& color, const QString& description); /// Add a string-only legend. /// \param description The legend description void AddTextLegendItem(const QString& description); /// Clear the scene. void Clear(); /// Update item positions. void Update(); protected: LegendMode legend_mode_; ///< Rendering either blocks with text, or just text QVector<ColorLegendItem> color_legends_; ///< Block to text legend pairings QVector<QGraphicsTextItem*> text_legends_; ///< Plain text legends const int kHorizontalSpacingAfterText = 20; ///< Horizontal spacing after the text, before the next item const int kVerticalSpacingAroundText = 2; ///< Vertical spacing above and below the text }; #endif // QTCOMMON_CUSTOM_WIDGETS_COLORED_LEGEND_SCENE_H_
true
6ae261985be014654191d6456b157769ebff78f5
C++
abdullahfarwees/HackerEarth
/MonkTakesAWalk.cpp
UTF-8
567
3.046875
3
[]
no_license
#include<iostream> /* https://www.hackerearth.com/practice/algorithms/searching/linear-search/practice-problems/algorithm/monk-takes-a-walk/ */ using namespace std; void fun() { string str; cin>>str; int count = 0; for(int i=0;i<str.size();i++) { if( str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' || str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') { ++count; } } cout<<count<<endl; } int main() { int tc; cin>>tc; for(int t=0;t<tc;t++)fun(); return 0; }
true
cd5ea8caa4f34efe2ea08f7b0e1765eb4c031b8a
C++
Pluto-Jin/fromZero2GrandMaster
/610~619/619/A.cpp
UTF-8
313
2.75
3
[]
no_license
#include "bits/stdc++.h" using namespace std; int main() { int t; cin>>t; while (t--) { string a,b,c; cin>>a; cin>>b; cin>>c; int flag; for (int i=0;i<a.size();i++) { if (c[i]==a[i] or c[i]==b[i]) flag=1; else {flag=0;break;} } if (flag) cout<<"YES"<<endl; else cout<<"NO"<<endl; } }
true
0143426b2730ba5c5858c21cee2d9c3ea4343fbc
C++
MCSH/rumi
/src/ast/While.h
UTF-8
318
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#pragma once #include "Statement.h" #include "Expression.h" class While: public Statement{ public: Expression *condition; Statement *st; While(Expression *condition, Statement *st); virtual void prepare(CC *cc) override; virtual void compile(CC *cc) override; virtual void codegen(CC *cc) override; };
true
5164bf1ff7cf26c60f5cc4afe84e102ce730d0f0
C++
cyberway/cyberway
/contracts/eosiolib/symbol.hpp
UTF-8
5,819
3.015625
3
[ "MIT" ]
permissive
#pragma once #include <eosiolib/core_symbol.hpp> #include <eosiolib/serialize.hpp> #include <eosiolib/print.hpp> #include <eosiolib/system.h> #include <tuple> #include <limits> namespace eosio { /** * @defgroup symbolapi Symbol API * @brief Defines API for managing symbols * @ingroup contractdev */ /** * @defgroup symbolcppapi Symbol CPP API * @brief Defines %CPP API for managing symbols * @ingroup symbolapi * @{ */ /** * Converts string to uint64_t representation of symbol * * @param precision - precision of symbol * @param str - the string representation of the symbol */ static constexpr uint64_t string_to_symbol( uint8_t precision, const char* str ) { uint32_t len = 0; while( str[len] ) ++len; uint64_t result = 0; for( uint32_t i = 0; i < len; ++i ) { if( str[i] < 'A' || str[i] > 'Z' ) { /// ERRORS? } else { result |= (uint64_t(str[i]) << (8*(1+i))); } } result |= uint64_t(precision); return result; } /** * Macro for converting string to char representation of symbol * * @param precision - precision of symbol * @param str - the string representation of the symbol */ #define S(P,X) ::eosio::string_to_symbol(P,#X) /** * uint64_t representation of a symbol name */ typedef uint64_t symbol_name; /** * Checks if provided symbol name is valid. * * @param sym - symbol name of type symbol_name * @return true - if symbol is valid */ static constexpr bool is_valid_symbol( symbol_name sym ) { sym >>= 8; for( int i = 0; i < 7; ++i ) { char c = (char)(sym & 0xff); if( !('A' <= c && c <= 'Z') ) return false; sym >>= 8; if( !(sym & 0xff) ) { do { sym >>= 8; if( (sym & 0xff) ) return false; ++i; } while( i < 7 ); } } return true; } /** * Returns the character length of the provided symbol * * @param sym - symbol to retrieve length for (uint64_t) * @return length - character length of the provided symbol */ static constexpr uint32_t symbol_name_length( symbol_name sym ) { sym >>= 8; /// skip precision uint32_t length = 0; while( sym & 0xff && length <= 7) { ++length; sym >>= 8; } return length; } /** * \struct Stores information about a symbol * * @brief Stores information about a symbol */ struct symbol_type { /** * The symbol name */ symbol_name value; symbol_type() { } /** * What is the type of the symbol */ symbol_type(symbol_name s): value(s) { } /** * Is this symbol valid */ bool is_valid()const { return is_valid_symbol( value ); } /** * This symbol's precision */ uint64_t precision()const { return value & 0xff; } /** * Returns uint64_t representation of symbol name */ uint64_t name()const { return value >> 8; } /** * The length of this symbol */ uint32_t name_length()const { return symbol_name_length( value ); } /** * */ operator symbol_name()const { return value; } /** * %Print the symbol * * @brief %Print the symbol */ void print(bool show_precision=true)const { if( show_precision ){ ::eosio::print(precision()); prints(","); } auto sym = value; sym >>= 8; for( int i = 0; i < 7; ++i ) { char c = (char)(sym & 0xff); if( !c ) return; prints_l(&c, 1 ); sym >>= 8; } } EOSLIB_SERIALIZE( symbol_type, (value) ) }; /** * \struct Extended asset which stores the information of the owner of the symbol * */ struct extended_symbol : public symbol_type { /** * The owner of the symbol * * @brief The owner of the symbol */ account_name contract; extended_symbol( symbol_name sym = 0, account_name acc = 0 ):symbol_type{sym},contract(acc){} /** * %Print the extended symbol * * @brief %Print the extended symbol */ void print()const { symbol_type::print(); prints("@"); printn( contract ); } /** * Equivalency operator. Returns true if a == b (are the same) * * @brief Subtraction operator * @param a - The extended asset to be subtracted * @param b - The extended asset used to subtract * @return boolean - true if both provided symbols are the same */ friend bool operator == ( const extended_symbol& a, const extended_symbol& b ) { return std::tie( a.value, a.contract ) == std::tie( b.value, b.contract ); } /** * Inverted equivalency operator. Returns true if a != b (are different) * * @brief Subtraction operator * @param a - The extended asset to be subtracted * @param b - The extended asset used to subtract * @return boolean - true if both provided symbols are the same */ friend bool operator != ( const extended_symbol& a, const extended_symbol& b ) { return std::tie( a.value, a.contract ) != std::tie( b.value, b.contract ); } friend bool operator < ( const extended_symbol& a, const extended_symbol& b ) { return std::tie( a.value, a.contract ) < std::tie( b.value, b.contract ); } EOSLIB_SERIALIZE( extended_symbol, (value)(contract) ) }; // }@ symbolapi } /// namespace eosio
true
990ed3e788cfd3fcbe058d5e4bef79e6dc43cb0d
C++
s1042992/Leetcode_practice
/34.cpp
UTF-8
817
2.921875
3
[]
no_license
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> ans; vector<int> arr; arr.push_back(-1); arr.push_back(-1); bool flag=true; for(int i=0;i<nums.size();i++) { if(nums[i]==target&&flag) { ans.push_back(i); flag=false; } if(nums[i]!=target&&!flag) { ans.push_back(i-1); break; } if(i==nums.size()-1&&nums[nums.size()-1]==target) { ans.push_back(nums.size()-1); } } if(ans.empty()) return arr; else return ans; } };
true
23c42a21ede34806dbcc471d0a9e475899ac68c4
C++
The-Fire-Ferrets/Paramourus-Rex
/include/EventInterface.h
UTF-8
491
2.65625
3
[ "Zlib" ]
permissive
#ifndef EVENTINTERFACE_H #define EVENTINTERFACE_H #include "Constants.h" class EventInterface { public: virtual const EventType& getEventType(void) const = 0; virtual float getTimeStamp(void) const = 0; virtual void Serialize(const std::ostream& o) const = 0; virtual EventInterface* copy(void) = 0; virtual const EventInterface* copy(void) const = 0; virtual const ActorInstance getSender(void) const = 0; virtual const ActorInstance getReceiver(void) const = 0; }; #endif
true
47dad6e25c61eff2708a5169dfc207acab58695d
C++
VLiamin/spbu
/sem1/hw4/4.2/head.cpp
UTF-8
1,986
3.171875
3
[]
no_license
#include <stdio.h> #include <string.h> #include "head.h" List *createList() { return new List {nullptr}; } void push(ListElement *&tmp, char information[length]) { if (tmp == nullptr) { tmp = new ListElement; tmp->next = nullptr; int i = 0; while (information[i] != '\0') { tmp->information[i] = information[i]; i++; } if (tmp->information[i - 1] != '\n') tmp->information[i] = '\n'; return; } else { push(tmp->next, information); return; } } void push(List *&list, char information[length]) { return push(list->first, information); } void save(ListElement *tmp, char *phone, FILE *f) { bool areEqual = false; while ((!areEqual) && (tmp)) { int i = 0; areEqual = true; tmp = tmp->next; while (tmp->information[i] != '\n') { if (tmp->information[i] != phone[i]) areEqual = false; i++; } } tmp = tmp->next; while (tmp) { fprintf(f, "%s", tmp->information); tmp = tmp->next; } return; } void save(List *list, char *phone, FILE *f) { save(list->first, phone, f); } char *search(ListElement *tmp, char *facts, int number) { bool areEqual = false; if (number == 1) { while ((!areEqual) && (tmp)) { int i = 0; areEqual = true; while (facts[i] != '\0') { if (tmp->information[i] != facts[i]) areEqual = false; i++; } tmp = tmp->next; } return tmp->information; } else { ListElement *p = tmp; while ((!areEqual) && (tmp)) { p = tmp; tmp = tmp->next; int i = 0; areEqual = true; while (facts[i] != '\0') { if (tmp->information[i] != facts[i]) areEqual = false; i++; } } return p->information; } } char *search(List *list, char *facts, int number) { return search(list->first, facts, number); } void deleteList(ListElement *tmp) { ListElement *p = tmp; while (tmp) { tmp = tmp->next; delete p; p = tmp; } return; } void deleteList(List *list) { deleteList(list->first); delete list; }
true
fb9bdb7919fbd4ba1b0c919f1e4baa8305523421
C++
lightionight/DirectX12Remaster
/Include/self/Box2dSceneManager.cpp
UTF-8
1,957
2.890625
3
[]
no_license
#include "Box2dSceneManager.h" #if defined (DEBUG) | defined (_DEBUG) #include <iostream> #endif // d (DEBUG) | defined (_DEBUG) #include <algorithm> Box2dSceneManager::Box2dSceneManager() { } Box2dSceneManager::~Box2dSceneManager() { } void Box2dSceneManager::Initialize(float gravity, float posX, float posY, float halfwidth, float halfHeight) { InitializeEngine(gravity); InitializeGround(posX, posY, halfwidth, halfHeight); } void Box2dSceneManager::InitializeEngine(float gravity) { m_Box2dEngine = std::make_unique<Box2dEngine>(gravity); } void Box2dSceneManager::InitializeGround(float posX, float posY, float halfwidth, float halfHeight) { Box2dObject objects; objects.InitAsGround(posX, posY, halfwidth, halfHeight, GetEngine()); m_AllObject.push_back(std::move(objects)); } b2World* Box2dSceneManager::GetEngine() { return m_Box2dEngine->GetEngine(); } // this function return reference may have some problem Box2dObject* Box2dSceneManager::GetSceneObject(const std::string& name) { for (size_t i = 0; i < m_AllObject.size(); i++) if (m_AllObject[i].GetName() == name) return &(m_AllObject[i]); return nullptr; } void Box2dSceneManager::AddBox2dObjects(std::string name,b2Vec2 points[], int counts, b2BodyType bodytype) { Box2dObject obj(name, points, counts, GetEngine(), bodytype); #if defined(DEBUG) | defined(_DEBUG) for (int i = 0; i < counts; i++) std::cout << "Points : " << i << ":" << points[i].x << "," << points[i].y << std::endl; #endif m_AllObject.push_back(std::move(obj)); #if defined(DEBUG) | defined(_DEBUG) Box2dObject test = m_AllObject.back(); b2PolygonShape* sp = test.GetShape(); for (int i = 0; i < 8; i++) std::cout << "After Add: "<< i << ":" << sp->m_vertices[i].x << ", " << sp->m_vertices[i].y << std::endl; #endif } void Box2dSceneManager::Run() { m_Box2dEngine->Start(); }
true
2572ee09e8f5a2d973996d3417dcfcc252537fd8
C++
shobhitjawa/dsAlgos
/searchalgorithms/pairwithadiff.cpp
UTF-8
442
2.765625
3
[]
no_license
#include<stdio.h> #include<iostream> #include<bits/stdc++.h> using namespace std; int main() { int arr[]={1, 8, 30, 40, 100}; int n=5; int x=60; int max=arr[0]; int i=0; //pair with a difference int j=1; while(i<n&&j<n) { if(i!=j&&arr[j]-arr[i]==x) { cout<<"pair found:"<<arr[i]<<"and"<<arr[j]; break; } else if(arr[j]-arr[i]<x) j++; else i++; } return 0; }
true
2a6d76e3b512f2d73b78537a1f8244402de52cff
C++
notherland/ilab_2course
/Triangles/tests.cpp
UTF-8
4,668
2.6875
3
[]
no_license
#define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/included/unit_test.hpp> #include "Triangles.h" BOOST_AUTO_TEST_CASE(Triangles_line_t_proj1) { point_t pl1{4, 3, 1}, pl2{6, 2, 1}, p1{4, 10, 7}, p2{1, 4.5, 1}; line_t l{pl1, pl2}; //(x-4)/2 = (y-3)/-1 = (z-1)/0; point_t p1_proj = l.projection_p(p1), p2_proj = l.projection_p(p2); point_t test_p1 {1.2, 4.4, 1}, test_p2{1, 4.5, 1}; BOOST_TEST (p1_proj.is_equal(test_p1)); BOOST_TEST (p2_proj.is_equal(test_p2)); } BOOST_AUTO_TEST_CASE(Triangles_line_t_proj2) { point_t pl1{1, 2, 6}, pl2{4, 0, 6}, p1{1, 44, 9}, p2{7, -2, 6}; line_t l{pl1, pl2}; //(x-1)/3 = (y-2)/-2 = (z-6)/0 point_t p1_proj = l.projection_p(p1), p2_proj = l.projection_p(p2); point_t test_p1 {-18.3846, 14.9231, 6}, test_p2{7, -2, 6}; BOOST_TEST (p1_proj.is_equal(test_p1)); BOOST_TEST (p2_proj.is_equal(test_p2)); } BOOST_AUTO_TEST_CASE(Triangles_triangle_t) { point_t A{4, 0, 2}, B{4, 4, 2}, C{0, 0, 0}, p1{0, 2, 0}, p2{4, 2, 2}, vp1{4, 2, 2}, vp2{2, 2, 1}; triangle_t t{A, B, C}; line_t l{p1, p2}; vector_t vec_cross = t.vec_cross_l(l), test_vec {vp1, vp2}; BOOST_TEST (vec_cross.is_equal(test_vec)); } BOOST_AUTO_TEST_CASE(Triangles_Same_plane_crossing) { point_t A1{2, 2, 0}, B1{4, 2, 0}, C1{3, 5, 0}, A2{3, 3, 0}, B2{4, 5, 0}, C2{4, 6, 0}; triangle_t t1{A1, B1, C1}, t2{A2, B2, C2}; plane_t test_plane {0, 0, 1, 0}; BOOST_TEST (t1.getplane().is_equal(test_plane)); BOOST_TEST (t2.getplane().is_equal(test_plane)); BOOST_TEST(check_crossing (t1, t2)); } BOOST_AUTO_TEST_CASE(Triangles_Same_plane_not_crossing) { point_t A1{0, 0, 0}, B1{4, 0, 4}, C1{2, 4, 2}, A2{1, 5, 1}, B2{6, 6, 6}, C2{3, 8, 3}; triangle_t t1{A1, B1, C1}, t2{A2, B2, C2}; plane_t test_plane {-1, 0, 1, 0}; BOOST_TEST(t1.getplane().is_parallel(test_plane)); BOOST_TEST (t1.getplane().is_equal(test_plane)); BOOST_TEST (t2.getplane().is_equal(test_plane)); BOOST_CHECK(!check_crossing (t1, t2)); } BOOST_AUTO_TEST_CASE(Triangles_Same_plane_crossing_inside) { point_t A1{2, 4, 14}, B1{4, 6, 4}, C1{1, 4, 2}, A2{3, 5, 9}, B2{3.5, 5.5, 6.5}, C2{3, 5.2, 5.6}; triangle_t t1{A1, B1, C1}, t2{A2, B2, C2}; plane_t test_plane {-12, 17, 1, -58}; BOOST_TEST (t1.getplane().is_equal(test_plane)); BOOST_TEST (t2.getplane().is_equal(test_plane)); BOOST_CHECK(check_crossing (t1, t2)); } BOOST_AUTO_TEST_CASE(Triangles_Same_plane_crossing_on_side) { point_t A1{10.5, 2, 0}, B1{4, 2, 10}, C1{3, 5, -6}, A2{10.5, 2, 0}, B2{4, 2, 10}, C2{-1.4, 0, 30}; triangle_t t1{A1, B1, C1}, t2{A2, B2, C2}; plane_t test_plane {20, 76, 13, -362}; BOOST_TEST (t1.getplane().is_equal(test_plane)); BOOST_TEST (t2.getplane().is_equal(test_plane)); BOOST_TEST(check_crossing (t1, t2)); } BOOST_AUTO_TEST_CASE(Triangles_Parallel_planes_not_crossing) { point_t A1{1, 3, -7}, B1{0, 0, -2}, C1{5, 7, -15}, A2{3.5, 0, 0}, B2{1, 2, -1.75}, C2{4, 6, -9.25}; triangle_t t1{A1, B1, C1}, t2{A2, B2, C2}; plane_t test_plane {1, 3, 2, 10}; BOOST_TEST (t1.getplane().is_parallel(test_plane)); BOOST_TEST (t2.getplane().is_parallel(test_plane)); BOOST_TEST(!check_crossing (t1, t2)); } BOOST_AUTO_TEST_CASE(Triangles_Different_planes_crossing) { point_t A1{0, 0, 0}, B1{4, 0, 0}, C1{4, 6, 0}, A2{0, 0, 4}, B2{4, 0, 4}, C2{3, 2, -1}; triangle_t t1{A1, B1, C1}, t2{A2, B2, C2}; plane_t test_plane1 {0, 0, 1, 0}, test_plane2 {0, 5, 2, -8}; BOOST_TEST (t1.getplane().is_equal(test_plane1)); BOOST_TEST (t2.getplane().is_equal(test_plane2)); BOOST_TEST(check_crossing (t1, t2)); } BOOST_AUTO_TEST_CASE(Triangles_Different_planes_not_crossing) { point_t A1{10, 22, 8}, B1{4, 10, 16}, C1{11, 6, 2}, A2{4, 0, 3}, B2{9, 6, 4}, C2{-3, 7, -8}; triangle_t t1{A1, B1, C1}, t2{A2, B2, C2}; plane_t test_plane1 {50, -7, 27, -562}, test_plane2 {-73, 48, 77, 61}; BOOST_TEST (t1.getplane().is_equal(test_plane1)); BOOST_TEST (t2.getplane().is_equal(test_plane2)); BOOST_TEST(!check_crossing (t1, t2)); } BOOST_AUTO_TEST_CASE(Triangles_Different_planes_crossing_on_side) { point_t A1{1, 2, 6}, B1{4, 0, 0}, C1{4, 6, 0}, A2{1, 2, 6}, B2{4, 0, 0}, C2{10, 9, -1}; triangle_t t1{A1, B1, C1}, t2{A2, B2, C2}; BOOST_TEST(check_crossing (t1, t2)); } BOOST_AUTO_TEST_CASE(Triangles_Different_planes_crossing_on_point) { point_t A1{0, 0, 0}, B1{4, 0, 4}, C1{4, 6, 0}, A2{0, 0, 0}, B2{4, 0, 4}, C2{3, 2, -1}; triangle_t t1{A1, B1, C1}, t2{A2, B2, C2}; plane_t test_plane1 {0, 0, 1, 0}, test_plane2 {0, 5, 2, -8}; BOOST_TEST(check_crossing (t1, t2)); }
true
c14a51b7d34d01c025f7dcc1d641822ccaf3abc4
C++
valfvo/punyduck
/src/litequarks/include/litequarks/LQHash.hpp
UTF-8
602
3.0625
3
[ "MIT" ]
permissive
#pragma once #include <functional> // std::hash template<class T> inline void lqHashCombine(std::size_t &seed, const T& v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } #ifndef LQ_NO_PAIR_HASH namespace std { template<class T1, class T2> struct hash<std::pair<T1, T2>> { size_t operator()(const std::pair<T1, T2>& p) const { size_t seed = 0; lqHashCombine(seed, p.first); lqHashCombine(seed, p.second); return seed; } }; } #endif
true
b37454d8d7906fd5d247cccb3e994e15cbbfa73c
C++
rpbrandau/OSU-Coursework
/162 - Intro pt 2 - Labs/LabE/list.hpp
UTF-8
706
2.859375
3
[]
no_license
/***************************************************************** ** Program Filename: list.h ** Author: Riley Brandau - brandaur@oregonstate.edu ** Date: 7/19/16 ** Description: Header file for List class *****************************************************************/ //#pragma once #ifndef LIST_HPP #define LIST_HPP #include <iostream> class List { private: struct node //adapted from book code to use char variable { char data; node* next; node(char data1, node *next1 = NULL) { data = data1; next = next1; } }; node* head; node* temp; node* tail; public: List(); //~List(); void insert(char x); void displayHead(); char remove(); }; #endif
true
5dcfbd746817efdf19ab8e5cf45c8ed991bfa4e6
C++
imxingquan/hotelMIS
/Samples/hotel/hotelMIS/HRoomCtrl.cpp
GB18030
3,795
2.734375
3
[ "MIT" ]
permissive
#include "stdAfx.h" #include "HRoomCtrl.h" #include <cassert> using namespace std; namespace hotelMIS{ HRoomCtrl::HRoomCtrl(mysqlpp::Connection *pCon ) { _pCon = pCon; } bool HRoomCtrl::isExistRoom(int roomid) { try{ mysqlpp::Query query = _pCon->query(); query << "SELECT room_id FROM t_roomSet WHERE room_id = "<< roomid; mysqlpp::Result res = query.store(); if ( res.empty()) return false; }mycatch(); return true; } int HRoomCtrl::insertRoom(int roomid,string name,int tableNum) { if ( isExistRoom(roomid) ) return -1; //ҪӵroomѾ. try{ /*id = getRoomMax() +1; assert(id != -1);*/ mysqlpp::Query query = _pCon->query(); query << "INSERT INTO t_roomSet (room_id,room_name,table_num) VALUES("<< roomid <<",'"<<name<<"',"<<tableNum<<")"; query.execute(); }mycatch(); return roomid; } void HRoomCtrl::updateRoom(HRoom &room) { try{ mysqlpp::Query query = _pCon->query(); query << "UPDATE t_roomSet SET room_name ='"<<room.room_name<<"',table_num=" <<room.table_num <<" WHERE room_id = " << room.room_id; query.execute(); }mycatch(); } void HRoomCtrl::deleteRoom(int id) { try{ mysqlpp::Query query = _pCon->query(); query << "DELETE FROM t_roomSet WHERE room_id = " << id; query.execute(); }mycatch(); } vector<HRoom> HRoomCtrl::getAllRoom() { vector<HRoom> vec; try{ mysqlpp::Query query = _pCon->query(); query << "SELECT * FROM t_roomSet ORDER BY room_id "; mysqlpp::Result res = query.store(); mysqlpp::Row row ; mysqlpp::Result::iterator it; for ( it = res.begin(); it != res.end(); it++){ row = *it; int roomId = row.lookup_by_name("room_id"); string room_name = row.lookup_by_name("room_name"); int tableNum = row.lookup_by_name("table_num"); HRoom room(roomId,room_name,tableNum); vec.push_back(room); } }mycatch(); return vec; } HRoom HRoomCtrl::getRoom(int roomId) { HRoom room; try{ mysqlpp::Query query = _pCon->query(); query << "SELECT * FROM t_roomSet WHERE room_id = " << roomId; mysqlpp::Result res = query.store(); if ( !res.empty() ) { mysqlpp::Row row; mysqlpp::Result::iterator it = res.begin(); row = *it; string roomName = row.lookup_by_name("room_name"); int tableNum = row.lookup_by_name("table_num"); room.setId(roomId); room.setName(roomName); room.setTableNum(tableNum); } }mycatch(); return room; } int HRoomCtrl::getRoomMax() { int id = -1; try{ mysqlpp::Query query = _pCon->query(); query << "SELECT MAX(room_id) as roomMaxId FROM t_roomSet "; mysqlpp::Result res = query.store(); if (! res.empty()) { mysqlpp::Row row ; mysqlpp::Result::iterator it = res.begin(); row = *it; string sid = row.lookup_by_name("roomMaxId"); if ( "NULL"== sid) id = 0; else id = row.lookup_by_name("roomMaxId"); } }mycatch(); return id; } int HRoomCtrl::getRoomCount()const { int id = -1; try{ mysqlpp::Query query = _pCon->query(); query << "SELECT COUNT(*) as roomCount FROM t_roomSet "; mysqlpp::Result res = query.store(); if (! res.empty()) { mysqlpp::Row row ; mysqlpp::Result::iterator it = res.begin(); row = *it; id = row.lookup_by_name("roomCount"); } }mycatch(); return id; } string HRoomCtrl::getRoomName(int roomId) { string roomName; try{ mysqlpp::Query query = _pCon->query(); query << "SELECT room_name FROM t_roomSet WHERE room_id = " <<roomId; mysqlpp::Result res = query.store(); if ( !res.empty()) { mysqlpp::Row row; mysqlpp::Result::iterator it = res.begin(); row = *it; roomName = row.lookup_by_name("room_name"); } }mycatch(); return roomName; } }
true
fa208267950be4559b6f021a15a2fa19c990f6e2
C++
EoinGorman/FinalYearProject
/Classes/include/PlayerManager.h
UTF-8
910
2.96875
3
[]
no_license
#pragma once #include "Player.h" class PlayerManager { public: //Functions static PlayerManager* GetInstance(); ~PlayerManager() { instanceFlag = false; } void ResetPlayerManager(); void SetNumberOfPlayers(int num); void AddPlayer(Player::Faction); Player* GetCurrentPlayer(); void CycleToNextPlayer(); int GetPlayerCount(); Player* GetPlayerByID(int id); std::vector<Player*> GetPlayers(); void DeleteMarkedPlayers(); private: int m_redFactionCount; int m_blueFactionCount; int m_greenFactionCount; int m_yellowFactionCount; int m_playerCount; int m_currentPlayerIndex; std::vector<Player*> m_players; //Functions PlayerManager() { //private constructor m_playerCount = 0; m_currentPlayerIndex = 0; m_redFactionCount = 0; m_blueFactionCount = 0; m_greenFactionCount = 0; m_yellowFactionCount = 0; } static bool instanceFlag; static PlayerManager *instance; };
true
00549098dc280b3e620c217607ecad091e2347ba
C++
pid011-study-archive/oop-study-2
/study/10/04_cube/main.cpp
UTF-8
671
3.578125
4
[]
no_license
#include <iostream> using namespace std; class Cube { double _x; double _y; double _z; public: Cube(double x, double y, double z) : _x(x), _y(y), _z(z) { } Cube operator+(const Cube& other) { double x = _x > other._x ? _x : other._x; double y = _y > other._y ? _y : other._y; double z = _z + other._z; return Cube(x, y, z); } void list(const char* msg) { cout << msg << " " << _x << ", " << _y << ", " << _z << endl; } }; int main() { Cube c(12.2, 89.4, 5.0); Cube d(67.3, 53.2, 1.3); Cube e = c + d; c.list("Welcome"); d.list("Vision"); e.list("Passion"); }
true
41688167cb115dd417eda1f624da6cb6e7c57586
C++
maliksh7/C-from-Crack
/Pointers/intial/ptr1.cpp
UTF-8
426
3.1875
3
[]
no_license
#include <iostream> using namespace std; int main(){ int a =10; int *p; int **p1; p = &a; p1 = &p; cout << "Address of a(by a): " << &a << endl; cout << "Address of a(by p): " << p << endl; cout << "Address of a(by p1): " << *p1 << endl; cout << "Value of a(by a): " << a << endl; cout << "Value of a(by p): " << *p << endl; cout << "Value of a(by p1): " << **p1 << endl; return 0; }
true
cd55879104ac4a9c58325d5a3579bdc6709a248a
C++
hanayashiki/pythonic
/pythonic/pythonic_elem_value.h
UTF-8
2,906
3.15625
3
[]
no_license
#pragma once #include <any> #include <iostream> #include <typeinfo> #include <typeindex> #include <string> #include "log.h" #include "pythonic_basic_types.h" #include "pythonic_container.h" #include "pythonic_utils_match.h" namespace pythonic { class list; class elem_value { std::any value; std::shared_ptr<container> cont; public: template<class ...Args> elem_value(Args... args) : value(std::forward<Args>(args)...) { PYC_DEBUG << "elem_value Use any initializer" << std::endl; } elem_value(container * c) { PYC_DEBUG << "elem_value Use container initializer" << std::endl; cont = std::shared_ptr<container>(reinterpret_cast<container*>(c)); } elem_value(list * c) : elem_value((container*)c) { } ~elem_value() { } template<typename T> inline T as() const { return std::any_cast<T>(this->value); } template<> inline any as<any>() const { return *this; } template<> inline const any & as<const any &>() const { return *this; } template<typename T> inline T as_mut() { return std::any_cast<T>(this->value); } template<> inline any as_mut<any>() { return *this; } template<> inline const any & as_mut<const any &>() { return *this; } static inline any remove_const(const elem_value & v) { elem_value v1 = v; return v1; } template<typename T> inline bool isinstance() const { return value.type() == typeid(T); } template<> inline bool isinstance<any>() const { return true; } template<> inline bool isinstance<const any &>() const { // std::cout << value.type().name() << ". " << std::endl; return true; } std::any & get_value() { return value; } std::type_index get_type_index() const { return std::type_index(value.type()); } auto & get_cont() { return cont; } const auto & get_cont() const { return cont; } #define EQUAL(type) if (that.isinstance<type>()) { return this->as<type>() == that.as<type>(); } bool operator == (const elem_value & that) const noexcept { return match( that, [=](const any & t) { if (this->get_type_index() == that.get_type_index()) { if (this->get_cont().get() != nullptr && that.get_cont().get() != nullptr) { return this->get_cont()->__equal__(*that.get_cont()); } BASIC_TYPES_LIST(EQUAL) return false; } else { return false; } } ); } #define LESS(type) if (that.isinstance<type>()) { return as<type>() < that.as<type>(); } bool operator < (const elem_value & that) const noexcept { return match( that, [=](const any & t) { if (this->get_type_index() == that.get_type_index()) { BASIC_TYPES_LIST(LESS) } else { return this->get_type_index() < that.get_type_index(); } } ); } }; #undef EQUAL #undef LESS }
true
b701804b0e88cdfe0e41292f575b31dd49eed95e
C++
shivambhushan/Codes
/XOR Profit Problem.cpp
UTF-8
368
3.46875
3
[]
no_license
#include<iostream> using namespace std; int XOR_Profit(int a, int b) { int max_xor = 0; for (int i = a; i < b; ++i) { int check_xor; for (int j = a+1; j <= b; ++j) { check_xor = i^j; if (check_xor>max_xor) { max_xor=check_xor; } } } return max_xor; } int main() { int a,b; cin>>a; cin>>b; cout<<XOR_Profit(a, b)<<endl; return 0; }
true
2be557add50d2d8a897307c8f53c0d1c9faca499
C++
glencornell/xdg-mini-launcher
/src/abstract_entry.hpp
UTF-8
579
2.890625
3
[]
no_license
#pragma once #include <string> namespace xdg { // The base class for all xdg desktop entry files class AbstractEntry { public: enum type_t { Unknown, Application, Link, Directory }; static type_t cvt(std::string const &str); static std::string cvt(type_t const t); public: virtual ~AbstractEntry(); AbstractEntry(type_t t, std::string const &name, std::string const &icon); private: // Options applicable to all desktop entries: type_t m_type; std::string m_name; std::string m_icon; AbstractEntry(); }; }
true
3ab78b1bbd6cc61c6e1d9abc22143cc7e876d2cb
C++
Harmon758/kolibrios
/programs/develop/libraries/libGUI/SRC/control_text.inc
UTF-8
4,651
2.78125
3
[]
no_license
/* control Text */ gui_text_size_t GetStringSize(font_t *font,char *s) { long len; gui_text_size_t size; len=strlen(s); if (font->size==FONT_CONSTANT_SIZE) { if (font->flags & FONT_FLAG_ORIENTATION_HORIZONTAL_FROM_LEFT_TO_RIGHT_ON) { size.sizex=len*font->sizex; size.sizey=font->sizey; } } return(size); } void TextBackgroundOn(gui_text_t *Text) { Text->txt_flags |=TEXT_BACKGROUND_ON; } void TextBackgroundOff(gui_text_t *Text) { Text->txt_flags &=TEXT_BACKGROUND_ON; } void DisplayText(gui_text_t *Text) { int x; int y; int sizex; int sizey; char v; font_t *font; gui_text_size_t size; struct FINITION *fin; x=Text->ctrl_x; y=Text->ctrl_y; fin=(struct FINITION*)Text->finition; font=(font_t*)Text->font; v=Text->txt_flags & TEXT_BACKGROUND_ON; if (v) font->flags|=FONT_FLAG_DRAW_BACKGROUND_ON; else font->flags&=FONT_FLAG_DRAW_BACKGROUND_OFF; v=Text->txt_flags & TEXT_ORIENTATION_FROM_LEFT_TO_RIGHT_ON; if (v) font->flags|=FONT_FLAG_ORIENTATION_HORIZONTAL_FROM_LEFT_TO_RIGHT_ON; else font->flags&=FONT_FLAG_ORIENTATION_HORIZONTAL_FROM_LEFT_TO_RIGHT_OFF; //recalculate size of control text befor draw size=GetStringSize((font_t*)Text->font,Text->text); Text->ctrl_sizex=(DWORD)size.sizex; Text->ctrl_sizey=(DWORD)size.sizey; DrawFont=(void(*)(finition_t *fin,int fx,int fy,DWORD color, DWORD background_color,font_t *font,BYTE *s))font->fnt_draw; DrawFont(fin,x,y,Text->color,Text->background_color,font,Text->text); } //--------------------------------------------------------------------------------- // control Text //--------------------------------------------------------------------------------- void TextProc(gui_text_t *Text,gui_message_t *message) { finition_t *fin; switch(message->type) { case MESSAGE_FULL_REDRAW_ALL: { //draw Text if (Text->flags & FLAG_SHOW_CONTROL) DisplayText(Text); break; } case MESSAGE_FULL_REDRAW_ALL_WITH_FINITION: { fin=(struct FINITION*)Text->finition; fin->flags=fin->flags | FINITION_ON; fin->x=message->arg1; fin->y=message->arg2; fin->sizex=message->arg3; fin->sizey=message->arg4; DisplayText(Text); break; } case MESSAGE_SPECIALIZED: { if (Text->flags & FLAG_GET_SPECIALIZED_MESSAGE_ON) { if (Text->flags & FLAG_SHOW_CONTROL) DisplayText(Text); Text->flags=Text->flags & FLAG_GET_SPECIALIZED_MESSAGE_OFF; } break; } case MESSAGE_CHANGE_POSITION_EVENT: { Text->ctrl_x=Text->ctrl_x+message->arg1; Text->ctrl_y=Text->ctrl_y+message->arg2; break; } case MESSAGE_DESTROY_CONTROL: { free(Text->finition); break; } case MESSAGE_SET_MAIN_PARENT: { SendMessage((struct HEADER*)Text,message); Text->main_parent=(DWORD*)message->arg1; break; } default: break; } //send message to child controls(if there is) SendMessage((struct HEADER*)Text,message); } //--------------------------------------------------------------------------------- // create control Text //--------------------------------------------------------------------------------- void* CreateText(gui_text_data_t *info_for_control) { gui_text_t *Text; finition_t *fin; gui_text_size_t size; Text=malloc(sizeof(struct ControlText)); Text->finition=malloc(sizeof(struct FINITION)); fin=(struct FINITION*)Text->finition; fin->flags=0; if (info_for_control->font==(DWORD*)NULL) Text->font=FontsMeneger.default_font; else Text->font=info_for_control->font; size=GetStringSize((font_t*)Text->font,info_for_control->text); ID++; #ifdef DEBUG printf("\ncreated text with ID=%d",(int)ID); #endif Text->child_bk=(DWORD*)NULL; Text->child_fd=(DWORD*)NULL; Text->active_control_for_keys=(DWORD*)NULL; Text->active_control_for_mouse=(DWORD*)NULL; Text->callback=(DWORD*)NULL; Text->timer=(DWORD*)NULL; Text->ctrl_proc=(DWORD*)&TextProc; Text->ctrl_x=(DWORD)info_for_control->x; Text->ctrl_y=(DWORD)info_for_control->y; Text->ctrl_sizex=(DWORD)size.sizex; Text->ctrl_sizey=(DWORD)size.sizey; Text->ctrl_ID=ID; Text->color=info_for_control->color; Text->background_color=info_for_control->background_color; Text->text=info_for_control->text; Text->txt_flags=0; Text->txt_flags|=TEXT_ORIENTATION_FROM_LEFT_TO_RIGHT_ON; if (info_for_control->background) { Text->txt_flags|=TEXT_BACKGROUND_ON; } else { Text->txt_flags&=TEXT_BACKGROUND_OFF; } Text->flags=0; Text->flags=Text->flags | FLAG_SHOW_CONTROL; return(Text); }
true
a7037f5fde10201c143ce812b2a09e479942f4e8
C++
shani24levi/MazeGenerator_andSolver
/Command.h
UTF-8
3,974
2.921875
3
[]
no_license
#pragma once #include "Maze2d.h" #include "View.h" #include "Model.h" #include <string> #include <map> using namespace std; class Command { public: Command() { v = new View(_out); mo = new Model(_out); } virtual void execute() = 0; void setCommend(std::string& s) { currComand = s; } void inOut(std::istream* in, std::ostream* out) { _in = in; _out = out; } void brackCommand(); void setAllComm(std::string& a, std::string& a1, std::string& a2, std::string& a3, std::string& a4) { commandName = a; s1 = a1; s2 = a2; s3 = a3; s4 = a4; } int convert(std::string& a) { int myint1 = stoi(a); return myint1; } protected: Maze2d m1; View* v; Model* mo; std::ostream* _out; // The output stream std::istream* _in; // The input stream std::string currComand; std::string commandName, s1, s2,s3,s4; int w, h; map<string, Maze2d> myMazesByName; }; class DirCommand : public Command { public: DirCommand(Maze2d* light) : m_light(light), Command(){} DirCommand(Maze2d _m1) { _m1 = m1; } void execute() { std::string path; if (s1 != " ") { path = s1; } else { std::cout << "path is not valid" << std::endl; return; } v->setOut(_out); v->dir(path); } private: Maze2d* m_light; Maze2d m1; }; class generatCommand : public Command { public: generatCommand(Maze2d* light) : m_light(light), Command() {} void execute() { //v = new View(_out); //mo = new Model(_out); w = convert(s2); h = convert(s3); Maze2d& _m = mo->generateMaze(w, h, s4); v->setOut(_out); //need to check if it came back as a valid maze and then v->generateMaze(s1); //save it in my map: myMazesByName[s1] = _m; v->setMazes(s1, _m); } private: Maze2d* m_light; }; class displyCommand : public Command { public: displyCommand(Maze2d* light) : m_light(light), Command() {} void execute() { //v = new View(_out); //mo = new Model(_out); v->setOut(_out); v->display(s1); } private: Maze2d* m_light; }; class saveCommand : public Command { public: saveCommand(Maze2d* light) : m_light(light) {} saveCommand(Maze2d _m1) { _m1 = m1; } void execute() { v = new View(_out); mo = new Model(_out); mo->setOut(_out); mo->save(s1, _m); } private: Maze2d* m_light; Maze2d _m; }; class loadCommand : public Command { public: loadCommand(Maze2d* light) : m_light(light) {} loadCommand(Maze2d _m1) { _m1 = m1; } void execute() { v = new View(_out); mo = new Model(_out); mo->setOut(_out); mo->load(s1, m1); mo->save(s2, m1); //save it with new name =s2 } private: Maze2d* m_light; Maze2d _m; }; class sizeMazeCommand : public Command { public: sizeMazeCommand(Maze2d* light) : m_light(light) {} sizeMazeCommand(Maze2d _m1) { _m1 = m1; } void execute() { v = new View(_out); mo = new Model(_out); mo->setOut(_out); int size = mo->mazeSize(m1); v->setOut(_out); v->mazeSize(size); } private: Maze2d* m_light; Maze2d _m; }; class sizeFileCommand : public Command { public: sizeFileCommand(Maze2d* light) : m_light(light) {} sizeFileCommand(Maze2d _m1) { _m1 = m1; } void execute() { v = new View(_out); mo = new Model(_out); mo->setOut(_out); int size = mo->fileSize(m1); v->setOut(_out); v->fileSize(size); } private: Maze2d* m_light; Maze2d _m; }; class solveCommand : public Command { public: solveCommand(Maze2d* light) : m_light(light) {} solveCommand(Maze2d _m1) { _m1 = m1; } void execute() { v = new View(_out); mo = new Model(_out); mo->setOut(_out); //Solution s = mo->solve(m1, s1); //v->setOut(_out); //if(s.getSolution() != nullptr) //v->solve(s1); } private: Maze2d* m_light; Maze2d _m; }; class displySolveCommand : public Command { public: displySolveCommand(Maze2d* light) : m_light(light) {} displySolveCommand(Maze2d _m1) { _m1 = m1; } void execute() { v = new View(_out); mo = new Model(_out); v->setOut(_out); v->display(s1); } private: Maze2d* m_light; Maze2d _m; };
true
ee1b144663fe03d9cd846dfe5b58f56efeccdab0
C++
Girl-Code-It/Beginner-CPP-Submissions
/syeda reeha quasar/milestone 7/octal to decimal.cpp
UTF-8
406
3.046875
3
[]
no_license
#include<iostream> #include<math.h> using namespace std; int main() { long long octal , tempoctal, decimal=0; int rem , place=0; cout<<"enter the octal number:"; cin>>octal; tempoctal=octal; while(tempoctal!=0) { rem = tempoctal%10; decimal+= pow(8, place)*rem; tempoctal/=10; place++; } place*=1000; cout<<"octal number is="<<octal<<endl; cout<<"decimal number is ="<<decimal; }
true
cb33e9475deb699943de84b4c79c29a6b6d7a751
C++
RPMiller/CSC190Ryan_Miller
/GameSolution/Game/ParticleEffect.h
UTF-8
532
2.640625
3
[]
no_license
#pragma once #include "Core.h" #include "Particle.h" #include "RandomGenerator.h" #include "Vector2.h" class ParticleEffect { protected : Particle* particles; RandomGenerator randomGenerator; Vector3 origin; int numberOfParticles; Color color; public: ParticleEffect(int numParticles,Vector3 origin); ~ParticleEffect(void); bool isRunning(); void SetOrigin(Vector3 nextOrigin); virtual void Init() = 0; virtual void Update(float dt) = 0; virtual void Draw(Core::Graphics graphics) = 0; void SetColor(Color color); };
true
ea1339327106040a060d906fa816f67a8fdb15a7
C++
Hao1Zhang/OOP
/practical-04/function-2-1.cpp
UTF-8
146
3.078125
3
[]
no_license
#include<iostream> void print_sevens(int *nums,int length){ for (int i=0;i<length;i++){ std::cout<<*(nums+i)*7<<std::endl; } }
true
a25258cff873cf8799449f2e85b665e77e3c57aa
C++
bootchk/nRF5x
/src/drivers/clock/compareRegister.h
UTF-8
1,829
2.90625
3
[]
no_license
#pragma once /* * Types of initializer parameters are platform independent types so API is platform independent. * Implementation uses platform specific types */ #include <stddef.h> // size_t #include "counter.h" // OSTime type on Counter /* * Thin wrapper/facade on HW compare register of Nordic RTC device. * * Not a singleton; has non-static methods. * * But instances are constants and methods are const functions: * they change the hardware but no data members. */ class CompareRegister { // We are not enabling event routing: unsigned int eventMask = RTC_EVTEN_COMPARE0_Msk; const size_t eventAddress; // nrf_rtc_event_t HW offset of event register from device base address const uint32_t eventMask; // nrf_rtc_int_t Mask for bit in HW interrupt registers INTEN or EVTEN !!! const unsigned int selfIndex = 0; public: CompareRegister( const size_t aEventAddress, // nrf_rtc_event_t const uint32_t aEventMask, // nrf_rtc_int_t const unsigned int aIndex ): // Initializer list required for const data members, parameterized eventAddress(aEventAddress), eventMask(aEventMask), selfIndex(aIndex) {} // body required void enableInterrupt() const; /* * Enable/disable "event routing" i.e. generation of signal (pulse on event) to PPI * * The counter rolls over, and compare match will generate the event repetitively, unless disabled. */ void enableEventSignal() const; void disableEventSignal() const; private: void disableInterrupt() const; void clearEvent() const; public: void disableInterruptAndClearEvent() const; bool isEvent() const; /* * Set value. * The value is an "alarm time" on the circular Counter clock. * Whose type is OSTime (24-bit) */ void set(const uint32_t newCompareValue) const; uint32_t* getEventRegisterAddress() const; };
true
7837b085fb78541f9fb16a945ba1c2c5f82655b4
C++
itsme-aparna/Coding-Notes
/C++/GraphsCPP/courseSchedule2.cpp
UTF-8
1,077
2.640625
3
[]
no_license
Course Schedule II - LeetCode 210 class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { vector<int> adj[numCourses]; vector<int> in(numCourses, 0); vector<int> res; for(auto x: prerequisites){ adj[x[1]].push_back(x[0]); in[x[0]]++; } queue<int> q; int coursesProcessed = 0; for(int i = 0; i < numCourses; i++){ if(in[i]==0){ coursesProcessed++; q.push(i); } } while(!q.empty()){ int temp = q.front(); res.push_back(temp); q.pop(); for(auto x: adj[temp]){ in[x]--; if(in[x]==0){ coursesProcessed++; q.push(x); } } } if (numCourses != coursesProcessed) return {}; else return res; } };
true
913d0100e1ad37b6ff94cd238fe7e0af81078a00
C++
madingx/leetcode-cpp
/algorithms/cpp/exclusiveTimeofFunctions/ExclusiveTimeofFunctions.cpp
UTF-8
3,192
3.578125
4
[]
no_license
// Source : https://leetcode.com/problems/exclusive-time-of-functions/ // Author : Mading // Date : 2019-05-29 /********************************************************************************** * 636. Exclusive Time of Functions [Medium] * On a single threaded CPU, we execute some functions. * Each function has a unique id between 0 and N-1. * We store logs in timestamp order that describe when a function is entered or exited. * Each log is a string with this format: "{function_id}:{"start" | "end"}:{timestamp}". * For example, "0:start:3" means the function with id 0 started at the beginning of timestamp 3. * "1:end:2" means the function with id 1 ended at the end of timestamp 2. * A function's exclusive time is the number of units of time spent in this function. * Note that this does not include any recursive calls to child functions. * Return the exclusive time of each function, sorted by their function id. * Example 1: |fun1 start ******************************** fun1 end| |fun0 start **---------------------------------------------------------**** fun0 end| 0 1 2 3 4 5 6 * Input: * n = 2 * logs = ["0:start:0","1:start:2","1:end:5","0:end:6"] * Output: [3, 4] * Explanation: * Function 0 starts at the beginning of time 0, then it executes 2 units of time and reaches the end of time 1. * Now function 1 starts at the beginning of time 2, executes 4 units of time and ends at time 5. * Function 0 is running again at the beginning of time 6, and also ends at the end of time 6, thus executing for 1 unit of time. * So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing. * Note: * 1 <= n <= 100 * Two functions won't start or end at the same time. * Functions will always log when they exit. * **********************************************************************************/ // 32 ms, faster than 74.50% of C++, 11.4 MB, less than 81.04% of C++ class Solution { public: vector<int> exclusiveTime(int n, vector<string>& logs) { vector<int> res(n); stack<int> threadstack; int begin = 0; for(int i = 0; i<logs.size(); i++){ int a = logs[i].find(':'); int funid = atoi( string(logs[i],0,a).c_str() ); int timestamp = 0; if(logs[i][a+1] == 's'){ timestamp = atoi(string(logs[i],a+7,logs[i].size()-a-7).c_str()); if( !threadstack.empty()){ int preid = threadstack.top(); res[preid] += timestamp - begin; begin = timestamp; } threadstack.push(funid); } else if(logs[i][a+1] == 'e'){ timestamp = atoi(string(logs[i],a+5,logs[i].size()-a-5).c_str()); if( !threadstack.empty()){ threadstack.pop(); res[funid] += timestamp - begin + 1; begin = timestamp + 1; } } } return res; } };
true
89de32ded99669410e1dcf8fd5d66df253b84330
C++
arknave/sph_fluid_simulation
/src/simulation.cpp
UTF-8
6,358
2.703125
3
[]
no_license
#include "simulation.h" #include "parameters.h" #include <functional> #include <igl/viewer/Viewer.h> using namespace std; using namespace Eigen; // anonymous namespace to handle LibIGL viewer. namespace { bool key_down(igl::viewer::Viewer& viewer, unsigned char key, int mod, Simulation *sim) { if (key == ' ') sim->params->paused = !sim->params->paused; else if (key == 'R') sim->reset(); return false; } bool init(igl::viewer::Viewer& viewer, Simulation *sim) { viewer.ngui->addWindow(Vector2i(220, 10), "SPH Fluid Simulation"); // Simulation environment variables. viewer.ngui->addGroup("Simulation Parameters"); viewer.ngui->addVariable("Number of Particles", sim->params->nb_particles); viewer.ngui->addVariable("Radius", sim->params->radius); viewer.ngui->addVariable("Mass", sim->params->mass); viewer.ngui->addVariable("Density", sim->params->density); viewer.ngui->addVariable("Viscocity", sim->params->viscocity); viewer.ngui->addVariable("Gravity", sim->params->gravity); viewer.ngui->addVariable("Time Step", sim->params->time_step); viewer.ngui->addVariable("Current Time", sim->current_time, false); viewer.ngui->addButton("Reset Parameters", [sim](){ sim->params->reset(); }); // Simulation controls.. viewer.ngui->addGroup("Simulation Controls"); viewer.ngui->addButton("Toggle Simulation", [sim](){ sim->params->paused = !sim->params->paused; }); viewer.ngui->addButton("Reset Simulation", [sim](){ sim->reset(); }); // Generate widgets. viewer.screen->performLayout(); return false; } bool post_draw(igl::viewer::Viewer& viewer, Simulation *sim) { // Take a step. if (!sim->params->paused) sim->step(); // Get the current mesh of the simulation. MatrixX3d V; MatrixX3i F; sim->render(V, F); // Update the viewer. viewer.data.clear(); viewer.data.set_mesh(V, F); // Signal to render. glfwPostEmptyEvent(); return false; } } // end anonymous namespace to handle LibIGL viewer. void Simulation::initialize() { cout << "Initializing simulation." << endl; meshes_.push_back(new Mesh("../obj/sphere.obj")); for (int i = 0; i < params->nb_particles; i++) { for (int j = 0; j < params->nb_particles; j++) { for (int k = 0; k < params->nb_particles; k++) { Particle *particle = new Particle(meshes_.front()); particle->m = params->mass; particle->r = params->radius; particle->c = Vector3d(i * 0.1, j * 0.1, k * 0.1); particle->v = Vector3d(i * 0.1, j * 0.1, k * 0.1); particles_.push_back(particle); } } } cout << "Total particles: " << particles_.size() << endl; } void Simulation::start() { igl::viewer::Viewer viewer; viewer.callback_key_down = bind(key_down, placeholders::_1, placeholders::_2, placeholders::_3, this); viewer.callback_init = bind(init, placeholders::_1, this); viewer.callback_post_draw = bind(post_draw, placeholders::_1, this); // Get all the meshes in the simulation. MatrixX3d V; MatrixX3i F; render(V, F); // Update the viewer. viewer.data.clear(); viewer.data.set_mesh(V, F); viewer.launch(); } void Simulation::reset() { cout << "Resetting simulation." << endl; // Clean up memory. for (Particle *particle : particles_) delete particle; for (Mesh *mesh : meshes_) delete mesh; // Reset the containers. particles_.clear(); meshes_.clear(); // Reinitialize. initialize(); } void Simulation::step() { int n = particles_.size(); double h = params->time_step; // New positions. VectorXd c_new(n * 3); // Velocity Verlet (update position, then velocity). for (int i = 0; i < n; i++) { c_new.segment<3>(i * 3) = particles_[i]->c + h * particles_[i]->v; particles_[i]->c = c_new.segment<3>(i * 3); } // F = -dV'. VectorXd forces = getForces(c_new); // F = ma. for (int i = 0; i < n; i++) particles_[i]->v += h / particles_[i]->m * forces.segment<3>(i * 3); // Update the clock. current_time += h; } void Simulation::render(MatrixX3d &V, MatrixX3i &F) const { // Find out the total number of vertex and face rows needed. int total_v_rows = 0; int total_f_rows = 0; for (const Particle *particle : particles_) { total_v_rows += particle->getV().rows(); total_f_rows += particle->getF().rows(); } // Reallocate to the proper amount of space. V.resize(total_v_rows, 3); V.setZero(); F.resize(total_f_rows, 3); F.setZero(); // The current block of vertices and faces. int total_v = 0; int total_f = 0; // Add each mesh to be rendered. for (const Particle *particle : particles_) { int nb_v = particle->getV().rows(); int nb_f = particle->getF().rows(); V.block(total_v, 0, nb_v, 3) = particle->getV(); F.block(total_f, 0, nb_f, 3) = particle->getF().array() + total_v; // Get the next offset. total_v += nb_v; total_f += nb_f; } } VectorXd Simulation::getForces(const VectorXd &c_new) const { // Accumulation of different forces. VectorXd force(c_new.rows()); force.setZero(); getGravityForce(c_new, force); getBoundaryForce(c_new, force); return force; } void Simulation::getGravityForce(const VectorXd &c_new, VectorXd &force) const { for (int i = 0; i < particles_.size(); i++) force(i * 3 + 1) += particles_[i]->m * params->gravity; } void Simulation::getBoundaryForce(const VectorXd &c_new, VectorXd &force) const { for (int i = 0; i < particles_.size(); i++) { const Vector3d &c = c_new.segment<3>(i * 3); double m = particles_[i]->m; for (int j = 0; j < 3; j++) { double p = c(j); double k = params->boundary_penalty; double b_min = params->boundary_min; double b_max = params->boundary_max; if (p < b_min) force(i * 3 + j) += (b_min - p) * k * m; if (p > b_max) force(i * 3 + j) += (b_max - p) * k * m; } } } Simulation::~Simulation() { delete params; for (Particle *particle : particles_) delete particle; for (Mesh *mesh : meshes_) delete mesh; }
true
988b3469a70040f8f927f91d0a1c20065f733d82
C++
SaeanSavin/Pac-man-SDL2-Exam
/PG4401_Eksamen/Animation.cpp
UTF-8
605
2.875
3
[]
no_license
#include "Animation.h" Animation::Animation(SDL_Renderer* r, std::string path, int tickRate) { length = 0; rate = tickRate; startTime = SDL_GetTicks(); for (const auto& entry : std::filesystem::directory_iterator(path)) { length++; auto tm = std::make_unique<Texture_Manager>(); if (entry.path().has_extension()) { frames.emplace_back(tm->loadTexture(&(entry.path().string())[0], r)); } } } SDL_Texture* Animation::getFrame() { int frame = ((SDL_GetTicks() - startTime) * rate / 1000) % length; return frames[frame]; } void Animation::resetAnimation() { startTime = SDL_GetTicks(); }
true
0392fe6437a0b497cc341b2e020be21539a5c15f
C++
Marcelo-Alarcon/Assignment5
/PscToC++/backend/interpreter/RuntimeStack.h
UTF-8
1,956
3.15625
3
[]
no_license
/** * <h1>RuntimeStack</h1> * * <p>The interpreter's runtime stack.</p> * * <p>Copyright (c) 2020 by Ronald Mak</p> * <p>For instructional purposes only. No warranties.</p> */ #ifndef RUNTIMESTACK_H_ #define RUNTIMESTACK_H_ #include <string> #include <vector> #include "RuntimeDisplay.h" #include "StackFrame.h" namespace backend { namespace interpreter { class RuntimeStack { private: vector<StackFrame *> stack; // runtime stack RuntimeDisplay *display; // runtime display public: /** * Constructor. */ RuntimeStack() : display(new RuntimeDisplay()) {} /** * Destructor. */ ~RuntimeStack() { delete display; } /** * @return an array list of the activation records on the stack. */ vector<StackFrame *> *records() { return &stack; } /** * Get the topmost stack frame at a given nesting level. * @param nestingLevel the nesting level. * @return the stack frame. */ StackFrame *getTopmost(const int nestingLevel) const { return display->getStackFrame(nestingLevel); } /** * Get the current nesting level. * @return the current level. */ int currentNestingLevel() const { int topIndex = stack.size() - 1; return topIndex >= 0 ? stack[topIndex]->getNestingLevel() : -1; } /** * Push a stack frame onto the stack for a routine being called. * @param frame the stack frame to push. */ void push(StackFrame *frame) { int nestingLevel = frame->getNestingLevel(); stack.push_back(frame); display->callUpdate(nestingLevel, frame); } /** * Pop a stack frame off the stack for a returning routine. */ void pop() { display->returnUpdate(currentNestingLevel()); stack.erase(stack.begin() + stack.size() - 1); } }; }} // namespace backend::interpreter #endif /* RUNTIMESTACK_H_ */
true
723a0d5120aea93403c0ea884fb71885647b9b00
C++
jhongpananon/Quadcopter
/L5_Application/quadcopter/quadcopter.hpp
UTF-8
946
2.828125
3
[]
no_license
/** * @file */ #ifndef QUADCOPTER_HPP_ #define QUADCOPTER_HPP_ #include "quadcopter_base.hpp" #include "lpc_pwm.hpp" /** * The quadcopter class * * This provides the interface to set the rotor PWMs */ class Quadcopter : public QuadcopterBase, public SingletonTemplate<Quadcopter> { public: /** * @{ Pure virtual method overrides of the MotorControllerIface */ void applyMotorValues(const motorValues_t& values); /** @} */ private: /// Private constructor for singleton class Quadcopter(); PWM mNorthMotor; ///< North motor PWM PWM mSouthMotor; ///< South motor PWM PWM mEastMotor; ///< East motor PWM PWM mWestMotor; ///< West motor PWM ///< Friend class used for Singleton Template friend class SingletonTemplate<Quadcopter>; }; #endif /* QUADCOPTER_HPP_ */
true
2c6db8e85887a2dc027588dee28eb051a8b70732
C++
Tomaat132/ProjectThirdPerson
/uGE/Colliders/SphereCollider.hpp
UTF-8
547
2.671875
3
[]
no_license
#ifndef SPHERECOLLIDER_H #define SPHERECOLLIDER_H #include "..\Collider.hpp" //the " .." means that the file is in the folder above namespace uGE { class SphereCollider : public Collider { public: SphereCollider(GameObject * aParent, float aRadius, std::string aName = "Sphere"); virtual ~SphereCollider(); float getRadius(); protected: private: float radius; };//end of SphereCollider class }//end of uGE #endif // SPHERECOLLIDER_H
true
afaeb183fde58d71d3da641936f4f15517e00c9f
C++
artyomdmitriev/cpp-labs
/hw15/task1/main.cpp
UTF-8
403
3.125
3
[]
no_license
#include <iostream> #include "Point.h" using namespace std; int main() { Point p(3, 4); Point p2(5, 6); cout << "X: " << p.getX() << endl; cout << "Y: " << p.getY() << endl; cout << "d0 distance: " << p.d0() << endl; cout << "Distance between p1 and p2: " << p.d(p2) << endl; cout << p << endl; cout << "Enter x and y for point: " << endl; cin >> p; return 0; }
true
20869385cfe77b5ceba03592236de5ba331d1601
C++
TheiloT/Projet-COVD
/edition.cpp
UTF-8
12,247
2.609375
3
[]
no_license
#include "edition.h" #include "correspondance.h" #include "jeu.h" void affiche_grille(int H, int L, int taille_case){ for (int i=0; i<=H; i++){ drawLine(0, i*taille_case, L*taille_case, i*taille_case, BLACK, 2); } for (int j=0; j<=L; j++){ drawLine(j*taille_case, 0, j*taille_case, H*taille_case, BLACK, 2); } } void drawAction(int x, int y, int k, int taille_case){ if (k == bouton_play){ int xa = x + int (0.25*taille_case); int xb = x + int (0.25*taille_case); int xc = x + int (0.85*taille_case); int ya = y + int (0.80*taille_case); int yb = y + int (0.20*taille_case); int yc = y + int (0.5*taille_case); int coord_triangle[6] = {xa, ya, xb, yb, xc, yc}; // triangle du bouton "play" fillRect(x, y, taille_case, taille_case, RED); fillPoly(coord_triangle, 3, WHITE); drawPoly(coord_triangle, 3, BLACK, 2); } else if (k == bouton_sauvegarder){ string s = "S"; drawString(x + int(0.2*taille_case), y + int(0.85*taille_case), s, BLACK, int (0.5*taille_case)); } else if (k == bouton_quitter){ int d = int (0.2 * taille_case); fillRect(x, y, taille_case, taille_case, RED); drawLine(x + 4 + d, y + 4 + d, x + taille_case - 4 - d, y + taille_case - 4 - d, WHITE, 8); drawLine(x + taille_case - 4 - d, y + 4 + d, x + 4 + d, y + taille_case - 4 - d, WHITE, 8); } else if (k == bouton_reset){ string r = "R"; drawString(x + int(0.2*taille_case), y + int(0.85*taille_case), r, BLACK, int (0.5*taille_case)); } } void drawBouton(int x, int y, int k, int taille_case_editeur){ int marge = int (taille_case_editeur/8.0); dessineCase(x + marge, y + marge, taille_case_editeur - 2*marge, k, neutre); } void affiche_boutons(int L, int taille_case, int taille_case_editeur, int bande_texte, string nom_map){ int x_dep = L * taille_case; // Lignes de separation drawLine(x_dep, bande_texte, x_dep + 6.5 * taille_case_editeur, bande_texte, BLACK, 2); drawLine(x_dep, bande_texte + 2 * taille_case_editeur, x_dep + 6.5 * taille_case_editeur, bande_texte + 2 * taille_case_editeur, BLACK, 2); drawLine(x_dep, bande_texte + 4 * taille_case_editeur, x_dep + 6.5 * taille_case_editeur, bande_texte + 4 * taille_case_editeur, BLACK, 2); // Affichage du nom de la map int dx = int (3.25*taille_case_editeur - taille_case_editeur * 0.125 * nom_map.size() ); int dy = int (0.5 * bande_texte - 0.125 * taille_case_editeur ); drawString(x_dep + dx, bande_texte - dy, nom_map, BLACK, int (taille_case_editeur * 0.25)); // Affichage des cases d'action int y_a = bande_texte + taille_case_editeur/2.0; for (int j = 0; j<3; j++){ int x = x_dep + (1.5*j + 0.5)*taille_case_editeur; int y = y_a; drawAction(x, y, j, taille_case_editeur); drawRect(x, y, taille_case_editeur, taille_case_editeur, BLACK, 2); } // Affichage des cases couleur int y_c = bande_texte + taille_case_editeur* (2.5); for (int j = 0; j<4; j++){ int x = x_dep + (1.5*j + 0.5)*taille_case_editeur; int y = y_c; fillRect(x, y, taille_case_editeur, taille_case_editeur, couleur_int_vers_color.at(j)); drawRect(x, y, taille_case_editeur, taille_case_editeur, BLACK, 2); } // Affichage des cases bloc int y_b = bande_texte + taille_case_editeur* (4); for (int j = 0; j<4; j++){ for (int i = 0; i<3; i++){ int x = x_dep + (1.5*j + 0.5)*taille_case_editeur; int y = y_b + (1.5*i + 0.5)*taille_case_editeur; drawBouton(x, y, Liste_boutons[j + 4*i][0], taille_case_editeur); drawRect(x, y, taille_case_editeur, taille_case_editeur, BLACK, 2); } } } bool getAction(int x, int y, int &bouton_action, int bande_texte, int L, int taille_case, int taille_case_editeur){ int x_dep = L*taille_case; if ( y < bande_texte + 1.5*taille_case_editeur && y > bande_texte + 0.5*taille_case_editeur){ // Verifie que la souris est a la bonne hauteur float num_x = (2.0 *(x - x_dep) / float(taille_case_editeur)) / 3.0; if (num_x - floor(num_x) > 1/3.0 && floor(num_x >= 0 && floor(num_x) < 4)){ bouton_action = floor (num_x); return true; } } return false; } bool getCouleur(int x, int y, int &bouton_couleur, int bande_texte, int L, int taille_case, int taille_case_editeur){ int x_dep = L*taille_case; if ( y < bande_texte + 3.5*taille_case_editeur && y > bande_texte + 2.5*taille_case_editeur){ // Verifie que la souris est a la bonne hauteur float num_x = (2.0 *(x - x_dep) / float(taille_case_editeur)) / 3.0; if ( num_x - floor(num_x) > 1/3.0 && floor(num_x >= 0 && floor(num_x) < 4) ){ bouton_couleur = floor (num_x); return true; } } return false; } bool getBloc(int x, int y, int &bouton_bloc, int bande_texte, int L, int taille_case, int taille_case_editeur, int nb_lignes){ int x_dep = L*taille_case; int y_dep = bande_texte + 4*taille_case_editeur; float num_x = (2.0 *(x - x_dep) / float(taille_case_editeur)) / 3.0; // numero de la colonne de boutons float num_y = (2.0 *(y - y_dep) / float(taille_case_editeur)) / 3.0; // numero de la ligne de boutons if ( num_x - floor(num_x) > 1/3.0 && num_y - floor(num_y) > 1/3.0 && floor(num_x >= 0 && floor(num_x) < 4 && floor(num_y >= 0 && floor(num_y) < nb_lignes ))){ bouton_bloc = floor (num_x) + 4 * floor(num_y); return true; } return false; } bool getEffet(int x, int y, int &bouton_effet, int bande_texte, int L, int taille_case, int taille_case_editeur, int nb_lignes){ int x_dep = L*taille_case; int y_dep = bande_texte + 2*taille_case_editeur; float num_x = (2.0 *(x - x_dep) / float(taille_case_editeur)) / 3.0; // numero de la colonne de boutons float num_y = (2.0 *(y - y_dep) / float(taille_case_editeur)) / 3.0; // numero de la ligne de boutons if ( num_x - floor(num_x) > 1/3.0 && num_y - floor(num_y) > 1/3.0 && floor(num_x >= 0 && floor(num_x) < 4 && floor(num_y >= 0 && floor(num_y) < nb_lignes ))){ int numero_case = floor (num_x) + 4 * floor(num_y); if (numero_case==7) bouton_effet=mur_modif; else bouton_effet = effets[numero_case]; return true; } return false; } bool placeBloc(int x, int y, int L, int H, int taille_case){ return ( x>0 && x<L*taille_case && y>0 && y<H*taille_case); } void creer_map(string nom_map, int L, int H, int taille_case, bool editer, Map map_a_editer, int num_map, int nb_niveaux, const string niveau){ const int taille_case_editeur = 2*taille_case; const int bande_texte = taille_case_editeur; const int nb_lignes = 3; // Ouverture de la fenetre Window w = openWindow(L*taille_case + 6.5 * taille_case_editeur, max( H*taille_case, int(bande_texte + (9.0 * taille_case_editeur)) ) ); setActiveWindow(w); if (!editer){ // Si on part de zero // Creation de la map map_a_editer = Map(nom_map, H,L); } map_a_editer.affiche_tout(taille_case); // Affichage de la map // Affichage de la grille et des boutons affiche_boutons(L, taille_case, taille_case_editeur, bande_texte, nom_map); affiche_grille(H, L, taille_case); int bouton_couleur = bouton_neutre; // Initialisation de la couleur a neutre int n_item = 0; // Correspond au premier item d'un vecteur bouton int bouton_bloc = 3; // Correspond au bloc vide int bouton_action = 4; // Correspond a aucune action // Coordonnees de la souris int x; int y; // Memoire de la derniere case visitee int dernier_x_case = -1; int dernier_y_case = -1; // Mode de saisi bool set_bloc = false; bool set_couleur = false; bool fin = false; while ( ! fin ){ getMouse(x, y); if ( getAction(x, y, bouton_action, bande_texte, L, taille_case, taille_case_editeur) ){ if (bouton_action == bouton_play){ drawLine(L * taille_case+1, 0, L * taille_case+1, H*taille_case,BLACK, 1); // Correction bug affichage int trash; // Ici on n'utilise pas le nombre d'etoiles collectees, donc on utilise un une variable "poubelle" run(map_a_editer, taille_case, trash); map_a_editer.affiche_tout(taille_case); drawLine(L * taille_case+1, 0, L * taille_case+1, H*taille_case,WHITE, 1); // Correction bug affichage affiche_grille(H, L, taille_case); } else if (bouton_action == bouton_sauvegarder){ // Sauvevarder le niveau cree int nb_portes_entree = 0; for (int j=0; j<L; j++) { for (int i=0; i<H; i++){ nb_portes_entree += est_dans(map_a_editer.get_case(j, i), portes_entree); } } if (nb_portes_entree==1) { // S'il y a bien une seule entree if (!editer){ map_a_editer.sauvegarder(niveau); closeWindow(w); fin = true; } else{ map_a_editer.sauvegarder_et_ecraser(num_map, niveau, nb_niveaux); closeWindow(w); fin = true; } } else { const int W_message = 700; const int H_message = 100; const int marge_x = int(W_message/12); const int marge_y = int(H_message/2); const string menu = "Erreur"; Window message_Window = openWindow(W_message, H_message, menu); setActiveWindow(message_Window); fillRect(0, 0, W_message, H_message, BLACK); string message = "Votre niveau doit avoir exactement 1 entrée !"; drawString(marge_x, marge_y, message, WHITE, W_message/40); click(); closeWindow(message_Window); setActiveWindow(w); } } else if (bouton_action == bouton_quitter){ // Quitter la creation de map sans sauvegarder closeWindow(w); fin = true; } } else if (getCouleur(x, y, bouton_couleur, bande_texte, L, taille_case, taille_case_editeur)){ set_couleur = true; set_bloc = false; } else if (getBloc(x, y, bouton_bloc, bande_texte, L, taille_case, taille_case_editeur, nb_lignes)){ n_item = 0; set_bloc = true; set_couleur = false; bouton_couleur = bouton_neutre; } else if (placeBloc(x, y, L, H, taille_case)){ int x_case = floor(x/taille_case); int y_case = floor(y/taille_case); // On modifie la map if (set_bloc){ if (x_case == dernier_x_case && y_case == dernier_y_case){ n_item = (n_item + 1) % Liste_boutons[bouton_bloc].size(); // On passe a l'item suivant si on reclique sur la meme case } else{ n_item = 0; // On repasse au premier item si on ne reclique pas sur la même case } map_a_editer.set_case(x_case, y_case, Liste_boutons[bouton_bloc][n_item]); dernier_x_case = x_case; dernier_y_case = y_case; } if (set_couleur){ map_a_editer.set_couleur(x_case, y_case, bouton_couleur); } // Dessin de la case map_a_editer.drawCase(x_case, y_case, taille_case); affiche_grille(H, L, taille_case); } } } void editer_map(Map map, int taille_case, int num_map, int nb_niveaux, string niveau){ creer_map (map.get_nom(), map.get_L(), map.get_H(), taille_case, true, map, num_map, nb_niveaux, niveau); }
true
08fcdb12f9bb84b930b866490b295f9ba962cbf0
C++
moevm/oop
/8382/Rocheva_Anna/lab5/landscapes/Forest.hpp
UTF-8
399
2.703125
3
[]
no_license
#ifndef LABOOP_FOREST_HPP #define LABOOP_FOREST_HPP #include "Landscape.hpp" class Forest : public Landscape{ public: Forest() : Landscape() {landName = FOREST;}; char getName() final {return 'F';}; void changeAttribute(Unit *unit) final {unit->changeAttributes(-10, 0, 0);}; Land getLandName() final {return landName;}; private: Land landName; }; #endif //LABOOP_FOREST_HPP
true
1a7fea35ffdf0782522350a3f0e04b3f7319eb63
C++
Xiao-MM/CProject
/sort/MergeSort.cpp
UTF-8
1,050
3.4375
3
[]
no_license
#include<iostream> using namespace std; void Merge(int*,int,int,int); //分解+合并 void MergeSort(int *arr, int start, int end){ int mid = (start + end)/2; if (start >= end){ return; } MergeSort(arr, start, mid); MergeSort(arr, mid+1, end); Merge(arr,start,mid,end); } //归并 void Merge(int *arr,int start,int mid,int end){ int *temp = (int *)malloc((end-start+1)*sizeof(int)); int i = start; int j = mid + 1; int k = 0; while (i <= mid && j <= end){ if (arr[i]<arr[j]) temp[k++] = arr[i++]; else temp[k++] = arr[j++]; } while (i <= mid) temp[k++] = arr[i++]; while (j <= end) temp[k++] = arr[j++]; for (int i = 0; i <= (end - start); i++) arr[start + i] = temp[i]; free(temp); } void printArr(int arr[],int len){ for (int i = 0; i < len; i++) cout<<arr[i]<<" "; cout<<endl; } int main(){ int arr[] = {2,1,4,3,7,5,9,9,6}; printArr(arr,9); MergeSort(arr,0,8); printArr(arr,9); }
true
44f8db6aa6be48e62ac762ef37a399fe3e204c37
C++
surbhit-sinha/1_d_combat_simulator
/1_d_combat_simulator.cpp
UTF-8
2,349
3.578125
4
[]
no_license
#include<iostream> #include<string> #include<random> using namespace std; int main() { mt19937 randGenerator(time(0)); // random number generator uniform_int_distribution<int> humanPower(50,100); // damage caused by human uniform_int_distribution<int> robotPower(30,60); // damage caused by robot // chance of hitting opponent uniform_real_distribution<float> chance(0.0f, 1.0f); int num_humans, num_robots; char current_chance = 'H'; // The game starts with humans attacking // Human properties float human_attack = 0.60; int human_strength = 200; int human_damage = humanPower(randGenerator); // Amount of damage done is random // Robot properties float robot_attack = 0.45; int robot_strength = 90; int robot_damage = robotPower(randGenerator); // Amount of damage done is random int current_human = human_strength, current_robot = robot_strength; // Tells the power of the current player fighting cout<<"Robots vs Humans!!!\n\n"; cout<<"This is the game of robots vs humans, where \nthe two species battle it out to be the best on Planet Earth.\n\n"; cout<<"Enter the number of humans you want to fight with"<<endl; cin>>num_humans; cout<<"Enter the number of robots"<<endl; cin>>num_robots; cout<<"\nStart fight!\n"<<endl; int temp_humans = num_humans, temp_robots = num_robots; while(temp_humans > 0 && temp_robots > 0) { float attack = chance(randGenerator); if (current_chance == 'H' && attack>human_attack) { current_robot -= human_damage; if (current_robot<0) { temp_robots--; current_robot = robot_strength; } current_chance = 'R'; } else if(current_chance == 'R' && attack>robot_attack) { current_human -= robot_damage; if (current_human<0) { temp_humans--; current_human = human_strength; } current_chance = 'H'; } } cout<<"FIGHT ENDED!!\n\nRESULTS --->\n\n"; if(temp_robots == 0 && temp_humans>0) { cout<<"\tHUMANS WON!"; cout<<"\n\tNumber of humans left = "<<temp_humans<<endl; } else if(temp_humans == 0 && temp_robots>0) { cout<<"\tROBOTS WON!"; cout<<"\n\tNumber of robots left = "<<temp_robots<<endl; } else if(temp_robots == 0 && temp_humans == 0) { cout<<"\tTIE!"; } cout<<"\tNumber of humans died = "<<num_humans-temp_humans<<", Number of robots died "<<num_robots-temp_robots<<endl; return 0; }
true
2361ace8367d8a6435af47ee2777218fa16cb6d2
C++
George-Creekbed/Nand2Tetris
/08/CodeWriter.cpp
UTF-8
21,049
2.953125
3
[]
no_license
#ifndef CODEWRITER_CPP_INCLUDED #define CODEWRITER_CPP_INCLUDED #include <iostream> #include <string> #include <algorithm> #include "CodeWriter.h" using std::string; using std::endl; using std::transform; CodeWriter::CodeWriter(const string& filename, const char* argv) { string argument(argv); size_t found_vm = argument.find(".vm"); if (found_vm == string::npos) // from directory { string::size_type slash = argument.rfind("\\"); // look for last instance of '\' in the path of directory string folder_name( argument.substr(slash) ); // substring created from 'slash' to the end write(argument + '\\' + folder_name + ".asm"); } else write(filename + ".asm"); // from file } void CodeWriter::write(const string& filename) { output_file.open(filename); //, std::ofstream::out | std::ofstream::app); } void CodeWriter::writeArithmetic(const string& arg1) { static int counter_true = 0; static int counter_end = 0; if (arg1 == "add") add(); else if (arg1 == "sub") sub(); else if (arg1 == "neg") neg(); else if (arg1 == "eq") // TRUE = -1; FALSE = 0 eq(counter_true, counter_end); else if (arg1 == "gt") // TRUE = -1; FALSE = 0 gt(counter_true, counter_end); else if (arg1 == "lt") // TRUE = -1; FALSE = 0 lt(counter_true, counter_end); else if (arg1 == "and") and_b(); else if (arg1 == "or") or_b(); else if (arg1 == "not") not_b(); } void CodeWriter::writePushPop(const string& c_push_pop, const string& segment, const int& index, const string& filename) { if (segment == "constant") constant(index); else if (segment == "local") { if (c_push_pop == "C_PUSH") localPush(index); else if (c_push_pop == "C_POP") localPop(index); } else if (segment == "argument") { if (c_push_pop == "C_PUSH") argumentPush(index); else if (c_push_pop == "C_POP") argumentPop(index); } else if (segment == "this") { if (c_push_pop == "C_PUSH") thisPush(index); else if (c_push_pop == "C_POP") thisPop(index); } else if (segment == "that") { if (c_push_pop == "C_PUSH") thatPush(index); else if (c_push_pop == "C_POP") thatPop(index); } else if (segment == "static") { if (c_push_pop == "C_PUSH") staticPush(index, filename); else if (c_push_pop == "C_POP") staticPop(index, filename); } else if (segment == "temp") { if (c_push_pop == "C_PUSH") tempPush(index); else if (c_push_pop == "C_POP") tempPop(index); } else if (segment == "pointer") { if (c_push_pop == "C_PUSH") pointerPush(index); else if (c_push_pop == "C_POP") pointerPop(index); } } // auxiliary method to writeLabel, writeIf, writeGoto: turns label uppercase string CodeWriter::labelUpper(const string& label, const string& function_name) { string label_upper(label.size(), ' '); transform(label.begin(), label.end(), label_upper.begin(), toupper); if ( function_name.empty() ) return label_upper; else return function_name + '$' + label_upper; } void CodeWriter::writeLabel(const string& label, const string& function_name = "") { output_file << '(' << labelUpper(label, function_name) << ')' << endl; } void CodeWriter::writeGoto(const string& label, const string& function_name = "") { output_file << "@" << labelUpper(label, function_name) << endl; output_file << "0; JMP" << endl; } void CodeWriter::writeIf(const string& label, const string& function_name = "") { output_file << "@SP" << endl; output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; output_file << "@" << labelUpper(label, function_name) << endl; output_file << "D; JLT" << endl; // TRUE condition D = -1 } void CodeWriter::writeFunction(const string& function_name, const int& num_locals) { // not using 'writeLabel' function for this because it'd generate all-uppercase label output_file << '(' << function_name << ')' << endl; for (int i = 0; i != num_locals; ++i) // PUSH constant 0; num_locals times constant(0); } void CodeWriter::writeReturn() { output_file << "@LCL" << endl; // endFrame[R14] = LCL output_file << "D = M" << endl; output_file << "@R14" << endl; output_file << "M = D" << endl; output_file << "@5" << endl; // retAddr[R15] = *(endFrame[R14] - 5) output_file << "D = A" << endl; output_file << "@R14" << endl; output_file << "D = M - D" << endl; output_file << "A = D" << endl; output_file << "D = M" << endl; output_file << "@R15" << endl; output_file << "M = D" << endl; argumentPop(0); // *ARG = pop output_file << "@ARG" << endl; // SP = ARG + 1 output_file << "D = M + 1" << endl; output_file << "@SP" << endl; output_file << "M = D" << endl; output_file << "@R14" << endl; // THAT = *(endFrame[R14] - 1) output_file << "MD = M - 1" << endl; output_file << "A = D" << endl; output_file << "D = M" << endl; output_file << "@THAT" << endl; output_file << "M = D" << endl; output_file << "@R14" << endl; // THIS = *(endFrame - 2) output_file << "MD = M - 1" << endl; output_file << "A = D" << endl; output_file << "D = M" << endl; output_file << "@THIS" << endl; output_file << "M = D" << endl; output_file << "@R14" << endl; // ARG = *(endFrame - 3) output_file << "MD = M - 1" << endl; output_file << "A = D" << endl; output_file << "D = M" << endl; output_file << "@ARG" << endl; output_file << "M = D" << endl; output_file << "@R14" << endl; // LCL = *(endFrame - 4) output_file << "MD = M - 1" << endl; output_file << "A = D" << endl; output_file << "D = M" << endl; output_file << "@LCL" << endl; output_file << "M = D" << endl; output_file << "@R15" << endl; output_file << "A = M" << endl; output_file << "0; JMP" << endl; } void CodeWriter::writeCall(const string& function_name, const int& num_args) { static int counter_return = 0; string return_address( function_name + ".RETURN." + std::to_string(counter_return) ); output_file << "@" << return_address << endl; // push retAddrLabel output_file << "D = A" << endl; output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; output_file << "M = M + 1" << endl; output_file << "@LCL" << endl; // push LCL output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; output_file << "M = M + 1" << endl; output_file << "@ARG" << endl; // push ARG output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; output_file << "M = M + 1" << endl; output_file << "@THIS" << endl; // push THIS output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; output_file << "M = M + 1" << endl; output_file << "@THAT" << endl; // push THAT output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; output_file << "M = M + 1" << endl; output_file << "@5" << endl; // ARG = SP - 5 - num_args output_file << "D = A" << endl; output_file << "@" << num_args << endl; output_file << "D = D + A" << endl; output_file << "@SP" << endl; output_file << "D = M - D" << endl; output_file << "@ARG" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // LCL = SP output_file << "D = M" << endl; output_file << "@LCL" << endl; output_file << "M = D" << endl; output_file << "@" << function_name << endl; // goto function_name label of called function output_file << "0; JMP" << endl; output_file << '(' << return_address << ')' << endl; // define retAddrLabel ++counter_return; } // auxiliaries to writeArithmetic void CodeWriter::add() { output_file << "@SP" << endl; output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = M + D" << endl; } void CodeWriter::sub() { output_file << "@SP" << endl; output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = M - D" << endl; } void CodeWriter::neg() { output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = -M" << endl; } void CodeWriter::eq(int& counter_true, int& counter_end) // TRUE = -1; FALSE = 0 { output_file << "@SP" << endl; output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "D = M - D" << endl; output_file << "@TRUE" << counter_true << endl; output_file << "D; JEQ" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = 0" << endl; output_file << "@END" << counter_end << endl; output_file << "0; JMP" << endl; output_file << "(TRUE" << counter_true << ")" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = -1" << endl; output_file << "(END" << counter_end << ")" << endl; counter_true++; counter_end++; } void CodeWriter::gt(int& counter_true, int& counter_end) // TRUE = -1; FALSE = 0 { output_file << "@SP" << endl; output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "D = M - D" << endl; output_file << "@TRUE" << counter_true << endl; output_file << "D; JGT" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = 0" << endl; output_file << "@END" << counter_end << endl; output_file << "0; JMP" << endl; output_file << "(TRUE" << counter_true << ")" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = -1" << endl; output_file << "(END" << counter_end << ")" << endl; counter_true++; counter_end++; } void CodeWriter::lt(int& counter_true, int& counter_end) // TRUE = -1; FALSE = 0 { output_file << "@SP" << endl; output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "D = M - D" << endl; output_file << "@TRUE" << counter_true << endl; output_file << "D; JLT" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = 0" << endl; output_file << "@END" << counter_end << endl; output_file << "0; JMP" << endl; output_file << "(TRUE" << counter_true << ")" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = -1" << endl; output_file << "(END" << counter_end << ")" << endl; counter_true++; counter_end++; } void CodeWriter::and_b() { output_file << "@SP" << endl; output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = M & D" << endl; } void CodeWriter::or_b() { output_file << "@SP" << endl; output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = M | D" << endl; } void CodeWriter::not_b() { output_file << "@SP" << endl; output_file << "A = M - 1" << endl; output_file << "M = !M" << endl; } // auxiliaries to writePushPop void CodeWriter::constant(const int& index) { output_file << "@" << index << endl; output_file << "D = A" << endl; output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; output_file << "M = M + 1" << endl; } void CodeWriter::localPush(const int& index) { output_file << "@" << index << endl; // addr = LCL + i output_file << "D = A" << endl; output_file << "@LCL" << endl; output_file << "A = M + D" << endl; output_file << "D = M" << endl; // *SP = *addr output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP++ output_file << "M = M + 1" << endl; } void CodeWriter::localPop(const int& index) { output_file << "@" << index << endl; // addr = LCL + i output_file << "D = A" << endl; output_file << "@LCL" << endl; output_file << "A = M + D" << endl; output_file << "D = A" << endl; output_file << "@R13" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP-- output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; // *addr = *SP output_file << "@R13" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; } void CodeWriter::argumentPush(const int& index) { output_file << "@" << index << endl; // addr = ARG + i output_file << "D = A" << endl; output_file << "@ARG" << endl; output_file << "A = M + D" << endl; output_file << "D = M" << endl; // *SP = *addr output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP++ output_file << "M = M + 1" << endl; } void CodeWriter::argumentPop(const int& index) { output_file << "@" << index << endl; // addr = ARG + i output_file << "D = A" << endl; output_file << "@ARG" << endl; output_file << "A = M + D" << endl; output_file << "D = A" << endl; output_file << "@R13" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP-- output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; // *addr = *SP output_file << "@R13" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; } void CodeWriter::thisPush(const int& index) { output_file << "@" << index << endl; // addr = THIS + i output_file << "D = A" << endl; output_file << "@THIS" << endl; output_file << "A = M + D" << endl; output_file << "D = M" << endl; // *SP = *addr output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP++ output_file << "M = M + 1" << endl; } void CodeWriter::thisPop(const int& index) { output_file << "@" << index << endl; // addr = THIS + i output_file << "D = A" << endl; output_file << "@THIS" << endl; output_file << "A = M + D" << endl; output_file << "D = A" << endl; output_file << "@R13" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP-- output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; // *addr = *SP output_file << "@R13" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; } void CodeWriter::thatPush(const int& index) { output_file << "@" << index << endl; // addr = THAT + i output_file << "D = A" << endl; output_file << "@THAT" << endl; output_file << "A = M + D" << endl; output_file << "D = M" << endl; // *SP = *addr output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP++ output_file << "M = M + 1" << endl; } void CodeWriter::thatPop(const int& index) { output_file << "@" << index << endl; // addr = THAT + i output_file << "D = A" << endl; output_file << "@THAT" << endl; output_file << "A = M + D" << endl; output_file << "D = A" << endl; output_file << "@R13" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP-- output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; // *addr = *SP output_file << "@R13" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; } void CodeWriter::staticPush(const int& index, const string& filename) { output_file << "@" << filename << '.' << index << endl; // addr = 16 + filename[0] + i output_file << "D = M" << endl; output_file << "@SP" << endl; // *SP = *addr output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP++ output_file << "M = M + 1" << endl; } void CodeWriter::staticPop(const int& index, const string& filename) { output_file << "@" << filename << '.' << index << endl; // addr = 16 + filename[0] + i output_file << "D = A" << endl; output_file << "@R13" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP-- output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; // *addr = *SP output_file << "@R13" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; } void CodeWriter::tempPush(const int& index) { output_file << "@" << index << endl; // addr = 5 + i output_file << "D = A" << endl; output_file << "@5" << endl; output_file << "A = A + D" << endl; output_file << "D = M" << endl; // *SP = *addr output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP++ output_file << "M = M + 1" << endl; } void CodeWriter::tempPop(const int& index) { output_file << "@" << index << endl; // addr = 5 + i output_file << "D = A" << endl; output_file << "@5" << endl; output_file << "A = A + D" << endl; output_file << "D = A" << endl; output_file << "@R13" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP-- output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; // *addr = *SP output_file << "@R13" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; } void CodeWriter::pointerPush(const int& index) { output_file << "@" << index << endl; // addr = THIS + 0/1 output_file << "D = A" << endl; output_file << "@THIS" << endl; output_file << "A = A + D" << endl; // *SP = addr output_file << "D = M" << endl; output_file << "@SP" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP++ output_file << "M = M + 1" << endl; } void CodeWriter::pointerPop(const int& index) { output_file << "@" << index << endl; // addr = THIS + 0/1 output_file << "D = A" << endl; output_file << "@THIS" << endl; output_file << "D = A + D" << endl; output_file << "@R13" << endl; output_file << "M = D" << endl; output_file << "@SP" << endl; // SP-- output_file << "AM = M - 1" << endl; output_file << "D = M" << endl; // addr = *SP output_file << "@R13" << endl; output_file << "A = M" << endl; output_file << "M = D" << endl; } void CodeWriter::writeInit() { output_file << "@256" << endl; // SP = 256 output_file << "D = A" << endl; output_file << "@SP" << endl; output_file << "M = D" << endl; writeCall("Sys.init", 0); // call Sys.init; } void CodeWriter::close() { if ( output_file.is_open() ) output_file.close(); } #endif // CODEWRITER_CPP_INCLUDED
true
2e4b801343b68e4cf9abce0eb99865c63bb371c8
C++
TheSableCZ/geParticle
/geParticleGL/src/geParticleGL/GPUParticleEmitter.cpp
UTF-8
1,108
2.65625
3
[]
no_license
/** @file GPUParticleEmitter.cpp * @brief Particle emitter accelrated on GPU. * @author Jan Sobol xsobol04 */ #include <geParticleGL/GPUParticleEmitter.h> ge::particle::GPUParticleEmitter::GPUParticleEmitter(std::string shaderSource, int particlesPerSecond) : GPUParticleEmitter(shaderSource, std::make_shared<ConstantRateCounter>(particlesPerSecond)) {} ge::particle::GPUParticleEmitter::GPUParticleEmitter(std::string shaderSource, std::shared_ptr<Counter> counter) : ComputeProgramWrapper(shaderSource), ParticleEmitterBase(counter) { checkUniform("newParticles"); checkUniform("particleCount"); } void ge::particle::GPUParticleEmitter::emitParticles(core::time_unit dt, std::shared_ptr<ge::particle::ParticleContainer> particles) { unsigned int newParticlesCount = getNumOfParticlesToCreate(dt); dispatchEmit(newParticlesCount, particles); } void ge::particle::GPUParticleEmitter::dispatchEmit(unsigned int newParticlesCount, std::shared_ptr<ParticleContainer> particles) { program->set("newParticles", newParticlesCount); program->set("particleCount", particles->size()); dispatch(1); }
true
03f59bf516c8d085f0784a30a6a89dd469a0980d
C++
Eric-GR-N/WeatherInfo_STI
/WeatherInfo.cpp
UTF-8
8,209
3.53125
4
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <algorithm> using namespace std; struct WeatherData { string date = "0"; double temperature = 0; double insideTemp = 0; double insideHum = 0; double humidity = 0; double mold = 0; double insideMold = 0; }; bool compareInsideTemp(WeatherData a, WeatherData b) //Sort functions for struct { if (a.insideTemp < b.insideTemp) { return 1; } else { return 0; } } bool compareInsideHum(WeatherData a, WeatherData b) { if (a.insideHum < b.insideHum) { return 1; } else { return 0; } } bool compareTemp(WeatherData a, WeatherData b) { if (a.temperature < b.temperature) { return 1; } else { return 0; } } bool compareHum(WeatherData a, WeatherData b) { if (a.humidity < b.humidity) { return 1; } else { return 0; } } bool compareMold(WeatherData a, WeatherData b) { if (a.mold < b.mold) { return 1; } else { return 0; } } bool compareInsideMold(WeatherData a, WeatherData b) { if (a.insideMold < b.insideMold) { return 1; } else { return 0; } } void frontEnd(); void readInput(string dateArray [], double tempArray[], double humidityArray [], double insideTempArray [], double insideHumArray []);//Arrays for input void getAutumn(string dateArray[], double tempArray[], string& autumn); void getWinter(string dateArray[], double tempArray[], string& winter); int main() { WeatherData finalArray[130]; //Variables used. string day; string dateArray[130]; double tempArray[130]; double insideTempArray[130]; double insideHumArray[130]; double humidityArray[130]; string winter = "0"; string autumn = "0"; char choice = '0'; char answer = '0'; readInput(dateArray, tempArray, humidityArray, insideTempArray, insideHumArray); // Reads input from the file. getAutumn(dateArray, tempArray, autumn); getWinter(dateArray, tempArray, winter); for (int i = 0; i < 130; i++) //Stores the final values in a struct. { finalArray[i].date = dateArray[i]; finalArray[i].temperature = tempArray[i]; finalArray[i].insideTemp = insideTempArray[i]; finalArray[i].humidity = humidityArray[i]; finalArray[i].insideHum = insideHumArray[i]; if (finalArray[i].insideTemp > 0 && finalArray[i].insideHum > 78) { finalArray[i].insideMold = finalArray[i].insideTemp + finalArray[i].insideHum; } else { finalArray[i].insideMold = 0; } if (finalArray[i].temperature > 0 && finalArray[i].humidity > 78) { finalArray[i].mold = finalArray[i].temperature + finalArray[i].humidity; } else { finalArray[i].mold = 0; } } frontEnd();//Function for design cout << " Hello and welcome to WeatherData, please make your choice below:" << endl; //Interface cout << endl; cout << " OUTSIDE" << endl; cout << endl; cout << " Warmest days [1]" << endl; cout << " Coldest days [2]" << endl; cout << " Days with the highest Humidity [3]" << endl; cout << " Days with the lowest Humidity [4]" << endl; cout << " Autumn [5]" << endl; cout << " Winter [6]" << endl; cout << " Highest risk of mold [7]" << endl; cout << " Middle temperature for a day of choice [8]" << endl; cout << endl; cout << " INSIDE" << endl; cout << endl; cout << " Warmest days inside [a]" << endl; cout << " Coldest days inside [b]" << endl; cout << " Highest humidity inside [c]" << endl; cout << " Lowest humidity inside [d]" << endl; cout << " Highest risk of mold inside [e]" << endl; cout << " Middle temperature for a day of choice inside [f]" << endl; do//This Do While-loop runs the program again if the user chooses 'y'. { cin >> choice; switch (choice)//Switch section to give the user choices for action. { case '1': cout << "The five warmest days were: " << endl; sort(finalArray, finalArray + 130, compareTemp); for (int i = 129; i > (129-5); i--) { cout << "Date: " << finalArray[i].date << " Temperature: " << finalArray[i].temperature << " Degrees Celcius" << endl; } break; case '2': cout << "The five coldest days were: " << endl; sort(finalArray, finalArray + 130, compareTemp); for (int i = 0; i < 5; i++) { cout << "Date: " << finalArray[i].date << " Temperature: " << finalArray[i].temperature << " Degrees Celcius" << endl; } break; case '3': cout << "The five days with the highest Humidity were: " << endl; sort(finalArray, finalArray + 130, compareHum); for (int i = 129; i > 129-5; i--) { cout << "Date: " << finalArray[i].date << " Humidity: " << finalArray[i].humidity << " %" << endl; } break; case '4': cout << "The five days with the lowest Humidity were: " << endl; sort(finalArray, finalArray + 130, compareHum); for (int i = 0; i < 5; i++) { cout << "Date: " << finalArray[i].date << " Humidity: " << finalArray[i].humidity << " %" << endl; } break; case '5': cout << "The first date of Autumn was: " << autumn << endl; break; case '6': cout << "There was no meteorological winter 2016.\nThe longest streak under 0 degrees celcius lasted four days and started: " << winter << endl; break; case '7': sort(finalArray, finalArray + 130, compareMold); cout << "The date : " << finalArray[129].date << " had the highest risk of mold - Humidity: " << finalArray[129].humidity << "% and Temperature: " << finalArray[129].temperature << " Degrees Celcius" << endl; break; case '8': cout << "Please choose a date (xxxx-xx-xx): "; cin >> day; for (int i = 0; i < 130; i++) { if (day == finalArray[i].date) { cout << "Date: " << finalArray[i].date << " - Temperature: " << finalArray[i].temperature << " Degrees Celcius" << endl; break; } } break; case 'a': cout << "The five warmest days inside were: " << endl; sort(finalArray, finalArray + 130, compareInsideTemp); for (int i = 129; i > (129 - 5); i--) { cout << "Date: " << finalArray[i].date << " Temperature: " << finalArray[i].insideTemp << " Degrees Celcius" << endl; } break; case 'b': cout << "The five coldest days inside were: " << endl; sort(finalArray, finalArray + 130, compareInsideTemp); for (int i = 0; i < 5; i++) { cout << "Date: " << finalArray[i].date << " Temperature: " << finalArray[i].insideTemp << " Degrees Celcius" << endl; } break; case 'c': cout << "The five days with the highest Humidity inside were: " << endl; sort(finalArray, finalArray + 130, compareInsideHum); for (int i = 129; i > 129 - 5; i--) { cout << "Date: " << finalArray[i].date << " Humidity: " << finalArray[i].insideHum << " %" << endl; } break; case 'd': cout << "The five days with the lowest Humidity inside were: " << endl; sort(finalArray, finalArray + 130, compareInsideHum); for (int i = 0; i < 5; i++) { cout << "Date: " << finalArray[i].date << " Humidity: " << finalArray[i].insideHum << " %" << endl; } break; case 'e': sort(finalArray, finalArray + 130, compareInsideMold); cout << "The date : " << finalArray[129].date << " had the highest risk of mold - Humidity: " << finalArray[129].insideHum << "% and Temperature: " << finalArray[129].insideTemp << " Degrees Celcius" << endl; break; case 'f': cout << "Please choose a date (xxxx-xx-xx): "; cin >> day; for (int i = 0; i < 130; i++) { if (day == finalArray[i].date) { cout << "Date: " << finalArray[i].date << " - Temperature: " << finalArray[i].insideTemp << " Degrees Celcius" << endl; break; } } break; default: cout << "Invalid input" << endl; break; } cout << "\nWould you like to run the program again?(y/n): "; cin >> answer; } while (answer == 'y' || answer == 'Y'); return 0; }
true
16ace563bbb356c8fff3f7f476cadb3f3c97e7a6
C++
MaxiFly29/ASD2_6
/ASD2_6/RBT.h
UTF-8
8,092
3.40625
3
[]
no_license
#pragma once #include <vector> #define RED false #define BLACK true #define LEFT 0 #define RIGHT 1 template<class T> class RBT_node { public: T data; bool color; //false - red, true - black RBT_node<T>* parent; RBT_node<T>* left; RBT_node<T>* right; RBT_node(T data, bool color) { this->data = data; this->color = color; this->parent = NULL; this->left = NULL; this->right = NULL; } int getDir() { //0 if left, 1 if right return (this->parent->left == this) ? LEFT : RIGHT; } RBT_node<T>* getChild(int dir) { return (dir == LEFT) ? this->left : this->right; } RBT_node<T>* getSibling() { if (this->parent == NULL) { return NULL; } return (this->parent->right == this) ? this->parent->left : this->parent->right; } RBT_node<T>* getUncle() { if ((parent == NULL) || (parent->parent == NULL)) { return NULL; } return this->parent->getSibling(); } bool hasRedChild() { return ((left != NULL) && (left->color == RED) || (right != NULL) && (right->color == RED)); } }; template<class T> class RBT { private: RBT_node<T>* root; int _size; void swapColors(RBT_node<T>* a, RBT_node<T>* b) { bool temp = a->color; a->color = b->color; b->color = temp; } void swapData(RBT_node<T>* a, RBT_node<T>* b) { T temp = a->data; a->data = b->data; b->data = temp; } void balance(RBT_node<T>* node) { RBT_node<T>* P = NULL; //parent RBT_node<T>* GP = NULL; //grand parent while ((node != root) && (node->parent->color == RED) && (node->color == RED)) { P = node->parent; GP = node->parent->parent; RBT_node<T>* U = NULL; U = node->getUncle(); if ((U != NULL) && (U->color == RED)) { P->color = BLACK; U->color = BLACK; GP->color = RED; node = GP; } else { if (node->getDir() != P->getDir()) { if (node->getDir() == RIGHT) { this->rotateLeft(P); } else { this->rotateRight(P); } node = P; P = node->parent; } if (node->getDir() == LEFT) { this->rotateRight(GP); } else { this->rotateLeft(GP); } swapColors(P, GP); node = P; } } root->color = BLACK; } bool _contains(T data, RBT_node<T>* node) { if (node == NULL) { return false; } if (node->data == data) { return true; } else if (node->data < data) { return _contains(data, node->right); } else { return _contains(data, node->left); } } RBT_node<T>* getSuccessor(RBT_node<T>* root) { if ((root->left != NULL) && (root->right != NULL)) { RBT_node<T>* current = root->right; while (current->left != NULL) { current = current->left; } return current; } if ((root->left == NULL) && (root->right == NULL)) { return NULL; } if (root->left == NULL) { return root->right; } else { return root->left; } } void rotate(RBT_node<T>* P, int dir) { RBT_node<T>* GP = P->parent; RBT_node<T>* C = P->getChild(1 - dir); RBT_node<T>* CC = C->getChild(dir); if (dir == LEFT) { P->right = CC; } else { P->left = CC; } if (CC != NULL) { CC->parent = P; } if (dir == LEFT) { C->left = P; } else { C->right = P; } P->parent = C; C->parent = GP; if (GP != NULL) { if (GP->left == P) { GP->left = C; } else { GP->right = C; } } else { this->root = C; } } void rotateLeft(RBT_node<T>* P) { rotate(P, LEFT); } void rotateRight(RBT_node<T>* P) { rotate(P, RIGHT); } void deleteNode(RBT_node<T>* node) { RBT_node<T>* toSwapWith = getSuccessor(node); bool bothBlack = (((toSwapWith == NULL) || (toSwapWith->color == BLACK)) && (node->color == BLACK)); if (toSwapWith == NULL) { if (node == root) { root = NULL; } else { if (bothBlack) { fixDoubleBlack(node); } if (node->getDir() == LEFT) { node->parent->left = NULL; } else { node->parent->right = NULL; } } delete node; return; } if ((node->left == NULL) || (node->right == NULL)) { if (node == root) { root = toSwapWith; } else { if (node->getDir() == LEFT) { node->parent->left = toSwapWith; } else { node->parent->right = toSwapWith; } toSwapWith->parent = node->parent; if (bothBlack) { fixDoubleBlack(toSwapWith); } else { toSwapWith->color = BLACK; } } delete node; return; } node->data = toSwapWith->data; deleteNode(toSwapWith); } void fixDoubleBlack(RBT_node<T>* node) { if (node == root) { return; } RBT_node<T>* sibling = node->getSibling(); if (sibling == NULL) { fixDoubleBlack(node->parent); } else { if (sibling->color == RED) { sibling->color = BLACK; node->parent->color = RED; if (sibling->getDir() == LEFT) { rotateRight(node->parent); } else { rotateLeft(node->parent); } fixDoubleBlack(node); } else { if (sibling->hasRedChild()) { if ((sibling->right != NULL) && (sibling->right->color == RED)) { if (sibling->getDir() == RIGHT) { sibling->right->color = BLACK; sibling->color = node->parent->color; rotateLeft(node->parent); } else { sibling->right->color = node->parent->color; rotateLeft(sibling); rotateRight(node->parent); } } else { if (sibling->getDir() == LEFT) { sibling->left->color = BLACK; sibling->color = node->parent->color; rotateRight(node->parent); } else { sibling->left->color = node->parent->color; rotateRight(sibling); rotateLeft(node->parent); } } node->parent->color = BLACK; } else { sibling->color = RED; if (node->parent->color == RED) { node->parent->color = BLACK; } else { fixDoubleBlack(node->parent); } } } } } void deleteByVal(T data, RBT_node<T>* node) { if (data < node->data) { deleteByVal(data, node->left); } else if (data > node->data) { deleteByVal(data, node->right); } else { deleteNode(node); } } void display(RBT_node<T>* node) { if (node == NULL) { return; } display(node->left); std::cout << node->data << ' '; display(node->right); } void clear(RBT_node<T>* root) { if (root == NULL) { return; } clear(root->left); clear(root->right); delete root; } T sum(RBT_node<T>* node) { if (node == NULL) { return 0; } return sum(node->left) + node->data + sum(node->right); } static void _getSorted(RBT_node<T>* node, std::vector<T>& v) { if (node->left) _getSorted(node->left, v); v.push_back(node->data); if (node->right) _getSorted(node->right, v); } public: RBT() { root = NULL; _size = 0; } RBT(T data) { root = new RBT_node<T>(data, true); _size = 1; } virtual ~RBT() { clear(); } void insert(T data) { if (root == NULL) { root = new RBT_node<T>(data, BLACK); _size = 1; return; } RBT_node<T>* current = root; RBT_node<T>* newNode = new RBT_node<T>(data, RED); _size++; while (true) { if (data == current->data) { delete newNode; _size--; return; } else if (data < current->data) { if (current->left == NULL) { current->left = newNode; newNode->parent = current; break; } else { current = current->left; } } else { if (current->right == NULL) { current->right = newNode; newNode->parent = current; break; } else { current = current->right; } } } if (newNode->parent->color == RED) { this->balance(newNode); } } bool contains(T data) { return _contains(data, root); } void erase(T data) { if (!contains(data)) { return; } else { deleteByVal(data, root); _size--; return; } } int size() { return this->_size; } virtual void display() { display(root); } void clear() { clear(root); root = NULL; _size = 0; } T sum() { return sum(root); } std::vector<T> getSorted() { std::vector<T> res; if (root) _getSorted(root, res); return res; } };
true
1ecb3172d8e85f346ac1e20fc606006ecb0f11e7
C++
niuxu18/logTracker-old
/second/download/httpd/gumtree/httpd_old_hunk_2947.cpp
UTF-8
1,026
2.71875
3
[]
no_license
* @return APR_SUCCESS or error */ apr_status_t ajp_msg_create(apr_pool_t *pool, apr_size_t size, ajp_msg_t **rmsg) { ajp_msg_t *msg = (ajp_msg_t *)apr_pcalloc(pool, sizeof(ajp_msg_t)); if (!msg) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "ajp_msg_create(): can't allocate AJP message memory"); return APR_ENOPOOL; } msg->server_side = 0; msg->buf = (apr_byte_t *)apr_palloc(pool, size); /* XXX: This should never happen * In case if the OS cannont allocate 8K of data * we are in serious trouble * No need to check the alloc return value, cause the * core dump is probably the best solution anyhow. */ if (msg->buf == NULL) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "ajp_msg_create(): can't allocate AJP message memory"); return APR_ENOPOOL; } msg->len = 0; msg->header_len = AJP_HEADER_LEN; msg->max_size = size; *rmsg = msg; return APR_SUCCESS;
true
b63afb645225fe0a1629819b30e09d1320c4dcde
C++
nikolausmayer/cmake-templates
/generic-ros-catkin-cplusplus-messages-cmake-example/src/server.cpp
UTF-8
919
3.015625
3
[ "MIT" ]
permissive
#include <chrono> #include <string> #include <thread> // ROS #include <ros/ros.h> // THIS PACKAGE'S MESSAGES #include <generic_package/GenericMessage.h> typedef generic_package::GenericMessage MSG; int main(int argc, char** argv) { /// Initialize node ros::init(argc, argv, "generic_server"); ROS_INFO("generic_server initialized"); /// Setup message publisher ros::NodeHandle nh; ros::Publisher generic_publisher = nh.advertise<MSG>("generic_topic", 1); while (ros::ok()) { /// Send a message MSG message; message.message_content = "GENERIC HELLO!"; message.header.stamp = ros::Time::now(); generic_publisher.publish(message); /// Spin once to publish ros::spinOnce(); /// Wait one second std::this_thread::sleep_for(std::chrono::seconds(1)); } /// Tidy up ROS_INFO("generic_server exiting..."); ros::shutdown(); /// Bye! return EXIT_SUCCESS; }
true
cbe1583007fea1f4d38c662ee43199834c3866be
C++
ozzi/alabina-game
/sessionmodel.cpp
UTF-8
2,504
2.5625
3
[]
no_license
#include "sessionmodel.h" #include <QDebug> #include <cassert> #include <numeric> #include "crashlogger.h" SessionModel::SessionModel(QObject *parent) : QAbstractListModel(parent), _totalPoints(0), _levelsNumber(0) { QHash<int, QByteArray> role_names; role_names.insert(ResultNameRole, "resultLevelName"); role_names.insert(ResultPointsRole, "resultTotalPoints"); setRoleNames(role_names); } void SessionModel::setLevelsInfo (unsigned aLevelsNumber) { _levelsNumber = aLevelsNumber; } const QString &SessionModel::username() const { return _username; } unsigned SessionModel::totalPoints() const { return _totalPoints; } void SessionModel::setDefaultUserName() { static int number = 0; QString default_user_name_prefix = "User_"; setUsername(default_user_name_prefix + QString::number(++number)); } void SessionModel::setUsername (const QString &username) { if (username != _username) { _username = username; _totalPoints = 0; _results.clear(); _orderedResults.clear(); emit usernameChanged(_username); } } int SessionModel::rowCount (const QModelIndex & aParent) const { return _orderedResults.size(); } QVariant SessionModel::data (const QModelIndex &aIndex, int aRole) const { QVariant ret_value; if (aIndex.isValid()) { switch (static_cast<ResultRoles>(aRole)) { case ResultNameRole: ret_value = _orderedResults.at(aIndex.row()).first; break; case ResultPointsRole: ret_value = _orderedResults.at(aIndex.row()).second; break; default: qDebug() << "SessionModel::data unknown role == " << aRole; assert(FALSE); break; } } return ret_value; } void SessionModel::onLevelCompleted(const QString &aLevelName, unsigned aTotalPoints) { beginResetModel(); _results[aLevelName] = aTotalPoints; QList<unsigned> values = _results.values(); _totalPoints = std::accumulate(values.begin(), values.end(), 0); buildOrderedResults(); endResetModel(); if (_orderedResults.size() == _levelsNumber) { emit allLevelsCompleted(_username, _totalPoints); } } void SessionModel::buildOrderedResults() { _orderedResults.clear(); _orderedResults.reserve(_results.size()); for (auto item = _results.begin(); item != _results.end(); ++item) { _orderedResults.push_back(qMakePair(item.key(), item.value())); } }
true
50d183366a5be601b3d60095cc86e1e2f349ca6a
C++
Tigrolik/git_workspace
/cpp/stroustrup_exercises/data_n_algos/drills/algos_examples.cpp
UTF-8
3,238
3.484375
3
[]
no_license
#include <iostream> #include <vector> #include <list> #include <numeric> #include <algorithm> #include <iterator> using veci = std::vector<int>; using vecd = std::vector<double>; using listd = std::list<double>; struct Record { double unit_price; int units; }; constexpr double price(const double v, const Record &r) { return v + r.unit_price * r.units; } struct Price { double operator()(const double v, const Record &r) { return v + r.unit_price * r.units; } }; class Larger_than { public: Larger_than(int vv): v{vv} { } bool operator()(const int x) { return x > v; } private: int v; }; struct Cmp_by_sqr { bool operator()(const int v1, const int v2) const { return v1 * v1 < v2 * v2; } }; constexpr bool odd(const int x) { return x & 1; } template <class C> void disp_cont(const C& c) { for (const auto &x: c) std::cout << x << ' '; std::cout << '\n'; } void test_find_if() { std::vector<int> v {5, 2, -4, 7, -9, 12}; // using bool function //auto p = std::find_if(std::begin(v), std::end(v), odd); // using lambda auto p = std::find_if(std::begin(v), std::end(v), [] (const int x) { return x & 1; }); if (p != std::end(v)) std::cout << *p << '\n'; const int val {11}; p = std::find_if(std::begin(v), std::end(v), [&val] (const int x) { return x > val; }); if (p != std::end(v)) std::cout << *p << '\n'; // using function object p = std::find_if(std::begin(v), std::end(v), Larger_than(8)); if (p != std::end(v)) std::cout << *p << '\n'; disp_cont(v); std::cout << "sorted by square values:\n"; sort(v.begin(), v.end(), Cmp_by_sqr()); disp_cont(v); } void test_accum() { std::array<double, 4> vd {1.5, -2.5, 4.0, 3.5}; disp_cont(vd); std::cout << "product: " << std::accumulate(begin(vd), end(vd), 1.0, std::multiplies<double>()) << '\n'; std::array<int, 4> vi {1, -2, 4, 3}; disp_cont(vi); std::cout << "product: " << std::accumulate(begin(vi), end(vi), 1.0, std::multiplies<double>()) << '\n'; std::vector<Record> vr; vr.push_back(Record {1.5, 2}); vr.push_back(Record {2.5, 8}); vr.push_back(Record {0.5, 11}); // function std::cout << std::accumulate(begin(vr), end(vr), 0.0, price) << '\n'; // function object std::cout << std::accumulate(begin(vr), end(vr), 0.0, Price()) << '\n'; } void test_inner() { //vecd d_price {81.86, 34.69, 54.45}; veci d_price {81, 34, 54}; listd d_weights {5.8549, 2.4808, 3.8940}; // inner product may take different containers of different types const double d_idx {std::inner_product(begin(d_price), end(d_price), begin(d_weights), 0.0)}; std::cout << d_idx << '\n'; } void test_partial_sum() { std::array<int, 8> a; a.fill(2); disp_cont(a); std::partial_sum(begin(a), end(a), std::ostream_iterator<int>{std::cout, " "}); std::cout << '\n'; std::partial_sum(begin(a), end(a), begin(a), std::multiplies<int>()); disp_cont(a); } int main() { //test_find_if(); //test_accum(); //test_inner(); test_partial_sum(); return 0; }
true
65bbaa405bfe2548e4b243a69bb23ae49573c11a
C++
xieofxie/Cognitive-Services-Voice-Assistant
/samples/clients/cpp-console/include/LinuxAudioPlayer.h
UTF-8
9,119
2.640625
3
[ "MIT", "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "MS-PL", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <alsa/asoundlib.h> #include <condition_variable> #include <list> #include <thread> #include <mutex> #include "AudioPlayer.h" #include "AudioPlayerEntry.h" #include "speechapi_cxx.h" namespace AudioPlayer { /// <summary> /// This object implemented the IAudioPlayer interface and handles the audio Playback for /// Linux using the ALSA library. /// </summary> /// <remarks> /// </remarks> class LinuxAudioPlayer :public IAudioPlayer{ public: /// <summary> /// Default constructor for the LinuxAudioPlayer. Here we will start a thread /// to play audio and open the default audio device in Mono16khz16bit /// </summary> /// <returns>a LinuxAudioPlayer object</returns> /// <example> /// <code> /// IAudioPlayer * audioPlayer = new LinuxAudioPlayer(); /// </code> /// </example> /// <remarks> /// </remarks> LinuxAudioPlayer(); /// <summary> /// Default destructor for the LinuxAudioPlayer. Closes the audio player and cleans up the thread /// </summary> /// <returns>a LinuxAudioPlayer object</returns> /// <example> /// <code> /// </code> /// </example> /// <remarks> /// </remarks> ~LinuxAudioPlayer(); /// <summary> /// Open the default audio device for ALSA and uses the Mono16khz16bit format. /// </summary> /// <returns>A return code with < 0 as an error and any other int as success</returns> /// <example> /// <code> /// IAudioPlayer * audioPlayer = new LinuxAudioPlayer(); /// audioPlayer->Open(); /// </code> /// </example> /// <remarks> /// </remarks> int Open(); /// <summary> /// Open will initialize the audio player with any specific OS dependent /// settings. This implementation takes an ALSA device name and an AudioPlayFormat /// enum to be used in setting up the AudioPlayer. /// </summary> /// <returns>A return code with < 0 as an error and any other int as success</returns> /// <example> /// <code> /// IAudioPlayer *audioPlayer = new LinuxAudioPlayer(); /// audioPlayer->Open("default",IAudioPlayer::AudioPlayerFormat::Mono16khz16bit); /// </code> /// </example> /// <remarks> /// This will force the audio device to be closed and reopened to ensure the specified format. /// </remarks> int Open(const std::string& device, AudioPlayerFormat format); /// <summary> /// ALSA expects audio to be sent in periods defined by frames. This function will compute the /// buffer size based on the channels, bytes per sample, and frames per period. /// </summary> /// <returns>An integer representing the expected buffer size in bytes</returns> /// <example> /// <code> /// IAudioPlayer *audioPlayer = new LinuxAudioPlayer(); /// int bufferSize = audioPlayer->GetBufferSize(); /// </code> /// </example> /// <remarks> /// </remarks> int GetBufferSize(); void SetAlsaMasterVolume(long volume); /// <summary> /// This method is used to actually play the audio. The buffer passed in /// should contain the raw audio bytes. /// </summary> /// <param name="buffer">A point to the buffer containing the audio bytes</param> /// <param name="bufferSize">The size in bytes of the buffer being passed in.</param> /// <returns>A return code with < 0 as an error and any other int as success</returns> /// <example> /// <code> /// IAudioPlayer *audioPlayer = new LinuxAudioPlayer(); /// audioPlayer->Open(); /// int bufferSize = audioPlayer->GetBufferSize(); /// unsigned char * buffer = (unsigned char *)malloc(bufferSize); /// // fill buffer with audio from somewhere /// audioPlayer->Play(buffer, bufferSize); /// </code> /// </example> /// <remarks> /// The method returns the number of frames written to ALSA. /// We assume Open has already been called. /// </remarks> int Play(uint8_t* buffer, size_t bufferSize); /// <summary> /// This method is used to actually play the audio. The PullAudioOutputStream /// passed in should be taken from the GetAudio() call on the activity received event. /// </summary> /// <param name="pStream">A shared pointer to the PullAudioOutputStream</param> /// <returns>A return code with < 0 as an error and any other int as success</returns> /// <example> /// <code> /// IAudioPlayer *audioPlayer = new LinuxAudioPlayer(); /// audioPlayer->Open(); /// ... /// /// //In the Activity received callback /// if (event.HasAudio()){ /// std::shared_ptr<Audio::PullAudioOutputStream> stream = event.GetAudio(); /// audioPLayer->Play(stream); /// } /// </code> /// </example> /// <remarks> /// Here we use the LinuxAudioPlayer as an example. This is preferred to the Byte array if possible /// since this will not cause copies of the buffer to be stored at runtime. /// In our implementation we assume Open is called before playing. /// </remarks> int Play(std::shared_ptr<Microsoft::CognitiveServices::Speech::Audio::PullAudioOutputStream> pStream); /// <summary> /// This function is used to programmatically set the volume of the audio player /// </summary> /// <returns>A return code with < 0 as an error and any other int as success</returns> /// <example> /// <code> /// IAudioPlayer *audioPlayer = new LinuxAudioPlayer(); /// audioPlayer->Open(); /// audioPlayer->SetVolume(50); /// </code> /// </example> /// <remarks> /// Here we use the LinuxAudioPlayer as an example. Though not all players will support this. See the cpp file for details. /// </remarks> int SetVolume(unsigned int percent); /// <summary> /// This function is used to clean up the audio players resources. /// </summary> /// <returns>A return code with < 0 as an error and any other int as success</returns> /// <example> /// <code> /// IAudioPlayer *audioPlayer = new LinuxAudioPlayer(); /// audioPlayer->Open(); /// int bufferSize = audioPlayer->GetBufferSize(); /// unsigned char * buffer = (unsigned char *)malloc(bufferSize); /// // fill buffer with audio from somewhere /// audioPLayer->Play(buffer, bufferSize, IAudioPlayer::AudioPlayerFormat::Mono16khz16bit); /// audioPlayer->Close(); /// </code> /// </example> /// <remarks> /// The ALSA library is drained and closed. /// </remarks> int Close(); private: snd_pcm_t* m_playback_handle; snd_pcm_uframes_t m_frames; snd_pcm_hw_params_t* m_params; unsigned int m_numChannels; unsigned int m_bytesPerSample; unsigned int m_bitsPerSecond; bool m_isPlaying = false; bool m_canceled = false; bool m_opened = false; std::string m_device; std::mutex m_queueMutex; std::mutex m_threadMutex; std::condition_variable m_conditionVariable; std::list<AudioPlayerEntry> m_audioQueue; std::thread m_playerThread; void PlayerThreadMain(); void PlayByteBuffer(std::shared_ptr<AudioPlayerEntry> pEntry); void PlayPullAudioOutputStream(std::shared_ptr<AudioPlayerEntry> pEntry); int WriteToALSA(uint8_t* buffer); }; }
true
eb3d0d8f810eba62dd9097a633f78f73f4279211
C++
Lisprez/asteria
/asteria/rocket/cow_vector.hpp
UTF-8
24,713
2.578125
3
[ "BSD-3-Clause" ]
permissive
// This file is part of Asteria. // Copyleft 2018 - 2020, LH_Mouse. All wrongs reserved. #ifndef ROCKET_COW_VECTOR_HPP_ #define ROCKET_COW_VECTOR_HPP_ #include "compiler.h" #include "assert.hpp" #include "throw.hpp" #include "utilities.hpp" #include "allocator_utilities.hpp" #include "reference_counter.hpp" namespace rocket { template<typename valueT, typename allocT = allocator<valueT>> class cow_vector; #include "details/cow_vector.ipp" /* Differences from `std::vector`: * 1. All functions guarantee only basic exception safety rather than strong exception safety, hence * are more efficient. * 2. `begin()` and `end()` always return `const_iterator`s. `at()`, `front()` and `back()` always * return `const_reference`s. * 3. The copy constructor and copy assignment operator will not throw exceptions. * 4. The specialization for `bool` is not provided. * 5. `emplace()` is not provided. * 6. Comparison operators are not provided. * 7. The value type may be incomplete. It need be neither copy-assignable nor move-assignable, but * must be swappable. **/ template<typename valueT, typename allocT> class cow_vector { static_assert(!is_array<valueT>::value, "invalid element type"); static_assert(is_same<typename allocT::value_type, valueT>::value, "inappropriate allocator type"); public: // types using value_type = valueT; using allocator_type = allocT; using size_type = typename allocator_traits<allocator_type>::size_type; using difference_type = typename allocator_traits<allocator_type>::difference_type; using const_reference = const value_type&; using reference = value_type&; using const_iterator = details_cow_vector::vector_iterator<cow_vector, const value_type>; using iterator = details_cow_vector::vector_iterator<cow_vector, value_type>; using const_reverse_iterator = ::std::reverse_iterator<const_iterator>; using reverse_iterator = ::std::reverse_iterator<iterator>; private: details_cow_vector::storage_handle<allocator_type> m_sth; public: // 26.3.11.2, construct/copy/destroy explicit constexpr cow_vector(const allocator_type& alloc) noexcept : m_sth(alloc) { } cow_vector(const cow_vector& other) noexcept : m_sth(allocator_traits<allocator_type>::select_on_container_copy_construction(other.m_sth.as_allocator())) { this->assign(other); } cow_vector(const cow_vector& other, const allocator_type& alloc) noexcept : m_sth(alloc) { this->assign(other); } cow_vector(cow_vector&& other) noexcept : m_sth(::std::move(other.m_sth.as_allocator())) { this->assign(::std::move(other)); } cow_vector(cow_vector&& other, const allocator_type& alloc) noexcept : m_sth(alloc) { this->assign(::std::move(other)); } constexpr cow_vector(nullopt_t = nullopt_t()) noexcept(is_nothrow_constructible<allocator_type>::value) : cow_vector(allocator_type()) { } explicit cow_vector(size_type n, const allocator_type& alloc = allocator_type()) : cow_vector(alloc) { this->assign(n); } cow_vector(size_type n, const value_type& value, const allocator_type& alloc = allocator_type()) : cow_vector(alloc) { this->assign(n, value); } // N.B. This is a non-standard extension. template<typename firstT, typename... restT, ROCKET_DISABLE_IF(is_same<firstT, allocator_type>::value)> cow_vector(size_type n, const firstT& first, const restT&... rest) : cow_vector() { this->assign(n, first, rest...); } template<typename inputT, ROCKET_ENABLE_IF(is_input_iterator<inputT>::value)> cow_vector(inputT first, inputT last, const allocator_type& alloc = allocator_type()) : cow_vector(alloc) { this->assign(::std::move(first), ::std::move(last)); } cow_vector(initializer_list<value_type> init, const allocator_type& alloc = allocator_type()) : cow_vector(alloc) { this->assign(init); } cow_vector& operator=(nullopt_t) noexcept { this->clear(); return *this; } cow_vector& operator=(const cow_vector& other) noexcept { noadl::propagate_allocator_on_copy(this->m_sth.as_allocator(), other.m_sth.as_allocator()); this->assign(other); return *this; } cow_vector& operator=(cow_vector&& other) noexcept { noadl::propagate_allocator_on_move(this->m_sth.as_allocator(), other.m_sth.as_allocator()); this->assign(::std::move(other)); return *this; } cow_vector& operator=(initializer_list<value_type> init) { this->assign(init); return *this; } private: // Reallocate the storage to `res_arg` elements. // The storage is owned by the current vector exclusively after this function returns normally. value_type* do_reallocate(size_type cnt_one, size_type off_two, size_type cnt_two, size_type res_arg) { ROCKET_ASSERT(cnt_one <= off_two); ROCKET_ASSERT(off_two <= this->m_sth.size()); ROCKET_ASSERT(cnt_two <= this->m_sth.size() - off_two); auto ptr = this->m_sth.reallocate(cnt_one, off_two, cnt_two, res_arg); ROCKET_ASSERT(!ptr || this->m_sth.unique()); return ptr; } // Clear contents. Deallocate the storage if it is shared at all. void do_clear() noexcept { if(!this->unique()) this->m_sth.deallocate(); else this->m_sth.pop_back_n_unchecked(this->m_sth.size()); } // Reallocate more storage as needed, without shrinking. void do_reserve_more(size_type cap_add) { auto cnt = this->size(); auto cap = this->m_sth.check_size_add(cnt, cap_add); if(!this->unique() || ROCKET_UNEXPECT(this->capacity() < cap)) { #ifndef ROCKET_DEBUG // Reserve more space for non-debug builds. cap |= cnt / 2 + 7; #endif this->do_reallocate(0, 0, cnt, cap | 1); } ROCKET_ASSERT(this->capacity() >= cap); } [[noreturn]] ROCKET_NOINLINE void do_throw_subscript_out_of_range(size_type pos) const { noadl::sprintf_and_throw<out_of_range>("cow_vector: subscript out of range (`%llu` > `%llu`)", static_cast<unsigned long long>(pos), static_cast<unsigned long long>(this->size())); } // This function works the same way as `std::string::substr()`. // Ensure `tpos` is in `[0, size()]` and return `min(tn, size() - tpos)`. size_type do_clamp_subvec(size_type tpos, size_type tn) const { auto tcnt = this->size(); if(tpos > tcnt) this->do_throw_subscript_out_of_range(tpos); return noadl::min(tcnt - tpos, tn); } template<typename... paramsT> value_type* do_insert_no_bound_check(size_type tpos, paramsT&&... params) { auto cnt_old = this->size(); ROCKET_ASSERT(tpos <= cnt_old); details_cow_vector::tagged_append(this, ::std::forward<paramsT>(params)...); auto cnt_add = this->size() - cnt_old; this->do_reserve_more(0); auto ptr = this->m_sth.mut_data_unchecked(); noadl::rotate(ptr, tpos, cnt_old, cnt_old + cnt_add); return ptr + tpos; } value_type* do_erase_no_bound_check(size_type tpos, size_type tn) { auto cnt_old = this->size(); ROCKET_ASSERT(tpos <= cnt_old); ROCKET_ASSERT(tn <= cnt_old - tpos); if(!this->unique()) { auto ptr = this->do_reallocate(tpos, tpos + tn, cnt_old - (tpos + tn), cnt_old); return ptr + tpos; } auto ptr = this->m_sth.mut_data_unchecked(); noadl::rotate(ptr, tpos, tpos + tn, cnt_old); this->m_sth.pop_back_n_unchecked(tn); return ptr + tpos; } public: // iterators const_iterator begin() const noexcept { return const_iterator(this->m_sth, this->data()); } const_iterator end() const noexcept { return const_iterator(this->m_sth, this->data() + this->size()); } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(this->end()); } const_reverse_iterator rend() const noexcept { return const_reverse_iterator(this->begin()); } const_iterator cbegin() const noexcept { return this->begin(); } const_iterator cend() const noexcept { return this->end(); } const_reverse_iterator crbegin() const noexcept { return this->rbegin(); } const_reverse_iterator crend() const noexcept { return this->rend(); } // N.B. This function may throw `std::bad_alloc`. // N.B. This is a non-standard extension. iterator mut_begin() { return iterator(this->m_sth, this->mut_data()); } // N.B. This function may throw `std::bad_alloc`. // N.B. This is a non-standard extension. iterator mut_end() { return iterator(this->m_sth, this->mut_data() + this->size()); } // N.B. This function may throw `std::bad_alloc`. // N.B. This is a non-standard extension. reverse_iterator mut_rbegin() { return reverse_iterator(this->mut_end()); } // N.B. This function may throw `std::bad_alloc`. // N.B. This is a non-standard extension. reverse_iterator mut_rend() { return reverse_iterator(this->mut_begin()); } // 26.3.11.3, capacity constexpr bool empty() const noexcept { return this->m_sth.empty(); } constexpr size_type size() const noexcept { return this->m_sth.size(); } // N.B. This is a non-standard extension. constexpr difference_type ssize() const noexcept { return static_cast<difference_type>(this->size()); } constexpr size_type max_size() const noexcept { return this->m_sth.max_size(); } // N.B. The return type and the parameter pack are non-standard extensions. template<typename... paramsT> cow_vector& resize(size_type n, const paramsT&... params) { auto cnt_old = this->size(); if(cnt_old < n) this->append(n - cnt_old, params...); else if(cnt_old > n) this->pop_back(cnt_old - n); ROCKET_ASSERT(this->size() == n); return *this; } constexpr size_type capacity() const noexcept { return this->m_sth.capacity(); } // N.B. The return type is a non-standard extension. cow_vector& reserve(size_type res_arg) { auto cnt = this->size(); auto cap_new = this->m_sth.round_up_capacity(noadl::max(cnt, res_arg)); // If the storage is shared with other vectors, force rellocation to prevent copy-on-write // upon modification. if(this->unique() && (this->capacity() >= cap_new)) return *this; this->do_reallocate(0, 0, cnt, cap_new); ROCKET_ASSERT(this->capacity() >= res_arg); return *this; } // N.B. The return type is a non-standard extension. cow_vector& shrink_to_fit() { auto cnt = this->size(); auto cap_min = this->m_sth.round_up_capacity(cnt); // Don't increase memory usage. if(!this->unique() || (this->capacity() <= cap_min)) return *this; this->do_reallocate(0, 0, cnt, cnt); ROCKET_ASSERT(this->capacity() <= cap_min); return *this; } // N.B. The return type is a non-standard extension. cow_vector& clear() noexcept { if(this->empty()) return *this; this->do_clear(); return *this; } // N.B. This is a non-standard extension. bool unique() const noexcept { return this->m_sth.unique(); } // N.B. This is a non-standard extension. long use_count() const noexcept { return this->m_sth.use_count(); } // element access const_reference at(size_type pos) const { auto cnt = this->size(); if(pos >= cnt) this->do_throw_subscript_out_of_range(pos); return this->data()[pos]; } const_reference operator[](size_type pos) const noexcept { auto cnt = this->size(); ROCKET_ASSERT(pos < cnt); return this->data()[pos]; } const_reference front() const noexcept { auto cnt = this->size(); ROCKET_ASSERT(cnt > 0); return this->data()[0]; } const_reference back() const noexcept { auto cnt = this->size(); ROCKET_ASSERT(cnt > 0); return this->data()[cnt - 1]; } // N.B. This is a non-standard extension. const value_type* get_ptr(size_type pos) const noexcept { auto cnt = this->size(); if(pos >= cnt) return nullptr; return this->data() + pos; } // There is no `at()` overload that returns a non-const reference. // This is the consequent overload which does that. // N.B. This is a non-standard extension. reference mut(size_type pos) { auto cnt = this->size(); if(pos >= cnt) this->do_throw_subscript_out_of_range(pos); return this->mut_data()[pos]; } // N.B. This is a non-standard extension. reference mut_front() { auto cnt = this->size(); ROCKET_ASSERT(cnt > 0); return this->mut_data()[0]; } // N.B. This is a non-standard extension. reference mut_back() { auto cnt = this->size(); ROCKET_ASSERT(cnt > 0); return this->mut_data()[cnt - 1]; } // N.B. This is a non-standard extension. value_type* mut_ptr(size_type pos) noexcept { auto cnt = this->size(); if(pos >= cnt) return nullptr; return this->mut_data() + pos; } // N.B. This is a non-standard extension. template<typename... paramsT> cow_vector& append(size_type n, const paramsT&... params) { if(n == 0) return *this; this->do_reserve_more(n); noadl::ranged_do_while(size_type(0), n, [&](size_type) { this->m_sth.emplace_back_unchecked(params...); }); return *this; } // N.B. This is a non-standard extension. cow_vector& append(initializer_list<value_type> init) { return this->append(init.begin(), init.end()); } // N.B. This is a non-standard extension. template<typename inputT, ROCKET_ENABLE_IF(is_input_iterator<inputT>::value)> cow_vector& append(inputT first, inputT last) { if(first == last) return *this; auto dist = noadl::estimate_distance(first, last); if(dist == 0) { noadl::ranged_do_while(::std::move(first), ::std::move(last), [&](const inputT& it) { this->emplace_back(*it); }); return *this; } this->do_reserve_more(dist); noadl::ranged_do_while(::std::move(first), ::std::move(last), [&](const inputT& it) { this->m_sth.emplace_back_unchecked(*it); }); return *this; } // 26.3.11.5, modifiers template<typename... paramsT> reference emplace_back(paramsT&&... params) { this->do_reserve_more(1); auto ptr = this->m_sth.emplace_back_unchecked(::std::forward<paramsT>(params)...); return *ptr; } // N.B. The return type is a non-standard extension. reference push_back(const value_type& value) { auto cnt_old = this->size(); // Check for overlapped elements before `do_reserve_more()`. auto srpos = static_cast<uintptr_t>(::std::addressof(value) - this->data()); this->do_reserve_more(1); if(srpos < cnt_old) { auto ptr = this->m_sth.emplace_back_unchecked(this->data()[srpos]); return *ptr; } auto ptr = this->m_sth.emplace_back_unchecked(value); return *ptr; } // N.B. The return type is a non-standard extension. reference push_back(value_type&& value) { this->do_reserve_more(1); auto ptr = this->m_sth.emplace_back_unchecked(::std::move(value)); return *ptr; } // N.B. This is a non-standard extension. cow_vector& insert(size_type tpos, const value_type& value) { this->do_clamp_subvec(tpos, 0); // just check this->do_insert_no_bound_check(tpos, details_cow_vector::push_back, value); return *this; } // N.B. This is a non-standard extension. cow_vector& insert(size_type tpos, value_type&& value) { this->do_clamp_subvec(tpos, 0); // just check this->do_insert_no_bound_check(tpos, details_cow_vector::push_back, ::std::move(value)); return *this; } // N.B. This is a non-standard extension. template<typename... paramsT> cow_vector& insert(size_type tpos, size_type n, const paramsT&... params) { this->do_clamp_subvec(tpos, 0); // just check this->do_insert_no_bound_check(tpos, details_cow_vector::append, n, params...); return *this; } // N.B. This is a non-standard extension. cow_vector& insert(size_type tpos, initializer_list<value_type> init) { this->do_clamp_subvec(tpos, 0); // just check this->do_insert_no_bound_check(tpos, details_cow_vector::append, init); return *this; } // N.B. This is a non-standard extension. template<typename inputT, ROCKET_ENABLE_IF(is_input_iterator<inputT>::value)> cow_vector& insert(size_type tpos, inputT first, inputT last) { this->do_clamp_subvec(tpos, 0); // just check this->do_insert_no_bound_check(tpos, details_cow_vector::append, ::std::move(first), ::std::move(last)); return *this; } iterator insert(const_iterator tins, const value_type& value) { auto tpos = static_cast<size_type>(tins.tell_owned_by(this->m_sth) - this->data()); auto ptr = this->do_insert_no_bound_check(tpos, details_cow_vector::push_back, value); return iterator(this->m_sth, ptr); } iterator insert(const_iterator tins, value_type&& value) { auto tpos = static_cast<size_type>(tins.tell_owned_by(this->m_sth) - this->data()); auto ptr = this->do_insert_no_bound_check(tpos, details_cow_vector::push_back, ::std::move(value)); return iterator(this->m_sth, ptr); } // N.B. The parameter pack is a non-standard extension. template<typename... paramsT> iterator insert(const_iterator tins, size_type n, const paramsT&... params) { auto tpos = static_cast<size_type>(tins.tell_owned_by(this->m_sth) - this->data()); auto ptr = this->do_insert_no_bound_check(tpos, details_cow_vector::append, n, params...); return iterator(this->m_sth, ptr); } iterator insert(const_iterator tins, initializer_list<value_type> init) { auto tpos = static_cast<size_type>(tins.tell_owned_by(this->m_sth) - this->data()); auto ptr = this->do_insert_no_bound_check(tpos, details_cow_vector::append, init); return iterator(this->m_sth, ptr); } template<typename inputT, ROCKET_ENABLE_IF(is_input_iterator<inputT>::value)> iterator insert(const_iterator tins, inputT first, inputT last) { auto tpos = static_cast<size_type>(tins.tell_owned_by(this->m_sth) - this->data()); auto ptr = this->do_insert_no_bound_check(tpos, details_cow_vector::append, ::std::move(first), ::std::move(last)); return iterator(this->m_sth, ptr); } // N.B. This function may throw `std::bad_alloc`. // N.B. This is a non-standard extension. cow_vector& erase(size_type tpos, size_type tn = size_type(-1)) { this->do_erase_no_bound_check(tpos, this->do_clamp_subvec(tpos, tn)); return *this; } // N.B. This function may throw `std::bad_alloc`. iterator erase(const_iterator tfirst, const_iterator tlast) { auto tpos = static_cast<size_type>(tfirst.tell_owned_by(this->m_sth) - this->data()); auto tn = static_cast<size_type>(tlast.tell_owned_by(this->m_sth) - tfirst.tell()); auto ptr = this->do_erase_no_bound_check(tpos, tn); return iterator(this->m_sth, ptr); } // N.B. This function may throw `std::bad_alloc`. iterator erase(const_iterator tfirst) { auto tpos = static_cast<size_type>(tfirst.tell_owned_by(this->m_sth) - this->data()); auto ptr = this->do_erase_no_bound_check(tpos, 1); return iterator(this->m_sth, ptr); } // N.B. This function may throw `std::bad_alloc`. // N.B. The return type and parameter are non-standard extensions. cow_vector& pop_back(size_type n = 1) { auto cnt_old = this->size(); ROCKET_ASSERT(n <= cnt_old); if(n == 0) return *this; if(!this->unique()) { this->do_reallocate(0, 0, cnt_old - n, cnt_old); return *this; } this->m_sth.pop_back_n_unchecked(n); return *this; } // N.B. This is a non-standard extension. cow_vector subvec(size_type tpos, size_type tn = size_type(-1)) const { if((tpos == 0) && (tn >= this->size())) // Utilize reference counting. return cow_vector(*this, this->m_sth.as_allocator()); else return cow_vector(this->data() + tpos, this->data() + tpos + this->do_clamp_subvec(tpos, tn), this->m_sth.as_allocator()); } // N.B. The return type is a non-standard extension. cow_vector& assign(const cow_vector& other) noexcept { this->m_sth.share_with(other.m_sth); return *this; } // N.B. The return type is a non-standard extension. cow_vector& assign(cow_vector&& other) noexcept { this->m_sth.share_with(::std::move(other.m_sth)); return *this; } // N.B. The parameter pack is a non-standard extension. // N.B. The return type is a non-standard extension. template<typename... paramsT> cow_vector& assign(size_type n, const paramsT&... params) { this->clear(); this->append(n, params...); return *this; } // N.B. The return type is a non-standard extension. cow_vector& assign(initializer_list<value_type> init) { this->clear(); this->append(init); return *this; } // N.B. The return type is a non-standard extension. template<typename inputT, ROCKET_ENABLE_IF(is_input_iterator<inputT>::value)> cow_vector& assign(inputT first, inputT last) { this->clear(); this->append(::std::move(first), ::std::move(last)); return *this; } cow_vector& swap(cow_vector& other) noexcept { noadl::propagate_allocator_on_swap(this->m_sth.as_allocator(), other.m_sth.as_allocator()); this->m_sth.exchange_with(other.m_sth); return *this; } // 26.3.11.4, data access const value_type* data() const noexcept { return this->m_sth.data(); } // Get a pointer to mutable data. This function may throw `std::bad_alloc`. // N.B. This is a non-standard extension. value_type* mut_data() { if(ROCKET_UNEXPECT(!this->empty() && !this->unique())) return this->do_reallocate(0, 0, this->size(), this->size() | 1); else return this->m_sth.mut_data_unchecked(); } // N.B. The return type differs from `std::vector`. constexpr const allocator_type& get_allocator() const noexcept { return this->m_sth.as_allocator(); } allocator_type& get_allocator() noexcept { return this->m_sth.as_allocator(); } }; template<typename valueT, typename allocT> inline void swap(cow_vector<valueT, allocT>& lhs, cow_vector<valueT, allocT>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } } // namespace rocket #endif
true
1e1f79d1dab6411af71385429e498aedb5c97bc5
C++
DokyeongLee-3/MetalSlug
/MetalSlug/Include/Object/Character.cpp
UTF-8
727
2.609375
3
[]
no_license
#include "Character.h" CCharacter::CCharacter() : m_CharacterInfo{} { } CCharacter::CCharacter(const CCharacter& obj) : CGameObject(obj) { m_CharacterInfo = obj.m_CharacterInfo; } CCharacter::~CCharacter() { } void CCharacter::Start() { CGameObject::Start(); } bool CCharacter::Init() { if (!CGameObject::Init()) return false; return true; } void CCharacter::Update(float DeltaTime) { CGameObject::Update(DeltaTime); } void CCharacter::PostUpdate(float DeltaTime) { CGameObject::PostUpdate(DeltaTime); } void CCharacter::Collision(float DeltaTime) { CGameObject::Collision(DeltaTime); } void CCharacter::Render(HDC hDC) { CGameObject::Render(hDC); } CCharacter* CCharacter::Clone() { return nullptr; }
true
adfb8f2c83f1e7c46ec25fee57c5317e9b2d4a03
C++
cedreg/dipRepo
/ROT/ROT/rottestclass.cpp
UTF-8
1,284
2.953125
3
[]
no_license
#include "rottestclass.h" #include <QDebug> #include <iostream> int rotTestClass::getActSize() const { return actSize; } rotTestClass::rotTestClass(int maxSize) { actSize = 0; size = maxSize; a = new int [size]; } rotTestClass::rotTestClass(const rotTestClass &other) { if(this != &other) { if(other.size != size) { delete a; size = other.size; a = new int [size]; } actSize = other.actSize; for(int i = 0; i < actSize; i++) { a[i] = other.a[i]; } } } rotTestClass& rotTestClass::operator=(const rotTestClass &other) { if(this != &other) { if(other.size != size) { delete a; size = other.size; a = new int [size]; } actSize = other.actSize; for(int i = 0; i < actSize; i++) { a[i] = other.a[i]; } } return *this; } rotTestClass::~rotTestClass() { } bool rotTestClass::push_back(int val) { if (actSize < size) { a[actSize++] = val; return true; } else { return false; } } void rotTestClass::COUT() { for (int i = 0; i < actSize; i++) { qDebug() << a[i]; } }
true
0e088d4454ded10b3ff0a91e53cddc6b873ef258
C++
Jamil132/DSA-COMPLETE-SERIES
/Array/Union.cpp
UTF-8
1,105
3.34375
3
[]
no_license
#include <iostream> #include <bits/stdc++.h> #define N 100 using namespace std; // Merging is Done when Array is Sorted // Time Complexity is Theta(n+m) // Overall O(n) void Union_Sort(int A[],int B[],int n,int m) { int C[N]; int i=0,j=0,k=0; while(i<n && j<m) { if(A[i]<B[j]) C[k++] = A[i++]; else if(A[j]<B[i]) C[k++] = B[j++]; else { C[k++] = A[i++]; ++j; } } for(;i<n;i++) { C[k++] = A[i]; } for(;j<m;j++) { C[k++] = B[j]; } // Displaying Elements for(int i=0;i<k;i++) { cout<<C[i]<<" "; } } int main() { int n; cout<<"Enter the Size of the 1st Array: "; cin>>n; int A[n]; cout<<"Enter Elements: "; for(int i=0;i<n;i++) { cin>>A[i]; } int m; cout<<"Enter the Size of the 2nd Array: "; cin>>m; int B[m]; cout<<"Enter Elements: "; for(int i=0;i<m;i++) { cin>>B[i]; } Union_Sort(A,B,n,m); return 0; }
true
047a16b2ab16a73077b7afdb393078d5667981cd
C++
dongb94/algorithm
/Data Structure/Stack.h
UTF-8
731
3.578125
4
[]
no_license
#include <iostream> template<typename T> class Stack { private: T *start; int nOfE; int size; public: Stack() { start = new T[10]; nOfE = 0; size = 10; } Stack(int N) { start = new T[N]; nOfE = 0; size = N; } void push(T n) { if (nOfE == size) { T *sizeIncreaseStack = new T[size * 2]; sizeIncreaseStack = start; for (int i = 0; i < size; i++) { sizeIncreaseStack[i] = start[i]; } start = sizeIncreaseStack; size *= 2; } start[nOfE] = n; nOfE++; } T pop() { if (nOfE == 0) return NULL; nOfE--; return start[nOfE]; } T peak() { if (nOfE == 0) return NULL; return start[nOfE - 1]; } int Size() { return nOfE; } bool isEmpty() { return nOfE == 0; } };
true
9c901c17b3cf79bef91a784294536b2aae3c5b53
C++
zarif98sjs/Competitive-Programming
/CodeForces/Virtual Contest/Round 641/D.cpp
UTF-8
3,048
2.546875
3
[]
no_license
/** If there is any subset of size 3 , which has at least 2 elements >=k we can make it . The idea is intuitive . **/ /** Which of the favors of your Lord will you deny ? **/ #include<bits/stdc++.h> using namespace std; #define LL long long #define PII pair<int,int> #define PLL pair<LL,LL> #define MP make_pair #define F first #define S second #define INF INT_MAX #define ALL(x) (x).begin(), (x).end() #define DBG(x) cerr << __LINE__ << " says: " << #x << " = " << (x) << endl #define READ freopen("alu.txt", "r", stdin) #define WRITE freopen("vorta.txt", "w", stdout) #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template<class TIn>using indexed_set = tree<TIn, null_type, less<TIn>,rb_tree_tag, tree_order_statistics_node_update>; /** PBDS ------------------------------------------------- 1) insert(value) 2) erase(value) 3) order_of_key(value) // 0 based indexing 4) *find_by_order(position) // 0 based indexing **/ template<class T1, class T2> ostream &operator <<(ostream &os, pair<T1,T2>&p); template <class T> ostream &operator <<(ostream &os, vector<T>&v); template <class T> ostream &operator <<(ostream &os, set<T>&v); inline void optimizeIO() { ios_base::sync_with_stdio(false); cin.tie(NULL); } const int nmax = 2e5+7; const LL LINF = 1e17; template <class T> string to_str(T x) { stringstream ss; ss<<x; return ss.str(); } //bool cmp(const PII &A,const PII &B) //{ // //} int ara[nmax]; int main() { optimizeIO(); int tc; cin>>tc; while(tc--) { int n,k; cin>>n>>k; bool ok = false; for(int i=1; i<=n; i++) { cin>>ara[i]; if(ara[i]==k) ok = true; } if(n==1) { if(ok) cout<<"YES"<<endl; else cout<<"NO"<<endl; continue; } if(n==2) { if(ara[1]>=k && ara[2]>=k && ok) cout<<"YES"<<endl; else cout<<"NO"<<endl; continue; } int sz = 3; int win_cnt = 0; bool ok2 = false; for(int i=1; i<=n; i++) { if(ara[i]>=k) win_cnt++; if(i>=sz) { if(win_cnt>=2) ok2 = true; if(ara[i-sz+1]>=k) win_cnt--; } } if(ok && ok2) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; } /** **/ template<class T1, class T2> ostream &operator <<(ostream &os, pair<T1,T2>&p) { os<<"{"<<p.first<<", "<<p.second<<"} "; return os; } template <class T> ostream &operator <<(ostream &os, vector<T>&v) { os<<"[ "; for(int i=0; i<v.size(); i++) { os<<v[i]<<" " ; } os<<" ]"; return os; } template <class T> ostream &operator <<(ostream &os, set<T>&v) { os<<"[ "; for(T i:v) { os<<i<<" "; } os<<" ]"; return os; }
true
e98255f39b81657a6b3a37e0fb94423a282ad7cd
C++
guzhaolun/LeetCode
/LeetCode/MyCode/67. add_binary.h
UTF-8
626
3.0625
3
[]
no_license
#include <string> #include <algorithm> using namespace std; class Solution67{ public: string addBinary(string a, string b) { int decade = 0; int sum = 0; int ones = 0; int as = a.size(), bs = b.size(); int size = max(as, bs); if (as < bs) { for (int i = 0; i < bs - as; i++) a.insert(a.begin(), '0'); } else { for (int i = 0; i < (as - bs); i++) b.insert(b.begin(), '0'); } for (int i = size - 1; i >= 0; i--) { int sum = a[i] - '0' + b[i] - '0' + decade; b[i] = sum % 2 + '0'; decade = sum / 2; } if (decade != 0) b.insert(b.begin(), decade + '0'); return b; } };
true
bec23573be36c2b1ebf3e388e3fcb88b988dff06
C++
ChaseCarthen/simphys
/quiz5/src/test/tests.cpp
UTF-8
3,028
3.046875
3
[]
no_license
#include "gtest/gtest.h" #include "mat22.h" #include "mat33.h" #include "mat44.h" #include <iostream> using namespace simphys; class matTest2 : public ::testing::Test { protected: mat22 a2; mat22 b2; vec2 v2; matTest2() : a2{1,2,3,4} , b2{1,2,3,4}, v2{1,1} { } }; class matTest3 : public ::testing::Test { protected: mat33 a3; mat33 b3; vec3 v3; matTest3() : a3{1,2,3,4,5,6,7,8,9} , b3{1,2,3,4,5,6,7,8,9}, v3{1,1,1} { } }; class matTest4 : public ::testing::Test { protected: mat44 a4; mat44 b4; vec4 v4; matTest4() : a4{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16} , b4{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}, v4{1,1,1,1} { } }; TEST_F(matTest2,elementtest) { a2(0,0)=1; EXPECT_EQ(1,a2(0,0)); EXPECT_EQ(2,a2(0,1)); EXPECT_EQ(3,a2(1,0)); EXPECT_EQ(4,a2(1,1)); } TEST_F(matTest2,transposetest) { a2.transpose(); EXPECT_EQ(1,a2(0,0)); EXPECT_EQ(3,a2(0,1)); EXPECT_EQ(2,a2(1,0)); EXPECT_EQ(4,a2(1,1)); } TEST_F(matTest2,vectortest) { auto v = a2 * v2; EXPECT_EQ(3,v.getX()); EXPECT_EQ(7,v.getY()); } TEST_F (matTest2, determinanttest) { EXPECT_EQ ( 1*4 - 2*3, a2.determinant()); } TEST_F (matTest3, determinanttest) { EXPECT_EQ(1*(5*9 - 6*8)-2*(4*9-6*7)+3*(4*8-5*7),a3.determinant()); } TEST_F(matTest3,elementtest) { EXPECT_EQ(1,a3(0,0)); EXPECT_EQ(2,a3(0,1)); EXPECT_EQ(3,a3(0,2)); EXPECT_EQ(4,a3(1,0)); EXPECT_EQ(5,a3(1,1)); EXPECT_EQ(6,a3(1,2)); EXPECT_EQ(7,a3(2,0)); EXPECT_EQ(8,a3(2,1)); EXPECT_EQ(9,a3(2,2)); } TEST_F(matTest3,transposetest) { a3.transpose(); EXPECT_EQ(1,a3(0,0)); EXPECT_EQ(4,a3(0,1)); EXPECT_EQ(7,a3(0,2)); EXPECT_EQ(2,a3(1,0)); EXPECT_EQ(5,a3(1,1)); EXPECT_EQ(8,a3(1,2)); EXPECT_EQ(3,a3(2,0)); EXPECT_EQ(6,a3(2,1)); EXPECT_EQ(9,a3(2,2)); } TEST_F(matTest3,vectortest) { auto v = a3 * v3; EXPECT_EQ(1*1+2*1+3*1,v.getX()); EXPECT_EQ(4*1+5*1+6*1,v.getY()); EXPECT_EQ(7*1+8*1+9*1,v.getZ()); } TEST_F(matTest4,elementtest) { EXPECT_EQ(1,a4(0,0)); EXPECT_EQ(2,a4(0,1)); EXPECT_EQ(3,a4(0,2)); EXPECT_EQ(4,a4(0,3)); EXPECT_EQ(5,a4(1,0)); EXPECT_EQ(6,a4(1,1)); EXPECT_EQ(7,a4(1,2)); EXPECT_EQ(8,a4(1,3)); EXPECT_EQ(9,a4(2,0)); EXPECT_EQ(10,a4(2,1)); EXPECT_EQ(11,a4(2,2)); EXPECT_EQ(12,a4(2,3)); EXPECT_EQ(13,a4(3,0)); EXPECT_EQ(14,a4(3,1)); EXPECT_EQ(15,a4(3,2)); EXPECT_EQ(16,a4(3,3)); } TEST_F(matTest4,transposetest) { a4.transpose(); EXPECT_EQ(1,a4(0,0)); EXPECT_EQ(5,a4(0,1)); EXPECT_EQ(9,a4(0,2)); EXPECT_EQ(13,a4(0,3)); EXPECT_EQ(2,a4(1,0)); EXPECT_EQ(6,a4(1,1)); EXPECT_EQ(10,a4(1,2)); EXPECT_EQ(14,a4(1,3)); EXPECT_EQ(3,a4(2,0)); EXPECT_EQ(7,a4(2,1)); EXPECT_EQ(11,a4(2,2)); EXPECT_EQ(15,a4(2,3)); EXPECT_EQ(4,a4(3,0)); EXPECT_EQ(8,a4(3,1)); EXPECT_EQ(12,a4(3,2)); EXPECT_EQ(16,a4(3,3)); } TEST_F(matTest4,vectortest) { auto v = a4 * v4; EXPECT_EQ(1*1+2*1+3*1+4*1,v.getX()); EXPECT_EQ(5*1+6*1+7*1+8*1,v.getY()); EXPECT_EQ(9*1+10*1+11*1+12*1,v.getZ()); EXPECT_EQ(13*1+14*1+15*1+16*1,v.getW()); }
true
6b2aa60fbdfc3502881676e98f514544c6f3262a
C++
Bekaryss/LeetCode-Old
/Bit Monipulation/Convert a Number to Hexadecimal 405/Convert a Number to Hexadecimal 405/Convert a Number to Hexadecimal 405.cpp
UTF-8
2,091
3.078125
3
[]
no_license
// Convert a Number to Hexadecimal 405.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; string toHex(int num) { if (num == 0) { return "0"; } vector<string> hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; string s = ""; long n; n = num < 0 ? pow(2, 32) + num : num; while (n != 0) { s = hex[n % 16] + s; n /= 16; } return s; } int main() { std::cout << "1a == " << toHex(26) << endl; std::cout << "ffffffff == " << toHex(-1) << endl; } // Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки" // Отладка программы: F5 или меню "Отладка" > "Запустить отладку" // Советы по началу работы // 1. В окне обозревателя решений можно добавлять файлы и управлять ими. // 2. В окне Team Explorer можно подключиться к системе управления версиями. // 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения. // 4. В окне "Список ошибок" можно просматривать ошибки. // 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода. // 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
true
110cb7cff7081792a14165d7a95aed1c2d3241b9
C++
pytorch/pytorch
/c10/cuda/CUDADeviceAssertionHost.h
UTF-8
6,394
2.875
3
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-secret-labs-2011", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
#pragma once #include <c10/cuda/CUDAMacros.h> #include <memory> #include <mutex> #include <string> #include <vector> #ifdef USE_CUDA #define TORCH_USE_CUDA_DSA #endif /// Number of assertion failure messages we can store. If this is too small /// threads will fail silently. constexpr int C10_CUDA_DSA_ASSERTION_COUNT = 10; constexpr int C10_CUDA_DSA_MAX_STR_LEN = 512; namespace c10 { namespace cuda { /// Holds information about any device-side assertions that fail. /// Held in managed memory and access by both the CPU and the GPU. struct DeviceAssertionData { /// Stringification of the assertion char assertion_msg[C10_CUDA_DSA_MAX_STR_LEN]; /// File the assertion was in char filename[C10_CUDA_DSA_MAX_STR_LEN]; /// Name of the function the assertion was in char function_name[C10_CUDA_DSA_MAX_STR_LEN]; /// Line number the assertion was at int line_number; /// Number uniquely identifying the kernel launch that triggered the assertion uint32_t caller; /// block_id of the thread that failed the assertion int32_t block_id[3]; /// third_id of the thread that failed the assertion int32_t thread_id[3]; }; /// Used to hold assertions generated by the device /// Held in managed memory and access by both the CPU and the GPU. struct DeviceAssertionsData { /// Total number of assertions found; a subset of thse will be recorded /// in `assertions` int32_t assertion_count; /// An array of assertions that will be written to in a race-free manner DeviceAssertionData assertions[C10_CUDA_DSA_ASSERTION_COUNT]; }; /// Use to hold info about kernel launches so that we can run kernels /// asynchronously and still associate launches with device-side /// assertion failures struct CUDAKernelLaunchInfo { /// Filename of the code where the kernel was launched from const char* launch_filename; /// Function from which the kernel was launched const char* launch_function; /// Line number of where the code was launched from uint32_t launch_linenum; /// Backtrace of where the kernel was launched from, only populated if /// CUDAKernelLaunchRegistry::gather_launch_stacktrace is True std::string launch_stacktrace; /// Kernel that was launched const char* kernel_name; /// Device the kernel was launched on int device; /// Stream the kernel was launched on int32_t stream; /// A number that uniquely identifies the kernel launch uint64_t generation_number; }; /// Circular buffer used to hold information about kernel launches /// this is later used to reconstruct how a device-side kernel assertion failure /// occurred CUDAKernelLaunchRegistry is used as a singleton class C10_CUDA_API CUDAKernelLaunchRegistry { private: /// Assume that this is the max number of kernel launches that might ever be /// enqueued across all streams on a single device static constexpr int max_kernel_launches = 1024; /// How many kernel launch infos we've inserted. Used to ensure that circular /// queue doesn't provide false information by always increasing, but also to /// mark where we are inserting into the queue #ifdef TORCH_USE_CUDA_DSA uint64_t generation_number = 0; #endif /// Shared mutex between writer and accessor to ensure multi-threaded safety. mutable std::mutex read_write_mutex; /// Used to ensure prevent race conditions in GPU memory allocation mutable std::mutex gpu_alloc_mutex; /// Pointer to managed memory keeping track of device-side assertions. There /// is one entry for each possible device the process might work with. Unused /// entries are nullptrs. We could also use an unordered_set here, but this /// vector design will be faster and the wasted memory is small since we /// expect the number of GPUs per node will always be small std::vector< std::unique_ptr<DeviceAssertionsData, void (*)(DeviceAssertionsData*)>> uvm_assertions; /// A single circular buffer holds information about every kernel launch the /// process makes across all devices. std::vector<CUDAKernelLaunchInfo> kernel_launches; bool check_env_for_enable_launch_stacktracing() const; bool check_env_for_dsa_enabled() const; public: CUDAKernelLaunchRegistry(); /// Register a new kernel launch and obtain a generation number back to be /// passed to the kernel uint32_t insert( const char* launch_filename, const char* launch_function, const uint32_t launch_linenum, const char* kernel_name, const int32_t stream_id); /// Get copies of the kernel launch registry and each device's assertion /// failure buffer so they can be inspected without raising race conditions std:: pair<std::vector<DeviceAssertionsData>, std::vector<CUDAKernelLaunchInfo>> snapshot() const; /// Get a pointer to the current device's assertion failure buffer. If no such /// buffer exists then one is created. This means that the first kernel launch /// made on each device will be slightly slower because memory allocations are /// required DeviceAssertionsData* get_uvm_assertions_ptr_for_current_device(); /// Gets the global singleton of the registry static CUDAKernelLaunchRegistry& get_singleton_ref(); /// If not all devices support DSA, we disable it const bool do_all_devices_support_managed_memory = false; /// Whether or not to gather stack traces when launching kernels bool gather_launch_stacktrace = false; /// Whether or not host-side DSA is enabled or disabled at run-time /// Note: Device-side code cannot be enabled/disabled at run-time bool enabled_at_runtime = false; /// Whether or not a device has indicated a failure bool has_failed() const; #ifdef TORCH_USE_CUDA_DSA const bool enabled_at_compile_time = true; #else const bool enabled_at_compile_time = false; #endif }; std::string c10_retrieve_device_side_assertion_info(); } // namespace cuda } // namespace c10 // Each kernel launched with TORCH_DSA_KERNEL_LAUNCH // requires the same input arguments. We introduce the following macro to // standardize these. #define TORCH_DSA_KERNEL_ARGS \ [[maybe_unused]] c10::cuda::DeviceAssertionsData *const assertions_data, \ [[maybe_unused]] uint32_t assertion_caller_id // This macro can be used to pass the DSA arguments onward to another // function #define TORCH_DSA_KERNEL_ARGS_PASS assertions_data, assertion_caller_id
true
2fd98db21e1a396cfc3a2e0b1890a64529f82947
C++
wzhFeng/HydrusExecuterTools
/HydrusFiles/Stringhelper.h
UTF-8
1,986
3.1875
3
[ "MIT" ]
permissive
#include <utility> #ifndef STRINGHELPER_H #define STRINGHELPER_H #include <string> #include <vector> class Stringhelper { public: Stringhelper(const std::string& s):_str(s) {} Stringhelper(const char* c):_str(c){} Stringhelper(const Stringhelper& rhs) { if(this!=&rhs) { _str=rhs._str; } } Stringhelper& operator=(const Stringhelper& rhs) { if(this!=&rhs) { _str=rhs._str; } return *this; } std::string str() const { return _str; } Stringhelper& arg(long long a); Stringhelper& arg(unsigned long long a); Stringhelper& arg(long a); Stringhelper& arg(unsigned long a); Stringhelper& arg(int a); Stringhelper& arg(unsigned int a); Stringhelper& arg(short a); Stringhelper& arg(unsigned short a); Stringhelper& arg(double a); Stringhelper& arg(char a); Stringhelper& arg(unsigned char a); Stringhelper& arg(const std::string &a); Stringhelper& simplified(); Stringhelper& trimmed(); std::vector<std::string> split(const std::string &sep) const; std::vector<std::string> split( char sep) const; bool startsWith(const std::string& s,bool bcaseSensitive=true) const; bool startsWith( char c,bool bcaseSensitive=true) const; Stringhelper& replace( char before, char after, bool bCaseSensitive=true); Stringhelper& replace(const std::string& before, const std::string& after, bool bCaseSensitive=true); int compare(const std::string& s,bool bCaseSensitive=true) const; std::string toupper() const; std::string tolower() const; protected: std::pair<size_t,size_t> findArgEscapes(); void replaceArgEscapes(const std::string& s); void replaceCaseSensitive(const std::string& before, const std::string& after); void replaceInCaseSensitive(const std::string& before, const std::string& after); private: std::string _str; }; #endif // STRINGHELPER_H
true
3c989e4a9121426e916899d2e2a9126da487c455
C++
datamsh/cpp
/2018_studied_C++/문성환_201427519_과제10사원_오버로딩.cpp
UHC
1,592
3.765625
4
[]
no_license
#include <iostream> #include <vector> #include <string> using namespace std; enum EmployeeLevel{,븮,,,}; class Employee { string name; EmployeeLevel level; public: Employee(string name, EmployeeLevel employee) :name(name), level(employee){ } string getName() const { return name; } int getLevel() const { return level; } friend ostream& operator << (ostream& os, const Employee& employee); }; ostream& operator << (ostream& os, const Employee& employee) { os << employee.level << "\t" << employee.name << endl; return os; } class Manager :public Employee { vector<Employee*> group; public: Manager(string name, EmployeeLevel employee) :Employee(name,employee){ } void addEmployee(Employee* employee) { group.push_back(employee); } friend ostream& operator << (ostream& os, const Manager& manager); }; ostream& operator << (ostream& os, const Manager& manager) { os << manager.group.size() << "\t" << manager.getName() << endl; os << "List of employees managed by me" << endl; for (vector<Employee*>::const_iterator it = manager.group.begin();it!=manager.group.end() ;it++) { Employee employee = **it; os << employee.getLevel() << "\t" << employee.getName() << endl; } return os; } int main() { Employee e1("ȫ", ), e2("", 븮), e3("", ); cout << e1 << e2 << e3; Manager m1("Tom", ); m1.addEmployee(&e1); m1.addEmployee(&e2); m1.addEmployee(&e3); cout << endl << "Information for Manager" << endl; cout << m1; }
true
897dfe231940bf4141b8c6bfed3d2be737508f69
C++
parksangji/Coding-Test
/Programmers/Level1/Level1-28.cc
UTF-8
303
2.6875
3
[]
no_license
#include <string> #include <vector> using namespace std; int solution(int num) { int answer = 0; long long num1 = num; while(num1 != 1) { if(answer >= 500 ) return -1; if(num1 & 1) num1 = num1* 3 + 1; else num1 /= 2; answer++; } return answer; }
true
874f3276624ae675a39bbf7fb746abe41fa0b94d
C++
lukasnymsa/WildCard
/src/PlayerAI.hpp
UTF-8
1,349
2.984375
3
[]
no_license
#ifndef WILDCARD_PLAYERAI_HPP #define WILDCARD_PLAYERAI_HPP #include "Player.hpp" /** * Represents AI player * Its cards, health, cursor_position etc. */ class PlayerAI : public Player { public: /** * Creates a new AI player * @param max_health maximal health of the player * @param health starting health of the player */ explicit PlayerAI(int max_health, int health) : Player(max_health, health) {} /** * AI decides what card to pick and use * @param key_input no implemtation in AI player * @return reaction to GameScreen based on chosen key */ int NextAction(int key_input) override; /** * Draws only text so player cant see AI's cards and info * @param win window to draw in * @param player current player * @param size rows of current screen */ void DrawCards(WINDOW * win, bool player, int size) const override; /** * Draws only text so player cant see AI's cards and info * @param win window to draw in * @param max_col amount of collumns of the screen * @param size rows of current screen */ void DrawInfo(WINDOW * win, int max_col, int size) const override; /** * Deletes instance of PlayerAI */ ~PlayerAI() override = default; private: void ThrowCard(); }; #endif //WILDCARD_PLAYERAI_HPP
true
a4d7415b96e1587e3d8512abb74e0d9873b66ab3
C++
varshakrishnakumar/Amazon-Customer-Data-Analysis
/main.cpp
UTF-8
1,981
3.109375
3
[]
no_license
#include "Graph.h" int main() { Graph graphtemp;//graph object to read data.csv file std::vector<std::pair<int, int> > Grr = graphtemp.readcsvresult("/home/NETID/aiushem2-lisamp2-rgyanm2-varshak3/data.csv"); //obtaining max number of nodes in the data int nodes = graphtemp.readcsvtemp("/home/NETID/aiushem2-lisamp2-rgyanm2-varshak3/data.csv"); Graph g = Graph(nodes);//graph object for SCC Graph g2 = Graph(nodes);//graph object for Coloring //adding an edge between related nodes for (unsigned int i = 0; i < Grr.size(); i++) { g.addEdge(Grr[i].first, Grr[i].second); g2.addEdgeColoring(Grr[i].first, Grr[i].second); } //storing output of SCC in result vector std::vector<int> result = g.printstronglyConnect(); //storing output of Graph Coloring in colorresult int-pair vector std::vector<std::pair<int, int> > colorresult = g2.greedyColoring(); /*Writing to stronglyconnected.csv*/ // Create an output filestream object for SCC std::ofstream myFile("stronglyconnected.csv"); // Send data to the stream for(unsigned i = 0; i < result.size(); ++i) { myFile << result.at(i) << ",\n"; } // Close the file myFile.close(); /*Writing to graphcolor.csv*/ // Create an output filestream object for Coloring std::ofstream myColorFile("graphcolor.csv"); int count=0; // Send data to the stream for(unsigned i = 0; i < colorresult.size(); ++i) { myColorFile << "Vertex "<< colorresult[i].first<< " ---> Color " << colorresult[i].second << "\n"; } //finding max number of colors used for(unsigned j = 0; j < colorresult.size(); ++j) { if(colorresult[j].second > count){ count = colorresult[j].second; } } //Writing max number of colors to end of .csv file myColorFile << "Max Colors used: " << count; // Close the file myColorFile.close(); return (0); }
true
230cd233e4a1961e84a7e7aa03385df22fe22fca
C++
reidaruss/Reid_Russell_CS3353
/Lab4/src/Node.h
UTF-8
459
2.90625
3
[]
no_license
// // Created by Reid Russell on 11/23/2019. // #ifndef LAB4_NODE_H #define LAB4_NODE_H #include <iostream> #include <vector> class Node { private: int nodeId; std::vector<float> position; public: Node(); void setPos(std::vector<float> pos); void setId(int id) {nodeId = id;} int getId()const {return nodeId;} std::vector<float> getPos() {return position;} float getPosAt(int i) {return position[i];} }; #endif //LAB4_NODE_H
true
66ad90a7454e144a509931bf5689b850fc4ffe10
C++
tommy-russoniello/cpp-tic-tac-toe
/board.h
UTF-8
2,997
3.65625
4
[]
no_license
#ifndef BOARD_H #define BOARD_H #include <random> #include <vector> using std::mt19937; using std::pair; using std::vector; class Board { private: bool won; char spaces [10]; vector<int> winningRow; vector<int> movesX; vector<int> movesO; mt19937 gen; // Sets given value at given position of board based on the indexes used internally for this // class. bool update (char xo, int pos); // Clears any marks from given space, resetting a victory if applicable. void clearSpace (int pos); // Determines whether current state of the board fulfills a victory condition and sets the 'won' // boolean accordingly. void checkIfWon (int pos, vector<int>& moves); // Determines if given middle space has fulfilled a victory condition and sets the 'won' boolean // accordingly. void midCheck (int pos, vector<int>& moves); // Determines if given corner space has fulfilled a victory condition and sets the 'won' boolean // accordingly. void cornerCheck (int pos, vector<int>& moves); // Determines if center space has fulfilled a victory condition and sets the 'won' boolean // accordingly. void centerCheck (vector<int>& moves); // Returns position opposite of given position. int opposite (int pos); // Returns whether or not the given vector contains the given element. bool vfind (vector<int> vec, int num); // Prints out the value of given space in proper color. void printSpace (int space); // Determines if given player is one away from having three of their marks in a row anywhere on // the board and returns a pair with (first) a boolean of whether or not it found a space that // satisfied the condition and (second) the position of the first space that satisfied the // condition. pair <bool, int> oneAway (char xo); // Returns vector containing the positions of all spaces that are unmarked. vector<int> allOpenSpaces (); // Returns position of a random unmarked corner space. int randomOpenCorner (); // Returns whether or not given position corresponds to a corner space. bool isCorner (int pos); // Returns whether or not given position corresponds to a mid space. bool isMid (int pos); // Returns whether or not given position corresponds to the center space. bool isCenter (int pos); // Returns whether or not given positions are adjacent to each other. bool isAdjacent (int pos_a, int pos_b); public: Board (); // Prints current state of board in typical format. void print (); // Prints board in typical format but with numbers in the spaces that correspond to the numbers // the user must enter to mark them. void printSample (); // Sets given value at given position of board based on the indexes known to the user. bool setValue (int pos, char xo); // Returns whether or not the current state of the board fulfills a victory condition. bool hasWon (); // Performs automatic movement for given player. void autoMove (char xo); }; #endif
true
ab4d539a43a5343d041ed14dc725b8c348b80b56
C++
Hennessey-ak/Stephen-prata-solutions
/golf.cpp
UTF-8
721
3.203125
3
[]
no_license
#include <iostream> #include <cstring> #include "golf.h" using std::cout; using std::cin; using std::endl; void setgolf(golf &g, const char *name, int hc) { std::strcpy(g.fullname,name); g.handicap = hc; } int setgolf(golf &g) { cout<<"Enter the name (Enter nothing to quit): "; cin.get(g.fullname,Len); if(!cin || g.fullname[0] == '\0') { cin.clear(); cin.get(); return 0; } else { while(cin.get() != '\n') continue; cout<<"Enter the handicap: "; cin>>g.handicap; cin.get(); return 1; } } void showgolf(const golf &g) { cout<<"Name: "<<g.fullname<<endl; cout<<"Handicap: "<<g.handicap<<endl; } void handicap(golf &g,int hc) { g.handicap = hc; }
true
d47b6fa93831b6318e826833d44a32f257c417f5
C++
akshaymishra5395/GeeksforGeeks
/Row with max 1s.cpp
UTF-8
426
3.125
3
[]
no_license
// https://practice.geeksforgeeks.org/problems/row-with-max-1s0023/1 class Solution{ public: int rowWithMax1s(vector<vector<int> > arr, int n, int m) { int j=arr[0].size()-1; int index=-1; for (int i=0;i<arr.size();i++) { while(j>=0 && arr[i][j]==1) { j--; index=i; } } return index; } }; // T.C= O(n+m) // S.C= O(1)
true
7c58c8f336f0c7d32e66cf0ea1dc22b201b4472a
C++
prudentboy/leetcode
/Solutions/102.binary-tree-level-order-traversal.cpp
UTF-8
1,153
3.21875
3
[]
no_license
/* * @lc app=leetcode id=102 lang=cpp * * [102] Binary Tree Level Order Traversal */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> ans; if (root == nullptr) return ans; std::queue<TreeNode*> q_tree; q_tree.push(root); vector<int> layer; TreeNode* tmp; int len(1); while(not q_tree.empty()) { tmp = q_tree.front(); q_tree.pop(); if (tmp->left != nullptr) { q_tree.push(tmp->left); } if (tmp->right != nullptr) { q_tree.push(tmp->right); } layer.push_back(tmp->val); if (layer.size() == len) { ans.push_back(layer); layer.clear(); len = q_tree.size(); } } return ans; } };
true
f831e5a97ba6685585ea216ab87973dd2694a4c4
C++
RafaelOstertag/gangof4
/src/game/game.hh
UTF-8
1,263
2.515625
3
[ "BSD-2-Clause" ]
permissive
#ifndef __GAME_HH #define __GAME_HH #include "../board/board.hh" #include "../board/boardrenderer.hh" #include "../scorer/scorer.hh" #include "../sdl/fontfactory.hh" #include "../sdl/renderable.hh" #include "../sdl/window.hh" #include "../tetrimino/tetriminostock.hh" #include "../sdl/text.hh" #include "labelvalue.hh" #include "preview.hh" #include "soundcallback.hh" #include <memory> class Game : public Renderable { public: Game(const Window& window, FontFactory& fontFactory, TetriminoStockPtr tetriminoStock, ScorerPtr scorer); virtual ~Game(); void rotateCurrentTetrimino() { board->rotateCurrentTetrimino(); } void moveCurrentTetriminoLeft() { board->moveCurrentTetriminoLeft(); } void moveCurrentTetriminoRight() { board->moveCurrentTetriminoRight(); } void nextMove(); ScorerPtr getScorer() const { return scorer; } virtual void render(const Renderer& renderer); private: TetriminoStockPtr tetriminoStock; ScorerPtr scorer; std::shared_ptr<Board> board; LabelValue score; LabelValue level; Text nextTetrimino; Text gameOverText; MinoTextureStore minoTextureStore; BoardRenderer boardRenderer; Preview preview; }; using GamePtr = std::shared_ptr<Game>; #endif
true
b9f9c7b64ff4c01579d8596a27bb1dc3b2481d04
C++
facebook/openbmc
/common/recipes-qin/ipc-interface/files/Ipc.h
UTF-8
2,820
3
3
[]
no_license
/* * Copyright 2014-present Facebook. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #pragma once #include <string> #include <functional> namespace openbmc { namespace qin { /** * Ipc class provides a general interface for polymorphism over * interprocess communication techniques such as file systems * and DBus. */ class Ipc { public: typedef void onConnFuncType(void); virtual ~Ipc() {} /** * Register for the Ipc connection. Throw errors if the connection * failed. */ virtual void registerConnection() = 0; /** * Unregister for the Ipc connection. Throw errors properly. */ virtual void unregisterConnection() = 0; /** * Register the object path on the connection. Throw errors if * the object cannot be registered. * * @param path of the object * @param userData to be associated with the object * @throw std::invalid_argument if path is illegal */ virtual void registerObject(const std::string &path, void* userData) = 0; /** * Unregister the dbus object with all the associated object args. * * @param path of the object */ virtual void unregisterObject(const std::string &path) = 0; /** * Check if the object path matches the rule of the Ipc */ virtual bool isPathAllowed(const std::string &path) const = 0; /** * The get function that forms a path from the given parentPath * and name. * * @param parentPath is path to parent of object to create path with * @param name is the name of the object to create path with * @return new path */ virtual const std::string getPath(const std::string &parentPath, const std::string &name) const = 0; /** * Callback on connection acquired for the user application to set */ std::function<onConnFuncType> onConnAcquired; /** * Callback on connection lost for the user application to set */ std::function<onConnFuncType> onConnLost; }; } // namesapce ipc } // namespace openbmc
true
72b17585c84f4bbcc0aec401924dbc0843cc64bd
C++
CameronJMurphy/AI-Repo
/Dinosaur Sim/inc/dijkstrasSearch.h
UTF-8
1,298
2.859375
3
[]
no_license
#pragma once #include <iostream> #include <vector> #include<list> #include <math.h> struct Vector2 { Vector2() : x(0), y(0){} Vector2(float X, float Y) : x(X), y(Y) {} float x; float y; float Magnitude() { return sqrt(x * x + y * y); } }; namespace Pathfinding { struct Edge { struct Node* target; float cost; }; struct Node { Node() {} ~Node() {} // User defined data attached to each node. Vector2 position; float gScore = 100000; float hScore = 100000; float fScore = 100000; Node* parent; std::vector< Edge > connections; bool operator <(Node* node) { if (node->fScore > fScore) { return true; } return false; } }; } std::vector<Pathfinding::Node*> GenerateNodeMap(const int width, const int height, const float windowWidth, const float windowHeight); float Heuristic(Pathfinding::Node* _target, Pathfinding::Node* _endNode); std::list<Pathfinding::Node*> dijkstrasSearch(Pathfinding::Node* startNode, Pathfinding::Node* endNode, std::vector<Pathfinding::Node*> map); void PosToNodeTranslation(float posX, float posY, int mapX, int mapY);
true
5ac348df2767f2f26405135e66065756bba0ad41
C++
Mayank-Parasar/leetcode
/pointer_to_array_of_matrices.cpp
UTF-8
2,013
3.546875
4
[]
no_license
// // Created by Mayank Parasar on 11/9/20. // /* Given by user input * create multiple matrices * with values; of dimension given by user * For example: * ./leetcode <num-matrix> <dim-of-mat-0> <dim-of-mat-1> <dim-of-mat-2> ... * This will print matrices: * Matrix-0: <dim-of-mat-0> X <dim-of-mat-0> * Matrix-1: <dim-of-mat-1> X <dim-of-mat-1> * Matrix-2: <dim-of-mat-2> X <dim-of-mat-2>.. and so on.. * Example: * ./leetcode 3 2 3 5 will produce following output * ----------------------------------------------------- Printing the Matrices.. Number of Matrices populated: 3 Printing Matrix: 0 2 2 2 2 Printing Matrix: 1 3 3 3 3 3 3 3 3 3 Printing Matrix: 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 * ----------------------------------------------------- * */ #include <iostream> #include <vector> std::vector<std::vector<std::vector<int>>*> mat_ptr; using namespace std; vector<int>* vec_ptr; int main(int argc, char* argv[]) { for(int mat_id = 2; mat_id < argc; mat_id++) { std::vector<std::vector<int>>* tmp; tmp = new std::vector<std::vector<int>> (atoi(argv[mat_id]), std::vector<int> (atoi(argv[mat_id]), atoi(argv[mat_id]))); mat_ptr.push_back(tmp); } std::cout << "Printing the Matrices.." << std::endl; std::cout << "Number of Matrices populated: " << mat_ptr.size() << std::endl; for (int mat_id = 0; mat_id < mat_ptr.size(); ++mat_id) { std::cout << "Printing Matrix: " << mat_id << std::endl; for(auto i : *mat_ptr[mat_id]) { for(auto k : i) { std::cout << k << " "; } std::cout << std::endl; } } vec_ptr = new vector<int>(10, 1); for (int ii = 0; ii < vec_ptr->size(); ++ii) { cout << (vec_ptr+ii) << endl; *(vec_ptr+ii) = 5; } cout << "-----------" << endl; for(int i : *vec_ptr) { cout << i << endl; } return 0; }
true
aba7558f3f4972f7f06e5af374ab9c4e217f339c
C++
ChuankunZhang/blastani
/DataInputClass.cpp
UTF-8
2,103
2.671875
3
[]
no_license
#include "DataInputClass.h" DataInputClass::DataInputClass(){ m_Path = " "; m_Query1 = " "; m_Query2 = " "; } DataInputClass::~DataInputClass(void){ } DataInputClass::DataInput(){ cout<<"*********************"<<endl<<"[ANI CALCULATOR v1.0]"<<endl<<"*********************"<<endl<<endl; cout<<"Please enter the BlastPlus Path [\"String\"] the genome1 file[\"String\"] the genome2 file[\"String\"]"<<endl; cout<<" recommanded blast path : C:/NCBI/blast+2.2.31+/bin/"<<endl; cout<<" directory path with gap (like \"Program Files/...\") "<<endl; cout<<" can be a problem in window OS."<<endl; cout<<" So, in case of containing gap in blast program path,"<<endl; cout<<" you should wrap the path with double quotation mark."<<endl; cout<<"e.g. -path /home/zck/ncbi-blast-2.2.23/bin -genome1 ../GCA/GCA_000026545.1_ASM2654v1_genomic.fna -genome2 ../GCA/GCA_000005845.2_ASM584v2_genomic.fna"<<endl; string query; char *next1=NULL; char *next2=NULL; char *l; char *l2; while(1) { getline(cin,query); next1=query.c_str(); l = strsep(&next1," "); r1 = atoi(l); next2 = next1; l = strsep(&next2,d); next1 = next2; l = strsep(&next1,d); r3=atof(l); next2 = next1; l = strsep(&next2,d); r4=atoi(l); next1 = next2; l = strsep(&next1,d); next2 = next1; l = strsep(&next2,d); next1 = next2; l = strsep(&next1,d); r7=atoi(l); next2 = next1; l = strsep(&next2,d); r8=atoi(l); } cout<<"Please enter the genome1 file[\"String\"]"<<endl; while(1) { getline(cin,m_Query1); const char *genome1=m_Query1.c_str(); if(!access(genome1, F_OK)) { cout<<"ok"<<endl; break; } else { perror("ERROR"); cout<<"Please enter the genome1 file again[\"String\"]"<<endl; } } cout<<"Please enter the genome2 file[\"String\"]"<<endl; while(1) { getline(cin,m_Query2); const char *genome2=m_Query2.c_str(); if(!access(genome2, F_OK)) { cout<<"ok"<<endl; break; } else { perror("ERROR"); cout<<"Please enter the genome2 file again[\"String\"]"<<endl; } } }
true
a48e2e9908d8932f4457632437a6d9589c6f62c7
C++
WULEI7/WULEI7
/数据结构作业/12.3 图的实现.cpp
GB18030
8,157
3.484375
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <stack> #include <queue> #define maxn 105 #define inf 999999999// using namespace std; typedef struct { int arcs[maxn][maxn];//ڽӾ int vexnum;//Ŵ1vexnum int arcnum;//ߣ int Graphkind;//ͼࣨ1Ϊͼ2Ϊ3Ϊͼ4Ϊ }MGraph;//ͼ void CreateDG(MGraph &G)//ͼG { cout<<"ͼGĶ"; cin>>G.vexnum; cout<<"ͼGĻ"; cin>>G.arcnum; for(int i=1;i<=G.vexnum;i++) for(int j=1;j<=G.vexnum;j++) G.arcs[i][j]=0;//ͼijʼ int u,v; cout<<"ÿijʼն˵㣺"<<endl; for(int i=1;i<=G.arcnum;i++) { cin>>u>>v; G.arcs[u][v]=1; } } void CreateDN(MGraph &G)//G { cout<<"GĶ"; cin>>G.vexnum; cout<<"GĻ"; cin>>G.arcnum; for(int i=1;i<=G.vexnum;i++) for(int j=1;j<=G.vexnum;j++) G.arcs[i][j]=inf;//ijʼ int u,v,w; cout<<"ÿijʼ㡢ն˵Ȩֵ"<<endl; for(int i=1;i<=G.arcnum;i++) { cin>>u>>v>>w; G.arcs[u][v]=w; } } void CreateUDG(MGraph &G)//ͼG { cout<<"ͼGĶ"; cin>>G.vexnum; cout<<"ͼGı"; cin>>G.arcnum; for(int i=1;i<=G.vexnum;i++) for(int j=1;j<=G.vexnum;j++) G.arcs[i][j]=0;//ͼijʼ int u,v; cout<<"ÿߵ㣺"<<endl; for(int i=1;i<=G.arcnum;i++) { cin>>u>>v; G.arcs[u][v]=1; G.arcs[v][u]=1; } } void CreateUDN(MGraph &G)//G { cout<<"GĶ"; cin>>G.vexnum; cout<<"Gı"; cin>>G.arcnum; for(int i=1;i<=G.vexnum;i++) for(int j=1;j<=G.vexnum;j++) G.arcs[i][j]=inf;//ijʼ int u,v,w; cout<<"ÿߵȨֵ"<<endl; for(int i=1;i<=G.arcnum;i++) { cin>>u>>v>>w; G.arcs[u][v]=w; G.arcs[v][u]=w; } } void CreateGraph(MGraph &G)//ͼG { cout<<"ͼࣨ1Ϊͼ2Ϊ3Ϊͼ4Ϊ"; cin>>G.Graphkind; switch(G.Graphkind) { case 1:CreateDG(G);break; case 2:CreateDN(G);break; case 3:CreateUDG(G);break; case 4:CreateUDN(G);break; default: cout<<"ʧܣ"<<endl; return; } } void PrintGraph(MGraph G)//ӡͼGڽӾ { printf("ͼGڽӾΪ\n"); for(int i=1;i<=G.vexnum;i++) { for(int j=1;j<=G.vexnum;j++) { if(G.arcs[i][j]==inf) printf(" 00");//ʾ else printf("%5d",G.arcs[i][j]); } printf("\n"); } } int VexDeg(MGraph G,int vex,vector<int> &vec)//ͼĶȺڽӵ { int cnt=0; if(G.Graphkind==3)//ͼ for(int i=1;i<=G.vexnum;i++) if(G.arcs[vex][i]!=0) { vec.push_back(i); cnt++; } if(G.Graphkind==4)// for(int i=1;i<=G.vexnum;i++) if(G.arcs[vex][i]!=inf) { vec.push_back(i); cnt++; } return cnt; } int VexIndeg(MGraph G,int vex)//ͼ { int cnt=0; if(G.Graphkind==1)//ͼ for(int i=1;i<=G.vexnum;i++) if(G.arcs[i][vex]!=0) cnt++; if(G.Graphkind==2)// for(int i=1;i<=G.vexnum;i++) if(G.arcs[i][vex]!=inf) cnt++; return cnt; } int VexOutdeg(MGraph G,int vex)//ͼij { int cnt=0; if(G.Graphkind==1)//ͼ for(int i=1;i<=G.vexnum;i++) if(G.arcs[vex][i]!=0) cnt++; if(G.Graphkind==2)// for(int i=1;i<=G.vexnum;i++) if(G.arcs[vex][i]!=inf) cnt++; return cnt; } int vis[maxn],dis[maxn]; void DFSGraph(MGraph G,int vex)//ӶvexʼȱͼG { cout<<vex<<" "; vis[vex]=1; for(int i=1;i<=G.vexnum;i++) if(G.arcs[vex][i]==1&&vis[i]==0) DFSGraph(G,i); } void BFSGraph(MGraph G)//Ӷ1ʼȱͼG { queue<int> que; for(int i=1;i<=G.vexnum;i++) if(vis[i]==0) { vis[i]=1; cout<<i<<" "; while(!que.empty()) { que.pop(); for(int j=1;j<=G.vexnum;j++) if(G.arcs[i][j]==1&&vis[j]==0) { vis[j]=1; cout<<j<<" "; que.push(j); } } } } //С int u[maxn],v[maxn],w[maxn],p[maxn],r[maxn];//u v wֱΪߵĶȨֵpΪ鼯ڵ㣬rΪߵı bool cmp(const int i,const int j) { return w[i]<w[j]; } int find(int x)//鼯 { return p[x]==x ? x:p[x]=find(p[x]); } int Kruskal(MGraph G)//Kruskal㷨С { int cnt=0,ans=0,n=G.vexnum,m=G.arcnum; for(int i=1;i<=n;i++) for(int j=i+1;j<=n;j++) if(G.arcs[i][j]<inf) { u[++cnt]=i; v[cnt]=j; w[cnt]=G.arcs[i][j]; } for(int i=1;i<=n;i++) p[i]=i; for(int i=1;i<=m;i++) r[i]=i; sort(r+1,r+m+1,cmp);//ߵȨֵ for(int i=1;i<=m;i++) { int e=r[i]; int x=find(u[e]); int y=find(v[e]); if(x!=y) { cout<<u[e]<<" "<<v[e]<<endl;//ı p[x]=y;//ϲ ans+=w[e]; } } return ans; } int Prim(MGraph G)//Prim㷨С { memset(vis,0,sizeof(vis)); int n=G.vexnum; for(int i=1;i<=n;i++) dis[i]=G.arcs[1][i]; dis[1]=0;vis[1]=1; for(int i=1;i<n;i++) { int k=0,minn=inf; for(int j=1;j<=n;j++) if(vis[j]==0&&dis[j]<minn) { minn=dis[j]; k=j; } vis[k]=1; cout<<k<<" ";//Ķ for(int j=1;j<=n;j++) if(vis[j]==0&&dis[j]>G.arcs[k][j]) dis[j]=G.arcs[k][j]; } cout<<endl; int ans=0; for(int i=1;i<=n;i++) ans+=dis[i]; return ans; } //· int Dijkstra(MGraph G,int u,int v)//Dijkstra㷨Դ· { memset(vis,0,sizeof(vis)); int n=G.vexnum; for(int i=1;i<=n;i++) dis[i]=G.arcs[u][i];//uΪԭ dis[u]=0;vis[u]=1; for(int i=1;i<n;i++) { int k=0,minn=inf; for(int j=1;j<=n;j++) if(vis[j]==0&&dis[j]<minn) { minn=dis[j]; k=j; } if(k==0) break;//˾ҪΪеͼ߲ͨ vis[k]=1; for(int j=1;j<=n;j++) if(vis[j]==0&&dis[j]>dis[k]+G.arcs[k][j]) dis[j]=dis[k]+G.arcs[k][j]; } return dis[v]; } int Floyd(MGraph G,int u,int v)//Floyd㷨· { for(int k=1;k<=G.vexnum;k++) for(int i=1;i<=G.vexnum;i++) for(int j=1;j<=G.vexnum;j++) if(G.arcs[i][k]+G.arcs[k][j]<G.arcs[i][j]) G.arcs[i][j]=G.arcs[i][k]+G.arcs[k][j]; return G.arcs[u][v];//uv· } int main() { MGraph G; int n; cin>>n;//ݱ //ݲ1ͼ ȡȱ if(n==1) { CreateGraph(G);//ͼG memset(vis,0,sizeof(vis)); cout<<"ͼGȱΪ"; DFSGraph(G,1);//Ӷ1ʼȱͼG cout<<endl; memset(vis,0,sizeof(vis)); cout<<"ͼGĹȱΪ"; BFSGraph(G);//ȱͼG cout<<endl; } //ݲ2 С· if(n==2) { CreateGraph(G);//ͼG vector<int> vec; cout<<"3ĶΪ"<<VexDeg(G,3,vec)<<endl; cout<<"3ڽӵΪ"; for(int i=0;i<vec.size();i++) cout<<vec[i]<<" "; cout<<endl; PrintGraph(G);//ӡͼGڽӾ cout<<"Prim㷨ͼGС"<<endl; cout<<"ÿμĶΪ"<<endl; cout<<"СΪ"<<Prim(G)<<endl; cout<<"Kruskal㷨ͼGС"<<endl; cout<<"ÿμıΪ"<<endl; cout<<"СΪ"<<Kruskal(G)<<endl; cout<<"Dijkstra㷨ö15֮·Ϊ"<<Dijkstra(G,1,5)<<endl; cout<<"Floyd㷨ö15֮·Ϊ"<<Floyd(G,1,5)<<endl; } return 0; } /* ͼ ȡȱ 8 9 1 2 1 3 2 4 2 5 3 6 3 7 4 8 5 8 6 7 С· 6 10 1 2 6 1 3 1 1 4 5 2 3 5 2 5 3 3 4 5 3 5 6 3 6 4 4 6 2 5 6 6 */
true
5f3e6432c87499034bbd88f308b724ce55d3409f
C++
JJBBB/Cplusplus-Library-based-on-the-single-list
/DATA/genDLList.h
UTF-8
1,305
3.484375
3
[]
no_license
#ifndef DOUBLY_LINKED_LIST #define DOUBLY_LINKED_LIST #include "stdafx.h" template<class T> class DLLNode { public: DLLNode() { next = prev = 0; } DLLNode(const T& el, DLLNode *n = 0, DLLNode *p = 0) { info = el; next = n; prev = p; } T info; DLLNode *next, *prev; }; template<class T> class DoublyLinkedList { public: DoublyLinkedList() { head = tail = 0; } void addToDLLTail(const T&); T deleteFromDLLTail(); void Travase()const; protected: DLLNode<T> *head, *tail; }; template<class T> void DoublyLinkedList<T>::addToDLLTail(const T& el) { if (tail != 0) { tail->next = new DLLNode<T>(el, tail->next, tail); tail = tail->next; head->prev = tail; } else { head = tail = new DLLNode<T>(el); tail->next = tail; tail->prev = tail; } } template<class T> T DoublyLinkedList<T>::deleteFromDLLTail() { DLLNode<T> *tmp = tail; T res = tail->info; if (head == tail) { delete head; head = tail = 0; } else { tail = tail->prev; delete tail->next; tail->next = head; head->prev = tail; } return res; } template<class T> void DoublyLinkedList<T>::Travase()const { DLLNode<T> *tmp; for (tmp = head; tmp != tail; tmp = tmp->next) { cout << tmp->info << endl; } cout << tail->info << endl; } #endif
true
204efa0ed56cfef6f19b602ae5edc3ef0e40ba98
C++
LuckyGrx/CppPrimer
/ch13/ex13_18.h
UTF-8
488
2.828125
3
[]
no_license
/// /// @file ex13_18.h /// @author zack(18357154046@163.com) /// @date 2017-09-08 19:04:58 /// #ifndef __CP5_EX13_18_H__ #define __CP5_EX13_18_H__ #include <string> class Employee{ public: Employee(); Employee(const std::string&); private: std::string _name; int _id; static int _id_increase; }; int Employee::_id_increase=0; Employee::Employee():_name(std::string()){ _id=_id_increase++; } Employee::Employee(const std::string &name):_name(name){ _id=_id_increase++; } #endif
true
f8aa27236b1913bba0b87b10597504d68be7d2e4
C++
nmicht/ejercicios-progra-cpp
/Secuenciales/practica9.cpp
UTF-8
472
3.171875
3
[]
no_license
#include <iostream> using namespace std; #define HORA 6.875 int main (int argc, char* argv[]) { float horastotales, hraextras, extras, salario; cout << "Cuantas horas trabajaste en la quincena? "; cin >> horastotales; hraextras = horastotales - 80; salario = 80 * HORA; extras = hraextras * HORA * 2; cout << "Salario: $" << salario << endl; cout << "Horas extras: $" << extras << endl; cout << "Total: $" << salario + extras; }
true
9ed60aee39815c16085ed45d7fe2e37cd50aa7de
C++
TsufCohen/AVL-Tree
/TreeNode.h
UTF-8
17,646
3.4375
3
[]
no_license
// // Created by Tsuf Cohen on 2019-06-15. // #ifndef TESTFORTREEAVL_TREENODE_H #define TESTFORTREEAVL_TREENODE_H #include <cstdio> #include <iostream> using std::size_t; /** * * @tparam T - must have 'operator=','operator<' and 'operator=='. * note: 'T information' is the node's key, so the fields (in class T) that are * used as keys must to be private and unable to be changed by methods. */ template <typename T /* typename Key, typename Data */ > class TreeNode { // Key; T* information; size_t height; TreeNode* left; TreeNode* right; //------------------------------------------------------------------------------ /**------------------------------UpdateHeight----------------------------------- * * a method used to update the node's height. */ void UpdateHeight() { if(left==NULL && right==NULL) { height = 0; return; } size_t a = 0, b = 0; if(left) { a = left->height; } if(right) { b = right->height; } size_t max = (a<b) ? b : a; height = max+1; } //------------------------------------------------------------------------------ /**----------------------------BaseRotateLeft----------------------------------- * * a method used to do left base rotation to the node. * * note: the method also updating the heights. * @return pointer to the updated root (return 'this' if no right-sub-tree). */ TreeNode<T>* BaseRotateLeft() { if(right==NULL) { return this; } TreeNode<T>* new_root = right; right = new_root->left; new_root->left = this; this->UpdateHeight(); new_root->UpdateHeight(); return new_root; } //------------------------------------------------------------------------------ /**------------------------------BaseRotateRight-------------------------------- * * a method used to do right base rotation to the node. * * note: the method also updating the heights. * @return pointer to the updated root (return 'this' if no left-sub-tree). */ TreeNode<T>* BaseRotateRight() { if(left==NULL) { return this; } TreeNode<T>* new_root = left; left = new_root->right; new_root->right = this; this->UpdateHeight(); new_root->UpdateHeight(); return new_root; } //------------------------------------------------------------------------------ /**---------------------------------DeleteNode---------------------------------- * * a method used to delete a given node, mainly the root. * note: we use this with the Delete method and DeleteRoot method only. * @param node - pointer to the node we want to delete. * @return pointer to the updated root of the node's sub-tree. * null if no son's or if null argument. */ TreeNode<T>* DeleteNode(TreeNode<T>* node) { if(node==NULL) { return NULL; } TreeNode<T>* L = node->left; TreeNode<T>* R = node->right; if(L==NULL && R==NULL) { // node don't have son's. delete node; return NULL; }else if(L==NULL || R==NULL) { // have only one son. TreeNode<T>* tmp = ((L==NULL) ? R : L); node->left = NULL; node->right = NULL; // so don't delete son by mistake. delete node; return tmp->UpdateBalance(); }else { // have two son's. TreeNode<T>* current = node->right; while(current->left) { // find the next Inorder. current = current->left; } T* tmp = node->information; // swap the nodes information. node->information = current->information; current->information = tmp; if(current == node->right) { // the right son is next Inorder. node->right = DeleteNode(current); }else { node->right = node->right->Delete(*tmp); } return node->UpdateBalance(); } } //------------------------------------------------------------------------------ public: /**-------------------------------Constructor----------------------------------- * * the constructor of the class. * note: the typename T must have 'operator=','operator<', 'operator<' and 'operator=='. * @param information - the pointer to the value we want to save in the node. * if NULL than we get an empty node. */ explicit TreeNode(T* information = NULL) : information(information), height(0), left(NULL), right(NULL) {} //------------------------------------------------------------------------------ /**--------------------------------Destructor----------------------------------- * * Destructor - delete the sub-trees first. */ ~TreeNode() { delete left; delete right; } //------------------------------------------------------------------------------ TreeNode(const TreeNode<T>& other) = delete; TreeNode<T>& operator=(const TreeNode<T>& other) = delete; //------------------------------------------------------------------------------ /**--------------------------------GetBalanceFactor----------------------------- * * a method used to calculate and get the balance factor of a node. * * note: (balance factor) = (left-sub-tree's height)-(right-sub-tree's height). * @return int - the balance factor. */ int GetBalanceFactor() { UpdateHeight(); int a = 0, b = 0; if(left) { a = (1+(int)(left->height)); } if(right) { b = (1+(int)(right->height)); } return (a-b); } //------------------------------------------------------------------------------ /**------------------------------UpdateBalance---------------------------------- * * a method used to balance the AVL node with it's sub-trees. * * note: the method also updating the heights. * @return pointer to the updated root (return 'this' if already balanced). */ TreeNode<T>* UpdateBalance() { if(left==NULL && right==NULL) { UpdateHeight(); return this; } switch(GetBalanceFactor()) { case 2: if(left->GetBalanceFactor()>=0) { return BaseRotateRight(); // LL rotate. }else { left = left->BaseRotateLeft(); // LR rotate. return BaseRotateRight(); } case -2: if(right->GetBalanceFactor()<=0) { return BaseRotateLeft(); // RR rotate. }else { right = right->BaseRotateRight(); return BaseRotateLeft(); // RL rotate. } default:return this; } } //------------------------------------------------------------------------------ /**------------------------------Find------------------------------------------- * * a method used to find information in the node or in the sub-trees. * * @param value - a value that the user want's to find. * @return pointer to the node with the value or null if not inside. */ const TreeNode<T>* Find(T& value) const { const TreeNode<T>* node = this; T* info = NULL; while(node) { info = node->information; if(*info==value) { // value is found. return node; }else if(*info<value) { // go to the right sub-tree. node = node->right; }else { // go to the left sub-tree. node = node->left; } } return NULL; } //------------------------------------------------------------------------------ /**---------------------------------Add----------------------------------------- * * a method used to add an information to the node or to the sub-trees. * note: if the node's information is NULL, the value is inserted immediately, * without balancing or heights updating. * @param value - a pointer to the value that the user want's to add * @return pointer to the node with the value added or null if already inside * or if null param. */ TreeNode<T>* Add(T* value) { if(value==NULL) { return NULL; } if(information==NULL) { // add information to an empty node. information = value; return this; } TreeNode<T>* new_node = NULL; if(*information>*value) { // add in the left sub-tree. if(left==NULL) { left = new TreeNode<T>(value); new_node = left; }else { new_node = left->Add(value); left = left->UpdateBalance(); // balance in case it is needed. } } if(*information<*value) { // add in the right sub-tree. if(right==NULL) { right = new TreeNode<T>(value); new_node = right; }else { new_node = right->Add(value); right = right->UpdateBalance(); // balance in case it is needed. } } UpdateHeight(); return new_node; // if information==value than new_node is null. } //------------------------------------------------------------------------------ /**---------------------------------DeleteRoot---------------------------------- * * a method used to delete the root only. * @param root - pointer to the root we want to delete. * @return pointer to the updated root, null if no son's or if null argument. */ TreeNode<T>* DeleteRoot(TreeNode<T>* root) { return DeleteNode(root); } //------------------------------------------------------------------------------ /**---------------------------------Delete-------------------------------------- * * a method used to delete an information from the node or from the sub-trees. * * @param value - a value that the user want's to delete * @return pointer to the updated root or null if no more nodes left. */ TreeNode<T>* Delete(T& value) { if(*information<value) { // delete in the right sub-tree. if(right) { if((*(right->information))==value) { right = DeleteNode(right); }else { right = right->Delete(value); } } } if(*information>value) { // delete in the left sub-tree. if(left) { if((*(left->information))==value) { left = DeleteNode(left); }else { left = left->Delete(value); } } } return UpdateBalance(); } //------------------------------------------------------------------------------ /**---------------------------------GetInformation------------------------------ * * note: 'T information' is the node's key, so the fields (in class T) that are * used as keys must to be private and unable to be changed by methods. * @return pointer to the information. */ T* GetInformation() const { return information; } //------------------------------------------------------------------------------ /**---------------------------------GetHeight----------------------------------- * * @return the height of to the node. */ size_t GetHeight() const { return height; } //------------------------------------------------------------------------------ /**--------------------------------CopyInorder---------------------------------- * * recursive method for copying the node's and it's sub-trees information. * note: Inorder tour * @param treeNode - a node to copy it's information. * @param array - an array to save the information. * note: the array must have the size of the tree(number of nodes). * @param array_size * @param counter - used for the array index indicator. * note: must be initialized with 0. * @return true if success */ bool CopyInorder( TreeNode<T>* treeNode, T** array, size_t array_size, size_t* counter) const { if(treeNode==NULL || array==NULL || array_size<=0 || counter==NULL) { return false; } if(*counter==array_size) { return false; } CopyInorder(treeNode->left, array, array_size, counter); array[*counter] = treeNode->information; ++(*counter); CopyInorder(treeNode->right, array, array_size, counter); return true; } //------------------------------------------------------------------------------ /**--------------------------------AddInorder----------------------------------- * * recursive method for adding information to an almost-full-empty-tree. * note: add in an Inorder tour. * @param treeNode - a node to copy the information. * @param array - an array with the information to copy. * note: the array must have the size of the tree(number of nodes) or less. * @param array_size * @param counter - used for the array index indicator. * note: must be initialized with 0. * @return true if success */ bool AddInorder( TreeNode<T>* treeNode, T** array, size_t array_size, size_t* counter) { if(treeNode==NULL || array==NULL || array_size<=0 || counter==NULL) { return false; } if(treeNode->information!=NULL || *counter==array_size) { return false; } AddInorder(treeNode->left, array, array_size, counter); treeNode->information = array[*counter]; ++(*counter); AddInorder(treeNode->right, array, array_size, counter); return true; } //------------------------------------------------------------------------------ /**--------------------------------DeleteInformation---------------------------- * * recursive method for deleting the node's and it's sub-trees information. * note: Inorder tour. * @param treeNode - a node to delete it's information. */ void DeleteInformation(TreeNode<T>* treeNode) { if(treeNode==NULL) { return; } DeleteInformation(treeNode->left); if(treeNode->information!=NULL) { delete treeNode->information; } DeleteInformation(treeNode->right); } //------------------------------------------------------------------------------ /**------------------------------AddEmptyNode----------------------------------- * * a method used to add a node to the node's sub-trees. * note: this method is used only to build an almost-full-empty-tree. * @param num_of_nodes_to_add - number of nodes we want to add to 'this'. * @return true - success, false - the root node is not empty or have two sons. */ bool AddEmptyNode(size_t num_of_nodes_to_add) { if(num_of_nodes_to_add<0 || information!=NULL) { return false; } if(num_of_nodes_to_add==0) { return true; }else if(num_of_nodes_to_add==1) { if(left==NULL || right==NULL) { // create a sub-tree. (left ? right : left) = new TreeNode<T>(); }else { return false; } }else if(left==NULL && right==NULL) {// in case num_of_nodes_to_add >= 2. left = new TreeNode<T>(); // create the left sub-tree. right = new TreeNode<T>(); // create the right sub-tree. size_t num_of_nodes_left = num_of_nodes_to_add-2; left->AddEmptyNode((num_of_nodes_left%2)+(num_of_nodes_left/2)); right->AddEmptyNode(num_of_nodes_left/2); }else { // in case sub-trees already exists. return false; } UpdateHeight(); // if success - update height and finish. return true; } //------------------------------------------------------------------------------ /**----------------------------------PrintVisualNodes--------------------------- * * @param node - the node we want to print visual. * note: the method will print also the node's sub-tree. * @param level - the level of the node inside the tree. */ void PrintVisualNodes(TreeNode<T>* node, size_t level) { if(node==NULL) { return; } PrintVisualNodes(node->left, level-1); std::cout << "\n "; for(size_t i = 0 ; i<level ; ++i) { std::cout << " "; } std::cout << *node->information; PrintVisualNodes(node->right, level-1); } //------------------------------------------------------------------------------ }; #endif //TESTFORTREEAVL_TREENODE_H
true