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
8e6fae2018a60720f4a5171834611b0fd2841e6b
C++
DeepLearnPhysics/larcv2
/larcv/app/ThreadIO/arxiv/KThread.h
UTF-8
963
3
3
[ "MIT" ]
permissive
/** * \file KThread.h * * \ingroup PyUtil * * \brief Class def header for a class KThread * * @author kazuhiro */ /** \addtogroup PyUtil @{*/ #ifndef KTHREAD_H #define KTHREAD_H #include <iostream> #include <thread> #include <vector> /** \class KThread User defined class KThread ... these comments are used to generate doxygen documentation! */ class KThread{ public: /// Default constructor KThread(){} /// Default destructor ~KThread(){ kill(); } std::vector<std::thread> _thread_v; std::vector<size_t> _sum_v; std::vector<bool> _die_v; inline void add(size_t id) { _sum_v[id] = 0; while(1) { usleep(1000000); _sum_v[id] += 1; if(_die_v[id]) break; } } inline size_t ctr(size_t id) const { return _sum_v.at(id); } void start(); inline void kill() { for(size_t i=0; i<_die_v.size(); ++i) _die_v[i] = true; usleep(1); } }; #endif /** @} */ // end of doxygen group
true
1fe05e018be2531d321661e04cf26c53b2ac1c82
C++
dcdolson/nsh-sf-devkit
/include/Demux/Demux.h
UTF-8
673
2.515625
3
[ "Apache-2.0" ]
permissive
#ifndef NSHDEV_DEMUX_H #define NSHDEV_DEMUX_H #include <Interfaces/Consumer.h> #include <memory> namespace nshdev { class Demux: public Consumer { public: Demux(); virtual void Receive(nshdev::PacketRef& packetRef, nshdev::NetInterface& receiveInterface) override; void SetConsumer(Consumer* consumer) { m_dataConsumer = consumer; } private: //! The consumer for OAM packets. //! The OAM consumer is constructed and owned by me. std::unique_ptr<Consumer> m_oamConsumer; //! Consumer for packets not matching OAM packets. //! The data consumer is owned by another. Consumer* m_dataConsumer; }; } #endif
true
899b5e8fb9a1225ce85b51dacb103ea90b59083f
C++
zvant/LeetCodeSolutions
/0088.merge_sorted_array_E.cpp
UTF-8
1,186
3.296875
3
[]
no_license
/** * https://leetcode.com/problems/merge-sorted-array/description/ * 2015/07 * 4 ms */ class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { if(m <= 0) { for(int idx = 0; idx < n; idx ++) nums1[idx] = nums2[idx]; return; } if(n <= 0) return; for(int idx = m - 1; idx >= 0; idx --) nums1[idx + n] = nums1[idx]; int idx1 = n; int idx2 = 0; int idx = 0; while(idx1 < m + n && idx2 < n) { while(idx1 < m + n && idx2 < n && nums1[idx1] <= nums2[idx2]) { nums1[idx] = nums1[idx1]; idx ++; idx1 ++; } while(idx1 < m + n && idx2 < n && nums2[idx2] <= nums1[idx1]) { nums1[idx] = nums2[idx2]; idx ++; idx2 ++; } } if(idx2 < n) { while(idx < m + n) { nums1[idx] = nums2[idx2]; idx ++; idx2 ++; } } } };
true
3cdd63bdd343d71b5aec276466406a47ffa437a3
C++
alexandraback/datacollection
/solutions_5744014401732608_0/C++/maiorpe/CF_A.cpp
UTF-8
1,806
2.578125
3
[]
no_license
//Шаблон #include <iostream> #include <algorithm> #include <vector> #include <string> #include <map> #include <set> #include <cstdio> #include <utility> #define ll long long #define MAXN 200100 using namespace std; struct point { ll t; ll r; ll c; ll x; point(ll a=0, ll b=0,ll cc=0,ll d=0){ t=a; r=b; c=cc; x=d; } }; double sqr(double a){return a*a;} int d[60][60]; int dp[3000]; int ans[60]; int main() { int n,t,b,m; cin>>t; for(int tt=0;tt<t;tt++){ cin>>b>>m; int aaa=(b*(b-1)/2); bool bb=false; cout<<"Case #"<<tt+1<<": "; for(int i=1;i<(1<<aaa);i++){ for(int j=0;j<aaa;j++) if((i & (1<<j))==0 ){ dp[j]=0; }else{ dp[j]=1; } int ind=0; for(int j=0;j<b-1;j++){ for(int k=j+1;k<b;k++){ d[j][k]=dp[ind]; ind++; } } for(int j=1;j<b;j++)ans[j]=0; ans[0]=1; for(int j=0;j<b-1;j++){ for(int k=j+1;k<b;k++) if(d[j][k]==1){ ans[k]+=ans[j]; } } if(ans[b-1]==m){ cout<<"POSSIBLE"<<endl; for(int j=0;j<b;j++){ for(int k=0;k<b;k++){ cout<<d[j][k]; } cout<<endl; } bb=true; break; } } if(!bb){ cout<<"IMPOSSIBLE"<<endl; } cout<<endl; } //cout<<fixed<<setprecision(16)<<ans<<endl; return 0; }
true
7713fb9408650591fa551e4613a39ffe8e363572
C++
HumanHyeon/Algorithm_Book
/archive/SeHyeon/21.01.17 Coding Practice No.34.cpp
UTF-8
837
2.953125
3
[]
no_license
#include <vector> #include <algorithm> using namespace std; bool cmp(const pair<double, int>& a, const pair<double, int>& b) { return a.first > b.first; } vector<int> solution(int N, vector<int> stages) { vector<pair<double, int>> table; vector<int> answer; int count[502] = { 0, }, reachPlayer = stages.size(); for (auto tmp : stages) count[tmp]++; for (int i = 1; i <= N; i++) { if (reachPlayer == 0) { table.push_back(make_pair(0, i)); continue; } double input = count[i] / (double)reachPlayer; reachPlayer -= count[i]; table.push_back(make_pair(input, i)); } stable_sort(table.begin(), table.end(), cmp); for(int i = 0; i < table.size(); i++) answer.push_back(table[i].second); return answer; } //계수 정렬에서 착안
true
406cabb12f6550ff7b22850e22ea86d7f23470ab
C++
LeverImmy/Codes
/比赛/学校/2019-11-9测试/source/PC43_HB-黄越/ball/ball.cpp
UTF-8
1,477
2.5625
3
[]
no_license
#pragma GCC optimize(2) #include <set> #include <cmath> #include <cstdio> #include <cctype> #include <algorithm> using namespace std; int read() { int x, c; while (!isdigit(c = getchar())); x = c - 48; while (isdigit(c = getchar())) x = x * 10 + c - 48; return x; } long long d[200010]; double r[200010]; struct v { int d; double r; bool operator<(const v& t) const { return d * d / r < t.d * t.d / t.r; } v(int a = 0, double b = 0): d(a), r(b) {} }; set<v> k; int main() { freopen("ball.in", "r", stdin); freopen("ball.out", "w", stdout); int n = read(); if (n <= 5000) { for (int i = 0; i < n; ++i) { d[i] = read(); r[i] = read(); if (!i) { printf("%.3f\n", r[i]); continue; } for (int j = 0; j < i; ++j) r[i] = min(r[i], (d[i] - d[j]) * (d[i] - d[j]) / 4.0 / r[j]); printf("%.3f\n", r[i]); } return 0; } for (int i = 0; i < n; ++i) { d[i] = read(); r[i] = read(); if (!i) { printf("%.3f\n", r[i]); k.insert(v(d[i], r[i])); continue; } if (i <= 200) { for (int j = 0; j < i; ++j) r[i] = min(r[i], (d[i] - d[j]) * (d[i] - d[j]) / 4.0 / r[j]); printf("%.3f\n", r[i]); k.insert(v(d[i], r[i])); continue; } int step = 100; for (set<v>::iterator it = k.begin(); step--; ++it) r[i] = min(r[i], (d[i] - it->d) * (d[i] - it->d) / 4.0 / it->r); for (int j = i - 100; j < i; ++j) r[i] = min(r[i], (d[i] - d[j]) * (d[i] - d[j]) / 4.0 / r[j]); k.insert(v(d[i], r[i])); printf("%.3f\n", r[i]); } return 0; }
true
ed4d8b00b4849186cca1b1eb7e6a3b6501ace588
C++
Alschn/Graphic-File-Converter
/graphic-file-converter/font.h
UTF-8
471
3
3
[]
no_license
#pragma once #include <memory> #include <vector> #include "image.h" class Font { public: static const int char_count = 36; const int letter_count = 26; const int digit_count = 10; static unsigned char alphabet[char_count]; std::vector<std::unique_ptr<Image>> char_images; Font(std::vector<std::unique_ptr<Image>> letters); void saveLetters(std::string& path); public: static void generateAlphabet(); static std::string extractFontName(std::string& path); };
true
b749dbaee5ae1b3f218705e1adc77e927c657dfe
C++
terman110/aduClock
/acCharSet.h
UTF-8
953
3.15625
3
[]
no_license
#ifndef __NUM_CHAR_H__ #define __NUM_CHAR_H__ enum enCharSet { Segment7 = 0, Cursive = 1, Binary = 2 }; class acCharSet { public: // Number of character sets static const int Count = 3; // Number width static const int NumberWidth = 4; // Character width static const int CharWidth = 8; // Selected character sets enCharSet CurrentSet; // Constructor: Load char set index from EEPROM acCharSet(); // Constructor: Set char set acCharSet(enCharSet selectedSet); // Select next char set int next(); // Read char set index from EEPROM void ReadFromEPROM(); // Write char set index to EEPROM void WriteToEPROM(); // Get byte byte get(int n, int y); // Get byte byte get(char c, int y); // Get 3x3 font bool array const bool* get_3x3(int n); // Get 3x3 font bool array const bool* get_3x3(char c); }; #endif // __NUM_CHAR_H__
true
fd919f550235ba0837b96e19647b8429aa5acb49
C++
Dsxv/competitveProgramming
/codeForces/div2/e75/D.cpp
UTF-8
1,186
2.703125
3
[]
no_license
#include <bits/stdc++.h> using namespace std ; #define int long long bool check(int s , int mid , pair<int,int>* a, int n){ vector<pair<int,int>> v ; int count = 0 ; for(int i = 0 ; i < n ; i++) { if(a[i].first >= mid) count++ , s -= a[i].first; if(a[i].second < mid) s -= a[i].first ; if(a[i].first < mid && a[i].second >= mid) v.push_back(a[i]) ; } int rem = (n+1)/2 - count ; // remaining elements >= mid if(rem < 0 ) rem = 0 ; if(v.size() < rem) return 0 ; for(int i = 0 ; i < v.size() ; i++){ if(i < v.size() - rem) s -= v[i].first ; else s -= mid ; // the elements greater than mid (rem elements) } return s >= 0 ; } int solve(pair<int,int>* a , int s , int n){ int lo = 0 , hi = s ; int ans = 0; while(lo <= hi){ int mid = (lo+hi)/2 ; if(check(s,mid,a,n)){ ans = max(ans,mid) ; lo = mid+1 ; }else{ hi = mid-1; } } return ans ; } int32_t main(){ int t ; cin >> t ; while(t--){ int n , s ; cin >> n >> s ; pair<int,int> a[n] ; for(int i = 0 ; i < n ; i++) cin >> a[i].first >> a[i].second ; sort(a,a+n); //cout << check(s,26,a,n) ; //cout << check(s,68,a,n) ; cout << solve(a,s,n) << '\n' ; } return 0 ; }
true
5c2ff09c53ca307040d3352edc5e5d857ce9a0cf
C++
DerrickPikachu/Leetcode
/submission/Kth_Largest_Element_in_a_Stream.cpp
UTF-8
1,434
3.53125
4
[]
no_license
class KthLargest { private: int k; vector<int> minheap; void insert(int val) { if (minheap.size() > k) { if (val > minheap[1]) { minheap[1] = val; for (int i=1; i*2<=minheap.size()-1;) { int j = i*2; if (j < minheap.size()-1) //check if minheap[j+1] is exist if (minheap[j] > minheap[j+1]) j++; if (minheap[i] < minheap[j]) break; else { swap(minheap[i], minheap[j]); i = j; } } } } else { minheap.push_back(val); for (int i=minheap.size()-1; i/2>0;) { if (minheap[i/2] > minheap[i]) { swap(minheap[i/2], minheap[i]); i /= 2; } else break; } } } public: KthLargest(int k, vector<int> nums) { this->k = k; minheap.push_back(0); for (int i=0; i<nums.size(); i++) insert(nums[i]); } int add(int val) { insert(val); return minheap[1]; } }; /** * Your KthLargest object will be instantiated and called as such: * KthLargest obj = new KthLargest(k, nums); * int param_1 = obj.add(val); */
true
578b0c4f881a36848d4f2a2b54ebaad83eadd809
C++
dudrl0944/-Intermediate-Ninja-Exam
/app_i(B Tree)/cpp파일/btree.cpp
UTF-8
10,667
2.796875
3
[]
no_license
//btree.tc #include "btnode.tc" #include "indbuff.tc" #include "btree.h" #include <iostream.h> const int MaxHeight = 5; template <class keyType> BTree<keyType>::BTree(int order, int keySize, int unique) : Buffer (1+2*order,sizeof(int)+order*keySize+order*sizeof(int)), BTreeFile (Buffer), Root (order) { Height = 1; Order = order; PoolSize = MaxHeight*2; Nodes = new BTNode * [PoolSize]; BTNode::InitBuffer(Buffer,order); Nodes[0] = &Root; } template <class keyType> BTree<keyType>::~BTree() { Close(); delete Nodes; } template <class keyType> int BTree<keyType>::Open (char * name, int mode) { int result; result = BTreeFile.Open(name, mode); if (!result) return result; // load root BTreeFile.Read(Root); Height = 1; // find height from BTreeFile! return 1; } template <class keyType> int BTree<keyType>::Create (char * name, int mode) { int result; result = BTreeFile.Create(name, mode); if (!result) return result; // append root node result = BTreeFile.Write(Root); Root.RecAddr=result; return result != -1; } template <class keyType> int BTree<keyType>::Close () { int result; result = BTreeFile.Rewind(); if (!result) return result; result = BTreeFile.Write(Root); if (result==-1) return 0; return BTreeFile.Close(); } template <class keyType> int BTree<keyType>::Insert (const keyType key, const int recAddr) { int result; int level = Height-1; int newLargest=0; keyType prevKey, largestKey; BTNode * thisNode, * newNode, * parentNode; thisNode = FindLeaf (key); //추가코드 시작 newNode = NewNode(); prevKey = NULL; //추가코드 마지막 // test for special case of new largest key in tree /* 원본소스 if (key > thisNode->LargestKey()) {newLargest = 1; prevKey=thisNode->LargestKey();} result = thisNode -> Insert (key, recAddr); */ //=========================<추가코드 시작>============================= if (Height <= 1){ if (recAddr == 0){ result = thisNode->Insert(key, recAddr); } } if (strcmp(key, thisNode->LargestKey())>0) //키값을 string타입으로 사용하기 때문에 //strcmp로 비교를 해야한다. { newLargest = 1; prevKey = thisNode->LargestKey(); } //=========================<추가코드 마지막>============================= result = thisNode->Insert(key, recAddr); // handle special case of new largest key in tree if (newLargest) for (int i = 0; i<Height-1; i++) { Nodes[i]->UpdateKey(prevKey,key); if (i>0) Store (Nodes[i]); } while (result==-1) // if overflow and not root { //remember the largest key largestKey=thisNode->LargestKey(); // split the node newNode = NewNode(); thisNode->Split(newNode); Store(thisNode); Store(newNode); level--; // go up to parent level if (level < 0) break; // insert newNode into parent of thisNode parentNode = Nodes[level]; result = parentNode->UpdateKey (largestKey,thisNode->LargestKey()); result = parentNode->Insert (newNode->LargestKey(),newNode->RecAddr); thisNode=parentNode; } Store(thisNode); if (level >= 0) return 1;// insert complete // else we just split the root int newAddr = BTreeFile.Append(Root); // put previous root into file // insert 2 keys in new root node Root.Keys[0]=thisNode->LargestKey(); Root.RecAddrs[0]=newAddr; Root.Keys[1]=newNode->LargestKey(); Root.RecAddrs[1]=newNode->RecAddr; Root.NumKeys=2; Height++; return 1; } /*원본소스 template <class keyType> int BTree<keyType>::Remove (const keyType key, const int recAddr) { // left for exercise return -1; } */ template <class keyType> int BTree<keyType>::Remove(const keyType key, const int recAddr) { int result; int level = Height - 1; // 레벨은 리프를 나타낸다. int merge_result = -1; int isRoot = 0; int temp_result = 0; int tem_rec = -1; // - tem_rec 는 merge 시 부모 노드의 언더플로우가 발생하면 처리하는 부분에서 사용. int upper_level = Height - 2; int a_temp; int isnei = -1; int isrnei = -1; int isLargest = 0; keyType prevKey, largestKey, nextKey; BTNode * thisNode, *newNode, *neighNode, *neighRNode; prevKey = NULL; largestKey = NULL; nextKey = NULL; neighNode = NULL; neighRNode = NULL; thisNode = FindLeaf(key); if (strcmp(key, thisNode->LargestKey()) == 0) // - 삭제하려는 키가 노드에서 가장 큰 키의 경우. { isLargest = 1; prevKey = key; } result = thisNode->Remove(key, recAddr); // - 노드 제거 largestKey = thisNode->LargestKey(); // - 제거후 가장 큰 키를 저장. if (isLargest == 1) // - 삭제한 키가 노드에서 가장 큰 키이면. { for (int i = 0; i<level; i++) { Nodes[i]->UpdateKey(prevKey, largestKey); // - 부모 노드들의 업데이트. if (i>0) Store(Nodes[i]); // - 이후 저장. } } while (result == -1) { if (upper_level < 0 && result == -1){ isRoot = 1; result = 0; break; } if (result == -1) // - 언더플로우 발생시. { prevKey = Nodes[level - 1]->Findprevkey(largestKey); if (strcmp(prevKey, largestKey) == 0) // - 노드 내에서 가장 작은 값을 merge 할 때. { nextKey = Nodes[level - 1]->Findnextkey(largestKey); neighRNode = FindLeaf(nextKey); a_temp = neighRNode->RMerge(thisNode); if (a_temp == 0) // - merge 한 노드가 오버플로우일때 { newNode = NewNode(); temp_result = neighNode->FSplit(newNode); neighRNode->RMerge(thisNode); for (int i = 0; i < level; i++) { Nodes[i]->UpdateKey(largestKey, neighRNode->LargestKey()); if (i>0) Store(Nodes[i]); } Store(neighRNode); Store(newNode); delete newNode; newNode = NULL; break; // - 부모 노드의 언더플로우가 발생하지 않을 상황. } if (a_temp == 1) // - merge 한 노드가 언더플로우일때. { result = Nodes[upper_level]->Remove(largestKey); Store(Nodes[upper_level]); for (int i = 0; i < level; i++) { Nodes[i]->UpdateKey(largestKey, neighRNode->LargestKey()); if (i>0) Store(Nodes[i]); } Store(neighRNode); } if (result == 1){ result = 0; break; } // - 부모 노드의 언더 플로우가 발생하지 않을 상황 if (result == -1){ upper_level--; level--; isrnei = 1; isnei = -1; continue; } } // - 노드 내에서 가장 작은 값을 merge 하는 부분은 여기까지. neighNode = FindLeaf(prevKey); // - 그 외의 경우. merge_result = neighNode->Merge(thisNode); if (merge_result == 0) // - merge한 노드가 오버플로우 일때. { newNode = NewNode(); temp_result = neighNode->FSplit(newNode); thisNode->RMerge(newNode); for (int i = 0; i<level; i++) { Nodes[i]->UpdateKey(prevKey, neighNode->LargestKey()); if (i>0) Store(Nodes[i]); } Store(neighNode); Store(thisNode); delete newNode; newNode = NULL; break; // - 부모 노드의 언더 플로우가 발생하지 않는 상황. } if (merge_result == 1) //- merge 한 노드가 오버플로우가 아닐때. { result = Nodes[upper_level]->Remove(largestKey); Store(Nodes[upper_level]); for (int i = 0; i<level; i++) { Nodes[i]->UpdateKey(prevKey, neighNode->LargestKey()); if (i>0) Store(Nodes[i]); } Store(neighNode); } if (result == 1) { result = 0; break; } upper_level--; level--; isnei = 1; isrnei = -1; } } if (result == 1) { Store(thisNode); } if (isRoot == 1) { if (Root.NumKeys != 1) { Store(thisNode); return 1; } if (isnei == 1) { Root.CopyNode(neighNode); } if (isrnei == 1) { Root.CopyNode(neighRNode); } Height--; } return 1; } template <class keyType> int BTree<keyType>::Search (const keyType key, const int recAddr) { BTNode * leafNode; leafNode = FindLeaf (key); return leafNode -> Search (key, recAddr); } template <class keyType> void BTree<keyType>::Print (ostream & stream) { stream << "BTree of height "<<Height<<" is "<<endl; Root.Print(stream); if (Height>1) for (int i = 0; i<Root.numKeys(); i++) { Print(stream, Root.RecAddrs[i], 2); } stream <<"end of BTree"<<endl; } template <class keyType> void BTree<keyType>::Print (ostream & stream, int nodeAddr, int level) { BTNode * thisNode = Fetch(nodeAddr); stream<<"Node at level "<<level<<" address "<<nodeAddr<<' '; thisNode -> Print(stream); if (Height>level) { level++; for (int i = 0; i<thisNode->numKeys(); i++) { Print(stream, thisNode->RecAddrs[i], level); } stream <<"end of level "<<level<<endl; } } //===========================<추가코드 시작>================================= template <class keyType> void BTree<keyType>::TPrint(ostream &stream) { stream << "BTree of height " << Height << " is " << std::endl << std::endl; int Tlevel = 2; Root.TPrint(stream); stream << std::endl; if (Height > 1) { for (int i = 0; i < Root.numKeys(); i++) { stream << std::endl; TPrint(stream, Root.RecAddrs[i], Tlevel); } } if (Height == 1) { return; } stream << endl; } template <class keyType> void BTree<keyType>::TPrint(std::ostream &stream, int nodeAddr, int level) { int btem_level = level; BTNode* thisNode = Fetch(nodeAddr); for (int i = 0; i < level; ++i) { stream << '\t'; } thisNode->TPrint(stream); stream << std::endl; if (Height > btem_level) { stream << std::endl; btem_level++; for (int i = 0; i < thisNode->numKeys(); i++) { TPrint(stream, thisNode->RecAddrs[i], btem_level); } } delete thisNode; thisNode = NULL; } //=============================<추가코드 마지막>============================= template <class keyType> BTreeNode<keyType> * BTree<keyType>::FindLeaf (const keyType key) // load a branch into memory down to the leaf with key { int recAddr, level; for (level = 1; level < Height; level++) { recAddr = Nodes[level-1]->Search(key,-1,0);//inexact search Nodes[level]=Fetch(recAddr); } return Nodes[level-1]; } template <class keyType> BTreeNode<keyType> * BTree<keyType>::NewNode () {// create a fresh node, insert into tree and set RecAddr member BTNode * newNode = new BTNode(Order); int recAddr = BTreeFile . Append(*newNode); newNode -> RecAddr = recAddr; return newNode; } template <class keyType> BTreeNode<keyType> * BTree<keyType>::Fetch(const int recaddr) {// load this node from File into a new BTreeNode int result; BTNode * newNode = new BTNode(Order); result = BTreeFile.Read (*newNode, recaddr); if (result == -1) return NULL; newNode -> RecAddr = result; return newNode; } template <class keyType> int BTree<keyType>::Store (BTreeNode<keyType> * thisNode) { return BTreeFile.Write(*thisNode, thisNode->RecAddr); }
true
a1d9afcd89ad9bd39737fac9671d9001a4dfb17e
C++
ivamshky/Practice-Codes
/[GfG]SearchSortedRotated.cpp
UTF-8
897
2.90625
3
[]
no_license
#include<iostream> #include<climits> #include<cstdio> #include<cmath> #include<algorithm> #include<vector> #include<string> #include<list> #define FORSC(A,n1,n2) for(int i=n1;i<n2;i++){cin>>A[i];} #define FOROUT(A,n1,n2) for(int i=n1;i<n2;i++){cout<<A[i]<<" ";} using namespace std; int searchKey(vector<int>& A, int key, int l, int r) { if(l>r) return -1; int mid = (l+r)/2; if(A[mid]==key) return mid; //Sorted if(A[l]<=A[mid]){ if(key >= A[l] && key <= A[mid]){ return searchKey(A,key,l,mid-1); } return searchKey(A,key,mid+1,r); } if(key>=A[mid] && key <=A[r]){ return searchKey(A,key,mid+1,r); } return searchKey(A,key,l,mid-1); } int main() { int t; cin>>t; while(t--){ int n; cin>>n; vector<int> A(n); FORSC(A,0,n); int key; cin>>key; cout<<searchKey(A,key,0,n-1)<<endl; } return 0; }
true
d91579e4e9c3e75d3723bfc72f1620e64cd21e31
C++
x-fer/xfer-natpro
/2015/zi/irena/irena.cpp
UTF-8
1,395
2.703125
3
[]
no_license
#include <cstdio> #include <iostream> #include <vector> #include <string> #include <cstring> #include <queue> using namespace std; int n; vector<string> V; int dist[2002][2002]; const int dx[] = {0, 1, 0, -1}; const int dy[] = {1, 0, -1, 0}; long long bfs(int px, int py, int kx, int ky){ queue<int> Q; Q.push(px); Q.push(py); memset(dist, -1, sizeof(dist)); dist[px][py] = 0; while (!Q.empty()){ int cx = Q.front(); Q.pop(); int cy = Q.front(); Q.pop(); for (int d = 0; d < 4; ++d){ int nx = cx + dx[d]; int ny = cy + dy[d]; if (nx < 0 || nx >=n || ny < 0 || ny >= n || V[nx][ny] == '*' || dist[nx][ny] != -1)continue; dist[nx][ny] = dist[cx][cy] + 1; Q.push(nx); Q.push(ny); } } int d = dist[kx][ky]; long long x = d; return x * (x + 1) / 2; } int main(void){ cin >> n; for (int i = 0; i < n; ++i){ string x; cin >> x; V.push_back(x); } int px, py; int kx, ky; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if (V[i][j] == 'I') {px = i; py = j;} else if (V[i][j] == 'F') {kx = i; ky = j;} cout << bfs(px, py, kx, ky) << endl; return 0; }
true
dd38211e410ba18c2a3193824785d8898c27c8cc
C++
lufinkey/WallpaperCycler
/src/wallcycler/parse/WallpaperSource.h
UTF-8
821
2.734375
3
[]
no_license
#pragma once #include <string> #include <vector> #include <functional> namespace wallcycler { class Wallpaper { public: Wallpaper() {} Wallpaper(const std::string& source_id, const std::string& wall_id, const std::string& url) : source_id(source_id), wall_id(source_id), url(url) {} std::string source_id; std::string wall_id; std::string url; }; class WallpaperSource { public: typedef struct SearchData { std::vector<Wallpaper> results; unsigned int totalpages; std::string error; } SearchData; typedef std::function<void(const SearchData& searchData)> SearchFinishCallback; virtual void search(const std::string& query, unsigned long resultsPerPage, unsigned long pagenum, SearchFinishCallback onfinish) const = 0; virtual std::string getSourceID() const = 0; }; }
true
7f701527d8ae0a96be399e815922dfd62b310145
C++
hero1s/server_frame
/src/utility/basic_functions.cpp
GB18030
1,012
2.953125
3
[]
no_license
#include "utility/basic_functions.h" #include <assert.h> #include <memory> #include <stdlib.h> /*************************************************************/ // 鰴λ־ bool SetBitFlag(uint32_t* szFlag, int32_t len, int32_t pos) { if (pos >= (len * 32)) { return false; } int iIdx = pos / 32; uint32_t bFlag = 0x01 << (31 - (pos % 32)); szFlag[iIdx] |= bFlag; return true; } bool UnsetBitFlag(uint32_t* szFlag, int32_t len, int32_t pos) { if (pos >= (len * 32)) { return false; } int iIdx = pos / 32; uint32_t bFlag = 0x01 << (31 - (pos % 32)); szFlag[iIdx] &= ~bFlag; return true; } bool IsSetBitFlag(uint32_t* szFlag, int32_t len, int32_t pos) { if (pos >= (len * 32)) { return false; } int iIdx = pos / 32; uint32_t bFlag = 0x01 << (31 - (pos % 32)); return (szFlag[iIdx] & bFlag) > 0; } bool ClearBitFlag(uint32_t* szFlag, int32_t len) { memset(szFlag, 0, len * 4); return true; }
true
aa5cc53c80c15c6123d6238b4f45713a82205d88
C++
jimin-hash/HistoryQueue
/JiminPark_Project1/Patient.hpp
UTF-8
546
2.671875
3
[]
no_license
#pragma once #include "InjuryList.hpp" #include "PriorityMap.hpp" #include <iostream> #include <string> class Patient { private: string patientName_; public: InjuryList* list = new InjuryList(); int priority_ = 0; int position_ = 1; Patient* prev_ = nullptr; Patient* next_ = nullptr; Patient(); ~Patient(); string getPatientName(); void setPatientName(string name); void addtoList(string injuryName); InjuryList* getInjuryList(); void setInjuryList(InjuryList* i); int calcPriority(PriorityMap* pm); void selectInjuryList(); };
true
2e1e0d564be2a3f0e1c773f3ca518a6258de6930
C++
rwbot/sandbox444
/utils_pcl/include/utils_pcl/CloudToImage.hpp
UTF-8
996
2.8125
3
[]
no_license
/** Class for publishing an image extracted from a point cloud on a topic. Author: Ankush Gupta */ #ifndef _CLOUD_TO_IMAGE_HPP_ #define _CLOUD_TO_IMAGE_HPP_ #include <ros/ros.h> #include <utils_pcl/CloudImageComm.hpp> #include <sensor_msgs/Image.h> class CloudToImage : CloudImageComm { /** The name of the topic on which the image is to be advertised.*/ std::string _img_out_topic; /** The image publisher. */ ros::Publisher _image_pub; /** This is called whenever a new point-cloud is recieved. */ void process() { this->publish_image(); } void publish_image() { _image_pub.publish(_img_ros); } public: CloudToImage(ros::NodeHandle * nh_ptr, std::string image_out_topic="/cloud_to_image/image_rect_color", std::string cloud_topic="/camera/depth_registered/points") : CloudImageComm(nh_ptr, cloud_topic), _img_out_topic(image_out_topic) { _image_pub = _nh_ptr->advertise<sensor_msgs::Image>(_img_out_topic, 1); } }; #endif
true
fa161e723c6a9ae9c53e94b63e604bb50f277d21
C++
chhanganivarun/DS
/lnklst/8.cpp
UTF-8
870
2.9375
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; #include"ll.h" int main() { int n; LinkedList ll; cout<<"Enter number of integers in the linked list:"; cin>>n; if(n>0) cout<<"Enter "<<n<<" integers:"; for(int i=0;i<n;i++) { int x; cin>>x; ll.push_back(x); } cout<<"\nCurrently the Linked List is:"<<endl; ll.display(); if(ll.head==NULL) { cout<<"Empty List!!\nAborting!!\n"; return -1; } int a[n]; for(int i=0;i<n;i++) a[i]=0; int minlist=ll.min(); for(Node *s=ll.head;s;s=s->next) { if(a[s->data-minlist]==0) a[s->data-minlist]=1; } for(Node *s=ll.head;s;s=s->next) { if(a[s->data-minlist]==1||a[s->data-minlist]==0) a[s->data-minlist]=2; else if(a[s->data-minlist]==2) { for(int i=0;i<n;i++) { if(a[i]==0) { s->data=minlist+i; a[i]=2; break; } } } } ll.display(); return 0; }
true
d705befb39d8ba2f4c4b9ae286d4838a0d47f9f6
C++
cursedtoxi/hurby-1
/main.cpp
UTF-8
1,974
2.546875
3
[]
no_license
/************************************************************************************* This file is the entry point of the Hurby Toy application: - Starts debug terminal - Starts Hurby toy - Enable test cases if needed *************************************************************************************/ #include "mbed.h" #include "main.h" // Debug terminal serial interface Serial pc(USBTX, USBRX); #if defined(ENABLE_SERIAL_BRIDGE_RECORD) || defined(ENABLE_SERIAL_BRIDGE_DOWNLOAD) Serial bridge(p28,p27); DigitalOut vrst(p20); #endif static void CheckTests(void); /* Starts application ****************************************************************/ int main() { // checks if some test is enabled CheckTests(); // creates hurby instance new Hurby(&pc); // runs forever for(;;){ } } /* Checks tests to be done ********************************************************/ static void CheckTests(void){ /* Enable logger?? */ #if defined(ENABLE_SERIAL_LOG) #warning "ENABLE_SERIAL_LOG activado"; pc.baud(115200); /* Enable bridge mode for training?? */ #elif defined(ENABLE_SERIAL_BRIDGE_RECORD) #warning "ENABLE_SERIAL_BRIDGE_RECORD activado"; pc.baud(9600); bridge.baud(9600); /* Enable bridge mode for download?? */ #elif defined(ENABLE_SERIAL_BRIDGE_DOWNLOAD) #warning "ENABLE_SERIAL_BRIDGE_DOWNLOAD activado"; pc.baud(115200); bridge.baud(115200); #endif /* Execute bridge mode?? */ #if defined(ENABLE_SERIAL_BRIDGE_RECORD) || defined(ENABLE_SERIAL_BRIDGE_DOWNLOAD) volatile char c; vrst.write(0); wait(0.1); vrst.write(1); wait(0.1); while(1) { if(pc.readable()) { c = pc.getc(); bridge.putc(c); } if(bridge.readable()) { c = bridge.getc(); pc.putc(c); } } #endif /* Else, Continue with some tests... */ /* Test fuzzy inference system */ #if defined(ENABLE_FUZZY_TEST) TestFuzzy(); #endif }
true
5013fd9c89862428da7215ddffc703d752480a89
C++
vishalpandya1990/LeetCodeProblems
/longest-common-substring.cpp
UTF-8
1,090
3.515625
4
[]
no_license
/* Dynamic Programming solution to find length of the longest common substring */ #include<iostream> #include<string.h> using namespace std; int LCSubStr(char *X, char *Y, int m, int n) { if(m == 0 || n == 0) return 0; int dp[m][n]; dp[0][0] = X[0] == Y[0] ? 1 : 0; for(int col = 1; col < n; col++) { dp[0][col] = 0; if(X[0] == Y[col]) dp[0][col] = 1; } for(int row = 1; row < m; row++) { dp[row][0] = 0; if(X[row] == Y[0]) dp[row][0] = 1; } int ans = 0; for(int row = 1; row < m; row++) { for(int col = 1; col < n; col++) { if(X[row] == Y[col]) dp[row][col] = 1 + dp[row-1][col-1]; else dp[row][col] = 0; ans = max(ans, dp[row][col]); } } return ans; } /* Driver program to test above function */ int main() { char X[] = "OldSite:GeeksforGeeks.org"; char Y[] = "NewSite:GeeksQuiz.com"; int m = strlen(X); int n = strlen(Y); cout << "Length of Longest Common Substring is " << LCSubStr(X, Y, m, n); return 0; }
true
8048fabbe177d87123ef40a8a7ec7db7f0952ce5
C++
LightingZZH/WD_C-
/20190613/network2/InetAddr.h
UTF-8
474
2.734375
3
[]
no_license
#ifndef __INETADDR_H__ #define __INETADDR_H__ #include <arpa/inet.h> #include <string> using std::string; class InetAddr { public: explicit InetAddr(unsigned short port); InetAddr(const string & ip, unsigned short port); InetAddr(const struct sockaddr_in & addr); string getIp() const; unsigned short getPort() const; struct sockaddr_in * getInetAddrPtr() {return &_addr;} ~InetAddr() {} private: struct sockaddr_in _addr; }; #endif
true
f19ae74c7552d60865cb23e4d07027fdf066aea8
C++
qingqiuleng/sort
/Sort.h
GB18030
6,531
3.0625
3
[]
no_license
#pragma once #include<iostream> #include<assert.h> using namespace std; //void InsertSort(int* parr,int size)//() //{ // assert(parr); // for (int i = 1; i < size; i++) // { // for (int j = i; j >= 0;j--) // { // if (parr[j]<parr[j-1]) // { // swap(parr[j], parr[j-1]); // } // } // } //} //void ShellSort(int* parr,int size)//ϣ //{ // assert(parr); // int gap = size / 2; // for (; gap > 0; gap /= 2) // { // for (int j = 0; j < size; j += gap) // { // if (parr[j]>parr[gap + j]) // { // // } // } // } //} //void ShellSort(int a[], int n) //{ // int i, j, gap; // // for (gap = n / 2; gap > 0; gap /= 2) // // for (i = 0; i < gap; i++) //ֱӲ // { // for (j = i + gap; j < n; j += gap) // if (a[j] < a[j - gap]) // { // int temp = a[j]; // int k = j - gap; // while (k >= 0 && a[k] > temp) // { // a[k + gap] = a[k]; // k -= gap; // } // a[k + gap] = temp; // } // } //} //void SelectSort(int* parr,int size)//ѡ //{ // assert(parr); // for (int i = 0; i < size; i++) // { // int min = parr[i]; // for (int j = i + 1; j < size; j++) // { // if (parr[j]<min) // { // swap(min, parr[j]); // } // } // if (min!=parr[i]) // { // swap(min, parr[i]); // } // } //} // //void SelectSort(int* parr, int size)//ѡŻ //{ // assert(parr); // int left; // int right; // for (left = 0,right = size - 1; left < right; left++, right--) // { // int min = parr[left]; // int max = parr[right]; // // for (int i = left+1; i <= right; i++)//ҳСԪ // { // if (min>parr[i]) // { // swap(min, parr[i]); // } // else if (parr[i] > max) // { // swap(max, parr[i]); // } // } // // if (min != parr[left]) // { // swap(min, parr[left]); // if (max == parr[left]) // { // max = min; // } // } // if (max != parr[right]) // { // swap(max, parr[right]); // if (min == parr[right]) // { // min = max; // } // // } // } //} //void _AdjustDown(int* parr,int parant,int size)//µ //{ // int child =2*parant+1 ; // // while (child<size) // { // if (parr[child] < parr[child + 1] && child + 1 < size) // { // child++; // } // if (parr[parant] < parr[child]) // { // swap(parr[parant], parr[child]); // parant = child; // child = 2 * parant + 1; // } // else // { // break; // } // } //} // //void HeapSort(int* parr,int size)// //{ // for (int i = (size - 1) / 2; i >= 0; i--) // { // _AdjustDown(parr, i, size); // } // // for (int i = 0; i < size; i++) // { // swap(parr[0], parr[size - 1 - i]); // _AdjustDown(parr, 0, size-1-i); // } //} //void QuickSort(int* parr,int left,int right)// //{ // // assert(parr); // if (left >= right) // { // return; // } // int key = parr[left]; // int i = left; // int j = right; // // while (i<j) // { // while (i < j&&key <= parr[j]) // { // j--; // } // parr[i] = parr[j]; // // while (i < j&&key >= parr[i]) // { // i++; // } // parr[j] = parr[i]; // } // // parr[i] = key; // QuickSort(parr, left, i - 1);//ݹ // QuickSort(parr, i + 1, right);//ݹ //} // //void BubbleSort(int* parr,int size)//ð //{ // assert(parr); // for (int i = 0; i < size-1; i++)//ѭn-1ΣÿѭһΣðݵһֵ // { // for (int j = 0; j < size - i - 1; j++) // { // if (parr[j]>parr[j + 1])//ԪرȽϣϴĽұarr[j+1] // { // swap(parr[j], parr[j + 1]); // } // } // } //} // //void BubbleSort(int* parr,int size)//ðŻ //{ // assert(parr); // bool flag = false; // // for (int i = 0; i < size; i++) // { // flag = false; // for (int j = 0; j < size - i - 1; j++) // { // if (parr[j]>parr[j + 1]) // { // swap(parr[j], parr[j + 1]); // flag = true; // } // } // if (flag == false)//һѭȽϽûзÿԪضȽϹˣ˵Ѿ // { // break;//Ѿѭ // } // } //} // //void Merge(int* parr,int* tmp,int start,int end,int mid ) //{ // int i = start; // int j = mid + 1; // int k = start; // // while (i < mid&&j<end) // { // if (parr[i] < parr[j]) // { // tmp[k++] = parr[i++]; // } // else // { // tmp[k++] = parr[j++]; // } // } // // while (i <= mid) // { // tmp[k++] = parr[i++]; // } // while (j <= end) // { // tmp[k++] = parr[j++]; // } // // for (i = 0; i <= end; i++) // { // parr[i] = tmp[i]; // } //} // //void MergeSort(int* parr,int* tmp, int start,int end)//鲢 //{ // if (start < end) // { // int midindex = (start + end) / 2; // MergeSort(parr, tmp, start, midindex); // MergeSort(parr, tmp, midindex + 1, end); // Merge(parr, tmp, start, end, midindex); // } //} //void CountingSort(int* parr,int size)// //{ // assert(parr); // int* count = new int[20]; // for (int i = 0; i < 20; i++) // { // count[i] = 0; // } // for (int i = 0; i <= size; i++) // { // count[parr[i]]++; // } // // for (int i = 0; i < 20; i++) // { // if (count[i] == 1) // { // cout << i<< " "; // } // } // delete[] count; //} int GetDigit(int* parr,int size)//ȡλ { int max = parr[0]; for (int i = 1; i <= size;i++) { if (max < parr[i]) { max = parr[i]; } } int digit = 0; while (max >= 10) { digit++; max %= 10; } digit++; return digit; } void RadixSort(int* parr,int size)// { assert(parr); int digit = GetDigit(parr, size); int* count = new int[10]; int* tmp = new int[size]; int radix = 1; for (int i = 0; i < digit; i++)//digit { for (int i = 0; i < 10; i++)//ֱӵַȽ0 { count[i] = 0; } for (int i = 0; i < size; i++)//ͳÿͰֵĸ { int d = (parr[i]/radix) % 10; count[d]++; } for (int i = 1; i < 10;i++)//ͳƳtmpұ߽ { count[i] = count[i - 1] + count[i]; } for (int i = size-1; i >=0;i--)//countͰһõtmp,Ӻǰɨ豣֤ȶ { int d = (parr[i]/radix) % 10; tmp[count[d]-1] = parr[i]; count[d]--; } for (int i = 0; i < size; i++)//tmpһοparr { parr[i] = tmp[i]; } radix *= 10;//ưһλ } delete []count; delete []tmp; }
true
bb5be26b1e3f87e974b6c0d1930770874f15a93d
C++
mihneadinik/CrackingTheCodingInterview
/2 - LinkedLists/2.5/25.cpp
UTF-8
3,079
3.1875
3
[]
no_license
#include <iostream> #include "/home/mihnea_dnk/Desktop/cracking/2 - LinkedLists/LinkedList.h" Node<int> *add(LinkedList<int> &nr1, LinkedList<int> &nr2) { int rest = 0, sum = 0; Node<int> *c1, *c2; c1 = nr1.getHead(); c2 = nr2.getHead(); // cream rezultatul drept o insiruire de noduri Node<int> *curr = nullptr; // ultimul nod adaugat Node<int> *first = nullptr; // primul nod din lista // cat timp putem aduna cifra cu cifra while (c1 != nullptr && c2 != nullptr) { // facem suma sum = c1->data + c2->data; // vedem daca avem rest de adunat if (rest) { sum += 1; rest = 0; } // mergem la urmatoarele cifre c1 = c1->next; c2 = c2->next; // vedem daca retinem rest if (sum / 10 != 0) { sum %= 10; rest = 1; } // pun suma intr un nod Node<int> *d = new Node<int> (sum); // verific daca e primul nod din lista if (curr != nullptr) { curr->next = d; curr = d; } else { curr = d; } if (first == nullptr) first = d; } // acelasi algoritm pana termin cifrele numerelor while (c1 != nullptr) { sum = c1->data; if (rest) { sum += 1; rest = 0; } c1 = c1->next; if (sum / 10 != 0) { sum %= 10; rest = 1; } Node<int> *d = new Node<int> (sum); if (curr != nullptr) { curr->next = d; curr = d; } else { curr = d; } if (first == nullptr) first = d; } while (c2 != nullptr) { sum = c2->data; if (rest) { sum += 1; rest = 0; } c2 = c2->next; if (sum / 10 != 0) { sum %= 10; rest = 1; } Node<int> *d = new Node<int> (sum); if (curr != nullptr) { curr->next = d; curr = d; } else { curr = d; } if (first == nullptr) first = d; } if (rest) { Node<int> *d = new Node<int> (1); curr->next = d; } return first; } int main() { int nrr1, x, nrr2; LinkedList <int> nr1; LinkedList <int> nr2; // citim numerele (sunt scrise invers) std::cin >> nrr1 >> nrr2; for (int i = 0; i < nrr1; i++) { std::cin >> x; nr1.addNode(i, x); } for (int i = 0; i < nrr2; i++) { std::cin >> x; nr2.addNode(i, x); } Node<int> *p1, *p2; p1 = add(nr1, nr2); p2 = p1; // afisam rezultatul while(p1 != nullptr) { std::cout << p1->data << " "; p1 = p1->next; } std::cout << std::endl; // eliberam memoria if (p2 != nullptr) p1 = p2->next; else p1 = nullptr; while (p1 != nullptr) { delete p2; p2 = p1; p1 = p1->next; } delete p2; return 0; }
true
3c29a43d68b1eccc2bd6b09319e86e5a0ec9d25c
C++
ttbond/srcfind
/agctNode.cpp
UTF-8
460
2.515625
3
[]
no_license
// // Created by ttbond on 18-10-17. // #ifndef SRCFIND_AGCTNODE_CPP #define SRCFIND_AGCTNODE_CPP #include "agctNode.h" agctNode::agctNode(){ num=0; for(int i=0;i<4;i++){ son[i]=NULL; } } inline agctNode *agctNode::enterSon(int id){ if(id<0||id>3){ printf("wrong Id in agctNode::enterSon(int id) value:%d\n",id); exit(-1); } if(son[id]==NULL){ son[id]=new agctNode(); } return son[id]; } #endif
true
eaca22f2d0359116bfe514de1c05026e9868d30a
C++
gaurav2497/ExpressionEngine-AndroidModule
/ExpressionsEngine/ExpressionModule/jni/Source/graph.h
UTF-8
4,179
3.359375
3
[]
no_license
#ifndef GRAPH_H #define GRAPH_H #include <iostream> #include <stack> #include <list> #include <vector> #include <string> #include "errors.h" using namespace std; using Cycles = vector<vector<string>>; void printCycles(Cycles &cycles) { for (int i = 0; i < cycles.size(); i++) { for (int j = 0; j < cycles[i].size(); j++) { cout << cycles[i][j] << "->"; } cout << cycles[i][0] << "\n"; } } enum State { NOT_VISITED = 1, IN_STACK, VISITED }; class Graph { std::vector<string> vertices; int V; list<int> *adj; // pointer to the vector consisting the edges. void dfs(int v, bool visited[], stack<int> &_stack); void processDFStree(State dfs_state[], stack<int> &dfs_stack, Cycles &cycles); vector<string> sprintCycle(stack<int> &dfs_stack, int v); public: Graph(); Graph(vector<string> &vertices); void addEdge(int v, int w); // from v to w void sort(vector<string> &sorted); void findCycles(Cycles &cycles); void print(); }; Graph::Graph() { this->vertices = {}; V = vertices.size(); adj = new list<int>[vertices.size()]; // declaring the holding array } Graph::Graph(vector<string> &vertices) { this->vertices = vertices; V = vertices.size(); adj = new list<int>[vertices.size()]; // declaring the holding array } void Graph::addEdge(int v, int w) { adj[v].push_back(w); } void Graph::dfs(int v, bool visited[], stack<int> &_stack) { visited[v] = true; list<int>::iterator j; for (j = adj[v].begin(); j != adj[v].end(); ++j) { if (!visited[*j]) { dfs(*j, visited, _stack); } } // once all adjacend nodes are visited _stack.push(v); } void Graph::sort(vector<string> &sorted) { stack<int> _stack; bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; for (int i = 0; i < V; i++) { if (visited[i] == false) { dfs(i, visited, _stack); } } while (!_stack.empty()) { sorted.push_back(vertices[_stack.top()]); _stack.pop(); } } vector<string> Graph::sprintCycle(stack<int> &dfs_stack, int v) { stack<int> temp; vector<string> cycle; temp.push(dfs_stack.top()); dfs_stack.pop(); while (temp.top() != v) { temp.push(dfs_stack.top()); dfs_stack.pop(); } while (!temp.empty()) { cycle.push_back(vertices[temp.top()]); dfs_stack.push(temp.top()); temp.pop(); } return cycle; } void Graph::processDFStree(State dfs_state[], stack<int> &dfs_stack, Cycles &cycles) { int v = dfs_stack.top(); list<int>::iterator j; for (j = adj[v].begin(); j != adj[v].end(); ++j) { if (dfs_state[*j] == IN_STACK) { // this is a cycle cycles.push_back(sprintCycle(dfs_stack, *j)); } else if (dfs_state[*j] == NOT_VISITED) { // explore this dfs_stack.push(*j); dfs_state[*j] = IN_STACK; processDFStree(dfs_state, dfs_stack, cycles); } } //we have printed all the cycles dfs_state[dfs_stack.top()] = VISITED; dfs_stack.pop(); } void Graph::findCycles(Cycles &cycles) { stack<int> dfs_stack; State *dfs_state = new State[V]; // the array to track the state of a vertice in DFS; for (int i = 0; i < V; i++) dfs_state[i] = NOT_VISITED; for (int i = 0; i < V; i++) { if (dfs_state[i] == NOT_VISITED) { dfs_stack.empty(); dfs_stack.push(i); dfs_state[i] = IN_STACK; processDFStree(dfs_state, dfs_stack, cycles); } } } void Graph::print() { int i = 0, j; for (i = 0; i < V; i++) { j = 0; cout << vertices[i] << "->"; if (adj[i].size() > 0) { // print the list list<int>::iterator j; for (j = adj[i].begin(); j != adj[i].end(); ++j) { cout << vertices[*j] << "->"; } } cout << endl; } } #endif
true
e283d3eebccc943ffb350c49b3e425740ab81b93
C++
maxbarnard99/Product-Shipping-Manager-
/src/shipping_item.h
UTF-8
1,337
3.234375
3
[]
no_license
#ifndef SHIPPING_ITEM_H #define SHIPPING_ITEM_H #include <string> struct Address{ std::string name; std::string street_address; std::string city; std::string state; std::string zip; }; class ShippingItem{ protected: struct Address address_; double weight_; double length_; bool delivered_; public: static const double kMaxWeight; static const double kMaxSize; static const double kMinSize; //constructor && destructor ShippingItem(); ShippingItem(struct Address address, double weight, double length); ~ShippingItem(){} //getters struct Address address() const {return address_;} double weight() const {return weight_;} double length() const {return length_;} bool delivered() const {return delivered_;} //setters void set_address(struct Address address); void set_weight(double weight); virtual void set_length(double length); void set_delivered(bool delivered); //other methods void MarkDelivered(); virtual double Volume() const = 0; //setting these to zero creates a pure virtual virtual void Display(std::ostream &out) const = 0; //class. }; #endif
true
5063d26653d0f6e241df4282460e7d392e9a279c
C++
forensictool/coex
/sources/plugins/TaskGetDictionary/src/coexDb.cpp
UTF-8
1,632
2.84375
3
[]
no_license
#include "coexDb.h" #include <iostream> CoexDB::CoexDB(){} //----------------------------------------------------------------------- CoexDB::CoexDB(const QString& filename) { m_bOpen = this->connect(filename); } //----------------------------------------------------------------------- CoexDB::~CoexDB(){} //----------------------------------------------------------------------- bool CoexDB::connect(const QString& filename) { m_sdb = QSqlDatabase::addDatabase("QSQLITE"); m_sdb.setDatabaseName(filename); bool bOpen = m_sdb.open(); if (bOpen) { QSqlQuery pragma_query(m_sdb); pragma_query.exec("PRAGMA auto_vacuum = 1"); QSqlQuery query("SELECT name FROM sqlite_master WHERE type='table' AND name='dictionary';"); if (!query.next()) { // table not exists try create it QSqlQuery query_create(m_sdb); QString strQuery = " CREATE TABLE dictionary (" " id INTEGER PRIMARY KEY AUTOINCREMENT, " " word varchar(50) NOT NULL)"; query_create.exec(strQuery); } } return bOpen; } //----------------------------------------------------------------------- void CoexDB::disconnect() { return; } //----------------------------------------------------------------------- bool CoexDB::insert(const QString& data) { if(!this->m_bOpen) return(false); QSqlQuery query(m_sdb); query.prepare("INSERT INTO dictionary(id, word) VALUES(NULL, :data)"); query.bindValue(":data", QVariant(data)); if(!query.exec()) { std::cout << "Error: " << query.lastError().text().toStdString() << std::endl; return(false); } return(true); }
true
0adb136185f22f57cf4899894fc25b8d7bb1cdc8
C++
joshuaGlass808/VMatrix
/vmatrix.h
UTF-8
944
2.875
3
[ "MIT" ]
permissive
#ifndef VMATRIX_H #define VMATRIX_H #include <vector> namespace VMatrix { typedef std::vector<std::vector<int>> MatrixVector; class Matrix { int colCount, rowCount; MatrixVector matrix; public: Matrix(const unsigned int, const unsigned int); Matrix(MatrixVector&, int, int); ~Matrix() { return; } bool fillMatrixWithRandNums(const unsigned int, const unsigned int); void printMatrix(); void setNewMatrix(MatrixVector const & mVec) { this->matrix = mVec; } int getColumnCount() const { return this->colCount; } int getRowCount() const { return this->rowCount; } MatrixVector getRawMatrixVector() const { return this->matrix; } friend Matrix operator + (Matrix const&, Matrix const&); friend Matrix operator - (Matrix const&, Matrix const&); friend Matrix operator * (Matrix const&, Matrix const&); }; } #endif
true
122b2580a43fd54eea8964162f7b1252df4e9e82
C++
smatskevich/MIPT-DIHT-Course1-2016
/HaffmanCoder/Source.cpp
WINDOWS-1251
551
2.6875
3
[]
no_license
#include <string> #include "Huffman.h" // original void Encode( IInputStream& original, IOutputStream& compressed ) { byte fromFirst = 0; while( original.Read( fromFirst ) ) { compressed.Write( fromFirst ); } } // void Decode( IInputStream& compressed, IOutputStream& original ) { byte fromFirst = 0; while( compressed.Read( fromFirst ) ) { original.Write( fromFirst ); } }
true
ab966327974eaf51f89d95f6dcd3660fa1fee085
C++
boruoyihao/algorithms
/leetCode/413_Arithmetic_Slices.cpp
UTF-8
2,287
3.84375
4
[]
no_license
/** *A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, these are arithmetic sequence: 1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9 The following sequence is not arithmetic. 1, 1, 2, 5, 7 A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N. A slice (P, Q) of array A is called arithmetic if the sequence: A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q. The function should return the number of arithmetic slices in the array A. Example: A = [1, 2, 3, 4] return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself. * * */ #include "common.h" #if 0 //O(N*N) class Solution { public: int numberOfArithmeticSlices(vector<int>& A) { if(A.size()<3){ return 0; } int count=0; for(int i=0;i<A.size()-2;i++){ int diff=A[i+1]-A[i]; for(int j=i+2;j<A.size();j++){ if(A[j]-A[j-1]==diff){ count++; }else{ break; } } } return count; } }; #endif #if 0 class Solution { public: int numberOfArithmeticSlices(vector<int>& A) { if(A.size()<3){ return 0; } int diff=A[1]-A[0]; int count=0; int mem=0; for(int i=2;i<A.size();i++){ if(diff==A[i]-A[i-1]){ mem++; }else{ count+=compute(mem); mem=0; diff=A[i]-A[i-1]; } } return count+compute(mem); } int compute(int n){ int count=0; for(int i=1;i<=n;i++){ count+=i; } return count; } }; #endif //O(N*N) time complexity O(1) Space complexity class Solution { public: int numberOfArithmeticSlices(vector<int>& A) { if(A.size()<3){ return 0; } int diff=A[1]-A[0]; int count=0; int mem=0; for(int i=2;i<A.size();i++){ if(diff==A[i]-A[i-1]){ mem++; count+=mem; }else{ mem=0; diff=A[i]-A[i-1]; } } return count; } }; int main(){ int array[]={1,2,3,4,5,7,9,11,13}; vector<int>A(array,array+9); Solution *s =new Solution; cout<<s->numberOfArithmeticSlices(A)<<endl; return 0; }
true
714ff8006e5d4106cf3cc3a9ddb9ced98cb39026
C++
saaamxzy/autocomplete
/Edge.hpp
UTF-8
752
3.21875
3
[]
no_license
/* * File name: Edge.hpp * Name: Yunlu Huang * Student ID: A91008991 * Partner Name: Zhengyuan Xu * Partner ID: A99076427 * Date: Aug 30, 2016 */ #ifndef EDGE_HPP #define EDGE_HPP #include <string> #include "Vertex.hpp" class Vertex; /* * This class is the directed edge of the graph. It represents an edge from * actor1 to actor2. It contains a name of the movie, both actors, the year of * the movie, and the weight of the edge. * It has 2 ptrs points to the first actor and the second one */ class Edge { public: std::string moviename; int year; int weight; Vertex* self; Vertex* other; Edge(std::string moviename, int year, bool weighted, Vertex* actor1, Vertex* actor2); //constructor }; #endif
true
29951180472a0a1b4c49342d4ddbd0f3c51ad39a
C++
victory118/sketchbook
/farmaid_ros/diff_steer.h
UTF-8
3,756
2.96875
3
[]
no_license
#ifndef DIFF_STEER_H #define DIFF_STEER_H namespace Farmaid { struct DiffDriveWheelVel { // struct to hold left and right wheel velocity variables float left; // left wheel velocity [m/s] float right;// right wheel velocity [m/s] }; class DiffSteer { public: DiffSteer(float wheelbase, float wheel_radius) : wheelbase_(wheelbase), wheel_radius_(wheel_radius), max_vel_(0), max_ang_vel_(0), ensure_ang_vel_(true) { } /** * @brief Converts unicycle velocity commands to motor velocity commands * @param vel: commanded forward velocity in m/s * ang_vel: commanded angular velocity in m/s */ virtual void Drive(float vel, float ang_vel) = 0; DiffDriveWheelVel UniToDiff(float vel, float ang_vel) { // This function ensures that ang_vel is respected as best as possible // by scaling vel. // vel - desired robot linear velocity [m/s] // ang_vel - desired robot angular velocity [rad/s] DiffDriveWheelVel diff_drive_wheel_vel = {0.0, 0.0}; if (!ensure_ang_vel_) { diff_drive_wheel_vel.right = (vel + ang_vel * wheelbase_ / 2.0); diff_drive_wheel_vel.left = (vel - ang_vel* wheelbase_ / 2.0); return diff_drive_wheel_vel; } // 1. Limit vel and ang_vel to be within the possible range float lim_ang_vel = max(min(ang_vel, max_ang_vel_), -max_ang_vel_); float lim_vel = max(min(vel, max_vel_), -max_vel_); // 2. Compute left and right wheel velocities required to achieve limited vel and ang_vel float lim_right_wheel_vel = (lim_vel + lim_ang_vel * wheelbase_ / 2.0); float lim_left_wheel_vel = (lim_vel - lim_ang_vel* wheelbase_ / 2.0); // 3. Find max and min of the limited wheel velocities float max_lim_wheel_vel = max(lim_right_wheel_vel, lim_left_wheel_vel); float min_lim_wheel_vel = min(lim_right_wheel_vel, lim_left_wheel_vel); // 4. Shift limited wheel velocities if they exceed the maximum wheel velocity if (max_lim_wheel_vel > max_vel_) { diff_drive_wheel_vel.right = lim_right_wheel_vel - (max_lim_wheel_vel - max_vel_); diff_drive_wheel_vel.left = lim_left_wheel_vel - (max_lim_wheel_vel - max_vel_); } else if (min_lim_wheel_vel < -max_vel_) { diff_drive_wheel_vel.right = lim_right_wheel_vel - (min_lim_wheel_vel + max_vel_); diff_drive_wheel_vel.left = lim_left_wheel_vel - (min_lim_wheel_vel + max_vel_); } else { diff_drive_wheel_vel.right = lim_right_wheel_vel; diff_drive_wheel_vel.left = lim_left_wheel_vel; } return diff_drive_wheel_vel; } float get_max_vel() { return max_vel_; } float get_max_ang_vel() { return max_ang_vel_; } bool get_ensure_ang_vel() { return ensure_ang_vel_; } void set_max_vel(float max_vel) { max_vel_ = max_vel; } void set_max_ang_vel(float max_ang_vel) { max_ang_vel_ = max_ang_vel; } void set_ensure_ang_vel(bool ensure_ang_vel) { ensure_ang_vel_ = ensure_ang_vel; } protected: float wheelbase_; float wheel_radius_; float max_vel_; // maximum forward velocity of robot with no rotation [m/s] float max_ang_vel_; // maximum angular velocity of robot with pure rotation [rad/s] bool ensure_ang_vel_; }; }; #endif
true
da1f89a91cf0bccc6632624391845d1834d0d2d9
C++
Andydiaz12/Estructura-de-Datos-con-Muratalla
/Ejercicios de parciales/3 parcial/ch03_10_24500468_240416.cpp
ISO-8859-1
1,358
3.34375
3
[]
no_license
/* Jos Andrs Daz Escobar 24 de Abril del 2016 10. BUSQUEDA BINARIA: 1) Inicializa un arreglo de flotantes de tamao 10 con cero. 2) Llena ste arreglo con datos que te d el usuario. 3) Posteriormente debers ordenar el arreglo utilizando quicksort. 4) Muestra el men: 1) buscar dato 2) salir. 5) Realizars la bsqueda binaria del dato dado y se indicar si NO se encontr y SI se encontr en que posicin se encuentra. 6) PERO irs imprimiendo en pantalla cada seccin en la que se est realizando la bsqueda. Y al final imprimirs cuantas comparaciones hizo para encontrarlo.*/ #include <stdio.h> #include <cstdlib> #include "libreria.h" int menu(){ int x; printf("1.\tBuscar dato\n2\tSalir.\n"); do{ printf("Ingrese la opcion deseada:\t"); scanf("%d", &x); if(x<1 || x>2){ printf("Opcion del menu invalida\n"); system("PAUSE"); system("CLS"); } }while(x<1 || x>2); return x; } float dato(){ float x; printf("Ingrese el dato a buscar:\t"); scanf("%f", &x); return x; } int main(){ float arr[10], DATO; int MENU; inicializar_arreglo(&arr); llenado_arreglo(&arr); quicksort(&arr, 0, 9); imprimir(&arr); do{ MENU=menu(); switch (MENU){ case 1: DATO=dato(); busquedabinaria(&arr, DATO); break; } }while(MENU != 2); system("PAUSE"); return 0; }
true
b3b49412867cf4b53978623f023cbea03a5bdcbc
C++
chanfool21/Competitive-Coding
/summer_love/Practice Codes/HackerRank/next_palin.cpp
UTF-8
630
3.1875
3
[]
no_license
#include<iostream> using namespace std; int palin(int ); int main() { int t; cin>>t; int a[t]; int i; for(i = 0; i < t; i++) { cin>>a[i]; } int j = 0; for(i = 0; i < t; i++) { j = a[i] + 1; while(j > a[i]) { if(palin(j) == 1) { cout<<j<<endl; break; } j++; } } return 0; } int palin(int a) { int t; t = a; int rev = 0; while(a != 0) { rev = (rev * 10) + (a % 10); a = a/10; } if(rev == t) { return 1; } return 0; }
true
ecba438b093ad31127fbc766dd3ce4137fed4295
C++
baskeboler/caraoke
/src/app.hh
UTF-8
1,554
2.6875
3
[]
no_license
#if !defined(APP_H) #define APP_H #include "globals.hh" #include "scene.hh" #include "song_info.hh" #include "sound_controller.hh" #include <SDL2/SDL.h> #include <SDL2/SDL_mixer.h> #include <SDL2/SDL_ttf.h> #include <functional> #include <iostream> #include <map> #include <memory> #include <vector> using std::cout, std::endl; using std::map; using std::shared_ptr; using std::vector; class App { private: static shared_ptr<App> _instance; // Screen dimension constants int SCREEN_WIDTH; int SCREEN_HEIGHT; SDL_Window *gWindow; SDL_Renderer *gRenderer; // The surface contained by the window SDL_Surface *gScreenSurface; vector<shared_ptr<EventHandler>> handlers; shared_ptr<Scene> current_scene; shared_ptr<SoundController> sound_controller; vector<SongInfo> songs; public: App(); public: static shared_ptr<App> get_instance(); ~App(); bool init(); int get_screen_width() const; int get_screen_height() const; SDL_Window *get_window() const; SDL_Renderer *get_renderer() const; SDL_Surface *get_screen_surface() const; void set_screen_width(int arg); void set_screen_height(int arg); void set_window(SDL_Window *arg); void set_renderer(SDL_Renderer *arg); void set_screen_surface(SDL_Surface *arg); void register_handler(shared_ptr<EventHandler> handler); void unregister_handler(shared_ptr<EventHandler> handler); void handle_event(SDL_Event &e); shared_ptr<Scene> get_current_scene() { return current_scene; } void set_current_scene(shared_ptr<Scene> scene); }; #endif // APP_H
true
196bd9a84c963c0d4a5911b26128255282a63219
C++
venkatrn/monolithic_pr2_planner
/monolithic_pr2_planner/include/monolithic_pr2_planner/TransitionData.h
UTF-8
1,947
2.71875
3
[]
no_license
#pragma once #include <monolithic_pr2_planner/StateReps/GraphState.h> #include <monolithic_pr2_planner/StateReps/RobotState.h> #include <monolithic_pr2_planner/StateReps/ContBaseState.h> #include <vector> namespace monolithic_pr2_planner { typedef std::vector<std::vector<double> > IntermSteps; /*! \brief Contains information generated during a state expansion. * * When a state is expanded, it usually has unique information about the * expansion, namely the intermediate states associated with the particular * motion primitive. This class wraps it all up so it can be easily used for * collision checking and path reconstruction by other objects. */ class TransitionData { public: TransitionData(){}; void successor_id(int id){ m_successor_id = id; }; int successor_id(){ return m_successor_id; }; void motion_type(int mt){ m_motion_type = mt; }; int motion_type() const { return m_motion_type; }; void interm_robot_steps(std::vector<RobotState> steps){ m_robot_interm_steps = steps; }; std::vector<RobotState> interm_robot_steps() const { return m_robot_interm_steps; }; void cont_base_interm_steps(std::vector<ContBaseState> steps){ m_cont_base_interm_steps = steps; }; std::vector<ContBaseState> cont_base_interm_steps() const { return m_cont_base_interm_steps; }; void cost(int cost){ m_cost = cost; }; int cost() const { return m_cost; }; private: int m_successor_id; int m_cost; // I'm providing two kinds of intermediate steps because I'm not // sure which one will be more useful... IntermSteps m_graph_interm_steps; std::vector<RobotState> m_robot_interm_steps; std::vector<ContBaseState> m_cont_base_interm_steps; int m_motion_type; }; }
true
5b45bdc7e692b86a419cb3148c68aae9565cad8f
C++
webturing/2018ACMEnforcement
/lec01-string/algorithm.cpp
UTF-8
531
2.9375
3
[ "MIT" ]
permissive
#include<iostream> #include<algorithm> //class string public:vector using namespace std; char foo(char&c){ if(isupper(c))return tolower(c); else if(islower(c))return toupper(c); return c; } int main() { int a=3,b=4; cout<<max(a,b)<<endl;//max/min cout<<__gcd(a,b)<<endl; swap(a,b); string s="abasfdFJKDJK"; // for(int i=0;i<s.size();i++) // s[i]=tolower(s[i]); // cout<<s<<endl; //transform(s.begin(),s.end(),s.begin(),::toupper); transform(s.begin(),s.end(),s.begin(),foo); cout<<s<<endl; }
true
2021dc1f448ef18831d5145019ddab962ac7d07c
C++
g-harinen/csis352
/examples/fileio.cpp
UTF-8
526
3
3
[]
no_license
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { int num; int sum=0; int count=0; ifstream in; ofstream out; in.open("data2"); in >> num; while (!in.eof()) { cerr << "read " << num << endl; sum += num; count++; in >> num; } in.close(); out.open("result"); cerr << "sum = " << sum << endl; cerr << "count = " << count << endl; out << "the average is " << static_cast<double>(sum)/count << endl; out.close(); return 0; }
true
d348ba390bafd774b4a2aa44a818f7de82b085fc
C++
swithers19/RRLS-Arduino-Library
/lib/serialInterface/serialInterface.cpp
UTF-8
4,446
2.921875
3
[]
no_license
#include "serialInterface.h" //Initialise the controller with room for 15 peripherals serialController::serialController(SoftwareSerial* ms) { this->cnt = 0; this->payloadArr = new peripheral*[15]; this->ddStore = 0; dev = 12; lastMillis = millis(); this->mySerial = ms; } //Process to add a peripheral, and add it to the index void serialController::addPeripheral(peripheral* periph) { this->payloadArr[(this->cnt)] = periph; this->cnt++; } //Keeps track of peripheral amount int serialController::getCnt() { mySerial->print(this->cnt); return this->cnt; } //Checks serial and whether we need to send or recieve data void serialController::checkSerial() { static bool debugStart = false; while (mySerial->available()) { int inChar = mySerial->read(); // get the new byte: if (inChar == '/') { this->sendPeriph(); //Send configuration data } else if (inChar == '&' && debugStart == false) { //Start debug control process debugStart = true; ddStore = new debugData[getCnt()]; //Creating data store for debugging data Serial.println("Setting debugStart"); } else if (debugStart == true) { debugStart = this->debugPeriphs(inChar); } } } //Read in debug values bool serialController::debugPeriphs(int inVal) { static int i = 0; static int periCtr = 0; bool debugStatus = true; bool errorFlag = false; if (inVal == DEBUG_TERM) { //errorFlag = peripheral list complete debugStatus = false; if (errorFlag == false) { Serial.println("Debug complete!"); debugMode(periCtr); //set debug parameters } periCtr = 0; i = 0; duration[0] = duration[1] = 0; } else { if (i < 2) { this->duration[i] = inVal; Serial.print("duration byte "); Serial.println(inVal, DEC); i++; } else if (i >= 2) { if ((i % 2 == 0) && (inVal != DEBUG_TERM)) { errorFlag = validateID(&ddStore[periCtr], inVal); //Error validation and Serial.println(errorFlag); i++; } else if((i % 2 == 1) && (inVal != DEBUG_TERM)) { ddStore[periCtr].mode = inVal; Serial.print("Mode: "); Serial.println(inVal, DEC); periCtr++; //Increment number of peripherals i++; } } if (errorFlag) { debugStatus = false; errorFlag = false; i = 0; periCtr = 0; } } return debugStatus; } //Ensures ID is valid, spits error if not correct bool serialController::validateID(debugData* ddStore,int inVal) { bool ret = true; for(int i = 0; i<getCnt(); i++) { if(inVal == this->payloadArr[i]->fetchID()) { ddStore->devPtr = this->payloadArr[i]; ddStore->id = inVal; Serial.print("ID is "); Serial.println(ddStore->id); ret = false; } } return ret; } //Function in charge of manipulating peripherals in debug void serialController::debugMode(int debugCnt) { unsigned long start = millis(); unsigned int dur = (duration[0]<<8) +duration[1]; mySerial->print('~++'); while (dur > (int)(millis() - start)) { //Set each peripheral to desired mode for (int i = 0; i<debugCnt; i++) { ddStore[i].devPtr->debugAction(ddStore[i].mode); } //this->sendPeriph(); } //Reset back to normal operation for (int i = 0; i<debugCnt; i++) { ddStore[i].devPtr->debugAction(ddStore[i].devPtr->fetchMode()); } } //Returns a peripheral pointer based on the index provided peripheral* serialController::retPeriph(int cnt) { return this->payloadArr[cnt]; } //Sends to serial all the data of each peripheral void serialController::sendPeriph() { mySerial->print('^'); mySerial->write(cnt); if ((millis() - (this->lastMillis)) > 50 ) { for (int i = 0; i < cnt; i++) { payloadArr[i]->writePeriph(mySerial); if (i < (cnt - 1)) { //mySerial->print('\n'); } } mySerial->print("++"); } this->lastMillis = millis(); }
true
8d6ef1d012def10b25dd1ded39f5425df52f8af8
C++
LBNL-UCB-STI/routing-framework
/RawData/VisumExtractPoi.cc
UTF-8
3,098
2.96875
3
[ "MIT", "GPL-3.0-only" ]
permissive
#include <cassert> #include <cstdlib> #include <fstream> #include <iostream> #include <map> #include <stdexcept> #include <string> #include <csv.h> #include "DataStructures/Geometry/CoordinateTransformation.h" #include "Tools/CommandLine/CommandLineParser.h" #include "Tools/StringHelpers.h" inline void printUsage() { std::cout << "Usage: VisumExtractPoi -crs <file> -i <file> -o <file>\n" "Extracts points of interest (e.g. schools and hospitals) from given Visum files.\n" " -crs <file> coordinate reference system used in the Visum network files\n" " -i <file> directory that contains the Visum network files\n" " -o <file> place output in <file>\n" " -help display this help and exit\n"; } int main(int argc, char* argv[]) { try { CommandLineParser clp(argc, argv); if (clp.isSet("help")) { printUsage(); return EXIT_SUCCESS; } const auto crs = clp.getValue<int>("crs"); const auto visumPathName = clp.getValue<std::string>("i"); auto outputFileName = clp.getValue<std::string>("o"); if (!endsWith(outputFileName, ".csv")) outputFileName += ".csv"; CoordinateTransformation trans(crs, CoordinateTransformation::WGS_84); std::ofstream outputFile(outputFileName); if (!outputFile.good()) throw std::invalid_argument("file cannot be opened -- '" + outputFileName + "'"); outputFile << std::fixed; outputFile << "# Source: " << visumPathName << "\n"; outputFile << "category,longitude,latitude\n"; std::cout << "Reading POI categories..." << std::flush; std::map<int, std::string> poiCategories; int id; char* name; using VisumFileReader = io::CSVReader<2, io::trim_chars<>, io::no_quote_escape<';'>>; VisumFileReader poiCatFileReader(visumPathName + "/POIKATEGORIE.csv"); poiCatFileReader.read_header(io::ignore_extra_column, "NR", "NAME"); while (poiCatFileReader.read_row(id, name)) { assert(*name != '\0'); assert(poiCategories.find(id) == poiCategories.end()); poiCategories[id] = name; } std::cout << " done.\n"; for (const auto& cat : poiCategories) { const auto poiFileName = visumPathName + "/POIOFCAT_" + std::to_string(cat.first) + ".csv"; std::ifstream poiFile(poiFileName); if (poiFile.good()) { std::cout << "Extracting POIs of category " << cat.second << "..." << std::flush; double easting, northing; double lng, lat; VisumFileReader poiFileReader(poiFileName, poiFile); poiFileReader.read_header(io::ignore_extra_column, "XKOORD", "YKOORD"); while (poiFileReader.read_row(easting, northing)) { trans.forward(easting, northing, lng, lat); outputFile << cat.second << ',' << lng << ',' << lat << '\n'; } std::cout << " done.\n"; } } } catch (std::exception& e) { std::cerr << argv[0] << ": " << e.what() << '\n'; std::cerr << "Try '" << argv[0] <<" -help' for more information.\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
true
5731a187437cbe739c4bb8372bb1d193d131a87a
C++
ZebraCakes/amp_ray
/code/Chapter1/chapter1.cpp
UTF-8
887
2.890625
3
[]
no_license
#include <stdio.h> #include "..\amp_lib\amp_math.h" void main(int ArgumentCount, char **Arguments) { int Width = 200; int Height = 100; FILE *outputFile; if (ArgumentCount > 1) { outputFile = fopen(Arguments[1], "w"); } else { outputFile = fopen("chapter1_output.ppm", "w"); } fprintf(outputFile, "P3\n%d %d\n255\n", Width, Height); for (i32 y = Height - 1; y >= 0; --y) { for (int x = 0; x < Width; ++x) { r32 Red = (r32)x / (r32)Width; r32 Green = (r32)y / (r32)Height; r32 Blue = 0.2; int RedInt = (i32)(255.9*Red); int GreenInt = (i32)(255.9*Green); int BlueInt = (i32)(255.9*Blue); fprintf(outputFile, "%d %d %d\n", RedInt, GreenInt, BlueInt); } } }
true
cdf2c3e10171df47fdcd71f3bb42414b9b7fa06f
C++
divyashah98/projects
/computerArch.Work/A6/BranchPred.cpp
UTF-8
3,158
3.21875
3
[]
no_license
#include <iostream> #include <iomanip> #include <cstdint> #include "BranchPred.h" using namespace std; BranchPred::BranchPred() { cout << "Branch Predictor Entries: " << BPRED_SIZE << endl; /* You should have some code that goes here */ predictions = 0; pred_takens = 0; mispredictions = 0; mispred_direction = 0; mispred_target = 0; for (int i = 0; i < BPRED_SIZE; i++) { predictionTable[i].stateNum = 0; predictionTable[i].targetPC = 0; } } /* You should add functions here */ bool BranchPred::predict(uint32_t pc) { predictions++; int index = (pc >> 2) % BPRED_SIZE; if (predictionTable[index].stateNum >= 2) { pred_takens++; return true; // Predict Taken } else { return false; // Predict Not Taken } } bool BranchPred::update(uint32_t pc, uint32_t targetPC, bool prediction, bool actualTaken) { int index = (pc >> 2) % BPRED_SIZE; // index for predictionTable if (prediction == true && actualTaken == true) { // if predicted taken, and actually taken if(predictionTable[index].stateNum < 3) { // increment saturation counter if not already at 3 predictionTable[index].stateNum++; // increment state if not at max } if(predictionTable[index].targetPC != targetPC) { mispredictions++; mispred_target++; // mispredicted branch target address predictionTable[index].targetPC = targetPC; // taken, so overwrite tPC return true; // send true to notify for a flush } } if(prediction == false && actualTaken == false) { // predicted not-taken correctly, decrement stateNum if(predictionTable[index].stateNum > 0) { // if not at mininmum, decrease predictionTable[index].stateNum--; } } //Direction mispredictions if(prediction == true && actualTaken == false) { // predicted taken, branch was not taken if(predictionTable[index].stateNum > 0) { predictionTable[index].stateNum--; } mispred_direction++; // predicted wrong (taken vs not-taken) mispredictions++; } if(prediction == false && actualTaken == true) { // predicted not taken, branch was taken if(predictionTable[index].stateNum < 3 ) { // increment saturation counter if not already at 1111 predictionTable[index].stateNum++; } mispred_direction++; mispredictions++; predictionTable[index].targetPC = targetPC; // update targetPC } return false; // if reached, we dont need to flush } void BranchPred::printFinalStats() { int correct = predictions - mispredictions; int not_takens = predictions - pred_takens; cout << setprecision(1); cout << "Branches predicted: " << predictions << endl; cout << " Pred T: " << pred_takens << " (" << (100.0 * pred_takens/predictions) << "%)" << endl; cout << " Pred NT: " << not_takens << endl; cout << "Mispredictions: " << mispredictions << " (" << (100.0 * mispredictions/predictions) << "%)" << endl; cout << " Mispredicted direction: " << mispred_direction << endl; cout << " Mispredicted target: " << mispred_target << endl; cout << "Predictor accuracy: " << (100.0 * correct/predictions) << "%" << endl; }
true
281b33bca0be732b9388414523dc6732d10651f6
C++
namworkmc/OOP_Project_FashionShopManagementSystem
/Fashion Shop Management System/Person_Customer_Staff_Seller_Security.h
UTF-8
5,481
2.578125
3
[]
no_license
#ifndef _PERSON_CUSTOMER_STAFF_SELLER_SECURITY_ #define _PERSON_CUSTOMER_STAFF_SELLER_SECURITY_ #include <iostream> #include <string> #include <vector> #include <exception> #include <Date.h> #include <ExcelFstream.h> #include <Tokenizer.h> #include <FakeAddress.h> #include <FakeAddress.h> #include <FakeName.h> #include <FakeBirthday.h> #include <FakeVnTel.h> using namespace std; class Person { protected: string _name; Date _date_of_birth; string _phone_number; Address _address; public: Person(string name = "", Date dob= Date (0,0,0), string phone = "", Address add= Address("", "", "", "", "")) { _name = name; _date_of_birth = dob; _phone_number = phone; _address = add; }; void setName(string _name); void setDoB(Date dob); void setPhoneNumber(string phone); void setAddress(Address add); string getName(); Date getDoB(); string getPhoneNumber(); Address getAddress(); //////// Friend ////////// friend class ExcelFstream; friend class ExcelIfstream; friend class ExcelOfstream; }; class Customer : public Person { private: string _customer_id; public: Customer(string name = "", Date dob = Date(0, 0, 0), string phone = "", Address add = Address("", "", "", "", ""), string customer_id = ""): Person(name, dob, phone, add) { _customer_id = customer_id; }; void setCustomerID(string customer_id); void setCustomerInfo(string name, Date dob, string phone, Address add, string customer_id); string getCustomerID(); Customer getCustomerInfo(); string toString(); void showCustomerInfo(); void parse(string line); //// Friend //// friend class ExcelFstream; friend class ExcelIfstream; friend class ExcelOfstream; }; class Staff : public Person { protected: string _staff_id; double _base_salary = 0; void setStaff(string name, Date dob, string phone, Address add, string staff_id, double base_salary); void setStaffID(string staff_id); void setBaseSalary(double salary); public: Staff(string name = "", Date dob = Date(0, 0, 0), string phone = "", Address add = Address("", "", "", "", ""), string staff_id = "", double base_salary = 0) : Person(name, dob, phone, add) { _staff_id = staff_id; _base_salary = base_salary; } public: virtual void setNewStaff(); string getStaffID(); void setLastID(vector <Staff*> staffs); virtual void setStaffInfo(vector<string> Tok) = 0; virtual double getSalary() = 0; virtual void showStaffInfo() = 0; virtual string toString() = 0; static void saveStaffList(vector<Staff*> staffs, string directory = "../Fashion Shop Management System/Database/Staff.csv"); static void openStaffList(vector <Staff*>& staffs, string directory = "../Fashion Shop Management System/Database/Staff.csv"); static bool login(vector <Staff*> staffs); static void sort(vector <Staff*>& staffs, string sort_by); static Staff* search(vector<Staff*>staffs, string for_what = "Seller"); void deleteStaff(vector <Staff*>& staffs); private: string last_ID; string getNewID(); public: bool operator==(const Staff*& staff); public: //// Friend // friend class ExcelFstream; friend class ExcelIfstream; friend class ExcelOfstream; }; class Security : public Staff { public: Security(string name = "", Date dob = Date(0, 0, 0), string phone = "", Address add = Address("", "", "", "", ""), string staff_id = "", double base_salary = 0) : Staff(name, dob, phone, add, staff_id, base_salary) {}; public: void setNewStaff(); void setSecurity(string name, Date dob, string phone, Address add, string staff_id, double base_salary); void setStaffInfo(vector<string> Tok); double getSalary(); void addSecurity(vector<Staff*>& staff, Staff* secu); string toString(); void showStaffInfo(); void parse(string line); /// Friend /// friend class ExcelFstream; friend class ExcelIfstream; friend class ExcelOfstream; }; class Seller : public Staff { private: double _real_salary; double _commission; // tiền hoa hồng int _sales; // doanh số bán hàng public: Seller(string name = "", Date dob = Date(0, 0, 0), string phone = "", Address add = Address("", "", "", "", ""), string staff_id = "", double base_salary = 0,double commission=0, int goods_sale =0,double real_salary=0) : Staff(name, dob, phone, add, staff_id, base_salary) { _commission = commission; _sales = goods_sale; _real_salary = real_salary; } private: void parse(string line); string toString(); private: void setCommission(); public: void setNewStaff(); void setSeller(string name, Date dob, string phone, Address add, string staff_id, double base_salary, double comission, int goodsale, double realsalary); void setBaseSalary(double base_salary); void setSales(int sales = 0); void setRealSalary(double real_salary); void setStaffInfo(vector<string> Tok); double getSalary(); double getCommission(); int getSales(); void updateSales(const int& sales); void updateSalary(); public: void addSeller(vector<Staff*>& staff, Staff* sell); void showStaffInfo(); static void bestSellerOfMonth(vector <Staff*> staffs); //// FRIEND //// friend class ExcelFstream; friend class ExcelIfstream; friend class ExcelOfstream; }; class StaffException : public exception { private: string _mess; public: StaffException(string mess) { _mess = mess; } public: const char* what() const throw() { return _mess.c_str(); } }; #endif // !_PERSON_CUSTOMER_STAFF_SELLER_SECURITY_
true
e3aeaf69c9ded9b06cc2ea48809cf00d32c65181
C++
devgoel186/DSA-And-CP-Concepts
/Coding Ninjas C++/Graphs/Graphs.cpp
UTF-8
1,836
3.671875
4
[]
no_license
#include <iostream> #include <vector> #include <queue> using namespace std; // Depth-First-Search Approach (DFS) void printDFS(int **edges, int n, int sv, bool *visited) { cout << sv << " "; visited[sv] = true; for (int i = 0; i < n; i++) { if (i == sv) continue; if (edges[sv][i] == 1) { if (visited[i]) continue; printDFS(edges, n, i, visited); } } } // Breadth-First-Search (BFS) void printBFS(int **edges, int n, int sv, bool *visited) { queue<int> pending; pending.push(sv); visited[sv] = true; while (!pending.empty()) { int currentVertex = pending.front(); pending.pop(); cout << currentVertex << " "; for (int i = 0; i < n; i++) { if (edges[currentVertex][i] == 1 && !visited[i]) { pending.push(i); visited[i] = true; } } } } int main() { int n; int e; cin >> n >> e; // Creating adjacency matrix int **edges = new int *[n]; for (int i = 0; i < n; i++) { edges[i] = new int[n]; for (int j = 0; j < n; j++) { edges[i][j] = 0; } } for (int i = 0; i < e; i++) { int fv, sv; cin >> fv >> sv; edges[fv][sv] = 1; edges[sv][fv] = 1; } bool *visited = new bool[n]; // Initialize all vissited array elements by false for (int i = 0; i < n; i++) { visited[i] = false; } cout << "DFS Traversal : "; printDFS(edges, n, 0, visited); // Initialize all vissited array elements by false for (int i = 0; i < n; i++) { visited[i] = false; } cout << "\nBFS Traversal : "; printBFS(edges, n, 0, visited); }
true
02274e021cc6392a8085b5343ae763a9bd5ddbc3
C++
neotron/PathFinder
/examples/cities.cpp
UTF-8
2,860
3.96875
4
[ "BSD-2-Clause" ]
permissive
/* USAGE run the executable with 3 arguments as follow : output_exe filename city1 city2 with filename the path to a text file containing lines in the following format : CityA CityB distance to represent a link between CityA and CityB and city1 / city2 being the start and goal example for France.txt : PathFinder.exe France.txt Lille Toulouse */ #include "../src/PathFinder.h" #include "../src/Dijkstra.h" #include <iostream> #include <string> #include <fstream> #include <vector> #include <map> /* Create our own class deriving DijkstraNode. This is needed for applying Dijkstra's Algorithm to our cities. We can though implement other functionnalities we need, that's why I am giving them a name for example. */ class City : public DijkstraNode { public: City(const std::string& name = "Unknown") { this->name = name; } std::string getName() const { return name; } void setName(const std::string& name) { this->name = name; } private: std::string name; }; int main(int argc, char** argv) { std::map<std::string, City> cities; // Again, it requires 3 arguments + the program name = 4 if(argc != 4) { std::cerr << "Invalid number of arguments provided (got " << argc << ", expected 4), type to exit." << std::endl; std::getchar(); return 0; } std::string start(argv[2]), end(argv[3]); std::fstream file(argv[1], std::ios::in); if(!file) { std::cerr << "Could not open file '" << argv[1] << "', type to exit." << std::endl; std::getchar(); return 0; } std::string line; std::string city1, city2; float distance; // We'll read the file and take the links between cities described in each line while(!file.eof()) { file >> city1 >> city2 >> distance; // read a line cities[city1].setName(city1); // Dummy initialization but hey, that's not the point here, cities[city2].setName(city2); /* Now we have to create the links between cities in order to make them usable by Dijkstra. A 'child' of a city is another city which can be directly accessed. */ cities[city1].addChild(&cities[city2], distance); cities[city2].addChild(&cities[city1], distance); } // Create the PathFinder and PathAlgorithm stuff PathFinder<City> p; std::vector<City*> solution; // We'll assume that the user is giving correct arguments, because we deny all responsibilities ! p.setStart(cities[start]); p.setGoal(cities[end]); std::cout << "Looking for shortest path between " << start << " and " << end << " ..." << std::endl; bool r = p.findPath<Dijkstra>(solution); if(r) // path found { std::cout << "Solution (" << solution.size()-1 << " steps) :" << std::endl; for(const auto& city : solution) std::cout << city->getName() << " "; std::cout << std::endl; } else std::cerr << "No path was found, sorry." << std::endl; std::getchar(); return 0; }
true
7492ce2de7c57b2751395605532ce7f09af8cbd2
C++
linghutf/topcoder
/interview/ImplStack.cpp
UTF-8
1,306
4
4
[]
no_license
#include <iostream> #include <queue> using namespace std; template<typename T> class CStack{ public: CStack(){} ~CStack(){} void EnQueue(const T& element); T DeQueue(); private: std::queue<T> q1; std::queue<T> q2; }; template<typename T> void CStack<T>::EnQueue(const T &element) { if(q2.empty()) q1.push(element); else if(q1.empty()) q2.push(element); else throw std::runtime_error("stack internal error."); //std::queue<int> q; } template<typename T> T CStack<T>::DeQueue() { if(q1.empty() && q2.empty()) throw std::runtime_error("stack is empty."); T data; if(q1.empty()){ //转移数据到q1 while(q2.size()!=1){ q1.push(q2.front()); q2.pop(); } data = q2.front(); q2.pop(); }else{ while(q1.size()!=1){ q2.push(q1.front()); q1.pop(); } data = q1.front(); q1.pop(); } return data; } int main(int argc, char *argv[]) { CStack<int> s; s.EnQueue(10); s.EnQueue(11); cout<<s.DeQueue()<<endl;//11 s.EnQueue(12); cout<<s.DeQueue()<<endl;//12 cout<<s.DeQueue()<<endl;//10 cout<<s.DeQueue()<<endl;//error return 0; }
true
19a0e9f49508ce185cc244f4b2dd0e9aa3d0a303
C++
codeALIAS/PROG
/src/Transactions.cpp
UTF-8
2,018
3.1875
3
[]
no_license
#include "Transactions.h" #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> Transaction::Transaction() { id = 0; date = "NULL"; products = "NULL"; } Transaction::Transaction(int id, string date, string products) { Transaction::id = id; Transaction::date = date; Transaction::products = products; } Transaction::Transaction(string line) // needs to skip first line ("4") { string delimiter = " ; "; size_t pos = 0; string token; int i = 0; string store_line[3]; string line_copy = line; while ((pos = line_copy.find(delimiter)) != string::npos) { token = line_copy.substr(0, pos); store_line[i] = token; line_copy.erase(0, pos + delimiter.length()); i++; } Transaction::id = atoi(store_line[0].c_str()); Transaction::date = store_line[1]; Transaction::products = line_copy.c_str(); } int Transaction::get_id() { return Transaction::id; } string Transaction::get_date() { return Transaction::date; } string Transaction::get_products() { return Transaction::products; } void Transaction::set_id(int id) { Transaction::id = id; } void Transaction::set_date(string date) { Transaction::date = date; } void Transaction::set_products(string products) { Transaction::products = products; } void Transaction::show() { cout << id << " ; " << date << " ; " << products << endl; } void Transaction::load_transactions_to_vector() { { cout << "Now loading all products " << endl; string line; ifstream myfile("transactions_work.txt"); if (myfile.is_open()) { myfile.ignore(1000, '\n'); //ignore the 4 while (getline(myfile, line)) // scans every line { Transaction new_transaction(line); /* int i = 0; client_vector[i] = new_client; i++; */ transactions_vector.push_back(new_transaction); } myfile.close(); } // cout << client_vector[2].get_name() << endl; // test, works. } } vector<Transaction> Transaction::get_transactions() { return transactions_vector; }
true
1814b545104e1e90c25d3ae22dbe988087fda676
C++
imulan/procon
/atcoder/arc074/f.cpp
UTF-8
2,229
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second // (行き先,容量,逆辺) struct edge{ int to,cap,rev; }; const int MAX_V = 222; // TODO:initialize const int F_INF = 123456789; // TODO:initialize vector<edge> G[MAX_V]; int level[MAX_V]; // sからの距離 int iter[MAX_V]; // どこまで調べ終わったか void add_edge(int from, int to, int cap){ G[from].pb({to,cap,(int)G[to].size()}); G[to].pb({from,cap,(int)G[from].size()-1}); } void dinic_bfs(int s){ memset(level,-1,sizeof(level)); queue<int> que; level[s]=0; que.push(s); while(!que.empty()){ int v = que.front(); que.pop(); rep(i,G[v].size()){ edge &e = G[v][i]; if(e.cap>0 && level[e.to]<0){ level[e.to] = level[v]+1; que.push(e.to); } } } } // 増加パスをdfsで探す int dinic_dfs(int v, int t, int f){ if(v==t) return f; for(int &i=iter[v]; i<(int)G[v].size(); ++i){ edge &e=G[v][i]; if(e.cap>0 && level[v]<level[e.to]){ int d = dinic_dfs(e.to,t,min(f,e.cap)); if(d>0){ e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } // sからtへの最大流 int max_flow(int s, int t){ int flow = 0; while(1){ dinic_bfs(s); if(level[t]<0) return flow; memset(iter,0,sizeof(iter)); int f; while((f=dinic_dfs(s,t,F_INF))>0) flow+=f; } } const int M = 191919; int main() { int h,w; cin >>h >>w; vector<string> s(h); rep(i,h) cin >>s[i]; int S = h+w, T = S+1; rep(i,h)rep(j,w) { if(s[i][j]=='o') add_edge(i,h+j,1); else if(s[i][j]=='S') { add_edge(S,i,M); add_edge(S,h+j,M); } else if(s[i][j]=='T') { add_edge(T,i,M); add_edge(T,h+j,M); } } int ans = max_flow(S,T); if(ans>=M) ans = -1; cout << ans << endl; return 0; }
true
a6c4dc22497f333220c788e3b3dee13b1f6f3889
C++
BigBossErndog/Amara-Framework
/amara/amara_controlScheme.cpp
UTF-8
6,419
2.71875
3
[ "MIT" ]
permissive
namespace Amara { class ControlScheme { public: Amara::GameProperties* properties = nullptr; Amara::InputManager* input = nullptr; std::unordered_map<std::string, Amara::Control*> controls; std::vector<Amara::Control*> controlList; ControlScheme(Amara::GameProperties* gameProperties) { properties = gameProperties; input = gameProperties->input; controlList.clear(); } virtual void configure(nlohmann::json config) { } virtual nlohmann::json toData() { nlohmann::json config; for (Amara::Control* control: controlList) { config[control->id] = control->toData(); } return config; } Amara::Control* newControl(std::string key) { if (get(key) != nullptr) { std::cout << "Control \"" << key << "\" already exists." << std::endl; return get(key); } Amara::Control* newControl = new Amara::Control(properties, key); controls[key] = newControl; controlList.push_back(newControl); return newControl; } Amara::Control* get(std::string key) { std::unordered_map<std::string, Amara::Control*>::iterator got = controls.find(key); if (got != controls.end()) { return got->second; } return nullptr; } Amara::Control* addKey(std::string id, Amara::Key* key) { Amara::Control* control = get(id); if (control != nullptr) { control->addKey(key); return control; } control = newControl(id); return addKey(id, key); } Amara::Control* addKey(std::string id, Amara::Keycode keyCode) { Amara::Key* key = input->keyboard->get(keyCode); if (key != nullptr) { return addKey(id, key); } key = input->keyboard->addKey(keyCode); return addKey(id, key); } Amara::Control* setKey(std::string id, Amara::Key* key) { Amara::Control* control = get(id); if (control != nullptr) { control->setKey(key); return control; } control = newControl(id); return setKey(id, key); } Amara::Control* setKey(std::string id, Amara::Keycode keyCode) { Amara::Key* key = input->keyboard->get(keyCode); if (key != nullptr) { return setKey(id, key); } key = input->keyboard->addKey(keyCode); return setKey(id, key); } Amara::Control* addButton(std::string id, Amara::Buttoncode bcode) { Amara::Control* control = get(id); if (control != nullptr) { control->addButton(bcode); return control; } control = newControl(id); return addButton(id, bcode); } Amara::Control* addButton(std::string id, Amara::Button* button) { return addKey(id, button); } void run() { for (Amara::Control* control : controlList) { control->run(); } } bool isDown(std::string id) { Amara::Control* control = get(id); if (control != nullptr) { return control->isDown; } return false; } bool justDown(std::string id) { Amara::Control* control = get(id); if (control != nullptr) { return control->justDown; } return false; } bool justUp(std::string id) { Amara::Control* control = get(id); if (control != nullptr) { return control->justUp; } return false; } bool tapped(std::string id) { Amara::Control* control = get(id); if (control != nullptr) { return control->tapped; } return false; } bool held(std::string id) { Amara::Control* control = get(id); if (control != nullptr) { return control->held; } return false; } bool held(std::string id, int time) { Amara::Control* control = get(id); if (control != nullptr && control->isDown) { if (control->downTime >= time) { return true; } } return false; } bool justDownOrHeld(std::string id, int gTime) { Amara::Control* control = get(id); return (justDown(id) || (isDown(id) && control->downTime > gTime)); } bool justDownOrPeriodic(std::string id, int gTime) { Amara::Control* control = get(id); return (justDown(id) || (isDown(id) && control->downTime % gTime == 0)); } bool justDownOrHeldPeriodic(std::string id, int gTimeHeld, int gTimePeriodic) { Amara::Control* control = get(id); return (justDown(id) || (isDown(id) && control->downTime > gTimeHeld && control->downTime % gTimePeriodic == 0)); } int downTime(std::string id) { Amara::Control* control = get(id); return control->downTime; } bool activated(std::string id) { Amara::Control* control = get(id); if (control != nullptr) { return control->activated; } return false; } }; }
true
ebcf5b47ca2a2a78ebe47aa29fd66f142bd42666
C++
SimplyKnownAsG/argreffunc
/tests/ExampleHelp.cpp
UTF-8
6,044
2.515625
3
[ "Apache-2.0" ]
permissive
#include "arf/argreffunc.hpp" #include "catch.hpp" #include <iostream> #include <sstream> TEST_CASE("example-help", "[example]") { arf::Parser parser("the-program-name"); SECTION("adding a help option") { bool show_help = false; parser.add("help", "show help", [&show_help](void) { show_help = true; }) .add_alias("h") .add_alias("?"); std::vector<std::string> params = { "--help" }; parser.parse(params); REQUIRE(show_help == true); } /// this is a comment, that I would like broken out SECTION("really long documentation") { std::string greeting = "Hello"; std::string name = "World"; parser.add( "name", R"(Lorem ipsum dolor sit amet, inani oratio salutandi ne mea, qui in affert nostro officiis, te pri velit cetero. Nibh expetenda consequuntur ex vim. Dictas civibus mei no. An iudico noster eam, eu labore accusam molestiae pro. Minim libris id mei, ex vide semper vix. Te ancillae molestie officiis qui, no ancillae reprimique est. Qui affert philosophia at, sit in mollis aliquam eloquentiam. Cum cu nobis oratio cotidieque, mel id dicta accusam efficiendi, pri ubique appetere at. Ad ubique aperiri scribentur nec, mea ei latine molestie. Eos iisque suscipiantur eu. Sit ad option docendi conceptam. Vis timeam adversarium in. At pro exerci propriae, usu id brute augue dicant, vim aliquando eloquentiam in. Quo an dolores gloriatur, vel delenit graecis eloquentiam et. Quo vivendo intellegebat te, alii postea utamur pri ea. Mel eu iuvaret deserunt, usu facete honestatis id, ne quo quot summo. Vis ne aperiri rationibus. Enim mollis tincidunt ex eos, eu eam nostro electram cotidieque.)", name); parser.add("greeting", "the thing ur gonna say", greeting); std::stringstream stream; parser.print_help(stream); auto expected = R"(the-program-name --name <name> Lorem ipsum dolor sit amet, inani oratio salutandi ne mea, qui in affert nostro officiis, te pri velit cetero. Nibh expetenda consequuntur ex vim. Dictas civibus mei no. An iudico noster eam, eu labore accusam molestiae pro. Minim libris id mei, ex vide semper vix. Te ancillae molestie officiis qui, no ancillae reprimique est. Qui affert philosophia at, sit in mollis aliquam eloquentiam. Cum cu nobis oratio cotidieque, mel id dicta accusam efficiendi, pri ubique appetere at. Ad ubique aperiri scribentur nec, mea ei latine molestie. Eos iisque suscipiantur eu. Sit ad option docendi conceptam. Vis timeam adversarium in. At pro exerci propriae, usu id brute augue dicant, vim aliquando eloquentiam in. Quo an dolores gloriatur, vel delenit graecis eloquentiam et. Quo vivendo intellegebat te, alii postea utamur pri ea. Mel eu iuvaret deserunt, usu facete honestatis id, ne quo quot summo. Vis ne aperiri rationibus. Enim mollis tincidunt ex eos, eu eam nostro electram cotidieque. --greeting <greeting> the thing ur gonna say )"; REQUIRE(expected == stream.str()); } SECTION("double spaces removed") { std::string spaced = "..."; parser.add("spaced", " there is a double. space", spaced); std::string expected = R"(the-program-name --spaced <spaced> there is a double. space )"; std::stringstream stream; parser.print_help(stream); REQUIRE(expected == stream.str()); } SECTION("long word extends beyond 80") { std::string spaced = "..."; parser.add("spaced", "first " "its-not-that-i-don't-like-spaces,it's-just-that-i-think-there-is-another-way " "last", spaced); std::string expected = R"(the-program-name --spaced <spaced> first its-not-that-i-don't-like-spaces,it's-just-that-i-think-there-is-another-way last )"; std::stringstream stream; parser.print_help(stream); REQUIRE(expected == stream.str()); } SECTION("multiple names and aliases") { std::string spaced = "..."; parser.add("name1", "description of name1", spaced) .add_alias("name2") .add_alias("n") .add_alias("1") .add_alias("2"); std::string expected = R"(the-program-name --name1 <name1>, --name2 <name1> -n <name1>, -1 <name1>, -2 <name1> description of name1 )"; std::stringstream stream; parser.print_help(stream); REQUIRE(expected == stream.str()); } SECTION("required positional") { std::string arg_ref = "..."; parser.add_positional("required-positional", "description of arg", arg_ref); std::string expected = R"(the-program-name <required-positional> description of arg )"; std::stringstream stream; parser.print_help(stream); REQUIRE(expected == stream.str()); } SECTION("optional positional") { std::string arg_ref = "..."; parser.add_positional("optional-positional", "description of arg", arg_ref, false); std::string expected = R"(the-program-name [optional-positional] description of arg )"; std::stringstream stream; parser.print_help(stream); REQUIRE(expected == stream.str()); } SECTION("switch") { bool arg_ref = false; parser.add("switch", "description of arg", [&]() { arg_ref = true; }); std::string expected = R"(the-program-name --switch description of arg )"; std::stringstream stream; parser.print_help(stream); REQUIRE(expected == stream.str()); } }
true
9032e48c4e7515d29acc1f548f8501ea40593ba7
C++
ajarno/GL40-Fitts
/result.cpp
UTF-8
3,418
2.6875
3
[]
no_license
#include "result.h" #include "ui_result.h" Result::Result(QWidget *parent, QVector<double> *_sizes, QVector<double> *_distances, QVector<double> *_times, float _a, float _b): QWidget (parent), ui(new Ui::Result), times(_times) { ui->setupUi(this); drawPlot(_sizes,_distances,_a,_b); fillLabels(); } Result::~Result() { delete ui; } void Result::drawPlot(QVector<double> *sizes, QVector<double> *distances, float a, float b) { QVector<double> *nb_cibles = new QVector<double>(); for (int i = 1; i <= 10; ++i) { nb_cibles->append(i); } customPlot = new QCustomPlot(this); customPlot->setGeometry(0,0,width(),height()/2); customPlot->addGraph(customPlot->xAxis,customPlot->yAxis); customPlot->addGraph(customPlot->xAxis,customPlot->yAxis); customPlot->graph(0)->setPen(QPen(Qt::blue)); customPlot->graph(0)->setData(*nb_cibles, *times); customPlot->graph(1)->setPen(QPen(Qt::red)); customPlot->graph(1)->setData(*nb_cibles, *fittsLaw(distances, sizes, a, b)); customPlot->xAxis->setLabel("Numéro de l'essai"); customPlot->yAxis->setLabel("Temps (ms)"); customPlot->xAxis->setRange(getMin(nb_cibles), getMax(nb_cibles)); QSharedPointer<QCPAxisTickerText> textTicker(new QCPAxisTickerText); for (int i = 0; i < nb_cibles->length(); i++) { textTicker->addTick(nb_cibles->value(i),"Taille : " + QString::number(sizes->value(i)) + "\nDistance : " + QString::number(distances->value(i))); } textTicker->setSubTickCount(getMax(nb_cibles)); customPlot->xAxis->setTicker(textTicker); customPlot->yAxis->setRange(getMin(times),getMax(times)); customPlot->replot(); } void Result::fillLabels() { ui->error_label->setNum(standardError()); ui->deviation_label->setNum(standardDeviation()); ui->mean_diff_label->setNum(meanDifference()); ui->confidence_label->setNum(confidenceRange()); } double Result::standardDeviation() { double variance(0); for (int i = 0; i < times->length(); i++) { variance += pow(times->value(i) - mean(),2); } return sqrt(variance/times->length()); } double Result::meanDifference() { QVector<double> *diff = new QVector<double>(); double mean(0); for (int i = 0; i < times->length() - 1; i++) { diff->append((times->value(i) + times->value(i+1))/2); } for (int i = 0; i < diff->length(); i++) { mean += diff->value(i); } return mean/diff->length(); } double Result::confidenceRange() { return mean()-1.96*standardError(); } double Result::standardError() { return standardDeviation()/sqrt(mean()); } double Result::mean() { double m(0); for (int i = 0; i < times->length(); i++) { m += times->value(i); } return m/times->length(); } QVector<double> *Result::fittsLaw(QVector<double> *distances, QVector<double> *sizes, double a, double b) { QVector<double> *fitts_result = new QVector<double>(); for (int i = 0; i < sizes->length(); i++) { fitts_result->append(a+b*log2((distances->value(i)/sizes->value(i))+1)); } return fitts_result; } double Result::getMin(QVector<double> *vector) { return *std::min_element(vector->constBegin(),vector->constEnd()); } double Result::getMax(QVector<double> *vector) { return *std::max_element(vector->constBegin(),vector->constEnd()); }
true
8b6404e99b8217fee4227090ffc43eaff61538cb
C++
coderSkyChen/ML_cpp
/classification/NaiveBayes/NaiveBayes.cpp
UTF-8
3,572
2.734375
3
[]
no_license
#include"NaiveBayes.h" #include<float.h> #include<math.h> #include<algorithm> #include<fstream> #include<iostream> #include<set> #include<sstream> void NaiveBayes::set_training_data_file(const string filepath) { training_data_filepath = filepath; } void NaiveBayes::get_training_data() { ifstream file(training_data_filepath.c_str()); string line; while(getline(file,line)) { istringstream iss(line); string attr; StringVector sv; while(getline(iss, attr, DELIM)) { sv.push_back(attr); } classes.push_back(sv.back()); // The last entry is the class name sv.pop_back(); inputdata.push_back(sv); } } void NaiveBayes::train() { get_training_data(); //compute class prob for(StringVector::const_iterator it=classes.begin();it!=classes.end();it++) { if(class_prob.find(*it)==class_prob.end()) { class_prob[*it] = 1.0; } else { class_prob[*it] += 1.0; } } for(MapSD::const_iterator it=class_prob.begin();it!=class_prob.end();it++) { class_prob[it->first] = (it->second) / classes.size(); } /* * count is a map of maps. * C1: count(x1), ... , count(xn) * . * CN: count(x1), ... , count(xn) */ MapSD vob; vobsize = 0; for(int i=0;i<inputdata.size();i++) { StringVector instance=inputdata[i]; for(int j=0;j<instance.size();j++) { if(vob.find(instance[j])==vob.end()) { vob[instance[j]] = 1.0; vobsize ++; } if(count.find(classes[i])==count.end()) { count[classes[i]] = new MapSD; (*count[classes[i]])[instance[j]] = 1.0; } else { if((*count[classes[i]]).find(instance[j])==(*count[classes[i]]).end()) { (*count[classes[i]])[instance[j]] = 1.0; } else { (*count[classes[i]])[instance[j]] += 1.0; } } } } for(MapOfMaps::const_iterator it=count.begin();it!=count.end();it++) { num_of_words_per_class[it->first] = 1.0; for(MapSD::const_iterator iit=it->second->begin();iit!=it->second->end();iit++) { num_of_words_per_class[it->first] += iit->second; } } } string NaiveBayes::classify(const string& input_attr) { istringstream iss(input_attr); string token; StringVector attr; int i=0; while(getline(iss,token,DELIM)) { attr.push_back(token); } double max_prob = -DBL_MAX; string max_class; for(MapOfMaps::const_iterator it=count.begin();it!=count.end();it++) { double prob=0.0; for(int i=0;i<attr.size();i++) { double p; if(it->second->find(attr[i])==it->second->end()) {// add 1 smoothing p= (0+1.0)/(num_of_words_per_class[it->first]+vobsize); } else { p= ((*it->second)[attr[i]]+1.0)/(num_of_words_per_class[it->first]+vobsize); } prob += log(p); } prob += log(class_prob[it->first]); if(prob>max_prob) { max_prob=prob; max_class = it->first; } } return max_class; }
true
d24076a383d1c102a5c77b27447f6bdaf6c19778
C++
RPeschke/SCT_Correlations2
/core_lib/src/ProcessorCollection.cc
UTF-8
1,262
2.625
3
[]
no_license
#include "sct/ProcessorCollection.h" ProcessorCollection::ProcessorCollection(){ } void ProcessorCollection::addProcessor(std::shared_ptr<processor> processor_){ m_processors.push_back(processor_); processor_->mpc = this; } init_returns ProcessorCollection::init(){ if (m_processors.empty()) { return i_error; } for (auto&e:m_processors){ auto ret=e->init(); if (ret!=i_sucess){ return ret; } } return i_sucess; } end_returns ProcessorCollection::end(){ for (auto&e : m_processors) { auto ret = e->end(); if (ret != e_success) { return ret; } } return e_success; } void ProcessorCollection::loop(){ if (init()==i_error) { return; } while (next()) { } end(); } void ProcessorCollection::loop(int last) { init(); int i = 0; while (next()&&++i<last) { } end(); } bool ProcessorCollection::next(){ for (auto&e : m_processors) { auto ret = e->processEvent(); if (ret != p_sucess) { return false; } } for (auto&e : m_processors) { auto ret = e->fill(); if (ret == p_skip) { return true; } if (ret != p_sucess) { return false; } } return true; } bool ProcessorCollection::next_debug() { return true; }
true
8ee7e78c4417d5a5ddb5a0d2b321f3a3f320ea90
C++
Artanidos/AnimationMaker
/src/AnimationItems/colorpicker.cpp
UTF-8
2,619
2.53125
3
[]
no_license
/**************************************************************************** ** Copyright (C) 2016 Olaf Japp ** ** This file is part of AnimationMaker. ** ** AnimationMaker is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** AnimationMaker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with AnimationMaker. If not, see <http://www.gnu.org/licenses/>. ** ****************************************************************************/ #include "colorpicker.h" #include <QImage> #include <QPainter> ColorPicker::ColorPicker() { m_hue = 0.0; m_lpressed = false; setMinimumSize(100, 100); } void ColorPicker::setHue(qreal value) { m_hue = value; update(); } qreal ColorPicker::hue() { return m_hue; } QSize ColorPicker::sizeHint() const { return QSize(100, 100); } void ColorPicker::paintEvent(QPaintEvent *) { QPainter painter(this); qreal s, l, a; QImage image(100, 100, QImage::Format_ARGB32); for(int x=0; x < 100; x++) { for(int y=0;y < 100; y++) { s = x / 100.0; l = (100 - y) / 100.0; a = 1.0; QColor color = QColor::fromHslF(m_hue, s, l, a); image.setPixel(x, y, color.rgba()); } } painter.drawImage(0, 0, image); } void ColorPicker::mousePressEvent(QMouseEvent * event) { if(event->button() == Qt::LeftButton) { m_lpressed = true; emit colorChanged(getColor(event)); } } void ColorPicker::mouseReleaseEvent(QMouseEvent * event) { if(m_lpressed) { m_lpressed = false; emit colorPicked(getColor(event)); } } QColor ColorPicker::getColor(QMouseEvent *event) { qreal s, l, a; int x, y; x = event->pos().x(); y = event->pos().y(); if(x < 0) x = 0; if(x > 100) x = 100; if(y < 0) y = 0; if(y > 100) y = 100; s = x / 100.0; l = (100 - y) / 100.0; a = 1.0; return QColor::fromHslF(m_hue, s, l, a); } void ColorPicker::mouseMoveEvent(QMouseEvent *event) { if ((event->buttons() & Qt::LeftButton) && m_lpressed) { emit colorChanged(getColor(event)); } }
true
cb103b37d0fa1416b2b0465d2ae4c6e7b6b83bdb
C++
jg-maon/DxLibGame01
/DxLibGame01/src/Math.cpp
SHIFT_JIS
6,706
3.234375
3
[]
no_license
/**============================================================================= @file Math.cpp @brief wIeNX @author Masato Yamamoto @date 2015-02-20 @par [] w\NX Size Vector3 Matrix4x4 @note Copyright (C) 2015 M.Yamamoto =============================================================================*/ #include "Math.h" #include <float.h> NS_DLG_BEGIN namespace ns_Math { #pragma region Size public methods /** @brief RXgN^ @param[in] Ȃ @return Ȃ */ Size::Size() : width(0.f) , height(0.f) { } /** @brief RXgN^ @param[in] _width @param[in] _height @return Ȃ */ Size::Size(float _width, float _height) : width(_width) , height(_height) { } /** @brief fXgN^ @param[in] Ȃ @return Ȃ */ Size::~Size() { } /** @brief LXgZq̃I[o[[h(Vector3) @param[in] Ȃ @return SizeVector3 */ Size::operator Vector3() const { return Vector3(width, height, 0.0f); } #pragma endregion // Size public methods #pragma region Vector3 public methods /** @brief RXgN^ @param[in] Ȃ @return Ȃ */ Vector3::Vector3() { x = y = z = 0.f; } /** @brief RXgN^ @param[in] v xNg @return Ȃ */ Vector3::Vector3(const VECTOR& v) { x = v.x; y = v.y; z = v.z; } /** @brief RXgN^ @param[in] c 萔 @return Ȃ */ Vector3::Vector3(const float c) { x = c; y = c; z = c; } /** @brief RXgN^ @param[in] _x X @param[in] _y Y @param[in] _z Z @return Ȃ */ Vector3::Vector3(float _x, float _y, float _z) { x = _x; y = _y; z = _z; } /** @brief fXgN^ @param[in] Ȃ @return Ȃ */ Vector3::~Vector3() { } /** @brief xNg𐳋K @param[in] Ȃ @return KxNgg */ Vector3& Vector3::Normalize() { float length = Norm(); x /= length; y /= length; z /= length; return *this; } #pragma endregion // Vector3 public methods #pragma region Matrix4x4 public methods /** @brief 3xNg4ɊgA4x4̍sɊ| @param[in] mat s @param[in] v xNg @return s~xNg */ Vector3 Matrix4x4::Matrix4x4_Mul_Vector3(const Matrix4x4& mat, const VECTOR& v) { float v4[4] = { v.x, v.y, v.z, 1.0f }; float rv4[4] = { 0.0f }; for (int y = 0; y<4; y++) for (int x = 0; x<4; x++) rv4[y] += mat.m[y][x] * v4[x]; return Vector3(rv4[0], rv4[1], rv4[2]); } /** @brief 3xNg𕽍sړsϊ @param[in] shiftX X @param[in] shiftY Y @param[in] shiftZ Z @param[in] orig xNg @return sړϊ̃xNg */ Vector3 Matrix4x4::CalcVector3ShiftXYZ(float shiftX, float shiftY, float shiftZ, const VECTOR& orig) { Matrix4x4 matShift(1.0f, 0.0f, 0.0f, shiftX, 0.0f, 1.0f, 0.0f, shiftY, 0.0f, 0.0f, 1.0f, shiftZ, 0.0f, 0.0f, 0.0f, 1.0f); return matShift * orig; } /** @brief 3xNggksϊ @param[in] scaleX X @param[in] scaleY Y @param[in] scaleZ Z @param[in] orig xNg @return gkϊ̃xNg */ Vector3 Matrix4x4::CalcVector3ScaleXYZ(float scaleX, float scaleY, float scaleZ, Vector3 orig) { Matrix4x4 matScale(scaleX, 0.0f, 0.0f, 0.0f, 0.0f, scaleY, 0.0f, 0.0f, 0.0f, 0.0f, scaleZ, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); return matScale * orig; } /** @brief 3xNg]sϊ @param[in] rotX XWA @param[in] rotY YWA @param[in] rotZ ZWA @param[in] orig xNg @return ]ϊ̃xNg */ Vector3 Matrix4x4::CalcVector3RotationXYZ(float rotX, float rotY, float rotZ, const VECTOR& orig) { Matrix4x4 matRotation( ::std::cosf(rotZ)*::std::cosf(rotX), ::std::cosf(rotZ)*::std::sinf(rotX)*::std::sinf(rotY) - ::std::sinf(rotZ)*::std::cosf(rotY), ::std::cosf(rotZ)*::std::sinf(rotX)*::std::cosf(rotY) + ::std::sinf(rotZ)*::std::sinf(rotY), 0.0f, ::std::sinf(rotZ)*::std::cosf(rotX), ::std::sinf(rotZ)*::std::sinf(rotX)*::std::sinf(rotY) + ::std::cosf(rotZ)*::std::cosf(rotY), ::std::sinf(rotZ)*::std::sinf(rotX)*::std::cosf(rotY) - ::std::cosf(rotZ)*::std::sinf(rotY), 0.0f, -::std::sinf(rotX), ::std::cosf(rotX)*::std::sinf(rotY), ::std::cosf(rotX)*::std::cosf(rotY), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); return matRotation * orig; } /** @brief Pʍs̎擾 @param[in] Ȃ @return Ȃ */ Matrix4x4 Matrix4x4::GetIdentity() { Matrix4x4 mat; for (int i = 0; i < 4; ++i) { mat.m[i][i] = 1.0f; } return mat; } /** @brief RXgN^ @param[in] Ȃ @return Ȃ */ Matrix4x4::Matrix4x4() { for (int i = 0; i<16; i++) m[i / 4][i % 4] = 0.0f; } /** @brief RXgN^ @param[in] c 萔 @return Ȃ */ Matrix4x4::Matrix4x4(float c) { for (int i = 0; i < 16; i++) m[i / 4][i % 4] = c; } /** @brief RXgN^ @param[in] f evf[s*] @return Ȃ */ Matrix4x4::Matrix4x4(const float f[16]) { for (int i = 0; i<16; i++) m[i / 4][i % 4] = f[i]; } /** @brief RXgN^ @param[in] f evf[s][] @return Ȃ */ Matrix4x4::Matrix4x4(const float f[4][4]) { for (int i = 0; i<4; i++) for (int j = 0; j<4; j++) m[i][j] = f[i][j]; } /** @brief RXgN^ @param[in] _11 ~ _44 evf @return Ȃ */ Matrix4x4::Matrix4x4(float _11, float _12, float _13, float _14, float _21, float _22, float _23, float _24, float _31, float _32, float _33, float _34, float _41, float _42, float _43, float _44) { m[0][0] = _11; m[0][1] = _12; m[0][2] = _13; m[0][3] = _14; m[1][0] = _21; m[1][1] = _22; m[1][2] = _23; m[1][3] = _24; m[2][0] = _31; m[2][1] = _32; m[2][2] = _33; m[2][3] = _34; m[3][0] = _41; m[3][1] = _42; m[3][2] = _43; m[3][3] = _44; } /** @brief RXgN^ @param[in] mat s @return Ȃ */ Matrix4x4::Matrix4x4(const MATRIX& mat) { for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) m[i][j] = mat.m[i][j]; } /** @brief fXgN^ @param[in] Ȃ @return Ȃ */ Matrix4x4::~Matrix4x4() { } #pragma endregion // Matrix4x4 public methods } // namespace ns_Math NS_DLG_END
true
04129995562ad7feb0927bee28cee88510756583
C++
codingbycoding/codingbycoding.github.io
/stl/stlmain.cpp
UTF-8
2,544
3.171875
3
[]
no_license
//g++ -ggdb -std=c++0x stlmain.cpp algorithm.cpp -o stlmain.linux #include <iostream> #include <cassert> #include <deque> #include <map> using namespace std; const static int intArg1 = 5; const static int intArg2 = 15; const static int intArg3 = 30; const static long longArg1 = 5; const static long longArg2 = 15; const static int intMagic1 = 10; const static int intMagic2 = 20; const static float floatMagic1 = 10.0; const static float floatMagic2 = 20.0; /*template<typename T> T sum(T arg1, T arg2) { return arg1 + arg2; }*/ /* nontype template function parameters. */ /*template<typename T, int magic> T sum(T arg1, T arg2) { return arg1 + arg2 + magic; }*/ //'float' is not a valid type for a template constant parameter /*template<typename T, float magic> T sum(T arg1, T arg2) { return arg1 + arg2 + magic; }*/ template<typename T=int, int magic = 100> T sum(T arg1, T arg2) { return arg1 + arg2 + magic; } //Overloading template<typename T=int, int magic = 100> T sum(T arg1, T arg2, T arg3) { return arg1 + arg2 + arg3; } template<typename T> class TStack { public: bool Empty() const { return elements.empty(); } T pop() { } private: std::deque<T> elements; }; struct TestKey_t { int id_1; int id_2; bool operator < (const TestKey_t& rhs) const { return id_2 < rhs.id_2; } }; struct TestValue_t { int id_1; int id_2; }; extern void test_stl_algo(); int main() { std::cout << "stlmain cpp..." << std::endl; //argument deduction. deduct T by argument intArg1. std::cout << "::sum(intArg1, intArg2) :" << ::sum(intArg1, intArg2) << std::endl; std::cout << "::sum(intArg1, intArg2) :" << ::sum<int>(intArg1, intArg2) << std::endl; std::cout << "::sum(intArg1, intArg2, intMagic1) :" << ::sum<int, intMagic1>(intArg1, intArg2) << std::endl; //std::cout << "::sum(intArg1, intArg2) :" << ::sum<int>(intArg1, intArg2) << std::endl; //error: 'float' is not a valid type for a template constant parameter //std::cout << "::sum(floatArg1, floatArg2, floatMagic1) :" << ::sum<float, intMagic1>(floatArg1, floatArg2) << std::endl; // TestKey_t tk1; // std::map<TestKey_t, int> tkM; // tkM[tk1] = 0; TestKey_t tk1; TestValue_t tv1; std::map<TestKey_t, TestValue_t> tkvM; if(tkvM.count(tk1) == 1) { std::cout << "count 1" << std::endl; } else { std::cout << "count 0" << std::endl; } tkvM[tk1] = tv1; test_stl_algo(); return 0; }
true
8dec5ffc00e62a958f9a146999f7632dea613dbe
C++
andrei-datcu/-homework-EGC-Computer-Graphics
/Datcu_Andrei_331CC_Tema1_EGC/tema1/Objects/LifeBonus.cpp
UTF-8
954
2.734375
3
[]
no_license
/* Autor: Datcu Andrei Daniel - 331CC * LifeBonus * Obiectul tip bonus care ofera o viata in plus * Cerc alb cu o cruce verde in centru */ #include "LifeBonus.h" #include "../Framework/Circle2D.h" #include "../Framework/Line2D.h" LifeBonus::LifeBonus(Point2D center, float radius):Bonus(1), circleCenter(center), radius(radius){ defineObject(); computeConvexHull(); reset(); } void LifeBonus::defineObject(){ stdCircularVelocity = 0; stdLinearVelocity = 0; initialCenter = circleCenter; push_back(Circle2D(circleCenter, radius, Color(1, 1, 1), false)); float rfactor = 2.0 / 3; Color green(0, 0.8, 0); push_back(Line2D(Point2D(circleCenter.x, circleCenter.y + rfactor *radius), Point2D(circleCenter.x, circleCenter.y - rfactor * radius), green)); push_back(Line2D(Point2D(circleCenter.x - rfactor *radius, circleCenter.y), Point2D(circleCenter.x + rfactor * radius, circleCenter.y), green)); }
true
77d44776f233cf994811fdcee0fc11ba6c5792e6
C++
mli42/cpp-piscine
/cpp04/ex01/Character.cpp
UTF-8
2,557
2.578125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Character.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mli <mli@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/10 13:47:35 by mli #+# #+# */ /* Updated: 2020/09/10 13:47:36 by mli ### ########.fr */ /* */ /* ************************************************************************** */ #include "Character.hpp" Character::Character(void) { return ; } Character::Character(std::string const &name) : \ _name(name), _apcount(40), _cweapon(NULL) { return ; } Character::Character(Character const &src) { *this = src; } Character::~Character(void) { return ; } Character &Character::operator=(Character const &rhs) { if (this == &rhs) return (*this); this->_name = rhs._name; this->_apcount = rhs._apcount; this->_cweapon = rhs._cweapon; return (*this); } std::ostream &operator<<(std::ostream &o, Character const &i) { o << i.getName() << " has " << i.getAPCount() << " AP and "; if (i.getWeapon()) o << "wields a " << i.getWeapon()->getName(); else o << "is unarmed"; o << std::endl; return (o); } void Character::recoverAP(void) { if (this->_apcount + 10 <= 40) this->_apcount += 10; else this->_apcount = 40; } void Character::attack(Enemy *&enemy) { if (!enemy) std::cout << "Enemy already dead or never existed!" << std::endl; if (!this->_cweapon || !enemy || this->_cweapon->getAPCost() > this->_apcount) return ; std::cout << this->_name << " attacks " << enemy->getType() \ << " with a " << this->_cweapon->getName() << std::endl; this->_apcount -= this->_cweapon->getAPCost(); this->_cweapon->attack(); enemy->takeDamage(this->_cweapon->getDamage()); if (enemy->getHP() <= 0) { delete enemy; enemy = NULL; } } void Character::equip(AWeapon *weapon) { this->_cweapon = weapon; } int Character::getAPCount(void) const { return (this->_apcount); } AWeapon const *Character::getWeapon(void) const { return (this->_cweapon); } std::string Character::getName(void) const { return (this->_name); }
true
f2591c9bfa50fce26ecd58334a92f5a2d38c8520
C++
lucylow/lgrtk
/src/plato/alg/CrsMatrix.cpp
UTF-8
1,411
2.609375
3
[ "BSD-2-Clause" ]
permissive
#include "CrsMatrix.hpp" namespace Plato { // For CrsMatrix A, sets b := Ax template < class Ordinal, class RowMapEntryType> void ApplyCrsMatrix( const CrsMatrix<Ordinal, RowMapEntryType> A, const typename CrsMatrix< Ordinal, RowMapEntryType>::ScalarVector x, const typename CrsMatrix< Ordinal, RowMapEntryType>::ScalarVector b) { auto rowMap = A.rowMap(); auto numRows = rowMap.size() - 1; auto columnIndices = A.columnIndices(); auto entries = A.entries(); Kokkos::parallel_for( Kokkos::RangePolicy<int>(0, numRows), LAMBDA_EXPRESSION(int rowOrdinal) { auto rowStart = rowMap(rowOrdinal); auto rowEnd = rowMap(rowOrdinal + 1); Scalar sum = 0.0; for (auto entryIndex = rowStart; entryIndex < rowEnd; entryIndex++) { auto columnIndex = columnIndices(entryIndex); sum += entries(entryIndex) * x(columnIndex); } b(rowOrdinal) = sum; }, "CrsMatrix Apply()"); } #define LGR_EXPL_INST(Ordinal, RowMapEntryType) \ template \ void ApplyCrsMatrix( \ const CrsMatrix<Ordinal, RowMapEntryType> A, \ const typename CrsMatrix< \ Ordinal, \ RowMapEntryType>::ScalarVector x, \ const typename CrsMatrix< \ Ordinal, \ RowMapEntryType>::ScalarVector b); LGR_EXPL_INST(int, int) #undef LGR_EXPL_INST } // namespace Plato
true
e2da53d7f0426c22a3a6276fc7bc6cc3c691af14
C++
ndsev/zserio
/test/language/enumeration_types/cpp/UInt8EnumTest.cpp
UTF-8
4,163
2.59375
3
[ "BSD-3-Clause" ]
permissive
#include "gtest/gtest.h" #include "zserio/BitStreamWriter.h" #include "zserio/BitStreamReader.h" #include "zserio/CppRuntimeException.h" #include "enumeration_types/uint8_enum/DarkColor.h" namespace enumeration_types { namespace uint8_enum { class UInt8EnumTest : public ::testing::Test { protected: static const size_t DARK_COLOR_BITSIZEOF; static const uint8_t NONE_VALUE; static const uint8_t DARK_RED_VALUE; static const uint8_t DARK_BLUE_VALUE; static const uint8_t DARK_GREEN_VALUE; zserio::BitBuffer bitBuffer = zserio::BitBuffer(1024 * 8); }; const size_t UInt8EnumTest::DARK_COLOR_BITSIZEOF = 8; const uint8_t UInt8EnumTest::NONE_VALUE = 0; const uint8_t UInt8EnumTest::DARK_RED_VALUE = 1; const uint8_t UInt8EnumTest::DARK_BLUE_VALUE = 2; const uint8_t UInt8EnumTest::DARK_GREEN_VALUE = 7; TEST_F(UInt8EnumTest, EnumTraits) { ASSERT_EQ(std::string("NONE"), zserio::EnumTraits<DarkColor>::names[0]); ASSERT_EQ(std::string("DARK_GREEN"), zserio::EnumTraits<DarkColor>::names[3]); ASSERT_EQ(4, zserio::EnumTraits<DarkColor>::names.size()); ASSERT_EQ(DarkColor::DARK_RED, zserio::EnumTraits<DarkColor>::values[1]); ASSERT_EQ(DarkColor::DARK_BLUE, zserio::EnumTraits<DarkColor>::values[2]); ASSERT_EQ(4, zserio::EnumTraits<DarkColor>::values.size()); } TEST_F(UInt8EnumTest, enumToOrdinal) { ASSERT_EQ(0, zserio::enumToOrdinal(DarkColor::NONE)); ASSERT_EQ(1, zserio::enumToOrdinal(DarkColor::DARK_RED)); ASSERT_EQ(2, zserio::enumToOrdinal(DarkColor::DARK_BLUE)); ASSERT_EQ(3, zserio::enumToOrdinal(DarkColor::DARK_GREEN)); } TEST_F(UInt8EnumTest, valueToEnum) { ASSERT_EQ(DarkColor::NONE, zserio::valueToEnum<DarkColor>(NONE_VALUE)); ASSERT_EQ(DarkColor::DARK_RED, zserio::valueToEnum<DarkColor>(DARK_RED_VALUE)); ASSERT_EQ(DarkColor::DARK_BLUE, zserio::valueToEnum<DarkColor>(DARK_BLUE_VALUE)); ASSERT_EQ(DarkColor::DARK_GREEN, zserio::valueToEnum<DarkColor>(DARK_GREEN_VALUE)); } TEST_F(UInt8EnumTest, stringToEnum) { ASSERT_EQ(DarkColor::NONE, zserio::stringToEnum<DarkColor>("NONE")); ASSERT_EQ(DarkColor::DARK_RED, zserio::stringToEnum<DarkColor>("DARK_RED")); ASSERT_EQ(DarkColor::DARK_BLUE, zserio::stringToEnum<DarkColor>("DARK_BLUE")); ASSERT_EQ(DarkColor::DARK_GREEN, zserio::stringToEnum<DarkColor>("DARK_GREEN")); } TEST_F(UInt8EnumTest, valueToEnumFailure) { ASSERT_THROW(zserio::valueToEnum<DarkColor>(3), zserio::CppRuntimeException); } TEST_F(UInt8EnumTest, stringToEnumFailure) { ASSERT_THROW(zserio::stringToEnum<DarkColor>("NONEXISTING"), zserio::CppRuntimeException); } TEST_F(UInt8EnumTest, enumHashCode) { // use hardcoded values to check that the hash code is stable ASSERT_EQ(1702, zserio::calcHashCode(zserio::HASH_SEED, DarkColor::NONE)); ASSERT_EQ(1703, zserio::calcHashCode(zserio::HASH_SEED, DarkColor::DARK_RED)); ASSERT_EQ(1704, zserio::calcHashCode(zserio::HASH_SEED, DarkColor::DARK_BLUE)); ASSERT_EQ(1709, zserio::calcHashCode(zserio::HASH_SEED, DarkColor::DARK_GREEN)); } TEST_F(UInt8EnumTest, bitSizeOf) { ASSERT_TRUE(zserio::bitSizeOf(DarkColor::NONE) == DARK_COLOR_BITSIZEOF); } TEST_F(UInt8EnumTest, initializeOffsets) { const size_t bitPosition = 1; ASSERT_TRUE(zserio::initializeOffsets(bitPosition, DarkColor::NONE) == bitPosition + DARK_COLOR_BITSIZEOF); } TEST_F(UInt8EnumTest, read) { zserio::BitStreamWriter writer(bitBuffer); writer.writeBits(static_cast<uint32_t>(DarkColor::DARK_RED), DARK_COLOR_BITSIZEOF); zserio::BitStreamReader reader(writer.getWriteBuffer(), writer.getBitPosition(), zserio::BitsTag()); DarkColor darkColor(zserio::read<DarkColor>(reader)); ASSERT_EQ(DARK_RED_VALUE, zserio::enumToValue(darkColor)); } TEST_F(UInt8EnumTest, write) { const DarkColor darkColor(DarkColor::DARK_BLUE); zserio::BitStreamWriter writer(bitBuffer); zserio::write(writer, darkColor); zserio::BitStreamReader reader(writer.getWriteBuffer(), writer.getBitPosition(), zserio::BitsTag()); ASSERT_EQ(DARK_BLUE_VALUE, reader.readBits(DARK_COLOR_BITSIZEOF)); } } // namespace uint8_enum } // namespace enumeration_types
true
b52a7a4a41fc879bc919ab9f1166b1c336bd1657
C++
Bojzen-I-Mitten/Stort-spelprojekt
/thomas/ThomasCore/src/thomas/graphics/Skybox.cpp
UTF-8
4,067
2.71875
3
[ "MIT" ]
permissive
#include "Skybox.h" #include "Renderer.h" #include "../utils/d3d.h" #include "../utils/Buffers.h" #include "../resource/texture/Texture2D.h" #include "../resource/texture/TextureCube.h" #include "../resource/Shader.h" namespace thomas { namespace graphics { SkyBox::SkyBox() { GenerateSphere(10, 10, 5.0f); m_skyMap = nullptr; m_shader = graphics::Renderer::Instance()->getShaderList().CreateShader("../Data/FXIncludes/SkyBoxShader.fx"); } SkyBox::~SkyBox() { } bool SkyBox::SetSkyMap(resource::TextureCube * tex) { m_skyMap = tex; return true; } resource::TextureCube * SkyBox::GetSkyMap() { return m_skyMap; } SkyBox::operator bool() const { return m_skyMap; //Check null } void SkyBox::GenerateSphere(unsigned horizontalLines, unsigned verticalLines, float radius) { std::vector<math::Vector3> sphereVerts; std::vector<unsigned int> sphereIndices; float phi = 0.0f; float theta = 0.0f; float twoPiDivVerticalLines = math::PI * 2 / verticalLines; float piDivHorizontalLines = math::PI / (horizontalLines + 1); sphereVerts.push_back(math::Vector3(0.0f, radius, 0.0f));//endpoint 1 for (unsigned t = 1; t < horizontalLines + 1; ++t) { theta = t * piDivHorizontalLines; for (unsigned p = 0; p < verticalLines; ++p) { phi = p * twoPiDivVerticalLines; sphereVerts.push_back(math::SphericalCoordinate(phi, theta, radius)); } } sphereVerts.push_back(math::Vector3(0.0f, -radius, 0.0f)); //endpoint 2 //Create top of sphere for (unsigned p = 2; p < verticalLines + 1; ++p)//connect endpoint 1 indices { sphereIndices.push_back(0); sphereIndices.push_back(p); sphereIndices.push_back(p - 1); } //add last triangle for top (first vert is douplicate) sphereIndices.push_back(0); sphereIndices.push_back(1); sphereIndices.push_back(verticalLines); //Create middle segments for (unsigned t = 0; t < horizontalLines - 1; ++t) { for (unsigned p = 2; p < verticalLines + 1; ++p) { sphereIndices.push_back(t * verticalLines + p);//+ 1 is for to exclude top vert sphereIndices.push_back((t + 1) * verticalLines + p);//take vert in next layer sphereIndices.push_back(t * verticalLines + p - 1); sphereIndices.push_back(t * verticalLines + p - 1); sphereIndices.push_back((t + 1) * verticalLines + p); sphereIndices.push_back((t + 1) * verticalLines + p - 1); } //Again append douplicate verts sphereIndices.push_back(t * verticalLines + 1); sphereIndices.push_back((t + 1) * verticalLines + 1); sphereIndices.push_back((t + 1) * verticalLines); sphereIndices.push_back((t + 1) * verticalLines); sphereIndices.push_back((t + 1) * verticalLines + 1); sphereIndices.push_back((t + 2) * verticalLines); } //Create bottom of sphere for (unsigned p = (uint32_t)sphereVerts.size() - verticalLines; p < sphereVerts.size(); ++p) { sphereIndices.push_back((uint32_t)sphereVerts.size() - 1); sphereIndices.push_back(p - 1); sphereIndices.push_back(p); } sphereIndices.push_back((uint32_t)sphereVerts.size() - 1); sphereIndices.push_back((uint32_t)sphereVerts.size() - 2); sphereIndices.push_back((uint32_t)sphereVerts.size() - 1 - verticalLines); m_vertBuffer = std::unique_ptr<utils::buffers::VertexBuffer>( new utils::buffers::VertexBuffer(sphereVerts)); m_indexBuffer = std::make_unique<utils::buffers::IndexBuffer>(sphereIndices); #ifdef _DEBUG m_vertBuffer->SetName("SKYBOX_VERTEX"); m_indexBuffer->SetName("SKYBOX_INDEX"); #endif } void SkyBox::Draw() { if (!m_skyMap) return; // No skymap, don't... m_shader->BindPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_shader->BindVertexBuffer(m_vertBuffer.get()); m_shader->BindIndexBuffer(m_indexBuffer.get()); m_shader->SetPropertyTextureCube("SkyMap", m_skyMap); m_shader->Bind(); m_shader->SetPass(0); m_shader->DrawIndexed(m_indexBuffer->IndexCount(), 0, 0); } } }
true
b5ed943815c505eabdcc1a874dc1882297b05a4f
C++
MagicaQuartet/algorithm
/baekjoon/1786.cpp
UTF-8
1,339
3.09375
3
[]
no_license
#include<iostream> #include<string> #include<vector> using namespace std; string T, P; vector<int> getPartialMatch(const string &P) { int m = P.size(); vector<int> pi(m, 0); int matched = 0; for (int i=1; i<m; i++) { while(matched > 0 && P[i] != P[matched]) { matched = pi[matched-1]; } if (P[i] == P[matched]) { matched++; pi[i] = matched; } } return pi; } vector<int> KMP(const string &T, const string &P) { int n = T.size(), m = P.size(); vector<int> ret; vector<int> pi = getPartialMatch(P); int matched = 0; for (int i=0; i<n; i++) { while(matched > 0 && T[i] != P[matched]) { matched = pi[matched-1]; } if (T[i] == P[matched]) { matched++; if (matched == m) { ret.push_back(i-m+1); matched = pi[matched-1]; } } } return ret; } int main() { cin.sync_with_stdio(false); cin.tie(0); getline(cin, T); getline(cin, P); vector<int> ret = KMP(T, P); cout << ret.size() << endl; for (auto i : ret) { cout << i+1 << " "; } return 0; } /* T, P를 제외한 모든 변수를 지역변수로 선언하고 각 함수의 인자와 반환값만 다른데 내가 구현한 코드는 틀리고 종만북 코드 형식을 따른 코드는 통과가 된다. 도대체 왜지...??? */
true
520da2b419f4551c77d0966c42927120332df4c0
C++
rayhan1099/cpp_Code_Semester_2_3
/postfix.cpp
UTF-8
2,378
2.984375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { string temp; cin>>temp; temp+=')'; string a=""; vector<char>amt; int co=0; stack<char>am; am.push('('); amt.push_back('('); co++; cout<<co<<": Stack: "<<'('<<endl; cout<<"Expression: "<<endl; int i=0; int j=0; for(i=0;i<temp.length();i++) { if((temp[i]>='A' and temp[i]<'Z') or (temp[i]>='a' and temp[i]<='z') or (temp[i]>='0' and temp[i]<='9')) { a+=temp[i]; } else if(temp[i]=='(') { am.push(temp[i]); amt.push_back(temp[i]); } else if(temp[i]=='+' or temp[i]=='-' or temp[i]=='*' or temp[i]=='/' or temp[i]=='^') { while(!am.empty()) { if(am.top()=='^') { a+=am.top(); am.pop(); amt.pop_back(); } else if((am.top()=='*' or am.top()=='/') and temp[i]!='^') { a+=am.top(); am.pop(); amt.pop_back(); } else if((am.top()=='+' or am.top()=='-') and temp[i]!='^' and temp[i]!='*' and temp[i]!='/') { a+=am.top(); am.pop(); amt.pop_back(); } else { am.push(temp[i]); amt.push_back(temp[i]); break; } } } else if(temp[i]==')') { while(!am.empty() and am.top()!='(') { a+=am.top(); am.pop(); amt.pop_back(); } am.pop(); amt.pop_back(); } co++; string s(amt.begin(),amt.end()); cout<<co<<": Stack: "<<s<<endl; cout<<"Expression: "<<a<<endl; } std::cout<<"Postfix Notation: "<<a<<endl; return 0; }
true
95f8cb6726e0ab9b350ef7470a32d83bc060becd
C++
chihyang/CPP_Primer
/chap13/Page545_rvaluereference.cpp
UTF-8
646
3.296875
3
[ "Apache-2.0" ]
permissive
#include <iostream> void foo(int&&) {std::cout << "void foo(int&&)" << std::endl;} void foo(int&) {std::cout << "void foo(int&)" << std::endl;} int main() { int i = 0; foo(2); foo(i); foo(std::move(i)); return 0; } // Note: lvalue and rvalue reference can be used to overload function. Because // they DO match different arguments. Compare this with Exer13_53_overload.cpp, // we can find that overloaded functions must be able to be passed different // arguments. If two functions with the same name can be passed completely // identical arguments, they will cause ambiguous call. Thus match rules on page // 245 won't work.
true
d4458b22f557808ed8168719ef298d2d95d6ee03
C++
VipulRaj-123/DSA
/Trees/univalued binary tree.cpp
UTF-8
610
2.8125
3
[]
no_license
class Solution { public: map<int,int>mp; bool isUnivalTree(TreeNode* root) { int c=0,count=0; if(root){ queue<TreeNode*>q; q.push(root); while(!q.empty()){ TreeNode* temp=q.front(); q.pop(); mp[temp->val]++; if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); } if(mp.size()==1) return true; return false; } return true; } };
true
563f115bc6782332705a046289cce21d8d64d3f2
C++
Jasonzj/leetcode
/cpp/257.cpp
UTF-8
1,597
3.515625
4
[]
no_license
/* * @lc app=leetcode.cn id=257 lang=cpp * * [257] 二叉树的所有路径 */ // @lc code=start /** * 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<string> binaryTreePaths(TreeNode* root) { if (!root) return {}; vector<string> res; stack<pair<TreeNode*, string>> s; s.push({root, ""}); while (!s.empty()) { auto cur = s.top(); auto node = cur.first; auto path = cur.second; s.pop(); path += to_string(node->val); if (!node->right && !node->left) { res.push_back(path); } if (node->right) s.push({node->right, path + "->"}); if (node->left) s.push({node->left, path + "->"}); } return res; } }; // @lc code=end class Solution { void preOrder(TreeNode* root, vector<string> &res, string path) { if (!root) return; path += to_string(root->val); if (!root->left && !root->right) { res.push_back(path); } if (root->left) preOrder(root->left, res, path + "->"); if (root->right) preOrder(root->right, res, path + "->"); } public: vector<string> binaryTreePaths(TreeNode* root) { if (!root) return {}; vector<string> res; preOrder(root, res, ""); return res; } };
true
57ea9eb2d07aebb4baeccf980e5bcb735f680835
C++
mgalang229/Codeforces-1594A-Consecutive-Sum-Riddle
/sol.cpp
UTF-8
582
3
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int tt; cin >> tt; while (tt--) { long long n; cin >> n; // view the image in this repository for better understanding // since negative numbers are included, we can simply include the negative // equivalent of the numbers in the range from 'l' to 'r' (inclusive) and not // include the negative equivalent of 'n' so that every pair would cancel each // other out and leave 'n' behind as the final answer cout << -(n - 1) << " " << n << '\n'; } return 0; }
true
ae9e3e88d332099af028fc2533fe936ae5a30297
C++
ujjaldas1997/Competitive-programming
/ksmallest_pair.cpp
UTF-8
624
3.09375
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; void ksmall_pair(vector<int> A, vector<int> B, int k){ int n1 = A.size(), n2 = B.size(); vector<int> index(n1, 0); for(int x = 0; x < k; ++x){ int pos = index[0], min_sum = INT_MAX; for(int i = 0; i < n1; ++i) if(A[i] + B[index[i]] < min_sum and index[i] < n2){ min_sum = A[i] + B[index[i]]; pos = i; } cout << A[pos] << "\t" << B[index[pos]] << endl; ++index[pos]; } return; } int main() { vector<int> A{1, 3}, B{2, 4, 5}; ksmall_pair(A, B, 3); return 0; }
true
7f345925c8060574375bde31f3761314d1af1bf3
C++
WhiZTiM/coliru
/Archive2/8f/686e7da5e07731/main.cpp
UTF-8
2,148
3.421875
3
[]
no_license
#include <iostream> #include <algorithm> #include <wchar.h> enum type { REG_SZ, REG_EXPAND_SZ, REG_MULTI_SZ } ; // dummy values template < typename C > bool print_byte_size( const C* lpData, type dwType ) { auto p = lpData ; switch(dwType) { case REG_SZ: case REG_EXPAND_SZ: while( *p++ ) ; break ; case REG_MULTI_SZ: while( *p++ || *p++ ) ; break ; default: return false ; } std::ptrdiff_t data_size_in_bytes = ( p - lpData ) * sizeof(*lpData) ; return std::cout << data_size_in_bytes << ' ' ; } template < typename C > bool print_byte_size2( const C* lpData, std::size_t n, type dwType ) { std::size_t nchars ; std::ptrdiff_t data_size_in_bytes ; switch(dwType) { case REG_SZ: case REG_EXPAND_SZ: nchars = std::find( lpData, lpData+n, 0 ) - lpData ; data_size_in_bytes = ( nchars + 1 ) * sizeof(C) ; break ; case REG_MULTI_SZ: nchars = std::adjacent_find( lpData, lpData+n, []( C a, C b ) { return !a && !b ; } ) - lpData ; data_size_in_bytes = ( nchars + 2 ) * sizeof(C) ; break ; default: return false ; } return std::cout << data_size_in_bytes << ' ' ; } template < typename STR > void test( const STR& str ) { std::cout << "size of char type is " << sizeof(*str) << " => REGSZ: " ; print_byte_size( str, REG_SZ ) ; print_byte_size2( str, sizeof(str), REG_SZ ) ; std::cout << " REG_MULTI_SZ: " ; print_byte_size( str, REG_MULTI_SZ ) ; print_byte_size2( str, sizeof(str), REG_MULTI_SZ ) ; std::cout << '\n' ; } int main() { const char str[] = "abcdefgh\0ijk\0lmn\0opqr\0stuv\0wxyz\0\0!!!!" ; test(str) ; const char16_t str16[] = u"abcdefgh\0ijk\0lmn\0opqr\0stuv\0wxyz\0\0!!!!" ; test(str16) ; const wchar_t wstr[] = L"abcdefgh\0ijk\0lmn\0opqr\0stuv\0wxyz\0\0!!!!" ; test(wstr) ; const char32_t str32[] = U"abcdefgh\0ijk\0lmn\0opqr\0stuv\0wxyz\0\0!!!!" ; test(str32) ; }
true
84c68e2650b706fad4124633776f2d6d8b171304
C++
adtag4/689-HW2
/src/Logger.cpp
UTF-8
1,291
3.359375
3
[]
no_license
// Logger.cpp #include "Logger.h" #include <queue> #include <thread> #include <iostream> #include <fstream> #include <chrono> #include <ctime> Logger::Logger() : Logger("log.log") { } Logger::Logger(std::string filename) : run_(true) { logFile_.open(filename); auto time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); logFile_ << "STARTING LOG AT: " << ctime(&time) << std::endl << std::endl; std::thread logThread(&Logger::main, this); // start logging thread logThread.detach(); // don't need to keep track - can shutdown with shutdown() on Logger object } void Logger::shutdown() { run_ = false; } void Logger::main() { while(run_) { while(!toWrite_.empty()) // stuff to write - and ensured to write (b/c check for run_ is outside) { auto item = toWrite_.front(); toWrite_.pop(); // write "TIME: MSG" auto time = std::chrono::system_clock::to_time_t(item.second); logFile_ << ctime(&time) << ": " << item.first << std::endl; } // don't need to burn all the cycles std::this_thread::sleep_for(std::chrono::milliseconds(100)); } // clean up logFile_.close(); } void Logger::log(std::string entry) { // add time auto x = std::make_pair(entry, std::chrono::system_clock::now()); toWrite_.push(x); // add to queue }
true
f2b04787c446dc87373d1329844ed0d1f6e3f55d
C++
ireullin/NetworkScanner
/src/TTLMap.h
BIG5
2,791
2.875
3
[]
no_license
#ifndef __TTLMAP__ #define __TTLMAP__ typedef struct { std::string OS; std::string Ver; }TTLInfo; class TTLMap { private: typedef std::tr1::shared_ptr<TTLInfo> TTLInfoPtr; typedef std::vector<TTLInfoPtr> ArrayTTL; typedef Dictionary2<int,ArrayTTL*> MapTTL; MapTTL m_icmp; MapTTL m_tcpudp; void Push(MapTTL& map, int ttl, const std::string& os, const std::string& ver); public: TTLMap(); ~TTLMap(); std::string IcmpInfo(int ttl); std::string TcpUdpInfo(int ttl); }; TTLMap::TTLMap() { std::string _filename = g_app.AbsolutePath() + "/ttl.prn"; std::ifstream _if( _filename.c_str() ); if(!_if.good()) throw FRAME_EXPCEPTION_1("open index.html failed"); char _buff[1024]; memset(_buff, 0, sizeof(_buff)); while(_if.getline(_buff, sizeof(_buff))) { StringPlus::SplitString _sp(_buff, ';'); int _ttl = atoi( StringPlus::Trim(_sp[3]).c_str()); std::string _type = StringPlus::Trim(_sp[2]); std::string _ver = StringPlus::Trim(_sp[1]); std::string _os = StringPlus::Trim(_sp[0]); if(_type=="ICMP") // uicmp Push(m_icmp, _ttl, _os, _ver); else if(_type.find("ICMP")==std::string::npos) // Sicmp Push(m_tcpudp, _ttl, _os, _ver); else // icmp]L { Push(m_icmp, _ttl, _os, _ver); Push(m_tcpudp, _ttl, _os, _ver); } } _if.close(); } TTLMap::~TTLMap() { for(m_icmp.Begin(); !m_icmp.End(); ++m_icmp) { ArrayTTL* _tmp = m_icmp.Value(); SAFE_DELETE(_tmp); } for(m_tcpudp.Begin(); !m_tcpudp.End(); ++m_tcpudp) { ArrayTTL* _tmp = m_tcpudp.Value(); SAFE_DELETE(_tmp); } } void TTLMap::Push(MapTTL& map, int ttl, const std::string& os, const std::string& ver) { ArrayTTL* _arr = NULL; if(map.ContainKey(ttl)) _arr = map[ttl]; else { _arr = new ArrayTTL(); map.Add(ttl, _arr); } TTLInfoPtr _infoptr(new TTLInfo()); _infoptr->OS = os; _infoptr->Ver = ver; _arr->push_back(_infoptr); } std::string TTLMap::IcmpInfo(int ttl) { if(!m_icmp.ContainKey(ttl)) return "unknown"; std::stringstream _ss; ArrayTTL* _arr = m_icmp[ttl]; for(int i=0; i<_arr->size(); i++) { _ss << _arr->at(i)->OS; if( _arr->at(i)->Ver != "") _ss << "(" << _arr->at(i)->Ver << ")"; if(_arr->size()-1 != i) _ss << "<br/>"; } return _ss.str(); } std::string TTLMap::TcpUdpInfo(int ttl) { std::stringstream _ss; if(!m_tcpudp.ContainKey(ttl)) return "unknown"; ArrayTTL* _arr = m_tcpudp[ttl]; for(int i=0; i<_arr->size(); i++) { _ss << _arr->at(i)->OS; if( _arr->at(i)->Ver != "") _ss << "(" << _arr->at(i)->Ver << ")"; if(_arr->size()-1 != i) _ss << "<br/>"; } return _ss.str(); } TTLMap g_ttlmap; #endif
true
6c0ba4b10aa5b3cbb0d0587307d5ab6bf57b43bc
C++
humeafo/metaSMT
/toolbox/sortnets/Level.hpp
UTF-8
1,765
2.859375
3
[ "MIT" ]
permissive
#pragma once #include <metaSMT/frontend/Logic.hpp> #include <boost/multi_array.hpp> using namespace metaSMT::logic; struct Level { std::vector<predicate> vars; Level(unsigned size) { for (unsigned i = 0; i < size; i++) { vars.push_back( new_variable() ); } } predicate & operator[] (unsigned i) { return vars[i]; } template <typename Context> typename Context::result_type is_sorted(Context & ctx) { //std::cout << "is_sorted called\n"; typename Context::result_type ret = evaluate(ctx, True); for (unsigned i = 1; i < vars.size(); i++) { ret = evaluate(ctx, And(ret, implies(vars[i-1], vars[i]) )); } return ret; } template <typename Context> typename Context::result_type equal_to(Context & ctx, std::string const & val) { typename Context::result_type ret = evaluate(ctx, True); for (unsigned i = 0; i < vars.size(); i++) { if(val[i] == '1') { ret = evaluate(ctx, And(ret, vars[i] )); } else { ret = evaluate(ctx, And(ret, Not(vars[i]) )); } } return ret; } template <typename Context> void print_assignment(std::ostream& out, Context & ctx) { for (unsigned i = 0; i < vars.size(); i++) { bool b = read_value(ctx, vars[i]); out << b; } out << '\n'; } template <typename Context> void print(std::ostream& out, Context & ctx) { print_assignment(out, ctx); } template <typename Context> std::string assignment(Context & ctx) { std::string ret(vars.size(), '-'); for (unsigned i = 0; i < vars.size(); i++) { bool b = read_value(ctx, vars[i]); ret[i] = b ? '1' : '0'; } return ret; } };
true
312b5d93849e43b9545dc57e3a2a5cd34bdde6dc
C++
Double95/DoubleRPG
/menuCombattre.cpp
UTF-8
1,184
3.21875
3
[]
no_license
#include "menuCombattre.h" using namespace std; void menuCombattre(Personnage &joueur) { int choixMenu(0); bool continuerMenu(true); do { joueur.afficherEtat(1); cout << "1. Retour | VIES | DEGATS | GAINS OR | GAINS XP |" << endl; cout << "2. ELFE >-------------| 100 | 0-4 | 0-30 | 0-50 |" << endl; cout << "3. OGRE >-------------| 100 | 0-12 | 0-50 | 0-70 |" << endl; cout << "4. GEANT >------------| 100 | 0-30 | 0-100 | 0-100 |" << endl; cout << endl << "Contre qui ce battre ? : "; cin >> choixMenu; switch(choixMenu) { case 1: // RETOUR continuerMenu = false; break; case 2: // ELFE 4 DEGATS combat(joueur, 1); break; case 3: // OGRE combat(joueur, 2); break; case 4: // GEANT combat(joueur, 3); break; default: choixMenu = 0; break; } }while(continuerMenu); }
true
418c3b8595424dc96d72a1cd66645b96c3fed00d
C++
mdzobayer/Problem-Solving
/Codeforces/1113 A. Sasha and His Trip.cpp
UTF-8
453
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n, v, tank = 0, need = 0, cost = 0, tmp; cin >> n >> v; if(n - 1 <= v) { cout << n - 1 << endl; return (0); } for (int i = 1; i <= n - v; ++i) { //cout << i << " " << tank << endl; if ( tank < v) { cost += (v - tank) * i; tank = v; } --tank; } cout << cost << endl; return (0); }
true
292ee0ea9177326c9e7693dee49c28c8d857557a
C++
L4v/sfml_game
/_src/state.cpp
UTF-8
987
2.8125
3
[]
no_license
#include "state.hpp" State::State(GameDataRef data) : mData(data), quit(false), mPaused(false), mKeytime(0.f), mKeytimeMax(10.f) { } State::~State(){} // Getters and setters const bool& State::getQuit() const{ return this->quit; } const bool State::getKeytime(){ if(this->mKeytime >= this->mKeytimeMax){ this->mKeytime = 0.f; return true; } return false; } // Functions void State::endState(){ this->quit = true; } void State::pauseState(){ this->mPaused = true; } void State::resumeState(){ this->mPaused = false; } void State::updateMousePositions(){ this->mousePosScreen = sf::Mouse::getPosition(); this->mousePosWindow = sf::Mouse::getPosition(*this->mData->window); this->mousePosView = this->mData->window->mapPixelToCoords( sf::Mouse::getPosition(*this->mData->window)); } void State::updateKeytime(const float& dt){ if(this->mKeytime < this->mKeytimeMax) this->mKeytime += 50.f * dt; }
true
8f5d5d9ee03bbad6a1cdae715d97ec7c6cccfcf6
C++
KeesBlokland/Arduino
/DS1820/Freezer/KB_FreezerPacketReceiver/KB_Freezer_Packet_Receiver.ino
UTF-8
2,741
2.75
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
/* Reading data, nothing fancy, just something that makes sure the Tx is running and sending it's stuff You can run this code on a Jeelink, and wathc the data on a putty connection. Set putty to listen on Comx and baudrate accordingly. */ #include <JeeLib.h> //https://github.com/jcw/jeelib // Define the data structure of the packet to be received. Should be similar to the transmitting side! typedef struct { int power, pulse, Lipo, misc2; } PayloadTX; // Create a variable to hold the received data of the defined structure . PayloadTX emontx; typedef struct { int gasPulse, gasPulseTime,DreamOn ; } PayloadGas; // need to calculate usage locally PayloadGas emongas; typedef struct {byte hour, min, sec, freeRam ;} PayloadEmonGLCD; // trying to se ewhat the GLCD is doing. PayloadEmonGLCD emonglcd ; typedef struct { float T1, T2, T3; } PayloadTmp; // can't be an int, since data is xx.x PayloadTmp montmp; void setup () { Serial.begin(9600); Serial.println("File: Packet_Receiver 28 Nov"); rf12_initialize(15,RF12_868MHZ,210); // NodeID, Frequency, Group } void loop () { if (rf12_recvDone() && rf12_crc == 0 && (rf12_hdr & RF12_HDR_CTL) == 0) { int node_id = (rf12_hdr & 0x1F); // Emontx node id is set to 10 switch (node_id){ // Power node id is set to 10 /* case 9: emongas = *(PayloadGas*) rf12_data; Serial.print ("Gas: "); Serial.println(emongas.DreamOn); Serial.print ("TimeBetweenPulses: "); Serial.print(emongas.gasPulseTime/10); Serial.println(emongas.gasPulseTime%10); break; case 10: emontx = *(PayloadTX*) rf12_data; Serial.print("Power:"); Serial.print(emontx.power); Serial.print(" Pulses:"); Serial.println(emontx.pulse); break ; case 13: emonglcd = *(PayloadEmonGLCD*) rf12_data; Serial.print("GLCD alive at "); Serial.print(emonglcd.hour); Serial.print(":"); Serial.print(emonglcd.min); Serial.print(":"); Serial.print(emonglcd.sec); Serial.print(". Mem "); Serial.println(emonglcd.freeRam); break; case 15: Serial.println("Nanode Transmission"); break; */ case 16: montmp = *(PayloadTmp*) rf12_data; // Serial.println ("DS1820's calling"); //removed these statements to get a clean logfile. Use putty to log the data. // Serial.print(":"); Serial.print(montmp.T1); Serial.print(":"); Serial.print(montmp.T2); Serial.print(":"); Serial.println(montmp.T3); break; } } }
true
4270d25836639aa56c1bb5d15ccd0b4f42392838
C++
MananKGarg/Placements
/CSES Problem Set/Minimizing Coins.cpp
UTF-8
817
2.9375
3
[]
no_license
/* Basic DP. DP array initialisation is important. Initialise all the values to INT_MAX except for dp[0]. Initialise dp[0] = 0. */ #include <bits/stdc++.h> using namespace std; typedef long long ll; void solve(){ ll n,x; cin >> n >> x; vector <ll> coins; for(ll i = 0; i < n; i++){ ll e; cin >> e; coins.push_back(e); } vector <ll> dp(x+1,INT_MAX); ll zero = 0; dp[0] = zero; for(ll i = 1; i < x+1; i++){ for(ll j = 0; j < coins.size(); j++){ if(i >= coins[j]){ dp[i] = min(dp[i],1 + dp[i - coins[j]]); } } } if(dp[x] == INT_MAX) { cout << -1; } else{ cout << dp[x]; } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); solve(); }
true
cdebf476781ffdc20f3d29efbe12745f517bf86f
C++
DarkStar1997/ImageProcessingLab
/src/test12.cpp
UTF-8
451
2.6875
3
[]
no_license
#include <opencv2/opencv.hpp> #include <iostream> #include <string> int main() { std::string filename; std::cin >> filename; cv::Mat img = cv::imread(filename); cv::Mat kernel = cv::Mat::ones(cv::Size(5, 5), CV_8U); cv::Mat erode, dilate; cv::erode(img, erode, kernel, cv::Point(), 10); cv::imshow("eroded", erode); cv::dilate(img, dilate, kernel, cv::Point(), 10); cv::imshow("dilated", dilate); cv::waitKey(); }
true
2f29575bfb987fa12df1fd68d25419e92f08b7f1
C++
varun431/Basic-Algorithms
/Highest_power_of_prime_in_factorial.cpp
UTF-8
421
2.859375
3
[]
no_license
#include <assert.h> #include <bits/stdc++.h> using namespace std; int answer[32]; void toBase(int n, int b, int* answer) { assert(b > 1); int q = n; int k = 0; while (q != 0) { answer[k] = q % b; q /= b; cout<<answer[k]<<"\t"; ++k; } } int main() { int answer[32]; int n = 100; int b = 3; toBase(n, b, answer); return 0; }
true
8e8d2d624cb477123f2851a543fadf84494a9f92
C++
Papa-Victor/8IAR125-ProjetRaven
/VS2015/Buckland_Chapter7 to 10_Raven/TeamManager.h
UTF-8
1,489
2.921875
3
[]
no_license
#ifndef TEAM_MANAGER_H #define TEAM_MANAGER_H #include "Team.h" #include "Raven_Game.h" #include <array> enum teams { RED, BLUE, GREEN }; class TeamManager { private: Raven_Game* game; TeamManager(Raven_Game* game); static TeamManager* instance; std::array<Team*, 3> m_Teams; public: ~TeamManager() {} TeamManager(const TeamManager&) = delete; TeamManager& operator=(const TeamManager&) = delete; static TeamManager* Instance(Raven_Game* game); template <class T> void AddTeam(teams colour); template <class T> void AddTeam(teams colour, Raven_Game* game); void RemoveTeam(teams colour) { delete m_Teams[colour]; m_Teams[colour] = NULL; } void AddBot(teams colour, Raven_Bot* bot); void RemoveBot(teams colour, Raven_Bot* bot); void NewWorldBot(Raven_Bot* addedBot); void BotWorldRemoval(Raven_Bot* bot); void UpdateTargetting(); void SetLeader(teams team, Raven_Bot* bot); void RenderTeamCircles(); Vector2D GetDroppedWeaponPosition(int team, int weaponType); void TryDroppedWeapons(std::list<Raven_Bot*> botList); void RenderDroppedWeapons(); void OnBotDeath(Raven_Bot* bot); }; #endif // !TEAM_MANAGER_H template<class T> inline void TeamManager::AddTeam(teams colour) { if (m_Teams[colour] != NULL) { delete m_Teams[colour]; } m_Teams[colour] = new T(); } template<class T> inline void TeamManager::AddTeam(teams colour, Raven_Game * game) { if (m_Teams[colour] != NULL) { delete m_Teams[colour]; } m_Teams[colour] = new T(game); }
true
8297298904fcab332562e626f46f63b33cccb6dc
C++
xiuwenliu/FiCoMaL
/CLHY_Sensor/CLHY_Sensor.ino
UTF-8
1,487
2.8125
3
[]
no_license
/* author : hymen81 Note : This code was depend on HX711 library */ //SPI lib #include <SPI.h> //Weight sensor #include <HX711.h> //Weight sensor lib pindefine HX711 hx(22, 24); unsigned long thisMillis = 0; unsigned long lastMillis = 0; double weight = 0; //Button cpoy from Google // Variables will change: int buttonPushCounter = 0; // counter for the number of button presses int buttonState = 0; // current state of the button int lastButtonState = 0; // previous state of the button void setup() { Serial.begin(9600); //Button pin pinMode(7, INPUT); // disable SD SPI pinMode(4, OUTPUT); digitalWrite(4, HIGH); delay(2000); } //Get weight from sensor void GetWeight() { weight = hx.read(); weight /= 100; Serial.println(weight); } //Get Button is down or not void GetButtonStates() { // read the pushbutton input pin: buttonState = digitalRead(7); // compare the buttonState to its previous state if (buttonState != lastButtonState) { // if the state has changed, increment the counter if (buttonState == HIGH) { // if the current state is HIGH then the button // wend from off to on: buttonPushCounter++; //Using string to notify tool when button down Serial.println("send"); } else { } delay(50); } // save the current state as the last state, //for next time through the loop lastButtonState = buttonState; } void loop() { GetWeight(); GetButtonStates(); }
true
ffee05fc64cfd6dc6722ecfb193dae7a2fee0b5a
C++
rum2mojito/Leetcode
/171.cpp
UTF-8
267
3.125
3
[]
no_license
// 171. Excel Sheet Column Number class Solution { public: int titleToNumber(string s) { int res = 0 , l = 0; for (int i=s.length()-1;i>=0;i--) { res += pow (26,l)*(s[i]-'A'+1); l++; } return res; } };
true
f8575fc075366eda704e7d2cf1601b561da8cf74
C++
zhangxiaoya/LeetCodeCPP
/solution026.cpp
UTF-8
552
2.796875
3
[]
no_license
#include "solution026.h" #include <algorithm> Solution026::Solution026() { } int Solution026::removeDuplicates(vector<int> &nums) { /* if(nums.size() == 0) return 0; if(nums.size() == 1) return 1; vector<int>::iterator it1,it2; it1 = nums.begin(); it2 = it1 + 1; int len = 1; for(;it2 != nums.end();++it2) { if(*it1 != *it2) { *(++it1) = *it2; ++len; } } return len; */ return distance(nums.begin(),unique(nums.begin(),nums.end())); }
true
242f7422c237eb45c409568eee2b5be30305840c
C++
Floral/Study
/C++/C++Primer_5th_Code/Chapter8/practice8_13.cpp
UTF-8
828
3.171875
3
[]
no_license
#include<iostream> #include<fstream> #include<sstream> #include<string> #include<vector> using namespace::std; struct PersonInfo { /* data */ string name; vector<string> phones; }; int main() { string line,word; vector<PersonInfo> people; fstream fs("chinese-3500.txt"); while (getline(fs,line)) { /* code */ stringstream ss(line); PersonInfo info; ss >> info.name; while (ss>>word) { /* code */ info.phones.push_back(word); } people.push_back(info); } for (auto &i : people) { std::cout<<i.name+" "; ostringstream oss; for (auto &j : i.phones) { oss<<j+" "; } oss<<endl; cout<<oss.str(); } return 0; }
true
b56d116fd6846a09a79b5555bd17d9efada3669f
C++
OldRiverChen/DNM
/series/data/distr/Distr.h
UTF-8
1,927
3.296875
3
[]
no_license
#ifndef _A_DISTR_ #define _A_DISTR_ #include <string> #include <iostream> #include <vector> #include <map> #include "..\Data.h" using namespace std; enum DistrType { BINNED_DOUBLE, BINNED_INT, BINNED_LONG, QUALITY_DOUBLE, QUALITY_INT, QUALITY_LONG }; template<class T,class V> class Distr :public Data { public: T binSize; V* values; public: Distr(string name,T& binSize,V* values); public: T getBinSize(); V* getValues(); public: static string getDistrTypeString(DistrType type); public: /** * outputs the contents stored in this distribution */ virtual void print(); /** * writes the contents of the distribution to the specified file in the * specified directory. * * @param dir * directory where to store the output * @param filename * file where to write the data to * @throws IOException */ virtual void write(string dir, string filename); virtual string getDistrType(); }; template<class T, class V> Distr<T, V>::Distr(string name, T& binSize, V * values) :Data(name) { this->binSize = binSize; this->values = values; } template<class T, class V> T Distr<T, V>::getBinSize() { return binSize; } template<class T, class V> V * Distr<T, V>::getValues() { return values; } template<class T, class V> string Distr<T, V>::getDistrTypeString(DistrType type) { string rs(""); switch (type) { case BINNED_DOUBLE: rs = "BINNED_DOUBLE"; break; case BINNED_INT: rs = "BINNED_INT"; break; case BINNED_LONG: rs = "BINNED_LONG"; break; case QUALITY_DOUBLE: rs = "QUALITY_DOUBLE"; break; case QUALITY_INT: rs = "QUALITY_INT"; break; case QUALITY_LONG: rs = "QUALITY_LONG"; break; } return rs; } template<class T, class V> void Distr<T, V>::print() { } template<class T, class V> void Distr<T, V>::write(string dir, string filename) { } template<class T, class V> string Distr<T, V>::getDistrType() { return string(""); } #endif
true
ccfc87c6ad987fa014d233fe855155908ccf2a1b
C++
Jackey65536/LeetCode
/LeetCode/learn10/datastruct.cpp
UTF-8
13,921
3.421875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <algorithm> #include <cstring> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #define TRIE_MAX_CHAR_NUM 26 struct TrieNode { TrieNode* child[TRIE_MAX_CHAR_NUM]; bool is_end; TrieNode() : is_end(false) { for (int i = 0; i < TRIE_MAX_CHAR_NUM; i++) { child[i] = 0; } } }; void preorder_trie(TrieNode* node, int layer) { for (int i = 0; i < TRIE_MAX_CHAR_NUM; i++) { if (node->child[i]) { for (int j = 0; j < layer; j++) { printf("---"); } printf("%c", i + 'a'); if (node->child[i]->is_end) { printf("(end)"); } printf("\n"); preorder_trie(node->child[i], layer + 1); } } } void get_all_word_from_trie(TrieNode* node, std::string& word, std::vector<std::string>& word_list) { for (size_t i = 0; i < TRIE_MAX_CHAR_NUM; i++) { if (node->child[i]) { word.push_back(i + 'a'); if (node->child[i]->is_end) { word_list.push_back(word); } get_all_word_from_trie(node->child[i], word, word_list); word.erase(word.length() - 1, 1); } } } // 字典树 class TrieTree { public: TrieTree() {} ~TrieTree() { for (int i = 0; i < _node_vec.size(); i++) { delete _node_vec[i]; } } // 将word插入至trie void insert(const char* word) { TrieNode* ptr = &_root; while (*word) { int pos = *word - 'a'; if (!ptr->child[pos]) { ptr->child[pos] = new_node(); } ptr = ptr->child[pos]; word++; } ptr->is_end = true; } // 搜索trie中是否存在word bool search(const char* word) { TrieNode* ptr = &_root; while (*word) { int pos = *word - 'a'; if (!ptr->child[pos]) { return false; } ptr = ptr->child[pos]; word++; } return ptr->is_end; } // 确认trie中是否有前缀prefix的单词 bool startsWith(const char* prefix) { TrieNode* ptr = &_root; while (*prefix) { int pos = *prefix - 'a'; if (!ptr->child[pos]) { return false; } ptr = ptr->child[pos]; prefix++; } return true; } TrieNode* root() { return &_root; } private: TrieNode* new_node() { TrieNode* node = new TrieNode(); _node_vec.push_back(node); return node; } // 保存所有node,析构时统一销毁 std::vector<TrieNode*> _node_vec; TrieNode _root; }; /** * 设计一个数据结构,支持如下操作: * 1、添加单词 * 2、搜索单词 * 搜索字符'a'~'z'或'.' */ class WordDictionary { public: WordDictionary(){}; void addWord(std::string word) { _trie_tree.insert(word.c_str()); } bool search(std::string word) { return search_trie(_trie_tree.root(), word.c_str()); } bool search_trie(TrieNode* node, const char* word) { if (*word == '\0') { return node->is_end; } if (*word == '.') { for (int i = 0; i < TRIE_MAX_CHAR_NUM; i++) { if (node->child[i] && search_trie(node->child[i], word + 1)) { return true; } } } else { int pos = *word - 'a'; if (node->child[pos] && search_trie(node->child[pos], word + 1)) { return true; } } return false; } private: TrieTree _trie_tree; }; /** * 并查集(不相交集合):它应用于N个元素的集合求并与查询问题,在该应用场景中, * 我们通常是在开始时让每个元素构成一个单元素的集合,然后按一定顺序将属于同 * 一组的元素所在的集合合并,期间要反复查找一个元素在那个集合中。 */ class DisjointSet { public: DisjointSet(int n) { for (int i = 0; i < n; i++) { _id.push_back(i); _size.push_back(1); } _count = n; } int find(int p) { while (p != _id[p]) { _id[p] = _id[_id[p]]; p = _id[p]; } return p; } void union_(int p, int q) { int i = find(p); int j = find(q); if (i == j) { return; } if (_size[i] < _size[j]) { _id[i] = j; _size[j] += _size[i]; } else { _id[j] = i; _size[i] += _size[j]; } _count--; } void print_set() { printf("元素:"); for (int i = 0; i < _id.size(); i++) { printf("%d ", i); } printf("\n"); printf("集合:"); for (int i = 0; i < _id.size(); i++) { printf("%d ", _id[i]); } printf("\n"); } int count() { return _count; } private: std::vector<int> _id; std::vector<int> _size; // 集合大小 int _count; // 集合个数 }; /** * 线段树:一种平衡二叉树(完全二叉树),它将一个线段区间划分成一些单元区间。 * 对于线段树中的每一个非叶子节点[a, b],它的左儿子表示的区间为[a, (a+b)/2], * 右儿子表示的区间为[(a+b)/2+1, b],最后的叶子节点数目为N,与数组下标对应。 * 线段树一版包括建立、查询、插入、更新等操作,建立规模为N的时间复杂度是O(NlogN), * 其他操作时间复杂度为O(logN) */ /** * value:区间和数组 * nums:原始数组 * pos:当前线段对应下标,即二叉树的层数 */ void build_segment_tree(std::vector<int>& value, std::vector<int>& nums, int pos, int left, int right) { if (left == right) { value[pos] = nums[left]; return; } int mid = (left + right) / 2; build_segment_tree(value, nums, pos * 2 + 1, left, mid); build_segment_tree(value, nums, pos * 2 + 2, mid + 1, right); // 左孩子区间+右孩子区间 value[pos] = value[pos * 2 + 1] + value[pos * 2 + 2]; } void print_segment_tree(std::vector<int>& value, int pos, int left, int right, int layer) { for (int i = 0; i < layer; i++) { printf("---"); } printf("[%d %d][%d]: %d\n", left, right, pos, value[pos]); if (left == right) { return; } int mid = (left + right) / 2; print_segment_tree(value, pos * 2 + 1, left, mid, layer + 1); print_segment_tree(value, pos * 2 + 2, mid + 1, right, layer); } int sum_range_segment_tree(std::vector<int>& value, int pos, int left, int right, int qleft, int qright) { if (qleft > right || qright < left) { return 0; } if (qleft <= left && qright >= right) { return value[pos]; } int mid = (left + right) / 2; return sum_range_segment_tree(value, pos * 2 + 1, left, mid, qleft, qright) + sum_range_segment_tree(value, pos * 2 + 2, mid + 1, right, qleft, qright); } void update_segment_tree(std::vector<int>& value, int pos, int left, int right, int index, int new_value) { if (left == right && left == index) { value[pos] = new_value; return; } int mid = (left + right) / 2; if (index <= mid) { update_segment_tree(value, pos * 2 + 1, left, mid, index, new_value); } else { update_segment_tree(value, pos * 2 + 2, mid + 1, right, index, new_value); } value[pos] = value[pos * 2 + 1] + value[pos * 2 + 2]; } /** * 给定一个整数数组nums,求这个整数数组中,下标i到下标j之间的数字和(i<=j), * a[i]+a[i+1]+...+a[j]。在求和的过程中,可能需要更新数组的某个元素a[i]. */ class NumArray { public: NumArray(std::vector<int> nums) { if (nums.size() == 0) { return; } int n = nums.size() * 4; for (int i = 0; i < n; i++) { _value.push_back(0); } build_segment_tree(_value, nums, 0, 0, nums.size() - 1); _right_end = nums.size() - 1; } void update(int i, int val) { update_segment_tree(_value, 0, 0, _right_end, i, val); } int sumRange(int i, int j) { return sum_range_segment_tree(_value, 0, 0, _right_end, i, j); } private: std::vector<int> _value; int _right_end; }; class Solution { public: // 求朋友圈数 int findCircleNum(std::vector<std::vector<int> >& M) { std::vector<int> visit(M.size(), 0); int count = 0; for (int i = 0; i < M.size(); i++) { if (!visit[i]) { DFS_graph(i, M, visit); count++; } } return count; } // 并查集实现 int findCircleNum2(std::vector<std::vector<int> >& M) { DisjointSet dis(M.size()); for (int i = 0; i < M.size(); i++) { for (int j = i + 1; j < M.size(); j++) { if (M[i][j]) { dis.union_(i, j); } } } return dis.count(); } private: void DFS_graph(int u, std::vector<std::vector<int> >& graph, std::vector<int>& visit) { visit[u] = 1; for (int i = 0; i < graph[u].size(); i++) { if (graph[u][i] && !visit[i]) { DFS_graph(i, graph, visit); } } } }; void testTrieNode() { TrieNode root; TrieNode n1; TrieNode n2; TrieNode n3; root.child['a' - 'a'] = &n1; root.child['b' - 'a'] = &n2; root.child['e' - 'a'] = &n3; n2.is_end = true; TrieNode n4; TrieNode n5; TrieNode n6; n1.child['b' - 'a'] = &n4; n2.child['c' - 'a'] = &n5; n3.child['f' - 'a'] = &n6; TrieNode n7; TrieNode n8; TrieNode n9; TrieNode n10; n4.child['c' - 'a'] = &n7; n4.child['d' - 'a'] = &n8; n5.child['d' - 'a'] = &n9; n6.child['g' - 'a'] = &n10; n7.is_end = true; n8.is_end = true; n9.is_end = true; n10.is_end = true; TrieNode n11; n7.child['d' - 'a'] = &n11; n11.is_end = true; // preorder_trie(&root, 0); std::string word; std::vector<std::string> word_list; get_all_word_from_trie(&root, word, word_list); for (int i = 0; i < word_list.size(); i++) { printf("%s ", word_list[i].c_str()); } } void testTrieTree() { TrieTree tt; tt.insert("abcd"); tt.insert("abc"); tt.insert("abd"); tt.insert("b"); tt.insert("bcd"); tt.insert("efg"); printf("preorder_trie:\n"); preorder_trie(tt.root(), 0); printf("\n"); std::vector<std::string> word_list; std::string word; printf("All words:\n"); get_all_word_from_trie(tt.root(), word, word_list); for (int i = 0; i < word_list.size(); i++) { printf("%s\n", word_list[i].c_str()); } printf("\n"); printf("Search:\n"); printf("abc: %d\n", tt.search("abc")); printf("abcd: %d\n", tt.search("abcd")); printf("bc: %d\n", tt.search("ac")); printf("b: %d\n", tt.search("b")); printf("\n"); printf("ab: %d\n", tt.startsWith("ab")); printf("abc: %d\n", tt.startsWith("abc")); printf("bc: %d\n", tt.startsWith("bc")); printf("fg: %d\n", tt.startsWith("fg")); } void testWordDictionary() { WordDictionary dic; dic.addWord("bad"); dic.addWord("dad"); dic.addWord("mad"); printf("%d\n", dic.search("pad")); printf("%d\n", dic.search("bad")); printf("%d\n", dic.search(".ad")); printf("%d\n", dic.search("b..")); } void testFindCircleNum() { Solution sol; int test[][3] = { {1, 1, 0}, {1, 1, 0}, {0, 0, 1}, }; std::vector<std::vector<int> > M(3, std::vector<int>(3, 0)); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { M[i][j] = test[i][j]; } } // printf("%d\n", sol.findCircleNum(M)); printf("%d\n", sol.findCircleNum2(M)); } void testDisjointSet() { DisjointSet dis(8); dis.print_set(); printf("Union(0, 5)\n"); dis.union_(0, 5); dis.print_set(); printf("Find(0) = %d, Find(5) = %d\n", dis.find(0), dis.find(5)); printf("Find(2) = %d, Find(5) = %d\n", dis.find(2), dis.find(5)); dis.union_(2, 4); dis.print_set(); dis.union_(0, 4); dis.print_set(); printf("Find(2) = %d, Find(5) = %d\n", dis.find(2), dis.find(5)); } void testSegment() { std::vector<int> nums; for (int i = 0; i < 6; i++) { nums.push_back(i); } std::vector<int> value(24, 0); build_segment_tree(value, nums, 0, 0, nums.size() - 1); printf("segment_tree: \n"); print_segment_tree(value, 0, 0, nums.size() - 1, 0); int sum_range = sum_range_segment_tree(value, 0, 0, nums.size() - 1, 2, 4); printf("sum_range [2, 4] = %d\n", sum_range); update_segment_tree(value, 0, 0, nums.size() - 1, 2, 10); printf("segment_tree:\n"); print_segment_tree(value, 0, 0, nums.size() - 1, 0); } void testNumArray() { std::vector<int> nums; nums.push_back(1); nums.push_back(3); nums.push_back(5); NumArray num_array(nums); printf("%d\n", num_array.sumRange(0, 2)); num_array.update(1, 2); printf("%d\n", num_array.sumRange(0, 2)); } int main() { // testTrieNode(); // testTrieTree(); // testWordDictionary(); // testDisjointSet(); // testFindCircleNum(); // testSegment(); testNumArray(); return 0; }
true
f946ba3d2a8005aaa1bf599e3705c97141d423df
C++
afewvowels/CPP-PRG-02-14-Personal-Information
/PRG-2-14-Personal-Information/main.cpp
UTF-8
907
3.734375
4
[]
no_license
// // main.cpp // PRG-2-14-Personal-Information // // Created by Keith Smith on 10/6/17. // Copyright © 2017 Keith Smith. All rights reserved. // // Write a program that displays the following pieces of information, each on a separate line: // Your name // Your address, with city, state, and ZIP code // Your telephone number // Your college major // // Use only a single cout statement to display all of this information. #include <iostream> #include <string> using namespace std; int main() { // Declare constants const string STR_NAME = "Keith B. Smith"; const string STR_ADDRESS = "REDACTED"; const string STR_TELEPHONE_NUMBER = "REDACTED"; const string STR_MAJOR = "Computer Science"; // Format and output to console cout << STR_NAME << endl << STR_ADDRESS << endl << STR_TELEPHONE_NUMBER << endl << STR_MAJOR << endl; return 0; }
true
6397398dae9e766fe141d75b735621bcbec034ae
C++
rirash/vm5
/Jump.h
UTF-8
2,537
3.015625
3
[]
no_license
#ifndef JUMP_H #define JUMP_H #include "Command.h" #include "Processor.h" class Jmp : public Command //Прямой безусловный переход { public: void go_to(Processor& cpu) noexcept { cmd32 com = cpu.get_Command(); uint16_t adress; //Составной адрес, куда прыгаем //По значению, лежащему в первом операнде определяем способ определения адреса switch (cpu.get_int16(com.command16.r1)) { case 0: adress = cpu.get_int16(com.command16.r2); break; //Адрес лежит в r2 case 1: adress = cpu.get_int16(com.command16.r2) + com.off; break; //Адрес = адрес в r2 + смещение case 2: adress = com.off; //Адрес = смещению } if (com.command16.s == 0) //Вообще, размер целого операнда. Сейчас же - способ определения перехода cpu.psw.setIP(adress); //Прямой else cpu.psw.setIP(cpu.psw.getIP() + adress); //Относительный } void operator()(Processor& cpu) noexcept override { go_to(cpu); } }; //УСЛОВНЫЕ ПЕРЕХОДЫ class JmpZF : public Jmp { void operator()(Processor& cpu) noexcept override { if (cpu.psw.getZF() == 1) go_to(cpu); } }; class JmpNZF : public Jmp { void operator()(Processor& cpu) noexcept override { if (cpu.psw.getZF() == 0) go_to(cpu); } }; class JmpSF : public Jmp { void operator()(Processor& cpu) noexcept override { if (cpu.psw.getSF() == 1) go_to(cpu); } }; class JmpNSF : public Jmp { void operator()(Processor& cpu) noexcept override { if (cpu.psw.getSF() == 0) go_to(cpu); } }; //ПЕРЕХОД/ВОЗВРАТ class Call : public Jmp { void operator()(Processor& cpu) noexcept { cmd32 com = cpu.get_Command(); //Вытаскиваем и разбираем команду datatype16 t16; t16.w16.i16 = cpu.psw.getIP(); //Запоминаем адрес возврата cpu.put(t16, com.command16.r1); cpu.psw.setIP(cpu.get_uint16(com.command16.r2)); //Прыгаем по новому адресу } }; class Return : public Jmp { void operator()(Processor& cpu) noexcept { cmd32 com = cpu.get_Command(); //Разбираем команду cpu.psw.setIP(cpu.get_uint16(com.command16.r1)); //Возвращаемся по старому IP } }; #endif//! JUMP_H
true
e69b94eb85f1e35972c37a0ab9c035951d4ea0b4
C++
KrishnaKumarAgawalla/tasks.cpp
/q-4.cpp
UTF-8
410
4.09375
4
[ "MIT" ]
permissive
/* WAP to find square and cube of a number using inline function. */ #include<iostream> using namespace std; inline int square(int n){ return n*n; } inline int cube(int n){ return n*n*n; } int main(){ int number; cout<<"Number: "; cin>>number; cout<<"Square of "<<number<<" is "<<square(number)<<endl; cout<<"Cube of "<<number<<" is "<<cube(number)<<endl; return 0; }
true
6fcd84ad14ba8836792adc8b01672ea81af6cd1b
C++
k-pratyush/competitive-coding
/chars.cpp
UTF-8
706
3.015625
3
[]
no_license
#include <iostream> #include <utility> #include <stack> using namespace std; int main() { string s = "abbcccb"; int k = 3; stack<pair<char, int> > st; for(auto i: s) { if(!st.empty()) { if(st.top().first == i && st.top().second < k-1) { pair<char, int> p = st.top(); st.pop(); p.second += 1; st.push(p); } else if(st.top().first == i && st.top().second == k - 1) st.pop(); else { st.push(make_pair(i, 1)); } } else { st.push(make_pair(i, 1)); } } string res = ""; while(!st.empty()) { pair<char, int> p = st.top(); st.pop(); for(int i = 0; i < p.second; i++) { res += p.first; } } reverse(res.begin(), res.end()); cout << res << endl; }
true
b357327a1896ff625e36225c96b25062d4d092de
C++
liuq901/code
/CF/cd_145_E.cpp
UTF-8
1,847
2.53125
3
[]
no_license
#include <cstdio> #include <algorithm> using namespace std; struct tree { int l,r,four,seven,big,small; bool change; }; char s[1000010]; tree a[2100000]; void updata(int x) { if (!a[x].change) return; a[x].change=false; if (a[x].l!=a[x].r) { int ls=x<<1,rs=ls+1; a[ls].change=!a[ls].change; a[rs].change=!a[rs].change; } swap(a[x].four,a[x].seven); swap(a[x].big,a[x].small); } void update(int x) { int ls=x<<1,rs=ls+1; updata(x); updata(ls); updata(rs); a[x].four=a[ls].four+a[rs].four; a[x].seven=a[ls].seven+a[rs].seven; a[x].big=max(max(a[x].four,a[x].seven),max(a[ls].four+a[rs].big,a[ls].big+a[rs].seven)); a[x].small=max(max(a[x].four,a[x].seven),max(a[ls].seven+a[rs].small,a[ls].small+a[rs].four)); } void build(int x,int l,int r) { a[x].l=l,a[x].r=r,a[x].change=false; if (l==r) { a[x].four=s[l]=='4'; a[x].seven=s[l]=='7'; a[x].big=a[x].small=1; return; } int ls=x<<1,rs=ls+1,mid=a[x].l+a[x].r>>1; build(ls,l,mid); build(rs,mid+1,r); update(x); } void modify(int x,int l,int r) { if (a[x].l==l && a[x].r==r) { a[x].change=!a[x].change; return; } updata(x); int ls=x<<1,rs=ls+1,mid=a[x].l+a[x].r>>1; if (r<=mid) modify(ls,l,r); else if (l>mid) modify(rs,l,r); else { modify(ls,l,mid); modify(rs,mid+1,r); } update(x); } int main() { int n,Q; scanf("%d%d%s",&n,&Q,s+1); build(1,1,n); while (Q--) { scanf("%s",s); if (s[0]=='c') { updata(1); printf("%d\n",a[1].big); } else { int l,r; scanf("%d%d",&l,&r); modify(1,l,r); } } return(0); }
true
8f4b9cfe83647098c68e6e15e34388f606f2bf61
C++
turmary/smalls
/ticpp-oneex/T04/T04-07.cpp
GB18030
520
2.96875
3
[]
no_license
//: T04:T04-07.cpp //Stash25doubleֵ,ʾ //{L} CppLib #include "CppLib.h" #include "../require.h" #include <iostream> using namespace std; int const d_count = 3; // 25; int main() { Stash dStash; dStash.initialize(sizeof(double)); cout <<"input " <<d_count <<" double numbers" <<endl; double d; for (int i = 0; i < d_count; i++) { cin >>d; dStash.add(&d); } for (int i = 0; i < d_count; i++) { cout <<*(double*)dStash.fetch(i) <<endl; } dStash.cleanup(); return 0; } ///:~
true
96bbf93500c571ad9de9f3d9498af71309b0e754
C++
jonniepolkinghorn482/LeetCode
/topic/HashMap/twoSum/main.cpp
UTF-8
1,908
3.25
3
[]
no_license
/* # Copyright (c) 2020 Xinyan Han. All rights reserved. */ #include <bits/stdc++.h> #include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: /** * 双指针法,复杂度O(N) */ // vector<int> twoSum(vector<int>& nums, int target) { // vector<int> ans; // vector<int> index(nums); // int n = nums.size(); // sort(nums.begin(), nums.end()); // for (int i = 0, j = n - 1; i < j;) { // if (nums[i] + nums[j] > target) { // --j; // } else if (nums[i] + nums[j] < target) { // ++i; // } else if (nums[i] + nums[j] == target) { // for (int k = 0; k < n; ++k) { // if (i < n && index[k] == nums[i]) { // ans.push_back(k); // i = n; // } else if (j < n && index[k] == nums[j]) { // ans.push_back(k); // j = n; // } // if (i == n && j == n) break; // } // break; // } // } // return ans; // } /** * 哈希法,复杂度O(N) */ vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> hashmap; vector<int> ans; for (int i = 0; i < nums.size(); ++i) { if (hashmap.find(target - nums[i]) != hashmap.end() && hashmap[target - nums[i]] != i) { ans.push_back(hashmap[target - nums[i]]); ans.push_back(i); break; } hashmap[nums[i]] = i; } return ans; } }; int main() { vector<int> nums{2, 7, 11, 15}; int target = 9; Solution solution; vector<int> k = solution.twoSum(nums, target); return 0; }
true
0f859db04f5b4a6bf443246e3a35c3094410a77e
C++
Rextens/OpenglFiles
/Logining.cpp
UTF-8
4,090
2.6875
3
[]
no_license
#include "Logining.h" Logining::Logining() { } Logining::~Logining() { } void Logining::loadLogins(std::string logins) { std::fstream file(logins); std::string password; std::string login; std::cin >> login; std::cin >> password; if (!file) { std::cout << "Cannnot open file with player name" << std::endl; getchar(); return; } std::string line; loginNow = login; std::vector<std::string> board; while (std::getline(file, line)) { board.push_back(line); } for (unsigned int i = 0; i < board.size(); i += 2) { if (board[i] == Auxiliary::encrypt(login) && board[i + 1] == Auxiliary::encrypt(password)) { logining = !logining; break; } } } void Logining::registry(std::string wayToFile) { std::ifstream file(wayToFile); std::string line; if (!file) { std::cout << "Cannnot open file with registry" << std::endl; getchar(); return; } std::vector<std::string> board; while (std::getline(file, line)) { board.push_back(line); } std::string getLogin; std::string password; std::cin >> getLogin; std::cin >> password; for (int i = 0; i < board.size(); i += 2) { if (board[i] == Auxiliary::encrypt(getLogin)) { std::cout << "This login is existing. Please give me same else" << std::endl; getchar(); return; } } board.push_back(Auxiliary::encrypt(getLogin)); board.push_back(Auxiliary::encrypt(password)); file.close(); std::ofstream output(wayToFile); if (!output) { std::cout << "Cannnot open file" << std::endl; getchar(); exit(0); } for (unsigned int i = 0; i < board.size(); i++) { output << board[i] << std::endl; } std::error_code error; Auxiliary::createFile("C:/Game/Saves/" + getLogin, error); Auxiliary::createFile("C:/Game/Saves/" + getLogin + "/Save", error); Auxiliary::createFile("C:/Game/Saves/" + getLogin + "/Save/camera", error); Auxiliary::createFile("C:/Game/Saves/" + getLogin + "/Save/Objects", error); Auxiliary::createFile("C:/Game/Saves/" + getLogin + "/Save/Player", error); Auxiliary::createFile("C:/Game/Saves/" + getLogin + "/Save/Timers", error); Auxiliary::createFile("C:/Game/Saves/" + getLogin + "/Save/Statistics", error); output.close(); std::ofstream outputWorld; outputWorld.open("C:/Game/Saves/" + getLogin + "/Save/Objects/generateOrbs.txt"); outputWorld << 0; outputWorld.close(); outputWorld.open("C:/Game/Saves/" + getLogin + "/Save/Objects/generateWorld.txt"); outputWorld << 0; outputWorld.close(); outputWorld.open("C:/Game/Saves/" + getLogin + "/Save/Objects/howManyOrbs.txt"); outputWorld.close(); outputWorld.open("C:/Game/Saves/" + getLogin + "/Save/Objects/saveObjects.txt"); for (int i = 0; i < 21; i++) { output << "0 0 0" << std::endl; } outputWorld.close(); outputWorld.open("C:/Game/Saves/" + getLogin + "/Save/Objects/saveOrbs.txt"); outputWorld.close(); outputWorld.open("C:/Game/Saves/" + getLogin + "/Save/camera/cameraPosition.txt"); outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld.close(); outputWorld.open("C:/Game/Saves/" + getLogin + "/Save/Player/championClass.txt"); outputWorld << 1 << std::endl; outputWorld.close(); outputWorld.open("C:/Game/Saves/" + getLogin + "/Save/Player/statistics.txt"); outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld << 0 << std::endl; outputWorld.close(); outputWorld.open("C:/Game/Saves/" + getLogin + "/Save/Timers/saveTimers.txt"); outputWorld.close(); outputWorld.open("C:/Game/Saves/" + getLogin + "/Save/Statistics/statistics.txt"); outputWorld << 50; outputWorld.close(); }
true
279326b5d154b1401d5b1316295f3f0cd6a734f4
C++
RPG-18/tmdb
/src/Storage.h
UTF-8
3,778
3.078125
3
[]
no_license
#pragma once #include <ctime> #include <cstdint> #include <memory> #include <unordered_map> namespace leveldb { class DB; class Iterator; class Slice; class Comparator; class Cache; } /*! * Хранилище метрик */ class Storage { public: class Iterator; typedef size_t MetricUid; /*! * Представление ключа */ struct Key { MetricUid muid; //!< uid метрики time_t timestamp; //!< время }; /*! * Конструктор * @param dir каталог для размещения базы данных и базы метрик * @param cacheSizeMb размер блока кеша */ Storage(const std::string& dir, size_t cacheSizeMb = 16); /*! * @brief Добавление метрики. * @param name имя метрики * @return уникальный идентификатор метрики * * Добавляет метрику в базу UID'ов и возвращает UID метрики. * Если метрика уже была добавлена, то возращает UID метрики */ MetricUid addMetric(const std::string& name); /*! * Записать значение * @param muid идентификатор метрики * @param timestamp временная точка * @param value значение * @return true если нет ошибок */ bool put(MetricUid muid, time_t timestamp, double value); /*! * Получить итератор для интервала значений метрики * @param muid идентификатор метрики * @param from начало интервала * @param to конец интервала * @return итератор */ Iterator get(MetricUid muid, time_t from, time_t to); Storage(const Storage&) = delete; Storage& operator=(const Storage&) = delete; private: /*! * Инициализация базы uid метрик */ void initUID(); /*! * Инициализация данных */ void initData(); private: /*! * Текущий индекс для UID */ MetricUid m_currentIndx; /*! * Базовый каталог */ std::string m_dir; /*! * Размер блока кеша */ size_t m_cacheSizeMb; /*! * Кеш для данных */ std::shared_ptr<leveldb::Cache> m_dataCache; /*! * База UID'ов */ std::shared_ptr<leveldb::DB> m_uid; /*! * База измерений */ std::shared_ptr<leveldb::DB> m_data; /*! * Мэп метрика -> uid */ std::unordered_map<std::string, MetricUid> m_metric2uid; }; /*! * Итератор для обхода последовательности данных */ class Storage::Iterator { public: typedef std::tuple<time_t, double> Value; typedef std::shared_ptr<leveldb::Iterator> IteratorPrivate; Iterator(); Iterator(const IteratorPrivate& iter, const Key& limit); /*! * Проверка итератора на валидность * @return true если итератор валиден */ bool valid() const; /*! * Получить значение * @return кортеж <время, значение> */ Value value() const; /*! * Переход к следующему элементу */ void next(); private: IteratorPrivate m_iter; //!< итератор LevelDB Key m_limit; //!< ключ для ограничения последовательности справа };
true
571c5f0852d6aaf7f47a6fcfd8d792e784716a64
C++
njoy/interpolation
/src/interpolation/table/right/interval/IsRuntimeConstant.hpp
UTF-8
423
2.578125
3
[ "BSD-2-Clause" ]
permissive
struct IsRuntimeConstant { template< typename Parent > class Type : public Interval<Parent> { public: using Ydata = typename Parent::Ydata; protected: Ydata value; public: Ydata rightIntervalValue() const { return this->value; } template< typename... Args > Type( Ydata data, Args&&... args ) : Interval<Parent>( std::forward< Args >( args )... ), value( data ){} }; };
true
69b1ae2ee2ef62abf5927b2cec1ea19527c21785
C++
zie87/wth_woth
/projects/mtg/include/AIStats.h
UTF-8
1,107
2.546875
3
[ "BSD-3-Clause" ]
permissive
#ifndef _AISTATS_H_ #define _AISTATS_H_ #define STATS_PLAYER_MULTIPLIER 15 #define STATS_CREATURE_MULTIPLIER 10 // floats #define STATS_AURA_MULTIPLIER 0.9f #define STATS_LORD_MULTIPLIER 0.5f #include <list> #include <string> using std::list; using std::string; class Player; class MTGCardInstance; class MTGCard; class Damage; class WEvent; class AIStat { public: int source; // MTGId of the card int value; int occurences; bool direct; AIStat(int _source, int _value, int _occurences, bool _direct) : source(_source), value(_value), occurences(_occurences), direct(_direct){}; }; class AIStats { public: Player* player; string filename; list<AIStat*> stats; AIStats(Player* _player, char* filename); ~AIStats(); void load(char* filename); void save(); AIStat* find(MTGCard* card); bool isInTop(MTGCardInstance* card, unsigned int max, bool tooSmallCountsForTrue = true); void updateStatsCard(MTGCardInstance* cardInstance, Damage* damage, float multiplier = 1.0); int receiveEvent(WEvent* event); void Render(); }; #endif
true
d9e8065844eb25b44a54e55bb1c5f8ef33535649
C++
lyswty/leetcode-solutions
/202.cpp
UTF-8
361
2.828125
3
[]
no_license
class Solution { public: bool isHappy(int n) { unordered_set<int>s; while(n!=1){ int next=0; while(n){ next+=(n%10)*(n%10); n/=10; } if(s.find(next)!=s.end()) return false; s.insert(next); n=next; } return true; } };
true
01bf2a41327235679e8445e4a6ec566b9d8c36d5
C++
zmaker/arduino_cookbook
/000-1-CorsoAvanzato/SK012-enum/enum.ino
UTF-8
452
2.71875
3
[]
no_license
enum stati {off, meta, piena, lamp}; enum stati stato; void go(enum stati st) { stato = st; } void setup() { Serial.begin(9600); } void loop() { switch(stato) { case off: f_off(); break; case meta: f_meta(); break; case piena: f_piena(); break; case lamp: f_blink(); break; } } void f_off(){ go(meta); } void f_meta(){ } void f_piena(){ } void f_blink(){ }
true
1252c55f967365d4264137a8a034c9770d3f7662
C++
umangdubey/Guessing_game
/project_game.cpp
UTF-8
3,633
3.390625
3
[]
no_license
#include<iostream> #include <cstdlib> #include<time.h> #include<stdio.h> #include<windows.h> using namespace std; class main{ public: void dis(); void switch_case(); void level(int); void clear(); }; main o; /* these are global variables */ int score_1=0; int score_2=0; int level[]={1,2,3,4,5,6,7,8,9,10}; void main :: dis() // display function { char name_player_1[10],name_player_2[10]; char choice; cout<< " Enter the first player name "<<endl; cin>> name_player_1; cout<< " Enter the second player name "<<endl; cin>> name_player_2; cout<<" choice who want to play first "<<" \n"<<" for player one (f) and for player second (S)"<<endl; cin>>choice; if( choice == 'f'){ cout<< "for starting the level one press key Q "<<endl; } else { cout<< " second player got chance to start the match "<<endl; cout<<"press Q to start the match "<<endl; } } void main::clear() //for clearing screen { system("cls"); } void main::level(int k) // for level 1 { Sleep(2000); cout<<" here is your first number"<<endl; int secret_num,guess_num; int new_score_1=0,new_score_2; /* initialize random seed: */ srand (time(NULL)); /* generate secret number between 1 and 10: */ for (int t=0;t<=level;t++) { secret_num = rand() % 10 + 1; cout<<secret_num<<endl; } Sleep(2000); o.clear(); cout<<" after clearing screen 1st player have to enter the number which display before "<<endl; cout<<" guess the number you seen"<<endl; cin>>guess_num; if(secret_num==guess_num) { cout<<" 1st player win the game "<<endl; new_score_1= score_1 + 5; } else { cout<<" 1st player lose the game "<<endl; new_score_1= score_1 - 5; } cout<<" clear the screen "<<endl; o.clear(); Sleep(2000); cout<<" now new number display for 2nd player"<<endl; /* initialize random seed: */ srand (time(0)); /* generate secret number between 1 and 10: */ secret_num = rand() % 10 + 1; cout<<secret_num<<endl; Sleep(2000); o.clear(); cout<<" after clearing screen 2nd player have to enter the number which display before "<<endl; cout<<" guess the number you seen"<<endl; cin>>guess_num; if(secret_num==guess_num) { cout<<" 2st player win the game "<<endl; new_score_2= score_2 + 5; } else { cout<<" 2st player lose the game "<<endl; new_score_2= score_2 - 5; } cout<<" 1st player score after level 1"<<"\n"<<new_score_1<<endl; cout<<"2nd player score after level 1"<<"\n"<<new_score_2<<endl; if(new_score_1>new_score_2) { cout<<"1st player win the game "<<endl; } else if (new_score_1==new_score_2) { cout<<" match tie "<<endl; } else { cout<<"2nd player win the game"<<endl; } Sleep(4000); o.clear(); cout<<" want to go on next level press button n "<<endl; o.switch_case(); } void main :: switch_case() { char i; cout<<"Enter your choice of , for start match(Q),for clearing screen (c),for next round (n),exit (e) \n"<<endl; cin>>i; switch(i) { case 'Q': o.level(level); break; case 'c': o.clear(); break; case 'e': exit(0); default: cout<<"wrong choice "; } } int main () { o.dis(); system("PAUSE"); o.switch_case(); }
true