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
6a6105c15080957eaf42e656b9f574e8072fbf39
C++
droneboost/scratch_rover
/driver/src/ds1339.cpp
UTF-8
5,098
3.078125
3
[]
no_license
/* DS1339 driver. */ #include <stdio.h> #include <unistd.h> #include "ds1339.h" using namespace BH; const char *DS1339::week_days[] = {"Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds"}; DS1339::DS1339(uint8_t device_address) : dev_address(device_address) { } DS1339::~DS1339() { } bool DS1339::init() { return true; } bool DS1339::setTime(RtcTime& time, bool start, bool thm) { uint8_t buffer[7]; printf("reading clock registers to write the new time : %d:%d:%d\n", time.hour, time.min, time.sec); if (!read(0, buffer, 7)) { printf("Failed to read from RTC\n"); return false; } // Now update only the time part (saving the existing flags) if (start) { buffer[0] &= 0x7F; } else { buffer[0] |= 0x80; } buffer[0] = (buffer[0]&0x80) | (decimalToBcd(time.sec)& 0x7f); buffer[1] = decimalToBcd(time.min); if (thm) { // AM PM format buffer[2] = (buffer[2]& 196) | (time.hour>12 ? (0x20 | ((decimalToBcd(time.hour-12)))) : decimalToBcd(time.hour)); } else { // 24 hours format buffer[2] = (buffer[2]& 196) | (decimalToBcd(time.hour) & 0x3F); } buffer[3] = time.wday; buffer[4] = decimalToBcd(time.date); buffer[5] = decimalToBcd(time.mon); buffer[6] = decimalToBcd(time.year-2000); printf("Writing new time and date data to RTC\n"); if (!write(0, buffer, 7) ) { printf("Failed to write the data to RTC!\n"); return false; } return true; } void DS1339::printfTime(RtcTime& time) { printf("current time is : year=%d, mon=%d, date=%d, wday=%d, hour=%d, min=%d, sec=%d\n", time.year, time.mon, time.date, time.wday, time.hour, time.min, time.sec); } bool DS1339::getTime(RtcTime& time) { uint8_t buffer[7]; bool thm = false; printf("Getting time from RTC\n"); if (!read(0, buffer, 7) ) { // Failed to read printf("Failed to read from RTC\n"); return false; } thm = ((buffer[2] & 64) == 64); time.sec = bcdToDecimal(buffer[0]&0x7F); time.min = bcdToDecimal(buffer[1]); if (thm) { // in 12-hour-mode, we need to add 12 hours if PM bit is set time.hour = DS1339::bcdToDecimal( buffer[2] & 31 ); if ((buffer[2] & 32) == 32) time.hour += 12; } else { time.hour = DS1339::bcdToDecimal( buffer[2] & 63 ); } time.wday = buffer[3]; time.date = DS1339::bcdToDecimal( buffer[4]); time.mon = DS1339::bcdToDecimal( buffer[5]); time.year = DS1339::bcdToDecimal(buffer[6]) + 2000; // plus hundret is because RTC is giving the years since 2000, but std c struct tm needs years since 1900 return true; } bool DS1339::startClock() { uint8_t strtStop = 0; printf ("Reading clock start/stop register value\n"); if (!read(0XE0, &strtStop, 1)) { printf("Failed to read clock start stop register !\n"); return false; } printf("current start/stop register value = %d\n", strtStop); strtStop &= 0x7F; printf("Writing back start/stop register value\n"); if (!write(0xE0, &strtStop, 1)) { printf("Faied to write the start stop register !\n"); return false; } printf("Start/stop register value successfully written\n"); return true; } bool DS1339::stopClock() { uint8_t strtStop; printf ("Reading clock start/stop register value\n"); if (!read(0, &strtStop, 1)) { printf("Failed to read clock start stop register !\n"); return false; } strtStop |= 0x80; printf("Writing back start/stop register value\n"); if (!write(0, &strtStop, 1)) { printf("Failed to write the start stop register !\n"); return false; } printf("Start/stop register value successfully written\n"); return true; } bool DS1339::setSquareWaveOutput(bool ena, SqwRateSelect rs) { uint8_t reg; printf("Reading register value first\n"); if (!read(7,&reg, 1)) { printf("Failed to read register value !\n"); return false; } printf("[Reg:0x07] = %02x\n", reg); // preserve the OUT control bit while writing the frequency and enable bits reg = (reg & 0x80) | (ena ? 0x10 : 0) | ((uint8_t)rs & 0x03); printf("Writing back register value\n"); printf("[Reg:0x07] = %02x\n", reg); if (!write(7, &reg, 1)) { printf("Failed to write register value !\n"); return false; } printf("Successfully changed the square wave output.\n"); return true; } bool DS1339::read(uint8_t address, uint8_t *buffer, int len) { if (IIC::readBytes(RPI2_I2C_1, dev_address, address, len, buffer) == 0) { printf("Failed to read register !\n"); return false; } printf("Successfully read %d registers from RTC\n", len); return true; } bool DS1339::write(uint8_t address, uint8_t *buffer, int len) { if (IIC::writeBytes(RPI2_I2C_1, dev_address, address, len, buffer) == 0) { printf("Failed to write data to rtc\n"); return false; } return true; }
true
f0adec62cee36b1c16166687967d3a9aca62f19c
C++
JerryZhou/Raccoon
/framework/src/app/kernel/dwinterlocked.h
UTF-8
1,653
2.71875
3
[]
no_license
#pragma once #include <intrin.h> class DW_APP_EXPORT DwInterlocked { public: /// interlocked increment, return result static int increment(int volatile& var); /// interlocked decrement, return result static int decrement(int volatile& var); /// interlocked add static int add(int volatile& var, int a); /// interlocked exchange static int exchange(int volatile* dest, int value); /// interlocked compare-exchange static int compareExchange(int volatile* dest, int e, int comparand); }; //------------------------------------------------------------------------------ /** */ __forceinline int DwInterlocked::increment(int volatile& var) { return _InterlockedIncrement((volatile LONG*)&var); } //------------------------------------------------------------------------------ /** */ __forceinline int DwInterlocked::decrement(int volatile& var) { return _InterlockedDecrement((volatile LONG*)&var); } //------------------------------------------------------------------------------ /** */ __forceinline int DwInterlocked::add(int volatile& var, int a) { return _InterlockedExchangeAdd((volatile LONG*)&var, a); } //------------------------------------------------------------------------------ /** */ __forceinline int DwInterlocked::exchange(int volatile* dest, int value) { return _InterlockedExchange((volatile LONG*)dest, value); } //------------------------------------------------------------------------------ /** */ __forceinline int DwInterlocked::compareExchange(int volatile* dest, int e, int comparand) { return _InterlockedCompareExchange((volatile LONG*)dest, e, comparand); }
true
9d09d2e1c4869b4a8d79b6d7ea61aefbaed7d062
C++
William-f-12/heima-CPP-2021-8-7
/29 C++常用查找算法/count_if.cpp
GB18030
527
3.5625
4
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; // - count_if(ʼν) class GreaterFive { public: bool operator()(int val) { return val > 5; } }; void test06() { vector<int> v; for (int i = 0; i < 10; i++) { v.push_back(i); } int num = count_if(v.begin(), v.end(), GreaterFive()); cout << "5ĸΪ" << num << endl; //Զ Ҫν } int main() { test06(); system("pause"); return 0; }
true
54f9f1e19665a137e8268090a42bc5096a321fdc
C++
HayimShaul/HElib_MatrixOperations
/Matrices.cpp
UTF-8
29,478
3.265625
3
[]
no_license
#include "Matrices.h" ostringstream MatricesSizesNotMatch::cnvt; /* ----- some helping functions ------ */ long myModulu(long num, long mod) //the regular modulo operator on minus numbers make trouble when trying to calculate enteries in the diagonal matrices. //for example, -7%3=-1, but I want it to be 2 (-7+3=-4, -4+3=-1, -1+3= 2) { //adding "mod" to "num" until it positive while(num<0) num+=mod; return num%mod; } unsigned int numDigit(long num){ return (num/10)==0 ? 1:numDigit(num/10)+1; } //How much digits in the input number. Uses for a "nice" printing unsigned int largestNumInMatrixDigits(vector<vector<long> > matrix) //Find the longest number in a matrix and returns it length (in digits). Uses for a "nice" printing { int largest = 0; long temp; for(unsigned int i=0; i < matrix.size(); i++) for(unsigned int j=0; j<matrix[i].size(); j++) if((temp = numDigit(matrix[i][j])) > largest) largest = temp; return largest; } void printNum(long num, int size){ int len = numDigit(num); cout << num; for(int i=len; i < size; i++) cout << " "; } Ctxt getNotVector(const EncryptedArray& ea, const FHEPubKey& publicKey){ vector<long> not_vec(ea.size(), 1); //vectors of 1, uses for NOT Ctxt not_ctxt(publicKey); ea.encrypt(not_ctxt, publicKey, not_vec); return not_ctxt; } /* --------------------- MatSize (matrices size operations) class --------------------*/ MatSize::MatSize(unsigned int first, unsigned int second): rows(first), columns(second) {} //MatSize::MatSize(unsigned int sz): rows(sz), columns(sz) {} MatSize MatSize::operator*(const MatSize& other) const{ if(!canMultiply(other)){ cout << "Sizes not accepted! first: ("<<rows<<"x"<<columns<<"), second: ("<<other.rows<<"x"<<other.columns<<"). return empty MatSize (0x0)" << endl; return MatSize(); } return MatSize(rows, other.columns); } MatSize MatSize::transpose() { return ((*this) = MatSize(this->columns, this->rows)); } MatSize MatSize::getTransposed() const { return MatSize(this->columns, this->rows); } MatSize MatSize::operator*=(const MatSize& other) { return ((*this) = (*this)*other); } bool MatSize::operator==(const MatSize& other) const { return (rows == other.rows && columns == other.columns); } bool MatSize::operator!=(const MatSize& other) const { return !(*this==other); } bool MatSize::canMultiply(const MatSize& other) const { return columns == other.rows; } bool MatSize::canAdd(const MatSize& other) const { return *(this) == other; } void MatSize::print() const { cout << "Rows: " << rows << ", Columns: " << columns << endl; } unsigned int MatSize::size() const { return rows*columns; } bool MatSize::isSquare() const { return rows==columns; } /* --------------------- PTMatrix (Plain Text Matrix) class --------------------------*/ PTMatrix::PTMatrix(vector<vector<long> > _matrix, bool diagonal) { if(diagonal) matrix = _matrix; else{ //transform from regular (rows order) representation to diagonal matrix = vector<vector<long> >(_matrix[0].size(), vector<long>(_matrix.size(),0)); for(unsigned int i=0, sz1 = matrix.size(); i < sz1; i++) for(unsigned int j=0, sz2 = matrix[i].size(); j < sz2; j++) matrix[i][j] = _matrix[j][(i+j)%sz1]; } } PTMatrix::PTMatrix(MatSize sizes, unsigned int numbersLimit) /*this constructor create a random matrix params: sizes: - the size of the matrix numbersLimit = the values limit, that means that all the values in the matrix would be between 0 to numbersLimit (not included), default : 10 */ { matrix = vector<vector<long> >(sizes.columns, vector<long>(sizes.rows)); for(unsigned int i=0; i < matrix.size(); i++) for(unsigned int j=0; j< matrix[i].size(); j++) matrix[i][j] = rand() % numbersLimit; } PTMatrix::PTMatrix(ifstream& file) /*read a matrix from a file the file format should be num_of_rows num_of_columns the matrix for example: 2 3 5 3 7 1 4 6 */ { string line, temp; int rows, cols; if (file.is_open()) { getline(file, line); //get number of rows temp = line.substr(0, line.find(' ')); rows = stoi(temp); temp = line.substr(line.find(' ')+1); cols = stoi(temp); matrix = vector<vector<long> >(cols, vector<long>(rows,0)); for(int i=0; i < rows; i++) { getline(file,line); for(int j=0; j < cols; j++){ temp = line.substr(0, line.find(' ')); matrix[myModulu(j-i,matrix.size())][i] = stoi(temp); line = line.substr(line.find(' ')+1); } } file.close(); } else cout << "Unable to open file"; } bool PTMatrix::save(ofstream& file) const{ if (file.is_open()) { unsigned int rows = getRows(), cols = getColumns(); file << rows << " " << cols << "\n"; for(unsigned int i=0; i < rows; i++){ for(unsigned int j=0; j < cols; j++) file << (*this)(i,j) << " "; file << "\n"; } file.close(); } else{ cout << "Unable to open file"; return false; } return true; } vector<vector<long> > PTMatrix::getMatrix() const{ unsigned int rows = getRows(), cols = getColumns(); vector<vector<long> > ret(rows, vector<long>(cols,0)); for(unsigned int i=0; i < rows ; i++) for(unsigned int j=0; j < cols; j++) ret[i][j] = (*this)(i,j); return ret; } EncryptedMatrix PTMatrix::encrypt(const EncryptedArray& ea, const FHEPubKey& publicKey) const{ vector<Ctxt> encMat(size(), Ctxt(publicKey)); unsigned int nslots = ea.size(); for(unsigned int i=0; i< size(); i++){ vector<long> temp = matrix[i]; temp.resize(nslots,0); ea.encrypt(encMat[i], publicKey, temp); } return EncryptedMatrix(encMat, MatSize(getRows(), getColumns())); } EncryptedMatrix PTMatrix::encrypt(const FHEPubKey& publicKey) const{ EncryptedArray ea(publicKey.getContext()); return encrypt(ea, publicKey); } long& PTMatrix::operator()(unsigned int row, unsigned int column){ if(row >= getRows() || column >= getColumns()) { cout << "Error, indices out of bound! MatSize: " << getRows() << "*" << getColumns() <<", indices: " << row << "*" << column << endl; throw out_of_range("Error, indices out of bound!"); } int i = row, j = column; //casting to int so the subtraction be ok return matrix[myModulu(j-i,matrix.size())][row]; } const long& PTMatrix::operator()(unsigned int row, unsigned int column) const{ if(row >= getRows() || column >= getColumns()) { cout << "Error, indices out of bound! MatSize: " << getRows() << "*" << getColumns() <<", indices: " << row << "*" << column << endl; throw out_of_range("Error, indices out of bound!"); } int i = row, j = column; //casting to int so the subtraction be ok return matrix[myModulu(j-i,matrix.size())][row]; } unsigned int PTMatrix::getRows() const { return matrix[0].size(); } unsigned int PTMatrix::getColumns() const { return matrix.size(); } void PTMatrix::print(string label) const{ if(label.compare("")!=0) cout << label << endl; unsigned int primarySize = getRows(); unsigned int secondarySize = getColumns(); unsigned int cellSize = largestNumInMatrixDigits(matrix)+1; //+1 for space cout << " "; for(unsigned int i=0; i< secondarySize*cellSize; i++) cout << "-"; cout << endl; for(unsigned int i=0; i< primarySize; i++) { cout << "|"; for(unsigned int j=0; j< secondarySize; j++) printNum((*this)(i,j), cellSize); cout << "|" << endl; } cout << " "; for(unsigned int i=0; i< secondarySize*cellSize; i++) cout << "-"; cout << endl; } PTMatrix PTMatrix::getSubMatrix(unsigned int i, unsigned int j, MatSize blockSize) const{ unsigned int numRows = blockSize.rows, numCols = blockSize.columns; if(getRows() < i + numRows) numRows = getRows()-i; if(getColumns() < j + numCols) numCols = getColumns()-j; vector<vector<long> > result(numRows, vector<long>(numCols,0)); for(unsigned int x=0; x < numRows; x++) for(unsigned int y=0; y < numCols; y++) result[x][y] = (*this)(i+x,j+y); return PTMatrix(result, false); } vector<long>& PTMatrix::operator[](unsigned int i) { return matrix[i]; } const vector<long>& PTMatrix::operator[](unsigned int i) const { return matrix[i]; } unsigned int PTMatrix::size() const { return matrix.size(); } MatSize PTMatrix::getMatrixSize() const { return MatSize(getRows(), getColumns()); } //operators PTMatrix PTMatrix::operator*(const PTMatrix& other) const{ //check sizes if(getColumns() != other.getRows()) throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize()); vector<vector<long> > res(getRows(), vector<long>(other.getColumns(),0)); for(unsigned int i=0; i < res.size(); i++) for(unsigned int j=0; j < res[i].size(); j++) for(unsigned int k = 0; k < other.getRows(); k++) res[i][j] += (*this)(i,k)*other(k,j); return PTMatrix(res, false); } PTMatrix PTMatrix::operator*=(const PTMatrix& other){ return (*this) = (*this)*other; } //mult by constant PTMatrix PTMatrix::operator*(unsigned int num) const { PTMatrix copy = *this; for(unsigned int i=0, sz1 = matrix.size(); i < sz1; i++) for(unsigned int j=0, sz2 = matrix[i].size(); j < sz2; j++) copy[i][j] *= num; return copy; } PTMatrix PTMatrix::operator*=(unsigned int num) { return ((*this) = (*this)*num); } PTMatrix PTMatrix::operator+(const PTMatrix& other) const{ //check sizes if(matrix.size() != other.matrix.size() || matrix[0].size() != other.matrix[0].size()) throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize()); unsigned int rows = getRows(), cols = getColumns(); vector<vector<long> > res = matrix; for(unsigned int i=0; i < rows; i++) for(unsigned int j=0; j < cols; j++) res[j][i] += other[j][i]; return PTMatrix(res, true); } PTMatrix PTMatrix::operator+=(const PTMatrix& other){ return (*this) = (*this)+other; } PTMatrix PTMatrix::operator-(const PTMatrix& other) const{ //check sizes if(matrix.size() != other.matrix.size() || matrix[0].size() != other.matrix[0].size()) throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize()); unsigned int rows = getRows(), cols = getColumns(); vector<vector<long> > res = matrix; for(unsigned int i=0; i < rows; i++) for(unsigned int j=0; j < cols; j++) res[j][i] -= other[j][i]; return PTMatrix(res, true); } PTMatrix PTMatrix::operator-=(const PTMatrix& other){ return (*this) = (*this)-other; } PTMatrix PTMatrix::transpose() const{ MatSize transposedSize = this->getMatrixSize().getTransposed(); vector<vector<long>> transposedMatrix(transposedSize.rows, vector<long>(transposedSize.columns, 0)); for(int i = 0; i < transposedSize.rows; i++) for(int j = 0; j < transposedSize.columns; j++) transposedMatrix[i][j] = (*this)(j,i); return PTMatrix(transposedMatrix, false); } PTMatrix PTMatrix::operator>(const PTMatrix& other) const { //check sizes if(matrix.size() != other.size() || matrix[0].size() != other[0].size()) throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize()); unsigned sz1 = matrix[0].size(), sz2 = matrix.size(); vector<vector<long> > res(sz1, vector<long>(sz2)); for(unsigned int i=0; i < sz1; i++) for(unsigned int j=0; j < sz2; j++) res[j][i] = matrix[j][i] > other[j][i]; return PTMatrix(res, true); } PTMatrix PTMatrix::operator<(const PTMatrix& other) const { //check sizes if(matrix.size() != other.size() || matrix[0].size() != other[0].size()) throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize()); unsigned sz1 = matrix[0].size(), sz2 = matrix.size(); vector<vector<long> > res(sz1, vector<long>(sz2)); for(unsigned int i=0; i < sz1; i++) for(unsigned int j=0; j < sz2; j++) res[j][i] = matrix[j][i] < other[j][i]; return PTMatrix(res, true); } PTMatrix PTMatrix::operator>=(const PTMatrix& other) const { //check sizes if(matrix.size() != other.size() || matrix[0].size() != other[0].size()) throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize()); unsigned sz1 = matrix[0].size(), sz2 = matrix.size(); vector<vector<long> > res(sz1, vector<long>(sz2)); for(unsigned int i=0; i < sz1; i++) for(unsigned int j=0; j < sz2; j++) res[j][i] = matrix[j][i] >= other[j][i]; return PTMatrix(res, true); } PTMatrix PTMatrix::operator<=(const PTMatrix& other) const { //check sizes if(matrix.size() != other.size() || matrix[0].size() != other[0].size()) throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize()); unsigned sz1 = matrix[0].size(), sz2 = matrix.size(); vector<vector<long> > res(sz1, vector<long>(sz2)); for(unsigned int i=0; i < sz1; i++) for(unsigned int j=0; j < sz2; j++) res[j][i] = matrix[j][i] <= other[j][i]; return PTMatrix(res, true); } bool PTMatrix::operator==(const PTMatrix& other) const{ if(matrix.size() != other.size() || matrix[0].size() != other[0].size()) return false; for(unsigned int i=0, sz1 = getRows() ; i < sz1; i++) for(unsigned int j=0, sz2 = getColumns(); j < sz2; j++) if((*this)(i,j) != other(i,j)) return false; return true; } bool PTMatrix::operator!=(const PTMatrix& other) const { return !(*this == other); } PTMatrix PTMatrix::operator%(unsigned int p) const{ vector<vector<long> > res = matrix; for(unsigned int i=0; i< size(); i++) for(unsigned int j=0; j < matrix[i].size(); j++) res[i][j] %= p; return PTMatrix(res, true); } PTMatrix PTMatrix::operator%=(unsigned int p) { return (*this) = (*this)%p; } PTMatrix PTMatrix::mulWithMod(const PTMatrix& other, long p) const { //check sizes if(getColumns() != other.getRows()) throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize()); vector<vector<long> > res(getRows(), vector<long>(other.getColumns(),0)); for(unsigned int i=0; i < res.size(); i++) for(unsigned int j=0; j < res[i].size(); j++) for(unsigned int k = 0; k < other.getRows(); k++){ res[i][j] += (*this)(i,k)*other(k,j); res[i][j] %= p; } return PTMatrix(res, false); } void PTMatrix::debugPrintDiagonalMatrixVector(){ for(int i = 0; i < this->size(); i++) { vector<long> vec = this->matrix[i]; cout << "vec #" << i << ": ["; for(int j=0; j < vec.size(); j++) cout << vec[j] << " "; cout << "]" << endl; } } /* --------------------- EncryptedMatrix class -------------*/ EncryptedMatrix::EncryptedMatrix(const vector<Ctxt>& encMatrix, const MatSize& origSize): matrix(encMatrix), matrixSize(origSize) {} PTMatrix EncryptedMatrix::decrypt(const EncryptedArray& ea, const FHESecKey& secretKey) const { vector<vector<long> > ret(matrix.size()); for(unsigned int i=0; i < matrix.size(); i++){ ea.decrypt(matrix[i], secretKey, ret[i]); ret[i].resize(matrixSize.rows, 0); } return PTMatrix(ret, true); } PTMatrix EncryptedMatrix::decrypt(const FHESecKey& secretKey) const { EncryptedArray ea(secretKey.getContext()); return decrypt(ea, secretKey); } //matrix multyplcation! EncryptedMatrix EncryptedMatrix::operator*(const EncryptedMatrix& other) const { //check sizes if(!matrixSize.canMultiply(other.matrixSize)) throw MatricesSizesNotMatch(matrixSize, other.matrixSize); Ctxt vec = matrix[0]; //save it for faster vec.getPubKey() in the loop EncryptedArray ea(vec.getContext()); bool squares = getMatrixSize().isSquare() && other.getMatrixSize().isSquare() && getRows()==ea.size(); //Use the square matrices formula (much faster) vector<Ctxt> res; int n = getRows(), m = getColumns(), k = other.getColumns(); //sizes: A(this):n*m, B(other):m*k for(int i=0; i < k; i++){ Ctxt C(vec.getPubKey()); for(int j=0; j< m; j++){ //work by my formula: C_i = Sig j= 0 to n-1 [ A_i * (B_i-j%n <<< j) ] Ctxt B = other[myModulu(i-j,k)]; //B_i-j%n if(squares) ea.rotate(B, -j); //rotate j left, B_i-j%n <<< j (or -j right) else{ //The general formula ea.shift(B, -j); //shift j left int length = m-j; for(int itter=1;length < n; itter++){ Ctxt toChain = other[myModulu(i-j+(itter*m),k)]; ea.shift(toChain, length); //shift length to right B += toChain; length+=m; } } B *= matrix[j]; //* A_j C += B; } res.push_back(C); } return EncryptedMatrix(res, matrixSize*other.matrixSize); } EncryptedMatrix EncryptedMatrix::operator*=(const EncryptedMatrix& other){ return ((*this) = (*this)*other); } //mult by constant EncryptedMatrix EncryptedMatrix::operator*(unsigned int num) const { if(num == 1) return *this; if(num == 0) //return 0's matrix in the same size return EncryptedMatrix(vector<Ctxt>(matrix.size(), Ctxt(matrix[0].getPubKey())), getMatrixSize()); EncryptedMatrix res = *this; for(unsigned int i=0, sz = matrix.size(); i < sz; i++) res[i].multByConstant(to_ZZX(num)); return res; } EncryptedMatrix EncryptedMatrix::operator*=(unsigned int num) { return ((*this) = (*this)*num); } //matrices addition EncryptedMatrix EncryptedMatrix::operator+(const EncryptedMatrix& other) const{ if(!matrixSize.canAdd(other.getMatrixSize())) throw MatricesSizesNotMatch(matrixSize, other.matrixSize); vector<Ctxt> ret = matrix; for(unsigned int i=0, len = matrix.size(); i < len; i++) ret[i] += other[i]; return EncryptedMatrix(ret, matrixSize); } EncryptedMatrix EncryptedMatrix::operator+=(const EncryptedMatrix& other){ return ((*this) = (*this)+other); } EncryptedMatrix EncryptedMatrix::operator-(const EncryptedMatrix& other) const{ if(!matrixSize.canAdd(other.matrixSize)) throw MatricesSizesNotMatch(matrixSize, other.matrixSize); vector<Ctxt> ret = matrix; for(unsigned int i=0, len = matrix.size(); i < len; i++) ret[i] -= other.matrix[i]; return EncryptedMatrix(ret, matrixSize); } /* * Square Formula : B_i = A_(-i mod n) <<< i * NonSquare Formula : TODO: formile the formula */ EncryptedMatrix EncryptedMatrix::transpose() const{ EncryptedArray ea(matrix[0].getContext()); const int fullSize = (int)ea.size(); int gap = fullSize - (int)this->matrixSize.rows; bool isSquare = this->matrixSize.isSquare(); vector<Ctxt> result; for(int i = 0; i < this->matrixSize.rows; i++){ Ctxt b_i(this->matrix[myModulu(-i,this->matrixSize.columns)]); if(isSquare){ if(gap){ Ctxt rightPart(b_i); ea.shift(b_i, -i); ea.shift(rightPart, fullSize - i); ea.shift(rightPart, -gap); b_i += rightPart; } else{ ea.rotate(b_i, -i); //rotate i left } } else{ ea.shift(b_i, -i); //shift i left int countItems = this->matrixSize.rows - i; for(int j = 1 ; countItems < this->matrixSize.columns; j++){ //Probably one of these parameters wrong Ctxt addition(this->matrix[myModulu(-i + j*this->matrixSize.rows,this->matrixSize.columns)]); ea.shift(addition, countItems); //shift countItems right b_i += addition; countItems += this->matrixSize.rows; } } result.push_back(b_i); } return EncryptedMatrix(result, this->matrixSize.getTransposed()); } //comparison operator (>, <, >= and <=) /*NOTE: WORKING ONLY FOR BINARY FIELD (p=2) Concept: For any 2 binary encrypted vectors A and B, A[i] > B[i] for any i iff A[i] = 1 and B[i] =0 The operators in binary fields are: operator* === AND operator+ === XOR + 1 === NOT */ EncryptedMatrix EncryptedMatrix::operator>(const EncryptedMatrix& other) const //A[i] > B[i] ==> A[i] == 1 && B[i] == 0 ==> A[i] & !B[i] ===> A*(B+1) { if(!matrixSize.canAdd(other.matrixSize)) //check sizes throw MatricesSizesNotMatch(matrixSize, other.matrixSize); Ctxt vec = matrix[0]; //save it for faster vec.getPubKey() in the loop if(vec.getPtxtSpace()!= 2) //check that the computations is on binary field throw NotBinaryField(); EncryptedArray ea(vec.getContext()); Ctxt not_ctxt = getNotVector(ea, vec.getPubKey()); vector<Ctxt> res = other.matrix; for(unsigned int i=0, sz = res.size(); i < sz; i++){ res[i] += not_ctxt; res[i] *= matrix[i]; } return EncryptedMatrix(res, matrixSize); } EncryptedMatrix EncryptedMatrix::operator<(const EncryptedMatrix& other) const //A[i] < B[i] ==> A[i] == 0 && B[i] == 1 ==> !A[i] & B[i] ===> (A+1)*B { if(!matrixSize.canAdd(other.matrixSize)) //check sizes throw MatricesSizesNotMatch(matrixSize, other.matrixSize); Ctxt vec = matrix[0]; //save it for faster vec.getPubKey() in the loop if(vec.getPtxtSpace()!= 2) //check that the computations is on binary field throw NotBinaryField(); EncryptedArray ea(vec.getContext()); Ctxt not_ctxt = getNotVector(ea, vec.getPubKey()); vector<Ctxt> res = matrix; for(unsigned int i=0, sz = res.size(); i < sz; i++){ res[i] += not_ctxt; res[i] *= other[i]; } return EncryptedMatrix(res, matrixSize); } EncryptedMatrix EncryptedMatrix::operator>=(const EncryptedMatrix& other) const //A[i] >= B[i] ==> !(A[i] < B[i]) => !(!A[i] & B[i]) ===> ((A+1)*B)+1 { if(!matrixSize.canAdd(other.matrixSize)) //check sizes throw MatricesSizesNotMatch(matrixSize, other.matrixSize); Ctxt vec = matrix[0]; //save it for faster vec.getPubKey() in the loop if(vec.getPtxtSpace()!= 2) //check that the computations is on binary field throw NotBinaryField(); EncryptedArray ea(vec.getContext()); Ctxt not_ctxt = getNotVector(ea, vec.getPubKey()); vector<Ctxt> res = matrix; for(unsigned int i=0, sz = res.size(); i < sz; i++){ res[i] += not_ctxt; res[i] *= other[i]; res[i] += not_ctxt; } return EncryptedMatrix(res, matrixSize); } EncryptedMatrix EncryptedMatrix::operator<=(const EncryptedMatrix& other) const //A[i] <= B[i] ==> !(A[i] > B[i]) => !(A[i] & !B[i]) ===> (A*(B+1))+1 { if(!matrixSize.canAdd(other.matrixSize)) //check sizes throw MatricesSizesNotMatch(matrixSize, other.matrixSize); Ctxt vec = matrix[0]; //save it for faster vec.getPubKey() in the loop if(vec.getPtxtSpace()!= 2) //check that the computations is on binary field throw NotBinaryField(); EncryptedArray ea(vec.getContext()); Ctxt not_ctxt = getNotVector(ea, vec.getPubKey()); vector<Ctxt> res = other.matrix; for(unsigned int i=0, sz = res.size(); i < sz; i++){ res[i] += not_ctxt; res[i] *= matrix[i]; res[i] += not_ctxt; } return EncryptedMatrix(res, matrixSize); } EncryptedMatrix EncryptedMatrix::operator-=(const EncryptedMatrix& other){ return ((*this) = (*this)-other); } bool EncryptedMatrix::operator==(const EncryptedMatrix& other) const{ if(matrixSize != matrixSize) return false; for(unsigned int i=0, len= matrix.size(); i < len; i++) if(matrix[i] != other.matrix[i]) //base on Ctxt::operator== return false; return true; } bool EncryptedMatrix::operator!=(const EncryptedMatrix& other) const { return !(*this == other); } //matrix multyplication by vector. NOTE: this return a column vector! so don't use it to create a matrix (unless you want it to be column vectors matrix) Ctxt EncryptedMatrix::operator*(const Ctxt& vec) const{ EncryptedArray ea(vec.getContext()); Ctxt result(vec.getPubKey()); int len = matrix.size(); //TODO: Still not perfectlly working Ctxt fixedVec = vec; if(ea.size() != getRows()) //Fix the problem that if the size of the vector is not nslots, the zero padding make the rotation push zeros to the begining of the vector { //replicate the vector to fill instead of zero padding for(unsigned int length =getRows(); length < ea.size(); length*=2){ Ctxt copyVec = fixedVec; ea.shift(copyVec, length); //shift length to right fixedVec+=copyVec; } } for(int i=0; i < len; i++) { Ctxt rotatedVec(fixedVec); //copy vec ea.rotate(rotatedVec, -i); //rotate it i right (-i left) rotatedVec *= matrix[i]; result += rotatedVec; } return result; } Ctxt& EncryptedMatrix::operator[](unsigned int i) { return matrix[i]; } const Ctxt& EncryptedMatrix::operator[](unsigned int i) const { return matrix[i]; } unsigned int EncryptedMatrix::getRows() const{ return getMatrixSize().rows; } unsigned int EncryptedMatrix::getColumns() const { return getMatrixSize().columns; } MatSize EncryptedMatrix::getMatrixSize() const { return matrixSize; } //Debug operations EncryptedMatrix EncryptedMatrix::debugMul(const EncryptedMatrix& other, bool logFile, bool relinearation) const{ //check sizes if(!matrixSize.canMultiply(other.matrixSize)){ cout << "ERROR! The matrices must be with suitable sizes!" << endl; return *this; //return this } ofstream* log = NULL; if(logFile) log = new ofstream("logFile.txt"); Ctxt vec(matrix[0]); //save it for faster vec.getPubKey() in the loop EncryptedArray ea(vec.getContext()); bool squares = getMatrixSize().isSquare() && other.getMatrixSize().isSquare() && getRows()==ea.size(); //Use the square matrices formula (much faster) cout << "Square matrices? " << squares << endl; if(logFile) (*log) << "Square matrices? " << squares << endl; int n = getRows(), m = getColumns(), k = other.getColumns(); //sizes: A(this):n*m, B(other):m*k vector<Ctxt> res(m, Ctxt(vec.getPubKey())); for(int i=0; i < k; i++){ for(int j=0; j< m; j++){ if(logFile) (*log) << "i: " << i+1 << " of " << k << ", j: " << j+1 << " of " << m << endl; //work by my formula: C_i = Sig j= 0 to n-1 [ A_i * (B_i-j%n <<< j) ] Ctxt B(other[myModulu(i-j,k)]); //B_i-j%n cout.flush(); cout << "i: " << i+1 << " of " << k << ", j: " << j+1 << " of " << m << " - rotate \r"; if(squares) ea.rotate(B, n-j); //rotate j left, B_i-j%n <<< j (or -j right) else{ //The general formula ea.shift(B, -j); //shift j left int length = m-j; for(int itter=1;length < n; itter++){ Ctxt toChain(other[myModulu(i-j+(itter*m),k)]); ea.shift(toChain, length); //shift length to right B += toChain; length+=m; } } cout.flush(); cout << "i: " << i+1 << " of " << k << ", j: " << j+1 << " of " << m << " - mul \r"; if(relinearation) B.multiplyBy(matrix[j]); //* A_j using relinearation else B *= matrix[j]; //* A_j cout.flush(); cout << "i: " << i+1 << " of " << k << ", j: " << j+1 << " of " << m << " - add \r"; res[i] += B; } if(logFile) (*log) << "Done with i=" << i+1 << endl; } cout.flush(); if(logFile){ (*log) << "DONE!!!!"; (*log).close(); delete log; } return EncryptedMatrix(res, matrixSize*other.matrixSize); } EncryptedMatrix EncryptedMatrix::debugAdd(const EncryptedMatrix& other, bool logFile) const{ //check sizes if(matrixSize != other.matrixSize){ cout << "ERROR! The matrices must be with suitable sizes!" << endl; return *this; //return this } ofstream* log = NULL; if(logFile) log = new ofstream("logFile.txt"); vector<Ctxt> res = matrix; for(unsigned int i=0, sz = matrix.size(); i < sz; i++){ if(logFile) (*log) << "i: " << i+1 << endl; cout << "i: " << i+1 << " \r"; res[i] += other[i]; cout.flush(); if(logFile) (*log) << "Done with i=" << i+1 << endl; } if(logFile){ (*log) << "DONE!!!!"; (*log).close(); delete log; } return EncryptedMatrix(res, matrixSize); }
true
51872619713b7b4ec66021aba89e48f82f7fdd2b
C++
libhet/bulk
/src/Bulk_CommandReader.cpp
UTF-8
2,321
2.890625
3
[]
no_license
#include "Bulk_CommandReader.h" //const std::string CommandReader::EmptyLine = ""; command_t CommandReader::ReadCommand() { command_t cmd; if(IsFirstCommand()) { GetFirstCommandTime(); } std::getline(m_input, cmd); return cmd; } commands_block_t CommandReader::ReadCommandsBlock() { if(IsDynamic()) { m_dynamic_size = false; return ReadDynamicBlock(); } else { return ReadStaticBlock(); } } void CommandReader::Process() { while(m_input) { auto commands = ReadCommandsBlock(); auto time = GetTimeMilliseconds(); notify(commands, time); } } commands_block_t CommandReader::ReadStaticBlock() { StartReadingBlock(); commands_block_t block; auto cmdCounter = 0u; while (cmdCounter < m_max_block_size) { auto command = ReadCommand(); if (command == DynamicBlockBegin) { m_dynamic_size = true; break; } else if (command == EndOfData) { break; } else { block.push_back(command); ++cmdCounter; } } return block; } commands_block_t CommandReader::ReadDynamicBlock() { StartReadingBlock(); commands_block_t block; bool innerBlock = false; while(true) { auto command = ReadCommand(); if (command == DynamicBlockBegin) { innerBlock = true; } else if (command == DynamicBlockEnd) { if(innerBlock) { innerBlock = false; } else { break; } } else if (command == EndOfData) { return EmptyCommandsBlock; } else { block.push_back(command); } } return block; } std::chrono::system_clock::time_point CommandReader::GetTime() { return std::chrono::system_clock::now(); } size_t CommandReader::GetTimeMilliseconds() { return std::chrono::time_point_cast<std::chrono::milliseconds>(m_time).time_since_epoch().count(); } void CommandReader::GetFirstCommandTime() { m_time = GetTime(); m_first_command = false; } bool CommandReader::IsFirstCommand() const { return m_first_command; } void CommandReader::StartReadingBlock() { m_first_command = true; } bool CommandReader::IsDynamic() const { return m_dynamic_size; }
true
984893aebb596ea74e8d3e79093f09c177d50827
C++
scoiatael/ThingsIdidAtII
/AISD/template.cpp
UTF-8
2,111
3.34375
3
[]
no_license
/******************** * Lukasz Czaplinski* * 247926 * * RNO * * ******************/ #include <iostream> #include <vector> #ifdef SPRAWDZACZKA #define NDEBUG #define assert_msg(X, Y) {} #endif #ifndef SPRAWDZACZKA #define assert_msg(X,Y) { if(!X) { Y; } } #endif #include <cassert> #include <string> using namespace std; namespace my { template<class T> void swap(T& a, T&b) { T temp(a); a=b; b=temp; } template<class T> T min(const T& a, const T& b) { return (a<b) ? a : b; } template<class T> T max(const T& a, const T& b) { return (a>b) ? a : b; } template<class T> class safe_con : public vector<T> { public: safe_con() : std::vector<T>() {} safe_con(const safe_con& arg) : std::vector<T>(arg) { assert_msg(false, cout << "safe_con copy constr invoked, copying " << arg.size() << " elements.\n" ); } safe_con(const vector<T>& arg) : std::vector<T>(arg) { assert_msg(false, cout << "safe_con constr from vec invoked, copying " << arg.size() << " elements.\n"); } T& operator[](const unsigned int& n) { assert(n < this->size()); return std::vector<T>::operator[](n); } T operator[](const unsigned int& n) const { assert(n < this->size()); return std::vector<T>::operator[](n); } safe_con& operator=(const safe_con& arg) { assert_msg(false, cout << "safe_con operator= invoked, copying " << arg.size() << " elements.\n"); std::vector<T>::operator=(arg); return *this; } }; template<class T> istream& operator>> (istream& stream, safe_con<T>& arg) { int size; stream >> size; arg.resize(size); for(unsigned int i=0; i<arg.size(); i++) stream >> arg[i]; return stream; } template<class T> ostream& operator<< (ostream& stream, const safe_con<T>& arg) { for(unsigned int i=0; i<arg.size();i++) stream << arg[i] << " "; return stream; } } int main() { my::safe_con<int> test, test2; cin >> test; test2 = test; cout << test2 << endl; }
true
83d77f3a0bd35abe08c0a69494f3b1e6de681cb9
C++
ethz-asl/refill
/src/examples/kalman_filter_example.cc
UTF-8
3,741
3.140625
3
[ "MIT" ]
permissive
#include <Eigen/Dense> #include <iostream> #include "refill/distributions/gaussian_distribution.h" #include "refill/filters/extended_kalman_filter.h" #include "refill/measurement_models/linear_measurement_model.h" #include "refill/system_models/linear_system_model.h" /* * This is an example program for using Refill to estimate the 3D position * using a constant position model and assuming measurements are 3D position * measurements of the real position. * * The system model can then be written as: * * x(k) = I * x(k-1) + v(k) * * with * * x(k) element of R^3 * * I = Identity matrix element of R^3x3 * * v(k) random variable distributed with N(0, dt * Q) * * where Q element of R^3x3 is the system model covariance. * * The measurement model can be written as: * * y(k) = I * x(k) + w(k) * * with * * w(k) ~ N(0, R) * * where R element of R^3x3 is the measurement model covariance. */ int main(int argc, char **argv) { /* initialize Q and R * Q = I * 2.0 * R = I */ Eigen::Matrix3d system_noise_cov = Eigen::Matrix3d::Identity() * 2.0; Eigen::Matrix3d measurement_noise_cov = Eigen::Matrix3d::Identity() * 1.0; /* initialize v(k) */ refill::GaussianDistribution system_noise(Eigen::Vector3d::Zero(), system_noise_cov); /* initialize w(k) */ refill::GaussianDistribution measurement_noise( Eigen::Vector3d::Zero(), measurement_noise_cov); /* initialize the system model */ refill::LinearSystemModel system_model(Eigen::Matrix3d::Identity(), system_noise); /* initialize the measurement model */ refill::LinearMeasurementModel measurement_model(Eigen::Matrix3d::Identity(), measurement_noise); /* initialize the initial state distribution * Assumed to be at position [1, 1, 1]^T with cov[I * 5] */ refill::GaussianDistribution initial_state(Eigen::Vector3d::Ones(), Eigen::Matrix3d::Identity() * 5.0); /* initialize the kf with the initial state */ refill::ExtendedKalmanFilter ekf(initial_state); /* assume that 1.0 seconds has passed and we get a position measurement at * [1.5, 1.5, 1.5]^T * t = 1.0 */ double dt = 1.0; Eigen::Vector3d measurement = Eigen::Vector3d::Constant(1.5); /* adapt the system model noise according to the time step */ system_noise.setCov(system_noise_cov * dt); /* adapt the system model */ system_model.setModelParameters(Eigen::Matrix3d::Identity(), system_noise); /* predict the kf to the current time */ ekf.predict(system_model); /* update the kf with the measurement and the measurement model */ ekf.update(measurement_model, measurement); /* print the current state */ std::cout << "State at t = 1.0:\n"; std::cout << "Mean:\n\n" << ekf.state().mean() << "\n\n"; std::cout << "Covariance:\n\n" << ekf.state().cov() << "\n\n"; /* Assume that another 0.5 seconds have passed and another measurement * is received * t = 1.5 */ dt = 0.5; measurement = Eigen::Vector3d::Constant(1.5); // adapt the system noise according to the time step system_noise.setCov(system_noise_cov * dt); // adapt the system model system_model.setModelParameters(Eigen::Matrix3d::Identity(), system_noise); /* predict the kf to the current time */ ekf.predict(system_model); /* update the kf with the measurement and the measurement model */ ekf.update(measurement_model, measurement); /* print the current state */ std::cout << "State at t = 1.5:\n"; std::cout << "Mean:\n\n" << ekf.state().mean() << "\n\n"; std::cout << "Covariance:\n\n" << ekf.state().cov() << "\n\n"; return 0; }
true
b967e1d639329ea921a823e813805420cb84ba96
C++
Corillian/dotnetnative
/DotNetNative/System/CharUnicodeInfo.h
UTF-8
1,557
2.609375
3
[ "MIT" ]
permissive
#ifndef _DOTNETNATIVE_SYSTEM_CHARUNICODEINFO_H_ #define _DOTNETNATIVE_SYSTEM_CHARUNICODEINFO_H_ #include "UnicodeCategory.h" #include "Char.h" namespace DotNetNative { namespace System { class String; class CharUnicodeInfo { public: static constexpr utf16char HIGH_SURROGATE_START = 0xd800; static constexpr utf16char HIGH_SURROGATE_END = 0xdbff; static constexpr utf16char LOW_SURROGATE_START = 0xdc00; static constexpr utf16char LOW_SURROGATE_END = 0xdfff; static constexpr int HIGH_SURROGATE_RANGE = 0x3FF; static constexpr int UNICODE_CATEGORY_OFFSET = 0; static constexpr int BIDI_CATEGORY_OFFSET = 1; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. static constexpr int UNICODE_PLANE01_START = 0x10000; private: CharUnicodeInfo() = delete; CharUnicodeInfo(const CharUnicodeInfo &copy) = delete; CharUnicodeInfo(CharUnicodeInfo &&mov) = delete; ~CharUnicodeInfo() = delete; public: static UnicodeCategory GetUnicodeCategory(const utf16char ch); static UnicodeCategory GetUnicodeCategory(const String &str, const int index); static UnicodeCategory GetUnicodeCategory(const int codePoint); static double GetNumericValue(const utf16char ch); static double GetNumericValue(const String &str, const int index); }; } } #endif
true
0ddf2af1a884ba82060e254285e477c6f652ccb7
C++
nileshjchoudhary/indus
/src/orderparameters/ProbeVolume_Box.h
UTF-8
2,830
2.90625
3
[ "MIT" ]
permissive
/* ProbeVolume_Box.h * * ABOUT: * - Currently only supports orthorhombic boxes * * DEVELOPMENT: */ #pragma once #ifndef PROBE_VOLUME_BOX_H #define PROBE_VOLUME_BOX_H // Standard headers #include <map> // Core headers #include "ProbeVolume.h" // Parent class #include "GenericFactory.h" // Register as a ProbeVolume #include "SwitchingFunction_WithRegions_x.h" class ProbeVolume_Box : public ProbeVolume { public: using Box = ProbeVolume::Box; using Real3 = ProbeVolume::Real3; using Rvec = ProbeVolume::Rvec; ProbeVolume_Box(ProbeVolumeInputPack& input_pack); // Constructor which ignores the ParameterPack in the input pack // and instead provides the necessary variables explicitly ProbeVolume_Box( ProbeVolumeInputPack& input_pack, const Real3& box_offset, const Box& box_matrix, const double sigma, const double alpha_c ); virtual void setGeometry() override; void setGeometry( const Real3& box_offset, // Position of lower-left corner: {x, y, z} const Box& box_matrix // Size and shape of box ); void setGeometry( const Real3& x_lower, // position of lower-left corner const Real3& x_upper // position of upper-right corner ); virtual void calculateIndicator( const Real3& x, // Output double& h_v, double& htilde_v, Real3& dhtilde_v_dx, RegionEnum& region ) const override; // Returns a string with complete, formatted information about the probe volume's // location and geometry which can be included in output files. Each line begins // with a "#" which signifies that it's a comment line. std::string getInputSummary(const std::string& prepend_string) const override; void getGeometry(Real3& box_offset, Box& box_matrix) { box_offset = box_offset_; box_matrix = box_matrix_; } // Returns whether the probe box is orthrhombic bool is_orthorhombic() const { for ( int a=0; a<DIM_; ++a ) { for ( int b=0; b<DIM_; ++b ) { if ( a != b and box_matrix_[a][b] != 0.0 ) { return false; } } } return true; } protected: virtual BoundingBox constructBoundingBox() const override; private: // Nominal ranges for orthorhombic boxes std::array<CommonTypes::Range,DIM_> axis_ranges_; std::array<CommonTypes::Range,DIM_> inner_axis_ranges_; // -alpha_c std::array<CommonTypes::Range,DIM_> outer_axis_ranges_; // +alpha_c // Box geometry (nominal and effective) Real3 box_offset_; // Position of lower-left corner Box box_matrix_; // Position of base: {x,y,z} Real3 center_; // Center point: {x,y,z} // Half-lengths (assumes an orthorhombic box) Real3 box_half_lengths_; // Switching functions for a box shifted to the origin // - Each runs from -L_i/2 to +L_i/2 std::array<SwitchingFunction_WithRegions_x, DIM_> switching_functions_shifted_box_; }; #endif // PROBE_VOLUME_BOX_H
true
c23da328c0967f2f7a27d24d36bec5f1539d97cf
C++
ReU1107/Project1
/Project1/Project1/Source/Engine/AnimationSystem/Motion/Motion.h
SHIFT_JIS
919
2.609375
3
[]
no_license
#pragma once #include "../../Utility/AccessObject.h" #include <memory> namespace Engine { namespace AnimationSystem { // O錾 class Avatar; class AvatarMask; // [VNX class Motion : public AccessObject<Motion> { private: using base = AccessObject<Motion>; protected: using AvatarPtr = std::shared_ptr<Avatar>; using AvatarMaskPtr = std::shared_ptr<AvatarMask>; public: // RXgN^ Motion(const std::string& name) noexcept; // fXgN^ virtual ~Motion() noexcept; public: // CX^XID static const InstanceID ID() { return InstanceID::Motion; } // CX^XID擾 virtual InstanceID GetInstanceID() const override { return InstanceID::Motion; } public: // XV virtual void Update(AvatarPtr avatar, AvatarMaskPtr mask, float deltaTime, float weight = 1.0f) = 0; }; } }
true
a7636aa0dffe879414ce46555705fd8f1012ef1e
C++
mletic/EmbeddedComputerSystems
/ARDUINO/Blink4/Blink4_ver1.ino
UTF-8
2,769
3.40625
3
[ "MIT" ]
permissive
/* Blink 4 Turns on/off LED according to SW position. Reveals logic behind Arduino digitalRead function Napisi svoju digitalWrite i pinModeOut funkciju */ #define dump(v) Serial.print(v) //************************************************************************ int digitalRead1(uint8_t pin) { volatile p32_ioport *iop; uint8_t port; uint16_t bit; int highLow; /* Check if pin number is in valid range. */ if (pin >= NUM_DIGITAL_PINS_EXTENDED) { return 0; } //* Get the port number for this pin. if ((port = digitalPinToPort(pin)) == NOT_A_PIN) { return LOW; } //* Obtain pointer to the registers for this io port. iop = (p32_ioport *)portRegisters(port); //* Obtain bit mask for the specific bit for this pin. bit = digitalPinToBitMask(pin); //dump("PORT=");dump(port); dump(" BIT=");dump(bit); //dump(" DATA=");dump(iop->port.reg); //dump("\n"); //* Get the pin state. if ((iop->port.reg & bit) != 0) { highLow = HIGH; } else { highLow = LOW; } return(highLow); } void digitalWrite1(uint8_t pin, uint8_t val) { volatile p32_ioport *iop; uint8_t port; uint16_t bit; /* Check if pin number is in valid range. */ if (pin >= NUM_DIGITAL_PINS_EXTENDED) { return; } //* Get the port number for this pin. if ((port = digitalPinToPort(pin)) == NOT_A_PIN) { return; } //* Obtain pointer to the registers for this io port. iop = (p32_ioport *)portRegisters(port); //* Obtain bit mask for the specific bit for this pin. bit = digitalPinToBitMask(pin); //* Set the pin state if (val == LOW) { iop->lat.clr = bit; } else { iop->lat.set = bit; } } void pinModeOut(uint8_t pin) { volatile p32_ioport *iop; uint8_t port; uint16_t bit; // Check if pin number is in valid range. if (pin >= NUM_DIGITAL_PINS_EXTENDED) { return; } //* Get the port number for this pin. if ((port = digitalPinToPort(pin)) == NOT_A_PIN) { return; } //* Obtain pointer to the registers for this io port. iop = (p32_ioport *)portRegisters(port); //* Obtain bit mask for the specific bit for this pin. bit = digitalPinToBitMask(pin); iop->tris.clr = bit; // make the pin an output iop->lat.clr = bit; // clear to output bit } // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin 27 as an output. //pinMode(27, OUTPUT); pinModeOut(27); // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop function runs over and over again forever void loop() { delay(200); if( digitalRead1(7) ) digitalWrite1(27, HIGH); else digitalWrite1(27, LOW); }
true
0f8cbe5eb087c1827e33d770a8b40684374ff865
C++
sachinsngh165/Competitive-Programing
/codechef/CHFNFRNv7.cpp
UTF-8
2,675
3.078125
3
[]
no_license
// // CHFNFRNv7.cpp // // // Created by SACHIN SINGH on 08/09/16. // // #include <iostream> #include <bits/stdc++.h> using namespace std; class Graph { int v,*color,*visited; list <int> *adj; public: void addEdge(int,int); Graph(int); bool isBipartite(); }; void Graph:: addEdge(int s,int d) { adj[s].push_back(d); } Graph::Graph(int n) { v=n; color=new int[n]; fill(color,color+v,-1); visited=new int[n]; adj=new list<int>[v]; fill(visited,visited+n,0); } bool Graph:: isBipartite() { queue<int> q; for(int i=1; i<v; i++) { if(!visited[i]) { q.push(i); color[i]=1; while(!q.empty()) { int u=q.front(); q.pop(); if(!visited[u]) { visited[u]=1; for(auto it=adj[u].begin(); it!=adj[u].end(); it++) { if(color[*it]==color[u]) return false; color[*it]=1-color[u]; q.push(*it); } } } } } return true; } void Complement(vector<vector<int> > &G,long long V) { for (long long i=1; i<V; i++) { for (long long j=1; j<V; j++) { if (G[i][j]==1) { G[i][j]=0; }else G[i][j]=1; } } } // Driver program int main() { ios::sync_with_stdio(false); long long t; cin>>t; for (long long cases=0; cases<t; cases++) { long long V; cin>>V; ++V; //construct a Graph of size V*V vector<vector<int> > G; G.resize(V, vector<int>(V, 0)); //since an element is related to itself for (long long i=1; i<V;i++) { G[i][i]=1; } long long m,u,v; cin>>m; for (long long i=0; i<m; i++) { cin>>u >>v; G[u][v]=1; G[v][u]=1; } Complement(G,V); Graph g(V); for (int i=1; i<V; i++) { for (int j=1; j<V; j++) { if (G[i][j]==1) { g.addEdge(i, j); } } } if(g.isBipartite()) cout<<"YES" <<endl; else cout<<"NO" <<endl; } return 0; }
true
92a5a0efa6dd4e5a3836eab5b023fb14ef5acfa9
C++
IvanKosh/ShortestRepetition
/main.cpp
UTF-8
809
2.96875
3
[]
no_license
/* * File: main.cpp * Author: bat * * Created on 17 Сентябрь 2015 г., 18:45 */ #include <iostream> #include <fstream> using namespace std; int main(int argc, char *argv[]) { ifstream stream(argv[1]); string line, temp; short i, l, j; bool test; while (getline(stream, line)) { test = false; l = line.length(); for(i = 1; i < l; i++) { temp = line.substr(0, i); for(j = i; j < l; j += i) { test = true; if (temp != line.substr(j, i)) { test = false; } } if (test) { cout << i << endl; break; } } if (!test) { cout << l << endl; } } return 0; }
true
c157bfbd6227e84397d2c2a94b9f5864b5b181c8
C++
venky1014/gbash
/echo.cpp
UTF-8
2,125
2.953125
3
[]
no_license
#include "command.h" #include "globals.h" #include <QString> #include <QDir> #include <QFile> #include <QTextStream> #include <QCommandLineParser> using namespace std; echo::echo(QString cmd){ QTextStream out (stdout); QString output; if(cmd.contains(">>")){ int index = cmd.indexOf(">>"); int length = cmd.length(); QString filename = cmd.right(length - index - 3); QFile file(filename); if (!file.exists()) out << "File does not exist!\n"; else { //out << index; QString in = cmd.remove(index, cmd.length()); in = cmd.mid(5); string s = in.toStdString(); QByteArray putt = s.c_str(); file.open(QIODevice::Append | QIODevice::Text); file.write(putt); file.flush(); file.close(); } } else if (cmd.contains(">")){ int index = cmd.indexOf(">"); int length = cmd.length(); QString filename = cmd.right(length - index - 2); QFile file(filename); if (!file.exists()) out << "File does not exist!\n"; else { QString in = cmd.remove(index, length); in = cmd.mid(5); string s = in.toStdString(); QByteArray putt = s.c_str(); file.open(QIODevice::WriteOnly | QIODevice::Text); file.write(putt); file.close(); } } else if(cmd.contains("|")){ } else if(cmd.contains("-h") or cmd.contains("--help") or cmd.contains("-?")){ parse.addHelpOption(); parse.setApplicationDescription("\nOutputs entered standard input back into the program\nUse >> followed by filename to append the standard input to that file\nUse > followed by the filename to overwrite contents of the file by the standard input\n "); out << parse.helpText(); } else { QString sub = cmd.mid(5); output = this->echo_n(sub); } out << output <<endl; } QString echo::echo_n(QString str){ // n = normal return str; }
true
507b98a7a94566189daad11f2f6d583e245cf11c
C++
TheGrimsey/NovusCore-AuthMaster
/server/Networking/MessageHandler.cpp
UTF-8
472
2.546875
3
[ "MIT" ]
permissive
#include "MessageHandler.h" #include "../ECS/Components/ConnectionComponent.h" MessageHandler::MessageHandler() { for (i32 i = 0; i < Opcode::OPCODE_MAX_COUNT; i++) { handlers[i] = nullptr; } } void MessageHandler::SetMessageHandler(Opcode opcode, MessageHandlerFn func) { handlers[opcode] = func; } bool MessageHandler::CallHandler(Packet* packet) { return handlers[packet->header.opcode] ? handlers[packet->header.opcode](packet) : true; }
true
1887dea93bf81c050dba06b68e11dbeffeb19449
C++
wanghuqiang123/C-primertest
/test13-28.cpp
GB18030
1,266
3.390625
3
[]
no_license
#include<iostream> #include<string> using namespace std; class TreeNode { private: string value; int count; TreeNode * left; TreeNode * right; public: TreeNode() :value(""),count(1),left(nullptr), right(nullptr) { } TreeNode(const string& s = string(),TreeNode* lchild = nullptr,TreeNode* rchild = nullptr) : value(s), count(1), left(nullptr), right(nullptr) { } TreeNode(const TreeNode& obj) :value(obj.value),count(1),left(obj.left),right(obj.right) { if (left) left->copyTree(); if (right) right->copyTree(); } TreeNode* copyTree(void) //Դ˽ڵΪ { if (left) left->copyTree(); if (right) right->copyTree(); count++; return this; //Լ+ } int ReleaseTree(void) { if (left) { if (!left->copyTree()) delete left; } if (right) { if (!right->copyTree()) delete right; } count--; return count; } ~TreeNode() { if (count) ReleaseTree(); } }; class BinaryTree { private: TreeNode* root; public: BinaryTree() :root(nullptr) { } BinaryTree(TreeNode* t = nullptr) :root(t) { } BinaryTree(const BinaryTree& obj):root(obj.root) { root->copyTree(); } ~BinaryTree() { if (!root->ReleaseTree()) delete root; } }; int main() { return 0; }
true
5183f9bae2c94b7765b34556fd31d112798dfeca
C++
MarvinZZJ/WangDaoAlgorithmNotes
/第4章:字符串/4.2:字符串处理/test4-5后缀字符串排序.cpp
UTF-8
583
3.171875
3
[]
no_license
/* 习题4.5 后缀字符串排序(上海交通大学复试上机题) https://www.nowcoder.com/questionTerminal/f89f96ea3145418b8e6c3eb75773f65a */ #include <iostream> #include <cstdio> #include <string> #include <algorithm> using namespace std; int main(){ string str; while(cin >> str){ string strs[str.size()]; for(int i = 0; i < str.size(); i++){ strs[i] = str.substr(i); } sort(strs, strs + str.size()); for(int i = 0; i < str.size(); i++){ cout << strs[i] << endl; } } return 0; }
true
dd448b94c3b9a57110b018bd1c2e31d8f1d245cc
C++
nathanbeckmann/OPEC
/opec.hpp
UTF-8
1,523
3.015625
3
[]
no_license
#pragma once #include <algorithm> #include "country.hpp" namespace opec { class Opec { public: enum Countries { SaudiArabia, Iran, Iraq, Kuwait, UAE, Venezuela, Nigeria, NumCountries }; Country& operator[] (Countries country) { return countries[country]; } Country& operator[] (int country) { return (*this)[Countries(country)]; } Opec() : countries({Country("Saudi Arabia", 108000, 12000, 9), Country("Iran", 41400, 4600, 10), Country("Iraq", 33300, 3700, 16), Country("Kuwait", 29700, 3300, 13), Country("UAE", 27000, 3000, 5), Country("Venezula", 39600, 4400, 20), Country("Nigeria", 24300, 2700, 7)}) { auto opecReserves = std::accumulate(&countries[0], &countries[NumCountries], 0, [] (int sum, const Country& c) { return sum + c.reserves; }); assert(opecReserves == 303300); auto opecCapacity = std::accumulate(&countries[0], &countries[NumCountries], 0, [] (int sum, const Country& c) { return sum + c.capacity; }); assert(opecCapacity == 33700); } private: Country countries[NumCountries]; }; extern Opec opec; }
true
65602ece2031e135288bad14bd959b2ab59b5bad
C++
fabsgc/Terminale-S-Zombie
/source-code/object_bonus.cpp
ISO-8859-1
2,943
3.1875
3
[]
no_license
#include "object_bonus.hpp" sf::Image m_imageObjectBonus; /** * constructeur * @access public * @return void */ Object_Bonus::Object_Bonus() { if (!m_imageObjectBonus.LoadFromFile(SPRITE_BONUS)) // Si le chargement du fichier a chou { std::cout<<"[ERREUR] : [Object_Bonus::Object_Bonus] : impossible de charger le sprite bonus"<<std::endl; } m_sprite.SetCenter(WIDTH_OBJECT_X/2, WIDTH_OBJECT_Y/2); m_sprite.SetImage(m_imageObjectBonus); } /** * affiche le bonus a l'ecran * @param sf::RenderWindow &window : rfrence vers l'instance de la fentre * @access public * @return void */ void Object_Bonus::display(sf::RenderWindow &window) { m_sprite.SetPosition(sf::Vector2f(m_positionObject.x, m_positionObject.y)); // Positionnement m_sprite.SetRotation(m_positionObject.rotate); m_sprite.SetScale(0.85,0.85); window.Draw(m_sprite); } /** * defini le type du bonus * @param int type : type du bonus * @access public * @return void */ void Object_Bonus::setType(int type) { m_type = type; switch(m_type) { case BONUS_SPEED : m_sprite.SetSubRect(sf::IntRect(0, 0, WIDTH_OBJECT_X, WIDTH_OBJECT_Y)); break; case BONUS_LIFE : m_sprite.SetSubRect(sf::IntRect(0, WIDTH_OBJECT_Y, WIDTH_OBJECT_X, WIDTH_OBJECT_Y*2)); break; case BONUS_AMMUNITION : //fait lorsque l'on indique l'id de l'arme break; } } /** * defini la valeur du bonus * @param int value : valeur que donnera le bonus * @access public * @return void */ void Object_Bonus::setValue(int value) { m_value = value; } /** * defini l'arme sur laquelle peut s'appliquer le bonus * @param int id : id de l'arme dans le cas ou le bonus concerne une arme * @access public * @return void */ void Object_Bonus::setArmeId(int id) { m_armeBonus = id; switch(m_type) { case BONUS_AMMUNITION : m_sprite.SetSubRect(sf::IntRect(WIDTH_OBJECT_X*(m_armeBonus-1), WIDTH_OBJECT_Y*2, WIDTH_OBJECT_X*(m_armeBonus), WIDTH_OBJECT_Y*3)); break; } } /** * retourne le type du bonus * @access public * @return int */ int Object_Bonus::getType() { return m_type; } /** * retourne la valeur du bonus * @access public * @return int */ int Object_Bonus::getValue() { return m_value; } /** * retourne l'id de l'arme qui peut-etre concernee * @access public * @return int */ int Object_Bonus::getArmeId() { return m_armeBonus; } /** * destructeur * @access public * @return void */ Object_Bonus::~Object_Bonus() { }
true
6452c4ab304ec6a7c7555e52faccff2bc379202d
C++
cosmicray001/academic
/problem_solving/LightOJ/1043/14534951_AC_0ms_1700kB.cpp
UTF-8
811
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; double ab, ac, bc, abc, def, rto; double fnc(double a, double b, double c){ double s = (a + b + c) / 2.0; return sqrt(s * (s - a) * (s - b) * (s - c)); } double ok(double ad){ double de = (ad * bc) / ab; double ae = (ad * ac) / ab; def = fnc(ad, de, ae); return def / (abc - def); } double fnc1(){ double lo = 0.0, hi = ab, mid; int t = 100; while(t--){ mid = (lo + hi) / 2; if(ok(mid) > rto) hi = mid; else lo = mid; } return mid; } int main(){ //freopen("input.txt", "r", stdin); int t, co = 0; for(scanf("%d", &t); t--; ){ scanf("%lf %lf %lf %lf", &ab, &ac, &bc, &rto); abc = fnc(ab, ac, bc); printf("Case %d: %.10lf\n", ++co, fnc1()); } return 0; }
true
80e3523bc5a0f8c05acedc86a0f110d5fb210158
C++
VilimRoller/Roman-Chess
/RomanChess/RomanChess/Eques.h
UTF-8
417
2.625
3
[ "MIT" ]
permissive
#pragma once #include "Figure.h" class Eques : public Figure { public: Eques(figureColour figure_colour = figureColour::Red, BoardCoordinates initial_position = BoardCoordinates{ 0,0 }, int figure_number = 0) { InitializeFigure(figure_colour, figureType::Eques, initial_position, figure_number); } void SetFigureTextureRect() override { SetTextureRect(SFMLConstants::FigureSpriteRectPos_Eques); } };
true
732734370ff47a3b4eb432ac00cf9f1d9fb1ca8b
C++
nur-alam/Problem-Solving
/Uva/3n+1/onlycycle.cpp
UTF-8
361
2.75
3
[]
no_license
#include<cstdio> int cycle(int m){ int i=1; while(1){ printf("%d ",m); if(m==1){ break; } if(m%2==0){ m=m/2; } else{ m=3*m+1; } i++; } return i; } int main(){ int m; scanf("%d",&m); int max=cycle(m); printf("\n%d",max); return 0; }
true
dbcf6a780184f34a8a14c2e9199adbb54e42ea79
C++
AlexIsHappy/CodeForces
/cf6A.cpp
UTF-8
1,155
2.84375
3
[]
no_license
#include <algorithm> #include <iomanip> #include <istream> #include <map> #include <numeric> #include <ostream> #include <set> #include <sstream> #include <string> #include <utility> #include <vector> using namespace std; // Powered by caide (code generator, tester, and library code inliner) class Solution { public: void solve(std::istream& in, std::ostream& out) { int a, b, c, s; in >> a >> b >> c >> s; vector<int> sid; sid.push_back(a); sid.push_back(b); sid.push_back(c); sid.push_back(s); bool isSeg = false; for (int i = 0; i < 4; i++){ vector<int> sd; for (int j = 0; j < 4; j++){ if (i != j){ sd.push_back(sid[j]); } } if (((sd[0] + sd[1]) > sd[2]) && ((sd[0] + sd[2]) > sd[1]) && ((sd[1] + sd[2]) > sd[0])){ out << "TRIANGLE"; return; } if (((sd[0] + sd[1]) == sd[2]) || ((sd[0] + sd[2]) == sd[1]) || ((sd[1] + sd[2]) == sd[0])){ isSeg = true; } } if (isSeg) out << "SEGMENT"; else out << "IMPOSSIBLE"; } }; void solve(std::istream& in, std::ostream& out) { out << std::setprecision(12); Solution solution; solution.solve(in, out); }
true
c79dbbbef0af6d06ccacc8afcf96946ff29879f6
C++
mviseu/Cpp_primer
/Chapter15/15_36.cc
UTF-8
699
3.03125
3
[]
no_license
#include "Query.h" #include "TextQuery.h" #include "QueryResult.h" #include <fstream> #include <iostream> int main() { std::ifstream file("input_text.txt"); TextQuery text(file); Query q = Query("fiery") & Query("bird") | Query("wind"); //print(std::cout, q.eval(text)); //q.eval(text); std::cout << q; return 0; } /* 1. Query(fiery, bird, wind) -> BaseQuery, WordQuery, Query(string) (3x each) 2. & operator -> BaseQuery, BinaryQuery, AndQuery, constructor Query(shared_ptr) (1x each) 3. | operator -> BaseQuery, BinaryQuery, OrQuery, constructor Query(shared_ptr) (1x each) Totals Query string 3 Query shared - 2 BaseQuery - 5 WordQuery - 1 OrQuery - 1 AndQuery - 1 BinaryQuery - 2 */
true
8cf12f26c0617bedd9e69a0f1b4ed9f3d5d56402
C++
daidodo/dell-virtual-machine
/BuildCmdLine.h
UTF-8
5,692
2.625
3
[]
no_license
#ifndef BUILDCMDLINE_H #define BUILDCMDLINE_H #include <string> #include <vector> #include <iostream> namespace DoZerg{ #ifdef VM_DBG_BLDCMDLINE #define VM_DBG_BLDCMDLINE0(str) std::cout<<"BuildCmdLine::HandleArguments(): "<<str; #define VM_DBG_BLDCMDLINE1(str,arg1) std::cout<<"BuildCmdLine::HandleArguments(): ";std::printf(str,arg1); #define VM_DBG_BLDCMDLINE2(str,arg1,arg2) std::cout<<"BuildCmdLine::HandleArguments(): ";std::printf(str,arg1,arg2); #else #define VM_DBG_BLDCMDLINE0(str) #define VM_DBG_BLDCMDLINE1(str,arg1) #define VM_DBG_BLDCMDLINE2(str,arg1,arg2) #endif template<class __ErrCount>class BuildCmdLine { public: typedef std::vector<std::string> __Arguments; typedef __ErrCount __ErrCount; private: static const char IN_EXT[5]; //file extensions static const char TMP_EXT[5]; static const char LST_EXT[5]; static const char OUT_EXT[5]; static const std::string DEFAULT_NAME; //default name of file public: ~BuildCmdLine(){} BuildCmdLine():omitDebugData(0),listing(0){} const char * InputFileName() const{return inputFile_.c_str();} const char * ListFileName() const{return listFile_.c_str();} const char * TempFileName() const{return tempFile_.c_str();} const char * OutputFileName() const{return outputFile_.c_str();} int Listing() const{return listing;} int OmitDebugData() const{return omitDebugData;} bool HandleArguments(const __Arguments & argv){ if(argv.empty()){ __ErrCount()<<"No Arguments\n"; PrintUsage(); return false; } //get input file name "filename.ASM" int inFileLen = int(argv[0].length()); if(inFileLen > 4 && argv[0][inFileLen - 4] == '.' && (argv[0][inFileLen - 3] == 'A' || argv[0][inFileLen - 3] == 'a') && (argv[0][inFileLen - 2] == 'S' || argv[0][inFileLen - 2] == 's') && (argv[0][inFileLen - 1] == 'M' || argv[0][inFileLen - 1] == 'm')){ inputFile_ = argv[0]; }else{ __ErrCount()<<"expecting .ASM file\n"; PrintUsage(); return false; } //process options bool OutFileSet = false; for(int i = 1,j = int(argv.size());i < j;++i){ if(argv[i][0] != '-'){ __ErrCount()<<"bad option,need \'-\' before "<<argv[i]<<'\n'; PrintUsage(); return false; } switch(argv[i][1]){ case 'd': case 'D':{ if(argv[i][2] != '\0'){ __ErrCount()<<"bad \'-d\' in "<<argv[i]<<'\n'; PrintUsage(); return false; } omitDebugData = true; VM_DBG_BLDCMDLINE0("Omit Debug Data is TRUE\n"); break;} case 'l': case 'L':{ if(argv[i][2] != '\0'){ __ErrCount()<<"bad \'-l\' in "<<argv[i]<<'\n'; PrintUsage(); return false; } listing = 1; VM_DBG_BLDCMDLINE0("List File set to TRUE\n"); break;} case 'o': case 'O':{ //output file must look like "file.RUN" if(argv[i][2] != '='){ __ErrCount()<<"bad \'-o=XXX\' in "<<argv[i]<<'\n'; PrintUsage(); return false; }else{ int len = int(argv[i].length()); if(len > 7/*(-o=file.RUN)4 + 3*/ && argv[i][len - 4] == '.' && (argv[i][len - 3] == 'R' || argv[i][len - 3] == 'r') && (argv[i][len - 2] == 'U' || argv[i][len - 2] == 'u') && (argv[i][len - 1] == 'N' || argv[i][len - 1] == 'n')){ outputFile_ = argv[i].substr(3); }else{ __ErrCount()<<"expecting .RUN file but "<<argv[i]<<'\n'; PrintUsage(); return false; } } OutFileSet = true; break;} case '?':{ PrintUsage(); return false;} default:{ __ErrCount()<<"bad option: "<<argv[i]<<'\n'; PrintUsage(); return false; } } } if(!OutFileSet) outputFile_ = inputFile_.substr(0,inFileLen - 4) + OUT_EXT; inFileLen = int(outputFile_.length()); listFile_ = outputFile_.substr(0,inFileLen - 4) + LST_EXT; tempFile_ = outputFile_.substr(0,inFileLen - 4) + TMP_EXT; //summary VM_DBG_BLDCMDLINE0("Command line summary\n"); VM_DBG_BLDCMDLINE1("\tinput file = %s\n",inputFile_.c_str()); VM_DBG_BLDCMDLINE1("\toutput file = %s\n",outputFile_.c_str()); VM_DBG_BLDCMDLINE1("\ttemp file = %s\n",tempFile_.c_str()); VM_DBG_BLDCMDLINE1("\tlist file = %s\n",listFile_.c_str()); if(listing){ VM_DBG_BLDCMDLINE0("\tlisting is ON\n"); }else{ VM_DBG_BLDCMDLINE0("\tlisting is OFF\n"); } if(omitDebugData){ VM_DBG_BLDCMDLINE0("\tomit Debug Data\n"); }else{ VM_DBG_BLDCMDLINE0("\tDebug Data included\n"); } return true; } private: void PrintUsage() const{ std::cout<<"\n\tDEllASM file.ASM [optoins]\n\n" <<"\tOptions:\n\n" <<"\t-d\t\tomit debug information\n" <<"\t-l\t\tproduce a listing file\n" <<"\t-o=XXX\t\tname of output file(compilation unit)\n" <<"\t-?\t\tprint help\n" <<"\n\tthere are no spaces between option characters\n\n"; } private: std::string inputFile_,listFile_,tempFile_,outputFile_; int omitDebugData; //true if omit debug data int listing; //true if desire a listing }; template<class __ErrCount> const char BuildCmdLine<__ErrCount>::IN_EXT[5] = ".ASM"; template<class __ErrCount> const char BuildCmdLine<__ErrCount>::TMP_EXT[5] = ".TMP"; template<class __ErrCount> const char BuildCmdLine<__ErrCount>::LST_EXT[5] = ".LST"; template<class __ErrCount> const char BuildCmdLine<__ErrCount>::OUT_EXT[5] = ".RUN"; template<class __ErrCount> const std::string BuildCmdLine<__ErrCount>::DEFAULT_NAME = "Un-Named"; }//namespace DoZerg #endif
true
e0b34340561d5ea5a612ed9de2eb2bf665e2239a
C++
RR294/Study
/coding_problems/max_rect_frm_bin_mtx.cpp
UTF-8
2,615
3.8125
4
[]
no_license
// Program to find max rectangle from binary matrix formed by 1. #include <iostream> // 1 0 1 1 0 // 0 1 1 0 1 // 1 1 1 0 1 // 1 1 1 0 0 // 0 1 1 1 1 // In above matrix , rectangle with mix 1 will be eight 1's. // Time complexity : O(rows * cols) // Space complexity : number of columns => O(cols) // to optimise space , takemin between rows & cols and sweep accordingly. // function to find matrix with max value from given row int get_max_frm_row(int bars[], int bar_cnt) { int max(0); int cnt(0); int min(9999); for(int bar_ind(0); bar_ind < bar_cnt; ++bar_ind) { if(bars[bar_ind] == 0) { // on 0 bar height, reset count & min height. cnt = 0; min = 9999; } else { // with each new bar height ... // increment bar count and maintain the min height. ++cnt; if(bars[bar_ind] < min) { min = bars[bar_ind]; } } // after each iteration, calculate max rect & // swap if it greater than previous max. int tmp = cnt * min; if (tmp > max) { max = tmp; } } return max; } // Function to max rectangle in binary matrix formed by 1. int find_max_rect(int mtx[][6], int rows, int cols) { int bar_sum_row[rows]; // copy first row ... for(int col_ind(0); col_ind < cols; ++col_ind) { bar_sum_row[col_ind] = mtx[0][col_ind]; } int max_rect = get_max_frm_row(bar_sum_row, cols); std::cout << "row index 0 max = " << max_rect << std::endl; for(int row_ind(1); row_ind < rows; ++row_ind) { for(int col_ind(0); col_ind < cols; ++col_ind) { if(mtx[row_ind][col_ind] == 0) { bar_sum_row[col_ind] = 0; } else { bar_sum_row[col_ind] += mtx[row_ind][col_ind]; } } int cur_max = get_max_frm_row(bar_sum_row, cols); if(cur_max > max_rect) { max_rect = cur_max; } std::cout << "row index " << row_ind << " max = " << max_rect << std::endl; } return max_rect; } int main() { int mtx[4][6] = { { 1, 0, 0, 1, 1, 1}, { 1, 0, 1, 1, 0, 1}, { 0, 1, 1, 1, 1, 1}, { 0, 0, 1, 1, 1, 1} }; int max_rect = find_max_rect(mtx, 4/*row_cnt*/, 6/*col_cnt*/); std::cout << "\nMax rect with 1 is " << max_rect << std::endl; return 0; } // source : https://www.youtube.com/watch?v=g8bSdXCG-lA
true
1bfbb0317df7b494d5b0fc9dadf0780366054c85
C++
bahareh-farhadi/C-Projects
/OneDrive/Desktop/Online Courses/C++ Projects/Online Orders Management System/Online Orders Management System/product.h
UTF-8
389
2.828125
3
[]
no_license
#pragma once #include <string> #include <iostream> using namespace std; class product { protected: int id; string name, seller,shipping,ship_date; double price; public: product(int id,string name,string seller,string shipping,string ship_date,double price); string get_name(); string get_seller(); string get_ship_date(); double get_price(); void display_prod(); ~product(); };
true
1bbb97f3ad53072a11d1837b36cda64c4532ad3a
C++
Shahin15-1573/mycode-arena
/Uva-OJ/Potentiometers.cpp
UTF-8
2,275
2.703125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <iostream> #include <algorithm> using namespace std; #define LI long int #define LLI long long int #define ULL unsigned long long #define memo(array, value) memset(array, value, sizeof(array)) #define MAX 200020 int arr[MAX], tree[MAX*4], n; void push_korlam(int node, int left, int right){ //if(tree[left] > tree[right]) tree[node] = tree[right]; //else tree[node] = tree[left]; tree[node] = tree[left] + tree[right]; } void segmant_tree (int node, int begin, int end){ int left, right, mid; if (begin == end){ tree[node] = arr[begin]; return; } left = node*2; right = (node*2) + 1; mid = (begin+end) / 2; segmant_tree(left, begin, mid); segmant_tree(right, mid+1, end); push_korlam(node, left, right); } void update(int node, int begin, int end, int p, int val){ int left, right, mid; if (begin == end){ tree[node] = val; return; } left = node*2; right = (node*2) + 1; mid = (begin+end) / 2; if (p <= mid) update(left, begin, mid, p, val); else update(right, mid+1, end, p, val); push_korlam(node, left, right); } int quary (int node, int begin, int end, int a, int b){ int left, right, mid, p1, p2, sum = 0; //if (a > end || b < begin) return 0; if (begin >= a && end <= b) return tree[node]; left = node*2; right = (node*2) + 1; mid = (begin+end) / 2; if (a <= mid) sum += quary(left, begin, mid, a, b); if (b > mid) sum += quary(right, mid+1, end, a, b); // p1 = quary(left, begin, mid, a, b); // p2 = quary(right, mid+1, end, a, b); return sum; } int main(){ int x, y, cs=1, i, j, ans, tmp, cnt; char ch[10]; while (scanf ("%d", &n) == 1 && n){ if (cs != 1) puts (""); printf ("Case %d:\n", cs++); memo (tree, 0); for (i = 1; i <= n; i++) scanf ("%d", &arr[i]); segmant_tree(1, 1, n); while (scanf ("%s", ch), strcmp("END", ch)){ scanf ("%d%d", &x, &y); if (ch[0] == 'S') update(1, 1, n, x, y); else{ ans = quary(1, 1, n, x, y); printf ("%d\n", ans); } } } return 0; }
true
e7c32ca003a77acd6d9fee07b64e2b11478716e5
C++
Fytch/Glossy
/src/window.cpp
UTF-8
5,688
2.546875
3
[ "MIT" ]
permissive
#include <glossy/window.hpp> #include <glossy/default_scene.hpp> #include <glossy/json2glsl.hpp> #include <glossy/stopwatch.hpp> #include <glossy/util.hpp> #include <string> #include <stdexcept> #include <cmath> #include <fstream> #include <iostream> void glossy::window::update_resolution( unsigned int width, unsigned int height ) { m_size.x = width; m_size.y = height; m_shader.setUniform( "resolution", sf::Glsl::Vec2{ static_cast< float >( m_size.x ), static_cast< float >( m_size.y ) } ); } sf::Vector3f glossy::window::get_position() const { return m_pos; } void glossy::window::set_position( sf::Vector3f const& p ) { m_pos = p; m_shader.setUniform( "pos", m_pos ); } void glossy::window::move( sf::Vector3f const& v ) { set_position( get_position() + v ); } void glossy::window::rotate_x( float angle ) { m_alpha += angle; if( m_alpha < 0.0f ) m_alpha += two_pi; if( m_alpha >= two_pi ) m_alpha -= two_pi; } void glossy::window::rotate_y( float angle ) { m_beta += angle; m_beta = clamp( deg2rad( -90 ), deg2rad( 90 ), m_beta ); } void glossy::window::update_camera() { const float sin_x = std::sin( m_alpha ); const float cos_x = std::cos( m_alpha ); const float sin_y = std::sin( m_beta ); const float cos_y = std::cos( m_beta ); m_at.x = sin_x * cos_y; m_at.y = sin_y; m_at.z = cos_x * cos_y; m_up.x = sin_x * -sin_y; m_up.y = cos_y; m_up.z = cos_x * -sin_y; m_right = cross( m_up, m_at ); m_shader.setUniform( "at", m_at ); m_shader.setUniform( "up", m_up ); m_shader.setUniform( "right", m_right ); } glossy::window::window( int argc, char** argv ) { if( argc > 2 ) throw std::runtime_error{ "too many program options provided" }; if( !sf::Shader::isAvailable() ) throw std::runtime_error{ "sf::Shader not available!" }; std::string code; if( argc == 2 ) code = json2glsl( argv[ 1 ] ); else code = json2glsl( default_scene ); if( !m_shader.loadFromMemory( code, sf::Shader::Fragment ) ) { std::ofstream dump{ "dump.log", std::ofstream::trunc }; dump << code; throw std::runtime_error{ "unable to process shader (see dump.log)" }; } const auto desktop = sf::VideoMode::getDesktopMode(); update_resolution( desktop.width * 2 / 3, desktop.height * 2 / 3 ); m_window.create( sf::VideoMode{ static_cast< unsigned >( m_size.x ), static_cast< unsigned >( m_size.y ) }, m_title, sf::Style::Default, sf::ContextSettings{ 0, 0, 0, 3, 0 } ); m_window.setView( sf::View{ { 0, 1, 1, -1 } } ); m_window.setMouseCursorVisible( false ); m_window.setMouseCursorGrabbed( true ); sf::Mouse::setPosition( m_size / 2, m_window ); m_window.setKeyRepeatEnabled( false ); // m_window.setVerticalSyncEnabled( true ); set_position( { 0, 1, 0 } ); update_camera(); } int glossy::window::run() { stopwatch global_timer; global_timer.start(); stopwatch frame_timer; frame_timer.start(); stopwatch fps_timer; fps_timer.start(); int frames = 0; bool forwards = false; bool left = false; bool backwards = false; bool right = false; bool up = false; bool down = false; while( m_window.isOpen() ) { ++frames; const auto fps_elapsed = fps_timer.elapsed_s_flt(); if( fps_elapsed >= 1.0 ) { fps_timer.start(); m_window.setTitle( m_title + ( " - " + std::to_string( static_cast< unsigned >( frames / fps_elapsed + 0.5 ) ) + " FPS" ) ); frames = 0; } for( sf::Event event; m_window.pollEvent( event ); ) { bool pressing = false; switch( event.type ) { case sf::Event::Closed: m_window.close(); break; case sf::Event::Resized: update_resolution( event.size.width, event.size.height ); break; case sf::Event::KeyPressed: pressing = true; case sf::Event::KeyReleased: switch( event.key.code ) { case sf::Keyboard::W: case sf::Keyboard::Up: forwards = pressing; break; case sf::Keyboard::A: case sf::Keyboard::Left: left = pressing; break; case sf::Keyboard::S: case sf::Keyboard::Down: backwards = pressing; break; case sf::Keyboard::D: case sf::Keyboard::Right: right = pressing; break; case sf::Keyboard::Space: up = pressing; break; case sf::Keyboard::LControl: down = pressing; break; case sf::Keyboard::F12: { sf::Texture tex; tex.create( m_size.x, m_size.y ); tex.update( m_window ); tex.copyToImage().saveToFile( "scrot.png" ); } default: ; // -Wswitch } break; case sf::Event::MouseMoved: if( m_window.hasFocus() ) { const sf::Vector2i center = m_size / 2; const int delta_x = -( center.x - event.mouseMove.x ); const int delta_y = center.y - event.mouseMove.y; constexpr float factor = 1.0f / 1000.0f; if( delta_x ) rotate_x( delta_x * factor ); if( delta_y ) rotate_y( delta_y * factor ); if( delta_x || delta_y ) { update_camera(); sf::Mouse::setPosition( center, m_window ); } } break; default: ; // -Wswitch } } const auto frame_elapsed = frame_timer.elapsed_s_flt(); frame_timer.start(); if( forwards || left || backwards || right || up || down ) { sf::Vector3f offset = m_at * static_cast< float >( forwards - backwards ) + m_right * static_cast< float >( right - left ) + m_up * static_cast< float >( up - down ); float speed = 5; if( sf::Keyboard::isKeyPressed( sf::Keyboard::LShift ) ) speed *= 3; speed *= frame_elapsed; offset *= speed; move( offset ); } m_shader.setUniform( "global_time", static_cast< float >( global_timer.elapsed_s_flt() ) ); m_window.clear(); m_window.draw( m_shape, &m_shader ); m_window.display(); } return 0; }
true
07f17aebed1998a3b9efa4e42a91063b7e8c2342
C++
IkerST/practicas_c
/mayor_suma_30.cpp
UTF-8
1,051
3.546875
4
[ "MIT" ]
permissive
#include "stdio.h" #include "iostream" int main() { int inp; int end=0; int arr[30]; int sum=0; int max=0; // Llenar variable con 0s for (int s=0; s < 30; s++) { arr[s]=0; } system("clear"); std::cout << "\n\t\033[1mBienvenido, este programa sumara 30 numeros o menos y \n"; std::cout << "\n\tmostrara el mayor\033[0m\n"; do { std::cout << "\nIntroduzca un numero mayor a \033[1m0\033[0m, o \033[1m0\033[0m para salir: "; std::cin >> inp; if ( inp != 0 && end < 30) { end++; arr[30-end]=inp; } else if ( inp != 0 ) { for (int a=0; a < 29; a++) { arr[a-1]=arr[a]; } arr[29]=inp; } } while ( inp != 0 ); for (int i=0; i < 30; i++) { if (arr[i] > max) { max=arr[i]; } sum+=arr[i]; } std::cout << "\nLa suma es: \033[1;32m" << sum << "\033[0m\n"; std::cout << "\nEl mayor es: \033[1;32m" << max << "\033[0m\n"; return 0; }
true
1d1d436edbbbcb1d65e7593a9a1ea9094ef7728d
C++
spjmurray/AoC2016
/c++/11a.cc
UTF-8
4,786
3.34375
3
[]
no_license
#include <set> #include <list> #include <algorithm> #include <iostream> #include <vector> // Constants identifying which element in an ElementPair we are refering to const unsigned int GENERATOR = 0; const unsigned int CHIP = 1; // A pair of element objects i.e. generator and chip typedef std::pair<unsigned int, unsigned int> ElementPair; // A collection on element objects and pairs typedef std::vector<ElementPair> Elements; class State { public: State(const Elements& elements, unsigned int floor = 0, unsigned int distance = 0) : elements(elements), floor(floor), distance(distance), guid(-1) {} // The Guid should be a globally unique state identifier with quick comparison long getGuid() { if(guid >= 0) { return guid; } // Colate elements into an array of generator/chip nibbles std::vector<unsigned int> pairs; for(auto i = elements.begin(); i != elements.end(); i++) pairs.emplace_back((*i).first << 4 | (*i).second); // Sort so that we only care about relative positions of generators and chips std::sort(pairs.begin(), pairs.end()); // Create the GUID state by concatenating the floor and sorted relative positions guid = floor; for(auto i = pairs.begin(); i != pairs.end(); i++) { guid <<= 8; guid |= *i; } return guid; } // Get the distance travelled unsigned int getDistance() const { return distance; } // Is this state the final one? bool done() const { for(auto i = elements.begin(); i != elements.end(); i++) if((*i).first != 3 || (*i).second != 3) return false; return true; } // Given a reference to a state list, populate it with valid next moves void getMoves(std::list<State*>& moves) const { // Get the set of generators and chips on the current floor std::vector<std::pair<unsigned int, unsigned int>> gc; unsigned int index = 0; for(unsigned int i = 0; i < elements.size(); i++) { if(elements[i].first == floor) gc.emplace_back(i, GENERATOR); if(elements[i].second == floor) gc.emplace_back(i, CHIP); } // Move up and down int movement[] = {1, -1}; for(unsigned int i = 0; i < sizeof(movement) / sizeof(int); i++) { // Discard illegal floor moves int new_floor = floor + movement[i]; if(new_floor < 0 || new_floor >= 4) continue; // Do all single generator movements for(auto j = gc.begin(); j != gc.end(); j++) { State* s = new State(elements, new_floor, distance + 1); s->move((*j).first, (*j).second, movement[i]); if(s->valid()) moves.push_back(s); else delete s; // For each permutation of pairs auto k = j; k++; for(; k != gc.end(); k++) { s = new State(elements, new_floor, distance + 1); s->move((*j).first, (*j).second, movement[i]); s->move((*k).first, (*k).second, movement[i]); if(s->valid()) moves.push_back(s); else delete s; } } } } private: // Move an element object the specified direction void move(unsigned int element, unsigned int object, int magnitude) { if(object == GENERATOR) elements[element].first += magnitude; else elements[element].second += magnitude; } // Is the state valid? bool valid() const { for(auto i = elements.begin(); i != elements.end(); i++) { if((*i).first == (*i).second) continue; for(auto j = elements.begin(); j != elements.end(); j++) if((*i).second == (*j).first) return false; } return true; }; private: Elements elements; unsigned int floor; unsigned int distance; long guid; }; int main(void) { // Initial problem state std::vector<ElementPair> input = {{0,0},{0,1},{0,1},{2,2},{2,2}}; State* state = new State(input); // A FIFO queue for our breadth-first search (O(1) insert and delete) std::list<State*> queue; queue.push_back(state); // A set of seen node GUIDs (O(log N) search) std::set<unsigned long> seen; seen.insert(state->getGuid()); // Process the FIFO queue in order... State* u; while(!queue.empty()) { // Select the current node u = queue.front(); queue.pop_front(); // Simulation complete, break out if(u->done()) break; // Get a list of valid moves std::list<State*> moves; u->getMoves(moves); // For each state if we've not seen it, queue it up and mark seen for(auto i = moves.begin(); i != moves.end(); i++) { if(seen.find((*i)->getGuid()) == seen.end()) { queue.push_back(*i); seen.insert((*i)->getGuid()); } } } std::cout << u->getDistance() << std::endl; return 0; }
true
9c8181c89fea82d244b67de88a6c54e56a3c6d46
C++
jazcap53/memModel
/pageTable.h
UTF-8
2,667
2.765625
3
[]
no_license
#ifndef AAJ_PAGE_TABLE_H #define AAJ_PAGE_TABLE_H #include <array> #include <algorithm> #include <cstdint> #include "fileShifter.h" #include "myMemory.h" #include "aJTypes.h" #include "aJUtils.h" namespace MemModel { /******************** There is one PgTabEntry for each slot in the std::array PageTable::PgTab. Each PgTabEntry corresponds to a page in memory, and holds: -- the number of the disk block whose data is currently held in that page, -- the index of the slot in memory occuped by that page, and -- the time the page was last accessed *********************/ // Note: we want move construct and move assign for PgTabEntry, so that // make_heap() in PageTable class will be as efficient as possible. struct PgTabEntry { PgTabEntry() : PgTabEntry(0UL, 0U, 0UL) {} PgTabEntry(bNum_t bN, uint32_t mSIx, uint64_t aT) : blockNum(bN), memSlotIx(mSIx), accTime(aT) {} PgTabEntry(const PgTabEntry &) = default; PgTabEntry(PgTabEntry &&) = default; PgTabEntry &operator=(const PgTabEntry &) = default; PgTabEntry &operator=(PgTabEntry &&) = default; bNum_t blockNum; uint32_t memSlotIx; uint64_t accTime; }; bool pTEComp(const PgTabEntry &l, const PgTabEntry &r); // comparator /******************** The page table is maintained as a min heap, ordered by the pTEComp function above. The min heap is held in private std::array<> member pgTab. Private member heapSize tracks the number of array entries that are currently part of the heap. ********************/ class PageTable { friend class MemMan; PageTable &operator=(const PageTable &) = delete; void updateATime(uint32_t loc); void resetATime(uint32_t loc); PgTabEntry &getPgTabEntry(uint32_t loc) { return pgTab[loc]; } const PgTabEntry &getPgTabEntry(uint32_t loc) const { return pgTab[loc]; } uint32_t getPgTabSlotFrmMemSlot(uint32_t memSlot) const; bool isLeaf(uint32_t memSlot) const { return memSlot >= heapSize / 2; } void heapify(); uint32_t getHeapSize() const { return heapSize; } void doPopHeap(PgTabEntry &popped); void doPushHeap(PgTabEntry newEntry); bool checkHeap() const; void setPgTabFull() { pgTabFull = true; } bool getPgTabFull() const { return pgTabFull; } void print() const; uint32_t heapSize = 0U; bool pgTabFull = false; std::array<PgTabEntry, u32Const::NUM_MEM_SLOTS> pgTab; mutable Tabber tabs; }; } #endif
true
4c64a7f995d27ca243d6eb93061084c65c6f3770
C++
xlnx/maybe-cc
/ir-gen/src/type/type.cc
UTF-8
3,025
2.59375
3
[]
no_license
#include "type.h" #include "def.h" TypeView const &TypeView::getVoidPtrTy() { static auto s_v = ( [] { Json::Value ast; return TypeView( std::make_shared<QualifiedType>( DeclarationSpecifiers() .add_type( QualifiedType( std::make_shared<mty::Void>() ), ast ) .into_type_builder( ast ) .add_level( std::make_shared<mty::Pointer>( mty::Void().type ) ) .build() ) ); } )(); return s_v; } TypeView const &TypeView::getBoolTy() { static auto s_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 1, false ) ); static auto s_v = TypeView( s_ty ); return s_v; } TypeView const &TypeView::getCharTy( bool is_signed ) { static auto s_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 8, true ) ); static auto u_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 8, false ) ); static auto s_v = TypeView( s_ty ); static auto u_v = TypeView( s_ty ); return is_signed ? s_v : u_v; } TypeView const &TypeView::getShortTy( bool is_signed ) { static auto s_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 16, true ) ); static auto u_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 16, false ) ); static auto s_v = TypeView( s_ty ); static auto u_v = TypeView( s_ty ); return is_signed ? s_v : u_v; } TypeView const &TypeView::getIntTy( bool is_signed ) { static auto s_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 32, true ) ); static auto u_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 32, false ) ); static auto s_v = TypeView( s_ty ); static auto u_v = TypeView( s_ty ); return is_signed ? s_v : u_v; } TypeView const &TypeView::getLongTy( bool is_signed ) { static auto s_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 64, true ) ); static auto u_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 64, false ) ); static auto s_v = TypeView( s_ty ); static auto u_v = TypeView( s_ty ); return is_signed ? s_v : u_v; } TypeView const &TypeView::getLongLongTy( bool is_signed ) { static auto s_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 64, true ) ); static auto u_ty = std::make_shared<QualifiedType>( std::make_shared<mty::Integer>( 64, false ) ); static auto s_v = TypeView( s_ty ); static auto u_v = TypeView( s_ty ); return is_signed ? s_v : u_v; } TypeView const &TypeView::getFloatTy() { static auto s_ty = std::make_shared<QualifiedType>( std::make_shared<mty::FloatingPoint>( 32 ) ); static auto s_v = TypeView( s_ty ); return s_v; } TypeView const &TypeView::getDoubleTy() { static auto s_ty = std::make_shared<QualifiedType>( std::make_shared<mty::FloatingPoint>( 64 ) ); static auto s_v = TypeView( s_ty ); return s_v; } TypeView const &TypeView::getLongDoubleTy() { static auto s_ty = std::make_shared<QualifiedType>( std::make_shared<mty::FloatingPoint>( 128 ) ); static auto s_v = TypeView( s_ty ); return s_v; }
true
0493263f99519076f51f129b1667bbdbaaa5b897
C++
stevebraveman/Code
/LUOGU/数列分段Section I.cpp
MacCentralEurope
355
2.546875
3
[]
no_license
//зֶSection I.cpp #include<iostream> using namespace std; int n,m,a[100005]; int main(){ cin>>n>>m; for(int i=1;i<=n;i++){ cin>>a[i]; } int tot=0; int b=0; for(int i=1;i<=n;i++){ b+=a[i]; if(b==m){ tot++; b=0; continue; } if(b>m){ b=0; b+=a[i]; tot++; } if(i==n&&b<m){ tot++; } } cout<<tot; }
true
cb6ac6e4c34050f9a462b5954f774f43587e200d
C++
jayson-adriano/Espressif_ESP32-Scale
/LegacyVersions/ESP32_Example/ESP32_Scale/ESP32_Scale.ino
UTF-8
4,344
2.640625
3
[ "LicenseRef-scancode-public-domain" ]
permissive
//PROJECT LIBRA SCALE MEASUREMENT SYSTEM //CODE BY MICHAEL KLOPFER + Calit2 Team (2017) #include <Hx711.h> //Load Cell A/D (HX711 library) #include <Adafruit_TLC59711.h> //12 Ch LED Controller, uses SPI only MOSI and CLK #include <SPI.h> //Constants #define portTICK_PERIOD_MS 10 //Interface Assignments #define HX711CLK 19 #define HX711DA 18 #define PIEZO 4 #define TAREBTN 21 #define TLC59711CLK 23 #define TLC59711DA 5 //Peripheral Setup #define NUM_TLC59711 1 // How many boards do you have chained? (Only 1 in this example) //Define Objects Hx711 scale(HX711DA, HX711CLK); // Object for scale - Hx711.DOUT - pin #A2 & Hx711.SCK - pin #A3 ---this sensor uses a propriatary synchronus serial communication, not I2C Adafruit_TLC59711 tlc = Adafruit_TLC59711(NUM_TLC59711, TLC59711CLK, TLC59711DA); //---------------------------------- //Global Variables float calibrated_scale_weight_g=0; //Holding variable for weight float calibrated_scale_weight_g_1 = 0; //For Averaging float calibrated_scale_weight_g_2 = 0; //For Averaging float calibrated_scale_weight_g_3 = 0; //For Averaging float tare_subtraction_factor=0; //When TARE is processed, this value is subtracted for the displayed weight //Initial Calibration Factors and offsets float scale_gain=-.0022103; //Initial Sensor Calibration Offset Value (fill in the `ratio` value here) [ratio = (w - offset) / 1000] where W is a known weight, say 1000 grams float scale_offset=36820; //Initial Sensor Calibration Offset Value (fill in the `offset` value here) float inherent_offset=33781; //Weight of unloaded sensor //Piezo Parameters int freq1 = 2000; int freq2 = 125; int dutyCycle = 50; int channel = 0; int resolution = 8; int piezoch = 3; //------------------------------------ //--------------------------------------------------------- void setup() { Serial.begin(115200); //begin Serial for LCD //User Interface Buttons Initialize pinMode(TAREBTN, INPUT_PULLUP); //Tare Button pinMode(PIEZO, OUTPUT); //Select Button digitalWrite(PIEZO, LOW); //Initalize Piezo ledcSetup(channel, freq1, resolution); ledcAttachPin(4, channel); //Initialize Piezo Driver tlc.begin(); tlc.write(); //Set the offset and gain values scale.setScale(scale_gain); //Gain scale.setOffset(scale_offset); //Offset Serial.println("****************END OF BIOS MESSAGES****************"); Serial.println(""); } //--------------------------------------------------------- void loop() { //Read scale Value - rememberm this can have multiple calls that are averaged, check the library for the HX711 if this is not running properly! calibrated_scale_weight_g_1=scale.getGram() - inherent_offset; //subtract inherent offset from pan weight (Read 1) calibrated_scale_weight_g_2=scale.getGram() - inherent_offset; //subtract inherent offset from pan weight (Read 2) calibrated_scale_weight_g_3=scale.getGram() - inherent_offset; //subtract inherent offset from pan weight (Read 3) calibrated_scale_weight_g = (calibrated_scale_weight_g_1 + calibrated_scale_weight_g_2 + calibrated_scale_weight_g_3)/3; //return mean average from 3 readings if (digitalRead(TAREBTN) != 0) //Look for Tare button Press { tare_subtraction_factor = calibrated_scale_weight_g; } calibrated_scale_weight_g = calibrated_scale_weight_g - tare_subtraction_factor; //Calculate weight //Serial.println(scale.averageValue()); //output of value prior to gram calculation Serial.print("Weight in grams: "); Serial.println(calibrated_scale_weight_g); Serial.print("Weight in Oz: "); Serial.println(calibrated_scale_weight_g*0.035274); Serial.println(); //Demo lights - state 1 (all ON) tlc.setLED(0, 65534, 65534, 65534); tlc.write(); tlc.setLED(1, 65534, 65534, 65534); tlc.write(); tlc.setLED(2, 65534, 65534, 65534); tlc.write(); tlc.setLED(3, 65534, 65534, 65534); tlc.write(); //Make a Sound! //ledcWriteTone(channel, freq2); vTaskDelay(1000 / portTICK_PERIOD_MS); //Demo lights - state 1 (all Off) tlc.setLED(0, 0, 0, 0); tlc.write(); tlc.setLED(1, 0, 0, 0); tlc.write(); tlc.setLED(2, 0, 0, 0); tlc.write(); tlc.setLED(3, 0, 0, 0); tlc.write(); //Make a Sound! //ledcWriteTone(channel, freq1); //ledcWrite(channel, dutyCycle); }
true
c84dc8bb5c64979b730b94c4cc187a38807641b7
C++
liuxiangbin/LeetCode
/012_IntegerToRoman.cpp
UTF-8
1,195
4.09375
4
[]
no_license
/* Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. */ /* 关于罗马数字的几条注意事项: 1、基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。 2、不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。 3、V 和X 左边的小数字只能用Ⅰ。 4、L 和C 左边的小数字只能用X。 5、D 和M 左边的小数字只能用C。 */ class Solution { public: string intToRoman(int num) { string res; if(num < 1) return res; string roman[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int dec[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; while(num > 0){ int i = 0; while(num<dec[i]) ++i; res += roman[i]; num -= dec[i]; } return res; } };
true
40b487f5c9837abd2223ebb41e87cfc5329b3ee1
C++
cmgp/LabProgAvan0
/PA_Lab_00_Ejercicio2/source/main.cpp
UTF-8
287
2.734375
3
[]
no_license
#include <iostream> #include "a.hpp" #include "b.hpp" #include "c.hpp" int main() { A a(65); B b(66); C c(67); a.set_b(&b); a.set_c(&c); b.set_a(&a); b.set_c(&c); c.set_a(&a); c.set_b(&b); std::cout << a << "\n" << b << "\n" << c << "\n"; }
true
43cc4bfe9c9fd0de208ed10a3a58c37fb1f79319
C++
scopchanov/SO-BoldMatch
/src/MainWindow.cpp
UTF-8
1,160
2.84375
3
[]
no_license
#include "MainWindow.h" #include <QVBoxLayout> #include <QLineEdit> #include <QLabel> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), myString("Today is today") { auto *widget = new QWidget(this); auto *layoutMain = new QVBoxLayout(widget); auto *edit = new QLineEdit(this); auto *label = new QLabel(myString, this); layoutMain->addWidget(edit); layoutMain->addWidget(label); layoutMain->addStretch(); connect(edit, &QLineEdit::textEdited, [this, label](const QString &text){ setBoldForMatching(text, label); }); setCentralWidget(widget); resize(200, 100); } void MainWindow::setBoldForMatching(const QString &p_text, QLabel *label) const { QRegExp regExp(p_text, Qt::CaseInsensitive, QRegExp::RegExp); QString str = myString; if (p_text.isEmpty()) { label->setText(myString); return; } int count = 0; int pos = 0; QStringList matches; while ((pos = regExp.indexIn(str, pos)) != -1) { ++count; pos += regExp.matchedLength(); matches.append(regExp.capturedTexts()); } foreach (const QString &match, matches) { str.replace(match, "<b>" + match + "</b>"); } label->setText(str); }
true
0a960ca9bab2e0618951708aeaf048b72b183d46
C++
langrange/LeetCode
/String/ExpressionMatching/ExpressionMatching/ExpressionMatching.cpp
WINDOWS-1252
760
3.890625
4
[]
no_license
/* Input : original:"good"; test:"go*" Output : 1 or 0 Interfacebool isMatch(const char *s, const char *p) Date: 12/16/2017 */ #include <iostream> using namespace std; bool isMatch(const char *s, const char *p); int main() { const char str[] = "good"; const char p[] = "go*"; cout << isMatch(str, p) << endl ; return 0; } bool isMatch(const char *s, const char *p){ //жǷǿַ if (*p == '\0') return *s == '\0'; if (*(p + 1) != '*'){ if ((*p == *s) || (*p == '.'&&*s != '\0')) return isMatch(s + 1, p + 1); else return false; } else{ if (*p == *s || (*p == '.'&&*s != '\0')) return isMatch(s + 1, p); else{ return isMatch(s, p + 2); } } }
true
2fa970a91f089bea3c7f7daa0fc91ae6fc7d57ba
C++
zuzg13/numerical_methods
/lab03/main.cpp
UTF-8
4,319
2.625
3
[]
no_license
#include <iostream> #include <cmath> #include <time.h> #include "nrutil.c" #include "gaussj.c" #define n 1000 #define m 5 #define max(X,Y) ((X)>(Y)? (X):(Y)) #define min(X,Y) ((X)<(Y)? (X):(Y)) #define abs(X) ((X)>0? (X):-(X)) void matrixvector(double**A, double*x, double*y); double scalar(double *a, double *b, bool flagt=false); void addvector(double *a, double *b, double *d, double c); int main(){ double **A = new double *[n]; double *b = new double[n]; double *x = new double[n]; double *r = new double[n]; double *tmp = new double[n]; double *tmp2 = new double[n]; double alpha =0.; clock_t start, end; double time; FILE *f1 = fopen("zad_a.dat", "w"); FILE *f2 = fopen("zad_b.dat", "w"); //###################################################################################################### // X0 = 0 for(int i=0;i<n;i++) A[i] = new double[n]; for(int i=0;i<n;i++) { b[i]=i+1; x[i]=0.; r[i]=0.; tmp[i]=0.; for(int j=0;j<n;j++) { if(abs(i-j)<=m) A[i][j]=1./(1.+ abs(i-j)); else A[i][j]=0.; } } int k=1; double norma1=0.; double norma2=0.; start=clock(); do{ matrixvector(A, x, tmp); //tp=A*x addvector(b, pom, r, -1); //r = b - tmp = b - A*x matrixvector(A, r, tmp2); // tmp = A *r = A *( b-A*x) alpha = scalar(r,r,true) / scalar(r, tmp2, true); addvector(x, r, x, alpha); // x = xx + alpha*r norma1 = sqrt(scalar(r,r,true)); norma2 = sqrt(scalar(x,x,true)); fprintf(f1, "%d %lf %lf %lf\n", k, norma1, alpha, norma2); k++; }while(norma1>1e-6); end=clock(); time= static_cast<double>(end-start)/ static_cast<double>(CLOCKS_PER_SEC); printf("time 1: %lf\n", time); delete [] tmp; delete [] tmp2; //###################################################################################################### // X0 = 1 tmp=new double[n]; tmp2=new double[n]; for(int i=0;i<n;i++) { x[i]=1.; r[i]=0.; tmp[i]=0.; } k=1; norma1=0.; norma2=0.; start=clock(); do{ matrixvector(A, x, tmp); //tmp=A*x addvector(b, tmp, r, -1); //r = b - tmp = b - A*x matrixvector(A, r, tmp2); // tmp = A *r = A *( b-A*x) alpha = scalar(r,r,true) / scalar(r, tmp2, true); addvector(x, r, x, alpha); // x = xx + alpha*r norma1 = sqrt(scalar(r,r,true)); norma2 = sqrt(scalar(x,x,true)); fprintf(f2, "%d %lf %lf %lf\n", k, norma1, alpha, norma2); k++; }while(norma1>1e-6); end=clock(); time = static_cast<double>(end-start)/ static_cast<double>(CLOCKS_PER_SEC); printf("time 2: %lf\n", time); //###################################################################################################### // gaussjc float **a = matrix(1, n, 1, n); float **d = matrix(1, n, 1, 1); for(int i=1;i<n+1;i++) d[i][0]=i+1; for(int i=1;i<n+1;i++) { for(int j=1;j<n+1;j++) { if(abs(i-j)<=m) a[i][j]=1./(1.+(abs(i-j))); else a[i][j]=0.; } } start=clock(); gaussj(a,n,d,1); end=clock(); time= static_cast<double>(end-start)/static_cast<double>(CLOCKS_PER_SEC); printf("time 3: %lf\n", time); for(int i=0;i<n;i++) { delete[] A[i]; } delete[] A; delete[] x; delete[] b; delete[] r; delete[] tmp; delete[] tmp2; free_matrix(a, 1,n,1,n); free_matrix(d, 1,n,1,1); } void matrixvector(double**A, double*x, double*y) { int jmin, jmax; for(int i=0;i<n;i++){ jmin=max(0,i-m); jmax=min(i+m,n-1); y[i]=0; for(int j=jmin;j<=jmax;j++) y[i]+=A[i][j]*x[j]; } } double scalar(double *a, double *b, bool flagt=false) { double s=0.; if(flagt) { for(int i=0;i<n;i++) s+=a[i]*b[i]; } else { for(int i=0;i<n;i++) s+=b[i]*a[n-1-i]; } return s; } void addvector(double *a, double *b, double *d, double c) { for(int i=0;i<n;i++) { d[i] = a[i] + c*b[i]; } }
true
229260013e0cda582d0815b08dd3160bfe17a940
C++
qzi/cgame
/CGame/src/ctimer.cpp
UTF-8
525
2.609375
3
[]
no_license
#include "ctimer.h" #include <gl/glut.h> // initialize singleton CTimer *CTimer::m_singleton = 0; unsigned long CTimer::GetTimeMSec( void ) { return glutGet( GLUT_ELAPSED_TIME ); } void CTimer::Initialize( void ) { m_currentTime = GetTimeMSec(); m_lastTime = 0; } void CTimer::Update( void ) { m_lastTime = m_currentTime; m_currentTime = GetTimeMSec(); } float CTimer::GetFps( void ) { return ((float)1000.0 / (float)(m_currentTime - m_lastTime)); } unsigned long CTimer::GetTime( void ) { return m_currentTime; }
true
11c5b57995e21441a87a7af6570e774c60ee9161
C++
wilcroft/starmap-cli
/star.cpp
UTF-8
7,821
3.109375
3
[]
no_license
#include "star.h" /************************************** * PRIVATE FUNCTIONS **************************************/ void Star::setX(int newX){ x = newX; } void Star::setY(int newY){ y = newY; } void Star::addPlanets(std::mt19937* mt){ std::uniform_real_distribution<> dist(0,100); double pct; double thresh; switch (type){ case (TYPE_RED): // M thresh = 22; for (int i=0; i<5; i++){ pct = dist(*mt); if (pct<thresh){ //HIT planet[i]=new Planet(mt, i, this); thresh = thresh*0.8; numPlanets++; } else{ planet[i] = nullptr; thresh=thresh*1.05; } } break; case (TYPE_ORANGE): // K thresh = 20; for (int i=0; i<5; i++){ pct = dist(*mt); if (pct<thresh){ //HIT planet[i] = new Planet(mt, i, this); thresh = thresh/4; numPlanets++; } else{ planet[i] = nullptr; thresh=thresh+18; } } break; case (TYPE_YELLOW): // G thresh = 20; for (int i=0; i<5; i++){ pct = dist(*mt); if (pct<thresh){ //HIT planet[i] = new Planet(mt, i, this); thresh = thresh/3; numPlanets++; } else{ planet[i] = nullptr; thresh=thresh+15; } } break; case (TYPE_WHITE): // F thresh = 40; for (int i=0; i<5; i++){ pct = dist(*mt); if (pct<thresh){ //HIT planet[i]=new Planet(mt, i, this); thresh = thresh*.6; numPlanets++; } else{ planet[i] = nullptr; thresh=thresh+10; } } break; case (TYPE_BLUEWHITE): // A thresh = 1; for (int i=0; i<5; i++){ pct = dist(*mt); if (pct<thresh){ //HIT planet[i]=new Planet(mt, i, this); thresh = thresh*0.8; numPlanets++; } else{ planet[i] = nullptr; thresh=thresh*3.1; } } break; case (TYPE_BLUE): // B thresh = 2; for (int i=0; i<5; i++){ pct = dist(*mt); if (pct<thresh){ //HIT planet[i]=new Planet(mt, i, this); //thresh = thresh*0.9; thresh += 4*i+6; numPlanets++; } else{ planet[i] = nullptr; //thresh=thresh*2.5; thresh+=2*(i+2)*(i+2); } } break; case (TYPE_BLUEVIOLET): // O default: for (int i=0; i<5; i++) { planet[i] = nullptr; } } } /************************************** * PUBLIC FUNCTIONS **************************************/ //Constructor Star::Star (std::mt19937* mt) { double pct; std::uniform_real_distribution<> dist(0,100); std::uniform_int_distribution<> plr (0,8); pct = dist (*mt); if (pct < 76.45) type = TYPE_RED; else if (pct < 88.55) type = TYPE_ORANGE; else if (pct < 96.19) type = TYPE_YELLOW; else if (pct < 99.24) type = TYPE_WHITE; else if (pct < 99.87) type = TYPE_BLUEWHITE; else if (pct < 99.995) type = TYPE_BLUE; else type = TYPE_BLUEVIOLET; pct = dist(*mt); if (pct < 85) size = DWARF; // The following Stars classes can be giant-sized; others with be re-categorized // RED // BLUE // BLUEVIOLET else if (pct < 98){ size = GIANT; if (type == TYPE_ORANGE || type ==TYPE_YELLOW || type == TYPE_WHITE) type = TYPE_RED; else if (type == TYPE_BLUEWHITE) type = TYPE_BLUE; } // The following Stars classes can be supergiant-sized; others with be re-categorized // RED // YELLOW // BLUE // BLUEVIOLET else{ size = SUPERGIANT; if (type == TYPE_ORANGE) type = TYPE_RED; else if (type == TYPE_WHITE) type = TYPE_YELLOW; else if (type == TYPE_BLUEWHITE) type = TYPE_BLUE; } // Mark as unowned owner = (enum starmapPlayer)plr(*mt); //Generate Planets numPlanets=0; addPlanets(mt); } //Destructor Star::~Star(){ for (int i=0; i<5; i++) if (planet[i]!=nullptr) delete planet [i]; } int Star::getX(){ return x;} int Star::getY(){ return y;} int Star::getNumPlanets(){return numPlanets;} enum starType Star::getType(){ return type;} enum starSize Star::getSize(){ return size;} std::string Star::getTypeString(){ switch (type){ case TYPE_NIL: return "NONE"; case TYPE_RED: return "RED"; case TYPE_YELLOW: return "YELLOW"; case TYPE_ORANGE: return "ORANGE"; case TYPE_WHITE: return "WHITE"; case TYPE_BLUE: return "BLUE"; case TYPE_BLUEWHITE: return "BLUE-WHITE"; case TYPE_BLUEVIOLET: return "BLUE-VIOLET"; default: return "NONE"; } }std::string Star::getSizeString(){ switch (size){ case DWARF: return "DWARF"; case GIANT: return "GIANT"; case SUPERGIANT: return "SUPERGIANT"; default: return "NONE"; } } void Star::printStarInfo() { cout << "(" << setw(3)<< x << ", " << setw(3) << y << ")\t" ; switch (type){ case TYPE_NIL: cout << "NONE" << endl; break; case TYPE_RED: cout << "RED "; break; case TYPE_YELLOW: cout << "YELLOW "; break; case TYPE_ORANGE: cout << "ORANGE "; break; case TYPE_WHITE: cout << "WHITE "; break; case TYPE_BLUE: cout << "BLUE "; break; case TYPE_BLUEWHITE: cout << "BLUE-WHITE "; break; case TYPE_BLUEVIOLET: cout << "BLUE-VIOLET "; break; default: ; } switch (size){ case DWARF: cout << "DWARF "; break; case GIANT: cout << "GIANT "; break; case SUPERGIANT: cout << "SUPERGIANT "; break; default: ; } cout << endl; for (int i=0; i<5; i++){ cout << "\t\t"; if (planet[i]==nullptr) cout << "-------"; else cout << planet[i]->getSizeString() << " " << planet[i]->getBiomeString(); cout << endl; } } rgb_t Star::getColor(){ rgb_t color; switch(type){ case TYPE_RED: color.r=0xFF; color.g=0x82; color.b=0x59; break; case TYPE_ORANGE: color.r=0xFF; color.g=0xBB; color.b=0x78; break; case TYPE_YELLOW: color.r=0xFF; color.g=0xFF; color.b=0x9F; break; case TYPE_WHITE: color.r=0xFF; color.g=0xFF; color.b=0xFF; break; case TYPE_BLUEWHITE: color.r=0xCA; color.g=0xFA; color.b=0xFF; break; case TYPE_BLUE: color.r=0xBF; color.g=0xDC; color.b=0xFF; break; case TYPE_BLUEVIOLET: color.r=0x9D; color.g=0xBB; color.b=0xFF; break; default: color.r=0; color.g=0; color.b=0; } return color; } enum planetType Star::getPlanetType(int i){ if (i<0 || i>=5 || planet[i]==nullptr) return PLANETTYPE_NOPLANET; else return planet[i]->getType(); } enum planetSize Star::getPlanetSize(int i){ if (i<0 || i>=5 || planet[i]==nullptr) return PLANETSIZE_NOPLANET; else return planet[i]->getSize(); } enum planetBiome Star::getPlanetBiome(int i){ if (i<0 || i>=5 || planet[i]==nullptr) return PLANETBIOME_NOPLANET; else return planet[i]->getBiome(); } std::string Star::getPlanetTypeString(int i){ if (i<0 || i>=5 || planet[i]==nullptr) return ""; else return planet[i]->getTypeString(); } std::string Star::getPlanetSizeString(int i){ if (i<0 || i>=5 || planet[i]==nullptr) return ""; else return planet[i]->getSizeString(); } std::string Star::getPlanetBiomeString(int i){ if (i<0 || i>=5 || planet[i]==nullptr) return ""; else return planet[i]->getBiomeString(); } std::string Star::getPlanetString(int i){ if (planet[i]==nullptr) return ""; else if (planet[i]->getType()==PLANETTYPE_GAS) return "GAS GIANT"; else return planet[i]->getSizeString() + " " + planet[i]->getBiomeString(); } void Star::printPlanet(int i){ if (i>=0 && i<5 && planet[i]!=nullptr) planet[i]->printPlanet(); } enum starmapPlayer Star::getOwner() { return owner;} void Star::setOwner (enum starmapPlayer p) {owner = p;}
true
215943bef76e5b72f0e1b10eb9c7ae7122178deb
C++
Hailaylin/C
/C_Language_Promgram-TanHaoQiang/7_function/0718_计算该天是该年的第几天.cpp
UTF-8
2,014
3.6875
4
[]
no_license
/** * @file 0718_计算该天是该年的第几天.cpp * @author your name (you@domain.com) * @brief * @version 0.1 * @date 2020-11-25 * * @copyright Copyright (c) 2020 * * C语言程序设计 题号:0718 题目:输入年月日,计算是该年的第几天 得分:0 作业提交截止时间:2020/12/20 0:00:00 题目内容: 输入年月日,计算是该年的第几天。 例: (1)输入:2016,12,31 输出:366 (2)输入:2016,10,25 输出:299 (3)输入:2016,2,29 输出:60 (4)输入:2016,1,1 输出:1 请注意,main()函数必须按如下所示编写: int main() { int sum_day(int year, int month, int day); int year,month,day; scanf("%d,%d,%d",&year, &month, &day); printf("%d\n",sum_day(year,month,day)); return 0; } */ #include<stdio.h> int sum_day(int year, int month, int day) { int run(int year); int i,sum=0; int month_day[13]={31,28,31,30,31,30,31,31,30,31,30,31};//月从下标0开始 /* if(run(year)==0 || (run(year)==1 && (month<=2))) //不是闰年的时候或者在闰年的前两个月 { for(i=0;i<month-1;i++) //加到前一个月 { sum+=month_day[i]; } return sum+=day; } else if(run(year)==1 && month>2) { month_day[1]=29; for(i=0;i<month-1;i++) //加到前一个月 { sum+=month_day[i]; } return sum+=day; } */ //更好的逻辑 if(run(year)==1 && month>2) month_day[1]=29; for(i=0;i<month-1;i++) //加到前一个月 { sum+=month_day[i]; } return sum+=day; } //判断是否是闰年 int run(int year) { if (year%4==0&&year%100!=0||year%400==0) return 1; else return 0; } int main() { int sum_day(int year, int month, int day); int year,month,day; scanf("%d,%d,%d",&year, &month, &day); printf("%d\n",sum_day(year,month,day)); return 0; }
true
991cd33937e5a20c0c015d5a9660bdc03796a45f
C++
amey16/Just-cp--
/stacks_queues/lv1/next_greater_element_to_right.cpp
UTF-8
612
2.859375
3
[]
no_license
#include<iostream> #include<stack> #include<string> #include<vector> using namespace std; int main(){ int n; cin>>n; vector<int> arr(n); stack<int> st; for(int i=0;i<n;i++){ cin>>arr[i]; } st.push(arr[arr.size()-1]); vector<int> newarr(n); newarr[n-1] = -1; for(int i=n-2;i>=0;i--){ while(!st.empty() && st.top()<=arr[i]){ st.pop(); } if(st.empty()) newarr[i] = -1; else newarr[i] = st.top(); st.push(arr[i]); } for(int i=0;i<n;i++) cout<<newarr[i]<<endl; }
true
ea09de30ad8f57b8e072ad75efef390c69c67a94
C++
DushyantaDhyani/CodeChef
/OCT13/MAANDI.cpp
UTF-8
624
2.71875
3
[]
no_license
#define MAX 32000 #include<iostream> #include<cstdio> #include<vector> #include<cmath> using namespace std; bool check(long num){ long lucky=0; long overlucky=0; int r; while(num>0){ r=num%10; if(r==7 || r==4){ return true; } num=num/10; } return false; } int main(){ int T; long N; long limit; int count; int i; scanf("%d",&T); while(T>0){ scanf("%ld",&N); count=0; limit=sqrt(N); i=1; while(i<=limit){ if((N%i==0)){ if(check(i)){ count++; } if((N/i)!=i){ if(check(N/i)){ count++; } } } i++; } printf("%d\n",count); T--; } return 0; }
true
b40c88ef251af15da5685cf0ec6e40acba0c8841
C++
fatdeer/leetcode
/70-Climbing-Stairs/solution.cpp
UTF-8
181
2.625
3
[]
no_license
class Solution { public: int climbStairs(int n) { const double s = sqrt(5); return floor((pow((1 + s) / 2, n + 1) + pow((1 - s) / 2, n + 1)) / s + 0.5); } };
true
b1cd38fc25dd1a3194ba4c29c498eed3d7bc15f3
C++
Srecko727/DataStructures-P1b
/ExpTree.h
UTF-8
873
2.8125
3
[]
no_license
// // ExpTree.h // // // Created by Resch,Cheryl on 7/11/19. // #ifndef ExpTree_h #define ExpTree_h #include <iostream> #include <cstring> #include <vector> using namespace std; //you may change this struct node { string data; node* left; node* right; bool isOp; int value; ~node(); }; class ExpTree { //do not change public methods public: ExpTree(); ~ExpTree(); void CreateTree(vector<string> postFix); void SetVariableValues(vector<int> values); int EvaluateTree(); void inOrderTraversalandPrint(ostream &out); private: node* root; node* newNode(int newN); node* newNode(string newN); bool isOp(string Operator); void inOrderTrav(node* root,ostream &out); void inOrderSet(node* root, vector<int> values, int counter); //add helper methods here }; #endif /* ExpTree_h */
true
b4caef04d5f9a491528166b9df4e4bdc8fc6ac13
C++
olligut1/testenvironment
/cppTutorial/Tutorial 3/tut3.cpp
UTF-8
510
3.25
3
[]
no_license
#include <iostream> using namespace std; //Hauptfunktion int main() { const int WOCHENTAGE = 7; char buchstabe; /*int Zahl1 = 0; int Zahl2 = 0; cout << "Bitte gebe die erste Zahl ein: "; cin >> Zahl1; cout << "Bitte gebe die zweite Zahl ein: "; cin >> Zahl2; cout << "Das Ergebnis von " << Zahl1 << " * " << Zahl2 << " = " << Zahl1 * Zahl2 << endl; */ cout << "Gib einen Namen ein: "; cin >> buchstabe; cout << "Dein Anfangsbuchstabe ist " << buchstabe << endl; system("PAUSE"); return 0; }
true
6e24b830b061bb363fbb3c40dd67bde4a0354eac
C++
Abraham-WH/2017ACMtraining
/DAY13 K/main.cpp
GB18030
1,022
2.9375
3
[]
no_license
#include <iostream> #include <stdio.h> using namespace std; int sample,n,m,l,r,father[1005],ans; void initset() { for(int i = 1; i <= n; i++) father[i] = i; return; } int searchset(int a) { /* if(father[a] != a) searchset(father[a]); return father[a];*/ int x;//ٵݹʹ while(a != father[a]) a = father[a]; return a; } void mergeset(int a,int b) { int x = searchset(a); int y = searchset(b); if(x!=y) { if(x>y) father[y]=x; else father[x]=y;//ϵĸڵϲ } return; } int main() { cin>>sample; for(int i = 0; i < sample; i++) { cin>>n>>m; ans = 0; initset(); for(int j = 0; j < m; j++) { cin>>l>>r; mergeset(l,r); } for(int j = 1; j <= n; j++) { if(father[j] == j) ans++; } cout<<ans<<endl; } return 0; }
true
0baa6879487f5606702378068e3e383fc3cdf761
C++
XiandongHu/basic-examples
/Algorithm/sort/merge.cpp
UTF-8
942
3.421875
3
[]
no_license
#include <stdio.h> #include "util.h" static void mergeArray(int a[], int first, int mid, int last, int tmp[]) { int i = first, j = mid + 1; int m = mid, n = last; int k = 0; while (i <= m && j <= n) { if (a[i] < a[j]) { tmp[k++] = a[i++]; } else { tmp[k++] = a[j++]; } } while (i <= m) { tmp[k++] = a[i++]; } while (j <= n) { tmp[k++] = a[j++]; } for (i = 0; i < k; i++) { a[first + i] = tmp[i]; } } static void mergeSort(int a[], int first, int last, int tmp[]) { if (first < last) { int mid = (first + last) / 2; mergeSort(a, first, mid, tmp); // 左边有序 mergeSort(a, mid + 1, last, tmp); // 右边有序 mergeArray(a, first, mid, last, tmp); // 再将两个有序数组合并 } } void mergeTest(int a[], int n) { int* b = new int[n]; copyArray(a, n, b); int* tmp = new int[n]; mergeSort(b, 0, n - 1, tmp); delete[] tmp; printf("归并排序: "); printArray(b, n); delete[] b; }
true
6e72ac7c5b317e8443685cb30a3b567b3d80c686
C++
tal130/C
/DanceClub/DanceClub/Dancer.h
UTF-8
632
2.953125
3
[]
no_license
#pragma once #ifndef __DANCER_H #define __DANCER_H #include <iostream> using namespace std; #include "Human.h" class Dancer : virtual public Human { protected: int level; char* style; public: Dancer(int level, const Human& human); Dancer(const Dancer&); ~Dancer(); Dancer& operator=(const Dancer& other); void setStyle(const char*); const char* getStyle() const; void setLevel(const int); int getLevel() const; const Dancer operator<(const Dancer dancer) const; const Dancer operator>(const Dancer dancer) const; friend ostream& operator<<(ostream& os, const Dancer& d); }; #endif //__DANCER_H
true
323085cfee72906b3c255a5aef9280cf26e6c3bc
C++
vignesh-cloud-prog/Data-Structures-and-Algorithms
/linkedList/singlyLinkedList/reverseLinkedList.cpp
UTF-8
1,331
3.921875
4
[]
no_license
#include<iostream> using namespace std; class Node { public: int data; Node *next; }; void printList(Node *n) { Node *temp = n; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout<<endl; } Node *addLinkedList() { Node *head, *newNode, *temp; head = 0; int choice = 1; while (choice) { newNode = new Node; cout << "Enter the data: "; cin >> newNode->data; newNode->next = 0; if (head == NULL) { head = temp = newNode; } else { temp->next = newNode; temp = newNode; } cout << "Do you want to continue (0/1) \n"; cin >> choice; } return head; } Node * reverseLinkedList(Node **head){ Node *currentNode,*preNode=0,*nextNode; currentNode=nextNode=*head; while (nextNode != 0) { nextNode =nextNode->next; currentNode->next=preNode; preNode=currentNode; currentNode=nextNode; } *head = preNode; return *head; } int main() { Node *head; head=addLinkedList(); cout<<"Entered linked list "<<endl; printList(head); cout<<"Reversed linked list "<<endl; head = reverseLinkedList(&head); printList(head); return 0; }
true
b5650d7cad1b054800fc893f98da34940a0080f5
C++
AlexandreEichenberger/onnx
/onnx/defs/sequence/defs.cc
UTF-8
23,983
2.609375
3
[ "Apache-2.0" ]
permissive
/* * SPDX-License-Identifier: Apache-2.0 */ #include "onnx/defs/function.h" #include "onnx/defs/schema.h" #include <numeric> #include <algorithm> namespace ONNX_NAMESPACE { static const char* SequenceEmpty_ver11_doc = R"DOC( Construct an empty tensor sequence, with given data type. )DOC"; ONNX_OPERATOR_SET_SCHEMA( SequenceEmpty, 11, OpSchema() .SetDoc(SequenceEmpty_ver11_doc) .Attr( "dtype", "(Optional) The data type of the tensors in the output sequence. " "The default type is 'float'.", AttributeProto::INT, OPTIONAL_VALUE) .Output( 0, "output", "Empty sequence.", "S") .TypeConstraint( "S", OpSchema::all_tensor_sequence_types(), "Constrain output types to any tensor type.") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { const auto* attr_proto = ctx.getAttribute("dtype"); auto elem_type = TensorProto::FLOAT; if (nullptr != attr_proto) { if (!attr_proto->has_i()) { fail_type_inference( "Attribute dtype should be of integer type and specify a type."); } auto attr_value = attr_proto->i(); elem_type = static_cast<TensorProto_DataType>(attr_value); } ctx.getOutputType(0) ->mutable_sequence_type() ->mutable_elem_type() ->mutable_tensor_type() ->set_elem_type(elem_type); })); static const char* SequenceConstruct_ver11_doc = R"DOC( Construct a tensor sequence containing 'inputs' tensors. All tensors in 'inputs' must have the same data type. )DOC"; ONNX_OPERATOR_SET_SCHEMA( SequenceConstruct, 11, OpSchema() .SetDoc(SequenceConstruct_ver11_doc) .Input( 0, "inputs", "Tensors.", "T", OpSchema::Variadic) .Output( 0, "output_sequence", "Sequence enclosing the input tensors.", "S") .TypeConstraint( "T", OpSchema::all_tensor_types(), "Constrain input types to any tensor type.") .TypeConstraint( "S", OpSchema::all_tensor_sequence_types(), "Constrain output types to any tensor type.") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { const size_t numInputs = ctx.getNumInputs(); if (numInputs < 1) { fail_type_inference("SequenceConstruct is expected to have at least 1 input."); } std::vector<int> input_elem_types; input_elem_types.reserve(numInputs); for (size_t i = 0; i < numInputs; ++i) { auto input_type = ctx.getInputType(i); if(nullptr == input_type){ fail_type_inference("Input type for input at index ", i, " is null. Type info is expected."); } input_elem_types.emplace_back(input_type->tensor_type().elem_type()); } if (std::adjacent_find(input_elem_types.begin(), input_elem_types.end(), std::not_equal_to<int>()) != input_elem_types.end()) { // not all input elem types are the same. fail_type_inference("Element type of inputs are expected to be the same."); } auto* output_tensor_type = ctx.getOutputType(0) ->mutable_sequence_type() ->mutable_elem_type() ->mutable_tensor_type(); output_tensor_type->set_elem_type(static_cast<TensorProto_DataType>(input_elem_types[0])); if (!hasNInputShapes(ctx, static_cast<int>(numInputs))) { return; } *(output_tensor_type->mutable_shape()) = ctx.getInputType(0)->tensor_type().shape(); for (size_t i = 1; i < numInputs; ++i) { const auto& input_shape = ctx.getInputType(i)->tensor_type().shape(); UnionShapeInfo(input_shape, *output_tensor_type); } })); static const char* SequenceInsert_ver11_doc = R"DOC( Outputs a tensor sequence that inserts 'tensor' into 'input_sequence' at 'position'. 'tensor' must have the same data type as 'input_sequence'. Accepted range for 'position' is in `[-n, n]`, where `n` is the number of tensors in 'input_sequence'. Negative value means counting positions from the back. 'position' is optional, by default it inserts 'tensor' to the back of 'input_sequence'. )DOC"; ONNX_OPERATOR_SET_SCHEMA( SequenceInsert, 11, OpSchema() .SetDoc(SequenceInsert_ver11_doc) .Input( 0, "input_sequence", "Input sequence.", "S") .Input( 1, "tensor", "Input tensor to be inserted into the input sequence.", "T") .Input( 2, "position", "Position in the sequence where the new tensor is inserted. " "It is optional and default is to insert to the back of the sequence. " "Negative value means counting positions from the back. " "Accepted range in `[-n, n]`, " "where `n` is the number of tensors in 'input_sequence'. " "It is an error if any of the index values are out of bounds. " "It must be a scalar(tensor of empty shape).", "I", OpSchema::Optional) .Output( 0, "output_sequence", "Output sequence that contains the inserted tensor at given position.", "S") .TypeConstraint( "T", OpSchema::all_tensor_types(), "Constrain to any tensor type.") .TypeConstraint( "S", OpSchema::all_tensor_sequence_types(), "Constrain to any tensor type.") .TypeConstraint( "I", {"tensor(int32)", "tensor(int64)"}, "Constrain position to integral tensor. It must be a scalar(tensor of empty shape).") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { const auto input0_type = ctx.getInputType(0); const auto input1_type = ctx.getInputType(1); if(nullptr == input0_type || nullptr == input1_type) { fail_type_inference( "Input Sequence and Tensor are expected to have type info. Current type is null."); } const auto seq_elem_type = input0_type->sequence_type().elem_type().tensor_type().elem_type(); const auto tensor_elem_type = input1_type->tensor_type().elem_type(); if (seq_elem_type != tensor_elem_type) { fail_type_inference( "Input Sequence and Tensor are expected to have the same elem type. Sequence=", seq_elem_type, " Tensor=", tensor_elem_type); } auto *output_tensor_type = ctx.getOutputType(0) ->mutable_sequence_type() ->mutable_elem_type() ->mutable_tensor_type(); output_tensor_type->set_elem_type(seq_elem_type); if (!hasNInputShapes(ctx, 2)) { return; } *(output_tensor_type->mutable_shape()) = input0_type->sequence_type().elem_type().tensor_type().shape(); UnionShapeInfo(input1_type->tensor_type().shape(), *output_tensor_type); })); static const char* SequenceAt_ver11_doc = R"DOC( Outputs a tensor copy from the tensor at 'position' in 'input_sequence'. Accepted range for 'position' is in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'. Negative value means counting positions from the back. )DOC"; ONNX_OPERATOR_SET_SCHEMA( SequenceAt, 11, OpSchema() .SetDoc(SequenceAt_ver11_doc) .Input( 0, "input_sequence", "Input sequence.", "S") .Input( 1, "position", "Position of the tensor in the sequence. " "Negative value means counting positions from the back. " "Accepted range in `[-n, n - 1]`, " "where `n` is the number of tensors in 'input_sequence'. " "It is an error if any of the index values are out of bounds. " "It must be a scalar(tensor of empty shape).", "I") .Output( 0, "tensor", "Output tensor at the specified position in the input sequence.", "T") .TypeConstraint( "S", OpSchema::all_tensor_sequence_types(), "Constrain to any tensor type.") .TypeConstraint( "T", OpSchema::all_tensor_types(), "Constrain to any tensor type.") .TypeConstraint( "I", {"tensor(int32)", "tensor(int64)"}, "Constrain position to integral tensor. It must be a scalar(tensor of empty shape).") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { const auto input0_type = ctx.getInputType(0); if(nullptr == input0_type) { fail_type_inference("Input type for input at index 0 is null. Type info is expected.") } ctx.getOutputType(0)->CopyFrom(input0_type->sequence_type().elem_type()); })); static const char* SequenceErase_ver11_doc = R"DOC( Outputs a tensor sequence that removes the tensor at 'position' from 'input_sequence'. Accepted range for 'position' is in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'. Negative value means counting positions from the back. 'position' is optional, by default it erases the last tensor from 'input_sequence'. )DOC"; ONNX_OPERATOR_SET_SCHEMA( SequenceErase, 11, OpSchema() .SetDoc(SequenceErase_ver11_doc) .Input( 0, "input_sequence", "Input sequence.", "S") .Input( 1, "position", "Position of the tensor in the sequence. " "Negative value means counting positions from the back. " "Accepted range in `[-n, n - 1]`, " "where `n` is the number of tensors in 'input_sequence'. " "It is an error if any of the index values are out of bounds. " "It must be a scalar(tensor of empty shape).", "I", OpSchema::Optional) .Output( 0, "output_sequence", "Output sequence that has the tensor at the specified position removed.", "S") .TypeConstraint( "S", OpSchema::all_tensor_sequence_types(), "Constrain to any tensor type.") .TypeConstraint( "I", {"tensor(int32)", "tensor(int64)"}, "Constrain position to integral tensor. It must be a scalar(tensor of empty shape).") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { const auto input0_type = ctx.getInputType(0); if(nullptr == input0_type) { fail_type_inference("Input type for input at index 0 is null. Type info is expected.") } ctx.getOutputType(0)->CopyFrom(*input0_type); })); static const char* SequenceLength_ver11_doc = R"DOC( Produces a scalar(tensor of empty shape) containing the number of tensors in 'input_sequence'. )DOC"; ONNX_OPERATOR_SET_SCHEMA( SequenceLength, 11, OpSchema() .SetDoc(SequenceLength_ver11_doc) .Input( 0, "input_sequence", "Input sequence.", "S") .Output( 0, "length", "Length of input sequence. It must be a scalar(tensor of empty shape).", "I") .TypeConstraint( "S", OpSchema::all_tensor_sequence_types(), "Constrain to any tensor type.") .TypeConstraint( "I", {"tensor(int64)"}, "Constrain output to integral tensor. It must be a scalar(tensor of empty shape).") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { auto* output_tensor_type = ctx.getOutputType(0)->mutable_tensor_type(); output_tensor_type->set_elem_type(TensorProto::INT64); output_tensor_type->mutable_shape()->Clear(); })); // Updated operators that consume/produce sequence of tensors. static const char* SplitToSequence_ver11_doc = R"DOC(Split a tensor into a sequence of tensors, along the specified 'axis'. Lengths of the parts can be specified using argument 'split'. 'split' must contain only positive numbers. 'split' is either a scalar (tensor of empty shape), or a 1-D tensor. If 'split' is a scalar, then 'input' will be split into equally sized chunks(if possible). Last chunk will be smaller if the 'input' size along the given axis 'axis' is not divisible by 'split'. Otherwise, the tensor is split into 'size(split)' chunks, with lengths of the parts on 'axis' specified in 'split'. In this scenario, the sum of entries in 'split' must be equal to the dimension size of input tensor on 'axis'. )DOC"; ONNX_OPERATOR_SET_SCHEMA( SplitToSequence, 11, OpSchema() .Input(0, "input", "The tensor to split", "T") .Input( 1, "split", "Length of each output. " "It can be either a scalar(tensor of empty shape), or a 1-D tensor. All values must be >= 0. ", "I", OpSchema::Optional) .Output( 0, "output_sequence", "One or more outputs forming a sequence of tensors after splitting", "S") .TypeConstraint( "T", OpSchema::all_tensor_types(), "Constrain input types to all tensor types.") .TypeConstraint( "I", {"tensor(int32)", "tensor(int64)"}, "Constrain split size to integral tensor.") .TypeConstraint( "S", OpSchema::all_tensor_sequence_types(), "Constrain output types to all tensor types.") .Attr( "axis", "Which axis to split on. " "A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1].", AttributeProto::INT, static_cast<int64_t>(0)) .Attr( "keepdims", "Keep the split dimension or not. Default 1, which means we keep split dimension. " "If input 'split' is specified, this attribute is ignored.", AttributeProto::INT, static_cast<int64_t>(1)) .SetDoc(SplitToSequence_ver11_doc) .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { const auto input0_type = ctx.getInputType(0); if(nullptr == input0_type) { fail_type_inference("Input type for input at index 0 is null. Type info is expected.") } ctx.getOutputType(0) ->mutable_sequence_type() ->mutable_elem_type() ->mutable_tensor_type() ->set_elem_type(input0_type->tensor_type().elem_type()); if (!hasInputShape(ctx, 0)) { return; } const auto& inputShape = input0_type->tensor_type().shape(); int r = inputShape.dim_size(); int axis = static_cast<int>(getAttribute(ctx, "axis", 0)); if (axis < -r || axis > r - 1) { fail_shape_inference( "Invalid value of attribute 'axis'. Rank=", r, " Value=", axis); } if (axis < 0) { axis += r; } size_t num_inputs = ctx.getNumInputs(); int64_t splitSize = 1; int64_t keepdims = 1; if (num_inputs == 1) { // input split is omitted, default to split by 1. auto attr_proto = ctx.getAttribute("keepdims"); if (attr_proto) { keepdims = attr_proto->i(); } } else { splitSize = [&]() -> int64_t { // Need input split shape info and initializer data to infer split sizes. if (!hasInputShape(ctx, 1)) { return -1; } const TensorProto* splitInitializer = ctx.getInputData(1); if (nullptr == splitInitializer || !splitInitializer->has_data_type()) { return -1; } std::vector<int64_t> splitSizes; if (splitInitializer->data_type() == TensorProto::INT64) { const auto& data = ParseData<int64_t>(splitInitializer); splitSizes.insert(splitSizes.end(), data.begin(), data.end()); } else if (splitInitializer->data_type() == TensorProto::INT32) { const auto& data = ParseData<int32_t>(splitInitializer); splitSizes.insert(splitSizes.end(), data.begin(), data.end()); } else { // unaccepted data type fail_shape_inference( "Only supports `int32_t` or `int64_t` inputs for split"); } if (splitSizes.size() == 0) { fail_shape_inference( "Input 'split' can not be empty."); } const auto& splitDim = inputShape.dim(axis); if (!splitDim.has_dim_value()) { // Unable to verify nor infer exact split dimension size. return -1; } int64_t splitDimValue = splitDim.dim_value(); const auto& splitShape = getInputShape(ctx, 1); if (splitShape.dim_size() == 0) { // split is scalar if (splitDimValue % splitSizes[0] == 0) { // all output chunks have the same shape, assign that to output sequence shape. return splitSizes[0]; } return -1; } else { // split is 1-D tensor int64_t splitSizesSum = std::accumulate(splitSizes.begin(), splitSizes.end(), (int64_t)0); if (splitDimValue != splitSizesSum) { fail_shape_inference( "Sum of split values not equal to 'input' dim size on 'axis'. 'axis' dim size=", splitDimValue, " sum of split values=", splitSizesSum); } if (std::adjacent_find(splitSizes.begin(), splitSizes.end(), std::not_equal_to<int64_t>()) == splitSizes.end()) { // all split sizes are the same. return splitSizes[0]; } return -1; } }(); } if (keepdims) { auto* outputShape = ctx.getOutputType(0) ->mutable_sequence_type() ->mutable_elem_type() ->mutable_tensor_type() ->mutable_shape(); *outputShape = inputShape; auto* dim = outputShape->mutable_dim(axis); // Tensors in sequence could not have different shapes explicitly. // Only assign dim_value when all chunks have the same shape. if (splitSize > 0) { dim->set_dim_value(splitSize); } else { dim->clear_dim_value(); dim->clear_dim_param(); } } else { TensorShapeProto* outputShape = ctx.getOutputType(0) ->mutable_sequence_type() ->mutable_elem_type() ->mutable_tensor_type() ->mutable_shape(); for (int i = 0; i < inputShape.dim_size(); ++i) { if (i != axis) { auto* dim = outputShape->add_dim(); dim->CopyFrom(inputShape.dim(i)); } } } })); static const char* ConcatFromSequence_ver11_doc = R"DOC( Concatenate a sequence of tensors into a single tensor. All input tensors must have the same shape, except for the dimension size of the axis to concatenate on. By default 'new_axis' is 0, the behavior is similar to numpy.concatenate. When 'new_axis' is 1, the behavior is similar to numpy.stack. )DOC"; ONNX_OPERATOR_SET_SCHEMA( ConcatFromSequence, 11, OpSchema() .Attr( "axis", "Which axis to concat on. Accepted range in `[-r, r - 1]`, " "where `r` is the rank of input tensors. " "When `new_axis` is 1, accepted range is `[-r - 1, r]`. ", AttributeProto::INT) .Attr( "new_axis", "Insert and concatenate on a new axis or not, " "default 0 means do not insert new axis.", AttributeProto::INT, static_cast<int64_t>(0)) .SetDoc(ConcatFromSequence_ver11_doc) .Input( 0, "input_sequence", "Sequence of tensors for concatenation", "S") .Output(0, "concat_result", "Concatenated tensor", "T") .TypeConstraint( "S", OpSchema::all_tensor_sequence_types(), "Constrain input types to any tensor type.") .TypeConstraint( "T", OpSchema::all_tensor_types(), "Constrain output types to any tensor type.") .TypeAndShapeInferenceFunction([](InferenceContext& ctx) { const auto input0_type = ctx.getInputType(0); if(nullptr == input0_type) { fail_type_inference("Input type for input at index 0 is null. Type info is expected.") } auto elem_type = input0_type->sequence_type().elem_type().tensor_type().elem_type(); ctx.getOutputType(0)->mutable_tensor_type()->set_elem_type(elem_type); if (!hasInputShape(ctx, 0)) { return; } auto axis_attr = ctx.getAttribute("axis"); if (!axis_attr) { fail_shape_inference("Required attribute axis is missing"); } int axis = static_cast<int>(axis_attr->i()); int new_axis = 0; auto new_axis_attr = ctx.getAttribute("new_axis"); if (new_axis_attr) { new_axis = static_cast<int>(new_axis_attr->i()); } const auto& input_shape = ctx.getInputType(0)->sequence_type().elem_type().tensor_type().shape(); auto rank = input_shape.dim_size(); if (1 != new_axis && 0 != new_axis) { fail_shape_inference("new_axis must be either 0 or 1"); } auto upper_bound = 1 == new_axis ? rank : rank - 1; auto lower_bound = 1 == new_axis ? -rank - 1 : -rank; if (axis < lower_bound || axis > upper_bound) { fail_shape_inference( "Invalid value of attribute 'axis'. Accepted range=[", lower_bound, ", ", upper_bound, "], Value=", axis); } if (axis < 0) { axis += (upper_bound + 1); } auto* output_shape = ctx.getOutputType(0) ->mutable_tensor_type() ->mutable_shape(); for (int i = 0; i <= upper_bound; ++i) { output_shape->add_dim(); if (i != axis) { output_shape->mutable_dim(i)->CopyFrom(input_shape.dim((i > axis && new_axis) ? i - 1 : i)); } } })); } // namespace ONNX_NAMESPACE
true
ffc3b945d5070cdf1436b0366f83c8039fce1eaf
C++
GaoLF/Leetcode
/Basic Calculator II.cpp
UTF-8
2,113
2.78125
3
[]
no_license
#include<iostream> #include<string> #include<vector> #include <cctype> #include<algorithm> #include<math.h> #include<stack> using namespace std ; typedef struct ListNode{ int val; ListNode * next; } ListNode; class Solution { public: int calculate(string s) { vector<int> A; vector<int> op; int size=s.length(); int i,j,res=0,oper=0,foo; for(i=0;i<size;i++){ if(s[i]=='('){ int flag=1; for(j=i+1;j<size;j++){ if(s[j]=='(') flag++; if(s[j]==')') flag--; if(flag==0) break; } A.push_back(calculate(s.substr(i+1,j-i-1))); i=j; } else if(s[i]<='9'&&s[i]>='0'){ foo=s[i]-'0'; for(i++;i<size;i++){ if(s[i]>'9'||s[i]<'0'){ i--; break; } else foo=foo*10+(int)(s[i]-'0'); } A.push_back(foo); } else if(s[i]=='+') op.push_back(1); else if(s[i]=='-') op.push_back(2); else if(s[i]=='*') op.push_back(3); else if(s[i]=='/') op.push_back(4); } //cout<<"!!"<<endl; //vector<int > temp; //temp.push_back(A[0]); //cout<<op.size()<<"!!"<<A.size()<<endl; if(A.size()==0) return 0; for(i=0;i<op.size();){ if(op[i]==1||op[i]==2) i++; else if(op[i]==3){ op.erase(op.begin()+i); A[i+1]=A[i]*A[i+1]; A.erase(A.begin()+i); } else if(op[i]==4){ op.erase(op.begin()+i); A[i+1]=A[i]/A[i+1]; A.erase(A.begin()+i); } } //cout<<op.size()<<"!!"<<A.size()<<endl; res=A[0]; //cout<<A[0]<<endl; for(i=0;i<op.size();i++){ //cout<<A[i]<<endl; if(op[i]==1) res+=A[i+1]; else res-=A[i+1]; } //cout<<res<<endl; return res; } void print() { cout<<calculate("1")<<endl; cout<<calculate("3+5 / 2")<<endl; cout<<calculate("3+2*2")<<endl; cout<<calculate("2-4-(8+2-6+(8+4-(1)+8-10))")<<endl; cout<<calculate("2-1 + 2 ")<<endl; cout<<calculate("(1+(4+5+2)-3)+(6+8)")<<endl; } }; int main() { Solution test; // cout<<test.Low("A man, a plan, a canal: Panama")<<endl; test.print(); // cout<<atoi("2147483648")<<endl; system("pause"); }
true
a303c66b2d5e3523d58a3f327e9f4f5a8007ef17
C++
pce913/Algorithm
/baekjoon/2893.cpp
UHC
1,821
3.421875
3
[]
no_license
#include<stdio.h> #include<algorithm> using namespace std; struct Triangle{ int x, y, r; Triangle(int _x, int _y, int _r){ x = _x, y = _y, r = _r; } Triangle(){} bool operator==(const Triangle& t)const{ return x == t.x && y == t.y && r == t.r; } }; Triangle triangle[15]; Triangle area_of_overlapped_triangle(Triangle a, Triangle b){ if (a.x > b.x) swap(a, b); int dx = b.x - a.x; a.x += dx; // ڵ尡 ݵ ־߸ 츦 ó ִ. ؿ if (a.y > b.y) swap 츦 óϱ ̴. a.r -= dx; if (a.r <= 0) //ġ ʴ ﰢ϶ return{ 0, 0, 0 }; if (a.y > b.y) swap(a, b); b.r = min(b.r, a.r - (b.y - a.y)); //yκ Ͼ b.r ǰ Ͼ a.r - (b.y - a.y) ȴ. if (b.r <= 0) return{ 0, 0, 0 }; else{ return b; } } int main(){ int n; scanf("%d",&n); for (int i = 0; i < n; i++){ scanf("%d %d %d", &triangle[i].x, &triangle[i].y, &triangle[i].r); } long long ans = 0; //- for (int bit = 1; bit < (1 << n); bit++){ // Ƿ 1 int cnt = 0; Triangle temp; bool isOverLap = true; for (int i = 0; i < n; i++){ if (bit&(1 << i)){ cnt++; if (cnt == 1){ temp = triangle[i]; } else{ temp = area_of_overlapped_triangle(temp, triangle[i]); } if (temp == Triangle(0, 0, 0)){ isOverLap = false; break; } } } if (isOverLap){ int r = temp.r; if (cnt & 1){ //(1LL << (cnt - 1)) ̰ ִ ׷ϱ Ȯ ˰ڴ. ans += (long long)(1LL << (cnt - 1))*r*r; //ġ ༮ } else{ ans -= (long long)(1LL << (cnt - 1))*r*r; } } } printf("%lld.%d",ans/2,(ans%2)*5); }
true
cc6350b42c05ecfb09960ec337a03e30e22b1261
C++
kbc19b13/PECO
/GameTemplate/Game/Enemy/Move/MoveState/MoveEscape.cpp
SHIFT_JIS
1,050
2.65625
3
[]
no_license
#include "stdafx.h" #include "MoveEscape.h" #include "Enemy/Kuma.h" MoveEscape::MoveEscape(Kuma* kuma) : IKumaMove(kuma) { m_player = Player::P_GetInstance(); //Aj[V̍Đ //鎞̃Aj[VĐ } void MoveEscape::Move() { //Ԏ̈ړLq //ړ̋Lq //DiscoveryJځ //EPlayerɕ߂܂ƍSԂɑJڂ //PlayeȑɋLqtO𗧂ĂďH //E苗Ɩ߂ԂɑJڂ //MoveEscapeNXȂŏړMove֐ɋLq m_speed = { 1.0f, 0.0f, 0.0f }; //N}̍WXV m_kuma->SetMoveSpeed(m_speed); //PlayerƃN}Ƃ̋߂āA1000Ɩ߂Ԃɐ؂ւB if (GetDistance(m_player->GetPosition(), m_pos) > 1000.0f) { //1000ȏȂ߂ԂɑJڂB //ړ߂菈ɐ؂ւB m_kuma->ExecuteFSM_Return(); } }
true
7ea2b7e454ce80a316f2f7b685d9834bf4e41be9
C++
LTLA/archive-csaw
/src/merge_windows.cpp
UTF-8
7,112
2.828125
3
[]
no_license
#include "csaw.h" int split_cluster(const int*, const int*, const int&, const int&, const int&, const int&, int*); void fillSEXP(SEXP&, const int); /* We assume that incoming elements are sorted by chr -> start -> end. We then proceed * to aggregate elements by chaining together elements that are less than 'tolerance' * apart and, if required, have the same 'sign'. We also split them if the difference * between the first start and the last end is greater than 'max_size'. */ SEXP merge_windows(SEXP chrs, SEXP start, SEXP end, SEXP sign, SEXP tolerance, SEXP max_size) try { if (!isInteger(chrs)) { throw std::runtime_error("chromosomes should be a integer vector"); } if (!isInteger(start)) { throw std::runtime_error("start vector should be integer"); } if (!isInteger(end)) { throw std::runtime_error("end vector should be integer"); } if (!isLogical(sign)) { throw std::runtime_error("sign vector should be logical"); } if (!isInteger(tolerance) || LENGTH(tolerance)!=1) { throw std::runtime_error("tolerance should be an integer scalar"); } // Setting up pointers. const int* cptr=INTEGER(chrs); const int* sptr=INTEGER(start); const int* eptr=INTEGER(end); const int* lptr=LOGICAL(sign); const int tol=asInteger(tolerance); // Checking whether we need to supply a maximum size. if (!isInteger(max_size) || LENGTH(max_size) > 1) { throw std::runtime_error("maximum size should be an integer scalar"); } const bool limit_size=(LENGTH(max_size)==1); const int maxs=(limit_size ? asInteger(max_size) : 0); // Providing some protection against an input empty list. const int n = LENGTH(chrs); if (n!=LENGTH(start) || n!=LENGTH(end) || n!=LENGTH(sign)) { throw std::runtime_error("lengths of vectors are not equal"); } // Proceeding with the merge operation. SEXP output=PROTECT(allocVector(VECSXP, 4)); try { SET_VECTOR_ELT(output, 0, allocVector(INTSXP, n)); if (n==0) { fillSEXP(output, 0); UNPROTECT(1); return output; } int* optr=INTEGER(VECTOR_ELT(output, 0)); int start_index=0, last_end=*eptr; bool diffchr, diffsign, nested=false, warned=false; int last_sign=*lptr; int i, ngroups; *optr=ngroups=1; for (i=1; i<n; ++i) { diffchr=(cptr[i]!=cptr[i-1]); diffsign=(lptr[i]!=last_sign); /* Fully nested regions don't have a properly defined interpretation when it comes * to splitting things by sign. We only support consideration of nested regions where * either of the boundaries are the same. That can be considered to break the * previous stretch if it had opposite sign. Otherwise, the next window would have to * make the decision to match the parent window or its nested child. * * If the start is the same, the window with the earlier end point should be ordered * first, so that won't pass the first 'if'. This means that it'll only enter with * a fully nested window. Start and end-point equality might be possible at the ends * of chromosomes where trimming enforces sameness, but full nesting should not be observed. * * If the nested region has the same sign as the parent, then everything proceeds * normally i.e. same cluster. We make sure to keep 'last_end' as the parent end in * such cases. This ensures that the following windows get a change to compute * distances to the parent end (which should be closer). */ nested=(!diffchr && eptr[i] < last_end); if (nested) { if (diffsign && !warned) { warning("fully nested windows of opposite sign are present and ignored"); warned=true; diffsign=false; } } if (diffchr // Obviously, changing if we're on a different chromosome. || sptr[i]-last_end-1 > tol // Space between windows, start anew if this is greater than the tolerance. || diffsign // Checking if the sign is consistent. ) { if (limit_size) { ngroups=split_cluster(sptr, eptr, last_end, start_index, i, maxs, optr); } // Splitting the cluster, if desired. ++ngroups; optr[i]=ngroups; start_index=i; } else { optr[i]=optr[i-1]; } // Using the parent window as the endpoint if it's nested, but otherwise bumping up the last stats. if (!nested) { last_end=eptr[i]; last_sign=lptr[i]; } } // Cleaning up the last cluster, if necessary. if (limit_size) { ngroups=split_cluster(sptr, eptr, last_end, start_index, n, maxs, optr); } // Now, identifying the chromosome, start and end of each region. fillSEXP(output, ngroups); int* ocptr=INTEGER(VECTOR_ELT(output, 1)); int* osptr=INTEGER(VECTOR_ELT(output, 2)); int* oeptr=INTEGER(VECTOR_ELT(output, 3)); for (i=0; i<ngroups; ++i) { ocptr[i] = -1; } int curgroup; for (i=0; i<n; ++i) { curgroup=optr[i]-1; if (ocptr[curgroup]<0) { ocptr[curgroup]=cptr[i]; osptr[curgroup]=sptr[i]; // Sorted by start, remember; only need this once. oeptr[curgroup]=eptr[i]; } else if (oeptr[curgroup] < eptr[i]) { oeptr[curgroup]=eptr[i]; } } } catch (std::exception& e){ UNPROTECT(1); throw; } UNPROTECT(1); return output; } catch (std::exception& e) { return mkString(e.what()); } int split_cluster(const int* starts, const int* ends, const int& actual_end, const int& xs, const int& xe, const int& width, int* output) { double full_width=actual_end-starts[xs]+1; if (full_width <= width) { return output[xs]; } int mult=int(std::ceil(full_width/width)); /* There can only be `mult` subclusters. At the worst, `cur_diff` will be equal to `actual_end - starts[xs]`. Division by `subwidth` will give an expression of `(actual_end - starts[xs]) / [ (actual_end - starts[xs] + 1) / mult ]`. This will always be less than `mult`, so flooring it will give `mult-1`, i.e., the last index of `instantiated`. */ std::deque<int> instantiated(mult, 0); int output_index=output[xs]; int i=0; // Allocating windows into subclusters, based on their midpoints. double subwidth=full_width/mult, cur_diff; for (i=xs; i<xe; ++i) { cur_diff = double(starts[i]+ends[i])*0.5 - starts[xs]; output[i] = int(cur_diff/subwidth); if (!instantiated[output[i]]) { instantiated[output[i]] = 1; } } /* Allocating output indices to the subclusters. This approach avoids situations where you get nonconsecutive cluster indices, e.g., when `tol` is greater than the maximum width. */ for (i=0; i<mult; ++i) { if (!instantiated[i]) { continue; } instantiated[i]=output_index; ++output_index; } // Assigning indices back to the output vector. for (i=xs; i<xe; ++i) { output[i]=instantiated[output[i]]; } // Returning the last group index that was used. return output_index-1; } void fillSEXP(SEXP& output, const int ngroups) { SET_VECTOR_ELT(output, 1, allocVector(INTSXP, ngroups)); SET_VECTOR_ELT(output, 2, allocVector(INTSXP, ngroups)); SET_VECTOR_ELT(output, 3, allocVector(INTSXP, ngroups)); return; }
true
00cd14766a0a34fcb2b35379e2815cb1d4c81c1d
C++
8Observer8/Rational
/rational.cpp
UTF-8
1,516
3.546875
4
[]
no_license
#include "rational.h" Rational::Rational(int numerator, int denominator) : mNumerator(numerator), mDenominator(denominator) { } int Rational::numerator() const { return mNumerator; } void Rational::setNumerator(int numerator) { mNumerator = numerator; } int Rational::denominator() const { return mDenominator; } void Rational::setDenominator(int denominator) { mDenominator = denominator; } const Rational operator*(const Rational &lhs, const Rational &rhs) { return Rational(lhs.mNumerator * rhs.mNumerator, lhs.mDenominator * rhs.mDenominator); } const Rational operator+(const Rational &lhs, const Rational &rhs) { Rational result; // Общий знаменатель int commonDenominator = lhs.denominator() * rhs.denominator(); // Числитель int a = lhs.numerator() * rhs.denominator(); int b = rhs.numerator() * lhs.denominator(); result.setNumerator(a + b); // Знаменатель result.setDenominator(commonDenominator); return result; } const Rational operator-(const Rational &lhs, const Rational &rhs) { Rational result; // Общий знаменатель int commonDenominator = lhs.denominator() * rhs.denominator(); // Числитель int a = lhs.numerator() * rhs.denominator(); int b = rhs.numerator() * lhs.denominator(); result.setNumerator(a - b); // Знаменатель result.setDenominator(commonDenominator); return result; }
true
def318e93f5ab833c53c863a488f520a88b780e2
C++
Carlos2508/Hoja-de-trabajo-5
/tarea 5 ejercicio 1.cpp
ISO-8859-1
3,850
3.484375
3
[]
no_license
/*EJERCICIO#2 Realice un programa que, dado el peso, la altura, la edad y el gnero (M/F) de un grupo de N personas que pertenecen a un departamento de la repblica, obtenga un promedio de peso, altura y edad de esta poblacin. Los datos deben guardarse de forma ordenada por edad en un archivo de datos. As mismo el programa debe ser capaz leer los datos del archivo y generar un reporte con la media del peso, altura y la edad.*/ #include <iostream> #include <string> #include <fstream> using namespace std; struct promedio{ float edad; float altura; float peso; string genero; }; struct emp { int num ; //clave de ordenamiento string name ; string age ; string bs ; }; void bubbleSort(emp list[], int tam); int main(){ float peso, altura; float edad; float mpeso=0, maltura=0,medad=0, n=0; string genero; cout<<"Ingrese el peso en lbs: "<<endl; cin>>peso; cout<<"Ingrese la altura en metros: "<<endl; cin>>altura; cout<<"Ingrese la edad: "<<endl; cin>>edad; cout<<"Ingrese el genero de la persona (M-masculino//F-femenino): "<<endl; cin>>genero; ofstream archivo; archivo.open("media.txt",ios::app); archivo<<edad<<"\t"<<peso<<"\t"<<altura<<"\t"<<genero<<endl; archivo.close(); /* ifstream archivo; //leer archivo archivo.open("media.txt",ios::in); cout << "---------------------------------------------" << endl; cout << "EDAD"<< "\t" << "PESO" << "\t" << "ALTURA"<< "\t"<< "GENERO"<< endl; cout << "---------------------------------------------" << endl; int lineas,i=0; string s,linea; if(archivo.fail()){ cout<<"No se pudo abrir el archivo!!!"; exit(1); //break; } while (getline(archivo, s)) lineas++; archivo.close(); promedio recordset[lineas]; archivo.open("media.txt",ios::in); if(archivo.fail()){ cout<<"No se pudo abrir el archivo!!!"; exit(1); } for (int i = 0; i < lineas; i++) { if (!archivo) { cerr << "No se puede abrir el archivo " << endl; system("PAUSE"); } archivo>>recordset[i].edad>>recordset[i].peso>>recordset[i].altura>>recordset[i].genero; } archivo.close(); ifstream fp; string Tmp; fp.open("media.txt"); emp emp_array[5]; if (fp) { for (int counter = 0; counter < 3; counter++) { fp >> emp_array[counter].num; fp >> emp_array[counter].name; fp >> emp_array[counter].age; fp >> emp_array[counter].bs; } } else puts("error"); // bubbleSort(emp_array, 5); for (int counter = 0; counter < 3; counter++) { cout << emp_array[counter].num << "\t"; cout << emp_array[counter].name << "\t"; cout << emp_array[counter].age << "\t"; cout << emp_array[counter].bs << endl; } for(int i = 0; i < lineas; i++){ mpeso+=recordset[i].peso; medad+=recordset[i].edad; maltura+=recordset[i].altura; n= n+1; } cout<<"La media de la edad es de: "<<endl; cout<<medad/n<<endl; cout<<"La media del peso es de: "<<endl; cout<<mpeso/n<<endl; cout<<"La media de la altura es de: "<<endl; cout<<maltura/n<<endl; system("PAUSE"); */ } void bubbleSort(emp list[], int tam){ emp temp; int i; int index; for (i = 1; i < tam; i++) { //cout<<"i: posicion actual antes"<<list[i].num<<endl; for (index = 0; index < tam - i; index++) if (list[index].num > list[index + 1].num) { //cout<<"Posicion de intercambio: "<<endl; temp = list[index]; //cout<<"var temp"<<temp.num<<endl; list[index] = list[index + 1]; cout<< list[index+1].num<<endl; list[index + 1] = temp; } //cout<<"i: posicion actual despues"<<list[i].num<<endl; } }
true
c34a8fc92acda468dff2479b0b3230c9f1be772f
C++
s-nandi/contest-problems
/graph-theory/toposort/sliding_blocks.cpp
UTF-8
4,695
2.84375
3
[]
no_license
// Toposort, creating dependency graph // https://open.kattis.com/problems/slidingblocks // 2018 Singapore Regional #include <bits/stdc++.h> using namespace std; constexpr auto MAXN = 400'000 + 5; vector dx = {0, -1, 0, 1}; vector dy = {-1, 0, 1, 0}; struct edge { int to; }; using graph = vector<vector<edge>>; struct direction { char ch{' '}; int index{-1}; }; struct block { int r, c; auto neighbors(const block &o) const { auto dx = r - o.r; auto dy = c - o.c; return ((dx == 0) ^ (dy == 0)) and abs(dx) <= 1 and abs(dy) <= 1; } auto direction_to(const block &o) const -> direction { auto dx = r - o.r; auto dy = c - o.c; if (dx == -1) { return {'v', c}; } else if (dx == 1) { return {'^', c}; } else if (dy == -1) { return {'>', r}; } else if (dy == 1) { return {'<', r}; } assert(false); } auto operator<(const auto &o) const { return tie(r, c) < tie(o.r, o.c); } }; enum color { white, black, grey }; auto has_cycle(graph &g, int curr, auto &colors, auto &topo) { if (colors[curr] != white) return colors[curr] == grey ? true : false; colors[curr] = grey; for (auto [to] : g[curr]) { if (has_cycle(g, to, colors, topo)) { return true; } } colors[curr] = black; topo.push_front(curr); return false; } auto toposort(graph &g) { deque<int> topo; vector<color> colors(g.size(), white); for (int i = 0; i < g.size(); i++) { if (has_cycle(g, i, colors, topo)) { return pair{false, topo}; } } return pair{true, topo}; } void get_constraints(const auto &g, auto &blocks, int curr, auto &constraints, auto &dirs, int prev = -1) { if (prev != -1) { dirs[curr] = blocks[curr].direction_to(blocks[prev]); constraints[prev].push_back({curr}); } for (auto [to] : g[curr]) { if (to == prev) continue; get_constraints(g, blocks, to, constraints, dirs, curr); } } auto find_first_after(const auto &vec, const auto &elem) { auto it = upper_bound(begin(vec), end(vec), elem); return (it != end(vec)) ? optional(*it) : nullopt; } auto find_first_before(const auto &vec, const auto &elem) { auto it = lower_bound(begin(vec), end(vec), elem); return (it != begin(vec)) ? optional(*prev(it)) : nullopt; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int r, c, b; cin >> r >> c >> b; vector<block> blocks(b); map<block, int> mapping; for (int i = 0; i < b; i++) { int x, y; cin >> x >> y; blocks[i] = {x, y}; mapping[{x, y}] = i; } graph g(b); for (int i = 0; i < b; i++) { auto [x, y] = blocks[i]; for (int k = 0; k < dx.size(); k++) { auto nx = x + dx[k]; auto ny = y + dy[k]; if (mapping.count({nx, ny})) { auto j = mapping[{nx, ny}]; g[i].push_back({j}); } } } vector<vector<pair<int, int>>> sorted_rows(MAXN), sorted_cols(MAXN); for (int i = 0; i < b; i++) { auto [r, c] = blocks[i]; sorted_rows[r].push_back({c, i}); sorted_cols[c].push_back({r, i}); } for (auto &row : sorted_rows) { sort(begin(row), end(row)); } for (auto &col : sorted_cols) { sort(begin(col), end(col)); } vector<direction> dirs(b); graph constraints(b); get_constraints(g, blocks, 0, constraints, dirs, -1); for (int i = 1; i < b; i++) { auto [r, c] = blocks[i]; auto [dir, ind] = dirs[i]; optional<pair<int, int>> later_block; if (dir == '>') { later_block = find_first_before(sorted_rows[r], pair{c, i}); } else if (dir == '<') { later_block = find_first_after(sorted_rows[r], pair{c, i}); } else if (dir == 'v') { later_block = find_first_before(sorted_cols[c], pair{r, i}); } else if (dir == '^') { later_block = find_first_after(sorted_cols[c], pair{r, i}); } if (later_block) { auto [pos, j] = *later_block; if (!blocks[i].neighbors(blocks[j])) { constraints[i].push_back({j}); } } } auto [no_cycle, ordering] = toposort(constraints); if (!no_cycle) { cout << "impossible" << '\n'; } else { cout << "possible" << '\n'; for (auto i : ordering) { if (i == 0) continue; cout << dirs[i].ch << " " << dirs[i].index << '\n'; } } }
true
c711bbb8fbcb267bcc98f62a3cdc207362f9bf9c
C++
gkonto/openmp
/src/_prod_cons_v01/c3_1/prod_cons.cpp
UTF-8
2,328
2.65625
3
[ "Apache-2.0" ]
permissive
#include <math.h> #include <iostream> #include <time.h> #include <chrono> #include <thread> #include <omp.h> #include "prod_cons.hpp" #include "../tools.hpp" /* * NOTES: * Den einai producer consumer pragmatikos * giati prota perimenei to single na teleiosei kai meta ksekinoyn ta tasks. */ Buffer *gl_buffer = 0; int consume() { int num = 0; #pragma omp critical { if (gl_buffer->len_ > 0) { num = gl_buffer->buf_[--gl_buffer->len_].x_; std::cout << "Consume: " << num << " Thread Id: " << omp_get_thread_num() << std::endl; } } std::this_thread::sleep_for(std::chrono::milliseconds(20)); return num; } void produce(int key) { #pragma omp critical { gl_buffer->buf_[gl_buffer->len_++].x_ = key; std::cout << "Produce: " << key << " Thread Id: " << omp_get_thread_num() << std::endl; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } #if 0 int producer_consumer(int iterations) { gl_buffer = new Buffer(iterations); int total = 0; int x = 0; #pragma omp parallel { #pragma omp single { for (int i = 0; i < iterations; ++i) { #pragma omp task depend(out : x) { produce(i); x = i; } } for (int i = 0; i < iterations; ++i) { #pragma omp task depend(in : x) { int temp = consume(); #pragma omp critical { std::cout << x << std::endl; total += temp; } } } } } return total; } #else int producer_consumer(int iterations) { gl_buffer = new Buffer(iterations); int total = 0; int x = 0; #pragma omp parallel { #pragma omp single nowait { #pragma omp taskloop for (int i = 0; i < iterations; ++i) { { produce(i); x = 1; } } #pragma omp taskloop for (int i = 0; i < iterations; ++i) { { int temp = consume(); #pragma omp atomic total += temp; } } } } return total; } #endif
true
b8da588f876397991ef935135175bdfb39326cd4
C++
mrmh-code/My_problem_solution_different_OJ
/2.CodeForces/50.A. I Wanna Be the Guy.cpp
UTF-8
432
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { set<int>s; int n; cin>>n; int p; cin>>p; for(int i=0; i<p; i++){ int a; cin>>a; s.insert(a); } cin>>p; for(int i=0; i<p; i++){ int a; cin>>a; s.insert(a); } if(s.size()==n){ cout<<"I become the guy."<<endl; }else{ cout<<"Oh, my keyboard!"<<endl; } }
true
d5cbf5d98671edf089d8f5f1bfc7f76e2415b5b4
C++
jinagii/GripDrive
/Engine/Collision.cpp
UHC
766
3.109375
3
[]
no_license
#include "Collision.h" bool Collision::CircleCollision(D2D1_POINT_2F point, int radius1, D2D1_POINT_2F point2, int radius2) { int distX = point.x - point2.x; // غ int distY = point.y - point2.y; // int distT = sqrt((distX * distX) + (distY * distY)); // // 1 2 ϴµ, ũⰡ Ƿ ϱ 2 ش. if (distT < radius1 + radius2) { return true; } else { return false; } } bool Collision::AABBCollision(RECT rc1, RECT rc2) { if (rc1.left < rc2.right && rc2.left < rc1.right && rc1.top < rc2.bottom && rc2.top < rc1.bottom) { return true; } else { return false; } }
true
7f1bbba6301db7634df893b0ad15f58f76e6d539
C++
pieisland/2021-coding-test-preparing
/책 문제 풀이/10. 그래프 이론/행성 터널*(210216).cpp
UTF-8
2,273
3.234375
3
[]
no_license
#include<cstdio> #include<stdio.h> #include<iostream> #include<vector> #include<queue> #include<algorithm> #include<string> using namespace std; //행성 터널 /* * 거리가 주어진 게 아니었던 문제. 그래서 각 노드사이의 거리를 구해야했는데 * n이 너무 커서 n(n-1)/2로 하기에는 너무 크다. * 주어진 조건이 |x1- x2| 이런 걸로 하는거라서 밑에처럼 거리를 정할 수 있는 거였다. * 근데 혼자 생각할 수 있을지는 모르겠다. 이해는 했는데. */ int n; int parent[100000]; vector<pair<int, int>> vecx; vector<pair<int, int>> vecy; vector<pair<int, int>> vecz; vector<pair<int, pair<int, int>>> edges; int findParent(int x) { if (x == parent[x]) return x; return parent[x] = findParent(parent[x]); } void unionParent(int x, int y) { x = findParent(x); y = findParent(y); if (x < y) parent[y] = x; else parent[x] = y; } int main(void) { cin >> n; for (int i = 0; i < n; i++) { int x, y, z; cin >> x >> y >> z; vecx.push_back({ x, i }); vecy.push_back({ y, i }); vecz.push_back({ z, i }); } for (int i = 0; i < n; i++) { parent[i] = i; } //이걸 개별로 저장하고 정렬해서 sort(vecx.begin(), vecx.end()); sort(vecy.begin(), vecy.end()); sort(vecz.begin(), vecz.end()); //인접한 두 개 사이의 간격만 보도록 함. 모두 할 필요는 없다.. 어차피 더 멀어질 뿐이라서. for (int i = 0; i < n - 1; i++) { edges.push_back({ vecx[i + 1].first - vecx[i].first, {vecx[i].second, vecx[i + 1].second} }); edges.push_back({ vecy[i + 1].first - vecy[i].first, {vecy[i].second, vecy[i + 1].second} }); edges.push_back({ vecz[i + 1].first - vecz[i].first, {vecz[i].second, vecz[i + 1].second} }); } //이 밑부터는 동일 sort(edges.begin(), edges.end()); int answer = 0; for (int i = 0; i < edges.size(); i++) { int cost = edges[i].first; int n1 = edges[i].second.first; int n2 = edges[i].second.second; if (findParent(n1) != findParent(n2)) { unionParent(n1, n2); answer += cost; } } cout << answer << '\n'; return 0; }
true
66b25e62a676482791b186b47cc98c4968fd9c1e
C++
hamlet96/LeetCodeProblems
/347_Top_K_Frequent_Elements/main.cpp
UTF-8
996
3.125
3
[]
no_license
#include <vector> #include <algorithm> using namespace std; class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { vector<int> count; vector<int> answer; int uniqueCounter = 0; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) { int j = i; int c = 0; while (nums[j] == nums[i]) { c++; if(j==nums.size()-1)break; j++; } auto it = find(nums.begin(), nums.end(), nums[i]); if(c>1)nums.erase(it, it+c-1); nums.shrink_to_fit(); count.push_back(c); } vector<int> g = count; sort(g.begin(), g.end()); int f = g.size() - 1; while (k) { auto it = find(count.begin(), count.end(), g[f]); auto index = distance(count.begin(), it); count[index] = 0; answer.push_back(nums[index]); k--; f--; } return answer; } }; int main() { //vector<int> matrix { 1,1,1,2,2,3 }; vector<int> matrix{ 1,2 }; Solution s = Solution(); s.topKFrequent(matrix,2); return 0; }
true
73f1d40c3d8488d1deb2ca7bd0022a1bd2e6e684
C++
tamenut/stm2
/skf/CGeneratioNoise.cpp
UHC
1,331
2.828125
3
[]
no_license
#include <iostream> #include "CGeneratioNoise.h" #include <time.h> CGeneratioNoise::CGeneratioNoise(void) { Initialize(); } CGeneratioNoise::~CGeneratioNoise(void) { } void CGeneratioNoise::Initialize(void) { /// seed seed = long(time(NULL)); } double CGeneratioNoise::NoiseGauss(double i_dblMean, double i_dblDeviation) { /** i_dblMean, i_dblDeviation þ noise Ͽ ϰ g Ѵ. **/ double as, a, g; int i; as = i_dblDeviation; a = 0; for(i=1; i<13; i++) { a = a + NoiseUniran(); } g = double((a - 6.0) * as + i_dblMean); return g; } double CGeneratioNoise::NoiseUniran(void) { /** 0 1̿ uniformϰ ϴ random number Ͽ ϰ ans **/ long int b15=32768, b16=65536, h15, h31, ovf, ms=2147483647, m1=24112, m2=26143, lp, l15; double ans; h15 = seed/b16; lp = (seed-h15*b16) * m1; l15 = lp/b16; h31 = h15*m1 + l15; ovf = h31/b15; seed = (((lp-l15*b16)-ms)+(h31-ovf*b15)*b16) + ovf; if(seed<0) seed = seed + ms; h15 = seed/b16; lp = (seed-h15*b16) * m2; l15 = lp/b16; h31 = h15*m2 + l15; ovf = h31/b15; seed = (((lp-l15*b16)-ms)+(h31-ovf*b15)*b16) + ovf; if(seed<0) seed = seed + ms; ans = double((2 * (seed/256) +1 )/ 16777216.); return ans; }
true
a84f25c1b0350df84e2946f1154af768437d0388
C++
auzierk13/mcd
/dallas_esp/ds18b20.ino
UTF-8
1,959
2.84375
3
[]
no_license
void setupDs18b20() { // start serial port Serial.begin(9600); Serial.println("Dallas Temperature IC Control Library Demo"); // Start up the library sensors.begin(); // Grab a count of devices on the wire numberOfDevices = sensors.getDeviceCount(); // locate devices on the bus Serial.print("Locating devices..."); Serial.print("Found "); Serial.print(numberOfDevices, DEC); Serial.println(" devices."); // report parasite power requirements Serial.print("Parasite power is: "); if (sensors.isParasitePowerMode()) Serial.println("ON"); else Serial.println("OFF"); // Search the wire for address if(sensors.getAddress(tempDeviceAddress, 0)) { Serial.print("Setting resolution to "); Serial.println(TEMPERATURE_PRECISION, DEC); // set the resolution to TEMPERATURE_PRECISION bit (Each Dallas/Maxim device is capable of several different resolutions) sensors.setResolution(tempDeviceAddress, TEMPERATURE_PRECISION); Serial.print("Resolution actually set to: "); Serial.print(sensors.getResolution(tempDeviceAddress), DEC); Serial.println(); }else{ Serial.print("Found ghost device at "); Serial.print(0, DEC); Serial.print(" but could not detect address. Check power and cabling"); } } // function to print the temperature for a device float printTemperature() { // call sensors.requestTemperatures() to issue a global temperature // request to all devices on the bus sensors.requestTemperatures(); // Send the command to get temperatures // Search the wire for address if(sensors.getAddress(tempDeviceAddress, 0)) { // It responds almost immediately. Let's print out the data // Use a simple function to print out the data float tempC = sensors.getTempC(tempDeviceAddress); Serial.print("Temp C: "); Serial.println(tempC); return tempC; } //else ghost device! Check your power requirements and cabling }
true
d39a1ee1c0d26af4a4efac06ef8a472958da5c8f
C++
kimdungdt2412/lthdt-18clc6-18127082
/18127082_W07_01/ex01.cpp
UTF-8
326
2.640625
3
[]
no_license
#include "Bike.h" #include "Truck.h" int main() { Bike b; Truck t; cout << "Motorbike" << endl; b.add_a_weight(); b.remove_a_weight(); b.add_fuel(); b.length(); b.fuel_left(); cout << "Truck" << endl; t.add_a_weight(); t.remove_a_weight(); t.add_fuel(); t.length(); t.fuel_left(); system("pause"); return 0; }
true
00034ced79f2a78a91f86ba8d3fa51a31ce41c28
C++
ajoathan/pso
/pso.h
UTF-8
797
2.6875
3
[ "Apache-2.0" ]
permissive
#include<cstddef> #include<vector> namespace pso { class solution { std::vector<double> values; public: solution(std::size_t size); std::size_t size() const; double& operator[](std::size_t idx); const double& operator[](std::size_t idx) const; solution operator+(const solution &b) const; solution operator-(const solution &b) const; solution operator*(const solution &b) const; }; solution operator*(const double &a, const solution &b); class particle { solution _actual; solution _speed; solution _pbest; double _val_pbest; std::vector<particle*> _neighbors; public: const solution pbest() const; const solution nbest() const; void add_neighbor(particle* neightbor); solution update(double c1, double c2); virtual double evaluate() = 0; }; }
true
23d743dfbcd2ef0408d0bc22c53fc46308671bf1
C++
duburcqa/jiminy
/core/src/io/AbstractIODevice.cc
UTF-8
8,231
2.796875
3
[ "MIT", "BSL-1.0", "MPL-2.0", "BSD-2-Clause" ]
permissive
/////////////////////////////////////////////////////////////////////////////// /// /// \brief Contains the AbstractIODevice class methods implementations. /// /////////////////////////////////////////////////////////////////////////////// #include "jiminy/core/Macros.h" #include "jiminy/core/io/AbstractIODevice.h" namespace jiminy { openMode_t operator|(openMode_t const & modeA, openMode_t const & modeB) { return static_cast<openMode_t>(static_cast<int32_t>(modeA) | static_cast<int32_t>(modeB)); } openMode_t operator&(openMode_t const & modeA, openMode_t const & modeB) { return static_cast<openMode_t>(static_cast<int32_t>(modeA) & static_cast<int32_t>(modeB)); } openMode_t operator|=(openMode_t & modeA, openMode_t const & modeB) { return modeA = modeA | modeB; } openMode_t operator&=(openMode_t & modeA, openMode_t const & modeB) { return modeA = modeA & modeB; } openMode_t operator~(openMode_t const & mode) { return static_cast<openMode_t>(~static_cast<int32_t>(mode)); } AbstractIODevice::AbstractIODevice() : modes_(openMode_t::NOT_OPEN), supportedModes_(openMode_t::NOT_OPEN), lastError_(hresult_t::SUCCESS), io_(nullptr) { // Empty on purpose } hresult_t AbstractIODevice::open(openMode_t const & modes) { hresult_t returnCode = hresult_t::SUCCESS; if (isOpen()) { PRINT_ERROR("Already open."); returnCode = lastError_ = hresult_t::ERROR_GENERIC; } if (returnCode == hresult_t::SUCCESS) { if ((modes & supportedModes_) != modes) { PRINT_ERROR("At least of the modes ", modes, " is not supported."); returnCode = lastError_ = hresult_t::ERROR_GENERIC; } } if (returnCode == hresult_t::SUCCESS) { returnCode = doOpen(modes); } if (returnCode == hresult_t::SUCCESS) { modes_ = modes; } return returnCode; } hresult_t AbstractIODevice::close(void) { hresult_t returnCode = hresult_t::SUCCESS; if (!isOpen()) { returnCode = hresult_t::ERROR_GENERIC; } if (returnCode == hresult_t::SUCCESS) { returnCode = doClose(); } if (returnCode == hresult_t::SUCCESS) { modes_ = NOT_OPEN; } return returnCode; } openMode_t const & AbstractIODevice::openModes(void) const { return modes_; } openMode_t const & AbstractIODevice::supportedModes(void) const { return supportedModes_; } bool_t AbstractIODevice::isWritable(void) const { return (modes_ & openMode_t::WRITE_ONLY) || (modes_ & openMode_t::READ_WRITE); } bool_t AbstractIODevice::isReadable(void) const { return (modes_ & openMode_t::READ_ONLY) || (modes_ & openMode_t::READ_WRITE); } bool_t AbstractIODevice::isOpen(void) const { return (modes_ != openMode_t::NOT_OPEN); } bool_t AbstractIODevice::isSequential(void) const { return false; } int64_t AbstractIODevice::size(void) { return bytesAvailable(); } hresult_t AbstractIODevice::resize(int64_t /* size */) { lastError_ = hresult_t::ERROR_GENERIC; PRINT_ERROR("This method is not available."); return lastError_; } hresult_t AbstractIODevice::seek(int64_t /* pos */) { lastError_ = hresult_t::ERROR_GENERIC; PRINT_ERROR("This method is not available."); return lastError_; } int64_t AbstractIODevice::pos(void) { return 0; } int64_t AbstractIODevice::bytesAvailable(void) { return 0; } hresult_t AbstractIODevice::getLastError(void) const { return lastError_; } hresult_t AbstractIODevice::write(void const * data, int64_t dataSize) { int64_t toWrite = dataSize; uint8_t const * bufferPos = static_cast<uint8_t const *>(data); while (toWrite > 0) { int64_t writtenBytes = writeData(bufferPos + (dataSize - toWrite), toWrite); if (writtenBytes <= 0) { lastError_ = hresult_t::ERROR_GENERIC; PRINT_ERROR("No data was written. The device is full is probably full."); return lastError_; } toWrite -= writtenBytes; } return hresult_t::SUCCESS; } hresult_t AbstractIODevice::read(void * data, int64_t dataSize) { int64_t toRead = dataSize; uint8_t * bufferPos = static_cast<uint8_t *>(data); while (toRead > 0) { int64_t readBytes = readData(bufferPos + (dataSize - toRead), toRead); if (readBytes <= 0) { lastError_ = hresult_t::ERROR_GENERIC; PRINT_ERROR("No data was read. The device is full is probably empty."); return lastError_; } toRead -= readBytes; } return hresult_t::SUCCESS; } hresult_t AbstractIODevice::setBlockingMode(bool_t /* shouldBlock */) { lastError_ = hresult_t::ERROR_GENERIC; PRINT_ERROR("This methid is not available."); return lastError_; } bool_t AbstractIODevice::isBackendValid(void) { return (io_.get() != nullptr); } void AbstractIODevice::setBackend(std::unique_ptr<AbstractIODevice> io) { io_ = std::move(io); supportedModes_ = io_->supportedModes(); } void AbstractIODevice::removeBackend(void) { io_.reset(); supportedModes_ = openMode_t::NOT_OPEN; } // Specific implementation - std::vector<uint8_t> template<> hresult_t AbstractIODevice::read<std::vector<uint8_t> >(std::vector<uint8_t> & v) { int64_t toRead = static_cast<int64_t>(v.size() * sizeof(uint8_t)); uint8_t * bufferPos = reinterpret_cast<uint8_t *>(v.data()); return read(bufferPos, toRead); } // Specific implementation - std::vector<char_t> template<> hresult_t AbstractIODevice::read<std::vector<char_t> >(std::vector<char_t> & v) { int64_t toRead = static_cast<int64_t>(v.size() * sizeof(char_t)); uint8_t * bufferPos = reinterpret_cast<uint8_t *>(v.data()); return read(bufferPos, toRead); } // Specific implementation - std::string template<> hresult_t AbstractIODevice::write<std::string>(std::string const & str) { int64_t toWrite = static_cast<int64_t>(str.size()); uint8_t const * bufferPos = reinterpret_cast<uint8_t const *>(str.c_str()); return write(bufferPos, toWrite); } // Specific implementation - std::vector<uint8_t> template<> hresult_t AbstractIODevice::write<std::vector<uint8_t> >(std::vector<uint8_t> const & v) { int64_t toWrite = static_cast<int64_t>(v.size() * sizeof(uint8_t)); uint8_t const * bufferPos = reinterpret_cast<uint8_t const *>(v.data()); return write(bufferPos, toWrite); } // Specific implementation - std::vector<char_t> template<> hresult_t AbstractIODevice::write<std::vector<char_t> >(std::vector<char_t> const & v) { int64_t toWrite = static_cast<int64_t>(v.size() * sizeof(char_t)); uint8_t const * bufferPos = reinterpret_cast<uint8_t const *>(v.data()); return write(bufferPos, toWrite); } // Specific implementation - std::vector<uint64_t> template<> hresult_t AbstractIODevice::write<std::vector<uint64_t> >(std::vector<uint64_t> const & v) { int64_t toWrite = static_cast<int64_t>(v.size() * sizeof(uint64_t)); uint8_t const * bufferPos = reinterpret_cast<uint8_t const *>(&v[0]); return write(bufferPos, toWrite); } }
true
9055ec39702f326073c4d1756ea78eeedaba25a5
C++
AlexTuckner/School_Projects
/Software Design Robot Project/iteration3/src/event_distress_call.h
UTF-8
1,592
2.578125
3
[]
no_license
/** * @file event_collision.h * * @copyright 2017 3081 Staff, All rights reserved. */ #ifndef SRC_EVENT_DISTRESS_CALL_H_ #define SRC_EVENT_DISTRESS_CALL_H_ /******************************************************************************* * Includes ******************************************************************************/ #include <stdlib.h> #include "src/event_entity_base_class.h" #include "src/position.h" /******************************************************************************* * Namespaces ******************************************************************************/ NAMESPACE_BEGIN(csci3081); /******************************************************************************* * Class Definitions ******************************************************************************/ /** * \class EventDistressCall : public EventBaseClass * @brief A distress event class, which is created after a * player collides with the robot. This will remove the proximity sensors * of a SuperBot so that it can collide, and freeze the player. */ class EventDistressCall : public EventEntityBaseClass { public: EventDistressCall(enum entity_type entity, Position position_of_event) : EventEntityBaseClass(entity, position_of_event), frozen(false) {} /*! * \fn get_is_frozen / set_is_frozen * This is a function used to determine if the object should be frozen or not */ bool get_is_frozen() const {return frozen;} void set_is_frozen(bool f) {frozen = f;} private: bool frozen; }; NAMESPACE_END(csci3081); #endif /* SRC_EVENT_DISTRESS_CALL_H_ */
true
49833117e20dd8fc6e4bd3870fb13a7365c48b3e
C++
epoels/SimpleWebCache
/HTTPIMAGEService.cpp
UTF-8
3,939
2.71875
3
[]
no_license
#include "/USERS/ericpoels/MakeUpTest/SimpleWebCache/headers/HTTPIMAGEService.h" #include "/USERS/ericpoels/MakeUpTest/SimpleWebCache/headers/HTTPResponseHeader.h" #include "/USERS/ericpoels/MakeUpTest/SimpleWebCache/headers/HTTPNotFoundExceptionHandler.h" HTTPIMAGEService::HTTPIMAGEService(FileCache * p_fileCache,bool p_clean_cache ) :HTTPService(p_fileCache,p_clean_cache) {} // Constructor setting data members using initialization list bool HTTPIMAGEService::execute(HTTPRequest * p_httpRequest,TCPSocket * p_tcpSocket) { try { // Try the following block and look for exceptions string resource = p_httpRequest->getResource(); // Fetching the resource from the HTTPRequest object FileCacheItem * fileCacheItem = fileCache->getFile(resource); // fetching the resource cache item fileCacheItem = fileCacheItem->fetchContent(); // update cache item if needed and return a clone // Instantiate an HTTPresponse object and set up its header attributes struct tm * tm; string s = p_httpRequest->getHeaderValue("If-Modified-Since"); // Compare the values of the last updated time and if modified since // if they are not equal begin the process of writing a new file to the socket if ( s != fileCacheItem->getLastUpdateTime() ) { HTTPResponseHeader * httpResponseHeader = new HTTPResponseHeader(p_tcpSocket,"OK",200,"HTTP/1.1"); httpResponseHeader->setHeader("Content-Type","image/gif"); // Set content type // Fetch the date/time string of the last modified attribute and set it to the header httpResponseHeader->setHeader("Last-Modified",fileCacheItem->getLastUpdateTime()); // This implies that the connection terminates after service the request; i.e. keep-alive is not supported httpResponseHeader->setHeader("Connection","close"); httpResponseHeader->setHeader("Content-Length",to_string(fileCacheItem->getSize())); httpResponseHeader->respond(); // Write back the response to the client through the TCPSocket // Write back the file to the client through the TCPSocket p_tcpSocket->writeToSocket(fileCacheItem->getStream(),fileCacheItem->getSize()); // delete the response delete(httpResponseHeader); } else { // Simply create a new response with an error code of 304 Not Modified HTTPResponseHeader * httpResponseHeader = new HTTPResponseHeader(p_tcpSocket,"Not Modified",304,"HTTP/1.1"); // Get the time time_t rawtime; char buffer[80]; time (&rawtime); tm = localtime(&rawtime); strftime(buffer,80,"%d-%m-%Y %I:%M:%S",tm); string str(buffer); // Set the date in the header httpResponseHeader->setHeader("Date",str); // Send the response back to the socket httpResponseHeader->respond(); // Delete the response delete(httpResponseHeader); } // delete (httpResponseHeader); // Delete the HTTP Response delete (fileCacheItem); // delete the cache item clone return true; // return true } catch (HTTPNotFoundExceptionHandler httpNotFoundExceptionHandler) { // Exception occurred and caught // Handle the exception and send back the corresponding HTTP status response to client httpNotFoundExceptionHandler.handle(p_tcpSocket); return false; // return false } } // Clone a new identical object and return it to the caller HTTPService * HTTPIMAGEService::clone () { // Instantiate an HTTPHTMLService object and set it up with the same fileCache. // Notice that the clean flag is set to false as the current object will be carrying this out. return new HTTPIMAGEService(fileCache,false); } HTTPIMAGEService::~HTTPIMAGEService() // Destructor { }
true
dfa41e04a7a6c3632bd014aaaf8d892420af0879
C++
rahulgupta999/RiceFarm
/source/Farm.cpp
UTF-8
15,539
2.546875
3
[]
no_license
// Ricefarm.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Farm.h" #include <ctime> #ifdef WIN32 #include <strstream> #endif struct comparator { bool operator() (riceVariety *first, riceVariety *second) { return (first->nonConflictingNeighbours.size() < second->nonConflictingNeighbours.size()); } }comparatorObj; farm::farm(int i, int j, char *inFilePath, char *outFilePath) : rows(i), columns(j), bestEffortSolution(false), maxTimeSec(300), totalRemoved(0), pollinationDays(3) { farmGrid = new plot**[rows]; for (int index=0; index<rows; ++index) { farmGrid[index] = new plot*[columns]; } int count = 1; for (int hindex=0; hindex<rows; ++hindex) { for (int vindex=0; vindex<columns; ++vindex) { plot *newplot = new plot(hindex, vindex, count); farmGrid[hindex][vindex] = newplot; farmPlotList.push_back(newplot); count++; } } farmPlotAdjacencyMap.resize(count); for (int hindex=0; hindex<rows; ++hindex) { for (int vindex=0; vindex<columns; ++vindex) { plot *plotObj = farmGrid[hindex][vindex]; int row = plotObj->rowIndex; int col = plotObj->colIndex; vector<plot *> adjacenPlotList; if (row-1 >= 0 && col-1 >= 0) adjacenPlotList.push_back(farmGrid[row-1][col-1]); if (row-1 >= 0) adjacenPlotList.push_back(farmGrid[row-1][col]); if (row-1 >= 0 && col+1 < columns) adjacenPlotList.push_back(farmGrid[row-1][col+1]); if (col+1 < columns) adjacenPlotList.push_back(farmGrid[row][col+1]); if (row+1 < rows && col+1 < columns) adjacenPlotList.push_back(farmGrid[row+1][col+1]); if (row+1 < rows) adjacenPlotList.push_back(farmGrid[row+1][col]); if (row+1 < rows && col-1 >= 0) adjacenPlotList.push_back(farmGrid[row+1][col-1]); if (col-1 >= 0) adjacenPlotList.push_back(farmGrid[row][col-1]); farmPlotAdjacencyMap[plotObj->plotNameAsIndex - 1] = adjacenPlotList; } } maxRiceVarietyUsedCount = 0; if (inFilePath == NULL) { inFilePath = "input.csv"; } inputFilePath = inFilePath; if (outFilePath == NULL) { outFilePath = "output.csv"; } outputFilePath = inputFilePath + "_" + "output.csv"; } farm::~farm() { for (auto &obj : farmPlotList) { delete obj; } for (auto &variety: riceVarietyList) { delete variety; } for (int index=0; index<rows; ++index) { delete [] farmGrid[index]; } delete [] farmGrid; } void farm::populateRiceVarietyList() { ifstream infile; infile.open(inputFilePath.c_str()); if (!infile) { throw "ERROR: Input file '" + inputFilePath + "' could not be opened, check if it is present"; } string line; getline(infile, line); if(*line.rbegin() == '\r') { line.resize(line.size() - 1); } #ifdef WIN32 if (stricmp(line.c_str(), "Variety,Flowering Date") != 0) #else if (strcasecmp(line.c_str(), "Variety,Flowering Date") != 0) #endif { throw (string("ERROR: input file CSV header '") + line + string("' is not as desired, check the sample")); } int lineNumber = 2; for (line.clear();getline(infile, line);line.clear()) { if(*line.rbegin() == '\r') { line.resize(line.size() - 1); } string name, sd, ed; size_t nameEnd = line.find_first_of(',', 0); if (nameEnd != string::npos) { name = line.substr(0, nameEnd); } else { throw "ERROR: input file CSV is corrupt at line " + getStringFromInt(lineNumber) ; } /*size_t sdEnd = line.find_first_of(',', nameEnd + 1); if (sdEnd != string::npos) { sd = line.substr(nameEnd + 1, sdEnd - nameEnd - 1); } else { throw "ERROR: input file CSV is corrupt at line " + lineNumber; }*/ //size_t edEnd = line.find_first_of('\0', sdEnd + 1); //if (edEnd != string::npos) //{ //ed = line.substr(sdEnd + 1); sd = line.substr(nameEnd + 1); //} //else //{ // throw "ERROR: input file CSV is corrupt at line " + lineNumber; //} ++lineNumber; riceVariety *variety = new riceVariety(name, sd, sd); riceVarietyList.push_back(variety); (riceVarietyDateMap[variety->sDate.actualDate]).push_back(variety); } infile.close(); } void farm::populateNonConflictingNeighbours() { for (auto &variety : riceVarietyList) { (variety)->nonConflictingNeighbours.clear(); (variety)->conflictingNeighbours.clear(); if (variety->blocked) continue; for (auto &runner : riceVarietyList) { if (runner->blocked) continue; if (runner == variety) { continue; } else if (!variety->pollinationConflicts(runner, pollinationDays)) { (variety)->nonConflictingNeighbours.insert(runner); } else { (variety)->conflictingNeighbours.insert(runner); } } } } void farm::sortListAsPerDesiredOrder() { //sort the map in decreasing order of conflict //std::sort(riceVarietyList.begin(), riceVarietyList.end(), comparatorObj); } void farm::resetFarm() { for (auto & variety : riceVarietyList) { variety->used = false; } for (int hindex=0; hindex<rows; ++hindex) { for (int vindex=0; vindex<columns; ++vindex) { farmGrid[hindex][vindex]->assignedVariety = NULL; } } return; } int farm::removeVariety() { map<string, vector<riceVariety *> >::iterator iter = riceVarietyDateMap.begin(); vector<riceVariety *> maxVector; for (; iter != riceVarietyDateMap.end(); ++iter) { bool atLeastOneActive = false; for (auto &variety : (*iter).second) { if (!variety->blocked) { atLeastOneActive = true; break; } } if (atLeastOneActive) { if ((*iter).second.size() > maxVector.size()) { maxVector = (*iter).second; } } } int count = floor(maxVector.size() / 2); int updated = 0; for (auto &variety : maxVector) { if (!count) break; if (!variety->blocked) { --count; ++updated; variety->blocked = true; } } return updated; } bool farm::recurseAndAssignVarietyToPlots(int currentPlotIndex, int remainingBlanks) { if (currentPlotIndex >= (int)farmPlotList.size()) { return true; } endTime = clock(); double elapsed_secs = double(endTime - beginTime) / CLOCKS_PER_SEC; if (elapsed_secs > maxTimeSec) { if (allowedRemoval) { int noRemoved = removeVariety(); maxBlanks += noRemoved; totalRemoved += noRemoved; if ((int)riceVarietyList.size() - totalRemoved < maxRiceVarietyUsedCount) { bestEffortSolution = true; return true; } --allowedRemoval; cout << "retrying after removing the variety" << endl; resetFarm(); populateNonConflictingNeighbours(); beginTime = clock(); return recurseAndAssignVarietyToPlots(0, maxBlanks); } else { //cout << "could not assign all varieties in " << maxTimeSec << "seconds. Hence saving the best solution so far for used plot count: " << maxRiceVarietyUsedCount << endl; bestEffortSolution = true; return true; } } /*if (remainingBlanks > 0) { farmPlotList[currentPlotIndex]->assignedVariety = NULL; bool retValue = recurseAndAssignVarietyToPlots(currentPlotIndex + 1, --remainingBlanks); if (retValue == true) { return true; } }*/ int allVarietyUsed = 0; for (int varietyIndex = 0; varietyIndex < (int)riceVarietyList.size(); ++varietyIndex) { riceVariety *currentVariety = riceVarietyList[varietyIndex]; //cout << "CPI "<< currentPlotIndex << " checking rvi " << varietyIndex << endl; if (currentVariety->used == true || currentVariety->blocked == true) { ++allVarietyUsed; // cout << "CPI "<< currentPlotIndex << "already used rvi " << varietyIndex << " " << allVarietyUsed << endl; continue; } if (willItConflict(currentPlotIndex, currentVariety)) { // cout << "CPI "<< currentPlotIndex << "it will conflict rvi " << varietyIndex << endl; continue; } //cout << "CPI "<< currentPlotIndex << "assigning rvi " << varietyIndex << endl; farmPlotList[currentPlotIndex]->assignedVariety = currentVariety; currentVariety->used = true; //cout << "starting trails for plot index : " << currentPlotIndex + 1 << endl; bool retValue = recurseAndAssignVarietyToPlots(currentPlotIndex + 1, remainingBlanks); //cout << "CPI "<< currentPlotIndex << "after recursion got result " << retValue << " for rvi " << varietyIndex << endl; if (retValue == false) { farmPlotList[currentPlotIndex]->assignedVariety = NULL; currentVariety->used = false; continue; } else { return true; } } if (allVarietyUsed == riceVarietyList.size()) { return true; } else if (remainingBlanks > 0) { farmPlotList[currentPlotIndex]->assignedVariety = NULL; bool retValue = recurseAndAssignVarietyToPlots(currentPlotIndex + 1, --remainingBlanks); if (retValue == true) { return true; } } if (allVarietyUsed > maxRiceVarietyUsedCount) { copyRiceVarietyToMaxRiceVariety(); maxRiceVarietyUsedCount = allVarietyUsed; } return false; } bool farm::willItConflict(int currentPlotIndex, riceVariety *possibleVariety) { //plot *currentPlot = farmPlotList[currentPlotIndex]; for (auto &neighbouringPlot : farmPlotAdjacencyMap[currentPlotIndex]) { riceVariety *varietyOnNeighbour = neighbouringPlot->assignedVariety; if (varietyOnNeighbour == NULL) { continue; } /*if ((possibleVariety->nonConflictingNeighbours).find(varietyOnNeighbour) == (possibleVariety->nonConflictingNeighbours).end()) { return true; }*/ if ((possibleVariety->conflictingNeighbours).find(varietyOnNeighbour) != (possibleVariety->conflictingNeighbours).end()) { return true; } } return false; } string farm::getStringFromInt(int num) { #ifdef WIN32 std::strstream ss; #else std::stringstream ss; #endif ss << num; return ss.str(); } void farm::placeRiceinGrid() { try { cout << "INFO: populating rice variety list from input file : " << inputFilePath << endl; populateRiceVarietyList(); int maxWhiteSpaces = 0; if (rows*columns < (int)riceVarietyList.size()) { string errorStr("ERROR : Total number of plots "); char *temp = (char*)malloc(10); errorStr += getStringFromInt(farmPlotList.size()); // itoa((int)farmPlotList.size(), temp, 10); errorStr += " is less than the number of varieties "; errorStr += getStringFromInt(riceVarietyList.size()); free(temp); throw errorStr; } else { maxWhiteSpaces = rows*columns - (int)riceVarietyList.size(); } cout << "INFO: populating conflicting neighbours for rice variety size: " << riceVarietyList.size() << endl; cout << "INFO: No. of pollination days = " << pollinationDays << endl; populateNonConflictingNeighbours(); //sortListAsPerDesiredOrder(); beginTime = clock(); maxRiceVarietyUsedCount = 0; cout << "INFO: try assigning varieties in the farm " << rows << "x" << columns << ". This may take some time " << endl; maxBlanks = maxWhiteSpaces; bool retValue = recurseAndAssignVarietyToPlots(0, maxWhiteSpaces); if (retValue == true) { cout << "INFO: decompiling output in file : " << outputFilePath << endl; decompileFarmGridInCSV(); } else { throw "ERROR : could not find a possible solution for given list of variety and farm size,\n\tplease try by \n\tchanging the list of varieties OR \n\tincreasing farm dimensions"; } } catch (string &errorStr) { cout << errorStr << endl; } catch (char *errorStr) { cout << errorStr << endl; } cout << "\n\tFINISHED !!!!" << endl; } void farm::decompileFarmGridInCSV() { ofstream outfile; outfile.open(outputFilePath.c_str()); if (!outfile) { throw "ERROR: Input file '" + outputFilePath + "' could not be opened, check if it is present"; } for (int hindex=0; hindex<rows; ++hindex) { for (int vindex=0; vindex<columns; ++vindex) { riceVariety *variety = farmGrid[hindex][vindex]->assignedVariety; if (bestEffortSolution) { variety = farmGrid[hindex][vindex]->maxAssignedVariety; } if (variety) { variety->dumped = true; string vName = variety->name; Date dt = variety->sDate; outfile << vName.c_str() << "(FD : " << dt.day << "/" << dt.month << ") ,"; //" " << dt.day << "/" << dt.month << "," ; } else { outfile << " LEAVE EMPTY ,"; } } outfile << endl; } outfile.close(); for (auto &variety : riceVarietyList) { if (variety->dumped == false) { string vName = variety->name; Date dt = variety->sDate; cout << "Unused variety : " << vName.c_str() << "(FD : " << dt.day << "/" << dt.month << ") " << endl; //" " << dt.day << "/" << dt.month << "," ; } } } void farm::copyRiceVarietyToMaxRiceVariety() { for (int hindex=0; hindex<rows; ++hindex) { for (int vindex=0; vindex<columns; ++vindex) { farmGrid[hindex][vindex]->maxAssignedVariety = farmGrid[hindex][vindex]->assignedVariety; } } }
true
02ef080741b1237dbe5b4282a7feb96cbcd3ccbd
C++
liangf/lc150
/sort_list.cpp
UTF-8
1,712
3.71875
4
[]
no_license
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *sortList(ListNode *head) { if (head == NULL) return NULL; int count = 0; ListNode *p = head; while (p != NULL) { count++; p = p->next; } head = sort(head, count); return head; } ListNode* sort(ListNode *head, int len) { if (len == 1) { head->next = NULL; return head; } ListNode *left, *midnode, *right; left = head; midnode = getMiddleNode(head, len); right = midnode->next; left = sort(left, len/2); right = sort(right, len-len/2); head = merge(left, len/2, right, len-len/2); return head; } ListNode* merge(ListNode *left, int lenL, ListNode *right, int lenR) { ListNode *head = new ListNode(-1); ListNode *cur = head; int countL = 0, countR = 0; while(left && right && countL<lenL && countR<lenR) { if (left->val <= right->val) { cur->next = left; left = left->next; countL++; } else { cur->next = right; right = right->next; countR++; } cur = cur->next; } if (countL == lenL) cur->next = right; else cur->next = left; cur = head->next; delete head; return cur; } ListNode* getMiddleNode(ListNode *head, int len) { ListNode *midnode = head; int count = 0; while (midnode != NULL) { count++; if (count == len/2) break; midnode = midnode->next; } return midnode; } }; int main() { ListNode *head = new ListNode(3); head->next = new ListNode(2); head->next->next = new ListNode(1); Solution s; head = s.sortList(head); while (head) { cout << head->val << endl; head = head->next; } }
true
687d2fb0e3e7a24801b99fb74c57ae64165aa5d2
C++
RuslanKutdusov/brdf_playground
/code/Camera.h
UTF-8
2,792
2.75
3
[]
no_license
#pragma once #include "Input.h" enum EProjectionType { kInvalidProjection = 0, kOrthoProjection, kPerspectiveProjection }; class BaseCamera { public: BaseCamera() = default; ~BaseCamera() = default; EProjectionType GetProjectionType() const; virtual void SetPosition(const XMVECTOR& pos); virtual void SetDirection(const XMVECTOR& dir); virtual void SetUp(const XMVECTOR& up); virtual void SetOrientation(const XMVECTOR& pos, const XMVECTOR& dir, const XMVECTOR& up); virtual void SetNearFarPlanes(float nearZ, float farZ); const XMVECTOR& GetPosition() const; const XMVECTOR& GetDirection() const; const XMVECTOR& GetUp() const; float GetNearZ() const; float GetFarZ() const; XMMATRIX GetWorldToViewMatrix() const; virtual XMMATRIX GetProjectionMatrix() const = 0; protected: EProjectionType m_projectionType = kInvalidProjection; XMVECTOR m_pos; XMVECTOR m_up; XMVECTOR m_dir; float m_nearZ; float m_farZ; }; class PerspectiveCamera : public BaseCamera { public: PerspectiveCamera(); void SetAspectRatio(float aspectRatio); void SetFovY(float fovY); float GetAspectRatio() const; float GetFovY() const; XMMATRIX GetProjectionMatrix() const; virtual void HandleInputEvent(const InputEvent& event) = 0; virtual void Update(const InputState& inputState, float elapsedTime) = 0; protected: float m_aspectRatio; float m_fovY; }; class FirstPersonCamera : public PerspectiveCamera { public: void SetOrientation(const XMVECTOR& pos, const XMVECTOR& dir, const XMVECTOR& up); void HandleInputEvent(const InputEvent& event); void Update(const InputState& inputState, float elapsedTime); protected: float m_speed = 4.0f; float m_rotationSpeed = 0.003f; XMINT2 m_prevMousePos = {0, 0}; float m_yawAngle; float m_pitchAngle; }; class OrbitCamera : public PerspectiveCamera { public: void SetOrientation(const XMVECTOR& pos, const XMVECTOR& center, const XMVECTOR& up); void HandleInputEvent(const InputEvent& event); void Update(const InputState& inputState, float elapsedTime); protected: float m_rotationSpeed = 0.003f; XMINT2 m_prevMousePos = {0, 0}; XMVECTOR m_center; float m_distance; float m_yawAngle; float m_pitchAngle; }; inline EProjectionType BaseCamera::GetProjectionType() const { return m_projectionType; } inline const XMVECTOR& BaseCamera::GetPosition() const { return m_pos; } inline const XMVECTOR& BaseCamera::GetDirection() const { return m_dir; } inline const XMVECTOR& BaseCamera::GetUp() const { return m_up; } inline float BaseCamera::GetNearZ() const { return m_nearZ; } inline float BaseCamera::GetFarZ() const { return m_farZ; } inline float PerspectiveCamera::GetAspectRatio() const { return m_aspectRatio; } inline float PerspectiveCamera::GetFovY() const { return m_fovY; }
true
ad8b068126e63af8fed97ff53c4b3799dc5fbf9a
C++
gitmokr/Education
/Chapter3/3_11up.cpp
UTF-8
1,986
3.34375
3
[]
no_license
#include "../../Hello, World!/Hello, World!/std_lib_facilities.h" int main() { cout << "How many one - cent coins do you have?\n"; int a; cin >> a; cout << "How many five - cent coins do you have?\n"; int b; cin >> b; cout << "How many ten - cent coins do you have?\n"; int c; cin >> c; cout << "How many twenty - cent coins do you have?\n"; int d; cin >> d; cout << "How many fifty - cent coins do you have?\n"; int f; cin >> f; int m; int r; int y; if (a > 1) { cout << "You have " << a << " one - cent coins\n"; } else { if (a == 1) { cout << "You have " << a << " one - cent coin\n"; } else { if (a < 1) { cout << "You don't have a one - cent coins.\n"; } } } if (b > 1) { cout << "You have " << b << " five - cent coins\n"; } else { if (b == 1) { cout << "You have " << b << " five - cent coin\n"; } else { if (b < 1) { cout << "You don't have a five - cent coins.\n"; } } } if (c > 1) { cout << "You have " << c << " ten - cent coins\n"; } else { if (c == 1) { cout << "You have " << c << " ten - cent coin\n"; } else { if (c < 1) { cout << "You don't have a ten - cent coins.\n"; } } } if (d > 1) { cout << "You have " << d << " twenty - cent coins\n"; } else { if (d == 1) { cout << "You have " << d << " twenty - cent coin\n"; } else { if (d < 1) { cout << "You don't have a twenty - cent coins.\n"; } } } if (f > 1) { cout << "You have " << f << " fifty - cent coins\n"; } else { if (f == 1) { cout << "You have " << f << " fifty - cent coin\n"; } else { if (f < 1) { cout << "You don't have a fifty - cent coins.\n"; } } } m = a + (b * 5) + (c * 10) + (d * 20) + (f * 50); r = m / 100; y = m % 100; cout << "You have " << r << " grivn " << y << " kopiok."; }
true
c61902ddd51bb4626f9fa0fc8cb4c2ad195e7c2a
C++
ConstanceYn/GameLoa
/src/MonstreNul.cpp
UTF-8
320
2.78125
3
[]
no_license
#include "MonstreNul.hpp" #include "Plateau.hpp" MonstreNul::MonstreNul(int x, int y):Monstre(x , y){ setSymbole('n'); } bool MonstreNul::teleport(int x, int y, Plateau& p) { if (!bouge){ int a = (rand()%3)-1; int b = (rand()%3)-1; bouge = true; return moving(y+a, x+b, p); } return false; }
true
3724d9215dc27267caa4ffb0466559b0621d3fd5
C++
Sahar-Alwakily/GitTeam11
/ProjectTeam11/ProjectTeam11.cpp
UTF-8
2,362
2.9375
3
[]
no_license
// ProjectTeam11.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include "Person.h" #include <fstream> #include <istream> #include <iostream> #include <string.h> #include "Employee.h" #include "Student.h" #include "Employee.h" #include "WorkingStudent.h" #include <iostream>> #include <string> using namespace std; #include <iostream> int main() { int c; int size; string Name; long id; int age; int average; string institute; float salary; bool sameinstitute = true; cout << "How much u need ?" << endl; cin >> size; Person** persons = new Person*[size]; for (int i = 0; i < size; i++) { cout << " what u need type Person" << endl << " 1- Person" << endl << "2- Student" << endl << "3 - Employee" << endl << "4- Working Student and Employee " << endl; cin >> c; if (c == 1) { cout << " Add for Person id ,Name , age : " << endl; cin >> id >> Name >> age; persons[i] = new Person(id, Name, age); } else if (c == 2) { cout << "add for Student : id , Name , age, average, institute " << endl; cin >> Name >> id >> age >> average >> institute; persons[i] = new Student(id, Name, age, average, institute); } else if (c == 3) { cout << " Add for Employee :id , name , age, salary: " << endl; cin >> Name >> id >> age >> salary; persons[i] = new Employee(id, Name, age, salary); } else if (c == 4) { cout << "Add for Working Student and Employee id ,name, age, salary,same_institute :" << endl; cin >> Name >> id >> age >> salary; persons[i] = new WorkingStudent(id, Name, age, average, institute, salary, same_institute); } } for (int i = 0; i < size; i++) { persons[i].Print(); } } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
true
b1f9b8ee95b35f12ed52d0ed74c5c0c4df88e815
C++
pretentiousgit/servo-party
/ADCTouch_Servo/ADCTouch_Servo.ino
UTF-8
1,747
2.703125
3
[]
no_license
#include <ADCTouch.h> #include <Servo.h> #ifdef __AVR_ATtiny85__ // Trinket, Gemma, etc. #include <avr/power.h> #endif // Pin Definitions #define ADC_BASE A0 #define ADC_READ A1 #define TOGGLE 40 // this is the yes-no threshold for touch #define ServoPin 9 #define TEST_LED 10 // Values for ADCTouch int ref0, ref1; //reference values to remove offset Servo towerServo; void setup() { // Turn on the serial port Serial.begin(9600); // Turn on ADCTouch and get base values ref0 = ADCTouch.read(ADC_BASE, 500); //create reference values to ref1 = ADCTouch.read(ADC_READ, 500); //account for the capacitance of the pad // Attach your servo towerServo.attach(ServoPin); // Set up the TEST_LED pinMode(TEST_LED, OUTPUT); } void loop() { int value0 = ADCTouch.read(ADC_BASE); // no second parameter int value1 = ADCTouch.read(ADC_READ); // --> 100 samples value0 -= ref0; // remove offset value1 -= ref1; // remove offset bool v0touched = value0 > TOGGLE; bool v1touched = value1 > TOGGLE; int constrainedValue = constrain(value1, 0, 180); String stringOne = "constrainedVal: "; String report = stringOne + constrainedValue; int servoVal = map(constrainedValue, 0, 180, 0, 180); int ledVal = map(constrainedValue, 0, 180, 150, 255); // Write code below here towerServo.write(servoVal); analogWrite(TEST_LED, 255); // print report to serial Serial.print(report); Serial.print(" | v1 "); Serial.print(value1); Serial.print(v1touched); Serial.print(" | servoVal: "); Serial.print(servoVal); Serial.print(" | LEDVal: "); Serial.print(ledVal); Serial.print("\n"); delay(15); }
true
d3bbe86f5f16aa7589db723f22b8281427a2f9b6
C++
AvantikaJalote/SEM_3_PRACTICALS_SY
/EXPERIMENT 3/PRAC3C_ALTERNATE.cpp
UTF-8
2,829
3.765625
4
[]
no_license
#include<iostream> #include<math.h> #define pi 3.14 using namespace std; inline double cube(float length) //calculates volume for cube //inline function { double vol=pow(length,3); return vol; } inline double sphere(float radius) //calculates volume for sphere //inline function { double vol=(4*pi*(pow(radius,3)))/3; return vol; } inline double cylinder(float radius,float height) //calculates volume for cylinder //inline function { double vol=pi*height*(pow(radius,2)); return vol; } inline double cone(float radius, float height) //calculates volume for cone //inline function { double vol=(pi*height*(pow(radius,2)))/3; return vol; } int main() { int choice; //select shape int cont; //takes choice if one wants to see main menu float length,height,radius; double vol; do { a: cout<<"\nMENU:"; cout<<"\n1.Cube"; cout<<"\n2.Sphere"; cout<<"\n3.Cylinder"; cout<<"\n4.Cone"; cout<<"\nEnter choice:"; cin>>choice; if(choice>4 || choice<1) //checks if menu choice entered is correct { cout<<"\nInvalid choice"; goto a; } switch(choice) { case 1: //for cube cout<<"\nEnter the length of side of the cube: "; cin>>length; vol=cube(length); cout<<"The volume of the cube is: "<<vol; break; case 2: //for radius cout<<"\nEnter the radius for the sphere: "; cin>>radius; vol=sphere(radius); cout<<"The volume of the sphere is: "<<vol; break; case 3: //for cylinder cout<<"\nEnter radius for the cylinder: "; cin>>radius; cout<<"Enter height for the cylinder: "; cin>>height; vol=cylinder(radius,height); cout<<"The volume of the cylinder is: "<<vol; break; case 4: //for cone cout<<"\nEnter radius for the cone: "; cin>>radius; cout<<"Enter height for the cone: "; cin>>height; vol=cone(radius,height); cout<<"The volume of the cone is: "<<vol; break; default: cout<<"\nInvalid input"; break; } cout<<"\n\nDo you want to see the menu?"; cout<<"\n1. Yes\n2. No"; cout<<"\nEnter choice:"; cin>>cont; }while(cont==1); return 0; }
true
b25c0c9ca70d5567bdf1aad96a56666eee4bf29e
C++
AutumnKite/Codes
/Codeforces/1511F Chainword/std.cpp
UTF-8
2,139
2.546875
3
[]
no_license
#include <bits/stdc++.h> const int P = 998244353; typedef std::vector<std::vector<int>> matrix; matrix operator*(const matrix &a, const matrix &b) { matrix s(a.size(), std::vector<int>(b[0].size())); for (int i = 0; i < (int)a.size(); ++i) { for (int k = 0; k < (int)b.size(); ++k) { for (int j = 0; j < (int)b[0].size(); ++j) { s[i][j] = (s[i][j] + 1ll * a[i][k] * b[k][j]) % P; } } } return s; } matrix qpow(matrix a, int b) { matrix s(a.size(), std::vector<int>(a.size())); for (int i = 0; i < (int)a.size(); ++i) { s[i][i] = 1; } for (; b; b >>= 1) { if (b & 1) { s = s * a; } a = a * a; } return s; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); int n, m; std::cin >> n >> m; std::vector<std::string> a(n); int mx = 0; for (int i = 0; i < n; ++i) { std::cin >> a[i]; mx = std::max(mx, (int)a[i].size()); } auto id = [&](int i, int j, int k) { return i * (mx * n + 1) + (j - 1) * n + k; }; matrix A(mx * (mx * n + 1), std::vector<int>(mx * (mx * n + 1))); for (int i = 0; i < mx; ++i) { for (int j = 1; j <= mx; ++j) { for (int k = 0; k < n; ++k) { if (i) { ++A[id(i, j, k)][id(i - 1, j, k)]; } for (int t = 0; t < n; ++t) { int lk = a[k].size(), lt = a[t].size(); bool flag = true; for (int p = 0; p < j && p < lt; ++p) { flag &= a[k][lk - j + p] == a[t][p]; } if (flag && i + std::min(j, lt) == mx) { if (lt < j) { ++A[id(i, j, k)][id(mx - 1, j - lt, k)]; } else if (lt > j) { ++A[id(i, j, k)][id(mx - 1, lt - j, t)]; } else { ++A[id(i, j, k)][id(mx - 1, mx + 1, 0)]; } } } } } if (i) { ++A[id(i, mx + 1, 0)][id(i - 1, mx + 1, 0)]; } } matrix B(mx * (mx * n + 1), std::vector<int>(mx * (mx * n + 1))); for (int i = 0; i < mx * (mx * n + 1); ++i) { B[i][i] = 1; } for (int t = 0; t < n; ++t) { ++B[id(mx - 1, mx + 1, 0)][id(mx - 1, a[t].size(), t)]; } matrix st(1, std::vector<int>(mx * (mx * n + 1))); st[0][id(mx - 1, mx + 1, 0)] = 1; st = st * qpow(B * A, m); std::cout << st[0][id(mx - 1, mx + 1, 0)] << "\n"; }
true
0ab7cc0ff16111d7ba7499ebac26c3ada2e7f421
C++
arabham/BattleTank
/Source/BattleTank/TankPlayerController.cpp
UTF-8
1,904
2.59375
3
[]
no_license
// Property of Do Over Games #include "TankPlayerController.h" #include "Engine/World.h" #include "DrawDebugHelpers.h" void ATankPlayerController::BeginPlay() { Super::BeginPlay(); } void ATankPlayerController::Tick(float DeltaTime) { Super::Tick(DeltaTime); AimTowardCrosshair(); } ATank* ATankPlayerController::GetControlledTank() const { return Cast<ATank>(GetPawn()); } void ATankPlayerController::AimTowardCrosshair() { if (!GetControlledTank()) { return; } FVector HitLocation; if (GetSightRayHitLocation(HitLocation)) { GetControlledTank()->AimAt(HitLocation); } } bool ATankPlayerController::GetSightRayHitLocation(FVector& HitLocation) const { // Find crosshair position in pixel coordinates int32 ViewportSizeX, ViewportSizeY; GetViewportSize(ViewportSizeX, ViewportSizeY); FVector2D ScreenLocation = FVector2D((ViewportSizeX * CrosshairXLocation), (ViewportSizeY * CrosshairYLocation)); // Deproject the screen position of the crosshair to a world direction FVector LookDirection; if (GetLookDirection(ScreenLocation, LookDirection)) { GetLookVectorHitLocation(LookDirection, HitLocation); return true; } return false; } bool ATankPlayerController::GetLookDirection(FVector2D ScreenLocation, FVector& LookDirection) const { FVector WorldLocation; // to be discarded return DeprojectScreenPositionToWorld(ScreenLocation.X, ScreenLocation.Y, WorldLocation, LookDirection); } bool ATankPlayerController::GetLookVectorHitLocation(FVector LookDirection, FVector& HitLocation) const { FHitResult HitResult; FVector TraceStart = PlayerCameraManager->GetCameraLocation(); FVector TraceEnd = TraceStart + (LookDirection * LineTraceRange); if (GetWorld()->LineTraceSingleByChannel(HitResult, TraceStart, TraceEnd, ECollisionChannel::ECC_Visibility)) { HitLocation = HitResult.Location; return true; } HitLocation = FVector(0); return false; }
true
e59b1e4e457801ca8d2bb66255ba5b90ba69e7ae
C++
AshtonBowen/2D-mobile-Robotics
/lab2_aria/lab2_aria/lib/edgeFollow.h
UTF-8
1,156
2.90625
3
[]
no_license
#include <ArAction.h> #include "PID.h" #include "Mapping.h" #include "FrameTime.h" class edgeFollow : public ArAction { public: edgeFollow(); //A default constructor virtual ~edgeFollow() {}; //A defualt deconstuctor virtual ArActionDesired * fire(ArActionDesired d); //A fire function for the action ArActionDesired desiredState; //A state to be returned for the robot for decisions to determine which action should be executed protected: int speed; //Speed of the robot in mm/s double deltaHeading; //Change in heading double m_distLeftSensor; //A variable to store the value from the sensors double m_distRightSensor; double m_angle; //A output from the sensors that stores the angle at which the closest point from to the robot to the object //Time till write float m_targetTime; //A variable that holds the target time //Time Keeping FrameTime Time; //A Object for accessing the timer //Mapping Mapping map; //A object for storing and creating the map //PID PID LeftCal; //Objects for left and right PID control system PID RightCal; };
true
6f1c01a6ba8f729aa03ef322363207914ae33c4d
C++
championloser/learn
/bo_thread/thread.h
UTF-8
399
2.5625
3
[]
no_license
#ifndef __THREAD_H__ #define __THREAD_H__ #include<pthread.h> #include<functional> namespace jjx { class Thread { public: //Thread(std::function<void()> cb); Thread(std::function<void()> &&cb); ~Thread(); void start(); void join(); private: static void * pthreadFunc(void *); private: pthread_t _pthid; bool _isRunning; std::function<void()> _callBack; }; }//end of namespace jjx #endif
true
0364929bcd82828617e5f1c760d1e64bf920f308
C++
Parmie/Vanagon
/src/ECUReader/Tools/Button.cpp
UTF-8
634
2.640625
3
[]
no_license
#ifndef Button_cpp #define Button_cpp #include <Arduino.h> #include "..\Arduino\DigitalInput.cpp" class Button { private: DigitalInput *_input; void (*_clickHandler)(void*); void *_clickHandlerData; typedef void (*callback)(void*); public: template<typename T> Button(DigitalInput *input, void (*clickHandler)(T*), T *userData) { _input = input; _clickHandler = (callback)clickHandler; _clickHandlerData = (void*)userData; }; void read() { _input->read(); if (_input->getRising()) { _clickHandler(_clickHandlerData); } }; }; #endif
true
0ea82017b514f0515f333325e36380c3c149aa96
C++
cpopescu/whisperlib2
/whisperlib/io/path.cc
UTF-8
3,941
2.953125
3
[]
no_license
#include "whisperlib/io/path.h" #include "absl/strings/str_cat.h" namespace whisper { namespace path { absl::string_view Basename(absl::string_view path) { auto pos = path.rfind(kDirSeparator); if (pos == absl::string_view::npos) { return path; } return path.substr(pos + 1); } absl::string_view Dirname(absl::string_view path) { auto pos = path.rfind(kDirSeparator); if (pos == absl::string_view::npos) { return ""; } return path.substr(0, pos); } std::string Normalize(absl::string_view path, char sep) { std::string s(path); const char sep_str[] = { sep, '\0' }; // Normalize the slashes and add leading slash if necessary for ( size_t i = 0; i < s.size(); ++i ) { if ( s[i] == '\\' ) { s[i] = sep; } } bool slash_added = false; if ( s[0] != sep ) { s = sep_str + s; slash_added = true; } // Resolve occurrences of "///" in the normalized path const char triple_sep[] = { sep, sep, sep, '\0' }; while ( true ) { const size_t index = s.find(triple_sep); if ( index == std::string::npos ) break; s = s.substr(0, index) + s.substr(index + 2); } // Resolve occurrences of "//" in the normalized path (but not beginning !) const char* double_sep = triple_sep + 1; while ( true ) { const size_t index = s.find(double_sep, 1); if ( index == std::string::npos ) break; s = s.substr(0, index) + s.substr(index + 1); } // Resolve occurrences of "/./" in the normalized path const char sep_dot_sep[] = { sep, '.', sep, '\0' }; while ( true ) { const size_t index = s.find(sep_dot_sep); if ( index == std::string::npos ) break; s = s.substr(0, index) + s.substr(index + 2); } // Resolve occurrences of "/../" in the normalized path const char sep_dotdot_sep[] = { sep, '.', '.', sep, '\0' }; while ( true ) { const size_t index = s.find(sep_dotdot_sep); if ( index == std::string::npos ) break; if ( index == 0 ) return slash_added ? "" : sep_str; // The only left path is the root. const size_t index2 = s.find_last_of(sep, index - 1); if ( index2 == std::string::npos ) return slash_added ? "": sep_str; s = s.substr(0, index2) + s.substr(index + 3); } // Resolve ending "/.." and "/." { const char sep_dot[] = { sep, '.' , '\0' }; const size_t index = s.rfind(sep_dot); if ( index != std::string::npos && index == s.length() - 2 ) { s = s.substr(0, index); } } { const char sep_dotdot[] = { sep, '.', '.', '\0' }; size_t index = s.rfind(sep_dotdot); if ( index != std::string::npos && index == s.length() - 3 ) { if ( index == 0 ) return slash_added ? "": sep_str; const size_t index2 = s.find_last_of(sep, index - 1); if ( index2 == std::string::npos ) return slash_added ? "": sep_str; s = s.substr(0, index2); } if ( !slash_added && s.empty() ) s = sep_str; } if ( !slash_added || s.empty() ) return s; return s.substr(1); } std::string Join(absl::string_view path1, absl::string_view path2, char path_separator) { if (path1.empty()) { return std::string(path2); } if (path2.empty()) { return std::string(path1); } if ((path1.size() == 1 && *path1.begin() == path_separator) || *path2.begin() == path_separator || *path1.rbegin() == path_separator) { return absl::StrCat(path1, path2); } return absl::StrCat(path1, absl::string_view(&path_separator, 1), path2); } std::string Join(absl::Span<std::string> paths) { std::string result_path; for (absl::string_view path : paths) { result_path = Join(result_path, path); } return result_path; } std::string Join(std::initializer_list<absl::string_view> paths) { std::string result_path; for (absl::string_view path : paths) { result_path = Join(result_path, path); } return result_path; } } // namespace path } // namespace whisper
true
0dc8d772500b2353c3d5c388d12ab8fda0e068f1
C++
ggjae/Algorithm-CS
/cpp/greedy/1783.cpp
UTF-8
557
3.265625
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int N, M; int main(void) { cin >> N >> M; if (N == 1) cout << 1 << endl; else if (N == 2) cout << min(4, (M + 1) / 2) << endl; //1, 2, 3, 4번이 적어도 한번씩은 나와야 한다 else if (N >= 3) { //가로가 6까지는 최대 4칸(1번, 4번, 2 or 3번) if (M <= 6) cout << min(4, M) << endl; else //2번 3번 한번씩 나머지는 1번, 4번 cout << M - 2 << endl; } return 0; }
true
9eb2856db1b8d727b238c249a8ff63a584d56f54
C++
walkccc/LeetCode
/solutions/2024. Maximize the Confusion of an Exam/2024.cpp
UTF-8
409
2.65625
3
[ "MIT" ]
permissive
class Solution { public: int maxConsecutiveAnswers(string answerKey, int k) { int ans = 0; int maxCount = 0; vector<int> count(2); for (int l = 0, r = 0; r < answerKey.length(); ++r) { maxCount = max(maxCount, ++count[answerKey[r] == 'T']); while (maxCount + k < r - l + 1) --count[answerKey[l++] == 'T']; ans = max(ans, r - l + 1); } return ans; } };
true
55c7bf1fa8426a948fe35b39c9ceb05175031072
C++
shubhampachori12110095/MDEVLRPTW
/Code/source/Helper.cpp
UTF-8
616
2.8125
3
[]
no_license
#include "../header/Helper.h" int** Helper::initializeIntegerMatriz(int length) { int **pij = new int *[length]; for(int i = 0; i < length; i++) { pij[i] = new int[length]; } return pij; } int** Helper::initializeIntegerMatriz(int length, int width) { int **pij = new int *[length]; for(int i = 0; i < length; i++) { pij[i] = new int[width]; } return pij; } float** Helper::initializeFloatMatriz(int length) { float **dij = new float *[length]; for(int i = 0; i < length; i++) { dij[i] = new float[length]; } return dij; }
true
02e18d1ae20e624aaa7c10817984a5ddc5daa81b
C++
huiyugan/3D_RFUltrasound_Reconstruction
/IntensityCompounding.cpp
UTF-8
2,125
3.15625
3
[ "MIT" ]
permissive
#include "IntensityCompounding.h" #include <stdio.h> #include <iostream> GaussianWeightedCompounding::GaussianWeightedCompounding(float sigma) { m_sigma = sigma; m_sigmaSQR = pow(sigma, 2.0f); } float GaussianWeightedCompounding::evaluate(std::vector<float> *intensityVector, std::vector<float> *distanceVector) { int _size = intensityVector->size(); float _intensityDenominator = 0.0f; float _intensityNominator = 0.0; std::vector<float>::iterator _distance = distanceVector->begin(); for(std::vector<float>::iterator _intensity = intensityVector->begin(); _intensity !=intensityVector->end();_intensity++, _distance++ ) { float _euclideanDistanceSQR = pow((*_distance),2.0f); const float _tempRatio = exp(-(_euclideanDistanceSQR)/(m_sigmaSQR)); // add the intensity contribution by weighting distance to the nominator and denominator // which after considering all relevant pixels will by division supply the gaussian interpolated intensity _intensityDenominator += _tempRatio; _intensityNominator += (*_intensity) * _tempRatio; } if ( _intensityDenominator > 0.0 ) return _intensityNominator / _intensityDenominator; else return 0.0; } MeanCompounding::MeanCompounding() { std::cout << "Mean Compounding ... " << std::endl; } float MeanCompounding::evaluate(std::vector<float> *intensityVector, std::vector<float> *distanceVector) { int _size = intensityVector->size(); float _intensityDenominator = 0.0f; float _intensityNominator = 0.0; std::vector<float>::iterator _distance = distanceVector->begin(); for(std::vector<float>::iterator _intensity = intensityVector->begin(); _intensity !=intensityVector->end();_intensity++, _distance++ ) { // add the intensity contribution by weighting distance to the nominator and denominator // which after considering all relevant pixels will by division supply the gaussian interpolated intensity _intensityNominator += (*_intensity); } if ( _size > 0 ) return _intensityNominator / static_cast<float>(_size); else return 0.0; }
true
6432ff47c9b879107b14f90da247ebcb268d7ad2
C++
buotex/problems
/maxprod.cpp
UTF-8
982
3.1875
3
[]
no_license
#include <vector> #include <algorithm> #include <iostream> using namespace std; class Solution { public: int maxProduct(int A[], int n) { vector<int> memory(n); int start =1; for (int i = 0 ; i < n; ++i){ memory[i] = (start *= A[i]); if (memory[i] == 0) start = 1; } int minabs = 1; int minint = 1; int maxint = memory[0]; for (int i = 1; i < n; ++i){ if (memory[i] > 0){ maxint = std::max(memory[i] / minint, maxint); minint = std::min(minint, memory[i]); } else if (memory [i] < 0){ maxint = std::max(-memory[i] / minabs, maxint); std::cout << minabs << " " << -memory[i] << std::endl; minabs = std::min(minabs, -memory[i]); } } return maxint; } }; int main() { int a[3] = {-2,0,-1}; Solution sol; return sol.maxProduct(a, 3); }
true
4351193f23cc7dd2758ab77ad78940fb9992b7a6
C++
eval1749/evita
/evita/gfx/rect_conversions.cc
UTF-8
926
2.671875
3
[]
no_license
// Copyright (c) 2014 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "evita/gfx/rect_conversions.h" #include <ctgmath> namespace gfx { // Returns the largest Rect that is enclosed by the given RectF. Rect ToEnclosedRect(const RectF& rect) { return gfx::Rect(static_cast<int>(::ceil(rect.left)), static_cast<int>(::ceil(rect.top)), static_cast<int>(::floor(rect.right)), static_cast<int>(::floor(rect.bottom))); } // Returns the smallest Rect that encloses the given RectF. Rect ToEnclosingRect(const RectF& rect) { return gfx::Rect(static_cast<int>(::floor(rect.left)), static_cast<int>(::floor(rect.top)), static_cast<int>(::ceil(rect.right)), static_cast<int>(::ceil(rect.bottom))); } } // namespace gfx
true
4d6d811f6f6413638fb06b4655d36e5cc42c33e7
C++
luqmaan/object-oriented
/random-number-generator/aRandomNumberGenerator.h
UTF-8
712
3.390625
3
[]
no_license
#include <iostream> #include <string> using namespace std; class aRandomNumberGenerator { public: aRandomNumberGenerator() { srand ( time(NULL) ); } void setLow(int l) { low = (int) l; } void setHigh(int h) { high = h; } int generate() { //if (low == NULL || high == NULL) { //throw "error, run setHigh or setLow"; //} int mod = (high - low) +1; int num = (rand() % mod); return num + 1; }; private: int low; int high; }; class Tracker { public: Tracker() { for (int i = 0; i < 8; i++) { count[i] = 0; } } void trackInt(int n) { count[n - 1]++; }; int getCount(int n) { return count[n-1]; } private: // length = high - low int count[8]; };
true
58e48f4c75cff3c4954f501484907df958af84fb
C++
muhammadaliwafa/Collection
/Serial Communication Arduino to ESP/ESP_RX/ESP_RX.ino
UTF-8
890
2.765625
3
[]
no_license
#include <ArduinoJson.h> #include <SoftwareSerial.h> SoftwareSerial fromArduino(D2,D3);//(RX, TX ESP) String dataKirim; void setup() { Serial.begin(9600); fromArduino.begin(9600); } void loop() { if(fromArduino.available()) { char c = fromArduino.read(); if(c == '}') { dataKirim += c; //data masuk String input = dataKirim; float v = value(input, "float").toFloat(); long it = value(input, "sensor2").toInt(); String str = value(input, "sensor1"); Serial.println(v,3); Serial.println(it); Serial.println(str); dataKirim = ""; } else { dataKirim += c; } } } String value(String input, String key){ int sindex = input.indexOf(key); int koma = input.indexOf(",", sindex); int colon = input.indexOf(":", sindex); String value = input.substring(colon+1, koma); return value; }
true
77c7cc01c430285e048f217c51aeadf353beaca3
C++
aishwarya4444/codeChallenges
/cp/lb/02_number_theory/euclid/cf_complicatedGCD.cpp
UTF-8
467
2.75
3
[]
no_license
/* https://codeforces.com/problemset/problem/664/A We examine two cases: a=b — the segment consists of a single number, hence the answer is a. a<b — we have gcd(a,a+1,a+2,...,b)=gcd(gcd(a,a+1),a+2,...,b)=gcd(1,a+2,...,b)=1. */ #include <bits/stdc++.h> #define si(n) scanf("%d", &n) #define sll(n) scanf("%lld", &n) #define ll long long using namespace std; int main() { string a, b; cin>>a>>b; if(a==b) { cout<<a; } else { cout<<1; } return 0; }
true
b603a95cf4e13f197602cc97bf69cd0e275e9460
C++
wuyou33/robot_cgmres
/src/common/memory_manager.cpp
UTF-8
866
2.8125
3
[ "BSD-2-Clause" ]
permissive
#include "common/memory_manager.hpp" namespace robotcgmres { namespace memorymanager { double* NewVector(const int dim) { if (dim > 0) { double* vec = new double[dim]; for (int i=0; i<dim; ++i) { vec[i] = 0; } return vec; } else { return nullptr; } } void DeleteVector(double* vec) { delete[] vec; } double** NewMatrix(const int dim_row, const int dim_column) { if (dim_row > 0 && dim_column > 0) { double** mat = new double*[dim_row]; mat[0] = new double[dim_row*dim_column]; for (int i=1; i<dim_row; ++i) { mat[i] = mat[i-1] + dim_column; } for (int i=0; i<dim_row*dim_column; ++i) { mat[0][i] = 0; } return mat; } else { return nullptr; } } void DeleteMatrix(double** mat) { delete[] mat[0]; delete[] mat; } } // namespace memorymanager } // namespace robotcgmres
true
c21fb58b4cddf0dffc521171d52b7d623fcfcc4f
C++
ByteNybbler/MannVsFate
/MannVsFate/weapon.cpp
UTF-8
1,191
2.515625
3
[]
no_license
#include "weapon.h" // Set to 0 to disable debug messages for weapons. #define WEAPON_DEBUG 0 #if WEAPON_DEBUG #include <iostream> #endif weapon::weapon() : has_projectiles(false), arc_fire(false), can_be_switched_to(true), does_damage(true), bots_too_dumb_to_use(false), can_be_charged(false), burns(false), explodes(false), bleeds(false), has_effect_charge_bar(false), projectile_override_crash_risk(false) {} weapon::~weapon() { #if WEAPON_DEBUG std::cout << "Weapon destroyed: " << first_name() << std::endl; #endif } bool weapon::is_a(const std::string& name) { for (unsigned int i = 0; i < names.size(); ++i) { if (names.at(i) == name) { return true; } } return false; } std::string weapon::first_name() const { return names.at(0); } bool weapon::matches_restriction(weapon_restrictions restriction) { if (type == slot::primary && (restriction == weapon_restrictions::primary || restriction == weapon_restrictions::none)) { return true; } if (type == slot::secondary && restriction == weapon_restrictions::secondary) { return true; } if (type == slot::melee && restriction == weapon_restrictions::melee) { return true; } return false; }
true
f1b6e221cd28ac15fed475e6eb3dd2bb7e969f61
C++
Tapia641/escom-sistemas-distribuidos
/7. C++/Desempeño_C++/string.cpp
UTF-8
811
3.390625
3
[]
no_license
//STRING IPN C++ #include <iostream> #include <string> #include <string.h> using namespace std; string generateString(){ static const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string s = ""; for (int i = 0; i < 3; ++i) { s += alphanum[rand() % (sizeof(alphanum) - 1)]; } return s; } void function(){ srand (time(NULL)); int N; cout<<"Ingresa N:"<<endl; cin >> N; // SOLUCION string stringVariable; int countIPN = 0; for (int i = 0; i < N; i++) { string stringG = generateString(); //stringG += " "; string ipn="IPN"; if (stringG.compare(ipn)==0) { countIPN++; } } cout<<countIPN<<endl; } int main(int argc, char const *argv[]) { function(); return 0; }
true
dad23c04ebe46e1156369eeb3560d92ed7b9dcbd
C++
gfcodearq/TP-FINAL-MAVI
/MAVI - TP_FINAL/BaseObjeto.h
UTF-8
1,111
2.828125
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include <string> using namespace sf; using namespace std; class BaseObjeto { public: BaseObjeto(string fileName, Vector2f vel); ~BaseObjeto(); //destructor void Draw(RenderWindow* wnd); //dibuja el objeto en pantalla void Update(float delta_t); //actualiza la posicion del objeto void SetScale(float uniformScale) {spr->setScale(uniformScale, uniformScale);} //setea la escala void SetPosition(Vector2f pos) { position = pos; } //setea la posicion void SetVelocity(Vector2f vel) { velocity = vel; } //setea la velocidad void SetAcceleration(Vector2f acc) { acceleration = acc; } //setea la aceleracion Vector2f GetPosition() { return position; } //devuelve la posicion Vector2f GetVelocity() { return velocity; } //devuelve la velocidad Vector2f GetAcceleration() { return acceleration; } //devuelve la aceleracion void AddAcceleration(Vector2f acc) { acceleration.x += acc.x; acceleration.y += acc.y; } private: Sprite *spr; Texture *tex; Vector2f position; Vector2f acceleration; Vector2f velocity; };
true
ff350dbb85df4df8466080ea59674b928c9ae2b0
C++
porcupineG/eviewer
/src/tree/typename.cpp
UTF-8
910
2.828125
3
[]
no_license
#include "typename.h" TypeName::TypeName(QString name) { this->name = name; treeWidgetItem = new QTreeWidgetItem(); treeWidgetItem->setText(0, name); } QMap<unsigned long long, TypeValue *> *TypeName::getChilds() { return &childs; } TypeValue * TypeName::insertChild(TypeValue *value) { TypeValue * val; QMap<unsigned long long int, TypeValue *>::iterator it = childs.find(value->getValue()); if (it == childs.end()) { val = *(childs.insert(value->getValue(), value)); } else { val = *it; } treeWidgetItem->addChild(val->getTreeWidgetItem()); val->setParent(this); return val; } QString TypeName::getName() { return name; } LevelName *TypeName::getParent() { return parent; } void TypeName::setParent(LevelName *parent) { this->parent = parent; } QTreeWidgetItem *TypeName::getTreeWidgetItem() { return treeWidgetItem; }
true