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
1f561f936565fe8a4cda6b2b83cac61d49145604
C++
playercore/mv_management
/source/ini_control.cpp
UTF-8
2,571
2.578125
3
[]
no_license
#include "ini_control.h" #include <memory> using std::vector; using std::wstring; using std::unique_ptr; CIniControl::CIniControl() : m_profilePath() { } CIniControl::~CIniControl() { } void CIniControl::Init(const wchar_t* path) { m_profilePath = path; } wstring CIniControl::GetIDFrom() { return GetProfileString(L"ID", L"START", L"0"); } wstring CIniControl::GetIDTo() { return GetProfileString(L"ID", L"END", L"0"); } vector<wstring> CIniControl::GetMVType() { wstring keys = GetProfileString(L"type", NULL, L""); const int bufSize = keys.size(); const wchar_t* p = &keys[0]; const wchar_t* stringEnd = p + bufSize; vector<wstring> types; while (p < stringEnd) { wstring key(p); if (key.empty()) { p++; continue; } wstring value = GetProfileString(L"type", key.c_str(), L""); types.push_back(value); p += key.length() + 1; } return types; } wstring CIniControl::GetPlayerPathName() { return GetProfileString(L"setup", L"PlayerPathName", L""); } wstring CIniControl::GetServerIP() { return GetProfileString(L"databaseSetup", L"ServerIP", L"0"); } wstring CIniControl::GetUserName() { return GetProfileString(L"databaseSetup", L"UserName", L""); } wstring CIniControl::GetPassword() { return GetProfileString(L"databaseSetup", L"Password", L""); } wstring CIniControl::GetDatabaseName() { return GetProfileString(L"databaseSetup", L"DatabaseName", L""); } void CIniControl::SetIDFrom(wchar_t* id) { WritePrivateProfileString(L"ID", L"START", id, m_profilePath.c_str()); } void CIniControl::SetIDTo(wchar_t* id) { WritePrivateProfileString(L"ID", L"END", id, m_profilePath.c_str()); } wstring CIniControl::GetProfileString(const wchar_t* appName, const wchar_t* keyName, const wchar_t* defaultValue) { int bufSize = 128; unique_ptr<wchar_t[]> buf; int charCopied; const int terminatorLength = (!appName || !keyName) ? 2 : 1; do { bufSize *= 2; buf.reset(new wchar_t[bufSize]); charCopied = GetPrivateProfileString(appName, keyName, defaultValue, buf.get(), bufSize, m_profilePath.c_str()); } while (charCopied >= (bufSize - terminatorLength)); wstring result; result.resize(charCopied); memcpy(&result[0], buf.get(), charCopied * sizeof(buf[0])); return result; }
true
e561f11e4bde34b3878a0df71a0d035582d68359
C++
degrand1/DataStructures
/Queue.h
UTF-8
635
3.234375
3
[]
no_license
#ifndef QUEUE_H #define QUEUE_H #include "LinkedList.h" template<class Data> class Queue { public: Queue(){ List = new LinkedList<Data>(); } ~Queue(); Node<Data>* Dequeue(); void Enqueue( Data Value ); bool IsEmpty() { return List->IsEmpty(); } private: LinkedList<Data>* List; }; template<class Data> Queue<Data>::~Queue() { if( List != NULL ) { delete List; List = NULL; } } template<class Data> void Queue<Data>::Enqueue( Data Value ) { List->AddElement(Value); } template<class Data> Node<Data>* Queue<Data>::Dequeue() { return List->IsEmpty() ? NULL : List->PopHead(); } #endif
true
63a2f301ea444c5ca7c3196852c7dbf09783cf53
C++
IvanIsCoding/OlympiadSolutions
/DMOJ/acc3p4.cpp
UTF-8
2,120
2.578125
3
[]
no_license
// Ivan Carvalho // Solution to https://dmoj.ca/problem/acc3p4 #include <bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 1e6 + 10; ll seg[4 * MAXN], lazy_a[4 * MAXN], lazy_r[4 * MAXN]; int N, Q; ll soma_pa(ll a, ll r, ll n) { ll b = a + (n - 1) * r; return ((a + b) * n) / 2; } void propagate(int pos, int left, int right) { if (lazy_a[pos] == 0 && lazy_r[pos] == 0) return; seg[pos] += soma_pa(lazy_a[pos], lazy_r[pos], right - left + 1); if (left != right) { int mid = (left + right) / 2; lazy_a[2 * pos] += lazy_a[pos]; lazy_a[2 * pos + 1] += lazy_a[pos] + (mid + 1 - left) * lazy_r[pos]; lazy_r[2 * pos] += lazy_r[pos]; lazy_r[2 * pos + 1] += lazy_r[pos]; } lazy_a[pos] = 0; lazy_r[pos] = 0; } void update(int pos, int left, int right, int i, int j, ll a, ll r) { propagate(pos, left, right); if (left > right || left > j || right < i) return; if (left >= i && right <= j) { lazy_a[pos] += a + r * (left - i); lazy_r[pos] += r; propagate(pos, left, right); return; } int mid = (left + right) / 2; update(2 * pos, left, mid, i, j, a, r); update(2 * pos + 1, mid + 1, right, i, j, a, r); seg[pos] = seg[2 * pos] + seg[2 * pos + 1]; } ll query(int pos, int left, int right, int i, int j) { propagate(pos, left, right); if (left >= i && right <= j) return seg[pos]; int mid = (left + right) / 2; if (j <= mid) return query(2 * pos, left, mid, i, j); else if (i >= mid + 1) return query(2 * pos + 1, mid + 1, right, i, j); else return query(2 * pos, left, mid, i, j) + query(2 * pos + 1, mid + 1, right, i, j); } int main() { scanf("%d %d", &N, &Q); for (int q = 1; q <= Q; q++) { int op, i, j, k; scanf("%d", &op); if (op == 1) { scanf("%d %d %d", &i, &j, &k); update(1, 1, N, i, j, k, k); } else { scanf("%d %d", &i, &j); printf("%lld\n", query(1, 1, N, i, j)); } } return 0; }
true
f8b70aadc1d9436ca68ef223ce0c8d4733c977df
C++
woke5176/Algoritms-and-data-structures
/118A_codeforces_String_Task.cpp
UTF-8
329
2.953125
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; int main() { string s; cin>>s; for(int i=0;i<s.size();i++){ char ch=tolower(s[i]); if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='y'){ continue; }else{ cout<<"."<<ch; } } return 0; }
true
a004f7e81b9e83a3872f2e76a7604415559cb00e
C++
stevens-rocksat-2020/oven_code
/src/PID-JACK.cpp
UTF-8
972
2.5625
3
[]
no_license
#include "PID-JACK.h" #include "OvenTemp.h" OvenState ovenState = OvenState_OFF; void PID::reset() { totalError=0; lastError=0; lastTimestamp=millis()-100; } double PID::get(double input) { double dt=(millis()-lastTimestamp)/1000.0; if(dt<10) { dt=10; } lastTimestamp=millis(); double error=target-input; totalError+=error*dt; double dError=(error-lastError)/dt; lastError=error; if(totalError>iMax) { totalError=iMax; } else if(totalError<-iMax) { totalError=-iMax; } double out = kp*(error+ki*totalError+kd*dError); out+=127; if(out>255) { out=255; } else if(out<0) { out=0; } return out; } void PID::pidLoop() { if(millis()-lastTimestamp<minLoopTime*1000) { return; } double curOut=get(ovenTemp()); if (ovenState != OvenState_OFF) { setOvenPower((int)curOut); } else { setOvenPower(0); } }
true
b3f65d477252560603a94498f2c7277e2fc02d54
C++
Gunjan827/Datastructures-and-Algorithms
/Stacks/nearest_smaller_to_right.cpp
UTF-8
975
4.09375
4
[]
no_license
/*Given an array of integers, find the closest (not considering distance, but value) smaller on right of every element. If an element has no smaller on the right side, print -1.*/ #include <iostream> #include <stack> using namespace std; void printNSR(int arr[], int n){ stack <int> s; int flag = 0; s.push(arr[n-1]); cout<<arr[n-1]<<" ----> -1\n"; for (int i = n-2; i >= 0 ; --i) { if(s.empty() == true){ s.push(arr[i]); } while(s.empty() == false){ if(s.top() < arr[i]){ cout<<arr[i]<<" ----> "<<s.top()<<endl; flag = 1; break; } else if(s.top() >= arr[i]){ s.pop(); flag = 0; } } if(flag == 0){ cout<<arr[i]<<" ----> -1\n"; } s.push(arr[i]); } } int main() { int n; cout<<"Enter the size of array\n"; cin>>n; int arr[n]; cout<< "Enter the array\n"; for (int i = 0; i < n; ++i) { cin>>arr[i]; } printNSR(arr , n); return 0; }
true
e66caa448c1891040e2bc21402fa6a72e6950dbf
C++
kihx/rasterizer
/xtozero/Texture.h
UTF-8
2,776
2.6875
3
[]
no_license
#ifndef _TEXTURE_H_ #define _TEXTURE_H_ #include <vector> #include <map> #include <string> #include <memory> #include "XtzMath.h" #include "XtzThreadPool.h" namespace xtozero { enum COLOR { BLUE = 0, GREEN, RED, }; struct TEXEL { unsigned char m_color[3]; }; class CFilter { public: explicit CFilter(); ~CFilter(); }; enum TEXTURE_ADDRESS_MODE { TEXTURE_ADDRESS_WRAP = 1, TEXTURE_ADDRESS_MIRROR, TEXTURE_ADDRESS_CLAMP, TEXTURE_ADDRESS_BORDER, TEXTURE_ADDRESS_MIRROR_ONCE, }; struct SAMPLER_DESC { public: TEXTURE_ADDRESS_MODE m_addressModeU; TEXTURE_ADDRESS_MODE m_addressModeV; unsigned int m_borderColor; }; class CSampler { private: std::shared_ptr<CFilter> m_filter; TEXTURE_ADDRESS_MODE m_addressModeU; TEXTURE_ADDRESS_MODE m_addressModeV; unsigned int m_borderColor; public: explicit CSampler( const SAMPLER_DESC& samplerDesc ); CSampler( const CSampler& sampler ); ~CSampler( ); inline void CalcTextureAddress( Vector2& texcoord ); inline const unsigned int GetBorderColor() const; inline void SetBorderColor( const int r, const int g, const int b ); }; class CTexture { private: unsigned int m_width; unsigned int m_height; protected: std::vector<TEXEL> m_texture; const unsigned int GetWidth() const { return m_width; } const unsigned int GetHeight() const { return m_height; } public: CTexture( const unsigned int width, const unsigned int height ); CTexture( ); virtual ~CTexture( ); void SetSize( const unsigned int width, const unsigned int height ); virtual void Load( const char *pfileName ) = 0; virtual const unsigned int Sample( const float u, const float v, std::shared_ptr<CSampler> sampler ) const = 0; virtual const unsigned int Sample( const Vector2& texCoord, std::shared_ptr<CSampler> sampler ) const = 0; virtual void DrawTexture( void* buffer, int width, int dpp ) const = 0; }; class CBitmap : public CTexture { private: BITMAPFILEHEADER m_bitmapHeader; BITMAPINFOHEADER m_bitmapInfoHeader; public: CBitmap( const unsigned int width, const unsigned int height ); CBitmap( ); virtual ~CBitmap( ); virtual void Load( const char *pfileName ); virtual const unsigned int Sample( const float u, const float v, std::shared_ptr<CSampler> sampler ) const; virtual const unsigned int Sample( const Vector2& texCoord, std::shared_ptr<CSampler> sampler ) const; virtual void DrawTexture( void* buffer, int width, int dpp ) const; }; class CTextureManager { private: SpinLock m_lockObject; std::map<std::string, std::shared_ptr<CTexture> > m_textureMap; public: explicit CTextureManager( ); ~CTextureManager( ); std::shared_ptr<CTexture> Load( const char *pfileName ); }; } #endif
true
3e6f62c81c266ab224b6448a52aedbef4406af29
C++
20191864233/G20
/c/c6/6.5/66.cpp
GB18030
658
2.84375
3
[]
no_license
// 66.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <stdlib.h> void nixv(int a[],int i); int main(int argc, char* argv[]) { int a[100],n; int i; printf("ij:\n"); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } nixv(a,n); for(i=0;i<n;i++) { printf("%d ",a[i]); } return 0; } void nixv(int a[],int n) { int mid=n/2; int temp,i; for(i=0;i<mid;i++) { temp=a[i]; a[i]=a[n-i-1]; a[n-i-1]=temp; } }
true
65ae694f8c39e103f6e85d7587adb67dc24653ce
C++
OhYee/PAT
/basic/1024.cpp
UTF-8
3,155
3.328125
3
[]
no_license
#include <cmath> #include <cstdio> #include<cstring> const int maxn = 10010; char s[maxn]; char base[maxn]; /* Find the first character c in the string s. Arguments: s - string len - length of s c - the character to find Return: The position of the character in the string. If cann't find the character, return -1. */ int findChar(char *s,int len,char c){ int pos = -1; for(int i=0;i<len;++i){ if(s[i] == c){ pos = i; break; } } return pos; } /* Erase the nonnumeric character. Arguments: s - raw string. len - length of s. Return: Length of the string. */ int eraseNonChar(char *s, int len) { int pos=0; for (int i=0;i<len;++i){ if(s[i]>='0'&&s[i]<='9') s[i-pos] = s[i]; else ++pos; } s[len-pos]='\0'; return len-pos; } /* String to integer Arguments: s - string bpos - begin position epos - end position Return: The integer */ int toInt(char *s, int bpos,int epos){ int fix = 1; int num=0; for(int i=bpos;i<epos;++i){ if (i==bpos && (s[i]=='+'||s[i]=='-')){ if(s[i]=='-') fix = -1; }else{ if(s[i]>='0'&&s[i]<='9') num=num*10+s[i]-'0'; } } return num*fix; } /* Get the sub-string Arguments: dst - destination string src - source string bpos - begin position epos - end position Return: The integer */ void subString(char *dst, char *src, int bpos, int epos){ //memcpy(dst,src+bpos,(epos-bpos)*sizeof(char)); //printf("%s %d %d\n",src,bpos,epos); for(int i = 0;i < epos-bpos;++i) dst[i] = src[i+bpos]; dst[epos-bpos]='\0'; } int main() { scanf("%s",s); int len = strlen(s); int ePos = findChar(s,len,'E'); bool fix = false; subString(base,s,0,ePos); fix = (base[0]=='-'); int baseLen = eraseNonChar(base,strlen(base)); int exponent = toInt(s,ePos+1,len); // printf("%c %s %d\n",(fix?'-':'+'),base,exponent); if(baseLen==1 && base[0]=='0') { printf("0"); } else { if(fix) printf("-"); if(exponent<0){ for(int i=0;i<-exponent;++i){ printf("0"); if(i==0) printf("."); } printf("%s",base); }else{ bool isFirst = true; for(int i=0;i<baseLen;++i){ if(!isFirst || base[i]!='0'){ printf("%c",base[i]); isFirst = false; } if(exponent==i && i!=baseLen-1) printf("."); } for(int i=0;i<=exponent-baseLen;++i) printf("0"); } } printf("\n"); return 0; }
true
c664e44145f42f076e43531f264c59ced06907cd
C++
eldr4d/buildit
/build/read.cpp
UTF-8
4,496
2.796875
3
[]
no_license
#include <iostream> #include <unistd.h> #include <stdlib.h> #include <string> #include <utility> #include "logmanager.hpp" using namespace std; typedef struct{ int employer = -1; string token; bool HTML = false; bool state = false; bool rooms = false; vector<pair<string,bool> > names; string logFile; bool allOk = false; bool alpha = false; bool beta = false; int lower = -1; int upper = -1; int lower2 = -1; int upper2 = -1; bool timeFlag = false; bool roomHistory = false; }arguments; arguments getArguments(int argc, char **argv){ arguments args; int c; bool firstUdone = false; bool firstLdone = false; while((c = getopt(argc, argv, "HK:SRE:G:AL:U:TBI")) != -1){ switch(c){ case 'K': args.token = string(optarg); break; case 'E': args.employer = 1; { pair<string,bool> tmp; tmp.first = string(optarg); tmp.second = true; args.names.push_back(tmp); } break; case 'G': args.employer = 0; { pair<string,bool> tmp; tmp.first = string(optarg); tmp.second = false; args.names.push_back(tmp); } break; case 'H': args.HTML = true; break; case 'A': args.alpha = true; break; case 'B': args.beta = true; break; case 'I': args.roomHistory = true; break; case 'U': if(firstUdone == false){ args.upper = atoi(optarg); firstUdone = true; }else{ if(args.upper2 == -1){ args.upper2 = atoi(optarg); }else{ args.allOk = false; return args; } } break; case 'L': if(firstLdone == false){ args.lower = atoi(optarg); firstLdone = true; }else{ if(args.lower2 == -1){ args.lower2 = atoi(optarg); }else{ args.allOk = false; return args; } } break; case 'S': args.state = true; break; case 'R': args.rooms = true; break; case 'T': args.timeFlag = true; break; case '?': break; } } args.allOk = false; for(; optind < argc; optind++){ if(args.allOk == true){ args.allOk = false; return args; }else{ args.allOk = true; } args.logFile = string(argv[optind]); } return args; } int main(int argc, char **argv){ arguments args = getArguments(argc, argv); if(args.allOk == false || args.token.length() <= 0){ cout << "invalid" << endl; return -1; } Logmanager myLog(args.logFile, args.token); if(myLog.securityViolation){ cerr << "integrity violation" << endl; return -1; } //myLog.prettyPrint(); if(args.roomHistory == false && args.timeFlag == false && args.state == true && args.names.size() == 0 && args.rooms == false && args.alpha == false && args.lower == -1 && args.upper == -1 && args.beta == false){ myLog.printState(args.HTML); }else if(args.roomHistory == false && args.timeFlag == false && args.state == false && args.names.size() == 1 && args.rooms == true && args.alpha == false && args.lower == -1 && args.upper == -1 && args.beta == false){ myLog.printUserData(args.names[0].first, args.employer == 1 ? true : false, args.HTML); }else if(args.roomHistory == false && args.timeFlag == false && args.alpha == true && args.lower2 == -1 && args.upper2 == -1 && args.lower >= 0 && args.upper >= 0 && args.upper > args.lower && args.state == false && args.employer == -1 && args.rooms == false && args.beta == false){ myLog.personsInTimeWindow(args.lower,args.upper,args.HTML); }else if(args.roomHistory == false && args.timeFlag == true && args.state == false && args.names.size() == 1 && args.rooms == false && args.alpha == false && args.lower == -1 && args.upper == -1 && args.HTML == false && args.beta == false){ myLog.totalTimeOfUser(args.names[0].first, args.employer == 1 ? true : false); }else if(args.roomHistory == false && args.timeFlag == false && args.alpha == false && args.lower2 >= 0 && args.upper2 >= 0 && args.lower2 < args.upper2 && args.lower >= 0 && args.upper >= 0 && args.upper > args.lower && args.state == false && args.employer == -1 && args.rooms == false && args.beta == true){ myLog.leavedPersonsDuringTimeWindow(args.lower,args.upper,args.lower2,args.upper2,args.HTML); }else if(args.roomHistory == true && args.timeFlag == false && args.alpha == false && args.lower == -1 && args.upper == -1 && args.state == false && args.names.size() > 0 && args.rooms == false && args.beta == false){ myLog.printSameRooms(args.names,args.HTML); }else{ cout << "invalid" << endl; return -1; } return 0; }
true
7c3ca333192de06d56f9f0519fc079ed24c07f56
C++
QINGSHURUNINDEXINGMING/CPP
/106_1實習+課堂/實習9_1201/最接近的完全平方數.cpp
BIG5
1,348
4.03125
4
[]
no_license
// (̱񪺧)g@Ө禡int sqrfloor(int n)AӨ禡@nApöǦ^p󵥩nḆnk(ơG}ڸƤ)C // psqrfloor(5)hǦ^4Fsqrfloor(9)hǦ^9C #include <iostream> using namespace std; int sqrfloor(int n) { for (int i = n; i>0; i--) { for (int j = 0; j < i; j++) { if (j*j == i) { return i; } } } } int main() { int num; cin >> num; cout << sqrfloor(num) << endl; } /* ǧ̼g #include <bits/stdc++.h> using namespace std; int sqrfloor(int num) { return (int)sqrt(num)*(int)sqrt(num); } int main() { int num; cin >> num; cout << sqrfloor(num)<<endl; } #include<iostream> using namespace std; int sqrfloor(int num) { for (int i = 1; ;i++) { if(i*i<=num && (i+1)*(i+1)>num) return i*i; } } int main() { int num; cin >> num; cout << sqrfloor(num)<<endl; } #include <iostream> using namespace std; int main() { int temp; int array[5] = {5,4,8,6,7}; for(int i=0; i < 5; i++) { for(int j=0; j < 5; j++) { if(array[i] > array[i+1]) { temp = array[i]; array[i] = array[i+1]; array[i+1] = temp; } } } for(int i=0; i < 5; i++) { cout << array[i] << " "; } }
true
b8e60cfdc6f88c2aaa65f4c44e65fea28c319955
C++
mothaibatacungmua/finger_of_death
/model/bert/common.cpp
UTF-8
969
2.734375
3
[]
no_license
#include "common.h" #include <fstream> #include <string> #include <iostream> std::string StringFormat(const std::string fmt_str, ...) { int final_n, n = ((int)fmt_str.size()) * 2; /* Reserve two times as much as the length of the fmt_str */ std::unique_ptr<char[]> formatted; va_list ap; while(1) { formatted.reset(new char[n]); /* Wrap the plain char array into the unique_ptr */ strcpy(&formatted[0], fmt_str.c_str()); va_start(ap, fmt_str); final_n = vsnprintf(&formatted[0], n, fmt_str.c_str(), ap); va_end(ap); if (final_n < 0 || final_n >= n) n += abs(final_n - n + 1); else break; } return std::string(formatted.get()); } void PrintFileContent(std::string filename){ std::ifstream i("data/bert_config.json"); char str[512]; while(i) { i.getline(str, 512); // delim defaults to '\n' if(i) std::cout << str << std::endl; } }
true
644607e30cea774320e07998ba58a6f80098132f
C++
nkorzh/Algorithms-DM
/1 semester/CT/3lab-DP/B.cpp
UTF-8
1,456
2.5625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define ll long long #define INF 100000000 int n, m; // <= 10 000 enum class Move : int { R, D }; vector<int> cost; vector<vector<int>> d; vector<vector<Move>> path; int main() { ios_base::sync_with_stdio(false); // freopen("a.in", "r", stdin); cin >> n >> m; d.resize(n + 1); path.resize(n + 1); for (int i = 1; i <= n; ++i) { d[i].resize(m + 1); path[i].resize(m + 1); for (int j = 1; j <= m; ++j) cin >> d[i][j]; } // d[i, 1] for (int i = 2; i <= n; ++i) d[i][1] += d[i - 1][1], path[i][1] = Move::D; // d[j, 1] for (int j = 2; j <= m; ++j) d[1][j] += d[1][j - 1], path[1][j] = Move::R; for (int i = 2; i <= n; ++i) for (int j = 2; j <= m; ++j) { // y x y x if (d[i - 1][j] > d[i][j - 1]) { // top left d[i][j] += d[i - 1][j]; path[i][j] = Move::D; } else { d[i][j] += d[i][j - 1]; path[i][j] = Move::R; } } vector<Move> ans; int i = n, j = m; while (i != 1 || j != 1) { ans.push_back(path[i][j]); if (path[i][j] == Move::D) i--; else j--; } cout << d[n][m] << "\n"; for (auto p = ans.rbegin(); p != ans.rend(); p++) cout << (*p == Move::D ? 'D' : 'R'); return 0; }
true
6ed2516bad72353d31697ee5d36d0ecdfd933c0c
C++
matthewfl/stuff
/any.hpp
UTF-8
3,284
3.640625
4
[]
no_license
#ifndef _ilang_any #define _ilang_any /* based off the boost::any class * created to give greater control over the generic types * added features: * able to delete generic types that are pointers without know what they are * */ #include <typeinfo> #include <assert.h> namespace ilang { class any { public: any () : content(0) {} template <typename ValueType> any (const ValueType &value) : content(new holder<ValueType>(value)) {} any(const any &other) : content(other.content ? other.content->clone() : 0) {} ~any () { delete content; } any & swap (any & rhs) { placeHolder *tmp = content; content = rhs.content; rhs.content = tmp; return *this; } any & operator=(any rhs) { rhs.swap(*this); return *this; } template<typename ValueType> any &operator=(const ValueType &rhs) { any(rhs).swap(*this); return *this; } bool empty() const { return !content; } const std::type_info & type () const { return content ? content->type() : typeid(void); } const bool isPointer () const { return content->isPointer(); } template <typename T> const bool canCast () const { //return content ? content->canCast<T>() : false; if(content->type() == typeid(T)) return true; // if(isPointer()) { //return dynamic_cast<T>(static_cast<holder<void*>* >(content)->held); return false; //}else{ return dynamic_cast<holder<T>* >(content); // } } template <typename T> T Cast () { } private: class placeHolder { public: virtual ~placeHolder() {}; virtual const std::type_info & type() const = 0; virtual placeHolder * clone () const = 0; virtual const bool isPointer () const = 0; virtual void destroy () = 0; //template <typename T> virtual const bool canCast const () = 0; // doesn't work }; template <class ValueType> class holder : public placeHolder { public: // these are the same for both holder (const ValueType &value) : held(value) {} virtual const std::type_info &type() const { return typeid(ValueType); } virtual placeHolder *clone() const { return new holder(held); } // these are different virtual const bool isPointer() const { return false; } virtual ~holder () { } virtual void destroy () { // not a pointer so not a problem } // the Variable ValueType held; }; template <typename ValueType> class holder<ValueType*> : public placeHolder { public: typedef ValueType* ValueType_ptr; // these are the same for both holder(const ValueType_ptr &value) : held(value) {} virtual const std::type_info &type() const { return typeid(ValueType_ptr); } virtual placeHolder *clone() const { return new holder(held); } // these are different virtual const bool isPointer () const { return true; } virtual ~holder () { } virtual void destroy () { delete held; } // the Variable ValueType_ptr held; }; // the Variable placeHolder *content; }; }; #endif // _ilang_any
true
046e6b83a7a18af73bbb96c4af0189504b24400f
C++
seanjsavage/TrainLight
/firmware/trainlight/application.ino
UTF-8
3,487
2.828125
3
[]
no_license
#include "neopixel.h" int activityLed = D7; unsigned int updateTimeout = 0; // next time to contact the server #define PIXEL_PIN D0 #define PIXEL_COUNT 60 #define PIXEL_TYPE WS2812B #define FAR 10 #define CLOSE 5 #define CLOSER 2 Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, PIXEL_TYPE); uint32_t closestColor = strip.Color(254,240,0); // Yellow uint32_t closerColor = strip.Color(0,240,0); // Bright Green uint32_t closeColor = strip.Color(0,60,0); // Dark Green uint32_t farColor = strip.Color(0,0,0); // Off void setup() { Time.zone(+1.0); // +1.0 Winter/ +2.0 Summer// TODO: detect DST Serial.begin(9600); pinMode(activityLed, OUTPUT); strip.begin(); strip.show(); // Initialize all pixels to 'off' strip.setBrightness(20); Spark.function("parse_values", parse_values); } void loop() { // setup led RGB.control(true); RGB.brightness(5); // Color zones: TL, TR, RT, RB, BR, BL, LB, LT. (Arranged clockwise, starting from upper left.) // That means: 22 Southbound, 24 S, N-Judah W, 6/71 W, 24 N, 22 N, 6/71 E, N-Judah E // To test locally: // parse_values("TL=1&TR=9&RT=1&RB=3&BR=12&BL=1&LB=4&LT=5&"); if (updateTimeout > millis()) { // keep the same color while waiting return; } digitalWrite(activityLed, HIGH); // indicate activity // check again in 5 seconds: updateTimeout = millis() + 5000; digitalWrite(activityLed, LOW); } // Set Transit Lites according to 8-zone square. Inputs a color each of the 8 zones, starting top left of the square and going clockwise. Colors them the specified colors, then waits ('wait2' seconds) void colorTransitLites(String TL, String TR, String RT, String RB, String BR, String BL, String LB, String LT) { int wait2 = 1; // Number of seconds to wait between each loop. uint16_t i; for(i=0; i<7; i++) { distanceToColor(i, LB); } for(i=7; i<15; i++) { distanceToColor(i, LT); } for(i=15; i<23; i++) { distanceToColor(i, TL); } for(i=23; i<30; i++) { distanceToColor(i, TR); } for(i=30; i<38; i++) { distanceToColor(i, RT); } for(i=38; i<45; i++) { distanceToColor(i, RB); } for(i=45; i<52; i++) { distanceToColor(i, BR); } for(i=52; i<60; i++) { distanceToColor(i, BL); } strip.show(); delay(wait2*1000); } void distanceToColor(uint16_t j, String distance) { if(distance == "CLOSEST") { strip.setPixelColor(j, closestColor); } else if(distance == "CLOSER") { strip.setPixelColor(j, closerColor); } else if(distance == "CLOSE") { strip.setPixelColor(j, closeColor); } else { strip.setPixelColor(j, farColor); } } String shortDescr(String &descr) { if(descr.startsWith("moderate ")){ descr.remove(3,5); return descr; } return descr; } int parse_values(String val){ int values[8]; String distances[8]; char c; short i = 0,target=0; while(val[i]){ c = val[i++]; if(c >= '0' && c <= '9'){ distances[target]+=c; } else{ values[target] = atoi(distances[target].c_str()); target++; } } values[target] = atoi(distances[target].c_str()); for(i = 0; i < 8; i++) { if(values[i] >= FAR || values[i] <= 0) distances[i] = "FAR"; else if(values[i] >= CLOSE) distances[i] = "CLOSE"; else if(values[i] >= CLOSER) distances[i] = "CLOSER"; else if(values[i] > 0) distances[i] = "CLOSEST"; } colorTransitLites(distances[0],distances[1],distances[2],distances[3],distances[4],distances[5],distances[6],distances[7]); return 0; }
true
75875dfbb75443933dab90ed969127a80a4071fd
C++
m19s/multi-ems
/example/ems_digital/wire_ems_time/wire_ems_time.ino
UTF-8
2,493
2.5625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
//2017/9/7 //Michi Kono, U-Tokyo #include <Metro.h> #include <Wire.h> //500 Hz max for voltage, due to metro.h res int channelNum = 10; Metro metroVolt[10]; //count time for pulse Metro metroTime[10]; //count time for duration int metroFlag[10]; //counting completed int channelState[10]; //the state of the channel int pinState[10]; //the pin state for pulse output int metVoltHolder[10]; //store the voltage int voltage[10]; Metro metroInit[10]; //considering the delay int initFlag[10]; void setup() { Wire.begin(1); // join i2c bus with address i Wire.onReceive(receiveEvent); // register event for (int i = 2; i < 14; i++) { pinMode(i, OUTPUT); } for (int i = 0; i < channelNum; i++) { metroVolt[i].interval(1); metroTime[i].interval(1); metroFlag[i] = 0; channelState[i] = 0; pinState[i] = 0; metVoltHolder[i] = 0; voltage[i] = 0; metroInit[i].interval(1000); initFlag[i] = 0; } } void loop() { voltOut(); } void receiveEvent(int howMany) { int duration[channelNum]; if (Wire.available() > 29) { for (int i = 0; i < channelNum; i++) { voltage[i] = Wire.read() * 10; if (voltage[i] > 500) { voltage[i] = 500; } channelState[i] = Wire.read(); duration[i] = Wire.read() * 1000 + 1000; //1000 is for stablization metroVolt[i].interval(1000 / (voltage[i] * 2)); metroTime[i].interval(duration[i]); metroVolt[i].reset(); metroTime[i].reset(); metroFlag[i] = 0; pinState[i] = 0; if (voltage[i] > 60) { metVoltHolder[i] = voltage[i] / 4; metroVolt[i].interval(1000 / (metVoltHolder[i] * 2)); } else { metVoltHolder[i] = voltage[i]; } metroInit[i].reset(); initFlag[i] = 0; } } } void voltOut() { for (int i = 0; i < channelNum; i++) { if (metroInit[i].check() == 1) { initFlag[i] = 1; } //if the duration has ended, stop if (metroTime[i].check() == 1) { metroFlag[i] = 1; channelState[i] = 0; digitalWrite(i + 2, LOW); } else if (channelState[i] == 0) { digitalWrite(i + 2, LOW); } //write ON and OFF else if (metroTime[i].check() == 0 && metroFlag[i] == 0 && channelState[i] == 1) { if (metroVolt[i].check() == 1) { if (pinState[i] == HIGH) { pinState[i] = LOW; if (metVoltHolder[i] < voltage[i] && initFlag[i] == 1) { metroVolt[i].interval(1000 / (metVoltHolder[i] * 2)); metVoltHolder[i] = metVoltHolder[i] + 1; } } else { pinState[i] = HIGH; } digitalWrite(i + 2, pinState[i]); } } } }
true
2fff43078eabe417445846cdf5b08d924aaa247e
C++
jml312/Cpp-course
/HW2/HW2Q2/main.cpp
UTF-8
665
3.53125
4
[]
no_license
#include <iostream> using namespace std; string buildSentence(char components[], int lc, int places[], int lp); int main() { char components[] = {"ol,wrd eH"}; int places[] = {8, 7, 1, 1, 0, 2, 6, 3, 0, 4, 1, 5}; cout << buildSentence(components, 9 , places, 12); return 0; } string buildSentence(char components[], int lc, int places[], int lp) { // The sentence string to be returned string sentence; // Loops over the length of the places array and adds the corresponding component at the current place index to the sentence for (int i = 0; i < lp; i++) { sentence += components[places[i]]; } return sentence; }
true
89c493935ff5c0846c1bb39821929bf7d7116998
C++
shobhit-saini/IB
/Day14/Trailing_Zeros_in_Factorial.cpp
UTF-8
380
3.5
4
[]
no_license
/* Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. Example : n = 5 n! = 120 Number of trailing zeros = 1 So, return 1 */ int Solution::trailingZeroes(int A) { int res, no = 0; res = A/5; no += res; while(res > 0) { res= res/5; no += res; } return no; }
true
bf6f8dfb401c5969568b6f1665a6e17a48eb623b
C++
LeeJehwan/Baekjoon-Online-Judge
/code/11437_LCA.cpp
UTF-8
936
2.609375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; #define endl '\n' const int MAX_N = 50001; vector<int> adj[MAX_N]; int lv[MAX_N], parent[MAX_N], chk[MAX_N]; void dfs(int here) { chk[here] = 1; int next; for (int i = 0; i < (int)adj[here].size(); i++) { next = adj[here][i]; if (chk[next]) continue; lv[next] = lv[here] + 1; parent[next] = here; dfs(next); } } int lca(int a, int b) { if (lv[a] < lv[b]) swap(a, b); while (lv[a] != lv[b]) { a = parent[a]; } if (a == b) return a; while (a != b) { a = parent[a]; b = parent[b]; } return a; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; for (int i = 0; i < n - 1; i++) { int a, b; cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); } int m; cin >> m; lv[1] = 0; dfs(1); for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; cout << lca(a, b) << endl; } }
true
f547764d36b2410df35eef1b1da4072a9e9ab875
C++
ywchen1994/ywchen
/RTEXTool/RingBuffer.cpp
UTF-8
1,365
2.765625
3
[]
no_license
#include "StdAfx.h" #include "RingBuffer.h" CRingBuffer::CRingBuffer(void) : m_HeadRingBuffer(0) , m_TailRingBuffer(0) { for(int i = 0 ; i < RingBufferSize ; i++) { m_DataRingBuffer[RingBufferSize] = 0; } } CRingBuffer::~CRingBuffer(void) { } bool CRingBuffer::BufferIsFull(void) { //TRACE("head = %d , tail = %d\n",m_HeadRingBuffer, m_TailRingBuffer); if(((m_HeadRingBuffer + 1) % RingBufferSize) == m_TailRingBuffer) return TRUE; else return FALSE; } bool CRingBuffer::BufferIsEmpty() { if(m_HeadRingBuffer == m_TailRingBuffer) return TRUE; else return FALSE; } UINT CRingBuffer::uiBufferSpace(void) { if(m_HeadRingBuffer >= m_TailRingBuffer) { return(RingBufferSize + m_TailRingBuffer - m_HeadRingBuffer - 1); } else { return (m_TailRingBuffer - m_HeadRingBuffer - 1); } } UINT CRingBuffer::uiBufferDataSize() { if(m_HeadRingBuffer >= m_TailRingBuffer) { return(m_HeadRingBuffer - m_TailRingBuffer); } else { return (RingBufferSize + m_HeadRingBuffer - m_TailRingBuffer); } } void CRingBuffer::ADD(unsigned char ucdata) { m_DataRingBuffer[m_HeadRingBuffer] = ucdata; m_HeadRingBuffer = ((m_HeadRingBuffer + 1) % RingBufferSize) ; } unsigned char CRingBuffer::Extract() { unsigned char ch = 0; ch = m_DataRingBuffer[m_TailRingBuffer]; m_TailRingBuffer = ((m_TailRingBuffer + 1) % RingBufferSize) ; return ch; }
true
2a539e4fa56cb052425022938879845b9210d6a5
C++
jiuyewxy/Cpp-Primer-Plus
/ch2/Q05.cpp
UTF-8
334
3.515625
4
[]
no_license
#include <iostream> float exchange(float); int main() { using namespace std; float celsius; cout<<"Please enter a Celsius value:"; cin>>celsius; cout<<celsius<<" degrees Celsius is "<<exchange(celsius)<<" degrees Fahrenheit."<<endl; return 0; } float exchange(float degree) { return degree*1.8+32.0; }
true
d664864c8e1d4c264a30da60e3522dea8a5b9d43
C++
Frank-Oroche/Algoritmos-Planificacion
/AlgoPlanificacion.cpp
ISO-8859-10
4,845
3.21875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <conio.h> #define M 10 //tamao de la matriz (numero de procesos - 1) void FCFS(int array[M][2]); void SRTF(int array[M][2]); void RR(int array[M][2]); int menu(); void ImprimirMatriz(int lastdone, int output[M][100]); void CopiarArray(int arr[M][2],int array[M][2]); int main(int argc, char *argv[]){ int op=0; int arr[M][2] = {{0,0},{1,3},{2,3},{3,4},{4,4},{5,2},{6,3},{7,4},{8,4},{9,4}}; //int arr[M][2] = {{0,0},{1,4},{2,3},{2,3},{3,2}}; do{ system("cls"); op=menu(); switch(op){ case 1: FCFS(arr); break; case 2: SRTF(arr); break; case 3: RR(arr); break; case 4: return 0; } }while(op!=4); } int menu(){ int op; do{ system("cls"); printf("\tMENU DE ALGORITMOS DE PLANIFICACION\n"); printf("[ 1]: FCFS\n"); printf("[ 2]: SRTF\n"); printf("[ 3]: RR\n"); printf("[ 4]: salir\n"); printf("\tElija una opcion...........[ ]\b\b"); scanf("%d",&op); }while(op<1 || 4<op); return op; } void ImprimirMatriz(int lastdone, int output[M][100]){ int i,l; printf(" "); for (l = 0; l < lastdone; l++) { printf("%2d ",l); } printf("\n "); for (l = 0; l < lastdone; l++) { printf("-----"); } printf("\n"); for (i = 1; i < M; i++) { printf("%c ",i+64); for (l = 0; l < lastdone; l++) { if (output[i][l] == 1) { printf(" - "); }else{ printf(" "); } } printf("\n"); } printf(" "); for (l = 0; l < lastdone; l++) { printf("-----"); } printf("\n"); getche(); } void CopiarArray(int arr[M][2],int array[M][2]){ int i,j; for(i=0;i<M;i++){ for(j=0;j<2;j++){ arr[i][j]=array[i][j]; } } } void FCFS(int array[M][2]){ int arr[M][2]; int i,j,k,l; int loop = 0,ready = 0,lastdone = 0,allprdone = 0; int output[M][100] = {0}; CopiarArray(arr,array); for (i = 1; i < M; i++) { loop += arr[i][1] + arr[i][0]; } for (i = 0; i < loop; i++) { ready = 0; for (j = 1; j < M; j++) { if (i >= arr[j][0] && arr[j][1] >= 1) { if (ready == 0) { ready = j; break; } } } if (ready > 0) { arr[ready][1]--; output[ready][i] = 1; } if (arr[M-1][1] < 1) { lastdone = ++i; break; } } ImprimirMatriz(lastdone,output); } void SRTF(int array[M][2]){ int arr[M][2]; int i,j,k,l; int loop = 0,ready = 0,lastdone = 0,allprdone = 0; int output[M][100] = {0}; CopiarArray(arr,array); for (i = 1; i < M; i++) { loop += arr[i][1]+arr[i][0]; } for (i = 0; i < loop; i++) { allprdone = 0; ready = 0; for (j = 1; j < M; j++) { if (i >=arr[j][0] && arr[j][1] >= 1) { if (ready == 0) { ready = j; }else if (arr[j][1] < arr[ready][1]) { ready = j; } } if (arr[j][1] < 1){ allprdone++; } } if (ready > 0) { arr[ready][1]--; output[ready][i] = 1; } if (allprdone == M-1) { lastdone = i; break; } } ImprimirMatriz(lastdone,output); } void RR(int array[M][2]){ int arr[M][2]; int i,j,l,k; int timequantom = 1,loop = 0,ready = 0,lastdone = 0,allprdone = 0; int output[M][100] = {0},q[M] = {0},scpr[M] = {0}; CopiarArray(arr,array); printf("\n\tIngrese Quantum: "); scanf("%d",&timequantom); for (i = 1; i < M; i++) { loop += arr[i][1] + arr[i][0]; } for (i = 0; i < loop; i++) { if (scpr[ready] % timequantom == 0 || arr[ready][1] < 1) { scpr[ready] = 0; q[ready] = 0; for (k = 1; k < M; k++) { if (i >= arr[k][0] && k != ready){ q[k]++; } } } allprdone = 0; ready = 0; for (j = 1; j < M; j++) { if (i >=arr[j][0] && arr[j][1] >= 1) { if (ready == 0) { ready = j; }else if (q[ready] < q[j]) { ready = j; } } if (arr[j][1] < 1){ allprdone++; } } if (ready > 0) { arr[ready][1]--; output[ready][i] = 1; scpr[ready]++; } if (allprdone == M-1) { lastdone = i; break; } } ImprimirMatriz(lastdone,output); }
true
acc2ed52b9cf9d749810964654c3df47fd331332
C++
R-Lebudi/Cplusplus
/ATM app/main.cpp
UTF-8
1,880
4.125
4
[]
no_license
#include <iostream> using namespace std; int main() { double balance, withdraw, deposit, overdraft; balance = 0; int input; cout << "Press 1 to display BALANCE \n" << "Press 2 to DEPOSIT money into the account \n" << "Press 3 to WITHDRAW money from the account \n" << "Press 4 for an OVERDRAFT from the account \n" << "Press 9 to EXIT \n" << "\n" << " Enter Choice: "; cin >> input; while(input != 9) { switch(input){ case 1: cout << " The current balance in your account is: " << balance << endl; break; case 2: cout << " Enter the amount you want to add into your account: "; cin >> deposit; balance = balance + deposit; cout << " You have deposited in " << deposit << " into your account." << endl; break; case 3: cout << " Enter the amount you want to withdraw from your account: "; cin >> withdraw; balance = balance - withdraw; cout << " You have withdrawn " << withdraw << " from your account." << endl; break; case 4: cout << " Enter the amount you want to overdraft your account: " <<endl; cin >> overdraft; balance = balance - overdraft; cout << " You have over drafted " << overdraft << " from your account." << endl; cout << " The total overdraft amount to be repaid is: " << endl; cout << ((balance)*20/100 - overdraft) << "\n"; balance = ((balance)*20/100 - overdraft); break; default: cout << " You have entered an invalid input." << endl; cout << "\n"; } cout << "Enter choice: "; cin >> input; } return 0; }
true
30d2901b3b2ed8c14cea3e89991e4cc5ceb53b57
C++
sauravstark/Preparations
/025 - AVL Tree Deletion.cpp
UTF-8
4,163
3.828125
4
[]
no_license
#include <stack> #include <algorithm> struct Node { int data; Node *left; Node *right; int height; }; int height(Node* node) { if(node == nullptr) return 0; return node->height; } Node* rotateL(Node *root); Node* rotateR(Node *root); Node* deleteNode(Node* root, int data) { Node *del_node = root; std::stack<Node*> visited_parents; while (del_node != nullptr) { visited_parents.push(del_node); if (data > del_node->data) { del_node = del_node->right; } else if (data < del_node->data) { del_node = del_node->left; } else { break; } } if (del_node == nullptr) return root; visited_parents.pop(); Node *del_parent = (visited_parents.empty() ? nullptr : visited_parents.top()); bool is_left_child = (del_parent != nullptr) && (data < del_parent->data); if ((del_node->left == nullptr) && (del_node->right == nullptr)) { if (del_parent != nullptr) { if (is_left_child) del_parent->left = nullptr; else del_parent->right = nullptr; } else { delete del_node; return nullptr; } delete del_node; } else if ((del_node->left == nullptr) || (del_node->right == nullptr)) { Node *child = (del_node->left == nullptr ? del_node->right : del_node->left); if (del_parent != nullptr) { if (is_left_child) del_parent->left = child; else del_parent->right = child; } else { delete del_node; return child; } delete del_node; } else { Node *successor = del_node->right; while(successor->left != nullptr) successor = successor->left; del_node->data = successor->data; del_node->right = deleteNode(del_node->right, successor->data); visited_parents.push(del_node); } while(!visited_parents.empty()) { Node *parent = visited_parents.top(); visited_parents.pop(); int l_height = height(parent->left); int r_height = height(parent->right); if (std::abs(l_height - r_height) > 1) { if (l_height > r_height) { if (height(parent->left->left) < height(parent->left->right)) parent->left = rotateL(parent->left); parent = rotateR(parent); } else { if (height(parent->right->right) < height(parent->right->left)) parent->right = rotateR(parent->right); parent = rotateL(parent); } } parent->height = std::max(height(parent->left), height(parent->right)) + 1; if (visited_parents.empty()) { return parent; } else { Node *grand_parent = visited_parents.top(); if (parent->data > grand_parent->data) grand_parent->right = parent; else grand_parent->left = parent; } } } Node* rotateL(Node* root) { if (root->right == nullptr) return root; Node *new_root = root->right; Node *temp_node = new_root->left; new_root->left = root; root->right = temp_node; root->height = std::max(height(root->left), height(root->right)) + 1; new_root->height = std::max(height(new_root->left), height(new_root->right)) + 1; return new_root; } Node* rotateR(Node* root) { if (root->left == nullptr) return root; Node *new_root = root->left; Node *temp_node = new_root->right; new_root->right = root; root->left = temp_node; root->height = std::max(height(root->left), height(root->right)) + 1; new_root->height = std::max(height(new_root->left), height(new_root->right)) + 1; return new_root; }
true
cd5cd2e40aa2ee4e21ee1b7494ed89a187098b26
C++
HyunsuKim6/Algorithm
/Divide&Conquer/2448.cpp
UTF-8
633
3.390625
3
[]
no_license
#include <iostream> using namespace std; int a[8000][4000] = { 0 }; void star(int x,int y, int h) { if (h == 3) { a[x][y] = 1; a[x - 1][y + 1] = 1; a[x + 1][y + 1] = 1; a[x - 2][y + 2] = 1; a[x - 1][y + 2] = 1; a[x][y + 2] = 1; a[x + 1][y + 2] = 1; a[x + 2][y + 2] = 1; return; } star(x, y, h/ 2); star(x - h / 2, y + h / 2, h / 2); star(x + h / 2, y + h / 2, h / 2); } int main() { int n; cin >> n; star(4000, 0, n); for (int i = 0; i < n; i++) { for (int j = 4000 - n +1; j < 4000+n; j++) { if (a[j][i] == 1) { cout << '*'; } else { cout << ' '; } } cout << endl; } }
true
c485732a9f44d2ea4cb0e0808d5505f2c7e02fc1
C++
Shubham915Arora/C-
/struct1.cpp
UTF-8
4,079
3.484375
3
[]
no_license
#include<iostream > #include<cstdlib> using namespace std; struct emp { int ecode; char name[50]; int age ; float salary; char ch1; }; int main() { emp e[1]; for(int i=0;i<=1;i++){ cout<<"\n Please Enter the details of the Employee : "<<i; cout<<"\n Employee code :"; cin>>e[i].ecode; cout<<"\n Name :"; cin>>e[i].name; cout<<"\n Age :"; cin>>e[i].age; cout<<"\n Salary :"; cin>>e[i].salary; } int ch,ec,ch2,c1=0,ch3,min; char ch1; do{ system("clear"); cout<<"\n Please Enter Your choice : "; cout<<"\n 1. Exit "; cout<<"\n 2. Display "; cout<<"\n 3. Change "; cout<<"\n 4. Sort "; cin>>ch; switch(ch){ case 2:{ cout<<"\n Please Enter the ecode of the employee of whom you wish to see the details :"; cin>>ec; int c=0; for(int j=0;j<=1;j++){ if(e[j].ecode==ec){ cout<<"\n Name of the employee :"<<e[j].name; cout<<"\n Age of the employee :"<<e[j].age; cout<<"\n Salary of the Employee :"<<e[j].salary; } else c++; } if(c==2){ cout<<"\n You Enetered a Wrong choice "; } } break; case 1:exit(0); default :{cout<<"\n SORRY!!!! , You entered a Wrong choice \n Press any key to try again "; break; } case 3: { cout<<"\n Please enter the ecode of the employee of whom you want to change the details : "; cin>>ec; for(int k=0;k<=1;k++){ if(e[k].ecode==ec){ cout<<"\n Please choose what do you want to change :"; cout<<"\n 1.) Name "; cout<<"\n 2.) Age "; cin>>ch2; switch(ch2){ case 1:{ cout<<"\n Exsisting Name of the Employee :"<<e[k].name; cout<<"\n Please Enter the new name : "; cin>>e[k].name; break; } case 2:{ cout<<"\n Exsisting age of the Employee : "<<e[k].age; cout<<"\n Please Enter the new age of the employee"; cin>>e[k].age; break; } } } else c1++; } if(c1==2) cout<<"\n You Entered a wrong ecode!!"; break; } case 4:{ int choice; cout<<"\n Please Enter your choice : "; cout<<"\n 1.) Age " cout<<"\n 2.) Salary "; cin>>ch3; switch(choice){ case 1:{ for(int i=0,j=0;i<5){ if(e[i].age>e[i+1].age){ i++; } else{ struct temp; temp=e[i]; e[i]=e[i+1]; e[i+1]=temp; i--; } } for(int i=0;i<5;i++){ cout<<e[i] } } } } } cout<<"\n Do you wish to continue (Y/N) ? "; cin>>ch1; }while(ch1=='y'||ch1=='Y'); }
true
cc593452c85d96c974dc33c06b9a8197312d76c5
C++
LuisMiranda132/othelloAI
/final/scout.cc
UTF-8
501
2.78125
3
[ "MIT" ]
permissive
#include "scout.h" #include <iostream> #include <time.h> using namespace std; int main(){ int i; int j; for (j = 33; j>=0; --j) { state_t init; bool curPlay = true; for(i=0;i<j;++i){ init = init.move(curPlay,PV[i]); curPlay = !curPlay; } time_t start, end; time (&start); int n = scout(init, 34-i, curPlay); time(&end); double dif = difftime (end,start); cout << "SCOUT: Para " << 34-i << " estados(" << "estado: " << i << ") duro " << dif << " segundos" << endl; } }
true
8ba140130111a2cdd14275d569d4e4d2d3eb876d
C++
jacky-huiyao/LeetCode
/Algorithm/#35#Search_Insert_Position/Search_Insert_Position.cpp
UTF-8
607
3.453125
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> using namespace std; class Solution { public: int searchInsert(int A[], int n, int target) { int i = 0; int j = n - 1; while (i <= j) { int mid = (int)((i + j)/2); if (A[mid] == target) return mid; else if (A[mid] > target) j = mid - 1; else i = mid + 1; } return i; } }; int main() { int a[] = {5, 6, 7, 8, 9, 10}; Solution sol; cout<<sol.searchInsert(a,6,11)<<endl; return 0; }
true
1f71e2700c9faab1a3e9d8cadc7c5a87df1985d2
C++
RaresPopescu0807/ComputerGraphics
/Framework-EGC-master/Source/Laboratoare/Tema2/Transform3D.h
UTF-8
1,153
2.984375
3
[]
no_license
#pragma once #include <include/glm.h> namespace Transform3D { // Translate matrix inline glm::mat4 Translate(float translateX, float translateY, float translateZ) { // TODO implement translate matrix return glm::mat4(1,0,0,0,0,1,0,0,0,0,1,0,translateX,translateY,translateZ,1); } // Scale matrix inline glm::mat4 Scale(float scaleX, float scaleY, float scaleZ) { // TODO implement scale matrix return glm::mat4(scaleX,0,0,0,0,scaleY,0,0,0,0,scaleZ,0,0,0,0,1); } // Rotate matrix relative to the OZ axis inline glm::mat4 RotateOZ(float radians) { // TODO implement rotate matrix return glm::mat4(1,0,0,0,0,cos(radians),sin(radians),0,0,-sin(radians),cos(radians),0,0,0,0,1); } // Rotate matrix relative to the OY axis inline glm::mat4 RotateOY(float radians) { // TODO implement rotate matrix return glm::mat4(cos(radians),0,-sin(radians),0,0,1,0,0,sin(radians),0,cos(radians),0,0,0,0,1); } // Rotate matrix relative to the OX axis inline glm::mat4 RotateOX(float radians) { // TODO implement rotate matrix return glm::mat4(cos(radians),sin(radians),0,0,-sin(radians),cos(radians),0,0,0,0,1,0,0,0,0,1); } }
true
56a95e7afccabb9df6f9b1c78a7acc20dfc00bb6
C++
anushkaGurjar99/Data-Structure-and-Algorithms
/LEETCODE/Math/Q171. Excel Sheet Column Number.cpp
UTF-8
865
3.34375
3
[]
no_license
/* * Author : Anushka Gurjar * Date : June 2020 * flags : -std=c++14 */ #include<bits/stdc++.h> using namespace std; // Problem Statement: https://leetcode.com/problems/excel-sheet-column-number/ class Solution{ public: int titleToNumber(string s){ if(s.size() == 0) return 0; int result = 0; for(auto ch: s){ result *= 26; result += ch - 'A' + 1; } return result; } }; /* For every additional digit of the string, we multiply the digit value by 26^n where n is the number of digits it is away from the one's place. This is similar to how the number 254 could be broken down as this: (2 x 10 x 10) + (5 x 10) + (4). The reason we use 26 instead of 10 is because 26 is our base. Example:- BCM = (2 x 26 x 26) + (3 x 26) + (13) */
true
546b7f294958ac73059c3d3ae08f4bb389e2c554
C++
bobur554396/PPI2020FALL
/w3/G1/20.cpp
UTF-8
336
3
3
[]
no_license
#include <iostream> using namespace std; int main() { // do while /* for(;condition;){ } while(condition){ } do { } while(condition) */ // int i = 100; // while(i < 10){ // cout << i << " "; // i++; // } int i = 100; do { cout << i << " "; i++; } while (i < 10); return 0; }
true
4a4f24d8f9bf57723389c81be143ba0aa88991e4
C++
Vitaliy-Grigoriev/PDL
/core/endian/engines/impl/LittleEndianImpl.hpp
UTF-8
2,621
2.890625
3
[ "MIT" ]
permissive
// ============================================================================ // Copyright (c) 2017-2021, by Vitaly Grigoriev, <Vit.link420@gmail.com>. // This file is part of PdlFramework open source project under MIT License. // ============================================================================ #pragma once #include <core/data/RawData.hpp> #include <optional> namespace pdl::core::endian { /** * @brief Function that performs left shift by a specified byte offset in little-endian format. * * @param [in] _begin - Pointer to begin position in byte sequence. * @param [in] _end - Pointer to end position in byte sequence (the element following the last one). * @param [in] _shift - Byte offset for left shift. * @param [in] _fill - New value of byte after left shift. */ void leftShiftLE(data::RawData::MemoryPointer _begin, data::RawData::MemoryPointer _end, size_t _shift, std::optional<data::RawData::Byte> _fill) noexcept; /** * @brief Function that performs right shift by a specified byte offset in little-endian format. * * @param [in] _begin - Pointer to begin position of the byte sequence. * @param [in] _end - Pointer to end position of the byte sequence (the element following the last one). * @param [in] _shift - Byte offset for right shift. * @param [in] _fill - New value of byte after right shift. */ void rightShiftLE(data::RawData::MemoryPointer _begin, data::RawData::MemoryConstPointer _end, size_t _shift, std::optional<data::RawData::Byte> _fill) noexcept; /** * @brief Function that performs left rotate by a specified byte offset in little-endian format. * * @param [in] _begin - Pointer to begin position in byte sequence. * @param [in] _end - Pointer to end position in byte sequence (the element following the last one). * @param [in] _shift - Byte offset for left rotate. */ void leftRotateLE(data::RawData::MemoryConstPointer _begin, data::RawData::MemoryPointer _end, std::size_t _shift) noexcept; /** * @brief Function that performs right rotate by a specified byte offset in little-endian format. * * @param [in] _begin - Pointer to begin position in byte sequence. * @param [in] _end - Pointer to end position in byte sequence (the element following the last one). * @param [in] _shift - Byte offset for right rotate. */ void rightRotateLE(data::RawData::MemoryPointer _begin, data::RawData::MemoryConstPointer _end, std::size_t _shift) noexcept; } // namespace endian.
true
ed5b1e5b324fa607deee6173e4efd8b02ea78755
C++
AbdelrahmanShaheen/DataStructures_Imp
/AVL-Tree/src/AvlTree.cpp
UTF-8
5,786
3.5
4
[]
no_license
#include "../include/AvlTree.h" #include <iostream> using namespace std; AvlTree::AvlTree(Node *r) : root(r) {} void AvlTree::Insert(int value) { root = Insert(value, root); } Node *AvlTree::Insert(int value, Node *ptr) { Node *newNode; if (root == NULL) //if tree is empty. { //Create a newnode : newNode = new Node; newNode->data = value; newNode->height = 1; newNode->lchild = NULL; newNode->rchild = NULL; return newNode; } if (ptr == NULL) //for leaf nodes. { //Create a newnode : newNode = new Node; newNode->data = value; newNode->height = 1; newNode->lchild = NULL; newNode->rchild = NULL; return newNode; } if (value < ptr->data) ptr->lchild = Insert(value, ptr->lchild); //go to left child. else if (value > ptr->data) ptr->rchild = Insert(value, ptr->rchild); // go to right child. //update height after insert. ptr->height = Height(ptr); //rotations : if ((BalanceFactor(ptr) == 2) && (value < ptr->lchild->data))//right rotation. { ptr = LLRotaion(ptr); } if ((BalanceFactor(ptr) == -2) && (value > ptr->rchild->data))//left rotation. { ptr = RRRotation(ptr); } if ((BalanceFactor(ptr) == 2) && (value > ptr->lchild->data))//do right then left rotation. { ptr = LRRotation(ptr); } if ((BalanceFactor(ptr) == -2) && (value < ptr->rchild->data)) //do left then right rotation. { ptr = RLRotation(ptr); } return ptr; } void AvlTree::InorOrder() { InorOrder(root); } void AvlTree::InorOrder(Node *ptr) { if (ptr) { cout<<ptr->data<<endl; InorOrder(ptr->lchild); InorOrder(ptr->rchild); } } int AvlTree::BalanceFactor(Node *ptr) { return Height(ptr->lchild) - Height(ptr->rchild); } Node *AvlTree::LLRotaion(Node *ptr) { Node *ptr1, *ptr2; ptr1 = ptr; ptr2 = ptr->lchild; ptr1->lchild = !ptr2->rchild ? NULL : ptr2->rchild; ptr2->rchild = ptr1; //update height after rotation. ptr1->height = Height(ptr1); ptr2->height = Height(ptr2); return ptr2; } int AvlTree::Height(Node *ptr) { int hl;//height of left sub tree. int hr; //height of the right sub tree. if (!ptr) return 0; if (!ptr->lchild) hl = 0; else hl = ptr->lchild->height; if (!ptr->rchild) hr = 0; else hr = ptr->rchild->height; return hr > hl ? hr + 1 : hl + 1; } Node *AvlTree::RRRotation(Node *ptr) { Node *ptr1, *ptr2; ptr1 = ptr; ptr2 = ptr->rchild; ptr1->rchild = ptr2->lchild; ptr2->lchild = ptr1; //update the heights : ptr1->height = Height(ptr1); ptr2->height = Height(ptr2); //the new root of ptr subtree. return ptr2; } Node *AvlTree::LRRotation(Node *ptr) { Node *ptr1, *ptr2, *ptr3; ptr1 = ptr; ptr2 = ptr->lchild; ptr3 = ptr->lchild->rchild; ptr1->lchild = ptr3->rchild; ptr2->rchild = ptr3->lchild; ptr3->lchild = ptr2; ptr3->rchild = ptr1; //update heights : ptr1->height = Height(ptr1); ptr2->height = Height(ptr2); ptr3->height = Height(ptr3); //the new root of ptr subtree. return ptr3; } Node *AvlTree::RLRotation(Node *ptr) { Node *ptr1, *ptr2, *ptr3; ptr1 = ptr; ptr2 = ptr->rchild; ptr3 = ptr2->lchild; ptr1->rchild = ptr3->lchild; ptr2->lchild = ptr3->rchild; ptr3->rchild = ptr2; ptr3->lchild = ptr1; //update the heights : ptr1->height = Height(ptr1); ptr2->height = Height(ptr2); ptr3->height = Height(ptr3); //the new root of ptr subtree. return ptr3; } Node *AvlTree::InPre(Node *ptr) { if (ptr->rchild != NULL) { ptr = ptr->rchild; } return ptr; } Node *AvlTree::InSucc(Node *ptr) { if (ptr->lchild != NULL) { ptr = ptr->lchild; } return ptr; } Node *AvlTree::Delete(int value, Node *ptr) { Node *ptr2; if (ptr == NULL) //for empty BST. return NULL; if (value < ptr->data) ptr->lchild = Delete(value, ptr->lchild); //go left. else if (value > ptr->data) ptr->rchild = Delete(value, ptr->rchild); //go right. else { if (ptr->lchild == NULL && ptr->rchild == NULL) //for a leaf node. { delete ptr; return NULL; } if (Height(ptr->lchild) > Height(ptr->rchild)) //for non leaf node . { ptr2 = InPre(ptr->lchild); ptr->data = ptr2->data; ptr->lchild = Delete(ptr2->data, ptr->lchild); } else { //for non leaf node. ptr2 = InSucc(ptr->rchild); ptr->data = ptr2->data; ptr->rchild = Delete(ptr2->data, ptr->rchild); } } //update height after delete. ptr->height = Height(ptr); //do rotations to make avl tree balanced after deletion: if (((BalanceFactor(ptr) == 2) && (BalanceFactor(ptr->lchild) == 1)) || ((BalanceFactor(ptr) == 2) && (BalanceFactor(ptr->lchild) == 0))) { ptr = LLRotaion(ptr); //right rotation. } else if (((BalanceFactor(ptr) == -2) && BalanceFactor(ptr->rchild) == -1) || ((BalanceFactor(ptr) == -2) && BalanceFactor(ptr->rchild) == 0)) { ptr = RRRotation(ptr); //left rotation. } else if ((BalanceFactor(ptr) == 2) && (BalanceFactor(ptr->lchild) == -1)) { ptr = LRRotation(ptr); //do right then left rotation. } else if ((BalanceFactor(ptr) == -2) && (BalanceFactor(ptr->rchild) == 1)) { ptr = RLRotation(ptr); //do left then right rotation. } return ptr; } void AvlTree::Delete(int value) { root = Delete(value, root); }
true
941e6c2c3c901f5ae292f948675889feab807855
C++
barunpuri/study
/C++ lifegame/lifegame.cpp
UTF-8
3,075
3.046875
3
[]
no_license
#include <iostream> #include <fstream> #include <vector> #include "lifegame.h" lifegame::lifegame() :row_size_(0), col_size_(0), generation_(0) { field_.clear(); } lifegame::lifegame(std::ifstream &fin) :row_size_(0), col_size_(0), generation_(0) { int data; fin >> row_size_ >> col_size_; input_data(fin); } lifegame::lifegame(int row, int col, std::ifstream& fin) :row_size_(row), col_size_(col), generation_(0) { input_data(fin); } int lifegame::getRow() const { return row_size_; } int lifegame::getCol() const { return col_size_; } int lifegame::getSize() const { return getRow()*getCol(); } int lifegame::getGeneration() const { return generation_; } void lifegame::input_data(std::ifstream& fin) { char data; for(int i=0; i<getRow()*getCol(); ++i) { fin >> data; field_.push_back(data); } } void lifegame::next() { std::vector<int> coming; coming.clear(); for(int i=0; i<getRow(); ++i) { for(int j=0; j<getCol(); ++j) { coming.push_back( update(i,j) ); } } for(int i=0; i<getSize(); ++i) field_[i] = coming[i]; ++generation_; } char lifegame::update(int i, int j) { int cnt ; cnt = count_close_cells(i, j); if( cnt == 3 ) return 'O'; else if( (field_[i*getCol() + j] == 'O')&&(cnt==2) ) return 'O'; else return 'X'; } int lifegame::count_close_cells(int x, int y) { int cnt = 0; int x_dir[8] = {-1,-1,0,1,1,1,0,-1}; int y_dir[8] = {0,1,1,1,0,-1,-1,-1}; int x_loc; int y_loc; for(int i=0; i<8; ++i) { x_loc = x+x_dir[i]; y_loc = y+y_dir[i]; if( ( (x%getRow()==0)&&(x_dir[i]==-1) ) ||( (x%getRow()==getRow()-1)&&(x_dir[i]==1) ) ||( (y%getCol()==0)&&(y_dir[i]==-1) ) ||( (y%getCol()==getCol()-1)&&(y_dir[i]==1) ) ) continue; if( field_[x_loc*getCol() + y_loc] == 'O') ++cnt; } return cnt; } int lifegame::count_living_cells() { int cnt=0; for(int i=0; i<getSize(); ++i) if( field_[i] == 'O' ) cnt += 1; return cnt; } char lifegame::operator() (unsigned int row, unsigned int col) const { return field_[row*getCol() + col]; } char& lifegame::operator() (unsigned int row, unsigned int col) { return field_[row*getCol() + col]; } int lifegame::color(int i, int j){ std::vector<bool> visited(getSize(), false); int cnt =0; if( field_[i*getCol() + j] == 'O' ) { visited[i*getCol() + j] = true; cnt = cnt_color(i,j, visited); } return cnt; } int lifegame::cnt_color(int x, int y, std::vector<bool>& visited) { int x_loc; int y_loc; int x_dir[8] = {-1,-1,0,1,1,1,0,-1}; int y_dir[8] = {0,1,1,1,0,-1,-1,-1}; int cnt = 1; //자기자신 for(int i=0; i<8; ++i) { x_loc = x+x_dir[i]; y_loc = y+y_dir[i]; if( ( (x%getRow()==0)&&(x_dir[i]==-1) ) ||( (x%getRow()==getRow()-1)&&(x_dir[i]==1) ) ||( (y%getCol()==0)&&(y_dir[i]==-1) ) ||( (y%getCol()==getCol()-1)&&(y_dir[i]==1) ) ) continue; if( visited[x_loc*getCol() + y_loc] ==false && field_[x_loc*getCol() + y_loc] == 'O') { visited[x_loc*getCol() + y_loc] = true; cnt += cnt_color(x_loc, y_loc, visited); } } return cnt; }
true
0174453f6da12956086db4c5bd27044e95344800
C++
bytzar/Tic-Tac-Toe-C-
/tic tac toe/Debug/main.cpp
UTF-8
5,127
3.734375
4
[]
no_license
#include <iostream> #include <windows.h> using namespace std; char square[9] = { '0','1','2','3','4','5','6','7','8' }; int cock = 0; int i; void grid() //prints the 3x3 grid { for (i = 0; i <= square[8]; i++) //repeats eight times, once for each square { if (i == 3) //once the third cycle has been reached, a new line is drawn { cout << "\n"; } if (i == 6) //once the sixth cycle has been reached, a new line is drawn { cout << "\n"; } if (i == 9) break; else if (square[i] == 20) //20 stands for every number that shall be printed as X, 20 is merely an arbitrairy number in this case cout << "X "; else if (square[i] == 21) cout << "O "; else cout << square[i] << " "; //if it is neither an X nor a Y field, the number corresponding for the field shall be printed with a space attachted to it } } void gam() { lamel: cout << endl << "\nP1 input a square and press enter" << "\n" << "\n"; cin >> cock; if (square[cock] == 20) //checks if the inout square is already taken by P1 { cout << "\nselect a square that is not taken" << "\n" << "\n"; goto lamel; grid(); } else if (square[cock] == 21) //checks if the inout square is already taken by P2 { cout << "\nselect a square that is not taken" << "\n" << "\n"; grid(); goto lamel; } else if (!cin) //if an inout is given in the wrong format, an eroor will be thrown { cout << "\nwrong input" << "\n" << "\n"; cin.clear(); cin.ignore(); grid(); goto lamel; } else if (cock > 8) //checks if input is above the available sqaure number { cout << "\nselect a valid square" << "\n" << "\n"; grid(); goto lamel; } else if (cock < 0) //checks if input is below the available sqaure number { cout << "\nwrong input" << "\n" << "\n"; cin.clear(); cin.ignore(); grid(); goto lamel; } else //if there are no errors the sqaure will be allocated to player 1 { square[cock] = 20; cout << "\n"; grid(); } } void game() //same thing but for player 2 { lecock: cout << endl << "\nP2 input a square and press enter" << "\n" << "\n"; cin >> cock; if (square[cock] == 20) { cout << "\nselect a square that is not taken" << "\n" << "\n"; grid(); goto lecock; } else if (square[cock] == 21) { cout << "\nselect a square that is not taken" << "\n" << "\n"; grid(); goto lecock; } else if (!cin) { cout << "\nwrong input" << "\n" << "\n"; cin.clear(); cin.ignore(); grid(); goto lecock; } else if (cock > 8) { cout << "\nselect a valid square" << "\n" << "\n"; grid(); goto lecock; } else if (cock < 0) { cout << "\nwrong input" << "\n" << "\n"; cin.clear(); cin.ignore(); grid(); goto lecock; } else { square[cock] = 21; cout << "\n"; grid(); } } int winflag() //checks if game shall be ended { if (square[0] == square[1] && square[1] == square[2]) //should three consequetive(:() squares allign the game shall be ended { cout << "\n\ncockgratulations\n\n"; return 0; } else if (square[3] == square[4] && square[4] == square[5]) { cout << "\n\ncockgratulations\n\n"; return 0; } else if (square[6] == square[7] && square[7] == square[8]) { cout << "\n\ncockgratulations\n\n"; return 0; } else if (square[0] == square[3] && square[3] == square[6]) { cout << "\n\ncockgratulations\n\n"; return 0; } else if (square[1] == square[4] && square[4] == square[7]) { cout << "\n\ncockgratulations\n\n"; return 0; } else if (square[2] == square[5] && square[5] == square[8]) { cout << "\n\ncockgratulations\n\n"; return 0; } else if (square[0] == square[4] && square[4] == square[8]) { cout << "\n\ncockgratulations\n\n"; return 0; } else if (square[2] == square[4] && square[4] == square[6]) { cout << "\n\ncockgratulations\n\n"; return 0; } else if (square[0] == square[3] && square[3] == square[6]) { cout << "\n\ncockgratulations\n\n"; return 0; } else { return 1; } } int main() //ask both players to complate for plays plus an extra one for P1, should the game not end before hand { start: grid(); for (int g = 0; g < 4; g++) { gam(); if (winflag() == 0) { goto lamar; } game(); if (winflag() == 0) { goto lamar; } } gam(); if (winflag() == 0) { goto lamar; } else { cout << "\nmagendarmentzuendung"; } lamar: string malock; cout << "play again? [y/n]:\n\n"; cin >> malock; if (malock == "y") { int cock = 0; square[0] = '0'; square[1] = '1'; square[2] = '2'; square[3] = '3'; square[4] = '4'; square[5] = '5'; square[6] = '6'; square[7] = '7'; square[8] = '8'; int g = 0; cout << "\n"; goto start; } else if (malock == "n") { exit; } else { cout << "\noh okay screw you then"; Sleep(2000); exit; } }
true
98242946077d35f182f3ff418fed3b28f95afc0e
C++
rafaelGuasselli/estudo_cpp
/Exemplos/stl/templates/vector.cpp
UTF-8
1,990
3.65625
4
[]
no_license
#include<iostream> #include<vector> using namespace std; int main(){ vector<int> vetor2;//Vector<tipo> nome; vector<int> vetor(3,5);//Parametros (x,y) tem o mesmo funcionamento do assign //caso não tenha o valor x sera adicionado 0 y vezes vetor2.clear();//"Reseta o vetor", muda o tamanho do vetor pra 0, mas os valores continuam la //so sera alterado na proxima inserção de dado que sobrescrevera o dado anteriormente escrito vetor.swap(vetor2);//Troca os valores do vetor1 pelo do vetor dois e vice versa vetor.push_back(10);//Adiciona um valor ao fim do vetor vetor.assign(7,100);//Adiciona x valores y ao vetor, sobrescreve apartir de 0 a x - 1 vetor.pop_back();//Apaga o ultimo elemento do vetor vetor.erase(vetor.begin() + 1,vetor.begin() + 2);//Apaga o valor entre a pos x e y vetor.emplace(vetor.begin() + 1,10);//Coloca um valor na pos x //caso tenha espaço empurra o antigo valor para o lado, se não sobrescreve vetor.emplace_back(10);//Adiciona um valor na ultima pos, mesmas propriedades do emplace vetor.empty();//teste se o vetor ta vazio vetor.resize(20, 100);//Redimenciona o vetor para x pos, caso x seja maior que o size as novas pos vetor.shrink_to_fit();//Deixa o vetor apenas com o tamanho necessario para alocar os valores atuais //terão valor y. Caso y não seja digitado as novas pos serão 0 int *ponteiro = vetor.data();//Aponta para o vetor, caso o vetor seja redimensionado da ruim cout<<vetor[3]<<endl;//Vetor[x], acessa o valor na posição x cout<<vetor.at(3)<<endl;//Mesmo que o de cima cout<<vetor.front()<<endl;//Pega o primeiro valor da sequencia cout<<vetor.back()<<endl;//Pega o ultimo valor da sequencia cout<<vetor.size()<<endl;//Pega o tamanho do vetor cout<<vetor.max_size()<<endl;//Pega o tamanho max do vetor cout<<vetor.capacity()<<endl;//Pega a capacidade do vetor cout<<ponteiro[3]<<endl; cout<<vetor2[0]; return 0; }
true
9e1f5b43cca6ecb29aa696c37631ffc7b28000c8
C++
VRedBull/C-Fundamentals
/Source Code/Basics/StockMarket.cxx
UTF-8
582
3.734375
4
[]
no_license
#include <iostream> #include <cmath> //Just a library to let us use some math functions using namespace std; int main(){ float amount, principal, interest=0.02; int nDays; cout<<"Enter for many days you wanna invest = "<<flush; cin>>nDays; cout<<"Enter your Money : "<<flush; cin>>amount; for (int i = 1; i<=nDays; i++){ amount = principal*pow(1+interest,i);//pow is a function in cmath library to use exponents if pow(2,3) then it's 2^3 cout<<"Day "<<i<<" ______________ "<<"Amount : "<<amount<<endl; } return 0; }
true
f96bab658aaf562ee49d78a57850ba91ffb2fb77
C++
shubh09/shared
/Topcoder/SRM410/DIV2 - 250.cpp
UTF-8
1,407
2.65625
3
[]
no_license
#include <iostream> #include <vector> #include <cstdio> #include <cstring> #include <string> #include <cmath> #include <algorithm> #include <utility> using namespace std; #define FOR(i,a,b) for (i=a;i<b;i++) #define s(n) scanf("%d",&n) #define p(n) printf("%d\n",n) #define pl(n) printf("%lld\n",n) #define sd(n) int n;scanf("%d",&n) #define sl(n) scanf("%lld",&n) #define sld(n) long long int n;scanf("%lld",&n) typedef long long ll; class ContiguousCacheEasy{ public: int bytesRead(int n,int k,vector <int> arr) { int s=arr.size(); int b=0; int ans=0; int i; FOR(i,0,s) { if (!(arr[i]-b<=k-1&&arr[i]>=b)) { int bt=b; if (arr[i]>b) { b=arr[i]-k+1; } else { b=arr[i]; } ans+=min(abs(bt-b),k); //p(abs(bt-b)); } } return ans; } }; //for testing int main() { ContiguousCacheEasy cls; int t=100; int i,j; vector <int> arr; FOR(i,0,t) { arr.clear(); sd(n);sd(k); sd(tt); FOR(j,0,tt) { sd(temp); arr.push_back(temp); } p(cls.bytesRead(n,k,arr)); } }
true
6e26a7487fd17d620c59b39e59e8a3b7522f9967
C++
Graphics-Physics-Libraries/RenderLibrary
/TFMEngine/src/tests/SimpleScene.cpp
UTF-8
4,687
2.5625
3
[]
no_license
#include "tests/SimpleScene.h" namespace SimpleScene { Mesh::Mesh * loadMesh(const std::string & file, unsigned int options) { std::vector<Mesh::Mesh *> meshes = Mesh::MeshManager::getInstance().loadMeshFromFile(file, options); if (meshes.size() == 0) { Log::getInstance().logError("No meshes were found in the given file"); return NULL; } return meshes[0]; } int main(int argc, char ** arg) { /*** INSTANCE SET UP ***/ // Default initialization (registers components for asset loading, memory building, synchronization, etc.) DefaultEngineInitialization(); unsigned int cubeOptions = (Mesh::Mesh::OPTION_COMPUTE_NORMALS_IF_ABSENT); unsigned int sphereOptions = (Mesh::Mesh::OPTION_COMPUTE_SMOOTHNORMALS_IF_ABSENT | Mesh::Mesh::OPTION_JOIN_IDENTICAL_VERTICES); // Asset load Mesh::Mesh * cube = loadMesh("./assets/mat_cube.obj", cubeOptions); Mesh::Mesh * sphere = loadMesh("./assets/sphere_mat_opacity.obj", sphereOptions); Mesh::Mesh * cube2 = loadMesh("./assets/mat_cube_2.obj", cubeOptions); Mesh::Mesh * sun = loadMesh("./assets/emissive_sphere.obj", sphereOptions); Mesh::Mesh * cubeBump = loadMesh("./assets/cube_bump.obj", cubeOptions | Mesh::Mesh::OPTION_COMPUTE_TANGENTSPACE); // Window creation Graphics::WindowConfiguration config; config.openGLContextProfile = GLFW_OPENGL_CORE_PROFILE; config.openGLMajorVersion = 4; config.openGLMinorVersion = 2; config.windowHeight = 750; config.windowWidth = 1200; config.windowTitle = "Test Instance"; config.windowPosX = 50; config.windowPosY = 50; DefaultImpl::GLFWWindowHandler * window = Graphics::ContextManager::getInstance().createWindow<DefaultImpl::GLFWWindowHandler>(config); // Engine Instance creation EngineInstance * instance = InstanceManager::getInstance().createInstance("TestInstance", window); // Scene set up RenderLib::Scene * scene = instance->getSceneManager().createScene("TestScene"); instance->getSceneManager().setActiveScene("TestScene"); if (scene == NULL) { std::cout << "RenderLib: Could not create a new scene named TestScene" << std::endl; return -1; } // Camera set up RenderLib::Camera * cam = scene->addCamera<RenderLib::Camera>("Main_Camera"); cam->addComponent<DefaultImpl::CameraController>(); cam->setProjectionParams((FLOAT)0.5, (FLOAT)75.0, (FLOAT)45.0); cam->translateView(VECTOR3(0.0, 0.0, -8.0)); // Light set up Lighting::DirectionalLight * dl = scene->addDirectionalLight("Sun"); dl->setLightColor(VECTOR3(1.0, 1.0, 1.0)); dl->setDiffuseIntensity(1.0f); dl->setSpecularIntensity(1.0f); dl->setAmbientIntensity(0.15f); dl->setDirection(VECTOR3(1.0, 1.0, 1.0)); Lighting::PointLight * pl = scene->addPointLight("Bulb"); pl->setLightColor(VECTOR3((FLOAT)1.0, (FLOAT)1.0, (FLOAT)0.4)); pl->setPosition(VECTOR3(-3.0, 2.0, 5.0)); pl->setDiffuseIntensity(1.0f); pl->setAmbientIntensity(0.1f); pl->setSpecularIntensity(0.9f); pl->setAttenuationFactors(0.7f, 0.2f, 0.1f); // Object set up // "Cube" RenderLib::SceneObject * obj = scene->addObject<SceneObject>("Cube"); obj->addComponent<DefaultImpl::MeshFilter>()->mesh = cube; obj->addComponent<DefaultImpl::MeshRenderer>(); obj->addComponent<DefaultImpl::ObjectSpinner>(); // "Moon" RenderLib::SceneObject * moon = scene->addObject<SceneObject>("Moon"); moon->transform.translate(VECTOR3(5, 0, 0)); moon->transform.scale(VECTOR3(0.5, 0.5, 0.5)); moon->addComponent<DefaultImpl::MeshFilter>()->mesh = sphere; moon->addComponent<DefaultImpl::MeshRenderer>(); moon->setParent(obj); // Cube crown RenderLib::SceneObject * crown = scene->addObject<SceneObject>("Crown"); crown->transform.translate(VECTOR3(0, 5, 0)); crown->transform.scale(VECTOR3(0.5, 0.5, 0.5)); crown->addComponent<DefaultImpl::MeshFilter>()->mesh = cube2; crown->addComponent<DefaultImpl::MeshRenderer>(); crown->setParent(obj); // Cube feet RenderLib::SceneObject * feet = scene->addObject<SceneObject>("Feet"); feet->transform.translate(VECTOR3(0, -2, 0)); //feet->transform.scale(VECTOR3(0.5, 0.5, 0.5)); feet->addComponent<DefaultImpl::MeshFilter>()->mesh = cubeBump; feet->addComponent<DefaultImpl::MeshRenderer>(); feet->setParent(obj); RenderLib::SceneObject * sunObj = scene->addObject<SceneObject>("Sun"); sunObj->transform.translate(VECTOR3(-3.0, 0.0, -3.0)); sunObj->addComponent<DefaultImpl::MeshFilter>()->mesh = sun; sunObj->addComponent<DefaultImpl::MeshRenderer>(); /*** EXECUTION (BLOCKING UNTIL ALL INSTANCES ARE DONE) ***/ // Run pipeline InstanceManager::getInstance().launchInstances(ExecutionMode::EXECUTION_PARALLEL); return 0; } }
true
3fe13b1fbe2b540569a5ff5216e0cc68ff72de97
C++
SJX516/DataStructureCppCode
/表达式计算/Calculate.cpp
GB18030
5,186
3.109375
3
[]
no_license
#include "Calculate.h" #include <string.h> using namespace std; Calculate::Calculate(string temp) { infix = temp; for(int i = 0 ; i < 20; i++) { ser_num[i] = 0; } ser = -1; } Calculate::~Calculate() { symbol_stack.Clear(); suffix_stack.Clear(); } int Calculate::Get_ser_num() //׺ʽеϳɵ֣ser_num[]Уµ׺ʽ { string temp = infix; infix = ""; bool whole_num = false; for(int i = 0 ; temp[i] !='\0' ; i++) { switch( temp[i] ) { case '+': case '-': case '*': case '/': case '(': case ')': infix = infix + temp[i]; whole_num = false; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if( whole_num ) { ser_num[ser] = 10*ser_num[ser]+temp[i]-'0'; } else { ser++; char m = '0'+ser; infix = infix + m; ser_num[ser] = 10*ser_num[ser]+temp[i]-'0'; whole_num = true; } break; default: infix = ""; cout<<"ʽкв淶ַʶ"<<endl; return 0; break; } } if( !Check() ) { cout<<"ʽ׺ʽĸʽ"<<endl; infix = ""; } return 0; } //ջ>ջʱջ int Calculate::Get_suffix() //ջ<ջʱջȽϣͬʱȥ { if( infix == "" ) return 0; for(int i = 0; infix[i] != '\0'; i++) { if( infix[i] >='0' && infix[i] <='C' ) { suffix_stack.Push( infix[i] ); } else { if( symbol_stack.IsEmpty() ) { symbol_stack.Push( infix[i] ); } else { char temp = '\0'; symbol_stack.Top(temp); if( Get_priority(infix[i],true) > Get_priority(temp,false) ) { symbol_stack.Push(infix[i]); } else if( Get_priority(infix[i],true) < Get_priority(temp,false) ) { symbol_stack.Pop(temp); suffix_stack.Push(temp); i--; } else if( Get_priority(infix[i],true) == Get_priority(temp,false) ) { symbol_stack.Pop(temp); } } } } char m='\0'; while( !symbol_stack.IsEmpty() ) { symbol_stack.Pop(m); suffix_stack.Push(m); } return 0; } int Calculate::Count() { ListStack<float> result; string suffix = ""; if( infix == "" ) return 0; char m='\0'; while( !suffix_stack.IsEmpty() ) { suffix_stack.Pop(m); suffix = suffix + m; } int len = suffix.size(); // cout<<len<<endl; for(int i = len-1; i >= 0; i-- ) { if( suffix[i] >= '0' && suffix[i] <= 'C' ) { result.Push(ser_num[ suffix[i]-'0' ] ); } else { float s2 ,s1; result.Pop(s2); result.Pop(s1); switch(suffix[i]) { case '+': result.Push(s1+s2); break; case '-': result.Push(s1-s2); break; case '*': result.Push(s1*s2); break; case '/': if( s2 == 0 ) { cout<<"Ϊ0"<<endl; return 0; } result.Push(s1/s2); break; } } } float k = 0; result.Top(k); cout<<"Ϊ"<<k<<endl; return 0; } int Calculate::Get_priority(char temp,bool out_stack) { if( out_stack ) { switch(temp) { case '(': return 8; case ')': return 1; case '+': case '-': return 2; case '*': case '/': return 4; } } else { switch(temp) { case '(': return 1; case ')': return 8; case '+': case '-': return 3; case '*': case '/': return 5; } } return 0; } bool Calculate::Check() { bool judge = true; for(int i = 0; infix[i] != '\0'; i++) { if( !( infix[i] >= '0' && infix[i] <= 'C') && infix[i]!='(' && infix[i]!=')' ) { if( !judge ) { return false; } judge = false; } else { judge = true; } } return true; } void Calculate::Print() { for(int i=0 ; infix[i] != '\0' ;i++) { cout<<infix[i]<<" "; } cout<<endl; for(int i=0 ; i<=ser; i++) { cout<<ser_num[i]<<" "; } cout<<endl; }
true
517b74b75dd646062546cfaed1b57e7e31764bea
C++
MykolaNemo/AdventOfCode
/2016/Day-19/main.cpp
UTF-8
1,610
3.609375
4
[]
no_license
#include <iostream> int input = 3018458; template<class T> struct Node { T value; Node* next = nullptr; Node(Node* parent, T data) { parent->next = this; value = data; } Node(T data) { value = data; } void remove_next() { if(next != nullptr) { Node* toDelete = next; next = next->next; delete toDelete; } } }; int main() { { int length = input; int firstIndex = 1; int step = 1; while(length > 1) { step *= 2; if(length % 2 == 1) { firstIndex += step; } length /= 2; } std::cout<<"[Part 1] Answer: "<<firstIndex<<std::endl; } { Node<int>* head = new Node<int>(1); Node<int>* current = head; Node<int>* beforeHalfElf; for(int i = 2; i <= input; ++i) { current = new Node<int>(current, i); if(i == input/2) { beforeHalfElf = current; } if(i == input) { current->next = head; } } int n = input; while(beforeHalfElf->next != beforeHalfElf) { beforeHalfElf->remove_next(); if(n % 2 == 1) { beforeHalfElf = beforeHalfElf->next; } --n; } std::cout<<"[Part 2] Answer: "<<beforeHalfElf->value<<std::endl; } return 0; } /* 1 7 2 6 5 4 3 */
true
e81a0cd5eaa5297ec7c05622a79ee2d2c19cdfbd
C++
batux/stochastic_cellular_automata
/parallel_dataset_processing/src/hashcode_producer/HashcodeProducer.cpp
UTF-8
1,140
3.125
3
[]
no_license
/* * HascodeProducer.cpp * * Created on: Dec 17, 2017 * Author: batuhan */ #include "HashcodeProducer.h" HashcodeProducer::HashcodeProducer() { // TODO Auto-generated constructor stub } HashcodeProducer::~HashcodeProducer() { // TODO Auto-generated destructor stub } int HashcodeProducer::createHashCode(vector<int> &positions) { int value = 0 ; string positionsAsText = preparePositionsAsText(positions); for(char &letter : positionsAsText) { value = (37 * value) + letter; } return value; // // int h = hash; // if (h == 0 && value.length > 0) { // char val[] = value; // // for (int i = 0; i < value.length; i++) { // h = 31 * h + val[i]; // } // hash = h; // } // return h; } string HashcodeProducer::preparePositionsAsText(vector<int> &positions) { stringstream stringStream; int positionSize = positions.size(); if(positionSize > 0) { for(int pValue : positions) { stringStream << pValue; } } else { stringStream << ""; } string positionsAsText = stringStream.str(); return positionsAsText; }
true
e7a817a21570e7279300d9a3dd743ef63151c606
C++
Leshy4/Cpp17-REF-and-Practice
/CODE from Book && Random/PolyAnimals/PolyAnimals.cpp
UTF-8
959
2.8125
3
[]
no_license
#include "pch.h" #include <iostream> #include <memory> void AnimalsBeingsDogsBeingThings(); int main() { AnimalsBeingsDogsBeingThings(); } void AnimalsBeingsDogsBeingThings() { Animal atticusAnimal("Atticus", 16, 25); atticusAnimal.talk(); Dog atticusDog("Doggo", 20, 303); atticusDog.talk(); Animal* atticusPtr = &atticusAnimal; atticusPtr->talk(); atticusPtr = &atticusDog; atticusPtr->talk(); GermanShepherd atticusShepherd; // Default Constructor Values atticusShepherd.talk(); atticusPtr = &atticusAnimal; atticusPtr->talk(); Mocha MochaTheGermanDog; MochaTheGermanDog.talk(); atticusPtr = &MochaTheGermanDog; atticusPtr->talk(); Squirrel normalSquirrel; normalSquirrel.sayName(); normalSquirrel.talk(); static_cast<Animal*>(atticusPtr); dynamic_cast<Squirrel*>(atticusPtr);//Should be Squirrel Function, but atticusPtr->talk(); //Says Mocha's stuff for some reason? };
true
b9bff60413f96753140c32cb12ceb048a5780248
C++
coreyao/MyRepository
/LearningOpenGL/Source/FrameWork/ParticleSystem.cpp
UTF-8
14,264
2.578125
3
[]
no_license
#include "ParticleSystem.h" #include "OpenGL/GLProgramManager.h" #include "Director.h" #include "Image/PNGReader.h" #include "Mesh.h" #include <utility> void CParticleSystem::AddEmitter( CEmitter* pNewEmitter ) { pNewEmitter->m_pParticleSystem = this; m_vEmitter.push_back(pNewEmitter); } void CParticleSystem::Update( float dt ) { for ( auto& pEmitter : m_vEmitter ) { pEmitter->Update(dt); } } void CParticleSystem::Render() { for ( auto& pEmitter : m_vEmitter ) { pEmitter->Render(); } } STransform& CParticleSystem::GetTransformData() { return m_transform; } void CEmitter::Update( float dt ) { m_fCurDuration += dt; if ( m_fCurDuration > m_fTotalDuration ) m_fCurDuration = 0.0f; if ( m_fEmissionRate > 0 ) { float fRate = 1.0f / m_fEmissionRate; m_fCurEmissionTime += dt; if ( m_fCurEmissionTime >= fRate ) { this->AddParticle(); m_fCurEmissionTime = 0.0f; } } std::vector<CParticleInstance*> toRecycle; for (auto& pParticle : m_vActiveParticle) { pParticle->Update(dt); if ( pParticle->m_fCurLifeTime <= 0 ) { toRecycle.push_back(pParticle); } } for (auto& pParticle : toRecycle) { RecycleParticle(pParticle); } } void CEmitter::Render() { for (auto& pParticle : m_vActiveParticle) { pParticle->Render(); } } void CEmitter::AddParticle() { CParticleInstance* pParticle = nullptr; if ( !m_vInactiveParticle.empty() ) { pParticle = m_vInactiveParticle.back(); m_vInactiveParticle.pop_back(); pParticle->Reset(); } else { pParticle = new CParticleInstance; pParticle->Init(this); } m_vActiveParticle.push_back(pParticle); } void CEmitter::RecycleParticle(CParticleInstance* pParticle) { auto it = std::find(m_vActiveParticle.begin(), m_vActiveParticle.end(), pParticle); if ( it != m_vActiveParticle.end() ) { m_vActiveParticle.erase(it); m_vInactiveParticle.push_back(pParticle); } } void CEmitter::SetTexture( const std::string& sTexFileName ) { CPNGReader pngReader(sTexFileName); if ( pngReader.GetData() ) { glGenTextures(1, &m_iTexture); glBindTexture(GL_TEXTURE_2D, m_iTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pngReader.GetWidth(), pngReader.GetHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, pngReader.GetData()); glBindTexture(GL_TEXTURE_2D, 0); delete [] pngReader.GetData(); } } void CEmitter::SetEmitMode( EEmitMode mode ) { m_emitMode = mode; } STransform& CEmitter::GetTransformData() { return m_transform; } CEmitterShape& CEmitter::GetEmitterShapeRef() { return m_EmiterShape; } void CEmitter::SetEmissionRate( float fEmitRate ) { m_fEmissionRate = fEmitRate; } void CEmitter::SetTotalDuration( float fTotalDuration ) { m_fTotalDuration = fTotalDuration; } void CEmitter::SetMaxParticles(int iMaxParticles) { m_iMaxParticles = iMaxParticles; } void CEmitter::SetShaderColor( const Color4F& rColor ) { m_ShaderColor = rColor; } void CEmitter::SetBlendMode( EBlendMode eMode ) { m_eBlendMode = eMode; } void CEmitter::SetTextureAnimationInfo( int iRow, int iCol, int iLoopTime ) { m_texAnimInfo.z = iRow; m_texAnimInfo.w = iCol; m_iTexAnimLoopTime = iLoopTime; } void CEmitter::SetRenderMode( ERenderMode eRenderMode ) { m_eRenderMode = eRenderMode; } void CParticleInstance::Update( float dt ) { m_fCurLifeTime -= dt; m_fCurLifeTime = max(m_fCurLifeTime, 0.0f); float fTotalLifeTime = m_pEmitter->m_fParticleLifeTime.GetValue(m_fElapsedRatio); float fLifeTimeRatio = ( fTotalLifeTime - m_fCurLifeTime ) / fTotalLifeTime; float fFinalSize = m_SizeOverLifeTime.GetValue(fLifeTimeRatio, 1.0f) * m_fStartSize; Color4F finalVertexColor = Color4F(m_startVertexColor, 1.0f) * Color4F(m_colorOverLifeTime.GetValue(fLifeTimeRatio, Color3B::WHITE), 1.0f); float fFinalAlpha = ( m_fStartVertexAlpha / 255.0f ) * ( m_AlphaOverLifeTime.GetValue(fLifeTimeRatio, 255) / 255.0f ); m_VertexColor = Color4F( finalVertexColor.r, finalVertexColor.g, finalVertexColor.b, fFinalAlpha ); m_fCurZRotation = m_ZRotationOverLifeTime.GetValue(fLifeTimeRatio, 0.0f); if ( m_pEmitter->m_texAnimInfo.z > 0 && m_pEmitter->m_texAnimInfo.w > 0 ) { float fModifiedRatio = m_pEmitter->m_iTexAnimLoopTime * fLifeTimeRatio - (int)(m_pEmitter->m_iTexAnimLoopTime * fLifeTimeRatio); m_iCurTexSheetFrame = m_pEmitter->m_TexSheetFrameOverLifeTime.GetValue(fModifiedRatio); } m_position += m_moveDir * m_fCurSpeed * dt; Mat4 viewMatrix = CDirector::GetInstance()->GetCurViewMat(); Mat4 TranslationMatrix = Mat4::CreateTranslationMat(m_position.x,m_position.y, m_position.z); Mat4 ScaleMatrix = Mat4::CreateScaleMat(fFinalSize, fFinalSize, fFinalSize); Mat4 ZRotationMatrix = Mat4::CreateRotationMat(0, 0, m_fCurZRotation); Mat4 BillboardMatrix = Mat4::IDENTITY; Vec3 forward; if ( m_pEmitter->m_emitMode == CEmitter::EEmitMode_Free ) forward = CDirector::GetInstance()->GetPerspectiveCamera()->GetLookAtDir() * (-1); else if ( m_pEmitter->m_emitMode == CEmitter::EEmitMode_Relative ) forward = m_parentMat.GetInversed() * Vec4(CDirector::GetInstance()->GetPerspectiveCamera()->GetLookAtDir() * (-1), 0.0f); if ( m_pEmitter->m_eRenderMode == CEmitter::ERenderMode_VerticalBillboard || m_pEmitter->m_eRenderMode == CEmitter::ERenderMode_HorizontalBillboard ) forward.y = 0; forward.Normalize(); Vec3 up(0, 1, 0); Vec3 right = up.Cross(forward); right.Normalize(); up = forward.Cross(right); up.Normalize(); BillboardMatrix.SetRight(Vec3(right.x, right.y, right.z)); BillboardMatrix.SetForward(Vec3(forward.x, forward.y, forward.z)); BillboardMatrix.SetUp(Vec3(up.x, up.y, up.z)); if (m_pEmitter->m_eRenderMode == CEmitter::ERenderMode_HorizontalBillboard) { BillboardMatrix = m_parentMat.GetInversed() * BillboardMatrix * Mat4::CreateRotationMat(-90, 0, 0); } if ( m_pEmitter->m_emitMode == CEmitter::EEmitMode_Free ) { m_MV = viewMatrix * TranslationMatrix * BillboardMatrix * ZRotationMatrix * ScaleMatrix; } else if ( m_pEmitter->m_emitMode == CEmitter::EEmitMode_Relative ) { m_parentMat = m_pEmitter->m_pParticleSystem->m_transform.GetTransformMat() * m_pEmitter->m_transform.GetTransformMat(); m_MV = viewMatrix * m_parentMat * TranslationMatrix * BillboardMatrix * ZRotationMatrix * ScaleMatrix; } } void CParticleInstance::BuildVBOAndVAO() { SCommonVertex leftTop; leftTop.m_pos.x = -0.5f; leftTop.m_pos.y = 0.5f; leftTop.m_UV.x = 0; leftTop.m_UV.y = 0; leftTop.m_color = Color4F::WHITE; m_vVertex.push_back(leftTop); SCommonVertex rightTop; rightTop.m_pos.x = 0.5f; rightTop.m_pos.y = 0.5f; rightTop.m_UV.x = 1; rightTop.m_UV.y = 0; rightTop.m_color = Color4F::WHITE; m_vVertex.push_back(rightTop); SCommonVertex rightBottom; rightBottom.m_pos.x = 0.5f; rightBottom.m_pos.y = -0.5f; rightBottom.m_UV.x = 1; rightBottom.m_UV.y = 1; rightBottom.m_color = Color4F::WHITE; m_vVertex.push_back(rightBottom); SCommonVertex leftBottom; leftBottom.m_pos.x = -0.5f; leftBottom.m_pos.y = -0.5f; leftBottom.m_UV.x = 0; leftBottom.m_UV.y = 1; leftBottom.m_color = Color4F::WHITE; m_vVertex.push_back(leftBottom); m_vVertexIndex.push_back(0); m_vVertexIndex.push_back(1); m_vVertexIndex.push_back(3); m_vVertexIndex.push_back(1); m_vVertexIndex.push_back(2); m_vVertexIndex.push_back(3); glGenBuffers(1, &m_vbo); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glBufferData(GL_ARRAY_BUFFER, m_vVertex.size() * sizeof(SCommonVertex), &m_vVertex.front(), GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &m_index_vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_index_vbo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_vVertexIndex.size() * sizeof(unsigned short), &m_vVertexIndex.front(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glGenVertexArrays(1, &m_vao); glGenSamplers(1, &m_Sampler); glSamplerParameteri(m_Sampler, GL_TEXTURE_WRAP_S, GL_REPEAT); glSamplerParameteri(m_Sampler, GL_TEXTURE_WRAP_T, GL_REPEAT); glSamplerParameteri(m_Sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glSamplerParameteri(m_Sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } extern CMesh* g_planePolygonMesh; void CParticleInstance::Render() { glUseProgram(m_theProgram); glBindVertexArray(m_vao); /*glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CW);*/ glDisable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthMask(false); glEnable(GL_BLEND); if ( m_pEmitter->m_eBlendMode == CEmitter::EBlendMode_ADD ) { glBlendFunc(GL_SRC_ALPHA,GL_ONE); } else if ( m_pEmitter->m_eBlendMode == CEmitter::EBlendMode_ALPHA_BLEND ) { glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); } SetVertexColor(); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(SCommonVertex), (GLvoid*) offsetof(SCommonVertex, m_pos)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(SCommonVertex), (GLvoid*) offsetof(SCommonVertex, m_color)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(SCommonVertex), (GLvoid*) offsetof(SCommonVertex, m_UV)); GLint modelViewMatrixUnif = glGetUniformLocation(m_theProgram, "modelViewMatrix"); if ( modelViewMatrixUnif >= 0 ) { glUniformMatrix4fv(modelViewMatrixUnif, 1, GL_FALSE, m_MV.m); } GLint perspectiveMatrixUnif = glGetUniformLocation(m_theProgram, "perspectiveMatrix"); if ( perspectiveMatrixUnif >= 0 ) { const Mat4& projMat = CDirector::GetInstance()->GetCurProjectionMat(); glUniformMatrix4fv(perspectiveMatrixUnif, 1, GL_FALSE, projMat.m); } GLint colorUnif = glGetUniformLocation(m_theProgram, "u_color"); if ( colorUnif >= 0 ) { glUniform4f( colorUnif, m_pEmitter->m_ShaderColor.r, m_pEmitter->m_ShaderColor.g, m_pEmitter->m_ShaderColor.b, m_pEmitter->m_ShaderColor.a ); } if ( m_pEmitter->m_iTexture >= 0 ) { glActiveTexture(GL_TEXTURE0 + m_colorTexUnit); glBindTexture(GL_TEXTURE_2D, m_pEmitter->m_iTexture); glBindSampler(m_colorTexUnit, m_Sampler); } GLint UVAnimUnif = glGetUniformLocation(m_theProgram, "u_UVAnim"); if ( UVAnimUnif >= 0 ) { if ( m_pEmitter->m_texAnimInfo.z > 0 && m_pEmitter->m_texAnimInfo.w > 0 ) { m_pEmitter->m_texAnimInfo.x = m_iCurTexSheetFrame / (int)m_pEmitter->m_texAnimInfo.w; m_pEmitter->m_texAnimInfo.y = m_iCurTexSheetFrame % (int)m_pEmitter->m_texAnimInfo.z; } glUniform4f( UVAnimUnif, m_pEmitter->m_texAnimInfo.x, m_pEmitter->m_texAnimInfo.y, m_pEmitter->m_texAnimInfo.z, m_pEmitter->m_texAnimInfo.w ); } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_index_vbo); glDrawElements(GL_TRIANGLES, m_vVertexIndex.size(), GL_UNSIGNED_SHORT, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glBindSampler(m_colorTexUnit, 0); glUseProgram(0); glDepthMask(true); } void CParticleInstance::SetGLProgram( GLuint theProgram ) { m_theProgram = theProgram; } void CParticleInstance::Reset() { m_pEmitter->m_EmiterShape.GeneratePositionAndDirection(m_position, m_moveDir); m_parentMat = m_pEmitter->m_pParticleSystem->m_transform.GetTransformMat() * m_pEmitter->m_transform.GetTransformMat(); if ( m_pEmitter->m_emitMode == CEmitter::EEmitMode_Free ) { m_position = m_parentMat * Vec4(m_position, 1.0f); m_moveDir = m_parentMat * Vec4(m_moveDir, 0.0f); } m_moveDir.Normalize(); m_fElapsedRatio = m_pEmitter->m_fCurDuration / m_pEmitter->m_fTotalDuration; m_fCurSpeed = m_pEmitter->m_fParticleStartSpeed.GetValue(m_fElapsedRatio); m_fCurLifeTime = m_pEmitter->m_fParticleLifeTime.GetValue(m_fElapsedRatio); m_fStartSize = m_pEmitter->m_fParticleStartSize.GetValue(m_fElapsedRatio, 1.0f); m_startVertexColor = m_pEmitter->m_particleStartColor.GetValue(m_fElapsedRatio, Color3B::WHITE); m_fStartVertexAlpha = m_pEmitter->m_fParticleStartAlpha.GetValue(m_fElapsedRatio, 255.0f); m_fCurZRotation = m_pEmitter->m_fParticleStartZRotation.GetValue(m_fElapsedRatio); m_SizeOverLifeTime.RandomPickIndex(); m_colorOverLifeTime.RandomPickIndex(); m_AlphaOverLifeTime.RandomPickIndex(); m_ZRotationOverLifeTime.RandomPickIndex(); } void CParticleInstance::Init( CEmitter* pParent ) { m_pEmitter = pParent; m_SizeOverLifeTime = m_pEmitter->m_sizeOverLifeTime; m_colorOverLifeTime = m_pEmitter->m_colorOverLifeTime; m_AlphaOverLifeTime = m_pEmitter->m_AlphaOverLifeTime; m_ZRotationOverLifeTime = m_pEmitter->m_ZRotationOverLifeTime; m_TexSheetFrameOverLifeTime = m_pEmitter->m_TexSheetFrameOverLifeTime; BuildVBOAndVAO(); SetGLProgram( CGLProgramManager::GetInstance()->CreateProgramByName("Particle") ); InitUniform(); Reset(); } void CParticleInstance::InitUniform() { GLint colorTextureUnif = glGetUniformLocation(m_theProgram, "u_colorTexture"); if ( colorTextureUnif >= 0 ) { glUniform1i(colorTextureUnif, m_colorTexUnit); } } void CParticleInstance::SetVertexColor() { for (auto& rVertex : m_vVertex) { rVertex.m_color = m_VertexColor; } glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glBufferData(GL_ARRAY_BUFFER, m_vVertex.size() * sizeof(SCommonVertex), &m_vVertex.front(), GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } void CEmitterShape::GeneratePositionAndDirection( Vec3& outPos, Vec3& outDir ) { if ( m_eShapeType == EShape_None ) { outPos = Vec3(0, 0, 0); } else if ( m_eShapeType == EShape_Box ) { outPos = Vec3( RANDOM_MINUS1_1(), RANDOM_MINUS1_1(), RANDOM_MINUS1_1() ) * m_extent; } else { if ( m_eEmitFromType == EEmitFrom_Base ) { if ( m_eShapeType == EShape_Cone ) { float fRandomRadius = RANDOM_MINUS1_1() * m_fRadius; float fRandomAngle = RANDOM_0_1() * DEG_TO_RAD(360.0f); outPos = Vec3( cosf(fRandomAngle), sinf(fRandomAngle), 0 ) * fRandomRadius; } } else if ( m_eEmitFromType == EEmitFrom_Base_Shell ) { if ( m_eShapeType == EShape_Cone ) { float fRandomAngle = RANDOM_0_1() * DEG_TO_RAD(360.0f); outPos = Vec3( cosf(fRandomAngle), sinf(fRandomAngle), 0 ) * m_fRadius; } } } outDir = Vec3(0, 0, 1); if ( m_eShapeType == EShape_Cone ) { Mat4 rotateX = Mat4::CreateRotationMat(RANDOM_MINUS1_1() * m_fAngle, 0, 0); Mat4 rotateZ = Mat4::CreateRotationMat(0, 0, RANDOM_MINUS1_1() * m_fAngle); outDir = rotateZ * rotateX * Vec4(outDir, 0.0f); } else { if ( m_bRandomDirection ) { outDir = Vec3(RANDOM_MINUS1_1(), RANDOM_MINUS1_1(), RANDOM_MINUS1_1()); } } outDir.Normalize(); }
true
9726016f382e9540407819093fd22a9020b491c6
C++
Spencer-Yoder/Ring-Bell
/GetTime.cpp
UTF-8
689
3.578125
4
[ "MIT" ]
permissive
#include "Header.h" #include<ctime> //Used for getting time //This Funciton Gets the current time from the computer and //converts it into local time. It saves the time in the class //varables. void RingBell::GetTime() { time_t currentTime; struct tm *localTime; time(&currentTime); // Get the current time localTime = localtime(&currentTime); // Convert the current time to the local time current_hour = localTime->tm_hour; //save the local time current_min = localTime->tm_min; current_sec = localTime->tm_sec; cout << "Chruch got out at: " << current_hour << ":" << current_min << "." << current_sec << endl << endl; //Show the time }
true
c52cd48cc69b99d72f176051c9469815e2de5003
C++
happycoder0011/Competitive-Coding-Contest-Solutions
/SEPTEMBER_long_challenge.cpp/chefina_and_swap.cpp
UTF-8
878
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef unsigned long long int ulli; bool check(int a[],int n,int sum) { int all=0; for(int i=0;i<n;i++) { if(all<sum) all += a[i]; else if(all==sum) return true; else if(all>sum) { return false; } } } int main() { ios::sync_with_stdio(0); cin.tie(0); int t,n; cin>>t; for(int i=0;i<t;i++) { cin>>n; int sum = ((n+1)*n)/2; if(sum%2!=0) { cout<<0; continue; } int num[n]; iota(num,num+n,1); int d=1; for(int k=0;k<n;k++) { for(int m=k+1;m<n-1;m++) { swap(num[k],num[m]); if(check(num,n,sum/2)==1) d++; swap(num[k],num[m]); } } cout<<d<<endl; } return 0;}
true
abdf3ecc1399d09c519616716d76b6bdd2b7b1e1
C++
peshe/SDP20-21
/exercises/2&4/Data Structures/Trees/ArbitraryTrees/Practice_Tasks/Solutions.cpp
UTF-8
4,541
3.203125
3
[ "CC0-1.0" ]
permissive
#include <iostream> #include <vector> #include <queue> struct Node { int fData; std::vector<Node*> fChildren; Node( int data = 0 ) : fData(data) {} }; Node* createTree() { int count = 0; Node* root = new Node( count++ ); root->fChildren.push_back(new Node( count++ )); root->fChildren.push_back(new Node( count++ )); root->fChildren.push_back(new Node( count++ )); root->fChildren[ 0 ]->fChildren.push_back( new Node( count++ ) ); root->fChildren[ 1 ]->fChildren.push_back( new Node( count++ ) ); root->fChildren[ 1 ]->fChildren.push_back( new Node( count++ ) ); root->fChildren[ 2 ]->fChildren.push_back( new Node( count++ ) ); root->fChildren[ 2 ]->fChildren[0]->fChildren.push_back( new Node( count++ ) ); root->fChildren[ 2 ]->fChildren[0]->fChildren.push_back( new Node( count++ ) ); root->fChildren[ 2 ]->fChildren[0]->fChildren.push_back( new Node( count++ ) ); root->fChildren[ 2 ]->fChildren[0]->fChildren.push_back( new Node( count++ ) ); root->fChildren[ 2 ]->fChildren[0]->fChildren.push_back( new Node( count++ ) ); return root; } Node* createNiceTree() { Node* root = new Node; root->fData = 10; root->fChildren.push_back( new Node ( 4 ) ); root->fChildren.push_back( new Node ( 3 ) ); root->fChildren.push_back( new Node ( 3 ) ); root->fChildren[ 0 ]->fChildren.push_back( new Node ( 3 ) ); root->fChildren[ 0 ]->fChildren.push_back( new Node ( 1 ) ); root->fChildren[ 1 ]->fChildren.push_back( new Node ( 2 ) ); root->fChildren[ 1 ]->fChildren.push_back( new Node ( 1 ) ); root->fChildren[ 0 ]->fChildren[ 0 ]->fChildren.push_back( new Node ( 1 ) ); root->fChildren[ 0 ]->fChildren[ 0 ]->fChildren.push_back( new Node ( 1 ) ); root->fChildren[ 0 ]->fChildren[ 0 ]->fChildren.push_back( new Node ( 1 ) ); return root; } void deleteTree( const Node* root ) { for ( const Node* child : root->fChildren ) deleteTree( child ); delete root; } size_t treeHeight( const Node* root ) { size_t maxChildHeight = 0; for ( const Node* child : root->fChildren ) { size_t currChildHeight = treeHeight( child ); if ( currChildHeight > maxChildHeight ) maxChildHeight = currChildHeight; } return 1 + maxChildHeight; } size_t treeBranchingFactor( const Node* root ) { size_t maxChildBranchingFactor = root->fChildren.size(); for ( const Node* child : root->fChildren ) { size_t currChildBranchingFactor = treeBranchingFactor( child ); if ( currChildBranchingFactor > maxChildBranchingFactor ) maxChildBranchingFactor = currChildBranchingFactor; } return maxChildBranchingFactor; } void printLevel( const Node* root, size_t level ) { if ( level == 0 ) { std::cout << root->fData << " "; return; } for ( const Node* child : root->fChildren ) printLevel( child, level - 1 ); } void printTree( const Node* root ) { for ( size_t i = 0; i < treeHeight( root ); i++ ) { printLevel( root, i ); std::cout << "\n"; } } size_t leavesOfTree( const Node* root ) { if ( root->fChildren.empty() ) return 1; size_t leaves = 0; for ( const Node* child : root->fChildren ) leaves += leavesOfTree( child ); return leaves; } bool allNodesEqualSumOfChildren( const Node* root ) { if ( root->fChildren.empty() ) return true; int sumChildrenData = 0; for ( const Node* child : root->fChildren ) sumChildrenData += child->fData; if ( root->fData != sumChildrenData ) return false; for ( const Node* child : root->fChildren ) if ( !allNodesEqualSumOfChildren( child ) ) return false; return true; } bool hasPathToLeafWithSum( const Node* root, int n ) { size_t searchSum = n - root->fData; if ( searchSum == 0 ) return true; if ( searchSum < 0 ) return false; for ( const Node* child : root->fChildren ) if ( hasPathToLeafWithSum( child, searchSum ) ) return true; return false; } int main() { Node* root = createNiceTree(); std::cout << treeHeight( root ) << "\n"; std::cout << treeBranchingFactor( root ) << "\n"; printTree( root ); std::cout << leavesOfTree( root ) << "\n"; std::cout << allNodesEqualSumOfChildren( root ) << "\n"; std::cout << hasPathToLeafWithSum( root, 15 ); deleteTree( root ); return 0; }
true
8abe1b7caf2644fecfb0972938f283539f8d3ffa
C++
datk1912/PokerProject
/1.3.cpp
UTF-8
479
3.109375
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; int count1(int n, int m) { static int s = 1, dem = 0; if (m == n) return 1 + dem; for (int i = m; i <= n; i++) if (s*i < n) { s *= i; count1(n, i); if (s > 1 )s /= i; } else if (s*i == n) { s = 1; dem++; break; } else if (s*i > n) break; } int main() { int n, m; cout << "n: "; cin >> n; cout << "m: "; cin >> m; cout << count1(n, m); }
true
c4b79158ac9cac73944bfbc3b40af18c4f827dce
C++
KarimAmrM/Restaurant-Ds-simulator
/Restaurant/Data Structers/PriorNode.h
UTF-8
634
3.5
4
[]
no_license
#pragma once template<class T> class PriorNode //This class is the same ass node but added a prioirty for the implemnetation of the priority queue { private: T item; double priority; PriorNode<T>* next; public: PriorNode() { next = nullptr; } PriorNode(T newItem) { item = newItem; next = nullptr; } void setItem(T newItem) { item = newItem; } void setNext(PriorNode<T>* nextNodePtr) { next = nextNodePtr; } void setPriority(int p) { priority = p; } T getItem() const { return item; } PriorNode<T>* getNext() const { return next; } double getPriority() { return priority; } };
true
100b08301153d00e3676f71d195c1e2be27f4fda
C++
maxyypoo/cs
/TotalofAll/110C/excp.cpp
UTF-8
1,018
3.1875
3
[]
no_license
#include <iostream> #include <stdexcept> using namespace std; template<class ItemType> class Box { private: ItemType item; public: void setItem(const ItemType& i) { item = i; } ItemType getItem() const { return item; } }; Box<int> findBox(Box<int> boxes[], int size, int target) { int i = 0; bool found = false; while (!found && (i<size)) { if (boxes[i].getItem() > 0) throw logic_error ("Negative number found, SSN number can only be positive"); else if (target==boxes[i].getItem()) found = true; else i++; } if (!found) throw logic_error ("Target not found in any box!"); return boxes[i]; } int main() { Box<int> ssn; Box<int> boxes[4]; boxes[0].setItem(5); boxes[1].setItem(330); boxes[2].setItem(-2); boxes[3].setItem(332); try { ssn = findBox (boxes, 4, 332); } catch (logic_error Logerr) { cout << Logerr.what() << endl; ssn.setItem(0); } throw 2; cout << ssn.getItem() << endl; return 0; }
true
eeb609e4221a78d9d345f614bbdbeec14c690595
C++
mariusjcb/LFA_HOMEWORK_3
/LFA_HOMEWORK_3/Pair.cpp
UTF-8
1,335
3.171875
3
[]
no_license
// // Pair.cpp // LFA_HOMEWORK_3 // // Created by Marius Ilie on 26/05/17. // Copyright © 2017 Marius Ilie. All rights reserved. // #include "Pair.hpp" //MARK: Setters void Pair::setLeg(Pair* pair) { this->leg = pair; } void Pair::setX(char x) { this->x = x; } void Pair::setNod(int z) { this->nod = z; } void Pair::setPushList(string list) { this->pushList = list; } void Pair::setPopList(char list) { this->popList = list; } //MARK: Getters Pair* Pair::getLeg() { return this->leg; } char Pair::getX() { return this->x; } int Pair::getNod() { return this->nod; } string Pair::getPushList() { return this->pushList; } char Pair::getPopList() { return this->popList; } //MARK: - Using Pairs //MARK: Insert new Pair into list with values void insertPairForValues(Pair *&start, int x, char z, char pop, string push) { //Prepare new Pair Pair *t = new Pair; t->setLeg(NULL); t->setX(z); t->setNod(x); t->setPopList(pop); t->setPushList(push); //For Empty list Save as start node and exit if (start == NULL) { start = t; return; } //Else: go to the last node and add new Pair after Pair *q; for (q = start; q->getLeg() != NULL; q = q->getLeg()); //Add new Pair into list q->setLeg(t); }
true
977cbe01854428aa9445592b71a719bc018f1f3f
C++
Shreyas9699/Strings
/ReverseWordsInString.cpp
UTF-8
561
3.296875
3
[]
no_license
//Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots. #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin>>T; while(T--){ string s, it; cin>>s; stringstream ss (s); vector<string> words; while(getline(ss, it, '.')){ words.push_back(it); } for(int i = words.size()-1; i>0;i--){ cout<<words[i]<<"."; } cout<<words[0]<<endl; } return 0; }
true
e18a7502f0b45b0c8e4f9d2e2c10f725a43436d1
C++
dsteinel/TheWurlitzer
/calcFreq.ino
UTF-8
651
2.5625
3
[]
no_license
/*** CONNECT FREQ SOURCE TO PIN 2 ***/ //http://forum.arduino.cc//index.php?topic=64219.30 /*** INTERRUPT SERVICE ROUTINE ***/ void isr(){ unsigned long now = micros(); if (numPulses == 1){ firstPulseTime = now; } else{ lastPulseTime = now; } ++numPulses; } /*** READ FREQ ***/ float readFrequency(unsigned int sampleTime) { numPulses = 0; // prime the system to start a new reading attachInterrupt(0, isr, RISING); // enable the interrupt delay(sampleTime); detachInterrupt(0); return (numPulses < 3) ? 0 : (1000000.0 * (float)(numPulses - 2))/(float)(lastPulseTime - firstPulseTime); }
true
51a8c2dea3d595c3794d6738968a427fc2bb9ae2
C++
lafio/work_space_C
/acm.hdu.edu.cn/1005_number_sequence.cpp
UTF-8
876
2.78125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int fx(int a,int b,int n){ int begin=0,end=1; int r[60]; int flag=0; r[0]=r[1]=r[2]=1; if(n==2||n==1){ return 1; }else{ for(int i=3;i<=n && !flag;i++){ r[i]=(r[i-1]*a+r[i-2]*b)%7; for(int j=2;j<i;j++){ if(r[j]==r[i] && r[j-1]==r[i-1]){ begin=j; end=i; flag=1; break; } } } if(flag)return r[begin+(n-end)%(end-begin)]; else return r[n]; } } int main(){ vector<int> result; int a,b,n; while(1){ cin>>a>>b>>n; if(a==0||b==0||n==0)break; else result.push_back(fx(a,b,n)); } for(int i=0;i<result.size();i++){ cout<<result[i]<<endl; } return 0; }
true
f188e9ab9c788128c0613d1c77662b7f19b32a83
C++
LPD-EPFL/consensusinside
/mpass/src/test/test_queue_pthread_wait.cc
UTF-8
3,508
2.671875
3
[]
no_license
/** * @author Aleksandar Dragojevic aleksandar.dragojevic@epfl.ch * */ #include <stdio.h> #include <pthread.h> #include "../common/constants.h" #include "../common/time.h" #include "../common/inttypes.h" #include "../mpass/queue.h" #include "test_queue_busy_wait.h" struct thread_data { mpass::QueueDefault *server_q; mpass::QueueDefault *client_q; }; static void *thread_fun_server(void *data); static void *thread_fun_client(void *data); static void send_to_server(mpass::CacheLine *item, void *data); static void server_receive(mpass::CacheLine *item, void *data); static void send_to_client(mpass::CacheLine *item, void *data); static void client_receive(mpass::CacheLine *item, void *data); #define TEST_MESSAGE_COUNT 100000 #define END_MESSAGE 0 static pthread_t server_t; static volatile bool start_flag; static struct { pthread_mutex_t server_mutex; pthread_cond_t server_cond; } server_data CACHE_LINE_ALIGNED; static struct { pthread_mutex_t client_mutex; pthread_cond_t client_cond; } client_data CACHE_LINE_ALIGNED; void test_queue_pthread_wait() { thread_data queues; queues.server_q = new(0,0) mpass::QueueDefault(); queues.client_q = new(1,1) mpass::QueueDefault(); pthread_mutex_init(&server_data.server_mutex, NULL); pthread_cond_init(&server_data.server_cond, NULL); pthread_mutex_init(&client_data.client_mutex, NULL); pthread_cond_init(&client_data.client_cond, NULL); start_flag = false; pthread_create(&server_t, NULL, thread_fun_server, &queues); while(!start_flag) { // do nothing } thread_fun_client(&queues); } void *thread_fun_client(void *data) { thread_data *queues = (thread_data *)data; pthread_mutex_lock(&client_data.client_mutex); //Added by Maysam Yabandeh //uint64_t start_time = mpass::get_time_ns(); uint64_t start_time = 0; for(int i = 1;i <= TEST_MESSAGE_COUNT;i++) { queues->server_q->enqueue(send_to_server, (void *)(uintptr_t)i); pthread_mutex_lock(&server_data.server_mutex); pthread_cond_signal(&server_data.server_cond); pthread_mutex_unlock(&server_data.server_mutex); pthread_cond_wait(&client_data.client_cond, &client_data.client_mutex); queues->client_q->dequeue(client_receive, NULL); } //Added by Maysam Yabandeh //uint64_t end_time = mpass::get_time_ns(); uint64_t end_time = 0; queues->server_q->enqueue(send_to_server, (void *)(uintptr_t)0); printf("[pthread_wait] Time to send %u messages and acks is: %" PRIu64 "\n", TEST_MESSAGE_COUNT, end_time - start_time); return NULL; } void send_to_server(mpass::CacheLine *item, void *data) { uint32_t num = (uint32_t)(uintptr_t)(data); uint32_t *dest = (uint32_t *)item; *dest = num; } void client_receive(mpass::CacheLine *item, void *data) { // do nothing } void *thread_fun_server(void *data) { thread_data *queues = (thread_data *)data; pthread_mutex_lock(&server_data.server_mutex); bool end_flag = false; start_flag = true; while(!end_flag) { pthread_cond_wait(&server_data.server_cond, &server_data.server_mutex); queues->server_q->dequeue(server_receive, (void *)&end_flag); queues->client_q->enqueue(send_to_client, NULL); pthread_mutex_lock(&client_data.client_mutex); pthread_cond_signal(&client_data.client_cond); pthread_mutex_unlock(&client_data.client_mutex); } return NULL; } void send_to_client(mpass::CacheLine *item, void *data) { // do nothing } void server_receive(mpass::CacheLine *item, void *data) { uint32_t *src = (uint32_t *)item; if(*src == END_MESSAGE) { bool *end_flag = (bool *)data; *end_flag = true; } }
true
fff3b6e1d37cbae7f4682ee2ed84c452e7cf0bba
C++
viaduct/telim_tmsd
/ptr_comp.h
UTF-8
576
2.953125
3
[]
no_license
#pragma once #include <type_traits> #include <memory> namespace telimtmsd { template <typename T> struct PtrComp final { using is_transparent = std::true_type; struct Adapt final { T const* ptr; Adapt(T const* in) : ptr(in) {} Adapt(std::shared_ptr<T const> const& in) : ptr(in.get()) {} Adapt(std::unique_ptr<T const> const& in) : ptr(in.get()) {} Adapt(std::shared_ptr<T> const& in) : ptr(in.get()) {} Adapt(std::unique_ptr<T> const& in) : ptr(in.get()) {} }; bool operator ()(Adapt first, Adapt second) const { return first.ptr < second.ptr; } }; }
true
b6ff96493041589d9ef88f9ff6aff458a5cc41de
C++
fedix/Algorithms_and_Data_Structures
/List/main.cpp
UTF-8
467
3.109375
3
[]
no_license
#include <iostream> #include "List.h" #include "List.cpp" using namespace std; int main() { List<int> q; cout << "testing as a queue" << endl; q.push_back(1); q.push_back(2); q.push_back(3); q.push_back(4); q.push_back(5); for (auto i = 0; i < q.GetSize(); i++) cout << q[i] << " "; q.pop_front(); cout <<endl << "pop_front: "; for (auto i = 0; i < q.GetSize(); i++) cout << q[i] << " "; return 0; }
true
dc597edccd767648b1bd0c5c846f4ae02e93c415
C++
coronalabs/corona
/platform/windows/Corona.Component.Library/CoronaLabs/WinRT/ImmutableByteBuffer.h
UTF-8
7,047
3.25
3
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-free-unknown" ]
permissive
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: support@coronalabs.com // ////////////////////////////////////////////////////////////////////////////// #pragma once #ifndef CORONALABS_CORONA_API_EXPORT # error This header file cannot be included by an external library. #endif #include <collection.h> namespace CoronaLabs { namespace WinRT { /// <summary>Stores a static collection of bytes which cannot be changed.</summary> /// <remarks> /// <para>You can only create instances of this class via its static From() methods.</para> /// <para> /// You can also access a pre-allocated "empty" version of this buffer via its static <see cref="Empty"/> property. /// </para> /// </remarks> public ref class ImmutableByteBuffer sealed : public Windows::Foundation::Collections::IIterable<byte> { private: /// <summary>Creates a new immutable byte buffer which wraps the given byte collection.</summary> /// <remarks>Constructor made private to force external code to use this class' static From() functions.</remarks> /// <param name="bytes"> /// <para>Read-only byte collection that the new byte buffer will wrap and store a reference to.</para> /// <para>Cannot be null or else an exception will be thrown.</para> /// </param> ImmutableByteBuffer(Windows::Foundation::Collections::IVectorView<byte>^ bytes); public: /// <summary>Fetches a byte from the buffer by its zero based index.</summary> /// <param name="index"> /// <para>Zero based index to the byte in the buffer.</para> /// <para>Will throw an exception if the index is out of bounds. (ie: less than zero or greater than Count.)</para> /// </param> /// <returns>Returns the indexed byte.</returns> byte GetByIndex(int index); /// <summary>Determins if this buffer contains zero bytes.</summary> /// <value> /// <para>True if this byte buffer does not contain any bytes.</para> /// <para>False if this buffer contains at least 1 byte.</para> /// </value> property bool IsEmpty { bool get(); } /// <summary>Determines if this buffer contains at least 1 byte.</summary> /// <value> /// <para>True if this buffer contains at least 1 byte.</para> /// <para>False if this buffer does not contain any bytes.</para> /// </value> property bool IsNotEmpty { bool get(); } /// <summary>Gets the number of bytes stored in this buffer.</summary> /// <value> /// <para>The number of bytes stored in this buffer.</para> /// <para>Zero if this byte buffer is empty.</para> /// </value> property int Count { int get(); } /// <summary>Gets an iterator used to iterate through all of the bytes in the buffer in a foreach loop.</summary> /// <returns>Returns an iterator to be used by a foreach loop.</returns> virtual Windows::Foundation::Collections::IIterator<byte>^ First(); /// <summary> /// <para>Gets a pre-allocated ImmutableByteBuffer instance which contains zero bytes.</para> /// <para>You can use this object to optimize member variable initialization of this type.</para> /// </summary> static property ImmutableByteBuffer^ Empty { ImmutableByteBuffer^ get(); } /// <summary>Creates a new immutable byte buffer containing a copy of the given byte collection.</summary> /// <param name="bytes">Byte collection to be copied to the new immutable byte buffer.</param> /// <returns> /// <para>Returns a new immutable byte buffer containing a copy of the given byte collection.</para> /// <para>Returns null if the given byte collection is null.</para> /// <para>Returns the <see cref="Empty"/> immutable byte buffer instance if the given collection is empty.</para> /// </returns> [Windows::Foundation::Metadata::DefaultOverload] static ImmutableByteBuffer^ From(Windows::Foundation::Collections::IIterable<byte>^ bytes); /// <summary>Creates a new immutable byte buffer containing a copy of the given byte collection.</summary> /// <param name="bytes">Byte collection to be copied to the new immutable byte buffer.</param> /// <returns> /// <para>Returns a new immutable byte buffer containing a copy of the given byte collection.</para> /// <para>Returns null if the given byte collection is null.</para> /// <para>Returns the <see cref="Empty"/> immutable byte buffer instance if the given collection is empty.</para> /// </returns> static ImmutableByteBuffer^ From(Windows::Foundation::Collections::IVector<byte>^ bytes); /// <summary>Creates a new immutable byte buffer containing a copy of the given byte array.</summary> /// <param name="bytes">Byte array to be copied to the new immutable byte buffer.</param> /// <returns> /// <para>Returns a new immutable byte buffer containing a copy of the given byte array.</para> /// <para>Returns null if the given byte array is null.</para> /// <para>Returns the <see cref="Empty"/> immutable byte buffer instance if the given array is empty.</para> /// </returns> static ImmutableByteBuffer^ From(const Platform::Array<byte>^ bytes); internal: /// <summary> /// Creates a new immutable byte buffer containing a copy of the given string's characters, /// excluding the null termination character. /// </summary> /// <param name="stringPointer">Pointer to the string to copy characters from. Can be null.</param> /// <returns> /// <para>Returns a new immutable byte buffer containing a copy of the given string's characters.</para> /// <para>Returns null if the given string is null.</para> /// <para>Returns the <see cref="Empty"/> immutable byte buffer instance if the given string is empty.</para> /// </returns> static ImmutableByteBuffer^ From(const char *stringPointer); /// <summary> /// <para>Creates a new immutable byte buffer containing a copy of the specified string's characters.</para> /// <para>Will copy null characters if they're within the "count" parameter's range.</para> /// </summary> /// <param name="stringPointer">Pointer to the string to copy characters from. Can be null.</param> /// <param name="count"> /// <para>Number of characters to copy from the given string, including null characters.</para> /// <para>Must be greater or equal to zero or else an exception will be thrown.</para> /// </param> /// <returns> /// <para>Returns a new immutable byte buffer containing a copy of the given string's characters.</para> /// <para>Returns null if the given string is null.</para> /// <para>Returns the <see cref="Empty"/> immutable byte buffer instance if the "count" parameter is zero.</para> /// </returns> static ImmutableByteBuffer^ From(const char *stringPointer, int count); private: /// <summary>Read-only container wrapping this class' byte collection.</summary> Windows::Foundation::Collections::IVectorView<byte>^ fBytes; }; } } // namespace CoronaLabs::WinRT
true
725d9a85654f780124440e75009d6634497c534e
C++
avinashw50w/ds_algo
/Dynamic programming/maximum sum subarray.cpp
UTF-8
1,998
3.15625
3
[]
no_license
#include<bits/stdc++.h> #define oo (1<<30) using namespace std; // dp solution // int fun(int a[], int n) { int dp[n + 1] = {}; dp[0] = a[0]; for (int i = 1; i < n; ++i) { dp[i] = max(a[i], a[i] + dp[i - 1]); } return *max_element(dp, dp + n); } /* the concept is : S[i..j] = S[j] - S[i-1] ,where S[i] means sum of all the elements from index position 0 to i. So,in order to maximise ( S[j] - S[i] ) , find the minimum value of S[i] for all S[j] calculated till then. And at the same time keep track of the maximum value obtained so far. */ // But the time complexity of the above programe is O(nlogn) ,lower_bound takes logn time // here is O(n) solution, it also handles the case when all the numbers are -ve pre_sum = 0, maxi = -oo; for (int i = 0; i < n; i++) { pre_sum += A[i]; maxi = max(maxi, pre_sum); if (pre_sum < 0) pre_sum = 0; } cout << maxi; ///////////////////////////////////////////////////////////// // a better one that handles handles the case when all numbers in array are negative. // int maxSubArraySum(vector<int> a) { int max_sum = INT_MIN; int curr_max = INT_MIN; for (int i = 0; i < a.size(); i++) { curr_max = max(a[i], curr_max + a[i]); max_sum = max(max_sum, curr_max); } return max_sum; } //////////////////////////////////////////////////////////////////////// // this one also finds the start and end index of the maximum subarray // int maxSubarraySum(int a[], int& start, int& finish, int n) { finish = -1; start = 0; int sum = 0, max_sum = INT_MIN; for (int i = 0; i < n; ++i) { sum += a[i]; if (sum < 0) { sum = 0; start = i + 1; } if (sum > max_sum) { max_sum = sum; finish = i; } } if (finish != -1) return max_sum; // if all the numbers are negative // max_sum = a[0]; start = finish = 0; for (int i = 1; i < n; ++i) { if (a[i] > max_sum) { max_sum = a[i]; start = finish = i; } } return max_sum; }
true
c225b66f02ba872bd9e65173d4d86d9e346dd487
C++
TPVejercicios/BowPractica_3.0
/ProyectosSDL/HolaSDL/GameState.h
ISO-8859-1
2,599
3.0625
3
[ "MIT" ]
permissive
#pragma once #include <list> #include "Resources.h" #include "checkML.h" using namespace std; using uint = unsigned int; class SDLApplication; class GameObject; class EventHandler; class GameStateMachine; class Background; class Texture; class Arrow; /* GameState manda los updates y renders los diferentes game objects. Tambin elimina los objetos. */ class GameState { protected: bool freeze = false; int currLevel = 0; const int MAX_LEVELS = 6; //Lista de todos los objetos list<GameObject*> gameObjects; //Lista de objetos con eventos list<EventHandler*> eventObjects; //Listas de objetos a borrar list<GameObject*> objectsToErase; //Lista con las flechas list<Arrow*> arrows; //Puntero al gameStateMachine GameStateMachine* gsm = nullptr; //Texture* background = nullptr; //Puntero al background SDLApplication* app = nullptr; //Agrega un gameObject a la lista de gameObjects inline void addGameObject(GameObject* _gm) { gameObjects.push_back(_gm); }; //Agrega un eventObject a la lista de evetObjects inline void addEventObject(EventHandler* _eH) { eventObjects.push_back(_eH); }; public: //Enumerados para la asignacin de texturas #pragma region ENUMERADOS //Estructura para definir cada nivel typedef struct { int butterflyNum; int arrows; int pointsToReach; double frame_ballon; }level; //Array constante para determinar los valores de cada nivel level LEVELS[6] = { //num de mariposas //flechas //Puntos a conseguir //Frame rate de los globos {5, 10, 50, 800}, //nivel 1 {10, 12, 250, 700}, //nivel 2 {12, 15, 550, 600}, //nivel 3 {15, 18, 800, 500}, //nivel 4 {16, 20, 1000, 400}, //nivel 5 {20, 25, 1250, 300} //nivel 6 }; #pragma endregion GameState(GameStateMachine* _gsm, SDLApplication* _app); ~GameState(); //Mtodos virtuales virtual void update(); virtual void render(); virtual void handleEvents(); //Agrega un gameObject a la lista de objetos a borrar void killObject(GameObject* _gm) { objectsToErase.push_back(_gm); }; //Devuelve la app SDLApplication* getApp() { return app; }; //Elimina los objetos de la lista a borrar void deleteObjects(); //Manda a guardar a todos los elementos "guardables" del juego void saveGameObjects(); //devuelve el actual nivel int getCurrLevel() { return currLevel; } //Devuelve el primer objeto en funcin del id GameObject* getObjById(int id_); //Activa la pausa inline void activeFreeze() { freeze = true; }; inline void deactiveFreeze() { freeze = false; }; };
true
5b1a9257d34c20da264694065a17c00eb6097717
C++
jaleng/cs171
/assignment_2/Vertex.h
UTF-8
1,172
3.59375
4
[]
no_license
#ifndef VERTEX_H_ #define VERTEX_H_ #include <Eigen/Dense> /** Hold 3 double coordinates for x,y,z space */ class Vertex { public: double x; double y; double z; explicit Vertex(double _x, double _y, double _z) : x{_x}, y{_y}, z{_z} {}; explicit Vertex(Eigen::MatrixXd m) : x{m(0)}, y{m(1)}, z{m(2)} {}; /** Take a vertex and transformation matrix; * return a transformed vertex. */ static Vertex transform_vertex(Vertex v, Eigen::MatrixXd t) { using Eigen::MatrixXd; MatrixXd vertex_matrix(4, 1); vertex_matrix << v.x, v.y, v.z, 1; MatrixXd temp(4, 1); temp = t * vertex_matrix; double W = temp(3, 0); double x, y, z; x = temp(0, 0) / W; y = temp(1, 0) / W; z = temp(2, 0) / W; return Vertex(x, y, z); } /** Return a Vector3d of the vertex coordinates. **/ Eigen::Vector3d matrix() const { return Eigen::Vector3d(x, y, z); } /** Check if all of the coords are between -1 and 1, inclusive. * "inNDCCube" only applies if vertex is in NDC coords. */ bool inNDCCube() { return x >= -1 && x <= 1 && y >= -1 && y <= 1 && z >= -1 && z <= 1; } }; #endif // VERTEX_H_
true
9793a864ca145792ac8443ffa8fb9e2677cc16cc
C++
dagophil/gameprototype
/sources/Player.cpp
UTF-8
2,830
2.546875
3
[]
no_license
#include "Player.h" #include "Vehicle.h" #include "Map.h" Player::Player(int playerId) : m_playerId(playerId), m_lives(10), m_opponent(0), m_joystick(true) { srand(time(NULL) ); m_vehicle = new Vehicle("car.mesh",400.f,this); //m_vehicle->translate(10*playerId,10*playerId,10*playerId); m_timer = new Ogre::Timer(); try { m_input = new PlayerInput; m_input->init(playerId,this); } catch(...) {} createPlayerCam(); createViewport(); } Vehicle* Player::getVehicle() { return m_vehicle; } void Player::update(const float & timestep) { if(m_joystick) { m_input->capture(); } m_vehicle->update(timestep); TopManager::Instance()->getOverlayManager()->update(); } void Player::disableJoystick() { m_joystick = false; } void Player::createViewport() { Ogre::RenderWindow* window = TopManager::Instance()->getGraphicManager()->getRenderWindow(); m_playerVp = window->addViewport(m_playerCam,1,0,0,1,1); m_playerVp->setOverlaysEnabled(true); m_playerCam->setAspectRatio(Ogre::Real(m_playerVp->getActualWidth()) / Ogre::Real(m_playerVp->getActualHeight())); } void Player::addLive() { m_lives++; } void Player::removeLive() { m_lives--; m_vehicle->PlayCollisionAnimation(); if (m_lives <= 0) { TopManager::Instance()->game_over(false); } //TopManager::Instance()->getOverlayManager()->update(); } int Player::getLives() { return m_lives; } void Player::createPlayerCam() { std::stringstream playerstringstream; playerstringstream << "playerCam" << m_playerId; std::string playerstring; playerstringstream >> playerstring; m_playerCam = TopManager::Instance()->getGraphicManager()->getSceneManager()->createCamera(playerstring); Ogre::SceneNode * camNode = m_vehicle->getSceneNode()->createChildSceneNode(Ogre::Vector3(0,+5,-20)); m_playerCam->setAutoTracking(true,m_vehicle->getSceneNode(),Ogre::Vector3(0,0,0)); m_playerCam->setNearClipDistance(0.1); camNode->attachObject(m_playerCam); } int Player::getX() { return m_vehicle->getSceneNode()->getPosition().x; } int Player::getY() { return m_vehicle->getSceneNode()->getPosition().y; } int Player::getZ() { return m_vehicle->getSceneNode()->getPosition().z; } Ogre::Radian Player::getAngle() { return m_vehicle->getSceneNode()->getOrientation().getPitch(); } int Player::getId() { return m_playerId; } unsigned long Player::getMilliseconds() { return m_timer->getMilliseconds(); } void Player::addOpponent() { m_opponent++; size_t numOpponents = TopManager::Instance()->getMap()->getNumOpponents(); if (m_opponent == numOpponents) { TopManager::Instance()->game_over(true); } } int Player::getOpponent() { return m_opponent; }
true
2c685d5fda953c113ff0ac56adb3f35abc7cea5d
C++
sciplot/sciplot
/sciplot/Utils.hpp
UTF-8
14,748
2.703125
3
[ "MIT" ]
permissive
// sciplot - a modern C++ scientific plotting library powered by gnuplot // https://github.com/sciplot/sciplot // // Licensed under the MIT License <http://opensource.org/licenses/MIT>. // // Copyright (c) 2018-2021 Allan Leal // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once // C++ includes #include <algorithm> #include <cctype> #include <cmath> #include <cstdlib> #include <fstream> #include <sstream> #include <string> #include <type_traits> #include <valarray> // sciplot includes #include <sciplot/Constants.hpp> #include <sciplot/Enums.hpp> #include <sciplot/Palettes.hpp> namespace sciplot { namespace internal { /// Return a string for a given value of a generic type. template <typename T> auto str(const T& val) -> std::string { std::stringstream ss; ss << val; return ss.str(); // Note: This is different than std::to_string(i). For example, it works with custom types. Also, std::to_string(2.0) may produce "2.000000", difficulting string comparison in the tests. } /// Return a string for a given char array inline auto str(const char* word) -> std::string { return word; } /// Return an empty string inline auto str() -> std::string { return {}; } /// Remove from the beginning of the string the given character (by default, space). inline auto trimleft(std::string str, unsigned char character = ' ') -> std::string { str.erase(str.begin(), std::find_if(str.begin(), str.end(), [&](unsigned char ch) { return ch != character; })); return str; } /// Remove from the end of the string the given character (by default, space). inline auto trimright(std::string str, unsigned char character = ' ') -> std::string { str.erase(std::find_if(str.rbegin(), str.rend(), [&](unsigned char ch) { return ch != character; }) .base(), str.end()); return str; } /// Trim the string from both ends inline auto trim(std::string str, unsigned char character = ' ') -> std::string { return trimleft(trimright(str, character), character); } /// Remove extra spaces from a string (e.g., `"abc acb xy s "` becomes `"abc acb xy s "`). inline auto collapseWhitespaces(std::string s) -> std::string { s.erase(std::unique(std::begin(s), std::end(s), [](unsigned char a, unsigned char b) { return std::isspace(a) && std::isspace(b); }), std::end(s)); return s; } /// Trim and collapse all spaces in a string (e.g., `" abc acb xy s "` becomes `"abc acb xy s"`). inline auto removeExtraWhitespaces(std::string s) -> std::string { return trim(collapseWhitespaces(s)); } /// Auxiliary function that returns the size of the vector argument with least size (for a single vector case) template <typename VectorType> auto minsize(const VectorType& v) -> std::size_t { return v.size(); } /// Auxiliary function that returns the size of the vector argument with least size template <typename VectorType, typename... Args> auto minsize(const VectorType& v, const Args&... args) -> std::size_t { return std::min<decltype(v.size())>(v.size(), minsize(args...)); } /// Check if type @p T is `std::string`. template <typename T> constexpr auto isString = std::is_same_v<std::decay_t<T>, std::string>; /// Check if type @p T is `std::string`. template <typename V> constexpr auto isStringVector = isString<decltype(std::declval<V>()[0])>; /// Auxiliary function that returns `" + val + "` if `val` is string, otherwise `val` itself. template <typename T> auto escapeIfNeeded(const T& val) { if constexpr (isString<T>) return "\"" + val + "\""; // Due bug #102 we escape data using double quotes else return std::isfinite(static_cast<double>(val)) ? internal::str(val) : MISSING_INDICATOR; // static_cast to avoid MSVC error C2668: 'fpclassify': ambiguous call to overloaded function } /// Auxiliary function to write many vector arguments into a line of an ostream object template <typename VectorType> auto writeline(std::ostream& out, std::size_t i, const VectorType& v) -> std::ostream& { out << escapeIfNeeded(v[i]) << '\n'; return out; } /// Auxiliary function to write many vector arguments into a line of an ostream object template <typename VectorType, typename... Args> auto writeline(std::ostream& out, std::size_t i, const VectorType& v, const Args&... args) -> std::ostream& { out << escapeIfNeeded(v[i]) << " "; writeline(out, i, args...); return out; } /// Auxiliary function to write many vector arguments into an ostream object template <typename... Args> auto write(std::ostream& out, const Args&... args) -> std::ostream& { const auto size = minsize(args...); for (std::size_t i = 0; i < size; ++i) writeline(out, i, args...); return out; } } // namespace internal namespace gnuplot { /// Return the formatted string for a plot title. inline auto titlestr(std::string word) -> std::string { return word == "columnheader" ? word : "'" + word + "'"; } /// Return the formatted string for a `option` with a leading space (e.g., "enhanced ") /// Note that if option is empty, then an empty string is returned. inline auto optionStr(std::string option) -> std::string { return option.size() ? (option + " ") : ""; } /// Return the formatted string for a `option value` pair with a leading space (e.g., "size 400,300 ", "ls 2 ") /// Note that if value is empty, then the option is not needed and an empty string is returned. inline auto optionValueStr(std::string option, std::string value) -> std::string { return value.size() ? (option + " " + value + " ") : ""; } /// Return the formatted string for a `command value` pair (e.g. "cmd value" or "set ab de") /// Note that if value is empty, then the command is not needed and an empty string is returned. inline auto cmdValueStr(std::string cmd, std::string value) -> std::string { return value.size() ? (cmd + " " + value + "\n") : ""; } /// Return the formatted, escaped string for a `command value` pair (e.g. "cmd 'value'", or "set ab 'de'") /// Note that if value is empty, then the command is not needed and an empty string is returned. inline auto cmdValueEscapedStr(std::string cmd, std::string value) -> std::string { return value.size() ? (cmd + " '" + value + "'\n") : ""; } /// Return the formatted string for a size pair (x,y). inline auto figureSizeStr(double sx, double sy) -> std::string { return internal::str(sx) + "," + internal::str(sy); } /// Return the formatted string for a size pair (x,y) in either as pixels or as inches (asinches == true). inline auto canvasSizeStr(std::size_t width, std::size_t height, bool asinches) -> std::string { return asinches ? (internal::str(width * POINT_TO_INCHES) + "in," + internal::str(height * POINT_TO_INCHES) + "in") : (internal::str(width) + "," + internal::str(height)); } /// Return the correct gnuplot string command for given rgb color (e.g., "#FF00FF") inline auto rgb(std::string color) -> std::string { return "rgb '" + color + "'"; } /// Return the correct gnuplot string command for given rgb color as hex number (e.g., 0xFF00FF) inline auto rgb(int hexcolor) -> std::string { return "rgb " + internal::str(hexcolor); } /// The struct where static angle methods are defined. struct angle { /// Return the angle in degree units. static auto deg(long val) -> std::string { return internal::str(val) + "deg"; } /// Return the angle in radian units. static auto rad(double val) -> std::string { return internal::str(val); } /// Return the angle in radian units as a multiple of number pi. static auto pi(double val) -> std::string { return internal::str(val) + "pi"; } }; /// Auxiliary function to create a data set in an ostream object that is understood by gnuplot template <typename... Args> auto writedataset(std::ostream& out, std::size_t index, const Args&... args) -> std::ostream& { // Save the given vectors x and y in a new data set of the data file out << "#==============================================================================" << std::endl; out << "# DATASET #" << index << std::endl; out << "#==============================================================================" << std::endl; // Write the vector arguments to the ostream object internal::write(out, args...); // Ensure two blank lines are added here so that gnuplot understands a new data set has been added out << "\n\n"; return out; } /// Auxiliary function to write palette data for a selected palette to start of plot script inline auto palettecmd(std::ostream& out, std::string palette) -> std::ostream& { out << "#==============================================================================" << std::endl; out << "# GNUPLOT-palette (" << palette << ")" << std::endl; out << "#------------------------------------------------------------------------------" << std::endl; out << "# see more at https://github.com/Gnuplotting/gnuplot-palettes" << std::endl; out << "#==============================================================================" << std::endl; out << palettes.at(palette) << std::endl; return out; } /// Auxiliary function to unset palette in plot script inline auto unsetpalettecmd(std::ostream& out) -> std::ostream& { out << "do for [i=1:20] { unset style line i }" << std::endl; return out; } /// Auxiliary function to write terminal commands for showing a plot from a script file inline auto showterminalcmd(std::ostream& out, std::string size, std::string font, std::string title) -> std::ostream& { out << "#==============================================================================" << std::endl; out << "# TERMINAL" << std::endl; out << "#==============================================================================" << std::endl; // We set a terminal here to make sure we can also set a size. This is necessary, because the // canvas size can ONLY be set using "set terminal <TERMINAL> size W, H". // See: http://www.bersch.net/gnuplot-doc/canvas-size.html#set-term-size // The GNUTERM variable contains the default terminal, which we're using for the show command. // See: http://www.bersch.net/gnuplot-doc/unset.html out << "set termoption enhanced" << std::endl; if (font.size()) out << "set termoption " << font << std::endl; out << "set terminal GNUTERM size " << size << (!title.empty() ? " title '" + title + "' " : "") << std::endl; out << "set encoding utf8" << std::endl; return out; } /// Auxiliary function to write terminal commands for saving a plot from a script file inline auto saveterminalcmd(std::ostream& out, std::string extension, std::string size, std::string font) -> std::ostream& { out << "#==============================================================================" << std::endl; out << "# TERMINAL" << std::endl; out << "#==============================================================================" << std::endl; out << "set terminal " << extension << " size " << size << " enhanced rounded " << font << std::endl; out << "set encoding utf8" << std::endl; return out; } /// Auxiliary function to set the output command to make GNUplot output plots to a file inline auto outputcmd(std::ostream& out, std::string filename) -> std::ostream& { out << "#==============================================================================" << std::endl; out << "# OUTPUT" << std::endl; out << "#==============================================================================" << std::endl; out << "set output '" << filename << "'" << std::endl; out << "set encoding utf8" << std::endl; return out; } /// Auxiliary function to write multiplot commands to a script file inline auto multiplotcmd(std::ostream& out, std::size_t rows, std::size_t columns, std::string title) -> std::ostream& { out << "#==============================================================================" << std::endl; out << "# MULTIPLOT" << std::endl; out << "#==============================================================================" << std::endl; out << "set multiplot"; if (rows != 0 || columns != 0) { out << " layout " << rows << "," << columns; } out << " " << "rowsfirst"; out << " " << "downwards"; if (!title.empty()) { out << " title '" << title << "'"; } out << std::endl; return out; } /// Auxiliary function to run gnuplot to show or save a script file // persistent == true: for show commands. show the file using GNUplot until the window is closed // persistent == false: for save commands. close gnuplot immediately inline auto runscript(std::string scriptfilename, bool persistent) -> bool { std::string command = persistent ? "gnuplot -persistent " : "gnuplot "; command += "\"" + scriptfilename + "\""; return std::system(command.c_str()) == 0; } /// Auxiliary function to escape a output path so it can be used for GNUplot. /// Removes every character from invalidchars from the path. inline auto cleanpath(std::string path) -> std::string { const std::string invalidchars = ":*?!\"<>|"; std::string result = path; result.erase(std::remove_if(result.begin(), result.end(), [&invalidchars](char c) { return (std::find(invalidchars.cbegin(), invalidchars.cend(), c) != invalidchars.cend()); }), result.end()); return result; } } // namespace gnuplot } // namespace sciplot
true
0812576944f4692ac6b82131138a5a614f636d5c
C++
hys2rang/WHrkTLQKF
/swexpert/swbasic/sum.cpp
UTF-8
1,617
3.59375
4
[]
no_license
/* 다음 100X100의 2차원 배열이 주어질 때, 각 행의 합, 각 열의 합, 각 대각선의 합 중 최댓값을 구하는 프로그램을 작성하여라. 다음과 같은 5X5 배열에서 최댓값은 29이다. [제약 사항] 총 10개의 테스트 케이스가 주어진다. 배열의 크기는 100X100으로 동일하다. 각 행의 합은 integer 범위를 넘어가지 않는다. 동일한 최댓값이 있을 경우, 하나의 값만 출력한다. [입력] 각 테스트 케이스의 첫 줄에는 테스트 케이스 번호가 주어지고 그 다음 줄부터는 2차원 배열의 각 행 값이 주어진다. [출력] #부호와 함께 테스트 케이스의 번호를 출력하고, 공백 문자 후 테스트 케이스의 답을 출력한다. */ #include <iostream> #include <algorithm> #include <string.h> using namespace std; const int MAX = 100; int max(int a, int b, int c, int d, int e); int main() { int arr[MAX][MAX]; for (int TC = 0; TC < 10; TC++) { int n,m=0; int sum_w[100] = { 0, }; int sum_h[100] = { 0, }; int ac1 = 0, ac2 = 0; cin >> n; for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { cin >> arr[i][j]; sum_w[i] += arr[i][j]; sum_h[j] += arr[i][j]; if (i == j) { ac1 += arr[i][j]; } if (i + j == 99) { ac2 += arr[i][j]; } } } for (int i = 0; i < 100; i++) { m = max(sum_w[i], sum_h[i], m, ac1, ac2); } cout << "#" << n<<" " << m << endl; } return 0; } int max(int a, int b, int c, int d, int e) { int M = max(a, b); M = max(M, c); M = max(M, d); M = max(M, e); return M; }
true
96da847f582197f461bb1e4f83c956e4b4471e50
C++
zyxave/baba
/public_html/asset/submission_files/370f6f8014a62a09268dd7a4a1d03c8b.cpp
UTF-8
256
2.671875
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; int n,x,t,hit; int cek(int x) { if(x==1) return hit; hit++; return cek(x/2); } int main () { x=1; cin>>t; for(int i=1;i<=t;i++) { hit=0; cin>>n; if(n==1) hit=1; cek(n); cout<<hit<<endl; } }
true
7881ee8ebd98e4c34739bd70990c84e7f013d31f
C++
201419/Programming-Training
/Leetcode/0431-0440.cpp
UTF-8
1,698
2.828125
3
[]
no_license
// https://leetcode-cn.com/problems/encode-n-ary-tree-to-binary-tree/ // 431. 将 N 叉树编码为二叉树 // --------------------------------------------------------------------------- // https://leetcode-cn.com/problems/all-oone-data-structure/ // 432. 全 O(1) 的数据结构 // --------------------------------------------------------------------------- // https://leetcode-cn.com/problems/minimum-genetic-mutation/ // 433. 最小基因变化 // --------------------------------------------------------------------------- // https://leetcode-cn.com/problems/number-of-segments-in-a-string/ // 434. 字符串中的单词数 // --------------------------------------------------------------------------- // https://leetcode-cn.com/problems/non-overlapping-intervals/ // 435. 无重叠区间 // --------------------------------------------------------------------------- // https://leetcode-cn.com/problems/find-right-interval/ // 436. 寻找右区间 // --------------------------------------------------------------------------- // https://leetcode-cn.com/problems/path-sum-iii/ // 437. 路径总和 III // --------------------------------------------------------------------------- // https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/ // 438. 找到字符串中所有字母异位词 // --------------------------------------------------------------------------- // https://leetcode-cn.com/problems/ternary-expression-parser/ // 439. 三元表达式解析器 // --------------------------------------------------------------------------- // https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order/ // 440. 字典序的第K小数字
true
45f82cc63f0a107cdb59db14199574af2ce6cce2
C++
Vaa3D/vaa3d_tools
/hackathon/PengXie/NeuronStructNavigator/cmake-3.6.2/Tests/CompileFeatures/cxx_contextual_conversions.cpp
UTF-8
635
3.1875
3
[ "MIT", "BSD-3-Clause" ]
permissive
#define assert(E) \ if (!(E)) \ return 1; template <class T> class zero_init { public: zero_init() : val(static_cast<T>(0)) { } zero_init(T val) : val(val) { } operator T&() { return val; } operator T() const { return val; } private: T val; }; int someFunc() { zero_init<int*> p; assert(p == 0); p = new int(7); assert(*p == 7); delete p; zero_init<int> i; assert(i == 0); i = 7; assert(i == 7); switch (i) { } int* vp = new int[i]; return 0; }
true
2495dba0f132c1177ecb8160549e572faeb1c6d8
C++
lcccc/nfcjcodes
/85-8.cpp
UTF-8
930
2.6875
3
[]
no_license
/* * Author: Nfcj * Created Time: 2011年08月05日 星期五 21时25分33秒 * File Name: 85-8.cpp */ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <vector> using namespace std; #define SZ(v) ((int)(v).size()) int tot,n,pm[50000]; bool ispm(int x) { for(int i = 2;i <= (int)sqrt(x);i++) if( x % i ==0) return false; return true; } void init(){ tot = 0; for(int i=2;i<=30000;i++) if(ispm(i)) pm[tot++] = i; } int maxfac(int x) { if( x == 1) return 1; int maxf = 0; for(int i = 0 ;i < tot;i++) { if( pm[i] > x) break; if(x % pm[i] == 0) maxf = pm[i]; } return maxf; } int main() { init(); cin>>n; int fac=0,k,a; for(int i = 0; i < n;i++) { cin>>a; if( maxfac(a) > fac ){ fac = maxfac(a);k = a;} } cout<<k<<endl; return 0; }
true
f12fd625ffea11240c8f805b824ee7a6fa658e63
C++
Neema-Rawat/8june_IoT
/Motor_Timer.ino
UTF-8
1,723
2.9375
3
[]
no_license
#include<LiquidCrystal.h> LiquidCrystal lcd(A0, A1, A2, A3, A4, A5); const byte ctrl_key = 3; const byte m_pins[2] = {12, 13}; void setup() { lcd.begin(16, 2); pinMode(ctrl_key, INPUT_PULLUP); for (int i = 0 ; i < 2; i++) pinMode(m_pins[i], OUTPUT); } bool gate_state = false; int counter = 0; // 0 - CLose, 1 - Open long start_time = 0; long timeStep = 500; // 1000 for 1sec gap void loop() { if (!digitalRead(ctrl_key)) { while (!digitalRead(ctrl_key)); gate_state ^= 1; start_time = millis(); } lcd.setCursor(1, 0); lcd.print(counter); lcd.print(" "); if (gate_state == 0) { // to close or Closed if (counter == 0) { // Closed lcd.setCursor(0, 1); lcd.print("GATE CLOSED "); gate_none(); } else { // closing lcd.setCursor(0, 1); lcd.print("GATE CLOSING"); if (millis() - start_time >= timeStep) { start_time = millis(); if (counter > 0) { counter--; } gate_off(); } } } else { // to open or Opened if (counter == 10) { // opened lcd.setCursor(0, 1); lcd.print("GATE OPENED "); gate_none(); } else { // opening lcd.setCursor(0, 1); lcd.print("GATE OPENING"); if (millis() - start_time >= timeStep) { start_time = millis(); if (counter < 10) { counter++; } gate_on(); } } } } void gate_on() { digitalWrite(m_pins[0], 1); digitalWrite(m_pins[1], 0); } void gate_off() { digitalWrite(m_pins[0], 0); digitalWrite(m_pins[1], 1); } void gate_none() { digitalWrite(m_pins[0], 0); digitalWrite(m_pins[1], 0); }
true
bfad280af5fde9ff0b60ebbaee530dfd54a47a8c
C++
fabiohenriquez/Archivo_Lab5_FabioHenriquez
/ingredientes.h
UTF-8
625
2.8125
3
[]
no_license
#ifndef INGREDIENTES_H #define INGREDIENTES_H #include<string> using std::string; class ingredientes{ private: string tipo; string ingrediente; int cantidad; double duracion; public: ingredientes();//ctor por defecto ingredientes(string,string,int,double); string getIngrediente();//instanciar matrices void setIngrediente(string i);//liberar memoria string getTipo();//instanciar matrices void setTipo(string t);//liberar memoria int getCantidad(); void setCantidad(int d); int getDuracion(); void setDuracion(int d); ~ingredientes();//destructor }; #endif
true
eaac95e02a6f6e9b319f5892951818bce15d44e5
C++
huaxiufeng/leetcode
/src/algorithm/cpp/reverse-linked-list/main.cpp
UTF-8
2,585
4.03125
4
[]
no_license
/* Reverse a singly linked list. click to show more hints. Hint: A linked list can be reversed either iteratively or recursively. Could you implement both? */ #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; template <typename T> void display(vector<T> array) { for (int i = 0; i < array.size(); i++) { cout<<array[i]<<" "; } cout<<endl; } struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; void AddList(ListNode* &head, int value) { if (!head) { head = new ListNode(value); } else { ListNode* p = head; while (p->next) { p = p->next; } ListNode* tail = new ListNode(value); p->next = tail; } } void DisplayList(ListNode* head) { ListNode* p = head; while (p) { cout<<p->val<<" "; p = p->next; } cout<<endl; } class Solution { public: /* ListNode* reverseList(ListNode* head) { ListNode *rhead = 0, *rtail = 0; ListNode *p = head; while (p) { ListNode *cur = p; p = p->next; if (!rtail) { rtail = cur; rhead = cur; rtail->next = 0; } else { cur->next = rhead; rhead = cur; } } return rhead; } */ /* ListNode* reverseList(ListNode* head) { if (!head) { return 0; } if (head->next == 0) { return head; } ListNode* cur = head; ListNode* rrest = reverseList(head->next); ListNode *p = rrest; while (p->next) { p = p->next; } p->next = cur; cur->next = 0; return rrest; } */ ListNode* reverseList(ListNode* head) { if (!head) { return 0; } if (head->next == 0) { return head; } ListNode *p = head; while (p->next->next) { p = p->next; } ListNode* cur = p->next; p->next = 0; cur->next = reverseList(head); return cur; } }; int main() { ListNode* head = 0; AddList(head, 1); AddList(head, 1); AddList(head, 2); AddList(head, 3); AddList(head, 3); AddList(head, 4); AddList(head, 4); AddList(head, 5); AddList(head, 5); DisplayList(head); Solution s; head = s.reverseList(head); DisplayList(head); return 0; }
true
70dcc43e9b415294a83492399bd52a94b8ffe32b
C++
RenMitsumata/Shu-Pre-Project
/Shader2D.cpp
SHIFT_JIS
5,208
2.515625
3
[]
no_license
#include "Manager.h" #include "DXManager.h" #include "Component.h" #include "Texture.h" #include "Shader2D.h" #include "window.h" #include <Windows.h> #include <stdio.h> #include <io.h> Shader2D::Shader2D() { } Shader2D::~Shader2D() { } void Shader2D::Init(const char * VS_Filename, const char * PS_Filename) { // ɕKvȃfoCX擾 device = Manager::Get()->GetDXManager()->GetDevice(); context = Manager::Get()->GetDXManager()->GetDeviceContext(); if (device == nullptr || context == nullptr) { MessageBox(NULL, "DirectXDevice̎擾Ɏs܂", "VF[_s", MB_ICONHAND); exit(-1); } // _VF[_ { FILE* file; long int fsize; file = fopen(VS_Filename, "rb"); fsize = _filelength(_fileno(file)); unsigned char* buffer = new unsigned char[fsize]; fread(buffer, fsize, 1, file); fclose(file); device->CreateVertexShader(buffer, fsize, NULL, &vertexShader); // ̓CAEg D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 4 * 2, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; UINT numElements = ARRAYSIZE(layout); device->CreateInputLayout(layout, numElements, buffer, fsize, &vertexLayout); delete[] buffer; } // sNZVF[_ { FILE* file; long int fsize; file = fopen(PS_Filename, "rb"); fsize = _filelength(_fileno(file)); unsigned char* buffer = new unsigned char[fsize]; fread(buffer, fsize, 1, file); fclose(file); device->CreatePixelShader(buffer, fsize, NULL, &pixelShader); delete[] buffer; } // 萔obt@ D3D11_BUFFER_DESC hBufferDesc; hBufferDesc.ByteWidth = sizeof(CONSTANT_UI); hBufferDesc.Usage = D3D11_USAGE_DEFAULT; hBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; hBufferDesc.CPUAccessFlags = 0; hBufferDesc.MiscFlags = 0; hBufferDesc.StructureByteStride = sizeof(float); device->CreateBuffer(&hBufferDesc, NULL, &constantBuffer); context->VSSetConstantBuffers(0, 1, &constantBuffer); hBufferDesc.ByteWidth = sizeof(XMFLOAT4); device->CreateBuffer(&hBufferDesc, NULL, &colorBuffer); context->UpdateSubresource(colorBuffer, 0, NULL, &color, 0, 0); context->PSSetConstantBuffers(0, 1, &colorBuffer); // vWFNVs񏉊 constantValue.projMat = XMMatrixOrthographicOffCenterLH(0.0f, WINDOW_WIDTH, WINDOW_HEIGHT, 0.0f, 0.0f, 1.0f); constantValue.projMat = XMMatrixTranspose(constantValue.projMat); context->UpdateSubresource(constantBuffer, 0, NULL, &constantValue, 0, 0); // ̓CAEgݒ context->IASetInputLayout(vertexLayout); // VF[_ݒ context->VSSetShader(vertexShader, NULL, 0); context->PSSetShader(pixelShader, NULL, 0); // Tv[Xe[gݒ D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); samplerDesc.Filter = D3D11_FILTER_ANISOTROPIC; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0; samplerDesc.MaxAnisotropy = 16; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; device->CreateSamplerState(&samplerDesc, &samplerState); context->PSSetSamplers(0, 1, &samplerState); } void Shader2D::Uninit() { if (constantBuffer) { constantBuffer->Release(); } if (vertexLayout) { vertexLayout->Release(); } if (pixelShader) { pixelShader->Release(); } if (vertexShader) { vertexShader->Release(); } } void Shader2D::Set() { if (device == nullptr || context == nullptr) { MessageBox(NULL, "VF[_Ă܂", "foCX擾s", MB_ICONHAND); exit(-1); } // VF[_ݒ context->VSSetShader(vertexShader, NULL, 0); context->PSSetShader(pixelShader, NULL, 0); // ̓CAEgݒ context->IASetInputLayout(vertexLayout); // vWFNVs񏉊iEBhEςAォςȂݒj context->UpdateSubresource(constantBuffer, 0, NULL, &constantValue, 0, 0); context->PSSetConstantBuffers(0, 1, &colorBuffer); // 萔obt@ݒ(萔obt@̌`قȂꍇAς) context->VSSetConstantBuffers(0, 1, &constantBuffer); } void Shader2D::SetTexture(Texture* texture) { ID3D11ShaderResourceView* srv[1] = { texture->GetShaderResourceView() }; context->PSSetShaderResources(0, 1, srv); } void Shader2D::SetTexture(ID3D11ShaderResourceView * srv) { ID3D11ShaderResourceView* defSrv[1] = { srv }; context->PSSetShaderResources(0, 1, defSrv); } void Shader2D::SetProjMatrix(XMMATRIX mat) { constantValue.projMat = XMMatrixTranspose(mat); } void Shader2D::SetDepth(float depth) { constantValue.depth = depth; } void Shader2D::ChangeColor() { time++; color = XMFLOAT4(sinf(XMConvertToRadians(time)), cosf(XMConvertToRadians(time)), sinf(XMConvertToRadians(time + 180)), 1.0f); context->UpdateSubresource(colorBuffer, 0, NULL, &color, 0, 0); }
true
7cafbabb56a0cf2a27d2d4a8ce13d94fcb7407c1
C++
AvneetSandhu/Data-Structures-Program
/stack.cpp
UTF-8
1,331
3.921875
4
[]
no_license
#include<iostream> #include<conio.h> #include<stdio.h> using namespace std; class stack { int top; int Stack[500]; public: void push(); void pop(); void display(); stack() { top=-1; } }; void stack::push() { int item; if(top>500) { cout<<"stack is full"<<endl; } else { top=top+1; Stack[top]=item; } } void stack::pop() { int item; if(top==-1) { cout<< "stack is empty"<<endl; } else { item=Stack[top]; top=top-1; } } void stack::display() { for(int i=top;i>=0;i--) { cout<< Stack[i]; } } int main() { stack s; int choice; while(1) { cout<< "1.Push"<<endl; cout<< "2.Pop"<<endl; cout<< "3.display"<<endl; cout<<"enter your choice"<<endl; cin>>choice; switch(choice) { case 1: cout<< "enter the element"<<endl; cin>>choice; s.push(); break; case 2:s.pop(); break; case 3: s.display(); break; case 4:default: cout<< "wrong choice"<<endl; } } return(0); }
true
5509bae7d2e29b6088ad0b8aebd3ab903a9f97a4
C++
sanus912/community-detection
/ori_MEMB.cpp
UTF-8
13,772
2.515625
3
[]
no_license
////////read .txt; omit the first 6 lines; from 0 to N-1;/////////////// #include <vector> #include <iostream> #include <fstream> #include <cstdlib> #include <string> #include <sstream> #include <iomanip> #include <ctime> using namespace std; const int MAX=12501; const int MAXR=10; const int MINR=1; int N=0; int L=0;//num of links float s,e; struct network { int b;//unburnt--->0; burnt--->1 vector<int> neighbor; int geodis[MAX]; int excmas; // calculate "excluded mass" of each node --- once int cendis; // "central distance" int boxid; // uncovered=-1;covered=0; centernode=1,2,3... }; network node[MAX]; int readnet(network *);//return num of links void printnet(network *, int); int excmas(network *, int); // return node with max excluded mass bool complete(network *); // determine whether all nodes are covered int MEMB(network *, int); // return Nb float boxcr(network *,int);//return lB* --- averaged real lB float module(network *,int);//calculate Modularity float moduleN(network *,int);//calculate Modularity_Newman's defination void khub(network *, int); float aveout(network * node, int Nb); void burning(network *);//calculate node[i].geodis[j]; return averaged path int main() { srand(time(NULL)); ofstream outFile; outFile.open("MEMB.txt"); outFile << "#lb" << "\t" << "lb*" << "\t" << "M" << "\t" << "M_Newman" << "\t" << "Nb" << "\t" << "s" << "\t" << "e" << "\t" << "Lout" <<endl; //ofstream pajek; //char Filename[40]; L = readnet(node); // N=# of nodes burning(node); cout << "burning Done!" << endl; int Nb; float lb; float Mb; float Mb_Newman; float Lout; for (int Rb=MINR; Rb<=MAXR; Rb++) { Nb=MEMB(node,Rb); lb=boxcr(node,Nb);// lB* Mb=module(node,Nb);// Modularity Mb_Newman=moduleN(node,Nb);// Modularity //outFile << 2*Rb+1 << "\t" << lb << "\t" << Mb << "\t" << Nb << endl; khub(node,Nb); Lout=aveout(node,Nb); //cout << "s= " << s << endl; //cout << "e= " << e << endl; outFile << 2*Rb+1 << "\t" << lb << "\t"<< Mb <<"\t" << Mb_Newman << "\t" << Nb << "\t" << s << "\t" << e << "\t" << Lout << endl; } outFile.close(); return 0; } void khub(network *, int Nb) { ofstream koutput; koutput.open("khub.txt"); koutput << "#khub" << "\t" << "k" << "\t" << "hub_id" << "\t" << "nh"<< endl; int k[Nb]; int khub[Nb]; int hub_id[Nb]; int n_hub[Nb]; for (int i=0;i<Nb;i++) { k[i]=0; khub[i]=0; n_hub[i]=0; } for (int i=0;i<N;i++) for (int j=i+1;j<N;j++) if ((node[i].geodis[j]==1)&&(node[i].boxid!=node[j].boxid)) { k[node[i].boxid-1]++; k[node[j].boxid-1]++; } for (int i=0;i<N;i++) if (khub[node[i].boxid-1]<int(node[i].neighbor.size())) { khub[node[i].boxid-1]=node[i].neighbor.size(); hub_id[node[i].boxid-1]=i; } for (int i=0; i<Nb; i++) for (int j=i+1; j<Nb; j++) if ((node[hub_id[i]].geodis[hub_id[j]]==1)) { n_hub[i]++; n_hub[j]++; } for (int i=0;i<Nb;i++) koutput << khub[i] << "\t" << k[i] << "\t" << hub_id[i] << "\t" << n_hub[i] << endl; koutput.close(); s=0.0; e=0.0; for (int i=0;i<Nb;i++){ s+= k[i]/float(khub[i]); e+= n_hub[i]/float(k[i]); } s/=Nb; e/=Nb; //cout << "s= " << s << endl; //cout << "e= " << e << endl; } //---calculate Modularity float moduleN(network * node, int Nb) { int sumd[Nb]; float in[Nb]; for (int i=0;i<Nb;i++) { sumd[i]=0; in[i]=0; } for (int i=0;i<N;i++) for (int j=i+1;j<N;j++) if (node[i].geodis[j]==1) if (node[i].boxid==node[j].boxid) in[node[i].boxid-1]++; for (int i=0; i<N; i++) sumd[node[i].boxid-1] += node[i].neighbor.size(); float m=0; for (int i=0;i<Nb;i++) m += in[i]/L-sumd[i]*sumd[i]/4/L/L; m=m/Nb; cout << m << endl; return m; } // burning ---> calculate node[i].geodis[j] void burning(network * node) { int i,t,c,g,h; //int ldis=0;//-------Longest geodistance unsigned int j,e,f,d; vector<int> active; vector<int> active0; bool flag; for (i=0;i<N;i++) { active.clear(); active0.clear(); for (c=0;c<N;c++) { node[c].b=0;//mark all nodes as unburnt } active.push_back(i); node[i].b=1; g=0; while (active.size()) { g++; if (g>2*MAXR) break; active0=active; active.clear(); for (j=0;j<active0.size();j++) { t=active0[j]; for (d=0;d<node[t].neighbor.size();d++) { h=node[t].neighbor[d]; if (!node[h].b) { flag=true; for (e=0;e<active.size();e++) if (active[e]==h) { flag=false; break; } if(flag) active.push_back(h); } } } for (f=0;f<active.size();f++) { node[active[f]].b=1; node[i].geodis[active[f]]=g; } } //g--; //if (g>ldis) ldis = g; } /* int sum_dis=0; for (int i=0;i<N;i++) for (int j=i+1;j<N;j++) sum_dis+= node[i].geodis[j]; float L=float(sum_dis)/(N*(N-1)/2); return L; */ } //---calculate Modularity float aveout(network * node, int Nb) { float out[Nb]; for (int i=0;i<Nb;i++) { out[i]=0; } for (int i=0;i<N;i++) for (int j=i+1;j<N;j++) if (node[i].geodis[j]==1) if (node[i].boxid!=node[j].boxid) { out[node[i].boxid-1]++; out[node[j].boxid-1]++; } float ave_out=0.0; for (int i=0;i<Nb;i++) ave_out+=out[i]; ave_out/=Nb; return ave_out; } //---calculate Modularity float module(network * node, int Nb) { float out[Nb]; float in[Nb]; for (int i=0;i<Nb;i++) { out[i]=0; in[i]=0; } for (int i=0;i<N;i++) for (int j=i+1;j<N;j++) if (node[i].geodis[j]==1) if (node[i].boxid==node[j].boxid) in[node[i].boxid-1]++; else { out[node[i].boxid-1]++; out[node[j].boxid-1]++; } /*float ave_out=0.0; for (int i=0;i<Nb;i++) ave_out+=out[i]; ave_out/=Nb; cout << "ave_out= " << ave_out << endl; */ float m=0; for (int i=0;i<Nb;i++) m=m+in[i]/out[i]; m=m/Nb; cout << m << endl; return m; } //---box correction float boxcr(network * node, int Nb) { int lb[Nb]; for (int t=0;t<Nb;t++) { int box[N]; int mass=0; for (int u=0;u<N;u++) if (node[u].boxid==(t+1)) { box[mass]=u; mass++; } //for (int i=0;i<mass;i++) // cout << box[i]; //cout << endl; lb[t]=0; for (int i=0;i<mass;i++) for (int j=i+1;j<mass;j++) if (node[box[i]].geodis[box[j]]>lb[t]) lb[t]=node[box[i]].geodis[box[j]]; } //for (int i=0;i<Nb;i++) // cout << lb[i] << endl; float lB=0; for (int i=0;i<Nb;i++) lB=lB+lb[i]; lB=lB/Nb+1; //cout << lB << endl; return lB; } int MEMB(network * node, int Rb) { for (int i=0;i<N;i++) { node[i].boxid = -1; // mark all nodes as uncovered and noncenters node[i].excmas = 0; node[i].cendis = 0; } //---calculation of the box centers int Nb=1; int p; while (!complete(node)) { p=excmas(node,Rb); //cout << "center_id= " << p << endl; node[p].boxid=Nb; for (int j=0;j<N;j++) if ((node[p].geodis[j]<=Rb)&&(node[p].geodis[j]>0)&&(node[j].boxid<0)) node[j].boxid=0; Nb++; //cout << "." << endl; } Nb=Nb-1; //cout << "Nb= " << Nb << endl; ofstream boxcenter; boxcenter.open("boxcenter.txt"); for (int i=0;i<N;i++) if (node[i].boxid>0) boxcenter << i << "\t" << node[i].boxid << endl; boxcenter.close(); //---calculation of the box centers---END //---assign each node to its nearest center int mini; for (int i=0;i<N;i++) if (node[i].boxid==0) { mini=Rb; for (int j=0;j<N;j++) if ((node[i].geodis[j]<mini)&&(node[i].geodis[j]>0)&&(node[j].boxid>0)) mini=node[i].geodis[j]; node[i].cendis=mini; } /* for (int i=3;i<=3;i++) cout << i << "'s cendis is " << node[i].cendis << endl; */ for (int t=1;t<=Rb;t++) for (int i=0;i<N;i++) if ((node[i].boxid==0)&&(node[i].cendis==t)) { int s=node[i].neighbor.size(); int u[s]; int e=0; for (int j=0;j<s;j++) { int w=node[i].neighbor[j]; if ((node[w].cendis<node[i].cendis)&&(node[w].boxid>0)) { u[e]=node[w].boxid; e++; } } if (e==0) cout << "e=0"<< endl; else { int z=rand()%e; node[i].boxid=u[z]; } //if (i==3) cout << "e= " << e << endl; } ofstream outFile; outFile.open("boxid.txt"); for (int i=0;i<N;i++) outFile << i << "\t" << node[i].boxid << endl; outFile.close(); //---assign each node to its nearest center---END //printnet(newnode, Nb); return Nb; } // --- determine whether all nodes are covered bool complete(network * node) { bool flag=true; for (int i=0;i<N;i++) if (node[i].boxid<0) flag=false; //cout << "complete check done! " << endl; return flag; } // --- calculate "excluded mass" int excmas(network * node, int Rb) { for (int i=0;i<N;i++){ if (node[i].boxid==-1) node[i].excmas = 1; else node[i].excmas = 0; } for (int i=0;i<N;i++) for (int j=0;j<N;j++) if ((node[i].geodis[j]<=Rb)&&(node[i].geodis[j]>0)&&(node[j].boxid==-1)) node[i].excmas++; /* for (int i=0;i<N;i++) cout << i << "'s excmas = " << node[i].excmas << endl; */ int mem=0; int mem_id=0; for (int i=0;i<N;i++) if ((node[i].excmas>mem)&&(node[i].boxid<=0)) { mem=node[i].excmas; mem_id=i; } //cout << mem_id << endl; return mem_id; } // --- read network & get N int readnet(network * node) { //char Filename[] = "network.txt"; char Filename[40]; ifstream inFile; cout << "Please enter name of data file: "; cin.getline(Filename, 40); inFile.open(Filename); if (!inFile.is_open()) { cout << "Could not open the file!" << Filename << endl; exit(EXIT_FAILURE); } for (int i=0;i<MAX;i++) { node[i].b = 0;// mark all nodes as unburnt --->0 node[i].boxid = -1; // mark all nodes as uncovered and noncenters node[i].excmas = 0; node[i].cendis = 0; for (int j=0;j<MAX;j++) { node[i].geodis[j]=0; } } string s; istringstream iss; for (int i=0; i<0; i++)//---! getline(inFile,s); while (getline(inFile,s)) { int i,j; iss.str(s); iss>>i>>j; //i--;//when read .net file //j--; //cout << i << "\t<-----> \t" << j << endl; node[i].neighbor.push_back(j); node[j].neighbor.push_back(i); iss.clear(); } inFile.close(); for (int i=0;i<MAX;i++) if (node[i].neighbor.size()) N++; cout << "# of nodes: " << N << endl; int sum_k=0; for (int i=0;i<N;i++) sum_k+=node[i].neighbor.size(); sum_k/=2; cout << "# of links : " << sum_k << endl; return sum_k; } // --- print out network void printnet(network * node) { for (int i=0;i<N;i++) { cout << "Node " << setw(2) << i << " has " << (int)node[i].neighbor.size(); cout << " edges:"; for (unsigned int j=0;j<node[i].neighbor.size();j++) cout << setw(3) << node[i].neighbor[j] << " "; cout << endl; } }
true
6af725d7f7d59d7d191a3eadd648ba85d6d2edbb
C++
Conception-Electronique-Prive/Bootloader_L452_CAN
/Core/Inc/utils.hpp
UTF-8
448
3.09375
3
[]
no_license
#pragma once #include <array> #include <cstdint> template<typename T> void toType(const std::array<uint8_t, 8>& data, T& var) { uint8_t* ptr = (uint8_t*)&var; for (size_t i = 0; i < sizeof(T); ++i, ++ptr) { *ptr = data[i]; } } template<typename T> void toArray(std::array<uint8_t, 8>& data, const T& var) { uint8_t* ptr = (uint8_t*)&var; for (size_t i = 0; i < sizeof(T); ++i, ++ptr) { data[i] = *ptr; } }
true
592e9c296fa2c28ba62c445a338cb3d402f7403a
C++
Aditya2150/SDE-Questions
/Day 7 (2 Pointers)/3sum.cpp
UTF-8
1,108
3.0625
3
[]
no_license
// Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] // such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. // Notice that the solution set must not contain duplicate triplets. class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>>v; sort(nums.begin(),nums.end()); int n=nums.size(); for(int i=0;i<n-2;i++) { if(i>0 && nums[i]==nums[i-1]) continue; int low=i+1,high=n-1; while(low<high) { if(nums[i]+nums[low]+nums[high]==0) { v.push_back(vector<int>{nums[i],nums[low],nums[high]}); while(low<n-1 && nums[low]==nums[low+1])low++; while(high>0 && nums[high]==nums[high-1])high--; low++,high--; } else if(nums[low]+nums[high]+nums[i]>0) high--; else low++; } } return v; } };
true
065b4d365f97140a0227bb75669d45f1f6c6d86a
C++
nosuggest/sladeRode3
/Chapter07/Teacher.cpp
UTF-8
2,027
3.453125
3
[]
no_license
// // Created by 沙韬伟 on 2019-09-24. // #include "Teacher.h" const string &Teacher::getName() const { return name; } void Teacher::setName(const string &name) { Teacher::name = name; } int Teacher::getAge() const { return age; } void Teacher::setAge(int age) { Teacher::age = age; } float *Teacher::getScores() const { return scores; } void Teacher::setScores(float *scores) { Teacher::scores = scores; } void Teacher::initScores() { this->scores = new float[1]; this->scoreCount = 1; } void Teacher::addScore(float score) { this->scores[this->scoreCount - 1] = score; // 创建一个新数组,分配scoreCount+1个空间 float *newScores = new float[scoreCount + 1]; float *oldScores = scores; // 复制原数组到新数组中 memcpy(newScores, scores, sizeof(float) * scoreCount); // 更新分配scoreCount scoreCount++; // scores指向新数组 scores = newScores; delete oldScores; } void Teacher::showInfo() { cout << getName() << "\t" << getAge() << endl; for (int i = 0; i < scoreCount - 1; ++i) { cout << this->scores[i] << "\t"; } cout << endl; } Teacher::Teacher() { initScores(); } Teacher::Teacher(const string &name, int age, float *scores, int scoreCount) : name(name), age(age), scores(scores), scoreCount(scoreCount) { initScores(); } Teacher::~Teacher() { cout << "release" << endl; delete this->scores; } Teacher::Teacher(const string &name, int age) : name(name), age(age) { initScores(); } float Teacher::getTotal() { float tmp = 0; for (int i = 0; i < scoreCount - 1; ++i) { tmp += scores[i]; } return tmp; } // 返回一个score更高的teacher对象 Teacher &Teacher::superSchooler(Teacher &teacher) { if (teacher.getTotal() > this->getTotal()) { return teacher;//返回对象引用 } else { return *this;//返回对象引用 } }
true
a55cd1554f011eb44a261ce6bf43dd476df2b35e
C++
Albert-learner/Lectopia
/HW17.cpp
UHC
828
3.109375
3
[]
no_license
/*ۼ : HW17*/ #include <stdio.h> #include <string.h> void myflush(); int main() { char eng_name[20]; double hei; char gen; char gend[8]; int i, len; for (i = 0; i < 2; i++) { printf("(࿹%d)\n", i+1); printf("# Է : "); fgets(eng_name, 20, stdin); printf("# Ű Է(cm ) : "); scanf("%lf", &hei); printf("# Է(M/F) : "); scanf(" %c", &gen); if (gen == 'M' || gen=='m') { strcpy(gend, ""); } else if(gen == 'W' || gen=='w') { strcpy(gend, ""); } len = strlen(eng_name); eng_name[len - 1] = '\0'; printf("%s Ű %0.2lfcm̰ %sԴϴ.\n", eng_name, hei, gend); printf("\n\n"); myflush(); } return 0; } void myflush() { while (getchar() != '\n') ; }
true
eeb2fb353d8e0cc563999fb7bdb2f802ab00e447
C++
niuxu18/logTracker-old
/second/download/rsync/gumtree/rsync_repos_function_259_rsync-2.6.8.cpp
UTF-8
922
2.671875
3
[]
no_license
unsigned int clean_fname(char *name, BOOL collapse_dot_dot) { char *limit = name - 1, *t = name, *f = name; int anchored; if (!name) return 0; if ((anchored = *f == '/') != 0) *t++ = *f++; while (*f) { /* discard extra slashes */ if (*f == '/') { f++; continue; } if (*f == '.') { /* discard "." dirs (but NOT a trailing '.'!) */ if (f[1] == '/') { f += 2; continue; } /* collapse ".." dirs */ if (collapse_dot_dot && f[1] == '.' && (f[2] == '/' || !f[2])) { char *s = t - 1; if (s == name && anchored) { f += 2; continue; } while (s > limit && *--s != '/') {} if (s != t - 1 && (s < name || *s == '/')) { t = s + 1; f += 2; continue; } limit = t + 2; } } while (*f && (*t++ = *f++) != '/') {} } if (t > name+anchored && t[-1] == '/') t--; if (t == name) *t++ = '.'; *t = '\0'; return t - name; }
true
df0655c95ff6cf88449547d15594d796b7d12b70
C++
lbc3402785/expressServer
/thread/workingthread.cpp
UTF-8
422
2.5625
3
[]
no_license
#include "workingthread.h" WorkingThread::WorkingThread(QObject *parent):QThread (parent) { state=CREATED; } WorkingThread::WorkingState WorkingThread::getState() const { return state; } void WorkingThread::setState(const WorkingState &value) { state = value; } bool WorkingThread::getStopSignal() const { return stopSignal; } void WorkingThread::setStopSignal(bool value) { stopSignal = value; }
true
31cc14a423af50f91898cface1261d815eff300e
C++
TheMrViper/gain-money
/Octets.h
UTF-8
1,428
2.6875
3
[]
no_license
#ifndef OCTETS_HEADER #define OCTETS_HEADER struct Rep { size_t cap; size_t len; size_t ref; static Rep null; public: void addref(void); void release(void); void * data(void); void * clone(void); void * unique(void); void * reserve(unsigned int); static size_t frob_size(unsigned int); static Rep * create(unsigned int); static void * operator new(unsigned int, unsigned int); static void operator delete(void *); }; struct Octets { private: void *base; Rep * rep(void) const; void unique(void); public: Octets & reserve(unsigned int); Octets & replace(const void *, unsigned int); ~Octets(); Octets(void); Octets(unsigned int); Octets(const void *, unsigned int); Octets(const void *, const void *); Octets(const Octets &); Octets & operator=(const Octets &); bool operator==(const Octets &) const; bool operator!=(const Octets &) const; Octets & swap(Octets &); void * begin(void); const void * begin(void) const; void * end(void); const void * end(void) const; size_t size(void) const; size_t capacity(void) const; Octets & clear(void); Octets & erase(void *, void *); Octets & insert(void *, const void *, unsigned int); Octets & insert(void *, const void *, const void *); Octets & resize(unsigned int); void dump(void); }; #endif // OCTETS_HEADER
true
a501e68a08548142259679309beaadc7b3e9213c
C++
bishal1433/Competitive-Programming
/Competative programming/problem A/solution.cpp
UTF-8
874
2.5625
3
[]
no_license
/* Paste the below link in your browser for question: https://codeforces.com/contest/1513/problem/A */ #include <bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define ll long long int void solve() { int n,k; cin>>n>>k; int check; if(n%2==0) { check=n/2-1; } else{ check=n/2; } if(k>check) { cout<<-1<<"\n"; return; } vector <int> v(n); for(int i=0;i<n;i++) { v[i]=i+1; } int j=n-2; while(k>0) { swap(v[j],v[j+1]); j=j-2; k--; } for(int i=0;i<n;i++) { cout<<v[i]<<" "; } cout<<"\n"; } int main() { fast; int t; cin>>t; while(t--) { solve(); } return 0; }
true
c7d1836d00ca82eb051d072e150c5238b9fafcd1
C++
lawtonsclass/f20-code-from-class
/csci40/lec29/sets.cpp
UTF-8
285
3.453125
3
[]
no_license
#include <iostream> #include <set> using namespace std; int main() { set<int> s; s.insert(2); s.insert(1); s.insert(3); // check if an element is there // (counts in sets can only ever be 0 or 1) cout << s.count(2) << endl; cout << s.count(4) << endl; return 0; }
true
0986b05a8866ffb5d63986e6f84424ea955290a7
C++
rychrd/waterScape
/src/imgProc.cpp
UTF-8
2,930
2.765625
3
[]
no_license
// // imgProc.cpp // nng_test // // Created by Richard on 27/08/2019. // Some pixel processing functions #include <stdio.h> #include "imgProc.h" // RGB 0.2126 // 0.7152 // 0.0722 //----------------------------------------------- Pxl::Pxl(){ w=320;h=240;chans=1; gradX.allocate(w, h, chans); gradY.allocate(w, h, chans); gradXY.allocate(w, h, chans); angs.allocate(w, h, chans); mags.allocate(w, h, chans); grayd.allocate(w, h, 1); diff.allocate(w, h, 1); } //----------------------------------------------- Pxl::Pxl(size_t w, size_t h, size_t chans){ } //----------------------------------------------- void Pxl::pxlSetup(size_t w, size_t h, size_t chans){ gradX.allocate(w, h, chans); gradY.allocate(w, h, chans); gradXY.allocate(w, h, chans); angs.allocate(w, h, chans); mags.allocate(w, h, chans); } //----------------------------------------------- Pxl::~Pxl(){ } //----------------------------------------------- ofPixels& Pxl::gradientX(ofPixels& px){ size_t numChans = px.getNumChannels(); if (numChans>1){} size_t w = px.getWidth(); size_t h = px.getHeight(); size_t col; for (size_t i=1; i<h-1; i++){ col = i * w * numChans; // span one row of pixels in the array for (size_t j=1; j<w-1; j+=numChans){ gradX[col+j] = (((px[(col+(j-1))]) *-1) + px[col+(j+1)]) * 0.5; // gradient in x using a [-1, 0, 1] kernel. } } return gradX; } //----------------------------------------------- ofPixels& Pxl::gradientY(ofPixels& px){ size_t w = px.getWidth(); size_t h = px.getHeight(); size_t col, colA, colB; for (size_t i=1; i<h-1; i++){ colA = (i-1) * w; // the pixel directly above in the image colB = (i+1) * w; // the pixel below col = i * w; // the centre pixel for (size_t j=1; j<w-1; j++){ gradY[col+j] = (((px[colA+j])*-1) + px[colB+j]) * 0.5; } } return gradY; } //----------------------------------------------- ofPixels& Pxl::gradientXY(ofPixels& xGrad, ofPixels& yGrad){ size_t totalPix = xGrad.size(); for (int i=0; i<totalPix;i++){ gradXY[i] = xGrad[i] + yGrad[i]; } return gradXY; } //----------------------------------------------- ofPixels& Pxl::grayScale(ofPixels& px_){ size_t numChans = px_.getNumChannels(); for (int i=0; i<grayd.size(); i++){ grayd[i] = ((px_[i*numChans] * 0.2126) + (px_[i*numChans+1] * 0.7152) + (px_[i*numChans+2] * 0.0722)); } return grayd; } //----------------------------------------------- ofPixels& Pxl::frameDiff(ofPixels& currentF, ofPixels& previousF){ size_t totalPix = currentF.size(); for (int i = 0; i<totalPix; i++){ diff[i] = abs(currentF[i] - previousF[i]); } return diff; }
true
75a3de96ebcd402f4318ad450bd8075f88cdb1ee
C++
kei1107/algorithm
/problems/Atcoder/ABC075_D.cpp
UTF-8
2,302
2.703125
3
[]
no_license
#include "bits/stdc++.h" using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const int INF = 1e9; const ll LINF = LLONG_MAX; /* <url:https://abc075.contest.atcoder.jp/tasks/abc075_d> 問題文============================================================ 2次元座標上に N 個の点があります。 i(1≦i≦N) 番目の点の座標は (xi,yi) です。 長方形の内部に N 点のうち K 個以上の点を含みつつ、それぞれの辺がX軸かY軸に平行な長方形を考えます。 このとき、長方形の辺上の点は長方形の内部に含みます。 それらの長方形の中で、最小の面積となるような長方形の面積を求めてください。 ================================================================= 解説============================================================= 長方形の右上と左下の角が頂点となり得るx、y値(全頂点のx,yの値) で全探索、 O(N^4 * N) N(<=50)から50^4 * 50 ~ 10^7 間に合う ================================================================ */ int main(void) { cin.tie(0); ios::sync_with_stdio(false); ll N,K; cin >> N >> K; vector<pll> ps(N); vector<ll> X(N),Y(N); for(int i = 0; i < N;i++){ cin >> ps[i].first >> ps[i].second; X[i] = ps[i].first; Y[i] = ps[i].second; } sort(X.begin(),X.end()); sort(Y.begin(),Y.end()); ll ans = LINF; for(int xi = 0; xi < N; xi++){ for(int xj = xi + 1; xj < N; xj++){ for(int yi = 0; yi < N; yi++){ for(int yj = 0; yj < N; yj++){ int cnt = 0; ll minx = X[xi], miny = Y[yi]; ll maxx = X[xj], maxy = Y[yj]; for(int k = 0; k < N;k++){ if(minx <= ps[k].first && ps[k].first <= maxx && miny <= ps[k].second && ps[k].second <= maxy) cnt++; } if(cnt >= K){ ans = min(ans,(maxx-minx)*(maxy-miny)); } } } } } cout << ans << endl; return 0; }
true
066d482952039b114779db25b7acf3667cad256a
C++
kyberdrb/EmployeeManagementSystem
/app/src/NoIDs_InID_Pool.h
UTF-8
209
2.84375
3
[]
no_license
#pragma once #include <exception> class NoIDs_InID_Pool : public std::exception { public: const char* what() const noexcept override { return "ID Pool is empty. No more IDs to borrow."; } };
true
678bfbcab1cf682e4c1c48d377b94c819caac177
C++
SubhamKumarPandey/DSA
/algorithms/CPlusPlus/Arrays/left-rotation.cpp
UTF-8
729
3
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> #define int long long int #define pb push_back using namespace std; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); int n,left_rotation_val; cin>>n>>left_rotation_val; int arr[n]; for (int i = 0; i < n; i++) { cin>>arr[i]; } left_rotation_val = left_rotation_val % n; //Doing this we can get the place from where the rotation starts. // 5 4 // 1 2 3 4 5 // 1 2 3 4 5 -> 2 3 4 5 1(1 rotation) -> 3 4 5 1 2(2 rotation) -> 4 5 1 2 3(3 rotation) -> 5 1 2 3 4(4 rotation) for(int i = left_rotation_val; i<n; i++){ cout<<arr[i]<<" "; } for(int i = 0;i<left_rotation_val;i++){ cout<<arr[i]<<" "; } }
true
cf050a54d1c7f9f00d424bd714584eac50d44c8e
C++
jackdongrepo/3081W-Bus-Simulation
/labs/lab03_class_basics/point2.h
UTF-8
237
2.65625
3
[]
no_license
#ifndef POINT2_H #define POINT2_H using namespace std; class Point2 { public: Point2(float x = 0, float y = 0); float DistanceBetween(Point2 other); int Quadrant(); void Print(); private: float x_cord, y_cord; }; #endif
true
cd98290c654949727f0457b02d079b75d3cb8e73
C++
spurnaye/ds-algos
/src/ds/LockFree/SPSCSpinLockQueue.h
UTF-8
1,467
3.46875
3
[]
no_license
#include <iostream> #include <atomic> // open ended SPSC Queue struct SPSCSpinLockQueue{ SPSCSpinLockQueue(){ head_ = new Node(-1, true); tail_ = new Node(-1, true); head_->next_ = tail_; tail_->prev_ = head_; }; SPSCSpinLockQueue& operator=(const SPSCSpinLockQueue& rhs) = delete; SPSCSpinLockQueue(const SPSCSpinLockQueue& rhs) = delete; void push(int64_t data){ Node* newNode = new Node(data); tryLock(); newNode->next_ = tail_; tail_->prev_->next_ = newNode; tail_->prev_ = newNode; std::cout << "pushed " << data; clearLock(); } int64_t pop(){ tryLock(); Node* next = head_->next_; head_->next_ = next->next_; next->next_->prev_ = head_; clearLock(); std::cout << "popped " << next->getData(); return next->getData(); } private: struct Node{ explicit Node(int64_t data, bool sentinal_node = false): data_{data}, sentinal_node_{sentinal_node}{}; int64_t getData(){return data_;} Node* next_ = nullptr; Node* prev_ = nullptr; private: int64_t data_ = -1; bool sentinal_node_ = false; }; bool tryLock(){ while(flag_.test_and_set(std::memory_order_acquire)){}; return true; } void clearLock(){ flag_.clear(std::memory_order_release); } Node* head_; Node* tail_; std::atomic_flag flag_; };
true
8f0406cef93e83ff4e4d2fdca39b5588c222e531
C++
futureyoungin/Algorithm-Study
/3-Week/dain/11659-구간합구하기4-dain.cpp
UTF-8
373
2.71875
3
[]
no_license
#include <iostream> using namespace std; int main(){ ios_base::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); int N, M, sum = 0; int array[100001]; cin >> N >> M; for(int i=1;i<=N;i++){ int a; cin >> a; sum += a; array[i] = sum; } for(int i=0;i<M;i++){ int start, end; cin >> start >> end; cout << array[end] - array[start-1] << "\n"; } }
true
61ab74ced2c8f29a9cda05f9fdce8e237ab94002
C++
ayushkr667/Codeforces-Problem
/Building_Teams.cpp
UTF-8
1,266
2.515625
3
[]
no_license
/*-------------------------------* | Name: Ayush Kumar | | College: SOE, CUSAT | | Dept: CSE | | Email: ayushkr667@gmail.com | *-------------------------------*/ #include<bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #define mp make_pair #define mod 1000000007 const double PI = 3.141592653589793238460; vector<int> arr[100001]; int team[100001], vis[100001]; int n, m, t; int flag = 1; void dfs(int node, int col) { vis[node] = 1; team[node] = col; vector<int>:: iterator it; for(it = arr[node].begin(); it!=arr[node].end(); it++) { if(vis[*it] && team[*it] == col) { flag = 0; } if(!vis[*it]) dfs(*it , col^1); } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin>>n>>m; while (m--) { int a, b; cin>>a>>b; arr[a].pb(b); arr[b].pb(a); } for(int i =1; i<=n; i++) { if(!vis[i]) dfs(i,0); } if(!flag) { cout<<"IMPOSSIBLE"; } else { for(int i=1; i<=n; i++) cout<<team[i]+1<<" "; } return 0; }
true
0344528cdf016279cfdb1b8819df9ef891e69f86
C++
garyhubley/ProjectEuler
/src/problem021.cpp
UTF-8
2,040
3.34375
3
[]
no_license
/* * File: Problem021.cpp * Author: Gary Hubley * Company: Self * Description: * This is my attempt at problem021 from projecteuler.net * * Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). * If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable * numbers. * * For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The * proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. * * Evaluate the sum of all the amicable numbers under 10000. * */ #include "EulerLib.h" #include <iostream> #include <chrono> #include <vector> #include <numeric> #include <algorithm> typedef std::chrono::high_resolution_clock Clock; #define ToSeconds( x ) ( std::chrono::duration_cast<std::chrono::seconds>( x ) ) #define ToMilliSeconds( x ) ( std::chrono::duration_cast<std::chrono::milliseconds>( x ) ) void problem021() { uint32_t sum_i, sum_d; std::vector< uint32_t > amicables; uint32_t idx = 0; auto start = Clock::now(); for ( uint32_t i = 2; i < 10000; i++ ) { if( std::find( amicables.begin(), amicables.end(), i ) != amicables.end() ) { continue; } std::vector< uint32_t > divisors = ProperDivisors( i ); sum_i = std::accumulate( divisors.begin(), divisors.end(), 0, std::plus<uint32_t>() ); if ( sum_i > i ) { std::vector< uint32_t > div_pair = ProperDivisors( sum_i ); sum_d = std::accumulate( div_pair.begin(), div_pair.end(), 0, std::plus<uint32_t>() ); if ( i == sum_d ) { amicables.push_back( i ); amicables.push_back( sum_i ); } } } sum_i = std::accumulate( amicables.begin(), amicables.end(), 0, std::plus<uint32_t>() ); //FwdPrintVector( amicables ); auto end = Clock::now(); std::cout << "Answer: " << sum_i << std::endl; std::cout << "Time: " << ToMilliSeconds( end - start ).count() << " milliseconds" << std::endl; }
true
2cbdf9fc57c16a37e493c3a446545ef3f5f93fce
C++
withelm/Algorytmika
/leetcode/algorithms/c++/Beautiful Arrangement/Beautiful Arrangement.cpp
UTF-8
1,224
2.9375
3
[]
no_license
class Solution { private: vector<vector<int>> next; int r; vector<bool> vis; void back(int k, int n) { // cout << k << " " << n << endl; // for(int i = 1; i <= n; i++) cout << vis[i] << " "; // cout << endl; if (k == n + 1) { ++r; return; } for (auto &i : next[k]) { if (!vis[i]) { vis[i] = true; back(k + 1, n); vis[i] = false; } } } public: int countArrangement(int n) { next.resize(20); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (j % i == 0) next[i].push_back(j); else if (i % j == 0) next[i].push_back(j); } } for (int i = 1; i <= n; i++) { cout << i << ": "; for (auto &x : next[i]) cout << x << " "; cout << endl; } vis.resize(n + 1); for (int i = 0; i < n + 1; i++) vis[i] = false; back(1, n); return r; } };
true
44effe60621418b97b6858d47ed02ffaeb3b13c7
C++
kmira1498/C-Class
/Practical 2/ex4/ex4.cpp
UTF-8
505
3.734375
4
[]
no_license
#include <iostream> using namespace std; //define function floyd to create the desired floyd's triangle void floyd (int lines) { int number = 1; cout << "Number of lines you want to display of Floyd's triangle: "; cin >> lines; for(int i = 1; i <= lines; ++i) { for(int j = 1; j <= i; ++j) { cout << number << " "; ++number; } cout << endl; }; } // call function int main() { int lines; floyd(lines); return 0; }
true
e30d2bf78c7b93635fc4d7ec3ae0467cbb400612
C++
Kristian-Krastev/OOP
/Introduction to Classes/Workers Task/Worker.h
UTF-8
392
2.90625
3
[]
no_license
#ifndef _WORKER_H_ #define _WORKER_H_ #include <string.h> class Worker { private: char name[32]; size_t year; double salary; public: Worker(); ~Worker(); public: const char* get_name() const; size_t get_year() const; double get_salary() const; void set_name(const char*); void set_year(size_t); void set_salary(double); void set_data(const char*, size_t, double); }; #endif
true
dbeb969700022b42103d0e73494410e54d00f0c3
C++
eskrut/multithread
/pthread/pthread.cpp
UTF-8
516
2.890625
3
[]
no_license
#include <stdlib.h> #include <pthread.h> #include <assert.h> void* someParallelTask(void *arg) { int *preciousValue = reinterpret_cast<int*>(arg); *preciousValue = 1; } int main(int argc, char**argv) { pthread_t thread; int value, othreValue; pthread_create(&thread, nullptr, someParallelTask, &value); someParallelTask(&othreValue); pthread_join(thread, nullptr); assert(value == othreValue); return 0; }
true
8766e63903161eb0fdc17d304b2a02840a2fb3e3
C++
shahzad-bhatti/mosaic_creator
/include/point.h
UTF-8
2,681
3.703125
4
[]
no_license
/** * @file point.h * Definition of a point class for k dimensional points. * * @author Shahzad Bhatti * @date Summer 2015 */ #ifndef POINT_H__ #define POINT_H__ #include <array> #include <cstdint> template <int Dim> class point { public: static_assert(Dim > 0, "Dimension argument must be positive"); /** * Creates a default point with zero values. */ point(); /** * Constructs a point from an array. * @param arr used to constuct point. */ point(double arr[Dim]); /** * Constructs a point from a list of arguments. * * @param args used to constuct point. */ template <class... Ts> explicit point(Ts... args); /** * Gets the value of the point object in the given dimension * (index). This function is const so we don't modify points using * this function. * * @param index The dimension of the point to grab. * @return The value of the point in the indexth dimension. * @throw std::out_of_range if accessing out of bounds */ double operator[](int index) const; /** * Gets the value of the point object in the given dimension * (index). This is the non-const version, so it can be used to * modify points like so: * * \code * point<3> a(1, 2, 3); * a[0] = 4; // a is now (4, 2, 3) * \endcode * * @param index The dimension of the point to grab. * @return The value of the point in the indexth dimension, by * reference (so that it may be modified). * @throw std::out_of_range if accessing out of bounds */ double& operator[](int index); private: double vals_[Dim]; }; /** * Compares two points for equality. * @param lhs The left hand side of the comparison * @param rhs The right hand side of the comparison * @return a boolean indicating whether lhs and rhs are equivalent points */ template <int Dim> bool operator==(const point<Dim>& lhs, const point<Dim>& rhs); template <int Dim> bool operator!=(const point<Dim>& lhs, const point<Dim>& rhs); /** * Compares whether a given point is smaller than another point. * * @param lhs The left hand side of the comparison * @param rhs The right hand side of the comparison * @return a boolean indicating whether lhs is less than rhs. */ template <int Dim> bool operator<(const point<Dim>& lhs, const point<Dim>& rhs); template <int Dim> bool operator>(const point<Dim>& lhs, const point<Dim>& rhs); template <int Dim> bool operator<=(const point<Dim>& lhs, const point<Dim>& rhs); template <int Dim> bool operator>=(const point<Dim>& lhs, const point<Dim>& rhs); #include "point.tcc" #endif
true
04fa2a7c7bc260f15d335807b1266f7e8884ef68
C++
norhakobyan/Struct-Stack
/StructStack.cpp
UTF-8
849
3.71875
4
[]
no_license
#include <iostream> const int size = 5; struct Stack { int stack[size]; int res; }; void push(Stack *, int); int pop(Stack *); int main() { Stack * tmp = new Stack; tmp->res = -1; push(tmp, 1); push(tmp, 2); push(tmp, 3); push(tmp, 4); push(tmp, 5); std::cout << std::endl; std::cout << "pop items " << pop(tmp) << std::endl; std::cout << "pop items " << pop(tmp) << std::endl; std::cout << "pop items " << pop(tmp) << std::endl; std::cout << "pop items " << pop(tmp) << std::endl; std::cout << "pop items " << pop(tmp) << std::endl; std::cout << std::endl; } void push(Stack * tmp, int sum) { if (tmp->res >= size) return; tmp->stack[++tmp->res] = sum; std::cout << "push items " << sum << std::endl; } int pop(Stack * tmp) { int sum = tmp->stack[tmp->res--]; return sum; }
true
368d96bd02471d2f38da3231fa387a892d09a9af
C++
samkellett/lmadb
/libs/cxx/include/cxx/adt/persistent_flat_map.hpp
UTF-8
2,973
2.9375
3
[]
no_license
#ifndef LMADB_CXX_ADT_PERSISTENT_FLAT_MAP_HPP #define LMADB_CXX_ADT_PERSISTENT_FLAT_MAP_HPP #include "cxx/filesystem.hpp" #include <boost/container/flat_map.hpp> #include <boost/interprocess/managed_mapped_file.hpp> namespace lmadb::cxx { template <typename Key, typename Value> class persistent_flat_map { // until required... static_assert(std::is_trivially_copyable_v<Key>); static_assert(std::is_trivially_copyable_v<Value>); using allocator = boost::interprocess::allocator< std::pair<Key, Value>, boost::interprocess::managed_mapped_file::segment_manager>; using map_type = boost::container::flat_map<Key, Value, std::less<Key>, allocator>; // TODO: make this dynamic. constexpr static auto map_size = 65536; public: using iterator = typename map_type::iterator; using const_iterator = typename map_type::const_iterator; using size_type = typename map_type::size_type; using key_type = typename map_type::key_type; using value_type = typename map_type::value_type; explicit persistent_flat_map(const cxx::filesystem::path &path); auto size() const -> std::size_t; auto insert(value_type value) -> std::pair<iterator, bool>; auto erase(const key_type &key) -> size_type; auto begin() const noexcept -> const_iterator; auto end() const noexcept -> const_iterator; auto find(const key_type &) const -> const_iterator; auto nth(size_type n) const -> const_iterator; private: boost::interprocess::managed_mapped_file file_; allocator alloc_; map_type *map_; }; template <typename Key, typename Value> persistent_flat_map<Key, Value>::persistent_flat_map(const cxx::filesystem::path &path) : file_{boost::interprocess::open_or_create, path.c_str(), map_size}, alloc_{file_.get_segment_manager()}, map_{file_.find_or_construct<map_type>("map")(alloc_)} { } template <typename Key, typename Value> auto persistent_flat_map<Key, Value>::size() const -> std::size_t { return map_->size(); } template <typename Key, typename Value> auto persistent_flat_map<Key, Value>::insert(value_type value) -> std::pair<iterator, bool> { return map_->insert(std::move(value)); } template <typename Key, typename Value> auto persistent_flat_map<Key, Value>::erase(const key_type &key) -> size_type { return map_->erase(key); } template <typename Key, typename Value> auto persistent_flat_map<Key, Value>::begin() const noexcept -> const_iterator { return map_->begin(); } template <typename Key, typename Value> auto persistent_flat_map<Key, Value>::end() const noexcept -> const_iterator { return map_->end(); } template <typename Key, typename Value> auto persistent_flat_map<Key, Value>::find(const key_type &key) const -> const_iterator { return map_->find(key); } template <typename Key, typename Value> auto persistent_flat_map<Key, Value>::nth(const size_type n) const -> const_iterator { return map_->nth(n); } } // namespace lmadb::cxx #endif // LMADB_CXX_ADT_PERSISTENT_FLAT_MAP_HPP
true
42e67611f974263a92ac555c7f4da9189b74fbf9
C++
ryanxunhuan/Sequential_Experimental_Design
/src/fileRead.cpp
UTF-8
484
2.953125
3
[]
no_license
#include "fileRead.h" /* Functions with templates are defined in header file. */ void readScalarAsString(char* const val, char const * const data, int &pos) { /* Initializations. */ int ctrVal(0); /* Find starting point for numeric value. */ while (data[pos] == ' ' || data[pos] == '=') pos++; /* Record numeric value. */ while (data[pos] != ' ' && data[pos] != '\0') { val[ctrVal] = data[pos]; ctrVal++; pos++; } val[ctrVal] = '\0'; }
true