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
a416d1826e58fa478a16ee24b9fcc41a99d9637e
C++
lars-frogner/RayImpact
/RayImpact/include/SpecularBTDF.hpp
UTF-8
2,340
2.640625
3
[]
no_license
#pragma once #include "BSDF.hpp" #include "FresnelReflector.hpp" namespace Impact { namespace RayImpact { // SpecularBTDF declarations class SpecularBTDF : public BXDF { private: const TransmissionSpectrum transmittance; // Fraction of incident light that is transmitted (disregarding Fresnel effects) const imp_float refractive_index_outside; // Index of refraction of the medium on the outside of the object const imp_float refractive_index_inside; // Index of refraction of the medium on the inside of the object const DielectricReflector dielectric_reflector; // Dielectric Fresnel reflector for the surface const TransportMode transport_mode; public: SpecularBTDF(const TransmissionSpectrum& transmittance, imp_float refractive_index_outside, imp_float refractive_index_inside, TransportMode transport_mode); Spectrum evaluate(const Vector3F& outgoing_direction, const Vector3F& incident_direction) const; Spectrum sample(const Vector3F& outgoing_direction, Vector3F* incident_direction, const Point2F& uniform_sample, imp_float* pdf_value, BXDFType* sampled_type = nullptr) const; imp_float pdf(const Vector3F& outgoing_direction, const Vector3F& incident_direction) const; }; // SpecularBTDF inline method definitions inline SpecularBTDF::SpecularBTDF(const TransmissionSpectrum& transmittance, imp_float refractive_index_outside, imp_float refractive_index_inside, TransportMode transport_mode) : BXDF::BXDF(BXDFType(BSDF_TRANSMISSION | BSDF_SPECULAR)), transmittance(transmittance), refractive_index_outside(refractive_index_outside), refractive_index_inside(refractive_index_inside), dielectric_reflector(refractive_index_outside, refractive_index_inside), transport_mode(transport_mode) {} inline Spectrum SpecularBTDF::evaluate(const Vector3F& outgoing_direction, const Vector3F& incident_direction) const { return Spectrum(0.0f); } inline imp_float SpecularBTDF::pdf(const Vector3F& outgoing_direction, const Vector3F& incident_direction) const { return 0; } } // RayImpact } // Impact
true
94f5bc9216672423281d457fc236e91a010ce901
C++
Navidulhaque/competitive-programming-solutions
/Codeforces/C++/1285/1285_B.cpp
UTF-8
1,850
2.671875
3
[]
no_license
// https://codeforces.com/problemset/problem/1285/B //Galatians 4:16 #include <bits/stdc++.h> #define sonic ios_base::sync_with_stdio(false); cin.tie(NULL); #define f(i,a,b) for(int i=a;i<b;i++) #define vi vector<int> #define newline cout<<endl; #define pb push_back #define all(a) a.begin(),a.end() #define ff first #define ss second typedef long long int ll; const double pi = 3.1415926535; ll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );} ll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;} ll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;} using namespace std; long int max(long int a,long int b,long int c) { return max(max(a, b), c); } long int maxCrossingSum(long int arr[], long int l, long int m, long int h) { long int sum = 0; long int left_sum = INT_MIN; for (long int i = m; i >= l; i--) { sum = sum + arr[i]; if (sum > left_sum) left_sum = sum; } sum = 0; long int right_sum = INT_MIN; for (long int i = m+1; i <= h; i++) { sum = sum + arr[i]; if (sum > right_sum) right_sum = sum; } return left_sum + right_sum; } long int maxSubArraySum(long int arr[], long int l, long int h) { if (l == h) return arr[l]; long int m = (l + h)/2; return max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m+1, h), maxCrossingSum(arr, l, m, h)); } int main() { long int t,n,arr[100005]={0}, ans; cin>>t; while(t--) { long int sum=0; cin>>n; f(i,0,n) {cin>>arr[i]; sum+=arr[i];} ans=max(maxSubArraySum(arr, 0, n-2), maxSubArraySum(arr, 1, n-1)); if(ans<sum) cout<<"YES\n"; else cout<<"NO\n"; } return 0; }
true
88d132eb44fd8d66d8fabc82e57bf0d46dc08e67
C++
ChenXinyu-CHD/Snake
/GameMap.cpp
UTF-8
1,578
3.078125
3
[]
no_license
/** * name : GameMap.cpp; * date : 2018/5/28; * g++ version : 8.1.0; * g++ options : -O2; * */ #include "GameMap.h" #include <cstdlib> #include <ctime> GameMap::GameMap(Snake *snake_p): snake(snake_p) { srand((unsigned)time(0)); for(int i = 0;i < MAX_HIGHT;++i) for(int j = 0;j < MAX_LENGTH;++j) if ( i == 0||i == MAX_HIGHT-1 || j == 0||j == MAX_LENGTH-1 ) map[i][j] = 'X'; else map[i][j] = ' '; foodPosition = createFood(); Position snakeHeadPosition = snake->getHeadPosition(); map[snakeHeadPosition.Y][snakeHeadPosition.X] = '*'; map[foodPosition.Y][foodPosition.X] = '+'; } void GameMap::update() { if(hasNotGameOver()) { Position oldSnakeTailPosition = snake->getTailPosition(); if(snake->tryToEatFood(foodPosition)) foodPosition = createFood(); else map[oldSnakeTailPosition.Y][oldSnakeTailPosition.X] = ' '; Position newSnakeHeadPosition = snake->getHeadPosition(); map[newSnakeHeadPosition.Y][newSnakeHeadPosition.X] = '*'; map[foodPosition.Y][foodPosition.X] = '+'; } } bool GameMap::hasNotGameOver() { Position position = snake->getThePositionFacingTo(); return( map[position.Y][position.X] == ' ' || map[position.Y][position.X] == '+' ); } Position GameMap::createFood() { int x = 0; int y = 0; Position result; while(map[y][x] != ' ') { y = rand() % (MAX_HIGHT - 4) + 2; x = rand() % (MAX_LENGTH - 4) + 2; } result.X = x; result.Y = y; return result; } Snake * GameMap::getSnake_ptr() {return snake;} GameMap::Map &GameMap::getMap() {return map;}
true
69c60acfdd067b29f128e35e6735a676c68ba507
C++
svelhinh/Projects
/Projects/piscine_cpp/j04/ex01/Enemy.cpp
UTF-8
1,438
2.71875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Enemy.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: svelhinh <svelhinh@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/06/20 17:15:28 by svelhinh #+# #+# */ /* Updated: 2017/04/07 20:00:35 by svelhinh ### ########.fr */ /* */ /* ************************************************************************** */ #include "Enemy.hpp" Enemy::Enemy() { return; } Enemy::Enemy(int hp, std::string const & type): _hp(hp), _type(type) { return; } Enemy::Enemy(Enemy const & src) { *this = src; return; } Enemy::~Enemy(void) { return; } std::string Enemy::getType( void ) const { return this->_type; } int Enemy::getHP( void ) const { return this->_hp; } void Enemy::setHP( int hp ) { this->_hp = hp; } void Enemy::takeDamage( int nb ) { if (nb > 0) this->_hp -= nb; } Enemy & Enemy::operator=(Enemy const & rhs) { _hp = rhs.getHP(); return *this; }
true
cbe2f13af8fe3c3d7f3faf236078c36b4b68945b
C++
marvins/Code_Sandbox
/opencv/cpp/stab-demo/cv/Fast_Marching.hpp
UTF-8
1,976
2.984375
3
[]
no_license
#ifndef STAB_DEMO_CV_VIDEOSTAB_FAST_MARCHING_HPP #define STAB_DEMO_CV_VIDEOSTAB_FAST_MARCHING_HPP // C++ Libraries #include <algorithm> #include <cmath> #include <queue> // OpenCV Libraries #include <opencv2/core.hpp> class FastMarchingMethod { public: FastMarchingMethod() : inf_(1e6f), size_(0) {} /** @brief Template method that runs the Fast Marching Method. @param mask Image mask. 0 value indicates that the pixel value must be inpainted, 255 indicates that the pixel value is known, other values aren't acceptable. @param inpaint Inpainting functor that overloads void operator ()(int x, int y). @return Inpainting functor. */ template<typename Inpaint> Inpaint run(const cv::Mat &mask, Inpaint inpaint); /** @return Distance map that's created during working of the method. */ cv::Mat distanceMap() const { return dist_; } private: enum { INSIDE = 0, BAND = 1, KNOWN = 255 }; struct DXY { float dist; int x, y; DXY() : dist(0), x(0), y(0) {} DXY(float _dist, int _x, int _y) : dist(_dist), x(_x), y(_y) {} bool operator<(const DXY &dxy) const { return dist < dxy.dist; } }; float solve(int x1, int y1, int x2, int y2) const; int &indexOf(const DXY &dxy) { return index_(dxy.y, dxy.x); } void heapUp(int idx); void heapDown(int idx); void heapAdd(const DXY &dxy); void heapRemoveMin(); float inf_; cv::Mat_<uchar> flag_; // flag map cv::Mat_<float> dist_; // distance map cv::Mat_<int> index_; // index of point in the narrow band std::vector<DXY> narrowBand_; // narrow band heap int size_; // narrow band size }; #include "Fast_Marching_Inl.hpp" #endif
true
04194d0cb3c2330aa600dcf5b6a48c413027462b
C++
waingt/pvz_wupaofuzhu
/src/utils.h
UTF-8
249
2.6875
3
[]
no_license
#pragma once #include <initializer_list> #define inrange(x,low,high) ((x)<(low)?(low):((x)>(high)?(high):(x))) template<typename T> bool in(T t, std::initializer_list<T> list) { for (auto& i : list) { if (t == i)return true; } return false; }
true
688189620791a98ed97cbf3c932f8bef3f1bf055
C++
yijunyu/demo
/datasets/github_cpp_10/7/71.cpp
UTF-8
1,941
2.78125
3
[ "BSD-2-Clause" ]
permissive
#include <thrust/iterator/iterator_traits.h> #include <thrust/detail/backend/cpp/merge.h> #include <thrust/detail/backend/cpp/detail/insertion_sort.h> namespace thrust { namespace detail { namespace backend { namespace cpp { namespace detail { template <typename RandomAccessIterator, typename StrictWeakOrdering> void stable_merge_sort(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp) { if (last - first < 32) { thrust::detail::backend::cpp::detail::insertion_sort(first, last, comp); } else { RandomAccessIterator middle = first + (last - first) / 2; thrust::detail::backend::cpp::detail::stable_merge_sort(first, middle, comp); thrust::detail::backend::cpp::detail::stable_merge_sort(middle, last, comp); thrust::detail::backend::cpp::inplace_merge(first, middle, last, comp); } } template <typename RandomAccessIterator1, typename RandomAccessIterator2, typename StrictWeakOrdering> void stable_merge_sort_by_key(RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, StrictWeakOrdering comp) { if (last1 - first1 <= 32) { thrust::detail::backend::cpp::detail::insertion_sort_by_key(first1, last1, first2, comp); } else { RandomAccessIterator1 middle1 = first1 + (last1 - first1) / 2; RandomAccessIterator2 middle2 = first2 + (last1 - first1) / 2; thrust::detail::backend::cpp::detail::stable_merge_sort_by_key(first1, middle1, first2, comp); thrust::detail::backend::cpp::detail::stable_merge_sort_by_key(middle1, last1, middle2, comp); thrust::detail::backend::cpp::inplace_merge_by_key(first1, middle1, last1, first2, comp); } } } } } } }
true
b928909644372650da789060e17745a37047db8c
C++
SebastianKunz/ChessEngine
/src/Figures/Pawn.cpp
UTF-8
1,629
2.890625
3
[ "MIT" ]
permissive
#include "Figures/Pawn.h" #include "GameBoard.h" Pawn::Pawn(const int y, const int x, const char color, FigureLoader *loader) : AFigure(y, x, color, Figure::PAWN, loader), _isFirstMove(true) { } bool Pawn::isLegalMove(const int y, const int x, AFigure ***board) const { if (!GameBoard::isInBounds(y, x)) return false; const int moveX = x - this->x; const int absX = abs(moveX); const int moveY = color * (this->y - y); // capture if (board[y][x] && absX == 1 && moveY == 1 && board[y][x]->getColor() != color) return true; if (moveX != 0 || moveY <= 0) return false; if (_isFirstMove) { if (moveY == 1 && !board[y][x]) return true; else if (moveY == 2 && !board[y][x] && GameBoard::isInBounds(y - 1, x) && !board[y - 1][x]) return true; return false; } else return moveY == 1 && absX == 0 && !board[y][x]; return false; } bool Pawn::canMoveTo(const int y, const int x, AFigure ***board) { bool ret = isLegalMove(y, x, board); _isFirstMove = false; return ret; } std::vector<SDL_Point> Pawn::getAllPossibleMoves(AFigure ***board) { std::vector<SDL_Point> moves; // this is just for debugging for (int y = 0; y < 8; y++) { for (int x = 0; x < 8; x++) { if (isLegalMove(y, x, board)) moves.push_back({x, y}); } } return moves; if (isLegalMove(x, y + 1, board)) { moves.push_back({x, y + 1}); } if (isLegalMove(x, y + 2, board)) { moves.push_back({x, y + 2}); } if (isLegalMove(x + 1, y + 1, board)) { moves.push_back({x + 1, y + 1 * color}); } if (isLegalMove(x - 1, y + 1, board)) { moves.push_back({x - 1, y + 1 * color}); } return moves; }
true
ce60550dced0a8fc7b5de45b139715679ef96a6f
C++
YarikAlex/BlackJack-Game-for-Geekbrains
/Player.cpp
UTF-8
594
3.25
3
[]
no_license
#include "Player.h" Player::Player(const string& name = "") : GenericPlayer(name) { m_Name = name; } Player:: ~Player() { } void Player::Win() const { cout << m_Name << ", you win!" << endl; } void Player::Lose() const { cout << m_Name << ", you lose!" << endl; } void Player::Push() const { cout << m_Name << ", you drew!" << endl; } bool Player::isHitting() { char answer; cout << m_Name << ", do you need another card? (Y or N): " << endl; cin >> answer; if (answer == 'Y' or answer == 'y') return true; else return false; }
true
116b3fa478e6c9b52f583c997aac195669b329e0
C++
PiotrJTomaszewski/SK2_Projekt
/CheckersClient/game_piece.cpp
UTF-8
1,514
2.578125
3
[ "MIT" ]
permissive
#include "game_piece.h" GamePiece::GamePiece(const QString man_pixmap, const QString king_pixmap, const GLOBAL::COLOR piece_color, QGraphicsItem *parent) : QGraphicsPixmapItem(man_pixmap, parent) { this->setZValue(10); this->piece_type = GLOBAL::MAN; this->piece_color = piece_color; this->setVisible(false); this->man_pixmap = QPixmap(man_pixmap); this->king_pixmap = QPixmap(king_pixmap); } void GamePiece::setPosition(QPointF position , int field) { this->setPos(position); this->field = field; } QPointF GamePiece::getPos() { return this->pos(); } void GamePiece::setPieceType(GLOBAL::PIECE_TYPE piece_type) { this->piece_type = piece_type; switch(piece_type) { case GLOBAL::MAN: this->setPixmap(man_pixmap); break; case GLOBAL::KING: this->setPixmap(king_pixmap); break; case GLOBAL::NO_PIECE: break; } } void GamePiece::capture() { this->piece_type = GLOBAL::NO_PIECE; this->setVisible(false); } void GamePiece::promoteToKing() { this->piece_type = GLOBAL::KING; this->setPixmap(king_pixmap); } GLOBAL::PIECE_TYPE GamePiece::getPieceType() { return this->piece_type; } GLOBAL::COLOR GamePiece::getPieceColor() { return this->piece_color; } void GamePiece::setMoveable(bool should_be_moveable) { if (should_be_moveable) this->setFlag(QGraphicsItem::ItemIsMovable); else this->setFlags(this->flags() & (~QGraphicsItem::ItemIsMovable)); } int GamePiece::getField() { return this->field; }
true
a6b870c61b9a1d5fdd359c40335fa8d83bb64917
C++
WhiZTiM/coliru
/Archive2/ec/42c461ba35b35b/main.cpp
UTF-8
307
3.296875
3
[]
no_license
#include <iostream> #include <exception> struct MyException : std::exception { const char *what() const noexcept override { return "My awesome message"; } }; int main() { try { throw MyException(); } catch (std::exception ex) { std::cout << ex.what(); } }
true
7fd6ca62ea3ee6620be4f769ca207672706d934e
C++
ike4892/CSCI20-Fall2016
/assignment1/assignment1.cpp
UTF-8
761
3.3125
3
[]
no_license
// Kasey Koch // Assignment 1 // Date created - 9/12/2016 // Date last worked on - 9/12/2016 #include <iostream> using namespace std; int main() { int hours = 0; float wage = 0; string firstName = ""; string lastName = ""; float net = 0; float gross = 0; float tax = 0; cout<<"What is your first name? "; cin>>firstName; cout<<"What is your last name? "; cin>>lastName; cout<<"How many hours did you work this week? "; cin>>hours; cout<<"What is your current hourly wage? "; cin>>wage; gross = hours * wage; tax = gross * 0.17; net = gross - tax; cout<<firstName<<" "<<lastName<<" your net pay is $"<<net<<" you paid $"<<tax<<" in taxes and your gross pay is $"<<gross ; return 0; }
true
1d52e6df61e6787cb5ca2250cdf68bfc1139540f
C++
dnllowe/NRG_Engine
/Classes/nrgTimer.h
UTF-8
1,965
3.0625
3
[]
no_license
#pragma once #include "pch.h" class nrgTimer { public: nrgTimer(); void Start(); //Starts timer void Stop(); //Stops timer void Pause(bool unpauseOnResumeInput = false); //Pauses timer (same as stop, but can be unpaused) bool IsUnpauseOnResume(); void Unpause(); //Resumes ticking, but only if previous paused bool IsRunning(); //Returns true if timer has started bool IsPaused(); //Returns whether clock has been stopped after starting long long GetElapsedTime(); //Returns time clocked long long GetElapsedSeconds(); //Returns time elapsed in seconds long long GetStartTime(); //Returns clock value when timer started long long GetStopTime(); //Returns clock value when timer stopped void Reset(); //Resets startTime, stopTime, and timeElapsed to 0 void Restart(); //Resets startTime, stopTime, and timeElapsed to 0, clock continues running void DecreaseTimeElapsed(long long); //Subtract ms from timeElapsed void IncreaseTimeElapsed(long long); //Add ms to timeElapsed void SetMark(long long value = -1); //Set time marker to value + current time, or current time if no value given long long GetMark(); //Get the latest mark set void AddTimeToMark(int moreTime); bool IsMarkSet(); //Check whether mark has been set void ResetMark(); //Reset time marker ~nrgTimer(); protected: bool isTicking = false; //Has clock started bool isPaused = false; //Whether clock has been stopped after starting bool markSet = false; //Has mark been set bool unpauseOnResume = true; //Whether to unpause time when app enters foreground long long startTime = 0; //Clock value at Start long long stopTime = 0; //Clock value at Stop long long elapsedTime = 0; //stopTime - startTime long long increasedTime = 0; //How much time was added to stop time to increase time elapsed long long decreasedTime = 0; //How much time was subtracted from stop time to decrease time elapsed long long mark = -1; //Time marked for reference in future };
true
284484aa46a53f8b13eee5cd39d513204d537a39
C++
CGQZtoast/c_plus
/test/作业训练二/9字符串压缩.cpp
UTF-8
827
2.796875
3
[]
no_license
#include <iostream> using namespace std; int main() { int n, a, b; cin >> n >> a >> b; string str; cin >> str; int ans = 0; string temp1, temp2; ans += a; for (int i = 1; i < n; i++) { bool flag = false; temp1 = str.substr(0, i); for (int j = 1; j < n; j++) { temp2 = str.substr(i, n - j); int cur = temp1.find(temp2); if (cur != -1) { int len = temp2.length(); if (len > b / a) { ans += b; flag = true; i += (n - j - 1); break; } } } if (flag == false) ans += a; } cout << ans; }
true
c34416f08179bb529211744de45256257fd05b94
C++
luist18/feup-aeda-proj
/src/application/controller/offer/view_offers_page_controller.cpp
UTF-8
1,235
2.9375
3
[ "MIT" ]
permissive
#include "view_offers_page_controller.h" ViewOffersPageController::ViewOffersPageController(CurrentSession &current_session, AuthUserManager &auth_user_manager, Company &company) : current_session(current_session), auth_user_manager(auth_user_manager), company(company) {} vector<Offer> ViewOffersPageController::getOffers(int page, int max_per_page) { vector<Offer> result; int first_index = (page - 1) * max_per_page; for (int i = 0; i < max_per_page; i++) { int index = first_index + i; if (index >= company.getOfferManager().getPossibleOffers().size()) break; result.push_back(company.getOfferManager().getPossibleOffers()[index]); } return result; } int ViewOffersPageController::getPageCount(int max_per_page) { int size = company.getOfferManager().getPossibleOffers().size(); return size / max_per_page + (size % max_per_page == 0 ? 0 : 1); } Offer *ViewOffersPageController::getOffer(int current_page, const int MAX_PER_PAGE, int index) { return &getOffers(current_page, MAX_PER_PAGE)[index]; }
true
ef328e0eb0a9b1621e8610aa8d16ded5f3be1b52
C++
haoranchen1104/RMbot
/RMbot_bringup/src/com_controller.cpp
UTF-8
8,965
2.53125
3
[]
no_license
#include "com_controller.h" com_controller::com_controller(com_controller& other) :nh_(other.nh_), dev_(other.dev_), baudrate_(other.baudrate_), time_out_(other.time_out_), hz_(other.hz_) {} com_controller::com_controller(ros::NodeHandle& nh, std::string dev="/dev/ttyUSB0", int baudrate=115200, int time_out = 1000, int hz = 50) :nh_(nh), dev_(dev), baudrate_(baudrate), time_out_(time_out), hz_(hz), odom_state(false) { if(init()){ ROS_INFO_STREAM("Communication Controller - Initialized."); }else{ ROS_ERROR_STREAM("Communication Controller - Initialization failed!!!"); } } //初始化 bool com_controller::init() { //set parameters nh_.setParam("dev", dev_); nh_.setParam("baudrate", baudrate_); nh_.setParam("time_out", time_out_); nh_.setParam("hz", hz_); ROS_INFO_STREAM("dev: "<<dev_); ROS_INFO_STREAM("buad: "<<baudrate_); ROS_INFO_STREAM("time_out: "<<time_out_); ROS_INFO_STREAM("hz: "<<hz_); try { ros_ser.setPort(dev_); ros_ser.setBaudrate(baudrate_); serial::Timeout t_o = serial::Timeout::simpleTimeout(time_out_); ros_ser.setTimeout(t_o); ros_ser.open(); ros_ser.flushInput(); } catch(const serial::IOException& e) { // std::cerr << e.what() << '\n'; ROS_ERROR_STREAM("Unable to open port." << e.what()); return false; } if(ros_ser.isOpen()){ ros_ser.flushInput(); ROS_INFO_STREAM("Serial Port Opened."); return true; }else { ROS_ERROR_STREAM("Serial Port is not open!!"); return false; } } //发送 void com_controller::send_speed_to_chassis(float x, float y, float w) { uint8_t data_tem[50]; unsigned int speed_0ffset=200; //速度偏移值 10m/s,把速度转换成正数发送 unsigned char i,counter=0; unsigned char cmd,length; unsigned int check=0; cmd =0xF2; data_tem[counter++] =0xAE; data_tem[counter++] =0xEA; data_tem[counter++] =0x08; data_tem[counter++] =cmd; data_tem[counter++] =((x+speed_0ffset)*100)/256; // X data_tem[counter++] =((x+speed_0ffset)*100); data_tem[counter++] =((y+speed_0ffset)*100)/256; // Y data_tem[counter++] =((y+speed_0ffset)*100); data_tem[counter++] =((w+speed_0ffset)*100)/256; // W data_tem[counter++] =((w+speed_0ffset)*100); // data_tem[counter++] =0xff; // data_tem[2] =counter-2 ; data_tem[counter++] =0xEF; data_tem[counter++] =0xFE; ros_ser.write(data_tem,counter); } bool com_controller::receive_uart_data() { unsigned char received_tem[500]; uint16_t len=0, i=0, j=0; unsigned char tem_last=0, tem_curr=0, rec_flag=0;//定义接受标志位 uint16_t header_count=0, step=0; //计算数据中有多少帧 uint16_t offset = 32768; len = serial_data.data.size(); //接受串口中的缓冲数据 if(len < 1 || len > 500){ ROS_INFO_STREAM("data is either too large or too short, len : "<< serial_data.data.size()); return false; } ROS_INFO_STREAM("Received Serial Data [Message length: "<< serial_data.data.size() << "]"); //找到所有帧位置 for(i=0; i<len; i++){ tem_last = tem_curr; tem_curr = serial_data.data.at(i); if(tem_last == 0xAE && tem_curr == 0xEA && rec_flag == 0){ rec_flag = 1; received_tem[j++] = tem_last; received_tem[j++] = tem_curr; // ROS_INFO_STREAM("Found frame head..."); }else if(rec_flag == 1){ received_tem[j++] = serial_data.data.at(i); if(tem_last == 0xEF && tem_curr == 0xFE){ header_count++; rec_flag = 2; } }else{ rec_flag = 0; } } //接收所有数据 step = 0; // for(i=0; i<header_count; i++){ for(i=0; i<1; i++){ //每一次接收数据中,只接收1帧数据,每一次接收的数据长度大约13帧,改为只解析其中的一帧,可以有效的降低cpu的计算资源 len = received_tem[2+step] + 4; // /////////////// // for(int tmp = 0; tmp < 30; tmp++){ // printf("0x%02X ", received_tem[step+tmp]); // } // printf("\n"); // /////////////// if(received_tem[0+step] == 0xAE && received_tem[1+step] == 0xEA && received_tem[len-2+step] == 0xEF && received_tem[len-1+step] == 0xFE){ if(received_tem[3+step] == 0x02){ //stm32中轮胎对应关系 左上[0] 左下[2] 右下[1] 右上[3] C_speed.wheelSpeed[0] = received_tem[4+step]*256 + received_tem[5+step] - offset;//左上 C_speed.wheelSpeed[1] = received_tem[8+step]*256 + received_tem[9+step] - offset;//左下 C_speed.wheelSpeed[2] = received_tem[6+step]*256 + received_tem[7+step] - offset;//右下 C_speed.wheelSpeed[3] = received_tem[10+step]*256 + received_tem[11+step] - offset;//右上 wheelSpeed2chassisSpeed(); C_speed.angle[0] = received_tem[12+step]*256 + received_tem[13+step] - offset; C_speed.angle[1] = received_tem[16+step]*256 + received_tem[17+step] - offset; C_speed.angle[2] = received_tem[14+step]*256 + received_tem[15+step] - offset; C_speed.angle[3] = received_tem[18+step]*256 + received_tem[19+step] - offset; short tmpangle = received_tem[20+step]*256 + received_tem[21+step]; C_speed.yawangle = ((float) tmpangle)/100.0-180; C_speed.zerocircle = received_tem[22+step]*256 + received_tem[23+step] - offset; ROS_INFO_STREAM("angle&yaw: "<< C_speed.angle[0] << ","<< C_speed.angle[1]<< ","<< C_speed.angle[2]<< ","<< C_speed.angle[3]<< "\t"<< C_speed.yawangle<< "," << C_speed.zerocircle); }else if(received_tem[3+step] == 0x01){ // TODO: 需要初始化yaw C_origin.angle[0] = received_tem[4+step]*256 + received_tem[5+step] - offset; C_origin.angle[1] = received_tem[8+step]*256 + received_tem[9+step] - offset; C_origin.angle[2] = received_tem[6+step]*256 + received_tem[7+step] - offset; C_origin.angle[3] = received_tem[10+step]*256 + received_tem[11+step] - offset; odom_state = true; std::cout<<"Initialized odometry state: "<< C_origin.angle[0]<<"\t"<< C_origin.angle[1]<<"\t"<< C_origin.angle[2]<<"\t"<< C_origin.angle[3] << std::endl; } }else{ ROS_WARN_STREAM("Failed to parse the frame!!!"); return false; } step += len; } return true; } void com_controller::wheelSpeed2chassisSpeed() { int v1 = C_speed.wheelSpeed[0]; int v2 = C_speed.wheelSpeed[1]; int v3 = C_speed.wheelSpeed[2]; int v4 = C_speed.wheelSpeed[3]; float K4_1 = 1.0 / (4.0 * WHEEL_K); C_speed.x = 0.25*v1+ 0.25*v2+ 0.25*v3+ 0.25*v4; C_speed.y = -0.25*v1+ 0.25*v2- 0.25*v3+ 0.25*v4; C_speed.w = -K4_1*v1-K4_1*v2+K4_1*v3+ K4_1*v4; } void com_controller::close_port() { if(ros_ser.isOpen()){ ros_ser.close(); ROS_INFO_STREAM("serial port closed."); } } void com_controller::wait_till_available(uint8_t buffer_size) { while(ros_ser.available() <= buffer_size) { sleep(0.001); } } bool com_controller::read_serial_data() { bool receive_flag = false; if(ros_ser.available()) { serial_data.data = ros_ser.read(ros_ser.available()); receive_flag = receive_uart_data(); } return receive_flag; } void com_controller::clear_buffer() { ros_ser.flushInput(); } void com_controller::get_initial_odometry_chassis() { uint8_t data_tem[12]; uint8_t cmd = 0xE1; data_tem[0] = 0xAE; data_tem[1] = 0xEA; data_tem[2] = 0x08; data_tem[3] = cmd; data_tem[4] = 0x00; data_tem[5] = 0x00; data_tem[6] = 0x00; data_tem[7] = 0x00; data_tem[8] = 0x00; data_tem[9] = 0x00; data_tem[10] = 0xEF; data_tem[11] = 0xFE; ros_ser.write(data_tem,12); } void com_controller::get_initial_odom_from_cspeed() { C_origin.angle[0] = C_speed.angle[0]; C_origin.angle[1] = C_speed.angle[1]; C_origin.angle[2] = C_speed.angle[2]; C_origin.angle[3] = C_speed.angle[3]; odom_state = true; ROS_INFO_STREAM("Initialize from the chassis speed..."); std::cout<<"Initialized odometry state: "<< C_origin.angle[0]<<"\t"<< C_origin.angle[1]<<"\t"<< C_origin.angle[2]<<"\t"<< C_origin.angle[3] << std::endl; } bool com_controller::odometry_state_got() { return odom_state; }
true
4149d4ff8c288f9dcdff15a966abc8da94e59e53
C++
yavuzDemir21/CMPE322_Project1
/EventSimulator.cpp
UTF-8
4,109
3.03125
3
[]
no_license
// // Created by Yavuz on 16/11/2018. // #include "EventSimulator.h" #include <fstream> #include <queue> EventSimulator::EventSimulator() { this->schedule; this->outputFile = ""; } EventSimulator::EventSimulator(vector<Process> _sched, string outputFile) { this->schedule = _sched; this->outputFile = outputFile; } void EventSimulator::Simulate() { //All smilation performs in here ofstream out(outputFile);//intializing output file priority_queue<Process> scheduleQueue; //queue for processes priority_queue<Process> copyQueue; // copy of the process queue for printing the queue int i=0; //number of processes int elapsedTime = schedule[i].arriveTime; //elapsed time if(elapsedTime != 0){ out<<"0:HEAD--TAIL" << endl; } Process current = schedule[i]; // process in the execution while(true){ bool changed = false; //shows whether a queue is changed or not while(i != schedule.size()-1 && schedule[i+1].arriveTime <= elapsedTime){ // check if the next process has arrived schedule[i+1].queueEntry = schedule[i+1].arriveTime; // update new process's queue entry time scheduleQueue.push(schedule[i+1]); // add new process to the queue changed = true; // queue is changed because of the new process/es i++; // increment the number of processes } if(scheduleQueue.size() == 0){ // if there is no process in the queue if(current.pointer == current.codeFile._instr.size()){ // chech if the current process finished it's instructions if(i == schedule.size()-1){ // check whether it is the last process of not break; }else{ // if it is not the last process fetch the next process current = schedule[i]; elapsedTime = current.arriveTime; changed = true; } }else if(i == 0 && current.pointer == 0){ changed = true; // fetch the first process } }else if(scheduleQueue.top().priority < current.priority){ //if there is a prior process in the queue fetch the prior process current.queueEntry = elapsedTime; scheduleQueue.push(current); // add current process to the queue current = scheduleQueue.top(); current.waitingTime += elapsedTime - current.queueEntry; //update the prior process's waiting time scheduleQueue.pop(); changed = true; }else{ if(current.pointer == current.codeFile._instr.size()){ // if current process finished fetch the next one in the queue current = scheduleQueue.top(); scheduleQueue.pop(); current.waitingTime += elapsedTime - current.queueEntry; changed = true; } } if(changed){ //if queue is changed print the state of the queue out<< elapsedTime << ":HEAD-" << current.name << "[" << current.pointer+1 << "]-" ; copyQueue = scheduleQueue; //create a copy queue for iterate while(copyQueue.size() != 0){ out << copyQueue.top().name << "[" << copyQueue.top().pointer+1 << "]-" ; copyQueue.pop(); } out<<"TAIL" << endl; } elapsedTime += current.codeFile._instr[current.pointer]; //update elapsed time current.pointer++; // update instruction pointer current.turnAroundTime = elapsedTime - current.arriveTime; //update turn out time schedule[current.number] = current; // update process in the array; } out<<elapsedTime <<":HEAD--TAIL\n" << endl; for(int i=0; i<schedule.size(); i++){ out<< "Turnaround time for " << schedule[i].name << " = " << schedule[i].turnAroundTime << " ms"<< endl; out<< "Waiting time for " << schedule[i].name << " = " << schedule[i].waitingTime << " ms"<< endl; } }
true
9077d634aee3709273e6024565c12041a62c1457
C++
zhuli19901106/codeeval
/easy/self-describing-numbers(AC).cpp
UTF-8
453
2.59375
3
[]
no_license
#include <cstdio> #include <cstring> using namespace std; int main() { char s[1000]; int c[10]; int i; int len; while (scanf("%s", s) == 1) { len = strlen(s); if (len > 10) { printf("0\n"); continue; } for (i = 0; i < 10; ++i) { c[i] = 0; } for (i = 0; i < len; ++i) { ++c[s[i] - '0']; } for (i = 0; i < len; ++i) { if (c[i] != s[i] - '0') { break; } } printf("%d\n", i == len ? 1 : 0); } return 0; }
true
fabd86661efea2b789edd5979c67418ee008021f
C++
nzuzow/335-project3
/Negate.h
UTF-8
708
2.765625
3
[]
no_license
#ifndef NEGATE_H #define NEGATE_H #include "ExprVisitor.h" #include "Expr.h" class Negate: public Expr{ private: Expr* m_opPtr; public: Negate (Expr* opr):m_opPtr(opr){}; virtual ~Negate() {delete m_opPtr;} Expr* getOperand() {return m_opPtr;} /*Test to get type*/ std::string getType() {return "neg";}; //virtual bool compute() {return -(m_opPtr->compute());} virtual bool compute(); /*{ if( m_opPtr->compute() == 0) { return 1; } else { return 0; } };*/ virtual void accept(ExprVisitor* v) {v->visitNegate(this);} }; #endif
true
6c5edbb034cd956e922efc9a5e13a2757a9c3e5a
C++
liaochiheng/CarND-PID-Control
/src/PID.cpp
UTF-8
4,058
2.984375
3
[]
no_license
#include "PID.h" #include <limits> #include <iostream> using namespace std; /* * TODO: Complete the PID class. */ PID::PID() {} PID::~PID() {} void PID::Init(double Kp, double Kd, double Ki) { this->Kp = Kp; this->Kd = Kd; this->Ki = Ki; p_error = std::numeric_limits<double>::max(); i_error = 0.0; } void PID::UpdateError(double cte) { if (p_error == std::numeric_limits<double>::max()) p_error = cte; d_error = cte - p_error; i_error += cte; p_error = cte; // std::cout << "UpdateError: " << p_error << ", " << i_error << ", " << d_error << endl; } double PID::TotalError() { double steer = -Kp * p_error - Kd * d_error - Ki * i_error; // std::cout << "TotalError: " << steer << " # " << Kp << ", " << Kd << ", " << Ki << endl; if (steer < -1.0) steer = -1.0; if (steer > 1.0) steer = 1.0; return steer; } void PID::Twiddle_Init(bool tw_switch, int tw_num) { twiddle_switch = tw_switch; twiddle_num = tw_num; twiddle_it = 0; twiddle_idx = 0; twiddle_idx_p = 0; twiddle_down = false; twiddle_err = 0.0; twiddle_p[0] = 0.2; twiddle_p[1] = 3.0; twiddle_p[2] = 0.01; twiddle_dp[0] = 0.1; twiddle_dp[1] = 1.0; twiddle_dp[2] = 0.005; twiddle_err_best = std::numeric_limits<double>::max(); Init(twiddle_p[0], twiddle_p[1], twiddle_p[2]); } bool PID::Twiddle(double cte) { twiddle_idx ++; twiddle_err += cte * cte; // off road if (cte < -4.0 || cte > 4.0) { twiddle_err = std::numeric_limits<double>::max(); Twiddle_NextRun(); // Need to reset simulator return true; } else if (twiddle_idx == twiddle_num) { Twiddle_NextRun(); // Need to reset simulator return true; } return false; } void PID::Twiddle_NextRun() { twiddle_it ++; double err = twiddle_err == std::numeric_limits<double>::max() ? std::numeric_limits<double>::max() : twiddle_err / (float)twiddle_idx; // Found better p if (err < twiddle_err_best) { twiddle_err_best = err; twiddle_dp[twiddle_idx_p] *= 1.1; twiddle_p_best[0] = twiddle_p[0]; twiddle_p_best[1] = twiddle_p[1]; twiddle_p_best[2] = twiddle_p[2]; std::cout << "Twiddle # " << twiddle_it << " ==> " << Kp << ", " << Kd << ", " << Ki << " best_err = " << err << endl; twiddle_idx_p ++; if (twiddle_idx_p == 3) twiddle_idx_p = 0; twiddle_p[twiddle_idx_p] += twiddle_dp[twiddle_idx_p]; twiddle_down = false; } else { // Faild to find better p if (twiddle_down == true) { // Now is twiddle down twiddle_p[twiddle_idx_p] += twiddle_dp[twiddle_idx_p]; twiddle_dp[twiddle_idx_p] *= 0.9; twiddle_idx_p ++; if (twiddle_idx_p == 3) twiddle_idx_p = 0; twiddle_p[twiddle_idx_p] += twiddle_dp[twiddle_idx_p]; twiddle_down = false; } else { twiddle_p[twiddle_idx_p] -= 2 * twiddle_dp[twiddle_idx_p]; twiddle_down = true; } if (twiddle_err == std::numeric_limits<double>::max()) std::cout << "Twiddle # " << twiddle_it << " [Off-Road]: " << Kp << ", " << Kd << ", " << Ki << endl; else std::cout << "Twiddle # " << twiddle_it << " [No-Better]: " << Kp << ", " << Kd << ", " << Ki << " err = " << err << endl; } // If need to stop double sum_dp = twiddle_dp[0] + twiddle_dp[1] + twiddle_dp[2]; if (sum_dp < 0.01) { std::cout << "********************************************************" << endl; std::cout << "Twiddle End. The best p = [" << twiddle_p_best[0] << ", " << twiddle_p_best[1] << ", " << twiddle_p_best[2] << "]." << endl; std::cout << "The best error is: " << twiddle_err_best << endl; std::cout << "********************************************************" << endl; twiddle_switch = false; Init(twiddle_p_best[0], twiddle_p_best[1], twiddle_p_best[2]); } else { Init(twiddle_p[0], twiddle_p[1], twiddle_p[2]); twiddle_idx = 0; twiddle_err = 0.0; if (twiddle_it % 10 == 0) { std::cout << "=======================" << endl; std::cout << "Twiddle dp: " << twiddle_dp[0] << ", " << twiddle_dp[1] << ", " << twiddle_dp[2] << endl; std::cout << "=======================" << endl; } } }
true
564d5012e510b5fcf584830c9ff178f7101f6e69
C++
autumn192837465/LeetCode
/1012. Complement of Base 10 Integer.cpp
UTF-8
1,139
3.734375
4
[]
no_license
/* Every non-negative integer N has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation. The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. For example, the complement of "101" in binary is "010" in binary. For a given number N in base-10, return the complement of it's binary representation as a base-10 integer. Example 1: Input: 5 Output: 2 Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10. Example 2: Input: 7 Output: 0 Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. Example 3: Input: 10 Output: 5 Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10. Note: 0 <= N < 10^9 */ class Solution { public: int bitwiseComplement(int N) { if(N == 0) return 1; int i = 1; while(i<=N){ i*=2; } return i-N-1; } };
true
c20b40945248b9c379aad99342bd3bb425d06b9e
C++
banetta/kpu_airport_control_system
/source/cpp/header/flightschedule.h
UHC
600
2.765625
3
[]
no_license
//by YHS #ifndef _FLIGHTSCHEDULE_ #define _FLIGHTSCHEDULE_ #include "main_header.h" // ¼ ִ. class ControlTower; class FlightSchedule { // Ŭ private: string airline; string destination; int seat[3]; int hour; string shit; int min; public: FlightSchedule() {}; // Ʈ FlightSchedule(string fairline, string fdestination, int* fseat, int fhour, string fshit, int fmin); void takeoff_check(ControlTower &ct); // ¼ üũ Լ void showthat(); }; #endif
true
1d2114982e80b1dd5da8296a46847d9afca3391a
C++
gorkinovich/LP2
/P01/A03/FDelincuentes.cpp
ISO-8859-1
13,407
2.71875
3
[ "MIT" ]
permissive
//--------------------------------------------------------------------------- // Gorka Surez Garca - Ing. Tec. Inf. de Gestin 2 B. // Prctica 01 - Apartado 03. //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop //--------------------------------------------------------------------------- #include "FDelincuentes.h" #include "FBusqueda.h" #include "Util.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TDelincuentes *Delincuentes; //--------------------------------------------------------------------------- /** * Funcin que mete en una etiqueta un nmero como texto de esta. * @param lbl Equiqueta que modificar. * @param numero Nmero que se va a mostrar en la etiqueta. */ void MeterNumeroEnLabel (TLabel * lbl, int numero) { lbl->Caption = lbl->Caption.sprintf("%d", numero + 1); } //--------------------------------------------------------------------------- __fastcall TDelincuentes::TDelincuentes(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- /** * Funcin que recoge del formulario los datos que formarn el delincuente * que estamos creando o modificando. * @return Devuelve el delincuente modificado. */ TDelincuente __fastcall TDelincuentes::dameDelincuente (void) { TCara aux; this->ObtenerCaraDeCheckButtons(aux); return inicializaDelincuente(this->TxtNombre->Text.c_str(), this->TxtDelitos->Text.c_str(), aux); } //--------------------------------------------------------------------------- /** * Funcin que recoge del formulario la cara que est seleccionada. * @param cara Cara que vamos a devolver. * @see ActualizarCheckButtons() */ void TDelincuentes::ObtenerCaraDeCheckButtons (TCara & cara) { cara = inicializaCara(this->RBTipoPelo->ItemIndex, this->RBTipoOjos->ItemIndex, this->RBTipoOrejas->ItemIndex, this->RBTipoBoca->ItemIndex); } //--------------------------------------------------------------------------- /** * Funcin que actualiza el formulario en base a una cara ya formada. * @param cara Cara que va a servir para actualizar los datos. * @see ObtenerCaraDeCheckButtons() */ void TDelincuentes::ActualizarCheckButtons (const TCara & cara) { this->RBTipoPelo->ItemIndex = getPelo(cara); this->RBTipoOjos->ItemIndex = getOjos(cara); this->RBTipoBoca->ItemIndex = getNarizYOrejas(cara); this->RBTipoOrejas->ItemIndex = getBoca(cara); } //--------------------------------------------------------------------------- /** * Funcin que carga en el formulario los datos de una posicin dada de la * lista de delincuentes que tenemos almacenados. * @param i Nmero de delincuente dentro de la lista. */ void __fastcall TDelincuentes::posicionar (int i) { if(i < getNumero(this->delincuentes)) { TDelincuente aux; getDelincuente(this->delincuentes, i, aux); this->TxtNombre->Text = (getNombre(aux)).c_str(); this->TxtDelitos->Text = (getDelitos(aux)).c_str(); this->Retrato->Text = dameCara(getCara(aux)).c_str(); this->ActualizarCheckButtons(getCara(aux)); this->index = i; MeterNumeroEnLabel(this->LblNumFicha, this->index); } } //--------------------------------------------------------------------------- /** * Funcin para actualizar la cara mostrada en el memo del formulario. */ void __fastcall TDelincuentes::actualizarCara (void) { string pelo = damePelo(this->RBTipoPelo->ItemIndex); string ojos = dameOjos(this->RBTipoOjos->ItemIndex); string narizOrejas = dameOrejasYNariz(this->RBTipoBoca->ItemIndex); string boca = dameBoca(this->RBTipoOrejas->ItemIndex); //----------------------------------------------------------------------- // Actualizamos el cuadro de texto con el retrato. //----------------------------------------------------------------------- this->Retrato->Lines->Clear(); this->Retrato->Lines->Add(pelo.c_str()); this->Retrato->Lines->Add(ojos.c_str()); this->Retrato->Lines->Add(narizOrejas.c_str()); this->Retrato->Lines->Add(boca.c_str()); this->Retrato->Lines->Add(" \\_____/"); } //--------------------------------------------------------------------------- /** * Funcin para generar un delincuente "vacio" en el formulario. * @see actualizarCara() */ void __fastcall TDelincuentes::vacia (void) { this->TxtNombre->Text = ""; this->TxtDelitos->Text = ""; this->actualizarCara(); } //--------------------------------------------------------------------------- /** * Funcin que agrega un delincuente a la lista del programa. * @param delincuente Delincuente que queremos agregar. * @see modificarDelincuente(), borrarDelincuente() */ void __fastcall TDelincuentes::agregarDelincuente (TDelincuente delincuente) { int indice; if(!getDelincuente(this->delincuentes, getNombre(delincuente), indice)) { if(!agregaDelincuente(this->delincuentes, delincuente)) MessageBox(Application->Handle, "No hay espacio en la base de datos.", "Base de datos completa", MB_ICONWARNING); } else { MessageBox(Application->Handle, "El criminal ya existe, por lo que debera modificarlo.", "Registro ya existente", MB_ICONWARNING); } } //--------------------------------------------------------------------------- /** * Funcin que modifica un delincuente en la lista del programa. * @param delincuente Delincuente que queremos modificar. * @see agregarDelincuente(), borrarDelincuente() */ void __fastcall TDelincuentes::modificarDelincuente (TDelincuente delincuente) { int indice; if(getDelincuente(this->delincuentes, getNombre(delincuente), indice)) { this->delincuentes.delincuentes[indice] = delincuente; } else { MessageBox(Application->Handle, "El criminal no existe, por lo que debera agregarlo.", "Registro inexistente", MB_ICONWARNING); } } //--------------------------------------------------------------------------- /** * Funcin que borra un delincuente en la lista del programa. * @param delincuente Delincuente que queremos borrar. * @see agregarDelincuente(), modificarDelincuente() */ void __fastcall TDelincuentes::borrarDelincuente (TDelincuente delincuente) { if(!borraDelincuente(this->delincuentes, getNombre(delincuente))) { if(getNumero(this->delincuentes) > 0) MessageBox(Application->Handle, "El registro que intenta borrar no existe.", "Registro inexistente", MB_ICONWARNING); else MessageBox(Application->Handle, "La base de datos de criminales est vaca.", "Base de datos vaca", MB_ICONWARNING); } } //--------------------------------------------------------------------------- /** * Funcin que pasa al anterior delincuente de la lista. * @param Sender Objeto que llama al mtodo. * @see CmdSigClick() */ void __fastcall TDelincuentes::CmdAntClick(TObject *Sender) { if(index > 0) this->posicionar(this->index - 1); else this->posicionar(0); } //--------------------------------------------------------------------------- /** * Funcin que pasa al siguiente delincuente de la lista. * @param Sender Objeto que llama al mtodo. * @see CmdAntClick() */ void __fastcall TDelincuentes::CmdSigClick(TObject *Sender) { this->posicionar(this->index + 1); } //--------------------------------------------------------------------------- /** * Funcin que agrega el delincuente formado a la lista. * @param Sender Objeto que llama al mtodo. * @see CmdBorrarClick(), CmdModificarClick(), CmdBuscarClick() */ void __fastcall TDelincuentes::CmdAgregarClick(TObject *Sender) { TDelincuente aux = this->dameDelincuente(); this->agregarDelincuente(aux); this->posicionar(getNumero(this->delincuentes) - 1); } //--------------------------------------------------------------------------- /** * Funcin que borra el delincuente formado a la lista. * @param Sender Objeto que llama al mtodo. * @see CmdAgregarClick(), CmdModificarClick(), CmdBuscarClick() */ void __fastcall TDelincuentes::CmdBorrarClick(TObject *Sender) { TDelincuente aux = this->dameDelincuente(); this->borrarDelincuente(aux); if(this->delincuentes.ultimo > 0) this->CmdAntClick(NULL); else this->vacia(); } //--------------------------------------------------------------------------- /** * Funcin que modifica el delincuente formado a la lista. * @param Sender Objeto que llama al mtodo. * @see CmdAgregarClick(), CmdBorrarClick(), CmdBuscarClick() */ void __fastcall TDelincuentes::CmdModificarClick(TObject *Sender) { TDelincuente aux = this->dameDelincuente(); this->modificarDelincuente(aux); } //--------------------------------------------------------------------------- /** * Funcin que busca un delincuente en la lista. * @param Sender Objeto que llama al mtodo. * @see CmdAgregarClick(), CmdBorrarClick(), CmdModificarClick() */ void __fastcall TDelincuentes::CmdBuscarClick(TObject *Sender) { Busqueda->ShowModal(); TCara cara = Busqueda->dameCara(); if((getPelo(cara) != 3) && (getOjos(cara) != 3) && (getNarizYOrejas(cara) != 3) && (getBoca(cara) != 3)) { int indice; if(getDelincuente(this->delincuentes, cara, indice)) { this->posicionar(indice); } else { MessageBox(Application->Handle, "La cara que busca no ha podido ser encontrada.", "Busqueda sin resultados", MB_ICONWARNING); } } } //--------------------------------------------------------------------------- /** * Funcin que se ejecuta al crear el formulario. * @param Sender Objeto que llama al mtodo. */ void __fastcall TDelincuentes::FormCreate(TObject *Sender) { FILE * f; this->index = 0; this->delincuentes = inicializaContenedorDelincuentes(); f = fopen("delincuentes.dat", "rb"); if(f != NULL) { TDelincuente aux; char letra; while(!feof(f)) { aux.nombre = ""; do{ fread(&letra, sizeof(char), 1, f); if(letra != 0) aux.nombre += letra; }while(letra != 0); aux.delitos = ""; do{ fread(&letra, sizeof(char), 1, f); if(letra != 0) aux.delitos += letra; }while(letra != 0); fread(&(aux.cara), sizeof(aux.cara), 1, f); if(aux.nombre != "") this->agregarDelincuente(aux); } } fclose(f); this->posicionar(0); } //--------------------------------------------------------------------------- /** * Funcin que se ejecuta al finalizar la aplicacin. * @param Sender Objeto que llama al mtodo. */ void __fastcall TDelincuentes::FormDestroy(TObject *Sender) { FILE * f; char zero = 0; f = fopen("delincuentes.dat", "wb"); if(f != NULL) { for(int i = 0; i < this->delincuentes.ultimo; ++i) { fprintf(f, "%s", this->delincuentes.delincuentes[i].nombre.c_str()); fwrite(&zero, sizeof(char), 1, f); fprintf(f, "%s", this->delincuentes.delincuentes[i].delitos.c_str()); fwrite(&zero, sizeof(char), 1, f); fwrite(&(this->delincuentes.delincuentes[i].cara), sizeof(TCara), 1, f); } } fclose(f); } //--------------------------------------------------------------------------- /** * Funcin que se ejecuta al mostrar el formulario. * @param Sender Objeto que llama al mtodo. */ void __fastcall TDelincuentes::FormShow(TObject *Sender) { this->actualizarCara(); MeterNumeroEnLabel(this->LblNumFicha, this->index); } //--------------------------------------------------------------------------- /** * Funcin que se ejecuta al cambiar el tipo de pelo. * @param Sender Objeto que llama al mtodo. */ void __fastcall TDelincuentes::RBTipoPeloClick(TObject *Sender) { this->actualizarCara(); } //--------------------------------------------------------------------------- /** * Funcin que se ejecuta al cambiar el tipo de ojos. * @param Sender Objeto que llama al mtodo. */ void __fastcall TDelincuentes::RBTipoOjosClick(TObject *Sender) { this->actualizarCara(); } //--------------------------------------------------------------------------- /** * Funcin que se ejecuta al cambiar el tipo de boca. * @param Sender Objeto que llama al mtodo. */ void __fastcall TDelincuentes::RBTipoBocaClick(TObject *Sender) { this->actualizarCara(); } //--------------------------------------------------------------------------- /** * Funcin que se ejecuta al cambiar el tipo de nariz y orejas. * @param Sender Objeto que llama al mtodo. */ void __fastcall TDelincuentes::RBTipoOrejasClick(TObject *Sender) { this->actualizarCara(); } //--------------------------------------------------------------------------- // Fin FDelincuentes.cpp //---------------------------------------------------------------------------
true
b0e7f7a3aaa59302f08ef8c3cdd80445df6f4b02
C++
LArSoft/lardataobj
/lardataobj/RawData/RawDigit.h
UTF-8
7,355
2.828125
3
[]
no_license
/** **************************************************************************** * @file RawDigit.h * @brief Definition of basic raw digits * @author brebel@fnal.gov * @see RawDigit.cxx raw.h * * Compression/uncompression utilities are declared in lardata/RawData/raw.h . * * Changes: * 20141210 Gianluca Petrillo (petrillo@fnal.gov) * data architecture revision changes: * - fADC made private * - removed constructor not assigning sample number * - added flags interface * * 2/19/2008 Mitch Soderberg * -modified RawDigit class slightly to be compatible with binary output of DAQ software, * and to include \# samples/channel explicity, instead of via sizeof() methods. * * ****************************************************************************/ #ifndef RAWDATA_RAWDIGIT_H #define RAWDATA_RAWDIGIT_H // C/C++ standard libraries #include <cstdlib> // size_t #include <vector> // LArSoft libraries #include "larcoreobj/SimpleTypesAndConstants/RawTypes.h" // raw::Compress_t, raw::Channel_t // ROOT includes #include "RtypesCore.h" /// Raw data description and utilities namespace raw { /** * @brief Collection of charge vs time digitized from a single readout channel * * This class hosts potentially compressed data. * It does not provide methods to uncompress it, not the same object can * become compressed/uncompressed or change compression type: to use a * compressed RawDigit, one has to create a new buffer, fill and use it: * * raw::RawDigit::ADCvector_t ADCs(digits.Samples()); // fix the size! * raw::Uncompress(digits.ADCs(), ADCs, digits.Compression()); * * (remember that you have to provide raw::Uncompress() with a buffer large * enough to contain the uncompressed data). * * The class provides some flags, defined in FlagIndices_t. * The construction of a RawDigit should be for example in the form: * * raw::RawDigit::ADCvector_t ADCs; * // ... fill the digits etc. * raw::RawDigit saturatedDigit( * channel, ADCs.size(), ADCs, raw::kNone, * DefaultFlags | SaturationBit * ); * raw::RawDigit unsaturatedDigit( * channel, ADCs.size(), ADCs, raw::kNone, * DefaultFlags & ~SaturationBit * ); * * */ class RawDigit { public: /// Type representing a (compressed) vector of ADC counts typedef std::vector<short> ADCvector_t; /* // removed waiting for a real use for flags /// Type for the digit flags typedef std::bitset<16> Flags_t; */ /// Default constructor: an empty raw digit RawDigit(); public: /* // removed waiting for a real use for flags typedef enum { fiSaturation, ///< saturation flag: set if saturated at any time NLArSoftFlags = 8, ///< LArSoft reserves flags up to here (this excluded) NFlagIndices = NLArSoftFlags ///< number of flags } FlagIndices_t; ///< type of index of flags */ /** * @brief Constructor: sets all the fields * @param channel ID of the channel the digits were acquired from * @param samples number of ADC samples in the uncompressed collection * @param adclist list of ADC counts vs. time, compressed * @param compression compression algorithm used in adclist * * Data from the adclist is copied into the raw digits. * Pedestal is set to 0 by default. */ RawDigit(ChannelID_t channel, ULong64_t samples, ADCvector_t const& adclist, raw::Compress_t compression = raw::kNone /*, const Flags_t& flags = DefaultFlags */ ); /** * @brief Constructor: sets all the fields * @param channel ID of the channel the digits were acquired from * @param samples number of ADC samples in the uncompressed collection * @param adclist list of ADC counts vs. time, compressed * @param compression compression algorithm used in adclist * * Data from the adclist is moved into the raw digits. * Pedestal is set to 0 by default. */ RawDigit(ChannelID_t channel, ULong64_t samples, ADCvector_t&& adclist, raw::Compress_t compression = raw::kNone /*, const Flags_t& flags = DefaultFlags */ ); /// Set pedestal and its RMS (the latter is 0 by default) void SetPedestal(float ped, float sigma = 1.); ///@{ ///@name Accessors /// Reference to the compressed ADC count vector const ADCvector_t& ADCs() const; /// Number of elements in the compressed ADC sample vector size_t NADC() const; /// ADC vector element number i; no decompression is applied short ADC(int i) const; /// DAQ channel this raw data was read from ChannelID_t Channel() const; /// Number of samples in the uncompressed ADC data ULong64_t Samples() const; /// Pedestal level (ADC counts) /// @deprecated Might be removed soon float GetPedestal() const; /// TODO RMS of the pedestal level? float GetSigma() const; /// Compression algorithm used to store the ADC counts raw::Compress_t Compression() const; ///@} /* // removed waiting for a real use for flags ///@{ ///@name Raw digit flag interface /// Flag set const Flags_t& Flags() const; /// Returns if saturation bit is set bool isSaturated() const; // the unsigned long long thing is from std::bitset<> constructors /// Bit for saturation static const unsigned long long SaturationBit = 1ULL << fiSaturation; /// Flags for a digit constructred by default static const unsigned long long DefaultFlags = 0ULL; ///@} */ private: std::vector<short> fADC; ///< ADC readout per tick, before pedestal subtraction ChannelID_t fChannel; ///< channel number in the readout ULong64_t fSamples; ///< number of ticks of the clock float fPedestal; ///< pedestal for this channel float fSigma; ///< sigma of the pedestal counts for this channel Compress_t fCompression; ///< compression scheme used for the ADC vector // removed waiting for a real use for flags // Flags_t fFlags; ///< set of digit flags }; // class RawDigit } // namespace raw //------------------------------------------------------------------------------ //--- inline implementation //--- inline size_t raw::RawDigit::NADC() const { return fADC.size(); } inline short raw::RawDigit::ADC(int i) const { return fADC.at(i); } inline const raw::RawDigit::ADCvector_t& raw::RawDigit::ADCs() const { return fADC; } inline raw::ChannelID_t raw::RawDigit::Channel() const { return fChannel; } inline ULong64_t raw::RawDigit::Samples() const { return fSamples; } inline float raw::RawDigit::GetPedestal() const { return fPedestal; } inline float raw::RawDigit::GetSigma() const { return fSigma; } inline raw::Compress_t raw::RawDigit::Compression() const { return fCompression; } /* // removed waiting for a real use for flags inline const raw::RawDigit::Flags_t& raw::RawDigit::Flags() const { return fFlags; } inline bool raw::RawDigit::isSaturated() const { return fFlags.test(fiSaturation); } */ #endif // RAWDATA_RAWDIGIT_H ////////////////////////////////////////////////////////////////////////
true
c22d4ea6e40a6fbe5ee1bd2efb4a83fcc374fdd9
C++
UFC-MDCC-HPC/PobCPP
/pork/elsa/elkhound/examples/gcom4/parser.cc
UTF-8
1,393
2.734375
3
[]
no_license
// parser.cc // driver program for guarded command example #include "lexer.h" // Lexer #include "gcom.h" // GCom #include "glr.h" // GLR #include "ptreenode.h" // PTreeNode #include "ptreeact.h" // ParseTreeLexer, ParseTreeActions #include <cstring> // strcmp int main(int argc, char *argv[]) { // use "-tree" command-line arg to print the tree bool printTree = argc==2 && 0==strcmp(argv[1], "-tree"); // create and initialize the lexer Lexer lexer; lexer.nextToken(&lexer); // create the parser context object GCom gcom; if (printTree) { // wrap the lexer and actions with versions that make a parse tree ParseTreeLexer ptlexer(&lexer, &gcom); ParseTreeActions ptact(&gcom, gcom.makeTables()); // initialize the parser GLR glr(&ptact, ptact.getTables()); // parse the input SemanticValue result; if (!glr.glrParse(ptlexer, result)) { printf("parse error\n"); return 2; } // print the tree PTreeNode *ptn = (PTreeNode*)result; ptn->printTree(std::cout, PTreeNode::PF_EXPAND); } else { // initialize the parser GLR glr(&gcom, gcom.makeTables()); // parse the input SemanticValue result; if (!glr.glrParse(lexer, result)) { printf("parse error\n"); return 2; } // print result printf("result: %d\n", (int)result); } return 0; }
true
9c341ca8329f332244fa159e5266a9626c7ebc0d
C++
csietingkai/leetcode
/(0084) largest rectangle in histogram.cpp
UTF-8
417
3.25
3
[]
no_license
class Solution { public: int largestRectangleArea(vector<int>& heights) { int max = 0; for (int i = 0; i < heights.size(); i++) { int min_height = heights[i]; for (int j = i; j < heights.size(); j++) { if (min_height > heights[j]) { min_height = heights[j]; } int rect_value = min_height * (j - i + 1); if (rect_value > max) { max = rect_value; } } } return max; } };
true
9a47799343dd9171d888e898f2619ed1ff42eea7
C++
mutual-ai/jules
/include/jules/base/const_vector.hpp
UTF-8
5,796
3.453125
3
[ "Zlib" ]
permissive
// Copyright (c) 2017 Filipe Verri <filipeverri@gmail.com> // My soul melts away for sorrow; // strengthen me according to your word! // Psalm 119:28 (ESV) #ifndef JULES_BASE_CONST_VECTOR_H /// \exclude #define JULES_BASE_CONST_VECTOR_H #include <memory> #include <type_traits> #include <vector> namespace jules { /// Sequence container with constant size and elements. /// /// The elements are stored contiguously and cannot be changed after /// the vector construction. /// /// \notes Unused memory is always freed. template <typename T, typename Allocator = typename std::vector<T>::allocator_type> class const_vector { public: /// \group member_types Class Types using container_type = std::vector<T, Allocator>; /// \group member_types using value_type = T; /// \group member_types using allocator_type = Allocator; /// \group member_types using size_type = typename container_type::size_type; /// \group member_types using difference_type = typename container_type::difference_type; /// \group member_types using const_reference = typename container_type::const_reference; /// \group member_types using const_iterator = typename container_type::const_iterator; /// \group member_types using const_reverse_iterator = typename container_type::const_reverse_iterator; ~const_vector() = default; /// \group constructors Constructors /// Constructs a constant vector: /// /// (1) with no elements. /// /// (2) by forwarding the parameters to the underlying standard vector. /// /// (3) explicitly by forwarding one parameter to the underlying standard vector. /// /// (4) from a standard vector. /// /// (5) from a initializer list. /// /// (6-7) from another vector. const_vector() : data_{std::make_shared<container_type>()} {} /// \group constructors template <typename... Args, typename = std::enable_if_t<(sizeof...(Args) > 1)>> const_vector(Args&&... args) : data_{std::make_shared<container_type>(std::forward<Args>(args)...)} {} /// \group constructors template <typename Arg> explicit const_vector(Arg&& arg) : data_{std::make_shared<container_type>(std::forward<Arg>(arg))} {} /// \group constructors const_vector(container_type source) : data_{std::make_shared<container_type>(std::move(source))} {} /// \group constructors const_vector(std::initializer_list<value_type> init, const allocator_type& alloc = {}) : data_{std::make_shared<container_type>(init, alloc)} {} /// \group constructors const_vector(const const_vector& source) = default; /// \group constructors const_vector(const_vector&& source) noexcept = default; /// \group assignment Assignment /// /// (1) Copy assignment. /// /// (2) Move assignment. auto operator=(const const_vector& source) -> const_vector& = default; /// \group assignment auto operator=(const_vector&& source) noexcept -> const_vector& = default; /// TODO: assign and get_allocator /// \group access Element access /// /// Accessing elements. /// /// (1) Access specified element with bounds checking. /// /// (2) Access specified element. /// /// (3) Access the first element. /// /// (4) Access the last element. /// /// (5) Direct access to the underlying array. auto at(size_type pos) const -> const_reference { return data_->at(pos); } /// \group access auto operator[](size_type pos) const -> const_reference { return (*data_)[pos]; } /// \group access auto front() const -> const_reference { return data_->front(); } /// \group access auto back() const -> const_reference { return data_->back(); } /// \group access auto data() const -> const value_type* { return data_->data(); } /// \group iterator Iterators /// /// (1-2) returns an iterator to the beginning. /// /// (3-4) returns an iterator to the end. /// /// (5-6) returns a reverse iterator to the beginning. /// /// (7-8) returns a reverse iterator to the end. auto begin() const -> const_iterator { return cbegin(); } /// \group iterator auto cbegin() const -> const_iterator { return data_->cbegin(); } /// \group iterator auto end() const -> const_iterator { return cend(); } /// \group iterator auto cend() const -> const_iterator { return data_->cend(); } /// \group iterator auto rbegin() const -> const_iterator { return crbegin(); } /// \group iterator auto crbegin() const -> const_iterator { return data_->crbegin(); } /// \group iterator auto rend() const -> const_iterator { return crend(); } /// \group iterator auto crend() const -> const_iterator { return data_->crend(); } /// \group capacity Capacity /// /// (1) checks whether the container is empty. /// /// (2) returns the number of elements. auto empty() const -> bool { return data_->empty(); } /// \group capacity auto size() const -> size_type { return data_->size(); } /// \group comparison Comparison /// Lexicographically compares the values in the vector. auto operator==(const const_vector& other) const -> bool { return *data_ == *other.data_; } /// \group comparison auto operator!=(const const_vector& other) const -> bool { return *data_ != *other.data_; } /// \group comparison auto operator<(const const_vector& other) const -> bool { return *data_ < *other.data_; } /// \group comparison auto operator<=(const const_vector& other) const -> bool { return *data_ <= *other.data_; } /// \group comparison auto operator>(const const_vector& other) const -> bool { return *data_ > *other.data_; } /// \group comparison auto operator>=(const const_vector& other) const -> bool { return *data_ >= *other.data_; } private: std::shared_ptr<container_type> data_; }; } // namespace jules #endif // JULES_BASE_CONST_VECTOR_H
true
fb81956984b548127fd98baf5c703af6a8bb03ca
C++
gilbertoesp/EstructurasDeDatos
/EstructurasLineales/ListaOrdenadaRepBaja.h
UTF-8
2,227
3.140625
3
[]
no_license
#ifndef LISTAORDENADAREPBAJA_H_INCLUDED #define LISTAORDENADAREPBAJA_H_INCLUDED #include "Caja.h" #include "Enumeraciones.h" /** Estructura lineal que organiza los datos dados de menor a mayor Esta Lista permite la repeticion de Datos, se recomineda que la repeticion de esta sea pequena ya que genera una nueva caja por cada valor repetido o no */ //******************************************************************************************* class ListaOrdenadaRepBaja{ ///Inicio de la lista. Variable auxiliar para desplazarnos en la Lista de forma interna Caja *principio,*anterior; /// Ultimo dato en ser agregado Caja *lugar_agregado; int cuantos; Posicion donde; Boolean encontrado; public: /** Constructor que inicializa los atributos del objeto en NULL o 0, segun corresponda */ ListaOrdenadaRepBaja(); /** Destructor que libera la memoria solicitada de toda la estructura */ ~ListaOrdenadaRepBaja(); /** Dado un Dato, los busca en la ListaOrdenadaRepBaja desde principio, guardando la informacion de la busqueda en las variables auxiliares (Caja*) anterior, (Posicion) donde y (Boolean) encontrado \param a Dato a buscar */ void buscar(int a); /** Agrega el nuevo dato al estructura \param a Dato a agregar */ void agregar(int a); /** Elimina un Dato especifico de la lista \param Dato a eliminar \return 0 Si el dato no se encuentra, (no se logro borrar) 1 si el dato fue borrado */ int borrar(int a); /** Retira el dato que sigue segun la naturaleza de la estructura, eliminando su espacio en memoria y solo regresando el Dato (int) \return Siguiente valor en la estructura */ int sacar(); /** Pinta la estructra en orden */ void pintar(); /** \return Cantidad de Datos en la estructura */ int cuantosSon(); /** El ultimo Dato agregado se guarda en la variable auxiliar lugar_agregado, para conseguirlo, se utiliza esta funcion \return Ultimo dato en ser agregado a la estructura */ Caja * LugarAgregado(); }; #endif // LISTAORDENADAREPBAJA_H_INCLUDED
true
2ac9fea95f1f3ba8a6319ffbd6363967b203080b
C++
elingg/cognitive-dissonance
/project/code/KalmanFilter.cpp
UTF-8
3,168
2.5625
3
[]
no_license
#include "KalmanFilter.h" #include "cv.h" #include "cxcore.h" #include "cvaux.h" #include "objects.h" #include "highgui.h" #include <iostream> using namespace std; /** * Utility function to convert a CvBlob to a CObject */ CObject cvBlobToCObject(CvBlob* blob, string label) { CObject obj; obj.rect = cvRect(0, 0, blob->w, blob->h); obj.rect.x = blob->x; obj.rect.y = blob->y; obj.label = label; return obj; } /** * Utility function to convert a CObject to CvBlob */ CvBlob cObjectToCVBlob(CObject cObject) { CvBlob blob; blob.x = cObject.rect.x; blob.y = cObject.rect.y; blob.w = cObject.rect.width; blob.h = cObject.rect.height; return blob; } /** * Kalman Filter */ KalmanFilter::KalmanFilter() {} KalmanFilter::~KalmanFilter() {} /** * Runs the update step for all the filters */ void KalmanFilter::update(CObjectList* classifierObjects) { size_t numFilters = filters.size(); //need this because the filters.size changes bool shouldPenalize[numFilters]; for(size_t i = 0; i < numFilters; i++) { shouldPenalize[i] = true; } for(size_t i = 0; i < classifierObjects->size(); i++) { bool foundMatchingBlob = false; for(size_t j = 0; j < filters.size(); j++) { CObject predicted = filters[j].predict(); if(predicted.label == classifierObjects->at(i).label) { //check overlap between filter and classifier object int overlap = predicted.overlap(classifierObjects->at(i)); double overlapRatio = (double) (2*overlap) / (predicted.area() + classifierObjects->at(i).area()); if(overlapRatio >= 0.8) { filters[j].update(classifierObjects->at(i)); filters[j].incrementCount(); shouldPenalize[j] = false; foundMatchingBlob = true; break; } } } if(!foundMatchingBlob) { //Create new blob because none was found KFObject kfObject; kfObject.update(classifierObjects->at(i)); filters.push_back(kfObject); } } for(size_t i = 0; i < numFilters; i++) { if(shouldPenalize[i]) { filters[i].decrementCount(); } } } /** * Runs predict step for all the kalman filters */ CObjectList KalmanFilter::predict() { kalmanObjects.clear(); for(size_t i = 0; i < filters.size(); i++) { if(filters[i].getCount() > 0) { CObject obj = filters[i].predict(); kalmanObjects.push_back(obj); } } for(size_t i = 0; i < filters.size(); i++) { if(filters[i].getCount() < -3) { filters.erase(filters.begin() + i); } } return kalmanObjects; } /** * Individual Kalman Filters for each blob tracked */ KFObject::KFObject() { count = 0; predictor = cvCreateModuleBlobTrackPredictKalman(); }; KFObject::~KFObject() {}; CObject KFObject::predict() { CvBlob* predicted = predictor->Predict(); return cvBlobToCObject(predicted, label); } void KFObject::update(CObject object) { label = object.label; CvBlob blob = cObjectToCVBlob(object); predictor->Update(&blob); } int KFObject::getCount() { return count; } void KFObject::incrementCount() { count++; } void KFObject::decrementCount() { count--; }
true
ce1ce7466ae0e0d08c958516f184939975c62e5b
C++
OPilgrim/circle-area
/Circle.cpp
GB18030
426
3.34375
3
[]
no_license
#include"CIRCEL.H" Circel::Circel() { this->r=0; //ʼrthis-> Ե } //һʼûиִֵʾ Circel::circel(double R) { this->r=R; //ֵr=R } double Circel::Area() { return 3.14*r*r; // } //ȻֱR㣬privateûˡȻֻһС򣬵еϰҪе
true
43dd9b300c3527b10d079928158fe11fbb37ac68
C++
luigibrancati/snake_game
/food.hpp
UTF-8
406
3.296875
3
[]
no_license
#ifndef _FOOD_H_ #define _FOOD_H_ #include <iostream> class Food { short pos_x; short pos_y; char symbol; public: Food(short x, short y, char s='x'): pos_x(x), pos_y(y), symbol(s) {} short getX() const {return this->pos_x;} short getY() const {return this->pos_y;} char getS() const {return this->symbol;} void replace(short x, short y){ this->pos_x=x; this->pos_y=y; } }; #endif
true
ae48e44dcd350369abc81fa9e821df21f6e4a57f
C++
qianwenxu/compiler
/node.h
UTF-8
6,080
2.734375
3
[]
no_license
#pragma once #include "cn.h" #include "entrytable.h" #include "fourele.h" #include<math.h> #define MAXCHILDREN 10 //每一个树结点所拥有的孩子结点的最大个数 class treenode { public: treenode* children[MAXCHILDREN]; int value_type;//int 1 float 2 double 3 char 4 ID 5 STRING 6 类型7 修饰符8 其他9 int children_number; float value_float; int value_int; char value_char; char* value_bool; char* value_name; string node_name; int array[15]; long long int value_temp; int curtable; int pointor_number; int array_number; int node_type; fourele *four; string temp; int minlabel; int maxlabel; string code_str=""; public: treenode() { this->children_number = 0; this->value_type = 0; this->value_temp = 0; this->curtable = current; this->pointor_number = 0; this->array_number = 0; for (int i = 0; i<15; i++) this->array[i] = 0; four = new fourele(); minlabel = 999999; maxlabel = -1; }; string tostring(int num) { string re = ""; while (num > 0) { int key = num % 100; char keychar = char(key + '/'); re += keychar; num = num / 100; } return re; }; string nametostring(long long int num) { string re = ""; while (num > 0) { int key = num % 1000; char keychar = key; re += keychar; num = num / 1000; } return re; } void nametofloat() { for (int i = strlen(this->value_name) - 1; i >= 0; i--) { this->value_temp = this->value_temp * 100 + this->value_name[i] - '/'; } }; void chartofloat() { this->value_temp = this->value_char; }; void booltofloat() { if (value_bool == "true") { this->value_temp = 1; } if (value_bool == "false") { this->value_temp = 0; } }; void stringtofloat() { temp = this->value_name; } void setarray() { int k = this->curtable; entry temp; while (k != -1) { int num = entrytable[k].number; for (int i = 0; i < num; i++) { temp = entrytable[k].item[i]; if (temp.name == this->value_temp) { for (int j = 0; j<15; j++) { this->array[j] = temp.eachrow[j]; } break; } } k = entrytable[k].parent; } } void changearray(treenode * t) { for (int i = 0; i<14; i++) this->array[i] = t->array[i + 1]; this->array[14] = 0; for (int i = 14; i>0; i--) if (this->array[i] != 0) { this->array[i] -= 1; break; } } void copyarray(treenode *s) { for (int i = 0; i<15; i++) this->array[i] = s->array[i]; } void changede(int a, int n, int p[15]) { int k = this->curtable; entry temp; while (k != -1) { int num = entrytable[k].number; for (int i = 0; i < num; i++) { if (entrytable[k].item[i].name == this->value_temp) { entrytable[k].item[i].deep_array = n; entrytable[k].item[i].entry_type = a; for (int sd = 0; sd<15; sd++) entrytable[k].item[i].eachrow[sd] = p[sd]; break; } } k = entrytable[k].parent; } } int findtype() { int k = this->curtable; entry temp; while (k != -1) { int num = entrytable[k].number; for (int i = 0; i < num; i++) { temp = entrytable[k].item[i]; if (temp.name == this->value_temp) return temp.entry_type; } k = entrytable[k].parent; } if (k == -1) { //cout<<this->value_temp; //cout<<this->curtable; } return -1; } int findpointordeep() { int k = this->curtable; entry temp; while (k != -1) { int num = entrytable[k].number; for (int i = 0; i < num; i++) { temp = entrytable[k].item[i]; if (temp.name == this->value_temp) return temp.deep_pointer; //cout << "temp.deep_array:" << temp.deep_array << "temp.deep_pointer" << temp.deep_pointer; } k = entrytable[k].parent; } return -1; } int findarraydeep() { int k = this->curtable; entry temp; while (k != -1) { int num = entrytable[k].number; for (int i = 0; i < num; i++) { temp = entrytable[k].item[i]; if (temp.name == this->value_temp) return temp.deep_array; //cout << "temp.deep_array:" << temp.deep_array << "temp.deep_pointer" << temp.deep_pointer; } k = entrytable[k].parent; } return -1; } bool ifcompare(treenode *s) { if (this->node_type != s->node_type) { cout << "node_type" << endl; return false; } else if ((this->pointor_number + this->array_number) != (s->pointor_number + s->array_number)) { cout << "node_add" << endl; return false; } else { for (int j = 14; j>0; j--) if (this->array[j] == s->array[j]) continue; else if (j == 1 && (s->pointor_number == 1 || this->pointor_number == 1)) return true; else { cout << "node_array" << endl; return false; } } return true; } string getre() { string arg = ""; if (this->value_type == 5) { long long int num = this->value_temp; while (num > 0) { int key = num % 100; arg += char(key + '/'); num = num / 100; } } else if (this->value_type == 1) arg = to_string(this->value_int); else if (this->value_type == 2 || this->value_type == 3) arg = to_string(this->value_float); else if (this->value_type == 4) { arg += "'"; arg += char(this->value_temp); arg += "'"; } else if (this->value_type == 6) { arg = temp; } else if (this->value_type == 6) arg = nametostring(this->value_temp); else if (this->value_type == 10) arg = this->value_bool; else arg = this->four->getre(); return arg; } void setarg(treenode * s, int num) { string arg = s->getre(); if (num == 1) this->four->setarg1(arg); else this->four->setarg2(arg); if (this->minlabel < s->minlabel) this->minlabel = s->minlabel; } void setre(int num) { this->four->setresult(num); } void setre(string s) { this->four->setre(s); } void setlabel(int label) { this->four->setlabel(label); this->maxlabel = label; this->minlabel = label; } void setopr(string oper) { this->four->setoper(oper); } bool ifexist() { if (this->maxlabel == -1||this->minlabel== 999999)return false; //if (this->four->arg1 == ""&&this->four->arg2 == ""&&this->four->oper == "")return false; else return true; } };
true
dceede3cbbcf48097f1287136bad70c970af27e4
C++
APU160139/LIGHT-OJ
/1354 - IP Checking.cpp
UTF-8
720
2.890625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int binary(int n); int main() { int a,b,c,d,e,f,g,h,i,k,m,n,p,T; scanf("%d",&T); for(i=1;i<=T;i++) { scanf("%d.%d.%d.%d",&a,&b,&c,&d); e = binary(a); f = binary(b); g = binary(c); h = binary(d); scanf("%d. %d. %d. %d",&k,&m,&n,&p); if(e==k && f==m && g==n && h==p){ printf("Case %d: Yes\n",i); } else{ printf("Case %d: No\n",i); } } return 0; } int binary(int n) { int rem,i=1,bin=0; while (n!=0) { rem=n%2; n = n/2; bin=bin+rem*i; i*=10; } return bin; }
true
b6916f7ee3b96cdda208b7116d79e4d3597f66e2
C++
Daiver/jff
/cpp/own_g/SpacePhysicalObjects/ship.h
UTF-8
381
2.609375
3
[]
no_license
#ifndef SHIP_H #define SHIP_H #include "spacephysicalobject.h" #include "destroyablespaceobject.h" namespace SpacePhysicalObjects { class Ship : public DestroyableSpaceObject { public: Ship(); float speed() const { return m_speed; } void setSpeed(const float speed) { this->m_speed = speed; } private: float m_speed; }; } #endif // SHIP_H
true
3134e61069c9fe3a8731e94a3023e52052c299b8
C++
yumayo/treelike
/include/treelike/utility/file_system.h
UTF-8
549
2.53125
3
[]
no_license
#pragma once #include <string> #include <vector> #include <algorithm> #include <filesystem> namespace treelike { namespace utility { class file_system { std::string _root_relative_path; std::vector<std::string> _names; public: void search( std::string const& relative_path ); std::vector<std::string>& get_names( ); private: void search_directory( std::tr2::sys::path const& path ); void search_file( std::tr2::sys::path const& path ); void search_path( std::tr2::sys::path const& path ); }; } }
true
8e0c5c5bde95908f3508cd43ec8351e3ff060a85
C++
R0B0T023/CPP
/insercion.cpp
UTF-8
583
3.3125
3
[]
no_license
#include<stdio.h> #include<iostream> using namespace std; int main() { int numeros[]={3,5,4,2,1,6}; int i,pos,aux; for(i=0;i<6;i++) { pos=i; aux=numeros[i]; while((pos>0) && (numeros[pos-1] > aux)) { numeros[pos]=numeros[pos-1]; pos--; } numeros[pos]=aux; } cout<<"orden ascendente: \n"; for(i=0;i<6;i++) { cout<<numeros[i]<<" "; } cout<<"\norden descendente: \n"; for(i=5;i>=0;i--) { cout<<numeros[i]<<" "; } return 0; }
true
e498d845cb52b8374797aab9051ea045e6db6d5e
C++
right-x2/Algorithm_study
/2470.cpp
UTF-8
935
2.625
3
[]
no_license
#include <vector> #include <iostream> #include <queue> #include <stack> #include <algorithm> using namespace std; vector<int> v; int a1,a2; int cur; int ans; int main(int argc, char** argv) { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int flag = 0; int n; int a; int s,e; cin>>n; for (int i = 0; i < n; ++i) { cin>>a; v.push_back(a); } sort(v.begin(),v.end()); s = 0; e = n-1; ans = v[0] + v[n-1]; if(ans<0) ans = -ans; a1 = v[0]; a2 = v[n-1]; while(s<e) { int box = v[s]+v[e]; if(box<0) { flag = 1; box = -box; } else flag = 0; if(box<ans) { ans = box; a1 = v[s]; a2 = v[e]; } if(flag==0) e--; else s++; } cout<<a1<<" "<<a2<<"\n"; return 0; }
true
2a9090d6c22a023a6aee2ec2010b632f14d78fc0
C++
szyszprzemek/Cpp_training
/kurs_cplusplus/exercise_template.cpp
UTF-8
389
3.75
4
[]
no_license
#include <iostream> int const size_d = 3; using namespace std; template <class T> T sum(T *input, int size_d, T sum=0){ for(int i=0; i<size_d; i++) sum += input[i]; return sum; } int main(){ cout << " Template for sum() "<< endl; int a[] = {1, 2, 3}; double b[] = {2.1, 2.2, 2.3}; cout << sum(a,3) << endl; cout << sum(b,3) << endl; return 0; }
true
2d446efb4faf7d3b5548ed0b35ad06881642dee7
C++
roman-zm/nsh
/main.cpp
UTF-8
4,418
2.5625
3
[]
no_license
#define STD_INPUT 0 #define STD_OUTPUT 1 #include <iostream> #include <sstream> #include <string> #include <cstring> #include <unistd.h> #include <fcntl.h> #include <vector> #include <sys/wait.h> #include <cstdio> #include <cstdlib> using namespace std; void printPromt() { char* USER; char* PWD; USER=getenv("USER"); PWD=get_current_dir_name(); printf("%s@%s:$ ", USER, PWD); setenv("PWD", PWD, 1); setenv("USER", USER, 1); } vector<char*> parseCommand(char* input) { vector<char*> params; char* buff = strtok(input," "); params.push_back(buff); while(buff){ buff = strtok(NULL, " "); params.push_back(buff); } return params; } void execCommand(vector<char*> params, vector<string> commands, char* envp[]) { if(!(strncmp("cd", params[0], strlen(params[0])))){ if(params.size() != 2){ if(params[1][0]=='/'){ chdir(params[1]); }else{ char currPath[4096]; strcpy(currPath, get_current_dir_name()); strcat(currPath, "/"); strcat(currPath, params[1]); chdir(currPath); } } } else if(!(strncmp("setenv", params[0], strlen(params[0])))){ char* envName = strtok(params[1], "="); char* envValue = strtok(NULL, "="); setenv(envName, envValue, 1); } else if(!(strncmp("getenv", params[0], strlen(params[0])))) { printf("%s\n", getenv(params[1])); } else if(!(strncmp("exit", params[0], strlen(params[0])))){ exit(0); } else { int status, execStatus=-1; size_t pathNumber=0; pid_t pid; switch(pid=fork()){ case -1: printf("Error -1\n"); break; case 0: printf("%i", execStatus); do{ execStatus = execve(commands[pathNumber].c_str() , &params[0], envp); pathNumber++; }while(execStatus==-1 && pathNumber<commands.size()); break; default: waitpid(-1, &status, 0); break; } } } vector<string> getCommand(vector<char*> params){ char* CPATH=getenv("PATH"); string PATH(CPATH); istringstream iss(PATH); vector<string> commands; string buffer; while(getline(iss, buffer, ':')){ buffer+="/"; buffer+=params[0]; commands.push_back(buffer); } return commands; } bool includes(vector<char*> params, char* delim){ for(size_t i=0; i<params.size(); i++){ if(params[i] ==NULL) return false; if(!strncmp(params[i], delim, sizeof(params[i]))) return true; } return false; } void execPipe(vector<char*> params) { int execStatus =-1; size_t pathNumber=0; vector<char*> params1; vector<char*> params2; for(int i=0; params[i][0] != '|'; i++){ if(params[i][0]!='|')params1.push_back(params[i]); } params1.push_back(NULL); for(size_t i=params1.size(); i<params.size(); i++){ params2.push_back(params[i]); } vector<string> commands1 = getCommand(params1); vector<string> commands2 = getCommand(params2); int fd[2]; pipe((&fd[0])); if(fork()){ execStatus=-1; pathNumber=0; close(fd[0]); close(STD_OUTPUT); dup(fd[1]); close(fd[1]); do{ execStatus = execve(commands1[pathNumber].c_str() , &params1[0], 0); pathNumber++; }while(execStatus==-1 && pathNumber<commands1.size()); } else { execStatus=-1; pathNumber=0; close(fd[1]); close(STD_INPUT); dup(fd[0]); close(fd[0]); do{ execStatus = execve(commands2[pathNumber].c_str() , &params2[0], 0); pathNumber++; }while(execStatus==-1 && pathNumber<commands2.size()); } } int main(int argc, char *argv[], char *envp[]) { cout<<"Welcome to nsh!"<<endl; while(true) { vector<char*> params; printPromt(); string input; getline(cin, input); char* inputString = (char*)input.c_str(); params = parseCommand(inputString); vector<string> commands = getCommand(params); if(params[0]!=NULL){ if(includes(params, "|")) execPipe(params); else execCommand(params, commands, envp); } } }
true
b498001145f21b948ac7a0804eb295e7a96846ff
C++
atkinsja/Traveling_Salesman
/GeneticMath/tour_manager.cpp
UTF-8
283
2.921875
3
[]
no_license
#include <vector> #include "tour_manager.h" void Tour_manager::add_city(City *city) { destination_cities->push_back(city); } City* Tour_manager::get_city(int index) { return destination_cities->at(index); } int Tour_manager::num_cities() { return destination_cities->size(); }
true
d906d2dd0216c039db09db800f5bf0f64695b671
C++
pharick/cpp
/1-year/31-pred-test/2.cpp
UTF-8
224
3.328125
3
[]
no_license
#include <iostream> using namespace std; int max(int x, int y) { if (x > y) return x; return y; } int main() { int a, b; cin >> a >> b; int z = max(a, 2*b) * max(2*a - b, b); cout << z << endl; return 0; }
true
1c9bf45e245d6e48d03b8b8513deddd6c85e9bc8
C++
walkccc/LeetCode
/solutions/0356. Line Reflection/0356.cpp
UTF-8
772
2.96875
3
[ "MIT" ]
permissive
class Solution { public: bool isReflected(vector<vector<int>>& points) { int minX = INT_MAX; int maxX = INT_MIN; unordered_set<pair<int, int>, pairHash> seen; for (const vector<int>& p : points) { const int x = p[0]; const int y = p[1]; minX = min(minX, x); maxX = max(maxX, x); seen.insert({x, y}); } const int sum = minX + maxX; // (leftX + rightX) / 2 = (minX + maxX) / 2 // leftX = minX + maxX - rightX // RightX = minX + maxX - leftX for (const vector<int>& p : points) if (!seen.count({sum - p[0], p[1]})) return false; return true; } private: struct pairHash { size_t operator()(const pair<int, int>& p) const { return p.first ^ p.second; } }; };
true
74a77ef240c8287a5297ad5afc5585f699274ee2
C++
MichalDolata/netquiz
/server/main.cpp
UTF-8
4,242
2.59375
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/epoll.h> #include <map> #include <netinet/in.h> #include <fcntl.h> #include "message.pb.h" #include "client.h" #include "question.h" using namespace std; void set_nonblock(int socket) { int flags; flags = fcntl(socket,F_GETFL,0); if(flags == -1) return; int res = fcntl(socket, F_SETFL, O_NONBLOCK, 1); cout << "set nonblock" << res << "\n"; } void bind_address(int listen_socket, int port) { sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr.s_addr = INADDR_ANY; if(bind(listen_socket, (sockaddr *)&server_addr, sizeof(server_addr)) == -1) { cerr << "Couldn't bind the address" << endl; exit(-1); } } void close_client_socket(int client_socket, int epoll_fd) { if(Client::client_list.find(client_socket) != Client::client_list.end()){ Client* client = Client::client_list.at(client_socket); Client::client_list.erase(client_socket); delete client; } epoll_event event_to_delete; event_to_delete.events = EPOLLIN; event_to_delete.data.fd = client_socket; epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client_socket, &event_to_delete); epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client_socket, &event_to_delete); shutdown(client_socket, SHUT_RDWR); close(client_socket); } void epoll_loop(int epoll_fd, int listen_socket) { epoll_event listen_event; listen_event.events = EPOLLIN; listen_event.data.fd = listen_socket; epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_socket, &listen_event); epoll_event current_event; while(true) { epoll_wait(epoll_fd, &current_event, 1, -1); if (current_event.events & EPOLLIN && current_event.data.fd == listen_socket) { int client_socket = accept(listen_socket, NULL, NULL); if(client_socket == -1) { continue; } listen_event.events = EPOLLIN; listen_event.data.fd = client_socket; epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_socket, &listen_event); set_nonblock(client_socket); Client::client_list.insert(pair<int, Client*>(client_socket, new Client(client_socket, epoll_fd))); } else if (current_event.events & EPOLLIN) { int client_socket = current_event.data.fd; if(Client::client_list.find(client_socket) == Client::client_list.end())continue; if(Client::client_list.at(client_socket)->read_from_socket() == -1) { close_client_socket(client_socket, epoll_fd); } } else if (current_event.events & EPOLLERR || current_event.events & EPOLLHUP) { int client_socket = current_event.data.fd; close_client_socket(client_socket, epoll_fd); } if (current_event.events & EPOLLOUT){ int client_socket = current_event.data.fd; if(Client::client_list.find(client_socket) == Client::client_list.end())continue; auto client = Client::client_list.at(client_socket); int res = client->send_message(); if(res == -1){ close_client_socket(client_socket, epoll_fd); }else if(res == 1){ epoll_event event_to_mod; event_to_mod.events = EPOLLIN; event_to_mod.data.fd = client_socket; epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client_socket, &event_to_mod); } } } } int load_port_from_config() { ifstream file{"settings.cfg"}; int port; string line; while(getline(file, line)) { stringstream ss{line}; string setting; getline(ss, setting, '='); if(setting == "PORT") { ss >> port; return port; } } return -1; } int main() { GOOGLE_PROTOBUF_VERIFY_VERSION; int port = load_port_from_config(); if(port == -1) { cerr << "Couldn't get port from config" << endl; exit(-1); } int listen_socket = socket(AF_INET, SOCK_STREAM, 0); int flag = 1; setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(int)); bind_address(listen_socket, port); listen(listen_socket, 1); int epoll_fd = epoll_create1(0); Question::current_question.run(epoll_fd); epoll_loop(epoll_fd, listen_socket); return 0; }
true
68cc3927206ace09b8211bcc9f2af5d1d7d52087
C++
msklyarov/Cocos2dx-Tetris
/proj.win32/TetrisGlass.cpp
UTF-8
3,335
2.90625
3
[]
no_license
#include "TetrisGlass.h" #include "Settings.h" #include "TetrisLayer.h" #include "Log.h" #include "cocos2d.h" CTetrisGlass* CTetrisGlass::_pSingletonInstance = NULL; CTetrisGlass::CTetrisGlass(void) { } CTetrisGlass::~CTetrisGlass(void) { clearGlass(); /*vector<GlassRow*>::iterator it; for (it = _glass.begin(); it != _glass.end(); it++) { (*it)->clear(); // elements of the vector are dropped: their destructors are called }*/ _glass.clear(); } CTetrisGlass* CTetrisGlass::getInstance() { if (_pSingletonInstance == NULL) { _pSingletonInstance = new CTetrisGlass(); } return _pSingletonInstance; } void CTetrisGlass::deleteInstance() { if (_pSingletonInstance != NULL) { delete _pSingletonInstance; _pSingletonInstance = NULL; } } void CTetrisGlass::addRow() { _glass.push_back(new GlassRow(CSettings::GlassBlocksWidth)); } bool CTetrisGlass::isValidEmptyCell(const int x, const int y) { if ( x < 0 || x > CSettings::GlassBlocksWidth - 1 || y < 0 || y > CSettings::GlassBlocksHeight + CSettings::FigureBlocksCount - 1 ) { return false; } if (y >= (int) _glass.size()) { return true; } return (_glass[y]->at(x) == NULL); } void CTetrisGlass::addFigure(CTetrisFigureBase* pFigure) { TetrisLayer* pTetrisLayer = (TetrisLayer*) pFigure->getParent(); for (int i = 0; i < CSettings::FigureBlocksCount; i++) { int blockPosX = pFigure->getBlockGlassPointX(i); int blockPosY = pFigure->getBlockGlassPointY(i); assert( blockPosX >= 0 && blockPosX < CSettings::GlassBlocksWidth && blockPosY >= 0 && blockPosY < CSettings::GlassBlocksHeight ); // move from TetrisFigure CScene to CLayer CCSprite* pSprite = (CCSprite*) pFigure->getChildren()->objectAtIndex(i); pSprite->setParent(NULL); pSprite->setPosition( ccp(pFigure->getBlockPointX(i), pFigure->getBlockPointY(i)) ); pTetrisLayer->addChild( pSprite ); // add to _glass array while (blockPosY >= (int) _glass.size()) { addRow(); } _glass[blockPosY]->at(blockPosX) = pSprite; } // Remove TetrisFigure CScene, but not CSprite's. pTetrisLayer->removeChild(pFigure, false); CLog::printGlass(this); } int CTetrisGlass::getRowsCount() const { return _glass.size(); } bool CTetrisGlass::isRowFull(const int iRowNum) { assert( iRowNum >= 0 && iRowNum < (int) _glass.size() ); GlassRow::iterator it; for (it = _glass[iRowNum]->begin(); it != _glass[iRowNum]->end(); it++) { if (*it == NULL) { return false; } } return true; } void CTetrisGlass::removeRow(const int iRowNum) { assert( iRowNum >= 0 && iRowNum < _glass.size() ); vector<CCSprite*>::iterator it; for (it = _glass[iRowNum]->begin(); it != _glass[iRowNum]->end(); it++) { if ( (*it) != NULL ) { // remove block from screen glass (*it)->getParent()->removeChild((*it), true); } } _glass[iRowNum]->clear(); // call destructor again ? :-) _glass.erase(_glass.begin() + iRowNum); // set Y-- for all upper blocks for (int i = iRowNum; i < _glass.size(); i++) { for (it = _glass[i]->begin(); it != _glass[i]->end(); it++) { if ( (*it) != NULL ) { // remove block from screen glass (*it)->setPositionY( (*it)->getPositionY() - CSettings::GlassCellSize ); } } } } void CTetrisGlass::clearGlass() { for (int i = _glass.size() - 1; i >= 0 ; i--) { removeRow(i); } }
true
02e9ebdc3df4d402a4a9a68d9cac493574a54fb5
C++
nickclark2016/containers
/projects/containers/include/slot_map.hpp
UTF-8
28,240
3.109375
3
[]
no_license
#ifndef slot_map_hpp__ #define slot_map_hpp__ /// \file slot_map.hpp /// <summary> /// File containing implementation of the slot map data structure and helper functionality. /// /// \author Nicholaus Clark /// \copyright Copyright 2021 Nicholaus Clark /// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated /// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the /// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to /// permit persons to whom the Software is furnished to do so, subject to the following conditions: <br /> /// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the /// Software. <br /> /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE /// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS /// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR /// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /// </summary> #include "stdint.hpp" #include "utility.hpp" namespace containers { /// <summary> /// Data structure that has a guaranteed constant time insertion, erasure, and retrieval. Insertion is performed /// in constant time if and only if the backing buffer is large enough. The values in the data structure are /// unordered. Values stored are guaranteed to be sequential in memory. /// /// The slot map data structure is a variable sized structure. The memory footprint of the structure consists /// of three buffers, a value buffer, a buffer storing all keys, and a buffer storing pointers from values to keys. /// Through these buffers, the slot map provides constant time lookup of a value provided a key and constant time /// erasure of a value given a key, however, there are multiple levels of indirection to achieve this. For a small /// number of elements, the lack of indirection in a vector makes it a cheaper alternative to the slot map. As the /// number of elements grows, the cost of erasure and search provided a key becomes cheaper than erasing a value /// from a vector and searching a vector for a value. With the current implementation of the data structure, it /// is not possible to sort the values. /// </summary> /// <typeparam name="Value"> /// Type of value stored in the slot map. /// </typeparam> /// <typeparam name="Index"> /// Type of value to be used as an index into the map. /// </typeparam> /// <typeparam name="Generation"> /// Type of value to be used as a generation counter for the map. /// </typeparam> template <typename Value, typename Index = u32, typename Generation = u32> class slot_map { public: /// <summary> /// Type alias for map indices. /// </summary> using index_type = Index; /// <summary> /// Type alias for generation counter in the map. /// </summary> using generation_type = Generation; /// <summary> /// Type alias for the value type stored in the map. /// </summary> using value_type = Value; /// <summary> /// Type alias of the value iterator for the map. /// </summary> using iterator = Value*; /// <summary> /// Type alias of the const value iterator for the map. /// </summary> using const_iterator = const Value*; /// <summary> /// Type alias of the reference of the value type stored in the map. /// </summary> using reference = Value&; /// <summary> /// Type alias of the const reference of the value type stored in the map. /// </summary> using const_reference = const Value&; /// <summary> /// Type alias of the pointer of the value type stored in the map. /// </summary> using pointer = Value*; /// <summary> /// Type alias of the const pointer of the value type stored in the map. /// </summary> using const_pointer = const Value*; /// <summary> /// Structure defining a key providing constant look up and erasure from the map. /// </summary> struct key { /// <summary> /// Index of the key in the map. /// </summary> index_type index; /// <summary> /// Generation of the key stored at the index in the map. /// </summary> generation_type generation; }; /// <summary> /// Constructs a new, empty map. The size and capacity of the map is guaranteed to be zero. /// </summary> slot_map(); /// <summary> /// Constructs a copy of the empty map. Keys fetched from <paramref name="other" /> are legal to use in this /// slot map and will point to an equivalent value. /// </summary> /// <param name="other"> /// Slot map to copy from. /// </param> slot_map(const slot_map& other); /// <summary> /// Moves the contents of <paramref name="other" /> into this slot map, removing all values from /// <paramref name="other" />. Keys fetched from <paramref name="other" /> are legal to use in this slot map /// and will point to an equivalent value. /// </summary> slot_map(slot_map&& other) noexcept; /// <summary> /// Deallocates all heap memory associated with the slot map and resets the size and capacity of the buffer. /// </summary> ~slot_map(); /// <summary> /// Copies the values of <paramref name="rhs" /> into this. If this map is not empty, all values stored in /// this map are released. Keys fetched from <paramref name="rhs" /> are legal to use in this slot map and /// will point to an equivalent value. /// </summary> /// <param name="rhs"> /// Slot map to copy contents from. /// </param> /// <returns> /// Reference to <c>this</c>. /// </returns> slot_map& operator=(const slot_map& rhs); /// <summary> /// Moves the values of <paramref name="rhs" /> into this. If this map is not empty, all values stored in /// this map are released. Keys fetched from <paramref name="rhs" /> are legal to use in this slot map and /// will point to an equivalent value. /// </summary> /// <param name="rhs"> /// Slot map to move contents from. /// </param> /// <returns> /// Reference to <c>this</c>. /// </returns> slot_map& operator=(slot_map&& rhs); /// <summary> /// Gets if the slot map contains no values. Equivalent to <c>size() == 0</c>. /// </summary> /// <returns> /// Is the map empty /// </returns> bool empty() const noexcept; /// <summary> /// Gets the number of values in the map. /// </summary> /// <returns> /// Number of values in the map. /// </returns> size_t size() const noexcept; /// <summary> /// Gets the number of values that the map can store without resizing its internal buffers. /// </summary> /// <returns> /// Number of values the map can store without resizing. /// </returns> size_t capacity() const noexcept; /// <summary> /// Gets the maximum number of values that can be stored in the map. /// </summary> /// <returns> /// Maximum number of values that can be stored in the map. /// </returns> size_t max_capacity() const noexcept; /// <summary> /// Ensures that the map can hold at least <paramref name="requested" /> values without requiring the backing /// buffers to resize. If <paramref name="requested" /> is less than the capacity of the map, no action is /// performed. /// </summary> /// <param name="requested"> /// Minimum capacity to reserve in the map. /// </param> void reserve(size_t requested); /// <summary> /// Gets an iterator to the first value in the slot map. This is not guaranteed to be the first value /// inserted into the map. /// </summary> /// <returns> /// Iterator to the first value in the slot map. /// </returns> iterator begin() noexcept; //! @copydoc slot_map<Value,Index,Generation>::begin() const_iterator begin() const noexcept; /// <summary> /// Gets an iterator to the end of the slot map. Dereferencing this iterator is undefined behavior. /// </summary> /// <returns> /// Iterator to the end of the slot map. /// </returns> iterator end() noexcept; //! @copydoc slot_map<Value,Index,Generation>::end() const_iterator end() const noexcept; //! @copydoc slot_map<Value,Index,Generation>::begin() const_iterator cbegin() const noexcept; //! @copydoc slot_map<Value,Index,Generation>::end() const_iterator cend() const noexcept; /// <summary> /// Gets a reference to the first value in the slot map. This is not guaranteed to be the first value /// inserted into the map. Results in undefined behavior if the map is empty. /// </summary> /// <returns> /// Reference to the first value. /// </returns> reference front(); //! @copydoc slot_map<Value,Index,Generation>::front() const_reference front() const; /// <summary> /// Gets a reference to the last value in the slot map. This is not guaranteed to be the last value /// inserted into the map. Results in undefined behavior if the map is empty. /// </summary> /// <returns> /// Reference to the last value. /// </returns> /// \pre Map is not empty. reference back(); //! @copydoc slot_map<Value,Index,Generation>::back() const_reference back() const; /// <summary> /// Gets a pointer to the buffer storing the values. /// </summary> /// <returns> /// Pointer to value buffer. /// </returns> pointer data() noexcept; //! @copydoc slot_map<Value,Index,Generation>::data() const_pointer data() const noexcept; /// <summary> /// Removes all values from the map. All keys created from this map are now invalid for this instance of the /// map. /// </summary> /// \post Map size is zero. void clear(); /// <summary> /// Inserts a value into map, returning a key for constant time lookup. /// </summary> /// <param name="value"> /// Value to insert into the map. /// </param> /// <returns> /// Key that references the inserted value in the map. /// </returns> /// \post Map contains <paramref name="value" /> /// \post Size of the map is increased by one. key insert(const value_type& value); //! @copydoc slot_map<Value,Index,Generation>::insert() key insert(value_type&& value); /// <summary> /// Removes a value from the map given its key. /// </summary> /// <param name="k"> /// Key of the value to remove from the map. /// </param> /// <returns> /// <c>true</c> if the value of the key is removed, else <c>false</c>. /// </returns> /// \post Map does not contain the value referenced by <paramref name="k" /> /// \post If the value was removed, the size of the map is decreased by one. bool erase(const key& k); /// <summary> /// Gets a reference to the value referenced by the key in the map. /// </summary> /// <param name="k"> /// Key to fetch the value of. /// </param> /// <returns> /// Value referenced by the key. /// </returns> /// \pre The map contains <paramref name="k" />. reference get(const key& k) noexcept; /// <summary> /// Gets a pointer to the value referenced by the key in the map. /// </summary> /// <param name="k"> /// Key to fetch the value of. /// </param> /// <returns> /// Pointer to the value in the map if the value exists, else <c>nullptr</c>. /// </returns> pointer try_get(const key& k) noexcept; private: key* m_slots; pointer m_data; size_t m_capacity; size_t m_size; Index m_free_slot_head; size_t* m_erase; key* allocate_slots(size_t count); void deallocate_slots(key* slots); pointer allocate_data_region(size_t count); void deallocate_data_region(pointer values); void destruct_data_region(pointer values); key create_new_key(); key pop_free_key(); void release(); template <typename T> void copy(T* source, T* destination, size_t count); template <typename T> void move(T* source, T* destination, size_t count); static constexpr size_t implicit_list_stop = ~Index(0); }; // class slot_map template <typename Value, typename Index, typename Generation> inline slot_map<Value, Index, Generation>::slot_map() : m_slots(nullptr), m_data(nullptr), m_capacity(0), m_size(0), m_free_slot_head(implicit_list_stop), m_erase(nullptr) { } template <typename Value, typename Index, typename Generation> inline slot_map<Value, Index, Generation>::slot_map(const slot_map& other) : slot_map() { m_slots = allocate_slots(other.m_capacity); m_data = allocate_data(other.m_capacity); m_size = other.m_size; m_capacity = other.m_capacity; m_free_slot_head = other.m_free_slot_head; m_erase = new size_t[m_capacity]; copy(other.m_slots, m_slots, m_capacity); copy(other.m_data, m_data, m_size); copy(other.m_erase, m_erase, m_capacity); } template <typename Value, typename Index, typename Generation> inline slot_map<Value, Index, Generation>::slot_map(slot_map&& other) noexcept : slot_map() { m_slots = other.m_slots; m_data = other.m_data; m_size = other.m_size; m_capacity = other.m_capacity; m_free_slot_head = other.m_free_slot_head; m_erase = other.m_erase; other.m_slots = nullptr; other.m_data = nullptr; other.m_erase = nullptr; } template <typename Value, typename Index, typename Generation> inline slot_map<Value, Index, Generation>::~slot_map() { release(); } template <typename Value, typename Index, typename Generation> inline slot_map<Value, Index, Generation>& slot_map<Value, Index, Generation>::operator=(const slot_map& rhs) { release(); m_slots = allocate_slots(rhs.m_capacity); m_data = allocate_data(rhs.m_capacity); m_size = rhs.m_size; m_capacity = rhs.m_capacity; m_free_slot_head = rhs.m_free_slot_head; m_erase = new size_t[m_capacity]; copy(rhs.m_slots, m_slots, m_capacity); copy(rhs.m_data, m_data, m_size); copy(rhs.m_erase, m_erase, m_capacity); return *this; } template <typename Value, typename Index, typename Generation> inline slot_map<Value, Index, Generation>& slot_map<Value, Index, Generation>::operator=(slot_map&& rhs) { release(); m_slots = rhs.m_slots; m_data = rhs.m_data; m_size = rhs.m_size; m_capacity = rhs.m_capacity; m_free_slot_head = rhs.m_free_slot_head; m_erase = rhs.m_erase; rhs.m_slots = nullptr; rhs.m_data = nullptr; rhs.m_erase = nullptr; return *this; } template <typename Value, typename Index, typename Generation> inline bool slot_map<Value, Index, Generation>::empty() const noexcept { return m_size == 0; } template <typename Value, typename Index, typename Generation> inline size_t slot_map<Value, Index, Generation>::size() const noexcept { return m_size; } template <typename Value, typename Index, typename Generation> inline size_t slot_map<Value, Index, Generation>::capacity() const noexcept { return m_capacity; } template <typename Value, typename Index, typename Generation> inline size_t slot_map<Value, Index, Generation>::max_capacity() const noexcept { return ~size_t(0); } template <typename Value, typename Index, typename Generation> inline void slot_map<Value, Index, Generation>::reserve(size_t sz) { // short circuit if trying to reserve smaller than currently allocated memory if (sz < m_capacity) { return; } key* new_slots = allocate_slots(sz); pointer new_payload_region = allocate_data_region(sz); size_t* new_erase = new size_t[sz]; for (size_t i = m_capacity; i < sz; ++i) { new_slots[i].index = static_cast<Index>(i) + 1; new_slots[i].generation = 0; } if (m_capacity > 0) { copy(m_slots, new_slots, m_capacity); move(m_data, new_payload_region, m_size); copy(m_erase, new_erase, m_capacity); destruct_data_region(m_data); deallocate_data_region(m_data); deallocate_slots(m_slots); delete[] m_erase; } m_data = new_payload_region; m_slots = new_slots; m_erase = new_erase; // link the back of the new slot region to the front of the current linked free list m_slots[sz - 1].index = m_free_slot_head; m_free_slot_head = static_cast<Index>(m_capacity); m_capacity = sz; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::iterator slot_map<Value, Index, Generation>::begin() noexcept { return m_data; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::const_iterator slot_map<Value, Index, Generation>::begin() const noexcept { return m_data; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::iterator slot_map<Value, Index, Generation>::end() noexcept { return m_data + m_size; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::const_iterator slot_map<Value, Index, Generation>::end() const noexcept { return m_data + m_size; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::const_iterator slot_map<Value, Index, Generation>::cbegin() const noexcept { return m_data; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::const_iterator slot_map<Value, Index, Generation>::cend() const noexcept { return m_data + m_size; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::reference slot_map<Value, Index, Generation>::front() { return *begin(); } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::const_reference slot_map<Value, Index, Generation>::front() const { return *cbegin(); } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::reference slot_map<Value, Index, Generation>::back() { return *(end() - 1); } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::const_reference slot_map<Value, Index, Generation>::back() const { return *(end() - 1); } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::pointer slot_map<Value, Index, Generation>::data() noexcept { return m_data; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::const_pointer slot_map<Value, Index, Generation>::data() const noexcept { return m_data; } template <typename Value, typename Index, typename Generation> inline void slot_map<Value, Index, Generation>::clear() { destruct_data_region(m_data); for (size_t i = 0; i < capacity(); ++i) { const Generation current_generation = m_slots[i].generation; m_slots[i].generation += 1; } } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::key slot_map<Value, Index, Generation>::insert( const slot_map<Value, Index, Generation>::value_type& value) { key k = m_free_slot_head == implicit_list_stop ? create_new_key() : pop_free_key(); m_slots[k.index].index = static_cast<Index>(size()); const Index idx = m_slots[k.index].index; m_data[idx] = value; m_erase[m_size] = k.index; ++m_size; return k; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::key slot_map<Value, Index, Generation>::insert( slot_map<Value, Index, Generation>::value_type&& value) { key k = m_free_slot_head == implicit_list_stop ? create_new_key() : pop_free_key(); const Index idx = m_slots[k.index].index; m_data[idx] = move(value); m_erase[m_size] = k.index; ++m_size; return k; } template <typename Value, typename Index, typename Generation> inline bool slot_map<Value, Index, Generation>::erase(const key& k) { const Index idx = k.index; const Generation gen = k.generation; if (idx < capacity()) { const key slot_key = m_slots[idx]; if (gen == slot_key.generation) { const Index data_index = slot_key.index; (data() + data_index)->~Value(); m_slots[idx].generation += 1; m_slots[idx].index = m_free_slot_head; m_free_slot_head = idx; m_erase[data_index] = m_erase[m_size - 1]; if (data_index != size() - 1) { *(data() + data_index) = containers::move(*(data() + size() - 1)); (data() + size() - 1)->~Value(); m_slots[m_erase[data_index]].index = data_index; } --m_size; return true; } } return false; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::reference slot_map<Value, Index, Generation>::get( const key& k) noexcept { return *try_get(k); } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::pointer slot_map<Value, Index, Generation>::try_get( const key& k) noexcept { const Index idx = k.index; const Generation gen = k.generation; if (idx < capacity()) { const key slot_key = m_slots[idx]; if (gen == slot_key.generation) { return m_data + slot_key.index; } } return nullptr; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::key* slot_map<Value, Index, Generation>::allocate_slots( size_t count) { static constexpr size_t key_size = sizeof(key); char* buffer = new char[key_size * count]; return reinterpret_cast<key*>(buffer); } template <typename Value, typename Index, typename Generation> inline void slot_map<Value, Index, Generation>::deallocate_slots(key* slots) { char* buffer = reinterpret_cast<char*>(slots); delete[] buffer; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::pointer slot_map<Value, Index, Generation>::allocate_data_region(size_t count) { static constexpr size_t data_size = sizeof(Value); char* buffer = new char[data_size * count]; return reinterpret_cast<pointer>(buffer); } template <typename Value, typename Index, typename Generation> inline void slot_map<Value, Index, Generation>::deallocate_data_region(pointer values) { char* data = reinterpret_cast<char*>(values); delete[] data; } template <typename Value, typename Index, typename Generation> inline void slot_map<Value, Index, Generation>::destruct_data_region(pointer values) { for (size_t i = 0; i < size(); ++i) { (data() + i)->~Value(); } } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::key slot_map<Value, Index, Generation>::create_new_key() { reserve(m_capacity + 1); const key k = pop_free_key(); m_slots[k.index].index = static_cast<Index>(size()); return k; } template <typename Value, typename Index, typename Generation> inline typename slot_map<Value, Index, Generation>::key slot_map<Value, Index, Generation>::pop_free_key() { key k; k.index = m_free_slot_head; k.generation = m_slots[m_free_slot_head].generation; m_free_slot_head = m_slots[m_free_slot_head].index; return k; } template <typename Value, typename Index, typename Generation> inline void slot_map<Value, Index, Generation>::release() { if (m_data != nullptr) { destruct_data_region(m_data); deallocate_data_region(m_data); m_data = nullptr; } if (m_slots != nullptr) { deallocate_slots(m_slots); m_slots = nullptr; } if (m_erase != nullptr) { delete[] m_erase; m_erase = nullptr; } m_size = 0; m_capacity = 0; m_free_slot_head = implicit_list_stop; } template <typename Value, typename Index, typename Generation> template <typename T> inline void slot_map<Value, Index, Generation>::copy(T* source, T* destination, size_t count) { for (size_t i = 0; i < count; ++i) { destination[i] = source[i]; } } template <typename Value, typename Index, typename Generation> template <typename T> inline void slot_map<Value, Index, Generation>::move(T* source, T* destination, size_t count) { for (size_t i = 0; i < count; ++i) { destination[i] = containers::move(source[i]); } } } // namespace containers #endif // slot_map_hpp__
true
0a55a002ec2dde5bedf9b5421f8b27479e48d9f2
C++
blomios/Teeko
/src/Menus/MainMenu.h
UTF-8
1,094
2.859375
3
[]
no_license
#ifndef TEEKO_MAINMENU_H #define TEEKO_MAINMENU_H #include "SpectatorMenu.h" /** * @brief Class for creating and rendering a main menu */ class MainMenu : public Menu { private: // The "Play (2 Players)" button of the main menu sf::RectangleShape play_two_button_; // The "Play against A.I." button sf::RectangleShape play_ai_button_; // The "Spectator mode" button sf::RectangleShape spectator_button_; // The "Exit Game" button sf::RectangleShape exit_button_; public: // Default constructor MainMenu(); // Calls the functions necessary to draw the background, the logo and the buttons, also wait for events (clicks) void Render() override; // Draws the 3 buttons of the main menu void DrawButtons() override; // On mouseover, changes the color of a button void ButtonsColorController(int mouse_x, int mouse_y) override; // Manages every events triggered by a mouse click void ClickController(int mouse_x, int mouse_y) override; // Draws the big "Teeko" logo void DrawTitle(); }; #endif //TEEKO_MAINMENU_H
true
d6f6988be087cb6aeede73bc98d88f971cae529e
C++
kk-katayama/compro
/library/Bellmanford/Bellmanford.cpp
UTF-8
1,137
3.234375
3
[]
no_license
//最短経路問題。全ての辺についてのループを全ての頂点の数だけ回す(最悪のケース)。O(V*E) //負のコストをもつ辺があっても適用可能。 struct edge{//辺の情報 int from,to,cost; }; int V,E;//頂点の数、辺の数 edge e[1001]; int d[1001];//d[v]は始点から頂点vまでの最短距離 bool update; void bellmanford(int s){//始点sからスタート for(int i=0;i<V;i++) d[i]=INF;//初期化 d[s]=0; for(int j=0;j<V;j++){ update=false;//更新したか否かのフラグ for(int i=0;i<E;i++){//全エッジについてループ int f=e[i].from,t=e[i].to,c=e[i].cost; if(d[f]!=INF&&d[t]>d[f]+c){//更新 d[t]=d[f]+c; update=true; } } if(!update) break; } } //負閉路の検出 bool find_negative_loop(){ for(int i=0;i<V;i++) d[i]=0;//初期化 for(int i=0;i<V;i++){ for(int j=0;j<E;j++){//全辺についてループ int f=e[i].from,t=e[i].to,c=e[i].cost; if(d[t]>d[f]+c){ d[t]=d[f]+c; if(i==V-1) return true; //V回目にも更新があるなら負閉路が存在する } } } return false; }
true
cf93f36d10aaf949909e723150e05009b901eb91
C++
pawelbeza/AlgoAnalysis
/Sort/bubble_sort.cpp
UTF-8
534
3.25
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; template <typename IteratorType> void bubbleSort(IteratorType first, IteratorType last){ IteratorType pom1; IteratorType pom2; bool change = 1; for(int i = 0; i < last-first && change; ++i){ change = 0; pom1 = first; pom2 = first+1; while(pom2 != last-i){ if(*pom1 > *pom2){ swap(*pom1, *pom2); change = 1; } ++pom1; ++pom2; } } }
true
3ab36a335947f67c3b8bf50e95ee5a58239936c3
C++
lvzongsheng/PAT
/EN1067.cpp
UTF-8
1,535
3
3
[]
no_license
// // main.cpp // PAT1067 // http://pat.zju.edu.cn/contests/pat-a-practise/1067 // Solutions: // 此题的解题思路不是很难,就是每次交换都尽量实现一个数的正确排序,即0跟0所在的位置的数进行交换。比如说0在7的位置上,则0跟7交换,值得注意的是当0回到0的位置上而整个序列未排序的话,需要使0跟任何不是排序好的数交换,以此类推。 // 此题对时间要求较高,自己用了两个优化思路,1. 用空间换时间,记录每个数所在的位置 2. 在0到0位置时,进行判断记录起点游标,减少比较量。 // Created by 吕 宗胜 on 21/10/13. // Copyright (c) 2013 吕 宗胜. All rights reserved. // #include <stdio.h> #include <stdlib.h> int main(int argc, const char * argv[]) { int n; scanf("%d",&n); int per[100000]; int erp[100000]; for(int i=0;i<n;i++){ scanf("%d",per+i); erp[per[i]] = i; } int count = 0; int index = 0; for(int i=index;i<n;i++){ if(per[i]==i){ continue; } index = i; if(per[0]==0){ int tm = per[i]; per[0] = tm; per[i] = 0; erp[0] = i; erp[tm] = 0; count++; } while(per[0]!=0){ int temp = erp[0]; int tt = erp[temp]; per[tt] = 0; per[temp] = temp; erp[0] = tt; count++; } } printf("%d",count); return 0; }
true
a5d9611322ec7684f82fd73d0d20de6dd8ea6c27
C++
Alaxe/noi2-ranking
/2017/solutions/B/LBS-Burgas/progres.cpp
UTF-8
711
2.546875
3
[]
no_license
#include <cstdio> #define MAXN 1000 int A[MAXN], N, D=1, n=0; void red(int x) { for(int a=x+1; a<=N; a++) { if(A[a] - A[x] == D) { n++; if(a!=N-1) {red(a);} } } } int main() { int maxA=0, minA=MAXN; scanf("%d", &N); for(int i=0; i<N; i++) { scanf("%d", (A+i)); if(A[i]<minA) minA = A[i]; if(A[i]>maxA) maxA = A[i]; } for(int i=0;i<N; i++) { if(A[i]!=maxA) { while((maxA - minA) - D + 1) { red(i); D++;n%=123456789012345; } } D=1; } printf("%d", n); return 0; }
true
0e9c7c17d8b11a587cda6ec50180724437807380
C++
jthemphill/love-letter
/choice.cc
UTF-8
1,878
3.171875
3
[]
no_license
#include <cstdio> #include "choice.h" #include "const.h" Choice::Choice(int turn, int player, Card holding, Card drawn) : turn_(turn), player_(player), holding_(holding), drawn_(drawn), action_(NULL) {} Choice::Choice(int turn, int player, Card holding, Card drawn, const Action* action) : turn_(turn), player_(player), holding_(holding), drawn_(drawn), action_(action) {} void Choice::print() const { printf( "Player %d had [%s, %s], played %s", player_, name_of_card(holding_), name_of_card(drawn_), name_of_card(action_->card_)); int target = NOBODY; switch (action_->card_) { case GUARD: case PRIEST: case BARON: case PRINCE: case KING: { const TargetedAction& targeted_action = *((const TargetedAction*) action_); target = targeted_action.targetPlayer_; if (target == NOBODY) { printf(" but could not find a letter to tamper with.\n"); return; } } break; default: break; } switch (action_->card_) { case GUARD: { const GuardAction& guard_action = *((const GuardAction*) action_); printf(" and claimed player %d has a %s.\n", target, name_of_card(guard_action.cardNamed_)); break; } case PRIEST: printf(" and looked at player %d's hand.\n", target); break; case BARON: printf(" and compared hands with player %d.\n", target); break; case HANDMAID: printf(" and got protection for a turn.\n"); break; case PRINCE: printf(" and forced player %d to discard and draw.\n", target); break; case KING: printf(" and traded hands with player %d.\n", target); break; default: printf(".\n"); break; } }
true
a6698a97bfa2247ff1c3960f5b5f415b1f912ba9
C++
williamchanrico/competitive-programming
/Toki Learning/Quadtree 1 Pengkodean.cpp
UTF-8
1,088
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int R, C, table[150][150], id[130]; void quadtree(int x, int y, int xx, int yy, string kode) { bool satu = false, nol = false; for (int a = x; a < xx; a++) for (int b = y; b < yy; b++) if (table[a][b] == 0) nol = true; else satu = true; if (satu && nol) { int mx = (x + xx) / 2, my = (y + yy) / 2; quadtree(x, y, mx, my, kode + "0"); quadtree(x, my, mx, yy, kode + "1"); quadtree(mx, y, xx, my, kode + "2"); quadtree(mx, my, xx, yy, kode + "3"); } else if (satu) { cout << "1" << kode << "\n"; } } int main() { scanf("%d %d", &R, &C); int tmp = 2; for (int a = 2; a <= 128; a++) { if (a > tmp) tmp *= 2; id[a] = tmp; } memset(table, 0, sizeof(table)); for (int a = 0; a < R; a++) for (int b = 0; b < C; b++) scanf("%d", &table[a][b]); quadtree(0, 0, id[R], id[C], ""); cout << "END\n"; }
true
81c2da29e3eeec59263d86c5e549a8499d5c0e93
C++
NWPlayer123/libmunna
/src/munna/filetypes/munna_yaz0.cpp
UTF-8
3,027
2.53125
3
[]
no_license
#include "munna/filetypes/munna_yaz0.h" namespace munna { yaz0::yaz0(munna::file& input, munna::file& output) { assert(input.read32() == 0x59617A30); //magic == "Yaz0" uncompressed_size = input.read32(); //yaz0+4 = uncompressed size input.seek(0x10); //for (u32 i = 0; i < uncompressed_size; ) { //for (int i = 0; i < 0x20; i++) { while (bytes_written <= uncompressed_size) { if (bits_left == 0) { //get new flag byte bits_left = 8; flags = input.readbyte(); //printf("new byte: %02X\n", flags); } if (flags & (1 << (bits_left - 1))) { //printf("1\n"); memmove((void*)&this->buffer[0], (void*)&this->buffer[1], 0xFFE); //move buffer back one byte this->buffer[0xFFE] = input.readbyte(); //set latest byte in buffer output.write(this->buffer[0xFFE]); //copy one byte to output bytes_written += 1; } else { //printf("0\n"); rle_data = input.read16(); if (rle_data >> 12) read_size = (rle_data >> 12) + 2; else read_size = input.readbyte() + 0x12; distance = (rle_data & 0xFFF) + 1; //printf("rle_data: %04X\n", rle_data); //printf("read_size: %d\n", read_size); //printf("distance: %03X\n", distance); if (read_size <= distance) { for (int j = 0; j < read_size; j++) { output.write(0x00); } /*printf("%016X\n", output.tell()); output.seek(output.tell() - distance); //seek backwards printf("%016X\n", output.tell()); input.read(&this->buffer[0xFFF - read_size], read_size); printf("%08X", 0xFFF - read_size); for (int j = 0; j < read_size; j++) { printf("%02X", this->buffer[(0xFFE - read_size) + j]); } printf("\n"); output.seek(0, 2); //memset(this->buffer, 0, 0xFFF); output.write(&this->buffer[0xFFE - read_size], read_size); /*output.write(&this->buffer[0xFFF - distance], read_size); memmove((void*)&this->buffer[0], (void*)&this->buffer[read_size], read_size);*/ } else { for (int j = 0; j < read_size; j++) { output.write(0x00); } /*for (int j = 0; j < read_size; j++) { output.write(0x00); memmove((void*)&this->buffer[0], (void*)&this->buffer[1], 0xFFE); this->buffer[0xFFE] = 0x00; //output.write(this->buffer[0xFFF - distance]); //memmove((void*)&this->buffer[0], (void*)&this->buffer[1], 0xFFE); }*/ } /*if (read_size > distance) { //edge case, byte repeats itself output.write(&this->buffer[0xFFF - distance], distance); memmove((void*)&this->buffer[0], (void*)&this->buffer[distance], distance); for (int i = 0; i < read_size - distance; i++) { output.write(this->buffer[0xFFE]); } } else { output.write(&this->buffer[0xFFF - distance], read_size); memmove((void*)&this->buffer[0], (void*)&this->buffer[read_size], read_size); }*/ /*for (int j = 0; j < read_size; j++) output.write(0x00);*/ bytes_written += read_size; } bits_left--; } printf("bytes_written: %08X\n", bytes_written); } }
true
5154e9c7cecb45e2b4e60fb8189cc647147b52da
C++
SeA-xiAoD/Learning_OpenCV3_Homework
/ch10/10_2/Ex_10_2.cpp
UTF-8
813
2.796875
3
[]
no_license
#include <opencv2/opencv.hpp> #include <iostream> using namespace std; int main( int argc, char** argv ) { cv::Mat img = cv::Mat::zeros(100, 100, CV_8U); img.at<uchar>(49, 49) = 255; img.at<uchar>(49, 50) = 255; img.at<uchar>(50, 49) = 255; img.at<uchar>(50, 50) = 255; cv::Mat smooth5, smooth9; // a cv::GaussianBlur(img, smooth5, cv::Size(5, 5), 0); cv::imshow("Smooth 5x5", smooth5); cv::waitKey(0); cv::destroyAllWindows(); // b cv::GaussianBlur(img, smooth9, cv::Size(9, 9), 0); cv::imshow("Smooth 9x9", smooth9); cv::waitKey(0); cv::destroyAllWindows(); // c cv::GaussianBlur(smooth5, smooth5, cv::Size(5, 5), 0); cv::imshow("Smooth 5x5", smooth5); cv::imshow("Smooth 9x9", smooth9); cv::waitKey(0); return 0; }
true
82ab8c94f66e2d4e524af3b691f6102a532463da
C++
3048205169/ECE551
/miniproject/CalculCov.cpp
UTF-8
783
2.703125
3
[]
no_license
#include <Eigen> #include "calculate.h" #include "read.h" void printMatrix(const Eigen::MatrixXd & corr) { for (int i = 0; i < corr.rows(); i++) { for (int j = 0; j < corr.cols(); j++) std::cout << corr(i, j) << "% "; std::cout << std::endl; } } void printAssets(Assets & assets) { for (unsigned long i = 0; i < assets.size(); i++) std::cout << assets[i]; } Eigen::MatrixXd CalCov(const Eigen::MatrixXd & corr, const Assets & assets) { unsigned long size = corr.rows(); Eigen::MatrixXd cov = Eigen::MatrixXd::Zero(size, size); for (unsigned long i = 0; i < size; i++) { for (unsigned long j = 0; j < size; j++) { cov(i, j) = (double)corr(i, j) / 100 * assets[i].getStDev() / 100 * assets[j].getStDev(); } } return cov; }
true
abf69c844fdaab40f3d24191c5d8791df689c5ab
C++
y3046308/addNewLines
/addNewLines/Source.cpp
UTF-8
8,587
3.125
3
[]
no_license
// reads text file (Korean & English), which doesn't have any line breaks and create new lines after every 4th periods. // directory of the file is set to "D:\\bcs\\old\\"; // user can continuously work with another text file after one another. // to finish, type "zz" // update: added folder directory function so user can pick a text file(or multiple text files) // from any folder and rename them as pleased // Setting: Project -> Property -> Use of Mfc -> Use MFC in a Shared DLL #include <stdio.h> #include <fstream> #include <tchar.h> #include <iostream> #include <locale> #include <vector> #include <afxdlgs.h> // for CFileDialog #include <conio.h> // for getch using namespace std; // # of periods we want in single paragraph #define REPETITION 4 void run(string in, string out) { // open a file ifstream myfile(in); string line; int index = 0; if (myfile.is_open()) { // create an output file ofstream newFile(out); while (std::getline(myfile, line)) { int tmp_index = index; string newline = ""; if (line != "") { //char prevVal = '\0'; int prevInd = -100; for (int i = 0; i < line.length(); i++) { string tmp = ""; char curr = line.at(i); if ((curr & 0x80) != 0x80) { // if ascii tmp += curr; // first add it to newfile // if we see period and it's not followed by another period if (curr == '.') { if (prevInd + 1 != i) { // dont want period in front of current period if (i + 1 < line.length() && line.at(i + 1) != '.') { if (tmp_index == REPETITION) { // if this is 5th period, add newlines tmp += "\n\n"; tmp_index = 0; } else { tmp_index++; // increment index } } } // keep track of previous periods so there is no space b/w consecutive periods prevInd = i; } } // If korean else if ((curr & 0x80) == 0x80) { tmp = line.substr(i, 2); i++; } //std::cout << i << ": " << tmp << endl; newline += tmp; } index = tmp_index; newFile << newline; } else { tmp_index = 0; newFile << endl << endl; } } myfile.close(); newFile.close(); } else { std::cout << "Failed to read " << in << endl; } } // each file path ends with double nulls // if multiple files are selected, they are separated by nulls // if single file is selected, there is no separator bool multi_file_selected(char* in) { char prev = '1'; bool hasSeparator = false; while (1) { char curr = *in; if (prev == '\0' && curr == '\0') break; if (prev == '\0' && curr != '\0') hasSeparator = true; prev = curr; in++; } std::cout << endl; return hasSeparator; } // extract filenames from input vector<string> extract_fileNames(char* in) { vector<string> out; //std::cout << "START---------------------------------" << endl; if (multi_file_selected(in)) { char prev = '1'; string tmp = ""; while (1) { char curr = *in; if (curr == '\0') { if (prev == '\0') { break; } out.push_back(tmp); tmp = ""; } else { std::cout << tmp << endl; tmp += curr; } prev = curr; in++; } // add \ to end of directory tmp = out[0]; out[0] = tmp + "\\"; } else { // only single file selected string new_str(in); // find the last occurrence of '\' int loc = new_str.rfind("\\"); // separate dir and filename string dir = new_str.substr(0, loc + 1); string fileName = new_str.substr(loc + 1); // index 0 of vector is directory of files out.push_back(dir); out.push_back(fileName); } /* std::cout << "end---------------------------------" << endl << endl; std::cout << "extract_fileNames---------------------------------------" << endl; for (int i = 0; i < out.size(); i++) { std::cout << out.at(i) << endl; } std::cout << "extract_fileNames---------------------------------------" << endl; */ return out; } // create new files vector<string> getNewName(vector<string> in, string prefix) { vector<string> out; out.push_back(in[0]); // add a directory //std::cout << "@@@@@@@@@@@@@@@@@@@@@@@@@" << endl; for (int i = 1; i < in.size(); i++) { string newFileName = prefix + in[i]; //std::cout << in[i] << "->" << newFileName << endl; out.push_back(newFileName); } //std::cout << "@@@@@@@@@@@@@@@@@@@@@@@@@" << endl; return out; } bool operator==(const string& lhs, const string& rhs) { if (lhs.compare(rhs) == 0) return true; return false; } int main() { std::cout << "*************WELCOME*************" << endl; std::cout << "This program reads a text file, which doesnt have line breaks," << endl; std::cout << "and add line breaks" << endl; std::cout << "By default, new text file is named \"new_(txt_name)\"" << endl; std::cout << "but you can also select new prefix" << endl; std::cout << "Press enter to get started" << endl; string c; std::getline(cin, c); // when ctrl-c is pressed, exit the loop while (1) { /* std::cout << "Enter a text filename (without an extension and type \"zz\" to end): "; string read; std::getline(cin, read); // type 'zzz' to finish if (!read.compare("zz")) break; string dir = "D:\\bcs\\old\\"; string fileName(read); string fileExtension = ".txt"; string fileFullName = fileName + fileExtension; string in = dir + fileFullName; string out = dir + "new_" + fileFullName; */ OPENFILENAME ofn; // common dialog box structure char szFile[1500]; // buffer for file name HWND hwnd; // owner window HANDLE hf; // file handle // Initialize OPENFILENAME /* reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646829(v=vs.85).aspx#open_file*/ ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; // the dialog box has no owner ofn.lpstrFile = szFile; // Set lpstrFile[0] to '\0' so that GetOpenFileName does not // use the contents of szFile to initialize itself. ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof(szFile); // no filter set //ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0"; ofn.lpstrFilter = "Text File\0*.txt\0All\0*.*\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; // initial directory set to D:\bcs:\old ofn.lpstrInitialDir = _T("D:\\bcs\\old\\"); // OFN_PATHMUSTEXIST: user can only type valid paths & file names // OFN_FILEMUSTEXIST: The user can type only names of existing files in the File Name entry field. // user is allowed to select multiple files at once ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER | OFN_ALLOWMULTISELECT; // Display the Open dialog box. if (GetOpenFileName(&ofn) == TRUE) { //hf = CreateFile(ofn.lpstrFile, GENERIC_READ, 0, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); string prefix; while (1) { std::cout << "1. use default prefix(new_)" << endl; std::cout << "2. use desired prefix" << endl; std::cout << "3. overwrite original files" << endl; std::cout << "Choose your option to save your file(s):"; // getch reads a character without using any buffer. // so no needs to press enter int choice = _getch(); std::cout << endl << endl; if (choice == '1') { prefix = "new_"; break; } else if (choice == '2') { std::cout << "Enter your prefix with an underscore:"; std::getline(cin, prefix); std::cout << endl << endl; break; } else if (choice == '3') { prefix = ""; break; } else { std::cout << "No such option" << endl << endl; } } char* lst = ofn.lpstrFile; vector<string> inputList = extract_fileNames(lst); vector<string> outputList = getNewName(inputList, prefix); for (int i = 1; i < inputList.size(); i++) { string in = inputList[0] + inputList[i]; string out = outputList[0] + outputList[i]; run(in, out); } } else { // exit the loop if no file is selected break; } std::cout << ">>>>>>>>>>>>>>>>>>>>Successfully Done<<<<<<<<<<<<<<<<<<<<" << endl; } std::cout << "************************************************" << endl; std::cout << "************************************************" << endl; std::cout << "********************FINISHED********************" << endl; std::cout << "************************************************" << endl; std::cout << "************************************************" << endl; c; std::getline(cin, c); }
true
14a94fdd374c043e97e9111b840eaaac028a75c8
C++
abnayak/brainz
/InterviewBit/Array/plus1.cpp
UTF-8
608
3.5
4
[]
no_license
#include <iostream> #include <algorithm> using namespace std; vector<int> plusOne(vector<int> &A) { int carry = 0; for(int i = A.size()-1; i >= 0; i--) { if( i == A.size()-1){ A[i] += 1; }else { A[i] += carry; carry = 0; } if(A[i] > 9){ A[i] = 0; carry = 1; } } if(carry == 1){ A.insert(A.begin(),carry); } while (A[0] == 0){ A.erase(A.begin()); } return A; } int main() { vector<int> A{ 0, 6, 0, 6, 4, 8, 8, 1}; vector<int> result = plusOne(A); for(auto i: result) { cout << i ; } cout << endl; return 0; }
true
065a926f2aa253211ebd30a17eaefc7db62e27ce
C++
ScXin/StorageAndBufferManager
/Storage_and_Buffer_Manager_v2/Hash_P2F.cpp
UTF-8
1,936
3.265625
3
[]
no_license
#include "Hash_P2F.h" using namespace std; Hash_P2F::Hash_P2F(){ init(); } void Hash_P2F::init(){ for(int i = 0; i < BUFFERSIZE; i ++){ BCB * newHead = new BCB; BCB * newTrail = new BCB; newHead ->isHead = true; newHead ->isTrail =false; newHead ->previous = nullptr; newHead ->next = newTrail; newTrail ->isHead = false; newTrail ->isTrail = true; newTrail ->previous = newHead; newTrail ->next = nullptr; hashTable[i] = newHead; } cout << "# (5/5) Hash table of page to frame initialize competed. #" << endl; } //Return whether the specific page with the pageID exist in the buffer. bool Hash_P2F::findPage(const int pageID){ int hashResult = hash(pageID); searchPtr = hashTable[hashResult]; while(searchPtr ->next ->isTrail != true){ searchPtr = searchPtr ->next; if (searchPtr ->pageID == pageID) return true; } return false; } //Calculate the hash. int Hash_P2F::hash(const int pageID) const{ return (pageID % BUFFERSIZE); } void Hash_P2F::insertBCB(const int frameID, const int pageID, const bool isWrite){ int hashResult = hash(pageID); BCB * inserting = new BCB; inserting ->frameID = frameID; inserting ->pageID = pageID; inserting ->isWrite = isWrite; inserting ->isHead = false; inserting ->isTrail =false; inserting ->previous = hashTable[hashResult]; inserting ->next = hashTable[hashResult] ->next; inserting ->next ->previous = inserting; hashTable[hashResult] ->next = inserting; } //Find where the node with the pageID is. BCB * Hash_P2F::locateNode(const int pageID){ int hashResult = hash(pageID); BCB * searchPtr = hashTable[hashResult]; while(searchPtr ->next ->isTrail != true){ searchPtr = searchPtr ->next; if(searchPtr ->pageID == pageID){ return searchPtr; } } } //Cut the two pointer of the node. void Hash_P2F::dropBCB(BCB * const victim){ victim ->previous ->next = victim ->next; victim ->next ->previous = victim ->previous; }
true
bacf4633e6f0b40f3cf0cd8fef5ca2fd504ddb3f
C++
RickyLiu0w0/HomeWorkCode
/Algorithms/Brute_Force/sequentialSearch2.cpp
UTF-8
415
3.53125
4
[]
no_license
#include <vector> int SequentialSearch2(std::vector<int> arr, int key) { //顺序查找的算法实现,它用例查找键作为限位器 //输入:一个n个元素的数组arr和一个查找键key //输出:第一个值等于key的元素的位置,如果找不到这个元素,返回-1 arr.push_back(key); int i = 0; while (arr[i] != key) i++; if (i < arr.size() - 1) return i; else return -1; }
true
a4dc1ef23da2a0088fcdff424e52e8478fc85cef
C++
frittblas/fbl
/game_projects/Ca2/GameState/Race/Maze.cpp
UTF-8
20,690
2.5625
3
[]
no_license
/* * * Charming Alarming 2: Reasonable Robots * * Maze.cpp * * Maze class implementation, takes care of the maze generation etc.. * * Hans Strömquist 2022 * */ #include "../../../../src/fbl.hpp" #include "../../Ecs/Ecs.hpp" #include "../../Ecs/Components.hpp" #include "../../Game.hpp" #include "Maze.hpp" Maze::aFlag gFlag[Maze::cMaxFlags]; // the flag sprites, externed in PathLogicSystem Maze::aCoin gCoin[Maze::cMaxCoins]; // the coins, also externed in PathLogicSystem // Maze-class implementation Maze::Maze() { std::cout << "Maze constructor." << std::endl; } Maze::~Maze() { std::cout << "Maze destructor." << std::endl; } void Maze::tick(Game& g) { if (mPickTimer > 0) pickStartPosition(g); else { if (mPickTimer == -150) { // wait a little before starting // make robots move for (int i = 0; i < mNumRacers; i++) fbl_pathf_set_path_status(mPathId[i], FBL_PATHF_FOUND); std::cout << "Picked pos: " << mPickedPosition << std::endl; std::cout << "Running! Num sprites: " << fbl_get_num_sprites() << std::endl; mPickTimer--; } else if(mPickTimer > -160) mPickTimer--; updateGUI(g); } } void Maze::setupPickStart() { // black bg mBlackBgId = fbl_create_prim(FBL_NORMAL_RECT, 0, 0, Game::DeviceResW, Game::DeviceResH, 0, 0, 1); fbl_set_prim_color(mBlackBgId, 0, 0, 0, 255); mBlackBgFade = 255; // get ready text fbl_load_ttf_font("font/garamond.ttf", 48); mGetReadyTextId = fbl_create_text(255, 69, 0, 255, (char*)"GET READY!"); fbl_set_text_align(mGetReadyTextId, FBL_ALIGN_CENTER); fbl_set_text_xy(mGetReadyTextId, fbl_get_screen_w() / 2, fbl_get_screen_h() / 3); // circle = type 6 (starts at id's 1-11) mCircleSize[0] = 5; mCircleSize[1] = 30; mCircleSize[2] = 55; int xOffset = Game::TileSize / 2 + 96; mFirstCircleId = fbl_create_prim(FBL_CIRCLE, xOffset, Game::TileSize / 2, 0, 0, mCircleSize[0], true, false); fbl_create_prim(FBL_CIRCLE, xOffset, Game::TileSize / 2, 0, 0, mCircleSize[1], true, false); fbl_create_prim(FBL_CIRCLE, xOffset, Game::TileSize / 2, 0, 0, mCircleSize[2], true, false); fbl_create_prim(FBL_CIRCLE, Game::LogicalResW - xOffset, Game::TileSize / 2, 0, 0, mCircleSize[0], true, false); fbl_create_prim(FBL_CIRCLE, Game::LogicalResW - xOffset, Game::TileSize / 2, 0, 0, mCircleSize[1], true, false); fbl_create_prim(FBL_CIRCLE, Game::LogicalResW - xOffset, Game::TileSize / 2, 0, 0, mCircleSize[2], true, false); fbl_create_prim(FBL_CIRCLE, xOffset, cMazeSizeY * Game::TileSize - Game::TileSize / 2, 0, 0, mCircleSize[0], true, false); fbl_create_prim(FBL_CIRCLE, xOffset, cMazeSizeY * Game::TileSize - Game::TileSize / 2, 0, 0, mCircleSize[1], true, false); fbl_create_prim(FBL_CIRCLE, xOffset, cMazeSizeY * Game::TileSize - Game::TileSize / 2, 0, 0, mCircleSize[2], true, false); fbl_create_prim(FBL_CIRCLE, Game::LogicalResW - xOffset, cMazeSizeY * Game::TileSize - Game::TileSize / 2, 0, 0, mCircleSize[0], true, false); fbl_create_prim(FBL_CIRCLE, Game::LogicalResW - xOffset, cMazeSizeY * Game::TileSize - Game::TileSize / 2, 0, 0, mCircleSize[1], true, false); fbl_create_prim(FBL_CIRCLE, Game::LogicalResW - xOffset, cMazeSizeY * Game::TileSize - Game::TileSize / 2, 0, 0, mCircleSize[2], true, false); mTimeBarId = fbl_create_prim(FBL_RECT, fbl_get_screen_w() / 2, (cMazeSizeY - 1) * Game::TileSize, mTimeToPick * 60, Game::TileSize / 2, 0, false, true); fbl_set_prim_color(mTimeBarId, 0, 255, 0, 255); mTimeBarRed = 0; mPickTimer = (mGetReadyTimer + mTimeToPick) * 60; // 8 seconds(i.e 3 + 5) } void Maze::pickStartPosition(Game& g) { // do some nice circle effects for (int i = 0; i < 3; i++) { mCircleSize[i]++; if(mCircleSize[i] > 55) mCircleSize[i] = 5; } for (int i = mFirstCircleId; i < (mFirstCircleId + 12); i++) { if ((i + 2) % 3 == 0) fbl_set_prim_size(i, 0, 0, mCircleSize[0]); else if ((i + 1) % 3 == 0) fbl_set_prim_size(i, 0, 0, mCircleSize[1]); else if (i % 3 == 0) fbl_set_prim_size(i, 0, 0, mCircleSize[2]); } // handle pick selection int xPickOffset = Game::TileSize * 6; int yPickOffset = Game::TileSize * 3; if (fbl_get_mouse_click(FBLMB_LEFT) > 0 && mPickTimer < mTimeToPick * 60) { // if clicked and after GET READY phase if(fbl_get_mouse_logical_x() < xPickOffset && fbl_get_mouse_logical_y() < yPickOffset){ // up left mPickedPosition = 0; // this is the picked corner mPickTimer = -1; // stop the pick corner state assignPaths(g); // assign new paths to the robots based on the selection } else if (fbl_get_mouse_logical_x() > Game::LogicalResW - xPickOffset && fbl_get_mouse_logical_y() < yPickOffset) { mPickedPosition = 1; mPickTimer = -1; assignPaths(g); } else if (fbl_get_mouse_logical_x() < xPickOffset && fbl_get_mouse_logical_y() > cMazeSizeY * Game::TileSize - yPickOffset) { mPickedPosition = 2; mPickTimer = -1; assignPaths(g); } else if (fbl_get_mouse_logical_x() > Game::LogicalResW - xPickOffset && fbl_get_mouse_logical_y() > cMazeSizeY * Game::TileSize - yPickOffset) { mPickedPosition = 3; mPickTimer = -1; assignPaths(g); } std::cout << "mouse xy: " << fbl_get_mouse_logical_x() << ", " << fbl_get_mouse_logical_y() << std::endl; } mPickTimer--; //count down if(mPickTimer < (mTimeToPick + 1) * 60) { mBlackBgFade -= 4; fbl_set_prim_color(mBlackBgId, 0, 0, 0, mBlackBgFade); } if(mPickTimer == mTimeToPick * 60){ fbl_set_prim_active(mBlackBgId, false); // deactivate bg after the fadeout fbl_set_text_active(mGetReadyTextId, false); } // time bar if(mPickTimer < mTimeToPick * 60){ fbl_set_prim_size(mTimeBarId, mPickTimer, Game::TileSize / 2, 0); int green_fade = mPickTimer; // 45 if(green_fade > 255) green_fade = 255; if(green_fade < 1) green_fade = 0; fbl_set_prim_color(mTimeBarId, mTimeBarRed, green_fade, 0, 255); mTimeBarRed++; if(mTimeBarRed > 255) mTimeBarRed = 255; //print(mPickTimer - 45) } if (mPickTimer < 1) { if (mPickTimer == 0) { mPickedPosition = rand() % 4; // if time runs out, assign a random position assignPaths(g); } // create gui for the robots () coins health etc createGUI(); std::cout << "created GUI!" << std::endl; for (int i = mFirstCircleId; i < (mFirstCircleId + 12); i++) fbl_set_prim_active(i, false); fbl_set_text_active(mGetReadyTextId, false); fbl_set_prim_active(mBlackBgId, false); fbl_set_prim_active(mTimeBarId, false); } } void Maze::initMaze(Game& g, int density, int numRacers) { int tries = 0; // number of brute force tries fbl_set_sprite_align(FBL_SPRITE_ALIGN_CENTER); // in the race, sprites are drawn from the center bc. of physics :) setupPickStart(); mNumRacers = numRacers; addBorder(); fbl_set_clear_color(50, 50, 50, 0); // set up starting positions (make this part of showRobotInRace()?) mStartPos[0][0] = Game::TileSize * 3; mStartPos[0][1] = 0; mStartPos[1][0] = Game::LogicalResW - Game::TileSize * 4; mStartPos[1][1] = 0; mStartPos[2][0] = Game::TileSize * 3; mStartPos[2][1] = Game::TileSize * 16; mStartPos[3][0] = Game::LogicalResW - Game::TileSize * 4; mStartPos[3][1] = Game::TileSize * 16; // collect the path id's and stuff for the racing robots for (int i = 0; i < numRacers; i++) { auto& path = g.mEcs->GetComponent<Path>(g.mRobots->mRacingRobots[i]); auto& pos = g.mEcs->GetComponent<Position>(g.mRobots->mRacingRobots[i]); mPathId[i] = path.id; mStartPos[i][0] = pos.x; mStartPos[i][1] = pos.y; mUseDiag[i] = path.diag; path.goalX = cTargetX; path.goalY = cTargetY; path.newPath = false; } // set all paths to not started for (int i = 0; i < numRacers; i++) fbl_pathf_set_path_status(mPathId[i], FBL_PATHF_NOT_STARTED); // brute force maze creation :) (with a density below 40 it's reasonable, 35 and below is really good (fast).) do { resetMaze(); randomizeMaze(density); for (int i = 0; i < cMaxRacers; i++) fbl_pathf_set_path_status(i, fbl_pathf_find_path(i, mStartPos[i][0], mStartPos[i][1], cTargetX, cTargetY, true)); tries++; } while (!mazeHasAllPaths()); // make robots not move at first stopPathing(); // set relevant tiles to walkable for (int i = 0; i < cMaxRacers; i++) fbl_pathf_set_walkability(mStartPos[i][0] / Game::TileSize, mStartPos[i][1] / Game::TileSize, FBL_PATHF_WALKABLE); fbl_pathf_set_walkability(cTargetX / Game::TileSize, cTargetY / Game::TileSize, FBL_PATHF_WALKABLE); // create all the sprites at correct locations populateMaze(); // add the flag and coins addItems(); for (int i = 0; i < numRacers; i++) std::cout << "Path status: " << fbl_pathf_get_path_status(mPathId[i]) << std::endl; std::cout << "has all paths: " << mazeHasAllPaths() << std::endl; std::cout << "Tries: " << tries << std::endl; std::cout << "Num sprites: " << fbl_get_num_sprites() << std::endl; } void Maze::stopPathing() { for (int i = 0; i < mNumRacers; i++) fbl_pathf_set_path_status(mPathId[i], FBL_PATHF_NOT_STARTED); } void Maze::resetMaze() { for (int i = 3; i < cMazeSizeX - 3; i++) for (int j = 0; j < cMazeSizeY; j++) fbl_pathf_set_walkability(i, j, FBL_PATHF_WALKABLE); // set all to walkable } void Maze::randomizeMaze(int density) { for (int i = 3; i < cMazeSizeX - 3; i++) for (int j = 0; j < cMazeSizeY; j++) if ((rand() % 100) < density) fbl_pathf_set_walkability(i, j, FBL_PATHF_UNWALKABLE); // set these to unwalkable } void Maze::populateMaze() { // creates sprites with correct coordinates as obstacles for (int i = 3; i < cMazeSizeX - 3; i++) { for (int j = 0; j < cMazeSizeY; j++) { // add a block if it's unwalkable if (fbl_pathf_get_walkability(i, j) == FBL_PATHF_UNWALKABLE) { int id = fbl_create_sprite(32, 416, 32, 32, 0); fbl_set_sprite_xy(id, i * Game::TileSize + 16, j * Game::TileSize + 16); // these get drawn from the center fbl_set_sprite_phys(id, true, FBL_RECT, FBL_PHYS_KINEMATIC, false); } } } } void Maze::addItems() { // add flags in the middle for (int i = 0; i < cMaxFlags; i++) { gFlag[i].id = fbl_create_sprite(265, 324, 17, 24, 0); fbl_set_sprite_xy(gFlag[i].id, cTargetX + 16, cTargetY + 16); // drawn from the center gFlag[i].state = FlagState::Center; // start in the center } // add random amount of coins (from 10 to 20) for (int i = 0; i < Maze::cMaxCoins; i++) gCoin[i].id = -1; // set all id's to -1 int numCoins = rand() % (Maze::cMaxCoins / 2) + 10; std::cout << "numCoins: " << numCoins << std::endl; for (int i = 0; i < numCoins; i++) { gCoin[i].id = fbl_create_sprite(320, 288, 16, 16, 0); fbl_set_sprite_animation(gCoin[i].id, true, 320, 288, 16, 16, 2, 30, true); int x = 3 + rand() % (cMazeSizeX - 6); int y = rand() % cMazeSizeY; while (fbl_pathf_get_walkability(x, y) == FBL_PATHF_UNWALKABLE || (x * Game::TileSize == cTargetX && y * Game::TileSize == cTargetY)) { int x = 3 + rand() % (cMazeSizeX - 6); y = rand() % cMazeSizeY; } fbl_set_sprite_xy(gCoin[i].id, x * Game::TileSize + 16, y * Game::TileSize + 16); // drawn from the center } } void Maze::addBorder() { // creates sprites with correct coordinates as obstacles for (int i = 0; i < cMazeSizeX + 6; i++) { for (int j = 0; j < cMazeSizeY; j++) { // draw a frame left and right of maze if ((i >= 0 && i < 3) || (i > 26 && i < 30)) { int id = fbl_create_sprite(64, 416, 32, 32, 0); fbl_set_sprite_xy(id, i * Game::TileSize + 16, j * Game::TileSize + 16); if(i == 2 || i == 27) fbl_set_sprite_phys(id, true, FBL_RECT, FBL_PHYS_KINEMATIC, false); } } } // add a row of unwalkable tiles at the very bottom, one step below screen (not visible) for (int i = 0; i < cMazeSizeX; i++) fbl_pathf_set_walkability(i, cMazeSizeY, FBL_PATHF_UNWALKABLE); // and two columns left and right of the maze for (int j = 0; j < cMazeSizeY; j++) fbl_pathf_set_walkability(2, j, FBL_PATHF_UNWALKABLE); for (int j = 0; j < cMazeSizeY; j++) fbl_pathf_set_walkability(27, j, FBL_PATHF_UNWALKABLE); } // create the gui in each corner showing how many flags and coins each robot has got, lifebars etc etc void Maze::createGUI() { // 96x64 gui thing in all 4 corners int id = fbl_create_sprite(416, 288, 96, 64, 0); fbl_set_sprite_xy(id, 48, 32); fbl_set_sprite_layer(id, 10); id = fbl_create_sprite(416, 288, 96, 64, 0); fbl_set_sprite_xy(id, 912, 32); fbl_set_sprite_layer(id, 10); id = fbl_create_sprite(416, 288, 96, 64, 0); fbl_set_sprite_xy(id, 48, 512); fbl_set_sprite_layer(id, 10); id = fbl_create_sprite(416, 288, 96, 64, 0); fbl_set_sprite_xy(id, 912, 512); fbl_set_sprite_layer(id, 10); // add base markers (spinning circles) topleft, top right, down left, down right, draw from center id = fbl_create_sprite(224, 352, 32, 32, 0); fbl_set_sprite_xy(id, 3 * Game::TileSize + 16, 16); fbl_set_sprite_animation(id, true, 224, 352, 32, 32, 9, 7, true); fbl_set_sprite_color(id, 255, 127, 80); // coral red fbl_set_sprite_alpha(id, 150); fbl_set_sprite_layer(id, 0); id = fbl_create_sprite(224, 352, 32, 32, 0); fbl_set_sprite_xy(id, (cMazeSizeX - 4) * Game::TileSize + 16, 16); fbl_set_sprite_animation(id, true, 224, 352, 32, 32, 9, 7, true); fbl_set_sprite_color(id, 80, 200, 120); // emerald green fbl_set_sprite_alpha(id, 150); fbl_set_sprite_layer(id, 0); id = fbl_create_sprite(224, 352, 32, 32, 0); fbl_set_sprite_xy(id, 3 * Game::TileSize + 16, (cMazeSizeY - 1) * Game::TileSize + 16); fbl_set_sprite_animation(id, true, 224, 352, 32, 32, 9, 7, true); fbl_set_sprite_color(id, 0, 150, 255); // bright blue fbl_set_sprite_alpha(id, 150); fbl_set_sprite_layer(id, 0); id = fbl_create_sprite(224, 352, 32, 32, 0); fbl_set_sprite_xy(id, (cMazeSizeX - 4) * Game::TileSize + 16, (cMazeSizeY - 1) * Game::TileSize + 16); fbl_set_sprite_animation(id, true, 224, 352, 32, 32, 9, 7, true); fbl_set_sprite_color(id, 251, 236, 93); // nice yellow fbl_set_sprite_alpha(id, 150); fbl_set_sprite_layer(id, 0); fbl_sort_sprites(FBL_SORT_BY_LAYER); // text items fbl_load_ttf_font("font/garamond.ttf", 15); gui[0].levelTextId = fbl_create_text(255, 255, 255, 255, "%d", 1); fbl_set_text_xy(gui[0].levelTextId, 38, 9); gui[1].levelTextId = fbl_create_text(255, 255, 255, 255, "%d", 1); fbl_set_text_xy(gui[1].levelTextId, 902, 9); gui[2].levelTextId = fbl_create_text(255, 255, 255, 255, "%d", 1); fbl_set_text_xy(gui[2].levelTextId, 38, 489); gui[3].levelTextId = fbl_create_text(255, 255, 255, 255, "%d", 1); fbl_set_text_xy(gui[3].levelTextId, 902, 489); fbl_load_ttf_font("font/garamond.ttf", 16); gui[0].flagTextId = fbl_create_text(255, 255, 255, 255, "%d", 0); fbl_set_text_xy(gui[0].flagTextId, 78, 26); gui[0].coinTextId = fbl_create_text(255, 255, 255, 255, "%d", 0); fbl_set_text_xy(gui[0].coinTextId, 38, 26); gui[1].flagTextId = fbl_create_text(255, 255, 255, 255, "%d", 0); fbl_set_text_xy(gui[1].flagTextId, 942, 26); gui[1].coinTextId = fbl_create_text(255, 255, 255, 255, "%d", 0); fbl_set_text_xy(gui[1].coinTextId, 902, 26); gui[2].flagTextId = fbl_create_text(255, 255, 255, 255, "%d", 0); fbl_set_text_xy(gui[2].flagTextId, 78, 506); gui[2].coinTextId = fbl_create_text(255, 255, 255, 255, "%d", 0); fbl_set_text_xy(gui[2].coinTextId, 38, 506); gui[3].flagTextId = fbl_create_text(255, 255, 255, 255, "%d", 0); fbl_set_text_xy(gui[3].flagTextId, 942, 506); gui[3].coinTextId = fbl_create_text(255, 255, 255, 255, "%d", 0); fbl_set_text_xy(gui[3].coinTextId, 902, 506); // red and blue hp/pow rects gui[0].hpRectId = fbl_create_prim(FBL_NORMAL_RECT, 33, 43, 50, 3, 0, false, true); //fbl_set_prim_color(gui[0].hpRectId, 0, 237, 55, 36); gui[0].powRectId = fbl_create_prim(FBL_NORMAL_RECT, 33, 53, 50, 3, 0, false, true); fbl_set_prim_color(gui[0].powRectId, 0, 162, 232, 255); gui[1].hpRectId = fbl_create_prim(FBL_NORMAL_RECT, 897, 43, 50, 3, 0, false, true); //fbl_set_prim_color(gui[0].hpRectId, 0, 237, 55, 36); gui[1].powRectId = fbl_create_prim(FBL_NORMAL_RECT, 897, 53, 50, 3, 0, false, true); fbl_set_prim_color(gui[1].powRectId, 0, 162, 232, 255); gui[2].hpRectId = fbl_create_prim(FBL_NORMAL_RECT, 33, 523, 50, 3, 0, false, true); //fbl_set_prim_color(gui[0].hpRectId, 0, 237, 55, 36); gui[2].powRectId = fbl_create_prim(FBL_NORMAL_RECT, 33, 533, 50, 3, 0, false, true); fbl_set_prim_color(gui[2].powRectId, 0, 162, 232, 255); gui[3].hpRectId = fbl_create_prim(FBL_NORMAL_RECT, 897, 523, 50, 3, 0, false, true); //fbl_set_prim_color(gui[0].hpRectId, 0, 237, 55, 36); gui[3].powRectId = fbl_create_prim(FBL_NORMAL_RECT, 897, 533, 50, 3, 0, false, true); fbl_set_prim_color(gui[3].powRectId, 0, 162, 232, 255); } void Maze::updateGUI(Game& g) { int barMaxWidth = 50; // Maximum width of hp and power bar int barPercentage = 0; // how many % are filled? int barWidth = 0; // the final bar for (int i = 0; i < mNumRacers; i++) { auto& stat = g.mEcs->GetComponent<Stats>(g.mRobots->mRacingRobots[i]); auto& plog = g.mEcs->GetComponent<PathLogic>(g.mRobots->mRacingRobots[i]); // update number of flags, coins and hp + power (energy) if (plog.baseX == Game::TileSize * 3 && plog.baseY == 0) setOneUIbox(stat, plog, 0, g.mRobots->mRacingRobots[i]); if (plog.baseX == Game::LogicalResW - Game::TileSize * 4 && plog.baseY == 0) setOneUIbox(stat, plog, 1, g.mRobots->mRacingRobots[i]); if (plog.baseX == Game::TileSize * 3 && plog.baseY == Game::TileSize * 16) setOneUIbox(stat, plog, 2, g.mRobots->mRacingRobots[i]); if (plog.baseX == Game::LogicalResW - Game::TileSize * 4 && plog.baseY == Game::TileSize * 16) setOneUIbox(stat, plog, 3, g.mRobots->mRacingRobots[i]); } } void Maze::setOneUIbox(Stats stat, PathLogic plog, int base, int entity) { int barMaxWidth = 50; // Maximum width of hp pand power bar double barPercentage = 0.0; int barWidth = 0; // update number of flags, coins and level if (gui[base].level != stat.level) { fbl_update_text(gui[base].levelTextId, 255, 255, 255, 255, "%d", stat.level); gui[base].level = stat.level; std::cout << "updated level text for player " << entity << std::endl; } if (gui[base].coins != plog.coins) { fbl_update_text(gui[base].coinTextId, 255, 255, 255, 255, "%d", plog.coins); gui[base].coins = plog.coins; std::cout << "updated coin text for player " << entity << std::endl; } if (gui[base].flags != plog.flags) { fbl_update_text(gui[base].flagTextId, 255, 255, 255, 255, "%d", plog.flags); gui[base].flags = plog.flags; std::cout << "updated flag text for player " << entity << std::endl; } // hp and power meters barPercentage = static_cast<double>(stat.hp) / stat.maxHp; // calc the percentage barWidth = std::round(barMaxWidth * barPercentage); // calc width of the bar fbl_set_prim_size(gui[base].hpRectId, barWidth, 3, 0); // resize the rect // same with power (energy) bar barPercentage = static_cast<double>(stat.energy) / stat.maxEnergy; barWidth = std::round(barMaxWidth * barPercentage); fbl_set_prim_size(gui[base].powRectId, barWidth, 3, 0); } bool Maze::mazeHasAllPaths() { for (int i = 0; i < cMaxRacers; i++) if (fbl_pathf_get_path_status(i) != FBL_PATHF_FOUND) return false; return true; } void Maze::assignPaths(Game& g) { // randomize paths, then assign mPickedPosition to the player and position everything int arr[] = { 0, 1, 2, 3 }; // create ordered array with starting positions // shuffle the array using the Fisher-Yates algorithm for (int i = cMaxRacers - 1; i > 0; i--) { int j = rand() % (i + 1); int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // find if a robot has the picked path, swap it with the players path (even if it's the player) for (int i = 0; i < cMaxRacers; i++) { if(arr[i] == mPickedPosition) { // found it // swap arr[i] = arr[0]; arr[0] = mPickedPosition; break; // break loop } } // place robots at the new random locations for (int i = 0; i < mNumRacers; i++) g.mRobots->showRobotInRace(g.mEcs, g.mRobots->mRacingRobots[i], arr[i]); for (int i = 0; i < mNumRacers; i++) { auto& pos = g.mEcs->GetComponent<Position>(g.mRobots->mRacingRobots[i]); auto& plog = g.mEcs->GetComponent<PathLogic>(g.mRobots->mRacingRobots[i]); mStartPos[i][0] = pos.x; mStartPos[i][1] = pos.y; // set the robots base coords plog.baseX = pos.x; plog.baseY = pos.y; } // finally find paths for the new locations (will find immediately, maze is already in place (maze is a place)) for (int i = 0; i < mNumRacers; i++) fbl_pathf_set_path_status(mPathId[i], fbl_pathf_find_path(mPathId[i], mStartPos[i][0], mStartPos[i][1], cTargetX, cTargetY, mUseDiag[i])); // don't start immediately stopPathing(); }
true
e0ee13ba9a548a46f41281f7a3c1771732467809
C++
rosero42/Basic-Client-Server
/Client.cpp
UTF-8
4,181
3
3
[]
no_license
#include <iostream> #include <string> #include <stdio.h> #include <sys/time.h> #include <sys/types.h> // socket, bind #include <sys/socket.h> // socket, bind, listen, inet_ntoa #include <netinet/in.h> // htonl, htons, inet_ntoa #include <arpa/inet.h> // inet_ntoa #include <netdb.h> // gethostbyname #include <unistd.h> // read, write, close #include <string.h> // bzero #include <netinet/tcp.h> // SO_REUSEADDR #include <sys/uio.h> // writev using namespace std; //Program must take in six arguments: // serverPort - server's port number // serverName - server's IP address or host name // iterations - number of iterations // nbufs - number of data buffers // bufsize - the size of each data buffer (bytes) // type - the type of transfer int main(int argc, char* argv[]) { //first, create a "help" flag for users to get info about the program if (argc < 3) { if (string(argv[1]) == "--help" || string(argv[1]) == "-h") { cout << "This is the help function. We'll write something else" << "here soon\n"; return 0; } } //Check that there are enough parameters // If there are too many parameters, the extra ones will not be considered if (argc < 7) { cerr << "ERROR: not enough arguments"; return 1; } //Define the parameters char* serverPort = argv[1]; char* serverName = argv[2]; int iterations = atoi(argv[3]); int nbufs = atoi(argv[4]); int bufsize = atoi(argv[5]); int type = atoi(argv[6]); //Check that the type is valid if (type < 1 || type > 3) { cerr << "ERROR: invalid type entered. Must be type 1, 2, or 3"; return 1; } //Declare addrinfo and servinfo struct addrinfo hints; struct addrinfo *servInfo; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; getaddrinfo(serverName, serverPort, &hints, &servInfo); //1. Open a new socket and create a secure connection //Open int clientSd = socket(servInfo->ai_family, servInfo->ai_socktype, servInfo->ai_protocol); //Connect int status = connect(clientSd, servInfo->ai_addr, servInfo->ai_addrlen); if(status < 0){ cerr << "Failed to connect to the server\n"; close(clientSd); return -1; } //2. allocate the data buffers char** databuf = new char* [nbufs]; for (int i = 0; i < nbufs; i++){ databuf[i] = new char[bufsize]; //Where nbufs * bufsize = 1500 } for (int i = 0; i < nbufs; i++) { for (int j = 0; j < bufsize; j++) { databuf[i][j] = 'A'; } } //3. Start a timer by calling gettimeofday struct timeval startTime; int start = gettimeofday(&startTime, NULL); struct timeval lapTime; //4. Repeat the iteration times of data transfers //Perform action needed for given type switch (type) { case 1: //Multiple Writes for (int i = 0; i < iterations; i++) { for (int j = 0; j < nbufs; j++) write(clientSd, databuf[j], bufsize); } break; case 2: for(int i = 0; i < iterations; i++){ struct iovec vector[nbufs]; for(int j = 0; j < nbufs; j++){ vector[j].iov_base = databuf[j]; vector[j].iov_len = bufsize; } writev(clientSd, vector, nbufs); } break; case 3: for(int i = 0; i < iterations; i++){ write(clientSd, (void*)databuf, nbufs * bufsize); } break; default: cerr << "It is not possible to be here\n"; return 1; } //5. Lap the timer by calling gettimeofday // where lap - start = data-transmission time int lap = gettimeofday(&lapTime, NULL); struct timeval data_transmission; timersub(&lapTime, &startTime, &data_transmission); //6. Receive from the server an acknowledgement that shows how many times // the server called read( ). int count = 0; int ret = read(clientSd, &count, sizeof(count)); //7. Stop the timer by calling gettimeofday, // where stop - start = round-trip time. struct timeval stopTime; struct timeval roundtrip; timersub(&stopTime, &startTime, &roundtrip); cout << "Test 1: data-transmission time = " << data_transmission.tv_usec << " usec, round-trip time = " << roundtrip.tv_usec << " usec, #reads = " << count << endl; //deallocate all instances of new for (int i = 0; i < nbufs; i++) delete[] databuf[i]; delete[] databuf; close(clientSd); return 0; }
true
4f989e03a4e62145edb3381d09526bc15533b27e
C++
ja754969/Cplusplus-Programming
/上課檔案/課本範例檔/chapter 10_使用者自訂函式/範例10-11.cpp
BIG5
850
3.390625
3
[]
no_license
#include <iostream> #include <cstdlib> #include <string> using namespace std; void totalmoney(int *,int,int,int); //ŧi禡 int main() { int money[2][3][2],i,j,k; string interval[2]={"W","U"}; for (i=0;i<2;i++) for (j=0;j<3;j++) for (k=0;k<2;k++) { cout << "J" << i+1<<"aq" << j+1 << "~" << interval[k] << "b~~B(:):" ; cin >> money[i][j][k] ; } totalmoney(&money[0][0][0],2,3,2); system("pause"); return 0; } void totalmoney(int *d , int l , int m , int n) //wq禡 { int i,j,k,sum=0; for (i=0;i<l;i++) for (j=0;j<m;j++) for (k=0;k<n;k++) sum=sum+*(d+i*m*n+j*n+k); // *(d+i*m*n+j*n+k) N money[i][j][k] cout << "`~B(:):" << sum << '\n' ; }
true
c88e1151a1da3f0f01337451ae84354afc7b5276
C++
juyingguo/android-knowledge-principle-interview
/18-c-and-cpp/cpp/C++程序设计题解与上机指导(第2版)-byeink/教材例题程序/c12/c12-3-2.cpp
UTF-8
340
2.984375
3
[]
no_license
#include <iostream> using namespace std; class Point {public: Point(){} virtual ~Point(){cout<<"executing Point destructor"<<endl;} }; class Circle:public Point {public: Circle(){} ~Circle(){cout<<"executing Circle destructor"<<endl;} private: int radus; }; void main() {Point *p=new Circle; delete p; }
true
4a4b36e7874cc31e939e4e308082c9e1588d5097
C++
FranckRJ/HVlov-server
/hvlov-server/hvlov-entries/include/IHvlovEntrySerializer.hpp
UTF-8
931
3.09375
3
[ "Zlib" ]
permissive
#pragma once #include <string> #include <vector> #include "BaseInterface.hpp" #include "HvlovEntry.hpp" namespace hvlov { /*! * Interface used to serialize HvlovEntries to diverse type of strings. */ class IHvlovEntrySerializer : public BaseInterface { public: /*! * Serialize an HvlovEntry to a JSON string. * * @param entry The HvlovEntry to serialize. * @return The HvlovEntry serialized to a JSON string. */ virtual std::string serializeEntryToJson(const HvlovEntry& entry) const = 0; /*! * Serialize a vector of HvlovEntries to a JSON string. * * @param entries The HvlovEntries to serialize. * @return The HvlovEntries serialized to a JSON string. */ virtual std::string serializeEntriesToJson(const std::vector<HvlovEntry>& entries) const = 0; }; } // namespace hvlov
true
12a9dfb0b77c164318300a7c9d029cc594c3a77b
C++
retrobrain/Employee
/Sources/employee.h
UTF-8
1,049
3.375
3
[]
no_license
#ifndef EMPLOYEE_H #define EMPLOYEE_H #include "globalappconsts.h" namespace SALARY { const int HOURLY = 2233; const int FIXED = 3344; } class Employee { public: Employee(); Employee(int id, const std::string &name, float salary, int T); // copy and assignment prohibited Employee(const Employee&) = delete; void operator=(const Employee&) = delete; virtual ~Employee(); virtual void setId(int id) { m_iId = id; } virtual int getId() const { return m_iId; } virtual void setName(const std::string &name) { m_strName = name; } virtual std::string getName() const { return m_strName; } virtual void setType(int type) { m_salaryType = type; } virtual int getType() const { return m_salaryType; } void setSalary(float salary) { m_fSalary = salary; } virtual float getSalary() const = 0; bool operator<(const Employee& object); protected: float m_fSalary; int m_salaryType; private: int m_iId; std::string m_strName; }; #endif // EMPLOYEE_H
true
6291d8e9ac38d075dda9c8f78f1adfd05b93b5c2
C++
Taekyukim02/usaco
/astar/plat/schlnet/schlnet.cpp
UTF-8
1,655
3.25
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #define MAX_N 100 using namespace std; int N; vector <int> graph[MAX_N+5]; // solve A methods int order[MAX_N + 5]; int orderIdx = 0; bool visited[MAX_N+5]; void topSort(int n) { visited[n] = true; for(int to : graph[n]) { if(!visited[to]) topSort(to); } order[orderIdx++] = n; } void markVisited(int n) { visited[n] = true; for(int to : graph[n]) { if(!visited[to]) markVisited(to); } } int solveA() { for(int i=0; i<N; i++) if(!visited[i]) topSort(i); reverse(order, order+N); for(int i=0; i<N; i++) visited[i] = false; int ans = 0; for(int i=0; i<N; i++) { if(!visited[order[i]]) { markVisited(order[i]); ans++; } } return ans; } // solve B methods vector <int> rGraph[MAX_N+5]; void markRVisited(int n) { visited[n] = true; for(int to : rGraph[n]) { if(!visited[to]) markRVisited(to); } } int solveB() { for(int i=0; i<N; i++) visited[i] = false; int ans1=0, ans2=0; // start from sink nodes, and mark all ancestor nodes (including cycles) for(int i=N-1; i>=0; i--) { if(!visited[order[i]]) { markRVisited(order[i]); ans1++; } } for(int i=0; i<N; i++) visited[i] = false; // start from all top nodes for(int i=0; i<N; i++) { if(!visited[order[i]]) { markVisited(order[i]); ans2++; } } return max(ans1, ans2); } int main() { // read input cin >> N; for(int i=0; i<N; i++) { int c; cin >> c; while(c != 0) { graph[i].push_back(c-1); rGraph[c-1].push_back(i); cin >> c; } } // solve A cout << solveA() << endl; // solve B cout << solveB() << endl; return 0; }
true
a64457874d64c73392a2938f98118ee7f7623a23
C++
ckobylko/HIPAccBenchmark
/src/Benchmark/Benchmark.cpp
UTF-8
1,960
2.578125
3
[]
no_license
// Benchmark.cpp : Defines the entry point for the console application. // #include "../../include/MemoryThroughput/MemoryThroughput.h" #include "../../include/ImageAdd/ImageAdd.h" #include "../../include/NormalizedGradient/NormalizedGradient.h" #include "../../include/BubbleSortMedian/BubbleSortMedian.h" #include "../../include/BubbleSortMedianOptimized/BubbleSortMedianOptimized.h" #include "../../include/Convolution/Convolution.h" #include "../../include/MinMaxDetector/MinMaxDetector.h" #include "../../include/TopologicalErosion/TopologicalErosion.h" #include "../../include/Mandelbrot/Mandelbrot.h" #include <stdexcept> #include <stdio.h> int main(int argc, char* argv[]) { try { const bool cbRunOldTests = false; const bool cbRunNewTests = true; // Running old tests if (cbRunOldTests) { MemoryThroughput::Run(); // Pixel-wise operations ImageAdd::Run(); NormalizedGradient::Run(); // Kernel operations for (unsigned int uiKernelSize = 3; uiKernelSize <= 9; uiKernelSize += 2) { Convolution::Run(uiKernelSize); } for (unsigned int uiKernelSize = 3; uiKernelSize <= 9; uiKernelSize += 2) { BubbleSortMedian::Run(uiKernelSize); } for (unsigned int uiKernelSize = 3; uiKernelSize <= 9; uiKernelSize += 2) { BubbleSortMedianOptimized::Run(uiKernelSize); } for (unsigned int uiKernelSize = 3; uiKernelSize <= 9; uiKernelSize += 2) { MinMaxDetector::Run( uiKernelSize ); } for (unsigned int uiKernelSize = 3; uiKernelSize <= 9; uiKernelSize += 2) { TopologicalErosion::Run(uiKernelSize); } } // Running new tests if (cbRunNewTests) { Mandelbrot::Run(); } } catch (std::exception &e) { printf( "\n\nERROR: %s\n\n", e.what() ); } return 0; }
true
c6d7e93f4d20c6820bbd8ee03a881392a2b74c0c
C++
enihsyou/Data-structures-Exercises
/No3/BinaryTree.h
UTF-8
7,280
3.40625
3
[]
no_license
#pragma once #include <memory> #include <ostream> #include <functional> struct TreeNode; class BinaryTree; typedef std::shared_ptr<TreeNode> TreeNodePtr; namespace { struct AsciiNode; typedef std::shared_ptr<AsciiNode> AsciiNodePtr; /** * \brief 为了输出二叉树的帮助类,保存了节点的左右支,与父节点的边长、方向,节点深度,字符标签数据 */ struct AsciiNode { AsciiNodePtr left = nullptr, right = nullptr; //左右支 int edgeLength; int height; int labelLength; int parentDirection; std::string label; }; struct AsciiTree { void print_ascii_tree(const BinaryTree &t); private: static const int MAX_HEIGHT = 30; // 最大打印高度 static const int INF = 1 << 20; static const int GAP = 2; // 同级两个节点之间最小距离 int leftProfile_[MAX_HEIGHT] = {0}; //左支 层 int rightProfile_[MAX_HEIGHT] = {0}; //右支 层 AsciiNodePtr root_; AsciiNodePtr buildTree(const BinaryTree &tree); AsciiNodePtr buildTreeRecursively(const TreeNodePtr t_node) const; /** * \brief 计算左支的偏离度 * \param t_node 处理的节点 * \param x 横坐标位置 * \param y 纵坐标,第y层 */ void computeLeftProfile(const AsciiNodePtr t_node, const int x, const int y); /** * \brief 计算右支的偏离度 * \param t_node 处理的节点 * \param x 横坐标位置 * \param y 纵坐标,第y层 */ void computeRightProfile(const AsciiNodePtr t_node, const int x, const int y); /** * \brief 递归计算节点与父节点之间的边长 * \param t_node 要计算的节点 */ void computeEdgeLengths(const AsciiNodePtr t_node); /** * \brief 分三段打印一个节点,第一阶段level==0,在居中的位置输出标签字符串。 第二阶段,判断是否存在左右支,输出斜杠 第三阶段,判断连接边是否结束,没有则继续打印边,结束则递归打印子节点 * \param node 树节点 * \param x 一行中的坐标,可能为负数 * \param level 当前打印的层级,使用引用,跨函数修改值 */ static void printLevel(const AsciiNodePtr node, const int x, const int level, int &print_next); }; } /** * \brief 二叉树的节点类 */ struct TreeNode { TreeNodePtr left_ = nullptr, right_ = nullptr; // 左右支 int key_; // 键 int value_ = 0; // 值 unsigned size_ = 1U; // 子树下有多少元素,包括自身 explicit TreeNode(const int key, const int value = 0, const unsigned size = 1U); /** * \brief 递归计算 以指定节点为根的二叉树 节点个数 * \return 该节点的子元素个数,包括本身 */ unsigned reSumSubSize(); void swapChildren(); void preOrderRecursiveTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void inOrderRecursiveTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void postOrderRecursiveTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void preOrderIterativeTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void inOrderIterativeTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void postOrderIterativeTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void levelOrderBFSTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; std::string toString() const; friend std::ostream &operator<<(std::ostream &os, const TreeNode &obj); }; /** * \brief 二叉树,实际上是二叉搜索树 */ class BinaryTree { TreeNodePtr root_ = nullptr; TreeNodePtr put(TreeNodePtr node, const int key, const int value) const; TreeNodePtr remove(TreeNodePtr node, const int key) const; TreeNodePtr min(TreeNodePtr node) const; TreeNodePtr max(TreeNodePtr node) const; TreeNodePtr deleteMin(TreeNodePtr node) const; TreeNodePtr deleteMax(TreeNodePtr node) const; public: /** * \brief 创建一棵空树 */ BinaryTree() = default; /** * \brief 由给定的键值对生成带有根节点的二叉树 * \param rootKey 根节点的键 * \param rootValue 根节点的值 */ BinaryTree(const int rootKey, const int rootValue); virtual ~BinaryTree(); /** * \brief 根据键获取对应的值,会抛出std::range_error * \param key 搜索的键 * \return 对应键的值,如果不存在则抛出错误 */ int get(const int key) const; /** * \brief 根据给定的键判断是否存在键值对在树中,递归搜索 * \param key 搜索的键 * \return 树中是否包含当前键的元素• */ bool contain(const int key) const noexcept; /** * \brief 根据给定的键值对插入到树中,如果原先不存在该键 则创建一个新的节点;否则替换原先的值 * \param key 要插入的键 * \param value 对应键的要插入的值 * \return 该键所在的节点 */ const TreeNode &put(const int key, const int value = 0); /** * \brief 删除指定键的元素,操作之后依然保持二叉树性质,如果键不在树中,则抛出std::range_error * \param key 指定删除的键 * \return 删除键的值 */ int remove(const int key); /** * \brief 判断是否是空树 * \return 树为空则返回true */ bool emptyQ() const noexcept; /** * \brief 删除最小元素,树为空会抛出std::underflow_error */ void deleteMin(); /** * \brief 删除最大元素,树为空会抛出std::underflow_error */ void deleteMax(); /** * \brief 寻找全树的最小节点 * \return 最小节点的引用,不允许修改 */ const TreeNode &min() const; /** * \brief 寻找全树的最大节点 * \return 最大节点的引用 ,不允许修改 */ const TreeNode &max() const; /** * \brief 通过递归方式,统计子叶个数,就是没有子节点的节点 * \return 子叶个数 */ unsigned leavesCount() const; /** * \brief 交换两个子元素,递归的方式,可以使用下面的通用方法实现 */ void swapChildren() const; /** * \brief 打印出来,树状图的方式 Ascii */ void print() const; void preOrderRecursiveTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void inOrderRecursiveTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void postOrderRecursiveTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void preOrderIterativeTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void inOrderIterativeTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void postOrderIterativeTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; void levelOrderBFSTraverse(const std::function<void(const TreeNode &)> &do_on_node) const; const TreeNodePtr &root() const { return root_; } friend std::ostream &operator<<(std::ostream &os, const BinaryTree &obj); };
true
07651e340a9706ebb44487f40e4fbd7ba16b081b
C++
zv-proger/ol_programms
/acmp/0280.cpp
WINDOWS-1251
456
2.5625
3
[]
no_license
/* : (zv.proger@yandex.ru) 0280 acmp.ru */ #include<bits/stdc++.h> using namespace std; using ll = long long; int main() { ll x; cin >> x; map<ll, int> divs; for (int i = 2; i <= x; i++) { if (x % i == 0) { x /= i; divs[i--]++; } } ll ans = 1; for (auto &p: divs) ans *= p.second; cout << ans; }
true
b429acacd8d45ef0a25fef278ec9e6536ed1a7b5
C++
Twinparadox/AlgorithmProblem
/Baekjoon/11401.cpp
UTF-8
578
3.015625
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; const long long MOD = 1000000007; long long power(long long x, long long n) { long long ans = 1; while (n > 0) { if (n % 2 == 1) ans = (ans * x) % MOD; x = (x * x) % MOD; n /= 2; } return ans; } long long fact(long long n) { long long ans = 1; for (long long i = 2; i <= n; i++) ans = (ans * i) % MOD; return ans; } int main(void) { long long N, K; cin >> N >> K; long long a = fact(N); long long b = fact(K); long long c = fact(N - K); cout << ((a % MOD * power(b, MOD - 2)) % MOD) * power(c, MOD - 2) % MOD; }
true
c8f2f9f9f9796f45cc1350c84ca2b5413d605ffd
C++
ThreeInches/Total_review
/总复习/BinarySortTree/BinarySortTree/BinarySortTree.cpp
UTF-8
284
2.578125
3
[]
no_license
#include <iostream> #include "BinarySortTree.h" using namespace std; int main() { gwp::BSTree<int> bst; bst.Insert(5); bst.Insert(3); bst.Insert(8); bst.Insert(6); bst.Insert(4); bst.Insert(7); bst.Insert(1); bst.Insert(2); bst.Erase(2); system("pause"); return 0; }
true
fe11d0cbf42c3f547a3dd3013707ad3f2f039a21
C++
WookieHere/AI_Project_ECE57000
/AI_Test_Project/AI_Test_Project/Output_Handler/Player_Training.cpp
UTF-8
7,507
2.6875
3
[]
no_license
// // Player_Training.cpp // AI_Test_Project // // Created by Luke Nasby on 10/31/20. // Copyright © 2020 Luke Nasby. All rights reserved. // #include "Player.hpp" #include "Output_Handler.hpp" #include "Random_Generator.hpp" #include "Player_Training.hpp" #define GENE_MAX_NEGATIVE -10000 #define GENE_MAX_POSITIVE 10000 #define GENE_COUNT 9 void Output_handler::breedPlayers() { Player_node* traversal_node = this->player_roster->next_node; Player_node* trail = this->player_roster->next_node; int new_size = 0; /* Player_node* temp = this->post_breeding_players->next_node; Player_node* trail = this->post_breeding_players->next_node; for(int l = 0; l < this->post_breeding_players->length; l++) { trail = temp; temp = temp->next_node; trail->ranked_player->~Player(); trail->ranked_player = NULL; free(trail); trail = NULL; }//clears the post breeding players */ this->post_breeding_players->next_node = NULL; this->post_breeding_players->length = 0; for(int i = 0; i < this->player_roster->length; i++) { if((this->player_roster->length - i) > getRandom2RN(0, this->player_roster->length)) { this->addToRoster(traversal_node->ranked_player, this->post_breeding_players); new_size++; //this will breed a new player on a 2RN of it's position trail = traversal_node; traversal_node = traversal_node->next_node; }else { //player was not bred traversal_node->ranked_player->~Player(); traversal_node->ranked_player = NULL; trail->next_node = traversal_node->next_node; free(traversal_node); traversal_node = NULL; //this->player_roster->length--; traversal_node = trail->next_node; } }//post breeding players is now partially filled traversal_node = this->player_roster->next_node; Player* new_player = NULL; double* rand_array = NULL; for(int k = 0; k < this->player_roster->length - new_size; k++) { new_player = new Player(traversal_node->ranked_player->Input_Console, this); rand_array = getRandomDoubleArray(GENE_MAX_NEGATIVE, GENE_MAX_POSITIVE, GENE_COUNT); new_player->manGenetics(rand_array); this->addToRoster(new_player, this->post_breeding_players); //this pads the end of the roster with new players } traversal_node = this->post_breeding_players->next_node; for(int j = 0; j < this->post_breeding_players->length; j += 2) { this->crossOver(traversal_node->ranked_player, traversal_node->next_node->ranked_player); if(getRandomInt(0, 100) > 95) { this->mutate(traversal_node->ranked_player); } if(getRandomInt(0, 100) > 95) { this->mutate(traversal_node->next_node->ranked_player); }//these mutate a player 5% of the time traversal_node = traversal_node->next_node->next_node; } /*if(this->player_roster->length > this->User_config->generation_size || this->post_breeding_players->length > this->User_config->generation_size) { printf("ERROR: roster size increased mid loop\n"); }*/ this->player_roster->next_node = NULL; this->player_roster->length = 0; }//this function generates the post_breeding_players list void Output_handler::crossOver(Player* A, Player* B) { Genetics gene_A = A->getGenetics(); Genetics gene_B = B->getGenetics(); int* combination_sequence = getRandomMatchup(0, GENE_COUNT); int genes_to_switch = getRandomInt(0, GENE_COUNT); int temp = 0; for(int i = 0; i < genes_to_switch; i++) { switch (combination_sequence[i]) { case 0: temp = gene_A.time_weight; gene_A.time_weight = gene_B.time_weight; gene_B.time_weight = temp; break; case 1: temp = gene_A.travel_weight; gene_A.travel_weight = gene_B.travel_weight; gene_B.travel_weight = temp; break; case 2: temp = gene_A.distance_weight; gene_A.distance_weight = gene_B.distance_weight; gene_B.distance_weight = temp; break; case 3: temp = gene_A.work_weight; gene_A.work_weight = gene_B.work_weight; gene_B.work_weight = temp; break; case 4: temp = gene_A.turning_rate; gene_A.turning_rate = gene_B.turning_rate; gene_B.turning_rate = temp; break; case 5: temp = gene_A.key_2; gene_A.key_2 = gene_B.key_2; gene_B.key_2 = temp; break; case 6: temp = gene_A.distance_2; gene_A.distance_2 = gene_B.distance_2; gene_B.distance_2 = temp; break; case 7: temp = gene_A.velocity_2; gene_A.velocity_2 = gene_B.velocity_2; gene_B.velocity_2 = temp; break; case 8: temp = gene_A.layer_2; gene_A.layer_2 = gene_B.layer_2; gene_B.layer_2 = temp; break; default: break; }//sadly there is not a better way to do that. } A->replaceGenes(gene_A); B->replaceGenes(gene_B); //this gets the sequence of genes that are flipped //only a fraction of the top of the array contain the indicies to be flipped } void Output_handler::mutate(Player* player) { Genetics gene_A = player->getGenetics(); int* combination_sequence = getRandomMatchup(0, GENE_COUNT); int genes_to_switch = getRandomInt(0, GENE_COUNT); double* new_genes = getRandomDoubleArray(GENE_MAX_NEGATIVE, GENE_MAX_POSITIVE, genes_to_switch); for(int i = 0; i < genes_to_switch; i++) { switch (combination_sequence[i]) { case 0: gene_A.time_weight = new_genes[i]; break; case 1: gene_A.travel_weight = new_genes[i]; break; case 2: gene_A.distance_weight = new_genes[i]; break; case 3: gene_A.work_weight = new_genes[i]; break; case 4: gene_A.turning_rate = new_genes[i]; break; case 5: gene_A.key_2 = new_genes[i]; break; case 6: gene_A.distance_2 = new_genes[i]; break; case 7: gene_A.velocity_2 = new_genes[i]; break; case 8: gene_A.layer_2 = new_genes[i]; break; default: break; }//sadly there is not a better way to do that. } player->replaceGenes(gene_A); }
true
e0fcae72bc755203fef2f886d186b99445b85c6a
C++
charles-pku-2013/CodeRes_Cpp
/BazelProject/examples/gflags_demo.cc
UTF-8
3,326
2.578125
3
[]
no_license
/* * Tutorial: https://gflags.github.io/gflags/#validate * gflags_demo.cpp * /tmp/test -nobig_menu --languages=Chinese,English,Japanese */ /* * Usage: * 不可以出现未定义的选项参数 * app_containing_foo --nobig_menu -languages="chinese,japanese,korean" ... * app_containing_foo --languages="chinese,japanese,korean" * app_containing_foo -languages="chinese,japanese,korean" * app_containing_foo --languages "chinese,japanese,korean" * app_containing_foo -languages "chinese,japanese,korean" * app_containing_foo --big_menu * app_containing_foo --nobig_menu * app_containing_foo --big_menu=true * app_containing_foo --big_menu=false */ /* * types: * DEFINE_bool: boolean * DEFINE_int32: 32-bit integer * DEFINE_int64: 64-bit integer * DEFINE_uint64: unsigned 64-bit integer * DEFINE_double: double * DEFINE_string: C++ string */ /* * NOTE!!! 关于 -flagfile * 命令行和flagfile不存在优先级先后,看参数中先指定谁就先解析谁 */ #include <iostream> #include <cstdio> #include <vector> #include <string> #include <cstring> #include <gflags/gflags.h> #define SPACES " \t\f\r\v\n" using namespace std; // 用于声明定义分离 /* * DECLARE_bool(big_menu); * DECLARE_string(languages); */ DEFINE_bool(big_menu, true, "Include 'advanced' options in the menu listing"); DEFINE_string(languages, "english,french,german", "comma-separated list of languages to offer in the 'lang' menu"); DEFINE_int32(port, 8888, "What port to listen on"); namespace { // 验证函数,看来至少要每种类型一个验证 bool ValidatePort(const char* flagname, gflags::int32 value) { cout << "ArgValidator() flagname = " << flagname << " value = " << value << endl; if (value > 1024 && value < 32768) // value is ok return true; printf("Invalid value for --%s: %d\n", flagname, (int)value); return false; } // 定义port_dummy为了保证RegisterFlagValidator先于main函数执行 const bool port_dummy = gflags::RegisterFlagValidator(&FLAGS_port, &ValidatePort); } // namespace void test1( int argc, char **argv ) { /* * error: ‘namespace’ definition is not allowed here * 看来不能在函数中定义 */ // DEFINE_int32(port, 0, "port arg in a function."); cout << FLAGS_port << endl; } int main( int argc, char **argv ) { int idx = gflags::ParseCommandLineFlags(&argc, &argv, true); // 未被gflags识别的参数 for (; idx < argc; ++idx) { cout << argv[idx] << endl; } cout << FLAGS_big_menu << endl; cout << FLAGS_languages << endl; cout << FLAGS_port << endl; // string cmd = "test -port 1234"; // vector<char*> opts; // char *p = const_cast<char*>(cmd.c_str()); // for (p = strtok(p, SPACES); p; p = strtok(NULL, SPACES)) // opts.push_back(p); // test1(opts.size(), &opts[0]); return 0; } #if 0 DEFINE_string(server, "", "server addr ip:port"); // lambda 函数参数检查 namespace { bool _check_server = gflags::RegisterFlagValidator(&FLAGS_server, [](const char* flagname, const std::string& value){ if (value.empty()) { //!!! NOTE here cannot use FLAGS_server std::cerr << flagname << " not set" << std::endl; return false; } return true; }); } // namespace #endif
true
5bb7d7814543d1e9f065ce4f9fdaaddc0aba96a1
C++
dashagriiva/SPOJ-Submissions
/Classical/STPAR.cpp
UTF-8
902
3.21875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <stack> using namespace std; int main() { int n; while(cin>>n && n) { vector<int> S(n); for(int i = 0; i < n; i++) cin>>S[i]; stack<int> Stack; int curr = 1; int index = 0; bool res = true; while(index < n && curr < n) { if (Stack.empty() == false && Stack.top() == curr) { Stack.pop(); curr++; } else if(S[index] == curr) { index++; curr++; } else if (S[index] > curr) { Stack.push(S[index]); index++; } else { if(Stack.top() != curr) { res = false; break; } else { Stack.pop(); curr++; } } } if(res) { while(Stack.empty() == false && Stack.top() == curr) { Stack.pop(); curr++; } } if(Stack.empty()) cout<<"yes"<<endl; else cout<<"no"<<endl; } }
true
caaf2450cf8e641fc304e3f727781e97ce660b09
C++
rzel/SimpleDualTest
/native_app/src/Application.h
UTF-8
3,848
3.015625
3
[]
no_license
/* * Application.h * * Created on: Nov 6, 2012 * Author: dpajak */ #ifndef APPLICATION_H_ #define APPLICATION_H_ #include "ManagedPtr.h" #include "System.h" namespace System { class Application: public ManagedAbstractObject { public: Application(void) { } ~Application(void) { } /** * Key up event handler. * @param button - id of the button */ virtual void keyUp(System::Key button) { (void)button; } /** * Key down event handler. * @param button - id of the button */ virtual void keyDown(System::Key button) { (void)button; } /** * Touch move event handler. * @param id - id of the event * @param x - x coordinate of the event * @param y - y coordinate of the event */ virtual void touchMove(int id, int x, int y) { (void)id; (void)x; (void)y; } /** * Touch down event handler. * @param id - id of the event * @param x - x coordinate of the event * @param y - y coordinate of the event */ virtual void touchDown(int id, int x, int y) { (void)id; (void)x; (void)y; } /** * Touch up event handler. * @param id - id of the event * @param x - x coordinate of the event * @param y - y coordinate of the event */ virtual void touchUp(int id, int x, int y) { (void)id; (void)x; (void)y; } /** * Touch cancel event handler. * @param id - id of the event * @param x - x coordinate of the event * @param y - y coordinate of the event */ virtual void touchCancel(int id, int x, int y) { (void)id; (void)x; (void)y; } /** * Called after applet construction. This function can run initial * conditional code such as resource allocation and data loading. If * this stage fails the function should return false, so that the * framework can shutdown the application gracefully. * @return true if applet initialization succeeded, false otherwise. * If false is returned, the application will quit immediately. */ virtual bool init(void) = 0; /** * Applet update function. Called for every received event. This * function might be called from a different thread than a render * thread! In consequence, it might be invoked more or less frequent * than <code>draw()</code>. Do not run any rendering code code. * The code here should finish execution as fast as possible, in * order to enable the OS to process next system messages. * Warning: update will be called before init * @return true if the applet wants to quit, false if it plans * to continue running. */ virtual bool update(void) = 0; /** * Applet draw function. Called every frame. */ virtual void draw(void) = 0; /** * Called upon applet termination (prior destructor). * Use this to free used resources, deallocate buffers, etc. */ virtual void exit(void) { } /** * Called when application is about to go into suspend state. * Use this function to stop background threads, and free all * intermediate resources. */ virtual void suspend(void) { } /** * Called when application is returning from the suspend state. */ virtual void resume(void) { } /** * Application entry-point. This function should return an instance of * <code>System::Application</code> that the framework will later on * pass events and control to. * @return instance of <code>System::Application</code> */ static managed_ptr<Application> AppInit(void); protected: }; } #endif /* APPLICATION_H_ */
true
c783bdab38b76f167c22bc2c441277e75c547151
C++
1564047446/byt
/test164.cpp
UTF-8
1,198
2.515625
3
[]
no_license
#include <stdio.h> int main() { int n; scanf("%d", &n); if (n < 10 || n > 30) { printf("0\n"); return 0; } int temp[10000][10]; int ans = 0; for (int a1 = 1; a1 <= 3; a1++) { for (int a2 = 1; a2 <= 3; a2++) { for (int a3 = 1; a3 <= 3; a3++) { for (int a4 = 1; a4 <= 3; a4++) { for (int a5 = 1; a5 <= 3; a5++) { for (int a6 = 1; a6 <= 3; a6++) { for (int a7 = 1; a7 <= 3; a7++) { for (int a8 = 1; a8 <= 3; a8++) { for (int a9 = 1; a9 <= 3; a9++) { for (int a10 = 1; a10 <= 3; a10++) { if (a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 == n) { temp[ans][0] = a1, temp[ans][1] = a2; temp[ans][2] = a3, temp[ans][3] = a4; temp[ans][4] = a5, temp[ans][5] = a6; temp[ans][6] = a7, temp[ans][7] = a8; temp[ans][8] = a9, temp[ans][9] = a10; ++ans; } } } } } } } } } } } printf("%d\n", ans); for (int i = 0; i < ans; i++) { for (int j = 0; j < 10; j++) { if (j == 0) { printf("%d", temp[i][j]); } else { printf(" %d", temp[i][j]); } } printf("\n"); } return 0; }
true
da91383bc82cd319b7c1c4fa30daf37d8ad02fad
C++
leonoronhas/cs165
/myCheck03a.cpp
UTF-8
1,819
3.5625
4
[]
no_license
/*********************************************************************** * Program: * CheckPoint 03a, Exceptions * Brother Comeau, CS165 * Author: * Leonardo Santos * Summary: * Enter a brief description of your program here! Please note that if * you do not take the time to fill out this block, YOU WILL LOSE POINTS. * Before you begin working, estimate the time you think it will * take you to do the assignment and include it in this header block. * Before you submit the assignment include the actual time it took. * * Estimated: 0.0 hrs * Actual: 0.0 hrs * Please describe briefly what was the most difficult part. ************************************************************************/ #include <iostream> using namespace std; /********************************************************************** * Add text here to describe what the function "main" does. Also don't forget * to fill this out with meaningful text or YOU WILL LOSE POINTS. ***********************************************************************/ int prompt() throw (string) { int number = -1; cout << "Enter a number: "; cin >> number; while(cin.fail()) { cin.clear(); cin.ignore(256, '\n'); cout << "Please enter a number and not a letter" << endl; } if (number < 0) throw string("The number cannot be negative."); if (number > 100) throw string("The number cannot be greater than 100."); if (number % 2 != 0) throw string("The number cannot be odd."); return number; } int main() { int number = 0; try { number = prompt(); cout << "The number is " << number << "." << endl; } catch (string errorMessage) { cout << "Error: " << errorMessage << endl; } return 0; }
true
001bbbafbbfac78c735abc64b145ec0a3348279f
C++
cogu/qt-apx
/remotefile/inc/qrmf_filemap2.h
UTF-8
1,647
2.609375
3
[ "MIT" ]
permissive
/** QT adaptation of RemoteFile Layer */ #ifndef QRMF_FILEMAP2_H #define QRMF_FILEMAP2_H #include <QString> #include <QtGlobal> #include <QList> #include "qrmf_file.h" namespace RemoteFile { /** * @brief Abstract base class for RemoteFile::FileMap2. Concrete classes needs to implement the assignFileAddressDefault method */ class FileMap2 { public: FileMap2():mFiles(),mIterator(),mLastFileIndex(-1) {} virtual ~FileMap2() {clear();} virtual bool insert(RemoteFile::File *file); virtual bool remove(RemoteFile::File *file); void clear(); int size() {return mFiles.size();} bool assignFileAddress(RemoteFile::File *file, quint32 startAddress, quint32 endAddress, quint32 addressBoundary); void iterInit(void); RemoteFile::File *next(); RemoteFile::File *findByAddress(quint32 address); RemoteFile::File *findByName(const char *name); protected: virtual bool assignFileAddressDefault(RemoteFile::File *file) = 0; bool verifyFileAddress(RemoteFile::File*, quint32 startAddress, quint32 endAddress); void insertDefault(RemoteFile::File *file); protected: QList<RemoteFile::File*> mFiles; //weak or strong reference to File*. strength of reference is decided by property typedef QList<RemoteFile::File*>::iterator ListIterator; ListIterator mIterator; int mLastFileIndex; }; class FileMapDefault2: public FileMap2 { public: FileMapDefault2():mAddressBoundary(4096){} ~FileMapDefault2(){} protected: bool assignFileAddressDefault(RemoteFile::File *file); protected: quint32 mAddressBoundary; }; } #endif // QRMF_FILEMAP2_H
true
587fb80762b2d6f7a814ae481fbb5d89ef783962
C++
mdzobayer/Problem-Solving
/Uva/Uva - 10905 Children's Game.cpp
UTF-8
2,358
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; /// Read & Write to File Short-Cut #define fRead(x) freopen(x, "r", stdin) #define fWrite(x) freopen(x, "w", stdout) /// Data type Short-Cut #define LLI long long int #define ULL unsigned long long int #define ff first #define ss second #define mk make_pair #define phb push_back #define ppb pop_back #define phf push_front #define ppf pop_front /// C Style Input Short-Cut #define scan(a) scanf("%d", &a); #define scan2(a, b) scanf("%d %d", &a, &b); #define scan3(a, b, c) scanf("%d %d %d", &a, &b, &c); #define scan4(a, b, c, d) scanf("%d %d %d %d", &a, &b, &c, &d); /// Utility #define SQR(x) ((x) * (x)) #define PI acos(-1.0) /// Fast Read and de-active buffer flash for C++ #define FastRead std::cin.sync_with_stdio(false);std::cin.tie(nullptr); ///======================== Let's GO ======================== struct number { string str; number() { str = ""; } number(string s) { str = s; } char AT(size_t a) { return str[a]; } void operator = ( number n) { this->str = n.str; } size_t size() { return str.size(); } bool operator < ( number x) { if (this->str == x.str) return false; size_t n = min(this->size(), x.size()); for (size_t i = 0; i < n; ++i) { if (this->AT(i) >= x.AT(i)) return true; else if(x.AT(i) < this->AT(i)) return false; } if (this->size() == n) return true; else return false; } }; int main() { FastRead fRead("in.txt"); //fWrite("out.txt"); vector <number> nt; number temp; /* temp.str = "123"; nt.phb(temp); temp.str = "124"; nt.phb(temp); temp.str = "56"; nt.phb(temp); temp.str = "90"; nt.phb(temp); temp.str = "9"; nt.phb(temp); sort(nt.begin(), nt.end()); for (int i = 0; i < nt.size(); ++i) { cout << nt[i].str << " "; } */ string s; LLI n, i; while(cin >> n) { if (n == 0) break; nt.clear(); cin.ignore(); for (i = 0; i < n; ++i) { cin >> s; temp.str = s; nt.phb(temp); } sort(nt.begin(), nt.end()); for (i = 0; i < nt.size(); ++i) { cout << nt[i].str; } cout << endl; } return (0); }
true
8a7e361052e2fe36b65724fe06d04b9cf164b7a7
C++
umaidansari12/Assignments-H-JHU
/1_tree/sum_root_to_leaf_numbers.cpp
UTF-8
406
2.90625
3
[]
no_license
class Solution { public: int solve(TreeNode* root, int s) { if (!root) return 0; if (!root->left and !root->right) return s * 10 + root->val; return solve(root->left, s * 10 + root->val) + solve(root->right, s * 10 + (root->val)); } int sumNumbers(TreeNode* root) { vector<int> r; return solve(root, 0); } };
true
db10caf76b1af6e40de49a1d819de2037f7e041b
C++
Justinianus2001/ProjectEuler
/old_version/P082.cpp
UTF-8
1,207
2.9375
3
[]
no_license
/* * Copyright (c) Justinianus * https://github.com/Justinianus2001/ProjectEuler */ #include "library.hpp" int main(int argc, char** argv){ freopen("P082.txt", "r", stdin); vector<long long> v[500]; long long cache[500][500], res = LLONG_MAX; long long len = 0, width = 0; string str; while(cin >> str){ vector<string> token = tokenize(str, ","); width = max(width, (long long)token.size()); for(string num: token) v[len].push_back(stoi(num)); len ++; } for(long long col = 0; col < width; col ++){ for(long long row = 0; row < len; row ++){ cache[row][col] = v[row][col]; if(col) cache[row][col] += cache[row][col - 1]; } for(long long rowDown = 1; rowDown < len; rowDown ++) cache[rowDown][col] = min(cache[rowDown][col], cache[rowDown - 1][col] + v[rowDown][col]); for(long long rowUp = len - 2; rowUp >= 0; rowUp --) cache[rowUp][col] = min(cache[rowUp][col], cache[rowUp + 1][col] + v[rowUp][col]); } for(long long row = 0; row < len; row ++) res = min(res, cache[row][width - 1]); cout << res; return EXIT_SUCCESS; } // Title: Problem 82 - Path sum: three ways // URL: https://projecteuler.net/problem=82 // Input: P082.txt // Output: 260324 // Lang: C++
true
7d2cfae8f5db87709bb089d45ca66904479d61d9
C++
svlpsu/crete-release
/lib/include/crete/elf_reader.h
UTF-8
2,090
2.8125
3
[ "BSD-2-Clause-Views" ]
permissive
#ifndef ELF_READER_H #define ELF_READER_H #include <gelf.h> #include <string> #include <vector> #include <stdint.h> #include <boost/filesystem/path.hpp> namespace crete { struct Entry { Entry() : addr(0), size(0) {} Entry(uintptr_t address, uintptr_t e_size) : addr(address), size(e_size) {} Entry(uintptr_t address, uintptr_t e_size, const std::string& e_name) : addr(address), size(e_size), name(e_name) {} template <class Archive> void serialize(Archive& ar, const unsigned int version) { (void)version; ar & addr; ar & size; ar & name; } uintptr_t addr; uintptr_t size; std::string name; }; bool operator<(const Entry& lhs, const Entry& rhs); class ELFReader { public: typedef std::vector<Entry> Entries; // TODO: should be a set that uses address range of uniqueness comparison (ordered according to address). public: ELFReader(const boost::filesystem::path& file); ~ELFReader(); int get_class(); // Architecture (32/64). Compare with ELFCLASS32/64. Elf64_Half get_type(); // Type of file. Compare with ET_* - ET_REL, ET_EXEC, ET_DYN, ET_CORE. 1, 2, 3, 4 specify relocatable, executable, shared, or core, respectively. Elf64_Half get_machine(); // Instruction set architecture. Compare with EM_* - EM_386, EM_X86_64, etc. Elf64_Addr get_entry_address(); // Starting address. e.g., 0x0804800 Entry get_section_entry(const std::string& section, const std::string& entry); // Returns Entry::addr = 0 if not found Entries get_section_entries(const std::string &section); Entry get_section(const std::string& section); std::vector<uint8_t> get_section_data(const std::string& section); protected: void open_file(const boost::filesystem::path& file); void init_elf(); void proc_header(); void proc_sections(); private: int fd_; Elf* elf_; Elf_Kind ekind_; GElf_Ehdr eheader_; std::vector<std::pair<Elf_Scn*, GElf_Shdr> > section_headers_; size_t section_header_str_idx_; }; } // namespace crete #endif // ELF_READER_H
true
6c758b76363641d419b0baefb40d8782c64362f9
C++
ykclin/Projects
/C++/networkfunction/networkfunction/function/function.cpp
UTF-8
393
2.53125
3
[]
no_license
#include "function.h" void CFunction::testspecialcharacter() { string aa = "aca\1hwb"; int m = 92; aa += m; unsigned int ia = aa[3]; int bb3 = aa.find(m); cout<<aa<<endl; aa = aa.replace(aa.find(m),1,"v"); cout<<aa<<endl; } void CFunction::testMaxNum() { int iInt = 0x7fffffff; unsigned int uInt = 0xffffffff; cout<<iInt<<endl; cout<<uInt<<endl; iInt+=1; cout<<iInt<<endl; }
true
06b2ee16da38ada4aeb299e0edd7dc8f857c8d8e
C++
vipin54/C-DSA
/circular_linklist.cpp
UTF-8
630
3.515625
4
[]
no_license
#include <stdio.h> #include <iostream> #include <array> using namespace std; struct node { public: int data; node *next; }*head=NULL; void create(int A[],int n){ int i; struct node *t,*last; head=new node; head->data=A[0]; head->next=head; last=head; for(i=1;i<n;i++){ t=new node; t->data=A[i]; t->next=last->next; last->next=t; last=t; } } void display(struct node *h){ do{ cout<<h->data<<" "; h=h->next; }while(head!=h); cout<<"\n"; } int main(){ int A[]={1,2,3,4,5}; create(A,5); display(head); }
true
05570934924ff8edb460f663a8234982647d1d4a
C++
isaiahIM/C_language_study
/graphic/square/main.cpp
UTF-8
1,697
3.03125
3
[]
no_license
#include <stdio.h> #include <iostream> #include <graphics.h> #include <math.h> #define PI 3.14159 #define SQUARE_SIZE 150 typedef struct _POSITION { int x; int y; } Pos; void SetPos(Pos *pos, int x, int y); void Sqare(int square[], Pos StartPos, int r, float Degree); float ToRadian(float Degree); int main( ) { initwindow( 700 , 500 , "WinBGIm" ); int r=SQUARE_SIZE, first=0, second=30-first, third=60-first, flag; int sqare[10]; Pos StartPos; SetPos(&StartPos, 300, 200); while(1) { if(r==SQUARE_SIZE) { flag=-1; } if(r==0) { flag=1; } cleardevice();// clear screen Sqare(sqare, StartPos, r, first); drawpoly(5,sqare); Sqare(sqare, StartPos, r, second); drawpoly(5,sqare); Sqare(sqare, StartPos, r, third); drawpoly(5,sqare); first+=1; second+=1; third+=1; r+=flag; Sleep(1); } getch(); closegraph( ); return( 0 ); } void SetPos(Pos *pos, int x, int y) { pos->x=x; pos->y=y; } void Sqare(int square[], Pos StartPos, int r, float Degree) { Pos pos; float degree=Degree-90; int i; for(i=0; i<10; i+=2) { degree+=90; Degree=ToRadian(degree); SetPos(&pos, StartPos.x + (int)(r*(cos(Degree))), StartPos.y + (int)(r*(sin(Degree)))); square[i]=pos.x; square[i+1]=pos.y; line(StartPos.x, StartPos.y, square[i], square[i+1]); } } float ToRadian(float Degree) { return (Degree*PI)/180; }
true
eebf8ce500a8ee85547d54d2e6f8cf9b43dd610c
C++
yaominzh/CodeLrn2019
/mooc43-bobo-algo/Play-with-Algorithms-master/09-Shortest-Path/Course Code (C++)/Chapter-09-Completed-Code/IndexMinHeap.h
UTF-8
4,182
3.734375
4
[ "Apache-2.0" ]
permissive
// // Created by liuyubobobo on 9/28/16. // #ifndef INC_03_IMPLEMENTATION_OF_DIJKSTRA_INDEXMINHEAP_H #define INC_03_IMPLEMENTATION_OF_DIJKSTRA_INDEXMINHEAP_H #include <iostream> #include <algorithm> #include <cassert> using namespace std; // 最小索引堆 template<typename Item> class IndexMinHeap{ private: Item *data; // 最小索引堆中的数据 int *indexes; // 最小索引堆中的索引, indexes[x] = i 表示索引i在x的位置 int *reverse; // 最小索引堆中的反向索引, reverse[i] = x 表示索引i在x的位置 int count; int capacity; // 索引堆中, 数据之间的比较根据data的大小进行比较, 但实际操作的是索引 void shiftUp( int k ){ while( k > 1 && data[indexes[k/2]] > data[indexes[k]] ){ swap( indexes[k/2] , indexes[k] ); reverse[indexes[k/2]] = k/2; reverse[indexes[k]] = k; k /= 2; } } // 索引堆中, 数据之间的比较根据data的大小进行比较, 但实际操作的是索引 void shiftDown( int k ){ while( 2*k <= count ){ int j = 2*k; if( j + 1 <= count && data[indexes[j]] > data[indexes[j+1]] ) j += 1; if( data[indexes[k]] <= data[indexes[j]] ) break; swap( indexes[k] , indexes[j] ); reverse[indexes[k]] = k; reverse[indexes[j]] = j; k = j; } } public: // 构造函数, 构造一个空的索引堆, 可容纳capacity个元素 IndexMinHeap(int capacity){ data = new Item[capacity+1]; indexes = new int[capacity+1]; reverse = new int[capacity+1]; for( int i = 0 ; i <= capacity ; i ++ ) reverse[i] = 0; count = 0; this->capacity = capacity; } ~IndexMinHeap(){ delete[] data; delete[] indexes; delete[] reverse; } // 返回索引堆中的元素个数 int size(){ return count; } // 返回一个布尔值, 表示索引堆中是否为空 bool isEmpty(){ return count == 0; } // 向最小索引堆中插入一个新的元素, 新元素的索引为i, 元素为item // 传入的i对用户而言,是从0索引的 void insert(int index, Item item){ assert( count + 1 <= capacity ); assert( index + 1 >= 1 && index + 1 <= capacity ); index += 1; data[index] = item; indexes[count+1] = index; reverse[index] = count+1; count++; shiftUp(count); } // 从最小索引堆中取出堆顶元素, 即索引堆中所存储的最小数据 Item extractMin(){ assert( count > 0 ); Item ret = data[indexes[1]]; swap( indexes[1] , indexes[count] ); reverse[indexes[count]] = 0; reverse[indexes[1]] = 1; count--; shiftDown(1); return ret; } // 从最小索引堆中取出堆顶元素的索引 int extractMinIndex(){ assert( count > 0 ); int ret = indexes[1] - 1; swap( indexes[1] , indexes[count] ); reverse[indexes[count]] = 0; reverse[indexes[1]] = 1; count--; shiftDown(1); return ret; } // 获取最小索引堆中的堆顶元素 Item getMin(){ assert( count > 0 ); return data[indexes[1]]; } // 获取最小索引堆中的堆顶元素的索引 int getMinIndex(){ assert( count > 0 ); return indexes[1]-1; } // 看索引i所在的位置是否存在元素 bool contain( int index ){ return reverse[index+1] != 0; } // 获取最小索引堆中索引为i的元素 Item getItem( int index ){ assert( contain(index) ); return data[index+1]; } // 将最小索引堆中索引为i的元素修改为newItem void change( int index , Item newItem ){ assert( contain(index) ); index += 1; data[index] = newItem; shiftUp( reverse[index] ); shiftDown( reverse[index] ); } }; #endif //INC_03_IMPLEMENTATION_OF_DIJKSTRA_INDEXMINHEAP_H
true
506d332d7e5ee549440f4b98651fedb85f8c591b
C++
Kanchii/Online_Judge_Problems
/Uri/1038.cpp
UTF-8
509
2.890625
3
[]
no_license
#include <iostream> using namespace std; int main() { int cod, quant; scanf("%d %d", &cod, &quant); if(cod == 1){ printf("Total: R$ %.2f\n", quant*4.00); } else if (cod == 2){ printf("Total: R$ %.2f\n", quant*4.50); } else if (cod == 3){ printf("Total: R$ %.2f\n", quant*5.00); } else if (cod == 4){ printf("Total: R$ %.2f\n", quant*2.00); } else if (cod == 5){ printf("Total: R$ %.2f\n", quant*1.50); } return 0; }
true
ba8936c9bdac5f1e7e21b24893a1e5ef98031483
C++
edict-game-program/shooting_game_1
/SystemForLearning0409/SystemForLearning/Game/Bullet.cpp
SHIFT_JIS
4,815
2.875
3
[]
no_license
#include "Bullet.h" #include <cmath> #include <Sprite.h> #include <Collision.h> #include "ShootingGame.h" #if COLLISION_VISIBLE #include <PrimitiveEdgeSprite.h> #endif using namespace core2d; // ----------------------------------------------------------------------- // e\NX // ----------------------------------------------------------------------- Bullet::Bullet(ShootingGame* manager) : GameObject(manager) , m_dirX(0.0f) , m_dirY(0.0f) , m_speed(0.0f) #if COLLISION_VISIBLE , m_collisionSprite(nullptr) #endif { } Bullet::~Bullet(void) { #if COLLISION_VISIBLE if (m_collisionSprite) { core2d::PrimitiveEdgeSprite::destroy(m_collisionSprite); } #endif } void Bullet::setDirection(float x, float y) { float length = sqrtf(x * x + y * y); if (length < FLT_EPSILON) { m_dirX = 0.0f; m_dirY = 0.0f; } else { m_dirX = x / length; m_dirY = y / length; } } void Bullet::setSpeed(float speed) { m_speed = speed; } // ----------------------------------------------------------------------- // vC[̒eNX // ----------------------------------------------------------------------- PlayerBullet::PlayerBullet(ShootingGame* manager) : Bullet(manager) , m_sprite(nullptr) , m_collision(nullptr) , m_damage(1) { } PlayerBullet::~PlayerBullet(void) { if (m_sprite) { Sprite::destroy(m_sprite); m_sprite = nullptr; } removeCollision(); if (m_collision) { delete m_collision; m_collision = nullptr; } } void PlayerBullet::update(void) { if (m_positionX < -10.0f || 650.f < m_positionX || m_positionY < -10.0f || 490.0f < m_positionY) { manager()->destroyGameObject(this); m_sprite->setActive(false); return; } m_positionX += m_dirX * m_speed; m_positionY += m_dirY * m_speed; m_sprite->setPosition(m_positionX, m_positionY); m_collision->x = m_positionX; m_collision->y = m_positionY; float rad = atan2f(m_dirY, m_dirX); m_sprite->setRotate(RAD_TO_DEG(rad)); #if COLLISION_VISIBLE m_collisionSprite->setPosition(m_positionX, m_positionY); m_collisionSprite->setActive(getCollisionVisible()); #endif } void PlayerBullet::onFirstUpdate() { m_sprite = new Sprite(ImagePlayerBullet2); m_sprite->setPriority(static_cast<unsigned int>(DrawPriority::Bullet)); m_sprite->setPosition(-100.0f, -100.0f); setDamage(m_damage); m_collision = new core2d::Collision::PointF(0, 0); addCollision(m_collision); #if COLLISION_VISIBLE m_collisionSprite = new core2d::BoxEdgeSprite(0.0f, 0.0f); m_collisionSprite->setPosition(-100, -100); m_collisionSprite->setColor(0.0f, 1.0f, 0.5f); #endif } void PlayerBullet::setDamage(int damage) { m_damage = damage; if(m_sprite) {//З͂オꍇɏe傫 float scale = static_cast<float>(m_damage); if (scale != 1.0f) { scale = 1.f + (scale * 0.2f); } m_sprite->setScale(scale, scale); } } int PlayerBullet::getDamage(void) { return m_damage; } // ----------------------------------------------------------------------- // G̒eNX // ----------------------------------------------------------------------- EnemyBullet::EnemyBullet(ShootingGame* manager, int imageId) : Bullet(manager) , m_sprite(nullptr) , m_collision(nullptr) , m_imageId(imageId) , m_spriteScaleX(1.0f) , m_spriteScaleY(1.0f) { } EnemyBullet::~EnemyBullet(void) { if (m_sprite) { Sprite::destroy(m_sprite); m_sprite = nullptr; } removeCollision(); if (m_collision) { delete m_collision; m_collision = nullptr; } } void EnemyBullet::setSpriteScale(float x, float y) { m_spriteScaleX = x; m_spriteScaleY = y; if(m_sprite) { m_sprite->setScale(m_spriteScaleX, m_spriteScaleY); } } void EnemyBullet::update(void) { if (m_positionX < -10.0f || 650.f < m_positionX || m_positionY < -10.0f || 490.0f < m_positionY) { manager()->destroyGameObject(this); m_sprite->setActive(false); return; } m_positionX += m_dirX * m_speed; m_positionY += m_dirY * m_speed; m_sprite->setPosition(m_positionX, m_positionY); m_collision->x = m_positionX; m_collision->y = m_positionY; float rad = atan2f(m_dirY, m_dirX); m_sprite->setRotate(RAD_TO_DEG(rad)); #if COLLISION_VISIBLE m_collisionSprite->setPosition(m_positionX, m_positionY); m_collisionSprite->setActive(getCollisionVisible()); #endif } void EnemyBullet::onFirstUpdate() { m_sprite = new Sprite(m_imageId); m_sprite->setPriority(static_cast<unsigned int>(DrawPriority::Bullet)); m_sprite->setPosition(-100.0f, -100.0f); setSpriteScale(m_spriteScaleX, m_spriteScaleY); m_collision = new core2d::Collision::PointF(0, 0); addCollision(m_collision); #if COLLISION_VISIBLE m_collisionSprite = new core2d::BoxEdgeSprite(0.0f, 0.0f); m_collisionSprite->setPosition(-100, -100); m_collisionSprite->setColor(0.0f, 1.0f, 0.5f); #endif }
true
2dcd223b129b91b96df6baaa86d7e0a257196bda
C++
Deepakgarg2309/hackoctoberfest2021
/prims_algorithm.cpp
UTF-8
1,422
3.171875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define V 5 int minKey(int array[], bool mstVisited[]) { int min = INT_MAX; int min_index; for (int i = 0; i < V; i++) { if (mstVisited[i] == false && array[i] < min) { min = array[i]; min_index = i; } } return min_index; } void printMst(int parent[], int graph[V][V]) { cout<<"Edge \tWeight\n"; for (int i = 1; i < V; i++) cout<<parent[i]<<" - "<<i<<" \t"<<graph[i][parent[i]]<<" \n"; } void primsMST(int graph[V][V]) { int parent[V]; int key[V]; bool mstVisited[V]; for (int i = 0; i < V; i++) { mstVisited[i] = false; key[i] = INT_MAX; } key[0] = 0; parent[0] = -1; for (int count = 0; count < V-1; count++) { int min = minKey(key, mstVisited); mstVisited[min] = true; for (int i = 0; i < V; i++) { if (graph[min][i] && mstVisited[i] == false && graph[min][i] < key[i]) { parent[i] = min; key[i] = graph[min][i]; } } } printMst(parent, graph); } int main() { int graph[V][V] = { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; primsMST(graph); return 0; }
true
36034fdb2c32c5ddd93c3ab746b6ffda3922a881
C++
lyapunov99/DataStructures
/solutions/lab-assoc/main.cpp
UTF-8
648
2.859375
3
[]
no_license
// // main.cpp // lab10 // // COMP 15: Data Structures // Tufts University Department of Computer Science // #include <iostream> #include "Assoc.h" using namespace std; int main (int argc, const char * argv[]) { Assoc presidents; presidents["Monaco"] = "Anthony"; presidents["Clinton"] = "Bill"; presidents["Bush"] = "Dubya"; presidents["Bacow"] = "Larry"; cout << presidents["Clinton"] << endl; presidents["Clinton"] = "Sax player"; cout << presidents["Bacow"] << endl; cout << presidents["Bush"] << endl; cout << presidents["Monaco"] << endl; cout << presidents["Clinton"] << endl; return 0; }
true
b3462b9c46828072e65f1b76586e08f5e0970be9
C++
rbary/isiviewer-1.3
/objects/triMesh.cpp
UTF-8
6,525
2.78125
3
[]
no_license
#include "triMesh.h" TriMesh::TriMesh() : Object3D() { _name="TriMesh"; std::cout<<"Meshing in progress..."<<endl; } void TriMesh::addVertex(Vertex v){ extendBoundingBox(v); _vertices.push_back(v); } void TriMesh::addVertex(double x, double y, double z){ addVertex(Vertex(x,y,z)); } void TriMesh::addTriangle(Triangle t){ _triangles.push_back(t); } void TriMesh::addTriangle(int v1, int v2, int v3){ Triangle t; t.push_back(v1); t.push_back(v2); t.push_back(v3); addTriangle(t); } void TriMesh::addNormalT(Normal n){ _normalsT.push_back(n); } void TriMesh::addNormalV(Normal n){ _normalsV.push_back(n); } Vertex TriMesh::getVertex(int i){ return _vertices[i]; } void TriMesh::computeBoundingBox(){ if(_vertices.size()<1) return; _bBoxMax=_vertices[0]; _bBoxMin=_vertices[0]; for(unsigned int i=0; i<_vertices.size(); ++i) extendBoundingBox(_vertices[i]); } void TriMesh::computeNormalsT(){ _normalsT.empty(); // Compute a normal for each triangle // and put it in normalsT vector. for(int t=0;t<_triangles.size();t++){ glm::vec3 const & a=_vertices[_triangles[t][0]]; glm::vec3 const & b=_vertices[_triangles[t][1]]; glm::vec3 const & c=_vertices[_triangles[t][2]]; Normal n=glm::normalize(glm::cross(b-a,c-a)); addNormalT(n); } } void TriMesh::computeNormalsV(float angle_threshold){ _normalsV.empty(); // Compute a normal for each vertex of each triangle // and put it in normalsV vector. // Each normal is the average of adjacent triangle normals. // Only normals whose angle with the current triangle normal // is below the angle_threshold is taken into account. float diffAngle; std::vector<GLint> tempTrgl; std::vector<std::vector<GLint> > adjList; for(unsigned int i=0;i<_vertices.size();i++){//for all vertices for(unsigned int j=0;j<_triangles.size();j++)//for all triangles if(_triangles[j][0]==i || _triangles[j][1]==i || _triangles[j][2]==i){ tempTrgl.push_back(j); } adjList.push_back(tempTrgl); tempTrgl.clear(); } for(unsigned int t=0;t<_triangles.size();t++){ for(int p=0;p<3;p++){ Normal n=_normalsT[t]; GLint currentPeak=_triangles[t][p]; for(unsigned int ti=0;ti<_triangles.size();ti++){ if(t!=ti){ if(std::find(adjList[currentPeak].begin(),adjList[currentPeak].end(),ti) != adjList[currentPeak].end()){ //we test the angle between the current triangle and adjacent triangle diffAngle=glm::angle(_normalsT[ti],_normalsT[t]); //cout<<"diff angle =>"<<diffAngle<<endl; if(diffAngle < angle_threshold){ n=n+(_normalsT[ti]); } } } } addNormalV(glm::normalize(n)); } } } double TriMesh::normalize(){ glm::vec3 size=_bBoxMax-_bBoxMin; glm::vec3 c=getBoundingBoxCenter(); double scale=2/max(size.x, max(size.y,size.z)); for(unsigned int i=0; i<_vertices.size(); ++i){ _vertices[i]+=c; _vertices[i]*=scale; } _bBoxMin+=c; _bBoxMin*=scale; _bBoxMax+=c; _bBoxMax*=scale; return scale; } std::string TriMesh::toString(){ ostringstream oss; oss<< "["<< _name <<" v:"<< _vertices.size() <<", t:"<< _triangles.size() <<"]"; return oss.str(); } void TriMesh::toOStream(std::ostream& out) const{ Object3D::toOStream(out); out << " v: " << _vertices.size() << std::endl; out << " t: " << _triangles.size() << std::endl; } void TriMesh::draw(bool flipnormals){ unsigned int i,t; bool smooth; Normal n; GLint mode[1]; glGetIntegerv(GL_SHADE_MODEL, mode); smooth= mode[0]==GL_SMOOTH && _normalsV.size()==_triangles.size()*3; if(smooth){ glBegin(GL_TRIANGLES); for(t=0; t<_triangles.size(); ++t) for(i=0; i<3; i++){ n=_normalsV[3*t+i]; if(flipnormals) n*=-1; // glNormal3fv(&n[0]); glNormal3fv(glm::value_ptr(n)); glVertex3fv(glm::value_ptr(_vertices[_triangles[t][i]])); } glEnd(); }else{ glBegin(GL_TRIANGLES); for(t=0; t<_triangles.size(); ++t){ n=_normalsT[t]; if(flipnormals) n*=-1; glNormal3fv(glm::value_ptr(n)); for(i=0; i<3; i++) glVertex3fv(glm::value_ptr(_vertices[_triangles[t][i]])); } glEnd(); } } void TriMesh::drawNormals(bool flipnormals){ unsigned int i,t; bool smooth; glm::vec3 p,n; GLint mode[1]; glGetIntegerv(GL_SHADE_MODEL, mode); smooth= mode[0]==GL_SMOOTH && _normalsV.size()==_triangles.size()*3; glColor3f(1,1,1); if(smooth){ for(i=0; i<_normalsV.size(); ++i){ n=_normalsV[i]; if(flipnormals) n*=-1; glNormal3fv(glm::value_ptr(n)); n/=10; glBegin(GL_LINES); glVertex3fv(glm::value_ptr(_vertices[_triangles[i/3][i%3]])); glVertex3fv(glm::value_ptr(_vertices[_triangles[i/3][i%3]]+n)); glEnd(); } }else{ for(t=0; t<_triangles.size(); ++t){ p= _vertices[_triangles[t][0]] +_vertices[_triangles[t][1]] +_vertices[_triangles[t][2]]; p/=3; n=_normalsT[t]; if(flipnormals) n*=-1; glNormal3fv(glm::value_ptr(n)); n/=10; glBegin(GL_LINES); glVertex3fv(glm::value_ptr(p)); glVertex3fv(glm::value_ptr(p+n)); glEnd(); } } } void TriMesh::drawVertices(){ glPointSize(3.); glBegin(GL_POINTS); for(unsigned int i=0; i<_vertices.size(); ++i ) glVertex3fv(glm::value_ptr(_vertices[i])); glEnd(); } float TriMesh::thresholdAngle(Normal v1,Normal v2){ //produit scalaire v1.v2 float PS=0; //norme de v1 //float v1norm=std::sqrt(std::pow(v1[0],2),std::pow(v1[1],2),std::pow(v1[2],2)); //norme de v2 //float v2norm=std::sqrt(std::pow(v2[0],2),std::pow(v2[1],2),std::pow(v2[2],2)); for(int i=0;i<3;i++) PS+=v1[i]*v2[i]; //return acos( PS/(v1norm * v2norm) * 180.0/pi); return 0; }
true
95062bf0a71a8f8db635a05ae02580e510e84af5
C++
saralazic/Single-pass-assembly
/ls160054d/src/Convert.cpp
UTF-8
2,338
3.1875
3
[]
no_license
#include "Convert.h" #include <iostream> using namespace std; string Convert::BinToHex(string bin) { string h_digit; string ret=""; for (int i = 0, j = 4 * i; i < 2; i++) { h_digit = bin.substr(j, 4); if (h_digit == "0000") ret += "0"; else if (h_digit == "0001") ret += "1"; else if (h_digit == "0010") ret += "2"; else if (h_digit == "0011") ret += "3"; else if (h_digit == "0100") ret += "4"; else if (h_digit == "0101") ret += "5"; else if (h_digit == "0110") ret += "6"; else if (h_digit == "0111") ret += "7"; else if (h_digit == "1000") ret += "8"; else if (h_digit == "1001") ret += "9"; else if (h_digit == "1010") ret += "A"; else if (h_digit == "1011") ret += "B"; else if (h_digit == "1100") ret += "C"; else if (h_digit == "1101") ret += "D"; else if (h_digit == "1110") ret += "E"; else if (h_digit == "1111") ret += "F"; } return ret; } string Convert::DecToHex(int dec) { string ret = ""; int v; if (dec == 0) return "00"; while (dec != 0) { if (dec % 16 < 10) v = 48; else v = 55; ret = char(dec % 16 + v) + ret; dec = dec / 16; } return ret; } string Convert::DecToBin1Digit(int dec) { string res = "XXXX"; switch (dec) { case 0: res = "0000"; break; case 1: res = "0001"; break; case 2: res = "0010"; break; case 3: res = "0011"; break; case 4: res = "0100"; break; case 5: res = "0101"; break; case 6: res = "0110"; break; case 7: res = "0111"; break; case 8: res = "1000"; break; case 9: res = "1001"; break; default: cout << "Nije jedna cifra! Greska u konverziji"; break; } return res; } char* Convert::StringToCharArr(string str, char from, char without, char to) { //cout << str.size()<<endl; char* res = new char[str.size()]; bool flag = (from == '\0') ? true : false; bool nw = (without == '\0')? true: false; int i, j; char c; j = 0; c = str[0]; for (i = 0; i < str.size(); i++, c = str[i]) { if (flag) { //from if (c == to) break; //to //without if (nw) res[j++] = c; else { if (c != without) res[j++] = c; } } else { if (c == from) flag = true; } } res[j] = '\0'; return res; /* char* c = new char[5]; c[0] = '3'; return c;*/ }
true
011d1f5ab97fe56a23bd1f50474a5019495c4aeb
C++
aleksay/quadr_ino_copter
/src/avrTimer1.cpp
UTF-8
4,604
2.8125
3
[]
no_license
#include "avrTimer1.h" // Variables uint16_t timer1_prescaler; uint16_t timer1_minHzPrescaler1; uint16_t timer1_minHzPrescaler8; uint16_t timer1_minHzPrescaler64; uint16_t timer1_minHzPrescaler256; // FUNCTIONS int8_t timer1_init() { // calculate max values per prescaler timer1_getPrescalerMinHz(); // configure timer1 timer1_fastPwm_ocr1atop_init(); // initialize timer1 global variable /* timer1_prescaler = DEFAULT_T1_INIT_PRESCALER; timer1_setFrequency(DEFAULT_T1_INIT_FREQUENCY); //also sets duty */ //timer1_stop(); return 0; } int8_t timer1_fastPwm_icr1top_init() { SET_TIMER1_PINB; SET_TIMER1_FREQUENCY_ICR1TOP(DEFAULT_T1_INIT_FREQUENCY); SET_TIMER1_DUTY_CHAN_B(DEFAULT_T1_INIT_DUTY); TIMER1_RESET; SET_TIMER1_PINOUT(B); SET_TIMER1_MODE_FASTPWM_ICR1; SET_TIMER1_PINB_NOTINVERTING(0); SET_TIMER1_INTERRUPT_OUTPUTCOMPARE_B; //SET_TIMER1_PRESCALER_1; return 0; } int8_t timer1_fastPwm_ocr1atop_init() { SET_TIMER1_INTERRUPT_OUTPUTCOMPARE_A; //SET_TIMER1_INTERRUPT_OUTPUTCOMPARE_B; //SET_TIMER1_INTERRUPT_OVERFLOW; TIMER1_RESET; SET_TIMER1_PINB; //SET_TIMER1_PINOUT(B); SET_TIMER1_MODE_FASTPWM_OCR1A; SET_TIMER1_PINB_NOTINVERTING(0); return 0; } void timer1_start(uint16_t Hz) { //timer1_setPrescaler(DEFAULT_T1_INIT_PRESCALER); timer1_setFrequency(Hz); } //stop timer1 by removing the prescaler void timer1_stop() { SET_TIMER1_STOP; pins_setDriveOpenInverter(); // TODO remove me } void timer1_getPrescalerMinHz(void) { timer1_minHzPrescaler1 = fastPWM_Top2Hz(1 , UINT16_MAX) + 1; timer1_minHzPrescaler8 = fastPWM_Top2Hz(8 , UINT16_MAX) + 1; timer1_minHzPrescaler64 = fastPWM_Top2Hz(64 , UINT16_MAX) + 1; timer1_minHzPrescaler256 = fastPWM_Top2Hz(256, UINT16_MAX) + 1; // debug("timer1_minHzPrescaler1:%u", timer1_minHzPrescaler1); // debug("timer1_minHzPrescaler8:%u", timer1_minHzPrescaler8); // debug("timer1_minHzPrescaler64:%u", timer1_minHzPrescaler64); // debug("timer1_minHzPrescaler256:%u", timer1_minHzPrescaler256); } uint16_t timer1_getPrescalerRequired(uint16_t Hz) { if (Hz >= timer1_minHzPrescaler1) return 1; if (Hz >= timer1_minHzPrescaler8) return 8; if (Hz >= timer1_minHzPrescaler64) return 64; if (Hz >= timer1_minHzPrescaler256) return 256; } int8_t timer1_setPrescaler(uint16_t _prescaler) { debug("prescaler set to: %d", _prescaler); switch (_prescaler) { case 1: SET_TIMER1_PRESCALER_1; timer1_prescaler = 1; return 0; case 8: SET_TIMER1_PRESCALER_8; timer1_prescaler = 8; return 0; case 64: SET_TIMER1_PRESCALER_64; timer1_prescaler = 64; return 0; case 256: SET_TIMER1_PRESCALER_256; timer1_prescaler = 256; return 0; case 1024: SET_TIMER1_PRESCALER_1024; timer1_prescaler = 1024; return 0; } return 1; } int8_t timer1_setFrequency(uint16_t Hz) { int8_t ret; // check Hz // TODO implement logging rate limiting if (Hz == timer1_getFrequency()) { log_warn("frequency unchanged! Hz:%u", Hz); return -1; } // update prescaler if necessary if (timer1_getPrescalerRequired(Hz) != timer1_getPrescaler() ) { timer1_setPrescaler(timer1_getPrescalerRequired(Hz)); } //debug("Hz:%u, Required prescaler:%u", Hz, timer1_getPrescalerRequired(Hz)); // convert Hz to register value TOP ret = timer1_setTop( fastPWM_Hz2Top(timer1_getPrescaler(), Hz) ); if (ret < 0) return ret; //debug("Top:%u",fastPWM_Hz2Top(timer1_getPrescaler(),Hz)); // set new duty, and return error code ret = timer1_setDuty(timer1_getDuty()); if (ret < 0) return ret; return 0; } int8_t timer1_setTop(uint16_t top) { if (timer1_getTop() == top) { log_warn("top unchanged!"); return -1; } // set new TOP value in register SET_TIMER1_FREQUENCY_OCR1ATOP(top); return 0; } int8_t timer1_setDuty(uint8_t duty) { if (duty < 0 || duty > 100) { log_err("bad duty: %d", duty); return -1; } SET_TIMER1_DUTY_CHAN_B( avrMap(duty, 0, 100, 0, timer1_getTop()) ); return 0; } uint16_t timer1_getPrescaler(void) { return timer1_prescaler; } uint16_t timer1_getFrequency(void) { return fastPWM_Top2Hz(timer1_getPrescaler(), timer1_getTop()); } uint16_t timer1_getTop(void) { // return ICR1; // Depending on PWM type used return OCR1A; } uint16_t timer1_getDuty(void) { return avrMap(OCR1B, 0, timer1_getTop(), 0, 100); } void timer1_timer1_ovf_handler(void) { SET_TIMER1_FREQUENCY_OCR1ATOP(timer1_getFrequency()); SET_TIMER1_DUTY_CHAN_B(timer1_getDuty()); }
true
68158e45e77ded284dc47a2f461632ed0b1718c2
C++
DoNotTouchMe/StudingCPlus
/stoke/main.cpp
UTF-8
862
3.09375
3
[]
no_license
#include <iostream> #include <String> using namespace std; class Stoke { private: string name; int article; int amt; public: Stoke () { name = "Null"; article = 0; amt = 0; } Stoke (string name) { this->name = name; this->article = 0; this->amt = 0; } void set (string name, int article, int amt) { this->name = name; this->article = article; this->amt = amt; } void get () { cout << "Name - " << name << " Article - " << article << " Amt - " << amt << "pc" << endl; } ~Stoke () { cout << "End working" << endl; } }; int main(int argc, const char * argv[]) { Stoke nail("Nail"); nail.get(); Stoke pin; pin.get(); Stoke skrew; skrew.set("Skrew", 3456, 10); skrew.get(); cin.get(); }
true
263f6dfffb54f5d48db19256c87c44ac9a241101
C++
project-arcana/clean-ranges
/src/clean-ranges/algorithms/last.hh
UTF-8
877
2.859375
3
[ "MIT" ]
permissive
#pragma once #include <clean-core/assert.hh> #include <clean-core/functors.hh> #include <clean-core/iterator.hh> #include <clean-ranges/detail/call.hh> namespace cr { /// returns the last element satisfying the predicate in the range /// NOTE: requires at least one matching element /// Complexity: O(n) template <class Range, class Predicate = cc::constant_function<true>> [[nodiscard]] constexpr decltype(auto) last(Range&& range, Predicate&& predicate = {}) { auto it = cc::begin(range); auto end = cc::end(range); size_t idx = 0; auto found = false; auto res_it = it; while (it != end) { if (cr::detail::call(idx, predicate, *it)) { res_it = it; found = true; } ++it; ++idx; } CC_ASSERT(found && "no element satisfying the predicate found"); return *res_it; } }
true
e70557c9c40004786248d6da6700b640d158ffc7
C++
keeyank/PPP
/Ch18/cat.cpp
UTF-8
1,052
3.25
3
[]
no_license
#include <iostream> #include <string> #include <sstream> using namespace std; int str_len(const char* s) { if (s == nullptr) return 0; int count = 0; while (s[count]) ++count; return count; } string cat(string s1, string s2, string delim = "") { ostringstream c; c << s1 << delim << s2; return c.str(); } char* cat(const char* s1, const char* s2, const char* delim = nullptr) { int n = str_len(s1) + str_len(delim) + str_len(s2) + 1; char* c = new char[n]; char* curr = c; while (*s1 != 0) { *curr = *s1; ++curr; ++s1; } if (delim) { while (*delim != 0) { *curr = *delim; ++curr; ++delim; } } while (*s2 != 0) { *curr = *s2; ++curr; ++s2; } *curr = 0; return c; } istream& read_cstr(istream& is, char* buffer, int max) { is.width(max); return is >> buffer; } int main() { constexpr int max = 128; char s1[max]; char s2[max]; while (true) { cin.getline(s1, max); cin.getline(s2, max); if (!cin) break; char* c = cat(s1, s2, "---"); cout << c << endl; delete[] c; } return 0; }
true
b87d819d3c9b52c0f9f385940560d43e55a5313e
C++
kenkov/nlp-tutorial
/unigram_worddivision.cpp
EUC-JP
2,560
2.53125
3
[]
no_license
#include <iostream> #include <cstdio> #include <string> #include <fstream> #include <string> #include <stack> #include <vector> #include <map> #include <algorithm> #include <cmath> #include <boost/algorithm/string.hpp> #include "util.h" using namespace std; vector<string> wordsplit( vector<string> uniwords, const char *modelfile, unsigned int max_word_len=10, double mx=pow(10, 10), const double lambda1 = 0.95, const long n_unk = 1e6 ) { // load model map<string, double> model = load_unimodel(modelfile); // main unsigned int size = uniwords.size(); // best score for forward step vector<double> best_score(size+1); // positions for backword step vector<int> before_pos(size+1); for (unsigned int i = 0; i <= size; i++) { best_score[i] = mx; before_pos[i] = 0; } best_score[0] = 0; for (unsigned int curpos = 0; curpos < uniwords.size(); curpos++) { for (unsigned int j = 0; j < min(max_word_len, size - curpos); j++) { string word = substring(uniwords, curpos, curpos + j); double prob = log(uniprob(word, model, lambda1, n_unk)); double cand_prob = best_score[curpos] - prob; int endpos = curpos + j + 1; if (cand_prob < best_score[endpos]) { best_score[endpos] = cand_prob; before_pos[endpos] = curpos; } } } // verbose //for (unsigned int i=0; i <= size; i++) { // printf("%d\t%f %d\n", i, best_score[i], before_pos[i]); //} int start = size; vector<string> answer; while (start != 0) { int curstart = before_pos[start]; answer.push_back(substring(uniwords, curstart, start-1)); start = curstart; } reverse(answer.begin(), answer.end()); return answer; } int main(int argc, const char *argv[]) { const char* modelfile = argv[1]; string str; while (getline(cin, str)) { vector<string> words(str.size()); for (unsigned int i=0; i < str.size(); i++) { words[i] = str[i]; } // ΥǥǤ </s> ϹθƤʤ // words.push_back("</s>"); vector<string> answer = wordsplit(words, modelfile); for (unsigned int i = 0; i < answer.size(); i++) { cout << answer[i]; if (i == answer.size() - 1) { cout << endl; } else { cout << " "; } } } return 0; }
true
2638331f218afc9807c52dbd09fdc9c4224ad8e1
C++
lys861205/test
/test.cc
UTF-8
1,598
3.6875
4
[]
no_license
#include <iostream> #include <sstream> #include <tuple> #include <exception> #include <string> #include <vector> using namespace std; class Girl { public: string name; int age; Girl() { cout << "Girl()" << endl; } ~Girl() { cout << "~Girl()" << endl; } Girl(string _name, int _age) : name(_name), age(_age) { cout << "Girl(string _name, int _age)" << endl; } Girl(const Girl& b) : name(b.name), age(b.age) { cout << "Girl(const Girl&)" << endl; } Girl(Girl&& b) : name(move(b.name)), age(b.age) { cout << "Girl(Girl&&)" << endl; } Girl& operator=(const Girl& b) { cout << "operator=(const Girl&)" << endl; this->name = b.name; this->age = b.age; return *this; } }; int main() { vector<Girl> v1; v1.emplace_back("girl1", 1); vector<Girl> v2; v2.reserve(1); std::cout << "==================" << std::endl; v2 = std::move(v1); std::cout << "==================" << std::endl; getchar(); // vector<Girl> bv; // // cout << bv.size() << endl; // cout << bv.capacity() << endl; // // bv.emplace_back("example1", 1); // // cout << bv.size() << endl; // cout << bv.capacity() << endl; // // bv.emplace_back("example2", 2); // // cout << bv.size() << endl; // cout << bv.capacity() << endl; // // bv.emplace_back("example3", 3); // // cout << bv.size() << endl; // cout << bv.capacity() << endl; // // bv.emplace_back("example4", 4); // // cout << bv.size() << endl; // cout << bv.capacity() << endl; // return 1; }
true
21b890dcec4d7035b022af1f4af278c55815213c
C++
harsh9500/LeetCode
/April Challenge 2021/April 29.cpp
UTF-8
828
2.84375
3
[]
no_license
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int n=nums.size(); vector<int> answer{-1,-1}; if(n==0) return answer; int low=0,high=n-1,mid; while(low<=high) { mid=low+(high-low)/2; if(nums[mid]==target) { int i=mid,j=mid; while(i>=0 && nums[i]==target) i--; while(j<n && nums[j]==target) j++; answer[0]=i+1; answer[1]=j-1; return answer; } if(nums[mid]>target) { high=mid-1; } else { low=mid+1; } } return answer; } };
true
fb8648806b6ab2ea9552ab7b04736ee4f5ba1e95
C++
Prince-1501/Hello_world-Competiitve-Programming
/Lecture - 26.cpp
UTF-8
881
2.9375
3
[]
no_license
// // main.cpp // hsgts // // Created by Prince Kumar on 29/03/19. // Copyright © 2019 Prince Kumar. All rights reserved. // Chef and his daily routine Problem Code: CHEFROUT #include <iostream> using namespace std; int main() { int T; cin>>T; while(T--) { string s; cin>>s; int count=0; for(int i=0;i<s.size()-1;i++) { if(s[i]=='C') { if(s[i+1]=='E' ||s[i+1]=='S' || s[i+1]=='C') count++; } else if(s[i]=='E') { if(s[i+1]=='S' || s[i+1]=='E') count++; } else if(s[i]=='S') { if(s[i+1]=='S') count++; } } if(count==s.size()-1) cout<<"yes"<<endl; else cout<<"no"<<endl; } }
true