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
2c067708c8be52a2f796ba9202d2e32ddd856577
C++
lobocv/sigproengine
/common_utils/include/domain_conversions.hpp
UTF-8
7,685
3.15625
3
[]
no_license
/*! \file domain_conversions.hpp \authors Calvin Lobo \date August 2006 \brief Conversion routines between sample index, time and depth. Due to finite antenna separation, conversion from time to depth is non-linear (hyperbolic). This library contains common functions to convert between these domains. Definitions: Zero Time: Time at which the Tx fires. First Break: Time (approximate) at which the Rx receives the first signal from the Tx (travel time through air). Tx Time: Elapsed time since zero time. Rx Time: Elapsed time since first break. */ #ifndef __DOMAIN_CONVERSIONS #define __DOMAIN_CONVERSIONS #include <math.h> #include <float.h> #include "sigpro_constants.h" namespace DepthTimeConversions { /** \brief Convert a time measured from zero-time to time measured from first break. \param dTxTime_ns Time measured from zero-time. \param dAntSep_m The antenna separation in meters. \return Time referenced from first break (Rx time) */ inline double TxTime2RxTime(double dTxTime_ns, double dAntSep_m) { // dAntSep_m / LIGHTSPEED_MPNS is time in air Tx to Rx return dTxTime_ns - (dAntSep_m / LIGHTSPEED_MPNS); } /** \brief Convert time measured from first break to time measured from zero-time. \param dRxTime_ns Time measured from first break. \param dAntSep_m The antenna separation in meters. \return Time measured from zero-time */ inline double RxTime2TxTime(double dRxTime_ns, double dAntSep_m) { // dAntSep_m / LIGHTSPEED_MPNS is time in air Tx to Rx return dRxTime_ns + (dAntSep_m / LIGHTSPEED_MPNS); } /** \brief Conversion of sample index to Rx time. \param dSampleIdx Zero-based index of the sample. \param dAntSep_m The antenna separation in meters. \param dSampleDeltaT_ns The sample delta t ns. \param dFirstBreakSampleNum The first break time sample cnt (1 based). \return Tx time at the specified sample index. */ double SampleIdx2TxTime(double dSampleIdx, double dAntSep_m, double dSampleDeltaT_ns, double dFirstBreakSampleNum) { double dRxTime = (dSampleIdx + 1.0 - dFirstBreakSampleNum) * dSampleDeltaT_ns; return dRxTime + (dAntSep_m / LIGHTSPEED_MPNS); } /** \brief Conversion of Tx time between transmitter and receiver to sample index. \param TxTime_ns Tx time. \param dAntSep_m The antenna separation in meters. \param dSampleDeltaT_ns The sample delta t ns. \param dFirstBreakSampleNum The first break sample cnt (1 based). \return Sample index at the specified Tx time. */ double TxTime2SampleIdx(double TxTime_ns, double dAntSep_m, double dSampleDeltaT_ns, double dFirstBreakSampleNum) { double dRxTime = TxTime_ns - (dAntSep_m / LIGHTSPEED_MPNS); return (dRxTime/dSampleDeltaT_ns) + dFirstBreakSampleNum - 1.0;//=dSampleIdx; } /** \brief Convert depth to Tx time. \param dDepth_m Depth in meters. \param dAntSep_m The antenna separation in meters. \param dVel_mpns Radar velocity in m/ns. \return Depth at the specified Tx time. */ double Depth2TxTime(double dDepth_m, double dVel_mpns, double dAntSep_m) { return 2.0 * sqrt(pow(dDepth_m,2) + pow((dAntSep_m/2),2)) / dVel_mpns; //t=2(d^2+(a/2)^2)^0.5 } /** \brief Convert depth to Rx time. \param dDepth_m Depth in meters. \param dAntSep_m The antenna separation in meters. \param dVel_mpns Radar velocity in m/ns. \return Depth at the specified Rx time. */ double Depth2RxTime(double dDepth_m, double dVel_mpns, double dAntSep_m) { double dTxTime_ns = Depth2TxTime(dDepth_m, dVel_mpns, dAntSep_m); return TxTime2RxTime(dTxTime_ns, dAntSep_m); } /** \brief Convert depth to sample index. \param dDepth_m Flight time from transmitter to receiver in ns. \param dAntSep_m The antenna separation in meters. \param dVel_mpns Radar velocity in m/ns. \param dSampleDeltaT_ns The sample delta t ns. \param dFirstBreakSampleNum The first break sample cnt (1 based). \return Sample index at the specified depth. */ double Depth2SampleIdx(double dDepth_m, double dVel_mpns, double dAntSep_m, double dSampleDeltaT_ns, double dFirstBreakSampleNum) { double dTxTime = Depth2TxTime(dDepth_m, dVel_mpns, dAntSep_m); double dRxTime = dTxTime - (dAntSep_m / LIGHTSPEED_MPNS); return (dFirstBreakSampleNum - 1.0) + (dRxTime / dSampleDeltaT_ns); } /** \brief Convert flight time to depth. \param dTxTime_ns Tx-referenced time. \param dAntSep_m The antenna separation in meters. \param dVel_mpns Radar velocity in m/ns. \return Depth at the specified Tx time. */ double TxTime2Depth(double dTxTime_ns, double dVel_mpns, double dAntSep_m) { int neg = 0; double retval, dAntPowCmp, dHypotomsPowCmp; // if(0.0 > dTxTime_ns) //-ve flight times are not solvable (duh) // return -DBL_MAX; //most negative // DA 2008-09-29 change to return meaningful negative data for negative flight times. if (dTxTime_ns < 0.0) { neg = 1; dTxTime_ns = -dTxTime_ns; } if (dAntSep_m / dVel_mpns >= dTxTime_ns) return 0.0; dAntPowCmp = pow((dAntSep_m / 2.0), 2); //(a/2)^2 dHypotomsPowCmp = pow((dVel_mpns * dTxTime_ns / 2.0), 2); //(vt/2)^2 if(dAntPowCmp > dHypotomsPowCmp) return -DBL_MAX; //most negative else { retval = sqrt(dHypotomsPowCmp - dAntPowCmp); //d^2=(vt/2)^2-(a/2)^2 if (neg) return -retval; else return retval; } } /** \brief Convert flight time to depth. \param dRxTime_ns Rx-referenced time. \param dAntSep_m The antenna separation in meters. \param dVel_mpns Radar velocity in m/ns. \return Depth at the specified Rx time. */ double RxTime2Depth(double dRxTime_ns, double dVel_mpns, double dAntSep_m){ double dTxTime_ns = RxTime2TxTime(dRxTime_ns, dAntSep_m); return TxTime2Depth(dTxTime_ns, dVel_mpns, dAntSep_m); } /** \brief Conversion of sample index to depth. \param dSampleIdx Zero-based index of the sample. \param dVel_mpns Radar velocity in m/ns. \param dAntSep_m The antenna separation in meters. \param dSampleDeltaT_ns The sample delta t ns. \param dFirstBreakSampleNum The first break sample cnt (1 based). \return Sample index at the specified depth. */ double SampleIdx2Depth(double dSampleIdx, double dVel_mpns, double dAntSep_m, double dSampleDeltaT_ns, double dFirstBreakSampleNum) { double ret; double dTxTime_ns = SampleIdx2TxTime(dSampleIdx, dAntSep_m, dSampleDeltaT_ns, dFirstBreakSampleNum); ret = TxTime2Depth(dTxTime_ns, dVel_mpns, dAntSep_m); if(0 < dTxTime_ns) return ret; else { if(ret<0) return ret; return -ret; } } /** \brief Get the sample index (zero based) of a given time in ns measured from first break. \param dRxTime_ns Time offset from first break. \param dSampleDeltaT_ns The sample delta t ns. \param dFirstBreakSampleNum The first break sample cnt (1 based). \return Zero based sample index that occured at time (measured from first break) in ns */ inline double RxTime2SampleIdx(double dRxTime_ns, double dSampleDeltaT_ns, double dFirstBreakSampleNum) { return dFirstBreakSampleNum - 1.0 + (dRxTime_ns / dSampleDeltaT_ns); } /** \brief Get the time in ns (measured from first break) of a given sample index (zero based). \param dSampleIdx The zero based sample index of signal \param dSampleDeltaT_ns The sample delta t ns. \param dFirstBreakSampleNum The first break sample cnt (1 based). \return Time of sample in ns (measured from first break) Can be a negative value. */ inline double SampleIdx2RxTime(double dSampleIdx, double dSampleDeltaT_ns, double dFirstBreakSampleNum) { return (dSampleIdx + 1.0 - dFirstBreakSampleNum) * dSampleDeltaT_ns; } } #endif
true
6fdc55b26b731334fa1f636887a2832d689ebe07
C++
johnmeehan/Game
/cPlayer.h
UTF-8
1,844
2.75
3
[]
no_license
#ifndef INC_CPLAYER_H #define INC_CPLAYER_H //#ifndef INC_CSQUAREDATA_H //#define INC_CSQUAREDATA_H //#ifndef INC_CCHARACTER_H //#define INC_CCHARACTER_H //#ifndef INC_ENUM_H //#define INC_ENUM_H #include"cSquareData.h" #include"cCharacter.h" #include"enum.h" #include"RandomNum.h" #include "cEnemy.h" ///////////////////////////////////////////////////////////////// // cPlayer is derived from a character // // has the ability to move, pick up, iniciate attack etc...... ///////////////////////////////////////////////////////////////// class cPlayer:public cCharacter{ // ALL FUNCTIONS SHOULD BE PASSED THE POINTER TO THE CURRENT SQUARE AND A LOCAL ONE MADE IN THE FUNCTION public: cPlayer(){ gold =0;}// constructor and set initial gold to 0 ~cPlayer(){;} // deconstructor char gameMenu(); // in game menu game_char pickCharacter(); //lets the user pick its character bool move(char, int *, int*, cEnemy *,cEnemy *,cEnemy *,cEnemy *,cEnemy *); // change the current location to new location bool checkSquare(cSquareData *); // first see if something is there ,(for llist) char selectAttack(); // menu for the user . returns a char i.e direction void look(cSquareData *); // print to screen whats in current square void look(cSquareData *, cEnemy *,cEnemy *,cEnemy *,cEnemy *,cEnemy *); // print to screen whats in current square bool attack(cPlayer *,cCharacter *,cRandomNumGen *); // attack a enemy if present on the square bool defend(); addGold(int); // add winnings to total int getGold(){return gold;} //return how much gold player has exit(); //Quit Game Destroy Board, squares private: int gold; // The amount of gold collected // inherits stats from cCharacter above }; //#endif //#endif #endif
true
94dc32b40cf90d6e491a4a708f81e73226d6657c
C++
adityanjr/code-DS-ALGO
/CodeForces/Complete/1200-1299/1271A-Suits.cpp
UTF-8
493
2.75
3
[ "MIT" ]
permissive
#include <cstdio> int main(){ long a, b, c, d, e, f; scanf("%ld %ld %ld %ld %ld %ld", &a, &b, &c, &d, &e, &f); long x = a; long y = (b < c) ? b : c; long total(0); if(e < f){ y = (y < d) ? y : d; total = f * y; d -= y; x = (x < d) ? x : d; total += e * x; } else{ x = (x < d) ? x : d; total = e * x; d -= x; y = (y < d) ? y : d; total += f * y; } printf("%ld\n", total); return 0; }
true
a920cab619c9a2a11c751430a0c3ef483d1f5aa7
C++
alvent98/C-plus-plus_Programming
/FilterBlur.cpp
UTF-8
1,475
3.203125
3
[]
no_license
#pragma once #include "FilterBlur.h" #include "Array.h" // Copy Constructor FilterBlur::FilterBlur(const FilterBlur & aFilter) { N = aFilter.N; } Image FilterBlur::operator<< (const Image & image) { //Create the new image object that is going to be returned Image newImage = image; int N = getN(); unsigned int width = newImage.getWidth(); unsigned int height = newImage.getHeight(); //Create a vector of floats, with N*N elements, each of them set at 1.0/(N*N) vector<float> dataTable (N*N, 1.F / (N*N)); //Create an array object with T = float, that contains the dataTable vector (just a container) math::Array<float> filterTable(N,N,dataTable); //Alter all the components, one by one. for (unsigned int currentWidth = 0; currentWidth < width; currentWidth++) { for (unsigned int currentHeight = 0; currentHeight < height; currentHeight++) { Color sum = Color(0,0,0); for (int m = (-1)*N / 2; m < N / 2; m++) { if (currentHeight + m >= 0 && currentHeight + m < height) { for (int n = (-1)*N / 2; n < N / 2; n++) { if (currentWidth + n >= 0 && currentWidth + n < width) { sum += image.getComponent(currentWidth + n, currentHeight + m) * filterTable.getComponent(n + N / 2, m + N / 2); } } } } sum = sum.clampToLowerBound(0); sum = sum.clampToUpperBound(1); newImage.setComponent(currentWidth, currentHeight, sum); } } return newImage; }
true
bcbd9d594a6549f7daa1d48f0be2e95252f009b3
C++
burakbayramli/books
/NumericalRecipes2/recipes/golden.cpp
UTF-8
830
2.671875
3
[]
no_license
#include <cmath> #include "nr.h" using namespace std; namespace { inline void shft2(DP &a, DP &b, const DP c) { a=b; b=c; } inline void shft3(DP &a, DP &b, DP &c, const DP d) { a=b; b=c; c=d; } } DP NR::golden(const DP ax, const DP bx, const DP cx, DP f(const DP), const DP tol, DP &xmin) { const DP R=0.61803399,C=1.0-R; DP f1,f2,x0,x1,x2,x3; x0=ax; x3=cx; if (fabs(cx-bx) > fabs(bx-ax)) { x1=bx; x2=bx+C*(cx-bx); } else { x2=bx; x1=bx-C*(bx-ax); } f1=f(x1); f2=f(x2); while (fabs(x3-x0) > tol*(fabs(x1)+fabs(x2))) { if (f2 < f1) { shft3(x0,x1,x2,R*x2+C*x3); shft2(f1,f2,f(x2)); } else { shft3(x3,x2,x1,R*x1+C*x0); shft2(f2,f1,f(x1)); } } if (f1 < f2) { xmin=x1; return f1; } else { xmin=x2; return f2; } }
true
d71426a10e4a7bc4a7f07d9d992b3d3421a5ebd2
C++
Pavan281/Functions.cpp
/Functions.cpp
UTF-8
1,127
4.125
4
[]
no_license
# Functions in C++ # Write a C++ program to Check Whether a Number can be Express as Sum of Two Prime Numbers. # Your output need to look something like this : Enter a positive integer: 34 34 = 3 + 31 34 = 5 + 29 34 = 11 + 23 34 = 17 + 17 #include <iostream> using namespace std; int main() { int n, i, a = 1, b = 1, c = 0, j; float sum = 0; cout << "\nCheck Whether the Number can be expressed as the Sum of Two Prime Numbers : \n"; cin >> n; for (i = 2; i <= n / 2; i++) { a = 1; b = 1; for (j = 2; j < i; j++) { if (i % j == 0) { a = 0; j = i; } } for (j = 2; j < n - i; j++) { if ((n - i) % j == 0) { b = 0; j = n - i; } } if (a == 1 && b == 1) { cout << n << " = " << i << " + " << n - i << endl; c = 1; } } if (c == 0) { cout << n << " The Number can not be expressed as the Sum of Two Prime Numbers."; } }
true
74310e320d8c331c379b30f10d7033c6eb312af2
C++
Zixuan-QU/Leetcode
/Code/rotate.cpp
UTF-8
1,508
3.546875
4
[]
no_license
//make a copy class Solution { public: void rotate(vector<vector<int> > &matrix) { int n = matrix.size(); vector<vector<int> > copy(n,vector<int>(n)); cout<<copy.size(); for(int i =0;i<n;i++) for(int j = 0;j<n;j++) copy[j][n-1-i] = matrix[i][j]; matrix = copy; } }; //in-place_1 class Solution { public: void rotate(vector<vector<int> > &matrix) { int n = matrix.size(); for(int i =0;i<=(n-1)/2;i++){ rotate(matrix,i,n-2*i); } } void rotate(vector<vector<int> > &matrix,int start,int length){ if(length <= 1) return; int tmp[4]; int n = matrix.size(); for(int j = start;j<n-start-1;j++){ tmp[0] = matrix[start][j]; tmp[1] = matrix[j][n-start-1]; tmp[2] = matrix[n-start-1][n-1-j]; tmp[3] = matrix[n-1-j][start]; matrix[start][j] = tmp[3]; matrix[j][n-start-1] = tmp[0]; matrix[n-start-1][n-1-j] = tmp[1]; matrix[n-1-j][start] = tmp[2]; } } }; //in-place_2 class Solution { public: void rotate(vector<vector<int> > &matrix) { int n = matrix.size(); for(int i =0;i<n;i++) for(int j=0;j<n-i;j++) swap(matrix[i][j],matrix[n-1-j][n-1-i]); for(int i =0;i<n/2;i++) for(int j =0;j<n;j++) swap(matrix[i][j],matrix[n-1-i][j]); } };
true
8109f4a0acdd7c72a17f504fcbdd39307bf73b6c
C++
lxlenovostar/algorithm
/leetcode/offer_ii_7/main.cc
UTF-8
1,953
3.25
3
[]
no_license
#include <set> #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> rets; std::set<int> check_vals; std::sort(nums.begin(), nums.end()); for (int i = 0; i < (int)nums.size(); ++i) { int delta = 0 - nums[i]; if (check_vals.find(nums[i]) == check_vals.end()) { check_vals.insert(nums[i]); } else { continue; } int begin = i+1; int end = nums.size() - 1; while (begin < end) { if (nums[begin] + nums[end] == delta) { std::vector<int> ret = {nums[i], nums[begin], nums[end]}; rets.push_back(ret); int last_begin_val = nums[begin]; begin++; while(begin < end) { if (nums[begin] == last_begin_val) { begin++; } else { break; } } continue;; } if (nums[begin] + nums[end] > delta) { end--; continue; } if (nums[begin] + nums[end] < delta) { begin++; continue; } } } return rets; } }; int main() { //vector<int> numbers = {0, 0, 0, 0}; //vector<int> numbers = {-1,0,1,2,-1,-4}; vector<int> numbers = {0, 0, 0}; Solution *test = new Solution(); const auto& vals = test->threeSum(numbers); for (const auto& val: vals) { for (const auto& item: val) { std::cout << item << " "; } std::cout << std::endl; } return 0; }
true
51dda322943dbb7ea662a3883a7f598751693fa1
C++
liumingzhuo/StructureAlg
/dynamic/SellStockTwo122.cc
UTF-8
1,320
3.640625
4
[]
no_license
/** * 122. Best Time to Buy and Sell Stock II * Say you have an array prices for which the ith element is the price of a given stock on day i. * Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). * Input: [7,1,5,3,6,4] * Output: 7 * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.   Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. **/ #include<vector> #include<iostream> #include<algorithm> using namespace std; class Solution { public: int maxProfit(vector<int>& prices) { //dp[i][k][0] = max(dp[i-1][k][0],dp[i-1][k-1][1] + price[i]); //dp[i][k][1] = max(dp[i-1][k][1],dp[i-1][k-1][0] - price[i]) //因为 k为无穷大 那么k-1 = k //所以 dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k][0] - price[i]) int dp_i_0 = 0; int dp_i_1 = INT16_MIN; for(int price:prices){ int flag = dp_i_0; dp_i_0 = max(dp_i_0, dp_i_1 + price); dp_i_1 = max(dp_i_1, flag-price); } return dp_i_0; } };
true
a884a734a115ba1a99e4411b758db855f7429052
C++
mamunhpath/leet-code
/sqrtx-4.cpp
UTF-8
331
3.15625
3
[]
no_license
// https://leetcode.com/problems/sqrtx/description/ class Solution { public: int mySqrt(int x) { if (x < 2) return x; int s = 0, e = x; while(e - s > 1){ int m = s + (e - s)/2; if(m <= x / m) s = m; else e = m; } return s; } };
true
69a48a434bffc4b837ecfc149650492e88ac1efc
C++
sheeraznarejo/SPOJ
/bytes2.cpp
UTF-8
670
2.96875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> int timesarray[10000008]; int main() { int n; int k, j; k = 5; j = 200; scanf("%d", &n); while(n--) { int arraysize, entry, exit2; int maxexit = 0; scanf("%d", &arraysize); int p = arraysize; while(p--) { scanf("%d %d", &entry, &exit2); if(exit2 > maxexit) maxexit = exit2; timesarray[entry] = k; timesarray[exit2] = j; } int sum = 0; int maxsum = 0; for(int i=0; i<= maxexit; i++) { if(timesarray[i] == k) { sum++; if(sum > maxsum) maxsum = sum; } else if (timesarray[i] == j) sum--; } printf("%d\n", maxsum); k++; j++; } }
true
6e5374bc74b07a26e6cc18e67c3c87aead16648c
C++
dongfufu/icp
/main.cpp
UTF-8
4,755
2.59375
3
[]
no_license
#include <iostream> #include <cmath> #include <cstdio> #include <iostream> #include <eigen3/Eigen/Dense> #include <eigen3/Eigen/Geometry> #include <ceres/ceres.h> #include <ceres/rotation.h> #include <vector> using namespace std; // Read a Bundle Adjustment in the Large dataset. // Templated pinhole camera model for used with Ceres. The camera is // parameterized using 9 parameters: 3 for rotation, 3 for translation, 1 for // focal length and 2 for radial distortion. The principal point is not modeled // (i.e. it is assumed be located at the image center). //残差块,输入两组点 //四元数存储输出按照x,y,z,w来做,初始化按照w,x,y,z来做 struct ICPError { ICPError(Eigen::Vector3d par_point,Eigen::Vector3d child_point){ par_point_=par_point; child_point_=child_point; } template<typename T> bool operator()(const T* q_res,const T *const t_res, T*residuals ) const{//transform为待优化变量,有6维 //q_res为一个存储四元数的数组 //设置四元数,构造w,x,y,z ,存储和输出x,y,z,w Eigen::Quaternion<T> q_use(q_res[3],q_res[0],q_res[1],q_res[2]); Eigen::Matrix<T,3,1> t_use(t_res[0],t_res[1],t_res[2]); Eigen::Matrix<T,3,1> m_par_point(T(par_point_(0)),T(par_point_(1)),T(par_point_(2))); Eigen::Matrix<T,3,1> m_child_point(T(child_point_(0)),T(child_point_(1)),T(child_point_(2))); Eigen::Matrix<T,3,1> my_after_child_point=q_use*m_child_point+t_use; //定义残差 residuals[0]=m_par_point(0)-my_after_child_point(0); residuals[1]=m_par_point(1)-my_after_child_point(1); residuals[2]=m_par_point(2)-my_after_child_point(2); return true; } static ceres::CostFunction* Create_Cost_Fun(const Eigen::Vector3d par_point,Eigen::Vector3d child_point) { //损失函数类型、输出维度、输入维度,此处输出维度为3,输入维度主要包括两个变量,四元数变量为4,平移变量维度为3 return (new ceres::AutoDiffCostFunction<ICPError,3,4,3>(new ICPError(par_point,child_point))); } Eigen::Vector3d par_point_,child_point_; }; int main(){ std::vector<Eigen::Vector3d> par_points; std::vector<Eigen::Vector3d> child_points; //初始化子点云 for(int i=0;i<200;i++) { Eigen::Vector3d temp(i,i+1,i+2); cout<<"temp="<<temp<<endl; child_points.push_back(temp); } //定义父到子之间的旋转关系 // Eigen::Matrix3d R; //wxyz初始化,xyzw存储 Eigen::Quaternion<double> q(1,0.2,0.2,0.2); q.normalize(); Eigen::Vector3d t; // //eigen中默认按行输入 // R<<1 ,0 ,0 ,0, 1, 0, 0, 0, 1; t<<2,3,4; //根据转换关系生成父点云 for(int i=0;i<200;i++) { Eigen::Vector3d par_point=q*child_points[i]+t; cout<<"par_point="<<par_point<<endl; par_points.push_back(par_point); } //设置优化初值 double q_res[4]={0,0,0,0.5}; double t_res[3]={1,2,3}; //开始优化 ceres::Problem problem; for(int i=0;i<par_points.size();i++) { //调用构造体中的静态函数,创建损失函数 ceres::CostFunction*cost=ICPError::Create_Cost_Fun(par_points[i],child_points[i]); problem.AddResidualBlock(cost,NULL,q_res,t_res); } //设置优化参数,开始优化 ceres::Solver::Options options; options.linear_solver_type = ceres::DENSE_SCHUR; options.max_num_iterations=500; options.minimizer_progress_to_stdout = true; ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.FullReport() << "\n"; cout<<"优化后的平移量"<<t_res[0]<<" "<<t_res[1]<<" "<<t_res[2]<<endl; cout<<"正确的平移量"<<t(0)<<" "<<t(1)<<" "<<t(2)<<endl; Eigen::Vector3d tt(t_res[0],t_res[1],t_res[2]); cout<<q_res[0]<<" "<<q_res[1]<<" "<<q_res[2]<<" "<<q_res[3]<<endl; Eigen::Quaternion<double> qq(q_res[3],q_res[0],q_res[1],q_res[2]); qq.normalize(); cout<<"优化后的四元数"<<" "<<qq.coeffs()<<endl ; cout<<"真实四元数"<<" "<<q.coeffs()<<endl; // ceres::AngleAxisToRotationMatrix(aix,RR); //根据优化后的参数计算点云重投影误差 double sum_error=0; double mse=0;//标准差 for(int i=0;i<child_points.size();i++) { Eigen::Vector3d tran_child_point=qq*child_points[i]+tt; sum_error+=(pow(tran_child_point(0)-par_points[i](0),2)+pow(tran_child_point(1)-par_points[i](1),2)+pow(tran_child_point(2)-par_points[i](2),2)); } mse=sqrt(sum_error/child_points.size()); cout<<"误差"<<mse<<endl; return 0; }
true
ee276cd5138bed67714fd591d667a0514bed18fb
C++
niuxu18/logTracker-old
/second/download/squid/gumtree/squid_repos_function_4353_squid-3.3.14.cpp
UTF-8
458
2.53125
3
[]
no_license
int Ssl::ErrorDetail::convert(const char *code, const char **value) const { *value = "-"; for (int i=0; ErrorFormatingCodes[i].code!=NULL; ++i) { const int len = strlen(ErrorFormatingCodes[i].code); if (strncmp(code,ErrorFormatingCodes[i].code, len)==0) { ErrorDetail::fmt_action_t action = ErrorFormatingCodes[i].fmt_action; *value = (this->*action)(); return len; } } return 0; }
true
4d68afe28d5635df859206a43fd24ab954c2b446
C++
OTTFFYZY/StandardCodeLibrary
/DataMaker_SpecialJudge_Debug/Checker_spj.cpp
UTF-8
746
2.53125
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <stdlib.h> #include <sstream> using namespace std; ifstream fin,myfin; string s1,s2; const char datamk[]="datamaker.exe > in.txt"; const char mypro[]="myprogram.exe < in.txt > myout.txt"; int f=1; bool check() { // } void spj() { while(!fin.eof()||!myfin.eof()) { if(fin.eof()||myfin.eof()) { cout<< "WA EOF!" <<endl; f=0; return; } if(!check()) return 0; } return 1; } int main() { while(f) { system(datamk); cout<<"ok0"<<endl; system(mypro); cout<<"ok1"<<endl; fin,open("in.txt",ios::in); myfin.open("myout.txt",ios::in); int i=1; spj(); if(f) cout<<"AC!!!!!!"<<endl; fin.close(); myfin.close(); //f=0; } return 0; }
true
a14bc0d870f351aa46c7c303f01eb7234e8208b4
C++
UniqueZHY/ZHY
/algorithm/54_炒鸡大整数.cpp
UTF-8
1,371
2.734375
3
[]
no_license
/************************************************************************* > File Name: 54_炒鸡大整数.cpp > Author: > Mail: > Created Time: 2019年12月21日 星期六 18时04分34秒 ************************************************************************/ #include<stdio.h> #include<string.h> #define max_n 1000 int ans[max_n + 5]; int res[max_n + 5]; void solve(int x) { memset(ans, 0, sizeof(ans)); ans[0] = 1,ans[1] = 1; for (int i = 1; i <= x; i++) { for (int j = 1; j <= ans[0]; j++) { ans[j] *= i; } for (int k = 1; k <= ans[0]; k++) { if (ans[k] < 10) continue; ans[k + 1] += ans[k] / 10; ans[k] %= 10; ans[0] += (ans[0] == k); } } memset(res, 0, sizeof(res)); res[0] = 1, res[1] = 1; for (int i = 1; i <= ans[0]; i++) { if (!ans[i]) continue; for (int j = 1; j <= res[0]; j++) { res[j] *= ans[i]; } for (int k = 1; k <= res[0]; k++) { if(res[k] < 10) continue; res[k + 1] += res[k] / 10; res[k] %= 10; res[0] += (res[0] == k); } } for (int i = res[0]; i >= 1; i--) { printf("%d", res[i]); } printf("\n"); } int main() { int x; while (scanf("%d", &x) != EOF) solve(x); return 0; }
true
483ae11db02765ee21ebde485d8af3923c2bb59c
C++
Fao2212/Proyecto-I-Estructuras
/SimulacionRestaurante/Cajero.cpp
UTF-8
1,218
2.75
3
[]
no_license
#include "Cajero.h" #include "Estado.h" #include "Cola.h" #include "Caja.h" #include "ListaSimple.h" #include "Nodo.h" #include "Peticion.h" #include "Plato.h" Cajero :: Cajero(Caja * caja){ this->estado = new Estado(); this->peticiones = new Cola<Peticion>(); this->atendidos = 0; this->caja = caja; } Peticion * Cajero:: tomarCuenta(){ if(caja->peticiones->siguienteEnCola() != nullptr){ Peticion * peticion = caja->peticiones->desencolar()->dato; peticiones->encolar(peticion); return peticion; } return nullptr; } Peticion * Cajero :: hacerCobro(){ if(peticiones->siguienteEnCola() != nullptr){ Peticion * peticion = peticiones->desencolar()->dato; caja->historial->insertar(peticion); return peticion; } return nullptr; } double Cajero :: ventasActuales(){ Nodo<Peticion> * temp = caja->historial->primerNodo; double total = 0; while (temp != nullptr) { for(int i = 0; i < 6; i++){ if(temp->dato->platos[i]!=nullptr) total += temp->dato->platos[i]->precio; } temp = temp->siguiente; } return total; }
true
d08820217f87c33a465894c36a71ccf16dcb4b3c
C++
raetro-deps/simdutf
/tests/reference/encode_utf16.h
UTF-8
426
2.703125
3
[ "MIT", "Apache-2.0" ]
permissive
#pragma once #include <cstdint> namespace simdutf { namespace tests { namespace reference { namespace utf16 { // returns whether the value can be represented in the UTF-16 bool valid_value(uint32_t value); // Encodes the value using either one or two words (returns 1 or 2 respectively) // Returns 0 if the value cannot be encoded int encode(uint32_t value, char16_t& W1, char16_t& W2); }}}} // namespace utf16
true
10b44d687d9aaba263bee106417f415af5ebb460
C++
PhantomStorm95/2020-2021-Prog-1-Programs-
/MP2_Wk2_D2_Bad_Credit_Random_Card_Generator.cpp
UTF-8
6,482
3.75
4
[]
no_license
//Bad Credit Random Credit Card Number Generator Souvik Kar Period 4 Petr #include <iostream> #include <vector> #include <math.h> #include<ctime> using namespace std; int main(){ //Variables //A variable that stores the random credit card number for future use, here it is a global variable long long CC; //Asking the user for some input into the program to produce some sort of output int input; int input2; //Stores the number of digits in each specfic type of card because each of the three are diffrent int digits; int remaining_card_digits = 0; //1st While loop that keeps running as long as the input2 (which is when the program asks the user if they want to genrate a random credit card number again) while(input2 != 2) { srand(time(0)); //A fancy function that makes sure when the random credit card is made it is more random //User Menu for the user to read and follow directions cout<<"Type of card to generate: \n"; cout<<"1 - AMEX \n"; cout<<"2 - MasterCard \n"; cout<<"3 - 13-digit Visa \n"; cout<<"4 - 16-digit Visa \n"; cin>>input; //This variable called start_card as a integer stores the 1st or 1st & 2nd digits of the selected credit card int start_card = 0; //If user selects a AMEX if(input == 1) { //Total number of digits is 15 digits = 15; //start_card is now a changed variable which produces a random number between 1 & 2 start_card = rand() % (2) + 1; //If its a 1 the first two digits of the card become 3 and 4 from left to right if(start_card == 1) { start_card = 34; } //Else if it's a 2 first two digits of the card become 3 and 7 from left to right else { start_card = 37; } remaining_card_digits = 2; } //If user selects a MasterCard else if(input == 2) { //Total number of digits now becomes 16 because of the diffrent type of card selected digits = 16; //start_card is now changed again to producing a random number for the first two digits being from 51-55 since it's a MasterCard start_card = rand() % (55 - 51 + 1) + 51; remaining_card_digits = 2; } //If user selects a Visa with 13 digits else if(input == 3) { //Total number of digits now becomes 13 because of the diffrent type of card selected digits = 13; //start_card doesn't need a random number generator for the first digit of a Visa because its only one digit you guessed it 4 start_card = 4; remaining_card_digits = 1; } //If user selects a Visa with 16 digits else if(input == 4) { //Total number of digits now becomes 16 because there is a another form of Visa with 16 digits :) digits = 16; //start_card doesn't need a random number generator for the first digit of a Visa because its only one digit you guessed it 4 start_card = 4; remaining_card_digits = 1; } //Creates a vector which stores the indivudal digits vector<int>CC_check(digits); //A boolean variable that stores the condtion false for use in the while loop parmeter for it to run bool CC_found = false; //2nd while loop will run as long as the random credit card number is kept on being made and all the checks are made then the boolean will become true while(CC_found == false) { //This for loop is for generating the random digits of the rest of the selected credit card number for(int i = 0; i < digits - remaining_card_digits ; i++) { CC = CC + ((rand() % 10) * (pow(10, i))); } //Now the variable CC keeps shifting the digits to the left to make the random credit card number complete CC = (start_card * pow(10, digits - remaining_card_digits)) + CC; //Creates a new variable to store the last digit in the vector postion int vector_postion = digits - 1; //This while loop inserts every digit of the random credit card number into the vector based on the index while(CC > 0) { int rem = CC % 10; CC_check[vector_postion] = rem; vector_postion = vector_postion - 1; CC = (CC/10); } //These variables are used for the third check known as CheckSum to verify the random credit number made int evenCheck = 0; int sumCheck = 0; //This for loop multiplies and adds the even digits starting with the second digit which is really index 1 and adds them up but has a condtion for(int x = 1; x < digits - 1; x = x + 2) { evenCheck = CC_check[x] * 2; //If the digit is more than 9 it will separate the two digits and then add them together, ex- 10 would be (1 + 0) if (evenCheck > 9) { evenCheck = 1 + (evenCheck - 10); } sumCheck = sumCheck + evenCheck; } //This for loop will add the digits that weren't included in the first for loop so the odd digits for(int x = 0; x <= digits - 1; x = x + 2) { evenCheck = CC_check[x]; sumCheck = sumCheck + evenCheck; } //A if statement that says if the last digit in sumCheck is 0 it is a legit random credit card for the selected type if((sumCheck % 10) == 0) { cout<<"Generated Card Number: "<<"\n"; for(int i=0; i < CC_check.size(); i++) { //Prints out the full random credit card number cout<<CC_check.at(i)<<" "; CC_found = true; } } } //Asks the user if they want to create another random credit card number for a type of card after the 1st one cout<<"\n\n"<<"Again? 1=yes, 2=no"; cin>>input2; //If the user enters the number 2 which is a no the program will exit if(input2 == 2) { return 0; } } }
true
673c7cc58b8a209173acea88ce35434a31d760d5
C++
ScarletMcLearn/UniThings
/CSC101-CPP/CSE-101-master/Aunnoy Sensei Reloaded.cpp
UTF-8
1,609
3.921875
4
[]
no_license
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int factorial(int num); void sort_array(int Arr[]); int median(int Arr[]); int main() { while (true) { cout<<endl<<endl<<"Enter Choice: "; string choice; cin>> choice; if (choice == "f") { cout<<endl<<"Enter Number: "; int number; cin>> number; factorial(number); } else if (choice == "m") { int Array[5]; srand(time(0)); cout<<endl<<"Array Elements: "; for (int j = 0; j<5; j++ ) { Array[j] = 0 + rand() % (10 + 1); cout<< Array[j] <<" "; } cout<<endl<<endl<<"Sorted Array: "; sort_array(Array); for (int j = 0; j<5; j++ ) { // Array[j] = 0 + rand() % (10 + 1); // cout<< 0 + rand() % (10 + 1) <<" "; cout<< Array[j] <<" "; } cout<<endl; median(Array); } else cout<<endl<<"Invalid Input. Try Again." <<endl; } return 0; } int factorial(int num) { int fact = 1; int n = num; for(int i = 1; i <=n; ++i) { fact *= i; } cout << "Factorial of " << n << " = " << fact; return fact; } void sort_array(int Arr[]) { int ArrSize = 5; for (int iter = 0; iter < ArrSize - 1; iter++) { for (int jiter = iter + 1; jiter < ArrSize; jiter++) { if (Arr[iter] > Arr[jiter]) { int temp = Arr[iter]; Arr[iter] = Arr[jiter]; Arr[jiter] = temp; } } } } int median(int Arr[]) { cout<<"Median: " << Arr[2] <<endl; return Arr[2]; }
true
95e9cb4726a2f7b0c1c16b4bebc831eb5e173bee
C++
thealberteitor/Metodologia-de-la-Programacion
/Prácticas MP/ConectaN/Version 1/include/Tablero.h
UTF-8
538
2.625
3
[]
no_license
#ifndef __TABLERO_H__ #define __TABLERO_H__ #include<iostream> using namespace std; class Tablero{ private: Matriz m; int fichas; public: Tablero(int fil, int col); int getfils() const; int getcols() const; char get(int fil, int col) const; void setfichas(int fich); bool Finalizado(char valor, int fila, int columna) const; bool Ganador(int turno, Jugador &p1, Jugador &p2, bool finalizado); bool Insert(int col, int &turno); bool Turno(int turno); void VaciarTablero(); void PrettyPrint(); }; #endif
true
4d16feef0697045027d3de041f445478482988ee
C++
nnm-t/m5stack-visiting-card
/scroll_text.h
UTF-8
1,395
2.796875
3
[ "MIT" ]
permissive
#pragma once #include <M5Stack.h> #include "rect.h" #include "vector2.h" class ScrollText { static constexpr int32_t width = TFT_HEIGHT; TFT_eSprite* _sprite; const Vector2 _position; const Rect _rect; const uint16_t _dx; int32_t _x; int32_t _y; bool _is_scroll; String _string; int32_t _scroll_width; void MoveReverseSide(uint32_t new_x) { _x = new_x; DrawString(_string, Vector2(_x, _y)); } public: ScrollText(TFT_eSprite* sprite, const Vector2& position, const Rect& rect, const uint16_t dx) : _sprite(sprite), _position(position), _rect(rect), _dx(dx) { _x = 0; _y = 0; _is_scroll = false; _string = String(); } void Begin() { _sprite->createSprite(_rect.GetWidth(), _rect.GetHeight()); } void Begin(String& font_name, FS& fs = SD) { Begin(); _sprite->loadFont(font_name, fs); } void Begin(const char* font_name, FS& fs = SD) { Begin(); _sprite->loadFont(font_name, fs); } void SetColor(const uint16_t foreground_color, const uint16_t background_color, const uint8_t color_depth); void DrawString(String& string, const Vector2& position); void SetScrollRect(const Vector2& position, const Rect& rect) { _sprite->setScrollRect(position.GetX(), position.GetY(), rect.GetWidth(), rect.GetHeight()); _scroll_width = rect.GetWidth(); } void Loop(); void End() { _is_scroll = false; _sprite->deleteSprite(); } };
true
b4df1a60e876f22be6c38681040d8b7924f29005
C++
Emilien-Delevoye/PSU_zappy_2019
/tests/src/forward.cpp
UTF-8
1,424
2.53125
3
[]
no_license
/* ** EPITECH PROJECT, 2020 ** zappy ** File description: ** Created by emilien */ #include "tests.h" #include <gtest/gtest.h> void do_move(data_server_t *data, client_t *cli) { cli->drone.orientation = NORTH; forward(data); EXPECT_EQ(cli->drone.tile->coord[0], 1); EXPECT_EQ(cli->drone.tile->coord[1], 0); cli->drone.orientation = SOUTH; forward(data); EXPECT_EQ(cli->drone.tile->coord[0], 0); EXPECT_EQ(cli->drone.tile->coord[1], 0); cli->drone.orientation = EAST; forward(data); EXPECT_EQ(cli->drone.tile->coord[0], 0); EXPECT_EQ(cli->drone.tile->coord[1], 1); cli->drone.orientation = WEST; forward(data); EXPECT_EQ(cli->drone.tile->coord[0], 0); EXPECT_EQ(cli->drone.tile->coord[1], 0); } TEST(forward, classic_test) { data_server_t data{}; client_t *cli = new client_t; memset(&data, 0, sizeof(data_server_t)); memset(cli, 0, sizeof(client_t)); data.params.height = 2; data.params.width = 2; setup_map(&data); data.cli_work = new list_actions_t; memset(data.cli_work, 0, sizeof(list_actions_t)); data.cli_work->cli = cli; cli->drone.tile = data.bottom_left; cli->drone.tile->list_players = new tile_players_t; cli->drone.tile->list_players->cli = cli; cli->drone.tile->list_players->next = new tile_players_t; cli->drone.tile->list_players->next->next = nullptr; do_move(&data, cli); }
true
db9f3ddf86046236b7cc3baed5bd0a4a6eb7215c
C++
t12cs015/TileMatrix
/Matrix.cpp
UTF-8
1,514
3.71875
4
[]
no_license
/* * Matrix.cpp * * Created on: 2015/08/31 * Author: stomo */ #include <iostream> #include <cstdlib> #include <cassert> #include "Matrix.hpp" using namespace std; /** * Default constructor */ Matrix::Matrix() { #ifdef DEBUG cout << "Matrix()\n"; #endif m_ = n_ = 0; top_ = NULL; } /** * Constructor * * @param m number of lows of the matrix * @param n number of columns of the matrix */ Matrix::Matrix( const unsigned int m, const unsigned int n ) { #ifdef DEBUG cout << "Matrix(m,n)\n"; #endif assert( m > 0 ); assert( n > 0 ); m_ = m; n_ = n; try { top_ = new double[ m_ * n_ ]; } catch (char *eb) { cerr << "Can't allocate memory space for Matrix class: " << eb << endl; exit(EXIT_FAILURE); } } /** * Destructor * */ Matrix::~Matrix() { #ifdef DEBUG cout << "~Matrix()\n"; #endif delete [] top_; } /** * Operator overload = */ Matrix &Matrix::operator=( const Matrix &T ) { assert( m_ == T.m_ ); assert( n_ == T.n_ ); for (unsigned int i = 0; i < m_ * n_; i++) top_[i] = T.top_[i]; return *this; } /** * Operator overload [] * * @param i index */ double &Matrix::operator[]( const unsigned int i ) const { assert( i >= 0 ); assert( i < m_ * n_ ); return top_[ i ]; } /** * Operator overload () * * @param i low index * @param j column index */ double &Matrix::operator()( const unsigned int i, const unsigned int j ) const { assert( i >= 0 ); assert( i < m_ ); assert( j >= 0 ); assert( j < n_ ); return top_[ i + j * m_ ]; }
true
1ea53d77bd79a945758edb723b88aabb7adf292c
C++
tjmahr/adventofcode18
/src/day09.cpp
UTF-8
2,109
3.109375
3
[]
no_license
#include <Rcpp.h> using namespace Rcpp; // This is a simple example of exporting a C++ function to R. You can // source this function into an R session using the Rcpp::sourceCpp // function (or via the Source button on the editor toolbar). Learn // more about Rcpp at: // // http://www.rcpp.org/ // http://adv-r.had.co.nz/Rcpp.html // http://gallery.rcpp.org/ // // // [[Rcpp::export]] // IntegerVector wrap_around_c(IntegerVector xs, IntegerVector y) { // int length_y = y.length(); // int length_xs = xs.length(); // // xs = ifelse(xs <= 0, xs + 1, xs); // xs = xs - 1; // // for(int i = 0; i < length_xs; ++i) { // // add divisor to remainder and go again to handle negative numbers // xs[i] = ((xs[i] % length_y) + length_y) % length_y; // } // // return xs + 1; // } //' @export // [[Rcpp::export]] int wrap_around_c2(int x, IntegerVector y) { int length_y = y.length(); if (x <= 0) { x = x + 1; } x = x - 1; x = ((x % length_y) + length_y) % length_y; x = x + 1; return x; } //' @export // [[Rcpp::export]] IntegerVector run_marbles_c_scores(int x, int marbles) { IntegerVector board(1); int game_length = marbles / 23; IntegerVector history(game_length); int position = 0; int current_position = 1; int next_step; int to_remove; int bonus; for (int i = 1; i <= marbles; ++i) { if (i % 23 == 0) { to_remove = wrap_around_c2(current_position - 7, board); bonus = board[to_remove - 1]; board.erase(to_remove - 1); position = wrap_around_c2(current_position - 7, board); history[(i / 23) - 1] = i + bonus; } else { next_step = current_position + 2; position = wrap_around_c2(next_step, board); board.insert(position - 1, i); } current_position = position; } return history; } // You can include R code blocks in C++ files processed with sourceCpp // (useful for testing and development). The R code will be automatically // run after the compilation. // /*** R run_marbles_c_scores(10, 300) wrap_around_c2(1, 0:1) wrap_around_c2(2, 0:1) wrap_around_c2(3, 0:1) */
true
e047582d1edd85cfbce614d38293fe6bad728272
C++
simon0191/ProgrammingExercises
/UVA.10924.PrimeWords/primeWords.cpp
UTF-8
876
2.96875
3
[]
no_license
#include <cstdio> #include <cmath> #include <cstring> #include <cctype> #include <sstream> using namespace std; int f(char c){ if(isupper(c)){ return c-'A'+27; } else{ return c-'a'+1; } } int main(){ char buff[1024]; int isPrime[1062]; memset(isPrime,true,sizeof(isPrime)); isPrime[0] = false; isPrime[1] = isPrime[2] = true; const int root = sqrt(1062)+1; for(int i = 2;i<=root;++i){ if(isPrime[i]){ for(int j = i*2;j<1062;j+=i){ isPrime[j] = false; } } } while(scanf("%s",buff)==1){ int sum = 0; for(int i = 0;buff[i];++i){ sum+=f(buff[i]); } if(isPrime[sum]){ puts("It is a prime word."); } else{ puts("It is not a prime word."); } } return 0; }
true
e8d0033ace899b924c626c4477b7766ad7cb3136
C++
dbetm/cp-history
/LeetCode/BC_BTZigZagLevelOrderTraversal.cpp
UTF-8
1,389
3.390625
3
[]
no_license
#include <bits/stdc++.h> // https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ // Tag(s): Árboles, estructuras de datos // NO COMPLETE IMPLEMENTED HERE using namespace std; /** * Definition for a binary tree node. **/ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> ans; if(root == NULL) return ans; queue<TreeNode*> myQ; bool fromLeftToRigth = true; int size, index; myQ.push(root); while(!myQ.empty()) { size = myQ.size(); vector<int> level(size); for(int i = 0; i < size; ++i) { TreeNode* aux = myQ.front(); myQ.pop(); index = (fromLeftToRigth) ? i : (size-1-i); level[index] = aux->val; if(aux->left) myQ.push(aux->left); if(aux->right) myQ.push(aux->right); } fromLeftToRigth = !fromLeftToRigth; ans.push_back(level); } return ans; } }; int main() { return 0; }
true
42bfb063794bbff139fa0259d5fd71da1539c4b8
C++
EmberCodeEx/Artificial-intelligence
/Search/informedGBS.cpp
UTF-8
2,753
3
3
[]
no_license
#include<iostream> #include<vector> #include<fstream> #include<queue> #include<functional> using namespace std; using Queu = priority_queue < pair<int, pair<int, int>>, vector < pair<int, pair<int, int>>>, greater < pair<int, pair<int, int> > >>; void getFile(ifstream &in, string filename) { in.open(filename); } bool assert(int i, int j, int m, int n) { if (i <= -1 || i >= m || j <= -1 || j >= n) return true; else return false; } bool IsValid_move(vector<vector<int>>&Maze, vector<vector<bool>>&visit, int i, int j, int m, int n) { if (assert(i, j, m, n)) { return false; } if (Maze[i][j] == 1)return false; else if (visit[i][j])return false; else return true; } bool is_Goal(int goal[][2], int i, int j) { return (goal[0][0] == i && goal[0][1] == j) ? true : false; } int CalculateHeuristic(int i, int j, int goal[][2]) { // calculate Euclidean distance between current cell and the goal return sqrt((i - goal[0][0])*(i - goal[0][0]) + (j - goal[0][1])*(j - goal[0][1])); } void informedGBS(vector<vector<int>>&Maze, Queu &Q, vector<vector<bool>>&visit, int goal[][2], int start[][2], int m, int n) { int heu = CalculateHeuristic(start[0][0], start[0][1], goal); Q.push({ heu,{ start[0][0], start[0][1] } }); while (!Q.empty()) { pair<int, pair<int, int>> val = Q.top(); Q.pop(); int i = 0, j = 0; i = val.second.first; j = val.second.second; visit[i][j] = true; cout << "( " << i << "," << j << ")" << " |"; if (is_Goal(goal, i, j)) { cout << "Goal found at " << i << "," << j << endl; return; } if (IsValid_move(Maze, visit, (i - 1), j, m, n)) { int heu = CalculateHeuristic((i - 1), j, goal); Q.push({ heu,{ (i - 1), j } }); } if (IsValid_move(Maze, visit, (1 + i), j, m, n)) { int heu = CalculateHeuristic((1 + i), j, goal); Q.push({ heu,{ (1 + i), j } }); } if (IsValid_move(Maze, visit, i, (j - 1), m, n)) { int heu = CalculateHeuristic(i, (j - 1), goal); Q.push({ heu,{ i, (j - 1) } }); } if (IsValid_move(Maze, visit, i, (1 + j), m, n)) { int heu = CalculateHeuristic(i, (1 + j), goal); Q.push({ heu,{ i, (1 + j) } }); } } cout << "No Goal Found!" << endl; } int main() { int m = 0, n = 0; int goal[1][2]; int start[1][2]; ifstream in; ofstream out; getFile(in, "in.txt"); in >> m >> n; in >> start[0][0] >> start[0][1]; in >> goal[0][0] >> goal[0][1]; goal[0][0]--, goal[0][1]--; vector<vector<int>>Maze(m, vector<int>(n)); vector<vector<bool>>visit(m, vector<bool>(n)); Queu Priority_fringe; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { in >> Maze[i][j]; visit[i][j] = false; cout << Maze[i][j] << " "; } cout << endl; } informedGBS(Maze, Priority_fringe, visit, goal, start, m, n); }
true
290af5f2abbc83294cb5a8ad04f5af2c1b1f5c6c
C++
leandrolillo/dev
/playground/src/video/Renderer.h
UTF-8
2,511
2.828125
3
[]
no_license
/* * Renderer.h * * Created on: Apr 1, 2021 * Author: leandro */ #ifndef SRC_VIDEO_RENDERER_H_ #define SRC_VIDEO_RENDERER_H_ #include<resources/ShaderProgramResource.h> #include<VideoRunner.h> #include<Camera.h> class Renderer { protected: const ShaderProgramResource *shader = null; VideoRunner *videoRunner = null; ResourceManager *resourceManager = null; bool enabled = true; public: // This did not work for some reason // Renderer(VideoRunner *videoRunner) { // this->videoRunner = videoRunner; // } virtual ~Renderer() {} void setVideoRunner(VideoRunner *videoRunner) { //This logic tries to make sure the video runner is valid. Maybe it would be better to use a reference here. if(videoRunner != null && videoRunner->getContainer() != null && videoRunner->getContainer()->getResourceManager() != null) { this->videoRunner = videoRunner; this->resourceManager = videoRunner->getContainer()->getResourceManager(); this->init(); } } void setShaderProgram(const ShaderProgramResource *shaderProgramResource) { this->shader = shaderProgramResource; } void sendMaterial(const MaterialResource *material) const { if(material != null) { videoRunner->sendVector("material.ambient", material->getAmbient()); videoRunner->sendVector("material.diffuse", material->getDiffuse()); videoRunner->sendVector("material.specular", material->getSpecular()); videoRunner->sendReal("material.alpha", material->getAlpha()); videoRunner->sendReal("material.shininess", material->getShininess()); } } void sendLight(const LightResource *light) const { if(light) { videoRunner->sendVector("light.ambient", light->getAmbient() * light->getShininess()); videoRunner->sendVector("light.diffuse", light->getDiffuse() * light->getShininess()); videoRunner->sendVector("light.specular", light->getSpecular() * light->getShininess()); videoRunner->sendVector("light.position", light->getPosition()); } } virtual bool init() { return true; }; virtual void render(const Camera &camera) = 0; virtual bool isEnabled() const { return this->videoRunner != null && shader != null && this->enabled; } void setEnabled(bool enabled) { this->enabled = enabled; } }; #endif /* SRC_VIDEO_RENDERER_H_ */
true
66590a4c9a506ecbe09ead6a5a87a7370a64af55
C++
sinanerdem/algorithms
/objects/recursion/numbinarydigit.cpp
UTF-8
1,405
2.734375
3
[]
no_license
/*---------------------------------------------------------------- Copyright (c) 2015 Author: Jagadeesh Vasudevamurthy file: num_binary_digit.cpp -----------------------------------------------------------------*/ /*---------------------------------------------------------------- All includes here -----------------------------------------------------------------*/ #include "recursion.h" /*---------------------------------------------------------------- WRITE CODE -----------------------------------------------------------------*/ /*---------------------------------------------------------------- num_binary_digit using iteration 0 1 1 1 4 100 15 1111 16 10000 -----------------------------------------------------------------*/ int recursion::num_binary_digit_iterative(unsigned n, int& num_itr){ if (n==0){return 1;} // int result=0; num_itr=0; while(n > 0){ // result += n%2 * pow(10,counter); n=n/2; num_itr++; } return num_itr; } int recursion::num_binary_digit_recursion(unsigned n, int& num_rec){ if (n<=1){ return 1; } num_rec++; return 1 + num_binary_digit_recursion(n/2, num_rec); } int recursion::num_binary_digit_stack(unsigned n, int& size_of_stack){ if (n<=1){ return 1; } dstack<int> s(_display); s.push(1); while(n>1){ s.push(n); n/=2; } size_of_stack = s.num_elements(); return s.num_elements(); } //EOF
true
e06db40af19f60418c8934480f7b6bb3870fea42
C++
095990/programming-kirpicheva-ulyana
/2021.09.20-Homework-2/Solution1/Project1/Source.cpp
WINDOWS-1251
2,311
3.109375
3
[ "Apache-2.0" ]
permissive
#include <iostream> using namespace std; int main(int argc, char* argv[]) { int n = 0; int a = 0; int b = 0; int c = 0; cin >> n; cin >> a; cin >> b; cin >> c; a = n / 100; b = n / 10 % 10; c = n % 10; switch (a) { case 1: cout << " "; break; case 2: cout << " "; break; case 3: cout << " "; break; case 4: cout << " "; break; case 5: cout << " "; break; case 6: cout << " "; break; case 7: cout << ""; break; case 8: cout << " "; break; case 9: cout << " "; break; default: break; } switch (b) { case 1: switch (c) { case 0: cout << " "; break; case 1: cout << " "; break; case 2: cout << " "; break; case 3: cout << " "; break; case 4: cout << " "; break; case 5: cout << " "; break; case 6: cout << " "; break; case 7: cout << " "; break; case 8: cout << " "; break; case 9: cout << " "; break; } break; case 2: cout << " "; break; case 3: cout << " "; break; case 4: cout << " "; break; case 5: cout << " "; break; case 6: cout << " "; break; case 7: cout << ""; break; case 8: cout << " "; break; case 9: cout << ""; break; default: break; } switch (c) { case 1: cout << " "; break; case 2: cout << " "; break; case 3: cout << " "; break; case 4: cout << " "; break; case 5: cout << " "; break; case 6: cout << " "; break; case 7: cout << " "; break; case 8: cout << " "; break; case 9: cout << " "; break; default: break; } if (c == 1) { cout << ""; } else if (c > 1 && c < 5) { cout << ""; } else { cout << "" << endl; } return EXIT_SUCCESS; }
true
3b617a44e277da09c24843b30beb0ee30e3a98a2
C++
Evalir/Algorithms
/Problems/TOJ/1017/1017/main.cpp
UTF-8
576
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; using ll = long long; int n; ll dp[510][510]; ll go(int cand, int rem) { if (rem == 0) return 1; ll w = 0; // increase cand if (dp[cand][rem] != -1) return dp[cand][rem]; if (cand + 1 <= rem) { w += go(cand + 1, rem); } // create tower with "cand" blocks if (cand <= rem) { w += go(cand+1, rem - cand); } dp[cand][rem] = w; return w; } int main() { cin >> n; memset(dp, -1, sizeof(dp)); ll ans = go(1, n)-1; cout << ans << endl; return 0; }
true
1fcd681d075c66a49b6e6861221c4320479f8535
C++
gameraccoon/hide-and-seek
/editor/src/componenteditcontent/typeeditconstructorhelpers.h
UTF-8
1,332
3.0625
3
[ "MIT" ]
permissive
#ifndef TYPEEDITCONSTRUCTORHELPERS_H #define TYPEEDITCONSTRUCTORHELPERS_H #include <memory> #include <functional> #include <QObject> namespace TypesEditConstructor { class BaseEdit { public: using Ptr = std::shared_ptr<BaseEdit>; }; template<typename T> class Edit : public BaseEdit { public: using Ptr = std::shared_ptr<Edit>; using WeakPtr = std::weak_ptr<Edit>; using OnChangeFn = std::function<void(const T&, const T&, bool)>; public: Edit(T initialValue) : mPrevValue(std::forward<T>(initialValue)) { } ~Edit() { delete mOwner; } void bindOnChange(OnChangeFn onChange) { mOnChange = onChange; } void transmitValueChange(T newValue, bool forceUpdateLayout = false) { if (newValue != mPrevValue) { if (mOnChange) { mOnChange(mPrevValue, std::forward<T>(newValue), forceUpdateLayout); } mPrevValue = newValue; } } void addChild(BaseEdit::Ptr child) { mChildObjects.emplace_back(child); } QObject* getOwner() { return mOwner; } T getPreviousValue() const { return mPrevValue; } Edit(const Edit&) = delete; Edit& operator=(const Edit&) = delete; private: T mPrevValue; OnChangeFn mOnChange; QObject* mOwner = HS_NEW QObject(); std::vector<BaseEdit::Ptr> mChildObjects; }; } #endif // TYPEEDITCONSTRUCTORHELPERS_H
true
c7c2ab910d744fb74321888372fe7cf2992bdb70
C++
luqilinok/Cpp-primer-Personal
/ch16/ex16_05.cpp
UTF-8
361
3.359375
3
[]
no_license
#include<iostream> #include<string> using namespace std; template<typename T, size_t N> void print(const T(&a)[N]) { for (auto iter = begin(a), iter != end(a); ++iter) { cout << *iter << endl; } cout << endl; } int main() { int a[6] = { 0,2,4,6,8,10 }; string vs[3] = { "hello","world","!" }; print(a); print(vs); system("pause"); return 0; }
true
97569b87d33b2caf39f0c038af95fd6e871ced36
C++
xpnguyen/GeomAlgoLib
/geom_algo_lib/mesh.h
UTF-8
5,315
2.921875
3
[]
no_license
#pragma once #include "base.h" #include "rtree.h" #include <unordered_map> #include <limits> typedef index_pair edge_type; typedef index_pair_hash edge_type_hash; struct mesh_face { static const mesh_face unset; union { struct { size_t a, b, c; }; size_t indices[3]; }; mesh_face(); mesh_face(size_t v1, size_t v2, size_t v3); mesh_face(size_t const indices[3]); void flip(); edge_type edge(uint8_t edgeIndex) const; bool contains_vertex(size_t vertIndex) const; bool is_degenerate() const; }; struct face_edges { size_t a = SIZE_MAX, b = SIZE_MAX, c = SIZE_MAX; face_edges() = default; face_edges(size_t const indices[3]); face_edges(size_t, size_t, size_t); void set(size_t, size_t, size_t); void set(size_t); }; enum class mesh_centroid_type { vertex_based = 0, area_based, volume_based }; enum class mesh_element { vertex, face }; class mesh { typedef std::vector<vec3>::const_iterator const_vertex_iterator; typedef std::vector<mesh_face>::const_iterator const_face_iterator; private: std::vector<vec3> m_vertices; std::vector<mesh_face> m_faces; /*Maps vertex indices to indices of connected faces.*/ std::vector<std::vector<size_t>> m_vertFaces; /*Maps the vertex indices to the indices of connected edges.*/ std::vector<std::vector<size_t>> m_vertEdges; /*Maps the vertex-index-pair to the index of the edge connecting those vertices.*/ std::unordered_map<edge_type, size_t, edge_type_hash> m_edgeIndexMap; /*Maps the edge index to the pair of connected vertex indices.*/ std::vector<edge_type> m_edges; /*Maps the edge index to the indices of the connected faces.*/ std::vector<std::vector<size_t>> m_edgeFaces; /*Maps the face index to the indices of the 3 edges connected to that face.*/ std::vector<face_edges> m_faceEdges; std::vector<vec3> m_vertexNormals; std::vector<vec3> m_faceNormals; bool m_isSolid; rtree3d m_faceTree; rtree3d m_vertexTree; void compute_cache(); void compute_topology(); void compute_rtrees(); void compute_normals(); void add_edge(const mesh_face&, size_t fi, uint8_t, size_t&); void add_edges(const mesh_face&, size_t fi); double face_area(const mesh_face& f) const; void get_face_center(const mesh_face& f, vec3& center) const; void check_solid(); vec3 area_centroid() const; vec3 volume_centroid() const; const rtree3d& element_tree(mesh_element element) const; void face_closest_pt(size_t faceIndex, const vec3& pt, vec3& closePt, double& bestSqDist) const; public: mesh(const mesh& other); mesh(const vec3* verts, size_t nVerts, const mesh_face* faces, size_t nFaces); mesh(const double* vertCoords, size_t nVerts, const size_t* faceVertIndices, size_t nFaces); size_t num_vertices() const noexcept; size_t num_faces() const noexcept; vec3 vertex(size_t vi) const; mesh_face face(size_t fi) const; vec3 vertex_normal(size_t vi) const; const vec3& face_normal(size_t fi) const; mesh::const_vertex_iterator vertex_cbegin() const; mesh::const_vertex_iterator vertex_cend() const; mesh::const_face_iterator face_cbegin() const; mesh::const_face_iterator face_cend() const; box3 bounds() const; double face_area(size_t fi) const; double area() const; box3 face_bounds(size_t fi) const; double volume() const; bool is_solid() const; vec3 centroid() const; vec3 centroid(const mesh_centroid_type centroid_type) const; bool contains(const vec3& pt) const; mesh* clipped_with_plane(const vec3& pt, const vec3& norm) const; template <typename size_t_inserter> void query_box(const box3& box, size_t_inserter inserter, mesh_element element) const { element_tree(element).query_box_intersects(box, inserter); }; template <typename size_t_inserter> void query_sphere(const vec3& center, double radius, size_t_inserter inserter, mesh_element element) const { element_tree(element).query_by_distance(center, radius, inserter); }; vec3 closest_point(const vec3& pt, double searchDist) const; }; PINVOKE void Mesh_GetData(mesh const* meshPtr, double*& vertices, int& nVerts, int*& faces, int& nFaces) noexcept; PINVOKE mesh* Mesh_Create(double const * vertices, int nVerts, int const* faces, int nFaces) noexcept; PINVOKE void Mesh_Delete(mesh const* meshPtr) noexcept; PINVOKE double Mesh_Volume(mesh const* meshPtr) noexcept; PINVOKE void Mesh_Centroid(mesh const* meshPtr, mesh_centroid_type type, double& x, double& y, double &z) noexcept; PINVOKE void Mesh_QueryBox(mesh const* meshptr, double const* bounds, int32_t*& retIndices, int32_t& numIndices, mesh_element element) noexcept; PINVOKE void Mesh_QuerySphere(mesh const* meshptr, double cx, double cy, double cz, double radius, int32_t*& retIndices, int32_t& numIndices, mesh_element element) noexcept; PINVOKE bool Mesh_ContainsPoint(mesh const* meshptr, double x, double y, double z); PINVOKE mesh* Mesh_ClipWithPlane(mesh const* meshptr, double* pt, double* norm); PINVOKE void Mesh_ClosestPoint(mesh const* meshptr, double* pt, double* closePt, double searchDistance);
true
47aaf76df7051f152be0c56f0ba44e34bc7974b8
C++
dmirmilshteyn/MIE444
/Follower/LineFollower.cpp
UTF-8
10,535
2.671875
3
[]
no_license
#include "LineFollower.h" // Global variables for line following int followerState = FOLLOWER_STATE_ONLINE; int turnState = TURN_STATE_DEFAULT; /*************LIne following PID constants***********/ float Kp = 2.1; float Ki = 0.003; float Kd = 700; float lastError; long integral = 0; bool leftForward = true; bool rightForward = true; /*************Wall Detection constants***********/ int wallSensorBuffer = 0; int wallBufferCounter = 0; double wallDistance = 0; int averageMotorSpeed;//avg PWM for both motors. Value is variable to control intersections and lane stability int stallPWM;//PWM at which the motor stalls unsigned long previousTime; unsigned long wallIdentificationStartTime = 0; int wallSampleCount = 0; int wallSampleTotal = 0; long wallEncoderTicks = 0; long wallTime = 0; float readLeft; float readRight; int determineStallPWMDone = 0; bool isRealigning = false; long lastRealignLeftMotorCount = 0; long lastRealignRightMotorCount = 0; int currentLeftMotorSpeed = 0; int currentRightMotorSpeed = 0; //CALCULATED THE PID CONTROLLER PARAMETERS void followLaneAnalog(unsigned long currentTime) { determineStallPWM(); float timeDifference = currentTime - previousTime; if (timeDifference < 1) { timeDifference = 1; } float derivative; float currentError = getLaneError(); //robot too far left is negative...too far right is positive float controller; integral = integral + (((currentError + lastError) / 2) * timeDifference); if (Ki * abs(integral) > 150) { if (integral > 0) { integral = 150 / Ki; } else { integral = -150 / Ki; } } derivative = (currentError - lastError) / timeDifference; lastError = currentError; controller = Kp * currentError + Ki * integral + Kd * derivative; MotorSpeeds motorSpeeds = driveMotorsPID(controller, derivative); publishLaneFollowingData(currentTime, motorSpeeds, currentError, integral, derivative, controller, readLeft, readRight); previousTime = currentTime; } //DRIVES MOTORS BASED ON PID CONTROLLER WHEN FOLLOWER_STATE_ONLINE MotorSpeeds driveMotorsBasic(float controller, float adjustedSpeed) { MotorSpeeds newMotorSpeeds; float speedOffsetFactor = abs(controller / 255); if (speedOffsetFactor > 1)speedOffsetFactor = 1; float speedOffset = speedOffsetFactor * (adjustedSpeed); /*int newLeftMotorSpeed; int newRightMotorSpeed;*/ if (controller <= 0) { newMotorSpeeds.left = adjustedSpeed; newMotorSpeeds.right = adjustedSpeed - speedOffset; } else if (controller > 0) { newMotorSpeeds.left = adjustedSpeed - speedOffset; newMotorSpeeds.right = adjustedSpeed; } //Controls what to do if the adjustedSpeed is too low //Function will assume the car is stopped and will try to keep the car centered with the line if (adjustedSpeed < stallPWM) { if (abs(lastError) > 50) { newMotorSpeeds.left = -signOf(controller) * (stallPWM + 10); newMotorSpeeds.right = signOf(controller) * (stallPWM + 10); } else { newMotorSpeeds.left = 0; newMotorSpeeds.right = 0; } } //checks if any of the motors are below stall PWM and sets them to zero else if (newMotorSpeeds.left < stallPWM || newMotorSpeeds.right < stallPWM) { if (abs(newMotorSpeeds.left) < stallPWM) { newMotorSpeeds.left = 0; } else if (abs(newMotorSpeeds.right) < stallPWM) { newMotorSpeeds.right = 0; } } /*if (readLeft < 750 && readRight < 750) { newRightMotorSpeed = 0; newLeftMotorSpeed = 0; }*/ //stops the car if it left the line (on white) return newMotorSpeeds; } //UPDATED THE FOLLOWER STATE void updateFollowerState(unsigned long currentTime) { if (readLeft < 600 && readRight < 600 && followerState != FOLLOWER_STATE_RIGHT && followerState != FOLLOWER_STATE_LEFT && followerState != FOLLOWER_STATE_STRAIGHT && followerState != FOLLOWER_STATE_WALL_DEADEND) { followerState = FOLLOWER_STATE_OFFLINE; } else if (followerState == FOLLOWER_STATE_OFFLINE) { followerState = FOLLOWER_STATE_ONLINE; } if (isRealigning && readLeft >= 600 && readRight >= 600) { if (lastRealignLeftMotorCount == -1 && lastRealignRightMotorCount == -1) { lastRealignLeftMotorCount = leftMotorCount; lastRealignRightMotorCount = rightMotorCount; } else if (leftMotorCount > lastRealignLeftMotorCount + 200 && rightMotorCount > lastRealignRightMotorCount + 200) { detectedIntersection = INTERSECTION_TYPE_NONE; isRealigning = false; } } if (followerState == FOLLOWER_STATE_STRAIGHT && detectedIntersection == INTERSECTION_TYPE_NONE && !IsSensorOnOrApproaching(SENSOR_LOCATION_LEFT) && !IsSensorOnOrApproaching(SENSOR_LOCATION_RIGHT) && readLeft >= 600 && readRight >= 600) { followerState = FOLLOWER_STATE_ONLINE; } } //THIS FUNCTION DRIVES THE MOTORS BASED ON THE STATE OF THE FOLLOWER. //driveMotorsBasic IS ENVOKED IF THE FOLLOWER IS IN ITS DEFAULT LINE FOLLOWING STATE MotorSpeeds driveMotorsPID(float controller, float derivative) { float adjustedSpeed = averageMotorSpeed; MotorSpeeds motorSpeeds; if (followerState == FOLLOWER_STATE_ONLINE || followerState == FOLLOWER_STATE_STRAIGHT) { motorSpeeds = driveMotorsBasic(controller, adjustedSpeed); } else if (followerState == FOLLOWER_STATE_OFFLINE) { motorSpeeds.left = -(adjustedSpeed * 1.2); motorSpeeds.right = adjustedSpeed * 1; } else if (followerState == FOLLOWER_STATE_WALL_START_DONE) { motorSpeeds.right = 0; motorSpeeds.left = 0; } else if (followerState == FOLLOWER_STATE_LEFT || followerState == FOLLOWER_STATE_RIGHT || followerState == FOLLOWER_STATE_WALL_DEADEND) { switch (turnState) { case TURN_STATE_DEFAULT: if (IsSensorOnOrApproaching(SENSOR_LOCATION_FRONT) == false) { turnState = TURN_STATE_HIT_WHITE; } break; case TURN_STATE_HIT_WHITE: if (IsSensorOnOrApproaching(SENSOR_LOCATION_FRONT)) { turnState = TURN_STATE_HIT_BLACK; } break; } if (turnState == TURN_STATE_HIT_BLACK) { turnState = TURN_STATE_DEFAULT; followerState = FOLLOWER_STATE_ONLINE; motorSpeeds.left = 0; motorSpeeds.right = 0; } else { if (followerState == FOLLOWER_STATE_LEFT) { // Turn left motorSpeeds.left = -averageMotorSpeed * 1.2; motorSpeeds.right = averageMotorSpeed * 1.25; } else if (followerState == FOLLOWER_STATE_RIGHT) { // Turn right motorSpeeds.right = -averageMotorSpeed * 1.2; motorSpeeds.left = averageMotorSpeed * 1.25; } else if (followerState == FOLLOWER_STATE_WALL_DEADEND) { // Turn right wallTime = millis(); isRealigning = true; lastRealignLeftMotorCount = -1; lastRealignRightMotorCount = -1; motorSpeeds.right = -(adjustedSpeed * 1.2); motorSpeeds.left = adjustedSpeed * 1; // Allow the planner to handle any cases before finalizing the rotation motorSpeeds = ProcessBeforeDeadEnd(motorSpeeds); } } } else if (followerState == FOLLOWER_STATE_WALL_START_DONE) { // Aaaaannnnnndd we're done! motorSpeeds.right = 0; motorSpeeds.left = 0; } driveMotorsAtSpeed(motorSpeeds); if (motorSpeeds.left == 0 && motorSpeeds.right == 0) { //delay(2000); lastIntersectionDetectionLeftEncoder = leftMotorCount; lastIntersectionDetectionRightEncoder = rightMotorCount; } return motorSpeeds; } //Function returns error of car's position relative to the lane float getLaneError() { readLeft = analogRead(LINE_FOLLOW_SENSOR_LEFT); readRight = analogRead(LINE_FOLLOW_SENSOR_RIGHT); return readLeft - readRight - 32; } //THIS FUNCTION WILL DETERMINE THE PWM AT WHICH THE MOTORS STALL //BY INCREMENTING PWM UNTIL THE ROVER STARTS MOVING. //IT IS TO ENSURE THE MOTORS NEVER OPERATE AT STALL PWM TO PREVENT DAMAGE. void determineStallPWM() { if (determineStallPWMDone == 0) { int i = 0; analogWrite(BIN2_LEFT_MOTOR, 0); analogWrite(AIN2_RIGHT_MOTOR, 0); do { delay(5); analogWrite(BIN1_LEFT_MOTOR, i);//drives left motor forward analogWrite(AIN1_RIGHT_MOTOR, i);//drives right motor forward i++; } while (leftMotorCount < 10 || rightMotorCount < 10); //((previousLeftMotorCount - leftMotorCount) / (1 / 1000) < (1204 * 0.05)); stallPWM = i;//i;// * 1.2; averageMotorSpeed = 90;//(255 - stallPWM) * 0.2 + stallPWM; leftMotorCount = 0; rightMotorCount = 0; determineStallPWMDone = 1; //publishSyncData(); } } //CODE FOR WALL DETECTION //FOLLOWER STATE WILL CHANGE TO FOLLOWER_STATE_WALL_DEADEND ONCE A WALL IS DETECTED void wallDetection(unsigned long currentTime) { wallSensorBuffer += analogRead(WALL_DISTANCE_SENSOR); wallBufferCounter++; if (wallBufferCounter >= 10) { wallDistance = ((double)wallSensorBuffer) / wallBufferCounter; wallBufferCounter = 0; wallSensorBuffer = 0; } if (followerState == FOLLOWER_STATE_ONLINE) { if (wallDistance > 200 ) { wallDistance = 0; followerState = FOLLOWER_STATE_WALL_DEADEND; } } } void wallDetection2(unsigned long currentTime) { if (followerState == FOLLOWER_STATE_ONLINE) { if (currentTime > wallTime + 1000) { wallTime = currentTime; if ((leftMotorCount + rightMotorCount) / 2 < wallEncoderTicks + 10) { followerState = FOLLOWER_STATE_WALL_DEADEND; } wallTime = currentTime; wallEncoderTicks = (leftMotorCount + rightMotorCount) / 2; } } } void driveMotorsAtSpeed(MotorSpeeds speeds) { #ifndef NOMOTORS //next 4 if statements drive the left and right motors forward or back depending on the signs of newLeftMotorSpeed and newRightMotorSpeed if (speeds.left >= 0) { leftForward = true; analogWrite(BIN2_LEFT_MOTOR, 0); analogWrite(BIN1_LEFT_MOTOR, speeds.left);//drives left motor forward } else { leftForward = false; analogWrite(BIN1_LEFT_MOTOR, 0); analogWrite(BIN2_LEFT_MOTOR, -speeds.left);//drives left motor reverse } if (speeds.right >= 0) { rightForward = true; analogWrite(AIN2_RIGHT_MOTOR, 0); analogWrite(AIN1_RIGHT_MOTOR, speeds.right);//drives right motor forward } else { rightForward = false; analogWrite(AIN1_RIGHT_MOTOR, 0); analogWrite(AIN2_RIGHT_MOTOR, -speeds.right);//drives right motor reverse } currentLeftMotorSpeed = speeds.left; currentRightMotorSpeed = speeds.right; #endif }
true
5559e89c5ae025cbb8cfa3ab4a27a8388c6eeae2
C++
zerlok/nsu-prog-all
/oop/task6/lifeobject.cpp
UTF-8
3,023
3.140625
3
[]
no_license
#include <vector> #include "lifeobject.h" #include "action.h" #include "populationmap.h" LifeObject::LifeObject(const Point &pos, int health, int damage, int mass) : _position(pos), _ttl(health), _damage(damage), _mass(mass), _type(Type::none) { if (_damage < Config::object_min_damage) _damage = Config::object_min_damage; if (_mass < Config::object_min_mass) _mass = Config::object_min_mass; } LifeObject::LifeObject(const LifeObject &obj) : _position(obj._position), _ttl(obj._ttl), _damage(obj._damage), _mass(obj._mass), _type(obj._type) { } LifeObject::~LifeObject() { } bool LifeObject::is_alive() const { return (_ttl > Config::object_dead_ttl); } bool LifeObject::is_eatable() const { return (_mass > Config::object_min_mass); } int LifeObject::get_health() const { return _ttl; } int LifeObject::get_damage() const { return _damage; } int LifeObject::get_mass() const { return _mass; } const LifeObject::Type &LifeObject::get_type() const { return _type; } const Point &LifeObject::get_position() const { return _position; } bool LifeObject::make_older() { if (!is_alive()) return false; --_ttl; if (!is_alive()) { kill(); return false; } return true; } LifeObject *LifeObject::clone() const { return new LifeObject(*this); } LifeObject::Action *LifeObject::create_action(const PopulationMap &map) { return nullptr; } void LifeObject::decrement_mass() { --_mass; } bool LifeObject::operator==(const LifeObject &obj) const { return (_type == obj._type); } bool LifeObject::operator!=(const LifeObject &obj) const { return !((*this) == obj); } bool LifeObject::operator<(const LifeObject &obj) const { return (_type < obj._type); } bool LifeObject::operator>(const LifeObject &obj) const { return (obj < (*this)); } bool LifeObject::operator<=(const LifeObject &obj) const { return (((*this) < obj) || ((*this) == obj)); } bool LifeObject::operator>=(const LifeObject &obj) const { return (obj <= (*this)); } void LifeObject::deal_damage(int dmg) { _ttl -= dmg; if (!is_alive()) kill(); } void LifeObject::kill() { _ttl = Config::object_dead_ttl; } LifeObject::Type get_type_by_name(const std::string &name) { if (!name.compare("Plant")) return LifeObject::Type::plant; else if (!name.compare("Herbivorous")) return LifeObject::Type::herbivorous; else if (!name.compare("Predator")) return LifeObject::Type::predator; return LifeObject::Type::none; } std::ostream &operator<<(std::ostream &out, const LifeObject::Type &type) { switch (type) { case LifeObject::Type::plant: out << "Plant"; break; case LifeObject::Type::herbivorous: out << "Herbivorous"; break; case LifeObject::Type::predator: out << "Predator"; break; default: case LifeObject::Type::none: out << "None"; break; } return out; } std::istream &operator>>(std::istream &in, LifeObject::Type &type) { std::string str; in >> str; type = get_type_by_name(str); return in; }
true
1567014179f15dfef85a9eb7c549cf21c9536703
C++
Nitish-K15/ADA
/Sorting/Practice.cpp
UTF-8
1,458
3.703125
4
[]
no_license
// Practice.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include<stdlib.h> #include<time.h> void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; } void SelectionSort(int a[]) { int min; for (int i = 0;i < 9;i++) { min = i; for (int j = i + 1;j < 10;j++) if (a[j] < a[min]) min = j; swap(a[i], a[min]); } } void display(int a[]) { for (int i = 0; i < 10;i++) std::cout << a[i] << " "; std::cout << "\n"; } int partition(int a[], int l, int h,int pivot) { while (l <= h) { while (a[l] < pivot) { l++; } while (a[h] > pivot) { h--; } if(l<=h) { swap(a[l],a[h]); l++; h--; } } return l; } void QuickSort(int a[], int l, int h) { if (l >= h) { return; } else { int pivot = a[(l + h) / 2]; int index = partition(a, l, h, pivot); QuickSort(a, l, index - 1); QuickSort(a, index, h); } } int main() { srand (time(NULL)); int a[10]; for(int i = 0;i < 10; i++) a[i] = rand() % 10 + 1; std::cout << "Array before sorting is "; display(a); //SelectionSort(a); QuickSort(a, 0, 9); std::cout << "Array after sorting is "; display(a); }
true
2e5065652edb23ba285f76aaca30f1ff80690984
C++
Rafat001/Solved_UVA_Problems_By_Rafat001
/UVA 294.cpp
UTF-8
796
2.765625
3
[]
no_license
#include<stdio.h> #include<math.h> int main() { long long t,i,a,b,limit,sum,maxx,n,j,k; scanf("%lld",&t); for(i=1; i<=t; i++) { maxx=0; scanf("%lld%lld",&a,&b); for(j=a; j<=b; j++) { sum=0; limit=sqrt(j); for(k=1; k<=limit; k++) { if(j%k==0) { sum++; if(j/k!=k) { sum++; } } } if(sum>maxx) { maxx=sum; n=j; } } printf("Between %lld and %lld, %lld has a maximum of %lld divisors.\n",a,b,n,maxx); } return 0; }
true
fa32cec7b9cfdbf3ad342dc4c69cc4fa89bbd262
C++
rallister/Phasor
/Phasor/PhasorAPI/memory.cpp
UTF-8
10,923
3.046875
3
[]
no_license
#include "memory.h" #include "api_readers.h" #include "../Common/MyString.h" #include <limits> using namespace Common; using namespace Manager; // Not sure why std::numeric_limits<T>::max conflicts with these defines // But it is.. #undef max #undef min static const int kMaxStringElements = 80; // Parses the input arguments into the destination address and (if specified) // the bit offset. struct s_number_read_info { LPBYTE address; int bit_offset; size_t i ; // kMaxArgsNormalRead is the maximum number of arguments that can // be passed in a normal (byte level) read. A bit read is always // kMaxArgsNormalRead + 1. s_number_read_info(const Object::unique_deque& args, bool is_read_bit, int kMaxArgsNormalRead = 2) : i(0) { address = (LPBYTE)ReadNumber<DWORD>(*args[i++]); if (!is_read_bit) { if (args.size() == kMaxArgsNormalRead) AddToAddress(*args[i++]); } else { // reading bit so extract the bit offset if (args.size() == kMaxArgsNormalRead + 1) AddToAddress(*args[i++]); bit_offset = ReadNumber<int>(*args[i++]); address += bit_offset / 8; bit_offset %= 8; } } void AddToAddress(const Object& num) { address += ReadNumber<DWORD>(num); } }; // Parse and validate input arguments ready for writing. template <typename T> struct s_number_write_info : s_number_read_info { T data; // Check the value is within the expected type's range. template <typename Type> bool CheckTypeLimits(double value, Type* out) { static const T max_value = std::numeric_limits<Type>::max(); static const T min_value = std::numeric_limits<Type>::min(); *out = (Type)value; return value <= max_value && value >= min_value; } template <> bool CheckTypeLimits<bool>(double value, bool* out) { *out = value == 1; return value == 1 || value == 0; } template <> bool CheckTypeLimits<float>(double value, float* out) { static const float max_value = std::numeric_limits<float>::max(); static const float min_value = -max_value; *out = (float)value; return value <= max_value && value >= min_value; } template <> bool CheckTypeLimits<double>(double value, double* out) { *out = value; return true; } // Can throw if value is out of range. s_number_write_info(CallHandler& handler, const Object::unique_deque& args, bool is_write_bit) : s_number_read_info(args, is_write_bit, 3) { double value = ReadNumber<double>(*args[i++]); if (!CheckTypeLimits<T>(value, &data)) handler.RaiseError("attempted to write value outside of type's range."); if (is_write_bit) { BYTE b = read_data<BYTE>(handler, address); if (data == 1) data = (BYTE)(b | (1 << bit_offset)); else { data = (BYTE)(b & ~(1 << bit_offset)); //data = (BYTE)(b ^ (1 << bit_offset)); } } } }; // shouldn't use bool template <> struct s_number_write_info<bool> {}; // Helper functions for reading/writing strings. template <typename T> void copy_string(const T* src, int elem_count, T* dest); template <> void copy_string<char>(const char* src, int elem_count, char* dest) { strcpy_s(dest, elem_count, src); } template <> void copy_string<wchar_t>(const wchar_t* src, int elem_count, wchar_t* dest) { wcscpy_s(dest, elem_count, src); } // ------------------------------------------------------------------------ // Reading functions template <class T> T readstring(typename T::value_type* src, int size_bytes) { typedef T::value_type char_type; char_type buff[81]; int buffer_char_count = sizeof(buff)/sizeof(char_type); int read_char_count = size_bytes / sizeof(char_type); int use_count = buffer_char_count < read_char_count ? buffer_char_count : read_char_count; copy_string<char_type>(src, use_count, buff); // make sure it's null terminated buff[use_count - 1] = 0; return buff; } template <class T> T reader(LPBYTE address, DWORD) { return *(T*)address; } template <> std::string reader<std::string>(LPBYTE address, DWORD size_bytes) { return readstring<std::string>((char*)address, size_bytes); } template <> std::wstring reader<std::wstring>(LPBYTE address, DWORD size_bytes) { return readstring<std::wstring>((wchar_t*)address, size_bytes); } // Reads from the specified memory address and raises a script error if // the address is invalid. template <class T> T read_data(CallHandler& handler, LPBYTE destAddress, DWORD size=sizeof(T)) { T data; DWORD oldProtect = 0; if (VirtualProtect(UlongToPtr(destAddress), size, PAGE_EXECUTE_READ, &oldProtect)) { data = reader<T>(destAddress, size); VirtualProtect(UlongToPtr(destAddress), size, oldProtect, &oldProtect); } else { std::string err = m_sprintf("Attempting read to invalid memory address %08X", destAddress); handler.RaiseError(err); } return data; } // ------------------------------------------------------------------------ // Writer functions template <class T> void writer(LPBYTE address, T data, DWORD) { *(T*)(address) = data; } template <> void writer<std::string>(LPBYTE address, std::string data, DWORD) { copy_string<char>(data.c_str(), data.size(), (char*)address); } template <> void writer<std::wstring>(LPBYTE address, std::wstring data, DWORD) { copy_string<wchar_t>(data.c_str(), data.size()+1, (wchar_t*)address); } template <class T> void write_data(CallHandler& handler, LPBYTE destAddress, T data, DWORD size = sizeof(T)) { DWORD oldProtect = 0; if (VirtualProtect(UlongToPtr(destAddress), size, PAGE_EXECUTE_READWRITE, &oldProtect)) { writer<T>(destAddress, data, size); VirtualProtect(UlongToPtr(destAddress), size, oldProtect, &oldProtect); FlushInstructionCache(GetCurrentProcess(), UlongToPtr(destAddress), size); } else { std::string err = m_sprintf("Attempting write to invalid memory address %08X", destAddress); handler.RaiseError(err); } } // ------------------------------------------------------------------------ // Reader/writer functions used by rest of the script. // // Reads from the specified memory address and raises a script error if the // address. The result is added to results. template <typename T> void read_number(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { s_number_read_info r(args, false); T value = read_data<T>(handler, r.address); results.push_back(std::unique_ptr<Object>(new ObjNumber(value))); } template <typename T> void read_string(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { LPBYTE address = (LPBYTE)ReadNumber<DWORD>(*args[0]); DWORD length = 0; if (args.size() == 2) length = ReadNumber<DWORD>(*args[1]); if (length > kMaxStringElements) handler.RaiseError("max string length is 80"); DWORD byte_length = length == 0 ? kMaxStringElements : length; byte_length *= sizeof(T::value_type); T str = read_data<T>(handler, address, byte_length); AddResultString(str, results); } // Writes to the specified memory address and raises a script error if the // address is invalid or if they value being written is outside the type's // range. template <class T> void write_number(CallHandler& handler, Object::unique_deque& args, bool write_bit=false) { s_number_write_info<T> w(handler, args, write_bit); write_data<T>(handler, w.address, w.data); } template <class T> void write_string(CallHandler& handler, LPBYTE address, T str) { write_data<T>(handler, address, str, (str.size() + 1)*sizeof(T::value_type)); } // ------------------------------------------------------------------------- // void l_readbit(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { s_number_read_info r(args, true); BYTE b = read_data<BYTE>(handler, r.address); bool bit = (b & (1 << r.bit_offset)) != 0; results.push_back(std::unique_ptr<Object>(new ObjBool(bit))); } void l_readbyte(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { read_number<BYTE>(handler, args, results); } void l_readchar(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { read_number<char>(handler, args, results); } void l_readword(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { read_number<WORD>(handler, args, results); } void l_readshort(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { read_number<short>(handler, args, results); } void l_readdword(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { read_number<DWORD>(handler, args, results); } void l_readint(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { read_number<int>(handler, args, results); } void l_readfloat(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { read_number<float>(handler, args, results); } void l_readdouble(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { read_number<double>(handler, args, results); } void l_readstring(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { read_string<std::string>(handler, args, results); } void l_readwidestring(CallHandler& handler, Object::unique_deque& args, Object::unique_list& results) { read_string<std::wstring>(handler, args, results); } void l_writebit(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { write_number<BYTE>(handler, args, true); } void l_writebyte(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { write_number<BYTE>(handler, args); } void l_writechar(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { write_number<char>(handler, args); } void l_writeword(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { write_number<WORD>(handler, args); } void l_writeshort(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { write_number<short>(handler, args); } void l_writedword(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { write_number<DWORD>(handler, args); } void l_writeint(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { write_number<int>(handler, args); } void l_writefloat(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { write_number<float>(handler, args); } void l_writedouble(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { write_number<double>(handler, args); } void l_writestring(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { LPBYTE address = (LPBYTE)ReadNumber<DWORD>(*args[0]); std::string str = ReadRawString(*args[1]); write_string<std::string>(handler, address, str); } void l_writewidestring(CallHandler& handler, Object::unique_deque& args, Object::unique_list&) { LPBYTE address = (LPBYTE)ReadNumber<DWORD>(*args[0]); std::wstring str = WidenString(ReadRawString(*args[1])); write_string<std::wstring>(handler, address, str); }
true
3d504f7adb2257eb4686666b3e502a8150da2e8f
C++
spott/microcontroller-projects
/projects/drummaster/rev2/src/pad/Pad.cpp
UTF-8
7,423
2.546875
3
[]
no_license
#include "Pad.h" #include "HiHat.h" #include "Drum.h" #include "Cymbal.h" using namespace digitalcave; ADC* Pad::adc = NULL; Pad* Pad::pads[PAD_COUNT] = { // Type MUX Indices DT Fade new HiHat( MUX_0, MUX_1, MUX_15, 50, 0.95), //Hihat + Pedal new Drum( MUX_2, 50), //Snare new Drum( MUX_3, 50), //Bass new Drum( MUX_4, 50), //Tom1 new Cymbal( MUX_5, MUX_14, 50, 0.98), //Crash new Drum( MUX_6, 50), //Tom2 new Drum( MUX_7, 50), //Tom3 new Cymbal( MUX_8, MUX_13, 50, 0.97), //Splash new Cymbal( MUX_9, MUX_12, 50, 0.99), //Ride new Drum( MUX_10, 50), //X0 new Drum( MUX_11, 50) //X1 }; //Initialize static pads array uint8_t Pad::currentIndex = 0; void Pad::init(){ //Initialize the ADC adc = new ADC(); adc->setResolution(10); adc->setConversionSpeed(ADC_LOW_SPEED); adc->setSamplingSpeed(ADC_VERY_LOW_SPEED); adc->setAveraging(4); //Drain any charge which is currently in each channel digitalWriteFast(DRAIN_EN, MUX_ENABLE); digitalWriteFast(ADC_EN, MUX_ENABLE); for(uint8_t i = 0; i < CHANNEL_COUNT; i++){ digitalWriteFast(MUX0, i & 0x01); digitalWriteFast(MUX1, i & 0x02); digitalWriteFast(MUX2, i & 0x04); digitalWriteFast(MUX3, i & 0x08); for(uint8_t i = 0; i < 5 && adc->analogRead(ADC_INPUT) > 3; i++) { delay(1); } } digitalWriteFast(ADC_EN, MUX_DISABLE); digitalWriteFast(DRAIN_EN, MUX_DISABLE); } Pad::Pad(uint8_t doubleHitThreshold) : strikeTime(0), peakValue(0), playTime(0), lastPiezo(0), doubleHitThreshold(doubleHitThreshold), padIndex(currentIndex), lastSample(NULL) { currentIndex++; } void Pad::play(double volume){ if (volume < 0) volume = 0; else if (volume >= 5.0) volume = 5.0; lastSample = Sample::findAvailableSample(padIndex, volume); lastSample->play(lookupFilename(volume), padIndex, volume); } double Pad::readPiezo(uint8_t muxIndex){ //Disable both MUXs digitalWriteFast(ADC_EN, MUX_DISABLE); digitalWriteFast(DRAIN_EN, MUX_DISABLE); //Set Sample digitalWriteFast(MUX0, muxIndex & 0x01); digitalWriteFast(MUX1, muxIndex & 0x02); digitalWriteFast(MUX2, muxIndex & 0x04); digitalWriteFast(MUX3, muxIndex & 0x08); //Enable ADC MUX... digitalWriteFast(ADC_EN, MUX_ENABLE); //Wait a bit to ensure a good signal from the MUX delayMicroseconds(5); //... read value... uint16_t currentValue = adc->analogRead(ADC_INPUT); //... and disable MUX again digitalWriteFast(ADC_EN, MUX_DISABLE); //If we are within double trigger threshold, AND the currentValue is greater than the last played value, // then we adjust the volume of the last played sample. We don't enable thr drain this time through; // if the volume is stable then it will be enabled next time around, and if it is still increasing we // want to go through here again. if (playTime + doubleHitThreshold > millis() && currentValue > lastRaw && lastSample != NULL){ double adjustedVolume = (currentValue - MIN_VALUE) / 256.0 * padVolume; lastSample->setVolume(adjustedVolume); lastRaw = currentValue; return 0; } //If we are still within the double hit threshold, OR if we are within 4x the double hit threshold // time-span AND the currently read value is less than one quarter of the previous one, then we // assume this is just a ghost double trigger. Re-enable the drain each time we go through here. if (playTime + doubleHitThreshold > millis() || (playTime + (doubleHitThreshold * 4) > millis() && ((currentValue - MIN_VALUE) / 256.0 * padVolume) < (lastPiezo / 4))){ digitalWriteFast(DRAIN_EN, MUX_ENABLE); delayMicroseconds(50); return 0; } if (currentValue < MIN_VALUE && peakValue < MIN_VALUE){ //No hit in progress } else if (currentValue >= MIN_VALUE && peakValue == 0){ //A new hit has started; record the time strikeTime = millis(); peakValue = currentValue; } else if (currentValue > peakValue){ //Volume is still increasing; record this as the new peak value peakValue = currentValue; } if (peakValue && (millis() - strikeTime) > MAX_RESPONSE_TIME){ //We have timed out; send whatever the peak value currently is double result = (peakValue - MIN_VALUE) / 256.0 * padVolume; lastRaw = peakValue; playTime = millis(); peakValue = 0; lastPiezo = result; return result; } return 0; } char* Pad::lookupFilename(double volume){ //Limit volume from 0 to 1 if (volume < 0) volume = 0; else if (volume >= 1.0) volume = 1.0; if (sampleVolumes == 0x00 || strlen(filenamePrefix) == 0x00) { return NULL; } //We find the closest match in fileCountByVolume int8_t closestVolume = volume * 16; //Multiply by 16 to get into the 16 buckets of the samples //Start at the current bucket; if that is not a match, look up and down until a match is found. At // most this will take 16 tries (since there are 16 buckets) for(uint8_t i = 0; i < 16; i++){ if (((closestVolume + i) <= 0x0F) && (sampleVolumes & _BV(closestVolume + i))) { closestVolume = closestVolume + i; break; } else if (((closestVolume - i) >= 0x00) && (sampleVolumes & _BV(closestVolume - i))) { closestVolume = closestVolume - i; break; } } closestVolume = closestVolume & 0x0F; snprintf(filenameResult, sizeof(filenameResult), "%s_%X.RAW", filenamePrefix, closestVolume); return filenameResult; } double Pad::getPadVolume(){ return padVolume; } void Pad::setPadVolume(double volume){ if (volume < 0) volume = 0; else if (volume >= 5.0) volume = 5.0; padVolume = volume; } void Pad::loadAllSamples(uint8_t kitIndex){ if (kitIndex >= Mapping::getKitCount()) kitIndex = 0; Mapping* mapping = Mapping::getMapping(kitIndex); for (uint8_t i = 0; i < PAD_COUNT; i++){ pads[i]->loadSamples(mapping->getFilenamePrefix(i)); pads[i]->fadeOverride = mapping->getCustom(i); } } void Pad::loadSamples(char* filenamePrefix){ //Clear the filenames for (uint8_t i = 0; i < sizeof(this->filenamePrefix); i++){ this->filenamePrefix[i] = 0x00; } for (uint8_t i = 0; i < sizeof(this->filenameResult); i++){ this->filenameResult[i] = 0x00; } //The filename prefix must be at least three chars if (strlen(filenamePrefix) < 3) return; strncpy(this->filenamePrefix, filenamePrefix, FILENAME_PREFIX_STRING_SIZE - 1); //Reset sampleVolumes sampleVolumes = 0x00; SerialFlash.opendir(); while (1) { char filename[16]; unsigned long filesize; if (SerialFlash.readdir(filename, sizeof(filename), filesize)) { uint8_t filenamePrefixLength = strlen(filenamePrefix); if (filenamePrefixLength > 6) filenamePrefixLength = 6; //Check that this filename starts with the currently assigned filename prefix if (strncmp(filenamePrefix, filename, filenamePrefixLength) != 0) { continue; } //Check that there is an underscore character immediately after the filename prefix. if (filename[filenamePrefixLength] != '_'){ continue; //Invalid filename, missing '_' before volume. } //Check that the filename volume is valid (0..F). The volume is the second character after the prefix. char fileVolume = filename[filenamePrefixLength + 1]; uint8_t volume; if (fileVolume >= '0' && fileVolume <= '9') volume = fileVolume - 0x30; else if (fileVolume >= 'A' && fileVolume <= 'F') volume = fileVolume - 0x37; else { continue; //Invalid volume } sampleVolumes |= _BV(volume); } else { break; // no more files } } }
true
8cf1b9ff1f58ae0ea8bf82cb13d6e8540842da6f
C++
Wingxvii/Ubisoft
/GameTest/Network.cpp
UTF-8
1,513
2.734375
3
[]
no_license
#include "stdafx.h" #include "Network.h" Network::Network() { } Network::Network(std::string ip) { //Start Winsock WSADATA data; WORD version = MAKEWORD(2, 2); //startup int wsOk = WSAStartup(version, &data); if (wsOk != 0) { return; } //socket connection tcp = socket(AF_INET, SOCK_STREAM, 0); //socket setup serverTCP.sin_family = AF_INET; serverTCP.sin_port = htons(54000); Connect(ip); } //connect to server void Network::Connect(std::string ip) { inet_pton(AF_INET, ip.c_str(), &serverTCP.sin_addr); int connResult = connect(tcp, (sockaddr*)&serverTCP, sizeof(serverTCP)); if (connResult == SOCKET_ERROR) { int x = WSAGetLastError(); } else { listening = true; } } //begin multithreaded updates void Network::StartUpdate() { std::thread update = std::thread([&]() { while (listening) { char* buf = new char[MAX_PACKET_SIZE]; int length = recv(tcp, buf, MAX_PACKET_SIZE, 0); if (length == SOCKET_ERROR) { int error = WSAGetLastError(); } Packet packet; packet.deserialize(buf); packetsIn.push_back(packet); } }); update.detach(); } //send data to network void Network::SendData(int packetType) { Packet packet; packet.packet_type = packetType; const unsigned int packet_size = sizeof(packet); char packet_data[packet_size]; //seralize packet.serialize(packet_data); int sendResult = send(tcp, packet_data, packet_size, 0); } //cleanup void Network::ShutDown() { listening = false; closesocket(tcp); WSACleanup(); }
true
e92f84ec568800f9d010fc8911114ac7f2f1825f
C++
cvmfs/cvmfs
/test/unittests/t_uid_map.cc
UTF-8
6,314
2.875
3
[]
permissive
/** * This file is part of the CernVM File System. */ #include <gtest/gtest.h> #include "uid_map.h" #include "util/posix.h" template <typename MapT> class T_UidMap : public ::testing::Test { protected: static const std::string sandbox; protected: typedef typename MapT::key_type key_type; typedef typename MapT::value_type value_type; protected: void SetUp() { const bool retval = MkdirDeep(sandbox, 0700); ASSERT_TRUE(retval) << "failed to create sandbox"; } void TearDown() { const bool retval = RemoveTree(sandbox); ASSERT_TRUE(retval) << "failed to remove sandbox"; } void WriteFile(const std::string &path, const std::string &content) { FILE *f = fopen(path.c_str(), "w+"); ASSERT_NE(static_cast<FILE*>(NULL), f) << "failed to open. errno: " << errno; const size_t bytes_written = fwrite(content.data(), 1, content.length(), f); ASSERT_EQ(bytes_written, content.length()) << "failed to write. errno: " << errno; const int retval = fclose(f); ASSERT_EQ(0, retval) << "failed to close. errno: " << errno; } std::string GetValidFile() { const std::string valid_file = "# comment\n" // comment "42 3\n" // ordinary rule "1 2\n" // ordinary rule with multiple spaces "\n" // empty line "# comment\n" // comment "* 1337\n"; // default value const std::string path = CreateTempPath(sandbox + "/valid", 0600); WriteFile(path, valid_file); return path; } std::string GetInvalidFile1() { const std::string invalid_file = "# comment\n" // comment "42 3\n" // ordinary rule "1 *\n" // invalid rule (non-numeric map result) <--- "\n" // empty line "# comment\n" // comment "* 1337\n"; // default value const std::string path = CreateTempPath(sandbox + "/invalid", 0600); WriteFile(path, invalid_file); return path; } std::string GetInvalidFile2() { const std::string invalid_file = "# comment\n" // comment "12 4\n" // ordinary rule "1\n"; // invalid rule (no map result) <--- const std::string path = CreateTempPath(sandbox + "/invalid", 0600); WriteFile(path, invalid_file); return path; } std::string GetInvalidFile3() { const std::string invalid_file = "# empty file\n" // comment "foo 14"; // invalid rule (non-numeric ID value) <--- const std::string path = CreateTempPath(sandbox + "/invalid", 0600); WriteFile(path, invalid_file); return path; } template <typename T> key_type k(const T k) const { return key_type(k); } template <typename T> value_type v(const T v) const { return value_type(v); } }; template <typename MapT> const std::string T_UidMap<MapT>::sandbox = "./cvmfs_ut_uid_map"; typedef ::testing::Types< UidMap, GidMap > UidMapTypes; TYPED_TEST_CASE(T_UidMap, UidMapTypes); TYPED_TEST(T_UidMap, Initialize) { TypeParam map; EXPECT_TRUE(map.IsValid()); EXPECT_FALSE(map.HasDefault()); EXPECT_TRUE(map.IsEmpty()); EXPECT_FALSE(map.HasEffect()); } TYPED_TEST(T_UidMap, Insert) { TypeParam map; map.Set(TestFixture::k(0), TestFixture::v(1)); map.Set(TestFixture::k(1), TestFixture::v(2)); EXPECT_TRUE(map.IsValid()); EXPECT_FALSE(map.HasDefault()); EXPECT_EQ(2u, map.RuleCount()); EXPECT_FALSE(map.IsEmpty()); EXPECT_TRUE(map.HasEffect()); } TYPED_TEST(T_UidMap, SetDefault) { TypeParam map; map.SetDefault(TestFixture::v(42)); EXPECT_EQ(0u, map.RuleCount()); EXPECT_TRUE(map.IsValid()); EXPECT_TRUE(map.HasDefault()); EXPECT_EQ(0u, map.RuleCount()); EXPECT_EQ(42u, map.GetDefault()); } TYPED_TEST(T_UidMap, Contains) { TypeParam map; map.Set(TestFixture::k(0), TestFixture::v(1)); map.Set(TestFixture::k(1), TestFixture::v(2)); EXPECT_TRUE(map.Contains(TestFixture::k(0))); EXPECT_TRUE(map.Contains(TestFixture::k(1))); EXPECT_FALSE(map.Contains(TestFixture::k(2))); map.SetDefault(TestFixture::v(42)); EXPECT_FALSE(map.Contains(TestFixture::k(2))); } TYPED_TEST(T_UidMap, Empty) { TypeParam map; EXPECT_TRUE(map.IsEmpty()); EXPECT_FALSE(map.HasEffect()); map.SetDefault(TestFixture::v(42)); EXPECT_TRUE(map.IsEmpty()); EXPECT_TRUE(map.HasEffect()); } TYPED_TEST(T_UidMap, MapWithoutDefault) { TypeParam map; map.Set(TestFixture::k(0), TestFixture::v(1)); map.Set(TestFixture::k(1), TestFixture::v(2)); EXPECT_EQ(TestFixture::v(1), map.Map(TestFixture::k(0))); EXPECT_EQ(TestFixture::v(2), map.Map(TestFixture::k(1))); EXPECT_EQ(TestFixture::v(3), map.Map(TestFixture::k(3))); } TYPED_TEST(T_UidMap, MapWithDefault) { TypeParam map; map.Set(TestFixture::k(0), TestFixture::v(1)); map.Set(TestFixture::k(1), TestFixture::v(2)); map.SetDefault(TestFixture::v(42)); EXPECT_EQ(TestFixture::v(1), map.Map(TestFixture::k(0))); EXPECT_EQ(TestFixture::v(2), map.Map(TestFixture::k(1))); EXPECT_EQ(TestFixture::v(42), map.Map(TestFixture::k(3))); } TYPED_TEST(T_UidMap, ReadFromFile) { TypeParam map; const std::string path = TestFixture::GetValidFile(); ASSERT_TRUE(map.Read(path)); EXPECT_TRUE(map.IsValid()); EXPECT_EQ(2u, map.RuleCount()); EXPECT_TRUE(map.HasDefault()); EXPECT_EQ(1337u, map.GetDefault()); EXPECT_TRUE(map.Contains(TestFixture::k(42))); EXPECT_TRUE(map.Contains(TestFixture::k(1))); EXPECT_FALSE(map.Contains(TestFixture::k(2))); EXPECT_FALSE(map.Contains(TestFixture::k(1337))); EXPECT_EQ(TestFixture::v(3), map.Map(TestFixture::k(42))); EXPECT_EQ(TestFixture::v(2), map.Map(TestFixture::k(1))); EXPECT_EQ(TestFixture::v(1337), map.Map(TestFixture::k(3))); EXPECT_EQ(TestFixture::v(1337), map.Map(TestFixture::k(4))); EXPECT_EQ(TestFixture::v(1337), map.Map(TestFixture::k(0))); } TYPED_TEST(T_UidMap, ReadFromCorruptFiles) { TypeParam map1; TypeParam map2; TypeParam map3; const std::string path1 = TestFixture::GetInvalidFile1(); const std::string path2 = TestFixture::GetInvalidFile2(); const std::string path3 = TestFixture::GetInvalidFile3(); ASSERT_FALSE(map1.Read(path1)); EXPECT_FALSE(map1.IsValid()); ASSERT_FALSE(map2.Read(path2)); EXPECT_FALSE(map2.IsValid()); ASSERT_FALSE(map3.Read(path3)); EXPECT_FALSE(map3.IsValid()); }
true
5e12d15a6b18624a0b7da9da77fd0ad4d58bc194
C++
ptolemyjenkins/sparky-clone
/SparkEngine-core/src/graphics/texture.cpp
UTF-8
2,242
2.671875
3
[]
no_license
#include "texture.h" #include <unordered_map> #include "../../libs/stb_image.h" namespace sparky { namespace graphics { std::unordered_map<std::string, resource::TextureResource> Texture::loadedTextures; Texture::Texture() { this->fileName = ""; resource = &resource::TextureResource(); } Texture::Texture(std::string fileName) { this->fileName = fileName; std::unordered_map<std::string, resource::TextureResource>::const_iterator result = Texture::loadedTextures.find(fileName); if (result != Texture::loadedTextures.end()) { resource = &Texture::loadedTextures[fileName]; resource->addReference(); } else { resource = Texture::loadTexture(fileName); Texture::loadedTextures[fileName] = *resource; } } Texture::~Texture() { if (resource->removeReference() && fileName != "") { if (loadedTextures.find(fileName) != loadedTextures.end()) { loadedTextures.erase(fileName); } } } void Texture::bind() { bind(0); } void Texture::bind(unsigned int samplerSlot) { if (samplerSlot >= 0 && samplerSlot <= 31) { glActiveTexture(GL_TEXTURE0 + samplerSlot); glBindTexture(GL_TEXTURE_2D, resource->getID()); } else { std::cerr << "Error: Invalid texture sampler slot:" << samplerSlot << std::endl; } } int Texture::getID() { return resource->getID(); } resource::TextureResource * Texture::loadTexture(std::string fileName) { resource::TextureResource resource = resource::TextureResource(); try { int width, height, numComponents; unsigned char* imageData = stbi_load(strcat("./res/textures/",fileName.c_str()), &width, &height, &numComponents, 4); glBindTexture(GL_TEXTURE_2D, resource.getID()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); glBindTexture(GL_TEXTURE_2D, 0); stbi_image_free(imageData); }catch (std::exception& e) { std::cout << e.what() << std::endl; exit(1); } return &resource; } } }
true
cec306bb2b19b568e56958b423cf064c0afe9e30
C++
M-Rodrigues/Programming
/Cracking the Coding Interview/Chapter 4 - Trees and Graphs/5.cpp
UTF-8
1,079
3.375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define error -1e6 class TreeNode { public: int data; TreeNode * left = NULL; TreeNode * right = NULL; TreeNode(int data = 0): data(data) {} }; bool isBST(TreeNode * node) { if (!node) return false; if (!node->left && !node->right) return true; if (node->left && !node->right) return (node->data >= node->left->data) && isBST(node->left); if (!node->left && node->right) return (node->data < node->right->data) && isBST(node->right); bool leftOk = node->data >= node->left->data; bool rightOk = node->data < node->right->data; return leftOk && rightOk && isBST(node->left) && isBST(node->right); } int main() { TreeNode * root = new TreeNode(30); TreeNode * n1 = new TreeNode(10); TreeNode * n2 = new TreeNode(40); root->left = n1; root->right = n2; n1->left = new TreeNode(5); n1->right = new TreeNode(12); n2->left = new TreeNode(37); printf("The tree is%s a BST\n",(isBST(root) ? "" : " not")); return 0; }
true
6e704572f0842c6408872aed8ed2877f4257180d
C++
Cheney0712/SysMonitor
/src/test/common/TestString.cpp
UTF-8
401
2.609375
3
[ "MIT" ]
permissive
#include <iostream> #include "StringUtil.h" #include <vector> #include <string> using namespace std; void test_string_split() { string ip = "127.0.0.1"; vector<string> strs; StringUtil::Split(ip, '.', strs); for (size_t i = 0; i < strs.size(); ++i) { cout << strs[i] << endl; } } int main(int argc, const char * argv[]) { test_string_split(); return 0; }
true
15231312d36c8e312cfc4f3e7d26443fa65489c1
C++
keithw96/FYP
/FYP/Play.h
UTF-8
1,856
2.53125
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include <string> #include <fstream> #include <istream> #include "Player.h" #include "Coin.h" #include "Gamestates.h" #include "Goal.h" #include "Enemy.h" #include "Pipe.h" #include "Tile.h" #include "MovingPlatform.h" #include "QuestionBlock.h" enum class PlayState { GAME, LOADING, GAMEOVER }; class Play { public: Play(); ~Play(); void init(); void initLevel(); void initNonTileMapEntities(); void initBonusArea(int lvNum); void pollEvent(sf::Event& event, sf::RenderWindow& window, GameStates& m_currentGamestate); void update(float dt, GameStates& gameState, sf::RenderWindow& window); void render(sf::RenderWindow& window); void setView(sf::RenderWindow &window); void loadNextLevel(); void killEverything(); private: PlayState m_currentPlayState; int m_currentWorld; int m_currentZone; int m_lives; int m_score; int m_coinCount; bool m_bonusRound; bool m_overWorld; bool m_underWorld; bool m_castle; sf::RectangleShape m_background; sf::RectangleShape m_renderRectangle; sf::RectangleShape m_updateRectangle; sf::Texture m_bgTexture; sf::Font m_font; sf::Text m_scoreTxt; sf::Text m_noCoinsTxt; Coin* m_coinTxt; sf::Text m_worldTxt; sf::Text m_timeTxt; sf::Text m_livesTxt; sf::Text m_gameOver; sf::Sprite m_livesSprite; sf::Texture m_livesTexture; sf::SoundBuffer m_bgMusicBuffer; sf::SoundBuffer m_deathSoundBuffer; sf::Sound m_bgMusic; sf::Sound m_deathSound; int m_timeLeft; sf::Clock m_timer; Player* m_player; Goal* m_goal; sf::View m_view; std::vector<Tile*> m_tiles; std::vector<Coin*> m_coins; std::vector<Enemy*> m_enemies; std::vector<Pipe*> m_pipes; std::vector<MovingPlatform*> m_movingPlatforms; std::vector<QuestionBlock*> m_questionBlocks; std::vector<sf::Sprite*> m_sprites; std::vector<sf::Texture*> m_textures; };
true
7f29f3a131d7e63d141db93572eb74fdf99d2aea
C++
vencik/libnn
/src/CXX/libnn/misc/fixable.hxx
UTF-8
5,226
2.84375
3
[ "BSD-3-Clause" ]
permissive
#ifndef libnn__misc__fixable_hxx #define libnn__misc__fixable_hxx /** * Fixable value * * \date 2015/09/09 * \author Vaclav Krpec <vencik@razdva.cz> * * * LEGAL NOTICE * * Copyright (c) 2015, Vaclav Krpec * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include <stdexcept> namespace libnn { namespace misc { /** * \brief Fixable value * * Container for a value that may be fixed. * The value fixation status may be checked. * Fixation is only done explicitly (constructors don't fix value). * Fixation may be soft and hard. * Soft fixation may be overriden and reset, unlike hard fixation. * * \tparam T Value type */ template <typename T> class fixable { public: /** Fixation status */ enum fix_t { UNFIXED = 0, /**< Value is not fixed */ SOFTFIX, /**< Value fixed (soft) */ HARDFIX, /**< Value fixed (hard) */ }; // end of enum fix_t private: T m_val; /**< Current value */ fix_t m_fix; /**< Value fixation status */ public: /** Constructor */ fixable(): m_fix(UNFIXED) {} /** Constructor (with initialiser) */ fixable(const T & val): m_val(val), m_fix(UNFIXED) {} /** Value is fixed (hard or soft) */ bool fixed() const { return UNFIXED != m_fix; } /** Value getter */ const T & get() const { return m_val; } /** Value getter (operator) */ operator const T & () const { return get(); } /** * \brief Value setter * * The function will set the value. * If the optional \c override_fixed parameter is \c true * it will do so even though the value is marked as soft fixed. * Otherwise, it will throw an exception (which is also the case * if hard fixation override is attempted). * * \param val Value * \param override_fixed Override soft fixation (optional) * * \return Value */ const T & set(const T & val, bool override_fixed = false) { switch (m_fix) { case UNFIXED: break; case SOFTFIX: if (override_fixed) break; case HARDFIX: throw std::logic_error( "libnn::misc::fixable: " "attempt to set fixed value"); } return m_val = val; } /** * \brief Value setter * * Restriction of \ref set. * * \param val Value * * \return Value */ const T & operator = (const T & val) { return set(val); } /** * \brief Fix value * * \param mode Fixation mode (optional) */ void fix(fix_t mode = SOFTFIX) { if (mode > m_fix) m_fix = mode; } /** * \brief Set & fix value * * See \ref set for parameters explanation. * * \param val Value * \param override_fixed Override fixation (optional) * \param mode Fixation mode (optional) */ void fix( const T & val, bool override_fixed = false, fix_t mode = SOFTFIX) { set(val, override_fixed); fix(mode); } /** * \brief Reset value * * The function resets value and removes its fixation mark, * except for hard fixation (which is not altered). * * \param val Initial value (optional) */ void reset(const T & val = T()) { if (HARDFIX != m_fix) { m_val = val; m_fix = UNFIXED; } } }; // end of template class fixable }} // end of namespace libnn::misc #endif // end of #ifndef libnn__misc__fixable_hxx
true
debd4e8c6614bf2b979bcedb0dd3c76bdb226ffc
C++
kakol20/HFG
/Models/objLoader.cpp
UTF-8
5,405
2.71875
3
[ "GPL-3.0-only" ]
permissive
/* Beginning DirectX 11 Game Programming By Allen Sherrod and Wendy Jones ObjModel - Used to represent an OBJ model. */ #include<fstream> #include<vector> #include<string> #include"objLoader.h" #include"TokenStream.h" ObjModel::ObjModel( ) { vertices_ = 0; normals_ = 0; texCoords_ = 0; totalVerts_ = 0; } ObjModel::~ObjModel( ) { Release( ); } void ObjModel::Release( ) { totalVerts_ = 0; if( vertices_ != 0 ) delete[] vertices_; if( normals_ != 0 ) delete[] normals_; if( texCoords_ != 0 ) delete[] texCoords_; vertices_ = 0; normals_ = 0; texCoords_ = 0; } bool ObjModel::LoadOBJ( const char * fileName ) { std::ifstream fileStream; int fileSize = 0; fileStream.open( fileName, std::ifstream::in ); if( fileStream.is_open( ) == false ) return false; fileStream.seekg( 0, std::ios::end ); fileSize = ( int )fileStream.tellg( ); fileStream.seekg( 0, std::ios::beg ); if( fileSize <= 0 ) return false; char *buffer = new char[fileSize]; if( buffer == 0 ) return false; memset( buffer, '\0', fileSize ); TokenStream tokenStream, lineStream, faceStream; std::string tempLine, token; fileStream.read( buffer, fileSize ); tokenStream.SetTokenStream( buffer ); delete[] buffer; tokenStream.ResetStream( ); std::vector<float> verts, norms, texC; std::vector<int> faces; char lineDelimiters[2] = { '\n', ' ' }; while( tokenStream.MoveToNextLine( &tempLine ) ) { lineStream.SetTokenStream( ( char* )tempLine.c_str( ) ); tokenStream.GetNextToken( 0, 0, 0 ); if( !lineStream.GetNextToken( &token, lineDelimiters, 2 ) ) continue; if( strcmp( token.c_str( ), "v" ) == 0 ) { lineStream.GetNextToken( &token, lineDelimiters, 2 ); verts.push_back( ( float )atof( token.c_str( ) ) ); lineStream.GetNextToken( &token, lineDelimiters, 2 ); verts.push_back( ( float )atof( token.c_str( ) ) ); lineStream.GetNextToken( &token, lineDelimiters, 2 ); verts.push_back( ( float )atof( token.c_str( ) ) ); } else if( strcmp( token.c_str( ), "vn" ) == 0 ) { lineStream.GetNextToken( &token, lineDelimiters, 2 ); norms.push_back( ( float )atof( token.c_str( ) ) ); lineStream.GetNextToken( &token, lineDelimiters, 2 ); norms.push_back( ( float )atof( token.c_str( ) ) ); lineStream.GetNextToken( &token, lineDelimiters, 2 ); norms.push_back( ( float )atof( token.c_str( ) ) ); } else if( strcmp( token.c_str( ), "vt" ) == 0 ) { lineStream.GetNextToken( &token, lineDelimiters, 2 ); texC.push_back( ( float )atof( token.c_str( ) ) ); lineStream.GetNextToken( &token, lineDelimiters, 2 ); texC.push_back( ( float )atof( token.c_str( ) ) ); } else if( strcmp( token.c_str( ), "f" ) == 0 ) { char faceTokens[3] = { '\n', ' ', '/' }; std::string faceIndex; faceStream.SetTokenStream( ( char* )tempLine.c_str( ) ); faceStream.GetNextToken( 0, 0, 0 ); for( int i = 0; i < 3; i++ ) { faceStream.GetNextToken( &faceIndex, faceTokens, 3 ); faces.push_back( ( int )atoi( faceIndex.c_str( ) ) ); faceStream.GetNextToken( &faceIndex, faceTokens, 3 ); faces.push_back( ( int )atoi( faceIndex.c_str( ) ) ); faceStream.GetNextToken( &faceIndex, faceTokens, 3 ); faces.push_back( ( int )atoi( faceIndex.c_str( ) ) ); } } /*else if (strcmp(token.c_str(), "s") == 0) { tokenStream.MoveToNextLine(&tempLine); }*/ else if( strcmp( token.c_str( ), "#" ) == 0 ) { int a = 0; int b = a; } token[0] = '\0'; } // "Unroll" the loaded obj information into a list of triangles. int vIndex = 0, nIndex = 0, tIndex = 0; int numFaces = ( int )faces.size( ) / 9; totalVerts_ = numFaces * 3; vertices_ = new float[totalVerts_ * 3]; if( ( int )norms.size( ) != 0 ) { normals_ = new float[totalVerts_ * 3]; } if( ( int )texC.size( ) != 0 ) { texCoords_ = new float[totalVerts_ * 2]; } // faces.size( )-1 the "-1" is an "extra" for( int f = 0; f < ( int )faces.size( )-1; f+=3 ) { vertices_[vIndex + 0] = verts[( faces[f + 0] - 1 ) * 3 + 0]; vertices_[vIndex + 1] = verts[( faces[f + 0] - 1 ) * 3 + 1]; vertices_[vIndex + 2] = verts[( faces[f + 0] - 1 ) * 3 + 2]; vIndex += 3; if(texCoords_) { texCoords_[tIndex + 0] = texC[( faces[f + 1] - 1 ) * 2 + 0]; texCoords_[tIndex + 1] = texC[( faces[f + 1] - 1 ) * 2 + 1]; tIndex += 2; } if(normals_) { normals_[nIndex + 0] = norms[( faces[f + 2] - 1 ) * 3 + 0]; normals_[nIndex + 1] = norms[( faces[f + 2] - 1 ) * 3 + 1]; normals_[nIndex + 2] = norms[( faces[f + 2] - 1 ) * 3 + 2]; nIndex += 3; } } verts.clear( ); norms.clear( ); texC.clear( ); faces.clear( ); return true; }
true
f5cfbdd0df3790b87c58cc7761cb4ebf4fb2658f
C++
edrumwri/drake
/solvers/minimum_value_constraint.h
UTF-8
6,961
3.0625
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include <functional> #include "drake/solvers/constraint.h" namespace drake { namespace solvers { /** Computes the penalty function φ(x) and its derivatives dφ(x)/dx. Valid penalty functions must meet the following criteria: 1. φ(x) ≥ 0 ∀ x ∈ ℝ. 2. dφ(x)/dx ≤ 0 ∀ x ∈ ℝ. 3. φ(x) = 0 ∀ x ≥ 0. 4. dφ(x)/dx < 0 ∀ x < 0. If `dpenalty_dx` is nullptr, the function should only compute φ(x). */ using MinimumValuePenaltyFunction = std::function<void(double x, double* penalty, double* dpenalty_dx)>; /** A hinge loss function smoothed by exponential function. This loss function is differentiable everywhere. The fomulation is described in section II.C of [2]. The penalty is <pre class="unicode-art"> ⎧ 0 if x ≥ 0 φ(x) = ⎨ ⎩ -x exp(1/x) if x < 0. </pre> [2] "Whole-body Motion Planning with Centroidal Dynamics and Full Kinematics" by Hongkai Dai, Andres Valenzuela and Russ Tedrake, IEEE-RAS International Conference on Humanoid Robots, 2014. */ void ExponentiallySmoothedHingeLoss(double x, double* penalty, double* dpenalty_dx); /** A linear hinge loss, smoothed with a quadratic loss near the origin. The formulation is in equation (6) of [1]. The penalty is <pre class="unicode-art"> ⎧ 0 if x ≥ 0 φ(x) = ⎨ x²/2 if -1 < x < 0 ⎩ -0.5 - x if x ≤ -1. </pre> [1] "Loss Functions for Preference Levels: Regression with Discrete Ordered Labels." by Jason Rennie and Nathan Srebro, Proceedings of IJCAI multidisciplinary workshop on Advances in preference handling. */ void QuadraticallySmoothedHingeLoss(double x, double* penalty, double* dpenalty_dx); /** Constrain all elements of the vector returned by the user-provided function to be no smaller than a specified minimum value. The formulation of the constraint is SmoothMax( φ((vᵢ - v_influence)/(v_influence - vₘᵢₙ)) / φ(-1) ) ≤ 1 where vᵢ is the i-th value returned by the user-provided function, vₘᵢₙ is the minimum allowable value, v_influence is the "influence value" (the value below which an element influences the constraint or, conversely, the value above which an element is ignored), φ is a solvers::MinimumValuePenaltyFunction, and SmoothMax(v) is a smooth, conservative approximation of max(v) (i.e. SmoothMax(v) >= max(v), for all v). We require that vₘᵢₙ < v_influence. The input scaling (vᵢ - v_influence)/(v_influence - vₘᵢₙ) ensures that at the boundary of the feasible set (when vᵢ == vₘᵢₙ), we evaluate the penalty function at -1, where it is required to have a non-zero gradient. The user-provided function may return a vector with up to `max_num_values` elements. If it returns a vector with fewer than `max_num_values` elements, the remaining elements are assumed to be greater than the "influence value". */ class MinimumValueConstraint final : public solvers::Constraint { public: /** Constructs a MinimumValueConstraint. @param num_vars The number of inputs to `value_function` @param minimum_value The minimum allowed value, vₘᵢₙ, for all elements of the vector returned by `value_function`. @param influence_value_offset The difference between the influence value, v_influence, and the minimum value, vₘᵢₙ (see class documentation). This value must be finite and strictly positive, as it is used to scale the values returned by `value_function`. Smaller values may decrease the amount of computation required for each constraint evaluation if `value_function` can quickly determine that some elements will be larger than the influence value and skip the computation associated with those elements. @default 1 @param max_num_values The maximum number of elements in the vector returned by `value_function`. @param value_function User-provided function that takes a `num_vars`-element vector and the influence distance as inputs and returns a vector with up to `max_num_values` elements. The function can omit from the return vector any elements larger than the provided influence distance. @param value_function_double Optional user-provide function that computes the same values as `value_function` but for double rather than AutoDiffXd. If omitted, `value_function` will be called (and the gradients discarded) when this constraint is evaluated for doubles. @pre `value_function_double(ExtractValue(x), v_influence) == ExtractValue(value_function(x, v_influence))` for all x. @pre `value_function(x).size() <= max_num_values` for all x. @throws std::exception if influence_value_offset = ∞. @throws std::exception if influence_value_offset ≤ 0. */ MinimumValueConstraint( int num_vars, double minimum_value, double influence_value_offset, int max_num_values, std::function<AutoDiffVecXd(const Eigen::Ref<const AutoDiffVecXd>&, double)> value_function, std::function<VectorX<double>(const Eigen::Ref<const VectorX<double>>&, double)> value_function_double = {}); ~MinimumValueConstraint() override {} /** Getter for the minimum value. */ double minimum_value() const { return minimum_value_; } /** Getter for the influence value. */ double influence_value() const { return influence_value_; } /** Getter for maximum number of values expected from value_function. */ double max_num_values() const { return max_num_values_; } /** Setter for the penalty function. */ void set_penalty_function(MinimumValuePenaltyFunction new_penalty_function); private: template <typename T> VectorX<T> Values(const Eigen::Ref<const VectorX<T>>& x) const; template <typename T> void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const; void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const override { throw std::logic_error( "MinimumValueConstraint::DoEval() does not work for symbolic " "variables."); } std::function<AutoDiffVecXd(const AutoDiffVecXd&, double)> value_function_; std::function<VectorX<double>(const VectorX<double>&, double)> value_function_double_; const double minimum_value_; const double influence_value_; /** Stores the value of 1 / φ((vₘᵢₙ - v_influence)/(v_influence - vₘᵢₙ)) = 1 / φ(-1). This is used to scale the output of the penalty function to be 1 when v == vₘᵢₙ. */ double penalty_output_scaling_; int max_num_values_{}; MinimumValuePenaltyFunction penalty_function_{}; }; } // namespace solvers } // namespace drake
true
375ff83c0f4c4820c9c709e47d126a570a6ad790
C++
keyboard-man/c_cpp
/boost/test/static_assert.cpp
UTF-8
633
3
3
[]
no_license
/************************************************************************* > File Name: static_assert.cpp > Author: He Jieting > mail: rambo@mail.ustc.edu.cn > Created Time: 2016年02月24日 星期三 15时36分06秒 ************************************************************************/ #include <boost/static_assert.hpp> #include <iostream> template<typename T> T my_min(T a, T b) { BOOST_STATIC_ASSERT_MSG(sizeof(T) < sizeof(int),"only short or char"); return a<b?a:b; } int main() { std::cout << my_min((short)1,(short)2) << std::endl; //complie error //std::cout << my_min(1L,3L) << std::endl; return 0; }
true
6f935ad59b1f841985c52137c9742ffea2af75f7
C++
Trbonnes/webserv
/core/webserver.cpp
UTF-8
1,145
2.84375
3
[]
no_license
#include "HttpServer.hpp" bool g_ismaster; HttpServer *g_server; int g_singaled; void printUsage() { std::cerr << "Usage: ./webserv [option argument]" << std::endl; std::cerr << std::endl; std::cerr << "Available options:" << std::endl; std::cerr << "\r-c : set the path to configuration file to the next argument" << std::endl; } static int parseArguments(HttpServer &server, const char **av) { size_t i; std::string opt; std::string arg; i = 1; while (av[i]) { if (av[i][0] == '-') { if (av[i + 1]) { opt = std::string(av[i]); arg = std::string(av[i+1]); if (opt == "-c") server.setConfigPath(arg); else return -1; i++; } else return -1; } else return -1; i++; } return (0); } int main(int ac, const char** av, const char** env) { HttpServer server; (void) ac; (void) av; (void) env; g_ismaster = true; g_server = &server; g_singaled = 0; if (ac > 1) { if (parseArguments(server, av)) { printUsage(); return 1; } } try { server.run(); } catch(const std::exception& e) { std::cerr << "" << std::endl; return 1; } return 0; }
true
237ae73f52270db351ca2558cac4010e9c8e1d84
C++
treinamento-fc/maratona
/competicoes/2017/Fase - Regional - 2017/M - Máquina de Café/maquinacafe.cpp
UTF-8
983
3.375
3
[]
no_license
//============================================================================ // Name : Problema M - maquinadecafe.cpp // Solução : Calcule os tempos considerando a máquina em cada um dos andares e depois ache o menor dos tempos // Author : Wilson // Version : // Copyright : Your copyright notice // Description : Maratona de Programação 2017 - Latin American Regional Contests //============================================================================ #include <iostream> #include <algorithm> using namespace std; int a1, a2, a3, tempos[3]; int main() { // Ler a1, a2 e a3; cin >> a1 >> a2 >> a3; //cout << a1 << " " << a2 << " " << a3 << endl; // Computando tempos considerando a máquina nos andares 1, 2 e 3 tempos[0] = (a2 *2) + (a3* 4); tempos[1] = (a1 *2) + (a3* 2); tempos[2] = (a1 *4) + (a2* 2); // Achar o menor tempo sort(tempos, tempos + 3); cout << tempos[0] << endl; return 0; }
true
4c2f40c5024c18f802e660bd4694a1a57ea67df0
C++
Maserhe/LeetCode
/653.两数之和-iv-输入-bst.cpp
UTF-8
1,474
3.1875
3
[]
no_license
/* * @lc app=leetcode.cn id=653 lang=cpp * * [653] 两数之和 IV - 输入 BST */ // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool findTarget(TreeNode* root, int k) { // 使用 vector // 二分 查找另一半。 if (!root) return false; stack<TreeNode *> st; vector<int> ans; TreeNode * tmp = root; while (st.size() || tmp) { while (tmp) { st.push(tmp); tmp = tmp->left; } TreeNode * t = st.top(); st.pop(); ans.push_back(t->val); tmp = t->right; } // 二分 查找答案。 int n = ans.size(); for (int i = 0; i < n; i ++ ){ int l = i + 1, r = n ; while (l < r) { int mid = l + r >> 1; if (ans[mid] == k - ans[i]) return true; if (ans[mid] < k - ans[i]) l = mid + 1; else r = mid; } } return false; } }; // @lc code=end
true
46f2c462dc332ec6898a11fb607edbe8036ed24e
C++
RolandoAndrade/NubeUCAB
/client/NubeUCAB-cliente/socket_client.h
UTF-8
1,147
2.84375
3
[]
no_license
#include "socket.h" #include "socket_exceptions.h" #include "commands.h" class ClientSocket : private Socket { public: ClientSocket() { } ClientSocket(int host, int port) { if(!Socket::create()) { throw SocketException(strerror(errno)); } if(!Socket::connect(host,port)) { throw SocketException(strerror(errno)); } } ClientSocket(string host, int port) { if(!Socket::create()) { throw SocketException(strerror(errno)); } int ip = lookup(host); if(!Socket::connect(ip,port)) { throw SocketException(strerror(errno)); } } ~ClientSocket() { Socket::close(); } ClientSocket& operator << (string &s) { if(Socket::send(s)==-1) { throw SocketException(strerror(errno)); } return *this; } ClientSocket& operator >> (string &s) { if(Socket::recv(s)==-1) { throw SocketException(strerror(errno)); } return *this; } void close() { if(!Socket::close()) { throw SocketException(strerror(errno)); } } int getFD() { if(!Socket::close()) { throw SocketException(strerror(errno)); } } };
true
ee71b7bb9ca0ba4162a044cfc079c7a2124318b9
C++
bbajcetic/BCGameJam20
/src/main.cpp
UTF-8
2,316
2.59375
3
[]
no_license
#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include <SDL2/SDL_mixer.h> #include <stdio.h> #include <string> #include <vector> #include "constants.h" #include "game.h" #include "network.h" /* Functions */ // Initialize SDL bool initSDL(); // Free memory, quit SDL void quitSDL(); /* Globals */ // Rendering window SDL_Window* gWindow = NULL; // Renderer SDL_Renderer* gRenderer = NULL; // Game loop bool running = true; int main(int argc, char *argv[]) { if (!initSDL()) { printf("Initialization failed!\n"); } else { // Game loop runGame(); printf("Game ending\n"); } Network_clean(); quitSDL(); return 0; } /* Function Definitions */ // Initialize SDL bool initSDL() { // Init flag bool loaded = true; // Initialization if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) { printf("SDL initialization failed! SDL_Error: %s\n", SDL_GetError()); loaded = false; } else { // Create window gWindow = SDL_CreateWindow("BC Game Jam 2020 Prevail", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (gWindow == NULL) { printf("Window creation failed! SDL_Error: %s\n", SDL_GetError()); loaded = false; } else { // Create Renderer gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (gRenderer == NULL) { printf("Renderer creation failed! SDL Error: %s\n", SDL_GetError()); loaded = false; } else { // Initialize image loading int imgFlag = IMG_INIT_JPG | IMG_INIT_PNG; if (!IMG_Init(imgFlag) & imgFlag) { printf("SDL_Image initialization failed! SDL_image Error: %s\n", IMG_GetError()); loaded = false; } // Initialize SDL Mixer if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { printf("SDL_Mixer initialization failed! SDL_mixer Error: %s\n", Mix_GetError()); loaded = false; } } } } return loaded; } // Free memory, quit SDL void quitSDL() { // Free and Destroy // Textures // Music // Destroy renderer SDL_DestroyRenderer(gRenderer); gRenderer = NULL; // Destroy window SDL_DestroyWindow(gWindow); gWindow = NULL; // Quit subsystems Mix_Quit(); IMG_Quit(); SDL_Quit(); }
true
49cc7e1d2180a928fffc20eadc9a2ca7f9412efd
C++
badger-dowdeswell/project-exported-function-blocks
/AGENT_SIFB/AGENT_SERVER_Library.cpp
UTF-8
3,452
2.765625
3
[]
no_license
// // AGENT SERVER LIBRARY // ==================== // Library of custom routines for the AGENT_SERVER diagnostic Service Interface Function Block. // // Note that the 4DIAC type definition section only allows one custom header entry so this file // can be linked in at compile time by referencing it in the Compiler Info section // as: #include "AGENT_LISTENER_library.cpp" // // Version history // =============== // 17.12.2018 BRD Original version. // // Module-level declarations // ========================= #include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <arpa/inet.h> #include <sys/socket.h> #include <errno.h> #include <unistd.h> #include <string> #include <fcntl.h> using std::cout; using std::string; using std::to_string; bool isListening = false; bool isConnected = false; int listenerSocket = 0; int serverSocket = 0; int new_Socket = 0; // // createListener() // ================ // Creates a listener that opens a connection to the agent that this SIFB function block // is working with. // // serverAddress IPv4 or IPv6 server address (e.g. 127.0.0.1) that this server operates // on as a listener/server. // thisPort Socket number that has been opened to the remote client to connect to. // returns True if the connection has been opened successfully.eee // bool createListener(string serverAddress, long int thisPort) { bool isConnected = false; struct sockaddr_in address; int addrlen = sizeof(address); int opt = 1; cout << "in createListener() " << serverAddress << " " << to_string(thisPort) << "\n"; if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0 )) == 0) { perror("Cannot create server socket.\n"); } else { perror("Created server socket.\n"); // Connect the socket to the port. if (setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("Error returned from setsockopt(). Cannot set server socket options.\n"); } else { address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(thisPort); // Set the socket to be non-blocking. Retrieve the initial settings specified with setsockopt() // and then reset the correct bit fsetNonBlocking(serverSocket); int flags = fcntl(serverSocket, F_GETFL, 0); // flags = 0; fcntl(serverSocket, F_SETFL, flags | SOCK_NONBLOCK); // Bind the socket to the port. if (bind(serverSocket, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("Cannot bind socket to the port.\n"); } else { // Start listening on that port. if (listen(serverSocket, 3) < 0) { perror("Error returned from listen(). Cannot start listening on that port.\n"); } else { perror("Listening on port.\n"); isConnected = true; } } } } return isConnected; } // // sendPacket2() // ============= // Sends a packet of data to the remote agent that was previously // connected to using createConnection() // // msg String to be sent to the server. Since the connection was opened as a Stream, there // no maximum size for this data packet. // void sendPacket2(int sendSocket, string msg) { if (isListening) { //send(sock, msg, strlen(msg), 0); send(sendSocket, msg.c_str(), msg.length(), 0); } else { perror("Cannot send data packet in sendPacket2(): no connection is open\n"); } }
true
645b2cea66770a879d95a2419d9a07bee838a53b
C++
AndrewOsip/Training
/comp4/Umap.h
UTF-8
539
2.71875
3
[]
no_license
#ifndef UMAP_H #define UMAP_H #include <fstream> #include <unordered_map> class Umap : std::unordered_map<uint, std::string> { public: Umap(const std::string& fileName) { mFileName.open(fileName); vocebWrite(); numOfCoinc(); } ~Umap() { mFileName.close(); } const std::unordered_map<uint, std::string> provideData() const { return *this; } private: void vocebWrite(); void numOfCoinc(); std::unordered_map<uint, std::string> mUMap; std::ifstream mFileName; }; #endif // UMAP_H
true
05acdbb4777baa3b6941698b5e807fe2c46a95ce
C++
joedo29/CS300DataStructure
/Assignment04/LinkedList.h
UTF-8
3,761
3.625
4
[]
no_license
#ifndef LINKEDLIST_H_ #define LINKEDLIST_H_ #include <iostream> using namespace std; template<class T> struct nodeLL { T data; nodeLL *next; }; template<class T> class LinkedList { private: LinkedList(const LinkedList &) = delete; //copy constructor protected: int count; nodeLL<T> *head, *last; public: LinkedList(); bool isEmpty(); int length(); T front(); T back(); void insertFirst(T &); void insertLast(T &); //////////////my added function virtual void insert(T &); virtual T deletenodeLL(T &); //////////////////////////// void destroylist(); LinkedList<T> &operator=(LinkedList<T> &); template<class U> friend ostream &operator<<(ostream &os, LinkedList<U> &list); virtual ~LinkedList(); }; template<class T> LinkedList<T>::LinkedList() { head = last = NULL; count = 0; } template<class T> bool LinkedList<T>::isEmpty() { return head == NULL; } template<class T> int LinkedList<T>::length() { return count; } template<class T> T LinkedList<T>::front() { return head->data; } template<class T> T LinkedList<T>::back() { return last->data; } template<class T> void LinkedList<T>::insertFirst(T &item) { nodeLL<T> *temp = new nodeLL<T>; temp->data = item; temp->next = head; head = temp; count++; if (last == NULL) last = temp; } template<class T> void LinkedList<T>::insertLast(T &item) { nodeLL<T> *newnodeLL = new nodeLL<T>; newnodeLL->data = item; newnodeLL->next = NULL; if (head == NULL) { head = last = newnodeLL; } else { last->next = newnodeLL; last = newnodeLL; } count++; } ///////////////// my edit ///////////////////////////////// template<class T> void LinkedList<T>::insert(T &item) { insertLast(item); //calls insert last as the default insert method } template<class T> T LinkedList<T>::deletenodeLL(T &item) { if (head == NULL) //check for empty list cerr << "empty list"; else { if (head->data == item) { //if head is to be deleted nodeLL<T> *p = head; head = head->next; delete p; count--; if (head == NULL) last = NULL; } else { //two pointers to traverse list nodeLL<T> *p = head; nodeLL<T> *q = p->next; while (q != NULL && !(q->data == item)) { //traverse through list to find desired nodeLL p = q; q = q->next; } if (q != NULL) { //item to be deleted was found, delete it p->next = q->next; //re assign p's next to nodeLL after q-- the nodeLL to be deleted count--; //decrement count if (last == q) last = p; //if nodeLL deleted was last nodeLL, reassign it delete q; //delete the nodeLL and free memory } } } return item; //return the nodeLL deleted } /////////////////////////////////////////////////////////////// template<class T> void LinkedList<T>::destroylist() { nodeLL<T> *p; while (head != NULL) { p = head; head = head->next; delete p; } last = NULL; count = 0; } template<class T> LinkedList<T> &LinkedList<T>::operator=(LinkedList<T> &list) { if (this != &list) { copylist(list); } return *this; } template<class T> ostream &operator<<(ostream &os, LinkedList<T> &list) { nodeLL<T> *p = list.head; while (p != NULL) { cout << p->data << endl; p = p->next; } return os; } template<class T> LinkedList<T>::~LinkedList() { destroylist(); } #endif /* LINKEDLIST_H_ */
true
8623715e0f06513677073a3c35093c8c20de010b
C++
hope-kim/Course1
/lp15/lp15.cpp
UTF-8
587
3
3
[]
no_license
// Hope Kim // ITP 165, Fall 2017 // Lab Practical 15 // hopekim@usc.edu #include <iostream> #include "Pyramid.h" int main() { // data for Pyramid class const unsigned int bSize = 4; Pyramid myPyramid(bSize); // data for Coordinate class Coordinate cArr[bSize]; cArr[0].setX(0.0); cArr[0].setY(1.1); cArr[1].setX(2.0); cArr[1].setY(2.1); cArr[2].setX(3.0); cArr[2].setY(3.1); cArr[3].setX(4.0); cArr[3].setY(4.1); myPyramid.setBase(cArr, bSize); myPyramid.setHeight(3.14159); myPyramid.print(); return 0; }
true
d96dc6a87e7a9601d5daec3a8aa0e4af1af6eade
C++
brayanhenao/Competitive-Programming
/URI/U1176.cpp
UTF-8
467
2.671875
3
[]
no_license
#include <bits/stdc++.h> #define endl '\n' using namespace std; int main() { ios_base::sync_with_stdio(false);cin.tie(NULL); vector<unsigned long long> fibonacci(61); fibonacci[0]=0; fibonacci[1]=1; for(int i=2;i<61;++i){ fibonacci[i]=fibonacci[i-1]+fibonacci[i-2]; } int T,N; while(cin>>T) { while(T--){ cin>>N; cout<<"Fib("<<N<<") = "<<fibonacci[N]<<endl; } } return 0; }
true
7b985fac042412f4e9a97c32774de01ca89cf106
C++
JanBone/Sieci-computerowe
/Tracerouter/tracerouter.cpp
UTF-8
2,815
2.890625
3
[]
no_license
// Katsiaryna Yalovik 306460 #include "receive.h" #include "send.h" #include "vector" #include <chrono> #include <iostream> #include <chrono> #include <tuple> using namespace std; int line = 1; std::vector<std::chrono::time_point<std::chrono::high_resolution_clock> >time_vec(91); double calculate(int id1, int id2, int id3, std::chrono::time_point<std::chrono::high_resolution_clock> finish1, std::chrono::time_point<std::chrono::high_resolution_clock> finish2, std::chrono::time_point<std::chrono::high_resolution_clock> finish3){ auto start1 = time_vec[id1]; auto start2 = time_vec[id2]; auto start3 = time_vec[id3]; return (std::chrono::duration_cast<std::chrono::milliseconds>(finish1 - start1).count() + std::chrono::duration_cast<std::chrono::milliseconds>(finish2 - start2).count() + std::chrono::duration_cast<std::chrono::milliseconds>(finish3 - start3).count())/3; } void print(vector<tuple <const char*,int, std::chrono::time_point< std::chrono::high_resolution_clock>>> vec){ long long int t; int size; if (vec.size()==0){ printf("%d. %s\n", line, "*"); line++; } else { size = vec.size(); if(size == 3){ t = calculate(get<1>(vec[0]), get<1>(vec[1]), get<1>(vec[2]), get<2>(vec[0]),get<2>(vec[1]), get<2>(vec[2])); for (int k =0; k< size; k++){ if (strcmp(std::get<0>(vec[k]), " ") != 0){ printf("%d. %s ", line, get<0>(vec[k])); printf("%lld ms.\n", t); line++; } } } else{ for (int k =0; k< size; k++){ if (strcmp(std::get<0>(vec[k]), " ") != 0){ printf("%d. %s ??\n", line, get<0>(vec[k])); line++; } } } } } int main(int argc, char* argv[]) { Receive receive(argv[1]); Send send; struct sockaddr_in addr; std::vector<std::tuple <const char*,int, std::chrono::time_point<std::chrono::high_resolution_clock>>> storage; int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if (argc != 2){ throw std::invalid_argument( "Invalid ip addres format"); } if ((inet_aton(argv[1], &addr.sin_addr) == 0)){ throw std::invalid_argument( "Invalid ip addres"); } if (sockfd < 0) { throw std::invalid_argument( "Socket creation failed"); } int id = 0; for (int ttl = 1; ttl <= 30; ttl++){ if (receive.returnFlag()){ break; } for (int j = 1; j <=3; j++){ auto start = std::chrono::high_resolution_clock::now(); time_vec[id] = start; send.sendPacket(sockfd, argv[1], ttl, id); id++; } storage = receive.receivePackets(sockfd,ttl, id); print(storage); } }
true
a9f694baf41dd4900980713d9aba48d8a54a947a
C++
LeviosaPumpkin/CMO
/CircleQueue.h
UTF-8
235
2.734375
3
[]
no_license
#ifndef CIRCLEQUEUE_H #define CIRCLEQUEUE_H #include <Queue> #include <iostream> template <class T> class CircleQueue : public Queue < T > { private: int size; public: CircleQueue(int size_) : Queue<T>(), size(size_) { } }; #endif
true
03a7582f04cd1badfa3c9faad77568b3ed8087aa
C++
SzymonTheWlod/Apocalypse
/src/gamelib/Source/Resources.cpp
UTF-8
1,710
3.046875
3
[]
no_license
#include "gamelib/Headers/Resources.h" Resources::Resources( int _water, int _food, int _wood, int _metal, int _fuel, int _med) : water(_water), food(_food), wood(_wood), metal(_metal), fuel(_fuel), med(_med) { } Resources Resources::takeDistribution(int amount) { Resources return_resource; while (amount > 0 && total() > 0) { return_resource.wood += takeIfAvailable(wood, amount); return_resource.metal += takeIfAvailable(metal, amount); return_resource.med += takeIfAvailable(med, amount); return_resource.food += takeIfAvailable(food, amount); return_resource.fuel += takeIfAvailable(fuel, amount); return_resource.water += takeIfAvailable(water, amount); } return return_resource; } int Resources::takeIfAvailable(int& resource, int& amount) { if (resource > 0 && amount > 0) { resource--; amount--; return 1; } return 0; } Resources Resources::operator+(Resources& resources) { this->wood += resources.wood; this->metal += resources.metal; this->med += resources.med; this->food += resources.food; this->fuel += resources.fuel; this->water += resources.water; return *this; } Resources Resources::operator-(Resources& resources) { this->wood -= resources.wood; this->metal -= resources.metal; this->med -= resources.med; this->food -= resources.food; this->fuel -= resources.fuel; this->water -= resources.water; return *this; } bool Resources::canCombineWith(const Resources& resources) { return (med + resources.med) >= 0 && (wood + resources.wood) >= 0 && (metal + resources.metal) >= 0 && (food + resources.food) >= 0 && (water + resources.water) >= 0 && (fuel + resources.fuel) >= 0; }
true
be8946cb6fe333f4b9ae8c0fb05235a994de5a95
C++
spectaclelabs/elvin
/elvin/pattern_event.h
UTF-8
2,708
3
3
[]
no_license
#ifndef ELVIN_PATTERN_EVENT_H #define ELVIN_PATTERN_EVENT_H #include <memory> #include <array> #include "event.h" #include "pattern_value.h" #include "time_data.h" #include "indices.h" #include "collections/interface.h" namespace elvin { template <typename CollectionType, typename DurationPattern, typename... CallbackArgs> class PatternEvent : public Event { public: PatternEvent(uint32_t time, CollectionType patterns, DurationPattern durationPattern, void(*callback)(CallbackArgs...)) : Event(time), patterns(std::move(patterns)), durationPattern(std::move(durationPattern)), callback(callback) { } virtual bool process(const TimeData &timeData) { PatternValue duration = durationPattern.next(); if (!duration.exists) { // No duration, so don't run the callback or add any further events return false; } auto indices = typename IndexBuilder<sizeof...(CallbackArgs)>::type(); bool shouldContinue = runCallback(indices); if (!shouldContinue) { // Pattern hasn't provided a value, so don't process the callback // or add any further events return false; } // All okay, so advance the time and re-add the event uint32_t dt = duration.value * timeData.beatLength; time += dt; return true; } private: // Runs the callback samples collected from the patterns template <size_t... Is> bool runCallback(Indices<Is...>) { // Collect the next value from each of the patterns std::array<float, sizeof...(CallbackArgs)> values; for (uint32_t i=0; i<collections::interface::size(patterns); i++) { PatternValue value = collections::interface::next(patterns, i); if (!value.exists) { return false; } values[i] = value.value; } // Do the call callback(values[Is]...); (void) values; return true; } CollectionType patterns; DurationPattern durationPattern; void(*callback)(CallbackArgs...); }; template <typename CollectionType, typename DurationPattern, typename... CallbackArgs> using PatternEventPtr = std::unique_ptr< PatternEvent< CollectionType, DurationPattern, CallbackArgs... > >; template <typename... CallbackArgs> using PatternEventCallback = typename PatternEvent<CallbackArgs...>::Callback; } #endif
true
c120bd67ec37a6cda5500af5f59bd3a53c6d4b98
C++
fwzhuang/zjucad_sdk
/include/hjlib/math_func/coo.h
UTF-8
9,894
2.625
3
[]
no_license
#ifndef HJ_MATH_FUNC_COO_H_ #define HJ_MATH_FUNC_COO_H_ #include <vector> #include <algorithm> #include <iostream> #include "config.h" namespace hj { namespace math_func { //! @brief inline size_t powi(size_t base, size_t pow) { size_t rtn = 1; for(size_t i = 0; i < pow; ++i) rtn *= base; return rtn; } //! c is dim major. TODO: put the requirement to function. template <typename T> void pack_coo(size_t num, size_t dim, const T *c, std::vector<std::vector<T> > &pc) { using namespace std; pc.resize(num); { size_t ni; #if HJ_FUNC_USE_OMP #pragma omp parallel for private(ni) #endif for(ni = 0; ni < num; ++ni) pc[ni].insert(pc[ni].begin(), c+ni*dim, c+ni*dim+dim); sort(pc.begin(), pc.end()); typename vector<vector<T> >::iterator pos = unique(pc.begin(), pc.end()); pc.erase(pos, pc.end()); } } template <typename T> class coo_pat_coo; template <typename T> class coo_pat_dense; template <typename T> class coo_pat_csc; class coo_l2g; template <typename INT> class coo_pat; // dim major template <typename INT> class coo_set { public: coo_set() :cur_pos_(0), format_(0) { } coo_set(size_t dim, size_t nf, size_t nx, size_t nnz) :cur_pos_(0) { if(nnz != -1) { coos_.resize(nnz*dim); format_ = 'S'; } else { nnz = nf * powi(nx, dim-1); format_ = 'D'; } dim_ = dim; nf_ = nf; nx_ = nx; } size_t nf(void) const { return nf_; } size_t nx(void) const { return nx_; } size_t dim(void) const { return dim_; } size_t coo_num(void) const { return coos_.size()/dim_; } bool is_dense(void) const { return format_ == 'D'; } coo_pat<INT> *get_coo_pat(void) const { switch(format_) { case 'D': return new coo_pat_dense<INT>(dim(), nf(), nx()); case 'S': { std::vector<std::vector<INT> > pc; pack_coo(coo_num(), dim(), &coos_[0], pc); coo_pat_dense<INT> cpd(dim()-1, nf(), nx()); if(dim() > 1 && cpd.nnz() < pc.size()) return new coo_pat_csc<INT>(dim(), nf(), nx(), pc); // std::cout << "use coo: " << pc.size() << " " << cpd.nnz() << std::endl; return new coo_pat_coo<INT>(dim(), nf(), nx(), pc); } } return 0; } private: friend class coo_l2g; inline void add(const INT*c) { assert(!is_dense()); std::copy(c, c+dim(), &coos_[cur_pos_]); cur_pos_ += dim(); } friend class coo_pat_coo<INT>; friend class coo_pat_csc<INT>; std::vector<INT> coos_; size_t cur_pos_, dim_, nf_, nx_; char format_; }; template <typename INT> class coo_pat_dense; template <typename INT> class coo_pat_coo; template <typename INT> class coo_pat { public: coo_pat(size_t dim, size_t nf, size_t nx, char format) :dim_(dim), nf_(nf), nx_(nx), format_(format), d_(0), s_(0), p_(0) { switch(format_) { case 'D': d_ = static_cast<const coo_pat_dense<INT> *>(this); break; case 'S': s_ = static_cast<const coo_pat_coo<INT> *>(this); break; case 'P': p_ = static_cast<const coo_pat_csc<INT> *>(this); break; } } inline size_t is_dense(void) const { return format_ == 'D'; } inline size_t nnz(void) const { return nnz_; } inline size_t dim(void) const { return dim_; } inline size_t nf(void) const { return nf_; } inline size_t nx(void) const { return nx_; } inline size_t operator()(const INT *coo) const { switch(format_) { case 'D': return (*d_)(coo); case 'S': return (*s_)(coo); case 'P': return (*p_)(coo); } return -1; } inline INT *operator()(size_t nzi, INT *coo) const { switch(format_) { case 'D': return (*d_)(nzi, coo); case 'S': return (*s_)(nzi, coo); case 'P': return (*p_)(nzi, coo); } return 0; } virtual ~coo_pat(){} protected: const size_t dim_, nf_, nx_; size_t nnz_; const char format_; const coo_pat_dense<INT> *d_; const coo_pat_coo<INT> *s_; const coo_pat_csc<INT> *p_; }; template <typename INT> class coo_pat_dense : public coo_pat<INT> { public: using coo_pat<INT>::dim; using coo_pat<INT>::nx; using coo_pat<INT>::nnz_; coo_pat_dense(size_t dim, size_t nf, size_t nx) :coo_pat<INT>(dim, nf, nx, 'D'){ nnz_ = nf * powi(nx, dim-1); } inline size_t operator()(const INT *coo) const { size_t ad = coo[0]; for(size_t d = 1; d < dim(); ++d) { ad *= nx(); ad += coo[d]; } return ad; } inline INT *operator()(size_t nzi, INT *coo) const { for(size_t d = dim()-1; d > 0; --d) { coo[d] = nzi%nx(); nzi = (nzi-coo[d])/nx(); } coo[0] = nzi; return coo; } }; template <typename INT> class coo_pat_coo : public coo_pat<INT> { public: using coo_pat<INT>::dim; using coo_pat<INT>::nnz_; using coo_pat<INT>::nnz; coo_pat_coo(size_t dim, size_t nf, size_t nx, const std::vector<std::vector<INT> > &pc) :coo_pat<INT>(dim, nf, nx, 'S') { coos_.resize(dim*pc.size()); for(size_t i = 0; i < pc.size(); ++i) { for(size_t d = 0; d < dim; ++d) coos_[i+d*pc.size()] = pc[i][d]; } nnz_ = pc.size(); } inline size_t operator()(const INT *coo) const { size_t beg = 0, end = nnz(); const INT *ptr = &coos_[0]; for(size_t i = 0; i < dim()-1; ++i, ptr+=nnz()) { const std::pair<const INT *, const INT *> r = std::equal_range(ptr+beg, ptr+end, coo[i]); beg = r.first - ptr; end = r.second - ptr; } beg = std::lower_bound(ptr+beg, ptr+end, coo[dim()-1])-ptr; if(beg == end || ptr[beg] != coo[dim()-1]) return -1; return beg; } inline INT *operator()(size_t nzi, INT *coo) const { assert(nzi < nnz()); for(size_t i = 0; i < dim(); ++i, nzi += nnz()) coo[i] = coos_[nzi]; return coo; } private: std::vector<INT> coos_; }; template <typename INT> class coo_pat_csc : public coo_pat<INT> { public: using coo_pat<INT>::dim; using coo_pat<INT>::nnz_; using coo_pat<INT>::nnz; coo_pat_csc(size_t dim, size_t nf, size_t nx, const std::vector<std::vector<INT> > &pc) :coo_pat<INT>(dim, nf, nx, 'P'), ptr_addr_(dim-1, nf, nx) { assert(dim > 1); nnz_ = pc.size(); // the last is coo, and the prev are ptrs ptr_.resize(ptr_addr_.nnz()+1, 0); coos_.resize(pc.size()); for(size_t pi = 1, nzi = 0; pi < ptr_.size(); ++pi) { ptr_[pi] = ptr_[pi-1]; for(; nzi < pc.size(); ++nzi) { coos_[nzi] = pc[nzi][dim-1]; const size_t pa = ptr_addr_(&pc[nzi][0]); assert(pa >= pi-1); if(pa == pi-1) ++ptr_[pi]; else break; } } #if 0 std::vector<INT> c(dim()); size_t nzi, nzi2; for(nzi = 0; nzi < nnz(); ++nzi) { (*this)(nzi, &c[0]); if(c != pc[nzi]) std::cout << "error." << nzi << std::endl; nzi2 = (*this)(&c[0]); if(nzi2 != nzi) std::cout << "error." << nzi2 << std::endl; } #endif } inline size_t operator()(const INT *coo) const { const size_t pa = ptr_addr_(coo); size_t beg = ptr_[pa], end = ptr_[pa+1]; const INT *idx = &coos_[0]; size_t off = std::lower_bound(idx+beg, idx+end, coo[dim()-1])-idx; if(off == end || idx[off] != coo[dim()-1]) return -1; return off; } inline INT *operator()(size_t nzi, INT *coo) const { assert(nzi < nnz()); coo[dim()-1] = coos_[nzi]; const size_t pa = std::upper_bound(ptr_.begin(), ptr_.end(), nzi)-ptr_.begin()-1; assert(pa != -1); ptr_addr_(pa, coo); return coo; } private: coo_pat_dense<INT> ptr_addr_; std::vector<INT> ptr_; std::vector<INT> coos_; }; //! return value for a coodindates with coordinate transform class coo_map { public: virtual ~coo_map(){}; coo_map(size_t f_base = 0) :f_base_(f_base) { } inline const size_t f_base(void) const { return f_base_; } inline size_t &f_base(void) { return f_base_; } private: size_t f_base_; }; template <typename VAL_TYPE, typename INT_TYPE> class coo2val_t : public coo_map { public: typedef VAL_TYPE val_type; typedef INT_TYPE int_type; coo2val_t(const coo_pat<int_type> &cp, val_type *val, size_t f_base = 0) :coo_map(f_base), cp_(cp), val_(val) { } //! NOTICE: coo will be changed inline val_type &operator[](int_type *coo) const { return val_[addr(coo)]; } private: inline size_t addr(int_type *coo) const { coo[0] += f_base(); const size_t ad = cp_(coo); assert(ad != -1); return ad; } const coo_pat<int_type> &cp_; val_type *val_; }; template <typename VAL_TYPE, typename INT_TYPE> coo2val_t<VAL_TYPE, INT_TYPE> coo2val(const coo_pat<INT_TYPE> &cp, VAL_TYPE *val, size_t f_base = 0) { return coo2val_t<VAL_TYPE, INT_TYPE>(cp, val, f_base); } class coo_l2g : public coo_map { public: coo_l2g(size_t f_base = 0) :coo_map(f_base) { } //! NOTICE: c will be changed template <typename INT_TYPE> inline void add(coo_set<INT_TYPE> &cs, INT_TYPE *c) const { c[0] += f_base(); cs.add(c); } }; template <typename INT> void coo2csc(const coo_pat<INT> &coo, INT *ptr, INT *idx, size_t beg, size_t nnz, size_t dim_base) { assert(coo.dim() >= 2+dim_base); ptr[0] = 0; std::vector<INT> c(coo.dim()); for(size_t ti = 1, ni = beg; ti != -1;) { ptr[ti] = ptr[ti-1]; for(; ni < nnz; ++ni) { if(coo(ni, &c[0])[dim_base] == ti-1) ++ptr[ti]; else { ++ti; break; } idx[ni] = c[dim_base+1]; } if(ni == nnz) ti = -1; } } // the last two dimension template <typename INT> void coo2csc(const coo_pat<INT> &coo, INT *ptr, INT *idx, INT *leading = 0) { assert(!coo.is_dense()); if(leading == 0) { coo2csc(coo, ptr, idx, 0, coo.nnz(), 0); assert(ptr[coo.nf()] == coo.nnz()); } else { assert(leading); if(coo.nf() == 1 && coo.dim() == 3) coo2csc(coo, ptr, idx, 0, coo.nnz(), 1); else assert(0); // may need turn coo into an iteratable object } } }} #endif
true
520876d3b648c979f1b8197275a12cac6cd45046
C++
adventurer-exp/boat_game
/tut4_boat/main.cpp
UTF-8
4,036
2.703125
3
[]
no_license
// // main.cpp // tut3_velocity // // Created by Simona Bilkova on 20/3/20. // Copyright © 2020 Simona Bilkova. All rights reserved. // #define GL_SILENCE_DEPRECATION #include <math.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> float cannon_angle = 45.0, boat_rotation = 0; const float angle_d = 1.0; // Idle callback for animation void update(void) { glutPostRedisplay(); } float degToRad(float deg) { return deg * M_PI / 180; } float radToDeg(float rad) { return rad * 180 / M_PI; } void drawAxes(float l) { glBegin(GL_LINES); glColor3f(1.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(l, 0.0, 0.0); glColor3f(0, 1, 0.0); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, l, 0.0); glColor3f(0, 0, 1); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, l); glEnd(); glColor3f(1, 1, 1); } void drawSquare() { glBegin(GL_LINE_LOOP); glVertex3f(-0.25, -0.25, 0.0); glVertex3f(0.25, -0.25, 0.0); glVertex3f(0.25, 0.25, 0.0); glVertex3f(-0.25, 0.25, 0.0); glEnd(); } float calculateX() { return cosf(degToRad(cannon_angle)) * 0.5; } float calculateY() { return sinf(degToRad(cannon_angle)) * 0.5; } void calculateProjectileStart() { // to be used as r x and ry as a starting point of the projectile float x, y; x = calculateX() + 0.5; y = calculateY() + 0.25; printf("x: %.2f, y: %.2f\n", x, y); } void drawTrapezoid(){ glBegin(GL_LINE_LOOP); glColor3f(1.0, 1.0, 1.0); glVertex3f(-0.5, -0.25, 0.0); glVertex3f(0.5, -0.25, 0.0); glVertex3f(1, 0.25, 0.0); glVertex3f(-1.0, 0.25, 0.0); glEnd(); } void drawBoat() { glRotatef(boat_rotation, 0.0, 0.0, 1.0); glPushMatrix(); // main deck glPushMatrix(); drawAxes(0.2); glPopMatrix(); // bridge glPushMatrix(); glTranslatef(0.0, 0.5, 0.0); drawAxes(0.2); drawSquare(); glPopMatrix(); // cannon glPushMatrix(); glTranslatef(0.5, 0.25, 0.0); glRotatef(cannon_angle, 0.0, 0.0, 1.0); drawAxes(0.2); glTranslatef(0.25, 0.0, 0.0); drawAxes(0.2); glScalef(1.0, 0.25, 1.0); drawSquare(); glTranslatef(0.25, 0.0, 0.0); drawAxes(0.2); glPopMatrix(); glPopMatrix(); } void display(void) { GLenum err; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); drawAxes(1.0); drawBoat(); calculateProjectileStart(); glPopMatrix(); glutSwapBuffers(); // Check for errors while ((err = glGetError()) != GL_NO_ERROR) printf("%s\n",gluErrorString(err)); } void keyboardCB(unsigned char key, int x, int y) { switch (key) { case 27: case 'q': exit(EXIT_SUCCESS); break; case 'c': cannon_angle -= angle_d; break; case 'C': cannon_angle += angle_d; break; case 'b': boat_rotation -= angle_d; break; case 'B': boat_rotation += angle_d; break; default: break; } glutPostRedisplay(); } void myReshape(int w, int h) { glViewport(0, 0, w *2, h*2); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } /* Main Loop * Open window with initial window size, title bar, * RGBA display mode, and handle input events. */ int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(400, 400); glutInitWindowPosition(500, 500); glutCreateWindow("Projectile Motion"); glutKeyboardFunc(keyboardCB); glutReshapeFunc(myReshape); glutDisplayFunc(display); glutIdleFunc(update); glutMainLoop(); }
true
8bbb6b6d286670b0c8bdabdfc4bc3ab567b2c0dc
C++
Bruin-Spacecraft-Group/SPARTAN
/Software/mock/i2c.h
UTF-8
4,207
3.1875
3
[ "MIT" ]
permissive
#ifndef I2C_H_INCLUDED #define I2C_H_INCLUDED #include "types.h" #include <stdexcept> namespace mraa { class I2c { public: /** * Instantiates an i2c bus. Multiple instances of the same bus can * exist and the bus is not guaranteed to be on the correct address * before read/write. * * @param bus The i2c bus to use * @param raw Whether to disable pinmapper for your board */ I2c(int bus, bool raw = false); /** * I2C constructor, takes a pointer to a I2C context and initialises the I2C class * * @param i2c_context void * to an I2C context */ I2c(void* i2c_context); /** * Closes the I2c Bus used. This does not guarantee the bus will not * be usable by anyone else or communicates this disconnect to any * slaves. */ ~I2c(); /** * Sets the i2c Frequency for communication. Your board may not support * the set frequency. Anyone can change this at any time and this will * affect every slave on the bus * * @param mode Frequency to set the bus to * @return Result of operation */ Result frequency(I2cMode mode); /** * Set the slave to talk to, typically called before every read/write * operation * * @param address Communicate to the i2c slave on this address * @return Result of operation */ Result address(uint8_t address); /** * Read exactly one byte from the bus * * @throws std::invalid_argument in case of error * @return char read from the bus */ uint8_t readByte(); /** * Read length bytes from the bus into *data pointer * * @param data Data to read into * @param length Size of read in bytes to make * @return length of read, should match length */ int read(uint8_t* data, int length); /** * Read byte from an i2c register * * @param reg Register to read from * * @throws std::invalid_argument in case of error * @return char read from register */ uint8_t readReg(uint8_t reg); /** * Read word from an i2c register * * @param reg Register to read from * * @throws std::invalid_argument in case of error * @return char read from register */ uint16_t readWordReg(uint8_t reg); /** * Read length bytes from the bus into *data pointer starting from * an i2c register * * @param reg Register to read from * @param data pointer to the byte array to read data in to * @param length max number of bytes to read * @return length passed to the function or -1 */ int readBytesReg(uint8_t reg, uint8_t* data, int length); /** * Write a byte on the bus * * @param data The byte to send on the bus * @return Result of operation */ Result writeByte(uint8_t data); /** * Write length bytes to the bus, the first byte in the array is the * command/register to write * * @param data Buffer to send on the bus, first byte is i2c command * @param length Size of buffer to send * @return Result of operation */ Result write(const uint8_t* data, int length); /** * Write a byte to an i2c register * * @param reg Register to write to * @param data Value to write to register * @return Result of operation */ Result writeReg(uint8_t reg, uint8_t data); /** * Write a word to an i2c register * * @param reg Register to write to * @param data Value to write to register * @return Result of operation */ Result writeWordReg(uint8_t reg, uint16_t data); }; } // namespace mraa #endif // I2C_H_INCLUDED
true
999a3a043ace49b44520236028b4e2028ed6f6a8
C++
MatiasBaci/TP-2-cuatro-en-linea
/Carta.h
UTF-8
819
2.875
3
[ "BSD-3-Clause" ]
permissive
/* * Carta.h * * Created on: Apr 30, 2021 * Author: algo2 */ // Clase Carta #ifndef SRC_CARTA_H_ #define SRC_CARTA_H_ #ifndef NULL #define NULL 0 #endif class Carta { private: int info; Carta* sig; public: /* * pre: Constructor sin argumentos nodo carta * pos: Genera una carta,que es un numero aleatorio del 1 al 4. */ Carta (); /* * pre: Constructor sin argumentos nodo carta * pos: Genera una carta,que es un numero aleatorio del 1 al 4. */ Carta (int valor); /* * pre: Existe la carta. * pos: Nos da el valor de la carta. */ int getInfo (); /* * pre: * pos: Avanza una carta. */ Carta* getSig(); /* * pre: * pos: Hace que la carta apunte a otra determinada. */ void setSig (Carta*); }; #endif /* SRC_CARTA_H_ */
true
0e88e158f3b0e30d1feccc0781d9517b2491d31b
C++
Shikhachandel/COllege
/add.cc
UTF-8
445
2.890625
3
[]
no_license
/*AIM:Program to add two numbers PROGRAM:*/ #include <iostream> using namespace std; int main() { int a,b,c; cout<<"Enter two numbers"; cin>>a>>b; c=a+b; cout<<"The sum is:"<<c; return 0; } /*OUTPUT hermione@granger:~$ cd Desktop hermione@granger:~/Desktop$ g++ OOPS1.1.cc hermione@granger:~/Desktop$ ./a.out Enter two numbers 2 80 The sum is:82 */
true
7635d45bb4d7280eee79cec9aaed9672101f3b12
C++
motxx/AOJ
/repository/10023.cpp
UTF-8
372
2.828125
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main(void) { string str; int n; while (1) { cin >> str; if (str == "-") break; cin >> n; for (int i = 0; i < n; i++) { int l; cin >> l; string left = str.substr(0, l); str = str.substr(l, str.length()) + left; } cout << str << endl; } return 0; }
true
6db1a14343947c40e2a0e088f6101182b8b5ddec
C++
jakibaki/whatsapp-purple
/libaxolotl-cpp/ratchet/rootkey.cpp
UTF-8
937
2.515625
3
[]
no_license
#include "rootkey.h" #include "curve.h" #include "derivedrootsecrets.h" #include <utility> RootKey::RootKey() { } RootKey::RootKey(const HKDF &kdf, const ByteArray &key) { this->kdf = kdf; this->key = key; } ByteArray RootKey::getKeyBytes() const { return key; } std::pair<RootKey, ChainKey> RootKey::createChain(const DjbECPublicKey &theirRatchetKey, const ECKeyPair &ourRatchetKey) { ByteArray sharedSecret = Curve::calculateAgreement(theirRatchetKey, ourRatchetKey.getPrivateKey()); ByteArray derivedSecretBytes = kdf.deriveSecrets(sharedSecret, ByteArray("WhisperRatchet"), DerivedRootSecrets::SIZE, key); DerivedRootSecrets derivedSecrets(derivedSecretBytes); RootKey newRootKey(kdf, derivedSecrets.getRootKey()); ChainKey newChainKey(kdf, derivedSecrets.getChainKey(), 0); std::pair<RootKey, ChainKey> pair; pair.first = newRootKey; pair.second = newChainKey; return pair; }
true
a484e1da12cb799ea1effd806be84673d87edc13
C++
asllanalija/CSCI135
/PROJECT 1/Task D/calc3.cpp
UTF-8
1,223
3.75
4
[]
no_license
/* Author: Asllan Alija Course: CSCI-135 Instructor: Genady Maryash Assignment: Project 1 Task D Can calculate squares of numbers, and can take in multiple expressions. */ #include <iostream> using namespace std; int main() { int num; char symbol; int sum = 0; bool cont = true; bool pos = true; // While there is still input, continue. while (cont) { if (cin >> num) { // Take in a number, then take in a symbol right after. If its an exponent, check last sign, and add/subtract the square. // If its not an exponent, it must be a + or -, so check for that, and assign the sign to a boolean variable. // true if positive, false if negative. cin >> symbol; if (symbol == '^') { if (pos) sum += num*num; else sum -= num*num; cin >> symbol; } else { if (pos) sum += num; else sum-= num; } if (symbol == '+') pos = true; else if (symbol == '-') pos = false; else if (symbol == ';') { cout << sum << endl; sum = 0; symbol = '+'; pos = true; } } else { cont = false; } } }
true
3893413d13631175d9f53848d76b90673cc29437
C++
b-chae/AlgorithmStudy
/baekjoon/1929.cpp
UTF-8
358
2.90625
3
[]
no_license
#include <iostream> using namespace std; int N, M; bool prime[1000001]; int main() { int i; for (i = 2; i <= 500000; i++) { int multiplier = 2; while (i * multiplier <= 1000000) { prime[i * multiplier] = true; multiplier++; } } prime[1] = true; cin >> N >> M; for (i = N; i <= M; i++) { if (prime[i] == false) cout << i << "\n"; } }
true
913a0be2d2e18be8e554337210a704ba2585d1cc
C++
TusharJadhav/usaco
/Section 1.3/Prime Cryptarithm/crypt1.cpp
UTF-8
1,997
2.78125
3
[ "MIT" ]
permissive
/* ID: tushar.4 PROG: crypt1 LANG: C++11 */ #include <iostream> #include <fstream> #include <string> #include <sstream> #include <unordered_set> #include <set> #include <unordered_map> #include <map> #include <vector> #include <queue> #include <deque> #include <array> #include <forward_list> #include <list> #include <stack> #include <algorithm> #include <functional> #include <limits> #include <memory> #include <tuple> #include <initializer_list> #include <utility> #include <iterator> #include <bitset> using namespace std; bool is_valid(int number, int expected_digits, const unordered_set<int>& set) { int actual_digits{ 0 }; while (number != 0) { int digit = number % 10; if (set.find(digit) == set.end()) return false; number /= 10; ++actual_digits; }; return actual_digits == expected_digits; } int main() { ofstream fout("crypt1.out"); ifstream fin("crypt1.in"); int n{ 0 }; fin >> n; vector<int> vec(n); unordered_set<int> set; for (int index = 0; index < n; ++index) { int no; fin >> no; vec[index] = no; set.insert(no); } int result{ 0 }; for (int a2 = 0; a2 < n; ++a2) { for (int a1 = 0; a1 < n; ++a1) { for (int a0 = 0; a0 < n; ++a0) { for (int b1 = 0; b1 < n; ++b1) { for (int b0 = 0; b0 < n; ++b0) { int first = (vec[a2] * 100) + (vec[a1] * 10) + vec[a0]; int second = (vec[b1] * 10) + vec[b0]; int inter1 = vec[b0] * first; if (!is_valid(inter1, 3, set)) continue; int inter2 = vec[b1] * first; if (!is_valid(inter2, 3, set)) continue; int product_result = inter1 + (inter2 * 10); if (!is_valid(product_result, 4, set)) continue; ++result; } } } } } fout << result << endl; return 0; }
true
e3abbe093c09deccc75fe2d580fbf2bd34a13cb3
C++
davidjamesmcclure/CodeSamples
/C++/DensityVisualiser/cav2.cpp
UTF-8
4,834
2.625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <GL/glut.h> #define GLUT_KEY_ESCAPE 27 #ifndef GLUT_WHEEL_UP #define GLUT_WHEEL_UP 3 #define GLUT_WHEEL_DOWN 4 #endif #include "Vector.h" #include "Matrix.h" #include "Volume.h" #define WIDTH 756 #define HEIGHT 256 int lowerRed = 75; int upperRed = 85; int lowerBlue = 100; int upperBlue = 170; static Volume* head = NULL; void Update() { glutPostRedisplay(); } void Draw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBegin(GL_POINTS); for(int y = 0; y < head->GetHeight()-50; y++) for(int z = 0; z < head->GetDepth(); z++) { float distance = 0.0; float alpha = 0.0; float intensity = 0.0; float red = 0.0; float blue = 0.0; float check = 0.0; for (int x = 0; x < head->GetWidth() - 20; x++) { unsigned char val = head->Get(x, y, z); if (alpha < 1){ if((val > lowerRed) && (val < upperRed)){ alpha = ((float)val/255.0) + ((1.0 - ((float)val/255.0)) * alpha); red = red + 1.0; intensity = intensity + (1.0 - alpha) * (((float)val/255.0)); }else if((val > lowerBlue) && (val < upperBlue)){ alpha = ((float)val/255.0) + ((1.0 - ((float)val/255.0)) * alpha); blue = blue + 1.0; intensity = intensity + (1.0 - alpha) * (((float)val/255.0)); } } else if((alpha >= 1) && (check == 0)){ distance = x; check = 1; } } float total = red + blue; if(total != 0.0){ Vector3 color = Vector3((red/total), intensity - (distance/255.0), (blue/total)); glColor3f(color.r(), color.g(), color.b()); glVertex3f(y, z*2, 0); } } for(int x = 0; x < head->GetWidth() - 20; x++) for(int z = 0; z < head->GetDepth(); z++) { float distance = 0.0; float alpha = 0.0; float intensity = 0.0; float red = 0.0; float blue = 0.0; float check = 0.0; for (int y = 0; y < head->GetHeight() - 40; y++) { unsigned char val = head->Get(x, y, z); if (alpha < 1){ if((val > lowerRed) && (val < upperRed)){ alpha = ((float)val/255.0) + ((1.0 - ((float)val/255.0)) * alpha); red = red + 1.0; intensity = intensity + (1.0 - alpha) * (((float)val/255.0)); }else if((val > lowerBlue) && (val < upperBlue)){ alpha = ((float)val/255.0) + ((1.0 - ((float)val/255.0)) * alpha); blue = blue + 1.0; intensity = intensity + (1.0 - alpha) * (((float)val/255.0)); } } else if((alpha >= 1) && (check == 0)){ distance = y; check = 1; } } float total = red + blue; if(total != 0.0){ Vector3 color = Vector3((red/total), intensity - (distance/255.0), (blue/total)); glColor3f(color.r(), color.g(), color.b()); glVertex3f(x + 256, z*2, 0); } } for(int x = 0; x < head->GetWidth() - 20; x++) for(int y = 0; y < head->GetHeight(); y++) { float distance = 0.0; float alpha = 0.0; float intensity = 0.0; float red = 0.0; float blue = 0.0; float check = 0.0; for (int z = 0; z < head->GetDepth() - 40; z++) { unsigned char val = head->Get(x, y, z); if (alpha < 1){ if((val > lowerRed) && (val < upperRed)){ alpha = ((float)val/255.0) + ((1.0 - ((float)val/255.0)) * alpha); red = red + 1.0; intensity = intensity + (1.0 - alpha) * (((float)val/255.0)); }else if((val > lowerBlue) && (val < upperBlue)){ alpha = ((float)val/255.0) + ((1.0 - ((float)val/255.0)) * alpha); blue = blue + 1.0; intensity = intensity + (1.0 - alpha) * (((float)val/255.0)); } } else if((alpha >= 1) && (check == 0)){ distance = z; check = 1; } } float total = red + blue; if(total != 0.0){ Vector3 color = Vector3((red/total), intensity - (distance/255.0), (blue/total)); glColor3f(color.r(), color.g(), color.b()); glVertex3f(y + 512, x, 0); } } glEnd(); glFlush(); glutSwapBuffers(); } void KeyEvent(unsigned char key, int x, int y) { switch(key) { case GLUT_KEY_ESCAPE: exit(EXIT_SUCCESS); break; case 'q': lowerRed -= 1; case 'w': lowerRed += 1; case 'a': upperRed -= 1; case 's': upperRed += 1; case 'o': lowerBlue -= 1; case 'p': lowerBlue += 1; case 'k': upperBlue -= 1; case 'l': upperBlue += 1; } } int main(int argc, char **argv) { head = new Volume("head"); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH|GLUT_MULTISAMPLE); glutInitWindowSize(WIDTH, HEIGHT); glutCreateWindow("cav2"); glClearColor(0.0, 0.0, 0.0, 1.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, WIDTH, HEIGHT, 0, -512, 512); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glutKeyboardFunc(KeyEvent); glutDisplayFunc(Draw); glutIdleFunc(Update); glutMainLoop(); delete head; };
true
bd018654958e64325f0bfdcd5768162bf06261bf
C++
AshifAli007/Algorithm
/encryption.cpp
UTF-8
1,321
2.953125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; // Complete the encryption function below. string encryption(string s) { int size=s.size(); int r,c,flag=0; float width = sqrt(size); cout<<width; for(int i=0;i<size/2;i++){ if(i==width){ flag=1; break; } } if(flag==0){ r = width,c =width+1; }else{ r=width; c=width; } if(r*c<size){ r++; } int k=0; char arr[r][c]; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ if(k>=s.size()){ arr[i][j] =' '; }else{ arr[i][j] = s[k++]; } } } for(int i=0;i<r;i++) { for(int j=0;j<c;j++){ cout<<arr[i][j]<<" "; } cout<<"\n"; } //cout<<r<<c; char code[200]; int t=0; for(int i=0;i<c;i++){ for(int j=0;j<r;j++){ if(arr[j][i]!=' ') code[t++] = arr[j][i]; } code[t++] =' '; } cout<<code; return code; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string s; getline(cin, s); string result = encryption(s); fout << result << "\n"; fout.close(); return 0; }
true
ebd0c8d888779efdd97453a2f48e3a544c0e214c
C++
floghos/Estructura-de-Datos
/Boletines/Lab7/MapG.cpp
UTF-8
2,264
3.15625
3
[]
no_license
#include "MapG.h" #include <string> #include <iostream> using namespace std; //Private Methods int MapG::goodhashCode(string key) { int hash = 13; for (int i = 0; i < key.length(); i++) { hash += key.at(i) * (1 << i); } return hash; } void MapG::rehash() { int newCapacity = capacity * 2; box *newMap = new box[newCapacity]; for (int i = 0; i < capacity; i++) { if (myMap[i].available) { continue; } else { int pos = goodhashCode(myMap[i].key) % newCapacity; while (!newMap[pos].available) { //linear probing pos++; pos %= newCapacity; } newMap[pos].key = myMap[i].key; newMap[pos].val = myMap[i].val; newMap[pos].available = false; } } delete[] myMap; myMap = newMap; capacity = newCapacity; } bool MapG::isFull() { return _size == capacity; } float MapG::loadFactor() { //I may not even use this return (float)_size/capacity; } //Public Methods MapG::MapG() { capacity = 10; myMap = new box[capacity]; } void MapG::insert(pair<string, int> data) { int pos = goodhashCode(data.first) % capacity; while (!myMap[pos].available) { pos++; //linear probing pos %= capacity; } myMap[pos].key = data.first; myMap[pos].val = data.second; myMap[pos].available = false; _size++; if (isFull()) { rehash(); } } void MapG::erase(string key) { bool error_404 = false; //key not found int pos = goodhashCode(key) % capacity; int startingPos = pos; while (myMap[pos].key.compare(key) != 0) { //linear probing if (myMap[pos].key.empty() || pos == startingPos) { error_404 = true; break; } pos++; pos %= capacity; } if (error_404) { // cout << "Error 404: String not found\n"; } else { myMap[pos].available = true; _size--; } } int MapG::at(string key) { bool error_404 = false; //key not found int pos = goodhashCode(key) % capacity; int startingPos = pos; while (myMap[pos].available || myMap[pos].key.compare(key) != 0) { //linear probing if (myMap[pos].key.empty() || pos == startingPos) { error_404 = true; break; } pos++; pos %= capacity; } if (error_404) { // cout << "Error 404: String not found\n"; return -1; } else { return myMap[pos].val; } } int MapG::size() { return _size; } bool MapG::empty() { return !_size; }
true
c7c44881016c5c1902f2411438c32e3c577f5fd3
C++
AWildTeddyBear/CSCI-3200-Parallel-Programming
/Classwork Stuff/PThreads/main.cpp
UTF-8
2,556
3.0625
3
[ "MIT" ]
permissive
// g++ main.cpp -Wall -O3 --std=c++17 -o out // ./out #include <iostream> #include <vector> #include <algorithm> #include <chrono> #include <ctime> #include <random> #include <future> #include <iomanip> #include <utility> #include <iterator> #include <numeric> bool isPrime(const unsigned int n); unsigned int countPrime(const std::vector<unsigned int>& vec); constexpr auto SIZE = 50000000; constexpr auto MULT = 1000000; constexpr auto low_bound = 1; constexpr auto up_bound = 10000; int main(void) { auto seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine dre(seed); std::uniform_int_distribution<unsigned int> di(low_bound,up_bound); std::vector<unsigned int> data(SIZE); std::generate(data.begin(), data.end(), [&dre, &di]{ return di(dre); }); const auto startSingleThread = std::clock(); unsigned int num_single{}; for (const auto& elem : data) if (isPrime(elem)) ++num_single; std::cout << "single thread prime count: " << num_single << std::endl; const auto finishSingleThread = std::clock(); std::cout << std::fixed << std::setprecision(2) << "single thread cpu time used: " << 1000 * (finishSingleThread - startSingleThread) / CLOCKS_PER_SEC << " ms" << std::endl; std::vector<std::vector<unsigned int>> subs(SIZE/MULT, std::vector<unsigned int> (MULT)); for (size_t i = 0; i < subs.size(); ++i) { subs[i].assign(std::make_move_iterator(data.begin() + MULT * i), std::make_move_iterator(data.begin() + MULT * i + MULT)); } std::vector<std::future<unsigned int>> threads{}; const auto startMultiThread = std::clock(); for (size_t i = 0; i < SIZE / MULT; ++i) { threads.emplace_back((std::async(std::launch::async, countPrime, std::move(subs[i])))); } unsigned int num_multi{}; for (auto& elem : threads) num_multi += elem.get(); std::cout << "multi thread prime count: " << num_multi << "\n"; const auto finishMultiThread = std::clock(); std::cout << std::fixed << std::setprecision(2) << "multi thread cpu time used: " << 1000 * (finishMultiThread - startMultiThread) / CLOCKS_PER_SEC << " ms" << std::endl; } bool isPrime(const unsigned int n) { if (n == 1) return true; for (int i = 2; i * i <= n; ++i) { if (!(n % i)) return false; } return true; } unsigned int countPrime(const std::vector<unsigned int>& vec) { unsigned int num{}; for (const auto& elem : vec) if(isPrime(elem)) ++num; return num; }
true
fe2cfb78c6f073d49818a4638ef5ad1128775c19
C++
yusuke-matsunaga/ym-bnet
/include/ym/BnNodeMap.h
UTF-8
1,996
2.796875
3
[]
no_license
#ifndef BNNODEMAP_H #define BNNODEMAP_H /// @file BnNodeMap.h /// @brief BnNodeMap のヘッダファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2023 Yusuke Matsunaga /// All rights reserved. #include "ym/bnet.h" BEGIN_NAMESPACE_YM_BNET ////////////////////////////////////////////////////////////////////// /// @class BnNodeMap BnNodeMap.h "BnNodeMap.h" /// @brief 番号をキーにしたノードの辞書 ////////////////////////////////////////////////////////////////////// class BnNodeMap { public: /// @brief コンストラクタ BnNodeMap( const BnNetworkImpl* network = nullptr ) : mNetwork{network} { } /// @brief デストラクタ ~BnNodeMap() = default; public: ////////////////////////////////////////////////////////////////////// // 外部インターフェイス ////////////////////////////////////////////////////////////////////// /// @brief 内容をクリアする. void clear() { mIdMap.clear(); } /// @brief 要素が登録されているか調べる. bool is_in( SizeType key ///< [in] キー ) const { return mIdMap.count(key) > 0; } /// @brief ノードを取り出す. BnNode get( SizeType key ///< [in] キー ) const { SizeType id = mIdMap.at(key); return BnNode{mNetwork, id}; } /// @brief ノードを登録する. void put( SizeType key, ///< [in] キー BnNode node ///< [in] ノード ) { mIdMap.emplace(key, node.id()); } /// @brief ノード番号の辞書を取り出す. unordered_map<SizeType, SizeType>& _id_map() { return mIdMap; } private: ////////////////////////////////////////////////////////////////////// // データメンバ ////////////////////////////////////////////////////////////////////// // ネットワーク const BnNetworkImpl* mNetwork; // ノード番号の辞書 unordered_map<SizeType, SizeType> mIdMap; }; END_NAMESPACE_YM_BNET #endif // BNNODEMAP_H
true
71eb5b56bd8e9af48f4bf77f69e2a49082cced3f
C++
Timdpr/maiolica
/src/pvtable.cpp
UTF-8
7,668
3.015625
3
[]
no_license
#include "defs.h" // Macros for extracting specific data out of the 'data' 64-bit int #define EXTRACT_SCORE(x) ((x & 0xFFFF) - INF_BOUND) #define EXTRACT_DEPTH(x) ((x >> 16) & 0x3F) #define EXTRACT_FLAGS(x) ((x >> 23) & 0x3) #define EXTRACT_MOVE(x) ((int)(x >> 25)) // Macro for combining data into the 'data' 64-bit int #define FOLD_DATA(score, depth, flags, move) ( (score + INF_BOUND) | (depth << 16) | (flags << 23) | ((U64)move << 25)) void dataCheck(const int move) { int depth = rand() % MAX_DEPTH; int flags = rand() % 3; int score = rand() % ALPHABETA_BOUND; U64 data = FOLD_DATA(score, depth, flags, move); printf("Orig : move:%s d:%d fl:%d sc:%d data:%llX\n", printMove(move), depth, flags, score, data); printf("Check: move:%s d:%d fl:%d sc:%d\n\n", printMove(EXTRACT_MOVE(data)), EXTRACT_DEPTH(data), EXTRACT_FLAGS(data), EXTRACT_SCORE(data)); } void tempHashTest(char *fen) { Board board{}; parseFen(fen, board); MoveList moveList[1]; generateAllMoves(board, moveList); for (int moveNum = 0; moveNum < moveList->count; ++moveNum) { if (!makeMove(board, moveList->moves[moveNum].move)) { continue; } undoMove(board); dataCheck(moveList->moves[moveNum].move); } } HashTable hashTable[1]; /// Populate Board's pvArray int getPVLine(const int depth, Board& board, const HashTable *table) { ASSERT(depth < MAX_DEPTH && depth >= 1) int move = probePVTable(board, table); int count = 0; // 'loop through board's pvArray until given depth, as long as legal moves are being found' while (move != NO_MOVE && count < depth) { ASSERT(count < MAX_DEPTH) if (moveExists(board, move)) { makeMove(board, move); board.pvArray[count++] = move; // populate pvArray with move } else { break; } move = probePVTable(board, table); } // Take the moves back!!!!11!!1! while (board.ply > 0) { undoMove(board); } return count; } /// Loop through every entry in the table, setting each pos key and move to zero void clearHashTable(HashTable *table) { for (HashEntry *hashEntry = table->hTable; hashEntry < table->hTable + table->numEntries; hashEntry++) { hashEntry->positionKey = U64(0); hashEntry->move = NO_MOVE; hashEntry->depth = 0; hashEntry->score = 0; hashEntry->flags = 0; hashEntry->age = 0; } table->currentAge = 0; } /** * 'Initialise hash table' * by dynamically declaring the memory for what is essentially an array */ void initHashTable(HashTable *table, const int MB) { int hashSize = 0x100000 * MB; table->numEntries = hashSize / sizeof(HashEntry); // how many entries can we fit inside? table->numEntries -= 2; // make sure we don't go over! if (table->hTable != nullptr) { free(table->hTable); // free table pointer's memory } // Todo: May have to change this substantially for larger sizes... table->hTable = (HashEntry *) malloc(table->numEntries * sizeof(HashEntry)); // allocate memory with similar logic to how it was freed! if (table->hTable == nullptr) { printf("Hash table allocation failed, trying again with %dMB", MB/2); initHashTable(table, MB / 2); } else { clearHashTable(table); printf("HashTable init complete with %d entries\n", table->numEntries); } } /// Get move indexed with this board's position key from principal variation table (if it exists) int probeHashEntry(Board& board, HashTable *table, int *move, int *score, int alpha, int beta, int depth) { // get index out of pos key modulo the number of entries! int index = board.positionKey % table->numEntries; ASSERT(index >= 0 && index <= hashTable->numEntries - 1) ASSERT(depth >=1 && depth < MAX_DEPTH) ASSERT(alpha < beta) ASSERT(alpha >= -ALPHABETA_BOUND && alpha <= ALPHABETA_BOUND) ASSERT(beta >= -ALPHABETA_BOUND && beta <= ALPHABETA_BOUND) ASSERT(board.ply >= 0 && board.ply < MAX_DEPTH) // if pos keys are equal... if (table->hTable[index].positionKey == board.positionKey) { *move = table->hTable[index].move; // get move if (table->hTable[index].depth >= depth) { // if depth >= search depth table->hit++; // we have a hit! ASSERT(hashTable->hTable[index].depth >= 1 && hashTable->hTable[index].depth < MAX_DEPTH) ASSERT(hashTable->hTable[index].flags >= HF_ALPHA && hashTable->hTable[index].flags <= HF_EXACT) // get score & adjust according to ply if it is a mate score (we got rid of this when storing) *score = table->hTable[index].score; if (*score > IS_MATE) { *score -= board.ply; } else if (*score < -IS_MATE) { *score += board.ply; } // check for match depending on flags switch (table->hTable[index].flags) { case HF_ALPHA: if (*score <= alpha) { *score = alpha; return true; } break; case HF_BETA: if (*score >= beta) { *score = beta; return true; } break; case HF_EXACT: return true; default: ASSERT(false) break; } } } return NO_MOVE; } /// Store a move in the table /// TODO: Look up the more complex algorithms for how and when to store hash entries void storeHashEntry(Board& board, HashTable *table, const int move, int score, const int flags, const int depth) { // make index out of pos key modulo the number of entries! int index = board.positionKey % table->numEntries; ASSERT(index >= 0 && index <= hashTable->numEntries - 1) ASSERT(depth >= 1 && depth < MAX_DEPTH) ASSERT(flags >= HF_ALPHA && flags <= HF_EXACT) ASSERT(score >= -INF_BOUND && score <= INF_BOUND) ASSERT(board.ply >= 0 && board.ply < MAX_DEPTH) bool replace = false; if (table->hTable[index].positionKey == 0) { // new entry replace = true; } else { // otherwise, if index that we're trying to replace is older than our current entry, or the depth is greater, then we replace if (table->hTable[index].age < table->currentAge || table->hTable[index].depth <= depth) { replace = true; } } if (!replace) { return; // return early without storing the worse entry! } // reset score back to 'infinite' (after it was adjusted by ply in the search) if (score > IS_MATE) { score += board.ply; } else if (score < -IS_MATE) { score -= board.ply; } // add move and pos key to table at index table->hTable[index].move = move; table->hTable[index].positionKey = board.positionKey; table->hTable[index].flags = flags; table->hTable[index].score = score; table->hTable[index].depth = depth; table->hTable[index].age = table->currentAge; } int probePVTable(const Board& board, const HashTable *table) { // get index out of pos key modulo the number of entries! int index = board.positionKey % table->numEntries; ASSERT(index >= 0 && index <= hashTable->numEntries - 1) // if pos keys are equal, we can return move at the index if (table->hTable[index].positionKey == board.positionKey) { return table->hTable[index].move; } return NO_MOVE; }
true
760a49444351409f843a5b79010b07aef279eb87
C++
kaanozbudak/cProjects
/calisma2.cpp
UTF-8
261
2.671875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> int main () { int sayi1,sayi2,a; printf("Please enter two numbers:\n"); scanf("%d %d",&sayi1,&sayi2); a=sayi1/sayi2; printf("Bolum:%d\n",a); sayi1%=sayi2; printf("Kalan:%d",sayi1); }
true
960a5f1e6fbe597e5204c2ee7f2f049c32b5d056
C++
tianfangm/Algorithm
/PTA/DataStructure/03-树2 List Leaves.cpp
UTF-8
1,931
3.453125
3
[]
no_license
#include <iostream> #include <vector> #include <queue> using namespace std; struct Node{ int val; int left,right; Node(){} Node(int c,int l,int r):val(c),left(l),right(r){} }; void LevelTraversal(vector<Node>tree,int root,vector<int>&result) { queue<int> q; q.push(root); while(!q.empty()) { int n = q.size(); for(int i =0;i<n;++i) { int Tmp = q.front(); q.pop(); if((tree[Tmp].left)!=-1) q.push(tree[Tmp].left); if((tree[Tmp].right)!=-1) q.push(tree[Tmp].right); if((tree[Tmp].right)==-1&&(tree[Tmp].left)==-1) { result.push_back(tree[Tmp].val); } } } } int CreateTree(vector<Node>&tree) { int n = 0; int ret = -1; scanf("%d",&n); vector<int> root(n,1); for(int i =0;i<n;++i) { Node node; char l,r; node.val = i; scanf("\n%c %c",&l,&r); if(l=='-') { node.left = -1; } else { node.left = l-'0'; root[l-'0']=0; } if(r=='-') { node.right = -1; } else { node.right = r-'0'; root[r-'0']=0; } tree.emplace_back(node); } for(int i =0;i<n;++i) { if(root[i]) { ret = i; break; } } return ret; } // 打印 void Print(const vector<int>&vec) { int n = vec.size(); for(int i =0;i<n;++i) { printf("%d",vec[i]); if(i!=n-1) { printf(" "); } } printf("\n"); } int main() { int root; vector<Node> tree; vector<int> result; root = CreateTree(tree); LevelTraversal(tree,root,result); Print(result); return 0; }
true
5f0fcccdbda378f1b0fd71f450866d9d4b67ed40
C++
Radmir2015/OOPLaboratory
/OOPLaba1/OOPLaba1/Student.h
WINDOWS-1251
2,560
3.65625
4
[]
no_license
#pragma once #include <string> #include <tuple> #include <vector> using namespace std; struct Date { int day, month, year; }; class Student { public: Student() { name = ""; surname = ""; orderNumber = ""; phoneNumber = ""; groupNumber = ""; enterDate = {0, 0, 0}; birthDate = {0, 0, 0}; } Student(string name, string surname = "", string orderNumber = "", string phoneNumber = "", string groupNumber = "", Date enterDate = {0, 0, 0}, Date birthDate = {0, 0, 0}) { this->name = name; this->surname = surname; this->orderNumber = orderNumber; this->phoneNumber = phoneNumber; this->groupNumber = groupNumber; this->enterDate = enterDate; this->birthDate = birthDate; } string getIntro() { return this->name + " " + this->surname; } string getOrderNumber() { return this->orderNumber; } string getSurname() { return this->surname; } string getGroupNumber() { return this->groupNumber; } Date getBirthDate() { return this->birthDate; } Date getEnterDate() { return this->enterDate; } private: string orderNumber, name, surname, phoneNumber, groupNumber; Date enterDate, birthDate; }; // string dateToString(Date date, char delim = '.') { return to_string(date.day) + delim + to_string(date.month) + delim + to_string(date.year); } // : bool isFilledDate(Date date) { return date.day != 0 && date.month != 0 && date.year != 0; } // tuple<bool, string, Date> getStudentByOrder(vector<Student> sts, string order) { tuple<bool, string, Date> temp; for (auto s : sts) { if (s.getOrderNumber() == order) { tuple<bool, string, Date> temp(true, s.getSurname(), s.getBirthDate()); return temp; } } return temp; } // , tuple<bool, Student, Student> inOneDate(vector<Student> sts) { tuple<bool, Student, Student> temp; for (int i = 0; i < sts.size() - 1; i++) for (int j = i + 1; j < sts.size(); j++) { if (dateToString(sts[i].getEnterDate()) == dateToString(sts[j].getEnterDate()) && isFilledDate(sts[i].getEnterDate())) { tuple<bool, Student, Student> temp(true, sts[i], sts[j]); return temp; } } return temp; }
true
5c354c7672ac4a7e74cc219eb045faec6aae4713
C++
CaoHoaiTan/HCMUTE
/Nhập môn lập trình - Introduction to Programming/Chapter 2/C Cplusplus/B36-Square(DK).cpp
UTF-8
401
3
3
[]
no_license
#include <stdio.h> #include <math.h> void nhap(int &n, float &x); float solve(int n, float x); void xuat(float kq); int main() { int n; float x; nhap(n,x); float kq=solve(n,x); xuat(kq); return 0; } void nhap(int &n,float &x) { scanf("%d%f", &n,&x); } float solve(int n, float x) { float s=0; for (int i=1;i<=n;i++) s=sqrt(x+s); return s; } void xuat(float kq) { printf("%f", kq); }
true
c0de2768edcd76d979a8bd763a96cc180519e2d8
C++
akileshsadassivam/MyTimepassCode
/cpp/pascal_row.cpp
UTF-8
746
3.0625
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <string> #include <cstdio> #include <list> #include <algorithm> #include <vector> using namespace std; uint64_t fact(uint64_t n){ if(n==1 || n==0){ return 1; } else return n*fact(n-1); } vector<uint64_t> getRow(uint64_t rowIndex) { vector<uint64_t> res; for (uint64_t i = 0; i <= rowIndex; i++) { res.push_back((uint64_t)(fact(rowIndex)/(fact(rowIndex-i)*fact(i)))); } return res; } int main(){ cout<<"enter row for pascal triangle"<<endl; uint64_t n; cin>>n; vector<uint64_t> pascal = getRow(n); for(uint64_t j=0;j<=n;j++){ cout<<pascal[j]<<" "; } cout<<endl; }
true
45ad535dbf93ff90f635a9c4d8631c4fe0d3553c
C++
tgabor7/OpenGLEngine
/Boring/InstanceRenderSystem.h
UTF-8
1,149
2.65625
3
[]
no_license
#pragma once #include "Mesh.h" #include "system.h" #include "EntityHandler.h" #include "Shader.h" #include "Maths.h" struct MeshInstance { vec3 position; vec3 rotation; vec3 scale; Texture *texture; }; class InstanceComponent : public Component<InstanceComponent> { public: InstanceComponent() {} InstanceComponent(ModelData data); InstanceComponent(ModelData data,bool rot); vector<MeshInstance> meshes; vector<Texture*> textures; ModelData data; int draw_count; GLuint vao; GLuint vbo; void addInstance(vec3 position, vec3 rotation, vec3 scale, Texture *texture); void addInstance(MeshInstance instance); void removeInstance(int id); bool rotation; ~InstanceComponent() {} private: }; class InstanceRenderSystem : public System { public: InstanceRenderSystem(); void update(double delta); ~InstanceRenderSystem(); private: Shader shader; vector<float> vboData; int pointer = 0; void storeMatrixData(mat4x4 matrix, float * vboData); void bindTexture(Texture *texture); void updateModelViewMatrix(vec3 position, float rx, float ry, float rz, float width, float height, float length, float scale, float * vboData); };
true
7eab38ff1dc1595585e9042c7702606fa543caaa
C++
bigfatbrowncat/cubes
/sfmlcube/src/movingcubes/Cube.h
UTF-8
666
2.578125
3
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
/* * Cube.h * * Created on: Nov 20, 2012 * Author: imizus */ #ifndef CUBE_H_ #define CUBE_H_ #include <SFML/Graphics.hpp> namespace sfmlcubes { namespace movingcubes { struct Cube { public: // Inner types enum ModelType { mtVoid, // Empty cube. Doesn't draw itself at all mtPlaying, mtWall }; public: static sf::Shader* cubeShader; public: // Fields ModelType modelType; sf::Color color; int x, y; public: // Functions Cube(int x, int y, ModelType modelType, sf::Color color); Cube(); bool operator == (const Cube& other); bool operator != (const Cube& other); }; } } #endif
true
a8ad1968ca48d6254e9ef3f5f875403db4da5e2a
C++
JakeS271/Intro-To-CPP-Assessment
/ITC++Assignment/Game.cpp
UTF-8
2,846
2.984375
3
[]
no_license
#include "Game.h" #include "Player.h" #include "Room.h" #include "MyString.h" #include <iostream> #include <vector> Game::Game() { } Game::~Game() { } MyString Room::location; MyString Game::UserCommand() { std::cout << "What shall we do?\n"; char command[256]; std::cin.getline(command, m_MAX_SIZE); return MyString(command); } void Game::start() { MyString intro("\nWelcome to The Mansion.\nYou are trapped inside and must find a way out.\n\n"), command; intro.print(); static Player player; Room m_studyR; endRoom m_exitR; lockRoom m_startR; puzzleRoom m_puzzleR; Room * m_startP = &m_startR; Room * m_studyP = &m_studyR; Room * m_puzzleP = &m_puzzleR; Room * m_exitP = &m_exitR; m_startR.roomDescrip("You are in the main foyer with a door to the EAST and the WEST\nThere's a locked trap door in the center of the room and paintings on the walls.\n\n"); m_startR.setDirections("west", "studyR"); m_startR.setDirections("east", "puzzleR"); m_startR.setRoomItems("painting", "It's a painting of a boat.\n\n", " ", false); m_startR.setRoomItems("trap door", "It's locked.\n\n", "key", true); m_studyR.roomDescrip("You are in a study.\nThere is a bookcase covered in dust and a desk next to it.\n\n"); m_studyR.setDirections("east", "startR"); m_studyR.setRoomItems("desk", "The desk has a letter on it with the name smudged.\nOnly the first half is clear.\nHAR\n\n", false); m_studyR.setRoomItems("bookcase", "Their is a book that seems average except a name it worn away except the last half.\nKYN\n\n", false); m_puzzleR.roomDescrip("You are in a black room with only a computer which poses a question.\nWhat is my name?\n\n"); m_puzzleR.setDirections("west", "startR"); m_puzzleR.setRoomItems("computer", "It's a strange computer only displaying a question.\nWhat is my name?\n\n", "", false); m_puzzleR.setAnswer("harkyn", "key", "THAT IS MY NAME\nA key descends from the light above and you pick it up.\n\n"); m_exitR.roomDescrip("You are in a tunnel that leads out of the mansion.\n\n"); cLocation[0].roomName = "startR"; cLocation[0].roomPointers = m_startP; cLocation[1].roomName = "studyR"; cLocation[1].roomPointers = m_studyP; cLocation[2].roomName = "puzzleR"; cLocation[2].roomPointers = m_puzzleP; cLocation[3].roomName = "exitR"; cLocation[3].roomPointers = m_exitP; Room::location = "startR"; while (m_end != true) { //m_end = true; Location(); } std::cout << "Congratulations!\nYou have beat the game.\n"; system("PAUSE"); } void Game::Location() { for (int i = 0; i < m_TOTAL_ROOM; i++) { if (cLocation[i].roomName == Room::location) { if (Room::location == "puzzleR") { cLocation[i].roomPointers->Update(UserCommand()); } cLocation[i].roomPointers->descriptPrint(); cLocation[i].roomPointers->Update(UserCommand()); break; } } }
true
c4c8b26af1bfeb789da7e9aa32f781600518bce0
C++
asmei1/SFML-IPS
/LClient/ResourceManager.h
UTF-8
798
2.65625
3
[]
no_license
#pragma once #include <string> #include <unordered_map> template<typename Derived, typename T> class ResourceManager { public: ResourceManager(const std::string& l_pathsFile) { LoadPaths(l_pathsFile); }; virtual ~ResourceManager() { PurgeResources(); } T* GetResource(const std::string& l_id); std::string GetPath(const std::string& l_id); bool RequireResource(const std::string& l_id); bool ReleaseResource(const std::string& l_id); void PurgeResources(); T* Load(const std::string& l_path); std::pair<T*, unsigned int>* Find(const std::string& l_id); bool Unload(const std::string& l_id); void LoadPaths(const std::string& l_pathFile); private: std::unordered_map<std::string, std::pair<T*, unsigned int>> m_resources; std::unordered_map<std::string, std::string> m_paths; };
true
e8a1a8893ca18027e55b3c4b1c504225233872d3
C++
alexandraback/datacollection
/solutions_5708921029263360_0/C++/Vikeydr/fashion.cpp
UTF-8
1,123
2.515625
3
[]
no_license
#include <fstream> #include <iostream> #include <set> #include <string.h> #include <algorithm> using namespace std; int main(){ int t; ifstream in("C-small-attempt1.in"); ofstream out("fashion.out"); in >> t; for (int tt = 0; tt < t;tt++){ int jean,p,s,kl; in >> jean >> p >> s >> kl; int jp[100],js[100],sp[100]; for (int i = 0; i < 100;i++){ jp[i] = 0; js[i] = 0; sp[i] = 0; } int day = 0; out << "Case #" << tt+1 << ": "; string res = ""; for (int k = 0;k < s;k++) for (int j = 0; j < p; j++) for (int i = 0; i < jean;i++){ if (jp[i*10+j] < kl && js[i*10+k] <kl && sp[j*10+k] < kl){ day++; jp[i*10+j] ++; js[i*10+k] ++; sp[j*10+k] ++; res = res + char(i+48) + char(j+48) + char(k+48)+ ' '; //cout << i << ' ' << j << ' ' << k << ' ' << day << endl; //cout << res << endl; } } out << day << endl; cout << res << endl; for (int i = 0 ;i < res.length();i++){ if (res[i] == ' ') out << endl; else out << (int(res[i])-48)+1 << ' '; } } in.close(); out.close(); }
true
4c64a7cf626b3a2b8ee83e5e3a55882b7fe7c634
C++
liyupi/sjtuoj
/1209.cpp
UTF-8
401
3.109375
3
[]
no_license
#include <iostream> using namespace std; int N; int getBitNum(int num) { int count = 0; while(num) { num &= num - 1; count++; } return count; } int main() { while (cin >> N) { int sum = 0; for (int i = 0; i < N; ++i) { int num; cin >> num; sum += getBitNum(num); } cout << sum << endl; } }
true
5e2f29c9048bf338a88eeb62e61307c8dac3928f
C++
polaris/hermes
/src/Queue.h
UTF-8
1,239
3.453125
3
[]
no_license
#ifndef _Queue_H #define _Queue_H #include <boost/lockfree/queue.hpp> #include <memory> #include <functional> #include <atomic> template <typename T> class Queue { public: explicit Queue(uint32_t size) : size_(size) , queue_(size_) , count_(0) { } Queue(uint32_t size, std::function<T* ()> create) : Queue(size) { for (uint32_t i = 0; i < size_; ++i) { push(create()); } } Queue(const Queue&) =delete; Queue& operator =(const Queue&) =delete; virtual ~Queue() { T* element; while (queue_.pop(element)) { delete element; } } void push(T* element) { if (element != nullptr) { queue_.push(element); count_++; } } T* pop() { T* element; if (queue_.pop(element)) { count_--; return element; } return nullptr; } uint32_t getSize() const { return size_; } uint32_t getCount() const { return count_; } private: const uint32_t size_; boost::lockfree::queue<T*> queue_; std::atomic<uint32_t> count_; }; template <typename T> using Pool = Queue<T>; #endif // _Queue_H
true
b1ee0ad4565487a3137647bee19b3dd738600466
C++
ajfoggia/BowlingProgram
/BowlingImplem.cpp
UTF-8
19,829
3.8125
4
[]
no_license
#include "bowlingHeader.h" #include <iostream> #include <iomanip> //Library used for setw() for formatting using namespace std; void Bowling::MainMenu() //Function that displays the menu to the terminal. { cout << "What would you like to do?\n"; cout << "1. Create a game\n"; cout << "2. Display the frames of the previous game\n"; cout << "3. Display the total score of the previous game\n"; cout << "4. Show this menu again\n"; cout << "5. Exit the program\n"; } bool Bowling::validCharCheck(char c) //Function to check if the user input is valid. { int reg_num = 0; reg_num = c - ASCII_conv; if(c == 'X' || c == 'x') //If there is a x, it is valid. return true; else if(c == '/') //If there is a /, it is valid. return true; else if(reg_num <= 9) //If it is less than or equal to 9, it is valid. return true; else //Anything else is not valid either. return false; } void Bowling::grabBoxScores(struct player p_player[]) //Function that grabs the scores of every box in every frame. { bool valid; //Variable to hold whether a user's input is valid. for (int p = 1; p <= 4; p++) //Loop that keeps track of which player is being totaled. { roll = 0; //Roll number is re-initialized. cout << "\nPlayer " << p << "'s score is now being totaled."; for (int f = 1; f <= MAX_FRAMES; f++) //Loop that controls which frame is being totaled. { if (f != MAX_FRAMES) //As long as it isn't the last frame, calculate the other frames. { cout << "\nPlease enter in the score for the first box in frame " << f << ": "; cin >> c_flag; valid = validCharCheck(c_flag); //Check to make sure that the input is valid. if (valid == true) //If the input is valid, put the input in the box. { if (c_flag == 'X' || c_flag == 'x') //If the input is a strike. { p_player[p].b_scores[roll] = 10; //Set first box to 10. cout << "STRIKE!!!!\n"; cout << "First box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; p_player[p].b_scores[roll] = 0; //Set second box to 0. roll++; } else //Otherwise, the input is just a number between 0-9. { p_player[p].b_scores[roll] = (int) c_flag - ASCII_conv; cout << "First box for frame " << " = " << p_player[p].b_scores[roll] << "\n"; roll++; c_flag = 0; //Re-initialize the flag. cout << "\nNow enter in the score for the second box: "; cin >> c_flag; if (c_flag == '/') //If the input is a spare. { p_player[p].b_scores[roll] = 10 - p_player[p].b_scores[roll - 1]; //Find the difference out of 10 to put correct value in box. cout << "SPARE!!!!\n"; cout << "Second box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; } else //Otherwise, the input is just another number between 0-9. { p_player[p].b_scores[roll] = (int) c_flag - ASCII_conv; cout << "Second box for frame " << " = " << p_player[p].b_scores[roll] << "\n"; roll++; } c_flag = 0; //Re-initialize the flag. } } else //Otherwise, the first input was not valid. { cout << "Sorry, that output is not accepted.\n"; cout << "Inputting a 0 for this frame.\n"; p_player[p].b_scores[roll] = 0; //Fill the roll with a 0. roll++; p_player[p].b_scores[roll] = 0; //Fill the next roll with a 0. roll++; c_flag = 0; } } else //It is the last frame. { c_flag = 0; cout << "\nPlease enter the score for the first box in the final frame (number " << f << "): "; cin >> c_flag; valid = validCharCheck(c_flag); //Check if the input is valid. if (valid == true) //If the input is valid. { if (c_flag == 'X' || c_flag == 'x') //If first score in final frame is a strike, two more boxes are allowed. { p_player[p].b_scores[roll] = 10; //Put 10 into the first box. cout << "STRIKE!!!\n"; cout << "First box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; c_flag = 0; cout << "\nNow enter in the score for the second box: "; cin >> c_flag; if (c_flag == 'X' || c_flag == 'x') //If second score is a strike, set second score to 10. { p_player[p].b_scores[roll] = 10; cout << "SECOND STRIKE!!!!\n"; cout << "Second box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; } else //Otherwise, the second score is just a number between 0-9. { p_player[p].b_scores[roll] = (int) c_flag - ASCII_conv; cout << "Second box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; } c_flag = 0; cout << "\nFinally enter in the score for the last box: "; cin >> c_flag; if (c_flag == 'X' || c_flag == 'x') //If the last score is a strike, set the last score to 10. { p_player[p].b_scores[roll] = 10; cout << "THIRD STRIKE (TURKEY)!!!\n"; cout << "Third box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; } else if (c_flag == '/') //If the last score makes a spare, find the difference to put into the last score. { p_player[p].b_scores[roll] = 10 - p_player[p].b_scores[roll - 1]; cout << "SPARE!!!!\n"; cout << "Third box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; } else //Otherwise, it is just a number between 0-9. { p_player[p].b_scores[roll] = (int) c_flag - ASCII_conv; cout << "Third box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; } } else //Otherwise, the first score on the final frame is not a strike and just a number between 0-9. { p_player[p].b_scores[roll] = (int) c_flag - ASCII_conv; cout << "First box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; c_flag = 0; cout << "\nNow enter in the score for the second box: "; cin >> c_flag; if (c_flag == '/') //If the second score makes a spare, find the difference to put into the second score. { p_player[p].b_scores[roll] = 10 - p_player[p].b_scores[roll - 1]; cout << "SPARE!!!!\n"; cout << "Second box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; c_flag = 0; cout << "\nFinally enter in the score for the last box: "; cin >> c_flag; if (c_flag == 'X' || c_flag == 'x') //If the last score is a strike, set the last score to 10. { p_player[p].b_scores[roll] = 10; cout << "STRIKE!!!\n"; cout << "Third box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; } else //Otherwise, it is just a number between 1-9. { p_player[p].b_scores[roll] = (int) c_flag - ASCII_conv; cout << "Third box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; } } else //Otherwise, the second box is just a number between 1-9. { p_player[p].b_scores[roll] = (int) c_flag - ASCII_conv; cout << "Third box for frame " << f << " = " << p_player[p].b_scores[roll] << "\n"; roll++; } } } else //Otherwise, the first input was not valid. { cout << "Sorry, that output is not accepted.\n"; cout << "Inputting a 0 for this frame.\n"; p_player[p].b_scores[roll] = 0; //Fill the roll with a 0. roll++; p_player[p].b_scores[roll] = 0; //Fill the next roll with 0. roll++; c_flag = 0; } } } } } void Bowling::calculateFrames(player p_player[]) //Function that finds the totals for all the frames. { for(int p = 1; p <= 4; p++) //Loop that keeps track of which player you are totaling. { roll = 0; //Initialize the roll you are on. for (int f = 1; f <= MAX_FRAMES; f++) //Loop that keeps track of which frame you are on. { if (p_player[p].b_scores[roll] == 10) //If roll is a strike, grab the next two rolls. { if (f == 1) //If it is the first frame, there is no previous total to add to. { p_player[p].f_scores[f] = 10; //Set starting total to 10 roll++; //Increment to skip over the 0 in box 2. if (p_player[p].b_scores[roll + 1] == 10) //If there is a second strike consecutively, add another 10 { p_player[p].f_scores[f] += 10; if (p_player[p].b_scores[roll + 3] == 10) //If there is a third strike, add the last 10. { p_player[p].f_scores[f] += 10; roll++; } else //Otherwise, there is no third strike and you just grab the next roll. { p_player[p].f_scores[f] += p_player[p].b_scores[roll + 3]; roll++; } } else { p_player[p].f_scores[f] += p_player[p].b_scores[roll + 1] + p_player[p].b_scores[roll + 2]; //Then add the next two rolls to the total. roll++; } } else //Otherwise, it is another frame and you can add the frame to the previous total. { p_player[p].f_scores[f] = p_player[p].f_scores[f - 1] + 10; //Add 10 to the previous total. roll++; //Increment to skip over the 0 in box 2. if (f == MAX_FRAMES) //If it is the last frame, add the extra rolls. { p_player[p].f_scores[f] += p_player[p].b_scores[roll]; roll++; p_player[p].f_scores[f] += p_player[p].b_scores[roll]; } else if (p_player[p].b_scores[roll + 1] == 10) //If there is a second strike consecutively, add another 10 { p_player[p].f_scores[f] += 10; if (p_player[p].b_scores[roll + 3] == 10) //If there is a third strike, add the last 10. { p_player[p].f_scores[f] += 10; roll++; } else if (f == MAX_FRAMES - 1) //If it is the 9th frame then just add the second roll of the final frame. { p_player[p].f_scores[f] += p_player[p].b_scores[roll + 2]; roll++; } else //Otherwise, there is no third strike and you just grab the next roll. { p_player[p].f_scores[f] += p_player[p].b_scores[roll + 3]; roll++; } } else //Otherwise, there are no consecutive strikes and it is totaled normally. { p_player[p].f_scores[f] += p_player[p].b_scores[roll + 1] + p_player[p].b_scores[roll + 2]; //Then add the next two rolls to the total. roll++; } } } else if (p_player[p].b_scores[roll] + p_player[p].b_scores[roll + 1] == 10) //If it is a spare { if (f == 1) //If it is the first frame. { p_player[p].f_scores[f] = 10; //Set starting total to 10. roll++; //Increment to skip over box 2. if (p_player[p].b_scores[roll + 1] == 10) //If there is a strike in the next box, add another 10. { p_player[p].f_scores[f] += 10; } else { p_player[p].f_scores[f] += p_player[p].b_scores[roll + 1]; //Then add the next roll to the total. roll++; } } else if (f == MAX_FRAMES) //If it is the final frame, add the next frame and then you get a bonus roll. { p_player[p].f_scores[f] = p_player[p].f_scores[f - 1] + 10; roll++; p_player[p].f_scores[f] += p_player[p].b_scores[roll + 1]; } else //Otherwise, it is not the first frame. { p_player[p].f_scores[f] = p_player[p].f_scores[f - 1] + 10; //Add 10 to the previous total. roll++; //Increment to skip over the 0 in box 2. if (p_player[p].b_scores[roll + 1] == 10) //If there is a second strike consecutively, add another 10 { p_player[p].f_scores[f] += 10; } else //It is just another frame. { p_player[p].f_scores[f] += p_player[p].b_scores[roll + 1]; //Then add the next roll to the total. roll++; } } } else //Otherwise, a strike was not rolled and you just total the frame normally. { if (f == 1) //If it is the first frame, there is no previous total to add to. { p_player[p].f_scores[f] = p_player[p].b_scores[roll]; //Add first roll to total. roll++; p_player[p].f_scores[f] += p_player[p].b_scores[roll]; //Then add the next roll to the total. roll++; } else //Otherwise, it is another frame and you can add the frame to the previous total. { p_player[p].f_scores[f] = p_player[p].f_scores[f - 1] + p_player[p].b_scores[roll]; //Add first roll to previous total. roll++; p_player[p].f_scores[f] += p_player[p].b_scores[roll]; //Then add the next roll. roll++; } } } } } void Bowling::displayFrames(struct player p_player[]) { calculateFrames(p_player); //Calculate the frame totals before displaying. for(int p = 1; p <= 4; p++) { cout << "/////////////////////////////////////////////////////////////////\n"; cout << setw(11) << "Player" << setw(10) << "Frame" << setw(18) << "Frame Score\n"; cout << setw(9) << p; for(int f = 1; f <= MAX_FRAMES; f++) { if(f == 1) //If it is the first frame. { cout << setw(10) << f << setw(15) << p_player[p].f_scores[f] << "\n"; } else //Otherwise, it is another frame { cout << setw(19) << f << setw(15) << p_player[p].f_scores[f] << "\n"; } } } } void Bowling::displayTotal(struct player p_player[]) { cout << setw(11) << "Player" << setw(16) << "Total Score\n"; for(int p = 1; p <= 4; p++) { cout << setw(9) << p << setw(12) << p_player[p].f_scores[10] << "\n"; //Display the last frames total because that is the total score. } } void Bowling::start() { cout << "Welcome to my bowling program!\n"; MainMenu(); //Open the menu cin >> choice; //Grab the users choice while(choice && choice != 5) //While the choice for exit is not selected, execute switch { switch(choice) //Switch statement to handle the choice. { case 1: //Case 1 is creation of the game. cout << "Game creation in progress\n"; grabBoxScores(n_players); cout << "\nGame has successfully been created!"; break; case 2: //Case 2 is displaying the previous games. displayFrames(n_players); cout << "\nFrame scores have successfully been displayed!"; break; case 3: //Case 3 is displaying the total score for each player. displayTotal(n_players); break; case 4: MainMenu(); //Case 4 is to re-display the menu break; case 5: break; //Case 5 is to exit the program default: cout << "Invalid choice. Please choose again.\n"; //Default option is that the choice is invalid. MainMenu(); break; } cin >> choice; //Grab next command } cout << "Have a great day!\n"; cout << "Good Bye!"; }
true
31e9d436b318de8149dbb28f0ba327a25cbfde0e
C++
dimatrubca/FloorPlanDSL
/FloorPlanDSL/Objects/Door.cpp
UTF-8
1,402
2.796875
3
[]
no_license
#pragma once #include "Door.h" Door::Door(std::map<TokenType, Object*> params, std::vector<Room*> rooms) : DrawableObject(DOOR_OBJ, params) { // TODO: require props String* idParent = dynamic_cast<String*>(params[ID_PARENT_PROP]); Integer* wallNr = dynamic_cast<Integer*>(params[WALL_PROP]); Measure* startOnWall = dynamic_cast<Measure*>(params[START_ON_WAL_PROP]); Measure* length = dynamic_cast<Measure*>(params[LENGTH_PROP]); if (!idParent || !wallNr || !startOnWall || !length) { std::cout << "Invalid Door props"; // throw error } Room* parentRoom = nullptr; for (auto room : rooms) { if (room->id == idParent->value) { parentRoom = room; break; } } if (!parentRoom) { std::cout << "Invalid parent id"; // throw } if (parentRoom->vertices.size() + 1< wallNr->value) { std::cout << "Invalid Wall Number"; } Position wallStart = parentRoom->vertices[wallNr->value]; Position wallEnd = parentRoom->vertices[wallNr->value + 1]; float dX = wallEnd.x - wallStart.x; float dY = wallEnd.y - wallStart.y; auto angle = atan2(dY, dX); this->start = Position(wallStart.x + startOnWall->value * cos(angle), wallStart.y + startOnWall->value * sin(angle)); this->end = Position(wallStart.x + (startOnWall->value + length->value) * cos(angle), wallStart.y + (startOnWall->value + length->value) * sin(angle)); this->width = parentRoom->border->width->value; }
true
c212389d3e98465ca9bea015544e222930d35959
C++
pag4k/KingOfNewYork
/gamecontroller.h
UTF-8
1,791
2.546875
3
[]
no_license
// ---------------------------------------------------------------------------- // COMP345 Assignment 4 // Due date: December 2, 2018 // Written by: Pierre-Andre Gagnon - 40067198 // ---------------------------------------------------------------------------- #ifndef GAMECONTROLLER_H #define GAMECONTROLLER_H #include "precompiledheader.h" #include "playercontroller.h" #include "game.h" namespace KingOfNewYork { class FMap; class FPlayer; class FTileStack; class FGameController { public: FGameController(); FGame &GetGame() { return *Game; } int GetPlayerCount() const; std::vector<std::unique_ptr<FPlayerController>> &GetPlayerControllers() { return PlayerControllers; } std::unique_ptr<FPlayerController> &GetPlayerController(const std::shared_ptr<FPlayer> &Player); void ChangeCelebrity(std::shared_ptr<FPlayer> &NewCelebrityPlayer); void ChangeStatueOfLiberty(std::shared_ptr<FPlayer> &NewStatueOfLibertyPlayer); const bool IsValid() const { return bIsValid; } //Initiatilization void StartupPhase(); void StartMainPhase(); bool DistributeCard(); private: //Initiatilization bool InitializationPhase(); std::unique_ptr<FMap> SelectMap(); bool DistributeTiles(FTileStack &TileStack, FMap &Map); int PromptPlayerCount(); void CreatePlayerControllers(int PlayerCount); void GetFirstPlayer(); void SelectStartingBoroughs(); void MainPhase(); std::optional<std::shared_ptr<FPlayer>> CheckVictoriousPlayer(); std::shared_ptr<FGame> Game; std::vector<std::unique_ptr<FPlayerController>> PlayerControllers; int CurrentPlayer; bool bIsValid; }; } #endif
true
2ec62a2e979d5335b80444a9128a11441ef0c03c
C++
maknoll/cg
/raytracer/Intersection.hpp
UTF-8
4,002
3
3
[]
no_license
#ifndef _INTERSECTION_HPP_INCLUDE_ONCE #define _INTERSECTION_HPP_INCLUDE_ONCE #include "Math.hpp" #include "Ray.hpp" namespace rt { class Intersection { public: /// Computes the intersection of a ray and an infinite plane defined by three vertices static bool linePlane(const Ray& ray, const Vec3 &a, const Vec3 &b, const Vec3 &c, Vec3& uvw, real & lambda) { // Barycentric approach according to lecture slides // Ray: x=o+t*d // Barycentric Triangle: x=a*u+b*v+c*w // Solve: o+t*d = u*a+v*b+w*c // This is an inhomogeneous linear system // (ax bx cx -dx) (u) = ox // (ay by cy -dy) (v) = oy // (az bz cz -dz) (w) = oz // (1 1 1 0 ) (t) = 1 // or in short: A*x = o // Then, solution is given by A^-1 * o = x // with x = (u,v,w,t)^T /* const Vec3& o = ray.origin(); const Vec3& d = ray.direction(); Mat4 A; A(0,0)=a[0];A(0,1)=b[0];A(0,2)=c[0];A(0,3)=-d[0]; A(1,0)=a[1];A(1,1)=b[1];A(1,2)=c[1];A(1,3)=-d[1]; A(2,0)=a[2];A(2,1)=b[2];A(2,2)=c[2];A(2,3)=-d[2]; A(3,0)=1 ;A(3,1)=1 ;A(3,2)=1 ;A(3,3)=0; A.invert(); Vec4 x=A*Vec4(o,1); uvw[0] = x[0]; uvw[1] = x[1]; uvw[2] = x[2]; lambda = x[3]; return true; */ ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// //Approach by Moeller and Trumbore //see Fast, Minimum Storage RayTriangle Intersection // Ray: x=o+t*d // Barycentric Triangle: x=u*a+v*b+w*c // w=1-u-v // Therefore // x=u*a+v*b+(1-u-v)*c // Solve: o+t*d = u*a+v*b+(1-u-v)*c // Rearrange, then // (ax-cx bx-cx -dx) (u) = (ox-dx) // (ay-cy by-cy -dy) (v) = (oy-dy) // (az-cz bz-cz -dz) (t) = (oz-dz) // or in short: A*x = b // Then, solution is given by A^-1 * b = x // with x = (u,v,t)^T // This system can be solved using Cramer's rule // x_i = det(A_i) / det(A) // where the i-th column is replaced with b in the Matrix A_i // // e1 = a-c // e2 = b-c // tt = o-d // then // ( ) (u) // (e1 e2 -d) (v) = tt // ( ) (t) // with // (u) ( det(tt,e2,-d) ) // (v) = 1/det(e1,e2,-d)* ( det(e1,tt,-d) ) // (t) ( det(e1,e2,tt) ) //use triple scalar product // det(a,b,c) = a * (b x c) = b * (c x a) = c*(a x b) , and // a * (b x c) = -a * (c x b) // then // (u) ( tt * (e2 x -d) ) // (v) = e1*(e2 x -d) ( e1 * (tt x -d) ) // (t) ( e1 * (e2 x tt) ) //rearrange terms for u,t // (u) ( tt * (e2 x -d) ) // (v) = e1*(e2 x -d) ( -d * (e1 x tt) ) // (t) (-e2 * (e1 x tt) ) // reuse expensive terms // pp = e2 x -d // qq = e1 x tt // then // (u) ( tt * pp ) // (v) = e1*pp ( -d * qq ) // (t) (-e2 * qq ) const Vec3& o = ray.origin(); const Vec3& d = ray.direction(); Vec3 e1 = a-c; Vec3 e2 = b-c; Vec3 tt = o-c; Vec3 pp = util::cross(e2,-d); Vec3 qq = util::cross(e1,tt); real detA = util::dot(e1,pp); if(fabs(detA) < Math::safetyEps()) return false; uvw[0] = (util::dot( tt,pp))/detA; uvw[1] = (util::dot( -d,qq))/detA; uvw[2] = 1-uvw[0]-uvw[1]; lambda = (util::dot(-e2,qq))/detA; return true; } /// Bounds the intersection to the triangle static bool lineTriangle(const Ray& ray, const Vec3 &a, const Vec3 &b, const Vec3 &c, Vec3& uvw, real & lambda) { if(!linePlane(ray,a,b,c,uvw,lambda)) return false; if(uvw[0]<0 || uvw[0]>1 || uvw[1]<0 || uvw[1]>1 || uvw[2]<0 || uvw[2]>1) return false; return true; } }; }//namespace rt #endif // _INTERSECTION_HPP_INCLUDE_ONCE
true
564c2e254608acc248bb57a4f21fe94b03ddbcb6
C++
windfornight/mengguOpenGL
/01_基本入门/快速入门/资源代码/particle.cpp
UTF-8
1,459
2.78125
3
[]
no_license
#include "particle.h" #include "utils.h" Particle::Particle() { mLifeTime = -1; } void Particle::Draw() { glEnable(GL_BLEND); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glDisable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, mTexture); glDisable(GL_LIGHTING); glColor4ubv(mColor); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex3f(mPosition.x - mHalfSize, mPosition.y - mHalfSize, 0.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(mPosition.x + mHalfSize, mPosition.y - mHalfSize, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(mPosition.x + mHalfSize, mPosition.y + mHalfSize, 0.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(mPosition.x - mHalfSize, mPosition.y + mHalfSize, 0.0f); glEnd(); glDisable(GL_BLEND); } void Particle::Init(GLubyte r, GLubyte g, GLubyte b, GLubyte a, float life) { mLivingTime = 0.0f; mLifeTime = life; mColor[0] = r; mColor[1] = g; mColor[2] = b; mColor[3] = a; } void Particle::Update(float deltaTime) { if (mLivingTime > mLifeTime) { return; } mLivingTime += deltaTime; float maxRadius = 300.0f; float rotateSpeed = 360.0f; float currentAngle = rotateSpeed * mLivingTime; float currentRadius = maxRadius * mLivingTime / mLifeTime; mPosition.x = currentRadius * cosf(currentAngle * 3.14 / 180.0f); mPosition.y = currentRadius * sinf(currentAngle * 3.14 / 180.0f); }
true
606967e708f93059e3e714e6b26fd8ff4b52fd9a
C++
mag619/StackADT_MG_MH
/Node.h
UTF-8
1,133
3.5625
4
[]
no_license
/** @file Node.h */ #ifndef _NODE #define _NODE template <class ItemType> class Node { private: ItemType item; // A data item Node<ItemType>* next; // Pointer to next node Node<ItemType>* prev; // Pointer to prev node public: //@post: sets next to NULL Node(); Node(const ItemType& anItem); //@pre: anItem is a data type; nextNodePtr is a pointer //@post: Creates a new Node with ItemType anItem and a head pointer pointing to *nextNodePtr Node(const ItemType& anItem, Node<ItemType>* nextNodePtr); //@pre: anItem is an object or data type //@post: sets node with data item of anItem type void setItem(const ItemType& anItem); //@pre: nextNodePtr is a pointer //@post: sets head ptr of Node to nextNodePtr void setNext(Node<ItemType>* nextNodePtr); //@pre: prevNodePtr is a pointer //@post: set tail pointer of Node to prevNodePtr void setPrev(Node<ItemType>* prevNodePtr); //@post: returns item of Node ItemType getItem() const; //@post: returns next Node Node<ItemType>* getNext() const; //@post: returns previous Node Node<ItemType>* getPrev() const; } ; // end Node #endif //_NODE_H__
true
61d3a9d11fb9dab762403ff4d72897e26bb00a47
C++
csg-tokyo/caldwell
/SyntheticProgramPair/SensorMonitorOO/src/Field.cpp
UTF-8
1,173
2.984375
3
[]
no_license
/* * Field.cpp * * Created on: Mar 27, 2017 * Author: Joe */ #include "Field.h" #include "Display.h" #include "utility.h" Field::Field(String const& name, FieldType type, uint16_t address, uint8_t length): m_name (name), m_type (type), m_address(address), m_length (length) { } void Field::update(uint8_t* data) { for (int i = 0; i < this->m_length; ++i) { this->m_buffer[i] = data[i]; } } String Field::toString() const { switch (this->m_type) { case FieldType::INTEGER: { int32_t data = ConvertToLittleEndian(*((int32_t*)this->m_buffer)); return ConvertIntegerToString(data); } case FieldType::STRING: { return String((char const*) m_buffer); } case FieldType::BOOL: { return ConvertBoolToString(m_buffer[0] != 0); } case FieldType::YES_NO: { return ConvertBoolToString(m_buffer[0] != 0, "yes", "no"); } case FieldType::ON_OFF: { return ConvertBoolToString(m_buffer[0] != 0, "on", "off"); } default: { return String(""); } } }
true
42ec91bf0e020b31aaf47f2df76ddfea7949484f
C++
zhyh329/JPEG_Deblocking
/JPEG/src/PSNR.cpp
UTF-8
3,414
3.125
3
[ "MIT" ]
permissive
/* * PSNR.cpp * * Created on: Feb 27, 2014 * Author: jigar */ #include <iostream> using namespace std; #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include "FileIO/fileIO.h" #include "definition.h" unsigned char* fileRead(char filename[], int fullsize); float getPSNR(unsigned char* im1, unsigned char* im2, int size); int main(int argc,char *argv[]){ char originalFile[NAME_MAXIMUM]; char fileNameAfterProcessing[NAME_MAXIMUM]; char option; char *programname = *argv; /* if no options entered, list all of the defaults */ if (argc == 1) { printf("%s\n",USAGE); printf("\nOPTIONS DESCRIPTIONS DEFAULTS\n"); printf("-i Input file \n"); printf("-o quantized file \n"); printf("\n"); printf("Both options are compulsory. \n"); fflush(stdout); exit(0); } /* read and interpret command line arguments */ while (--argc && ++argv) { if (*argv[0] == '-' && strlen(*argv) == 2) { /* each option has 1 letter */ option = *++argv[0]; if (--argc && ++argv) { /* examine the option */ switch (option) { /* examine the option letter */ case 'i': strncpy(originalFile, *argv, NAME_MAXIMUM); break; case 'o': strncpy(fileNameAfterProcessing, *argv, NAME_MAXIMUM); break; default: fprintf(stderr, "%s: %c: %s\n", programname, option, NOTOPTION); exit(1); break; } } else { fprintf(stderr, "%s %s %s\n", USAGE, programname,HOWTOUSE_PSNR); exit(2); } } else if (*argv[0] == '-') { /* user entered unknown option */ ++argv[0]; fprintf(stderr, "%s: %s: %s\n", programname, *argv, NOTOPTION); exit(3); } else { /* user entered unknown string */ fprintf(stderr, "%s: %s: %s\n", programname, *argv, NOTOPTION); exit(4); } } // char originalFile[] = "resources/couple.256"; // char fileNameAfterProcessing[] = "resources/couple_5bitquantizedOutput.dat"; int fullsize = getFileSize(originalFile); //Read the 2 files unsigned char* im1 = fileRead(originalFile,fullsize); unsigned char* im2 = fileRead(fileNameAfterProcessing,fullsize); //Get the PSNR float PSNR = getPSNR(im1,im2,fullsize); cout << "PSNR is : " << PSNR << endl; } /** * This function computed the PSNR given two data files: * File1: Original File * File2: File after Processing */ float getPSNR(unsigned char* im1, unsigned char* im2, int size){ float PSNR, MSE = 0; int max = 0; for(int i = 0; i < size; i++){ //Compute the Max Value if(im1[i] > max) max = im1[i]; //Compute the MSE MSE += pow((im2[i] - im1[i]),2); } MSE /= size; cout << "MSE is : " << MSE << endl; cout << "MAX value in image is : " << max << endl; PSNR = 10*log10f(max*max/MSE); return PSNR; } /** * This function reads the file and stores it in 1-D unsigned char array */ unsigned char* fileRead(char filename[], int fullsize){ FILE *file; // image data array. Assigning memory unsigned char* imgArray = new unsigned char[fullsize]; // read image "ride.raw" into image data matrix if (!(file = fopen(filename, "rb"))) { cout << "Cannot open file: " << filename << endl; exit(1); } fread(imgArray, sizeof(unsigned char), fullsize, file); fclose (file); return imgArray; }
true