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
544e139604c318a6e82957993bd8d63328642b53
C++
SiChiTong/Lib830
/components/DigitalLED.cpp
UTF-8
2,263
3.09375
3
[ "MIT" ]
permissive
#include <cmath> #include "frc/DigitalOutput.h" #include "frc/DriverStation.h" #include "frc/smartdashboard/SmartDashboard.h" #include "frc/Timer.h" #include "DigitalLED.h" using frc::DriverStation; using frc::DigitalOutput; using frc::SmartDashboard; namespace Lib830 { void DigitalLED::Enable() { red_channel->EnablePWM(0.0); green_channel->EnablePWM(0.0); blue_channel->EnablePWM(0.0); } DigitalLED::DigitalLED(DigitalOutput * red, DigitalOutput * green, DigitalOutput * blue) { red_channel = red; green_channel = green; blue_channel = blue; Enable(); } DigitalLED::DigitalLED(int red, int green, int blue) { red_channel = new DigitalOutput(red); green_channel = new DigitalOutput(green); blue_channel = new DigitalOutput(blue); Enable(); } void DigitalLED::Set( double red, double green, double blue){ red_channel->UpdateDutyCycle(red); green_channel->UpdateDutyCycle(green); blue_channel->UpdateDutyCycle(blue); SmartDashboard::PutNumber("red", red_channel->Get()); SmartDashboard::PutNumber("green", green_channel->Get()); SmartDashboard::PutNumber("blue", blue_channel->Get()); } void DigitalLED::Set(Color color) { Set(color.red, color.green, color.blue); } void DigitalLED::Disable() { Set(0,0,0); } void DigitalLED::Alternate(Color color_1, Color color_2) { timer.Start(); int time = timer.Get(); if (time%2 == 0) { Set(color_1); } else { Set(color_2); } } void DigitalLED::SetAllianceColor() { auto color = DriverStation::GetInstance().GetAlliance(); if (color == DriverStation::kBlue) { Set(0,0,1); } else if (color == DriverStation::kRed) { Set(1,0,0); } else { Set(0,0,0); } } void DigitalLED::RainbowFade(float fade_duration) { timer.Start(); double x = timer.Get() *(pi/(fade_duration/2)); double r = 0.5*sin(x) + 0.5; double g = (0.5*sin(x - ((2*pi)/3))) + 0.5; double b = (0.5*sin(x - ((4*pi)/3))) + 0.5; Set(r,g,b); } DigitalLED::Color DigitalLED::hex2color(int hex) { Color color; color.red = ((hex &0xff0000) >> 16 )/255.0; color.green = ((hex &0x00ff00) >> 8)/255.0; color.blue = ((hex &0x0000ff))/255.0; return color; } void DigitalLED::Set(int hex) { Color color = hex2color(hex); Set(color); } }
true
838d8c83935eaf04e084a65b75ad479c9906db79
C++
kalsan1998/face_tracking_camera
/MotorController.cpp
UTF-8
1,826
3.1875
3
[]
no_license
#include "MotorController.h" #include <iostream> #include "Chip.h" MotorController::MotorController(Chip *chip, int channel) : MotorController(chip, channel, 90) {} MotorController::MotorController(Chip *chip, int channel, int init_angle) : chip(chip), channel(channel) { if (!chip) { throw "MotorController: Received null chip"; } if (channel < 0 || channel > 15) { throw "MotorController: Invalid channel"; } start_reg = 6 + (4 * channel); stop_reg = start_reg + 2; set_angle(init_angle); } double MotorController::get_angle() const { return curr_angle; } void MotorController::set_angle(double angle) { // Write values to PWM registers // The chip has a PWM frequency of 200Hz (5ms per pulse). // The 4095 divides that 5ms into slices (1.2us per slice). // // The full range (0deg to 180deg -> 0.5ms to 2.5ms) gives us values of approximately 410 to // 2050. // Approximate values based on physically assessing things. static const int min = 300; static const int max = 2200; // Don't allow rotations near the min/max by this amount (just to be safe). static const int margin = 75; int stop_time = min + ((max - min) * angle / 180.0); //std::cout << "Stop time: " << stop_time << std::endl; if (stop_time < min + margin || stop_time > max - margin) { throw "MotorController: Attempted to set angle out of range"; } char buffer[3]; int length = 3; buffer[0] = start_reg; buffer[1] = 0; buffer[2] = 0; chip->write_buffer(buffer, length); buffer[0] = stop_reg; buffer[1] = stop_time & 0xff; // Low bytes first buffer[2] = (stop_time >> 8) & 0xff; chip->write_buffer(buffer, length); curr_angle = angle; }
true
4d7181f84d56a2c569b36a0622024f980288fedf
C++
IHR57/Competitive-Programming
/LightOJ/1014 (Iftar Party)-2.cpp
UTF-8
1,020
2.796875
3
[]
no_license
#include <iostream> #include <algorithm> #include <cstdio> #include <math.h> using namespace std; typedef long long int lint; lint divisor[1000005]; int main() { lint P, L, Q; int test, cases = 1; scanf("%d", &test); while(test--){ scanf("%lld %lld", &P, &L); Q = (P - L); printf("Case %d:", cases++); //special Case if( L >= Q){ printf(" impossible\n"); continue; } int sqrtQ = (int) sqrt(Q) + 1; int j = 0; for(int i = 1; i <= sqrt(Q); i++){ if(Q % i == 0 && i*i != Q){ divisor[j++] = i; divisor[j++] = Q / i; } if(Q % i == 0 && i*i == Q){ divisor[j++] = i; } } int len = j; sort(divisor, divisor + len); for(int i = 0; i < len; i++){ if(divisor[i] > L) printf("% lld", divisor[i]); } printf("\n"); } return 0; }
true
6344838de3615122e2eb092ddccd03d0a5d337c9
C++
tomerlo/HW4-mamat
/Cashier.H
UTF-8
499
2.53125
3
[]
no_license
#pragma once #ifndef _CASHIER_H_ #define _CASHIER_H_ #include <string.h> #include <stdlib.h> #include <stdio.h> #include <iostream> #include "Employee.H" #include "DubbedMovie.H" #include "Theater.H" class Cashier : public Employee { public: Cashier(char* workerName, int workerSalary, char* workHours[7]); int getTicketProfit() const; int sellTickets(Movie* pmovie, Theater* ptheater, BOOL isDubbed, int numOfTickets, int wantedRow, int mostRightCol); private: int m_ticketProfit; }; #endif
true
b5fb620c636ac724bc3f3b954ff94d47cfcc984d
C++
hiro-dot-exe/patient-observer
/src/image_renderer.h
UTF-8
2,509
2.671875
3
[ "MIT" ]
permissive
#ifndef KINECT_PATIENTS_OBSERVER_IMAGE_RENDERER_H_ #define KINECT_PATIENTS_OBSERVER_IMAGE_RENDERER_H_ class Observer; /// <summary> /// Manages the drawing of image data. /// </summary> class ImageRenderer { public: explicit ImageRenderer(Observer *observer); virtual ~ImageRenderer(); /// <summary> /// Set the window to draw to as well as the video format. /// Implied bits per pixel is 32. /// </summary> /// <param name="hWnd">window to draw to</param> /// <param name="pD2DFactory">already created D2D factory object</param> /// <param name="sourceWidth">width of image data to be drawn</param> /// <param name="sourceHeight">height of image data to be drawn</param> /// <param name="sourceStride">length (in bytes) of a single scanline</param> /// <returns>indicates success or failure</returns> HRESULT Initialize(HWND hwnd, ID2D1Factory *pD2DFactory, int sourceWidth, int sourceHeight, int sourceStride); /// <summary> /// Draws a 32 bit per pixel image of previously specified width, height, /// and stride to the associated hwnd. /// </summary> /// <param name="pImage">image data in RGBX format</param> /// <param name="cbImage">size of image data in bytes</param> /// <returns>indicates success or failure</returns> HRESULT Draw(BYTE *pImage, unsigned long cbImage); private: static const FLOAT cStrokeWidth; /// <summary> /// Ensure necessary Direct2d resources are created. /// </summary> /// <returns>indicates success or failure</returns> HRESULT EnsureResources(); /// <summary> /// Dispose of Direct2d resources. /// </summary> void DiscardResources(); void DrawPatientState(); void DrawHeadPosition(); void DrawShoulderPosition(); void DrawPatientArea(); void DrawBedArea(); void DrawLevel(); void Graph(); void GraphPatientState(); void GraphProbabilityPatientOnBed(); HWND m_hWnd; // Format information. UINT m_sourceWidth; UINT m_sourceHeight; LONG m_sourceStride; // Direct2D. ID2D1Factory *m_pD2DFactory; ID2D1HwndRenderTarget *m_pRenderTarget; ID2D1Bitmap *m_pBitmap; IDWriteFactory *m_pDWriteFactory; IDWriteTextFormat *m_pTextFormat; ID2D1SolidColorBrush *m_pGreenBrush; ID2D1SolidColorBrush *m_pLightGreenBrush; ID2D1SolidColorBrush *m_pOrangeBrush; // Observer. Observer *m_pObserver; }; #endif // KINECT_PATIENTS_OBSERVER_IMAGE_RENDERER_H_
true
4fffbb5375d1554c46d9e2e91bf7dd3a025f659d
C++
KelsenH/WordLocator
/BST_Node.cpp
UTF-8
2,154
3.734375
4
[]
no_license
/** * Implementation of BST_Node methods */ #include "BST_Node.h" BST_Node::BST_Node (std::string word) : word_ (word), left_ (NULL), right_ (NULL), line_numbers_ () {} void BST_Node::append (int line_num) { //Find way to delete these List_Node * n = new List_Node (line_num); line_numbers_.insert (* n); } void BST_Node::set_left (BST_Node & left) { this -> left_ = & left; } void BST_Node::set_right (BST_Node & right) { this -> right_ = & right; } std::string BST_Node::print_line_numbers (void) { return line_numbers_.print_list (); } std::string BST_Node::get_word (void) { return this -> word_; } void BST_Node::insert (std::string word, int line_num) { std::string curr_word = this -> get_word (); if (word == curr_word) { this -> append (line_num); } else if (word < curr_word) { if (this -> left_ == NULL) { left_ = new BST_Node (word); left_ -> append (line_num); } else { left_ -> insert (word, line_num); } } else if (word > curr_word) { if (this -> right_ == NULL) { right_ = new BST_Node (word); right_ -> append (line_num); } else { right_ -> insert (word, line_num); } } } BST_Node * BST_Node::remove (std::string word, BST_Node * parent) { if (word < this -> word_) { if (this -> left_ != NULL) { return left_ -> remove (word, this); } else {return NULL;} } else if (word > this -> word_) { if (this -> right_ != NULL) { return right_ -> remove (word, this); } else {return NULL;} } else { if (left_ != NULL && right_ != NULL) { this -> word_ = right_ -> get_min (); return right_ -> remove (this -> word_, this); } else if (parent -> left_ == this) { parent -> left_ = (left_ != NULL) ? left_ : right_; return this; } else if (parent -> right_ == this) { parent -> right_ = (left_ != NULL) ? left_ : right_; return this; } } } std::string BST_Node::get_min (void) { if (left_ == NULL) { return word_; } else { return left_ -> get_min (); } }
true
e901fe10157327952586ee6300e4cdf8b245de53
C++
kuniyoshi/chapter7
/c7/src/Iterator/Image.h
UTF-8
529
2.921875
3
[]
no_license
#ifndef BAKUDAN_ITERATOR_IMAGE #define BAKUDAN_ITERATOR_IMAGE #include "Point.h" #include "Iterator/Loop.h" class Size; namespace Iterator { class Image { private: Point from_; Point to_; int width_; Loop loop_x_; Loop loop_y_; public: Image(const Point& from, const Point& to, const Size& size); ~Image(); Image& operator++(); operator int() const; bool has_next() const; int width() const; int height() const; int unbiased_x() const; int unbiased_y() const; void reset(); }; } // namespace Iterator #endif
true
cc3893ad08f3a54b2919f9e46de8edfce7fc2219
C++
walterqin/weighbridge
/core/logdatawidget.cpp
UTF-8
2,188
2.546875
3
[]
no_license
#include <QtGui> #include "logdatawidget.h" #include "profile.h" LogDataWidget::LogDataWidget(QWidget *parent) : QWidget(parent) { QIcon logWarmIcon(style()->standardPixmap(QStyle::SP_MessageBoxWarning)); QIcon logCritialIcon(style()->standardPixmap(QStyle::SP_MessageBoxCritical)); QIcon logInfoIcon(style()->standardPixmap(QStyle::SP_MessageBoxInformation)); QStringList logTypeLbl; logTypeLbl << tr("系统日志"); m_logTypeWidget = new QTreeWidget; m_logTypeWidget->setHeaderLabels(logTypeLbl); addLogType(logCritialIcon, tr("紧急")); addLogType(logWarmIcon, tr("警告")); addLogType(logInfoIcon, tr("提示")); QStringList messageLabels; messageLabels << tr("概要") << tr("生成者") << tr("日期"); m_logBriefWidget = new QTreeWidget; m_logBriefWidget->setHeaderLabels(messageLabels); m_logBriefWidget->resizeColumnToContents(0); m_logBriefWidget->resizeColumnToContents(1); m_logDetail = new QTextEdit; m_logDetail->setReadOnly(true); m_logDataSplitter = new QSplitter(Qt::Vertical); m_logDataSplitter->addWidget(m_logBriefWidget); m_logDataSplitter->addWidget(m_logDetail); m_logDataSplitter->setStretchFactor(1, 1); m_mainSplitter = new QSplitter(Qt::Horizontal); m_mainSplitter->addWidget(m_logTypeWidget); m_mainSplitter->addWidget(m_logDataSplitter); m_mainSplitter->setStretchFactor(1, 1); } LogDataWidget::~LogDataWidget() { } void LogDataWidget::addLogType(const QIcon &icon, const QString &name) { QTreeWidgetItem *root; if (m_logTypeWidget->topLevelItemCount() == 0) { root = new QTreeWidgetItem(m_logTypeWidget); root->setText(0, tr("日志类型")); m_logTypeWidget->setItemExpanded(root, true); } else { root = m_logTypeWidget->topLevelItem(0); } QTreeWidgetItem *newItem = new QTreeWidgetItem(root); newItem->setText(0, name); newItem->setIcon(0, icon); if (!m_logTypeWidget->currentItem()) m_logTypeWidget->setCurrentItem(newItem); } void LogDataWidget::addMessage(const QString &subject, const QString &from, const QString &date) { }
true
427e9947a81e5629ed7a6abcbab7264eb2ba9390
C++
RoundRaccoon/MyAdventOfCode2020
/day7/secondStar.cpp
UTF-8
2,394
2.796875
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <map> #include <queue> #include <utility> using namespace std; map<string, int> indexOfColor; ifstream f(".in"); long long solve(int bags[601][601], int n, int start) { queue<pair<int, long long>> q; q.push(make_pair(start, 1)); long long ans = 0; while (!q.empty()) { pair<int,long long> crtPair = q.front(); q.pop(); int crt = crtPair.first; long long multiplier = crtPair.second; for (int i = 1; i <= n; ++i) if(bags[crt][i]) { ans += bags[crt][i]*multiplier; q.push(make_pair(i,bags[crt][i]*multiplier)); } } return ans; } int main() { string s; int bags[601][601]; int destIndex = 0; for (int i = 1; i <= 600; ++i) for (int j = 1; j <= 600; ++j) bags[i][j] = false; int n = 0; while (getline(f, s)) { int i = 0, j; for (; s[i] != ' '; ++i) ; ++i; for (; s[i] != ' '; ++i) ; string currentColor = s.substr(0, i); if (indexOfColor.find(currentColor) == indexOfColor.end()) { n++; indexOfColor[currentColor] = n; if (currentColor.compare("shiny gold") == 0) destIndex = n; } for (; i < s.length(); ++i) { if (isdigit(s[i])) { int number = s[i] - '0'; int j = i + 2; for (; j < s.length() && s[j] != ' '; ++j) ; ++j; for (; j < s.length() && s[j] != ' '; ++j) ; string newColor = s.substr(i + 2, j - i - 2); if (indexOfColor.find(newColor) != indexOfColor.end()) { bags[indexOfColor[currentColor]][indexOfColor[newColor]] = number; } else { n++; indexOfColor[newColor] = n; bags[indexOfColor[currentColor]][indexOfColor[newColor]] = number; if (newColor.compare("shiny gold") == 0) destIndex = n; } } } } cout << solve(bags,n,destIndex); return 0; }
true
b627c6be69a0b13f07bc7172ee1e2acfdb006c3b
C++
elikos/elikos_detection
/src/elikos_detection/TargetDetection/RobotDesc.h
UTF-8
2,120
3.09375
3
[ "MIT" ]
permissive
#ifndef DETECT_ROBOTDESC_H #define DETECT_ROBOTDESC_H #define PI 3.1415926535 #include <opencv2/core/core.hpp> #include "string" using namespace std; enum ColorsIndex {WHITE, GREEN, RED}; class RobotDesc { public: //Constructors and destructor RobotDesc(); RobotDesc(int, int, int); ~RobotDesc(); //Setter and getters int getID() const; void setID(int id); double getDirection() const; void setDirection(double direction); //The window is the area where we can find the robot on the frame cv::RotatedRect getWindow() const; void setWindow(cv::RotatedRect); int getHPos(); int getVPos(); void setXPos(int pos); void setYPos(int pos); void setRadius(int radius); void setColor(ColorsIndex); int getXPos() const; int getYPos() const; int getRadius() const; ColorsIndex getColor() const; cv::Scalar getHSVmin(); cv::Scalar getHSVmax(); void setHSVmin(cv::Scalar scalar); void setHSVmax(cv::Scalar scalar); double getArea(); void setArea(double area); double getDistance(){return distancePrevious;} void setDistance(double d){distancePrevious=d;} bool getAlreadyFound(){return alreadyFound;} void setAlreadyFound(bool a){alreadyFound=a;} bool getInsideFOV(){return insideFOV;} void setInsideFOV(bool in){insideFOV=in;} bool operator==(const RobotDesc& otherDesc) const; private: /////Attributes///// //Inside fov(field of view) bool insideFOV; // center int xPos, yPos; int radius; double area; //direction is an angle in radians double direction; //distance from the previous position on frame. TODO: Could be interesting to choose which robot to keep when there are many with the same ID. double distancePrevious; //to insure that there is only one robot by id bool alreadyFound; int id;//Used to compare two RobotDesc //window is the area on the frame where the robot was found cv::RotatedRect window; ColorsIndex color; string type; cv::Scalar HSVmin, HSVmax; }; #endif
true
d373d65005079c796e3a9f3065f1fd71da3920ee
C++
ycliuxinwei/My-leetcode-practice
/array/plusOne.cpp
UTF-8
999
3.9375
4
[]
no_license
/* Copyright 2015 Edmund Liu Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. */ #include <vector> #include <iostream> using namespace std; // print the vector void printVector(const vector<int>& a) { cout << "["; vector<int>::const_iterator it; for (it = a.begin(); it != a.end()-1; it++) cout << *it << " "; cout << *it << "]" << endl; } vector<int> plusOne(vector<int>& digits) { vector<int>::reverse_iterator it; int carry = 1; for (it = digits.rbegin(); it != digits.rend(); it++) { *it = (*it+carry); carry = *it/10; *it %= 10; } if (carry > 0) digits.insert(digits.begin(), carry); return digits; } int main() { int a[] = {9, 9, 9, 9, 9}; vector<int> digits(a, a+5); printVector(digits); vector<int> result = plusOne(digits); printVector(result); return 0; }
true
735d17749dedb4b3f7a03095805b90a17d3a34ef
C++
Rani-Zz/skill-tutorials
/玩转算法面试/7-9-404-Sum of Left Leaves/main.cpp
GB18030
764
3.625
4
[]
no_license
/** * 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 { private: int sumLeft(TreeNode* root,bool isleft) { if(root==NULL) return 0; if(isleft&&root->left==NULL&&root->right==NULL) { return root->val; } return sumLeft(root->left,true)+sumLeft(root->right,false); } public: /** *͵ Ǹڵ *ʱԱǷ *ǷΪжǷΪڵ */ int sumOfLeftLeaves(TreeNode* root) { return sumLeft(root,false); } };
true
159cb70a89682caf1bdac81edd9f58529debd0b2
C++
fabestine1/MyThing
/Fontys-Assignments-2019-2020-master/Embedded systems/TheVaultVN/FinalModel1.ino
UTF-8
1,008
3.296875
3
[]
no_license
// Including the Display #include "Display.h". // Declaring Red and Green lights const int LED1 = 4; const int LED2 = 5; const int LED3 = 6; //Declaring Buttonsint PIN_KEY1 = 9; int PIN_KEY2 = 8; //StartTheProgram int attempts = 0; //iterator to follow the numbers int i = 0; //counter which data we will use to assign int count1 = 1000; int count2 = 100; int count3 = 10; int count4 = 1; //passcodes int originalPasscode = 2431; int inputPasscode = 0; //iterator for the while loop int c; void setup() { //Red and green light pinMode(LED1, OUTPUT); //TwoButtons pinMode(PIN_KEY1, INPUT_PULLUP); pinMode(PIN_KEY2, INPUT_PULLUP); } int read_key() { int key1 = digitalRead(PIN_KEY1); int key2 = digitalRead(PIN_KEY2); if (key1 == LOW) return 1; if (key2 == LOW) return 2; return 0; } void loop() { int key = read_key(); Display.showDigitAt(0, 3); Display.showDigitAt(1, 2); Display.showDigitAt(2, 1); Display.showDigitAt(3, 4); delay(5000); }
true
c3242b36ddce27913d7cbd7e91febf7461520627
C++
Petrychho/studies
/lesson1/lab2.cpp
UTF-8
467
3.484375
3
[]
no_license
#include <iostream> int main() { int mass[10] = {0,1,2,3,4,5,6,7,8,9}; int mod; int i = 0; int min = mass[0]; int max = mass[0]; int i_min = 0; int i_max = 0; std::cin >> mod; while(i < 10) { if(mass[i] % mod < min) { min = mass[i]; i_min = i; } if(mass[i] % mod > max) { max = mass[i]; i_max = i; } i++; } std::cout << "Max = " << mass[i_max] << std::endl; std::cout << "Min = " << mass[i_min] << std::endl; return 0; }
true
260dcd6713c302bd2964d6ba4d963dab6903f51d
C++
inthra-onsap/algorithms-archive
/string/finite_automata/finite_automata.cc
UTF-8
1,773
2.984375
3
[]
no_license
#include "finite_automata.h" namespace algorithms_archive { namespace string { std::vector<int> FiniteAutomata::ProcessLps(std::string str) { std::vector<int> lps(str.length(), 0); int border = 0; lps[0] = 0; for (int i = 1; i < str.length(); ++i) { while (border > 0 && str[i] != str[border]) border = lps[border - 1]; border = (str[i] == str[border]) ? border + 1 : 0; lps[i] = border; } return lps; } std::vector<std::vector<int>> FiniteAutomata::PreprocessStates(std::string str) { int num_states = str.length() + 1; std::vector<std::vector<int>> states(num_states, std::vector<int>(256, 0)); int prefix_border; std::vector<int> lps = ProcessLps(str); for (int state = 0; state < num_states; ++state) { for (int ch = 65; ch < 68; ++ch) { if (state < str.length() && ch == str[state]) { states[state][ch] = state + 1; } else { prefix_border = (state > 0) ? lps[state - 1] : 0; while (prefix_border > 0 && ch != str[prefix_border]) prefix_border = lps[prefix_border - 1]; states[state][ch] = (ch == str[prefix_border]) ? prefix_border + 1 : 0; } } } return states; } std::vector<int> FiniteAutomata::PatternMatching(std::string pattern, std::string text) { std::vector<int> all_occurrences; if (pattern.length() > text.length()) { return all_occurrences; } std::vector<std::vector<int>> states_tbl = PreprocessStates(pattern); int curr_state = 0; for (int i = 0; i < text.length(); ++i) { curr_state = states_tbl[curr_state][text[i]]; if (curr_state == pattern.length()) { all_occurrences.push_back(i - pattern.length() + 1); } } return all_occurrences; } } // namespace string } // namespace algorithms_archive
true
43b8a5379878a2cfadd87094798b223ed50984c2
C++
michael-pruglo/advent-of-code-2019
/helpers/IntcodeComputerASCII.cpp
UTF-8
521
2.78125
3
[]
no_license
// // Created by Michael on 06/02/20. // #include "IntcodeComputerASCII.hpp" std::string IntcodeComputerASCII::grabOutput() { auto outp = IntcodeComputer::grabOutput(); std::string res; res.reserve(outp.size()); for (char c: outp) res.push_back(c); return res; } IntcodeComputer::Mem_t IntcodeComputerASCII::run(const std::string& input) { std::vector<Mem_t> inp; inp.reserve(input.size()); for (Mem_t x: input) inp.push_back(x); return IntcodeComputer::run(inp); }
true
a7d53d68141706187e66750459e89fa7c90bfe1b
C++
AavaGames/SDL_Dominos
/SDL_Dominos/SDL_Dominos/Managers/AssetManager.cpp
UTF-8
4,106
2.796875
3
[ "Unlicense" ]
permissive
// // AssetManager.cpp // SDL_Tutorial // // Created by Philip Fertsman on 2020-01-15. // Copyright © 2020 Philip Fertsman. All rights reserved. // #include "AssetManager.h" namespace SDLFramework { AssetManager * AssetManager::sInstance = nullptr; AssetManager * AssetManager::Instance() { if (sInstance == nullptr) { sInstance = new AssetManager(); } return sInstance; } void AssetManager::Release() { delete sInstance; sInstance = nullptr; } AssetManager::AssetManager() { } AssetManager::~AssetManager() { for (auto tex : mTextures) { if (tex.second != nullptr) { SDL_DestroyTexture(tex.second); } } mTextures.clear(); } SDL_Texture * AssetManager::GetTexture(std::string filename, bool managed) { std::string fullPath = SDL_GetBasePath(); fullPath.append("Assets/" + filename); if (mTextures[fullPath] == nullptr) { mTextures[fullPath] = Graphics::Instance()->LoadTexture(fullPath); } if (mTextures[fullPath] != nullptr && managed) { mTextureRefCount[mTextures[fullPath]] ++; } return mTextures[fullPath]; } void AssetManager::DestroyTexture(SDL_Texture *texture) { if (mTextureRefCount.find(texture) != mTextureRefCount.end()) { mTextureRefCount[texture]--; if (mTextureRefCount[texture] == 0) { for (auto elem : mTextures) { if (elem.second == texture) { SDL_DestroyTexture(elem.second); mTextures.erase(elem.first); return; } } for (auto elem : mTexts) { if (elem.second == texture) { SDL_DestroyTexture(elem.second); mTexts.erase(elem.first); return; } } } } } TTF_Font * AssetManager::GetFont(std::string filename, int size) { std::string fullPath = SDL_GetBasePath(); fullPath.append("Assets/" + filename); std::stringstream ss; ss << size; std::string key = fullPath + ss.str(); if (mFonts[key] == nullptr) { mFonts[key] = TTF_OpenFont(fullPath.c_str(), size); if (mFonts[key] == nullptr) { std::cerr << "Unable to load font " << filename << "! TTF Error: " << TTF_GetError() << std::endl; } } return mFonts[key]; } SDL_Texture * AssetManager::GetText(std::string text, std::string fontPath, int size, SDL_Color color, bool managed) { std::stringstream ss; ss << size << (int)color.r << (int)color.g << (int)color.b; std::string key = text + fontPath + ss.str(); if (mTexts[key] == nullptr) { TTF_Font * font = GetFont(fontPath, size); mTexts[key] = Graphics::Instance()->CreateTextTexture(text, font, color); } if (mTexts[key] != nullptr && managed) { mTextureRefCount[mTexts[key]]++; } return mTexts[key]; } Mix_Music * AssetManager::GetMusic(std::string filename, bool managed) { std::string fullPath = SDL_GetBasePath(); fullPath.append("Assets/" + filename); if (mMusic[fullPath] == nullptr) { mMusic[fullPath] = Mix_LoadMUS(fullPath.c_str()); } if (mMusic[fullPath] == nullptr) { std::cerr << "Unable to load music " << filename << "! Mix error: " << Mix_GetError() << std::endl; } else if (managed) { mMusicRefCount[mMusic[fullPath]]++; } return mMusic[fullPath]; } Mix_Chunk * AssetManager::GetSFX(std::string filename, bool managed) { std::string fullPath = SDL_GetBasePath(); fullPath.append("Assets/" + filename); if (mSFX[fullPath] == nullptr) { mSFX[fullPath] = Mix_LoadWAV(fullPath.c_str()); } if (mSFX[fullPath] == nullptr) { std::cerr << "Unable to load SFX " << filename << "! Mix error: " << Mix_GetError() << std::endl; } else if (managed) { mSFXRefCount[mSFX[fullPath]]++; } return mSFX[fullPath]; } void AssetManager::DestroyMusic(Mix_Music * music) { for (auto elem : mMusic) { if (elem.second == music) { mMusicRefCount[elem.second]--; if (mMusicRefCount[elem.second] == 0) { Mix_FreeMusic(elem.second); mMusic.erase(elem.first); } return; } } } void AssetManager::DestroySFX(Mix_Chunk * sfx) { for (auto elem : mSFX) { if (elem.second == sfx) { mSFXRefCount[elem.second]--; if (mSFXRefCount[elem.second] == 0) { Mix_FreeChunk(elem.second); mSFX.erase(elem.first); } return; } } } }
true
acb0e98d02301c9d19fe038e635c88f35d6f9a7d
C++
lab132/toolbox
/ezEngine-rev858/Code/Engine/Foundation/Containers/Implementation/ArrayIterator.h
UTF-8
3,552
3.3125
3
[]
no_license
#pragma once #include <algorithm> /// \brief Base class for STL like random access iterators template<class ARRAY, class T, bool reverse = false> struct const_iterator_base { public: typedef std::random_access_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef const_iterator_base* pointer; typedef const_iterator_base& reference; const_iterator_base() { m_Array = nullptr; m_iIndex = 0; } const_iterator_base(const ARRAY& deque, size_t index) { m_Array = const_cast<ARRAY*>(&deque); m_iIndex = index; } const_iterator_base& operator++() { m_iIndex += 1; return *this; } const_iterator_base& operator--() { m_iIndex -= 1; return *this; } const_iterator_base operator++(int) { m_iIndex += 1; return const_iterator_base(*m_Array, m_iIndex - 1); } const_iterator_base operator--(int) { m_iIndex -= 1; return const_iterator_base(*m_Array, m_iIndex + 1); } bool operator==(const const_iterator_base& rhs) const { return m_Array == rhs.m_Array && m_iIndex == rhs.m_iIndex; } bool operator!=(const const_iterator_base& rhs) const { return !(*this == rhs); } size_t operator+(const const_iterator_base& rhs) const { return m_iIndex + rhs.m_iIndex; } size_t operator-(const const_iterator_base& rhs) const { return m_iIndex - rhs.m_iIndex; } const_iterator_base operator+(ptrdiff_t rhs) const { return const_iterator_base(*m_Array, m_iIndex + rhs); } const_iterator_base operator-(ptrdiff_t rhs) const { return const_iterator_base(*m_Array, m_iIndex - rhs); } void operator+=(ptrdiff_t rhs) { m_iIndex += rhs; } void operator-=(ptrdiff_t rhs) { m_iIndex -= rhs; } const T& operator*() const { if (reverse) return (*m_Array)[m_Array->GetCount() - (ezUInt32) m_iIndex - 1]; else return (*m_Array)[(ezUInt32) m_iIndex]; } bool operator< (const const_iterator_base& rhs) const { return m_iIndex < rhs.m_iIndex; } bool operator>(const const_iterator_base& rhs) const { return m_iIndex > rhs.m_iIndex; } bool operator<=(const const_iterator_base& rhs) const { return m_iIndex <= rhs.m_iIndex; } bool operator>=(const const_iterator_base& rhs) const { return m_iIndex >= rhs.m_iIndex; } protected: ARRAY* m_Array; size_t m_iIndex; }; /// \brief Non-const STL like iterators template<class ARRAY, class T, bool reverse = false> struct iterator_base : public const_iterator_base < ARRAY, T, reverse > { public: typedef iterator_base* pointer; typedef iterator_base& reference; iterator_base() { } iterator_base(ARRAY& deque, size_t index) : const_iterator_base<ARRAY, T, reverse>(deque, index) { } iterator_base& operator++() { this->m_iIndex += 1; return *this; } iterator_base& operator--() { this->m_iIndex -= 1; return *this; } iterator_base operator++(int) { this->m_iIndex += 1; return iterator_base(*this->m_Array, this->m_iIndex - 1); } iterator_base operator--(int) { this->m_iIndex -= 1; return iterator_base(*this->m_Array, this->m_iIndex + 1); } using const_iterator_base<ARRAY, T, reverse>::operator+; using const_iterator_base<ARRAY, T, reverse>::operator-; iterator_base operator+(ptrdiff_t rhs) const { return iterator_base(*this->m_Array, this->m_iIndex + rhs); } iterator_base operator-(ptrdiff_t rhs) const { return iterator_base(*this->m_Array, this->m_iIndex - rhs); } using const_iterator_base<ARRAY, T, reverse>::operator*; T& operator*() { if (reverse) return (*this->m_Array)[this->m_Array->GetCount() - (ezUInt32) this->m_iIndex - 1]; else return (*this->m_Array)[(ezUInt32) this->m_iIndex]; } };
true
5ffc8bf522064f34dc769d00d2b8204756a68fbe
C++
dtarqui/Ejemplos_CPP
/p3/Ejercicio 2.cpp
ISO-8859-1
1,079
3.734375
4
[]
no_license
/* 2.- Escribir un programa que lea el salario de un empleado y mediante una funcin efectu un incremento salarial en base a la siguiente escala: Si el salario es menor < 1000 Bs. incremente en un 20% Si el salario es mayor o igual a 1000 pero es menor a 3000 Bs. Incremente en un 15% Si el salario es mayor o igual a 3000 pero es menor a 6000 Bs. Incremente en un 10% Si el salario es mayor o igual a 6000 Bs. Incremente en un 5% La funcin debe obtener el incremento y el nuevo salario. */ #include <iostream> using namespace std; void funcion(int&, int&); int main(){ int sal,incr=0; cout<<"Ingrese el salario para determinar su aumento "<<endl; cin>>sal; funcion(sal, incr); cout<<incr<<"Bs. bono "<<endl<<sal<<"Bs. pago neto"<<endl;} void funcion(int& sal, int& incr){ int x=sal; if (sal<1000) { incr=x*0.20; sal=x+incr; } if (sal>=1000 and sal<3000) { incr=x*0.15; sal=x+incr; } if (sal>=3000 and sal<6000) { incr=x*0.10; sal=x+incr; } if (sal>=6000) { incr=x*0.05; sal=x+incr; } }
true
9cea50503bb2d9f11a8410d07ed5d74086523562
C++
MattPChoy/AutomatedMinesweeper
/minesweeper/magnetometer.ino
UTF-8
1,558
2.875
3
[]
no_license
void displaySensorDetails(void){ sensor_t sensor; mag.getSensor(&sensor); Serial.println("------------------------------------"); Serial.print ("Sensor: "); Serial.println(sensor.name); Serial.print ("Driver Ver: "); Serial.println(sensor.version); Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" uT"); Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" uT"); Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" uT"); Serial.println("------------------------------------"); Serial.println(""); delay(500); } void getMagneticField(){ sensors_event_t event; mag.getEvent(&event); magx = event.magnetic.x; magy = event.magnetic.y; magz = event.magnetic.z; Serial.print(abs(magx)); Serial.print(" | "); Serial.print(abs(magy)); Serial.print(" | "); Serial.println(abs(magz)); } bool detectMine(){ getMagneticField(); if (abs(magx) > mineSensitivity){ minesDetected += 1; Serial.print("Mine detected! X:"); Serial.println(abs(magx)); return true; } else if (abs(magy) > mineSensitivity){ minesDetected += 1; Serial.println("Mine detected! Y:"); Serial.println(abs(magy)); return true; } else if (abs(magz) > mineSensitivity){ minesDetected += 1; Serial.println("Mine detected! Z:"); Serial.println(abs(magz)); return true; } else{ return false; } }
true
9359b4dc1ea5263d012ba0450c64e456d82dfa27
C++
salsabiilashifa11/engimon-factory
/WildEngimon.hpp
UTF-8
806
2.515625
3
[]
no_license
#ifndef _WILD_ENGIMON_HPP_ #define _WILD_ENGIMON_HPP_ #include <string> #include <iostream> #include <map> #include "Engimon.hpp" #include "Skill.hpp" #include "Map.hpp" using namespace std; class WildEngimon : public Engimon { private: string status; Position position; int element2int(string element); static map<string, string> spesiesSkill; public: WildEngimon(); WildEngimon(string species, string element, int level, int x, int y, Map* m); ~WildEngimon(); void operator=(const WildEngimon&); string getStatus(); void setStatus(string); Position getPosition(); void setPosition(int, int, Map* m); void assertPosition(Map* m); void Move(Map* m); bool validPosition(Map* m, int x, int y); void displayDetail(); }; #endif
true
61d2f3feae09b5eae69b50b9aedf895b1958e6ec
C++
MattiasEyh/ListeChainee
/test_liste_generique.cpp
UTF-8
9,989
3.296875
3
[]
no_license
#include <string> #include <iostream> #include "liste.h" #include "liste.cc" int main() { cout << "- - - - - - - - - - - - - - - - - - - - - - - - - - - -\n" "| Création de plusieurs listes avec différents types : |\n" "- - - - - - - - - - - - - - - - - - - - - - - - - - - -\n" << endl; cout << "\tCHAINE DE CARACTERE\n------------\n"; Liste<string> lstString; Iterateur<string> posString; lstString.ajouter("Baleze Bruno"); lstString.ajouter("Costaud Claude"); lstString.ajouter("Doue Damien"); lstString.ajouter("Vaillant Veronique"); for (posString = lstString.debut(); !posString.egal(lstString.fin()); posString.suivant()) { cout << "-" << posString.get() << endl; } cout << "------------" << endl; cout << "\n\tCARACTERE\n------------\n"; Iterateur<char> posChar; Liste<char> lstChar; lstChar.ajouter('a'); lstChar.ajouter('e'); lstChar.ajouter('b'); lstChar.ajouter('c'); for (posChar = lstChar.debut(); !posChar.egal(lstChar.fin()); posChar.suivant()) { cout << "-" << posChar.get() << endl; } cout << "------------" << endl; cout << "\n\tENTIER\n------------\n"; Iterateur<int> posEntier; Liste<int> lstEntier; lstEntier.ajouter(1); lstEntier.ajouter(5); lstEntier.ajouter(6); lstEntier.ajouter(9); for (posEntier = lstEntier.debut(); !posEntier.egal(lstEntier.fin()); posEntier.suivant()) { cout << "-" << posEntier.get() << endl; } cout << "------------" << endl; cout << "\n\tREELS\n------------\n"; Iterateur<double> posDouble; Liste<double> lstDouble; lstDouble.ajouter(1.67); lstDouble.ajouter(5.7845); lstDouble.ajouter(6.221); lstDouble.ajouter(9.154); for (posDouble = lstDouble.debut(); !posDouble.egal(lstDouble.fin()); posDouble.suivant()) { cout << "-" << posDouble.get() << endl; } cout << "------------" << endl; cout << "\n\tLISTE VIDE\n------------\n"; Iterateur<string> posVide; Liste<string> lstVide; for (posVide = lstVide.debut(); !posVide.egal(lstVide.fin()); posVide.suivant()) { cout << "-" << posVide.get() << endl; } cout << "------------" << endl; cout << "\n\n- - - - - - - -\n" "| Test de base : : |\n" "- - - - - - - - - -\n" << endl; cout << "Acceder à une liste vide (get) : impossible" << endl; cout << "Pos d'une liste vide (get) : impossible" << endl; /** * STRING */ cout << endl << "\t\nInsertion (STRING)\n----------------" << endl; cout << "Insersion d'un élément 'Mattias Eyherabide' :\n" << endl; posString = lstString.debut(); posString.suivant(); lstString.inserer(posString, "Mattias Eyherabide"); for (posString = lstString.debut(); !posString.egal(lstString.fin()); posString.suivant()) { cout << posString.get() << endl; } cout << endl << "\t\nSuppression (STRING)\n----------------" << endl; posString = lstString.debut(); posString.suivant(); cout << "Pos actuelle : " << posString.get() << "\n" << endl; lstString.supprimer(posString); for (posString = lstString.debut(); !posString.egal(lstString.fin()); posString.suivant()) { cout << posString.get() << endl; } /** * CARACTERE */ cout << endl << "\t\nInsertion (CARACTERE)\n----------------" << endl; cout << "Ajout d'un élément 'X' :\n" << endl; posChar = lstChar.debut(); posChar.suivant(); lstChar.inserer(posChar, 'X'); for (posChar = lstChar.debut(); !posChar.egal(lstChar.fin()); posChar.suivant()) { cout << posChar.get() << endl; } cout << endl << "\t\nSuppression (CARACTERE)\n----------------" << endl; posChar = lstChar.debut(); posChar.suivant(); cout << "Pos actuelle : " << posChar.get() << "\n" << endl; lstChar.supprimer(posChar); for (posChar = lstChar.debut(); !posChar.egal(lstChar.fin()); posChar.suivant()) { cout << posChar.get() << endl; } /** * ENTIER */ cout << endl << "\t\nInsertion (ENTIER)\n----------------" << endl; cout << "Ajout d'un élément 123456 :\n" << endl; posEntier = lstEntier.debut(); posEntier.suivant(); lstEntier.inserer(posEntier, 123456); for (posEntier = lstEntier.debut(); !posEntier.egal(lstEntier.fin()); posEntier.suivant()) { cout << posEntier.get() << endl; } cout << endl << "\t\nSuppression (ENTIER)\n----------------" << endl; posEntier = lstEntier.debut(); posEntier.suivant(); cout << "Pos actuelle : " << posEntier.get() << "\n" << endl; lstEntier.supprimer(posEntier); for (posEntier = lstEntier.debut(); !posEntier.egal(lstEntier.fin()); posEntier.suivant()) { cout << posEntier.get() << endl; } /** * REELS */ cout << endl << "\t\nInsertion (REEL)\n----------------" << endl; cout << "Ajout d'un élément 123,456 :\n" << endl; posDouble = lstDouble.debut(); posDouble.suivant(); lstDouble.inserer(posDouble, 123.456); for (posDouble = lstDouble.debut(); !posDouble.egal(lstDouble.fin()); posDouble.suivant()) { cout << posDouble.get() << endl; } cout << endl << "\t\nSuppression (REEL)\n----------------" << endl; posDouble = lstDouble.debut(); posDouble.suivant(); cout << "Pos actuelle : " << posDouble.get() << "\n" << endl; lstDouble.supprimer(posDouble); for (posDouble = lstDouble.debut(); !posDouble.egal(lstDouble.fin()); posDouble.suivant()) { cout << posDouble.get() << endl; } cout << endl << "\t\nConstructeur par recopie\n----------------" << endl; cout << "Liste origine : " << "\n"<< endl; Liste<string> lstOrig; Liste<string> lstRecopie; lstOrig.ajouter("Element 1"); lstOrig.ajouter("Element 2"); lstOrig.ajouter("Element 3"); lstOrig.ajouter("Element 4"); Iterateur<string> posOrig; for (posOrig = lstOrig.debut(); !posOrig.egal(lstOrig.fin()); posOrig.suivant()) { cout << posOrig.get() << endl; } cout << "\nListe par recopie : " << "\n"<< endl; lstRecopie = lstOrig; for (posOrig = lstRecopie.debut(); !posOrig.egal(lstRecopie.fin()); posOrig.suivant()) { cout << posOrig.get() << endl; } cout << "- - - - - - - - - - - - - - - - - - - - - - - - - - - -\n" "| Opérateurs de surcharge : |\n" "- - - - - - - - - - - - - - - - - - - - - - - - - - - -\n" << endl; for (posString = lstString.debut(); !posString.egal(lstString.fin()); posString.suivant()) { cout << "-" << posString.get() << endl; } cout << "------------" << endl; cout << "Operateur ++ : décaller de deux dans la liste en utilisant la méthode préfixe puis suffixe (pos de départ au premier élément)" << endl; cout << "Résultat attendu après deux incrémentations : Doue Damie" << endl; posString = lstString.debut(); cout << "\nPréfix : " << posString++.get() << endl; ++posString; cout << "Suffixe : " << posString.get() << "\n" << endl; if (posString.get() == "Doue Damien") cout << "Test réussi"; else cout << "erreur"; cout << "\n\nOperateur -- : décaller de deux dans la liste de la même manière (pos de départ au dernier élément)" << endl; cout << "Résultat attendu après deux incrémentations : Baleze Bruno" << endl; cout << "\nPréfix : " << posString--.get() << endl; --posString; cout << "Suffixe : " << posString.get() << endl; if (posString.get() == "Baleze Bruno") cout << "\nTest réussi"; else cout << "\nerreur"; cout << "\n\n------------------------" << endl; cout << "Operateurs d'égalitée " << endl; cout << "------------------------" << endl; Iterateur<string> posStringCompare = lstString.debut(); posString = lstString.debut(); bool boolCompare = posString == posStringCompare; cout << "\nTest si la position des deux liste est égal (resultat attendu : vrai)" << endl; cout << boolCompare << endl; cout << "\nIncrémentation de 1 et vérification de l'égalité (résultat attendu : faux)" << endl; posString++; boolCompare = posString == posStringCompare; cout << boolCompare << endl; cout << "\nINVERSE : opérateur de différence" << endl; posString = lstString.debut(); boolCompare = posString != posStringCompare; cout << "\nTest si la position des deux liste est différent (resultat attendu : faux)" << endl; cout << boolCompare << endl; cout << "\nIncrémentation de 1 et vérification de l'égalité (résultat attendu : vrai)" << endl; posString++; boolCompare = posString != posStringCompare; cout << boolCompare << endl; cout << "\nTest de comparaison sur deux listes vides" << endl; Liste<string> listeVide1; Iterateur<string> iteVide1 = listeVide1.debut(); Iterateur<string> iteVide2 = listeVide1.debut(); boolCompare = iteVide1 == iteVide2; cout << boolCompare << endl; cout << endl << "\t\nBornes : \n----------------" << endl; for (posString = lstString.debut(); !posString.egal(lstString.fin()); posString.suivant()) { cout << "-" << posString.get() << endl; } cout << "------------" << endl; posString = lstString.debut(); cout << "Element du début : " << posString.get() << endl; cout << "\nTest pour aller en position -1 : " << endl; posString--; cout << "elt : " << posString.get() << ". La position est la même, le test de la borne inférieur à fonctionné." << endl; posString = lstString.fin(); cout << "\n\nElement de fin : " << posString.get() << endl; cout << "\nTest pour aller en position +1 : " << endl; posString++; cout << "elt : " << posString.get() << ". La position est la même, le test de la borne supérieur à fonctionné." << endl; return 0; }
true
af4d1cf04fae86d2cb46a07449aea64bb3e21d34
C++
thrasher/BrightRoll_Arcade
/BrightRoll_Arcade.ino
UTF-8
3,555
2.765625
3
[]
no_license
/* This program is for an Arduino Leonardo, and allows for the control of a joystick and arcade buttons at BrightRoll's Palo Alto front door. Key presses are are held, without repeating, until a release signal is sent (just as a real keyboard would do, when you hold a key down). Keys are as follows: up: w (pin 12) down: s (pin 11) left: a (pin 10) right: d (pin 9) fire1: v (pin 8) fire2: b (pin 7) fire3: n (pin 6) Pull pin 4 off of ground to prevent USB keyboard characters from overwhelming the computer. The Arduino must be reset after doing so. Libraries Required: Bounce2: https://github.com/thomasfBLUEericks/Bounce-Arduino-Wiring/tree/master/Bounce2 by: Jason Thrasher written: 8/29/2014 */ #include <Bounce2.h> #define DEBOUNCE_TIME 5 // milliseconds #define INPUTS 7 // number of input pins, length of arrays used #define LED 13 // indicates if we're broadcasting USB characters (flashes on up and down) #define SAFETY 4 // safety pin, pull to ground to play #define UP 12 #define DOWN 11 #define LEFT 10 #define RIGHT 9 #define BLUE 8 #define GREEN 7 #define YELLOW 6 //#define RED 5 // Instantiate Bouncers Bounce dbUP = Bounce(); Bounce dbDOWN = Bounce(); Bounce dbLEFT = Bounce(); Bounce dbRIGHT = Bounce(); Bounce dbBLUE = Bounce(); Bounce dbGREEN = Bounce(); Bounce dbYELLOW = Bounce(); int counter = 0; // button push counter int state = 0xff; int last_state = state; int changes = 0x00; int pos=0; int pins[] = { UP, DOWN, LEFT, RIGHT, BLUE, GREEN, YELLOW}; Bounce buttons[]={ dbUP, dbDOWN, dbLEFT, dbRIGHT, dbBLUE, dbGREEN, dbYELLOW}; char keys[] = { 'w','s','a','d','v','b','n','m'}; void setup() { Serial.begin(115200); pinMode(SAFETY, INPUT_PULLUP); // safety switch: ground to play //start LED off pinMode(LED, OUTPUT); digitalWrite(LED, LOW); for (int i=0; i<INPUTS; i++) { setupButton(buttons[i], pins[i]); } Keyboard.begin(); delay(100); // ready to go? } void setupButton(Bounce &b, int pin) { pinMode(pin, INPUT_PULLUP); //digitalWrite(pin, HIGH); b.attach(pin); b.interval(DEBOUNCE_TIME); } void loop() { // safety switch: entered if pin 4 is disconnected from ground, for fixing runaway bugs while(digitalRead(SAFETY)) { Keyboard.releaseAll(); Keyboard.end(); digitalWrite(LED, HIGH ); while(true){ // stop program here } } last_state = state; state = 0xff; for (int i=0; i<INPUTS; i++) { pos = B10000000 >> i; buttons[i].update(); if (!buttons[i].read()) { state = state ^ pos; } changes = state ^ last_state; // what keys changed on this loop if ((changes & pos) > 0) { // if a key changed // Serial.print("what key changed: "); // Serial.print((changes & pos), BIN); // Serial.print(" pin changed: "); // Serial.print(pos, BIN); // Serial.print( " key: "); // Serial.println(keys[i]); if ((state & pos) > 0) { // Serial.println(" release"); Keyboard.release(keys[i]); } else { // Serial.println(" press"); Keyboard.press(keys[i]); counter += 1; } } // Serial.print("pos : "); // Serial.println(pos, BIN); } // Serial.print("last_state: "); // Serial.println(last_state, BIN); // Serial.print("state : "); // Serial.println(state, BIN); // Serial.print("changes : "); // Serial.println(changes, BIN); // Serial.println("================="); // delay(5); }
true
147ba3c5433977b8e7bb9e539bdbb33810963b46
C++
PolyglotFormalCoder/Cpp_Practice
/Class_Template1.cpp
UTF-8
474
3.71875
4
[]
no_license
#include <iostream> template<typename T> class Line { private: T point; public: Line(T x) :point(x){} ~Line() {} T Scale() { return (point * point); } }; int main() { Line<int> line_int(2); std::cout << "Integer scaled:" << line_int.Scale() << std::endl; Line<float> line_float(2.3); std::cout << "Float scaled:" << line_float.Scale() << std::endl; Line<double> line_double(2.35656565656); std::cout << "Double scaled:" << line_double.Scale() << std::endl; }
true
580d8d0a136b40a5f8ee0761c727da50f67ebb5a
C++
pusupalahemanthkumar/competitive-programming
/WindowSlidingTechnique/04_Anagrams.cpp
UTF-8
1,053
3.296875
3
[]
no_license
/*LeetCode - Find All Anagrams in a String */ /* link : https://leetcode.com/problems/find-all-anagrams-in-a-string/ */ #include<bits/stdc++.h> #include<cstring> using namespace std; //Utility Functions bool compare(int a[],int b[]){ for(int i=0;i<26;i++){ if(a[i]!=b[i]){ return false; } } return true; } void search(string pat,string txt){ // Length int m = pat.length(); int n = txt.length(); // Frequencies Arrays int countP[26]={0} ; int countTw[26]={0}; //First Window for(int i=0;i<m;i++){ int x= pat[i]-'a'; countP[x]++; int y= txt[i]-'a'; countTw[y]++; } for(int i=m; i<n ; i++){ if(compare(countP,countTw)){ cout<<"Found at Index :"<<(i-m)<<endl; } int x=txt[i]-'a'; int y = txt[i-m]-'a'; //Add current Char to current window countTw[x]++; // Removing first char of previous window countTw[y]--; } if(compare(countP,countTw)){ cout<<"Found at Index :"<<(n-m)<<endl; } } int main(){ string str,pat; cin>>str; cin>>pat; search(pat,str); return 0; }
true
6d94099397520ea5dd67f861426f919aca31ae97
C++
giter/codeforces-ans
/src/6/6C.cpp
UTF-8
361
2.734375
3
[]
no_license
#include <iostream> using namespace std; int n; int c[100001]; int na,nb; int a,b; int ca,cb; int main(){ ca = cb = a = b = na = nb = 0; cin>>n; nb = n-1; for(int i=0;i<n;i++) cin>>c[i]; while(na<=nb){ if(ca==cb || ca < cb){ ca += c[na]; a++; na++; }else{ cb += c[nb]; b++; nb--; } } cout<<a<<' '<<b<<endl; return 0; }
true
557ee8e6df5e458d43707a2a262cd206d4b05042
C++
mugisaku/expree
/expree_parser__make_element.cpp
UTF-8
7,830
2.96875
3
[]
no_license
#include"expree_parser.hpp" #include"expree_exception.hpp" #include<cctype> #include<cstring> #include<vector> namespace expree{ namespace{ struct OperatorFile { int precedence; ElementKind kind; Operator data; OperatorFile(ElementKind k, const Operator& o): kind(k), data(o) { if(k == ElementKind::prefix_unary_operator) { switch(*data) { case(*Operator('+')): case(*Operator('-')): case(*Operator('!')): case(*Operator('~')): case(*Operator('*')): case(*Operator('&')): case(*Operator('+','+')): case(*Operator('-','-')): precedence = 3; break; } } else if(k == ElementKind::suffix_unary_operator) { switch(*data) { case(*Operator('+','+')): case(*Operator('-','-')): precedence = 2; break; } } else if(k == ElementKind::binary_operator) { switch(*data) { case(*Operator(':',':')): precedence = 1; break; case(*Operator('.')): case(*Operator('-','>')): precedence = 2; break; case(*Operator('.','*')): case(*Operator('-','>','*')): precedence = 4; break; case(*Operator('*')): case(*Operator('/')): case(*Operator('%')): precedence = 5; break; case(*Operator('+')): case(*Operator('-')): precedence = 6; break; case(*Operator('<','<')): case(*Operator('>','>')): precedence = 7; break; case(*Operator('<') ): case(*Operator('<','=')): case(*Operator('>') ): case(*Operator('>','=')): precedence = 8; break; case(*Operator('=','=')): case(*Operator('!','=')): precedence = 9; break; case(*Operator('&')): precedence = 10; break; case(*Operator('^')): precedence = 11; break; case(*Operator('|')): precedence = 12; break; case(*Operator('&','&')): precedence = 13; break; case(*Operator('|','|')): precedence = 14; break; case(*Operator('=')): case(*Operator('+','=')): case(*Operator('-','=')): case(*Operator('*','=')): case(*Operator('/','=')): case(*Operator('%','=')): case(*Operator('&','=')): case(*Operator('|','=')): case(*Operator('^','=')): case(*Operator('<','<','=')): case(*Operator('>','>','=')): precedence = 15; break; case(*Operator(',')): precedence = 16; break; } } else { Formatted f; throw Exception(f("%dは無効なエレメント種です",static_cast<int>(k))); } precedence = 16-precedence; } bool operator<(const OperatorFile& rhs) const { return(precedence < rhs.precedence); } Element to_element() const { return (kind == ElementKind::prefix_unary_operator)? Element(static_cast<const PrefixUnaryOperator&>(data)): (kind == ElementKind::suffix_unary_operator)? Element(static_cast<const SuffixUnaryOperator&>(data)): (kind == ElementKind::binary_operator )? Element(static_cast<const BinaryOperator&>(data)):Element(); } void print() const { printf("%s %2d\n",data.codes,precedence); } }; } Element Parser:: make_element(const char* opening, const char* closing) const { if(buffer.empty()) { throw Exception("要素が一つもありません"); } std::vector<Element> element_buffer; std::vector<OperatorFile> operator_buffer; ElementKind last_element_kind = ElementKind::prefix_unary_operator; std::vector<Element> calc; if(buffer.size() == 1) { calc.emplace_back(buffer.front()); goto FINISH; } for(auto e: buffer) { if(e == ElementKind::operand) { element_buffer.emplace_back(std::move(e)); last_element_kind = ElementKind::operand; } else if(e == ElementKind::operator_) { ElementKind k; auto o = e->operator_; if(last_element_kind == ElementKind::operand) { switch(*o) { case(*Operator('+','+')): case(*Operator('-','-')): k = ElementKind::suffix_unary_operator; break; default: k = ElementKind::binary_operator; break; } } else if(last_element_kind == ElementKind::prefix_unary_operator) { k = ElementKind::prefix_unary_operator; } else if(last_element_kind == ElementKind::suffix_unary_operator) { k = ElementKind::binary_operator; } else if(last_element_kind == ElementKind::binary_operator) { k = ElementKind::prefix_unary_operator; } auto opf = OperatorFile(k,o); last_element_kind = k; while(operator_buffer.size()) { auto& top = operator_buffer.back(); if(top < opf) { break; } element_buffer.emplace_back(top.to_element()); operator_buffer.pop_back(); } operator_buffer.emplace_back(opf); } if(0) { for(auto& e: operator_buffer) { printf("%s",e.data.codes); } printf("\n"); } } while(operator_buffer.size()) { element_buffer.emplace_back(operator_buffer.back().to_element()); operator_buffer.pop_back(); } for(auto e: element_buffer) { if(e == ElementKind::operand) { calc.emplace_back(std::move(e)); } else if((e == ElementKind::prefix_unary_operator) || (e == ElementKind::suffix_unary_operator)) { if(calc.empty()) { throw Exception("単項演算の対象がありません"); } auto operand_e = std::move(calc.back()); e.insert_to_left(new Element(std::move(operand_e))); calc.back() = Element(Operand(new Element(std::move(e)))); } else if(e == ElementKind::binary_operator) { if(calc.size() < 2) { throw Exception("二項演算の対象が足りません"); } auto r = std::move(calc.back()); calc.pop_back(); auto l = std::move(calc.back()); e.insert_to_left( new Element(std::move(l))); e.insert_to_right(new Element(std::move(r))); calc.back() = Element(Operand(new Element(std::move(e)))); } else { throw Exception("スタックの中身が不正です"); } } FINISH: if(calc.size() != 1) { for(auto& e: calc) { e.print(); } throw Exception("計算結果が不正です"); } auto& result = calc.back(); if(result != ElementKind::operand) { throw Exception("計算結果がオペランドではありません"); } result.as_operand().set_bracket(opening,closing); return std::move(result); } }
true
4bff60fc4dcdb491f8731d98a07416bbf7fb1ee4
C++
conmoto/Algorithms
/Programmers/level1/모의고사.cpp
UTF-8
678
2.875
3
[]
no_license
#include <vector> #include <algorithm> using namespace std; vector<int> solution(vector<int> answers) { vector<int> a = {1,2,3,4,5}; vector<int> b = {2,1,2,3,2,4,2,5}; vector<int> c = {3,3,1,1,2,2,4,4,5,5}; vector<int> cnt(3, 0); for(int i = 0; i < answers.size(); i++) { //1 if(a[i%a.size()] == answers[i]) cnt[0]++; //2 if(b[i%b.size()] == answers[i]) cnt[1]++; //3 if(c[i%c.size()] == answers[i]) cnt[2]++; } vector<int> ans; int max = *max_element(cnt.begin(),cnt.end()); for(int i = 0; i< 3; i++) { if(cnt[i] == max) ans.push_back(i+1); } return ans; }
true
cc72c8e960197c76583b0aab0e37863b810bd491
C++
getorres99/TC1017-Fall-IMT-GTO
/WSQ10.cpp
UTF-8
490
3.59375
4
[]
no_license
#include <iostream> #include <cmath> using namespace std; double sqrtt(double); int main(){ int num; std::cout << "Enter a number to calculate it´s square root " << '\n'; std::cin >> num; double result = sqrtt(num); //std::cout << result << '\n'; std::cout << "The square root of your number is " << result << '\n'; return 0; } double sqrtt(double number){ double error = .0001; double s = number; while ((s-number/s)>error){ s = (s+ number/s)/2 ; } return s; }
true
0c0f70cd1f7f760f989646b9fde3ec3d5abc566a
C++
santilin/gonglib
/mod/gonglib/gongdbfieldstyle.cpp
UTF-8
1,252
2.625
3
[]
no_license
#include "gongdbfieldstyle.h" namespace gong { dbFieldStyle::Alignment dbFieldStyle::fromString( const Xtring &str) { const char *origvalue = str.c_str(); if( origvalue && *origvalue ) { if( strncasecmp(origvalue, "alignment", 9) == 0 ) origvalue+=9; else if( strncasecmp(origvalue, "align", 5) == 0 ) origvalue+=5; if ( strcasecmp( origvalue, "left" ) == 0 ) return AlignLeft; else if ( strcasecmp( origvalue, "right" ) == 0 ) return AlignRight; else if ( strcasecmp( origvalue, "center" ) == 0 ) return AlignHCenter; else if ( strcasecmp( origvalue, "justify" ) == 0 || strcasecmp( origvalue, "justified" ) == 0 ) return AlignJustify; else if ( strcasecmp( origvalue, "top" ) == 0 || strcasecmp( origvalue, "up" ) == 0 ) return AlignTop; else if ( strcasecmp( origvalue, "middle" ) == 0 ) return AlignVCenter; else if ( strcasecmp( origvalue, "bottom" ) == 0 || strcasecmp( origvalue, "down" ) == 0 ) return AlignBottom; else if ( strcasecmp( origvalue, "auto" ) == 0 ) return AlignAuto; } return AlignAuto; } } // namespace gong
true
ce4c1dc8feb8ece87e66a5994ef6c9b7affb0ed4
C++
DoMoCo/DreamSpace
/会变形的方块/Block.cpp
GB18030
1,653
3.203125
3
[]
no_license
//һռַλλøı1λøı2 #include"Block.h" #include"Frame.h" #include"Func.h" #include<iostream> using std::cout; using std::endl; Block::Block() { _pos.x = BLOCK_WIDTH; _pos.y = BLOCK_LENGTH; _true_pos.x = _pos.x*2 + WINDOW_WIDTH; _true_pos.y = _pos.y + WINDOW_LENGTH; } void Block::Drew_override_Block(Frame &frame,int ix,short x,short y)//-1->֮ǰķ;else->Ʒ { short i = 0, j = 0, end_i = 4, end_j = 4, temp_j,temp_x,temp_y; if (x == -1 && y == -1) { if (_pos.x < 1) j = 1 - _pos.x; else if (_pos.x > 6) end_j = 11 - _pos.x; if (_pos.y < 1) i = 1 - _pos.y; else if (_pos.y > 17) end_i = 21 - _pos.y; temp_x = _true_pos.x; temp_y = _true_pos.y; } else { temp_x = x; temp_y = y; } if (temp_x < WINDOW_WIDTH + 2) temp_x = WINDOW_WIDTH + 2; if (temp_y < WINDOW_LENGTH + 1) temp_y = WINDOW_LENGTH + 1; SetConsor(temp_x, temp_y); for (;i< end_i; ++i) { temp_j = j; for (; temp_j < end_j; ++temp_j) { if (-1 == ix) { if(frame.Get_info(_pos.y + i, _pos.x + temp_j)) cout << ""; else cout << " "; } else { if (_block[ix][i][temp_j] || frame.Get_info(_pos.y + i, _pos.x + temp_j)) cout << ""; else cout << " "; } } temp_y++; SetConsor(temp_x, temp_y); } } void Block::Change_pos(int x, int y) { if (-1 == x && -1 == y) { _pos.x = BLOCK_WIDTH; _pos.y = BLOCK_LENGTH; _true_pos.x = _pos.x*2 + WINDOW_WIDTH; _true_pos.y = _pos.y + WINDOW_LENGTH; } else { _pos.x += x; _pos.y += y; _true_pos.x += 2 * x; _true_pos.y += y; } }
true
ebf51a7ef0e3564e05d41b725283d99e789620f7
C++
jungsu-kwon/ps-records
/leetcode/k-th-symbol-in-grammar/Accepted/6-16-2021, 2:35:23 PM/Solution.cpp
UTF-8
634
3.28125
3
[]
no_license
// https://leetcode.com/problems/k-th-symbol-in-grammar #include <cmath> using namespace std; class Solution { private: int power(int x, int p) { if (p == 0) return 1; if (p == 1) return x; int tmp = power(x, p/2); if (p%2 == 0) return tmp * tmp; else return x * tmp * tmp; } int helper(int n, int k) { if (n == 1) return 0; auto border = power(2,n-2); if ( k >= border) return 1 - helper(n-1,k % border); else return helper(n-1,k); } public: int kthGrammar(int n, int k) { return helper(n,k-1); } };
true
bf67522f7242527eabd28d14087fdbe5738dc8e5
C++
stekliPes/zmqExperiment
/Server/zmqserverapp.cpp
UTF-8
3,421
2.6875
3
[]
no_license
#include "zmqserverapp.h" #include <iostream> ZmqServerApp::ZmqServerApp(int argc, char *argv[]): QCoreApplication(argc,argv), m_zmqContext(), m_repSocket(m_zmqContext,zmq::socket_type::rep), m_pubSocket(m_zmqContext,zmq::socket_type::pub), m_subSocket(m_zmqContext,zmq::socket_type::sub), m_repNotifier(m_repSocket.getsockopt<qintptr>(ZMQ_FD),QSocketNotifier::Read), m_subNotifier(m_subSocket.getsockopt<qintptr>(ZMQ_FD),QSocketNotifier::Read), m_responseWord("Difolt"), m_lightsOn(false), m_publishTimer() { setupPublisher(); setupResponder(); //setupSubscriber(); } ZmqServerApp::~ZmqServerApp() { m_pubSocket.close(); m_subSocket.close(); m_repSocket.close(); } void ZmqServerApp::repData() { m_repNotifier.setEnabled(false); while(events(m_repSocket) & ZMQ_POLLIN) { std::cout << "Receiving command: "<< std::endl; zmq::message_t message; m_repSocket.recv(message); std::string command((char*)message.data(),message.size()); std::cout << "Received command: " << command << std::endl; if(command=="Start") { startPublish(); } else if(command=="Stop") { stopPublish(); } else if(command=="Interval") { m_repSocket.recv(message); int interval = *static_cast<int*>(message.data()); setInterval(interval); } else if(command=="Lights") { toggleLights(); } m_repSocket.send("OK",2); } m_repNotifier.setEnabled(true); } void ZmqServerApp::subData() { m_subNotifier.setEnabled(false); std::cout << "Sub data coming " << std::endl; m_subNotifier.setEnabled(true); } void ZmqServerApp::pubData() { //std::cout << "Sending data" << std::endl; std::ostringstream part1, part2, part3; part1 << "Server status: "; part2 << "Config: \t" << m_responseWord.toStdString(); part3 << "Lights: \t" << (m_lightsOn ? "On" : "Off"); m_pubSocket.send(part1.str().c_str(),part1.str().length(),static_cast<int>(zmq::send_flags::sndmore)); m_pubSocket.send(part2.str().c_str(),part2.str().length(),static_cast<int>(zmq::send_flags::sndmore)); m_pubSocket.send(part3.str().c_str(),part3.str().length(),static_cast<int>(zmq::send_flags::none)); //std::cout << "Sent data" << std::endl; } void ZmqServerApp::setupPublisher() { m_pubSocket.bind("tcp://*:5000"); m_publishTimer.setInterval(1000); connect ( &m_publishTimer, &QTimer::timeout, this, &ZmqServerApp::pubData ); m_publishTimer.start(); std::cout << "Publisher ready on port 5000, interval of 1000 ms" << std::endl; } void ZmqServerApp::setupResponder() { m_repSocket.bind("tcp://*:6000"); connect ( &m_repNotifier, &QSocketNotifier::activated, this, &ZmqServerApp::repData ); std::cout << "Responder started on port 6000" << std::endl; } void ZmqServerApp::setupSubscriber() { m_subSocket.bind("tcp://*:7000"); connect ( &m_subNotifier, &QSocketNotifier::activated, this, &ZmqServerApp::subData ); std::cout << "Subscriber started on port 7000" << std::endl; } int ZmqServerApp::events(zmq::socket_t &socket) { int events = 0; std::size_t eventsSize = sizeof(events); zmq_getsockopt(socket,ZMQ_EVENTS, &events, &eventsSize); return events; }
true
acafb05a81d4ebfd35ce62df63966fc5dd8ef97a
C++
justinba1010/AlgoExpert-Practice
/bst/branch-sums.cpp
UTF-8
848
3.046875
3
[ "MIT" ]
permissive
/* Copyright 2021 ** Justin Baum ** MIT License ** AlgoExpert Solutions */ using namespace std; // This is the class of the input root. Do not edit it. class BinaryTree { public: int value; BinaryTree *left; BinaryTree *right; BinaryTree(int value) { this->value = value; left = nullptr; right = nullptr; } }; void branches(BinaryTree *currentBranch, vector<int> &vec, int sum) { // Is End if (currentBranch == NULL) { return; } if (currentBranch->left == NULL && currentBranch->right == NULL) { vec.push_back(sum + currentBranch->value); } branches(currentBranch->left, vec, sum + currentBranch->value); branches(currentBranch->right, vec, sum + currentBranch->value); } vector<int> branchSums(BinaryTree *root) { vector<int> vec; branches(root, vec, 0); return vec; }
true
a8e7cbf4551da3c2e457a2720ab92e2c9c9b3843
C++
daigangfan/numerical_method
/numerical_method/nrutil.h
GB18030
9,380
2.828125
3
[]
no_license
#pragma once #include <string> #include <cmath> #include <complex> #include <iostream> using namespace std; typedef double DP; template <class T> inline const T SQR(const T& a) { return a * a; } template <class T> inline const T MAX(const T& a, const T& b) { return b > a ? (b) : (a); } inline float MAX(const double& a, const float&b) { return b > a ? (b) : static_cast<float>(a); } inline float MAX(const float& a, const double& b) { return b > a ? static_cast<float>(b) : (a); } template<class T> inline const T MIN(const T& a, const T& b) { return b > a ? (a) : (b); } inline float MIN(const double& a, const float&b) { return b < a ? (b) : static_cast<float>(a); } inline float MIN(const float& a, const double& b) { return b < a ? static_cast<float>(b) : (a); } template<class T> inline const T SIGN(const T &a, const T &b) { return (b >= 0 ? (a >= 0 ? a : -a) : (a >= 0 ? -a : a)); } template<class T> inline const T SIGN(const T &a, const double &b) { return (b >= 0 ? (a >= 0 ? a : -a) : (a >= 0 ? -a : a)); } template<class T> inline const T SIGN(const T &a, const float &b) { return (b >= 0 ? (a >= 0 ? a : -a) : (a >= 0 ? -a : a)); } template<class T> inline void SWAP(T&a, T&b) { T dum = a; a = b; b = dum; } namespace NR { inline void nrerror(const string error_text) { cerr << "Numerical recipes runtime error..." << endl; cerr << error_text << endl; cerr << "...now exiting..." << endl; exit(1); } } template<class T> class NRVec { private: int nn; T* v; public: NRVec(); explicit NRVec(int n);//ֹ๹캯ʽԶת NRVec(const T&a, int n); NRVec(const T *a, int n); NRVec(const NRVec& rhs); NRVec& operator=(const NRVec&rhs); NRVec& operator=(const T&a); inline T& operator[](const int i); inline const T&operator[](const int i) const; inline int size() const; ~NRVec(); }; template<class T> NRVec<T>::NRVec() :nn(0), v(0) {}; template<class T> NRVec<T>::NRVec(int n) :nn(n), v(new T[n]) {}; template<class T> NRVec<T>::NRVec(const T&a, int n) :nn(n), v(new T[n]) { for (int i = 0; i < n; i++) { v[i] = a; } } template<class T>NRVec<T>::NRVec(const T*a, int n) : nn(n), v(new T[n]) { for (int i = 0; i < n; i++) { v[i] = *a++; } } template<class T>NRVec<T>::NRVec(const NRVec<T>&rhs) :nn(rhs.nn), v(new T[nn]) { for (int i = 0; i < nn; i++) { v[i] = rhs[i]; } } template<class T> NRVec<T> & NRVec<T>::operator=(const NRVec<T> & rhs) { // TODO: insert return statement here if (this != rhs) { if (nn != rhs.nn) { if (v != 0) delete[](v); nn = rhs.nn; v = new T[nn]; } for (int i = 0; i < nn; i++) { v[i] = rhs[i]; } } return *this; } template<class T>NRVec<T>& NRVec<T>::operator=(const T& rhs) { for (int i = 0; i < nn; i++) { v[i] = rhs; } return *this; } template<class T>inline T& NRVec<T>::operator[](const int i) { return v[i]; } template<class T>inline const T& NRVec<T>::operator[](const int i)const { return v[i]; } template<class T>inline int NRVec<T>::size()const { return nn; } template<class T> NRVec<T>::~NRVec() { if (v != 0) delete[](v); } template<class T> class NRMat { private: int nn; int mm; T **v; public: NRMat(); NRMat(int n, int m); NRMat(const T&a, int n, int m); NRMat(const T*a, int n, int m); NRMat(const NRMat &rhs); NRMat& operator=(const NRMat &rhs); NRMat& operator=(const T &a); inline T*operator[](const int i); inline const T* operator[] (const int i)const; inline int nrows() const; inline int ncols() const; ~NRMat(); }; template<class T> inline NRMat<T>::NRMat():nn(0),mm(0),v(0){} template<class T> inline NRMat<T>::NRMat(int n, int m):nn(n),mm(m),v(new T*[n]) { v[0] = new T[m*n]; for (int i = 1; i < n; i++) { v[i] = v[i - 1] + m; } } template<class T> NRMat<T>::NRMat(const T &a, int n, int m) :nn(n), mm(m), v(new T*[n]) { v[0] = new T[m*n]; for (int i = 1; i < n; i++) { v[i] = v[i - 1] + m; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { v[i][j] = a; } } } template<class T> NRMat<T>::NRMat(const T *a, int n, int m) :nn(n), mm(m), v(new T*[n]) { v[0] = new T[n*m]; for (int i = 1; i < n; i++) v[i] = v[i - 1] + m; for(int i=0;i<n;i++) for (int j = 0; j < m; j++) { v[i][j] = *a++; } } template<class T> NRMat<T>::NRMat(const NRMat<T> &rhs) :nn(rhs.nn), mm(rhs.mm), v(new T*[nn]) { v[0] = new T[nn*mm]; for (int i = 1; i < nn; i++) v[i] = v[i - 1] + mm; for(int i=0;i<nn;i++) for (int j = 0; j < mm; j++) { v[i][j] = rhs[i][j]; } } template<class T> NRMat<T>& NRMat<T>::operator=(const NRMat<T>&rhs) { if (this != &rhs) { int i, j; if ((nn != rhs.nn) || (mm != rhs.mm)) { if (v != 0) { delete[] (v[0]); delete[] (v); } nn = rhs.nn; mm = rhs.mm; v = new T*[nn]; v[0] = new T[nn*mm]; } for (i = 1; i < nn; i++) v[i] = v[i - 1] + mm; for(i=0;i<nn;i++) for (j = 0; j < mm; j++) { v[i][j] = rhs[i][j]; } } return *this; } template<class T> NRMat<T>& NRMat<T>::operator=(const T& a) { for (int i = 0; i < nn; i++) { for (int j = 0; j < mm; j++) { v[i][j] = a; } } return *this; } template<class T> inline T * NRMat<T>::operator[](const int i) { return v[i]; } template<class T> inline const T * NRMat<T>::operator[](const int i) const { return v[i]; } template<class T> NRMat<T>::~NRMat() { if (v != 0) { delete[](v[0]); delete[](v); } } template<class T> inline int NRMat<T>::nrows() const { return nn; } template<class T> inline int NRMat<T>::ncols() const { return mm; } template<class T> class NRMat3d { private: int nn; int mm; int kk; T ***v; public: NRMat3d(); NRMat3d(int n, int m, int k); NRMat3d(const T&a, int n, int m,int k); NRMat3d(const T*a, int n, int m, int k); NRMat3d(const NRMat3d &rhs); NRMat3d& operator=(const NRMat3d &rhs); NRMat3d& operator=(const T &a); inline T** operator[](const int i); inline const T* const * operator[] (const int i)const; inline int dim1() const ; inline int dim2() const ; inline int dim3() const ; ~NRMat3d(); }; template<class T> inline NRMat3d<T>::NRMat3d() :nn(0), mm(0),kk(0), v(0) {} template<class T> inline NRMat3d<T>::NRMat3d(int n, int m, int k) : nn(n), mm(m), kk(k),v(new T**[n]) { v[0] = new T*[m*n]; v[0][0] = new T[m*n*k]; for (int j = 1; j < m; j++) v[0][j] = v[0][j - 1] + k; for (int i = 1; i < n; i++) { v[i] = v[i - 1] + m; v[i][0] = v[i - 1][0] + m*k; for (int j = 1; j < m; j++) { v[i][j] = v[i][j - 1] + k; } } } template<class T> NRMat3d<T>::NRMat3d(const T &a, int n, int m, int k) :nn(n), mm(m),kk(k), v(new T**[n]) { v[0] = new T*[m*n]; v[0][0] = new T[m*n*k]; for (int j = 1; j < m; j++) v[0][j] = v[0][j - 1] + k; for (int i = 1; i < n; i++) { v[i] = v[i - 1] + m; v[i][0] = v[i - 1][0] + m * k; for (int j = 1; j < m; j++) { v[i][j] = v[i][j - 1] + k; } } for(int i=0;i<n;i++) for(int j=0;j<m;j++) for (int l = 0; l < k; l++) { v[i][j][l] = a; } } template<class T> NRMat3d<T>::NRMat3d(const T *a, int n, int m,int k) :nn(n), mm(m),kk(k), v(new T**[n]) { v[0] = new T*[m*n]; v[0][0] = new T[m*n*k]; for (int j = 1; j < m; j++) v[0][j] = v[0][j - 1] + k; for (int i = 1; i < n; i++) { v[i] = v[i - 1] + m; v[i][0] = v[i - 1][0] + m * k; for (int j = 1; j < m; j++) { v[i][j] = v[i][j - 1] + k; } } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) for(int l=0;l<k;l++) { v[i][j][l] = *a++; } } template<class T> NRMat3d<T>::NRMat3d(const NRMat3d<T> &rhs) :nn(rhs.nn), mm(rhs.mm),kk(rhs.kk),v(new T**[nn]) { v[0] = new T*[mm*nn]; v[0][0] = new T[mm*nn*kk]; for (int j = 1; j < mm; j++) v[0][j] = v[0][j - 1] + kk; for (int i = 1; i < nn; i++) { v[i] = v[i - 1] + mm; v[i][0] = v[i - 1][0] + mm * kk; for (int j = 1; j < mm; j++) { v[i][j] = v[i][j - 1] + kk; } } for (int i = 0; i < nn; i++) for (int j = 0; j < mm; j++) for(int l=0;l<kk;l++) { v[i][j][l]= rhs[i][j][l]; } } template<class T> NRMat3d<T>& NRMat3d<T>::operator=(const NRMat3d<T>&rhs) { if (this != &rhs) { if ((nn != rhs.nn) || (mm != rhs.mm)) { if (v != 0) { delete[](v[0][0]); delete[](v[0]); delete[](v); } nn = rhs.nn; mm = rhs.mm; kk = rhs.kk; v = new T**[nn]; v[0] = new T*[nn*mm]; v[0][0] = new T[nn*mm*kk]; } for (int j = 1; j < mm; j++) v[0][j] = v[0][j - 1] + kk; for (int i = 1; i < nn; i++) { v[i] = v[i - 1] + mm; v[i][0] = v[i - 1][0] + mm * kk; for (int j = 1; j < mm; j++) { v[i][j] = v[i][j - 1] + kk; } } for (int i = 0; i < nn; i++) for (int j = 0; j < mm; j++) for (int l = 0; l < kk; l++) { v[i][j][l] = rhs[i][j][l]; } } return *this; } template<class T> NRMat3d<T>& NRMat3d<T>::operator=(const T& a) { for (int i = 0; i < nn; i++) for (int j = 0; j < mm; j++) for (int l = 0; l < kk; l++) { v[i][j][l] = a; } return *this; } template<class T> inline T ** NRMat3d<T>::operator[](const int i) { return v[i]; } template<class T> inline const T * const * NRMat3d<T>::operator[](const int i) const { return v[i]; } template<class T> NRMat3d<T>::~NRMat3d() { if (v != 0) { delete[](v[0][0]); delete[](v[0]); delete[](v); } } template<class T> inline int NRMat3d<T>::dim1() const { return nn; } template<class T> inline int NRMat3d<T>::dim2() const { return mm; } template<class T> inline int NRMat3d<T>::dim3() const { return kk; }
true
e56538cb178c0b1dad455a20898cf00869e24e0f
C++
yaishori/c-cpp
/c++/memory man/memPage_t.h
UTF-8
992
2.75
3
[]
no_license
#include "memManager_t.h" #ifndef H_PAGE #define H_PAGE class memPage_t: virtual public memManager_t{ public: virtual ~memPage_t(); memPage_t(); memPage_t(const unsigned int pos, const unsigned int actual,const char* page); virtual unsigned int getCapacity()const{ return m_capacity; } const char* getString() const{ return m_page; } virtual unsigned int readhelper(void* buff,unsigned int bytes, unsigned int position); virtual unsigned int readData(void* buff,unsigned int nbytes); virtual unsigned int readData(void* buff,unsigned int nbytes, unsigned int position); virtual unsigned int writeHelper(void* buff,unsigned int bytes, unsigned int position); virtual unsigned int writeData(void* buff,unsigned int nbytes); virtual unsigned int writeData(void* buff,unsigned int nbytes, unsigned int position); bool isFull(){ return (getActualSize()==defaultSize+1); } private: const unsigned int m_capacity; static unsigned int defaultSize; char* m_page; }; #endif
true
9245e40b90e52705a83da2eac34c90b295f0efb7
C++
MatthewRock/Taverner
/include/Timer.hpp
UTF-8
4,457
3.515625
4
[]
no_license
#ifndef TIMER_HPP #define TIMER_HPP #include <chrono> /** \brief This header implements the class Timer. Timer allows the creation of clock, with various precisions available, is available for C++11 standard, generic. */ namespace Taverner { typedef std::chrono::high_resolution_clock Timer_Clock_Precise; typedef std::chrono::steady_clock Timer_Clock_Steady; typedef std::chrono::system_clock Timer_Clock_System; typedef std::chrono::hours Timer_Precision_Hour; typedef std::chrono::minutes Timer_Precision_Minute; typedef std::chrono::seconds Timer_Precision_Seconds; typedef std::chrono::milliseconds Timer_Precision_Milliseconds; typedef std::chrono::microseconds Timer_Precision_Microseconds; typedef std::chrono::nanoseconds Timer_Precision_Nanoseconds; template<typename Clock_Type = Timer_Clock_Precise, typename Time_Precision = Timer_Precision_Milliseconds> class Timer { typename Clock_Type::time_point startTime; long long pauseTime; bool started; bool paused; public: //Default constructor of Timer. Setting everything to 0 and false. Timer() : pauseTime(0), started(false), paused(false) {} //Start counting time. It basically sets startTicks to current ticks from SDL_GetTicks(), and sets started to true. void start(); //Set flags to false. void stop(); //Keeps value of ticks when timer has stopped. Will be used to resume timer. void pause(); //starts counting time from the stopped time. void unpause(); //Return startTicks(if running), pausedTicks(if paused), or 0 if timer isn't started int getTicks(); inline bool isPaused() { return paused;}; inline bool isStarted() { return started;}; inline int seconds(int s) { return s*1000;} inline int seconds(double s) { return s*1000;} static inline auto getCurrentTime() -> decltype(Clock_Type::now()) { return Clock_Type::now(); } }; template <typename Clock_Type, typename Time_Precision> void Timer<Clock_Type, Time_Precision>::start() { //Set flags started = true; paused = false; //Time that passes when we're paused. Currently 0 - we just started. pauseTime = 0; //Set starting time point. startTime = Clock_Type::now(); } template <typename Clock_Type, typename Time_Precision> void Timer<Clock_Type, Time_Precision>::stop() { //Zero flags. Everything else will be cleaned up in proper starting functions //Also, since we've stopped, now there is no sense to check time from clock. started = false; paused = false; } template <typename Clock_Type, typename Time_Precision> void Timer<Clock_Type, Time_Precision>::pause() { //If timer isn't paused, and is running if( started && (!paused) ) { //Pause it paused = true; //Count the time that passed from start till now std::chrono::duration<double> time = Clock_Type::now() - startTime; //And return it in milliseconds. pauseTime += std::chrono::duration_cast<Time_Precision>(time).count(); } } template <typename Clock_Type, typename Time_Precision> void Timer<Clock_Type, Time_Precision>::unpause() { //If program is paused(can only be paused when running) if( paused ) { //Start from now. //We don't have to set startTime = Clock_Type::now(); //We aren't paused anymore. paused = false; } } template <typename Clock_Type, typename Time_Precision> int Timer<Clock_Type, Time_Precision>::getTicks() { if(started) { if( paused ) { return pauseTime; } else { //Count the time that passed from start till now std::chrono::duration<double> time = Clock_Type::now() - startTime; //And return it in milliseconds. return std::chrono::duration_cast<Time_Precision>(time).count() + pauseTime; } } return 0; } }; #endif // TIMER_HPP
true
f87fd0eef9725253b874b945ee859517b6078d23
C++
Techno-coder/UndertaleCPPLibrary
/revision_2/src/src/headers/fights/states/FightAttackEnemySelectState.h
UTF-8
974
2.5625
3
[]
no_license
#ifndef PROJECT_FIGHTATTACKENEMYSELECTSTATE_H #define PROJECT_FIGHTATTACKENEMYSELECTSTATE_H #include "../../core/State.h" #include "../FightInterfaceControls.h" #include "../Fight.h" #include "../../render/Sprite.h" namespace ug { class FightAttackEnemySelectState : public State { static FightAttackEnemySelectState instance; FightInterfaceControls* interfaceControlsInstance; ug::Sprite soulSprite; int currentEnemySelected = 0; Fight* currentFight; protected: void load() override; public: static FightAttackEnemySelectState& getInstance(); void initialize() override; void handleEvent(sf::Event &event) override; void update() override; void draw() override; void loadFight(Fight* fight); void loadFight(Fight* fight, int currentlySelected); int getCurrentEnemySelected() const; }; } #endif //PROJECT_FIGHTATTACKENEMYSELECTSTATE_H
true
e7d03710d9a9443b0464db35f0eeca687aa3c554
C++
aosipov91/zaton
/src/core/Timer.cpp
UTF-8
433
2.546875
3
[]
no_license
#include "Timer.h" Timer::Timer() {} Timer::~Timer() {} void Timer::Start() { } void Timer::Pause() { } void Timer::Stop() { } void Timer::Begin() { } void Timer::BeginWithDelay(float delay) { } void Timer::SetTime(float f) { } float Timer::GetTime() { return float(10.0); } bool Timer::isRunning() { return true; } void Timer::Update(float fElapsedTime) { }
true
f23533defb76e572685a2438948cf25c3b6ffd65
C++
MichalTurski/TKOM_PASER
/LibraryInterface/Symbols.h
UTF-8
849
2.578125
3
[]
no_license
// // Created by michal on 29.11.18. // #ifndef PROJEKT_SYMBOLS_H #define PROJEKT_SYMBOLS_H #include <string> #include <map> #include <bits/unique_ptr.h> #include "Object.h" #include "ClassFactory.h" class Function; class FunctionDefinition; class ClassFactory; class Symbols { private: std::map<std::string, FunctionDefinition&> localFunctions; std::map<std::string, ExternFunction*> externFunctions; ClassFactory classFactory; public: Symbols(); ~Symbols(); Function *getFunction(const std::string &name); Object *createObject(const std::string &name, const std::string &reference); void addLocalFunction(FunctionDefinition &function); void addExternFunction(const std::string &name, ExternFunction *function); void addClass(const std::string &name, Object *prototype); }; #endif //PROJEKT_SYMBOLS_H
true
b4e1eb69feaed0ead54c80d78b6d4def498f040a
C++
locolocoer/mycode
/Game-Programming-Using-Qt-5-Beginners-Guide-Second-Edition-master/Chapter03/Qt GUI Programming/tictactoe/tictactoe ver6/configurationdialog.cpp
UTF-8
1,203
2.546875
3
[ "MIT" ]
permissive
#include "configurationdialog.h" #include "ui_configurationdialog.h" #include <QPushButton> ConfigurationDialog::ConfigurationDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ConfigurationDialog) { ui->setupUi(this); connect(ui->player1Name, &QLineEdit::textChanged, this, &ConfigurationDialog::updateOKButtonState); connect(ui->player2Name, &QLineEdit::textChanged, this, &ConfigurationDialog::updateOKButtonState); updateOKButtonState(); } ConfigurationDialog::~ConfigurationDialog() { delete ui; } void ConfigurationDialog::updateOKButtonState() { QPushButton *okButton = ui->buttonBox->button(QDialogButtonBox::Ok); okButton->setEnabled(!ui->player1Name->text().isEmpty() && !ui->player2Name->text().isEmpty()); } void ConfigurationDialog::setPlayer1Name(const QString &p1name) { ui->player1Name->setText(p1name); } void ConfigurationDialog::setPlayer2Name(const QString &p2name) { ui->player2Name->setText(p2name); } QString ConfigurationDialog::player1Name() const { return ui->player1Name->text(); } QString ConfigurationDialog::player2Name() const { return ui->player2Name->text(); }
true
540beb4eaa3a849cbbd94bdb5c8fe1163d6d6170
C++
daniel1124/cpp_course_project
/student_file_system/print_data.cpp
UTF-8
715
3.625
4
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; template<class T,class Pred> void my_for_each(T iter1, T iter2, Pred fun){ for(;iter1 != iter2; iter1++){ fun(*iter1); } } void Print(int n) { cout << n*n << ","; } struct MyPrint { void operator()( const string & s ) { cout << s << ","; } }; int main() { int t; int a[5]; vector<string> vt; cin >> t; while( t--) { vt.clear(); for(int i = 0;i < 5; ++i) cin >> a[i]; for(int i = 0;i < 5; ++i) { string s; cin >> s; vt.push_back(s); } my_for_each(a,a+5,Print); cout << endl; my_for_each(vt.begin(),vt.end(),MyPrint()); cout << endl; } return 0; }
true
f7da38809de8d97f29edb3341472f0857057a4b0
C++
HersonaREAL/my_cpp_primer_code
/chapter15/1529.cpp
UTF-8
569
2.59375
3
[]
no_license
#include<iostream> #include"1511.h" #include <fstream> #include<vector> #include <algorithm> #include<memory> #include<cctype> #include<stdexcept> using std::cin; using std::cout; using std::ifstream; using std::ofstream; using std::endl; using std::string; using std::vector; using std::shared_ptr; int main(){ vector<shared_ptr<Quote>> v; auto sa = std::make_shared<Bulk_quote>("doki",100,10,0.3),sb = std::make_shared<Bulk_quote>("dokidoki",200,5,0.4); v.push_back(sa); v.push_back(sb); int sum = 0; for(auto &q:v) sum+=q->net_price(10); cout<<sum<<endl; }
true
8c4acd0e07f905f77eadc043e7ae970a84127f17
C++
adiatomei/c_plus_exercises
/algoritmi_fund/main.cpp
UTF-8
6,327
3.4375
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; //Divizibilitatea void diviz(int a, int b){ if(a % b == 0 || b % a == 0) { cout << "Da\n"; }else{ cout << "Nu\n"; } } //Paritate string parit(int a){ if(a % 2 == 0){ return "par"; }else{ return "impar"; } } //Divizorii unui numar int* divizor_nr(int a){ int index = 0; static int b[100]; for(int i = 1; i <= a; i++){ if(a % i == 0){ b[index] = i; index++; } } return (b); } //Divizorii proprii int* divizor_prop(int a){ int index = 0; static int b[100]; for(int i = 2; i <= a/2; i++){ if(a % i == 0){ b[index] = i; index++; } } return (b); } //Primalitatea unui numar string prim_num(int a){ int status = 0; if(a == 1){ status = 1; }else{ for(int i = 2; i <= a/2; i++){ if(a % i == 0){ status = 1; break; } } } return status ? "neprim" : "prim"; } //Descompunerea in factori primi void fact_prim(int a){ int d = 2, p; while(a > 1){ p = 0; while(a % d == 0){ p++; a /= d; } if(p != 0){ cout << d << "^" << p << ", "; } d++; } } //Cel mai mare divizor comun intre 2 numere întregi int biggest_div(int a, int b){ int r = a % b; while(r != 0){ a = b; b = r; r = a % b; } return b; } //Numere perfecte void perfect_num(int n){ int s; for(int i = 1; i < n; i++){ s = 0; for(int d = 1; d <= i/2; d++){ if(i % d == 0){ s += d; } } if(s == i){ cout << i << " este numar perfect\n"; } } } //Numere prietene void friend_nums(int a, int b){ int sa = 0, sb = 0; for(int i = 2; i <= a/2; i++){ if(a % i == 0){ sa += i; } } for(int i = 2; i <= b/2; i++){ if(b % i == 0){ sb += i; } } if(sa == b && sb == a){ cout << a << " si " << b << " sunt numere prietene.\n"; cout << sa << ", " << sb; }else{ cout << a << " si " << b << " nu sunt numere prietene.\n"; cout << sa << ", " << sb; } } //Factorial int fact(int n){ int p = 1; for(int i = 1; i <= n; i++){ p *= i; } return p; } //Sirul lui Fibonacci int fibo(int n){ int f1 = 1, f2 = 2, f3; if(n < 3){ return 1; }else{ for(int i = 3; i < n; i++){ f3 = f2 + f1; f1 = f2; f2 = f3; } return f3; } } // Numarul invers int invers_num(int a){ int inv = 0; while(a != 0){ inv = inv * 10 + a % 10; a = a / 10; } return inv; } // Numarul palindrom void is_palindrom(int a){ int inv = 0, rep = a; while(a != 0){ inv = inv * 10 + a % 10; a = a / 10; } if(rep == inv){ cout << rep << " este palindrom.\n"; }else{ cout << rep << " nu este palindrom.\n"; } } // Maximul intr-un sir void max_num(int n, int x){ int max = x; for(int i = 2; i <= n; i++){ cout << "Introduceti numar.\n"; cin >> x; if(x > max){ max = x; } } cout << "Cel mai mare numar introdus este " << max << endl; } int main() { //1.Divizibiltate /*int num1, num2; cout << "Introduceti doua numere intregi\n"; cin >> num1 >> num2; cout << num1 << " si " << num2 << " sunt divizibile?\n"; diviz(num1, num2);*/ //2.Paritate /*int num1; cout << "Introduceti un numar intreg\n"; cin >> num1; cout << num1 << " este numar " << parit(num1) << endl;*/ //3.Divizorii unui numar /*int num, i = 0; int *d; cout << "Introduceti un numar intreg\n"; cin >> num; d = divizor_nr(num); cout << "Numerele divizibile cu " << num << " sunt: "; while(d[i] != NULL){ cout << d[i] << "\t"; i++; } }*/ //4.Divizorii proprii /* int num, i = 0; int *d; cout << "Introduceti un numar intreg\n"; cin >> num; d = divizor_prop(num); cout << "Divizorii proprii lui " << num << " sunt: "; while(d[i] != NULL){ cout << d[i] << "\t"; i++; } if(*d == NULL){ cout << "Numarul nu are divizori proprii\n"; }*/ //5. Primalitatea unui numar /* int num; cout << "Introduceti un numar intreg\n"; cin >> num; cout << "Numarul introdus este " << prim_num(num) << endl; */ //6. Descompunerea în factori primi ai unui număr /*int num; cout << "Introduceti un numar intreg.\n"; cin >> num; fact_prim(num);*/ //7. Cel mai mare divizor comun intre 2 numere întregi /*int num1, num2; cout << "Introduceti doua numere intregi. Primul trebuie sa fie mai mare ca al doilea.\n"; cin >> num1 >> num2; cout << "Cel mai mare divizor commun intre " << num1 << " si " << num2 << " este " << biggest_div(num1, num2) << endl;*/ //8.Numere perfecte /*int num; cout << "Introduceti un numar intreg\n"; cin >> num; perfect_num(num);*/ //9. Numere prietene /*int num1, num2; cout << "Introduceti doua numere intregi.\n"; cin >> num1 >> num2; friend_nums(num1, num2);*/ //10 Factorial /*int num; cout << "Introduceti un numar intreg.\n"; cin >> num; cout << fact(num) << endl;*/ //11 Sirul lui Fibonnaci /*int num; cout << "Introduceti un numar intreg.\n"; cin >> num; cout << "Al " << num << "-lea termen din sirul lui Fibonnaci este " << fibo(num) << endl;*/ //12. Mumarul invers /*int num; cout << "Introduceti un numar intreg.\n"; cin >> num; cout << "Inversul lui " << num << " este " << invers_num(num) << endl;*/ //13. Numarul palindrom /*int num; cout << "Introduceti un numar intreg.\n"; cin >> num; is_palindrom(num);*/ //14. Maximul intr-un sir de numere int num1, num2; cout << "Introduceti numarul de numere introduse.\n"; cin >> num1; cout << "Introduceti numar.\n"; cin >> num2; max_num(num1, num2); return 0; }
true
dae79dadcf7bf9d8ba0f14bc213d36de2b867894
C++
notorious94/UVa-solution
/1185 UVA.cpp
UTF-8
665
2.515625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; /// M A C R O Starts Here #define pf printf #define sf scanf #define MAX 500000 #define sif(a) scanf("%d",&a) #define pif(a) printf("%d\n",a) #define pi acos(-1.0) typedef long long ll; typedef unsigned long long ull; int factorialDigit ( int n ) { if(n==0||n==1) return 1; return floor(((n+0.5)*log(n)-n+0.5*log(2*pi))/log(10))+1; } int main() { //freopen("in.txt","r", stdin); //freopen("out.txt","w", stdout); ios_base::sync_with_stdio(false); cin.tie(NULL); int t,n; sif(t); while(t--) { sif(n); pf("%d\n",factorialDigit(n)); } return 0; }
true
0a3dfe13ef692c2337d0f2eb5578391dc204bc04
C++
SmartPolarBear/project-dionysus
/kern/libs/basic_io/ftoa.cc
UTF-8
2,165
2.75
3
[ "MIT" ]
permissive
#include "system/types.h" constexpr auto MAX_PRECISION = 10; static const double rounders[MAX_PRECISION + 1] = { 0.5, // 0 0.05, // 1 0.005, // 2 0.0005, // 3 0.00005, // 4 0.000005, // 5 0.0000005, // 6 0.00000005, // 7 0.000000005, // 8 0.0000000005, // 9 0.00000000005 // 10 }; size_t ftoa_ex(double f, char *buf, int precision) { char *ptr = buf; char *p = ptr; char *p1; char c; long intPart; // check precision bounds if (precision > MAX_PRECISION) precision = MAX_PRECISION; // sign stuff if (f < 0) { f = -f; *ptr++ = '-'; } if (precision < 0) // negative precision == automatic precision guess { if (f < 1.0) precision = 6; else if (f < 10.0) precision = 5; else if (f < 100.0) precision = 4; else if (f < 1000.0) precision = 3; else if (f < 10000.0) precision = 2; else if (f < 100000.0) precision = 1; else precision = 0; } // round value according the precision if (precision) f += rounders[precision]; // integer part... intPart = f; f -= intPart; if (!intPart) *ptr++ = '0'; else { // save start pointer p = ptr; // convert (reverse order) while (intPart) { *p++ = '0' + intPart % 10; intPart /= 10; } // save end pos p1 = p; // reverse result while (p > ptr) { c = *--p; *p = *ptr; *ptr++ = c; } // restore end pos ptr = p1; } // decimal part if (precision) { // place decimal point *ptr++ = '.'; // convert while (precision--) { f *= 10.0; c = f; *ptr++ = '0' + c; f -= c; } } // terminating zero *ptr = 0; return ptr - buf; }
true
c3876159bc27f41005ca0ffc826f7a1e498621f0
C++
davidataka/AlgorithmsAndDataStructures
/lab2/l2b_competition.cpp
UTF-8
1,954
3.109375
3
[]
no_license
#include <iostream> using namespace std; void merge(string data[][2], int left, int middle, int right) { int size1 = middle - left + 1; int size2 = right - middle; string left_part[size1][2]; string right_part[size2][2]; for (int i = 0; i < size1; i++) for (int j = 0; j < 2; j++) left_part[i][j] = data[i + left][j]; for (int i = 0; i < size2; i++) for (int j = 0; j < 2; j++) right_part[i][j] = data[i + middle + 1][j]; int i = 0; int j = 0; int k = left; while ((i < size1) && (j < size2)) { if (left_part[i][0] <= right_part[j][0]) { data[k][0] = left_part[i][0]; data[k][1] = left_part[i][1]; i++; } else { data[k][0] = right_part[j][0]; data[k][1] = right_part[j][1]; j++; } k++; } while (i < size1) { data[k][0] = left_part[i][0]; data[k][1] = left_part[i][1]; i++; k++; } while (j < size2) { data[k][0] = right_part[j][0]; data[k][1] = right_part[j][1]; j++; k++; } } void mergesort(string data[][2], int left, int right) { if (left < right) { int middle = (right + left) / 2; mergesort(data, left, middle); mergesort(data, middle + 1, right); merge(data, left, middle, right); } } int main() { freopen("race.in", "r", stdin); freopen("race.out", "w", stdout); int n; cin >> n; string data[n][2]; for (int i = 0; i < n; i++) for (int j = 0; j < 2; j++) cin >> data[i][j]; mergesort(data, 0, n - 1); cout << "=== " << data[0][0] << " ===" << "\n" << data[0][1] << "\n"; for (int k = 1; k < n; k++) { if ((k > 0) && (data[k][0] != data[k - 1][0])) cout << "=== " << data[k][0] << " ===" << "\n"; cout << data[k][1] << "\n"; } return 0; }
true
327a87bb93e170f71664643cd4b04ef4e3d176ed
C++
JanMalitschek/Mineral
/Source/Nodes/Node.cpp
UTF-8
1,680
2.71875
3
[]
no_license
#include "Node.h" #include "NodeEditor.h" #include "Graphs/NodeGraphProcessor.h" Node::Node(int numInputs) { this->numInputs = numInputs; for (int i = 0; i < numInputs; i++) inputs.push_back(nullptr); } Node::~Node() { disconnectAll(); for (int i = 0; i < numInputs; i++) delete inputs[i]; inputs.clear(); delete buffer; } void Node::initBuffer(int bufferSize) { buffer = (SIMDFloat*)malloc(sizeof(SIMDFloat) * bufferSize); } void Node::connectInput(int index, Node* other) { jassert(index < numInputs); inputs[index] = other; } void Node::disconnectInput(int index) { jassert(index < numInputs); inputs[index] = nullptr; } void Node::disconnectInput(Node* potentialInput) { for (int i = 0; i < numInputs; i++) if (inputs[i] == potentialInput) inputs[i] = nullptr; } void Node::disconnectAll() { for (int i = 0; i < numInputs; i++) inputs[i] = nullptr; } int Node::getNumInputs() { return numInputs; } std::vector<Node*>& Node::getInputs() { return inputs; } bool Node::isMarked() { return editor->marked; } void Node::mark(bool marked) { editor->marked = marked; } int Node::getNumConnectedInputs() { int numConnectedInputs = 0; for (int i = 0; i < numInputs; i++) if (inputs[i]) numConnectedInputs++; return numConnectedInputs; } int Node::getNumMarkedInputs() { int numMarkedInputs = 0; for (int i = 0; i < numInputs; i++) if (inputs[i] && inputs[i]->isMarked()) numMarkedInputs++; return numMarkedInputs; } void Node::getInputInfo(int& getNumConnectedInputs, int& getNumMarkedInputs) { for (int i = 0; i < numInputs; i++) if (inputs[i]) { getNumConnectedInputs++; if (inputs[i]->isMarked()) getNumMarkedInputs++; } }
true
3ed216f6b62e73e27fa0e5732b748b51a2dfbab4
C++
anonymokata/ae85d9b8-4c15-11ea-90ff-52e448637004
/Pencil.h
UTF-8
756
2.734375
3
[]
no_license
#ifndef PENCILDURABILITYKATA_PENCIL_H #define PENCILDURABILITYKATA_PENCIL_H #include <memory> #include <string> class Eraser; class Paper; class PencilPoint; class Pencil { public: explicit Pencil( std::unique_ptr<PencilPoint> point = std::make_unique<PencilPoint>(), std::unique_ptr<Eraser> eraser = std::make_unique<Eraser>()); Pencil(const Pencil&) = delete; Pencil& operator=(const Pencil&) = delete; void write(Paper& paper, const std::string& new_text); void erase(Paper& paper, const std::string& to_erase); void edit(Paper& paper, size_t position, const std::string& new_text); void sharpen(); private: std::unique_ptr<PencilPoint> mPoint; std::unique_ptr<Eraser> mEraser; }; #endif
true
d17dfd91339ec6c5f70dae7c68b1f9a97d26222a
C++
237K/ProblemSolving
/BOJ#1026.cpp
WINDOWS-1252
600
2.796875
3
[]
no_license
// // OS Windows // 2019.08.25 // // [Algorithm Problem Solving] // // BAEKJOON #1026 // #include <iostream> #include <vector> #include <algorithm> using namespace std; int main(int argc, char** argv) { freopen("s_input1026.txt", "r", stdin); ios::sync_with_stdio(false); cin.tie(NULL); int N, n, ret; vector<int> A, B; cin >> N; A.resize(N); B.resize(N); for (n = 0; n < N; ++n) cin >> A[n]; for (n = 0; n < N; ++n) cin >> B[n]; sort(A.begin(), A.end(), greater<int>()); sort(B.begin(), B.end()); ret = 0; for (n = 0; n < N; ++n) ret += A[n] * B[n]; cout << ret; return 0; }
true
63880222a3332ef73e23549ea372c12de5525968
C++
packetsss/Cpp
/Leetcode/Easy/1603_Design_Parking_System.cpp
UTF-8
759
3.453125
3
[]
no_license
#include <iostream> #include <vector> #include <set> #include <unordered_set> #include <map> #include <unordered_map> using namespace std; class ParkingSystem { public: int arr[3]; ParkingSystem(int big, int medium, int small) { arr[0] = big; arr[1] = medium; arr[2] = small; } bool addCar(int carType) { arr[carType - 1]--; return arr[carType - 1] >= 0; } }; // -------- BELOW is used to call the class above --------- // int main() { ParkingSystem p(1, 1, 0); int lst[] = {1, 2, 3, 1}; for(int i = 0; i < *(&lst + 1) - lst; i++) // iterate through length of lst { printf("Car type: %d, can be added: %s\n", lst[i], p.addCar(lst[i]) ? "true":"false"); } }
true
c08322b22ee6a9c749d1d2970cf826cdb22061dd
C++
hieupm123/Hieu
/code/C++/CSES-Solutions/Introductory Problems/Number Spiral (1071)/rainboy.cpp
UTF-8
413
2.90625
3
[]
no_license
/* https://cses.fi/problemset/task/1071 Number Spiral */ #include <stdio.h> int main() { int t; scanf("%d", &t); while (t--) { int x, y, tmp; long long a; scanf("%d%d", &x, &y); a = x > y ? x : y; if (a % 2 == 1) tmp = x, x = y, y = tmp; printf("%lld\n", x > y ? a * a - (y - 1) : (a - 1) * (a - 1) + x); } return 0; }
true
1cf14c60d33c7f48bfac1fd418d3e93d4731d5be
C++
balhayer/epp-preparation-practice
/PART1/deleteSmallestPositive/Prob1.cpp
UTF-8
910
3.828125
4
[]
no_license
#include <iostream> using namespace std; void deleteSmallestPos(int arr[], int size) { int minPos = -1; for(int i = 0; i < size; ++i) { if(arr[i] > 0) { if(minPos == -1 || arr[i] < arr[minPos]) { minPos = i; } } } for(int i = minPos; i < size-1; ++i) { arr[i] = arr[i+1]; } } void printArray(int arr[], int size) { for(int i = 0; i < size; ++i) { cout << arr[i] << " "; } cout << endl; } int main() { int myarray[100]; cout << "Enter number of integers : "; int n; cin >> n; cout << "Enter " << n << " integers" << endl; for (int i = 0; i < n; i++) cin >> myarray[i]; cout << "Contents of array : "; printArray(myarray, n); deleteSmallestPos(myarray, n); cout << "Contents of array after deleteSmallestPos: "; printArray(myarray, n - 1); system("pause"); return 0; }
true
95b9e2590da26588434368ffbe20acd4c97c418f
C++
makersmelx/VE281
/LAB/LAB3/src/selection.cpp
UTF-8
2,447
3.34375
3
[]
no_license
// // Created by 吴佳遥 on 2019-10-10. // #include "sort.h" int rSelect(int *nums, int left, int right, int k) { if (left == right) { return nums[left]; } int index = rand() % (right - left + 1) + left; swap(index, left, nums); int pivot = nums[left]; int i = left + 1, j = i; for (; i <= right; i++) { if (nums[i] < pivot) { swap(j, i, nums); j++; } } swap(j - 1, left, nums); int relative = (j - 1) - left; if (relative == k) { return nums[j - 1]; } else if (relative > k) { return rSelect(nums, left, j - 2, k); } else { return rSelect(nums, j, right, k - relative - 1); } } static int choosePivot(int *nums, int left, int right) { if (left == right) { return nums[left]; } int length = right - left + 1; int divLength = length % 5 == 0 ? length / 5 : length / 5 + 1; int *res = new int[divLength]; int itr = 0; for (int i = 0; i < length; i = i + 5) { int tmpRight = (i + 4 >= length) ? length - 1 : i + 4; int tmpLength = tmpRight - i + 1; int *div = new int[tmpLength]; for (int j = i; j <= tmpRight; j++) { div[j - i] = nums[j]; } quickSort(div, 0, tmpLength - 1); if (tmpLength % 2 == 1) { res[itr++] = div[tmpLength / 2]; } else { res[itr++] = (div[tmpLength / 2] + div[tmpLength / 2 - 1]) / 2; } delete[] div; } int x = choosePivot(res, 0, divLength - 1); delete[] res; return x; } int dSelect(int *nums, int left, int right, int k) { if (left == right) { return nums[left]; } int pivot = choosePivot(nums, left, right); int pivotat = 0; for (int i = left; i < right; i++) { if (nums[i] == pivot) { pivotat = i; } } swap(pivotat, left, nums); //int pivot = nums[left]; int i = left + 1, j = i; for (; i <= right; i++) { if (nums[i] < pivot) { swap(j, i, nums); j++; } } swap(j - 1, left, nums); if (j - 1 == k) { return nums[k]; } else if (j - 1 > k) { return rSelect(nums, left, j - 2, k); } else { return rSelect(nums, j, right, k - j + 1); } }
true
d7503928a82377bdd5a18b7eabdb9c817c319c42
C++
arpitjp/temp
/Postfix to Infix.cpp
UTF-8
548
3.546875
4
[]
no_license
//postfix to infix #include<bits/stdc++.h> using namespace std; string PostfixToInfix(string exp) { string s1, s2; stack<string> s; for (int i = 0; i < exp.length(); i++) { if(isalpha(exp[i])) s.push(exp.substr(i, 1)); else { s2 = s.top(); s.pop(); s1 = s.top(); s.pop(); s.push("(" + s1 + " " + exp.substr(i, 1) + " " + s2 + ")"); } } return s.top(); } int main() { cout << PostfixToInfix("abcd^e-fgh*+^*+i-"); }
true
9e38ac18f78e9490e44f35e8e8e8b76f5bf80440
C++
fallnomega/CPP_Labs
/CompSci165/Lab12/History.cpp
UTF-8
5,338
3.625
4
[]
no_license
// Lab 12: History.cpp // Programmer: Jason Hillin // Editor(s) used: MS Visual C++ 2010 Express // Compiler(s) used: MS Visual C++ 2010 Express #include <iostream> using std::cout; using std::cin; using std::endl; #include <iomanip> using std::setw; #include <fstream> using std::ifstream; using std::ofstream; #include <cstring> #include <cstdlib> //class class course { public: char nCourse[11]; char term[7]; int units; char grade; course *next; }; //function void coutClass(course* a); //print class void clearList(course* head);//delete list course* insert(course*, course*); // insertion int courseCmp(const course*, const course*); //compare course int myStricmp(const char* dst, const char* src); //semester compare int myStrnicmp(const char* dst, const char* src, int count);//tie breaker //////// //main// //////// int main() { cout << "Lab 12: History.cpp\n"; cout << "Programmer: Jason Hillin\n\n"; //setting up default link list course *head = 0; //empty linked list ///////////// //insertion// ///////////// cout << "\n\nCourse Listing\n-----------------------------------------------\n" << " Courses" << setw(15) <<" Term" << setw(10) << "Units" <<setw(10) << "Grade\n" << "-----------------------------------------------\n"; for(course* p=head;p;p=p->next) coutClass(p); //prompt to enter new courses cout << "\n\nWould you like to add to the listing [y/n]?> "; char answer; cin >> answer; cin.ignore(1000,10); if(answer=='n') { cout <<"\n\nGood bye!" << endl; }//if else { while(true) { //get new entry cout << "Please enter new course name, term, units, and grade " << "with a space between them.\nExample: compsc-110 fa2009 4 a\n"; course* newCourse = new course; cin >> newCourse->nCourse; cin >> newCourse->term; cin >> newCourse->units; cin >> newCourse->grade; head =insert(newCourse,head);//call //show new node on the current list cout << "\n\nNew Course Listing\n------------------\n" << " Courses" << setw(15) <<" Term" << setw(10) << "Units" <<setw(10) << "Grade\n" << "----------------------------------------------\n"; for(course* p=head;p;p=p->next) coutClass(p); //want to add more prompt cout << "\n\nContinue adding more course?(y/n):"; char aanswer; cin >> aanswer; cin.ignore(1000,10); if(aanswer=='n') { cout << "\n\nCourse Listing\n-----------------------------------------------\n" << " Courses" << setw(15) <<" Term" << setw(10) << "Units" <<setw(10) << "Grade\n" << "-----------------------------------------------\n"; for(course* p=head;p;p=p->next) coutClass(p); cout << "Bye" << endl; break; }//if }//while }//else //remove all nodes from listing clearList(head); cout << endl; }//main ///////////// //functions// ///////////// void coutClass(course* a) //print course listings { cout << setw(15) << a->nCourse <<setw(7) << " "<< a->term << setw(6) << a->units << setw(8) << a->grade << endl; } void clearList(course* head)//clear list { while(head) { course* next = head->next; delete head; head=next; }//while } course* insert(course* t, course* h) //insertion method { course* p, *prev; for (p=h, prev=0; p; prev=p, p=p->next) if (courseCmp(t, p) < 0) // if "t" precedes "p"... break; // "t" goes between "prev" and "p" t->next = p; // "t" inserted before "p" if (prev) // "t" inserted after "prev" prev->next = t; else // "t" added to front of list h = t; return h; } // COMPARE function for above int courseCmp(const course* a, const course* b) // header { //validate the length if((strlen(a->term) !=6) || (strlen(b->term) !=6)) // .. in cstring return myStricmp(a->nCourse, b->nCourse); if(myStricmp(a->term, b->term)==0) return myStricmp(a->nCourse, b->nCourse); //handle ties here if(myStricmp(a->term, b->term)==0) return myStricmp(a->nCourse,b->nCourse); //compare the years int yearA = atoi(a->term + 2); //atoi is found ... int yearB = atoi(b->term+2);//..in cstlib if(yearA<yearB) return -1; //termA comes first if(yearA>yearB) return 1; //termB comes first //compare semesters in case of same year if(myStrnicmp(a->term, "SP", 2) == 0) return -1; //termA comes first if(myStrnicmp(a->term,"SU",2) == 0) return myStrnicmp(b->term,"SP",2) ? -1: 1; return 1; } int myStricmp(const char* dst, const char* src) { int f, l; do { if (((f = (unsigned char)(*(dst++))) >= 'A') && (f <= 'Z')) f -= 'A' - 'a'; if (((l = (unsigned char)(*(src++))) >= 'A') && (l <= 'Z')) l -= 'A' - 'a'; } while (f && (f == l)); return(f - l); } int myStrnicmp(const char* dst, const char* src, int count) { int f, l; do { if (((f = (unsigned char)(*(dst++))) >= 'A') && (f <= 'Z')) f -= 'A' - 'a'; if (((l = (unsigned char)(*(src++))) >= 'A') && (l <= 'Z')) l -= 'A' - 'a'; } while (--count && f && (f == l)); return (f - l); }
true
2a8fedbe31655beadbe4e02a4e7a9b2dbcf98d97
C++
deba19/Coding-Challenge
/sostronk_DebasisJana.cpp
UTF-8
4,911
2.96875
3
[]
no_license
/* So Stronk Assignment This program is made by Debasis Jana, Lovely Professional University University Reg No: 11701186 Email ID: debasisjana93@gmail.com Mobile Number: 9609624692 / 8918470674 */ #include<bits/stdc++.h> #define fastio ios_base::sync_with_stdio(false); cin.tie(NULL) using namespace std; int main() { fastio; string m; getline(cin,m); vector<pair<string,int>> player; string line, name; int score; while (getline(cin, line) && !line.empty()) { istringstream iss(line); if (iss >> name >> score) player.push_back(make_pair(name, score)); } //we need at least m*2 numbers of players to make 2 teams of size m each if(player.size()<stoi(m)*2) { cout<<"\nTeam making is not possible\n"; } else { //team declaration vector<pair<vector<string>,double>>teamA; vector<pair<vector<string>,double>>teamB; int k=1,totrun=0; double avgrun=0; for(int i=0;i<=stoi(m);i++) { vector<string>plyr; totrun=0,avgrun=0; //Creating possible team A //adding the first teammate in the list plyr.push_back(player[0].first); //counting total run of this team players totrun+=player[0].second; int j; for(j=k;j<stoi(m)+k-1;++j) { //adding other m-1 teammates in a team plyr.push_back(player[j].first); //counting total run of this team players totrun+=player[j].second; } avgrun=totrun/(double)plyr.size(); //Added one possible team A with average score of the team mates teamA.push_back(make_pair(plyr,avgrun)); //clearing all data from the temporary team list plyr.clear(), totrun=0,avgrun=0; int count1=0; //creating possible team B for(int w=1;w<k;w++) { count1++; plyr.push_back(player[w].first); totrun+=player[w].second; } for(int w=j;w<stoi(m)-count1+j;w++) { plyr.push_back(player[w].first); totrun+=player[w].second; } avgrun=totrun/(double)plyr.size(); //Added one possible team B with average score of the team mates teamB.push_back(make_pair(plyr,avgrun)); k++; } //Activate these lines if you want to see players team wise /* for(auto xx:teamA) { vector<string>ss=xx.first; for(auto yy:ss) cout<<yy<<" "; cout<<xx.second<<"\n"; } cout<<"\n"; for(auto xx:teamB) { vector<string>ss=xx.first; for(auto yy:ss) cout<<yy<<" "; cout<<xx.second<<"\n"; }*/ //making a vector pair of difference of two teams average score and the two teams vector<pair<double,pair<pair<vector<string>,double>,pair<vector<string>,double>>>>answer; for(int i=0;i<teamA.size();i++) { //Match i+1, team one player list vector<string>t1=teamA[i].first; //Match i+1, team two player list vector<string>t2=teamB[i].first; //Match i+1, team one average score double avg1=teamA[i].second; //Match i+1, team two average score double avg2=teamB[i].second; //difference of their average score double diff=abs(avg1-avg2); //pushing them all in a vector answer.push_back(make_pair(diff,make_pair(make_pair(teamA[i].first,avg1),make_pair(teamB[i].first,avg2)))); } //sorting difference of average scores from best to worst sort(answer.begin(),answer.end()); for(int i=0;i<answer.size();i++) { //Match i+1, team one player list vector<string>t1=answer[i].second.first.first; //Match i+1, team two player list vector<string>t2=answer[i].second.second.first; //Match i+1, team one average score double avg1=answer[i].second.first.second; //Match i+1, team two average score double avg2=answer[i].second.second.second; //printing possible matches with given format cout<<t1[0]; for(int j=1;j<t1.size();j++) cout<<","<<t1[j]; cout<<" ("<<avg1<<")"; cout<<" vs "; cout<<t2[0]; for(int j=1;j<t2.size();j++) cout<<","<<t2[j]; cout<<" ("<<avg2<<")"; cout<<"\n"; } } return 0; }
true
a8868428077a2c4309a55884a0d9cfb4295dc103
C++
zhuangqh/Cpp-course
/project/stage1/Vector.h
UTF-8
467
2.671875
3
[]
no_license
#ifndef VECTOR_H #define VECTOR_H class Vector { private: int _dim; int *_vector; void create(int); public: Vector(); Vector(const Vector &); ~Vector(); explicit Vector(int dim); void set(const int *, int dim); void set_one(int index, int value); int dimension() const; int length() const; void print() const; Vector operator+(const Vector&) const; Vector operator-(const Vector&) const; Vector operator*(const Vector&) const; }; #endif
true
0f14cd0fae62cba8a8dad10a2963a0e925b2e249
C++
ZeroOne101010/EdgeOfTheUniverse
/EdgeOfTheUniverse/BackGroundLayer.cpp
UTF-8
450
2.578125
3
[]
no_license
#include "World.h" #include "BackGroundLayer.h" BackGroundLayer::BackGroundLayer(World* world, glm::vec2 speed, glm::vec2 size) { this->speed = speed; layer.Size = size; this->world = world; layer.Angle = 0; } Alterable BackGroundLayer::draw(Renderer* renderer, Alterable alters) { layer.textureRect = FloatRect(world->Position.x * -speed.x, world->Position.y * -speed.y, layer.Size.x, layer.Size.y); renderer->draw(&layer); return alters; }
true
7c634415ffba18a3945824670ce0ca8f1c5e462a
C++
kmiloarguello/cplusplus
/Pto2_agosto.cpp
UTF-8
652
3.28125
3
[]
no_license
#include<stdio.h> #include<conio.h> #include<string.h> #include<ctype.h> main() { char a[30]; int i,mayus=0,minus=0,numero=0,caracter=0,espacio=0;; printf("Escriba el Texto (max 30 caracteres)\n"); gets(a); for(i=0;a[i]!='\0';i++) { if(isspace(a[i])){ espacio++; } if( isupper(a[i])){ mayus++; } if( islower(a[i])){ minus++; } if( isdigit(a[i])){ numero++; } if( ispunct(a[i])){ caracter++; } } printf("\n\nMayusculas: %d ",mayus); printf("\nMinusculas: %d ",minus); printf("\nNumeros: %d ",numero); printf("\nCaracteres Especiales: %d ",caracter); printf("\nEspacios: %d ",espacio); getch(); }
true
8426755f46bbe5954a5121e209d78f14e73badc2
C++
Graff46/OGSR-Engine
/ogsr_engine/xrGame/purchase_list_inline.h
UTF-8
918
2.59375
3
[ "Apache-2.0" ]
permissive
//////////////////////////////////////////////////////////////////////////// // Module : purchase_list_inline.h // Created : 12.01.2006 // Modified : 12.01.2006 // Author : Dmitriy Iassenev // Description : purchase list class inline functions //////////////////////////////////////////////////////////////////////////// #pragma once IC float CPurchaseList::deficit(const shared_str& section) const { DEFICITS::const_iterator I = m_deficits.find(section); if (I != m_deficits.end()) return ((*I).second); return (1.f); } IC const CPurchaseList::DEFICITS& CPurchaseList::deficits() const { return (m_deficits); } IC void CPurchaseList::deficit(const shared_str& section, const float& deficit) { DEFICITS::iterator I = m_deficits.find(section); if (I != m_deficits.end()) { (*I).second = deficit; return; } m_deficits.insert(std::make_pair(section, deficit)); }
true
41f79b283a28d029aab1c3ac6b09528d16b33e5e
C++
dniklaus/wiring-skeleton
/lib/adapter/MyBuiltinLedIndicatorAdapter.cpp
UTF-8
684
2.8125
3
[ "MIT" ]
permissive
/* * MyBuiltinLedIndicatorAdapter.cpp * * Created on: 04.11.2019 * Author: nid */ #include "MyBuiltinLedIndicatorAdapter.h" #include <Arduino.h> MyBuiltinLedIndicatorAdapter::MyBuiltinLedIndicatorAdapter() { // initialize built in LED pin as output pinMode(LED_BUILTIN, OUTPUT); // switch LED off setLed(false); } MyBuiltinLedIndicatorAdapter::~MyBuiltinLedIndicatorAdapter() { } void MyBuiltinLedIndicatorAdapter::notifyStatusChange(bool status) { setLed(status); } void MyBuiltinLedIndicatorAdapter::setLed(bool isOn) { #ifdef ESP8266 // the built-in LED logic on ESP8266 module is inverted! isOn = !isOn; #endif digitalWrite(LED_BUILTIN, isOn); }
true
86351432d0475442d8f5557bdb87aad58375aaae
C++
wolfdan666/WolfEat3moreMeatEveryday
/LeetCode/53_最大子序和.cpp
UTF-8
2,324
2.96875
3
[]
no_license
/* 2020年5月3日20:35:58 感觉线段树能够秒了这题,这题应该是用了线段树的基本思路 但是自己有点不太记得了...所以先想想吧 想到了前缀和,然后相减得到区间和 尴尬,这个标签是简单啊,2020年5月3日20:45:24 为啥想这么久 题感消退了很多...看tutorial吧,羞耻 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/maximum-subarray/solution/zui-da-zi-xu-he-by-leetcode-solution/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 看了答案,真的不能做人了...绝了 */ #include<bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i, a, b) for(int i = int(a); i <= int(b); ++i) #define per(i, b, a) for(int i = int(b); i >= int(a); --i) #define mem(x, y) memset(x, y, sizeof(x)) #define SZ(x) x.size() #define mk make_pair #define pb push_back #define fi first #define se second const ll mod=1000000007; const int inf = 0x3f3f3f3f; inline int rd(){char c=getchar();int x=0,f=1;while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}return x*f;} inline ll qpow(ll a,ll b){ll ans=1%mod;for(;b;b>>=1){if(b&1)ans=ans*a%mod;a=a*a%mod;}return ans;} class Solution { public: int maxSubArray(vector<int>& nums) { int pre = 0, maxAns = nums[0]; for (const auto &x: nums) { pre = max(pre + x, x); maxAns = max(maxAns, pre); } return maxAns; } }; class Solution2 { public: struct Status { int lSum, rSum, mSum, iSum; }; Status pushUp(Status l, Status r) { int iSum = l.iSum + r.iSum; int lSum = max(l.lSum, l.iSum + r.lSum); int rSum = max(r.rSum, r.iSum + l.rSum); int mSum = max(max(l.mSum, r.mSum), l.rSum + r.lSum); return (Status) {lSum, rSum, mSum, iSum}; }; Status get(vector<int> &a, int l, int r) { if (l == r) return (Status) {a[l], a[l], a[l], a[l]}; int m = (l + r) >> 1; Status lSub = get(a, l, m); Status rSub = get(a, m + 1, r); return pushUp(lSub, rSub); } int maxSubArray(vector<int>& nums) { return get(nums, 0, nums.size() - 1).mSum; } }; int main(){ return 0; }
true
88770fc13ecccda677111942d17ec70ab5c074be
C++
mizimmerman/PracticeProblems
/classes.cpp
UTF-8
781
2.734375
3
[]
no_license
#include <iostream> using namespace std; #include "classes.h" /* Constructors */ FootballPlayer::FootballPlayer() { name = "none"; height = 0; weight = 0; position = "none"; } FootballPlayer::FootballPlayer(string n, int h, int w, string pos) { set_name(n); set_height(h); set_weight(w); set_position(pos); } /* TODO */ /* Setters */ void FootballPlayer::set_name(string n) { } void FootballPlayer::set_height(int h) { } void FootballPlayer::set_weight(int w) { } void FootballPlayer::set_position(string pos) { } /* Getters */ string FootballPlayer::get_name() { } int FootballPlayer::get_height() { } int FootballPlayer::get_weight() { } string FootballPlayer::get_position() { } /* Other functions */ void FootballPlayer::display_player() { }
true
04a476a9c12bcd473cc864a9f3a3d772a5ce2fec
C++
RohiniRG/Daily-Coding
/Day79(Sort_stack).cpp
UTF-8
724
3.921875
4
[]
no_license
/* Given a stack, the task is to sort it such that the top of the stack has the greatest element. Example: Input: Stack: 3 2 1 Output: 3 2 1 */ // ********************************************************************************************************** # include <bits/stdc++.h> using namespace std; void sortedInsert(stack<int> &s, int x) { if(s.empty() or x>s.top()) { s.push(x); return; } int temp = s.top(); s.pop(); sortedInsert(s,x); s.push(temp); } void sort(stack <int> &s) { if(!s.empty()) { int x = s.top(); s.pop(); sort(s); sortedInsert(s,x); } } int main() { stack <int> stk; stk.push(1); stk.push(2); stk.push(3); sort(stk); cout<<stk.top()<<endl; }
true
72036b31123ffe445286b568e01c369ff733a1dc
C++
Showtim3/Programming
/CodingBlocks/sumOfArray.cpp
UTF-8
1,105
2.84375
3
[]
no_license
#include <iostream> #include <set> #include <map> #include <vector> #include <algorithm> #include <cmath> #define li long int #define ll long long #define lli long long int using namespace std; vector<int> returnSumArray(vector<int> a, vector<int> b,int n, int m){ int i=0, sum; vector<int> ans; int carry=0; while(i!=m){ sum=a[n-1-i] + carry + b[m-1-i]; carry = sum/10; ans.push_back(sum%10); i++; } for(;i<n;i++){ sum=carry + a[n-1-i]; carry = sum/10; ans.push_back(sum%10); } if(carry){ ans.push_back(carry); } return ans; } int main(){ int n,m; vector<int> a; vector<int> b; int ele,i; cin>>n; for(i=0;i<n;i++){ cin>>ele; a.push_back(ele); } cin>>m; for(i=0;i<m;i++){ cin>>ele; b.push_back(ele); } vector<int> ans; if(n>m){ ans = returnSumArray(a,b,n,m); } else { ans = returnSumArray(b,a,m,n); } for(i=ans.size()-1;i>=0;i--){ cout<<ans[i]<<", "; } cout<<"END"<<endl; return 0; }
true
43b3506e0dc3feafbe7ca465678922062a711557
C++
PrecedentBrute/mlsa-recruitment-tasks
/Task1.cpp
UTF-8
264
3.0625
3
[]
no_license
#include<iostream> int main() { int x, y, z; std::cout << "Enter x, y and z : " << std::endl; std::cin >> x >> y >> z; int ahead = y % x; int to_travel = x - ahead; if (z >= to_travel) std::cout << "YES" << std::endl; else std::cout << "NO" << std::endl; }
true
b8302d29a66a2d6d882d75a7849bbe5011e469a7
C++
efraindrummer/matrices_C-language
/3diagonal.cpp
WINDOWS-1258
976
2.96875
3
[]
no_license
/*Efrain May Mayo 170869 Universidad Autonoma del Camen Ingenieria en computacion*/ #include<stdio.h> #define maxcol 30 #define maxfil 20 void llenardia(int a[][maxcol],int nfilas, int ncols); void escribirsalida(int a[][maxcol],int nfilas, int ncols); main(){ int nfilas, ncols; int a[maxfil][maxcol]; printf("Cuantas filas? \n"); scanf("%d",&nfilas); printf("Cuantas columnas? \n"); scanf("%d",&ncols); llenardia(a,nfilas,ncols); printf("\n linea intermedia: \n \n"); escribirsalida(a,nfilas,ncols); } /*leer una tabla de enteros*/ void llenardia(int a[][maxcol],int m, int n){ int fila, col; for(fila=0; fila<m; fila++){ for(col=0; col<n; col++) if(fila==col){ a[fila][col]=1; }else{ if(fila!=col){ a[fila][col]=0; } } }return; } void escribirsalida(int a[][maxcol],int m, int n){ int fila, col; for(fila=0; fila<m; fila++){ for(col=0; col<n; col++) printf("%4d",a[fila][col]); printf("\n"); }return; }
true
0ec07ee75a79fe0425a107f512ddecb60e7c86d7
C++
khainacs/Task_in_class
/quadratic_equation.cpp
UTF-8
965
2.875
3
[]
no_license
#include<stdio.h> int main(void) { float a, b, c, delta, x1, x2; printf("nhap 3 so a, b, c:\n"); scanf("%f%f%f", &a, &b, &c); delta = b*b - 4*a*c; if (a == 0) { if ((b == 0) && ( c == 0)) { printf("phuong vo so nghiem\n"); } else if ((b != 0) && (c == 0)) { printf( "phuong trinh co nghiem bang 0\n"); } else if (( b == 0) && (c != 0)) { printf("phuong trinh vo nghiem"); } } else if (a != 0) { if (delta < 0) { printf("phuong trinh vo nghiem"); } else if (delta == 0) { printf("phuong trinh co nghiem kep x1 = x2 =", -b/(2*a)); } else if( delta > 0 ) { x1 = ((-b + sqrt(delta)) / (2*a)); x2 = ((- b - sqrt(delta)) / (2*a)); printf("phuong trinh co 2 nghiem phan biet %f va %f", x1, x2); } } }
true
da2b8dd9b0ff4489170032a741946c1c8ba172aa
C++
Mukund-Raj/C-plus-plus-Programs
/gemstones_hackerrank.cpp
UTF-8
851
2.625
3
[]
no_license
#include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; main() { int flag=0; int gemstones=0; vector<string>st(0); st.push_back("hrbbwaacqlobwmrdzb"); st.push_back("baccd"); st.push_back("eeabg"); //st.push_back("oafhdlasd"); for(int i=0;i<st.size();i++) { sort(st[i].begin(),st[i].end()); } //cout<<max; for(int i=0;i<st.size();i++) { cout<<st[i]<<endl; } size_t found; int i=0; //for(int i=0;i<st[0].length();i++) while(i<st[0].length()) { if(st[0][i]==st[0][i+1]) { st[0].erase(st[0].begin()+i); } else i++; } cout<<st[0]; for(int i=0;i<st[0].length();i++) { for(int j=1;j<st.size();j++) { found=st[j].find(st[0][i]); if(found == -1) { flag=1; break; } } if(flag==0) { gemstones++; } flag=0; } cout<<gemstones; return 0; }
true
cfcf1a610e26ff91f999167b7f1d16692bb23258
C++
dhirsbrunner/phosg
/KDTree.hh
UTF-8
3,029
2.90625
3
[ "MIT" ]
permissive
#pragma once #include <stdint.h> #include <deque> #include <memory> #include <vector> #include <sys/types.h> template <typename CoordType, size_t dimensions, typename ValueType> class KDTree { public: struct Point { CoordType coords[dimensions]; Point() = default; bool operator==(const Point& other); bool operator!=(const Point& other); }; private: struct Node { Point pt; size_t dim; Node* before; Node* after; // technically after_or_equal Node* parent; ValueType value; Node(Node* parent, const Point& pt, size_t dim, const ValueType& v); template<typename... Args> Node(const Point& pt, Args&&... args); }; Node* root; size_t node_count; // TODO: make this not recursive static size_t count_subtree(const Node* n); static size_t depth_recursive(Node* n, size_t depth); void collect_into(Node* n, std::vector<Node*>& ret); void link_node(Node* new_node); bool delete_node(Node* n); Node* find_subtree_min_max(Node* n, size_t target_dim, bool find_max); public: class Iterator : public std::iterator< std::input_iterator_tag, std::pair<Point, ValueType>, ssize_t, const std::pair<Point, ValueType>*, std::pair<Point, ValueType>&> { public: explicit Iterator(Node* n); Iterator& operator++(); Iterator operator++(int); bool operator==(const Iterator& other) const; bool operator!=(const Iterator& other) const; const std::pair<Point, ValueType>& operator*() const; const std::pair<Point, ValueType>* operator->() const; private: std::deque<Node*> pending; std::pair<Point, ValueType> current; friend class KDTree; }; // TODO: figure out if this can be generalized with some silly template // shenanigans. for now we just implement some common cases and assert at // runtime that the right one is called. (for some reason C-style varagrs // doesn't work, and it's not safe anyway if the caller passes the wrong // argument count) static Point make_point(CoordType x); static Point make_point(CoordType x, CoordType y); static Point make_point(CoordType x, CoordType y, CoordType z); static Point make_point(CoordType x, CoordType y, CoordType z, CoordType w); KDTree(); ~KDTree(); // TODO: be unlazy KDTree(const KDTree&) = delete; KDTree(KDTree&&) = delete; KDTree& operator=(const KDTree&) = delete; KDTree& operator=(KDTree&&) = delete; Iterator insert(const Point& pt, const ValueType& v); template <typename... Args> Iterator emplace(const Point& pt, Args&&... args); bool erase(const Point& pt, const ValueType& v); void erase_advance(Iterator& it); const ValueType& at(const Point& pt) const; bool exists(const Point& pt) const; std::vector<std::pair<Point, ValueType>> within(const Point& low, const Point& high) const; bool exists(const Point& low, const Point& high) const; size_t size() const; size_t depth() const; Iterator begin() const; Iterator end() const; }; #include "KDTree-inl.hh"
true
b1b27f54f888d7621c96e6305efcd36f9b8c66b0
C++
ImRohan7/MovementAlgorithms
/AIMovementAlgorithms/AIMovementAlgorithms/KinemSeek.cpp
UTF-8
1,822
2.828125
3
[]
no_license
#include "KinemSeek.h" #include <random> #define MaxRotation 5.0f // max rotation velocity // for no arrival physics::SteeringOutput AI::KinemSeek::getSteering() { physics::SteeringOutput steering; ofVec2f dir = (mTarget.mPosition - mCharacter.mPosition).normalize(); // get vel dir steering.mLinear = dir * mMaxSpeed; return steering; } // with dynamic arrive physics::SteeringOutput AI::KinemSeek::getSteeringForArrival() { physics::SteeringOutput steering; ofVec2f dir = mTarget.mPosition - mCharacter.mPosition; // get vel dir float distance = dir.length(); float targetSpeed = 0.0f; ofVec2f targetVel; // if we already reached if (distance < mTargetRadArrive) return steering; // if outside slow rad then we go max velocity if (distance > mSlowRadArrive) targetSpeed = mMaxSpeed; // else we scale the speed with the distance remaining else targetSpeed = mMaxSpeed * (distance / mSlowRadArrive); // targetVel = dir.normalize(); targetVel *= targetSpeed; // get acceleration dir steering.mLinear = targetVel - mCharacter.mVelocity; //steering.mLinear = targetVel; steering.mLinear /= mTimeTotargetArrive; // clamp acceleration if (steering.mLinear.length() > mMaxAccel) { steering.mLinear.normalize(); steering.mLinear *= mMaxAccel; } steering.mAngular = 0; return steering; } // wandering physics::SteeringOutput AI::KinemSeek::getSteeringForWandering() { physics::SteeringOutput steering; float x = cos(mCharacter.mOrientation); float y = sin(mCharacter.mOrientation); steering.mLinear = mMaxSpeed * ofVec2f(x, y); float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); steering.mAngular = (rand()%2 == 0) ? r : -r; steering.mAngular *= mMaxRotat; return steering; }
true
772ee823be74f5ed3b0f7a856dd1bf7a5e7b644b
C++
MdAkdas/My_Codes
/Coding Blocks Course/Array/next_permutation.cpp
UTF-8
438
2.734375
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { int t; cin>>t; string s; while(t--) { s.clear(); int n; cin>>n; int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; s+=(a[i]+'0'); } //cout<<s<<endl; next_permutation(s.begin(), s.end()); //cout<<s; for(int i=0;i<n;i++) { cout<<s[i]-'0'<<" "; } cout<<endl; } return 0; }
true
0e2c81e48998cfb69dd69cfb5dd529764b855c6e
C++
Loptt/cplus-programs
/Programs/Alg/ronda2.cpp
UTF-8
921
3.28125
3
[]
no_license
#include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; int height(TreeNode *r) { if (r == nullptr) return 0; int leftHeight = height(r->left); int rightHeight = height(r->right); return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1; } int diameterH(TreeNode *r) { if (r == nullptr) return 0; int diameter = height(r->left) + height(r->right); int leftDiameter = diameterH(r->left); int rightDiameter = diameterH(r->right); return ((diameter > leftDiameter) ? (diameter > rightDiameter ? diameter : rightDiameter) : (leftDiameter > rightDiameter ? leftDiameter : rightDiameter)); } int diameterOfBST(TreeNode* r) { return diameterH(r); } int main() { return 0; }
true
c7411a26875da6f7396f51fd6c6c21617e5b97dd
C++
elvircrn/ccppcodes
/matrix_multiplication.cpp
UTF-8
757
2.65625
3
[]
no_license
/* 3 1 3 3 5 5 4 35 */ #include <iostream> #include <cstdio> #include <cstdlib> using namespace std; const int inf = 1<<28; int dp [1000] [1000], a [1000], b [1000], n; int main () { scanf ("%d", &n); for (int i = 0; i < 999; i++) for (int j = 0; j < 999; j++) if (i == j) continue; else dp [i] [j] = inf; for (int i = 0; i < n; i++) cin>>a [i]>>b [i]; cout<<endl; for (int i = 2; i <= n; i++) { for (int j = 0; j < n - i + 1; j++) { for (int k = j; k < j + i; k++) { dp [j] [j + i - 1] = min (dp [j] [j + i - 1], dp [j] [k] + dp [k + 1] [j + i - 1] + a [j] * b [k] * b [j + i - 1]); } } } printf ("%d \n", dp [0] [n - 1]); return 0; }
true
1e264b9c2069f619a79e876010d5652fc4afceff
C++
EnricoCorsaro/DIAMONDS
/demos/demoFive2DGaussians.cpp
UTF-8
6,564
2.671875
3
[ "MIT" ]
permissive
// // Compile with: // clang++ -o demoFive2DGaussians demoFive2DGaussians.cpp -L../build/ -I ../include/ -l diamonds -stdlib=libc++ -std=c++11 -Wno-deprecated-register // #include <cstdlib> #include <iostream> #include <iomanip> #include <fstream> #include "Functions.h" #include "File.h" #include "MultiEllipsoidSampler.h" #include "KmeansClusterer.h" #include "EuclideanMetric.h" #include "Prior.h" #include "UniformPrior.h" #include "NormalPrior.h" #include "Results.h" #include "Ellipsoid.h" #include "ZeroModel.h" #include "FerozReducer.h" #include "PowerlawReducer.h" #include "demoFive2DGaussians.h" #include "PrincipalComponentProjector.h" int main(int argc, char *argv[]) { ArrayXXd data; // Creating dummy arrays for the covariates and the observations. // They're not used because we compute our Likelihood directly. ArrayXd covariates; ArrayXd observations; // ------------------------------------------------------------------- // ----- First step. Set up the models for the inference problem ----- // ------------------------------------------------------------------- // Set up a dummy model. This won't be used because we're computing // the Likelihood directly, but the Likelihood nevertheless expects a model in // its constructor. ZeroModel model(covariates); // ------------------------------------------------------- // ----- Second step. Set up all prior distributions ----- // ------------------------------------------------------- int Ndimensions = 2; // Number of free parameters (dimensions) of the problem vector<Prior*> ptrPriors(1); ArrayXd parametersMinima(Ndimensions); ArrayXd parametersMaxima(Ndimensions); parametersMinima << -0.7, -0.7; // Centroid x direction, Centroid y direction parametersMaxima << +1.0, +1.0; UniformPrior uniformPrior(parametersMinima, parametersMaxima); ptrPriors[0] = &uniformPrior; // ----------------------------------------------------------------- // ----- Third step. Set up the likelihood function to be used ----- // ----------------------------------------------------------------- Multiple2DGaussiansLikelihood likelihood(observations, model); // ------------------------------------------------------------------------------- // ----- Fourth step. Set up the K-means clusterer using an Euclidean metric ----- // ------------------------------------------------------------------------------- EuclideanMetric myMetric; int minNclusters = 1; int maxNclusters = 6; int Ntrials = 10; double relTolerance = 0.01; bool printNdimensions = false; PrincipalComponentProjector projector(printNdimensions); bool featureProjectionActivated = true; KmeansClusterer kmeans(myMetric, projector, featureProjectionActivated, minNclusters, maxNclusters, Ntrials, relTolerance); // --------------------------------------------------------------------- // ----- Sixth step. Configure and start nested sampling inference ----- // --------------------------------------------------------------------- bool printOnTheScreen = true; // Print results on the screen int initialNobjects = 200; // Initial number of active points evolving within the nested sampling process. int minNobjects = 200; // Minimum number of active points allowed in the nesting process. int maxNdrawAttempts = 20000; // Maximum number of attempts when trying to draw a new sampling point. int NinitialIterationsWithoutClustering = 100; // The first N iterations, we assume that there is only 1 cluster. int NiterationsWithSameClustering = 20; // Clustering is only happening every X iterations. double initialEnlargementFraction = 10.0; // Fraction by which each axis in an ellipsoid has to be enlarged. // It can be a number >= 0, where 0 means no enlargement. double shrinkingRate = 0.2; // Exponent for remaining prior mass in ellipsoid enlargement fraction. // It is a number between 0 and 1. The smaller the slower the shrinkage // of the ellipsoids. double terminationFactor = 0.05; // Termination factor for nesting loop. MultiEllipsoidSampler nestedSampler(printOnTheScreen, ptrPriors, likelihood, myMetric, kmeans, initialNobjects, minNobjects, initialEnlargementFraction, shrinkingRate); double tolerance = 1.e2; double exponent = 0.4; PowerlawReducer livePointsReducer(nestedSampler, tolerance, exponent, terminationFactor); string outputPathPrefix = "demoFive2DGaussians_"; nestedSampler.run(livePointsReducer, NinitialIterationsWithoutClustering, NiterationsWithSameClustering, maxNdrawAttempts, terminationFactor, 0, outputPathPrefix); nestedSampler.outputFile << "# List of configuring parameters used for the ellipsoidal sampler and X-means" << endl; nestedSampler.outputFile << "# Row #1: Minimum Nclusters" << endl; nestedSampler.outputFile << "# Row #2: Maximum Nclusters" << endl; nestedSampler.outputFile << "# Row #3: Initial Enlargement Fraction" << endl; nestedSampler.outputFile << "# Row #4: Shrinking Rate" << endl; nestedSampler.outputFile << minNclusters << endl; nestedSampler.outputFile << maxNclusters << endl; nestedSampler.outputFile << initialEnlargementFraction << endl; nestedSampler.outputFile << shrinkingRate << endl; nestedSampler.outputFile.close(); // ------------------------------------------------------- // ----- Last step. Save the results in output files ----- // ------------------------------------------------------- Results results(nestedSampler); results.writeParametersToFile("parameter"); results.writeLogLikelihoodToFile("logLikelihood.txt"); results.writeEvidenceInformationToFile("evidenceInformation.txt"); results.writePosteriorProbabilityToFile("posteriorDistribution.txt"); double credibleLevel = 68.3; bool writeMarginalDistributionToFile = true; results.writeParametersSummaryToFile("parameterSummary.txt", credibleLevel, writeMarginalDistributionToFile); // That's it! return EXIT_SUCCESS; }
true
2e61b6f7e14b79ed876af0296f1a2e6f71f3eee3
C++
sicwea001/shiqw_source
/Beverage/mocha.h
UTF-8
701
3.265625
3
[]
no_license
#ifndef MOCHA_H #define MOCHA_H #include "condiment_decorator.h" class Mocha : public CondimentDecorator { public: Mocha(Beverage* beve) { beverage = beve; // 想办法让被装饰者被记录到实例变量中。这里做法是:把饮料当作构造器的参数, // 再由构造器将此饮料记录在实例变量中。 } QString getDescription() { return beverage->getDescription()+", Mocha"; // 描述:帮助这杯饮料都有什么材料 } double cost() { return 0.20 + beverage->cost(); // 0.2是摩卡的价钱,加上被装饰的价钱 } private: Beverage* beverage; }; #endif // MOCHA_H
true
4fe33e257ac346fb0d9343b6f79f0140fd8104fc
C++
douglasralmeida/pp-proj
/src/test-array.cc
UTF-8
944
3.546875
4
[]
no_license
/* ** Projeto de Algoritmos Paralelos ** Namespace Array - TESTE */ #include <iostream> #include "array.hpp" #define ARRAY_SIZE 10 using namespace std; int main() { double* source; double* dest; cout << "Teste de alocacao de vetores" << endl; cout << "============================" << endl << endl; cout << "Alocando vetor1..." << endl; source = new double[ARRAY_SIZE]; dest = new double[ARRAY_SIZE]; for (int i = 0; i < ARRAY_SIZE; i++) source[i] = (double)2*i; cout << endl << "Vetor de origem:" << endl; Array::show(source, ARRAY_SIZE); cout << endl << "Copiando vetor1 para vetor2..." << endl; for (int i = 0; i < ARRAY_SIZE; i++) Array::copy(source, dest, ARRAY_SIZE); cout << endl << "Vetor de destino:" << endl; Array::show(dest, ARRAY_SIZE); cout << endl << "Finalizando..." << endl; delete source; delete dest; exit(EXIT_SUCCESS); }
true
a36eb6ad042167c8ca8c50caec90a63a135c4c05
C++
Rudthaky/lessons
/lesson73.cpp
UTF-8
1,278
3.828125
4
[]
no_license
#include <iostream> #include <string> using namespace std; /* * Что такое класс * Что такое объект класса */ class Human //class - пользовательский тип данных { public: //модификатор доступа int age; //поле класса int weight; string name; }; class Point { public: int X; int Y; int Z; }; int main() { Point a; //создание преременной "а" типа Point, a - объект класа Point a.X = 1; //передаем в "а", параметр "Х", значение координаты по Х a.Y = 3; a.Z = 5; cout << a.X << " " << a.Y << " " << a.Z << endl; Human firstHuman; firstHuman.age = 30; firstHuman.name = "Ivanov Ivan Ivanovych"; firstHuman.weight = 100; cout << firstHuman.name << "\tage = " << firstHuman.age << "\tweight = " << firstHuman.weight << endl; Human secondHuman; secondHuman.age = 18; secondHuman.name = "Petrov Petr Petrovich"; secondHuman.weight = 65; cout << secondHuman.name << "\tage = " << secondHuman.age << "\tweight = " << secondHuman.weight << endl; return 0; }
true
2d1694801fcb6560bd8c9af62acdc2b92c16fc69
C++
ibradam/voronoi
/include/voronoi/voronoi_cell.hpp
UTF-8
1,068
2.53125
3
[]
no_license
/********************************************************************** * PACKAGE : voronoi * COPYRIGHT: (C) 2015, Ibrahim Adamou, Bernard Mourrain, Inria **********************************************************************/ #pragma once #include <geometrix/regularity.hpp> #include <geometrix/tmsh_cell.hpp> //==================================================================== /*! * \brief The voronoi_cell struct */ struct voronoi_cell : mmx::tmsh_cell<3> { typedef double C; typedef voronoi_cell Cell; public: voronoi_cell(): tmsh_cell<3>() {} voronoi_cell(const voronoi_cell& cl): tmsh_cell<3>(cl) {} void add_active(int i) { //mdebug()<<"add active"<<i<< "size"<<m_active.size(); if(std::find(m_active.begin(), m_active.end(),i) == m_active.end()) m_active.push_back(i); //mdebug()<<">add active"<<i<< "size"<<m_active.size(); } unsigned nba () const { return m_active.size(); } std::vector<int> m_active; }; //====================================================================
true
3be620433dfa3b4e6c490e4ef72d656d21a03c8b
C++
lxwgcool/EigenDel
/ShareLibrary/clsvcf1000genome.cpp
UTF-8
8,253
2.578125
3
[]
no_license
#include "clsvcf1000genome.h" #include <fstream> #include <iostream> #include <unistd.h> ClsVcf1000Genome::ClsVcf1000Genome() { } int ClsVcf1000Genome::ParseVcf(string strVcfFile, string strSampleName) { if(::access(strVcfFile.c_str(), 0) != 0) { cout << "Error: VCF File does not existed!" << endl; return 1; } vector<St_SV> vSV; vSV.clear(); St_SV stSV; ifstream ifsVcf; ifsVcf.open(strVcfFile.c_str()); string strLine; int iSampleIndex = -1; vector<string> vSeq; while(!ifsVcf.eof()) { getline(ifsVcf, strLine); //Skip the comment line if(strLine.substr(0, 1) == "#") { if(strSampleName != "" && strLine.substr(0, 6) == "#CHROM") { //Try to find the column index of specific person --> iSampleIndex = GetColNumber(strLine, strSampleName); //<-- } continue; } stSV.Clear(); //The regular line string::size_type iStart = 0; string::size_type iOffset = 0; int iLen = 0; string strTmp = ""; // 1. 1st column --> Chome Index iOffset = strLine.find('\t', iStart); iLen = iOffset - iStart; strTmp = strLine.substr(iStart, iLen); stSV.strChrom = strTmp; //atoi(strTmp.c_str()); iStart = iOffset + 1; // 2: 2nd column --> Position iOffset = strLine.find('\t', iStart); iLen = iOffset - iStart; strTmp = strLine.substr(iStart, iLen); stSV.iPos = atoi(strTmp.c_str()); iStart = iOffset + 1; // 3: 4th column --> Ref Seq iOffset = strLine.find('\t', iStart); iStart = iOffset + 1; iOffset = strLine.find('\t', iStart); iLen = iOffset - iStart; strTmp = strLine.substr(iStart, iLen); stSV.strRef = strTmp; iStart = iOffset + 1; // 4: 8th column --> Info for(int i=0; i<3; i++) { iOffset = strLine.find('\t', iStart); iStart = iOffset + 1; } iOffset = strLine.find('\t', iStart); iLen = iOffset - iStart; strTmp = strLine.substr(iStart, iLen); //(1) iLen -- SVLEN iStart = strTmp.find("SVLEN"); if(iStart != string::npos) // find it { iStart += 5 + 1; // length (SVLEN) is 5, and "=" is 1 iOffset = strTmp.find(";", iStart); if(iOffset == string::npos) // going to the end of current sequence { iOffset = strTmp.length(); } iLen = iOffset - iStart; stSV.iLen = atoi(strTmp.substr(iStart, iLen).c_str()); } //(2) SVType -- SVTYPE iStart = strTmp.find("SVTYPE"); if(iStart != string::npos) // find it { iStart += 6 + 1; // length (SVTYPE) is 6, and "=" is 1 iOffset = strTmp.find(";", iStart); if(iOffset == string::npos) // going to the end of current sequence { iOffset = strTmp.length(); } iLen = iOffset - iStart; stSV.strType = strTmp.substr(iStart, iLen); } //(3) iEnd -- ;END= iStart = strTmp.find(";END="); if(iStart != string::npos) // find it { iStart += 5; // length (;END=) is 5 iOffset = strTmp.find(";", iStart); if(iOffset == string::npos) // going to the end of current sequence { iOffset = strTmp.length(); } iLen = iOffset - iStart; stSV.iEnd = atoi(strTmp.substr(iStart, iLen).c_str()); } //For the specific sample --> if(iSampleIndex != -1) { vSeq.clear(); SpliteSeq(strLine, '\t', vSeq); if(vSeq.size() > iSampleIndex) { stSV.stSample.strName = strSampleName; //Check Genotype --> string strSeq = vSeq[iSampleIndex]; //cout << "Genotype: " << strSeq << endl; if(strSeq == "." || strSeq == "0") // Why genotype sometimes is "." ?? { stSV.stSample.iGT1 = 0; stSV.stSample.iGT2 = 0; } else if(strSeq == "1") { stSV.stSample.iGT1 = 1; stSV.stSample.iGT2 = 0; } else if(strSeq == "2") { stSV.stSample.iGT1 = 1; stSV.stSample.iGT2 = 1; } else { stSV.stSample.iGT1 = atoi(strSeq.substr(0, 1).c_str()); stSV.stSample.iGT2 = atoi(strSeq.substr(2, 1).c_str()); } //<-- } } //<-- //put SV into vector vSV.push_back(stSV); } ifsVcf.close(); //Separate vSv to vGenoSv --> m_vChromSv.clear(); St_ChromSV stChromSv; for(vector<St_SV>::iterator itr = vSV.begin(); itr != vSV.end(); itr++) { bool bFindChrom = false; for(vector<St_ChromSV>::iterator itrChromSv = m_vChromSv.begin(); itrChromSv != m_vChromSv.end(); itrChromSv++) { if(itrChromSv->strChrom == itr->strChrom) { itrChromSv->vSv.push_back(*itr); bFindChrom = true; break; } } if(!bFindChrom) { stChromSv.Clear(); stChromSv.strChrom = itr->strChrom; stChromSv.vSv.push_back(*itr); m_vChromSv.push_back(stChromSv); } } vSV.clear(); //release heap //<-- return 0; } void ClsVcf1000Genome::GetDeletion(vector<St_ChromSV>& vChromSvDEL, string strSampleName, string strChrom) { if(m_vChromSv.empty()) return; vChromSvDEL.clear(); St_ChromSV stChromSvDEL; for(vector<St_ChromSV>::iterator itrChromSv = m_vChromSv.begin(); itrChromSv != m_vChromSv.end(); itrChromSv++) { if(strChrom == "") // This means we need to consider the whole geonome {} else { if(itrChromSv->strChrom != strChrom) continue; } stChromSvDEL.Clear(); stChromSvDEL.strChrom = itrChromSv->strChrom; for(vector<St_SV>::iterator itr = itrChromSv->vSv.begin(); itr != itrChromSv->vSv.end(); itr++) { if(itr->strType.find("DEL") != string::npos) //find it { if(strSampleName != "") { //Get the deletion only contained bystr SampleName if(itr->stSample.strName == strSampleName && (itr->stSample.iGT1 == 1 || itr->stSample.iGT2 == 1)) stChromSvDEL.vSv.push_back(*itr); } else stChromSvDEL.vSv.push_back(*itr); } } vChromSvDEL.push_back(stChromSvDEL); //Only need to record one chromosome if(strChrom != "") break; } } int ClsVcf1000Genome::GetColNumber(string& strSeq, string strSampleName) //Get Column Number { vector<string> vSeq; SpliteSeq(strSeq, '\t', vSeq); int iIndex = 0; int iSampleIndex = -1; for(vector<string>::iterator itr = vSeq.begin(); itr != vSeq.end(); itr++, iIndex++) { if(*itr == strSampleName) { iSampleIndex = iIndex; break; } } return iSampleIndex; } void ClsVcf1000Genome::SpliteSeq(string& strSeq, char cDelimiter, vector<string>& vSeq) { vSeq.clear(); string::size_type iOffset = 0; string::size_type iPos = 0; int iLen = 0; string strSubStr = ""; while(iPos != string::npos) { iPos = strSeq.find(cDelimiter, iOffset); if(iPos != string::npos) { iLen = iPos - iOffset; strSubStr = strSeq.substr(iOffset, iLen); vSeq.push_back(strSubStr); iOffset = iPos + 1; } } return; }
true
c0a7c448a051195e5cb1bb65b8ab7a815638cda0
C++
kailasspawar/DS-ALGO-PROGRAMS
/Trees/ConvertBinTreeintoDoublyLList.cpp
UTF-8
1,636
3.375
3
[]
no_license
#include<iostream> #include"bint.h" #include<deque> #include<stack> using namespace std; void push(bnode &head,bnode node) { node->right = head; node->left = NULL; if(head) head->left = node; head = node; } void printList(bnode head) { while(head) { cout<<head->data<<" "; head = head->right; } } void spiralOrder(bnode root) { if(!root) return ; deque<bnode>q; stack<bnode>s; q.push_front(root); int level = 0; while(!q.empty()) { int nodeCount = q.size(); if(level&1) { while(nodeCount > 0) { bnode node = q.front(); q.pop_front(); s.push(node); if(node->left) q.push_back(node->left); if(node->right) q.push_back(node->right); nodeCount--; } } else { while(nodeCount > 0) { bnode node = q.back(); q.pop_back(); s.push(node); if(node->right) q.push_front(node->right); if(node->left) q.push_front(node->left); nodeCount--; } } level++; } bnode head = NULL; while(!s.empty()) { push(head,s.top()); s.pop(); } cout<<"Created Dll is \n"; printList(head); } int main() { bnode root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); //root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); spiralOrder(root); }
true
2fddac08fc9e8123111374a0202804cefc62d7c7
C++
aLagoG/kygerand
/microsoft2017/first.cpp
UTF-8
1,704
3.4375
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> #include <string> using namespace std; //Longest Palindromic Subsequence O(n^2) int countOnes(int value){ int count=0; while(value){ value&=(value-1); count++; } return count; } int main(){ int n; scanf("%d",&n); // char seq[] = "alaaabaaabbbbaaaa"; // int n = strlen(seq); for(int i=0;i<n;i++){ string a,b; cout<<"Group "<<i+1<<":"<<" "; cin>>a>>b; if(a[0]!=b[0]){ if((a[0]=='1'&&b[0]=='2')||(a[0]=='2'&&b[0]=='1')){ cout<<"3"; } if((a[0]=='2'&&b[0]=='3')||(a[0]=='3'&&b[0]=='2')){ cout<<"1"; } if((a[0]=='1'&&b[0]=='3')||(a[0]=='3'&&b[0]=='1')){ cout<<"2"; } }else{ cout<<a[0]; } if(a[1]!=b[1]){ if((a[1]=='E'&&b[1]=='S')||(a[1]=='S'&&b[1]=='E')){ cout<<"F"; } if((a[1]=='E'&&b[1]=='F')||(a[1]=='F'&&b[1]=='E')){ cout<<"S"; } if((a[1]=='F'&&b[1]=='S')||(a[1]=='S'&&b[1]=='F')){ cout<<"E"; } }else{ cout<<a[1]; } if(a[2]!=b[2]){ if((a[2]=='R'&&b[2]=='P')||(a[2]=='P'&&b[2]=='R')){ cout<<"G"; } if((a[2]=='R'&&b[2]=='G')||(a[2]=='G'&&b[2]=='R')){ cout<<'P'; } if((a[2]=='P'&&b[2]=='G')||(a[2]=='G'&&b[2]=='P')){ cout<<"R"; } }else{ cout<<a[2]; } if(a[3]!=b[3]){ if((a[3]=='O'&&b[3]=='S')||(a[3]=='S'&&b[3]=='O')){ cout<<"D"; } if((a[3]=='O'&&b[3]=='D')||(a[3]=='D'&&b[3]=='O')){ cout<<'S'; } if((a[3]=='S'&&b[3]=='D')||(a[3]=='D'&&b[3]=='S')){ cout<<"O"; } }else{ cout<<a[3]; } cout<<endl; } return 0; }
true
14dc0f1a8e30a16b5155b1a3899fdb4abb41ef1f
C++
imnu-ciec-20171106168/Two-Times
/Chess.cpp
GB18030
1,880
2.578125
3
[]
no_license
// Chess.cpp: implementation of the CChess class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MyTask.h" #include "Chess.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CChess::CChess() { type=0; num=0; } CChess::~CChess() { } CChess& CChess::operator=(CChess& p) { num=p.num; type=p.type; pointB=p.pointB; pointW=p.pointW; return* this; } void CChess::Serialize(CArchive &ar) { if(ar.IsStoring()) { ar<<num; ar<<type; ar<<pointB; ar<<pointW; } else { ar>>num; ar>>type; ar>>pointB; ar>>pointW; } } CPoint CChess::PointToStonePos(CPoint point) { int xGrid=26,yGrid=26; int xpt=(int)floor(point.x/xGrid); int ypt=(int)floor(point.y/yGrid); CPoint pt(xpt,ypt); return pt; } CPoint CChess::PointToStonePos(int m,int n) { int xGrid=26,yGrid=26; int xpt=m*xGrid+7; int ypt=n*yGrid+9; CPoint pt(xpt,ypt); return pt; } void CChess::DisplayStone(CDC* pDC,UINT IDResource,CPoint point) { CBitmap Bitmap; Bitmap.LoadBitmap(IDResource);//λͼװڴ CDC MemDC; MemDC.CreateCompatibleDC(pDC); //ڴ豸 CBitmap *OldBitmap=MemDC.SelectObject(&Bitmap); BITMAP bm; //BITMAPṹ Bitmap.GetBitmap(&bm); //ȡλͼϢ if(IDResource==IDB_MASK) pDC->BitBlt(point.x,point.y,bm.bmWidth,bm.bmHeight, &MemDC,0,0,SRCAND);//λͼ else pDC->BitBlt(point.x,point.y,bm.bmWidth,bm.bmHeight,&MemDC,0,0,SRCPAINT);//λͼ pDC->SelectObject(OldBitmap);//ָ豸 MemDC.DeleteDC(); }
true
097112d8a3f49e603681ed5d11ca23f07fa1570e
C++
virtyaluk/leetcode
/problems/38/solution.cpp
UTF-8
744
3.109375
3
[]
no_license
class Solution { public: string countAndSay(int n) { if (n == 1) { return "1"; } if (n == 2) { return "11"; } string curAns = countAndSay(n - 1), ans; int cnt = 1; for (int i = 1; i < size(curAns); i++) { if (curAns[i] != curAns[i - 1]) { ans.push_back('0' + cnt); ans.push_back(curAns[i - 1]); cnt = 1; } else { cnt++; } if (i == size(curAns) - 1) { ans.push_back('0' + cnt); ans.push_back(curAns[i]); } } return ans; } };
true
f0ad7124b67f1a82f5a75e792a8f76fddba75c9a
C++
justinzliu/Data-Structures-II
/A4/a4.cpp
UTF-8
929
3.484375
3
[]
no_license
/* 301070053 jzl1 Justin Liu ** a4.cpp ** Assignment 4, CMPT-225 ** ** Reads a sequence of integers (in the range of int's) from standard in; ** It is interpreted as two lists, separated by a single 0 **/ #include <iostream> #include "heap.h" #include "HCompare.h" using namespace std; int main() { long double x ; bool List2 = false; //list 1 Heap heap1; //list 2 Heap heap2; cin >> x; //grab values from text specified in stdin while( !cin.eof() ){ if (x == 0) { List2 = true ; } //insert into list1 else if (!List2) { heap1.insert(x,x); } //insert into list2 else { heap2.insert(x,x); } cin >> x; } x = HCompare(heap1,heap2); cout << "301070053 jzl1 Justin Liu\n"; if (x == -1) { cout << "None" << endl; } else { cout << x << endl; } return 0; }
true
42d66ff39193f01e347b0442278f6e8a491b9d9a
C++
15831944/TCIDE
/src/match/my/MyVarList.h
GB18030
3,553
2.84375
3
[]
no_license
/////////////////////////////////2009.12.19 Ф㷶޶////////////////////////// #ifndef MYVARLIST_H #define MYVARLIST_H #include"MyVar.h" #include"match/My/MyValue.h" MATCH_CPP_NAMESPACE_BEGIN //˱Ľڵ struct varNode { MyVar * var; //ָ varNode * next; //ָһڵ varNode() { var=0; next=0; } }; //ﶨһ,Ҫֲ class PARSERS_EXPORT MyVarList { public: // //:캯 //˵: // MyVarList(); // ~MyVarList(); //:һڵ // //ֵ: // //void ޷ // //˵: // //var varNode * ڵ void appendVar(varNode *var); //ڸһ вѡ һ //:һڵ // //ֵ: // //MyVar * ָ // //˵: // //name const XMLCh * const MyVar *findVarByName(const XMLCh * const name); //жһǷ bool VarNameExist(const XMLCh * const name) const; //:رͷڵ //ֵ:: // //const varNode * бͷڵ const varNode *getListHead() const; // //:رβڵ //ֵ:: // //const varNode * бβڵ const varNode *getListEnd() const; //:ݱ,޸ıֵ // //ֵ: // //bool trueʾ޸ijɹ,falseʾ޸ʧ // //˵: // //name const XMLCh* const //toSet const XMLCh* const ֵַʽ //bool setVarValueByName(const XMLCh * const name,const XMLCh * const value,VARTYPE type); //:ݱ,޸ıֵ // //ֵ: // //bool trueʾ޸ijɹ,falseʾ޸ʧ // //˵: // //name const XMLCh* const //toSet const MyValue* const ֵMyValue͵ָ bool setVarValueByName(const XMLCh * const name,const _variant_t * const value); void reset(); private: //ʼ void initialize(); //,еıڴ void cleanUp(); varNode * fVarHead; //ͷڵ varNode * fVarEnd; //βڵ /** * Copy constructor */ MyVarList(const MyVarList& node); MyVarList& operator=(const MyVarList& toAssign); }; MATCH_CPP_NAMESPACE_END #endif
true
bdb06ef39e235a6d8c01b1e580d8f896e489689d
C++
joker-hyt/gvoice_use
/gvoice_test/util/crypto/hash.h
UTF-8
738
2.96875
3
[]
no_license
#pragma once inline unsigned int hash_value(int v) { return static_cast<unsigned int>(v); } inline unsigned int hash_value(unsigned int v) { return static_cast<unsigned int>(v); } template <class T> inline void hash_combine(unsigned int& seed, T const& v) { seed ^= hash_value(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); } template <class It> inline unsigned int hash_range(It first, It last) { unsigned int seed = 0; for(; first != last; ++first) { hash_combine(seed, *first); } return seed; } template <class It> inline unsigned int hash_range(unsigned int& seed, It first, It last) { for(; first != last; ++first) { hash_combine(seed, *first); } return seed; }
true
f5ed886951ce0804c53587764fa1db2e4a432d08
C++
CombustibleLemons/digifab
/temperature_control/temperature_control.ino
UTF-8
6,214
2.8125
3
[ "MIT" ]
permissive
/* * Inputs ADC Value from Thermistor and outputs Temperature in Celsius * requires: include <math.h> * Utilizes the Steinhart-Hart Thermistor Equation: * Temperature in Kelvin = 1 / {A + B[ln(R)] + C[ln(R)]3} * where A = 0.001129148, B = 0.000234125 and C = 8.76741E-08 * * These coefficients seem to work fairly universally, which is a bit of a * surprise. * * Schematic: * [Ground] -- [10k-pad-resistor] -- | -- [thermistor] --[Vcc (5 or 3.3v)] * | * Analog Pin 0 * * In case it isn't obvious (as it wasn't to me until I thought about it), the analog ports * measure the voltage between 0v -> Vcc which for an Arduino is a nominal 5v, but for (say) * a JeeNode, is a nominal 3.3v. * * The resistance calculation uses the ratio of the two resistors, so the voltage * specified above is really only required for the debugging that is commented out below * * Resistance = PadResistor * (1024/ADC -1) * * I have used this successfully with some CH Pipe Sensors (http://www.atcsemitec.co.uk/pdfdocs/ch.pdf) * which be obtained from http://www.rapidonline.co.uk. * */ #include <math.h> #define ThermistorPIN 0 // Analog Pin 0 // Steinhart-Hart Equation coefficients, generate using the following data //53000 Ohms = 23C //43500 Ohms = 27C //37500 Ohms = 30C //12000 Ohms = 100C //733 Ohms = 200C //1250 Ohms = 149C // New ABC //#define A 0.003759325431 //#define B 0.0010779671 //#define C -0.000004314127533 // Old ABC #define A 0.002177290523 #define B 0.00004984386308 #define C 0.0000005105364710 #include <PID_v1.h> #define RelayPin 5 // PID Stuff //Define Variables we'll be connecting to double Setpoint, Input, Output; //Specify the links and initial tuning parameters PID myPID(&Input, &Output, &Setpoint, 2, 5, 4, DIRECT); int WindowSize = 5000; unsigned long windowStartTime; // Thermistor stuff float vcc = 4.91; // only used for display purposes, if used // set to the measured Vcc. float pad = 9850; // balance/pad resistor value, set this to // the measured resistance of your pad resistor float thermr = 10000; // thermistor nominal resistance float Thermistor(int RawADC) { long Resistance; float Temp; // Dual-Purpose variable to save space. Resistance=pad*((1024.0 / RawADC) - 1); Temp = log(Resistance); // Saving the Log(resistance) so not to calculate it 4 times later Temp = 1 / (A + (B * Temp) + (C * Temp * Temp * Temp)); Temp = Temp - 273.15; // Convert Kelvin to Celsius // BEGIN- Remove these lines for the function not to display anything //Serial.print("ADC: "); //Serial.print(RawADC); //Serial.print("/1024"); // Print out RAW ADC Number //Serial.print(", vcc: "); //Serial.print(vcc,2); //Serial.print(", pad: "); //Serial.print(pad/1000,3); //Serial.print(" Kohms, Volts: "); //Serial.print(((RawADC*vcc)/1024.0),3); //Serial.print(", Resistance: "); //Serial.print(Resistance); //Serial.print(" ohms, "); // END- Remove these lines for the function not to display anything // Uncomment this line for the function to return Fahrenheit instead. //temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert to Fahrenheit return Temp; // Return the Temperature } int MotorControl = 5; void setup() { Serial.begin(115200); // HeaterControl pinMode(MotorControl, OUTPUT); // PID Controller windowStartTime = millis(); // Temperature to aim PID controller at Setpoint = 65.0; //tell the PID to range between 0 and the full window size myPID.SetOutputLimits(0, WindowSize); //turn the PID on myPID.SetMode(AUTOMATIC); } long previousMillis = 0; long interval = 200; void loop() { double temp; temp=Thermistor(analogRead(ThermistorPIN)); // read ADC and convert it to Celsius int heater_on = digitalRead(2); // Print on an interval unsigned long now = millis(); if(now - previousMillis > interval) { // save the last time you blinked the LED previousMillis = now; Serial.print("Celsius: "); Serial.print(temp,1); // display Celsius //temp = (temp * 9.0)/ 5.0 + 32.0; // converts to Fahrenheit //Serial.print(", Fahrenheit: "); //Serial.print(temp,1); // display Fahrenheit Serial.println(""); Serial.print(digitalRead(2)); Serial.print("\n"); } /************************************************ * turn the output pin on/off based on pid output ************************************************/ if(heater_on){ myPID.SetMode(AUTOMATIC); Input = temp; myPID.Compute(); if(now - windowStartTime>WindowSize) { //time to shift the Relay Window windowStartTime += WindowSize; } if(Output > now - windowStartTime) digitalWrite(RelayPin,HIGH); else digitalWrite(RelayPin,LOW); } else{ myPID.SetMode(MANUAL); if(now - windowStartTime>WindowSize) { //time to shift the Relay Window windowStartTime += WindowSize; } digitalWrite(MotorControl, LOW); } // delay(100); // Delay a bit... } /******************************************************** * PID RelayOutput Example * Same as basic example, except that this time, the output * is going to a digital pin which (we presume) is controlling * a relay. The pid is designed to output an analog value, * but the relay can only be On/Off. * * To connect them together we use "time proportioning * control" Tt's essentially a really slow version of PWM. * First we decide on a window size (5000mS say.) We then * set the pid to adjust its output between 0 and that window * size. Lastly, we add some logic that translates the PID * output into "Relay On Time" with the remainder of the * window being "Relay Off Time" ********************************************************/
true
13e3a3878031629eab4cb53be2968840895fc445
C++
svinniepoopy/mini_architectures
/lfu_cache/lfu_cache.cpp
UTF-8
5,732
3.5
4
[]
no_license
// least frequently used cache #include <iostream> #include <list> #include <utility> #include <unordered_map> #include <map> #include <vector> /* // use an unordered map as the cache containing the key and a pair of values // key : {val, <lru list iterator, map iterator>} // map: items ordered by frequency // list: items ordered by recent usage // get: update usage and frequency count // update frequency count: // get the freq it // remove item from the map using the frequency iterator // update map by incrementing frequency // save iterator // update usage count: // get the lru list list // move the item to the front // save iterator // update cache with new values of the freq iterator and the lru list iterator // put: add new item or if the item exists update // if the item exists replace the old value with the new and call get and ignore // the returned value // otherwise // do eviction // create a new entry in the cache // add frequency count // save the iterator // add usage count // save the iterator // update cache with the freq and lru list iterator // eviction: remove the key with the least frequency // locate the first entry in the map // if there are multiple entries in this list, select the item with the lower lru value // for this item remove it from frequency map // remove it from the lru list // remove it from the cache */ struct node { int val; int freq; std::list<int>::iterator it; std::list<std::list<int>::iterator>::iterator list_it; }; class LFUCache { public: LFUCache(int capacity):cap{capacity} {} int get(int key) { std::cout << "get " << key << '\n';; auto it = cache.find(key); if (it == cache.end()) { return -1; } // get the value int val = it->second.val; int freq = it->second.freq; std::cout << "val " << val << " freq " << freq << '\n'; // pair list_it, map_it auto list_it = it->second.it; // remove item from frequency map auto map_it = freq_map.find(freq); std::cout << "map it\n"; if (map_it->second.size()==1) { freq_map.erase(freq); } else { freq_map[freq].erase(it->second.list_it); } std::cout << "update lru list \n"; // update lru list lru_list.erase(list_it); lru_list.push_front(key); // update frequency map freq_map[freq+1].push_front(lru_list.begin()); auto map_list_it = freq_map.find(freq+1); // update cache cache[key] = node{val, freq+1, lru_list.begin(), map_list_it->second.begin()}; return val; } void evict() { if (freq_map.empty()) { return; } auto freq_map_it = freq_map.begin(); auto iter_list = freq_map_it->second; int evict_key; if (iter_list.size()>1) { evict_key = **std::prev(iter_list.end()); } else { evict_key = **iter_list.begin(); } auto lru_list_it = *std::prev(iter_list.end()); auto cache_it = cache.find(evict_key); std::cout << "evict key: " << evict_key << " evict val " << cache_it->second.val << '\n'; cache.erase(evict_key); lru_list.erase(lru_list_it); freq_map.begin()->second.pop_back(); } void put(int key, int value) { std::cout << "put key " << key << " val " << value << '\n'; auto it = cache.find(key); if (it != cache.end()) { auto list_it = it->second.it; // update lru list entry lru_list.erase(list_it); lru_list.push_front(key); int freq = it->second.freq; // update frequency auto map_it = freq_map.find(freq); if (map_it->second.size()==1) { freq_map.erase(freq); } else { freq_map[freq].erase(it->second.list_it); } freq_map[freq+1].push_front(lru_list.begin()); // update cache with new iterators auto map_list_it = freq_map.find(freq+1); cache.erase(key); std::cout << "put update key " << key << " value " << value << " new freq " << freq+1 << '\n'; cache[key] = {value, freq+1, lru_list.begin(), map_list_it->second.begin()}; } else { if (lru_list.size()==cap) { evict(); } // add the new key, val // add to lru list lru_list.push_front(key); // add to frequency map freq_map[1].push_front(lru_list.begin()); auto map_list_it = freq_map.find(1); std::cout << "k " << key << " " << " val " << value << '\n'; cache[key] = node{value, 1, lru_list.begin(), map_list_it->second.begin()}; } } private: using lst_it = std::list<int>::iterator; int cap; std::list<int> lru_list; // BST of freq to set of list iterators std::map<int, std::list<lst_it>> freq_map; // hash table of keys to val, list iterator and map iterator std::unordered_map<int, node> cache; }; int main() { LFUCache lfu{0}; /* lfu.put(1, 1); lfu.put(2, 2); int v = lfu.get(1); std::cout << "get(1) 1 == " << v << '\n'; lfu.put(3, 3); v = lfu.get(2); std::cout << "get(2) -1 == " << v << '\n'; v = lfu.get(3); std::cout << "get(3) 3 == " << v << '\n'; lfu.put(4, 4); v = lfu.get(1); std::cout << "get(1) -1 == " << v << '\n'; v = lfu.get(3); std::cout << "get(3) 3 == " << v << '\n'; v = lfu.get(4); std::cout << "get(4) 4 == " << v << '\n'; lfu.put(5,5); v = lfu.get(5); std::cout << "get(5) 5 == " << v << '\n'; lfu.put(6,6); lfu.put(7,7); v = lfu.get(6); std::cout << "get(6) 6 == " << v << '\n'; v = lfu.get(7); std::cout << "get(7) 7 == " << v << '\n'; lfu.put(3,1); lfu.put(2,1); lfu.put(2,2); lfu.put(4,4); int v = lfu .get(2); std::cout << v << '\n'; */ lfu.put(0,0); int v = lfu.get(0); return 0; }
true
32a54623af45f2ad9ab3ebc3bef1fe35e1b8bc43
C++
soachishti/Data-Structures-coded-in-CS201
/Intermediate/QueueUsingArray.cpp
UTF-8
2,081
3.59375
4
[]
no_license
#include <iostream> using namespace std; class Queue { public: int size, *data, *front = NULL, *rear = NULL; bool full; Queue(int s) { full = false; size = s; data = new int[size]; front = data; } void enQueue(int d) { int *tmp = (front == data) ? data + size - 1: front - 1; if (rear == tmp) { cout << "Queue is full" << endl; } else { if (rear == NULL) { rear = data; *rear = d; } else { if (rear == (data + size - 1)) rear = data; else rear++; *rear = d; } cout << d << "\t\t" << rear << endl; } } void deQueue(){ if (rear == NULL) { cout << "Queue is empty." << endl; } else { if (rear == front) rear = NULL; int tmp = *front; *front = -1; if (front == data + size - 1) front = data; else front++; cout << tmp << endl; } } void info () { cout << endl << endl; for (int i = 0 ; i < size ;i++) { if (rear == data + i) cout << "r"; if (front == data + i) cout << "f"; cout << "\t"; cout << *(data + i) << "\t\t" << data + i << endl; } cout << endl << endl; } }; int main () { Queue q(5); //q.deQueue(); // Empty q.enQueue(0); q.enQueue(1); q.enQueue(2); q.enQueue(3); q.enQueue(4); q.enQueue(5); // Full q.enQueue(6); // Full q.info(); q.deQueue(); q.deQueue(); q.deQueue(); q.deQueue(); q.deQueue(); q.deQueue(); // Empty q.info(); q.enQueue(6); q.enQueue(7); q.deQueue(); q.deQueue(); q.deQueue(); //Empty return 0; }
true
c74de27a8395b98e8461dc0da22454b2e550e31f
C++
AbhinavtiwarIdk/c_programming
/use of constant.cpp
UTF-8
763
2.8125
3
[]
no_license
#include <stdio.h> int main() { const int MonthsinYear=12; int Monthsintenyear=12*10; int MoneyGeneratedPerMonth; MoneyGeneratedPerMonth=500; printf("Hello, This code is designed by Manish Mathuria \n"); printf("The approximate yearly income will be: %d \n", MoneyGeneratedPerMonth * MonthsinYear); MoneyGeneratedPerMonth=600; printf("The approximate yearly income will be: %d \n", MoneyGeneratedPerMonth * MonthsinYear); MoneyGeneratedPerMonth=700; printf("The approximate yearly income will be: %d \n", MoneyGeneratedPerMonth * MonthsinYear); MoneyGeneratedPerMonth=1000; printf("The approximate ten year income will be: %d \n", MoneyGeneratedPerMonth * Monthsintenyear); return 0; }
true
87705bd959fe0065174763514ed1aa07844412b1
C++
Hongyan0627/Interview_questions
/138CopyListWithRandomPointer.h
UTF-8
953
3.265625
3
[]
no_license
// LeetCode // // Created by Hongyan on 01/10/17. // Copyright © 2017 Hongyan. All rights reserved. // class ListNode { int val; ListNode* next; ListNode(int x):val(x), next(NULL){} }; struct RandomListNode { int label; RandomListNode *next, *random; RandomListNode(int x):val(x), next(NULL), random(NULL) {} }; class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { if(!head) return NULL; RandomListNode* p = head; while(p) { RandomListNode* new_node = new RandomListNode(p->label); new_node->next = p->next; p->next = new_node; p = new_node->next; } p = head; while(p) { if(p->random) { p->next->random = p->random->next; } p = p->next->next; } RandomListNode dummy(0); dummy.next = head->next; p = head->next; while(head) { head->next = p->next; head = head->next; if(head) { p->next = head->next; p = p->next; } } return dummy.next; } }
true
8a30f7f25fe0ab7021c0ab2810ba41d7d6be1fa9
C++
samyak3/Algorithms
/Spoj/ToDo/IWGBS - 0110SS.cpp
UTF-8
625
3.125
3
[]
no_license
/* * IWGBS - 0110SS.cpp * * Created on: Oct 31, 2015 * Author: Admin */ #include<iostream> #include<vector> using namespace std; typedef unsigned long long ull; vector<ull>Wzero;//number of ways we can make a number from 1 and 0 which ends with zero vector<ull>Wone;//number of ways we can make a number from 1 and 0 which ends with one int N; int main() { cin >> N ; for(int i = 0; i <= N ; i++) { Wzero.push_back(0); Wone.push_back(0); } Wzero[1] = 1; Wone[1] = 1; for(int i = 2 ; i <= N ; i++) { Wzero[i] = Wone[i-1]; Wone[i] = Wone[i-1] + Wzero[i-1]; } cout<<Wzero[N] + Wone[N]<<endl; }
true
923ca680173b2000a769b76f922b009c707fc8f6
C++
wbrbr/drums
/src/arduino.cpp
UTF-8
875
3.328125
3
[ "MIT" ]
permissive
#include "arduino.hpp" #include <iostream> Arduino::Arduino(): serial("/dev/ttyACM0") { } Arduino::~Arduino() { } bool Arduino::isMessageAvailable() { return serial.getAvailable() >= 8; } Message Arduino::readMessage() { char buf[8]; serial.readBytes(buf, 8); Message msg; msg.type = (uint16_t)buf[0] * 256 + (uint16_t)buf[1]; msg.arg1 = (uint16_t)buf[2] * 256 + (uint16_t)buf[3]; msg.arg2 = (uint16_t)buf[4] * 256 + (uint16_t)buf[5]; msg.arg3 = (uint16_t)buf[6] * 256 + (uint16_t)buf[7]; return msg; } void Arduino::writeMessage(Message msg) { char buf[8]; buf[0] = msg.type / 256; buf[1] = msg.type % 256; buf[2] = msg.arg1 / 256; buf[3] = msg.arg1 % 256; buf[4] = msg.arg2 / 256; buf[5] = msg.arg2 % 256; buf[6] = msg.arg3 / 256; buf[7] = msg.arg3 % 256; serial.writeBytes(buf, 8); }
true
b42a8a12b8fb377d9de2d19139c6cb77a7d2f22c
C++
mrsteakhouse/project-template
/template/template/equipment.h
UTF-8
461
2.671875
3
[]
no_license
#ifndef _equipment_h_ #define _equipment_h_ #include <iostream> #include <cstdlib> #include <string> using namespace std; namespace equipment { class equip { public: equip(); ~equip(); int strenght; int ressistence; int mana; int endurance; int life; int spellpower; int agility; int type; string equipname; private: }; class weapon { public: weapon(); ~weapon(); int wpdmg; string wpname; } } #endif
true
921adbbfef004b26fd5f3c0b87053eccbe3f7c49
C++
ly774508966/GameRender3D
/lonely3D/ColorConverter.cpp
GB18030
5,774
3.25
3
[]
no_license
#include "ColorConverter.h" #include "Color.h" // 8һֽ void ColorConverter::Convert1BitTo16Bit( uint8* inData, uint16* outData, uint32 width, uint32 height, uint32 linepad, bool flip) { if (!inData || !outData) return; // ת if (flip) outData += width * height; for (uint32 y = 0;y < height;y++) { int32 shift = 7; if (flip) outData -= width; for (uint32 x = 0;x < width;x++) { outData[x] = ((*inData >> shift) & 0x01) ? 0xFFFF : 0x8000; if (--shift < 0) { shift = 7; ++inData; } } if (shift != 7) // һ ++inData; if (!flip) outData += width; inData += linepad; } } // һֽ2 void ColorConverter::Convert4BitTo16Bit( uint8* inData, uint16* outData, uint32 width, uint32 height, uint32* paletteentry, uint32 linepad, bool flip) { if (!inData || !outData) return; if (flip) outData += width * height; for (uint32 y = 0;y < height;y++) { int32 shift = 4; if (flip) outData -= width; for (uint32 x = 0;x < width;x++) { uint16 v = X8R8G8B8_TO_A1R5G5B5(paletteentry[(*inData >> shift) & 0x0F]); outData[x] = v; if (shift == 0) { shift = 4; ++inData; } else shift = 0; } if (shift != 4) ++inData; if (!flip) outData += width; inData += linepad; } } // һֽ1 void ColorConverter::Convert8BitTo16Bit( uint8* inData, uint16* outData, uint32 width, uint32 height, uint32* paletteentry, uint32 linepad, bool flip) { if (!inData || !outData) return; if (flip) outData += width * height; int32 totalIndex = 0; for (uint32 y = 0;y < height;y++) { if (flip) outData -= width; for (uint32 x = 0;x < width;x++) { int32 index = (*inData); uint16 v = X8R8G8B8_TO_A1R5G5B5(paletteentry[index]); outData[x] = v; ++inData; totalIndex++; } if (!flip) outData += width; inData += linepad; totalIndex += linepad; } } void ColorConverter::Convert8BitTo24Bit( uint8* inData, uint8* outData, uint32 width, uint32 height, uint32* paletteentry, uint32 linepad, bool flip) { if (!inData || !outData) return; int32 lineWidth = width * 3; if (flip) outData += lineWidth * height; for (uint32 y = 0; y < height; y++) { if (flip) outData -= lineWidth; for (int32 x = 0; x < lineWidth; x += 3) { uint16 v = X8R8G8B8_TO_A1R5G5B5(paletteentry[(*inData)]); outData[x + 0] = uint8(v); outData[x + 1] = uint8(v); outData[x + 2] = uint8(v); ++inData; } if (!flip) outData += lineWidth; inData += linepad; } } void ColorConverter::Convert8BitTo32Bit( uint8* inData, uint32* outData, uint32 width, uint32 height, uint32* paletteentry, uint32 linepad, bool flip) { if (!inData || !outData) return; if (flip) outData += width * height; for (uint32 y = 0;y < height;y++) { if (flip) outData -= width; for (uint32 x = 0;x < width;x++) { uint16 v = X8R8G8B8_TO_A1R5G5B5(paletteentry[(*inData)]); outData[x] = v; ++inData; } if (!flip) outData += width; inData += linepad; } } void ColorConverter::Convert16BitTo16Bit( uint16* inData, uint16* outData, uint32 width, uint32 height, uint32 linepad, bool flip) { if (!inData || !outData) return; if (flip) outData += width * height; for (uint32 y = 0;y < height;y++) { if (flip) outData -= width; for (uint32 x = 0;x < width;x += 2) { outData[x] = *inData; ++inData; } if (!flip) outData += width; inData += linepad; } } void ColorConverter::Convert16To24Bit( uint16* inData, uint8* outData, uint32 width, uint32 height, uint32 linepad, bool flip) { if (!inData || !outData) return; int32 lineWidth = width * 3; if (flip) outData += lineWidth * height; for (uint32 y = 0;y < height;y++) { if (flip) outData -= lineWidth; for (int32 x = 0;x < lineWidth;x += 3) { outData[x + 0] = uint8(*inData); outData[x + 1] = uint8(*inData); outData[x + 2] = uint8(*inData); ++inData; } if (!flip) outData += lineWidth; inData += linepad; } } void ColorConverter::Convert16To32Bit( uint16* inData, uint32* outData, uint32 width, uint32 height, uint32 linepad, bool flip) { if (!inData || !outData) return; if (flip) outData += width * height; for (uint32 y = 0;y < height;y++) { if (flip) outData -= width; for (uint32 x = 0;x < width;x++) { outData[x] = *inData; ++inData; } if (!flip) outData += width; inData += linepad; } } void ColorConverter::Convert24To24Bit( uint8* inData, uint8* outData, uint32 width, uint32 height, uint32 linepad, bool flip, bool bgr) { if (!inData || !outData) return; const uint32 lineWidth = width * 3; if (flip) outData += lineWidth * height; for (uint32 y = 0;y < height;y++) { if (flip) outData -= lineWidth; if (bgr) { for (uint32 x = 0;x < lineWidth;x += 3) { outData[x + 0] = inData[x + 2]; outData[x + 1] = inData[x + 1]; outData[x + 2] = inData[x + 0]; } } else { memcpy(outData, inData, lineWidth); } if (!flip) outData += lineWidth; inData += linepad; } } void ColorConverter::Convert32To32Bit( uint32* inData, uint32* outData, uint32 width, uint32 height, uint32 linepad, bool flip) { if (!inData || !outData) return; if (flip) outData += width * height; for (uint32 y = 0;y < height;y++) { if (flip) outData -= width; memcpy(outData, inData, width * sizeof(uint32)); if (!flip) outData += width; inData += width; } }
true
167a8394e0dde34eda2f260e8757668bd6c444ad
C++
Chungchhay/CS32
/Project3 Part 2/Actor.h
UTF-8
5,743
3.046875
3
[]
no_license
#ifndef ACTOR_H_ #define ACTOR_H_ #include "GraphObject.h" #include "Compiler.h" class StudentWorld; class Actor : public GraphObject { public: Actor(StudentWorld* world, int startX, int startY, Direction startDir, int imageID, int depth); virtual ~Actor(); // Action to perform each tick. virtual void doSomething() = 0; // Is this actor dead? virtual bool isDead() const; void setDead(bool arg); // Cause this actor to be be bitten, suffering an amount of damage. virtual void getBitten(int amt); // Cause this actor to be be poisoned. virtual void getPoisoned(); //virtual void setPoisoned(bool arg); // Cause this actor to be be stunned. virtual void getStunned(); // Can this actor be picked up to be eaten? virtual bool isEdible() const; void setEdible(bool arg); // Is this actor detected by an ant as a pheromone? bool isPheromone() const; void setPheromon(bool arg); int getColonies() const; void setColonies(int arg); // Is this actor an enemy of an ant of the indicated colony? virtual bool isEnemy(int colony) const; // Is this actor detected as dangerous by an ant of the indicated colony? virtual bool isDangerous(int colony) const; // Is this actor the anthill of the indicated colony? virtual bool isAntHill(int colony) const; // Get this actor's world. StudentWorld* getWorld() const; void setWorld(StudentWorld *arg); private: StudentWorld *world; bool dead; bool edible; bool pheromone; int colonies; }; class Pebble : public Actor { public: Pebble(StudentWorld* sw, int startX, int startY); virtual void doSomething(); }; class EnergyHolder : public Actor { public: EnergyHolder(StudentWorld* sw, int startX, int startY, Direction startDir, int energy, int imageID, int depth); virtual bool isDead() const; // Get this actor's amount of energy (for a Pheromone, same as strength). int getEnergy() const; // Adjust this actor's amount of energy upward or downward. void updateEnergy(int amt); // Add an amount of food to this actor's location. void addFood(int amt); int pickupFood(int amt); // Have this actor pick up an amount of food and eat it. int pickupAndEatFood(int amt); // Does this actor become food when it dies? virtual bool becomesFoodUponDeath() const; private: int hitPoints; }; class Food : public EnergyHolder { public: Food(StudentWorld* sw, int startX, int startY, int energy); virtual void doSomething(); virtual bool isEdible() const; }; class AntHill : public EnergyHolder { public: AntHill(StudentWorld* sw, int startX, int startY, int colony, Compiler* program); virtual void doSomething(); virtual bool isMyHill(int colony) const; int getColonies() const; void setColonies(int arg); Compiler *getProgram() const; void setProgram(Compiler *arg); private: int setID(int colony); int colonies; Compiler *m_program; }; class Pheromone : public EnergyHolder { public: Pheromone(StudentWorld* sw, int startX, int startY, int colony); virtual void doSomething(); virtual bool isPheromone(int colony) const; // Increase the strength (i.e., energy) of this pheromone. void increaseStrength(); private: int pickImageID(int colony); int m_colony; }; class TriggerableActor : public Actor { public: TriggerableActor(StudentWorld* sw, int x, int y, int imageID); virtual bool isDangerous(int colony) const; }; class WaterPool : public TriggerableActor { public: WaterPool(StudentWorld* sw, int x, int y); virtual void doSomething(); }; class Poison : public TriggerableActor { public: Poison(StudentWorld* sw, int x, int y); virtual void doSomething(); }; class Insect : public EnergyHolder { public: Insect(StudentWorld* world, int startX, int startY, int energy, int imageID); virtual void doSomething(); virtual void getBitten(int amt); virtual void getPoisoned(); virtual void getStunned(); virtual bool isEnemy(int colony); virtual bool becomesFoodUponDeath() const; void setStunZero(); // Increase the number of ticks this insect will sleep by the indicated amount. void increaseSleepTicks(int amt); int getSleepTicks() const; bool getTicksDelayed() const; void setTicksDelayed(int arg); bool isStunned() const; void setStunned(bool arg); bool isPoisoned() const; void setPoisoned(bool arg); private: int bitten; int a, b; bool stunned; int ticksDelayed; bool poisoned; }; class Ant : public Insect { public: Ant(StudentWorld* sw, int startX, int startY, int colony, Compiler* program, int imageID); virtual void doSomething(); virtual void getBitten(int amt); virtual void getPoisoned(); virtual void getStunned(); virtual void updateIC(); virtual int getIC(); virtual bool isEnemy(int colony) const; virtual bool moveForwardIfPossible(); private: int holdFood; Compiler *compile; int col; int counter; int dis; int bite; int m_ic; bool bitten; bool blocked; }; class Grasshopper : public Insect { public: Grasshopper(StudentWorld* sw, int startX, int startY, int energy, int imageID); virtual void doSomething(); int getDistance() const; void setDistance(int arg); private: int distance; }; class BabyGrasshopper : public Grasshopper { public: BabyGrasshopper(StudentWorld* sw, int startX, int startY); virtual bool isEnemy(int colony) const; virtual void doSomething(); virtual void getPoisoned(); }; class AdultGrasshopper : public Grasshopper { public: AdultGrasshopper(StudentWorld* sw, int startX, int startY); virtual void getBitten(int amt); virtual void doSomething(); virtual void getStunned(); }; #endif // ACTOR_H_
true
65396b540210aa2dd3c11414b85d575cd585a597
C++
fant12/geditor
/GEditor1_4/model/soundarea.h
UTF-8
1,000
2.609375
3
[]
no_license
#ifndef SOUNDAREA_H #define SOUNDAREA_H #include "mediaarea.h" // class -------------------------------------------------------------------------------- //! SoundArea class. /*! * \brief The SoundArea class describes an area, where sound can be played. */ class SoundArea : public MediaArea { Q_OBJECT // -------------------------------------------------------------------------------- public: /*! * \brief The default constructor. * \param parent the parent object */ explicit SoundArea(QObject *parent = 0); // -------------------------------------------------------------------------------- public: /*! * \brief Gives the class type. * \returns the enum index for the object type */ int getToyType(); /*! * \brief Plays the sound. * \param id the integer that defines the sound url */ void play(quint32 id); }; #endif // SOUNDAREA_H
true
a3c2b734a18b831774b9e9b75ddd098e8d0e6396
C++
tpoliaw/columns
/src/square.cpp
UTF-8
987
2.703125
3
[]
no_license
#include <cstdlib> #include <iostream> #include "square.h" using namespace std; square::square(int cols, int c) { setRandColour(c); setPos((int)SQUARE_SIZE/2 + SQUARE_SIZE * (rand() % cols),(int)SQUARE_SIZE/2); } QRectF square::boundingRect() const { return QRectF(-SQUARE_SIZE/2, -SQUARE_SIZE/2, SQUARE_SIZE, SQUARE_SIZE); } void square::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->setBrush(QBrush(colour)); painter->drawRect(-SQUARE_SIZE/2, -SQUARE_SIZE/2, SQUARE_SIZE, SQUARE_SIZE); } void square::setRandColour(int c) { int x = rand() % c; intColour = x; switch (x) { case 0: colour = QColor(0,0,0xFF); break; case 1: colour = QColor(0,0xFF,0); break; case 2: colour = QColor(0xFF,0,0); break; case 3: colour = QColor(0xFF,0xFF,0); break; case 4: colour = QColor(0,0xFF,0xFF); break; case 5: colour = QColor(0xFF,0,0xFF); break; default: colour = QColor(0,0,0); } }
true