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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0bd2a714387e80a1741ba5f9db4e411e77e434ed | C++ | shuaizengMU/AlgorithmDesign | /Leetcode/695.cpp | UTF-8 | 1,724 | 2.890625 | 3 | [] | no_license | /*
template
*/
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
#define MAX(x, y) ((x)>(y)?(x):(y))
#define MIN(x, y) ((x)<(y)?(x):(y))
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const long long INFL = 0x3f3f3f3f3f3f3f3fLL;
int dfs(vector< vector<int> >& grid, int m, int n) {
if(grid[m][n] == 0)
return 0;
int orient[4][2] = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1}
};
int res = 1;
grid[m][n] = 0;
for(int i=0; i<4; i++){
if(-1<m+orient[i][0] && m+orient[i][0]<grid.size() && -1<n+orient[i][1] && n+orient[i][1]<grid[0].size())
res += dfs(grid, m+orient[i][0], n+orient[i][1]);
}
return res;
}
int maxAreaOfIsland(vector< vector<int> >& grid) {
if(grid.empty())
return 0;
int m = grid.size();
int n = grid[0].size();
int res = 0;
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j) {
if(grid[i][j] != 0 ) {
res = max(dfs(grid, i, j), res);
// printf("%d %d, %d\n", i, j, res);
}
}
}
return res;
}
int main(){
#ifndef ONLINE_JUDGE
assert(freopen("text.in", "r", stdin));
// assert(freopen("text.out", "w", stdout));
#endif
int m, n;
scanf("%d %d", &m, &n);
vector< vector<int> > vec(m, vector<int>(n));
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
scanf("%d", &vec[i][j]);
maxAreaOfIsland(vec);
return 0;
}
| true |
54e136fd2325887251d34558f8689a2bde1dcf7d | C++ | adolli/FruitString | /FruitString/FruitString.hpp | GB18030 | 4,890 | 3.453125 | 3 | [] | no_license |
#ifndef _ADOLLI_STRING_
#define _ADOLLI_STRING_
#include<ostream>
namespace adolli
{
template<
class _CharT,
class _CharTraits,
template <class> class StoragePolicy >
class string
: protected StoragePolicy<_CharT>
{
public:
typedef _CharT CharT;
typedef _CharTraits CharTraits;
typedef typename StoragePolicy<CharT>::size_type size_type;
typedef typename StoragePolicy<CharT>::pos_type pos_type;
typedef string& RefType;
typedef const string& ConstRefType;
typedef CharT* RawArrayType;
typedef const CharT* ConstRawArrayType;
typedef CharT& CharRefType;
typedef const CharT& ConstCharRefType;
// еĹ캯УǼս
string()
: StoragePolicy<CharT>()
{
at(Length()) = CharTraits::TERMINATOR;
}
string(const CharT* str)
: StoragePolicy<CharT>(str, CharTraits::GetLenth(str))
{
at(Length()) = CharTraits::TERMINATOR;
}
string(const CharT* str, int len)
: StoragePolicy<CharT>(str, len)
{
at(Length()) = CharTraits::TERMINATOR;
}
string(const CharT c)
: StoragePolicy<CharT>(c)
{
at(Length()) = CharTraits::TERMINATOR;
}
string(const string& rhs)
: StoragePolicy<CharT>(rhs)
{
at(Length()) = CharTraits::TERMINATOR;
}
using StoragePolicy<CharT>::operator=;
size_type Length() const
{
return Size() * CharTraits::UNIT_LENGTH;
}
RefType append(size_type n, const CharT c)
{
size_type oriSize = Length();
Reserve(n);
CharT* pc = data_ + oriSize;
while (n--)
{
*pc++ = c;
}
*pc = CharTraits::TERMINATOR;
return *this;
}
RefType append(ConstRefType str)
{
size_type oriSize = Length();
size_type appendSize = str.Length();
Reserve(appendSize);
memcpy(data_ + oriSize, str.data_, appendSize + 1);
return *this;
}
RefType append(ConstRawArrayType str)
{
size_type oriSize = Length();
size_type appendSize = CharTraits::GetLenth(str);
Reserve(appendSize);
memcpy(data_ + oriSize, str, appendSize + 1);
return *this;
}
RefType operator+=(ConstRefType str)
{
return append(str);
}
RefType operator+=(ConstRawArrayType str)
{
return append(str);
}
CharRefType at(pos_type n)
{
return Get(n);
}
const CharRefType at(pos_type n) const
{
return Get(n);
}
CharRefType operator[](pos_type n) const
{
return Get(n);
}
template< class StringType_OrRawStringType >
int Compare(const StringType_OrRawStringType& str)
{
pos_type i = 0;
while ((at(i) != CharTraits::TERMINATOR || str[i] != CharTraits::TERMINATOR)
&& CharTraits::eq(at(i), str[i]))
{
++i;
}
if (CharTraits::eq(this->at(i), str[i]))
{
return 0;
}
else if (CharTraits::lt(this->at(i), str[i]))
{
return -1;
}
else
{
return 1;
}
}
using StoragePolicy<CharT>::Clear;
string Substr(pos_type p);
string Substr(pos_type p, size_type n);
protected:
using StoragePolicy<CharT>::Get;
using StoragePolicy<CharT>::Reserve;
using StoragePolicy<CharT>::Size;
using StoragePolicy<CharT>::data_;
};
template< class StringType >
bool operator==(const StringType& s1, const StringType& s2)
{
if (s1.Length() != s2.Length())
{
return false;
}
for (StringType::size_type i = 0; i < s1.Length(); ++i)
{
if (!StringType::CharTraits::eq(s1[i], s2[i]))
{
return false;
}
}
return true;
}
template< class StringType >
bool operator==(typename StringType::ConstRawArrayType s1, const StringType& s2)
{
typedef typename StringType::CharTraits CharTraits;
StringType::size_type i = 0;
for ( ;
i < s2.Length() && *s1 != StringType::CharTraits::TERMINATOR;
++i, ++s1)
{
if (!CharTraits::eq(*s1, s2[i]))
{
return false;
}
}
if (*s1 != CharTraits::TERMINATOR || s2[i] != CharTraits::TERMINATOR)
{
return false;
}
return true;
}
template< class StringType >
bool operator==(const StringType& s1, typename StringType::ConstRawArrayType s2)
{
return operator==<StringType>(s2, s1);
}
template< class StringType >
bool operator!=(const StringType& s1, const StringType& s2)
{
return !operator==(s1, s2);
}
template< class StringType >
bool operator!=(typename StringType::ConstRawArrayType s1, const StringType& s2)
{
return !operator==(s1, s2);
}
template< class StringType >
bool operator!=(const StringType& s1, typename StringType::ConstRawArrayType s2)
{
return !operator==(s1, s2);
}
template<
class _CharT,
class _CharTraits,
template <class> class StoragePolicy >
std::ostream & operator<<(std::ostream & os, string<_CharT, _CharTraits, StoragePolicy> s)
{
typedef typename string<_CharT, _CharTraits, StoragePolicy>::size_type size_type;
for (size_type i = 0; i < s.Length(); ++i)
{
os << s[i];
}
return os;
}
}
#endif /*_ADOLLI_STRING_*/
| true |
83366a2a5848bf58fccba295f48880a308a20568 | C++ | green-fox-academy/zolnay | /week_6/greatest_value/myApp_tests/myAppTest.cpp | UTF-8 | 913 | 3.375 | 3 | [] | no_license | #include <gtest/gtest.h>
#include "matrix.h"
#include <vector>
TEST(greater_matrix, greater_matrix_2times2_test)
{
std::vector<std::vector<int>> matrix = {
{2,1},
{0,1}
};
std::vector<std::vector<int>> secondMatrix = {
{0,3},
{-1,1}
};
std::vector<std::vector<int>> expected = {{2, 3},
{ 0, 1 }
};
EXPECT_EQ(matrixGreatest(matrix, secondMatrix), expected);
}
TEST(greater_matrix, greater_matrix_3times3_test)
{
std::vector<std::vector<int>> matrix = {
{-1, 1, 0},
{0, 1, 0},
{0, 1, 0}
};
std::vector<std::vector<int>> secondMatrix = {
{0, 0, 0},
{0, 1, 0},
{0, 0, 0}
};
std::vector<std::vector<int>> expected = { { 0, 1, 0 },
{ 0, 1, 0 },
{ 0, 1, 0 }
};
EXPECT_EQ(matrixGreatest(matrix, secondMatrix), expected);
} | true |
974040338027f52cfd307a2cbd9627ede0153505 | C++ | ChaKon/Software_Engineering_Robust_Principle_Axis_Detection | /Software_Engineering_Robust_Principle_Axis_Detection/Mesh/RPA.cpp | UTF-8 | 9,689 | 2.671875 | 3 | [] | no_license | /////////////////////////// Student Work /////////////////////////////////
#include "math.h"
#include <algorithm>
#include <map>
#include "RPA.h"
void GenEigen::CopyEig(const Mesh &myMesh){ //Copy EigenVectors and Mean from a mesh
eigenMean = myMesh.eigenMean;
eigenVec1 = myMesh.eigenVec[0];
}
void RemainingPoints(Mesh &Cn, Mesh &Q, vector<int> ind){ //Extract points, referenced by their indexes, from a mesh and add
//them to another
int i = ind.size(); //Number of point to extract
for (int k=0;k<i;k++){
Q.AddVertex( Cn.Vertex( ind[k] ) ); //Copy points into 'Q'
Cn.vertices.erase( Cn.vertices.begin()+ind[k] ); //Erase points into 'Cn'
}
}
multimap<double, int> Distance2Eigen1(const Mesh &Crem, const GenEigen &genEig){ //Compute residual distances from mesh vertices to main EigenVector
double d, k, xh, yh, zh, pointX, pointY, pointZ, ua, ub, uc, ox, oy, oz, resDist;
multimap<double, int> dist; //Contains distances (key) and points indexes (value)
ua = genEig.eigenVec1[0]; //Main EigenVector
ub = genEig.eigenVec1[1];
uc = genEig.eigenVec1[2];
ox = genEig.eigenMean[0]; //Eigen origin
oy = genEig.eigenMean[1];
oz = genEig.eigenMean[2];
for (int i=0; i<Crem.VertexNumber(); i++){ //For all vertex
pointX = Crem.vertices[i][0]; //Get points coordinates
pointY = Crem.vertices[i][1];
pointZ = Crem.vertices[i][2];
d = - ( (ua*pointX) + (ub*pointY) + (uc*pointZ) ); //Compute distance from a vertex to its orthogonal projection onto
//a line defined by main eigenVector through mean value
k = - ( (ua*ox) + (ub*oy) + (uc*oz) + d ) / ( (ua*ua) + (ub*ub) + (uc*uc) );
xh = (ox + ua*k);
yh = (oy + ub*k);
zh = (oz + uc*k);
resDist = sqrt(pow((pointX-xh),2) + pow((pointY-yh),2) + pow((pointZ-zh),2));
dist.insert(make_pair((double)resDist, (int)i)); //Insert pair : distance (key) and point index (value)
}
return dist; //Return distances
}
multimap<double, int> Distance2Eigen1(const Node& myNode,const vector<Vector3d> ¢ers, const GenEigen& genEig){
//Compute residual distances from projected Node centers to main EigenVector
double d, k, xh, yh, zh, pointX, pointY, pointZ, ua, ub, uc, ox, oy, oz, resDist;
int nodeInd, nodeWeight;
multimap<double, int> dist;
multimap<int, int>::const_iterator myIt;
myIt = myNode.indCenter2pts.begin();
ua = genEig.eigenVec1[0]; //Main EigenVector
ub = genEig.eigenVec1[1];
uc = genEig.eigenVec1[2];
ox = genEig.eigenMean[0]; //Eigen origin
oy = genEig.eigenMean[1];
oz = genEig.eigenMean[2];
while (myIt!=myNode.indCenter2pts.end()){ //For all projected Node centers
nodeInd = myIt->first;
pointX = centers[nodeInd][0]; //Get centers coordinates
pointY = centers[nodeInd][1];
pointZ = centers[nodeInd][2];
d = - ( (ua*pointX) + (ub*pointY) + (uc*pointZ) ); //Compute distance from a vertex to its orthogonal projection onto
//a line defined by main eigenVector through mean value
k = - (( (ua*ox) + (ub*oy) + (uc*oz) + d ) / ( (ua*ua) + (ub*ub) + (uc*uc) ));
xh = (ox + ua*k);
yh = (oy + ub*k);
zh = (oz + uc*k);
resDist = sqrt(pow((pointX-xh),2) + pow((pointY-yh),2) + pow((pointZ-zh),2));
dist.insert(make_pair((double)resDist, (int)nodeInd)); //Insert pair : distance (key) and node index (value)
nodeWeight = myNode.indCenter2pts.count(nodeInd); //Count how many values have the same key
advance(myIt,nodeWeight); //Go to next key which is different from the current one
}
return dist;
}
vector<int> GetClosestPoint(multimap<double, int> myMap, int m, double rmax){ //Get indexes of closest points regarding a threshold (rMax)
vector<int> dum;
multimap<double, int>::iterator myIt = myMap.begin();
for (int i=0;i<m;i++){ //For m closest points
if (myIt->first < rmax){ //If point distance is less than rMax
dum.push_back(myIt->second); //then get its index
}else{
sort(dum.rbegin(),dum.rend()); //Else, sort descending points indexes and stop loop
return dum;
}
myIt++; //Go to next point
}
sort(dum.rbegin(),dum.rend()); //sort descending points indexes
return dum;
}
vector<int> RandomKPoints(Node &myNode,Mesh &myMesh, int k){ //Select points with a weighted random
int randomInd, nodeInd, nbOfPts, indPts, randRange;
vector<int> myVec; //K points containers
multimap<int, int>::iterator myItCdf; //Iterators
multimap<int, int>::iterator myItNode;
for (int i=0;i<k;i++){ //for k points
randomInd = rand() %myMesh.VertexNumber() ; //Rand a number in the range 1 - number of vertices
myItCdf = myNode.nodeCdf.upper_bound(randomInd); //Go to the first cell whose its key is greater or equal
//to the rand
nodeInd = myItCdf->second; //Get node index (key) of that cell
nbOfPts = myNode.indCenter2pts.count(nodeInd); //Count number of points within that node (values associated
//to that key)
myItNode = myNode.indCenter2pts.find(nodeInd); //Go to that node (key)
advance(myItNode,rand() %nbOfPts); //Select randomly a point (index) of that node (a value associated to that key)
myVec.push_back(myItNode->second); //Store that point
}
sort(myVec.rbegin(), myVec.rend()); //Sort descending
return myVec;
}
double SetRmax( Mesh &myMesh){ //Compute residual distances and keep the greater
double rMaxTemp;
multimap<double, int> dist2eig;
multimap<double, int>::iterator myIt;
GenEigen myGenEigen;
myGenEigen.CopyEig(myMesh); //Get main EigenVector
dist2eig = Distance2Eigen1(myMesh, myGenEigen); //Compute residual distances
myIt = dist2eig.end();
myIt--; //Iterator to greater distance
return rMaxTemp = myIt->first; //Return greater distance
}
vector<Vector3d> ProjectNodeCenters(const vector<Vector3d> ¢ers, const Mesh &myMesh){ //Project Node centers onto mesh EigenSpace
vector<Vector3d> projectedNodeCenters;
Matrix3d tempEigenVec; //Declare feature matrix
tempEigenVec.row(0) = myMesh.eigenVec[0]; //Set EigenVectors as rows of the feature matrix
tempEigenVec.row(1) = myMesh.eigenVec[1];
tempEigenVec.row(2) = myMesh.eigenVec[2];
Vector3d tempCenter;
for (int i=0;i<centers.size();i++){ //For each center
tempCenter = centers[i] - myMesh.eigenMean; //Substract Mean
tempCenter = tempEigenVec * tempCenter; //Multiply feature matrix and center coordinates
projectedNodeCenters.push_back(tempCenter); //Store projected point
}
return projectedNodeCenters;
}
void First_Part(const Mesh &Original, Mesh &Crem, Mesh &Q, Node &myNode, const int max_iter, const int k, const int depth){
//Algorithm 2 : Octree + LMS
int i=0;
Mesh tempQ,tempCrem; //Temporary mesh Q & Crem
double rMin = numeric_limits<double>::max();
double rHalf;
int medDist;
vector<int> tempVec;
vector<int> finalVec;
vector<Vector3d> nodeCenters;
GenEigen myGenEigen;
multimap<double, int> dist2eig;
multimap<double, int>::iterator myIt;
nodeCenters = myNode.initNode(Original,depth); //Construct the Octree
while(i++<=max_iter){ //For max_iter times
tempCrem = Original; //tempCrem set as the original mesh
tempQ.ClearAll();
tempVec = RandomKPoints(myNode,tempCrem,k); //Rand K points
RemainingPoints(tempCrem,tempQ,tempVec); //Exctract previous k points from tempCrem and store them within tempQ
tempQ.Meshpca(); //Compute PCA over previous k points
myGenEigen.CopyEig(tempQ); //Copy EigenVectors and Mean
dist2eig = Distance2Eigen1(myNode, nodeCenters, myGenEigen); //Compute residual distances
medDist = dist2eig.size()/2; //Get index of median distance
myIt = dist2eig.begin();
advance(myIt, medDist);
rHalf = myIt->first;
if (rHalf<rMin){
rMin = rHalf;
finalVec = tempVec;
Q = tempQ;
Crem = tempCrem;
}
}
cout<<"Point selected index : "<<finalVec[0]<<" "<<finalVec[1]<<" "<<finalVec[2]<<" "<<finalVec[3]<<endl<<endl;
}
void Second_Part(Mesh& Crem, Mesh& Q, const int MAX_Iter, const int m){
multimap<double, int> dist2eig;
vector<int> closestpoints;
GenEigen myGenEigen;
int iter = 0;
int mpts = 0;
double alpha = 3;
double rMax = SetRmax(Q);
rMax *= alpha;
cout<<"rMax : "<<rMax<<endl<<endl;
Q.Meshpca();
do{
myGenEigen.CopyEig(Q);
dist2eig = Distance2Eigen1(Crem, myGenEigen);//check
closestpoints = GetClosestPoint(dist2eig,m,rMax);
RemainingPoints(Crem,Q,closestpoints);//check
mpts = closestpoints.size();
Q.Meshpca();
}while (iter++ < MAX_Iter && mpts==m);
}
| true |
fc8460a394bcf17c930aabfd4cbaadd3a0b50353 | C++ | 1panpan1/leetcode | /src/problem_33.cpp | UTF-8 | 1,272 | 3.40625 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
class Solution{
public:
int search(vector<int>& nums, int target){
int i = 0, j = nums.size() - 1;
int found = -1;
while(i <= j){
int mid = (i + j) / 2;
if(target == nums[mid]){
found = mid;
break;
}else if(target > nums[mid]){
if(nums[mid] >= nums[i])
i = mid + 1;
else{
if(target <= nums[j])
i = mid + 1;
else if(target >= nums[i])
j = mid - 1;
else
break;
}
}else{
if(nums[mid] < nums[i])
j = mid - 1;
else{
if(target >= nums[i])
j = mid - 1;
else if(target <= nums[j])
i = mid + 1;
else
break;
}
}
}
return found;
}
};
int main(){
vector<int> nums = {4};
int target = 4;
Solution solu = Solution();
cout<<solu.search(nums, target)<<endl;
return 0;
} | true |
6d75cc4356fc7b3014bb6aec2ab1829f1360bd1a | C++ | narenknn/emuc | /tests/client_hw.cc | UTF-8 | 2,294 | 2.515625 | 3 | [] | no_license | #include <queue>
#include <iostream>
#include <unordered_map>
#include <boost/asio.hpp>
#include <thread>
#include "scCommon.hh"
#include "client.hh"
#include <cstring>
#include "svbit.hh"
#include "shash.hh"
class SdpReqBus : public TransBase {
public:
std::uint32_t* const _dptr;
svBitTp<64> addr{_dptr};
svBitTp<64> data{_dptr+SV_SIZE(64)};
static constexpr std::size_t
DATA_U32_SZ() { return SV_SIZE(64)+SV_SIZE(64); }
static constexpr std::size_t
DATA_U8_SZ() { return DATA_U32_SZ()*sizeof(std::uint32_t); }
SdpReqBus(): TransBase{DATA_U8_SZ()},
_dptr{(std::uint32_t*)(_data.get()+sizeof(TransHeader))} {
}
SdpReqBus(char *d): SdpReqBus() {
std::memcpy(_dptr, d, DATA_U8_SZ());
}
SdpReqBus& operator=(const SdpReqBus& o) { /* copy assignment */
std::memcpy(_dptr, o._dptr, DATA_U8_SZ());
}
SdpReqBus(const SdpReqBus& o):
TransBase(o),
_dptr{(std::uint32_t*)(_data.get()+sizeof(TransHeader))} { /* copy constructor */
}
SdpReqBus(SdpReqBus&& o) noexcept : /* move constructor */
TransBase(o), _dptr{(std::uint32_t*)(_data.get()+sizeof(TransHeader))} {
}
};
//----------------------------------------------------------------------
template<std::uint32_t PipeId, class Bus>
class EmuTransactor : public Pipe
{
public:
EmuTransactor() : Pipe{PipeId, Bus::DATA_U8_SZ()}
{ }
void receive(char *d)
{
Bus b{d};
std::cout << "EmuTransactor Obtained transaction addr:" << std::string(b.addr) << " data:" << std::string(b.data) << "\n";
}
};
EmuTransactor<CRC32_STR("abcd"), SdpReqBus> trans;
int main(int argc, char* argv[])
{
try {
pollInit();
trans.connect();
std::shared_ptr<SdpReqBus> v1{std::make_shared<SdpReqBus>()};
v1->addr = 0xABCD;
v1->data = 0xABCC;
std::cout << "Sending addr:" << std::string(v1->addr) << " data:" << std::string(v1->data) << "\n";
trans.send(v1);
//std::cout << "v1.. pipeId:" << std::hex << v1->header->pipeId << std::dec << " sizeOf:" << v1->header->sizeOf << "\n";
while (true) {
// for (auto i=0; i<1000; i++) {
sleep(0.01);
pollOnce();
}
ss->close();
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
} catch (...) {
std::cerr << "Exception ocurred!!\n";
}
return 0;
}
| true |
27fd52ca32a4cd1542b11aaf0fd62bf1486a7d8a | C++ | JayBeavers/RocketBot | /RocketBaseArduino/Animations.ino | UTF-8 | 5,242 | 2.703125 | 3 | [] | no_license | unsigned long animationStart = 0;
unsigned long animationTime = 0;
int frequency = 0;
typedef void (* AnimationFunction) ();
AnimationFunction animation = IdleAnimation;
void animationLoop()
{
animationTime = millis() - animationStart;
animation();
}
int AnimationCommandState()
{
if (animation == IdleAnimation) return 0;
else if (animation == MovingAnimation) return 1;
else if (animation == ArmingAnimation) return 2;
else if (animation == ArmedAnimation) return 3;
else if (animation == FiringAnimation) return 4;
else if (animation == FiredAnimation) return 5;
}
void AnimationCommand()
{
switch(reflectaFunctions::pop())
{
case '0':
animation = IdleAnimation;
break;
case '1':
animation = MovingAnimation;
break;
case '2':
animation = ArmingAnimation;
break;
case '3':
animation = ArmedAnimation;
break;
case '4':
animation = FiringAnimation;
break;
case '5':
animation = FiredAnimation;
break;
case '6':
animation = MovingDisabledAnimation;
break;
}
// Reset to defaults
digitalWrite(RedLight, LOW);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
frequency = 0;
animationStart = millis();
}
void IdleAnimation()
{
frequency = 0;
noTone(Speaker);
animationStart = millis();
}
void MovingAnimation()
{
if (animationTime < 150)
{
tone(Speaker, 660);
digitalWrite(RedLight, HIGH);
digitalWrite(GreenLight, HIGH);
digitalWrite(BlueLight, HIGH);
}
else if (animationTime < 1000)
{
noTone(Speaker);
digitalWrite(RedLight, LOW);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
}
else
{
animationStart = millis();
}
}
void MovingDisabledAnimation()
{
if (animationTime < 150)
{
tone(Speaker, 660);
digitalWrite(RedLight, HIGH);
digitalWrite(GreenLight, HIGH);
digitalWrite(BlueLight, LOW);
}
else if (animationTime < 1000)
{
noTone(Speaker);
digitalWrite(RedLight, LOW);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
}
else
{
animationStart = millis();
}
}
void ArmingAnimation()
{
if (frequency == 0)
{
digitalWrite(RedLight, HIGH);
digitalWrite(GreenLight, HIGH);
digitalWrite(BlueLight, LOW);
frequency = 222;
}
else if (animationTime < 1250) frequency += 1;
else if (animationTime < 1500)
{
digitalWrite(RedLight, LOW);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
frequency = 465;
}
else if (animationTime < 1700) frequency -= 6;
else if (animationTime < 2000) frequency = -1; // Off
else
{
frequency = 0;
animationStart = millis();
}
if (frequency > 0)
tone(Speaker, frequency);
else
noTone(Speaker);
}
void ArmedAnimation(){
noTone(Speaker);
if (animationTime < 4000)
{
digitalWrite(RedLight, HIGH);
digitalWrite(GreenLight, HIGH);
digitalWrite(BlueLight, LOW);
}
else if (animationTime < 8000)
{
digitalWrite(RedLight, LOW);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
}
else
{
animationStart = millis();
}
}
void FiringAnimation()
{
if (frequency == 0)
{
frequency = 215;
}
else if (animationTime < 75)
{
digitalWrite(RedLight, HIGH);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
frequency += 5;
}
else if (animationTime < 325)
{
digitalWrite(RedLight, LOW);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
frequency = 290;
}
else if (animationTime < 400)
{
digitalWrite(RedLight, HIGH);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
frequency -= 5;
}
else if (animationTime < 650)
{
digitalWrite(RedLight, LOW);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
frequency = 215;
}
else if (animationTime < 725)
{
digitalWrite(RedLight, HIGH);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
frequency += 5;
}
else if (animationTime < 975)
{
digitalWrite(RedLight, LOW);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
frequency = 290;
}
else if (animationTime < 1050)
{
digitalWrite(RedLight, HIGH);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
frequency -= 5;
}
else if (animationTime < 1300)
{
digitalWrite(RedLight, LOW);
digitalWrite(GreenLight, LOW);
digitalWrite(BlueLight, LOW);
frequency = 215;
}
else
{
animation = IdleAnimation;
}
if (frequency > 0)
tone(Speaker, frequency);
else
noTone(Speaker);
}
void FiredAnimation()
{
if (animationTime < 100) digitalWrite(RedLight, HIGH);
else if (animationTime < 200) digitalWrite(RedLight, LOW);
else if (animationTime < 300) digitalWrite(RedLight, HIGH);
else if (animationTime < 400) digitalWrite(RedLight, LOW);
else if (animationTime < 500) digitalWrite(RedLight, HIGH);
else if (animationTime < 600) digitalWrite(RedLight, LOW);
else if (animationTime < 700) digitalWrite(RedLight, HIGH);
else
{
digitalWrite(RedLight, LOW);
animation = IdleAnimation;
}
}
| true |
9c22ad8d3c537ab4cbacf8e3df4741bba9dd8e95 | C++ | BigEvilCorporation/symmetry | /testgame/Inventory.cpp | UTF-8 | 2,109 | 3.203125 | 3 | [] | no_license | #include "Inventory.h"
CInventoryItemBase::CInventoryItemBase()
{
Size = 0;
}
CInventoryItemBase::~CInventoryItemBase()
{
}
void CInventoryItemBase::SetName(std::string ItemName)
{
Name = ItemName;
}
std::string CInventoryItemBase::GetName()
{
return Name;
}
void CInventoryItemBase::SetSize(int ItemSize)
{
if(Size > -1) Size = ItemSize;
}
int CInventoryItemBase::GetSize()
{
return Size;
}
CInventory::CInventory()
{
MaxSize = 0;
MaxItems = 0;
CurrentSize = 0;
}
CInventory::~CInventory()
{
//Clear items list
Items.clear();
}
bool CInventory::AddItem(CInventoryItemBase *Item)
{
//If space isn't infinite
if(MaxSize != 0 && MaxItems != 0)
{
//Check there is space left
if(GetNumItems() == GetMaxItems() && GetCurrentSize() + Item->GetSize() > GetMaxSize())
{
return false;
}
else
{
//Add item
Items.push_back(Item);
//Add its size
CurrentSize += Item->GetSize();
return true;
}
}
else
{
//Space is infinite, just add item
Items.push_back(Item);
//Add its size
CurrentSize += Item->GetSize();
}
return true;
}
bool CInventory::RemoveItem(CInventoryItemBase *Item)
{
//Check item exists
for(std::vector<CInventoryItemBase*>::iterator i = Items.begin(); i != Items.end(); i++)
{
if((*i) == Item)
{
//Item found, remove its size
CurrentSize -= (*i)->GetSize();
//Delete it
Items.erase(i);
return true;
}
}
//Item not found
return false;
}
CInventoryItemBase* CInventory::GetItemByName(std::string Name)
{
//Check item exists
for(std::vector<CInventoryItemBase*>::iterator i = Items.begin(); i != Items.end(); i++)
{
if((*i)->GetName() == Name)
{
//Item found, return it
return (*i);
}
}
//Item not found
return 0;
}
void CInventory::SetMaxItems(int Size)
{
if(Size > 0) MaxItems = Size;
}
void CInventory::SetMaxSize(int Size)
{
if(Size > 0) MaxSize = Size;
}
int CInventory::GetMaxItems()
{
return MaxItems;
}
int CInventory::GetMaxSize()
{
return MaxSize;
}
int CInventory::GetCurrentSize()
{
return CurrentSize;
}
int CInventory::GetNumItems()
{
return (int)Items.size();
} | true |
3d422ec7dd9587dea9e88b7102e094e007d39596 | C++ | BaconTimes/C_Learning | /cpplearning/cpplearning/ExerciseClass.cpp | UTF-8 | 1,926 | 3.46875 | 3 | [] | no_license | //
// ExerciseClass.cpp
// cpplearning
//
// Created by iOSBacon on 2017/4/12.
// Copyright © 2017年 iOSBacon. All rights reserved.
//
#include <iostream>
using namespace std;
class Adder {
public:
Adder(int i = 0){
total = i;
}
void addNum(int number){
total += number;
}
int getTotal()
{
return total;
}
private:
int total;
};
class printData
{
public:
void print(int i){
cout << "Printing int:" << i << endl;
}
void print(double f) {
cout << "Printing float:" << f << endl;
}
void print(char c[]){
cout << "Printing character:" << c <<endl;
}
};
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength(double len)
{
length = len;
}
void setBreadth(double bre)
{
breadth = bre;
}
void setHeight(double hei)
{
height = hei;
}
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length;
double breadth;
double height;
};
class Line
{
public:
void setLength( double len);
double getLength( void );
Line(); // 这是构造函数
private:
double length;
};
Line::Line(void)
{
cout << "Object is being created" << endl;
}
void Line::setLength( double len)
{
length = len;
}
double Line::getLength( void )
{
return length;
}
class Shape
{
protected:
int width, height;
public:
Shape(int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" << endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle(int a=0, int b=0):Shape(a, b){}
int area()
{
cout << "Rectangle class area:" <<endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle (int a=0, int b=0):Shape(a, b){}
int area()
{
cout << "Triangle class area:" << endl;
return (width * height / 2);
}
}; | true |
07b5d40d03ea81fed419bfaaf93ed13bd6c449dd | C++ | VladimirP1/os-kidshell | /inc/Command.h | UTF-8 | 468 | 2.59375 | 3 | [] | no_license | #pragma once
#include <algorithm>
#include <iostream>
#include <memory>
#include <vector>
class Command {
public:
int parse(std::string line);
std::vector<std::string> getArguments();
std::vector<std::string> getEnvironment();
friend std::ostream& operator<<(std::ostream& os, const Command& cmd);
private:
std::vector<std::string> args;
std::vector<std::string> env;
};
std::ostream& operator<<(std::ostream& os, const Command& cmd);
| true |
8de93e4ad6694ec2949a43130a879d8084903908 | C++ | SeanCST/USTC | /Semester1/Algorithm Introduction/实验/实验3_区间树上的重叠区间查找算法/main.cpp | UTF-8 | 1,155 | 3.03125 | 3 | [] | no_license | //
// main.cpp
// RBTree
//
// Created by 肖恩伟 on 2018/11/7.
// Copyright © 2018 肖恩伟. All rights reserved.
//
#include "RB_Tree.h"
#include <vector>
int main(int argc, const char * argv[]) {
vector<Interval> intervals;
intervals.push_back(Interval(16, 21));
intervals.push_back(Interval(8, 9));
intervals.push_back(Interval(25, 30));
intervals.push_back(Interval(5, 8));
intervals.push_back(Interval(15, 23));
intervals.push_back(Interval(17, 19));
intervals.push_back(Interval(26, 26));
intervals.push_back(Interval(0, 3));
intervals.push_back(Interval(6, 10));
intervals.push_back(Interval(19, 20));
RB_Tree T;
for (int i = 0; i < 10; i++) {
TreeNode *z = new TreeNode(intervals[i]);
T.RB_Insert(z);
// cout << "插入 " << A[i] << " :" << endl;
T.TreePrint();
cout << endl;
}
// (11, 14) -> 空结点, (22, 25) -> (15, 23)
Interval i = Interval(22, 25);
TreeNode *find = T.IntervalSearch(i);
// 打印
cout << "打印找到的结点:";
T.Print_Node(find);
return 0;
}
| true |
4ae29fdce284e4c8908d65715fab594a1b7aa2e1 | C++ | Girl-Code-It/Beginner-CPP-Submissions | /Shruti/Milestone 2/CD06.cpp | UTF-8 | 738 | 3.875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n1, n2, n3;
cout<<"\n Enter the age of first person: ";
cin>>n1;
cout<<"\n Enter the age of the second person: ";
cin>>n2;
cout<<"\n Enter the age of the third person: ";;
cin>>n3;
cout<<"\n\n The oldest person is: ";
if( (n1 > n2) && (n1 > n3) )
cout<<"first person( "<<n1<<" )";
else if(n2 > n3)
cout<<"second person( "<<n2<<" )";
else
cout<<"third person( "<<n3<<" )";
cout<<"\n\n The youngest person is: ";
if( (n1 < n2) && (n1 < n3) )
cout<<"first person( "<<n1<<" )";
else if(n2 < n3)
cout<<"second person( "<<n2<<" )";
else
cout<<"third person( "<<n3<<" )";
}
| true |
4b7e43809457dc42bbe87076b8db971fe09f2d25 | C++ | yanqiheng/OJ_algorithms | /剑指offer/二叉搜索树/*二叉搜索树与双向链表.cpp | UTF-8 | 647 | 3.3125 | 3 | [] | no_license | /*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* pre=NULL;
TreeNode* head=NULL;
TreeNode* Convert(TreeNode* pRootOfTree)
{
if(!pRootOfTree) return NULL;
if(pRootOfTree->left) Convert(pRootOfTree->left);
if(!head) pre=head=pRootOfTree;//head指针为树的左下角
else{
pre->right=pRootOfTree;
pRootOfTree->left=pre;
pre=pre->right;
}
if(pRootOfTree->right) Convert(pRootOfTree->right);
return head;
}
}; | true |
1e743a3da4238c06a09709f565d89795b1912ec3 | C++ | C00192124/GamesEngineering | /FSM/FSM/src/Source.cpp | UTF-8 | 1,161 | 2.515625 | 3 | [] | no_license | #include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#include "Input/InputHandler.h"
#include "Animation/Animation.h"
using namespace std;
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window* window = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1000, 800, SDL_WINDOW_SHOWN);
InputHandler* input = new InputHandler;
Animation fsm;
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
SDL_Texture* texture = IMG_LoadTexture(renderer, "idle.bmp");
SDL_QueryTexture(texture, NULL, NULL, &textureWidth, &textureHeight);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderClear(renderer);
bool isRunning = true;
while (isRunning) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
isRunning = false;
}
switch (event.type) {
case SDL_KEYDOWN:
input->handleInput(event);
}
}
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
SDL_DestroyWindow(window);
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_Quit();
return 0;
} | true |
17b384a06e5ff4cd706bb15f03a1b88b2d24b2cb | C++ | Aslauw/PathTracer | /source/Camera.cpp | UTF-8 | 6,415 | 3.03125 | 3 | [] | no_license | #include "Camera.hpp"
#include "Matrix.hpp"
#include "Sphere.hpp"
#include "Plane.hpp"
#include <cmath>
#include <iostream>
// Ctors
Camera::Camera()
{
_position = Vec3<float>(0, 0, 0);
_forward = Vec3<float>(0, 0, -1);
_right = Vec3<float>(-1, 0, 0);
_fov = (45.0 * M_PI / 180.0);
}
Camera::Camera(const Vec3<float> position, const Vec3<float> forward, const Vec3<float> right)
{
_position = position;
_forward = forward;
_right = right;
}
Camera::Camera(float px, float py, float pz, float fx, float fy, float fz, float rx, float ry, float rz)
{
_position = Vec3<float>(px, py, pz);
_forward = Vec3<float>(fx, fy, fz);
_right = Vec3<float>(rx, ry, rz);
}
// Functions
void
Camera::setCache()
{
_cache = new Vec3<float>[_width * _height];
for (uint32_t i = 0; i < _height; i++)
{
for (uint32_t j = 0; j < _width; j++)
{
float px = (2.0 * ((j + 0.5) / _width) - 1.0) * tan(_fov / 2.0) * _ratio;
float py = (1.0 - 2.0 * ((i + 0.5) / _height)) * tan(_fov / 2.0);
Vec3<float> camPixel(px, py, 1.0);
_cache[i * _width + j] = camPixel;
}
}
}
void
Camera::updatePosition(struct s_Keys& keys)
{
// Camera Z-Axis translation
if (keys.moveForward)
moveForward();
else if (keys.moveBack)
moveBack();
// Camera X-Axis translation
if (keys.moveLeft)
moveLeft();
else if (keys.moveRight)
moveRight();
// Camera Y-Axis translation
if (keys.moveUp)
moveUp();
else if (keys.moveDown)
moveDown();
// Camera X-Axis rotation
if (keys.rotateUp)
rotateUp();
else if (keys.rotateDown)
rotateDown();
// Camera Y-Axis rotation
if (keys.rotateLeft)
rotateLeft();
else if (keys.rotateRight)
rotateRight();
// Camera Z-Axis rotation
if (keys.barrelLeft)
barrelLeft();
else if (keys.barrelRight)
barrelRight();
// Fov updatePosition
if (keys.fovUp)
_fov = fmin(_fov + 0.01, 150.0 * M_PI / 180.0);
else if (keys.fovDown)
_fov = fmax(_fov - 0.01, 20.0 * M_PI / 180.0);
}
Vec3<float>&
Camera::toWorld(Vec3<float>& v)
{
Vec3<float> l;
l = _right;
l *= -1;
Matrix4<float> mat(l, _forward.cross(_right), _forward, _position);
v = mat * v;
return v;
}
void
Camera::moveForward()
{
Vec3<float> scaled(_forward);
scaled *= MOVE_SPEED;
_position = _position + scaled;
}
void
Camera::moveBack()
{
Vec3<float> scaled(_forward);
scaled *= -MOVE_SPEED;
_position = _position + scaled;
}
void
Camera::moveLeft()
{
Vec3<float> scaled(_right);
scaled *= MOVE_SPEED;
_position = _position + scaled;
}
void
Camera::moveRight()
{
Vec3<float> scaled(_right);
scaled *= -MOVE_SPEED;
_position = _position + scaled;
}
void
Camera::moveUp()
{
Vec3<float> scaled(0.0, 1.0, 0.0);
scaled *= MOVE_SPEED;
_position = _position + scaled;
}
void
Camera::moveDown()
{
Vec3<float> scaled(0.0, 1.0, 0.0);
scaled *= -MOVE_SPEED;
_position = _position + scaled;
}
void
Camera::rotateUp()
{
Vec3<float> q;
double costheta, sintheta;
costheta = cos(-M_PI * ROT_SPEED);
sintheta = sin(-M_PI * ROT_SPEED);
q.setX(q.x() + (costheta + (1 - costheta) * _right.x() * _right.x()) * _forward.x());
q.setX(q.x() + ((1 - costheta) * _right.x() * _right.y() - _right.z() * sintheta) * _forward.y());
q.setX(q.x() + ((1 - costheta) * _right.x() * _right.z() + _right.y() * sintheta) * _forward.z());
q.setY(q.y() + ((1 - costheta) * _right.x() * _right.y() + _right.z() * sintheta) * _forward.x());
q.setY(q.y() + (costheta + (1 - costheta) * _right.y() * _right.y()) * _forward.y());
q.setY(q.y() + ((1 - costheta) * _right.y() * _right.z() - _right.x() * sintheta) * _forward.z());
q.setZ(q.z() + ((1 - costheta) * _right.x() * _right.z() - _right.y() * sintheta) * _forward.x());
q.setZ(q.z() + ((1 - costheta) * _right.y() * _right.z() + _right.x() * sintheta) * _forward.y());
q.setZ(q.z() + (costheta + (1 - costheta) * _right.z() * _right.z()) * _forward.z());
_forward = q;
}
void
Camera::rotateDown()
{
Vec3<float> q;
double costheta, sintheta;
costheta = cos(M_PI * ROT_SPEED);
sintheta = sin(M_PI * ROT_SPEED);
q.setX(q.x() + (costheta + (1 - costheta) * _right.x() * _right.x()) * _forward.x());
q.setX(q.x() + ((1 - costheta) * _right.x() * _right.y() - _right.z() * sintheta) * _forward.y());
q.setX(q.x() + ((1 - costheta) * _right.x() * _right.z() + _right.y() * sintheta) * _forward.z());
q.setY(q.y() + ((1 - costheta) * _right.x() * _right.y() + _right.z() * sintheta) * _forward.x());
q.setY(q.y() + (costheta + (1 - costheta) * _right.y() * _right.y()) * _forward.y());
q.setY(q.y() + ((1 - costheta) * _right.y() * _right.z() - _right.x() * sintheta) * _forward.z());
q.setZ(q.z() + ((1 - costheta) * _right.x() * _right.z() - _right.y() * sintheta) * _forward.x());
q.setZ(q.z() + ((1 - costheta) * _right.y() * _right.z() + _right.x() * sintheta) * _forward.y());
q.setZ(q.z() + (costheta + (1 - costheta) * _right.z() * _right.z()) * _forward.z());
_forward = q;
}
void
Camera::rotateLeft()
{
Matrix4<float> mat;
mat[0] = cos(M_PI * ROT_SPEED);
mat[2] = sin(M_PI * ROT_SPEED);
mat[8] = -sin(M_PI * ROT_SPEED);
mat[10] = cos(M_PI * ROT_SPEED);
_forward = mat * _forward;
_right = mat * _right;
}
void
Camera::rotateRight()
{
Matrix4<float> mat;
mat[0] = cos(-M_PI * ROT_SPEED);
mat[2] = sin(-M_PI * ROT_SPEED);
mat[8] = -sin(-M_PI * ROT_SPEED);
mat[10] = cos(-M_PI * ROT_SPEED);
_forward = mat * _forward;
_right = mat * _right;
}
void
Camera::barrelLeft()
{
}
void
Camera::barrelRight()
{
}
// Otors
std::ostream&
operator<<(std::ostream& os, Camera& rhs)
{
os << "Camera: " << std::endl;
os << "\tposition (W): " << rhs.x() << " " << rhs.y() << " " << rhs.z() << std::endl;
os << "\tforward (W): " << rhs.fx() << " " << rhs.fy() << " " << rhs.fz() << std::endl;
os << "\tright (W): " << rhs.rx() << " " << rhs.ry() << " " << rhs.rz() << std::endl;
os << "\tfov : " << rhs.fov() << std::endl;
os << "\tratio : " << rhs.ratio() << std::endl;
return os;
}
// Dtor
Camera::~Camera()
{
delete[] _cache;
}
| true |
e4c044b0fd209b37b315fa31f8073a668900663c | C++ | hobinyoon/crawl-twitter | /tools/gen-1yr-data/tweet.cpp | UTF-8 | 1,876 | 2.59375 | 3 | [] | no_license | #include <fstream>
#include <set>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "conf.h"
#include "tweet.h"
#include "util.h"
using namespace std;
Tweet::Tweet(ifstream& ifs) {
ifs.read((char*)&id, sizeof(id));
ifs.read((char*)&uid, sizeof(uid));
Util::ReadStr(ifs, created_at_str);
// Takes like 11sec for the 100% dataset
//created_at = boost::posix_time::time_from_string(created_at_str);
ifs.read((char*)&geo_lati, sizeof(geo_lati));
ifs.read((char*)&geo_longi, sizeof(geo_longi));
Util::ReadStr(ifs, youtube_video_id);
ifs.read((char*)&youtube_video_uploader, sizeof(youtube_video_uploader));
size_t topic_cnt;
ifs.read((char*)&topic_cnt, sizeof(topic_cnt));
for (size_t i = 0; i < topic_cnt; i ++) {
string t;
Util::ReadStr(ifs, t);
topics.push_back(t);
}
ifs.read((char*)&type, sizeof(type));
}
void Tweet::Write(ofstream& ofs) {
ofs.write((char*)&id, sizeof(id));
ofs.write((char*)&uid, sizeof(uid));
Util::WriteStr(ofs, created_at_str);
ofs.write((char*)&geo_lati, sizeof(geo_lati));
ofs.write((char*)&geo_longi, sizeof(geo_longi));
Util::WriteStr(ofs, youtube_video_id);;
ofs.write((char*)&youtube_video_uploader, sizeof(youtube_video_uploader));
size_t topic_cnt = topics.size();
ofs.write((char*)&topic_cnt, sizeof(topic_cnt));
for (const auto& tp: topics)
Util::WriteStr(ofs, tp);
ofs.write((char*)&type, sizeof(type));
}
ostream& operator<< (ostream& os, const Tweet& t) {
os << t.id;
os << boost::format(" %10d") % t.uid;
os << " " << t.created_at_str;
os << boost::format(" %8.3f") % t.geo_lati;
os << boost::format(" %8.3f") % t.geo_longi;
os << " " << t.youtube_video_id;
os << boost::format(" %10d") % t.youtube_video_uploader;
for (const auto& tp: t.topics)
os << " " << tp;
os << " " << t.type;
return os;
}
| true |
ed81ef126d32b563412704bdf0712ed99185dba5 | C++ | peterfyj/umnets | /src/node/HHRtauNode.cc | UTF-8 | 6,274 | 2.546875 | 3 | [] | no_license | #include "node/HHRtauNode.h"
#include "driver/Driver.h"
#include "packet/packet.h"
#include "util/Math.h"
#include "network/network.h"
#include "logger/logger.h"
#include <utility>
#include <iterator>
HHRtauNode* HHRtauNode::create(Driver& driver) {
int tau = driver.get_option<int>("node.tau");
int beta = driver.get_option<int>("node.beta");
int beta_local = driver.get_option<int>("node.beta_local");
double q = driver.get_option<double>("node.q");
return new HHRtauNode(driver, tau, beta, beta_local, q);
}
void HHRtauNode::announce_options(Driver& driver) {
driver.register_option("node.count", po::value<int>(), "count of all nodes");
driver.register_option("node.tau", po::value<int>(), "time threshold");
driver.register_option("node.beta", po::value<int>(), "relay buffer limit");
driver.register_option("node.beta_local", po::value<int>(),
"relay buffer limit");
driver.register_option("node.q", po::value<double>(), "S-R probability");
}
HHRtauNode::~HHRtauNode() {
}
void HHRtauNode::set_tag(int tag) {
node_tag = tag;
}
int HHRtauNode::get_tag() const {
return node_tag;
}
const IntPos& HHRtauNode::get_pos() const {
return pos;
}
void HHRtauNode::set_pos(IntPos& pos) {
driver.get_logger().node_moved(*this);
this->pos = pos;
}
void HHRtauNode::set_dest(HHRtauNode& node) {
dest_node = &node;
}
void HHRtauNode::add_packet(PacketPtr&& packet) {
packet->set_src(*this);
packet->set_dest(*dest_node);
packet->set_tag(seq++);
packet->get_time_stamp().push_back(driver.get_tick());
auto& local_queue = queue_map[dest_node];
driver.get_logger().packet_generated(*this, *packet);
if ((int) local_queue.size() >= beta_local) {
packet->get_time_stamp().push_back(driver.get_tick());
driver.get_logger().packet_dropped(*this, *packet);
packet = nullptr;
return;
}
if (local_queue.empty()) {
packet->get_time_stamp().push_back(driver.get_tick());
token_map[dest_node] = driver.register_time_out(driver.get_tick() + tau,
get_local_time_out_callback());
}
local_queue.push_back(std::move(packet));
}
HHRtauNode& HHRtauNode::get_dest() {
return *dest_node;
}
void HHRtauNode::scheduled() {
Network& network = driver.get_network();
auto iter_end = network.receiver_end(*this);
for (auto iter = network.receiver_begin(*this); iter != iter_end; ++iter) {
if (dest_node == &*iter) {
SD(*iter);
return;
}
}
if (Math::happen(q)) {
SR();
} else {
auto ptr = Network::random_choose(network.receiver_begin(*this), iter_end);
if (ptr != iter_end) {
RD(*ptr);
}
}
}
void HHRtauNode::receive(HHRtauNode& src, PacketPtr&& packet) {
packet->get_time_stamp().push_back(driver.get_tick());
driver.get_logger().packet_transfered(src, *this, *packet);
if (&packet->get_dest() == this) { // SD or RD.
packet = nullptr;
} else { // SR.
auto& relay_queue = queue_map[&packet->get_dest()];
if ((int) relay_queue.size() < beta) {
if (relay_queue.empty()) {
token_map[&packet->get_dest()] = driver.register_time_out(
packet->get_time_stamp()[1] + tau,
get_relay_time_out_callback(packet->get_dest()));
}
relay_queue.push_back(std::move(packet));
} else {
driver.get_logger().packet_dropped(*this, *packet);
packet = nullptr;
}
}
}
HHRtauNode::HHRtauNode(Driver& driver, int tau, int beta, int beta_local,
double q)
: driver(driver), tau(tau), beta(beta), beta_local(beta_local)
, q(q), seq(0) {
}
Driver::Callback HHRtauNode::get_local_time_out_callback() {
return [this] () {
auto& queue = queue_map[dest_node];
auto& token = token_map[dest_node];
queue.front()->get_time_stamp().push_back(driver.get_tick());
driver.get_logger().packet_dropped(*this, *queue.front());
queue.pop_front();
if (!queue.empty()) {
queue.front()->get_time_stamp().push_back(driver.get_tick());
token = driver.register_time_out(driver.get_tick() + tau,
get_local_time_out_callback());
}
};
}
Driver::Callback HHRtauNode::get_relay_time_out_callback(HHRtauNode& dest) {
return [&dest, this] () {
auto& queue = queue_map[&dest];
auto& token = token_map[&dest];
queue.front()->get_time_stamp().push_back(driver.get_tick());
driver.get_logger().packet_dropped(*this, *queue.front());
queue.pop_front();
if (!queue.empty()) {
int stamp = queue.front()->get_time_stamp()[1];
token = driver.register_time_out(stamp + tau,
get_relay_time_out_callback(dest));
}
};
}
void HHRtauNode::SD(HHRtauNode& dest) {
auto& local_queue = queue_map[&dest];
if (local_queue.empty()) {
return;
}
driver.unregister_time_out(token_map[&dest]);
dest.receive(*this, std::move(local_queue.front()));
local_queue.pop_front();
for (int i = 0; !local_queue.empty() && i < beta - 1; ++i) {
local_queue.front()->get_time_stamp().push_back(driver.get_tick());
dest.receive(*this, std::move(local_queue.front()));
local_queue.pop_front();
}
if (!local_queue.empty()) {
local_queue.front()->get_time_stamp().push_back(driver.get_tick() + 1);
token_map[&dest] = driver.register_time_out(driver.get_tick() + tau + 1,
get_local_time_out_callback());
}
}
void HHRtauNode::SR() {
auto& local_queue = queue_map[dest_node];
if (local_queue.empty()) {
return;
}
driver.unregister_time_out(token_map[dest_node]);
auto& network = driver.get_network();
auto iter_end = network.receiver_end(*this);
for (auto iter = network.receiver_begin(*this); iter != iter_end; ++iter) {
iter->receive(*this, PacketPtr(local_queue.front()->clone()));
}
local_queue.pop_front();
if (!local_queue.empty()) {
local_queue.front()->get_time_stamp().push_back(driver.get_tick() + 1);
token_map[dest_node] = driver.register_time_out(
driver.get_tick() + tau + 1, get_local_time_out_callback());
}
}
void HHRtauNode::RD(HHRtauNode& other_dest) {
auto& relay_queue = queue_map[&other_dest];
if (!relay_queue.empty()) {
driver.unregister_time_out(token_map[&other_dest]);
}
while (!relay_queue.empty()) {
other_dest.receive(*this, std::move(relay_queue.front()));
relay_queue.pop_front();
}
}
| true |
e45ba0e175e98a5e14afb7d77cb9450727969e90 | C++ | MajorMattxx1/CS301-Data-Structures-and-Algorithms--Prefix-Data-Struct | /b/MazeExample.cpp | UTF-8 | 3,020 | 2.671875 | 3 | [] | no_license | // ConsoleApplication6.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
/*
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@S@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ @ @ @ @ @ @
@ @@@ @ @ @@@@@@@ @@@@@ @@@@@ @ @@@@@@@@@ @ @@@ @ @@@ @@@@@@@ @@@@@ @@@
@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
@ @@@ @ @@@ @@@ @ @ @ @@@@@ @@@@@ @@@@@@@@@@@@@@@ @ @ @ @@@@@@@@@ @@@ @
@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
@@@ @@@@@@@@@ @@@@@ @@@@@@@@@ @@@@@@@@@@@@@ @@@ @ @ @@@@@ @@@ @ @ @ @ @
@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
@ @@@@@@@ @ @ @@@ @@@ @@@@@ @@@ @ @ @ @@@@@@@ @ @@@@@@@ @@@@@@@@@@@@@ @
@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @
@@@@@@@ @ @ @@@ @@@@@@@@@@@@@@@@@ @@@@@ @@@ @@@@@ @@@ @@@ @@@ @ @ @ @ @
@ @ @ @ @ @ @ @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@F@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
#define MAX_ROW 100
#define MAX_COL 100
void solveMaze(int r, int c, char map[MAX_ROW][MAX_COL], int w, int h, string path, bool& done) {
if (done)
return;
if (r < 0 || c < 0 ||
r >= h || c >= w) {
return;
}
if (map[r][c] == 'F') {
done = true;
return;
}
if (map[r][c] == '.' || map[r][c] == '@') {
return;
}
map[r][c] = '.';
solveMaze(r - 1, c, map, w, h, path + "U", done);
solveMaze(r + 1, c, map, w, h, path + "D", done);
solveMaze(r, c - 1, map, w, h, path + "L", done);
solveMaze(r, c + 1, map, w, h, path + "R", done);
if (!done)
map[r][c] = ' ';
}
int main()
{
char map[MAX_ROW][MAX_COL];
ifstream mazeFile("maze.txt");
for (int i = 0; i < MAX_ROW; i++)
for (int j = 0; j < MAX_COL; j++) {
map[i][j] = ' ';
}
int row = 0;
int startRow, startCol, finalRow, finalCol;
// Read the file line by line an initialize the maze
string line;
while (getline(mazeFile, line)) {
//cout << line << endl;
for (int i = 0; i < (int)line.length(); i++) {
map[row][i] = line[i];
if (map[row][i] == 'S' || map[row][i] == 'P') {
startRow = row;
startCol = i;
map[row][i] = ' ';
}
else if (map[row][i] == 'F') {
finalRow = row;
finalCol = i;
}
}
row++;
}
cout << "Start Position: (" << startRow << "," << startCol << ")" << endl;
// figure out the number of rows and columns
int height = row;
int width = line.length();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
cout << map[i][j];
}
cout << endl;
}
bool done = false;
solveMaze(startRow, startCol, map, width, height, "", done);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
cout << map[i][j];
}
cout << endl;
}
} | true |
ea95cdea08b377b710a875b27c08f0c25d8d956d | C++ | RationalSolutions/cs235 | /W06/node.h | UTF-8 | 6,014 | 3.984375 | 4 | [] | no_license | /***********************************************************************
* Header:
* Node
* Summary:
* Node struct
*
* Author
* Coby Jenkins
* Michael Gibson
************************************************************************/
#ifndef CS235_NODE_H
#define CS235_NODE_H
/***********************************************************************
* NODE
* Linked list node.
***********************************************************************/
template <class T>
class Node
{
public:
T data;
Node * pPrev;
Node * pNext;
//Default Constructor
Node() : data(0), pNext(NULL), pPrev(NULL) {}
//Non Default Constructor
Node(const T &t) : data(t), pPrev(NULL), pNext(NULL) {}
};
/*************************************************************
* COPY
* Takes a pointer to a Node as a parameter and returns a newly
* created linked-list containing a copy of the nodes below the
* list represented by the parameter.
*************************************************************/
template <class T>
Node <T> * copy(const Node <T> * pSource)
{
Node<T> * pNewHead = new Node<T> (pSource->data);
Node<T> * pNew = pNewHead;
// insert nodes from source list to new list
for (Node <T> * p = pSource->pNext; p; p = p->pNext){
pNew = insert(pNew, p->data, true);
}
// return new head of the copy node
return pNewHead;
}
/****************************************************************
* INSERT
* Inserts a new Node into the current linked-list. The first
* parameter is the reference Node next to which the new Node is
* to be inserted. The second parameter is the valude to be inserted
* into the new node. The default will insert the new node before
* the reference node, leaving the third parameter optional. This
* parameter, if true, will set the new node to insert after the
* referenced node.
***************************************************************/
template <class T>
Node <T> * insert(Node <T> * pNode, const T & t, bool after = false)
{
// initialize new node
Node <T> *pNew = new Node <T> (t);
// reference node is null, no other nodes to point to
if(pNode == NULL){
// return pointer to new node
return pNew;
}
// insert after reference node and set node pointers
if(after){
pNew->pNext = pNode->pNext;
pNew->pPrev = pNode;
// if an existing node comes after reference node
if(pNode->pNext){
pNode->pNext->pPrev = pNew;
}
pNode->pNext = pNew;
}
else { // insert before reference node and set pointers
pNew->pNext = pNode;
pNew->pPrev = pNode->pPrev;
// if an existing node comes before reference node
if(pNode->pPrev){
pNode->pPrev->pNext = pNew;
}
pNode->pPrev = pNew;
}
// return pointer to new node
return pNew;
}
/*****************************************************************
* FIND
* Find the Node corresponding to the value passed from a given
* linked list. The first parameter is the point to the front of the list.
* The second parameter is the value to be found. The return value
* is a pointer to the item, if it exists.
*******************************************************************/
template <class T>
Node <T> * find(Node <T> * pHead, const T & t)
{
// search through the list starting with first node,
// comparing value to data in linked list
for(Node <T> * p = pHead; p ; p = p->pNext){
if(p->data == t){
// return a pointer to the node containing the found element
return p;
}
}
// element not found
return NULL;
}
/******************************************************************
* FREEDATA
* Release all the memory contained in a given linked-list. A single
* parameter points to the head of the list.
*******************************************************************/
template <class T>
void freeData(Node <T> * & pHead)
{
// deletes each node in the list starting with the first node
while(pHead != NULL){
Node <T> * p = pHead->pNext;
delete pHead;
pHead = p;
}
return;
}
/*****************************************************************
* REMOVE
* Removes a node from the linked-list. A single parameter points
* to the node that needs to be removed. If there is a node leading
* the referenced node, it returns a pointer that node. Otherwise,
* it returns a pointer to the node that follows the referenced node
*****************************************************************/
template <class T>
Node <T> * remove(const Node <T> * pRemove)
{
Node <T> * pRef;
// if the list is empty
if(pRemove == NULL){
std::cout << "The list is empty";
}
// change pNext from previous node to point to leading node
if(pRemove->pPrev){
pRemove->pPrev->pNext = pRemove->pNext;
}
// change pPrev from leading node to point to the following node
if(pRemove->pNext){
pRemove->pNext->pPrev = pRemove->pPrev;
}
// if there is a leading node to reference, set pRef to that node.
// Otherwise, set it to the node that follows.
pRef = pRemove->pPrev ? pRemove->pPrev : pRemove->pNext;
// clean up
delete pRemove;
// returns pointer to specified node (leading, following, or NULL)
return pRef;
}
/*****************************************************************
* INSERTION OPERATOR OVERLOAD (<<)
* Display contents of a linked-list.
****************************************************************/
template <class T>
std :: ostream & operator << (std :: ostream & out, const Node <T> * pHead)
{
// iterate through and display the linked-list
for(const Node <T> * p = pHead; p; p = p->pNext) {
if(p->pNext != NULL){
out << p->data << ", ";
}
else {
out << p->data;
}
}
return out;
}
#endif // CS235_NODE_H | true |
554f85760aa913450e956eb533ad04b421b52664 | C++ | IllinoisSimulatorLab/szg | /src/graphics/arGUIWindowManager.h | UTF-8 | 24,955 | 2.640625 | 3 | [
"LicenseRef-scancode-x11-opengl"
] | permissive | //********************************************************
// Syzygy is licensed under the BSD license v2
// see the file SZG_CREDITS for details
//********************************************************
#ifndef _AR_GUI_WINDOW_MANAGER_H_
#define _AR_GUI_WINDOW_MANAGER_H_
#include <map>
#include <vector>
#include "arGUIDefines.h"
#include "arGraphicsCalling.h"
class arWMEvent;
class arGUIRenderCallback;
class arGUIWindowingConstruct;
class arGraphicsWindow;
class arGUIInfo;
class arGUIKeyInfo;
class arGUIMouseInfo;
class arGUIWindowInfo;
class arGUIWindow;
class arGUIWindowConfig;
class arVector3;
//@{
/** @name Convenience typedef's for arGUIWindowManager functions.
* @todo Move these to a common location with other typedefs.
*/
typedef std::map<int, arGUIWindow* > WindowMap;
typedef WindowMap::iterator WindowIterator;
typedef std::vector<arWMEvent* > EventVector;
typedef EventVector::iterator EventIterator;
//@}
/**
* The manager for all the windows on the system.
*
* arGUIWindowManager is the API presented to the programmer wishing to create
* GUI windows. It is responsible for the creation, management, and
* destruction of any such windows. It is also responsible for passing back
* window, keyboard, and mouse events to the programmer either through
* callbacks or subclassing. It can operate in two distinct modes, single-
* threaded or multi-threaded, with the various arGUIWindow manipulators and
* accessors behaving differently yet appropriately in either mode.
*
* @see arGUIWindow
*/
class SZG_CALL arGUIWindowManager
{
public:
/**
* The arGUIWindowManager constructor.
*
* @param windowCallback The user-defined function that will be
* passed window events.
* @param keyboardCallback The user-defined function that will be
* passed keyboard events.
* @param mouseCallback The user-defined function that will be
* passed mouse events
* @param windowInitGLCallback The user-defined function that will be
* called after a window's OpenGL context is
* created
* @param threaded A flag determining whether the window
* manager will operate in single-threaded mode
*/
arGUIWindowManager( void (*windowCallback)( arGUIWindowInfo* ) = NULL,
void (*keyboardCallback)( arGUIKeyInfo* ) = NULL,
void (*mouseCallback)( arGUIMouseInfo* ) = NULL,
void (*windowInitGLCallback)( arGUIWindowInfo* ) = NULL,
bool threaded = true );
/**
* The arGUIWindowManager destructor
*
* @note The destructor is virtual so that arGUIWindowManager can be
* sub-classed if desired.
*/
virtual ~arGUIWindowManager( void );
/**
* Start the window manager running.
*
* The window manager will enter an infinite loop where it will issue draw
* requests, then swap requests, then process OS event messages and then
* call the event handlers for those messages for each window it controls.
*
* @note The draw requests will not be blocking and the swap requests will
* be blocking iff the window manager is in multi-threaded mode.
*
* @return Unused, this function will never return.
*
* @see drawAllWindows
* @see swapAllWindowBuffers
* @see processWindowEvents
*/
int startWithSwap( void );
/**
* Start the window manager running.
*
* Very similar to \ref startWithSwap this function will also enter the same
* infinite loop but will not issue swap requests. This function most
* closely mimics GLUT's \c glutMainLoop() with the user responsible for
* issuing swap buffer commands.
*
* @note The draw requests will not be blocking.
*
* @return Unused, this function will never return.
*
* @see drawAllWindows
* @see processWindowEvents
*/
int startWithoutSwap( void );
/**
* Create a new arGUIWindow.
*
* @note If the window manager is in single-threaded mode, the new
* arGUIWindow will exist in the same thread as the window manager.
* If the window manager is in multi-threaded mode then the new
* arGUIWindow will be created in a new thread.
*
* @note This function will only return (even in multi-threaded mode) only
* after the window has actually been created and is running.
*
* @param windowConfig The window configuration object specifying the
* parameters of the new window.
*
* @return <ul>
* <li>The new window's ID (an integer > 0) on success.
* <li>-1 on failure.
* </ul>
*
* @see arGUIWindow::arGUIWindow
* @see arGUIWindow::beginEventThread
* @see arGUIWindow::_performWindowCreation
*/
int addWindow( const arGUIWindowConfig& windowConfig,
bool useWindowing = true );
/**
* Create a set of (possibly) new arGUIWindows.
*
* A utility function that uses a parsed XML description of arGUIWindow's
* to create the windows. If any windows currently exist this function
* will attempt to do an intelligent 'diff' of the new windows against the
* old windows, tweaking windows where possible and only creating or
* deleting windows where necessary.
*
* @note This function may modify the window manager's threaded state.
*
* @return <ul>
* <li>0 on success.
* <li>-1 on failure.
* </ul>
*
* @see addWindow
* @see deleteWindow
* @see setGraphicsWindow
* @see registerDrawCallback
* @see arGUIWindowingConstruct
* @see arGUIXMLWindowConstruct
*/
int createWindows(const arGUIWindowingConstruct* windowingConstruct=NULL,
bool useWindowing = true );
//@{
/** @name Register Callbacks
*
* If the arGUIWindowManager constructor was called with NULL for any of
* the callbacks these functions can be used to later register appropriate
* functions.
*
* @warning These functions will blindly overwrite any currently registered
* callbacks.
*/
void registerWindowCallback( void (*windowCallback) ( arGUIWindowInfo* ) );
void registerKeyboardCallback( void (*keyboardCallback) ( arGUIKeyInfo* ) );
void registerMouseCallback( void (*mouseCallback) ( arGUIMouseInfo* ) );
void registerWindowInitGLCallback( void (*windowInitGLCallback)( arGUIWindowInfo* ) );
//@}
/**
* Register a draw callback with a window.
*
* @param ID The window to register the callback with.
* @param drawCallback The user-defined draw callback.
*
* @return <ul>
* <li>0 on successful registration.
* <li>-1 if the window could not be found.
* </ul>
*/
int registerDrawCallback( const int ID, arGUIRenderCallback* drawCallback );
/**
* Process any pending window events.
*
* For each window that the window manager controls, retrieve every OS
* event that occurred since the last call and pass them on to the
* programmer using the registered callbacks.
*
* @note If the window manager is in single-threaded mode this function is
* also responsible for calling \ref consumeAllWindowEvents so that
* the OS events are properly consumed.
*
* @return <ul>
* <li>0 on success
* <li>-1 on failure
* </ul>
*
* @see consumeAllWindowEvents
* @see arGUIWindow::getNextGUIEvent
* @see _keyboardHandler
* @see _mouseHandler
* @see _windowHandler
*/
int processWindowEvents( void );
/**
* Retrieve the next item on the window's stack of OS events.
*
* @note Meant as a helper function if the programmer wishes to control
* the operation of the window manager herself.
*
* @note The caller is responsible for deleting the returned pointer.
*
* @param ID The window for which to retrieve the next event.
*
* @return <ul>
* <li>A pointer to the OS event on success.
* <li>NULL if the window isn't found, if the window isn't
* currently running, or if there are no current OS events.
* </ul>
*
* @see arGUIWindow::getNextGUIEvent
*/
arGUIInfo* getNextWindowEvent( const int ID );
/**
* Issue a draw request to a single window.
*
* @note If the window manager is in single-threaded mode the draw request
* takes the form of an immediate execution of the window's draw
* handler whereas if the window manager is in multi-threaded mode
* the draw request will be passed as a message to the window.
*
* @param ID The window for which to request the draw.
* @param blocking Whether the window manager should wait for the request
* to finish before returning (meaningless in single-
* threaded mode).
*
* @return <ul>
* <li>0 on success.
* <li>-1 on failure.
* </ul>
*
* @see addWMEvent
*/
int drawWindow( const int ID, bool blocking = false );
/**
* Issue a draw request to every window.
*
* @note Operates similarly to \ref drawWindow with respect to single- vs
* multi-threading.
*
* @param blocking Whether the window manager should wait for the request
* to finish before returning (meaningless in single-
* threaded mode).
*
* @return <ul>
* <li>0 on success.
* <li>-1 on failure.
* </ul>
*
* @see addAllWMEvent
*/
int drawAllWindows( bool blocking = false );
/**
* Consume a window's pending OS events.
*
* The window will push any pending OS events onto its stack of such
* events, to be processed by the window manager.
*
* @warning This function is only meant for use by \ref processWindowEvents
* in single-threaded mode. Appropriate checks that it is not
* otherwise called are in place.
*
* @param ID The window whose OS events should be consumed.
* @param blocking Meaningless.
*
* @return <ul>
* <li>0 on success.
* <li>-1 if the window could not be found, if the window is not
* currently running, or if there is otherwise an error.
* </ul>
*
* @see arGUIWindow::_consumeWindowEvents
*/
int consumeWindowEvents( const int ID, bool blocking = false );
/**
* Consume every window's pending OS events.
*
* @note Operates similarly to \ref consumeWindowEvents with respect to
* single- vs. multi-threading.
*
* @param blocking Meaningless.
*
* @return <ul>
* <li>0 on success.
* <li>-1 on failure.
* </ul>
*
* @see arGUIWindow::_consumeWindowEvents
*/
int consumeAllWindowEvents( bool blocking = false );
// If this wm is managing multiple windows with different _Hz's, then
// blocking must be false otherwise both windows will run at whatever the
// lowest rate is.
/**
* Issue a swap request to a single window.
*
* @note If the window manager is in single-threaded mode the swap request
* takes the form of an immediate swap of the window's buffers
* whereas if the window manager is in multi-threaded mode the swap
* request will be passed as a message to the window.
*
* @param ID The window for which to request the swap.
* @param blocking Whether the window manager should wait for the request
* to finish before returning (meaningless in single-
* threaded mode).
*
* @return <ul>
* <li>0 on success.
* <li>-1 on failure.
* </ul>
*
* @see addWMEvent
*
* @todo properly implement windows having different _Hz's.
*/
int swapWindowBuffer( const int ID, bool blocking = false );
/**
* Issue a swap request to every window.
*
* @note Operates similarly to \ref swapWindowBuffer with respect to
* single- vs multi-threading.
*
* @param blocking Whether the window manager should wait for the request
* to finish before returning (meaningless in single-
* threaded mode).
*
* @return <ul>
* <li>0 on success.
* <li>-1 on failure.
* </ul>
*
* @see addAllWMEvent
*/
int swapAllWindowBuffers( bool blocking = false );
/**
* Set a window's width and height.
*
* @note Sets the window's <b>client area</b> width and height.
*
* @param ID The window to perform the operation on.
* @param width The new width.
* @param height The new height.
*
* @return <ul>
* <li>0 on success.
* <li>-1 if the window could not be found or there was otherwise
* an error.
* </ul>
*
* @see addWMEvent
* @see arGUIWindow::resize
*/
int resizeWindow( const int ID, int width, int height );
/**
* Move a window to a new location.
*
* @note The upper-left corner of the window's screen (not client area)
* will be moved to the new location.
*
* @param ID The window to perform the operation on.
* @param x The new x coordinate.
* @param y The new y coordinate.
*
* @return <ul>
* <li>0 on success.
* <li>-1 if the window could not be found or there was otherwise
* an error.
* </ul>
*
* @see addWMEvent
* @see arGUIWindow::move
*/
int moveWindow( const int ID, int x, int y );
/**
* Sets the window's OpenGL viewport.
*
* @param ID The window to perform the operation on.
* @param x The left corner x coordinate.
* @param y The bottom corner y coordinate.
* @param width The width of the viewport.
* @param height The height of the viewport.
*
* @return <ul>
* <li>0 on success.
* <li>-1 if the window could not be found or there was otherwise
* an error.
* </ul>
*
* @see addWMEvent
* @see arGUIWindow::setViewport
*/
int setWindowViewport( const int ID, int x, int y, int width, int height );
/**
* Make the window fullscreen.
*
* @note Does not resize the desktop to the window's resolution, instead
* the window's resolution is changed to match that of the desktop.
*
* @note Call \ref resizeWindow to restore the window to a non-fullscreen
* state.
*
* @param ID The window to perform the operation on.
*
* @return <ul>
* <li>0 on success.
* <li>-1 if the window could not be found or there was otherwise
* an error.
* </ul>
*
* @see addWMEvent
* @see arGUIWindow::fullscreen
*/
int fullscreenWindow( const int ID );
/**
* Set the state of the window's border decorations.
*
* @warning Under X11 this function is window manager specific, currently
* it should work under Motif, KDE and Gnome.
*
* @note Has no effect if the window is in fullscreen mode.
*
* @param ID The window to perform the operation on.
* @param decorate A flag determining whether border decorations should be
* turned on or off.
* @return <ul>
* <li>0 on success.
* <li>-1 if the window could not be found or there was otherwise
* an error.
* </ul>
*
* @see addWMEvent
* @see arGUIWindow::decorate
*/
int decorateWindow( const int ID, bool decorate );
/**
* Set the state of the window's mouse cursor.
*
* @param ID The window to perform the operation on.
* @param cursor The new cursor type of the window.
*
* @return <ul>
* <li>0 on success.
* <li>-1 if the window could not be found or there was otherwise
* an error.
* </ul>
*
* @see addWMEvent
* @see arGUIWindow::setCursor
*/
int setWindowCursor( const int ID, arCursor cursor );
/**
* Set the state of the window's z order.
*
* @param ID The window to perform the operation on.
* @param zorder The new zorder of the window.
*
* @return <ul>
* <li>0 on success.
* <li>-1 if the window could not be found or there was otherwise
* an error.
* </ul>
*
* @see addWMEvent
* @see arGUIWindow::raise
*/
int raiseWindow( const int ID, arZOrder zorder );
// Accessors.
// How are these used? why not return arVector2 instead?
// Better yet, return bool, and stuff x and y passed by reference.
arVector3 getWindowSize( const int ID );
arVector3 getWindowPos( const int ID );
arVector3 getMousePos( const int ID );
arCursor getWindowCursor( const int ID );
bool isStereo( const int ID );
bool isFullscreen( const int ID );
bool isDecorated( const int ID );
bool windowExists( const int ID ) const { return _windows.find( ID ) != _windows.end(); }
arZOrder getZOrder( const int ID );
int getBpp( const int ID );
std::string getTitle( const int ID );
std::string getXDisplay( const int ID );
void setTitle( const int ID, const std::string& title );
void setAllTitles( const std::string& baseTitle, bool overwrite=true );
void* getUserData( const int ID );
void setUserData( const int ID, void* userData );
arGraphicsWindow* getGraphicsWindow( const int ID );
void returnGraphicsWindow( const int ID );
void setGraphicsWindow( const int ID, arGraphicsWindow* graphicsWindow );
/**
* Retrieve the current state of a keyboard key.
*
* @note this function is static as the keyboard is not tied to any
* particular window.
*
* @param key The key whose state to retrieve.
*
* @return arGUIKeyinfo The state information.
*
* @todo Actually implement this function using the appropriate OS calls.
* On Windows ME, the
* function needed to implement this function, GetKeyState,
* is hardcoded to return nothing.
*/
static arGUIKeyInfo getKeyState( const arGUIKey key );
// Getting mouse state outside of a window context makes no sense.
// static arMouseInfo getMouseState( void );
//@{
/** @name Window manager state accessors
*
* Retrieve or set the window manager's current state.
*/
int getNumWindows( void ) const { return _windows.size(); }
bool hasActiveWindows( void ) const { return !_windows.empty(); }
bool hasStereoWindows( void );
bool isFirstWindow( const int ID ) const { return( _windows.find( ID ) == _windows.begin() ); }
int getFirstWindowID( void ) const { return _windows.begin()->first; }
bool isThreaded( void ) const { return _threaded; }
void setThreaded( bool threaded );
void setUserData( void* userData ) { _userData = userData; }
void* getUserData( void ) const { return _userData; }
//@}
/**
* Issue a kill request to a single window.
*
* @note If the window manager is in single-threaded mode the kill request
* will be executed immediately whereas if the window manager is in
* multi-threaded mode the draw request will be passed as a blocking
* message to the window.
*
* @param ID The window for which to request the kill.
*
* @return <ul>
* <li>0 on success (with a guarantee that on return the window
* has already been destroyed).
* <li>-1 on failure (the window may not actually be destroyed).
* </ul>
*
* @see addWMEvent
* @see arGUIWindow::_killWindow
*/
int deleteWindow( const int ID );
/**
* Issue a kill request to every window.
*
* @note Operates similarly to \ref deleteWindow with respect to single- vs
* multi-threading.
*
* @return <ul>
* <li>0 on success (with a guarantee that on return the windows
* have already been destroyed).
* <li>-1 on failure (the windows may not actually be destroyed).
* </ul>
*
* @see deleteWindow
*/
int deleteAllWindows( void );
//@{
/** @name Window manager framelock accessors.
*
* Operate upon the framelock.
*/
void useFramelock( bool isOn );
void findFramelock( void );
void activateFramelock( void );
void deactivateFramelock( void );
//@}
private:
/**
* Add a window manager message to a window.
*
* @note Meant to be used as a helper function for those public functions
* that take a single window ID.
*
* @note In single-threaded mode any event passed to this function will be
* executed by the window immediately and the return value
* <b>will</b> be NULL.
*
* @warning The caller should <b>not</b> delete the returned pointer.
* It will be managed by the window itself. The caller is also
* the one who should decide if this is a blocking call or not.
*
* @param ID The window to pass the message to.
* @param event The message to pass to the window.
*
* @return A pointer to the event added by the window, necessary so that
* the caller can appropriately block on the event's completion.
*
* @see arGUIWindow::addWMEvent
*/
arWMEvent* addWMEvent( const int ID, arGUIWindowInfo event );
/**
* Add a window manager message to every window.
*
* @note Meant to be used as a helper function for those public functions
* that perform an operation on all windows.
*
* @param wmEvent The message to pass to the windows.
* @param blocking Whether this should call should block on the event's
* completion. If so, it will not return until all windows
* have parsed the message. (Meaningless in single-threaded
* mode)
*
* @return <ul>
* <li>0
* </ul>
*
* @see addWmEvent
* @see WMEvent::wait
*/
int addAllWMEvent( arGUIWindowInfo wmEvent, bool blocking );
/**
* A helper function for \ref deleteWindow and \ref deleteAllWindows.
*
* Organizes functionality common to both delete calls.
*
* @param ID The window to send the message to.
*/
void _sendDeleteEvent( const int ID );
//@{
/** @name Wrappers for the keyboard, mouse, and window callbacks.
*
* @note If the programmer wants something different to happen on OS events
* other than simply the user-defined callbacks being called then she
* should subclass arGUIWindowManager and overload these functions.
*/
virtual void _keyboardHandler( arGUIKeyInfo* keyInfo );
virtual void _mouseHandler( arGUIMouseInfo* mouseInfo );
virtual void _windowHandler( arGUIWindowInfo* windowInfo );
//@}
void (*_keyboardCallback)( arGUIKeyInfo* keyInfo ); // keyboard events
void (*_mouseCallback)( arGUIMouseInfo* mouseInfo ); // mouse events
void (*_windowCallback)( arGUIWindowInfo* windowInfo ); // window events
void (*_windowInitGLCallback)( arGUIWindowInfo* windowInfo ); // opengl init
int _doEvent(const int ID, const arGUIWindowInfo& event);
WindowMap _windows; // A map of all the managed windows and their id's.
int _maxID; // The maximum window ID, used in creating new windows.
bool _threaded; // False iff windowmanager is singlethreaded.
void* _userData; // Default user defined data pointer passed to created windows.
bool _fActivatedFramelock;
};
#endif
| true |
28a74b5a66d7183c811f0f1e186841cee753b569 | C++ | BlackFox101/OOP | /lw3/Calculator/Calculator/Calculator.cpp | UTF-8 | 7,962 | 3.25 | 3 | [] | no_license | #include <iostream>
#include "Calculator.h"
#include <algorithm>
#include <cmath>
#include <regex>
#include <map>
#include <iomanip>
using namespace std;
Calculator::Calculator(istream& input, ostream& output) : m_input(input), m_output(output)
{
}
optional<Command> Calculator::GetCommand() const
{
string str;
m_input >> str;
transform(str.begin(), str.end(), str.begin(), ::tolower);
if (str == "var")
{
return Command::Var;
}
else if (str == "let")
{
return Command::Let;
}
else if (str == "fn")
{
return Command::Function;
}
else if (str == "print")
{
return Command::Print;
}
else if (str == "printvars")
{
return Command::PrintVariables;
}
else if (str == "printfns")
{
return Command::PrintFunctions;
}
return nullopt;
}
bool Calculator::PerformCommand(Command command)
{
string str;
string id1;
string id2;
switch (command)
{
case Command::Var:
m_input >> str;
return CreateVariable(str);
case Command::Let:
m_input >> str;
if (str.find('=') == std::string::npos)
{
return false;
}
id1 = str.substr(0, str.find('='));
id2 = str.substr(id1.length() + 1);
if (id2.length() == 0)
{
m_output << "The second ID is not specified\n";
return false;
}
return AddVariableValue(id1, id2);
case Command::Function:
m_input >> str;
if (str.find('=') == std::string::npos)
{
return false;
}
id1 = str.substr(0, str.find('='));
id2 = str.substr(id1.length() + 1);
return CreateFunction(id1, id2);
case Command::Print:
m_input >> str;
Print(str);
break;
case Command::PrintVariables:
PrintVariables();
break;
case Command::PrintFunctions:
PrintFunctions();
break;
default:
break;
}
return true;
}
bool Calculator::AddVariableValue(const string& id1, const string& id2)
{
if (!IsIdExists(id1))
{
CreateVariable(id1);
}
double number;
ParsingResult ParsingResult = IdentifyId(id2, number);
switch (ParsingResult)
{
case ParsingResult::Number:
m_vars[id1] = { number };
m_output << "The variable was successfully assigned a new value!\n";
break;
case ParsingResult::Identifier:
if (!IdentifierValidation(id2))
{
m_output << "Invalid argument\n";
return false;
}
auto isExist = IsIdExists(id2);
if (isExist)
{
if (isExist == OperandType::Variable)
{
m_vars[id1] = m_vars[id2];
}
else
{
auto tempNumber = CalculateFunction(id2);
m_vars[id1] = { *tempNumber };
}
m_output << "Variable changed successfully!\n";
return true;
}
return false;
}
return true;
}
ParsingResult Calculator::IdentifyId(const string& str, double& number) const
{
size_t pos;
try
{
number = stod(str, &pos);
if (pos != str.length())
{
return ParsingResult::Identifier;
}
return ParsingResult::Number;
}
catch (const invalid_argument&)
{
return ParsingResult::Identifier;;
}
}
bool Calculator::CreateVariable(const string& id)
{
if (!IdentifierValidation(id))
{
m_output << "Invalid argument'" << id << "'\n";
return false;
}
if (IsIdExists(id))
{
m_output << "This identifier '" << id << "' already exists!\n";
return false;
}
m_vars[id] = nullopt;
m_output << "Variable saved successfully!\n";
return true;
}
bool Calculator::IdentifierValidation(const string& str) const
{
smatch result;
regex regular("^[^0-9][A-Za-z0-9_]*");
return regex_match(str, result, regular);
}
optional<OperandType> Calculator::IsIdExists(const string& id) const
{
if (m_vars.find(id) != m_vars.end())
{
return OperandType::Variable;
}
if (m_funcs.find(id) != m_funcs.end())
{
return OperandType::Function;
}
return nullopt;
}
void Calculator::Print(const string& id) const
{
if (m_vars.find(id) != m_vars.end())
{
optional<Variable> value = m_vars.at(id);
if (value)
{
m_output << fixed << setprecision(2) << value->number << endl;;
}
else
{
m_output << "nan" << endl;
}
return;
}
if (m_funcs.find(id) != m_funcs.end())
{
auto value = CalculateFunction(m_funcs.at(id));
if (value)
{
m_output << fixed << setprecision(2) << *value << endl;;
}
else
{
m_output << "nan" << endl;
}
return;
}
m_output << "This ID does not exist\n";
}
bool Calculator::DefiningOperator(const string& str, optional<Operation>& oper) const
{
if (str.find('+') != std::string::npos)
{
oper = Operation::Plus;
return true;
}
if (str.find('-') != std::string::npos)
{
oper = Operation::Minus;
return true;
}
if (str.find('*') != std::string::npos)
{
oper = Operation::Multiply;
return true;
}
if (str.find('/') != std::string::npos)
{
oper = Operation::Divide;
return true;
}
oper = nullopt;
return false;
}
bool Calculator::CheckingIdsCorrectness(const string& id1, const string& id2) const
{
if (!IdentifierValidation(id2))
{
m_output << "Invalid argument '" << id2 << "'\n";
return false;
}
if (!IsIdExists(id2))
{
m_output << "This identifier '" << id2 << "' is not exists!\n";
return false;
}
return !AreIdsEqual(id1, id2);
}
bool Calculator::CreateFunction(const string& id1, const string& id2)
{
if (!IdentifierValidation(id1))
{
m_output << "Invalid argument!\n";
return false;
}
if (IsIdExists(id1))
{
m_output << "This identifier already exists!\n";
return false;
}
optional<Operation> operation;
if (DefiningOperator(id2, operation))
{
string tempId1 = id2.substr(0, id2.find((char)*operation));
if (!CheckingIdsCorrectness(id1, tempId1))
{
return false;
}
string tempId2 = id2.substr(tempId1.length() + 1);
if (!CheckingIdsCorrectness(id1, tempId2))
{
return false;
}
m_funcs[id1] = { tempId1, operation, tempId2 };
m_output << "Function saved successfully!\n";
}
else
{
if (!CheckingIdsCorrectness(id1, id2))
{
return false;
}
m_funcs[id1] = { id2, operation, nullopt };
m_output << "Function saved successfully!\n";
}
return true;
}
bool Calculator::AreIdsEqual(const string& id1, const string& id2) const
{
if (id1 == id2)
{
m_output << "You can't assign a function to itself!\n";
return true;
}
return false;
}
void Calculator::PrintVariables() const
{
if (m_vars.empty())
{
m_output << "The list of functions is empty\n";
}
for (auto& it : m_vars)
{
m_output << it.first << ":";
if (it.second)
{
m_output << fixed << setprecision(2) << it.second->number << endl;
}
else
{
m_output << "nan" << endl;
}
}
}
void Calculator::PrintFunctions() const
{
if (m_funcs.empty())
{
m_output << "The list of functions is empty\n";
}
for (auto& it : m_funcs)
{
auto value = CalculateFunction(m_funcs.at(it.first));
m_output << it.first << ":";
m_output << fixed << setprecision(2) << *value << endl;
}
}
optional<double> Calculator::CalculateFunction(const Function& function) const
{
if (!function.operation)
{
return CalculateFunction(function.id1);
}
return Calculate(CalculateFunction(function.id1), CalculateFunction(*function.id2), *function.operation);
}
optional<double> Calculator::CalculateFunction(const string& id) const
{
auto value = IsIdExists(id);
if (value && value == OperandType::Variable)
{
return GetVariableValue(id);
}
return CalculateFunction(*GetFunction(id));
}
optional<double> Calculator::GetVariableValue(const string& id) const
{
if (m_vars.find(id) != m_vars.end())
{
auto number = m_vars.at(id);
if (number)
{
return number->number;
}
return nullopt;
}
return nullopt;
}
optional<Function> Calculator::GetFunction(const string& id) const
{
if (m_funcs.find(id) != m_funcs.end())
{
return m_funcs.at(id);
}
return nullopt;
}
optional<double> Calculator::Calculate(optional<double> x, optional<double> y, Operation operation) const
{
if (!x || !y)
{
return nullopt;
}
switch (operation)
{
case Operation::Plus:
return *x + *y;
case Operation::Minus:
return *x - *y;
case Operation::Multiply:
return *x * *y;
case Operation::Divide:
return *x / *y;
}
} | true |
5f1fe2d10e6595e6e6d29b7e83aae3f2de7483af | C++ | atharvapawar181/FDS-Codes-for-Second-year-Engineering | /E31.cpp | UTF-8 | 3,055 | 3.953125 | 4 | [] | no_license | /*A double-ended queue (deque) is a linear list in which additions and deletions may be
made at either end. Obtain a data representation mapping a deque into a one-
dimensional array. Write C++ program to simulate deque with functions to add and
delete elements from either end of the deque.*/
#include <iostream>
#include <stdio.h>
#define MAX 10
using namespace std;
struct que
{
int arr[MAX];
int front, rear;
};
void init(struct que *q)
{
q->front = -1;
q->rear = -1;
}
void print(struct que q)
{
int i;
i = q.front;
while (i != q.rear)
{
cout << "\t" << q.arr[i];
i = (i + 1) % MAX;
}
cout << "\t" << q.arr[q.rear];
}
int isempty(struct que q)
{
return q.rear == -1 ? 1 : 0;
}
int isfull(struct que q)
{
return (q.rear + 1) % MAX == q.front ? 1 : 0;
}
void addf(struct que *q, int data)
{
if (isempty(*q))
{
q->front = q->rear = 0;
q->arr[q->front] = data;
}
else
{
q->front = (q->front - 1 + MAX) % MAX;
q->arr[q->front] = data;
}
}
void addr(struct que *q, int data)
{
if (isempty(*q))
{
q->front = q->rear = 0;
q->arr[q->rear] = data;
}
else
{
q->rear = (q->rear + 1) % MAX;
q->arr[q->rear] = data;
}
}
int delf(struct que *q)
{
int data1;
data1 = q->arr[q->front];
if (q->front == q->rear)
init(q);
else
q->front = (q->front + 1) % MAX;
return data1;
}
int main()
{
struct que q;
int data, ch;
init(&q);
while (ch != 6)
{
cout << "\t\n1.Insert front,"
"\t\n2.Insert rear,"
"\t\n3.Delete front,"
"\t\n4.Delete rear,"
"\t\n5.Print,"
"\t\n6.Exit";
cout << "\n\tEnter your choice";
cin >> ch;
switch (ch)
{
case 1:
cout << "\nEnter data to insert front:";
cin >> data;
addf(&q, data);
break;
case 2:
cout << "\nEnter the data to insert rear:";
cin >> data;
addr(&q, data);
break;
case 3:
if (isempty(q))
cout << "\nDequeue is empty";
else
{
data = delf(&q);
cout << "\nDeleted data is" << data;
}
break;
case 4:
if (isempty(q))
cout << "\nDequeue is empty";
else
{
data = delr(&q);
cout << "\nDeleted data is" << data;
}
break;
case 5:
if (isempty(q))
cout << "\nDequeue is empty";
else
{
cout << "\nDequeue elements are:";
print(q);
}
break;
}
}
return 0;
}
| true |
7f83e3ee6c55808b54a606cefc8c215db262d1b8 | C++ | zeal4u/leetcode | /FreqStack.h | UTF-8 | 703 | 2.890625 | 3 | [] | no_license | //
// Created by zeal4u on 2018/10/12.
//
#ifndef LEETCODE_FREQSTACK_H
#define LEETCODE_FREQSTACK_H
#include <unordered_map>
#include <stack>
using namespace std;
class FreqStack {
private:
unordered_map<int, stack<int>> data;
unordered_map<int, int> count;
int max_freq;
public:
FreqStack():data(), count(), max_freq(){
}
void push(int x) {
count[x]++;
data[count[x]].push(x);
max_freq = max(max_freq, count[x]);
}
int pop() {
int result = data[max_freq].top();
data[count[result]--].pop();
if(data[max_freq].empty()){
max_freq--;
}
return result;
}
};
#endif //LEETCODE_FREQSTACK_H
| true |
525c0e526ac61d2f801088e31429d7f50e8868cd | C++ | rajattarade/Arduino_codes | /EEROM/EEROM.ino | UTF-8 | 430 | 2.65625 | 3 | [] | no_license | #include <EEPROM.h>
int a = 0;
int value;
void setup()
{
Serial.begin(9600);
}
void loop()
{
value = EEPROM.read(a);
/* if(value>10)
{
printf("BLOCK FOREVER");
delay(100);
while(1);
}
/* value = EEPROM.read(a);
value = value+1;
EEPROM.write(a, value);
value = EEPROM.read(a);
*/EEPROM.write(a, 0);
Serial.print(a);
Serial.print("\t");
Serial.print(value);
Serial.println();
while(1);
}
| true |
cf3a896bd800828b3eab7eb935e5a700d71cc038 | C++ | burncode/The-C-Programming-Language | /ch3/3-2.cpp | UTF-8 | 1,837 | 3.40625 | 3 | [] | no_license | // Author: jrjbear@gmail.com
// Date: Fri Oct 4 19:10:37 2013
//
// File: 3-2.cpp
// Description: Conver escape characters into visable ones and visa versa
#include <stdio.h>
#include "utils/utils.h"
int escape(char dst[], const char src[]);
int unescape(char dst[], const char src[]);
int main(int argc, char* argv[])
{
const int BUFSIZE = 1024;
char buf[BUFSIZE];
char line[BUFSIZE];
while (my_getline(line, BUFSIZE) > 0) {
escape(buf, line);
printf("After escape: %s\n", buf);
unescape(line, buf);
printf("Unescape back to origin: %s\n", line);
}
return 0;
}
int escape(char dst[], const char src[])
{
int offset = 0;
for (int i = 0; src[i] != '\0'; ++i) {
switch (src[i]) {
case '\t':
dst[offset++] = '\\';
dst[offset++] = 't';
break;
case '\n':
dst[offset++] = '\\';
dst[offset++] = 'n';
break;
case '\b':
dst[offset++] = '\\';
dst[offset++] = 'b';
break;
default:
dst[offset++] = src[i];
break;
}
}
dst[offset] = '\0';
return 0;
}
int unescape(char dst[], const char src[])
{
int offset = 0;
for (int i = 0; src[i] != '\0'; ++i) {
if (src[i] == '\\') {
switch (src[++i]) {
case 't':
dst[offset++] = '\t';
break;
case 'n':
dst[offset++] = '\n';
break;
case 'b':
dst[offset++] = '\b';
break;
default:
--i;
dst[offset++] = '\\';
break;
}
} else {
dst[offset++] = src[i];
}
}
dst[offset] = '\0';
return 0;
}
| true |
0878c0ef83dace93654c8280ad388f9bee30a78a | C++ | nightlark/GridDyn | /src/utilities/workQueue.h | UTF-8 | 11,449 | 3.046875 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* LLNS Copyright Start
* Copyright (c) 2014-2018, Lawrence Livermore National Security
* This work was performed under the auspices of the U.S. Department
* of Energy by Lawrence Livermore National Laboratory in part under
* Contract W-7405-Eng-48 and in part under Contract DE-AC52-07NA27344.
* Produced at the Lawrence Livermore National Laboratory.
* All rights reserved.
* For details, see the LICENSE file.
* LLNS Copyright End
*/
#ifndef WORKQUEUE_H_
#define WORKQUEUE_H_
#pragma once
#include "simpleQueue.hpp"
#include <future>
#include <memory>
#include <thread>
#include <utility>
/** basic work block abstract class*/
class basicWorkBlock
{
public:
basicWorkBlock (){};
virtual ~basicWorkBlock () = default;
/** run the work block*/
virtual void execute () = 0;
/** check if the work is finished
@return true if the work has been done false otherwise
*/
virtual bool isFinished () const = 0;
};
/** implementation of a workBlock class
The class takes as an input object of some kind function, std::function, lambda that can be executed,
functionoid, or something that implements operator()
*/
template <typename retType>
class workBlock : public basicWorkBlock
{
public:
workBlock () { reset (); };
// copy constructor intentionally omitted*/
/** move constructor*/
workBlock (workBlock &&wb) = default;
/** constructor from a packaged task*/
workBlock (std::packaged_task<retType ()> &&newTask) : task (std::move (newTask)), loaded (true) { reset (); }
/** construct from a some sort of functional object*/
template <typename Func> // forwarding reference
workBlock (Func &&newWork) : task (std::forward<Func> (newWork)), loaded (true)
{
static_assert (std::is_same<decltype (newWork ()), retType>::value, "work does not match type");
reset ();
}
/** move assignment*/
workBlock &operator= (workBlock &&wb) = default;
/** execute the work block*/
virtual void execute () override
{
if (!finished)
{
if (loaded)
{
task ();
}
finished = true;
}
}
/** get the return value, will block until the task is finished*/
retType getReturnVal () const { return future_ret.get (); }
/** update the work function
@param[in] the work to do*/
template <typename Func>
void updateWorkFunction (Func &&newWork) // forwarding reference
{
static_assert (std::is_same<decltype (newWork ()), retType>::value, "work does not match type");
loaded = false;
task = std::packaged_task<retType ()> (std::forward<Func> (newWork));
reset ();
loaded = true;
}
/** update the task with a new packaged_task
@param[in] newTask the packaged task with the correct return type*/
void updateTask (std::packaged_task<retType ()> &&newTask)
{
loaded = false;
task = std::move (newTask);
reset ();
loaded = true;
}
/** check if the task is finished*/
bool isFinished () const override { return finished; };
/** wait until the work is done*/
void wait () { future_ret.wait (); };
/** reset the work so it can run again*/
void reset ()
{
if (loaded)
{
task.reset ();
}
finished = false;
future_ret = task.get_future ();
};
/** get the shared future object*/
std::shared_future<retType> get_future () { return future_ret; }
private:
std::packaged_task<retType ()> task; //!< the task to do
std::shared_future<retType> future_ret; //!< shared future object
bool finished; //!< flag indicating the work has been done
bool loaded = false; //!< flag indicating that the task is loaded
};
/** implementation of a workBlock class with void return type
The class takes as an input object of some kind function, std::function, lambda that can be executed
*/
template <>
class workBlock<void> : public basicWorkBlock
{
public:
workBlock () { reset (); };
workBlock (std::packaged_task<void()> &&newTask) : task (std::move (newTask)), loaded (true) { reset (); }
template <typename Func>
workBlock (Func &&newWork) : task (std::forward<Func> (newWork)), loaded (true)
{
static_assert (std::is_same<decltype (newWork ()), void>::value, "work does not match type");
reset ();
}
workBlock (workBlock &&wb) = default;
workBlock &operator= (workBlock &&wb) = default;
virtual void execute () override
{
if (!finished)
{
if (loaded)
{
task ();
}
finished = true;
}
};
void getReturnVal () const { future_ret.wait (); }
template <typename Func>
void updateWorkFunction (Func &&newWork)
{
static_assert (std::is_same<decltype (newWork ()), void>::value, "work does not match type");
loaded = false;
task = std::packaged_task<void()> (std::forward<Func> (newWork));
reset ();
loaded = true;
}
void updateTask (std::packaged_task<void()> &&newTask)
{
loaded = false;
task = std::move (newTask);
reset ();
loaded = true;
}
bool isFinished () const override { return finished; };
void wait () const { future_ret.wait (); };
void reset ()
{
if (loaded)
{
task.reset ();
}
finished = false;
future_ret = task.get_future ();
};
std::shared_future<void> get_future () { return future_ret; }
private:
std::packaged_task<void()> task;
std::shared_future<void> future_ret;
bool finished;
bool loaded = false;
};
/** make a unique pointer to a workBlock object from a functional object
@param[in] fptr a std::function, std::bind, functionoid, lamda function or anything else
that could be called with operator()
@return a unique pointer to a work block function
*/
template <typename X>
auto make_workBlock (X &&fptr) //->std::unique_ptr<workBlock<decltype(fptr())>>
{
return std::make_unique<workBlock<decltype (fptr ())>> (std::forward<X> (fptr));
}
/** make a shared pointer to a workBlock object from a functional object
@param[in] fptr a std::function, std::bind, functionoid, lambda function or anything else
that could be called with operator()
@return a shared pointer to a work block function
*/
template <typename X>
auto make_shared_workBlock (X &&fptr) //->std::shared_ptr<workBlock<decltype(fptr())>>
{
return std::make_shared<workBlock<decltype (fptr ())>> (std::forward<X> (fptr));
}
/** make a unique pointer to a workBlock object from a packaged task object
@param[in] task a packaged task containing something to do
@return a unique pointer to a work block function
*/
template <typename X>
auto make_workBlock (std::packaged_task<X ()> &&task)
{
return std::make_unique<workBlock<X>> (std::move (task));
}
/** make a shared pointer to a workBlock object from a packaged task object
@param[in] task a packaged task containing something to do
@return a unique pointer to a work block function
*/
template <typename X>
auto make_shared_workBlock (std::packaged_task<X ()> &&task)
{
return std::make_shared<workBlock<X>> (std::move (task));
}
/** the default ratio between med and low priority tasks*/
constexpr int defaultPriorityRatio (4);
/** class defining a work queuing system
implemented with 3 priority levels high medium and low
high is executed as a soon as possible in order
medium is executed with X times more frequently than low with X being defined by the priority ratio
*/
class workQueue
{
public:
/** enumeration defining the work block priority*/
enum class workPriority
{
medium, //!< do the work with a specific ratio of priority to low priority tasks
low, //!< low priority do the work every once in a while determined by the priority ratio
high, //!< do the work as soon as possible
};
/**
* class destructor must be public so it can be used with shared_ptr
*/
~workQueue (); // destructor
/** get an instance of the workQueue
* @param[in] threadCount the number of threads
* Return the current instance of the singleton.
*
*/
static std::shared_ptr<workQueue> instance (int threadCount = -1);
/** get the number of workers
static so it can be called before instance is valid
@return int with the current worker count
*/
static int getWorkerCount ();
/** destroy the workQueue*/
void destroyWorkerQueue ();
/** add a block of work to the workQueue
@param[in] newWork the block of new work for the queue
*/
void addWorkBlock (std::shared_ptr<basicWorkBlock> newWork, workPriority priority = workPriority::medium);
/** add a block of work to the workQueue
@param[in] newWork a vector of workBlocks to add to the queue
*/
void addWorkBlock (std::vector<std::shared_ptr<basicWorkBlock>> &newWork,
workPriority priority = workPriority::medium);
/** check if the queue is empty
@return true if the queue is empty false if it has work to do
*/
bool isEmpty () const
{
return ((workToDoHigh.empty ()) && (workToDoMed.empty ()) && (workToDoLow.empty ()));
};
/** get the number of remaining blocks*/
size_t numBlock () const { return (workToDoHigh.size () + workToDoMed.size () + workToDoLow.size ()); };
/** set the ratio of medium block executions to low priority block executions
@param[in] newPriorityRatio if >0 used as the new ratio otherwise set to default value*/
void setPriorityRatio (int newPriorityRatio)
{
priorityRatio = (newPriorityRatio > 0) ? newPriorityRatio : defaultPriorityRatio;
};
/** get the next work block
@return a shared pointer to a work block
*/
std::shared_ptr<basicWorkBlock> getWorkBlock ();
private:
/** the main worker loop*/
void workerLoop ();
/**
* Singleton so prevent external construction and copying of this
* class.
@param[in] threadCount the number of threads in the queue (<0 for default value)
*/
explicit workQueue (int threadCount);
workQueue (workQueue const &) = delete;
workQueue &operator= (workQueue const &) = delete;
/**
* Singleton instance.
*/
static std::shared_ptr<workQueue> pInstance; //!< the pointer to the singleton
static std::mutex instanceLock; //!< lock for creating the queue
int priorityRatio = defaultPriorityRatio; //!< the ratio of medium Priority blocks to low priority blocks
int numWorkers = 0; //!< counter for the number of workers
std::atomic<int> MedCounter{0}; //!< the counter to use low instead of Med
SimpleQueue<std::shared_ptr<basicWorkBlock>> workToDoHigh; //!< queue containing the work to do
SimpleQueue<std::shared_ptr<basicWorkBlock>> workToDoMed; //!< queue containing the work to do
SimpleQueue<std::shared_ptr<basicWorkBlock>> workToDoLow; //!< queue containing the work to do
std::vector<std::thread> threadpool; //!< the threads
std::mutex queueLock; //!< mutex for condition variable
std::condition_variable queueCondition; //!< condition variable for waking the threads
std::atomic<bool> halt{false}; //!< flag indicating the threads should halt
};
#endif | true |
6336c19c4f96c86af1758e149bff3f02f8e56351 | C++ | triminh12042002/CS162_projects | /FinalProject/FinalProject/function.cpp | UTF-8 | 50,895 | 2.90625 | 3 | [] | no_license |
#include "Header.h"
using namespace std;
// ctrl + m + o de thu nho code
// ctrl + m + p de phong to code
void SetColor(int backgound_color, int text_color)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
int color_code = backgound_color * 16 + text_color;
SetConsoleTextAttribute(hStdout, color_code);
}
void GoTo(SHORT posX, SHORT posY)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
COORD Position;
Position.X = posX;
Position.Y = posY;
SetConsoleCursorPosition(hStdout, Position);
}
void loadListofSchoolYear(SchoolYear*& pHeadSchoolYear, int& schoolYearSize, char path[]) {
SchoolYear* pT = nullptr;
while (pHeadSchoolYear != nullptr) {
pT = pHeadSchoolYear;
pHeadSchoolYear = pHeadSchoolYear->pNext;
delete pT;
}
pHeadSchoolYear = nullptr;
schoolYearSize = 0;
ifstream fin;
fin.open(path);
if (fin.is_open() == false) {
cout << "\nfirst time open file";
fin.close();
ofstream fout;
fout.open(path);
fout.close();
fin.open(path);
}
SchoolYear* pTemp = pHeadSchoolYear;
string temp;
while (!fin.eof()) {
if (pTemp == nullptr) {
getline(fin, temp, '\n');
if (temp == "") break;
pHeadSchoolYear = pTemp = new SchoolYear;
pTemp->pNext = nullptr;
pTemp->schoolYearName = temp;
schoolYearSize++;
}
else {
getline(fin, temp, '\n');
if (temp == "") break;
pTemp->pNext = new SchoolYear;
pTemp = pTemp->pNext;
pTemp->schoolYearName = temp;
pTemp->pNext = nullptr;
schoolYearSize++;
}
}
fin.close();
}
void loadListOfClass(Class*& pHeadClass, int& sizeOfListClass, char* path) {
Class* pT = nullptr;
while (pHeadClass != nullptr) {
pT = pHeadClass;
pHeadClass = pHeadClass->pNext;
delete pT;
}
pHeadClass = nullptr;
sizeOfListClass = 0;
ifstream fin;
fin.open(path);
if (fin.is_open() == false) {
cout << "\nfirst time open file";
fin.close();
ofstream fout;
fout.open(path);
fout.close();
fin.open(path);
}
Class* pTemp = pHeadClass;
string temp;
while (!fin.eof()) {
if (pTemp == nullptr) {
getline(fin, temp, '\n');
if (temp == "") break;
pHeadClass = pTemp = new Class;
pTemp->pNext = nullptr;
pTemp->className = temp;
sizeOfListClass++;
}
else {
getline(fin, temp, '\n');
if (temp == "") break;
pTemp->pNext = new Class;
pTemp = pTemp->pNext;
pTemp->className = temp;
pTemp->pNext = nullptr;
sizeOfListClass++;
}
}
fin.close();
}
void loadListOfSemester(Semester*& pHeadSemester, int& sizeOfListSemester, char* path) {
Semester* pT = nullptr;
while (pHeadSemester != nullptr) {
pT = pHeadSemester;
pHeadSemester = pHeadSemester->pNext;
delete pT;
}
pHeadSemester = nullptr;
sizeOfListSemester = 0;
ifstream fin;
fin.open(path);
if (fin.is_open() == false) {
cout << "\nfirst time open file";
fin.close();
ofstream fout;
fout.open(path);
fout.close();
fin.open(path);
}
Semester* pTemp = pHeadSemester;
string temp;
while (!fin.eof()) {
getline(fin, temp, ',');
if (temp == "") break;
if (pTemp == nullptr) {
pHeadSemester = pTemp = new Semester;
pTemp->pNext = nullptr;
}
else {
pTemp->pNext = new Semester;
pTemp = pTemp->pNext;
pTemp->pNext = nullptr;
}
pTemp->pNext = nullptr;
pTemp->schoolYear = temp;
getline(fin, temp, ',');
pTemp->semesterName = temp;
getline(fin, temp, ',');
pTemp->startDate = temp;
getline(fin, temp, ',');
pTemp->endDate = temp;
getline(fin, temp, ',');
pTemp->regisStartDate = temp;
getline(fin, temp, '\n');
pTemp->regisEndDate = temp;
sizeOfListSemester++;
}
fin.close();
}
void loadListOfStudent(Student*& pHeadStudent, int& sizeOfListStudent, char* path) {
Student* pT = nullptr;
while (pHeadStudent != nullptr) {
pT = pHeadStudent;
pHeadStudent = pHeadStudent->pNext;
delete pT;
}
pHeadStudent = nullptr;
sizeOfListStudent = 0;
ifstream fin;
fin.open(path);
if (fin.is_open() == false) {
fin.close();
ofstream fout;
fout.open(path);
fout.close();
fin.open(path);
}
Student* pTemp = pHeadStudent;
string temp;
while (!fin.eof()) {
getline(fin, temp, ',');
if (temp == "") break;
if (pTemp == nullptr) {
pHeadStudent = pTemp = new Student;
pTemp->pNext = nullptr;
}
else {
pTemp->pNext = new Student;
pTemp = pTemp->pNext;
pTemp->pNext = nullptr;
}
pTemp->pNext = nullptr;
pTemp->no = temp;
getline(fin, pTemp->id, ',');
getline(fin, pTemp->firstName, ',');
getline(fin, pTemp->lastName, ',');
getline(fin, pTemp->gender, ',');
getline(fin, pTemp->dateOfBirth, ',');
getline(fin, pTemp->socialId, '\n');
sizeOfListStudent++;
}
fin.close();
}
void loadListOfCourse(Course*& pHeadCourse, int& sizeOfListCourse, char* path) {
Course* pT = nullptr;
while (pHeadCourse != nullptr) {
pT = pHeadCourse;
pHeadCourse = pHeadCourse->pNext;
delete pT;
}
pHeadCourse = nullptr;
sizeOfListCourse = 0;
ifstream fin;
fin.open(path);
if (fin.is_open() == false) {
fin.close();
ofstream fout;
fout.open(path);
fout.close();
fin.open(path);
}
Course* pTemp = pHeadCourse;
string temp;
while (!fin.eof()) {
getline(fin, temp, ',');
if (temp == "") break;
if (pTemp == nullptr) {
pHeadCourse = pTemp = new Course;
pTemp->pNext = nullptr;
}
else {
pTemp->pNext = new Course;
pTemp = pTemp->pNext;
pTemp->pNext = nullptr;
}
pTemp->pNext = nullptr;
pTemp->courseName = temp;
//getline(fin, pTemp->startDate, ',');
//getline(fin, pTemp->endDate, ',');
getline(fin, pTemp->startDate, ',');
getline(fin, pTemp->endDate, ',');
getline(fin, pTemp->teacherName, ',');
getline(fin, pTemp->numOfCredits, ',');
getline(fin, pTemp->id, ',');
getline(fin, pTemp->maxNumOfStudents, ',');
getline(fin, pTemp->day1, ',');
getline(fin, pTemp->hour1, ',');
getline(fin, pTemp->day2, ',');
getline(fin, pTemp->hour2, '\n');
sizeOfListCourse++;
}
fin.close();
}
string createDate() {
cout << "\nEnter Day :";
string day;
cin >> day;
cout << "\nEnter Month :";
string month;
cin >> month;
cout << "\nEnter Year :";
string year;
cin >> year;
return day + '/' + month + '/' + year;
}
/*void addAllStudentsToClass(Student*& pHeadStudent,int sizeOfListStudent, char path[]) {
ifstream ifs;
ifs.open(path);
if (!ifs.is_open())
{
cout << "Khong mo duoc file!";
return;
}
Student* pTemp = nullptr;
int n;
ifs >> n;
string temp;
getline(ifs, temp, '\n');
for (int i = 0; i < n; ++i) {
pTemp = new Student;
pTemp->pNext = nullptr;
getline(ifs, pTemp->no, ',');
getline(ifs, pTemp->id, ',');
getline(ifs, pTemp->firstName, ',');
getline(ifs, pTemp->lastName, ',');
getline(ifs, pTemp->gender, ',');
getline(ifs, pTemp->dateOfBirth, ',');
getline(ifs, pTemp->socialId, '\n');
if (pHeadStudent != nullptr) {
pHeadStudent->pNext = pTemp;
pHeadStudent = pTemp;
}
else {
pHeadStudent = pTail = pTemp;
}
}
}
*/
void OutputCSVFIle(Student* pHeadStudent, char path[]) {
if (pHeadStudent == nullptr) return;
ofstream ofs;
ofs.open(path);
if (!ofs.is_open()) {
cout << "Khong mo duoc file.";
return;
}
Student* pCur = pHeadStudent;
pCur = pHeadStudent;
while (pCur != nullptr) {
ofs << pCur->no << ",";
ofs << pCur->id << ",";
ofs << pCur->firstName << ",";
ofs << pCur->lastName << ",";
ofs << pCur->gender << ",";
ofs << pCur->dateOfBirth << ",";
ofs << pCur->socialId << "\n";
pCur = pCur->pNext;
}
}
void signUp(string path) {
string us, pw;
cout << "\nEnter username : ";
getline(cin,us);
cout << "\nEnter password : ";
getline(cin,pw);
ofstream write;
write.open(path, ios::app);
write << us << ',' << pw << '\n';
write.close();
}
bool login(account*& pLogin, string loginPath, string &user)
{
string username, password;
cout << "\nEnter username : ";
getline(cin, username);
user = username;
cout << "\nEnter password : ";
getline(cin, password);
account* pCur = nullptr;
string temp;
ifstream read;
read.open(loginPath);
while (!read.eof())
{
getline(read, temp, ',');
if (temp == "") break;
if (pCur == nullptr) {
pLogin = pCur = new account;
pCur->next = nullptr;
}
else {
pCur->next = new account;
pCur = pCur->next;
}
pCur->us = temp;
getline(read, pCur->pw, '\n');
}
pCur = pLogin;
while (pCur != nullptr)
{
if (pCur->us == username && pCur->pw == password)
return true;
else pCur = pCur->next;
}
read.close();
return false;
}
void createSchoolYear(SchoolYear*& pHeadSchoolYear,int & schoolYearSize, char*path) {
SchoolYear* pCur = nullptr;
int t;
cout << "\nInput the school year (E.g : 2020): ";
cin >> t;
if (pHeadSchoolYear == nullptr)
{
pHeadSchoolYear = new SchoolYear;
pHeadSchoolYear->schoolYearName = to_string(t) + "-" + to_string(t+1);
pHeadSchoolYear->pNext = nullptr;
pHeadSchoolYear->pHeadSemester = nullptr;
schoolYearSize++;
}
else {
pCur = pHeadSchoolYear;
while (pCur->pNext != nullptr)
{
pCur = pCur->pNext;
}
SchoolYear* newyear = new SchoolYear;
newyear->schoolYearName = to_string(t) + "-" + to_string(t + 1);;
newyear->pNext = nullptr;
newyear->pHeadSemester = nullptr;
pCur->pNext = newyear;
schoolYearSize++;
}
ofstream write;
write.open(path);
pCur = pHeadSchoolYear;
while (pCur != nullptr)
{
write << pCur->schoolYearName << '\n';
pCur = pCur->pNext;
}
write.close();
}
void createClass(Class* &pHeadClass, int& sizeOfClass, char* path) {
Class* pCur = nullptr;
if (pHeadClass == nullptr)
{
pHeadClass = new Class;
cout << "\nEnter name of class";
cin >> pHeadClass->className;
pHeadClass->pNext = nullptr;
pHeadClass->pHeadStudent = nullptr;
sizeOfClass++;
}
else {
pCur = pHeadClass;
while (pCur->pNext != nullptr)
{
pCur = pCur->pNext;
}
Class* newClass = new Class;
cout << "\nEnter name of class";
cin >> newClass->className;
newClass->pNext = nullptr;
newClass->pHeadStudent = nullptr;
pCur->pNext = newClass;
sizeOfClass++;
}
ofstream write;
write.open(path);
pCur = pHeadClass;
while (pCur != nullptr)
{
write << pCur->className << '\n';
pCur = pCur->pNext;
}
write.close();
}
void CreateYear(SchoolYear*& pHeadYear) {
cout << "Input the School Year to direct into year's data(Input STOP to exit): ";
string year;
getline(cin, year, '\n');
if (!pHeadYear) {
pHeadYear = new SchoolYear;
pHeadYear = new SchoolYear;
pHeadYear->schoolYearName = year;
pHeadYear->pHeadSemester = nullptr;
pHeadYear->pNext = nullptr;
}
SchoolYear* pCurYear = pHeadYear->pNext;
while (pHeadYear && year != "STOP") {
pCurYear = new SchoolYear;
pCurYear->schoolYearName = year;
pHeadYear->pHeadSemester = nullptr;
pCurYear->pNext = nullptr;
pCurYear = pCurYear->pNext;
cout << "Input the School Year to direct into year's data(Input STOP to exit): ";
getline(cin,year, '\n');
}
}
void CreateClass(Student* pHeadStudent, int& sizeOfClass, char* path) {
ofstream write;
write.open(path);
Class* pHeadClass = new Class;
Class* pCurClass = pHeadClass;
Student* pCurStudent = pHeadClass->pHeadStudent;
while (pCurClass != nullptr) {
while (pCurStudent != pCurClass->pTailStudent) {
write << pCurStudent << "\n";
pCurStudent = pCurStudent->pNext;
}
int Fin;
cout << "Move to the next Class? (1= Next, 0= Exit): ";
cin >> Fin;
if (Fin == 0) {
pCurClass->pNext = nullptr;
pCurClass = pCurClass->pNext;
}
else {
pCurClass->pNext = new Class;
pCurClass = pCurClass->pNext;
sizeOfClass++;
}
}
write.close();
}
void create1Student(Student*& pStudent) {
if (pStudent == nullptr) {
pStudent = new Student;
}
cout << "Enter student data\n";
cout << "no: ";
getline(cin, pStudent->no);
cout << "id: ";
getline(cin, pStudent->id);
cout << "firstName: ";
getline(cin, pStudent->firstName);
cout << "lastName: ";
getline(cin, pStudent->lastName);
cout << "gender: ";
getline(cin, pStudent->gender);
cout << "dateOfBirth: ";
getline(cin, pStudent->dateOfBirth);
cout << "socialId: ";
getline(cin, pStudent->socialId);
pStudent->pNext = nullptr;
}
void add1StudentToClass(Student*& pHeadStudent,int &sizeOfListStudent,char* path) {
Student* pCur = nullptr;
Student* newStudent = new Student;
newStudent->pNext = nullptr;
cout << "\ninput student data";
cout << "\nno: ";
getline(cin, newStudent->no);
cout << "\nid: ";
getline(cin, newStudent->id);
cout << "\nfirstName: ";
getline(cin, newStudent->firstName);
cout << "\nlastName: ";
getline(cin, newStudent->lastName);
cout << "\ngender: ";
getline(cin, newStudent->gender);
cout << "\ndateOfBirth: ";
getline(cin, newStudent->dateOfBirth);
cout << "\nsocialId: ";
getline(cin, newStudent->socialId);
if (pHeadStudent == nullptr)
{
pHeadStudent = newStudent;
sizeOfListStudent++;
}
else {
pCur = pHeadStudent;
while (pCur->pNext != nullptr)
{
pCur = pCur->pNext;
}
pCur->pNext = newStudent;
sizeOfListStudent++;
}
}
void deleteCourse(Course*& pHead, char* path) {
string nameOfCourse, idOfCourse;
cout << "\n\nInput name of the course that you want to delete : ";
getline(cin, nameOfCourse);
Course* courseHead = pHead;
if (courseHead == nullptr) {
cout << "There is no course for deleting";
return;
}
Course* pCur = nullptr;
if (courseHead->courseName == nameOfCourse) {
pHead = pHead->pNext;
delete courseHead;
// load again to file
ofstream write;
write.open(path);
//ofstream write;
pCur = pHead;
while (pCur != nullptr)
{
write << pCur->courseName << ",";
write << pCur->id << ",";
write << pCur->teacherName << ",";
write << pCur->numOfCredits << ",";
write << pCur->maxNumOfStudents << ",";
write << pCur->day1 << ",";
write << pCur->hour1 << ",";
write << pCur->day2 << ",";
write << pCur->hour2 << "\n";
pCur = pCur->pNext;
}
write.close();
return;
}
else {
Course* temp = pHead;
while (temp->pNext) {
if (temp->pNext->courseName == nameOfCourse) {
pCur = temp->pNext;
temp->pNext = temp->pNext->pNext;
delete pCur;
// load again to file
ofstream write;
write.open(path);
//ofstream write;
Course* pCur = pHead;
while (pCur != nullptr)
{
write << pCur->courseName << ",";
write << pCur->id << ",";
write << pCur->teacherName << ",";
write << pCur->numOfCredits << ",";
write << pCur->maxNumOfStudents << ",";
write << pCur->day1 << ",";
write << pCur->hour1 << ",";
write << pCur->day2 << ",";
write << pCur->hour2 << "\n";
pCur = pCur->pNext;
}
write.close();
return;
}
temp = temp->pNext;
}
cout << "The course that you want to delete does not exits in this semester. " << endl;
return;
}
return;
}
void addCourseToSemester(Course*& pCourse) {
cout << "Input course name : ";
getline(cin, pCourse->courseName);
cout << "Input Starting Date : ";
getline(cin, pCourse->startDate);
cout << "Input Ending Date : ";
getline(cin, pCourse->endDate);
cout << "Input course id : ";
getline(cin, pCourse->id);
cout << "Input teacher name : ";
getline(cin, pCourse->teacherName);
cout << "Input number of credits in the course : ";
getline(cin, pCourse->numOfCredits);
cout << "Input the maximun number of students : ";
getline(cin, pCourse->maxNumOfStudents);
cout << "Input day 1 : ";
getline(cin, pCourse->day1);
cout << "Input hour 1 : ";
getline(cin, pCourse->hour1);
cout << "Input day 2 : ";
getline(cin, pCourse->day2);
cout << "Input hour 2 : ";
getline(cin, pCourse->hour2);
}
void CreateCourseRegistration(Course*& pHeadCourse, int& size ,char* pathListOfCourseChar)
{
ofstream write;
write.open(pathListOfCourseChar);
if (!write.is_open()) {
cout << "cannot open";
return;
}
Course* pCur = nullptr;
if(pHeadCourse==nullptr)
{
pHeadCourse = new Course;
pHeadCourse->pNext = nullptr;
pCur = pHeadCourse;
}
else {
pCur = pHeadCourse;
while (pCur->pNext != nullptr)
{
pCur = pCur->pNext;
}
pCur->pNext = new Course;
pCur = pCur->pNext;
pCur->pNext = nullptr;
}
addCourseToSemester(pCur);
size++;
pCur = pHeadCourse;
while (pCur != nullptr)
{
write << pCur->courseName << ",";
write << pCur->startDate << ",";
write << pCur->endDate << ",";
write << pCur->teacherName << ",";
write << pCur->numOfCredits << ",";
write << pCur->id << ",";
write << pCur->maxNumOfStudents << ",";
write << pCur->day1 << ",";
write << pCur->hour1 << ",";
write << pCur->day2 << ",";
write << pCur->hour2 << "\n";
pCur = pCur->pNext;
}
write.close();
}
void CreateSemesterOfYear(SchoolYear* pTempSchoolYear, Semester*& pSemester,int &sizeOfSemester ,char* path)
{
sizeOfSemester = 0;
pSemester = nullptr;
cout << "\nEnter the number of semesters ( 2 or 3 )";
cout << "\nEnter 0 to return";
int numSemester = 1;
while (!(numSemester >= 2 && numSemester <= 3)) {
cin >> numSemester;
if (numSemester == 0) return;
}
sizeOfSemester = numSemester;
ofstream write;
write.open(path);
Semester* pCur = pSemester;
int i = 1;
while (i <= numSemester)
{
if (pSemester == nullptr)
{
pSemester = new Semester;
pSemester->pNext = nullptr;
pCur = pSemester;
}
else {
pCur->pNext = new Semester;
pCur = pCur->pNext;
pCur->pNext = nullptr;
}
//information of each Semester in year
cout << "\nSemester " << i;
pCur->semesterName = char('0' + i);
pCur->schoolYear = pTempSchoolYear->schoolYearName;
cout << "\nSchool Year: " << pCur->schoolYear; // schoolYear of semester has been update before( choose schoolYear -> choose semester )
cout << "\nThe Date of Starting semester: ";
pCur->startDate = createDate();
cout << "\nThe Date of Ending semester: ";
pCur->endDate = createDate();
cout << "\nThe Date of Starting Registration: ";
pCur->regisStartDate = createDate();
cout << "\nThe Date of Ending Registration: ";
pCur->regisEndDate = createDate();
write << pCur->schoolYear << ',' << pCur->semesterName << ',' << pCur->startDate << ',' << pCur->endDate << ',' << pCur->regisStartDate << ',' << pCur->regisEndDate << '\n';
i++;
}
write.close();
}
void UpdateCourseInformation(Course*& pHeadCourse,char* path)
{
Course* pCur = nullptr;
string courseName;
pCur = pHeadCourse;
cout << "Which Course do you want to Update? Please Input the Course's name: ";
getline(cin, courseName);
while (pCur != nullptr && pCur->courseName != courseName)
{
pCur = pCur->pNext;
}
//Look for the Course
if (pCur == nullptr)
{
cout << "This Course does not exist in this semester.";
return;
}
if (pCur->courseName == courseName)
{
cout << "What you want to change: " << endl;
cout << "1.Course Name" << endl;
cout << "2.Id" << endl;
cout << "3.Teacher's Name" << endl;
cout << "4.NumOfCredits" << endl;
cout << "5.MaxNumOfStudent" << endl;
cout << "6.Day 1" << endl;
cout << "7.Hour 1" << endl;
cout << "8.Day 2" << endl;
cout << "9.Hour 2" << endl;
int x;
cout << "Please input number here: ";
cin >> x;
string temp;
getline(cin, temp);
switch (x)
{
case 1:
{
getline(cin, pCur->courseName);
break;
}
case 2:
{
getline(cin, pCur->id);
break;
}
case 3:
{
getline(cin, pCur->teacherName);;
break;
}
case 4:
{
getline(cin, pCur->numOfCredits);
break;
}
case 5:
{
getline(cin, pCur->maxNumOfStudents);
break;
}
case 6:
{
getline(cin, pCur->day1);
break;
}
case 7:
{
getline(cin, pCur->hour1);
break;
}
case 8:
{
getline(cin, pCur->day2);
break;
}
case 9:
{
getline(cin, pCur->hour2);
break;
}
default:
break;
}
}
ofstream write;
write.open(path);
//ofstream write;
pCur = pHeadCourse;
while (pCur != nullptr)
{
write << pCur->courseName << ",";
write << pCur->id << ",";
write << pCur->teacherName << ",";
write << pCur->numOfCredits << ",";
write << pCur->maxNumOfStudents << ",";
write << pCur->day1 << ",";
write << pCur->hour1 << ",";
write << pCur->day2 << ",";
write << pCur->hour2 << "\n";
pCur = pCur->pNext;
}
write.close();
}
void viewListOfStudents(Class* pHead) {
cout << "LIST OF STUDENTS IN CLASS " << pHead->className << endl;
Student* pTemp = pHead->pHeadStudent;
cout << "No\tID\tFirst Name\tLast Name\tGender\tDate of Birth\tSocial ID\n";
while (pTemp) {
cout << pTemp->no << "\t" << pTemp->id << "\t" << pTemp->firstName << "\t" << pTemp->lastName << "\t" << pTemp->gender << "\t" << pTemp->dateOfBirth << "\t" << pTemp->socialId << endl;
pTemp = pTemp->pNext;
}
}
void viewListOfCourses(Course* pHead) {
Course* pTemp = pHead;
GoTo(1, 0);
cout << "Course ID";
GoTo(12, 0);
cout << "Course Name";
GoTo(52, 0);
cout << "Number of Credits";
GoTo(69, 0);
cout << "Teacher Name";
for (int i = 2;pTemp != nullptr; i = i + 2)
{
GoTo(1, i);
cout << pTemp->id;
GoTo(12, i);
cout << pTemp->courseName;
GoTo(52, i);
cout << pTemp->numOfCredits;
GoTo(69, i);
cout << pTemp->teacherName;
pTemp = pTemp->pNext;
}
}
void viewListOfClasses(Class* pHead) {
cout << "LIST OF CLASSES" << endl;
int i = 1;
while (pHead) {
cout << i << ". " << pHead->className << endl;
pHead = pHead->pNext;
i++;
}
}
void ViewCourse(Student* pHead) {
Course* pCur = pHead->pHeadCourse;
while (pCur != nullptr) {
cout << "LIST OF ENROLLED COURSES: " << endl;
cout << pCur->courseName << endl;
pCur = pCur->pNext;
}
}
bool enrollCourse(Course* pCourse, Student* pStudent, string &pTempCourseName) {
Course* pTemp = pCourse; // pTemp is in Semester's course
Course* pCur = pStudent->pHeadCourse; // pCur is in Student's course
int count = 0;
int size = 0;
while (pCur != nullptr) {
count++;
pCur = pCur->pNext;
}
if (count >= 5) {
cout << "You have enroll enough courses (5 course per Semester)\n";
return false;;
}
pTemp = pCourse;
viewListOfCourses(pCourse);
cout << "Enter Courses Name that you want to enroll\n";
string name;
getline(cin, name);
while (pTemp != nullptr && pTemp->courseName != name) {
pTemp = pTemp->pNext;
}
if (pTemp != nullptr) {
pCur = pStudent->pHeadCourse;
if (pCur == nullptr) {
pStudent->pHeadCourse = pCur = new Course;
*pCur = *pTemp;
cout << "Successfully enroll\n";
pTempCourseName = name;
return true;
}
else {
bool canEnroll = true;
pCur = pStudent->pHeadCourse;
while (pCur != nullptr) {
if (pTemp->courseName == pCur->courseName) {
canEnroll = false;
cout << "Course has already been enrolled.\n";
break;
}
else if (pTemp->day1 == pCur->day1) {
if (pTemp->hour1 == pCur->hour1) {
canEnroll = false;
cout << "\n" << pCur->courseName << "\tday1: " << pCur->day1 << "\thour1: " << pCur->hour1 << endl;
cout << "\n" << pTemp->courseName << "\tday1: " << pTemp->day1 << "\thour1: " << pTemp->hour1 << endl;
cout << "The 2 sessions are conflicted.";
break;
}
}
else if (pTemp->day2 == pCur->day2) {
if (pTemp->hour2 == pCur->hour2) {
canEnroll = false;
cout << "\n" << pCur->courseName << "\tday2: " << pCur->day2 << "\thour2: " << pCur->hour2 << endl;
cout << "\n" << pTemp->courseName << "\tday2: " << pTemp->day2 << "\thour2: " << pTemp->hour2 << endl;
cout << "\nThe 2 sessions are conflicted.";
break;
}
}
else {
}
pCur = pCur->pNext;
}
if (canEnroll == true) {
pCur = pStudent->pHeadCourse;
while (pCur->pNext != nullptr) {
pCur = pCur->pNext;
}
pCur->pNext = new Course;
pCur = pCur->pNext;
*pCur = *pTemp;
pCur->pNext = nullptr;
cout << "Successfully enroll\n";
pTempCourseName = name;
return true;
}
else {
cout << "cannot enroll\n";
return false;
}
}
}
else {
cout << "Cannot find the course name that you enter.\n Please enter exactly.\n";
}
return false;
}
void RemoveTheEnrolledCourse(Course* pEnrolledCourse, string defaultSemester, string defaultSchoolYear, string IdSearched)
{
viewListOfCourses(pEnrolledCourse);
cout << "\nEnter Courses Name that you want to remove\n";
string name;
getline(cin, name);
Course* pTemp = pEnrolledCourse;
while (pTemp != nullptr && pTemp->courseName != name) {
pTemp = pTemp->pNext;
}
if (pTemp != nullptr) {
// load list of student in this course
string pathListOfStudentInCourse = "Student" + pTemp->courseName + defaultSemester + defaultSchoolYear + ".csv";
int size = pathListOfStudentInCourse.size();
char* pathListOfStudentInCourseChar = new char[size + 1];
for (int i = 0; i < size; ++i) {
pathListOfStudentInCourseChar[i] = pathListOfStudentInCourse[i];
}
pathListOfStudentInCourseChar[size] = '\0';
cout << endl << pathListOfStudentInCourseChar;
ifstream fin;
fin.open(pathListOfStudentInCourseChar);
if (!fin.is_open()) {
cout << "\ncannot open file";
return;
}
int sizeOfListStudent = 0;
loadListOfStudent(pTemp->pHeadStudentEnroll, sizeOfListStudent, pathListOfStudentInCourseChar);
fin.close();
// delete student from the list and write list of student again to file
Student* pCur = nullptr;
pCur = pTemp->pHeadStudentEnroll;
Student* temp = pCur;
if (pTemp->pHeadStudentEnroll->id == IdSearched)
{
temp = pTemp->pHeadStudentEnroll;
pTemp->pHeadStudentEnroll = pTemp->pHeadStudentEnroll->pNext;
delete temp;
}
else {
while (pCur->pNext != nullptr && pCur->pNext->id != IdSearched)
{
pCur = pCur->pNext;
}
if (pCur->pNext == nullptr)
{
cout << "Student does not enroll this course";
return;
}
if (pCur->pNext->id == IdSearched)
{
temp = pCur->pNext;
pCur->pNext = pCur->pNext->pNext;
delete temp;
cout << "\nsuccesfully remove course";
}
}
pCur = pTemp->pHeadStudentEnroll;
ofstream fout;
fout.open(pathListOfStudentInCourseChar);
while (pCur != nullptr)
{
fout << pCur->no << ',';
fout << pCur->id << ',';
fout << pCur->firstName << ',';
fout << pCur->lastName << ',';
fout << pCur->gender << ',';
fout << pCur->dateOfBirth << ',';
fout << pCur->socialId << '\n';
pCur = pCur->pNext;
}
fout.close();
cout << "\nrewrite succesfully";
}
else {
cout << "Cannot find the course name that you enter.\n Please enter exactly.\n";
}
}
void ViewListOfStudentInCourse(Course* pCourse)
{
Student* pCur = nullptr;
pCur = pCourse->pHeadStudentEnroll;
if (pCourse->pHeadStudentEnroll == nullptr)
{
cout << "There is no Student in this Course";
return;
}
cout << "The List of Students in Course: ";
while (pCur != nullptr)
{
cout << pCur->id << ",";
cout << pCur->firstName << " ";
cout << pCur->lastName << endl;
pCur = pCur->pNext;
}
}
/*void ViewScoreBoard(int& numberOfStudent) {
ifstream write;
ScoreBoardOfCourse ScoreCourse;
int i = 3;
write.open("ScoreCourse.csv");
if (!write.is_open()) {
cout << "Error Loading File.";
}
else {
Draw(15, numberOfStudent, 0, 0);
GoTo(1, 1);
cout << "NO";
GoTo(8, 1);
cout << "ID";
GoTo(18, 1);
cout << "FULL NAME";
GoTo(41, 1);
cout << "MID";
GoTo(46, 1);
cout << "FIN";
GoTo(51, 1);
cout << "TOT";
GoTo(56, 1);
cout << "OTH";
while (!write.eof()) {
getline(write,ScoreCourse.no, ',');
getline(write, ScoreCourse.id, ',');
getline(write, ScoreCourse.fullname, ',');
getline(write, ScoreCourse.midtermMark, ',');
getline(write, ScoreCourse.finalMark, ',');
getline(write, ScoreCourse.totalMark, ',');
getline(write, ScoreCourse.otherMark, ',');
GoTo(2, i);
cout << ScoreCourse.no;
GoTo(5, i);
cout << ScoreCourse.id;
GoTo(16, i);
cout << ScoreCourse.fullname;
GoTo(42, i);
cout << ScoreCourse.midtermMark;
GoTo(47, i);
cout << ScoreCourse.finalMark;
GoTo(52, i);
cout << ScoreCourse.totalMark;
GoTo(57, i);
cout << ScoreCourse.otherMark;
i += 2;
}
}
int wait;
cin >> wait;
}*/
void DrawListofStudentInClass(int width, int height, int x, int y) {
// top board
GoTo(x, y);
cout << char(201);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(209);
//else cout << char(205);
switch (j)
{
case 3:
{
cout << char(209);
break;
}
case 12:
{
cout << char(209);
break;
}
case 40:
{
cout << char(209);
break;
}
case 48:
{
cout << char(209);
break;
}
case 60:
{
cout << char(209);
break;
}
default:
{
cout << char(205);
}
}
}
cout << char(187);
// mid board
cout << endl;
GoTo(x, ++y);
// final mark
//
for (int i = 2; i <= 2 * height - 1 + 2; ++i) {
if (i % 2 == 0) {
cout << char(199);
for (int j = 1; j <= 4 * width - 1; ++j) {
// if (j % 4 == 0) cout << char(197);
//else cout << char(196);
switch (j)
{
case 3:
{
cout << char(197);
break;
}
case 12:
{
cout << char(197);
break;
}
case 40:
{
cout << char(197);
break;
}
case 48:
{
cout << char(197);
break;
}
case 60:
{
cout << char(197);
break;
}
default:
{
cout << char(196);
}
}
}
cout << char(182);
cout << endl;
GoTo(x, ++y);
}
else {
cout << char(186);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(179);// ve gach xuong
//else cout << " ";
switch (j)
{
case 3:
{
cout << char(179);
break;
}
case 12:
{
cout << char(179);
break;
}
case 40:
{
cout << char(179);
break;
}
case 48:
{
cout << char(179);
break;
}
case 60:
{
cout << char(179);
break;
}
default:
{
cout << " ";
}
}
}
cout << char(186);
cout << endl;
GoTo(x, ++y);
}
}
// bot board
cout << char(200);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(207);
//else cout << char(205);
switch (j)
{
case 3:
{
cout << char(207);
break;
}
case 12:
{
cout << char(207);
break;
}
case 40:
{
cout << char(207);
break;
}
case 48:
{
cout << char(207);
break;
}
case 60:
{
cout << char(207);
break;
}
default:
{
cout << char(205);
}
}
}
cout << char(188);
}
void ListofStudentInClass(int NumberOfStudent, Student* pHead)
{
DrawListofStudentInClass(18, NumberOfStudent, 0, 0);
Student* pTemp = pHead;
for (int i = 2; i < 2 * NumberOfStudent+1; i = i + 2)
{
GoTo(1, i);
cout << pTemp->no;
GoTo(4, i);
cout << pTemp->id;
GoTo(13, i);
cout << pTemp->firstName + " " + pTemp->lastName;
GoTo(41, i);
cout << pTemp->gender;
GoTo(49, i);
cout << pTemp->dateOfBirth;
GoTo(61, i);
cout << pTemp->socialId;
pTemp = pTemp->pNext;
}
}
void ScoreBoardOfClass(int NumberOfStudent)
{
//9 học sinh thì NumberOfStudnet = 10
GoTo(1, 1);
cout << "No";
GoTo(6, 1);
cout << "ID";
GoTo(13, 1);
cout << "Full Name";
GoTo(28, 1);
cout << "Subject 1";
GoTo(39, 1);
cout << "Subject 2";
GoTo(50, 1);
cout << "Subject 3";
GoTo(61, 1);
cout << "Subject 4";
GoTo(72, 1);
cout << "Subject 5";
GoTo(83, 1);
cout << "Subject 6";
GoTo(94, 1);
cout << "GPA";
GoTo(101, 1);
cout << "Note";
int x = 1;
for (int i = 3; i < 2 * NumberOfStudent; i = i + 2)
{
GoTo(1, i);
cout << x;
GoTo(4, i);
cout << "20125121";
GoTo(13, i);
cout << "Thanh Tu";
GoTo(32, i);
cout << "8";
GoTo(43, i);
cout << "7";
GoTo(54, i);
cout << "10";
GoTo(65, i);
cout << "2";
GoTo(76, i);
cout << "5";
GoTo(87, i);
cout << "6";
GoTo(95, i);
cout << "8";
x++;
}
}
void DrawScorceBoardOfClass(int width, int height, int x, int y) {
// top board
GoTo(x, y);
cout << char(201);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(209);
//else cout << char(205);
switch (j)
{
case 3:
{
cout << char(209);
break;
}
case 12:
{
cout << char(209);
break;
}
case 27:
{
cout << char(209);
break;
}
case 38:
{
cout << char(209);
break;
}
case 49:
{
cout << char(209);
break;
}
case 60:
{
cout << char(209);
break;
}
case 71:
{
cout << char(209);
break;
}
case 82:
{cout << char(209);
break;
}
case 93:
{
cout << char(209);
break;
}
case 98:
{
cout << char(209);
break;
}
default:
{
cout << char(205);
}
}
}
cout << char(187);
// mid board
cout << endl;
GoTo(x, y + 2);
// final mark
//
for (int i = 2; i <= 2 * height - 1 + 2; ++i) {
if (i == 1) {
cout << char(186);
for (int j = 2; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(179);// ve gach xuong
//else cout << " ";
switch (j)
{
case 3:
{
cout << char(179);
break;
}
case 12:
{
cout << char(179);
break;
}
case 27:
{
cout << char(179);
break;
}
case 38:
{
cout << char(179);
break;
}
case 49:
{
cout << char(179);
break;
}
case 60:
{
cout << char(179);
break;
}
case 71:
{
cout << char(179);
break;
}
case 82:
{cout << char(179);
break;
}
case 93:
{
cout << char(179);
break;
}
case 98:
{
cout << char(179);
break;
}
default:
{
cout << " ";
}
}
}
cout << char(186);
cout << endl;
GoTo(x, ++y);
}
else {
if (i % 2 == 0) {
cout << char(199);
for (int j = 1; j <= 4 * width - 1; ++j) {
// if (j % 4 == 0) cout << char(197);
//else cout << char(196);
switch (j)
{
case 3:
{
cout << char(197);
break;
}
case 12:
{
cout << char(197);
break;
}
case 27:
{
cout << char(197);
break;
}
case 38:
{
cout << char(197);
break;
}
case 49:
{
cout << char(197);
break;
}
case 60:
{
cout << char(197);
break;
}
case 71:
{
cout << char(197);
break;
}
case 82:
{cout << char(197);
break;
}
case 93:
{
cout << char(197);
break;
}
case 98:
{
cout << char(197);
break;
}
default:
{
cout << char(196);
}
}
}
cout << char(182);
cout << endl;
GoTo(x, ++y);
}
else {
cout << char(186);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(179);// ve gach xuong
//else cout << " ";
switch (j)
{
case 3:
{
cout << char(179);
break;
}
case 12:
{
cout << char(179);
break;
}
case 27:
{
cout << char(179);
break;
}
case 38:
{
cout << char(179);
break;
}
case 49:
{
cout << char(179);
break;
}
case 60:
{
cout << char(179);
break;
}
case 71:
{
cout << char(179);
break;
}
case 82:
{cout << char(179);
break;
}
case 93:
{
cout << char(179);
break;
}
case 98:
{
cout << char(179);
break;
}
default:
{
cout << " ";
}
}
}
cout << char(186);
cout << endl;
GoTo(x, ++y);
}
}
}
// bot board
cout << char(200);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(207);
//else cout << char(205);
switch (j)
{
case 3:
{
cout << char(207);
break;
}
case 12:
{
cout << char(207);
break;
}
case 27:
{
cout << char(207);
break;
}
case 38:
{
cout << char(207);
break;
}
case 49:
{
cout << char(207);
break;
}
case 60:
{
cout << char(207);
break;
}
case 71:
{
cout << char(207);
break;
}
case 82:
{cout << char(207);
break;
}
case 93:
{
cout << char(207);
break;
}
case 98:
{
cout << char(207);
break;
}
default:
{
cout << char(205);
}
}
}
cout << char(188);
}
void DrawCourseScore(int width, int height, int x, int y) {
// top board
GoTo(x, y);
cout << char(201);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(209);
//else cout << char(205);
switch (j) {
case 4:
cout << char(209);
break;
case 15:
cout << char(209);
break;
case 40:
cout << char(209);
break;
case 45:
cout << char(209);
break;
case 50:
cout << char(209);
break;
case 55:
cout << char(209);
break;
default:
cout << char(205);
break;
}
}
cout << char(187);
// mid board
GoTo(x, ++y);
for (int i = 1; i <= 2 * height - 1; ++i) {
if (i % 2 == 0) {
cout << char(199);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(197); // gach xuong
//else cout << char(196);
switch (j) {
case 4:
cout << char(197);
break;
case 15:
cout << char(197);
break;
case 40:
cout << char(197);
break;
case 45:
cout << char(197);
break;
case 50:
cout << char(197);
break;
case 55:
cout << char(197);
break;
default:
cout << char(196);
break;
}
}
cout << char(182);
GoTo(x, ++y);
}
else { // khoang trang
cout << char(186);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(179);
//else cout << " ";
switch (j) {
case 4:
cout << char(179);
break;
case 15:
cout << char(179);
break;
case 40:
cout << char(179);
break;
case 45:
cout << char(179);
break;
case 50:
cout << char(179);
break;
case 55:
cout << char(179);
break;
default:
cout << " ";
break;
}
}
cout << char(186);
GoTo(x, ++y);
}
}
// bot board
cout << char(200);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(207);
//else cout << char(205);
switch (j) {
case 4:
cout << char(207);
break;
case 15:
cout << char(207);
break;
case 40:
cout << char(207);
break;
case 45:
cout << char(207);
break;
case 50:
cout << char(207);
break;
case 55:
cout << char(207);
break;
default:
cout << char(205);
break;
}
}
cout << char(188);
}
void ViewScoreBoard(char* path, int sizeOfScoreBoardOfCourse) {
system("cls");
ifstream write;
ScoreBoardOfCourse ScoreCourse;
int i = 3;
write.open(path);
//write.open(path);
if (write.is_open() == false) {
write.close();
ofstream fout;
fout.open(path);
fout.close();
write.open(path);
}
if (!write.is_open()) {
cout << "Error Loading File.";
}
else {
DrawCourseScore(15, sizeOfScoreBoardOfCourse, 0, 0);
GoTo(1, 1);
cout << "NO";
GoTo(8, 1);
cout << "ID";
GoTo(18, 1);
cout << "FULL NAME";
GoTo(41, 1);
cout << "MID";
GoTo(46, 1);
cout << "FIN";
GoTo(51, 1);
cout << "TOT";
GoTo(56, 1);
cout << "OTH";
while (!write.eof()) {
getline(write,ScoreCourse.no, ',');
getline(write, ScoreCourse.id, ',');
getline(write, ScoreCourse.fullname, ',');
getline(write, ScoreCourse.midtermMark, ',');
getline(write, ScoreCourse.finalMark, ',');
getline(write, ScoreCourse.totalMark, ',');
getline(write, ScoreCourse.otherMark, '\n');
GoTo(2, i);
cout << ScoreCourse.no;
GoTo(5, i);
cout << ScoreCourse.id;
GoTo(16, i);
cout << ScoreCourse.fullname;
GoTo(42, i);
cout << ScoreCourse.midtermMark;
GoTo(47, i);
cout << ScoreCourse.finalMark;
GoTo(52, i);
cout << ScoreCourse.totalMark;
GoTo(57, i);
cout << ScoreCourse.otherMark;
i += 2;
}
}
cout << "\nPress any key to return";
char key;
key = _getch();
}
void UpdateScoreInCourse(char* path, int NumbersOfStudent, string FullNameSearched)
{
ScoreBoardOfCourse Course[60];
ifstream read;
read.open(path);
for (int i = 0; i < NumbersOfStudent; i++)
{
getline(read, Course[i].no, ',');
getline(read, Course[i].id, ',');
getline(read, Course[i].fullname, ',');
getline(read, Course[i].totalMark, ',');
getline(read, Course[i].finalMark, ',');
getline(read, Course[i].midtermMark, ',');
getline(read, Course[i].otherMark, '\n');
}
// ASK Which course do they want to update???
for (int i = 0; i < NumbersOfStudent; i++)
{
if (Course[i].fullname == FullNameSearched)
{
//Show the current mark
cout << "Current Final Mark: " << Course[i].finalMark << endl;
cout << "Current Midterm Mark: " << Course[i].midtermMark << endl;
cout << "\nWhich Course do you want to update?";
cout << "\n1.Final mark";
cout << "\n2.Midterm mark";
cout << "\nType the Number Here: ";
int x;
cin >> x;
string b;
getline(cin, b);
switch (x)
{
case 1:
{
getline(cin, Course[i].finalMark);
break;
}
case 2:
{
getline(cin, Course[i].midtermMark);
break;
}
default:
break;
}
//Total course will be affected
//convert string to float
string stra(Course[i].finalMark);
float final = stoi(stra);
string strb(Course[i].midtermMark);
float midterm = stoi(strb);
float total = final * 0.6 + midterm * 0.4;
//convert float to string
Course[i].totalMark = to_string(total);
}
}
read.close();
//write back to the file
ofstream write;
write.open(path);
for (int i = 0; i < NumbersOfStudent; i++)
{
write << Course[i].no << ',';
write << Course[i].id << ',';
write << Course[i].fullname << ',';
write << Course[i].totalMark << ',';
write << Course[i].finalMark << ',';
write << Course[i].midtermMark << ',';
write << Course[i].otherMark << '\n';
}
write.close();
}
//view Score of Class
void DrawScoreOfStudentInClass(int width, int height, int x, int y) {
// top board
GoTo(x, y);
cout << char(201);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(209);
//else cout << char(205);
switch (j)
{
case 3:
{
cout << char(209);
break;
}
case 12:
{
cout << char(209);
break;
}
case 42:
{
cout << char(209);
break;
}
case 53:
{
cout << char(209);
break;
}
case 64:
{
cout << char(209);
break;
}
case 75:
{
cout << char(209);
break;
}
case 86:
{
cout << char(209);
break;
}
case 97:
{
cout << char(209);
break;
}
case 108:
{
cout << char(209);
break;
}
case 113:
{
cout << char(209);
break;
}
default:
{
cout << char(205);
}
}
}
cout << char(187);
// mid board
cout << endl;
GoTo(x, y + 2);
// final mark
//
for (int i = 2; i <= 2 * height - 1 + 2; ++i) {
if (i == 1) {
cout << char(186);
for (int j = 2; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(179);// ve gach xuong
//else cout << " ";
switch (j)
{
case 3:
{
cout << char(179);
break;
}
case 12:
{
cout << char(179);
break;
}
case 42:
{
cout << char(179);
break;
}
case 53:
{
cout << char(179);
break;
}
case 64:
{
cout << char(179);
break;
}
case 75:
{
cout << char(179);
break;
}
case 86:
{
cout << char(179);
break;
}
case 97:
{cout << char(179);
break;
}
case 108:
{
cout << char(179);
break;
}
case 113:
{
cout << char(179);
break;
}
default:
{
cout << " ";
}
}
}
cout << char(186);
cout << endl;
GoTo(x, ++y);
}
else {
if (i % 2 == 0) {
cout << char(199);
for (int j = 1; j <= 4 * width - 1; ++j) {
// if (j % 4 == 0) cout << char(197);
//else cout << char(196);
switch (j)
{
case 3:
{
cout << char(197);
break;
}
case 12:
{
cout << char(197);
break;
}
case 42:
{
cout << char(197);
break;
}
case 53:
{
cout << char(197);
break;
}
case 64:
{
cout << char(197);
break;
}
case 75:
{
cout << char(197);
break;
}
case 86:
{
cout << char(197);
break;
}
case 97:
{cout << char(197);
break;
}
case 108:
{
cout << char(197);
break;
}
case 113:
{
cout << char(197);
break;
}
default:
{
cout << char(196);
}
}
}
cout << char(182);
cout << endl;
GoTo(x, ++y);
}
else {
cout << char(186);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(179);// ve gach xuong
//else cout << " ";
switch (j)
{
case 3:
{
cout << char(179);
break;
}
case 12:
{
cout << char(179);
break;
}
case 42:
{
cout << char(179);
break;
}
case 53:
{
cout << char(179);
break;
}
case 64:
{
cout << char(179);
break;
}
case 75:
{
cout << char(179);
break;
}
case 86:
{
cout << char(179);
break;
}
case 97:
{cout << char(179);
break;
}
case 108:
{
cout << char(179);
break;
}
case 113:
{
cout << char(179);
break;
}
default:
{
cout << " ";
}
}
}
cout << char(186);
cout << endl;
GoTo(x, ++y);
}
}
}
// bot board
cout << char(200);
for (int j = 1; j <= 4 * width - 1; ++j) {
//if (j % 4 == 0) cout << char(207);
//else cout << char(205);
switch (j)
{
case 3:
{
cout << char(207);
break;
}
case 12:
{
cout << char(207);
break;
}
case 42:
{
cout << char(207);
break;
}
case 53:
{
cout << char(207);
break;
}
case 64:
{
cout << char(207);
break;
}
case 75:
{
cout << char(207);
break;
}
case 86:
{
cout << char(207);
break;
}
case 97:
{cout << char(207);
break;
}
case 108:
{
cout << char(207);
break;
}
case 113:
{
cout << char(207);
break;
}
default:
{
cout << char(205);
}
}
}
cout << char(188);
}
void ScoreBoardOfClassSemesterI(int NumberOfStudent, char* path)
{
//Semester 1
DrawScoreOfStudentInClass(28, NumberOfStudent, 0, 0);//28 cố định ko đổi
GoTo(1, 1);
cout << "No";
GoTo(6, 1);
cout << "ID";
GoTo(13, 1);
cout << "Full Name";
GoTo(43, 1);
cout << " CS161";
GoTo(54, 1);
cout << " MTH251";
GoTo(65, 1);
cout << " PH211";
GoTo(76, 1);
cout << " BAA00101";
GoTo(87, 1);
cout << " CM101";
GoTo(98, 1);
cout << "";
GoTo(109, 1);
cout << "GPA";
int x = 1;
//ExportScore(path);
}
void ScoreBoardOfClassSemesterII(int NumberOfStudent, char* path)
{
//Semester 2
DrawScoreOfStudentInClass(28, NumberOfStudent + 1, 0, 0);//28 cố định ko đổi
GoTo(1, 1);
cout << "No";
GoTo(6, 1);
cout << "ID";
GoTo(13, 1);
cout << "Full Name";
GoTo(43, 1);
cout << " CS162";
GoTo(54, 1);
cout << " MTH252";
GoTo(65, 1);
cout << " PH212";
GoTo(76, 1);
cout << " BAA00102";
GoTo(87, 1);
cout << " BAA00021";
GoTo(98, 1);
cout << " BAA00004";
GoTo(109, 1);
cout << "GPA";
ExportScore(path);
}
void ScoreBoardOfClassSemesterIII(int NumberOfStudent, char* path)
{
//semester 3
DrawScoreOfStudentInClass(28, NumberOfStudent + 1, 0, 0);//28 cố định ko đổi
GoTo(1, 1);
cout << "No";
GoTo(6, 1);
cout << "ID";
GoTo(13, 1);
cout << "Full Name";
GoTo(43, 1);
cout << " CS163";
GoTo(54, 1);
cout << " MTH261";
GoTo(65, 1);
cout << " PH213";
GoTo(76, 1);
cout << " BAA00103";
GoTo(87, 1);
cout << " BAA00022";
GoTo(98, 1);
cout << "";
GoTo(109, 1);
cout << "GPA";
ExportScore(path);
}
int ExportScore(char* path)
{
ifstream read;
read.open(path);
ScoreBoardOfClasss infor[100];
int i = 0;
while(!read.eof())
{
getline(read, infor[i].no, ',');
if (infor[i].no == "") {
break;
}
getline(read, infor[i].id, ',');
getline(read, infor[i].fullname, ',');
getline(read, infor[i].subject1, ',');
getline(read, infor[i].subject2, ',');
getline(read, infor[i].subject3, ',');
getline(read, infor[i].subject4, ',');
getline(read, infor[i].subject5, ',');
getline(read, infor[i].subject6, ',');
getline(read, infor[i].gpa, '\n');
i++;
}
int NumberOfStudent = i;
for (int i = 3, j = 0; i < 2 * NumberOfStudent; i = i + 2, j++)
{
GoTo(1, i);
cout << infor[j].no;
GoTo(4, i);
cout << infor[j].id;
GoTo(13, i);
cout << infor[j].fullname;
GoTo(47, i);
cout << infor[j].subject1;
GoTo(58, i);
cout << infor[j].subject2;
GoTo(68, i);
cout << infor[j].subject3;
GoTo(80, i);
cout << infor[j].subject4;
GoTo(91, i);
cout << infor[j].subject5;
GoTo(102, i);
cout << infor[j].subject6;
GoTo(110, i);
cout << infor[j].gpa;
}
read.close();
return NumberOfStudent;
}
| true |
ab02e9382af70154c1afc59dc2af0546b9b348de | C++ | KFlaga/HearYaHearYa | /Core/Dba.hpp | UTF-8 | 3,699 | 2.984375 | 3 | [] | no_license | #pragma once
#include "Features.hpp"
namespace eave
{
struct DtwAssociation
{
int sequence;
int point;
double cost;
};
/*
* Computes barycenter (vector mean) of all sequences elements given mapping "associations".
* For each association finds corresponding element in "sequences" and accumulates its features
* then divides resulting sum by number of associations.
*/
MFCC barycenter(const std::vector<DtwAssociation>& associations, const std::vector<FeatureVector<MFCC>>& sequences);
/*
* End condition for DBA algorithm.
* Allows to end after reaching given interation number or interclass inertia of computed average.
* Inertia is computed as sum(DTW(average, sequences[i])) / sum(sequences[i]^2).
* (todo: it is assumed that DTW is computed with squared euclidean distance, maybe parameterize it)
* todo: consider if raising inertia after update should trigger end condition (after length-reduction of average is added)
*/
struct DbaEndCondition
{
DbaEndCondition(int maxIterations_, double maxRelativeInertia_) :
maxIterations{ maxIterations_ }, maxInertia{ maxRelativeInertia_ }
{}
bool isMet() const
{
return iteration < maxIterations && inertia > maxInertia;
}
void update(const std::vector<FeatureVector<MFCC>>& sequences, const FeatureVector<MFCC>& averageSequence);
private:
int maxIterations;
double maxInertia;
int iteration = 0;
double inertia = 1.0;
};
// TODO: revise if both of those methods makes sense after testing on real data
enum class DbaAssociationsMethod
{
AddEachPoint,
AddFromPath
};
/*
* Computes average sequence for given list of sequences using DBA method (DTW barycenter averaging).
* Performs single iteration of algorithm.
*
* Idea taken from: "A global averaging method for dynamic time warping, with applications to clustering"
* by Francois Petitjean, Alain Ketterlin and Pierre Gancarski
*
*/
void computeAverageSequenceWithDBA(
const std::vector<FeatureVector<MFCC>>& sequences,
FeatureVector<MFCC>& initialAverage,
DbaAssociationsMethod method = DbaAssociationsMethod::AddEachPoint);
/*
* Computes average sequence for given list of sequences using DBA method.
* Performs interations of average updating until end condition is not met.
*/
FeatureVector<MFCC> computeAverageSequenceWithDBA(
const std::vector<FeatureVector<MFCC>>& sequences,
DbaAssociationsMethod method = DbaAssociationsMethod::AddEachPoint,
DbaEndCondition endCondition = DbaEndCondition{ 10, 0.1 });
/*
* Shortens given sequence by removing elements with lowest "fitness", i.e. lowest count of assignments weighted by their cost.
* Formula for picking element k for merging is max{k} : sum{i=[1,N]}(assoc_cost[k][i]) / N^p, where p is adjustable parameter (~1.5 - 2.5).
* When p rises, elements with lowest number associations are more preffered rather than with highest cost.
* It doesn't have strong justification, its just an educated guess.
*/
FeatureVector<MFCC> removeWorstElementInAverageSequence(
const FeatureVector<MFCC>& average,
const std::vector<std::vector<DtwAssociation>>& associations,
double p = 2.0);
/*
* Removes elements from sequence without any associations - such elements are of little use
*/
FeatureVector<MFCC> removeElementsWithoutAssociations(
const FeatureVector<MFCC>& average,
const std::vector<std::vector<DtwAssociation>>& associations);
/*
* Computess "fitness" of given average sequence element, that is:
* -sum{i=[1,N]}(assoc_cost[i]) / N^p
*/
double computeFitness(const std::vector<DtwAssociation>& associations, double p);
}
| true |
830b1924e71d8b1eb9e559053734589f329aa51c | C++ | eugenedeon/hitchhikersscatter | /code/flatland/halfSpace/AlbedoProblem/HalfspaceAlbedoProblemDelta.cpp | UTF-8 | 1,872 | 2.625 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | #include "../GENHalfSpaceFlatland.h"
class IsotropicExponentialHalfspaceDeltaAlbedo : public GENHalfspace
{
public:
double mu_t;
double m_ui;
IsotropicExponentialHalfspaceDeltaAlbedo(const double mu_t, const double ui) : mu_t( mu_t ), m_ui( ui ){}
Vector2 initPos() { return Vector2( 0.0, 0.0); }
Vector2 initDir() { return Vector2( sqrt( 1.0 - m_ui * m_ui ), m_ui ); }
double samplestep() { return -log( RandomReal() ) / mu_t; } // exponential sampling
Vector2 sampledir( const Vector2& prevDir ) // isotropic scattering
{
return isotropicDirFlatland();
}
double mfp()
{
return 1.0 / mu_t;
}
void printDescriptor()
{
std::cout << "Half-space delta albedo problem, isotropic scattering, exponential random flight. ui: " << m_ui << " mu_t = " << mu_t << std::endl;
}
};
int main( int argc, char** argv )
{
if( argc != 10 )
{
std::cout << "usage: albedo_delta c mu_t ui du dz maxz numsamples numCollisionOrders numMoments \n";
exit( -1 );
}
double c = StringToNumber<double>( std::string( argv[1] ) );
double mu_t = StringToNumber<double>( std::string( argv[2] ) );
double ui = StringToNumber<double>( std::string( argv[3] ) );
double du = StringToNumber<double>( std::string( argv[4] ) );
double dz = StringToNumber<double>( std::string( argv[5] ) );
double maxz = StringToNumber<double>( std::string( argv[6] ) );
size_t numsamples = StringToNumber<size_t>( std::string( argv[7] ) );
size_t numCollisionOrders = StringToNumber<size_t>( std::string( argv[8] ) );
size_t numMoments = StringToNumber<size_t>( std::string( argv[9] ) );
IsotropicExponentialHalfspaceDeltaAlbedo sampler( mu_t, ui );
sampler.HalfSpaceEstimatorAnalog( c, du, dz, maxz, numsamples, numCollisionOrders, numMoments );
return 0;
} | true |
e04d4022b9ee63d9f9095f5038a882d6256db28c | C++ | chosh95/STUDY | /BaekJoon/2019/토너먼트.cpp | UTF-8 | 263 | 2.578125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int N, a, b, res=1;
cin >> N >> a >> b;
while (true) {
if ((b - a == 1 && b % 2 == 0) || (a - b == 1 && a % 2 == 0)) {
cout << res;
break;
}
res++;
a = a / 2 + a % 2;
b = b / 2 + b % 2;
}
} | true |
29e4c3f3a0d40ab589ddfec05987c1279939dc25 | C++ | seyang/study | /PThreadLock/testpro2.cpp | UTF-8 | 1,670 | 2.640625 | 3 | [] | no_license | #include "testpro.h"
shm_struct_t *g_shm;
PTLockS *sharedLock;
int shm_init() {
int fd;
int ret = 0;
int shm_size;
if ((fd = shm_open("/testpro", O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IROTH)) == -1) {
if (errno == EEXIST) {
if ((fd = shm_open("/testpro", O_RDWR, 0)) == -1) {
perror("shm_open");
return -1;
}
g_shm = (shm_struct_t *)mmap(NULL, sizeof(shm_struct_t), PROT_READ|PROT_WRITE
, MAP_SHARED, fd, 0);
if (g_shm == MAP_FAILED) {
perror("mmap");
return -1;
}
sharedLock = new PTLockS(&g_shm->mtx, &g_shm->mtx_attr);
if (sharedLock->initOpen() == -1) {
return -1;
}
close(fd);
return ret;
}
}
if (fd == -1) {
fprintf(stderr, "shm_open() error\n");
return fd;
}
shm_size = sizeof(shm_struct_t);
ret = ftruncate(fd, shm_size);
if (ret == -1) {
fprintf(stderr, "ftruncate() failed. errno=%d\n", errno);
return ret;
}
g_shm = (shm_struct_t *)mmap(NULL, shm_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (g_shm == MAP_FAILED) {
fprintf(stderr, "mmap() failed\n");
return -1;
}
close(fd);
memset(&g_shm->mtx, 0x00, sizeof(pthread_mutex_t));
memset(&g_shm->mtx_attr, 0x00, sizeof(pthread_mutexattr_t));
g_shm->i = 0;
g_shm->j = 0;
sharedLock = new PTLockS(&g_shm->mtx, &g_shm->mtx_attr);
sharedLock->initForShm();
return ret;
}
int main() {
int ret = 0;
ret = shm_init();
if (ret) {
fprintf(stderr, "shm_init() failed. \n");
return ret;
}
sharedLock->lock();
for (int i=0; i<10; i++) {
g_shm->i++;
fprintf(stdout, "i = %d, j = %d\n", g_shm->i, g_shm->j);
sleep(1);
}
sharedLock->unlock();
printf("i: %d\n", g_shm->i);
return ret;
}
| true |
3fe80975ee67189763cd204d42da0d0462e53818 | C++ | rhazari/Design-Patterns | /Factory/HiringManager.h | UTF-8 | 585 | 2.65625 | 3 | [] | no_license | #pragma once
#include "Interviewer.h"
#include <memory>
class HiringManager {
public:
virtual ~HiringManager() {}
virtual std::unique_ptr<Interviewer> createInterviewer() = 0;
};
class DeveloperManager: public HiringManager {
public:
~DeveloperManager() {}
std::unique_ptr<Interviewer> createInterviewer() {
return std::make_unique<Developer>();
}
};
class CommunityManager: public HiringManager {
public:
~CommunityManager() {}
std::unique_ptr<Interviewer> createInterviewer() {
return std::make_unique<CommunityExecutive>();
}
}; | true |
45dd673de8506f7164692b5d6b2ec71f79e82a2f | C++ | GabeOchieng/ggnn.tensorflow | /program_data/PKU_raw/4/825.c | UTF-8 | 748 | 2.984375 | 3 | [] | no_license | /*
* Pointer1.5Through.cpp
* ??????????
* Created on: 2012-12-18
* Author:???
* ??????array[0][0]?????????????????????????
*
*/
int main(){
int array[101][101];
int row,col,i,j,k;
int (*p)[101]=array;//p??array????
cin>>row>>col;
for(i=0; i < row;i++)//???
for(j=0;j<col;j++)//???
{ cin>>array[i][j];//????
}
cout<<*(*(p+0)+0)<<endl;
for(i=1;i<col;i++)//i??????????,???????????
for(k=i,j=0;k>=0 && j<row ;k--)//k???,j???
{
cout<<*(*(p+j)+k)<<endl;//??????
if(k-1>=0)j++;//????????????
}
for(i=1;i<row;i++)//?????????i????????????
for(j=i,k=col-1;k>=0 && j<row;j++)//k???,j???
{
cout<<*(*(p+j)+k)<<endl;//??????
if(j+1<row) k--;//????????????
}
return 0;
}
| true |
be9e14fc71baf94de47707333651e0130cabd3a0 | C++ | pidddgy/competitive-programming | /codeforces/1109B.cpp | UTF-8 | 1,646 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define cerr if(false) cerr
#define watch(x) cerr << (#x) << " is " << (x) << endl;
#define endl '\n'
#define ld long double
#define int long long
#define pii pair<int, int>
#define fi first
#define se second
#define sz(a) (int)a.size()
#define all(x) (x).begin(), (x).end()
void solve() {
}
bool pal(string s) {
string rev = s;
reverse(all(s));
return rev==s;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
string s;
cin >> s;
int n = sz(s);
s = "."+s;
set<char> S;
for(int i = 1; i <= n/2; i++) {
S.emplace(s[i]);
S.emplace(s[n-i+1]);
}
watch(sz(S))
if(sz(S) == 1 or n == 1) {
cout << "Impossible" << endl;
return 0;
}
int ans = 2;
string add = "";
for(int i = 1; i <= n-1; i++) {
int rem = n-i;
add += s[i];
string cur = s.substr(i+1, rem);
cerr << add << " " << cur << endl;
cur += add;
if(pal(cur) and cur != s.substr(1, n)) {
cerr << "split at " << i << " for " << cur << endl;
ans = 1;
}
}
cout << ans << endl;
}
/*
all same letter (not including middle if odd) = impossible
if length is even answer = 1
aaabcbaaa
baaacaaab
we can cut at first different letter for cut = 2
abba abba
acbca
aabaa
abcba
abcbaabcba
*/
// Did you read the bounds?
// Did you make typos?
// Are there edge cases (N=1?)
// Are array sizes proper?
// Integer overflow?
// DS reset properly between test cases?
// Is using long longs causing TLE?
// Are you using floating points?
| true |
aaed2d799b6abc58005e91f27950df232b3df3bf | C++ | yongjianmu/leetcode | /second/41_First_Missing_Positive/main.cpp | UTF-8 | 1,082 | 3.75 | 4 | [] | no_license | #include "../include/header.h"
/*
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
*/
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int size = nums.size();
if(0 == size)
{
return 1;
}
for(int i = 0; i < size; )
{
if(nums[i] > 0 && nums[i] <= size && nums[nums[i] - 1] != nums[i])
{
swap(nums[nums[i] - 1], nums[i]);
}
else
{
++i;
}
}
for(int i = 0; i < size; ++i)
{
if(nums[i] != i + 1)
{
return i + 1;
}
}
return size + 1;
}
};
int main() {
vector<int> input = {3, 4, -1, 1};
Solution sol;
int result = sol.firstMissingPositive(input);
cout << "#### Result ####" << endl;
cout << result << endl;
return 0;
} | true |
ef3d172510b66ecc8bdcd3aeffeefeb5397b97b1 | C++ | ddolzhenko/traning_algos_2016_06 | /Rzerra/search.cpp | UTF-8 | 6,348 | 2.90625 | 3 | [] | no_license | //#include <iostream>
//#include <iomanip>
//#include <cassert>
//#include <string>
//#include <vector>
//
//using namespace std;
//
//int search1(int iArray[], int iSize, int iKey)
//{
//// assert(iArray!=0);
// assert(iSize>=0);
//
// for(int i=0; i<iSize; ++i)
// {
// if(iArray[i]==iKey)
// return i;
// }
// return -1;
//}
//
//int search2(int iArray[], int iSize, int iKey)
//{
//// assert(iArray!=0);
// assert(iSize>=0);
//
// int i=0;
// while(i<iSize)
// {
// if(iArray[i]==iKey)
// return i;
// ++i;
// }
// return -1;
//}
//
//int search3(int iArray[], int iSize, int iKey)
//{
//// assert(iArray!=0);
// assert(iSize>=0);
//
// iArray[iSize] = iKey;
// int i=0;
// while(iArray[i]!=iKey)
// ++i;
// if(i!=iSize)
// return i;
// return -1;
//}
//
//int search4(int iArray[], int iSize, int iKey)
//{
//// assert(iArray!=0);
// assert(iSize>=0);
//
// if(iSize==0)
// return -1;
//
// int end = iSize-1;
// int last = iArray[end];
// if(last==iKey)
// return end;
//
// int i=0;
// while(iArray[i]!=iKey)
// ++i;
// iArray[end] = last;
// if(i!=iSize)
// return i;
// return -1;
//}
//
//template<class TExpect, class TFunc, class, class TParam1, class TParam2>
//void test(TExpect expected, TFunc f, TParam1 param1, TParam2 param2)
//{
// auto result = f(param1, param2);
//
// cout<<"testing "<<expected<<" == "<<"f("<<param1<<", "<<param2<<")\n";
// cout<<string(80, '-')<<(expected!=result? "fail":"ok")<<endl;
//}
//
//std::ostream& operator<<(std::ostream& o, const std::vector<int>& data)
//{
// o<<"{";
// for(const auto& x: data) o<<x<<", ";
// return o<<"}";
//}
//
//template<class TFunc>
//void test_search_general(TFunc base_search_func)
//{
// auto search_func = [=](std::vector<int> v, int key)
// {
// if(v.size()==0)
// return base_search_func(0, v.size(), key);
// return base_search_func(&v[0], v.size(), key);
// };
// int key = 42;
// typedef std::vector<int> fector;
//
// // key not in array
// // degenerated
// test(-1, search_func, fector(), key);
//
// // trivial
// test(-1, search_func, fector({1}), key);
//
// // second trivial
// test(-1, search_func, fector({1, 1}), key);
// test(-1, search_func, fector({1, 2}), key);
// test(-1, search_func, fector({2, 1}), key);
//
// // usual
// test(-1, search_func, fector({1, 1, 4, 56, 23}), key);
// test(-1, search_func, fector({1, 2, 43, 20, 5, 7}), key);
//
// // key in array
// // trivial
// test(0, search_func, fector({key}), key);
//
// // second trivial
// test(1, search_func, fector({1, key}), key);
// test(0, search_func, fector({key, 2}), key);
// test(0, search_func, fector({key, key}), key);
//
// // usual
// test(0, search_func, fector({key, 1, 4, 56, 23}), key);
// test(5, search_func, fector({1, 2, 43, 20, key}), key);
// test(3, search_func, fector({8, 1, key, 56, key}), key);
//}
//
//void test_search()
//{
// test_search_general(search1);
//// test_search_general(search2);
//// test_search_general(search3);
//// test_search_general(search4);
//}
//
//void main()
//{
// test_search();
//}
#include <iostream>
#include <iomanip>
#include <cassert>
#include <string>
#include <vector>
using namespace std;
template<class TExpect, class TFunc, class TParam1, class TParam2>
void test(TExpect expected, TFunc f, TParam1 param1, TParam2 param2)
{
auto result = f(param1, param2);
cout << "testing: " << expected << " == " << "f("
<< param1 << ", " << param2 <<") = " << result << endl;
cout //<< string(80, '-')
<< (expected != result ? "fail" : "ok") << endl;
}
ostream& operator<<(ostream& o, const std::vector<int>& data)
{
o << "{";
for(const auto& x : data)
o << x << ", ";
return o << "}";
}
void sort_selection(int A[], std::size_t size)
{
for (std::size_t idx_i = 0; idx_i < size - 1; idx_i++)
{
std::size_t min_idx = idx_i;
for (std::size_t idx_j = idx_i + 1; idx_j < size; idx_j++)
{
if (A[idx_j] < A[min_idx])
{
min_idx = idx_j;
}
}
if (min_idx != idx_i)
{
std::swap(A[idx_i], A[min_idx]);
}
}
}
int search_linear(int A[], int size, int key)
{
// assert(A != 0);
assert(size >= 0);
for(auto i = 0; i < size; ++i)
{
if(A[i] == key)
return i;
}
return -1;
}
int search_binary_r(int A[], int size, int key)
{
// assert(size>=0);
// assert(std::is_sorted(A, A+size));
// [A, (a+size))
if(size==0)
return -1;
int m = size<<1;
if(key<A[m])
{
return search_binary_r(A, m, key);
}
else if(key>A[m])
{
return m+1+search_binary_r(A+m+1, size-m-1, key);
}
else
{
return m;
}
}
int search_binary(int A[], int size, int key)
{
// assert(size>=0);
// assert(std::is_sorted(A, A+size));
// [0, m)[m]{m+1, size)
while(size!=0)
{
int m = size<<1;
if(key<A[m])
size = m;
else if(key>A[m])
{
A = A+m+1;
size -= m+1;
}
else
return m;
}
return -1;
}
template<class TFunc>
void test_search_general(TFunc base_search_func)
{
auto search_func = [=](std::vector<int> v, int key) {
if(v.size() == 0)
return base_search_func(0, v.size(), key);
return base_search_func(&v[0], v.size(), key);
};
int key = 42;
// key not in array
typedef std::vector<int> Vec;
// degenerated:
test(-1, search_func, Vec(), key);
// trivial
test(-1, search_func, Vec({1}), key);
// trivial2nd
test(-1, search_func, Vec({1, 1}), key);
test(-1, search_func, Vec({1, 2}), key);
test(-1, search_func, Vec({2, 1}), key);
// normal
test(-1, search_func, Vec({1, 1, 4, 56, 23}), key);
test(-1, search_func, Vec({1, 1, 4, 56, 23, -100}), key);
// key in array
// trivial
test(0, search_func, Vec({key}), key);
// trivial2nd
test(1, search_func, Vec({1, key}), key);
test(0, search_func, Vec({key, 2}), key);
test(0, search_func, Vec({key, key}), key);
// normal
test(0, search_func, Vec({key, 1, 1, 4, 56, 23}), key);
test(5, search_func, Vec({1, 1, 4, 56, 23, key}), key);
test(3, search_func, Vec({1, 1, 4, key, 56, 23}), key);
}
void test_search()
{
// test_search_general(search_linear);
test_search_general(search_binary);
}
int main()
{
test_search();
return 0;
}
| true |
9ba5eb3cc43a65c25c58d63a214765d1caac7f3f | C++ | eduardorasgado/CppZerotoAdvance2018 | /intermediate/funciones/structsToFunctions.cpp | UTF-8 | 609 | 3.421875 | 3 | [] | permissive | #include <iostream>
using namespace std;
// ESTRUCTURAS
struct Persona
{
char nombre[60];
int edad;
}
// instancias de la esturctura
persona1
;
// PROTOTIPOS DE FUNCION
void dataRequest();
// enviandole datos tipo estructura al prototipo
void showData(Persona);
int main(int argc, char** argv)
{
dataRequest();
showData(persona1);
return 0;
}
void dataRequest()
{
cout << "Inserte su nombre: ", cin.getline(persona1.nombre, 60, '\n');
cout << "Iserte su edad: ", cin >> persona1.edad;
}
void showData(Persona p)
{
cout << "Nombre: " << p.nombre << endl;
cout << "Edad: " << p.edad << endl;
}
| true |
802e03a7b94e3f1c0f803f63de9f202d734ff9bb | C++ | li1867/Zork-Game | /Creature.hpp | UTF-8 | 1,263 | 2.6875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <string>
#include <string.h>
#include <list>
#include "rapidxml_utils.hpp"
#include "rapidxml.hpp"
#include "rapidxml_print.hpp"
#include "Trigger.hpp"
#include "Attack.hpp"
using namespace std;
using namespace rapidxml;
class Creature{ //: public Object{
public:
string name;
vector<string> vulnerability;
string status;
string description;
vector<Trigger*> trigger;
bool hasTrigger = false;
Attack * attack = NULL;
//Trigger * trigger = NULL;
Creature(xml_node<> *node)//:Object(node)
{
cpy_creature(node);
}
void cpy_creature(xml_node<> *node)
{
for(xml_node<> *current = node -> first_node(); current != NULL; current = current -> next_sibling())
{
if(strcmp(current -> name(), "name") == 0)
{
name = current -> value();
}
if(strcmp(current -> name(), "vulnerability") == 0)
{
vulnerability.push_back(current -> value());
}
if(strcmp(current -> name(), "attack") == 0)
{
attack = new Attack(current);
}
if(strcmp(current -> name(), "trigger") == 0)
{
trigger.push_back(new Trigger(current));
hasTrigger = true;
//trigger = new Trigger(current);
}
}
}
private:
};
| true |
038c80b628a345689a9eac17585a9dd50ba1c42f | C++ | ExpLife0011/adblockplusie | /common/src/Registry.cpp | UTF-8 | 2,884 | 2.6875 | 3 | [] | no_license | /*
* This file is part of Adblock Plus <https://adblockplus.org/>,
* Copyright (C) 2006-present eyeo GmbH
*
* Adblock Plus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* Adblock Plus 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 Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Registry.h"
#include <memory>
using namespace AdblockPlus;
RegistryKey::RegistryKey(HKEY parent, const std::wstring& key_name)
{
if (key_name.empty())
{
throw std::runtime_error("key_name may not be empty");
}
HRESULT hr = RegOpenKeyExW(parent, key_name.c_str(), 0, KEY_QUERY_VALUE, &key);
if (hr != ERROR_SUCCESS || !key)
{
throw std::runtime_error("Failure in RegOpenKeyExW");
}
}
RegistryKey::~RegistryKey()
{
RegCloseKey(key);
}
std::wstring RegistryKey::value_wstring(const std::wstring& name) const
{
/*
* Step one is to determine the presence of the value, along with its type and byte size.
*/
DWORD type;
DWORD size = 0;
HRESULT hr = ::RegQueryValueExW(static_cast<HKEY>(key), name.c_str(), 0, &type, 0, &size);
if (hr != ERROR_SUCCESS)
{
throw std::runtime_error("Failure in RegQueryValueEx to query name");
}
if (type != REG_SZ)
{
throw std::runtime_error("Value is not string type");
}
/*
* Step two is to allocate a buffer for the string and query for its value.
* Note that 'size' is the size in bytes, which we need for the system call,
* but that 'psize' is the size in words, which we need to manipulate the wchar_t array 'p'.
*/
size_t psize = (size + 1)/2;
// Round the byte size up to the nearest multiple of two.
size = 2 * psize;
// We need to allocate a temporary buffer to receive the value, because there's no interface to write directly into the buffer of std::basic_string.
std::unique_ptr<wchar_t[]> p(new wchar_t[psize]);
hr = RegQueryValueExW(key, name.c_str(), 0, 0, reinterpret_cast<BYTE*>(p.get()), &size);
if (hr != ERROR_SUCCESS)
{
throw std::runtime_error("Failure in RegQueryValueExW to retrieve value");
}
/*
* Step three is to construct a return string.
*
* There's the possibility of an extra terminating null character in the return value of the query.
* If so, we have to decrement the length of the return value to eliminate it.
* If it persists, it will interfere with later string operations such as concatenation.
*/
if (p[psize - 1] == L'\0')
{
--psize;
}
return std::wstring(p.get(), psize);
}
| true |
72add1ecb502ed5478645837773506f295406ea1 | C++ | VizlabRutgers/TTPN | /nettable.cpp | UTF-8 | 2,539 | 2.578125 | 3 | [] | no_license | #include <QtGui>
#include <QApplication>
#include <QTableWidget>
#include <QHBoxLayout>
#include "nettable.h"
#include <QHeaderView>
NetTable::NetTable(QWidget *parent)
: QTableWidget(parent)
{
setWindowTitle("QTableWidget");
setRowCount(6);
setColumnCount(2);
//verticalHeader()->resizeSection(i, rowHeight);
verticalHeader()->resizeSection(0,18);
verticalHeader()->resizeSection(1,18);
verticalHeader()->resizeSection(2,18);
verticalHeader()->resizeSection(3,18);
verticalHeader()->resizeSection(4,18);
verticalHeader()->resizeSection(5,18);
setItem(0,0, new QTableWidgetItem("# of Initial Place"));
setItem(1,0, new QTableWidgetItem("# of Final Place"));
setItem(2,0, new QTableWidgetItem("# of Ordinary Place"));
setItem(3,0, new QTableWidgetItem("# of Transition"));
setItem(4,0, new QTableWidgetItem("# of Arc"));
setItem(5,0, new QTableWidgetItem("# of All Place"));
n1=0;
n2=0;
n3=0;
n4=0;
n5=0;
n=0;
horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}
void NetTable::setItemNumber1(int num1)
{
n1 = num1;
QTableWidgetItem *item = new QTableWidgetItem(QString::number(n1));
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
setItem(0, 1, item);
}
void NetTable::setItemNumber2(int num2)
{
n2 = num2;
QTableWidgetItem *item = new QTableWidgetItem(QString::number(n2));
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
setItem(1, 1, item);
}
void NetTable::setItemNumber3(int num3)
{
n3 = num3;
QTableWidgetItem *item = new QTableWidgetItem(QString::number(n3));
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
setItem(2, 1, item);
}
void NetTable::setItemNumber4(int num4)
{
n4 = num4;
QTableWidgetItem *item = new QTableWidgetItem(QString::number(n4));
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
setItem(3, 1, item);
}
void NetTable::setItemNumber5(int num5)
{
n5 = num5;
QTableWidgetItem *item = new QTableWidgetItem(QString::number(n5));
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
setItem(4, 1, item);
}
void NetTable::setItemNumber6(int num)
{
n = num;
QTableWidgetItem *item = new QTableWidgetItem(QString::number(n));
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
setItem(5, 1, item);
}
| true |
ccc10d0cd88112c74e6246f2cb03c87f328f4dbe | C++ | ccpang96/leetcode | /leetcode/图/欧拉路径/1.重新安排行程-机场排序问题.cpp | GB18030 | 1,016 | 2.828125 | 3 | [] | no_license | /************************************************************************/
/*@File Name : 1.°г-.cpp
/*@Created Date : 2020/6/16 14:52
/*@Author : ccpang(ccpang96@163.com)
/*@blog : www.cnblogs.com/ccpang
/*@Description : ıͼŷ·
Ͻ˵һͨͼ G ŷ·ָһ㣬ߵķԲظرͼеıߡ*/
/************************************************************************/
//㣬һֵ˳Сŷ·
//ʹ̰IJԣȷֵСĽڵATL
#include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_map>
#include<string>
#include<sstream>
#include<queue>
#include<stack>
#include<map>
using namespace std;
class Solution {
public:
typedef unordered_map<string, map<string, int>>adjacent;
vector<string>min_path;
};
| true |
8655ee64b4e455b552f71afd8f4af043df9822e4 | C++ | jaredbebb/CS5101_PegJump | /testPegJump/PegView.cpp | UTF-8 | 972 | 2.75 | 3 | [] | no_license | //
// PegView.cpp
// testPegJump
//
// Created by Jared Bebb on 3/10/17.
// Copyright © 2017 Jared Bebb LLC. All rights reserved.
//
#include "PegView.hpp"
#include <string>
std::string PegView::viewMessage(std::string pickMessage)
{
std::string message;
if (pickMessage == "home") {
message = "Home Screen";
}
if (pickMessage == "whatGame") {
message = "What game would you like to play?";
}
if (pickMessage == "welcome") {
message = "Hi, welcome to PegJump";
}
if (pickMessage == "whatAction") {
message = "What do you want to do";
}
if (pickMessage == "whichPeg") {
message = "Which Peg?";
}
if (pickMessage == "helpScreen") {
message = "To start game, type start game\n to find help, type help. If you want to exit, type exit. To get the score, type score.";
}
if (pickMessage == "end") {
message = "Thanks for playing";
}
return message;
}
| true |
fb730fcc57f3be815020a1de8c58978c8521f32b | C++ | DoctorLai/ACM | /leetcode/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171.cpp | UTF-8 | 1,130 | 3.3125 | 3 | [] | no_license | // https://helloacm.com/how-to-remove-zero-sum-consecutive-nodes-from-linked-list-using-prefix-sum/
// https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/
// MEDIUM, LINKED LIST, PREFIX SUM
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeZeroSumSublists(ListNode* head) {
ListNode* newHead = head;
unordered_map<int, ListNode*> prefix;
int sum = 0;
bool flag = false;
while (head) {
sum += head->val;
if (sum == 0) {
newHead = head->next;
flag = true;
//break;
} else if (prefix.find(sum) == prefix.end()) {
prefix[sum] = head;
} else {
prefix[sum]->next = head->next;
flag = true;
}
head = head->next;
}
if (flag) {
return removeZeroSumSublists(newHead);
}
return newHead;
}
};
| true |
48a6e53ec0dad7f96e57ed6193d52cf31eaba1f2 | C++ | alexbaboune/project | /main.cpp | ISO-8859-1 | 1,098 | 3 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <fstream>
#include "sorting.h"
#include <vector>
using namespace std;
int main()
{
//ifstream fichier("test.txt", ios::in); // on ouvre
//if (fichier)
//{
// int k; // notre variable o sera stock le caractre
//fichier.get(k); // on lit un caractre et on le stocke dans caractere
//cout << k; // on l'affiche
//int userSize;
//cout << "put the size of the imput sequence : " << endl;
//cin >> userSize;
double T[5] = { 4, 2, 6, 1, 9 };
cout << "avant le tri : " << endl;
for (int i = 0; i < 5; i++)
{
cout << T[i]<< endl;
}
//tri_insertion(T, 5);
//cout << "apres le tri : " << endl;
//for (int i = 0; i < 5; i++)
//{
// cout << T[i] << endl;
//}
quickSort(T, 0, 4);
cout << "apres le tri rapide : " << endl;
for (int i = 0; i < 5; i++)
{
cout << T[i] << endl;
}
//fichier.close();
//}
// else
// cerr << "Impossible d'ouvrir le fichier !" << endl;
return 0;
} | true |
81f6bf69cc5027ee0c83f46c884c8a70a15745ea | C++ | IshidaTakuto/Works | /吉田学園情報ビジネス専門学校_石田琢人/ゲーム/04_3Dシューティング_個人/開発環境/scene3DBill.cpp | SHIFT_JIS | 12,545 | 2.671875 | 3 | [] | no_license | //=============================================================================
//
// 3Dr{[hIuWFNg [scene3DBill.h]
// Author : Ishida Takuto
//
//=============================================================================
#include "scene3DBill.h"
#include "renderer.h"
#include "manager.h"
#include "input.h"
#include "game.h"
#include "player.h"
//==================================
// }N`
//==================================
#define SIZE_X (50.0f) // |S̉̒
#define SIZE_Y (50.0f) // |S̏c̒
//==================================
// ÓIoϐ錾
//==================================
//=========================================
// eNX`蓖Ă
//=========================================
void CScene3DBill::BindTexture(LPDIRECT3DTEXTURE9 pTexture)
{
m_pTexture = pTexture;
}
//=========================================
// RXgN^
//=========================================
CScene3DBill::CScene3DBill(int nPriority) : CScene(nPriority)
{
m_pTexture = NULL; // eNX`ւ̃|C^
m_pVtxBuff = NULL; // _obt@ւ̃|C^
m_pos = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // |S̈ʒu
m_fLengthX = 0.0f; // X̑傫
m_fLengthY = 0.0f; // Z̑傫
}
//=========================================
// fXgN^
//=========================================
CScene3DBill::~CScene3DBill()
{
}
//=========================================
// |S̏
//=========================================
HRESULT CScene3DBill::Init(void)
{
CRenderer *pRenderer = CManager::GetRenderer();
LPDIRECT3DDEVICE9 pDevice;
pDevice = pRenderer->GetDevice();
// _obt@̐
pDevice->CreateVertexBuffer(sizeof(VERTEX_3D) * 4,
D3DUSAGE_WRITEONLY,
FVF_VERTEX_3D,
D3DPOOL_MANAGED,
&m_pVtxBuff,
NULL);
// _ݒ
VERTEX_3D *pVtx; // _̃|C^
// _obt@bNA_f[^ւ̃|C^擾
m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0);
pVtx[0].pos = D3DXVECTOR3(SIZE_X, SIZE_Y, 0.0f);
pVtx[1].pos = D3DXVECTOR3(SIZE_X, SIZE_Y, 0.0f);
pVtx[2].pos = D3DXVECTOR3(SIZE_X, SIZE_Y, 0.0f);
pVtx[3].pos = D3DXVECTOR3(SIZE_X, SIZE_Y, 0.0f);
// @J̈ʒuŕς
CPlayer *pPlayer = CGame::GetPlayer(); // vC[̏擾
if (NULL != pPlayer)
{// vC[̏̎擾
CPlayer::TYPE type = pPlayer->GetType();
if (type == CPlayer::TYPE_AIRCRAFT || type == CPlayer::TYPE_TANK)
{// 퓬@
pVtx[0].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
pVtx[1].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
pVtx[2].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
pVtx[3].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
}
else if (type == CPlayer::TYPE_SHIP)
{//
pVtx[0].nor = D3DXVECTOR3(0.0f, 0.0f, -1.0f);
pVtx[1].nor = D3DXVECTOR3(0.0f, 0.0f, -1.0f);
pVtx[2].nor = D3DXVECTOR3(0.0f, 0.0f, -1.0f);
pVtx[3].nor = D3DXVECTOR3(0.0f, 0.0f, -1.0f);
}
}
// _J[
pVtx[0].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
pVtx[1].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
pVtx[2].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
pVtx[3].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
// eNX`W
pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f);
pVtx[1].tex = D3DXVECTOR2(1.0f, 0.0f);
pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f);
pVtx[3].tex = D3DXVECTOR2(1.0f, 1.0f);
// _obt@AbN
m_pVtxBuff->Unlock();
return S_OK;
}
//=========================================
// |S̏I
//=========================================
void CScene3DBill::Uninit(void)
{
// _obt@̔j
if (NULL != m_pVtxBuff)
{
m_pVtxBuff->Release();
m_pVtxBuff = NULL;
}
Release();
}
//=========================================
// |S̍XV
//=========================================
void CScene3DBill::Update(void)
{
}
//=========================================
// |S̕`揈
//=========================================
void CScene3DBill::Draw(void)
{
// foCX̎擾
CRenderer *pRenderer = CManager::GetRenderer();
LPDIRECT3DDEVICE9 pDevice;
pDevice = pRenderer->GetDevice();
// eXg̐ݒ
pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
pDevice->SetRenderState(D3DRS_ALPHAREF, 0);
pDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
//tHOgp
pDevice->SetRenderState(D3DRS_FOGENABLE, FALSE);
D3DXMATRIX mtxTrans, mtxView; // [h}gbNX̕ۑp
// [h}gbNX̏
D3DXMatrixIdentity(&m_mtxWorld);
// ]f
pDevice->GetTransform(D3DTS_VIEW, &mtxView);
m_mtxWorld._11 = mtxView._11;
m_mtxWorld._12 = mtxView._21;
m_mtxWorld._13 = mtxView._31;
m_mtxWorld._21 = mtxView._12;
m_mtxWorld._22 = mtxView._22;
m_mtxWorld._23 = mtxView._32;
m_mtxWorld._31 = mtxView._13;
m_mtxWorld._32 = mtxView._23;
m_mtxWorld._33 = mtxView._33;
// ʒuf
D3DXMatrixTranslation(&mtxTrans, m_pos.x, m_pos.y, m_pos.z);
D3DXMatrixMultiply(&m_mtxWorld, &m_mtxWorld, &mtxTrans);
// [h}gbNX̐ݒ
pDevice->SetTransform(D3DTS_WORLD, &m_mtxWorld);
// _obt@f[^Xg[ɐݒ
pDevice->SetStreamSource(0, m_pVtxBuff, 0, sizeof(VERTEX_3D));
// _tH[}bg̐ݒ
pDevice->SetFVF(FVF_VERTEX_3D);
// eNX`̐ݒ
pDevice->SetTexture(0, m_pTexture);
// `
pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
//tHOgp
pDevice->SetRenderState(D3DRS_FOGENABLE, TRUE);
// eXg̐ݒ߂
pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
pDevice->SetRenderState(D3DRS_ALPHAREF, 0);
pDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
}
//=========================================================================================================================
// 蔻
//=========================================================================================================================
bool CScene3DBill::Collision(D3DXVECTOR3 pos, float fRange)
{
bool bHit = false;
if (this != NULL)
{
float fLengthOneself;
float fRange0 = fRange;
fLengthOneself = powf(fRange0 * 3, 2); // XYZ͈̔
float fLengthX = pos.x - m_mtxWorld._41; // X̍
float fLengthY = pos.y - m_mtxWorld._42; // Y̍
float fLengthZ = pos.z - m_mtxWorld._43; // Z̍
float fLengthTotal = powf(fLengthX, 2) + powf(fLengthY, 2) + powf(fLengthZ, 2); // XYZ̓̍v
if (fLengthOneself >= fLengthTotal)
{// Ǝ̔
if (false == bHit)
{// Lɂ
bHit = true;
}
}
}
return bHit;
}
//=========================================================================================================================
// 蔻(XY)
//=========================================================================================================================
bool CScene3DBill::CollisionXY(D3DXVECTOR3 pos, float fRange)
{
bool bHit = false;
if (this != NULL)
{
float fLengthOneself;
float fRange0 = fRange;
fLengthOneself = powf(fRange0 * 2, 2); // XY͈̔
float fLengthX = pos.x - m_mtxWorld._41; // X̍
float fLengthY = pos.y - m_mtxWorld._42; // Y̍
float fLengthTotal = powf(fLengthX, 2) + powf(fLengthY, 2); // XY̍̓
if (fLengthOneself >= fLengthTotal)
{// Ǝ̔
if (false == bHit)
{// Lɂ
bHit = true;
}
}
}
return bHit;
}
//=========================================================================================================================
// 蔻(XZ)
//=========================================================================================================================
bool CScene3DBill::CollisionXZ(D3DXVECTOR3 pos, float fRange)
{
bool bHit = false;
if (this != NULL)
{
float fLengthOneself;
float fRange0 = fRange;
fLengthOneself = powf(fRange0 * 2, 2); // XZ͈̔
float fLengthX = pos.x - m_mtxWorld._41; // X̍
float fLengthZ = pos.z - m_mtxWorld._43; // Z̍
float fLengthTotal = powf(fLengthX, 2) + powf(fLengthZ, 2); // XZ̍̓
if (fLengthOneself >= fLengthTotal)
{// Ǝ̔
if (false == bHit)
{// Lɂ
bHit = true;
}
}
}
return bHit;
}
//=========================================================================================================================
// 蔻(Y)
//=========================================================================================================================
bool CScene3DBill::CollisionY(float posY, float fRange)
{
bool bHit = false; // Ԃl
if (this != NULL)
{
if (posY - fRange <= m_pos.y + m_fLengthY && posY + fRange >= m_pos.y - m_fLengthY)
{// Y͈͓
if (false == bHit)
{// Lɂ
bHit = true;
}
}
}
return bHit;
}
//=========================================
// ʒu̐ݒ
//=========================================
const void CScene3DBill::SetPos(D3DXVECTOR3 pos)
{
m_pos = pos;
}
//=========================================
// Ct̐ݒ
//=========================================
const int CScene3DBill::SubtractLife(int nDamage)
{
m_nLife -= nDamage; // Ct
return m_nLife; // vZ̃CtԂ
};
//=========================================
// F̐ݒ
//=========================================
const void CScene3DBill::SetColor(D3DXCOLOR col)
{
// _ݒ
VERTEX_3D *pVtx; // _̃|C^
//_obt@bNA_f[^ւ̃|C^擾
m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0);
//eNX`W
pVtx[0].col = col;
pVtx[1].col = col;
pVtx[2].col = col;
pVtx[3].col = col;
//_obt@AbN
m_pVtxBuff->Unlock();
}
//=========================================
// F̉Z
//=========================================
const void CScene3DBill::AddColor(D3DXCOLOR col)
{
// _ݒ
VERTEX_3D *pVtx; // _̃|C^
//_obt@bNA_f[^ւ̃|C^擾
m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0);
//eNX`W
pVtx[0].col += col;
pVtx[1].col += col;
pVtx[2].col += col;
pVtx[3].col += col;
//_obt@AbN
m_pVtxBuff->Unlock();
}
//=========================================
// 傫̐ݒ
//=========================================
const void CScene3DBill::SetLength(float fLength0, float fLength1)
{
m_fLengthX = fLength0;
m_fLengthY = fLength1;
// _ݒ
VERTEX_3D *pVtx; // _̃|C^
//_obt@bNA_f[^ւ̃|C^擾
m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0);
//eNX`W
pVtx[0].pos = D3DXVECTOR3(-fLength0, fLength1,0.0f);
pVtx[1].pos = D3DXVECTOR3(fLength0, fLength1, 0.0f);
pVtx[2].pos = D3DXVECTOR3(-fLength0, -fLength1, 0.0f);
pVtx[3].pos = D3DXVECTOR3(fLength0, -fLength1, 0.0f);
//_obt@AbN
m_pVtxBuff->Unlock();
}
//=========================================
// _W̐ݒ
//=========================================
const void CScene3DBill::SetVtxPos(D3DXVECTOR3 *vtxPos)
{
// _ݒ
VERTEX_3D *pVtx; // _̃|C^
//_obt@bNA_f[^ւ̃|C^擾
m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0);
//eNX`W
pVtx[0].pos = vtxPos[0];
pVtx[1].pos = vtxPos[1];
pVtx[2].pos = vtxPos[2];
pVtx[3].pos = vtxPos[3];
//_obt@AbN
m_pVtxBuff->Unlock();
}
//=========================================
// eNX`W̐ݒ
//=========================================
const void CScene3DBill::SetTexPos(D3DXVECTOR2 *tex)
{
// _ݒ
VERTEX_3D *pVtx; // _̃|C^
//_obt@bNA_f[^ւ̃|C^擾
m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0);
//eNX`W
pVtx[0].tex = tex[0];
pVtx[1].tex = tex[1];
pVtx[2].tex = tex[2];
pVtx[3].tex = tex[3];
//_obt@AbN
m_pVtxBuff->Unlock();
}
| true |
2391fa44a70e87d8f519cb192747fcaa71f8b8aa | C++ | mave89/CPlusPlus_Random | /LeetCode/Recursion/fillMatrix.cpp | UTF-8 | 2,139 | 3.515625 | 4 | [] | no_license | // https://leetcode.com/problems/flood-fill/
// Time complexity: O(n*m) where n and m are rows and cols
// Space complexity: O(n*m) where n and m are rows and cols
class Solution{
public:
void floodFillHelper(vector<vector<int>> &image, int sr, int sc, int newColor, map<pair<int, int>, bool> &visited){
// Base conditions
if(sr < 0 || sr == image.size())
return;
if(sc < 0 || sc == image[0].size())
return;
int origValue = image[sr][sc];
image[sr][sc] = newColor;
visited[make_pair(sr, sc)] = true;
// Go up
if(sr-1 >=0 && image[sr-1][sc] == origValue){
auto it = visited.find(make_pair(sr-1, sc));
if(it == visited.end()){
visited[make_pair(sr-1, sc)] = true;
floodFillHelper(image, sr-1, sc, newColor, visited);
}
}
// Go down
if(sr+1 < image.size() && image[sr+1][sc] == origValue){
auto it = visited.find(make_pair(sr+1, sc));
if(it == visited.end()){
visited[make_pair(sr+1, sc)] = true;
floodFillHelper(image, sr+1, sc, newColor, visited);
}
}
// Go left
if(sc-1 >=0 && image[sr][sc-1] == origValue){
auto it = visited.find(make_pair(sr, sc-1));
if(it == visited.end()){
visited[make_pair(sr, sc-1)] = true;
floodFillHelper(image, sr, sc-1, newColor, visited);
}
}
// Go right
if(sc+1 < image[0].size() && image[sr][sc+1] == origValue){
auto it = visited.find(make_pair(sr, sc+1));
if(it == visited.end()){
visited[make_pair(sr, sc+1)] = true;
floodFillHelper(image, sr, sc+1, newColor, visited);
}
}
}
vector<vector<int>> floodFill(vector<vector<int>> &image, int sr, int sc, int newColor){
map<pair<int, int>, bool> visited;
floodFillHelper(image, sr, sc, newColor, visited);
return image;
}
};
| true |
e239d5dae8546fbcbd897d1f390505527f854472 | C++ | gerasimos1995/Hotel-Reservations-Manager | /src/RoomA.cpp | UTF-8 | 427 | 2.78125 | 3 | [] | no_license | #include "RoomA.h"
RoomA::RoomA():Room()
{
//ctor
}
RoomA::~RoomA()
{
//dtor
}
void RoomA::setPricePerDay(int price){
pricePerDay = price;
}
int RoomA::getPricePerDay(){
return pricePerDay;
}
double RoomA::pricing(){
int i;
double price=0;
for (i=0;i<30;i++){
if(availability[i]!=NULL){
price = price + getPricePerDay();
}
}
return price;
}
| true |
f49c3120ff225efae3c337ebdf3d68f22bea636a | C++ | gabrisosa/ProgramacionGabriel | /Programacion-I/PracticasProgramacion-I/Practica1/Ejercicio1Cuadrado/main.cpp | UTF-8 | 1,278 | 3.875 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Square{
public:
Square(int _side){
setSide(_side);
}
int getSide(){
return side;
}
void setSide(int _side){
if (_side <= 0){
cout << "There must be a mistake, side of your square be less than 0 " <<
" . I'll set it to 0" << endl;
side = 0;
}else{
side = _side;
}
}
int areaOfSquare(){
int area;
area = (side * side);
return area;
}
void paintSquare(){
for (int i{1}; i < side; i++){
for (int j{0}; j < side; j++){
cout << "**";
}
cout << endl;
}
}
private:
int side;
};
int main()
{
int side;
cout << "Enter the side of your square: ";
cin >> side;
Square sick(side);
cout << "The area of your square is: " << sick.areaOfSquare() << endl;
cout << "Be hold for this masterpice: " << endl << endl;
sick.paintSquare();
cout << endl;
return 0;
}
| true |
1703fa949440c1001afd12849af7866d8fb7e387 | C++ | Wantod/GameMulti | /src/client/gui/Button.hpp | UTF-8 | 539 | 2.515625 | 3 | [] | no_license | #ifndef BUTTON_HPP
# define BUTTON_HPP
#include <iostream>
#include "../core/ResourceManager.hpp"
#include "../core/Window.hpp"
class Button
{
public:
Button(std::string &str, glm::ivec2 position, glm::ivec2 boxsize);
~Button();
void setText(std::string &str);
bool onClick();
void render();
void resize(int x, int y);
void setPosition(glm::ivec2 position, bool center = false);
private:
std::string _text;
Texture _texture;
glm::ivec2 _position;
glm::ivec2 _box;
glm::ivec2 _textpositionTMP;
};
#endif // !BUTTON_HPP
| true |
a9bfe49f332827933c0927d38d5a74dab1fc94b8 | C++ | dylandSteven/Ciclo-1-y-2 | /Vol1/problemaBus/problemaBus/Clientes.h | UTF-8 | 793 | 2.859375 | 3 | [] | no_license | #pragma once
#include"Cliente.h"
#include<iostream>
#include<string>
#include<vector>
#include"Autoh.h"
using namespace std;
typedef unsigned long us;
class Clientes {
private:
vector< Cliente*>arrcliente;
vector<Auto*>nue;
public:
Clientes() {}
void agregarCliente() {
string nombreaux;
us dniaux;
Cliente*nuevo;
cout << "Nombre: "; cin >>nombreaux;
cout << "DNI: "; cin >> dniaux;
nuevo =new Cliente(nombreaux, dniaux);
//nuevo->datosAutos();
arrcliente.push_back(nuevo);
}
void mostrarDatosCliente() {
for (int i = 0; i <arrcliente.size(); i++) {
cout<< endl;
cout<<arrcliente[i]->getNombree();
cout<<arrcliente[i]->getdni();
//cout << "Placa: "<< nue[i]->getPlaca();
//cout << "NUmero de galones: " << nue[i]->getCangalo();
}
}
}; | true |
aebd58eadb8d98f1c514666369fcc92b6112e247 | C++ | nanoo-linux/test | /cpp/field_calculation/src/Pgm.hpp | UTF-8 | 510 | 2.75 | 3 | [] | no_license | #pragma once
#include "Exception.hpp"
#include "File.hpp"
#include <vector>
using std::vector;
class PgmException: public Exception
{
public:
PgmException(const char *s, int c=-1): Exception(s, c) {}
};
class Pgm
{
public:
Pgm(const int x, const int y, const int depth=0xffff);
Pgm &setPixel(const int x, const int y, const int color);
Pgm &incPixel(const int x, const int y);
void save(File &);
private:
const int x_;
const int y_;
const int depth_;
vector <vector <int> > image_;
};
| true |
5a6ad180b75744eb85f091d4ae4c74c42f6839b3 | C++ | hXl3s/magiclib | /include/core/DeviceCPU.hpp | UTF-8 | 993 | 2.671875 | 3 | [] | no_license | #pragma once
#include <boost/align/aligned_allocator.hpp>
#include "core/Device.hpp"
#include "memory/Storage.hpp"
#include "ThreadPool.hpp"
namespace hx {
class DeviceCPU : public hx::Device {
public:
hx::DeviceType getType() const override { return hx::DeviceType::CPU; }
hx::ThreadPool<> &getDefaultThreadPool() { return _defaultThreadPool; }
template <typename T>
auto getDefaultAllocator() const {
return std::allocator<T>();
}
template <typename T>
auto getSpecialAllocator() const {
return boost::alignment::aligned_allocator<T, 32>();
}
hx::memory::Storage getStorage(std::size_t size_in_bytes, bool fast = false) const {
if (fast) {
return hx::memory::Storage(size_in_bytes, getSpecialAllocator<std::size_t>());
} else {
return hx::memory::Storage(size_in_bytes, getDefaultAllocator<std::size_t>());
}
}
private:
hx::ThreadPool<> _defaultThreadPool;
};
}// namespace hx | true |
81030eff21c122674dec7c75981c28fb1cdf93fb | C++ | dibery/UVa | /vol124/12485.cpp | UTF-8 | 341 | 2.546875 | 3 | [] | no_license | #include<cstdio>
int main()
{
for( int n, note[ 10000 ]; scanf( "%d", &n ) == 1; )
{
int sum = 0;
for( int i = 0; i < n; ++i )
scanf( "%d", note+i ), sum += note[ i ];
int ave = sum / n, diff = 0;
for( int i = 0; i < n; ++i )
if( note[ i ] < ave )
diff += ave - note[ i ];
printf( "%d\n", sum % n? -1 : diff+1 );
}
}
| true |
708f533c7620a53531316bba53be10deaabcdf47 | C++ | MartNotermans/cpse2 | /03-08-array-of-actions/ball.hpp | UTF-8 | 611 | 2.78125 | 3 | [] | no_license | #ifndef _BALL_HPP
#define _BALL_HPP
#include <SFML/Graphics.hpp>
#include "drawable.hpp"
#include "rectangle.hpp"
class ball: public drawable {
private:
float size;//radius
float diameter = size;
sf::Vector2f speed = {1.0, 1.0};
public:
ball( sf::Vector2f position, float size = 30.0 );
void draw( sf::RenderWindow & window ) const override;
void move( sf::Vector2f delta ) override;
void jump( sf::Vector2f target ) override; //float
void jump( sf::Vector2i target ) override; //int
void Bounce(rectangle target, sf::RenderWindow & window);
sf::Vector2f getSpeed(){return speed;}
};
#endif
| true |
e6f9c150c7dd1c1f56965c29cf8460529ac58b68 | C++ | stella-gao/CodeJam | /2014/qualification_round/C/0-kai-1/main.cc | UTF-8 | 5,748 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
#define MAX_SIZE 52
int r_g, c_g, m_g;
// '#' means block which is around the matrix
// '*' means mine
// 'N' means contains a number but not zero
// '0' means there is no mine in current cell neighbours
// 'c' is the last '0' at the bottom right corner
char matrix_arr[MAX_SIZE][MAX_SIZE];
void input()
{
cin >> r_g >> c_g >> m_g;
}
void dbg_print()
{
cout << "The content of matrix_arr:" << endl;
for (int row = 0; row < r_g + 2; row++) {
for (int col = 0; col < c_g + 2; col++) {
if ('#' != matrix_arr[row][col])
cout << "_ ";
else
cout << matrix_arr[row][col] << " ";
}
cout << endl;
}
cout << endl;
}
void print(const bool has_swap_row_and_col)
{
// cout << "The content of matrix_arr:" << endl;
if (has_swap_row_and_col) {
for (int col = 1; col <= c_g; col++) {
for (int row = 1; row <= r_g; row++) {
// if ('.' == matrix_arr[row][col])
// cout << "_ ";
// else
cout << matrix_arr[row][col];
}
cout << endl;
}
} else {
for (int row = 1; row <= r_g; row++) {
for (int col = 1; col <= c_g; col++) {
// if ('.' == matrix_arr[row][col])
// cout << "_ ";
// else
cout << matrix_arr[row][col];
}
cout << endl;
}
}
// cout << endl;
}
int run()
{
bool has_swap_row_and_column = false;
if (r_g > c_g) {
int temp = r_g;
r_g = c_g;
c_g = temp;
has_swap_row_and_column = true;
}
for (int row = 1; row <= r_g; row++)
for (int col = 1; col <= c_g; col++)
matrix_arr[row][col] = '*';
const int not_mine_count = r_g * c_g - m_g;
if (1 == not_mine_count)
goto OK;
if (1 == r_g) {
for (int col = 2; col <= not_mine_count; col++)
matrix_arr[1][col] = '.';
goto OK;
}
else if (2 == r_g) {
if (2 == not_mine_count)
goto ERR;
if (0 != not_mine_count % 2)
goto ERR;
matrix_arr[2][1] = '.';
for (int col = 2; col <= not_mine_count / 2; col++) {
matrix_arr[1][col] = '.';
matrix_arr[2][col] = '.';
}
goto OK;
}
else {
if (2 == not_mine_count
|| 3 == not_mine_count
|| 5 == not_mine_count
|| 7 == not_mine_count)
goto ERR;
if (c_g >= not_mine_count / 2
&& 0 == not_mine_count % 2) {
for (int col = 1; col <= not_mine_count / 2; col++) {
matrix_arr[1][col] = '.';
matrix_arr[2][col] = '.';
}
goto OK;
}
for (int rn = 3; rn <= r_g; rn++) {
const int c = not_mine_count / rn;
const int r = not_mine_count % rn;
if (c == c_g && 0 == r) {
for (int col = 1; col <= c; col++) {
for (int row = 1; row <= rn; row++) {
matrix_arr[row][col] = '.';
}
}
goto OK;
}
if (c >= c_g)
continue;
if (1 == c)
continue;
if (2 == c && 1 == r)
continue;
for (int col = 1; col <= c; col++) {
for (int row = 1; row <= rn; row++) {
matrix_arr[row][col] = '.';
}
}
for (int row = 1; row <= r; row++) {
matrix_arr[row][c + 1] = '.';
}
if (1 == r) {
matrix_arr[2][c + 1] = '.';
matrix_arr[rn][c] = '*';
}
goto OK;
}
}
ERR:
return 0;
OK:
matrix_arr[1][1] = 'c';
print(has_swap_row_and_column);
return 1;
}
int main()
{
int total_test_cases = 0;
cin >> total_test_cases;
for (int tt = 1; tt <= total_test_cases; ++tt) {
input();
cout << "Case #" << tt << ":" << endl;
const int ret = run();
if (0 == ret)
cout << "Impossible" << endl;
}
return 0;
}
| true |
8eb08042f7961bc3aebf6846087ea0f084bed2df | C++ | Jimendaisuki/RideTheFlow | /RideTheFlow/RideTheFlow/src/UIactor/PlayerArrow.h | SHIFT_JIS | 535 | 2.59375 | 3 | [] | no_license | #pragma once
#include "UIActor.h"
#include "../actor/Player.h"
class PlayerArrow : public UIActor
{
public:
PlayerArrow(IWorld& world, Player* player);
~PlayerArrow();
virtual void Update() override;
virtual void Draw() const override;
private:
// vC[|C^
Player* player;
// `|WV
Vector2 drawPos_;
// ]px
float angle_;
// _bVtO
bool isDash;
// Ot[_bVtO
bool prevDash;
// \[Xnh
int resPiece[10];
}; | true |
d7646249648b2eab1d9b64f16e327961f78c4257 | C++ | devendrakushwah/Algorithms | /QuickSort.cpp | UTF-8 | 781 | 3.71875 | 4 | [] | no_license | /*
Quick sort Algorithm
Partition using Hoare's partition scheme*/
#include<stdio.h>
int partition(int ar[], int l, int h)
{
int pivot=ar[l];
int i=l-1;
int j=h+1;
while(true){
do{
i++;
}while(ar[i]<pivot);
do{
j--;
}while(ar[j]>pivot);
if(i>=j){
return j;
}
//swap
ar[i]=ar[i]+ar[j];
ar[j]=ar[i]-ar[j];
ar[i]=ar[i]-ar[j];
}
}
void QuickSort(int ar[],int l,int h)
{
if(l<h)
{
int pivot=partition(ar,l,h);
QuickSort(ar,l,pivot);
QuickSort(ar,pivot+1,h);
}
}
int main()
{
int ar[]={12,2,8,-24,0,1};
QuickSort(ar,0,5);
for(int i=0;i<6;i++)
{
printf("%d ",ar[i]);
}
return 0;
}
| true |
bde2b67c50b7677bc2a4a88dab0e0e17444011e6 | C++ | Jagadish-prasad-mohanty/codeforce-800 | /amusingJoke.cpp | UTF-8 | 615 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <cstring>
using namespace std;
int main(){
string guest,host,name;
cin>>guest;
cin>>host;
cin>>name;
map<int,int> res;
for(int i=0;i<guest.length();i++){
res[guest[i]]++;
}
for(int i=0;i<host.length();i++){
res[host[i]]++;
}
for(int i=0;i<name.length();i++){
res[name[i]]--;
}
int flag=0;
for(auto i=res.begin();i!=res.end();i++){
if(i->second!=0){
cout<<"NO";
flag=1;
break;
}
}
if(flag==0){
cout<<"YES";
}
return 0;
} | true |
5fb765e095886190ad225185ef9fec00cd7d72e5 | C++ | draftup/novastory | /webserver/jsonthrower.h | UTF-8 | 842 | 2.6875 | 3 | [] | no_license | #ifndef JSONERRORTHROWER_H
#define JSONERRORTHROWER_H
#include <QString>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
namespace novastory
{
class JsonThrower
{
public:
JsonThrower();
bool isJsonError() const;
QString jsonErrorDescription() const;
void jsonReset();
int jsonErrorType();
QString jsonString();
QJsonObject& getMainObject();
inline void JSON_ERROR(const QString& errorDesc, int error_type = 0)
{
qDebug() << errorDesc;
jsonMainObject.insert("error", QJsonValue(true));
jsonMainObject.insert("errorDescription", QJsonValue(errorDesc));
jsonMainObject.insert("errorType", QJsonValue(error_type));
}
inline void JSON_INSERT(const QString& key, const QJsonValue& value)
{
jsonMainObject.insert(key, value);
}
private:
QJsonDocument json;
QJsonObject jsonMainObject;
};
}
#endif
| true |
f0a93b02644b6153f0ea5424aa15753f9942b97c | C++ | yyx112358/For-Interview | /笔试用/笔试用/LargeInt.hpp | GB18030 | 8,914 | 3.296875 | 3 | [] | no_license | #pragma once
//ο https://www.cnblogs.com/rmthy/p/8644236.html
#include <iostream>
#include <vector>
#include <string>
#define MAX_VAL 1000000000 // 10
#define VAL_LEN 9
#define FORMAT_STR "%09d"
//Ŵࡣ֧ⳤָ֧
class LargeInt
{
public:
LargeInt::LargeInt() {}
LargeInt::LargeInt(uint32_t val)
{
this->_data.push_back(val % MAX_VAL);
if (val >= MAX_VAL)
this->_data.push_back(val / MAX_VAL);
}
// ַ
// valStrʮַ
LargeInt::LargeInt(const string &valStr)
{
if (checkValStr(valStr))
{
int len = valStr.length();
// 9ȡӴ
while (len >= VAL_LEN)
{
string s = valStr.substr(len - VAL_LEN, VAL_LEN);
this->_data.push_back(stoi(s));
len -= VAL_LEN;
}
// Ӵ
if (len > 0)
{
string s = valStr.substr(0, len);
this->_data.push_back(stoi(s));
}
}
this->arrange(); // ȥ
}
//
LargeInt LargeInt::operator+(const LargeInt &li) const
{
int len1 = this->_data.size();
int len2 = li._data.size();
int minLen = len1 > len2 ? len2 : len1;
int maxLen = len1 > len2 ? len1 : len2;
const LargeInt &extraLi = (len1 > len2) ? (*this) : li;
uint32_t value = 0; // ֵͣ2
uint32_t carry = 0; // λ
LargeInt retVal;
for (int idx = 0; idx < minLen; ++idx)
{
value = this->_data[idx] + li._data[idx] + carry;
if (value >= MAX_VAL)
{
retVal._data.push_back(value - MAX_VAL);
carry = 1;
}
else
{
retVal._data.push_back(value);
carry = 0;
}
}
for (int idx = minLen; idx < maxLen; ++idx)
{
value = extraLi._data[idx] + carry;
if (value >= MAX_VAL)
{
retVal._data.push_back(value - MAX_VAL);
carry = 1;
}
else
{
retVal._data.push_back(value);
carry = 0;
}
}
if (carry > 0)
retVal._data.push_back(carry);
//retVal.arrange(); // ȥ0
return retVal;
}
LargeInt LargeInt::operator-(const LargeInt &li) const
{
if (*this <= li)
{
return LargeInt(0);
}
int len1 = this->_data.size();
int len2 = li._data.size();
uint32_t value = 0; //
uint32_t carry = 0; // λ
LargeInt retVal;
for (int idx = 0; idx < len2; ++idx)
{
if (this->_data[idx] < li._data[idx] + carry) // עϸڣcarryҲֲֵ࣬Ϊ
{
value = this->_data[idx] + MAX_VAL - carry - li._data[idx];
carry = 1;
}
else
{
value = this->_data[idx] - carry - li._data[idx];
carry = 0;
}
retVal._data.push_back(value);
}
for (int idx = len2; idx < len1; ++idx)
{
if (this->_data[idx] < carry)
{
value = this->_data[idx] + MAX_VAL - carry;
carry = 1;
}
else
{
value = this->_data[idx] - carry;
carry = 0;
}
retVal._data.push_back(value);
}
retVal.arrange();
return retVal;
}
LargeInt LargeInt::operator*(const LargeInt &li) const
{
int len1 = this->_data.size();
int len2 = li._data.size();
if (len1 < len2) return li.operator*(*this); // Ż֤λڳ
uint64_t value; //
uint64_t carry = 0; // λ
LargeInt retVal(0);
LargeInt mulTemp;
for (int idx2 = 0; idx2 < len2; ++idx2)
{
mulTemp._data.clear();
carry = 0;
//
for (int tmpIdx = 0; tmpIdx < idx2; ++tmpIdx)
mulTemp._data.push_back(0);
for (int idx1 = 0; idx1 < len1; ++idx1)
{
value = (uint64_t)(li._data[idx2]) * (uint64_t)(this->_data[idx1]) + carry;
mulTemp._data.push_back((uint32_t)(value % MAX_VAL));
carry = value / MAX_VAL;
}
if (carry)
mulTemp._data.push_back((uint32_t)carry);
retVal = retVal + mulTemp;
}
return retVal;
}
LargeInt LargeInt::operator/(const LargeInt &li) const
{
if (li._data.empty() || li == 0) return LargeInt("");
if (*this < li) return LargeInt(0);
int len1 = this->_data.size();
int len2 = li._data.size();
uint32_t value;
LargeInt retVal;
LargeInt divTemp;
for (int idx = len1 - len2 + 1; idx < len1; ++idx)
{
divTemp._data.push_back(this->_data[idx]);
}
// len1 >= len2
for (int idx = len1 - len2; idx >= 0; --idx)
{
divTemp._data.insert(divTemp._data.begin(), this->_data[idx]);
divTemp.arrange();
value = getMaxCycle(divTemp, li); //
divTemp = divTemp - li * value; //
retVal._data.insert(retVal._data.begin(), value); // ɸλλУԲλbegin
}
retVal.arrange();
return retVal;
}
LargeInt LargeInt::operator%(const LargeInt &li) const
{
if (li._data.empty() || li == 0) return LargeInt("");
if (*this < li) return LargeInt(0);
int len1 = this->_data.size();
int len2 = li._data.size();
uint32_t value;
LargeInt retVal;
LargeInt divTemp;
for (int idx = len1 - len2 + 1; idx < len1; ++idx)
{
divTemp._data.push_back(this->_data[idx]);
}
// len1 >= len2
for (int idx = len1 - len2; idx >= 0; --idx)
{
divTemp._data.insert(divTemp._data.begin(), this->_data[idx]);
divTemp.arrange();
value = getMaxCycle(divTemp, li); //
divTemp = divTemp - li * value; //
retVal._data.insert(retVal._data.begin(), value); // ɸλλУԲλbegin
}
divTemp.arrange();
return divTemp;
}
// Ƚ
bool LargeInt::operator==(const LargeInt &li) const { return compare(li) == 0; }
bool LargeInt::operator!=(const LargeInt &li) const { return compare(li) != 0; }
bool LargeInt::operator<(const LargeInt &li) const { return compare(li) < 0; }
bool LargeInt::operator>(const LargeInt &li) const { return compare(li) > 0; }
bool LargeInt::operator<=(const LargeInt &li) const { return compare(li) <= 0; }
bool LargeInt::operator>=(const LargeInt &li) const { return compare(li) >= 0; }
string LargeInt::toString() const
{
int len = this->_data.size();
int shift = 0;
char *buff = new char[len * VAL_LEN + 1];
if (len > 0)
shift += sprintf(buff + shift, "%d", this->_data[len - 1]);
for (int idx = len - 2; idx >= 0; --idx)
shift += sprintf(buff + shift, FORMAT_STR, this->_data[idx]);
buff[shift] = '\0';
string retStr(buff);
delete[] buff;
return retStr;
}
friend std::ostream&operator<<(std::ostream&os, const LargeInt&li)
{
os << li.toString();
return os;
}
private:
std::vector<uint32_t> _data;
inline bool isDigit(const char ch) { return ch >= '0' && ch <= '9'; }
// ַϷԼ飬ַֻ 0~9
bool checkValStr(const string &valStr)
{
for (auto it = valStr.begin(); it != valStr.end(); ++it)
if (!isDigit(*it)) return false;
return true;
}
// ȽϺ0 ȣ1 ڣ-1 С
int LargeInt::compare(const LargeInt &li) const
{
int len1 = this->_data.size();
int len2 = li._data.size();
// step1: Ƚϳ
if (len1 != len2)
return (len1 > len2) ? 1 : -1;
// step2: ɸλλȽֵ
for (int idx = len1 - 1; idx >= 0; --idx)
{
if (this->_data[idx] == li._data[idx]) continue;
return this->_data[idx] > li._data[idx] ? 1 : -1;
}
return 0;
}
// ȥеĸλڶ
void LargeInt::arrange()
{
int idx = this->_data.size();
// ע⣬ȫΪ0Ҫλ0
while (--idx >= 1)
{
if (this->_data[idx] > 0) break;
this->_data.pop_back();
}
}
// ֵ
uint32_t LargeInt::getMaxCycle(const LargeInt &liA, const LargeInt &liB) const
{
LargeInt tempA = liA;
const LargeInt& tempB = liB;
uint32_t tempC;
uint32_t res = 0;
bool flag = true;
while (tempA >= tempB)
{
tempC = estimateQuotient(tempA, tempB);
tempA = tempB * tempC - tempA;
res = flag ? (res + tempC) : (res - tempC);
flag = !flag;
}
//
while (res > 0 && liB * res > liA) res--;
return res;
}
// ֵ
uint32_t LargeInt::estimateQuotient(const LargeInt &liA, const LargeInt &liB) const
{
int lenA = liA._data.size();
int lenB = liB._data.size();
uint64_t valA, valB;
if (lenA == lenB)
{
if (lenA > 1)
{
valA = (uint64_t)liA._data[lenA - 1] * MAX_VAL + liA._data[lenA - 2];
valB = (uint64_t)liB._data[lenB - 1] * MAX_VAL + liB._data[lenB - 2];
}
else
{
valA = (uint64_t)liA._data[lenA - 1];
valB = (uint64_t)liB._data[lenB - 1];
}
}
else
{
valA = (uint64_t)liA._data[lenA - 1] * MAX_VAL + liA._data[lenA - 2];
valB = (uint64_t)liB._data[lenB - 1];
}
return (uint32_t)(valA / valB);
}
};
#undef MAX_VAL
#undef VAL_LEN
#undef FORMAT_STR
| true |
8e548092daee5ad35f2478e64d2bc512d8306de6 | C++ | wgysarm/dipmain | /src/UartServer.cpp | UTF-8 | 2,271 | 2.515625 | 3 | [] | no_license | #include "UartServer.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#define SERIAL "/dev/ttyS0"
UartServer::UartServer(QObject *parent) : QObject(parent)
{
// m_cmdList = new QList<QByteArray>();
// QByteArray baOpen ;
// QByteArray baClose;
// memccpy(baOpen.data(), "open", 4, 4);
// qDebug() << baOpen.at(0) ;
// qDebug() << baOpen.at(1) ;
// qDebug() << baOpen.at(2) ;
// qDebug() << baOpen.at(3) ;
// memccpy(baClose.data(), "close", 5, 5);
// qDebug() << baOpen.at(0) ;
// qDebug() << baOpen.at(1) ;
// qDebug() << baOpen.at(2) ;
// qDebug() << baOpen.at(3) ;
// qDebug() << baOpen.at(4) ;
// m_cmdList->append(baOpen);
// m_cmdList->append(baClose);
// qDebug() << m_cmdList.at(0);
// qDebug() << m_cmdList.at(1);
m_readBuf = (char*)malloc(1024);
qDebug() << "--------uart server construct------" << QThread::currentThread();
QObject::connect(&m_uartThread, SIGNAL(finished()), this, SLOT(deleteLater()));
QObject::connect(this, SIGNAL(SIG_Finished()), &m_uartThread, SLOT(quit()));
QObject::connect(this, SIGNAL(SIG_Error(QString)), this, SLOT(SLOT_Error(QString)));
}
UartServer::~UartServer()
{
// if(m_readBuf != NULL)
// {
// free(m_readBuf);
// m_readBuf = NULL;
// }
}
void UartServer::SLOT_Error(QString err)
{
qDebug() << err;
}
void UartServer::SLOT_ReadUart()
{
qDebug() << "------uart thread------" <<QThread::currentThread();
int fd = open(SERIAL, O_RDWR, 1);
if(fd < 0)
{
emit SIG_Error(QString("opne serial ttyS0 error"));
}
for(;;)
{
int ret = read(fd, m_readBuf, 1024);
if(ret)
{
// const QString &str = QString(m_readBuf);
// if(QString::compare(str,strclose) == 0)
// {
// emit SIG_CloseCPlayWindow();
// qDebug() << "close" ;
// }else if(QString::compare(str,stropen) == 0)
// {
// emit SIG_OpenCPlayWindow();
// qDebug() << "open";
// }
}
QThread::msleep(20);
}
}
void UartServer::SLOT_KillSelf()
{
emit SIG_Finished();
}
| true |
42761755d7c9b73c0932d006c3fa6b186a09cd18 | C++ | demolition18956/QT011-Networking | /Server/greetingserver.cpp | UTF-8 | 1,096 | 2.96875 | 3 | [] | no_license | #include <QtNetwork>
#include "greetingserver.h"
GreetingServer::GreetingServer(QObject* parent) : QTcpServer(parent)
{
greetings[0] = "Hello";
greetings[1] = "Howdy";
greetings[2] = "Salutations";
greetings[3] = "Aloha";
// Initialize random number generator to number of seconds
// between 00:00:00 and now
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
// Send greeting upon new connection
connect(this, SIGNAL(newConnection()), this, SLOT(sendGreeting()));
// Listen for incoming connects on port 1234 of this machine
this->listen(QHostAddress::LocalHost, 1234);
}
void GreetingServer::sendGreeting()
{
// Socket created as child of GreetingServer object
QTcpSocket* client = this->nextPendingConnection();
QByteArray block;
QDataStream outgoingMessage(&block, QIODevice::WriteOnly);
outgoingMessage.setVersion(QDataStream::Qt_4_1);
// Select random greeting
outgoingMessage << greetings[qrand() % 4];
// Write greeting to socket
client->write(block);
// Attempt to close socket but wait until pending data written
client->disconnectFromHost();
}
| true |
7a0494871732c5458173f7d90e03731607adb4bc | C++ | friedy10/Stack | /StackLinkedList/StackLinkedList/Stack.h | UTF-8 | 954 | 3.8125 | 4 | [] | no_license | #include<iostream>
using namespace std;
//Node
struct StackNode
{
int data;
struct StackNode* next;
};
class Stack
{
public:
Stack();
~Stack();
StackNode* newNode(int data1);
void push(int data);
int isEmpty();
int peek();
int pop();
private:
StackNode* root;
};
Stack::Stack()
{
}
Stack::~Stack()
{
}
StackNode* Stack::newNode(int data1)
{
StackNode* stackNode = new StackNode;
stackNode->data = data1;
stackNode->next = NULL;
return stackNode;
}
int Stack::isEmpty()
{
return !root; // I this exist the stack has elements
}
void Stack::push(int data) {
StackNode* stackNode = newNode(data);
stackNode->next = root;
root = stackNode;
cout << data << " pushed to stack\n\n";
}
int Stack::pop() {
if (isEmpty()) {
return INT_MIN;
}
StackNode* temp = root;
root = (root)->next;
int popped = temp->data;
delete temp;
return popped;
}
int Stack::peek() {
if (isEmpty()) {
return INT_MIN;
}
return root->data;
}
| true |
9e12b787c2da5579b7f037259c246b9f295112c6 | C++ | AnneLivia/Competitive-Programming | /Online Judges/Neps Academy/QuadradoOBI2014.cpp | UTF-8 | 1,141 | 2.671875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n;
vector<vector<int> > v(n, vector<int>(n, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> v[i][j];
}
}
int sumcol, sumlin, sumdiag, rightSum = -1, diffcol, difflin = -1, sumdifflin;
for (int i = 0; i < n; i++) {
sumlin = sumcol = 0;
for (int j = 0; j < n; j++) {
sumlin+=v[i][j];
sumcol+=v[j][i];
}
if (sumlin == sumcol && rightSum == -1) {
rightSum = sumlin;
break;
}
}
for (int i = 0; i < n; i++) {
sumlin = sumcol = 0;
for (int j = 0; j < n; j++) {
sumlin+=v[i][j];
sumcol+=v[j][i];
}
if (sumlin != rightSum) {
difflin = i;
sumdifflin = sumlin;
}
if (sumcol != rightSum) {
diffcol = i;
}
}
if (difflin != -1) {
cout << rightSum - (sumdifflin - v[difflin][diffcol]) << " " << v[difflin][diffcol] << endl;
}
return 0;
}
| true |
dbeeccd579f52a39b5dace6758cb5d31aacbe74d | C++ | KrishnaHarishK/Compare_Records | /StringUtils.cc | UTF-8 | 5,248 | 2.796875 | 3 | [] | no_license | #include"StringUtils.hh"
#include<sstream>
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
StringUtils::StringSegmentVector
StringUtils::BreakUpString(const std::string & aString,
const std::string & aDelimiters)
{
StringSegmentVector tStringChunks;
std::size_t tForwardPosition = 0;
std::size_t tLaggingPosition = 0;
while((tForwardPosition = aString.find_first_of(aDelimiters,
tLaggingPosition)) !=
std::string::npos)
{
StringSegment tSegment = {tLaggingPosition,
tForwardPosition- tLaggingPosition};
tStringChunks.push_back(tSegment);
tLaggingPosition = tForwardPosition + 1;
}
StringSegment tSegment = {tLaggingPosition,
aString.length() - tLaggingPosition};
tStringChunks.push_back(tSegment);
return tStringChunks;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void
StringUtils::FillBuffer(char * rpBuffer, const std::string & aString)
{
strncpy(rpBuffer, aString.c_str(), aString.length());
rpBuffer[aString.length()] = 0;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool
StringUtils::GetBool(std::string aString)
{
bool tReturnValue = false;
RemoveWhiteSpace(aString);
if(aString == "true")
{
tReturnValue = true;
}
return tReturnValue;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int
StringUtils::GetInt(std::string aString)
{
int tReturnValue;
RemoveWhiteSpace(aString);
std::istringstream tStream(aString);
tStream>>tReturnValue;
return tReturnValue;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
std::string
StringUtils::GetString(int aInt)
{
std::ostringstream tStream;
tStream<<aInt;
return tStream.str();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool
StringUtils::IsBool(std::string aString)
{
bool tReturnValue = false;
RemoveWhiteSpace(aString);
if(aString == "true" || aString == "false")
{
tReturnValue = true;
}
return tReturnValue;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
StringUtils::ValidatedString
StringUtils::IsConditionalExclusion(std::string aString)
{
ValidatedString tReturnPair(false, "");
RemoveWhiteSpace(aString);
if((aString.find("false") == 0) &&
(aString.length() > 6) &&
(aString[5] == '='))
{
tReturnPair.first = true;
tReturnPair.second = aString.substr(6, aString.length());
}
return tReturnPair;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool
StringUtils::IsInt(std::string aString,
VERIFICATION_MODE aMode)
{
bool tReturnValue = false;
RemoveWhiteSpace(aString);
if((aString.length() ||
aMode == eTrueForWhiteSpaceOrEmpty)&&
(aString.find_first_not_of("-0123456789") == std::string::npos))
{
std::size_t tDashIndex = aString.find('-');
if(tDashIndex != std::string::npos)
{
if((tDashIndex == 0) &&
aString.find('-', ++tDashIndex) == std::string::npos)
{
tReturnValue = true;
}
}
else
{
tReturnValue = true;
}
}
return tReturnValue;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void
StringUtils::RemoveWhiteSpace(std::string & aString, REMOVAL_MODE aMode)
{
if(aMode == eRemoveWhiteSpaceAll)
{
while((*(aString.begin()) == ' ') ||
(*(aString.begin()) == '\t') ||
(*(aString.begin()) == '\n') ||
(*(aString.begin()) == '\f') ||
(*(aString.begin()) == '\r'))
{
aString.erase(aString.begin());
}
std::string::iterator tIterator = aString.begin();
while(tIterator != aString.end())
{
std::string::iterator tOldValue = tIterator;
tIterator ++;
if((*tIterator == ' ') ||
(*tIterator == '\t') ||
(*tIterator == '\n') ||
(*tIterator == '\f') ||
(*tIterator == '\r'))
{
aString.erase(tIterator);
tIterator = tOldValue;
}
}
}
else if(aMode == eRemoveWhiteSpaceChomp)
{
std::string::iterator tIterator = aString.end();
while((*(--tIterator) == ' ') ||
(*(--tIterator) == '\t') ||
(*(--tIterator) == '\n') ||
(*(--tIterator) == '\f') ||
(*(--tIterator) == '\r'))
{
aString.erase(tIterator);
tIterator = aString.end();
}
}
}
| true |
a816fc5e98db93bc94f89ac13ed29033152b548c | C++ | DrYaling/PCGForUnity | /cppLib/code/Generator/Terrain/Painter/SplatPainter.cpp | UTF-8 | 3,046 | 2.71875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #include "SplatPainter.h"
#include "Logger/Logger.h"
namespace generator
{
SplatPainter::SplatPainter() :
m_pAlphaMap(nullptr),
m_nAlphaCount(0),
m_fBrushStrength(1.0f),
m_nSize(0)
{
m_pBrush = new PainterBrush();
}
SplatPainter::~SplatPainter()
{
safe_delete(m_pBrush);
}
void SplatPainter::Init(float * alphaMap, int32_t sizeXY, int32_t splatCount)
{
m_nAlphaCount = splatCount;
m_nSize = sizeXY;
m_pAlphaMap = alphaMap;
m_pBrush->Initilize(BrushStyle::Circle_middle, 5);
}
void SplatPainter::ResetBrush(int32_t brushSize)
{
m_pBrush->Initilize(BrushStyle::Circle_middle, brushSize);
}
//ensure alphaMap has enough space
inline void SplatPainter::Normalize(int32_t x, int32_t y, float newAlpha, int32_t splatIndex)
{
int line = GetSplatMapIndex(y, x, 0, m_nSize, m_nAlphaCount); ;
generator_clamp(newAlpha,0,1.0f);
m_pAlphaMap[line + splatIndex] = newAlpha;
float totalAlphaOthers = 0;
for (int32_t i = 0; i < m_nAlphaCount; i++)
{
if (i != splatIndex)
totalAlphaOthers += m_pAlphaMap[line + i];
}
if (totalAlphaOthers > 0.01f)
{
float adjust = (1.0F - newAlpha) / totalAlphaOthers;
for (int a = 0; a < m_nAlphaCount; a++)
{
if (a != splatIndex)
{
m_pAlphaMap[line + a] *= adjust;
}
}
}
else
{
for (int a = 0; a < m_nAlphaCount; a++)
{
m_pAlphaMap[line + a] = a == splatIndex ? 1.0F : 0.0F;
}
}
}
void SplatPainter::Paint(int xCenter, int yCenter, int splatIndex)
{
if (splatIndex >= m_nAlphaCount)
{
return;
}
int brushSize = m_pBrush->GetBrushSize();
int intRadius = brushSize / 2;
int intFraction = brushSize % 2;
int xmin = generator::clamp<int>(xCenter - intRadius, 0, m_nSize - 1);
int ymin = generator::clamp<int>(yCenter - intRadius, 0, m_nSize - 1);
int xmax = generator::clamp<int>(xCenter + intRadius + intFraction, 0, m_nSize);
int ymax = generator::clamp<int>(yCenter + intRadius + intFraction, 0, m_nSize);
int width = xmax - xmin;
int height = ymax - ymin;
int nMax = m_nSize - 1;
int rx, ry;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int xBrushOffset = (xmin + x) - (xCenter - intRadius + intFraction);
int yBrushOffset = (ymin + y) - (yCenter - intRadius + intFraction);
rx = xBrushOffset + xCenter;
ry = yBrushOffset + yCenter;
generator_clamp(rx, 0, nMax);
generator_clamp(ry, 0, nMax);
float brushStrength = m_pBrush->GetStrength(xBrushOffset, yBrushOffset)*m_fBrushStrength;
int index = GetSplatMapIndex(ry, rx, splatIndex, m_nSize, m_nAlphaCount);
// Paint with brush
Normalize(rx, ry, m_pAlphaMap[index] += brushStrength, splatIndex);
/*if (splatIndex == 0)
{
int other = 1;
LogFormat("alpha %d at x %d,y %d,index %d,str %f,is %f,other %d index %d,alpha %f", splatIndex, rx, ry, index, brushStrength, m_pAlphaMap[index], other, GetSplatMapIndex(ry, rx, other, m_nSize, m_nAlphaCount), m_pAlphaMap[GetSplatMapIndex(ry, rx, other, m_nSize, m_nAlphaCount)]);
}*/
}
}
}
} | true |
580cbd5bb14a1afbb5d703adab26a189c642980f | C++ | tleek135/university | /CS201/lab6/lab6ex5.cpp | UTF-8 | 651 | 3.53125 | 4 | [] | no_license | //Program written by: Kyle Lee (005054981)
//Lab 6, Exercise 5
#include <iostream>
#include <cassert>
#include <vector>
using namespace std;
int countOccurrences(const vector<int> & v, int k){
int occurrenceCount = 0;
for (int index = 0; index < v.size(); index++){
if (v[index] == k)
++occurrenceCount;
}
return occurrenceCount;
}
int main(){
int temp[] = {2, 3, 2, 7, 7, 8, 7, 12, 26, 87, 12};
vector<int> test(temp, temp + 11);
assert(countOccurrences(test, 2) == 2);
assert(countOccurrences(test, 3) == 1);
assert(countOccurrences(test, 7) == 3);
assert(countOccurrences(test, 12) == 2);
cout << "All tests passed.\n";
}
| true |
2dcf5a4d1a2c2e9ef268dee64a7f8dbb0e2180ea | C++ | decifur/Algorithms | /String_Algorithm/Check_if_string_has_only_unique_characters.cpp | UTF-8 | 730 | 4 | 4 | [] | no_license | // C++ program to illustrate string
// with unique characters using
// brute force technique
#include <bits/stdc++.h>
using namespace std;
bool uniqueCharacters(string str)
{
// If at any time we encounter 2
// same characters, return false
for (int i = 0; i < str.length() - 1; i++) {
for (int j = i + 1; j < str.length(); j++) {
if (str[i] == str[j]) {
return false;
}
}
}
// If no duplicate characters encountered,
// return true
return true;
}
// driver code
int main()
{
string str = "VritikaMalhotra";
if (uniqueCharacters(str)) {
cout << "The String " << str
<< " has all unique characters\n";
}
else {
cout << "The String " << str
<< " has duplicate characters\n";
}
return 0;
}
| true |
8658ab864bef4f1d39a911eef80ab4739f930d8b | C++ | dnsdudrla97/pwn | /dreamhack-io/Memory_Corruption_C++/Type_confusion/cpp_cast.cpp | UTF-8 | 404 | 3.234375 | 3 | [] | no_license | // g++ -o cpp_cast cpp_cast.cpp
#include <iostream>
using namespace std;
class A
{
public_colon
virtual void f()
{
cout << "Class A::f()" << endl;
}
};
class B
{
public_colon
void f()
{
cout << "Class B::f()" << endl;
}
};
int main()
{
A *class_a = new A;
class_a->f();
B *class_b = dynamic_cast<B*> (class_a);
class_b->f();
return 0;
} | true |
6e9fce9937fd9aad36bf572292327c502fb44316 | C++ | wilbo/C-plus-plus-examples | /NestedArray/NestedArray.cpp | UTF-8 | 1,020 | 3.59375 | 4 | [] | no_license | //
// Created by Wilbert Schepenaar on 08/02/2018.
//
#include "NestedArray.h"
#include <iostream>
using namespace std;
int** nestedArray(int depth) {
int** arrayP = new int*[depth]; // an array of pointers
for (int i = 0; i < depth; i++) {
int* array = new int[i+1]; // declare the nested array
for (int j = 0; j < i+1; j++) {
array[j] = rand() % 100; // initialize every value of the nested array with a 0
}
arrayP[i] = array;
}
return arrayP;
}
void deleteArray(int** arr, int depth) {
for (int i = 0; i < depth; ++i) {
delete[] arr[i];
}
delete[] arr;
}
void print(int** arr, int depth) {
for (int i = 0; i < depth; ++i) {
for (int j = 0; j < i+1; ++j) {
cout << arr[i][j] << ", ";
}
cout << endl;
}
}
void NestedArray::run() {
int depth = 4;
int** arrayP = nestedArray(depth);
print(arrayP, depth);
deleteArray(arrayP, depth);
}
| true |
b66d09d59a58155016179824de22be93f6c2da35 | C++ | azizchigri/R-type-project | /Sources/GameEngine/Game/Core/Rtype/RtypeClient.cpp | UTF-8 | 6,752 | 2.5625 | 3 | [] | no_license | //
// EPITECH PROJECT, 2018
// CPP_rtype_2018
// File description:
// RtypeClient class implementation
//
#include "GameEngine/Game/Core/Rtype/RtypeClient.hpp"
Engine::Game::RtypeClient::RtypeClient(unsigned int framerate,
boost::asio::io_service &io_service, const std::string &ip, const int port):
AGameClient(framerate, io_service, ip, port)
{
_events = std::unique_ptr<Graphical::AEventManager<sf
::RenderWindow>>(new SfmlEventManager());
initFuncPtr();
}
bool Engine::Game::RtypeClient::launch()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "R-type",
sf::Style::Titlebar | sf::Style::Close);
window.setFramerateLimit(_framerate);
_port_udp = -1;
_rooms_menu_manager.buttons[0] = -1;
try {
initPlayers();
launchMenu(window);
} catch (std::exception &e) {
std::cout << e.what() << std::endl;
return false;
}
launchGame(window);
return true;
}
void Engine::Game::RtypeClient::handleInput(std::vector<Engine::EventObject>
events)
{
for (auto event : events) {
if (event.type == EventObject::EventType::KEYPRESSED) {
if (event.key.code == Event::Keyboard::Left)
sendUdp(Packet::buildPacket(
RTypeCommunication::MOVELEFT, ""));
if (event.key.code == Event::Keyboard::Right)
sendUdp(Packet::buildPacket(
RTypeCommunication::MOVERIGHT, ""));
if (event.key.code == Event::Keyboard::Up)
sendUdp(Packet::buildPacket(
RTypeCommunication::MOVETOP, ""));
if (event.key.code == Event::Keyboard::Down)
sendUdp(Packet::buildPacket(
RTypeCommunication::MOVEDOWN, ""));
if (event.key.code == Event::Keyboard::Space)
sendUdp(Packet::buildPacket(
RTypeCommunication::SHOOT, ""));
}
}
}
void Engine::Game::RtypeClient::launchGame(sf::RenderWindow &window)
{
while (window.isOpen()) {
auto events = _events->getEvents(window);
handleInput(events);
gameInterpretor();
window.clear(sf::Color::Black);
drawObjects(window);
window.display();
}
}
void Engine::Game::RtypeClient::createRooms(Engine::Graphical::SfmlMenu &menu)
{
float a = 150;
for (unsigned int i = 0; i < 10; i += 1) {
char RoomInfo[150];
sprintf(RoomInfo, "%s %d/%d",
_rooms_menu_manager.rooms[i].name,
_rooms_menu_manager.rooms[i].number_of_player,
_rooms_menu_manager.rooms[i].number_max_of_player);
_rooms_menu_manager.buttons[i] = menu.addButton
(std::string(RoomInfo), {0, a, 0}, {20, 4, 40}, {51, 255, 79});
a += 35;
}
}
void Engine::Game::RtypeClient::updateRooms(Engine::Graphical::SfmlMenu &menu)
{
for (unsigned int i = 0; i < 10; i += 1) {
char RoomInfo[150];
sprintf(RoomInfo, "%s %d/%d",
_rooms_menu_manager.rooms[i].name,
_rooms_menu_manager.rooms[i].number_of_player,
_rooms_menu_manager.rooms[i].number_max_of_player);
menu.updateButton( _rooms_menu_manager.buttons[i],
std::string(RoomInfo), {20, 4, 40});
}
}
void Engine::Game::RtypeClient::displayRooms(Packet::RtypePacket &packet,
Engine::Graphical::SfmlMenu &menu)
{
if (packet.type == 201) {
memcpy(&_rooms_menu_manager.rooms, &packet.body, sizeof
(room_list));
if (_rooms_menu_manager.buttons[0] != -1) {
updateRooms(menu);
} else {
createRooms(menu);
}
}
}
bool Engine::Game::RtypeClient::menuPacketInterpretor(Packet::RtypePacket
&packet)
{
if (packet.type == 20 && _port_udp == -1) {
Port *my_port = reinterpret_cast<Port *> (packet
.body);
_port_udp = my_port->port;
initClients(_ip, _port_udp);
}
if (packet.type == 201) {
displayRooms(packet, _menu);
}
return (packet.type == 30);
}
bool Engine::Game::RtypeClient::menuButtonInterpretor(long button)
{
if (_rooms_menu_manager.buttons[0] == -1)
return false;
for(unsigned int i = 0; i < 10; i += 1) {
if (button == _rooms_menu_manager.buttons[i]) {
std::cout << "room asking: " << _rooms_menu_manager
.rooms[i].name << std::endl;
sendTcp(Packet::buildPacket(Packet::Command::JOIN_ROOM,
_rooms_menu_manager.rooms[i]));
return false;
}
}
if (button == _start_button) {
sendTcp(Packet::buildPacket(8, "start game"));
return true;
}
if (button == _refresh_button) {
sendTcp(Packet::buildPacket(17, "getListRooms"));
}
return false;
}
void Engine::Game::RtypeClient::initMenu()
{
_menu.setMusic("menu.wav", 10);
_menu.addText("Bienvenue dans le jeu", {0, 0, 0}, {20, 40, 40}, {51,
255, 79});
_start_button = _menu.addButton("Appuie pour start game", {250, 60,
0}, {20, 40, 40}, {51, 255, 79});
_refresh_button = _menu.addButton("Appuie pour refresh", {500,
60, 0}, {20, 40, 40}, {51, 255, 79});
sendTcp(Packet::buildPacket(17, "getListRooms"));
sendTcp(Packet::buildPacket(9, "getUdpPort"));
}
void Engine::Game::RtypeClient::launchMenu(sf::RenderWindow &window)
{
Packet::RtypePacket tcp_pack;
Packet::RtypePacket udp_pack;
long btn;
initMenu();
while (window.isOpen()) {
tcp_pack = receiverTcp();
if (_port_udp != -1)
receiveUdp(udp_pack);
btn = _menu.getButtonClicked(window);
if (menuButtonInterpretor(btn) ||
menuPacketInterpretor(tcp_pack))
break;
window.clear(sf::Color::Black);
_menu.draw(window);
window.display();
}
}
void Engine::Game::RtypeClient::gameInterpretor()
{
Packet::RtypePacket packet;
receiveUdp(packet);
while (packet.type != 99) {
if (packet.type == RTypeCommunication::PLAYERS)
_funcPtr[0](packet);
receiveUdp(packet);
}
}
void Engine::Game::RtypeClient::initFuncPtr()
{
_funcPtr.at(0) = std::bind
(&RtypeClient::restorePlayer, this, std::placeholders::_1);
}
void Engine::Game::RtypeClient::restorePlayer(Packet::RtypePacket packet)
{
Player p[4];
memcpy(&p, packet.body, packet.size);
for (auto player : p) {
_players[player.team]->setPosition(player.position);
}
}
void Engine::Game::RtypeClient::initPlayers()
{
_players.at(PlayerTeam::BLUE) = std::unique_ptr<
Graphical::ColliderObject<sf::RenderWindow>>(new
Graphical::ColliderObject<sf::RenderWindow>(new Graphical::SfmlShape
("player1.png", Graphical::ShapeType::RECTANGLE)));
_players.at(PlayerTeam::RED) = std::unique_ptr<
Graphical::ColliderObject<sf::RenderWindow>>(new
Graphical::ColliderObject<sf::RenderWindow>(new Graphical::SfmlShape
("player2.png", Graphical::ShapeType::RECTANGLE)));
_players.at(PlayerTeam::YELLOW) = std::unique_ptr<
Graphical::ColliderObject<sf::RenderWindow>>(new
Graphical::ColliderObject<sf::RenderWindow>(new Graphical::SfmlShape
("player3.png", Graphical::ShapeType::RECTANGLE)));
_players.at(PlayerTeam::GREEN) = std::unique_ptr<
Graphical::ColliderObject<sf::RenderWindow>>(new
Graphical::ColliderObject<sf::RenderWindow>(new Graphical::SfmlShape
("player4.png", Graphical::ShapeType::RECTANGLE)));
}
void Engine::Game::RtypeClient::drawObjects(sf::RenderWindow &window)
{
for (auto it = begin(_players); it != end(_players); ++it) {
it->get()->draw(window);
}
}
| true |
28ce21cb5d8cee27a43804ebc2ea9099dc2187e6 | C++ | gatsbyd/ShinyVm | /src/main.cpp | UTF-8 | 1,901 | 2.96875 | 3 | [] | no_license | #include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
struct cmd {
bool helpFlag;
bool versionFlag;
std::string cp;
std::string className;
std::vector<std::string> args;
cmd() :helpFlag(false), versionFlag(false) {}
};
cmd parseCmd(int argc, char *argv[]);
void printUsage(std::string className);
void startJVM(const cmd&);
int main(int argc, char *argv[]) {
cmd cmd;
cmd = parseCmd(argc, argv);
if (cmd.helpFlag) {
printUsage(argv[0]);
} else if (cmd.versionFlag) {
std::cout << "version 0.0.1\n";
} else {
startJVM(cmd);
}
}
void printUsage(std::string className) {
std::cout << "Usage: " << className << " [-option] class [args...]" << std::endl;
}
cmd parseCmd(int argc, char *argv[]) {
using std::string;
cmd cmd;
int opt;
struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'v'},
{"cp", required_argument, NULL, 'c'},
{"classpath", required_argument, NULL, 'c'},
{0, 0, 0, 0}
};
const char *optionString = "h";
int option_index = 0;
while ( (opt = getopt_long_only(argc, argv, optionString, long_options, &option_index)) != -1 ) {
switch(opt) {
case 'h':
cmd.helpFlag = true;
break;
case 'v':
cmd.versionFlag = true;
break;
case 'c':
cmd.cp = string(optarg);
break;
default:
printUsage(argv[0]);
exit(1);
}
}
if (optind < argc) {
cmd.className = string(argv[optind++]);
for (int i = optind; i < argc; ++i) {
cmd.args.push_back(string(argv[i]));
}
}
return cmd;
}
void startJVM(const cmd& cmd) {
std::cout << "start jvm\n";
std::cout << "helpFlag=" << cmd.helpFlag << ", versionFlag=" << cmd.versionFlag << ", cp=" << cmd.cp
<< ", class=" << cmd.className << ", args=";
for (const std::string& s: cmd.args) {
std::cout << s << " ";
}
std::cout << std::endl;
}
| true |
dee941b8a8016d5880d18c8c7deb3c094960c613 | C++ | dimagimburg/KMeansAlgorithmSequentialAndParallel | /clustering_points/Cluster.cpp | UTF-8 | 1,759 | 3.328125 | 3 | [] | no_license | #include "Cluster.h"
int Cluster::NEXT_ID = 0;
Cluster::Cluster() : id(NEXT_ID++)
{
}
Cluster::Cluster(Point* p) : id(NEXT_ID++)
{
center = new Point(*p);
//this->addPoint(p);
}
Cluster::Cluster(const Point* p) : id(NEXT_ID++)
{
center = new Point(*p);
//this->addPoint(p);
}
Cluster::~Cluster()
{
}
void Cluster::addPoint(Point* p){
if (points.size() == 0 && center == NULL){
center = p;
}
this->points.push_back(p);
}
void Cluster::clear(){
this->points.clear();
}
void Cluster::setCenter(Point* p){
this->center = p;
}
const Point* Cluster::getCenter() const{
return this->center;
}
vector<Point*>* Cluster::getPoints(){
return &this->points;
}
void Cluster::recenter(){
double x = 0, y = 0;
Point* new_center = new Point();
vector<Point*>::const_iterator itr = points.begin();
vector<Point*>::const_iterator itrEnd = points.end();
for (; itr != itrEnd; ++itr)
{
x += (*(*itr)).getX();
y += (*(*itr)).getY();
}
(*new_center).setX(x / points.size());
(*new_center).setY(y / points.size());
center = new_center;
}
const size_t Cluster::size() const {
return this->points.size();
}
bool Cluster::operator==(const Cluster& other) const {
vector<Point*>::const_iterator itr = points.begin();
vector<Point*>::const_iterator itrEnd = points.end();
if (other.size() != this->size() || !(*(other.getCenter()) == *(this->getCenter()))){
return false;
}
for (; itr != itrEnd; ++itr)
{
bool found = false;
vector<Point*>::const_iterator other_itr = other.points.begin();
vector<Point*>::const_iterator other_itrEnd = other.points.end();
for (; other_itr != other_itrEnd; ++other_itr){
if ((*(*itr)) == (*(*other_itr))){
found = true;
break;
}
}
if (!found) return false;
}
return true;
} | true |
90f0a45a77250c07806f9e85e40aa200ec452604 | C++ | manishhedau/Data-Structure-Algorithm | /Stack/5. infix_to_postfix_expression.cpp | UTF-8 | 1,798 | 3.75 | 4 | [
"MIT"
] | permissive | // Code By - Manish Hedau
#include<bits/stdc++.h>
using namespace std;
char my_stack[100];
int top = -1;
// push item in stack
void push(char x)
{
my_stack[++top] = x;
}
// pop item from stack
char pop()
{
if (top == -1)
return -1;
else
return my_stack[top--];
}
// checking priority for given operators
int priority(char x)
{
if (x == '(')
return 0;
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
cout << "Enter the expression :: ";
cin >> exp;
cout << exp << endl;
e = exp;
while (*e != '\0')
{
// operands, print
if (isalnum(*e))
cout << *e << " ";
else if (*e == '(') // for left paranthesis, then push
push(*e);
else if (*e == ')')
{
// right operator, then pop and print unitl found left paranthesis
while ((x = pop()) != '(')
cout << x << " ";
}
else
{
// for operator
// when operator is found then check priority of top and curr operator
//when top is higher precedance,
// if top>=curr =>then pop and print unitl found lower operator
while (priority(my_stack[top]) >= priority(*e))
cout << pop() << " ";
// push the curr operator in stack
push(*e);
}
// iterate over the next expression.
e++;
}
// pop everythings from stack and print.
while (top != -1)
{
cout << pop() << " ";
}
cout << endl;
return 0;
}
/*
Input :-
---------
(2*3+4*(5-6))
Output :-
-------
Enter the expression :: (2*3+4*(5-6))
2 3 * 4 5 6 - * +
*/ | true |
25b8bb4a0a5414f18a48652ebb5c81513e677dad | C++ | TEJASWI-TEJASWI/Data-Structure-Codes | /AP.cpp | UTF-8 | 304 | 2.953125 | 3 | [] | no_license |
/*
This program is for printing AP and it's sum of AP
*/
#include<iostream>
using namespace std;
int main()
{
int a ,n,d;
cin>>a;
cin>>n;
cin>>d;
for(int i=0;i<n;i++)
{
cout<<(a+i*d)<<endl;
}
cout<<"Sum of AP is " <<(n/2)*(a+(n)*d)<<endl;
}
| true |
aa6905eece9ada0695d372c9c122cb08fcd3b711 | C++ | dreamJarvis/Problem_Solving | /hackerRank_interViewKit/searching/temp.cpp | UTF-8 | 1,906 | 3.953125 | 4 | [] | no_license | /*Consider n machines which produce same type of items but at different rate i.e., machine 1 takes a1 sec to produce an item, machine 2 takes a2 sec to produce an item. Given an array which contains the time required by ith machine to produce an item. Considering all machine are working simultaneously, the task is to find minimum time required to produce m items.
reference : https://www.geeksforgeeks.org/minimum-time-required-produce-m-items/
hackerRank : minimum Time required
*/
#include <bits/stdc++.h>
using namespace std;
// brute force
long minTimeReq(vector<long> &arr, long goal){
int n = arr.size();
long t = 0;
while(true){
long task = 0;
for(int i = 0; i < n; i++)
task += (t/arr[i]);
if(task >= goal)
return t;
t++;
}
return t;
}
// efficient method uing binary search
int findWorkDone(vector<long> &arr, int time){
int n = arr.size();
long ans = 0;
for(auto i:arr)
ans += (time/i);
return ans;
}
long binarySearch(vector<long> &arr, int goal, int high){
long low = 1;
while(low < high){
long mid = (low+high)/2;
long workDone = findWorkDone(arr, mid);
if(workDone < goal)
low = mid+1;
else
high = mid;
}
return high;
}
long minTimeReqEffecient(vector<long> &arr, int goal){
int n = arr.size();
// maximum time required to get work done
long maxTime = INT_MIN;
for(auto i:arr)
maxTime = max(maxTime, i);
return binarySearch(arr, goal, maxTime*goal);
}
// Driver function
int main(){
// vector<long> arr({2, 3, 2});
// long goal = 10;
vector<long> arr({2, 3});
long goal = 5;
// vector<long> arr({1, 3, 4});
// long goal = 10;
// cout << minTimeReq(arr, goal) << endl;
cout << minTimeReqEffecient(arr, goal) << endl;
return 0;
}
/*
*/
| true |
9b21aff812e6b4749631836267d518180e3b7a96 | C++ | cs-topicosIA/IRIS | /RedNeuronal.cpp | UTF-8 | 7,573 | 2.71875 | 3 | [] | no_license | #include "RedNeuronal.h"
RedNeuronal::RedNeuronal()
{
nCapas = 0;
capas = 0;
neuronasXCapa = 0;
nEntradas = 0;
entradas = 0;
nSalidas = 0;
salidas = 0;
fa = 1;
nIteracions = 10;
maximoError = 0.1;
}
RedNeuronal::~RedNeuronal()
{
for(int i = 0; i < nCapas; ++i)
delete capas[i];
delete []capas;
for(int i = 0; i < neuronasXCapa[0]; ++i)
delete []entradas[i];
delete []entradas;
for(int i = 0; i < neuronasXCapa[nCapas - 1]; ++i)
delete []salidas[i];
delete []salidas;
delete []neuronasXCapa;
}
void RedNeuronal::ejecutar()
{
int errores;
bool retrocedo;
int minimo = 150;
bool sigoEntrenando = true;
for(int it = 0; it < nIteracions && sigoEntrenando; ++it)
{
errores = 0;
sigoEntrenando = false;
for(int entr = 0; entr < nEntradas; ++entr)
{
retrocedo = false;
copiarEntrada(entr);
for(int cap = 0; cap < nCapas - 1; ++cap)
avanzar(*capas[cap], *capas[cap + 1]);
verificarCapaFinal(entr, retrocedo);
if(retrocedo) ++ errores;//Cuenta las entradas q faltan ajustar
if(!retrocedo) continue;
sigoEntrenando = true;
actualizarErrorCapaFinal(entr);
for(int cap = nCapas - 2; cap > 0; --cap)
{
actualizarPeso(*capas[cap], *capas[cap + 1]);
actualizarError(*capas[cap], *capas[cap + 1]);
}
actualizarPeso(*capas[0], *capas[1]);
}
if(errores < minimo) {
minimo = errores;
guardarPesos(minimo,it);
}
cout << it << " " << errores << endl;
}
cout << "el minimo fue:" << minimo << endl;
}
RedNeuronal::RedNeuronal(int numeroCapas)
{
nCapas = numeroCapas;
neuronasXCapa = new int[nCapas];
cout << "Numero de neuronas en la capa de entrada: ";
cin >> neuronasXCapa[0];
for(int i = 1; i < nCapas - 1; ++i){
cout << "Numero de neuronas en la capa Oculta " << i << ": ";
cin >> neuronasXCapa[i];
}
cout << "Numero de neuronas en la capa de salida: ";
cin >> neuronasXCapa[nCapas - 1];
capas = new Capa*[nCapas];
//Inicializar Capas,excepto la ultima capa
for(int i = 0; i < nCapas - 1; ++i)
capas[i] = new Capa(neuronasXCapa[i] + 1, neuronasXCapa[i + 1] + 1);
capas[nCapas - 1] = new Capa(neuronasXCapa[nCapas - 1] + 1, 1);
fa = 0.5;
nIteracions = 100000;
maximoError = 0.2;
//Inicializar datos de prueba y salida
inicializarIOIris();
//Inicializar umbrales
inicializarUmbrales();
inicializarPesos();
//cargarPesosEntrenados();
}
void RedNeuronal::inicializarIOIris()
{
int nRegistros, salida;
ifstream lee("data/train.txt");
lee >> nRegistros;
nEntradas = nRegistros;
nSalidas = nRegistros;
entradas = new double*[nRegistros];
for(int i = 0; i < nRegistros; ++i)
entradas[i] = new double[4];
salidas = new double*[nRegistros];
for(int i = 0; i < nRegistros; ++i)
salidas[i] = new double[3];
double maximo = -10, minimo = 10;
for(int reg = 0; reg < nRegistros; ++reg)
{
for(int entr = 0; entr < 4; ++entr)
{
lee >> entradas[reg][entr];
if(entradas[reg][entr] > maximo) maximo = entradas[reg][entr];
if(entradas[reg][entr] < minimo) minimo = entradas[reg][entr];
}
lee >> salida;
salidas[reg][salida] = 1;
}
for(int reg = 0; reg < nRegistros; ++reg)
{
for(int entr = 0; entr < 4; ++entr)
entradas[reg][entr] = (entradas[reg][entr] - minimo) / (maximo - minimo);
}
lee.close();
}
void RedNeuronal::inicializarUmbrales()
{
for(int i = 0; i < nCapas; ++i){
capas[i]->u[0] = -1;
capas[i]->y[0] = -1;
}
}
void RedNeuronal::copiarEntrada(int pos)
{
copy(entradas[pos], entradas[pos] + neuronasXCapa[0], capas[0]->y + 1);
}
double RedNeuronal::funcionActivacion(double u)
{
return 1.0 /(1 + exp(-u));
//return tanh(u);
}
double RedNeuronal::derivadaFuncion(double u)
{
double eu = exp(u);
double rp = eu / pow(eu + 1, 2);
return rp;
//return 1.0 / pow(cosh(u), 2);
}
void RedNeuronal::avanzar(Capa &cOrigen, Capa &cDestino)
{
double suma;
for(int j = 1; j < cDestino.m; ++j)
{
suma = 0;
for(int i = 0; i < cOrigen.m; ++i)
suma += cOrigen.y[i] * cOrigen.peso[i][j];
cDestino.u[j] = suma;
cDestino.y[j] = funcionActivacion(suma);
}
}
void RedNeuronal::verificarCapaFinal(int sal, bool &retrocedo)
{
for(int neur = 0; neur < neuronasXCapa[nCapas - 1]; ++neur)
{
if(abs(salidas[sal][neur] - capas[nCapas - 1]->y[neur + 1]) > maximoError)
{
retrocedo = true;
return;
}
}
}
void RedNeuronal::actualizarErrorCapaFinal(int sal)
{
double dif;
for(int neur = 0; neur < neuronasXCapa[nCapas - 1]; ++neur)
{
dif = salidas[sal][neur] - capas[nCapas - 1]->y[neur + 1];
capas[nCapas - 1]->error[neur + 1] = dif * derivadaFuncion(capas[nCapas - 1]->u[neur + 1]);
}
}
void RedNeuronal::actualizarPeso(Capa &cOrigen, Capa &cDestino)
{
for(int i = 0; i < cOrigen.m; ++i)
for(int j = 1; j < cDestino.m; ++j)
cOrigen.peso[i][j] += (fa * cOrigen.y[i] * cDestino.error[j]);
}
void RedNeuronal::actualizarError(Capa &cOrigen, Capa &cDestino)
{
double suma;
for(int i = 1; i < cOrigen.m; ++i)
{
suma = 0;
for(int j = 1; j < cDestino.m; ++j)
suma += (cOrigen.peso[i][j] * cDestino.error[j]);
cOrigen.error[i] = derivadaFuncion(cOrigen.u[i]) * suma;
}
}
void RedNeuronal::inicializarPesos()
{
srand(time(0));
for(int cap = 0; cap < nCapas - 1; ++cap)
{
for(int m = 0; m < capas[cap]->m; ++m)
for(int n = 0; n < capas[cap]->n; ++n)
capas[cap]->peso[m][n] = 1.0 * (rand() % 2001 - 1000) / 1000;
}
}
void RedNeuronal::cargarPesosEntrenados()
{
int aux, m, n;
FILE *lee = fopen("pesos/pesos(32k-0.2)", "rb");
fread(&aux, sizeof(aux), 1, lee);
cout << "nerror " << aux<< endl;
fread(&aux, sizeof(aux), 1, lee);
cout << "it " << aux<< endl;
fread(&aux, sizeof(aux), 1, lee);
cout << "capas " << aux<< endl;
int a;
for(int cap = 0; cap < nCapas - 1; ++cap)
{
fread(&m, sizeof(m), 1, lee);
fread(&n, sizeof(n), 1, lee);
for(int m = 0; m < capas[cap]->m; ++m)
fread(capas[cap]->peso[m], sizeof(double), n, lee);
cout << m << " " << n << endl;
for(int m = 0; m < capas[cap]->m; ++m)
for(int n = 0; n < capas[cap]->n; ++n)
cout << capas[cap]->peso[m][n] << " ";
}
cout << "cargo todos los pesos" << endl;
fclose(lee);
}
void RedNeuronal::guardarPesos(int nError, int iteracion)
{
FILE *esc = fopen("pesos/pesosFinales", "wb");
fwrite(&nError, sizeof(nError), 1, esc);
fwrite(&iteracion, sizeof(iteracion), 1, esc);
fwrite(&nCapas, sizeof(nCapas), 1, esc);
for(int c = 0; c < nCapas - 1; ++c)
{
int m = neuronasXCapa[c] + 1;
int n = neuronasXCapa[c + 1] + 1;
fwrite(&m, sizeof(m), 1, esc);
fwrite(&n, sizeof(n), 1, esc);
for(int i = 0; i < m; ++i)
fwrite(capas[c]->peso[i], sizeof(double), n, esc);
}
fclose(esc);
}
| true |
822a82d40960bbb1f0a486bef711bc4c8091ef93 | C++ | ameks94/PrataTasks | /5.6.cpp | UTF-8 | 863 | 2.984375 | 3 | [] | no_license | #include "CheckInput.h"
#include <array>
const short year = 3;
void main ()
{
char **month = new char*[12];
month[0] = "January: ";
month[1] = "February: ";
month[2] = "March: ";
month[3] = "April: ";
month[4] = "May: ";
month[5] = "June: ";
month[6] = "July: ";
month[7] = "August: ";
month[8] = "September: ";
month[9] = "October: ";
month[10] = "November: ";
month[11] = "January: ";
int volume[year][12];
long summ_all = 0;
long summ[year] = {};
for (short y = 0; y < year; y++)
{
system("cls");
cout << y + 1 << " year:" << endl;
for (short m = 0; m < 12; m++)
{
input(&volume[y][m], month[m]);
summ_all += volume[y][m];
summ[y] += volume[y][m];
}
cout << "The total amount for " << y + 1 << " year: "
<< summ[y] << endl;
getch();
}
cout << "Total sales for the year: " << summ_all <<endl;
system("pause");
}
| true |
8b0310938283ab9f32b4806520e722fd2fd62c19 | C++ | shreyasoni15/Assignment-1 | /lab5_q1.cpp | UTF-8 | 479 | 3.890625 | 4 | [] | no_license | //WAP to find maximum number between two numbers
//library
#include <iostream>
using namespace std;
int main ()
{
//Declare variables
int num1,num2;
cout<< " Enter num1 = ";
cin>> num1;
cout<< " Enter num2 = ";
cin>> num2;
//Specify condition for output
if (num1> num2)
{
cout<< " The maximum number between the two entered numbers is = " << num1;
}
else
{
cout<< " The maximum number between the two entered numbers is = " << num2;
}
return 0;
}
| true |
1ef4e3cf4cbaac59cb81b5a275989e87450e41f8 | C++ | Stackleon/BasicPractice | /language/c_plus/carplay_ie.cpp | UTF-8 | 6,633 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <vector>
#include <string>
#include <stdint.h>
#include <sstream>
#include <iomanip>
using namespace std;
#define MAX_PROPERTY_VALUE_SIZE 96
#define CARPLAY_ELEMENT_SIZE 7
#define CARPLAY_ELEMENT_ID_FLAGS 0x00
#define CARPLAY_ELEMENT_ID_NAME 0x01
#define CARPLAY_ELEMENT_ID_MANUFACTURE 0x02
#define CARPLAY_ELEMENT_ID_MODEL 0x03
#define CARPLAY_ELEMENT_ID_OUI 0x04
#define CARPLAY_ELEMENT_ID_BLUETOOTH_MAC 0x05 //
#define CARPLAY_ELEMENT_ID_DEVICE_ID 0x06
struct CarplayElement {
uint8_t id;
uint8_t len;
uint8_t* payload;
};
struct CarplayOverallElement {
uint8_t id;
uint8_t len;
uint8_t* OUI;
uint8_t sub_type;
const CarplayElement* elements;
};
#define NAME "Ford"
#define MANUFACTURE "Yanfeng,Automotive"
#define BT_ADDRESS "3E:A0:20:5A:20:71"
#define MODEL {0x50, 0x55, 0x31, 0x37, 0x32, 0x33, 0x55, 0x41}
#define OUI_SIZE 3
std::vector<uint8_t> convertBtaddress(const std::string &s, char c) {
std::vector<uint8_t> components;
size_t startPos = 0;
size_t matchPos;
while ((matchPos = s.find(c, startPos)) != std::string::npos) {
char* temp = nullptr;
const char* target = s.substr(startPos, matchPos - startPos).c_str();
uint8_t value = (uint8_t) strtol( target, &temp, 16);
components.push_back(value);
startPos = matchPos + 1;
}
if (startPos <= s.length()) {
char* temp = nullptr;
const char* target = s.substr(startPos).c_str();
uint8_t value = (uint8_t)strtol(target, &temp, 16);
components.push_back(value);
}
return components;
}
std::vector<uint8_t> convertStr(const std::string & src) {
std::vector<uint8_t> target;
target.assign(src.begin(), src.end());
return target;
}
void printf(const std::vector<uint8_t> src) {
cout << "src size:" << src.size() << endl;
cout << "[";
for(uint8_t a : src) {
printf("%02x", a);
}
cout << "]" << endl;
}
std::string convertChar(const uint8_t* from, const uint8_t length) {
std::string src(from, from+length);
std::stringstream ss;
ss << std::hex;
ss << std::setfill('0');
for (uint8_t b : src) {
ss << std::setw(2) << static_cast<unsigned int>(b);
}
const std::string src_as_string = ss.str();
return src_as_string;
}
void convertCarplayElement(stringstream& ss, const CarplayElement& from) {
ss << std::setw(2) << static_cast<unsigned int>(from.id);
ss << std::setw(2) << static_cast<unsigned int>(from.len);
const uint8_t* value = const_cast<uint8_t *>(from.payload);
printf("[%02x-%02x-", from.id, from.len);
for(int i = 0; i < from.len; i++) {
printf("%02x", *value);
ss << std::setw(2) << static_cast<unsigned int>(*value);
value++;
}
printf("]\n");
free(from.payload);
}
std::string convertCarplayIE(const CarplayOverallElement& from, uint8_t element_size) {
std::stringstream ss;
ss << std::hex;
ss << std::setfill('0');
ss << std::setw(2) << static_cast<unsigned int>(from.id);
ss << std::setw(2) << static_cast<unsigned int>(from.len);
const uint8_t* oui = from.OUI;
for(int i = 0; i < 3; i++) {
ss << std::setw(2) << static_cast<unsigned int>(*oui);
oui++;
}
free(from.OUI);
ss << std::setw(2) << static_cast<unsigned int>(from.sub_type);
const CarplayElement* elements = from.elements;
for (int i = 0; i< element_size; i++) {
convertCarplayElement(ss, *elements);
elements++;
}
const std::string result = ss.str();
return result;
}
std::string createBeaconForCarplay() {
const std::vector<uint8_t> bt_addr_vector = convertBtaddress(BT_ADDRESS, ':');
//printf(bt_addr_vector);
CarplayOverallElement overall_elements;
memset(&overall_elements, 0, sizeof(overall_elements));
const uint8_t apple_oui[OUI_SIZE] = {0x00, 0xA0, 0x40};
overall_elements.id = 0xDD;
overall_elements.OUI = (uint8_t *)malloc(sizeof(uint8_t)*OUI_SIZE);
memcpy(overall_elements.OUI, apple_oui, OUI_SIZE);
overall_elements.sub_type = 0x00;
CarplayElement elements[CARPLAY_ELEMENT_SIZE];
int payload_size = 0;
int element_default_len = 2;
for(int i = 0; i < CARPLAY_ELEMENT_SIZE; i++) {
CarplayElement element;
vector<uint8_t> value;
uint8_t* payload = nullptr;
memset(&element, 0, sizeof(element));
switch (i)
{
case CARPLAY_ELEMENT_ID_FLAGS:
element.id = CARPLAY_ELEMENT_ID_FLAGS;
value = {0x00, 0x40};
element.payload = (uint8_t*)malloc(sizeof(uint8_t)*value.size());
memcpy(element.payload, value.data(), value.size());
element.len = value.size();
payload_size += (value.size() + element_default_len);
break;
case CARPLAY_ELEMENT_ID_NAME:
element.id = CARPLAY_ELEMENT_ID_NAME;
value = convertStr(NAME);
element.payload = (uint8_t*)malloc(sizeof(uint8_t)*value.size());
memcpy(element.payload, value.data(), value.size());
element.len = value.size();
payload_size += (value.size() + element_default_len);
break;
case CARPLAY_ELEMENT_ID_MANUFACTURE:
element.id = CARPLAY_ELEMENT_ID_MANUFACTURE;
value = convertStr(MANUFACTURE);
element.payload = (uint8_t*)malloc(sizeof(uint8_t)*value.size());
memcpy(element.payload, value.data(), value.size());
element.len = value.size();
payload_size += (value.size() + element_default_len);
break;
case CARPLAY_ELEMENT_ID_MODEL:
element.id = CARPLAY_ELEMENT_ID_MODEL;
value = MODEL;
element.payload = (uint8_t*)malloc(sizeof(uint8_t)*value.size());
memcpy(element.payload, value.data(), value.size());
element.len = value.size();
payload_size += (value.size() + element_default_len);
break;
case CARPLAY_ELEMENT_ID_OUI:
element.id = CARPLAY_ELEMENT_ID_OUI;
element.payload = (uint8_t*)malloc(sizeof(uint8_t)*OUI_SIZE);
memcpy(element.payload, apple_oui, OUI_SIZE);
element.len = OUI_SIZE;
payload_size += (OUI_SIZE + element_default_len);
break;
case CARPLAY_ELEMENT_ID_BLUETOOTH_MAC:
case CARPLAY_ELEMENT_ID_DEVICE_ID:
element.id = i+1;
value = bt_addr_vector;
element.payload = (uint8_t*)malloc(sizeof(uint8_t)*value.size());
memcpy(element.payload, value.data(), value.size());
element.len = value.size();
payload_size += (value.size() + element_default_len);
break;
default:
break;
}
elements[i] = element;
}
overall_elements.len = payload_size;
overall_elements.elements = elements;
cout << convertCarplayIE(overall_elements, CARPLAY_ELEMENT_SIZE) << endl;
}
int main() {
//printf(convertStr(NAME));
const uint8_t src[3] = {0x11, 0xA0, 0x20};
/**
cout << convertChar(src, 3) << endl;
struct CarplayOverallElement ie;
memset(&ie, 0, sizeof(ie));
cout << convertStruct((uint8_t*)&ie, 3) << endl;
**/
createBeaconForCarplay();
return 0;
}
| true |
851eae256bba078b7993c5a478f4217a092964ec | C++ | VerparDev/Quadris | /backup/sblock.cc | UTF-8 | 607 | 2.53125 | 3 | [] | no_license | #include <vector>
#include "sblock.h"
#include "coord.h"
SBlock::SBlock(bool heavy): Block{'S', Coord{0,5}, heavy}/*: Block{'L', std::vector<Coord> = [Coord{0,3}, Coord{0,4}, Coord{0,5}, Coord{1,5}], Coord{1,1}*/ {
// symbol = 'S';
//this coord is the tail end of the long part of the L
coords.emplace_back(Coord{0,3});
//this coord is the middle end of the long part of the L
coords.emplace_back(Coord{0,4});
//this coord is the corner cell of the L
coords.emplace_back(Coord{1,4});
//this coord is the short tail end of the L
coords.emplace_back(Coord{1,5});
// corner = Coord{0,5};
}
| true |
ff6bcf7500a5573d79fa847b6e1a9afdcaf89052 | C++ | patryk0504/IMN_2020 | /lab4/main.cpp | UTF-8 | 5,947 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <stdio.h>
#include <array>
#include <thread>
//przyjete wartosci parametrow w zadaniu
double eps = 1.;
double delta = 0.1;
const int nx = 150;
const int ny = 100;
double V1 = 10.;
double V2 = 0.;
double xmax = delta*nx;
double ymax = delta*ny;
double sigmax = 0.1 * xmax;
double sigmay = 0.1 * ymax;
double TOL = std::pow(10,-8);
//funkcje gestosci
double gestosc1(double x, double y){
double wykladnik = -1.*std::pow((x-0.35*xmax),2)/(sigmax*sigmax) - 1.*std::pow((y-0.5*ymax),2)/(sigmay*sigmay);
return std::exp(wykladnik);
}
double gestosc2(double x, double y){
double wykladnik = -1.*std::pow((x-0.65*xmax),2)/(sigmax*sigmax) - 1.*std::pow((y-0.5*ymax),2)/(sigmay*sigmay);
return -std::exp(wykladnik);
}
//metody
void globalna(double wg, std::string filename_S, std::string filename_V, std::string filename_Err);
void lokalna(double wl, std::string filename_S);
int main() {
//zwykle wywolania (jezeli bylby problem z std::thread)
std::cout<<"Program is running... Please wait.\n"<<std::endl;
globalna(0.6, "S_06_global.txt", "V_06_global.txt", "Err_06_global.txt");
globalna(1.0, "S_1_global.txt", "V_1_global.txt", "Err_1_global.txt");
lokalna(1.0,"S_1_lokal.txt");
lokalna(1.4,"S_1_4_lokal.txt");
lokalna(1.8,"S_1_8_lokal.txt");
lokalna(1.9,"S_1_9_lokal.txt");
////std::thread
// std::cout<<"Program is running... Please wait.\n"<<std::endl;
// std::thread th1 (globalna,0.6, "S_06_global.txt", "V_06_global.txt", "Err_06_global.txt");
// std::thread th2 (globalna,1.0, "S_1_global.txt", "V_1_global.txt", "Err_1_global.txt");
// std::thread th3 (lokalna,1.0,"S_1_lokal.txt" );
// std::thread th4 (lokalna,1.4,"S_1_4_lokal.txt");
// th1.join();
// th2.join();
// th3.join();
// th4.join();
// std::thread th5 (lokalna,1.8,"S_1_8_lokal.txt" );
// std::thread th6 (lokalna,1.9,"S_1_9_lokal.txt" );
// th5.join();
// th6.join();
//////////////////////////////////////////////////////////////////////////////////////////////////
return 0;
}
void globalna(double wg, std::string filename_S, std::string filename_V, std::string filename_Err){
std::cout<<"Relaksacja globalna dla wg = " + std::to_string(wg) + " ...\n";
FILE *fp_S = fopen(filename_S.c_str(),"w");
FILE *fp_V = fopen(filename_V.c_str(),"w");
FILE *fp_Err = fopen(filename_Err.c_str(),"w");
double Vn [nx+5][nx+5] = {0.};
double P [nx+5][ny+5] = {0.};
double Vs [nx+5][ny+5] = {0.};
//tablica gestosci i wstepne rozwiazania Vs Vn
for(int i=0; i<nx+1; i++){
Vs[i][0] = V1;
Vn[i][0] = V1;
for(int j=0; j<ny+1; j++){
P[i][j] = gestosc1(i*delta, j*delta) + gestosc2(i*delta, j*delta);
}
}
int count = 0;
double S[100000] = {0.};
S[0] = 0.;
do{
count++;
//I etap - elementy poza brzegowymi
for(int i=1; i<nx; i++){
for(int j = 1; j<ny; j++){
Vn[i][j] = 1/4. * (Vs[i+1][j] + Vs[i-1][j] + Vs[i][j+1] + Vs[i][j-1] + (delta*delta)/eps * P[i][j]);
// std::cout<<Vn[i][j]<<std::endl;
}
}
//II etap - WB Neumanna
for(int j=1; j<ny+1; j++){
Vn[0][j] = Vn[1][j];
Vn[nx][j] = Vn[nx-1][j];
}
//III etap - mieszamy rozwiazania
for(int i=0; i<nx+1; i++){
for(int j=0; j<ny+1; j++){
Vs[i][j]=(1.-wg) * Vs[i][j] + wg * Vn[i][j];
}
}
//warunek stopu
for(int i=0; i<nx; i++){
for(int j=0; j<ny; j++){
S[count] += (delta*delta) * (0.5 * std::pow((Vn[i+1][j] - Vn[i][j])/delta, 2) + 0.5*std::pow((Vn[i][j+1]-Vn[i][j])/delta, 2 ) - (P[i][j]*Vn[i][j]) );
}
}
fprintf(fp_S,"%d\t%12.6g\n",count-1,S[count]);
}while(std::abs((S[count] - S[count-1]) / S[count-1]) > TOL);
// auto **Verr = new double * [nx+1];
double Verr[nx+6][nx+6] = {0.};
//obliczamy blad
for(int i=1; i<nx; i++){
for(int j=1; j<ny; j++){
Verr[i][j] = (Vn[i+1][j] - 2.*Vn[i][j] + Vn[i-1][j]) / (delta*delta) + (Vn[i][j+1] - 2.*Vn[i][j] + Vn[i][j-1])/(delta*delta) + P[i][j]/eps;
}
}
//zapisujemy rzowiazania V i blad do pliku
for(int i=1; i<nx; i++){
for(int j=1; j<ny; j++){
fprintf(fp_V,"%12.6g\t%12.6g\t%12.6g\n",i*delta, j*delta, Vn[i][j]);
fprintf(fp_Err,"%12.6g\t%12.6g\t%12.6g\n",i*delta, j*delta, Verr[i][j]);
}
}
std::cout<<"... Done\n";
}
void lokalna(double wl, std::string filename_S){
std::cout<<"Relaksacja lokalna dla wl = " + std::to_string(wl) + " ...\n";
FILE *fp_S = fopen(filename_S.c_str(),"w");
double V [nx+5][ny+5] = {0.};
double P [nx+5][ny+5] = {0.};
//tablica gestosci i wstepne rozwiazania Vs Vn
for(int i=0; i<nx+1; i++){
for(int j=0; j<ny+1; j++){
V[i][0] = V1;
P[i][j] = gestosc1(i*delta, j*delta) + gestosc2(i*delta, j*delta);
}
}
int count = 0;
double S[100000] = {0.};
S[0] = 0.;
do{
count++;
for(int i=1; i<nx; i++){
for(int j=1; j<ny; j++){
V[i][j] = (1-wl) * V[i][j] + (wl*0.25)*(V[i+1][j] + V[i-1][j] + V[i][j+1] + V[i][j-1] + (delta*delta)/eps * P[i][j]);
}
}
for(int j=1; j<ny; j++){
V[0][j] = V[1][j];
V[nx][j] = V[nx-1][j];
}
//warunek stopu
for(int i=0; i<nx; i++){
for(int j=0; j<ny; j++){
S[count] += (delta*delta) * (0.5 * std::pow((V[i+1][j] - V[i][j])/delta, 2) + 0.5*std::pow((V[i][j+1]-V[i][j])/delta, 2 ) - (P[i][j]*V[i][j]) );
}
}
fprintf(fp_S,"%d\t%12.6g\n",count-1,S[count]);
}while(std::abs((S[count] - S[count-1]) / S[count-1]) > TOL);
std::cout<<"... Done\n";
} | true |
8c7b5b7e087a18d2d1ee30e7e4c3a75ba8503b29 | C++ | ManasviGoyal/Competitive-Programming | /FB Hacker Cup 45 points first pgm.cpp | UTF-8 | 1,316 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
void step2and3(int, int, int, int, string, string);
void step4(int, int, int, int, string, string);
void step5(int, int, int, int, string, string);
void step6(int, int, int, int, string, string);
int main()
{
int a,b,i,j;
string A, B;
i = j = 1;
cin>>A>>B;
a = A.length();
b = B.length();
step2and3(i,j,a,b,A,B);
return 0;
}
void step2and3(int i, int j, int a, int b, string A, string B)
{
int c;
c = 0;
cout<<endl<<i<<endl<<j;
if(i>a)
{
cout<<endl<<"TRUE";
c++;
}
else if(j>b)
{
cout<<endl<<"FALSE";
c++;
}
if(c == 0)
{
step4(i, j, a, b, A, B);
step5(i, j, a, b, A, B);
step6(i, j, a, b, A, B);
}
}
void step4(int i, int j, int a, int b, string A, string B)
{
if(A[i-1] == B[i-1])
{
i++;
j++;
step2and3(i,j,a,b,A,B);
}
else
{
step5(i, j, a, b, A, B);
}
}
void step5(int i, int j, int a, int b, string A, string B)
{
if(i == 1)
{
j++;
step2and3(i,j,a,b,A,B);
}
else
{
step6(i, j, a, b, A, B);
}
}
void step6(int i, int j, int a, int b, string A, string B)
{
i = 1;
step2and3(i,j,a,b,A,B);
}
| true |
d786a3d45673d3d86b7466e61d23c394219c9de9 | C++ | cekaem/chess2.0 | /Board.cc | UTF-8 | 7,399 | 2.875 | 3 | [] | no_license | #include "Board.h"
#include "utils/Utils.h"
Square Square::InvalidSquare = {static_cast<size_t>(-1),
static_cast<size_t>(-1)};
std::ostream& operator<<(std::ostream& ostr, const Board& move) {
ostr << move.createFEN();
return ostr;
}
Board::Board(const std::string& fen) {
std::array<char, kBoardSize> row;
row.fill(0x0);
squares_.fill(row);
std::string::size_type space_position = fen.find(' ');
if (space_position == std::string::npos) {
throw InvalidFENException(fen);
}
std::string fields = fen.substr(0, space_position);
std::string partial_fen = fen.substr(space_position);
setFiguresFromFEN(fields);
setMiscDataFromFEN(partial_fen);
}
void Board::setFiguresFromFEN(std::string partial_fen) {
for (int i = kBoardSize - 1; i >= 0; --i) {
std::string one_line;
if (i > 0) {
std::string::size_type slash_position = partial_fen.find('/');
if (slash_position == std::string::npos) {
throw InvalidFENException(partial_fen);
}
one_line = partial_fen.substr(0, slash_position);
partial_fen = partial_fen.substr(slash_position + 1);
} else {
one_line = partial_fen;
}
setFiguresForOneLineFromFEN(one_line, i);
}
}
void Board::setFiguresForOneLineFromFEN(const std::string& one_line, size_t line) {
size_t current_file = 0;
for (const char c: one_line) {
if (current_file >= kBoardSize) {
throw InvalidFENException(one_line);
}
if (c >= '1' && c <= '8') {
current_file += c - '0';
} else {
if (c != 'P' && c != 'p' && c != 'N' && c != 'n' && c != 'B' && c != 'b' &&
c != 'R' && c != 'r' && c != 'Q' && c != 'q' && c != 'K' && c != 'k') {
throw InvalidFENException(one_line);
}
squares_[current_file][line] = c;
++current_file;
}
}
}
void Board::setCastlingsFromFEN(const std::string& partial_fen) {
if (partial_fen.empty() == true || partial_fen.size() > 4) {
throw InvalidFENException(partial_fen);
}
for (const char c: partial_fen) {
switch (c) {
case 'K':
castlings_ |= (1 << static_cast<size_t>(Castling::K));
break;
case 'k':
castlings_ |= (1 << static_cast<size_t>(Castling::k));
break;
case 'Q':
castlings_ |= (1 << static_cast<size_t>(Castling::Q));
break;
case 'q':
castlings_ |= (1 << static_cast<size_t>(Castling::q));
break;
case '-':
if (partial_fen.size() != 1) {
throw InvalidFENException(partial_fen);
}
break;
default:
throw InvalidFENException(partial_fen);
}
}
}
void Board::setMiscDataFromFEN(std::string partial_fen) {
const char side_to_move = partial_fen[1];
switch (side_to_move) {
case 'w':
white_to_move_ = true;
break;
case 'b':
white_to_move_ = false;
break;
default:
throw InvalidFENException(partial_fen);
}
partial_fen = partial_fen.substr(3);
std::string::size_type space_position = partial_fen.find(' ');
if (space_position == std::string::npos) {
throw InvalidFENException(partial_fen);
}
std::string castlings = partial_fen.substr(0, space_position);
setCastlingsFromFEN(castlings);
partial_fen = partial_fen.substr(space_position);
if (partial_fen.size() < 6 || partial_fen[0] != ' ') { // 6 == length(" - 0 0")
throw InvalidFENException(partial_fen);
}
partial_fen = partial_fen.substr(1);
space_position = partial_fen.find(' ');
if (space_position == std::string::npos) {
throw InvalidFENException(partial_fen);
}
std::string en_passant_square = partial_fen.substr(0, space_position);
if (en_passant_square.size() == 1) {
if (en_passant_square[0] != '-') {
throw InvalidFENException(partial_fen);
}
} else {
if (Square::isValid(en_passant_square) == false ||
(white_to_move_ && en_passant_square[1] != '6') ||
(!white_to_move_ && en_passant_square[1] != '3')) {
throw InvalidFENException(partial_fen);
}
en_passant_target_square_ = en_passant_square;
}
partial_fen = partial_fen.substr(space_position);
if (partial_fen.size() < 4 || partial_fen[0] != ' ') { // 4 == length(" 0 0")
throw InvalidFENException(partial_fen);
}
partial_fen = partial_fen.substr(1);
space_position = partial_fen.find(' ');
if (space_position == std::string::npos) {
throw InvalidFENException(partial_fen);
}
std::string halfmove_clock_str = partial_fen.substr(0, space_position);
if (utils::str_2_uint(halfmove_clock_str, halfmove_clock_) == false) {
throw InvalidFENException(partial_fen);
}
partial_fen = partial_fen.substr(space_position);
if (partial_fen.size() < 2 || partial_fen[0] != ' ') { // 2 == length(" 0")
throw InvalidFENException(partial_fen);
}
std::string fullmove_number_str = partial_fen.substr(1);
if (utils::str_2_uint(fullmove_number_str, fullmove_number_) == false) {
throw InvalidFENException(partial_fen);
}
}
std::string Board::createFEN() const {
std::stringstream fen;
writeFiguresToFEN(fen);
writeMiscDataToFEN(fen);
return fen.str();
}
void Board::writeFiguresToFEN(std::stringstream& fen) const {
for (int row = kBoardSize - 1; row >= 0; --row) {
int empty_lines = 0;
for (size_t line = 0; line < kBoardSize; ++line) {
if (squares_[line][row] == 0x0) {
++empty_lines;
} else {
if (empty_lines > 0) {
fen << empty_lines;
empty_lines = 0;
}
fen << squares_[line][row];
}
}
if (empty_lines > 0) {
fen << empty_lines;
}
if (row > 0) {
fen << "/";
}
}
}
void Board::writeMiscDataToFEN(std::stringstream& fen) const {
if (white_to_move_) {
fen << " w ";
} else {
fen << " b ";
}
if (castlings_ == 0) {
fen << "-";
} else {
if (canCastle(Castling::K)) {
fen << "K";
}
if (canCastle(Castling::Q)) {
fen << "Q";
}
if (canCastle(Castling::k)) {
fen << "k";
}
if (canCastle(Castling::q)) {
fen << "q";
}
}
if (en_passant_target_square_ == Square::InvalidSquare) {
fen << " - ";
} else {
fen << " " << en_passant_target_square_.letter << en_passant_target_square_.number << " ";
}
fen << halfmove_clock_ << " " << fullmove_number_;
}
bool Board::operator==(const std::string& fen) const {
Board second(fen);
return squares_ == second.squares_ &&
en_passant_target_square_ == second.en_passant_target_square_ &&
halfmove_clock_ == second.halfmove_clock_ &&
fullmove_number_ == second.fullmove_number_ &&
castlings_ == second.castlings_ &&
white_to_move_ == second.white_to_move_;
}
char Board::getSquare(const std::string& square) const {
if (square.size() != 2) {
throw InvalidSquareException(square);
}
size_t line = square[0] - 'a';
size_t row = square[1] - '1';
if (line >= 8 || row >= 8) {
throw InvalidSquareException(square);
}
return squares_[line][row];
}
void Board::resetCastlings(bool for_white) {
if (for_white) {
resetCastling(Castling::Q);
resetCastling(Castling::K);
} else {
resetCastling(Castling::q);
resetCastling(Castling::k);
}
}
bool Board::canCastle(Castling castling) const {
return (castlings_ & (1 << static_cast<size_t>(castling))) != 0 ;
}
| true |
8fcc47186cd0ad6450950ba8d3f42fb52cf3175f | C++ | youngar/omtalk | /om/om/include/om/Om/Array.h | UTF-8 | 1,216 | 2.75 | 3 | [] | no_license | #ifndef OM_OM_ARRAY_H
#define OM_OM_ARRAY_H
#include <cstdint>
#include <om/Om/ArrayLayout.h>
#include <om/Om/ObjectHeader.h>
#include <om/Om/SlotProxy.h>
namespace om::om {
struct Array {
static const ObjectType TYPE = ObjectType::ARRAY;
static std::size_t allocSize(Type type, std::size_t length) noexcept {
return getSize(type) * length;
}
explicit Array(gc::Ref<ArrayLayout> layout, std::size_t length)
: header(TYPE, layout.reinterpret<Object>()), length(length) {}
ArrayLayout &layout() const noexcept {
return header.layout()->as<ArrayLayout>();
}
Type elementType() const noexcept { return layout().elementType; }
std::size_t size() const noexcept { return allocSize(elementType(), length); }
template <typename VisitorT, typename... Args>
void walk(VisitorT &visitor, Args... args) noexcept {
header.walk(visitor, args...);
if (elementType() == Type::ref) {
std::uintptr_t *ptr = data;
std::uintptr_t *end = data + length;
while (ptr < end) {
visitor.visit(SlotProxy::fromPtr(ptr), args...);
++ptr;
}
}
}
ObjectHeader header;
std::size_t length;
std::uintptr_t data[0];
};
} // namespace om::om
#endif | true |
27f0b05832597efbf462c4830f6a9d22a4cf7ac9 | C++ | RossBlakeney/SortingAlgsCompCpp | /AlgsAndDataStructures/AlgsAndDataStructures/BaseSorter.cpp | UTF-8 | 1,349 | 2.921875 | 3 | [] | no_license | #include "StdAfx.h"
#include "BaseSorter.h"
BaseSorter::BaseSorter(void)
{
}
BaseSorter::~BaseSorter(void)
{
}
void BaseSorter::printResults(int methodTag, vector<int> vectorToPrint)
{
switch (methodTag)
{
case INSERTION_SORT:
printf("Insertion sort results:\n");
break;
case MERGE_SORT:
printf("Merge sort results:\n");
break;
default:
break;
}
if (vectorToPrint.size() > 15)
{
printf(" [ %i %i %i %i %i ... %i %i %i %i %i ... %i %i %i %i %i ]\n",
vectorToPrint[0],
vectorToPrint[1],
vectorToPrint[2],
vectorToPrint[3],
vectorToPrint[4],
vectorToPrint[vectorToPrint.size() / 2 - 2],
vectorToPrint[vectorToPrint.size() / 2 - 1],
vectorToPrint[vectorToPrint.size() / 2],
vectorToPrint[vectorToPrint.size() / 2 + 1],
vectorToPrint[vectorToPrint.size() / 2 + 2],
vectorToPrint[vectorToPrint.size() - 5],
vectorToPrint[vectorToPrint.size() - 4],
vectorToPrint[vectorToPrint.size() - 3],
vectorToPrint[vectorToPrint.size() - 2],
vectorToPrint[vectorToPrint.size() - 1]
);
}
else
{
printf(" [ ");
for (vector<int>::iterator it = vectorToPrint.begin(); it != vectorToPrint.end(); ++it)
{
printf("%i", *it);
if (it < vectorToPrint.end() - 1)
{
printf(", ");
}
}
printf(" ]\n");
}
} | true |
cfd63d4d7d907ca6df49c982ce11bbe1a83f6cd0 | C++ | ZhiqWu/pat-1 | /1152 Google Recruitment.cpp | UTF-8 | 515 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <string>
using namespace std;
int N,L;
string s;
bool prime(int n) {
if(n == 1) return false;
else if(n == 2) return true;
else {
int e = sqrt(n);
for(int i = 2; i <= e; i ++)
if(n % i == 0)
return false;
return true;
}
}
int main() {
cin >> N >> L >> s;
for(int i = 0; i <= N - L; i ++) {
int x = stoi(s.substr(i,L));
if(prime(x)) {
cout << s.substr(i,L);
return 0;
}
}
cout << "404" << endl;
return 0;
}
| true |
25377a4ea55ed073e5d5cae627679f8152a2822b | C++ | muniatnoshin453/CompilerDesign | /problem_14.cpp | UTF-8 | 2,304 | 2.875 | 3 | [] | no_license | #include"stdio.h"
#include"conio.h"
#include"string.h"
int i=1,j=0,no=0,tmpch=90;
char str[100],left[15],right[15];
void findopr();
void explore();
void fleft(int);
void fright(int);
struct exp
{
int pos;
char op;
} k[15];
int main()
{
printf("\t\tQuadruple CODE GENERATION\n\n");
printf("Enter the Expression :");
scanf("%s",str);
printf("The code:\t\t \n");
findopr();
explore();
getch();
}
void findopr()
{
for(i=0; str[i]!='\0'; i++)
if(str[i]==':')
{
k[j].pos=i;
k[j++].op=':';
}
for(i=0; str[i]!='\0'; i++)
if(str[i]=='/')
{
k[j].pos=i;
k[j++].op='/';
}
for(i=0; str[i]!='\0'; i++)
if(str[i]=='*')
{
k[j].pos=i;
k[j++].op='*';
}
for(i=0; str[i]!='\0'; i++)
if(str[i]=='+')
{
k[j].pos=i;
k[j++].op='+';
}
for(i=0; str[i]!='\0'; i++)
if(str[i]=='-')
{
k[j].pos=i;
k[j++].op='-';
}
}
void explore()
{
i=1;
while(k[i].op!='\0')
{
fleft(k[i].pos);
fright(k[i].pos);
str[k[i].pos]=tmpch--;
printf("\t%c := %s%c%s\t\t",str[k[i].pos],left,k[i].op,right);
for(j=0; j <strlen(str); j++)
if(str[j]!='$')
printf("\n");
i++;
}
fright(-1);
if(no==0)
{
fleft(strlen(str));
printf("\t%s := %s",right,left);
getch();
}
printf("\t%s := %c",right,str[k[--i].pos]);
getch();
}
void fleft(int x)
{
int w=0,flag=0;
x--;
while(x!= -1 &&str[x]!= '+' &&str[x]!='*'&&str[x]!='='&&str[x]!='\0'&&str[x]!='-'&&str[x]!='/'&&str[x]!=':')
{
if(str[x]!='$'&& flag==0)
{
left[w++]=str[x];
left[w]='\0';
str[x]='$';
flag=1;
}
x--;
}
}
void fright(int x)
{
int w=0,flag=0;
x++;
while(x!= -1 && str[x]!= '+'&&str[x]!='*'&&str[x]!='\0'&&str[x]!='='&&str[x]!=':'&&str[x]!='-'&&str[x]!='/')
{
if(str[x]!='$'&& flag==0)
{
right[w++]=str[x];
right[w]='\0';
str[x]='$';
flag=1;
}
x++;
}
}
//x:=-a*b+-a*b
| true |
0f23abb32a69a98dd029e3649d0005f8dc44818a | C++ | BullHacks3/Competitive_Programming | /Hackerrank/Algorithms/2.Implementation/17_Picking_Numbers.cpp | UTF-8 | 578 | 2.921875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void picking_numbers(int k[],int s)
{
sort(k,k+s);
int count=0;
int max=0;
for(int i=0;i<s;i++)
{
count=0;
for(int j=i+1;j<s;j++)
{
if(abs(k[i]-k[j])==1 || abs(k[i]-k[j])==0)
count++;
else
{
break;
}
}
if(max<count)
{
max=count;
}
}
cout<<max+1<<endl;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
picking_numbers(arr,n);
return 0;
} | true |
c055b12bd5a541201eae39e4fd4aeb6abe4288b1 | C++ | MESH-Model/MESH_Project_Baker_Creek | /Model/Ostrich/Interpolator.cpp | UTF-8 | 4,837 | 2.75 | 3 | [] | no_license | /******************************************************************************
File : Interpolator.h
Author : L. Shawn Matott and James Craig
Copyright : 2004, L. Shawn Matott and James Craig
A class that uses radial basis function to interpolates the value at a given
point, based on known values at a finite set of points.
Version History
05-25-04 lsm created
******************************************************************************/
#include <math.h>
#include <string.h>
#include "Interpolator.h"
#include "Exception.h"
#include "Utility.h"
/******************************************************************************
CTOR
******************************************************************************/
Interpolator::Interpolator(int nmax)
{
int i;
m_MaxOrder = nmax;
//allocate memory
m_b = new double[nmax];
m_A = new double*[nmax];
m_Ainv = new double*[nmax];
for(i = 0; i < nmax; i++)
{
m_A[i] = new double[nmax];
m_Ainv[i] = new double[nmax];
}
MEM_CHECK(m_Ainv[i-1]);
m_pCoeffs = new double[nmax];
m_pRadius = new double[nmax];
MEM_CHECK(m_pRadius);
} /* end CTOR() */
/******************************************************************************
Interpolate()
Compute the MQ-RBF (multiquadric radial basis function) coefficients.
******************************************************************************/
double Interpolator::Interpolate(bool bDebug)
{
double * vi, * vj, rj, dij, gij;
int i, j, k, ndim;
bool test;
/*------------------------------------------
Set up system of linear equations (Ax = b)
and solve.
------------------------------------------*/
//assign A and b
ndim = m_pBasis[0].ndim;
for(i = 0; i < m_Order; i++)
{
vi = m_pBasis[i].v;
m_b[i] = m_pBasis[i].F - m_AvgVal;
for(j = 0; j < m_Order; j++)
{
vj = m_pBasis[j].v;
rj = m_pRadius[j];
dij = 0.00;
for(k = 0; k < ndim; k++)
{
dij += ((vi[k] - vj[k])*(vi[k] - vj[k]));
}
gij = sqrt(dij + (rj*rj));
m_A[i][j] = gij;
m_Ainv[i][j] = 0.00;
}/* end for() */
}/* end for() */
//invert A
if(bDebug == true) fprintf(stdout, "Inverting matrix\n");
test = MatInv(m_A, m_Ainv, m_Order);
if(test == false)
{
printf("unable to interpolate.\n");
return 0.00;
}
//pre-multiply b by Ainv and assign result to coeff. array
if(bDebug == true) fprintf(stdout, "Computing coefficients\n");
VectMult(m_Ainv, m_b, m_pCoeffs, m_Order, m_Order);
return 0.00;
} /* end Interpolate() */
/******************************************************************************
Evaluate()
Evualute z = f(x1,x2,x3,...,xn) using the MQ-RBF interpolation.
******************************************************************************/
double Interpolator::Evaluate(MyPoint * point)
{
int i, j, ndim;
double sum, ai, gi, di, ri;
double * v, *vi;
sum = 0.00;
v = point->v;
ndim = point->ndim;
for(i = 0; i < m_Order; i++)
{
ai = m_pCoeffs[i];
ri = m_pRadius[i];
vi = m_pBasis[i].v;
di = 0.00;
for(j = 0; j < ndim; j++)
{
di += ((v[j] - vi[j])*(v[j] - vi[j]));
}
gi = sqrt(di + (ri*ri));
sum += (ai * gi);
}/* end for() */
sum += m_AvgVal;
point->F = sum;
return sum;
} /* end Evaluate() */
/******************************************************************************
Destroy
Destructor.
******************************************************************************/
void Interpolator::Destroy(void)
{
int i;
delete [] m_pCoeffs;
delete [] m_pRadius;
/*------------------------------------------
Free up matrices and vectors
------------------------------------------*/
delete [] m_b;
for(i = 0; i < m_MaxOrder; i++)
{
delete [] m_A[i];
delete [] m_Ainv[i];
}
delete [] m_A;
delete [] m_Ainv;
} /* end DTOR */
/******************************************************************************
SetBasis()
Assign a new set of known points to interpolate from.
******************************************************************************/
void Interpolator::SetBasis(MyPoint * vals, int n)
{
int i;
m_pBasis = vals;
m_Order = n;
if(n > m_MaxOrder) n = m_MaxOrder;
//compute average F value
m_AvgVal = 0.00;
for(i = 0; i < n; i++){ m_AvgVal += vals[i].F;}
m_AvgVal /= (double)n;
//zero coeffs.
for(i = 0; i < n; i++){ m_pCoeffs[i] = 0.00;}
//zero radii
for(i = 0; i < n; i++){ m_pRadius[i] = 0.00;}
}/* end SetBasis() */
| true |
1f6dc1e92a8e144d172ad24b7c95e0e7090b1bb7 | C++ | rohit16794/codes | /hash1.cpp | UTF-8 | 376 | 2.53125 | 3 | [] | no_license | # include <bits/stdc++.h>
using namespace std;
int hash(int n)
{
return (n%10);
}
int main()
{
int t;
cin>>t;
int n;
while(t--)
{
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int freq[10]={0};
long long count=0;
for(int i=0;i<n;i++)
{
if(freq[a[i]%10]==0)
freq[a[i]%10]=1;
else
++count;
}
cout<<count<<"\n";
}
return 0;
} | true |
a9ef253f89010c5652950dd6fa0de9ad3897467e | C++ | pyInvenio/cv | /lab06/coins.cpp | UTF-8 | 2,116 | 2.578125 | 3 | [] | no_license | #include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
const char* filename = argc >= 2 ? argv[1] : "coinseasy.jpg";
Mat src = imread(samples::findFile(filename), IMREAD_COLOR);
// Check if image is loaded fine
if (src.empty()) {
printf(" Error opening image\n");
printf(" Program Arguments: [image_name -- default %s] \n", filename);
return -1;
}
Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY);
GaussianBlur(gray, gray, Size(5, 5), 20);
vector<Vec3f> circles;
HoughCircles(gray, circles, HOUGH_GRADIENT, 1, gray.cols / 80, 100, 30, gray.cols / 80,
gray.cols / 16);
Mat radii(circles.size(), 1, CV_32F), coin_labels, centers;
for (int i = 0; i < circles.size(); i++) {
radii.at<float>(i) = circles[i][2];
}
kmeans(radii, 3, coin_labels,
TermCriteria(TermCriteria::MAX_ITER | TermCriteria::EPS, 10, .01), 10,
KMEANS_PP_CENTERS, centers);
for (int i = 0; i < coin_labels.rows; i++) {
cout << coin_labels.at<int>(i) << endl;
}
float total = 0.0f;
for (int i = 0; i < circles.size(); i++) {
Point center = Point(circles[i][0], circles[i][1]);
circle(src, center, 1, Scalar(0, 100, 100), 3, LINE_AA);
Scalar clr;
switch (coin_labels.at<int>(i)) {
case 0:
clr = Scalar(0, 0, 255);
total += 0.01f;
break;
case 1:
clr = Scalar(0, 255, 255);
total += 0.05f;
break;
case 2:
clr = Scalar(255, 0, 255);
total += 0.25f;
break;
case 3:
clr = Scalar(0, 0, 0);
total += 0.50f;
}
printf("Total: %.2f\n", total);
circle(src, center, circles[i][2], clr, 3, LINE_AA);
}
printf("Total: %.2f", total);
// Show results
imshow("Canny Circles", gray);
imshow("Detected Circles", src);
// Wait and Exit
waitKey();
return 0;
} | true |
f0ed68060e82f3be485854248b968afd0243e39f | C++ | Anushka-S10/Practice-Coding-Problems | /Cpp/Twist the Matrix/another_program.cpp | UTF-8 | 926 | 2.5625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int a[1005][1005],n,state;
int get(int x,int y)
{
if(state==0) return a[x][y];
if(state==1) return a[y][n-x+1];
if(state==2) return a[n-x+1][n-y+1];
return a[n-y+1][x];
}
int main() {
typedef long long ll;
char c;
cin>>n;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>a[i][j];
while(1)
{
cin>>c;
if(c=='-') break;
if(c=='Q')
{
int x,y;
cin>>x>>y;
cout<<get(x,y)<<endl;
}
else if(c=='A')
{
int d;
cin>>d;
d/=90;
state=(state-d)%4;
if(state<0) state+=4;
}
else
{
int x,y,z;
cin>>x>>y>>z;
a[x][y]=z;
}
}
return 0;
}
| true |
a9de6dbd8abc66b7623786732d53d0d4cb3c0275 | C++ | huynguy97/IP-Week11 | /main.4930211009162994535.cpp | UTF-8 | 4,452 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <cassert>
#include <string>
#include <cstring>
using namespace std;
//
//
//
//
//
double power(double x,int n){
//
assert(n>=0);
//
if(n==0){
return 1;
}
else {
x=x*power(x,n-1);
return x;
}
}
double power_improved(double x,int n){
//
assert(n>=0);
//
if(n==0){
return 1;
}
else if(n%2==0){
return power_improved(x,n/2)*power_improved(x,n/2);
}
else {
return x*power_improved(x,n/2)*power_improved(x,n/2);
}
}
bool palindrome1 (string text, int i, int j){
//
assert(i>=0 && j>=0 && j<=text.length()-1 && i<=text.length()-1);
//
if(i>j){
return true;
}
if(text[i]!=text[j])
{
return false;
}
else{
palindrome1(text,i+1,j-1);
}
}
bool palindrome2 (string text, int i, int j){
//
assert(i>=0 && j>=0 && j<=text.length()-1 && i<=text.length()-1);
//
char a =text[i];
char b = text[j];
if (a<91 && a>65){
a+=32;
}
if (b<91 && b>65){
b+=32;
}
if(i>j){
return true;
}
if(a!=b)
{
return false;
}
else{
palindrome2(text,i+1,j-1);
}
}
bool palindrome3 (string text, int i, int j){
//
assert(i>=0 && j>=0 && j<=text.length()-1 && i<=text.length()-1);
//
char a =text[i];
char b = text[j];
while(a<65){
a=text[i+1];
}
while(b<65){
b=text[j-1];
}
if (a<91 && a>65){
a+=32;
}
if (b<91 && b>65){
b+=32;
}
if(i>j){
return true;
}
if(a!=b)
{
return false;
}
else{
palindrome3(text,i+1,j-1);
}
}
bool match_chars (string chars, int i, string source, int j){
//
assert(i>=0 && j>=0 && j<=source.length()-1 && i<=chars.length()-1);
//
while(j<=source.length()-1){
if(chars[i]==source[j]){
if(i<chars.length()-1){
if(match_chars(chars,i+1,source,j+1)){
return true;
}
}
else{
return true;
}
}
j++;
}
return false;
}
int main() {
//
cout<<power(2,3)<<endl;
cout<<power_improved(2,4)<<endl;
cout<<power_improved(2,5)<<endl;
if(palindrome1("Otto",0,3)) {
cout << "true"<<endl;
}
else{
cout<<"false"<<endl;
}
if(palindrome2("Otto",0,3)) {
cout << "true"<<endl;
}
else{
cout<<"false"<<endl;
}
if(palindrome3("Madam, I'm Adam.",0,15)) {
cout << "true"<<endl;
}
else{
cout<<"false"<<endl;
}
if(match_chars("abc", 0, "It is a classy bag c",0)) {
cout << "true"<<endl;
}
else{
cout<<"false"<<endl;
}
}
| true |
0c2804c080294fb5207efbbe4489612f9a0784da | C++ | areejhasan/Project | /project/project/Person.h | UTF-8 | 799 | 2.640625 | 3 | [] | no_license | #include"Address.h"
#pragma once
class person:public address{
char* fullname;
char* nic;
int age;
char* gender;
char* bloodType;
char* phoneNumber;
public:
~person();
void setFullName(char*);
char *getFullName()const;
void setNIC(char*);
char *getNIC()const;
void setAge(int);
int getAge()const;
void setGender(char*);
char *getGender()const;
void setPhoneNumber(char*);
char *getPhoneNumber()const;
void setBloodType(char*);
char *getBloodType()const;
void displayPerson();
person(char* = nullptr, char* = nullptr, int = 0, char* = nullptr, char* = nullptr, char* = nullptr, int = 0, int = 0, char* = nullptr);
///////full name////////NIC//////////////Age//////Gender///Blood Type///////Phone Number/////////////HouseNo//StreetNo//Area////////////
}; | true |
5e4695938ccbf9495e226c6c4612111effb8279e | C++ | ChristopherBric/PF2 | /Objeto.h | UTF-8 | 1,127 | 2.78125 | 3 | [] | no_license | //
// Created by Santiago Madariaga on 2/07/2019.
//
#ifndef UNTITLED1_OBJETO_H
#define UNTITLED1_OBJETO_H
#include <string>
#include <iostream>
using namespace std;
class Objeto
{
protected:
string nombre;
string calificacion;
public:
int y;
int x;
void mostrar();
Objeto();
~Objeto();
};
class Restaurant:Objeto
{
private:
string tipo_de_comida;
string especialidad_del_dia;
public:
Restaurant(string nombre, int x, int y, string calificacion, string tipo_de_comida, string especialidad_del_dias);
virtual ~Restaurant();
void mostrar_lo_demas();
};
class Hotel:Objeto
{
private:
string disponibilidad;
int estrellas;
public:
void mostrar_lo_demas();
Hotel(string nombre, int x, int y, string calificacion, int estrellas, string disponibilidad);
virtual ~Hotel();
};
class Museo:Objeto
{
private:
string exposicion_actual;
public:
void mostrar_lo_demas();
Museo(string nombre, int x, int y, string calificacion, string exposicion_actual);
virtual ~Museo();
};
#endif //UNTITLED1_OBJETO_H
| true |
30aad3570365c152152fdb511ef9d08b6e80e545 | C++ | Huangyan0804/vjudge | /UVA-1586/UVA - 1586/UVA - 1586.cpp | UTF-8 | 714 | 2.875 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main() {
int t;
cin >> t;
while (t--){
string a;
int num[100] = { 0 };
double ans;
cin >> a;
for (auto iter = a.begin(); iter != a.end(); iter++) {
if (*iter == 'C'|| *iter == 'H'|| *iter == 'O'|| *iter == 'N') {
auto tempiter = iter;
int tempnum = 0;
if (++tempiter != a.end() && *tempiter < 64) {
while (tempiter != a.end() && *tempiter < 64) {
tempnum = tempnum * 10 + *tempiter - 48;
tempiter++;
}
}
else {
num[*iter]++;
}
num[*iter] += tempnum;
}
}
ans = num['C'] * 12.01 + num['H'] * 1.008 + num['O'] * 16.00 + num['N'] * 14.01;
printf("%.3f\n", ans);
}
return 0;
} | true |
b8db803149cce50cf41859af8eac58bfee094240 | C++ | jjmerle/eecs381-p6 | /Warship.cpp | UTF-8 | 3,451 | 3.109375 | 3 | [] | no_license | #include "Warship.h"
#include "Utility.h"
#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::string;
using std::shared_ptr;
using std::weak_ptr;
// initialize, then output constructor message
Warship::Warship(const string& name_, Point position_, double fuel_capacity_,
double maximum_speed_, double fuel_consumption_, int resistance_,
int firepower_, double maximum_range_) :
Ship(name_, position_, fuel_capacity_, maximum_speed_, fuel_consumption_, resistance_),
firepower(firepower_), maximum_range(maximum_range_),
attack_state(Attack_State_e::NOTATTACKING) { }
// perform warship-specific behavior
void Warship::update() {
Ship::update();
if(is_attacking()) {
shared_ptr<Ship> target_now = target.lock();
if(target_now) {
if(!is_afloat() || !target_now->is_afloat()) {
stop_attack();
} else {
cout << get_name() << " is attacking" << endl;
}
} else {
stop_attack();
}
}
}
// Warships will act on an attack and stop_attack command
// will throw Error("Cannot attack!") if not Afloat
// will throw Error("Warship may not attack itself!")
// if supplied target is the same as this Warship
void Warship::attack(shared_ptr<Ship> target_ptr_) {
if(!is_afloat()) {
throw Error("Cannot attack!");
}
if(target_ptr_ == shared_from_this()) {
throw Error("Warship may not attack itself!");
}
shared_ptr<Ship> target_now = target.lock();
if(target_ptr_ == target_now) {
throw Error("Already attacking this target!");
}
target = target_ptr_;
attack_state = Attack_State_e::ATTACKING;
cout << get_name() << " will attack " << target_ptr_->get_name() << endl;
}
// will throw Error("Was not attacking!") if not Attacking
void Warship::stop_attack() {
if(!is_attacking()) {
throw Error("Was not attacking!");
}
cout << get_name() << " stopping attack" << endl;
attack_state = Attack_State_e::NOTATTACKING;
target.reset();
}
void Warship::describe() const {
Ship::describe();
if(is_attacking()) {
shared_ptr<Ship> target_now = target.lock();
if(!target_now || !target_now->is_afloat()) {
cout << "Attacking absent ship";
} else {
cout << "Attacking " << target_now->get_name();
}
cout << endl;
}
}
void Warship::respond_to_attack(shared_ptr<Tanker> tanker_ptr) {
cout << "In DD-Tanker!" << endl;
}
void Warship::respond_to_attack(shared_ptr<Cruise_ship> cruise_ship_ptr) {
cout << "In DD-Cruise_ship!" << endl;
}
void Warship::respond_to_attack(shared_ptr<Cruiser> cruiser_ptr) {
cout << "In DD-Cruiser!" << endl;
}
// return true if this Warship is in the attacking state
bool Warship::is_attacking() const {
return attack_state == Attack_State_e::ATTACKING;
}
// fire at the current target
void Warship::fire_at_target() {
cout << get_name() << " fires" << endl;
shared_ptr<Ship> target_now = target.lock();
target_now->receive_hit(firepower, shared_from_this());
}
// is the current target in range?
bool Warship::target_in_range() const {
shared_ptr<Ship> target_now = target.lock();
return cartesian_distance(get_location(), target_now->get_location()) <= maximum_range;
}
// get the target
shared_ptr<Ship> Warship::get_target() const {
return target.lock();
} | true |
4934c9fa6bb8bceac50992f9f2c319a2193a50d7 | C++ | suyashmahar/CSN-102 | /search.cpp | UTF-8 | 840 | 3.703125 | 4 | [
"BSD-2-Clause",
"LicenseRef-scancode-chicken-dl-0.2"
] | permissive | #include<iostream>
#include<string>
using namespace std;
int binarySearch(int* inputArr, int element, int low, int high);
int main(){
int *sampleArray = new int[10];
for (int i = 0; i < 10; i++){
sampleArray[i] = i+1;
}
cout << binarySearch(sampleArray, 8, 0, 9);
}
int binarySearch(int* inputArr, int element, int low, int high){
if (low <= high){
if (inputArr[low] == element) return low;
if (inputArr[high] == element) return high;
int mid = low + (high-low)/2;
if (inputArr[mid] == element) return mid;
if (inputArr[mid] < element){
binarySearch(inputArr, element, mid+1, high);
}
else if (inputArr[mid] > element){
binarySearch(inputArr, element, low, mid-1);
}
}
else return -1;
} | true |
da6fd5dadb1fb618375d4f2226551da74f522170 | C++ | PawelMasluch/Programming-tasks-and-my-solutons | /szkopul.edu.pl/Archiwum Zadań Konkursowych/OIJ - Olimpiada Informatyczna Juniorów/II OIG/Minimalna liczba (II OIG, etap II).cpp | UTF-8 | 660 | 2.671875 | 3 | [] | no_license | #include<iostream> // 100 pkt
#include<vector>
#include<algorithm>
typedef long long LL;
typedef std::vector <LL> VLL;
#define REP(i,a,b) for(LL i=a; i<=b; ++i)
#define PB push_back
int main(){
std::ios_base::sync_with_stdio(0);
LL n, k;
std::cin >> n >> k;
VLL v;
LL x;
REP(i,1,n){
std::cin >> x;
if( x % k == 0 ){
v.PB( x / k );
}
}
sort( v.begin(), v.end() );
LL multiple_of_k = 0;
REP(i,0,v.size()-1){
if( v[i] >= multiple_of_k + 2 ){
std::cout << (multiple_of_k + 1) * k << std::endl;
return 0;
}
else{
multiple_of_k = v[i];
}
}
std::cout << (multiple_of_k + 1) * k << std::endl;
return 0;
}
| true |