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
75141d4985fae267bfc97ad81d033da86be9eb31
C++
yiyayiya557/epc
/Utility/H/CircularBuffer.h
UTF-8
1,761
3.09375
3
[]
no_license
#ifndef __CircularBuffer_h__ #define __CircularBuffer_h__ #include "ReEntrantMutex.h" #include "Semaphore.h" #define DEF_STREAM_BUFFER_SIZE 4096 // 4K PROJECT_NS_BEGIN /**************************************************************************************** * Thread safe circular buffer, * on write it will overwrite the oldest buffer as necessary, * on read it will read the oldest buffer until no newer buffer could be read ****************************************************************************************/ class CircularBuffer { public: CircularBuffer(int nSize=DEF_STREAM_BUFFER_SIZE, bool bOverwritten=false); // nSize specify the size of the circular buffer // bOverwritten true to overwite the oldest data whenever needed. // virtual ~CircularBuffer(); int Empty(); // return the # of bytes discarded bool IsEmpty(); // return true if no data available, false otherwise int GetReadableDataLength(); // return # of bytes currently in buffer inline int GetBufferSize() { return m_nSize > 0 ? m_nSize-1 : 0; } int Write(PBYTE pBuffer, int nBufSize, bool bAllOrNone=true); // bAllOrNone // true: to write the whole pBuffer of nBufSize if the available // empty buffer can accommodate them; otherwise, dont write any data // false: wirte as many bytes as possible. // return # of bytes written into StreamBuffer, if bOverwritten is true // it always returns nBufSize int Read(PBYTE pBuffer, int nBufSize, int nWaitMs=0); // nWaitMs ms to wait for data available. // return # of bytes read private: bool m_bOverWritten; PBYTE m_pbBuffer; int m_nHead, m_nTail, m_nSize; CReEntrantMutex m_mtxBuffer; CSemaphore m_semaData; bool m_bSingaled; }; PROJECT_NS_END #endif //__CircularBuffer_h__
true
359a6f8ed5a7ee002b3798dc41e61773f74c28cc
C++
tikhova/discrete-math-2018
/Labs/S2 MATROID LAB/D.cpp
UTF-8
1,455
2.875
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <set> #include <math.h> using namespace std; int main() { freopen("cycles.in", "r", stdin); freopen("cycles.out", "w", stdout); // Input & check 1 axiom int n, m; cin >> n >> m; vector<vector<int>> s(m); vector<int> masks(m, 0); vector<bool> belongs((1 << n), false); int count, x; bool nontrivial = false; for (int i = 0; i < m; ++i) { cin >> count; if (count == 0) nontrivial = true; for (int j = 0; j < count; ++j) { cin >> x; --x; s[i].push_back(x); masks[i] |= (1 << x); } belongs[masks[i]] = true; } if (!nontrivial) { cout << "NO" << endl; return 0; } // Check 2 axiom for (int i = 0; i < m; i++) { for (int j = 0; j < n; ++j) if ((masks[i] & (1 << j)) && !belongs[masks[i] ^ (1 << j)]) { cout << "NO" << endl; return 0; } } // Check 3 axiom for (int i = 0; i < m; i++) for (int j = 0; j < m; j++) if (s[i].size() > s[j].size()) { int a = masks[i]; int b = masks[j]; for (int k = 0; k < n; k++) if ((a & (1 << k)) && (b & (1 << k))) a ^= (1 << k); // now a = mask[i]\mask[b] bool isReplacable = false; for (int k = 0; k < n; k++) if ((a & (1 << k)) && belongs[b + (1 << k)]) { isReplacable = true; break; } if (!isReplacable) { cout << "NO" << endl; return 0; } } cout << "YES" << endl; return 0; }
true
1b3d15ffdeeba77514cfe62952032438ef8e626f
C++
anonymouslei/LeetCode
/tree/543_DiameterOfBinaryTree.cpp
UTF-8
1,075
3.28125
3
[]
no_license
// // Created by lei.ge on 6/11/2020. // //Runtime: 12 ms, faster than 74.24% of C++ online submissions for Diameter of Binary Tree. //Memory Usage: 20.7 MB, less than 34.36% of C++ online submissions for Diameter of Binary Tree. /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int diameterOfBinaryTree(TreeNode* root) { ans_ = 0; LongestPath(root); return ans_; } private: int ans_; int LongestPath(TreeNode* root) { if (!root) return -1; int leftLength = LongestPath(root->left) + 1; int rightLength = LongestPath(root->right) + 1; ans_ = max(ans_, leftLength + rightLength); return max(leftLength, rightLength); } };
true
d6944f2bda137d3e8adb16c26a0d7e9363d53d13
C++
Longarithm/silver_marriage
/geometry/_standard_library.cpp
UTF-8
2,204
3.140625
3
[]
no_license
bool eq(ld a, ld b) { return (fabs(a - b) < eps); } struct pt { ld x, y; pt(): x(0), y(0) {} pt(ld _x, ld _y) { x = _x, y = _y; } void read() { cin >> x >> y; } void print() { cout << x << ' ' << y << endl; } friend bool eq(pt a, pt b) { return eq(a.x, b.x) && eq(a.y, b.y); } friend bool operator==(pt a, pt b) { return a.x == b.x && a.y == b.y; } friend bool operator<(pt a, pt b) { return (a.x < b.x) || (eq(a.x, b.x) && (a.y < b.y)); } friend pt operator-(pt p1, pt p2) { return pt(p1.x - p2.x, p1.y - p2.y); } friend pt operator+(pt p1, pt p2) { return pt(p1.x + p2.x, p1.y + p2.y); } friend pt operator*(pt a, ld b) { return pt(a.x * b, a.y * b); } friend pt operator/(pt a, ld b) { return pt(a.x / b, a.y / b); } ld len() { return sqrt(.0 + x * x + y * y); } ld dist(pt p) { return (*this - p).len(); } pt norm() { pt v = *this; ld L = v.len(); assert(L >= eps); v.x /= L; v.y /= L; return v; } friend ld operator*(pt p1, pt p2) { return p1.x * p2.x + p1.y * p2.y; } friend ld operator%(pt p1, pt p2) { return p1.x * p2.y - p2.x * p1.y; } friend ld angle(pt p1, pt p2) { return abs(atan2(p1 % p2, p1 * p2)); } ld polarAngle() { ld res = atan2(y, x); return (res < 0) ? res + 2 * pi : res; } pt rotate(ld w) { return pt(x * cos(w) - y * sin(w), x * sin(w) + y * cos(w)); } friend bool cw(pt a, pt b, pt c) { return ((c - a) % (b - a)) > 0; } friend bool ccw(pt a, pt b, pt c) { return ((c - a) % (b - a)) < 0; } }; struct line { ld A, B, C; line(): A(0), B(0), C(0) {} line(ld _A, ld _B, ld _C) { A = _A, B = _B, C = _C; } bool lay(pt p) { return eq(A * p.x + B * p.y + C, 0); } line(pt p1, pt p2) { A = p1.y - p2.y; B = p2.x - p1.x; C = -(A * p1.x + B * p1.y); assert(lay(p1)); assert(lay(p2)); } bool parallel(line n) { return eq(A * n.B - B * n.A, 0); } bool equivalent(line n) { return parallel(n) && eq(A * n.C - C * n.A, 0) && eq(B * n.C - C * n.B, 0); } }; ld polygonArea(vector<pt> a) { ld ans = 0; for (int i = 1; i < (int)a.size(); i++) ans += (a[i - 1] % a[i]); ans += (a.back() % a[0]); return fabs(ans) / 2; }
true
896ff55e83b7b10c0ba06676b11cbe056ea2eab6
C++
wen96/pl-man2
/masternetwork/src/CNetwork.cpp
UTF-8
2,989
2.921875
3
[ "MIT" ]
permissive
#include "CNetwork.h" #include "CNetworkServer.h" /////////////////////////////////////////////////////////////////////////////// /// \brief Network constructor /////////////////////////////////////////////////////////////////////////////// CNetwork::CNetwork() : m_networkInitialized(false) {} /////////////////////////////////////////////////////////////////////////////// /// \brief Network initialization /// /// It initializes network modules an prepares everything to start creating /// servers or connecting to peers /////////////////////////////////////////////////////////////////////////////// void CNetwork::initialize() { // INITIALIZE ENET if (enet_initialize() != 0) throw "ERROR: There was an error initializing enet and network could" " not be started\n"; m_networkInitialized = true; } ///////////////////////////////////////////////////////////////////////////// /// \brief Creates a server and puts it into listening /// /// \param port Port where to listen for clients /// \param host Host where to listen for clients (default ANY) /// \param peerCount Maximum simultaneous connected peers (default 100) /// \param channelLimit Number of communication channels (default 2) /// \param incomingBandwidth Maximum incoming bandwidth in Bps (default to max) /// \param outgoingBandwidth Maximum outgoing bandwidth in Bps (default to max) /////////////////////////////////////////////////////////////////////////////// CNetworkServer& CNetwork::createServer(enet_uint16 port, enet_uint32 host, size_t peerCount, size_t channelLimit, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth) { CNetworkServer* newserver = NULL; if (m_networkInitialized) { /// TODO: Check for exceptions newserver = new CNetworkServer(port, host,peerCount, channelLimit, incomingBandwidth, outgoingBandwidth); m_vecServers.push_back(newserver); } else { /// TODO: What to do when network is not initialized } return *newserver; } /////////////////////////////////////////////////////////////////////////////// /// \brief Restores network state to previous at closing /////////////////////////////////////////////////////////////////////////////// CNetwork::~CNetwork() { if (m_networkInitialized) { //enet_deinitialize(); atexit (enet_deinitialize); m_networkInitialized = false; } for (unsigned int i = 0; i < m_vecClients.size(); i++){ delete m_vecClients[i]; m_vecClients[i] = NULL; } m_vecClients.clear(); for (unsigned int i = 0; i < m_vecServers.size(); i++){ delete m_vecServers[i]; m_vecServers[i] = NULL; } m_vecServers.clear(); } CNetworkClient* CNetwork::createClient() { CNetworkClient* newclient = NULL; if (m_networkInitialized) { /// TODO: Check for exceptions newclient = new CNetworkClient(); m_vecClients.push_back(newclient); } else { throw "Exception: The network has not been initialized before create a client"; } return newclient; }
true
fc12a7d8c35a7e2f75481225938fc30de6811b1a
C++
Bryanskaya/AnalysisOfAlgorithms
/lab_06/program/ant_search.cpp
UTF-8
4,070
2.6875
3
[]
no_license
#include "ant_search.h" matrix_double_t create_pheromone(int n) { matrix_double_t res; vector<double> temp; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) temp.push_back(INIT_PHR); res.push_back(temp); } return res; } double find_avg_path(matrix_t& c) { int n = c.size(); double res = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) res += c[i][j]; return res / n; } vector<ant_t> create_colony(int n) { vector<ant_t> res; for (int i = 0; i < n; i++) { ant_t ant; ant.done_path.push_back(i); ant.cur_pos = i; ant.len_path = 0; res.push_back(ant); } return res; } bool is_exist(int index, vector<int> path) { for (int i = 0; i < path.size(); i++) if (path[i] == index) return true; return false; } void update_ant(int new_pos, int len, ant_t& ant) { ant.done_path.push_back(new_pos); ant.len_path += len; ant.cur_pos = new_pos; } int find_next_top(matrix_t& c, vector<int>& pos_path, ant_t& ant, matrix_double_t& phr, double a, double b) { int k = 0; vector<double> p; double p_temp, sum = 0, cur_sum = 0, comp_p; for (int i = 0; i < pos_path.size(); i++) { int node = pos_path[i]; if (c[ant.cur_pos][node]) p_temp = pow(phr[ant.cur_pos][node], a) / pow(c[ant.cur_pos][node], b); else p_temp = 0; p.push_back(p_temp); sum += p_temp; } if (sum == 0) return -1; comp_p = (double)rand() / RAND_MAX * sum; while (cur_sum < comp_p) { cur_sum += p[k]; k++; } return k-1; } void find_path(matrix_t& c, matrix_double_t& phr, ant_t& ant, double a, double b) { vector<int> pos_path; int ind, flag = 1; for (int i = 0; i < c.size(); i++) if (i != ant.cur_pos) pos_path.push_back(i); while (pos_path.size() != 0) { ind = find_next_top(c, pos_path, ant, phr, a, b); if (ind == -1) break; update_ant(pos_path[ind], c[ant.cur_pos][pos_path[ind]], ant); pos_path.erase(pos_path.begin() + ind); if (pos_path.size() == 0 && flag) { pos_path.push_back(ant.done_path[0]); flag = 0; } } } void find_vaporization(matrix_double_t& phr, double k) { for (int i = 0; i < phr.size(); i++) for (int j = 0; j < phr[i].size(); j++) phr[i][j] = (1 - k) * phr[i][j]; } void increase_phr(matrix_double_t& pheromone, vector<ant_t> colony, double q) { for (int i = 0; i < colony.size(); i++) for (int j = 0; j < colony[i].done_path.size() - 1; j++) { int node1 = colony[i].done_path[j]; int node2 = colony[i].done_path[j+1]; pheromone[node1][node2] += q / colony[i].len_path; if (pheromone[node1][node2] < MIN_K_PHR * INIT_PHR) pheromone[node1][node2] = MIN_K_PHR * INIT_PHR; pheromone[node2][node1] = pheromone[node1][node2]; } } void elite_increase(double q, vector<int>& tour, int len, matrix_double_t& phr) { int num_el_ant = 2; if (!tour.size()) return; for (int i = 0; i < tour.size() - 1; i++) { int node1 = tour[i]; int node2 = tour[i + 1]; phr[node1][node2] += num_el_ant * q / len; phr[node2][node1] += num_el_ant * q / len; } } int ant_search(double a, double b, matrix_t& c, double k_vpr, double q, int t_max, vector<int>& result) { //double q = find_avg_path(c); matrix_double_t pheromone = create_pheromone(c.size()); int len = 1e7; vector<int> tour; for (int t = 0; t < t_max; t++) { vector<ant_t> colony = create_colony(c.size()); for (int i = 0; i < colony.size(); i++) { find_path(c, pheromone, colony[i], a, b); if (colony[i].len_path < len && colony[i].done_path.size() == c.size() + 1) { len = colony[i].len_path; tour = colony[i].done_path; } } find_vaporization(pheromone, k_vpr); elite_increase(q, tour, len, pheromone); increase_phr(pheromone, colony, q); } /*cout << "Found tour: "; for (int i = 0; i < tour.size(); i++) cout << tour[i] << " "; cout << "\nIts length: " << len << endl;*/ result = tour; return len; }
true
56699fa792f8fd79a2ec15146b4eae61dc498437
C++
hizengbiao/SLR-compiler
/code/编译实验一【词法分析】/analyze.h
GB18030
4,223
2.53125
3
[]
no_license
#pragma once #include "defineAndStruct.h" #include <stdio.h> #include <sstream> class analyze { string line; //ǰɨ int i; //ǰɨַλ char ch; //ǰɨַ int ccount; //ǰɨ赽Ĵ int po_ch; //ǰǼ˶ٸʶ //int po_nu = 0; //ǰǼ˶ٸ int nowline;//ǰɨǴеĵڼ int count_err; //ǰɨĴ char errs[60]; //Ϣ int errsLine[60];//ÿԴек string tab_ch[1000];//ʶǼDZ //int tab_nu[100]; ifstream in;//ı ofstream out2;//ɴı ofstream out;//ı int ista;//﷨ıʽʼλ int iend;//﷨ıʽĽλ int sp;//ջָstack± int ssp;//ջָsstack± int ii;//ǰҪķڴʷ(buf)еλ int lr;//ƽǹԼdz int nxq;//һԪʽĵַ ntab33 ntab3[200];//洢ÿʽɵԪʽĵַ int label;//ntab3± aa downline;//» aa Et;//ʽ int sign; //sign=1ʽ䣬sign=2ѭ䣬sign=3ǿ int newt;//²ʱ aa buf[3000];//ʷʷĽ aa buf2[300];//򲼶ʽַ stackType stack[100];//﷨ջ stackType sstack[100];//򲼶ʽ﷨ջ int jj;//ǰҪķbuf2еλ fourexp fexp[200];//Ԫʽ洢 ll labelmark[10];//ifwhileһͷǸ״̬ int labeltemp[10];//ifelseмǸ״̬ int pointmark;//labelmarkĵǰ± int pointtemp;//labeltempĵǰ± int ret;//ʽʽӳ˳ int ret2;//˳ int subline;//ԴĴк public: analyze();//ʼ void stCifa();//ʼдʷ void stYufa();//ʼ﷨ int findd(string m);//ұʶmڱʶǼDZеλ void identifier();//ʶַDZʶDZ void number();//ʶ void backch();//һַ void readch();//ȡһַ void scanOneLine();//ʷһ void show();//ʷĽ void showiden(); //ʶ void shownum(); // void showZhuangtai();//״̬ջ void showFuhao();//ջ void showYuyi();//ջ void showYuyi(int yu);//ջ void showZhan(int lrr);//ʾջԼƽ string changeStackB(int sy,int zho);//ֱطӦţʮʶǷǷս string finsBuf(int q);//buf±귵ضӦķ void reset();//﷨ջ void reset2();//﷨ջ void show2(int st, int en);//ʷдλistaiendԪ string finds(int tc);//ֱ뷵ط void stsend();//ʱ㵱ǰʽĿʼλúͽλ void show3(/*int c*/);//㵽ǰһļ int conv(aa tem);//ŷڳLRеĺ int conv2(aa tem);//ŷʽLRеĺ int conv3(aa tem);//ŷڲʽLRеĺ int test(int value);//жϵǰַdzĻ0򷵻1ʽʽ int newtemp();//һµʱ int lrparse();//﷨ int lrparse2();//ʽķ int lrparse3();//ʽķ int emit(string op1, aa arg1, aa arg2, int result1);//һԪʽ int merge(int p1, int p2);// void show4exp();//Ԫʽ void backpatch(int p, int t);// ~analyze(); };
true
f45b6443c2c6f2af6a7f66e03dcbfc68af5bbbf7
C++
fineday009/Problemset_accepted
/树/lc102层次遍历.cpp
UTF-8
906
3.03125
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; if(!root) return res; vector<int> perline; queue<TreeNode*> _queue; TreeNode* last=root; _queue.push(root); while(!_queue.empty()){ TreeNode* frt=_queue.front(); _queue.pop(); perline.push_back(frt->val); if(frt->left) _queue.push(frt->left); if(frt->right) _queue.push(frt->right); if(frt==last){ last=_queue.back(); res.push_back(perline); perline.clear(); } } return res; } };
true
4b695b026d44d5a01d53a3d0cc920f8c47745bb8
C++
luguoss/test_leetcode
/20.有效的括号.cpp
UTF-8
995
3.296875
3
[]
no_license
/* * @lc app=leetcode.cn id=20 lang=cpp * * [20] 有效的括号 */ // @lc code=start #include <stack> #include <unordered_map> class Solution { public: bool isValid(string s) { if(s.size() == 0) { return true; }else if(s.size() % 2 == 1) { return false; } stack<char> sign; unordered_map<char, char> key = {{'(',')'},{'{','}'},{'[',']'} }; for(int i = 0; i < s.size();i++) { if(key.find(s[i]) != key.end()) { sign.push(s[i]); } else { if(sign.size()>0) { if(key.find(sign.top())->second == s[i]) sign.pop(); }else { return false; } } } if(sign.size() == 0) return true; return false; } }; // @lc code=end
true
97e89193d011c91e5d630157dc06911f9c459610
C++
lyh458/InteractionModels_DemoCode
/src/iModOSG/MyInteractionTetrahedronMeshView.cpp
UTF-8
7,610
2.765625
3
[]
no_license
// // MyInteractionTetrahedronMeshView.cpp // BoneAnimation // // Created by Christian on 30.11.13. // // #include "MyInteractionTetrahedronMeshView.h" using namespace MyInteractionMesh; MyInteractionTetrahedronMeshView::MyInteractionTetrahedronMeshView(MyInteractionMeshModel* model) { _model = model; } MyInteractionTetrahedronMeshView::~MyInteractionTetrahedronMeshView() { _model = nullptr; } osg::Geode* MyInteractionTetrahedronMeshView::createGeodeFacade(Shape* shape, osg::Vec4 color) { Tetrahedron* tetra = (Tetrahedron*) shape; return createTetrahedronGeode(tetra->a->asOsgVec(), tetra->b->asOsgVec(), tetra->c->asOsgVec(), tetra->d->asOsgVec(), color); } osg::Geometry* MyInteractionTetrahedronMeshView::createGeometryFacade(Shape* shape, osg::Vec4 color) { Tetrahedron* tetra = (Tetrahedron*) shape; return createTetrahedronGeometry(tetra->a->asOsgVec(), tetra->b->asOsgVec(), tetra->c->asOsgVec(), tetra->d->asOsgVec(), color); } osg::Vec4f MyInteractionTetrahedronMeshView::getColorFacade(Shape* currentShape, Shape* oldShape, osg::Vec4f oldColor) { Tetrahedron* currTetra= (Tetrahedron*) currentShape; Tetrahedron* oldTetra = (Tetrahedron*) oldShape; return getColorForTetrahedron( boost::make_tuple(currTetra->a->asOsgVec(), currTetra->b->asOsgVec(), currTetra->c->asOsgVec(), currTetra->d->asOsgVec()), boost::make_tuple(oldTetra->a->asOsgVec(), oldTetra->b->asOsgVec(), oldTetra->c->asOsgVec(), oldTetra->d->asOsgVec()), oldColor); } Shape* MyInteractionTetrahedronMeshView::getShapeFromOSGGeometry(osg::Geometry* geometry, std::vector<Vertice>* verticeVec) { osg::Array *vecArray = geometry->getVertexArray(); osg::Vec3Array *vec3Array = dynamic_cast<osg::Vec3Array*>(vecArray); osg::Vec3 oldVec1 = (*vec3Array)[0]; osg::Vec3 oldVec2 = (*vec3Array)[1]; osg::Vec3 oldVec3 = (*vec3Array)[2]; osg::Vec3 oldVec4 = (*vec3Array)[3]; verticeVec->push_back(Vertice(oldVec1)); verticeVec->push_back(Vertice(oldVec2)); verticeVec->push_back(Vertice(oldVec3)); verticeVec->push_back(Vertice(oldVec4)); Tetrahedron *t = new Tetrahedron(&(*verticeVec)[0], &(*verticeVec)[1], &(*verticeVec)[2], &(*verticeVec)[3]); return (Shape*) t; // currently have to delete shape by yourself } osg::Geode* MyInteractionTetrahedronMeshView::createTetrahedronGeode(osg::Vec3 v1, osg::Vec3 v2, osg::Vec3 v3, osg::Vec3 v4,osg::Vec4 color) { osg::Geode* geode = new osg::Geode(); geode->addDrawable(this->createTetrahedronGeometry(v1, v2, v3, v4, color)); geode->setName("MyInteractionMesh_Tetrahedron"); return geode; } osg::Geometry* MyInteractionTetrahedronMeshView::createTetrahedronGeometry(osg::Vec3 v1, osg::Vec3 v2, osg::Vec3 v3, osg::Vec3 v4, osg::Vec4 color) { osg::Geometry* geometry = new osg::Geometry(); osg::Vec3Array* vertices = new osg::Vec3Array(); vertices->push_back(v1); vertices->push_back(v2); vertices->push_back(v3); vertices->push_back(v4); vertices->dirty(); geometry->setVertexArray(vertices); osg::DrawElementsUInt* base = new osg::DrawElementsUInt( osg::PrimitiveSet::TRIANGLES, 0 ); base->push_back( 2 ); base->push_back( 1 ); base->push_back( 0 ); osg::DrawElementsUInt* face1 = new osg::DrawElementsUInt( osg::PrimitiveSet::TRIANGLES, 0 ); face1->push_back( 3 ); face1->push_back( 1 ); face1->push_back( 0 ); osg::DrawElementsUInt* face2 = new osg::DrawElementsUInt( osg::PrimitiveSet::TRIANGLES, 0 ); face2->push_back( 3 ); face2->push_back( 2 ); face2->push_back( 1 ); osg::DrawElementsUInt* face3 = new osg::DrawElementsUInt( osg::PrimitiveSet::TRIANGLES, 0 ); face3->push_back( 3 ); face3->push_back( 2 ); face3->push_back( 0 ); geometry->addPrimitiveSet( base ); geometry->addPrimitiveSet( face1 ); geometry->addPrimitiveSet( face2 ); geometry->addPrimitiveSet( face3 ); /////OLD/COLOR -> WITHOUT BLENDING/LIGHTNING // osg::Vec4Array* colors = new osg::Vec4Array(); // colors->push_back(color); // colors->dirty(); // //#ifdef OSG_VERSION_LESS_THAN_3_DOT_2 // geometry->setColorArray(colors); // bis OSG 3.1 // geometry->setColorBinding(osg::Array::BIND_PER_PRIMITIVE_SET); // bis OSG 3.1 //#else // geometry->setColorArray(colors, osg::Array::BIND_PER_PRIMITIVE_SET); // erst ab OSG 3.2 //#endif // // geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, false); /////////// /////NEW/COLOR + GL_LIGHTNING/BLENDING // setting up lightning for triangle osg::StateSet* state = geometry->getOrCreateStateSet(); osg::ref_ptr<osg::Material> material = new osg::Material; // Set alpha material->setAlpha(osg::Material::FRONT_AND_BACK, 0.3); material->setEmission(osg::Material::FRONT_AND_BACK, color); state->setAttributeAndModes( material.get() , osg::StateAttribute::ON | osg::StateAttribute::MATERIAL); // Turn on blending osg::BlendFunc* blend = new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA ); state->setAttributeAndModes(blend); state->setMode(GL_BLEND, osg::StateAttribute::ON ); state->setMode(GL_LIGHTING, osg::StateAttribute::ON); state->setRenderingHint( osg::StateSet::TRANSPARENT_BIN ); //////////// // osg::LineWidth* lineWidth = new osg::LineWidth(); // lineWidth->setWidth(1.0f); // state->setAttributeAndModes(lineWidth, osg::StateAttribute::ON); geometry->dirtyDisplayList(); geometry->setUseDisplayList(false); geometry->setDataVariance(osg::Object::DYNAMIC); return geometry; } osg::Vec4f MyInteractionTetrahedronMeshView::getColorForTetrahedron(TetrahedronCoordinates current, TetrahedronCoordinates old, osg::Vec4f oldColor) { double areaNew = Tetrahedron::getVolume(Vertice(current.get<0>()), Vertice(current.get<1>()), Vertice(current.get<2>()), Vertice(current.get<3>())); double areaOld = Tetrahedron::getVolume(Vertice(old.get<0>()), Vertice(old.get<1>()), Vertice(old.get<2>()), Vertice(old.get<3>())); osg::Vec4f newColor; double r,g; r = oldColor.r(); g = oldColor.g(); if (areaNew < areaOld) { if(r>=0.05) r = r-0.05; if(g<=0.95) g = g+0.05; newColor = osg::Vec4f(r,g,0.0f, 1.0f); } else if (areaNew > areaOld) { if(r<=0.95) r = r+0.05; if(g>=0.05) g = g-0.05; newColor = osg::Vec4f(r,g,0.0f, 1.0f); } else { newColor = oldColor; } return newColor; }
true
8ad085dd07648522f719424aaeed5c02604fff08
C++
david-browning/Queue-Game-Library
/QGL_Input/include/Helpers/qgl_pointer_helpers.h
UTF-8
2,681
2.625
3
[]
no_license
#pragma once #include "include/qgl_input_include.h" #include "include/qgl_input_key.h" namespace qgl::input { using input_mouse_button = typename winrt::Windows::UI::Input::PointerUpdateKind; constexpr std::array<winrt::Windows::UI::Input::PointerUpdateKind, 11> pointer_keys = { input_mouse_button::LeftButtonPressed, input_mouse_button::RightButtonPressed, input_mouse_button::MiddleButtonPressed, input_mouse_button::XButton1Pressed, input_mouse_button::XButton2Pressed, input_mouse_button::Other, input_mouse_button::LeftButtonReleased, input_mouse_button::RightButtonReleased, input_mouse_button::MiddleButtonReleased, input_mouse_button::XButton1Released, input_mouse_button::XButton2Released, }; constexpr std::array<winrt::Windows::UI::Input::PointerUpdateKind, 5> pointer_press_keys = { input_mouse_button::LeftButtonPressed, input_mouse_button::RightButtonPressed, input_mouse_button::MiddleButtonPressed, input_mouse_button::XButton1Pressed, input_mouse_button::XButton2Pressed, }; constexpr std::array<winrt::Windows::UI::Input::PointerUpdateKind, 5> pointer_release_keys = { input_mouse_button::LeftButtonReleased, input_mouse_button::RightButtonReleased, input_mouse_button::MiddleButtonReleased, input_mouse_button::XButton1Released, input_mouse_button::XButton2Released, }; inline input_key pointer_key(input_mouse_button button) noexcept { static const std::unordered_map<input_mouse_button, input_key> POINTER_KIND_INPUT_KEY_MAP = { { input_mouse_button::LeftButtonPressed,input_key::LeftButton }, { input_mouse_button::RightButtonPressed,input_key::RightButton }, { input_mouse_button::MiddleButtonPressed,input_key::MiddleButton }, { input_mouse_button::XButton1Pressed,input_key::XButton1 }, { input_mouse_button::XButton2Pressed,input_key::XButton2 }, { input_mouse_button::LeftButtonReleased,input_key::LeftButton }, { input_mouse_button::RightButtonReleased,input_key::RightButton }, { input_mouse_button::MiddleButtonReleased,input_key::MiddleButton }, { input_mouse_button::XButton1Released,input_key::XButton1 }, { input_mouse_button::XButton2Released, input_key::XButton2 }, }; if (POINTER_KIND_INPUT_KEY_MAP.count(button) > 0) { // The above guard will keep this from throwing. // Mark the function as noexcept. return POINTER_KIND_INPUT_KEY_MAP.at(button); } return input_key::None; } }
true
9e27419d1f0a68e70595559266e932f014249de5
C++
HONGYU-LEE/NetWorkProgram
/IOMultiplexing/select/select_srv.cc
UTF-8
2,117
2.890625
3
[ "MIT" ]
permissive
#include<iostream> #include<string> #include<unistd.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include"TcpSocket.hpp" #include"select.hpp" using namespace std; int main(int argc, char* argv[]) { if(argc != 3) { cerr << "正确输入方式: ./select_srv.cc ip port\n" << endl; return -1; } string srv_ip = argv[1]; uint16_t srv_port = stoi(argv[2]); TcpSocket lst_socket; //创建监听套接字 CheckSafe(lst_socket.Socket()); //绑定地址信息 CheckSafe(lst_socket.Bind(srv_ip, srv_port)); //开始监听 CheckSafe(lst_socket.Listen()); Select s; s.Add(lst_socket); while(1) { vector<TcpSocket> vec; //去掉未就绪描述符 bool ret = s.Wait(vec); if(ret == false) { continue; } //取出就绪描述符进行处理 for(auto socket : vec) { //如果就绪的是监听套接字,则代表有新连接 if(socket.GetFd() == lst_socket.GetFd()) { TcpSocket new_socket; ret = lst_socket.Accept(&new_socket); if(ret == false) { continue; } //新建套接字加入集合中 s.Add(new_socket); } //新数据到来 else { string data; //接收数据 ret = socket.Recv(data); //断开连接,移除监控 if(ret == false) { s.Del(socket); socket.Close(); continue; } cout << "cli send message: " << data << endl; data.clear(); if(ret == false) { s.Del(socket); socket.Close(); continue; } } } } //关闭监听套接字 lst_socket.Close(); return 0; }
true
aba2336ca4e17e83eb2d5d83bd5eef172b15c1e3
C++
MichaelSt98/NNS
/3D/MPI/MPI_NBody/include/Octant.h
UTF-8
2,814
3.109375
3
[]
no_license
// // Created by Michael Staneker on 25.01.21. // #ifndef NBODY_OCTANT_H #define NBODY_OCTANT_H #include "Vector3D.h" #include <iostream> #include <utility> class Tree; class Octant { private: double length; Vector3D center; public: /**! * Constructor for Octant class. * * @param _x x coordinate for center * @param _y y coordinate for center * @param _z z coordinate for center * @param _length length of octant instance */ Octant(double _x, double _y, double _z, double _length); /**! * Move constructor for Octant class. * * @param otherOctant other Octant instance */ Octant(Octant&& otherOctant); /**! * Copy constructor for Octant class. * * @param otherOctant other Octant istance */ Octant(const Octant& otherOctant); /**! * Overwritten stream operator to print Octant instances. */ friend std::ostream &operator<<(std::ostream &os, const Octant &octant); /**! * get length of the octant instance * * @return length of the octant instance as double */ double getLength() const; /**! * Check if particle is within the octant instance. * * @param particle Body instance * @return bool, whether particle within the Octant */ bool contains(const Vector3D &particle) const; /**! * Get the corresponding sub-octant (when subdividing is required) in dependence of the particle to be insert * * * UNW -> 0 * * UNE -> 1 * * USW -> 2 * * USE -> 3 * * LNW -> 4 * * LNE -> 5 * * LSW -> 6 * * LSE -> 7 * * @param particle Body instance * @return integer, sub-octant */ int getSubOctant(const Vector3D &particle) const; /**! * (- + +) or upper-north-west * * @return upper-north-west octant */ Octant getUNW() const; /**! * (+ + +) or upper-north-east * * @return upper-north-east octant */ Octant getUNE() const; /**! * (- - +) or upper-south-west * * @return upper-south-west octant */ Octant getUSW() const; /**! * (+ - +) or upper-south-east * * @return upper-south-east octant */ Octant getUSE() const; /**! * (- + -) or lower-north-west * * @return lower-north-west octant */ Octant getLNW() const; /**! * (+ + -) or lower-north-east * * @return lower-north-east octant */ Octant getLNE() const; /**! * (- - -) or lower-south-west * * @return lower-south-west octant */ Octant getLSW() const; /**! * (+ - -) or lower-south-east * * @return lower-south-east */ Octant getLSE() const; }; #endif //NBODY_OCTANT_H
true
fc81a355fd7666dc5b8c48b632aea93104b55798
C++
el-bart/ACARM-ng
/src/filternewevent/Filter/NewEvent/Exception.hpp
UTF-8
668
2.625
3
[]
no_license
/* * Exception.hpp * */ #ifndef INCLUDE_FILTER_NEWEVENT_EXCEPTION_HPP_FILE #define INCLUDE_FILTER_NEWEVENT_EXCEPTION_HPP_FILE #include "Filter/Exception.hpp" namespace Filter { namespace NewEvent { /** \brief base for all new-event-filter-related exceptions. */ class Exception: public Filter::Exception { public: /** \brief create execption with given message. * \param where place where exception has been thrown. * \param what message to represent. */ Exception(const Location &where, const std::string &what): Filter::Exception(where, "newevent", what) { } }; // class Exception } // namespace NewEvent } // namespace Filter #endif
true
95d0ea3592e1e5d6c36f08fd01d0d899ec708904
C++
wyuange/node_cpp_addon
/lib/bigNumber.cpp
UTF-8
6,386
2.65625
3
[]
no_license
#include <iostream> #include <stack> #include <string> #include <algorithm> #include <node.h> #include <node_object_wrap.h> #include "bigNumber.h" Local<String> ToLocalString(const char* str) { Isolate* isolate = Isolate::GetCurrent(); EscapableHandleScope scope(isolate); Local<String> s = String::NewFromUtf8(isolate, str, NewStringType::kNormal).ToLocalChecked(); return scope.Escape(s); } char* ToCString(Local<String> from) { Isolate* isolate = Isolate::GetCurrent(); String::Utf8Value v(isolate, from); return *v; } void FillZero(std::string& from, int length) { while (length--) { from.insert(from.begin(), '0'); } } void RightFillZero(std::string& from, int length) { while(length--) { from.push_back('0'); } } void NativeAdd(std::string& a, std::string& b) { FillZero(a, std::max(a.size(), b.size()) - a.size()); FillZero(b, std::max(a.size(), b.size()) - b.size()); std::string result; int t = 0; for (int i = a.size() - 1; i >= 0; i--) { int v1 = a[i] - '0'; int v2 = b[i] - '0'; int v = v1 + v2 + t; if (v > 10) { t = v / 10; v = v % 10; } else { t = 0; } result.insert(result.begin(), v + '0'); } if (t) result.insert(result.begin(), t + '0'); a = result; } void NativeMultiply(std::string& a, std::string& b) { FillZero(a, std::max(a.size(), b.size()) - a.size()); FillZero(b, std::max(a.size(), b.size()) - b.size()); std::string result; for (int i = a.length() - 1; i >= 0; i-- ) { std::string t; int sum = 0; int v1 = a[i] - '0'; for (int j = b.length() - 1; j >= 0; j--) { int v2 = b[j] - '0'; int v = v1 * v2 + sum; if (v > 10) { sum = v / 10; v = v % 10; } else { sum = 0; } t.insert(t.begin(), v + '0'); } if (sum) t.insert(t.begin(), sum + '0'); RightFillZero(t, a.size() - i - 1); NativeAdd(result, t); } a = result; } void BigNumber::Init(Local<Object> exports) { Isolate* isolate = exports->GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); Local<ObjectTemplate> dataTemplate = ObjectTemplate::New(isolate); dataTemplate->SetInternalFieldCount(1); Local<Object> data = dataTemplate->NewInstance(context).ToLocalChecked(); Local<FunctionTemplate> fnTemplate = FunctionTemplate::New(isolate, New, data); fnTemplate->SetClassName(ToLocalString("BigNumber")); fnTemplate->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(fnTemplate, "add", Add); NODE_SET_PROTOTYPE_METHOD(fnTemplate, "multiply", Multiply); NODE_SET_PROTOTYPE_METHOD(fnTemplate, "val", Val); Local<Function> constructor = fnTemplate->GetFunction(context).ToLocalChecked(); data->SetInternalField(0, constructor); exports->Set(context, ToLocalString("BigNumber"), constructor).FromJust(); } void BigNumber::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); if (args.IsConstructCall()) { Local<String> val = args[0].As<String>(); auto bigNumber = new BigNumber(ToCString(val)); bigNumber->Wrap(args.This()); args.GetReturnValue().Set(args.This()); return; } const int argc = 1; Local<Value> argv[] = {args[0]}; Local<Function> constructor = args.Data().As<Object>()->GetInternalField(0).As<Function>(); Local<Object> result = constructor->NewInstance(context, argc, argv).ToLocalChecked(); args.GetReturnValue().Set(result); } void BigNumber::Add(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); auto bigNumber = node::ObjectWrap::Unwrap<BigNumber>(args.Holder()); if (args[0]->IsString()) { Local<String> val = args[0].As<String>(); std::string other(ToCString(val)); NativeAdd(bigNumber->value, other); args.GetReturnValue().Set(ToLocalString(bigNumber->value.c_str())); return; } if (args[0]->IsNumber()) { int number = int(args[0].As<Number>()->NumberValue(context).FromJust()); std::string other = std::to_string(number); NativeAdd(bigNumber->value, other); args.GetReturnValue().Set(ToLocalString(bigNumber->value.c_str())); return; } if (args[0]->IsObject()) { Local<Object> object = args[0].As<Object>(); Local<Function> getVal = object->Get(context, ToLocalString("val")).ToLocalChecked().As<Function>(); Local<Value> e; Local<String> val = getVal->Call(context, args.Holder(), 0, &e).ToLocalChecked().As<String>(); std::string other(ToCString(val)); NativeAdd(bigNumber->value, other); args.GetReturnValue().Set(ToLocalString(bigNumber->value.c_str())); return; } isolate->ThrowException(Exception::TypeError(ToLocalString("Type error"))); } void BigNumber::Multiply(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); auto bigNumber = node::ObjectWrap::Unwrap<BigNumber>(args.Holder()); if (args[0]->IsString()) { Local<String> str = args[0].As<String>(); std::string other(ToCString(str)); NativeMultiply(bigNumber->value, other); args.GetReturnValue().Set(ToLocalString(bigNumber->value.c_str())); return; } if (args[0]->IsNumber()) { int number = int (args[0].As<Number>()->NumberValue(context).FromJust()); std::string other = std::to_string(number); NativeMultiply(bigNumber->value, other); args.GetReturnValue().Set(ToLocalString(bigNumber->value.c_str())); return; } if (args[0]->IsObject()) { Local<Object> obj = args[0].As<Object>(); Local<Function> getVal = obj->Get(context, ToLocalString("val")).ToLocalChecked().As<Function>(); Local<Value> e; Local<String> str = getVal->Call(context, args.Holder(), 0, &e).ToLocalChecked().As<String>(); std::string other(ToCString(str)); NativeMultiply(bigNumber->value, other); args.GetReturnValue().Set(ToLocalString(bigNumber->value.c_str())); return; } isolate->ThrowException(Exception::TypeError(ToLocalString("Type error"))); } void BigNumber::Val(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); auto bigNumber = node::ObjectWrap::Unwrap<BigNumber>(args.Holder()); args.GetReturnValue().Set(ToLocalString(bigNumber->value.c_str())); }
true
358811ca4e66c5ae11e0ee22846a91aa1fc258b7
C++
IsuraManchanayake/computer-graphics-assignments
/CGUtils/camera.cpp
UTF-8
3,153
2.828125
3
[]
no_license
#include "camera.h" #include <cmath> #include <iostream> CGUTILS_NAMESPACE_BEGIN Camera::Camera() { } Camera::Camera(const Vector<3>& pos, double angle, const Vector<3>& coa, const Vector<3>& up, double n, double f) : pos(pos), angle(angle), coa(coa), n(n), f(f) { view = (coa - pos).unit(); this->up = view.cross(up).cross(view).unit(); auto w = view.cross(this->up); auto C = Matrix<4>({ {w.x(), this->up.x(), -view.x(), 0.0}, {w.y(), this->up.y(), -view.y(), 0.0}, {w.z(), this->up.z(), -view.z(), 0.0}, { 1.0, 1.0, 1.0, 1.0} }) * Matrix<4>::traslation_mat({pos.x(), pos.y(), pos.z(), 1.0}); viewing_transform = C * Matrix<4>({ {1 / tan(angle / 2), 0.0, 0.0, 0.0}, {0.0, 1 / tan(angle / 2), 0.0, 0.0}, {0.0, 0.0, (f + n) / (f - n), -1.0}, {0.0, 0.0, (2 * f * n) / (f - n), 0.0} }); } void Camera::set_pos(const Vector<3>& pos) { view = (coa - pos).unit(); up = view.cross(up).cross(view).unit(); update_matrix(); } void Camera::set_angle(double angle) { this->angle = angle; update_matrix(); } void Camera::set_coa(const Vector<3>& coa) { this->coa = coa; view = (coa - pos).unit(); up = view.cross(up).cross(view).unit(); update_matrix(); } void Camera::set_view(const Vector<3>& view) { this->view = view; coa = pos + view * coa.norm(); up = view.cross(up).cross(view).unit(); update_matrix(); } void Camera::set_up(const Vector<3>& up) { this->up = view.cross(up).cross(view).unit(); update_matrix(); } void Camera::set_n(double n) { this->n = n; update_matrix(); } void Camera::set_f(double f) { this->f = f; update_matrix(); } void Camera::update_matrix(void) { auto w = view.cross(this->up); auto C = Matrix<4>({ {w.x(), this->up.x(), -view.x(), 0.0}, {w.y(), this->up.y(), -view.y(), 0.0}, {w.z(), this->up.z(), -view.z(), 0.0}, { 1.0, 1.0, 1.0, 1.0} }) * Matrix<4>::traslation_mat({pos.x(), pos.y(), pos.z(), 1.0}); viewing_transform = C * Matrix<4>({ {1 / tan(angle / 2), 0.0, 0.0, 0.0}, {0.0, 1 / tan(angle / 2), 0.0, 0.0}, {0.0, 0.0, (f + n) / (f - n), -1.0}, {0.0, 0.0, (2 * f * n) / (f - n), 0.0} }); } CGUTILS_NAMESPACE_END
true
3a358aaf39761698f5567578c72ae753ca602077
C++
pp1565156/PetIBM
/src/utilities/SimulationParameters.h
UTF-8
1,582
2.578125
3
[ "MIT" ]
permissive
/***************************************************************************//** * \file SimulationParameters.h * \author Anush Krishnan (anush@bu.edu) * \brief Definition of the class `SimulationParameters`. */ #if !defined(SIMULATION_PARAMETERS_H) #define SIMULATION_PARAMETERS_H #include "types.h" #include <iostream> #include <string> #include <vector> #include <petscsys.h> /** * \class SimulationParameters * \brief Stores various parameters used in the simulation */ class SimulationParameters { public: /** * \class TimeScheme * \brief Stores info about the numerical scheme to use. */ class TimeIntegration { public: TimeScheme scheme; ///< type of time-stepping scheme std::vector<PetscReal> coefficients; ///< coefficients of integration }; // TimeIntegration std::string directory; ///< directory of the simulation PetscReal dt; ///< time-increment PetscInt startStep, ///< initial time-step nt, ///< number of time steps nsave; ///< data-saving interval IBMethod ibm; ///< type of system to be solved TimeIntegration convection, ///< time-scheme for the convection term diffusion; ///< time-scheme for the diffusion term // constructors SimulationParameters(); SimulationParameters(std::string directory); // destructor ~SimulationParameters(); // parse input file and store simulation parameters void initialize(std::string filePath); // print simulation parameters PetscErrorCode printInfo(); }; // SimulationParameters #endif
true
a7c8e2f1e294bdadf420703d9c86572ebfc5e165
C++
midskavid/RenderingAlgorithms
/Assignment1/Source/Film.cpp
UTF-8
796
2.90625
3
[]
no_license
#include "Film.h" #include "../FreeImage/FreeImage.h" void Film::AddColor(Point2i pt, RGBColor color) { mFilm[pt[0]][pt[1]] = mFilm[pt[0]][pt[1]] + color; } void Film::WriteToImage(std::string fname) { FreeImage_Initialise(); FIBITMAP* img = FreeImage_Allocate(mWidth,mHeight,24); RGBQUAD c; for(int jj=0;jj<mHeight;++jj) { auto& row = mFilm[jj]; for(int ii=0;ii<mWidth;++ii) { //std::cout<<row[ii]<<std::endl; c.rgbRed = row[ii].GetRed()*255; c.rgbGreen = row[ii].GetGreen()*255; c.rgbBlue = row[ii].GetBlue()*255; //std::cout<<ii<<" "<<jj<<" "<<row[ii].GetRed()<<std::endl; FreeImage_SetPixelColor(img, ii, jj, &c); } } FreeImage_Save(FIF_PNG, img, fname.c_str(),0); }
true
3c96df1eccf981e603a33570bd9831a516913c48
C++
obada-a/s3tp
/test/s3tp_start.cpp
UTF-8
1,397
2.5625
3
[]
no_license
// // Created by lorenzodonini on 06.09.16. // #include "../core/TransportDaemon.h" int main(int argc, char ** argv) { if (argc != 4) { std::cout << "Invalid arguments. Expected unix_path, transceiver_type, start_prt" << std::endl; return -1; } s3tp_daemon daemon; TRANSCEIVER_CONFIG config; int argi = 1; int start_port = 0; socket_path = argv[argi++]; //Creating spi interface char * transceiverType = argv[argi++]; start_port = atoi(argv[argi++]); if (strcmp(transceiverType, "spi") == 0) { config.type = SPI; Transceiver::SPIDescriptor desc; config.descriptor.spi = "/dev/spidev1.1#P8_46"; config.descriptor.interrupt = PinMapper::find("P8_45"); } else if (strcmp(transceiverType, "fire") == 0) { config.type = FIRE; Transceiver::FireTcpPair pairs[S3TP_VIRTUAL_CHANNELS]; std::cout << "Created config for [port:channel]: "; for (int i=0; i < S3TP_VIRTUAL_CHANNELS; i++) { pairs[i].port = start_port + (i*2); pairs[i].channel = i; config.mappings.push_back(pairs[i]); std::cout << start_port + (i*2) << ":" << i << " "; } std::cout << std::endl; } else { std::cout << "Invalid parameters" << std::endl; return -2; } daemon.init(&config); daemon.startDaemon(); }
true
09ab0f458b7b78e9242d9754262770df2ce73473
C++
kyeonglinSong/algorithm_study
/C++/baekjoon_10448.cpp
UHC
689
3.171875
3
[]
no_license
// 19.09.16 ī ̷ #include <iostream> #include <cstdio> #include <vector> using namespace std; vector<int> arr; void calculate() { int n = 1; while (n * (n + 1) / 2 < 1000) { arr.push_back(n * (n + 1) / 2); n++; } } bool triangularNum(int n) { for (int i = 0; i < arr.size() ; i++) for (int j = 0; j < arr.size() ; j++) for (int k = 0; k < arr.size() ; k++) if (arr[i] + arr[j] + arr[k] == n) return true; return false; } int main() { int t, k; scanf("%d", &t); calculate(); for (int i = 0; i < t; i++) { scanf("%d",&k); if (triangularNum(k)) printf("1\n"); else printf("0\n"); } return 0; }
true
2c145e4e463e1f0894966273f3825a846ed63156
C++
mmardanova/C-lab-5
/src/task2.cpp
UTF-8
1,074
3
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <time.h> #include <stdlib.h> #include "task2.h" void clearMatrix(char(*arr)[M]) { for (int i = 0; i < M; i++) { for (int j = 0; j < M; j++) { arr[i][j] = ' '; } } } void fillMatrix(char(*arr)[M]) { for (int i = 0; i < (M/2); i++) { for (int j = 0; j < (M/2); j++) { int temp = rand() % 2; arr[i][j] = (temp) ? (' ') : ('*'); } } } void setMatrix(char(*arr)[M]) { for (int i = 0; i < (M / 2); i++) { for (int j = (M / 2), k = ((M / 2) - 1); j < M, k >= 0; j++, k--) { arr[i][j] = arr[i][k]; } } for (int i = (M / 2), k = ((M / 2) - 1); i < M, k >= 0; i++, k--) { for (int j = 0; j < (M / 2); j++) { arr[i][j] = arr[k][j]; } } for (int i = (M / 2), k = ((M / 2) - 1); i < M, k >= 0; i++, k--) { for (int j = (M / 2), n = ((M / 2) - 1); j < M, n >= 0; j++, n--) { arr[i][j] = arr[k][n]; } } } void printMatrix(char(*arr)[M]) { for (int i = 0; i < M; i++) { for (int j = 0; j < M; j++) { printf("%c", arr[i][j]); } printf("\n"); } }
true
6eb3c7df748cd4831d8e61dd2edab271872263ff
C++
mohamedmaged/heelo-world
/date.h
UTF-8
458
2.640625
3
[]
no_license
#ifndef DATE_H #define DATE_H class date { private: int day ; int month; int year; public: date (int d=0,int m=0,int y=0) { day =d; month=m; year=y; } void setday (int d){ day=d; } void setmonth (int m) { month=m; } void setyear (int y) { year=y; } int getday() { return day; } int getmonth() { return month; } int getyear () { return year; } }; ;;;;;; #endif // DATE_H
true
26571d5e3c384a41810353d8ab71d44b582cea9f
C++
calofmijuck/SNUCSE
/2017 Fall/Computer Programming/Studying Codes/Rational.cpp
UTF-8
2,168
3.4375
3
[]
no_license
#include <iostream> #include <cassert> #include "Rational.h" using namespace std; Rational::Rational() { SetNumerator(0); SetDenominator(1); } Rational::Rational(int numer, int denom) { SetNumerator(numer); SetDenominator(denom); } Rational::Rational(const Rational &r) { SetDenominator(r.GetNumerator()); SetDenominator(r.GetDenominator()); } Rational::~Rational() { } int Rational::GetNumerator() const { return NumeratorValue; } int Rational::GetDenominator() const { return DenominatorValue; } void Rational::SetNumerator(int numer) { NumeratorValue= numer; } void Rational::SetDenominator(int denom) { if(denom != 0) { DenominatorValue = denom; } else { cout << "Illegal denominator: " << denom << "using 1" << endl; DenominatorValue = 1; } } Rational Rational::Add(const Rational &r) const { int a = GetNumerator(); int b = GetDenominator(); int c = r.GetNumerator(); int d = r.GetDenominator(); return Rational(a * d + b * c, b * d); } Rational Rational::Multiply(const Rational &r) const { int a = GetNumerator(); int b = GetDenominator(); int c = r.GetNumerator(); int d = r.GetDenominator(); return Rational(a * c, b * d); } void Rational::Insert(ostream &sout) const { sout << GetNumerator() << "/" << GetDenominator(); } void Rational::Extract(istream &sin) { int numer; int denom; char slash; sin >> numer >> slash >> denom; assert(slash == '/'); SetNumerator(numer); SetDenominator(denom); } Rational operator+(const Rational &r, const Rational &s) { return r.Add(s); } Rational operator*(const Rational &r, const Rational &s) { return r.Multiply(s); } Rational& Rational::operator=(const Rational &r) { SetNumerator(r.GetNumerator()); SetDenominator(r.GetDenominator()); return *this; } ostream& operator<<(ostream &sout, const Rational &r) { r.Insert(sout); return sout; } istream& operator>>(istream &sin, Rational &r) { r.Extract(sin); return sin; }
true
579c44c06f801aba8c82c4c5f3b4c7f8c162c21b
C++
Setyobudi/dasar-pemrograman
/Muhammad Hakim Setyobudi/tugas_2_Muhammad_Hakim_Setyobudi.cpp
UTF-8
1,082
2.625
3
[]
no_license
#include<iostream>// #include<iostreem> using namespace std; int main()// Int main() { int nilai_a;// int nilai a; //deklarasi variabel dengan nama(nilai_a) sebagai integer cout<<"Masukkan nilai a :"; //menampilkan tulisan "Masukkan nilai a :" cin>>nilai_a;// cin<<nilai_a; /*untuk merekam inputan sebagai data //dan disimpan di variabel nilai_a*/ cout<<"nilai a yang anda masukkan adalah : "; cout<<nilai_a<<endl;// cout<<nilai_a;<<endI; //menampilkan data dari variabel nilai_a system("pause");// sistem("pause") return 0; }// ) /* Nama : M. Hakim Setyobudi Sandi : tetap seperti Tugas Individu 1 Ditambahkan pada : 20/03/13 15:49 Deskripsi : Tugas Individu 2 */ // kode Editor : 1111 01 010 11 00
true
3bbe3cc1b63106f5792c1aba474fab24a05af475
C++
imyjalil/NCRwork
/Data structures/Assignment 1/program2/program2.cpp
UTF-8
1,458
3.796875
4
[]
no_license
#include "pch.h" #include<string.h> #include <iostream> using namespace std; class Stack { int top; char *s; int size; public: Stack() { top = -1; } void setsize(int a) { size = a; s = new char[size]; } void push(char a) { if (isfull()) { cout << "Stack already full" << endl; return; } s[++top] = a; } char pop() { if (isempty()) return -1; char a = s[top--]; return a; } bool isfull() { return (top == size - 1); } bool isempty() { return (top == -1); } char peek() { if (!isempty()) return s[top]; return -1; } void display() { if (isempty()) { cout << "Stack empty" << endl; return; } for (int i = 0; i <= top; i++) cout << s[i] << " "; cout << endl; } bool check(char *str) { int i; for (i = 0; i < strlen(str); i++) { if (str[i] == '[' || str[i] == '(') { push(str[i]); } else if (str[i] == ']' || str[i] == ')') { char c = peek(); if (c == -1) break; if (str[i] == ']') { if (c == '[') { pop(); } else { break; } } else if (str[i] == ')') { if (c == '(') { pop(); } else break; } } } if (i != strlen(str) || top != -1) return true; return false; } }; int main() { cout << "Enter expression" << endl; char s[100]; cin >> s; Stack sta; sta.setsize(strlen(s) + 1); if (sta.check(s)) cout << "Unbalanced" << endl; else cout << "Balanced" << endl; }
true
b7c7743e7a1db3ac21af201c90fbe486ec46b8c3
C++
zteo-phd-software/ironstack
/common/timer.cpp
UTF-8
1,769
3.296875
3
[ "BSD-3-Clause" ]
permissive
#include "timer.h" // constructor timer::timer() { start(); deadline_ms_ = 0; } // sets the current time point and clears the sleep deadline void timer::clear() { start(); deadline_ms_ = 0; } // same as clear, but easier to understand in some code implementations void timer::reset() { clear(); } // resets the time point to the current time void timer::start() { last_ = chrono::steady_clock::now(); } // resets the time point to the current time adjusted by some displacement void timer::set_start_relative_to_now(int displacement_ms) { chrono::milliseconds time_shift(displacement_ms); last_ = chrono::steady_clock::now() - time_shift; } // setup a sleep deadline void timer::set_deadline_ms(int deadline_ms) { deadline_ms_ = deadline_ms; } // sleeps a thread until the time is up void timer::sleep_until_timer_deadline(int deadline_ms) { int time_to_sleep = 0; if (deadline_ms == -1) { time_to_sleep = deadline_ms_ - get_time_elapsed_ms(); } else { time_to_sleep = deadline_ms - get_time_elapsed_ms(); } if (time_to_sleep < 0) { return; } sleep_for_ms(time_to_sleep); } // gets the amount of time elapsed in milliseconds int timer::get_time_elapsed_ms() const { chrono::steady_clock::time_point now = chrono::steady_clock::now(); return (chrono::duration_cast<chrono::milliseconds>(now-last_)).count(); } // sleeps for a given amount of time void timer::sleep_for_ms(int interval_ms) { this_thread::sleep_for(std::chrono::milliseconds(interval_ms)); } // gets the number of milliseconds since the epoch uint32_t timer::ms_since_epoch() { chrono::time_point<chrono::system_clock, chrono::milliseconds> now = chrono::time_point_cast<chrono::milliseconds>(chrono::system_clock::now()); return now.time_since_epoch().count(); }
true
e2dce0f21a1bc569169e47904adfda3bc17a1f7b
C++
Sugrue/UOIT-Projects
/Introduction to Programming/Assignment 1/Exercise2.cpp
UTF-8
1,104
3.8125
4
[]
no_license
#include <iostream>; using namespace std; int main(){ //Variable declaration double dblAmountOfNumbers = 0, dblAverage = 0, dblNumber = 0; int intNumOfPositiveNum = 0; //requests user input for the amount of number he/she wishes to enter cout<<"Please enter the amount of numbers you wish to enter : "<<endl; cin>>dblAmountOfNumbers; for (int i = 1; i <= dblAmountOfNumbers; i++) { //Requests the numbers cout<<endl <<"Please enter a positive value = "; cin>>dblNumber; /* checks if the numbers are positive, if so calculates the new average also increments the count wish keeps track of number of numbers entered */ if (dblNumber >= 0) { dblAverage = (dblAverage + dblNumber)/i; intNumOfPositiveNum += 1; } } /* Output, checks if more than one positive number was entered by the user. if so the average is displayed, if not an error message is displayed */ if (intNumOfPositiveNum > 1) cout<<endl <<"The Average of all positive numbers entered is "<<dblAverage<<endl; else cout<<"Too few numbers were entered."<<endl; system("Pause"); return 0; }
true
d95baf24421abca78982cd9e1e1f17adb96ddd06
C++
aah867/kmeans
/parallel/support.cpp
UTF-8
7,287
2.796875
3
[]
no_license
#include <kmeans.h> using namespace std; unsigned int cluster_index[CLUSTER_SIZE]; #ifdef __linux__ double timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) { return ((timeA_p->tv_sec * 1000000) + timeA_p->tv_nsec/(double)1000) - ((timeB_p->tv_sec * 1000000) + timeB_p->tv_nsec/(double)1000); } #endif void print_simd_reg(simd_int mm_reg) { int buffer[VECSIZE32]; simd_storeu_i((simd_int*) buffer, mm_reg); for(int i=0; i<VECSIZE32; i++) { cout << buffer[i] << " "; } cout << endl; } void print_centroids( const data_t* __restrict__ centroids, int num_centroids) { printf("Scalar centroids:\n"); for(int i=0; i<num_centroids; i++) { for(int j=0; j<DIMENSION; j++) { cout << centroids[i*DIMENSION+j] << " "; } cout << endl; } } void print_simd_centroids( simd_data_t * centroids, int num_clusters ) { printf("SIMD centroids:\n"); #if 0 for(int i=0; i<num_clusters; i++) { for(int j=0; j<DIMENSION; j++) { cout << centroids[i*DIMENSION+j] << " "; } cout << endl; } #else for(int i=0; i<num_clusters; i+=VECSIZE32) { for(int ll=0; ll <VECSIZE32; ll++) { for(int kk=0; kk<DIMENSION; kk++) { cout << centroids[i*DIMENSION + kk*VECSIZE32 + ll] << " "; } cout << endl; } } #endif } void print_data( simd_data_t *data, int size) { for(int i=0; i<size; i++) { for(int j=0; j<DIMENSION; j++) { cout << data[i*DIMENSION+j] << " "; } cout << endl; } cout << endl; } unsigned long loadData(string filename, data_t *data, int max_length) { ifstream myfile (filename); if ( !myfile.good() ) { cerr << "Cannot find file." << endl; return false; } string line; unsigned long ts_length=0; while ( !myfile.eof()) { double point; if(ts_length >= max_length) break; getline (myfile,line); stringstream ss(line); for(int i=0; i<DIMENSION; i++) { ss >> point; data[ts_length*DIMENSION+i] = (int32_t)point; // cout <<ts_length+1 << ":" << data[ts_length*DIMENSION+i] << "\t"; } // cout << endl; ts_length++; } myfile.close(); return ts_length; } void get_clusterIndex(unsigned long ts_length, int num_clusters) { #if 1 //cout << "Cluster index:" << endl; for(int j=0; j<num_clusters; j++) { cluster_index[j] = rand()%ts_length; //cout << cluster_index[j] << " "; } //cout << endl; #else cluster_index[0] = 7; cluster_index[1] = 1; cluster_index[2] = 9; cluster_index[3] = 12; cluster_index[4] = 3; cluster_index[5] = 6; cluster_index[6] = 14; cluster_index[7] = 15; #endif } void load_lookup(data_t *centroids, int num_clusters, int32_t lookup[][DIMENSION]) { //cout << "\n Lookup Table is building:" << endl; for(int i=0; i<num_clusters; i++) { for(int j=0; j<DIMENSION; j++) { lookup[i][j] = (centroids[i*DIMENSION+j] * centroids[i*DIMENSION+j]) >> 1; //cout << lookup[i][j] << " "; } //cout << endl; } } void load_simd_lookup(simd_data_t *simd_centroids, int num_clusters, int32_t *simd_lookup) { for(int i=0; i<num_clusters; i++) { for(int j=0; j<DIMENSION; j+=VECSIZE32) { simd_int mm_c = simd_loadu_i((simd_int const*) &simd_centroids[i*DIMENSION+j]); mm_c = _mm_srli_epi32(simd_mul_lo(mm_c, mm_c), 0x01); simd_storeu_i((simd_int*) &simd_lookup[i*DIMENSION+j], mm_c); } } } simd_int horizontal_add(simd_int vec) { simd_int temp; temp = vec; temp = _mm_shuffle_epi32(temp, 0x39); vec = simd_add_i(temp, vec); temp = vec; temp = _mm_shuffle_epi32(temp, 0x72); vec = simd_add_i(vec, temp); return vec; } // TODO: Optimize this part by using SIMD horizontal add + SIMD extract long add_simd_int(simd_int vec) { long sum=0; int32_t tmp[VECSIZE32]; simd_storeu_i((simd_int*) tmp, vec); for(int i=0; i<VECSIZE32; i++) sum += tmp[i]; return sum; } int32_t simd_horizontal_add(simd_int vec) { int32_t sum[4]; simd_int mm_a = vec; simd_int mm_b = _mm_shuffle_epi32(mm_a, 0x39); mm_b = simd_add_i(mm_a, mm_b); mm_a = _mm_shuffle_epi32(mm_b, 0x3E); mm_b = simd_add_i(mm_a, mm_b); simd_storeu_i((simd_int*) sum, mm_b); return sum[0]; } #if __linux__ long long add_simd256_int(__m256i vec) { long long sum=0; int64_t tmp[VECSIZE32]; _mm256_storeu_si256((__m256i *) tmp, vec); for(int i=0; i<VECSIZE32; i++) sum += tmp[i]; return sum; } #endif void load_initial_clusters( data_t * centroids, int num_clusters, const data_t* data ) { // cout << "\n Initial cluster values:" << endl; for(int i=0; i<num_clusters; i++) { int indx = cluster_index[i]; // cout << indx << ":\t"; for(int j=0; j<DIMENSION; j++) { centroids[i*DIMENSION+j] = data[indx*DIMENSION+j]; // cout << centroids[i*DIMENSION+j] << "\t"; } // cout << endl; } // cout << endl; } void load_simd_data( simd_data_t* simd_data, data_t* data, unsigned long N) { int x_indx = 0; int y_indx = 0; int ctr = 0; int x_base = 0; for(int i=0; i<N; i++) { for(int j=0; j<DIMENSION; j++) { *(simd_data+i*DIMENSION+j) = data[x_indx*DIMENSION+y_indx]; x_indx++; if(x_indx%VECSIZE32 == 0) { x_indx = x_base; y_indx++; if(y_indx%DIMENSION==0) { ctr++; y_indx = 0; x_base = ctr*VECSIZE32; x_indx = x_base; } } } } #if 0 cout << "SIMD Data:" << endl; for(int i=0; i<N; i++) { for(int j=0; j<DIMENSION; j++) { cout << *(simd_data+i*DIMENSION + j) << " "; } cout << endl; } #endif } void load_comp_data( comp_ds_t* comp_data, simd_data_t* simd_data, unsigned long N) { for(int i=0; i<N*DIMENSION; i++) { comp_data[i] = (comp_ds_t) simd_data[i]; int32_t tmp_data = (int32_t) comp_data[i]; if(tmp_data != (simd_data[i])) { cout << "ERROR: " << tmp_data << " != " << simd_data[i] << endl; exit(0); } } } void load_initial_simd_clusters( simd_data_t * centroids, int num_clusters, const data_t* data ) { #if 0 for(int i=0; i<num_clusters; i++) for(int j=0; j<DIMENSION; j++) centroids[j*num_clusters+i] = data->point[cluster_index[i]*DIMENSION+j]; #endif for(int i=0; i<num_clusters; i++) { int B=i/VECSIZE32; int C=i%VECSIZE32; for(int j=0; j<DIMENSION; j++) { centroids[B*DIMENSION*VECSIZE32+j*VECSIZE32+C]=data[cluster_index[i]*DIMENSION+j]; } } // cout << "\n Initial SIMD cluster values:" << endl; // print_data(centroids, num_clusters); #if 0 for(int i=0; i<num_clusters; i++) { for(int j=0; j<DIMENSION; j++) { //cout << centroids[i*DIMENSION+j] << " "; ////cout << centroids->points[j*num_clusters + i] << " "; // For comparison } //cout << endl; } //cout << endl; //cout << "????? VEC ?????" << endl; for(int i=0; i<num_clusters; i++) { for(int j=0; j<DIMENSION; j++) { //cout << *(centroids+j*VECSIZE32 + i) << " "; if( j== DIMENSION-1) { //cout << endl; } } //cout << endl; } #endif } void warmup_cache() { srand((unsigned)time(0)); int *a = (int*) malloc(4096*4096*sizeof(int)); int *b = (int*) malloc(4096*4096*sizeof(int)); int *c = (int*) malloc(4096*4096*sizeof(int)); for(int i=0; i<4096*4096; i++) { a[i] = (int) rand()/RAND_MAX; b[i] = (int) rand()/RAND_MAX; } for(int i=0; i<4096*4096; i++) { c[i] = a[i] + b[i]; } free(a); free(b); free(c); }
true
758dd8b7537f974cd85fd51ee022209faef49ca1
C++
aFleetingTime/Cpp
/14.OverloadedOperatorAndTypeConversion/42/FunctionObject.cpp
UTF-8
1,339
2.828125
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <iterator> #include <functional> #include <random> using namespace std::placeholders; int main() { std::vector<std::string> b; std::copy(std::istream_iterator<std::string>(std::cin), std::istream_iterator<std::string>(), std::back_inserter(b)); std::vector<int> a; int(*Stoi)(const std::string&, std::size_t*, int) = std::stoi; std::transform(b.cbegin(), b.cend(), std::back_inserter(a), std::bind(Stoi, _1, nullptr, 0)); constexpr std::size_t TargetMaxNum = 1024; constexpr const char *TargetStr = "pooh"; std::mt19937 g(1729); b.emplace(b.begin() + std::uniform_int_distribution<>(0, b.size())(g), TargetStr); std::size_t num = std::count_if(a.cbegin(), a.cend(), std::bind(std::greater<int>(), _1, TargetMaxNum)); auto index = std::find_if(b.cbegin(), b.cend(), std::bind(std::not_equal_to<std::string>(), _1, TargetStr)); std::transform(a.cbegin(), a.cend(), a.begin(), std::bind(std::multiplies<int>(), _1, 2)); ; std::cout << "(a) " << num << std::endl; std::copy(b.cbegin(), b.cend(), std::ostream_iterator<std::string>(std::cout, " ")); std::cout << "\n(b) " << (index - b.cbegin()) << std::endl; std::cout << "(c) "; std::copy(a.cbegin(), a.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; }
true
31bccddf4b4144f2c4b66168f1b2574237aa02e6
C++
Humblefool14/UVa-solutions
/Numbers/382 Perfection.cpp
UTF-8
462
3.03125
3
[]
no_license
#include<bits/stdc++.h> #include<iostream> using namespace std; int main() { int t; cout << "Perfection Output" << endl; while(cin >> t,t>0) { int sum=0; for(int i=2;i<=(t/2);i++) { if(t%i==0) { sum+=i; } } if(sum > t) cout << t << " Abundant" << endl; if(sum==t) cout << t << " Perfect" << endl; if(sum<t) cout << t<< " Deficient" << endl; } cout << "End of Output"<< endl; return 0; }
true
3670ae6107e4ba7773f621ae99b03510bc8af607
C++
9chu/et
/src/Base.cpp
UTF-8
5,844
2.59375
3
[ "MIT" ]
permissive
/** * @file * @author chu * @date 2018/1/7 */ #include <et/Base.hpp> #include <set> #include <fstream> using namespace std; using namespace et; //////////////////////////////////////////////////////////////////////////////// LuaHelper namespace { class KeywordList { public: KeywordList() { m_stList.emplace("and"); m_stList.emplace("false"); m_stList.emplace("local"); m_stList.emplace("then"); m_stList.emplace("break"); m_stList.emplace("for"); m_stList.emplace("nil"); m_stList.emplace("true"); m_stList.emplace("do"); m_stList.emplace("function"); m_stList.emplace("not"); m_stList.emplace("until"); m_stList.emplace("else"); m_stList.emplace("goto"); m_stList.emplace("or"); m_stList.emplace("while"); m_stList.emplace("elseif"); m_stList.emplace("if"); m_stList.emplace("repeat"); m_stList.emplace("end"); m_stList.emplace("in"); m_stList.emplace("return"); } public: bool operator()(const std::string& test)const noexcept { return m_stList.find(test) != m_stList.end(); } bool operator()(const char* test)const noexcept { return m_stList.find(test) != m_stList.end(); } private: set<string> m_stList; }; } bool et::IsLuaIdentifier(const char* raw)noexcept { size_t len = strlen(raw); if (len == 0) return false; for (size_t i = 0; i < len; ++i) { char ch = raw[i]; if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_' || (i > 0 && ch >= '0' && ch <= '9'))) return false; } return true; } bool et::IsLuaKeyword(const char* raw)noexcept { static const KeywordList kKeywords {}; return kKeywords(raw); } bool et::IsLuaKeyword(const std::string& raw)noexcept { static const KeywordList kKeywords {}; return kKeywords(raw); } //////////////////////////////////////////////////////////////////////////////// StringUtils std::string et::Format(const char* format, ...)noexcept { va_list args; va_start(args, format); auto str(FormatV(format, args)); va_end(args); return str; } std::string et::FormatV(const char* format, std::va_list args)noexcept { string ret; // 计算format后占用大小 va_list ap; va_copy(ap, args); const int l = vsnprintf(nullptr, 0, format, ap); va_end(ap); if (l < 0) return string(); // 尝试分配足够大小 try { ret.resize(static_cast<size_t>(l)); } catch (...) { ret.clear(); return ret; } // 执行format if (l > 0) vsprintf(&ret[0], format, args); return ret; } void et::TrimEnd(std::string& str)noexcept { while (!str.empty()) { char last = str.back(); if (last > 0 && isspace(last)) str.pop_back(); else break; } } //////////////////////////////////////////////////////////////////////////////// ReadFile std::string et::GetFileName(const char* path) { const char* lastFilenameStart = path; while (*path) { char c = *path; if (c == '\\' || c == '/') lastFilenameStart = path + 1; ++path; } return string(lastFilenameStart); } void et::ReadFile(std::string& out, const char* path) { out.clear(); ifstream t(path, ios::binary); if (!t.good()) ET_THROW(IOException, "Open file \"%s\" error", path); t.seekg(0, std::ios::end); if (!t.good()) ET_THROW(IOException, "Seek to end on file \"%s\" error", path); auto size = t.tellg(); if (size < 0) ET_THROW(IOException, "Tellg on file \"%s\" error", path); out.reserve(size); t.seekg(0, std::ios::beg); if (!t.good()) ET_THROW(IOException, "Seek to begin on file \"%s\" error", path); out.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); if (out.length() != (size_t)size) ET_THROW(IOException, "Read file \"%s\" error", path); } //////////////////////////////////////////////////////////////////////////////// Exception Exception::Exception(const char* file, int line, const char* func, const char* format, ...) : m_pszFile(file), m_iLine(line), m_pszFunc(func) { va_list args; va_start(args, format); auto description(FormatV(format, args)); va_end(args); m_pDescription = make_shared<string>(std::move(description)); } Exception::Exception(const Exception& rhs)noexcept : m_pszFile(rhs.m_pszFile), m_iLine(rhs.m_iLine), m_pszFunc(rhs.m_pszFunc), m_pDescription(rhs.m_pDescription) { } Exception::Exception(Exception&& rhs)noexcept { std::swap(m_pszFile, rhs.m_pszFile); std::swap(m_iLine, rhs.m_iLine); std::swap(m_pszFunc, rhs.m_pszFunc); std::swap(m_pDescription, rhs.m_pDescription); } Exception& Exception::operator=(const Exception& rhs)noexcept { m_pszFile = rhs.m_pszFile; m_iLine = rhs.m_iLine; m_pszFunc = rhs.m_pszFunc; m_pDescription = rhs.m_pDescription; return *this; } Exception& Exception::operator=(Exception&& rhs)noexcept { m_pszFile = rhs.m_pszFile; m_iLine = rhs.m_iLine; m_pszFunc = rhs.m_pszFunc; m_pDescription = rhs.m_pDescription; rhs.m_pszFile = nullptr; rhs.m_iLine = 0; rhs.m_pszFunc = nullptr; rhs.m_pDescription = nullptr; return *this; } const char* Exception::GetDescription()const noexcept { return m_pDescription ? m_pDescription->c_str() : ""; } const char* Exception::what()const noexcept { return GetDescription(); }
true
177abffdd102592b39da03d83fc1f0df9b8c2acb
C++
ziyuhuang/BankingSystem
/Account.h
UTF-8
1,810
3.21875
3
[]
no_license
// // Account.h // BankingSystem // // Created by ZIYU HUANG on 10/30/16. // Copyright © 2016 ZIYU HUANG. All rights reserved. // #ifndef Account_h #define Account_h #include "Customer.h" #include <string> #include "DepositTransaction.hpp" #include "WithdrawTransaction.hpp" #include <list> #include "Exception.h" using namespace std; class Account{ public: //constructor //theId: account id //theBalance: initial balance //thePassword: passowrd of the account //theCustomer: customer of the account Account(int theId, float theBalance, string thePassword, Customer theCustomer); //return the id of the account int getAccountNumber() const {return account_id;}; //return the balance of this account float getBalance() const {return balance;}; //set new balance of this account //newBalance: new balance to set void setBalance(float newBalance){balance = newBalance;} //return the password of the account string getPassword(){return password;} //withdraw from the account //transaction: transaction to perform virtual bool withdraw(WithdrawTransaction transaction); //deposit to the account //transaction: transaction to perform bool deposit(DepositTransaction transaction); //list the acctivities of the account over time void showAccountActivities(); //accessor function for CheckingAccount & SavingAccount class void addWithdrawTransaction(WithdrawTransaction transaction) {tranSacRecords.push_back(transaction);} //get customer Customer getCustomer() const{ return customer; } private: int account_id; float balance; string password; Customer customer; list<Transaction> tranSacRecords; }; #endif /* Account_h */
true
02e74f8d84365d5e677a0c9d859de3a15801e353
C++
xb985547608/VIDICON
/InterfacialDesign/Switch/switchwidget.cpp
UTF-8
3,138
2.53125
3
[]
no_license
#include "switchwidget.h" #include "ui_switchform.h" #include <QDebug> SwitchWidget::SwitchWidget(QWidget *parent) : QWidget(parent), ui(new Ui::SwitchForm) { ui->setupUi(this); connect(ui->btnWelcome, SIGNAL(clicked()), this, SLOT(onWelcomeBtn())); connect(ui->btnPreview, SIGNAL(clicked()), this, SLOT(onPreviewBtn())); connect(ui->btnPlayback, SIGNAL(clicked()), this, SLOT(onPlaybackBtn())); connect(ui->btnPhoto, SIGNAL(clicked()), this, SLOT(onPhotoBtn())); connect(ui->btnSettings, SIGNAL(clicked()), this, SLOT(onSettingsBtn())); connect(ui->btnLogout, SIGNAL(clicked()), this, SLOT(onLogoutBtn())); onWelcomeBtn(); } SwitchWidget::~SwitchWidget() { } void SwitchWidget::refreshProperty(QWidget *widget, const char *name, const QVariant &value) { widget->setProperty(name, value); widget->style()->unpolish(widget); widget->style()->polish(widget); } void SwitchWidget::resetMenuProperty() { refreshProperty(ui->btnWelcome, "choice", "false"); refreshProperty(ui->btnPreview, "choice", "false"); refreshProperty(ui->btnPlayback, "choice", "false"); refreshProperty(ui->btnPhoto, "choice", "false"); refreshProperty(ui->btnSettings, "choice", "false"); } void SwitchWidget::setSettingsBtnVisible(bool visible) { ui->btnSettings->setVisible(visible); } void SwitchWidget::switchWidgetHandler(SwitchWidget::SwitchState form) { switch(form){ case SwitchWidget::Main: resetMenuProperty(); refreshProperty(ui->btnWelcome, "choice", "true"); emit signalSwitchState(SwitchWidget::Main); break; case SwitchWidget::Preview: resetMenuProperty(); refreshProperty(ui->btnPreview, "choice", "true"); emit signalSwitchState(SwitchWidget::Preview); break; case SwitchWidget::Playback: resetMenuProperty(); refreshProperty(ui->btnPlayback, "choice", "true"); emit signalSwitchState(SwitchWidget::Playback); break; case SwitchWidget::Photo: resetMenuProperty(); refreshProperty(ui->btnPhoto, "choice", "true"); emit signalSwitchState(SwitchWidget::Photo); break; case SwitchWidget::Settings: resetMenuProperty(); refreshProperty(ui->btnSettings, "choice", "true"); emit signalSwitchState(SwitchWidget::Settings); break; default: break; } } void SwitchWidget::onWelcomeBtn() { switchWidgetHandler(SwitchWidget::Main); } void SwitchWidget::onPreviewBtn() { switchWidgetHandler(SwitchWidget::Preview); } void SwitchWidget::onPlaybackBtn() { switchWidgetHandler(SwitchWidget::Playback); } void SwitchWidget::onPhotoBtn() { switchWidgetHandler(SwitchWidget::Photo); } void SwitchWidget::onSettingsBtn() { switchWidgetHandler(SwitchWidget::Settings); } void SwitchWidget::onLogoutBtn() { emit signalLogout(); }
true
42619c5194e2e7be3a349eaad3edcd892f3c9fc9
C++
isant028/cs100_lab8_VisitorPattern
/Mult.hpp
UTF-8
988
3.140625
3
[]
no_license
#ifndef __MULT_HPP__ #define __MULT_HPP__ #include "base.hpp" class Mult : public Base { public: double value1; double value2; double testfinal; Base* leftnode; Base* rightnode; Mult(Base* test1,Base* test2) : Base() { leftnode = test1; rightnode = test2; value1 = test1->evaluate(); value2 = test2 ->evaluate(); testfinal = value1 * value2; } virtual double evaluate() {return testfinal;} virtual std::string stringify() {return std::to_string(value1) + "*" + std::to_string(value2);} Iterator* create_iterator(){ Iterator* it = new BinaryIterator(this); return it; } Base* get_left(){ return this->leftnode; } Base* get_right(){ return this->rightnode; } void accept(CountVisitor* myvisitor){ myvisitor->visit_mult(); } }; #endif //__MULT_HPP__
true
666c5e3468ea79a568bd11ef0794d09e5ff676b1
C++
j-thomps21/CS
/IC210/homework/hw31/vector.h
UTF-8
279
2.515625
3
[]
no_license
#include <iostream> #include <string> #include <cmath> using namespace std; struct Vector { int vals[4]; }; Vector operator-(Vector a, Vector b); Vector operator+(Vector a, Vector b); istream& operator>>(istream &in, Vector &a); ostream& operator<<(ostream &out, Vector a);
true
304f4a9554c3f804ea828617f3b853adea1ecc3b
C++
Reesing/learn
/cpp/cpp.primer/exercises/4.6/iter.cc
UTF-8
565
3.375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { vector<string> svec = {"a","b","c","d","e"}; auto iter = svec.begin(); cout << "*iter++:" << *iter++ << endl; //error:cout << "(*iter)++:" << (*iter)++ << endl; //error:cout << "*iter.empty():" << *iter.empty() << endl; cout << "(*iter).empty():" << (*iter).empty() << endl; cout << "iter->empty():" << iter->empty() << endl; //error:cout << "++*iter:" << ++*iter << endl; cout << "(++iter)->empty():" << (++iter)->empty() << endl; return 0; }
true
27ce06beee903cfd8098bf62145de26077a676d4
C++
IamGary24/CollegeCourseWork
/GaryFowler_Program3Starcraft/GaryFowler_Program3Starcraft/SuperSoldier.cpp
UTF-8
3,555
3.078125
3
[]
no_license
//SuperSoldier.cpp //Class functions for Supersoldier derived class //Created by: Gary Fowler //for Dr. McWhorter CSCI 428 Program 3 #include "stdafx.h" #include <iostream> //included class definition files #include "SuperSoldier.h" //initialize flamethrower damage and ammo int SuperSoldier::grenadeDamage = 40; //grenade damage int SuperSoldier::launcherDamage = 30; //launcher damage int SuperSoldier::superAid = 20; SuperSoldier::SuperSoldier() { } SuperSoldier::SuperSoldier(string tempName, string tempType, string tempTeam) : Infantry(tempName, tempType, tempTeam), Firebat(tempName, tempType, tempTeam), Ghost(tempName, tempType, tempTeam), Marine(tempName, tempType, tempTeam), Medic(tempName, tempType, tempTeam) { setStickyGrenade(10); setRocketLauncher(10); } void SuperSoldier::setStickyGrenade(int tempStickyGrenade) { stickyGrenade = 5; } int SuperSoldier::getStickyGrenade() { return stickyGrenade; } void SuperSoldier::setRocketLauncher(int tempRocketLauncher) { Infantry::setPistol(tempRocketLauncher); rocketLauncher = Infantry::getPistol(); } int SuperSoldier::getRocketLauncher() { return rocketLauncher; } void SuperSoldier::speak() { cout << endl; cout << Infantry::getName() << ": I am ready" << endl; } void SuperSoldier::display() { Infantry::display(); bool cloak; string cloakon; if (getCloak()) { cloakon = "on"; } else { cloakon = "off"; } cout << right << setw(8) << getAssaultRifle() << setw(8) << getFlameThrower() << setw(8) << getSniperRifle() << setw(8) << cloakon << setw(7) << getBoosterShot(); } void SuperSoldier::attack(Infantry* inoutbeingAttacked) { //attack first with grenade if (stickyGrenade != 0 && this->Infantry::getHealth() != 0 && inoutbeingAttacked->getHealth() != 0) { stickyGrenade--; inoutbeingAttacked->getAttacked(grenadeDamage); } else if (this->Infantry::getHealth() <= 0) { cout << endl; cout << Infantry::getName() << " is dead."; } else if (inoutbeingAttacked->getHealth() <= 0) { cout << endl; cout << "He has been vanguished."; } else if (stickyGrenade == 0) { cout << endl; cout << "It cannot be done, I have no more grenades."; } //attack second with rocket launcher if (rocketLauncher != 0 && this->Infantry::getHealth() != 0 && inoutbeingAttacked->getHealth() != 0) { rocketLauncher--; Infantry::setPistol(rocketLauncher); inoutbeingAttacked->getAttacked(launcherDamage); } else if (this->Infantry::getHealth() <= 0) { cout << endl; cout << Infantry::getName() << " is dead."; } else if (inoutbeingAttacked->getHealth() <= 0) { cout << endl; cout << "He has been vanguished."; } else if (stickyGrenade == 0) { cout << endl; cout << "It cannot be done, I have no more rockets."; } } void SuperSoldier::renderAid(Infantry* inoutbeingHelped) { if (this->Infantry::getHealth() != 0 && inoutbeingHelped->getHealth() != 0) { if (inoutbeingHelped->getHealth() > 50) { cout << endl; cout << "I will not, they should fight"; } else if (inoutbeingHelped->getHealth() <= 50) { cout << endl; cout << "Let me aid him."; inoutbeingHelped->receiveAid(superAid); } } } void SuperSoldier::getAttacked(int damage) { Infantry::getAttacked(damage); } void SuperSoldier::receiveAid(int healthBoost) { Infantry::receiveAid(healthBoost); } void SuperSoldier::die() { this->Infantry::setHealth(0); stickyGrenade = 0; rocketLauncher = 0; Infantry::setPistol(0); cout << endl; cout << this->Infantry::getName() << ": has died."; } SuperSoldier::~SuperSoldier() { }
true
da1c2baa4f11369b3ff04778be5af4c4b9403ec5
C++
ailyanlu1/Programming-Challenges
/poj/poj1625.cpp
UTF-8
5,212
2.65625
3
[]
no_license
# include <iostream> # include <cstdio> # include <cstring> const int SMAX = 223; const int CMAX = 50; const int PMAX = 50; const int NMAX = 10; int ID_MAP[SMAX]; const int BASE = 10000; const int DLEN = 100; class BigInt { public: int n; short d[DLEN]; BigInt(): n(1) { memset(d, 0, sizeof(short)*DLEN); } BigInt(int q): n(1) { memset(d, 0, sizeof(short)*DLEN); d[0] = q; } BigInt operator+ (const BigInt& M) const { BigInt R; int i = 0, v = 0; while(i < n || i < M.n){ R.d[i] = d[i] + M.d[i] + v; v = R.d[i] / BASE; R.d[i] %= BASE; ++i; } if(v > 0){ R.d[i++] = v; } R.n = i; return R; } BigInt& operator+= (const BigInt& M) { int i = 0, v = 0; while(i < n || i < M.n){ d[i] += M.d[i] + v; v = d[i] / BASE; d[i] %= BASE; ++i; } if(v > 0){ d[i++] = v; } n = i; return *this; } void print() const { printf("%d", d[n-1]); for(int i = n-2; i >= 0; --i){ printf("%04d", d[i]); } printf("\n"); } }; BigInt dp[PMAX*NMAX][PMAX]; class AC_AUTO { private: struct TNode { bool invalid; int fail; int next[CMAX]; } T[PMAX*NMAX]; int root; int size; int lsize; public: void init(int _lsize) { root = 0; size = 1; lsize = _lsize; for(int i = 0; i < PMAX*NMAX; ++i){ T[i].invalid = false; T[i].fail = -1; for(int j = 0; j < lsize; ++j){ T[i].next[j] = -1; } } } void insert(const unsigned char* str) { int cur = root; for(int i = 0; str[i] != '\0'; ++i){ int k = ID_MAP[str[i]]; if(T[cur].next[k] == -1){ T[cur].next[k] = size++; } cur = T[cur].next[k]; } T[cur].invalid = true; } void build_fail() { int head = 0, tail = 0; int Q[PMAX*NMAX]; for(int i = 0; i < lsize; ++i){ if(T[root].next[i] != -1){ T[T[root].next[i]].fail = root; Q[tail++] = T[root].next[i]; } } while(head != tail){ int cur = Q[head++]; for(int i = 0; i < lsize; ++i){ if(T[cur].next[i] != -1){ int p = T[cur].fail; while(p != -1){ if(T[p].next[i] != -1){ T[T[cur].next[i]].fail = T[p].next[i]; T[T[cur].next[i]].invalid |= T[T[p].next[i]].invalid; break; } p = T[p].fail; } if(p == -1) T[T[cur].next[i]].fail = root; Q[tail++] = T[cur].next[i]; } } } } void build_states(int len) { BigInt E(1); for(int j = 0; j < lsize; ++j){ if(T[root].next[j] != -1){ if(!T[T[root].next[j]].invalid){ dp[T[root].next[j]][1] = E; } }else{ dp[root][1] = dp[root][1] + E; } } for(int i = 2; i <= len; ++i){ for(int j = 0; j < size; ++j){ if(T[j].invalid) continue; for(int k = 0; k < lsize; ++k){ if(T[j].next[k] != -1){ if(!T[T[j].next[k]].invalid){ dp[T[j].next[k]][i] += dp[j][i-1]; } }else{ int p = T[j].fail; while(p != -1){ if(T[p].next[k] != -1){ if(!T[T[p].next[k]].invalid){ dp[T[p].next[k]][i] += dp[j][i-1]; } break; } p = T[p].fail; } if(p == -1) dp[root][i] += dp[j][i-1]; } } } } } void solve(int len) { BigInt R; for(int i = 0; i < size; ++i){ if(T[i].invalid) continue; R += dp[i][len]; } R.print(); } }; void init_id_map(const unsigned char* letters) { for(int i = 0; i < SMAX; ++i){ ID_MAP[i] = -1; } for(int i = 0; letters[i] != '\0'; ++i){ ID_MAP[letters[i]] = i; } } int main() { unsigned char letters[PMAX+1]; int n, m, p; scanf("%d%d%d", &n, &m, &p); getchar(); gets((char*)letters); init_id_map(letters); AC_AUTO ac_trie; ac_trie.init(n); for(int i = 0; i < p; ++i){ gets((char*)letters); ac_trie.insert(letters); } ac_trie.build_fail(); ac_trie.build_states(m); ac_trie.solve(m); return 0; }
true
a50e2487dbd76b7919c1a070c82c825dbc96c664
C++
Delt4Squad/Hand-Bot
/Recepteur.ino
UTF-8
2,126
2.65625
3
[]
no_license
#include <VirtualWire.h> const char* MSGA = "A"; //Avant const char* MSGB = "B"; //Arriere const char* MSGC = "C"; //Gauche const char* MSGD = "D"; //Droite const char* MSGE = "E"; //Avant + Droite const char* MSGF = "F"; //Avant + Gauche const char* MSGG = "G"; //Arriere + Droite const char* MSGH = "H"; //Arriere + Gauche const char* MSGP = "P"; //Retourner -> Pause const char* MSGZ = "Z"; //Rien const char* MSGI = "I"; //Monter const char* MSGJ = "J"; //Descendre const char* MSGK = "K"; //Serrer const char* MSGL = "L"; //Desserer void setup() { Serial.begin(9600); vw_setup(2000); vw_rx_start(); } void loop() { byte message[VW_MAX_MESSAGE_LEN]; byte taille_message = VW_MAX_MESSAGE_LEN; vw_wait_rx(); if (vw_get_message(message, &taille_message)) { if (strcmp((char*) message, MSGA) == 0){ Serial.println("AVANT"); } else if (strcmp((char*) message, MSGB) == 0) { Serial.println("ARRIERE"); } else if (strcmp((char*) message, MSGC) == 0) { Serial.println("GAUCHE"); } else if (strcmp((char*) message, MSGD) == 0) { Serial.println("DROITE"); } else if (strcmp((char*) message, MSGE) == 0) { Serial.println("AVANT DROITE"); } else if (strcmp((char*) message, MSGF) == 0) { Serial.println("AVANT GAUCHE"); } else if (strcmp((char*) message, MSGG) == 0) { Serial.println("ARRIERE DROITE"); } else if (strcmp((char*) message, MSGH) == 0) { Serial.println("ARRIERE GAUCHE"); } else if (strcmp((char*) message, MSGI) == 0) { Serial.println("MONTER"); } else if (strcmp((char*) message, MSGJ) == 0) { Serial.println("DESCENDRE"); } else if (strcmp((char*) message, MSGK) == 0) { Serial.println("SERRER"); } else if (strcmp((char*) message, MSGL) == 0) { Serial.println("DESSERRER"); } else if (strcmp((char*) message, MSGP) == 0) { Serial.println("PAUSE"); } else if (strcmp((char*) message, MSGZ) == 0) { Serial.println("---"); } else{ Serial.println("Message corrompu"); } } }
true
0d0290a937d062ed9e139c0d673be702ac6d63d8
C++
bnavarma/SharedMemory
/SharedMemory/b_tree.h
UTF-8
4,775
2.8125
3
[]
no_license
#pragma once #include "shared_memory.h" #include "pool_allocator.h" template <class A, class B> class b_tree { public: IndexNode<A> *root; void* page_start; pool_allocator<IndexNode<A>, MaxSize>* idx_allocator; pool_allocator<LeafNode<A, B>, MaxSize>* leaf_allocator; pool_allocator<B, MaxSize>* data_allocator; b_tree(void* pg_start, size_t tree_start, size_t alloc_start); int search(int key, IndexNode<A>* node); int search(int key, LeafNode<A, B>* node); void node_split(IndexNode<A>* node); void node_split(LeafNode<A, B>* node); void insert_non_split(int key, IndexNode<A>* node, void* data_node); void insert_non_split(int key, LeafNode<A, B>* node, B* value); void insert_rec(int key, IndexNode<A>* node, void* value); void insert(int key, B* value); }; template<class A, class B> b_tree<A, B>::b_tree(void* pg_start, size_t tree_start, size_t alloc_start) { page_start = pg_start; root = (IndexNode<A>*) tree_start; idx_allocator = &pool_allocator<IndexNode<A>, MaxSize>(pg_start, alloc_start); size_t temp_leaf_off = alloc_start + 2 ^ 10 + MaxSize*(sizeof(IndexNode<A>) + sizeof(size_t)); leaf_allocator = &pool_allocator<LeafNode<A,B>, MaxSize>(pg_start, temp_leaf_off); size_t data_leaf_off = temp_leaf_off + 2 ^ 10 + MaxSize*(sizeof(LeafNode<A, B>) + sizeof(size_t)); data_allocator = &pool_allocator<B, MaxSize>(pg_start, data_leaf_off); if (*((int*)root) == NULL) { root = idx_allocator->allocate(); insert(0, NULL); } } template <class A, class B> int b_tree<A, B>::search(int key, IndexNode<A>* node) { auto temp = 0; for (auto i = 0; i < BranchSize; i++) { temp = i; if (key >= node->keys[i]) { break; } } if (key > node->keys[BranchSize - 1]) { temp = BranchSize; } return temp; } template <class A, class B> int b_tree<A, B>::search(int key, LeafNode<A, B>* node) { for (auto i = 0; i < BranchSize; i++) { if (key == node->keys[i]) { return i; } if (key > node->keys[i]) { return i; } } throw; } template<class A, class B> void b_tree<A, B>::node_split(IndexNode<A>* node) { auto temp = idx_allocator->allocate(); for (auto i = (BranchSize / 2) + 1; i <= BranchSize; i++) { if (i != BranchSize) { temp->keys[i - (BranchSize / 2) - 1] = node->keys[i]; node->keys[i] = NULL; } temp->nodes[i - (BranchSize / 2) - 1] = node->nodes[i]; node->nodes[i] = NULL; } node->keys[BranchSize / 2] = NULL; temp->next = node->next; temp->prev = node; node->next = temp; } template <class A, class B> void b_tree<A, B>::node_split(LeafNode<A, B>* node) { auto temp = leaf_allocator->allocate(); for (auto i = BranchSize / 2; i < BranchSize; i++) { temp->keys[i - (BranchSize / 2)] = node->keys[i]; temp->values[i - (BranchSize / 2)] = node->values[i]; node->keys[i] = NULL; node->values[i] = NULL; } temp->next = node->next; temp->prev = node; node->next = temp; } template <class A, class B> void b_tree<A, B>::insert_non_split(int key, IndexNode<A>* node, void* data_node) { int idx = search(key, node); for (auto i = BranchSize; i > idx; i--) { if (i == BranchSize) { node->nodes[i] = node->nodes[i - 1]; } else { node->keys[i] = node->keys[i - 1]; node->nodes[i] = node->nodes[i - 1]; } } node->keys[idx] = key; node->nodes[idx] = static_cast<Node*>(data_node); } template<class A, class B> void b_tree<A, B>::insert_non_split(int key, LeafNode<A, B>* node, B* data_node) { int idx = search(key, node); for (auto i = BranchSize - 1; i > idx; i--) { node->keys[i] = node->keys[i - 1]; node->values[i] = node->values[i - 1]; } node->keys[idx] = key; node->values[idx] = data_node; } template <class A, class B> void b_tree<A, B>::insert_rec(int key, IndexNode<A>* node, void* value) { auto idx = search(key, node); Node* temp = node->nodes[idx]; IndexNode<A>* idx_node = dynamic_cast<IndexNode<A>*>(temp); if (idx_node != NULL) { if (idx_node->keys[BranchSize - 1] != NULL) { node_split(idx_node); insert_non_split(idx_node->next->keys[0], node, idx_node->next); } if (key > idx_node->next->keys[0]) { insert_rec(key, idx_node->next, value); } else { insert_rec(key, idx_node, value); } } LeafNode<A, B>* leaf_node = dynamic_cast<LeafNode<A, B>*>(temp); if (leaf_node != NULL) { if (leaf_node->keys[BranchSize - 1] != NULL) { node_split(leaf_node); insert_non_split(leaf_node->next->keys[0], node, leaf_node->next); } if (key > leaf_node->next->keys[0]) { insert_non_split(key, leaf_node->next, static_cast<B*>(value)); } else { insert_non_split(key, leaf_node, static_cast<B*>(value)); } } } template <class A, class B> void b_tree<A, B>::insert(int key, B* value) { if (root->keys[BranchSize] != NULL) { node_split(root); } insert_rec(key, root, value); }
true
cb2822b05f23a5487e671cbb01e7e01847328a7a
C++
vgasparyan1995/OnLineHiring
/RandomPermutator.cpp
UTF-8
987
3.078125
3
[]
no_license
#include "RandomPermutator.h" #include <algorithm> #define pow_3(n) ((n)*(n)*(n)) std::random_device RandomPermutator::s_rd; std::mt19937 RandomPermutator::s_generator(s_rd()); int RandomPermutator::uniform_random(const int from, const int to) { std::uniform_int_distribution<> distributor(from, to); return distributor(s_generator); } std::vector<int> RandomPermutator::get_one(const int size) { std::vector<int> permutation; RandomPermutator::Transposition transposition; for (int i = 0; i < size; ++i) { transposition.push_back( std::make_pair(i, uniform_random(1, pow_3(size)))); } std::sort(transposition.begin(), transposition.end(), [] (const TranspositionUnit& lhs, const TranspositionUnit& rhs) -> bool { return lhs.second < rhs.second; }); for (const auto& unit : transposition) { permutation.push_back(unit.first); } return permutation; }
true
68909793b5236a7f01ae2250b1bd60e774de4426
C++
aorura/fontLength
/FontDumy/LengthCalculationDummy8.h
UTF-8
4,498
2.765625
3
[]
no_license
#ifndef LENGTHCALCULATIONDUMMY8_H #define LENGTHCALCULATIONDUMMY8_H #include "LengthCalculationInterface.h" #include <QObject> class LengthCalculationDummy8 : public QObject, public LengthCalculationInterface { Q_OBJECT Q_INTERFACES(LengthCalculationInterface) public: /// Konstruktor. LengthCalculationDummy8(); /** * \name Attribute: */ //@{ /// Der Name der Längenberechnung. virtual QString name() const; /// Eine eindeutige Id der Längenberechnung. virtual const QUuid &uniqueId() const; /// Eine (ausführliche) Beschreibung. virtual QString description() const; /// Version. virtual QString version() const; /// Autor. virtual QString author() const; /// Datum. virtual QString date() const; /// Schriftart-Typ. virtual FontTypeE fontType() const; //@} /** * \name Verzeichnis: */ //@{ /** * Dateien aus dem Datenverzeichnis auslesen. */ virtual const QStringList fetchFontFiles() const; //@} /** * \name Schriftarten: */ //@{ /** * Kann die Schriftart \a strFontName aufgelöst werden?. * Bei dem Parameter \a strFontName handelt es sich um eine * Schriftartbezeichnung und nicht um einen Dateinamen. */ virtual bool canResolveFont( const QString &strFontName ) const; /// Eine Liste mit allen zur Verfügung stehenden Schriftarten. virtual const QStringList availableFonts() const; /// Eine Liste mit allen zur Verfügung stehenden Schriftarten im Verzeichnis \a strPath. virtual const QStringList availableFonts( const QString &strPath ) const; /** * Kann das Zeichen \a chr in der Schriftart \a strFontName aufgelöst werden?. * Wenn der Parameter \a bStore = true ist, kann ein nicht aufgelöstes Zeichen * in einer Fehlerliste gespeichert werden. */ virtual bool canResolveChar( const QChar &c, const QString &strFontName, bool bStore ); //@} /** * \name Breitenberechnung: */ //@{ /** * Breitenberechnung für den Text \a strText durchführen. * Zur Längenberechnung wird die Schriftart verwendet, die * die Attribute \a strFontName, \a iFontSize, \a bBoldFont * und \a bItalicFont besitzt. * * \return Es wird die berechnete Breite in Pixeln zurückgegeben. * Im Fehlerfall wird -1 zurückgegeben. * * Der Parameter \a iResultCode gibt Auskunft darüber, ob * die Berechnung korrekt ausgeführt werden konnte oder * ein spezieller Fehler auftrat. * * \sa CalculationResultE. */ virtual int calculateWidth( const QString &strText, const QString &strFontName, int iFontSize, bool bBoldFont, bool bItalicFont, const CalculateFontShowMessagesE eMessages, unsigned int *iResultCode = 0 ); //@} }; /*=================================================================*\ * Inlines * \*-----------------------------------------------------------------*/ inline QString LengthCalculationDummy8::name() const { #if defined(NDEBUG) return tr( "Dummy8" ); #else return tr( "Dummy8-DBG" ); #endif } inline const QUuid &LengthCalculationDummy8::uniqueId() const { static QUuid *uuid = 0; if ( ! uuid ) { uuid = new QUuid( "{d7eeb149-ba5a-46ef-a9cc-4bb09e7d6eef}" ); } return *uuid; } inline QString LengthCalculationDummy8::description() const { return tr( "A dummy length-calculation is executed, which assumes 8 pixels for every character." ); } inline QString LengthCalculationDummy8::version() const { return tr( "3.0" ); } inline QString LengthCalculationDummy8::author() const { return tr( "Kai Schrader" ); } inline QString LengthCalculationDummy8::date() const { return tr( "August 04, 2009" ); } inline LengthCalculationInterface::FontTypeE LengthCalculationDummy8::fontType() const { return FontTypeVector; } inline bool LengthCalculationDummy8::canResolveFont( const QString &/* strFontName */ ) const { return true; } inline bool LengthCalculationDummy8::canResolveChar( const QChar &/*c*/, const QString &/*strFontName*/, bool /*bStore*/ ) { return true; } #endif // LENGTHCALCULATIONDUMMY8_H
true
fc7adf3c1ba90aa44f8934d970fcc5c255eaf176
C++
yukarinoki/programing_contests
/joi2008-spring/closest_pair.cpp
UTF-8
1,436
2.90625
3
[]
no_license
/****************************** verified by http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A ******************************/ #include <iostream> #include <algorithm> #include <vector> #include <cmath> using namespace std; #define INF 1000000000.0; typedef pair<double, double> P; bool compare_y(P a, P b){ return a.second < b.second; } double closest_pair(vector<P> &a, int pos, int n){ if(n==1) return INF; int m = n/2; double x = a[m+pos].first; double d = min(closest_pair(a,pos,m), closest_pair(a,pos+m,n-m)); inplace_merge(a.begin()+pos,a.begin()+pos+m,a.begin()+pos+n, compare_y); vector<P> b; for(int i=0;i<n;i++){ if(fabs(a[i+pos].first - x) >= d) continue; for(int j=0;j < b.size(); j++){ double dx = a[i+pos].first - b[b.size()-1-j].first; double dy = a[i+pos].second - b[b.size()-j-1].second; if(dy >= d) break; d = min(d, sqrt(dx *dx + dy * dy)); } b.push_back(a[i+pos]); } /* for(int i=0;i<n;i++){ cout << "(" << a[i+pos].first <<","<< a[i+pos].second<<")"; } cout << endl; cout << d << endl; */ return d; } int main(){ int n; cin >> n; vector<P> points(n); for(int i=0;i<n;i++){ cin >> points[i].first >> points[i].second; } sort(points.begin(), points.end()); printf("%.16lf\n", closest_pair(points, 0, n)); }
true
63cf889b89c99863f0ea0d491ae3d8f22d52f02f
C++
Chineseguuys/huawei2020Codecraft
/chusai/test_change_line.cpp
UTF-8
745
2.59375
3
[]
no_license
#include <iostream> #include <algorithm> #include <map> #include <unordered_map> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <unistd.h> // 使用 mmap 需要的头文件 #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main(int argc, char** argv) { const char file_name[] = "result.txt"; struct stat st; int fd = open(file_name, O_RDONLY); fstat(fd, &st); int fd_len = st.st_size; char* file_content_buf = (char*)mmap(NULL, fd_len, PROT_READ, MAP_PRIVATE, fd, 0); for (int index = 0; index < 100; ++index) { if (file_content_buf[index] == '\r') std::cout << index << " "; } std::cout << "\r\n"; munmap(file_content_buf, fd_len); close(fd); return 0; }
true
dd69062b233f2a11b8894a423c057f4aed1739f2
C++
Niraka/ThirdYearProject
/Include/ClientNetworking/NetworkTCPHandler.h
UTF-8
3,360
3.203125
3
[]
no_license
/** The NetworkTCPHandler is a component of the NetworkManager that handles TCP communication. @author Nathan */ #ifndef NETWORK_TCP_HANDLER_H #define NETWORK_TCP_HANDLER_H #include <set> #include <mutex> #include <thread> #include <memory> #include <queue> #include <SFML/Network.hpp> #include "NetworkMessage.h" #include "NetworkConnectionListener.h" class NetworkTCPHandler { private: std::set<NetworkConnectionListener*> m_connectionListeners; std::shared_ptr<NetworkTCPHandler> m_self; std::queue<NetworkMessage> m_inboundMessages; std::queue<sf::Packet> m_outboundMessages; std::mutex m_mutex; sf::TcpSocket m_tcpSocket; sf::Int32 m_iNetworkId; bool m_bRunning; bool m_bConnected; sf::Time m_timeout; unsigned short m_uiPort; sf::IpAddress m_ipAddress; /** Executes the TCP handler. */ void execute(); /** Attempts to connect to the server. If the connection was already established, this function returns true. @return True if the connection was established, false otherwise */ bool attemptServerConnection(); protected: public: /** Constructs a NetworkTCPHandler with the given connection parameters. @param address The remote TCP address @param uiPort The remote TCP port @param timeout The connection attempt timeout */ NetworkTCPHandler(sf::IpAddress& address, unsigned short uiPort, sf::Time& timeout); ~NetworkTCPHandler(); /** Starts the NetworkTCPHandler. A shared pointer to the NetworkTCPHandler is stored to ensure the object is able to safely deconstruct in its own time. This function is thread-safe. @param A shared pointer to THIS NetworkTCPHandler */ void start(std::shared_ptr<NetworkTCPHandler> self); /** Stops the NetworkTCPHandler. Pending messages are flushed. Note that the handler may reside in memory for a short while after this function is called. This function is thread-safe. */ void stop(); /** Adds a NetworkConnectionListener. Duplicates and nullptrs rejected. This function is thread-safe. @param l The listener to add */ void addConnectionListener(NetworkConnectionListener* l); /** Removes a NetworkConnectionListener. This function is thread-safe. @param l The listener to remove */ void removeConnectionListener(NetworkConnectionListener* l); /** Flushes all pending inbound and outbound messsages. This function is thread-safe. */ void flushMessages(); /** Gets the next NetworkMessage on the inbound messages queue. If there were no inbound messages, this function does nothing. The message is popped off of the internal messages queue. This function is thread-safe. @param msg The NetworkMessage to populate @return True if the message is valid */ bool getInboundMessage(NetworkMessage& msg); /** Appends a message to the outbound queue. If the client is not connected to the server, it will attempt to connect for as long as there are pending outbound messages. This function is thread-safe. @param packet The packet to send */ void putOutboundMessage(sf::Packet& packet); /** Gets the network id. This function is thread-safe. @return The network id */ sf::Int32 getNetworkId(); /** Returns true if the TCP connection is live. This function is thread-safe. @return True if the TCP connection is live, false if it is not */ bool isConnected(); }; #endif
true
bd0c1edd520c34226ff988317b6ffb49d75c2785
C++
ChiaYi-LIN/Computer-Programming
/PSA06/b04704016_p1.cpp
UTF-8
972
4.03125
4
[]
no_license
#include <iostream> #include <cstdio> using namespace std; int main() { // aPtr will reference the first element of array a int *aPtr, N; int last; // N is the size of array a cout << "Please enter array size : "; cin >> N; // initial an array with size N int a[N] = {0}; // put value in array a for (int i=0; i<N; i++){ a[i] = i; } // use pointer aPtr to get the first element of array a aPtr = &a[0]; cout << "The address of aPtr is: " << &aPtr << endl; // because sizeof(int) = 4; // we want to print the second element of array // the address of second element is aPtr + 4 // use * to dereference the value cout << "The second element is: " << *(aPtr+1) <<endl; // assign the last element to int number last = a[N-1]; cout << "The last is: " << last << endl; // print the "value" of entire array cout<<"The values of array: "; for (int i=0; i<N; i++) { cout << (*aPtr+i) << " "; } return 0; }
true
b9b4787789c7fee51af393746339f819d1641adb
C++
CasperBHansen/CPP
/8/find.h
UTF-8
1,020
3.625
4
[]
no_license
/* * find.h * * Defines the generic function find(b, e, t) * * Description: * Returns an iterator denoting the first occurrence of the value t, * or for which the predicate p is true (if p is supplied), in the * sequence denoted by the input iterators b and e. Returns e if no * such element exists. */ #ifndef FIND_H #define FIND_H #include "utilities.h" #include <assert.h> #include <stdexcept> #include <iostream> using std::cout; using std::endl; template<class S, class T> S _find(S b, S e, T t) { while(b != e && (* b) != t) { b++; } return b; } template <class S, class T> void test_find(const T& source, S t, bool expected) { S result = (* _find(source.begin(), source.end(), t)); assert( (result == t) == expected ); } void find_tests() { cout << "Testing find(b, e, t):\t"; test_find( make_range(0, 10), 0, true); test_find( make_range(0, 10), 15, false); test_find( make_range(0, 10), 9, true); test_find( make_range(0, 10), -1, false); cout << "Passed!" << endl; } #endif // FIND_H
true
88830cc223fcd081c189f57e0d1c0c135a1d6dbe
C++
aphelps/Network-Boxes
/Networked_Boxes.ino
UTF-8
491
2.625
3
[]
no_license
/* * Box networking */ #include "messaging.h" /* "Unique" ID for the node */ node_id_t local_ID = 0x4321; void setup() { } void loop() { unsigned char buffer[MSG_MAX_LENGTH]; msg_header_t *hdr = (msg_header_t *)buffer; unsigned short read; /* Receive a message directed to this node */ read = messaging_return_packet(buffer, sizeof (buffer), local_ID); /* TODO: Do something */ /* Send a response to the message */ messaging_ack_packet(hdr, local_ID, NULL, 0); }
true
3e14a07849d1836363aabaa9002a4688e83e3c65
C++
raulmorenoamoretti/Sudoku
/sudo_f/main.cpp
UTF-8
623
3.1875
3
[]
no_license
#include <iostream> #include "sudoku_3.h" #include "sudoku_2.h" using namespace std; int num; int main() { sudoku_2 sudo2; sudoku_3 sudo3; cout<<"Elige un numero:\n 1. Dibuja Soduko 3x3," "\n 2.Dibuja Soduko 2X2" "\n 3. Jugar sudoku 3X3" "\n 4. Jugar sudoku 2x2" << endl; cin>>num; if (num==1) { sudo3.generar_sudoku(); sudo3.ImprimirSudoku(); } if (num==2) { sudo2.generar_sudoku(); sudo2.ImprimirSudoku();} if (num==3) { sudo3.Iniciar(); } if (num==4) { sudo2.Iniciar(); } return 0;}
true
0d4e008f63f2772c509107ea78c6a12dcdcacb48
C++
NickPollard/Stellariad
/src/system/hash.cpp
UTF-8
2,216
3.078125
3
[]
no_license
// hash.c #include "common.h" #include "hash.h" //----------------------- #include "mem/allocator.h" unsigned int mhash( const char* src ) { unsigned int seed = 0x0; int len = strlen( src ); return MurmurHash2( src, len, seed ); } /* void* hashtable_findOrAdd( hashtable, key ) { } void* hashtable_find( hashtable, key ) { // NYI assert( 0 ); // find the key in the hashtable // If it's not there, return null return NULL; } */ map* map_create( int max, int stride ) { map* m = (map*)mem_alloc( sizeof( map )); m->max = max; m->count = 0; m->stride = stride; m->keys = (int*)mem_alloc( sizeof( int ) * max ); m->values =(uint8_t*) mem_alloc( stride * max ); memset( m->keys, 0, sizeof( int ) * max ); memset( m->values, 0, stride * max ); return m; } void* map_find( map* m, int key ) { for ( int i = 0; i < m->count; i++ ) { if ( m->keys[i] == key ) return m->values + (i * m->stride); } return NULL; } void map_add( map* m, int key, void* value ) { assert( map_find( m, key) == NULL ); assert( m->count < m->max ); int i = m->count; m->keys[i] = key; if ( value ) // Allow NULL in which case don't copy memcpy( m->values + (i * m->stride), value, m->stride ); m->count++; } void* map_findOrAdd( map* m, int key ) { void* data = map_find( m, key ); if ( !data ) { data = m->values + (m->count * m->stride); map_add( m, key, NULL ); } return data; } void map_addOverride( map* m, int key, void* value ) { void* data = map_findOrAdd( m, key ); memcpy( data, value, m->stride ); } void map_delete( map* m ) { mem_free( m->keys ); mem_free( m->values ); mem_free( m ); } void test_map() { map* test_map = map_create( 16, sizeof( unsigned int )); int key = mhash( "modelview" ); unsigned int value = 0x3; map_add( test_map, key, &value ); unsigned int* modelview = (unsigned int*)map_find( test_map, key ); assert( *modelview = value ); } // *** Test void test_murmurHash( const char* source ) { printf( "Hash of: \"%s\" is 0x%x.\n", source, mhash( source )); } void test_hash() { test_map(); /* test_murmurHash( "test" ); test_murmurHash( "blarg" ); test_murmurHash( "scrund" ); test_murmurHash( "people" ); test_murmurHash( "simples" ); */ }
true
c459c91beac311b309d4750a10721537d930211a
C++
Guillem96/Allegro-PokemonGame
/Game/Game/objectslist.cpp
UTF-8
1,515
3.21875
3
[]
no_license
#include "objectslist.h" Olist Olist_create(){ Olist ol; ol.f = (NodeO*)malloc(sizeof(NodeO)); if (ol.f == NULL){ printf("\nList is not created"); } else{ (*(ol.f)).seg = NULL; ol.prv = ol.f; } return ol; } Olist Olist_insert(Olist ol, Object o){ NodeO *aux; aux = (NodeO*)malloc(sizeof(NodeO)); if (aux == NULL){ printf("\nInsert error"); } else{ (*aux).o = o; (*aux).seg = (*(ol.prv)).seg; (*(ol.prv)).seg = aux; ol.prv = aux; } return ol; } Object Olist_consult(Olist ol){ Object o; if ((*(ol.f)).seg == NULL){ printf("\nObject list is empty"); } else{ o = (*((*(ol.prv)).seg)).o; } return o; } Olist Olist_delete(Olist ol){ NodeO *aux; if ((*(ol.f)).seg == NULL){ printf("\nObject list is empty"); } else{ aux = (*(ol.prv)).seg; (*(ol.prv)).seg = (*aux).seg; free(aux); } return ol; } Olist Olist_forward(Olist ol){ if ((*(ol.prv)).seg == NULL){ printf("\nList is already at the end"); } else{ ol.prv = (*(ol.prv)).seg; } return ol; } int Olist_empty(Olist ol){ return (*(ol.f)).seg == NULL; } int Olist_final(Olist ol){ return (*(ol.prv)).seg == NULL; } Olist Olist_start(Olist ol){ ol.prv = ol.f; return ol; } Olist Olist_destroy(Olist ol){ NodeO *aux; aux = (*(ol.f)).seg; free(ol.f); while (aux != NULL){ ol.f = aux; aux = (*(ol.f)).seg; free(ol.f); } return ol; } int Olist_howmany(Olist ol){ int compt = 0; ol = Olist_start(ol); while (!Olist_final(ol)){ compt++; ol = Olist_forward(ol); } return compt; }
true
7b718788212098b00d53e9f201791d6a1a8041c0
C++
SummerZJU/Data-Structure-Visualization
/project/Common/Parameter/IntParameter.cpp
UTF-8
279
2.71875
3
[ "MIT" ]
permissive
#include "IntParameter.h" IntParameter::IntParameter(int para): para(para) { } IntParameter::~IntParameter() { } int IntParameter::get() const { return para; } void IntParameter::set(int para) { this->para = para; } IntParameter::operator int() const { return get(); }
true
bac12d08907163185225061a8e22a5b255a745e8
C++
DanNixon/CSC3224_CSC3222_Gaming
/Engine_UIMenu/MenuItem.cpp
UTF-8
1,594
2.734375
3
[]
no_license
/** * @file * @author Dan Nixon (120263697) * * For CSC3224 Project 1. */ #include "MenuItem.h" #include <Engine_Graphics/Alignment.h> #include <Engine_Graphics/RectangleMesh.h> #include "IMenu.h" using namespace Engine::Graphics; namespace Engine { namespace UIMenu { /** * @brief Creates a new menu item. * @param menu Menu this item is a part of * @param parent Parent menu item * @param name Name of this item */ MenuItem::MenuItem(IMenu *menu, SceneObject *parent, const std::string &name) : TextPane(name, menu->textHeight(), menu->shader(), menu->font(), TextMode::SHADED) , m_menu(menu) { parent->addChild(this); // Set alignment of text textured rectangle Alignment_bitset align; align.set(Alignment::X_LEFT); align.set(Alignment::Y_BOTTOM); static_cast<RectangleMesh *>(m_mesh)->setAlignment(align); // Default values setText(name); setTextColour(Colour(0.0f, 0.0f, 0.0f, 1.0f)); setState(MenuItemState::NORMAL); } MenuItem::~MenuItem() { } /** * @brief Sets the selection state of this item. * @param state Selection state * @see MenuItem::state */ void MenuItem::setState(MenuItemState state) { m_state = state; Colour bgColour = m_menu->itemColour(m_state); setBackgroundColour(bgColour); } /** * @copydoc TextPane::setText * @param layout If the layout should be updated after the text is changed */ void MenuItem::setText(const std::string &str, bool layout) { TextPane::setText(str); if (layout) m_menu->layout(); } } }
true
939cfc3c6dd7701985af83498144fb7f046962c2
C++
stharakan/par_nystrom
/gaussKernel.hpp
UTF-8
1,575
3.203125
3
[]
no_license
#include "El.hpp" #include "math.h" //#include "omp.h" //#include "kernel_inputs.hpp" #include <iostream> #include <functional> using namespace El; class GaussKernel { public: // Kernel Params double sigma; double gamma; // Grid const Grid* grid; GaussKernel(){}; /* * Constructor: * kernel_inputs: contains sigma/gamma */ GaussKernel(double _h, const Grid* _grid) : grid(_grid) { sigma = _h; gamma = 1.0 / (2 * sigma * sigma); }; ~GaussKernel(){}; /* * Sets sigma and gamma */ void setParams(double sig,const Grid* _grid); /* * Computes a Gaussian kernel matrix of a particular set of * data with itself. The memory should be allocated already * for K or an error will be thrown. NOTE: Because of the way * Elemental works, only the UPPER part of K is accurate */ void SelfKernel(DistMatrix<double>& data, DistMatrix<double>& K); /* * Computes pairwise distances of a data matrix with itself. * User allocates memory for dists */ void SelfDists(DistMatrix<double>& data, DistMatrix<double>& dists); /* * Computes a Gaussian kernel matrix of a set of data with * given target points. Again, the space for the kernel matrix * should already be allocated. */ void Kernel(DistMatrix<double>& data1, DistMatrix<double>& data2, DistMatrix<double>& K); /* * Computes pairwise distances between two sets of data. user * allocates memory for dists */ void Dists(DistMatrix<double>& data1, DistMatrix<double>& data2, DistMatrix<double> &dists); };
true
3fd1e84f7dfd7cf36bf66bb86a1b584509e02b5a
C++
kmunson/CommentReflowerVSIX
/CommentReflowerTest/Compare/RegressionBullets.compare.cpp
UTF-8
1,781
3.3125
3
[]
no_license
// 1) test - just a single line bullet // 2) test - This line is far too long and so should wrap to the right hand side // of the word test // 3) test - this bullet is wrapped too short and so should be merged // Text at a normal indentation after a bullet. This should wrap normally. // 1) A different type of bullet with the same type of start as the previous // one. Very long so that it has to wrap. // 2) Just a short one that should be pulled up // - a hypenated bullet pint. Again very long so that is has to wrap. Yes this // is vey long. // - bullet point by itself. // - bullet point to be wrapped // @tag - Again very long so that is has to wrap. Yes this is very long. Yes // this is very long. In fact so long that it has to wrap down two lines. // In fact so long that it has to wrap down two lines. // @tag Just checking that the other type of tag works correctly. // 0 - now the single character followed by hyphen test indented at the // same level as last /** * - Bullet on a single line that should not be pulled up */ /** * Now we are checking that different indenations work. * This should not be joined with the previous line and should wrap with the * correct indentation. This should wrap happily with the previous line. * A different indentation again. * And back a the first indentation. */ /// Doxygen style. with spaces. /// 1) test - hello there /// Doxygen style with tabs. /// 1) test - hello there /*! * Doxygen comment allows blank comments to be skipped on first line and for the * block still to be recognised and processed. */ /*! Also allows for stuff on first line, which should be wrapped correctly, as * long as the indents match. */ /* * Same with C-style comment */
true
059c650f76027106e80049e634dba52c451675ce
C++
eklavaya2208/practice-ml-cp
/Algorithmic Toolbox/week3_greedy_algorithms/car_fueling.cpp
UTF-8
582
2.78125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; inline int MinRefills(vector<int> x, int n, int L){ int lr=0,cr=0,ans=0; while(cr<=n){ lr = cr; while(cr<=n && x[cr+1]-x[lr]<=L){ cr++; } if(cr==lr){ return -1; } if(cr<=n){ ans++; } } return ans; } int main(){ int d,L,n,ans; cin>>d>>L>>n; vector<int> x(n+2); x[0] = 0; x[n+1] = d; for(int i=1;i<=n;i++){ cin>>x[i]; } ans = MinRefills(x,n,L); cout<<ans; }
true
8811b6d5b74c1850664ed9e8151f98466eff1de3
C++
ayamahmod/competitive-programming
/CodeForces/231A-Team.cpp
UTF-8
265
2.734375
3
[]
no_license
//http://codeforces.com/problemset/problem/231/A #include<iostream> using namespace std; int main() { int n,x,y,z,num=0; cin>>n; for(int i=0;i<n;i++) { cin>>x>>y>>z; if((x+y==2)||(y+z==2)||(x+z==2)) num++; } cout<<num<<endl; return 0; }
true
fc86dbb86a31217aebda831e3f0dd0553d717a89
C++
gundamace17/LeetCode
/C++/0001. Two Sum.cpp
UTF-8
938
3.453125
3
[]
no_license
#include <iostream> #include <cmath> #include <unordered_map> #include <vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> prevMap; for (int i = 0; i < nums.size(); i++) { int diff = target - nums[i]; // Use the diff to search the other number in the array // and it must be target - nums[i] if(prevMap.count(diff)){ // If diff exists, return the index of diff stored in prevMap and i cout << prevMap[diff] << " " << i << endl; return { prevMap[diff], i }; } prevMap[nums[i]] = i; // Store the index of each element in nums } return {}; } }; int main() { Solution sol; vector<int> nums = {2, 3, 1, 4}; sol.twoSum(nums, 3); return 0; }
true
6e4538fd768c4927bfbcecb8f541e1bfe4aec208
C++
ShingenTakeda/Ikemen-PP
/src/Common.hpp
UTF-8
825
2.796875
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <iostream> #include <cstdint> #include <math.h> class Common { public: //Message whoever made this and ask them what this does /* IMax = int32(^uint32(0) >> 1) IErr = ^IMax */ int32_t Random(); int Srand(int32_t s); int32_t Rand(int32_t min, int32_t max); int32_t RandI(int32_t min, int32_t max); //Make this two funnctions type float 32 bits _Float32 RandF(); _Float32 RandF32(); ///SearchFile returns the directory that file is located ///This search on deffile directory, then it keep looking on other dirs std::string SearchFile(std::string file, std::string deffile); private: int Max(int32_t max); int Min(int32_t min); };
true
9a6046bc0a6129e5bee2ae4e65a5743db4929aca
C++
anixpower/Arduino
/anix_robot/anix_robot.ino
UTF-8
1,117
2.6875
3
[]
no_license
String message; // variabila bluetooth // 1 si r stanga si dreapta x spate si o fata void setup(){ pinMode(13,OUTPUT); pinMode(12,OUTPUT); pinMode(11,OUTPUT); pinMode(10,OUTPUT); Serial.begin(9600); } void loop(){ while(Serial.available()) { message+=char(Serial.read());//salveaza in variabila } if(!Serial.available()) { if(message!="") {//if data is available Serial.println(message); //show the data if(message=="o"){ digitalWrite(10,HIGH); digitalWrite(13,HIGH); }else if(message=="x"){ digitalWrite(11,HIGH); digitalWrite(12,HIGH); } else if(message=="r"){ digitalWrite(10,HIGH); } else if(message=="l"){ digitalWrite(13,HIGH); } else if(message=="0") { digitalWrite(10,LOW); digitalWrite(11,LOW); //protectie digitalWrite(12,LOW); digitalWrite(13,LOW); } message=""; //clear the data } } delay(50); //delay }
true
ca1e306c0a3c9028270b8ab08df22cf95f4a33e5
C++
windystrife/UnrealEngine_NVIDIAGameWorks
/Engine/Source/ThirdParty/llvm/3.6.2/include/clang/Analysis/Analyses/ThreadSafetyLogical.h
UTF-8
2,717
2.625
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
//===- ThreadSafetyLogical.h -----------------------------------*- C++ --*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // This file defines a representation for logical expressions with SExpr leaves // that are used as part of fact-checking capability expressions. //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYLOGICAL_H #define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYLOGICAL_H #include "clang/Analysis/Analyses/ThreadSafetyTIL.h" namespace clang { namespace threadSafety { namespace lexpr { class LExpr { public: enum Opcode { Terminal, And, Or, Not }; Opcode kind() const { return Kind; } /// \brief Logical implication. Returns true if the LExpr implies RHS, i.e. if /// the LExpr holds, then RHS must hold. For example, (A & B) implies A. inline bool implies(const LExpr *RHS) const; protected: LExpr(Opcode Kind) : Kind(Kind) {} private: Opcode Kind; }; class Terminal : public LExpr { til::SExpr *Expr; public: Terminal(til::SExpr *Expr) : LExpr(LExpr::Terminal), Expr(Expr) {} const til::SExpr *expr() const { return Expr; } til::SExpr *expr() { return Expr; } static bool classof(const LExpr *E) { return E->kind() == LExpr::Terminal; } }; class BinOp : public LExpr { LExpr *LHS, *RHS; protected: BinOp(LExpr *LHS, LExpr *RHS, Opcode Code) : LExpr(Code), LHS(LHS), RHS(RHS) {} public: const LExpr *left() const { return LHS; } LExpr *left() { return LHS; } const LExpr *right() const { return RHS; } LExpr *right() { return RHS; } }; class And : public BinOp { public: And(LExpr *LHS, LExpr *RHS) : BinOp(LHS, RHS, LExpr::And) {} static bool classof(const LExpr *E) { return E->kind() == LExpr::And; } }; class Or : public BinOp { public: Or(LExpr *LHS, LExpr *RHS) : BinOp(LHS, RHS, LExpr::Or) {} static bool classof(const LExpr *E) { return E->kind() == LExpr::Or; } }; class Not : public LExpr { LExpr *Exp; public: Not(LExpr *Exp) : LExpr(LExpr::Not), Exp(Exp) {} const LExpr *exp() const { return Exp; } LExpr *exp() { return Exp; } static bool classof(const LExpr *E) { return E->kind() == LExpr::Not; } }; /// \brief Logical implication. Returns true if LHS implies RHS, i.e. if LHS /// holds, then RHS must hold. For example, (A & B) implies A. bool implies(const LExpr *LHS, const LExpr *RHS); bool LExpr::implies(const LExpr *RHS) const { return lexpr::implies(this, RHS); } } } } #endif
true
1dc0d7d49f4bd365c502451784b694f74cb0a1aa
C++
MH15/swerve-arduino-core
/swerve.ino
UTF-8
8,946
2.59375
3
[]
no_license
#include "BigMotor.h" #include "Step.h" // defines pins numbers const int stepPin = 4; const int dirPin = 3; const int victor_pin = 5; // declare the motors Step stepper(8); BigMotor motor(9); // Bluetooth #define HC06 Serial3 // void setup() // { // pinMode(LED_BUILTIN, OUTPUT); // Serial.begin(9600); // while (!Serial) // ; // delay(2000); // Serial.println("SETUP"); // motor.pin(victor_pin); // stepper.pin(stepPin, dirPin); // stepper.rotate(360, HIGH); // // open bluetooth channels // HC06.begin(9600); // } // void loop() // { // // read bluetooth // if (HC06.available()) // { // Serial.write(HC06.read()); // } // // int pos = input.toInt(); // // Bring the motor up to speed // // motor.LinearAccel(pos, 300); // // Rotate the stepper 90 degrees // stepper.rotate(180, HIGH); // delay(1000); // } #define VERSION "\n\nAndroTest V2.0 - @kas2014\ndemo for V5.x App" // V2.0 changed to pure ASCII Communication Protocol ** not backward compatible ** // V1.4 improved communication errors handling // V1.3 renamed for publishing, posted on 09/05/2014 // V1.2 Text display ** not backward compatible ** // V1.1 Integer display // V1.0 6 buttons + 4 data char implemented // Demo setup: // Button #1 controls pin #13 LED // Button #4 toggle datafield display rate // Button #5 configured as "push" button (momentary) // Other buttons display demo message // Arduino pin#2 to TX BlueTooth module // Arduino pin#3 to RX BlueTooth module // make sure your BT board is set @57600 bps // better remove SoftSerial for PWM based projects // For Mega 2560: // remove #include "SoftwareSerial.h", SoftwareSerial mySerial(2,3); // search/replace mySerial >> Serial1 // pin#18 to RX bluetooth module, pin#19 to TX bluetooth module #define STX 0x02 #define ETX 0x03 #define ledPin LED_BUILTIN #define SLOW 750 // Datafields refresh rate (ms) #define FAST 250 // Datafields refresh rate (ms) byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0}; // bytes received byte buttonStatus = 0; // first Byte sent to Android device long previousMillis = 0; // will store last time Buttons status was updated long sendInterval = SLOW; // interval between Buttons status transmission (milliseconds) String displayStatus = "xxxx"; // message to Android device void setup() { HC06.begin(9600); Serial.begin(9600); pinMode(ledPin, OUTPUT); Serial.println(VERSION); while (HC06.available()) HC06.read(); // empty RX buffer motor.pin(victor_pin); stepper.pin(stepPin, dirPin); stepper.rotate(360, HIGH); } void loop() { if (HC06.available()) { // data received from smartphone delay(2); cmd[0] = HC06.read(); if (cmd[0] == STX) { int i = 1; while (HC06.available()) { delay(1); cmd[i] = HC06.read(); if (cmd[i] > 127 || i > 7) break; // Communication error if ((cmd[i] == ETX) && (i == 2 || i == 7)) break; // Button or Joystick data i++; } if (i == 2) getButtonState(cmd[1]); // 3 Bytes ex: < STX "C" ETX > else if (i == 7) getJoystickState(cmd); // 6 Bytes ex: < STX "200" "180" ETX > } } stepper.run(); motor.run(); sendBlueToothData(); } void sendBlueToothData() { static long previousMillis = 0; long currentMillis = millis(); if (currentMillis - previousMillis > sendInterval) { // send data back to smartphone previousMillis = currentMillis; // Data frame transmitted back from Arduino to Android device: // < 0X02 Buttons state 0X01 DataField#1 0x04 DataField#2 0x05 DataField#3 0x03 > // < 0X02 "01011" 0X01 "120.00" 0x04 "-4500" 0x05 "Motor enabled" 0x03 > // example HC06.print((char)STX); // Start of Transmission HC06.print(getButtonStatusString()); HC06.print((char)0x1); // buttons status feedback HC06.print(GetdataInt1()); HC06.print((char)0x4); // datafield #1 HC06.print(GetdataFloat2()); HC06.print((char)0x5); // datafield #2 HC06.print(displayStatus); // datafield #3 HC06.print((char)ETX); // End of Transmission } } String getButtonStatusString() { String bStatus = ""; for (int i = 0; i < 6; i++) { if (buttonStatus & (B100000 >> i)) bStatus += "1"; else bStatus += "0"; } return bStatus; } int GetdataInt1() { // Data dummy values sent to Android device for demo purpose static int i = -30; // Replace with your own code i++; if (i > 0) i = -30; return i; } float GetdataFloat2() { // Data dummy values sent to Android device for demo purpose static float i = 50; // Replace with your own code i -= .5; if (i < -50) i = 50; return i; } void getJoystickState(byte data[8]) { int joyX = (data[1] - 48) * 100 + (data[2] - 48) * 10 + (data[3] - 48); // obtain the Int from the ASCII representation int joyY = (data[4] - 48) * 100 + (data[5] - 48) * 10 + (data[6] - 48); joyX = joyX - 200; // Offset to avoid joyY = joyY - 200; // transmitting negative numbers if (joyX < -100 || joyX > 100 || joyY < -100 || joyY > 100) return; // commmunication error // Your code here ... // Serial.print("Joystick position: "); // Serial.print(joyX); // Serial.print(", "); // Serial.println(joyY); int joyRot = (int)((atan2(joyX, joyY) * 4068) / 71); int joyMag = (int)sqrt(joyX * joyX + joyY * joyY); motor.setSpeed(joyMag); stepper.setAngle(joyRot); Serial.println("Joystick angle: " + (String)stepper.angleToApproach + ", magnitude: " + motor.speedToApproach); } void getButtonState(int bStatus) { switch (bStatus) { // ----------------- BUTTON #1 ----------------------- case 'A': buttonStatus |= B000001; // ON Serial.println("\n** Button_1: ON **"); // your code... displayStatus = "LED <ON>"; Serial.println(displayStatus); digitalWrite(ledPin, HIGH); break; case 'B': buttonStatus &= B111110; // OFF Serial.println("\n** Button_1: OFF **"); // your code... displayStatus = "LED <OFF>"; Serial.println(displayStatus); digitalWrite(ledPin, LOW); break; // ----------------- BUTTON #2 ----------------------- case 'C': buttonStatus |= B000010; // ON Serial.println("\n** Button_2: ON **"); // your code... displayStatus = "Button2 <ON>"; Serial.println(displayStatus); break; case 'D': buttonStatus &= B111101; // OFF Serial.println("\n** Button_2: OFF **"); // your code... displayStatus = "Button2 <OFF>"; Serial.println(displayStatus); break; // ----------------- BUTTON #3 ----------------------- case 'E': buttonStatus |= B000100; // ON Serial.println("\n** Button_3: ON **"); // your code... displayStatus = "Motor #1 enabled"; // Demo text message Serial.println(displayStatus); break; case 'F': buttonStatus &= B111011; // OFF Serial.println("\n** Button_3: OFF **"); // your code... displayStatus = "Motor #1 stopped"; Serial.println(displayStatus); break; // ----------------- BUTTON #4 ----------------------- case 'G': buttonStatus |= B001000; // ON Serial.println("\n** Button_4: ON **"); // your code... displayStatus = "Datafield update <FAST>"; Serial.println(displayStatus); sendInterval = FAST; break; case 'H': buttonStatus &= B110111; // OFF Serial.println("\n** Button_4: OFF **"); // your code... displayStatus = "Datafield update <SLOW>"; Serial.println(displayStatus); sendInterval = SLOW; break; // ----------------- BUTTON #5 ----------------------- case 'I': // configured as momentary button // buttonStatus |= B010000; // ON Serial.println("\n** Button_5: ++ pushed ++ **"); // your code... displayStatus = "Button5: <pushed>"; break; // case 'J': // buttonStatus &= B101111; // OFF // // your code... // break; // ----------------- BUTTON #6 ----------------------- case 'K': buttonStatus |= B100000; // ON Serial.println("\n** Button_6: ON **"); // your code... displayStatus = "Button6 <ON>"; // Demo text message break; case 'L': buttonStatus &= B011111; // OFF Serial.println("\n** Button_6: OFF **"); // your code... displayStatus = "Button6 <OFF>"; break; } // --------------------------------------------------------------- }
true
6c487a533b26ec66d2e55aa03a415f39921f429e
C++
sunayski/notSofiaLib
/src/Misc/IdHolder.h
UTF-8
232
2.65625
3
[]
no_license
#ifndef ID_HOLDER_H #define ID_HOLDER_H #include "Holder.h" class IdHolder : public Holder<int> { public: using Holder<int>::Holder; int id() const { return Holder<int>::value(); } }; #endif // ID_HOLDER_H
true
eb3e3b270e947028979f09b8d10953a745531ec6
C++
DHaylock/CuisineColour
/src/ImageController.h
UTF-8
3,146
2.546875
3
[]
no_license
// // ImageController.h // CusineColor // // Created by David Haylock on 10/02/2015. // // enum AnimationType { ANIMATION_TYPE_BACK, ANIMATION_TYPE_BOUNCE, ANIMATION_TYPE_CIRC, ANIMATION_TYPE_CUBIC, ANIMATION_TYPE_ELASTIC, ANIMATION_TYPE_EXPO, ANIMATION_TYPE_LINEAR, ANIMATION_TYPE_QUAD, ANIMATION_TYPE_QUART, ANIMATION_TYPE_QUINT, ANIMATION_TYPE_SINE }; enum ImageType { CUSINE_IMAGE }; #include <stdio.h> #include "ImageSelector.h" #include "ofMain.h" #include "ofxTween.h" //-------------------------------------------------------------- class ImageController { public: ImageController(){ } ~ImageController(){ } void setup(int x, int y, int w, int h); void update(); void draw(); void setSlot1(ImageType type); void setSlot2(ImageType type); int getControllerType(); void setControllerID(int id); int getControllerID(); void deleteImage1(); void deleteImage2(); void addImage1(ofImage img); void addImage2(ofImage img); // Preview void drawImage1(int x,int y); void drawImage2(int x,int y); void stopAnimating(); bool isClicked(int x,int y); void isSelected(bool _selected); bool isEditable(); bool removeElement(int x, int y); void fade1to2(int type); void fade2to1(int type); void fadeWhiteIn(int type); void fadeWhiteOut(int type); void setAnimationLength(int time); void animate1to2(int type); void animate2to1(int type); bool hasTweenFinished(); bool hasTweenGotHalfway(); bool hasFadeToWhiteFinished(); void setMoveOrFade(bool val); void setWhiteOrImage(bool val); void setImage1ID(string id); void setImage2ID(string id); string getImage1ID(); string getImage2ID(); int getCurrentFrame(); void setFadeToWhite(bool value); void setImageCaption(string caption); ofPoint getOrigin(); void drawOutline(); string getImageCaption(); private: ofImage image1; ofImage image2; ImageType slot1; ImageType slot2; ofFbo scene; int _x; int _y; int _w; int _h; bool _fadeToWhite; string _imageCaption; string _image1ID; string _image2ID; bool selected; int _id; int _time; int _currentFrame; bool _moveOrFade; bool _whiteOrImage; ofxTween tweenImage1; ofxTween tweenImage2; ofxTween fadeToWhiteTween; ofxEasingBack easingback; ofxEasingBounce easingbounce; ofxEasingCirc easingcirc; ofxEasingCubic easingcubic; ofxEasingElastic easingelastic; ofxEasingExpo easingexpo; ofxEasingLinear easinglinear; ofxEasingQuad easingquad; ofxEasingQuart easingquart; ofxEasingQuint easingquint; ofxEasingSine easingsine; };
true
6daef8e57cf389d28304fa96d33f7d601c3a38a3
C++
MiladShafiee/Surena4HumanoidSimulation-Choreonoid
/src/Util/YAMLWriter.h
UTF-8
3,368
2.8125
3
[ "MIT", "IJG", "Zlib" ]
permissive
/** @author Shin'ichiro Nakaoka */ #ifndef CNOID_UTIL_YAML_WRITER_H #define CNOID_UTIL_YAML_WRITER_H #include "ValueTree.h" #include <boost/lexical_cast.hpp> #include <stack> #include <string> #include <fstream> #include "exportdecl.h" namespace cnoid { class CNOID_EXPORT YAMLWriter { public: YAMLWriter(const std::string filename); YAMLWriter(std::ostream& os); ~YAMLWriter(); void putNode(const ValueNode* node); void setIndentWidth(int n); void setKeyOrderPreservationMode(bool on); void startDocument(); void putComment(const std::string& comment, bool doNewLine = true); void putString(const std::string& value); void putSingleQuotedString(const std::string& value); void putDoubleQuotedString(const std::string& value); void putBlockStyleString(const std::string& value, bool isLiteral); inline void putLiteralString(const std::string& value) { putBlockStyleString(value, true); } inline void putFoldedString(const std::string& value) { putBlockStyleString(value, false); } template <class DataType> inline void putScalar(const DataType& value){ putString(boost::lexical_cast<std::string>(value)); } void putScalar(const double& value); void setDoubleFormat(const char* format); void startMapping(); void startFlowStyleMapping(); void putKey(const std::string& key, StringStyle style = PLAIN_STRING); template <class DataType> inline void putKeyValue(const std::string& key, const DataType& value){ putKey(key); putScalar(value); } inline void putKeyValue(const std::string& key, const std::string& value){ putKey(key); putDoubleQuotedString(value); } void endMapping(); void startListing(); void startFlowStyleListing(); void endListing(); bool isOpen(); #ifdef CNOID_BACKWARD_COMPATIBILITY void startSequence() { startListing(); } void startFlowStyleSequence() { startFlowStyleListing(); } void endSequence() { endListing(); } #endif private: std::ofstream ofs; std::ostream& os; int indentWidth; bool isCurrentNewLine; int numDocuments; bool isKeyOrderPreservationMode; bool doInsertLineFeed; const char* doubleFormat; enum { TOP, MAPPING, LISTING }; struct State { int type; bool isFlowStyle; bool isKeyPut; bool hasValuesBeenPut; std::string indentString; }; std::stack<State> states; State* current; bool isTopLevel(); State& pushState(int type, bool isFlowStyle); void popState(); void indent(); void newLine(); bool makeValuePutReady(); bool startValuePut(); void endValuePut(); void putString_(const std::string& value); void putSingleQuotedString_(const std::string& value); void putDoubleQuotedString_(const std::string& value); void putKey_(const std::string& key, StringStyle style); void startMappingSub(bool isFlowStyle); void startListingSub(bool isFlowStyle); void putNodeMain(const ValueNode* node, bool doCheckLF); void putScalarNode(const ScalarNode* scalar); void putMappingNode(const Mapping* mapping); void putListingNode(const Listing* listing); }; #ifdef CNOID_BACKWARD_COMPATIBILITY typedef YAMLWriter YamlWriter; #endif } #endif
true
75175e470c9ba9b562365387cb4df2cb6b08daa7
C++
OS2World/APP-GRAPHICS-Dovetail
/control.cc
UTF-8
685
2.71875
3
[ "LicenseRef-scancode-public-domain" ]
permissive
#include "control.h" // basic functions shared by all controls Control::Control(HWND hParent, ULONG ulId) { fCreated=FALSE; if(ulId > 0) hWnd = WinWindowFromID(hParent,ulId); } BOOL Control::Hide() { return (BOOL) WinShowWindow(hWnd, FALSE); } BOOL Control::Show() { return (BOOL) WinShowWindow(hWnd, TRUE); } Control::~Control() { // destroy window if we created it. All subclasses are expected // to have an option to create the window. if(fCreated) WinDestroyWindow(hWnd); } VOID Control::SetPos(SHORT xp, SHORT yp, SHORT width, SHORT height) { WinSetWindowPos( hWnd, 0, xp, yp, width, height, SWP_MOVE | SWP_SIZE); }
true
f0c17c2fd5bcf456785f2daac2d55c5747f2021b
C++
mirmik/ralgo
/ralgo/third/terathon/TSMatrix2D.h
UTF-8
14,020
2.875
3
[ "MIT" ]
permissive
// // This file is part of the Terathon Math Library, by Eric Lengyel. // Copyright 1999-2022, Terathon Software LLC // // This software is distributed under the MIT License. // Separate proprietary licenses are available from Terathon Software. // #ifndef TSMatrix2D_h #define TSMatrix2D_h //# \component Math Library //# \prefix Math/ #include "TSVector2D.h" #define TERATHON_MATRIX2D 1 namespace Terathon { class Matrix2D; struct ConstMatrix2D; //# \class Matrix2D Encapsulates a 2&#x202F;&times;&#x202F;2 matrix. // //# The $Matrix2D$ class encapsulates a 2&#x202F;&times;&#x202F;2 matrix. // //# \def class Matrix2D : public Mat2D<TypeMatrix2D> // //# \ctor Matrix2D(); //# \ctor Matrix2D(float n00, float n01, float n10, float n11); //# \ctor Matrix2D(const Vector2D& a, const Vector2D& b); // //# \param nij The value of the entry residing in row <i>i</i> and //column <i>j</i>. //# \param a The values of the entries residing in first column. //# \param b The values of the entries residing in second column. // //# \desc //# The $Matrix2D$ class is used to store a 2&#x202F;&times;&#x202F;2 //matrix. The entries of the matrix # are accessed using the $()$ operator //with two indexes specifying the row and column of an entry. //# //# The default constructor leaves the entries of the matrix undefined. If //the four entries are # supplied, then the $n$<i>ij</i> parameter specifies //the entry in the <i>i</i>-th row and # <i>j</i>-th column. If the matrix //is constructed using the two vectors $a$ and $b$, then # these vectors //initialize the two columns of the matrix. // //# \operator float& operator ()(machine i, machine j); //# Returns a reference to the entry in the <i>i</i>-th row and //<i>j</i>-th column. # Both $i$ and $j$ must be 0 or 1. // //# \operator const float& operator ()(machine i, machine j) const; //# Returns a constant reference to the entry in the <i>i</i>-th row //and <i>j</i>-th column. # Both $i$ and $j$ must be 0 or 1. // //# \operator Vector2D& operator [](machine j); //# Returns a reference to the <i>j</i>-th column of a matrix. $j$ //must be 0 or 1. // //# \operator const Vector2D& operator [](machine j) const; //# Returns a constant reference to the <i>j</i>-th column of a //matrix. $j$ must be 0 or 1. // //# \operator Matrix2D& operator *=(const Matrix2D& m); //# Multiplies by the matrix $m$. // //# \operator Matrix2D& operator *=(float s); //# Multiplies by the scalar $s$. // //# \operator Matrix2D& operator /=(float s); //# Multiplies by the inverse of the scalar $s$. // //# \action Matrix2D operator *(const Matrix2D& m1, const Matrix2D& m2); //# Returns the product of the matrices $m1$ and $m2$. // //# \action Matrix2D operator *(const Matrix2D& m, float s); //# Returns the product of the matrix $m$ and the scalar $s$. // //# \action Matrix2D operator /(const Matrix2D& m, float s); //# Returns the product of the matrix $m$ and the inverse of the //scalar $s$. // //# \action Vector2D operator *(const Matrix2D& m, const Vector2D& v); //# Returns the product of the matrix $m$ and the column vector //$v$. // //# \action Point2D operator *(const Matrix2D& m, const Point2D& p); //# Returns the product of the matrix $m$ and the column vector //$p$. // //# \action Vector2D operator *(const Vector2D& v, const Matrix2D& m); //# Returns the product of the row vector $v$ and the matrix //$m$. // //# \action float Determinant(const Matrix2D& m); //# Returns the determinant of the matrix $m$. // //# \action Matrix2D Inverse(const Matrix2D& m); //# Returns the inverse of the matrix $m$. If $m$ is singular, then //the result is undefined. // //# \action Matrix2D Adjugate(const Matrix2D& m); //# Returns the adjugate of the matrix $m$. // //# \privbase Mat2D Matrices use a generic base class to store their //components. // //# \also $@Vector2D@$ //# \function Matrix2D::Set Sets all four entries of a matrix. // //# \proto Matrix2D& Set(float n00, float n01, float n10, float n11); //# \proto Matrix2D& Set(const Vector2D& a, const Vector2D& b); // //# \param nij The new value of the entry residing in row <i>i</i> and //column <i>j</i>. //# \param a The new values of the entries residing in first column. //# \param b The new values of the entries residing in second column. // //# \desc //# The $Set$ function sets all four entries of a matrix, either by //specifying each entry individually # or by specifying each of the two //columns as 2D vectors. //# //# The return value is a reference to the matrix object. // //# \also $@Matrix2D::SetIdentity@$ //# \also $@Matrix2D::MakeRotation@$ //# \function Matrix2D::SetIdentity Sets a matrix to the //2&#x202F;&times;&#x202F;2 identity matrix. // //# \proto Matrix2D& SetIdentity(void); // //# \desc //# The $SetIdentity$ function replaces all entries of a matrix with the //entries of the identity matrix. //# //# The return value is a reference to the matrix object. // //# \also $@Matrix2D::Set@$ //# \also $@Matrix2D::MakeRotation@$ //# \function Matrix2D::Orthogonalize Orthogonalizes the columns of a //matrix. // //# \proto Matrix2D& Orthogonalize(column); // //# \param column The index of the column whose direction does not //change. This must be 0 or 1. // //# \desc //# The $Orthogonalize$ function uses Gram-Schmidt orthogonalization to //orthogonalize the columns # of a matrix. The column whose index is //specified by the $column$ parameter is normalized to unit length. # The //remaining column is orthogonalized and made unit length. Only the column //not specified # by the $column$ parameter can change direction. //# \function Matrix2D::MakeRotation Returns a matrix that represents a //rotation in the 2D plane. // //# \proto static Matrix2D MakeRotation(float angle); // //# \param angle The angle through which to rotate, in radians. // //# \desc //# The $MakeRotation$ function returns a matrix representing a rotation //through the angle given # by the $angle$ parameter in the 2D plane. // //# \also $@Matrix2D::SetIdentity@$ //# \also $@Matrix2D::Set@$ //# \function Matrix2D::MakeScale Returns a matrix that represents a //scale. // //# \proto static Matrix2D MakeScale(float scale); //# \proto static Matrix2D MakeScale(float sx, float sy); // //# \param scale The scale along both axes. //# \param sx The scale along the <i>x</i> axis. //# \param sy The scale along the <i>y</i> axis. // //# \desc //# The $MakeScale$ function returns a matrix representing a scale. //# If only the $scale$ parameter is specified, then the scale is uniform //along both axes. # If the $sx$ and $sy$ parameters are specified, then //they correspond to the scale along # the <i>x</i> and <i>y</i> axis, //respectively. // //# \also $@Matrix2D::SetIdentity@$ //# \also $@Matrix2D::Set@$ struct TypeMatrix2D { typedef float component_type; typedef Matrix2D matrix2D_type; typedef TypeVector2D column_type_struct; typedef TypeVector2D row_type_struct; }; class Matrix2D : public Mat2D<TypeMatrix2D> { public: TERATHON_API static const ConstMatrix2D identity; inline Matrix2D() = default; TERATHON_API Matrix2D(float n00, float n01, float n10, float n11); TERATHON_API Matrix2D(const Vector2D &a, const Vector2D &b); TERATHON_API Matrix2D &Set(float n00, float n01, float n10, float n11); TERATHON_API Matrix2D &Set(const Vector2D &a, const Vector2D &b); Matrix2D &operator=(const Matrix2D &m) { matrix = m.matrix; return (*this); } template <typename type_struct, int count, int index_00, int index_01, int index_10, int index_11> Matrix2D &operator=(const Submat2D<type_struct, count, index_00, index_01, index_10, index_11> &m) { matrix = m; return (*this); } TERATHON_API Matrix2D &operator*=(const Matrix2D &m); TERATHON_API Matrix2D &operator*=(float s); TERATHON_API Matrix2D &operator/=(float s); TERATHON_API Matrix2D &SetIdentity(void); TERATHON_API Matrix2D &Orthogonalize(int32 column); TERATHON_API static Matrix2D MakeRotation(float angle); TERATHON_API static Matrix2D MakeScaleX(float sx); TERATHON_API static Matrix2D MakeScaleY(float sy); TERATHON_API static Matrix2D MakeScale(float scale); TERATHON_API static Matrix2D MakeScale(float sx, float sy); }; template <typename type_struct, int count, int index_x, int index_y> inline typename type_struct::vector2D_type operator*(const Matrix2D &m, const Subvec2D<type_struct, count, index_x, index_y> &v) { return (m.matrix * v); } template <typename type_struct, int count, int index_x, int index_y> inline typename type_struct::vector2D_type operator*(const Subvec2D<type_struct, count, index_x, index_y> &v, const Matrix2D &m) { return (v * m.matrix); } template <typename type_struct, int count, int index_00, int index_01, int index_10, int index_11> inline Vector2D operator*(const Submat2D<type_struct, count, index_00, index_01, index_10, index_11> &m, const Vector2D &v) { return (m * v.xy); } template <typename type_struct, int count, int index_00, int index_01, int index_10, int index_11> inline Vector2D operator*(const Vector2D &v, const Submat2D<type_struct, count, index_00, index_01, index_10, index_11> &m) { return (v.xy * m); } inline Vector2D operator*(const Matrix2D &m, const Vector2D &v) { return (m.matrix * v.xy); } inline Point2D operator*(const Matrix2D &m, const Point2D &p) { return (Point2D::origin + m.matrix * p.xy); } inline Vector2D operator*(const Vector2D &v, const Matrix2D &m) { return (v.xy * m.matrix); } inline Matrix2D operator*(const Matrix2D &m1, const Matrix2D &m2) { return (m1.matrix * m2.matrix); } template <typename type_struct, int count, int index_00, int index_01, int index_10, int index_11> inline Matrix2D operator*(const Matrix2D &m1, const Submat2D<type_struct, count, index_00, index_01, index_10, index_11> &m2) { return (m1.matrix * m2); } template <typename type_struct, int count, int index_00, int index_01, int index_10, int index_11> inline Matrix2D operator*(const Submat2D<type_struct, count, index_00, index_01, index_10, index_11> &m1, const Matrix2D &m2) { return (m1 * m2.matrix); } TERATHON_API Matrix2D operator*(const Matrix2D &m, float s); TERATHON_API Matrix2D operator/(const Matrix2D &m, float s); inline Matrix2D operator*(float s, const Matrix2D &m) { return (m * s); } struct ConstMatrix2D { float n[2][2]; operator const Matrix2D &(void) const { return (reinterpret_cast<const Matrix2D &>(*this)); } const Matrix2D *operator&(void) const { return (reinterpret_cast<const Matrix2D *>(this)); } const Matrix2D *operator->(void) const { return (reinterpret_cast<const Matrix2D *>(this)); } float operator()(int32 i, int32 j) const { return (reinterpret_cast<const Matrix2D &>(*this)(i, j)); } const Vector2D &operator[](machine j) const { return (reinterpret_cast<const Matrix2D &>(*this)[j]); } }; TERATHON_API float Determinant(const Matrix2D &m); TERATHON_API Matrix2D Inverse(const Matrix2D &m); TERATHON_API Matrix2D Adjugate(const Matrix2D &m); } #endif
true
7e701f10d05acac69e64779e3a0fe1239ad00d56
C++
naohisas/KVS
/Source/Core/Network/SocketAddress.cpp
UTF-8
9,084
2.828125
3
[ "BSD-3-Clause", "MIT", "Zlib", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
/****************************************************************************/ /** * @file SocketAddress.cpp * @author Naohisa Sakamoto */ /****************************************************************************/ #include "SocketAddress.h" #include <cstdlib> namespace kvs { /*==========================================================================*/ /** * Constructor. */ /*==========================================================================*/ SocketAddress::SocketAddress(): m_ip( kvs::IPAddress() ), m_port( 0 ) { this->initialize( &m_address ); } /*==========================================================================*/ /** * Constructor. * @param address_name [in] address as string */ /*==========================================================================*/ SocketAddress::SocketAddress( const char* address_name ): m_ip( kvs::IPAddress() ), m_port( 0 ) { this->split_ip_and_port( address_name ); this->initialize( &m_address ); } /*==========================================================================*/ /** * Constructor. * @param ip [in] IP address * @param port [in] port number */ /*==========================================================================*/ SocketAddress::SocketAddress( const kvs::IPAddress& ip, const int port ): m_ip( ip ), m_port( port ) { this->initialize_address( ip, port ); } /*==========================================================================*/ /** * Constructor. * @param other [in] socket address */ /*==========================================================================*/ SocketAddress::SocketAddress( const SocketAddress& other ): m_ip( other.m_ip ), m_port( other.m_port ) { this->copy_address( other.m_address ); } /*==========================================================================*/ /** * Substitution operator '='. * @param other [in] socket address */ /*==========================================================================*/ SocketAddress& SocketAddress::operator = ( const SocketAddress& other ) { m_ip = other.m_ip; m_port = other.m_port; this->copy_address( other.m_address ); return( *this ); } /*==========================================================================*/ /** * Comparison operator '<' * @param other1 [in] socket address 1 * @param other2 [in] socket address 2 */ /*==========================================================================*/ bool operator < ( const SocketAddress& other1, const SocketAddress& other2 ) { if( other1.ip() < other2.ip() ) return( true ); if( other1.ip() > other2.ip() ) return( false ); return( other1.port() < other2.port() ); } /*==========================================================================*/ /** * Comparison operator '>' * @param other1 [in] socket address 1 * @param other2 [in] socket address 2 */ /*==========================================================================*/ bool operator > ( const SocketAddress& other1, const SocketAddress& other2 ) { return( other1 < other2 ); } /*==========================================================================*/ /** * Comparison operator '<=' * @param other1 [in] socket address 1 * @param other2 [in] socket address 2 */ /*==========================================================================*/ bool operator <= ( const SocketAddress& other1, const SocketAddress& other2 ) { return( !( other1 > other2 ) ); } /*==========================================================================*/ /** * Comparison operator '>=' * @param other1 [in] socket address 1 * @param other2 [in] socket address 2 */ /*==========================================================================*/ bool operator >= ( const SocketAddress& other1, const SocketAddress& other2 ) { return( !( other1 < other2 ) ); } /*==========================================================================*/ /** * Equal operator '=='. * @param other1 [in] socket address 1 * @param other2 [in] socket address 2 */ /*==========================================================================*/ bool operator == ( const SocketAddress& other1, const SocketAddress& other2 ) { return( ( other1.ip() == other2.ip() ) && ( other1.port() == other2.port() ) ); } /*==========================================================================*/ /** * Not-equal perator '!=' * @param other1 [in] socket address 1 * @param other2 [in] socket address 2 */ /*==========================================================================*/ bool operator != ( const SocketAddress& other1, const SocketAddress& other2 ) { return( !( other1 == other2 ) ); } /*==========================================================================*/ /** * Operator '<<'. * @param os [in] output stream * @param other [in] socket address */ /*==========================================================================*/ std::ostream& operator << ( std::ostream& os, const SocketAddress& other ) { os << other.ip() << ":" << other.port(); return( os ); } /*==========================================================================*/ /** * Get the IP address. * @retval IP address */ /*==========================================================================*/ const kvs::IPAddress& SocketAddress::ip() const { return( m_ip ); } /*==========================================================================*/ /** * Get the port number. * @return port number */ /*==========================================================================*/ int SocketAddress::port() const { return( m_port ); } /*==========================================================================*/ /** * Get the socket address. * @retval socket address */ /*==========================================================================*/ const SocketAddress::address_type& SocketAddress::address() const { return( m_address ); } /*==========================================================================*/ /** * Set the IP address. * @param ip [in] IP address */ /*==========================================================================*/ void SocketAddress::setIp( const kvs::IPAddress& ip ) { m_ip = ip; } /*==========================================================================*/ /** * Set the port number. * @param port [in] port number */ /*==========================================================================*/ void SocketAddress::setPort( const int port ) { m_port = port; } /*==========================================================================*/ /** * Set the socket address. * @param address [in] socket address */ /*==========================================================================*/ void SocketAddress::setAddress( const address_type& address ) { this->copy_address( address ); m_ip = kvs::IPAddress( address.sin_addr ); m_port = ntohs( address.sin_port ); } /*==========================================================================*/ /** * Initialize. * @param address [in] pointer to the socket address */ /*==========================================================================*/ void SocketAddress::initialize( address_type* address ) { memset( reinterpret_cast<void*>( address ), 0, sizeof( *address ) ); } /*==========================================================================*/ /** * Initialize socket address. * @param ip [in] IP address * @param port [in] port number */ /*==========================================================================*/ void SocketAddress::initialize_address( const kvs::IPAddress& ip, const int port ) { this->initialize( &m_address ); m_address.sin_family = AF_INET; m_address.sin_port = htons( static_cast<unsigned short>( port ) ); m_address.sin_addr = ip.address(); } /*==========================================================================*/ /** * Copy the socket address. * @param address [in] socket address */ /*==========================================================================*/ void SocketAddress::copy_address( const SocketAddress::address_type& address ) { memcpy( reinterpret_cast<void*>( &m_address ), reinterpret_cast<const void*>( &address ), sizeof( m_address ) ); } /*==========================================================================*/ /** * Spilt IP adress and port number from the given string. * @param address_name [in] socket address as string */ /*==========================================================================*/ void SocketAddress::split_ip_and_port( const char* address_name ) { const std::string delim(":"); std::string ip_and_port( address_name ); std::string::size_type p = ip_and_port.find_first_of( delim ); if( p != std::string::npos ) { m_ip = ip_and_port.substr(0,p).c_str(); ip_and_port = ip_and_port.substr(p+1); m_port = atoi( ip_and_port.c_str() ); } } } // end of namespace kvs
true
a5f26cf84233dc05570344a0faf8975adfb35d6a
C++
lukemcraig/PanningTheory
/Source/MatrixRenderer.cpp
UTF-8
3,424
2.515625
3
[]
no_license
/* ============================================================================== MatrixRendererImplementation.h Created: 22 Apr 2018 8:56:43pm Author: Luke ============================================================================== */ #include "../JuceLibraryCode/JuceHeader.h" #include "MatrixRenderer.h" //============================================================================== MatrixRenderer::MatrixRenderer() { // In your constructor, you should add any child components, and // initialise any special settings that your component needs. } MatrixRenderer::~MatrixRenderer() { } void MatrixRenderer::paint (Graphics& g) { //g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); // clear the background g.setColour (Colours::white); auto lb = getLocalBounds(); // transform into uv coords uvTransform_ = AffineTransform(); // [0.0,height]-> [0.0,1.0] uvTransform_ = uvTransform_.scaled(lb.getWidth(), lb.getHeight()); g.addTransform(uvTransform_); auto aspect = ((float)lb.getWidth() / lb.getHeight()); //aspect = 1.0f; //auto xOffset = 0.5f * aspect; auto xOffset = 0.5f; drawBrackets(g, xOffset); g.addTransform(uvTransform_.inverted()); drawMatrixValues(g, xOffset, aspect); } void MatrixRenderer::drawBrackets(juce::Graphics & g, float xOffset) { // center the origin auto centerTransform = AffineTransform().translated(xOffset, 0.5f); g.addTransform(centerTransform); auto leftBracket = getMatrixBracket(); auto rightBracket = getMatrixBracket(true); float thickness = .025f; g.strokePath(leftBracket, PathStrokeType(thickness)); g.strokePath(rightBracket, PathStrokeType(thickness)); g.addTransform(centerTransform.inverted()); } void MatrixRenderer::drawMatrixValues(juce::Graphics & g, float xOffset, float aspect) { auto arect = getLocalBounds().toFloat(); //auto rectpath = Path(); //rectpath.addRectangle(arect.reduced(10)); auto nCol = matrixToRender_->getNumColumns(); auto nRow = matrixToRender_->getNumRows(); auto cellHeight = (float)getLocalBounds().getHeight() / nRow; auto cellWidth = (float)getLocalBounds().getWidth() / nCol; for (int col = 0; col < nCol; col++) { for (int row = 0; row < nRow; row++) { auto cellTrans = AffineTransform().scaled(1.0f / nCol, 1.0f / nRow); auto cellTrans2 = cellTrans.translated(col*cellWidth, row*cellHeight); //g.strokePath(rectpath, PathStrokeType(1), cellTrans2); g.setColour(Colours::white); g.setFont(24); auto arect2 = arect.transformed(cellTrans2); g.drawText(String(matrixToRender_->operator()(row, col), 2), arect2, Justification::centred, true); } } } Path MatrixRenderer::getMatrixBracket(bool rightBracket) { auto linePath = Path(); float depth = .1f; float xleft = -0.5f; float ytop = 0.5f; float ybottom = -0.5f; linePath.startNewSubPath(xleft + depth, ytop); linePath.lineTo(xleft, ytop); linePath.lineTo(xleft, ybottom); linePath.lineTo(xleft + depth, ybottom); if (rightBracket) { auto flipTransform = AffineTransform::scale(-1, 1); linePath.applyTransform(flipTransform); } return linePath; } void MatrixRenderer::resized() { // This method is where you should set the bounds of any child // components that your component contains.. } void MatrixRenderer::setMatrixToRender(dsp::Matrix<float>* matrixToRender) { matrixToRender_ = matrixToRender; }
true
710d0c633de9b3a6551601dc4947de9ab981753a
C++
michaljanus90/FactoryMock
/tests/CopyTest.cpp
UTF-8
1,479
2.765625
3
[]
no_license
#include "Filesystemhelpers.hpp" #include "Usage.hpp" #include "ItemMock.hpp" #include "FactoryMock.hpp" #include <memory> #include "gtest/gtest.h" using namespace src; class FileSystemTC : public testing::Test { public: FileSystemTC() { std::cout<< "Running Ctor\n"; createDirectory(path); } ~FileSystemTC() { std::cout<< "Running Dtor\n"; // removeFile(path + fileN); removeDirectory(path); } void createFile(const std::string& fileName, const std::string& content) { std::ofstream outfile (fileName); outfile << content; outfile.close(); } protected: std::string path = "./tmp/"; std::string fileN = "dupa.txt"; }; TEST_F(FileSystemTC, firstTest) { auto pathFile = path + fileN; { const std::string content = "michal jest super"; createFile(pathFile, content); EXPECT_TRUE(doesFileExists(pathFile)); EXPECT_EQ(content, getFileContent(pathFile)); } { removeFile(pathFile); EXPECT_FALSE(doesFileExists(pathFile)); } } TEST_F(FileSystemTC, secondTest) { auto pathFile = path + fileN; { const std::string content = "dupa_12"; createFile(pathFile, content); EXPECT_TRUE(doesFileExists(pathFile)); EXPECT_EQ(content, getFileContent(pathFile)); } { removeFile(pathFile); EXPECT_FALSE(doesFileExists(pathFile)); } }
true
557ab7d6d6f0322dd5e37cc4cd4321b0280ef405
C++
faultyagatha/res15-opengl
/frustumCullingExample_complete/src/ofApp.cpp
UTF-8
6,275
3.09375
3
[ "MIT" ]
permissive
#include "ofApp.h" // HERE'S THE GENERAL IDEA: // // 0. Place some spheres at random positions into the scene. // 1. Calculate which spheres can be culled from camera 0's view // 2. Flag the culled spheres, so they will be rendered in red instead of white. // 3. Draw the scene. // 4. Then: BONUS: draw the culling camera's frustum (camera 0) into the scene, // But only, if we're not watching the scene through that camera. //-------------------------------------------------------------- void ofApp::setup(){ // initialise variables to default values activeCam = 1; mCountInFrustum = 0; ofSetSphereResolution(4); // populate the scene with 100 randomly distributed spheres for (int i =0; i < 100; i++){ SphereNode s; s.setGlobalPosition(ofVec3f(ofRandom(-100,100),ofRandom(-100,100),ofRandom(-100,100))); s.radius = ofRandom(4,15); spheres.push_back(s); } mCam[0].setupPerspective(false,60, 20, 300); mCam[0].disableMouseInput(); mCam[0].setDistance(300); mCam[0].reset(); mCam[1].setupPerspective(false,30, 0.1, 20000); mCam[1].enableMouseInput(); mCam[1].setDistance(2600); mCam[1].reset(); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(ofFloatColor(0.23)); ofSetColor(ofColor::white); ofNoFill(); ofEnableDepthTest(); mCam[activeCam].begin(); { ofSetColor(ofColor::white); vector<ofVec4f> frustumPlanes = calculateFrustumPlanes(mCam[0].getProjectionMatrix()); // we could erase the 3rd element, that is the far plane, // therefore we are testing against an infinitely far frustum, // that is, an open frustum in view direction. // frustumPlanes.erase(frustumPlanes.begin() + 2); ofMatrix4x4 mvm = mCam[0].getModelViewMatrix(); for (auto & s : spheres){ // --- note that we have to transform the sphere centres to the eye space of our frustum culling camera manually, ofVec3f sInEyeSpace = s.getGlobalPosition() * mvm; s.inFrustum = getInFrustum(frustumPlanes, sInEyeSpace, s.radius); } // ----------- // let's count the number of spheres within the frustum of camera 0: mCountInFrustum = 0; for(auto & s : spheres){ s.draw(); if (s.inFrustum) ++ mCountInFrustum; } if (activeCam == 1) { // let's draw the frustum of camera 0 // but first, draw a stand-in for the actual camera. // this will draw a cube and an axis representation where the other camera sits. mCam[0].draw(); // get the camera's near and far plane distance values. float nearC = mCam[0].getNearClip(); float farC = mCam[0].getFarClip(); // Now comes the tricky bit: we want to draw the frustum where camera 0 sits. // Therefore, we move to camera 0 eye space, And draw the frustum fron there. ofPushMatrix(); // we are currently in world space. ofMultMatrix(mCam[0].getModelViewMatrix().getInverse()); // we are now in camera2 view space! // where the origin is at camera2's global position. // draw the frustum in yellow, wireframe ofSetColor(ofColor::yellow); // we want to draw the frustum of camera 0. to do this, we grab the matrix that transforms // from view space into clip space (i.e. the projection matrix) // then we take our unit clip cube (i.e. the cube that delimits clip space) // (this cube is defined to be +-1 into each x, y , z) // and transform it back into view space. We transform it back into // viewspace by applying the inverse transform viewspace -> clipspace // which is the inverse of applying the projection matrix, which is applying // the inverse projection matrix. // so first, grab camera 0's inverse projection matrix: ofMatrix4x4 projectionMatrixInverse = mCam[0].getProjectionMatrix().getInverse(); // the edges of our unit cube in clip space: ofVec3f clipCube[8] = { ofVec3f(-1,-1,-1), ofVec3f(-1, 1,-1), ofVec3f( 1,-1,-1), ofVec3f( 1, 1,-1), ofVec3f(-1,-1, 1), ofVec3f(-1, 1, 1), ofVec3f( 1,-1, 1), ofVec3f( 1, 1, 1), }; // since the clip cube is expressed in clip (=projection) space, we want this // transformed back into our current space, view space, i.e. apply the inverse // projection matrix to it. for (int i =0; i<8; i++){ clipCube[i] = clipCube[i] * projectionMatrixInverse; } // now draw our clip cube side edge rays - note that since the coordinates are // now in world space, we can draw them without applying any additional trans- // formations. for (int i=0;i<4;i++){ ofLine(clipCube[i],clipCube[i+4]); } //// draw the clip cube cap ofRect(clipCube[0],clipCube[3].x-clipCube[0].x,clipCube[3].y-clipCube[0].y); ofRect(clipCube[4],clipCube[7].x-clipCube[4].x,clipCube[7].y-clipCube[4].y); ofPopMatrix(); // and back to world space! } } mCam[activeCam].end(); ofDrawBitmapStringHighlight( "Active Cam: "+ ofToString(activeCam,4,' ') + "\n" + "Visible spheres: "+ ofToString(mCountInFrustum,4,' ') + "\n" + "Press 'c' to switch cameras.", 200, 20); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ switch (key) { case 'c': mCam[activeCam].disableMouseInput(); activeCam = (activeCam + 1) % 2; mCam[activeCam].enableMouseInput(); break; default: break; } } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
true
11d9fa80fcd202c6a3f31e86372d7558fbc42521
C++
polansks/CS-162-FinalProject
/Player.hpp
UTF-8
1,071
2.8125
3
[]
no_license
/**************************************************************** ** File Name: Player.hpp ** Author: Scott Polansky ** Date: Dec 5, 2017 ** Description: A class for the player in the game ****************************************************************/ #ifndef Player_hpp #define Player_hpp #include <stdio.h> #include <iostream> #include <string> #include "Space.hpp" #include "Item.hpp" #include "Bag.hpp" #include "direction.h" using std::string; class Player { private: string name; Space* currentSpace; int health; const int STARTING_HEALTH = 25; Bag playerBag; public: Player(); Player(string, Space*); Player(const Player &); Player& operator=(const Player&); ~Player(); string getName(); void setName(string); Space* getCurrentSpace(); Space* getSpace(DIRECTION); void setCurrentSpace(Space*); int getHealth(); void move(DIRECTION); bool addToBag(Item *); int oxygenCount(); int hydrogenCount(); bool hasWater(); }; #endif /* Player_hpp */
true
2134b8a90b43f3c0e296c39aa94cc640788eb0bf
C++
ewuharun/Algorithm
/BFS/the_flight_plane.cpp
UTF-8
1,414
2.578125
3
[]
no_license
#include<iostream> #include<stdio.h> #include<vector> #include<queue> using namespace std; int graph[1005][1005]; int visited[1005]; int dis[1005]; int parents[1005]; int count=0; queue<int>arr; void printpath(int x,int y,int node) { if(parents[y]==-1){ return ; } printpath(x,parents[y],node); arr.push(parents[y]); count++; } int main() { int node,edge; cin>>node>>edge; int m,c; cin>>m>>c; int u,v; for(int i=1;i<=edge;i++){ cin>>u>>v; graph[u][v]=c; graph[v][u]=c; } for(int i=1;i<=node;i++){ visited[i]=-1; dis[i]=0; parents[i]=-1; } int start; cin>>start; queue<int>q; q.push(start); visited[start]=1; int hold; while(!q.empty()){ hold=q.front(); q.pop(); //visited[hold]=1; for(int i=1;i<=node;i++){ if(graph[hold][i]==c){ if(visited[i]==-1){ dis[i]=dis[hold]+c; parents[i]=hold; visited[i]=1; q.push(i); } } } } int x,y; cin>>y; printpath(start,y,node); cout<<count+1<<endl; while(!arr.empty()){ int a=arr.front(); cout<<a<<" "; arr.pop(); } cout<<y<<endl; }
true
7015fe306232c49b798deff37fb51b7c9130c748
C++
marcinlos/zephyr
/Zephyr/src/zephyr/glfw/input_adapter.cpp
UTF-8
5,451
2.609375
3
[]
no_license
/** * @file input_adapter.cpp */ #include <zephyr/glfw/input_adapter.hpp> namespace zephyr { namespace glfw { Key keyFromGLFW(int key) { switch (key) { case GLFW_KEY_A: return Key::A; case GLFW_KEY_B: return Key::B; case GLFW_KEY_C: return Key::C; case GLFW_KEY_D: return Key::D; case GLFW_KEY_E: return Key::E; case GLFW_KEY_F: return Key::F; case GLFW_KEY_G: return Key::G; case GLFW_KEY_H: return Key::H; case GLFW_KEY_I: return Key::I; case GLFW_KEY_J: return Key::J; case GLFW_KEY_K: return Key::K; case GLFW_KEY_L: return Key::L; case GLFW_KEY_M: return Key::M; case GLFW_KEY_N: return Key::N; case GLFW_KEY_O: return Key::O; case GLFW_KEY_P: return Key::P; case GLFW_KEY_Q: return Key::Q; case GLFW_KEY_R: return Key::R; case GLFW_KEY_S: return Key::S; case GLFW_KEY_T: return Key::T; case GLFW_KEY_U: return Key::U; case GLFW_KEY_V: return Key::V; case GLFW_KEY_W: return Key::W; case GLFW_KEY_X: return Key::X; case GLFW_KEY_Y: return Key::Y; case GLFW_KEY_Z: return Key::Z; case GLFW_KEY_0: return Key::K0; case GLFW_KEY_1: return Key::K1; case GLFW_KEY_2: return Key::K2; case GLFW_KEY_3: return Key::K3; case GLFW_KEY_4: return Key::K4; case GLFW_KEY_5: return Key::K5; case GLFW_KEY_6: return Key::K6; case GLFW_KEY_7: return Key::K7; case GLFW_KEY_8: return Key::K8; case GLFW_KEY_9: return Key::K9; case GLFW_KEY_F1: return Key::F1; case GLFW_KEY_F2: return Key::F2; case GLFW_KEY_F3: return Key::F3; case GLFW_KEY_F4: return Key::F4; case GLFW_KEY_F5: return Key::F5; case GLFW_KEY_F6: return Key::F6; case GLFW_KEY_F7: return Key::F7; case GLFW_KEY_F8: return Key::F8; case GLFW_KEY_F9: return Key::F9; case GLFW_KEY_F10: return Key::F10; case GLFW_KEY_F11: return Key::F11; case GLFW_KEY_F12: return Key::F12; case GLFW_KEY_LEFT_CONTROL: return Key::LEFT_CTRL; case GLFW_KEY_RIGHT_CONTROL: return Key::RIGHT_CTRL; case GLFW_KEY_LEFT_ALT: return Key::LEFT_ALT; case GLFW_KEY_RIGHT_ALT: return Key::RIGHT_ALT; case GLFW_KEY_LEFT_SHIFT: return Key::LEFT_SHIFT; case GLFW_KEY_RIGHT_SHIFT: return Key::RIGHT_SHIFT; case GLFW_KEY_MENU: return Key::MENU; case GLFW_KEY_SPACE: return Key::SPACE; case GLFW_KEY_TAB: return Key::TAB; case GLFW_KEY_CAPS_LOCK: return Key::CAPS_LOCK; case GLFW_KEY_ESCAPE: return Key::ESCAPE; case GLFW_KEY_ENTER: return Key::RETURN; case GLFW_KEY_BACKSPACE: return Key::BACKSPACE; case GLFW_KEY_COMMA: return Key::COMMA; case GLFW_KEY_PERIOD: return Key::PERIOD; case GLFW_KEY_APOSTROPHE: return Key::APOSTROPHE; case GLFW_KEY_SLASH: return Key::SLASH; case GLFW_KEY_BACKSLASH: return Key::BACKSLASH; case GLFW_KEY_GRAVE_ACCENT: return Key::GRAVE; case GLFW_KEY_SEMICOLON: return Key::SEMICOLON; case GLFW_KEY_RIGHT_BRACKET: return Key::RIGHT_BRACKET; case GLFW_KEY_LEFT_BRACKET: return Key::LEFT_BRACKET; case GLFW_KEY_MINUS: return Key::MINUS; case GLFW_KEY_EQUAL: return Key::EQUALS; case GLFW_KEY_INSERT: return Key::INSERT; case GLFW_KEY_DELETE: return Key::DELETE; case GLFW_KEY_HOME: return Key::HOME; case GLFW_KEY_END: return Key::END; case GLFW_KEY_PAGE_UP: return Key::PAGE_UP; case GLFW_KEY_PAGE_DOWN: return Key::PAGE_DOWN; case GLFW_KEY_PRINT_SCREEN: return Key::PRINT_SCREEN; case GLFW_KEY_SCROLL_LOCK: return Key::SCROLL_LOCK; case GLFW_KEY_NUM_LOCK: return Key::NUM_LOCK; case GLFW_KEY_UP: return Key::UP; case GLFW_KEY_DOWN: return Key::DOWN; case GLFW_KEY_LEFT: return Key::LEFT; case GLFW_KEY_RIGHT: return Key::RIGHT; case GLFW_KEY_KP_0: return Key::PAD0; case GLFW_KEY_KP_1: return Key::PAD1; case GLFW_KEY_KP_2: return Key::PAD2; case GLFW_KEY_KP_3: return Key::PAD3; case GLFW_KEY_KP_4: return Key::PAD4; case GLFW_KEY_KP_5: return Key::PAD5; case GLFW_KEY_KP_6: return Key::PAD6; case GLFW_KEY_KP_7: return Key::PAD7; case GLFW_KEY_KP_8: return Key::PAD8; case GLFW_KEY_KP_9: return Key::PAD9; case GLFW_KEY_KP_ADD: return Key::PAD_PLUS; case GLFW_KEY_KP_SUBTRACT: return Key::PAD_MINUS; case GLFW_KEY_KP_MULTIPLY: return Key::PAD_TIMES; case GLFW_KEY_KP_DIVIDE: return Key::PAD_DIV; case GLFW_KEY_KP_DECIMAL: return Key::PAD_DECIMAL; case GLFW_KEY_KP_ENTER: return Key::PAD_RETURN; default: return Key::UNKNOWN; } } } /* namespace glfw */ } /* namespace zephyr */
true
3d6bacaa626c8aa56b6a723e8c0a66f402c028a0
C++
WildGenie/VirtualGameSandbox
/CppVhdAPI/Registry/RegTest.cpp
UTF-8
1,205
2.71875
3
[ "Zlib" ]
permissive
#pragma warning(disable: 4201) // nameless struct/union #include <windows.h> #include <tchar.h> #pragma warning(default: 4201) #include "RegistryKey.hpp" #include <iostream> using namespace JetByteTools; int main() { try { //CRegistryKey key = CRegistryKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE")); CRegistryKey key = CRegistryKey(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DESCRIPTION")); for (CRegistryKey::SubkeyIterator it = key.BeginSubkeyIteration(); it != key.EndSubkeyIteration(); ++it) { std::cout << it.GetName() << std::endl; CRegistryKey thisKey = it.OpenKey(); for (CRegistryKey::ValueIterator val = thisKey.BeginValueIteration(); val != thisKey.EndValueIteration(); ++val) { std::cout << " " << val.GetName() << " - " << val.AsString() << std::endl; } } CRegistryKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE")).CreateKey(_T("JetByteTest")).SetValue(_T(""), _T("This is a Test")); CRegistryKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE")).DeleteKey(_T("JetByteTest")); } catch (CRegistryKey::Exception &e) { e.MessageBox(); } return 1; }
true
fcd96cedceb232b20ff62a5c90b50cc04b7fee37
C++
MaksPetrov/lab21
/#6.cpp
UTF-8
406
2.96875
3
[]
no_license
#include <iostream> using namespace std; int main() { string str, s = ""; getline(cin, str); unsigned i = str.length()-1; int count = 0; while(count!=2) { if(int(str[i])==92) { count += 1; } i -= 1; } i += 2; while(int(str[i])!=92) { s += str[i]; i += 1; } cout << s; }
true
e2979eb1ec0abe88799cde8b69f5f3b9fc74fc64
C++
joonas-yoon/PS
/Kakao/Blind Recruitment/2018/2.cpp
UTF-8
1,051
2.828125
3
[]
no_license
#include <string> #include <vector> using namespace std; using lld = long long; struct Round { int score; char bonus, opt; }; int powWithBonus(int k, char bns) { int x = 1, res = k; if (bns == 'D') x = 2; else if (bns == 'T') x = 3; while (--x > 0) res *= k; return res; } int solution(string dartResult) { vector<Round> v; int num = 0, len = dartResult.length(); char bns = 0, opt = 0; bool cut = false; for (int i = 0; i < len; ++i) { char c = dartResult[i]; if ('0' <= c && c <= '9') { if (cut) { v.push_back({ num, bns, opt }); num = bns = opt = 0; } num = 10 * num + c - '0'; cut = false; } else if ('A' <= c && c <= 'Z') bns = c, cut = true; else opt = c, cut = true; } v.push_back({ num, bns, opt }); for (int i = 0; i < 3; ++i) { v[i].score = powWithBonus(v[i].score, v[i].bonus); if (v[i].opt == '#') { v[i].score *= -1; } if (v[i].opt == '*') { v[i].score *= 2; if (i > 0) v[i - 1].score *= 2; } } int answer = 0; for (auto& x : v) answer += x.score; return answer; }
true
de5947a8e3dd0a86612a49748704ab2cb03d9316
C++
darrell24015/Uno
/Grove_LED_Button/Grove_LED_Button.ino
UTF-8
774
2.90625
3
[ "CC0-1.0" ]
permissive
/* Grove_LED_Button * Demo of Grove - Starter Kit * Loovee 2013-3-10 * This demo will show you how to use Grove Touch Sensor Button to control a LED * Also works the same way with the mechanical button * Grove - Button connect to D3 * Grove - LED connect to D7 */ // Define your pins const int pinButton = 3; const int pinLED = 7; const int boardLED = 13; void setup() { // put your setup code here, to run once: pinMode(pinButton, INPUT); pinMode(pinLED, OUTPUT); pinMode(boardLED, OUTPUT); } void loop() { // put your main code here, to run repeatedly: if (digitalRead(pinButton)) { digitalWrite(pinLED, HIGH); digitalWrite(boardLED, HIGH); } else { digitalWrite(pinLED, LOW); digitalWrite(boardLED, LOW); } delay(10); }
true
04988dc8e4ec8088426dbba55aaadf58c9e9bb67
C++
henke37/psf-shellext
/Mininscf-shellext/psfParser.cpp
UTF-8
3,729
2.578125
3
[]
no_license
#include "common.h" #include "psfParser.h" #include <cstring> PsfParser::PsfParser(IStream *_stream) : stream(_stream) { stream->AddRef(); } PsfParser::~PsfParser() { stream->Release(); } HRESULT PsfParser::readLong(uint32_t &out) { HRESULT hresult; ULONG bytesRead; CHAR readBuf[4]; hresult=stream->Read(&version,1,&bytesRead); retIfNonOk; out=readBuf[0] | readBuf[1]<<8 | readBuf[2]<<16 | readBuf[3] <<24; return S_OK; } HRESULT PsfParser::parse() { STATSTG streamStat; ULONG bytesRead; HRESULT hresult; hresult=stream->Stat(&streamStat,STATFLAG_NONAME); retIfFail; if(streamStat.cbSize.QuadPart<MIN_PCF_SIZE) { return E_INVALIDARG; } LARGE_INTEGER seekPos; seekPos.QuadPart=0; hresult=stream->Seek(seekPos,STREAM_SEEK_SET,nullptr); retIfFail; CHAR fileSig[3]; hresult=stream->Read(fileSig,3,&bytesRead); retIfNonOk; if(strcmp(fileSig,"PSF")!=0) return E_INVALIDARG; hresult=stream->Read(&version,1,&bytesRead); retIfNonOk; uint32_t reservatedLength,compressedLength,compressedCrc; hresult=readLong(reservatedLength); retIfNonOk; hresult=readLong(compressedLength); retIfNonOk; hresult=readLong(compressedCrc); retIfNonOk; seekPos.QuadPart=reservatedLength+compressedLength; hresult=stream->Seek(seekPos,STREAM_SEEK_CUR,nullptr); retIfFail; CHAR tagSig[5]; hresult=stream->Read(tagSig,5,&bytesRead); retIfFail; if(hresult==S_FALSE) return S_FALSE; if(strcmp(tagSig,"[TAG]")!=0) return E_INVALIDARG; seekPos.QuadPart=0; hresult=stream->Seek(seekPos,STREAM_SEEK_CUR,&tagStart); retIfFail; return parseTags(); } #define ReadBuffLen 256 HRESULT PsfParser::parseTags() { HRESULT hresult; bool inName=true; std::string name; std::string value; //TODO: deal with the case of no tags at all in the existing file try { do { CHAR readBuff[ReadBuffLen]; ULONG bytesRead; hresult=stream->Read(readBuff,ReadBuffLen,&bytesRead); retIfFail; for(ULONG i=0;i<bytesRead;++i) { CHAR &c=readBuff[i]; if(c=='=') { //TODO: trim whitespace inName=false; } else if(c=='\r') { } else if(c=='\n') { inName=true; //TODO: trim whitespace auto existingItr=tags.find(name); if(existingItr!=tags.end()) { existingItr->second+="\n"; existingItr->second+=value; } else { tags.insert(std::make_pair(name,value)); } name.clear(); value.clear(); } else if(inName) { name+=c; } else { value+=c; } } } while(hresult==S_OK); return S_OK; } catch (std::bad_alloc ba) { return E_OUTOFMEMORY; } } HRESULT PsfParser::saveTags() { HRESULT hresult; ULONG bytesWritten; try { LARGE_INTEGER seekPos; seekPos.QuadPart=tagStart.QuadPart; hresult=stream->Seek(seekPos,STREAM_SEEK_SET,nullptr); retIfFail; for(auto &kv: tags) { auto &key=kv.first; auto &value=kv.second; const char *keyBuff=key.c_str(); const char *valueBuff=value.c_str(); //such a mess for newline values const char *lineStart=keyBuff; for(;;) { const char *lineEnd=std::strstr(lineStart,"\n"); bool lastLine= !lineEnd; int lineLen; if(lastLine) { lineLen=std::strlen(lineStart); lineEnd=lineStart+lineLen; } else { lineLen=lineStart-lineEnd; } hresult=stream->Write(keyBuff,key.length(),&bytesWritten); retIfFail; char eq[]={'='}; hresult=stream->Write(eq,1,&bytesWritten); retIfFail; stream->Write(lineStart,lineLen,&bytesWritten); retIfFail; char nl[]={'\n'}; hresult=stream->Write(nl,1,&bytesWritten); retIfFail; if(lastLine) { break; } lineStart=lineEnd+1; } } return S_OK; } catch (std::bad_alloc ba) { return E_OUTOFMEMORY; } }
true
b6cf5c594c80ef2c945059ef39edb6be3a223005
C++
lwxwx/multi-master-tool
/easy_logger/test_main.cc
UTF-8
1,800
2.578125
3
[ "MIT" ]
permissive
/* * @Author: wei * @Date: 2020-06-16 10:25:27 * @LastEditors: Do not edit * @LastEditTime: 2020-06-16 15:14:57 * @Description: file content * @FilePath: /multi-master-tool/easy_logger/test_main.cc */ #include "include/easylogger.h" #include <iostream> // void fun1() // { // EasyLogger("fun","./async_log.txt",EasyLogger::warn) << "fun1 : test log message"; // EasyLoggerWithTrace("./async_log.txt",EasyLogger::warn) << "FUN1 : test log message"; // } // void fun2() // { // EasyLogger("fun","./async_log.txt",EasyLogger::warn) << "fun2 : test log message"; // EasyLoggerWithTrace("./async_log.txt",EasyLogger::warn) << "FUN2 : test log message"; // } int main(void) { //fun1(); //fun2(); // EasyLogger("test_log","./async_log.txt",EasyLogger::error) << "test log message"; // EasyLogger("test_log","./async_log.txt",EasyLogger::info) << "test log message"; // EasyLogger("test_log","./async_log.txt",EasyLogger::debug) << "test log message"; //EasyLogger("test_log","./async_log.txt",EasyLogger::warn) << "test log message"; //EasyLoggerWithTrace("./async_log.txt",EasyLogger::warn).force_flush() << "test log message"; //tmp_loggger.force_flush(); //EasyLoggerWithTrace("./async_log.txt",EasyLogger::error) << "test log message"; // EasyStringLog("./async_log.txt","test_log","flush success?!",EasyLogger::LOG_LEVEL::info); // EasyStringLog("./async_log.txt","test_log","flush success?!",EasyLogger::LOG_LEVEL::debug); // EasyStringLog("./async_log.txt","test_log","flush success?!",EasyLogger::LOG_LEVEL::warn); // EasyStringLog("./async_log.txt","test_log","flush success?!",EasyLogger::LOG_LEVEL::error); EasyDebugLog("./async_log.txt","test_log",EasyLogger::info,"ative","fail"); return 0; }
true
3bbc7666238b7825e5c5e6fc5e9ef9bb0a66928c
C++
lucianap/7559-tp1
/src/Status/Status.cpp
UTF-8
3,646
2.734375
3
[]
no_license
// // Created by nestor on 23/09/19. // #include <Signal/SignalHandler.h> #include <Informe/Informe.h> #include "Status.h" #include "SolicitudStatus.h" Status::Status(Logger &logger) : ProcesoHijo(logger) {} Status::~Status() { } void Status::cargar(std::string statusSerializado) { //TODO //implementar leer el proceso del status serializado. // implementar constructor copia //this->registroVenta = } void Status::setCantPipes(int cant){ this->cantPipes = cant; } pid_t Status::ejecutar() { logger.log("Ejecutamos un Proceso Status"); pid = fork(); // en el padre devuelvo el process id if (pid != 0) return pid; // siendo distribuidor, me seteo y ejecuto lo que quiero SignalHandler::getInstance()->registrarHandler(SIGINT, &sigint_handler); SignalHandler::getInstance()->registrarHandler(SIGUSR1, &sigusr1_handler); logger.log("Naci como Status y tengo el pid: "+to_string(getpid())); this->iniciarAtencion(); logger.log("Termino la tarea del Status"); SignalHandler::destruir(); exit(0); } Pipe Status::getPipeEntrada() { return pipeEntrada; } Pipe Status::getPipeSalida() { return pipeSalida; } void Status::iniciarAtencion() { int cantEofs = 0; while (sigint_handler.getGracefulQuit() == 0) { try { if(cantEofs>=this->cantPipes && sigusr1_handler.getSaveAndQuit() != 0)break; SolicitudStatus unaSolicitud = recibirSolicitud(); if(unaSolicitud.getTipoSolicitud() != SolicitudStatus::TIPO_SOLICITUD_EOF){ despacharSolicitud(unaSolicitud); }else{ cantEofs++; } } catch (std::string &error) { logger.log("Error atendiendo solicitudes en el status: " + error); break; } } this->getPipeEntrada().cerrar(); this->getPipeSalida().cerrar(); } void Status::despacharSolicitud(SolicitudStatus solicitud) { if (solicitud.getTipoSolicitud() == SolicitudStatus::TIPO_SOLICITUD_ALTA_VENTA) { registroVenta.contabilizarRamoVendido(solicitud.getRamo()); } else if (solicitud.getTipoSolicitud() == SolicitudStatus::TIPO_SOLICITUD_INFORME) { this->enviarInforme(); } } SolicitudStatus Status::recibirSolicitud() { char buffer[SolicitudStatus::TAM_TOTAL]; string mensajeError; std::stringstream ss; ssize_t bytesleidos = pipeEntrada.leer(static_cast<void*>(buffer), SolicitudStatus::TAM_TOTAL); if (bytesleidos != SolicitudStatus::TAM_TOTAL) { if (bytesleidos == -1) mensajeError = strerror(errno); else mensajeError = "Error al leer una solicitud en el Status. solo se lee bytes: " + bytesleidos; throw(std::string(mensajeError)); } ss << buffer; SolicitudStatus solicitudStatus(ss.str()); std::stringstream mensajelog; mensajelog << "Solicitud recibida: " << solicitudStatus.toString(); logger.log(mensajelog.str()); return solicitudStatus; } void Status::enviarInforme() { Informe informe = this->registroVenta.generarInformes(); string mensajeError; ssize_t bytesleidos = pipeSalida.escribir(informe.serializar().c_str(), Informe::TAM_TOTAL_BYTES); if (bytesleidos != Informe::TAM_TOTAL_BYTES) { if (bytesleidos == -1) mensajeError = strerror(errno); else mensajeError = "Error al escribir informe en el Status. Bytes escritos: " + std::to_string(bytesleidos); throw(std::string(mensajeError)); } } std::string Status::serializar() { return this->registroVenta.serializar(); }
true
ba516046407c585b642f1f7c4ea4fda1684dcd50
C++
epidersis/olymps
/327A/327A.cpp
UTF-8
581
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { short n, temp, max = 0; cin >> n; bool *arr = new bool[n]; for (short i = 0; i < n; i++) cin >> arr[i]; for (short k = 0; k < n; k++) { for (short i = 0; i < n - k; i++) { for (short j = i; j < n - k; j++) arr[j] = !arr[j]; temp = count(arr, arr+n, 1); if (temp > max) max = temp; for (short j = i; j < n - k; j++) arr[j] = !arr[j]; } } cout << max; return 0; }
true
d32d70f955385688da627d238f39586e4dab1152
C++
ji12345ba/CS225-UIUC
/lab_memory/tests/catchlib.cpp
UTF-8
2,168
3.0625
3
[]
no_license
#include "catchlib.hpp" namespace cs225 { bool fileExists(std::string fileName) { std::ifstream f(fileName.c_str()); bool exists = f.good(); f.close(); return exists; } void print_valgrind() { std::cout << "===============================================================================" << std::endl; std::cout << "===============================================================================" << std::endl; std::cout << "You may want to run these test cases in valgrind!" << std::endl; std::cout << "valgrind --leak-check=full ./test" << std::endl; std::cout << "OR: " << std::endl; std::cout << "valgrind --leak-check=full ./test \"[valgrind]\"" << std::endl; std::cout << "===============================================================================" << std::endl; std::cout << "===============================================================================" << std::endl; std::cout << std::endl; } void print_quote(std::string filename) { std::vector<std::string> quotes; std::ifstream quote_file(filename); std::string line; while (std::getline(quote_file, line)) { quotes.push_back(line); } if (quotes.size() > 0) { size_t index = rand() % quotes.size(); std::cout << std::endl << std::endl; std::cout << "===============================================================================" << std::endl; std::cout << "===============================================================================" << std::endl; std::cout << "===============================================================================" << std::endl; std::cout << quotes[index] << std::endl; std::cout << "===============================================================================" << std::endl; std::cout << "===============================================================================" << std::endl; std::cout << "===============================================================================" << std::endl; std::cout << std::endl << std::endl; } } }
true
dd3a5f7b1be186867d75356945e2d52657474acd
C++
eatoncns/sdl-asteroids
/asteroids/src/gameTest/cpp/GameLoopTest.cpp
UTF-8
2,805
2.984375
3
[]
no_license
#include <gmock/gmock.h> #include <GameLoop.hpp> #include <Game.hpp> #include <TestTimer.hpp> #include <boost/assign/list_of.hpp> #include <list> #include <string> using namespace pjm; using namespace boost::assign; using ::testing::Eq; using ::testing::ElementsAre; struct TestGame : public Game { TestGame() : passInitialisation(true), iterations(0) {} bool isRunning() { return (iterations-- > 0); } bool initialise() { calls.push_back("init"); return passInitialisation; } void update(unsigned int iTimeElapsed) { calls.push_back("update"); updateTimes.push_back(iTimeElapsed); } void draw() { calls.push_back("draw"); } bool passInitialisation; unsigned int iterations; std::list<std::string> calls; std::list<unsigned int> updateTimes; }; class GameLoopTest : public ::testing::Test { protected: GameLoopTest() : gameLoop(game, timer) { timer.times = list_of(3)(6)(10)(15).to_adapter(); } bool runIterations(const unsigned int iIterations) { game.iterations = iIterations; return gameLoop.run(); } int callCount(const std::string& iFunction) { return std::count(game.calls.begin(), game.calls.end(), iFunction); } TestGame game; TestTimer timer; GameLoop gameLoop; }; TEST_F(GameLoopTest, DoesNoUpdatesWhenGameIsStopped) { runIterations(0); EXPECT_THAT(callCount("update"), Eq(0)); } TEST_F(GameLoopTest, UpdatesUntilGameIsStopped) { runIterations(2); EXPECT_THAT(callCount("update"), Eq(2)); } TEST_F(GameLoopTest, DrawsUntilGameIsStopped) { runIterations(2); EXPECT_THAT(callCount("draw"), Eq(2)); } TEST_F(GameLoopTest, CallsInitialiseOnce) { runIterations(3); EXPECT_THAT(callCount("init"), Eq(1)); } TEST_F(GameLoopTest, CallsGameFunctionsInExpectedOrder) { runIterations(1); EXPECT_THAT(game.calls, ElementsAre("init", "update", "draw")); } TEST_F(GameLoopTest, DoesNoUpdatesWhenInitialisationFails) { game.passInitialisation = false; runIterations(1); EXPECT_THAT(callCount("update"), Eq(0)); } TEST_F(GameLoopTest, IndicatesIntialisationFailure) { game.passInitialisation = false; EXPECT_FALSE(runIterations(1)); } TEST_F(GameLoopTest, PassesElapsedTimeToUpdate) { runIterations(3); EXPECT_THAT(game.updateTimes, ElementsAre(3, 4, 5)); } TEST_F(GameLoopTest, RunsExtraUpdatesToCatchUpMissedFrames) { unsigned int ticks = GameLoop::TICKS_PER_FRAME; timer.times = list_of(0)(ticks)(3*ticks).to_adapter(); runIterations(2); EXPECT_THAT(game.updateTimes, ElementsAre(ticks, ticks, ticks)); }
true
3bf44434e345d6eadd4f3fccb92a4b282ae173eb
C++
AndreSci/Cpp
/lesson_007/queue.cpp
UTF-8
959
3.015625
3
[]
no_license
#include <iostream> #include <vector> #include <string> using namespace std; int main() { int Q(5), people(0); int worry_peop_step(0); cin >> Q; int* worry_people = new int [Q]; for (int e(0); e < Q; e++) worry_people[e] = 0; vector<string> i; string come_quiet; for (int p(0); p < Q; p++) { cin >> come_quiet; if(come_quiet != "WORRY_COUNT") cin >> people; if (come_quiet == "COME" && people > 0) { for (int j(0); j < people; j++) { i.push_back(" "); } } if (come_quiet == "COME" && people < 0) { for (int j(0); j > people; j--) { i.pop_back(); } } if (come_quiet == "WORRY") { i[people - 1] = { "WORRY" }; } if (come_quiet == "WORRY_COUNT") { for (int f(0); f < i.size(); f++) { if (i[f] == "WORRY") worry_people[worry_peop_step]++; } worry_peop_step++; } } for(int g(0); g< worry_peop_step; g++) cout << worry_people[g] << endl; return 0; }
true
1666e21fe9d5a68e6e2678def45a1f758c9ea797
C++
arash-ha/Cpp
/Find All Numbers Disappeared in an Array.cpp
UTF-8
1,405
3.703125
4
[]
no_license
/* Find All Numbers Disappeared in an Array Given an array of integers where 1 = a[i] = n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6] Constraints: n == nums.length 1 <= n <= 10^5 1 <= nums[i] <= n Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. */ // Solution I class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { if (nums.empty()) return {}; vector<int> result{}; for(int num : nums) while(nums[num - 1] != num) swap(num, nums[num - 1]); for (int i = 0; i < nums.size(); i++) if (nums [i] != i + 1) result.emplace_back(i + 1); return result; } }; // Solution II class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { for(int i = 0; i < nums.size(); i++){ int m = abs(nums[i]) - 1; nums[m] = nums[m] > 0 ? -nums[m] : nums[m]; } vector<int> res; for(int i = 0; i < nums.size(); i++) { if(nums[i] > 0) res.emplace_back(i + 1); } return res; } };
true
d7fda6f428f94f687c89b4f6717a92ad13e49fee
C++
nikhildhruwe/cpp_practice
/primeFactor.cpp
UTF-8
406
3.546875
4
[]
no_license
#include <iostream> using namespace std; int main(){ int number ; cout<<"Enter a number"<<endl; cin>>number; while(number%2==0) { cout<<"2 "; number/=2; } for (int i = 3; i*i<=number; i+=2){ while (number%i==0){ cout<< i << " "; number/=i; } } if (number>2) cout << number<<endl; else cout<<endl; }
true
6c744328cb566cd8614d964382034a918dc4317a
C++
BenWeber42/algo-labs
/week2/03_aliens/solution.cpp
UTF-8
1,897
2.921875
3
[]
no_license
#include <cassert> #include <iostream> #include <utility> #include <algorithm> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(false); int tests; cin >> tests; for (int test = 0; test < tests; ++test) { int n, m; cin >> n >> m; vector<pair<int, int>> intervals; for (int i = 0; i < n; ++i) { int p, q; cin >> p >> q; if (p != 0) { assert(q != 0); assert(p <= q); intervals.push_back(make_pair(p, q)); } else { assert(q == 0); } } // check if there are unbeaten humans: sort(intervals.begin(), intervals.end(), [] (const pair<int, int>& a, const pair<int, int>& b) { return a.first < b.first || (a.first == b.first && a.second > b.second); }); int beaten = 0; for (const auto& interval: intervals) { if (beaten + 1 < interval.first) { break; } beaten = max(beaten, interval.second); } if (beaten < m) { // there are some unbeaten humans cout << 0 << endl; continue; } // check which aliens beat all other aliens int count = 0, max_bound = 0; pair<int, int> last = make_pair(0, 0); for (const auto& interval: intervals) { if (interval.second > max_bound) { ++count; max_bound = interval.second; last = interval; continue; } if (interval.second < max_bound) { continue; } assert(interval.second == max_bound); if (last == interval) { // decrease count due to duplicate --count; // reset last, in case of tripple etc last = make_pair(0, 0); } } cout << count << endl; } }
true
3f2b486c5d734ebb0fa21032cc46bc4f84d4b28e
C++
Sabuj-Kumar/Problem_Solve
/sabuj/Rahul vai/Projects and presentation/60-65-66/Final(joma deoyar jonno)/code.cpp
UTF-8
4,136
2.9375
3
[]
no_license
#include <cstdio> #include <iostream> #include <cstdlib> #include <cstring> using namespace std; struct data { char Airlines_name[1000]; int Planes; bool available; char t_list[100][20]; }all[1000]; void data_print(data A) { printf("%s has ",A.Airlines_name); printf("%d Planes \nstatus: ",A.Planes); A.available ? puts("available") : puts("not available"); puts("plane list"); for(int i=0; i<A.Planes; i++) printf("%s. ",A.t_list[i]); puts("\n"); } struct plane_detail { char name[1000], number[1000]; int a_hour,a_min, d_hour,d_min; int capacity,available_seats; char passenger[100][35]; }detail[1000]; void plane_detail_print(plane_detail U) { printf(" %s %s \n",U.name,U.number); printf("capacity is %d and %d available seats. \n",U.capacity,U.available_seats); printf("arrival time %d:%d\n",U.a_hour,U.a_min); printf("departure time %d:%d\nPassenger List",U.d_hour,U.d_min); for(int i=0; i<U.capacity-U.available_seats; i++) puts(U.passenger[i]); puts("\n"); } void file_one() { FILE *P1; P1=fopen("file_1.txt","r+"); for(int i=0, j; i<10; i++) { char c[1000],ch[1000]; fscanf(P1,"%s %s",ch, all[i].Airlines_name); fscanf(P1,"%s %d",ch, &all[i].Planes); fscanf(P1,"%s %s",ch, c); (!strcmp(c,"Yes"))? all[i].available=1 : all[i].available=0; fscanf(P1,"%s",ch); for(j=0; j<all[i].Planes; j++) fscanf(P1,"%s", all[i].t_list[j]); all[i].t_list[j-1][(strlen(all[i].t_list[j-1])-1)]='\0'; } //for(int i=0; i<10; i++) data_print(all[i]); } void file_two() { FILE *P2; P2=fopen("file_2.txt","r+"); for(int i=0, j; i<40; i++) { char c[1000],ch[1000]; fscanf(P2,"%s %s %s",ch, detail[i].name,detail[i].number); fscanf(P2,"%s %d",ch, &detail[i].capacity); detail[i].available_seats=detail[i].capacity; fscanf(P2,"%s %d:%d",ch,&detail[i].a_hour,&detail[i].a_min); fscanf(P2,"%s %d:%d",ch,&detail[i].d_hour,&detail[i].d_min); fscanf(P2,"%s",ch); for(j=0; j<detail[i].capacity; j++) fscanf(P2,"%s", detail[i].passenger[j]); } //for(int i=0; i<40; i++) plane_detail_print(detail[i]); } void user() { puts("\t\t*******************************\n\t\t*******************************\n\n\t\t\tAir Ticket Management\n\n\n\t\t*******************************\n\t\t*******************************\n"); char ch[1000],str[1000]; for(;;) { puts("The following planes are available\n"); puts(" Bangladesh_Airlines\n Emirates_Airlines\n Japan_Airlines\n Kolkata_Airlines\n Riad_Airlines\n Quatar_Airlines\n Dubai_Airlines\n China_Eastern_Airlines\n Delta_Airlines\n Singapore_Airlines\n"); printf("Which plane do you want..??\nPlease type the plane name "); scanf("%s",ch); int wanted, wanted_plane_number; for(int i=0; i<10; i++) if(!strcmp(ch,all[i].Airlines_name)) wanted=i; puts("here is the detail of this plane \n"); data_print(all[wanted]); puts("Please enter the airlines name with the plane number you want... "); scanf("%s %s",ch,str); for(int i=0; i<40; i++) if(!strcmp(ch,detail[i].name)&&!strcmp(str,detail[i].number)) wanted_plane_number=i; plane_detail_print(detail[wanted_plane_number]); if(detail[wanted_plane_number].available_seats!=0) { puts("please enter your name"); getchar(); gets(detail[wanted_plane_number].passenger[ detail[wanted_plane_number].capacity - detail[wanted_plane_number].available_seats ]); detail[wanted_plane_number].available_seats--; puts("\n\nWelcome...!!!"); printf("Your ticket number is %d\n",detail[wanted_plane_number].capacity - detail[wanted_plane_number].available_seats); } else puts("\nsorry...!!! not available"); puts("\n\n-------------------------------------------------------------------\n"); } } int main() { file_one(); file_two(); user(); return 0; }
true
030015bb80e387189d9788f4804e1ca67ff04d8e
C++
shishir-roy/competitive-programming-master
/LightOJ/1276 - Very Lucky Numbers.cpp
UTF-8
1,377
2.625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; vector<long long int>lucky,vlucky; void lucky_gen(long long int num) { if(num>1000000100000LL) { return; } if(num!=0) { lucky.push_back(num); } lucky_gen(num*10+4); lucky_gen(num*10+7); } set<long long int>st; void vlucky_gen(int ps,long long int num) { if(num>1000000100000LL) { return; } if(num<=1000000100000LL and num>1) { st.insert(num); } if(ps>=lucky.size()) { return; } if(num<=1000000100000LL/lucky[ps])vlucky_gen(ps+1,num); if(num<=1000000100000LL/lucky[ps])vlucky_gen(ps+1,num*lucky[ps]); if(num<=1000000100000LL/lucky[ps])vlucky_gen(ps,num*lucky[ps]); } int main() { // clock_t b=clock(); lucky_gen(0); sort(lucky.begin(),lucky.end()); vlucky_gen(0,1LL); copy(st.begin(),st.end(),back_inserter(vlucky)); sort(vlucky.begin(),vlucky.end()); // clock_t e=clock(); // cout << (float)(e-b)/CLOCKS_PER_SEC << endl; int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { long long int a,b; cin >> a >> b; long long int ans=upper_bound(vlucky.begin(),vlucky.end(),b)-lower_bound(vlucky.begin(),vlucky.end(),a-1); cout << "Case " << qq << ": " << ans << '\n'; } return 0; }
true
6770f2cf7f4525ac81813e91427846ab2dfb1c6d
C++
DecimatorMind/Code-Chef-CPP-Answers
/Code Chef C++ Answers/FLOW004.cpp
UTF-8
460
2.796875
3
[]
no_license
// // FLOW004.cpp // Code Chef C++ Answers // // Created by Pranjal Bhardwaj on 24/07/20. // Copyright © 2020 Pranjal Bhardwaj. All rights reserved. // #include <iostream> using namespace std; int flow004(){ int iter; cin >> iter; for(int i = 0;i < iter;i++){ int n,temp = 0,flag; cin >> n; flag = n%10; while(n){ temp = n%10; n /= 10; } cout << (temp+flag) << endl; } return 0; }
true
7f05a0370a807fd9f2177f5b9f68cddfbbb488b7
C++
m1h4/Touch
/Sound.h
UTF-8
565
2.71875
3
[ "MIT" ]
permissive
#pragma once class Sound { public: Sound(void) : mBuffers(NULL), mBufferCount(0) {} ~Sound(void) { Unload(); } bool LoadFromFile(LPCTSTR path,unsigned long buffers = 8); bool LoadFromMemory(LPWAVEFORMATEX format,unsigned char* data,unsigned long size,unsigned long buffers); void Unload(void); bool Play(bool loop = false); bool GetPlaying(void) const; bool GetLooping(void) const; void Stop(void); void Reset(void); void SetVolume(float volume); float GetVolume(void) const; public: unsigned long mBufferCount; IDirectSoundBuffer** mBuffers; };
true
f5506bc12321140325098179d2aec02a6292c4cc
C++
hiddeninplainsight/EmbeddedHelperLibrary
/tests/exponential_smoothing.tests.cpp
UTF-8
1,480
3.046875
3
[ "MIT" ]
permissive
#include <ehl/exponential_smoothing.h> #include <unity_cpp.h> #include <ehl/algorithm.h> TEST_GROUP(exponential_smoothing); TEST_SETUP(exponential_smoothing) { } TEST_TEAR_DOWN(exponential_smoothing) { } TEST(exponential_smoothing, A_smoothing_factor_of_1_applies_no_smoothing) { ehl::exponential_smoothing<float> smoothed(1.0f); smoothed.add_value(10); TEST_ASSERT_EQUAL_FLOAT(10, smoothed.value()); smoothed.add_value(20); TEST_ASSERT_EQUAL_FLOAT(20, smoothed.value()); } TEST(exponential_smoothing, A_smoothing_factor_of_0_5_smoothes_the_data) { ehl::exponential_smoothing<float> smoothed(0.5f); smoothed.add_value(10); TEST_ASSERT_EQUAL_FLOAT(5, smoothed.value()); smoothed.add_value(10); TEST_ASSERT_EQUAL_FLOAT(7.5, smoothed.value()); } TEST(exponential_smoothing, A_integer_type_can_be_smoothed_by_a_factor_of_0_5) { ehl::exponential_smoothing<int> smoothed(5, 10); smoothed.add_value(10); TEST_ASSERT_EQUAL_INT(5, smoothed.value()); smoothed.add_value(10); TEST_ASSERT_EQUAL_INT(7, smoothed.value()); } TEST(exponential_smoothing, exponential_smoothing_can_be_passed_to_algorithms) { ehl::exponential_smoothing<float> smoothed(0.75); float const original[3] = {10.0f, 5.0f, 10.0f}; float smoothed_data[3] = {0.0f}; ehl::transform(original, original + 3, smoothed_data, smoothed); TEST_ASSERT_EQUAL_FLOAT(7.5f, smoothed_data[0]); TEST_ASSERT_EQUAL_FLOAT(5.625f, smoothed_data[1]); TEST_ASSERT_EQUAL_FLOAT(8.90625f, smoothed_data[2]); }
true
686589e7c43cfb50397bc7b5a64d3a0e1a9d89a9
C++
Hendra89ms/Cpp_Program
/Faktorial2.cpp
UTF-8
332
3.421875
3
[]
no_license
#include<iostream> using namespace std; int faktorial (int n); int main(){ int angka,hasil; cout<<"Menghitung faktorial : "; cin>>angka; hasil=faktorial(angka); cout<<"\nNilainya adalah : "<<hasil<<endl; } int faktorial(int n){ if (n<= 1){ cout<<n; return n; }else{ cout<< n << "*"; return n*faktorial(n-1); } }
true
259fa25a41b26dea9b748c3b4842223c5186146a
C++
MadisonStevens98/Hotel-Booking-Demo
/Main.cpp
UTF-8
4,387
3.421875
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include "Hotel.h" #include "Room.h" using namespace std; char charinput; int intinput; string date; Room arrayofcourtyardrooms[70]; Room arrayofscenicrooms[35]; Room arrayofsuiterooms[15]; Room arrayofpenthouserooms[2]; void myfilewriter(Hotel& Ourhotel , ofstream& myfile) { myfile.open(date); myfile.write((char*)&Ourhotel, sizeof(Ourhotel)); myfile.close(); }; Hotel Hotelconstructor(Hotel& Ourhotel) { Ourhotel.totalrooms = 122; Ourhotel.totalreserved = 0; Ourhotel.totalopen = 122; Ourhotel.totalopencourtyard = 70; Ourhotel.totalreservedcourtyard = 0; Ourhotel.totalopenscenic = 15; Ourhotel.totalreservedscenic = 0; Ourhotel.totalopensuite = 35; Ourhotel.totalreservedsuite = 0; Ourhotel.totalopenpenthouse = 2; Ourhotel.totalreservedpenthouse = 0; for (int i = 0; i < 70; i++) { arrayofcourtyardrooms[i].constructor(125, 101 + i, "Courtyard"); } for (int i = 0; i < 35; i++) { arrayofscenicrooms[i].constructor(145, 201 + i, "Scenic"); } for (int i = 0; i < 15; i++) { arrayofsuiterooms[i].constructor(350, 236 + i, "Suite"); } for (int i = 0; i < 2; i++) { arrayofpenthouserooms[i].constructor(1135, 301 + i, "Penthouse"); } return Ourhotel; }; void recurse(Hotel& e, ofstream& myfile) { cout << "\nHotel Current Status:\nTotal # of Rooms: " << e.totalrooms << "\nOpen Rooms: " << e.totalopen << "\nReserved Rooms: " << e.totalreserved; cout << "\nType R to make a reservation, and type T for the days total revenue and room status. Type D if you would like to change the date.\n"; cin >> charinput; if (charinput == 'T') { e.getTotal(); } else if (charinput == 'R') { cout << "\nPlease select which room from the following options:\n1.Courtyard\n2.Scenic\n3.Suite\n4.Penthouse\n"; cin >> intinput; if (intinput == 1) { for (int i = 0; i < 70; i++) { if (arrayofcourtyardrooms[i].occupantname == "") cout << "Please enter the name of occupent: "; cin >> arrayofcourtyardrooms[i].occupantname; cout << "Room number: " << arrayofcourtyardrooms[i].roomnumber << " has been reserved under " << arrayofcourtyardrooms[i].occupantname<< "\n"; arrayofcourtyardrooms[i].reservecourtyard(e); i = 70; } myfilewriter(e, myfile); } else if (intinput == 2) { for (int i = 0; i < 35; i++) { if (arrayofscenicrooms[i].occupantname == "") cout << "Please enter the name of occupent: "; cin >> arrayofscenicrooms[i].occupantname; cout << "Room number: " << arrayofscenicrooms[i].roomnumber << " has been reserved under " << arrayofscenicrooms[i].occupantname<< "\n"; arrayofscenicrooms[i].reservescenic(e); i = 35; } myfilewriter(e, myfile); } else if (intinput == 3) { for (int i = 0; i < 15; i++) { if (arrayofsuiterooms[i].occupantname == "") cout << "Please enter the name of occupent: "; cin >> arrayofsuiterooms[i].occupantname; cout << "Room number: " << arrayofsuiterooms[i].roomnumber << " has been reserved under " << arrayofsuiterooms[i].occupantname << "\n"; arrayofsuiterooms[i].reservesuite(e); i = 15; } myfilewriter(e, myfile); } else if (intinput == 4) { for (int i = 0; i < 2; i++) { if (arrayofpenthouserooms[i].occupantname == "") cout << "Please enter the name of occupent: "; cin >> arrayofpenthouserooms[i].occupantname; cout << "Room number: " << arrayofpenthouserooms[i].roomnumber << " has been reserved under " << arrayofpenthouserooms[i].occupantname << "\n"; arrayofpenthouserooms[i].reservepenthouse(e); i = 2; } myfilewriter(e, myfile); } } else if (charinput == 'D'){ cout << "Please enter the date for reservations (ex.MMDDYY). Try to keep the date format consistant.: "; cin >> date; ifstream file1; file1.open(date); file1.read((char*)&e, sizeof(e)); } else { cout << "Please try again."; } recurse(e, myfile); }; int main() { Hotel Ourhotel; Hotelconstructor(Ourhotel); cout << "Please enter the date for reservations (ex.MMDDYY). Try to keep the date format consistant.: "; cin >> date; ifstream file1; file1.open(date); file1.read((char*)&Ourhotel, sizeof(Ourhotel)); ofstream myfile; recurse(Ourhotel, myfile); system("PAUSE"); }
true
79645a27c3f53135a1ccc1585c9e43a3062fb975
C++
ashehata277/Projects-C-
/Arrays/String class.cpp
UTF-8
394
3.1875
3
[]
no_license
#include<iostream> #include<string> //for string class using namespace std; int main() { string s1="Man "; string s2="Beast"; string s3; s3=s1; //assign and without the library cant write that cout<< s3<<endl; s3= "neither "+s1+" nor "; //concatenate s3+=s2; //concatenate cout<< s3<< endl; s1.swap(s2); cout<<s1<<"nor"<<s2<<endl; system ("pause"); return 0; }
true
91ef1a285c1670795fb60e7fcd2154355eb88380
C++
jjuiddong/Common
/Motion/script/mathscript.h
UHC
1,295
2.5625
3
[ "MIT" ]
permissive
// ͽ ũƮ ü #pragma once namespace mathscript { //----------------------------------------------------------------------------------------- // Mixing Command Parser struct sFactor; struct sDTerm; namespace OP_MULTI { enum TYPE { MULTI, DIVIDE }; } namespace OP_PLUS { enum TYPE { PLUS, MINUS }; } namespace FACTOR_TYPE { enum TYPE { ID, NUMBER, EXPR, FUNC, }; } struct sTerm { sDTerm *dterm; OP_MULTI::TYPE op; sTerm *term; }; struct sDTerm { sFactor *factor1; OP_MULTI::TYPE op; sFactor *factor2; }; struct sExpr { sTerm *term1; OP_PLUS::TYPE op; sExpr *expr; }; struct sExprList { sExpr *expr; sExprList *next; }; struct sFunc { string id; //sExpr *expr; sExprList *exprs; }; struct sFactor { FACTOR_TYPE::TYPE type; string id; float number; sExpr *expr; sFunc *func; }; struct sAssignStmt { string id; sExpr *expr; }; struct sStatement { sAssignStmt *assign; sExpr *expr; sStatement *next; }; void rm_statement(sStatement *p); void rm_assignstmt(sAssignStmt *p); void rm_factor(sFactor *p); void rm_term(sTerm *p); void rm_dterm(sDTerm *p); void rm_expr(sExpr *p); void rm_func(sFunc*p); void rm_exprlist(sExprList *p); }
true
010f017f978a81b52880f1236ba247495bf86f2e
C++
FabienPean/vectr
/example.cpp
UTF-8
1,920
3.3125
3
[ "MIT" ]
permissive
#include "vectr.h" #include <vector> #include <iostream> struct X { static inline int n = 0; int x; X(int i) : x(i) { std::cout << "constructed-default" << std::endl; ++n; } X() { std::cout << "constructed-default" << std::endl; ++n; } X(X&& y) { std::cout << "constructed-move" << std::endl; x = y.x; ++n; } X& operator=(X&& y) { std::cout << "assign-move" << std::endl; x = y.x; ++n; return *this; } X(const X& y) { std::cout << "constructed-copy" << std::endl; x = y.x; ++n; } X& operator=(const X& y) { std::cout << "assign-copy" << std::endl; x = y.x; ++n; return *this; } ~X() { std::cout << "destroyed" << std::endl; --n; } operator int& () { return x; } operator const int& () const { return x; } }; auto test(vectr::vecter&& vin) { vectr::vecter v; v = std::move(vin); assert(v.vector<X>(0) == 42); } auto test(vectr::vecter& vin) { vectr::vecter v(vin); assert(v.vector<X>(0) == 42); } int main() { { auto vd = vectr::vecter::create<X>(); vd.vector<X>().push_back(42); assert(vd.vector<X>(0).x == 42); vd.vector<X>().push_back(3); assert(vd.vector<X>(0).x == 42); assert(vd.vector<X>(1) == 3); test(vd); test(std::move(vd)); vd.vector<X>().push_back(23); assert(vd.vector<X>(0) == 23); vd.vector<X>().push_back(2); assert(vd.vector<X>(0) == 23); assert(vd.vector<X>(1) == 2); } { vectr::vecter va = vectr::vecter(); va = vectr::vecter::create<X>(); va.vector<X>().push_back(42); assert(X::n == 1); } assert(X::n == 0); auto vx = vectr::vecter::create<X>(); vx.vector<X>().emplace_back(42); vx.vector<X>().emplace_back(404); auto&& x = vx.vector<X>().pop_back(); assert(x.x == 404); vx.resize(6); assert(vx.capacity() == 8); return vx.vector<X>().size(); }
true
d56d38c3b2881d01128ce6844a501126ea643c34
C++
Tonmoy55/Basic-Problem-Solving
/armostrong_number.cpp
UTF-8
740
3.1875
3
[]
no_license
#include <bits/stdc++.h> #include <conio.h> using namespace std; int power(int rem , int a) { int pow=1,i=1; while(i<=a) { pow=pow*rem; i++; } return pow; } int main() { int i,digit=0,rem,sum=0; int a,b; cout<< "Enter a number to check armstrong number:"; cin>> i; a=i; while(a!=0) { a = a/10; digit++; } b=i; while(b!=0) { rem=b%10; sum=sum+power(rem,digit); b=b/10; } if(sum==i) cout << sum <<" Is ARMOSTRONG"<<endl; else cout << i<<" Is Not ARMOSTRONG" << endl; }
true
d41db507ef025decb269e5a5754dc9d78d91ca81
C++
aruna09/Competitive-Programming
/Codechef/DEM5.cpp
UTF-8
556
2.859375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ long int a=0, b=0, sum=0; cin>>a>>b; if((b-a+1)%2==0){ int temp = (b-a+1)/2; while(temp--){ sum = sum+a*a+b*b; a++; b--; } cout<<sum; } else{ int temp1= (b-a)/2; while(temp1--){ sum=sum+a*a+b*b; a++; b--; } sum=sum+((b-a)/2)+a*a; cout<<sum; } }
true