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
996f9d18c37f3fa0dc3a4563eaf04bcbf4859cf4
C++
rselvanathan/star_rage
/SRC/Quaternion.cpp
UTF-8
13,892
3.546875
4
[]
no_license
/* This class represents a Quaternion which can be used for rotations. Author : Romesh Selvanathan Date : 03/05/12 References : dhpoware. (2012). OpenGL Third Person Camera Demo. [online]. Available at: <http://www.dhpoware.com/demos/glThirdPersonCamera2.html.>[Accessed: 21 December 2011]. Fletcher, D and Parberry, I. (2002). 3D Math Primer for Graphics and Game Development. Texas: Wordware */ #include "Quaternion.h" #include "Matrix4.h" const Quaternion Quaternion::IDENTITY(1.0f, 0.0f, 0.0f, 0.0f); /* Default Constructor */ Quaternion::Quaternion() { x = y = z = 0.0f; w = 1.0f; } /* Quartenion with sepcified values(w in radians, and this will be normalized) */ Quaternion::Quaternion(float _w,float _x, float _y, float _z) : w(_w), x(_x), y(_y), z(_z) { //this->x = x; this->y = y; this->z = z; this->w = w; //Normalize(); } /* Quaternion with Eular Angles representation (in degrees) */ //Quaternion::Quaternion(const float x, const float y, const float z) //{ // ConvertEularToQuat(x, y, z); //} /* Quaternion with axis-angle representation (w in radians) */ Quaternion::Quaternion(const float angle, const Vec3& v) { ConvertAxisToQuat(angle, v); } Quaternion::Quaternion(const float headDegrees, const float pitchDegrees, const float rollDegrees) { SetHeadPitchRoll(headDegrees, pitchDegrees, rollDegrees); } Quaternion::Quaternion(const Matrix4 &m) { GetMatrix(m); } /* The Identity values of the Quaternion */ void Quaternion::Identity() { x = y = z = 0.0f; w = 1.0f; } /* Normalizing the Quaternion works very similarly to a Vector. It the Quaternion is close to the unit - length then this method will not do anything. TOLERANCE is the check to see if it is close enough to the unit - length*/ void Quaternion::Normalize() { // Magnitude of the Quaternion (size) float mag = (w*w) + (x*x) + (y*y) + (z*z); //Check if the value is close enough to the unit- length if(fabs(mag) > TOLERANCE && fabs(mag -1.f) > TOLERANCE) { //if not // square root the magnitude to obtain length(just like the vector method of normalizing) float length = sqrt(mag); // divide each component by the length w /= length; x /= length; y /= length; z /= length; } } // Returns the Quatornian with negative values. Quaternion Quaternion::Conjugate() const { Quaternion tmp(w, -x, -y, -z); return tmp; } Quaternion Quaternion::Inverse() const { float mag = sqrtf(w * w + x * x + y * y + z * z); float invMag = 1.0f / mag; return Conjugate() * invMag; } /* Converting a axis-angle representation to a quaternion. The formula for converting to quaternion from an rotation about and angle 'A' about axis(unit vector) V is q = cos(A/2) + V*sin(A/2) */ void Quaternion::ConvertAxisToQuat(const float angle, const Vec3& v) { // temp angle A / 2 float tempAngle = angle/2; // temp Vector Vec3 tempVec(v); // Unit-Vector if temp tempVec.Normalize(); // the sin(A/2) value float sinAngle = sin(tempAngle); // the V*sin(A/2) values for each component in a vector x = (tempVec.x * sinAngle); y = (tempVec.y * sinAngle); z = (tempVec.z * sinAngle); // the cos(A/2) value w = cos(tempAngle); //Normalize to make sure unit-quat is returned //Normalize(); } /* Convert from Eular angle (degrees) representation to Quaternions Basically we create 3 Quartenions, one for x(pitch), one for yaw(y) and one for z(roll) and multiply them together as (Q1 * Q2 * Q3) to obtain a single quaternion with the combined rotations. The calculation below does the same however it is shorter.*/ void Quaternion::ConvertEularToQuat(const float x, const float y, const float z) { // convert angles to radians then half them float halfx = (x*DEG2RAD) / 2.f; float halfy = (y*DEG2RAD) / 2.f; float halfz = (z*DEG2RAD) / 2.f; // obtain the cos values for each halfed value float cosX = cos(halfx); float cosY = cos(halfy); float cosZ = cos(halfz); // obtain the sin values for each halfed value float sinX = sin(halfx); float sinY = sin(halfy); float sinZ = sin(halfz); // do the shorter version of multiplying and obtaining a single quaternion // out of the 3 rotations. this->x = (sinZ * cosX * cosY) - (cosZ * sinX * sinY); this->y = (cosZ * sinX * cosY) + (sinZ * cosX * sinY); this->z = (cosZ * cosX * sinY) - (sinZ * sinX * cosY); this->w = (cosZ * cosX * cosY) + (sinZ * sinX * sinY); // Normalize the values Normalize(); } // Converting Euler Angles into Quaternion - Basically a Quaternion into a matrix or use a rotation matrix // from which extracting all the 3 axes you can obtain the new Quaternion void Quaternion::ConvertEularToQuat(const Matrix4& m, const float pitchDegrees, const float headingDegrees, const float rollDegrees) { // Construct a quaternion from an euler transformation. We do this rather // than use Quaternion::fromHeadPitchRoll() to support constraining heading // changes to the world Y axis. this->Identity(); Quaternion rotation = Quaternion::IDENTITY; Vec3 localXAxis(m[0][0], m[0][1], m[0][2]); Vec3 localYAxis(m[1][0], m[1][1], m[1][2]); Vec3 localZAxis(m[2][0], m[2][1], m[2][2]); if (headingDegrees != 0.0f) { // In order to allow free rotation in any direction have to use the local Y axis rather than a global one, where only rotations in one direction is allowed // so for ex if I roll 90 degrees and then want to rotate I am stil using the world Y axis rather than local, so it would seem tham I am looking up and down rather than // sideways. Se this below is the wrong one to use //rotation.ConvertAxisToQuat(headingDegrees * DEG2RAD,Vec3(0.0f, 1.0f, 0.0f)); rotation.ConvertAxisToQuat(headingDegrees * DEG2RAD, localYAxis); (*this) *= rotation; } if (pitchDegrees != 0.0f) { rotation.ConvertAxisToQuat(pitchDegrees * DEG2RAD, localXAxis); (*this) *= rotation; } if (rollDegrees != 0.0f) { rotation.ConvertAxisToQuat(rollDegrees * DEG2RAD, localZAxis); (*this) *= rotation; } } // Extract and obtain the three orientation axis by turning this quaternion into a matrix first void Quaternion::ExtractOrientationAxis(Vec3& right, Vec3& up, Vec3& forward) { Matrix4 m = this->SetMatrix(); right = Vec3(m[0][0], m[0][1], m[0][2]); right.Normalize(); up = Vec3(m[1][0], m[1][1], m[1][2]); up.Normalize(); forward = Vec3(-m[2][0], -m[2][1], -m[2][2]); forward.Normalize(); } /* Return the current values of the quaternion */ void Quaternion::GetValues(float &w, float &x, float &y, float &z) const { w = this->w; x = this->x; y = this->y; z = this->z; } /* Convert from quaternion to axis/angle representation To find angle of rotation its : w = cos(A/2) and for non-normalized rotation axis the vector is simply Qv from quaternion where q = (w, Qv) ~ Qv = (Qx, Qy, Qz)*/ void Quaternion::GetAxisAngle(float &angle, Vec3& v) const { // length of x y z of quaternion //float length = (float)sqrt(x*x + y*y + z*z); float sinHalfThetaSq = 1.f - (w* w); /* if scale is 0 then set angle to 0 and return vector(0, 0, 1) this is because is length is - that measn there is no rotation which will cause the ais to be infinite(BAD!) */ //if(length == 0.f) { if(sinHalfThetaSq <= 0.f) { angle = 0.0f; v.x = 1.0f; v.y = 0.0f; v.z = 0.0f; /* else angle = acos(w) * 2.f (opposite of w = cos(A/2)) and vector is each component of Qv / length to = each component of vector and at last normalize the vector. */ } else { // angle in radians angle = (float)acos(w) * 2.f; float length = 1.f/sqrt(sinHalfThetaSq); v.x = x * length;///length; v.y = y * length;///length; v.z = z * length;///length; //v.Normalize(); } } // Reference from Chapter 10 " Orientation and Angular Displacement in 3D" pg 176, // Book "3D Math Primer for Graphics and Game Development " , Fletcher Dunn and Ian Parberry void Quaternion::GetSlerpQuat(Quaternion &result, Quaternion q2, float t) { float cosOmega = this->w * q2.w + this->x * q2.x * this->y * q2.y + this->z * q2.z; if(cosOmega < 0.0f) { q2.w = -q2.w; q2.x = -q2.x; q2.y = -q2.y; q2.z = -q2.z; cosOmega = -cosOmega; } float k0, k1; if( cosOmega > 0.9999f){ k0 = 1.0f - t; k1 = t; } else { float sinOmega = sqrt(1.0f - cosOmega* cosOmega); float omega = atan2(sinOmega, cosOmega); float oneOverSingOmega = 1.0f / sinOmega; k0 = sin((1.0f - t)*omega)*oneOverSingOmega; k1 = sin(t * omega) * oneOverSingOmega; } result.w = this->w * k0 + q2.w * k1; result.x = this->x * k0 + q2.x * k1; result.y = this->y * k0 + q2.y * k1; result.z = this->z * k0 + q2.z * k1; } //////////////////////////////////////////////////////Matrix///////////////////////////////////////// void Quaternion::SetHeadPitchRoll(float headDegrees, float pitchDegrees, float rollDegrees) { Matrix4 m; m.SetEularAngles(headDegrees, pitchDegrees, rollDegrees); GetMatrix(m); } void Quaternion::GetHeadPitchRoll(float &headDegrees, float &pitchDegrees, float &rollDegrees) const { Matrix4 m = SetMatrix(); m.GetEularAngles(headDegrees, pitchDegrees, rollDegrees); } /*Creates a quaternion from a rotation matrix. The algorithm used is from Allan and Mark Watt's "Advanced Animation and Rendering Techniques" (ACM Press 1992). */ void Quaternion::GetMatrix(const Matrix4 &m) { float s = 0.0f; float q[4] = {0.0f}; float trace = m[0][0] + m[1][1] + m[2][2]; if (trace > 0.0f) { s = sqrtf(trace + 1.0f); q[3] = s * 0.5f; s = 0.5f / s; q[0] = (m[1][2] - m[2][1]) * s; q[1] = (m[2][0] - m[0][2]) * s; q[2] = (m[0][1] - m[1][0]) * s; } else { int nxt[3] = {1, 2, 0}; int i = 0, j = 0, k = 0; if (m[1][1] > m[0][0]) i = 1; if (m[2][2] > m[i][i]) i = 2; j = nxt[i]; k = nxt[j]; s = sqrtf((m[i][i] - (m[j][j] + m[k][k])) + 1.0f); q[i] = s * 0.5f; s = 0.5f / s; q[3] = (m[j][k] - m[k][j]) * s; q[j] = (m[i][j] + m[j][i]) * s; q[k] = (m[i][k] + m[k][i]) * s; } x = q[0], y = q[1], z = q[2], w = q[3]; } /* Converts this quaternion to a rotation matrix. | 1 - 2(y^2 + z^2) 2(xy + wz) 2(xz - wy) 0 | | 2(xy - wz) 1 - 2(x^2 + z^2) 2(yz + wx) 0 | | 2(xz + wy) 2(yz - wx) 1 - 2(x^2 + y^2) 0 | | 0 0 0 1 | */ Matrix4 Quaternion::SetMatrix() const { float x2 = x + x; float y2 = y + y; float z2 = z + z; float xx = x * x2; float xy = x * y2; float xz = x * z2; float yy = y * y2; float yz = y * z2; float zz = z * z2; float wx = w * x2; float wy = w * y2; float wz = w * z2; Matrix4 m; m[0][0] = 1.0f - (yy + zz); m[0][1] = xy + wz; m[0][2] = xz - wy; m[0][3] = 0.0f; m[1][0] = xy - wz; m[1][1] = 1.0f - (xx + zz); m[1][2] = yz + wx; m[1][3] = 0.0f; m[2][0] = xz + wy; m[2][1] = yz - wx; m[2][2] = 1.0f - (xx + yy); m[2][3] = 0.0f; m[3][0] = 0.0f; m[3][1] = 0.0f; m[3][2] = 0.0f; m[3][3] = 1.0f; return m; } //////////////////////////////////////////////////////operators////////////////////////////////////// Quaternion operator*(float lhs, const Quaternion &rhs) { return rhs * lhs; } bool Quaternion::operator==(const Quaternion &rhs) const { return closeEnough(w, rhs.w) && closeEnough(x, rhs.x) && closeEnough(y, rhs.y) && closeEnough(z, rhs.z); } bool Quaternion::operator!=(const Quaternion &rhs) const { return !(*this == rhs); } Quaternion Quaternion::operator*(const Quaternion &rhs) const { Quaternion tmp(*this); tmp *= rhs; return tmp; } Quaternion &Quaternion::operator+=(const Quaternion &rhs) { w += rhs.w, x += rhs.x, y += rhs.y, z += rhs.z; return *this; } Quaternion &Quaternion::operator-=(const Quaternion &rhs) { w -= rhs.w, x -= rhs.x, y -= rhs.y, z -= rhs.z; return *this; } Quaternion &Quaternion::operator*=(const Quaternion &rhs) { // Multiply so that rotations are applied in a left to right order. Quaternion tmp( (w * rhs.w) - (x * rhs.x) - (y * rhs.y) - (z * rhs.z), (w * rhs.x) + (x * rhs.w) - (y * rhs.z) + (z * rhs.y), (w * rhs.y) + (x * rhs.z) + (y * rhs.w) - (z * rhs.x), (w * rhs.z) - (x * rhs.y) + (y * rhs.x) + (z * rhs.w)); /*// Multiply so that rotations are applied in a right to left order. Quaternion tmp( (w * rhs.w) - (x * rhs.x) - (y * rhs.y) - (z * rhs.z), (w * rhs.x) + (x * rhs.w) + (y * rhs.z) - (z * rhs.y), (w * rhs.y) - (x * rhs.z) + (y * rhs.w) + (z * rhs.x), (w * rhs.z) + (x * rhs.y) - (y * rhs.x) + (z * rhs.w)); */ *this = tmp; return *this; } Quaternion &Quaternion::operator*=(float scalar) { w *= scalar, x *= scalar, y *= scalar, z *= scalar; return *this; } Quaternion &Quaternion::operator/=(float scalar) { w /= scalar, x /= scalar, y /= scalar, z /= scalar; return *this; } Quaternion Quaternion::operator+(const Quaternion &rhs) const { Quaternion tmp(*this); tmp += rhs; return tmp; } Quaternion Quaternion::operator-(const Quaternion &rhs) const { Quaternion tmp(*this); tmp -= rhs; return tmp; } Quaternion Quaternion::operator*(float scalar) const { Quaternion tmp(*this); tmp *= scalar; return tmp; } Quaternion Quaternion::operator/(float scalar) const { Quaternion tmp(*this); tmp /= scalar; return tmp; } Vec3 Quaternion::operator* (const Vec3 &vec) const { Vec3 vn(vec); vn.Normalize(); Quaternion vecQuat, resQuat; vecQuat.x = vn.x; vecQuat.y = vn.y; vecQuat.z = vn.z; vecQuat.w = 0.0f; resQuat = vecQuat * Conjugate(); resQuat = *this * resQuat; return (Vec3(resQuat.x, resQuat.y, resQuat.z)); }
true
d7897f686b13cc30f04cc4feb53871bfedb048dc
C++
randevlper/Memory
/Memory/05-File IO/main.cpp
UTF-8
3,248
3.15625
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <random> #include <chrono> void closed(); void open(); int printFile(std::string file); bool isRunning = true; int main() { srand(time(0)); //closed(); open(); //ask if they want another file system("pause"); return 0; } void closed() { //Ask for input //enter input "file.txt" //call printFile std::string fileName; std::cout << "Is there a file you would like to read? \n\n" << "> "; std::cin >> fileName; printf("\n"); printFile(fileName); while (isRunning) { std::cout << "\nIs there another file you would like to read? \n\n" << "> "; std::cin >> fileName; printf("\n"); printFile(fileName); } isRunning = true; std::cout << "Enter a filename to save some info. \n\n" << "> "; std::cin >> fileName; std::fstream file; if (!fileName.compare("no")) { isRunning = false; } else { file.open(fileName, std::ios_base::out); } while (isRunning) { std::cout << "What other info? \n\n" << "> "; std::cin >> fileName; if (!fileName.compare("no")) { isRunning = false; break; } file << fileName << std::endl; } } int printFile(std::string fileName) { std::fstream file; if (!fileName.compare("no")) { isRunning = false; return 1; } file.open(fileName); if (file.fail()) { std::cout << "File not found" << std::endl;; return -1; } //Print file here std::cout << fileName << std::endl << "---------------------" << std::endl; std::string buffer; while ( getline(file, buffer) ) { std::cout << buffer << std::endl; } file.close(); return 0; } bool didProc(int prob) { if ((rand() % 100 + 1) <= prob) { return true; } return false; } int printGarbledFile(std::string fileName); int printCommaFile(std::string fileName); void open() { //printGarbledFile("importantMessage.txt"); printCommaFile("commaSep.txt"); printCommaFile("commaSepDos.txt"); } int printGarbledFile(std::string fileName) { std::fstream file; if (!fileName.compare("no")) { isRunning = false; return 1; } file.open(fileName); if (file.fail()) { std::cout << "File not found" << std::endl;; return -1; } //Print file here std::cout << fileName << std::endl << "---------------------" << std::endl; std::string buffer; while (getline(file, buffer)) { for (int i = 0; i < buffer.size(); i++) { if (didProc(20)) { buffer.at(i) = 219; } } std::cout << buffer << std::endl; } file.close(); } int printCommaFile(std::string fileName) { std::fstream file; if (!fileName.compare("no")) { isRunning = false; return 1; } file.open(fileName); if (file.fail()) { std::cout << "File not found" << std::endl;; return -1; } //Print file here std::cout << fileName << std::endl << "---------------------" << std::endl; int startIndex = 1; std::string output; std::string buffer; while (getline(file, buffer)) { for (int i = 0; i < buffer.size(); ++i) { switch (buffer.at(i)) { case '{': break; case '}': std::cout << output << std::endl; break; case ' ': break; case ',': std::cout << output << std::endl; output = ""; break; default: output += buffer.at(i); break; } } } }
true
db2535c68ae6ab486fd343847750e3f3fb9b92a5
C++
Ohohcakester/Simplex
/fraction.h
UTF-8
1,239
2.890625
3
[]
no_license
#ifndef FRACTION_H #define FRACTION_H #include <string> using namespace std; struct Fraction { int n, d; Fraction(); Fraction(int n, int d); Fraction(int n); Fraction (const Fraction &o); void init(int n, int d); int gcd(int a, int b); float toFloat(); string toString(); Fraction& operator*=(const Fraction &o); Fraction& operator/=(const Fraction &o); Fraction& operator+=(const Fraction &o); Fraction& operator-=(const Fraction &o); bool operator==(const Fraction &o) const; bool operator!=(const Fraction &o) const; bool operator<(const Fraction &o) const; bool operator>(const Fraction &o) const; bool operator<=(const Fraction &o) const; bool operator>=(const Fraction &o) const; bool isPositive(); bool isNegative(); bool isZero(); bool isInvalid(); }; Fraction operator*(const Fraction& o, const Fraction& o2); Fraction operator/(const Fraction& o, const Fraction& o2); Fraction operator+(const Fraction& o, const Fraction& o2); Fraction operator-(const Fraction& o, const Fraction& o2); ostream& operator<< (ostream& stream, Fraction& obj); Fraction parseFraction(string s); #endif
true
eb1b645f8594064c140ba99a612fd00af8dda175
C++
ailyanlu1/Programming-Challenges
/leetcode/Combination Sum II.cpp
UTF-8
1,087
2.921875
3
[]
no_license
class Solution { public: vector<vector<int> > combinationSum2(vector<int> &num, int target) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<int> cur_ans; vector< vector<int> > result; set< vector<int> > visited; sort( num.begin(), num.end() ); dfs( target, 0, visited,cur_ans, result, num ); return result; } void dfs( int target, int choose, set< vector<int> > &visited, vector<int>& cur_ans, vector< vector<int> >&result, vector<int> &num ){ if( target==0 ){ if( visited.find(cur_ans)!=visited.end() ) return; visited.insert(cur_ans); result.push_back(cur_ans); return; } if( target < 0 ){ return; } for( int i = choose; i < num.size(); ++i ){ if( target-num[i] >= 0 ){ cur_ans.push_back(num[i]); dfs( target-num[i], i+1, visited, cur_ans, result, num ); cur_ans.pop_back(); } } } };
true
730390fcb5480d7fa10e4d2f57139d55c27b836b
C++
duonghau/abncounting
/cpp/AlignmentRecord.cpp
UTF-8
5,467
2.609375
3
[]
no_license
#include "AlignmentRecord.h" using namespace std; // isdigit() AlignmentRecord::AlignmentRecord(){}; AlignmentRecord::~AlignmentRecord(){}; AlignmentRecord::AlignmentRecord(const string & record_raw, bool lite){ std::vector<string> tokens=stringSplit(record_raw); qname=tokens[0]; flag=atoi(tokens[1].c_str()); rname=tokens[2]; pos=atoi(tokens[3].c_str()); cigar=tokens[5]; end=pos+getMLength();//calculate mapped length if(lite==false){ mapq=atoi(tokens[4].c_str()); rnext=tokens[6]; pnext=atoi(tokens[7].c_str()); tlen=atoi(tokens[8].c_str()); seq=tokens[9]; qual=tokens[10]; } for(int i=11; i<tokens.size();i++){ string tmp=tokens[i]; if(tmp!=""){ tags[tmp.substr(0,2)]=tmp; } } } string AlignmentRecord::getQname(void) const{ return qname; } int AlignmentRecord::getFlag(void) const{ return flag; } string AlignmentRecord::getRname(void) const{ return rname; } int AlignmentRecord::getPos(void) const{ return pos; } int AlignmentRecord::getMapq(void) const{ return mapq; } string AlignmentRecord::getCigar(void) const{ return cigar; } string AlignmentRecord::getRnext(void) const{ return rnext; } int AlignmentRecord::getPnext(void) const{ return pnext; } int AlignmentRecord::getTlen(void) const{ return tlen; } string AlignmentRecord::getSeq(void) const{ return seq; } string AlignmentRecord::getQual(void) const{ return qual; } // AS,XN, XM, XO, XG, NM, YS int AlignmentRecord::getNumericTag(const string & tag) const{ if (!(tag=="AS" || tag=="XN"||tag=="XM"||tag=="XO" ||tag=="XG"||tag=="NM"||tag=="YS")){ return -1; //invalid tag } if ( tags.find(tag) == tags.end() ) { return -1;//not found }else { map<string,string>mytags=tags; vector<string> tokens=stringSplit(mytags[tag],':'); if(tokens.size()>0){ return atoi(tokens[2].c_str()); }else{ return -1; } } } // for all obtional tags string AlignmentRecord::getStringTag(const string & tag) const{ map<string,string>mytags=tags; vector<string> tokens=stringSplit(mytags[tag],':'); if(tokens.size()>0){ return tokens[2].c_str(); }else{ return ""; } } bool AlignmentRecord::isPaired(void) const{ return (flag & SAM_FPAIRED); } bool AlignmentRecord::isMapped(void) const{ return !(flag & SAM_FUNMAP); } bool AlignmentRecord::isSecondary(void) const{ return (flag & SAM_FSECONDARY); } bool AlignmentRecord::isReverse(void) const{ return (flag & SAM_FREVERSE); } bool AlignmentRecord::isDuplicate(void) const{ return (flag & SAM_FDUP); } bool AlignmentRecord::isRead1(void) const{ return (flag & SAM_FREAD1); } bool AlignmentRecord::isRead2(void) const{ return (flag & SAM_FREAD2); } int AlignmentRecord::getStart(void) const{ return pos; } int AlignmentRecord::getEnd(void) const{ return end; } int AlignmentRecord::getMLength(){ // mapped length is count from CIGAR chars [MX=] // all other CIGAR chars do not affect end position string regex_string = "([[:digit:]]+)[MX]"; if(cigar==""){ return 0; }else{ // user regular expression for calculate the mapped length int length=0; // boost::regex expr{regex_string}; // string::const_iterator begin = cigar.begin(); // string::const_iterator end = cigar.end(); // boost::match_results<string::const_iterator> matchs; // while (regex_search(begin, end, matchs, expr)) { // string match= string(matchs[1].first, matchs[2].second-1); // length+=atoi(match.c_str()); // begin = matchs[0].second; // } boost::regex expr{regex_string}; string::const_iterator begin = cigar.begin(); string::const_iterator end = cigar.end(); boost::match_results<string::const_iterator> matchs; while (regex_search(begin, end, matchs, expr)) { string match= string(matchs[1].first, matchs[2].second-1); length+=atoi(match.c_str()); begin = matchs[0].second; } return length; } } int AlignmentRecord::getMappedLength(void) const{ return (end-pos); } bool AlignmentRecord::isValid(const int & minLength) const{ return ((getEnd()-getStart()) > 0) && (getMappedLength()>minLength); } // identity= match/(maped length)= (M-XM)/M float AlignmentRecord::getIdentity(void) const{ int mappedLength=getMappedLength(); return ((float)(mappedLength-getNumericTag("XM"))/mappedLength); } std::vector<string> AlignmentRecord::stringSplit(const string & record, char split) const{ vector<string> tokens; istringstream iss(record); string token; while(getline(iss, token, split)){ tokens.push_back(token); } return tokens; } int AlignmentRecord::getStrand(void) const{ if(isRead1()){ return 1; }else{ return 2; } } void AlignmentRecord::setStart(const int & start){ this->pos=start; } void AlignmentRecord::setEnd(const int & end){ this->end=end; } bool AlignmentRecord::isKeep(void) const{ return keep; } void AlignmentRecord::unKeep(void){ keep=false; } string AlignmentRecord::toString(void) const{ stringstream ss; ss<<qname<<"_"<<getStrand()<<" "<<rname<<" "<<pos<<" "<<end; return ss.str(); }
true
4ce49acb886beba68d63b92146d55735e4a0a1a4
C++
henrywoo/ultraie
/client/uutoolbar/src/lib/6beebase/guard.h
UTF-8
1,938
2.53125
3
[]
no_license
// UltraIE - Yet Another IE Add-on // Copyright (C) 2006-2010 // Simon Wu Fuheng (simonwoo2000 AT gmail.com), Singapore // Homepage: http://www.linkedin.com/in/simonwoo // // 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 3 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, see <http://www.gnu.org/licenses/>. #ifndef __UULOGGING_GUARD__ #define __UULOGGING_GUARD__ #include "basictypes.h" #include <windows.h>//CRITICAL_SECTION /// Multithreaded Synchronization /// Implemented using CRITICAL_SECTION for speed (see MS Doc) class cmutex { public: cmutex(){ InitializeCriticalSection (&m_cs); } ~cmutex(){ DeleteCriticalSection (&m_cs); } void acquire(){ EnterCriticalSection (&m_cs); } void release(){ LeaveCriticalSection(&m_cs); } private: /// MS Doc states that CRITICAL_SECTION should not be copied DISALLOW_COPY_AND_ASSIGN(cmutex); CRITICAL_SECTION m_cs; }; /// Guard for Multithreaded Synchronization objects /// Ensure that resource is locked/unlocked regardless of exit path class cguard { public: /// @param l - reference the lock to use explicit cguard(cmutex& m) : m_cs(m){ acquire(); } ~cguard(){ release(); } void acquire(){ m_cs.acquire(); } void release(void){ m_cs.release(); } private: DISALLOW_IMPLICIT_CONSTRUCTORS(cguard); cmutex& m_cs; }; #endif
true
64edf588438fc192c9ce04210b1a992533b55519
C++
shivral/cf
/0300/80/381a.cpp
UTF-8
772
3.375
3
[ "Unlicense" ]
permissive
#include <iostream> #include <vector> template <typename T> std::istream& operator >>(std::istream& input, std::vector<T>& v) { for (T& a : v) input >> a; return input; } void answer(unsigned x, unsigned y) { std::cout << x << ' ' << y << '\n'; } void solve(const std::vector<unsigned>& a) { const size_t n = a.size(); unsigned sums[2] = {}; for (int left = 0, right = n - 1, index = 0; left <= right; ) { if (a[left] > a[right]) { sums[index] += a[left++]; } else { sums[index] += a[right--]; } index ^= 1; } answer(sums[0], sums[1]); } int main() { size_t n; std::cin >> n; std::vector<unsigned> a(n); std::cin >> a; solve(a); return 0; }
true
d3b0dc6ee9e775dff4c8356462edd34941d37828
C++
jcrowe6/wiki_graph
/Vertex.h
UTF-8
592
2.859375
3
[]
no_license
#pragma once #include <vector> #include <string> #include <iostream> #include <vector> #include <list> class Vertex { public: std::list<int> categories; // categories the article is in (yes there are multiple apparently) std::string name; // article name int id; std::list<int> neighbors; // stores all adjacent vertices of that vertex std::list<int> in_neighbors; // stores all verticies that point INTO this node bool visited; Vertex(); Vertex(std::string n, int gid); bool operator==(const Vertex& v) const; };
true
851046f30766f2e855ac6d992ad2672c75557c5c
C++
txfyxzzy/dev
/c/zlib/test.cc
UTF-8
900
3.15625
3
[]
no_license
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <zlib.h> int main(int argc, char* argv[]) { char text[] = "zlib compress and uncompress test\nturingo@163.com\n2012-11-05\n"; uLong tlen = strlen(text) + 1; /* 需要把字符串的结束符'\0'也一并处理 */ char* buf = NULL; uLong blen; /* 计算缓冲区大小,并为其分配内存 */ blen = compressBound(tlen); /* 压缩后的长度是不会超过blen的 */ if((buf = (char*)malloc(sizeof(char) * blen)) == NULL) { printf("no enough memory!\n"); return -1; } /* 压缩 */ if(compress(buf, &blen, text, tlen) != Z_OK) { printf("compress failed!\n"); return -1; } /* 解压缩 */ if(uncompress(text, &tlen, buf, blen) != Z_OK) { printf("uncompress failed!\n"); return -1; } /* 打印结果,并释放内存 */ printf("%s", text); if(buf != NULL) { free(buf); buf = NULL; } return 0; }
true
d6a8f42c6840c2d6ca8b5674c38713fb0bfffd74
C++
Intiser/ProblemSolvingAndContest
/UvaOnlineJudge/12917.cpp
UTF-8
249
2.578125
3
[]
no_license
#include<iostream> #include<stdio.h> using namespace std; int main(){ int p,n,o; while(cin>>p>>n>>o){ if(n>(o-p)){ printf("Hunters win!\n"); } else{ printf("Props win!\n"); } } }
true
33a9ac0f0ea1ed2d6a352c41e6346abc6289189d
C++
luyiming112233/PatCodeRepo
/PatCodeRepo/PatAdv/A1014.cpp
GB18030
1,479
2.71875
3
[]
no_license
#include<cstdio> #include<queue> using namespace std; #define maxn 1010 int N, M, K, Q, a[maxn] = { 0 }; struct wait_queue { int time; queue<int> q; }wqs[20]; int time2num(int hh, int mm) { return hh * 60 + mm; } void print_time(int num,int num2) { if (num >= 1020) { printf("Sorry\n"); } else { int hh, mm; hh = (num+num2) / 60; mm = (num+num2) % 60; printf("%02d:%02d\n", hh, mm); } } //ķǿմ int get_quick_window() { int min = -1,mintime=10000000; for (int i = 0; i < N; i++) { if (!wqs[i].q.empty() && wqs[i].time+a[wqs[i].q.front()] < mintime) { min = i; mintime = wqs[i].time+ a[wqs[i].q.front()]; } } return min; } int main(){ int b[maxn] = { 0 },wait,win,cus,query; scanf("%d%d%d%d", &N, &M, &K, &Q); for (int i = 1; i <= K; i++) { scanf("%d", &a[i]); } if (N*M >= K) { wait = K + 1; } else { wait = N * M + 1; } //ʼʱ for (int i = 0; i < 20; i++) { wqs[i].time = time2num(8, 0); } //ʼ for (int i = 1; i < wait; i++) { wqs[(i-1)%N].q.push(i); } //ִҵ for (int i = 1; i <= K; i++) { win = get_quick_window(); if (win == -1) break; cus = wqs[win].q.front(); wqs[win].q.pop(); b[cus] = wqs[win].time; wqs[win].time = wqs[win].time + a[cus]; //һcus if (wait <= K) { wqs[win].q.push(wait); wait++; } } for (int i = 0; i < Q; i++) { scanf("%d", &query); print_time(b[query],a[query]); } return 0; }
true
cc0388863b8f967b6df896296ceacbb6eb6e1b65
C++
Irwin1985/cppmonkey
/main/environment.hpp
UTF-8
509
2.84375
3
[ "Apache-2.0" ]
permissive
#if !defined(ENVIRONMENT_H) #define ENVIRONMENT_H #include <string> #include <memory> #include <unordered_map> #include "object.hpp" class Environment { public: Environment(): store{} {}; Environment(std::shared_ptr<Environment> outer): store{}, parent{outer} {}; virtual ~Environment() = default; Object set(std::string, Object); Object get(std::string); private: std::unordered_map<std::string, Object> store; std::shared_ptr<Environment> parent; }; #endif // ENVIRONMENT_H
true
e543528f6786e60c078b586e9db1f164fe2487d1
C++
adityaemaulana/cp-training
/UVA/Graph/1103 - Ancient Messages.cpp
UTF-8
3,068
3.015625
3
[]
no_license
#include <vector> #include <iostream> #include <string> #include <algorithm> using namespace std; typedef vector<char> vc; vector<vc> grid; vc hieroglyph{'W', 'A', 'K', 'J', 'S', 'D'}; vector<string> hextobin{"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110", "1111"}; vector<int> x{1, 0, -1, 0}, y{0, -1, 0, 1}; void fill(int i , int j, int r, int c, char ch){ if(i < 0 || i == r || j == c || j < 0) return; if(grid[i][j] != ch) return; grid[i][j] = '.'; for(size_t p = 0; p < x.size(); p++){ fill(i + x[p], j + y[p], r, c, ch); } } void fillBackground(int r, int c){ for(int i = 0; i < r; i++){ for(int j = 0; j < c; j++){ if(i == 0 || i == r-1 || j == 0 || j == c-1){ fill(i, j, r, c, '0'); } } } } bool searchHieroglyph(int r, int c, pair<int, int>& pos){ bool found = false; int i, j; for(i = 0 ; i < r; i++){ if(found) break; for(j = 0; j < c; j++){ if(grid[i][j] == '1'){ pos = make_pair(i, j); found = true; break; } } } return found; } int main(){ int col, row, cases = 0; char ch; while(cin >> row >> col){ cases++; if(!col && !row) break; grid.clear(); grid.assign(row, vc()); // Input for(int i = 0; i < row; i++){ for(int j = 0 ; j < col; j++){ cin >> ch; string val = isalpha(ch) ? hextobin[10+(ch-97)] : hextobin[ch-48]; for(auto &x : val){ grid[i].push_back(x); } } } // Size of column increased because hex to binary conversion col *= 4; // Fill background for differintiating hieroglyph and background fillBackground(row, col); pair<int, int> hgPos; vc result; while(searchHieroglyph(row, col, hgPos) == true){ int i = hgPos.first, j = hgPos.second; // Fill Hieroglpyh Outline fill(i, j, row, col, '1'); // Count Hieroglyph's holes int count = 0; for(i = 0; i < row; i++){ for(j = 0; j < col; j++){ if(grid[i][j] == '0' && i > 0 && i < row-1 && j > 0 && j < col-1){ if(grid[i-1][j] == '.' || grid[i+1][j] == '.' || grid[i][j-1] == '.' || grid[i][j+1] == '.'){ count++; fill(i, j, row, col, '0'); } } } } result.push_back(hieroglyph[count]); } sort(result.begin(), result.end()); string stringresult(result.begin(), result.end()); cout << "Case " << cases << ": " << stringresult << endl; } }
true
6858807e2817d1b955fc26736ba293b2434f7583
C++
onesmash/WukongBase
/base/thread/Thread.cpp
UTF-8
2,080
2.578125
3
[]
no_license
// // Thread.cpp // AppCore // // Created by Xuhui on 15/5/10. // Copyright (c) 2015年 Xuhui. All rights reserved. // #include "base/thread/Thread.h" #include "base/message_loop//Time.h" #include "base/message_loop/MessageLoop.h" namespace WukongBase { namespace Base { static uv_key_t threadLocalStorageKey; Thread::Thread(const std::string& name): name_(name), thread_(nullptr), messageLoop_(nullptr), started_(false), mutex_(), cv_() { } Thread::~Thread() { if(thread_ != nullptr && thread_->joinable()) { stop(); thread_->join(); } } bool Thread::start() { thread_ = std::shared_ptr<std::thread>(new std::thread(&Thread::threadMain, this)); std::unique_lock<std::mutex> lock(mutex_); cv_.wait(lock); started_ = true; return true; } void Thread::stop() { if(!started_ && !messageLoop_) return; if(messageLoop_->running()) { messageLoop_->postTask(std::bind(&Thread::stopMessageLoop, this)); } started_ = false; } void Thread::join() { thread_->join(); } void Thread::stopMessageLoop() { messageLoop_->quite(); } void Thread::threadMain() { messageLoop_ = new MessageLoop(); messageLoop_->attachToCurrentThread(); uv_key_create(&threadLocalStorageKey); std::unordered_map<std::string, std::shared_ptr<void>>* storage = new std::unordered_map<std::string, std::shared_ptr<void>>(); uv_key_set(&threadLocalStorageKey, storage); cv_.notify_one(); messageLoop_->run(); } void Thread::sleep(double seconds) { std::this_thread::sleep_for(std::chrono::microseconds((long long)(seconds * kMicroSecondsPerSecond))); } std::unordered_map<std::string, std::shared_ptr<void>>* Thread::getThreadLocalStorage() { std::unordered_map<std::string, std::shared_ptr<void>>* storage = nullptr; if(threadLocalStorageKey > 0) { storage = (std::unordered_map<std::string, std::shared_ptr<void>>*)uv_key_get(&threadLocalStorageKey); } return storage; } } }
true
1ad3411eec8bd036e52a074e0a8a48d7b1723646
C++
floura-angel/onemoredb-1
/BigQ.cc
UTF-8
4,474
2.828125
3
[]
no_license
#include <climits> #include <unistd.h> #include <cstring> #include "BigQ.h" using namespace std; char tempFilePath[PATH_MAX]; BigQ::BigQ(Pipe &in, Pipe &out, OrderMaker &orderMaker, int runlen1) { inPipe = &in; outPipe = &out; runlen = runlen1; maker = &orderMaker; pthread_create(&worker_thread, NULL, workerThread, (void *) this); } BigQ::BigQ(){ } BigQ::~BigQ() { } void BigQ::phaseOne() { Record tempRecord; Compare comparator = Compare(*maker); const long maxSize = PAGE_SIZE * runlen; long curSize = 0; vector<Record *> recordList; Page page; int page_index=0; while (inPipe->Remove(&tempRecord)) { Record *record = new Record(); record->Copy(&tempRecord); // curSize += record->GetLength(); if(!page.Append(&tempRecord)){ if (++page_index == runlen){ sort(recordList.begin(), recordList.end(), comparator); dumpSortedList(recordList); page_index=0; } page.EmptyItOut(); page.Append(&tempRecord); } // if (curSize >= maxSize) { // curSize = 0; // sort(recordList.begin(), recordList.end(), comparator); // dumpSortedList(recordList); // } recordList.emplace_back(record); } // cout<<"Current Record Size: "<<curSize<<endl; if (recordList.empty()) { outPipe->ShutDown(); file.Close(); pthread_exit(NULL); } sort(recordList.begin(), recordList.end(), comparator); // cout<<"RecordList: "<<recordList.size()<<endl; dumpSortedList(recordList); // cout<<"Sucess of Dumping Sorted List"<<endl; } void BigQ::phaseTwo() { // cout <<"phase2: " << blockNum <<endl; vector<Page> tempPage(blockNum); priority_queue<IndexedRecord *, vector<IndexedRecord *>, IndexedRecordCompare> priorityQueue(*maker); for (int i = 0; i < blockNum; i++) { file.GetPage(&tempPage[i], blockStartOffset[i]++); IndexedRecord *indexedRecord = new IndexedRecord(); indexedRecord->blockIndex = i; tempPage[i].GetFirst(&(indexedRecord->record)); priorityQueue.emplace(indexedRecord); } while (!priorityQueue.empty()) { IndexedRecord *indexedRecord = priorityQueue.top(); priorityQueue.pop(); int blockIndex = indexedRecord->blockIndex; outPipe->Insert(&(indexedRecord->record)); if (tempPage[blockIndex].GetFirst(&(indexedRecord->record))) { priorityQueue.emplace(indexedRecord); } else if (blockStartOffset[blockIndex] < blockEndOffset[blockIndex]) { file.GetPage(&tempPage[blockIndex], blockStartOffset[blockIndex]++); tempPage[blockIndex].GetFirst(&(indexedRecord->record)); priorityQueue.emplace(indexedRecord); } else { delete indexedRecord; } } } void BigQ::dumpSortedList(vector<Record *> &recordList) { Page outPage; blockStartOffset.push_back(file.GetLength() - 1); for (auto rec : recordList) { if (!outPage.Append(rec)) { file.AddPage(&outPage, file.GetLength() - 1); outPage.EmptyItOut(); outPage.Append(rec); delete rec; rec = NULL; } } file.AddPage(&outPage, file.GetLength() - 1); blockEndOffset.push_back(file.GetLength() - 1); ++blockNum; recordList.clear(); } void *BigQ::workerThread(void *arg) { BigQ *bigQ = (BigQ *) arg; bigQ->init(); bigQ->phaseOne(); // clog << "bigq: phase-1 completed.." << endl; bigQ->phaseTwo(); // clog << "bigq: phase-2 completed.." << endl; bigQ->close(); remove(tempFilePath); pthread_exit(NULL); } void BigQ::init() { if (getcwd(tempFilePath, sizeof(tempFilePath)) != NULL) { strcat(tempFilePath, "/temp/tmp"); strcat(tempFilePath, getRandStr(10).c_str()); } else { cerr << "error while getting curent dir" << endl; exit(-1); } file.Open(0, tempFilePath); file.AddPage(new Page(), -1); } void BigQ::close() { outPipe->ShutDown(); file.Close(); } string BigQ::getRandStr(int len) { static string charset = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; string result; result.resize(len); for (int i = 0; i < len; i++) { result[i] = charset[rand() % charset.length()]; } return result; }
true
27e6eff09ba514a975d43c6c9311941bcf09ebb2
C++
tc-imba/VE475
/challenges/c2/cipher2/byte.cpp
UTF-8
1,333
3
3
[]
no_license
// // Created by liu on 17-7-3. // #include "byte.h" #include <iostream> #include <ctime> using namespace std; std::vector<uint8_t> byte_encode(const std::string &str) { vector<uint8_t> bytes; for (int i = 0; i < str.length(); i++) { bytes.push_back(alphabet_rev[str[i]]); } // for (auto &it:bytes) // cout << int(it) << "\t"; // cout << endl; return bytes; } std::string byte_decode(const std::vector<uint8_t> &bytes) { string str; for (int i = 0; i < bytes.size(); i++) { str.push_back(alphabet[bytes[i] % alphabet_size]); } // cout << str << endl; return str; } std::vector<uint8_t> byte_encode_double(const std::string &str) { vector<uint8_t> bytes; for (int i = 0; i < str.length(); i += 2) { bytes.push_back(alphabet_rev[str[i]] % 4 * alphabet_size + alphabet_rev[str[i + 1]]); } // for (auto &it:bytes) // cout << int(it) << "\t"; // cout << endl; return bytes; } std::string byte_decode_double(const std::vector<uint8_t> &bytes) { srand(time(0)); string str; for (int i = 0; i < bytes.size(); i++) { str.push_back(alphabet[bytes[i] / alphabet_size + 4 * (rand() % 16)]); str.push_back(alphabet[bytes[i] % alphabet_size]); } //cout << str << endl; return str; }
true
f78a1e4d3eb18d139b4b849fe0e249c57b494c82
C++
Leocodefocus/project
/Cplusplus/Chapter_3/BagInterface.h
UTF-8
1,947
3.625
4
[]
no_license
#ifndef _BAG_INTERFACE #define _BAG_INTERFACE #include <vector> using namespace std; template<class ItemType> class BagInterface { public: /** Gets the current number of entries in this bag. @return The integer number of entries currently in the bag */ virtual int getCurrentSize() const=0; /**Adds a new entry to this bag. @post If successful,newEntry is stored in the bag and the count of items in the bag has increased by 1. @param newEntry The project to be added as a new entry. @return True if addition was successful,or false if not. Set the method which do not change object to const */ virtual bool add(const ItemType& newEntry) =0; /**See whether this bag is empty. @return True if the bag is empty,or false if not. */ virtual bool isEmpty() const=0; /**Remove one occurrence of a given entry from this bag,if possible. @post If successful,anEntry has been removed from the bag and the count of items in the bag has decreased by 1. @param anEntry the entry to be removed @return True if removal was successful,or false if not Set the unchangeable param to const var */ virtual bool remove(const ItemType& anEntry) = 0; /** Removes all entries from this bag. @post Bag contains no items,and the count of items is 0. */ virtual void clear() = 0; /** Counts the number of times a given entry appears in bag. @param anEntry The entry to be counted. @return The number of times anEntry appears in the bag. */ virtual int getFrequencyOf(const ItemType& anEntry) const = 0; /** Tests whether this bag contains a given entry. @param anEntry The entry to locate. @return True if bag contains anEntry, or false otherwise. */ virtual bool contains(const ItemType& anEntry) const = 0; /** Empties and then fills a given vector with all entries that are in this bag. @return A vector containing all the entries in the bag. */ virtual vector<ItemType> toVector() const = 0; };//end Interface
true
25a0b1eeb7c196b423ce525a0584b9aefd7ef956
C++
quantumhara/cpp_ex
/cp0058.cpp
UTF-8
342
2.890625
3
[]
no_license
#include <iostream> using namespace std; void sub(); int g = 100; int main() { int a = 200; cout << "g=" << g << '\n'; cout << "a=" << a << '\n'; sub(); return 0; } void sub() { int b = 300; cout << "g=" << g << '\n'; cout << "a is not defined in this function" << '\n'; cout << "b=" << b << '\n'; }
true
9e57b12b44eb14afca02d32434c9fcc95e88338c
C++
liwei86521/c_plus_base_pro
/15_extend_3.cpp
UTF-8
1,660
3.546875
4
[]
no_license
#include <iostream> #include <cstring> #include <stdio.h> /* 谈谈你对重写,重载理解 函数重载 Overload: 必须在同一个类中进行 在一个类中,同名的方法如果有不同的参数列表(参数类型不同、参数个数不同甚至是参数顺序不同)则视为重载 重载的时候,返回值类型可以相同也可以不相同 函数重写 Override: 必须发生于父类与子类之间(继承) 子类 在方法名,参数列表,返回类型都相同的情况下, 对方法体进行修改或重写,这就是重写 使用virtual声明之后能够产生多态(如果不使用virtual,那叫重定义) * */ using namespace std; class Base{ public: Base(){ m_A = 100; } void fun(){ cout << "Base func调用" << endl; } void fun(int a){ cout << "Base func (int a)调用" << endl; } int m_A; }; class Son :public Base{ public: Son(){ m_A = 200; } void fun(){ cout << "Son func调用" << endl; } int m_A; }; void test15_03() { Son s1; cout << s1.m_A << endl; //想调用 父类中 的m_A cout << s1.Base::m_A << endl; // 调用父类的属性 s1.fun(); s1.Base::fun(10); //调用父类的func } //如果子类和父类拥有同名的函数 属性 ,子类会覆盖父类的成员吗? 不会 //如果子类与父类的成员函数名称相同,子类会把父类的所有的同名版本都隐藏掉 //想调用父类的方法,必须加作用域 int main15_03() { test15_03(); return 0; }
true
ba66312f34af0856343e8fba381d72ef252d213d
C++
berglindduna/Data-Structure
/Palindrome/main.cpp
UTF-8
466
3.09375
3
[]
no_license
#include <iostream> #include <cstring> #include "palindrome.h" using namespace std; // Tests int main() { char a[] = "abcdcba"; char b[] = "1221"; char c[] = "ablab"; if (palindrome(a, 0, strlen(a)-1)) cout << a << " is a palindrome" << endl; if (palindrome(b, 0, strlen(b)-1)) cout << b << " is a palindrome" << endl; if (palindrome(c, 0, strlen(c)-1)) cout << c << " is a palindrome" << endl; return 0; }
true
40702b6737f54145453803d4a8322a36aee88edf
C++
night0205/zorejudge
/e623.cpp
UTF-8
323
2.9375
3
[]
no_license
//e623: PPAP #include<iostream> #include<string> using namespace std; main(){ string ans[4] = {"Pen","Pineapple","Apple","Pineapple pen"}; int n; cin >> n; int a = 0; int te = 0; while(te<n){ a++; for(int i=0;i<4;i++){ te += a; if(te>=n){ a = i; n = 0; break; } } } cout << ans[a]; }
true
345b22927d81f9893f28da8aa0f20994bfd9a1b1
C++
nandiniramakrishnan/xnor-net-ios
/xnor/xnor/Convolution.cpp
UTF-8
4,831
2.625
3
[]
no_license
// // Convolution.cpp // xnor // // Created by Nandini Ramakrishnan on 29/04/17. // Copyright © 2017 Shalini Ramakrishnan. All rights reserved. // #include "Convolution.hpp" #include "im2col.hpp" #include <arm_neon.h> Convolution::Convolution(int k,int stride, int c, int pad, int group, int num) { this->k = 5; this->stride = stride; this->pad = pad; this->group = group; this->num = num; this->channel = c; } arma::fmat Convolution::binConv(uint8_t *input, int h_in, int w_in) { /* Toy example weights */ //arma::fmat w(k*k, 1); //w.fill(1/(k*k)); //arma::fmat w = { 1, 1, 1, 1, 1, 8, 8, 1, 1, 8, 8, 1, 1, 1, 1, 1 }; //arma::fmat w = { 9, 0, 9, 7, 0, 7, 9, 0, 9 }; arma::fmat w = { 1, 1, 1, 1, 1, 1, 2, 4, 2, 1, 1, 4, 8, 4, 1, 1, 2, 4, 2, 1, 1, 1, 1, 1, 1 }; //arma::fmat w(1, k*k); //w.fill(1.0); w = w.t(); arma::wall_clock timer; /* Average of weights */ arma::fmat weight_avgs = arma::mean(w); /* Obtain patches from im2col */ int h_out = (h_in + 2*pad - k) / stride + 1; int w_out = (w_in + 2*pad - k) / stride + 1; int numPatches = h_out * w_out; int sizeCol = k * k * channel * numPatches; float *data_col = new float[sizeCol]; im2col(input, 1, h_in, w_in, k, stride, pad, data_col); /* Vector size for NEON operations */ int neon_vec_size = 16; int patch_size = k*k; int num_vecs_per_patch = ceil((float)patch_size / (float)neon_vec_size); /* Get averages of sub tensors */ arma::fmat patches(data_col, h_out*w_out, k*k); // std::cout << "mean = " << arma::max(arma::max(patches)) << std::endl; // std::cout << "stddev = " << arma::stddev(arma::vectorise(patches)) << std::endl; patches = (patches / arma::max(arma::max(patches))); /// arma::stddev(arma::vectorise(patches)); w = w / arma::max(arma::max(w)); arma::fmat K = arma::mean(patches, 1); /* Get signs of input patches using Armadillo */ arma::uchar_mat input_signs(numPatches, neon_vec_size*num_vecs_per_patch); input_signs(arma::span::all, arma::span(0,k*k - 1) ) = arma::conv_to<arma::uchar_mat>::from(arma::sign(patches)); input_signs = input_signs.t(); // Transpose the matrix to get patches as cols //input_signs.insert_rows( patch_size - 1, neon_vec_size - patch_size ); //printf("input signs done\n"); /* Get signs of weights using Armadillo */ arma::uchar_mat weight_signs(neon_vec_size*num_vecs_per_patch, num); weight_signs(arma::span(0,k*k - 1), arma::span::all ) = arma::conv_to<arma::uchar_mat>::from(arma::sign(w)); // input_signs = arma::sign(input_signs); //printf("weight signs done\n"); // arma::uchar_mat weight_signs = arma::conv_to<arma::uchar_mat>::from(arma::sign(w)); // weight_signs.insert_rows( patch_size - 1, neon_vec_size - patch_size ); /* Temp vector for doing bitcount */ uint8_t *bitcount_ptr = new uint8_t[neon_vec_size*neon_vec_size*num_vecs_per_patch]; /* Declare return value */ arma::fmat result(numPatches, num); //printf("before the for loops\n"); timer.tic(); /* Perform the convolution */ for (int i = 0; i < num; i++) { //printf("filter number = %d\n", i); uint8_t *weight_sign_ptr = weight_signs.colptr(i); arma::fmat scaling_factor = K * weight_avgs(i); for (int j = 0; j < numPatches; j++) { //printf("patch number = %d\n", j); uint8_t *input_sign_patch_ptr = input_signs.colptr(j); for (int m = 0; m < num_vecs_per_patch; m++) { uint8x16_t input_vec = vld1q_u8(&input_sign_patch_ptr[m*neon_vec_size]); uint8x16_t weight_vec = vld1q_u8(weight_sign_ptr); uint8x16_t and_res = vandq_u8(input_vec, weight_vec); // VAND q0,q0,q0 // for (int l = 0; l < neon_vec_size; l++) { // printf("%u & %u = %u\n", input_vec[l], weight_vec[l], and_res[l]); // printf("---\n"); // } vst1q_u8(bitcount_ptr, and_res); // load into arma vec and sum arma::uchar_vec bitcount(bitcount_ptr, neon_vec_size); // for (int l = 0; l < neon_vec_size; l++) { // printf("%u", bitcount(l)); // } // printf("\n%u\n", arma::sum(bitcount)); result(j, i) += arma::sum(bitcount); } } //std::cout << "Scaling factor = " << scaling_factor << std::endl; result.col(i) = result.col(i) % scaling_factor; } double binconvsecs = timer.toc(); std::cout << "Binary convolution took " << binconvsecs << " seconds" << std::endl; return reshape(result, h_out, w_out); }
true
68f01f61493fb3463957bdafe55dfd5c637949b6
C++
andresusanopinto/novelty-detection-thesis
/novelty-gm/synthetic/single-factor.cc
UTF-8
16,056
2.625
3
[]
no_license
/** * Novelty Detection Scripts * * Copyright 2011: André Susano Pinto * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Graph.h" #include "Graph-internal.h" #include "Query.h" #include "util.h" #include <cassert> #include <cstdio> #include <set> #include <iostream> #include <fstream> #include <algorithm> #include <cmath> using namespace std; #include <boost/foreach.hpp> #include <boost/scoped_ptr.hpp> using namespace boost; /** * This experiment tries to approach a graph where variable * a is only connected with a single type of factor \phi. * */ namespace { string room(int i) { return "r" + to_string(i); } string prop(int i) { return "p" + to_string(i); } vector<string> vector_of(const string &a, const string &b) { vector<string> t(2); t[0] = a, t[1] = b; return t; } struct GraphStructure { int rooms; int senses; set<pair<int,int> > edges; void createRandom(int rooms, int senses, int extra_conn) { this->rooms = rooms; this->senses = senses; // Creates a tree for (int i = 1; i < rooms; ++i) { int other = random() % i; edges.insert(make_pair(other, i)); } // Tries to add extra room connectivity while (extra_conn--) { int a = random() % rooms; int b = random() % rooms; if (a == b) continue; if (a > b) swap(a, b); edges.insert(make_pair(a, b)); } // Adds senses (they are randomly split by the rooms) for (int i = 0; i < senses; ++i) { int r = random() % rooms; edges.insert(make_pair(r, rooms+i)); } } }; class MGraph : public Graph { public: vector<const Variable*> vars; MGraph(const GraphStructure &structure, const VariableType *room, const VariableType *sense, const FactorData *rrf, const FactorData *rsf) { // Build Graph for (int i = 0; i < structure.rooms; ++i) vars.push_back(CreateVariable(room)); for (int i = 0; i < structure.senses; ++i) vars.push_back(CreateVariable(sense)); typedef pair<int,int> Edge; BOOST_FOREACH(const Edge &e, structure.edges) { int a = e.first; int b = e.second; vector<const Variable*> nodes; nodes.push_back(vars[a]); nodes.push_back(vars[b]); CreateFactor(b < structure.rooms? rrf : rsf, nodes); } } void print(const vector<const Variable*> &obs_vars, const vector<string> &obs_vals) { map<const Variable*, string> id; BOOST_FOREACH(const Variable* var, vars) id[var] = "n" + to_string(id.size()); vector<const ::Factor*> factors; ListFactors(&factors); BOOST_FOREACH(const ::Factor* fac, factors) BOOST_FOREACH(const Variable* var, fac->variables_) if (id.count(var) == 0) id[var] = "n" + to_string(id.size()); printf("graph sample {\n"); printf(" node [shape=circle];\n"); BOOST_FOREACH(const Variable* var, vars) printf(" %s;\n", id[var].c_str()); for (size_t i = 0; i < obs_vars.size(); ++i) printf(" %s[label=%s];\n", id[obs_vars[i]].c_str(), obs_vals[i].c_str()); int nf = 1; printf(" node [shape=square];\n"); BOOST_FOREACH(const ::Factor* fac, factors) { string fid = "f" + to_string(nf++); printf(" %s;\n", fid.c_str()); BOOST_FOREACH(const Variable* var, fac->variables_) printf(" %s -- %s;\n", fid.c_str(), id[var].c_str()); } printf("}\n"); } }; void FilterVariable(const set<string> &allowed, VariableType *type) { type->values.clear(); type->values.reserve(allowed.size()); type->values.insert(type->values.end(), allowed.begin(), allowed.end()); } void FilterFactor(int varid, const string &vartype, const VariableType &var, FactorData *data) { (*data).variables[varid].second = vartype; map<vector<string>, double> potential; typedef pair<vector<string>,double> iter; BOOST_FOREACH(const iter &it, data->potential) if (find(var.values.begin(), var.values.end(), it.first[varid]) != var.values.end()) potential.insert(it); potential.swap(data->potential); } } size_t room_types = 7; size_t n_known_rooms = 5; size_t property_types = 8; int C = 1; set<string> known_rooms; set<string> novel_rooms; GraphInformation gi; // Real World VariableType *type_real_room = NULL; VariableType *type_real_prop = NULL; FactorData *factor_rroom_rprop = NULL; // Filtered Real Worlds VariableType *type_real_kroom = NULL; VariableType *type_real_nroom = NULL; FactorData *factor_rkroom_rprop = NULL; FactorData *factor_rnroom_rprop = NULL; // Conditional Learning VariableType *type_known_room = NULL; FactorData *factor_kroom_kprop = NULL; // Unconditional Learning VariableType *type_any_room = NULL; FactorData *factor_aroom_kprop = NULL; void generate_real_distribution_vars_and_factors() { for (size_t i = 0; i < n_known_rooms; ++i) known_rooms.insert(room(i)); for (size_t i = n_known_rooms; i < room_types; ++i) novel_rooms.insert(room(i)); // Real room variable. { VariableType &type = *(type_real_room = gi.Add("real_room", VariableType())); type.values.insert(type.values.end(), known_rooms.begin(), known_rooms.end()); type.values.insert(type.values.end(), novel_rooms.begin(), novel_rooms.end()); sort(type.values.begin(), type.values.end()); } // Real property variable. { VariableType &type = *(type_real_prop = gi.Add("real_prop", VariableType())); for (int i = 0; i < property_types; ++i) type.values.push_back(prop(i)); sort(type.values.begin(), type.values.end()); } // Real factor(room, property). { FactorData &factor = *(factor_rroom_rprop = gi.Add("f(room, property)", FactorData())); factor.variables.push_back(make_pair("room", "real_room")); factor.variables.push_back(make_pair("prop", "real_prop")); BOOST_FOREACH(const string &room, type_real_room->values) BOOST_FOREACH(const string &prop, type_real_prop->values) factor.potential[vector_of(room, prop)] = 0.1; BOOST_FOREACH(const string &room, type_real_room->values) factor.potential[vector_of(room, type_real_prop->values[random()%property_types])] = 0.3 + drand48(); } // Make filtered versions of known and novel rooms to use to generate samples. type_real_kroom = gi.Add("known_room", *type_real_room); FilterVariable(known_rooms, type_real_kroom); type_real_nroom = gi.Add("novel_room", *type_real_room); FilterVariable(novel_rooms, type_real_nroom); factor_rkroom_rprop = gi.Add("f_real(room, property|room in known rooms)", *factor_rroom_rprop); FilterFactor(0, "known_room", *type_real_kroom, factor_rkroom_rprop); factor_rnroom_rprop = gi.Add("f_real(room, property|room in novel rooms)", *factor_rroom_rprop); FilterFactor(0, "novel_room", *type_real_nroom, factor_rnroom_rprop); } void generate_samples(vector<vector<string> > *output, VariableType *room, FactorData *factor, int size) { BOOST_FOREACH(vector<string> &sample, *output) { GraphStructure s; int n_properties = size; if (n_properties == -1) n_properties = 1 + (random() % 17); s.createRandom(1, n_properties, 0); MGraph g(s, room, type_real_prop, NULL, factor); Query q(&g); q.Sample(g.vars, &sample); } } void generate_unconditional_samples(vector<vector<string> > *output, int size = -1) { generate_samples(output, type_real_room, factor_rroom_rprop, size); } void generate_conditional_ksamples(vector<vector<string> > *output, int size = -1) { generate_samples(output, type_real_kroom, factor_rkroom_rprop, size); } void generate_conditional_nsamples(vector<vector<string> > *output, int size = -1) { generate_samples(output, type_real_nroom, factor_rnroom_rprop, size); } void learn_known_room_distribution(const vector<vector<string> > samples) { type_known_room = type_real_kroom; // Learn factor(room, property | room in known_rooms) from labelled data. FactorData &factor = *(factor_kroom_kprop = gi.Add("f(room, prop|room in known rooms)", FactorData())); factor.variables.push_back(make_pair("room", "known_room")); factor.variables.push_back(make_pair("prop", "real_prop")); BOOST_FOREACH(const vector<string> &sample, samples) { const string room = sample[0]; for (size_t f = 1; f < sample.size(); ++f) { const string prop = sample[f]; factor.potential[vector_of(room, prop)]++; } } // Added smoothing factor. BOOST_FOREACH(const string &room, known_rooms) BOOST_FOREACH(const string &prop, type_real_prop->values) factor.potential[vector_of(room, prop)]++; } void learn_any_room_distribution(const vector<vector<string> > &samples) { // Create variable type for any room states. type_any_room = gi.Add("any_room", VariableType()); type_any_room->values.push_back("any"); // Learn factor(room, property | room is any room) form unlabelled data. { FactorData &factor = *(factor_aroom_kprop = gi.Add("f(room, prop|room is any room)", FactorData())); factor.variables.push_back(make_pair("room", "any_room")); factor.variables.push_back(make_pair("prop", "real_prop")); BOOST_FOREACH(const vector<string> &sample, samples) for (size_t f = 1; f < sample.size(); ++f) factor.potential[vector_of("any", sample[f])]++; BOOST_FOREACH(const string &prop, type_real_prop->values) factor.potential[vector_of("any", prop)] += C; map<vector<string>,double>::iterator iter; for (iter = factor.potential.begin(); iter != factor.potential.end(); ++iter) { // iter->second *= exp(-4.86222); // iter->second *= exp(0.399); } } } void compare_real_normalization_factors() { for (size_t i = 1; i < 100; ++i) { GraphStructure s; int n_properties = i; //1 + (random() % 15); s.createRandom(1, n_properties, 0); MGraph real_g(s, type_real_room, type_real_prop, NULL, factor_rroom_rprop); MGraph any_g (s, type_any_room, type_real_prop, NULL, factor_aroom_kprop); Query rq(&real_g); Query aq(&any_g); // Absolute difference: vector<const Variable*> var; vector<string> var_clamp; double abs_rlogz = rq.LogZ(var, var_clamp); double abs_alogz = aq.LogZ(var, var_clamp); cout << n_properties << ": total_abs_diff = " << exp(abs_rlogz - abs_alogz) << endl; cout << n_properties << ": total_rel_diff = " << (abs_rlogz - abs_alogz)/n_properties << endl; } } double junk() { return 0.1 + drand48()/5; } void compare_performance(const vector<vector<string> > &samples) { vector<pair<pair<int,double>,bool> > result_fix; vector<pair<pair<int,double>,bool> > result_dyn; vector<pair<pair<int,double>,bool> > result_opt; BOOST_FOREACH(const vector<string> &sample, samples) { int n_properties = sample.size()-1; GraphStructure s; s.createRandom(1, n_properties, 0); MGraph known_g(s, type_known_room, type_real_prop, NULL, factor_kroom_kprop); MGraph any_g (s, type_any_room, type_real_prop, NULL, factor_aroom_kprop); MGraph real_g (s, type_real_room, type_real_prop, NULL, factor_rroom_rprop); Query kq(&known_g); Query aq(&any_g); Query rq(&real_g); vector<const Variable*> k_prop(known_g.vars.begin()+1, known_g.vars.end()); vector<const Variable*> a_prop(any_g.vars.begin()+1, any_g.vars.end()); vector<const Variable*> r_prop(real_g.vars.begin()+1, real_g.vars.end()); vector<string> clamp(sample.begin()+1, sample.end()); double klogZ = kq.LogZ(k_prop, clamp); double alogZ = aq.LogZ(a_prop, clamp); // log(2) + log(\phi_k(x)) < k_i log(s_i) + log(\phi_a(x)) // log(s_i) > (log(2) + log(\phi_k(x)) - log(\phi_a(x))) / k_i double dyn_threshold = (-1+klogZ - alogZ)/n_properties; result_dyn.push_back(make_pair(make_pair(n_properties, exp(dyn_threshold)), known_rooms.count(sample[0]) == 1)); // Assuming a constant probability of drawing a novel sample. vector<const Variable*> no_prop; vector<string> no_clamp; double t_klogZ = kq.LogZ(no_prop, no_clamp); double t_alogZ = aq.LogZ(no_prop, no_clamp); double fix_threshold = exp((klogZ - t_klogZ) - (alogZ - t_alogZ)); result_fix.push_back(make_pair(make_pair(n_properties, fix_threshold), known_rooms.count(sample[0]) == 1)); //result_dyn.push_back(make_pair(make_pair(n_properties, fix_threshold/n_properties), known_rooms.count(sample[0]) == 1)); // Real distribution double notnovel_p = 0.0; double novel_p = 0.0; double r_logZ = rq.LogZ(r_prop, clamp); BOOST_FOREACH(const string room, type_real_room->values) { vector<string> aclamp; aclamp.push_back(room); aclamp.insert(aclamp.end(), clamp.begin(), clamp.end()); double prob = exp( rq.LogZ(real_g.vars, aclamp) - r_logZ ); if (known_rooms.count(room)) notnovel_p += prob; else novel_p += prob; } result_opt.push_back(make_pair(make_pair(n_properties, notnovel_p), known_rooms.count(sample[0]) == 1)); } sort(result_dyn.begin(), result_dyn.end()); sort(result_fix.begin(), result_fix.end()); { ofstream os_known("result_dyn_threshold_known.data"); ofstream os_novel("result_dyn_threshold_novel.data"); for (size_t i = 0; i < result_dyn.size(); ++i) if (result_dyn[i].second) os_known << fixed << result_dyn[i].first.first + junk() << " " << fixed << result_dyn[i].first.second << endl; else os_novel << fixed << result_dyn[i].first.first - junk() << " " << fixed << result_dyn[i].first.second << endl; } { ofstream os_known("result_fix_threshold_known.data"); ofstream os_novel("result_fix_threshold_novel.data"); for (size_t i = 0; i < result_fix.size(); ++i) if (result_fix[i].second) os_known << fixed << result_fix[i].first.first + junk() << " " << fixed << result_fix[i].first.second << endl; else os_novel << fixed << result_fix[i].first.first - junk() << " " << fixed << result_fix[i].first.second << endl; } { ofstream os_known("result_opt_threshold_known.data"); ofstream os_novel("result_opt_threshold_novel.data"); for (size_t i = 0; i < result_opt.size(); ++i) if (result_opt[i].second) os_known << fixed << result_opt[i].first.first + junk() << " " << fixed << result_opt[i].first.second << endl; else os_novel << fixed << result_opt[i].first.first - junk() << " " << fixed << result_opt[i].first.second << endl; } } void example_single_factor() { generate_real_distribution_vars_and_factors(); vector<vector<string> > conditional_samples(20*n_known_rooms); generate_conditional_ksamples(&conditional_samples); learn_known_room_distribution(conditional_samples); vector<vector<string> > unconditional_samples(20*room_types); generate_unconditional_samples(&unconditional_samples); learn_any_room_distribution(unconditional_samples); assert(gi.CheckConsistency()); // compare_real_normalization_factors(); vector<vector<string> > test_data; for (size_t i = 1; i < 18; ++i) { { vector<vector<string> > data(50); generate_conditional_ksamples(&data, i); test_data.insert(test_data.end(), data.begin(), data.end()); } { vector<vector<string> > data(50); generate_conditional_nsamples(&data, i); test_data.insert(test_data.end(), data.begin(), data.end()); } } compare_performance(test_data); }
true
cbd53034a6afb4ce9c4fd4df780fc81a85ba6a0f
C++
pathakaditya6/Competitive-Programming
/HackerRank/2D-ArrayDS.cpp
UTF-8
2,080
2.71875
3
[]
no_license
// In the name of Aadi Shakti // We are nothing and You are everything // Jai Mata Di #include <bits/stdc++.h> using namespace std; int main() { int res[16] ; int arr[6][6] ; for(int i = 0 ; i < 6 ; i++) { for(int j = 0 ; j < 6 ; j++) { cin >> arr[i][j]; } } res[0] = arr[0][0] + arr[0][1] + arr[0][2] + arr[2][0] + arr[2][1] + arr[2][2] + arr[1][1] ; res[1] = arr[0][1] + arr[0][2] + arr[0][3] + arr[2][1] + arr[2][2] + arr[2][3] + arr[1][2] ; res[2] = arr[0][2] + arr[0][3] + arr[0][4] + arr[2][2] + arr[2][3] + arr[2][4] + arr[1][3] ; res[3] = arr[0][3] + arr[0][4] + arr[0][5] + arr[2][3] + arr[2][4] + arr[2][5] + arr[1][4] ; res[4] = arr[1][0] + arr[1][1] + arr[1][2] + arr[3][0] + arr[3][1] + arr[3][2] + arr[2][1] ; res[5] = arr[1][1] + arr[1][2] + arr[1][3] + arr[3][1] + arr[3][2] + arr[3][3] + arr[2][2] ; res[6] = arr[1][2] + arr[1][3] + arr[1][4] + arr[3][2] + arr[3][3] + arr[3][4] + arr[2][3] ; res[7] = arr[1][3] + arr[1][4] + arr[1][5] + arr[3][3] + arr[3][4] + arr[3][5] + arr[2][4] ; res[8] = arr[2][0] + arr[2][1] + arr[2][2] + arr[4][0] + arr[4][1] + arr[4][2] + arr[3][1] ; res[9] = arr[2][1] + arr[2][2] + arr[2][3] + arr[4][1] + arr[4][2] + arr[4][3] + arr[3][2] ; res[10] = arr[2][2] + arr[2][3] + arr[2][4] + arr[4][2] + arr[4][3] + arr[4][4] + arr[3][3] ; res[11] = arr[2][3] + arr[2][4] + arr[2][5] + arr[4][3] + arr[4][4] + arr[4][5] + arr[3][4] ; res[12] = arr[3][0] + arr[3][1] + arr[3][2] + arr[5][0] + arr[5][1] + arr[5][2] + arr[4][1] ; res[13] = arr[3][1] + arr[3][2] + arr[3][3] + arr[5][1] + arr[5][2] + arr[5][3] + arr[4][2] ; res[14] = arr[3][2] + arr[3][3] + arr[3][4] + arr[5][2] + arr[5][3] + arr[5][4] + arr[4][3] ; res[15] = arr[3][3] + arr[3][4] + arr[3][5] + arr[5][3] + arr[5][4] + arr[5][5] + arr[4][4] ; // for(auto x : res ) cout << x << " "; // cout << endl ; int maxx = -1000 ; for(int i = 0; i < 16 ; i++) { if(res[i] > maxx ) maxx = res[i] ; } cout << maxx << endl ; }
true
691cae6e66a17c9bf9c90de0b14cbc8883bc9639
C++
SantiagoBarbosaNieto/Intro_IA
/Proyecto3_InferenciaBayesiana/src/Dato.h
UTF-8
311
2.5625
3
[]
no_license
#pragma once #include <iostream> #include <map> using namespace std; class Dato { private: map<string, string> valores; public: Dato(); ~Dato(); string buscarDato(string col); void ingresarDato(string col, string dato); void imprimirValores(); map<string, string> darValores(); int tam(); };
true
ae10de00d32fa3fd149229a876be42ab3e9ecb5f
C++
MorrigansWings/GamePhysics
/Katamari/Katamari Game/PhysicsEngine/PhysicsManager.cpp
UTF-8
10,207
2.546875
3
[ "Apache-2.0" ]
permissive
#include "PhysicsManager.h" #include <iostream> #include "ForceGenerators/ParticleForceGenerator.h" #include "ForceGenerators/GravityForceGenerator.h" #include "ForceGenerators/SpringForceGenerator.h" #include "Collision/ParticleContact.h" #include "Collision/ParticleContactGenerator.h" #include "Collision/GroundContactGenerator.h" #include "Collision/CableParticleConnection.h" #include "Collision/RodParticleConnection.h" PhysicsManager* PhysicsManager::s_Instance = nullptr; PhysicsManager::PhysicsManager() { s_Instance = this; // Set up force generators GravityForceGenerator* gravity = new GravityForceGenerator(2.0f); // scale gravity by 2 m_particleForceRegistry.add("gravity", gravity); m_maxPasses = 50; } PhysicsManager::~PhysicsManager() { for (auto iter = m_particleSet.itBegin(); iter != m_particleSet.itEnd(); ++iter) delete iter->second; m_particleSet.clear(); for (auto iter = m_particleForceRegistry.itBegin(); iter != m_particleForceRegistry.itEnd(); ++iter) delete iter->second; m_particleForceRegistry.clear(); m_forceRegistrations.clear(); } void PhysicsManager::setupGround(float height, float xbounds, float ybounds) { m_groundHeight = height; //m_groundXBounds = xbounds; // currently ignored! will be good for planes with edges //m_groundYBounds = ybounds; // that you can fall off off // create ground collision generator GroundContactGenerator* ground = new GroundContactGenerator(); ground->setGroundHeight(m_groundHeight); m_particleContactRegistry.add("ground", ground); } void PhysicsManager::update(float duration) { // Clear force accumulators for (auto iter = m_particleSet.itBegin(); iter != m_particleSet.itEnd(); ++iter) iter->second->clearAccumulation(); // Generate forces via generators updateForces(duration); // Integrate particle positions integrateParticles(duration); // Compute set of all particles in contact generateCollisions(); singlePassCollisions(duration); //multiPassCollisions(duration); // clear contacts after resolution for (unsigned int i = 0; i < m_contacts.getSize(); ++i) m_contacts.removeAt(i); m_contacts.clear(); } void PhysicsManager::updateForces(float duration) { //for (auto it = m_forceRegistrations.itBegin(); it != m_forceRegistrations.itEnd(); ++it) for (unsigned int i = 0; i < m_forceRegistrations.getSize(); ++i) { //std::cout << "PHYSICSMANAGER:updateForces: Attempting to update generator " << i << std::endl; ParticleForceGenerator* generator = m_forceRegistrations[i].generator; Particle* particle = m_forceRegistrations[i].particle; generator->updateForce(particle, duration); } } void PhysicsManager::integrateParticles(float duration) { for (auto iter = m_particleSet.itBegin(); iter != m_particleSet.itEnd(); ++iter) iter->second->integrate(duration); } void PhysicsManager::generateCollisions() { for (auto iter = m_particleContactRegistry.itBegin(); iter != m_particleContactRegistry.itEnd(); ++iter) { //std::cout << "PHYSICSMANAGER:generateCollisions(): Generating collisions with generator: " << iter->first << std::endl; iter->second->AddContact(s_Instance); } } void PhysicsManager::resolveCollisions(float duration) { for (unsigned int i = 0; i < m_contacts.getSize(); ++i) { m_contacts[i]->resolve(duration); } // clear contacts after resolution...? for (unsigned int i = 0; i < m_contacts.getSize(); ++i) { m_contacts.removeAt(i); } m_contacts.clear(); } void PhysicsManager::singlePassCollisions(float duration) { // Resolve velocities for all particles in contact resolveCollisions(duration); } void PhysicsManager::multiPassCollisions(float duration) { int processed = 0; while (processed < m_maxPasses) { float minSeparatingVelocity = std::numeric_limits<float>::max(); int candidate = 0; for (unsigned int i = 0; i < m_contacts.getSize(); ++i) { // get collision with greatest velocity float separating = m_contacts[i]->separatingVelocity(); if (separating <= minSeparatingVelocity && (separating < 0.0f || m_contacts[i]->getPenetrationDepth() > 0)) { minSeparatingVelocity = separating; candidate = i; } } // no collision found if (minSeparatingVelocity > 0.0f) return; // Get particles involved Particle* first = m_contacts[candidate]->getFirstParticle(); Particle* second = m_contacts[candidate]->getSecondParticle(); // process best candidate std::cout << "PHYSICSMANAGER:multiPassCollisions: Processing candidate #" << std::to_string(candidate) << std::endl; m_contacts[candidate]->resolve(duration); // Get new positions of particles involved Vector3 firstPos = m_contacts[candidate]->getFirstParticle()->getPosition(); Vector3 secondPos = Vector3(0.0f); if (m_contacts[candidate]->getSecondParticle() != nullptr) secondPos = m_contacts[candidate]->getSecondParticle()->getPosition(); // update particle positions in each other contact for (unsigned int i = 0; i < m_contacts.getSize(); ++i) { ParticleContact* contact = m_contacts[i]; if (contact->getFirstParticle() == first) contact->getFirstParticle()->setPosition(firstPos); if (second != nullptr) if (contact->getFirstParticle() == second) contact->getFirstParticle()->setPosition(secondPos); if (contact->getSecondParticle() != nullptr) { if (contact->getSecondParticle() == first) contact->getSecondParticle()->setPosition(firstPos); if (second != nullptr) if (contact->getSecondParticle() == second) contact->getSecondParticle()->setPosition(secondPos); } } ++processed; } } string PhysicsManager::createParticle(string name) { //std::cout << "PHYSICSMANAGER::createParticle(): Attempting to create new particle named " << name << "..." << std::endl; if (!m_particleSet.containsKey(name)) { m_particleSet.add(name, new Particle()); //std::cout << "\tCreated new particle named " << name << std::endl; return name; } else return ""; } string PhysicsManager::createParticle(string name, Vector3 pos) { //std::cout << "PHYSICSMANAGER::createParticle(): Attempting to create new particle named " << name << " at position : " << pos.ToString() << std::endl; if (!m_particleSet.containsKey(name)) { Particle* newpart = new Particle(); newpart->setPosition(pos); m_particleSet.add(name, newpart); //std::cout << "\tCreated new particle named " << name << std::endl; return name; } else return ""; } bool PhysicsManager::applyGravity(string &name) { if (m_particleSet.containsKey(name) && m_particleForceRegistry.containsKey("gravity")) { ForceRegistration newForce; newForce.generator = m_particleForceRegistry["gravity"]; newForce.particle = m_particleSet[name]; m_forceRegistrations.add(newForce); return true; } return false; } string PhysicsManager::addConnection(string &name, string first, string second, ConnectionType type) { //std::cout << "PHYSICSMANAGER::addConnection(): Attempting to add connection " << name << "..." << std::endl; //std::cout << "\tChecking for keys ( " << first << ", " << second << ") ..." << std::endl; string result = ""; if (m_particleSet.containsKey(first) && m_particleSet.containsKey(second)) { //std::cout << "\tBoth keys ( " << first << ", " << second << ") found! moving into switch statement..." << std::endl; switch (type) { case ROD: // Add only if name doesn't already exist in registry if (!m_particleContactRegistry.containsKey(name + "_rod")) result = addRod(name + "_rod", first, second); break; case CABLE: // return without adding if contact name already exists if (!m_particleContactRegistry.containsKey(name + "_cable")) result = addCable(name + "_cable", first, second); break; case SPRING: // return without adding if contact name already exists if (! m_particleForceRegistry.containsKey(name + "_spring_first") && ! m_particleForceRegistry.containsKey(name + "_spring_second")) { //std::cout << "PHYSICSMANAGER:addConnection: Attempting to add spring force generators to registry..." << std::endl; // One generator for each side... result = addSpring(name + "_spring_first", first, second); result += addSpring(name + "_spring_second", second, first); if (result != "") result = name + "_spring"; } break; } } return result; } string PhysicsManager::addRod(string &name, string first, string second) { RodParticleConnection* rod = new RodParticleConnection(); rod->mp_first = m_particleSet[first]; rod->mp_second = m_particleSet[second]; // calculate max length float mLength = Vector3::getDistance( rod->mp_first->getPosition(), rod->mp_second->getPosition()); rod->setMaxLength(mLength); // Add contact generator to registry //std::cout << "PHYSICSMANAGER::addRod(): Adding RodParticleConnection to particleContactRegistry[" << name << "]" << std::endl; //m_particleContactRegistry[name] = rod; m_particleContactRegistry.add(name, rod); return name; } string PhysicsManager::addCable(string &name, string first, string second) { CableParticleConnection* cable = new CableParticleConnection(); cable->mp_first = m_particleSet[first]; cable->mp_second = m_particleSet[second]; float mLength = Vector3::getDistance(cable->mp_second->getPosition(), cable->mp_first->getPosition()); cable->setMaxLength(mLength); cable->setRestitution(0.5f); // Add contact generator to registry //m_particleContactRegistry[name] = cable; m_particleContactRegistry.add(name, cable); return name; } string PhysicsManager::addSpring(string &name, string particle, string anchor) { // One generator for each side... Particle* partPart = m_particleSet[particle]; Particle* anchorPart = m_particleSet[anchor]; SpringForceGenerator* spring = new SpringForceGenerator(anchorPart); //first is anchored by second float restLength = Physics::Vector3::getDistance(partPart->getPosition(), anchorPart->getPosition()); spring->setRestLength(restLength); //m_particleForceRegistry[name] = spring; m_particleForceRegistry.add(name, spring); ForceRegistration registration; registration.generator = spring; registration.particle = partPart; m_forceRegistrations.add(registration); return name; }
true
05dba1f7fe54330215fbd9ffc8bde4adcd4e31b4
C++
currently1/option_pricer
/Option_Pricer.h
UTF-8
2,975
2.546875
3
[]
no_license
#include "Lin_Algebra.h" class pricer { public: virtual double get_price(); double(*forward_func)(double); double(*vol_func)(double, double); double(*payoff_func)(double); double(*discount_func)(double); double expire_time; }; class pde_pricer : public pricer { /* S(t) = F(t)exp(x(t)) dx = -0.5\sigma(x,t)^2 dt + sigma(x,t) dw g(x,t) = E[P(X,T)|(x,t)] dg/dt + (-0.5\sigma^2)dg/dx + 0.5 \sigma^2 d^2g/dx^2 = 0 price(x,t) = discount(t,T)g(x,t) */ public: pde_pricer(); virtual double get_price(); virtual void mush_grid(); virtual vector<double> get_grid_slice(){ return grid_slice; }; virtual vector<double> get_spot_slice(){ return spot_slice; }; virtual double lower_price_func(); virtual double upper_price_func(); protected: trigonal_matrix trig_mat; double slice_time, time_step, spot_step, spot_range_min, spot_range_max, lower_x, upper_x; vector<double> grid_slice; vector<double> spot_slice; virtual void set_payoff_slice(); virtual void step_back_one_dt(); void set_matrix(); virtual void set_b(); }; class pde_pricer_with_barrier : public pde_pricer { public: virtual void mush_grid(); double(*lower_b_func)(double); double(*upper_b_func)(double); double(*lower_r_func)(double); double(*upper_r_func)(double); virtual double lower_price_func(); virtual double upper_price_func(); }; class pde_pricer_american : public pde_pricer { public: virtual void mush_grid(); double(*early_payoff_func)(double, double); }; class pde_pricer_american_barrier : virtual public pde_pricer_american, virtual public pde_pricer_with_barrier { public: virtual void mush_grid(); }; class pde_pricer_auto_call : public pde_pricer { public: pde_pricer_auto_call(bool is_main_pricer=true); ~pde_pricer_auto_call(); virtual double get_price(); virtual void mush_grid(); double(*autocall_func)(double, double); bool(*ko_func)(double); double(*ko_payoff_func)(double); bool is_continuous_barrier; virtual double lower_price_func(); virtual double upper_price_func(); pde_pricer_auto_call* ko_pricer_ptr; bool is_main_pricer; }; class monte_carlo_pricer : public pricer { /* S(t) = F(t)exp(x(t)) dx = -0.5\sigma(x,t)^2 dt + sigma(x,t) dw g(x,t) = E[P(X,T)|(x,t)] dg/dt + (-0.5\sigma^2)dg/dx + 0.5 \sigma^2 d^2g/dx^2 = 0 price(x,t) = discount(t,T)g(x,t) */ public: monte_carlo_pricer( int num_paths = 40000 ); virtual double get_price(); virtual double get_error(); double get_shift_price(double log_shift);// quick and dirty - assume no vol skew - just scale all the spots path up. void simulate(); double(*path_payoff_func)(vector<double>,vector<double>); protected: vector<vector<double>> random_numbers; // on w. vector<vector<double>> paths; // on S. vector<double> event_times; vector<double> times; void set_times(); private: int number_paths; void gen_random_numbers(); void gen_paths(); };
true
e70d6862f326b0847e891e5caf1a20d551a33eb8
C++
TracyBaraza/Arduino
/Arduino_exercise/Arduino_exercise.ino
UTF-8
1,128
2.8125
3
[]
no_license
int REDLED=4; int GREENLED=2; int blinknumberREDLED=5; int blinknumberGREENLED=6; void setup() { Serial.begin(9600); pinMode (REDLED,OUTPUT); pinMode (GREENLED,OUTPUT); Serial.println("This is my first program"); Serial.println(" "); } void loop() { for(int j=1; j<=blinknumberREDLED; j=j+1) { Serial.print(" Blinking LED is RED # "); Serial.println(j); digitalWrite(REDLED,HIGH); delay(1000); digitalWrite(REDLED,LOW); delay(1000); } Serial.println(" "); for(int j=1; j<=blinknumberGREENLED; j=j+1) { Serial.print(" Blinking LED is GREEN # "); Serial.println(j); digitalWrite(GREENLED,HIGH); delay(1000); digitalWrite(GREENLED,LOW); delay(1000); } Serial.println(" "); }
true
677997941e89c0ea5c27d2b1eb8b60a489e9d2a6
C++
her-cat/meow-cpp
/src/coroutine/context.cc
UTF-8
1,615
2.890625
3
[ "MIT" ]
permissive
#include <iostream> #include "context.h" #include "meow.h" #include "log.h" using meow::Context; Context::Context(size_t stack_size, coroutine_function_t fn, void *private_data) : stack_size_(stack_size), fn_(fn), private_data_(private_data) { swap_ctx_ = nullptr; try { /* 创建一个 C 栈(实际上是从堆中分配的内存) */ stack_ = new char[stack_size_](); } catch (const std::bad_alloc &e) { meow_error("%s", e.what()) } /* 将堆模拟成栈 */ void *sp = (void *) ((char *) stack_ + stack_size_); /* 将 context_func 回调函数和自定义的堆栈填充到 ctx_ 中 */ ctx_ = make_fcontext(sp, stack_size_, (void (*)(intptr_t)) &context_func); } /* 上下文回调函数 */ void Context::context_func(void *arg) { Context *_this = (Context *) arg; /* 执行回调函数 */ _this->fn_(_this->private_data_); /* 标识已结束 */ _this->end_ = true; /* 让出当前协程 */ _this->swap_out(); } /* 进入当前协程的上下文 */ bool Context::swap_in() { /* 将当前上下文信息保存到 swap_ctx_,并切换到 ctx_ */ jump_fcontext(&swap_ctx_, ctx_, (intptr_t) this, true); return true; } /* 切换到前一个协程的上下文 */ bool Context::swap_out() { /* 将当前上下文信息保存到 ctx_,并切换到 swap_ctx_ */ jump_fcontext(&ctx_, swap_ctx_, (intptr_t) this, true); return true; } Context::~Context() { if (swap_ctx_) { delete[] stack_; stack_ = nullptr; } }
true
d05d00455481a261194c99d90459bbb93817695a
C++
blxckdog7702/algorithm
/vsAlgorithm/Algorithm/Algorithm/QuickSort.cpp
UHC
1,395
3.359375
3
[]
no_license
//#include<string> //#include<iostream> // //using namespace std; // //void quicksort(int low, int high, int s[]); //void partition(int low, int high, int& pivot, int s[]); // //int main() //{ // int s[50] = {0}; // int low, high; // int i, n; // // cout << "Է ?" << endl; // cin >> n; // // while (n < 0 || n > 50) { // cout << "Է" << endl; // cin >> n; // } // // for (i = 0; i < n; i++) { // cin >> s[i]; // } // // low = 0; // high = n - 1; // // quicksort(low, high, s); // // for (i = 0; i < n; i++) { // cout << s[i] << " "; // } // // return 0; // //} // //void quicksort(int low, int high, int s[]) { // int pivot; // // if (high > low) { // partition(low, high, pivot, s); // // ĵ 迭 ȣѴ. // quicksort(low, pivot - 1, s); // quicksort(pivot + 1, high, s); // // } //} // //void partition(int low, int high, int& pivot, int s[]) { // int i, j; // int temp; // int pivotItem; // // pivotItem = s[low]; // j = low; // // for (i = low + 1; i <= high; i++) { // // pivot [i] Ͽ [j] ȯѴ. // if (s[i] < pivotItem) { // j++; // temp = s[i]; // s[i] = s[j]; // s[j] = temp; // } // // } // // // pivot [j] ٲ [j] ִ pivot Ѵ. // pivot = j; // temp = s[low]; // s[low] = s[pivot]; // s[pivot] = temp; // //}
true
5d7f2a0edfd1d03ba19411bc9a445bd2ddb9c333
C++
mluna030/Last-of-the-labs
/lab26.cpp
UTF-8
1,149
3.71875
4
[]
no_license
#include <iostream> using namespace std; const int ARR_SIZE = 10; void bSort(double ar[]); int main() { double nums[ARR_SIZE]; for(int i =0; i < ARR_SIZE; i++) { cout << "Enter value " << i+1 << " of " << ARR_SIZE << " to be sorted: "; cin >> nums[i]; cout << endl; } cout << endl << endl << "Sorting values." << endl << endl; bSort(nums); cout << "Sorted values are: "; for(int i = 0; i < ARR_SIZE; i++) { cout << endl << nums[i]; } cout << endl << endl; return 0; } void bSort(double ar[]) //bubble sort { double temp = 0; bool flag = false; do { flag = false; //lower flag at start of new pass through array for(int i = 0; i < ARR_SIZE - 1; i++) //for each pair of elements in array { if(ar[i] < ar[i-1]) //if out of order (NOT including equal!) { //swap temp = ar[i]; ar[i] = ar[i-1]; ar[i-1] = temp; //raise flag flag = true; } //close if } //close for }while(flag == true); //close do-while (repeat if flag is raised) }//close function
true
eeaf1beb3242336f82c98f6e22f4e019cf8dff96
C++
mingyuefly/leetcode
/leetcode/prune/Sudoku Solver37/Sudoku Solver/Sudoku Solver/main.cpp
UTF-8
4,692
3.59375
4
[ "MIT" ]
permissive
// // main.cpp // Sudoku Solver // /** Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must occur exactly once in each column. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. The '.' character indicates empty cells. Example 1: Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] Explanation: The input board is shown above and the only valid solution is shown below: Constraints: board.length == 9 board[i].length == 9 board[i][j] is a digit or '.'. It is guaranteed that the input board has only one solution. */ // Created by mingyue on 2020/10/7. // Copyright © 2020 Gmingyue. All rights reserved. // #include <iostream> #include <vector> #include <set> using namespace std; class Solution { public: int spaceSum; vector<vector<int>> spaceV; bool sign; bool isValidSudoku(int n, char c, vector<vector<char>>& board) { vector<int> spacePoint = spaceV[n]; int length = (int)board.size(); for (int i = 0; i < length; i++) { if (board[spacePoint[0]][i] == c) { return false; } } for (int i = 0; i < length; i++) { if (board[i][spacePoint[1]] == c) { return false; } } int row = (spacePoint[0] / 3) * 3; int column = (spacePoint[1] / 3) * 3; for (int i = row; i < row + 3; i++) { for (int j = column; j < column + 3; j++) { if (board[i][j] == c) { return false; } } } return true; } void dfs(int n, vector<vector<char>>& board) { if (n == spaceSum) { sign = true; return; } char cs[9] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; vector<int> spacePoint = spaceV[n]; for (int j = 0; j < 9; j++) { if (isValidSudoku(n, cs[j], board)) { board[spacePoint[0]][spacePoint[1]] = cs[j]; dfs(n + 1, board); if (sign) { return ; } board[spacePoint[0]][spacePoint[1]] = '.'; } } } void solveSudoku(vector<vector<char>>& board) { int sum = 0; for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[i].size(); j++) { if (board[i][j] == '.') { vector<int> a; a.push_back(i); a.push_back(j); spaceV.push_back(a); sum++; } } } spaceSum = sum; sign = false; dfs(0, board); } }; int main(int argc, const char * argv[]) { char boardArray[9][9] = {{'5','3', '.','.','7','.','.','.','.'} ,{'6','.', '.','1','9','5','.','.','.'} ,{'.','9', '8','.','.','.','.','6','.'} ,{'8','.', '.','.','6','.','.','.','3'} ,{'4','.', '.','8','.','3','.','.','1'} ,{'7','.', '.','.','2','.','.','.','6'} ,{'.','6', '.','.','.','.','2','8','.'} ,{'.','.', '.','4','1','9','.','.','5'} ,{'.','.', '.','.','8','.','.','7','9'}}; vector<vector<char>> inputV; for (int i = 0; i < 9; i++) { vector<char> row; for (int j = 0; j < 9; j++) { row.push_back(boardArray[i][j]); } inputV.push_back(row); } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { cout << inputV[i][j] << ' '; } cout << endl; } cout << endl; Solution solution = Solution(); solution.solveSudoku(inputV); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { cout << inputV[i][j] << ' '; } cout << endl; } cout << endl; return 0; }
true
2bd37c786923d93743857119db52b2d5667e0071
C++
contacoonta/sgap-ccpp
/008 함수 function/001 function/main.cpp
UTF-8
797
3.609375
4
[]
no_license
/* 함수 function - main 함수에 집중된 코드를 분산. - 함수로 만든 코드를 재사용. y = f ( x ) int main( ) 1. 함수의 필요성 알아야.. 2. 함수를 정의.. 3. 함수를 선언.. */ #include <stdio.h> // 3. add 함수의 선언 int add(int a, int b); int div(int a, int b); void show(int k); void main() { int nA = 3, nB = 7; int nC = nA + nB; // 1. add 함수의 필요성. nC = add(nA, nB); //printf("nC = %d\n", nC); show(nC); // sub - // mul * // div / nC = div(nB, nA); //printf("nC = %d\n", nC); show(nC); // mod % } // 2. add 함수 정의. int add(int a, int b) { int c = a + b; return c; } int div(int a, int b) { return a / b; } void show(int k) { printf("---------show-----------\n"); printf("결과 = %d\n", k); }
true
7a76ccadc1a214e036701ca1d80cddfa7b2a4a67
C++
Midren/graphical_edtior
/newscenedialog.cpp
UTF-8
1,150
2.546875
3
[]
no_license
#include "newscenedialog.h" NewSceneDialog::NewSceneDialog() { QGridLayout *layout = new QGridLayout; QLabel *heightLabel = new QLabel(tr("Height of scene: ")); QLabel *widthLabel = new QLabel(tr("Width of scene: ")); heightEdit = new QLineEdit(tr("300")); widthEdit = new QLineEdit(tr("300")); addButton = new QDialogButtonBox(QDialogButtonBox::Ok); cancelButton = new QDialogButtonBox(QDialogButtonBox::Cancel); QIntValidator *val = new QIntValidator(1, 1024, this); heightEdit->setValidator(val); widthEdit->setValidator(val); connect(addButton, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(cancelButton, &QDialogButtonBox::rejected, this, &QDialog::reject); layout->addWidget(heightLabel, 1, 1); layout->addWidget(heightEdit, 1, 2); layout->addWidget(widthLabel, 2, 1); layout->addWidget(widthEdit, 2, 2); layout->addWidget(addButton, 3, 1); layout->addWidget(cancelButton, 3, 2); setLayout(layout); } int NewSceneDialog::getHeight() { return heightEdit->text().toInt(); } int NewSceneDialog::getWidth() { return widthEdit->text().toInt(); }
true
a428960b778668f330fea027c799ef1585c37820
C++
smrnjeet222/DS-Algo
/Algo_Coursera-Specialization/AlgoToolbox/week5_dynamic_programming1/1_money_change_again/change_dp.cpp
UTF-8
896
3.28125
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> using namespace std; int get_change_recursive(int m) { //write your code here if (m <= 0) return 0; int one = (m >= 1) ? get_change_recursive(m - 1) + 1 : 9999; int three = (m >= 3) ? get_change_recursive(m - 3) + 1 : 9999; int four = (m >= 4) ? get_change_recursive(m - 4) + 1 : 9999; return min(one, min(three, four)); } int get_change(int m) { //write your code here vector<int> table(m + 1, 9999); table[0] = 0; int coins[] = {1, 3, 4}; for (int i = 0; i <= m; i++) { for (int j = 0; j < 3; j++) { if (i >= coins[j]) { int minCoin = table[i - coins[j]] + 1; if (minCoin < table[i]) table[i] = minCoin; } } } return table[m]; } int main() { int m; cin >> m; cout << get_change(m) << '\n'; }
true
faeb188e81e6d25b91fb50461ec8f2493da966e3
C++
highstar97/Programmers_all_questions
/Summer_Winter_Coding_untill_2018/number_game.cpp
UTF-8
539
3.390625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> int solution(std::vector<int> A, std::vector<int> B) { int i=0,j=0; int answer = 0; sort(A.begin(),A.end()); sort(B.begin(),B.end()); for(; i<A.size(); i++){ for(j; j<B.size(); j++){ if(A[i] < B[j]){ j++; answer++; break; } } } return answer; } int main(){ std::vector<int> A = {5,1,3,7}; std::vector<int> B = {2,2,6,8}; std::cout << solution(A,B); }
true
b7a2bf846d4899f62092a7aa1a7ca9d5b22a0ac9
C++
karansonawane/CPP_Tutorial
/prac.cpp
UTF-8
1,398
4.15625
4
[]
no_license
// Assignment operators are : // #include<iostream> // using namespace std; // int main() // { // int a = 3, b=4; // cout<<"The value of assignment operator a+b is: "<<a+b<<endl; // cout<<"The value of assignment operator a-b is: "<<a-b <<endl; // cout<<"The value of assignment operator a/b is: "<<a/b<<endl; // cout<<"The value of assignment operator a%b is: "<<a%b<<endl; // cout<<"The value of assignment operator a*b is: "<<a*b<<endl; // cout<<"The value of assignment operator a++ is: "<<a++<<endl; // cout<<"The value of assignment operator a-- is: "<<a--<<endl; // cout<<"The value of assignment operator ++a is: "<<++a<<endl; // cout<<"The value of assignment operator --a is: "<<--a<<endl; // return 0; // } // #include<iostream> // using namespace std; // int main(){ // int num1, num2; // cout<<"Enter the Value of num1: \n"; // cin>>num1; // cout<<"Enter the Value of num2: \n"; // cin>>num2; // cout<<"The sum is: "<< num1+num2; // return 0; // } #include<iostream> using namespace std; void swap (int* a, int* b){ int temp = *a; *a = *b; *b = temp; } int main(){ int x = 4, y = 5 ; cout << "The value of x is "<<x<<" and the value of y is " <<y<< endl; swap(x, y); cout << "The value of x is "<<x<<" and the value of y is " <<y<< endl; return 0; }
true
1fea6b6b83bcd5726fd39c462c863427f246b0ff
C++
ChallengerCY/C-Base
/Chapter5/compstr1.cpp
UTF-8
944
3.828125
4
[]
no_license
// // Created by cy on 2020/1/1. // #include <iostream> #include <cstring> int main() { using namespace std; char word[5]="?ate"; for (char ch = 'a'; strcmp(word,"mate"); ch++) { cout<<word<<endl; word[0]=ch; } cout<<"After loop ends,word is "<<word<<endl; return 0; } /**本段代码小结 * word=="mate" 并不是数组字符串比较的方法。两个实际上都代表地址。判断的是是否存储在相同的地址上。 * strcmp用于比较字符串,如果相同则返回0,如果第一个字符串按字母排序在第二个地址前,那么会返回负数。否则返回正数。 * 按系统排序比按照字母排序更准确。意味着字符是根据字符的系统编码来比较的。大写字符的编码比小写字符的编码小。 * 两个字符串即使被存在长度不同的数组中,也会是相同的,因为是以空字符比较而不是数组长度。 * */
true
d2e0127ce262d4a79134c8b0d470b1269b828a20
C++
mrdrivingduck/leet-code
/338.CountingBits.cpp
UTF-8
1,824
3.71875
4
[ "MIT" ]
permissive
/** * @author Mr Dk. * @version 2021/03/03 */ /* Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example 1: Input: 2 Output: [0,1,1] Example 2: Input: 5 Output: [0,1,1,2,1,2] Follow up: It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass? Space complexity should be O(n). Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/counting-bits 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /* 实际上是一道动态规划题。根据奇数和偶数的二进制表示的性质,使用之前 已经得出的二进制数量的结果。奇数之比前一个偶数多了一个 1;偶数与 小一半的数的 1 的个数相同。 */ #include <cassert> #include <iostream> #include <vector> using std::cout; using std::endl; using std::vector; class Solution { public: vector<int> countBits(int num) { vector<int> bits(num + 1, 0); for (int i = 1; i <= num; i++) { if (i & 1) { bits[i] = bits[i - 1] + 1; } else { bits[i] = bits[i >> 1]; } } return bits; } }; int main() { Solution s; vector<int> bits; bits = { 0,1,1 }; assert(bits == s.countBits(2)); bits = { 0,1,1,2,1,2 }; assert(bits == s.countBits(5)); return 0; }
true
65d972a45abdff2b45c53cd6dd455aa637f08c9e
C++
AK-Reid/Mobile-Data-Collector
/Master_Code_Due.ino
UTF-8
25,042
2.515625
3
[]
no_license
//Including gfx & touchscreen libraries #include <Adafruit_GFX.h> #include <MCUFRIEND_kbv.h> #include <TouchScreen.h> //Defining the display MCUFRIEND_kbv tft; //Pressure threshholds #define MINPRESSURE 200 #define MAXPRESSURE 1000 // I2C_Anything from : http://www.gammon.com.au/i2c //Important library, this handles the I2C data transfer between the Uno and Due. Written by Nick Gammon //You need to link the "I2C_Anything.h" file to this file, by having it in the same Arduino project folder, and opening it as an attached tab in the IDE. #include "I2C_Anything.h" const int slaveAddress = 9; //This particular display has an uncommon pin layout, if it's not exactly as follows the touch functionality will fail. const int XP = 8, XM = A2, YP = A3, YM = 9; //ID=0x9341 //Results of the screen calibration, produced by the touchscreen calibrator code within the mcufriend library. const int TS_LEFT = 95, TS_RT = 914, TS_TOP = 77, TS_BOT = 892; TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300); //Defining some of the simplier buttons wusing the Adafruit_gfx button library. Adafruit_GFX_Button menu_btn, back_btn, confirm_btn, cancel_btn, ok_btn; //Global variables and constants float lux; int currentPage; int buttonNumber; int buttonState; int thickness = 4; int curvature = 12; unsigned long timeStamp = 0; unsigned long currentTime = 0; const long period = 500; unsigned long timerStart = 0; const long printInterval = 1000; float volts; float tst; float lat; float lon; float alt; String latValueString; float average = 0; int pixel_x, pixel_y; //Global vars for Touch_getXY(), for the Adafruit_gfx buttons. bool Touch_getXY(void) { TSPoint p = ts.getPoint(); pinMode(YP, OUTPUT); pinMode(XM, OUTPUT); digitalWrite(YP, HIGH); digitalWrite(XM, HIGH); bool pressed = (p.z > MINPRESSURE && p.z < MAXPRESSURE); if (pressed) { pixel_x = map(p.x, TS_LEFT, TS_RT, 0, 240); //Defining the parameters of the tft with the screen calibration results. pixel_y = map(p.y, TS_TOP, TS_BOT, 0, 320); } return pressed; } //Defining some colors, most were not used, colors with the "COLOR_" prefix were buggy for an unknown reason, having banded horizontal lines when appllied as a button color for example. #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF #define COLOR_NAVY 0x000F #define COLOR_DARK_GREEN 0x03E0 #define COLOR_DARK_CYAN 0x03EF #define COLOR_OLIVE 0x7BE0 #define COLOR_LIGHT_GREY 0xC618 #define COLOR_DARK_GREY 0x7BEF #define COLOR_MAROON 0x7800 #define COLOR_GEISHA 0x0BC8 #define COLOR_HOT_PINK 0xF81F //Interval and time tracker for the average lux display unsigned long previousMillis = 0; const long interval = 15000; //Interval and time tracker for the timing of the constant_gps_and_lux_data_loop unsigned long previousLoopTime = 0; const long loopTimingInterval = 1000; //Initial setup void setup(void) { Serial.begin(9600); //Opens serial port to begin the serial for communication between the boards, rate set to 9600 bps Wire.begin(); //Begin the wire for communication between the two boards via I2C uint16_t ID = tft.readID(); tft.begin(ID); //Starting up the touchscreen display, without this it will be blank homeScreen(); //Running the function for the home screen } void homeScreen(){ currentPage = 0; //Current page global var updated when the function is executed, to prevent buttons bleeding through and triggering on all pages simultaneously. tft.setRotation(0); //Portrait tft.fillScreen(BLACK); tft.setTextColor(WHITE, BLACK); tft.setTextSize(2); tft.setCursor(100, 0); //Dividing lines tft.drawLine(5,40,300,40,0x0000ff); tft.drawLine(5,100,300,100,0x0000ff); tft.drawLine(5,140,300,140,0x0000ff); tft.drawLine(5,190,300,190,0x0000ff); //Constant text items tft.setCursor (90,10); tft.setTextSize (4); tft.setTextColor (WHITE,BLACK); tft.println ("Lux"); tft.setCursor (90,10); tft.setTextSize (4); tft.setTextColor (WHITE,BLACK); tft.println ("Lux"); tft.setCursor (15,110); tft.setTextSize (2); tft.setTextColor (WHITE,BLACK); tft.println ("Avg Lux Value(15s)"); //Initializing the menu button menu_btn.initButton(&tft, 205, 300, 60, 30, WHITE, CYAN, BLACK, "MENU", 2); menu_btn.drawButton(); } void buttonMenu(){ currentPage = 1; //Current page global var updated when the function is executed, to prevent buttons bleeding through and triggering on all pages simultaneously. tft.setRotation(0); //Portrait tft.fillScreen(BLACK); tft.setTextSize(2); tft.setTextColor(WHITE, BLACK); tft.setCursor(100, 0); back_btn.initButton(&tft, 25, 300, 40, 30, WHITE, CYAN, BLACK, "<-", 3); //Initilization and drawing for the back button to return to the home screen back_btn.drawButton(); //Drawing of the main buttons for the button menu tft.drawRoundRect(10, 13, 220, 40, 18, WHITE); tft.setCursor (25,25); tft.setTextColor (WHITE,BLACK); tft.setTextSize (2); tft.print("Interesting Tree"); tft.drawRoundRect(10, 68, 220, 40, 18, WHITE); tft.setCursor (25,80); tft.setTextColor (WHITE,BLACK); tft.setTextSize (2); tft.print("Geology"); tft.drawRoundRect(10, 123, 220, 40, 18, WHITE); tft.setCursor (25,135); tft.setTextSize(2); tft.print("Coffee in Need"); tft.drawRoundRect(10, 178, 220, 40, 18, WHITE); tft.setCursor (25,190); tft.setTextColor (WHITE,BLACK); tft.setTextSize (2); tft.print("Animal Sign"); tft.drawRoundRect(10, 233, 220, 40, 18, WHITE); tft.setCursor (25,245); tft.setTextColor (WHITE,BLACK); tft.setTextSize (2); tft.print("Other"); } void confirmation_popup(){ currentPage = 2; //Current page global var updated when the function is executed, to prevent buttons bleeding through and triggering on all pages simultaneously. /* Length and width are changed from a fixed origin. Not uniformly on each end from the center. The 2xi modifier adjust the length and width from the origin, which creates the thicker effect on the right hand side, which needs to be counteracted by adding i to position to shift it, for a total of 1 pixel spaced concentric rounded rectangles In a nutshell this draws a sequence of concentric boundaries and stacks them up because just one is too thin. */ for (int i = 0; i < thickness; i++) { tft.drawRoundRect(10 + i, 11 + i, 220 - i*2, 303 - i*2, curvature, COLOR_NAVY); } tft.fillRoundRect(10+(thickness), 11+(thickness), 220-(thickness*2), 303-(thickness*2), curvature, WHITE); //Breaking out the constant text items that appear in the popup, and the specifics are added in if statements in the loop tft.setCursor(20,25); tft.setTextColor (BLACK, WHITE); tft.setTextSize (2); tft.println("Are you sure you"); tft.setCursor(20,40); tft.println("want to write the"); tft.setCursor(20,55); tft.println("GPS and lux data"); //Initializing and drawing of the confirm and cancel buttons confirm_btn.initButton(&tft, 65, 287, 90, 37, COLOR_HOT_PINK, GREEN, BLACK, "Confirm", 2); confirm_btn.drawButton(); cancel_btn.initButton(&tft, 175, 287, 90, 37, COLOR_HOT_PINK, CYAN, BLACK, "Cancel", 2); cancel_btn.drawButton(); } void OK_popup() { currentPage = 3; //Current page global var updated when the function is executed, to prevent buttons bleeding through and triggering on all pages simultaneously. /* Length and width are changed from a fixed origin. Not uniformly on each end from the center. The 2xi modifier adjust the length and width from the origin, which creates the thicker effect on the right hand side, which needs to be counteracted by adding i to position to shift it, for a total of 1 pixel spaced concentric rounded rectangles In a nutshell this draws a sequence of concentric boundaries and stacks them up because just one is too thin. */ for (int i = 0; i < thickness; i++) { tft.drawRoundRect(10 + i, 70 + i, 220 - i*2, 175 - i*2, curvature, COLOR_NAVY); } tft.fillRoundRect(10+(thickness), 70+(thickness), 220-(thickness*2), 175-(thickness*2), curvature, WHITE); ok_btn.initButton(&tft, 120, 220, 175, 25, COLOR_HOT_PINK, CYAN, BLACK, "Ok", 2); ok_btn.drawButton(); } void constant_gps_and_lux_data_loop() { /* Loop needs to be set on a timer, currently it executes once per second. Otherwise the serial read on the RPI will encounter many errors, mostly failed to read character, or outright failure, writing either "Fail" or "0.00" to file. I'm not presently sure why. But the solution is to slow it down, once a second seems to work excellently. I would guess the serial port on the RPI is just overloaded with data if it's not slowed down. */ unsigned long loopTimer = millis(); if (loopTimer - previousLoopTime >= loopTimingInterval) { previousLoopTime = loopTimer; int reqLength = (sizeof volts) + (sizeof lat) + (sizeof lon) + (sizeof alt); //Keeping track of the size of everything being transfered, so we can make sure it's all there, and not send gibberish. int n = Wire.requestFrom(slaveAddress, reqLength); //Requesting bytes from the slave device if( n == reqLength ) { // Checks if the number of bytes received was that what was requested I2C_readAnything( volts); //Using Nick Gammon I2C library to read the GPS data coming off the RPI so we can display it I2C_readAnything( lat); I2C_readAnything( lon); I2C_readAnything( alt); //Converting the electrical data from the light sensor into a lux value float amps = volts / 10000.0; float microamps = amps * 1000000; lux = microamps * 2.0; Serial.println(lux); //Constantly printing the lux value to the serial so it can be read by the RPI and printed to the .csv file constantly. if (currentPage == 0){ //Setting up constant text items to display the GPS data from the RPI tft.setTextSize (3); tft.setCursor (80,60); tft.setTextColor (GREEN,BLACK); tft.println(lux); tft.setTextSize (2); tft.setTextColor (WHITE,BLACK); tft.setCursor (5,210); tft.println ("lat = "); tft.setCursor (78,210); tft.print(lat, 10); tft.setCursor (5,250); tft.println ("lon = "); tft.setCursor (78,250); //Set to 9, because due to particular geographic location lon has two digits in the integer-part. tft.print(lon, 9); tft.setCursor (5,290); tft.println ("alt = "); tft.setCursor (78,290); tft.print(alt); } //Calculating the average lux value for (int i=0; i < 40; i++) { average = average + lux; } average = average/40; //Printing the average lux value to the display every 15 seconds unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; if (currentPage == 0) { tft.setTextSize (3); tft.setCursor (90,160); tft.setTextColor (GREEN,BLACK); tft.println(average); } } if (Serial.available() > 0) { //Check if there's data to be read, this is data that's already stored in the serial buffer which holds 64 bytes. String gpsString = ""; String data[3]; //Defining the number of items in the data, which in this case is three, for lat, lon, and alt. while (Serial.available()) { //Pause to allow the byte to arrive in input buffer without jambling delay(2); //Read a single character from the buffer at a time char ch = Serial.read(); //Append that single character to the gpsString gpsString+= ch; } //Initialization of some tracker variables to keep track of the string location and the data index. int stringStart = 0; int gpsDataIndex = 0; for (int i=0; i < gpsString.length(); i++) { //Look for seperator comma appended to the end of rasperry pi GPS string data if(gpsString.charAt(i) == ',') { //Flush previous values from array to prevent random character noise and error. data[gpsDataIndex] = ""; //Save substring into array for each lat, lon, alt. data[gpsDataIndex] = gpsString.substring(stringStart, i); //Setup new string starting point until the next comma is found. stringStart = (i+1); gpsDataIndex++; } } } } else { Serial.println(F( "Fail")); //If something goes wrong, it prints a fail to the serial output } } } void loop(void) { //Critically important loop execution constant_gps_and_lux_data_loop(); //Setting up the "self location" and press functionality of the Adafruit_gfx buttons TSPoint p = ts.getPoint(); bool down = Touch_getXY(); back_btn.press(down && back_btn.contains(pixel_x, pixel_y)); menu_btn.press(down && menu_btn.contains(pixel_x, pixel_y)); confirm_btn.press(down && confirm_btn.contains(pixel_x, pixel_y)); cancel_btn.press(down && cancel_btn.contains(pixel_x, pixel_y)); ok_btn.press(down && ok_btn.contains(pixel_x, pixel_y)); if (currentPage == 0) { //Check if the page is correct before triggering a button if (p.z > 10 && p.z < 1000) { //Checks if the pressure applied to the screen is within range if (p.x > 668 && p.x < 854 && p.y > 778 && p.y < 867 && MINPRESSURE && p.z < MAXPRESSURE) { //Seems redundant, but touch input can be finicky, and having another pressure check reduces the chance of a mispress. menu_btn.drawButton(true); buttonMenu(); } } } /* For the following large, main buttons, they are going to be done "manually" in-stead of using the Adafruit_gfx buttons press functionality. This is because the Adafruit_gfx buttons are limited in their customizability and more specifically, didn't work well with the text I wanted to display on them. */ //Interesting Tree Button if (currentPage == 1) { if (p.z > 10 && p.z < 1000) { if (p.x > 155 && p.x < 840 && p.y > 155 && p.y < 236 && MINPRESSURE && p.z < MAXPRESSURE) { buttonNumber = 0; tft.drawRoundRect(10, 13, 220, 40, 18, MAGENTA); delay(200); tft.drawRoundRect(10, 13, 220, 40, 18, WHITE); confirmation_popup(); tft.setCursor(20,70); tft.println("of this cool"); tft.setCursor(20,85); tft.println("tree to the .csv?"); } } } //Interesting Geology Button, e.g boulders, cliff faces, canyon formations if (currentPage == 1) { if (p.z > 10 && p.z < 1000) { if (p.x > 155 && p.x < 840 && p.y > 277 && p.y < 370 && MINPRESSURE && p.z < MAXPRESSURE) { buttonNumber = 1; tft.drawRoundRect(10, 68, 220, 40, 18, MAGENTA); delay(200); tft.drawRoundRect(10, 68, 220, 40, 18, WHITE); confirmation_popup(); tft.setCursor(20,70); tft.println("of this geologic"); tft.setCursor(19,85); tft.println("formation to the"); tft.setCursor(19, 100); tft.println(".csv?"); } } } //Coffee Tree In Need Button, e.g it's sick and needs fertilizer if (currentPage == 1) { if (p.z > 10 && p.z < 1000) { if (p.x > 155 && p.x < 840 && p.y > 410 && p.y < 498 && MINPRESSURE && p.z < MAXPRESSURE) { buttonNumber = 2; tft.drawRoundRect(10, 123, 220, 40, 18, MAGENTA); delay(200); tft.drawRoundRect(10, 123, 220, 40, 18, WHITE); confirmation_popup(); tft.setCursor(20,70); tft.println("of this coffee"); tft.setCursor(19,85); tft.println("tree that needs"); tft.setCursor(19, 100); tft.println("attending to, "); tft.setCursor(19, 115); tft.println("to the .csv?"); } } } //Animal Sign Button if (currentPage == 1) { if (p.z > 10 && p.z < 1000) { if (p.x > 155 && p.x < 840 && p.y > 542 && p.y < 630 && MINPRESSURE && p.z < MAXPRESSURE) { buttonNumber = 3; tft.drawRoundRect(10, 178, 220, 40, 18, MAGENTA); delay(200); tft.drawRoundRect(10, 178, 220, 40, 18, WHITE); confirmation_popup(); tft.setCursor(20,70); tft.println("of this animal"); tft.setCursor(19,85); tft.println("sign to the .csv?"); tft.setCursor(19, 100); tft.println("attending to, "); tft.setCursor(19, 115); tft.println("to the .csv?"); } } } //Other Button, for anything else of note if (currentPage == 1) { if (p.z > 10 && p.z < 1000) { if (p.x > 155 && p.x < 840 && p.y > 667 && p.y < 760 && MINPRESSURE && p.z < MAXPRESSURE) { buttonNumber = 4; currentTime = millis(); tft.drawRoundRect(10, 233, 220, 40, 18, MAGENTA); delay(200); tft.drawRoundRect(10, 233, 220, 40, 18, WHITE); confirmation_popup(); tft.setCursor(20,70); tft.println("of this other"); tft.setCursor(19,85); tft.println("noteworthy locat-"); tft.setCursor(19, 100); tft.println("ion to the .csv?"); } } } if (currentPage == 2 && buttonNumber == 0) { if (confirm_btn.justPressed()) { confirm_btn.drawButton(true); //write current data to csv Serial.print(lux); Serial.print(",0"); Serial.println(); for (int i = 0; i < thickness; i++) { tft.drawRoundRect(10 + i, 11 + i, 220 - i*2, 303 - i*2 , curvature, COLOR_HOT_PINK); delay(150); } OK_popup(); tft.setTextColor (BLACK); tft.setCursor(20,90); tft.println("GPS location and"); tft.setCursor(20,105); tft.println("lux data of" ); tft.setCursor(20,120); tft.println("tree successfully"); tft.setCursor(20,135); tft.println("written to the"); tft.setCursor(20,150); tft.println(".csv file"); } } /* Controlling what happens when a specific button is pressed, essentially when a button is pressed, it sends the current lux value to the RPI, along with a number that marks which button was just pressed. In addition the border of the button turns pink just for asthetics, and on the butttons respective confirmation screens, it prints the appropriate text. */ if (currentPage == 2 && buttonNumber == 1) { if (confirm_btn.justPressed()) { confirm_btn.drawButton(true); //write current data to csv Serial.print(lux); Serial.print(",1"); Serial.println(); for (int i = 0; i < thickness; i++) { tft.drawRoundRect(10 + i, 11 + i, 220 - i*2, 303 - i*2 , curvature, COLOR_HOT_PINK); delay(150); } OK_popup(); tft.setCursor(20,90); tft.println("GPS location and"); tft.setCursor(20,105); tft.println("lux data of" ); tft.setCursor(20,120); tft.println("geology formation"); tft.setCursor(20,135); tft.println("successfully "); tft.setCursor(20,150); tft.println("written to the"); tft.setCursor(20,165); tft.println(".csv file"); } } if (currentPage == 2 && buttonNumber == 2) { if (confirm_btn.justPressed()) { confirm_btn.drawButton(true); //write current data to csv Serial.print(lux); Serial.print(",2"); Serial.println(); for (int i = 0; i < thickness; i++) { tft.drawRoundRect(10 + i, 11 + i, 220 - i*2, 303 - i*2 , curvature, COLOR_HOT_PINK); delay(150); } OK_popup(); tft.setCursor(20,90); tft.println("GPS location and"); tft.setCursor(20,105); tft.println("lux data of" ); tft.setCursor(20,120); tft.println("coffee tree"); tft.setCursor(20,135); tft.println("successfully "); tft.setCursor(20,150); tft.println("written to the"); tft.setCursor(20,165); tft.println(".csv file"); } } if (currentPage == 2 && buttonNumber == 3) { if (confirm_btn.justPressed()) { confirm_btn.drawButton(true); //write current data to csv Serial.print(lux); Serial.print(",3"); Serial.println(); for (int i = 0; i < thickness; i++) { tft.drawRoundRect(10 + i, 11 + i, 220 - i*2, 303 - i*2 , curvature, COLOR_HOT_PINK); delay(150); } OK_popup(); tft.setCursor(20,90); tft.println("GPS location and"); tft.setCursor(20,105); tft.println("lux data of" ); tft.setCursor(20,120); tft.println("animal sign"); tft.setCursor(20,135); tft.println("successfully "); tft.setCursor(20,150); tft.println("written to the"); tft.setCursor(20,165); tft.println(".csv file"); } } if (currentPage == 2 && buttonNumber == 4) { if (confirm_btn.justPressed()) { confirm_btn.drawButton(true); //write current data to csv Serial.print(lux); Serial.print(",4"); Serial.println(); for (int i = 0; i < thickness; i++) { tft.drawRoundRect(10 + i, 11 + i, 220 - i*2, 303 - i*2 , curvature, COLOR_HOT_PINK); delay(150); } OK_popup(); tft.setCursor(20,90); tft.println("GPS location and"); tft.setCursor(20,105); tft.println("lux data of"); tft.setCursor(20,120); tft.println("other noteworthy"); tft.setCursor(20,135); tft.println("spot successfully"); tft.setCursor(20,150); tft.println( "written to the"); tft.setCursor(20,165); tft.println(".csv file"); } } //Back to home page button if (currentPage == 1) { if (back_btn.justPressed()) { back_btn.drawButton(true); homeScreen(); delay(100); } } //Confirmation popup "cancel" button, no need for any "ifs" like the confirm button, since it alwats does the same thing. if (currentPage == 2) { if (cancel_btn.justPressed()) { cancel_btn.drawButton(true); delay(200); } if (cancel_btn.justReleased()) { cancel_btn.drawButton(); buttonMenu(); } } //The "ok" button after the data has been sent to the RPI if (currentPage == 3) { if (ok_btn.justPressed()) { ok_btn.drawButton(true); delay(100); } if (ok_btn.justReleased()) { ok_btn.drawButton(); delay(300); buttonMenu(); } } } //End of loop
true
9642c8696eaec4ab9c54b18023f825fe3bf764f7
C++
hchen106/Appointment_System
/Appointment_System/src/controller/LoginUIController.cpp
UTF-8
3,549
2.609375
3
[]
no_license
#include "controller.h" #include "src/model/tcpConnection.h" #include <iostream> using namespace boost::asio; Controller::LoginUIController::LoginUIController(std::string IP , int PORT, boost::asio::io_service& io_service, boost::asio::ssl::context& context) : io_service_(io_service), socket_(io_service_), tcp_socket(io_service, context), context_(context){ //TODO: this->IP = IP; this->PORT = PORT; //boost::asio::io_service io_service; this->TcpConnection(); } void Controller::LoginUIController::closeConnection() { std::string command = "server logout"; std::cout << command << std::endl; boost::system::error_code error; boost::asio::write(new_connection->socket(), boost::asio::buffer(command),error); } Controller::MainWindowUIController* Controller::LoginUIController::createMainWindowController() { Controller::MainWindowUIController *controller = new Controller::MainWindowUIController(new_connection,loginID); return controller; } void Controller::LoginUIController::TcpConnection() { //TODO: //boost::asio::io_service io_service; //this->tcp_socket = boost::shared_ptr<ip::tcp::socket>(new ip::tcp::socket(io_service)); //this->tcp_socket = boost::shared_ptr<ip::tcp::socket> tcp_socket; //this->tcp_socket->connect(ip::tcp::endpoint(boost::asio::ip::address::from_string(this->IP),this->PORT)); new_connection = tcpConnection::create(io_service_,context_); new_connection->socket().connect(ip::tcp::endpoint(boost::asio::ip::address::from_string(this->IP),this->PORT)); //boost::system::error_code error; //boost::array<char, 128> buf; //boost::system::error_code error; //size_t len = socket_.read_some(boost::asio::buffer(buf), error); //boost::array<char, 128> buf; //boost::asio::streambuf buffer; //std::size_t len = boost::asio::read(socket_,boost::asio::buffer(buf)); //std::cout.write(buf.data(), len) << std::endl; //std::cout << buffer << std::endl; //boost::asio::write(*(this->tcp_socket), boost::asio::buffer("hello\n"),error); /* if(!error) { std::cout << "Successful" << std::endl; }else { std::cout << "Failed" << error.message() << std::endl; } */ std::cout << "Connected" << std::endl; } std::string Controller::LoginUIController::isVertified(std::string username, std::string password){ //TODO: boost::system::error_code error; std::string mes = " " + username + " " + password; std::string command = "server vertify" + mes; boost::asio::write(new_connection->socket(), boost::asio::buffer(command),error); if(!error) { //std::cout << "Successfully sent command" << std::endl; boost::array<char, 128> buf; boost::asio::streambuf buffer; //std::size_t len = boost::asio::read(socket_,boost::asio::buffer(buf)); size_t len = new_connection->socket().read_some(boost::asio::buffer(buf), error); //std::cout.write(buf.data(), len) << " Logined."<< std::endl; loginID = username; return buf.data(); }else { //std::cout << "Failed to send message" << error.message() << std::endl; return "Failed to send message"; } /* boost::asio::write(socket_, boost::asio::buffer(mes),error); if(!error) { std::cout << "Successful" << std::endl; }else { std::cout << "Failed" << error.message() << std::endl; } */ }
true
6b310d6da295817aab72e5d14dd87a5688d00a0c
C++
MaSteve/UVA-problems
/UVA11185.cpp
UTF-8
385
2.953125
3
[ "MIT" ]
permissive
#include <iostream> #include <stack> using namespace std; int main() { int n; stack<char> s; while (cin >> n && n >= 0) { while (n >= 3) { s.push(n%3 + '0'); n /= 3; } s.push(n + '0'); while (!s.empty()) { printf("%c", s.top()); s.pop(); } printf("\n"); } return 0; }
true
dccedacb2a6d7d7658edef9a6e2536bb6794f233
C++
sos0911/PS_Cpluslplus
/Cppcont/src/CPP_Src/Chapter 16 source/DynamicPolymorphicCasting.cpp
UTF-8
324
3.140625
3
[]
no_license
#include <iostream> using namespace std; class AAA { public: virtual void ShowSimple() { cout<<"AAA"<<endl; } }; class BBB: public AAA { public: void ShowSimple() { cout<<"BBB"<<endl; } }; int main(void) { AAA * ptr1 = new BBB; BBB * ptr2 = dynamic_cast<BBB*>(ptr1); return 0; }
true
261b9c79617be294f403df5dfe5f3ba3f7bb1241
C++
tslothorst/Learning-Cpp
/Section9/SumofOddInts/SumofOddInts/main.cpp
UTF-8
231
2.90625
3
[ "MIT" ]
permissive
#include "main.h" #include<iostream> using namespace std; int main() { int sum{}; for (int i = 0; i <= 15; ++i) { if (i % 2 > 0) { cout << i << endl; sum += i; } } cout << "sum is: " << sum << endl; return 0; }
true
fa0803acc24b8375461e30dfadbae5e65aa8369c
C++
Jasper-Shi/Milestone-oop345
/ms3/ms3/order.cpp
UTF-8
2,553
3.328125
3
[]
no_license
#include <iostream> #include <fstream> #include <vector> #include <string> #include "util.h" using namespace std; class Order { string orderCustomer, orderProduct; vector<string> itemList; public: Order(vector<string> row) { if (row.size() < 3) { throw std::string("Expected 3 or more fields, found ") + std::to_string(row.size()); } if (validCustomerName(row[0])) { orderCustomer = row[0]; } else { throw std::string("Expected a customer name --- found '") + row[0] + "'"; } if (validProductName(row[1])) { orderProduct = row[1]; } else { throw std::string("Expected a customer name --- found '") + row[1] + "'"; } for (auto i = 2; i < row.size(); i++) { if (validItemName(row[i])) itemList.push_back(row[i]); else throw std::string("Expected a customer name --- found '") + row[i] + "'"; } } void print() { std::cout << " /Customer/Product/Items .../ = " << "/" << orderCustomer << "/" << orderProduct ; for (auto item : itemList) std::cout << "/" << item; std::cout << "\n"; } void graph(fstream& os) { std::string q = "\""; for (auto item : itemList) os << q << orderCustomer + ":" + orderProduct << q << " -> " << q << item << q << "[color=blue];\n"; } }; class OrderManager { vector< Order > orderList; public: OrderManager(vector < vector< string > > & csvData) { for (auto& row : csvData) { try { if (row.size() > 2) orderList.push_back(std::move(Order(row))); } catch (const std::string& e) { std::cerr << e << "\n"; } } } void print() { for (auto e : orderList) e.print(); } void graph(string& filename) { std::string f = filename + ".gv"; std::fstream os(f, std::ios::out | std::ios::trunc); os << "digraph orderGraph {\n"; for (auto t : orderList) { t.graph(os); } os << "}\n"; os.close(); std::string cmd = std::string("dot -Tpng ") + filename + ".gv > " + filename + ".gv.png"; std::cout << cmd << " returned " << system(cmd.c_str()) << "\n"; } }; int main(int argc, char*argv[]) { try { if (argc != 3) { throw string("Usage ") + argv[0] + string(": filename delimiter-char"); } string filename = string(argv[1]); // 1st arg is filename char delimiter = argv[2][0]; // 2nd arg, 1st char is delimiter vector < vector< string > > csvOrderData; csvReader(filename, delimiter, csvOrderData); // csvPrint(csvOrderData); OrderManager om(csvOrderData); om.print(); om.graph(filename); } catch (const string& e) { cerr << e << "\n"; } }
true
1937b20322193898c0eee0a9898e5adb69cc1623
C++
DIC3BlOCK/POO_Devoir-2
/LigueHockeyApp.cpp
UTF-8
6,453
2.796875
3
[]
no_license
/*---------------------------------------------------------------------*/ /* FICHIER: LigueHockeyApp.cpp */ /* */ /* AUTEUR(S): Thomas Bergeron, Alex Roberge */ /* */ /* DATE: 2021/02/10 */ /* */ /* DESCRIPTION: Fonction principale du programme. L'éxécution de celui-*/ /* ci commence à cet endroit. */ /*---------------------------------------------------------------------*/ #include "Inclusion.h" #include "Club.h" #include "Ecran.h" #include "Parcours.h" #include "Joueur.h" #include "Palmares.h" #include "Entraineur.h" #include "TitreGagne.h" #include "LigueHockey.h" #include "Date.h" #include "Periode_Resultat.h" void CreerValeursDefaut(vector<Club*> &clubs); int main() { setlocale(LC_CTYPE, "fr-FR"); Periode test(2, 4); Resultat test2(5, 7); cout << test.nbButsLocal << endl << test2.nbButsLocal; /* vector<Club*> clubs; CreerValeursDefaut(clubs); LigueHockey* ligue = new LigueHockey(clubs); Ecran ecranPrincipal (ligue); ecranPrincipal.MenuPrincipal(); delete ligue;*/ return EXIT_SUCCESS; } void CreerValeursDefaut(vector<Club*> &clubs) { /* Cette fonction sert pour tester le programme principal. Elle crée des objets par défaut. */ //Construction d'objets club par défaut Club* club01 = new Club("Club #1", "histoire du club #1", "couleur du club #1", 2001, "Ville du club #1", "adresse du club #1"); Club* club02 = new Club("Club #2", "histoire du club #2", "couleur du club #2", 2002, "Ville du club #2", "adresse du club #2"); Club* club03 = new Club("Club #3", "histoire du club #3", "couleur du club #3", 2003, "Ville du club #3", "adresse du club #3"); Club* club04 = new Club("Club #4", "histoire du club #4", "couleur du club #4", 2003, "Ville du club #4", "adresse du club #4"); Club* club05 = new Club("Club #5", "histoire du club #5", "couleur du club #5", 2003, "Ville du club #5", "adresse du club #5"); //Construction de parcours de joueurs vector<Parcours*> parcoursJ1; Parcours* parcoursJoueurUn = new Parcours("clubNom1", "datePassageParcours1"); parcoursJ1.push_back(parcoursJoueurUn); vector<Parcours*> parcoursJ2; Parcours* parcoursJoueurdeux = new Parcours("clubNom2", "datePassageParcours2"); parcoursJ2.push_back(parcoursJoueurdeux); vector<Parcours*> parcoursJ3; Parcours* parcoursJoueurtrois = new Parcours("clubN2om3", "datePassageParcours3"); parcoursJ2.push_back(parcoursJoueurtrois); vector<Parcours*> parcoursJ4; Parcours* parcoursJoueurquatre = new Parcours("clubN2om4", "datePassageParcours4"); parcoursJ2.push_back(parcoursJoueurquatre); //Ajout de joueurs Joueur* j = new Joueur("Thomas", "Bergeron", 1.5f, 120, "villeNaissance", parcoursJ1); Joueur* j2 = new Joueur("Alex", "Roberge", 100, 54, "Sainte-Monique", parcoursJ2); Joueur* j3 = new Joueur("joueur3", "famille3", 123, 456, "villeNaissanceJ3", parcoursJ3); Joueur* j4 = new Joueur("joueur4", "famille4", 1020, 524, "villeNaissanceJ4", parcoursJ4); //Ajout du/des joueur(s) au club. club01->ajouterJoueur(j); club01->ajouterJoueur(j2); club02->ajouterJoueur(j3); club02->ajouterJoueur(j4); //palmarès des clubs Palmares* p1 = new Palmares("coupe stanley", "15 decembre 2001"); Palmares* p2 = new Palmares("coupe memorial", "demain"); Palmares* p3 = new Palmares("burger coupe", "2 juillet 1965"); Palmares* p4 = new Palmares("coupe #4", "date #4"); Palmares* p5= new Palmares("coupe #5", "date #5"); Palmares* p6 = new Palmares("coupe #6", "date #6"); Palmares* p7 = new Palmares("coupe #7", "date #7"); Palmares* p8 = new Palmares("coupe #8", "date #8"); vector<Palmares*> pal01; pal01.push_back(p1); pal01.push_back(p2); pal01.push_back(p3); pal01.push_back(p4); vector<Palmares*> pal02; pal02.push_back(p5); pal02.push_back(p6); vector<Palmares*> pal03; pal03.push_back(p7); vector<Palmares*> pal04; pal03.push_back(p8); club01->setPalmares(pal01); club02->setPalmares(pal02); club03->setPalmares(pal03); club04->setPalmares(pal04); //Liste de titres gagnées, pour tester l'option numéro 2 du menu (invite de commande). TitreGagne* titre01 = new TitreGagne("titre1", "22 novembre 1964", "Club #1"); TitreGagne* titre02 = new TitreGagne("titre2", "23 novembre 1965", "Club #1"); //Réserver pour l'entraîneur 1, qui sera le plus titré (pour tester). TitreGagne* titre03 = new TitreGagne("titre3", "12 novembre 1970", "Club #1"); /*---------------------------------------------------------------------------*/ TitreGagne* titre04 = new TitreGagne("titre4", "25 décembre 1999", "Club #2"); TitreGagne* titre05 = new TitreGagne("titre5", "13 septembre 2001", "Club #4"); TitreGagne* titre06 = new TitreGagne("titre6", "12 novembre 3456", "Club #5"); TitreGagne* titre07 = new TitreGagne("Aucun", "", ""); // Ceci crée un entraîneur, lui ajoute un titre et ajoute ensuite cet entraîneur à un club. PS: peut=être faire un sous-programme si on le présente. Entraineur* entraineur01 = new Entraineur("Potvin", "Ivan", "Boîte de céréales"); entraineur01->AjouterTitreGagne(titre01); entraineur01->AjouterTitreGagne(titre02); //Devrait être l'entraîneur le + titré. entraineur01->AjouterTitreGagne(titre03); club01->setEntraineur(entraineur01); Entraineur* entraineur02 = new Entraineur("Massé", "Manon", "lieu d'obtention de grade 2"); entraineur02->AjouterTitreGagne(titre04); club02->setEntraineur(entraineur02); Entraineur* entraineur03 = new Entraineur("Traillette", "Mami", "lieu d'obtention de grade 3"); entraineur03->AjouterTitreGagne(titre05); club03->setEntraineur(entraineur03); Entraineur* entraineur04 = new Entraineur("Neutron", "Jimmy", "Laboratoire"); entraineur04->AjouterTitreGagne(titre06); club04->setEntraineur(entraineur04); Entraineur* entraineur05 = new Entraineur("Ou-roche", "Caillou", "lieu d'obtention de grade 2"); entraineur05->AjouterTitreGagne(titre07); club05->setEntraineur(entraineur05); //Envoie du club à une liste de clubs (sert entre autre à trouver le club le + titré). clubs.push_back(club01); clubs.push_back(club02); clubs.push_back(club03); clubs.push_back(club04); clubs.push_back(club05); }
true
dcf5ea084b9e9488c7d32c6c1684c4ba260be57a
C++
lineCode/ABx
/abserv/abserv/CollisionComp.h
UTF-8
553
2.90625
3
[]
no_license
#pragma once namespace Game { class Actor; namespace Components { /// Only an Actor can have a CollisionComp, because only moving objects need it. class CollisionComp { private: Actor& owner_; public: CollisionComp() = delete; explicit CollisionComp(Actor& owner) : owner_(owner) { } // non-copyable CollisionComp(const CollisionComp&) = delete; CollisionComp& operator=(const CollisionComp&) = delete; ~CollisionComp() = default; void Update(uint32_t timeElapsed); void ResolveCollisions(); }; } }
true
d8522ab7fd47abfe0d75a944c0b2058db68f6f81
C++
RodrigoHolztrattner/Wonderland
/Wonderland/Wonderland/Source/Engine/Wonderland.cpp
ISO-8859-1
11,407
2.515625
3
[ "MIT" ]
permissive
// Wonderland.cpp : Defines the entry point for the console application. // #define GLFW_INCLUDE_VULKAN //#include <pthread.h> // #include "SystemClass.h" #include <fstream> #include <iterator> #include <algorithm> #include <map> #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> /* => The engine will be divided by modules: - Thread library - System specific - __InternalPeonJob stealing system - Multitasking for all module - File explorer (IO file system) - With cached/temporary/predicted data - Core (main engine functionality) - Entity-component system - Data driven (oriented) - Physics engine - Sound engine - Resource deployer - Shader composer (collection of shaders) - Super-shader support - Shard library (network system) - Void connection support */ /* => Systems so criados logo na inicializao da engine, logo, no precisam de algum tipo especial de controlador e podem usar o new/delete. => Componentes so os objetos que podem ser criados dinamicamente e persistem durante frames, eles devem ser criados em forma de array (e no vetor de ponteiros) e devem suportar vrios threads. Devemos usar um modelo especial de alocao para eles: - Toda criao de componente deve inicialmente feita usando-se a memria temporria e depois esta sendo copiada para a rea permanente. => Particle Emitter solicita nova particula => Entidade e Position Component criados => Adiciono o Position Component na sua array de controle => Problema pois outra thread pode estar atualizando a array de controle ou mesmo adicionando outro elemento => Solues: Mutex (NO), atualizao no problema e podemos dar um jeito do adicionamento ser thread-safe => Novo problema: Deleo de componentes => Um componente s pode ser deletado se OU a entidade a qual ele pertence for deletada OU o componente em si no utilizado como dependencia de algum outro componente OU o componente ou possui alguma dependencia, mas esta dependencia tambm o possui como dependencia (assim, deletando todo o conjunto de dependencia) (mutualmente dependentes, embora isso no deveria existir). Seguindo essa regra nunca precisaremos informar outros componentes da deleo de algum irmo. => Um componente marcado para deleo dever ter sua estrutura de linked-list editada e a deleo propria ser realizada na fase final do update frame => Talvez o component vector deva saber do escopo do objeto base componente e permitir iterar automaticamente fazendo update e verificando o deletion status. */ // #include "Common\Entity Component\ComponentVector.h" /* => Por testes melhor que a gente use vrios threads para ler arquivos => O ideal que cada thread tenha sempre um FILE para cada arquivo que ele possa ler => Threads usando FILEs compartilhados so lentos => Criao de FILEs desprezvel => Usar mesmo sistema do job system => Pensar em uma implementao genrica para o job system */ //aqui: /* - Criar um command pool "per-thread" com cada uma das caracteristicas possveis - Criar um tipo de command buffer inteligente que pode variar do tipo que tem pre alocado um para cada imagem (esttico), ou desaloca e remontado quase que a cada frame (semi-esttico) ou remontado sempre a cada frame (dinmico). - Diferente do OpenGL e DirectX onde tinhamos um objeto (unidade) e ela continha o seu vertex/index buffer, texture reference, etc e na hora de renderizar puxavamos todos esses dados no shader e renderizavamos usando instanced, aqui devemos criar uma especie de "layout" de renderizao. - Esse layout ir ser como um buffer de vertices mas alm disso possuir dados referentes binding de texturas e uniform buffers, logo, diferentemente de como faziamos generalizando os objetos dos shaders e depois enviando para renderizao separadamente, aqui precisamos criar esse link logo de inicio. - Preciso ver como fao para usar esse template do Descriptor Set para vrios objetos, at certo ponto eu sei criar s o template mas aparentemente na hora que eu fao um VkDescriptorSet eu "linko" os dados, sendo que para cada objeto eu deveria atualiz-los, devo ter vrios destes e criar um render pass para cada objeto? - Se eu quero renderizar apenas um tipo de objeto alterando posies e tal fcil, s usar instancing e atualizar o uniform buffer (usar uma array e renderizar por batches), agora caso eu queira usar um "shader" para vrios objetos eu preciso atualizar o vertex buffer, texture, etc. At para instancing eu talvez precisasse atualizar o buffer de textura (na real posso enviar vrias tex por vez e usar um index para pegar elas). */ #include "..\..\Editor\System\MainViewController.h" #include "..\..\Editor\Foundation\ECS\ECS_Component.h" #include "..\..\Editor\Foundation\ECS\ECS_Entity.h" #include "..\..\Editor\Foundation\ECS\ECS_System.h" // #include "..\..\Editor\Foundation\UI\UIView.h" #include "..\..\Editor\Modules\Flux\Flux.h" #include "..\..\Editor\Application.h" // // // #include "..\..\Editor\Modules\Peon\Peon.h" #include <functional> #include <iostream> #include <vector> int main() { // Our application initialization params Application::InitializationParams initParams = {}; initParams.sApplicationName = "Chronicles of a Fallen Soul"; initParams.sEngineName = "Wonderland"; initParams.sApplicationVersion = VK_MAKE_VERSION(0, 0, 1); initParams.sEngineVersion = VK_MAKE_VERSION(0, 0, 1); initParams.sTotalNumberPeonThreads = 4; initParams.sThreadRingBufferSize = 65000; // Create and initialize the main application Application mainApplication = {}; if (!mainApplication.Initialize(initParams)) { return false; } // Run the main loop mainApplication.MainLoop(); // bool result; // // Get all creator a register instances we need Flux::ClassCreator* classCreatorInstance = Flux::ClassCreator::GetInstance(); Flux::ClassRegister* classRegisterInstance = Flux::ClassRegister::GetInstance(); Flux::TypeCreator* typeCreatorInstance = Flux::TypeCreator::GetInstance(); Flux::TypeRegister* typeRegisterInstance = Flux::TypeRegister::GetInstance(); Flux::DynamicMemberFunctionCreator* memberFunctionCreatorInstance = Flux::DynamicMemberFunctionCreator::GetInstance(); // Basic type registration // Flux::Type* intType = typeCreatorInstance->CreateType("int"); Flux::Type* floatType = typeCreatorInstance->CreateType("float"); Flux::Type* charType = typeCreatorInstance->CreateType("char"); Flux::Type* stringType = typeCreatorInstance->CreateType("string"); Flux::Type* booleanType = typeCreatorInstance->CreateType("bool"); Flux::Type* vectorType = typeCreatorInstance->CreateType("vector"); // Class creation // // Create a new class Flux::Class* newClass = classCreatorInstance->CreateClass("Car"); if (newClass == nullptr) { return false; } // Create a variable from the created class Flux::MemberVariable speedVariable; result = speedVariable.Build(floatType, "m_Speed"); if (!result) { return false; } // Add the member variable result = newClass->AddMemberVariable(speedVariable); if(!result) { return false; } // Create a variable from the created class Flux::MemberVariable distanceVariable; result = distanceVariable.Build(intType, "m_CurrentDistance"); if (!result) { return false; } // Add the member variable result = newClass->AddMemberVariable(speedVariable); if (!result) { return false; } // Create a variable from the created class Flux::MemberVariable costVariable; result = costVariable.Build(floatType, "m_CostPerDistance"); if (!result) { return false; } // Add the member variable result = newClass->AddMemberVariable(speedVariable); if (!result) { return false; } // Function creation // // Create the nem member function Flux::DynamicMemberFunction* newFunction = memberFunctionCreatorInstance->CreateDynamicMemberFunction("CalculateTime", *newClass); if (newFunction == nullptr) { return false; } /* - Handle precisa ter um id de verso */ /* => Dynamic Function: - Head -> Definies de uma funo (qual o nome, se pertence uma classe, quais entradas... etc) - Body -> Como esta definido o seu corpo, quais funes (boxes) so utilizados, quais foram as ligaes efetuadas, variveis utilizadas... etc - Linker -> Realizao da compilao da DynamicFunction em realtime. */ /* - Vamos ter uma nova classe que vai ser tipo um box, ele vai contar o ponto inicial, final e vai possuir blocos que vo se ligar entre si, esses blocos fazem referncia um box conectado. - Comeando no bloco inicial, vamos ir para o proximo, aqui podemos ter por exemplo uma funo membro, nosso objetivo ser pegar os dados da funo membro, fazer a chamada com ela utilizando as variveis linkadas (nota que no foi incluido a gerao dos nomes das variveis). - Aps isso vamos para a proxima funo, que pode ser um loop por exemplo, o loop deve criar uma varivel que vai ser o contador e usar os parmetros de entrada para realizar as chamadas seguintes. - Da pra perceber que o ideal fechar cada bloco, por exemplo no primeiro, podemos passar as variveis linkadas aos sockets de entrada para o "fechador" da funo membro utilizada e ela fica responsvel por usar essas entradas e gerar a chamada, podendo at mesmo retornar e assim seguimos para a proxima box ou continuar por conta propria. - No segundo exemplo nos iriamos para um loop, ele vai ter os valores de entrada (index inicial, final, etc) e provavelmente deveriamos continuar a execuo por conta propria. - Temos que pensar em como vamos fazer os ifs, os sequences, sets, gets, for eachs, prints, etc... So todas funes standard, intrinsic. - Talvez devemos separar tipo, funes membro, funes normais, loop for, if, set, get e assim vai... S que as funes (tanto membro quando normais) existiriam de vrias formas precisando serem registradas enquanto os outros seriam classes especializadas que no precisariam serem registradas, afinal j teriamos uma de cada tipo. - O ideal seria que tivermos uma forma de criar essas funes intrinsics, talvez seja possvel faze-las na parte de funes normais ou quem sabe fazer um criador para elas. */ /* - Uma box pode ter inputs e outputs, no importa qual o tipo de box. - Uma input/output pode ser de vrios tipos. - Uma box pode ser uma funo, uma caixa de debug, um start ou end dentro de uma funo, etc. - Uma input/output pode ser uma varivel, um valor absoluto, uma constante, etc. - Uma input/output pode ter um valor temporrio para teste na engine. - Uma input/output pode ser uma array, nesse caso ele no pode possuir um valor absoluto e sim deve ser uma varivel. - Uma box SEMPRE deve ter (se tiver) apenas UMA entrada. - Uma box pode ter vrias sadas desde que mantenha em mente que as sadas sero executadas em sequncia (depende da interpretao da box) */ //////////////// // INITIALIZE // //////////////// MainViewController viewController; viewController.Initialize(); //////////////////////// //////////////////////// //////////////////////// return 0; }
true
2bbc66864c7ea13cdd2fcf90a7865a7d075a9ce2
C++
UnendingGlory/Cplusplus_Primer
/ch15/15_28.h
UTF-8
4,168
3.765625
4
[]
no_license
// define the Quote and Bulk_quote copy-control members #ifndef CH_15_28_H #define CH_15_28_H #include <string> #include <iostream> using std::string; class Quote { private: std::string bookNo; protected: // 允许派生类访问 double price = 0.0; public: Quote() { std::cout << "Quote : default constructing\n"; }; Quote(const string &book, double sales_price) : bookNo(book), price(sales_price){ std::cout << "Quote : constructor taking 2 parameters\n"; } // copy constructor Quote(const Quote &q) : bookNo(q.bookNo), price(q.price){ std::cout << "Quote : copy constructing\n"; } // move constructor Quote(Quote && q) noexcept : bookNo(std::move(q.bookNo)), price(std::move(q.price)){ std::cout << "Quote : move constructing\n"; } // copy = Quote& operator=(const Quote &rhs) { // tackle self-assgin if(this != &rhs) { bookNo = rhs.bookNo; price = rhs.price; } std::cout << "Quote : copy-assignment operator\n"; return *this; } // move = Quote& opertor(Quote &&rhs) { if(this != &rhs) { bookNo = std::move(rhs.bookNo); price = std::move(rhs.price); } std::cout << "Quote : move-assignment operator\n"; return *this; } // destructing virtual ~Quote() { std::cout << "Quote : destructing\n"; }; // the caller of the function is a lvalue virtual Quote* clone() const & { return new Quote(*this); } // the caller of the function is a rvalue virtual Quote* clone() const && { return new Quote(std::move(*this)); } string isbn() const { return bookNo; } // 返回给定数量的书籍的销售总额 // 派生类负责改写并使用不同的折扣计算算法(对于每一本书来说) virtual double net_price(std::size_t n) const { // n为销售额 return n * price; } }; class Bulk_quote : public Quote{ public: Bulk_quote() { std::cout << "Bulk_quote : default constructing\n"; } // 调用基类的构造函数 Bulk_quote(const string &book, double p, size_t qty, double disc) : Quote(book, p), min_qty(qty), discount(disc){ std::cout << "Bulk_quote : constructor taking 2 parameters\n"; } // copy constructor Bulk_quote(const Bulk_quote &rhs) : Quote(rhs), min_qty(rhs.min_qty), discount(rhs.discount) { std::cout << "Bulk_quote : copy constructing\n"; } // move constructor Bulk_quote(Bulk_quote &&rhs) : Quote(std::move(rhs)), min_qty(std::move(rhs.min_qty)), discount(std::move(rhs.discount)) { std::cout << "Bulk_quote : move constructing\n"; } // copy-assignment Bulk_quote &operator=(const Bulk_quote &rhs) { // called the copy-assignment operator explicitly Quote::operator=(rhs); min_qty = rhs.min_qty; discount = rhs.discount; std::cout << "Bulk_quote : copy-assignment operator\n"; return *this; } // move-assignment Bulk_quote &operator=(Bulk_quote &&rhs) { // called the copy-assignment operator explicitly if(this != &rhs) { Quote::operator=(std::move(rhs)); min_qty = std::move(rhs.min_qty); discount = std::move(rhs.discount); std::cout << "Bulk_quote : move-assignment operator\n"; } return *this; } ~Bulk_quote() { std::cout << "Bulk_quote : destructing\n"; } // the caller of the function is a lvalue virtual Bulk_quote* clone() const & { return new Bulk_quote(*this); } // the caller of the function is a rvalue virtual Bulk_quote* clone() const && { return new Bulk_quote(std::move(*this)); } // 覆盖基类的函数版本以实现大量购买的折扣政策 double net_price(std::size_t) const override; private: size_t min_qty = 0; // 是用折扣政策的最小购买量min_quantity double discount = 0.0; // 以小数代表折扣额 }; double print_total(std::ostream &, const Quote &, size_t); #endif
true
86fc6d666f8b220f84d730fdddd3e441a2bc51da
C++
Jackiebibili/my_projects
/Arithmetic_OverFlowed/Node.h
UTF-8
424
3.1875
3
[]
no_license
#ifndef NODE_H #define NODE_H #include<iostream> #include<cstdlib> class Node { private: int num = 0; int loc = 0; Node* next = nullptr; public: Node(); //default constructor Node(int num); //overloading constructor Node(int pos, int num); Node(const Node& right); int getNum() const; int getPos() const; Node* getNext(); void setNum(int n); void setPos(int pos); void setNext(Node* ptr); ~Node(); }; #endif
true
cbf2ee8e23d4e3c922810fae672ae09afda087a4
C++
magicLeeFeng/HiveRender
/Hive/Hive/Math/ARPoint.h
WINDOWS-1252
730
2.515625
3
[]
no_license
/************************************************************************/ /* */ /************************************************************************/ #pragma once class ARVector3; class ARPoint { public: ARPoint(void); ~ARPoint(void); ARPoint(float x,float y,float z); ARPoint operator+(const ARVector3 &v) const; ARPoint operator+=(const ARVector3 &v); ARPoint operator-(const ARVector3 &v) const; ARVector3 operator-(const ARPoint &p) const; ARPoint operator-=(const ARVector3 &v); float distance(const ARPoint &a, const ARPoint &b); float distanceSuqared(const ARPoint &a,const ARPoint &b); public: float x; float y; float z; };
true
ca2413204c3845d00c3c0a1e20a121c6fb5b8b20
C++
namichie/CSI2372
/Project/Cardnanza/Deck.h
UTF-8
502
2.875
3
[]
no_license
#ifndef DECK_H #define DECK_H #include <istream> #include <vector> #include "Card.h" using namespace std; class CardFactory; class Deck { public: Deck() = default; Deck(istream & in, const CardFactory * cardFactory); static Deck randomizedDeck(CardFactory * cardFactory); bool isEmpty(); Card * draw(); void print(ostream & out) const; friend ostream & operator<<(ostream & out, const Deck & deck); private: vector<Card *> m_cards; }; #endif // !DECK_H
true
3463fcf20ee2945bbef250da92712fd5bacab74c
C++
yangyanzhe/GeometryManipulation
/src/PolygenPainter/paint.cpp
UTF-8
15,991
2.640625
3
[]
no_license
#include "paint.h" #include <windows.h> #include <winuser.h> #include <wingdi.h> #include <QDebug> #include <cmath> #include <stack> Paint::Paint() { frontColor = RGB(255, 127, 39); backColor = RGB(255, 255, 255); lineWidth = 2; range = 6; isDrawing = false; direction = true; withInnerCircle = false; map = NULL; currentPolygen = NULL; lastPolygen = NULL; lastNode = NULL; mmode = rectangle; clipPolygen = new Polygen; clipPolygenDone = false; } Paint::~Paint() { Polygen* p = map; Polygen* q; while(p!= NULL){ q = p->next; delete p; p = q; } //delete clipPolygen; } void Paint::drawBoundary(HDC &hdc, Polygen* poly) { if(poly == NULL) return; HPEN hPen = CreatePen(PS_SOLID, lineWidth, frontColor); SelectObject(hdc, hPen); Node* s = poly->begin; Node* q = s; Node* p = s->next; while(true){ POINT* m = q->itself; POINT* n = p->itself; MoveToEx(hdc, m->x, m->y, (LPPOINT) NULL); LineTo(hdc, n->x, n->y); q = p; p = p->next; if(q == s) break; } } void Paint::drawPolygen(HDC& hdc, POINT* p) { gHDC = hdc; if(isDrawing){ POINT* q = lastNode->itself; if(isFinished(p, currentPolygen)){ // drawing polygen ends delete p; p = currentPolygen->begin->itself; lastNode->next = currentPolygen->begin; isDrawing = false; //resortNodeArray(); if(!withInnerCircle){ fill(hdc, currentPolygen, backColor); drawBoundary(hdc, currentPolygen); } } else{ // continue drawing Node* mNode = new Node(); mNode->itself = p; mNode->next = NULL; lastNode->next = mNode; lastNode = mNode; } MoveToEx(hdc, q->x, q->y, (LPPOINT) NULL); LineTo(hdc, p->x, p->y); } else{ isDrawing = true; Polygen* sPoly = new Polygen(); Node* sNode = new Node(); sNode->itself = p; sNode->next = NULL; sPoly->begin = sNode; sPoly->next = NULL; sPoly->dir = direction; //qDebug() << direction << " " << withInnerCircle; if(direction && withInnerCircle){ currentInnerPolygen = sPoly; direction = false; } currentPolygen = sPoly; lastNode = sNode; if(!map){ // polygen set is null map = currentPolygen; lastPolygen = currentPolygen; } else{ lastPolygen->next = currentPolygen; lastPolygen = currentPolygen; //qDebug() << "connect to the next one"; } } } void Paint::drawSquare(HDC& hdc, POINT* p) { gHDC = hdc; if(isDrawing){ POINT* q = lastNode->itself; Node* nodeTwo = new Node(); Node* nodeThree = new Node(); Node* nodeFour = new Node(); POINT* pTwo = new POINT(); POINT* pFour = new POINT(); pTwo->x = p->x; pTwo->y = q->y; pFour->x = q->x; pFour->y = p->y; nodeFour->itself = pFour; nodeFour->next = lastNode; nodeThree->itself = p; nodeThree->next = nodeFour; nodeTwo->itself = pTwo; nodeTwo->next = nodeThree; lastNode->next = nodeTwo; isDrawing = false; if(!withInnerCircle) fill(hdc, currentPolygen, backColor); //qDebug() << "finish the fill operation."; HPEN hPen = CreatePen(PS_SOLID, lineWidth, frontColor); SelectObject(hdc, hPen); MoveToEx(hdc, q->x, q->y, (LPPOINT) NULL); LineTo(hdc, q->x, p->y); MoveToEx(hdc, q->x, p->y, (LPPOINT) NULL); LineTo(hdc, p->x, p->y); MoveToEx(hdc, p->x, p->y, (LPPOINT) NULL); LineTo(hdc, p->x, q->y); MoveToEx(hdc, p->x, q->y, (LPPOINT) NULL); LineTo(hdc, q->x, q->y); //resortNodeArray(); // resort the node according to the direction } else{ isDrawing = true; Polygen* sPoly = new Polygen(); Node* sNode = new Node(); sNode->itself = p; sNode->next = NULL; sPoly->begin = sNode; sPoly->next = NULL; sPoly->dir = direction; if(direction && withInnerCircle){ currentInnerPolygen = sPoly; direction = false; } currentPolygen = sPoly; lastNode = sNode; if(!map){ // polygen set is null map = currentPolygen; lastPolygen = currentPolygen; } else{ lastPolygen->next = currentPolygen; lastPolygen = currentPolygen; } } } void Paint::drawPolygenWithInnerCircle(HDC &hdc, POINT *p) { if(mmode == polygen){ drawPolygen(hdc, p); } else if(mmode == rectangle){ drawSquare(hdc, p); } } //void Paint::drawEclipse(HDC &hdc, POINT *p) bool Paint::isFinished(POINT* p, Polygen* poly) { // compare p with the start point POINT* s = poly->begin->itself; int x = s->x - p->x; int y = s->y - p->y; if(-range <= x && x <= range && -range <= y && y <= range ){ p->x = s->x; p->y = s->y; return true; } else{ return false; } } // resort the node according to the direction void Paint::resortNodeArray() { } // fill the polygen with backcolor void Paint::fill(HDC &hdc, Polygen* p, COLORREF color) { int ymin = 0; int ymax = 0; int xmin = 0; int xmax = 0; findBoundary(ymin, ymax, xmin, xmax, p); //qDebug() << xmin << " " << xmax << " " << ymin << " " << ymax; int size = (xmax - xmin + 1) * (ymax - ymin + 1); //qDebug() << "size " << size; int* map = new int [size]; memset(map, 0, size * sizeof(int)); // 0-out; 2-edge; 1-inner markEdge(map, xmin, ymin, xmax-xmin+1, p); markCorner(map, xmin, ymin, xmax-xmin+1, ymax-ymin+1, p); //markEdge(hdc, map, xmin, ymin, xmax-xmin+1, p); HPEN hPen = CreatePen(PS_SOLID, lineWidth, color); SelectObject(hdc, hPen); scanFill(map, xmax-xmin+1, ymax-ymin+1, xmin, ymin, true, hdc, color); if(map != NULL){ delete []map; map = NULL; } } void Paint::scanFill(int* map, int width, int height, int xmin, int ymin, bool paint, HDC &hdc, COLORREF color) { //qDebug() << map[width*height-1]; //qDebug() << "width " << width << " height " << height; POINT* m = new POINT; POINT* n = new POINT; for(int j = 0; j<height; j++) { bool inner = false; for(int i = 0; i<width; i++) { int index = j*width+i; if(map[index] == 0) continue; if(!inner){ if(map[index] == 2) continue; m->x = i+xmin; m->y = j+ymin; inner = true; } else { n->x = i+xmin; n->y = j+ymin; // considering the width to be over 1 pixel if(n->x == m->x + 1){ m->x = n->x; continue; } else{ if(paint){ MoveToEx(hdc, m->x, m->y, (LPPOINT) NULL); LineTo(hdc, n->x, n->y); } fillLine(map, xmin, ymin, width, m->x, m->y, n->x, n->y); inner = false; if(map[index] == 2){ m->x = n->x; inner = true; continue; } i++; while(i<width && map[j*width+i]){ i++; } i--; } } } } delete m; delete n; } void Paint::findBoundary(int& ymin, int& ymax, int& xmin, int& xmax, Polygen* p) { if(p == NULL) return; Node* start = p->begin; Node* n = start->next; POINT* point = start->itself; ymin = point->y; ymax = ymin; xmin = point->x; xmax = xmin; while(n != start){ point = n->itself; if(point->y < ymin){ ymin = point->y; } else if(point->y > ymax){ ymax = point->y; } if(point->x < xmin){ xmin = point->x; } else if(point->x > xmax){ xmax = point->x; } n = n->next; } } void Paint::markEdge(int* map, int xmin, int ymin, int width, Polygen* p) //void Paint::markEdge(HDC& hdc, bool* map, int xmin, int ymin, int width, Polygen* p) { //HPEN hPen = CreatePen(PS_SOLID, lineWidth, RGB(0,0,0)); //SelectObject(hdc, hPen); if(p == NULL) return; Node* start = p->begin; Node* n = start; POINT* m1; POINT* m2; while(true) { m1 = n->itself; m2 = n->next->itself; int x, y, dx, dy, e; int x0 = m1->x - xmin; int y0 = m1->y - ymin; int x1 = m2->x - xmin; int y1 = m2->y - ymin; x = x0; y = y0; dx = abs(x1 - x0); dy = abs(y1 - y0); int addX = (x1 - x0) > 0 ? 1 : -1; int addY = (y1 - y0) > 0 ? 1 : -1; if(dx >= dy){ e = -dx; for(int i = 0; i<=dx; i++) { map[x + y * width] = 1; //MoveToEx(hdc, x, y, (LPPOINT) NULL); //LineTo(hdc, x+1, y); x+=addX; e = e + 2 * dy; if(e >= 0) { y+=addY; e = e - 2 * dx; } } } else{ e = -dy; for(int i = 0; i<=dy; i++) { map[x + y * width] = 1; //MoveToEx(hdc, x, y, (LPPOINT) NULL); //LineTo(hdc, x+1, y); y+=addY; e = e + 2 * dx; if(e >= 0) { x+=addX; e = e - 2 * dy; } } } n = n->next; if(n == start) break; } } void Paint::markCorner(int* map, int xmin, int ymin, int width, int height, Polygen* p) { if(p == NULL) return; Node* start = p->begin; Node* last = start; Node* current = start->next; POINT* q; int x, y, xl, xr, yb, yt; while(true) { q = current->itself; x = q->x - xmin; y = q->y - ymin; int y1 = last->itself->y - ymin; int y2 = current->next->itself->y - ymin; xl = x; xr = x; yb = y; yt = y; if(xl > 0) xl = xl-1; if(xr < width-1) xr = xr+1; if(yb > 0) yb = yb-1; if(yt < height-1) yt = yt+1; int xlt = xl; int xrt = xr; if((y1 > y && y2 > y) || (y1 < y && y2 < y)){ map[x+y*width] = 2; //qDebug() << "corner" << x+xmin << " " << y+ymin; while(map[xlt+y*width] == 1){ //qDebug() << "corner" << xlt+xmin << " " << y+ymin; map[xlt+y*width] = 2; xlt--; if(xlt < 0) break; } while(map[xrt+y*width] == 1){ map[xrt+y*width] = 2; //qDebug() << "corner" << xrt+xmin << " " << y+ymin; xrt++; if(xrt > width-1) break; } int addY = y1 > y ? 1 : -1; int y0 = y+addY; while(map[x+y0*width] == 1){ xlt = xl; xrt = xr; map[x+y0*width] = 2; bool flag = false; //if(map[xl+y0*width] == 1){ while(map[xlt+y0*width] == 1){ flag = true; map[xlt+y0*width] = 2; //qDebug() << "corner" << xlt+xmin << " " << y0+ymin; xlt--; if(xlt < 0) break; } while(map[xrt+y0*width] == 1){ flag = true; map[xrt+y0*width] = 2; //qDebug() << "corner" << xrt+xmin << " " << y0+ymin; xrt++; if(xrt > width-1) break; } if(!flag){ y = y0 + addY; if(y < 0 || y > height-1){ break; } } else break; } } last = current; current = current->next; if(last == start) break; } } void Paint::fillPolygenWithInnerCircle(HDC &hdc) { Polygen *p = currentInnerPolygen; int ymin = 0; int ymax = 0; int xmin = 0; int xmax = 0; findBoundary(ymin, ymax, xmin, xmax, p); // qDebug() << xmin << " " << xmax << " " << ymin << " " << ymax; int width = xmax - xmin + 1; int height = ymax - ymin + 1; int size = width * height; //qDebug() << "size " << size; int* map = new int [size]; memset(map, 0, size * sizeof(int)); // 0-out; 2-edge; 1-inner markEdge(map, xmin, ymin, width, p); markCorner(map, xmin, ymin, width, height, p); while(p->next != NULL){ if(p->next->dir == true) break; p = p->next; markEdge(map, xmin, ymin, width, p); markCorner(map, xmin, ymin, width, height, p); } HPEN hPen = CreatePen(PS_SOLID, lineWidth, backColor); SelectObject(hdc, hPen); scanFill(map, xmax-xmin+1, ymax-ymin+1, xmin, ymin, true, hdc, frontColor); drawBoundary(hdc, currentInnerPolygen); p = currentInnerPolygen; while(p->next != NULL){ if(p->next->dir) break; p = p->next; drawBoundary(hdc, p); } if(map != NULL){ delete []map; map = NULL; } } void Paint::convertPolygenToDot(int* map, int xmin, int ymin, int width, int height, Polygen* p) { markEdge(map, xmin, ymin, width, p); markCorner(map, xmin, ymin, width, height, p); while(p->next != NULL){ if(p->next->dir == true) break; p = p->next; markEdge(map, xmin, ymin, width, p); markCorner(map, xmin, ymin, width, height, p); } scanFill(map, width, height, xmin, ymin, false, gHDC, RGB(0, 0, 0)); } void Paint::fillLine(int* map, int xmin, int ymin, int width, int x1, int y1, int x2, int y2) { int px, py, dx, dy, e; int px0 = x1-xmin; int px1 = x2-xmin; int py0 = y1-ymin; int py1 = y2-ymin; px = px0; py = py0; dx = abs(px1 - px0); dy = abs(py1 - py0); int addX = (px1 - px0) > 0 ? 1 : -1; int addY = (py1 - py0) > 0 ? 1 : -1; if(dx >= dy){ e = -dx; for(int i = 0; i<=dx; i++) { map[px + py * width] = 3; px+=addX; e = e + 2 * dy; if(e >= 0) { py+=addY; e = e - 2 * dx; } } } else{ e = -dy; for(int i = 0; i<=dy; i++) { map[px + py * width] = 3; py+=addY; e = e + 2 * dx; if(e >= 0) { px+=addX; e = e - 2 * dy; } } } } void Paint::drawDotPolygen(HDC &hdc, int* map, int xmin, int ymin, int width, int height) { COLORREF color = RGB(0, 0, 0); //HPEN hPen = CreatePen(PS_SOLID, lineWidth, color); //SelectObject(hdc, hPen); for(int j = 0; j<height; j++) { for(int i = 0; i<width; i++) { int index = i+j*width; if(map[index] > 0) { SetPixel(hdc, i+xmin, j+ymin, color); } } } } void Paint::clipDotPolygen(int* map, int xmin, int ymin, int width, int height) { }
true
c4e8868d29567545010a57c51713c5753ce8ca83
C++
SarahFDAK/CS201
/Labs/lab26/lab26/lambdas_main.cpp
UTF-8
2,153
3.578125
4
[]
no_license
/** * @file lambdas.hpp * @author Student Name * @date Mar 21, 2019 * John Quan * * Practice using lambda functions */ #include <cstdlib> #include <iostream> #include <algorithm> #include <iterator> #include <utility> #include <vector> #include <string> #include "lambdas.hpp" int main() { // TODO: REQUIRED // Create a vector<pair<size_t, string>> to enumerate // each string in the WIKIPEDIA_CPP string vector. std::vector<SizeStringPair> init; for(const auto &s: WIKIPEDIA_CPP){ init.push_back(std::make_pair(s.size(), s)); } // TODO: REQUIRED // Use std::sort with a comparison lambda function that sorts // the vector pairs with the first member in descending order. sort(init.begin(), init.end(), [](SizeStringPair a, SizeStringPair b){ return a.first < b.first; }); std::cout << printVectorPairs(init.begin(), init.end()) << "\n\n\n" << std::endl; sort(init.begin(), init.end(), [](SizeStringPair a, SizeStringPair b){ return a.second > b.second; }); std::cout << printVectorPairs(init.begin(), init.end()) << "\n\n\n" << std::endl; // auto i = init.begin(); // while(i < init.end()){ // auto addl2 = std::find_if(init.begin(), init.end(), // [](SizeStringPair a){ // std::string str = a.second; // return str.size()>=15; // }); // if (addl2 == init.end()) // break; // std::cout << addl2->first << ", " << addl2->second << std::endl; // i++; // } // TODO: REQUIRED // Use printVectorPairs() to print the vector // TODO: ADDITIONAL 1 // Use std::sort with a comparison lambda function that sorts // the vector pairs with the second member in ascending order. // TODO: ADDITIONAL 1 // Use printVectorPairs() to print the vector // TODO: ADDITIONAL 2 // Use std::find_if with a comparison lambda function that prints // the vector pairs where the pair's second.length() > 15. // Print the vector as described in the lab. return 0; }
true
b0ebc345606611bb8b9dc5c1e402abab0b208b74
C++
MIPT-ILab/mipt-mips-old-branches
/akochetygov_task_2/func_sim/func_memory/func_memory.cpp
UTF-8
1,951
2.859375
3
[ "MIT" ]
permissive
/** * func_memory.cpp - the module implementing the concept of * programer-visible memory space accesing via memory address. * @author Alexander Titov <alexander.igorevich.titov@gmail.com> * Copyright 2012 uArchSim iLab project */ // Generic C #include <cassert> #include <cstdlib> // Generic C++ #include <string> #include <iostream> #include <sstream> // uArchSim modules #include <func_memory.h> FuncMemory::FuncMemory( const char* executable_file_name, const char* const elf_sections_names[], short num_of_elf_sections) { // Change it with your implementation. int i; assert( num_of_elf_sections > 0); for( i= 0; i < num_of_elf_sections; i++) { assert( elf_sections_names[i]); } sections = new ElfSection* [num_of_elf_sections]; section_num = num_of_elf_sections; filename = executable_file_name; for( i = 0; i < num_of_elf_sections; i++ ) { sections[i] = new ElfSection ( executable_file_name, elf_sections_names[i]); } } FuncMemory::~FuncMemory() { // Change it with your implementation. int i; for( i = 0; i < section_num; i++) delete sections[i]; delete [] sections; } uint64 FuncMemory::read( uint64 addr, short num_of_bytes) const { // Change it with your implementation. int i; for( i = 0; i < section_num; i++) { if( sections[i]->isInside( addr, num_of_bytes)) { return sections[i]->read( addr, num_of_bytes); } } cerr<<"mistake in addres:"<<addr<<" and number of bytes"<<num_of_bytes<<endl; return NO_VAL64; } string FuncMemory::dump( string indent) const { // Change it with your implementation ostringstream oss; int i; oss << indent << "Dump file \"" << filename <<"\""<< endl; for( i = 0; i < section_num; i++) { oss << sections[i]->dump( indent) << endl; } return oss.str(); }
true
6b34b8329adf5b74c1fc186e18f190c1c62a63cd
C++
hiren505/studentRegSystem
/school_func.cpp
UTF-8
7,936
3.65625
4
[]
no_license
#include <iostream> #include <fstream> #include <iomanip> #include "school.h" using namespace std; /* This is a member function of school class. This function basically takes the parameters from the keyboard and stores in the school object */ void school::input_student_data() { cout<<"\nEnter Student ID: "; cin>>student_id; cin.get(); cout<<"\nEnter your First name : "; cin.getline(first_name,15); cout<<"\nEnter your last name : "; cin.getline(last_name,15); cout<<"\nEnter Guardian Cell no. : "; cin>>guardian_cell_no; } /* This is a member function of class school. This function displays the privet members of the class school */ void school::display_student_data(school s1) { cout<<endl<<"**"<<setw(15)<<s1.student_id<<setw(22)<<s1.first_name<<setw(18)<<s1.last_name<<setw(25)<<s1.guardian_cell_no<<" **"; } /* This is a member function of school. This function returns the student id of the class object that it receives. */ int school::return_student_id(school s1) { int id_to_return = s1.student_id; return id_to_return; } /* This function calls the input_data member function of school and append the data int the file. */ void append_student_data() { ofstream file1; file1.open("Record.txt",ios::app); school student; student.input_student_data(); file1.write((char *)(&student), sizeof(student)); cout<<"\nData Apended Successfully\n"; file1.close(); } /* This function displays the list of Students stored in the File in a proper format. */ void display_all_student_data() { cout<<endl<<endl; cout<<"\n\n*******************************************************************************************************"; cout<<"\n** Student ID"<<" First Name"<<" Last Name"<<" Guardian cell No. **"<<endl; cout<<"*******************************************************************************************************"; ifstream file1; school s1; file1.open("Record.txt",ios::in); if(file1.is_open()) { while(1) { file1.read( (char *) (&s1), sizeof(s1)); if(file1.eof()) { break; } cout<<"\n** **"; s1.display_student_data(s1); cout<<"\n** **"; } file1.close(); } else { cout<<"\nFile does not exist\n"; } cout<<"\n*******************************************************************************************************"; } /* This function displays the wecome screen of the software This functon contains the options that can be performed when selected. */ int display_options() { int choice; cout<<"\n\n*******************************************************************************************************"; cout<<"\n********************************* Welcome To Student Registration System *************************"; cout<<"\n*******************************************************************************************************"; cout<<"\n** **"; cout<<"\n** **"; cout<<"\n** 1. Add a Student to Database **"; cout<<"\n** **"; cout<<"\n** 2. Delete a student from Database **"; cout<<"\n** **"; cout<<"\n** 3. Modify student Information **"; cout<<"\n** **"; cout<<"\n** 4. Display All students Information **"; cout<<"\n** **"; cout<<"\n** 5. Exit From this Software **"; cout<<"\n** **"; cout<<"\n*******************************************************************************************************"; cout<<"\n** **"; cout<<"\n** Enter Your Choice : ";cin>>choice; cout<<"** **"; cout<<"\n** **"; cout<<"\n*******************************************************************************************************\n\n"; return choice; } /* This function asks the user to enter a ID that he want to delete. And then delets the particular ID. */ void delete_student() { int id_to_delete; int present_status = 0; cout<<"\n*******************************************************************************************************"; cout<<"\n** **"; cout<<"\n** Enter the ID You want to delete : "; cin>>id_to_delete; cout<<"*******************************************************************************************************\n\n"; school s1; ifstream filetoread; ofstream filetowrite; filetoread.open("Record.txt"); filetowrite.open("temp.txt"); while(1) { filetoread.read((char *)(&s1), sizeof(s1)); if(filetoread.eof()) { break; } if(s1.return_student_id(s1) != id_to_delete) { filetowrite.write((char *)(&s1), sizeof(s1)); } else { present_status = 1; } } filetoread.close(); filetowrite.close(); remove("Record.txt"); rename("temp.txt","Record.txt"); if(present_status == 1) { cout<<"\n\n"; cout<<"\n*******************************************************************************************************"; cout<<"\n** **"; cout<<"\n** Student ID No : "<<id_to_delete<<" deleted Successfully **"; cout<<"\n** **"; cout<<"\n*******************************************************************************************************"; } else { cout<<"\n\n"; cout<<"\n*******************************************************************************************************"; cout<<"\n** **"; cout<<"\n** Sorry the Student Id you mentioned was not found in the file !!!!! **"; cout<<"\n** **"; cout<<"\n*******************************************************************************************************"; } } /* This function displays the Good day message */ void quit_software() { cout<<"\n*******************************************************************************************************"; cout<<"\n** Have A Good Day ! **"; cout<<"\n*******************************************************************************************************\n\n\n\n"; }
true
9856e40e5d6059e0e8133623369c7411203f720a
C++
OverMe/lulzKey
/include/Memory.h
UTF-8
381
2.921875
3
[]
no_license
/** * @file Memory.h * * @brief Memory management namespace. */ #include <Type.h> namespace Memory { void* alloc (Type::ulong size); void* free (void* pointer); } // Kernel space new's void* operator new (Type::ulong size); void* operator new[] (Type::ulong size) // Kernel space delete's void operator delete (void* pointer) void operator delete[] (void* pointer)
true
a68c33ad054cd9454c508958f0e68ec8bd9e5cad
C++
albertium/GridPricing
/Options.h
UTF-8
1,044
2.515625
3
[]
no_license
// // Created by Albert Wong on 3/23/18. // #ifndef HULLWHITE_OPTIONS_H #define HULLWHITE_OPTIONS_H #include "PricerHelper.h" #include "DiffusionPDE.h" #include "GridPricer.h" #include "Curve.h" #include <cmath> #include <algorithm> #include <iomanip> class Options { protected: double m_price; public: explicit Options() : m_price(0.0) {}; virtual ~Options() = default; inline double GetPrice() const { return m_price; }; }; class EuropeanOption : public Options { private: double m_S, m_K, m_r, m_q, m_sig, m_T; public: explicit EuropeanOption(double S, double K, double r, double q, double sig, double T, OptionType type); ~EuropeanOption() override = default; }; class AmericanOption : public Options { public: explicit AmericanOption(double S, double K, double r, double q, double sig, double T); // put option ~AmericanOption() override = default; }; class TestOption : public Options { public: explicit TestOption(); ~TestOption() override = default; }; #endif //HULLWHITE_OPTIONS_H
true
49b8eead4dbf0fd9866a2c62907594eb9742fae0
C++
kajyuuen/cpp-intro-practice
/src/008/for01.cpp
UTF-8
199
2.65625
3
[]
no_license
int main() { // for ( 変数の宣言 ; 終了条件の確認 ; 各ループの最後に必ず行う処理 ) 文 for( int i = 1; i <= 100; ++i ) { std::cout << i << " "s ; } }
true
20e18a8a550c017505731bff08f045efeeffa532
C++
SixtyOne61/Hub_Spacel
/Hub_Spacel/Source/Hub_Spacel/Public/Noise/SpacelNoise.h
UTF-8
982
2.640625
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" /** * */ class HUB_SPACEL_API SpacelNoise { private: struct Grad { Grad(double _x, double _y, double _z) : m_x(_x) , m_y(_y) , m_z(_z) , m_w(0) {} double m_x; double m_y; double m_z; double m_w; }; static SpacelNoise* m_instance; SpacelNoise(); public: ~SpacelNoise(); static SpacelNoise* getInstance() { if (!m_instance) { m_instance = new SpacelNoise(); } return m_instance; } float getNoise(double _xin, double _yin, double _zin) const; int fastFloor(double _x) const; double dot(Grad const& _g, double _x, double _y, double _z) const; float getOctaveNoise(double _x, double _y, double _z, int _octaves) const; public: // Skewing and unskewing factors for 2, 3, and 4 dimensions double m_f3; double m_g3; TArray<short> m_p; short m_perm[512]; short m_permMod12[512]; TArray<Grad> m_grad3; };
true
d9d1152601643153e8e57d6551daa7536f1d2908
C++
mrabets/cpp-course
/template-inheritance/Monoblock.h
UTF-8
835
2.703125
3
[ "MIT" ]
permissive
#pragma once #include "Stationary.h" class Monoblock : public Stationary { public: Monoblock(); Monoblock(string standColour, int powerSupply, string model); Monoblock(const Monoblock& object); ~Monoblock(); string getStandColour() const; void setStandColour(string standColour); friend bool operator<(const Monoblock& first, const Monoblock& second); friend bool operator==(const Monoblock& first, const Monoblock& second); friend istream& operator >> (istream& in, Monoblock& obj); friend ostream& operator << (ostream& os, const Monoblock& obj); friend fstream& operator<<(fstream& out, Monoblock& obj); friend fstream& operator>>(fstream& in, Monoblock& obj); friend ofstream& operator<<(ofstream& out, Monoblock& obj); friend ifstream& operator>>(ifstream& in, Monoblock& obj); private: string standColour; };
true
c2777256d43bf4ff7192fa47751db7b93714a7d8
C++
madaan/funcs
/hello.cpp
UTF-8
310
2.78125
3
[]
no_license
//sg #include<iostream> #define INF 100000; using namespace std; int add(int a, int b) { return a + b; } int div(int a, int b) { if (b != 0){ return a / b; } else return INF; } int mul (int a, int b) { // multiplies two nmbrs { return a*b; } int main() { cout << "Hi"; return 0; }
true
fb04e6b148ec139d6ac21ce2ef6e49a9058736bc
C++
eparu/TronGame
/Client/Client/main.cpp
UTF-8
7,874
2.9375
3
[]
no_license
#include <SFML/Graphics.hpp> #include <random> #include <iostream> #include <utility> #include <vector> #include <chrono> #include <thread> #include <boost/asio.hpp> using namespace sf; constexpr int W = 600; constexpr int H = 480; constexpr int speed = 1; class Field { public: Field() { cells.assign(W, std::vector<bool>(H)); for (auto i = 0U; i < W; i++) { for (auto j = 0U; j < H; j++) { cells[i][j] = false; } } } bool isOccupiedCell(int x, int y) { return cells[x][y]; } bool isOccupiedCell(std::pair<int, int> point) { return cells[point.first][point.second]; } void setCell(int x, int y) { cells[x][y] = true; } void setCell(std::pair<int, int> point) { cells[point.first][point.second] = true; } private: std::vector<std::vector<bool>> cells; }; enum class Direction { Down, Left, Right, Up }; class Player { public: Player(Color c): color(c) { std::uniform_int_distribution <> uid_dir(0, 3); std::default_random_engine dre(std::chrono::system_clock().now().time_since_epoch().count()); x = rand() % W; y = rand() % H; dir = static_cast<Direction>(uid_dir(dre)); } Player(Color c, int p_x, int p_y, Direction d): color(c), x(p_x), y(p_y), dir(d) {} void update() { switch (dir) { case Direction::Up: y--; break; case Direction::Left: x--; break; case Direction::Right: x++; break; case Direction::Down: y++; break; default: break; } if (x >= W) x = 0; if (x < 0) x = W - 1; if (y >= H) y = 0; if (y < 0) y = H - 1; } std::pair<int, int> getСoordinates() { return std::pair<int, int>(x, y); } int getX() { return x; } int getY() { return y; } void setX(int x_value) { x = x_value; } void setY(int y_value) { y = y_value; } Direction getDirection() { return dir; } void setDirection(Direction d) { dir = d; } Color getColor() { return color; } ~Player() = default; private: int x, y; Direction dir; Color color; }; void read_data_until(boost::asio::ip::tcp::socket& socket, Player& p) { while (true) { boost::asio::streambuf buffer; boost::asio::read_until(socket, buffer, '\n'); int message; std::istream input_stream(&buffer); input_stream >> message; auto m_dir = static_cast<Direction>(message); switch (m_dir) { case Direction::Down: if (p.getDirection() != Direction::Up) { p.setDirection(Direction::Down); } break; case Direction::Left: if (p.getDirection() != Direction::Right) { p.setDirection(Direction::Left); } break; case Direction::Right: if (p.getDirection() != Direction::Left) { p.setDirection(Direction::Right); } break; case Direction::Up: if (p.getDirection() != Direction::Down) { p.setDirection(Direction::Up); } break; default: break; } if (message == 10) { boost::asio::write(socket, boost::asio::buffer("10\n")); return; } } } int main() { Field field; RenderWindow window(VideoMode(W, H), "The Tron Game!"); window.setFramerateLimit(60); Texture texture; texture.loadFromFile("background.jpg"); Sprite sBackground(texture); Player p1(Color::Red, 500, 400, Direction::Up); Player p2(Color::Green, 100, 100, Direction::Down); Sprite sprite; RenderTexture t; t.create(W, H); t.setSmooth(true); sprite.setTexture(t.getTexture()); t.clear(); t.draw(sBackground); bool Exit = false; std::string raw_ip_address = "93.175.8.43"; auto port = 8001; try { boost::asio::ip::tcp::endpoint endpoint( boost::asio::ip::address::from_string(raw_ip_address), port); boost::asio::io_service io_service; boost::asio::ip::tcp::socket socket(io_service, endpoint.protocol()); socket.connect(endpoint); std::thread Thread(read_data_until, std::ref(socket), std::ref(p2)); while (window.isOpen()) { Event e; while (window.pollEvent(e)) { if (e.type == Event::Closed) window.close(); } if (Keyboard::isKeyPressed(Keyboard::Left) && p1.getDirection() != Direction::Right && p1.getDirection() != Direction::Left) { p1.setDirection(Direction::Left); boost::asio::write(socket, boost::asio::buffer("1\n")); } if (Keyboard::isKeyPressed(Keyboard::Right) && p1.getDirection() != Direction::Left && p1.getDirection() != Direction::Right) { p1.setDirection(Direction::Right); boost::asio::write(socket, boost::asio::buffer("2\n")); } if (Keyboard::isKeyPressed(Keyboard::Up) && p1.getDirection() != Direction::Down && p1.getDirection() != Direction::Up) { p1.setDirection(Direction::Up); boost::asio::write(socket, boost::asio::buffer("3\n")); } if (Keyboard::isKeyPressed(Keyboard::Down) && p1.getDirection() != Direction::Up && p1.getDirection() != Direction::Down) { p1.setDirection(Direction::Down); boost::asio::write(socket, boost::asio::buffer("0\n")); } if (Exit) continue; for ( int i = 0; i < speed; i++) { p1.update(); p2.update(); if (field.isOccupiedCell(p1.getСoordinates())) { Exit = true; std::cout << "Failed\n"; } if (field.isOccupiedCell(p2.getСoordinates())) { if (!Exit) { Exit = true; std::cout << "Win\n"; } } field.setCell(p1.getСoordinates()); field.setCell(p2.getСoordinates()); CircleShape c(3); c.setPosition(p1.getX(),p1.getY()); c.setFillColor(p1.getColor()); t.draw(c); c.setPosition(p2.getX(), p2.getY()); c.setFillColor(p2.getColor()); t.draw(c); t.display(); } window.clear(); window.draw(sprite); window.display(); } boost::asio::write(socket, boost::asio::buffer("10\n")); Thread.join(); } catch (boost::system::system_error& e) { std::cout << "Error occured! Error code = " << e.code() << ". Message: " << e.what() << std::endl; system("pause"); return e.code().value(); } std::cout << "end\n"; return 0; }
true
5f4484339021599c4a6ed935e91cea562dc3b921
C++
asimonov/CarND3-P1-Path-Planning
/src/Car.cpp
UTF-8
7,632
2.828125
3
[]
no_license
// // Created by Alexey Simonov on 05/08/2017. // #include "Car.h" #include <math.h> #include <cassert> #include "helpers.h" #include <fstream> #include <ios> using namespace std; Car::Car(int id, double x, double y, double yaw, double s, double d, int lane, double speed, double acceleration, double target_speed, double max_speed, double max_acceleration ) { _id = id; _x = x; _y = y; _yaw = yaw; _s = s; _d = d; _lane = lane; assert(speed>=0); _speed = speed; _acceleration = acceleration; assert(target_speed>=0); _target_speed = target_speed; assert(max_speed>0); _max_speed = max_speed; assert(max_acceleration>0); _max_acceleration = max_acceleration; _state = pair<Maneuvre ,int>(CONSTANT_SPEED, _lane); // default state _predictions_dt = -1.0; } Car Car::advance(double T) const { Car advanced(*this); // use copy advanced._speed += _acceleration * T; advanced._s += _speed * T + 0.5 * _acceleration * T * T; return advanced; } // generate predictions. depends on the state void Car::generate_predictions(double T, double dt) { assert(dt>0); _predictions_dt = dt; _predictions.clear(); Maneuvre m = _state.first; int l = _state.second; switch (m) { case CONSTANT_SPEED: for (double t=0; t<=T; t+=dt) { _predictions.push_back({_lane, _s + _speed * t}); } break; case KEEP_LANE: case PREPARE_CHANGE_LANE: for (double t=0; t<=T; t+=dt) { double s = _s + _speed * t + 0.5 * _acceleration * t * t; _predictions.push_back({_lane, s}); } break; case CHANGE_LANE: for (double t=0; t<=T; t+=dt) { double s = _s + _speed * t + 0.5 * _acceleration * t * t; // assume lane change happens in the middle of time horizon if (t<=T/2.0) _predictions.push_back({_lane, s}); else _predictions.push_back({l, s}); } break; } } const predictions_type& Car::get_predictions() const { return _predictions; } double Car::maxAccelerationForLane(const std::vector<Car>& other_cars, double maneuvre_time) { double delta_v_til_target = _target_speed - _speed; double acc_til_target = delta_v_til_target / maneuvre_time; // can be negative double acc_sign = 1; if (acc_til_target<0) acc_sign = -1; // this is acceleration to get to target speed in maneuvre_time. with no obstacles double max_acc = acc_sign * min(_max_acceleration * 0.8, fabs(acc_til_target)); // find nearest car in front that we may need to follow double leading_s_now = 1e+10; Car car(*this); // placeholder object for car in front for (auto it = other_cars.begin(); it != other_cars.end(); it++) if (it->getLane() == _lane && it->getS() > _s) { // there is car in front if (it->getS() < leading_s_now) { leading_s_now = it->getS(); car = *it; // copy } } // adjust our acceleration based on leading vehicle int NUM_LENGTHS_BEHIND_TARGET = 3; if (leading_s_now < 1e+10)// && acc_sign>0) { double delta_s = (car.getS() - NUM_LENGTHS_BEHIND_TARGET*LENGTH) - _s; delta_s += (car.getSpeed() - _speed)*maneuvre_time; // calculate de/acceleration to end up behind that car at specified time horizon double a = 2.0 * delta_s / (maneuvre_time * maneuvre_time); if (a<max_acc) max_acc = a; if (max_acc<0) max_acc = max(-_max_acceleration*0.8,max_acc); else max_acc = min(_max_acceleration*0.8,max_acc); } return max_acc; } void Car::setState(std::pair<Maneuvre, int>& state, const std::vector<Car>& other_cars, double maneuvre_time) { // sets _state, _lane, _acceleration _state = state; Maneuvre m = _state.first; int l = _state.second; assert(maneuvre_time>0.0); // realizing the state by adjusting speed/acceleration switch (m) { case CONSTANT_SPEED: _acceleration = 0.0; break; case KEEP_LANE: _acceleration = maxAccelerationForLane(other_cars, maneuvre_time); break; case CHANGE_LANE: _lane = l; _acceleration = maxAccelerationForLane(other_cars, maneuvre_time); break; case PREPARE_CHANGE_LANE: int old_lane = _lane; int NUM_LENGTHS_BEHIND_TARGET = 3; _lane = l; // eliminate cars (from copy) until we are left with only cars in the target lane that are behind us vector<Car> cars_copy = other_cars; while (cars_copy.size()) { if (cars_copy[cars_copy.size()-1].getLane() != _lane) { cars_copy.pop_back(); continue; } // car in the lane we want to merge into. Car c = cars_copy[cars_copy.size()-1]; // we are not interested in cars in front as we are not considering speeding up. // so we only look at cars behind our position+buffer if (c.getS() > _s + NUM_LENGTHS_BEHIND_TARGET*LENGTH) { cars_copy.pop_back(); continue; } break; } if (cars_copy.size()) { // find the closest car behind (descending sort on distance) sort(cars_copy.begin(), cars_copy.end(), [](const Car& x, const Car& y)->bool{return x.getS() > y.getS();}); Car nearest_behind = cars_copy[0]; //double delta_v = nearest_behind.getSpeed() - _speed; // new speed is _speed plus delta double delta_s = (nearest_behind.getS() - NUM_LENGTHS_BEHIND_TARGET*LENGTH) - _s; // negative distance delta_s += (nearest_behind.getSpeed() - _speed)*maneuvre_time; // calculate [de]acceleration to end up behind that car at specified time horizon double a = 2.0 * delta_s / (maneuvre_time * maneuvre_time); if (a<0) _acceleration = max(-_max_acceleration*0.8,a); else _acceleration = min(_max_acceleration*0.8,a); } else { // no potential obstacles in the target lane, pick best acceleration _acceleration = maxAccelerationForLane(other_cars, maneuvre_time); } _lane = old_lane; break; } } double Car::get_target_time() const { assert(_predictions_dt>0); assert(_predictions.size()); return (_predictions.size()-1)*_predictions_dt; } int Car::get_target_lane() const { int res = _lane; if (_state.first == CHANGE_LANE) res = _state.second; return res; } void Car::dumpToStream(const std::string& filename) const { ofstream out_stream(filename.c_str(), ios_base::app); out_stream << "lane : "<< _lane << endl; out_stream << "id : "<< _id << endl; out_stream << "x,y : "<< _x << " " << _y << endl; out_stream << "yaw : "<< _yaw << endl; out_stream << "s,d : "<< _s << " " << _d << endl; out_stream << "speed: "<< _speed << endl; out_stream << "acc : "<< _acceleration << endl; out_stream << "maneuvre : "<< _state.first << endl; out_stream << "target lane : "<< _state.second << endl; out_stream << endl; out_stream.close(); } // translate x,y in car coordinates into global coordinates (given car position on the map) std::vector<double> Car::car2global(double x_car, double y_car) const { double x_map = x_car * cos(_yaw) - y_car * sin(_yaw) + _x; double y_map = x_car * sin(_yaw) + y_car * cos(_yaw) + _y; return {x_map, y_map}; } // translate x,y in map coordinates into car coordinates (given car position on the map) std::vector<double> Car::global2car(double x_map, double y_map) const { double x_car = (x_map - _x) * cos(_yaw) + (y_map - _y) * sin(_yaw); double y_car = (y_map - _y) * cos(_yaw) - (x_map - _x) * sin(_yaw); return {x_car, y_car}; }
true
040685bd81a94b909460645983c04bd09057454f
C++
HerculesShek/cpp-practise
/src/ch6/basic/demo02.cc
UTF-8
340
3.578125
4
[ "MIT" ]
permissive
#include <iostream> using namespace std; int fact(int val) { int res = 1; while(val > 1) res *= val--; return res; } int fabi(int i) { if(i<=2) return 1; return fabi(i-1) + fabi(i-2); } int main() { int res = fact(5); cout << "5! is " << res << endl; cout << "the 5th fabi num is " << fabi(5) << endl; return 0; }
true
e2d234c4a1503c17ecb229d6514e2974fce8cacb
C++
iRoy7/Strings_Handling
/ex_string_pattern_match.cpp
UTF-8
956
2.671875
3
[]
no_license
#include "stdafx.h" #include <stdio.h> const int SMAX = 256; static int brute_force(const char* ptn, const char* src, int pln, int sln) { // base case: if (sln < pln) return 0; // general case: int ptn_cnt = 0; int pidx = 0; int sidx = 0; while (pidx < pln && sidx < sln) { if (src[sidx] != ptn[pidx]) { sidx = sidx - pidx; pidx = -1; } sidx += 1; pidx += 1; if (pidx == pln) { ptn_cnt++; pidx = 0; } } if (sidx == sln && ptn_cnt > 0) return ptn_cnt; else return 0; } int main() { freopen("ex_string_pattern_match.txt", "r", stdin); setbuf(stdout, NULL); int T; scanf("%d", &T); for (int tc = 1; tc <= T; tc++) { char PTN[SMAX], SRC[SMAX]; scanf("%s %s", PTN, SRC); int pln, sln; for (pln = 0; PTN[pln]; pln++); for (sln = 0; SRC[sln]; sln++); printf("Pattern count = %d\n", brute_force(PTN, SRC, pln, sln)); } return 0; }
true
d33858498d894378e239ed53c5750d156dfadd5b
C++
Neriok/Stella
/Source/Collections/Array.h
UTF-8
4,800
3.34375
3
[]
no_license
#pragma once #include "Typedef.h" #include "IIterable.h" #include <initializer_list> namespace Stella::Collections { template <class T, Size N> class Array : public IIterable<T> { /*----------------------------------------------------------------------- Fields -----------------------------------------------------------------------*/ private: T elements[N]; /*----------------------------------------------------------------------- Constructors & Destructors -----------------------------------------------------------------------*/ public: FORCEINLINE Array() = default; FORCEINLINE Array(const T* pointer, Size count) { if (count > N) return; // @todo throw ArgumentOutOfRangeException for (int i = 0; i < N; i++) { if (i < count) { elements[i] = pointer[i]; continue; } elements[i] = NULL; } } FORCEINLINE Array(const Array<const T, N>& constArray) : Array(constArray.elements, N) { } FORCEINLINE Array(std::initializer_list<T> initializerList) : Array(initializerList.begin(), initializerList.size()) { } /*----------------------------------------------------------------------- Methods -----------------------------------------------------------------------*/ public: bool IsEmpty() const { return false; } Size Count() const { return N; } T* GetData() { return elements; } const T* GetData() const { return elements; } T* Begin() { return elements; } const T* Begin() const { return elements; } T* End() { return elements + N; } const T* End() const { return elements + N; } T& Front() { return elements[0]; } const T& Front() const { return elements[0]; } T& Back() { return elements[N - 1]; } const T& Back() const { return elements[N - 1]; } void Fill(const T& value) { for (int i = 0; i < N; i++) { elements[i] = value; } } void Swap(const Array<T, N>& other) { for (int i = 0; i < N; i++) { // ... } } /*----------------------------------------------------------------------- Operators -----------------------------------------------------------------------*/ public: T& operator[](Size index) { return elements[index]; } const T& operator[](Size index) const { return elements[index]; } bool operator==(Array<T, N>& other) { T* b1 = Begin(); T* b2 = other.Begin(); T* e1 = End(); for (; b1 != e1; b1++, b2++) { if (*b1 != *b2) { return false; } } return true; } bool operator!=(Array<T, N>& other) { return !(operator==(other)); } bool operator<(Array<T, N>& other) { T* b1 = Begin(); T* b2 = other.Begin(); T* e1 = End(); for (; b1 != e1; b1++, b2++) { if (*b1 < *b2) return true; if (*b2 < *b1) return false; } return false; } bool operator<=(Array<T, N>& other) { return !(other < *this); } bool operator>(Array<T, N>& other) { return other < *this; } bool operator>=(Array<T, N>& other) { return !(*this < other); } /*----------------------------------------------------------------------- IIterable -----------------------------------------------------------------------*/ public: SharedPointer<IIterator<T>> GetIterator() const { return new ArrayIterator(*this); } /*----------------------------------------------------------------------- ArrayIterator -----------------------------------------------------------------------*/ private: class ArrayIterator : public IIterator<T> { private: Int32 index; Array<T, N> array; public: ArrayIterator(const Array<T, N>& array) : array(array), index(0) { } bool MoveNext() { if (index < N) { index++; return true; } index = N + 1; return false; } bool HasCurrent() const { return index > 0 && index < N + 1; } T& GetCurrent() { if (!HasCurrent()) { // @todo throw InvalidOperationException } return array[index - 1]; } const T& GetCurrent() const { if (index == 0 || index == N + 1) { // @todo throw InvalidOperationException } return array[index - 1]; } void Reset() { index = 0; } }; }; template<class T> class Array<T, 0> { public: bool IsEmpty() const { return true; } Size GetSize() const { return 0; } }; template <class T, Size N> class Array <const T, N> { public: T elements[N]; }; }
true
4871c1a6558e5c92681fba3d8702c0590b740d7a
C++
Anubhav12345678/competitive-programming
/UNITGCDAPRILLONGCODECHEFVVVVVVIMP.cpp
UTF-8
1,113
3.203125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; template<typename T = int> vector<T> create(size_t n){ return vector<T>(n); } template<typename T, typename... Args> auto create(size_t n, Args... args){ return vector<decltype(create<T>(args...))>(n, create<T>(args...)); } int main(){ ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--){ int n; cin >> n; /** if the n is 1 the answer is 1 else the lower bound of the answer is floor(N / 2), because no two even numbers can be in the same set this bound can be achieved by creating pair of adjacent numbers (i.e (1, 2) (3, 4) (5, 6) ...) if N is odd, the number N will be unused, but it can be put in the tuple (1, 2) as it's an odd number the GCD(2, N) = 1 * */ if(n == 1){ cout << 1 << '\n'; cout << 1 << ' ' << 1 << '\n'; } else { cout << n / 2 << '\n'; if(n % 2){ cout << 3 << ' ' << 1 << ' ' << 2 << ' ' << n << '\n'; } else { cout << 2 << ' ' << 1 << ' ' << 2 << '\n'; } for(int i = 4; i <= n; i += 2){ cout << 2 << ' ' << i - 1 << ' ' << i << '\n'; } } } return 0; }
true
a880906593fecf48d21a11f969b05db6d01cfc96
C++
PrikhodkoStanislav/HomeWork
/I semester/HomeWork8/Zadacha1 hash table/Zadacha1 hash/hash.h
UTF-8
607
2.875
3
[]
no_license
#pragma once #include "list.h" using namespace list; namespace hash { struct HashTable; // create new hashtable HashTable *createHashTable(); // delete hashtable void deleteHashTable(HashTable *hashTable); // insert to hashtable new element void insertToHashTable(HashTable *hashTable, ElementType newElement); // Is element in the hashtable? bool exist(HashTable *hashTable, ElementType element); // remove element from hashtable void remove(HashTable *hashTable, ElementType element); // print elements of hashtable with number of their repetition on console void printHashTable(HashTable *hashTable); }
true
b0e3d5612d1ae32b6066801bf07dce659e62a0e8
C++
bsmsnd/LeetCode-CharlieChen
/269.alien-dictionary.cpp
UTF-8
2,869
3.09375
3
[ "MIT" ]
permissive
/* * @lc app=leetcode id=269 lang=cpp * * [269] Alien Dictionary */ #include <iostream> #include <string> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; class Solution { public: unordered_map<char, unordered_set<char>> m; unordered_map<char, char> parent; unordered_map<char, bool> visited; string ans; bool failure = false; void addRule(string a, string b) // a < b { int k = min(a.length(), b.length()); for (int i = 0;i < k;i++) if (a[i] != b[i]) { // add rule: b[i] --> a[i] // first check if not a[i] --> b[i] if (m.find(a[i]) != m.end() && m[a[i]].find(b[i]) != m[a[i]].end()) { cout<<"conflict!"<<endl; failure = true; return; } if (m.find(b[i]) == m.end()) m[b[i]] = unordered_set<char>(); if(m[b[i]].find(a[i]) == m[b[i]].end()) m[b[i]].insert(a[i]); return; } } bool DFS_visit(char vertex) { visited[vertex] = true; if(m.find(vertex) != m.end()) { for (auto& m : m[vertex]) { if (!visited[m]) { parent[m] = vertex; if (!DFS_visit(m)) return false; } else { char p = parent[vertex]; while(p!=-1) { if (p == m) return false; p = parent[p]; } } } } ans+=vertex; return true; } string alienOrder(vector<string>& words) { m.clear(); // step 1: build graph int N = words.size(); for (int i = 0;i < N-1;i++) for (int j = i+1; j < N; j++) { addRule(words[i], words[j]); if(failure) return ""; } for (int i = 0;i < N; i++) for (int j = 0;j < words[i].size(); j++) if (parent.find(words[i][j]) == parent.end()) { parent[words[i][j]] = -1; visited[words[i][j]] = false; } // step 2: topological sort for (auto it = parent.begin(); it != parent.end(); it++) { char cur = it->first; if (!visited[cur]) { if (!DFS_visit(cur))return ""; } } return ans; } };
true
514ced355d74288c866731a4619d5a809eed060f
C++
karencaro/Visualizacion2D
/ViewPipeline.h
UTF-8
700
2.796875
3
[]
no_license
#pragma once class ViewPipeline { CRect w; //ventana (el area que se quiere desplegar) CRect vp;//Puerto de vista (viewport) //(En que parte del dispositivo se va a //desplegar) float sx,sy; //factores de escalamiento ventana/viewport public: ViewPipeline(void); ~ViewPipeline(void); void SetViewport(CRect nvp); // Transforma p en coordenadas mundiales a coordenadas de dispositivo CPoint WorldToDevice(CPoint p); CPoint DeviceToWorld(CPoint p); public: // modifica la ventana del viewing pipeline void SetWindow(CRect nw); CRect GetWindow(){return w;}; CRect GetViewport(){return vp;}; bool ClipLine(CPoint & p1, CPoint & p2); char Codificacion(CPoint &p); };
true
c7cc6770e498bf923c03f8831c23378b5f4737e1
C++
AllenXL/algorithm
/Merge Two Sorted Lists/Merge Two Sorted Lists/main.cpp
WINDOWS-1252
919
3.828125
4
[]
no_license
#include <iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; //ݹ ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode* res; if (l1->val < l2->val) { res = l1; l1->next = mergeTwoLists(l1->next, l2); } else { res = l2; l2->next = mergeTwoLists(l2->next, l1); } return res; } void show(ListNode* head) { while (head != NULL) { cout << head->val << " "; head = head->next; } cout << endl; } int main() { ListNode* l1 = new ListNode(1); l1->next = new ListNode(3); l1->next->next = new ListNode(5); ListNode* l2 = new ListNode(2); l2->next = new ListNode(4); l2->next->next = new ListNode(6); cout << "l1:" << endl; show(l1); cout << "l2:" << endl; show(l2); cout << "res:" << endl; show(mergeTwoLists(l1, l2)); int aa; cin >> aa; }
true
0ea3bdd0c0fc2d42105c5d281c8fc1150fb5b7bd
C++
The-Assembly/Arduino-Triggered-Camera-Shutter
/Camera_Trigger.ino
UTF-8
1,918
2.671875
3
[]
no_license
/* * created by Rui Santos, http://randomnerdtutorials.com * * Complete Guide for Ultrasonic Sensor HC-SR04 * *modified by Judhi Prasetyo for camera shutter control * * Ultrasonic sensor Pins: VCC: +5VDC Trig : Trigger (INPUT) - Pin11 Echo: Echo (OUTPUT) - Pin 12 GND: GND */ int trigPin = 8; //Trig - green Jumper int echoPin = 7; //Echo - blue Jumper int camPin = 13; // camera will take picture if object is closer than this distance (in cm) int cam_distance = 30; long duration, cm, inches; void setup() { //Serial Port begin Serial.begin (9600); //Define inputs and outputs pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(camPin, OUTPUT); } void loop() { // The sensor is triggered by a HIGH pulse of 10 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: digitalWrite(trigPin, LOW); delayMicroseconds(5); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the signal from the sensor: a HIGH pulse whose duration is the time (in microseconds) // from the sending // of the ping to the reception of its echo off of an object. pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); // convert the time into a distance cm = (duration/2) / 29.1; inches = (duration/2) / 74; Serial.print(cm); Serial.println("cm"); if (cm <1) { Serial.println("---"); pinMode(echoPin, OUTPUT); digitalWrite(echoPin, HIGH); delay(3); digitalWrite(echoPin, LOW); pinMode(echoPin, INPUT); } if (cm < cam_distance and cm > 0) { // additional codes by Judhi to trigger the camera digitalWrite(camPin, HIGH); delay(100); digitalWrite(camPin, LOW); delay(500); Serial.println("Taking picture!"); } delay(50); }
true
0e4cd7aff095adcd72a0834a5708e8dd92e3d449
C++
eldsg/BOJ
/BOJ/5639/5639.cpp
UTF-8
704
3.640625
4
[]
no_license
#include<stdio.h> #include<stdlib.h> typedef struct tree{ int data; struct tree *left; struct tree *right; }tree; tree *insert(tree *node, int data){ if (node == NULL){ tree *temp; temp = (tree*)malloc(sizeof(tree)); temp->data = data; temp->left = temp->right = NULL; return temp; } if (data > (node->data)){ node->right = insert(node->right,data); } else if (data < (node->data)){ node->left = insert(node->left, data); } return node; } void print(tree *node){ if (node == NULL) return; print(node->left); print(node->right); printf("%d\n", node->data); } int main(){ tree *root = NULL; int num; while (~scanf("%d", &num)){ root = insert(root, num); } print(root); }
true
617aea4757276703d9965cf1e00b7a1a6afaa17a
C++
iishipatel/Competetive-Programming
/ice cream parlor.cpp
UTF-8
586
2.578125
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main(){ int T; cin>>T; for(int t = 0; t<T; t++){ int M, N; cin>>M>>N; int c[N]; for(int n = 0; n<N; n++){ cin>>c[n]; } int i, j; bool found = false; for(i = 0; i<N; i++){ for(j = i+1; j<N; j++){ if(c[i]+c[j]==M){ found = true; break; } } if(found) break; } cout<<i+1<<" "<<j+1<<endl; } }
true
ac645b995fa562b1c5e8d68192bb6fec5761dcc9
C++
7421/muduo_learning
/test/test8.cpp
UTF-8
945
2.78125
3
[]
no_license
#include <iostream> #include <unistd.h> #include "./net/EventLoop.h" #include "./net/InetAddress.h" #include "./net/TcpServer.h" void onConnection(const muduo::TcpConnectionPtr& conn) { if (conn->connected()) { std::cout << "onConnection(): new connection [" << conn->name().c_str() << "]" << " from " << conn->peerAddress().toHostPort().c_str() << std::endl; } else { std::cout << " onConnection(): connection " << conn->name() << " is down \n"; } } void onMessage(const muduo::TcpConnectionPtr& conn, const char* data, ssize_t len) { std::cout << "onMessage(): received " << len << " bytes from connection " << conn->name().c_str() << std::endl; } int main() { std::cout << getpid(); muduo::InetAddress listenAddr(5001); muduo::EventLoop loop; muduo::TcpServer server(&loop, listenAddr); server.setConnectionCallback(onConnection); server.setMessageCallback(onMessage); server.start(); loop.loop(); }
true
f4912dfefb938070b378b31549e9a7c264b9d61f
C++
hugtalbot/caribou
/src/Caribou/Topology/Grid/Internal/BaseUnidimensionalGrid.h
UTF-8
3,145
3
3
[]
no_license
#ifndef CARIBOU_TOPOLOGY_ENGINE_GRID_INTERNAL_UNIDIMENSIONALGRID_H #define CARIBOU_TOPOLOGY_ENGINE_GRID_INTERNAL_UNIDIMENSIONALGRID_H #include <Caribou/Topology/Grid/Internal/BaseGrid.h> namespace caribou::topology::internal { /** * Simple representation of an unidimensional (1D) Grid in space. * * ** Do not use this class directly. Use instead caribou::topology::engine::Grid. ** * * The functions declared in this class can be used with any type of grids (static grid, container grid, etc.). * * Do to so, it uses the Curiously recurring template pattern (CRTP) : * https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern * * A Grid is a set of multiple cell entities (same-length lines in 1D, rectangles * in 2D and rectangular hexahedrons in 3D) aligned in the x, y and z axis. * * * @tparam GridType_ Type of the derived grid class that will implement the final functions. */ template <class GridType_> struct BaseUnidimensionalGrid : public BaseGrid<1, GridType_> { static constexpr size_t Dimension = 1; using GridType = GridType_; using Base = BaseGrid<1, GridType_>; using UInt = typename Base::UInt; using NodeIndex = typename Base::NodeIndex; using CellIndex = typename Base::CellIndex; using Dimensions = typename Base::Dimensions; using Subdivisions = typename Base::Subdivisions; using LocalCoordinates = typename Base::LocalCoordinates; using WorldCoordinates = typename Base::WorldCoordinates; using GridCoordinates = typename Base::GridCoordinates; using CellSet = typename Base::CellSet; using Base::Base; using Base::cell_coordinates_at; /** Get the node index at a given grid location. */ inline auto node_index_at(const GridCoordinates & coordinates) const noexcept -> NodeIndex { return coordinates[0]; } /** Get the grid location of the node at the given node index */ inline auto node_coordinates_at(const NodeIndex & index) const noexcept -> GridCoordinates { return GridCoordinates (index); } /** Get the node location in world coordinates at node index */ inline auto node(const NodeIndex & index) const noexcept -> WorldCoordinates { const auto & anchor_position = Self().anchor_position(); const auto H = Self().H(); return anchor_position + index*H; } /** Get the cell index at a given grid location. */ inline auto cell_index_at(const GridCoordinates & coordinates) const noexcept -> CellIndex { // Index is generated by looking at the cells as a flatten array const auto & i = coordinates[0]; return i; } /** Get the grid location of the cell at the given cell index */ inline auto cell_coordinates_at(const CellIndex & index) const noexcept -> GridCoordinates { return GridCoordinates (index); } private: inline constexpr const GridType & Self() const { return static_cast<const GridType &> (*this); } }; } // namespace caribou::topology::internal #endif //CARIBOU_TOPOLOGY_GRID_INTERNAL_UNIDIMENSIONALGRID_H
true
264ca0b78fbe87268e4764c8522b2762806f8641
C++
DuckMonster/SmallGame
/Game/src/Core/Standard/Color.h
UTF-8
801
3.71875
4
[]
no_license
#pragma once class Color { public: /* Standard colors */ static const Color white; static const Color black; static const Color transparent; static const Color red; static const Color green; static const Color blue; static const Color orange; static const Color purple; static const Color cyan; static const Color yellow; static Color FromHex(uint32 hex); static Color FromBytes(uint8 r, uint8 g, uint8 b, uint8 a); /* Constructors */ Color() : r(1.f), g(1.f), b(1.f), a(1.f) {} Color(float r, float g, float b, float a) : r(r), g(g), b(b), a(a) {} Color operator*(const Color& other) { return Color(r * other.r, g * other.g, b * other.b, a * other.a); } // Clamps the color so that all values are between [0, 1] void Clamp(); float r; float g; float b; float a; };
true
f4662064d2397b73849934e7a1f146fc99c9c325
C++
AnandDev006/CPlusPlusCodes
/DCP_v1/DCP121.cpp
UTF-8
1,688
3.125
3
[]
no_license
/* author : Anand Given a string which we can delete at most k, return whether you can make a palindrome. For example, given 'waterrfetawx' and a k of 2, you could delete f and x to get 'waterretaw'. */ #include <bits/stdc++.h> #define sz(a) int((a).size()) #define pb push_back #define mp(a, b) make_pair(a, b) #define all(c) (c).begin(), (c).end() #define tr(c, i) for (typeof((c).begin()) i = (c).begin(); i != (c).end(); i++) #define present(c, x) ((c).find(x) != (c).end()) #define cpresent(c, x) (find(all(c), x) != (c).end()) #define X first #define Y second using namespace std; typedef long long ll; typedef pair<ll, ll> ii; void printArray(const vector<ll> &arr) { cout << "[ "; for (ll i = 0; i < sz(arr) - 1; ++i) { cout << arr[i] << ", "; } cout << arr[sz(arr) - 1] << " ]" << endl; } // longest common subsequence between input and its reverse bool canBeMadePalindromeInKDeleteions(string input, ll k) { ll inputLen = input.length(); string a = input; reverse(all(input)); string b = input; vector<vector<ll>> DP(inputLen + 1, vector<ll>(inputLen + 1, 0)); for (ll i = 1; i <= inputLen; ++i) { for (ll j = 1; j <= inputLen; ++j) { if (a[j - 1] == b[i - 1]) { DP[i][j] = 1 + DP[i - 1][j - 1]; } else { DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]); } } } cout << inputLen - DP[inputLen][inputLen] << endl; return ((inputLen - DP[inputLen][inputLen]) <= k); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); assert(canBeMadePalindromeInKDeleteions("waterrfetawx", 2)); assert(canBeMadePalindromeInKDeleteions("abac", 2)); return 0; }
true
f4cba61245373bf262322e5bd9de4c296fac2466
C++
Stasich/learning_cpp
/Lafore_exercises/902_strconv.cpp
UTF-8
1,436
3.46875
3
[]
no_license
// strconv.cpp #include <iostream> #include <string.h> //#include <string> using namespace std; class String { protected: static const int MAX = 80; char str [ MAX ]; public: String() { str[0] = '\0'; cout << "ска";} String( const char s [] ) { strcpy ( str, s ); } String( char s [] ) { strcpy ( str, s ); } void display() const; operator char* (); }; class Pstring : public String { public: Pstring() : String() {} Pstring( const char s[] ) { if ( strlen( s ) > MAX - 1 ) { int j = 0; for ( j ; j < MAX -1; j++ ) str[ j ] = s [ j ]; str [ j ] = '\0'; } else strcpy( str, s ); } }; int main() { Pstring s1 = "This is very very long str. Ok my name is Stas and it is my program for education"; cout << "Дллинная строка: "; s1.display(); Pstring s2 = "This is short"; cout << "Короткая строка: "; s2.display(); cout << endl; return 0; } void String::display() const { cout << str << endl; } String::operator char*() { return str; } /*Pstring::Pstring( const char s1[] ) { if ( strlen( s1 ) > (MAX - 1) ) { int j = 0; for ( j ; j < MAX -1; j++ ) str[ j ] = s1 [ j ]; str [ j ] = '\0'; } else String(s1); }*/
true
e36b6087092c3cb64985c24ea8e6c6b1e5e3358b
C++
amansirohi05/DS-Algo
/Arrays/Array math/Add One To Number.cpp
UTF-8
1,123
3.296875
3
[]
no_license
// https://www.interviewbit.com/problems/add-one-to-number/ vector<int> Solution::plusOne(vector<int> &A) { bool flag = false; vector<int> C; for(int i=0;i<A.size();i++){ // removing prefix zeros if(A[i]!=0){ flag = true; } if(flag){ C.push_back(A[i]); } } if(C.size()==0){ // cases where all are 0 C.push_back(1); return C; } int temp = A[A.size()-1]; if(temp!=9){ // cases where last digit is not 9 C.pop_back(); C.push_back(temp+1); return C; } else{ if(C.size()==1){ // case where only single 9 C.pop_back(); C.push_back(1); C.push_back(0); return C; } for(int i=C.size()-1;i>0;i--){ // cases with last digit as 9 C[i] = 0; C[i-1] += 1; // carry if(C[i-1]<10) break; } if(C[0]==10){ // handling cases where all digits are 9 C[0] = 1; C.push_back(0); } return C; } }
true
d74f40bfa9d24bfbacce89a57997463cc936dea3
C++
boivie/sikozu
/src/main.cpp
UTF-8
2,852
2.5625
3
[]
no_license
#include <sys/types.h> #include <sys/time.h> #include <sys/queue.h> #include <stdlib.h> #include <stdio.h> #include <iostream> #include <string.h> #include <err.h> #include <event.h> #include <sys/types.h> #include <vector> #include "server.h" #include "coreservice.h" #include <boost/program_options.hpp> #include <dlfcn.h> #include <exception> // for std::bad_alloc #include <new> #include <cstdlib> // for malloc() and free() // Visual C++ fix of operator new #if 0 void* operator new (size_t size) { printf("alloc %d\n", size); void *p=malloc(size); if (p==0) // did malloc succeed? throw std::bad_alloc(); // ANSI/ISO compliant behavior return p; } void operator delete (void *p) { free(p); } #endif //#include "simpledb.h" using namespace Sikozu; using namespace std; namespace po = boost::program_options; int main(int argc, char **argv) { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("port", po::value<int>(), "use UDP port number") ("external,x", po::value< vector<string> >(), "enable external library") ("threads,t", po::value<int>(), "Number of worker threads to use (default: 4)") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 1; } // Create the server, and the worker threads int worker_threads = (vm.count("threads")) ? vm["threads"].as<int>() : 4; Server* server_p = new Server(worker_threads); // Start listening socket uint16_t port = (vm.count("port")) ? vm["port"].as<int>() : 9081; server_p->listen_udp(port); // Register services - core and external ServiceRegistry& sr = server_p->get_service_registry(); sr.register_service(new CoreService(server_p->get_nodeid())); if (vm.count("external") > 0) { const vector<string>& values = vm["external"].as<vector<string> >(); for (vector<string>::const_iterator i = values.begin(); i != values.end(); ++i) { string dlname = *i; cout << "Loading external library: " << dlname << endl; void* handle = dlopen(dlname.c_str(), RTLD_LAZY); if (!handle) { cerr << "Cannot open library: " << dlerror() << '\n'; return 1; } typedef void (*sikozu_load_t)(Server*); // reset errors dlerror(); sikozu_load_t sikozu_load = (sikozu_load_t) dlsym(handle, "sikozu_load"); const char *dlsym_error = dlerror(); if (dlsym_error) { cerr << "Cannot load symbol 'create_service': " << dlsym_error << endl; dlclose(handle); return 1; } sikozu_load(server_p); } } cout << "Executing main loop." << endl; server_p->run(); cout << "Exiting..." << endl; return 0; }
true
0ad0bdd80d04d3c74922b608119fede6d3365a03
C++
sittiufairoh/Strukdat-11
/exercise2.cpp
UTF-8
4,365
3.53125
4
[]
no_license
/* Program : exercise-02 Nama : Sitti Ufairoh Azzahra NPM : 140810180002 Deskripsi : Binary Search Tree Tanggal : 15 Mei 2019 */ #include<iostream> using namespace std; struct Simpul{ int info; Simpul* left; Simpul* right; }; typedef Simpul* pointer; typedef pointer Tree; void createSimpul(pointer& pBaru){ pBaru=new Simpul; cout<<"Masukkan satu angka : "; cin>>pBaru->info; pBaru->left=NULL; pBaru->right=NULL; } void insertBST (Tree& Root, pointer pBaru){ if(Root==NULL){ Root=pBaru; } else if (pBaru->info < Root->info){ insertBST(Root->left,pBaru); } else if (pBaru->info > Root->info){ insertBST(Root->right,pBaru); } else{ cout<<"Sudah ada"<<endl; } } void preOrder (Tree Root) { if (Root != NULL){ cout<< Root->info <<endl; preOrder(Root->left); preOrder(Root->right); } } void inOrder (Tree Root) { if (Root != NULL){ inOrder(Root->left); cout<< Root->info <<endl; inOrder(Root->right); } } void postOrder (Tree Root) { if (Root != NULL){ postOrder(Root->left); postOrder(Root->right); cout<< Root->info <<endl; } } int height(Tree Root){ if (Root==NULL) return 0; else{ int lHeight=height(Root->left); int rHeight=height(Root->right); if (lHeight>rHeight) return (lHeight+1); else return (rHeight+1); } } void givenLevel(Tree Root, int level){ if (Root==NULL) return; if (level==1) cout << Root->info << " "; else if (level>1){ givenLevel(Root->left,level-1); givenLevel(Root->right,level-1); } } void kedalaman(Tree Root){ int h=height(Root); for (int i=1; i<=h; i++){ cout << i-1 << ": " <<" [ "; givenLevel(Root,i); cout<< "]"<< endl; } } void levelOrder(Tree Root){ int h=height(Root); for (int i=1; i<=h; i++){ cout << i << ": " <<" [ "; givenLevel(Root,i); cout<< "]"<< endl; } } void Anak(Tree Root, pointer pBaru){ pBaru= Root; if(pBaru!=NULL){ cout<<"Parent Node = "<<pBaru->info<<endl; if(pBaru->left == NULL) cout<<"Left Child = NULL"<<endl; else cout<<"Left Child = "<<pBaru->left->info<<endl; if(pBaru->right == NULL) cout<<"Right Child = NULL"<<endl; else cout<<"Right Child = "<<pBaru->right->info<<endl; cout<<endl; Anak(Root->left, pBaru); Anak(Root->right, pBaru); } } int main(){ Tree Root; pointer p; int pil, n; char ans; Root=NULL; cout<<"\tTREE"<<endl; cout<<"Masukkan banyak data :"; cin>>n; //masukkin 15 for (int i=0;i<n;i++){ createSimpul(p); insertBST(Root,p); //input 7 11 3 4 5 9 12 15 1 10 2 25 8 14 19 } do{ system("CLS"); cout<<"\tMENU"<<endl; cout<<"====================="<<endl; cout<<"[1] Insert BST"<<endl; cout<<"[2] Preorder"<<endl; cout<<"[3] Inorder"<<endl; cout<<"[4] Postorder"<<endl; cout<<"[5] Kedalaman"<<endl; cout<<"[6] Level"<<endl; cout<<"[7] Anak"<<endl; cout<<"[8] Exit"<<endl; cout<<"====================="<<endl; cout<<"Pilihan : ";cin>>pil; switch(pil){ case 1: cout<<"\nInsert BST "<<endl; createSimpul(p); insertBST(Root,p); case 2: cout<<"\nPREORDER"<<endl; preOrder(Root); break; case 3: cout<<"\nINORDER"<<endl; inOrder(Root); break; case 4: cout<<"\nPOSTORDER"<<endl; postOrder(Root); break; case 5: cout<<"\nKEDALAMAN"<<endl; kedalaman(Root); break; case 6: cout<<"\nLEVEL"<<endl; levelOrder(Root); break; case 7: cout<<"ANAK"<<endl; Anak(Root, p); break; case 8: cout<<"\nOke Sudah selesai, Terima Kasih :) "<<endl; return 0; break; default: cout<<"MAMPUS SALAH NGASAL INPUT SIH!!"<<endl; break; } cout<<"Kembali ke menu?(Y/N)"; cin>>ans; } while(ans=='y'|| ans=='Y'); }
true
d581592d5abf9150039e53005b04bcde5ca2eccf
C++
dfki-asr/patchwise_inpainting_zcurves
/libInpainting/src/costfunction/L2CostFunction.cpp
UTF-8
1,341
2.515625
3
[]
no_license
#include "stdafx.h" #include "L2CostFunction.h" #include "dictionary/Dictionary.h" #include "StatusFlags.h" namespace inpainting { L2CostFunction::L2CostFunction(Problem* problem, Dictionary* dictionary) : DictionaryBasedCostFunctionKernel( problem, dictionary ) { } L2CostFunction::~L2CostFunction() { } void L2CostFunction::computeCostForInterval(IndexInterval interval) { for (int dictionaryIndex = interval.first; dictionaryIndex <= interval.last; dictionaryIndex++) { const int patchIndex = dictionary->getCompressedDictionary()[ dictionaryIndex ]; const float cost = computeCostFunction( patchIndex ); resultCost.push_back(cost); } } float L2CostFunction::computeCostFunction( unsigned int indexOfSourcePatch ) { dictionaryAccess.setPatchId(indexOfSourcePatch); dataAccess.setPatchId(indexOfTargetPatch); maskAccess.setPatchId(indexOfTargetPatch); float distance = 0.0f; for (unsigned int i = 0; i < dataAccess.size(); i++) { const unsigned char pixelStatus = maskAccess[i]; if (pixelStatus == EMPTY_REGION || pixelStatus == TARGET_REGION) continue; unsigned char pA = dictionaryAccess[i]; unsigned char pB = dataAccess[i]; const float distanceInDimension = (float)(pB - pA); distance += distanceInDimension * distanceInDimension; } return sqrtf(distance); } }
true
84d1e3a6f9661ddd569c589f2285cfe70035f609
C++
hj24/PAT-A-Level
/PAT_A_1013.cpp
UTF-8
766
2.8125
3
[]
no_license
#include <cstdio> #include <algorithm> using namespace std; int v[1000][1000]; bool visited[1000]; int n, m, k; void creat_map(){ scanf("%d%d%d",&n,&m,&k); for (int i = 0; i < m; ++i){ int c_1, c_2; scanf("%d%d",&c_1,&c_2); v[c_1][c_2] = v[c_2][c_1]= 1; } } void dfs(int node){ visited[node] = true; for (int i = 1; i <= n; ++i){ if (visited[i] == false && v[node][i] == 1){ dfs(i); } } } void solve(){ for (int i = 0; i < k; ++i){ int count = 0; fill(visited, visited + 1000, false); int c; scanf("%d",&c); visited[c] = true; for (int j = 1; j <= n ; ++j){ if (visited[j] == false){ dfs(j); count++; } } printf("%d\n", count - 1); } } int main(int argc, char const *argv[]){ creat_map(); solve(); return 0; }
true
d8f13688cfb3ecd32c305af8714ebec919162c1a
C++
kovarex/BhaalBot
/src/CostReservation.hpp
UTF-8
768
2.9375
3
[]
no_license
#pragma once #include <Cost.hpp> #include <string> #include <vector> #include <Module.hpp> class CostReservation; class CostReservationItem { public: CostReservationItem(Cost cost); virtual ~CostReservationItem(); virtual std::string str() const = 0; void clear(); Cost cost; CostReservation* owner; }; class CostReservation : Module { public: CostReservation(ModuleContainer& moduleContainer); ~CostReservation(); void registerItem(CostReservationItem* item); void unregisterItem(CostReservationItem* item); Cost getReseved() const { return this->reserved; } void onFrame() override; bool canAfford(const Cost& cost) const; private: void erase(CostReservationItem* item); std::vector<CostReservationItem*> items; Cost reserved; };
true
19f357b93d22da12790b1066078cf3d42d824ba3
C++
Touhidul121/All_code4
/The 81 part 4/smart_phone.cpp
UTF-8
416
2.515625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { ll n; cin>>n; ll a; vector<ll>v; for(int i=0;i<n;i++) { cin>>a; v.push_back(a); } ll res=0; sort(v.begin(),v.end()); if(n&1) { res=v[n/2]; cout<<(ll)res*((n/2)+1)<<"\n"; } else { res=v[n/2-1]; cout<<(ll)res*(n/2+1)<<"\n"; } }
true
91e5030713c741613311f26414b0469f223bd88c
C++
vslavik/poedit
/deps/boost/libs/polygon/test/voronoi_diagram_test.cpp
UTF-8
3,540
2.53125
3
[ "GPL-1.0-or-later", "MIT", "BSL-1.0" ]
permissive
// Boost.Polygon library voronoi_diagram_test.cpp file // Copyright Andrii Sydorchuk 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. #include <boost/core/lightweight_test.hpp> #include <boost/polygon/voronoi_diagram.hpp> #include <boost/polygon/voronoi_geometry_type.hpp> using namespace boost::polygon; typedef voronoi_cell<double> voronoi_cell_type; typedef voronoi_vertex<double> voronoi_vertex_type; typedef voronoi_edge<double> voronoi_edge_type; typedef voronoi_diagram<double> voronoi_diagram_type; void voronoi_cell_test() { voronoi_cell_type cell(1, SOURCE_CATEGORY_INITIAL_SEGMENT); cell.color(27); BOOST_TEST(!cell.contains_point()); BOOST_TEST(cell.contains_segment()); BOOST_TEST(cell.is_degenerate()); BOOST_TEST(cell.source_index() == 1); BOOST_TEST(cell.source_category() == SOURCE_CATEGORY_INITIAL_SEGMENT); BOOST_TEST(cell.incident_edge() == NULL); BOOST_TEST(cell.color() == 27); voronoi_edge_type edge(true, true); cell.incident_edge(&edge); BOOST_TEST(!cell.is_degenerate()); BOOST_TEST(cell.incident_edge() == &edge); } void voronoi_vertex_test() { voronoi_vertex_type vertex(1, 2); vertex.color(27); BOOST_TEST(vertex.is_degenerate()); BOOST_TEST(vertex.x() == 1); BOOST_TEST(vertex.y() == 2); BOOST_TEST(vertex.incident_edge() == NULL); BOOST_TEST(vertex.color() == 27); voronoi_edge_type edge(true, true); vertex.incident_edge(&edge); BOOST_TEST(!vertex.is_degenerate()); BOOST_TEST(vertex.incident_edge() == &edge); } void voronoi_edge_test() { voronoi_edge_type edge1(false, false); edge1.color(13); BOOST_TEST(!edge1.is_primary()); BOOST_TEST(edge1.is_secondary()); BOOST_TEST(!edge1.is_linear()); BOOST_TEST(edge1.is_curved()); BOOST_TEST(!edge1.is_finite()); BOOST_TEST(edge1.is_infinite()); BOOST_TEST(edge1.color() == 13); voronoi_edge_type edge2(true, true); edge2.color(14); BOOST_TEST(edge2.is_primary()); BOOST_TEST(!edge2.is_secondary()); BOOST_TEST(edge2.is_linear()); BOOST_TEST(!edge2.is_curved()); BOOST_TEST(!edge2.is_finite()); BOOST_TEST(edge2.is_infinite()); BOOST_TEST(edge2.color() == 14); edge1.twin(&edge2); edge2.twin(&edge1); BOOST_TEST(edge1.twin() == &edge2); BOOST_TEST(edge2.twin() == &edge1); edge1.next(&edge2); edge1.prev(&edge2); edge2.next(&edge1); edge2.prev(&edge1); BOOST_TEST(edge1.next() == &edge2); BOOST_TEST(edge1.prev() == &edge2); BOOST_TEST(edge1.rot_next() == &edge1); BOOST_TEST(edge1.rot_prev() == &edge1); voronoi_cell_type cell(1, SOURCE_CATEGORY_INITIAL_SEGMENT); edge1.cell(&cell); BOOST_TEST(edge1.cell() == &cell); voronoi_vertex_type vertex0(1, 2); edge1.vertex0(&vertex0); BOOST_TEST(edge1.vertex0() == &vertex0); BOOST_TEST(edge2.vertex1() == &vertex0); voronoi_vertex_type vertex1(2, 1); edge2.vertex0(&vertex1); BOOST_TEST(edge1.vertex1() == &vertex1); BOOST_TEST(edge2.vertex0() == &vertex1); BOOST_TEST(edge1.is_finite()); BOOST_TEST(edge2.is_finite()); } void voronoi_diagram_test() { voronoi_diagram_type vd; BOOST_TEST(vd.num_cells() == 0); BOOST_TEST(vd.num_vertices() == 0); BOOST_TEST(vd.num_edges() == 0); vd.clear(); } int main() { voronoi_cell_test(); voronoi_vertex_test(); voronoi_edge_test(); voronoi_diagram_test(); return boost::report_errors(); }
true
2e38194e1d6511d815e4dc6cb4ad1fb6d2d50087
C++
Sachin5411/Algo-Practice-C-
/smartkeypad.cpp
UTF-8
552
2.953125
3
[]
no_license
#include<iostream> using namespace std; string table[] = { " ", ".+@$", "abc", "def", "ghi", "jkl" , "mno", "pqrs" , "tuv", "wxyz" }; void smartkeypad(char in[],char out[],int i,int j) { if(in[i]=='\0'){ out[j]='\0'; cout<<out<<endl; return; } int digit=in[i]-'0'; for(int k=0;table[digit][k]!='\0';k++){ out[j]=table[digit][k]; smartkeypad(in,out,i+1,j+1); } } int main(){ char in[100],out[100]; cin>>in; smartkeypad(in,out,0,0); return 0; }
true
be7727b77bf9b3cd0303dcdd3f1995afac935016
C++
yuvalschl/max-flow-algorithem
/HeapCell.cpp
UTF-8
431
3.125
3
[]
no_license
#include "HeapCell.h" HeapCell::HeapCell() { this->m_key = 0; this->m_data = 0; } HeapCell::HeapCell(int key, int data) { this->m_key = key; this->m_data = data; } int HeapCell::getKey() const { return this->m_key; } int HeapCell::getData() const { return this->m_data; } void HeapCell::setKey(int key) { this->m_key = key; } void HeapCell::setData(int data) { this->m_data = data; }
true
023d63e45f0aca6e242f36916459f26f38a7bfa4
C++
MingYueRuYa/cprimeprimecode
/c++_code/constructor/manage_dynamic_cache/strvec.cpp
UTF-8
1,848
3
3
[]
no_license
/**************************************************************** ** ** Copyright (C) 2016 635672377@qq.com ** All rights reserved. ** ***************************************************************/ #include <memory> #include <iostream> #include <algorithm> #include "strvec.h" using std::cout; using std::endl; StrVec::StrVec() { mFirst = nullptr; mEnd = nullptr; mCapacity = nullptr; } StrVec::StrVec(std::initializer_list<string> pStringList) { mFirst = mAllocator.allocate(pStringList.end() - pStringList.begin()); mEnd = uninitialized_copy(pStringList.begin(), pStringList.end(), mFirst); } StrVec::~StrVec() { Free(); } StrVec::StrVec(const StrVec &pStrVec) { } StrVec::StrVec(const StrVec &&pStrVec) { } StrVec& StrVec::operator=(const StrVec &pStrVec) { return *this; } StrVec& StrVec::operator=(const StrVec &&pStrVec) { return *this; } void StrVec::PushBack(const string &pString) { //check memory is enough //CheckMemory() mAllocator.construct(mEnd++, pString); } void StrVec::Foreach() { string *tempstring = mFirst; while (mEnd - tempstring) { cout << *tempstring++ << " "; } cout << endl; } size_t StrVec::Size() { return mEnd - mFirst; } void StrVec::Free() { if (nullptr != mFirst && nullptr != mEnd) { string *tempstring = mFirst; while (mEnd - tempstring) { mAllocator.destroy(tempstring++); } mAllocator.deallocate(mFirst, mCapacity - mFirst); } } void StrVec::Reallocator() { size_t size = mEnd - mFirst; string *firstaddr = mAllocator.allocate(size * 2); string *endaddr = uninitialized_copy(mFirst, mEnd, firstaddr); Free(); mFist = firstaddr; mEnd = endaddr; mCapacity = mFirst + size * 2; } bool StrVec::CheckMemory() { size_t currentsize = mEnd - mFirst; size_t maxsize = mCapacity - mFirst; if (currentsize >= maxsize) { return true; } return false; }
true
8d0f0db4e1056cd6d96d2bc778cdd986d860ffda
C++
frozenca/CLRS
/12_binary_search_trees/easy/03_bst_successor.h
UTF-8
5,881
2.9375
3
[ "Apache-2.0" ]
permissive
#ifndef __CLRS4_BST_SUCCESSOR_H__ #define __CLRS4_BST_SUCCESSOR_H__ #include <cassert> #include <common.h> #include <iostream> #include <stdexcept> namespace frozenca { using namespace std; template <typename T> struct BSTSuccNode { T key_ = T{}; BSTSuccNode *succ_ = nullptr; unique_ptr<BSTSuccNode> left_; unique_ptr<BSTSuccNode> right_; BSTSuccNode() = default; BSTSuccNode(const T &key) : key_{key} {} BSTSuccNode(const BSTSuccNode &node) = delete; BSTSuccNode &operator=(const BSTSuccNode &node) = delete; BSTSuccNode(BSTSuccNode &&node) = delete; BSTSuccNode &operator=(BSTSuccNode &&node) = delete; friend void succ_print(ostream& os, const BSTSuccNode* node) { if (node) { os << node->key_ << ' '; succ_print(os, node->succ_); } } }; template <typename T, typename Comp = less<T>> class BSTSuccessor { using Node = BSTSuccNode<T>; unique_ptr<Node> root_; static void verify(const Node *node) { if (!node) { return; } assert(!node->left_ || (Comp{}(node->left_->key_, node->key_))); assert(!node->right_ || (Comp{}(node->key_, node->right_->key_))); verify(node->left_.get()); verify(node->right_.get()); } void verify() const { verify(root_.get()); } public: BSTSuccessor() = default; BSTSuccessor(const BSTSuccessor &other) = delete; BSTSuccessor &operator=(const BSTSuccessor &other) = delete; BSTSuccessor(BSTSuccessor &&other) = delete; BSTSuccessor &operator=(BSTSuccessor &&other) = delete; Node *tree_search(const T &key) const { return tree_search(root_.get(), key); } void tree_insert(const T &key) { auto z = make_unique<Node>(key); auto x = root_.get(); Node *y = nullptr; Node *pred = nullptr; while (x) { y = x; if (Comp{}(z->key_, x->key_)) { x = x->left_.get(); } else { pred = x; x = x->right_.get(); } } if (!y) { root_ = move(z); } else if (Comp{}(key, y->key_)) { y->left_ = move(z); if (pred) { pred->succ_ = y->left_.get(); } y->left_->succ_ = y; } else { y->right_ = move(z); y->right_->succ_ = y->succ_; y->succ_ = y->right_.get(); } verify(); } private: static Node *tree_minimum(Node *node) { while (node && node->left_) { node = node->left_.get(); } return node; } static Node *tree_maximum(Node *node) { while (node && node->right_) { node = node->right_.get(); } return node; } public: void tree_delete(const T &key) { auto x = root_.get(); Node *parent = nullptr; Node *pred = nullptr; while (x && key != x->key_) { parent = x; if (Comp{}(key, x->key_)) { x = x->left_.get(); } else { pred = x; x = x->right_.get(); } } if (!x) { return; } if (!x->left_) { // replace x by its right child if (!parent) { root_ = move(x->right_); } else if (x == parent->left_.get()) { parent->left_ = move(x->right_); if (pred) { if (parent->left_) { pred->succ_ = tree_minimum(parent->left_.get()); } else { pred->succ_ = parent; } } } else { auto succ = x->succ_; parent->right_ = move(x->right_); parent->succ_ = succ; } } else if (!x->right_) { // replace x by its left child if (!parent) { root_ = move(x->left_); pred = tree_maximum(root_.get()); if (pred) { pred->succ_ = nullptr; } } else if (x == parent->left_.get()) { parent->left_ = move(x->left_); pred = tree_maximum(parent->left_.get()); if (pred) { pred->succ_ = parent; } } else { auto succ = x->succ_; parent->right_ = move(x->left_); parent->succ_ = tree_minimum(parent->right_.get()); pred = tree_maximum(parent->right_.get()); pred->succ_ = succ; } } else { auto y = x->right_.get(); auto yp = x; while (y->left_) { yp = y; y = y->left_.get(); } unique_ptr<Node> y_holder; if (y != x->right_.get()) { unique_ptr<Node> yr = move(y->right_); y_holder = move(yp->left_); yp->left_ = move(yr); y_holder->right_ = move(x->right_); if (yp->left_) { y_holder->succ_ = tree_minimum(yp->left_.get()); } else { y_holder->succ_ = yp; } } if (!y_holder) { assert(yp == x); y_holder = move(x->right_); } auto xl = move(x->left_); pred = tree_maximum(xl.get()); if (!parent) { root_ = move(y_holder); y = root_.get(); } else if (x == parent->left_.get()) { parent->left_ = move(y_holder); y = parent->left_.get(); } else { parent->right_ = move(y_holder); y = parent->right_.get(); } pred->succ_ = y; y->left_ = move(xl); } verify(); } static Node *tree_search(Node *node, const T &key) { if (!node || key == node->key_) { return node; } if (Comp{}(key, node->key_)) { return tree_search(node->left_.get(), key); } else { return tree_search(node->right_.get(), key); } } friend ostream &operator<<(ostream &os, const BSTSuccessor<T> &tree) { auto node = tree.root_.get(); while (node && node->left_) { node = node->left_.get(); } succ_print(os, node); return os; } }; } // namespace frozenca #endif //__CLRS4_BST_SUCCESSOR_H__
true
79b83d98523c6f1baa694a6e59dc5884c6ae9582
C++
VinekNet/Zombie
/src/Bomber.cpp
UTF-8
315
2.6875
3
[]
no_license
#include "Bomber.h" Bomber::Bomber() { setStrenght(getStrenght()*2); //ctor } Bomber::~Bomber() { cout<<"Zombie Bomber " <<getNom() << " detruit"<<endl; //dtor } void Bomber::explosion(Zombie* cible){ cible->setPv(cible->getPv() - (getStrenght()*3)); Zombie::~Zombie; }
true
48b0371e5d0877c57b1293040b4b26ea03343713
C++
akasharun-gh/SDL-2D-Game
/src/animation.cpp
UTF-8
1,818
3.1875
3
[]
no_license
#include <iostream> #include "animation.h" // Method to load texture of image to render target SDL_Texture *Animation::LoadTexture(std::string filepath, SDL_Renderer *renderTarget) { SDL_Texture *texture = nullptr; SDL_Surface *surface = IMG_Load(filepath.c_str()); if (surface == NULL) std::cout << "Error: " << SDL_GetError() << std::endl; else { texture = SDL_CreateTextureFromSurface(renderTarget, surface); if (texture == NULL) { std::cout << "Error: " << SDL_GetError() << std::endl; } } SDL_FreeSurface(surface); return texture; } // Method to initialize the position of the animation on the screen void Animation::initAnimationPos(int &&xy_init_pos) { animationPos.x = animationPos.y = xy_init_pos; animationPos.w = frameWidth; animationPos.h = frameHeight; initPos.x = initPos.y = xy_init_pos; initPos.w = frameWidth; initPos.h = frameHeight; } // Method to initialize the sprite animation from the sprite sheet provided void Animation::initAnimationRect(int &&sprite_w, int &&sprite_h, int &&x, int &&y) { frameWidth = textureWidth / sprite_w; frameHeight = textureHeight / sprite_h; // Initialize Animation animationRect.x = frameWidth * x; animationRect.y = frameHeight * y; animationRect.w = frameWidth; animationRect.h = frameHeight; } // Method to resize the dimensions of the animation on screeen void Animation::resizeAnimation(int &&fwidth, int &&fheight) { animationPos.w = fwidth; animationPos.h = fheight; } // Returns the current position of the animation SDL_Rect &Animation::getPlayerPos() { return animationPos; } // Returns the current Rect of the animation on sprite sheet SDL_Rect &Animation::getPlayerRect() { return animationRect; }
true
15dc4e0811bb0d1006f8efb642306a799ae19e31
C++
thijsking/AirHandlingUnit
/Eind code AHU/_TheUnit/src/HeatingElement.cpp
UTF-8
683
3.34375
3
[]
no_license
#include "HeatingElement.h" /** * Create the HeatingElement object and assign the provided parameter data to the corresponding variables. */ HeatingElement::HeatingElement(iCommunication* communication, uint8_t address) : iActuator(communication,address) { } /** * Destroy the HeatingElement object */ HeatingElement::~HeatingElement() { } /** * It first checks if the value isn't to high, because our setup can't handle that. It also checks if it isn't a negative number. * After that it calls the SetValue function of his base class. */ void HeatingElement::SetValue(uint8_t value) { if (value < 0) value = 0; else if (value > 30) value = 30; iActuator::SetValue(value); }
true
c27065c5d9b82e7b076745ec56411554c7a66f1a
C++
ClaraGhabro/text_mining
/src/trie/nodes.hh
UTF-8
680
3.046875
3
[]
no_license
#pragma once #include "node.hh" namespace trie { /** * \fn add_node * * \brief Add a node in the vector containing all nodes */ std::size_t add_node(); /** * \fn get_node * * \brief Return a node using a given index. * * \param index The index of the node to return */ Node& get_node(std::size_t index); /** * \fn serialize_node * * \brief Serialiaze nodes in a file * * \param file where the nodes will be serialized */ void serialize_nodes(const char* file); /** * \f deserialize_node * * \brief Deserialiaze a file and put its content in a vector of node * * \param file where the content will be read */ Node& deserialize_nodes(const char* file); }
true
db0e9eb4341e643c8081f9a53b9a416d92628aca
C++
manishhedau/Data-Structure-Algorithm
/6. Linked List/8_Merge_sort_over_ll.cpp
UTF-8
1,904
3.71875
4
[ "MIT" ]
permissive
// Code By - Manish Hedau #include<bits/stdc++.h> using namespace std; class node { public: int data; node *next; // constructor node(int d) { data = d; next = NULL; } }; void insertHead(node *&head, int data) { // check if ll is empty if (head == NULL) { head = new node(data); return; } node *new_bucket = new node(data); new_bucket->next = head; head = new_bucket; } void printNode(node *head) { while (head != NULL) { cout << head->data << " -> "; head = head->next; } cout << endl; } void take_input(node *&head) { int data; cin >> data; while (data != -1) { insertHead(head, data); cin >> data; } } node *midPoint(node *head) { node *slow = head; node *fast = head->next; while (fast != NULL and fast->next != NULL) { fast = fast->next->next; slow = slow->next; } return slow; } node *merge(node *head1, node *head2) { // base case if (head1 == NULL) { return head2; } if (head2 == NULL) { return head1; } node *temp = NULL; if (head1->data < head2->data) { temp = head1; temp->next = merge(head1->next, head2); } else { temp = head2; temp->next = merge(head1, head2->next); } return temp; } // Time complexity - O(N logN) // Space complexity - O(N) node *merge_sort(node *head) { // base case if (head == NULL or head->next == NULL) { return head; } // Recursive case // 1. Break node *mid = midPoint(head); node * first = head; node * second = mid->next; mid->next = NULL; // 2. Recursive sort the linked list first = merge_sort(first); second = merge_sort(second); return merge(first, second); } int main() { node *head = NULL; take_input(head); printNode(head); cout << "Sorting the Linked List : " << endl; head = merge_sort(head); printNode(head); return 0; } /* Input :- -------- 5 6 8 2 1 -1 Output :- --------- 1 -> 2 -> 8 -> 6 -> 5 -> Sorting the Linked List : 1 -> 2 -> 5 -> 6 -> 8 -> */
true
4576b4639d36b6438fb2ac231c8e2846f7254018
C++
UnitySio/MonoChrome-Direct2D-GUI-Framework
/x64/Framework/Includes/Color.cpp
UTF-8
474
2.90625
3
[]
no_license
#include "Color.h" Color* Color::DarkGray = new Color(60, 60, 60, 255); Color* Color::LightGray = new Color(180, 180, 180, 255); Color* Color::Black = new Color(0, 0, 0, 255); Color* Color::White = new Color(255, 255, 255, 255); Color* Color::Red = new Color(255, 0, 0, 255); Color* Color::Green = new Color(0, 255, 0, 255); Color* Color::Blue = new Color(0, 0, 255, 255); Color* Color::Cyan = new Color(0, 255, 255, 255); Color* Color::Brown = new Color(139, 69, 19, 255);
true
68a22f6e5326130a06d93a1ca85d283ad24dac74
C++
palais-ai/ailib
/AICore/Blackboard.h
UTF-8
3,670
3.09375
3
[ "MIT" ]
permissive
#ifndef BLACKBOARD_H #define BLACKBOARD_H #pragma once #include "ai_global.h" #include "Any.h" #include "btHashMap.h" #include <map> BEGIN_NS_AILIB template <typename KEY> class BlackboardListener { public: virtual void onValueChanged(const KEY& key, const ailib::hold_any& value) = 0; }; typedef uint32_t Handle; const static Handle INVALID_HANDLE = 0; /** * @brief Blackboard A generic class to store knowledge associated to unique keys. */ template <typename KEY> class Blackboard { typedef std::map<Handle, BlackboardListener<KEY>* > BlackboardListeners; public: typedef KEY key_type; Blackboard() : mCount(INVALID_HANDLE) { ; } // INVALID_HANLDE (= 0) is never returned. Handle addListener(BlackboardListener<KEY>* listener) { AI_ASSERT(listener, "Tried to add NULL listener."); mListeners.insert(std::make_pair(++mCount, listener)); return mCount; } void removeListener(Handle id) { size_t numRemoved = mListeners.erase(id); AI_ASSERT(numRemoved == 1, "Tried to remove non-existant listener."); } template <typename T> FORCE_INLINE T get(const KEY& key) const { return ailib::any_cast<T>(mKnowledge[key]); } FORCE_INLINE bool has(const KEY& key) const { return mKnowledge.find(key) != NULL; } template <typename T> void set(const KEY& key, const T& value) { ailib::hold_any newVal(value); mKnowledge.insert(key, newVal); for(typename BlackboardListeners::iterator it = mListeners.begin(); it != mListeners.end(); ++it) { it->second->onValueChanged(key, newVal); } } FORCE_INLINE void remove(const KEY& key) { mKnowledge.remove(key); } uint32_t getHashCode() const { // CREDITS: FNV-1a algorithm primes from http://www.isthe.com/chongo/tech/comp/fnv/ // (public domain) static const uint32_t fnv_prime = 16777619; static const uint32_t offset_basis = 2166136261; uint32_t hash = offset_basis; // Combine the hashes of the individual keys. for(int i = 0; i < mKnowledge.size(); ++i) { hash *= fnv_prime; hash += mKnowledge.getKeyAtIndex(i).getHash(); } } FORCE_INLINE int size() const { return mKnowledge.size(); } bool operator==(const Blackboard& other) const { if(size() != other.size()) { return false; } for(int i = 0; i < mKnowledge.size(); ++i) { const KEY& key = mKnowledge.getKeyAtIndex(i); const ailib::hold_any* value = other.mKnowledge.find(key); if(value == NULL || *value != *mKnowledge.getAtIndex(i)) { return false; } } return true; } private: // TODO: Use sparse hashmap instead. btHashMap<KEY, ailib::hold_any> mKnowledge; BlackboardListeners mListeners; uint32_t mCount; }; // Adapter class to enable the use of Blackboards as keys in btHashMap. template <typename KEY> class HashBlackboard { private: Blackboard<KEY>* mBlackboard; unsigned int mHash; public: HashBlackboard(Blackboard<KEY>* board) : mBlackboard(board), mHash(board->getHashCode()) { ; } FORCE_INLINE unsigned int getHash() const { return mHash; } FORCE_INLINE bool equals(const HashBlackboard& other) const { return mBlackboard == other.mBlackboard; } }; END_NS_AILIB #endif // BLACKBOARD_H
true
9fe149e53bdd1a11784d14f106287de1c1376373
C++
bbernardoni/pillow
/pillow/enemy.cpp
UTF-8
564
2.5625
3
[ "MIT" ]
permissive
#include "enemy.h" Enemy::Enemy(Vector2f pos) : Character(Texture(), IntRect(0, 0, 50, 100), NULL, pos) { id = enemy; damaging = true; addBoundingBox(FloatRect(0.0f, 0.0f, 1.0f, 1.0f)); hp = 100.0f; } void Enemy::update(Time deltaTime){ float dt = deltaTime.asSeconds(); Vector2f vel = getArrowsVel() * dt; Uint8 color = (Uint8)(hp / 100.0f * 255.0f); sprite.setColor(Color(0, color, 0)); setDirAngle(vel); sprite.move(vel); } float Enemy::getDamage(EntityID source){ return 10; } Time Enemy::getInvTime(EntityID source){ return seconds(0.1f); }
true