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
445fdfd142c0d9d7cb9a2c6a81410a812bb2e8f6
C++
ryszard-raby/IoT
/Arduino/Firebase/src/main.cpp
UTF-8
2,932
2.5625
3
[]
no_license
#if defined(ESP32) #include <WiFi.h> #elif defined(ESP8266) #include <ESP8266WiFi.h> #endif #include <Arduino.h> #include <FirebaseService.h> #include <DateTime.h> #include <time.h> #include <cstdlib> #include <iostream> #include <Timer.h> #include <C:/Users/ryszard.raby/OneDrive/auth/auth.h> uint8_t builtInLed = 2; long long int serverTime = 0; unsigned long liveTime = 0; FirebaseService firebaseService; DateTime currentTime = DateTime(0, 0, 0, 0, 0, 0); int morning_start, evening_start, morning_power, evening_power; int secondTemp = 0; const int timersCount = 2; Timer timer[timersCount]; const int pinsCount = 3; int pin[pinsCount] = {4, 5, 12}; void connectWiFi() { WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("......."); Serial.println("Connected with IP:"); Serial.println(WiFi.localIP()); Serial.println(); } DateTime fullDate(long long int millis) { time_t t = millis / 1000; struct tm *tm = localtime(&t); tm->tm_hour += 2; time_t t2 = mktime(tm); tm = localtime(&t2); return DateTime(tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); } void getData(String key, String value) { if (key == "morning") { timer[0].hour = std::stoi(value.c_str()); timer[0].done = false; } if (key == "evening") { timer[1].hour = std::stoi(value.c_str()); timer[1].done = false; } if (key == "morning-power") { timer[0].value = std::stoi(value.c_str()); timer[0].done = false; } if (key == "evening-power") { timer[1].value = std::stoi(value.c_str()); timer[1].done = false; } if (key == "gpio2") { analogWrite(builtInLed, 255 - value.toInt()); } Serial.println(key + " : " + value); } void callback(String key, String value) { getData(key, value); if (key == "time") { serverTime = std::stoll(value.c_str()); } } void setup() { Serial.begin(9600); pinMode(builtInLed, OUTPUT); for (int i = 0; i < pinsCount; i++) { pinMode(pin[i], OUTPUT); } connectWiFi(); firebaseService.connectFirebase(); firebaseService.setCallback([](String key, String value) { callback(key, value); }); firebaseService.setTimestamp(); liveTime = millis(); } void setPinValue(int value) { for (int i = 0; i < pinsCount; i++) { analogWrite(pin[i], value); } } void loop() { firebaseService.firebaseStream(); currentTime = fullDate(serverTime + millis() - liveTime); if (millis() - liveTime > 600000) { firebaseService.setTimestamp(); liveTime = millis(); Serial.println(String(currentTime.hour) + ":" + String(currentTime.minute) + ":" + String(currentTime.second)); } for(int i = 0; i < timersCount; i++) { if (currentTime.hour >= timer[i].hour) { if (!timer[i].done) { setPinValue(timer[i].value); } timer[i].done = true; } } }
true
8286c4f74489bacce03b9d287c40521160ae726d
C++
KadirIsk/Snake
/Snake/Ssnake.cpp
UTF-8
2,684
3.046875
3
[]
no_license
#include "Ssnake.h" Ssnake::Ssnake(int x = 0, int y = 0) { this->gameIsOver = new bool(false); Block block(x, y); listOfBlock.push_back(block); block = Block(x, y + 1); listOfBlock.push_back(block); } Ssnake::Ssnake(deque<Block> listOfBlock) { this->gameIsOver = new bool(false); this->listOfBlock = listOfBlock; } Ssnake::Ssnake():Ssnake(0,0){ this->gameIsOver = new bool(false); } Ssnake::~Ssnake() { } Block Ssnake::getFirstBlock() { return this->listOfBlock.front(); } Block Ssnake::getLastBlock() { return this->listOfBlock.back(); } void Ssnake::setListOfBlock(deque<Block> listOfBlock) { this->listOfBlock = listOfBlock; } deque<Block> Ssnake::getListOfBlock() { return this->listOfBlock; } void Ssnake::pushBlock(Block block) { this->listOfBlock.push_back(block); } bool Ssnake::move(deque<CheckPoint> checkPoints, Coordinate prey) { for (deque<CheckPoint>::iterator check_it = checkPoints.begin(); check_it != checkPoints.end(); ++check_it) { for (deque<Block>::iterator block_it = listOfBlock.begin(); block_it != listOfBlock.end(); ++block_it) { if (check_it->getCoordinate() == block_it->getCoordinate()) { block_it->setDirection(check_it->getDirection()); } } } for (deque<Block>::iterator it = listOfBlock.begin(); it != listOfBlock.end(); ++it) it->moveNextPoint(); bool flag = addBlockToTail(prey); for (deque<CheckPoint>::iterator check_it = checkPoints.begin(); check_it != checkPoints.end(); ++check_it) { for (deque<Block>::iterator block_it = listOfBlock.begin(); block_it != listOfBlock.end(); ++block_it) { if (check_it->getCoordinate() == block_it->getCoordinate()) { block_it->setDirection(check_it->getDirection()); } } } return flag; } bool Ssnake::breakTheWall(int M, int N) { Coordinate coordinate = this->getLastBlock().getCoordinate(); if (coordinate.getX() >= M || coordinate.getY() >= N || coordinate.getX() < 0 || coordinate.getY() < 0) { *this->gameIsOver = true; return true; } return false; } bool Ssnake::hitTheTail() { Coordinate coordinate = getLastBlock().getCoordinate(); int count = 0; for (deque<Block>::iterator block_it = listOfBlock.begin(); block_it != listOfBlock.end(); ++block_it) if (coordinate == block_it->getCoordinate()) count++; if (count > 1) { *this->gameIsOver = true; return true; } return false; } bool Ssnake::addBlockToTail(Coordinate prey) { Block block = listOfBlock.front(); if (block.getPrevPosition(block.getDirection()) == prey) { Block newBlock(block.getPrevPosition(block.getDirection())); newBlock.setDirection(block.getDirection()); listOfBlock.push_front(newBlock); return true; } return false; }
true
484f6cdf4e519ad266087eba6b053013c139708a
C++
hitrich/Autonomous_Car_Lane_Det
/LaneDetector/Raw.cpp
UTF-8
1,273
2.8125
3
[ "MIT" ]
permissive
// // Created by crypton on 01.06.2021. // void TimeAnalyze::Start(){ if(debug){ clk_start = clock(); } } void TimeAnalyze::Stop(){ if(debug){ clk_duration = clock() - clk_start; clk_total += clk_duration; if( clk_maxtime < clk_duration ) clk_maxtime = clk_duration; if(clk_mintime > clk_duration) clk_mintime = clk_duration; framecounter++; } } void TimeAnalyze::Reset(){ if(debug){ clk_start = 0; clk_total = 0; clk_duration = 0; clk_maxtime = 0; clk_mintime = 100 * (double)CLOCKS_PER_SEC; framecounter = 0; } } void TimeAnalyze::Print(){ if(debug) { cout<<endl <<"TIME ANALYZE NAME: " << name <<endl <<"Number of Frame: " << framecounter <<endl <<"Maximum Frame Duration (s): " << (clk_maxtime /(double) CLOCKS_PER_SEC ) <<"\nMinumum Frame Duration (s): " << (clk_mintime /(double) CLOCKS_PER_SEC ) <<"\nAverage Frame Duration (s): " << (clk_total /(double) CLOCKS_PER_SEC ) / (double) framecounter <<"\nTOTAL TIME (s): " << (clk_total / (double) CLOCKS_PER_SEC) <<endl << "------\n"; } }
true
53cde9ff7802e8108eb93571877c07a6ce7c9131
C++
tayaharshuk/HW3
/Backup/UniqueArray.h
UTF-8
1,403
2.90625
3
[]
no_license
#ifndef MTMPARKINGLOT_UNIQUEARRAY_H #define MTMPARKINGLOT_UNIQUEARRAY_H #include <cstdio> #include <functional> #include "UniqueArrayExceptions.h" template <class Element, class Compare = std::equal_to<Element>> class UniqueArray { unsigned int size; Element** arr; int next; const Compare compare; public: UniqueArray(unsigned int size); UniqueArray(const UniqueArray& other); ~UniqueArray(); UniqueArray& operator=(const UniqueArray&) = delete; unsigned int insert(const Element& element); bool getIndex(const Element& element, unsigned int& index) const; const Element* operator[] (const Element& element) const; bool remove(const Element& element); unsigned int getCount() const; unsigned int getSize() const; class Filter { public: virtual bool operator() (const Element&) const = 0; }; UniqueArray filter(const Filter& f) const{ UniqueArray newArr(*this); for (int i = 0; i < size ; i++) { if (arr[i] != NULL && !f(*arr[i])){ newArr.remove(*(newArr.arr[i])); } } return newArr; } class UniqueArrayIsFullException : public std::exception{ const char *what() const noexcept override { return "Array is full"; } }; }; #include "UniqueArrayImp.h" #endif //MTMPARKINGLOT_UNIQUEARRAY_H
true
240a041d98b9a39a497481c626642ca244685bbd
C++
aksrit/Covid-19-Market-Scheduler
/Code.cpp
UTF-8
3,611
3
3
[]
no_license
#include <iostream> #include <vector> #define pb push_back #define ll long long int #define fi first #define se second #define vi std::vector<int> #define vl vector<ll> #define vd vector<long double> #define vvd vector<vector<long double> > #define vvi std::vector<vi> #define pii pair<int,int> #define pll pair<ll,ll> using namespace std; ll k,m,t,n; // where k = total types of shops opening in one time slot in one market, t = time slots available, m = number of parallel markets, n = types of shops long double c; // c= trade-off constant vector<vector<long double> >v; // list of distances between a type of shop and rest others. vector<vector<vector<ll> > > A,ans; // A corresponds to initial state and ans corresponds to final state long double goodness() // to calculate the goodness value { long double distance =0, similarities=0; ll i,j; // To calculate the similarities of all pairs within a single time slot in the same market for(i=0;i<m;i++){ for(j=0;j<t;j++){ for(ll kk=0;kk<k;kk++){ for(ll jj=kk+1;jj<k;jj++){ similarities+=(1-v[A[i][j][kk]-1][A[i][j][jj]-1]); } } } } //To calculate the distances of all pairs within a single time slot in the parallel market for(i=0;i<m;i++){ for(j=0;j<t;j++){ for(ll kk=0;kk<k;kk++){ for(ll jj=i+1;jj<m;jj++){ for(ll kkk=0;kkk<k;kkk++) distance+=v[A[i][j][kk]-1][A[jj][j][kkk]-1]; } } } } // goodness value is c*distance+similarities return c*distance+similarities; } int main() { cin>> k>>m >>t>>c; // taking inputs of k,m,t,c n=k*m*t; ll i,j; // To take input as a list of distances between a type of shop and rest others as a 3D array of m,t,k Size. for(i=0;i<n;i++){ vd temp; for(j=0;j<n;j++){ double xx; cin>> xx; temp.pb(xx); } v.pb(temp); } ll cnt=1; // Choosing the initial state for(i=0;i<m;i++){ vector<vector<ll> > B(t,vector<ll>(k)); for(j=0;j<t;j++){ for(ll kk=0;kk<k;kk++){ B[j][kk]=cnt++; } } A.pb(B); } long double mini= goodness(); // calculating goodness value for initial state ans=A; // Initializing ans as the initial state //Applying Greedy Hill Climb Algorithm for(i=0;i<1000000;i++){ ll i1=rand()%m,j1=rand()%t,k1=rand()%k; //randomly selecting any state ll i2=rand()%m,j2=rand()%t,k2=rand()%k; //randomly selecting any state swap(A[i1][j1][k1],A[i2][j2][k2]); //swapping randomly selected states long double local_max=goodness(); //calculating goodness value corresponding state // if the current state has goodness value greater, then updating the ans as that state, and also updating the mini value to the current local max if(local_max>mini){ mini=local_max; ans=A; } // else if goodness value is not greater than we keep iterating over the best state achieved till now. else { A=ans; } } //Printing the output in the required format for(i=0;i<m;i++){ for(j=0;j<t;j++){ for(ll kk=0;kk<k;kk++){ cout<<ans[i][j][kk]; cout<<" "; } if(j!=t-1){ cout<<"| "; } } cout<<endl; } return 0; }
true
a41aad07b05ad6ba804a54ae732570f2a454673c
C++
sumanthkv-bmsce/ADA
/longPalin.cpp
UTF-8
703
2.796875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int t[100][100]; int longPalin(string s1,string s2,int n,int m) { for(int i=0;i<n+1;i++) { t[i][0] = 0; } for(int i=0;i<m+1;i++) { t[0][i] = 0; } for(int i=1;i<n+1;i++) { for(int j=1;j<m+1;j++) { if(s1[i]==s2[j]) { t[i][j] = 1+t[i-1][j-1]; } else { t[i][j] = max(t[i-1][j],t[i][j-1]); } } } return t[n][m]; } int main() { string s1; cin>>s1; string s2 = s1; reverse(s1.begin(),s1.end()); memset(t,-1,sizeof(t)); int ele = longPalin(s2,s1,s1.length(),s1.length()); cout<<ele<<endl; }
true
e9e9705a7e4b1e7acca51e159ed4ec399b31875f
C++
Happy-Ferret/WikiAdventure
/WikiAdventure/Source/WA-SDL/SDLDebugQueueList.cpp
UTF-8
887
2.53125
3
[ "LicenseRef-scancode-public-domain" ]
permissive
#include "SDLDebugQueueList.h" CSDLDebugQueueList::CSDLDebugQueueList(): CSDLSizedQueueList( 300 ) { //DebugInfo( "CSDLBaseObject", "CSDLBaseObject", "Info", "Creating base SDL object.", FILE_INFO ); m_iPosX = 5; m_iPosY = 5; m_iAlpha = 150; m_iCountdownTime = 0; m_iTimeThreshold = 2000; // 1000 miliseconds = 1 second } CSDLDebugQueueList::~CSDLDebugQueueList() { //DebugInfo( "CSDLBaseObject", "~CSDLBaseObject", "Info", "Unloading base SDL object.", FILE_INFO ); } void CSDLDebugQueueList::Clear() { m_iCountdownTime = 0; CSDLSizedQueueList::Clear(); } void CSDLDebugQueueList::Think( const int& iElapsedTime ) { if ( m_vpObjects.size() > 0 ) { m_iCountdownTime += iElapsedTime; if ( m_iCountdownTime >= m_iTimeThreshold ) { m_iCountdownTime = 0; RemoveTopObject(); } } else { m_iCountdownTime = 0; } CSDLSizedQueueList::Think( iElapsedTime ); }
true
8ec52e7f9043a65658b5d2c9e2c5a2c53ae3dbb1
C++
du-dung/algorithm
/BOJ_17406_배열돌리기4_200206.cpp
UTF-8
2,706
3.609375
4
[]
no_license
/* 17406. 배열 돌리기 4 Gold 5 https://www.acmicpc.net/problem/17406 - 가능한 회전 연산 실행 순서를 모두 실행하며 최솟값 갱신하기 -> 연산 수행 순서에 따라 배열의 모양이 다르다 */ #include <iostream> #include <tuple> #include <vector> #include <climits> using namespace std; int N, M, K; vector<tuple<int, int, int>> turnOp; int answer = INT_MAX; vector<vector<int>> turn(int r, int c, int s, vector<vector<int>> arr) { //회전시키기 -> 매개변수 arr이 변한다 //가장 왼쪽 윗 칸이 (r-s, c-s), 가장 오른쪽 아랫 칸이 (r+s, c+s)인 정사각형을 시계 방향으로 한 칸씩 돌린다 // -> 반시계방향으로 진행하며 값을 가져온다 for (int n = 0; n < s; n++) { //바깥 쪽 사각형부터 회전 -> s는 사각형 개수 int len = 2*(s-n); //정사각형의 한 변의 길이 -1 int x = r - s + n, y = c - s + n; //가장 왼쪽 윗 칸의 좌표 int leftTop = arr[x][y]; //가장 왼쪽 윗 칸의 값 //좌변 for (int i = 0; i < len; i++, x++){ arr[x][y] = arr[x + 1][y]; } //밑변 for (int i = 0; i < len; i++, y++) { arr[x][y] = arr[x][y + 1]; } //우변 for (int i = 0; i < len; i++, x--) { arr[x][y] = arr[x - 1][y]; } //윗변 for (int i = 0; i < len-1; i++, y--) { //마지막 한 칸은 저장해둔 값으로 지정 arr[x][y] = arr[x][y - 1]; } arr[x][y] = leftTop; } return arr; } int getMinSum(vector<vector<int>> &arr) { int min = INT_MAX; for (int i = 1; i < arr.size(); i++) { int s = 0; for (int j = 0; j < arr[0].size(); j++) { s += arr[i][j]; } if (s < min) min = s; } return min; } void dfs(int n, vector<bool> turned, vector<vector<int>> arr) { //n은 현재까지 수행한 연산의 개수, turned & arr - call by value if (n == K) { //연산 수행 끝 -> 계산 int tmp = getMinSum(arr); if (tmp < answer) answer = tmp; return; } for (int i = 0; i < K; i++) { if (!turned[i]) { //아직 안돌았어 turned[i] = true; dfs(n + 1, turned, turn(get<0>(turnOp[i]), get<1>(turnOp[i]), get<2>(turnOp[i]), arr)); turned[i] = false; } } } int main() { //input cin >> N >> M >> K; vector<vector<int>> arr(N+1, vector<int>(M+1)); //index는 1~N * 1~M for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { cin >> arr[i][j]; } } turnOp = vector<tuple<int,int,int>>(K); //인스턴스 생성 for (int i = 0; i < K; i++){ cin >> get<0>(turnOp[i]) >> get<1>(turnOp[i]) >> get<2>(turnOp[i]); } //solve //가능한 연산 실행 순서의 모든 경우의 수 구하기 -> 순열 (재귀) vector<bool> turned(K, false); dfs(0, turned, arr); //output cout << answer; }
true
4aa2ed20a99a0561d66274711757fea25ee48bd9
C++
mirmik/malgo
/malgo/matrix.h
UTF-8
13,055
2.71875
3
[]
no_license
#ifndef MALGO_MATRIX_H #define MALGO_MATRIX_H #include <malgo/util.h> #include <malgo/vector.h> #include <malgo/algo/multiply.h> #include <malgo/algo/inverse.h> #include <malgo/raw/basealgo.h> #include <nos/trace.h> #include <linalg/linalg.h> namespace malgo { template <class M> struct matrix_iterator1; template <class M> struct matrix_iterator2; template <class M> struct const_matrix_iterator1; template <class M> struct const_matrix_iterator2; template <class M> struct matrix_iterator { M& m; int pos1; int pos2; matrix_iterator(M& _m, int _pos1, int _pos2) : m(_m), pos1(_pos1), pos2(_pos2) {} type_t<M> operator*() { return m(pos1, pos2); } const type_t<M> operator*() const { return m(pos1, pos2); } matrix_iterator2<M> begin2() { return {m, pos1, pos2}; } matrix_iterator2<M> end2() { return {m, pos1, m.size2()}; } bool operator==(const matrix_iterator& oth) { return pos1 == oth.pos1 && pos2 == oth.pos2; } bool operator!=(const matrix_iterator& oth) { return pos1 != oth.pos1 || pos2 != oth.pos2;; } }; template <class M> struct matrix_iterator1 : public matrix_iterator<M> { matrix_iterator1(M& _m, int _pos1, int _pos2) : matrix_iterator<M>(_m, _pos1, _pos2) {} matrix_iterator1 operator++() { ++matrix_iterator<M>::pos1; return *this; }; matrix_iterator1 operator++(int) { auto ret = *this; ++matrix_iterator<M>::pos1; return ret; }; }; template <class M> struct const_matrix_iterator1 : public matrix_iterator1<M> { const_matrix_iterator1(M& _m, int _pos1, int _pos2) : matrix_iterator1<M>(_m, _pos1, _pos2) {} }; template <class M> struct matrix_iterator2 : public matrix_iterator<M> { matrix_iterator2(M& _m, int _pos1, int _pos2) : matrix_iterator<M>(_m, _pos1, _pos2) {} matrix_iterator2 operator++() { ++matrix_iterator<M>::pos2; return *this; }; matrix_iterator2 operator++(int) { auto ret = *this; ++matrix_iterator<M>::pos2; return ret; }; }; template <class M> struct const_matrix_iterator2 : public matrix_iterator2<M> { const_matrix_iterator2(M& _m, int _pos1, int _pos2) : matrix_iterator2<M>(_m, _pos1, _pos2) {} }; template <class T, class A> class matrix; template <class T, class A> class matrix_view; template <class T, class A> class const_matrix_view; template <class T, class A> struct traits<matrix<T, A>> { using type = T; using alloc = A; using matrix = malgo::matrix<T,A>; using const_matrix_view = malgo::const_matrix_view<T,A>; using vector = malgo::vector<T,A>; using iterator = T*; using const_iterator = const T*; using iterator1 = matrix_iterator1<matrix>; using const_iterator1 = const_matrix_iterator1<matrix>; using iterator2 = matrix_iterator2<matrix>; using const_iterator2 = const_matrix_iterator2<matrix>; using matout = matrix_view<T,A>; }; template <class T, class A> struct traits<matrix_view<T, A>> { using type = T; using alloc = A; using matrix = malgo::matrix<T,A>; using matrix_view = malgo::matrix_view<T,A>; using const_matrix_view = malgo::const_matrix_view<T,A>; using vector = malgo::vector<T,A>; using iterator = T*; using const_iterator = const T*; using iterator1 = matrix_iterator1<matrix>; using const_iterator1 = const_matrix_iterator1<matrix>; using iterator2 = matrix_iterator2<matrix>; using const_iterator2 = const_matrix_iterator2<matrix>; }; template <class M> struct mroot { using type = typename traits<M>::type; using alloc = typename traits<M>::alloc; M& self_cast() { return *static_cast<M*>(this); } const M& self_cast() const { return *static_cast<const M*>(this); } type& elem(int i) { return self_cast().elem(i); } const type& elem(int i) const { return self_cast().elem(i); } int size() const { return self_cast().size(); } int size1() const { return self_cast().size1(); } int size2() const { return self_cast().size2(); } type* data() { return self_cast().data(); } const type* data() const { return self_cast().data(); } vecview<type, alloc> operator[](int i) { return self_cast()[i]; } const vecview<type, alloc> operator[](int i) const { return self_cast()[i]; } type& operator()(int i, int j) { return self_cast()(i, j); } const type& operator()(int i, int j) const { return self_cast()(i, j); } typename traits<M>::iterator begin() { return self_cast().begin(); }; typename traits<M>::iterator const end() { return self_cast().end(); }; typename traits<M>::iterator1 begin1() { return self_cast().begin1(); }; typename traits<M>::iterator1 const end1() { return self_cast().end1(); }; typename traits<M>::iterator2 begin2() { return self_cast().begin2(); }; typename traits<M>::iterator2 const end2() { return self_cast().end2(); }; }; template <class M> struct compact_matrix : public mroot<M> { using type = typename traits<M>::type; using alloc = typename traits<M>::alloc; using parent = mroot<compact_matrix<M>>; type* _data; int _size1; int _size2; int size() const { return _size1 * _size2; } int size1() const { return _size1; } int size2() const { return _size2; } type* data() { return _data; } const type* data() const { return _data; } type& elem(int i) { return _data[i]; } const type& elem(int i) const { return _data[i]; } vecview<type, alloc> operator[](int i) { return { _data + i * _size2, _size2 }; } const vecview<type, alloc> operator[](int i) const { return { _data + i * _size2, _size2 }; } type& operator()(int i, int j) { return _data[i * _size2 + j]; } const type& operator()(int i, int j) const { return _data[i * _size2 + j]; } type* begin() { return _data; } const type* begin() const { return _data; } type* const end() { return _data + _size1 * _size2; } const type* const end() const { return _data + _size1 * _size2; } matrix_iterator1<M> begin1() { return {static_cast<M&>(*this), 0, 0}; } const_matrix_iterator1<M> begin1() const { return {static_cast<M&>(*this), 0, 0}; } matrix_iterator1<M> const end1() { return {static_cast<M&>(*this), _size1, 0}; } const_matrix_iterator1<M> const end1() const { return {static_cast<M&>(*this), _size1, 0}; } matrix_iterator2<M> begin2() { return {static_cast<M&>(*this), 0, 0}; } const_matrix_iterator2<M> begin2() const { return {static_cast<M&>(*this), 0, 0}; } matrix_iterator2<M> const end2() { return {static_cast<M&>(*this), 0, _size2 }; } const_matrix_iterator2<M> const end2() const { return {static_cast<M&>(*this), 0, _size2 }; } operator matrix_view<type_t<M>, alloc_t<M>>() { return {_data, _size1, _size2}; } }; template <class T, class A = std::allocator<T>> struct matrix : public compact_matrix<matrix<T, A>>, public matrix_keeper<matrix<T, A>> { using parent = compact_matrix<matrix<T, A>>; using keeper = matrix_keeper<matrix<T, A>>; matrix() {} matrix(int size1, int size2) { keeper::create(size1, size2); } matrix(const std::initializer_list<std::initializer_list<T>>& list) { keeper::create(list.size(), list.begin()->size()); T* ptr = parent::_data; for (const auto& c : list) { for (const auto& v : c) { *ptr++ = v; } } } matrix(const matrix& oth) { keeper::create(oth.size1(), oth.size2()); T* ptr = parent::_data; const T*mptr = oth.data(); for (int i = 0; i < parent::size(); ++i) *ptr++ = *mptr++; } template<class M> matrix(const mroot<M>& oth) { keeper::create(oth.size1(), oth.size2()); T* ptr = parent::_data; const T*mptr = oth.data(); for (int i = 0; i < parent::size(); ++i) *ptr++ = *mptr++; } template<int N> matrix(const std::vector<linalg::vec<T,N>>& oth) { keeper::create(oth.size(), N); T* ptr = parent::data(); for (unsigned int i = 0; i < oth.size(); ++i) for (int j = 0; j < N; ++j) *ptr++ = oth[i][j]; //T* ptr = parent::_data; //const T*mptr = oth.data(); //for (int i = 0; i < parent::size(); ++i) *ptr++ = *mptr++; } }; template <class T, class A = std::allocator<T>> struct matrix_view : public compact_matrix<matrix_view<T, A>> { using parent = compact_matrix<matrix_view<T, A>>; matrix_view(T* data, int size1, int size2) : parent(data, size1, size2) {}; template <class W> matrix_view(mroot<W>& mat) : parent(mat.data(), mat.size1(), mat.size2()) {}; }; template<class F, class A, class B> using mxm_apply_t = matrix<ret_t<F, type_t<A>, type_t<B>>, alloc_t<A>>; template<class F, class A, class B> using sxm_apply_t = matrix<ret_t<F, A, type_t<B>>, alloc_t<A>>; template<class F, class A, class B> using mxs_apply_t = matrix<ret_t<F, type_t<A>, B>, alloc_t<A>>; template<class F, class A, class B> mxm_apply_t<F,A,B> elementwise(F&& f, const mroot<A>& a, const mroot<B>& b) { mxm_apply_t<F,A,B> res(a.size1(), b.size2()); for (int i = 0; i < a.size(); ++i) res.elem(i) = f(a.elem(i), b.elem(i)); return res; } template<class F, class A, class B> sxm_apply_t<F,A,B> sxm_elementwise(F&& f, const A& a, const mroot<B>& b) { sxm_apply_t<F,A,B> res(b.size1(), b.size2()); for (int i = 0; i < b.size(); ++i) res.elem(i) = f(a, b.elem(i)); return res; } template<class F, class A, class B> mxs_apply_t<F,A,B> mxs_elementwise(F&& f, const mroot<A>& a, const B& b) { mxs_apply_t<F,A,B> res(a.size1(), a.size2()); for (int i = 0; i < a.size(); ++i) res.elem(i) = f(a.elem(i), b); return res; } //Lexicographic compare template<class A, class B> int compare(const mroot<A>& a, const mroot<B>& b) { if (a.size() != b.size()) return a.size() - b.size(); auto ait = a.begin(); auto bit = b.begin(); auto aend = a.end(); while (ait != aend) { auto r = *ait++ - *bit++; if (r != 0) return r; } return 0; } template<class A, class B> bool operator == (const mroot<A>& a, const mroot<B>& b) { return compare(a, b) == 0; } template<class A, class B> bool operator != (const mroot<A>& a, const mroot<B>& b) { return compare(a, b) != 0; } template<class A, class B> bool operator < (const mroot<A>& a, const mroot<B>& b) { return compare(a, b) < 0; } template<class A, class B> bool operator > (const mroot<A>& a, const mroot<B>& b) { return compare(a, b) > 0; } template<class A, class B> bool operator <= (const mroot<A>& a, const mroot<B>& b) { return compare(a, b) <= 0; } template<class A, class B> bool operator >= (const mroot<A>& a, const mroot<B>& b) { return compare(a, b) >= 0; } //Algebraic template<class A, class B> mxm_apply_t<detail::op_add,A,B> operator + (const mroot<A>& a, const mroot<B>& b) { return elementwise(detail::op_add{}, a, b); } template<class A, class B> mxm_apply_t<detail::op_sub,A,B> operator - (const mroot<A>& a, const mroot<B>& b) { return elementwise(detail::op_sub{}, a, b); } template<class A, class B> mxs_apply_t<detail::op_mul,A,B> operator * (const mroot<A>& a, B b) { return mxs_elementwise(detail::op_mul{}, a, b); } //template<class A, class B> mxm_apply_t<detail::op_mul,A,B> operator * (const mroot<A>& a, const mroot<B>& b) { return elementwise(detail::op_mul{}, a, b); } //template<class A, class B> mxm_apply_t<detail::op_div,A,B> operator / (const mroot<A>& a, const mroot<B>& b) { return elementwise(detail::op_div{}, a, b); } //Basealgo template<class M> matrix_t<M> transpose(const compact_matrix<M>& a) { matrix_t<M> res(a.size2(), a.size1()); malgo::raw::transpose(a.data(), a.size1(), a.size2(), res.data()); return res; } //template<class M> matrix_t<M> inverse(const compact_matrix<M>& a) { assert(a.size1() == a.size2()); matrix_t<M> res(a.size1(), a.size1()); malgo::raw::square_matrix_inverse(a.data(), a.size1(), res.data()); return res; } template<class M> matrix_t<M> exponent(const compact_matrix<M>& a) { assert(a.size1() == a.size2()); matrix_t<M> res(a.size1(), a.size1()); malgo::raw::square_matrix_exponent(a.data(), a.size1(), res.data()); return res; } template<class T, class A = std::allocator<T>> matrix<T,A> diag(const std::initializer_list<T>& lst) { matrix<T,A> ret(lst.size(), lst.size()); const auto* data = lst.begin(); for (int i = 0; i < lst.size(); ++i) ret(i,i) = data[i]; return ret; } template<class T> matrix<T> identity(int num) { matrix<T> ret(num,num); for (int i = 0; i < num; ++i) for (int j = 0; j < num; ++j) ret(i,j) = i==j ? 1 : 0; return ret; } } template<class C, class M> std::basic_ostream<C> & operator << (std::basic_ostream<C> & out, const malgo::mroot<M> & m) { out << '{'; for (int i = 0; i < m.size1() - 1; ++i) { out << '{'; for (int j = 0; j < m.size2() - 1; ++j) { out << m[i][j] << ','; } out << m[i][m.size2() - 1] << '}' << ','; } out << '{'; for (int j = 0; j < m.size2() - 1; ++j) { out << m[m.size1() - 1][j] << ','; } out << m[m.size1() - 1][m.size2() - 1] << '}' << '}'; } #endif
true
1256acb65565a97acbccc78ad6b13bd7e5c327af
C++
xianghuade/Challenge_Programming_Contest_2nd_Edition
/chapter_02/sub2.3/lisequence.cpp
UTF-8
432
2.84375
3
[]
no_license
//最长上升子序列 #include <iostream> #include <algorithm> using namespace std; const int MAX_N = 1000; int n; int num[MAX_N + 1]; int dp[MAX_N + 1]; int main(){ int res = 0; cin >> n; for(int i=0; i<n; i++) cin >> num[i]; for(int i=0; i<n; i++){ dp[i] = 1; for(int j=0; j<i; j++){ if(num[j] < num[i]){ dp[i] = max(dp[i], dp[j] + 1); } } res = max(res, dp[i]); } cout << res << endl; return 0; }
true
f13b59654e9f39d46cb97613b4fb0120e8416b15
C++
josesaldanavi/upn_funAlg
/Fundamentos de programaciòn/Semana5.cpp
ISO-8859-1
669
3.375
3
[]
no_license
#include <iostream> using namespace std; int main() { int n1,n2,opc; int op=1; char opc1; while(op>0) { cout<<"Ingrese el primer nmero : "; cin>>n1; cout<<"Ingrese el nmero de desplazamiento: "; cin>>n2; cout<<"Ingrese que tipo de desplazamiento desea en numeros indicados:"<<endl; cout<<"1)<<(izquierda)"<<"2)>>(derecha)"<<endl; cin>>opc; switch(opc) { case 1:cout<<"Resultado es:"<<(n1<<n2);break; case 2:cout<<"Resultado es:"<<(n1>>n2);break; } cout<<endl<<endl; cout<<"quiere ingresar de nuevo?"<<"s/n :"<<endl; cin>>opc1; if(opc1=='s') { op++; system("cls"); } if(opc1=='n') { cout<<"adios"; } } }
true
6c1ef320d2304c71fb07f56114425c491a422190
C++
niyaznigmatullin/nncontests
/utils/IdeaProject/archive/unsorted/2015.01/2015.01.16 - SNWS 2015 Round 2/g.cpp
UTF-8
752
2.796875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; template<typename T> void printerr(T a) { auto i = begin(a); auto j = end(a); cerr << "["; while (i != j) { cerr << *i << ", "; i++; } cerr << "]"; cerr << endl; } ostream_iterator<int> debug(cerr, ", "); int b[123213]; int main() { std::vector<int> a = {1, 2, 3}; printf("%d\n", a.size()); printerr(a); std::copy(b, b + 10, debug); array<tuple<int, int, string>, 10> z; for (int i = 0; i < 10; i++) { int x, y; string name; cin >> x >> y >> name; z[i] = make_tuple(x, y, name); } std::sort(z.begin(), z.end()); for (auto i : z) { cerr << get<0>(i) << ' ' << get<1>(i) << ' ' << get<2>(i) << endl; } }
true
35b74a696629babce316e83c3f9c7c3dad5cd3f3
C++
LeTobi/tobilib
/database/tools/basetransfer.cpp
UTF-8
4,186
2.59375
3
[]
no_license
#define TC_DATABASE_INTERN #include "../database.h" #include <iostream> #include <cmath> using namespace tobilib; using namespace database_detail; Database sourcedb; Database targetdb; void transfer_data(Member src, Member tgt) { if (src.memtype.blockType != tgt.memtype.blockType) return; if (src.memtype.ptrType().name != tgt.memtype.ptrType().name) return; int amount = std::min(src.memtype.amount,tgt.memtype.amount); if (amount>1) { for (int i=0;i<amount;i++) transfer_data(src[i],tgt[i]); return; } if (src.memtype.blockType == BlockType::t_bool) tgt.set(src.get<bool>()); if (src.memtype.blockType == BlockType::t_char) tgt.set(src.get<char>()); if (src.memtype.blockType == BlockType::t_int) tgt.set(src.get<int>()); if (src.memtype.blockType == BlockType::t_double) tgt.set(src.get<double>()); if (src.memtype.blockType == BlockType::t_ptr) tgt.set( Cluster( &targetdb, targetdb.get_file(tgt.memtype.target_type), src->index() )); if (src.memtype.blockType == BlockType::t_list) for (Member item: src) tgt.emplace().set( Cluster( &targetdb, targetdb.get_file(tgt.memtype.target_type), item->index() )); } void transfer_data(Cluster src, Cluster tgt) { for (MemberType& memtype: src.cf->type.members) { if (!tgt.cf->type.contains(memtype.name)) continue; transfer_data( src[memtype.name], tgt[memtype.name] ); } } void transfer_data() { for (ClusterFile& srcfile: sourcedb.clusters) { ClusterFile* tgtfile = targetdb.get_file(srcfile.type.name); if (tgtfile == nullptr) continue; unsigned int capacity = srcfile.get_data_capacity(); for (unsigned int i=0;i<capacity;i++) transfer_data( Cluster(&sourcedb,&srcfile,i), Cluster(&targetdb,tgtfile,i) ); } } void allocate_clusters(std::string name) { ClusterFile* sourcefile = sourcedb.get_file(name); ClusterFile* targetfile = targetdb.get_file(name); if (targetfile==nullptr) return; unsigned int capacity = sourcefile->get_data_capacity(); while (targetfile->get_data_capacity() < capacity) targetfile->extend_data_capacity(); targetfile->set_data_capacity(capacity); targetfile->set_first_filled(sourcefile->get_first_filled()); targetfile->set_last_filled(sourcefile->get_last_filled()); targetfile->set_first_empty(sourcefile->get_first_empty()); targetfile->set_last_empty(sourcefile->get_last_empty()); for (unsigned int i=1;i<capacity;i++) { targetfile->set_occupied(i,sourcefile->get_occupied(i)); targetfile->set_previous(i,sourcefile->get_previous(i)); targetfile->set_next(i,sourcefile->get_next(i)); targetfile->set_refcount_add(i,-targetfile->get_refcount(i)); Cluster(&targetdb,targetfile,i).init_memory(); } } void allocate_clusters() { for (ClusterFile& cf: sourcedb.clusters) allocate_clusters(cf.type.name); } void transfer(std::string srcpath, std::string tarpath) { sourcedb.log.prefix = "source database: "; targetdb.log.prefix = "target database: "; sourcedb.setPath(srcpath); if (!sourcedb.init() || !sourcedb.open()) return; targetdb.setPath(tarpath); if (!targetdb.init() || !targetdb.open()) return; targetdb.disable_crash_protection(); std::cout << "allocate entries" << std::endl; targetdb.listfile.set_first_empty(0); targetdb.listfile.set_last_empty(0); targetdb.listfile.set_data_capacity(1); allocate_clusters(); std::cout << "transfer data" << std::endl; transfer_data(); std::cout << "finished" << std::endl; } int main(int argc, const char** args) { if (argc != 3) { std::cout << "Erwarte Ursprung und Zielanweisung:\nbasetransfer [source] [target]" << std::endl; return 0; } transfer(args[1],args[2]); }
true
bdda6022a87e9ee182e300cb92a5930f082320a7
C++
kbrauss/FMM2D
/src/Box.cc
UTF-8
27,950
3.265625
3
[ "CC-BY-4.0", "MIT" ]
permissive
/** Box.cc * * Created on: Jun 21, 2016 * Author: Keith D Brauss */ #include <complex> #include <vector> #include <iostream> #include <string> #include "Box.h" #include "Util.h" using namespace std; /** * The Problem Type * * We want to apply the FMM to a problem that has the following properties * - The domain is the unit square [0,1]x[0,1] * - The refinement is quadtree where one cell is a square and is split into * 4 squares of equal size * - The source points x and the target points y will be the same * (the source points x will also be the target points y). * The cells at each refinement level are squares * - The number of source (or target) particles in each cell at the lowest refinement level (l = L) are known * - We will set this number of particles per cell at l = L to nParticlesPerCell = 4 * - The particles' locations are determined by formulas that use the coordinates of the corners of their cells * - Example: - Suppose that the corners are ll=(0.0,0.0), lr=(1.0,0.0), ul=(0.0,1.0), and ur=(1.0,1.0), * where ll stands for lower-left, lr stands for lower-right, ul stands for upper left, * ur stands for upper right * - We wish the four particles to be inside the cell and 1/4 away from each corner w.r.t. the x and y axis * - Therefore, assuming that we are working with squares for cells, we can measure the length * of one side of the cell \f$s = \sqrt{ (ll[0] - lr[0])^2 + (ll[1] - lr[1])^2 }\f$. * - We want 1/4 of this distance. Let d = 0.25s * - Lets refer to the particles as points in the source vector x, say x1, x2, x3, x4 * - Then let x1[0] = ll[0] + d; x1[1] = ll[1] + d; * x2[0] = lr[0] - d; x2[1] = lr[1] + d; * x3[0] = ul[0] + d; x3[1] = ul[1] - d; * x4[0] = ur[0] - d; xr[1] = ur[1] - d; * * ul(0,1) *------------------------* ur(1,1) * | | * | | * | * * | * | x3 x4 | * | | * | | * | | * | * * | * | x1 x2 | * | | * ll(0,0) *------------------------* lr(1,0) * * |------------s-----------| * |--d---| |---d--| * * * The series representing the mother function is truncated at the index value p. * - Therefore, the coefficient arrays: c, dtilde, and d will have a size of p+1 * (since the series index starts counting at zero). * For each refinement level l, there are 4^l cells * - for l = 1, there are 4^1 = 4 cells * - for l = 2, there are 4^2 = 16 cells * - for l = 3, there are 4^3 = 64 cells * - ... * - for l = L, there are 4^L cells * Therefore, since the number of particles per cell at the lowest refinement level is set, * the total number of points in the domain is known and equals nParticlesPerCell*pow(4,L) * - Example: If the lowest refinement level is L = 3 and nParticlesPerCell = 4, * then the total number of particles is 4*4^3 = 4*64 = 256 particles in the domain * */ /** * Header Interface for Class Point * class Box { public: int DEFAULT_P = 12; int DEFAULT_LEVEL=3; int DEFAULT_INDEX=0; int level; // refinement level of box int index; // cell index of box (or cell) int p; // p is the index at which the series are truncated // unsigned int nParticlesPerCell = 4; // points in each cell at lowest refinement level (l = L) // int totalParticles; // total particles in domain (unit square) bool empty; // is box empty std::vector<std::complex<double> > c; std::vector<std::complex<double> > dtilde; std::vector<std::complex<double> > d; // // The number of source points (and target points) in a box will depend // on the refinement level. The lowest level l = L will have 4 particles // per box. As we work up through the levels to level l = 0, the number // of particles will increase by a multiple of 4 when going from one level // up to the next (four children for each parent) std::vector<Point> x; // source points std::vector<Point> y; // target points // Creates a new instance of Node Box(); Box(int level, int index, int p); int getLevel() { return level; }; void printLevel() { std::cout << "Box level is " << level << '\n'; }; void setLevel(int i) { this->level = i; }; int getIndex() { return index; }; void printIndex() { std::cout << "Box index is " << index << '\n'; }; void setIndex(int i) { this->index = i; }; Point getCenter(); double getSize() { return std::pow(2.0, -level); }; void setP(int p) { this->p = p; }; bool isEmpty() { return empty; }; std::vector<std::complex<double> > getC() {return c; }; void addToC(std::vector<std::complex<double> > &increment); std::string cToString(); void printC(); std::vector<std::complex<double> > getD() {return d; }; void addToD(const std::vector<std::complex<double> > &increment); std::string dToString(); void printD(); std::vector<std::complex<double> > getDtilde() {return dtilde; }; void addToDtilde(const std::vector<std::complex<double> > &increment); std::string dtildeToString(); void printDtilde(); void addX(Point &p); int getSizeX() { return this->x.size(); }; std::vector<Point> getX() { return this->x; }; void printSizeX() { std::cout << "Box sizeX is " << x.size() << "\n"; }; void addY(Point &p); int getSizeY() { return this->y.size(); }; std::vector<Point> getY() { return this->y; }; void printSizeY() { std::cout << "Box sizeY is " << y.size() << "\n"; }; std::string toString(); int getParentIndex(); void getNeighborsIndex (std::vector<int> &neighbor_indexes); void getParentsNeighborsIndex (std::vector<int> &parents_neighbor_indexes); void getNeighborsE4Index (std::vector<int> &neighborE4_indexes); void getChildrenIndex(std::vector<int> &children_indexes); private: void getChildrenIndexOfBox(int levelOfBox, int indexOfBox, std::vector<int> &children_indexes_of_box); }; */ Box::Box() : level(DEFAULT_LEVEL), index(DEFAULT_INDEX), p(DEFAULT_P), empty(true), c(p+1), dtilde(p+1), d(p+1) { for (int i=0; i<p; ++i) { // intiializing coefficients c[i] = 0.0; dtilde[i] = 0.0; d[i] = 0.0; } } Box::Box(int level, int index, int p) : level(level), index(index), p(p), empty(true), c(p+1), dtilde(p+1), d(p+1) { for (int i=0; i<p; ++i) { // intiializing coefficients c[i] = 0.0; dtilde[i] = 0.0; d[i] = 0.0; } } Point Box::getCenter() { Util util; std::complex<double> ll_corner = util.uninterleave(this->index, this->level); std::complex<double> middle(0.5,0.5); ll_corner += middle; ll_corner *= getSize(); Point center(ll_corner); return center; } void Box::addToC(std::vector<std::complex<double> > &increment) { for (unsigned int i=0; i<c.size(); ++i) c[i] = c[i] + increment[i]; } std::string Box::cToString() { std::string ansc = " C: "; for (unsigned int i=0; i<c.size(); ++i) { ansc+= "(" + std::to_string(c[i].real()) + " " + std::to_string(c[i].imag()) + ") "; } return ansc + "\n"; } void Box::printC() { std::cout << cToString() << "\n"; } void Box::addToD(const std::vector<std::complex<double> > &increment) { for (unsigned int i=0; i<d.size(); ++i) d[i] = d[i] + increment[i]; } std::string Box::dToString() { std::string ansd = " D: "; for (unsigned int i=0; i<d.size(); ++i) { ansd+= "(" + std::to_string(d[i].real()) + " " + std::to_string(d[i].imag()) + ") "; } return ansd + "\n"; } void Box::printD() { std::cout << dToString() << "\n"; } void Box::addToDtilde(const std::vector<std::complex<double> > &increment) { for (unsigned int i=0; i<dtilde.size(); ++i) dtilde[i] = dtilde[i] + increment[i]; } std::string Box::dtildeToString() { std::string ansdt = " Dtilde: "; for (unsigned int i=0; i<dtilde.size(); ++i) { ansdt+= "(" + std::to_string(dtilde[i].real()) + " " + std::to_string(dtilde[i].imag()) + ") "; } return ansdt + "\n"; } void Box::printDtilde() { std::cout << dtildeToString() << "\n"; } void Box::addX(Point &p) { this->x.push_back(p); } void Box::addY(Point &p) { this->y.push_back(p); } std::string Box::toString() { std::string ans = "box (l = " + std::to_string(level) + ", n = " + std::to_string(index) + ") \n"; std::string ansc = " C: "; std::string ansdt = " Dtilde: "; std::string ansd = " D: "; for (unsigned int i=0; i<c.size(); ++i) { ansc+= "(" + std::to_string(c[i].real()) + " " + std::to_string(c[i].imag()) + ") "; ansdt+="(" + std::to_string(dtilde[i].real()) + " " + std::to_string(dtilde[i].imag()) + ") "; ansd+= "(" + std::to_string(d[i].real()) + " " + std::to_string(d[i].imag()) + ") "; } ans += ansc + "\n" + ansdt + "\n" + ansd + "\n"; return ans; } /** * Explanation of getParentIndex * * * ^ y-axis * | * | * | * | * | * * 1.0 ------------------------------------------------------------------ * | | | | || | | | | * | 21 | 23 | 29 | 31 || 53 | 55 | 61 | 63 | * | | | | || | | | | * 0.875 --------5---------------7----------------13--------------15------- * | | | | || | | | | * | 20 | 22 | 28 | 30 || 52 | 54 | 60 | 62 | * | | | | || | | | | * 0.75 ----------------1--------------------------------3---------------- * | | | | || | | | | * | 17 | 19 | 25 | 27 || 49 | 51 | 57 | 59 | * | | | | || | | | | * 0.625 --------4---------------6----------------12--------------14------- * | | | | || | | | | * | 16 | 18 | 24 | 26 || 48 | 50 | 56 | 58 | * | | | | || | | | | * 0.5 __________________________________________________________________ * * | | | | || | | | | * | 5 | 7 | 13 | 15 || 37 | 39 | 45 | 47 | * | | | | || | | | | * 0.375 --------1---------------3----------------9---------------11------- * | | | | || | | | o | * | 4 | 6 | 12 | 14 || 36 | 38 | 44 | 46 | * | | | | || | | | | * 0.25 ----------------0--------------------------------2---------------- * | | | | || | | | | * | 1 | 3 | 9 | 11 || 33 | 35 | 41 | 43 | * | | | | || | | | | * 0.125 --------0---------------2----------------8---------------10------- * | | | | || | | | | * | 0 | 2 | 8 | 10 || 32 | 34 | 40 | 42 | * | | x | | || | | | | * 0.0 ------------------------------------------------------------------ ---------------> * 0.0 0.125 0.25 0.375 0.5 0.625 0.75 0.875 1.0 x-axis * * This is level l=3 refinement * * * going to parent level (level - 1) * shifting the index of this box to right 2 bits (syntax is index >> 2) * * Example: index n = 8 and level l = 2 * * At level l = 2 have 4^l = 4^2 = 16 cells * At parent level l = 2-1 = 1 have 4^l = 4^1 = 4 cells * * In binary n = 8 is 00001000 * Shifting 00001000 to right 2 bits gives 00000010 = 2^1 = 2 * We can see above that cell n=8 at l=2 has parent cell n=2 at l=1 * * Example: index n = 12 and level l = 2 * * At level l = 3 have 4^l = 4^3 = 64 cells * At parent level l = 3-1 = 2 have 4^2 = 4^2 = 16 cells * * In binary n = 12 is 00001100 * Shifting 00001100 to right 2 bits gives 00000011 = 2^1 + 2^0 = 2 + 1 = 3 * We can see above that cell n=8 at l=2 has parent cell n=2 at l=1 * */ int Box::getParentIndex() { return index >> 2; } /** * Explanation of getNeighborsIndex * * The nested for loop * for (int i=-1; i<=1; i++) for (int j=-1; j<=1; j++) if ( (i!=0||j!=0) && x+i>=0 && x+i<Math.pow(2, level) && y+j>=0 && y+j<Math.pow(2, level)) ans.addElement( t.getBox(level, Util.interleave(x+i, y+j, level)) ); * * Looking at the nested for loop, we see that there are 3*3 = 9 cases and that the case * (i,j) = (0,0) is removed as a possibility by the if statement. Therefore, there are 8 cases and * these match up with the 8 possible neighbors. The case (0,0) matches up with the center cell * for which we are trying to find the neighbors. * We can see that -1, 0, and 1 for i corresponds to left, center (zero) and right one cell length (one unit) * in the x direction * and -1, 0, and 1 for j corresponds to up, center (zero) and down one unit in the y direction from the cell of interest. * * Example: Let tmp = 0.15625 + 0.03125i * Then uninterleave function of class Util returns the location of the lower left corner * of the cell where this point is located. The location is given in terms of cell lengths from the * lower left corner of the domain. For this example the point (0.15625,0.03125) is located in the * lower left corner of cell n = 2. The uninterleave function would return 1 + 0i or x = 1 and y = 0 * implying left one cell length from the lower left corner of the domain and up zero cell lengths * to reach the lower left corner of cell n = 2. * * Let level = 3 * For the cell n = 2 containing the point (0.15625,0.03125) and having x = 1 and y = 0 * The neighbors of n = 0,1,2,3,8, and 9 * * i = -1 * j = -1 * ((i=)-1!=0 || (j=)-1!=0) && ((x+i=1+-1=)0>=0) && ((x+i=1+-1=)0<8(=2^3)) && (y+j=0+-1=-1>=0) && ((y+j=0+-1=)-1<8(=2^3)) * T T T F T = False * (False) There is no neighbor diagonally off the lower left corner of the cell n = 2 * * i = -1 * j = 0 * ((i=)-1!=0 || (j=)0!=0) && ((x+i=1+-1=)0>=0) && ((x+i=1-1=)0<8(=2^3)) && (y+j=0+0=0>=0) && (y+j=0+0=0<8(=2^3)) * T T T T T = True * (True) There is a neighbor directly to the left of the cell n = 2 * Recall that ans is a vector of boxes * ans.addElement( t.getBox(level, Util.interleave(x+i, y+j, level)) ); * ans.addElement( t.getBox(3, Util.interleave(1+-1, 0+0, 3)) ); * ans.addElement( t.getBox(3, Util.interleave(0, 0, 3)) ); * * The interleave function returns the index n = 0. * Since Util.interleave(0,0,3) returns the box that is zero increments horizontally and zero increments * vertically upward from the lower left hand corner of the domain. The index for this cell is n = 0. * * i = -1 * j = 1 * ((i=)-1!=0 || (j=)1!=0) && ((x+i=1+-1=)0>=0) && ((x+i=1+-1=)-1<8(=2^3)) && ((y+j=0+1=)1>=0) && ((y+j=0+1=)1<8(=2^3)) * T T T T T = True * (True) There is a neighbor diagonally off the upper left corner of the cell n = 2 * Recall that ans is a vector of boxes * ans.addElement( t.getBox(level, Util.interleave(x+i, y+j, level)) ); * ans.addElement( t.getBox(3, Util.interleave(1+-1, 0+1, 3)) ); * ans.addElement( t.getBox(3, Util.interleave(0, 1, 3)) ); * * The interleave function returns the index n = 1. * Since Util.interleave(0,1,3) returns the box that is zero increments horizontally and one increment * vertically upward from the lower left hand corner of the domain. The index for this cell is n = 1. * * i = 0 * j = -1 * ((i=)0!=0 || (j=)-1!=0) && ((x+i=1+0=)1>=0) && ((x+i=1+0=)1<8(=2^3)) && ((y+j=0+-1=)-1>=0) && ((y+j=0+-1=)-1<8(=2^3)) * T T T F T = False * (False) There is no neighbor directly below the cell n = 2 * * i = 0 * j = 0 * ((i=)0!=0 || (j=)0!=0) && ((x+i=1+0=)1>=0) && ((x+i=1+0=)1<8(=2^3)) && ((y+j=0+0=)0>=0) && ((y+j=0+0=)0<8(=2^3)) * F T T T T = False * (False) The cell located zero units left and zero units up is the cell itself (it is its own neighbor) * and is automatically accounted for * * i = 0 * j = 1 * ((i=)0!=0 || (j=)1!=0) && ((x+i=1+0=)1>=0) && ((x+i=1+0=)1<8(=2^3)) && ((y+j=0+1=)1>=0) && ((y+j=0+1=)1<8(=2^3)) * T T T T T = True * (True) There is a neighbor directly above the cell n = 2 * Recall that ans is a vector of boxes * ans.addElement( t.getBox(level, Util.interleave(x+i, y+j, level)) ); * ans.addElement( t.getBox(3, Util.interleave(1+0, 0+1, 3)) ); * ans.addElement( t.getBox(3, Util.interleave(1, 1, 3)) ); * * The interleave function returns the index n = 3. * Since Util.interleave(1,1,3) returns the box that is one horizontal cell length and one vertical * cell length upward from the lower left hand corner of the domain. The index for this cell is n = 3. * * i = 1 * j = -1 * ((i=)1!=0 || (j=)-1!=0) && ((x+i=1+1=)2>=0) && ((x+i=1+1)=2<8(=2^3)) && ((y+j=0+-1=)-1>=0) && ((y+j=0+-1=)-1<8(=2^3)) * T T T F T = False * (False) There is no neighbor diagonally off the lower right corner of the cell n = 2 * * i = 1 * j = 0 * ((i=)1!=0 || (j=)0!=0) && ((x+i=1+1=)2>=0) && ((x+i=1+1=)2<8(=2^3)) && ((y+j=0+0=)0>=0) && ((y+j=0+0=)0<8(=2^3)) * T T T T T = True * (True) There is a neighbor directly to the right of the cell n = 2 * Recall that ans is a vector of boxes * ans.addElement( t.getBox(level, Util.interleave(x+i, y+j, level)) ); * ans.addElement( t.getBox(3, Util.interleave(1+1, 0+0, 3)) ); * ans.addElement( t.getBox(3, Util.interleave(2, 0, 3)) ); * * The interleave function returns the index n = 8. * Since Util.interleave(1,1,3) returns the box that is two horizontal cell lengths and zero vertical * cell lengths upward from the lower left hand corner of the domain. The index for this cell is n = 8. * * i = 1 * j = 1 * ((i=)1!=0 || (j=)1!=0) && ((x+i=1+1=)2>=0) && ((x+i=1+1=)2<8(=2^3)) && ((y+j=0+1=)1>=0) && ((y+j=0+1)=1<8(=2^3)) * T T T T T = True * (True) There is a neighbor diagonally off the upper right corner of the cell n = 2 * Recall that ans is a vector of boxes * ans.addElement( t.getBox(level, Util.interleave(x+i, y+j, level)) ); * ans.addElement( t.getBox(3, Util.interleave(1+1, 0+1, 3)) ); * ans.addElement( t.getBox(3, Util.interleave(2, 1, 3)) ); * * The interleave function returns the index n = 9. * Since Util.interleave(2,1,3) returns the box that is two increments horizontally and one increment * vertically upward from the lower left hand corner of the domain. The index for this cell is n = 9. * */ void Box::getNeighborsIndex(std::vector<int> &neighbor_indexes) { // Finding x,y increments (cell lengths) from the lower left corner of // the domain to the lower left corner of this Box (cell) using the uninterleave // function from class Util and placing these increments in tmp in terms of // real term = horizontal units from lower left corner of domain and // imag term = vertical units from lower left corner of the domain neighbor_indexes.resize(0); Util util; std::complex<double> tmp = util.uninterleave(index,level); int x = (int)tmp.real(); int y = (int)tmp.imag(); for (int i=-1; i<=1; i++) for (int j=-1; j<=1; j++) if ( (i!=0||j!=0) && x+i>=0 && x+i<std::pow(2, level) && y+j>=0 && y+j<std::pow(2, level)) neighbor_indexes.push_back(util.interleave(x+i, y+j, level)); } // see getNeighborsIndex above for explanation void Box::getParentsNeighborsIndex(std::vector<int> &parents_neighbor_indexes) { // Finding x,y increments (cell lengths) from the lower left corner of // the domain to the lower left corner of this Box (cell) using the uninterleave // function from class Util and placing these increments in tmp in terms of // real term = horizontal units from lower left corner of domain and // imag term = vertical units from lower left corner of the domain parents_neighbor_indexes.resize(0); Util util; int parent_index; parent_index = this->getParentIndex(); std::complex<double> tmp = util.uninterleave(parent_index, level-1); int x = (int)tmp.real(); int y = (int)tmp.imag(); for (int i=-1; i<=1; i++) for (int j=-1; j<=1; j++) if ( (i!=0||j!=0) && x+i>=0 && x+i<std::pow(2, level-1) && y+j>=0 && y+j<std::pow(2, level-1)) parents_neighbor_indexes.push_back(util.interleave(x+i, y+j, level-1)); } /** * Explanation of getNeighborsE4Index * * The member function gets the interaction list for this box * The interaction list or set E_4 is made up of this box's parent's * nearest neighbor's children (peers of this box). * However, the list does not include the nearest neighbors of this box. * We obtain the interaction list E_4 by * (1) getting the indices of the near neighbors of this box * - we will check to make sure that these cell indexes are * - not in the interaction list set E_4 that will be returned * (2) getting the indexes of this box's parent's nearest neighbors * - we will then get the children of each of these parent boxes * - the children then form the interaction list - minus the near neighbors of this box * (3) getting the set of indices for the children of this box's parent's nearest neighbors * (4) comparing and removing the indices of this box's near neighbors from the list (set) * of step (3) */ void Box::getNeighborsE4Index(std::vector<int> &neighborE4_indexes) { neighborE4_indexes.resize(0); // getting the indexes of the near neighbors of this box std::vector<int> neighbor_indexes; neighbor_indexes.resize(0); this->getNeighborsIndex(neighbor_indexes); // getting the (parent) indexes of the near neighbors of the parent of this box std::vector<int> parents_neighbor_indexes; parents_neighbor_indexes.resize(0); this->getParentsNeighborsIndex(parents_neighbor_indexes); //for (unsigned int i=0; i<neighbor_indexes.size(); ++i) // std::cout << "neighbor_indexes[" << i << "] = " << neighbor_indexes[i] << "\n"; //for (unsigned int j=0; j<parents_neighbor_indexes.size(); ++j) // std::cout << "parents_neighbor_indexes[" << j << "] = " << parents_neighbor_indexes[j] << "\n"; // getting the (peer) indexes of the children of the neighbors of the parent std::vector<int> parent_neighbor_children_indexes; std::vector<int> box_children_indexes; parent_neighbor_children_indexes.resize(0); for (unsigned int i=0; i<parents_neighbor_indexes.size(); ++i) { box_children_indexes.resize(0); getChildrenIndexOfBox(level-1, parents_neighbor_indexes[i], box_children_indexes); for (unsigned int m=0; m<box_children_indexes.size(); ++m) parent_neighbor_children_indexes.push_back(box_children_indexes[m]); } // comparing and removing the indexes from the parent_neighbor_children that // are also near neighbors of this box bool flag_not_in_list = false; // true that parent_neighbor_children_indexes[i] is not // in the interaction list (is a near neighbor) of this box for (unsigned int i=0; i<parent_neighbor_children_indexes.size(); ++i) { flag_not_in_list = false; for (unsigned int j=0; j<neighbor_indexes.size(); ++j) if (parent_neighbor_children_indexes[i] == neighbor_indexes[j]) flag_not_in_list = true; if (flag_not_in_list == true) { // not adding the index 'parent_neighbor_children_indexes[i]' // to the interaction list neighborE4_indexes } else { neighborE4_indexes.push_back(parent_neighbor_children_indexes[i]); } } } /** Explanation of getChildrenIndex * * For 2D, quadtree structure we have four children indices to get * * In the for loop * for (int i=0; i<4; ++i) * children_indexes.push_back((index<<2)+i); * * the command * (index<<2)+i; * * shifts the index to the left two bits * * Example: l = 2 and index n = 9 * * n = 9 = 2^3 + 2^0 = 00001001 * * Shifting n = 9 to the left two bits (index << 2) * we have 00100100 and this is * 00100100 = 2^2 + 2^5 = 4 + 32 = 36 * * We can see that this is the index of the lower * left (ll) child (l=3 and n=36) of cell l=2 and n = 9 * (See the grid diagram above.) * * The other three children are obtained by adding * 1, 2, and 3 to the index of this child * (36 + 1 = 37 (ul), 36 + 2 = 38 (lr), and 36 + 3 = 39 (ur)) * */ void Box::getChildrenIndex(std::vector<int> &children_indexes) { children_indexes.resize(0); for (int i=0; i<4; ++i) children_indexes.push_back((this->index<<2)+i); } void Box::getChildrenIndexOfBox(int levelOfBox, int indexOfBox, std::vector<int> &children_indexes_of_box) { // need to assert that levelOfBox is between 2 and 8 // if refinement level is greater than 8, then bitwise operations will be incorrect (8 bits) // if refinement level is less than 2, then FMM does not apply (series approximation convergence not guaranteed) children_indexes_of_box.resize(0); for (int i=0; i<4; ++i) children_indexes_of_box.push_back((indexOfBox<<2)+i); }
true
3923ad1c70eccbb76b105cd4354c30c6e71ec06d
C++
alphamale327/Arduino
/SmartHome/security_camera_project/Security_Camera_Sleep140515/SleepMode_UNO/SleepMode_UNO.ino
UTF-8
4,266
2.75
3
[]
no_license
#include <avr/sleep.h> // powerdown library #include <avr/interrupt.h> // interrupts library #include <Adafruit_VC0706.h> // camera library #include <SoftwareSerial.h> // camera serial change // On Uno: camera TX connected to pin 6, camera RX to pin 8: SoftwareSerial cameraconnection = SoftwareSerial(6, 8); Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection); #define PIRSensor 2 #define light 13 #define voltCheck 0 volatile int deviceState; volatile int currentState; //*************************************************** // * Name: PIRInterrupt, "ISR" to run when interrupted in Sleep Mode void PIRInterrupt() { detachInterrupt(0); //disable interrupts while we wake up detachInterrupt(1); /* First thing to do is disable sleep. */ sleep_disable(); if(digitalRead(PIRSensor) == HIGH && currentState != 1) { takePic(); } } void SerialInterrupt() { detachInterrupt(0); //disable interrupts while we wake up detachInterrupt(1); /* First thing to do is disable sleep. */ sleep_disable(); if (Serial.available() > 0) { // read the oldest byte in the serial buffer: deviceState = Serial.read(); } switch(deviceState){ case '1': //disable detecting Serial.write(0xf8); deviceState = 10; //idle state currentState = 1; break; case '2': //enable detecting Serial.write(0xf8); deviceState = 10; currentState = 2; break; case '3': takePic(); deviceState = 10; break; case '4': Serial.write(0xf8); batteryLife(); deviceState = 10; break; default: Serial.write(0xf9); deviceState = 10; break; } } //*************************************************** // * Name: enterSleep void enterSleep() { //cli(); attachInterrupt(0, PIRInterrupt, HIGH); attachInterrupt(1, SerialInterrupt, CHANGE); /* the sleep modes SLEEP_MODE_IDLE - the least power savings SLEEP_MODE_ADC SLEEP_MODE_PWR_SAVE SLEEP_MODE_STANDBY SLEEP_MODE_PWR_DOWN - the most power savings */ set_sleep_mode(SLEEP_MODE_PWR_DOWN); // setting up for sleep ... sleep_enable(); // setting up for sleep ... //sei(); sleep_mode(); // now goes to Sleep and waits for the interrupt /* The program will continue from here after the interrupt. */ // then go to the void Loop() } // *********************************************************************** // set up the pins as Inputs, Outputs, etc. void setup() { pinMode(light, OUTPUT); pinMode (PIRSensor,INPUT); digitalWrite (PIRSensor, HIGH); // internal pullup enabled Serial.begin(57600); //if (!cam.begin()) { // Serial.write("No camera found?"); //no camera // delay(500); // return; //} // Set the picture size - you can choose one of 640x480, 320x240 or 160x120 // Remember that bigger pictures take longer to transmit! //cam.setImageSize(VC0706_320x240); // medium //cam.setImageSize(VC0706_640x480); // biggest cam.setImageSize(VC0706_160x120); // small uint8_t imgsize = cam.getImageSize(); delay (3000); // turn on, start the module, scan room } // **************************************** // setup is done, start program void loop() { enterSleep(); } // end void loop void takePic(){ digitalWrite(light,HIGH); //cam.setMotionDetect(false); //digitalWrite(light, HIGH); //Serial.println("Take a picture in 0.5 sec"); delay(500); cam.takePicture(); uint16_t jpglen = cam.frameLength(); while (jpglen > 0) { // read 32 bytes at a time; uint8_t *buffer; uint8_t bytesToRead = min(32, jpglen); // change 32 to 64 for a speedup but may not work with all setups! buffer = cam.readPicture(bytesToRead); Serial.write(buffer, bytesToRead); jpglen -= bytesToRead; } cam.resumeVideo(); digitalWrite(light, LOW); } void batteryLife() { int value = analogRead(voltCheck); //if(value < 430){ //Serial.println("Warning! Please replace a bettery!"); //} //Serial.println(value); value = map(value, 210, 900, 0, 100); Serial.write(0xf1); Serial.write(value); }
true
8c9e80e214f8382e4c8818949bc3b3e6163d57f3
C++
timi-liuliang/echo
/thirdparty/google/ruy/ruy/blocking_counter.h
UTF-8
2,447
2.71875
3
[ "MIT" ]
permissive
/* Copyright 2019 Google LLC. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef RUY_RUY_BLOCKING_COUNTER_H_ #define RUY_RUY_BLOCKING_COUNTER_H_ #include <atomic> #include <condition_variable> // NOLINT(build/c++11) // IWYU pragma: keep #include <mutex> // NOLINT(build/c++11) // IWYU pragma: keep #include "ruy/time.h" namespace ruy { // A BlockingCounter lets one thread to wait for N events to occur. // This is how the master thread waits for all the worker threads // to have finished working. // The waiting is done using a naive spinlock waiting for the atomic // count_ to hit the value 0. This is acceptable because in our usage // pattern, BlockingCounter is used only to synchronize threads after // short-lived tasks (performing parts of the same GEMM). It is not used // for synchronizing longer waits (resuming work on the next GEMM). class BlockingCounter { public: BlockingCounter() : count_(0) {} // Sets/resets the counter; initial_count is the number of // decrementing events that the Wait() call will be waiting for. void Reset(int initial_count); // Decrements the counter; if the counter hits zero, signals // the threads that were waiting for that, and returns true. // Otherwise (if the decremented count is still nonzero), // returns false. bool DecrementCount(); // Waits for the N other threads (N having been set by Reset()) // to hit the BlockingCounter. // // Will first spin-wait for `spin_duration` before reverting to passive wait. void Wait(const Duration spin_duration); private: std::atomic<int> count_; // The condition variable and mutex allowing to passively wait for count_ // to reach the value zero, in the case of longer waits. std::condition_variable count_cond_; std::mutex count_mutex_; }; } // namespace ruy #endif // RUY_RUY_BLOCKING_COUNTER_H_
true
f4b3904990e12828ae7dfa7bed2327a7e4e55c59
C++
mkrum/neuralnet
/c++/neuron.cpp
UTF-8
1,243
3.015625
3
[]
no_license
//Neuron Class Implemention // mkrum #include "Neuron.h" //default activation functions double sigmoid(double); double sigmoidDer(double); Neuron::Neuron(int size){ std::random_device r; std::default_random_engine gen(r()); std::uniform_real_distribution<double> dist(0, 1); for(int i = 0; i < size; i++){ weights.push_back(dist(gen)); } error.reserve(size); inputs.reserve(size); bias = dist(gen); _activation = &sigmoid; _activationDer = &sigmoidDer; stepSize = .7; } double Neuron::feedForward(vector<double> ins){ inputs = ins; double sum = 0; for(int i = 0; i < weights.size(); i++){ sum += inputs[i] * weights[i]; } output = _activation(sum + bias); return output; } vector<double> Neuron::backPropagate(double inError){ for(int i = 0; i < weights.size(); i++){ error[i] = inError * _activationDer(output) * weights[i]; weights[i] -= stepSize * inError * _activationDer(output) * inputs[i]; } bias -= stepSize* inError * _activationDer(output) * bias; return error; } double sigmoid(double val){ return 1/(1 + exp(-val)); } double sigmoidDer(double val){ return sigmoid(val) * ( 1 - sigmoid(val)); }
true
9e4ebfa8e14d8f3b898a56cc02bb44e0ab77be8b
C++
AmaranthYan/RayMarching
/Light2D/source/Shader.h
UTF-8
1,166
2.65625
3
[]
no_license
#pragma once #include <glad/glad.h> #include <iostream> #define MAX_SHADER_SIZE 16384 // single shader file cannot exceed 16 kb class Shader { public: Shader(const char *vertex_file, const char *fragment_file); Shader(const char *compute_file); // remove copy constructor/assignment Shader(const Shader &) = delete; Shader &operator=(const Shader &) = delete; // define move constructor/assignment Shader(Shader &&shader) : shader_program(shader.shader_program) { shader.shader_program = 0; } Shader &operator=(Shader &&shader) { if (this != &shader) { // release prev shader Release(); std::swap(shader_program, shader.shader_program); } } // release shader on destruct ~Shader() { Release(); } void Use(); int GetUniform(const char *param_name); private: unsigned int shader_program = 0; void Release() { glDeleteProgram(shader_program); shader_program = 0; } void Load(const char *shader_file, char *source); unsigned int Compile(const int shader_type, const char *shader_file); void Link(const unsigned int vertex_shader, const unsigned int fragment_shader); void Link(const unsigned int compute_shader); };
true
129c860b2e35a0f66c7957ae2d8540eb82297d2d
C++
GBelzoni/workspace
/CppRate_Curve_tests/Tests/LinearZeroesInnerCurve_test.cpp
UTF-8
2,194
2.65625
3
[]
no_license
/* * LinearZeroesInnerCurve_test.cpp * * Created on: Jun 5, 2013 * Author: phcostello */ #include "LinearZeroesInnerCurve.h" #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include "InstrumentDF.h" #include <vector> //#include "BaseInnerCurve.h" using namespace std; BOOST_AUTO_TEST_SUITE( LinerZeroInnerCurve) BOOST_AUTO_TEST_CASE( basic_tests ) { double expiry1 = 1; LinearZeroesInnerCurve curve; //Check that can't get expiry before fitted BOOST_CHECK_THROW(curve.get_DF(expiry1), CurveNotFitted ); //Add two instruments InstrumentDF df1,df2,df3; df1.fromCcr(0.05,0.5); df2.fromCcr(0.01,1.0); df3.fromCcr(0.03,0.2); curve.add_DF(df1); curve.add_DF(df2); curve.add_DF(df3); BOOST_MESSAGE("df1's df = " << df1.getDf()); BOOST_MESSAGE("df2's df = " << df2.getDf()); BOOST_MESSAGE("df3's df = " << df3.getDf()); int len = curve.length(); BOOST_CHECK_EQUAL(len, 3); vector<vector<double> > list = curve.GetDFList(); BOOST_CHECK_CLOSE(list[0][0], 0.994018, 0.01); //Check df BOOST_CHECK_CLOSE(list[0][1], 0.2, 0.01); //Check expiry BOOST_MESSAGE("Added one df instrument: Check df and expiry ok"); //Fit curve //QuantLib::LinearInterpolation LinInt = curve.fit_curve(); curve.fit_curve(); BOOST_MESSAGE("Curve Fitted"); InstrumentDF df; double dfval; df = curve.get_DF(0.3); dfval = df.getCcr(); BOOST_MESSAGE("Fitted cc rate is " << dfval); df = curve.get_DF(0.8); dfval = df.getCcr(); BOOST_MESSAGE("Fitted cc rate is " << dfval); //Check that extrapolation is working df = curve.get_DF(0.00001); dfval = df.getCcr(); BOOST_MESSAGE("Fitted cc rate is " << dfval); //works but a little strange as can't tell how extrapolating. //Not holding constant zero rate outside of interp range //Can get around by adding overnight depo InstrumentDF df4; df4.fromCcr(0.01,0.004); //Overnight Depo curve.reset(); curve.add_DF(df1); curve.add_DF(df2); curve.add_DF(df3); curve.add_DF(df4); curve.fit_curve(); //Check that extrapolation is working df = curve.get_DF(0.1); //Halfway to first rate dfval = df.getCcr(); BOOST_MESSAGE("Fitted final cc rate is " << dfval); } BOOST_AUTO_TEST_SUITE_END()
true
9fde523f8d5ffc289b89a0d1a4d69b977e7e05c2
C++
GyosunShin/ProblemSolving
/백준 유형별 문제풀이/이분탐색/2805나무 자르기(3rd).cpp
UHC
938
2.890625
3
[]
no_license
//  M ؼ ܱ⿡ ִ ִ ϴ α׷ ۼϽÿ. // (1 N( ) 1,000,000, 1 M( ) 2,000,000,000) #include <cstdio> #include <algorithm> using namespace std; int N, M; int pan[1000000]; int mmax = -1; int ans; bool check(int input){ long long tmp_cnt = 0; for(int i = 0 ; i < N ; ++i){ int tmp = pan[i] - input; if(tmp < 0) continue; tmp_cnt += tmp; } if(tmp_cnt >= M) return true; return false; } void solve(){ int left = 1; int right = mmax; while(left <= right){ int mid = (left + right) / 2; if(check(mid)){ left = mid + 1; } else{ right = mid - 1; } } ans = right; } int main(){ scanf("%d %d", &N, &M); for(int i = 0 ; i < N ; ++i){ scanf("%d", &pan[i]); mmax = max(mmax, pan[i]); } solve(); printf("%d", ans); return 0; }
true
34459c1a9f75590d91bb9225664c87f6ddf4613c
C++
redfox5557/Replit-Stuff
/Weekly-Challenges/Week 1/Week1-C++.cpp
UTF-8
1,276
3.859375
4
[]
no_license
#include <iostream> int main() { int square = 0; int squareRoot = 2; int beforeSquareRoot = squareRoot; int previousNum = 1; std::cout << "Enter a number(preferably a perfect square): "; std::cin >> square; if (square == 0 || square == 1) { std::cout << "Your number inputted is " << square << " , and " << square << " is the square of itself, so your answer is " << square << "!\n"; abort(); } while (true) { if (squareRoot % 1000 == 0) { std::cout << "."; } if (squareRoot % 10000 == 0) { std::cout << "This may take some time"; } for (int i = 1; i < beforeSquareRoot; i++) { squareRoot += beforeSquareRoot; } if (squareRoot == square) { squareRoot = beforeSquareRoot; break; } else if (squareRoot > square) { squareRoot = beforeSquareRoot; std::cout << "\nYour number must not be a perfect square. The square root is between " << previousNum << " and " << squareRoot << "!"; abort(); } squareRoot = beforeSquareRoot; previousNum = squareRoot; squareRoot += 1; beforeSquareRoot = squareRoot; } std::cout << "\nThe square root of " << square << " is " << squareRoot << "!\nThanks for using our program!\n"; }
true
5b1860378053e89be02a4d26e5a3b4cd3d987820
C++
prestonf136/Steem
/STEEM/src/library/VertexBuffer/VertexBuffer.hpp
UTF-8
462
2.6875
3
[]
no_license
#pragma once #include <glad/glad.h> #include "../steem_macros.hpp" namespace Steem { struct VertexBufferInfo { GLuint size; GLfloat *VertexArray; }; } namespace Steem { class VertexBuffer { private: GLuint m_BufferID; public: VertexBuffer(Steem::VertexBufferInfo info); ~VertexBuffer(); inline void Bind() const { glBindBuffer(GL_ARRAY_BUFFER, m_BufferID); }; inline void UnBind() const { glBindBuffer(GL_ARRAY_BUFFER, 0); }; }; }
true
c24ae0b82b3e2dc095b5b67c0fbf17c0c3979669
C++
QinHaoChen97/VS_C
/DFS/51.n-皇后.cpp
UTF-8
2,734
3.015625
3
[]
no_license
// @before-stub-for-debug-begin #include <vector> #include <string> #include "commoncppproblem51.h" using namespace std; // @before-stub-for-debug-end /* * @lc app=leetcode.cn id=51 lang=cpp * * [51] N 皇后 */ // @lc code=start #include<iostream> #include<vector> using namespace std; //皇后可以走横竖斜三个方向 class Solution { public: vector<vector<int>> used;//判断当前的子能不能走,放2代表放了棋子,1代表是攻击范围 vector<vector<string>> ans; int path;//用来判断现在摆放了几个皇后 vector<vector<string>> solveNQueens(int n) { //1<=n<=9 if (n==1) { return {{"Q"}}; } //因为是n*n的棋盘和n个棋子,所以满足条件的解法一定是每行放一个棋子 //故只需要便利第一行就可 used=vector<vector<int>>(n,vector<int>(n,0)); for (int j = 0; j < n; j++) { dfs(0,j,n); } return ans; }; void dfs(int i,int j,int n) { /*if (i>=n && j>=n) { return; } */ if (used[i][j]!=0) { return; } path++;//放置一枚皇后 vector<vector<int>> lastused=used;//用于回溯 setattack(i,j,n); used[i][j]=2;//标识皇后的位置 if (path==n) { vector<string> s_ans; string s=""; for (auto row:used) { s=""; for (auto column:row) { if (column==2) { s+="Q"; } else { s+="."; } } s_ans.push_back(s); } ans.push_back(s_ans); } else { for (int j = 0; j < n; j++) { dfs(i+1,j,n); } } //回溯 used=lastused; path--; return; }; void setattack(int i,int j,int n)//设置攻击范围 { for (auto row:used[i])//行置1 { row=1; } for (int k=0;k<n;k++)//列置1 { used[k][j]=1; } //斜对角只需要向下置1,因为是上面一行放好后才往下放,上面一行必定已经被占 //左下角 int row=i,column=j; while (row<n-1 && column>0) { used[++row][--column]=1; } row=i,column=j; while (row<n-1 && column<n-1) { used[++row][++column]=1; } }; }; // @lc code=end
true
1ee27f5904f7d2712489f87a18504c1759e120a8
C++
SenorGato/script_bot
/include/string_util.hpp
UTF-8
1,863
3.40625
3
[ "MIT" ]
permissive
#ifndef LIPH_STRING_UTIL_HPP #define LIPH_STRING_UTIL_HPP #include <cctype> #include <cstddef> #include <string> #include <string_view> // yes, overloading operators for std::string and std::string_view combinations is not allowed, but // i don't care template<typename Char, typename Traits, typename Alloc> std::basic_string<Char, Traits, Alloc> operator+(std::basic_string<Char, Traits, Alloc> left, std::basic_string_view<Char, Traits> right) { left.append(right); return left; } template<typename Char, typename Traits, typename Alloc> std::basic_string<Char, Traits, Alloc> operator+(std::basic_string_view<Char, Traits> left, std::basic_string<Char, Traits, Alloc> right) { right.insert(0, left); return right; } template<typename Char, typename Traits, typename Alloc> bool operator<(const std::basic_string<Char, Traits, Alloc> &left, std::basic_string_view<Char, Traits> right) { return std::string_view(left) < right; } template<typename Char, typename Traits, typename Alloc> bool operator<(std::basic_string_view<Char, Traits> left, const std::basic_string<Char, Traits, Alloc> &right) { return left < std::string_view(right); } inline bool starts_with(std::string_view str, std::string_view prefix) { return str.size() >= prefix.size() && str.substr(0, prefix.size()) == prefix; } inline std::string to_lower(std::string str) { for(std::size_t i = 0, len = str.size(); i < len; ++i) str[i] = std::tolower(str[i]); return str; } inline std::string to_lower(std::string_view str) { return to_lower(std::string(str)); } inline std::string trim(const std::string &str) { std::size_t first_letter = str.find_first_not_of(' '); if(first_letter == std::string::npos) return ""; return str.substr(first_letter, str.find_last_not_of(' ') - first_letter + 1); } #endif
true
b5633dc1b94a5a0266b6efc793698d829e34fcab
C++
Scronty/bitcoin-sv
/src/test/threadpool_tests.cpp
UTF-8
3,979
2.78125
3
[ "MIT" ]
permissive
// Copyright (c) 2018 The Bitcoin SV developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/test/unit_test.hpp> #include <threadpool.h> #include <atomic> #include <iostream> #include <task.h> #include <task_helpers.h> namespace { // Each task increments a counter by this much constexpr unsigned Increment { 1000000 }; // A shared counter std::atomic<unsigned> Counter {0}; // A function task void Function(unsigned inc) { // Some pointless work for(unsigned i = 0; i < inc; ++i) { Counter++; } } // A member function task struct TaskClass { void MemberFunction(unsigned inc) { Function(inc); } }; TaskClass taskClass {}; // A lambda task auto lambdaTask { [](unsigned inc){ Function(inc); } }; } BOOST_AUTO_TEST_SUITE(TestThreadPool); // Test basic non-prioritised thread pool handling BOOST_AUTO_TEST_CASE(NonPrioritised) { CThreadPool<CQueueAdaptor> pool { "TestPool", 4 }; BOOST_CHECK_EQUAL(pool.getPoolSize(), 4); BOOST_CHECK_EQUAL(Counter, 0); // Submit some tasks to the queue std::vector<std::future<void>> results {}; results.push_back(make_task(pool, Function, Increment)); results.push_back(make_task(pool, Function, Increment)); results.push_back(make_task(pool, Function, Increment)); results.push_back(make_task(pool, Function, Increment)); results.push_back(make_task(pool, Function, Increment)); results.push_back(make_task(pool, &TaskClass::MemberFunction, &taskClass, Increment)); results.push_back(make_task(pool, &TaskClass::MemberFunction, &taskClass, Increment)); results.push_back(make_task(pool, &TaskClass::MemberFunction, &taskClass, Increment)); results.push_back(make_task(pool, &TaskClass::MemberFunction, &taskClass, Increment)); results.push_back(make_task(pool, &TaskClass::MemberFunction, &taskClass, Increment)); results.push_back(make_task(pool, lambdaTask, Increment)); results.push_back(make_task(pool, lambdaTask, Increment)); results.push_back(make_task(pool, lambdaTask, Increment)); results.push_back(make_task(pool, lambdaTask, Increment)); results.push_back(make_task(pool, lambdaTask, Increment)); // Wait for all tasks to complete for(auto& res : results) { res.get(); } // Should have run 15 tasks BOOST_CHECK_EQUAL(Counter, Increment * results.size()); } // Test prioritised thread pool handling BOOST_AUTO_TEST_CASE(Prioritised) { // Single threaded pool for reproducable task execution ordering CThreadPool<CPriorityQueueAdaptor> pool { "TestPool", 1 }; // Make sure nothing starts executing until we have queued everything pool.pause(); BOOST_CHECK(pool.paused()); // Each task will add a result to this vector std::vector<std::string> taskResults {}; // Expected final contents std::vector<std::string> expectedResults { "VeryHigh", "High", "Medium", "Unspec", "Low" }; // Some tasks to run std::vector<std::future<void>> results {}; results.push_back(make_task(pool, CTask::Priority::Low, [&taskResults](){ taskResults.push_back("Low"); })); results.push_back(make_task(pool, CTask::Priority::Medium, [&taskResults](){ taskResults.push_back("Medium"); })); results.push_back(make_task(pool, CTask::Priority::High, [&taskResults](){ taskResults.push_back("High"); })); results.push_back(make_task(pool, [&taskResults](){ taskResults.push_back("Unspec"); })); results.push_back(make_task(pool, 10, [&taskResults](){ taskResults.push_back("VeryHigh"); })); // Wait for all tasks to complete pool.run(); BOOST_CHECK(!pool.paused()); for(auto& res : results) { res.get(); } BOOST_CHECK(taskResults == expectedResults); } BOOST_AUTO_TEST_SUITE_END();
true
dea8d59649abafd9bd6672c7f36c0aa13c250e26
C++
jtrfid/C-Program
/2019/2019上机/备选题目/57 Fibonacci数列 函数与递归 ok/Fibonacii.cpp
GB18030
1,107
3.859375
4
[]
no_license
/***************************************************************** 43 Fibonacci ʱ: 2 ڴ: 10000MB һʽFibonacciж£ F(0)=7 F(1)=11 F(n)=F(n-1)+F(n-2)n>=2 nֵжF(n)Ƿܱ3 ˵ ݣݵһΪt(t<100)ʾΪtУÿһn0<=n<=100 ˵ ÿݣF(n)ܱ3yesno 3 1 2 3 no yes no ʾϢ **********************************************************************/ #include <stdio.h> #include <math.h> int Fibonacci(int n) { int f; if(n == 0) f = 7; else if(n == 1) f = 11; else f = Fibonacci(n-1) + Fibonacci(n-2); return f; } int main() { int i,t,n[100]; scanf("%d",&t); for(i = 0; i < t; i++) scanf("%d",&n[i]); for(i = 0; i < t; i++) { if(Fibonacci(n[i]) % 3 == 0) printf("yes\n"); else printf("no\n"); } return 0; }
true
950feb75057b3db637f58603278ca0bf9bab4899
C++
DavutK/SEP2
/Milestone 3/Se2PM2/Hal.cpp
UTF-8
3,404
2.546875
3
[]
no_license
/* * Ampeln.cpp * * Created on: 15.04.2013 * Author: Davut */ #include "Hal.h" Mutex* Hal::halMutex = new Mutex(); Hal* Hal::instance = NULL; Hal::Hal() { halMutex->lock(); // Initialisierung der Digitalen IO Karte out8(DIO_BASE + DIO_OFFS_CTRL, 0x8A); out8(DIO_BASE + DIO_OFFS_A, 0x00); out8(DIO_BASE + DIO_OFFS_B, 0x00); out8(DIO_BASE + DIO_OFFS_C, 0x00); halMutex->unlock(); } Hal::~Hal() { halMutex->unlock(); out8(DIO_BASE + DIO_OFFS_A, 0x00); out8(DIO_BASE + DIO_OFFS_B, 0x00); out8(DIO_BASE + DIO_OFFS_C, 0x00); instance = NULL; halMutex->~Mutex(); } //Hal* Hal::getInstance() { // // Zugriffsrechte fuer den Zugriff auf die HW holen // if (-1 == ThreadCtl(_NTO_TCTL_IO, 0)) { // perror("ThreadCtl access failed\n"); // return NULL; // } // // if (instance == NULL) { // instance = new Hal(); // } // return instance; // //} Hal* Hal::getInstance() { // Zugriffsrechte fuer den Zugriff auf die HW holen if (-1 == ThreadCtl(_NTO_TCTL_IO, 0)) { perror("ThreadCtl access failed\n"); return NULL; } if (instance == NULL) { halMutex->lock(); if (instance == NULL) instance = new Hal(); halMutex->unlock(); } return instance; } void Hal::ampelRotAus() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val & ~BIT_7); halMutex->unlock(); } void Hal::ampelRotAn() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val | BIT_7); halMutex->unlock(); } void Hal::ampelGelbAus() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val & ~BIT_6); halMutex->unlock(); } void Hal::ampelGelbAn() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val | BIT_6); halMutex->unlock(); } void Hal::ampelGruenAus() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val & ~BIT_5); halMutex->unlock(); } void Hal::ampelGruenAn() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val | BIT_5); halMutex->unlock(); } //Laufband neu void Hal::laufbandVor() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val & ~BIT_1); val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val & ~BIT_3); val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val | BIT_0); halMutex->unlock(); } void Hal::laufbandZurueck() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val & ~BIT_3); val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val & ~BIT_0); val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val | BIT_1); halMutex->unlock(); } void Hal::laufbandStop() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val & ~BIT_0); val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val & ~BIT_1); val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val | BIT_3); halMutex->unlock(); } void Hal::weicheAuf() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val | BIT_4); halMutex->unlock(); } void Hal::weicheZu() { halMutex->lock(); uint8_t val = in8(DIO_BASE + DIO_OFFS_A); out8(DIO_BASE + DIO_OFFS_A, val & ~BIT_4); halMutex->unlock(); }
true
f3c7566b7596af3b6145b75fdf794e4b77fe5aa4
C++
1816013/guratan
/myGame/Classes/obj/Player.h
SHIFT_JIS
2,163
2.640625
3
[]
no_license
#pragma once #include"Obj.h" enum class Ability { PowerUp, SpeedUp, Heal, ChargeLevel, ChargeSpeed, MAX }; enum class PlayerAct { IDLE, MOVE, ATTACK, CHARGE, MAX }; enum class ChargeType { SHOT, TWISTER, FLONTAL, MAX }; using AbilityPair = std::pair<std::string, Ability>; //O, AreB class Player : public Obj { public: // ֐ static cocos2d::Sprite* createPlayer(); Player(); ~Player(); void addExp(const int exp); float GetMovePower(); float GetPowerRate(); void SetAbility(AbilityPair ability); void SetStrong(bool flag); bool IsCharged(); bool GetStrong(); void SetChargeType(ChargeType chargeType); void SetPlayerAct(PlayerAct playerAct); ChargeType GetChargeType(); std::vector<AbilityPair> GetUnacquiredAbility(); bool ColisionObj(Obj& hitObj, cocos2d::Scene& scene)override; std::unique_ptr<OPRT_state>_inputState; CREATE_FUNC(Player); private: bool init()override; // @ײč쐬 void update(float delta)override; // ڲ԰̈ړƱҰݏ void attack(float delta, cocos2d::Scene& scene); void LevelUp(void); cocos2d::Animation* SetAnim(DIR dir); // ɉҰ݂̐ݒ // ϐ cocos2d::DrawNode* line; PlayerAct _playerAct; float _actTime; int _hpMax; int _expMax; // ȏɂȂƃxAbv int _level; // x float _charge; // `[WĂ鎞 float _chargeMax; // `[W܂鎞 int _chargeLevel; // `[W̋ int _chargeLevelMax; // `[W̍ő勭 float _powerRate; // U̓AreBp float _movePower; // ړxAreB␳p ChargeType _chargeType; cocos2d::Sprite* texSprite; // `pXvCg摜傫boundingboxł̓蔻肪łȂߕKv cocos2d::Animation* _oldAnim; // eLXg cocos2d::Label* lvText; cocos2d::Label* chargeText; std::vector<AbilityPair>_ability; // 擾ĂAreB std::vector<AbilityPair>_unacquiredAbility; // 擾AreB };
true
257b79f96bc17c8c19075ba2c34c4f9551b8527c
C++
HyangRim/Algorithm_Back
/2485.cpp
UTF-8
687
2.53125
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int arr[100001]; int art[100001]; int gcd(int a, int b) { return b ? gcd(b, a%b) : a; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int N; cin >> N; for (int x = 0; x < N; x++) { cin >> arr[x]; } for (int x = 1; x < N; x++) { art[x] = arr[x] - arr[x - 1]; } int tmp; int min = 987654321; for (int x = 1; x < N - 1; x++) { tmp = gcd(art[x - 1], art[x]); if (min > tmp) min = tmp; } int ans = 0; for (int x = 0; x < N; x++) { if (x + 1 == N) break; if (arr[x - 1] - arr[x] != min) { tmp = (arr[x+1] - arr[x]) / min -1; ans += tmp; } } cout << ans; return 0; }
true
3c7f3696fea7325cfcb0a6953291c77809f305e2
C++
mzhg/opengl_study
/ant_vr_sdk/geometry3d.h
UTF-8
1,873
3.453125
3
[]
no_license
#pragma once #include <glm.hpp> namespace jet { namespace util { /** * <code>Plane</code> defines a plane where Normal dot (x,y,z) = Constant. * This provides methods for calculating a "distance" of a point from this * plane. The distance is pseudo due to the fact that it can be negative if the * point is on the non-normal side of the plane. * * @author Mark Powell * @author Joshua Slack */ template<typename Type> struct Plane { enum class Side { POSITIVE, NEGATIVE, NONE }; Plane() : f3Normal(static_cast<Type>(0)), fConstant(static_cast<Type>(0)){} Plane(glm::tvec3<Type, glm::highp> _normal, Type _w) : f3Normal(_normal), fConstant(_w){} static glm::tvec3<Type, glm::highp> getClosestPoint(const glm::tvec3<Type, glm::highp>& point, const Plane<Type>& plane) { Type t = (plane.fConstant - glm::dot(plane.f3Normal, point)) / glm::dot(plane.f3Normal, plane.f3Normal); return plane.f3Normal * t + point; } static glm::tvec3<Type, glm::highp> reflect(const glm::tvec3<Type, glm::highp>& point, const Plane<Type>& plane) { Type d = pseudoDistance(point, plane); return plane.f3Normal * (-d * static_cast<Type>(2.0)) + point; } static Type pseudoDistance(const glm::tvec3<Type, glm::highp>& point, const Plane<Type>& plane) { return glm::dot(plane.f3Normal, point) - plane.fConstant; } static Side whichSide(const glm::tvec3<Type, glm::highp>& point, const Plane<Type>& plane) { Type zero = static_cast<Type>(0); Type dis = pseudoDistance(point); if (dis < zero) { return Side::NEGATIVE; } else if (dis > zero) { return Side::POSITIVE; } else { return Side::NONE; } } glm::tvec3<Type, glm::highp> f3Normal; Type fConstant; }; typedef Plane<float> Planef; typedef Plane<double> Planed; } }
true
e0fe1d18a2c9a084f1038856e94c79c05bebb3dc
C++
rajputsher/CPP_CriticalSkills
/7_MultidimensionalArrays/Arrays/MultidimensionalArrays.cpp
UTF-8
2,281
3.5625
4
[]
no_license
#include<iostream> using namespace std; int mainA1() { double grades[7][6] = {0}; // Danny Grades grades[0][0] = 50, grades[0][1] = 33, grades[0][2] = 40, grades[0][3] = 30; // Joe Grades grades[1][0] = 35, grades[1][1] = 50, grades[1][2] = 40, grades[1][3] = 30; // And so on // Juli Grades grades[6][0] = 35, grades[6][1] = 30, grades[6][2] = 47, grades[6][3] = 16; return 0; } int mainA2() { double grades[7][6] = { 0 }; // Danny Grades grades[0][0] = 50, grades[0][1] = 33, grades[0][2] = 40, grades[0][3] = 30; // Joe Grades grades[1][0] = 35, grades[1][1] = 50, grades[1][2] = 40, grades[1][3] = 30; // Juli Grades grades[6][0] = 35, grades[6][1] = 30, grades[6][2] = 47, grades[6][3] = 16; for (int row = 0; row < 7; ++row) { cout << "Row " << row << ": "; for (int col = 0; col < 4; ++col) { cout << grades[row][col] << " "; } cout << "\n"; } return 0; } int mainA3() { double grades[7][6] = { 0 }; for (int row = 0; row < 7; ++row) for (int col = 0; col < 4; ++col) cin >> grades[row][col]; for (int row = 0; row < 7; ++row) { cout << "Row " << row << ": "; for (int col = 0; col < 4; ++col) { cout << grades[row][col] << " "; } cout << "\n"; } return 0; } int mainA4() { double grades[7][6] = { 0 }; for (int row = 0; row < 7; ++row) for (int col = 0; col < 4; ++col) cin >> grades[row][col]; for (int row = 0; row < 7; ++row) { cout << "Row " << row << ": "; for (int col = 0; col < 4; ++col) { cout << grades[row][col] << " "; } cout << "\n"; } return 0; } int mainA5() { double grades[7][6] = { 0 }; for (int row = 0; row < 7; ++row) for (int col = 0; col < 4; ++col) cin >> grades[row][col]; for (int col = 0; col < 4; ++col) { cout << "Col " << col << ": "; for (int row = 0; row < 7; ++row) { cout << grades[row][col] << " "; } cout << "\n"; } return 0; } int mainA6() { double grades[7][6] = { 0 }; for (int row = 0; row < 7; ++row) for (int col = 0; col < 4; ++col) cin >> grades[row][col]; for (int row = 0; row < 7; ++row) { double sum = 0; for (int col = 0; col < 4; ++col) sum += grades[row][col]; double avg = sum / 7.0; cout << "Student # " << row + 1 << " has average grade: " << avg << "\n"; } return 0; }
true
a7223c0f8ee95443359e514ce1eef7d1c70510b8
C++
gusenov/examples-cpp
/crtp/example-5/Overriding.h
UTF-8
334
2.671875
3
[ "MIT" ]
permissive
#ifndef OVERRIDING_H #define OVERRIDING_H #include "Base.h" #include <iostream> struct Overriding: Base<Overriding> { void f() { std::cout << "Special case" << std::endl; } // This method must exists to prevent endless recursion in Base::f void pure() { std::cout << "pure() from Overriding" << std::endl; } }; #endif
true
4f1ce14a2879fceb8388cfbba44adb20a22e431c
C++
nishantprajapati123/Computer-Graphics-Lab
/openGL with freeGLUT/Bresenham.cpp
UTF-8
3,005
2.953125
3
[]
no_license
#if 0 #include <Windows.h> #include <iostream> #include <GL\glew.h> #include <GL\freeglut.h> #include <cmath> #define PI 3.14159265358979324 using namespace std; int x1, y1, x2, y2; void draw_pixel(int x, int y) { glBegin(GL_POINTS); glVertex2i(x, y); glEnd(); } // Drawing (display) routine. void drawScene(void) { int dx, dy, i, e; int incx, incy, inc1, inc2; int x,y; dx = x2-x1; dy = y2-y1; if (dx < 0) dx = -dx; if (dy < 0) dy = -dy; incx = 1; if (x2 < x1) incx = -1; incy = 1; if (y2 < y1) incy = -1; x = x1; y = y1; if (dx > dy) { draw_pixel(x, y); e = 2 * dy-dx; inc1 = 2*(dy-dx); inc2 = 2*dy; for (i=0; i<dx; i++) { if (e >= 0) { y += incy; e += inc1; } else e += inc2; x += incx; draw_pixel(x, y); } } else { draw_pixel(x, y); e = 2*dx-dy; inc1 = 2*(dx-dy); inc2 = 2*dx; for (i=0; i<dy; i++) { if (e >= 0) { x += incx; e += inc1; } else e += inc2; y += incy; draw_pixel(x, y); } } // Flush created objects to the screen, i.e., force rendering. glFlush(); } // Initialization routine. void setup(void) { // Set background (or clearing) color. glClearColor(0.0, 0.0, 0.0, 0.0); } // OpenGL window reshape routine. void resize(int w, int h) { // Set viewport size to be entire OpenGL window. glViewport(0, 0, (GLsizei)w, (GLsizei)h); // Set matrix mode to projection. glMatrixMode(GL_PROJECTION); // Clear current projection matrix to identity. glLoadIdentity(); // Specify the orthographic (or perpendicular) projection, // i.e., define the viewing box. glOrtho(0.0, 400.0, 0.0, 400.0, -1.0, 1.0); // Set matrix mode to modelview. glMatrixMode(GL_MODELVIEW); // Clear current modelview matrix to identity. glLoadIdentity(); } // Keyboard input processing routine. void keyInput(unsigned char key, int x, int y) { switch(key) { // Press escape to exit. case 27: exit(0); break; default: break; } } // Main routine: defines window properties, creates window, // registers callback routines and begins processing. int main(int argc, char **argv) { cout<<"Enter (X1,Y1):"; cin>>x1>>y1; cout<<"\nEnter (X2,Y2):"; cin>>x2>>y2; // Initialize GLUT. glutInit(&argc, argv); // Set display mode as single-buffered and RGB color. glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Set OpenGL window size. glutInitWindowSize(500, 500); // Set position of OpenGL window upper-left corner. glutInitWindowPosition(100, 100); // Create OpenGL window with title. glutCreateWindow("circle.cpp"); // Initialize. setup(); // Register display routine. glutDisplayFunc(drawScene); // Register reshape routine. glutReshapeFunc(resize); // Register keyboard routine. glutKeyboardFunc(keyInput); // Begin processing. glutMainLoop(); return 0; } #endif // 0
true
0623c9975f40653d778f4792674c0a11aa3cdac5
C++
Byeong-Chan/ByeongChan_PS_Note
/C:C++/2055.cpp
UTF-8
590
2.59375
3
[]
no_license
#include <stdio.h> int gcd(int a, int b) { if (a % b == 0) return b; else return gcd(b, a%b); } long long comb3(long long a) { long long tmp = (a*(a - 1)*(a - 2)); return tmp / 6; } int main() { int i, j; int n, m; int x, y; int tmp; long long ans; long long k; long long all; scanf("%d %d", &n, &m); all = (n + 1) * (m + 1); ans = comb3(all) - comb3(n + 1) * (m + 1) - comb3(m + 1) * (n + 1); for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { tmp = gcd(i, j); k = tmp - 1; ans -= (k * (n - i + 1) * (m - j + 1) * 2); } } printf("%lld", ans); return 0; }
true
4e14cc1e4d5bc9bb6d43d753698a89a904073192
C++
SahilMadan/chip8_emu
/system/char_sprite_map.cc
UTF-8
4,147
2.546875
3
[]
no_license
#include "char_sprite_map.h" #include <stdexcept> #include <string> namespace chip8_emu { namespace system { namespace char_sprite_map { void InitCharSpriteInMemory(Memory* memory) { int memory_addr = 0; // Sprite 0 memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xF0); // Sprite 1 memory->WriteByte(memory_addr++, 0x20); memory->WriteByte(memory_addr++, 0x60); memory->WriteByte(memory_addr++, 0x20); memory->WriteByte(memory_addr++, 0x20); memory->WriteByte(memory_addr++, 0x70); // Sprite 2 memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x10); memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x80); memory->WriteByte(memory_addr++, 0xF0); // Sprite 3 memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x10); memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x10); memory->WriteByte(memory_addr++, 0xF0); // Sprite 4 memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x10); memory->WriteByte(memory_addr++, 0x10); // Sprite 5 memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x80); memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x10); memory->WriteByte(memory_addr++, 0xF0); // Sprite 6 memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x80); memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xF0); // Sprite 7 memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x10); memory->WriteByte(memory_addr++, 0x20); memory->WriteByte(memory_addr++, 0x40); memory->WriteByte(memory_addr++, 0x40); // Sprite 8 memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xF0); // Sprite 9 memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x10); memory->WriteByte(memory_addr++, 0xF0); // Sprite A memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0x90); // Sprite B memory->WriteByte(memory_addr++, 0xE0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xE0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xE0); // Sprite C memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xF0); // Sprite D memory->WriteByte(memory_addr++, 0xE0); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0x90); memory->WriteByte(memory_addr++, 0xE0); // Sprite E memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x80); memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x80); memory->WriteByte(memory_addr++, 0xF0); // Sprite F memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x80); memory->WriteByte(memory_addr++, 0xF0); memory->WriteByte(memory_addr++, 0x80); memory->WriteByte(memory_addr++, 0x80); } std::size_t GetCharSpriteAddr(std::uint8_t character) { if (character > 0xF) { throw std::out_of_range("Invalid sprite character: " + std::to_string(character)); } return static_cast<std::size_t>(character) * 5; } } // namespace char_sprite_map } // namespace system } // namespace chip8_emu
true
1c3d68e57f4c1aee38f71b169bddaf2deb065c20
C++
csobaistvan/OpenLensFlare
/LensPlanner/src/GhostSerializer.cpp
UTF-8
8,274
2.734375
3
[]
no_license
#include "GhostSerializer.h" //////////////////////////////////////////////////////////////////////////////// GhostSerializer::GhostSerializer(QIODevice* io, QMap<float, OLEF::GhostList>* ghosts): m_ioDevice(io), m_ghosts(ghosts) {} //////////////////////////////////////////////////////////////////////////////// void GhostSerializer::serializeGhost(QXmlStreamWriter& xml, const OLEF::Ghost& ghost) { // Serialize the interfaces xml.writeStartElement("interfaces"); //for (auto interface: ghost) for (auto it = ghost.begin(); it != ghost.end(); ++it) { xml.writeTextElement("interface", QString::number(*it)); } xml.writeEndElement(); // Serialize the pupil bounds xml.writeStartElement("pupilBounds"); xml.writeTextElement("x", QString::number(ghost.getPupilBounds()[0].x)); xml.writeTextElement("y", QString::number(ghost.getPupilBounds()[0].y)); xml.writeTextElement("w", QString::number(ghost.getPupilBounds()[1].x)); xml.writeTextElement("h", QString::number(ghost.getPupilBounds()[1].y)); xml.writeEndElement(); // Serialize the sensor bounds xml.writeStartElement("sensorBounds"); xml.writeTextElement("x", QString::number(ghost.getSensorBounds()[0].x)); xml.writeTextElement("y", QString::number(ghost.getSensorBounds()[0].y)); xml.writeTextElement("w", QString::number(ghost.getSensorBounds()[1].x)); xml.writeTextElement("h", QString::number(ghost.getSensorBounds()[1].y)); xml.writeEndElement(); // Serialize the rest of the attributes xml.writeTextElement("avgIntensity", QString::number(ghost.getAverageIntensity())); xml.writeTextElement("minChannels", QString::number(ghost.getMinimumChannels())); xml.writeTextElement("optimalChannels", QString::number(ghost.getOptimalChannels())); xml.writeTextElement("minRays", QString::number(ghost.getMinimumRays())); xml.writeTextElement("optimalRays", QString::number(ghost.getOptimalRays())); } //////////////////////////////////////////////////////////////////////////////// void GhostSerializer::serializeGhostList(QXmlStreamWriter& xml, const OLEF::GhostList& ghosts) { xml.writeStartElement("ghosts"); for (const auto& ghost: ghosts) { xml.writeStartElement("ghost"); serializeGhost(xml, ghost); xml.writeEndElement(); } xml.writeEndElement(); } //////////////////////////////////////////////////////////////////////////////// bool GhostSerializer::serialize() { // Create the xml stream. QXmlStreamWriter xml; xml.setDevice(m_ioDevice); xml.setAutoFormatting(true); xml.writeStartDocument(); xml.writeStartElement("ghostList"); for (auto it = m_ghosts->begin(); it != m_ghosts->end(); ++it) { xml.writeStartElement("list"); xml.writeTextElement("angle", QString::number(it.key())); serializeGhostList(xml, it.value()); xml.writeEndElement(); } xml.writeEndElement(); xml.writeEndDocument(); return true; } //////////////////////////////////////////////////////////////////////////////// void GhostSerializer::deserializeGhost(QXmlStreamReader& xml, OLEF::Ghost& ghost) { if (xml.name() != "ghost") { xml.raiseError("Not a valid ghost list file."); return; } while (xml.readNextStartElement()) { if (xml.name() == "interfaces") { int ifaceId = 0; while (xml.readNextStartElement()) { if (xml.name() == "interface") { ghost[ifaceId++] = xml.readElementText().toInt(); } else { xml.raiseError("Not a valid ghost list file."); return; } } ghost.setLength(ifaceId); } else if (xml.name() == "pupilBounds") { OLEF::Ghost::BoundingRect bounds; while (xml.readNextStartElement()) { if (xml.name() == "x") { bounds[0].x = xml.readElementText().toDouble(); } else if (xml.name() == "y") { bounds[0].y = xml.readElementText().toDouble(); } else if (xml.name() == "w") { bounds[1].x = xml.readElementText().toDouble(); } else if (xml.name() == "h") { bounds[1].y = xml.readElementText().toDouble(); } else { xml.raiseError("Not a valid ghost list file."); return; } } ghost.setPupilBounds(bounds); } else if (xml.name() == "sensorBounds") { OLEF::Ghost::BoundingRect bounds; while (xml.readNextStartElement()) { if (xml.name() == "x") { bounds[0].x = xml.readElementText().toDouble(); } else if (xml.name() == "y") { bounds[0].y = xml.readElementText().toDouble(); } else if (xml.name() == "w") { bounds[1].x = xml.readElementText().toDouble(); } else if (xml.name() == "h") { bounds[1].y = xml.readElementText().toDouble(); } else { xml.raiseError("Not a valid ghost list file."); return; } } ghost.setSensorBounds(bounds); } else if (xml.name() == "avgIntensity") { ghost.setAverageIntensity(xml.readElementText().toDouble()); } else if (xml.name() == "minChannels") { ghost.setMinimumChannels(xml.readElementText().toDouble()); } else if (xml.name() == "optimalChannels") { ghost.setOptimalChannels(xml.readElementText().toDouble()); } else if (xml.name() == "minRays") { ghost.setMinimumRays(xml.readElementText().toDouble()); } else if (xml.name() == "optimalRays") { ghost.setOptimalRays(xml.readElementText().toDouble()); } else { xml.raiseError("Not a valid ghost list file."); return; } } } //////////////////////////////////////////////////////////////////////////////// void GhostSerializer::deserializeGhostList(QXmlStreamReader& xml, float& angle, OLEF::GhostList& ghosts) { if (xml.name() != "list") { xml.raiseError("Not a valid ghost list file."); return; } while (xml.readNextStartElement()) { if (xml.name() == "angle") { angle = xml.readElementText().toDouble(); } else if (xml.name() == "ghosts") { while (xml.readNextStartElement()) { OLEF::Ghost ghost; deserializeGhost(xml, ghost); ghosts.push_back(ghost); } } else { xml.raiseError("Not a valid ghost list file."); return; } } } //////////////////////////////////////////////////////////////////////////////// bool GhostSerializer::deserialize() { // Resulting optical system. QMap<float, OLEF::GhostList> result; // Create the xml stream. QXmlStreamReader xml; xml.setDevice(m_ioDevice); // Process the elements if (!xml.readNextStartElement() || xml.name() != "ghostList") { xml.raiseError("Not a valid ghost list file."); } while (xml.readNextStartElement()) { OLEF::GhostList list; float angle; deserializeGhostList(xml, angle, list); result[angle] = list; } // Make sure it was successfuly read. if (xml.error()) { return false; } // Save the results *m_ghosts = result; return true; }
true
81598e7a80b5bae046e671a776c9dd9a94fd160b
C++
eikofee/projetALcpp
/projetALcpp/src/Maths/Color.cpp
UTF-8
160
2.578125
3
[]
no_license
#include <Maths/Color.hpp> Color::Color(short red, short green, short blue, short alpha) { r = red; g = green; b = blue; a = alpha; } Color::~Color() { }
true
895391a19fd6d5d77ef6cf28e50a6b534caa51be
C++
LuisSilva96/proximity_detector
/Qt Graphics/player.cpp
UTF-8
7,369
2.6875
3
[]
no_license
# include "player.h" Player::Player() { player.load(":/simulation/sprites/circulito.png"); sensor[0][0].load(":/simulation/sprites/UP3.png"); sensor[0][1].load(":/simulation/sprites/UP2.png"); sensor[0][2].load(":/simulation/sprites/UP.png"); sensor[1][0].load(":/simulation/sprites/DOWN3.png"); sensor[1][1].load(":/simulation/sprites/DOWN2.png"); sensor[1][2].load(":/simulation/sprites/DOWN.png"); sensor[2][0].load(":/simulation/sprites/RIGHT3.png"); sensor[2][1].load(":/simulation/sprites/RIGHT2.png"); sensor[2][2].load(":/simulation/sprites/RIGHT.png"); sensor[3][0].load(":/simulation/sprites/LEFT3.png"); sensor[3][1].load(":/simulation/sprites/LEFT2.png"); sensor[3][2].load(":/simulation/sprites/LEFT.png"); position.setX(20); position.setY(20); player_rect = new QRect(20,20, player.width(), player.height()); } Player::~Player() { //empty } void Player::update_rect() { QRect * new_rect = new QRect(position.x(),position.y(),player_rect->width(), player_rect->height()); player_rect = new_rect; } void Player::proximity(list<Object> & objects) { QVector2D tmp, tmp1; bool aux_n = false, aux_s = false, aux_e = false, aux_o = false; north = 2000; south = 2000; east = 2000; west = 2000; float temporal; for (auto object : objects) { for(int i = object.get_x(); i <= object.get_x() + object.width(); i++) { if(i >= position.x() && i <= position.x() + player_rect->width() && position.y() >= object.get_y() ) { tmp.setX(position.x()); tmp.setY(position.y()); tmp1.setX(position.x()); tmp1.setY(object.get_y() + object.height()); temporal = tmp.distanceToPoint(tmp1); if(temporal < north) { north = temporal; aux_n = true; } } else if(i >= position.x() && i <= position.x() + player_rect->width() && position.y() <= object.get_y()) { tmp.setX(position.x()); tmp.setY(position.y() + player_rect->height()); tmp1.setX(position.x()); tmp1.setY(object.get_y()); temporal = tmp.distanceToPoint(tmp1); if(temporal < south) { south = temporal; aux_s = true; } } } if(aux_n == false) north = 2000; if(aux_s == false) south = 2000; for(int i = object.get_y(); i <= object.get_y() + object.height(); i++) { if(i >= position.y() && i <= position.y() + player_rect->height() && position.x() <= object.get_x()) { tmp.setX(position.x()+ player_rect->width()); tmp.setY(position.y()); tmp1.setX(object.get_x()); tmp1.setY(position.y()); temporal = tmp.distanceToPoint(tmp1); if(temporal < east) { east = temporal; aux_e = true; } } if(i >= position.y() && i <= position.y() + player_rect->height() && position.x() >= object.get_x()) { tmp.setX(position.x()); tmp.setY(position.y()); tmp1.setX(object.get_x() + object.width()); tmp1.setY(position.y()); temporal = tmp.distanceToPoint(tmp1); if(temporal < west) { west = temporal; aux_o = true; } } } if(aux_e == false) east = 2000; if(aux_o == false) west = 2000; } /* std::cout << "North: " << north << std::endl; std::cout << "South: " << south << std::endl; std::cout << "East: " << east << std::endl; std::cout << "West: " << west << std::endl; */ } QPixmap Player::proximity_sprite() { int i, j = 3; float min = 2000; if(north < south && north < east && north < west) { min = north; i = 0; } else if(south < north && south < east && south < west) { min = south; i = 1; } else if(east < north && east < south && east < west) { min = east; i = 2; } else if(west < north && west < south && west < east) { min = west; i = 3; } if(min <= 20) j = 2; else if (min > 20 && min < 80) j = 1; else if(min >= 80 && min < 140) j = 0; if(j == 3) return player; return sensor[i][j]; } void Player::draw(QPainter & painter) { painter.drawPixmap(position.x(), position.y(), player); painter.drawPixmap(position.x(), position.y(), proximity_sprite()); } QRect Player::get_rect() { return *player_rect; } bool Player::colliding_player(list<Object> & objects, int && i, int && j) { bool flag = false; QRect * look_up = new QRect(player_rect->x()+i, player_rect->y()+j, player_rect->height(), player_rect->width()); for (auto object : objects) { QRect tmp = object.get_rect(); flag = tmp.intersects(*look_up); if(flag) break; } if(look_up->x() < 0 || look_up->x() > 920 || look_up->y() < 0 || look_up->y() > 820) flag = true; return flag; } void Player::move(QKeyEvent * evt, list<Object> & objects) { if(evt->key() == Qt::Key_Up or evt->key() == Qt::Key_Down or evt->key() == Qt::Key_Left or evt->key() == Qt::Key_Right) { keys_pressed.insert(evt->key()); } if (keys_pressed.size() == 1) { switch (evt->key()) { case Qt::Key_Up: { if(not(colliding_player(objects, 0, -8))) { position.setY(position.y() - SPEED); } } break; case Qt::Key_Down: { if(not(colliding_player(objects, 0, 8))) { position.setY(position.y() + SPEED); } } break; case Qt::Key_Right: { if(not(colliding_player(objects, 8, 0))) { position.setX(position.x() + SPEED); } } break; case Qt::Key_Left: { if(not(colliding_player(objects, -8, 0))) { position.setX(position.x() - SPEED); } } break; } } if (keys_pressed.size() > 1) { if (keys_pressed.contains(Qt::Key_Up) and keys_pressed.contains(Qt::Key_Right)) { if(not(colliding_player(objects, 8, -8))) { position.setY(position.y() - SPEED); position.setX(position.x() + SPEED); update_rect(); } } if (keys_pressed.contains(Qt::Key_Up) and keys_pressed.contains(Qt::Key_Left)) { if(not(colliding_player(objects, -8, -8))) { position.setY(position.y() - SPEED); position.setX(position.x() - SPEED); update_rect(); } } if (keys_pressed.contains(Qt::Key_Down) and keys_pressed.contains(Qt::Key_Right)) { if(not(colliding_player(objects, 8, 8))) { position.setY(position.y() + SPEED); position.setX(position.x() + SPEED); update_rect(); } } if (keys_pressed.contains(Qt::Key_Down) and keys_pressed.contains(Qt::Key_Left)) { if(not(colliding_player(objects, -8, 8))) { position.setY(position.y() + SPEED); position.setX(position.x() - SPEED); update_rect(); } } } update_rect(); proximity(objects); } int Player::get_x() { return position.x(); } int Player::get_y() { return position.y(); } void Player::set_x(int && x) { position.setX(x); } void Player::set_y(int && y) { position.setY(y); } void Player::release_key(QKeyEvent *evt) { keys_pressed.remove(evt->key()); }
true
34bed902df2d088771fc79c45cb3723ded62bdd0
C++
ak672676/BinaryTree-Graph-Implementation
/BST.cpp
UTF-8
2,564
3.5
4
[]
no_license
#include<iostream> #include<queue> using namespace std; struct node{ int data; node *l,*r; node(int data){ this->data=data; l=NULL; r=NULL; } }; node *root; static int i=0; node* insert(node *p,int x){ node *q=p; if(p==NULL){ node *new1=new node(x); new1->data=x; new1->l=NULL; new1->r=NULL; p=new1; //cout<<"\nADDED"<<x<<endl; return p; } else{ if(q->data>=x) q->l=insert(q->l,x); else q->r=insert(q->r,x); } return q; } void inOrderDisplay(node *p){ node *q=p; if(q==NULL) return ; else{ inOrderDisplay(q->l); cout<<q->data<<" "; inOrderDisplay(q->r); } } void preOrderDisplay(node *p){ node *q=p; if(q==NULL) return ; else{ cout<<q->data<<" "; preOrderDisplay(q->l); preOrderDisplay(q->r); } } void postOrderDisplay(node *p){ node *q=p; if(q==NULL) return ; else{ postOrderDisplay(q->l); postOrderDisplay(q->r); cout<<q->data<<" "; } } int search(node *p,int x) { node *q=p; if(q==NULL) return -1; else { if(q->data==x) return 1; else if(q->data>x) search(q->l,x); else search(q->r,x); } } void mirrorImageConversion(node *p){ node *q=p; if(q==NULL) return; else{ mirrorImageConversion(q->l); mirrorImageConversion(q->r); node* temp; temp=q->l; q->l=q->r; q->r=temp; } } void levelOrderDisplay(node *p){ if(p==NULL) return; else{ queue<node*> q; q.push(p); while(!q.empty()){ int s=q.size(); while(s>0){ node *t=q.front(); cout<<t->data<<" "; q.pop(); if(t->l!=NULL){ q.push(t->l); } if(t->r!=NULL){ q.push(t->r); } s--; } } cout<<endl; } } int main() { root=NULL; node *w; root=insert(root,6); root=insert(root,4); root=insert(root,2); root=insert(root,15); root=insert(root,75); root=insert(root,55); root=insert(root,25); root=insert(root,175); root=insert(root,50); root=insert(root,52); root=insert(root,170); //root=insert(root,54); root=insert(root,5); cout<<"\nINORDER\n"; inOrderDisplay(root); cout<<"\nPREORDER\n"; preOrderDisplay(root); cout<<"\nPOSTORDER\n"; postOrderDisplay(root); //MIRRORIMAGE CONVERSION //mirrorImageConversion(root); cout<<"\nLEVEL ORDER TRAVERSAL\n"; levelOrderDisplay(root); return 0; }
true
bf2edd6308364b1bdf8243669dd9dbac8f96b34d
C++
Miserlou/RJModules
/src/DelayA.h
UTF-8
6,727
2.578125
3
[ "MIT" ]
permissive
#ifndef STK_DELAYA_H #define STK_DELAYA_H #include "Filter.h" namespace stk { /***************************************************/ /*! \class DelayA \brief STK allpass interpolating delay line class. This class implements a fractional-length digital delay-line using a first-order allpass filter. If the delay and maximum length are not specified during instantiation, a fixed maximum length of 4095 and a delay of 0.5 is set. An allpass filter has unity magnitude gain but variable phase delay properties, making it useful in achieving fractional delays without affecting a signal's frequency magnitude response. In order to achieve a maximally flat phase delay response, the minimum delay possible in this implementation is limited to a value of 0.5. by Perry R. Cook and Gary P. Scavone, 1995--2019. */ /***************************************************/ class DelayA : public Filter { public: //! Default constructor creates a delay-line with maximum length of 4095 samples and delay = 0.5. /*! An StkError will be thrown if the delay parameter is less than zero, the maximum delay parameter is less than one, or the delay parameter is greater than the maxDelay value. */ DelayA( StkFloat delay = 0.5, unsigned long maxDelay = 4095 ); //! Class destructor. ~DelayA(); //! Clears all internal states of the delay line. void clear( void ); //! Get the maximum delay-line length. unsigned long getMaximumDelay( void ) { return inputs_.size() - 1; }; //! Set the maximum delay-line length. /*! This method should generally only be used during initial setup of the delay line. If it is used between calls to the tick() function, without a call to clear(), a signal discontinuity will likely occur. If the current maximum length is greater than the new length, no memory allocation change is made. */ void setMaximumDelay( unsigned long delay ); //! Set the delay-line length /*! The valid range for \e delay is from 0.5 to the maximum delay-line length. */ void setDelay( StkFloat delay ); //! Return the current delay-line length. StkFloat getDelay( void ) const { return delay_; }; //! Return the value at \e tapDelay samples from the delay-line input. /*! The tap point is determined modulo the delay-line length and is relative to the last input value (i.e., a tapDelay of zero returns the last input value). */ StkFloat tapOut( unsigned long tapDelay ); //! Set the \e value at \e tapDelay samples from the delay-line input. void tapIn( StkFloat value, unsigned long tapDelay ); //! Return the last computed output value. StkFloat lastOut( void ) const { return lastFrame_[0]; }; //! Return the value which will be output by the next call to tick(). /*! This method is valid only for delay settings greater than zero! */ StkFloat nextOut( void ); //! Input one sample to the filter and return one output. StkFloat tick( StkFloat input ); //! Take a channel of the StkFrames object as inputs to the filter and replace with corresponding outputs. /*! The StkFrames argument reference is returned. The \c channel argument must be less than the number of channels in the StkFrames argument (the first channel is specified by 0). However, range checking is only performed if _STK_DEBUG_ is defined during compilation, in which case an out-of-range value will trigger an StkError exception. */ StkFrames& tick( StkFrames& frames, unsigned int channel = 0 ); //! Take a channel of the \c iFrames object as inputs to the filter and write outputs to the \c oFrames object. /*! The \c iFrames object reference is returned. Each channel argument must be less than the number of channels in the corresponding StkFrames argument (the first channel is specified by 0). However, range checking is only performed if _STK_DEBUG_ is defined during compilation, in which case an out-of-range value will trigger an StkError exception. */ StkFrames& tick( StkFrames& iFrames, StkFrames &oFrames, unsigned int iChannel = 0, unsigned int oChannel = 0 ); protected: unsigned long inPoint_; unsigned long outPoint_; StkFloat delay_; StkFloat alpha_; StkFloat coeff_; StkFloat apInput_; StkFloat nextOutput_; bool doNextOut_; }; inline StkFloat DelayA :: nextOut( void ) { if ( doNextOut_ ) { // Do allpass interpolation delay. nextOutput_ = -coeff_ * lastFrame_[0]; nextOutput_ += apInput_ + ( coeff_ * inputs_[outPoint_] ); doNextOut_ = false; } return nextOutput_; } inline StkFloat DelayA :: tick( StkFloat input ) { inputs_[inPoint_++] = input * gain_; // Increment input pointer modulo length. if ( inPoint_ == inputs_.size() ) inPoint_ = 0; lastFrame_[0] = nextOut(); doNextOut_ = true; // Save the allpass input and increment modulo length. apInput_ = inputs_[outPoint_++]; if ( outPoint_ == inputs_.size() ) outPoint_ = 0; return lastFrame_[0]; } inline StkFrames& DelayA :: tick( StkFrames& frames, unsigned int channel ) { #if defined(_STK_DEBUG_) if ( channel >= frames.channels() ) { oStream_ << "DelayA::tick(): channel and StkFrames arguments are incompatible!"; handleError( StkError::FUNCTION_ARGUMENT ); } #endif StkFloat *samples = &frames[channel]; unsigned int hop = frames.channels(); for ( unsigned int i=0; i<frames.frames(); i++, samples += hop ) { inputs_[inPoint_++] = *samples * gain_; if ( inPoint_ == inputs_.size() ) inPoint_ = 0; *samples = nextOut(); lastFrame_[0] = *samples; doNextOut_ = true; apInput_ = inputs_[outPoint_++]; if ( outPoint_ == inputs_.size() ) outPoint_ = 0; } return frames; } inline StkFrames& DelayA :: tick( StkFrames& iFrames, StkFrames& oFrames, unsigned int iChannel, unsigned int oChannel ) { #if defined(_STK_DEBUG_) if ( iChannel >= iFrames.channels() || oChannel >= oFrames.channels() ) { oStream_ << "DelayA::tick(): channel and StkFrames arguments are incompatible!"; handleError( StkError::FUNCTION_ARGUMENT ); } #endif StkFloat *iSamples = &iFrames[iChannel]; StkFloat *oSamples = &oFrames[oChannel]; unsigned int iHop = iFrames.channels(), oHop = oFrames.channels(); for ( unsigned int i=0; i<iFrames.frames(); i++, iSamples += iHop, oSamples += oHop ) { inputs_[inPoint_++] = *iSamples * gain_; if ( inPoint_ == inputs_.size() ) inPoint_ = 0; *oSamples = nextOut(); lastFrame_[0] = *oSamples; doNextOut_ = true; apInput_ = inputs_[outPoint_++]; if ( outPoint_ == inputs_.size() ) outPoint_ = 0; } return iFrames; } } // stk namespace #endif
true
141eb18e0b87626c81a8632e045cc79ab73ac42a
C++
trungvdhp/master-ntou
/Test/13/330.cpp
UTF-8
418
2.5625
3
[]
no_license
#include<stdio.h> #include<string.h> char check[256]; int main() { char a[256]; char b[256]; gets(a); gets(b); int n=strlen(a); int m=strlen(b); if(n!=m) printf("no"); else { for(int i=0;i<n;i++) { check[a[i]]++; check[b[i]]++; } for(int i=0;i<n;i++) { if(check[a[i]]==1) { printf("no"); return 0; } } printf("yes"); } return 0; }
true
39c25dc672bafa6b33e08117c7b0d18005690afb
C++
wangruici/pat_doing
/pat_a1052/pat_a1052_0.cpp
UTF-8
1,065
3.140625
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> using std::sort; const int maxn=100010; struct Node { int address; int data; int next; bool flag; }node[maxn]; bool cmp(Node a,Node b){ if(a.flag==false||b.flag==false) return a.flag>b.flag; else{ return a.data<b.data; } } int main(){ int begin_address,count; for(int i=0;i<maxn;++i){ node[i].flag=false; } scanf("%d %d",&count,&begin_address); int address; for(int i=0;i<count;++i){ scanf("%d",&address); scanf("%d %d",&node[address].data,&node[address].next); node[address].address=address; } int effective_count=0; int p=begin_address; while(p!=-1){ node[p].flag=true; p=node[p].next; ++effective_count; } if(effective_count==0){ printf("0 -1"); return 0; } sort(node,node+maxn,cmp); printf("%d %05d\n",effective_count,node[0].address); for(int i=0;i<effective_count-1;++i){ printf("%05d %d %05d\n",node[i].address,node[i].data,node[i+1].address); } printf("%05d %d -1\n",node[effective_count-1].address,node[effective_count-1].data); return 0; }
true
a80b8cd373704b04221f294d89b64630f86e7514
C++
il1ya/Algorithm
/1.Grokking_algorithms/Quicksort/LoopSum.cpp
UTF-8
348
3.65625
4
[]
no_license
#include <iostream> #include <vector> // суммирует все числа и возвращает сумму. int sum(std::vector<int> arr){ int total = 0; for(int x = 0; x < arr.size(); x++){ total += arr[x]; } return total; } int main() { std::vector<int> arr {1,2,3,4}; std::cout << sum(arr); return 0; }
true
e5e35b32afaeee771111ad1d2a6fdb715427f4c0
C++
LaureenL/rm_game
/Text_Based_Interactive_Game/Text.cpp
UTF-8
1,495
3.046875
3
[]
no_license
#include <iostream> #include "Text.h" #include <sstream> #include "Globals.h" int wrap (std::string* text) { char c = 0; unsigned int width = 78; unsigned int n = 0; unsigned int i = 0; unsigned int r = 0; unsigned int rStart[M_ROW]; for (i = 0; i < M_ROW; i++) { rStart[i] = 0; } for (i = 0; i < text->length(); ++i) { if ((*text)[i] == '\n') { r++; rStart[r] = i; } else if ((i - rStart[r]) > width) { for (n = i; n > rStart[r]; --n) { c = (*text)[n]; if (isspace(c)) { (*text)[n] = '\n'; r++; rStart[r] = n; } } } } return r + 1; } void screen (const std::string text) { int r = 0; std::string prompt = text; r = wrap(&prompt); std::cout << prompt << std::endl; flush(r); } void flush (int n) { std::cout << std::string(SCR_HEIGHT - n,'\n'); } int getInt (int N) { std::string input = ""; std::string thang = ""; int numb = 0; std::cout << "Please enter a number: "; getline(std::cin, input); std::stringstream myStream(input); if (myStream >> numb) { if (numb > N) { return FAIL; } else if (numb < 1) { return FAIL; } else { return numb; } } else { return FAIL; } }
true
9a60ee37bf1a1c72560e8ffea2d063defb0191a2
C++
ccion/design_pattern
/design_pattern/B_composite_pattern/composite_pattern.h
UTF-8
3,317
3.640625
4
[]
no_license
/***************************************************************************** * 文件名: composite_pattern.h * * @功能描述:组合模式,又叫整体模式,是用于把一组相似的对象当做一个单一的对象,组合模式依据 树形结构来组合,用来表示部分以及整体层次 * * @意图: 将对象组合合成树形结构以表示"部分-整体"的层次结构,组合模式使得用户对单个对象和组合对象 的使用具有一致性 * @主要解决: 它在我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以像处理简单元素一样 来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦 * @何时使用: 1.您想表示对象的部分-整体层次结构(树形结构) 2.您希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象 * @如何解决: 树枝和叶子实现统一接口,树枝内部组合该接口 * @应用实例: 1.算术表达式包括操作数,操作符和另一个操作数,其中,另一个操作符也可以是操作数,操作符 和另一个操作数 * @优点: 1.高层模块调用简单 2.节点自由增加 * @缺点: 在使用组合模式时,其叶子和树枝的声明都是实现类,而不是接口,违反了依赖倒置原则 * * *************************************************************************/ #ifndef COMPOSITE_PATTERN_H #define COMPOSITE_PATTERN_H #include <iostream> #include <string> #include <vector> #include <algorithm> #include <memory> class Component { public: Component(std::string str) { m_str = str; } virtual ~Component(){} virtual void add(Component *param) = 0; virtual void remove(Component *param) = 0; virtual void display() = 0; protected: std::string m_str; }; class Leaf : public Component { public: Leaf(std::string str) : Component(str) {} ~Leaf() {} void add(Component *param) { std::cout << "Leaf cannot add" << std::endl; } void remove(Component *param) { std::cout << "Leaf cannot remove" << std::endl; } void display() { std::cout << m_str << std::endl; } }; class Composite : public Component { public: Composite(std::string str) : Component(str) {} ~Composite() { if(!m_vec.empty()) { m_vec.clear(); } } void add(Component *param) { auto it = find_if(m_vec.begin(), m_vec.end(), [param](std::shared_ptr<Component> ptr){return param == ptr.get();}); if(it == m_vec.end()) { m_vec.push_back(std::shared_ptr<Component>(param)); } } void remove(Component *param) { auto it = find_if(m_vec.begin(), m_vec.end(), [param](std::shared_ptr<Component> ptr){return param == ptr.get();}); if(it == m_vec.end()) { return; } m_vec.erase(it); } void display() { for(auto it = m_vec.cbegin(); it != m_vec.cend(); it++){ (*it)->display(); } } private: std::vector<std::shared_ptr<Component>> m_vec; }; #endif
true
9d3f3e6f5f703c0a949b94e54b1fbf8217dff483
C++
yotam-medini/cj
/2020/ks-round-H/rugby.cc
UTF-8
6,907
2.6875
3
[]
no_license
// CodeJam // Author: Yotam Medini yotam.medini@gmail.com -- #include <algorithm> #include <fstream> #include <iostream> #include <array> #include <string> #include <utility> #include <vector> #include <cstdlib> using namespace std; typedef unsigned u_t; typedef unsigned long ul_t; typedef unsigned long ul_t; typedef long long ll_t; typedef array<ll_t, 2> ll2_t; typedef vector<ll_t> vll_t; typedef vector<ll2_t> vll2_t; static unsigned dbg_flags; class Rugby { public: Rugby(istream& fi); void solve_naive(); void solve(); void print_solution(ostream&) const; private: ll_t move_price(const ll2_t& target) const; ll_t x_solve() const; ll_t y_solve() const; ll_t delta_sum(vll_t& a, ll_t x) const; u_t N; vll2_t players; ll_t solution; ll_t x_solution, y_solution; }; Rugby::Rugby(istream& fi) : solution(0) { fi >> N; players.reserve(N); while (players.size() < N) { ll_t x, y; fi >> x >> y; players.push_back(ll2_t{x, y}); } } void Rugby::solve_naive() { ll2_t xymin = players[0], xymax = players[0]; for (const ll2_t& player: players) { for (u_t i: {0, 1}) { if (xymin[i] > player[i]) { xymin[i] = player[i]; } if (xymax[i] < player[i]) { xymax[i] = player[i]; } } } const ll_t Nm1 = N - 1; solution = N * ((xymax[0] - xymin[0]) + N + (xymax[1] - xymin[1])); ll2_t target, best; for (target[0] = xymin[0] - Nm1; target[0] <= xymax[0] + Nm1; ++target[0]) { for (target[1] = xymin[1]; target[1] <= xymax[1]; ++target[1]) { ll_t price = move_price(target); if (solution > price) { solution = price; best = target; } } } if (dbg_flags & 0x1) { cerr << "best=("<<best[0]<<", "<<best[1]<<")\n"; } } void Rugby::solve() { solution = x_solve() + y_solve(); } void minby(ll_t& v, ll_t x) { if (v > x) { v = x; } } void maxby(ll_t& v, ll_t x) { if (v < x) { v = x; } } ll_t Rugby::x_solve() const { ll_t x_price = 0; vll_t xs; xs.reserve(N); for (const ll2_t& player: players) { xs.push_back(player[0]); } sort(xs.begin(), xs.end()); ll_t low = xs[0]; ll_t high = xs[N - 1]; for (size_t i = 0, ie = xs.size(); i != ie; ++i) { const ll_t curr = xs[i]; minby(low, curr - i); maxby(high, curr + (N - 1) - i); } high -= (N - 1); // we base delta_sum on xs if (high < low) { swap(low, high); } bool found = false; while (low + 2 <= high) { ll_t mid = (low + high)/2; ll_t prices[3]; for (ll_t i = 0; i < 3; ++i) { prices[i] = delta_sum(xs, mid + (i - 1)); } if ((prices[0] >= prices[1]) && (prices[1] <= prices[2])) { low = high = mid; x_price = prices[1]; found = true; } else if ((prices[0] == prices[1]) || (prices[1] == prices[2])) { low = high = mid; x_price = prices[1]; found = true; } else if (prices[0] < prices[1]) { high = mid - 1; } else { low = mid + 1; } } ll_t x_best = low; if (!found) { x_price = delta_sum(xs, low); if (low != high) { ll_t h_price = delta_sum(xs, high); if (x_price > h_price) { x_price = h_price; x_best = high; } } } if (dbg_flags & 0x1) { cerr << "x_price=" <<x_price << ", x_best=" << x_best << '\n'; } return x_price; } ll_t Rugby::delta_sum(vll_t& a, ll_t x) const { ll_t delta = 0; for (size_t i = 0; i < N; ++i) { delta += llabs(x + i - a[i]); } return delta; } ll_t Rugby::y_solve() const { vll_t ys; ys.reserve(N); for (const ll2_t& player: players) { ys.push_back(player[1]); } sort(ys.begin(), ys.end()); ll_t ymed = ys[N / 2]; ll_t y_price = 0; for (size_t i = 0; i < size_t(N / 2); ++i) { y_price += (ymed - ys[i]); } for (size_t i = size_t(N / 2) + 1; i < size_t(N); ++i) { y_price += ys[i] - ymed; } if (dbg_flags & 0x1) { cerr << "y_price="<<y_price << ", ymed=" << ymed << '\n'; } return y_price; } ll_t Rugby::move_price(const ll2_t& target) const { vll2_t splayers(players); sort(splayers.begin(), splayers.end()); ll_t price = 0; for (u_t i = 0; i < N; ++i) { const ll2_t& player = splayers[i]; const ll_t xtarget = target[0] + i; ll_t xdelta = llabs(xtarget - player[0]); ll_t ydelta = llabs(target[1] - player[1]); ll_t delta = xdelta + ydelta; price += delta; } return price; } void Rugby::print_solution(ostream &fo) const { fo << ' ' << solution; } int main(int argc, char ** argv) { const string dash("-"); bool naive = false; bool tellg = false; int rc = 0, ai; for (ai = 1; (rc == 0) && (ai < argc) && (argv[ai][0] == '-') && argv[ai][1] != '\0'; ++ai) { const string opt(argv[ai]); if (opt == string("-naive")) { naive = true; } else if (opt == string("-debug")) { dbg_flags = strtoul(argv[++ai], 0, 0); } else if (opt == string("-tellg")) { tellg = true; } else { cerr << "Bad option: " << opt << "\n"; return 1; } } int ai_in = ai; int ai_out = ai + 1; istream *pfi = (argc <= ai_in || (string(argv[ai_in]) == dash)) ? &cin : new ifstream(argv[ai_in]); ostream *pfo = (argc <= ai_out || (string(argv[ai_out]) == dash)) ? &cout : new ofstream(argv[ai_out]); if ((!pfi) || (!pfo) || pfi->fail() || pfo->fail()) { cerr << "Open file error\n"; exit(1); } string ignore; unsigned n_cases; *pfi >> n_cases; getline(*pfi, ignore); void (Rugby::*psolve)() = (naive ? &Rugby::solve_naive : &Rugby::solve); ostream &fout = *pfo; ul_t fpos_last = pfi->tellg(); for (unsigned ci = 0; ci < n_cases; ci++) { Rugby rugby(*pfi); getline(*pfi, ignore); if (tellg) { ul_t fpos = pfi->tellg(); cerr << "Case (ci+1)="<<(ci+1) << ", tellg=[" << fpos_last << " " << fpos << ") size=" << (fpos - fpos_last) << "\n"; fpos_last = fpos; } (rugby.*psolve)(); fout << "Case #"<< ci+1 << ":"; rugby.print_solution(fout); fout << "\n"; fout.flush(); } if (pfi != &cin) { delete pfi; } if (pfo != &cout) { delete pfo; } return 0; }
true
a60afaf479eebe3be7ca925594272addcd42ec4b
C++
cypress777/dltrace_cyp
/utils/funcmsg.hpp
UTF-8
1,726
2.59375
3
[]
no_license
#ifndef _DLTRACE_FUNCMSG_H_ #define _DLTRACE_FUNCMSG_H_ #include <string> #include <unordered_map> #include "breakpoint.hpp" namespace dltrace { class FuncMsgIndexHash; class FuncMsgIndex { friend class FuncMsgIndexHash; private: unsigned long m_addr; std::string m_funcName; CONSTRUCTOR: FuncMsgIndex() = default; explicit FuncMsgIndex(unsigned long, std::string); public: bool operator==(const FuncMsgIndex&) const; void setAddr(unsigned long); unsigned long getAddr() const; void setFuncName(std::string); std::string getFuncName() const; }; class FuncMsgIndexHash { public: size_t operator()(const FuncMsgIndex&) const; }; class FuncMsg { public: enum class FUNCMSGTYPE { FUNCIN, FUNCOUT, }; private: BreakPointSptr m_pBreakPoint; std::string m_funcName; FUNCMSGTYPE m_type; CONSTRUCTOR: FuncMsg() = default; explicit FuncMsg(const BreakPointSptr&); explicit FuncMsg(const BreakPointSptr&, const std::string&); explicit FuncMsg(const BreakPointSptr&, const std::string&, FUNCMSGTYPE); DESTRUCTOR: public: FuncMsgIndex makeIndex() const; void setBreakPoint(const BreakPointSptr&); BreakPointSptr getBreakPoint() const; void setFuncName(const std::string&); std::string getFuncName() const; void setType(FUNCMSGTYPE); FUNCMSGTYPE getType() const; }; typedef std::unordered_map<FuncMsgIndex ,FuncMsg, FuncMsgIndexHash> FuncMsgMap; typedef std::pair<FuncMsgIndex, FuncMsg> FuncMsgMapPair; } #endif
true
d403a490a13a6792c204bb5d3de5d7a4f635d32b
C++
jpoirier/x-gauges
/Nesis/Common/Geometry/Line2D.h
UTF-8
8,785
3.046875
3
[]
no_license
#pragma once #ifndef __GEOMETRY_LINE2D_H #define __GEOMETRY_LINE2D_H /*************************************************************************** * * * Copyright (C) 2006 by Kanardia d.o.o. [see www.kanardia.eu] * * Writen by: * * Ales Krajnc [ales.krajnc@kanardia.eu] * * * * Status: Open Source * * * * License: GPL - GNU General Public License * * See 'COPYING.html' for more details about the license. * * * ***************************************************************************/ /*! \file Line2D.h \brief Declaration file for the Line2D class. \author Ales Krajnc \date 1.1.2006 - ported from VisualStudio code. */ // -------------------------------------------------------------------------- #include <functional> #include "Point2D.h" #include "MathEx.h" // -------------------------------------------------------------------------- namespace geometry { // -------------------------------------------------------------------------- //! The class implements several useful geometry operations on a line. /*! The line has a direction from point A->B. The A represents the start point, while B represents end point of the line. However, the line is endless. A and B are just useful points on a line. Thus the class is a mixture of line and vector behaviour. It stores start and end point together with line equation: ax + by + c = 0. This class implements the line in the 2D (XY) plain. */ class Line2D { public: //! Intersection flags - use with the #GetIntersection method. enum Intersect { intNone = 0, //!< There is no intersection. intExist = 1, //!< Intersection exists intFirst = 2, //!< Intersection point lies within the first line. intSecond = 4, //!< Intersection point lies within the second line. intBoth = 7 //!< Combination of all: exist, first and second. }; //! Position flags enum Positon { posOnLine = 1, //!< The point lies on the line direction posInside = 2, //!< The point is inside the line (between A and B). posPositive = 4, //!< The point lies on the positive halfspace. posNegative = 8, //!< The point lies on the negative halfspace. posA = 16, //!< The point lies on the point A posB = 32, //!< The point lies on the point B posEnd = 48, //!< Check if the point lies on A or B posInsideEnd = 50, //!< Check if the point is inside, on A or on B. }; public: //! Default constructor Line2D(); //! Constructor from four parameters that represent two points Line2D(qreal dAx, qreal dAy, qreal dBx, qreal dBy); //! Contructor from two points Line2D(const Point2D& ptA, const Point2D& ptB); //! Copy constructor. Line2D(const Line2D& line); public: //! Copies the given object into this. void Copy(const Line2D& C); //! Assignment operator. const Line2D& operator=(const Line2D& C) { Copy(C); return *this; } //! The start point of the line. const Point2D& GetA() const { return m_ptA; } //! The start point of the line. Same as #GetA. const Point2D& GetStart() const { return GetA(); } //! The end point of the line. const Point2D& GetB() const { return m_ptB; } //! The end point of the line. Same as #GetB. const Point2D& GetEnd() const { return GetB(); } //! Sets the new line start (A) and end (B) points. void Set(const Point2D& ptA, const Point2D& ptB); //! Set line equation coefficients directly void Set(qreal dA, qreal dB, qreal dC); //! Sets the new start point. void SetA(const Point2D& ptA); //! Sets the new end point. void SetB(const Point2D& ptB); //! Sets the new start point. Same as #SetA. void SetStart(const Point2D& ptA) { SetA(ptA); } //! Sets the new end point. Same as #SetB. void SetEnd(const Point2D& ptB) { SetB(ptB); } //! For given y coordinate calculates the x coordinate. qreal GetX(qreal y) const { return ((a) ? (-c-b*y)/a : 0.); } //! For given x coordinate calculates the y coordinate. qreal GetY(qreal x) const { return ((b) ? (-c-a*x)/b : 0.); } //! Swaps the start/end points. The line changes direction. void Swap(); //! Returns the line length. qreal GetLength() const; //! Moves the line for given offset (dx,dy). void Move(qreal dx, qreal dy ); //! Moves the line for the given point void Move(const Point2D& d) { Move(d.GetX(), d.GetY()); } //! Moves the line in the current line direction for the dl units. void MoveInDirection (qreal dl); //! Moves the line in the perpendicular direction for the dt units. void Offset (qreal dt); //! Rotates the line for the given angle around the origin. void Rotate(qreal dAlpha); //! Rotates the line for the given angle around given point. void Rotate(const Point2D& ptO, qreal dAlpha); //! Returns the current line angle in radians. qreal GetAngle() const; //! Returns the angle between this line and line b. qreal GetAngle(const Line2D& liB) const; //! Returns the intersection point with the line b. Check the return flags! int GetIntersection(const Line2D& liB, Point2D& ptInt, qreal dTol=1E-12) const; //! Returns true if given line is parallel to this line. bool IsParallel(const Line2D& liB, qreal dTol=1E-12) const; //! Returns the intersection point with a perpendicular trough pt. Point2D GetNearestPoint(const Point2D& pt) const; //! Creates a parallel line which goes trough point t. Line2D CreateParallel(const Point2D& t) const { return Line2D(t.GetX(), t.GetY(), t.GetX()+b, t.GetY()-a); } //! Creates a perpendicular line which goes trough point t. Line2D CreatePerpendicular(const Point2D& p) const; //! Creates a direction (unit length) line. Line2D CreateDirection(qreal dRelS, qreal dRelAlpha) const; //! Calculates the overlap of two lines. Line2D GetOverlap(const Line2D& ln) const; //! Tells where the point p lies. Returns a combination of flags. There is some tolerance. unsigned int GetPosition(const Point2D& p, qreal dTol=1E-12) const; //! Get the line point which is dRelS line lengths away from the start point. Point2D At(qreal dRelS) const; //! Returns number of line lengths needed to reach point p from the start point. qreal GetScalar(const Point2D& p, qreal dTol=1E-12) const; //! Returns true if line is a nondegenerate line. bool IsValid() const { return a || b; } //! Serializes the line to the CArchive stream. void Serialize(QDataStream& ar); //! Normalizes the line. The start point remains at point A, but // the B is recalculated at such way, that length will be 1. void Normalize(); //! Operator == The lines are equal if the points are equal bool operator==(const Line2D& line) { return GetA()==line.GetA() && GetB()==line.GetB(); } protected: //! Calculates the internal variables according to the start and end point. void Setup(); protected: //! Start point of the line. Point2D m_ptA; //! End point of the line. Point2D m_ptB; private: // Line coefficients (we violate naming rules here due to historical reasons. //! Coefficient a of the ax + by + c = 0 line equation. qreal a; //! Coefficient b of the ax + by + c = 0 line equation. qreal b; //! Coefficient c of the ax + by + c = 0 line equation. qreal c; }; // ----------------------------------------------------------------------------- //! Outputs the Line2D object to the out stream. inline std::ostream& operator<<(std::ostream& out, const Line2D& li) { out << "A" << li.GetA() << "-->B" << li.GetB() << ": L = " << li.GetLength() << " alpha = " << common::Deg(li.GetAngle()); return out; } // ----------------------------------------------------------------------------- //! Special binary_function that sorts points on the line. class Point2DSortLineLess : std::binary_function<Point2D, Point2D, bool> { public: Point2DSortLineLess(const Line2D& ln) { m_line = ln; } result_type operator() (first_argument_type a, second_argument_type b); private: Line2D m_line; }; // ----------------------------------------------------------------------------- } // namespace geometry #endif // __GEOMETRY_LINE2D_H
true
e80718d0e529c93e3af39af58f80f89fd7da40cc
C++
claq2/adventofcode2018
/AdventOfCode2018/MsUnitTest/Day07Tests.cpp
UTF-8
1,564
2.71875
3
[]
no_license
#include "stdafx.h" #include "CppUnitTest.h" #include "../AdventOfCode2018Lib/Day07/Day07.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace std; namespace MsUnitTest { TEST_CLASS(Day07Tests) { public: TEST_METHOD(ReadInput) { Day07 day7; vector<string> coords(day7.ReadInput()); Assert::AreEqual(size_t(101), coords.size()); } TEST_METHOD(Part1) { Day07 day7; string actual; vector<string> input({ "Step C must be finished before step A can begin.", "Step C must be finished before step F can begin.", "Step A must be finished before step B can begin.", "Step A must be finished before step D can begin.", "Step B must be finished before step E can begin.", "Step D must be finished before step E can begin.", "Step F must be finished before step E can begin.", }); string expected("CABDFE"); actual = day7.Part1(input); Assert::AreEqual(expected, actual); } TEST_METHOD(Part2) { Day07 day7; string actual; vector<string> input({ "Step C must be finished before step A can begin.", "Step C must be finished before step F can begin.", "Step A must be finished before step B can begin.", "Step A must be finished before step D can begin.", "Step B must be finished before step E can begin.", "Step D must be finished before step E can begin.", "Step F must be finished before step E can begin.", }); string expected("15"); actual = day7.Part2(input); Assert::AreEqual(expected, actual); } }; }
true
b92174c34ef01a322df82d5dd4557ca252dd8998
C++
RizkiAlhamid/Composer-List-Database-
/LinkedList.h
UTF-8
5,562
3.984375
4
[]
no_license
#ifndef LinkedList_h #define LinkedList_h #include <stdio.h> #include <iostream> #include "Node.h" using namespace std; template <class T> class LinkedList{ private: Node<T>* first; Node<T>* last; public: LinkedList(); ~LinkedList(); void printList() const; void append(const T data); void prepend(const T data); bool removeFront(); void insert(const T data); bool remove(const T data); bool find(const T data); bool isEmpty() const; T getFirst() const; T getLast() const; }; //=========================== // Default Constructor //=========================== template<class T> LinkedList<T>::LinkedList(){ first = nullptr; last = nullptr; } //=========================== // Destructor //=========================== template<class T> LinkedList<T>::~LinkedList(){ Node<T> * iter = first; Node<T> * temp = nullptr; while(iter != nullptr){ temp = iter->next; delete iter; iter = temp; } } //=========================== // Print List Method // Showing all the data in the linked list //=========================== template<class T> void LinkedList<T>::printList() const{ if(first == nullptr) return; else{ Node<T>* iter = first; while(iter != nullptr){ cout << iter->data; iter = iter->next; } cout << endl; } } //=========================== // Append method // Receive a data as argument and append it to the last node in the list //=========================== template<class T> void LinkedList<T>::append(const T data){ Node<T>* temp = new Node<T>; temp->data = data; temp->next = nullptr; if(first == nullptr){ first = temp; last = temp; } else{ Node<T>* iter = first; while(iter->next != nullptr){ iter = iter->next; } iter->next = temp; last = temp; } } //=========================== // Prepend Method // Receives data and append it at the beginning od the list //=========================== template<class T> void LinkedList<T>::prepend(const T data){ Node<T>* temp = new Node<T>; temp->data = data; if(first == nullptr){ first = temp; last = temp; } else{ temp->next = first; first = temp; } } //=========================== // Remove Front method // remove the first node of the list //=========================== template<class T> bool LinkedList<T>::removeFront(){ if(first == nullptr) return false; else{ Node<T>* target = first; first = first->next; delete target; } return true; } //=========================== // Insert method // Receives a data and insert the data to the list // with the in increasing order //=========================== template<class T> void LinkedList<T>::insert(const T data){ Node<T>* temp = new Node<T>; temp->data = data; temp->next = nullptr; if(first == nullptr){ first = temp; last = temp; } else{ Node<T>* current = first; Node<T>* preNode = nullptr; while(current != nullptr && current->data < data){ preNode = current; current = current->next; } if(preNode == nullptr){ temp->next = first; first = temp; last = temp->next; } else{ temp->next = current; preNode->next = temp; last = temp; } } } //=========================== // Remove method // receives a data and search the data through the list // and remove it if it's found //=========================== template<class T> bool LinkedList<T>::remove(const T data){ Node<T>* current = first; Node<T>* preNode = nullptr; if(current == nullptr) return false; else if(current->data == data){ current = first->next; delete first; first = current; } else{ while(current != nullptr && current->data != data){ preNode = current; current = current->next; } if(current == nullptr){ return false; } else{ preNode->next = current->next; delete current; } } return true; } //=========================== // Find method // receives a data and search for that data in the list // returns true if it's found, return false otherwise //=========================== template<class T> bool LinkedList<T>::find(const T data){ Node<T>* find = first; while(find != nullptr){ if(find->data == data){ return true; }else{ find = find->next; } } return false; } //=========================== // Is Empty method // check if the list is empty or not // return true if empty, false otherwise //=========================== template<class T> bool LinkedList<T>::isEmpty() const{ if(first == nullptr) return true; return false; } //=========================== // Get First method // get and return the first node's data of the list //=========================== template<class T> T LinkedList<T>::getFirst() const{ return first->data; } //=========================== // Get Last method // get and return the last node's data of the list //=========================== template<class T> T LinkedList<T>::getLast() const{ return last->data; } #endif /* LinkedList_h */
true
580fecb9b6acd8114d69289dbda821e00d3609f7
C++
GCZhang/Profugus
/packages/Utils/utils/Vector_Lite.hh
UTF-8
6,551
2.96875
3
[ "BSD-2-Clause" ]
permissive
//----------------------------------*-C++-*----------------------------------// /*! * \file Utils/utils/Vector_Lite.hh * \author Derived from Rob Lowrie's Vector_Lite (LANL) * \date Thu Jan 3 11:39:29 2008 * \brief Vector_Lite class definition. * \note Copyright (C) 2008 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #ifndef Utils_utils_Vector_Lite_hh #define Utils_utils_Vector_Lite_hh #include <iostream> #include <numeric> #include <cstddef> #include <iterator> #include <algorithm> #include <initializer_list> #include "Utils/harness/DBC.hh" namespace profugus { //===========================================================================// /*! * \class Vector_Lite * \brief Array container that is a wrapper around a standard C array. * * It adds iterator and arithemtic support, along with bounds checking (via * Utils' DBC). * * An alternative to this class is boost::array (www.boost.org). However, * boost::array is an aggregate type, which has advantages (can use * initializers) and disadvantages (public data, cannot be a base class). * boost::array also doesn't do bounds checking. * * \param T Type of each array element. * * \param N Length of array. */ /*! * \example utils/test/tstVector_Lite.cc * * Test of Vector_Lite. */ //===========================================================================// template <class T, size_t N> class Vector_Lite { public: //@{ //! Typedefs. typedef T value_type; typedef value_type* pointer; typedef const T* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef ptrdiff_t difference_type; typedef size_t size_type; typedef pointer iterator; typedef const_pointer const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; //@} private: // >>> DATA T d_U[N]; public: // Empty constructor inline explicit Vector_Lite(); // Constructor based on a scalar value. inline explicit Vector_Lite(const T &u); // Constructor for N = 2. inline Vector_Lite(const T &u0, const T &u1); // Constructor for N = 3. inline Vector_Lite(const T &u0, const T &u1, const T &u2); // Constructor for N = 4. inline Vector_Lite(const T &u0, const T &u1, const T &u2, const T &u3); // Constructor for N = 5. inline Vector_Lite(const T &u0, const T &u1, const T &u2, const T &u3, const T &u4); // Initializer list construction. inline Vector_Lite(std::initializer_list<T> list); // Copy and move constructor Vector_Lite(const Vector_Lite& rhs) = default; Vector_Lite(Vector_Lite&& rhs) = default; // >>> MANIPULATORS // Assignment from a another Vector_Lite. Vector_Lite &operator=(const Vector_Lite &rhs) = default; Vector_Lite &operator=(Vector_Lite &&rhs) = default; // Assignment from a scalar. inline Vector_Lite &operator=(const T &rhs); // Comparisons to another Vector_Lite. inline bool operator==(const Vector_Lite &a) const; inline bool operator<(const Vector_Lite &a) const; inline bool all_gt(const Vector_Lite &a) const; inline bool all_lt(const Vector_Lite &a) const; inline bool all_ge(const Vector_Lite &a) const; inline bool all_le(const Vector_Lite &a) const; // Basic arithmetic operations, vector right-hand side. inline Vector_Lite &operator+=(const Vector_Lite &a); inline Vector_Lite &operator-=(const Vector_Lite &a); inline Vector_Lite &operator*=(const Vector_Lite &a); inline Vector_Lite &operator/=(const Vector_Lite &a); // Basic arithmetic operations, scalar right-hand side. template<class T2> inline Vector_Lite &operator+=(const T2 &a); template<class T2> inline Vector_Lite &operator-=(const T2 &a); template<class T2> inline Vector_Lite &operator*=(const T2 &a); template<class T2> inline Vector_Lite &operator/=(const T2 &a); // >>> ACCESSORS //! Indexing using []. reference operator[](const size_type i) { REQUIRE(i < N); return d_U[i]; } //! const indexing using []. const_reference operator[](const size_type i) const { REQUIRE(i < N); return d_U[i]; } //@{ //! C++11-like data access pointer data() { return d_U; } const_pointer data() const { return d_U; } //@} //! Front and back elements (unchecked) const_reference front() const { return d_U[0]; } reference front() { return d_U[0]; } const_reference back() const { return d_U[N-1]; } reference back() { return d_U[N-1]; } //@} // >>> ITERATOR SUPPORT //! Iterator begin. iterator begin() { return d_U; } //! Const iterator begin. const_iterator begin() const { return d_U; } //! Begin reverse iterator. reverse_iterator rbegin() { return reverse_iterator(end()); } //! Begin reverse const_iterator. const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator crbegin() const { return rbegin(); } //! Iterator end. iterator end() { return d_U + N; } //! End reverse iterator. reverse_iterator rend() { return reverse_iterator(begin()); } //! End reverse const_iterator. const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } const_reverse_iterator crend() const { return rend(); } //! Const iterator end. const_iterator end() const { return d_U + N; } //! Number of elements (\a N); for STL support. size_type size() const { return N; } //! Max number of elements (\a N); for STL support. size_type max_size() const { return N; } //! True if \a N = 0; for STL support. bool empty() const { return N == 0; } }; } // end namespace profugus //---------------------------------------------------------------------------// // INLINE AND FREE FUNCTIONS //---------------------------------------------------------------------------// #include "Vector_Lite.i.hh" #endif // Utils_utils_Vector_Lite_hh //---------------------------------------------------------------------------// // end of utils/Vector_Lite.hh //---------------------------------------------------------------------------//
true
4d037dd70832fa69e9e256f97828c623d9d84b37
C++
matthiasholl/R3BRoot
/r3bdata/pspData/R3BPspxPrecalData.h
UTF-8
1,456
2.703125
3
[]
no_license
#ifndef R3BPSPXPRECALDATA_H #define R3BPSPXPRECALDATA_H #include "TObject.h" /** * Class containing PSPX detector data on Precal level. * Originally, this class was introduced for the analysis of jun16, but it should also work for later experiments. * @author Ina Syndikus * @since March 2017 */ class R3BPspxPrecalData : public TObject { public: /** Default Constructor **/ R3BPspxPrecalData(); /** Standard Constructor **/ R3BPspxPrecalData(UShort_t detector, UShort_t strip, Float_t energy1, Float_t energy2); /** Destructor **/ virtual ~R3BPspxPrecalData() {} // Getters inline const UShort_t& GetDetector() const { return fDetector; } inline const UShort_t& GetStrip() const { return fStrip; } inline const Float_t& GetEnergy1() const { return fEnergy1; } inline const Float_t& GetEnergy2() const { return fEnergy2; } private: UShort_t fDetector; /**< Detector number, counting from 1 */ UShort_t fStrip; /**< Strip number, counting from 1 */ Float_t fEnergy1; /**< Energy/Collected charge for odd channel corresponding to the strip. This value needs no gain correction (Mapped2Precal Position Calibration).*/ Float_t fEnergy2; /**< Energy/Collected charge for even channel corresponding to the strip. This value is gain corrected (Mapped2Precal Position Calibration).*/ public: ClassDef(R3BPspxPrecalData, 2) }; #endif
true
2cbfca580fa4599e96b7a00d555dc7b07082ccec
C++
rehno-lindeque/Flower-of-Persia
/src/models/roof.h
UTF-8
3,763
3.09375
3
[ "MIT" ]
permissive
#ifndef __ROOF_H__ #define __ROOF_H__ class Roof : public Model { protected: // Warning: this is actually a reverse cylinder void extrudeHalfZCylinder(float* position, uint divisions, float* radia, float* heights, uint heightSegments) { float a = PI / divisions; // half cylinder for(uint cz = 0; cz < heightSegments; cz++) { float angle = 0; for(uint cx = 0; cx < divisions; cx++) { glNormal3f( cos(angle),-sin(angle), 0.0f); drawVertex3fv((Vector3)position + Vector3(-cos(angle)*radia[cz+1], sin(angle)*radia[cz+1], heights[cz+1])); // tl glNormal3f( cos(angle),-sin(angle), 0.0f); drawVertex3fv((Vector3)position + Vector3(-cos(angle)*radia[cz], sin(angle)*radia[cz], heights[cz])); // bl glNormal3f( cos(angle+a),-sin(angle+a), 0.0f); drawVertex3fv((Vector3)position + Vector3(-cos(angle+a)*radia[cz], sin(angle+a)*radia[cz], heights[cz])); // br glNormal3f( cos(angle+a),-sin(angle+a), 0.0f); drawVertex3fv((Vector3)position + Vector3(-cos(angle+a)*radia[cz+1], sin(angle+a)*radia[cz+1], heights[cz+1])); // tr angle += a; } } } // precondition: divisions must be even void drawXYCap(float* position, uint divisions, float radius) { float a = PI / divisions; // half cylinder float angle = 0.0f; for(uint cx = 0; cx < divisions/2; cx++) { glNormal3f( 0.0f, 0.0f, -1.0f); drawVertex3fv((Vector3)position); // origin glNormal3f( 0.0f, 0.0f, -1.0f); drawVertex3fv((Vector3)position + Vector3(-cos(angle)*radius, sin(angle)*radius, 0.0f)); // left glNormal3f( 0.0f, 0.0f, -1.0f); drawVertex3fv((Vector3)position + Vector3(-cos(angle+a)*radius, sin(angle+a)*radius, 0.0f)); // middle glNormal3f( 0.0f, 0.0f, -1.0f); drawVertex3fv((Vector3)position + Vector3(-cos(angle+a+a)*radius, sin(angle+a+a)*radius, 0.0f)); // right angle += 2*a; } } void drawReverseXYCap(float* position, uint divisions, float radius) { float a = PI / divisions; // half cylinder float angle = 0.0f; for(uint cx = 0; cx < divisions/2; cx++) { glNormal3f( 0.0f, 0.0f, 1.0f); drawVertex3fv((Vector3)position); // origin glNormal3f( 0.0f, 0.0f, 1.0f); drawVertex3fv((Vector3)position + Vector3(-cos(angle+a+a)*radius, sin(angle+a+a)*radius, 0.0f)); // right glNormal3f( 0.0f, 0.0f, 1.0f); drawVertex3fv((Vector3)position + Vector3(-cos(angle+a)*radius, sin(angle+a)*radius, 0.0f)); // middle glNormal3f( 0.0f, 0.0f, 1.0f); drawVertex3fv((Vector3)position + Vector3(-cos(angle)*radius, sin(angle)*radius, 0.0f)); // left angle += 2*a; } } public: GLuint displayList; virtual void build() { uint roofSegments = 12; float height = 16.0f; float radia[] = { 24.0f, 24.0f, 20.0f }; float heights[] = { 0.0f, 48.0f, 52.0f }; float quad[][3] = { { 24.0f, 32.0f,-36.0f}, // tl { 24.0f, 32.0f,-24.0f}, // bl {-24.0f, 32.0f,-24.0f}, // br {-24.0f, 32.0f,-36.0f}, // tr }; displayList = glGenLists(1); glNewList(displayList, GL_COMPILE); glPushMatrix(); glBegin(GL_QUADS); extrudeHalfZCylinder(Vector3(0.0f, 32.0f, -24.0f), roofSegments, radia, heights, 2); drawXYCap(Vector3(0.0f, 32.0f, 28.0f), roofSegments, 20.0f); drawReverseXYCap(Vector3(0.0f, 32.0f, -24.0f), roofSegments, 24.0f); drawQuad(quad[0], quad[1], quad[2], quad[3]); glEnd(); glEndList(); } virtual void render() { glCallList(displayList); } virtual void renderNormals() { } }; #endif
true
c4d04595ec590a37386e70b829ea4e5699d3cf5b
C++
andyyang200/CP
/Competitive Programming/Contests/USACO/Contests/2016 - 2017/US Open/Bronze/Lost Cow 2/lostcow.cpp
UTF-8
587
2.75
3
[]
no_license
#include <iostream> using namespace std; int main(void) { freopen("lostcow.in", "r", stdin); freopen("lostcow.out", "w", stdout); int x; int y; cin >> x >> y; int dis = 0; int cur = x; int change = 1; while (true) { int end = x + change; while (cur < end) { cur++; dis++; if (cur == y) { cout << dis << endl; return 0; } } while (cur > end) { cur--; dis++; if (cur == y) { cout << dis << endl; return 0; } } change += change; change = -change; } cout << dis << endl; }
true
acf4c14a9869d1e6dc825bcf816e776b3c501c7f
C++
henryoier/leetcode
/052_N-QueensII/052_N-QueensII.cpp
UTF-8
1,128
3.359375
3
[]
no_license
/************************************************************************* > File Name: 052_N-QueensII.cpp > Author: Sheng Qin > Mail: sheng.qin@yale.edu > Created Time: Fri Sep 2 01:09:08 2016 ************************************************************************/ #include<iostream> using namespace std; class Solution { public: int totalNQueens(int n) { int path[n]; int result = 0; dfs(0, n, path, result); return result; } private: void dfs(int depth, int n, int path[], int& result){ if(depth == n) result++; for(int i = 0; i < n; i++){ if(checkLegal(depth, i, path)){ path[depth] = i; dfs(depth + 1, n, path, result); } } } bool checkLegal(int depth, int i, int path[]){ for(int j = depth - 1; j >= 0; j--){ if(path[j] == i || abs(i - path[j]) == abs(depth - j)) return false; } return true; } }; int main(){ Solution newSolution; cout << newSolution.totalNQueens(4) << endl; return 0; }
true
b59cac534c1c9199a4d698ad85f6e7ab1b104c0c
C++
AMROZIA-MAZHAR/function_tasks
/function_task4.cpp
UTF-8
991
3.375
3
[]
no_license
#include<iostream> #include<string> using namespace std; string input(); int check(string part_num); string deliverymethod(string part_num); int main(){ string part_num=input(); int str_length=check(part_num); if(str_length==4 || str_length==5){ cout<<"part number contain "<<str_length<<" characters"<<endl; string method=deliverymethod(part_num); if(method=="ms") cout<<"Mail_Standard"<<endl; else if(method=="mp") cout<<"Mail_Priority"<<endl; else if(method="fs") cout<<"FedEx"<<endl; else cout<<"2nd and 3rd character are not delivery method"<<endl; } return 0; } string input(){ string part_num; cout<<"enter the part number of 4 or 5 characters"<<endl; cin>>part_num; return part_num; } int check(string part_num){ int str_length; str_length=part_num.length(); return str_length; } string deliverymethod(string part_num){ string sub_string=part_num.substr(1,2); return sub_string; }
true
3f47ef4a68b8f3e61456d53dd015cd4feec5a5c8
C++
suffisme/CC-Solutions
/Hackerearth/Prime-Interval.cpp
UTF-8
481
2.59375
3
[]
no_license
#include <bits/stdc++.h> #define ll long long using namespace std; bool P[10001]; void SieveOfErasthothenes() { int n = 10001; for(int i=0;i<n;i++) P[i]=true; for(int i=2;i*i<n;i++) { if(P[i]) { for(int j=i*i; j<=n; j += i) P[j] = false; } } P[1]=false; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int l,r; cin>>l>>r; SieveOfErasthothenes(); for(int i=l;i<=r;i++) if(P[i]) cout<<i<<" "; }
true
db65e24271a97d1ff3eaa0239a80f4880d6cf9ed
C++
bhavinisehgal18/geeksforgeeks
/zeroandone.cpp
UTF-8
744
3.234375
3
[]
no_license
#include<iostream> using namespace std; void segregate(int arr[], int n) { int count = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0) count++; } for (int i = 0; i < count; i++) arr[i] = 0; for (int i = count; i < n; i++) arr[i] = 1; } void print(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout<<endl; } int main() { int t; cin>>t; while(t!=0) { int n; cin>>n; int arr[n]; for(int i=0; i<n;i++) { cin>>arr[i]; } segregate(arr, n); print(arr, n); t--; } return 0; }
true
a0df5e07c86b885529e0c8ff5836017d53ba6152
C++
dcheng289/Class-Projects
/wxWidgets-Paint-Program/PaintModel.h
UTF-8
2,176
2.71875
3
[]
no_license
#pragma once #include <memory> #include <vector> #include "Shape.h" #include "Command.h" #include <wx/bitmap.h> #include <stack> class PaintModel : public std::enable_shared_from_this<PaintModel> { public: PaintModel(); // Draws any shapes in the model to the provided DC (draw context) void DrawShapes(wxDC& dc, bool showSelection = true); // Clear the current paint model and start fresh void New(); // Add a shape to the paint model void AddShape(std::shared_ptr<Shape> shape); // Remove a shape from the paint model void RemoveShape(std::shared_ptr<Shape> shape); // Command functions bool HasActiveCommand(); void CreateCommand(CommandType commandType, const wxPoint & start); void UpdateCommand(const wxPoint & wPoint); void Finalize(std::shared_ptr<PaintModel> pModel); // Undo and Redo void Undo(); void Redo(); bool CanUndo(); bool CanRedo(); void ClearRedo(); // Pen Functions wxPen GetPen(); void SetPen(wxPen pen); wxColour GetPenColor(); void SetPenColor(wxColour colour); int GetPenWidth(); void SetPenWidth (int width); // Brush Functions wxBrush GetBrush(); void SetBrush(wxBrush brush); wxColour GetBrushColor(); void SetBrushColor(wxColour colour); // Selection Functions void SelectShape (const wxPoint& selectionPoint); void ResetSelectedShape(); bool HasSelectedShape(); bool IntersectsSelectedShape(const wxPoint& mousePoint); std::shared_ptr<Shape> GetSelectedShape(); // Export/Import void FileExport(const std::string &fileName, const wxSize& size); void FileImport(const wxString& fileName); private: // Vector of all the shapes in the model std::vector<std::shared_ptr<Shape>> mShapes; std::shared_ptr<Command> mActiveCommand; // Undo and Redo Stacks std::stack<std::shared_ptr<Command>> mUndoStack; std::stack<std::shared_ptr<Command>> mRedoStack; // Pen and Brush wxPen mPen; wxBrush mBrush; // Selections std::shared_ptr<Shape> mSelectedShape; // Import map wxBitmap importMap; bool loadedMap; };
true
e37400ebbe402d62b8575c70bc272952e9f01177
C++
aman-ahluwalia/Spoj-solutions
/FCTRL2.cpp
UTF-8
485
2.8125
3
[]
no_license
#include<iostream> using namespace std; int main() { int t; cin>>t; while(t--) { int n,i,j,arr[200]; cin>>n; arr[0] = 1; int m=0; for(i=1;i<=n;i++) { int temp = 0; for(j=0;j<=m;j++) { temp = arr[j] * i + temp; arr[j] = temp%10; temp/=10; } while(temp!=0) { arr[++m] = temp%10; temp/=10; } } for(i=m;i>=0;i--) cout<<arr[i]; cout<<endl; } return 0; }
true
ac9d6fb344793699824cb098b1b356db52f615b2
C++
BarArbel/Software-Engineering-Methods
/FinalProject/FinalProject/Source.cpp
UTF-8
1,649
2.515625
3
[]
no_license
#include "../Common/Border/Border.h" #include "../Common/Border/DoubleBorder.h" #include "../Common/Border/NullBorder.h" #include "../Common/Border/SingleBorder.h" #include "../Common/EventEngine.h" #include "../Common/Graphics.h" #include "../Controls/Button.h" #include "../Controls/CheckList.h" #include "../Controls/ComboBox.h" #include "../Controls/Label.h" #include "../Controls/MessageBox.h" #include "../Controls/NumericBox.h" #include "../Controls/Panel.h" #include "../Controls/RadioBox.h" #include "../Controls/textbox.h" int main(int argc, char** argv) { DoubleBorder* db = new DoubleBorder; NullBorder* nb = new NullBorder; SingleBorder* sb = new SingleBorder; Panel P(0, 0, db, Color::White, Color::Black); Button B(0, 10, 10, sb, Color::White, Color::Black, "Show"); semMessageBox MB(0, 0, 30, db, Color::White, Color::Cyan, "Message", "Ok", "Cancel", &B); TextBox TB(40, 0, 10, sb, Color::White, Color::Cyan); ComboBox CB(40, 10, sb, Color::White, Color::Cyan); CB.addToList("one"); CB.addToList("two"); CB.addToList("forty seven"); CheckList CL(60, 10, 20, db, Color::Purple, Color::White); CL.addToList("hello"); CL.addToList("HELLO"); CL.addToList("HeLlO"); RadioBox RB(50, 10, 15, db, Color::Blue, Color::White); RB.addToList("qwer"); RB.addToList("asdf"); RB.addToList("zxcv"); Label L(0, 15, 10, nb, Color::White, Color::Black, "Such WOW"); NumericBox NB(50, 5, 50, -1000, sb, Color::White, Color::Black); P.addControl(&B); P.addControl(&MB); P.addControl(&TB); P.addControl(&CB); P.addControl(&CL); P.addControl(&RB); P.addControl(&L); P.addControl(&NB); EventEngine e; e.run(P); return 0; }
true
7ad7456a15c8c361556691b9e9da07c691d92f2f
C++
Chet8n/InterviewPrep
/6.Backtracking 2/Vertical and Horizontal Sums.cpp
UTF-8
3,049
3.859375
4
[]
no_license
/* Vertical and Horizontal Sums Problem Description Given a matrix B, of size N x M, you are allowed to do at most A special operations on this grid such that there is no vertical or horizontal contiguous subarray that has a sum greater than C. A special operation involves multiplying any element by -1 i.e. changing its sign. Return 1 if it is possible to achieve the answer, otherwise 0. Problem Constraints 1 <= N, M <= 10 0 <= A <= 5 -105 <= B[i][j], C <= 105 Input Format The first argument is an integer A, representing the number of special operations allowed. The second argument has the N x M integer matrix, B. The third argument is an integer C, as described in the problem statement. Output Format Return 1 if it is possible to achieve the answer, otherwise 0. Example Input Input 1: A = 3 B = [ [1, 1, 1] [1, 1, 1] [1, 1, 1] ] C = 2 Input 2: A = 1 B = [ [1, 1, 1] [1, 1, 1] [1, 1, 1] ] C = 2 Example Output Output 1: 1 Output 2: 0 Example Explanation Explanation 1: The given matrix does not satisfy the conditions, but if we apply the special operation to B[0][0], B[1][1], B[2][2], then the matrix would satisfy the given conditions i.e. no row or column has a sum greater than 2. Explanation 2: It is not possible to apply the special operation to 1 element to satisfy the conditions. */ bool ok(vector<vector<int>> &b, int c) { int n = b.size(); int m = b[0].size(); for (int i = 0; i < n; i++) { int msf = -1e8; int sum = -1e8; for (int j = 0; j < m; j++) { msf = max(msf + b[i][j], b[i][j]); sum = max(sum, msf); } if (sum > c) { return false; } } for (int j = 0; j < m; j++) { int msf = -1e8; int sum = -1e8; for (int i = 0; i < n; i++) { msf = max(msf + b[i][j], b[i][j]); sum = max(sum, msf); } if (sum > c) { return false; } } return true; } bool go(int a, vector<vector<int>> &b, int c, int x, int y) { int n = b.size(); int m = b[0].size(); if (ok(b, c)) { return true; } if (a == 0 or x == n) { return false; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if ( (i == x and j >= y) or (i > x)) { if (b[i][j] > 0) { b[i][j] = -b[i][j]; if (j == m - 1) { if (go(a - 1, b, c, i + 1, 0)) { return true; } } else { if (go(a - 1, b, c, i, j + 1)) { return true; } } b[i][j] = -b[i][j]; } } } } return false; } int Solution::solve(int a, vector<vector<int> > &b, int c) { bool ans = go(a, b, c, 0, 0); return ans ? 1 : 0; }
true
45b70016b25a368a9a54cec9ef45e76207df1706
C++
TheEgghead27/Lets_Learn_Cpp
/LLCPP_Solutions/LLCPP_013_Solutions/13_Solution_01/main.cpp
UTF-8
571
3.328125
3
[]
no_license
#include <iostream> #include <string> using namespace std; enum Flower { Poppy, Daisy, Rose, Dandelion, Daffodil }; void Flower_Printer(Flower f) { switch (f) { case Poppy: cout << "Poppy" << endl; break; case Daisy: cout << "Daisy" << endl; break; case Rose: cout << "Rose" << endl; break; case Dandelion: cout << "Dandelion" << endl; break; case Daffodil: cout << "Daffodil" << endl; break; default: cout << "Unknown. Kill it with fire!" << endl; } } int main() { Flower_Printer(Poppy); string y; getline(cin, y); return 0; }
true
9770c1adb26b25697b0e556fbb676421a8e6bf0a
C++
PROgram52bc/Elevator
/eleGraphics/testEleGraphics.cpp
UTF-8
453
2.78125
3
[]
no_license
/* * testconio.cpp: test program for the conio function set */ #include <iostream> #include "eleGraphics.h" #include "conio.h" using namespace std; using namespace conio; int main() { cerr << clrscr() << flush; for (int i=5; i>1; i--) { cout << clrscr(); elegraphics::drawFloor(7); elegraphics::drawElevator(i,elegraphics::down); cout << gotoRowCol(100,0) << "Press something to make it go down." << endl; cin.get(); } return 0; }
true
ce883e54530d6d234623515a3880c0eb5ecab6f9
C++
Marukyu/RankCheck
/src/Shared/Utils/Utilities.cpp
UTF-8
7,983
2.65625
3
[ "MIT" ]
permissive
#include <SFML/Config.hpp> #include <SFML/System/Time.hpp> #include <SFML/System/Vector2.hpp> #include <Shared/Utils/MiscMath.hpp> #include <Shared/Utils/StrNumCon.hpp> #include <Shared/Utils/Utilities.hpp> #include <Shared/Utils/OSDetect.hpp> #include <Poco/File.h> #include <Poco/Path.h> #include <Poco/DirectoryIterator.h> #include <algorithm> #include <cctype> #include <cstddef> #include <ctime> #include <deque> #include <exception> #include <initializer_list> #include <iostream> #include <iterator> #include <locale> #include <sstream> #include <string> #include <vector> std::string toUppercase(std::string str) { for (std::string::iterator it = str.begin(); it != str.end(); ++it) *it = toupper(*it); return str; } std::string toLowercase(std::string str) { for (std::string::iterator it = str.begin(); it != str.end(); ++it) *it = tolower(*it); return str; } bool equalsIgnoreCase(const std::string & a, const std::string & b) { std::size_t size = a.size(); if (size != b.size()) { return false; } for (std::size_t i = 0; i < size; ++i) { if (tolower(a[i]) != tolower(b[i])) { return false; } } return true; } bool stringStartsWith(const std::string& string, const std::string& prefix) { if (string.length() >= prefix.length()) { return string.compare(0, prefix.length(), prefix) == 0; } else { return false; } } bool stringEndsWith(const std::string& string, const std::string& suffix) { if (string.length() >= suffix.length()) { return string.compare(string.length() - suffix.length(), suffix.length(), suffix) == 0; } else { return false; } } void splitString(std::string str, const std::string & separator, std::vector<std::string> & results, bool ignoreEmpty) { results.clear(); std::size_t found = str.find_first_of(separator); while (found != std::string::npos) { if (found > 0) results.push_back(str.substr(0, found)); else if (!ignoreEmpty) results.push_back(std::string()); str = str.substr(found + 1); found = str.find_first_of(separator); } if (str.length() > 0) results.push_back(str); } std::string getTimeString() { std::time_t rawtime; std::tm * timeinfo; char buffer[80]; std::string ret; time(&rawtime); timeinfo = localtime(&rawtime); ret.assign(buffer, strftime(buffer, 80, "%X", timeinfo)); return ret; } bool listFiles(std::string dir, std::vector<std::string> & vec, bool recursive, bool sorted, std::string prefix) { try { Poco::File directory(dir); if (!directory.isDirectory()) { return false; } for (Poco::DirectoryIterator it(directory); it != Poco::DirectoryIterator(); ++it) { std::string filename = Poco::Path(it->path()).getFileName(); if (it->isDirectory()) { if (recursive) { std::string next = dir + Poco::Path::separator() + filename; std::string newPrefix = prefix + filename + Poco::Path::separator(); listFiles(next, vec, true, sorted, newPrefix); } } else if (it->isFile()) { if (sorted) { vec.insert(std::lower_bound(vec.begin(), vec.end(), filename), filename); } else { vec.push_back(prefix + filename); } } } return true; } catch (std::exception & ex) { return false; } } bool listDirectories(std::string dir, std::vector<std::string> & vec, bool recursive, bool sorted, std::string prefix) { try { Poco::File directory(dir); if (!directory.isDirectory()) { return false; } for (Poco::DirectoryIterator it(directory); it != Poco::DirectoryIterator(); ++it) { std::string filename = Poco::Path(it->path()).getFileName(); if (it->isDirectory()) { if (sorted) { vec.insert(std::lower_bound(vec.begin(), vec.end(), filename), filename); } else { vec.push_back(prefix + filename); } if (recursive) { std::string next = dir + Poco::Path::separator() + filename; std::string newPrefix = prefix + filename + Poco::Path::separator(); listDirectories(next, vec, true, sorted, newPrefix); } } } return true; } catch (std::exception & ex) { return false; } } bool fileExists(const std::string & filename) { try { return Poco::File(filename).exists(); } catch (std::exception & ex) { return false; } } bool isDirectory(const std::string & filename) { try { return fileExists(filename) && Poco::File(filename).isDirectory(); } catch (std::exception & ex) { return false; } } bool createDirectory(const std::string& path) { return Poco::File(path).createDirectory(); } void createDirectories(const std::string& path) { return Poco::File(path).createDirectories(); } std::string getFileExtension(const std::string & filename) { // no dot found in file name. if (filename.find_last_of(".") == std::string::npos) return ""; std::string extension = filename.substr(filename.find_last_of(".")); // last dot found within path name, so no dot in file name. if (extension.find_first_of("/\\") != std::string::npos) return ""; return extension; } std::string removeFileExtension(const std::string & filename) { // no dot found in file name. if (filename.find_last_of(".") == std::string::npos) return filename; std::string filestem = filename.substr(0, filename.find_last_of(".")); std::string extension = filename.substr(filename.find_last_of(".")); // last dot found within path name, no dot to be removed in file name. if (extension.find_first_of("/\\") != std::string::npos) return filename; return filestem; } std::string extractFileName(const std::string& path) { std::size_t found = path.find_last_of("/\\"); if (found == std::string::npos) { return path; } else { return path.substr(found + 1); } } std::string removeFileName(const std::string& path) { std::size_t found = path.find_last_of("/\\"); if (found == std::string::npos) { return ""; } else { return path.substr(0, found); } } std::string getByteSizeString(sf::Uint64 bytes) { if (bytes < 1000) { return cNtoS(bytes) + " B"; } else if (bytes < 1000000) { return cNtoS(round<double>(bytes / 1000.0, 1)) + " KB"; } else if (bytes < 1000000000) { return cNtoS(round<double>(bytes / 1000000.0, 1)) + " MB"; } else { return cNtoS(round<double>(bytes / 1000000000.0, 1)) + " GB"; } } std::string fillStringWithChar(std::string str, char chr, std::size_t targetSize) { if (str.size() < targetSize) return std::string(targetSize - str.size(), chr) + str; else return str; } std::string getSfTimeString(sf::Time time) { std::ostringstream str; str.precision(2); str << std::fixed; if (time < sf::milliseconds(1)) { str << time.asMicroseconds() << "us"; } else if (time < sf::seconds(1)) { str << round(time.asSeconds() * 1000.f, 2) << "ms"; } else if (time < sf::seconds(60)) { str << round(time.asSeconds(), 2) << "s"; } else if (time < sf::seconds(60 * 60)) { str << int(time.asSeconds()) / 60 << ":" << fillStringWithChar(cNtoS(int(time.asSeconds()) % 60), '0', 2) << "." << fillStringWithChar(cNtoS((time.asMilliseconds() / 10) % 100), '0', 2); } else { return getRoughSfTimeString(time); } return str.str(); } std::string getRoughSfTimeString(sf::Time time) { if (time > sf::seconds(60 * 60)) { return cNtoS(int(time.asSeconds() / 60 / 60)) + ":" + fillStringWithChar(cNtoS(int(time.asSeconds() / 60) % 60), '0', 2) + ":" + fillStringWithChar(cNtoS(int(time.asSeconds()) % 60), '0', 2); } else { return cNtoS(int(time.asSeconds() / 60) % 60) + ":" + fillStringWithChar(cNtoS(int(time.asSeconds()) % 60), '0', 2); } } bool pointInPoly(const std::vector<sf::Vector2f> & vertices, const sf::Vector2f & point) { bool ret = false; for (std::size_t i = 0, j = vertices.size() - 1; i < vertices.size(); j = i++) { const sf::Vector2f & v1 = vertices[i], &v2 = vertices[j]; if ((v1.y > point.y) != (v2.y > point.y) && point.x < (v2.x - v1.x) * (point.y - v1.y) / (v2.y - v1.y) + v1.x) ret = !ret; } return ret; }
true
b8f5fbd851dfe3469d4b2c7ca7a8352013943849
C++
CreativeMachinesLab/softbotEscape
/base/hyperneat/JGTL/include/JGTL_Variant.h
UTF-8
8,615
2.515625
3
[]
no_license
#ifndef VARIANT_H_INCLUDED #define VARIANT_H_INCLUDED #include <iostream> #include "JGTL_LocatedException.h" namespace JGTL { template <class Type,bool condition, Type Then, Type Else> struct TYPEIF { static const Type RESULT=Then; }; template <class Type,Type Then, Type Else> struct TYPEIF<Type,false, Then, Else> { static const Type RESULT=Else; }; template < class One, class Two = One, class Three = One, class Four = One, class Five = One, class Six = One, class Seven = One, class Eight = One, class Nine = One, class Ten = One > struct STATIC_MAX_SIZE { const static int RESULT = TYPEIF< int, (sizeof(Two) > sizeof(Three)), STATIC_MAX_SIZE<One,One,Two,Four,Five,Six,Seven,Eight,Nine,Ten>::RESULT, STATIC_MAX_SIZE<One,One,Three,Four,Five,Six,Seven,Eight,Nine,Ten>::RESULT >::RESULT; }; template < class One, class Two, class Three, class Four, class Five, class Six, class Seven, class Eight, class Nine > struct STATIC_MAX_SIZE<One,One,Two,Three,Four,Five,Six,Seven,Eight,Nine> { const static int RESULT = TYPEIF< int, (sizeof(Two) > sizeof(Three)), STATIC_MAX_SIZE<One,One,One,Two,Four,Five,Six,Seven,Eight,Nine>::RESULT, STATIC_MAX_SIZE<One,One,One,Three,Four,Five,Six,Seven,Eight,Nine>::RESULT >::RESULT; }; template < class One, class Two, class Three, class Four, class Five, class Six, class Seven, class Eight > struct STATIC_MAX_SIZE<One,One,One,Two,Three,Four,Five,Six,Seven,Eight> { const static int RESULT = TYPEIF< int, (sizeof(Two) > sizeof(Three)), STATIC_MAX_SIZE<One,One,One,One,Two,Four,Five,Six,Seven,Eight>::RESULT, STATIC_MAX_SIZE<One,One,One,One,Three,Four,Five,Six,Seven,Eight>::RESULT >::RESULT; }; template < class One, class Two, class Three, class Four, class Five, class Six, class Seven > struct STATIC_MAX_SIZE<One,One,One,One,Two,Three,Four,Five,Six,Seven> { const static int RESULT = TYPEIF< int, (sizeof(Two) > sizeof(Three)), STATIC_MAX_SIZE<One,One,One,One,One,Two,Four,Five,Six,Seven>::RESULT, STATIC_MAX_SIZE<One,One,One,One,One,Three,Four,Five,Six,Seven>::RESULT >::RESULT; }; template < class One, class Two, class Three, class Four, class Five, class Six > struct STATIC_MAX_SIZE<One,One,One,One,One,Two,Three,Four,Five,Six> { const static int RESULT = TYPEIF< int, (sizeof(Two) > sizeof(Three)), STATIC_MAX_SIZE<One,One,One,One,One,One,Two,Four,Five,Six>::RESULT, STATIC_MAX_SIZE<One,One,One,One,One,One,Three,Four,Five,Six>::RESULT >::RESULT; }; template <class One, class Two, class Three, class Four, class Five> struct STATIC_MAX_SIZE<One,One,One,One,One,One,Two,Three,Four,Five> { const static int RESULT = TYPEIF< int, (sizeof(Two) > sizeof(Three)), STATIC_MAX_SIZE<One,One,One,One,One,One,One,Two,Four,Five>::RESULT, STATIC_MAX_SIZE<One,One,One,One,One,One,One,Three,Four,Five>::RESULT >::RESULT; }; template <class One, class Two, class Three, class Four> struct STATIC_MAX_SIZE<One,One,One,One,One,One,One,Two,Three,Four> { const static int RESULT = TYPEIF< int, (sizeof(Two) > sizeof(Three)), STATIC_MAX_SIZE<One,One,One,One,One,One,One,One,Two,Four>::RESULT, STATIC_MAX_SIZE<One,One,One,One,One,One,One,One,Three,Four>::RESULT >::RESULT; }; template <class One, class Two, class Three> struct STATIC_MAX_SIZE<One,One,One,One,One,One,One,One,Two,Three> { const static int RESULT = TYPEIF< int, (sizeof(Two) > sizeof(Three)), STATIC_MAX_SIZE<One,One,One,One,One,One,One,One,One,Two>::RESULT, STATIC_MAX_SIZE<One,One,One,One,One,One,One,One,One,Three>::RESULT >::RESULT; }; template <class One, class Two> struct STATIC_MAX_SIZE<One,One,One,One,One,One,One,One,One,Two> { const static int RESULT = TYPEIF< int, (sizeof(One) > sizeof(Two)), sizeof(One), sizeof(Two) >::RESULT; }; class NullVariantClass {}; template< class Class1, class Class2=NullVariantClass, class Class3=NullVariantClass, class Class4=NullVariantClass, class Class5=NullVariantClass, class Class6=NullVariantClass, class Class7=NullVariantClass, class Class8=NullVariantClass, class Class9=NullVariantClass, class Class10=NullVariantClass > class Variant { protected: char data[ STATIC_MAX_SIZE< Class1, Class2, Class3, Class4, Class5, Class6, Class7, Class8, Class9, Class10 >::RESULT ]; unsigned char typeOfData; public: Variant() : typeOfData(0) {} Variant(const Variant<Class1,Class2,Class3,Class4,Class5,Class6,Class7,Class8,Class9,Class10> &other) : typeOfData(0) { switch(typeOfData) { case 0: break; case 1: setValue(other.getValue<Class1>()); break; case 2: setValue(other.getValue<Class2>()); break; case 3: setValue(other.getValue<Class3>()); break; default: break; } } template<class T> bool isOfType() { switch(typeOfData) { case 0: return false; case 1: if(typeid(Class1) != typeid(T)) return false; break; case 2: if(typeid(Class2) != typeid(T)) return false; break; case 3: if(typeid(Class3) != typeid(T)) return false; break; default: return false; break; } return true; } template<class ReturnValueClass> ReturnValueClass getValue() const { const ReturnValueClass* ptr = getValuePtr<ReturnValueClass>(); if(ptr==NULL) { throw CREATE_LOCATEDEXCEPTION_INFO("Oops, tried to get the value of a variant which was assigned to a different type"); } return *ptr; } template<class ReturnValueClass> ReturnValueClass &getValueRef() { ReturnValueClass* ptr = getValuePtr<ReturnValueClass>(); if(ptr==NULL) { throw CREATE_LOCATEDEXCEPTION_INFO("Oops, tried to get the reference of a variant which was assigned to a different type"); } return *ptr; } template<class ReturnValueClass> const ReturnValueClass &getValueRef() const { const ReturnValueClass* ptr = getValuePtr<ReturnValueClass>(); if(ptr==NULL) { throw CREATE_LOCATEDEXCEPTION_INFO("Oops, tried to get the reference of a variant which was assigned to a different type"); } return *ptr; } template<class ReturnValueClass> ReturnValueClass* getValuePtr() { if(!typeOfData) { throw CREATE_LOCATEDEXCEPTION_INFO("OOPS"); } switch(typeOfData) { case 1: if(typeid(Class1) != typeid(ReturnValueClass)) return NULL; break; case 2: if(typeid(Class2) != typeid(ReturnValueClass)) return NULL; break; case 3: if(typeid(Class3) != typeid(ReturnValueClass)) return NULL; break; default: return NULL; break; } return ((ReturnValueClass*)data); } template<class ReturnValueClass> const ReturnValueClass* getValuePtr() const { if(!typeOfData) { throw CREATE_LOCATEDEXCEPTION_INFO("OOPS"); } switch(typeOfData) { case 1: if(typeid(Class1) != typeid(ReturnValueClass)) return NULL; break; case 2: if(typeid(Class2) != typeid(ReturnValueClass)) return NULL; break; case 3: if(typeid(Class3) != typeid(ReturnValueClass)) return NULL; break; default: throw CREATE_LOCATEDEXCEPTION_INFO("OOPS"); return ((const ReturnValueClass*)data); break; } return ((const ReturnValueClass*)data); } void clearValue() { if (typeOfData) { switch(typeOfData) { case 1: ((Class1*)data)->~Class1(); break; case 2: ((Class2*)data)->~Class2(); break; case 3: ((Class3*)data)->~Class3(); break; default: throw CREATE_LOCATEDEXCEPTION_INFO("OOPS"); break; } typeOfData=0; } memset(data,0,STATIC_MAX_SIZE< Class1, Class2, Class3, Class4, Class5, Class6, Class7, Class8, Class9, Class10 >::RESULT ); } template<class ValueToSet> void setValue(const ValueToSet &newValue) { clearValue(); new(data) ValueToSet(newValue); if(typeid(ValueToSet).name() == typeid(Class1).name()) { typeOfData = 1; } else if(typeid(ValueToSet).name() == typeid(Class2).name()) { typeOfData = 2; } else if(typeid(ValueToSet).name() == typeid(Class3).name()) { typeOfData = 3; } else { throw CREATE_LOCATEDEXCEPTION_INFO("Oops, tried to set the value of a variant with a type that is not supported"); } } }; } #endif // VARIANT_H_INCLUDED
true
72a0670ea43a1771e7990127a4d784574eed4555
C++
SachioKuro/Breakout
/Breakout/Ball.cpp
UTF-8
2,605
3.046875
3
[]
no_license
#include "Ball.hpp" #include <algorithm> #include <iostream> #include "Game.hpp" namespace Breakout { Ball::Ball(Game* game, float size, Color color) : MovableGameObject(game, game->BoundsW() / 2, game->BoundsH() - 100, color), engine(dev()), random_alpha(0, 360 * M_PI / 180), size(size) {} Ball::Ball(Game* game, float size, Color color, float x, float y) : Ball(game, size, color) { this->X(x); this->Y(y); } void Ball::Render(Renderer* renderer) const { renderer->DrawFilledCircle(x_pos, y_pos, size, this->color.r, this->color.g, this->color.b, this->color.a); } void Ball::Update(Action action) { switch (action) { // Activate the ball case Breakout::GameObject::Action::start: // Choose random angle alpha = random_alpha(engine); // Initialize the x- and y-velocities velocity_x = cosf(alpha); velocity_y = sinf(alpha); break; // Update the ball case Breakout::GameObject::Action::update: update_position(); break; // A block was destroyed case Breakout::GameObject::Action::block_destroyed: // Increases the speed of the ball this->IncVelocityMultiByPer(1.01); break; // Ball hit the ground case Breakout::GameObject::Action::hit_ground: this->alive = false; break; default: break; } } bool Ball::pointInCirlce(float x, float y) { float d_x = x - x_pos; float d_y = y - y_pos; float dist = sqrt(d_x * d_x + d_y * d_y); return dist <= size; } bool Ball::pointOnLine(float px, float py, float x1, float y1, float x2, float y2) { float dist_1 = sqrt((x1 - px) * (x1 - px) + (y1 - py) * (y1 - py)); float dist_2 = sqrt((x2 - px) * (x2 - px) + (y2 - py) * (y2 - py)); float line_length = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); float eps = .01f; return dist_1 + dist_2 >= line_length - eps && dist_1 + dist_2 <= line_length + eps; } bool Ball::IntersectsLine(float x1, float y1, float x2, float y2) { if (pointInCirlce(x1, y1) || pointInCirlce(x2, y2)) return true; float line_length = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); float dot_line_circle = ((x_pos - x1) * (x2 - x1) + (y_pos - y1) * (y2 - y1)) / (line_length * line_length); float closest_x = x1 + dot_line_circle * (x2 - x1); float closest_y = y1 + dot_line_circle * (y2 - y1); if (!pointOnLine(closest_x, closest_y, x1, y1, x2, y2)) return false; float dist_x = closest_x - x_pos; float dist_y = closest_y - y_pos; return sqrt(dist_x * dist_x + dist_y * dist_y) <= size; } void Ball::OnDestroy() { game->Update(GameObject::Action::ball_destroyed); } }
true
56029a165d15a3e5b7b05cc4899b945688873e3b
C++
Steenall/morpion3D-C-PlusPlus
/player.cpp
UTF-8
1,488
3.15625
3
[]
no_license
#include "player.hpp" #include <string> #include <iostream> Player::Player(){ pColor=new Color(Color::BLUE); pName=new std::string("Player"); } Player::Player(const std::string name, const Color color){ pName= new std::string(name); pColor=new Color(color); pHouse=new short int(0); short int temp=1; for(int i=0;i<nbTypePiece;i++){ (*pHouse)+=temp*nbPieceParType; temp*=10; } } Color Player::getColor() { return *pColor; } std::string Player::getName(){ return *pName; } int Player::getPiecesInHouse(const Size pieceSize){ short int temp; switch (pieceSize) { case Size::SMALL: temp = (*pHouse)%10; break; case Size::MEDIUM: temp = ((*pHouse)/10)%10; break; case Size::LARGE: temp = (*pHouse)/100; break; default: temp = 0; } return temp; } bool Player::retirePiece(const Size pieceSize){ if(getPiecesInHouse(pieceSize)!=0){ short int temp; switch (pieceSize) { case Size::SMALL: temp = 1; break; case Size::MEDIUM: temp = 10; break; case Size::LARGE: temp = 100; break; } (*pHouse)-=temp; return true; }else{ return false; } } Player::~Player(){ /*delete pName; delete pColor; delete pHouse; pName=nullptr; pColor=nullptr; pHouse=nullptr;*/ }
true
83a027d75d3709dc63bf5d4f4f27b18f3f46544e
C++
t9jaje00/Olio-ohjelmointi
/tehtava17/main.cpp
UTF-8
375
3.046875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { vector<int> vektori; for(int i=1; i <= 100; i++) //työnnetäät luvut 1-100 vektoriin vektori.push_back(i); for (auto i = vektori.begin(); i != vektori.end(); i++) // tulostetaan vektori alusta loppuun, i:tä osoittimena käyttäen cout << *i << "\n"; return 0; }
true
a50abd12b6a26430689e2e3bfaefc8699feb5a14
C++
JiekangHuang/Arduino
/p2_4_1Segment_7_LED/p2_4_1Segment_7_LED/p2_4_1Segment_7_LED.ino
UTF-8
1,715
2.984375
3
[]
no_license
// Arduino pin: 2,3,4,5,6,7,8 byte seven_seg_digits[10][7] = { { 0,0,0,0,0,0,1 }, // = 0 x { 1,0,0,1,1,1,1 }, // = 1 x { 0,0,1,0,0,1,0 }, // = 2 x { 0,0,0,0,1,1,0 }, // = 3 x { 1,0,0,1,1,0,0 }, // = 4 x { 0,1,0,0,1,0,0 }, // = 5 x { 0,1,0,0,0,0,0 }, // = 6 x { 0,0,0,1,1,1,1 }, // = 7 x { 0,0,0,0,0,0,0 }, // = 8 x { 0,0,0,1,1,0,0 } // = 9 x }; // set the Arduino pins connected to the LED segments on Radio Shack 276-075 // which is National Semiconductor ELS-321HDB/A (very different from // standard 7-seg display // comment list below is LED pin# > Arduino pin# | segment name void setup() { pinMode(2, OUTPUT); //14 > 2 A pinMode(3, OUTPUT); //13 > 3 B pinMode(4, OUTPUT); // 8 > 4 C pinMode(5, OUTPUT); // 7 > 5 D pinMode(6, OUTPUT); // 6 > 6 E pinMode(7, OUTPUT); // 2 > 7 F pinMode(8, OUTPUT); // 1 > 8 G pinMode(9, OUTPUT); //RDP> 9 decimal point writeDot(1); // start with the "dot" off pinMode(A13, OUTPUT); digitalWrite(A13, LOW); //LED輸出 pinMode(30, OUTPUT); pinMode(31, OUTPUT); pinMode(32, OUTPUT); digitalWrite(32, LOW); digitalWrite(31, LOW); digitalWrite(30, LOW); } void writeDot(byte dot) { digitalWrite(9, dot); // decimal point - pin 9 on Arduino } void sevenSegWrite(byte digit) { byte pin = 2; // Arduino pin where the segment list starts for (byte segCount = 0; segCount < 7; ++segCount) { digitalWrite(pin, seven_seg_digits[digit][segCount]); ++pin; } } // displays digits from 9 to 0 void loop() { for (byte count = 0; count < 10; count++) { delay(1000); sevenSegWrite(count); } // delay(1000); }
true
b8bc98b97537575a994d98d23b96b9471b91e6dd
C++
Zugzwangs/Gomina
/src/gui/graphicshitboxitem.cpp
UTF-8
2,297
2.5625
3
[]
no_license
/*******************************************************/ // // /*******************************************************/ #include "graphicshitboxitem.h" #include <QPen> #include <QDebug> graphicsHitboxItem::graphicsHitboxItem(QGraphicsItem* parent) : QGraphicsRectItem(parent) { initialisation(); } graphicsHitboxItem::graphicsHitboxItem(qreal x, qreal y, qreal width, qreal height, QGraphicsItem * parent) : QGraphicsRectItem(x, y, width, height, parent) { initialisation(); } graphicsHitboxItem::graphicsHitboxItem(const QRectF &rect, QGraphicsItem* parent) : QGraphicsRectItem(rect, parent) { initialisation(); } void graphicsHitboxItem::initialisation() { GamePos = QPoint(0, 0); // hitbox => keep item invisible setPen( Qt::NoPen ); setBrush( QBrush(Qt::transparent) ); // set behavior setAcceptHoverEvents(true); setFlag( QGraphicsItem::ItemIsMovable, false); setFlag( QGraphicsItem::ItemIsSelectable, false); } void graphicsHitboxItem::hoverEnterEvent(QGraphicsSceneHoverEvent* event) { qDebug() << "graphicsHitboxItem::hoverEnterEvent()"; setBrush( QBrush(Qt::blue) ); QGraphicsRectItem::hoverEnterEvent(event); } void graphicsHitboxItem::hoverMoveEvent(QGraphicsSceneHoverEvent* event) { qDebug() << "graphicsHitboxItem::hoverMoveEvent()"; } void graphicsHitboxItem::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) { qDebug() << "graphicsHitboxItem::hoverLeaveEvent()"; setBrush( QBrush(Qt::transparent) ); QGraphicsRectItem::hoverLeaveEvent(event); } void graphicsHitboxItem::mousePressEvent(QGraphicsSceneMouseEvent * event) { if (event->button() == Qt::LeftButton) { event->accept(); qDebug() << "MOUSE PRESS EVENT ON HITBOX"; qDebug() << "HitBoxItemPos x=" << this->pos().x() << " y=" << this->pos().y(); qDebug() << "HitBoxItemScenePos x=" << this->scenePos().x() << " y=" << this->scenePos().y(); qDebug() << "GamePos is x=" << GamePos.x() << " y=" << GamePos.y(); emit clicked(GamePos); } else { event->ignore(); } } void graphicsHitboxItem::setGamePos(QPoint p) { GamePos = p; } QPoint graphicsHitboxItem::getGamePos() { return GamePos; } graphicsHitboxItem::~graphicsHitboxItem() { }
true
dae9e2ee0f74f5a31facb0128fc1ccf442e3a913
C++
DamonAknuh/Bmp2Excel-Image-Converter
/BMP2EXCEL.hpp
UTF-8
921
2.953125
3
[]
no_license
#ifndef __BMP2EXCEL_HPP__ #define __BMP2EXCEL_HPP__ //SECOND VERSION #include <iostream> #include <string> #include <vector> #include <sstream> #include <cstring> #include "Byte2Int.hpp" class triplet { public: triplet() { first = 0; second = 0; third = 0; } void make_triplet(int one, int two, int three) { first = one; second = two; third = three; } void set_first(int temp){ first = temp; } void set_second(int temp){ second = temp; } void set_third(int temp){ third = temp; } int get_first(){ return first; } int get_second(){ return second; } int get_third(){ return third; } private: int first; int second; int third; }; typedef std::vector <std::vector <triplet>> PIXEL_ARRAY; PIXEL_ARRAY Read_File(std::string Filename); void Write_Excel_File(PIXEL_ARRAY DATA, std::string Filename); #endif
true
227aa4fd1c452f6c121e368ba9675cd6a534561a
C++
codeAligned/acm-icpc-1
/archived/2014-NEERC-Northern/G.cc
UTF-8
558
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long LL; typedef pair<int, int> PII; int w, h; bool ok(int x1, int y1, int x2, int y2) { return x2 - x1 >= w && y2 - y1 >= h; } int main() { freopen("grave.in", "r", stdin); freopen("grave.out", "w", stdout); int x1, y1, x2, y2, x3, y3, x4, y4; scanf("%d%d%d%d", &x1, &y1, &x2, &y2); scanf("%d%d%d%d", &x3, &y3, &x4, &y4); scanf("%d%d", &w, &h); if (ok(x1, y1, x3, y2) | ok(x4, y1, x2, y2) | ok(x1, y4, x2, y2) | ok(x1, y1, x2, y3)) puts("Yes"); else puts("No"); return 0; }
true
e654a1c74fa113f015284669c32a15706b45aad0
C++
INTechSenpai/sumobot
/programmation/testPathfindingSimple/pathfinding.cpp
UTF-8
6,142
2.796875
3
[]
no_license
#include "pathfinding.h" #include <iostream> #include <math.h> Pathfinding::Pathfinding() {} Trajectory Pathfinding::computePath(Position start, Position pointIntermediaire, Position goal) { float xCentre, yCentre, rayonCourbure, distanceParcourue; Trajectory trajectoire; xCentre = -1*( (pointIntermediaire.y*(goal.y*goal.y - start.y*start.y + goal.x*goal.x - start.x*start.x ) + start.y*(-1*goal.y*goal.y - goal.x*goal.x + pointIntermediaire.x*pointIntermediaire.x ) + start.y*start.y*goal.y - pointIntermediaire.x*pointIntermediaire.x*goal.y + start.x*start.x*goal.y + pointIntermediaire.y*pointIntermediaire.y*(start.y - goal.y) ) / (2*pointIntermediaire.x*goal.y - 2*start.x*goal.y + (2*start.x - 2*goal.x)*pointIntermediaire.y + (2*goal.x - 2*pointIntermediaire.x )*start.y) ); yCentre = (pointIntermediaire.x*(goal.y*goal.y + goal.x*goal.x - start.x*start.x ) + start.x*(-1*goal.y*goal.y - goal.x*goal.x ) + (start.x - goal.x)*pointIntermediaire.y*pointIntermediaire.y + (goal.x - pointIntermediaire.x)*start.y*start.y + start.x*start.x*goal.x + pointIntermediaire.x*pointIntermediaire.x*(start.x - goal.x )) / (2*pointIntermediaire.x*goal.y - 2*start.x*goal.y + (2*start.x - 2*goal.x )*pointIntermediaire.y + (2*goal.x - 2*pointIntermediaire.x)*start.y); rayonCourbure = sqrt((start.x - xCentre)*(start.x - xCentre) + (start.y - yCentre)*(start.y - yCentre)); float valeurAcos1 = (start.x - xCentre)/rayonCourbure; float valeurAcos2 = (goal.x - xCentre)/rayonCourbure; std::cout << "valeurAcos1 : " << valeurAcos1 << std::endl; std::cout << "valeurAcos2 : " << valeurAcos2 << std::endl; if ( (valeurAcos1<-1)||(valeurAcos1>1)||(valeurAcos2<-1)||(valeurAcos2>1)) { return trajectoire; } distanceParcourue = rayonCourbure*(acos(valeurAcos1)-acos(valeurAcos2)); std::cout << "rayonCourbure : " << rayonCourbure << std::endl; std::cout << "distanceParcourue : " << distanceParcourue << std::endl; if (distanceParcourue < 0) { distanceParcourue *= -1; } UnitMove unitmove; unitmove.setBendRadiusMm(rayonCourbure); unitmove.setLengthMm(distanceParcourue); unitmove.setSpeedMm_S(350); trajectoire.push_back(unitmove); return trajectoire; } Trajectory Pathfinding::computePath(Position start, Position goal) { Trajectory trajectoire; UnitMove unitmove; unitmove.setSpeedMm_S(sqrt(start.xSpeed*start.xSpeed + start.ySpeed*start.ySpeed)); start.orientation = fmod(start.orientation,2*M_PI); goal.orientation = fmod(goal.orientation,2*M_PI); //rotation pure if ((start.x == goal.x)&&(start.y==goal.y)) { unitmove.stopAfterMove = true; unitmove.setBendRadiusMm(0); unitmove.setLengthRadians(fmod(start.orientation - goal.orientation,2*M_PI)); } //trajectoire droite else if ((start.orientation == goal.orientation)) { unitmove.stopAfterMove = false; unitmove.setBendRadiusMm(INFINITE_RADIUS); unitmove.setLengthMm(sqrt((start.x - goal.x)*(start.x - goal.x) + (start.y - goal.y)*(start.y - goal.y))); } //trajectoire courbe else { float rayonCourbure = sqrt((start.x - goal.x)*(start.x - goal.x) + (start.y - goal.y)*(start.y - goal.y)) / (2*cos( (M_PI/2) - fmod(start.orientation - goal.orientation,2*M_PI) / 2)); float longueurMvt = rayonCourbure*(start.orientation - goal.orientation); /* if (longueurMvt < 0) { longueurMvt *= -1; }*/ unitmove.stopAfterMove = false; unitmove.setBendRadiusMm(rayonCourbure); unitmove.setLengthMm(longueurMvt); } trajectoire.push_back(unitmove); std::cout << "R : " << unitmove.getBendRadiusMm() << std::endl; std::cout << "L : " << unitmove.getLengthMm() << std::endl; return trajectoire; } /* Trajectory Pathfinding::computePath(float rot, float rayonCourbure, float longueur) { Trajectory trajectoire; UnitMove rotation; UnitMove ligneCourbe; rotation.stopAfterMove = true; rotation.setBendRadiusMm(0); rotation.setLengthRadians(fmod(rot,2*M_PI)); rotation.setSpeedMm_S(sqrt(start.xSpeed*start.xSpeed + start.ySpeed*start.ySpeed)); trajectoire.push_back(rotation); ligneCourbe.stopAfterMove = false; ligneCourbe.setBendRadiusMm(rayonCourbure); ligneCourbe.setLengthMm(longueur); ligneCourbe.setSpeedMm_S(sqrt(start.xSpeed*start.xSpeed + start.ySpeed*start.ySpeed)); trajectoire.push_back(ligneCourbe); return trajectoire; }*/ Trajectory Pathfinding::computePathFoncerRobot(Position start, Position goal, float longueur) { Trajectory trajectoire; if ((fmod(goal.orientation - start.orientation,2*M_PI) > M_PI - 0.14)&& (fmod(goal.orientation - start.orientation,2*M_PI) < M_PI + 0.14)) { longueur *=-1; } float angleRotation = goal.orientation - start.orientation; while (angleRotation > M_PI/2) { angleRotation = angleRotation - M_PI; } while (angleRotation < -1*M_PI/2) { angleRotation = M_PI + angleRotation; } std::cout << "angleRotation : " << angleRotation << std::endl; std::cout << "longueur : " << longueur << std::endl; if (! ((angleRotation < 0.14)&&(-0.14 < angleRotation))) { UnitMove rotation; rotation.stopAfterMove = true; rotation.setBendRadiusMm(0); rotation.setSpeedMm_S(sqrt(start.xSpeed*start.xSpeed + start.ySpeed*start.ySpeed)); rotation.setLengthRadians(angleRotation); trajectoire.push_back(rotation); } else { UnitMove avancerDroit; avancerDroit.stopAfterMove = false; avancerDroit.setBendRadiusMm(INFINITE_RADIUS); avancerDroit.setLengthMm(longueur); avancerDroit.setSpeedMm_S(sqrt(start.xSpeed*start.xSpeed + start.ySpeed*start.ySpeed)); trajectoire.push_back(avancerDroit); } return trajectoire; }
true
fb4526d9dd4bd3d6999c7b5bc77870f863ddc80f
C++
Inyu/CCC-CCryptChat
/CCC-VS/Main.cpp
IBM852
770
2.625
3
[ "MIT" ]
permissive
#include <stdio.h> #include <conio.h> #include <time.h> void output(const char logpath[100]); struct User { char name[50]; time_t lastloginTimestamp; }; typedef struct User User; int main(void) { User test; const char logpath[100] = "testlog.txt"; const char key[100] = "rB880$561k9xs0n6Zk917d59F3R7e30$2L7674F1O53aVnhI3rS*!12QG899c6I265D784U822IRy#W175628Xw5p4v274DJg8c"; //KEY IN PLAINTEXT: MUCH SECRE, SUCH SAFE time(&test.lastloginTimestamp); printf("%lld\n", (long long)test.lastloginTimestamp); output(logpath); printf("\n\n ||END OF 0.0.2|| \n\n"); _getch(); return 1; } void output(const char logpath[100]) { FILE *log; char current; log = fopen(logpath, "r+t"); if (log != NULL) { current = fgetc(log); while (current != EOF) { fputc(current, stdout); current = fgetc(log); } } else printf("ERROR 001"); }
true
908e6d891c28048d085421e648761bde0edb982f
C++
BaomingRose/Algorithms
/day7/换肉.cpp
GB18030
859
2.765625
3
[]
no_license
/*׼m׼һǮԹԼ룬 n꣬iҪJ[i]⣬ ȫԻF[i]𣬵Ȼѡijֻһ֣ ܻö*/ #include<iostream> #include<algorithm> using namespace std; const int maxn = 1000 + 5; struct node { int j, f; double d; friend bool operator < (node a, node b) { return a.d > b.d; } } dp[maxn]; int main() { int m, n; cin >> m >> n; for(int i = 0; i < n; ++i) { cin >> dp[i].f >> dp[i].j; dp[i].d = dp[i].f * 1.0 / dp[i].j; } sort(dp, dp + n); double ans = 0; for(int i = 0; i < n; ++i) { if(m >= dp[i].j) { m -= dp[i].j; ans += dp[i].f; }else { ans += m * dp[i].d; break; } } printf("%.3f", ans); return 0; }
true
68730bd5db1263a5e13b6653389fc1f4daa3834b
C++
alexlambson/graphics-programming
/ASS_08/ASS_08/Terrain.h
UTF-8
809
2.75
3
[]
no_license
#pragma once #include <cstdlib> #include <vector> #include "Helpers.h" using namespace std; enum Color { RED, GREEN, BLUE }; enum TerrainType{ GROUND, WATER }; class Terrain{ public: Terrain(int x, int y, bool store = false); void Draw(TerrainType terrain); WorldSize size; double static GenerateHeight(double x, double y, TerrainType terrain); vector < vector<WorldPosition> > GroundPoints; vector < vector<WorldPosition> > WaterPoints; void GenerateTerrain(TerrainType terrain); void DrawMemory(TerrainType terrain); /* private: class point{ public: point(int x, int y, int z); void Draw(); Color mColor; ArrayPosition mArrayPos; WorldPosition mWorldPosition; }; //no need to store points //vector<vector<point>> points; */ }; double GenerateColor(double height, Color color);
true
46b1bd073190f97b33976323faae797362eba92f
C++
AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen
/GPU Pro5/06_Compute/Object-order Ray Tracing for Fully Dynamic Scenes/beMath/header/beMath/beSphere.h
UTF-8
842
2.546875
3
[ "MIT", "BSD-3-Clause" ]
permissive
/*****************************************************/ /* breeze Engine Math Module (c) Tobias Zirr 2011 */ /*****************************************************/ #pragma once #ifndef BE_MATH_SPHERE #define BE_MATH_SPHERE #include "beMath.h" #include "beSphereDef.h" #include "beVector.h" #include "beMatrix.h" namespace beMath { /// Transforms the given sphere. template <class Component, size_t Dimension> LEAN_INLINE sphere<Component, Dimension> mulh(const sphere<Component, Dimension> &left, const matrix<Component, Dimension + 1, Dimension + 1> &right) { float maxScaleSq = 0.0f; for (size_t i = 0; i < Dimension; ++i) maxScaleSq = max( lengthSq( vector<Component, Dimension>(right[i]) ), maxScaleSq ); return sphere<Component, Dimension>( mulh(left.center, right), left.radius * sqrt(maxScaleSq) ); } } // namespace #endif
true
551913160e620f071bfa0fe55b4074cb673ae907
C++
jmg217/maxwell_dev
/dot_prod_test.cpp
UTF-8
563
3.3125
3
[]
no_license
#include <iostream> #include <vector> #include <stdio.h> #include <math.h> double inner_product(int N, std::vector<double>& first_vector, std::vector<double>& second_vector); int main(){ int N=10000000; std::vector<double> first_vector(N); std::vector<double> second_vector(N); for(int i=0 ; i < N ; i++) { //x_host[i]=first_vector[i]; //y_host[i]=second_vector[i]; first_vector[i] = sin(i*0.013); second_vector[i] = cos(i*0.019); } double dot=inner_product(N, first_vector, second_vector); std::cout<<dot<<std::endl; return 0; }
true
ee22802421271ba63948f46ce0207a82df4079b3
C++
Br3nder/ADS_lab2
/SortAlgorithms.cpp
UTF-8
3,534
3.71875
4
[]
no_license
#include <iostream> using namespace std; bool isSorted(int* array, int size) { for (int i = 0; i < size - 1; i++) if (array[i] > array[i + 1]) return false; return true; } void shuffle(int *array, int size) { for (int i = 0; i < size; i++) swap(array[i], array[rand() % size]); } void showArray(int* array, int size) { for (int i = 0; i < size; i++) { cout << array[i] << " "; } } void showArray(char* array, int size) { for (int i = 0; i < size; i++) { cout << array[i] << " "; } } void quickSort(int* array, int first, int last) { if (first < last) { int left = first, right = last, pivot = array[(left + right) / 2]; do { while (array[left] < pivot) left++; while (array[right] > pivot) right--; if (left <= right) { int tmp = array[left]; array[left] = array[right]; array[right] = tmp; left++; right--; } } while (left <= right); quickSort(array, first, right); quickSort(array, left, last); } } void insertionSort(int* array, int size) { int tmp, item; // last element for (int counter = 1; counter < size; counter++) { tmp = array[counter]; item = counter - 1; // save prev element index while (item >= 0 && array[item] > tmp) { array[item + 1] = array[item]; array[item] = tmp; item--; } } } void countingSort(char* array, int size) { char max = 0; for (int i = 0; i < size; i++) if (array[i] > max) max = array[i]; char* arr2 = new char[max + 1]; for (int i = 0; i < max + 1; i++) arr2[i] = 0; for (int i = 0; i < size; ++i) { ++arr2[array[i]]; } int b = 0; for (int i = 0; i < max + 1; ++i) { for (int j = 0; j < arr2[i]; ++j) { array[b++] = i; } } } int binarySearch(int *array, int size, int num) { int left = -1; int middle; int right = size - 1; // left & right searching border while (right - left > 1) { middle = (left + right) / 2; // middle of searching zone if (array[middle] >= num) right = middle; else left = middle; } if (array[right] == num) return 1; else return 0; } void bogoSort(int *array, int size) { int i = 1; while (!isSorted(array, size)) { /*if (i % 10000 == 0) { system("cls"); cout << "I'm trying... It's " << i << " attempt!\n"; }*/ shuffle(array, size); i++; } //cout << "I have done this with " << i << " attempts\n"; } bool isSort(int* array, int size) { for (int i = 0; i < size - 1; i++) if (array[i + 1] < array[i]) return false; return true; } void fillArrayByRandom(int* array, int size, int maxNum) { for (int i = 0; i < size; i++) array[i] = rand() % maxNum; } void fillCharArrayByRandom(char* array, int size, int maxNum) { for (int i = 0; i < size; i++) array[i] = rand() % maxNum; } bool isSortChar(char* array, int size) { for (int i = 0; i < size - 1; i++) if (array[i + 1] < array[i]) return false; return true; }
true
7d6d37bde12b8b4392cde49cad740c22eec34e3f
C++
shahin-fotowat/College-Tour
/collegetour-master/src/distance.h
UTF-8
1,035
3.484375
3
[]
no_license
#ifndef DISTANCE_H #define DISTANCE_H #include "college.h" /** * @brief The Distance class * Represents two colleges and their distances */ class Distance { private: College startCollege; College endCollege; int distance; public: Distance(); /** * @brief Distance constructor * @param initStartCollege Starting College * @param initEndCollege Ending College * @param initDistance Distance between starting and ending College */ Distance(College initStartCollege, College initEndCollege, int initDistance); /** * @brief getStartCollege * @return Starting College */ College getStartCollege() const; /** * @brief getEndCollege * @return Ending College */ College getEndCollege() const; /** * @brief getDistance * @return Distance between the starting and ending College */ int getDistance() const; void setDistance(College initStartCollege, College initEndCollege, int initDistance); }; #endif // DISTANCE_H
true
c1b92821e058c56c7fa0b594f3482e38612b77ff
C++
tnakaicode/jburkardt
/mpi/sum_mpi.cpp
UTF-8
4,228
2.546875
3
[]
no_license
# include <cstdlib> # include <iostream> # include <iomanip> # include <ctime> # include <mpi.h> using namespace std; int main ( int argc, char *argv[] ); void timestamp ( ); //****************************************************************************80 int main ( int argc, char *argv[] ) //****************************************************************************80 // // Purpose: // // MAIN is the main program for SUM. // // Discussion: // // SUM is an example of using the MPI message passing interface library. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 16 June 2016 // // Author: // // John Burkardt // // Reference: // // Forrest Hoffman, // Message Passing with MPI and PVM, // LINUX Magazine, // Volume 4, Number 4, April 2002, pages 38-41, 63. // // William Gropp, Ewing Lusk, Anthony Skjellum, // Using MPI: Portable Parallel Programming with the // Message-Passing Interface, // Second Edition, // MIT Press, 1999, // ISBN: 0262571323. // { # define N 100 double array[N]; int i; int id; int p; double PI = 3.141592653589793238462643; double seed; MPI_Status status; double sum; double sum_all; int tag; // // Initialize MPI. // MPI_Init ( &argc, &argv ); // // Get the number of processes. // MPI_Comm_size ( MPI_COMM_WORLD, &p ); // // Determine the rank of this process. // MPI_Comm_rank ( MPI_COMM_WORLD, &id ); // // Say hello. // if ( id == 0 ) { timestamp ( ); cout << "\n"; cout << "SUM - Master process:\n"; cout << " C++ version\n"; cout << "\n"; cout << " An MPI example program.\n"; cout << " The master process computes some coefficients,\n"; cout << " sends them to each worker process, which sums them.\n"; cout << "\n"; cout << " Compiled on " << __DATE__ << " at " << __TIME__ << ".\n"; cout << "\n"; cout << " The number of processes available is " << p << "\n"; } // // The master process initializes the array. // if ( id == 0 ) { seed = 1.2345; for ( i = 0; i < N; i++ ) { array[i] = ( double ) i * seed * PI; } } // // The master process broadcasts the computed initial values // to all the other processes. // MPI_Bcast ( array, N, MPI_DOUBLE, master, MPI_COMM_WORLD ); // // Each process adds up its entries. // sum = 0.0; for ( i = 0; i < N; i++ ) { sum = sum + array[i] * ( double ) id; } cout << "\n"; cout << "SUM - Process " << id << ":\n"; cout << " My contribution to the sum is " << sum << "\n"; // // Each worker process sends its sum back to the master process. // if ( id != 0 ) { MPI_Send ( &sum, 1, MPI_DOUBLE, master, 1, MPI_COMM_WORLD ); } else { sum_all = sum; for ( i = 1; i < p; i++ ) { tag = 1; MPI_Recv ( &sum, 1, MPI_DOUBLE, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD, &status ); sum_all = sum_all + sum; } } if ( id == 0 ) { cout << "\n"; cout << "SUM - Master process:\n"; cout << " The total sum is " << sum_all << "\n"; } // // Terminate MPI. // MPI_Finalize ( ); // // Terminate. // if ( id == 0 ) { cout << "\n"; cout << "SUM - Master process:\n"; cout << " Normal end of execution.\n"; cout << "\n"; timestamp ( ); } return 0; # undef N } //****************************************************************************80 void timestamp ( ) //****************************************************************************80 // // Purpose: // // TIMESTAMP prints the current YMDHMS date as a time stamp. // // Example: // // 31 May 2001 09:45:54 AM // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 08 July 2009 // // Author: // // John Burkardt // // Parameters: // // None // { # define TIME_SIZE 40 static char time_buffer[TIME_SIZE]; const struct std::tm *tm_ptr; size_t len; std::time_t now; now = std::time ( NULL ); tm_ptr = std::localtime ( &now ); len = std::strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm_ptr ); std::cout << time_buffer << "\n"; return; # undef TIME_SIZE }
true
94cf2d08db6105b98b2ea4c01d18eb39237f45ec
C++
237K/DataStructure
/List_ArrayList.cpp
UTF-8
2,465
3.65625
4
[]
no_license
// // OS Windows // 2019.02.23 // // [자료구조] // <1. Linked List> // 1) 배열 기반 리스트 // #include <iostream> #include <cstdio> using namespace std; const static int LIST_LEN = 100; template <typename T> class List { private: T arr[LIST_LEN]; int NumOfData; int CurPosition; public: void ListInit(List *plist); void ListInsert(List* plist, T data); int ListFirst(List* plist, T* pdata); int ListNext(List* plist, T* pdata); T ListRemove(List* plist); int ListCount(List* plist); }; template <typename T> void List<T>::ListInit(List *plist) { (plist->NumOfData) = 0; (plist->CurPosition) = -1; } template <typename T> void List<T>::ListInsert(List* plist, T data) { if (plist->NumOfData >= LIST_LEN) { puts("더 이상 저장할 수 없습니다.\n"); return; } (plist->arr[plist->NumOfData]) = data; (plist->NumOfData++); } template <typename T> int List<T>::ListFirst(List* plist, T* pdata) { if (plist->NumOfData == 0) return 0; (plist->CurPosition) = 0; *pdata = plist->arr[0]; return 1; } template <typename T> int List<T>::ListNext(List *plist, T* pdata) { if (plist->CurPosition >= (plist->NumOfData) - 1) return 0; (plist->CurPosition)++; *pdata = plist->arr[plist->CurPosition]; return 1; } template <typename T> T List<T>::ListRemove(List* plist) { int temp_pos = plist->CurPosition; int num = plist->NumOfData; T temp_data = plist->arr[temp_pos]; for (int i = temp_pos; i < num; ++i) plist->arr[i] = plist->arr[i + 1]; (plist->CurPosition)--; (plist->NumOfData)--; return temp_data; } template <typename T> int List<T>::ListCount(List* plist) { return plist->NumOfData; } int main(int argc, char** argv) { List<int> list; list.ListInit(&list); list.ListInsert(&list, 11); list.ListInsert(&list, 22); list.ListInsert(&list, 33); printf("Number Of Data : %d\n", list.ListCount(&list)); int data; if (list.ListFirst(&list, &data)) { printf("%d ", data); while (list.ListNext(&list, &data)) printf("%d ", data); } printf("\n\n"); printf("22찾아서 삭제\n\n"); if (list.ListFirst(&list, &data)) { if (data == 22) list.ListRemove(&list); while (list.ListNext(&list, &data)) { if (data == 22) list.ListRemove(&list); } } printf("Number Of Data : %d\n", list.ListCount(&list)); if (list.ListFirst(&list, &data)) { printf("%d ", data); while (list.ListNext(&list, &data)) printf("%d ", data); } printf("\n\n"); return 0; }
true
77423df72d86b42a7b6dfd07f2de6034a2c95948
C++
rogers140/leetcode-oj
/String to Integer/Solution.cpp
UTF-8
1,506
3.28125
3
[]
no_license
#include <stdio.h> #include <iostream> #include <string.h> using namespace std; class Solution { public: int atoi(const char *str) { int length = strlen(str); int sign = 1; int start = 0; for (int i = 0; i < length; i++) { if (str[i] == ' ' || str[i] == 0x9) { start++; } else { break; } } if (str[start] == '-') { sign = -1; start++; } else if (str[start] == '+') { sign = 1; start ++; } unsigned int result = 0; for (int i = start; i < length; i++) { if (isdigit(str[i])) { int digit = str[i] - '0'; if (INT_MAX / 10 >= result) result *= 10; else return sign == -1 ? INT_MIN : INT_MAX; if (INT_MAX - digit >= result) result += digit; else return sign == -1 ? INT_MIN : INT_MAX; } else { //illegal input break; } } return sign*((int)result); } }; int main(int argc, char const *argv[]) { Solution *s = new Solution(); const char *test1 = "1"; const char *test2 = "123 456"; const char *test3 = " 10522545459"; const char *test4 = " -0012a42"; const char *test5 = " +004500"; const char *test6 = "30000000000000000"; cout<<"test1 : "<<s->atoi(test1)<<endl; cout<<"test2 : "<<s->atoi(test2)<<endl; cout<<"test3 : "<<s->atoi(test3)<<endl; cout<<"test4 : "<<s->atoi(test4)<<endl; cout<<"test5 : "<<s->atoi(test5)<<endl; cout<<"test6 : "<<s->atoi(test6)<<endl; return 0; }
true
a4e00101c1b14b52059f67b0a0e52b7937bb50b2
C++
josecarreno/Solitariopp
/solitario_0_3/VecJugadores.cpp
UTF-8
2,431
2.9375
3
[]
no_license
#include "StdAfx.h" #include "VecJugadores.h" CVecJugadores::CVecJugadores(void) { N = 0; leeDeArchivo(); if ( N == 0 ) vec = NULL; } CVecJugadores::~CVecJugadores(void) { if (N>0) { guardaEnArchivo(); for(int i=0; i<N; i++) { delete vec[i]; } delete [] vec; } } void CVecJugadores::leeDeArchivo() { FILE * archivo = fopen("jugadores.dat", "rb"); if ( archivo != NULL ) { fread(&N, sizeof(N), 1, archivo); vec = new CJugador *[N]; for(int i=0; i<N; i++) { CJugador * aux = new CJugador(); aux->leeDeArchivo(archivo); vec[i] = aux; } fclose(archivo); } } void CVecJugadores::guardaEnArchivo() { FILE * archivo = fopen("jugadores.dat", "wb"); if (archivo != NULL) { fwrite(&N, sizeof(N), 1 ,archivo); for(int i=0; i<N; i++) vec[i]->guardaEnArchivo(archivo); fclose(archivo); } } int CVecJugadores::getN() { return N; } CJugador * CVecJugadores::getJugEnPos(int pos) { return vec[pos]; } void CVecJugadores::agregarJugador(CJugador *nuevo) { CJugador* *temp = new CJugador *[N+1]; for(int i=0; i<N; i++) temp[i] = vec[i]; delete [] vec; vec = temp; vec[N] = new CJugador(nuevo->getMovimientos(), nuevo->getTiempo(), nuevo->getCartasIniciales()); N++; } void CVecJugadores::eliminarUltimo() { if (N <= 0) return; CJugador* *temp = new CJugador *[N-1]; for(int i=0; i<N-1; i++) temp[i] = vec[i]; delete vec[N-1]; delete [] vec; vec = temp; N--; } bool CVecJugadores::verificar_mejor_tiempo(int tiempo) { if (N < 5) return true; if (tiempo < vec[N-1]->getTiempo()) return true; return false; } void CVecJugadores::ordenar() { int k; CJugador * aux; for (int i=1; i<N; i++) { aux = vec[i]; k = i-1; while (k >= 0 && aux->getTiempo() < vec[k]->getTiempo()) { vec[k+1] = vec[k]; k--; } vec[k+1] = aux; } } void CVecJugadores::dibujar(Graphics ^g) { g->DrawString("Tiempo", gcnew Font("Calibri", 14),Brushes::White, 45, 15); g->DrawString("Movimientos", gcnew Font("Calibri", 14),Brushes::White, 125, 15); for(int i=0; i<N ;i++) { g->DrawString(i+1 + ". ", gcnew Font("Calibri", 14),Brushes::White, 15, 45 + i *15); g->DrawString(vec[i]->getMin().ToString() + " : " + vec[i]->getSeg().ToString(), gcnew Font("Calibri", 14),Brushes::White, 55, 45 + i *15); g->DrawString(vec[i]->getMovimientos().ToString(), gcnew Font("Calibri", 14),Brushes::White, 175, 45 + i *15); } }
true
3650a76b907da929a9120f7167773294ba515eed
C++
Saadmalik16/OOP
/1st assignment ch no 2 Exercise problems/2.20.cpp
UTF-8
512
3.78125
4
[]
no_license
#include <iostream> using namespace std; int main() { int radius, diameter; double constantValue, circumference, area; cout << "Radius of the circle: "; cin >>radius ; diameter = radius * 2; cout << "The diameter is: "<< diameter << "\n"; constantValue = 3.14159; circumference = constantValue * diameter; cout<< "The circumference is: "<< circumference<< "\n"; area = constantValue * radius * radius; cout <<"The area of the circle is: " <<area ; return 0; }
true
64a622dfbdf45146796fe9e0eb7e7a56ae5180cd
C++
hanrick2000/LeetCode-7
/Power of Two/Method.cpp
UTF-8
356
3.21875
3
[]
no_license
//Given an integer, write a function to determine if it is a power of two. // //傻逼题 class Solution { public: bool isPowerOfTwo(int n) { int mask = 1; for(int i = 0; i < 31; ++i) { if(n == mask) return true; mask<<=1; } return false; } };
true
a835396c317ff3602de739f8536b3d489d6da69a
C++
NorbertNiebieski/Public_Transport_System
/Przystanki.h
WINDOWS-1250
1,836
3.203125
3
[]
no_license
#ifndef Przystanki_H #define Przystanki_H #include <iostream> #include <vector> #include <string> #include "Line.h" #include <map> using namespace std; class Przystanek { private: string m_bus_stop_name; bool m_on_demand; bool m_frist_zone; vector<string> m_line_list; public: //Konstruktor domylny Przystanek(string bus_stop_name = " ", bool on_deman = 0, bool frist_zone = 0) : m_bus_stop_name{ bus_stop_name }, m_on_demand{ on_deman }, m_frist_zone{frist_zone} {} //gettery i settery poszczegolnych zmienych string get_bus_stop_name() { return m_bus_stop_name; } void set_bus_stop_name(const string& bus_stop_name) { m_bus_stop_name = bus_stop_name; } bool get_on_demand() { return m_on_demand; } void set_on_demand(bool on_demand) { m_on_demand = on_demand; } bool get_frist_zone() { return m_frist_zone; } void set_frist_zone(bool frist_zone) { m_frist_zone = frist_zone; } vector<string> get_line_list() { return m_line_list; } void set_line_list(vector<string> bus_line_list) { m_line_list = bus_line_list; } void add_line_list(string line_number) { m_line_list.push_back(line_number); } //funkcja wywietlajca obiekty klasy Przystanek w konsolli void show_up( string end_bus_stop) { cout << m_bus_stop_name; if (m_on_demand) { cout << " Na zadanie"; } if (!m_frist_zone) { cout << " Uwaga, przystanek w drugiej strefie!"; } cout << endl << endl; for (unsigned int i = 0; i < m_line_list.size(); i++) { vector<string> wektor; wektor = lines[m_line_list[i]+end_bus_stop]->get_bus_stop_list(); cout << i+1 << ". " << m_line_list[i] << " -> " << wektor[wektor.size()-1] << endl; } } }; // ownik przechowujcy obiekty klasy przystanek map<string, Przystanek*> bus_stops; #endif // !Przystanki_h
true
d28bc0f984282ba21669d01e2ed1b4ba784b4465
C++
yottacto/competitive-programming
/poj/1947.cc
UTF-8
1,169
2.703125
3
[]
no_license
// ml:run = $bin < input // ml:std = c++03 #include <iostream> #include <algorithm> #include <vector> int const inf = 1 << 29; int const maxn = 200; int f[maxn][maxn]; int n, size; int ans = inf; std::vector<std::vector<int> > g; void add_edge(int x, int y) { g[x].push_back(y); g[y].push_back(x); } void dp(int u, int parent) { f[u][1] = 0; for (int t = 0; t < int(g[u].size()); t++) { int v = g[u][t]; if (v == parent) continue; dp(v, u); for (int i = size; i >= 1; i--) { int tmp = f[u][i] + 1; for (int j = 1; j < i; j++) tmp = std::min(tmp, f[u][i - j] + f[v][j]); f[u][i] = tmp; } } } int main() { std::ios::sync_with_stdio(false); std::cin >> n >> size; g.resize(n + 1); for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) f[i][j] = inf; for (int i = 1; i < n; i++) { int x, y; std::cin >> x >> y; add_edge(x, y); } dp(1, 0); int ans = f[1][size]; for (int i = 2; i <= n; i++) ans = std::min(ans, f[i][size] + 1); std::cout << ans << "\n"; }
true
4c389119e8c348abfa8f1dfc9985f12f60753432
C++
lmh760008522/ProgrammingExercises
/北大推免10题/2018软件考试/g.cpp
GB18030
1,057
3
3
[]
no_license
//С /* ĸPѸ·R RУ id id ·ij p=0 50㣬100 */ #include<cstdio> #include<vector> #include<algorithm> using namespace std; typedef struct node{ int a,b; int len; }; bool comp(node a1,node a2){ if(a1.len<a2.len){ return true; } return false; } int main(){ int p,r; scanf("%d",&p); while(p!=0){ scanf("%d",&r); if(r==0){ printf("0\n"); scanf("%d %d",&p,&r); continue; } vector<node> v; v.clear(); for(int i=0;i<r;i++){ int x,y,length; scanf("%d %d %d",&x,&y,&length); node temp; temp.a=x, temp.b=y, temp.len=length; v.push_back(temp); } sort(v.begin(),v.end(),comp); int ans=0; bool visit[50]={false}; for(int i=0;i<v.size();i++){ if(visit[ v[i].a ] == true && visit[ v[i].b ] == true){ continue; }else{ ans += v[i].len; visit[ v[i].a ] = true; visit[ v[i].b ] = true; } } printf("%d\n",ans); scanf("%d",&p); } return 0; }
true
2134c47774081e92cc2ddcc11d5e6673358afede
C++
danielkrupinski/GOESP
/GOESP/Linux/LinuxFileMap.h
UTF-8
597
2.9375
3
[ "MIT" ]
permissive
#pragma once #include <cstddef> #include <sys/mman.h> class LinuxFileMap { public: LinuxFileMap(void* address, std::size_t length, int protection, int flags, int fileDescriptor, off_t offset) : map{ mmap(address, length, protection, flags, fileDescriptor, offset) }, length{ length } {} [[nodiscard]] bool isValid() const noexcept { return map != MAP_FAILED; } [[nodiscard]] void* get() const noexcept { return map; } ~LinuxFileMap() { munmap(map, length); } private: void* map = MAP_FAILED; std::size_t length = 0; };
true
7065cc3dc271c7ebd2eeffe6c8295e323266cd03
C++
7NGU/Compiler
/Lexical_Analyzer.cpp
UTF-8
4,582
2.734375
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_LINE 255 #define Key "KETWORD_END" struct opt{ char att[MAX_LINE]; int spe; }; opt analyze(char *input); void pop(char *str, int x); void push(); int isDigit(char x); int isLetter(char x); int isCharacter(char x); int isSpace(char x); char word[MAX_LINE]; int n, i; static char Reserved[][15]={"while", "if", "else", "int", Key}; static int Reserves_num[] = {20, 17, 15, 5}; static char Character[][15] = {"+", "-", "*", "/", "%", "=", ">", "<", "!", "(", ")", ";", "{", "}", "[", "]", ",",Key}; static int Character_num[] = {41, 42, 43, 44, 45, 46, 47, 49, 55, 81, 82, 84, 86, 87, 88, 89, 90}; static char Character_double[][15] = {">=", "<=", "==", "!=", "&&", "||", "++", "--", Key}; static int Character_double_num[] = {48, 50, 51, 52, 53, 54, 56, 57}; int isSpace(char x){ if(x == 32){ return 1; } else{ return 0; } } int isLetter(char x){ if((x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z')){ return 1; } else{ return 0; } } int isCharacter(char x){ if((x >= '0' && x <= '9') || (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') || x < 33 || x == 127){ return 0; } else{ return 1; } } int isDigit(char x){ if(x >= '0' && x <= '9'){ return 1; } else{ return 0; } } void pop(char *str, int x){ word[n++] = str[x]; } void push(){ word[--n] = '\0'; } struct opt analyze(char *input){ //puts(input); struct opt res; //unsigned long length_s = strlen(input); //for(int i = 0; i < length_s; i++){ if(isLetter(input[i])){ n = 0; do{ pop(input, i); i++; }while((isLetter(input[i]) || isDigit(input[i])) && !isSpace(input[i])); //判断是否为保留字符 int num = 0; while(strcmp(Reserved[num], Key)){ if(!strcmp(Reserved[num], word)){ //printf("<%d, ->\n", Reserves_num[num]); res.spe = Reserves_num[num]; strcpy(res.att, "-"); i--; memset(word, '\0', MAX_LINE); return res; } else{ num++; } } { //printf("<111, %s>\n", word); res.spe = 111; strcpy(res.att, word); i--; memset(word, '\0', MAX_LINE); return res; } } else if(isDigit(input[i])){ n = 0; do{ pop(input, i); i++; }while(isDigit(input[i])); //printf("<100, %s>\n", word); res.spe = 100; strcpy(res.att, word); i--; memset(word, '\0', MAX_LINE); return res; } else if(isCharacter(input[i])){ n = 0; int num = 0; pop(input, i); if(!isCharacter(input[i+1])){ while(1){ if(!strcmp(Character[num], word)){ //printf("<%d, ->\n", Character_num[num]); res.spe = Character_num[num]; strcpy(res.att, "-"); memset(word, '\0', MAX_LINE); return res; } else{ num++; } } } else{ pop(input, i+1); while(strcmp(Character_double[num], Key)){ if(!strcmp(Character_double[num], word)){ //printf("<%d, ->\n", Character_double_num[num]); res.spe = Character_double_num[num]; strcpy(res.att, "-"); i++; memset(word, '\0', MAX_LINE); return res; } else{ num++; } } { push(); num = 0; while(1){ if(!strcmp(Character[num], word)){ //printf("<%d, ->\n", Character_num[num]); res.spe = Character_num[num]; strcpy(res.att, "-"); memset(word, '\0', MAX_LINE); return res; } else{ num++; } } //printf("<%d, ->\n", Character_num[num]); } } } else { i++; res = analyze(input); } return res; //} }
true
7d3e42b372834379f09948ff6d2ac574d4619d1a
C++
Ervie/Danmaku
/Implementacja/Danmaku/StageConst.h
WINDOWS-1250
1,010
2.625
3
[]
no_license
#pragma once /// <summary> /// Przestrze staych /// </summary> namespace StageConst { /// <summary> /// Stae wykorzystywane w grze /// </summary> static struct StageConsts { //// ==== STAE static const unsigned short BUTTON_NUM = 2; static const unsigned short TEX_NUM = 3; static const unsigned short STAGE_POS_X = 63; static const unsigned short STAGE_POS_Y = 32; static const unsigned short STAGE_WIDTH = 614; static const unsigned short STAGE_HEIGHT = 706; static const unsigned short SCORE_PADDING = 10; static const unsigned short GRAZE_DISTANCE = 10; // wciganie bonusw na 1/5 wysokoci od gry static const unsigned short BONUS_VACUUM_Y = static_cast<short>((STAGE_POS_Y + STAGE_HEIGHT) * 1.0f / 5.0f); static const unsigned short AVATAR_NUMBER = 4; static const unsigned short GAME_POS_X = 0; static const unsigned short GAME_POS_Y = 0; static const unsigned short GAME_WIDTH = 1024; static const unsigned short GAME_HEIGHT = 768; } Consts; }
true
13ab842485a0bd4b90700711cdca6f119538577b
C++
gpevnev/cplusplus-2017
/homework/2nd term/2/printer.cpp
UTF-8
1,904
3.203125
3
[]
no_license
// // printer.cpp // ASCII Printer // // Created by Greg Pevnev on 16/03/2017. // Copyright © 2017 Greg Pevnev. All rights reserved. // #include "printer.hpp" void Printer::putCharacter(char c) { line.push_back(c); } void Printer::putInteger(int i) { string number; if(i < 0) { putCharacter('-'); i *= -1; } if( i == 0) { putCharacter('0'); } while (i != 0) { number.push_back('0' + (i % 10)); i /= 10; } reverse(number.begin(), number.end()); line.append(number); } void Printer::print() { vector<string> ASCII = translateToASCII(); for(int j = 0; j < ASCII_HEIGHT; ++j) { cout << ASCII[j] << endl; } } void Printer::clear() { line.clear(); } vector<string> Printer::translateToASCII() { vector<string> result(ASCII_HEIGHT); for(int i = 0; i < ASCII_HEIGHT; ++i) { for(size_t j = 0; j < line.size(); ++j) { int letNumber; switch(line[j]) { case '+': letNumber = 10; break; case '-': letNumber = 11; break; case '(': letNumber = 12; break; case ')': letNumber = 13; break; case '*': letNumber = 14; break; case '/': letNumber = 15; break; default: letNumber = line[j] - '0'; } result[i].append(symbols[letNumber][i]); } } return result; }
true
f48e3f4e2a248b1df6cc859ea06efede9d9e1f09
C++
Lovepreet-Singh-ACET/Data-Strucutres-cpp
/arrays/binarySearch.cpp
UTF-8
685
3.046875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int binarySearch(int arr[], int size, int key){ int s = 0; int e = size; while (s <= e) { int mid = (s+e)/2; if (arr[mid] == key){ return mid; }else if (arr[mid] < key){ s = mid +1; }else{ e = mid -1; } } return -1; } int main(){ #ifndef ONLINE_JDUGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n; cin >> n; int array[n]; for(int i =0; i < n; i++){ cin>>array[i]; } int key = 10; cout << binarySearch(array, n, key); return 0; }
true
b56e7f03d949fdf844452d443f615741ba08c677
C++
Lil-Lexus/rrrrrrrr
/ConsoleApplication5/ConsoleApplication5.cpp
UTF-8
588
2.984375
3
[]
no_license
// ConsoleApplication5.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> using namespace std; int main() { const int n = 10; double m[n]{ 1, 2, 5, 6, -1, 4, 5, 5, -8, -10 }; int indlast; double sum = 0; for (int i = n - 1; i > 0; i--) { if (m[i] > 0) { indlast = i; i = 0; } } for (int i = 0; i < indlast; i++) { sum += m[i]; } for (int i = 0; i < n; i++) { cout << m[i] << " "; } cout << endl; cout << sum; }
true
a260a4aebe1c72cb581ef618e52abb1c0bc1bbf0
C++
volsungdenichor/cpp_essentials
/include/cpp_essentials/core/detail/repeat_iterator.hpp
UTF-8
1,621
2.9375
3
[]
no_license
#ifndef CPP_ESSENTIALS_CORE_DETAIL_REPEAT_ITERATOR_HPP_ #define CPP_ESSENTIALS_CORE_DETAIL_REPEAT_ITERATOR_HPP_ #pragma once #include <cpp_essentials/cc/cc.hpp> #include <cpp_essentials/core/iterator_facade.hpp> #include <cpp_essentials/core/detail/iterator_func_helper.hpp> namespace cpp_essentials::core { namespace detail { template <class T> class repeat_iterator : public core::iterator_facade < repeat_iterator<T> , std::random_access_iterator_tag , const T&> { public: using base_type = core::iterator_facade < repeat_iterator<T> , std::random_access_iterator_tag , const T&>; INHERIT_ITERATOR_FACADE_TYPES(base_type) repeat_iterator() = default; repeat_iterator(T value, int index) : _value{ std::move(value) } , _index{ index } { } reference ref() const { return _value; } pointer ptr() const { return &_value; } void inc() { ++_index; } void dec() { --_index; } void advance(difference_type offset) { _index += offset; } bool is_equal(const repeat_iterator& other) const { return _index == other._index; } bool is_less(const repeat_iterator& other) const { return _index < other._index; } difference_type distance(const repeat_iterator& other) const { return other._index - _index; } private: T _value; int _index; }; } /* namespace detail */ } /* namespace cpp_essentials::core */ #endif /* CPP_ESSENTIALS_CORE_DETAIL_REPEAT_ITERATOR_HPP_ */
true
acbef5b504820945d55bbc146201c2faf3ebf282
C++
abhijeetgu/LPMNOIDA11JUNE
/Lecture-8/ReadANumberAndString.cpp
UTF-8
266
2.921875
3
[]
no_license
#include <iostream> using namespace std; int main(){ int n; char a[100]; // Read number cin>>n; // cin.get(); // ' ' or '\n' will not get stored i.e. ignored cin.ignore(); // Read string cin.getline(a,100); cout<<n<<endl; cout<<a<<endl; return 0; }
true
e9aad3f4832bebb7a8ac9517224a15a380f2c8c4
C++
krishauser/KrisLibrary
/math/sample.h
UTF-8
2,252
3.34375
3
[]
permissive
#ifndef MATH_SAMPLE_H #define MATH_SAMPLE_H #include <vector> /** @file math/sample.h * @brief Functions for random sampling of various sets. */ namespace Math { /** @addtogroup Math */ /*@{*/ struct Interval; struct ClosedIntervalSet; /** @brief Samples an integer with weighted probability. * * The probability of sampling integer i in [0,n) is wi / W * where W = sum of all wi. */ int WeightedSample(const std::vector<Real>& weights); /// Same as above, but the sum of all weights, W, is provided. int WeightedSample(const std::vector<Real>& weights,Real totWeight); /// Same as above, but the array stores cumulative weights (i.e. partial sums) /// O(log n) algorithm int CumulativeWeightedSample(const std::vector<Real>& partialSumWeights); /** @brief Allocates total samples within the buckets in num, roughly * evenly. An O(n) algorithm where n is the number of buckets. * * Specifically, this allocates at least floor(total/n) samples to each bucket, * then distributes the remaining total-n*floor(total/n) such that no bucket * receives more than 1 extra sample. */ void RandomAllocate(std::vector<int>& num,size_t total); /// Same as above, but with weights. void RandomAllocate(std::vector<int>& num,size_t total,const std::vector<Real>& weights); /// Uniformly samples the given intervals Real Sample(const Interval& s); /// Uniformly samples the interval set Real Sample(const ClosedIntervalSet& s); /// Uniform distribution on boundary of a circle with radius r void SampleCircle(Real r, Real& x, Real& y); /// Uniform distribution inside a circle with radius r void SampleDisk(Real r, Real& x, Real& y); /// Uniform distribution in the triangle whose vertices are (0,0),(1,0),(0,1) void SampleTriangle(Real& x, Real& y); /// Uniform distribution on boundary of a sphere with radius r void SampleBall(Real r, Real& x, Real& y, Real& z); /// Uniform distribution inside a sphere with radius r void SampleSphere(Real r, Real& x, Real& y, Real& z); /// Uniformly samples from a hyper-ball of dimension v.size() void SampleHyperBall(Real r,std::vector<Real>& v); /// Uniformly samples from a hyper-sphere of dimension v.size() void SampleHyperSphere(Real r,std::vector<Real>& v); } //namespace Math /*@}*/ #endif
true
655cdb455dc7d1d9522876a3ff9168ea5e90faf5
C++
zjkang/ITint5
/001_新手入门--元素累加.cpp
GB18030
568
3.140625
3
[]
no_license
/* : Annie Kim, anniekim.pku[at]gmail.com ʱ: Sep 12, 2013 Ŀ: --Ԫۼ Ѷ: Easy : http://www.itint5.com/oj/#1 : һnarrԪ֮͡ мԼսᳬ32λз͵ķΧ Solution: ۼӡ */ //arrԪ֮ //Ҫmain! int arrSum(const vector<int> &arr) { int sum = 0, N = arr.size(); for (int i = 0; i < N; ++i) sum += arr[i]; return sum; }
true