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
d0b644aa5df6988880463cd679d747f4846bf195
C++
phillipthomasjamessteiner/MPU-6050-Library
/MPU_6050_Wire.h
UTF-8
1,125
2.6875
3
[ "MIT" ]
permissive
// Library for MPU-6050 6 axis Accel/Gryo/Temp #ifndef MPU_6050_Wire_h #define MPU_6050_Wire_h #define ACCELX_REG 59 #define ACCELY_REG 61 #define ACCELZ_REG 63 #define GYROX_REG 67 #define GYROY_REG 69 #define GYROZ_REG 71 #define TEMP_REG 65 #define ACCEL_CONFIG_REG 28 #define GYRO_CONFIG_REG 27 class MPU_6050_Wire { public: MPU_6050_Wire(); void begin(uint8_t address); // Initialize w/ address void setAccelConfig(uint8_t AFS); // Accuracy Config for Accelerometers void setGyroConfig(uint8_t GFS); // Accuracy Config for Gyroscopes int16_t readAccelX(); int16_t readAccelY(); int16_t readAccelZ(); int16_t readGyroX(); int16_t readGyroY(); int16_t readGyroZ(); int16_t readTemp(); // Read Internal Temperiture Register double accelInGs(int16_t rawAccel); double gyroInDegPerSec(int16_t rawGyro); double tempInCelcius(int16_t rawTemp); uint8_t AFS, GFS; private: uint8_t address; int16_t AccelX, AccelY, AccelZ, GyroX, GyroY, GyroZ, Temp; }; #endif
true
fe43b7a18e539a35bbd866572371a99a7f7959a7
C++
uspgamedev/ugdk
/modules/ugdk-core/src/math/integer2D.cc
UTF-8
5,058
3.0625
3
[ "Zlib" ]
permissive
#include <ugdk/math/integer2D.h> #include <cmath> #include <algorithm> #include <assert.h> #include <ugdk/math/vector2D.h> #define SWAPVARS(temp,var1,var2) temp = var1; var1 = var2; var2 = temp using namespace ugdk::enums; using mirroraxis::MirrorAxis; namespace ugdk { namespace math { static int absolute_value(int v) { return std::max(v, -v); } Integer2D::Integer2D(const ugdk::math::Vector2D& vec2d) : x(static_cast<int>(vec2d.x)), y(static_cast<int>(vec2d.y)) {} // Returns the norm-1. int Integer2D::NormOne() const { return absolute_value(x) + absolute_value(y); } double Integer2D::Length() const { return sqrt(LengthSquared()); } double Integer2D::Angle() const { return atan2(static_cast<double>(y), static_cast<double>(x)); } void Integer2D::Rotate(RotDeg rotdeg) { int temp; switch(rotdeg) { case NINETY: // (x, y) = (y, -x) SWAPVARS(temp,x,y); x = -x; break; case TWO_NINETY: // (x, y) = (-x, -y) x = -x; y = -y; break; case THREE_NINETY: // (x, y) = (-y, x) SWAPVARS(temp,x,y); y = -y; break; } } Integer2D Integer2D::Rotated(RotDeg rotdeg) const { Integer2D ret = *this; ret.Rotate(rotdeg); return ret; } void Integer2D::Mirror(const MirrorAxis mirror) { int temp; switch(mirror) { case mirroraxis::HORZ: y = -y; break; case mirroraxis::DIAG_UP: SWAPVARS(temp,x,y); break; case mirroraxis::VERT: x = -x; break; case mirroraxis::DIAG_DOWN: SWAPVARS(temp,x,y); x = -x; y = -y; break; default: assert(false); break; } } Integer2D Integer2D::Mirrored(const MirrorAxis mirror) const { Integer2D ret = *this; ret.Mirror(mirror); return ret; } void Integer2D::Multiply(const Integer2D& multiplier) { x *= multiplier.x; y *= multiplier.y; } Integer2D Integer2D::Multiplied(const Integer2D& multiplier) const { Integer2D ret = *this; ret.Multiply(multiplier); return ret; } void Integer2D::Divide(const Integer2D& divisor) { assert(divisor.x != 0 && divisor.y != 0); x /= divisor.x; y /= divisor.y; } Integer2D Integer2D::Divided(const Integer2D& divisor) const { assert(divisor.x != 0 && divisor.y != 0); Integer2D ret = *this; ret.Divide(divisor); return ret; } void Integer2D::Scale(const Integer2D& multiplier, const Integer2D& divisor) { assert(divisor.x != 0 && divisor.y != 0); this->Multiply(multiplier); this->Divide(divisor); } Integer2D Integer2D::Scaled(const Integer2D& multiplier, const Integer2D& divisor) const { assert(divisor.x != 0 && divisor.y != 0); Integer2D ret = *this; ret.Scale(multiplier,divisor); return ret; } void Integer2D::Mod(const Integer2D& divisor) { assert(divisor.x != 0 && divisor.y != 0); x %= divisor.x; y %= divisor.y; } Integer2D Integer2D::Remainder(const Integer2D& divisor) const { assert(divisor.x != 0 && divisor.y != 0); Integer2D ret = *this; ret.Mod(divisor); return ret; } Integer2D& Integer2D::operator+=(const Integer2D &other) { x += other.x; y += other.y; return *this; } Integer2D& Integer2D::operator-=(const Integer2D &other) { x -= other.x; y -= other.y; return *this; } Integer2D& Integer2D::operator*=(int scalar) { x *= scalar; y *= scalar; return *this; } Integer2D& Integer2D::operator/=(int scalar) { assert( scalar != 0 ); x /= scalar; y /= scalar; return *this; } Integer2D& Integer2D::operator%=(int scalar) { assert ( scalar != 0 ); x %= scalar; y %= scalar; return *this; } Integer2D Integer2D::operator+(const Integer2D &right) const { Integer2D ret = *this; ret += right; return ret; } Integer2D Integer2D::operator-(const Integer2D &right) const { Integer2D ret = *this; ret -= right; return ret; } Integer2D Integer2D::operator-() const { return Integer2D(-x, -y); } Integer2D Integer2D::operator*(int scalar) const { Integer2D ret = *this; ret *= scalar; return ret; } Vector2D Integer2D::operator*(double scalar) const { Vector2D ret(*this); ret *= scalar; return ret; } Integer2D Integer2D::operator/(int scalar) const { assert( scalar != 0 ); Integer2D ret = *this; ret /= scalar; return ret; } Integer2D Integer2D::operator%(int scalar) const { assert( scalar != 0 ); Integer2D ret = *this; ret %= scalar; return ret; } int Integer2D::operator*(const Integer2D& right) const { return x * right.x + y * right.y; } Integer2D Integer2D::operator%(const Integer2D& right) const { assert( right.x != 0 && right.y != 0 ); return Remainder(right); } Integer2D operator*(int scalar, const Integer2D& right) { return right * scalar; } Vector2D operator*(double scalar, const Integer2D& right) { return right * scalar; } } // namespace math } // namespace ugdk
true
053176fdd81a8e2945361934ec3030e5cf9ec5d3
C++
Maruf089/Competitive-Programming
/Greedy_Algorithm.cpp
UTF-8
1,831
3.328125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { /// input number of Task int Total_task = 5 ; int Total_robot_number = 5 ; /// create cost matrix for every task int cost_for_task_1[] = {10,7,12,15,8}; int cost_for_task_2[] = {9,7,5,2,8}; int cost_for_task_3[] = {5,7,9,8,2}; int cost_for_task_4[] = {14,37,32,35,38}; int cost_for_task_5[] = {48,47,42,45,48}; int Min = INT_MAX , index = -1; for(int i=0;i<Total_task;i++) { if(cost_for_task_1[i]<=Min) { index = i+1; Min = cost_for_task_1[i]; } } cout << "For task 1 - assigned robot number is " << index << endl; Min = INT_MAX , index = -1; for(int i=0;i<Total_task;i++) { if(cost_for_task_2[i]<=Min) { index = i+1; Min = cost_for_task_2[i]; } } cout << "For task 2 - assigned robot number is " << index << endl; Min = INT_MAX , index = -1; for(int i=0;i<Total_task;i++) { if(cost_for_task_3[i]<=Min) { index = i+1; Min = cost_for_task_3[i]; } } cout << "For task 3 - assigned robot number is " << index << endl; Min = INT_MAX , index = -1; for(int i=0;i<Total_task;i++) { if(cost_for_task_4[i]<=Min) { index = i+1; Min = cost_for_task_4[i]; } } cout << "For task 4 - assigned robot number is " << index << endl; Min = INT_MAX , index = -1; for(int i=0;i<Total_task;i++) { if(cost_for_task_5[i]<=Min) { index = i+1; Min = cost_for_task_5[i]; } } cout << "For task 5 - assigned robot number is " << index << endl; }
true
faf90bd92ad68321351d452c9b68ebe13e3725b6
C++
c3e/GLaDOS_Receiver
/GLaDOSServoControl.cpp
UTF-8
6,273
2.609375
3
[]
no_license
#if defined(ARDUINO) && ARDUINO >= 100 #include <Arduino.h> #else #include <WProgram.h> #endif #include <Servo.h> #include "GLaDOSServoControl.h" GLaDOSServoControl::GLaDOSServoControl(Servo newServo, uint16_t startPos, uint16_t rangeMin, uint16_t rangeMax) { _thisServo = newServo; _rangeMin = 650; _rangeMax = 2400; _curPos = 1500; // start and end speed _startSpeed = 3; _endSpeed = 3; if (rangeMin >= _rangeMin && rangeMax <= _rangeMax) { _rangeMin = rangeMin; _rangeMax = rangeMax; } if (startPos >= _rangeMin && startPos <= _rangeMax) { _curPos = startPos; } _prePos = _curPos; _newPos = _curPos; // smooth motion stuff start values _pie = 3.14159; // the cake is a lie! _sineSize = 1700; //general resolution of the servos = lowest microsecond to highest microsecond,approximately _eventCycle = _sineSize * 100; //some gigantic number so the nextStep function never runs out of ticks //servo 1 800-2200 decrease to open _sineWaveVar = 0; // sine wave x variable counts from 1 to 1700 (servo resolution) only starts counting after wait# reaches its activation value. _countExtended = 0; _speed = 0; //a value that consists of small increment values that change in magnitude depending on if the wave starts slow and ends fast or vise versa. _speedTick = 0; //ticks off how long the hold position for the servo is in very small ms increments giving the illusion of a slower or faster moving servo _amplitude = 0; //a# amplitude higher value taller wave shorter value shorter wave by magnitude: a=(highest # - lowest #)/2 //_phaseShift = 0; //b# lower value = longer wave or higher value=shorter wave this is phase shift or stretch of function b=2pi/(period*2) where period is desired wave size _phaseShift = (2 * _pie / (_sineSize * 2)); //coefficient of sine math function _frequencyOffset = 0; //c# is x frequency offset = what part of curve want to look at _yOffset = 0; //d# is y offset = 0.5*amplitude shifts the curve so it is wholey in 1st quadrant _atEnd = 1; //trigger value either 0 or 1 to declare that that servo has reached its final position and so servo movement sequence of all servos (once all report per#=1)can end. _exForCount = 0; _numberOfSinusWaves = 1; _msWaitTime = 10; //_thisServo.writeMicroseconds(_curPos); } bool GLaDOSServoControl::setNewPos(uint16_t newPos) { if (newPos >= _rangeMin && newPos <= _rangeMax) { if (newPos != _prePos) { //resets and values established _newPos = newPos; _atEnd = 0; _sineWaveVar = 1; _countExtended = 1; _speedTick = 1; //_sineSize = ((_numberOfSinusWaves * 2) - 1) * _sineSize; //ranges from _numberOfSinusWaves=1,2,3,4,5 _sineSize#= 1*1700,3*1700,5*1700,7*1700 _exForCount = 0; //position dependent sine wave coeficients if (_newPos > _prePos) { _amplitude = (_newPos - _prePos) / 2; _frequencyOffset = (1.5) * _pie; _yOffset = _prePos + _amplitude; } else //(ynext# < yprev#) { _amplitude = (_prePos - _newPos) / 2; _frequencyOffset = (0.5) * _pie; _yOffset = _prePos - _amplitude; } return true; } } return false; } void GLaDOSServoControl::setStartSpeed(uint16_t startSpeed) { if (startSpeed < 1) { _startSpeed = 1; } else if (startSpeed > 25) { _startSpeed = 25; } else { _startSpeed = startSpeed; } } void GLaDOSServoControl::setEndSpeed(uint16_t endSpeed) { if (endSpeed < 1) { _endSpeed = 1; } else if (endSpeed > 25) { _endSpeed = 25; } else { _endSpeed = endSpeed; } } /* * getter for stuff */ uint16_t GLaDOSServoControl::getRangeMin(){return _rangeMin;} uint16_t GLaDOSServoControl::getRangeMax(){return _rangeMax;} uint16_t GLaDOSServoControl::getCurPos(){return _curPos;} bool GLaDOSServoControl::isAtEndPos(){return _atEnd;} // calculates the next position based on sinewave void GLaDOSServoControl::nextStep() { if(_exForCount < _eventCycle && _atEnd != 1) { // traditional speed values start off as spa# and end up as spb# as _exForCount# ticks away on the fly as curve is being drawn. // result is a sine curve that is compressed in the x axis on one end (spa#=large number) and stretched on other end (spb#=small number). if (_startSpeed > _endSpeed) {_speed = ((_countExtended + 1) / _sineSize) * (_startSpeed - _endSpeed) + _endSpeed;} //start fast end slow else {_speed = ((_countExtended + 1) / _sineSize) * (_endSpeed - _startSpeed) + _startSpeed;} // start slow end fast if (_exForCount > _msWaitTime && _sineWaveVar > _sineSize) //condition 3 motion is done and position is held { _prePos = _newPos; _newPos = _curPos; _atEnd = 1; //declares this servo is finished with its movement } else if (_exForCount > _msWaitTime) //condition 2 sin wave function active with optional hold position while big loop asks other servos for their turn { //new position of servo is written if (_sineWaveVar < _sineSize && _speedTick == 1) { _curPos = _amplitude * sin((_sineWaveVar) * _phaseShift + _frequencyOffset) + _yOffset; //the math function _speedTick += 1; // start of increment to _exForCount for possible pauses at this position to simulate slow _sineWaveVar += 1; //increments sine wave operator x in y=f(x) } //sine wave is sustained at old value for 1 to speed# as counted by speedtick# else if (_speedTick > 1 && _speedTick < _speed) { _speedTick += 1; //increments _speedTick to delay the servo at one position along its travel to simulate a speed } //sine wave is now permitted to continue drawing and moving to points by having speedtick# reset else { _speedTick = 1; //reset for next sin wave increment through of sine fun _sineWaveVar += 1; //locks out the sine function from going past _sineSize by ever increasing _exForCount# // _exForCount is given a positive or negative counter to follow sin wave so speed can be adjusted float tempCounCheck = _sineWaveVar / _sineSize; if (tempCounCheck <= 1) {_countExtended += 1;} else if (tempCounCheck > 1 && tempCounCheck < 2) {_countExtended -= 1;} } } //end if statement for case 2 _exForCount += 1; } //############# END OF GLOBAL LOOP FOR ALL SERVOS ############ _thisServo.writeMicroseconds(_curPos); // push current position to servo }
true
51a734391106a4ead20340878269eb985fd56935
C++
shelmets/unix_tasks
/unix_task6/app.cpp
UTF-8
1,562
2.703125
3
[]
no_license
#include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <math.h> bool file_exist(char *filename){ struct stat buffer; return (stat (filename, &buffer) == 0); } int main(int argc, char * argv[]) { int fd_main = open("./main", O_WRONLY); if (fd_main==-1){ perror("open"); return 1; } printf("Open file main\n"); pid_t pid = getpid(); printf("Pid: %d\n", pid); char name_socket[100]; char byte; sprintf(name_socket, "app%i", pid); if (!file_exist(name_socket)){ umask(0); if (mknod(name_socket, S_IFIFO | 0777, 0) < 0){ perror("mknod"); exit(2); } printf("Create socket %s\n", name_socket); } int len = strlen(name_socket); name_socket[len] = '\n'; name_socket[len+1] = '\0'; if (write(fd_main, name_socket, len + 1) == -1){ perror("write"); exit(2); } printf("Write name_socket\n"); close(fd_main); name_socket[len] = '\0'; int fd_app = open(name_socket, O_RDONLY); if (fd_app==-1){ perror("open"); exit(2); } printf("Open socket %s\n", name_socket); printf("Wait\n"); int ret, count = 0; while ((ret = read(fd_app, &byte, 1))!=0){ if (ret==-1){ if (errno == EINTR || errno == EAGAIN) continue; perror("read"); break; } count++; } printf("%i\n", count); close(fd_app); printf("Close %s\n", name_socket); if (unlink(name_socket)==-1){ perror("unlink"); exit(2); } return 0; }
true
637707aa0e461d5ea3afb058ac741ddf965e1d33
C++
tainzhi/acm
/leetcode-cn/566.cc
UTF-8
628
2.6875
3
[]
no_license
class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { if (nums.size() == 0 && r * c != 0) return nums; if (nums.size() * nums[0].size() != r * c) return nums; vector<vector<int>> result(r, vector<int>(c)); int oi = 0, oj = 0; for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { result[i][j] = nums[oi][oj]; ++oj; if (oj == nums[0].size()) { oj = 0; ++oi; } } } return result; } };
true
50a23ddd0664be4df6273942c6b548622a72ecb4
C++
gorobot/symmath
/test/numerics/test_complex.cc
UTF-8
2,281
3.265625
3
[]
no_license
#include <catch2/catch.hpp> #include <complex> #include <symmath/numerics/complex.hpp> #include <symmath/type_traits/is_element_of.hpp> #include <symmath/type_traits/is_field.hpp> #include <symmath/type_traits/is_scalar.hpp> using namespace std::complex_literals; TEST_CASE("Complex: properties", "[numerics]") { SECTION("should be an element of the complex numbers") { REQUIRE(sym::is_element_of<sym::ComplexNumbers, sym::Complex>{}); } SECTION("should have addition operator") { REQUIRE(sym::HasProperty<sym::Complex, sym::addition>{}); } SECTION("should have multiplication operator") { REQUIRE(sym::HasProperty<sym::Complex, sym::multiplication>{}); } SECTION("should be a field") { REQUIRE(sym::is_field<sym::ComplexNumbers>{}); } SECTION("should be a scalar") { REQUIRE(sym::is_scalar<sym::Complex>{}); } } TEST_CASE("Complex: operations", "[numerics]") { sym::Complex a(2.0 + 2.0i); sym::Complex b(1.0 + 1.0i); SECTION("should be able to add") { sym::Complex result; result = a + b; REQUIRE(result == 3.0 + 3.0i); result = a + (1.0 + 1.0i); REQUIRE(result == 3.0 + 3.0i); result = (2.0 + 2.0i) + b; REQUIRE(result == 3.0 + 3.0i); // result = a + 1.0i; } SECTION("should be able to divide") { sym::Complex result; result = a / b; REQUIRE(result == 2.0 + 0.0i); result = a / (1.0 + 1.0i); REQUIRE(result == 2.0 + 0.0i); result = (2.0 + 2.0i) / b; REQUIRE(result == 2.0 + 0.0i); // result = a / 1.0i; } SECTION("should be able to multiply") { sym::Complex result; result = a * b; REQUIRE(result == 0.0 + 4.0i); result = a * (1.0 + 1.0i); REQUIRE(result == 0.0 + 4.0i); result = (2.0 + 2.0i) * b; REQUIRE(result == 0.0 + 4.0i); // result = a * 1.0i; result = inv(a); REQUIRE(result == 0.25 - 0.25i); } SECTION("should be able to subtract") { sym::Complex result; result = a - b; REQUIRE(result == 1.0 + 1.0i); result = a - (1.0 + 1.0i); REQUIRE(result == 1.0 + 1.0i); result = (2.0 + 2.0i) - b; REQUIRE(result == 1.0 + 1.0i); // result = a - 1.0i; result = -a + b; REQUIRE(result == -1.0 - 1.0i); result = a - -b; REQUIRE(result == 3.0 + 3.0i); } }
true
448f9187fff8d6750be7562db6917c83f0adcedc
C++
acerNZ/HAL
/HAL/IMU/Drivers/Phidgets/PhidgetsDriver.cpp
UTF-8
5,792
2.625
3
[ "Apache-2.0" ]
permissive
#include "PhidgetsDriver.h" #include <sys/time.h> #include <HAL/Utils/TicToc.h> namespace hal { //callback that will run if the Spatial is attached to the computer int CCONV AttachHandler(CPhidgetHandle spatial, void *userptr) { ((PhidgetsDriver *)userptr)->_AttachHandler(spatial); return 0; } //callback that will run if the Spatial is detached from the computer int CCONV DetachHandler(CPhidgetHandle spatial, void *userptr) { ((PhidgetsDriver *)userptr)->_DetachHandler(spatial); return 0; } //callback that will run if the Spatial generates an error int CCONV ErrorHandler(CPhidgetHandle spatial, void *userptr, int ErrorCode, const char *unknown) { ((PhidgetsDriver *)userptr)->_ErrorHandler(spatial,ErrorCode,unknown); return 0; } //callback that will run at datarate //data - array of spatial event data structures that holds the spatial data packets that were sent in this event //count - the number of spatial data event packets included in this event int CCONV SpatialDataHandler(CPhidgetSpatialHandle spatial, void *userptr, CPhidgetSpatial_SpatialEventDataHandle *data, int count) { ((PhidgetsDriver *)userptr)->_SpatialDataHandler(spatial,data,count); return 0; } } /* namespace */ using namespace hal; /////////////////////////////////////////////////////////////////////////// PhidgetsDriver::PhidgetsDriver() : m_hSpatial(0) { Init(); } /////////////////////////////////////////////////////////////////////////// PhidgetsDriver::~PhidgetsDriver() { //since user input has been read, this is a signal to terminate the program so we will close the phidget and delete the object we created CPhidget_close((CPhidgetHandle)m_hSpatial); CPhidget_delete((CPhidgetHandle)m_hSpatial); } /////////////////////////////////////////////////////////////////////////// void PhidgetsDriver::_AttachHandler(CPhidgetHandle spatial) { //Set the data rate for the spatial events int minRate; CPhidgetSpatial_getDataRateMax((CPhidgetSpatialHandle)spatial,&minRate); CPhidgetSpatial_setDataRate((CPhidgetSpatialHandle)spatial, minRate); // int serialNo; // CPhidget_getSerialNumber(spatial, &serialNo); // printf("Spatial %10d attached!", serialNo); } /////////////////////////////////////////////////////////////////////////// void PhidgetsDriver::_DetachHandler(CPhidgetHandle /*spatial*/) { // int serialNo; // CPhidget_getSerialNumber(spatial, &serialNo); // printf("Spatial %10d detached! \n", serialNo); } /////////////////////////////////////////////////////////////////////////// void PhidgetsDriver::_ErrorHandler(CPhidgetHandle /*spatial*/, int ErrorCode, const char *unknown) { printf("Phidgets Driver: Error handled. %d - %s \n", ErrorCode, unknown); } /////////////////////////////////////////////////////////////////////////// void PhidgetsDriver::_SpatialDataHandler(CPhidgetSpatialHandle /*spatial*/, CPhidgetSpatial_SpatialEventDataHandle *data, int count) { int i; /* printf("Number of Data Packets in this event: %d\n", count); for(i = 0; i < count; i++) { printf("=== Data Set: %d ===\n", i); printf("Acceleration> x: %6f y: %6f x: %6f\n", data[i]->acceleration[0], data[i]->acceleration[1], data[i]->acceleration[2]); printf("Angular Rate> x: %6f y: %6f x: %6f\n", data[i]->angularRate[0], data[i]->angularRate[1], data[i]->angularRate[2]); printf("Magnetic Field> x: %6f y: %6f x: %6f\n", data[i]->magneticField[0], data[i]->magneticField[1], data[i]->magneticField[2]); printf("Timestamp> seconds: %d -- microseconds: %d\n", data[i]->timestamp.seconds, data[i]->timestamp.microseconds); } printf("---------------------------------------------\n"); /**/ for(i = 0; i < count; i++){ hal::ImuMsg imuData; hal::VectorMsg* pbVec = imuData.mutable_accel(); pbVec->add_data(data[i]->acceleration[0]); pbVec->add_data(data[i]->acceleration[1]); pbVec->add_data(data[i]->acceleration[2]); pbVec = imuData.mutable_gyro(); pbVec->add_data(data[i]->angularRate[0]); pbVec->add_data(data[i]->angularRate[1]); pbVec->add_data(data[i]->angularRate[2]); pbVec = imuData.mutable_mag(); pbVec->add_data(data[i]->magneticField[0]); pbVec->add_data(data[i]->magneticField[1]); pbVec->add_data(data[i]->magneticField[2]); imuData.set_system_time(hal::Tic()); imuData.set_device_time(data[i]->timestamp.seconds + data[i]->timestamp.microseconds * 1E-6); if( m_ImuCallback ) { m_ImuCallback(imuData); } } } /////////////////////////////////////////////////////////////////////////// bool PhidgetsDriver::Init() { //create the spatial object CPhidgetSpatial_create(&m_hSpatial); //Set the handlers to be run when the device is plugged in or opened from software, unplugged or closed from software, or generates an error. CPhidget_set_OnAttach_Handler((CPhidgetHandle)m_hSpatial, AttachHandler, this); CPhidget_set_OnDetach_Handler((CPhidgetHandle)m_hSpatial, DetachHandler, this); CPhidget_set_OnError_Handler((CPhidgetHandle)m_hSpatial, ErrorHandler, this); //Registers a callback that will run according to the set data rate that will return the spatial data changes //Requires the handle for the Spatial, the callback handler function that will be called, //and an arbitrary pointer that will be supplied to the callback function (may be NULL) CPhidgetSpatial_set_OnSpatialData_Handler(m_hSpatial, SpatialDataHandler, this); //open the spatial object for device connections CPhidget_open((CPhidgetHandle)m_hSpatial, -1); return true; } /////////////////////////////////////////////////////////////////////////// void PhidgetsDriver::RegisterIMUDataCallback(IMUDriverDataCallback callback) { m_ImuCallback = callback; }
true
4f82c42979f81e0d5ffc57f942ebf206f33e84c8
C++
ArturKnopik/Game
/Learn_Game/Arkanoid_Level.cpp
UTF-8
706
2.640625
3
[]
no_license
#include "Arkanoid_Level.h" void Arkanoid::Level::addBlock(std::shared_ptr<Arkanoid::Block> block) { blockList.push_back(block); } Arkanoid::Level::Level() { blockList.clear(); for (int i = 0; i < 6; i++) { for (int j = 0; j < 9; j++) { addBlock(std::shared_ptr<Block>(new Block(sf::Vector2f(40+j*100, 50+i*40), sf::Vector2f(90, 30), 2))); } } } Mario::Level::Level(std::string name) :name(name) { } void Mario::Level::getLevelName() { name; } std::shared_ptr<Arkanoid::Level> Arkanoid::Level::getNextLevel() { return std::shared_ptr<Arkanoid::Level>(new Arkanoid::Level()); } std::vector<std::shared_ptr<Arkanoid::Block>> Arkanoid::Level::getBlockList() { return blockList; }
true
5b202b84e11b29b8c092619b59f2eab7e76114d6
C++
mseefelder/mbv
/mbv-utils.h
UTF-8
8,348
3.4375
3
[]
no_license
#include <limits> #include <iostream> #include <forward_list> #include <utility> #include <algorithm> #include <chrono> using namespace std; struct UnionOperation{ int parent; int child; bool increasedParentRank; UnionOperation(): parent(0), child(0), increasedParentRank(false){} UnionOperation(int p, int c, bool i): parent(p), child(c), increasedParentRank(i){} }; class UnionFind{ private: int* parent; int* rank; int elementCount; int disjointSetCount; int findSet (int x) { int top = x; while(parent[top] != top) { top = parent[top]; } return top; } public: UnionFind() : parent(nullptr), elementCount(0), disjointSetCount(0) { } UnionFind(int n) : elementCount(n), disjointSetCount(n) { parent = new int[elementCount]; rank = new int[elementCount]; for (int i = 0; i < elementCount; ++i) { parent[i] = i; rank[i] = 0; } } ~UnionFind() { if(parent){ delete [] parent; } if (rank) { delete [] rank; } } void printElements() { for (int i = 0; i < elementCount; ++i) { cout<<parent[i]<<","; } cout<<endl; } bool unionSet (int x, int y, UnionOperation &op) { int setX = findSet(x); int setY = findSet(y); if(setX == setY) { return false; } if(rank[setX] > parent[setY]){ parent[setY] = setX; op = UnionOperation(setX,setY,false); } else{ parent[setX] = setY; rank[setY]++; op = UnionOperation(setY,setX,true); } disjointSetCount--; return true; } void undoUnion(UnionOperation &op) { parent[op.child] = op.child; if(op.increasedParentRank){ rank[op.parent]--; } disjointSetCount++; return; } int getElementCount() { return elementCount; } int getElement(int e) { return parent[e]; } int getDisjointSetCount() { printElements(); return disjointSetCount; } }; class Graph { public: //For every vertex, a forward_list of edges it's connected to forward_list<int>* vertices; //A list with all the edges pair<int, int>* edges; //A list with vertex degrees int* vertexDegrees; //Sizes int nVertices, mEdges; //Amount of edges already added int addedEdges; Graph() : vertices(nullptr), edges(nullptr), vertexDegrees(nullptr), nVertices(0), mEdges(0), addedEdges(0) {} Graph(int n, int m) : nVertices(n), mEdges(m), addedEdges(0) { vertices = new forward_list<int>[nVertices]; vertexDegrees = new int[nVertices]; edges = new pair<int, int>[mEdges]; for (int i = 0; i < nVertices; ++i) { vertexDegrees[i] = 0; } } void addEdge(int u, int v) { if(addedEdges == mEdges) { //cout<<"Already added all edges"<<endl; } edges[addedEdges] = pair<int, int>(u, v); vertices[u].push_front(addedEdges); vertexDegrees[u]++; vertices[v].push_front(addedEdges); vertexDegrees[v]++; addedEdges++; } }; class sort_indices { private: float* valueArr; public: sort_indices(float* arr) : valueArr(arr) {} bool operator()(int i, int j) const { return valueArr[i]<valueArr[j]; } }; class MBVSolutionUndo { private: public: int branchVertexCount, activeEdgeCount; UnionFind* vertexConnected; int* edgeState; float* edgeWeight; int* edgeIndex; int* vertexDegrees; int* vertexProhibitedDegrees; UnionOperation* unionsList; int unionCounter; int* unionEdges; Graph *G; float* relaxedSolution; int currentRelaxedSolution; float constantRelaxedSubtractor; MBVSolutionUndo(Graph &sourceGraph) : G(&sourceGraph), branchVertexCount(0), activeEdgeCount(0), unionCounter(0), currentRelaxedSolution(0), constantRelaxedSubtractor(0.0) { vertexDegrees = new int[G->nVertices]; vertexProhibitedDegrees = new int[G->nVertices]; vertexConnected = new UnionFind(G->nVertices); edgeState = new int[G->mEdges]; edgeWeight = new float[G->mEdges]; edgeIndex = new int[G->mEdges]; unionsList = new UnionOperation[G->nVertices-1]; unionEdges = new int[G->nVertices-1]; relaxedSolution = new float[G->nVertices]; int deg = 0; for (int v = 0; v < G->nVertices; ++v) { vertexDegrees[v] = 0; vertexProhibitedDegrees[v] = 0; relaxedSolution[v] = 0.0; } for (int e = 0; e < G->mEdges; ++e) { edgeState[e] = 0; edgeWeight[e] = 0.0; edgeIndex[e] = e; } //sort sortEdges(); //cout<<"Sorted!"<<endl; } MBVSolutionUndo(int bvc) : G(nullptr), branchVertexCount(bvc), activeEdgeCount(0) {} ~MBVSolutionUndo() { /**/ //if (vertexConnected) //{ // delete vertexConnected; //} if (edgeState) { delete [] edgeState; } if (vertexDegrees) { delete [] vertexDegrees; } if (edgeWeight) { delete [] edgeWeight; } if (edgeIndex) { delete [] edgeIndex; } /**/ } void sortEdges() { int deg = 0; int v = 0; //Calculate edge weights for (int e = 0; e < G->mEdges; ++e) { edgeIndex[e] = e; edgeWeight[e] = 0.0; //Prepare "heuristic" weights for sorting v = G->edges[e].first; deg = G->vertexDegrees[v] - vertexProhibitedDegrees[v]; if(deg > 2) { edgeWeight[e] += 1.0/deg; } v = G->edges[e].second; deg = G->vertexDegrees[v] - vertexProhibitedDegrees[v]; if(deg > 2) { edgeWeight[e] += 1.0/deg; } } //Calculate constant weight subtractor constantRelaxedSubtractor = 0.0; for (int v = 0; v < G->nVertices; ++v) { deg = G->vertexDegrees[v] - vertexProhibitedDegrees[v]; if(deg > 2) { constantRelaxedSubtractor += 2.0/deg; } } //sort sort(edgeIndex, edgeIndex+G->mEdges, sort_indices(edgeWeight)); } int getEdgeState(int e) { return edgeState[e]; } bool activateEdge(int e) { if(edgeState[e] != 0) { return false; } //Vertices connected by edge int u = G->edges[e].first; int v = G->edges[e].second; UnionOperation op; bool doesntMakeCycle = vertexConnected->unionSet(u, v, op); //If this forms a cycle end with false if(!doesntMakeCycle){ return false; } //store last union unionsList[unionCounter] = op; unionEdges[unionCounter] = e; unionCounter++; //activate edge edgeState[e] = 1; activeEdgeCount++; relaxedSolution[currentRelaxedSolution + 1] = relaxedSolution[currentRelaxedSolution] + edgeWeight[e]; currentRelaxedSolution++; //Update branch vertice count if(vertexDegrees[u] == 2) { branchVertexCount++; } if(vertexDegrees[v] == 2) { branchVertexCount++; } //Increase vertices' degrees vertexDegrees[u]++; vertexDegrees[v]++; /* cout<<" activate ["; for (int i = 0; i < G->mEdges; i++) { cout<<i<<": "<<edgeState[i]<<", "; } cout<<"]"<<endl; */ return true; } void undoActivateEdge() { unionCounter--; vertexConnected->undoUnion(unionsList[unionCounter]); //deactivate edge int e = unionEdges[unionCounter]; edgeState[e] = 0; activeEdgeCount--; currentRelaxedSolution--; //Decrease vertices' degrees //Vertices connected by edge int u = G->edges[e].first; int v = G->edges[e].second; vertexDegrees[u]--; vertexDegrees[v]--; //Update branch vertice count if(vertexDegrees[u] == 2) { branchVertexCount--; } if(vertexDegrees[v] == 2) { branchVertexCount--; } /* cout<<"deactivate ["; for (int i = 0; i < G->mEdges; i++) { cout<<i<<": "<<edgeState[i]<<", "; } cout<<"]"<<endl; */ } void prohibitEdge(int e) { //Vertices connected by edge int u = G->edges[e].first; int v = G->edges[e].second; vertexProhibitedDegrees[u]++; vertexProhibitedDegrees[v]++; edgeState[e] = -1; /* cout<<" prohibit ["; for (int i = 0; i < G->mEdges; i++) { cout<<i<<": "<<edgeState[i]<<", "; } cout<<"]"<<endl; */ } void undoProhibitEdge(int e) { //Vertices connected by edge int u = G->edges[e].first; int v = G->edges[e].second; vertexProhibitedDegrees[u]--; vertexProhibitedDegrees[v]--; edgeState[e] = 0; /* cout<<"unprohibit ["; for (int i = 0; i < G->mEdges; i++) { cout<<i<<": "<<edgeState[i]<<", "; } cout<<"]"<<endl; */ } int getBranchVertexCount() { return branchVertexCount; } int getActiveEdgeCount() { return activeEdgeCount; } int getDisjointSetCount() { return vertexConnected->getDisjointSetCount(); } float getRelaxedSolution() { return relaxedSolution[currentRelaxedSolution] - constantRelaxedSubtractor; } };
true
bbe87f18d66f89086b63cad1477e933a8f98cd3e
C++
chanchoi829/simulation
/include/Model.h
UTF-8
5,504
3.390625
3
[]
no_license
/* Model is part of a simplified Model-View-Controller pattern. Model keeps track of the Sim_objects in our little world. It is the only component that knows how many Islands and Ships there are, but it does not know about any of their derived classes, nor which Ships are of what kind of Ship. It has facilities for looking up objects by name, and removing Ships. When created, it creates an initial group of Islands and Ships using the Ship_factory. Finally, it keeps the system's time. Controller tells Model what to do; Model in turn tells the objects what do, and when asked to do so by an object, tells all the Views whenever anything changes that might be relevant. Model also provides facilities for looking up objects given their name. */ #ifndef MODEL_H #define MODEL_H #include <map> #include <memory> #include <set> #include <string> #include <vector> struct Point; class Sim_object; class Island; class Ship_component; class Ship; class View; class Model { public: // Getters int get_time() const { return time; } std::map<std::string, std::shared_ptr<Island>> get_island_map() { return island_map; } std::map<std::string, std::shared_ptr<Ship>> get_ship_map() { return ship_map; } // Will throw Error("Island not found!") if no island of that name std::shared_ptr<Island> get_island_ptr(const std::string& name) const; // Returns nullptr if there is no ship of that name std::shared_ptr<Ship> get_ship_ptr(const std::string& name) const; std::shared_ptr<Ship_component> get_ship_composite_ptr(const std::string& name) const; // tell all objects to describe themselves void describe() const; // increment the time, and tell all objects to update themselves void update(); // Add a new ship to the containers, and update the view // Throws Error if there is already a Ship or Island with that name. // If insertion fails for any exception, the pointed-to Ship is deleted // and the exception rethrown. void add_ship(std::shared_ptr<Ship> new_ship); // Add a Ship_composite to ship_component_map // Throw an Error when the Ship_composite's name is a duplicate name void add_composite(std::shared_ptr<Ship_component> new_group); // Add a Ship to an existing Ship_composite // Throw an Error when composite or ship does not exist, or when ship is // being added to a Ship_composite whose top Ship_composite already // has the ship. void add_ship_to_composite(const std::string& composite, std::shared_ptr<Ship_component> ship); // Create a Ship_composite and add it to an existing Ship_composite. void add_composite_to_composite(const std::string& composite, std::shared_ptr<Ship_component> composite_in); // Remove a Ship_composite void remove_composite(const std::string& group_to_remove); // Find a Ship_composite with the given string // and remove the given Ship from the Ship_composite void remove_ship_from_composite(const std::string& composite, const std::string& ship_name); // Describe Ship_components in ship_component_map. // Indexing indicates the hierarchy // e.g. // Favorites // Warships // Cruisers // Ajax // Torpedoboats void describe_composite() const; /* View services */ // Attaching a View adds it to the container and causes it to be updated // with all current objects'location (or other state information. void attach(std::shared_ptr<View>); // Detach the View by discarding the supplied pointer from the container of Views // - no updates sent to it thereafter. void detach(std::shared_ptr<View>); // notify the views about an object's location void notify_location(const std::string& name, Point location); // notify the views that an object is now gone void notify_gone(const std::string& name); // notify the Views about a Ship's fuel void notify_view_about_ship_fuel(const std::string& name, double fuel) const; // notify the Views about a Ship's course void notify_view_about_ship_course(const std::string& name, double course) const; // notify the Views about a Ship's speed void notify_view_about_ship_speed(const std::string& name, double speed) const; // Remove a Ship from sim_object_map and ship_map void remove_ship(std::shared_ptr<Ship> ship_ptr); // Find a Ship_composite with the given name std::shared_ptr<Ship_component> find_composite_ptr(const std::string& name); // Check if name conflicts with another Island, Ship, or Ship_composite's name. // Throw an Error if it does. void check_if_name_duplicate(const std::string& name); // For Singleton static Model& get_instance(); // disallow copy/move construction or assignment Model(Model& obj) = delete; Model(Model&& obj) = delete; Model& operator=(Model& obj) = delete; Model& operator=(Model&& obj) = delete; private: // create the initial objects Model(); ~Model() { } int time; // the simulated time std::map<std::string, std::shared_ptr<Sim_object>> sim_object_map; std::map<std::string, std::shared_ptr<Ship>> ship_map; std::map<std::string, std::shared_ptr<Island>> island_map; std::map<std::string, std::shared_ptr<Ship_component>> ship_component_map; std::set<std::string> ship_composite_names; std::vector<std::shared_ptr<View>> view_vec; }; #endif
true
99ca1a151422002cefaf3aa16da83390c206d8c8
C++
Neum9/LearnOpenGL
/TextureTest/Shader.cpp
UTF-8
2,677
3.0625
3
[]
no_license
#include "Shader.h" Shader::Shader(const GLchar * vertexPath, const GLchar * fragmentPath) { //read shader from file path string vertexCode; string fragmentCode; ifstream vShaderFile; ifstream fShaderFile; //assure ifstream can catch exception vShaderFile.exceptions(ifstream::failbit | ifstream::badbit); fShaderFile.exceptions(ifstream::failbit | ifstream::badbit); try { //open file vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); stringstream vShaderStream, fShaderStream; //ready the content to data buffer stream vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); //close stream vShaderFile.close(); fShaderFile.close(); //convert data stream to string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); } catch (const std::exception&) { cout << "ERROR::SAHDER::FILE_NOT_SUCCESSFULLY_READ" << endl; } const char* vShaderCode = vertexCode.c_str(); const char* fShaderCode = fragmentCode.c_str(); //compile shader unsigned int vertex, fragment; int success; char infoLog[512]; //vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); //log compile error glGetShaderiv(vertex, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertex, 512, NULL, infoLog); cout << "ERROR::SHADER::VERTEX::COMPILE_FAILED\n" << infoLog << endl; } //fragment shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); //log compile error glGetShaderiv(fragment, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragment, 512, NULL, infoLog); cout << "ERROR::SHADER::FRAGMENT::COMPILE_FAILED\n" << infoLog << endl; } //shader program ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); glLinkProgram(ID); //log error glGetProgramiv(ID, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(ID, 512, NULL, infoLog); cout << "ERROR::SHADER::SHADER::PROGRAM::LINKING_FAILED" << infoLog << endl; } //shader has link to the program,so never need it! glDeleteShader(vertex); glDeleteShader(fragment); } void Shader::use() { glUseProgram(ID); } void Shader::setBool(const string & name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } void Shader::setInt(const string & name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } void Shader::setFloat(const string & name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); }
true
9aafef4f94243f2bea6da6b301443e37d140c80e
C++
ParticularJ/interview
/leetcode148.cpp
GB18030
1,871
4.09375
4
[]
no_license
/* merge_sort : 鲢 top_downݹ鷨: time complexity: O(nlogn) space complexicity O(logn) 1 ռ䣬ʹСΪѾ֮ͣÿռźϲ 2 趨ָ룬 λ÷ֱΪѾеʼλ 3 ȽָָԪأѡСԪط뵽ϲռ䣬ƶָ뵽һλ 4 ظ3β 5 һʣµԪֱӸƵϲβ bottom up: time : O(nlogn) space O(1) 1 ÿֽй鲢 γɣn/2У 2 вΪ1ٴι鲢 3 ظ2 ֪ */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: // ݹⷽ space O(logn) ListNode* sortList1(ListNode* head) { if (head == NULL||head->next==NULL)return head; ListNode* fast = head->next; ListNode* slow = head; // ָ룬жϿָպλм䡣 while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } //жϿ ListNode* mid = slow->next; slow->next = nullptr; return mergesort(sortList(head), sortList(mid)); } ListNode* mergesort(ListNode* l1, ListNode* l2) { //ܽ ListNode dummy(0); ListNode* tail = &dummy; while (l1 && l2) { if (l1->val > l2->val)swap(l1, l2); // tailָheadڵ tail->next = l1; // ֱƶһλ l1 = l1->next; tail = tail->next; } if (l1)tail->next = l1; if (l2)tail->next = l2; return dummy.next; public: //ⷽ space O(1) ListNode* sortList2(ListNode* head) { } } };
true
7bf4831c858255bc43afb10763e6f1f6b89a1c39
C++
mkrivos/astlib
/astlib/AsterixItemCode.h
UTF-8
1,250
2.71875
3
[ "MIT" ]
permissive
/// /// \package astlib /// \file AsterixItemCode.h /// /// \author Marian Krivos <nezmar@tutok.sk> /// \date 13. 2. 2017 - 19:49:36 /// /// (C) Copyright 2017 R-SYS,s.r.o /// All rights reserved. /// #pragma once #include "GeneratedTypes.h" #include "Astlib.h" namespace astlib { /** * Class that encapsulate unique asterix pair<item id, item type>. * Use this class with generated codes ASTERIX_CODE_* to identification of decoded asterix items. */ struct AsterixItemCode { constexpr AsterixItemCode(Poco::UInt32 value = 0) : value(value) {} constexpr AsterixItemCode(const AsterixItemCode& old ) : value(old.value) {} constexpr AsterixItemCode(int code, int type, bool array = false) : value((array << 31) | (type << 24) | (code & 0x0FFF)) { } constexpr int code() const { return value & 0xFFF; } constexpr int type() const { return (value>>24) & 0xF; } constexpr bool isArray() const { return bool(value & 0x80000000); } constexpr bool isValid() const { return value != 0; } const Poco::UInt32 value = 0; }; inline bool operator < (const AsterixItemCode left, const AsterixItemCode right) { return left.value < right.value; } }
true
8e05f53bfc34ebeb4d6df527b4ee7249d50a9659
C++
prprprpony/oj
/uva/122.cpp
UTF-8
2,253
3.375
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <queue> using namespace std; bool error; struct Node { int val; Node *child[2]; Node() { val = -1; for (int i = 0 ; i < 2; ++i) child[i] = NULL; } int index(char c) { switch (c) { case 'L': return 0; break; case 'R': return 1; break; case ')': return -1; break; } } void add(char* pos, const int& v) { int i = index(*pos); if (i != -1) { if (child[i] == NULL) child[i] = new Node; child[i]->add(pos + 1, v); } else { if (val == -1) val = v; else error = true; } } void clear() { for (int i = 0; i < 2; ++i) { if (child[i] != NULL) { child[i]->clear(); delete child[i]; child[i] = NULL; } } val = -1; } bool complete() { if (val == -1) return false; for (int i = 0 ; i < 2; ++i) if (child[i] != NULL) if (!child[i]->complete()) return false; return true; } }; int main() { char buf[300]; int v; char *pos; Node root; Node* it; while (scanf("%s", buf) == 1) { if (buf[1] != ')') { sscanf(buf+1, "%d", &v); for (pos = buf; *pos != ','; ++pos); root.add(pos + 1, v); } else { if (error || !root.complete()) printf("not complete\n"); else { queue<Node*> q; q.push(&root); while (!q.empty()) { it = q.front(); q.pop(); for (int i = 0; i < 2; ++i) if (it->child[i] != NULL) q.push(it->child[i]); printf("%d", it->val); putchar(!q.empty() ? ' ' : '\n'); } } error = false; root.clear(); } } return 0; }
true
55553bef95e6bf701c24c2adda5a33d39acd0ba8
C++
texaszn/CS-2315
/lab45.cpp
UTF-8
2,769
3.296875
3
[]
no_license
// Zach Nadeau // CS 2315 // Lab 45 #include <cstdlib> #include <cmath> #include <cctype> #include <lab45.h> using namespace std; const bool DEBUG = false; void printDebug(const BigInt&); BigInt::BigInt() { // constructor digits = 0 this->sign = ZERO; this->digits.push_back('0'); printDebug(*this); } BigInt::BigInt( int num ) { // constructor digits = num if (num == 0) { this->sign = ZERO; this->digits.push_back('0'); printDebug(*this); return; } else if (num < 0) { this->sign = NEGATIVE; num *= -1; } else { this->sign = POSITIVE; } while (num > 0) { this->digits.push_back((num % 10) + '0'); num /= 10; } printDebug(*this); } BigInt::BigInt( const string str ) { // constructor digits = str uint n = str.size(); if (fsaForInt(str) == 0) { // fsa = finite state automata this->sign = ZERO; this->digits.push_back('0'); printDebug(*this); return; } else { this->sign = POSITIVE; for (uint i = 0; i < n; i++) { if (str.at(i) == '-') this->sign = NEGATIVE; else if (isdigit(str.at(i))) this->digits.push_front(str.at(i)); } while (!this->digits.empty() && this->digits.back() == '0') this->digits.pop_back(); if (this->digits.empty()) { this->sign = ZERO; this->digits.push_back('0') } printDebug(*this); } } BigInt::BigInt( const BigInt& other ) { // copy constructor this->sign = other.sign; this->digits = other.digits; printDebug(*this); } bool BigInt::operator==( const BigInt& rhs ) const { // Equality typename list<char>::const_iterator i = this->digits.begin(), j = rhs.digits.begin(); if ((this->digits.size() != rhs.digits.size()) || (this->sign != rhs.sign)) return false; while (i != this->digits.end()) { if (*i != *j) return false; ++i; ++j; } return true; } bool BigInt::operator< ( const BigInt& rhs ) const { // Less Than auto i = this->digits.rbegin(), j = rhs.digits.rbegin(); if (this->sign > rhs.sign) return false; else if (this->sign < rhs.sign) return true; if (this->sign == ZERO) return false; else if (this->sign == POSITIVE) { if (this->digits.size() != rhs.digits.size()) return this->digits.size() < rhs.digits.size(); while (i != this->digits.rend()) { if (*i > *j) return false; if (*i < *j) return true; ++i; ++j; } } else { if (this->digits.size() != rhs.digits.size()) return this->digits.size() > rhs.digits.size(); while (i != this->digits.rend()) { if (*i < *j) return false; if (*i > *j) return true; ++i; ++j; } } return false; } void printDebug(const BigInt& a) { if (DEBUG) cout << /* a.sign << */ " " << a << endl; }
true
dcbc271ecffe8f23de6caab1b85869877658c492
C++
kapil8882001/Coding-Practice-1
/C++ Solutions/Design/LC716_MaxStack.cpp
UTF-8
1,813
4.09375
4
[]
no_license
// 716. Max Stack /* Design a max stack that supports push, pop, top, peekMax and popMax. push(x) -- Push element x onto stack. pop() -- Remove the element on top of the stack and return it. top() -- Get the element on the top. peekMax() -- Retrieve the maximum element in the stack. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one. Example 1: MaxStack stack = new MaxStack(); stack.push(5); stack.push(1); stack.push(5); stack.top(); -> 5 stack.popMax(); -> 5 stack.top(); -> 1 stack.peekMax(); -> 5 stack.pop(); -> 1 stack.top(); -> 5 Note: -1e7 <= x <= 1e7 Number of operations won't exceed 10000. The last four operations won't be called when stack is empty. */ class MaxStack { public: /** initialize your data structure here. */ MaxStack() { } void push(int x) { data.insert(data.begin(), x); mp[x].push_back(data.begin()); } int pop() { int x = *data.begin(); mp[x].pop_back(); if (mp[x].empty()) mp.erase(x); data.erase(data.begin()); return x; } int top() { return *data.begin(); } int peekMax() { return mp.rbegin()->first; } int popMax() { int x = mp.rbegin()->first; list<int>::iterator iter = mp[x].back(); mp[x].pop_back(); if (mp[x].empty()) mp.erase(x); data.erase(iter); return x; } private: list<int> data; map<int, vector<list<int>::iterator>> mp; }; /** * Your MaxStack object will be instantiated and called as such: * MaxStack obj = new MaxStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.peekMax(); * int param_5 = obj.popMax(); */
true
fe1c7af5ba73c3c2e727aa4e13c016a6187c8cac
C++
CuzzImBatman/CS162-19APCS2-DEADLINE-POWER-1
/Project/functionAllRoles.cpp
UTF-8
11,482
3.46875
3
[]
no_license
#include "function.h" int login(AcademicYears* year, Accounts*& acc, string pwd) { if (acc->uName[0] <= 57) { //student SHA256_CTX check; sha256_init(&check); sha256_update(&check, pwd, pwd.length()); Classes* tempClass = year->classes; while (tempClass) { Students* tempSt = tempClass->students; while (tempSt) { if (tempSt->account->uName == acc->uName) if (ComparePwd( tempSt->account->pwd, check)) { delete acc; acc = tempSt->account; return 1; } else { //cout << "Wrong password." << endl; return 0; } tempSt = tempSt->next; } tempClass = tempClass->next; } //cout << "Wrong username." << endl; return 0; } else { //staff or lecturer SHA256_CTX check; sha256_init(&check); sha256_update(&check, pwd, pwd.length()); Semesters* tempSemes = year->semesters; while (tempSemes) { Staffs* tempStaff = tempSemes->staffs; while (tempStaff) { if (tempStaff->account->uName == acc->uName) if ( ComparePwd(tempStaff->account->pwd , check) ) { delete acc; acc = tempStaff->account; return 2; } else { //cout << "Wrong password." << endl; return 0; } tempStaff = tempStaff->next; } Lecturers* tempLec = tempSemes->lecturers; while (tempLec) { if (tempLec->account->uName == acc->uName) if (ComparePwd(tempLec->account->pwd ,check)) { delete acc; acc = tempLec->account; return 3; } else { //cout << "Wrong password." << endl; return 0; } tempLec = tempLec->next; } tempSemes = tempSemes->next; } //cout << "Wrong username." << endl; return 0; } } void showClassOptions(AcademicYears*& year) { int choice; bool variableName = 1; while (variableName) { cout << endl << "Sub menu: What do you want to do? " << endl; cout << "[1] Import students from a csv file." << endl; cout << "[2] Manually add a new student to a class." << endl; cout << "[3] Edit an existing student." << endl; cout << "[4] Remove a student." << endl; cout << "[5] Change students from class A to class B." << endl; cout << "[6] View list of classes." << endl; cout << "[7] View list of students in a class." << endl; cout << "[8] Back." << endl; cout << "Your choice: "; cin >> choice; switch (choice) { case 1: { importAClassFromCsvFile(year->classes); break; } case 2: { addAStudentToAClass(year->classes); break; } case 3: { editAStudent(year->classes); break; } case 4: { removeAStudent(year->classes, year->semesters->courses, year->semesters->semesterNo, year->year); break; } case 5: { changeClassForStudents(year->classes, year->semesters->courses, year->semesters->semesterNo, year->year); break; } case 6: { viewListOfClasses(year); break; } case 7: { viewListOfStudentsInAClass(year); break; } case 8: variableName = 0; default: break; } } } void showCourseOptions(AcademicYears*& year) { int choice; bool variableName = 1; AcademicYears* y = nullptr; while (variableName) { cout << endl << "Sub menu: What do you want to do? " << endl; cout << "[1] Create/update/delete/view academic years, and semesters." << endl; cout << "[2] From a semester, import courses from a csv file." << endl; cout << "[3] Manually add a new course." << endl; cout << "[4] Edit an existing course." << endl; cout << "[5] Remove a course." << endl; cout << "[6] Remove a specific student from a course." << endl; cout << "[7] Add a specific student to a course." << endl; cout << "[8] View list of courses in the current semester." << endl; cout << "[9] View list of students of a course." << endl; cout << "[10] View attendance list of a course." << endl; cout << "[11] Create/update/delete/view all lecturers." << endl; cout << "[12] Back." << endl; cout << "Your choice: "; cin >> choice; switch (choice) { case 1: { cout << endl << "Sub menu: What do you want to do?" << endl << "[1] Create an academic year." << endl << "[2] Edit an academic year." << endl << "[3] Delete an academic year." << endl << "[4] View all academic year." << endl << "Your choice: "; cin >> choice; switch (choice) { case 1: { createAcademicYear(year); break; } case 2: { updateAcademicYear(year); break; } case 3: { deleteAcademicYear(year); break; } case 4: { viewAcademicYear(year); break; } default: break; } break; } case 2: { ImportCourseFromCsv(year); break; } case 3: { AddCourse(year); break; } case 4: { EditCourse(year); break; } case 5: { DeleteCourse(year); break; } case 6: { RemovedStudentFromCourseClass(year); break; } case 7: { AddStudentToCourseClass(year); break; } case 8: { viewCourseOfSemester(year); break; } case 9: { View_StudentList_Course(year); break; } case 10: { View_Attendance_List(year); break; } case 11: { cout << endl << "Sub menu: What do you want to do?" << endl << "[1] Create a new lecturer." << endl << "[2] Edit a lecturer." << endl << "[3] Delete a lecturer." << endl << "[4] View all lecturers." << endl << "Your choice: "; cin >> choice; switch (choice) { case 1: { createLecturer(year); break; } case 2: { updateLecturer(year); break; } case 3: { deleteLecturer(year); break; } case 4: { viewLecturer(year); break; } default: break; } break; } case 12: variableName = 0; default: break; } } } void showScoreboardOptions(AcademicYears*& year) { int choice; bool variableName = 1; while (variableName) { cout << endl << "Sub menu: What do you want to do? " << endl; cout << "[1] Search and view the scoreboard of a course." << endl; cout << "[2] Export a scoreboard to a csv file." << endl; cout << "[3] Back." << endl; cout << "Your choice: "; cin >> choice; switch (choice) { case 1: { ViewAScoreboard(year); break; } case 2: { Export_ScoreBoard(year); break; } case 3: variableName = 0; default: break; } } } void showAttendanceListOptions(AcademicYears*& year) { int choice; bool variableName = 1; while (variableName) { cout << endl << "Sub menu: What do you want to do? " << endl; cout << "[1] Search and view attendance list of a course." << endl; cout << "[2] Export a attendance list to a csv file." << endl; cout << "[3] Back." << endl; cout << "Your choice: "; cin >> choice; switch (choice) { case 1: { ViewAttendanceListOfACourse(year); break; } case 2: { exportAttendanceListOfCourse(year); break; } case 3: variableName = 0; default: break; } } } void showMenu(Accounts*& acc, AcademicYears*& year) { Classes* cl = year->classes; Students* st=cl->students; while (cl) { st = findStudent(cl->students, acc->uName); if(st && st->Status)break; cl = cl->next;; } switch (acc->role) { case 1: { //call student functions int choice; bool variableName = 1; while (variableName) { cout << endl << "Sub menu: What do you want to do? " << endl; cout << "[1] Check-in." << endl; cout << "[2] View check-in result." << endl; cout << "[3] View schedules." << endl; cout << "[4] View my scores of a course." << endl; cout << "[5] Back to main menu." << endl; cout << "Your choice: "; cin >> choice; switch (choice) { case 1: { Tick(st); break; } case 2: { viewCheckIn(st->checkincourse); break; } case 3: { viewSchedule(st); break; } case 4: { viewScoreCourse(st); break; } case 5: variableName = 0; default: break; } } break; } case 3: { //call lecturer functions int choice; bool variableName = 1; while (variableName) { cout << endl << "Sub menu: What do you want to do? " << endl; cout << "[1] View list of courses in the current semester." << endl; cout << "[2] View list of students of a course." << endl; cout << "[3] View attendance list of a course." << endl; cout << "[4] Edit an attendance." << endl; cout << "[5] Import scoreboard of a course from a csv file." << endl; cout << "[6] Edit grade of a student." << endl; cout << "[7] View a scoreboard." << endl; cout << "[8] Back to main menu." << endl; cout << "Your choice: "; cin >> choice; switch (choice) { case 1: { viewCourseOfASemester(year); break; } case 2: { ViewStudentListOfACourse(year); break; } case 3: { ViewAttendanceListOfACourse(year); break; } case 4: { Edit_Attend_List(year,acc); break; } case 5: { ImportScoreBoard( year,acc); break; } case 6: { Edit_ScoreBoard_Student(year,acc); break; } case 7: { ViewAScoreboard(year); break; } case 8: variableName = 0; default: break; } } break; } case 2: { //call staff functions int choice; bool variableName = 1; while (variableName) { cout << endl << "Sub menu: What do you want to do? " << endl; cout << "[1] View class-related options." << endl; cout << "[2] View course-related options." << endl; cout << "[3] View scoreboard-related options." << endl; cout << "[4] View attedance-list-related options." << endl; cout << "[5] Back to main menu." << endl; cout << "Your choice: "; cin >> choice; switch (choice) { case 1: { showClassOptions(year); break; } case 2: { showCourseOptions(year); break; } case 3: { showScoreboardOptions(year); break; } case 4: { showAttendanceListOptions(year); break; } case 5: variableName = 0; default: break; } } break; } default: break; } } bool ComparePwd(SHA256_CTX a, SHA256_CTX b) { for (int i = 0; i < 8; i++) if (a.state[i] != b.state[i])return false; return true; } void changePwd(Accounts*& acc) { SHA256_CTX confirm; string oldPwd, newPwd, conPwd; do { cout << endl << "Type in your old password." << endl; cin >> oldPwd; sha256_init(&confirm); sha256_update(&confirm, oldPwd, oldPwd.length()); if (!ComparePwd(confirm, acc->pwd)) cout << endl << "The old password does not match." << endl; } while (!ComparePwd(confirm, acc->pwd)); do { cout << "Type in your new password." << endl; cin >> newPwd; if (newPwd == oldPwd) cout << endl << "New password cannot be the same as old password." << endl; } while (newPwd == oldPwd); do { cout << "Type in your new password again to confirm." << endl; cin >> conPwd; if(newPwd != conPwd) cout << endl << "The new password does not match with confirm password." << endl; } while (newPwd != conPwd); sha256_init(&acc->pwd); sha256_update(&acc->pwd, conPwd, conPwd.length()); cout << endl << "Password changed." << endl; } void viewProfile(Accounts* acc) { cout << endl << "Your profile: " << endl; cout << "Name: " << acc->lastname << ' ' << acc->firstname << endl; cout << "DoB (dd-mm-yyyy): " << acc->doB->day << '-' << acc->doB->month << '-' << acc->doB->year << endl; cout << "Gender: "; switch (acc->gender) { case 'F': cout << "Female" << endl; break; case 'M': cout << "Male" << endl; break; case 'O': cout << "Other" << endl; break; } cout << "Username: " << acc->uName << endl; cout << endl; } void logout(Accounts*& acc) { acc = nullptr; }
true
96f7ea11685991bda30fdfcf5ddbd3161d2205b5
C++
LeadingIsmi/FA
/Alimov FA8.1/memory.h
UTF-8
1,489
3.125
3
[]
no_license
#pragma once #include <list> #include "memblock.h" using namespace std; class Memory { protected: void* s; size_t size; list<Memblock> memblocks; list<Memblock> available; list<Memblock> unavailable; void sort_list(); virtual void heap_compact() = 0; virtual void deallocate_algorithm(Memblock* block) = 0; virtual Memblock* search_available_memblock(size_t n) const = 0; virtual Memblock* split_memblock(Memblock* block, size_t n) = 0; public: Memory(size_t n); virtual ~Memory(); Memblock* allocate(size_t n); void dealocate(Memblock* block); }; class Memory_allocator1 : public Memory { private: void print_mem(void* s, size_t n, bool is_filled) const; void get_prev_next_neighbours(Memblock* block); protected: void heap_compact() override; void deallocate_algorithm(Memblock* block) override; Memblock* search_available_memblock(size_t n) const override; Memblock* split_memblock(Memblock* block, size_t n) override; public: Memory_allocator1(size_t n) : Memory(n) {} ~Memory_allocator1() {} }; class Memory_allocator2 : public Memory { private: void print_mem(void* s, size_t n) const; protected: void heap_compact() override; void deallocate_algorithm(Memblock* block) override; Memblock* search_available_memblock(size_t n) const override; Memblock* split_memblock(Memblock* block, size_t n) override; public: Memory_allocator2(size_t n) : Memory(n) {} ~Memory_allocator2() {} };
true
69b14a24bb07c0bd961da101ff53b00a4a315dd3
C++
yashart/seminarsded
/binary_translation/binary_file.cpp
UTF-8
3,959
2.984375
3
[]
no_license
// // Created by yashart on 29.03.15. // #include <stdlib.h> #include <stdio.h> #include <string.h> #include "binary_file.h" errors binary_buffer_constructor(binary_buffer* buffer) { buffer->buffer = NULL; buffer->buffer = (char*) calloc (0, sizeof(*buffer->buffer)); buffer->length = 0; if(binary_buffer_OK(buffer)) PLEASE_KILL_MY_VERY_BAD_FUNCTION(binary_buffer_OK(buffer)); return OK; } errors binary_buffer_destructor(binary_buffer* buffer) { if(binary_buffer_OK(buffer)) PLEASE_KILL_MY_VERY_BAD_FUNCTION(binary_buffer_OK(buffer)); free(buffer->buffer); buffer->length = -117; buffer->buffer = NULL; return OK; } errors binary_buffer_OK(binary_buffer* buffer) { if(!buffer) return BAD_FILE; if(!buffer->buffer) return NULL_PTR; if(buffer->length < 0) return BAD_SIZE; return OK; } errors bin_buffer_add_elem(binary_buffer* buffer, long value, int size) { if(binary_buffer_OK(buffer)) PLEASE_KILL_MY_VERY_BAD_FUNCTION(binary_buffer_OK(buffer)); buffer->buffer = (char*) realloc(buffer->buffer, buffer->length + (size_t)size); if(!buffer->buffer) PLEASE_KILL_MY_VERY_BAD_FUNCTION(BAD_MALLOC); switch (size) { case 1: buffer->buffer[buffer->length] = (char) value; break; case 2: *(short*)(buffer->buffer + buffer->length) = (short) value; break; case 4: *(int*)(buffer->buffer + buffer->length) = (int) value; break; case 8: *(long*)(buffer->buffer + buffer->length) = value; break; default: PLEASE_KILL_MY_VERY_BAD_FUNCTION(BAD_SIZE); } buffer->length += size; if(binary_buffer_OK(buffer)) PLEASE_KILL_MY_VERY_BAD_FUNCTION(binary_buffer_OK(buffer)); return OK; } errors bin_buffer_add_str(binary_buffer *buffer, const char *str, int str_len) { if(binary_buffer_OK(buffer)) PLEASE_KILL_MY_VERY_BAD_FUNCTION(binary_buffer_OK(buffer)); buffer->buffer = (char*) realloc(buffer->buffer, buffer->length + str_len); if(!buffer->buffer) PLEASE_KILL_MY_VERY_BAD_FUNCTION(BAD_MALLOC); memcpy(&buffer->buffer[buffer->length], str, str_len); buffer->length += str_len; if(binary_buffer_OK(buffer)) PLEASE_KILL_MY_VERY_BAD_FUNCTION(binary_buffer_OK(buffer)); return OK; } void bin_buffer_dump(binary_buffer *buffer, const char* file_name) { FILE* file = fopen(file_name, "wb"); //printf("----------------------------------\n"); printf("%d\n", binary_buffer_OK(buffer)); fwrite(buffer->buffer, sizeof(char), buffer->length, file); //printf("\n----------------------------------"); fclose(file); } char* bin_buffer_scan(const char *file_name, long* file_len) { FILE* file = fopen(file_name, "rb"); fseek (file, 0, SEEK_END); *file_len = ftell(file); fseek (file, 0, SEEK_SET); char* buffer = (char*) calloc(*file_len ,sizeof(*buffer)); if(!buffer) PLEASE_KILL_MY_VERY_BAD_FUNCTION(BAD_MALLOC); for(int i = 0; i < *file_len; i++ ) { if(!fscanf(file, "%c", &buffer[i])) PLEASE_KILL_MY_VERY_BAD_FUNCTION(BAD_FILE); } buffer[*file_len - 1] = 0;//last simbol fclose(file); if(!buffer) PLEASE_KILL_MY_VERY_BAD_FUNCTION(BAD_MALLOC); return buffer; } int* bin_buffer_scan_hex(const char *file_name, long *file_len) { FILE* file = fopen(file_name, "r"); int* buffer = NULL; int scan_value = 0; long buffer_len = 0; while(fscanf(file, "%x ", &scan_value) == 1) { buffer_len ++; buffer = (int*) realloc(buffer, sizeof(*buffer) * buffer_len); if(!buffer) PLEASE_KILL_MY_VERY_BAD_FUNCTION(BAD_MALLOC); buffer[buffer_len - 1] = scan_value; } *file_len = buffer_len; fclose(file); return buffer; }
true
a03bbb1edbe7f21abe3a9f824723d9f071169bac
C++
pinkmoon-io/AERO-21D
/catkin_diff_gps/src/diff_gps/include/diff_gps/linuxserial.h
UTF-8
1,346
2.625
3
[]
no_license
// // Created by liqiangwei on 18-8-28. // #ifndef IO_LINUXSERIAL_H #define IO_LINUXSERIAL_H #endif //IO_LINUXSERIAL_H #include<stdio.h> /*标准输入输出定义*/ #include<stdlib.h> /*标准函数库定义*/ #include<unistd.h> /*Unix 标准函数定义*/ #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> /*文件控制定义*/ #include<termios.h> /*PPSIX 终端控制定义*/ #include<errno.h> /*错误号定义*/ #include<iostream> //宏定义 #define FALSE -1 #define TRUE 0 class roserialhandler { private: char *portname;//串口名 int baudrate;//波特率 int fd;//文件描述符 public: //有参构造函数,输入串口名和波特率 roserialhandler(char port[],int baudr) { portname = port; baudrate = baudr; } //析构函数的声明 ~roserialhandler(); //打开串行端口 int UART0_Open(); //关闭串行端口 void UART0_Close(int fd); //设置串行端口 //speed—— flow_ctrl——数据流控制参数 databits int UART0_Set(int speed, int flow_ctrl, int databits, int stopbits, int parity); int UART0_Init(int flow_ctrl,int databits,int stopbits,int parity); int UART0_Recv(unsigned char *rcv_buf,int data_len); int UART0_Send(char *send_buf,int data_len); };
true
c661905522e5330163898329fbd672508ab812a9
C++
Adam-Huang/competition
/C/effectivecpp/item_03.cpp
UTF-8
1,841
3.609375
4
[]
no_license
#include<bits/stdc++.h> using namespace std; class CTextBase{ int* size; char* p; public: CTextBase(const char* other); int& getsize() const; char& operator[](int pos) const; }; CTextBase::CTextBase(const char* other){ // printf("[line %d]: value of size: %d \n", __LINE__, size);//默认初始值在这之前就已经初始化了 size = new int(strlen(other) + 1); p = new char[*size]; strcpy(p,other); } int& CTextBase::getsize() const{ printf("[line %d]: address of size: %p \n", __LINE__, size); return *size; } char& CTextBase::operator[](int pos) const{ printf("[line %d]: address of size: %p \n", __LINE__, &p[pos]); return p[pos]; } int main(){ /* char greeting[] = "Hello"; const char *p = greeting; greeting[0] = 'J'; // *p = 'H'; 只是不能通过这个变量修改 printf("[line %d]: value of greeting: %s, value of p: %s \n", __LINE__, greeting, p); */ const CTextBase T("Hello"); int* a = &T.getsize(); // 返回值是右值,要用常量引用才可以。 printf("[line %d]: address of size: %p \n", __LINE__, a); char* p = &T[0]; printf("[line %d]: value of p: %p \n", __LINE__, p); return 0; } /* [line 20]: value of size: 10 [line 27]: address of size: 0x7ffe07257a60 [line 47]: address of size: 0x7ffe07257a60 [line 32]: address of size: 0x602000000010 [line 50]: value of p: 0x602000000010 1. 行号全部减5 2. 声明左值引用,引用不了T.getsize(),需要声明常量引用。但是[]符号返回值也是右值呀,为啥可以取地址 参考:https://www.runoob.com/cplusplus/returning-values-by-reference.html 被引用的对象不能超出作用域。所以返回一个对局部变量的引用是不合法的 */
true
1ded8c06efde5420167ccd88d0ca0f4777dfbeef
C++
nangege/robotCute
/robotCute/colorFinder.cpp
UTF-8
2,087
2.921875
3
[ "MIT" ]
permissive
#include "ColorFinder.h" void colorFinder::getPosition() { int count = 0; //找到的小球颜色像素数目 int countX = 0; //找到的小球y坐标和 int countY = 0; //找到的小球x坐标和 for(int i = 0; i < grayImg.cols ; i++) { for(int j = 0;j < grayImg.rows; j++) { uchar data = grayImg.at<uchar>(j,i); if(data > 0) { count++; countX +=i; countY += j; } } } if(count > 0) { center.x = countX/count; center.y = countY/count; } else { center.x = 0; center.y = 0; } } Point colorFinder::findColor(int h,int s,int v) { H = h; S = s; V = v; ImgProcess(); int type = MORPH_RECT; Mat inputElem = getStructuringElement(type,Size(3,3)); erode(grayImg,grayImg,inputElem); dilate(grayImg,grayImg,inputElem); getPosition(); return center; } void colorFinder::ImgProcess() { vector<Mat> hsvVec ; split(hsvImg,hsvVec); for(int i = 0 ; i < hsvVec[0].cols; ++i) { for(int j = 0 ; j < hsvVec[0].rows; j ++) { int h = hsvVec[0].at<uchar>(j,i); int s = hsvVec[1].at<uchar>(j,i); int v = hsvVec[2].at<uchar>(j,i); if(h < (H +20)&&h > (H - 20)) { if(s > (S - 30)) { if(v > (V - 30)) { grayImg.at<uchar>(j,i) = 255; } else { grayImg.at<uchar>(j,i) = 0; } } else { grayImg.at<uchar>(j,i) = 0; } } else { grayImg.at<uchar>(j,i) = 0; } } } } void colorFinder::setImg(Mat & image) { cvtColor(image,hsvImg,CV_BGR2HSV); grayImg.create(Size(hsvImg.cols,hsvImg.rows),CV_8UC1); }
true
e912a555dea57049b1f11be1dd71c6a646ebd1c4
C++
LenaShengzhen/eVTOL_Simulation
/src/MultiThread/Simulation.h
UTF-8
881
2.578125
3
[]
no_license
#ifndef SIMULATION_H #define SIMULATION_H #include <chrono> #include <iostream> #include <fstream> #include <ctime> #include <vector> #include <queue> #include <thread> #include <iomanip> // keep decimals #include <string> #include <time.h> #include <cassert> #include <cstdint> #include <unistd.h> #include <condition_variable> using namespace std; class Plane; // Realize simulation in units of frames, // time of each frame = program running time / number of total frames. class Simulation { public: void init(vector<vector<double>> & data); static void phread_frame_timer(void* __this); ~Simulation(); void start_thread(); int get_frame(){return _frame;}; private: unsigned int _frame = 0; // local frame id vector<Plane*> _planes; //void sim(int frameID); // simulation in each frame. }; string getTime(); // print current time. #endif
true
550d141bc42007020535f3e36129cbc3cd267ba7
C++
MoeAl-khalkhali/Azul
/9/Player.h
UTF-8
698
2.859375
3
[]
no_license
#include <iostream> #include "Mosaic.h" #ifndef PLAYER_H #define PLAYER_H class Player { public: Player(std::string name, int id); Player(std::string name, int id, int points); ~Player(); int getPoints(); void resetPoints(); std::string getName(); Mosaic* getBoard(); void addPoints(int points); void removePoints(int points); void loadGame(std::istream& inputStream); void setStarter(bool yesOrNo); bool isStarter(); int getId(); void saveGame(std::ofstream& myfile); void setCPU(bool cpu); bool isCPU(); private: int points; std::string name; Mosaic* board; int id; bool starter; bool cpu; }; #endif
true
cb12d0fcd7190d25b3a3b08a1e66b635218d182c
C++
shehryarnaeem/SamplePrograms
/MWDS/employee.h
UTF-8
827
3.109375
3
[]
no_license
#ifndef EMPLOYEE_H #define EMPLOYEE_H #include "person.h" #include "employeeexpenserecord.h" #include <QString> #include <vector> class Employee : public Person { private: int emp_id; int emp_age; QString emp_role; double salary; static int count; std::vector<EmployeeExpenseRecord> records; public: Employee(); Employee(QString,QString,QString,int,QString,double, std::vector<EmployeeExpenseRecord>); Employee(const Employee&); void set_age(int); void set_role(QString); void set_salary(double); void set_records(std::vector<EmployeeExpenseRecord>); int get_empid()const; int get_age()const; QString get_role()const; double get_salary()const; std::vector<EmployeeExpenseRecord> get_records()const; static int get_count(); }; #endif // EMPLOYEE_H
true
e83cab902fe180606bf8e333f46246df0be7450a
C++
vaithak/NandToTetris
/projects/08/VMTranslator/CodeWriter.cpp
UTF-8
11,390
2.625
3
[]
no_license
#include "CodeWriter.h" using namespace Hack::VMTranslator; CodeWriter::CodeWriter(const std::string &file, bool is_dir){ this->filename = file; int index = 0; for(int i=this->filename.length()-1; i>=0; i--){ if(this->filename[i] == '/'){ index = i; break; } } this->filename = this->filename.substr(index+1); this->labelId = 0; if(is_dir){ fout.open(file + "/" + filename + ".asm"); } else{ fout.open(file + ".asm"); } unary_operators["not"] = "!"; unary_operators["neg"] = "-"; binary_operators["add"] = "+"; binary_operators["and"] = "&"; binary_operators["or"] = "|"; binary_operators["sub"] = "-"; compare_operators["eq"] = "JEQ"; compare_operators["lt"] = "JLT"; compare_operators["gt"] = "JGT"; segment_code_map["local"] = "LCL"; segment_code_map["argument"] = "ARG"; segment_code_map["this"] = "THIS"; segment_code_map["that"] = "THAT"; } std::string CodeWriter::generateLabel(std::string name){ labelId++; return (filename + name + std::to_string(labelId)); } std::string CodeWriter::generateStaticSymbol(std::string str_index){ return (filename + "." + str_index); } // write bootstrap code void CodeWriter::writeInit(){ fout<<"@256\n"; fout<<"D=A\n"; fout<<"@SP\n"; fout<<"M=D\n"; } void CodeWriter::changeFilename(std::string new_filename){ this->filename = new_filename; int index = 0; for(int i=this->filename.length()-1; i>=0; i--){ if(this->filename[i] == '/'){ index = i; break; } } this->filename = this->filename.substr(index+1); } void CodeWriter::writeArithmetic(std::string command){ fout<<"//"<<command<<"\n"; if(unary_operators.find(command) != unary_operators.end()){ fout<<"@SP"<<"\n"; fout<<"A=M-1"<<"\n"; fout<<("M=" + unary_operators[command] + "M\n"); } else if(binary_operators.find(command) != binary_operators.end()){ // extract top value as well as fix stack pointer fout<<"@SP"<<"\n"; fout<<"AM=M-1"<<"\n"; fout<<"D=M"<<"\n"; // extract second value fout<<"@SP"<<"\n"; fout<<"A=M-1"<<"\n"; if(command == "sub") fout<<("M=M" + binary_operators[command] + "D\n"); else fout<<("M=D" + binary_operators[command] + "M\n"); } else if(compare_operators.find(command) != compare_operators.end()){ fout<<"@SP"<<"\n"; fout<<"A=M-1"<<"\n"; fout<<"D=M"<<"\n"; fout<<"A=A-1"<<"\n"; fout<<"M=M-D"<<"\n"; // Fix stack pointer fout<<"D=A+1"<<"\n"; fout<<"@SP"<<"\n"; fout<<"M=D"<<"\n"; // check topmost value fout<<"A=D-1"<<"\n"; fout<<"D=M"<<"\n"; std::string curr_true_label = generateLabel("TRUE"); fout<<"@" + curr_true_label<<"\n"; fout<<("D;" + compare_operators[command])<<"\n"; // No need for false label as it will execute if no jump, but would have to jump over TRUE fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"A=A-1"<<"\n"; fout<<"M=0"<<"\n"; std::string curr_end_label = generateLabel("END"); fout<<"@" + curr_end_label<<"\n"; fout<<"0;JMP"<<"\n"; // TRUE label fout<<"(" + curr_true_label + ")"<<"\n"; fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"A=A-1"<<"\n"; fout<<"M=-1"<<"\n"; // END of comparison label fout<<"(" + curr_end_label + ")"<<"\n"; } fout<<std::endl; } void CodeWriter::writePushPop(std::string command, std::string segment, int index){ std::string str_index = std::to_string(index); if(command == "C_PUSH"){ fout<<"//"<<"push " + segment + " " + str_index<<"\n"; if(segment == "constant"){ // push value on stack fout<<"@" + str_index<<"\n"; fout<<"D=A"<<"\n"; fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; // update stack pointer fout<<"@SP"<<"\n"; fout<<"M=M+1"<<"\n"; } else if(segment == "local" || segment == "argument" || segment == "this" || segment == "that"){ // extracting value from segment area fout<<"@" + str_index<<"\n"; fout<<"D=A"<<"\n"; fout<<"@" + segment_code_map[segment]<<"\n"; fout<<"A=M+D"<<"\n"; fout<<"D=M"<<"\n"; // updating it in stack fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; // update stack pointer fout<<"@SP"<<"\n"; fout<<"M=M+1"<<"\n"; } else if(segment == "temp" || segment == "pointer"){ // extract value from segment area fout<<"@" + str_index<<"\n"; fout<<"D=A"<<"\n"; if(segment == "temp") fout<<"@5"<<"\n"; else fout<<"@3"<<"\n"; fout<<"A=D+A"<<"\n"; fout<<"D=M"<<"\n"; // push that value onto stack fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; // update stack pointer fout<<"@SP"<<"\n"; fout<<"M=M+1"<<"\n"; } else{ // extract value from segment area fout<<("@" + generateStaticSymbol(str_index))<<"\n"; fout<<"D=M"<<"\n"; // push that value onto stack fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; // update stack pointer fout<<"@SP"<<"\n"; fout<<"M=M+1"<<"\n"; } } else{ fout<<"//"<<"pop " + segment + " " + std::to_string(index)<<"\n"; if(segment == "local" || segment == "argument" || segment == "this" || segment == "that"){ // storing address of segment location into R13 fout<<"@" + str_index<<"\n"; fout<<"D=A"<<"\n"; fout<<"@" + segment_code_map[segment]<<"\n"; fout<<"D=M+D"<<"\n"; fout<<"@R13"<<"\n"; fout<<"M=D"<<"\n"; // update stack pointer and extract value fout<<"@SP"<<"\n"; fout<<"AM=M-1"<<"\n"; fout<<"D=M"<<"\n"; // updating it in segment area fout<<"@R13"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; } else if(segment == "temp" || segment == "pointer"){ // extract address of segment location and store into R13 fout<<"@" + str_index<<"\n"; fout<<"D=A"<<"\n"; if(segment == "temp") fout<<"@5"<<"\n"; else fout<<"@3"<<"\n"; fout<<"D=D+A"<<"\n"; fout<<"@R13"<<"\n"; fout<<"M=D"<<"\n"; // pop value from stack and update stack pointer fout<<"@SP"<<"\n"; fout<<"AM=M-1"<<"\n"; fout<<"D=M"<<"\n"; // Store popped value into segment location fout<<"@R13"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; } else{ // pop value from stack and update stack pointer fout<<"@SP"<<"\n"; fout<<"AM=M-1"<<"\n"; fout<<"D=M"<<"\n"; // Store popped value into static location fout<<("@" + generateStaticSymbol(str_index))<<"\n"; fout<<"M=D"<<"\n"; } } fout<<std::endl; } void CodeWriter::writeLabel(std::string labelName){ fout<<"//label "<<labelName<<"\n"; fout<<"("<<labelName<<")"<<"\n"; fout<<std::endl; } void CodeWriter::writeGotoLabel(std::string labelName){ fout<<"//goto "<<labelName<<"\n"; fout<<("@" + labelName)<<"\n"; fout<<"0;JMP\n"; fout<<std::endl; } void CodeWriter::writeIfGotoLabel(std::string labelName){ fout<<"//if-goto "<<labelName<<"\n"; fout<<"@SP\n"; fout<<"AM=M-1\n"; fout<<"D=M\n"; fout<<("@" + labelName)<<"\n"; fout<<"D;JNE\n"; fout<<std::endl; } void CodeWriter::writeFunction(std::string functionName, int numLocal){ fout<<"//function "<<functionName<<" "<<numLocal<<"\n"; fout<<("(" + functionName + ")")<<"\n"; for(int i=0;i<numLocal;i++){ this->writePushPop("C_PUSH", "constant", 0); } } void CodeWriter::writeCall(std::string functionName, int numArgs){ fout<<"//call "<<functionName<<" "<<numArgs<<"\n"; std::string ret_label = generateLabel("_ret_" + functionName + "_"); // save return address fout<<("@" + ret_label)<<"\n"; fout<<"D=A"<<"\n"; fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; fout<<"@SP"<<"\n"; fout<<"M=M+1"<<"\n"; // save LCL fout<<"@LCL\n"; fout<<"D=M"<<"\n"; fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; fout<<"@SP"<<"\n"; fout<<"M=M+1"<<"\n"; // save ARG fout<<"@ARG\n"; fout<<"D=M"<<"\n"; fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; fout<<"@SP"<<"\n"; fout<<"M=M+1"<<"\n"; // save THIS fout<<"@THIS\n"; fout<<"D=M"<<"\n"; fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; fout<<"@SP"<<"\n"; fout<<"M=M+1"<<"\n"; // save THAT fout<<"@THAT\n"; fout<<"D=M"<<"\n"; fout<<"@SP"<<"\n"; fout<<"A=M"<<"\n"; fout<<"M=D"<<"\n"; fout<<"@SP"<<"\n"; fout<<"M=M+1"<<"\n"; // ARGS = SP-n-5 fout<<"@SP"<<"\n"; fout<<"D=M"<<"\n"; fout<<"@5"<<"\n"; fout<<"D=D-A"<<"\n"; fout<<"@"<<numArgs<<"\n"; fout<<"D=D-A"<<"\n"; fout<<"@ARG\n"; fout<<"M=D"<<"\n"; // LCL = SP fout<<"@SP"<<"\n"; fout<<"D=M"<<"\n"; fout<<"@LCL"<<"\n"; fout<<"M=D"<<"\n"; // goto f fout<<("@" + functionName)<<"\n"; fout<<"0;JMP"<<"\n"; // create label for returning fout<<("(" + ret_label + ")")<<"\n"; fout<<std::endl; } void CodeWriter::writeReturn(){ fout<<"//return\n"; // FRAME = LCL, R13 used for FRAME fout<<"@LCL\n"; fout<<"D=M\n"; fout<<"@R13\n"; fout<<"M=D\n"; // RET = *(FRAME-5), R14 used for RET fout<<"@5\n"; fout<<"A=D-A\n"; fout<<"D=M\n"; fout<<"@R14\n"; fout<<"M=D\n"; // *ARG=pop() fout<<"@SP\n"; fout<<"A=M-1\n"; fout<<"D=M\n"; fout<<"@ARG\n"; fout<<"A=M\n"; fout<<"M=D\n"; // SP=ARG+1 fout<<"@ARG\n"; fout<<"D=M+1\n"; fout<<"@SP\n"; fout<<"M=D\n"; // THAT=*(FRAME-1) fout<<"@R13\n"; fout<<"AM=M-1\n"; fout<<"D=M\n"; fout<<"@THAT\n"; fout<<"M=D\n"; // THIS=*(FRAME-2) fout<<"@R13\n"; fout<<"AM=M-1\n"; fout<<"D=M\n"; fout<<"@THIS\n"; fout<<"M=D\n"; // ARG=*(FRAME-3) fout<<"@R13\n"; fout<<"AM=M-1\n"; fout<<"D=M\n"; fout<<"@ARG\n"; fout<<"M=D\n"; // LCL=*(FRAME-4) fout<<"@R13\n"; fout<<"AM=M-1\n"; fout<<"D=M\n"; fout<<"@LCL\n"; fout<<"M=D\n"; // Goto RET fout<<"@R14\n"; fout<<"A=M\n"; fout<<"0;JMP\n"; } void CodeWriter::close(){ fout.close(); }
true
cbad7ba76cbdd1720d59d93ddc4d14fdc1925c8e
C++
ChloeVallet/TP_catalogueTrajets
/Application/Application.cpp
UTF-8
6,382
2.953125
3
[]
no_license
/************************************************************************* Application - description ------------------- début : $DATE$ copyright : (C) $ANNEE$ par $AUTEUR$ e-mail : $EMAIL$ *************************************************************************/ //---------- Réalisation du module <Application> (fichier Application.cpp) --------------- ///////////////////////////////////////////////////////////////// INCLUDE //-------------------------------------------------------- Include système using namespace std; #include <iostream> //------------------------------------------------------ Include personnel #include "Application.h" #include "../Catalogue/Catalogue.h" #include "../Collection/Collection.h" #include "../Trajet/Trajet.h" #include "../TrajetSimple/TrajetSimple.h" #include "../TrajetCompose/TrajetCompose.h" /////////////////////////////////////////////////////////////////// PRIVE //------------------------------------------------------------- Constantes //------------------------------------------------------------------ Types //---------------------------------------------------- Variables statiques //------------------------------------------------------ Fonctions privées static void saisirVilles(char * depart, char * arrivee){ cout << "Ville de départ : " ; cin >> depart; cout << endl; cout << "Ville de d'arrivée : " ; cin >> arrivee; } static moyenTransport choisirMoyenTransport() // Mode d'emploi : // // Contrat : // // Algorithme : // { int moyenTransport; cout << "Moyen de transport : " << endl; cout << "1. AUTO" << endl; cout << "2. BATEAU" << endl; cout << "3. AVION" << endl; cout << "4. TRAIN" << endl; cin >> moyenTransport; switch (moyenTransport) { case 1: return AUTO; case 2: return BATEAU; case 3: return AVION; case 4: return TRAIN; default: cout << "Erreur choisir un autre moyen de transport" << endl; choisirMoyenTransport(); break; } return AUTRE; }//----- fin de choisirMoyenTransport static TrajetSimple * creerTrajetSimple() // Mode d'emploi : // // Contrat : // // Algorithme : // { char villeDepart[50]; char villeArrivee[50]; moyenTransport transport; saisirVilles(villeDepart,villeArrivee); transport = choisirMoyenTransport(); TrajetSimple * tSimple = new TrajetSimple(villeDepart, villeArrivee, transport); return tSimple; } //----- fin de creerTrajetSimple static TrajetCompose * creerTrajetCompose() // Mode d'emploi : // // Contrat : // // Algorithme : // { int nbTrajetSimples; char villeDepart[50]; char villeArrivee[50]; cout << "Combien trajets simples composent le trajet composé à créer ?" << endl; cin >> nbTrajetSimples; moyenTransport transport; saisirVilles(villeDepart,villeArrivee); TrajetCompose * tCompose = new TrajetCompose(villeDepart, villeArrivee, nbTrajetSimples); for (int i = 0; i < nbTrajetSimples; ++i) { cout << "----------------------------------------------------------------" << endl; tCompose->Ajouter(creerTrajetSimple()); } cout << "----------------------------------------------------------------" << endl; return tCompose; } //----- fin de creerTrajetCompose static void ajouterTrajet(Catalogue * catalogue) // Mode d'emploi : // // Contrat : // // Algorithme : // { int choixTypeTrajets; cout << "1. Ajouter un trajet simple" << endl; cout << "2. Ajouter un trajet composé" << endl; cout << "----------------------------------------------------------------" << endl; cout << "Saisissez votre choix : " << endl; cin >> choixTypeTrajets; cout << "----------------------------------------------------------------" << endl; switch (choixTypeTrajets) { case 1: catalogue->Ajouter(creerTrajetSimple()); break; case 2: catalogue->Ajouter(creerTrajetCompose()); break; } } //----- fin de ajouterTrajet static void rechercherTrajets(Catalogue * catalogue) { char villeDepart[50]; char villeArrivee[50]; saisirVilles(villeDepart, villeArrivee); catalogue->Rechercher(villeDepart,villeArrivee); } static void menuPrincipal(int * choixOptions){ cout << "----------------------------------------------------------------" << endl; cout << "Options :" << endl; cout << "1. Ajouter un nouveau trajet au catalogue" << endl; cout << "2. Consulter le catalogue" << endl; cout << "3. Rechercher un trajet dans le catalogue" << endl; cout << "4. Arreter le programme" << endl; cout << "----------------------------------------------------------------" << endl; cout << "Saisissez votre choix : " << endl; cin >> *(choixOptions); cout << "----------------------------------------------------------------" << endl; } ////////////////////////////////////////////////////////////////// PUBLIC //---------------------------------------------------- Fonctions publiques int main () // Algorithme : // { Catalogue catalogue; int choixOptions = 0; cout << "----------------------------------------------------------------" << endl; cout << " CATALOGUE DE TRAJETS " << endl; cout << "----------------------------------------------------------------" << endl; menuPrincipal(&choixOptions); while (choixOptions == 1 || choixOptions == 2 || choixOptions == 3 ){ switch (choixOptions) { case 1: cout << "Option 1" << endl; ajouterTrajet(&catalogue); menuPrincipal(&choixOptions); break; case 2: cout << "Option 2" << endl; catalogue.Afficher(); menuPrincipal(&choixOptions); break; case 3: cout << "Option 3" << endl; rechercherTrajets(&catalogue); menuPrincipal(&choixOptions); break; default: cout << "Option 4" << endl; break; } } return 0; } //----- fin de main
true
46a47e57d7a24d03202d813bf87561e2c9d9212e
C++
ltaoj/LeetCodeCPP
/single-number-ii.cpp
UTF-8
346
3.046875
3
[]
no_license
class Solution { public: int singleNumber(int A[], int n) { int ones = 0; int twos = 0; int three; for (int i = 0;i < n;i++) { twos |= ones&A[i]; ones ^= A[i]; three = ones&twos; ones &= ~three; twos &= ~three; } return ones; } };
true
70b7762d6b74c0a85fb042c41bd496ff4697773e
C++
TorstenRobitzki/bluetoe
/tests/test_characteristics.hpp
UTF-8
1,666
2.53125
3
[ "MIT" ]
permissive
#ifndef BLUETOE_TESTS_CHARACTERISTICS_HPP #define BLUETOE_TESTS_CHARACTERISTICS_HPP #include <bluetoe/characteristic_value.hpp> namespace { std::uint32_t simple_value = 0xaabbccdd; const std::uint32_t simple_const_value = 0xaabbccdd; typedef bluetoe::characteristic< bluetoe::characteristic_uuid< 0xD0B10674, 0x6DDD, 0x4B59, 0x89CA, 0xA009B78C956B >, bluetoe::bind_characteristic_value< std::uint32_t, &simple_value > > simple_char; typedef bluetoe::characteristic< bluetoe::characteristic_uuid16< 0xD0B1 >, bluetoe::bind_characteristic_value< std::uint32_t, &simple_value > > short_uuid_char; typedef bluetoe::characteristic< bluetoe::characteristic_uuid< 0xD0B10674, 0x6DDD, 0x4B59, 0x89CA, 0xA009B78C956B >, bluetoe::bind_characteristic_value< const std::uint32_t, &simple_const_value > > simple_const_char; template < typename Char > struct read_characteristic_properties : Char { read_characteristic_properties() { using suuid = bluetoe::service_uuid16< 0x4711 >; using srv = bluetoe::server<>; const bluetoe::details::attribute value_attribute = this->template attribute_at< std::tuple<>, 0, bluetoe::service< suuid >, srv >( 0 ); std::uint8_t buffer[ 100 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 0 ); BOOST_REQUIRE( bluetoe::details::attribute_access_result::success == value_attribute.access( read, 1 ) ); properties = buffer[ 0 ]; } std::uint8_t properties; }; } #endif // include guard
true
3873821ec591be39c8804eec5e9595524a79dc45
C++
cenariusxz/ACM-Coding
/newstu/2015/草爷要的榜shujuceshi.cpp
UTF-8
689
2.546875
3
[]
no_license
#include<stdio.h> #include<string.h> typedef long long ll; ll ans[105]; int main(){ int n,k; int count=0; while(scanf("%d%d",&n,&k)!=EOF){ memset(ans,0,sizeof(ans)); count++; if(n>100||n<1)printf("%d:n:%d\n",count,n); if(k>10||k<1)printf("%d:k:%d\n",count,k); for(int i=1;i<=n;++i){ for(int j=1;j<=k;++j){ int a,b; scanf("%d:%d",&a,&b); if(a<0||a>4||b<0||b>59)printf("%d:%d:%d\n",count,a,b); ans[i]+=a*60+b; } for(int j=1;j<=k;++j){ int c; scanf("%d",&c); if(c<1||c>200)printf("%d:%d\n",count,c); ans[i]+=(c-1)*20; } } for(int i=1;i<=n;++i)if(ans[i]>2147483647ll)printf("%dWA\n",count); } printf("%d\n",count); return 0; }
true
57e8e2d0bf39b57e999fdf26f21dcc6e61f17337
C++
KillenX/WayWatch
/WW Exit/Ticket.h
UTF-8
273
2.5625
3
[]
no_license
#pragma once #include <string> #include <iostream> class Ticket { public: Ticket(std::string, std::string, double); void printTicketHeader(std::ostream &); void printTicket(std::ostream &); private: std::string licensePlate; std::string dateTime; double price; };
true
70b448c668fba29e26c885e3ae8d5d2b1b7e9488
C++
nicholsonjohnc/laso-old
/LASO/HS006.cpp
UTF-8
778
3.15625
3
[ "Apache-2.0" ]
permissive
#include "HS006.h" bool LASO::HS006::objFun(double *x, double *fObj) { fObj[0] = pow((1.0 - x[0]), 2.0); return true; } bool LASO::HS006::objGrad(double *x, double *gObj) { gObj[0] = 2.0 * (1.0 - x[0]) * (-1.0); gObj[1] = 0.0; return true; } bool LASO::HS006::conFun(double *x, double *fCon) { fCon[0] = 10.0 * (x[1] - x[0] * x[0]); return true; } bool LASO::HS006::conJac(double *x, double *jCon) { // Note: Jacobian is stored in single dimensional vector. // Numbering system is as follows: // [design variable number * total number of constraints + constraint number] jCon[0 * 1 + 0] = -20.0 * x[0]; // Derivative of the first constraint wrt variable 1. jCon[1 * 1 + 0] = 10.0; // Derivative of the first constraint wrt variable 2. return true; }
true
d2e851ea0e34629052836740c0f098cfea434bc2
C++
silencelee/leetcode
/algorithm/714.best-time-to-buy-and-sell-stock-with-transaction-fee.cpp
UTF-8
2,182
3.328125
3
[]
no_license
/* * @lc app=leetcode id=714 lang=cpp * * [714] Best Time to Buy and Sell Stock with Transaction Fee * * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/ * * algorithms * Medium (53.10%) * Likes: 1513 * Dislikes: 46 * Total Accepted: 67.8K * Total Submissions: 125K * Testcase Example: '[1,3,2,8,4,9]\n2' * * Your are given an array of integers prices, for which the i-th element is * the price of a given stock on day i; and a non-negative integer fee * representing a transaction fee. * You may complete as many transactions as you like, but you need to pay the * transaction fee for each transaction. You may not buy more than 1 share of * a stock at a time (ie. you must sell the stock share before you buy again.) * Return the maximum profit you can make. * * Example 1: * * Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 * Output: 8 * Explanation: The maximum profit can be achieved by: * Buying at prices[0] = 1Selling at prices[3] = 8Buying at prices[4] = * 4Selling at prices[5] = 9The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = * 8. * * * * Note: * 0 < prices.length . * 0 < prices[i] < 50000. * 0 <= fee < 50000. * */ // @lc code=start /* class Solution { public: int maxProfit(vector<int>& prices, int fee) { int n = prices.size(); if (n == 0) return 0; vector<int> f(n, 0); vector<int> g(n, 0); g[0] = -prices[0]; for (int i = 1; i < n; ++i) { f[i] = max(f[i - 1], g[i - 1] + prices[i] - fee); g[i] = max(g[i - 1], f[i - 1] - prices[i]); } return f[n - 1]; } }; */ class Solution { public: int maxProfit(vector<int>& prices, int fee) { int n = prices.size(); if (n == 0) return 0; const int INF = 0x3f3f3f3f; vector<vector<int>> f(n + 1, vector<int>(2, -INF)); f[0][0] = 0; for (int i = 1; i <= n; ++i) { f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i - 1] - fee); f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i - 1]); } return f[n][0]; } }; // @lc code=end
true
fccf80e7fe9e422aaec35ada6bcedd3733dfa301
C++
KIMGEONUNG/poly-merger
/code/test/src/core/PolygonMergerTest.cpp
UTF-8
782
2.5625
3
[]
no_license
#include <cppunit/extensions/HelperMacros.h> #include "PolygonMergerTest.h" #include "PolygonMerger.h" #include "Point.h" #include "Polygon.h" void PolygonMergerTest::mergeTest() { using namespace PolyMerger; int morphRecSize = 3; PolygonMerger merger; Point pts1[4]; pts1[0] = Point(1,1); pts1[1] = Point(5,1); pts1[2] = Point(5,5); pts1[3] = Point(1,5); Polygon rec1 = Polygon(pts1, 4); Point pts2[4]; pts2[0] = Point(6,1); pts2[1] = Point(10,1); pts2[2] = Point(10,5); pts2[3] = Point(6,5); Polygon rec2 = Polygon(pts2, 4); merger = PolygonMerger(morphRecSize); Polygon polys[2]; polys[0] = rec1; polys[1] = rec2; Polygon* rs = merger.merge(polys, 2); double area = rs[0].getArea(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Merge test fail",36.0 ,area); }
true
e357343358697a05bcafa7aaf9c7d60ad0a05166
C++
jinsenglin/cplusplus
/11.max-heap/code.cpp
UTF-8
4,020
3.46875
3
[]
no_license
#include <iostream> #include "function.h" #include <cstring> using namespace std; void Implement::Insert(int value) { int currentNode = ++size; while(currentNode !=1 && heap[currentNode/2] < value) { // Swap with parent node heap[currentNode]=heap[currentNode/2]; currentNode /= 2; // currentNode now points to parent } heap[currentNode] = value; } void Implement::DeleteMax() { if ( size > 0 ) { int lastE = heap[size--]; // trickle down int currentNode = 1; // root int child = 2; // A child of currentNode while(child <= size) { // Set child to larger child of currentNode if (child < size && heap[child] < heap[child+1]) child++; // Can we put lastE in currentNode? if (lastE >= heap[child]) break; // Yes! // No! heap[currentNode] = heap[child]; // Move child up currentNode = child; child *=2; // Move down a level } heap[currentNode] = lastE; } } int Implement::MaxPathWeight(int index) { int result = 0; if (index <= size) { int leftNode = index*2; int rightNode = index*2+1; int leftWeight = MaxPathWeight(leftNode); int rightWeight = MaxPathWeight(rightNode); if (leftWeight > rightWeight) { result = leftWeight + heap[index]; } else { result = rightWeight + heap[index]; } } return result; } string Implement::InorderTraversal(int index) { string result = ""; if (index <= size) { int leftNode = index*2; int rightNode = index*2+1; string leftResult = InorderTraversal(leftNode); if (leftResult != "") { //cout << "DEBUG: leftResult = '" << leftResult << "'" << endl; result.append(leftResult); } //cout << "DEBUG: " << to_string(heap[index]) << endl; if (result != "") { result.append(" " + to_string(heap[index])); } else { result.append(to_string(heap[index])); } string rightResult = InorderTraversal(rightNode); if (rightResult != "") { //cout << "DEBUG: rightResult = '" << rightResult << "'" << endl; result.append(" " + rightResult); } } return result; } string Implement::PreorderTraversal(int index) { string result = ""; if (index <= size) { int leftNode = index*2; int rightNode = index*2+1; //cout << "DEBUG: " << to_string(heap[index]) << endl; result.append(to_string(heap[index])); string leftResult = PreorderTraversal(leftNode); if (leftResult != "") { //cout << "DEBUG: leftResult = '" << leftResult << "'" << endl; result.append(" " + leftResult); } string rightResult = PreorderTraversal(rightNode); if (rightResult != "") { //cout << "DEBUG: rightResult = '" << rightResult << "'" << endl; result.append(" " + rightResult); } } return result; } string Implement::PostorderTraversal(int index) { string result = ""; if (index <= size) { int leftNode = index*2; int rightNode = index*2+1; string leftResult = PostorderTraversal(leftNode); if (leftResult != "") { //cout << "DEBUG: leftResult = '" << leftResult << "'" << endl; result.append(leftResult); } string rightResult = PostorderTraversal(rightNode); if (rightResult != "") { //cout << "DEBUG: rightResult = '" << rightResult << "'" << endl; result.append(" " + rightResult); } //cout << "DEBUG: " << to_string(heap[index]) << endl; if (result != "") { result.append(" " + to_string(heap[index])); } else { result.append(to_string(heap[index])); } } return result; }
true
9714c04209108d8a2622c138c557a96935ad837a
C++
bartekpacia/cpp-training
/algo-and-ds/ads/stack/main.cpp
UTF-8
309
3.21875
3
[ "MIT" ]
permissive
#include <iostream> #include "stack.hpp" using namespace std; template class Stack<int>; int main() { Stack<int>* stack = new Stack<int>(); stack->Push(1); stack->Push(2); stack->Push(3); while (!stack->isEmpty()) { int popped = stack->Pop(); cout << popped << endl; } return 0; }
true
c28ed111fbf96edd39a5d4682c6d2722e957033f
C++
chm994483868/AlgorithmExample
/Algorithm_C/OfferReview/01_38/31_StackPushPopOrder/StackPushPopOrder_1.hpp
UTF-8
1,096
2.90625
3
[]
no_license
// // StackPushPopOrder_1.hpp // OfferReview // // Created by CHM on 2020/11/5. // Copyright © 2020 CHM. All rights reserved. // #ifndef StackPushPopOrder_1_hpp #define StackPushPopOrder_1_hpp #include <stdio.h> #include <stack> using namespace std; namespace StackPushPopOrder_1 { // 31:栈的压入、弹出序列 // 题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是 // 否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列 1、2、3、4、 // 5是某栈的压栈序列,序列 4、5、3、2、1 是该压栈序列对应的一个弹出序列,但 // 4、3、5、1、2 就不可能是该压栈序列的弹出序列。 bool isPopOrder(const int* pPush, const int* pPop, int nLength); // 测试代码 void Test(const char* testName, const int* pPush, const int* pPop, int nLength, bool expected); void Test1(); void Test2(); void Test3(); void Test4(); // push 和 pop 序列只有一个数字 void Test5(); void Test6(); void Test7(); void Test(); } #endif /* StackPushPopOrder_1_hpp */
true
88fed6a33d69b6e7aea26991df20b5713bd2c24f
C++
tornadoblot/acmicpc_project
/acmicpc_project/7568.cpp
UTF-8
400
3
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { pair<int, int> arr[50]; int N, i, grade; cin >> N; for (i = 0; i < N; i++) { cin >> arr[i].first >> arr[i].second; } for (i = 0; i < N; i++) { grade = 0; for (int j = 0; j < N; j++) { if (arr[i].first < arr[j].first && arr[i].second < arr[j].second) grade++; } cout << grade + 1 << ' '; } return 0; }
true
dce618f9ca4c1a78be37b590e5d744fc4f020467
C++
ASHISH-GITHUB2495/Math-algorithms-for-competitive-programmings
/Linear Diophantine equations/Linear diophantine equation solutions between intervals.cpp
WINDOWS-1250
1,911
2.96875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define pb push_back #define ll long long int #define mod 100000 #define rep(i,k,n) for(ll i=k;i<n;i++) #define E cout<<endl #define MAX 1000002 #define u_m unordered_map //hashing container void linearDiophantineSolutions(ll a, ll b, ll c, ll xmin, ll xmax, ll ymin, ll ymax) { //the solution always exists between 0 to c. int flag = 0; for (ll i = xmin; i <= xmax; i++) { if ((c - (i * a)) % b == 0) { ll y = (c - (i * a)) / b; flag = 1; if (y >= ymin && y <= ymax) { cout << "x = " << i << " and y = " << (c - (i * a)) / b << endl; } } } if (flag == 0) cout << "Not possible\n" << endl; } int main() { //////////////////////////////////////start............... //Number of given solution of diophantine equations(if exists) BRUTE-Force // ax+by=c ; find x=(c-by)/a and y=(c-ax)/b // we will find the solutions that exis in between intervals ll a, b, c; cin >> a >> b >> c; ll xmin, xmax, ymin, ymax; cin >> xmin >> xmax >> ymin >> ymax; linearDiophantineSolutions(a, b, c, xmin, xmax, ymin, ymax); ////////////////////////////////////////end-......................... return 0; } //c v a s selecting text or x for selecting cut //ctrl+d after selecting text to select same type //ctrl+shift+d for copy and paste the line below it //ctrl+del to delete a text //ctrl+left to jump left of line or vice versa //ctrl+shift+" / " to comment whole block and vice versa for undo //ctrl+" / " for commenting a line /* when N <= 10, then both O(N!) and O(2N) are ok (for 2N probably N <= 20 is ok too) when N <= 100, then O(N3) is ok (I guess that N4 is also ok, but never tried) when N <= 1.000, then N2 is also ok when N <= 1.000.000, then O(N) is fine (I guess that 10.000.000 is fine too, but I never tried in contest) finally when N = 1.000.000.000 then O(N) is NOT ok, you have to find something better*/
true
7d27e8bdc848f462894120d5bb6c0f39995be348
C++
tyq-1112/leetcode_note
/1-100/1. Two Sum.cpp
UTF-8
1,298
3.578125
4
[]
no_license
 #include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> mp; vector<int> ans(2,0); for(int i = 0 ; i < nums.size() ; ++i){ int x = target - nums[i]; if(mp.find(x) != mp.end()) { ans[1] = i ; ans[0] = mp[x] ; return ans; } mp[nums[i]] = i; } return ans; } }; int main(){ Solution solution; vector<int> nums = {2,7,11,15}; auto t = solution.twoSum(nums,9); cout<<t[0]<<" "<<t[1]<<endl; return 0; } /* 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target的那两个整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。 示例 1: 输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。 示例 2: 输入:nums = [3,2,4], target = 6 输出:[1,2] 2 <= nums.length <= 10^4 -10^9 <= nums[i] <= 10^9 -10^9 <= target <= 10^9 只会存在一个有效答案 */
true
86930eca96ceb01bd1cfe19b22241df14009a487
C++
NCAR/lrose-core
/codebase/libs/forayRal/src/Foray/ForayLibs/trunk/Libraries/Dorade/source/DoradeBlockCelv.cpp
UTF-8
4,559
2.703125
3
[ "BSD-3-Clause" ]
permissive
// // // // #include <stdio.h> #include "DoradeBlockCelv.h" using namespace std; using namespace ForayUtility; // Static values string DoradeBlockCelv::id_("CELV"); ////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////// DoradeBlockCelv::DoradeBlockCelv(){ blockSize_ = 12; } ////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////// DoradeBlockCelv::~DoradeBlockCelv(){ } ////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////// bool DoradeBlockCelv::test(Buffer &buffer) throw(Fault){ try { if(id_ != buffer.get_string_from_char(0,4)){ return false; } }catch(Fault &re){ re.add_msg("DoradeBlockCelv::test: caught Fault.\n"); throw re; } return true; } ////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////// int DoradeBlockCelv::write_size(int numberOfCells) throw(Fault){ return 12 + (numberOfCells * 4); } ////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////// bool DoradeBlockCelv::decode(Buffer &buffer) throw(Fault){ try{ if(!test(buffer)){ return false; } stringValues_ ["id"] = buffer.get_string_from_char ( 0,4); blockSize_ = buffer.get_four_byte_integer( 4); integerValues_["block_size"] = blockSize_; int numberCells = buffer.get_four_byte_integer( 8); integerValues_["number_of_cells"] = numberCells; doubleValues_ ["meters_to_first_cell"] = buffer.get_four_byte_float (12); // first value. for(int aa = 0; aa < numberCells; aa++){ int loc = 12 + (aa * 4); doubleVector_.push_back(buffer.get_four_byte_float(loc)); } validate(); }catch(Fault re){ re.add_msg("DoradeBlockCelv::decode:: caught Fault \n"); throw re; }catch(...){ throw Fault("DoradeBlockCelv::decode: caught exception \n"); } return true; } ////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////// void DoradeBlockCelv::encode(Buffer &buffer) throw(Fault){ unsigned char *bufferData; try { validate(); int numberCells = get_integer("number_of_cells"); int blockSize = (numberCells * 4) + 12; bufferData = buffer.new_data(blockSize); buffer.set_string ( 0,id_,4); buffer.set_four_byte_integer( 4,blockSize_); buffer.set_four_byte_integer( 8,numberCells); doubleIterator_ = doubleVector_.begin(); for(int cell = 0; cell < numberCells; cell++){ int loc = 12 + (cell * 4); buffer.set_four_byte_float(loc,*doubleIterator_); doubleIterator_++; } }catch(Fault &re){ re.add_msg("DoradeBlockCelv::encode : caught Fault \n"); throw re; } } ////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////// string DoradeBlockCelv::listEntry(){ string returnString(""); char lineChar[4096]; sprintf(lineChar, "%4s %5d \n", stringValues_["id"].c_str(), integerValues_["block_size"]); returnString += lineChar; sprintf(lineChar,"\tnumber_of_cells: %d\n", get_integer("number_of_cells")); returnString += lineChar; sprintf(lineChar,"\n"); returnString += string(lineChar); return returnString; } ////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////// DoradeBlockCelv *DoradeBlockCelv::castToDoradeBlockCelv(){ return this; } ////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////// void DoradeBlockCelv::validate() throw (Fault){ validate_integer("DoradeBlockCelv","number_of_cells"); int numberCells = get_integer("number_of_cells"); if(doubleVector_.size() != get_integer("number_of_cells")){ char msg[2048]; sprintf(msg,"DoradeBlockCelv::validate : number_of_cells value of %d is not the same as doubleVector size of %d \n", numberCells, doubleVector_.size()); throw Fault(msg); } }
true
16d2aeec08818a13d681c1f5842e5364c0100580
C++
manohar45/Leetcode_solutions
/1_Two_Sum.cpp
UTF-8
463
2.75
3
[]
no_license
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int>mp; int temp=0; unordered_map<int,int>:: iterator it; for (int i=0;i<nums.size();i++) { temp=target-nums[i]; it=mp.find(temp); if(it!=mp.end()) { return {it->second,i}; } mp[nums[i]]=i; } return {}; } };
true
0696a84b3edfb1fde5f499bcd18a141c53ca4c1e
C++
montreal91/workshop
/forgery/magic_genes_cpp/src/mage.h
UTF-8
682
3.21875
3
[]
no_license
#pragma once #include <iostream> #include <vector> #include <random> class MMage { public: MMage( bool female = true ); MMage( MMage& mother, MMage& father ); int GetCurrentAge() const; int GetEstimatedAge() const; // TODO: remove in release // int GetCurrentChildren() const; int GetEstimatedChildren() const; bool GetSex() const; void AgeUp(); bool IsAlive() const; void AddChild(); bool IsReadyToMate() const; private: bool m_sex; // true - female, false = male int m_current_age; int m_estimated_age; int m_current_children; int m_estimated_children; };
true
c151f545bf8de33e4d03cb8ccd7c8ed21e789dea
C++
Somrat-Hossen/Algorithm-
/Number Theory/Euler totient for single n.cpp
UTF-8
400
2.9375
3
[]
no_license
#include<bits/stdc++.h> #define mx 100000000 using namespace std; int Euler_totient(int n) { int i,j; int tmp=n; for(i=2;i*i<=n;i++) { if(n%i==0) { while(n%i==0) { n/=i; } tmp=(tmp/i)*(i-1); } } if(n>2) tmp=(tmp/n)*(n-1); return tmp; } int main() { int n; cin>>n; int phi_of_n=Euler_totient(n); cout<<phi_of_n<<endl; }
true
9393b92325fecb7bfcf2f7db2466283bfa85e8ba
C++
bayareamediagroup/Control-Structures
/ch13/projects/ex1/inc/date.h
UTF-8
887
3.8125
4
[ "MIT" ]
permissive
#ifndef DATE_H #define DATE_H class CDate { /* member variables */ private: int day; int month; int year; /* member functions */ public: void setDay(int); void setMonth(int); void setYear(int); int getDay() const; int getMonth() const; int getYear() const; }; /* mutators(setter) */ void CDate::setDay(int d) { day = d; } void CDate::setMonth(int m) { month = m; } void CDate::setYear(int y) { year = y; } /* accessors(getter) */ int CDate::getDay() const { return day; } int CDate::getMonth() const { return month; } int CDate::getYear() const { return year; } #endif /* Design a class called Date. * * The class should store a date in three integers: month, day, and year. * * There should be member functions to print the date in the following forms: * 12/25/2014 * December 25, 2014 * 25 December 2014 * */
true
06fcc739bab0cf8529558d085b67746a1758449a
C++
martinpiper/ReplicaNetPublic
/ReplicaNetPublic/Includes/RNPlatform/Inc/Encryption.h
UTF-8
3,196
2.78125
3
[]
no_license
/* START_LICENSE_HEADER Copyright (C) 2000 Martin Piper, original design and program code Copyright (C) 2001 Replica Software This program file is copyright (C) Replica Software and can only be used under license. For more information visit: http://www.replicanet.com/ Or email: info@replicanet.com END_LICENSE_HEADER */ #include "RNPlatform/Inc/MemoryTracking.h" #ifndef __ENCRYPTION_H__ #define __ENCRYPTION_H__ namespace RNReplicaNet { // Key length must be an integer multiple of 4 and be at least 8 const int kEncryptionKeyLengthBytes = 8; /** * An symmetric encryption class that is designed to be fast and maintain the size of the original data. */ class Encryption { public: struct Key { public: Key(); Key(const Key &source); virtual ~Key(); /** * Creates a key from data and an input length. * \param data the data to use as a seed for the key. This can be NULL to use the default key. * \param length the length of the data to use for creating the key */ void Create(const void *data,const int length); /** * Adds the data to an existing crypto key, for example a salt value to cause the key to change for each block of data. * \param data the data to use as a seed for the key. This can be NULL to use the default key. * \param length the length of the data to use for creating the key */ void AddCrypto(const void *data,const int length); void AddCrypto(const unsigned char salt); unsigned char mKey[kEncryptionKeyLengthBytes]; }; /** * Encrypt a portion of memory with a key. * \param data the pointer to the start of the memory * \param length the length of the memory in bytes * \param key the key to use */ static void Encrypt(void *data,int length,Key *key); /** * Decrypt a portion of memory with a key. * \param data the pointer to the start of the memory * \param length the length of the memory in bytes * \param key the key to use */ static void Decrypt(void *data,int length,Key *key); /** * Encrypt a portion of memory with a key with a commutative algorithm. * \param data the pointer to the start of the memory * \param length the length of the memory in bytes * \param key the key to use */ static void CommutativeEncrypt(void *data,int length,Key *key); /** * Decrypt a portion of memory with a key with a commutative algorithm. * \param data the pointer to the start of the memory * \param length the length of the memory in bytes * \param key the key to use */ static void CommutativeDecrypt(void *data,int length,Key *key); /** * Encrypt a portion of memory with a key with a commutative bytewise algorithm. * \param data the pointer to the start of the memory * \param length the length of the memory in bytes * \param key the key to use */ static void CommutativeEncryptBytewise(void *data,int length,Key *key); /** * Decrypt a portion of memory with a key with a commutative bytewise algorithm. * \param data the pointer to the start of the memory * \param length the length of the memory in bytes * \param key the key to use */ static void CommutativeDecryptBytewise(void *data,int length,Key *key); }; } // namespace RNReplicaNet #endif
true
668ea23a77e47626ca572b5ef119409e0781a461
C++
HustCoderHu/CodingPractice
/bishi/360-2018autumn/main.cpp
UTF-8
1,363
2.84375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; void q1() { vector<int> inp; int n; cin >> n; inp.resize(n); for (int i = 0; i < n ; ++i) cin >> inp[i]; if (n <= 2) { cout << -1 << endl; return; } int maxe = -1; int cnt = 2; maxe = max(inp.at(0), inp.at(1)); maxe = max(maxe, inp.at(2)); int sum = inp.at(0) + inp.at(1); for (; cnt < n; ++cnt) { sum += inp.at(cnt); maxe = max(maxe, inp.at(cnt)); if (2*maxe < sum) break; } if (cnt == n) { cnt == -1; } cout << cnt+1 << endl; } void q2() { int q; int k, l, r; vector<int> kvec; vector<long> lvec; vector<long> rvec; cin >> q; kvec.reserve(q); lvec.reserve(q); rvec.reserve(q); for (int i = 0; i < q; ++i) { cin >> k >> l >> r; kvec.push_back(k); lvec.push_back(l); rvec.push_back(r); } vector<long> res; res.reserve(q); int v; for (int i = 0; i < q; ++i) { v = 1; k = kvec.at(i); l = lvec.at(i); r = rvec.at(i); while (v*k-1 <= r) { v *= k; } while (v < l) { v = v + } } } int main(int argc, char *argv[]) { // q1(); q2(); return 0; }
true
4dfa074f9915ab220d3e1ee7ed6ea300c9d8e3a3
C++
Kurangceret/Decoupling
/decoupling_proj/RayCast.cpp
UTF-8
18,889
2.65625
3
[]
no_license
#include "RayCast.h" #include "Utility.h" #include "PathFinder.h" #include <algorithm> extern "C" { # include "lua.h" # include "lauxlib.h" # include "lualib.h" }; #include <LuaBridge.h> /*if (!designatedNode) falseFlag = true; if (std::find(toBeAvoidedNodes.begin(), toBeAvoidedNodes.end(), designatedNode) != toBeAvoidedNodes.end()) { falseFlag = true; if (contactedAvoidedNodes) *contactedAvoidedNodes = true; } if (designatedNode && designatedNode->tile) collidedTileList.push_back(designatedNode->tile);*/ RayCast::RayCast() { } RayCast::~RayCast() { } RayCast::TileChecker RayCast::mStandardTileChecker = [](AStarNode* designatedNode) -> bool{ if (!designatedNode || designatedNode->tile || designatedNode->isFallable) return false; return true; }; bool RayCast::castRayLinesFromRect(const sf::Vector2f& initialMidRectPos, const sf::FloatRect& rect, const sf::Vector2f& targetPos, PathFinder* pathFinder, const TileChecker& tileChecker) { sf::Vector2f direction = Utility::unitVector(targetPos - initialMidRectPos); if (direction == sf::Vector2f()) return true; sf::Vector2f tileSize = pathFinder->getTileSize(); std::vector<sf::Vector2f> otherRayPoints; const sf::Vector2f topLeft = initialMidRectPos + sf::Vector2f((-rect.width / 2.f), (-rect.height / 2.f)); const sf::Vector2f topRight = initialMidRectPos + sf::Vector2f((rect.width / 2.f), (-rect.height / 2.f)); const sf::Vector2f bottomRight = initialMidRectPos + sf::Vector2f((rect.width / 2.f), (rect.height / 2.f) - 1.f); const sf::Vector2f bottomLeft = initialMidRectPos + sf::Vector2f((-rect.width / 2.f), (rect.height / 2.f) - 1.f); otherRayPoints.push_back(topLeft); otherRayPoints.push_back(topRight); otherRayPoints.push_back(bottomRight); otherRayPoints.push_back(bottomLeft); int widthRemainder = static_cast<int>(std::floor(((rect.width - 1.f) / tileSize.x))); int heightRemainder = static_cast<int>(std::floor(((rect.height - 1.f) / tileSize.y))); /* |---------------| | | | | |---------------| ----------> Width | | | V Height is the indicator if direction going down or up, the width is the one to be ray cast if direction going left or right, the height is the one to be ray cast */ if (direction.x != 0.f && heightRemainder > 0){ sf::Vector2f pointToBeUsed = direction.x > 0.f ? topRight : topLeft; float addY = rect.height / (heightRemainder + 1); int i = 1; while (i <= heightRemainder) otherRayPoints.push_back(pointToBeUsed + sf::Vector2f(0.f, addY * i++)); } if (direction.y != 0.f && widthRemainder > 0){ sf::Vector2f pointToBeUsed = direction.y > 0.f ? bottomLeft : topLeft; float addX = rect.width / (widthRemainder + 1); int i = 1; while (i <= widthRemainder) otherRayPoints.push_back(pointToBeUsed + sf::Vector2f(addX * i++, 0.f)); } return castMultipleRayLines(initialMidRectPos, otherRayPoints, targetPos, pathFinder, tileChecker); } bool RayCast::castMultipleRayLines(const sf::Vector2f& initialPos, std::vector<sf::Vector2f>& otherPos, const sf::Vector2f& targetPos, PathFinder* pathFinder, const TileChecker& tileChecker) { sf::Vector2f direction = Utility::unitVector(targetPos - initialPos); std::vector<sf::Vector2f> anotherPos = otherPos; if (direction.y != 0.f){ if (!checkHorizontalTile(initialPos, targetPos, direction, otherPos, pathFinder, tileChecker)) return false; } if (direction.x != 0.f){ if (!checkVerticalTile(initialPos, targetPos, direction, anotherPos, pathFinder, tileChecker)) return false; } return true; } bool RayCast::castRayLineScript(float initialX, float initialY, float targetX, float targetY, PathFinder* pathFinder, lua_State* luaState) { luabridge::LuaRef luaTileChecker = luabridge::LuaRef::fromStack(luaState, 6); TileChecker tileChecker; if (!luaTileChecker.isNil()){ tileChecker = [&](AStarNode* curNode) -> bool{ return luaTileChecker(curNode); }; } else tileChecker = mStandardTileChecker; return castRayLine(sf::Vector2f(initialX, initialY), sf::Vector2f(targetX, targetY), pathFinder, tileChecker); } bool RayCast::castRayLine(const sf::Vector2f& initialPos, const sf::Vector2f& targetPos, PathFinder* pathFinder, const RayCast::TileChecker& nodeChecker) { sf::Vector2f direction = Utility::unitVector(targetPos - initialPos); //std::vector<Entity*> tilesHorizontal, tilesVertical; std::vector<sf::Vector2f> otherPos, anotherPos; if (direction.y != 0.f){ if (!checkHorizontalTile(initialPos, targetPos, direction, otherPos, pathFinder, nodeChecker)) return false; } if (direction.x != 0.f){ if (!checkVerticalTile(initialPos, targetPos, direction, anotherPos, pathFinder, nodeChecker)) return false; } return true; } bool RayCast::checkHorizontalTile(const sf::Vector2f& initialPos, const sf::Vector2f& targetPos, const sf::Vector2f& direction, std::vector<sf::Vector2f>& otherPos, PathFinder* pathFinder, const RayCast::TileChecker& tileChecker) { AStarNode *targetNode = pathFinder->sceneToGraph(targetPos); if (!targetNode) return false; sf::Vector2f tileSize = pathFinder->getTileSize(); sf::Vector2f curPosition = initialPos; //here it is y / x, since we would like to know //how much distance has X travelled when Y reached the tileSizeHeight //float dirRadian = std::atan2(std::abs(direction.y), std::abs(direction.x)); float dirRadian = std::atan2(direction.y, direction.x); float degree = Utility::toDegree(dirRadian); float anotherDegree = Utility::vectorToDegree(direction, false); float yA = tileSize.y; if (direction.y < 0.f) yA = -tileSize.y; float xA = tileSize.x / (std::tan(dirRadian)); if ((direction.x > 0.f && xA < 0.f) || (direction.x < 0.f && xA > 0.f)) xA *= -1.f; //int index = -1; int index = 0; sf::Vector2f* indexPos = &curPosition; std::vector<sf::Vector2f> designatedPosList; sf::Vector2f diffToTarget = targetPos - initialPos; otherPos.push_back(initialPos); while (index < static_cast<int>(otherPos.size())){ //if (index >= 0){ indexPos = &otherPos[index]; designatedPosList.push_back(*indexPos + diffToTarget); //} float newY = std::floor(indexPos->y / tileSize.y) * tileSize.y - 1.f; if (direction.y > 0.f){ newY = std::floor(indexPos->y / tileSize.y) * tileSize.y + tileSize.y; } float additionalX = (std::abs(indexPos->y - newY)) / std::tan(dirRadian); if ((direction.x > 0.f && additionalX < 0.f) || (direction.x < 0.f && additionalX > 0.f)) additionalX *= -1.f; float newX = indexPos->x + additionalX; indexPos->x = newX; indexPos->y = newY; index++; } //designatedPosList.push_back(targetPos); while (true){ bool falseFlag = false; int i = 0; for (auto iterPos = otherPos.begin(); iterPos != otherPos.end();){ const sf::Vector2f& designatedPos = designatedPosList[i]; if ( (direction.x == 0.f || (direction.x > 0.f && iterPos->x >= designatedPos.x) || (direction.x < 0.f && iterPos->x <= designatedPos.x)) && (direction.y == 0.f || (direction.y > 0.f && iterPos->y >= designatedPos.y) || (direction.y < 0.f && iterPos->y <= designatedPos.y)) ) { AStarNode* designatedNode = pathFinder->sceneToGraph(designatedPos); /*if (!designatedNode) falseFlag = true; if (std::find(toBeAvoidedNodes.begin(), toBeAvoidedNodes.end(), designatedNode) != toBeAvoidedNodes.end()) { falseFlag = true; if (contactedAvoidedNodes) *contactedAvoidedNodes = true; } if (designatedNode && designatedNode->tile) collidedTileList.push_back(designatedNode->tile);*/ if (!tileChecker(designatedNode)) falseFlag = true; iterPos = otherPos.erase(iterPos); designatedPosList.erase(designatedPosList.begin() + i); continue; } AStarNode* node = pathFinder->sceneToGraph((*iterPos)); if (!tileChecker(node)) falseFlag = true; /*if (!node) falseFlag = true; if (std::find(toBeAvoidedNodes.begin(), toBeAvoidedNodes.end(), node) != toBeAvoidedNodes.end()) { falseFlag = true; if (contactedAvoidedNodes) *contactedAvoidedNodes = true; } if (node && node->tile) collidedTileList.push_back(node->tile);*/ iterPos->x += xA; iterPos->y += yA; i++; iterPos++; } if (falseFlag /*|| !collidedTileList.empty()*/) return false; if (otherPos.empty()) return true; } return true; } /*bool RayCast::checkHorizontalTile(const sf::Vector2f& initialPos, const sf::Vector2f& targetPos, const sf::Vector2f& direction, std::vector<sf::Vector2f>& otherPos, PathFinder* pathFinder, const std::vector<AStarNode*>& toBeAvoidedNodes, bool* contactedAvoidedNodes, std::vector<Entity*>& collidedTileList) { AStarNode *targetNode = pathFinder->sceneToGraph(targetPos); if (!targetNode) return false; sf::Vector2f tileSize = pathFinder->getTileSize(); sf::Vector2f curPosition = initialPos; //here it is y / x, since we would like to know //how much distance has X travelled when Y reached the tileSizeHeight //float dirRadian = std::atan2(std::abs(direction.y), std::abs(direction.x)); float dirRadian = std::atan2(direction.y, direction.x); float degree = Utility::toDegree(dirRadian); float anotherDegree = Utility::vectorToDegree(direction, false); float yA = tileSize.y; if (direction.y < 0.f) yA = -tileSize.y; float xA = tileSize.x / (std::tan(dirRadian)); if ((direction.x > 0.f && xA < 0.f) || (direction.x < 0.f && xA > 0.f)) xA *= -1.f; //int index = -1; int index = 0; sf::Vector2f* indexPos = &curPosition; std::vector<sf::Vector2f> designatedPosList; sf::Vector2f diffToTarget = targetPos - initialPos; otherPos.push_back(initialPos); while (index < static_cast<int>(otherPos.size())){ //if (index >= 0){ indexPos = &otherPos[index]; designatedPosList.push_back(*indexPos + diffToTarget); //} float newY = std::floor(indexPos->y / tileSize.y) * tileSize.y - 1.f; if (direction.y > 0.f){ newY = std::floor(indexPos->y / tileSize.y) * tileSize.y + tileSize.y; } float additionalX = (std::abs(indexPos->y - newY)) / std::tan(dirRadian); if ((direction.x > 0.f && additionalX < 0.f) || (direction.x < 0.f && additionalX > 0.f)) additionalX *= -1.f; float newX = indexPos->x + additionalX; indexPos->x = newX; indexPos->y = newY; index++; } //designatedPosList.push_back(targetPos); while (true){ bool falseFlag = false; int i = 0; for (auto iterPos = otherPos.begin(); iterPos != otherPos.end();){ const sf::Vector2f& designatedPos = designatedPosList[i]; if ( (direction.x == 0.f || (direction.x > 0.f && iterPos->x >= designatedPos.x) || (direction.x < 0.f && iterPos->x <= designatedPos.x)) && (direction.y == 0.f || (direction.y > 0.f && iterPos->y >= designatedPos.y) || (direction.y < 0.f && iterPos->y <= designatedPos.y)) ) { AStarNode* designatedNode = pathFinder->sceneToGraph(designatedPos); if (!designatedNode) falseFlag = true; if (std::find(toBeAvoidedNodes.begin(), toBeAvoidedNodes.end(), designatedNode) != toBeAvoidedNodes.end()) { falseFlag = true; if (contactedAvoidedNodes) *contactedAvoidedNodes = true; } if (designatedNode && designatedNode->tile) collidedTileList.push_back(designatedNode->tile); //if everything is safe, we delete it from further calculation //if (!falseFlag && collidedTileList.empty()){ iterPos = otherPos.erase(iterPos); designatedPosList.erase(designatedPosList.begin() + i); continue; //} } AStarNode* node = pathFinder->sceneToGraph((*iterPos)); if (!node) falseFlag = true; if (std::find(toBeAvoidedNodes.begin(), toBeAvoidedNodes.end(), node) != toBeAvoidedNodes.end()) { falseFlag = true; if (contactedAvoidedNodes) *contactedAvoidedNodes = true; } if (node && node->tile) collidedTileList.push_back(node->tile); iterPos->x += xA; iterPos->y += yA; i++; iterPos++; } if (falseFlag || !collidedTileList.empty()) return false; if (otherPos.empty()) return true; } return true; }*/ bool RayCast::checkVerticalTile(const sf::Vector2f& initialPos, const sf::Vector2f& targetPos, const sf::Vector2f& direction, std::vector<sf::Vector2f>& otherPos, PathFinder* pathFinder, const TileChecker& tileChecker) { AStarNode *targetNode = pathFinder->sceneToGraph(targetPos); if (!targetNode) return false; sf::Vector2f tileSize = pathFinder->getTileSize(); sf::Vector2f curPosition = initialPos; //float dirRadian = std::atan2(std::abs(direction.x), std::abs(direction.y)); float dirRadian = std::atan2(direction.x, direction.y); float xA = tileSize.x; if (direction.x < 0.f) xA = -tileSize.x; float yA = tileSize.y / std::tan(dirRadian); if ((direction.y > 0.f && yA < 0.f) || (direction.y < 0.f && yA > 0.f)) yA *= -1.f; int index = 0; sf::Vector2f* indexPos = &curPosition; std::vector<sf::Vector2f> designatedPosList; sf::Vector2f diffToTarget = targetPos - initialPos; otherPos.push_back(initialPos); while (index < static_cast<int>(otherPos.size())){ //if (index >= 0){ indexPos = &otherPos[index]; designatedPosList.push_back(*indexPos + diffToTarget); //} float newX = std::floor(indexPos->x / tileSize.x) * tileSize.x - 1.f; if (direction.x > 0.f){ newX = std::floor(indexPos->x / tileSize.x) * tileSize.x + tileSize.x; //if (index < 0) // newX--; } float additionalY = (std::abs(indexPos->x - newX)) / std::tan(dirRadian); if ((direction.y > 0.f && additionalY < 0.f) || (direction.y < 0.f && additionalY > 0.f)) additionalY *= -1.f; float newY = indexPos->y + additionalY; indexPos->x = newX; indexPos->y = newY; index++; } //horizontal line checking while (true){ bool falseFlag = false; int i = 0; for (auto iterPos = otherPos.begin(); iterPos != otherPos.end();){ const sf::Vector2f& designatedPos = designatedPosList[i]; if ( (direction.x == 0.f || (direction.x > 0.f && iterPos->x >= designatedPos.x) || (direction.x < 0.f && iterPos->x <= designatedPos.x)) && (direction.y == 0.f || (direction.y > 0.f && iterPos->y >= designatedPos.y) || (direction.y < 0.f && iterPos->y <= designatedPos.y)) ) { AStarNode* designatedNode = pathFinder->sceneToGraph(designatedPos); /*if (!designatedNode) falseFlag = true; if (std::find(toBeAvoidedNodes.begin(), toBeAvoidedNodes.end(), designatedNode) != toBeAvoidedNodes.end()) { falseFlag = true; if (contactedAvoidedNodes) *contactedAvoidedNodes = true; } if (designatedNode && designatedNode->tile) collidedTileList.push_back(designatedNode->tile);*/ if (!tileChecker(designatedNode)) falseFlag = true; //if everything is safe, we delete it from further calculation //if (!falseFlag && collidedTileList.empty()){ iterPos = otherPos.erase(iterPos); designatedPosList.erase(designatedPosList.begin() + i); continue; //} } AStarNode* node = pathFinder->sceneToGraph((*iterPos)); if (!tileChecker(node)) falseFlag = true; iterPos->x += xA; iterPos->y += yA; i++; iterPos++; } if (falseFlag) return false; if (otherPos.empty()) return true; } return true; } /*bool RayCast::checkVerticalTile(const sf::Vector2f& initialPos, const sf::Vector2f& targetPos, const sf::Vector2f& direction, std::vector<sf::Vector2f>& otherPos, PathFinder* pathFinder, const std::vector<AStarNode*>& toBeAvoidedNodes, bool* contactedAvoidedNodes, std::vector<Entity*>& collidedTileList) { AStarNode *targetNode = pathFinder->sceneToGraph(targetPos); if (!targetNode) return false; sf::Vector2f tileSize = pathFinder->getTileSize(); sf::Vector2f curPosition = initialPos; //float dirRadian = std::atan2(std::abs(direction.x), std::abs(direction.y)); float dirRadian = std::atan2(direction.x, direction.y); float xA = tileSize.x; if (direction.x < 0.f) xA = -tileSize.x; float yA = tileSize.y / std::tan(dirRadian); if ((direction.y > 0.f && yA < 0.f) || (direction.y < 0.f && yA > 0.f)) yA *= -1.f; int index = 0; sf::Vector2f* indexPos = &curPosition; std::vector<sf::Vector2f> designatedPosList; sf::Vector2f diffToTarget = targetPos - initialPos; otherPos.push_back(initialPos); while (index < static_cast<int>(otherPos.size())){ //if (index >= 0){ indexPos = &otherPos[index]; designatedPosList.push_back(*indexPos + diffToTarget); //} float newX = std::floor(indexPos->x / tileSize.x) * tileSize.x - 1.f; if (direction.x > 0.f){ newX = std::floor(indexPos->x / tileSize.x) * tileSize.x + tileSize.x; //if (index < 0) // newX--; } float additionalY = (std::abs(indexPos->x - newX)) / std::tan(dirRadian); if ((direction.y > 0.f && additionalY < 0.f) || (direction.y < 0.f && additionalY > 0.f)) additionalY *= -1.f; float newY = indexPos->y + additionalY; indexPos->x = newX; indexPos->y = newY; index++; } //horizontal line checking while (true){ bool falseFlag = false; int i = 0; for (auto iterPos = otherPos.begin(); iterPos != otherPos.end();){ const sf::Vector2f& designatedPos = designatedPosList[i]; if ( (direction.x == 0.f || (direction.x > 0.f && iterPos->x >= designatedPos.x) || (direction.x < 0.f && iterPos->x <= designatedPos.x)) && (direction.y == 0.f || (direction.y > 0.f && iterPos->y >= designatedPos.y) || (direction.y < 0.f && iterPos->y <= designatedPos.y)) ) { AStarNode* designatedNode = pathFinder->sceneToGraph(designatedPos); if (!designatedNode) falseFlag = true; if (std::find(toBeAvoidedNodes.begin(), toBeAvoidedNodes.end(), designatedNode) != toBeAvoidedNodes.end()) { falseFlag = true; if (contactedAvoidedNodes) *contactedAvoidedNodes = true; } if (designatedNode && designatedNode->tile) collidedTileList.push_back(designatedNode->tile); //if everything is safe, we delete it from further calculation //if (!falseFlag && collidedTileList.empty()){ iterPos = otherPos.erase(iterPos); designatedPosList.erase(designatedPosList.begin() + i); continue; //} } AStarNode* node = pathFinder->sceneToGraph((*iterPos)); if (!node) falseFlag = true; if (std::find(toBeAvoidedNodes.begin(), toBeAvoidedNodes.end(), node) != toBeAvoidedNodes.end()) { falseFlag = true; if (contactedAvoidedNodes) *contactedAvoidedNodes = true; } if (node && node->tile) collidedTileList.push_back(node->tile); iterPos->x += xA; iterPos->y += yA; i++; iterPos++; } if (falseFlag || !collidedTileList.empty()) return false; if (otherPos.empty()) return true; } return true; }*/
true
0530454c016677b3c70d94db58ad9d97d70edd90
C++
TeamLaw/SFML-V1.0
/EntityBuilder.cpp
UTF-8
638
2.9375
3
[]
no_license
#include "Environment.h" void buildPlayer(std::shared_ptr<Room> room) { player.setMaxHealth(100); player.setHealth(100); player.setDamage(10); player.setCurrentRoom(room); player.setFillColor(sf::Color::Green); player.center(); } Enemy buildEnemy(std::shared_ptr<Room> room) { int x = room->getPosition().x + 10, y = room->getPosition().y + 10, sizeX = room->getSize().x - 10, sizeY = room->getSize().y - 10; Enemy enemy; enemy.setMaxHealth(20); enemy.setHealth(20); enemy.setDamage(4); enemy.setFillColor(sf::Color::Red); enemy.setPosition(random(x, sizeX), random(y, sizeY)); return enemy; }
true
d1ff404e19e8749aa5f783945b2b6c719ee494a1
C++
Noppesj/Temere
/Temere/Graphic/graphicobject.cpp
UTF-8
2,528
2.734375
3
[]
no_license
#include "graphicobject.h" using namespace Temere::Graphic; GraphicObject::GraphicObject() : SceneObject() { mpShader = nullptr; mpTexture = nullptr; } GraphicObject::GraphicObject(const std::vector<Vertex*> &vertices,const std::vector<GLuint>& indices, const std::string& fileName) : SceneObject() { mpShader = nullptr; mpTexture = nullptr; mBufferResource = GraphicManager::getInstance()->loadBufferResource(vertices, indices, fileName); } GraphicObject::GraphicObject(const GraphicObject& ref) : SceneObject(ref) { mBufferResource = ref.mBufferResource; mpShader = ref.mpShader; mpTexture = ref.mpTexture; } GraphicObject::~GraphicObject() { } const GraphicObject& GraphicObject::operator=(const GraphicObject& ref) { if(this != &ref) { SceneObject::operator=(ref); mBufferResource = ref.mBufferResource; mpShader = ref.mpShader; mpTexture = ref.mpTexture; } return *this; } bool GraphicObject::loadShaders(const std::string& vertexShader_path, const std::string& fragmentShader_path) { mpShader = GraphicManager::getInstance()->loadShader(vertexShader_path, fragmentShader_path); return (mpShader != nullptr) ? true : false; } bool GraphicObject::loadTexture(const std::string& texturePath) { mpTexture = GraphicManager::getInstance()->loadTexture(texturePath); return (mpTexture != nullptr) ? true : false; } void GraphicObject::Draw(const glm::mat4 &projMatrix, const glm::mat4 &viewMatrix) { GraphicManager::getInstance()->UseShader(mpShader); int projectionMatrixLocation = glGetUniformLocation(mpShader->getShaderId(), "projectionMatrix"); // Get the location of our projection matrix in the shader int viewMatrixLocation = glGetUniformLocation(mpShader->getShaderId(), "viewMatrix"); // Get the location of our view matrix in the shader int modelMatrixLocation = glGetUniformLocation(mpShader->getShaderId(), "modelMatrix"); // Get the location of our model matrix in the shader glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projMatrix[0][0]); // Send our projection matrix to the shader glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, &viewMatrix[0][0]); // Send our view matrix to the shader glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, &getModelMatrix()[0][0]); // Send our model matrix to the shader GraphicManager::getInstance()->UseTexture(mpTexture); glBindVertexArray(mBufferResource->getVertexArrayObject()); glDrawElementsBaseVertex(GL_TRIANGLES, mBufferResource->getNumIndices(), GL_UNSIGNED_INT, 0, 0); glBindVertexArray(0); }
true
033337947f096d25478c3d861f5ff28536bfd81f
C++
ethanmcmike/LUNAR
/libraries/SmartBuffer.cpp
UTF-8
778
3.203125
3
[]
no_license
#include "SmartBuffer.h" SmartBuffer::SmartBuffer(){ } SmartBuffer::SmartBuffer(String key){ this->key = key; } SmartBuffer::~SmartBuffer(){} void SmartBuffer::setKey(String key){ this->key = key; } void SmartBuffer::put(char c){ //Already full if(index == key.length()){ return; } //Middle of key else if(c == key[index]){ index++; } //Start of key else if(c == key[0]){ index = 1; } //Incorrect character else { reset(); } } boolean SmartBuffer::full(){ return index >= key.length(); } void SmartBuffer::reset(){ index = 0; } void SmartBuffer::setFull(){ index = key.length(); } int SmartBuffer::getIndex(){ return index; } void SmartBuffer::set(int index){ int size = key.length(); this->index = (index > size) ? size : index; }
true
538531be0339803a56a56b106285d381fefbde9b
C++
Hikai/Map
/Main.cpp
UTF-8
805
3.09375
3
[]
no_license
#include "Map.h" int main() { Node * node1, * node2, * node3, * node4, * node5, * node6; Store * store_node; Store * store_node2; node1 = store_node->create_node(123); node2 = store_node->create_node(321); node3 = store_node->create_node(132); node4 = store_node2->create_node('a'); node5 = store_node2->create_node('b'); node6 = store_node2->create_node('c'); store_node->add_node(node1); store_node->add_node(node2); store_node->add_node(node3); store_node->add_node(node4); store_node->add_node(node5); store_node->add_node(node6); cout << store_node->root->data << endl; cout << store_node->root->left->data << endl; cout << store_node->root->right->data << endl; store_node->separate_node(node3); store_node->separate_node(node2); store_node->separate_node(node1); return 0; }
true
f94694c5a21990b1629b38fddb915eead790f35d
C++
RenShuhuai-Andy/code-for-book-BeginningAlgorithmContests2nd
/第3章/习题/习题3-2 分子量.cpp
UTF-8
2,417
2.9375
3
[]
no_license
#include <iostream> #include <cstdio> using namespace std; const char name[] = "CHON"; double weight[] = {12.01, 1.008, 16.00, 14.01}; int main(void) { int t; char s[81]; cin >> t; while (t--) { scanf("%s", s); int num; double sum = 0; int i = 0; while (s[i]) { int j; for (j = 0; j < 4; j ++) { if (s[i] == name[j]) break; } i ++; num = 1; if (isdigit(s[i])) num = (s[i++]-'0'); if (isdigit(s[i])) num = num*10 + (s[i++]-'0'); sum += num * weight[j]; } printf("%.3lf\n", sum); } return 0; } // WRONG // #include <stdio.h> // #include <string.h> // #include <math.h> // #include <ctype.h> // #define maxn 50 // char s[maxn]; // int main() // { // int T; // scanf("%d",&T); // while(T--) // { // memset(s,0,sizeof(s)); // scanf("%s",s); // float mass=0.0; // float total_mass=0.0; // int digit=0; // int num=0; // for(int i=0;i<strlen(s);i++) // { // if(s[i]=='C') // { // if(isalpha(s[i-1])) // num=1; // total_mass+=mass*num; // mass=12.01; // } // else if(s[i]=='H') // { // if(isalpha(s[i-1])) // num=1; // total_mass+=mass*num; // mass=1.008; // } // else if(s[i]=='O') // { // if(isalpha(s[i-1])) // num=1; // total_mass+=mass*num; // mass=16.00; // } // else if(s[i]=='N') // { // if(isalpha(s[i-1])) // num=1; // total_mass+=mass*num; // mass=14.01; // } // else if (isdigit(s[i])) // { // if(isalpha(s[i-1])) // digit=num=0; // num=num*pow(10,digit)+(s[i]-'0'); // digit++; // } // if(strlen(s)==1) // total_mass=mass; // } // printf("%.3f\n",total_mass); // } // return 0; // }
true
f7b0cd6695d8e263573138de2b6a27aed494cb3a
C++
Acka1357/ProblemSolving
/BeakjoonOJ/3000/3079_입국심사.cpp
UTF-8
515
2.515625
3
[]
no_license
// // Created by Acka on 2017. 8. 1.. // #include <stdio.h> int t[100000]; int main() { int N, M; scanf("%d %d", &N, &M); for(int i = 0; i < N; i++) scanf("%d", &t[i]); long long l = 0, r = (long long)M * t[0], m, ans, sum; while(l <= r){ m = (l + r) / 2; for(int i = sum = 0; i < N; i++) sum += m / t[i]; if(sum >= M){ ans = m; r = m - 1; } else l = m + 1; } printf("%lld\n", ans); return 0; }
true
ece7f5ae4972570261f1fc16221bd5cb824f1c95
C++
drjnmrh/udppipes
/sources/sockets/udpdgram.cpp
UTF-8
1,922
2.84375
3
[ "MIT" ]
permissive
#include "sockets/udpdgram.hpp" using namespace udp::sockets; UdpDgram::UdpDgram() noexcept : _pData(nullptr), _szData(0) {} UdpDgram::~UdpDgram() noexcept { if (_pData) delete[] _pData; } UdpDgram::UdpDgram(std::initializer_list<uint8_t> data) noexcept : _source() , _pData(0), _szData(data.size()) { _pData = new uint8_t[data.size()]; size_t i = 0; for (const auto& d : data) { _pData[i++] = d; } } UdpDgram::UdpDgram(UdpAddress sourceAddress, std::unique_ptr<uint8_t[]> && pData, size_t szData) noexcept : _source(std::move(sourceAddress)) , _pData(pData.release()), _szData(szData) {} UdpDgram::UdpDgram(UdpDgram&& another) noexcept : _source(std::move(another._source)) , _pData(another._pData), _szData(another._szData) { another._pData = nullptr; another._szData = 0; } UdpDgram& UdpDgram::operator = (UdpDgram&& another) noexcept { if (this != &another) { UdpDgram tmp(std::move(another)); Swap(tmp, *this); } return *this; } UdpDgram UdpDgram::clone() const noexcept { if (!_pData) { return UdpDgram(_source, nullptr, 0); } assert(_szData > 0); std::unique_ptr<uint8_t[]> pDataCopy = std::make_unique<uint8_t[]>(_szData); std::memcpy(pDataCopy.get(), _pData, _szData); return UdpDgram(_source, std::move(pDataCopy), _szData); } UdpDgram UdpDgram::clone(UdpAddress source) const noexcept { if (!_pData) { return UdpDgram(source, nullptr, 0); } assert(_szData > 0); std::unique_ptr<uint8_t[]> pDataCopy = std::make_unique<uint8_t[]>(_szData); std::memcpy(pDataCopy.get(), _pData, _szData); return UdpDgram(source, std::move(pDataCopy), _szData); } /*static*/ void UdpDgram::Swap(UdpDgram& a, UdpDgram& b) { std::swap(a._source, b._source); std::swap(a._pData, b._pData); std::swap(a._szData, b._szData); }
true
6ac91a53b71706f46ce1ae879ce0899cbb9d133e
C++
ciniak/algorithms
/UVa/Biorhytms/biorhytms.cpp
UTF-8
1,109
2.578125
3
[]
no_license
//============================================================================ // Name : biorhytms.cpp // Author : Michal Marcinkowski // Description : http://uva.onlinejudge.org - problem 756 - Biorhytms //============================================================================ #include <cstdio> #include <cstdlib> using namespace std; int main() { int p, e, i, d, result, rPE, k; int cAlfaPEI = 2, iP = 33, pPeP = 644, pPePiP = 21252, caseNumber = 1; scanf("%d %d %i %d", &p, &e, &i, &d); while ((p != -1) || (e != -1) || (i != -1) || (d != -1)) { rPE = ((p * -252) + (e * 253)); result = 0; k = 0; while (result <= d) { result = (pPeP * ((k++ * iP) - (rPE * cAlfaPEI) + (i * cAlfaPEI))) + rPE; if (result < 0) { result *= -1; if (result >= pPePiP) { result %= pPePiP; } result = pPePiP - result; } } result -= d; if (result > pPePiP) { result %= pPePiP; } if (result == 0) { result = pPePiP; } printf("Case %d: the next triple peak occurs in %d days.\n", caseNumber, result); caseNumber++; scanf("%d %d %i %d", &p, &e, &i, &d); } }
true
64c76007d6948939ca218f8ec4cc48cde027caca
C++
hhirsch/glPortal
/source/assets/map/XmlHelper.cpp
UTF-8
2,170
2.890625
3
[ "Zlib" ]
permissive
#include "XmlHelper.hpp" #include <stdexcept> #include <vector> #include <engine/core/math/Math.hpp> using namespace std; using namespace tinyxml2; namespace glPortal { std::string XmlHelper::mandatoryAttributeMessage("Mandatory attribute has not been defined."); std::string XmlHelper::invalidElementMessage( "pushAttributeToVector received an invalid XML-Element." ); /** * Pushes vector coordinates from an XML-element to a Vector3f. * Trying to pull attributes from a non-existing element is considered an exception. */ void XmlHelper::pushAttributeVertexToVector(XMLElement *xmlElement, Vector3f &targetVector) { if (xmlElement) { int xQueryResult = xmlElement->QueryFloatAttribute("x", &targetVector.x); int yQueryResult = xmlElement->QueryFloatAttribute("y", &targetVector.y); int zQueryResult = xmlElement->QueryFloatAttribute("z", &targetVector.z); if (xQueryResult == XML_NO_ATTRIBUTE){ throwMandatoryAttributeException("<x>"); } if (yQueryResult == XML_NO_ATTRIBUTE){ throwMandatoryAttributeException("<y>"); } if (zQueryResult == XML_NO_ATTRIBUTE){ throwMandatoryAttributeException("<z>"); } } else { throw runtime_error(invalidElementMessage); } } void XmlHelper::throwMandatoryAttributeException(const std::string &message){ throw runtime_error(mandatoryAttributeMessage + message); } void XmlHelper::extractPosition(XMLElement *xmlElement, Vector3f &position) { pushAttributeVertexToVector(xmlElement->FirstChildElement("position"), position); } void XmlHelper::extractRotation(XMLElement *xmlElement, Vector3f &rotation) { XMLElement *elm = xmlElement->FirstChildElement("rotation"); if (elm) { Vector3f tmpRot; pushAttributeVertexToVector(elm, tmpRot); rotation.pitch = rad(tmpRot.x); rotation.yaw = rad(tmpRot.y); rotation.roll = rad(tmpRot.z); } else { rotation.pitch = rotation.yaw = rotation.roll = 0; } } void XmlHelper::extractScale(XMLElement *xmlElement, Vector3f &scale) { pushAttributeVertexToVector(xmlElement->FirstChildElement("scale"), scale); } } /* namespace glPortal */
true
dddfbbb2c6723ff02953400b0162ee6fddface2e
C++
rezikun/BigInt
/BigInt/main.cpp
UTF-8
252
2.84375
3
[]
no_license
#include "big_int.h" #include <iostream> int main() { while (true) { std::string first_s, second_s; std::cin >> first_s >> second_s; big_int::BigInt first(first_s); big_int::BigInt second(second_s); std::cout << first / second << "\n"; } }
true
a1e6ecadd6e4bec611c9bcce45cfa991b02b4865
C++
sandereto/AED
/Aula01/Exercicio2.cpp
UTF-8
213
2.59375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> float calcula (float x, float y, float z){ return (sqrtl(x+y+z)); } main(){ printf("Resultado: %3.2f\n",calcula(2,3,4)); }
true
6957573724e87510ea3d10bd39c003b16f846c92
C++
alanscottthomas/StudentPrograms
/CSI-230/lab4/AlanAssignment4Chap6Prob14.cpp
UTF-8
1,630
3.46875
3
[]
no_license
//Alan Thomas //Assignment#4 2/19/2015 //Chapter6 Problem 14 #include <iostream> using namespace std; //in-patient function double Patient(int days,double rate,double charges,double medication){ double total; total=(days*rate)+charges+medication; return total; } //out patient function double Patient(double charges, double medication){ double total; total=charges+medication; return total; } //main function int main(){ char ans; int days; double rate, charges, medication; cout<<"Please enter 'i' for in-patient billing and 'o' for outpatient billing: "; cin>>ans; //input validation while(!(ans =='i' || ans=='I'||ans=='o'||ans=='O')){ cout<<"Invalid input"; cout<<endl<<"Please enter 'i' for in-patient billing and 'o' for outpatient billing: "; cin.clear(); cin.ignore(); cin>>ans; } //inpatient if(ans == 'I' || ans == 'i'){ cout<<"Number of days in hospital: "; cin>>days; cout<<"Enter rate: "; cin>>rate; cout<<"Enter any additonal charges: "; cin>>charges; cout<<endl<<"Enter charges pertaining to medication cost: "; cin>>medication; cout<<endl<<"The total for this hospital stay is: $"<<Patient(days,rate,charges,medication)<<endl; system("PAUSE"); } //outpatient else if (ans=='o' || ans=='O'){ cout<<"Enter any charges encured during this patient's visit: "; cin>>charges; cout<<endl<<"Enter charges that occured due to medication administration: "; cin>>medication; cout<<endl<<"The total charge for this patient's outpatient visit is: $"<<Patient(charges,medication)<<endl; system("PAUSE"); } return 0; }
true
c6e44344cd75cd72c4db1c13842ff4252f0323b4
C++
htr751/MyWindowsDebugger
/MyWindowsDebugger/DebugEventController.cpp
UTF-8
926
2.578125
3
[]
no_license
#include"DebugEventController.h" #include"windowsUtillities.h" #include"Utillities.h" #include<stdexcept> void DebugEventController::WaitForDebugEvent(){ DEBUG_EVENT event = { 0 }; bool err = WaitForDebugEventEx(&event, INFINITE); if (!err) CreateRunTimeError(GetLastErrorMessage()); this->event = event; } void DebugEventController::ContinueDebugee(DWORD continueStatus) const noexcept { if (continueStatus != DBG_CONTINUE && continueStatus != DBG_EXCEPTION_NOT_HANDLED) CreateLogicError(L"continue status parameter is invalid"); bool err = ContinueDebugEvent(this->event.getProcessID(), this->event.getThreadID(), continueStatus); if (!err) CreateRunTimeError(GetLastErrorMessage()); } ThreadID_t DebugEventController::GetCurrentThreadID() const noexcept { return this->event.getThreadID(); } ProcessID_t DebugEventController::GetCurrentProcessID() const noexcept { return this->event.getProcessID(); }
true
e4829390e5a8ba506773d004878c533b8e2fe208
C++
arrebole/Leisure
/src/OJ/1246【循环嵌套】【数组】求非素数(质数/main.cc
UTF-8
639
2.96875
3
[]
no_license
#include <stdio.h> #include <vector> using namespace std; int main() { vector<int> vec; int *a = new int[20]; for (int i = 0; i < 20; i++) { scanf("%d", a + i); } for (int i = 0; i < 20; i++) { for (int j = i+1; j < 20; j++) { if (a[j] % a[i] == 0) { vec.push_back(a[j]); a[j] = 1; } if (a[i] % a[j] == 0) { vec.push_back(a[i]); } } } for (int i = 0; i < vec.size(); i++) { printf("%d\n", vec[i]); } delete[] a; return 0; }
true
11a733573b3faff1386f2b663f5bf05b933152fe
C++
trustee-wallet/djinni-react-native
/support-lib/cpp/JobQueueImpl.hpp
UTF-8
515
2.546875
3
[ "Apache-2.0" ]
permissive
#include "JobQueue.hpp" #include "Job.hpp" #include <functional> #include <list> #include <memory> #include <mutex> class JobQueueImpl : public JobQueue { public: static std::shared_ptr<JobQueueImpl> create(); JobQueueImpl(); virtual ~JobQueueImpl(); std::shared_ptr<Job> poll() override; void interruptPoll() override; void enqueue(std::function<void()> function); private: std::list<std::function<void()>> mQueue; std::mutex mMutex; std::condition_variable mCondition; };
true
776d114f649ce3f2dc2e7484559d92330d887214
C++
kaushal-banthia/Library-Management-System
/LMS.cpp
UTF-8
19,319
3.171875
3
[]
no_license
#include <bits/stdc++.h> #include <dirent.h> #include <sys/types.h> using namespace std; //Note: All the books are inside a directory, whose name is taken as input from the user //function that checks if a string ends with another string bool hasEnding (string fullString, string ending); //function that is used to read a directory string read_directory(); //function to display all the available files which are named in "index.txt" void display_files(); //function to search for a book in the directory via its title or its author name void search_files(string directory); //function that prints a book to the console void print_book(vector <string> book, string directory); //function that performs different analytics on the Books (Play and Novel). Can be extended to other genres as well void analytics(vector <string> book, string directory); //function that gives the complete filename of the book chosen string get_filename(vector <string> book, string directory); //class for Book class Book { protected: string filename, input; public: //constructor Book(string filename_) { filename = filename_; } //setter function for input string set_input() { cin>>input; return input; } //getter function for filename string get_filename() { return filename; } }; //subclass of class Book for Novel class Novel: public Book { int para_chapter, chapter_number = 0;; int chapter_array[5] = {0, 0, 0, 0, 0}; public: //constructor Novel(string filename) : Book(filename){} //function for choosing whether to work on a paragraph or a chapter int para_or_chap() { cout<<"Enter 1 for looking in paragraphs\nEnter 2 for looking in chapters"<<endl; cin>>para_chapter; return para_chapter; } //function that changes the rankings of the top 5 paragraphs or chapters void transfer(vector <vector<string>> &top, int top_count[], int limit, vector <string> para, int count) { for (int i = 4; i > limit; i--) { top_count[i] = top_count[i-1]; top[i] = top[i-1]; chapter_array[i] = chapter_array[i-1]; } top_count[limit] = count; top[limit] = para; chapter_array[limit] = chapter_number; } //function that finds the top 5 paragraphs or chapters void counter() { vector <string> para; vector <vector <string>> top { {""}, {""}, {""}, {""}, {""} }; int count = 0; int top_count[5] = {0, 0, 0, 0, 0}; string line; fstream book_novel; book_novel.open(filename, ios::in); while (!book_novel.eof()) { getline(book_novel, line); if ((para_chapter == 1 && line == "") || (para_chapter == 2 && line.substr(0, 7) == "CHAPTER")) { if (line.substr(0, 7) == "CHAPTER") chapter_number++; if (top_count[0] < count) transfer(top, top_count, 0, para, count); else if (top_count[1] < count) transfer(top, top_count, 1, para, count); else if (top_count[2] < count) transfer(top, top_count, 2, para, count); else if (top_count[3] < count) transfer(top, top_count, 3, para, count); else if (top_count[4] < count) transfer(top, top_count, 4, para, count); para.clear(); count = 0; } else { para.push_back(line); istringstream iss(line); do { string subs; iss >> subs; char end_char = subs[subs.length()-1]; if (end_char == '.' || end_char == ',' || end_char == '!' || end_char == ';' || end_char == ':' || end_char == '?' || end_char == '&') subs = subs.substr(0, subs.length()-1); transform(subs.begin(), subs.end(), subs.begin(), ::tolower); transform(input.begin(), input.end(), input.begin(), ::tolower); if (subs == input) count++; } while (iss); } } chapter_number++; if (top_count[0] < count) transfer(top, top_count, 0, para, count); else if (top_count[1] < count) transfer(top, top_count, 1, para, count); else if (top_count[2] < count) transfer(top, top_count, 2, para, count); else if (top_count[3] < count) transfer(top, top_count, 3, para, count); else if (top_count[4] < count) transfer(top, top_count, 4, para, count); string title; if (para_chapter == 1) title = "Paragraph"; else title = "Chapter"; cout<<endl; for (int i = 0; i < 5; i++) { cout<<title<<" at rank "<<i+1<<" for number of matching words"<<endl; if (para_chapter == 2) cout<<"Chapter Number: ["<<chapter_array[i]-1<<"]"<<endl; // for (int j = 0; j < top[i].size(); j++) // { // cout<<top[i][j]<<endl; // } //************************************************* //uncomment the above 4 lines only if you want to display the chapter too! //************************************************* cout<<"Number of words matched: "<<top_count[i]<<endl<<endl; } } }; //subclass of class Book for Play class Play: public Book { vector <vector<vector<string>>> vec; public: //constructor Play(string filename) : Book(filename){} //function to read in all the characters that appear in the play scenewise void reader() { int act_number = 0, scene_number = 0; vector<vector<string>> act; vector<string> scene; fstream play_book; play_book.open(filename, ios::in); while (!play_book.eof()) { string line; getline(play_book, line); int flag = 1; int caps = 1; int i; for (i = 0; i < line.length(); i++) { if (line[i] == '.') break; } for (int j = 0; j < i; j++) { if (islower(line[j])) { flag = 0; break; } } if (flag == 1) line = line.substr(0, i+1); if ((flag || line.find("SCENE") != string::npos) && line.length() != 0) { //3 cases->its an act, its a scene, its characters if (line.find("ACT") != string::npos) { vec.push_back(act); act.clear(); act_number++; scene_number = 0; continue; } if (line.find("SCENE") != string::npos) { act.push_back(scene); scene.clear(); scene_number++; continue; } if (line[0] != '*' && act_number) { scene.push_back(line.substr(0, line.length()-1)); } } } act.push_back(scene); vec.push_back(act); } //function to find the other characters that appear along with the input character in the same scene void counter() { vector <string> characters; transform(input.begin(), input.end(), input.begin(), ::toupper); for (auto i = vec.begin(); i != vec.end(); i++) { for (auto j = i->begin(); j != i->end(); j++) { if (count(j->begin(), j->end(), input)) { for (auto k = j->begin(); k != j->end(); k++) { characters.push_back(*k); } } } } set<string> s; for (int i = 0; i < characters.size(); i++) { s.insert(characters[i]); } s.erase(input); cout<<"Characters that appeared with "<<input<<" in at least one scene:"<<endl; for (auto i = s.begin(); i != s.end(); i++) { cout<<*i<<endl; } if (s.size() == 0) cout<<"No Characters appeared with "<<input<<endl; } }; //main function int main(void) { string directory = read_directory(); display_files(); search_files(directory); } //function that checks if a string ends with another string bool hasEnding (string fullString, string ending) { if (fullString.length() >= ending.length()) return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending)); else return false; } //function that is used to read a directory string read_directory() { DIR *dr; struct dirent *en; cout<<"Enter the name of the directory"<<endl; string directory; cin>>directory; string first = "./"; directory = first + directory + first[1]; dr = opendir(directory.c_str()); //open all directory if (dr) { while ((en = readdir(dr)) != NULL) { if (hasEnding(en->d_name, ".txt")) { fstream file; file.open("index.txt", ios::in); if (!file) file.open("index.txt", ios::out); string line; int flag = 0; while(!file.eof()) { getline(file, line); if (hasEnding(line, en->d_name)) { flag = 1; break; } } if (flag == 0) { cout<<"New book found"<<endl<<"Name: "<<en->d_name<<endl<<"What is the type of this book? (Novel or Play)"<<endl; string type; cin>>type; fstream file_write; file_write.open("index.txt", ios::app); file_write<<"Filename: "<<en->d_name<<endl<<"Type: "<<type<<endl; string name = en->d_name; fstream file_text; file_text.open(directory + name, ios::in); while (!file_text.eof()) { string line; getline(file_text, line); if (line.substr(0, 5) == "Title") file_write<<line<<endl; if (line.substr(0, 6) == "Author") { file_write<<line<<endl; break; } } file_write.close(); file_text.close(); } file.close(); } } closedir(dr); //close all directory } return directory; } //function to display all the available files which are named in "index.txt" void display_files() { fstream file_display; file_display.open("index.txt", ios::in); while (!file_display.eof()) { string line; cout<<endl; for (int i = 0; i < 4; i++) { getline(file_display, line); cout<<line<<endl; } } file_display.close(); } //function to search for a book in the directory via its title or its author name void search_files(string directory) { while (1) { int count = 0; vector <string> book; while (1) { cout<<"Enter 1 to search a book by its Title"<<endl<<"Enter 2 to search a book by its Author's Name"<<endl; int searcher; cin>>searcher; int flag = 0; if (searcher == 1) { cout<<"Enter the name of the title of the book"<<endl; string name; getline(cin, name); getline(cin, name); fstream file; file.open("index.txt", ios::in); while(!file.eof()) { string filename, type, title, author; getline(file, filename); getline(file, type); getline(file, title); getline(file, author); transform(title.begin(), title.end(), title.begin(), ::tolower); transform(name.begin(), name.end(), name.begin(), ::tolower); if (title.find(name) != string::npos) { count++; cout<<endl<<"Book Found"<<endl<<"["<<count<<"]"<<endl; cout<<filename<<endl; cout<<type<<endl; cout<<title<<endl; cout<<author<<endl; book.push_back(filename); flag = 1; } } if (flag == 0) cout<<"No book found"<<endl; break; } else if (searcher == 2) { cout<<"Enter the name of the author of the book"<<endl; string name; getline(cin, name); getline(cin, name); fstream file; file.open("index.txt", ios::in); while(!file.eof()) { string filename, type, title, author; getline(file, filename); getline(file, type); getline(file, title); getline(file, author); transform(author.begin(), author.end(), author.begin(), ::tolower); transform(name.begin(), name.end(), name.begin(), ::tolower); if (author.find(name) != string::npos) { count++; cout<<endl<<"Book Found"<<endl<<"["<<count<<"]"<<endl; cout<<filename<<endl; cout<<type<<endl; cout<<title<<endl; cout<<author<<endl; book.push_back(filename); flag = 1; } } if (flag == 0) cout<<"No book found"<<endl; break; } else { cout<<"Wrong number input"<<endl; continue; } } cout<<endl<<"Number of books found: "<<count<<endl; if (book.size() != 0) { int select; while(1) { cout<<"Enter 1 to read the book. Enter 2 to perform analytics tasks on it."<<endl; cin>>select; if (select == 1) { print_book(book, directory); cout<<endl<<"Book Finshed"<<endl; break; } else if (select == 2) { analytics(book, directory); break; } else cout<<"Wrong number entered. Enter again"<<endl; } } cout<<"Enter 1 to search again. Enter anything else to exit"<<endl; int exiter; cin>>exiter; if (exiter != 1) break; } } //function that prints a book to the console void print_book(vector <string> book, string directory) { string filename = get_filename(book, directory); if (filename == "invalid") return; fstream file; file.open(filename, ios::in); while (!file.eof()) { string line; for (int i = 0; i < 50; i++) { getline(file, line); cout<<line<<endl; } int flag; //0 for next, 1 for exit while (1) { cout<<endl<<endl<<"Press 'N' to go to the next page and 'E' to exit"<<endl; char parser; cin>>parser; if (parser == 'n' || parser == 'N') { flag = 0; break; } else if (parser == 'e' || parser == 'E') { flag = 1; break; } else cout<<"Wrong letter entered"<<endl; } if (flag == 0) continue; else break; } } //function that performs different analytics on the Books (Play and Novel). Can be extended to other genres as well void analytics(vector <string> book, string directory) { string filename = get_filename(book, directory); if (filename == "invalid") return; string type; fstream file; file.open("index.txt", ios::in); while(!file.eof()) { string file_name, type_, title, author; getline(file, file_name); getline(file, type_); getline(file, title); getline(file, author); if (hasEnding(filename, file_name.substr(10, file_name.length()-10))) { type = type_.substr(6, type_.length()-6); break; } } if (type == "Novel" || type == "novel") { Novel parser(filename); //object for class Novel cout<<"Enter the input word"<<endl; string input = parser.set_input(); while(1) { int para_or_chapter = parser.para_or_chap(); if (para_or_chapter != 1 && para_or_chapter != 2) { cout<<"Wrong Input"; continue; } parser.counter(); break; } } else if (type == "Play" || type == "play") { Play parser(filename); //object for class Play cout<<"Enter the Input Character"<<endl; string input = parser.set_input(); parser.reader(); parser.counter(); } } //function that gives the complete filename of the book chosen string get_filename(vector <string> book, string directory) { cout<<endl<<"Enter the serial number of the book that you want to get displayed (The number displayed in the square bracketrs)"<<endl; int serial; cin>>serial; //if the serial number entered is invalid if (serial > book.size() || serial <= 0) { cout<<"Invalid serial number"<<endl; return "invalid"; } return (directory + book[serial-1].substr(10, book[serial-1].length()-10)); }
true
223e0128d6adffdf0f6bdbd919d792cec9b2f635
C++
TheCell/Sudoku
/sudokugenerator.cpp
UTF-8
37,558
2.84375
3
[]
no_license
#include <QCoreApplication> #include "sudokugenerator.h" #include <iostream> #include <algorithm> // for std::find #include <iterator> // for std::begin, std::end #include <string> Sudokugenerator::Sudokugenerator() { } void Sudokugenerator::init(int seed) { //Sudokugenerator::generateSudoku(seed); Sudokugenerator::prepareArray(); //std::string sudokuString = "003020600900305001001806400008102900700000008006708200002609500800203009005010300"; std::string sudokuString = "000000600000305001001806400008102900700000008006708200002609500800203009005010300"; if (Sudokugenerator::loadFromFile(sudokuString)) { std::cout << "loading success!"; } else { std::cout << "loading failed!"; } } void Sudokugenerator::prepareArray() { // fill floor 1-9 with numbers for (int i = 1; i < 10; i++) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { Sudokugenerator::sudokuArray[x][y][i] = (i); } } } // floor 0 is the playfloor for (int y = 9; y >= 0; y--) { for (int x = 0; x < 9; x++) { Sudokugenerator::sudokuArray[x][y][0] = 0; } } Sudokugenerator::arrayChanged = true; } void Sudokugenerator::generateSudoku(int seed) { Sudokugenerator::initGenerator(seed); /*while (Sudokugenerator[x][y][0] == 0) { }*/ // one problem remains. I can run into a dead end. int randomNumber = 0; /*for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { while (Sudokugenerator::sudokuArray[x][y][0] == 0) { randomNumber = Sudokugenerator::numberGenerator.getNumber(); if (Sudokugenerator::numberCanBePicked(x, y, randomNumber)) { Sudokugenerator::removeNumberFromArray(x, y, randomNumber); printf("remove Number: %d\n", randomNumber); Sudokugenerator::sudokuArray[x][y][0] = randomNumber; } Sudokugenerator::showArray(); } Sudokugenerator::showArray(); } }*/ /* * working! */ /*int x = 0; int y = 0; for (int i = 0; i < 7; i++) { bool numberRemoved = false; randomNumber = Sudokugenerator::numberGenerator.getNumber(); while (!numberRemoved) { x = Sudokugenerator::numberGenerator.getNumber(); y = Sudokugenerator::numberGenerator.getNumber(); if (Sudokugenerator::numberCanBePicked(x, y, randomNumber)) { Sudokugenerator::removeNumberFromArray(x, y, randomNumber); numberRemoved = true; } } }*/ for (int i = 0; i < 9; i++) { bool numberRemoved = false; bool numberRemoved2 = false; while (!numberRemoved) { randomNumber = Sudokugenerator::numberGenerator.getNumber(); if (Sudokugenerator::numberCanBePicked(i, 0, randomNumber)) { Sudokugenerator::removeNumberFromArray(i, 0, randomNumber); numberRemoved = true; } } if (i > 0) { while (!numberRemoved2) { randomNumber = Sudokugenerator::numberGenerator.getNumber(); if (Sudokugenerator::numberCanBePicked(0, i, randomNumber)) { Sudokugenerator::removeNumberFromArray(0, i, randomNumber); numberRemoved2 = true; } } } } Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(1); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(2); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(3); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(4); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(5); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(6); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(7); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(8); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(9); /*bool testnu = true; while(testnu) { randomNumber = Sudokugenerator::numberGenerator.getNumber(); if (Sudokugenerator::numberCanBePicked(2,1,randomNumber)) { Sudokugenerator::removeNumberFromArray(2,1,randomNumber); testnu = false; } } testnu = true; while(testnu) { randomNumber = Sudokugenerator::numberGenerator.getNumber(); if (Sudokugenerator::numberCanBePicked(2,2,randomNumber)) { Sudokugenerator::removeNumberFromArray(2,2,randomNumber); testnu = false; } } testnu = true; while(testnu) { randomNumber = Sudokugenerator::numberGenerator.getNumber(); if (Sudokugenerator::numberCanBePicked(1,2,randomNumber)) { Sudokugenerator::removeNumberFromArray(1,2,randomNumber); testnu = false; } } Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(3); auto test = Sudokugenerator::blockHasOnlyOneValue(1, 1); printf("block has: %d,%d,%d\n", std::get<0>(test),std::get<1>(test),std::get<2>(test)); int test2 = Sudokugenerator::cellHasOnlyOneValue(1, 1); printf("Cell has: %d\n", test2);*/ Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(); } void Sudokugenerator::showArray(int floor) { if (Sudokugenerator::arrayChanged) { printf("3D Array, Floor number: %d\n", floor); printf(" |----------+-----------+----------| \n"); for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { if (x == 0) { printf(" | %d ", Sudokugenerator::sudokuArray[x][y][floor]); } else if (x == 8) { printf(" %d | ", Sudokugenerator::sudokuArray[x][y][floor]); } else if (x % 3 == 0) { printf(" | %d ", Sudokugenerator::sudokuArray[x][y][floor]); } else { printf(" %d ", Sudokugenerator::sudokuArray[x][y][floor]); } if ((y + 1) % 3 == 0 && x == 8) { printf("\n |----------+-----------+----------|"); } } printf("\n"); } Sudokugenerator::arrayChanged = false; } } bool Sudokugenerator::numberCanBePicked(int x, int y, int number) { int x1 = 0; int y1 = 0; //Sudokugenerator::showArray(number); if (Sudokugenerator::sudokuArray[x][y][number] != number) { return false; } // check if the block does not already contain this number if ((x != 2 && y != 2) || (x != 5 && y != 5) || (x != 8 && y != 8)) { if (x < 3) { x1 = 0; } else if (x < 6) { x1 = 3; } else { x1 = 6; } if (y < 3) { y1 = 0; } else if (y < 6) { y1 = 3; } else { y1 = 6; } // check blocks bool secondNumberExists = false; for (int i = 1; (i < 10 && !secondNumberExists); i++) { for (int y2 = 0; (y2 < 3 && !secondNumberExists); y2++) { for (int x2 = 0; (x2 < 3 && !secondNumberExists); x2++) { //printf("_%d_", x2); //printf(".%d.", x2 < 3); if (Sudokugenerator::sudokuArray[x1 + x2][y1 + y2][i] == i ) { secondNumberExists = true; } } } } if (!secondNumberExists) { return false; } // check line number next to this one In case we snatch the last free place for this one for (int i = 1; i < 10; i++) { if ( i != number) { if (Sudokugenerator::sudokuArray[x+1][y][i] == i) { secondNumberExists = true; } } } /*Sudokugenerator::showArray(1); Sudokugenerator::showArray(2); Sudokugenerator::showArray(3); Sudokugenerator::showArray(4); Sudokugenerator::showArray(5); Sudokugenerator::showArray(6); Sudokugenerator::showArray(7); Sudokugenerator::showArray(8); Sudokugenerator::showArray(9);*/ if (!secondNumberExists) { return false; } } // add tests for empty blocks if the number gets removed. That would left me with a dead end // it's ok to take numbers out return true; } void Sudokugenerator::removeNumberFromArray(int x, int y, int number) { Sudokugenerator::arrayChanged = true; Sudokugenerator::sudokuArray[x][y][number] = (number * -1); Sudokugenerator::sudokuArray[x][y][0] = number; for (int i = 0; i < 9; i++) { // remove column if (Sudokugenerator::sudokuArray[x][i][number] == number) { Sudokugenerator::sudokuArray[x][i][number] = 0; } // remove row if (Sudokugenerator::sudokuArray[i][y][number] == number) { Sudokugenerator::sudokuArray[i][y][number] = 0; } // remove on all other floors. if (Sudokugenerator::sudokuArray[x][y][i + 1] == i + 1) { Sudokugenerator::sudokuArray[x][y][i + 1] = 0; } } if (x < 3) { x = 0; } else if (x < 6) { x = 3; } else { x = 6; } if (y < 3) { y = 0; } else if (y < 6) { y = 3; } else { y = 6; } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (Sudokugenerator::sudokuArray[x + j][y + i][number] == number) { Sudokugenerator::sudokuArray[x + j][y + i][number] = 0; } } } } void Sudokugenerator::initGenerator(int seed) { printf("\nSeed: %d\n\n", seed); Sudokugenerator::numberGenerator = Randomengine(seed); } /** * @brief Sudokugenerator::cellHasOnlyOneValue checks a given cell. If there are multiple values still possible to fill in, it returns -1. * @param x * @param y * @param number we want to check * @return Returns the only possible Number, if there are multiple Numbers possible in the given cell returns -1. */ int Sudokugenerator::cellHasOnlyOneValue(int x, int y) { int onlyNumber = -1; for (int i = 10; i > 0; i--) { if (Sudokugenerator::sudokuArray[x][y][i] == i) { // first match? asign the value. Multiple match will stop and return -1 if (onlyNumber == -1) { onlyNumber = i; } else { // more then 1 number possible for this cell. Return -1 return -1; } } /* // skip the one number we want to fill in if (i != number) { // if a floor has still the prefilled number in, we know that besides our wanted floor there is another floor that could possibly fill this cell. if (Sudokugenerator::sudokuArray[x][y][number] == number) { return false; } }*/ } return onlyNumber; } /** * @brief Sudokugenerator::blockHasOnlyOneValue * @param x * @param y * @param number * @return tuple <number, x, y> number contains -1 if there are still multiple values available. Else returns the Number, X, Y coordinate. */ std::tuple<int, int, int> Sudokugenerator::blockHasOnlyOneValue(int x, int y) { auto lastValue = std::make_tuple (-1, 0, 0); if (x < 3) { x = 0; } else if (x < 6) { x = 3; } else { x = 6; } if (y < 3) { y = 0; } else if (y < 6) { y = 3; } else { y = 6; } for (int x2 = 0; x2 < 3; x2++) { for (int y2 = 0; y2 < 3; y2++) { for (int i = 10; i > 0; i--) { if (Sudokugenerator::sudokuArray[x + x2][y + y2][i] == i) { // was there already a value asigned other then the current i or is it the first value found and maybe unique in this block if (std::get<0>(lastValue) == -1) { std::get<0>(lastValue) = i; std::get<1>(lastValue) = x + x2; std::get<2>(lastValue) = y + y2; std::cout << "\nNumber:" << std::get<0>(lastValue) << "\n"; } else { // more then 1 number possible, returning -1 std::get<0>(lastValue) = -1; return lastValue; } } } } } return lastValue; } bool Sudokugenerator::loadFromFile(std::string sudokuString) { int x = -1; int y = -1; for (int i = 0; i < sudokuString.length(); i++) { x = i % 9; if (i % 9 == 0) { y++; } /*std::cout << i << ": " << sudokuString[i] << "\n"; printf("\n%d\n", (sudokuString[i] - '0'));*/ /*if ((sudokuString[i] - '0') > 0) { printf("x:%d y:%d\n", x, y); }*/ if (sudokuString[i] - '0' > 0) { if (Sudokugenerator::numberCanBePicked(x, y, (sudokuString[i] - '0'))) { Sudokugenerator::removeNumberFromArray(x, y, (sudokuString[i] - '0')); /*if (x == 0 && y == 4) { printf("number xy 7 oder 9 _%d_", sudokuString[i] - '0'); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(7); }*/ } else { return false; } } } return true; } /** * @brief Sudokugenerator::fillSingleCells checks the Sudoku for Cells with a single applicable Number * @return true if a cell has been filled, false if no cell has a single value left */ bool Sudokugenerator::fillSingleCells() { bool arrayModified = false; for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { int number = Sudokugenerator::cellHasOnlyOneValue(x, y); //printf("_%d/x%d/y%d_", number,x,y); if (number > 0) { Sudokugenerator::removeNumberFromArray(x, y, number); arrayModified = true; Sudokugenerator::arrayChanged = true; } } } if (arrayModified) { return true; } else { return false; } } void Sudokugenerator::solveSudoku() { bool cellRemoved = true; while (cellRemoved) { cellRemoved = false; Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(); cellRemoved = Sudokugenerator::fillSingleCells(); } // no cell can be easily filled in now but there can be free cells. std::string placeholder = Sudokugenerator::sudokuToString(); //std::cout << "tempSudoku: " << placeholder << std::endl; Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(9); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(8); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(7); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(6); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(5); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(4); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(3); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(2); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(1); bool valueGuessed = Sudokugenerator::guessNextValue(); Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(0); if (valueGuessed) { std::cout << "value guessed"; bool cellRemoved = true; while (cellRemoved) { cellRemoved = false; Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(); cellRemoved = Sudokugenerator::fillSingleCells(); } } else { std::cout << "value NOT guessed"; } Sudokugenerator::arrayChanged = true; Sudokugenerator::showArray(); // TODO check dead ends and load other branches in printf("SOLVED!\n"); } int Sudokugenerator::blockWithMinimumRemainingValues() { // the 9 blocks of a Sudoku int blocks[9]; // temporary array for holding the numbers int tempValues[9]; int blockWithMinimum = -1; for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { int x2 = 0; int y2 = 0; if (x < 3) { x2 = 0; } else if (x < 6) { x2 = 3; } else { x2 = 6; } if (y < 3) { y2 = 0; } else if (y < 6) { y2 = 3; } else { y2 = 6; } // THIS IS A MESS, DON'T KILL ME, I'm sorry for copy pasta this, struct with inner method was a struggle if (x2 == 0 && y2 == 0) { int blockNumber = 0; blocks[blockNumber] = 0; for (int i = 0; i < 9; i++) { tempValues[i] = 0; } // loop through the block and check every cell for (int y3 = 0; y3 < 3; y3++) { for (int x3 = 0; x3 < 3; x3++) { // check if there is not already a number assigned to this cell if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][0] == 0) { // iterate all numbers to check which number is possible for (int i = 9; i > 0; i--) { //int numberInArr = Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i]; //printf("%d and i = %d | x%d y%d\n", numberInArr, i, x3 + x2, y3 + y2); // check if the cell is still untouched if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i] == i) { //printf("number %d is possible in block %d at Pos x%d, y%d\n", i, blockNumber, x3 + x2, y3 + y2); // check if number is already found at another cell of this block; if (tempValues[i] != i) { tempValues[i] = i; blocks[blockNumber] ++; } } } } } } } else if (x2 == 3 && y2 == 0) { int blockNumber = 1; blocks[blockNumber] = 0; for (int i = 0; i < 9; i++) { tempValues[i] = 0; } // loop through the block and check every cell for (int y3 = 0; y3 < 3; y3++) { for (int x3 = 0; x3 < 3; x3++) { // check if there is not already a number assigned to this cell if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][0] == 0) { // iterate all numbers to check which number is possible for (int i = 9; i > 0; i--) { //int numberInArr = Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i]; //printf("%d and i = %d | x%d y%d\n", numberInArr, i, x3 + x2, y3 + y2); // check if the cell is still untouched if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i] == i) { //printf("number %d is possible in block %d at Pos x%d, y%d\n", i, blockNumber, x3 + x2, y3 + y2); // check if number is already found at another cell of this block; if (tempValues[i] != i) { tempValues[i] = i; blocks[blockNumber] ++; } } } } } } } else if (x2 == 6 && y2 == 0) { int blockNumber = 2; blocks[blockNumber] = 0; for (int i = 0; i < 9; i++) { tempValues[i] = 0; } // loop through the block and check every cell for (int y3 = 0; y3 < 3; y3++) { for (int x3 = 0; x3 < 3; x3++) { // check if there is not already a number assigned to this cell if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][0] == 0) { // iterate all numbers to check which number is possible for (int i = 9; i > 0; i--) { // check if the cell is still untouched if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i] == i) { //printf("number %d is possible in block %d at Pos x%d, y%d\n", i, blockNumber, x3 + x2, y3 + y2); // check if number is already found at another cell of this block; if (tempValues[i] != i) { tempValues[i] = i; blocks[blockNumber] ++; } } } } } } } else if (x2 == 0 && y2 == 3) { int blockNumber = 3; blocks[blockNumber] = 0; for (int i = 0; i < 9; i++) { tempValues[i] = 0; } // loop through the block and check every cell for (int y3 = 0; y3 < 3; y3++) { for (int x3 = 0; x3 < 3; x3++) { // check if there is not already a number assigned to this cell if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][0] == 0) { // iterate all numbers to check which number is possible for (int i = 9; i > 0; i--) { // check if the cell is still untouched if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i] == i) { //printf("number %d is possible in block %d at Pos x%d, y%d\n", i, blockNumber, x3 + x2, y3 + y2); // check if number is already found at another cell of this block; if (tempValues[i] != i) { tempValues[i] = i; blocks[blockNumber] ++; } } } } } } } else if (x2 == 3 && y2 == 3) { int blockNumber = 4; blocks[blockNumber] = 0; for (int i = 0; i < 9; i++) { tempValues[i] = 0; } // loop through the block and check every cell for (int y3 = 0; y3 < 3; y3++) { for (int x3 = 0; x3 < 3; x3++) { // check if there is not already a number assigned to this cell if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][0] == 0) { // iterate all numbers to check which number is possible for (int i = 9; i > 0; i--) { // check if the cell is still untouched if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i] == i) { //printf("number %d is possible in block %d at Pos x%d, y%d\n", i, blockNumber, x3 + x2, y3 + y2); // check if number is already found at another cell of this block; if (tempValues[i] != i) { tempValues[i] = i; blocks[blockNumber] ++; } } } } } } } else if (x2 == 6 && y2 == 3) { int blockNumber = 5; blocks[blockNumber] = 0; for (int i = 0; i < 9; i++) { tempValues[i] = 0; } // loop through the block and check every cell for (int y3 = 0; y3 < 3; y3++) { for (int x3 = 0; x3 < 3; x3++) { // check if there is not already a number assigned to this cell if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][0] == 0) { // iterate all numbers to check which number is possible for (int i = 9; i > 0; i--) { // check if the cell is still untouched if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i] == i) { //printf("number %d is possible in block %d at Pos x%d, y%d\n", i, blockNumber, x3 + x2, y3 + y2); // check if number is already found at another cell of this block; if (tempValues[i] != i) { tempValues[i] = i; blocks[blockNumber] ++; } } } } } } } else if (x2 == 0 && y2 == 6) { int blockNumber = 6; blocks[blockNumber] = 0; for (int i = 0; i < 9; i++) { tempValues[i] = 0; } // loop through the block and check every cell for (int y3 = 0; y3 < 3; y3++) { for (int x3 = 0; x3 < 3; x3++) { // check if there is not already a number assigned to this cell if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][0] == 0) { // iterate all numbers to check which number is possible for (int i = 9; i > 0; i--) { // check if the cell is still untouched if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i] == i) { //printf("number %d is possible in block %d at Pos x%d, y%d\n", i, blockNumber, x3 + x2, y3 + y2); // check if number is already found at another cell of this block; if (tempValues[i] != i) { tempValues[i] = i; blocks[blockNumber] ++; } } } } } } } else if (x2 == 3 && y2 == 6) { int blockNumber = 7; blocks[blockNumber] = 0; for (int i = 0; i < 9; i++) { tempValues[i] = 0; } // loop through the block and check every cell for (int y3 = 0; y3 < 3; y3++) { for (int x3 = 0; x3 < 3; x3++) { // check if there is not already a number assigned to this cell if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][0] == 0) { // iterate all numbers to check which number is possible for (int i = 9; i > 0; i--) { // check if the cell is still untouched if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i] == i) { //printf("number %d is possible in block %d at Pos x%d, y%d\n", i, blockNumber, x3 + x2, y3 + y2); // check if number is already found at another cell of this block; if (tempValues[i] != i) { tempValues[i] = i; blocks[blockNumber] ++; } } } } } } } else if (x2 == 6 && y2 == 6) { int blockNumber = 8; blocks[blockNumber] = 0; for (int i = 0; i < 9; i++) { tempValues[i] = 0; } // loop through the block and check every cell for (int y3 = 0; y3 < 3; y3++) { for (int x3 = 0; x3 < 3; x3++) { // check if there is not already a number assigned to this cell if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][0] == 0) { // iterate all numbers to check which number is possible for (int i = 9; i > 0; i--) { // check if the cell is still untouched if (Sudokugenerator::sudokuArray[x3 + x2][y3 + y2][i] == i) { //printf("number %d is possible in block %d at Pos x%d, y%d\n", i, blockNumber, x3 + x2, y3 + y2); // check if number is already found at another cell of this block; if (tempValues[i] != i) { tempValues[i] = i; blocks[blockNumber] ++; } } } } } } } } } int tempAmount = 10; for (int i = 0; i < 9; i++) { if (blocks[i] < tempAmount) { tempAmount = blocks[i]; blockWithMinimum = i; } } return blockWithMinimum; } std::tuple<int, int, int> Sudokugenerator::cellInBlockWithLowestPossibilities(int blockNumber) { int x = 0; int y = 0; int tempLowest = -1; auto coordinates = std::make_tuple (-1, -1, -1); if (blockNumber == 2 || blockNumber == 5 || blockNumber == 8) { x = 3; } else if (blockNumber == 3 || blockNumber == 6 || blockNumber == 9) { x = 6; } if (blockNumber > 3 && blockNumber < 7) { y = 3; } else if (blockNumber > 6) { y = 6; } for (int y2 = 0; y2 < 3; y2++) { for (int x2 = 0; x2 < 3; x2++) { if (Sudokugenerator::sudokuArray[x + x2][y + y2][0] == 0) { int numbers = Sudokugenerator::amountOfPossibleValuesForCell(x + x2, y + y2); if (tempLowest < numbers) { tempLowest = numbers; std::get<0>(coordinates) = x + x2; std::get<1>(coordinates) = y + y2; std::get<2>(coordinates) = Sudokugenerator::getFirstFreeNumber(x + x2, y + y2); } } } } return coordinates; } std::string Sudokugenerator::sudokuToString() { std::string sudokuAsString = ""; for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { sudokuAsString += std::to_string(Sudokugenerator::sudokuArray[x][y][0]); } } return sudokuAsString; } bool Sudokugenerator::guessNextValue() { int nextBlockCheck = Sudokugenerator::blockWithMinimumRemainingValues(); printf("Block Number %d has the lowest possibilities\n", nextBlockCheck); auto nextCell = Sudokugenerator::cellInBlockWithLowestPossibilities(nextBlockCheck); printf("Cell x%d y%d has the lowest possibilities\n", std::get<0>(nextCell), std::get<1>(nextCell)); if (std::get<0>(nextCell) > -1 && std::get<1>(nextCell) > -1) { if (Sudokugenerator::numberCanBePicked(std::get<0>(nextCell), std::get<1>(nextCell), std::get<2>(nextCell))) { std::cout << "Number " << std::get<2>(nextCell) << " at Pos x" << std::get<0>(nextCell) << ", y" << std::get<1>(nextCell) << " guessed" << std::endl; Sudokugenerator::removeNumberFromArray(std::get<0>(nextCell), std::get<1>(nextCell), std::get<2>(nextCell)); return true; } else { std::cout << "Number can not be picked" << std::endl; return false; } } else { std::cout << "woops" << std::endl; return false; } } int Sudokugenerator::amountOfPossibleValuesForCell(int x, int y) { int possibilities = 0; for (int i = 10; i > 0; i--) { if (Sudokugenerator::sudokuArray[x][y][i] == i) { possibilities++; } } return possibilities; } int Sudokugenerator::getFirstFreeNumber(int x, int y) { for (int i = 10; i > 0; i--) { if (Sudokugenerator::sudokuArray[x][y][i] == i) { return i; } } std::cout << "Cell has no free Numbers"; return -1; } //todo bool Sudokugenerator::pathIsDeadEnd() { bool isDeadEnd = true; if (!Sudokugenerator::sudokuHasEmptySpots()) { } return isDeadEnd; } //todo bool Sudokugenerator::sudokuHasEmptySpots() { for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { if (Sudokugenerator::sudokuArray[x][y][0] == 0) { return true; } } } return false; }
true
70fdd97d5dd8b646157ede55d18e894d03a3ec9c
C++
centuryglass/KeyChord
/Source/MainWindow.h
UTF-8
1,368
2.703125
3
[]
no_license
#pragma once /** * @file MainWindow.h * * @brief Creates the main application window, and makes sure the application * is closed if the window is blocked. */ #include "JuceHeader.h" /** * @brief The sole application window object and the root component in the * component display tree. */ class MainWindow : public juce::DocumentWindow { public: /** * @brief Creates and shows the main application window. * * @param windowName Sets the text of the window title bar. */ MainWindow(juce::String windowName); virtual ~MainWindow() { } private: /** * @brief Closes the application normally when the window closes. */ void closeButtonPressed() override; /** * @brief Resizes page content to match the window size. */ virtual void resized() override; /** * @brief Starts the exit timer when the window loses focus, and stops * if if the window gains focus again. */ void activeWindowStatusChanged() override; /** * @brief Shuts down the application if the window loses focus and doesn't * regain it. */ class ExitTimer : public juce::Timer { private: virtual void timerCallback() override; }; ExitTimer exitTimer; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow) };
true
7714b71b0dc111ad4cb53c533b8a1ebaf7272cd1
C++
finallyly/ThaiSyllableHMM
/HMM.h
UTF-8
1,319
2.546875
3
[]
no_license
/*=============================================================== * Copyright (C) 2017 All rights reserved. * * FileName:HMM.h * creator:yuliu1@microsoft.com * Time:12/03/2017 * Description: * Notice: * Updates: * ================================================================*/ #ifndef _HMM_H #define _HMM_H #include "HMMProbability.h" // please add your code here! struct Node { int labelId; double alpha; double beta; double cost; int leftIndex; int rightIndex; Node():labelId(-1), alpha(0.0),beta(0.0),cost(0.0),leftIndex(-1),rightIndex(-1) { }; }; class HMM { public: HMM(std::vector<std::string> sentVec,HMMProbability* hmmModel); void Forward(HMMProbability* hmmModel); void Backward(HMMProbability* hmmModel); std::pair<double, int> Viterbi(HMMProbability* hmmModel); ~HMM( ); void FillGammas(HMMProbability* hmmModel); void FillEpsilons(HMMProbability* hmmModel); void BaumWelch(HMMProbability* hmmModel); void Train(HMMProbability* hmmModel); std::vector<std::string> GetMaxProbSequence(int index,HMMProbability* hmmModel); std::vector<std::string> Predict(HMMProbability *hmmModel); private: Node **nodemap; std::vector<int> symbolIds; int sentLen; std::vector<std::vector<double> > gammas; std::vector<double**> epsilons; }; #endif
true
f686a541944131e686ffa738bcc33e91ee7238fc
C++
konnase/algorithm
/剑指offer/剑指offer_15_反转链表.cpp
UTF-8
1,179
3.140625
3
[ "Apache-2.0" ]
permissive
// // Created by 李青坪 on 2019/2/26. // #include <cstdio> #include <algorithm> #include <vector> #include <iostream> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; class Solution { public: ListNode* ReverseList(ListNode* pHead) { if (pHead == NULL) return NULL; if (pHead->next == NULL) return pHead; ListNode* pre = pHead; ListNode* index; ListNode* next = pHead->next; pHead->next = NULL; while (next != NULL){ index = next; next = next->next; index->next = pre; pre = index; } return pre; } }; int n; int main() { Solution s; ListNode *r = new ListNode(1); int a[] = {0, 2, 0, 1, 3, 4, 7, 6, 0, 5, 8, 9, 0, 3, 1, 2, 4}; // int a[] = {}; ListNode *value = r; for (int i : a) { ListNode *temp = new ListNode(i); value->next = temp; value = temp; } ListNode *result = s.ReverseList(r); while (result != NULL) { cout << result->val << " "; result = result->next; } }
true
3c59f1c43d89d088a1ae4ad0ab0ffe72f5c656fc
C++
sponeil/VKSandbox
/Code/VKContext/VKMath.h
UTF-8
5,530
3.140625
3
[ "Unlicense", "LicenseRef-scancode-public-domain", "Libpng" ]
permissive
// VKMath.h // This code is part of the VKContext library, an object-oriented class // library designed to make Vulkan API easier to use with object-oriented // languages. It was designed and written by Sean O'Neil, who disclaims // any copyright to release it in the public domain. // #ifndef __VKMath_h__ #define __VKMath_h__ #define _USE_MATH_DEFINES #include <math.h> namespace VK { const float LOGHALF = -0.693147f; // log(0.5) const float LOGHALFI = -1.442695f; // Inverse of log(0.5) const float DELTA = 1e-6f; // Small number for comparing floating point numbers const double PI_DOUBLE = 3.141592653589793; const double PI_FLOAT = (float)PI_DOUBLE; /// A namespace for encapsulating common math routines. /// Aside from allowing me to define new "standard" math routines, like cubic /// and quintic, it also allows me to override existing math routines like sin /// and cos. For now the single-precision versions of the trig functions are /// used because they're an order of magnitude faster than the double- /// precision versions. namespace Math { template <class T> inline void Swap(T &a, T &b) { T t = a; a = b; b = t; } template <class T> inline T Abs(T a) { return (a < 0 ? -a : a); } template <class T> inline T Min(T a, T b) { return (a < b ? a : b); } template <class T> inline T Max(T a, T b) { return (a > b ? a : b); } template <class T> inline T Avg(T a, T b) { return (a + b) / (T)2; } template <class T> inline T Clamp(T x, T min, T max){ return (x < min ? min : (x > max ? max : x)); } template <class T> inline T Lerp(T a, T b, float t){ return (a + (b - a) * t); } template <class T> inline T Cubic(T a) { return a*a*((T)3-(T)2*a); } template <class T> inline T Quintic(T a) { return a*a*a*(a*(a*(T)6-(T)15)+(T)10); } template <class T> inline T Sign(T a) { return a < 0 ? (T)-1 : (T)1; } template <class T> inline T Square(T a) { return a * a; } template <class T> inline T SquareWithSign(T a) { return a < 0 ? -(a * a) : (a * a); } template <class T> inline T Step(T a, T x) { return (T)(x >= a); } template <class T> inline T Boxstep(T a, T b, T x) { return Clamp((x-a)/(b-a), 0, 1); } template <class T> inline T Pulse(T a, T b, T x) { return (T)((x >= a) - (x >= b)); } template <class T> inline bool IsPo2(T n) { for(int bits = 0; bits == 0 && n > 0; n >>= 1) bits += n & 1; return n == 0; } // Implements linear interpolation between two points // As t goes from 0 to 1, the return value goes from p0 to p1 following a straight line // Transitions are usually sharp and very noticeable template <class T> inline float LinearInterpolation(const T &p0, const T &p1, float t) { return (p0 + (p1 - p0) * t); } // Implements cubic interpolation between two points // As t goes from 0 to 1, the return value goes from p0 to p1 following a fixed curve // Some transitions look better than linear, but some look worse template <class T> inline float CubicInterpolation(const T &p0, const T &p1, float t) { return (p0 + (p1 - p0) * Cubic(t)); } // Implements Camull-Rom spline interpolation between 2 points (requires the 2 surrounding points). // As t goes from 0 to 1, the return value goes from p1 to p2 following a dynamic curve based on the 2 surrounding points // It is very smooth with no noticeable transitions template <class T> inline float CatmullRom(const T &p0, const T &p1, const T &p2, const T &p3, float t) { float t2 = t*t; float t3 = t2*t; const float K = 0.5f; return (float)(p1 + (-K*p0 + K*p2)*t + (2*K*p0 + (K-3)*p1 + (3-2*K)*p2 - K*p3)*t2 + (-K*p0 + (2-K)*p1 + (K-2)*p2 + K*p3)*t3); //return 0.5f * ((2 * p1) + (-p0 + p2)*t + (2*p0 - 5*p1 + 4*p2 - p3)*t2 + (-p0 + 3*p1 - 3*p2 + p3)*t3); } inline float ToRadians(float fDegrees) { return fDegrees * 0.01745329f; } inline float ToDegrees(float fRadians) { return fRadians * 57.295779f; } inline float Sin(float a) { return sinf(a); } inline float Cos(float a) { return cosf(a); } inline float Tan(float a) { return tanf(a); } inline float Asin(float a) { return asinf(a); } inline float Acos(float a) { return acosf(a); } inline float Atan(float a) { return atanf(a); } inline float Atan2(float y, float x) { return atan2f(y, x); } inline float Sqrt(float a) { return sqrtf(a); } inline int Floor(float a) { return ((int)a - (a < 0 && a != (int)a)); } inline int Ceiling(float a) { return ((int)a + (a > 0 && a != (int)a)); } inline float SqrtWithSign(float a) { return a < 0 ? -sqrtf(-a) : sqrtf(a); } inline float Gamma(float a, float g) { return powf(a, 1/g); } inline float Bias(float a, float b) { return powf(a, logf(b) * LOGHALFI); } inline float Expose(float l, float k) { return (1 - expf(-l * k)); } inline float Gain(float a, float b) { if(a <= DELTA) return 0; if(a >= 1-DELTA) return 1; register float p = (logf(1 - b) * LOGHALFI); if(a < 0.5) return powf(2 * a, p) * 0.5f; else return 1 - powf(2 * (1 - a), p) * 0.5f; } inline float Smoothstep(float a, float b, float x) { if(x <= a) return 0; if(x >= b) return 1; return Cubic((x - a) / (b - a)); } inline float Mod(float a, float b) { a -= ((int)(a / b)) * b; if(a < 0) a += b; return a; } inline void Normalize(float *f, int n) { int i; float fMagnitude = 0; for(i=0; i<n; ++i) fMagnitude += f[i]*f[i]; fMagnitude = 1 / sqrtf(fMagnitude); for(i=0; i<n; ++i) f[i] *= fMagnitude; } }; } // namespace VK #endif // __VKMath_h__
true
eedb35dac587f82b31e54c8f9ff9095f7cd2cf6c
C++
pklim101/codelib
/algorithm/lc/moveZeros.cpp
UTF-8
1,063
3.5
4
[]
no_license
/************************************************************************* > File Name: moveZeros.cpp > Author: tony > Mail: tony@z.com > Created Time: 2020年04月17日 星期五 11时39分21秒 ************************************************************************/ #include<iostream> #include<vector> using namespace std; //双指针 //遍历,将非0的往前移,覆盖到j的位置,每覆盖一次,j就+1; //最后将j后面的位置置0. void moveZeroes(vector<int>& nums) { int j = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) { nums[j] = nums[i]; j++; } } for (int i = j; i < nums.size(); i++) { nums[i] = 0; } } void moveZeroes2(vector<int>& nums) { int zeroIndex = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) { if (i != zeroIndex) swap(nums[i], nums[zeroIndex]); zeroIndex++; } } } int main(){ int a[] = {0,1,0,3,12}; vector<int> vec(a, a+5); moveZeroes(vec); for (int i : vec){ cout << i << endl; } return 0; }
true
6d7f846219c6d6bf78bdda415cd29899e8608aac
C++
varkey98/Leetcode-Solutions
/concatenatedwords.cpp
UTF-8
3,878
3.046875
3
[]
no_license
int dfs_visit(string s,vector<string>& words)// wrong answer { if(!s.length()) return 0; int flag=true; int q=-1; for(auto x:words) { if(!x.length()||x.length()>s.length()) continue; else if(s.substr(0,x.length()).compare(x)==0) { flag=false; q=max(q,dfs_visit(s.substr(x.length()),words)); if(q>-1) break; } } if(q>-1||!flag) return q+1; else return -1; } vector<string> dfs(vector<string>& words) { vector<string> ret; for(string x:words) if(dfs_visit(x,words)>1) ret.push_back(x); return ret; } vector<string> findAllConcatenatedWordsInADict(vector<string>& words) { return dfs(words); } // java solution of trie class trie { public trie[] children; public boolean eof; public trie () { children =new trie[26]; for(int i=0;i<26;++i) children[i]=null; eof=false; } public void insert(trie root,String key) { trie temp=root; for(int i=0;i<key.length();++i) { char x=key.charAt(i); if(temp.children[x-'a']==null) temp.children[x-'a']=new trie(); temp=temp.children[x-'a']; } temp.eof=true; } public trie search(trie root,String key) { trie temp=root; for(int i=0;i<key.length();++i) { char x=key.charAt(i); if(temp.children[x-'a']==null) return null; else temp=temp.children[x-'a']; } return temp; } } class Solution { HashMap<String,Integer> memo = new HashMap<String,Integer>(); int dfs_visit(String s,String[] words,trie root) { if(s.length()==0) return 0; if(memo.containsKey(s)==true) return memo.get(s); int q=-1; trie temp=root; for(int i=0;i<s.length();++i) { String key=new String(); key+=s.charAt(i); if(temp!=null) temp=root.search(temp,key); else break; if(temp!=null&&temp.eof) q=Math.max(q,dfs_visit(s.substring(i+1),words,root)); } if(q>-1) q+=1; memo.put(s,q); return q; } List<String> dfs(String[] words,trie root) { List<String> ret=new ArrayList<String>(); for(String s: words) if(dfs_visit(s,words,root)>1) ret.add(s); return ret; } public List<String> findAllConcatenatedWordsInADict(String[] words) { trie root=new trie(); for(String x:words) root.insert(root,x); return dfs(words,root); } } /////////////// struct trie // c++ solution gives tle { struct trie *children[26]; bool eof; }; trie* createNode() { trie* ret=(trie*)malloc(sizeof(trie)); for(int i=0;i<26;++i) ret->children[i]=NULL; ret->eof=false; return ret; } void insert(trie* root,string key) { trie* temp=root; for(char x:key) { if(temp->children[x-'a']==NULL) temp->children[x-'a']=createNode(); temp=temp->children[x-'a']; } temp->eof=true; } trie* search(trie* root,string key) { trie* temp=root; for(char x:key) { if(temp->children[x-'a']==NULL) return NULL; else temp=temp->children[x-'a']; } return temp; } map<string,int> memo; int dfs_visit(string s,vector<string>& words,trie* root) { if(!s.length()) return 0; if(memo.find(s)!=memo.end()) return memo[s]; int q=-1; trie* temp=root; for(int i=0;i<s.length();++i) { string key; key.push_back(s[i]); if(temp) temp=search(temp,key); else break; if(temp!=NULL&&temp->eof) q=max(q,dfs_visit(s.substr(i+1),words,root)); } if(q>-1) return memo[s]=q+1; else return memo[s]=-1; } vector<string> dfs(vector<string>& words,trie* root) { vector<string> ret; for(string s: words) if(dfs_visit(s,words,root)>1) ret.push_back(s); return ret; } vector<string> findAllConcatenatedWordsInADict(vector<string>& words) { trie* root=createNode(); for(auto x:words) insert(root,x); return dfs(words,root); }
true
bc3a9413fa97087ac6e5aca4e563afcbc13af3dc
C++
johnk-/rencpp
/tests/block-test.cpp
UTF-8
1,221
2.765625
3
[ "BSL-1.0" ]
permissive
#include <iostream> #include "rencpp/ren.hpp" using namespace ren; #include "catch.hpp" TEST_CASE("block test", "[rebol] [block]") { SECTION("empty") { Block block {}; CHECK(block.length() == 0); Block explicitEmpties {Block {}, Block {}, Block {}}; Block implicitEmpties {{}, {}, {}}; CHECK(explicitEmpties.isEqualTo(implicitEmpties)); } SECTION("singleton") { // This is a tricky case Block singleton {"foo"}; Value singletonAsValue = singleton; static_cast<Block>(singletonAsValue); Block singletonInitializer {singleton}; } Block randomStuff {"blue", Block {true, 1020}, 3.04}; SECTION("nested") { // See discussion on: // // https://github.com/hostilefork/rencpp/issues/1 Block blk { {1, true}, {false, 2} }; CHECK(blk.isBlock()); CHECK(blk[1].isBlock()); CHECK(blk[2].isBlock()); Block blk1 = static_cast<Block>(blk[1]); Block blk2 = static_cast<Block>(blk[2]); CHECK(blk1[1].isInteger()); CHECK(blk1[2].isLogic()); CHECK(blk2[1].isLogic()); CHECK(blk2[2].isInteger()); } }
true
82b9e29403a89799885e6cd7a7857dc1999291e9
C++
kuqadk3/CTF-and-Learning
/codeforces/contest_round_579_div3/A/hack/test02.cpp
UTF-8
1,914
2.78125
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; int gcd(int x,int y) { return y?gcd(y,x%y):x; } int main() { ios::sync_with_stdio(false); int q; cin>>q; while(q--) { int n,a[1000]; cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; if(n==1)cout<<"YES"<<endl; else { int flag=0; if(a[1]==1) { if(a[2]==2) { for(int i=3;i<=n;i++) { if(a[i]<a[i-1]) { flag=1;break; } } if(flag)cout<<"NO"<<endl; else cout<<"YES"<<endl; } else if(a[2]==n) { for(int i=3;i<=n;i++) { if(a[i]>a[i-1]) { flag=1;break; } } if(flag)cout<<"NO"<<endl; else cout<<"YES"<<endl; } else cout<<"NO"<<endl; } else if(a[1]==n) { if(a[2]==1) { for(int i=3;i<=n;i++) { if(a[i]<a[i-1]) { flag=1;break; } } if(flag)cout<<"NO"<<endl; else cout<<"YES"<<endl; } else if(a[2]==n-1) { for(int i=3;i<=n;i++) { if(a[i]>a[i-1]) { flag=1;break; } } if(flag)cout<<"NO"<<endl; else cout<<"YES"<<endl; } else cout<<"NO"<<endl; } else { if(a[1]<a[2]) { for(int i=2;i<=n;i++) { if(a[1]+i-1==a[i]) { continue; } else if(a[1]+i-1>n&&a[1]+i-1-n==a[i]) { continue; } else { flag=1;break; } } if(flag)cout<<"NO"<<endl; else cout<<"YES"<<endl; } else { for(int i=2;i<=n;i++) { if(a[1]-i+1==a[i]) { continue; } else if(a[1]-i+1<=0&&a[1]-i+1+n==a[i]) { continue; } else { //cout<<"i="<<i<<" a1="<<a[1]<<" a="<<a[1]-i+1<<" ai="<<a[i]<<endl; flag=1;break; } } if(flag)cout<<"NO"<<endl; else cout<<"YES"<<endl; } } } } return 0; }
true
c2644e1f711be7e08d2e481a61ee069068a844ed
C++
linw/Workplace-in-Linux
/for_findingjob/something_useful/test_init_list.cpp
UTF-8
926
2.65625
3
[]
no_license
/* * ===================================================================================== * * Filename: test_init_list.cpp * Author: linwei * E-mail: kinglw8729@gmail.com * Created: 2012-09-12 23:01:37 * Last Edit: * Compiler: gcc * Description: * ===================================================================================== */ #include <iostream> using namespace std; class A{ public: A(){ cout<<"construct A"<<endl; } A(const A& a){ cout<<"copy construct A"<<endl; } }; class C{ public: C(){ cout<<"construct C"<<endl; } C(const C& c){ cout<<"copy construct C"<<endl; } }; class B{ public: B(const A& _a, const C& _c):c(_c),a(_a){ cout<<"construct B"<<endl; } B(){ } private: A a; C c; public: static A sa; }; int main(int argv, char* args[]) { A a; C c; B b; // b.sa; return 0; }
true
777b801e907341455f5e0cb0d7f5d35ac1c2e2cf
C++
rathoresrikant/HacktoberFestContribute
/Algorithms/Search/Ternary_search.cpp
UTF-8
1,140
3.484375
3
[ "MIT" ]
permissive
#include<iostream> #include<cstdio> #include<cmath> #include<algorithm> using namespace std; int main() { int i, n, val, low, high, mid1, mid2, a[50]; printf("Enter the size of an array : "); scanf("%d", &n); printf("Enter the elements : "); for(i=0; i<n; i++) { scanf("%d", &a[i]); } sort(a, a+n); printf("The sorted array is : "); for(i=0; i<n; i++) { printf("%d ", a[i]); } printf("\n"); printf("Enter the element which you want to search : "); scanf("%d", &val); low=0; high=n-1; while(low<=high) { mid1=((low+high)/2); mid2=(mid1*2); if(val==a[mid1]) { printf("Position is : %d.\n", mid1+1); break; } else if(a[mid1]>val) { high=mid1-1; } else if(val==a[mid2]) { printf("Position is : %d.\n", mid2+1); break; } else if(a[mid2]<val) { low=mid2+1; } else { low=mid1+1; high=mid2-1; } } return 0; }
true
8ba280cd07bb6c4c54e8741213033434a3dc1ba3
C++
cycasmi/proyectos-VS
/Tercer semestre Data structures/Recursive Hanoi/Recursive Hanoi/Hanoi.cpp
WINDOWS-1250
637
3.625
4
[]
no_license
// Name: Cynthia Berenice Castillo Milln. // Student no. A01374530 // Homework 1 Hanoi Towers #include <cstdio> using namespace std; #pragma warning (disable: 4996) void hanoi(int &counter, int n, int p1, int p2, int p3) { counter++; if (n > 1) { hanoi(counter, n - 1, p1, p3, p2); hanoi(counter, n - 1, p3, p2, p1); } } int main() { unsigned int number; int counter = 0; printf("Give me a number:"); while (scanf("%d", &number) != EOF) { printf("The number of moves for a hanoi tower of %d disc(s) is:", number); hanoi(counter, number, 1, 2, 3); printf(" %d", counter); counter = 0; printf("\n\nGive me a number:"); } return 0; }
true
a6b179730344eea10db453b56be3310e0c052eb3
C++
BobDeng1974/finemedia
/include/ffw/media/ddsloader.h
UTF-8
1,251
2.515625
3
[ "MIT" ]
permissive
/* This file is part of FineFramework project */ #ifndef FFW_MEDIA_DDS_LOADER #define FFW_MEDIA_DDS_LOADER #include "imageloader.h" #include <fstream> namespace ffw { /** * @ingroup media */ class FFW_API DdsLoader: public ImageReader { public: DdsLoader(const std::string& path); DdsLoader(const DdsLoader& other) = delete; DdsLoader(DdsLoader&& other); void swap(DdsLoader& other); DdsLoader& operator = (const DdsLoader& other) = delete; DdsLoader& operator = (DdsLoader&& other); virtual ~DdsLoader(); size_t readRow(void* dest) override; bool getMipMap(int level) override; bool getCubemap(int side); void close() override; inline bool isCubemap() const { return iscubemap; } inline int getCubemapOffset() const { return cubemapOffset; } private: void open(const std::string& path); ffw::SwapWrapper<std::fstream> input; size_t pixelsOffset; bool invertBits; bool swaprgb; bool iscubemap; int cubemapOffset; }; } inline void swap(ffw::DdsLoader& first, ffw::DdsLoader& second){ first.swap(second); } #endif
true
bc91eb06a5bdf494061d97978d05be4977a6e0fd
C++
BackupTheBerlios/netpanzer-svn
/branches/start/netpanzerutils/src/Lib/Math.cpp
UTF-8
4,058
2.765625
3
[]
no_license
/* Copyright (C) 1998 Pyrosoft Inc. (www.pyrosoftgames.com), Matthew Bogue This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <config.h> #include <assert.h> #include "Math.hpp" float Math::cosTable[360 + 1]; float Math::sinTable[360 + 1]; // rad2Deg //-------------------------------------------------------------------------- // Purpose: Converts from radians to degrees. //-------------------------------------------------------------------------- int Math::rad2Deg(float radian) { return int(radian * (180.0 / M_PI)); } // end Math::rad2Deg // deg2Rad //-------------------------------------------------------------------------- // Purpose: Converts from degrees to radians. //-------------------------------------------------------------------------- float Math::deg2Rad(int degree) { return degree * (M_PI / 180.0); } // end Math::deg2Rad // degAngle //-------------------------------------------------------------------------- int Math::degAngle(const iXY &a, const iXY &b) { return rad2Deg(radAngle(a, b)); } // end Math::degAngle // degAngle //-------------------------------------------------------------------------- int Math::degAngle(float x, float y) { return rad2Deg(radAngle(x, y)); } // end Math::degAngle // unitDirection //-------------------------------------------------------------------------- fXY Math::unitDirection(const iXY &a, const iXY &b) { float angle = radAngle(a, b); return unitDirection(angle); } // end Math::unitDirection // unitDirection //-------------------------------------------------------------------------- fXY Math::unitDirection(float angle) { return fXY(cos(angle), sin(angle)); } // end Math::unitDirection // radAngle //-------------------------------------------------------------------------- float Math::radAngle(const iXY &a, const iXY &b) { return atan2(b.y - a.y, b.x - a.x); } // end Math::radAngle // radAngle //-------------------------------------------------------------------------- float Math::radAngle(float x, float y) { return atan2(y, x); } // end Math::radAngle // unitDirectionEast //-------------------------------------------------------------------------- fXY Math::unitDirectionEast(const fXY &northDirection) { float angle = radAngle(northDirection.x, northDirection.y); angle += M_PI / 2.0; return unitDirection(angle); } // end Math::unitDirectionEast // unitDirectionWest //-------------------------------------------------------------------------- fXY Math::unitDirectionWest(const fXY &northDirection) { float angle = radAngle(northDirection.x, northDirection.y); angle -= M_PI / 2.0; return unitDirection(angle); } // end Math::unitDirectionWest // getCos //-------------------------------------------------------------------------- float Math::getCos(int angle) { assert(angle >= 0 && angle <= 360); return cosTable[angle]; } // end Math::getCos // getSin //-------------------------------------------------------------------------- float Math::getSin(int angle) { assert(angle >= 0 && angle <= 360); return sinTable[angle]; } // end Math::getSin // init //-------------------------------------------------------------------------- Math::Math() { for (int i = 0; i <= 360; i++) { float radians = deg2Rad(i); cosTable[i] = cos(radians); sinTable[i] = sin(radians); } } // end Math::init Math math;
true
1d43abbfe8284c1e4c297971bbe2d2433c58e601
C++
ejuarezg/NM4P
/Cpp/bess.cpp
UTF-8
1,067
3.171875
3
[]
no_license
#include "NumMeth.h" void bess( int m_max, double x, Matrix& jj ) { // Bessel function // Inputs // m_max Largest desired order // x = Value at which Bessel function J(x) is evaluated // Output // jj = Vector of J(x) for order m = 0, 1, ..., m_max //* Perform downward recursion from initial guess int maxmx = (m_max > x) ? m_max : ((int)x); // Max(m,x) // Recursion is downward from m_top (which is even) int m_top = 2*((int)( (maxmx+15)/2 + 1 )); Matrix j(m_top+1); j(m_top+1) = 0.0; j(m_top) = 1.0; double tinyNumber = 1e-16; int m; for( m=m_top-2; m>=0; m--) // Downward recursion j(m+1) = 2*(m+1)/(x+tinyNumber)*j(m+2) - j(m+3); //* Normalize using identity and return requested values double norm = j(1); // NOTE: Be careful, m=0,1,... but for( m=2; m<=m_top; m+=2 ) // vector goes j(1),j(2),... norm += 2*j(m+1); for( m=0; m<=m_max; m++ ) // Send back only the values for jj(m+1) = j(m+1)/norm; // m=0,...,m_max and discard values } // for m=m_max+1,...,m_top
true
8c1fdd434e5ded12af85930a50aa59726b722554
C++
aashutoshtaikar/cppProjects
/Concurrency/important points/2.1.dataraces_Mutex.cpp
UTF-8
1,194
3.5
4
[]
no_license
#include <iostream> #include <fstream> #include <thread> #include <chrono> #include <string> #include <mutex> //more realistic example to protect file write class LogFile{ std::mutex m_mutex; std::ofstream m_file; public: LogFile(){ m_file.open("3.log.txt"); } void shared_print(std::string msg, int id){ std::lock_guard<std::mutex> guard(m_mutex); m_file << msg <<':' << id << "\n"; } ~LogFile(){ m_file.close(); } /* never return m_file to the outside world */ // std::ofstream& getStream() {return m_file;} /* never pass m_file as an argument to user provided function */ // void process_file(void user_func(std::ofstream&)){ // user_func(m_file); // } }; void function1(LogFile& log){ for(int i = 0; i >- 10; i--){ std::this_thread::sleep_for(std::chrono::seconds(1)); log.shared_print(std::string("From t1: "), i); } } int main() { LogFile log; std::thread t1(function1, std::ref(log)); for(int i = 0; i < 10; i++){ std::this_thread::sleep_for(std::chrono::seconds(1)); log.shared_print(std::string("From main: "), i); } t1.join(); return 0; }
true
d12d068d40d3258a8cf6350561a4701f36155420
C++
testTemtProj/OLD_PROJECT
/sud/TrieLib/TrieBuilder_impl.cpp
UTF-8
10,298
2.953125
3
[]
no_license
#include <QDataStream> #include <QVector> #include <QMap> #include <QSet> #include "TrieBuilder.h" class TrieBuilderImpl { public: TrieBuilderImpl() : m_root(new BuilderNode(0,0)), m_nodeCount(0) { } BuilderNode *addNode(char_t value, BuilderNode *parent) { if (!parent) return 0; // Если значение уже содержится, возвращаем указатель на него foreach (BuilderNode *n, parent->m_children) { if (n->value() == value) return n; } // Создаём новый узел BuilderNode *node = new BuilderNode(value, parent); parent->m_children.append(node); m_nodeCount++; return node; } BuilderNode *root() const { return m_root; } int nodeCount() const { return m_nodeCount; } /** Сохраняет словарь в устройство \a out. Формат словаря: 4 байта 'YS!\0' Сигнатура 4 байта quint32 Смещение начала данных x байт Мета-данные ................... Данные */ void save(QIODevice &out) { if (!out.isOpen() || !out.isWritable()) out.open(QIODevice::ReadWrite | QIODevice::Truncate); QDataStream data(&out); saveHeader(data); qint64 offset = data.device()->pos(); saveNode(data, root(), offset, offset, 0); } /** Сохраняет заголовок словаря */ void saveHeader(QDataStream &data) { // Сигнатура data << (quint8) 'Y' << (quint8) 'S' << (quint8) '!' << (quint8) '\0'; // Место для смещения начала данных data << (quint32) 0; saveMetaData(data); quint32 offset = data.device()->pos(); data.device()->seek(4); data << (quint32) offset; data.device()->seek(offset); } /** Сохраняет метаданные словаря. Записи мета-данных храняться друг за другом в таком формате: 4 байта длина ключа x байт строка ключа в Utf-8 4 байта длина данных, ассоциированных с ключём x байт мета-данные После последней записи идут четыре байта терминатора 0xFFFFFFFF. */ void saveMetaData(QDataStream &data) { foreach (QString key, m_metaData.keys()) { writeLongByteArray(data, key.toUtf8()); writeLongByteArray(data, m_metaData[key]); } data << (quint32) 0xffffffff; } /*! Сохраняет узел \a n со всеми дочерними узлами в поток \a data. Возвращает конечное смещение узла \a n. \param data Поток, в который производится сохранение \param n Узел, который будет сохранён со всеми потомками \param offset Смещение, по которому начнётся запись узла \a n. \param parentOffset Смещение родительского узла \param parentIndex Индекс узла \a n среди дочерних узлов \a parent */ quint64 saveNode(QDataStream &data, BuilderNode *n, quint64 offset, quint64 parentOffset, qint8 parentIndex) { data.device()->seek(offset); int count = n->children().count(); quint8 type; if (count == 0) type = BuilderNode::Terminator; else if (count == 1) type = BuilderNode::Chain; else type = BuilderNode::OneChar; bool hasData = !n->data().isEmpty(); quint8 typeWithFlags = type; if (hasData) typeWithFlags |= BuilderNode::HasData; parentOffset = offset - parentOffset; quint64 posOffsets; quint64 nextChildOffset; switch (type) { case BuilderNode::OneChar: // Узел, имеющий нескольких детей data << typeWithFlags; data << (quint32) parentOffset; // [parent] data << (quint8) parentIndex; data << (quint8) count; for (int i = 0; i < count; i++) data << (quint8) n->child(i)->value(); posOffsets = data.device()->pos(); for (int i = 0; i < count; i++) data << (quint32) 0; if (hasData) { writeByteArray(data, n->data()); } nextChildOffset = data.device()->pos(); for (int i = 0; i < count; i++) { data.device()->seek(posOffsets + i * sizeof(quint32)); data << (quint32) (nextChildOffset - offset); nextChildOffset = saveNode(data, n->child(i), nextChildOffset, offset, i); } return nextChildOffset; case BuilderNode::Chain: // Цепочка по одному символу { data << typeWithFlags; data << (quint32) parentOffset; // [parent] data << (quint8) parentIndex; QVector<char_t> chain; QMap<int, QByteArray> mapData; QByteArray ownData = n->data(); while (n->children().count() == 1) { n = n->child(0); chain.append(n->value()); if (!n->data().isEmpty()) { mapData[chain.size() - 1] = n->data(); } } data << (quint8) chain.size(); foreach(char_t v, chain) data << (quint8) v; if (hasData) // Собственные данные writeByteArray(data, ownData); QList<int> keys = mapData.keys(); // Кол-во данных data << (quint8) keys.length(); // Индексы символов с данными foreach (int key, keys) { data << (quint8) key; } if (!hasSameValues(mapData)) { foreach (int key, keys) { writeByteArray(data, mapData[key]); // data << (quint8) mapData[key].length(); // Кол-во данных // saveString(data, mapData[key]); // Данные узлов } } else { typeWithFlags |= BuilderNode::ChainSameData; QByteArray nodeData = mapData.values()[0]; writeByteArray(data, nodeData); nextChildOffset = data.device()->pos(); data.device()->seek(offset); data << typeWithFlags; data.device()->seek(nextChildOffset); } if (n->children().count() == 0) { nextChildOffset = data.device()->pos(); typeWithFlags |= BuilderNode::ChainTerminated; data.device()->seek(offset); data << typeWithFlags; return nextChildOffset; } return saveNode(data, n, data.device()->pos(), offset, chain.size() - 1); } case BuilderNode::Terminator: data << typeWithFlags; data << (quint32) parentOffset; // [parent] data << (quint8) parentIndex; if (hasData) writeByteArray(data, n->data()); return data.device()->pos(); default: data << type; data << (quint32) parentOffset; // [parent] data << (quint8) parentIndex; return data.device()->pos(); } } /*! Сохраняет \a array в поток \a data. Длина массива ограничена 255 байтами. */ void writeByteArray(QDataStream &data, const QByteArray &array) { int length = array.length(); Q_ASSERT( length < 255 ); data << (quint8) length; data.writeRawData(array.data(), length); } /*! Сохраняет \a array в поток \a data. Длина массива ограничена 4 Гб. Внимание: массивы, сохранённые этой функцией и writeByteArray никак не различаются, необходимо следить за корректным чтением. */ void writeLongByteArray(QDataStream &data, const QByteArray &array) { quint32 length = array.length(); data << (quint32) length; data.writeRawData(array.data(), length); } /*! Возвращает true, если карта содержит все одинаковые значения. */ bool hasSameValues(const QMap<int, QByteArray> &map) { if (map.count() < 2) return false; return QSet<QByteArray>::fromList(map.values()).count() == 1; } /*! Устанаваливает метаданные \a data по ключу \a key */ void setMetaData(const QString &key, const QByteArray &data) { m_metaData[key] = data; } /*! Устанаваливает метаданные \a data по ключу \a key. Строка сохраняется в UTF-8. */ void setMetaData(const QString &key, const QString &data) { m_metaData[key] = data.toUtf8(); } /*! Возвращает метаданные по ключу \a key. */ QByteArray metaData(const QString &key) { return m_metaData.value(key); } private: BuilderNode *m_root; int m_nodeCount; QMap<QString, QByteArray> m_metaData; };
true
1e781ff5f41276619db5e62ae2378ca42da432d5
C++
Jaiss123/Myserver-mini
/mini-server v1.8/TimerQueue.cpp
UTF-8
4,920
2.921875
3
[]
no_license
#include <sys/timerfd.h> #include <inttypes.h> #include <stdio.h> #include <strings.h> #include <unistd.h> #include "TimerQueue.h" #include "Channel.h" #include "EventLoop.h" #include "Timestamp.h" #include <iostream> TimerQueue::TimerQueue(EventLoop *pLoop) :_timerfd(createTimerfd()) ,_pLoop(pLoop) ,_timerfdChannel(new Channel(_pLoop, _timerfd)) // Memory Leak !!! ,_addTimerWrapper(new AddTimerWrapper(this)) // Memory Leak !!! ,_cancelTimerWrapper(new CancelTimerWrapper(this)) // Memory Leak !!! { _timerfdChannel->setCallback(this); _timerfdChannel->enableReading(); } TimerQueue::~TimerQueue() { ::close(_timerfd); } void TimerQueue::doAddTimer(void* param) { Timer* pTimer = static_cast<Timer*>(param); bool earliestChanged = insert(pTimer); if(earliestChanged) { resetTimerfd(_timerfd, pTimer->getStamp()); } } void TimerQueue::doCancelTimer(void* param) { Timer* pTimer = static_cast<Timer*>(param); Entry e(pTimer->getId(), pTimer); TimerList::iterator it; for(it = _timers.begin(); it != _timers.end(); ++it) { if(it->second == pTimer) { _timers.erase(it); break; } } } /////////////////////////////////////// /// Add a timer to the system /// @param pRun: callback interface /// @param when: time /// @param interval: /// 0 = happen only once, no repeat /// n = happen after the first time every n seconds /// @return the process unique Timer* of the timer void* TimerQueue::addTimer(IRun* pRun, Timestamp when, double interval) { Timer* pTimer = new Timer(when, pRun, interval); //Memory Leak !!! _pLoop->queueLoop(_addTimerWrapper, pTimer); return static_cast<void*>(pTimer); } void TimerQueue::cancelTimer(void* timerId) { _pLoop->queueLoop(_cancelTimerWrapper, (void*)timerId); } void TimerQueue::handleRead() { Timestamp now(Timestamp::now()); readTimerfd(_timerfd, now); //find the active timer vector<Entry> expired = getExpired(now); vector<Entry>::iterator it; for(it = expired.begin(); it != expired.end(); ++it) { it->second->run(); } reset(expired, now); } void TimerQueue::handleWrite() {} int TimerQueue::createTimerfd() { int timerfd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); if(timerfd < 0) { cout << "failed in timerfd_create" << endl; } return timerfd; } std::vector<TimerQueue::Entry> TimerQueue::getExpired(Timestamp now) { std::vector<Entry> expired; Entry sentry(now, reinterpret_cast<Timer*>(UINTPTR_MAX)); TimerList::iterator end = _timers.lower_bound(sentry); copy(_timers.begin(), end, back_inserter(expired)); _timers.erase(_timers.begin(), end); return expired; } void TimerQueue::readTimerfd(int timerfd, Timestamp now) { uint64_t howmany; ssize_t n = ::read(timerfd, &howmany, sizeof(howmany)); if (n != sizeof(howmany)) { cout << "Timer::readTimerfd() error " << endl; } } void TimerQueue::reset(const vector<Entry>& expired, Timestamp now) { vector<Entry>::const_iterator it; for(it = expired.begin(); it != expired.end(); ++it) { if(it->second->isRepeat()) { it->second->moveToNext(); insert(it->second); } } Timestamp nextExpire; if(!_timers.empty()) { nextExpire = _timers.begin()->second->getStamp(); } if(nextExpire.valid()) { resetTimerfd(_timerfd, nextExpire); } } void TimerQueue::resetTimerfd(int timerfd, Timestamp stamp) { struct itimerspec newValue; struct itimerspec oldValue; bzero(&newValue, sizeof(newValue)); bzero(&oldValue, sizeof(oldValue)); newValue.it_value = howMuchTimeFromNow(stamp); int ret = ::timerfd_settime(timerfd, 0, &newValue, &oldValue); if(ret) { cout << "timerfd_settime error" << endl; } } bool TimerQueue::insert(Timer* pTimer) { bool earliestChanged = false; Timestamp when = pTimer->getStamp(); TimerList::iterator it = _timers.begin(); if(it == _timers.end() || when < it->first) { earliestChanged = true; } pair<TimerList::iterator, bool> result = _timers.insert(Entry(when, pTimer)); if(!(result.second)) { cout << "_timers.insert() error " << endl; } return earliestChanged; } struct timespec TimerQueue::howMuchTimeFromNow(Timestamp when) { int64_t microseconds = when.microSecondsSinceEpoch() - Timestamp::now().microSecondsSinceEpoch(); if (microseconds < 100) { microseconds = 100; } struct timespec ts; ts.tv_sec = static_cast<time_t>( microseconds / Timestamp::kMicroSecondsPerSecond); ts.tv_nsec = static_cast<long>( (microseconds % Timestamp::kMicroSecondsPerSecond) * 1000); return ts; }
true
154e0ffbb81d82757aa1488c4939f83297ad6e2f
C++
svofski/vector06sdl
/src/fd1793.h
UTF-8
24,793
2.640625
3
[]
no_license
// fd1793.h for vector06sdl by Viacheslav Slavinsky, ported from vector06js // // Originally based upon: // fd1793.js from Videoton TV-Computer project by Bela Babik // https://github.com/teki/jstvc #pragma once #include <string> #include <vector> #include <iostream> #include "options.h" #include "util.h" #include "fsimage.h" struct DiskImage { virtual uint8_t get(int i) { return 0; } virtual void set(int /*index*/, uint8_t /*value*/) {} virtual size_t size() { return 0; } virtual void flush() {} virtual ~DiskImage() {} }; struct CardboardDiskImage : public DiskImage { }; class DetachedDiskImage : public DiskImage { std::vector<uint8_t> _data; public: DetachedDiskImage() = delete; DetachedDiskImage(const std::vector<uint8_t> & data) : _data(data) {} ~DetachedDiskImage() override { FILE * dump = fopen(".saved.fdd", "wb"); if (dump) { fwrite(&_data[0], 1, _data.size(), dump); } fclose(dump); } uint8_t get(int index) override { if (index < 0 || index >= (int)size()) throw std::out_of_range("boundary error"); return _data[index]; } void set(int index, uint8_t value) override { if (index < 0 || index >= (int)size()) throw std::out_of_range("boundary error"); _data[index] = value; } size_t size() override { return _data.size(); } }; class FileDiskImage : public DiskImage { std::string filename; std::vector<uint8_t> _data; bool loaded; bool dirty; public: FileDiskImage(const std::string & path) : filename(path), loaded(false), dirty(false) { } ~FileDiskImage() { flush(); } uint8_t get(int index) override { if (index < 0 || index >= (int)size()) throw std::out_of_range("boundary error"); return _data[index]; } void set(int index, uint8_t value) override { if (index < 0 || index >= (int)size()) throw std::out_of_range("boundary error"); bool changed = _data[index] != value; if (changed) { _data[index] = value; dirty = true; } } size_t size() override { load(); return _data.size(); } void load() { if (!loaded) { _data = util::load_binfile(filename); loaded = true; } } void flush() override { if (dirty) { std::string tmp = util::tmpname(filename); FILE * copy = fopen(tmp.c_str(), "wb"); if (copy) { fwrite(&_data[0], 1, _data.size(), copy); } fclose(copy); if (0 == util::careful_rename(tmp, filename)) { dirty = false; } } } bool is_valid() { load(); return _data.size() > 0; } }; class DirectoryImage : public DiskImage { std::string path; std::string dirimage; FilesystemImage dir; bool loaded; bool dirty; public: DirectoryImage(const std::string & path) : path(path), dir(FilesystemImage::MAX_FS_BYTES), loaded(false), dirty(false) {} ~DirectoryImage() { flush(); } uint8_t get(int index) override { if (index < 0 || index >= (int)size()) throw std::out_of_range("boundary error"); return dir.data()[index]; } void set(int index, uint8_t value) override { if (index < 0 || index >= (int)size()) throw std::out_of_range("boundary error"); bool changed = dir.data()[index] != value; if (changed) { dir.data()[index] = value; dirty = true; } } size_t size() override { load(); return dir.data().size(); } void load() { if (!loaded) { dir.mount_local_dir(path); loaded = true; dirimage = path + "/" + "dirimage.fdd"; dirty = true; flush(); } } void flush() override { if (dirty) { std::string tmp = util::tmpname(dirimage); FILE * copy = fopen(tmp.c_str(), "wb"); if (copy) { fwrite(&dir.data()[0], 1, dir.data().size(), copy); fclose(copy); } else { fprintf(stderr, "%s: failed to write to %s\n", __PRETTY_FUNCTION__, tmp.c_str()); } if (0 == util::careful_rename(tmp, dirimage)) { dirty = false; } } } }; class FDisk { private: std::string name; public: std::unique_ptr<DiskImage> dsk; private: int sectorsPerTrack; int sectorSize; int totSec; int numHeads; int tracksPerSide; int data; int track; int side; int sector; int position; int readOffset; int readLength; int readSource; uint8_t readBuffer[6]; public: FDisk() : dsk(std::make_unique<CardboardDiskImage>()) { this->init(); } void attach(const std::vector<uint8_t> & data) { this->dsk = std::make_unique<DetachedDiskImage>(data); this->init(); } void attach(const std::string & file) { this->dsk = std::make_unique<FileDiskImage>(file); if (this->dsk->size() == 0) { this->dsk = std::make_unique<DirectoryImage>(file); } this->init(); } void init() { this->sectorsPerTrack = 9; this->sectorSize = 512; this->totSec = 720; this->numHeads = 1; this->tracksPerSide = (this->totSec / this->sectorsPerTrack / this->numHeads) | 0; this->data = 0; this->track = 0; this->side = 0; this->position = 0; // read helpers this->readOffset = 0; this->readLength = 0; this->readSource = 0; // 0: dsk, 1: readBuffer this->parse_v06c(); } static int sector_length_to_code(int length) { switch (length) { case 128: return 0; case 256: return 1; case 512: return 2; case 1024: return 3; } printf("FD1793 bad sector length %d\n", length); return -1; } bool isReady() const { return this->dsk->size() > 0; } void seek(int track, int sector, int side) { if (isReady()) { int offsetSector = (sector != 0) ? (sector - 1) : 0; this->position = (track * (this->sectorsPerTrack * this->numHeads) + (this->sectorsPerTrack * side) + offsetSector) * this->sectorSize; this->track = track; this->side = side; if (Options.log.fdc) { printf("FD1793: disk seek position: %08x " "(side:%d,trk:%d,sec:%d)\n", this->position, this->side, this->track, sector); } } }; void readSector(int sector) { this->readLength = this->sectorSize; this->readOffset = 0; this->readSource = 0; this->sector = sector; this->seek(this->track, this->sector, this->side); } void readAddress() { this->readLength = 6; this->readSource = 1; this->readOffset = 0; this->readBuffer[0] = this->track; this->readBuffer[1] = this->side; // invert side ? not sure this->readBuffer[2] = this->sector; this->readBuffer[3] = FDisk::sector_length_to_code(this->sectorSize); this->readBuffer[4] = 0; this->readBuffer[5] = 0; } bool read() { bool finished = true; if (this->readOffset < this->readLength) { finished = false; if (this->readSource) { this->data = this->readBuffer[this->readOffset]; } else { this->data = this->dsk->get(this->position + this->readOffset); } this->readOffset++; } else { if (Options.log.fdc) { printf("FD1793: read finished src:%d\n", this->readSource); } } //printf("FD1793: disk read, rem: %d finished: %d\n", this->readLength, // finished); return finished; } bool write_data(uint8_t data) { bool finished = true; if (this->readOffset < this->readLength) { finished = false; this->dsk->set(this->position + this->readOffset, data); this->readOffset++; if (this->readOffset == this->readLength) { this->dsk->flush(); } } else { if (Options.log.fdc) { printf("FD1793: write finished: position=%08x\n", this->position); for (int i = 0; i < this->readLength; ++i) { printf("%02x ", this->dsk->get(this->position + i)); if ((i + 1) % 16 == 0 || i + 1 == this->readLength) { printf(" "); for (int j = -15; j <= 0; ++j) { printf("%c", util::printable_char( this->dsk->get(this->position + i + j))); } printf(" W\n"); } } } } return finished; } void writeSector(int sector) { this->readLength = this->sectorSize; this->readOffset = 0; this->readSource = 0; this->sector = sector; this->seek(this->track, this->sector, this->side); } // Vector-06c floppy: 2 sides, 5 sectors of 1024 bytes bool parse_v06c() { const int FDD_NSECTORS = 5; if (!this->isReady()) { return false; } this->tracksPerSide = (this->dsk->size() >> 10) / 2 * FDD_NSECTORS; this->numHeads = 2; this->sectorSize = 1024; this->sectorsPerTrack = 5; this->totSec = this->dsk->size() / 1024; return true; }; uint8_t read_data() const { return this->data; } }; class FD1793 { private: FDisk _disks[4]; int _pr; // port 4, parameter register: SS,MON,DDEN,HLD,DS3,DS2,DS1,DS0 // motor on: 1: motor on // double density: 1: on // hold: 1: head on disk (it is or-ed with motor on) // drive select: 1: drive active int _side; // side select: 0: side 0, 1: side 1 int _intrq; int _data; // data int _status; int _command; int _commandtr; int _track; int _sector; int _stepdir; int _lingertime; int _dsksel; int LINGER_BEFORE; int LINGER_AFTER; char debug_buf[16]; int debug_n; FDisk & dsk(int n = -1) { return _disks[n == -1 ? _dsksel : n]; } public: const int ST_NOTREADY = 0x80; // sampled before read/write const int ST_READONLY = 0x40; const int ST_HEADLOADED = 0x20; const int ST_RECTYPE = 0x20; const int ST_WRFAULT = 0x20; const int ST_SEEKERR = 0x10; const int ST_RECNF = 0x10; const int ST_CRCERR = 0x08; const int ST_TRACK0 = 0x04; const int ST_LOSTDATA = 0x04; const int ST_INDEX = 0x02; const int ST_DRQ = 0x02; const int ST_BUSY = 0x01; const int PRT_INTRQ = 0x01; const int PRT_DRQ = 0x80; const int CMD_READSEC = 1; const int CMD_READADDR = 2; const int CMD_WRITESEC = 3; // Delays, not yet implemented: // A command and between the next status: mfm 14us, fm 28us // Reset // - registers cleared // - restore (03) command // - steps until !TRO0 goes low (track 0) // FD1793() : _dsksel(0) { LINGER_AFTER = 2; _lingertime = 3; _stepdir = 1; } void init() { } FDisk & disk(int drive) { if (drive < 0 || drive > 3) { throw std::out_of_range("drives must be in range 0..3"); } return this->_disks[drive]; } void exec() { bool finished; if (this->_commandtr == CMD_READSEC || this->_commandtr == CMD_READADDR) { if (this->_status & ST_DRQ) { printf("FD1793: invalid read\n"); return; } finished = this->dsk().read(); if (finished) { this->_status &= ~ST_BUSY; this->_intrq = PRT_INTRQ; } else { this->_status |= ST_DRQ; this->_data = this->dsk().read_data(); } //if (Options.log.fdc) { // printf("FD1793: exec - read done, " // "finished: %d data: %02x status: %02x\n", // finished, this->_data, this->_status); //} } else if (this->_commandtr == CMD_WRITESEC) { if ((this->_status & ST_DRQ) == 0) { finished = this->dsk().write_data(this->_data); if (finished) { this->_status &= ~ST_BUSY; this->_intrq = PRT_INTRQ; } else { this->_status |= ST_DRQ; } } } else { // finish lingering this->_status &= ~ST_BUSY; } } int sectorcnt = 0; int readcnt = 0; int fault = 0; int read(int addr) { if (Options.nofdc) return 0xff; int result = 0; if (this->dsk().isReady()) this->_status &= ~ST_NOTREADY; else this->_status |= ST_NOTREADY; int returnStatus; switch (addr) { case 0: // status // if ((this->_status & ST_BUSY) && this->_lingertime > 0) { // if (--this->_lingertime == 0) { // this->exec(); // } // } // to make software that waits for the controller to start happy: // linger -10 to 0 before setting busy flag, set busy flag // linger 0 to 10 before exec returnStatus = this->_status; if (this->_status & ST_BUSY) { if (this->_lingertime < 0) { returnStatus &= ~ST_BUSY; // pretend that we're slow ++this->_lingertime; } else if (this->_lingertime < this->LINGER_AFTER) { ++this->_lingertime; } else if (this->_lingertime == this->LINGER_AFTER) { ++this->_lingertime; this->exec(); returnStatus = this->_status; } } //this->_status &= (ST_BUSY | ST_NOTREADY); this->_intrq = 0; //if (this->fault) { // printf("read status: injecting fault: result= ff\n"); // returnStatus = 0xff; //} result = returnStatus; break; case 1: // track result = this->_track; break; case 2: // sector result = this->_sector; break; case 3: // data if (!(this->_status & ST_DRQ)) { //throw ("invalid read"); if (Options.log.fdc) { printf("FD1793: reading too much!\n"); } } result = this->_data; ++this->readcnt; if (this->readcnt == 1024) { ++this->sectorcnt; } if (Options.log.fdc) { if (this->_status & ST_DRQ) { printf("%02x ", result); this->debug_buf[this->debug_n] = result; if (++this->debug_n == 16) { printf(" "); this->debug_n = 0; for (int i = 0; i < 16; ++i) { printf("%c", util::printable_char( this->debug_buf[i])); } printf("\n"); } } } this->_status &= ~ST_DRQ; this->exec(); //console.log("FD1793: read data:",Utils.toHex8(result)); break; case 4: if (this->_status & ST_BUSY) { this->exec(); } // DRQ,0,0,0,0,0,0,INTRQ // faster to use than FDC result = this->_intrq | ((this->_status & ST_DRQ) ? PRT_DRQ : 0); break; default: printf("FD1793: invalid port read\n"); result = -1; break; } if (!(this->_status & ST_DRQ) && Options.log.fdc) { printf("FD1793: read port: %02x result: %02x status: %02x\n", addr, result, this->_status); } return result; }; void command(int val) { int cmd = val >> 4; int param = val & 0x0f; int update, multiple; update = multiple = (param & 1); this->_intrq = 0; this->_command = val; this->_commandtr = 0; switch (cmd) { case 0x00: // restor, type 1 if (Options.log.fdc) { printf("CMD restore\n"); } this->_intrq = PRT_INTRQ; if (this->dsk().isReady()) { this->_track = 0; this->dsk().seek(this->_track, 1, this->_side); } else { this->_status |= ST_SEEKERR; } break; case 0x01: // seek if (Options.log.fdc) { printf("CMD seek: %02x\n", param); } this->dsk().seek(this->_data, this->_sector, this->_side); this->_track = this->_data; this->_intrq = PRT_INTRQ; this->_status |= ST_BUSY; this->_lingertime = this->LINGER_BEFORE; break; case 0x02: // step, u = 0 case 0x03: // step, u = 1 if (Options.log.fdc) { printf("CMD step: update=%d\n", update); } this->_track += this->_stepdir; if (this->_track < 0) { this->_track = 0; } this->_lingertime = this->LINGER_BEFORE; this->_status |= ST_BUSY; break; case 0x04: // step in, u = 0 case 0x05: // step in, u = 1 if (Options.log.fdc) { printf("CMD step in: update=%d\n", update); } this->_stepdir = 1; this->_track += this->_stepdir; this->_lingertime = this->LINGER_BEFORE; this->_status |= ST_BUSY; //this->dsk().seek(this->_track, this->_sector, this->_side); break; case 0x06: // step out, u = 0 case 0x07: // step out, u = 1 if (Options.log.fdc) { printf("CMD step out: update=%d\n", update); } this->_stepdir = -1; this->_track += this->_stepdir; if (this->_track < 0) { this->_track = 0; } this->_lingertime = this->LINGER_BEFORE; this->_status |= ST_BUSY; break; case 0x08: // read sector, m = 0 case 0x09: // read sector, m = 1 { //int rsSideCompareFlag = (param & 2) >> 1; //int rsDelay = (param & 4) >> 2; //int rsSideSelect = (param & 8) >> 3; this->_commandtr = CMD_READSEC; this->_status |= ST_BUSY; this->dsk().seek(this->_track, this->_sector, this->_side); this->dsk().readSector(this->_sector); this->debug_n = 0; if (Options.log.fdc) { printf("CMD read sector m:%d p:%02x sector:%d " "status:%02x\n", multiple, param, this->_sector, this->_status); } this->_lingertime = this->LINGER_BEFORE; } break; case 0x0A: // write sector, m = 0 case 0x0B: // write sector, m = 1 { this->_commandtr = CMD_WRITESEC; this->_status |= ST_BUSY; this->_status |= ST_DRQ; this->dsk().seek(this->_track, this->_sector, this->_side); this->dsk().writeSector(this->_sector); this->debug_n = 0; if (Options.log.fdc) { printf("CMD write sector m:%d p:%02x sector:%d " "status:%02x\n", multiple, param, this->_sector, this->_status); } this->_lingertime = this->LINGER_BEFORE; } break; case 0x0C: // read address this->_commandtr = CMD_READADDR; this->_status |= ST_BUSY; this->dsk().readAddress(); this->_lingertime = this->LINGER_BEFORE; if (Options.log.fdc) { printf("CMD read address m:%d p:%02x status:%02x", multiple, param, this->_status); } break; case 0x0D: // force interrupt if (Options.log.fdc) { printf("CMD force interrupt\n"); } break; case 0x0E: // read track printf("CMD read track (not implemented)\n"); break; case 0x0F: // write track printf("CMD write track (not implemented)\n"); break; } // if ((this->_status & ST_BUSY) != 0) { // this->_lingertime = 10; // } }; void write(int addr, int val) { if (Options.log.fdc) { printf("FD1793: write [%02x]=%02x: ", addr, val); } switch (addr) { case 0: // command if (Options.log.fdc) { printf("COMMAND %02x: ", val); } this->command(val); break; case 1: // track (current track)j if (Options.log.fdc) { printf("set track:%d\n", val); } this->_track = val; this->_status &= ~ST_DRQ; break; case 2: // sector (desired sector) if (Options.log.fdc) { printf("set sector:%d\n", val); } this->_sector = val; this->_status &= ~ST_DRQ; break; case 3: // data if (Options.log.fdc) { printf("set data:%02x\n", val); } this->_data = val; this->_status &= ~ST_DRQ; this->exec(); break; case 4: // param reg this->_pr = val; // Kishinev v06c // 0 0 1 1 x S A B this->_dsksel = val & 3; this->_side = ((~val) >> 2) & 1; // invert side if (Options.log.fdc) { printf("set pr:%02x disk select: %d side: %d\n", val, val & 3, this->_side); } // // SS,MON,DDEN,HLD,DS3,DS2,DS1,DS0 // if (val & 1) this->dsk() = this->_disks[0]; // else if (val & 2) this->dsk() = this->_disks[1]; // else if (val & 4) this->dsk() = this->_disks[2]; // else if (val & 8) this->dsk() = this->_disks[3]; // else this->dsk() = this->_disks[0]; // this->_side = (this->_pr & 0x80) >>> 7; break; default: printf("invalid port write\n"); return; } } };
true
8c62d1a94a1e50a5fb06639276d312a22920c95d
C++
jawiezhu/Exercise
/leetcode/C++/RemoveLinkedListElements.cpp
UTF-8
5,008
3.953125
4
[]
no_license
// Remove all elements from a linked list of integers that have value val. // Example // Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 // Return: 1 --> 2 --> 3 --> 4 --> 5 //MY ERROR // class Solution { // public: // ListNode* removeElements(ListNode* head, int val) { // if(head==NULL) return NULL; // if(head->val==val&&head->next==NULL) // return NULL; // if(head->val==val) // head=head->next; // ListNode * p=head; // while(p->next) // { // if(p->next->next==NULL&&p->next->val==val) // { // p->next=NULL; // break; // } // if(p->next->val==val) // { // p->next=p->next->next; // } // p=p->next; // } // return head; // } // }; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(head==NULL) return NULL; ListNode * p=head; ListNode * q=head->next; while(q) { if(q->val==val) { p->next=q->next; delete q; q=p->next; }else{ p=p->next; q=q->next; } } if(head->val==val) { p=head; head=head->next; delete p; } return head; } }; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { if (head == NULL) { return NULL; } ListNode *result = head; ListNode *p = head; while (p && p->val == val) { ListNode *temp = p; p = p->next; delete temp; } result = p; while (p) { if (p->next && p->next->val == val) { ListNode *temp = p->next; p->next = p->next->next; delete temp; continue; } p = p->next; } return result; } }; //遇到val则删除,否则继续前进,直到链表结尾。 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* newhead = new ListNode(-1); newhead->next = head; ListNode* pre = newhead; ListNode* cur = head; while(cur != NULL) { if(cur->val == val) { cur = cur->next; pre->next = cur; } else { pre = cur; cur = cur->next; } } return newhead->next; } }; // 第一种: // 直接两个指针pre和cur,一前一后,相互挨着,cur指针遇到val后,pre的next直接指向cur的下一个指针,同时cur也向后移动一个。 // 第二种: // 把指定的元素看成雷区,cur指针进入雷区后,pre停止并等待cur出雷区,同时pre的next指针指向出雷区的第一个元素。但是这种方法得有一个是否进入雷区的标志,但是我觉得可以优化。 // 第三种方法: // 优雅的递归调用 ListNode* removeElements(ListNode* head, int val) { ListNode *pre; ListNode *cur; ListNode *temp; pre = head; while(pre != NULL && pre->val == val) { temp = pre; pre = pre->next; delete temp; } if(pre == NULL) { return NULL; } head = pre; cur = pre->next; while(cur != NULL) { if(cur->val == val) { temp = cur; pre->next = cur->next; delete temp; } else { pre = cur; } cur = cur->next; }//while return head; } ListNode* removeElements(ListNode* head, int val) { ListNode *temp = NULL; if(head && head->val == val) { temp = head; head = removeElements(head->next, val); delete temp; } if(head && head->next) { head->next = removeElements(head->next, val); } return head; } /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode p = dummy; ListNode q = head; while(q!=null) { if(q.val == val) { p.next = q.next; } else { p = p.next; } q = q.next; } return dummy.next; } }
true
0ebfca96fad18c5b71d0e04363b1c191014843c7
C++
optimisticninja/machine-learning
/include/training_data.h
UTF-8
861
2.6875
3
[]
no_license
#pragma once #include <vector> #include <string> using namespace std; class TrainingData { private: vector<vector<double>> data; vector<vector<double>> inputs; vector<vector<double>> expected; unsigned num_inputs; unsigned num_outputs; public: TrainingData(string fname, unsigned num_inputs); unsigned get_num_inputs(); unsigned get_num_outputs(); vector<vector<double>>& get_data(); vector<vector<double>>& get_inputs(); vector<double> get_inputs(unsigned i); vector<vector<double>>& get_expected(); vector<double>& get_expected(unsigned i); vector<double>& get_row(unsigned row_num); double get_cell(unsigned row_num, unsigned col_num); unsigned get_count(); };
true
fbff0a71513126e72ebb4ec6095dd2a4248d576f
C++
hncj811/kdTree
/MegaTree.cpp
UTF-8
6,033
3.125
3
[]
no_license
#include "MegaTree.h" #include <fstream> #include <vector> #include <string> #include<cstring> #include<cmath> int partition(std::vector<MegaNode> &arr, int depth, int top, int bottom){ MegaNode pivot= arr[top]; std::vector<MegaNode> left; std::vector<MegaNode> right; for( int i= top+1; i <= bottom; i++) { if(arr[i].vals[depth] <= pivot.vals[depth]) left.push_back(arr[i]); else right.push_back(arr[i]); } for( int i= 0; i < left.size(); i++) arr[top+i]= left[i]; int ppos = top + left.size(); arr[ppos ]= pivot; for(int i= 0; i < right.size(); i++){ arr[ ppos +i +1] = right[i]; } return ppos; } void quickSort(std::vector <MegaNode> &arr, int top, int bottom, int depth) { if(bottom <= top) return; int middle = partition(arr, depth, top, bottom); quickSort(arr, top, middle-1, depth); quickSort(arr, middle+1, bottom, depth); } int fmedian( std::vector<MegaNode> &arr, int depth){ quickSort(arr, 0, arr.size()-1, depth); int mid= arr.size()/2; return mid; } MegaTree::MegaTree( int dim, std::string filename): head(NULL), dim(dim) { char *cstr = new char [filename.length()+1]; std::strcpy (cstr, filename.c_str()); std::ifstream fin; if(!fin){ std::cerr<<"Error writing file... Exiting now.\n"; //exit(1); } fin.open(cstr); int numOfRecords= 5; fin >> numOfRecords; //std::cout<<"# of records: "<< numOfRecords<<std::endl; std::vector<MegaNode> points; for( int i =0; i < numOfRecords; i++) { std::string record; double vals[dim]; fin >> record; //std::cout <<record<< std::endl; for(int j=0; j<dim; j++) fin >> vals[j]; points.push_back( MegaNode(record, dim, vals) ); } // std::cout<<"1st point: "; //for(int i=0; i< dim; i++) std::cout<< points[0].vals[i] << " "; //std::cout << std::endl; //int ndx =0; head = new MegaNode( makeTree(points, 0)); /* while(points.size() >=1){ int median = fmedian(points, ndx); //std::cout<<"Median: " <<median.name<<std::endl; insert(points[median]); points.erase( points.begin() + median); ndx= (ndx+1)%dim; }*/ //fin.close(); } MegaNode MegaTree::makeTree(std::vector<MegaNode> ls, int depth){ // if(ls.size()== 1) return &ls[0]; //int axis = depth% dim; //fmedian sorts vector gives median ndx int median = fmedian(ls, depth); std::vector<MegaNode> left, right; MegaNode N(ls[median]); for(int i=0; i< ls.size(); i++) { if(i < median) left.push_back(ls[i]); if(i > median) right.push_back(ls[i]); } if(left.size() >0) N.left= new MegaNode( makeTree( left, ++depth%dim)); if(right.size() >0) N.right= new MegaNode( makeTree(right, ++depth%dim)); return N; } void deleteNode(MegaNode *N){ if (N== NULL) return; deleteNode(N->left); deleteNode(N->right); delete N; } MegaTree::~MegaTree(){ deleteNode(head); } void MegaTree::insert(std::string name, double vals[]){ MegaNode *cur= head; if(cur == NULL){ head= new MegaNode(name, dim, vals); return; } int ndx= 0; int treeDepth = 0; while(true){ ndx = treeDepth % dim; if( vals[ndx] < cur->vals[ndx] ){ if( cur->left == NULL){ cur->left = new MegaNode(name, dim, vals); return; } else cur = cur->left; } else if( vals[ndx] >= cur->vals[ndx] ){ if( cur->right == NULL ){ cur->right= new MegaNode(name, dim, vals); return; } else cur = cur->right; } ++treeDepth; } } void MegaTree::insert(MegaNode n){ MegaNode *cur= head; if(cur == NULL){ head= new MegaNode(n); return; } int ndx= 0; int treeDepth = 0; while(true){ ndx = treeDepth % dim; if( n.vals[ndx] < cur->vals[ndx] ){ if( cur->left == NULL){ cur->left = new MegaNode(n); return; } else cur = cur->left; } else if( n.vals[ndx] >= cur->vals[ndx] ){ if( cur->right == NULL ){ cur->right= new MegaNode(n); return; } else cur = cur->right; } ++treeDepth; } } void MegaTree::termsInPreOrder(MegaNode *N, int depth){ if( N== NULL) return; std::cout<< N->name<< ": "; for(int i=0; i <dim; i++) std::cout <<N->vals[i] << " "; std::cout<< std::endl; termsInPreOrder(N->left, ++depth); termsInPreOrder(N->right, ++depth); } std::string MegaTree::nearestNode(double vals[]){ MegaNode* best = NN( vals, head, NULL, 0); return best->name; } MegaNode* MegaTree::NN(double vals[], MegaNode* cur, MegaNode* champ, int ndx){ if(champ ==NULL) champ= cur; if(cur ==NULL) return champ; if(cur->name=="Kinshasa") { std::cout<<"Kinshasa: "<< dist(vals, cur->vals, dim) <<std::endl; for(int i =0; i< dim; ++i) std::cout<< cur->vals[i] << " "; } double curdist = dist(vals, cur->vals, dim); double bestDist = dist(vals, champ->vals, dim); if(curdist < bestDist) champ = cur; bestDist = dist(vals, champ->vals, dim); //champ = NN(vals, cur->left, champ, (ndx+1)%dim); //champ= NN(vals, cur->right, champ, (ndx+1)%dim); MegaNode *visit_first= cur->left, *visit_second= cur->right; //if pt[ndx] is greater than splitting plane cur_>vals{ndx] go //right else go left first if(vals[ndx] > cur->vals[ndx]) { //std::swap(visit_first, visit_second); visit_second=cur->left; visit_first= cur->right; } champ= NN(vals, visit_first, champ, (ndx+1)%dim); bestDist = dist(vals, champ->vals, dim); //if dist b/t pt[ndx] & plane is greater than bestDist this means //NN is already found... Dont search second subtree if( fabs(vals[ndx] - cur->vals[ndx]) > bestDist) return champ; champ= NN(vals, visit_second, champ, (ndx+1)%dim); return champ; } double MegaTree::dist( double vals[], double rhs[], int len){ double dist =0.0; for(int i=0; i < len; ++i) dist += pow(vals[i]- rhs[i], 2); return sqrt(dist); }
true
f41fc302342f7dedfde7410837669ec7709ffc78
C++
saimisosa/CS2124-SPRING
/rec07_sepComp_2020/Student.h
UTF-8
680
2.6875
3
[]
no_license
// // Created by Saimanasa Juluru on 3/13/20. // #ifndef REC07_SEPCOMP_STUDENT_H #define REC07_SEPCOMP_STUDENT_H #include <vector> #include <string> #include <iostream> using namespace std; namespace BrooklynPoly { class Course; class Student { friend ostream& operator<<(ostream& os, const Student& rhs); public: // Student methods needed by Registrar Student(const string& name); const string& getName() const; bool addCourse(Course*); // Student method needed by Course void removedFromCourse(Course*); private: string name; vector<Course*> courses; }; } #endif //REC07_SEPCOMP_STUDENT_H
true
74950cc04a5d71cd8eeee1b9c4339f25f19bffcc
C++
AltropInc/alt
/src/util/net/SocketAddress.h
UTF-8
3,562
2.515625
3
[]
no_license
#pragma once #include "IPAddress.h" #include <sys/socket.h> // for sockaddr_storage namespace alt { using PortId = uint16_t; constexpr PortId WILDCARD_PORT_ID = 0; class ALT_UTIL_PUBLIC SocketAddress { public: //----------------------------------------------------------------------------- // Constructors //----------------------------------------------------------------------------- /// \brief construct an empty uninitialized address /// (family()==IPFamily::Unset) SocketAddress(); /// \brief construct a socket address by a given io address and port SocketAddress(const IPAddress& addr, PortId port #if ALT_IPV6_AVAILABLE , uint32_t flowinfo_ =0 , uint32_t scope_ =0 #endif ); /// \brief construct a socket address from the native one SocketAddress(const struct sockaddr_storage& ip_addr) noexcept(false); void fromRawFormat(const struct sockaddr_storage& ip_addr) noexcept(false); void toRawForamt(struct sockaddr_storage& ip_addr) noexcept(false); static SocketAddress fromString( const char* addr, size_t length=0, PortId default_port=WILDCARD_PORT_ID); template <typename StrT> static SocketAddress fromString(const StrT& addr, PortId default_port=WILDCARD_PORT_ID) { return fromString(addr.c_str(), addr.length(), default_port); } std::string toString() const; size_t hash() const; IPFamily family() const; int af() const; const void* ipAddr(socklen_t& addr_length) const; IPAddress ipAddr() const; const sockaddr* addr() const; socklen_t addrLength() const; PortId port() const; #if ALT_IPV6_AVAILABLE uint32_t flowInfo() const; uint32_t scope() const; #endif private: struct sockaddr_storage storage_; /* IPAddress addr_; PortId port_ {WILDCARD_PORT_ID}; #if ALT_IPV6_AVAILABLE uint32_t flowinfo_ {0}; uint32_t scope_ {0}; #endif */ }; } // namespace alt namespace std { template <> struct hash<alt::SocketAddress> { size_t operator()(const alt::SocketAddress& key) const noexcept { return key.hash(); } }; } // namespace std #if 0 struct sockaddr { unsigned short sa_family; // address family, AF_xxx char sa_data[14]; // 14 bytes of protocol address }; struct sockaddr_in { short sin_family; // e.g. AF_INET, AF_INET6 unsigned short sin_port; // e.g. htons(3490) struct in_addr sin_addr; // see struct in_addr, below char sin_zero[8]; // zero this if you want to }; struct sockaddr_in6 { u_int16_t sin6_family; // address family, AF_INET6 u_int16_t sin6_port; // port number, Network Byte Order u_int32_t sin6_flowinfo; // IPv6 flow information struct in6_addr sin6_addr; // IPv6 address u_int32_t sin6_scope_id; // Scope ID }; struct sockaddr_storage { short ss_family; char __ss_pad1[_SS_PAD1SIZE]; __MINGW_EXTENSION __int64 __ss_align; char __ss_pad2[_SS_PAD2SIZE]; }; struct sockaddr_storage { sa_family_t ss_family; // address family // all this is padding, implementation specific, ignore it: char __ss_pad1[_SS_PAD1SIZE]; int64_t __ss_align; char __ss_pad2[_SS_PAD2SIZE]; }; #endif
true
0d0a7326cf53118e7513bea91f6172f472accd7a
C++
godnoTA/acm.bsu.by
/1. Деревья поиска/0.0 #3295/[OK]185823.cpp
UTF-8
742
3.09375
3
[ "Unlicense" ]
permissive
#include <fstream> #include <vector> #include <algorithm> int main() { std::ifstream fin("input.txt"); std::ofstream fout("output.txt"); long n = 0; long long sum = 0; std::vector<long> listBT; while (!fin.eof()) { // считали значения из файла и занесли их в список fin >> n; listBT.push_back(n); } n = 0; std::sort(listBT.rbegin(), listBT.rend()); long size = listBT.size(); // узнали размер обработанного листа for (long i = 0; i < size; i++) { if(n != listBT[i]) { n = listBT[i]; sum += n; } }// посчитали сумму fout << sum; fin.close(); fout.close(); return 0; }
true
dfe67e1c2dde0b26db98b9a88757432b9c022ee7
C++
rencheckyoself/turtlebot3-navigation
/nuslam/src/landmarks.cpp
UTF-8
6,845
2.59375
3
[]
no_license
/// \file /// \brief This node clusters laser scan data points and fits each cluster to a circular landmark /// /// PARAMETERS: /// distance_threshold: (double) Threshold to determine if a point is in a cluster /// radius_threshold: (double) Threshold to determine if a cirlce fit is valid for an obstacle /// frame_id: (string) The frame the Laser scan data is relative to /// PUBLISHES: /// /landmark_data: (nuslam/TurtleMap) a list of centers and radii for cylindrical landmarks /// SUBSCRIBES: /// /scan: (sensor_msgs/LaserScan) the raw laser data from the turtlebot /// SERIVCES: #include <vector> #include <Eigen/Dense> #include "ros/ros.h" #include "std_msgs/Header.h" #include "geometry_msgs/Point.h" #include "geometry_msgs/Point32.h" #include "nuslam/TurtleMap.h" #include "sensor_msgs/LaserScan.h" #include "sensor_msgs/PointCloud.h" #include "rigid2d/rigid2d.hpp" #include "nuslam/cylinder_detect.hpp" static double distance_threshold = 0; static double radius_threshold = 0; static std::string frame_id = "Did not Fill"; static ros::Publisher pub_cmd, pub_pc; /// \brief converts a point in polar coordinates into cartesian coordinates /// \param r: the distange to the point /// \param theta: the angle to the point /// \return (rigid2d::Vector2D) x,y coordinates of the point rigid2d::Vector2D polar2cart(double r, double theta) { return rigid2d::Vector2D(r*std::cos(theta), r*std::sin(theta)); } /// \brief Callback function for the sensor subscriber void callback_robotScan(sensor_msgs::LaserScan::ConstPtr data) { ros::NodeHandle temp_n("~"); int plot_cluster = 0; temp_n.getParam("plot_cluster", plot_cluster); std::vector<rigid2d::Vector2D> temp_points; // Temporary cluster of points std::vector<std::vector<rigid2d::Vector2D>> buf_points_list; // list of all point clusters std::vector<std::vector<rigid2d::Vector2D>> points_list; // list of all point clusters std::vector<geometry_msgs::Point32> pc_points; geometry_msgs::Point32 pc_point; sensor_msgs::PointCloud pointcloud; double cur_range = 0; double cur_theta = 0; double max_range = data->range_max; double min_range = data->range_min; // Loop through the data points in the returned array to find clusters // ROS_INFO_STREAM("Total scan points: " << data->ranges.size()); for(unsigned int i = 0; i < data->ranges.size(); i++) { cur_range = data->ranges.at(i); cur_theta = data->angle_min + (data->angle_increment * i); // check if the point is valid valid point if(cur_range < max_range && cur_range > min_range) { // if the current cluster is empty, add point to the list if(temp_points.empty()) { temp_points.push_back(polar2cart(cur_range, cur_theta)); } // if the current point is within the distance threshold, add to the // current point list else if(std::fabs(cur_range - data->ranges.at(i-1)) <= distance_threshold) { temp_points.push_back(polar2cart(cur_range, cur_theta)); } // if the current point is outside of the distance threshold, add current // point a new cluster else if(std::fabs(cur_range - data->ranges.at(i-1)) > distance_threshold) { buf_points_list.push_back(temp_points); temp_points.clear(); temp_points.push_back(polar2cart(cur_range,cur_theta)); } // Error Catching else { ROS_ERROR_STREAM("Valid Point not assigned. Point ID " << i << " Point range " << cur_range << " Point bearing " << cur_theta); } } } // If last cluster merges with the first cluster, then combine the two point lists if(std::fabs(data->ranges.at(0) - data->ranges.at(data->ranges.size()-1)) <= distance_threshold) { buf_points_list.at(0).insert(buf_points_list.at(0).end(), temp_points.begin(), temp_points.end()); } else // Save final cluster { buf_points_list.push_back(temp_points); } // Plot one cluster of data for(unsigned int buf_ctr = 0; buf_ctr < buf_points_list.at(plot_cluster).size()-1; buf_ctr++) { pc_point.x = buf_points_list.at(plot_cluster).at(buf_ctr).x; pc_point.y = buf_points_list.at(plot_cluster).at(buf_ctr).y; pc_point.z = 0.1; pc_points.push_back(pc_point); } pointcloud.points = pc_points; pointcloud.header.frame_id = frame_id; pointcloud.header.stamp = ros::Time::now(); pub_pc.publish(pointcloud); pc_points.clear(); int total_clusters = buf_points_list.size(); // Prune clusters with less than 3 points for(int j = 0; j < total_clusters; j++) { temp_points.clear(); temp_points = buf_points_list.back(); buf_points_list.pop_back(); if(temp_points.size() > 3) { points_list.push_back(temp_points); } } // Circle Fitting Algorithm // For more details see: A. Al-Sharadqah and N. Chernov, Error Analysis for // Circle Fitting Algorithms, Electronic Journal of Statistics (2009), Volume 3 p 886-911 // https://projecteuclid.org/download/pdfview_1/euclid.ejs/1251119958 temp_points.clear(); std::vector<double> circle_param; geometry_msgs::Point center_point; std::vector<geometry_msgs::Point> center_points; std::vector<double> radii; nuslam::TurtleMap cluster_data; for(auto cluster : points_list) { // Fit circle to a cluster circle_param = cylinder::fit_circles(cluster); // eliminate if radius is unreasonably large if(circle_param.at(2) < radius_threshold) { center_point.x = circle_param.at(0); center_point.y = circle_param.at(1); center_points.push_back(center_point); radii.push_back(circle_param.at(2)); // ROS_INFO_STREAM("STEP 10 Complete"); } else { // ROS_INFO_STREAM("Cluster eliminated due to a large radius size."); } } // ROS_INFO_STREAM("Init Clusters: " << points_list.size() << " Fin Clusters: " << center_points.size()); // Assemble variable to publish cluster_data.header.frame_id = frame_id; cluster_data.centers = center_points; cluster_data.radii = radii; pub_cmd.publish(cluster_data); } /// \brief main function to create the real_waypoints node int main(int argc, char** argv) { ros::init(argc, argv, "landmarks"); ros::NodeHandle n; ros::NodeHandle pn("~"); ros::Subscriber sub_scan = n.subscribe("scan", 1, callback_robotScan); pub_cmd = n.advertise<nuslam::TurtleMap>("landmark_data", 1); pub_pc = n.advertise<sensor_msgs::PointCloud>("pointcloud_data", 12); pn.getParam("distance_threshold", distance_threshold); pn.getParam("radius_threshold", radius_threshold); pn.getParam("frame_id", frame_id); ROS_INFO_STREAM("LANDMARKS: Distance Threshold " << distance_threshold); ROS_INFO_STREAM("LANDMARKS: Radius Threshold " << radius_threshold); ROS_INFO_STREAM("LANDMARKS: Frame ID " << frame_id); ros::spin(); }
true
d335aa141cf801b68c21ff7b7956924b5399ceb1
C++
igoingdown/leetcode
/130_bfs_mle.cpp
UTF-8
1,320
2.796875
3
[]
no_license
class Solution { private: int m, n; int bias[5] = {1, 0, -1, 0, 1}; void bfs(vector<vector<char>>& board, int i, int j) { if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') return; queue<pair<int, int>> q; q.push(make_pair(i, j)); while (!q.empty()) { auto p = q.front(); q.pop(); int x = p.first, y = p.second; board[x][y] = 'F'; for (int k = 0; k < 4; k++) { int new_x = x + bias[k], new_y = y + bias[k + 1]; if (new_x >= 0 && new_x < m && new_y >= 0 && new_y < n && board[new_x][new_y] == 'O') { q.push(make_pair(new_x, new_y)); } } } } public: void solve(vector<vector<char>>& board) { if (board.size() == 0 || board[0].size() == 0) return; m = board.size(), n = board[0].size(); for (int i = 0; i < m; i++) { bfs(board, i, 0); bfs(board, i, n - 1); } for (int j = 0; j < n; j++) { bfs(board, 0, j); bfs(board, m - 1, j); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { board[i][j] = (board[i][j] == 'F' ? 'O' : 'X'); } } } };
true
b63c6a223a711728a1de79e04093c2180b260688
C++
rparrot/CPP-Learning
/basics/exception.cpp
UTF-8
669
3.265625
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; int main(){ // Uncomment one of the following line //int call_api = 2; //float call_api = 2.2; //char call_api = 'R'; try { cout<<"trying to use API value\n"; cout<<"Did some testing with api value\n"; throw call_api; cout<<"NO code execute after return and throw\n"; } catch(int x) { cout<<"Integer exception handled\n"; }catch(float f){ cout<<"Float exception handled\n"; }catch(...){ // Catch any type of error cout<<"Something went wrong\n"; } cout<<"Keep on moving with rest of code\n"; return 0; }
true
5e5b92d0818de015c0f1dc9d6626df4f373cbf4f
C++
jwebb68/nel
/src/nel/heaped/test_box.cc
UTF-8
3,160
3.234375
3
[ "Apache-2.0" ]
permissive
// -*- mode: c++; indent-tabs-mode: nil; tab-width: 4 -*- #include <nel/heaped/box.hh> #include <catch2/catch.hpp> namespace nel { namespace test { namespace heaped { namespace box { TEST_CASE("heaped::Box", "[heaped][box]") { // must be able to create a boxed value auto a1 = nel::heaped::Box<int>::try_from(1).unwrap(); // must create not empty. REQUIRE(a1.has_value()); } TEST_CASE("heaped::Box::move", "[heaped][box]") { // must be able to move box contents from one box to another. auto a1 = nel::heaped::Box<int>::try_from(1).unwrap(); auto a2 = nel::move(a1); // moved from is no empty REQUIRE(!a1.has_value()); // moved to is not empty REQUIRE(a2.has_value()); // moved to has old a1 value REQUIRE(*a2 == 1); // A const boxed cannot be moved? // what is const, the box or the value? } // TODO: test Box copy must fail compile. TEST_CASE("heaped::Box::deref", "[heaped][box]") { // deref must return value value put into the box. // mutable version auto a1 = nel::heaped::Box<int>::try_from(1).unwrap(); REQUIRE(*a1 == 1); // and value is not consumed by the deref REQUIRE(*a1 == 1); // and can mutate the boxed value *a1 = 3; REQUIRE(*a1 == 3); // const version auto c1 = nel::heaped::Box<int const>::try_from(2).unwrap(); REQUIRE(*c1 == 2); // and value is not consumed by the deref REQUIRE(*c1 == 2); // and cannot mutate the boxed value // *c1 = 3; // compile fail // REQUIRE(*a1 == 2); } TEST_CASE("heaped::Box::has_value", "[heaped][box]") { // a newly created boxed always has a value. auto a1 = nel::heaped::Box<int>::try_from(2).unwrap(); REQUIRE(a1.has_value()); // moving the boxed value to another causes the variable to lose it's value. auto a2 = nel::move(a1); REQUIRE(!a1.has_value()); REQUIRE(a2.has_value()); } TEST_CASE("heaped::Box::unwrap", "[heaped][box]") { // unwrap of empty produces panic.. // can box ever be created empty? // TODO: how to test this? // auto a1 = nel::heaped::Box<int>(); // REQUIRE(!a1.has_value()); // REQUIRE(a1.unwrap()); // unwrap of value returns that value. // and invalidates the box. auto a1 = nel::heaped::Box<int>::try_from(1).unwrap(); REQUIRE(a1.unwrap() == 1); REQUIRE(!a1.has_value()); // cannot unwrap const box? // unwraping invalidates box so cannot be const.. (?) // TODO: how to test fails compile? // auto const c1 = nel::heaped::Box<int>(2); // REQUIRE(c2.unwrap() == 2); // unwrap of a box containing a const must work. auto a2 = nel::heaped::Box<int const>::try_from(2).unwrap(); REQUIRE(a2.unwrap() == 2); REQUIRE(!a2.has_value()); } #if 0 TEST_CASE("heaped::Box::eq", "[heaped][box]") { auto a0 = nel::heaped::Box<int>(0); auto a1 = nel::heaped::Box<int>(1); auto a2 = nel::heaped::Box<int>(2); auto i = nel::heaped::Box<int>(1); REQUIRE(i == a1); REQUIRE(i != a2); REQUIRE(i > a0); REQUIRE(i < a2); } #endif }; // namespace box }; // namespace heaped }; // namespace test }; // namespace nel
true
e0a7128be7247bba34cd092f30c9c2d7fcf565ed
C++
sanghoon23/Algorithm
/Programmers_1001_Matching&Removing/ConsoleApplication1_Test/ConsoleApplication1_Test.cpp
UTF-8
1,034
3.21875
3
[]
no_license
#include "pch.h" #include <iostream> #include <string> #include <vector> #include <list> #include <stack> #include <algorithm> using namespace std; string Merge(string S) { string Str = S; for (int i = 0; i < Str.size() - 1; ++i) { if (Str[i] == Str[i + 1]) { Str.erase(i, 2); if (Str == "") break; } } return Str; } //int solution(string S) //{ // //제거만되면 가능한것인가 모두 제거해야되는건가 // bool Answer = 0; // // while (S.size() > 0) // { // string Temp = S; // string Result = Merge(S); // if (Result == Temp) return false; // else S = Result; // } // // return true; //} int solution(string S) { stack<char> Stack; Stack.push(S[0]); for (int i = 1; i < S.size(); ++i) { if (Stack.empty()) { Stack.push(S[i]); continue; } int Top = Stack.top(); if (Top == S[i]) Stack.pop(); else { Stack.push(S[i]); } } if (Stack.empty()) return true; return false; } int main() { string Insert = "baabaa"; int Result = solution(Insert); return 0; }
true
ed6c05fec768204ac8147e35d9ddf02f264e0f2c
C++
multitudinous/mapgen
/src/platform.cpp
UTF-8
3,078
2.671875
3
[ "Apache-2.0" ]
permissive
#include "platform.h" //============================================================================ //============================================================================ #ifndef WIN32 int _vscprintf(const char * format, va_list pargs) { int retval; va_list argcopy; va_copy(argcopy, pargs); retval = vsnprintf(NULL, 0, format, argcopy); va_end(argcopy); return retval; } #endif //============================================================================ //============================================================================ void Platform::getFontSearchPaths(std::vector<std::string> *list) { #ifdef WIN32 list->push_back(std::getenv("WINDIR") + std::string("/fonts/")); #endif #ifdef _APPLE_ list->push_back(std::string("/System/Library/Fonts/")); list->push_back(std::string("/Library/Fonts/")); list->push_back(std::string("~/Library/Fonts/")); list->push_back(std::string("/Network/Library/Fonts/")); #endif #if defined(LINUX) || defined(__linux) list->push_back(std::string("/usr/share/fonts/")); list->push_back(std::string("~/.fonts/")); if( char const* env_p = std::getenv( "MAPGEN_FONT_PATH" ) ) { list->push_back( env_p ); } #endif } /* This is going to be one of those 'simple' problems could have an over-the-top solution depending on what you need this information for. I will have to apologize for the vaguer Linux answers, as font management across Linux distributions are not consistent and can be very configurable, can be influenced by desktop environment, can be remotely served, etc. Checking for environment You can check various platforms via the use of macros defined for specific environments. Windows - #if defined(_WIN32) _WIN32 is defined for both 32-bit and 64-bit Windows. Mac OSX - #if defined(_APPLE_) && defined(_MACH_) _APPLE_ is defined for all Apple computers, and _MACH_ is defined if the system supports Mach system calls, a la Mac OSX Linux (generic) - #if defined(linux) || defined(__linux) Font directory locations ----------------------------------- Windows On Windows newer than 3.1, the font directory is located in %WINDIR%\fonts. Mac OS X Mac OSX has multiple font directories /System/Library/Fonts - Fonts necessary for the system. Do not touch these. /Library/Fonts - Additional fonts that can be used by all users. This is generally where fonts go if they are to be used by other applications. ~/Library/Fonts - Fonts specific to each user. /Network/Library/Fonts - Fonts shared for users on a network. Linux As mentioned above, a Linux distribution may not have specified font directories at all. I remember dealing with this issue a while back since Linux distros don't use any specific font management. There could be an XFS (X Font Server) serving up fonts remotely. The most common locations for fonts across Linux distributions are /usr/share/fonts, /usr/local/share/fonts, and user-specific ~/.fonts Some systems may have configured font directories in the file /etc/fonts/fonts.conf or /etc/fonts/local.conf. */
true
ea41053815e8959334b9fda7ded609e3ffa4e51e
C++
PeterLinkSchultz/Automat-UI
/Binder/LambdaBinder.cpp
UTF-8
1,030
2.828125
3
[]
no_license
#include "pch.h" #include "LambdaBinder.h" void LambdaBinder::bindNodes(StateList &state) { Nodes* nodes = state.getNodes(); for (auto& it : *nodes) { bindGroup(it); } } pGroupCondition LambdaBinder::getCondition(int index) { return data[index-1]->condition; } void LambdaBinder::bindGroup(StateNode &node) { pGroupCondition state = new groupCondition; for (auto& jump : node.jumps) { state->insert({ jump->direction, jump->value }); } auto it = find_if(data.begin(), data.end(), [state](Group<pGroupCondition> *existed) { return isEqualGroups(*state, *existed->condition); }); auto templateLambdaGroup = new Group<pGroupCondition>{ counter, state, {} }; if (it == data.end()) { templateLambdaGroup->items.push_back(&node); data.push_back(templateLambdaGroup); node.lambda = data.back(); counter++; } else { (*it)->items.push_back(&node); node.lambda = *it; delete state; } } vector<LambdaGroup*>* LambdaBinder::getData() { return &data; }
true
bb4638335fd5242e297715a728a5c3876f7a6bea
C++
masa-k0101/Self-Study_Cpp
/Cp3/3-2-2_trainning.cpp
UTF-8
826
3.828125
4
[]
no_license
//vオブジェクトは、ほかのパラメータ同様、値で渡される //そのために、関数内でのパラメータ変更はコールに使われたオブジェクトに影響しない #include<iostream> namespace A { class samp { int i; public: samp(int n) { i = n; } void set_i(int n) { i = n; } int get_i() { return i; } }; //o.iの平方にセット、しかし、sqr_it()には影響しない void sqr_it(samp o) { o.set_i(o.get_i() * o.get_i()); std::cout << "Copy of a has i value of " << o.get_i() << "\n"; } } main() { A::samp a(10); sqr_it(a); //aは値で渡される std::cout << "But a.i is unchanged in main: "<< a.get_i() << "\n"; return 0; }
true
64e902b6ec4942bd409c5016c080048019279128
C++
jw3/example-pdal-plugin
/writer/MyWriter.cpp
UTF-8
2,661
2.78125
3
[]
no_license
#include "MyWriter.h" #include <pdal/pdal_macros.hpp> #include <pdal/util/FileUtils.hpp> #include <pdal/util/ProgramArgs.hpp> namespace pdal { static PluginInfo const s_info = PluginInfo( "writers.mywriter", "My awesome Writer", "http://path/to/documentation" ); CREATE_SHARED_PLUGIN(1, 0, MyWriter, Writer, s_info); std::string MyWriter::getName() const { return s_info.name; } struct FileStreamDeleter { template <typename T> void operator()(T* ptr) { if (ptr) { ptr->flush(); FileUtils::closeFile(ptr); } } }; void MyWriter::addArgs(ProgramArgs& args) { // setPositional() Makes the argument required. args.add("filename", "Output filename", m_filename).setPositional(); args.add("newline", "Line terminator", m_newline, "\n"); args.add("datafield", "Data field", m_datafield, "UserData"); args.add("precision", "Precision", m_precision, 3); } void MyWriter::initialize() { m_stream = FileStreamPtr(FileUtils::createFile(m_filename, true), FileStreamDeleter()); if (!m_stream) { std::stringstream out; out << "writers.mywriter couldn't open '" << m_filename << "' for output."; throw pdal_error(out.str()); } } void MyWriter::ready(PointTableRef table) { m_stream->precision(m_precision); *m_stream << std::fixed; Dimension::Id d = table.layout()->findDim(m_datafield); if (d == Dimension::Id::Unknown) { std::ostringstream oss; oss << "Dimension not found with name '" << m_datafield << "'"; throw pdal_error(oss.str()); } m_dataDim = d; *m_stream << "#X:Y:Z:MyData" << m_newline; } void MyWriter::write(PointViewPtr view) { for (PointId idx = 0; idx < view->size(); ++idx) { double x = view->getFieldAs<double>(Dimension::Id::X, idx); double y = view->getFieldAs<double>(Dimension::Id::Y, idx); double z = view->getFieldAs<double>(Dimension::Id::Z, idx); unsigned int myData = 0; if (!m_datafield.empty()) { myData = (int)(view->getFieldAs<double>(m_dataDim, idx) + 0.5); } *m_stream << x << ":" << y << ":" << z << ":" << myData << m_newline; } } void MyWriter::done(PointTableRef) { m_stream.reset(); } }
true
1eed4c5ec2a91a4d5c74234ca796b44097ef35bb
C++
wjxzju/leetcode_cpp
/leetcode_cpp/leetcode_76.h
UTF-8
1,072
2.921875
3
[]
no_license
#ifndef __LEETCODE_76 #define __LEETCODE_76 #include <iostream> #include <vector> #include <algorithm> #include <unordered_map> using namespace std; class Solution { public: static string minWindow(string s, string t) { unordered_map<char, int> tMap; for (size_t i = 0; i < t.size(); i++) { if (tMap.find(t[i]) == tMap.end()) tMap[t[i]] = 1; else{ tMap[t[i]]++; } } int left = 0, count = 0; int minLen = 0x7fffffff; int minStart = 0; for (size_t right = 0; right <s.size(); right++) { if ( tMap.find(s[right]) != tMap.end()){ //find a char in string tMap[s[right]]--; if (tMap[s[right]] >= 0) count++; } while (count == t.size()){ if (right - left + 1 < minLen){ minStart = left; minLen = right - left + 1; } if (tMap.find(s[left]) != tMap.end()){ tMap[s[left]] ++; if (tMap[s[left]] > 0) count--; } left++; } } //cout << minStart << " " << minLen << endl; if (minLen == 0x7fffffff) return ""; return s.substr(minStart, minLen); } }; #endif
true