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
dd16c996f516df632e96f8726a79044b9f784b37
C++
ia-toki/tcframe
/test/integration/resources/runner/evaluator/scorer/custom/scorer.cpp
UTF-8
701
3.09375
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; /* * AC if contestant's second line is a permutation of judge's. * */ int N; vector<int> read(ifstream& out) { string answer; out >> answer; vector<int> numbers(N); for (int i = 0; i < N; i++) { out >> numbers[i]; } sort(numbers.begin(), numbers.end()); return numbers; } int main(int argc, char* argv[]) { ifstream tc_in(argv[1]); ifstream tc_out(argv[2]); ifstream con_out(argv[3]); tc_in >> N; vector<int> ans_judge = read(tc_out); vector<int> ans_con = read(con_out); if (ans_judge == ans_con) { cout << "AC" << endl; } else { cout << "WA" << endl; } }
true
0f247e5c4bbd0436bdf7c6e3f42a56feb45b1848
C++
kosehy/42_cpp-piscine
/d02/ex02/Fixed.class.cpp
UTF-8
2,565
3.390625
3
[]
no_license
#include "Fixed.class.hpp" int Fixed::_bit = 8; Fixed::Fixed(void) : _fp(0) { std::cout << "Default constructor called" << std::endl; } Fixed::Fixed(const int fp) : _fp(fp << _bit) { std::cout << "Int constructor called" << std::endl; } Fixed::Fixed(const float fp) : _fp(fp * ( 1 << _bit)) { std::cout << "Float constructor called" << std::endl; } Fixed::Fixed(const Fixed &old) { std::cout << "Copy constructor called" << std::endl; _fp = old.getRawBits(); } Fixed::~Fixed(void) { std::cout << "Destructor called" << std::endl; } Fixed &Fixed::operator = (Fixed const &rhs) { std::cout << "Assignation operator called" << std::endl; if (this != &rhs) this->_fp = rhs.getRawBits(); return (*this); } bool Fixed::operator > (const Fixed &rhs) const { return (_fp > rhs.getRawBits()); } bool Fixed::operator < (const Fixed &rhs) const { return (_fp < rhs.getRawBits()); } bool Fixed::operator >= (const Fixed &rhs) const { return (_fp >= rhs.getRawBits()); } bool Fixed::operator <= (const Fixed &rhs) const { return (_fp <= rhs.getRawBits()); } bool Fixed::operator == (const Fixed &rhs) const { return (_fp == rhs.getRawBits()); } bool Fixed::operator != (const Fixed &rhs) const { return (_fp != rhs.getRawBits()); } Fixed Fixed::operator + (Fixed const &rhs) const { return (this->toFloat() + rhs.toFloat()); } Fixed Fixed::operator - (Fixed const &rhs) const { return (this->toFloat() - rhs.toFloat()); } Fixed Fixed::operator * (Fixed const &rhs) const { return (this->toFloat() * rhs.toFloat()); } Fixed Fixed::operator / (Fixed const &rhs) const { return (this->toFloat() / rhs.toFloat()); } Fixed& Fixed::operator ++(void) { ++_fp; return (*this); } Fixed Fixed::operator ++(int) { Fixed tmp = *this; this->_fp++; return (tmp); } Fixed& Fixed::operator --(void) { --_fp; return (*this); } Fixed Fixed::operator --(int) { Fixed tmp = *this; this->_fp--; return (tmp); } int Fixed::getRawBits(void) const { std::cout << "getRawBits member function called" << std::endl; return (_fp); } void Fixed::setRawBits(int const raw) {_fp = raw;} float Fixed::toFloat(void) const { return ((float)_fp / ( 1 << _bit)); } int Fixed::toInt(void) const { return (_fp >> _bit); } std::ostream &operator << (std::ostream &o, const Fixed &rhs) { o << rhs.toFloat(); return (o); } const Fixed& Fixed::min(const Fixed &a, const Fixed &b) { return (a.getRawBits() < b.getRawBits() ? a : b); } const Fixed& Fixed::max(const Fixed &a, const Fixed &b) { return (a.getRawBits() > b.getRawBits() ? a : b); }
true
27c1b25fecbe9fa22292f27b82ea070b0b76a6e1
C++
dppereyra/darkreign2
/source/3rdparty/won/msg/TMessage.cpp
UTF-8
17,265
2.625
3
[]
no_license
#include "common/won.h" #include "BadMsgException.h" #include "TMessage.h" // Titan messages base classes w/ reference counting namespace { using WONMsg::BadMsgException; using WONMsg::TRawData; using WONMsg::TRawMsg; using WONMsg::BaseMessage; using WONMsg::TMessage; using WONMsg::MiniMessage; using WONMsg::SmallMessage; using WONMsg::LargeMessage; using WONMsg::HeaderMessage; const unsigned long CHUNKSIZE = 512; }; // TRawData, the actual object that is reference counted against //////////////////////////////////////////////////////////////// // Default Constructor TRawData::TRawData() : mRefCount(1), mChunkMult(1), mDataP(NULL), mDataLen(0), mReadPtrP(NULL), mWritePtrP(NULL), mStrBuf(), mWStrBuf() {} // Data Constructor TRawData::TRawData(unsigned long theDataLen, const void *theData) : mRefCount(1), mChunkMult(1), mDataP(NULL), mDataLen(0), mReadPtrP(NULL), mWritePtrP(NULL), mStrBuf(), mWStrBuf() { if (theDataLen > 0) { AllocateNewBuffer(theDataLen); if (theData) memcpy(mDataP, theData, theDataLen); } } // Copy Constructor TRawData::TRawData(const TRawData& theDataR) : mRefCount(1), mChunkMult(1), mDataP(NULL), mDataLen(0), mReadPtrP(NULL), mWritePtrP(NULL), mStrBuf(), mWStrBuf() { if (theDataR.mDataLen > 0) { AllocateNewBuffer(theDataR.mDataLen); memcpy(mDataP, theDataR.mDataP, theDataR.mDataLen); mWritePtrP = mDataP + (theDataR.mWritePtrP - theDataR.mDataP); mReadPtrP = mDataP + (theDataR.mReadPtrP - theDataR.mDataP); } } // Destructor TRawData::~TRawData() { delete [] mDataP; } void * TRawData::AllocateNewBuffer(unsigned long theSize) { if (theSize != mDataLen) { delete [] mDataP; mDataLen = theSize; mDataP = new unsigned char[theSize]; } // Reset read and write pointers mReadPtrP = mWritePtrP = mDataP; mChunkMult = 1; return mDataP; } // for now, append operations have no optimizations // we implement a full re-allocation and copy // nNewBytes = number of new bytes to add void * TRawData::AddAllocate(unsigned long nNewBytes, bool chunkAlloc, bool doDumbCheck) { unsigned long aNewLen = 0; // No buffer, alloc a new one of the requested size if (! mDataP) AllocateNewBuffer(nNewBytes); // Grow buffer if no writes have happened or requested size would be off // end of existing buffer. else if ((doDumbCheck && mWritePtrP == mDataP) || ((mWritePtrP + nNewBytes) > (mDataP + mDataLen))) { aNewLen = mDataLen + nNewBytes; if (chunkAlloc) { aNewLen += CHUNKSIZE * mChunkMult; mChunkMult *= 2; // Double for next time } } // If buffer must be grown, do so. if (aNewLen > 0) { unsigned char* aTmpP = new unsigned char[aNewLen]; memcpy(aTmpP, mDataP, mDataLen); mReadPtrP = aTmpP + (mReadPtrP - mDataP); mWritePtrP = aTmpP + (mWritePtrP - mDataP); delete [] mDataP; mDataP = aTmpP; mDataLen = aNewLen; } // Return the write position return mWritePtrP; } void TRawData::ResetBuffer(void) { delete [] mDataP; mReadPtrP = mWritePtrP = mDataP = NULL; mDataLen = 0; mChunkMult = 1; } unsigned long TRawData::GetDataLen() const { return (mWritePtrP > mDataP ? (mWritePtrP - mDataP) : mDataLen); } void TRawData::AppendLongLong(__int64 theLongLong) { AddAllocate(sizeof(__int64), true); *(reinterpret_cast<__int64*>(mWritePtrP)) = WONCommon::htotll(theLongLong); mWritePtrP += sizeof(__int64); } void TRawData::AppendLong(unsigned long theLong) { AddAllocate(sizeof(unsigned long), true); *(reinterpret_cast<unsigned long*>(mWritePtrP)) = WONCommon::htotl(theLong); mWritePtrP += sizeof(unsigned long); } void TRawData::AppendShort(unsigned short theShort) { AddAllocate(sizeof(unsigned short), true); *(reinterpret_cast<unsigned short*>(mWritePtrP)) = WONCommon::htots(theShort); mWritePtrP += sizeof(unsigned short); } void TRawData::AppendByte(unsigned char theByte) { AddAllocate(sizeof(unsigned char), true); *mWritePtrP = theByte; mWritePtrP += sizeof(unsigned char); } void TRawData::AppendBytes(long theNumBytes, const void* theBytesP, bool chunkAlloc, bool doDumbCheck) { AddAllocate(theNumBytes, chunkAlloc, doDumbCheck); memcpy(mWritePtrP, theBytesP, theNumBytes); mWritePtrP += theNumBytes; } void TRawData::SkipWritePtrAhead(unsigned long theNumBytes) { AddAllocate(theNumBytes, false, false); mWritePtrP+=theNumBytes; } //UNICODE void TRawData::Append_PW_STRING(const wstring& theString) { unsigned short aNumChar = theString.size(); AppendShort(aNumChar); if (aNumChar > 0) { unsigned long aByteCt = aNumChar * sizeof(wchar); AddAllocate(aByteCt, true); WONCommon::htotUnicodeString(theString.data(), (wchar*)mWritePtrP, aNumChar); mWritePtrP += aByteCt; } } void TRawData::Append_PA_STRING(const string& theString) { unsigned short aNumChar = theString.size(); AppendShort(aNumChar); if (aNumChar > 0) { AddAllocate(aNumChar, true); memcpy(mWritePtrP, theString.c_str(), aNumChar); mWritePtrP += aNumChar; } } void TRawData::ReadWString(wstring& theBufR) const { theBufR.erase(); unsigned short aNumChar = ReadShort(); //may throw! if (aNumChar > 0) { WONCommon::WONString aBuf((wchar*)mReadPtrP, aNumChar); theBufR = aBuf.GetUnicodeString(); unsigned long theLen = static_cast<unsigned long>(aNumChar) * sizeof(wchar); CheckLength(theLen); //may throw! mReadPtrP += theLen; } } const wstring& TRawData::Read_PW_STRING() const { ReadWString(mWStrBuf); return mWStrBuf; } void TRawData::ReadString(string& theBufR) const { theBufR.erase(); unsigned short aNumChar = ReadShort(); //may throw! if (aNumChar > 0) { CheckLength(aNumChar); //may throw! theBufR.append((char *) mReadPtrP, aNumChar); mReadPtrP += aNumChar; } } const string& TRawData::Read_PA_STRING() const { ReadString(mStrBuf); return mStrBuf; } __int64 TRawData::ReadLongLong() const { CheckLength(sizeof(__int64)); //may throw! __int64 theLongLong = *(reinterpret_cast<__int64*>(mReadPtrP)); mReadPtrP += sizeof(__int64); //increment return WONCommon::ttohll(theLongLong); } unsigned long TRawData::ReadLong() const { CheckLength(sizeof(unsigned long)); //may throw! unsigned long theLong = *(reinterpret_cast<unsigned long*>(mReadPtrP)); mReadPtrP += sizeof(unsigned long); //increment return WONCommon::ttohl(theLong); } unsigned short TRawData::ReadShort() const { CheckLength(sizeof(unsigned short)); //may throw! unsigned short theShort = *(reinterpret_cast<unsigned short*>(mReadPtrP)); mReadPtrP += sizeof(unsigned short); //increment return WONCommon::ttohs(theShort); } unsigned char TRawData::ReadByte() const { CheckLength(sizeof(unsigned char)); //may throw! unsigned char theByte = *mReadPtrP; mReadPtrP += sizeof(unsigned char); //increment return theByte; } const void * TRawData::ReadBytes(long theNumBytes) const { CheckLength(theNumBytes); //may throw! void * theBytes = mReadPtrP; mReadPtrP += theNumBytes; //increment return theBytes; } // Don't advance read pointer on the peek.. const void * TRawData::PeekBytes(long theNumBytes) const { CheckLength(theNumBytes); //may throw! void * theBytes = mReadPtrP; return theBytes; } unsigned long TRawData::BytesLeftToRead() const { unsigned long aBytesTotal = GetDataLen(); unsigned long aBytesRead = mReadPtrP - mDataP; return (aBytesRead < aBytesTotal ? aBytesTotal - aBytesRead : 0); } void TRawData::CheckLength(unsigned long theLen) const { const unsigned char* anEndP = mDataP + GetDataLen(); const unsigned char* aReadEndP = mReadPtrP + theLen; if (aReadEndP > anEndP) throw BadMsgException(WONCommon::ExBadTitanMessage, __LINE__, __FILE__, "Attempt to read past end of message!"); } // TRawMsg implementation ///////////////////////////////////////////// TRawMsg::TRawMsg() : rep(new TRawData()) {} TRawMsg::TRawMsg(unsigned long theDataLen, const void *theData) : rep(new TRawData(theDataLen, theData)) {} TRawMsg::TRawMsg(const TRawMsg& Rmsg) : rep(Rmsg.rep) { #ifdef WIN32 InterlockedIncrement(&(rep->mRefCount)); #else rep->mRefCountCrit.Enter(); rep->mRefCount++; rep->mRefCountCrit.Leave(); #endif } TRawMsg::~TRawMsg() { long result; #ifdef WIN32 result = InterlockedDecrement(&(rep->mRefCount)); #else rep->mRefCountCrit.Enter(); result = --(rep->mRefCount); rep->mRefCountCrit.Leave(); #endif if (result <= 0) delete rep; } TRawMsg& TRawMsg::operator=(const TRawMsg& theRawMsgR) //shallow copy { #ifdef WIN32 InterlockedIncrement(&(theRawMsgR.rep->mRefCount)); // protect against A = A #else theRawMsgR.rep->mRefCountCrit.Enter(); theRawMsgR.rep->mRefCount++; // protect against A = A theRawMsgR.rep->mRefCountCrit.Leave(); #endif long result; #ifdef WIN32 result = InterlockedDecrement(&(rep->mRefCount)); #else rep->mRefCountCrit.Enter(); result = --(rep->mRefCount); rep->mRefCountCrit.Leave(); #endif if (result <= 0) delete rep; rep = theRawMsgR.rep; //share representation return *this; } TRawMsg* TRawMsg::Duplicate() const { return new TRawMsg(*this); } void TRawMsg::Unpack() {} void * TRawMsg::Pack() { return rep->mDataP; } const void * TRawMsg::GetDataPtr() const { return rep->mDataP; } void * TRawMsg::GetDataPtr() { return rep->mDataP; } void TRawMsg::CopyOnWrite() { if (rep->mRefCount > 1) { TRawData* aTmpP = rep; rep = new TRawData(*aTmpP); #ifdef WIN32 InterlockedDecrement(&(aTmpP->mRefCount)); #else aTmpP->mRefCountCrit.Enter(); aTmpP->mRefCount--; aTmpP->mRefCountCrit.Leave(); #endif } } // BaseMessage implementation ///////////////////////////////////// BaseMessage::BaseMessage() {} BaseMessage::BaseMessage(const BaseMessage& Tmsg) : TRawMsg(Tmsg), mMessageClass(Tmsg.mMessageClass) {} BaseMessage::BaseMessage(unsigned long theDataLen, const void *theData) : TRawMsg( theDataLen, theData ) {} BaseMessage::~BaseMessage() {} BaseMessage& BaseMessage::operator= (const BaseMessage& theMsgR) { TRawMsg::operator=(theMsgR); mMessageClass = theMsgR.mMessageClass; return *this; } void* BaseMessage::AllocateBodyBuffer(unsigned long size) { if (size < GetHeaderLength() || size > MAXMSG_SIZE) //brain damaged header { WDBG_LH("BaseMessage::AllocateBodyBuffer bad message length, len=" << size); BadMsgException anEx(WONCommon::ExBadTitanMessage, __LINE__, __FILE__); anEx.GetStream() << "MsgLen=" << size; throw anEx; } return AddAllocate(size - GetHeaderLength()); } void BaseMessage::Unpack() { UnpackHeader(); } void BaseMessage::UnpackHeader() const { ResetReadPointer(); ReadBytes(GetHeaderLength()); } void* BaseMessage::Pack() { ResetWritePointer(); SkipWritePtrAhead(GetHeaderLength()); return GetDataPtr(); } BaseMessage* BaseMessage::GetMsgOfType(unsigned char theHeaderType) { HeaderType aHeaderType = (HeaderType)theHeaderType; BaseMessage *aMsg = NULL; switch(theHeaderType) { case CommonService: case EncryptedService: case FactoryServer: case AuthServer: case DirServer: case ParamServer: case ChatServer: case SIGSAuthServer: case OverlordServer: case Auth1Login: case Auth1LoginHL: case Auth1PeerToPeer: aMsg = new TMessage; break; case HeaderService0Message0: case HeaderEncryptedService: case HeaderWithTag: case HeaderWithTagAndExpiration: aMsg = new HeaderMessage; break; case HeaderService1Message1: // non-encrypted MiniMessages case MiniEncryptedService: // encrypted Service1Message1 (aka MiniMessage) aMsg = new MiniMessage; break; case HeaderService2Message2: // non-encrypted SmallMessages case SmallEncryptedService: // encrypted Service2Message2 (aka SmallMessage) aMsg = new SmallMessage; break; case HeaderService4Message4: // non-encrypted LargeMessage case LargeEncryptedService: // encrypted Service4Message4 (aka LargeMessage) aMsg = new LargeMessage; break; default: aMsg = NULL; } if(aMsg!=NULL) aMsg->ResetWritePointer(); return aMsg; } // HeaderMessage implementation /////////////////////////////////////// HeaderMessage::HeaderMessage() : BaseMessage(eHeaderMessage) { AllocateHeaderBuffer(); SetHeaderType(HeaderService0Message0); } HeaderMessage::HeaderMessage(const HeaderMessage& msg) : BaseMessage(msg) {} HeaderMessage::HeaderMessage(unsigned long theDataLen, const void *theData) : BaseMessage(theDataLen, theData) { mMessageClass = eHeaderMessage; } HeaderMessage::~HeaderMessage() {} HeaderMessage& HeaderMessage::operator=(const HeaderMessage& theMsgR) { BaseMessage::operator=(theMsgR); return *this; } TRawMsg* HeaderMessage::Duplicate() const { return new HeaderMessage(*this); } void* HeaderMessage::Pack() { // Don't pack the message since this is simply a wrapper for an underlying message which // is already packed. return GetDataPtr(); } void HeaderMessage::Dump(std::ostream& os) const { os << "HeaderMessage Dump:" << endl; os << " Data Size: " << GetDataLen() << endl; os << " HeaderType: " << (int)GetHeaderType() << endl; } // MiniMessage implementation /////////////////////////////////////// MiniMessage::MiniMessage() : BaseMessage(eMiniMessage) { AllocateHeaderBuffer(); SetHeaderType(HeaderService1Message1); SetServiceType(0); SetMessageType(0); } MiniMessage::MiniMessage(const MiniMessage& msg) : BaseMessage(msg) {} MiniMessage::MiniMessage(unsigned long theDataLen, const void *theData) : BaseMessage(theDataLen, theData) { mMessageClass = eMiniMessage; } MiniMessage::~MiniMessage() {} MiniMessage& MiniMessage::operator=(const MiniMessage& theMsgR) { BaseMessage::operator=(theMsgR); return *this; } TRawMsg* MiniMessage::Duplicate() const { return new MiniMessage(*this); } void* MiniMessage::Pack() { BaseMessage::Pack(); return GetDataPtr(); } void MiniMessage::Dump(std::ostream& os) const { os << "MiniMessage Dump:" << endl; os << " Data Size: " << GetDataLen() << endl; os << " HeaderType: " << (int)GetHeaderType() << endl; os << " ServiceType: " << (int)GetServiceType() << endl; os << " MessageType: " << (int)GetMessageType() << endl; } // SmallMessage implementation /////////////////////////////////////// SmallMessage::SmallMessage() : BaseMessage(eSmallMessage) { AllocateHeaderBuffer(); SetHeaderType(HeaderService2Message2); SetServiceType(0); SetMessageType(0); } SmallMessage::SmallMessage(const SmallMessage& msg) : BaseMessage(msg) {} SmallMessage::SmallMessage(unsigned long theDataLen, const void *theData) : BaseMessage(theDataLen, theData) { mMessageClass = eSmallMessage; } SmallMessage::~SmallMessage() {} SmallMessage& SmallMessage::operator=(const SmallMessage& theMsgR) { BaseMessage::operator=(theMsgR); return *this; } TRawMsg* SmallMessage::Duplicate() const { return new SmallMessage(*this); } void* SmallMessage::Pack() { BaseMessage::Pack(); return GetDataPtr(); } void SmallMessage::Dump(std::ostream& os) const { os << "SmallMessage Dump:" << endl; os << " Data Size: " << GetDataLen() << endl; os << " HeaderType: " << (int)GetHeaderType() << endl; os << " ServiceType: " << (int)GetServiceType() << endl; os << " MessageType: " << (int)GetMessageType() << endl; } // LargeMessage implementation /////////////////////////////////////// LargeMessage::LargeMessage() : BaseMessage(eLargeMessage) { AllocateHeaderBuffer(); SetHeaderType(HeaderService4Message4); SetServiceType(0); SetMessageType(0); } LargeMessage::LargeMessage(const LargeMessage& msg) : BaseMessage(msg) {} LargeMessage::LargeMessage(unsigned long theDataLen, const void *theData) : BaseMessage(theDataLen, theData) { mMessageClass = eLargeMessage; } LargeMessage::~LargeMessage() {} LargeMessage& LargeMessage::operator=(const LargeMessage& theMsgR) { BaseMessage::operator=(theMsgR); return *this; } TRawMsg* LargeMessage::Duplicate() const { return new LargeMessage(*this); } void* LargeMessage::Pack() { BaseMessage::Pack(); return GetDataPtr(); } void LargeMessage::Dump(std::ostream& os) const { os << "LargeMessage Dump:" << endl; os << " Data Size: " << GetDataLen() << endl; os << " HeaderType: " << (int)GetHeaderType() << endl; os << " ServiceType: " << (int)GetServiceType() << endl; os << " MessageType: " << (int)GetMessageType() << endl; } // TMessage implementation //////////////////////////////////////// // ** TMessages are OBSOLETE ** TMessage::TMessage() : BaseMessage(eTMessage) { AllocateHeaderBuffer(); SetServiceType(0); SetMessageType(0); } TMessage::TMessage(const TMessage& Tmsg) : BaseMessage(Tmsg) {} TMessage::TMessage(unsigned long theDataLen, const void *theData) : BaseMessage(theDataLen, theData) { mMessageClass = eTMessage; } TMessage::~TMessage() {} TMessage& TMessage::operator= (const TMessage& theMsgR) { BaseMessage::operator=(theMsgR); return *this; } TRawMsg* TMessage::Duplicate() const { return new TMessage(*this); } void * TMessage::Pack() { BaseMessage::Pack(); return GetDataPtr(); } void TMessage::Dump(std::ostream& os) const { os << "TMessage Dump:" << endl; os << " Data Size: " << GetDataLen() << endl; os << " ServiceType: " << (int)GetServiceType() << endl; os << " MessageType: " << (int)GetMessageType() << endl; }
true
3076d3bd946f7d930704491193582e9ba19756b5
C++
JinYeJin/algorithm-study
/November,2020~July,2021/2021-01-01/9273_진예진_정제헌을 팔자!_실패.cpp
UTF-8
885
2.59375
3
[]
no_license
/* https://www.slideserve.com/urbana/sample-solutions-ctu-open-contest-2013-czech-technical-university-in-prague https://www.acmicpc.net/problem/7516 */ #include <stdio.h> #include <iostream> #include <string> using namespace std; int main(){ FILE *stream =freopen("S2\\27\\input\\9273.txt", "r", stdin); if(!stream) perror("freopen"); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); string input_value; while(true){ cin >> input_value; string denominator = input_value.substr(2); int n = stoi(denominator); int answer = 0; for(int a = n+1; a <= n*2; a++){ if(a*n%(a-n) == 0){ answer++; cout << "answer: " << a << "\n"; } } cout << answer; if(cin.eof() == true) break; else cout << "\n"; } return 0; }
true
a57e1ecebb5d44d30af7d953d456ab97e85d6006
C++
duytruong2022/Algorithms
/BinarySearch.cpp
UTF-8
457
2.84375
3
[]
no_license
#include<stdio.h> long long B_search (long long a[], long long first, long long last, long long x) { long long center; if (last >= first) { center = (last + first) / 2; if (a[center] == x) return 1; else if (a[center] > x) return B_search (a, first, center - 1, x); else return B_search (a, center + 1, last, x); } return 0; } long long main() { long long a[] = {1, 3, 5, 7, 9, 12, 15}; prlong longf("%d", B_search (a, 0, 6, 9)); }
true
453f41288b9a6a37ce228b5d97e132674e703d2c
C++
savnik/LaserNavigation
/aurobotservers/trunk/include/ugen4/uplane.h
UTF-8
5,786
2.703125
3
[]
no_license
/*************************************************************************** * Copyright (C) 2006 by DTU (Christian Andersen) * * jca@oersted.dtu.dk * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef UPLANE_H #define UPLANE_H #include "u3d.h" #include "uline.h" /** * General definition of a 3D plane, defined bu ax + by +cz + d = 0. * The normal vector (a,b,c) is assumed (and set) to be a unit vector, and d will be positive or zero * (The distance to the plane (from origo) is then d) * to ease distance calculations. * @author Christian Andersen <jca@oersted.dtu.dk> */ class UPlane { public: /** * Constrctor */ UPlane(); /** * Destructor */ ~UPlane(); /** * clear sets the plane to span the x-y axis zeros. */ void clear() { // a plane that spans the x,y axes a = 0.0; b = 0.0; c = 1.0; d = 0.0; } /** * Set the plane from three 3D positions. * Using a = A1, b=A2, c = A3, d = A, * and Ai = det(x1, x2, x3), where x1 is p1 coulumn, x2 is x2 column x3 is p3 column, * except for column i wich is set to [1 1 1]'. * A uses the full matrix. * \param p1 is a 3d position on plane * \param p2 is a 3d position on plane * \param p3 is a 3d position on plane * All positions must be different, else the result will be unpredicted, and isValid() will return false. */ void set(UPosition p1, UPosition p2, UPosition p3); /** * Print result to a string */ const char * print(const char * preStr, char * buff, const int buffCnt); /** * Set plane from a position and a normal vector. * \param p1 is a 3d position on the plane * \param n1 is a 3d normal vector (need not be a unit vector) * normal vector must not be a null vector (else unpredicted result). */ void set(UPosition p1, UPosition n1); /** * Set plane from the position on the plane closest to origin. * \param p1 is a the closest 3d position on the plane that is closest to the origin * the position must not be a null vector (else unpredicted result). */ void set(UPosition p1); /** * Set plane from the position on the plane closest to the origin. * \param p1 is the 3d position on the plane that is closest to the origin * the position must not be a null vector (else unpredicted result). */ inline void set(double x, double y, double z) { UPosition v(x,y,z); set(v); }; /** * Adjust plane parameters to make (a,b,c) a unit vector and 'd' a positive value. */ void normalize(); /** * Set plane values direct, the a,b,c must not form a null vector. * \param a,b,c,d is the plane parameters (will be normalixed to have a,b,c as a unit vector) * normal vector must not be a null vector (else unpredicted result). */ inline void set(double ia, double ib, double ic, double id) { a=ia; b=ib; c=ic; d=id; normalize(); }; /** * The plane is defined valid, if the normal vector defined as (a,b,c) has length 1. * \returns true if valid plane. */ bool isValid() { return (fabs(sqr(a) + sqr(b) + sqr(c) - 1.0) < 1e-10); }; /** * Get normal vector */ UPosition getNormal() { UPosition result(a, b, c); return result; } /** * \brief Get signed distance from point to plane. * The distance is positive if the position is at the origin-side of the plane * \param p1 is the 3d point * \return distance to point */ inline double distSigned(UPosition p1) { return a*p1.x + b*p1.y + c*p1.z + d; }; /** * \brief Get distance from point to plane. * \param p1 is the 3d point * \return distance to point */ inline double dist(UPosition p1) { return fabs(distSigned(p1)); }; /** * Get point on plane nearest to a point off the plane. * \param p1 is the position off the plane. * */ UPosition getOnPlane(UPosition p1); /** * Get position on plane, where the line is crossing the plane. * \param crossingLine is the line that is assumed to cross the line * \param notParallel is true if the crossing is OK, otherwise the point is far away, in the right * direction and on the line, but not on the plane. * \returns the common point on the line and plane. */ UPosition getLineCrossing(ULine crossingLine, bool * notParallel); /** * Get the line from intersection of two planes. * \param plane2 is the second plane. * \param notParallel is true if the result is OK. * \returns the intersection line. */ ULine getPlaneCrossing(UPlane plane2, bool * notParallel); public: /** parameter values for a general plane */ double a, b, c, d; }; #endif
true
846403cb69eaa5eef37126b37c5b4d804707d091
C++
chromium/chromium
/ui/views/controls/progress_ring_utils.cc
UTF-8
3,243
2.875
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/progress_ring_utils.h" #include <utility> #include <vector> #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/skia_conversions.h" namespace views { namespace { // Specifies a single section of the ring. Multiple sections should be specified // in clockwise order and should sum to 360 degrees. struct ArcSpec { enum class Color { kBackground, kForeground }; Color color; SkScalar sweep_angle; }; void DrawRing(gfx::Canvas* canvas, const SkRect& bounds, SkColor background_color, SkColor foreground_color, float stroke_width, SkScalar start_angle, const std::vector<ArcSpec>& arcs) { // Flags for the background portion of the ring. cc::PaintFlags background_flags; background_flags.setStyle(cc::PaintFlags::Style::kStroke_Style); background_flags.setAntiAlias(true); background_flags.setColor(background_color); background_flags.setStrokeWidth(stroke_width); // Flags for the filled portion of the ring. cc::PaintFlags foreground_flags; foreground_flags.setStyle(cc::PaintFlags::Style::kStroke_Style); foreground_flags.setAntiAlias(true); foreground_flags.setColor(foreground_color); foreground_flags.setStrokeWidth(stroke_width); SkPath background_path, foreground_path; SkScalar cur_angle = start_angle; for (const ArcSpec& arc : arcs) { SkPath& path = arc.color == ArcSpec::Color::kBackground ? background_path : foreground_path; path.addArc(bounds, cur_angle, arc.sweep_angle); cur_angle += arc.sweep_angle; } CHECK_EQ(cur_angle, 360 + start_angle); canvas->DrawPath(std::move(foreground_path), std::move(foreground_flags)); canvas->DrawPath(std::move(background_path), std::move(background_flags)); } } // namespace void DrawProgressRing(gfx::Canvas* canvas, const SkRect& bounds, SkColor background_color, SkColor progress_color, float stroke_width, SkScalar start_angle, SkScalar sweep_angle) { std::vector<ArcSpec> arcs; arcs.push_back({ArcSpec::Color::kForeground, sweep_angle}); arcs.push_back({ArcSpec::Color::kBackground, 360 - sweep_angle}); DrawRing(canvas, bounds, background_color, progress_color, stroke_width, start_angle, arcs); } void DrawSpinningRing(gfx::Canvas* canvas, const SkRect& bounds, SkColor background_color, SkColor progress_color, float stroke_width, SkScalar start_angle) { std::vector<ArcSpec> arcs; // Draw alternating foreground and background arcs of equal sizes (6 total). for (int i = 0; i < 3; ++i) { arcs.push_back({ArcSpec::Color::kForeground, 60}); arcs.push_back({ArcSpec::Color::kBackground, 60}); } DrawRing(canvas, bounds, background_color, progress_color, stroke_width, start_angle, arcs); } } // namespace views
true
6c1a89141f87bccd18870017a9fecf1c73270226
C++
ktj007/Raiderz_Public
/Develop/mdk/RealSpace3/RS3UnitTest/RTestShaderCompositeManager.cpp
UHC
3,285
2.703125
3
[]
no_license
#include "stdafx.h" #include "RMaterial.h" // TODO: RMaterial.h Ŭ ʾƵ ʰ ؾ . #include "RShaderCompositeManager.h" #include "RShaderComposite.h" using namespace rs3; const int TEST_ID0 = 0; const int TEST_ID1 = RSC_COUNT - 1; TEST( TestShaderCompositeManager, GetComponentsNameList ) { vector<string> rscComponentNames; RSCID rscNullID; RShaderCompositeManager::GetComponentsNameList( rscNullID, rscComponentNames ); EXPECT_EQ( 0, rscComponentNames.size() ); RSCID rscTestID = RSCID( TEST_ID0 ) | RSCID( TEST_ID1 ); RShaderCompositeManager::GetComponentsNameList( rscTestID, rscComponentNames ); EXPECT_EQ( 2, rscComponentNames.size() ); EXPECT_STREQ( componentNames[TEST_ID0].name, rscComponentNames[0].c_str() ); EXPECT_STREQ( componentNames[TEST_ID1].name, rscComponentNames[1].c_str() ); }; TEST( TestShaderCompositeManager, GetShaderComponentIDByName ) { RSCID rscTestID; rscTestID = RShaderCompositeManager::GetShaderComponentIDByName( componentNames[TEST_ID0].name ); EXPECT_TRUE( componentNames[TEST_ID0].flag == rscTestID ); rscTestID = RShaderCompositeManager::GetShaderComponentIDByName( componentNames[TEST_ID1].name ); EXPECT_TRUE( componentNames[TEST_ID1].flag == rscTestID ); }; TEST( TestShaderCompositeManager, ShaderComposite ) { size_t count = sizeof(componentNames)/sizeof(ShaderComponentPair); EXPECT_EQ( count, RSC_COUNT ); class MockShaderComponent : public RShaderComponent { public: MockShaderComponent( const string& strString ) { Create(strString); } }; class MockShaderComposite : public RShaderComposite { public: MockShaderComposite( RSCID rscComponents ) : RShaderComposite(rscComponents) { } using RShaderComposite::Composite; }; RSCID MCS_1( 0, 1 ); RSCID MCS_2( 0, 1<<1 ); RSCID MCS_3( 0, 1<<2 ); class MockCompositeManager : public RShaderCompositeManager { public: virtual bool Create() { m_shaderComponents.resize(3); m_shaderComponents[0] = new MockShaderComponent("interface()\n{\n$define = test1\n}"); // test1 m_shaderComponents[1] = new MockShaderComponent("interface()\n{\n$name = test2\n}"); m_shaderComponents[2] = new MockShaderComponent("interface()\n{\n$dependency = test1\n}"); return true; } virtual RShaderComposite* NewShaderComposite(RSCID rscComponents) { return new MockShaderComposite(rscComponents); } }; MockCompositeManager aManager; aManager.Create(); // ι° Ʈ ̸  ִ Ȯ EXPECT_STREQ( aManager.GetShaderComponent( 1 )->GetName().c_str(), "test2" ); MockShaderComposite composite( MCS_1 | MCS_2 | MCS_3 ); bool bSuccess = composite.Composite( &aManager ); EXPECT_TRUE( bSuccess ); // 1 MockShaderComposite composite2( MCS_2 | MCS_3 ); bSuccess = composite2.Composite( &aManager ); EXPECT_FALSE( bSuccess ); // 4 Ʈ ûѰͰ ޶ MockShaderComposite invalidComposite( MCS_1 | MCS_2 | MCS_3 | RSCID( 0, 1<<3 ) ); bSuccess = invalidComposite.Composite( &aManager ); EXPECT_FALSE( bSuccess ); // TODO: ڵ带 Ͽ ϰ Ȯϸ ڴ. aManager.Destroy(); }
true
4b59549105602bf20093030d171c792ab7d6a9b2
C++
bjahagirdar/DSA
/assign2 cricket.cpp
UTF-8
3,437
3.734375
4
[]
no_license
#include <iostream> #include <cstring> using namespace std; class Student { int N; int roll[20]; string name[20]; public: void accept(); //Function to accept no. of students int funion(Student, Student); //Function to find union void intersect(Student, Student); //Function to find intersection void diff(Student, Student); //Function to find difference void display(); //Function to display result }; void Student :: accept() { cout << "\n Enter total no of students : "; cin >> N; for(int i=0; i<N; i++) { cout << "\n Enter name of student : "; cin >> name[i]; cout << " Enter roll no. : "; cin >> roll[i]; } } int Student :: funion(Student a, Student b) { int index = a.N; int flag; int i, j; cout << "{ "; for(i=0; i<a.N; i++) { name[i] = a.name[i]; roll[i] = a.roll[i]; cout << name[i] << "-" << roll[i] << " "; } for(i=0; i<b.N; i++) { flag = 0; for(j=0; j<a.N; j++) { if(b.roll[i] == a.roll[j]) { flag=1; break; } } if(flag == 0) { roll[index] = b.roll[i]; name[index] = b.name[i]; cout << name[index] << "-" << roll[index] << " "; index++; } } cout << "}" << endl; return index; } void Student :: intersect(Student a, Student b) { int i, j, k; k=0; cout << "{ "; for(i=0; i<a.N; i++) { for(j=0; j<b.N; j++) { if(a.roll[i] == b.roll[j]) { roll[k] = a.roll[i]; name[k] = a.name[i]; cout << name[k] << "-" << roll[k] << " "; k++; } } } cout << "}" << endl; } void Student :: diff(Student a, Student b) { int i, j, k, diff, flag; k=0; flag=0; cout << "{ "; for(i=0; i<a.N; i++) { flag=0; for(j=0; j<b.N; j++) { if(a.roll[i] == b.roll[j]) { flag=1; break; } } if(flag == 0) { roll[k] = a.roll[i]; name[k] = a.name[i]; cout << name[k] << "-" << roll[k] << " "; k++; } } cout << "}" << endl; } int main() { Student cricket_obj, badmin_obj, union_obj, inter_obj, diff_obj; int m=0; int n=0; cout << "\n Enter total number of students in SE COMP : "; cin >> n; cout << "\n Enter student details who play cricket : "; cricket_obj.accept(); cout << "\n Enter student details who play badminton : "; badmin_obj.accept(); cout << "\n List of students who play cricket or badminton are : "; m = union_obj.funion(cricket_obj, badmin_obj); cout << "\n List of students who play both cricket and badminton are : "; inter_obj.intersect(cricket_obj, badmin_obj); cout << "\n List of students who play only cricket are : "; diff_obj.diff(cricket_obj, badmin_obj); cout << "\n List of students who play only badminton are : "; diff_obj.diff(badmin_obj, cricket_obj); cout << "\n Number of students who play neither cricket nor badminton are : " << n-m; return 0; }
true
418951a954840543d056f7861715fabb00b8de53
C++
cha63506/tiny-2d-games
/feos/miniwars/source/character.arm.cpp
UTF-8
2,122
3.015625
3
[]
no_license
#include <string.h> #include "miniwars.h" Character::~Character() { for(it = weapons.begin(); it != weapons.end(); it++) { Weapon *weapon = *it; delete weapon; } } void Character::pickup(Weapon *w) { if(!w) return; for(list<Weapon*>::iterator iter = weapons.begin(); iter != weapons.end(); iter++) { Weapon *weapon = *iter; if(strcmp(w->getName(), weapon->getName()) == 0) { if(w->getUpgrade() > weapon->getUpgrade()) weapon->setUpgrade(w->getUpgrade()); weapon->addAmmo(w->getAmmo()); return; } } weapons.push_back(w); if(weapons.size() == 1) nextWeapon(); } Weapon* Character::nextWeapon() { it++; if(it == weapons.end()) it = weapons.begin(); return 0; } void Character::move(int keys) { switch(keys & (KEY_UP|KEY_DOWN|KEY_LEFT|KEY_RIGHT)) { case KEY_UP: y -= speed; break; case KEY_DOWN: y += speed; break; case KEY_LEFT: x -= speed; break; case KEY_RIGHT: x += speed; break; case (KEY_UP|KEY_LEFT): x -= mulf32(floattof32(0.707106781f), speed); y -= mulf32(floattof32(0.707106781f), speed); break; case (KEY_UP|KEY_RIGHT): x += mulf32(floattof32(0.707106781f), speed); y -= mulf32(floattof32(0.707106781f), speed); break; case (KEY_DOWN|KEY_LEFT): x -= mulf32(floattof32(0.707106781f), speed); y += mulf32(floattof32(0.707106781f), speed); break; case (KEY_DOWN|KEY_RIGHT): x += mulf32(floattof32(0.707106781f), speed); y += mulf32(floattof32(0.707106781f), speed); break; } if(x < 0) x = 0; if(x >= inttof32(256)) x = inttof32(256)-1; if(y < 0) y = 0; if(y >= inttof32(192)) y = inttof32(192)-1; } void Character::move(Character *target) { s32 angle = atan2Tonc(target->getY()-y, target->getX()-x); x += mulf32(speed, cosLerp(angle)); y += mulf32(speed, sinLerp(angle)); if(x < 0) x = 0; if(x >= inttof32(256)) x = inttof32(256)-1; if(y < 0) y = 0; if(y >= inttof32(192)) y = inttof32(192)-1; }
true
0719f31647b7e89cd6440b83138ea6ea1ba64e69
C++
networkit/networkit
/networkit/cpp/clique/MaximalCliques.cpp
UTF-8
12,675
2.640625
3
[ "MIT" ]
permissive
#include <algorithm> #include <cassert> #include <utility> #include <networkit/auxiliary/SignalHandling.hpp> #include <networkit/centrality/CoreDecomposition.hpp> #include <networkit/clique/MaximalCliques.hpp> namespace { // Private implementation namespace using NetworKit::count; using NetworKit::index; using NetworKit::node; class MaximalCliquesImpl { private: const NetworKit::Graph *G; std::vector<std::vector<node>> *result; std::function<void(const std::vector<node> &)> &callback; bool maximumOnly; count maxFound; std::vector<node> pxvector; std::vector<node> pxlookup; std::vector<index> firstOut; std::vector<node> head; public: MaximalCliquesImpl(const NetworKit::Graph &G, std::vector<std::vector<node>> &result, std::function<void(const std::vector<node> &)> &callback, bool maximumOnly) : G(&G), result(&result), callback(callback), maximumOnly(maximumOnly), maxFound(0), pxvector(G.numberOfNodes()), pxlookup(G.upperNodeIdBound()), firstOut(G.upperNodeIdBound() + 1), head(G.numberOfEdges()) {} private: void buildOutGraph() { index currentOut = 0; for (node u = 0; u < G->upperNodeIdBound(); ++u) { firstOut[u] = currentOut; if (G->hasNode(u)) { index xpboundU = pxlookup[u]; G->forEdgesOf(u, [&](node v) { if (xpboundU < pxlookup[v]) { head[currentOut++] = v; } }); } } firstOut[G->upperNodeIdBound()] = currentOut; } template <typename F> void forOutEdgesOf(node u, F callback) const { for (index i = firstOut[u]; i < firstOut[u + 1]; ++i) { callback(head[i]); } } bool hasNeighbor(node u, node v) const { for (index i = firstOut[u]; i < firstOut[u + 1]; ++i) { if (head[i] == v) return true; } return false; } count outDegree(node u) const { return firstOut[u + 1] - firstOut[u]; } void swapNodeToPos(node u, index pos) { assert(pos < pxvector.size()); node pxvec2 = pxvector[pos]; std::swap(pxvector[pxlookup[u]], pxvector[pos]); pxlookup[pxvec2] = pxlookup[u]; pxlookup[u] = pos; } public: void run() { NetworKit::CoreDecomposition cores(*G, false, false, true); cores.run(); Aux::SignalHandler handler; handler.assureRunning(); const auto &orderedNodes = cores.getNodeOrder(); index ii = 0; for (const node u : orderedNodes) { pxvector[ii] = u; pxlookup[u] = ii; ii += 1; } handler.assureRunning(); #ifndef NDEBUG for (auto u : orderedNodes) { assert(pxvector[pxlookup[u]] == u); } #endif // Store out-going neighbors in the direction of higher core numbers. // This means that the out-degree is bounded by the maximum core number. buildOutGraph(); handler.assureRunning(); for (index iu = orderedNodes.size(); iu-- > 0;) { node u = orderedNodes[iu]; index xpbound = iu + 1; #ifndef NDEBUG for (auto v : orderedNodes) { if (v == u) break; assert(pxlookup[v] < xpbound); } #endif // Check if u can be the starting point of a new clique // of size greater than maxFound. // Note that the clique starting at u could be of // size outDegree(u) + 1, but then it is still only the // same size as maxFound. if (maximumOnly && maxFound > outDegree(u)) { swapNodeToPos(u, iu); continue; } count xcount = 0; count pcount = 0; G->forNeighborsOf(u, [&](node v) { #ifndef NDEBUG assert(pxlookup[v] < pxvector.size()); assert(xcount <= xpbound); assert(pcount <= pxvector.size() - xpbound); #endif if (pxlookup[v] < xpbound) { // v is in X swapNodeToPos(v, xpbound - xcount - 1); xcount += 1; } else { // v is in P swapNodeToPos(v, xpbound + pcount); pcount += 1; } }); #ifndef NDEBUG { // assert all neighbors of u were stored in one range around xpbound assert(xcount + pcount == G->degree(u)); std::vector<index> neighborPositions; G->forNeighborsOf(u, [&](node v) { neighborPositions.push_back(pxlookup[v]); assert(pxvector[pxlookup[v]] == v); }); std::sort(neighborPositions.begin(), neighborPositions.end()); for (index i = 0; i < neighborPositions.size(); ++i) { assert(neighborPositions[i] == xpbound - xcount + i); } } #endif std::vector<node> r = {u}; tomita(xpbound - xcount, xpbound, xpbound + pcount, r); swapNodeToPos(u, iu); handler.assureRunning(); } } void tomita(index xbound, index xpbound, index pbound, std::vector<node> &r) { if (xbound == pbound) { // if (X, P are empty) if (callback) { callback(r); } else if (!maximumOnly) { result->push_back(r); } else if (r.size() > maxFound) { result->clear(); result->push_back(r); maxFound = r.size(); } return; } if (xpbound == pbound) return; #ifndef NDEBUG assert(xbound <= xpbound); assert(xpbound <= pbound); assert(pbound <= pxvector.size()); #endif Aux::SignalHandler handler; handler.assureRunning(); node u = findPivot(xbound, xpbound, pbound); std::vector<node> movedNodes; // Find all nodes in P that are not neighbors of the pivot // this step is necessary as the next loop changes pxvector, // which prohibits iterating over it in the same loop. std::vector<node> toCheck; // Step 1: mark all outgoing neighbors of the pivot in P std::vector<bool> pivotNeighbors(pbound - xpbound); forOutEdgesOf(u, [&](node v) { index vpos = pxlookup[v]; if (vpos >= xpbound && vpos < pbound) { pivotNeighbors[vpos - xpbound] = true; } }); // Step 2: for all not-yet marked notes check if they have the pivot as neighbor. // If not: they are definitely a non-neighbor. for (index i = xpbound; i < pbound; i++) { if (!pivotNeighbors[i - xpbound]) { node p = pxvector[i]; if (!hasNeighbor(p, u)) { toCheck.push_back(p); } } } for (auto pxveci : toCheck) { count xcount = 0, pcount = 0; // Group all neighbors of pxveci in P \cup X around xpbound. // Step 1: collect all outgoing neighbors of pxveci forOutEdgesOf(pxveci, [&](node v) { if (pxlookup[v] < xpbound && pxlookup[v] >= xbound) { // v is in X swapNodeToPos(v, xpbound - xcount - 1); xcount += 1; } else if (pxlookup[v] >= xpbound && pxlookup[v] < pbound) { // v is in P swapNodeToPos(v, xpbound + pcount); pcount += 1; } }); // Step 2: collect all nodes in X that have not yet been collected // and that have pxveci as outgoing neighbor. for (index i = xbound; i < xpbound;) { // stop if we have reached the collected neighbors if (i == xpbound - xcount) break; node x = pxvector[i]; if (hasNeighbor(x, pxveci)) { swapNodeToPos(x, xpbound - xcount - 1); xcount += 1; } else { // Advance only if we did not swap otherwise we have already // a next candidate at position i. ++i; } } // Step 3: collect all nodes in P that have not yet been collected // and that have pxveci as outgoing neighbor. for (index i = xpbound + pcount; i < pbound; ++i) { node p = pxvector[i]; if (hasNeighbor(p, pxveci)) { swapNodeToPos(p, xpbound + pcount); pcount += 1; } } r.push_back(pxveci); #ifndef NDEBUG assert(xpbound + pcount <= pbound); assert(xpbound - xcount >= xbound); #endif // only the pcount nodes in P are candidates for the clique, // therefore r.size() + pcount is an upper bound for the maximum // size of the clique that can still be found in this branch // of the recursion. if (!maximumOnly || maxFound < (r.size() + pcount)) { tomita(xpbound - xcount, xpbound, xpbound + pcount, r); } r.pop_back(); swapNodeToPos(pxveci, xpbound); xpbound += 1; assert(pxvector[xpbound - 1] == pxveci); movedNodes.push_back(pxveci); } for (node v : movedNodes) { // move from X -> P swapNodeToPos(v, xpbound - 1); xpbound -= 1; } #ifndef NDEBUG for (node v : movedNodes) { assert(pxlookup[v] >= xpbound); assert(pxlookup[v] < pbound); } #endif } node findPivot(index xbound, index xpbound, index pbound) const { // Counts for every node in X \cup P how many outgoing neighbors it has in P std::vector<count> pivotNeighbors(pbound - xbound); const count psize = pbound - xpbound; // Step 1: for all nodes in X count how many outgoing neighbors they have in P for (index i = 0; i < xpbound - xbound; i++) { node u = pxvector[i + xbound]; forOutEdgesOf(u, [&](node v) { if (pxlookup[v] >= xpbound && pxlookup[v] < pbound) { ++pivotNeighbors[i]; } }); // If a node has |P| neighbors, we cannot find a better candidate if (pivotNeighbors[i] == psize) return u; } // Step 2: for all nodes in P // a) increase counts for every neighbor in P \cup X to account for incoming neighbors // b) count all outgoing neighbors in P for (index i = xpbound - xbound; i < pivotNeighbors.size(); ++i) { node u = pxvector[i + xbound]; forOutEdgesOf(u, [&](node v) { index neighborPos = pxlookup[v]; if (neighborPos >= xbound && neighborPos < pbound) { ++pivotNeighbors[neighborPos - xbound]; if (neighborPos >= xpbound) { ++pivotNeighbors[i]; } } }); } node maxnode = pxvector[xbound]; count maxval = pivotNeighbors[0]; // Step 3: find maximum for (index i = 1; i < pivotNeighbors.size(); ++i) { if (pivotNeighbors[i] > maxval) { maxval = pivotNeighbors[i]; maxnode = pxvector[i + xbound]; } } #ifndef NDEBUG assert(maxnode < G->upperNodeIdBound() + 1); #endif return maxnode; } }; } // namespace namespace NetworKit { MaximalCliques::MaximalCliques(const Graph &G, bool maximumOnly) : G(&G), maximumOnly(maximumOnly) {} MaximalCliques::MaximalCliques(const Graph &G, std::function<void(const std::vector<node> &)> callback) : G(&G), callback(std::move(callback)), maximumOnly(false) {} const std::vector<std::vector<node>> &MaximalCliques::getCliques() const { if (callback) throw std::runtime_error("MaximalCliques used with callback does not store cliques"); assureFinished(); return result; } void MaximalCliques::run() { hasRun = false; result.clear(); MaximalCliquesImpl(*G, result, callback, maximumOnly).run(); hasRun = true; } } // namespace NetworKit
true
099c730bb029a8a67eab1de70dc80ef99767896d
C++
flydecahedron/engine
/src/Audio.hpp
UTF-8
5,215
2.953125
3
[]
no_license
#ifndef AUDIO_HPP_ #define AUDIO_HPP_ #include <SFML/Audio.hpp> #include "utils/Uncopyable.hpp" #include <cassert> #include <vector> #include <queue> #include <algorithm> #include <iostream> #include <unordered_map> /** Maximum amount of sounds at any given time. SFML docs state 256 is recommended max */ const int MaxSounds = 200; /** * Adds and plays sounds to the game engine by name and filepath. * Implemented so that entityx events can be used to tell the AudioSystem to play sounds by * passing the name of the sound to its Audio ref. When sounds are added by calling addSound(), * the private AudioLoader handles loading the buffer from the given filepath so that the buffer * can be accessed by name. Music is handled the same except that loadMusic() needs to be called * first. This is done since music is obviously more heavyweight and if needed the same can be * done for sounds and their sound buffers if optimization is needed (but makes for a less clean * api). */ class Audio : private Uncopyable { public: /** * Ensures that only one instance exists and reserves the sounds vector according * to MaxSounds. */ Audio(); /** allows others instances to be created by setting instantiated to false */ ~Audio(); /** Checks if sounds are done playing and invalidates sounds if they are. * Basically, the vector containing all the sounds is iterated through and if the sound status * is equal to sf::Sound::Stopped (which comes from the status enum) then its index is pushed onto * the queue of available indices. Only reads are done on the sounds vector during iteration * which allows for the possibility of multithreading. * Currently this is called every frame in the Level class. * @see Level */ void update(); /** * Adds and loads the sound to the game. * The appropriate sf::SoundBuffer is loaded in memory so that sounds can be played with * little overhead. If the name already exists it, the filePath will be overriden by the new * path passed in. * @see AudioLoader * @param name Used to play sounds and access their buffers by name * @param filePath The actual file that the buffer will be loaded from */ void addSound(const std::string& name, const std::string& filePath); /** * Frees the buffer from their associated containers. * @see AudioLoader * @param name The same name used when initially adding the sound */ void freeSound(const std::string& name); /** * Adds the music's file path by name to the game. * @param name Used to associate the file path with the name given * @param filePath Location of the music file */ void addMusic(const std::string& name, const std::string& filePath); /** * Loads the music into memory. * unique_ptr is used to contain the music and is owned by AudioLoader. * @param name Same name used when adding music */ void loadMusic(const std::string& name); /** * Frees the music from memory without deleting the name and associated file path. * @param name Same name used when adding music */ void freeMusic(const std::string& name); /** * Plays the sound by the given name with default values such as volume, etc. * A new sound instance is created per call and its buffer is set to its appropriate buffer * in the buffers map contained by loader. Invalidated indices are used first before pushing * the new sound onto the back of the sounds container. * * Possible Future Changes: A handle maybe returned to changed the specific sound being played. * This could be an int according to its index (which would only be valid until the initial * playthrough of the sound is finished). Since sounds are supposed to be relatively short, * setting the initial parameters for the sound will probably be the easiest/safest way to * handle sound effects and such. Maybe this could be handled in the update method through * events emitted by the ecs. * @param name */ void playSound(const std::string& name); // return a handle? to perform actions on sound(vol, etc) //void stop(const std::string& name); /** * Plays the associated music file from its current position. * @param name Same name used when adding music */ void playMusic(const std::string& name); /** * Pauses the associated music file at its current position which can be resumed with playMusic(). * @param name Same name used when adding music */ void pauseMusic(const std::string& name); /** * Stops and rewinds the associated music file. * @param name Same name used when adding music */ void stopMusic(const std::string& name); private: /** Ensures only one Audio object is instantiated */ static bool instantiated; /** Contains all sounds and is asserted to not grow (might be changed to array later). */ std::vector<sf::Sound> sounds; /** Indices of sounds container that new sounds can be placed into */ std::queue<unsigned short int> availableIndices; std::unordered_map<std::string, std::string> soundPaths; std::unordered_map<std::string, std::string> musicPaths; std::unordered_map<std::string, sf::SoundBuffer> buffers; std::unordered_map<std::string, std::unique_ptr<sf::Music>> musicPtrs; }; #endif /* AUDIO_HPP_ */
true
1cf6eb33d8ab95fc7694e9143ea58fff2b00566d
C++
norbertsiwinski/ZadanieLiczbyZespolone
/ZespoloneFinal/src/Statystyki.cpp
UTF-8
979
2.96875
3
[ "MIT" ]
permissive
using namespace std; #include "Statystyki.hh" void inicjuj(Statystyki &st){ st.dobre=0; st.wszystkie=0; } void wyswietl(Statystyki &st){ cout<<st.dobre; cout<<st.wszystkie; } int ile_dobrych(Statystyki &st){ st.dobre++; return st.dobre; } void dodaj_popr(Statystyki &st){ ile_dobrych(st); ile_wszystkich(st); } void dodaj_zla(Statystyki &st){ ile_wszystkich(st); } int ile_wszystkich(Statystyki &st){ st.wszystkie=st.wszystkie+1; return st.wszystkie; } float procent_dobrych(Statystyki &st){ return ((float)st.dobre/(float)st.wszystkie)*100; } void wyswietl_s(Statystyki &st) { cout << procent_dobrych(st); } ostream & operator <<(ostream &strm, Statystyki &st){ strm<<"Liczba pytan:"<< st.wszystkie<<endl; strm<<"Liczba poprawnych odp:"<< st.dobre<<endl; strm<<"Liczba blednych odp:"<<st.wszystkie - st.dobre<<endl; strm<<"Procent dobrych odp:"<<procent_dobrych(st); return strm; }
true
5ed255a87366b924d50d893805e5297a2008bc96
C++
TheIslland/learning-in-collegelife
/20.蓝桥/网页跳转.cpp
UTF-8
1,482
2.875
3
[]
no_license
/************************************************************************* > File Name: 网页跳转.cpp > Author:TheIslland > Mail: 861436930@qq.com > Created Time: 2019年02月20日 星期三 16时21分18秒 ************************************************************************/ #include <iostream> #include <algorithm> #include <string> #include <vector> #include <queue> #include <stack> using namespace std; int main() { int n; cin >> n; stack<string> forward, back; string temp; while (n--) { string operate, web; cin >> operate; if (operate == "VISIT") { cin >> web; while (!forward.empty()) forward.pop(); if (!temp.empty()) back.push(temp); temp = web; cout << web << endl; } else if (operate == "BACK") { if (back.empty()) { cout << "Ignore" << endl; } else { if (!temp.empty()) forward.push(temp); string url = back.top(); temp = url; cout << url << endl; back.pop(); } } else { if (forward.empty()) { cout << "Ignore" << endl; } else { if (!temp.empty()) back.push(temp); string url = forward.top(); temp = url; cout << url << endl; forward.pop(); } } } return 0; }
true
6f343a90d7ca1df33c8c9059546cedcf87e9aa58
C++
Sookmyung-Algos/2021algos
/algos_assignment/3rd_grade/송혜민_songfox00/11월 4주차/2042.cpp
UTF-8
1,367
2.609375
3
[]
no_license
#include <iostream> using namespace std; long long v[1000001]; long long tree[1<<21]; void init(int node_idx, int node_left, int node_right){ if(node_left==node_right){ tree[node_idx]=v[node_left]; return; } int mid=(node_left+node_right)/2; init(node_idx*2, node_left, mid); init(node_idx*2+1, mid+1, node_right); tree[node_idx]=tree[node_idx*2]+tree[node_idx*2+1]; } long long query(int node_idx, int s, int e, int l, int r){ if(s > r || e < l) return 0; if(l <= s && e <= r) return tree[node_idx]; int mid=(s+e)/2; return query(node_idx*2, s, mid, l, r) + query(node_idx*2+1, mid+1, e, l, r); } void update(int node_idx, int node_left, int node_right, int update_idx, long long val){ if(node_left > update_idx || node_right < update_idx) return; if(node_left == node_right){ tree[node_idx]=val; return; } int mid=(node_left+node_right)/2; update(node_idx*2, node_left, mid, update_idx, val); update(node_idx*2+1, mid+1, node_right, update_idx, val); tree[node_idx]=tree[node_idx*2]+tree[node_idx*2+1]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); int n,m,k; cin>>n>>m>>k; for(int i=1;i<=n;i++){ cin>>v[i]; } init(1,1,n); long long a, b, c; for(int i=0;i<m+k;i++){ cin>>a>>b>>c; if(a==1){ update(1,1,n,b,c); } else { cout<<query(1,1,n,b,c)<<'\n'; } } return 0; }
true
bf9f7594ecf0852ff32ecc11585a8d9b31b16497
C++
Coder-Goo/AlgorithmLearning
/nowcoder/剑指offer/JZ61扑克牌中的顺子.cpp
UTF-8
930
3.375
3
[]
no_license
从扑克牌中抽5张牌,判断是不是顺子 先排序: //牌之间的差别< 大小王的个数就可以连成顺子 class Solution { public: bool isStraight(vector<int>& nums) { sort(nums.begin(), nums.end()); //时间复杂度 if(nums[0] != 0) { for(int i = 1; i<5; i++) { if(nums[i] - nums[i-1] != 1) return false; } } else { int zero_count = 1; int i = 1; for(; i<5; i++) { if(nums[i] != 0) break; else { zero_count ++; } } int diff = 0; for(int j = i+1; j<5; j++) { if(nums[j] == nums[j-1]) return false; diff += nums[j] - nums[j-1]; } diff -= (4-i); if(zero_count < diff) return false; } return true; } };
true
4be41f6e1bcd6c3395a6d2def860341495988f4e
C++
rakhi2207/C-Learning
/Practice questions/SumNNaturalNo.cpp
UTF-8
242
2.96875
3
[]
no_license
#include<iostream> using namespace std; long int sum(long int n) { long int sum1=(n*(n+1))/2; return sum1; } int main() { long int a; cout<<"Enter the natural no"; cin>>a; cout<<"Sum is "<<sum(a)<<"\n"; return 0; }
true
5e2528423fd32ee8c1529775a00288b07ced1966
C++
FDI-debug/Laboratory_1sem
/Gordeychuk_Nikita_201_331_lab2.cpp
UTF-8
1,584
3.53125
4
[]
no_license
#include <iostream> using namespace std; int fact(int N) { int F = 1; for(int i = 1; i <= N; i++) { F *= i; } return F; } void task1(int number) { for (int i = 0; i <= number; i++) { for (int j = 0; j <= i; j++) { cout << j; } cout << endl; } } void task2(int n) { for (int k; k <= n; k++) { cout << fact(n) / (fact(n - k) * fact(k)) << " "; } cout << endl; } void task3() { int count, sum, num; while (true) { cout << "Введите число: "; cin >> num; if (num == 0) { break; } else { sum += num; count += 1; } } cout << sum / count << endl; } int main() { int num, n, choice = 0; while (true) { cout << "Что вы хотите выполнить?\n 1 задание \n 2 задание \n 3 задание \n 4 Выход" << endl; cin >> choice; switch (choice) { case 1: { cout << "Введите длину ребра числового треугольника: "; cin >> num; task1(num); break; } case 2: { cout << "Введите коэффициент n: "; cin >> n; task2(n); break; } case 3: { task3(); break; } case 4: { return 0; break; } } } }
true
b7f59d7f8b50e09051aa1756b132db9864ac9c8c
C++
LaelRodrigues/Lab3
/include/questao2/conta.h
UTF-8
2,722
3.46875
3
[]
no_license
/** * @file conta.h * @brief Definicao da classe Conta para representar uma Conta * @author Lael Rodrigues(laelrodrigues7@gmail.com) * @since 28/10/2017 * @date 29/10/2017 */ #ifndef CONTA_H #define CONTA_H #include <memory> using std::shared_ptr; #include <string> using std::string; #include <iostream> using std::ostream; #include <vector> using std::vector; #include "movimentacao.h" /** * @class Conta conta.h * @brief Classe que representa uma Conta * @details Atributos de uma conta: agencia, numero, saldo, * status, limite, limite disponivel e a lista de * movivementacaoes */ class Conta { private: string agencia; /**< Numero da agencia */ string numero; /**< Numero da conta */ float saldo; /**< Saldo da conta */ bool status; /**< status da conta(se e especial ou nao) */ float limite; /**< Limite da conta(caso seja especial) */ float limiteDisp; /**< Limite disponivel da conta(caso seja especial) */ vector<shared_ptr<Movimentacao>> movimentacoes; /**< Lista de movimentacoes */ public: /** @brief Construtor padrao */ Conta(); /** @brief Construtor parametrizado */ Conta(string _agencia, string _numero, float _saldo, bool _status, float _limite); /** @brief Destrutor padrao */ ~Conta(); /** @brief Retorna o numero da agencia */ string getAgencia(); /** @brief Retorna o numero da conta */ string getNumero(); /** @brief Retorna o saldo da conta */ float getSaldo(); /** @brief Retorna se a conta e especial ou nao */ bool getStatus(); /** @brief Retorna o limite da conta(se a conta for especial) */ float getLimite(); /** @brief Retorna o limite disponivel da conta(se a conta for especial) */ float getLimiteDisp(); /** @brief Retorna A lista de movimentacoes */ vector<shared_ptr<Movimentacao>>& getMovimentacoes(); /** @brief Modifica o numero da agencia */ void setAgencia(string _agencia); /** @brief Modifica o numero da conta */ void setNumero(string _numero); /** @brief Modifica o saldo da conta*/ void setSaldo(float _saldo); /** @brief Modifica o status(se a conta e especial ou nao)*/ void setStatus(bool _status); /** @brief Modifica o limite da conta(se a conta for especial) */ void setLimite(float _limite); /** @brief Modifica o limite disponivel da conta(se a conta for especial) */ void setLimiteDisp(float _limiteDisp); /** @brief Adiciona uma movimentacao a lista de movimentacoes */ void setMovimentacoes(shared_ptr<Movimentacao>& _movimentacao); /** @brief Sobrecarga do operador de comparacao */ bool operator==(Conta& conta); /** @brief Sobrecarga do operador de insercao em stream */ friend ostream& operator<<(ostream& o, Conta& conta); }; #endif
true
8f7ad88c1d0b21f97f7679f269aedd16918c50e3
C++
MohamedAboBakr/Codeforces
/606-A-20737309.cpp
UTF-8
361
2.5625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int a,b,c; cin >> a >> b >> c; int x,y,z; cin >> x >> y >> z; int la = a-x>0?(a-x)/2:(a-x); int lb = b-y>0?(b-y)/2:(b-y); int lc = c-z>0?(c-z)/2:(c-z); if(la + lb + lc >= 0) cout << "YES" << endl; else cout << "NO" << endl; }
true
bd5fc62b6eedc8b92a5cbe684e9235abae16e931
C++
kks227/BOJ
/1100/1120.cpp
UTF-8
365
2.546875
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int main(){ char A[51], B[51]; scanf("%s %s", A, B); int Alen = strlen(A); int Blen = strlen(B); int result = Blen; for(int i=0; Alen+i<=Blen; i++){ int cnt = 0; for(int j=0; j<Alen; j++) if(A[j] != B[i+j]) cnt++; result = min(result, cnt); } printf("%d\n", result); }
true
9ffc13cdab98a156586095cac92fa5cda3ded667
C++
ETalienwx/ETGitHub
/Default_member_function/Main.cpp
GB18030
1,876
3.40625
3
[]
no_license
//#include <iostream> //using namespace std; //ռ //namespace bit //{ // int printf = 10; //} // //int main() //{ // cout << bit::printf << endl; // system("pause"); // return 0; //} //ȱʡ //#include <iostream> //using namespace std; //void f(int a = 10) //{ // cout << a << endl; //} //int main() //{ // f(); // f(50); // return 0; //} //autoѧϰ //int main() //{ // int x = 10; // auto y = 'c'; // auto a = &x; // auto* b = &x; // auto& c = x; // cout << typeid(y).name() << endl; // cout << typeid(a).name() << endl; // cout << typeid(b).name() << endl; // cout << typeid(c).name() << endl; // return 0; //} // //int main() //{ // int a; // double b; // char c; // cin >> a; // cin >> b >> c; // cout << a << endl; // cout << b << " " << c << endl; // system("pause"); // return 0; //} //ѧ //class student //{ //public: // void StudentShow() // { // cout << _name <<" "<< _age << endl; // } //public: // char* _name; // int _age; //}; //int main() //{ // student s; // s._name = "zhangsan"; // s._age = 18; // s.StudentShow(); // system("pause"); // return 0; //} //class Date //{ //public: // void Init(int year,int month,int day) // { // _year = year; // _month = month; // _day = day; // } // void Print() // { // std::cout << _year << "-" << _month << "-" << _day << std::endl; // } //private: // int _year; // int _month; // int _day; //}; //int main() //{ // Date d1; // d1.Init(2019, 1, 1); // d1.Print(); // // Date d2; // d2.Init(2019, 2, 23); // d2.Print(); // // Date* p = nullptr; // p->Print(); // // system("pause"); // return 0; //} ////ֵָ //void f(int) //{ // cout << "f(int)" << endl; //} //void f(int*) //{ // cout << "f(int*)" << endl; //} //int main() //{ // f(0);//f(int) // f(NULL);//f(int) // f((int*)NULL);//f(int*) // f(nullptr);//f(int*) // return 0; //}
true
eb91ebc528440a99cbf7cdedf8c199965e02bb3d
C++
kmouelouel/CPlusAdvance
/Interview Cake/UnixProgramProject/UnixProgramProject/main.cpp
UTF-8
2,600
3.03125
3
[]
no_license
///* Name: kahina Mouelouel //student ID:1470398 //Class :COMSC-171 //Instructor:Stuart Fogg //*/ // // //#include <iostream> //#include <string> // //#include <fstream> //#include <cstdlib> // //using namespace std; // //// this function delet all space in the beginning of line. //string DeletSpaceInBEginning( string inputstr){ // int i=0, len=inputstr.length(); // if(len==0) // {return inputstr; } // else // { // while (inputstr[0]==' ') // {inputstr=inputstr.substr(1); // } // //return inputstr; // } // //} //// move the instruction between Do to done //void MoveInstDo_Done(ifstream inputfile, ofstream outfile){ // string line; // inputfile>>line; // // //} // //// this function return the first word in the line instruction // string FirstWord(string inputstr){ // int i=0, len=inputstr.length(); // string word; // // while(inputstr[i]!=' ' ){ // word+=inputstr[i]; // i++; // } // return word; // } // // main function where the programm start the execution //int main(){ // // list of keywords that determine how the program has to write // const int Size=10; // string keywords[Size]={"while","until","for","case","if","done","esac","elif","else","fi"}; // string inputFile; // int choose=0; // string path; // cout<<" What will be your input:"<<endl; // cout<<"1)from user input\n2)from a File"<<endl; // cin>>choose; // // //ofstream output("sourceoutt.txt"); // switch (choose) // { // case 1: // break; // case 2: // // to creat file // cout<<"please, entre the path to your source as C:/Demo/.."<<endl; // cin>>path; // ifstream input; // input.open(path);// OPE NHE FILE THAT GIVEN BY Chemin // fstream output("resultfinal.txt"); // if(!input.is_open()) // { // cerr<< "File could not opened "<< path<<endl; // exit(1); // } // else // { // cout<<"the file was opened "<< path<<endl; // } // std::string line,word,thFirsteword; // //The position of the first character that matches // while(std::getline(input,line)){ // line= DeletSpaceInBEginning(line); // // input<<line<<endl; // } // output.close(); // // while (input>>thFirsteword) // { // cout<<thFirsteword<<endl; // // std::getline(input,line); // cout<<line<<endl; // //line= DeletSpaceInBEginning(line); // // //output<<line<<endl; // // cout<<line<<endl; // } // // break; // /* default: // cout<<"I don't know what "<<choose<<" is!"<<endl; */ // }// end which // cout <<"the result of source"<<endl; //system("pause"); //}// end main
true
ce5c05269c532b958fb1c089c584ea212c16b606
C++
polgreen/fastsynth-2
/src/fastsynth/bitvector2integer.cpp
UTF-8
1,682
2.875
3
[]
no_license
#include "bitvector2integer.h" #include <util/arith_tools.h> // TODO: check how we get value from constant or symbol bitvector void bitvec2integert::convert(exprt &expr) { for (auto &op : expr.operands()) convert(op); if (expr.id() == ID_constant) { if (expr.type().id() == ID_unsignedbv) { mp_integer mpint; to_integer(to_constant_expr(expr), mpint); expr = constant_exprt(integer2string(mpint), integer_typet()); } } else if (expr.id() == ID_symbol) { if (expr.type().id() == ID_unsignedbv) { expr = symbol_exprt(to_symbol_expr(expr).get_identifier(), integer_typet()); } } else if (expr.id() == ID_infinity) { if (expr.type().id() == ID_unsignedbv) expr = infinity_exprt(integer_typet()); } } void bitvec2integert::convert(typet &type) { for (auto &t : type.get_sub()) { const typet st = static_cast<const typet &>(t); if (st == get_nil_irep()) break; else convert(type.subtype()); } if (type.id() == ID_unsignedbv) type = integer_typet(); else if (type.id() == ID_array) { exprt new_size = to_array_type(type).size(); convert(new_size); // std::cout << "ARRAY SIZE " << new_size.pretty() << std::endl; type = array_typet(to_array_type(type).subtype(), new_size); } else if (type.id() == ID_mathematical_function) { for (auto &d : to_mathematical_function_type(type).domain()) convert(d); convert(to_mathematical_function_type(type).codomain()); } } // void bitvec2integert::convert_back(exprt &expr, std::size_t bv_size) // { // } // void bitvec2integert::convert_back(typet &type, std::size_t bv_size) // { // }
true
da96dd2db8b574e6e852014721e9ad69e7904756
C++
bobpepin/dust3d
/src/animationclipplayer.cpp
UTF-8
2,012
2.90625
3
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
#include "animationclipplayer.h" AnimationClipPlayer::~AnimationClipPlayer() { clear(); } void AnimationClipPlayer::setSpeedMode(SpeedMode speedMode) { m_speedMode = speedMode; } void AnimationClipPlayer::updateFrameMeshes(std::vector<std::pair<float, Model *>> &frameMeshes) { clear(); m_frameMeshes = frameMeshes; frameMeshes.clear(); m_currentPlayIndex = 0; m_countForFrame.restart(); if (!m_frameMeshes.empty()) m_timerForFrame.singleShot(0, this, &AnimationClipPlayer::frameReadyToShow); } void AnimationClipPlayer::clear() { freeFrames(); delete m_lastFrameMesh; m_lastFrameMesh = nullptr; } void AnimationClipPlayer::freeFrames() { for (auto &it: m_frameMeshes) { delete it.second; } m_frameMeshes.clear(); } int AnimationClipPlayer::getFrameDurationMillis(int frame) { int millis = m_frameMeshes[frame].first * 1000; if (SpeedMode::Slow == m_speedMode) { millis *= 2; } else if (SpeedMode::Fast == m_speedMode) { millis /= 2; } return millis; } Model *AnimationClipPlayer::takeFrameMesh() { if (m_currentPlayIndex >= (int)m_frameMeshes.size()) { if (nullptr != m_lastFrameMesh) return new Model(*m_lastFrameMesh); return nullptr; } int millis = getFrameDurationMillis(m_currentPlayIndex) - m_countForFrame.elapsed(); if (millis > 0) { m_timerForFrame.singleShot(millis, this, &AnimationClipPlayer::frameReadyToShow); if (nullptr != m_lastFrameMesh) return new Model(*m_lastFrameMesh); return nullptr; } m_currentPlayIndex = (m_currentPlayIndex + 1) % m_frameMeshes.size(); m_countForFrame.restart(); Model *mesh = new Model(*m_frameMeshes[m_currentPlayIndex].second); m_timerForFrame.singleShot(getFrameDurationMillis(m_currentPlayIndex), this, &AnimationClipPlayer::frameReadyToShow); delete m_lastFrameMesh; m_lastFrameMesh = new Model(*mesh); return mesh; }
true
47a25c69a33476756e53a651cbf20b82db460af8
C++
dmontoyain/cpp
/cpp_piscine/d03/ex01/ScavTrap.cpp
UTF-8
2,672
3.15625
3
[]
no_license
#include "ScavTrap.hpp" ScavTrap::ScavTrap(void) : name("noname"), hp(100), maxhp(100), ep(100), maxep(100), level(1), meleedamage(20), rangeddamage(15), armordamage(3) { std::cout << "SC4V-TP <" << name << "> constructed" << std::endl; } ScavTrap::ScavTrap(std::string name) : name(name), hp(100), maxhp(100), ep(100), maxep(100), level(1), meleedamage(20), rangeddamage(15), armordamage(3) { std::cout << "SC4V-TP <" << name << "> constructed" << std::endl; } ScavTrap::~ScavTrap(void) { std::cout << "SC4V-TP <" << name << "> terminated" << std::endl; } ScavTrap::ScavTrap(ScavTrap const& rhs) : name(rhs.name + " copy") { *this = rhs; std::cout << "SC4V-TP <" << name << "> replicated from " << rhs.name << std::endl; } ScavTrap& ScavTrap::operator=(ScavTrap const& rhs) { hp = rhs.hp; maxhp = rhs.maxhp; ep = rhs.ep; maxep = rhs.ep; level = rhs.level; meleedamage = rhs.meleedamage; rangeddamage = rhs.rangeddamage; armordamage = rhs.armordamage; std::cout << "SC4V-TP <" << name << "> stats copied from " << rhs.name << std::endl; return *this; }; void ScavTrap::rangedAttack ( std::string const & target ) { std::cout << "SC4V-TP " + name + " attacks " + target + " at range, causing " + std::to_string(rangeddamage) + " points of damage !" << std::endl; } void ScavTrap::meleeAttack ( std::string const & target ) { std::cout << "SC4V-TP " + name + " attacks " + target + " at range, causing " + std::to_string(meleedamage) + " points of damage !" << std::endl; } void ScavTrap::takeDamage ( unsigned int amount ) { std::cout << "SC4V-TP <" << name << "> takes <" << amount << "> points of damage" << std::endl; if (amount >= hp) { hp = 0; std::cout << "SC4V-TP <" << name << "> has taken critical damage" << std::endl; } else { hp -= amount; std::cout << "SC4V-TP <" << name << "> has <" << hp << "/" << maxhp << "> HP left" << std::endl; } } void ScavTrap::beRepaired ( unsigned int amount ) { std::cout << "SC4V-TP <" << name << "> restores <" << amount << "> HP" << std::endl; if (hp + amount >= maxhp) { hp = maxhp; std::cout << "SC4V-TP <" << name + "> restored to full health < " << maxhp << "/" << maxhp << ">" << std::endl; } else { hp += amount; std::cout << "SC4V-TP <" << name << "> has <" << hp << "/" << maxhp << "> HP left" << std::endl; } } void ScavTrap::challengeNewComer( std::string const& target ) { std::cout << "SC4V-TP <" << name << "> challenges <" << target << "> to <" << challenges[rand() % CHALLGS] << ">" << std::endl; }
true
bacf333977fd5321462d0fdd0329bb4e50561734
C++
gusteran/CS-2303
/Homework6/src/Board.cpp
UTF-8
4,843
3.265625
3
[]
no_license
/* * Board.cpp * * Created on: Oct 7, 2019 * Author: gustt */ #include "Board.h" Board::Board() { ships[0] = new AircraftCarrier(0, 0, HORIZONTAL); ships[1] = new Battleship(2, 0, HORIZONTAL); ships[2] = new Cruiser(4, 0, HORIZONTAL); ships[3] = new Destroyer(6, 0, HORIZONTAL); ships[4] = new Submarine(8, 0, HORIZONTAL); for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS; col++) { board[row][col] = EMPTY; } } for (int shipN = 0; shipN < 5; shipN++) { int row = ships[shipN]->getRow(); int col = ships[shipN]->getCol(); for (int length = ships[shipN]->getLength(); length > 0; length--) { board[row][col] = shipN; if (ships[shipN]->getDirection() == HORIZONTAL) col++; else if (ships[shipN]->getDirection() == VERTICAL) row++; } } } Board::Board(bool isPlayer) { srand(time(NULL)); ships[0] = new AircraftCarrier(0, 0, HORIZONTAL); ships[1] = new Battleship(0, 0, HORIZONTAL); ships[2] = new Cruiser(0, 0, HORIZONTAL); ships[3] = new Destroyer(0, 0, HORIZONTAL); ships[4] = new Submarine(0, 0, HORIZONTAL); for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS; col++) { board[row][col] = EMPTY; } } int numSet = 0; while (numSet < 5) { int row; int col; if (!isPlayer) { row = rand() % (ROWS - ships[numSet]->getLength()); col = rand() % (COLS - ships[numSet]->getLength()); ships[numSet]->setDirection(rand() % 2); } else { fflush(stdout); printf("Please enter the row, column, and direction of the "); switch (numSet) { case 0: printf("Airplane Carrier of length 5"); break; case 1: printf("Battleship of length 4"); break; case 2: printf("Cruiser of length 3"); break; case 3: printf("Destroyer of length 2"); break; case 4: printf("Submarine Carrier of length 3"); break; } printf("\nRow: \t"); fflush(stdout); scanf("%d", &row); fflush(stdin); printf("Col: \t"); fflush(stdout); scanf("%d", &col); fflush(stdin); printf("Direcion (Horizontal/Vertical: \t"); fflush(stdout); char c; scanf("%c", &c); fflush(stdin); ships[numSet]->setDirection((c == 'h' || c == 'H') ? HORIZONTAL:VERTICAL); printf("Row %d, Col %d, Direction %c \n", row, col, (c == 'h' || c == 'H') ? 'H':'V'); } ships[numSet]->setLocation(row, col); if (ships[numSet]->setLocation(row, col)) { bool isEmpty = true; for (int length = ships[numSet]->getLength(); length > 0; length--) { isEmpty &= (board[row][col] == EMPTY); if (ships[numSet]->getDirection() == HORIZONTAL) col++; else if (ships[numSet]->getDirection() == VERTICAL) row++; } if (isEmpty) { for (int length = ships[numSet]->getLength(); length > 0; length--) { if (ships[numSet]->getDirection() == HORIZONTAL) col--; else if (ships[numSet]->getDirection() == VERTICAL) row--; board[row][col] = numSet; } numSet++; } } } } bool Board::hasLost(){ bool lost = false; for(Ship *ship: ships) lost |= ship->hasSunk(); return lost; } bool Board::shot(int row, int col) { if (isShip(row, col)) { return ships[board[row][col]]->hit(row, col); } else if (isValid(row, col)) { board[row][col] = MISS; } return false; } bool Board::isHit(int row, int col) { return isShip(row, col) && ships[board[row][col]]->isHit(row, col); } bool Board::isShip(int row, int col) { return isValid(row, col) && board[row][col] < EMPTY; } bool Board::isValid(int row, int col) { return row >= 0 && row < ROWS && col >= 0 && col < COLS; } void Board::printBoard(bool canView) { for (int col = 0; col < COLS + 2; col++) printf("-"); printf("\n"); for (int row = 0; row < ROWS; row++) { printf("|"); for (int col = 0; col < COLS; col++) { if ((isShip(row, col) && canView) || isHit(row, col)) printf("%c", ships[board[row][col]]->toChar(row, col)); else if (board[row][col] == MISS) printf("%c", '*'); else printf("%c", '~'); } printf("|\n"); } for (int col = 0; col < COLS + 2; col++) printf("-"); printf("\n\n"); } void Board::filePrintBoard(bool canView) { FILE *outputP = fopen("output.txt", "r+"); fseek(outputP, 0L, SEEK_END); fprintf(outputP, "\n\n\n\n"); for (int col = 0; col < COLS + 2; col++) fprintf(outputP, "-"); fprintf(outputP, "\n"); for (int row = 0; row < ROWS; row++) { fprintf(outputP, "|"); for (int col = 0; col < COLS; col++) { if ((isShip(row, col) && canView) || isHit(row, col)) fprintf(outputP, "%c", ships[board[row][col]]->toChar(row, col)); else if (board[row][col] == MISS) fprintf(outputP, "%c", '*'); else fprintf(outputP, "%c", '~'); } fprintf(outputP, "|\n"); } for (int col = 0; col < COLS + 2; col++) fprintf(outputP, "-"); fprintf(outputP, "\n\n"); fclose(outputP); }
true
6755e4d19aa4d7a8d4bdccf5ff6cab0083bfac80
C++
ruihanxu2/leetCode_FBtag
/TwoSum.cpp
UTF-8
253
3.15625
3
[]
no_license
vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> m; for(int i = 0; i < nums.size(); i++){ if(m.count(target - nums[i])) return vector<int>{m[target - nums[i]], i}; else{ m[nums[i]] = i; } } return vector<int>(); }
true
fce13da03df594239393dbb8a744f410b39fdb21
C++
RyukuA/Beaglebone
/Pwm.cpp
UTF-8
1,515
2.6875
3
[]
no_license
/* * Pwm.cpp * * Created on: 21 Dec 2015 * Author: pi */ #include "Pwm.hpp" #include <string.h> #include <iostream> #include <fstream> using namespace std; #define MAX 64 Pwm::Pwm() { // TODO Auto-generated constructor stub } Pwm::~Pwm() { // TODO Auto-generated destructor stub } int Pwm::SetDuty(unsigned int PWMPin, double duty, unsigned int PWMSecond, unsigned int Pval) { //FILE* FileHandle = NULL; char setValue[7], PWMValue[MAX]; sprintf(PWMValue, "/sys/devices/ocp.3/pwm_test_P%d_%d.%d/duty", Pval, PWMPin, PWMSecond); ofstream FileHandle(PWMValue); if(FileHandle.is_open()) { FileHandle << duty; FileHandle.close(); } /* if((FileHandle = fopen(PWMValue, "rb+")) == NULL) { cout << "Cannot open duty handle" << endl; return 1; } strcpy(setValue, duty); fwrite(&setValue, sizeof(char), 7, FileHandle); fclose(FileHandle); */ return 0; } int Pwm::SetPeriod(unsigned int pin, char* period, unsigned second, unsigned int pval) { //FILE* FileHandle = NULL; char setValue[8], PWMValue[MAX]; sprintf(PWMValue, "/sys/devices/ocp.3/pwm_test_P%d_%d.%d/period", pval, pin, second); ofstream FileHandle(PWMValue); if(FileHandle.is_open()) { FileHandle << period; FileHandle.close(); } /* if((FileHandle = fopen(PWMValue, "rb+")) == NULL) { cout << "Cannot open duty handle" << endl; return 1; } */ cout << "Got past opening the file" << endl; //strcpy(setValue, period); //fwrite(&setValue, sizeof(char), 8, FileHandle); //fclose(FileHandle); return 0; }
true
73024a6a6b40cc8cd11942ef7f9fa6d6cb893f78
C++
rohanrao619/Data_Structures_and_Algorithms
/Searching/Maximum_Water_Between_2_Buildings.cpp
UTF-8
975
3.265625
3
[]
no_license
// { Driver Code Starts //Initial Template for C++ // C++ implementation of the approach #include<bits/stdc++.h> using namespace std; // } Driver Code Ends //User function Template for C++ // Return the maximum water that can be stored int maxWater(int height[], int n) { //Your code here int low = 0, high = n-1, result = 0; while(low<high) { result = max(result,(abs(high-low)-1)*min(height[low],height[high])); if(height[low]<=height[high]) low++; else high--; } return result; } // { Driver Code Starts. // Driver code int main() { int t; cin>>t; while(t--) { int n; cin>>n; int height[n]; for(int i=0;i<n;i++) { cin>>height[i]; } cout<<(maxWater(height, n))<<endl; } } // } Driver Code Ends
true
b853c799492664d06fd5bc057649cc328d17f196
C++
paulamlago/EDA-1
/Acepta_El_Reto/problema_272.cpp
UTF-8
1,205
2.90625
3
[ "WTFPL" ]
permissive
#include <iostream> #include <string> #include <cmath> #include <vector> using namespace std; inline void out(int n) { int N = n, rev, count = 0; rev = N; if (N == 0) { putchar_unlocked('0'); // putchar('\n'); return; } while ((rev % 10) == 0) { count++; rev /= 10; } rev = 0; while (N != 0) { rev = (rev << 3) + (rev << 1) + N % 10; N /= 10; } while (rev != 0) { putchar_unlocked(rev % 10 + '0'); rev /= 10; } while (count--) putchar_unlocked('0'); // putchar('\n'); } inline void in(int &n) { n = 0; int ch = getchar_unlocked(); int sign = 1; while (ch < '0' || ch > '9') { if (ch == '-')sign = -1; ch = getchar_unlocked(); } while (ch >= '0' && ch <= '9') n = (n << 3) + (n << 1) + ch - '0', ch = getchar_unlocked(); n = n * sign; } void solve(int num) { int res = 0; int b6[8]; int j = 0; do { res = num % 6; b6[j] = res; ++j; num /= 6; } while (num >= 6); if (num) { b6[j] = num; j++; } for (int i = j - 1; i >= 0; i--) { out(b6[i]); } putchar('\n'); } int main() { int n; int num; in(n); while (n--) { in(num);; solve(num); } return 0; }
true
e0bee309e3f4b19d00cd86957bd82991d8295321
C++
Linzecong/My-ACM-Code
/CodeForces/339A/12436692_AC_30ms_1860kB.cpp
UTF-8
639
2.703125
3
[]
no_license
#include<iostream> #include<algorithm> #include<map> #include<queue> #include<memory.h> #include<string> #include<stdlib.h> using namespace std; int a[1005]; int cnt=0; string temp; int main(){ string str; cin>>str; for(int i=0;i<str.length();i++) { if(str[i]=='+') { a[cnt++]=stoi(temp); temp.clear(); } else{ temp.push_back(str[i]); } } a[cnt++]=stoi(temp); temp.clear(); sort(a,a+cnt); for(int i=0;i<cnt;i++) if(i!=cnt-1) cout<<a[i]<<"+"; else cout<<a[i]<<endl; return 0; }
true
1d93cc2f97eb8067ce214473c8d89239ea5ee330
C++
Cat-Sniper/UbisoftNext2020
/NextAPI2020/GameTest/Entities/Enemies/Spike.cpp
UTF-8
3,596
2.796875
3
[]
no_license
#include "stdafx.h" #include "Spike.h" #include "App/app.h" #include "Managers/GameMath.h" Spike::Spike(Vec2 position, Vec2 sectionTop, Vec2 sectionBack, Vec2 section, float adjustment) { m_isAlive = true; m_hurtOnTouch = true; m_hitRadius = 3.0f; m_adjustment = adjustment; float lengthOfSection = GameMath::Distance(sectionTop, sectionBack); float currentLength = GameMath::Distance(position, sectionBack); Vec2 Direction = GameMath::NormalizeDirection(sectionTop, sectionBack); m_section[0] = (int)section.x; m_section[1] = (int)section.y; m_currentStop = currentLength * (NUM_STOPS-1) / lengthOfSection; if (m_currentStop >= NUM_STOPS / 2) m_currentStop /= 2; // Populate Vector stops for (int i = 0; i < NUM_STOPS; i++) { currentLength = lengthOfSection * i / (NUM_STOPS-1); Vec2 stopPosition = { sectionTop.x + Direction.x * currentLength, sectionTop.y + Direction.y * currentLength }; m_stops[(NUM_STOPS-1) - i] = stopPosition; } m_position = m_stops[m_currentStop]; // Initialize Geometry m_geometry[0] = { 3, 0}; m_geometry[1] = { 1.5, 0.5}; m_geometry[2] = { 2,-2}; m_geometry[3] = { 0.5, -1.5}; m_geometry[4] = { 0,-3}; m_geometry[5] = {-0.5,-1.5}; m_geometry[6] = {-2,-2}; m_geometry[7] = {-1.5, -0.5}; m_geometry[8] = {-3, 0}; m_geometry[9] = {-1.5, 0.5}; m_geometry[10] = {-2, 2}; m_geometry[11] = {-0.5, 1.5}; m_geometry[12] = { 0, 3}; m_geometry[13] = { 0.5, 1.5}; m_geometry[14] = { 2, 2}; m_geometry[15] = { 1.5, 0.5}; for (int i = 0; i < m_nVerts; i++) { m_geometry[i].x += 3; m_geometry[i].y += 3; m_geometry[i].x *= 2; m_geometry[i].y *= 2; } } Spike::~Spike() { } void Spike::Update(float deltaTime) { if (m_isAlive) { float elapsedTime = m_currentTime + deltaTime; // Move toward the player if possible if (m_canMove) { m_timeSinceLastMove = elapsedTime; m_currentStop++; m_position = m_stops[m_currentStop]; m_canMove = false; } // Calculate position of player center Vec2 centroidPt; int xSum = 0, ySum = 0; for (int k = 0; k < m_nVerts; k++) { xSum += m_geometry[k].x; ySum += m_geometry[k].y; } centroidPt.x = (float)xSum / m_nVerts; centroidPt.y = (float)ySum / m_nVerts; Vec2 newPos = m_position; Vec2 t = { newPos.x - centroidPt.x, newPos.y - centroidPt.y }; // Declare and initialize composite matrix to identity Matrix3x3 matComposite; GameMath::Matrix3x3SetIdentity(matComposite); GameMath::Translate2D(t.x, t.y, matComposite); // Apply composite matrix to bullet vertices GameMath::TransformVerts2D(m_nVerts, m_geometry, matComposite); if (elapsedTime - m_timeSinceLastMove > m_moveDelay - m_adjustment && m_currentStop < (NUM_STOPS-1)) { m_canMove = true; } m_currentTime = elapsedTime; } } void Spike::Draw() { if (m_isAlive) { Vec2 startPos = m_geometry[0]; for (int i = 1; i < m_nVerts; i++) { Vec2 endPos = m_geometry[i]; App::DrawLine(startPos.x, startPos.y, endPos.x, endPos.y, GameMath::Red.r, GameMath::Red.g, GameMath::Red.b); startPos = endPos; if (i == m_nVerts - 1) { endPos = m_geometry[0]; App::DrawLine(startPos.x, startPos.y, endPos.x, endPos.y, GameMath::Red.r, GameMath::Red.g, GameMath::Red.b); } } App::DrawLine(m_stops[m_currentStop].x, m_stops[m_currentStop].y, m_stops[0].x, m_stops[0].y, GameMath::Orange.r, GameMath::Orange.g, GameMath::Orange.b); } } void Spike::GetShot() { m_currentStop--; m_timeSinceLastMove = m_currentTime; if (m_currentStop == 0) { m_isAlive = false; } else { m_position = m_stops[m_currentStop]; } }
true
6b0a98e413e8f6a2f4f01d5da8f8aa98acf53b6a
C++
HusterYP/DataStructure
/Sort/Sort_C/SelectSort.cpp
UTF-8
1,764
3.609375
4
[]
no_license
#include<stdio.h> #include<stdlib.h> #define status int #define MAX_COUNT 1000 // 默认对1000个数据进行排序操作 // 函数声明 void CreateRandom(); void ReadFromFile(int* num); void WriteToFile(int* num); void SelectSort(int* num); /*********************************************** * 选择排序 ***********************************************/ int main() { CreateRandom(); int* num = (int*)malloc(sizeof(int)*MAX_COUNT); ReadFromFile(num); SelectSort(num); WriteToFile(num); free(num); return 0; } // 生成随机数存入文件 void CreateRandom() { FILE* fp; if((fp = fopen("data.txt","w")) == NULL) { printf("Open File Error !\n"); return; } for(int i=0;i<MAX_COUNT;i++) { fprintf(fp,"%d\t",rand() % 10000); } fclose(fp); } // 从文件读取数据 void ReadFromFile(int* num) { FILE* fp; if((fp = fopen("data.txt","r")) == NULL) { printf("Open File Error !\n"); return; } for(int i=0;i<MAX_COUNT;i++) { fscanf(fp,"%d",&num[i]); } fclose(fp); } // 将排好序的数据写入文件 void WriteToFile(int* num) { FILE* fp; if((fp = fopen("result.txt","w")) == NULL) { printf("Open File Error !\n"); return; } for(int i=0;i<MAX_COUNT;i++) { fprintf(fp,"%d\t",num[i]); } fclose(fp); } void SelectSort(int* num) { int temp; for(int i=0;i<MAX_COUNT;i++) { int min = i; for(int j=i+1;j<MAX_COUNT;j++) { if(num[j] < num[min]) min = j; } if(min != i) { temp = num[i]; num[i] = num[min]; num[min] = temp; } } }
true
251f2c18bf2b2b1ce3ed7644b33de7a447111185
C++
magickazer/epsilon
/ion/src/shared/events_modifier.cpp
UTF-8
3,574
2.859375
3
[]
no_license
#include "events_modifier.h" #include <assert.h> namespace Ion { namespace Events { static ShiftAlphaStatus sShiftAlphaStatus = ShiftAlphaStatus::Default; static int sLongRepetition = 1; int sEventRepetitionCount = 0; ShiftAlphaStatus shiftAlphaStatus() { return sShiftAlphaStatus; } void removeShift() { if (sShiftAlphaStatus == ShiftAlphaStatus::Shift) { sShiftAlphaStatus = ShiftAlphaStatus::Default; } else if (sShiftAlphaStatus == ShiftAlphaStatus::ShiftAlpha ) { sShiftAlphaStatus = ShiftAlphaStatus::Alpha; } else if (sShiftAlphaStatus == ShiftAlphaStatus::ShiftAlphaLock) { sShiftAlphaStatus = ShiftAlphaStatus::AlphaLock; } } bool isShiftActive() { return sShiftAlphaStatus == ShiftAlphaStatus::Shift || sShiftAlphaStatus == ShiftAlphaStatus::ShiftAlpha || sShiftAlphaStatus == ShiftAlphaStatus::ShiftAlphaLock; } bool isAlphaActive() { return sShiftAlphaStatus == ShiftAlphaStatus::Alpha || sShiftAlphaStatus == ShiftAlphaStatus::ShiftAlpha || sShiftAlphaStatus == ShiftAlphaStatus::AlphaLock || sShiftAlphaStatus == ShiftAlphaStatus::ShiftAlphaLock; } bool isLockActive() { return sShiftAlphaStatus == ShiftAlphaStatus::AlphaLock || sShiftAlphaStatus == ShiftAlphaStatus::ShiftAlphaLock; } void setLongRepetition(int longRepetition) { sLongRepetition = longRepetition; } int repetitionFactor() { return sLongRepetition; }; void setShiftAlphaStatus(ShiftAlphaStatus s) { sShiftAlphaStatus = s; } static void ComputeAndSetRepetionFactor(int eventRepetitionCount) { // The Repetition factor is increased by 4 every 20 loops in getEvent(2 sec) setLongRepetition((eventRepetitionCount / 20) * 4 + 1); } void resetLongRepetition() { sEventRepetitionCount = 0; ComputeAndSetRepetionFactor(sEventRepetitionCount); } void incrementRepetitionFactor() { sEventRepetitionCount++; ComputeAndSetRepetionFactor(sEventRepetitionCount); } void updateModifiersFromEvent(Event e) { assert(e.isKeyboardEvent()); switch (sShiftAlphaStatus) { case ShiftAlphaStatus::Default: if (e == Shift) { sShiftAlphaStatus = ShiftAlphaStatus::Shift; } else if (e == Alpha) { sShiftAlphaStatus = ShiftAlphaStatus::Alpha; } break; case ShiftAlphaStatus::Shift: if (e == Shift) { sShiftAlphaStatus = ShiftAlphaStatus::Default; } else if (e == Alpha) { sShiftAlphaStatus = ShiftAlphaStatus::ShiftAlpha; } else { sShiftAlphaStatus = ShiftAlphaStatus::Default; } break; case ShiftAlphaStatus::Alpha: if (e == Shift) { sShiftAlphaStatus = ShiftAlphaStatus::ShiftAlpha; } else if (e == Alpha) { sShiftAlphaStatus = ShiftAlphaStatus::AlphaLock; } else { sShiftAlphaStatus = ShiftAlphaStatus::Default; } break; case ShiftAlphaStatus::ShiftAlpha: if (e == Shift) { sShiftAlphaStatus = ShiftAlphaStatus::Alpha; } else if (e == Alpha) { sShiftAlphaStatus = ShiftAlphaStatus::ShiftAlphaLock; } else { sShiftAlphaStatus = ShiftAlphaStatus::Default; } break; case ShiftAlphaStatus::AlphaLock: if (e == Shift) { sShiftAlphaStatus = ShiftAlphaStatus::ShiftAlphaLock; } else if (e == Alpha) { sShiftAlphaStatus = ShiftAlphaStatus::Default; } break; case ShiftAlphaStatus::ShiftAlphaLock: if (e == Shift) { sShiftAlphaStatus = ShiftAlphaStatus::AlphaLock; } else if (e == Alpha) { sShiftAlphaStatus = ShiftAlphaStatus::Default; } break; } } } }
true
b45e1aaac6926e1ae31a73ee6f6c56850449debd
C++
linefinc/MinerIA
/TestGame/myMap.cpp
UTF-8
6,601
3.0625
3
[]
no_license
#include "myMap.h" #include "VectorUtils.h" #include <limits> #include <cmath> myMap::myMap(int width, int height, unsigned int ScreenWidth, unsigned int boxSide)// todo: cange coordiante sistem to fit with game coordinte :boxSide(boxSide), ScreenWidth(ScreenWidth), scale(1) { map = new std::vector<MapItem>(); // reset limit minX = INT_MAX; minY = INT_MAX; maxX = INT_MIN; maxY = INT_MIN; // texure array TextureList = new std::vector<sf::Texture*>(); // load texture from file GreyTexture = new sf::Texture(); GreyTexture->loadFromFile("../data/base/base_0001.png"); TextureList->push_back(GreyTexture); // base RedTexture RedTexture = new sf::Texture(); RedTexture->loadFromFile("../data/base/base_0010.png"); TextureList->push_back(RedTexture); // base 003 GreenTexture0 = new sf::Texture(); GreenTexture0->loadFromFile("../data/base/base_0020.png"); TextureList->push_back(GreenTexture0); // GreenTexture1 = new sf::Texture(); GreenTexture1->loadFromFile("../data/base/base_0021.png"); TextureList->push_back(GreenTexture1); // base 008 GreenTexture2 = new sf::Texture(); GreenTexture2->loadFromFile("../data/base/base_0022.png"); TextureList->push_back(GreenTexture2); // todo: fix // base 008 GreenTexture3 = new sf::Texture(); GreenTexture3->loadFromFile("../data/base/base_0022.png"); TextureList->push_back(GreenTexture3); for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) { AddCell(x, y, true, 0); } clock.restart(); } myMap::~myMap(void) { } // // Add cell to Maps // void myMap::AddCell(int x, int y, bool walkable, unsigned char wheatLevel) { if (GetCell(x, y) != NULL) { return; } MapItem item(x, y, walkable); item.setWheatLevel(wheatLevel); item.sprite = new sf::Sprite(); item.sprite->setPosition(VectorUtils::ConvertToScreenSpace(x, y, ScreenWidth)); if (walkable == false) { item.sprite->setTexture(*RedTexture, true); return; } else { if (wheatLevel == 0) { item.sprite->setTexture(*GreyTexture, true); } else { item.sprite->setTexture(*GreenTexture0, true); } } map->push_back(item); // update limit if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y; } myMap::MapItem* myMap::GetCell(int x, int y) const { // todo: use more efficient way to scan array for (unsigned int index = 0; index < map->size(); index++) { if ((map->at(index).x == x) && (map->at(index).y == y)) { return &(map->at(index)); } } return NULL; } void myMap::SetValue(int x, int y, bool walkable, unsigned char wheatLevel) { myMap::MapItem* pItem = GetCell(x, y); if (pItem != NULL) { if (walkable == false) { pItem->setWalkable(false); pItem->sprite->setTexture(*RedTexture, true); return; } else { pItem->setWalkable(true); pItem->setWheatLevel(wheatLevel); if (wheatLevel == 0) { pItem->sprite->setTexture(*GreyTexture, true); } else { // update graphics if (wheatLevel < 4) // 0001b 0 - 3 { pItem->sprite->setTexture(*GreenTexture0, true); return; } if ((wheatLevel > 3) && (wheatLevel < 8)) // 001xb 4-7 { pItem->sprite->setTexture(*GreenTexture1, true); return; } if ((wheatLevel > 7) && (wheatLevel < 13)) // 01xxb 8 - 12 { pItem->sprite->setTexture(*GreenTexture2, true); return; } if (wheatLevel > 12) // 1xxxb 12 - 15 { pItem->sprite->setTexture(*GreenTexture3, true); return; } } } } } // Cell Is Empty // return true if the cell is wolkable // return flase if the cell is not wolkable bool myMap::CellIsEmpty(int x, int y) const { if ((x < minX) || (y < minY)) { return false; } if ((x > maxX) || (y > maxY)) { return false; } myMap::MapItem* pItem = GetCell(x, y); if (pItem != NULL) { return pItem->getWalkable(); } return false; } // Cell Is Empty // return true if the cell is wolkable // return flase if the cell is not wolkable unsigned int myMap::getWheatLevel(int x, int y) const { if ((x < minX) || (y < minY)) { return 0; } if ((x > maxX) || (y > maxY)) { return 0; } myMap::MapItem* pItem = GetCell(x, y); if (pItem != NULL) { return pItem->getWheatLevel(); } return 0; } void myMap::draw(sf::RenderTarget& target, sf::RenderStates states) const { for (unsigned int index = 0; index < map->size(); index++) { if (map->at(index).sprite) { target.draw(*map->at(index).sprite, states); } } } void myMap::Dump(const char* fileName) const { FILE* fp = NULL; if (fopen_s(&fp, fileName, "w") == 0) { exit(0); } if (fp == NULL) { return; } for (int y = minY; y <= maxY; y++) { for (int x = minX; x <= maxX; x++) { myMap::MapItem* pItem = GetCell(x, y); if (pItem == NULL) { fprintf(fp, "X;"); } else { if (pItem->getWalkable() == false) { fprintf(fp, "W;"); } if (pItem->getWalkable() == true) { fprintf(fp, "%d;",pItem->getWheatLevel()); } } } fprintf(fp, "\n"); } fclose(fp); } void myMap::Update(void) { if (clock.getElapsedTime().asSeconds() < 1) { return; } clock.restart(); for (int y = minY; y < maxY; y++) for (int x = minX; x < maxX; x++) { myMap::MapItem* pItem = this->GetCell(x, y); if (pItem == nullptr) { continue; } if (pItem->getWalkable() == true) { continue; } // update current cell unsigned char wheatLevel = pItem->getWheatLevel(); if ((++wheatLevel) > 15) { wheatLevel = 15; } pItem->setWheatLevel(wheatLevel); } } bool myMap::NearestWheat(sf::Vector2f localPosition, sf::Vector2f* out) const { MapItem* bestNode = nullptr; float distance2 = INT_MAX; for (unsigned int index = 0; index < map->size(); index++) { if ((map->at(index).getWalkable() == true)&(map->at(index).getWheatLevel() > 0)) { printf("myMap::NearestWheat %d %d %d\n", map->at(index).x, map->at(index).y, map->at(index).getWheatLevel()); float deltaX = map->at(index).x - localPosition.x; float distanceTemp = deltaX * deltaX; float deltaY = map->at(index).y - localPosition.y; distanceTemp += deltaY*deltaY; if (distance2 > distanceTemp) { distance2 = distanceTemp; bestNode = &map->at(index); } } } // to do : add error if not exist Wheat if (bestNode == nullptr) { return false; } out->x = static_cast<float>(bestNode->x); out->y = static_cast<float>(bestNode->y); printf("myMap::NearestWheat Best: %d %d %d\n", bestNode->x, bestNode->y, bestNode->getWheatLevel()); return true; }
true
a642f0d3c855b4c8b115b7135f3be950f047a705
C++
eliseumiguel/TVPP-DEV
/src/common/Strategy/NearestIPStrategy.hpp
UTF-8
3,432
2.8125
3
[]
no_license
#ifndef NEARESTIPSTRATEGY_H #define NEARESTIPSTRATEGY_H #include "Strategy.hpp" typedef struct NearestNode { unsigned int posVector; unsigned int dist[4]; } NearestNode; class NearestIPStrategy: public Strategy { private: void SelectPeers(vector<PeerData*>* peers, Peer* srcPeer, int quantity, unsigned int minimalBandwidthOut){} void SelectPeers(vector<PeerData*>* peers, Peer* srcPeer, int quantity) { vector<PeerData*> results; unsigned int dif = 256; vector<string> vectorIpOctets; string query = srcPeer->GetIP(); vector<string> vectorIpQueryOctets; Tokenize(query, vectorIpQueryOctets, "."); NearestNode nearest; for (int i = 0; i < quantity; i++) { initializeNearest(nearest); //PARA CADA VETOR DA LISTA for (int j = 0; j < (int)peers->size(); j++) { vector<string> vectorIpOctets; Tokenize((*peers)[j]->GetPeer()->GetIP(), vectorIpOctets, "."); //NUMERO DE OCTETOS - SEMPRE TERA O TAMANHO 4 int tam = vectorIpOctets.size(); for (int g = 0; g < tam; g++) { dif = calculateDistance(atoi(vectorIpQueryOctets[g].c_str()), atoi(vectorIpOctets[g].c_str())); //SE A DISTANCIA DO OCTETO ATUAL FOR MAIOR DE UM IP ANTERIOR, DESCONSIDERA O IP E VAI PARA O PROX DA LISTA if (dif > nearest.dist[g]) break; // SE A DIST DO OCTETO DA LISTA FOR MENOR QUE A DISTANCIA DE UM IP SELECIONADO, O IP MAIS PROXIMO EH O VERIFICADO E VAI PARA O PROXIMO if (dif < nearest.dist[g]) { updateNearest(nearest, vectorIpOctets, vectorIpQueryOctets, j); break; } } } results.push_back((*peers)[nearest.posVector]); peers->erase(peers->begin()+nearest.posVector); } delete peers; peers = &results; } void Tokenize(const string& str, vector<string>& tokens, const string& delimiters = " ") { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } int calculateDistance(int ip1, int ip2) { if(ip1 > ip2) return ip1 - ip2; else return ip2 - ip1; } void updateNearest(NearestNode& nearest, vector<string>& newNearest, vector<string>& query, int indice) { nearest.posVector = indice; nearest.dist[0] = calculateDistance(atoi(newNearest[0].c_str()), atoi(query[0].c_str())); nearest.dist[1] = calculateDistance(atoi(newNearest[1].c_str()), atoi(query[1].c_str())); nearest.dist[2] = calculateDistance(atoi(newNearest[2].c_str()), atoi(query[2].c_str())); nearest.dist[3] = calculateDistance(atoi(newNearest[3].c_str()), atoi(query[3].c_str())); } void initializeNearest(NearestNode& nearest) { nearest.posVector = 0; nearest.dist[0] = 256; nearest.dist[1] = 256; nearest.dist[2] = 256; nearest.dist[3] = 256; }; }; #endif
true
95ce0304960253692b4e322154e788a4f4092098
C++
erengy/nstd
/include/nstd/string/split.hpp
UTF-8
1,805
3.171875
3
[ "MIT" ]
permissive
#pragma once #include <algorithm> #include <functional> #include <string> #include <string_view> #include <vector> #include "constants.hpp" namespace nstd { namespace detail { using string_predicate_t = std::function<bool(const char)>; } // namespace detail inline std::vector<std::string> split(std::string_view str) { std::vector<std::string> output; while (true) { size_t pos = str.find_first_of(string_constants::whitespace); if (pos == std::string_view::npos) { if (!str.empty()) { output.push_back(std::string{str}); } break; } if (pos > 0) { output.push_back(std::string{str.substr(0, pos)}); str.remove_prefix(pos); } pos = str.find_first_not_of(string_constants::whitespace); str.remove_prefix(std::min(pos, str.size())); } return output; } inline std::vector<std::string> split(std::string_view str, const std::string_view delimiter) { std::vector<std::string> output; while (true) { const size_t pos = str.find(delimiter); if (pos == std::string_view::npos) { output.push_back(std::string{str}); break; } output.push_back(std::string{str.substr(0, pos)}); str.remove_prefix(pos + delimiter.size()); } return output; } inline std::vector<std::string> split_if( std::string_view str, const detail::string_predicate_t predicate) { std::vector<std::string> output; while (true) { const auto it = std::find_if(str.begin(), str.end(), predicate); if (it == str.end()) { output.push_back(std::string{str}); break; } const auto pos = std::distance(str.begin(), it); output.push_back(std::string{str.substr(0, pos)}); str.remove_prefix(pos + 1); } return output; } } // namespace nstd
true
a2408e87a2620b4fca54fce9aa5bf4a7b2e8abcf
C++
fossabot/deplug
/plugkit/src/frame.hpp
UTF-8
904
2.59375
3
[ "MIT" ]
permissive
#ifndef PLUGKIT_FRAME_H #define PLUGKIT_FRAME_H #include "types.hpp" #include <memory> namespace plugkit { class FrameView; class Frame final { public: Frame(); virtual ~Frame(); Timestamp timestamp() const; void setTimestamp(const Timestamp &timestamp); size_t length() const; void setLength(size_t length); uint32_t index() const; void setIndex(uint32_t index); Layer *rootLayer() const; void setRootLayer(Layer *layer); const FrameView *view() const; void setView(const FrameView *view); uint32_t sourceId() const; void setSourceId(uint32_t id); private: Frame(const Frame &) = delete; Frame &operator=(const Frame &) = delete; private: Timestamp mTimestamp = std::chrono::system_clock::now(); size_t mLength = 0; uint32_t mSeq = 0; Layer *mLayer = nullptr; const FrameView *mView = nullptr; uint32_t mSourceId = 0; }; } // namespace plugkit #endif
true
a1e8cd5849dd76a58327c01fd002ee28fc8adfd8
C++
rvfarias/LP1_LISTA1
/questao3/src/main.cpp
UTF-8
2,077
2.90625
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> #include "invoice.h" using namespace std; int main(){ Invoice in1; Invoice in2; Invoice in3; Invoice in4; in1.setValor(); in2.setCodItem(2220003); in2.setDescr("Usado"); in2.setPreco(70.00); in2.setQitem(4); in2.setValor(); in3.setCodItem(32432444); in3.setDescr("Completo"); in3.setPreco(149.99); in3.setQitem(-2); in3.setValor(); in4.setCodItem(12346321); //in4.setDescr(); in4.setPreco(-200.00); in4.setQitem(5); in4.setValor(); cout << "Numero: " << in1.getCodItem() << endl; cout << "Quatidade comprada: " << in1.getQitem() << endl; cout << "Preço do item: " << in1.getPreco() << endl; cout << "Descrição: " << in1.getDescr() << endl; cout << "Valor total: " << in1.getInvoiceAmount() << endl; cout << endl; cout << "Numero: " << in2.getCodItem() << endl; cout << "Quatidade comprada: " << in2.getQitem() << endl; cout << "Preço do item: " << in2.getPreco() << endl; cout << "Descrição: " << in2.getDescr() << endl; cout << "Valor total: " << in2.getInvoiceAmount() << endl; cout << endl; cout << "Numero: " << in3.getCodItem() << endl; cout << "Quatidade comprada: " << in3.getQitem() << endl; cout << "Preço do item: " << in3.getPreco() << endl; cout << "Descrição: " << in3.getDescr() << endl; cout << "Valor total: " << in3.getInvoiceAmount() << endl; cout << endl; cout << "Numero: " << in4.getCodItem() << endl; cout << "Quatidade comprada: " << in4.getQitem() << endl; cout << "Preço do item: " << in4.getPreco() << endl; cout << "Descrição: " << in4.getDescr() << endl; cout << "Valor total: " << in4.getInvoiceAmount() << endl; cout << endl; return 0; }
true
22c2ff70b36805ff6e7386f6e195baae55080684
C++
avanishgiri/Algorithms
/CodeEval/test.cpp
UTF-8
1,033
3.015625
3
[]
no_license
#include <iostream> #include <cstdlib> #include <vector> #include <math.h> #include <fstream> #include <sstream> using namespace std; int main(int argc, char **argv){ ifstream file; file.open(argv[1]); string test; long long limit; while (!file.eof()) { getline(file, test); if (test.length() == 0) continue; //ignore all empty lines else { stringstream ss(test); ss >> limit; limit--; long long sqrtlimit = sqrt(limit); vector<bool> sieve(limit+1, false); for(long long n = 4; n <= limit; n += 2) sieve[n] = true; for(long long n=3; n <= sqrtlimit; n = n+2){ if(!sieve[n]){ cout << n << ","; for(long long m = n*n; m<=limit; m=m+(2*n)) sieve[m] = true; } } long long last; for(long long i=limit; i >= 0; i--){ if(sieve[i] == false){ last = i; break; } } for(long long i=2;i<=limit;i++) { if(!sieve[i]) if(i != last) cout<<i<<","; else cout<<i; } cout<<endl; } } }
true
bb666ccd785e280e8bc01c51febbaa7abdaebf1f
C++
ribeiropdiogo/CG
/engine/ObjLoader.cpp
UTF-8
6,411
2.59375
3
[]
no_license
#include "ObjLoader.h" #include "Common.h" #include <unordered_map> #include <sstream> #include <TexLoader.h> #define OBJ_FOLDER "../../samples/3D/" using namespace std; void parse_point_wvobj(string name, int *indexes, int* sizes) { int num, i = 0; string item; stringstream ss(name); while( getline(ss,item,'/') ) { if(!item.empty()) { num = stoi(item); if(num < 0) { num = sizes[i] + num; } else num--; indexes[i++] = num; } else { indexes[i++] = 1; } } } // Reads all of the materials associated with the specified name. // used must provide the necessary mtlib unordered_map<string,Material> parse_materials(string mtlib) { string line, name; ifstream file(OBJ_FOLDER + mtlib); bool first_found = true; Material* mat = new Material(); unordered_map<string,Material>* materials = new unordered_map<string,Material>(); if(file.is_open()) { while ( getline(file,line) ) { if(!line.empty()) { string str; vector<string> tokens; stringstream ss(line); while(getline(ss, str,' ')) { tokens.push_back(str); } if(!tokens[0].compare("newmtl")) { // new material found. name = tokens[1]; if(!first_found) { materials->insert({name, *mat}); mat = new Material(); } else first_found = false; } else if(!tokens[0].compare("Ka")) { // specifications of ambient. mat->ambient = glm::vec4(stof(tokens[1]),stof(tokens[2]),stof(tokens[3]),1); } else if(!tokens[0].compare("Kd")) { // specifications of diffuse. mat->diffuse = glm::vec4(stof(tokens[1]),stof(tokens[2]),stof(tokens[3]),1); } else if(!tokens[0].compare("Ks")) { // specifications of specular. mat->specular = glm::vec4(stof(tokens[1]),stof(tokens[2]),stof(tokens[3]),1); } else if(!tokens[0].compare("Ns")) { // specifications of shininess. mat->shininess = stof(tokens[1]); } else if(!tokens[0].compare("map_Kd")) { // new texture found. mat->idTexture = TexLoader::loadTexture(tokens[1].c_str()); } } } materials->insert({name, *mat}); } return *materials; } Object3d* ObjLoader::loadWVObj(string file_name, GLuint id_tex, Material material) { string line, name; ifstream file(OBJ_FOLDER + file_name); vector<glm::vec3> points; vector<glm::vec3> normals; vector<glm::vec2> texcoord; unordered_map<string,Material> materials; Object3d* obj = new Object3d(id_tex, material); if(file.is_open()) { while ( getline(file,line) ) { if(!line.empty()) { string str; vector<string> tokens; stringstream ss(line); while(getline(ss, str,' ')) { tokens.push_back(str); } if(!tokens[0].compare("v")) { // Found new vertice. points.push_back(glm::vec3( stof(tokens[1]),stof(tokens[2]),stof(tokens[3]) )); } else if(!tokens[0].compare("vn")) { // found new vertice normal normals.push_back(glm::vec3( stof(tokens[1]),stof(tokens[2]),stof(tokens[3]) )); } else if(!tokens[0].compare("vt")) { // found new tex coord. texcoord.push_back(glm::vec2( stof(tokens[1]),stof(tokens[2]) )); } else if(!tokens[0].compare("mtllib")) { // found new material lib, must learn and conquest. auto newmats = parse_materials(tokens[1]); materials.insert(newmats.begin(), newmats.end()); } else if(!tokens[0].compare("usemtl")) { // if the material was previously observed. if( materials.find(tokens[1]) != materials.end() ) { // then, announce the new material. obj->announce_material(materials[tokens[1]]); } } else if(!tokens[0].compare("f")) { int indexes[3]; int sizes[3] = {(int)points.size(), (int)texcoord.size(), (int)normals.size()}; int N = tokens.size() - 3; for(int i = 0; i < N; i++) { for(int j = 0; j < 3; j++ ) { glm::vec2 tc = glm::vec2(0); parse_point_wvobj(tokens[i+j+1],indexes,sizes); if(texcoord.size() != 0) tc = glm::vec2(texcoord[indexes[1]]); obj->add_face_point(points[indexes[0]], normals[indexes[2]], tc); } } } } } } return obj; } Object3d* ObjLoader::load3DObj(string file_name, GLuint id_tex, Material material) { float val = 0.0f; Object3d *obj = new Object3d(id_tex, material); GLuint numVertices = 0, tempI = 0; ifstream inFile(file_name); inFile >> numVertices; for (int i=0; i < numVertices; i++) { for (int j = 0; j < 8; j++) { inFile >> val; obj->add_atomic(val); } } while (!inFile.eof()) { inFile >> tempI; obj->add_index(tempI); } inFile.close(); return obj; } Object3d* ObjLoader::loadFile(string file_name, GLuint id_tex, Material material) { string path = OBJ_FOLDER; path.append(file_name); return isSuffixOf(file_name, ".obj") ? loadWVObj(path, id_tex, material) : load3DObj(path, id_tex, material); }
true
e2d9f8f675711360eb0e3dc2d99c0f31f26d51dd
C++
woshilinlin/tool
/test1/rtspcamera.h
UTF-8
1,128
2.515625
3
[]
no_license
#ifndef RTSPCAMERA_H #define RTSPCAMERA_H #include <opencv2/opencv.hpp> #include <QImage> class RTSPCamera : public QObject { Q_OBJECT public: /*! * \brief RTSPCamera rtsp协议摄像头 * \param rtspUrl url路径 */ RTSPCamera(const QString & rtsp_url); /*! * \brief doCapture 拍照 */ void doCapture(); /*! * \brief frameSize 图片大小 * \return 返回图片大小 */ QSize frameSize(); public slots: /*! * \brief vInit 初始化摄像头 * \return 初始化成功返回true */ bool vInit(); /*! * \brief vRelease 释放资源 */ void vRelease(); /*! * \brief doCaptures 获取图片的槽函数 * \return cv::Mat格式的图片 */ cv::Mat doCaptures(); signals: /*! * \brief sendIamage 发送图片信号 */ void sendIamage(const cv::Mat &); /*! * \brief capture 拍照信号 */ void capture(); private: cv::VideoCapture _camera; QString _rtsp_url = QString::null; QImage _lastCapturedImage; QSize _frameSize; }; #endif // RTSPCAMERA_H
true
dfacc05c6d6de598ac8c038f6a8d37d7b89828e2
C++
berneylin/LeetCode2019Spring
/28/implement_strStr.cpp
UTF-8
605
2.953125
3
[]
no_license
class Solution { public: int strStr(string haystack, string needle) { int needleLen = needle.size(); int haystackLen = haystack.size(); if(!needleLen) return 0; int ret = -1; for(int i=0;i<haystackLen-needleLen+1;i++){ bool thisCmp = true; for(int j=0;j<needleLen;j++){ if(haystack[i+j]!=needle[j]){ thisCmp = false; break; } } if(thisCmp){ ret = i; break; } } return ret; } };
true
8178436a49c8c6206f39cf8a790d77ed114ae782
C++
OliverAkhtar/Projects
/Introduction to Progamming/Lab Projects/lab9/powersOfTwo.cpp
UTF-8
374
4.0625
4
[]
no_license
/*This program prints the powers of 2 from zero to a user inputted integer.*/ #include <iostream> #include <cmath> using namespace std; int main() { int number; int counter; cout << "A table of powers, enter a number: "; cin >> number; for(counter=0; counter<=number; counter++) cout << "2 to the power of " << counter << " is " << pow(2,counter) << endl; return 0; }
true
caad8e57de2f13689a954b29ffc5947802c8d3a2
C++
rafaeltmbr/algorithm-data-structure
/graph/test/graph-testbench.cpp
UTF-8
15,252
3.0625
3
[]
no_license
/* Build Commands: g++ graph-testbench.cpp ../src/graph.cpp ../../list/src/list.cpp -g -Wall -std=c++14 -o graph.exe */ #include "../include/graph.hpp" #include <iostream> #define ASSERT(cond, msg) \ if (cond) \ std::cout << "#"; \ else { \ std::cerr << "\n Test failed (" << __LINE__ << "): " << msg << std::endl; \ exit(EXIT_FAILURE); \ } using namespace std; void testConstructor(Graph& graph); void testInsertVertex(Graph& graph); void testRemoveVertex(Graph& graph); void testInsertEdges(Graph& graph); void testRemoveEdges(Graph& graph); void testNoMatchFunction(Graph& graph); void testGetMethods(Graph& graph); void testDestroy(Graph& graph); int main() { cout << "------------------------ Graph Testbench ------------------------\n"; Graph graph; testConstructor(graph); testInsertVertex(graph); testRemoveVertex(graph); testInsertEdges(graph); testRemoveEdges(graph); testNoMatchFunction(graph); testGetMethods(graph); testDestroy(graph); cout << "------------------------ Testbench Succeed ------------------------" << endl; } void testConstructor(Graph& graph) { cout << " Constructor Test: "; const int charArraySize = 3; char charArray[charArraySize] = { 'A', 'B', 'C' }; graph.match = [](const void* char1, const void* char2) { if (!char1 || !char2) return false; char c1 = *(char*)char1; char c2 = *(char*)char2; return c1 == c2; }; ASSERT(graph.howManyVertexes() == 0, "graph shouldn't have vertexes"); ASSERT(graph.howManyEdges() == 0, "Graph shouldn't have edges"); for (int i = 0; i < charArraySize; i++) ASSERT(graph.insertVertex(charArray + i), "insertVertex() failed on loop: " << i); ASSERT(graph.insertEdge(charArray, charArray + 2), "insertEdge() failed"); ASSERT(graph.howManyVertexes() == 3, "howManyVertexes() failed"); ASSERT(graph.howManyEdges() == 1, "howManyEdges() failed"); Graph copy(graph); ASSERT(copy.howManyVertexes() == 3, "howManyVertexes() failed"); ASSERT(copy.howManyEdges() == 1, "howManyEdges() failed"); ASSERT(graph.hasVertex(charArray), "hasVertex() failed"); ASSERT(graph.removeVertex(charArray), "remove() failed"); ASSERT(!graph.hasVertex(charArray), "hasVertex() failed"); ASSERT(graph.howManyVertexes() == 2, "howManyVertexes() failed"); for (int i = 1; i < charArraySize; i++) ASSERT(graph.removeVertex(charArray + i), "removeVertex() failed on loop: " << i); ASSERT(graph.howManyVertexes() == 0, "graph shouldn't have vertexes"); ASSERT(graph.howManyEdges() == 0, "Graph shouldn't have edges"); ASSERT(copy.howManyVertexes() == 3, "howManyVertexes() failed"); ASSERT(copy.howManyEdges() == 1, "howManyEdges() failed"); cout << " PASSED\n"; } void testInsertVertex(Graph& graph) { cout << " Insert Vertex Test: "; const int arraySize = 10; int iarray[arraySize] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; graph.match = [](const void* data1, const void* data2) { if (!data1 || !data2) return false; int d1 = *(int*)data1; int d2 = *(int*)data2; return d1 == d2; }; ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(graph.insertVertex(iarray + i), "insertVertex() failed in loop: " << i); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(!graph.insertVertex(iarray + i), "insertVertex() failed in loop: " << i); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); graph.destroy(); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); cout << " PASSED\n"; } void testRemoveVertex(Graph& graph) { cout << " Remove Vertex Test: "; const int arraySize = 10; int iarray[arraySize] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; int narray[arraySize] = { -10, -20, -30, -40, -50, -60, -70, -80, -90, -100 }; graph.match = [](const void* data1, const void* data2) { if (!data1 || !data2) return false; int d1 = *(int*)data1; int d2 = *(int*)data2; return d1 == d2; }; ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(graph.insertVertex(iarray + i), "insertVertex() failed in loop: " << i); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(!graph.removeVertex(narray + i), "removeVertex() failed in loop: " << i); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(graph.removeVertex(iarray + i), "removeVertex() failed in loop: " << i); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); cout << " PASSED\n"; } void testInsertEdges(Graph& graph) { cout << " Insert Edge Test: "; const int arraySize = 10; int iarray[arraySize] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; int narray[arraySize] = { -10, -20, -30, -40, -50, -60, -70, -80, -90, -100 }; graph.match = [](const void* data1, const void* data2) { if (!data1 || !data2) return false; int d1 = *(int*)data1; int d2 = *(int*)data2; return d1 == d2; }; ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(graph.insertVertex(iarray + i), "insertVertex() failed in loop: " << i); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); ASSERT(!graph.insertEdge(iarray, iarray), "insertEdge() failed"); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); for (int i = 1; i < arraySize; i++) ASSERT(graph.insertEdge(iarray, iarray + i), "insertEdge() failed"); ASSERT(graph.howManyEdges() == arraySize - 1, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); for (int i = 1; i < arraySize; i++) ASSERT(!graph.insertEdge(iarray, iarray + i), "insertEdge() failed"); ASSERT(graph.howManyEdges() == arraySize - 1, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(!graph.insertEdge(iarray, narray + i), "insertEdge() failed"); ASSERT(graph.howManyEdges() == arraySize - 1, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); graph.destroy(); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); cout << " PASSED\n"; } void testRemoveEdges(Graph& graph) { cout << " Remove Edge Test: "; const int arraySize = 10; int iarray[arraySize] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; int narray[arraySize] = { -10, -20, -30, -40, -50, -60, -70, -80, -90, -100 }; graph.match = [](const void* data1, const void* data2) { if (!data1 || !data2) return false; int d1 = *(int*)data1; int d2 = *(int*)data2; return d1 == d2; }; ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(graph.insertVertex(iarray + i), "insertVertex() failed in loop: " << i); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); for (int i = 1; i < arraySize; i++) ASSERT(graph.insertEdge(iarray, iarray + i), "insertEdge() failed"); ASSERT(graph.howManyEdges() == arraySize - 1, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); ASSERT(graph.insertEdge(iarray + 1, iarray + 2), "insertEdge() failed"); ASSERT(graph.howManyEdges() == arraySize, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); ASSERT(graph.removeVertex(iarray + 1), "removeVertex() failed"); ASSERT(graph.howManyEdges() == arraySize - 2, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize - 1, "howManyVertexes() failed"); for (int i = 2; i < arraySize; i++) ASSERT(!graph.removeEdge(iarray, narray + i), "removeEdge() failed"); ASSERT(graph.howManyEdges() == arraySize - 2, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize - 1, "howManyVertexes() failed"); for (int i = 2; i < arraySize; i++) ASSERT(graph.removeEdge(iarray, iarray + i), "removeEdge() failed"); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize - 1, "howManyVertexes() failed"); graph.destroy(); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); cout << " PASSED\n"; } void testNoMatchFunction(Graph& graph) { cout << " No Match Function Test: "; const int arraySize = 10; int iarray[arraySize] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; int narray[arraySize] = { -10, -20, -30, -40, -50, -60, -70, -80, -90, -100 }; ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(graph.insertVertex(iarray + i), "insertVertex() failed in loop: " << i); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); for (int i = 1; i < arraySize; i++) ASSERT(graph.insertEdge(iarray, iarray + i), "insertEdge() failed"); ASSERT(graph.howManyEdges() == arraySize - 1, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); ASSERT(graph.insertEdge(iarray + 1, iarray + 2), "insertEdge() failed"); ASSERT(graph.howManyEdges() == arraySize, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); ASSERT(graph.removeVertex(iarray + 1), "removeVertex() failed"); ASSERT(graph.howManyEdges() == arraySize - 2, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize - 1, "howManyVertexes() failed"); for (int i = 2; i < arraySize; i++) ASSERT(!graph.removeEdge(iarray, narray + i), "removeEdge() failed"); ASSERT(graph.howManyEdges() == arraySize - 2, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize - 1, "howManyVertexes() failed"); for (int i = 2; i < arraySize; i++) ASSERT(graph.removeEdge(iarray, iarray + i), "removeEdge() failed"); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize - 1, "howManyVertexes() failed"); graph.destroy(); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); cout << " PASSED\n"; } int summation(int n) { int acc = 0; for (; n; n--) acc += n; return acc; } void testGetMethods(Graph& graph) { cout << " Get Methods Test: "; const int arraySize = 10; int iarray[arraySize] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(graph.insertVertex(iarray + i), "insertVertex() failed in loop: " << i); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); for (int j = 0; j < arraySize - 1; j++) for (int i = j + 1; i < arraySize; i++) ASSERT(graph.insertEdge(iarray + j, iarray + i), "insertVertex() failed in loop: " << j << ", " << i); ASSERT(graph.howManyEdges() == summation(arraySize - 1), "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); List list; ASSERT(graph.getVertexesList(&list), "getVertexesList() failed"); ASSERT(list.getSize() == arraySize, "getSize() failed"); for (int i = 0; i < arraySize; i++) ASSERT(list.getElementByData(iarray + i), "getElementByData() failed"); list.destroy(); for (int i = 0; i < arraySize; i++) { ASSERT(graph.getAdjacencyList(iarray + i, &list), "getAdjacencyList() failed"); ASSERT(list.getSize() == arraySize - i - 1, "getSize() failed in loop: " << i); for (int j=i+1; j < arraySize; j++) ASSERT(list.getElementByData(iarray+j), "getElementByData() failed in loop: " << i << ", " << j); list.destroy(); } graph.destroy(); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); cout << " PASSED\n"; } void testDestroy(Graph& graph) { cout << " Constructor Test: "; const int arraySize = 10; int iarray[arraySize] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); for (int i = 0; i < arraySize; i++) ASSERT(graph.insertVertex(iarray + i), "insertVertex() failed in loop: " << i); ASSERT(graph.howManyEdges() == 0, "howManyEdges() failed"); ASSERT(graph.howManyVertexes() == arraySize, "howManyVertexes() failed"); static int sum = 0; graph.destroyFunc = [](void* data) { int* d = (int*)data; sum += *d; }; ASSERT(sum == 0, "sum should be 0"); graph.destroy(); ASSERT(graph.howManyVertexes() == 0, "howManyVertexes() failed"); ASSERT(sum == summation(arraySize), "destroy() failed"); cout << " PASSED\n"; }
true
912a895f6f585e9f3b1da7c2b108eb374f850396
C++
NavyaaSharma/January-leetcode-challenge
/Sort the Matrix Diagonally.cpp
UTF-8
1,053
2.84375
3
[]
no_license
#### PROBLEM LINK //https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3614/ #### SOLUTION class Solution { public: vector<vector<int>> diagonalSort(vector<vector<int>>& mat) { int m=mat.size(); int n=mat[0].size(); for(int i=m-1;i>=0;i--) { vector<int>v; for(int j=i,k=0;j<m && k<n;j++,k++) { v.push_back(mat[j][k]); } sort(v.begin(),v.end()); for(int j=i,k=0;j<m && k<n;j++,k++) { mat[j][k]=v[k]; } } for(int j=1;j<n;j++) { vector<int>v; for(int i=0,k=j;i<m && k<n;i++,k++) { v.push_back(mat[i][k]); } sort(v.begin(),v.end()); for(int i=0,k=j;i<m && k<n;i++,k++) { mat[i][k]=v[i]; } } return mat; } };
true
22eeb36dd1554af717cab4ff604e7781f32d6343
C++
devcbandung/clashofcode-testdata-and-solution
/devc-meetup-venue/spec.cpp
UTF-8
7,370
2.671875
3
[ "MIT" ]
permissive
#include <tcframe/spec.hpp> #include <cassert> using namespace tcframe; class DSU { public: DSU(int n): p(vector<int>(n+1)), n(n) { for (int i = 1; i <= n; ++i) { p[i] = i; } } int findSet(int x) { return p[x] == x ? x : p[x] = findSet(p[x]); } void mergeSet(int x, int y) { p[findSet(x)] = findSet(y); } bool isSameSet(int x, int y) { return findSet(x) == findSet(y); } private: vector<int> p; int n; }; class ProblemSpec : public BaseProblemSpec { protected: std::vector<std::string> maze; int N, AR, AC, MR, MC; std::string ans; void InputFormat() { LINE(N); LINE(AR, AC, MR, MC); LINES(maze) % SIZE(N); } void OutputFormat() { LINE(ans); } void GradingConfig() { TimeLimit(2); MemoryLimit(512); } void Constraints() { CONS(1 <= N && N <= 100); CONS(1 <= AR && AR <= N); CONS(1 <= AC && AC <= N); CONS(1 <= MR && MR <= N); CONS(1 <= MC && MC <= N); CONS(validMaze(maze, N)); } bool validMaze(const vector<string>& m, int n) { if (m.size() != n) return false; for (const string& l : m) { if (l.size() != n) return false; for (char c : l) { if (c != '.' && c != '#') return false; } } return true; } }; class TestSpec : public BaseTestSpec<ProblemSpec> { protected: void TestCases() { // Samples CASE(N = 4, AR = 2, AC = 3, MR = 4, MC = 1, maze = { "....", ".#..", ".##.", "...." } ); CASE(N = 4, AR = 2, AC = 3, MR = 4, MC = 1, maze = { "..#.", ".#..", ".##.", "...#" } ); // Test Cases // TC1: N = 10, hardcoded ok CASE(N = 10, AR = 1, AC = 9, MR = 4, MC = 1, maze = { "#...#..#..", "..#..#..#.", ".#.#..#.#.", ".#..#.#...", "##.##..#.#", "...#..#...", ".#.#.#.##.", "...#.#....", "..#...###.", "#...#....." } ); // TC2: N = 10, hardcoded tersesat CASE(N = 10, AR = 1, AC = 2, MR = 2, MC = 3, maze = { "..##.#....", ".#.....##.", "..#.###...", "#..#...#.#", ".#...#.#..", "..#.#..##.", "#..#...#..", "..#..##.#.", ".#.##...#.", "......#..." } ); // TC3: N = 35, scattered CASE(N = 35, scattered()); // TC4: N = 100, scattered CASE(N = 100, scattered()); // TC5: N = 99, snake CASE(N = 99, snake(false)); // TC6: N = 99, snake, tersesat CASE(N = 99, snake(true)); // TC7: N = 99, MST CASE(N = 99, mst(false, 0)); // // TC8: N = 99, MST, tersesat CASE(N = 99, mst(true, 0)); // // TC9: N = 71, MST with holes CASE(N = 71, mst(false, 15)); // TC10: N = 99, MST with holes CASE(N = 99, mst(false, 49)); } void reset() { maze.clear(); string line = ""; for (int i = 0; i < N; ++i) { line += "."; } for (int i = 0; i < N; ++i) { maze.push_back(line); } } void scattered() { reset(); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { if (rnd.nextDouble(1.) < 0.35) { maze[i][j] = '#'; } } } AR = rnd.nextInt(1, N); AC = rnd.nextInt(1, N); while (maze[AR-1][AC-1] == '#') { AR = rnd.nextInt(1, N); AC = rnd.nextInt(1, N); } MR = rnd.nextInt(1, N); MC = rnd.nextInt(1, N); while (maze[MR-1][MC-1] == '#' || (AR == MR && AC == MC)) { MR = rnd.nextInt(1, N); MC = rnd.nextInt(1, N); } } void snake(bool blocked) { reset(); for (int i = 1; i < N; i += 2) { for (int j = 0; j < N; ++j) { maze[i][j] = '#'; } } for (int i = 1; i < N; i += 4) { maze[i][N-1] = '.'; } for (int i = 3; i < N; i += 4) { maze[i][0] = '.'; } AR = AC = 1; MR = MC = N; if (N % 4 == 3) { MC = 1; } if (blocked) { int rblocked = N / 2; if (rblocked % 2) rblocked++; maze[rblocked][rnd.nextInt(N)] = '#'; } } void mst(bool blocked, int holes) { reset(); vector<pair<int, int>> edges; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { if ((i % 2 == 1) || (j % 2 == 1)) { maze[i][j] = '#'; if ((j % 2) == 0 && i+1 < N) { edges.emplace_back(N * (i-1) + j, N * (i+1) + j); } if ((i % 2) == 0 && j+1 < N) { edges.emplace_back(N * i + j-1, N * i + j+1); } } } } rnd.shuffle(edges.begin(), edges.end()); DSU dsu(N*N); vector<pair<int, int>> unused; for (pair<int, int> edge : edges) { int ar = edge.first / N; int ac = edge.first % N; int br = edge.second / N; int bc = edge.second % N; if (!dsu.isSameSet(edge.first, edge.second)) { dsu.mergeSet(edge.first, edge.second); maze[(ar + br) / 2][(ac + bc) / 2] = '.'; } else { unused.emplace_back((ar + br) / 2, (ac + bc) / 2); } } // find longest diameter int start = findFurthestDescendant(0); AR = start / N + 1; AC = start % N + 1; int end = findFurthestDescendant(start); MR = end / N + 1; MC = end % N + 1; if (blocked) { vector<int> p = findPath(start, end); int iblocked = p.size() / 2 + rnd.nextInt(-3, 3); int rblocked = p[iblocked]/N; int cblocked = p[iblocked]%N; maze[rblocked][cblocked] = '#'; } else if (holes > 0) { rnd.shuffle(unused.begin(), unused.end()); for (int i = 0; i < holes; ++i) { assert(maze[unused[i].first][unused[i].second] == '#'); maze[unused[i].first][unused[i].second] = '.'; } } } vector<int> findPath(int start, int end) { queue<int> q; map<int, bool> v; map<int, int> p; q.push(end); v[end] = true; while (!q.empty()) { int x = q.front(); q.pop(); if (x == start) break; int r = x/N; int c = x%N; if (maze[r][c] == '#') continue; if (r > 0 && !v[x-N]) { q.push(x-N); v[x-N] = true; p[x-N] = x; } if (r < N-1 && !v[x+N]) { q.push(x+N); v[x+N] = true; p[x+N] = x; } if (c > 0 && !v[x-1]) { q.push(x-1); v[x-1] = true; p[x-1] = x; } if (c < N-1 && !v[x+1]) { q.push(x+1); v[x+1] = true; p[x+1] = x; } } vector<int> res; if (!v[start]) return res; res.push_back(start); while (start != end) { start = p[start]; res.push_back(start); } return res; } int findFurthestDescendant(int c) { vector<int> depth(N*N); for (int i = 0; i < N*N; ++i) { depth[i] = -1; } dfs(c/N, c%N, 0, depth); int maxDepth = -1, ans = 0; for (int i = 0; i < N*N; ++i) { if (depth[i] > maxDepth) { maxDepth = depth[i]; ans = i; } } return ans; } void dfs(int r, int c, int d, vector<int> &depth) { if (r < 0 || r == N) return; if (c < 0 || c == N) return; if (maze[r][c] == '#') return; if (depth[r*N + c] != -1) return; depth[r*N + c] = d; dfs(r+1, c, d+1, depth); dfs(r-1, c, d+1, depth); dfs(r, c+1, d+1, depth); dfs(r, c-1, d+1, depth); } };
true
d39a921eff06acf6443dd0a6acbbdfa845862926
C++
siggame/MegaMinerAI-12
/testClients/hannaClient/UnitType.h
UTF-8
1,154
2.859375
3
[]
no_license
// -*-c++-*- #ifndef UNITTYPE_H #define UNITTYPE_H #include <iostream> #include "structures.h" ///Represents type of unit. class UnitType { public: void* ptr; UnitType(_UnitType* ptr = NULL); // Accessors ///Unique Identifier int id(); ///The name of this type of unit. char* name(); ///The UnitType specific id representing this type of unit. int type(); ///The oxygen cost to spawn this unit type into the game. int cost(); ///The power of the attack of this type of unit. int attackPower(); ///The power of this unit types's digging ability. int digPower(); ///The power of this unit type's filling ability. int fillPower(); ///The maximum amount of this health this unit can have int maxHealth(); ///The maximum number of moves this unit can move. int maxMovement(); ///The power of the unit type's offensive siege ability. int offensePower(); ///The power of the unit type's defensive siege ability. int defensePower(); ///The range of the unit type's attack. int range(); // Actions // Properties friend std::ostream& operator<<(std::ostream& stream, UnitType ob); }; #endif
true
37f28c3a234dee1f132a14090e1529e38080b207
C++
z-rui/nbuf
/example/my_game_pb.cc
UTF-8
1,489
2.78125
3
[]
no_license
#include "my_game.pb.h" #include <cassert> #include <cstdio> #include <sstream> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> void save(std::ostream *os) { my_game::Hero x; my_game::Item *it; x.set_name("n37h4ck"); x.set_gender(my_game::FEMALE); x.set_race(my_game::ELF); x.set_hp(1337); x.set_mana(42); it = x.add_inventory(); it->set_name("quarterstaff"); it->set_quantity(1); it->set_corroded(true); it = x.add_inventory(); it->set_name("cloak of magic resistance"); it->set_quantity(1); it->set_buc(my_game::BLESSED); it = x.add_inventory(); it->set_name("wand of wishing"); it = x.add_inventory(); it->set_name("orchish helmet"); it->set_quantity(1); it->set_buc(my_game::CURSED); it->set_enchantment(-4); google::protobuf::io::OstreamOutputStream s(os); x.SerializeToZeroCopyStream(&s); } void dump(const std::string& s) { FILE *f = popen("xxd", "w"); fwrite(s.data(), 1, s.size(), f); pclose(f); } void load(std::istream *is) { my_game::Hero x; { google::protobuf::io::IstreamInputStream s(is); x.ParseFromZeroCopyStream(&s); } { google::protobuf::io::OstreamOutputStream s(&std::cout); google::protobuf::TextFormat::Print(x, &s); } assert(x.hp() == 1337); } int main() { std::stringstream ss; save(&ss); /* write something into the buffer */ dump(ss.str()); /* show the buffer content */ load(&ss); /* read back from the buffer */ google::protobuf::ShutdownProtobufLibrary(); }
true
acc1d7f61bfe729609614ed1e4fd5d51b9b06b03
C++
TTgogogo/Android-App-Profiling
/apprepo/i-team-video_segment/imagefilter/nnf.h
UTF-8
2,216
2.546875
3
[]
no_license
/* * nnf.h * ImageFilterLib * * Created by Matthias Grundmann on 5/24/09. * Copyright 2009 Matthias Grundmann. All rights reserved. * */ // Computation of nearest neighborfield // Based on: Connelly Barnes, Eli Shechtman, Adam Finkelstein, Dan B Goldman // PatchMatch: A Randomized Correspondence Algorithm for Structural Image Editing, // SIGGRAPH 2009 #ifndef NNF_H__ #define NNF_H__ #include <opencv2/core/core_c.h> #include <vector> using std::vector; #include <boost/array.hpp> namespace ImageFilter { // Computes the nearest neighbor field for image src w.r.t the image ref. // Output is an offset field of size [src.width() - 2 * patch_rad, src.height() - 2 * patch_rad] // The offset field is specified by // a) offset: for each location i in src the closest patch in ref is ref[i + offset[i]] // (must be matrix of type int) // b) ptr: for each location i in src the closest patch in ref is ptr[i] // Pass zero to any output that is not required by the caller. // Maximum supported patch size is 80 pixels. // Beyond that overflow in internal structures occurs. void ComputeNNF(const IplImage* src, const IplImage* ref, int patch_rad, int iterations, CvMat* offset, vector<const uchar*>* offset_vec, CvMat* min_values); // Variant of the above function for feature descriptor representation (e.g. SIFT). // Output offset is required, min_values is optional. typedef boost::array<float, 128> SIFT_DESC; void ComputeNNF(const int src_width, const int src_height, const vector<SIFT_DESC>& src, const int ref_width, const int ref_height, const vector<SIFT_DESC>& ref, const int patch_rad, int iterations, CvMat* offset, CvMat* min_values = 0); // Creates Image from nearest neighor void AveragePatches(const IplImage* ref, const vector<const uchar*>& offset, int patch_rad, CvMat* min_values, IplImage* output); } #endif // NNF_H__
true
997f9990f773c01f4a24e8abb13fd4462e28e9bb
C++
in0x/FinalFrontier
/src/Renderer.cpp
UTF-8
1,383
3.015625
3
[]
no_license
#include "stdafx.h" #include "Renderer.h" Renderer::Renderer(RenderTarget* t) { target = t; } Renderer::~Renderer() { for (auto layer : layers) delete layer; } void Renderer::clear() { for (auto layer : layers) delete layer; layers.clear(); } void Renderer::addLayer(int index) { if (index == -1) layers.push_back(new LayerComponent()); /*else if (index > layers.size()) { layers.push_back(new LayerComponent()); }*/ else { layers.insert(layers.begin() + index, new LayerComponent()); } } void Renderer::removeLayer(int index) { delete layers[index]; layers.erase(layers.begin() + index); } void Renderer::registerRenderComponent(RenderComponent* rc, int layerIndex) { layers[layerIndex]->tiles.push_back(rc); View view = target->getView(); rc->setView(view.getCenter(), view.getSize()); } void Renderer::draw() { for (auto* var : layers) { View view = target->getView(); var->setView(view.getCenter(), view.getSize()); target->draw(*var); } } void Renderer::unregisterRenderComponent(RenderComponent * rc, int layerIndex) { std::vector<RenderComponent*>& layer = layers[layerIndex]->tiles; std::vector<RenderComponent*>::iterator it; for (it = layer.begin(); it != layer.end(); it++) { if (*it == rc) break; } if (*it != rc) { std::cout << "Could not find element to delete" << std::endl; return; } layer.erase(it); }
true
082aec03ed4bb1ee206eef071c1752d3b6fe506f
C++
MattiaCossu89/CPP
/4/ex01/Character.hpp
UTF-8
1,484
2.640625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Character.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mcossu <mcossu@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/06 15:07:21 by mcossu #+# #+# */ /* Updated: 2021/05/06 15:07:22 by mcossu ### ########.fr */ /* */ /* ************************************************************************** */ #pragma once #define str std::string #define o_stream std::ostream #include "AWeapon.hpp" #include "Enemy.hpp" #include <iostream> #include <string> class Character { private: str name; int AP; AWeapon *weap; public: Character(std::string const & name); Character(const Character &copy); virtual ~Character(); Character &operator=(const Character &copy); void recoverAP(); void equip(AWeapon*); void attack(Enemy*); str const &getName() const; int getAP() const; const AWeapon *getWeapon() const; }; std::ostream &operator<<(std::ostream &os, const Character &c);
true
d97a11709c7ea805d255aee4d376eecf9d3f3246
C++
gkUwen/rodent
/src/driver/tri.h
UTF-8
2,070
3.359375
3
[ "MIT" ]
permissive
#ifndef TRI_H #define TRI_H #include "float3.h" #include "bbox.h" struct Tri { float3 v0, v1, v2; Tri() {} Tri(const float3& v0, const float3& v1, const float3& v2) : v0(v0), v1(v1), v2(v2) {} float3& operator[] (int i) { return i == 0 ? v0 : (i == 1 ? v1 : v2); } const float3& operator[] (int i) const { return i == 0 ? v0 : (i == 1 ? v1 : v2); } float area() const { return length(cross(v1 - v0, v2 - v0)) / 2; } /// Computes the triangle bounding box. void compute_bbox(BBox& bb) const { bb.min = min(v0, min(v1, v2)); bb.max = max(v0, max(v1, v2)); } /// Splits the triangle along one axis and returns the resulting two bounding boxes. void compute_split(BBox& left_bb, BBox& right_bb, int axis, float split) const { left_bb = BBox::empty(); right_bb = BBox::empty(); const float3& e0 = v1 - v0; const float3& e1 = v2 - v1; const float3& e2 = v0 - v2; const bool left0 = v0[axis] <= split; const bool left1 = v1[axis] <= split; const bool left2 = v2[axis] <= split; if (left0) left_bb.extend(v0); if (left1) left_bb.extend(v1); if (left2) left_bb.extend(v2); if (!left0) right_bb.extend(v0); if (!left1) right_bb.extend(v1); if (!left2) right_bb.extend(v2); if (left0 ^ left1) { const float3& p = clip_edge(axis, split, v0, e0); left_bb.extend(p); right_bb.extend(p); } if (left1 ^ left2) { const float3& p = clip_edge(axis, split, v1, e1); left_bb.extend(p); right_bb.extend(p); } if (left2 ^ left0) { const float3& p = clip_edge(axis, split, v2, e2); left_bb.extend(p); right_bb.extend(p); } } private: static float3 clip_edge(int axis, float plane, const float3& p, const float3& edge) { const float t = (plane - p[axis]) / (edge[axis]); return p + t * edge; } }; #endif // TRI_H
true
b0aa2e7ec92c2ebf6589a19ae9d200913c9b5cf1
C++
verdande2/CST211-Spring-12
/Assignment 11/Assignment 11/main.cpp
UTF-8
3,099
3.1875
3
[]
no_license
/*********************************************************** * Author: Andrew Sparkes * Title: CST 211 Assignment 11 * Filename: main.cpp * Date Created: 5-24-12 * Modified: 5-26-12 : documentation, small tweaks * * Overview: * This program is a driver demonstrating the basic * capabilities of a undirected graph class * * Input: * None. * * Output: * Will output a basic test of the class to console. ************************************************************/ #include <iostream> using std::cout; using std::endl; #include "UndirectedGraph.h" #include <string> using std::string; #include <crtdbg.h> #define _CRTDBG_MAP_ALLOC template <class T> void Print(T& data); int main() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); cout << "Making a graph with string type data and double type weights..." << endl; UndirectedGraph<string, string, double> myGraph; /* myGraph.InsertEdge("Klamath Falls, OR", "Medford, OR", "Edge Description Here", 76.8); myGraph.InsertEdge("Klamath Falls, OR", "Eugene, OR", "Edge Description Here", 173.0); myGraph.InsertEdge("Klamath Falls, OR", "Bend, OR", "Edge Description Here", 137.0); myGraph.InsertEdge("Medford, OR", "Eugene, OR", "Edge Description Here", 167.0); myGraph.InsertEdge("Eugene, OR", "Salem, OR", "Edge Description Here", 66.3); myGraph.InsertEdge("Salem, OR", "Portland, OR", "Edge Description Here", 47.1); myGraph.InsertEdge("Bend, OR", "Salem, OR", "Edge Description Here", 132.0); myGraph.InsertEdge("Eugene, OR", "Bend, OR", "Edge Description Here", 128.0); myGraph.InsertEdge("Bend, OR", "Portland, OR", "Edge Description Here", 162.0); */ myGraph.ForceInsertEdge("A", "B", "A<->B", 1); myGraph.ForceInsertEdge("B", "C", "B<->C", 1); myGraph.ForceInsertEdge("C", "A", "C<->A", 1); myGraph.ForceInsertEdge("D", "A", "D<->A", 1); myGraph.ForceInsertEdge("D", "E", "D<->E", 1); myGraph.ForceInsertEdge("A", "E", "A<->E", 1); cout << endl << "Outputting graph:" << endl; cout << "BreadthFirstTraversal:" << endl; myGraph.BreadthFirstTraversal(&Print<string>); cout << "DepthFirstTraversal:" << endl; myGraph.DepthFirstTraversal(&Print<string>); UndirectedGraph<string, string, double> test; test = myGraph; cout << endl << "Outputting assigned graph:" << endl; cout << "BreadthFirstTraversal:" << endl; test.BreadthFirstTraversal(&Print<string>); cout << "DepthFirstTraversal:" << endl; test.DepthFirstTraversal(&Print<string>); UndirectedGraph<string, string, double> copy(test); cout << endl << "Outputting copy constructed graph:" << endl; cout << "BreadthFirstTraversal:" << endl; copy.BreadthFirstTraversal(&Print<string>); cout << "DepthFirstTraversal:" << endl; copy.DepthFirstTraversal(&Print<string>); cout << "Removing B Node" << endl; myGraph.DeleteNode(string("B")); myGraph.BreadthFirstTraversal(&Print<string>); cout << "Removing Edge from A to E" << endl; myGraph.DeleteEdge(string("A"), string("E")); myGraph.BreadthFirstTraversal(&Print<string>); system("pause"); return 0; } template <class T> void Print(T& data) { cout << data << endl; }
true
9b50c680071e43087783f90e4fd0d734ded3e534
C++
xobe19/CP-Learning
/merge_sort.cpp
UTF-8
1,066
2.859375
3
[]
no_license
#include <iostream> #include <bits/stdc++.h> using namespace std; vector<int> merge(vector<int> &a, vector<int> &b) { auto it1 = a.begin(); auto it2 = b.begin(); vector<int> sorted; while(it1 != a.end() && it2 != b.end()) { if(*it1 < *it2) { sorted.push_back(*it1); it1++; } else { sorted.push_back(*it2); it2++; } } while(it1 != a.end()) { sorted.push_back(*it1); it1++; } while(it2 != b.end()) { sorted.push_back(*it2); it2++; } return sorted; } vector<int> f(vector<int> &a) { if(a.size() <= 1) return a; int mid = a.size()/2; auto nons1 = vector<int>(a.begin(), a.begin() + mid); auto nons2 = vector<int>(a.begin() + mid, a.end()); auto sorted1 = f(nons1); auto sorted2 = f(nons2); return merge(sorted1, sorted2); } int main() { int n; cin >> n; vector<int> d; for(int i = 0; i < n; i++) { int t; cin >> t; d.push_back(t); } vector<int> fin = f(d); for(int a: fin) { std::cout << a; } return 0; }
true
f7a3f24b8150440c53a0075b4117b98751815fc2
C++
SaiSree-0517/becomecoder
/combinations.cpp
UTF-8
690
3.34375
3
[]
no_license
#include <iostream> using namespace std; void getCombinations(int arr[], int index, int num, int reducedNum) { if (reducedNum < 0) return; if (reducedNum == 0) { for (int i = 0; i < index; i++) { cout << arr[i] << " "; } cout << endl; return; } int prev = (index == 0)? 1 : arr[index-1]; for (int k = prev; k <= num ; k++) { arr[index] = k; getCombinations(arr, index + 1, num, reducedNum - k); } } void findCombinations(int n) { int arr[n]; getCombinations(arr, 0, n, n); } int main() { int n; cin>>n; findCombinations(n); return 0; }
true
ac4c7c1e99b12fb73a063af2fc86e9731657ab59
C++
Randool/Algorithm
/DP/最优矩阵链乘.cpp
UTF-8
885
2.734375
3
[]
no_license
#include <cstdio> #include <cstring> #include <iostream> #define MAXN 55 #define INF 0x3f3f3f3f typedef long long LL; using namespace std; int n; int mat[MAXN]; int G[MAXN][MAXN]; void MatrixChain(int n, int* mat) { memset(G, 0, sizeof(G)); for (int l=2; l<=n; ++l) { for (int i=1; i<=n; ++i) { int j = i + l - 1; int tmp = INF; for (int k=i; k<j; ++k) { tmp = min(tmp, G[i][k] + G[k+1][j] + mat[i-1] * mat[k] * mat[j]); } G[i][j] = tmp; } } } void Show(int n) { for (int i=1; i<=n; ++i) { for (int j=1; j<=n; ++j) { if (j >= i) printf("%5d ", G[i][j]); else printf("%5d ", 0); } printf("\n"); } } int main() { //freopen("in.txt", "r", stdin); /* 6 30 35 15 5 10 20 25 */ scanf("%d", &n); for (int i=1; i<=n+1; i++) scanf("%d", &mat[i]); MatrixChain(n, mat); printf("Optimization : %d\n", G[1][n]); Show(n); return 0; }
true
e1db47a5e56eea5cb4ebc33a6490703c46d7ff1b
C++
msDikshaGarg/Images-and-Morphological-Operators
/src/Image.h
UTF-8
1,014
2.734375
3
[]
no_license
#include<iostream> #include<fstream> #include<string> #include<cmath> using namespace std; typedef struct Pixel { unsigned char rgb[3]; }; struct PPM { Pixel* mPixels = nullptr; char mType[3]; unsigned int mRows; unsigned int mColumns; unsigned int size; unsigned int mMaxValue; }; PPM load(const string fileName); PPM load1(const string fileName); class Image { public: PPM ppmFile; Image operator+ (const Image& ppmFile); Image operator+= (const Image& ppmFile); Image operator- (const Image& ppmFile); Image operator-= (const Image& ppmFile); Image operator* (const float m); Pixel& operator[] (int i); Image gamma(const float gamma); Image applyGamma(const float val, const float maxValue); Image alpha(const float alpha, const Image& img); Image applyAlpha(const float alpha, const Image& img); void save(const string fileName); //PPM * generate (const string & fileName) };
true
560ace31bd68713a3b71460cbfc5a6092fc4a5d0
C++
shiLinwong/workspace
/QtGuiExamples/MultiScreen/main.cpp
UTF-8
2,195
2.5625
3
[]
no_license
#include "mainwindow.h" #include <QApplication> #include <QTextCodec> #include <QDesktopWidget> #include <QMainWindow> #include <QDebug> typedef struct{ int screen_no; QRect rect; }SCREEN; int main(int argc, char *argv[]) { QApplication a(argc, argv); QDesktopWidget *desktop = QApplication::desktop(); int screen_count = desktop->screenCount();//获取当前屏幕个数 int prim_screen = desktop->primaryScreen();//获取主屏幕的索引序号 int desktop_width = desktop->width();//获取虚拟屏幕全宽,是获取的总宽度,对于横向扩展屏来说,也就是 屏幕1+ 屏幕2 + ...n 的宽度 int desktop_height = desktop->height(); //获取虚拟屏幕全高 qDebug()<<"screen_count = "<<screen_count; qDebug()<<"prim_screen = "<<prim_screen; qDebug()<<"desktop_width = "<<desktop_width; qDebug()<<"desktop_height = "<<desktop_height; // MainWindow wd[screen_count]; MainWindow *wd = new MainWindow[screen_count]; QRect rect; for(int i = 0 ; i < screen_count; i++){ rect = desktop->screenGeometry(prim_screen + i); //整个屏幕的矩形区域 rect = desktop->availableGeometry(prim_screen + i);//当前屏幕的可用部分 int scrren_width = rect.width(); int screen_height = rect.height(); int offsetX = rect.x(); int offsetY = rect.y(); qDebug()<<"offsetX = "<<offsetX; // qDebug()<<"offsetY = "<<offsetY; qDebug()<<"Current Screen is "<<prim_screen + i<<"; screen width = "<<scrren_width<<"; screen height = "<<screen_height; if(i == 0){ wd[i].move(0,0); }else{ wd[i].move(offsetX,offsetY); // wd[i].move(desktop->screenGeometry(prim_screen+i-1).width(),0); } wd[i].setWindowTitle(QString::fromLocal8Bit("屏幕")+QString::number(i)); // wd[i].setScreenSize(0,0,scrren_width,screen_height); // wd[i].setScreenIndex(prim_screen + i); // wd[i].setWindowFlags( Qt::FramelessWindowHint); wd[i].showMaximized(); // wd[i].resize(scrren_width,screen_height); wd[i].show(); } return a.exec(); }
true
112783baee4458b9075b9c062a9b7d3db63798bf
C++
mrdepth/libdgmpp
/src/Character.hpp
UTF-8
4,090
2.75
3
[ "MIT" ]
permissive
// // Character.hpp // dgmpp // // Created by Artem Shimanski on 16.11.2017. // #pragma once #include "Skill.hpp" #include "Structure.hpp" #include "Ship.hpp" #include "Implant.hpp" #include "Booster.hpp" namespace dgmpp { class Character: public Type { public: Character(); Character (const Character& other); virtual ~Character(); const std::string& name() const noexcept { LOCK(this); return name_(); } template<typename T> void name (T&& name) noexcept { LOCK(this); name_(std::forward<T>(name)); } std::shared_ptr<Ship> ship() const { LOCK(this); return ship_(); } void ship (const std::shared_ptr<Ship>& ship) { LOCK(this); return ship_(ship); } void setSkillLevels (int level) { LOCK(this); setSkillLevels_(level); } void add(const std::shared_ptr<Implant>& implant, bool replace = false) { LOCK(this); add_(implant, replace); } void add(const std::shared_ptr<Booster>& booster, bool replace = false) { LOCK(this); add_(booster, replace); } // Implant* addImplant(TypeID typeID, bool replace = false) { return add(Implant::Create(typeID), replace); } // Booster* addBooster(TypeID typeID, bool replace = false) { return add(Booster::Create(typeID), replace); } void remove(Implant* implant) { LOCK(this); remove_(implant); } void remove(Booster* booster) { LOCK(this); remove_(booster); } std::vector<std::shared_ptr<Skill>> skills() const { LOCK(this); return skills_(); } std::vector<std::shared_ptr<Implant>> implants() const { LOCK(this); return implants_(); } std::vector<std::shared_ptr<Booster>> boosters() const { LOCK(this); return boosters_(); } std::shared_ptr<Implant> implant (Implant::Slot slot) const noexcept { LOCK(this); return implant_(slot); } std::shared_ptr<Booster> booster (Booster::Slot slot) const noexcept { LOCK(this); return booster_(slot); } Meter droneControlDistance() { LOCK(this); return droneControlDistance_(); } protected: virtual void setEnabled_ (bool enabled) override; virtual Type* domain_ (MetaInfo::Modifier::Domain domain) noexcept override; virtual void reset_() override; private: struct SlotCompare { template <typename A, typename B, typename = decltype(std::declval<A>()->slot()), typename = decltype(std::declval<B>()->slot())> bool operator() (const A& a, const B& b) const noexcept { return a->slot() < b->slot(); } template <typename T, typename K, typename = std::enable_if_t<std::is_same_v<K, decltype(std::declval<T>()->slot())>>> bool operator() (const T& a, K b) const noexcept { return a->slot() < b; } template <typename T, typename K, typename = std::enable_if_t<std::is_same_v<K, decltype(std::declval<T>()->slot())>>> bool operator() (K a, const T& b) const noexcept { return a < b->slot(); } typedef void is_transparent; }; friend class Gang; friend class Ship; std::shared_ptr<Ship> shipValue_; std::map<TypeID, std::shared_ptr<Skill>> skillsMap_; std::set<std::shared_ptr<Implant>, SlotCompare> implantsSet_; std::set<std::shared_ptr<Booster>, SlotCompare> boostersSet_; std::string nameValue_; bool factorReload_() const noexcept; const std::string& name_() const noexcept { return nameValue_; } template<typename T> void name_ (T&& name) noexcept { nameValue_ = std::forward<T>(name); } std::shared_ptr<Ship> ship_() const { return shipValue_; } void ship_ (const std::shared_ptr<Ship>& ship); void setSkillLevels_ (int level); void add_(const std::shared_ptr<Implant>& implant, bool replace = false); void add_(const std::shared_ptr<Booster>& booster, bool replace = false); void remove_(Implant* implant); void remove_(Booster* booster); std::vector<std::shared_ptr<Skill>> skills_() const; std::vector<std::shared_ptr<Implant>> implants_() const; std::vector<std::shared_ptr<Booster>> boosters_() const; std::shared_ptr<Implant> implant_ (Implant::Slot slot) const noexcept; std::shared_ptr<Booster> booster_ (Booster::Slot slot) const noexcept; Meter droneControlDistance_(); }; }
true
72cf07064870cdcc820080d66981837957bb4a0e
C++
genius52/leetcode
/src/cpp/list/707. Design Linked List.hpp
UTF-8
3,398
4.15625
4
[]
no_license
struct Listnode{ int val = 0; Listnode* next = nullptr; }; class MyLinkedList { Listnode* head = nullptr; Listnode* tail = nullptr; int size = 0; public: /** Initialize your data structure here. */ MyLinkedList() { } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ int get(int index) { if(index >= size) return -1; auto visit = head; while(index > 0){ visit = visit->next; index--; } return visit->val; } /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ void addAtHead(int val) { auto new_node = new Listnode(); new_node->val = val; new_node->next = head; head = new_node; size++; if(size == 1){ tail = head; } } /** Append a node of value val to the last element of the linked list. */ void addAtTail(int val) { auto new_node = new Listnode(); new_node->val = val; if(tail == nullptr){ head = new_node; tail = new_node; }else{ tail->next = new_node; tail = new_node; } size++; } /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ void addAtIndex(int index, int val) { if(index > size) return; if(index == size){//add tail auto new_node = new Listnode(); new_node->val = val; if(size == 0){//empty list head = new_node; }else{ tail->next = new_node; } tail = new_node; }else if(index < size){ if(index == 0){ auto new_node = new Listnode(); new_node->val = val; new_node->next = head; head = new_node; }else{ auto visit = head; Listnode* pre = nullptr; while(index > 0){ pre = visit; visit = visit->next; index--; } auto new_node = new Listnode(); new_node->val = val; new_node->next = visit; pre->next = new_node; } } size++; } /** Delete the index-th node in the linked list, if the index is valid. */ void deleteAtIndex(int index) { if(index >= size) return; int old_index = index; if(index == 0){ auto del = head; head = head->next; delete del; del = nullptr; }else{ auto visit = head; Listnode* pre = nullptr; while(index > 0){ pre = visit; visit = visit->next; index--; } pre->next = visit->next; delete visit; visit = nullptr; if(old_index == size - 1){ tail = pre; } } size--; } };
true
f7d3573b37fe8334efe490c1068ee0fd4fb9b6d7
C++
Dinngger/cpp_class
/complex.cpp
UTF-8
2,197
3.609375
4
[]
no_license
#include<iostream> using namespace std; class Complex{ double real, imag; public: Complex(){ } Complex(double real, double imag){ this->real = real; this->imag = imag; } Complex& operator=(const Complex& comp){ if(&comp != this){ this->real = comp.real; this->imag = comp.imag; } return *this; } Complex operator~() const{ return Complex(real, -imag); } friend const Complex operator+(const Complex& a, const Complex& b); friend const Complex operator-(const Complex& a, const Complex& b); friend const Complex operator*(const Complex& a, const Complex& b); friend const Complex operator*(const double x, const Complex& b); friend ostream& operator<<(ostream& out, const Complex& comp); friend istream& operator>>(istream& in, Complex& comp); }; const Complex operator+(const Complex& a, const Complex& b){ return Complex(a.real+b.real, a.imag+b.imag); } const Complex operator-(const Complex& a, const Complex& b){ return Complex(a.real-b.real, a.imag- b.imag); } const Complex operator*(const Complex& a, const Complex& b){ return Complex(a.real*b.real-a.imag*b.imag, a.real*b.imag+a.imag*b.real); } const Complex operator*(const double x, const Complex& b){ return Complex(x*b.real, x*b.imag); } ostream& operator<<(ostream& out, const Complex& comp){ out << '(' << comp.real << ',' << comp.imag << "i)"; return out; } istream& operator>>(istream& in, Complex& comp){ cout << "real:"; if(in >> comp.real){ cout << "imaginary:"; in >> comp.imag; } return in; } int main(){ Complex a(3.0, 4.0); Complex c; cout << "Enter a complex number (q to quit):\n"; while(cin >> c){ cout << "c is " << c << endl; cout << "complex conjugate is " << ~c << endl; cout << "a is " << a << endl; cout << "a + c is " << a + c << endl; cout << "a - c is " << a - c << endl; cout << "a * c is " << a * c << endl; cout << "2 * c is " << 2 * c << endl; cout << "Enter a complex number (q to quit):\n"; } cout << "Done!\n"; return 0; }
true
85cd9d2085f319e6406f8b162ce5737c78763013
C++
j0sht/csci160
/practice/fileio/e2.cpp
UTF-8
1,150
4.03125
4
[]
no_license
/* * Write a function that takes two filenames and an integer N as parameters, * attempts to open the first for reading and the second for writing, and * copies the first N characters of the first file into the second */ #include <cstdio> #include <cstdlib> void copyFirstN(const char *source, const char *dest, int n) { FILE *fpin; FILE *fpout; fpin = fopen(source, "r"); if (fpin == NULL) { printf("Couldn't open %s\n", source); return; } fpout = fopen(dest, "w"); if (fpout == NULL) { printf("Couldn't open %s\n", dest); fclose(fpin); return; } char c; for (int i = 0; (i < n) && (c != EOF); i++) if ((c=getc(fpin)) != EOF) fputc(c, fpout); if (c != '\n' && c != EOF) fputc('\n', fpout); fclose(fpin); fclose(fpout); } int main(int argc, char *argv[]) { if (argc != 3) { printf("Usage: %s <source file> <destination file>\n", argv[0]); exit(1); } int n; printf("Enter number of characters to copy: "); int res = scanf("%d", &n); if (res != 1) { printf("Not an integer\n"); exit(1); } copyFirstN(argv[1], argv[2], n); return 0; }
true
8bc421b95039509cd5467b430e5cc7073f43c8fa
C++
ForeStrikeGallery/old-C-
/Goodrich/arrays/minmaxdist.cpp
UTF-8
965
3.40625
3
[]
no_license
#include<iostream> #include<cstdlib> using namespace std; int max(int a, int b) { return a>b?a:b; } int min(int a, int b) { return a<b?a:b; } void insertion_sort(int *arr, int N) { for (int i=1; i<N; i++) { int j = i-1; int key = arr[i]; while (j >= 0 && arr[j] > key) { arr[ j + 1] = arr[j] j--; } arr[j + 1] = key; } } void insertionCount(int *arr, int N, int K) { insertion_sort(arr, N); int min, max; min = arr[0]; max = arr[N-1]; if (k > max - min) { for (int i=0; i<N; i++) { arr[i] += k; } return } int new_max = max(arr[0], arr[N-1]); int new_min = min(arr[0], arr[N-1]); for(int i=1; i<N-1; i++) { if (arr[i] < new_min) { arr[i] = arr[i] + k; } else if (arr[i] > new_max){ arr[i] -= k; } else if (dist(arr[i], new_min) > dist(arr[i], new_max) { arr[i] -= k; } else { arr[i] += k; } } } int main() { int arr = {1, 4,3,5 ,6}; int N = sizeof(arr)/sizeof(arr[0]); }
true
d3595245605e7ce6abf968cd533ebd880ce9a90d
C++
palezero/PAT
/pat_test_yi/1028.cpp
UTF-8
772
3.1875
3
[]
no_license
#include <iostream> #include <cstdio> #include <string> #include <algorithm> using namespace std; typedef struct { string name; short year; short month; short day; int date; }Group; bool cmp(Group g1, Group g2) { return g1.date < g2.date; } int main() { int num; int count = 0; cin>>num; Group people[num]; Group temp; int min = 18140906; int max = 20140906; for (int i = 0; i < num; ++i) { cin>>temp.name; scanf("%d/%d/%d", &temp.year, &temp.month, &temp.day); temp.date = temp.day + temp.month * 100 + temp.year * 10000; if(!(temp.date < min || temp.date > max)) people[count++] = temp; } sort(people, people+count, cmp); if(count > 0) cout<<count<<" "<<people[0].name<<" "<<people[count-1].name<<endl; else cout<<0<<endl; return 0; }
true
28232bd1d4954f9f4085b20405984ae7a875321c
C++
vivian-jq/AIFM
/aifm/inc/object.hpp
UTF-8
2,652
3
3
[ "MIT" ]
permissive
#pragma once #include <limits> namespace far_memory { // Forward declaration. template <typename T> class UniquePtr; class Object { // // Format: // |<------------------ header ------------------>| // |ptr_addr(6B)|data_len(2B)|ds_id(1B)|id_len(1B)|data|object_ID| // // ptr_addr: points to the corresponding far-mem pointer. During GC, // the collector uses the field to jump from Region to far-mem // pointer, and marks the far-mem pointer as absent from local // cache. // data_len: the length of object data. // ds_id: the data structure ID. // id_len: the length of object ID. // data: object data. // object_ID: the unique object ID which is used by the remote side to // locate the object during swapping in and swapping out. private: constexpr static uint32_t kPtrAddrPos = 0; constexpr static uint32_t kPtrAddrSize = 6; constexpr static uint32_t kDataLenPos = 6; constexpr static uint32_t kDSIDPos = 8; constexpr static uint32_t kIDLenPos = 9; // It stores the address of the object (which is stored in the local region). uint64_t addr_; public: constexpr static uint32_t kDSIDSize = 1; constexpr static uint32_t kIDLenSize = 1; constexpr static uint32_t kDataLenSize = 2; constexpr static uint32_t kHeaderSize = kPtrAddrSize + kDataLenSize + kDSIDSize + kIDLenSize; constexpr static uint16_t kMaxObjectSize = std::numeric_limits<uint16_t>::max(); constexpr static uint16_t kMaxObjectIDSize = (1 << (8 * kIDLenSize)) - 1; constexpr static uint16_t kMaxObjectDataSize = kMaxObjectSize - kHeaderSize - kMaxObjectIDSize; Object(); // Create a reference to the object at address addr. Object(uint64_t addr); // Initialize the object at address addr. Field ptr_addr is written by // far-mem pointer. Object(uint64_t addr, uint8_t ds_id, uint16_t data_len, uint8_t id_len, const uint8_t *id); void init(uint8_t ds_id, uint16_t data_len, uint8_t id_len, const uint8_t *id); uint64_t get_addr() const; uint16_t get_data_len() const; uint8_t get_obj_id_len() const; void set_ptr_addr(uint64_t address); const uint8_t *get_obj_id() const; uint64_t get_ptr_addr() const; uint64_t get_data_addr() const; void set_ds_id(uint8_t ds_id); uint8_t get_ds_id() const; void set_data_len(uint16_t data_len); void set_obj_id(const uint8_t *id, uint8_t id_len); void set_obj_id_len(uint8_t id_len); uint16_t size() const; bool is_freed() const; void free(); }; } // namespace far_memory #include "internal/object.ipp"
true
5149d2b687d390943bdc0252f6519f79101edc2a
C++
mcrossen/macattack
/logger.h
UTF-8
224
2.59375
3
[]
no_license
#pragma once #include <iostream> // simple class to handle log messages // log::verbose must be set to actually display the log class log { public: log(std::string module, std::string message); static bool verbose; };
true
f8cb4339aef9283f3e5114046108436b3d89b144
C++
heyuanzhen/PathTracer
/PathTracer/Utils/Sampler.h
UTF-8
1,374
2.671875
3
[]
no_license
// // Sampler.h // PathTracer // // Created by HYZ on 2018/2/3. // Copyright © 2018年 HYZ. All rights reserved. // #ifndef Sampler_h #define Sampler_h #include <eigen3/Eigen/Dense> #include "typeAlias.h" class Sampler{ protected: public: Sampler(); virtual ~Sampler(); //virtual double random1D() const; Point2d random2D() const; virtual void initializeSampler() = 0; virtual double get1D() = 0; virtual Point2d get2D() = 0; }; class StratifiedSampler : public Sampler { public: StratifiedSampler(const int _blocks); ~StratifiedSampler(); //clip input blocks to nearest n^2 (floor) void clipInputBlocks(); //initialize stratified sampler void initializeSampler(); //generate 2-D random number array void genRandNumArr2D(); //test if there are random number in array that is not used bool noNumRemains(); //get 1-D random number in array virtual double get1D(); //get 2-D random number in array virtual Point2d get2D(); private: int blocks; int blocksPerAxis; Point2d* randNumArr; int currentNumberIndex; }; class RandomSampler : public Sampler{ public: RandomSampler(); ~RandomSampler(); virtual void initializeSampler(); virtual double get1D(); virtual Point2d get2D(); }; #endif /* Sampler_h */
true
ebe83f96b794d300ae9050e8bfc5489946647814
C++
CZhang1997/BoundedQueue
/Main.cpp
UTF-8
519
3.015625
3
[ "MIT" ]
permissive
//Churong Zhang #include<iostream> using namespace std; #include"CircularQueue.h" void main() { //CircularQueue list; /*int size = 10; for(int a = 0; a < size; a++) { list.que(a+20); if(a%2 == 0) cout << list.deque() << " "; } cout << endl;*/ CircularQueue list (20); for (int b = 0; b < 20; b++) { list.que(b+10); } while (!list.isEmpty()) { cout << list.deque() << " "; } cout << endl << list.getHead() << " " << list.getTail() << endl; system("pause"); }
true
80175de22d469c72325f0d0be5994239247eef1a
C++
harshit12345677/LCA
/BST_LCA.cpp
UTF-8
1,591
3.890625
4
[]
no_license
#include<iostream> using namespace std; class Node { public: int data; Node *left; Node *right; Node(int d) { data = d; left = NULL; right = NULL; } }; class BST { public: Node* insertBST(Node* root, int data) { // Complete function to insert a node in the BST rooted at 'root' if(root==NULL) { Node *temp=new Node(data); root=temp; return root; } if(data>root->data) { root->right=insertBST(root->right,data); } else root->left=insertBST(root->left,data); return root; } Node *returnLCA(Node *root, int v1,int v2) { // Complete function to return pointer of LCA of v1 and v2 if(root==NULL) return NULL; if(root->data<v1&&root->data<v2) { return returnLCA(root->right,v1,v2); } else return returnLCA(root->left,v1,v2); return root; } }; int main() { // Loop to iterate over test cases BST myTree; Node* root = NULL; // Code to read input and insert node in BST int v1, v2; // Read v1 and v2 int t; cin>>t; int n; for(int i=0;i<t;i++) { cin>>n; int arr[n]; for(int j=0;j<n;j++) { cin>>arr[j]; root=myTree.insertBST(root,arr[j]); } cout<<root->left->data; } cin>>v1>>v2; Node *ans = myTree.returnLCA(root, v1, v2); cout << ans->data; }
true
22d5141b9f2b74fcd3ecf6511b91d8cf9370d079
C++
BieremaBoyzProgramming/bbpPairings
/src/matching/detail/rootblossomsig.h
UTF-8
3,614
2.671875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef ROOTBLOSSOMSIG_H #define ROOTBLOSSOMSIG_H #include <vector> #include "types.h" namespace matching { namespace detail { template <typename> struct Blossom; template <typename> class Graph; template <typename> class ParentBlossom; template <typename> struct Vertex; /** * A class containing the extra info associated with a top-level blossom. */ template <typename edge_weight> class RootBlossom { public: /** * If label is OUTER, this vector is used to determine the minimum edge * between a pair of OUTER RootBlossoms. For each other OUTER RootBlossom, * this vector holds a pointer to the Vertex in this RootBlossom that is * part of the minimum edge between them. The position in the vector is * indexed by the other RootBlossom's baseVertex's vertexIndex. * * Only valid during the augmentation step. */ std::vector<Vertex<edge_weight> *> minOuterEdges; /** * If label is OUTER, this is the minimum resistance between this * RootBlossom and another OUTER RootBlossom, unless there are none, in * which case it is graph.maxEdgeWeight * 2u + 1u. * * Only valid during the augmentation step. */ typename edge_weight_traits<edge_weight>::vector::reference minOuterEdgeResistance; Blossom<edge_weight> &rootChild; Vertex<edge_weight> *baseVertex; /** * The Vertex to which baseVertex is currently matched, or 0 if it is not. */ Vertex<edge_weight> *baseVertexMatch{ }; /** * Only valid during the augmentation step. */ Label label; /** * If label is INNER, this is the vertex in another blossom that was used * to label this blossom. * * Only valid during the augmentation step. */ Vertex<edge_weight> *labelingVertex; /** * If label is INNER, this is the vertex in this blossom that was used * to label this blossom. * * Only valid during the augmentation step. */ Vertex<edge_weight> *labeledVertex; RootBlossom(RootBlossom<edge_weight> &) = delete; RootBlossom(RootBlossom<edge_weight> &&) = delete; RootBlossom(Vertex<edge_weight> &, vertex_index, Graph<edge_weight> &); template <class PathIterator> RootBlossom(PathIterator, PathIterator, Graph<edge_weight> &); RootBlossom( Blossom<edge_weight> &, Vertex<edge_weight> &, Vertex<edge_weight> *, Graph<edge_weight> &); RootBlossom( Blossom<edge_weight> &, Vertex<edge_weight> &, Vertex<edge_weight> *, Label, Vertex<edge_weight> *, Vertex<edge_weight> *, Graph<edge_weight> &); void putVerticesInMatchingOrder() const &; void freeAncestorOfBase(Blossom<edge_weight> &, Graph<edge_weight> &) &; void prepareVertexForWeightAdjustments( Vertex<edge_weight> &, Graph<edge_weight> & ) &; private: RootBlossom( ParentBlossom<edge_weight> &, const std::vector<RootBlossom<edge_weight> *> &, Graph<edge_weight> &, const RootBlossom<edge_weight> &); void updateRootBlossomInDescendants(RootBlossom<edge_weight> &) &; void initializeFromChildren( const std::vector<RootBlossom<edge_weight> *> &, Graph<edge_weight> &) &; }; template <typename edge_weight> void augmentToSource(Vertex<edge_weight> *, Vertex<edge_weight> *); } } #endif
true
3db8f202daf33c513fe7dd34c3c0fceee78ce282
C++
sivikt/memoria
/src/core/src/fixed_size_datum.cpp
UTF-8
4,658
2.609375
3
[ "BSD-3-Clause", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
// Copyright 2019 Victor Smirnov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memoria/core/datatypes/datum.hpp> namespace memoria { template <typename DataType> Datum<DataType> datum_from_sdn_value(const DataType*, int64_t value) { return Datum<DataType>(value); } template <typename DataType> Datum<DataType> datum_from_sdn_value(const DataType*, double value) { return Datum<DataType>(value); } template <typename DataType> Datum<DataType> datum_from_sdn_value(const DataType*, bool value) { return Datum<DataType>(value); } template <typename DataType> Datum<DataType> datum_from_sdn_value(const DataType*, const U8StringView& str) { U8StringView tstr = trim_string(str); std::istringstream iss (tstr.to_string()); using Value = typename DataTypeTraits<DataType>::ViewType; Value ivalue{}; iss >> ivalue; if (!iss.eof()) { MMA_THROW(RuntimeException()) << format_ex("Can't convert [{}] to {}", tstr, make_datatype_signature_string<BigInt>()); } return Datum<DataType>(ivalue); } template Datum<TinyInt> datum_from_sdn_value(const TinyInt*, const U8StringView&); template Datum<TinyInt> datum_from_sdn_value(const TinyInt*, int64_t); template Datum<TinyInt> datum_from_sdn_value(const TinyInt*, double); template Datum<TinyInt> datum_from_sdn_value(const TinyInt*, bool); template Datum<UTinyInt> datum_from_sdn_value(const UTinyInt*, const U8StringView&); template Datum<UTinyInt> datum_from_sdn_value(const UTinyInt*, int64_t); template Datum<UTinyInt> datum_from_sdn_value(const UTinyInt*, double); template Datum<UTinyInt> datum_from_sdn_value(const UTinyInt*, bool); template Datum<SmallInt> datum_from_sdn_value(const SmallInt*, const U8StringView&); template Datum<SmallInt> datum_from_sdn_value(const SmallInt*, int64_t); template Datum<SmallInt> datum_from_sdn_value(const SmallInt*, double); template Datum<SmallInt> datum_from_sdn_value(const SmallInt*, bool); template Datum<USmallInt> datum_from_sdn_value(const USmallInt*, const U8StringView&); template Datum<USmallInt> datum_from_sdn_value(const USmallInt*, int64_t); template Datum<USmallInt> datum_from_sdn_value(const USmallInt*, double); template Datum<USmallInt> datum_from_sdn_value(const USmallInt*, bool); template Datum<Integer> datum_from_sdn_value(const Integer*, const U8StringView&); template Datum<Integer> datum_from_sdn_value(const Integer*, int64_t); template Datum<Integer> datum_from_sdn_value(const Integer*, double); template Datum<Integer> datum_from_sdn_value(const Integer*, bool); template Datum<UInteger> datum_from_sdn_value(const UInteger*, const U8StringView&); template Datum<UInteger> datum_from_sdn_value(const UInteger*, int64_t); template Datum<UInteger> datum_from_sdn_value(const UInteger*, double); template Datum<UInteger> datum_from_sdn_value(const UInteger*, bool); template Datum<BigInt> datum_from_sdn_value(const BigInt*, const U8StringView&); template Datum<BigInt> datum_from_sdn_value(const BigInt*, int64_t); template Datum<BigInt> datum_from_sdn_value(const BigInt*, double); template Datum<BigInt> datum_from_sdn_value(const BigInt*, bool); template Datum<UBigInt> datum_from_sdn_value(const UBigInt*, const U8StringView&); template Datum<UBigInt> datum_from_sdn_value(const UBigInt*, int64_t); template Datum<UBigInt> datum_from_sdn_value(const UBigInt*, double); template Datum<UBigInt> datum_from_sdn_value(const UBigInt*, bool); template Datum<Real> datum_from_sdn_value(const Real*, const U8StringView&); template Datum<Real> datum_from_sdn_value(const Real*, int64_t); template Datum<Real> datum_from_sdn_value(const Real*, double); template Datum<Real> datum_from_sdn_value(const Real*, bool); template Datum<Double> datum_from_sdn_value(const Double*, const U8StringView&); template Datum<Double> datum_from_sdn_value(const Double*, int64_t); template Datum<Double> datum_from_sdn_value(const Double*, double); template Datum<Double> datum_from_sdn_value(const Double*, bool); }
true
350a29af65b4beb2306337d2d133f7b74f3eecde
C++
MysteryPizzaGuy/Crucible
/10012-Data Structures And Algorithms/#14/Tasks/Task 4/Source.cpp
UTF-8
696
3.171875
3
[]
no_license
#include <iostream> #include <unordered_set> #include <random> #include <vector> #include <string> void genString(std::vector<std::string>& v, int howMany) { std::random_device dev; std::mt19937 gen{ dev() }; std::uniform_int_distribution<int> dis{97, 101}; for (size_t i = 0; i < howMany; i++) { std::string temp; for (size_t i = 0; i < 5; i++) { temp += dis(gen); } v.push_back(temp); } } int main() { std::unordered_set<std::string> us; std::vector<std::string> v; genString(v, 1000); for (auto i = v.begin(); i < v.end(); i++) { auto check = us.insert(*i); if (!check.second) { std::cout << "Failure inserting: " << *i << std::endl; } } return 0; }
true
3c37d639540608ba9e71cddcac1cd33cf2318b48
C++
Samuel-Taya/Lab1-ProjectEuler-1-to-7-and-9
/Problem4.cpp
UTF-8
842
3.96875
4
[]
no_license
// largest palindrome made from the product of two 3-digit numbers. #include <iostream> #include <math.h> using namespace std; bool palindromo(int n) { int num = n; int inv = 0; // operacion para invertir el numero while (num>0) { inv = inv * 10 + num % 10; // obtiene el ultimo digito num = num / 10; // elimina el ultimo digito } if (inv == n) return true; return false; } int main() { int num, aux; num = 0; for (int i=100; i<1000; i++) // numeros de 3 digitos { for (int j=100; j<1000; j++) { aux = i*j; if (palindromo(aux) && aux>num) // aux>num para hallar el palindromo mas grande num=aux; } } cout<<num; return 0; }
true
315f7c3f632746ac1a6ec6c545ec2c8c8a008441
C++
graybriggs/advent-of-code-2016
/day2.cpp
UTF-8
1,528
3.109375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <fstream> std::vector<std::string> getCodes(std::string fname) { std::vector<std::string> codes; std::ifstream ifs(fname); std::string line; while (std::getline(ifs, line)) { codes.push_back(line); } return codes; } int main() { std::vector<std::string > codes = getCodes("day2-input.txt"); // Part 1 std::cout << "Part 1\n"; int x = 0; int y = 0; for (auto& code : codes) { for (int i = 0; i < code.length(); i++) { switch (code[i]) { case 'U': if (y < 1) y++; break; case 'D': if (y > -1) y--; break; case 'L': if (x > -1) x--; break; case 'R': if (x < 1) x++; break; } } std::cout << x << ", " << y << std::endl; } // Part 2 std::cout << "Part 2\n"; int grid[5][5] = { {0,0,1,0,0}, {0,2,3,4,0}, {5,6,7,8,9}, {0,-1,-2,-3,0}, {0,0,-4,0,0} }; x = 0; y = 2; for (auto& code : codes) { for (int i = 0; i < code.length(); i++) { switch (code[i]) { case 'U': if (y > 0 && grid[y - 1][x] != 0) y--; break; case 'D': if (y < 4 && grid[y + 1][x] != 0) y++; break; case 'L': if (x > 0 && grid[y][x - 1] != 0) x--; break; case 'R': if (x < 4 && grid[y][x + 1] != 0) x++; break; } } std::cout << x << ", " << y << std::endl; } char c; std::cin >> c; }
true
468dba3ab569b0cdba413090dc6a0600b2310f4c
C++
bluemix/Online-Judge
/UVA/Volume VII/706 LCD Display.cpp
WINDOWS-1252
3,736
3.046875
3
[]
no_license
/* 9038399 706 LCD Display Accepted C++ 0.024 2011-07-11 08:57:09 */ #include<stdio.h> #define MAX 1000 void print(char table[][MAX],char c,int s,int x){ int row,cul; // l for(cul=x;cul<=x+s+1;cul++) for(row=0;row<=2*s+2;row++) if(cul==x||cul==x+s+1) if((row>=1&&row<=s)||(row>=s+2&&row<=2*s+1)) table[row][cul]='|'; else table[row][cul]=' '; else if((row>=1&&row<=s)||(row>=s+2&&row<=2*s+1)) table[row][cul]=' '; else table[row][cul]='-'; switch(c){ case '0': for(cul=x+1;cul<=x+s;cul++) table[s+1][cul]=' '; break; case '1': for(row=1;row<=2*s+2;row++) table[row][x]=' '; for(cul=x+1;cul<=x+s;cul++) table[0][cul]=table[s+1][cul]=table[2*s+2][cul]=' '; break; case '2': for(row=1;row<=s;row++) table[row][x]=' '; for(row=s+2;row<=2*s+1;row++) table[row][x+s+1]=' '; break; case '3': for(row=1;row<=2*s+1;row++) table[row][x]=' '; break; case '4': for(cul=x;cul<=x+s+1;cul++) table[0][cul]=table[2*s+2][cul]=' '; for(row=s+2;row<=2*s+1;row++) table[row][x]=' '; break; case '5': for(row=1;row<=s;row++) table[row][x+s+1]=' '; for(row=s+2;row<=2*s+1;row++) table[row][x]=' '; break; case '6': for(row=1;row<=s;row++) table[row][x+s+1]=' '; break; case '7': for(row=1;row<=2*s+1;row++) table[row][x]=' '; for(cul=x+1;cul<=x+s;cul++) table[s+1][cul]=table[2*s+2][cul]=' '; break; case '8': break; case '9': for(row=s+2;row<=2*s+1;row++) table[row][x]=' '; break; } for(row=0;row<=2*s+2;row++) table[row][x+s+2]=' '; } int main(){ int s; char str[100]; while(scanf("%d%s",&s,str)==2){ if(s==0&&(str[0]=='0'&&str[1]=='\0')) break; char table[30][MAX]; int row,cul=0; for(int i=0;str[i]!='\0';i++){ print(table,str[i],s,cul); cul+=s+3; } for(row=0,cul--;row<=2*s+2;row++) table[row][cul]='\0'; for(int i=0;i<=2*s+2;i++) printf("%s\n",table[i]); putchar('\n'); } return 0; } /* A friend of you has just bought a new computer. Until now, the most powerful computer he ever used has been a pocket calculator. Now, looking at his new computer, he is a bit disappointed, because he liked the LC-display of his calculator so much. So you decide to write a program that displays numbers in an LC-display-like style on his computer. Input The input file contains several lines, one for each number to be displayed. Each line contains two integers s, n ( ), where n is the number to be displayed and s is the size in which it shall be displayed. The input file will be terminated by a line containing two zeros. This line should not be processed. Output Output the numbers given in the input file in an LC-display-style using s ``-'' signs for the horizontal segments and s ``|'' signs for the vertical ones. Each digit occupies exactly s+2 columns and 2s+3 rows. (Be sure to fill all the white space occupied by the digits with blanks, also for the last digit.) There has to be exactly one column of blanks between two digits. Output a blank line after each number. (You will find a sample of each digit in the sample output.) Sample Input 2 12345 3 67890 0 0 Sample Output -- -- -- | | | | | | | | | | | | -- -- -- -- | | | | | | | | | | -- -- -- --- --- --- --- --- | | | | | | | | | | | | | | | | | | | | | | | | --- --- --- | | | | | | | | | | | | | | | | | | | | | | | | --- --- --- --- -------------------------------------------------------------------------------- Miguel A. Revilla 2000-02-09 */
true
a2ddf83faf829ccf38302620a13ae0e4e983ca4d
C++
faterer/cpm
/leetcode/cpp/066-PlusOne.cpp
UTF-8
1,006
4.09375
4
[]
no_license
// No.66 easy https://leetcode.com/problems/plus-one/ // Given a non-negative number represented as an array of digits, plus one to the number. // The digits are stored such that the most significant digit is at the head of the list. #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> plusOne(vector<int>& digits) { int n = digits.size(); for(int i = n-1; i >= 0; i--) { if(digits[i] == 9) { digits[i] = 0; } else { digits[i] += 1; return digits; } } digits[0] = 1; digits.push_back(0); return digits; } }; int main() { int array1[] = {9,9,9,9}; int array2[] = {1,1,1,1}; vector<int> digits1(array1, array1+4); vector<int> digits2(array2, array2+4); vector<int> digits; Solution s; digits = s.plusOne(digits1); for(auto digit : digits1) cout << digit; cout << endl; digits = s.plusOne(digits2); for(auto digit : digits) cout << digit; cout << endl; return 0; }
true
43f4d1444c2f22b0fee4af1d4cd1d13b9216a5a7
C++
Katipo007/avokii
/src/Avokii/Graphics/Camera.hpp
UTF-8
4,725
2.640625
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
#pragma once #include "Avokii/Types/Vector.hpp" #include "Avokii/Types/Quaternion.hpp" #include "Avokii/Types/Matrix.hpp" #include "Avokii/Graphics/WorldSpace.hpp" namespace Avokii::Graphics { class Camera { public: enum class Type { Free, Orthographic, Spherical, NumCameraTypes, }; public: virtual Type GetType() const = 0; virtual const Mat4f& GetProjectionMatrix() const = 0; virtual const Mat4f& GetViewMatrix() const = 0; virtual const Mat4f& GetViewProjectionMatrix() const = 0; protected: Camera() = default; virtual ~Camera() = default; }; class PerspectiveCamera : public Camera { public: virtual const Mat4f& GetProjectionMatrix() const override { RecalculatePerspective(); return mMatProjection; } [[nodiscard]] float GetFOV() const { RecalculatePerspective(); return mFov; } [[nodiscard]] float GetAspect() const { RecalculatePerspective(); return mAspect; } [[nodiscard]] float GetClipNear() const { RecalculatePerspective(); return mClipNear; } [[nodiscard]] float GetClipFar() const { RecalculatePerspective(); return mClipFar; } virtual void Reset( float fov_rad, float aspect, float clip_near, float clip_far ); void Resetd( float fov_deg, float aspect, float clip_near, float clip_far ); virtual void SetFOV( float fov_rad ); void SetFOVd( float fov_deg ); virtual void SetAspectRatio( float aspect ); virtual void SetAspectRatio( uint32_t width, uint32_t height ) { SetAspectRatio( (float)height / float( width ) ); } virtual void SetClipSpace( float clip_near, float clip_far ); protected: PerspectiveCamera(); PerspectiveCamera( float fov_rad, float aspect, float clip_near, float clip_far ); private: void RecalculatePerspective() const; // not really const mutable Mat4f mMatProjection{ 1.f }; mutable bool mProjectionDirty{ true }; float mFov; // radians float mAspect; float mClipNear; float mClipFar; }; class FreelookCamera : public PerspectiveCamera { public: FreelookCamera(); [[nodiscard]] Type GetType() const override { return Type::Free; } [[nodiscard]] static Type GetStaticType() noexcept { return Type::Free; } [[nodiscard]] const Mat4f& GetViewMatrix() const override { Recalculate(); return mMatView; } [[nodiscard]] const Mat4f& GetViewProjectionMatrix() const override { Recalculate(); return mMatViewProjection; } [[nodiscard]] const Vec3f& GetPosition() const noexcept { return mPosition; } void SetPosition( const Vec3f& new_target_position ); [[nodiscard]] const auto& GetOrientation() const noexcept { return mOrientation; } void SetOrientation( const Quaternion& orientation ); private: void Recalculate() const; private: Vec3f mPosition{}; Quaternion mOrientation{}; // cached matrices mutable Mat4f mMatView{ 1.f }; mutable Mat4f mMatViewProjection{ 1.f }; mutable bool mDirty{ true }; }; class GimbalFreeLookCamera final : public FreelookCamera { }; // TODO: Orthographic camera class SphericalCamera final : public PerspectiveCamera { public: SphericalCamera() = default; [[nodiscard]] Type GetType() const override { return Type::Spherical; } [[nodiscard]] static Type GetStaticType() { return Type::Spherical; } [[nodiscard]] const Mat4f& GetViewMatrix() const override { Recalculate(); return mMatView; } [[nodiscard]] const Mat4f& GetViewProjectionMatrix() const override { Recalculate(); return mMatViewProjection; } [[nodiscard]] const Vec3f& GetPosition() const noexcept { return mTargetPosition; } void SetPosition( const Vec3f& new_target_position ); // Move relative to world void Move( const Vec3f& delta ); // Move relative to camera look direction void Pan( const Vec3f& delta ); // Move relative to camera look direction without changing Z coordinate void PanXY( const Vec2f& delta ); float GetRadius() const noexcept { return mRadius; } void SetRadius( float radius ); // +: in, -: out void Zoom( float distance ) { SetRadius( GetRadius() - distance ); } void SetRotation( float pitch_rad, float yaw_rad ); void SetRotationD( float pitch_deg, float yaw_deg ); void Rotate( float delta_pitch_rad, float delta_yaw_rad ); // [pitch, yaw], radians [[nodiscard]] std::pair<float, float> GetSphericalRotation() const; [[nodiscard]] Vec3f GetCartesianRotation() const; private: void Recalculate() const; private: float mPitch{ 0 }; // radians float mYaw{ 0 }; // radians float mRadius{ 1 }; // distance from target, worldspace Vec3f mTargetPosition{ 0, 0, 0 }; // cached matrices mutable Mat4f mRotation{ 1.f }; mutable Mat4f mMatView{ 1.f }; mutable Mat4f mMatViewProjection{ 1.f }; mutable bool mDirty{ true }; }; }
true
d8e96c753e31335f24665b104e24d33a6c30d786
C++
Pythalex/windscribeGUI-Linux
/input/parser.cpp
UTF-8
2,518
2.921875
3
[]
no_license
#include "parser.hpp" using std::string; using std::vector; void parse_state(State *s){ string status = read_windscribe_status(); if (status == "Service communication error"){ debug("Windscribe returned Service communication error."); return ; } string firewall = read_firewall(); string account = read_account_details(); if (!s) s = new State(); s->started = parse_started(status); s->connected = parse_connected(status); s->IP = parse_IP(status); s->firewall = parse_firewall(firewall); s->username = parse_account_username(account); } bool parse_started(string status){ vector<string> split = explode(status, "\n"); return (split.size() > 0 && split[0] !=\ "Windscribe is not running"); } bool parse_connected(string status){ vector<string> split = explode(status, "\n"); return (split.size() > 2 && split[2] != "DISCONNECTED"); } string parse_IP(string status){ vector<string> split = explode(status, "\n"); vector<string> IP_line_split = explode(split[1], ":"); if (IP_line_split.size() > 1) return trim_whitespaces(IP_line_split[1]); else return "N/A"; } string parse_account_username(string account_output){ vector<string> split = explode(account_output, "\n"); vector<string> user_line_split = explode(split[1], ":"); if (user_line_split.size() > 1) return trim_whitespaces(user_line_split[1]); else return "N/A"; } string parse_firewall(string firewall_output){ vector<string> split = explode(firewall_output, "\n"); vector<string> mode_line_split = explode(split[1], ":"); if (mode_line_split.size() > 1) return trim_whitespaces(mode_line_split[1]); else return "N/A"; } vector<Location> parse_locations(string location_output){ vector<Location> locations = vector<Location>(); vector<string> split = explode(location_output, "\n"); // skip commentary line for (uint i = 1; i < split.size(); i++){ vector<string> line_split = explode_substring(split[i], " "); Location l = Location(); l.country = trim_whitespaces(line_split[0]); l.short_name = trim_whitespaces(line_split[1]); l.city = trim_whitespaces(line_split[2]); l.label = trim_whitespaces(line_split[3]); l.pro = (trim_whitespaces(line_split[4]) == "*" ?\ true : false); locations.push_back(l); } return locations; }
true
39f4e35ae40d7970df2ef8ac7b84d63a2ce74218
C++
taricketts/Roman-Numeral
/RomanNumeral.h
UTF-8
4,937
3.4375
3
[]
no_license
/* * RomanNumeral.h * * Created on: Nov 10, 2014 * Author: Tom */ #include <string> #include <iostream> using namespace std; #ifndef ROMANNUMERAL_H_ #define ROMANNUMERAL_H_ class RomanNumeral { private: string roman[7]; int arabic[7]; public: RomanNumeral(); ~RomanNumeral(); int romanToArabic(string input); string messyArabicToRoman(int input); string subtractiveRoman(string input); int getSingleArabic(string input); string getSingleRoman(int input); bool isRoman(string input); }; RomanNumeral::RomanNumeral() { roman[0] = "I"; roman[1] = "V"; roman[2] = "X"; roman[3] = "L"; roman[4] = "C"; roman[5] = "D"; roman[6] = "M"; arabic[0] = 1; arabic[1] = 5; arabic[2] = 10; arabic[3] = 50; arabic[4] = 100; arabic[5] = 500; arabic[6] = 1000; } RomanNumeral::~RomanNumeral() { } int RomanNumeral::romanToArabic(string input) { int output = 0; int length = input.length(); if (isRoman(input) == true) { for (int i = 0; i < length; i++) { if (i == length - 1) { output += getSingleArabic(input.substr(i)); } else if (getSingleArabic(input.substr(i, 1)) < getSingleArabic(input.substr(i + 1, 1))) { output += getSingleArabic(input.substr(i + 1, 1)) - getSingleArabic(input.substr(i, 1)); i++; } else { output += getSingleArabic(input.substr(i, 1)); } } } else { output = -1; } return output; } string RomanNumeral::messyArabicToRoman(int input) { string output; int tmp = 0; if (input / 1000 >= 1) { tmp = input / 1000; input -= (tmp * 1000); for (int i = 0; i < tmp; i++) { output += "M"; } } if (input / 500 == 1) { tmp = input / 500; input -= 500; output += "D"; } if (input / 100 >= 1) { tmp = input / 100; input -= (tmp * 100); for (int i = 0; i < tmp; i++) { output += "C"; } } if (input / 50 >= 1) { tmp = input / 50; input -= (tmp * 100); for (int i = 0; i < tmp; i++) { output += "L"; } } if (input / 10 >= 1) { tmp = input / 10; input -= (tmp * 10); for (int i = 0; i < tmp; i++) { output += "X"; } } if (input / 5 >= 1) { tmp = input / 5; input -= (tmp * 5); for (int i = 0; i < tmp; i++) { output += "V"; } } if (input != 0) { for (int i = 0; i < input; i++) { output += "I"; } } return output; } string RomanNumeral::subtractiveRoman(string input) { int length = input.length(); // may not be needed: int count = 0; string output = ""; string tmp = ""; string single = ""; for (int i = 0; i < length; i++) { if (i == length - 1) { output += input.substr(i, 1); return output; } else if (i == length - 2) { output += input.substr(i, 1) + input.substr(i + 1, 1); return output; } else if (i == length - 3) { output += input.substr(i, 1) + input.substr(i + 1, 1) + input.substr(i + 2, 1); return output; } else { tmp = input.substr(i, 4); single = tmp.substr(0, 1); } if (single == tmp.substr(0, 1) && single == tmp.substr(1, 1) && single == tmp.substr(2, 1) && single == tmp.substr(3)) { /* check single for value, make correct conversion, change tmp, and add to output */ } else { output += tmp; } } return input; } bool RomanNumeral::isRoman(string input) { int length = input.size(); bool validity = true; for (int z = 0; z < length; z++) { if (z == length - 1) { if (input.substr(z) == roman[0] || input.substr(z) == roman[1] || input.substr(z) == roman[2] || input.substr(z) == roman[3] || input.substr(z) == roman[4] || input.substr(z) == roman[5] || input.substr(z) == roman[6]) { //Checks validity } else { validity = false; return validity; } } else if (input.substr(z, 1) == roman[0] || input.substr(z, 1) == roman[1] || input.substr(z, 1) == roman[2] || input.substr(z, 1) == roman[3] || input.substr(z, 1) == roman[4] || input.substr(z, 1) == roman[5] || input.substr(z, 1) == roman[6]) { //Checks validity } else { validity = false; return validity; } } return validity; } string RomanNumeral::getSingleRoman(int input) { string val; if (input == arabic[0]) val = roman[0]; else if (input == arabic[1]) val = roman[1]; else if (input == arabic[2]) val = roman[2]; else if (input == arabic[3]) val = roman[3]; else if (input == arabic[4]) val = roman[4]; else if (input == arabic[5]) val = roman[5]; else if (input == arabic[6]) val = roman[6]; else val = '0'; return val; } int RomanNumeral::getSingleArabic(string input) { int val; if (input == roman[0]) val = arabic[0]; else if (input == roman[1]) val = arabic[1]; else if (input == roman[2]) val = arabic[2]; else if (input == roman[3]) val = arabic[3]; else if (input == roman[4]) val = arabic[4]; else if (input == roman[5]) val = arabic[5]; else if (input == roman[6]) val = arabic[6]; else val = -1; return val; } #endif /* ROMANNUMERAL_H_ */
true
28c781c3c83da84c86940c2b65456fe3bbe0afa7
C++
vagran/phoenix
/lib/common/CommonLib.cpp
UTF-8
37,138
3.1875
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
/* * /phoenix/lib/common/CommonLib.cpp * * This file is a part of Phoenix operating system. * Copyright (c) 2011-2012, Artyom Lebedev <artyom.lebedev@gmail.com> * All rights reserved. * See COPYING file for copyright details. */ /** @file CommonLib.cpp * Run-time mid-level support functions. * * This file contains definitions for C run-time support functions. */ #include <sys.h> /** Fill block of memory. * * Sets the first @a size bytes of the block of memory pointed by @a dst * to the specified @a value (interpreted as an unsigned char). * @param dst Pointer to the block of memory to fill. * @param value Value to be set. The value is passed as an int, but the function * fills the block of memory using the unsigned char conversion of this * value. * @param size Number of bytes to be set to the value. */ #ifdef memset #undef memset #endif /* memset */ ASMCALL void * memset(void *dst, u8 value, size_t size) { void *ret = dst; while (size) { *static_cast<u8 *>(dst) = value; dst = static_cast<u8 *>(dst) + 1; size--; } return ret; } /** Copy block of memory. * * Copies the values of @a size bytes from the location pointed by @a src * directly to the memory block pointed by @a dst. * @par * The underlying type of the objects pointed by both the source and destination * pointers are irrelevant for this function; The result is a binary copy of the * data. * @par * The function does not check for any terminating null character in source - * it always copies exactly @a size bytes. * @par * To avoid overflows, the size of the arrays pointed by both the destination * and source parameters, shall be at least @a size bytes, and should not * overlap (for overlapping memory blocks, @link memmove @endlink is a safer * approach). * * @param dst Pointer to the destination array where the content is to be * copied, type-casted to a pointer of type @c void*. * @param src Pointer to the source of data to be copied, type-casted to a * pointer of type @c void*. * @param size Number of bytes to copy. * * @return @a dst is returned. */ #ifdef memcpy #undef memcpy #endif /* memcpy */ ASMCALL void * memcpy(void *dst, const void *src, size_t size) { void *ret = dst; while (size) { *static_cast<u8 *>(dst) = *(u8 *)src; dst = static_cast<u8 *>(dst) + 1; src = static_cast<const u8 *>(src) + 1; size--; } return ret; } /** Move block of memory * * Copies the values of @a size bytes from the location pointed by @a src to the * memory block pointed by @a dst. Copying takes place as if an intermediate * buffer were used, allowing the destination and source to overlap. * @par * The underlying type of the objects pointed by both the source and destination * pointers are irrelevant for this function; The result is a binary copy of the * data. * @par * The function does not check for any terminating null character in source - * it always copies exactly @a size bytes. * @par * To avoid overflows, the size of the arrays pointed by both the destination * and source parameters, shall be at least @a size bytes. * * @param dst Pointer to the destination array where the content is to be * copied, type-casted to a pointer of type @c void*. * @param src Pointer to the source of data to be copied, type-casted to a * pointer of type @c const @c void*. * @param size Number of bytes to copy. * * @return @a dst is returned. */ #ifdef memmove #undef memmove #endif /* memmove */ ASMCALL void * memmove(void *dst, const void *src, size_t size) { void *ret = dst; if (src > dst) { while (size) { *static_cast<u8 *>(dst) = *static_cast<const u8 *>(src); dst = static_cast<u8 *>(dst) + 1; src = static_cast<const u8 *>(src) + 1; size--; } } else { dst = static_cast<u8 *>(dst) + size - 1; src = static_cast<const u8 *>(src) + size - 1; while (size) { *static_cast<u8 *>(dst) = *static_cast<const u8 *>(src); dst = static_cast<u8 *>(dst) - 1; src = static_cast<const u8 *>(src) - 1; size--; } } return ret; } /** Compare two blocks of memory. * * Compares the first @a size bytes of the block of memory pointed by @a ptr1 to * the first @a size bytes pointed by @a ptr2, returning zero if they all match * or a value different from zero representing which is greater if they do not. * * @param ptr1 Pointer to block of memory. * @param ptr2 Pointer to block of memory. * @param size Number of bytes to compare. * * @return Returns an integral value indicating the relationship between the * content of the memory blocks: @n * @li A zero value indicates that the contents of both memory blocks are equal. * @li A value greater than zero indicates that the first byte that does not * match in both memory blocks has a greater value in @a ptr1 than in @a ptr2 as * if evaluated as unsigned char values; And a value less than zero indicates * the opposite. */ #ifdef memcmp #undef memcmp #endif /* memcmp */ ASMCALL int memcmp(const void *ptr1, const void *ptr2, size_t size) { while (size) { if (*static_cast<const u8 *>(ptr1) != *static_cast<const u8 *>(ptr2)) { return *static_cast<const u8 *>(ptr2) - *static_cast<const u8 *>(ptr1); } size--; } return 0; } /** Locate character in block of memory. * * Searches within the first @a size bytes of the block of memory pointed by * @a ptr for the first occurrence of value (interpreted as an @c unsigned * @c char), * and returns a pointer to it. * * @param ptr Pointer to the block of memory where the search is performed. * @param value Value to be located. The value is passed as an @c int, but the * function performs a byte per byte search using the @c unsigned @c char * conversion of this value. * @param size Number of bytes to be analyzed. * * @return A pointer to the first occurrence of @a value in the block of memory * pointed by @a ptr. If the value is not found, the function returns 0. */ #ifdef memchr #undef memchr #endif /* memchr */ ASMCALL void * memchr(void *ptr, int value, size_t size) { u8 *p = static_cast<u8 *>(ptr); while (size) { if (static_cast<u8>(value) == *p++) { return static_cast<void *>(p - 1); } size--; } return 0; } /** Convert ASCII character to upper case. */ ASMCALL int toupper(int c) { if (c >= 'a' && c <= 'z') { c -= 'a' - 'A'; } return c; } /** Convert ASCII character to lower case. */ ASMCALL int tolower(int c) { if (c >= 'A' && c <= 'Z') { c += 'a' - 'A'; } return c; } #ifdef strlen #undef strlen #endif /* strlen */ ASMCALL size_t strlen(const char *str) { register const char *s; for (s = str; *s; ++s); return s - str; } #ifdef strcpy #undef strcpy #endif /* strcpy */ ASMCALL char * strcpy(char *dst, const char *src) { char *ret = dst; while (*src) { *dst = *src; dst++; src++; } *dst = 0; return ret; } ASMCALL char * strncpy(char *dst, const char *src, size_t len) { char *ret = dst; size_t numLeft = len; while (*src && numLeft) { *dst = *src; dst++; src++; numLeft--; } if (numLeft) { *dst = 0; } else if (len) { *(dst - 1) = 0; } return ret; } ASMCALL int strcmp(const char *s1, const char *s2) { while (*s1 == *s2) { if (!*s1) { return 0; } s1++; s2++; } return *s2 - *s1; } ASMCALL int strncmp(const char *s1, const char *s2, size_t len) { while (len && *s1 == *s2) { if (!*s1) { return 0; } s1++; s2++; len--; } if (!len) { return 0; } return *s2 - *s1; } ASMCALL const char * strchr(const char *str, int c) { while (*str) { if (*str == c) { return str; } str++; } return 0; } ASMCALL const char * strstr(const char *s, const char *find) { char c, sc; size_t len; if ((c = *find++)) { len = strlen(find); do { do { if (!(sc = *s++)) { return 0; } } while (sc != c); } while (strncmp(s, find, len)); s--; } return s; } /** Check if ASCII character belongs to alphanumeric class. */ ASMCALL bool isalnum(int c) { if (c >= '0' && c <= '9') { return true; } if (c >= 'a' && c <= 'z') { return true; } if (c >= 'A' && c <= 'Z') { return true; } return false; } /** Check if ASCII character is alphabetic. */ ASMCALL bool isalpha(int c) { if (c >= 'a' && c <= 'z') { return true; } if (c >= 'A' && c <= 'Z') { return true; } return false; } /** Check is ASCII character is control character. */ ASMCALL bool iscntrl(int c) { return c < 32; } /** Check if ASCII character is digit. */ ASMCALL bool isdigit(int c) { return c >= '0' && c <= '9'; } /** Check if ASCII character is pseudo-graphical character. */ ASMCALL bool isgraph(int c) { return isalnum(c) || ispunct(c); } /** Check if ASCII character is lower case alphabetical character. */ ASMCALL bool islower(int c) { return c >= 'a' && c <= 'z'; } /** Check if ASCII character is printable. */ ASMCALL bool isprint(int c) { return isalnum(c) || ispunct(c) || c == ' '; } /** Check if ASCII character is punctuation character. */ ASMCALL bool ispunct(int c) { return !(iscntrl(c) || isalnum(c) || c == ' '); } /** Check if ASCII character is space character. */ ASMCALL bool isspace(int c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' || c == '\f'; } /** Check if ASCII character is upper case alphabetical character. */ ASMCALL bool isupper(int c) { return c >= 'A' && c <= 'Z'; } /** Check if ASCII character is hexadecimal digit. */ ASMCALL bool isxdigit(int c) { if (c >= '0' && c <= '9') { return true; } if (c >= 'a' && c <= 'f') { return true; } if (c >= 'A' && c <= 'F') { return true; } return false; } /** Check if ASCII character belongs to low part half of ASCII table. */ ASMCALL bool isascii(int c) { return c >= 0 && c <= 127; } ASMCALL long strtol(const char *nptr, const char **endptr, unsigned base) { const char *s = nptr; unsigned long acc; u8 c; unsigned long cutoff; bool neg = false; int any, cutlim; /* * Skip white space and pick up leading +/- sign if any. * If base is 0, allow 0x for hex and 0 for octal, else * assume decimal; if base is already 16, allow 0x. */ do { c = *s++; } while (isspace(c)); if (c == '-') { neg = true; c = *s++; } else if (c == '+') { c = *s++; } if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } if (base == 0) { base = c == '0' ? 8 : 10; } /* * Compute the cutoff value between legal numbers and illegal * numbers. That is the largest legal value, divided by the * base. An input number that is greater than this value, if * followed by a legal input character, is too big. One that * is equal to this value may be valid or not; the limit * between valid and invalid numbers is then based on the last * digit. For instance, if the range for longs is * [-2147483648..2147483647] and the input base is 10, * cutoff will be set to 214748364 and cutlim to either * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated * a value > 214748364, or equal but the next digit is > 7 (or 8), * the number is too big, and we will return a range error. * * Set any if any `digits' consumed; make it negative to indicate * overflow. */ cutoff = neg ? -(LONG_MIN + 1) : LONG_MAX; cutlim = cutoff % base; cutoff /= base; for (acc = 0, any = 0;; c = *s++) { if (!isascii(c)) { break; } if (isdigit(c)) { c -= '0'; } else if (isalpha(c)) { c -= isupper(c) ? 'A' - 10 : 'a' - 10; } else { break; } if (c >= base) { break; } if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) { any = -1; } else { any = 1; acc *= base; acc += c; } } if (any < 0) { acc = neg ? LONG_MIN : LONG_MAX; } else if (neg) { acc = -acc; } if (endptr) { *endptr = any ? s - 1 : nptr; } return (acc); } /* * Convert a string to an unsigned long integer. */ ASMCALL unsigned long strtoul(const char *nptr, const char **endptr, unsigned base) { const char *s = nptr; unsigned long acc; unsigned char c; unsigned long cutoff; bool neg = false; int any, cutlim; /* * See strtol for comments as to the logic used. */ do { c = *s++; } while (isspace(c)); if (c == '-') { neg = true; c = *s++; } else if (c == '+') { c = *s++; } if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } if (base == 0) { base = c == '0' ? 8 : 10; } cutoff = (unsigned long)ULONG_MAX / (unsigned long)base; cutlim = (unsigned long)ULONG_MAX % (unsigned long)base; for (acc = 0, any = 0;; c = *s++) { if (!isascii(c)) { break; } if (isdigit(c)) { c -= '0'; } else if (isalpha(c)) { c -= isupper(c) ? 'A' - 10 : 'a' - 10; } else { break; } if (c >= base) { break; } if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) { any = -1; } else { any = 1; acc *= base; acc += c; } } if (any < 0) { acc = 0xffffffff; } else if (neg) { acc = -acc; } if (endptr != 0) { *((const char **)endptr) = any ? s - 1 : nptr; } return (acc); } ASMCALL i64 strtoq(const char *nptr, const char **endptr, unsigned base) { const char *s; u64 acc; unsigned char c; u64 qbase, cutoff; bool neg; int any, cutlim; /* * Skip white space and pick up leading +/- sign if any. * If base is 0, allow 0x for hex and 0 for octal, else * assume decimal; if base is already 16, allow 0x. */ s = nptr; do { c = *s++; } while (isspace(c)); if (c == '-') { neg = true; c = *s++; } else { neg = false; if (c == '+') c = *s++; } if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } if (base == 0) { base = c == '0' ? 8 : 10; } /* * Compute the cutoff value between legal numbers and illegal * numbers. That is the largest legal value, divided by the * base. An input number that is greater than this value, if * followed by a legal input character, is too big. One that * is equal to this value may be valid or not; the limit * between valid and invalid numbers is then based on the last * digit. For instance, if the range for quads is * [-9223372036854775808..9223372036854775807] and the input base * is 10, cutoff will be set to 922337203685477580 and cutlim to * either 7 (neg==0) or 8 (neg==1), meaning that if we have * accumulated a value > 922337203685477580, or equal but the * next digit is > 7 (or 8), the number is too big, and we will * return a range error. * * Set any if any `digits' consumed; make it negative to indicate * overflow. */ qbase = base; if (neg) { cutoff = -(QUAD_MIN + QUAD_MAX); cutoff += QUAD_MAX; } else { cutoff = QUAD_MAX; } cutlim = cutoff % qbase; cutoff /= qbase; for (acc = 0, any = 0;; c = *s++) { if (!isascii(c)) { break; } if (isdigit(c)) { c -= '0'; } else if (isalpha(c)) { c -= isupper(c) ? 'A' - 10 : 'a' - 10; } else { break; } if (c >= base) { break; } if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) { any = -1; } else { any = 1; acc *= qbase; acc += c; } } if (any < 0) { acc = neg ? QUAD_MIN : QUAD_MAX; } else if (neg) { acc = -acc; } if (endptr != 0) { *((const char **)endptr) = any ? s - 1 : nptr; } return (acc); } ASMCALL u64 strtouq(const char *nptr, const char **endptr, unsigned base) { const char *s = nptr; u64 acc; unsigned char c; u64 qbase, cutoff; bool neg; int any, cutlim; /* * See strtoq for comments as to the logic used. */ do { c = *s++; } while (isspace(c)); if (c == '-') { neg = true; c = *s++; } else { neg = false; if (c == '+') { c = *s++; } } if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } if (base == 0) { base = c == '0' ? 8 : 10; } qbase = base; cutoff = UQUAD_MAX / qbase; cutlim = UQUAD_MAX % qbase; for (acc = 0, any = 0;; c = *s++) { if (!isascii(c)) { break; } if (isdigit(c)) { c -= '0'; } else if (isalpha(c)) { c -= isupper(c) ? 'A' - 10 : 'a' - 10; } else { break; } if (c >= base) { break; } if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) { any = -1; } else { any = 1; acc *= qbase; acc += c; } } if (any < 0) { acc = UQUAD_MAX; } else if (neg) { acc = -acc; } if (endptr != 0) { *endptr = any ? s - 1 : nptr; } return (acc); } /* sscanf family, borrowed from FreeBSD */ #define BUF 32 /* Maximum length of numeric string. */ /* * Flags used during conversion. */ #define LONG 0x01 /* l: long or double */ #define SHORT 0x04 /* h: short */ #define SUPPRESS 0x08 /* suppress assignment */ #define POINTER 0x10 /* weird %p pointer (`fake hex') */ #define NOSKIP 0x20 /* do not skip blanks */ #define QUAD 0x400 /* * The following are used in numeric conversions only: * SIGNOK, NDIGITS, DPTOK, and EXPOK are for floating point; * SIGNOK, NDIGITS, PFXOK, and NZDIGITS are for integral. */ #define SIGNOK 0x40 /* +/- is (still) legal */ #define NDIGITS 0x80 /* no digits detected */ #define DPTOK 0x100 /* (float) decimal point is still legal */ #define EXPOK 0x200 /* (float) exponent (e+3, etc) still legal */ #define PFXOK 0x100 /* 0x prefix is (still) legal */ #define NZDIGITS 0x200 /* no zero digits detected */ /* * Conversion types. */ #define CT_CHAR 0 /* %c conversion */ #define CT_CCL 1 /* %[...] conversion */ #define CT_STRING 2 /* %s conversion */ #define CT_INT 3 /* integer, i.e., strtoq or strtouq */ static const char *__sccl(char *, const char *); /** Parse string into provided variables. * * @param str Null terminated input string. * @param fmt Format specifier for input string parsing. * @return Number of variables assigned. */ int sscanf(const char *str, const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = vsscanf(str, fmt, ap); va_end(ap); return ret; } /** Parse string into provided variables. * * @param str Null terminated input string. * @param fmt Format specifier for input string parsing. * @param ap Arguments list with pointer to variables to assign values to. * @return Number of variables assigned. */ int vsscanf(const char *str, char const *fmt, va_list ap) { size_t inr; int c; /* character from format, or conversion */ size_t width; /* field width, or 0 */ char *p; /* points into all kinds of strings */ size_t n; /* handy integer */ int flags; /* flags as defined above */ char *p0; /* saves original value of p when necessary */ int nassigned; /* number of fields assigned */ int nconversions; /* number of conversions */ int nread; /* number of characters consumed from fp */ int base; /* base argument to strtoq/strtouq */ enum ccfntype { ccfn_none, ccfn_strtoq, ccfn_strtouq }; ccfntype ccfn; /* conversion function (strtoq/strtouq) */ char ccltab[256]; /* character class table for %[...] */ char buf[BUF]; /* buffer for numeric conversions */ /* `basefix' is used to avoid `if' tests in the integer scanner */ static short basefix[17] = { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; inr = strlen(str); nassigned = 0; nconversions = 0; nread = 0; base = 0; ccfn = ccfn_none; for (;;) { c = *fmt++; if (c == 0) { return nassigned; } if (isspace(c)) { while (inr > 0 && isspace(*str)) { nread++, inr--, str++; } continue; } if (c != '%') { goto literal; } width = 0; flags = 0; /* * switch on the format. continue if done; * break once format type is derived. */ again: c = *fmt++; switch (c) { case '%': literal: if (inr <= 0) { goto input_failure; } if (*str != c) { goto match_failure; } inr--, str++; nread++; continue; case '*': flags |= SUPPRESS; goto again; case 'l': flags |= LONG; goto again; case 'q': flags |= QUAD; goto again; case 'h': flags |= SHORT; goto again; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': width = width * 10 + c - '0'; goto again; /* * Conversions. * */ case 'd': c = CT_INT; ccfn = ccfn_strtoq; base = 10; break; case 'i': c = CT_INT; ccfn = ccfn_strtoq; base = 0; break; case 'o': c = CT_INT; ccfn = ccfn_strtouq; base = 8; break; case 'u': c = CT_INT; ccfn = ccfn_strtouq; base = 10; break; case 'x': flags |= PFXOK; /* enable 0x prefixing */ c = CT_INT; ccfn = ccfn_strtouq; base = 16; break; case 's': c = CT_STRING; break; case '[': fmt = __sccl(ccltab, fmt); flags |= NOSKIP; c = CT_CCL; break; case 'c': flags |= NOSKIP; c = CT_CHAR; break; case 'p': /* pointer format is like hex */ flags |= POINTER | PFXOK; c = CT_INT; ccfn = ccfn_strtouq; base = 16; break; case 'n': nconversions++; if (flags & SUPPRESS) { /* ??? */ continue; } if (flags & SHORT) { *va_arg(ap, short *) = nread; } else if (flags & LONG) { *va_arg(ap, long *) = nread; } else if (flags & QUAD) { *va_arg(ap, i64 *) = nread; } else { *va_arg(ap, int *) = nread; } continue; } /* * We have a conversion that requires input. */ if (inr <= 0) { goto input_failure; } /* * Consume leading white space, except for formats * that suppress this. */ if ((flags & NOSKIP) == 0) { while (isspace(*str)) { nread++; if (--inr > 0) { str++; } else { goto input_failure; } } /* * Note that there is at least one character in * the buffer, so conversions that do not set NOSKIP * can no longer result in an input failure. */ } /* * Do the conversion. */ switch (c) { case CT_CHAR: /* scan arbitrary characters (sets NOSKIP) */ if (width == 0) { width = 1; } if (flags & SUPPRESS) { size_t sum = 0; for (;;) { if ((n = inr) < width) { sum += n; width -= n; str += n; if (sum == 0) { goto input_failure; } break; } else { sum += width; inr -= width; str += width; break; } } nread += sum; } else { memcpy(va_arg(ap, char *), str, width); inr -= width; str += width; nread += width; nassigned++; } nconversions++; break; case CT_CCL: /* scan a (nonempty) character class (sets NOSKIP) */ if (width == 0) { width = ~0; /* `infinity' */ } /* take only those things in the class */ if (flags & SUPPRESS) { n = 0; while (ccltab[static_cast<u8>(*str)]) { n++, inr--, str++; if (--width == 0) { break; } if (inr <= 0) { if (n == 0) { goto input_failure; } break; } } if (n == 0) goto match_failure; } else { p0 = p = va_arg(ap, char *); while (ccltab[static_cast<u8>(*str)]) { inr--; *p++ = *str++; if (--width == 0) { break; } if (inr <= 0) { if (p == p0) { goto input_failure; } break; } } n = p - p0; if (n == 0) { goto match_failure; } *p = 0; nassigned++; } nread += n; nconversions++; break; case CT_STRING: /* like CCL, but zero-length string OK, & no NOSKIP */ if (width == 0) width = ~0; if (flags & SUPPRESS) { n = 0; while (!isspace(*str)) { n++, inr--, str++; if (--width == 0) { break; } if (inr <= 0) { break; } } nread += n; } else { p0 = p = va_arg(ap, char *); while (!isspace(*str)) { inr--; *p++ = *str++; if (--width == 0) break; if (inr <= 0) break; } *p = 0; nread += p - p0; nassigned++; } nconversions++; continue; case CT_INT: /* scan an integer as if by strtoq/strtouq */ #ifdef hardway if (width == 0 || width > sizeof(buf) - 1) width = sizeof(buf) - 1; #else /* size_t is unsigned, hence this optimisation */ if (--width > sizeof(buf) - 2) width = sizeof(buf) - 2; width++; #endif flags |= SIGNOK | NDIGITS | NZDIGITS; for (p = buf; width; width--) { c = *str; /* * Switch on the character; `goto ok' * if we accept it as a part of number. */ switch (c) { /* * The digit 0 is always legal, but is * special. For %i conversions, if no * digits (zero or nonzero) have been * scanned (only signs), we will have * base==0. In that case, we should set * it to 8 and enable 0x prefixing. * Also, if we have not scanned zero digits * before this, do not turn off prefixing * (someone else will turn it off if we * have scanned any nonzero digits). */ case '0': if (base == 0) { base = 8; flags |= PFXOK; } if (flags & NZDIGITS) flags &= ~(SIGNOK|NZDIGITS|NDIGITS); else flags &= ~(SIGNOK|PFXOK|NDIGITS); goto ok; /* 1 through 7 always legal */ case '1': case '2': case '3': case '4': case '5': case '6': case '7': base = basefix[base]; flags &= ~(SIGNOK | PFXOK | NDIGITS); goto ok; /* digits 8 and 9 ok if decimal or hex */ case '8': case '9': base = basefix[base]; if (base <= 8) break; /* not legal here */ flags &= ~(SIGNOK | PFXOK | NDIGITS); goto ok; /* letters ok if hex */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': /* no need to fix base here */ if (base <= 10) break; /* not legal here */ flags &= ~(SIGNOK | PFXOK | NDIGITS); goto ok; /* sign ok only as first character */ case '+': case '-': if (flags & SIGNOK) { flags &= ~SIGNOK; goto ok; } break; /* x ok if flag still set and 2nd char */ case 'x': case 'X': if ((flags & PFXOK) && p == buf + 1) { base = 16; /* if %i */ flags &= ~PFXOK; goto ok; } break; } /* * If we got here, c is not a legal character * for a number. Stop accumulating digits. */ break; ok: /* * c is legal: store it and look at the next. */ *p++ = c; if (--inr > 0) { str++; } else { break; /* end of input */ } } /* * If we had only a sign, it is no good; push * back the sign. If the number ends in `x', * it was [sign] '0' 'x', so push back the x * and treat it as [sign] '0'. */ if (flags & NDIGITS) { if (p > buf) { str--; inr++; } goto match_failure; } c = p[-1]; if (c == 'x' || c == 'X') { --p; str--; inr++; } if ((flags & SUPPRESS) == 0) { u64 res; *p = 0; ASSERT(ccfn != ccfn_none); if (ccfn == ccfn_strtoq) { res = strtoq(buf, 0, base); } else { res = strtouq(buf, 0, base); } if (flags & POINTER) { vm::Vaddr va(res); *va_arg(ap, void **) = va; } else if (flags & SHORT) { *va_arg(ap, short *) = res; } else if (flags & LONG) { *va_arg(ap, long *) = res; } else if (flags & QUAD) { *va_arg(ap, i64 *) = res; } else { *va_arg(ap, int *) = res; } nassigned++; } nread += p - buf; nconversions++; break; } } input_failure: return nconversions != 0 ? nassigned : -1; match_failure: return nassigned; } /* * Fill in the given table from the scanset at the given format * (just after `['). Return a pointer to the character past the * closing `]'. The table has a 1 wherever characters should be * considered part of the scanset. */ static const char * __sccl(char *tab, const char *fmt) { int c, n, v; /* first `clear' the whole table */ c = *fmt++; /* first char hat => negated scanset */ if (c == '^') { v = 1; /* default => accept */ c = *fmt++; /* get new first char */ } else { v = 0; /* default => reject */ } for (n = 0; n < 256; n++) { tab[n] = v; } if (c == 0) { return fmt - 1; /* format ended before closing ] */ } /* * Now set the entries corresponding to the actual scanset * to the opposite of the above. * * The first character may be ']' (or '-') without being special; * the last character may be '-'. */ v = 1 - v; for (;;) { tab[c] = v; /* take character c */ doswitch: n = *fmt++; /* and examine the next */ switch (n) { case 0: /* format ended too soon */ return fmt - 1; case '-': /* * A scanset of the form * [01+-] * is defined as `the digit 0, the digit 1, * the character +, the character -', but * the effect of a scanset such as * [a-zA-Z0-9] * is implementation defined. The V7 Unix * scanf treats `a-z' as `the letters a through * z', but treats `a-a' as `the letter a, the * character -, and the letter a'. * * For compatibility, the `-' is not considered * to define a range if the character following * it is either a close bracket (required by ANSI) * or is not numerically greater than the character * we just stored in the table (c). */ n = *fmt; if (n == ']' || n < c) { c = '-'; break; /* resume the for(;;) */ } fmt++; /* fill in the range */ do { tab[++c] = v; } while (c < n); c = n; /* * Alas, the V7 Unix scanf also treats formats * such as [a-c-e] as `the letters a through e'. * This too is permitted by the standard.... */ goto doswitch; case ']': /* end of scanset */ return fmt; default: /* just another character */ c = n; break; } } NOT_REACHED(); return 0; }
true
765e4d1995ae7bf9813f24f6ad5dda0fd1776256
C++
David-Badiane/VbrArt
/sketch_fcpc3.ino
UTF-8
2,874
3.078125
3
[]
no_license
// constants won't change. They're used here to set pin numbers: const int buttLedNumber = 4; const int buttonPin[buttLedNumber] = {2, 3, 4, 5}; // the number of the pushbutton pin const int ledPin[buttLedNumber] = {6, 7, 8, 9}; // the number of the LED pin // Variables will change: int ledState[buttLedNumber] = {LOW, LOW, LOW, LOW}; // the current state of the output pin int lastButtonState[buttLedNumber] = {LOW, LOW, LOW, LOW}; // the previous reading from the input pin int count = 0; int sensorValue = 0; //initialization of sensor variable, equivalent to EMA Y float EMA_a = 0.4; //initialization of EMA alpha int EMA_S = 0; //initialization of EMA S int sceneNum = 0; int lastSceneNum; int lastSensorValue; //Functions prototype: //void switchDebounce(unsigned long &lastDebounceTime, unsigned long &debounceDelay, int &ledState, int &buttonState, int &lastButtonState, int &reading, int count); // the following variables are unsigned longs because the time, measured in // milliseconds, will quickly become a bigger number than can be stored in an int. unsigned long lastDebounceTime[buttLedNumber]; // the last time the output pin was toggled unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers void setup() { //Set the leds pins as outputs for(int i = 0; i < buttLedNumber; i++){ pinMode(buttonPin[i], INPUT); } //Set the leds pins as outputs for(int i = 0; i < buttLedNumber; i++){ pinMode(ledPin[i], OUTPUT); } // set initial LED state for(int i = 0; i < buttLedNumber; i++){ digitalWrite(ledPin[i], ledState[i]); } Serial.begin(9600); //Start the serial monitor EMA_S = analogRead(A0); } void loop() { if (count > buttLedNumber - 1){ count = 0; } // int sceneNum; // read the state of the switch into a local variable: int reading = digitalRead(buttonPin[count]); if (reading != lastButtonState[count]) { // reset the debouncing timer lastDebounceTime[count] = millis(); } if (millis() - lastDebounceTime[count] > debounceDelay){ if(reading == HIGH) { for(int i = 0; i < buttLedNumber; i++) { if (i == count) { ledState[i] = HIGH; sceneNum = i; } else { ledState[i] = LOW; } } } } // set the LEDs: digitalWrite(ledPin[count], ledState[count]); sensorValue = analogRead(A0); EMA_S = (EMA_a*sensorValue) + ((1-EMA_a)*EMA_S); if(sceneNum != lastSceneNum || EMA_S != lastSensorValue) { Serial.print(sceneNum); Serial.print(' '); Serial.print(EMA_S); Serial.print('\n'); lastSceneNum = sceneNum; lastSensorValue = EMA_S; delay(50); } // save the reading. Next time through the loop, it'll be the lastButtonState: lastButtonState[count] = reading; count += 1; }
true
a9e927dd1a950b9dd3688883118bb2422c9639eb
C++
kamalsirsa/vtp
/TerrainSDK/vtdata/vtString.cpp
UTF-8
30,562
2.734375
3
[ "MIT" ]
permissive
// // vtString.cpp // // Copyright (c) 2001-2011 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtString.h" #include <stdlib.h> #include <ctype.h> #include <stdio.h> #include <wchar.h> #define InterlockInc(i) (*(i))++ #define InterlockDec(i) --(*(i)) ///////////////////////////////////////////////////////////////////////////// // static class data, special inlines // vtChNil is left for backward compatibility static char vtChNil = '\0'; // For an empty string, m_pchData will point here // (note: avoids special case of checking for NULL m_pchData) // empty string data (and locked) static int _vtInitData[] = { -1, 0, 0, 0 }; static vtStringData* _vtDataNil = (vtStringData*)&_vtInitData; pcchar _vtPchNil = (pcchar)(((uchar*)&_vtInitData)+sizeof(vtStringData)); ////////////////////////////////////////////////////////////////////////////// // Construction/Destruction vtString::vtString(const vtString& stringSrc) { if (stringSrc.GetData()->nRefs >= 0) { m_pchData = stringSrc.m_pchData; InterlockInc(&GetData()->nRefs); } else { Init(); *this = stringSrc.m_pchData; } } // construct from subset of characters from an ANSI string (converts to char) vtString::vtString(pcchar lpch, int nLength) { Init(); if (nLength != 0) { AllocBuffer(nLength); memcpy(m_pchData, lpch, nLength*sizeof(char)); } } void vtString::AllocBuffer(int nLen) // always allocate one extra character for '\0' termination // assumes [optimistically] that data length will equal allocation length { if (nLen == 0) Init(); else { vtStringData* pData; pData = (vtStringData*) new uchar[sizeof(vtStringData) + (nLen+1)*sizeof(char)]; pData->nAllocLength = nLen; pData->nRefs = 1; pData->data()[nLen] = '\0'; pData->nDataLength = nLen; m_pchData = pData->data(); } } void vtString::FreeData(vtStringData* pData) { delete[] (uchar*)pData; } void vtString::Release() { if (GetData() != _vtDataNil) { if (InterlockDec(&GetData()->nRefs) <= 0) FreeData(GetData()); Init(); } } void vtString::Release(vtStringData* pData) { if (pData != _vtDataNil) { if (InterlockDec(&pData->nRefs) <= 0) FreeData(pData); } } void vtString::Clear() { if (GetData()->nDataLength == 0) return; if (GetData()->nRefs >= 0) Release(); else *this = &vtChNil; } void vtString::CopyBeforeWrite() { if (GetData()->nRefs > 1) { vtStringData* pData = GetData(); Release(); AllocBuffer(pData->nDataLength); memcpy(m_pchData, pData->data(), (pData->nDataLength+1)*sizeof(char)); } } void vtString::AllocBeforeWrite(int nLen) { if (GetData()->nRefs > 1 || nLen > GetData()->nAllocLength) { Release(); AllocBuffer(nLen); } } // // free any attached data // vtString::~vtString() { if (GetData() != _vtDataNil) { if (InterlockDec(&GetData()->nRefs) <= 0) FreeData(GetData()); } } ////////////////////////////////////////////////////////////////////////////// // Helpers for the rest of the implementation void vtString::AllocCopy(vtString& dest, int nCopyLen, int nCopyIndex, int nExtraLen) const { // will clone the data attached to this string // allocating 'nExtraLen' characters // Places results in uninitialized string 'dest' // Will copy the part or all of original data to start of new string int nNewLen = nCopyLen + nExtraLen; if (nNewLen == 0) { dest.Init(); } else { dest.AllocBuffer(nNewLen); memcpy(dest.m_pchData, m_pchData+nCopyIndex, nCopyLen*sizeof(char)); } } ////////////////////////////////////////////////////////////////////////////// // More sophisticated construction vtString::vtString(pcchar szStr) { Init(); int nLen = SafeStrlen(szStr); if (nLen != 0) { AllocBuffer(nLen); memcpy(m_pchData, szStr, nLen*sizeof(char)); } } ////////////////////////////////////////////////////////////////////////////// // Assignment operators // All assign a new value to the string // (a) first see if the buffer is big enough // (b) if enough room, copy on top of old buffer, set size and type // (c) otherwise free old string data, and create a new one // // All routines return the new string (but as a 'const vtString&' so that // assigning it again will cause a copy, eg: s1 = s2 = "hi there". // void vtString::AssignCopy(int nSrcLen, pcchar szSrcData) { AllocBeforeWrite(nSrcLen); memcpy(m_pchData, szSrcData, nSrcLen*sizeof(char)); GetData()->nDataLength = nSrcLen; m_pchData[nSrcLen] = '\0'; } const vtString& vtString::operator=(const vtString& stringSrc) { if (m_pchData != stringSrc.m_pchData) { if ((GetData()->nRefs < 0 && GetData() != _vtDataNil) || stringSrc.GetData()->nRefs < 0) { // actual copy necessary since one of the strings is locked AssignCopy(stringSrc.GetData()->nDataLength, stringSrc.m_pchData); } else { // can just copy references around Release(); m_pchData = stringSrc.m_pchData; InterlockInc(&GetData()->nRefs); } } return *this; } const vtString& vtString::operator=(pcchar lpsz) { AssignCopy(SafeStrlen(lpsz), lpsz); return *this; } ////////////////////////////////////////////////////////////////////////////// // concatenation // NOTE: "operator+" is done as friend functions for simplicity // There are three variants: // vtString + vtString // and for ? = char, pcchar // vtString + ? // ? + vtString void vtString::ConcatCopy(int nSrc1Len, pcchar szSrc1Data, int nSrc2Len, pcchar szSrc2Data) { // -- master concatenation routine // Concatenate two sources // -- assume that 'this' is a new vtString object int nNewLen = nSrc1Len + nSrc2Len; if (nNewLen != 0) { AllocBuffer(nNewLen); memcpy(m_pchData, szSrc1Data, nSrc1Len*sizeof(char)); memcpy(m_pchData+nSrc1Len, szSrc2Data, nSrc2Len*sizeof(char)); } } vtString operator+(const vtString& string1, const vtString& string2) { vtString s; s.ConcatCopy(string1.GetData()->nDataLength, string1.m_pchData, string2.GetData()->nDataLength, string2.m_pchData); return s; } vtString operator+(const vtString& string, pcchar lpsz) { vtString s; s.ConcatCopy(string.GetData()->nDataLength, string.m_pchData, vtString::SafeStrlen(lpsz), lpsz); return s; } vtString operator+(pcchar lpsz, const vtString& string) { vtString s; s.ConcatCopy(vtString::SafeStrlen(lpsz), lpsz, string.GetData()->nDataLength, string.m_pchData); return s; } ////////////////////////////////////////////////////////////////////////////// // concatenate in place void vtString::ConcatInPlace(int nSrcLen, pcchar szSrcData) { // -- the main routine for += operators // concatenating an empty string is a no-op! if (nSrcLen == 0) return; // if the buffer is too small, or we have a width mis-match, just // allocate a new buffer (slow but sure) if (GetData()->nRefs > 1 || GetData()->nDataLength + nSrcLen > GetData()->nAllocLength) { // we have to grow the buffer, use the ConcatCopy routine vtStringData* pOldData = GetData(); ConcatCopy(GetData()->nDataLength, m_pchData, nSrcLen, szSrcData); vtString::Release(pOldData); } else { // fast concatenation when buffer big enough memcpy(m_pchData+GetData()->nDataLength, szSrcData, nSrcLen*sizeof(char)); GetData()->nDataLength += nSrcLen; m_pchData[GetData()->nDataLength] = '\0'; } } const vtString& vtString::operator+=(pcchar lpsz) { ConcatInPlace(SafeStrlen(lpsz), lpsz); return *this; } const vtString& vtString::operator+=(const vtString& string) { ConcatInPlace(string.GetData()->nDataLength, string.m_pchData); return *this; } const vtString& vtString::operator+=(char ch) { ConcatInPlace(1, &ch); return *this; } void vtString::Concat(pcchar buffer, size_t length) { ConcatInPlace(length, buffer); } ////////////////////////////////////////////////////////////////////////////// // less common string expressions vtString operator+(const vtString& string1, char ch) { vtString s; s.ConcatCopy(string1.GetData()->nDataLength, string1.m_pchData, 1, &ch); return s; } vtString operator+(char ch, const vtString& string) { vtString s; s.ConcatCopy(1, &ch, string.GetData()->nDataLength, string.m_pchData); return s; } /////////////////////////////////////////////////////////////////////////////// // String comparison and Testing bool vtString::IsNumber() const { const char *s = (const char *) m_pchData; if ((s[0] == '-') || (s[0] == '+')) s++; while (*s) { if (!isdigit((uchar) (*s))) return false; s++; } return true; } bool vtString::Matches(pcchar lpsz) const { const char *string = (const char *) m_pchData; const char *wild = lpsz; const char *cp=0, *mp=0; // set to 0 to avoid compiler warning while ((*string) && (*wild != '*')) { if ((*wild != *string) && (*wild != '?')) return false; wild++; string++; } while (*string) { if (*wild == '*') { if (!*++wild) return true; mp = wild; cp = string+1; } else if ((*wild == *string) || (*wild == '?')) { wild++; string++; } else { wild = mp; string = cp++; } } while (*wild == '*') wild++; return !*wild; } /////////////////////////////////////////////////////////////////////////////// // Advanced direct buffer access pchar vtString::GetBuffer(int nMinBufLength) { if (GetData()->nRefs > 1 || nMinBufLength > GetData()->nAllocLength) { // we have to grow the buffer vtStringData* pOldData = GetData(); int nOldLen = GetData()->nDataLength; // AllocBuffer will tromp it if (nMinBufLength < nOldLen) nMinBufLength = nOldLen; AllocBuffer(nMinBufLength); memcpy(m_pchData, pOldData->data(), (nOldLen+1)*sizeof(char)); GetData()->nDataLength = nOldLen; vtString::Release(pOldData); } // return a pointer to the character storage for this string return m_pchData; } void vtString::ReleaseBuffer(int nNewLength) { CopyBeforeWrite(); // just in case GetBuffer was not called if (nNewLength == -1) nNewLength = strlen(m_pchData); // zero terminated GetData()->nDataLength = nNewLength; m_pchData[nNewLength] = '\0'; } pchar vtString::GetBufferSetLength(int nNewLength) { GetBuffer(nNewLength); GetData()->nDataLength = nNewLength; m_pchData[nNewLength] = '\0'; return m_pchData; } void vtString::FreeExtra() { if (GetData()->nDataLength != GetData()->nAllocLength) { vtStringData* pOldData = GetData(); AllocBuffer(GetData()->nDataLength); memcpy(m_pchData, pOldData->data(), pOldData->nDataLength*sizeof(char)); vtString::Release(pOldData); } } pchar vtString::LockBuffer() { pchar lpsz = GetBuffer(0); GetData()->nRefs = -1; return lpsz; } void vtString::UnlockBuffer() { if (GetData() != _vtDataNil) GetData()->nRefs = 1; } /////////////////////////////////////////////////////////////////////////////// // Commonly used routines (rarely used routines in STREX.CPP) int vtString::Find(char ch) const { return Find(ch, 0); } int vtString::Find(char ch, int nStart) const { int nLength = GetData()->nDataLength; if (nStart >= nLength) return -1; // find first single character pchar lpsz = strchr(m_pchData + nStart, (uchar)ch); // return -1 if not found and index otherwise return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData); } int vtString::FindOneOf(pcchar lpszCharSet) const { pchar lpsz = strpbrk(m_pchData, lpszCharSet); return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData); } void vtString::MakeUpper() { CopyBeforeWrite(); #ifdef WIN32 _strupr(m_pchData); #else for (char *p = m_pchData; *p; p++ ) *p = toupper(*p); #endif } void vtString::MakeLower() { CopyBeforeWrite(); #ifdef WIN32 _strlwr(m_pchData); #else for (char *p = m_pchData; *p; p++ ) *p = tolower(*p); #endif } void vtString::MakeReverse() { CopyBeforeWrite(); #ifdef WIN32 _strrev(m_pchData); #else { int len = strlen( m_pchData ); for ( int i = len / 2 - 1; i >= 0; i-- ) { char tmp = m_pchData[i]; m_pchData[ i ] = m_pchData[len-1-i]; m_pchData[len-1-i] = tmp; } } #endif } void vtString::SetAt(int nIndex, char ch) { CopyBeforeWrite(); m_pchData[nIndex] = ch; } // formatting (using wsprintf style formatting) void WIN_UNIX_CDECL vtString::Format(pcchar lpszFormat, ...) { va_list argList; va_start(argList, lpszFormat); FormatV(lpszFormat, argList); va_end(argList); } void vtString::FormatV(pcchar lpszFormat, va_list argList) { #ifdef _MSC_VER va_list argListSave = argList; #else // probably gcc, which has the newer standard "va_copy" macro va_list argListSave; va_copy(argListSave, argList); #endif // make a guess at the maximum length of the resulting string int nMaxLen = 0; for (pcchar lpsz = lpszFormat; *lpsz != '\0'; lpsz++) { // handle '%' character, but watch out for '%%' if (*lpsz != '%' || *(++lpsz) == '%') { nMaxLen++; continue; } int nItemLen = 0; // handle '%' character with format int nWidth = 0; for (; *lpsz != '\0'; lpsz++) { // check for valid flags if (*lpsz == '#') nMaxLen += 2; // for '0x' else if (*lpsz == '*') nWidth = va_arg(argList, int); else if (*lpsz == '-' || *lpsz == '+' || *lpsz == '0' || *lpsz == ' ') ; else // hit non-flag character break; } // get width and skip it if (nWidth == 0) { // width indicated by nWidth = atoi(lpsz); for (; *lpsz != '\0' && isdigit(*lpsz); lpsz++) ; } int nPrecision = 0; if (*lpsz == '.') { // skip past '.' separator (width.precision) lpsz++; // get precision and skip it if (*lpsz == '*') { nPrecision = va_arg(argList, int); lpsz++; } else { nPrecision = atoi(lpsz); for (; *lpsz != '\0' && isdigit(*lpsz); lpsz++) ; } } // should be on type modifier or specifier if (strncmp(lpsz, "I64", 3) == 0) { lpsz += 3; } else { switch (*lpsz) { // modifiers that affect size case 'h': lpsz++; break; case 'l': lpsz++; break; // modifiers that do not affect size case 'F': case 'N': case 'L': lpsz++; break; } } // now should be on specifier switch (*lpsz) { // single characters case 'c': case 'C': nItemLen = 2; va_arg(argList, int); break; // strings case 's': { const char *pstrNextArg = va_arg(argList, pcchar); if (pstrNextArg == NULL) nItemLen = 6; // "(null)" else { nItemLen = strlen(pstrNextArg); nItemLen = std::max(1, nItemLen); } } break; case 'S': /* FIXME: This case should do wchar_t *'s */ const char *pstrNextArg = va_arg(argList, pcchar); if (pstrNextArg == NULL) nItemLen = 6; // "(null)" else { nItemLen = strlen(pstrNextArg); nItemLen = std::max(1, nItemLen); } break; } // adjust nItemLen for strings if (nItemLen != 0) { if (nPrecision != 0) nItemLen = std::min(nItemLen, nPrecision); nItemLen = std::max(nItemLen, nWidth); } else { switch (*lpsz) { // integers case 'd': case 'i': case 'u': case 'x': case 'X': case 'o': va_arg(argList, int); nItemLen = 32; nItemLen = std::max(nItemLen, nWidth+nPrecision); break; case 'e': case 'g': case 'G': va_arg(argList, double); nItemLen = 128; nItemLen = std::max(nItemLen, nWidth+nPrecision); break; case 'f': va_arg(argList, double); nItemLen = 128; // width isn't truncated // 312 == strlen("-1+(309 zeroes).") // 309 zeroes == max precision of a double nItemLen = std::max(nItemLen, 312+nPrecision); break; case 'p': va_arg(argList, void*); nItemLen = 32; nItemLen = std::max(nItemLen, nWidth+nPrecision); break; // no output case 'n': va_arg(argList, int*); break; default: ; } } // adjust nMaxLen for output nItemLen nMaxLen += nItemLen; } GetBuffer(nMaxLen); vsprintf(m_pchData, lpszFormat, argListSave); ReleaseBuffer(); va_end(argListSave); } void vtString::TrimRight() { // find beginning of trailing spaces by starting at beginning CopyBeforeWrite(); // beware trouble with signed characters being cast to negative ints uchar *lpsz = (uchar *) m_pchData; uchar *lpszLast = NULL; while (*lpsz != '\0') { if (isspace(*lpsz)) { if (lpszLast == NULL) lpszLast = lpsz; } else lpszLast = NULL; lpsz++; } if (lpszLast != NULL) { // truncate at trailing space start *lpszLast = '\0'; GetData()->nDataLength = lpszLast - (uchar *) m_pchData; } } void vtString::TrimLeft() { // find first non-space character CopyBeforeWrite(); char *lpsz = m_pchData; while (isspace(*lpsz)) lpsz++; if (lpsz != m_pchData) { // fix up data and length int nDataLength = GetData()->nDataLength - (lpsz - m_pchData); memmove(m_pchData, lpsz, (nDataLength+1)*sizeof(char)); GetData()->nDataLength = nDataLength; } } ////////////////////////////////////////////////////////////////////////////// // Very simple sub-string extraction vtString vtString::Mid(int nFirst) const { return Mid(nFirst, GetData()->nDataLength - nFirst); } vtString vtString::Mid(int nFirst, int nCount) const { // out-of-bounds requests return sensible things if (nFirst < 0) nFirst = 0; if (nCount < 0) nCount = 0; if (nFirst + nCount > GetData()->nDataLength) nCount = GetData()->nDataLength - nFirst; if (nFirst > GetData()->nDataLength) nCount = 0; // optimize case of returning entire string if (nFirst == 0 && nFirst + nCount == GetData()->nDataLength) return *this; vtString dest; AllocCopy(dest, nCount, nFirst, 0); return dest; } vtString vtString::Right(int nCount) const { if (nCount < 0) nCount = 0; if (nCount >= GetData()->nDataLength) return *this; vtString dest; AllocCopy(dest, nCount, GetData()->nDataLength-nCount, 0); return dest; } vtString vtString::Left(int nCount) const { if (nCount < 0) nCount = 0; if (nCount >= GetData()->nDataLength) return *this; vtString dest; AllocCopy(dest, nCount, 0, 0); return dest; } ////////////////////////////////////////////////////////////////////////////// // Finding int vtString::ReverseFind(char ch) const { // find last single character const char *lpsz = strrchr(m_pchData, ch); // return -1 if not found, distance from beginning otherwise return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData); } // find a sub-string (like strstr) int vtString::Find(pcchar szSub) const { return Find(szSub, 0); } int vtString::Find(pcchar szSub, int nStart) const { int nLength = GetData()->nDataLength; if (nStart > nLength) return -1; // find first matching substring const char *lpsz = strstr(m_pchData + nStart, szSub); // return -1 for not found, distance from beginning otherwise return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData); } // advanced manipulation // replace occurrences of chOld with chNew int vtString::Replace(char chOld, char chNew) { int nCount = 0; // short-circuit the nop case if (chOld != chNew) { char *pszBuffer = m_pchData; // otherwise modify each character that matches in the string bool bCopied = false; int nLength = GetLength(); ; for (int iChar = 0; iChar < nLength; iChar ++) { // replace instances of the specified character only if( pszBuffer[iChar] == chOld ) { if( !bCopied ) { bCopied = true; CopyBeforeWrite(); } pszBuffer[iChar] = chNew; nCount++; } } } return nCount; } // replace occurrences of strOld with strNew int vtString::Replace(const char *strOld, const char *strNew, bool bReplaceAll) { int iCount = 0; // count of replacements made char *pszBuffer = m_pchData; size_t uiOldLen = strlen(strOld); size_t uiNewLen = strlen(strNew); size_t dwPos = 0; while ( pszBuffer[dwPos] != 0 ) { char *result = strstr(pszBuffer + dwPos, strOld); if ( result == NULL ) break; // exit the loop else { dwPos = result - pszBuffer; //replace this occurance of the old string with the new one *this = Left(dwPos) + strNew + Right(GetLength() - dwPos - uiOldLen); //move up pos past the string that was replaced dwPos += uiNewLen; pszBuffer = m_pchData; //increase replace count ++iCount; // stop now? if ( !bReplaceAll ) break; // exit the loop } } return iCount; } // remove occurrences of chRemove int vtString::Remove(char chRemove) { CopyBeforeWrite(); char *pstrSource = m_pchData; char *pstrDest = m_pchData; char *pstrEnd = m_pchData + GetData()->nDataLength; while (pstrSource < pstrEnd) { if (*pstrSource != chRemove) { *pstrDest = *pstrSource; pstrDest++; } pstrSource++; } *pstrDest = '\0'; int nCount = pstrSource - pstrDest; GetData()->nDataLength -= nCount; return nCount; } #if 0 // insert character at zero-based index; concatenates // if index is past end of string int vtString::Insert(int nIndex, char ch) { int nCount = 0; return nCount; } // insert substring at zero-based index; concatenates // if index is past end of string int vtString::Insert(int nIndex, pcchar pstr) { int nCount = 0; return nCount; } #endif // delete nCount characters starting at zero-based index int vtString::Delete(int iIndex, int nCount) { // check bounds first if (iIndex < 0) iIndex = 0; if (nCount < 0) nCount = 0; int nLength = GetLength(); if ((nCount+iIndex) > nLength) { nCount = nLength-iIndex; } // now actually remove characters if (nCount > 0) { CopyBeforeWrite(); int nCharsToCopy = nLength-(iIndex+nCount)+1; memmove( m_pchData+iIndex, m_pchData+iIndex+nCount, nCharsToCopy ); // BD added to fix a bug where the end of string is moved in, but vtString // still thinks the string is full length. GetData()->nDataLength -= nCount; } return GetLength(); } void vtString::FormatForURL(const char *szInput) { *this = ""; for (const char *c = szInput; *c; c++) { switch (*c) { case '\r': break; case '\n': *this += '+'; break; case ' ': *this += "%20"; break; case ',': *this += "%2C"; break; case '#': *this += "%23"; break; //case ':': // *this += "%3A"; // break; case '\\': *this += '/'; break; default: *this += *c; } } } vtString vtString::FormatForURL() const { vtString str; str.FormatForURL(m_pchData); return str; } ////////////////////////////////////////////////////////////////////////////// // Unicode / UTF8 support #if SUPPORT_WSTRING wstring2 vtString::UTF8ToWideString() { wstring2 ws; ws.from_utf8(m_pchData); return ws; } /** * For a vtString which contains a UTF-8 encoded string, attempt to convert it * to a string in the local (current locale) character set. */ vtString vtString::UTF8ToLocal() { // first make wide string wstring2 ws; ws.from_utf8(m_pchData); // get ready for conversion int len = ws.length(); const wchar_t *cstr = ws.c_str(); mbstate_t mbstate; memset(&mbstate, '\0', sizeof (mbstate)); // then convert it to a (local encoding) multi-byte string vtString str; char *target = str.GetBufferSetLength(len); int count = wcsrtombs(target, &cstr, len+1, &mbstate); return str; } vtString UTF8ToLocal(const char *string_utf8) { // Safety check if (!string_utf8) return vtString(""); // First make wide string wstring2 ws; ws.from_utf8(string_utf8); // Then use mb_str to convert to local encoding vtString str = ws.mb_str(); #if 0 // In theory, this code should be better, because it does not rely on // the fixed-size static buffer in wstring2::mb_str(), but wcsrtombs // does not behave well. int len = ws.length(); const wchar_t *cstr = ws.c_str(); mbstate_t mbstate; memset(&mbstate, '\0', sizeof (mbstate)); // then convert it to a (local encoding) multi-byte string vtString str; char *target = str.GetBufferSetLength(len); int count = wcsrtombs(target, &cstr, len+1, &mbstate); #endif return str; } #else // Fallback for non-WSTRING case: we just hope our string is UTF8 compatible! vtString vtString::UTF8ToLocal() { return *this; } vtString UTF8ToLocal(const char *string_utf8) { return vtString(string_utf8); } #endif // SUPPORT_WSTRING ///////////////////////////////////////////////////////////////////////////// vtString EscapeStringForXML(const char *input) { vtString output; const char *p1 = input; for (; ('\0' != *p1); p1++) { switch (*p1) { case '<': output += "&lt;"; break; case '&': output += "&amp;"; break; case '>': output += "&gt;"; break; case '"': output += "&quot;"; break; case '\'': output += "&apos;"; break; default: output += *p1; } } return output; } void EscapeStringForXML(const std::string &input, std::string &output) { output = ""; const char *p1 = input.c_str(); for (; ('\0' != *p1); p1++) { switch (*p1) { case '<': output += "&lt;"; break; case '&': output += "&amp;"; break; case '>': output += "&gt;"; break; case '"': output += "&quot;"; break; case '\'': output += "&apos;"; break; default: output += *p1; } } } #if SUPPORT_WSTRING void EscapeStringForXML(const std::wstring &input, std::string &output) { output = ""; char cbuf[3]; for (const wchar_t *p1 = input.c_str(); *p1 != L'\0'; p1++) { switch (*p1) { case L'<': output += "&lt;"; break; case L'&': output += "&amp;"; break; case L'>': output += "&gt;"; break; case L'"': output += "&quot;"; break; case L'\'': output += "&apos;"; break; default: // wide character to multi-byte wctomb(cbuf, *p1); output += *cbuf; } } } void EscapeStringForXML(const std::wstring &input, std::wstring &output) { output = L""; const wchar_t *p1 = input.c_str(); for (; (L'\0' != *p1); p1++) { switch (*p1) { case L'<': output += L"&lt;"; break; case L'&': output += L"&amp;"; break; case L'>': output += L"&gt;"; break; case L'"': output += L"&quot;"; break; case L'\'': output += L"&apos;"; break; default: output += *p1; } } } #endif // SUPPORT_WSTRING ///////////////////////////////////////////////////////////////////////////// // wstring2 #if SUPPORT_WSTRING using namespace std; char wstring2::s_buffer[MAX_WSTRING2_SIZE]; wstring2::wstring2() : wstring() { } wstring2::wstring2(const wchar_t *__s) : wstring(__s) { } wstring2::wstring2(const char *__s) { int len = strlen(__s); wchar_t *tmp = new wchar_t[len*2+1]; mbstowcs(tmp, __s, len+1); // now copy the result into our own storage *((wstring*)this) = tmp; // and get rid of the temporary buffer delete [] tmp; } const char *wstring2::mb_str() const { const wchar_t *guts = c_str(); size_t result = wcstombs(s_buffer, guts, MAX_WSTRING2_SIZE); return s_buffer; } #define WC_UTF16 static size_t encode_utf16(uint input, wchar_t *output) { if (input<=0xffff) { if (output) *output++ = (wchar_t) input; return 1; } else if (input>=0x110000) { return (size_t)-1; } else { if (output) { *output++ = (wchar_t) ((input >> 10)+0xd7c0); *output++ = (wchar_t) ((input&0x3ff)+0xdc00); } return 2; } } static size_t decode_utf16(const wchar_t *input, uint &output) { if ((*input<0xd800) || (*input>0xdfff)) { output = *input; return 1; } else if ((input[1]<0xdc00) || (input[1]>=0xdfff)) { output = *input; return (size_t)-1; } else { output = ((input[0] - 0xd7c0) << 10) + (input[1] - 0xdc00); return 2; } } static uint utf8_max[]= { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff, 0xffffffff }; size_t wstring2::from_utf8(const char *psz) { size_t safe_length = strlen(psz)+1; wchar_t *tmp = new wchar_t[safe_length*2]; wchar_t *buf = tmp; size_t n = safe_length; size_t len = 0; while (*psz && ((!buf) || (len < n))) { uchar cc = *psz++, fc = cc; unsigned cnt; for (cnt = 0; fc & 0x80; cnt++) fc <<= 1; if (!cnt) { // plain ASCII char if (buf) *buf++ = cc; len++; } else { cnt--; if (!cnt) { // invalid UTF-8 sequence return (size_t)-1; } else { unsigned ocnt = cnt - 1; uint res = cc & (0x3f >> cnt); while (cnt--) { cc = *psz++; if ((cc & 0xC0) != 0x80) { // invalid UTF-8 sequence return (size_t)-1; } res = (res << 6) | (cc & 0x3f); } if (res <= utf8_max[ocnt]) { // illegal UTF-8 encoding return (size_t)-1; } size_t pa = encode_utf16(res, buf); if (pa == (size_t)-1) return (size_t)-1; if (buf) buf += pa; len += pa; } } } if (buf && (len < n)) *buf = 0; // now copy the result into our own storage *((wstring*)this) = tmp; // and get rid of the temporary buffer delete [] tmp; return len; } const char *wstring2::to_utf8() const { char *buf = s_buffer; size_t len = 0; size_t n = MAX_WSTRING2_SIZE; const wchar_t *psz = c_str(); while (*psz && ((!buf) || (len < n))) { uint cc; #ifdef WC_UTF16 size_t pa = decode_utf16(psz, cc); psz += (pa == (size_t)-1) ? 1 : pa; #else cc=(*psz++) & 0x7fffffff; #endif unsigned cnt; for (cnt = 0; cc > utf8_max[cnt]; cnt++) {} if (!cnt) { // plain ASCII char if (buf) *buf++ = (char) cc; len++; } else { len += cnt + 1; if (buf) { *buf++ = (char) ((-128 >> cnt) | ((cc >> (cnt * 6)) & (0x3f >> cnt))); while (cnt--) *buf++ = (char) (0x80 | ((cc >> (cnt * 6)) & 0x3f)); } } } if (buf && (len<n)) *buf = 0; return s_buffer; } #endif // SUPPORT_WSTRING /** Useful function which wraps the C standard library's strtok */ void vtTokenize(char *buf, const char *delim, vtStringArray &tokens) { char *p = NULL; p = strtok(buf, delim); while (p != NULL) { tokens.push_back(vtString(p)); p = strtok(NULL, delim); } } int vtFindString(const vtStringArray &arr, const char *find) { for (size_t i = 0; i < arr.size(); i++) { if (arr[i].Compare(find) == 0) return (int) i; } return -1; } vtString vtConcatArray(const vtStringArray &arr, const char delim) { vtString cat; for (size_t i = 0; i < arr.size(); i++) { cat += arr[i]; if (i < arr.size()-1) cat += delim; } return cat; } /** Extract a string array (ie. tokenize) with the messy non-const of strtok */ void vtExtractArray(const vtString &input, vtStringArray &arr, const char delim) { int curr = 0, next, len = input.GetLength(); while ((next = input.Find(delim, curr)) != -1) { arr.push_back(vtString((const char *)input+curr, next-curr)); curr = next+1; } // and remainder after last delim if (curr != len) arr.push_back(vtString((const char *)input+curr, len-curr)); }
true
af977f9cf2d8d08e2b8817533e89721a49541a91
C++
cryptowerk/cealr
/src/properties.h
UTF-8
4,534
3.03125
3
[ "Apache-2.0" ]
permissive
/* * _____ _____ _____ ___ ______ *| __| __|/ _ \| | | _ | Command line tool for sealing files with Cryptowerk API *| |__| __| _ | |__| *|_____|_____|__| |__|______|__|\__\ https://github.com/cryptowerk/cealr * *Licensed under the Apache 2.0 License <https://opensource.org/licenses/Apache-2.0>. *Copyright (c) 2018 Cryptowerk <http://www.cryptowerk.com>. * */ #ifndef SEALER_PROPERTIES_H #define SEALER_PROPERTIES_H static const char *const DEFAULT_PROPERTIES = "~/.cealr/config.properties"; #include <iostream> #include <fstream> #include <sstream> #include <string> #include <exception> #include <map> using namespace std; /*! @brief exception thrown in case of errors during opening files */ class file_exception : public exception { private: runtime_error err_msg; public: explicit file_exception(const string &file); virtual const char *what(); }; /*! @brief handling property files as key/value maps */ class properties : private map<string, string> { private: string file; //!< physical file containing properties in form <key> = <value> bool saved; //!< is true when properties have changed, otherwise false public: /*! @brief constructor with file name @param file_name is the name of the property file */ explicit properties(const string &); properties(); ~properties(); /*! @brief reading property files into this object (interpreted as a map) This method is reading from files that contains lines in the format <key> = <value> or #<comment> and assigning it to (*this)[key] = value; */ void read_from_file(); /*! @brief getter for file name This method returns the name and the path of the properties file @return the name and the path of the properties file */ const string &getFile() const; bool operator==(const properties &) const; bool operator!=(const properties &) const; /*! @brief dumps properties into output stream This override serves the purpose of getting output for debugging. */ friend ostream &operator<<(ostream &, const properties &); /*! @brief getting a value for a key @param key the key for which the value should be returned @param default_val contains the value to be returned (default NULL) in case the key is not part of the properties @param cloneValue if true, a copy of the value is returnde, otherwise a pointer to the value in the properties @return returns the value for the key, if it was found, otherwise the value in default_val */ string *get(const string &key, string *default_val = nullptr, bool cloneValue = true); /*! @brief setting a value for a key This method is setting/changing the given value for the given key, additionally it is setting the member saved = false @param key contains the key for which the given value is to be stored @param value contains the value to be stored for the given key */ void put(const string &key, const string &val); /*! @brief deleting the key value pair from the properties This method is deleting the entry for the given key, additionally it is setting the member saved = false @param key contains the key for which the properties-entry is to be deleted */ void remove(const string &key); /*! This method is saving te properties in the right format. If the properties file is in read only mode and the current user has the privilege to change this mode, it will be set to read/write for this user before the file is saved. After the properties are saved, the file will be set to read only for the given user and all other users will have no rights for reading or writing on this property file (storing account credentials unencrypted). @throws file_exception if the user has no privilege to change the mode of the property file or if the saving of the file fails. */ void save(); /*! @brief getter for saved @return true if the properties need to be saved, otherwise false (have been changed since reading/last save) */ bool isSaved(); /*! @brief setter for file name @param fileName contains the file name for the properties */ void set_file(const string &fileName); /*! @brief Converts the relative file name to a full path name Converts the given file name in a full file name with path, if it was found @param file_name contains a relative or a file name with path @return file name with path */ static const string get_full_file_name(const string &file_name); }; #endif //SEALER_PROPERTIES_H
true
ecdc713985fe6354ffbc1aaa809b3eff542e6d7f
C++
kien-vu-uet/HomeWork
/week5/functionCallStack.cpp
UTF-8
293
3.5
4
[]
no_license
#include <iostream> using namespace std; int factorial(int x) { if (x <= 2) return x; return x * factorial(x - 1); } int main() { int N; cin >> N; cout << "x = " << N << " at " << &N << endl; cout << "Factorial of " << N << " is : " << factorial(N); return 0; }
true
cc10a67961f7740fbd9a72bc851edee0b8278c38
C++
SwagSoftware/Kisak-Strike
/ivp/havana/havok/hk_math/matrix3.h
UTF-8
2,978
3
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef HAK_MATH_MATRIX3_H #define HAK_MATH_MATRIX3_H #ifndef HK_MATH_VECMATH_H #error Include <hk_math/vecmath.h> Do not include this file directly. #endif // HK_MATH_VECMATH_H //: A generic 3x3 matrix class hk_Matrix3 { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_CONSTRAINT, hk_Matrix3) inline hk_Matrix3(); //: Empty default constructor inline ~hk_Matrix3() {} //:: Empty default destructor inline void set_elem(int row, int column, hk_real value); //: Set element (row,column) to value // No range checking is done. inline hk_real operator() (int r, int c) const; //: Get element (row, column) // No range checking is done. inline void _set_rows( const hk_Vector3& r0, const hk_Vector3& r1, const hk_Vector3& r2); //: Set all values of the matrix at once, rowwise. void set_rows( const hk_Vector3& r0, const hk_Vector3& r1, const hk_Vector3& r2); //: Set all values of the matrix at once, rowwise. void set_cols( const hk_Vector3& r0, const hk_Vector3& r1, const hk_Vector3& r2); //: Set all values of the matrix at once, rowwise. inline void _get_rows( hk_Vector3& r0, hk_Vector3& r1, hk_Vector3& r2); inline void _get_row( int row, hk_Vector3& r); void set_zero(); void set_diagonal( hk_real m00, hk_real m11, hk_real m22 ); void set_identity_rotation(); //: Sets this to be the identity // i.e. all diagonal elements set to 1, all // nondiagonal elements set 0. bool is_identity_rotation() const; void set_cross_skew( const hk_Vector3& r, const hk_Matrix3& R ); //: r x R is accomplished by converting r to the skew symetric matrix r~ // and then muliplying r~*R. void rotate ( int axis, hk_real angle ); //: rotates the matrix in place // Note: very very slow function hk_result invert(hk_real epsilon); //: Attempt to invert the matrix in place. // If the matrix is invertible, it is overwritten with // its inverse and the routine returns HK_OK. Otherwise // the matrix is left unchanged and HK_FAULT is returned. void set_rotated_diagonal_matrix( const hk_Rotation &r, const hk_Vector3 &diagonal_matrix3 ); //: this = r * matrix3(diagonal_matrix3) * r.transpose() void transpose(); void set_mul3( const hk_Matrix3& a, const hk_Matrix3& b ); void set_mul3_inv2( const hk_Matrix3& a, const hk_Rotation& b ); //: this = a * b.transpose() void set_mul3_inv( const hk_Rotation& a, const hk_Matrix3& b ); //: this = a.transpose() * b void operator +=( const hk_Matrix3& a ); void operator -=( const hk_Matrix3& a ); inline hk_real *get_elem_address(int r, int c); inline hk_Vector3& get_column(int x); inline const hk_Vector3& get_column(int x) const; protected: hk_real HK_ALIGNED_VARIABLE(m_elems[12],16); }; #endif /* HAK_MATH_MATRIX3_H */
true
597aaa07217d7451e362f54de46c7b17bf12ccd4
C++
rituraj0/Topcoder
/Old Topcoder SRM codes/CyclicGame.cpp
UTF-8
5,282
2.796875
3
[]
no_license
#include <algorithm> #include <iomanip> #include <iostream> #include <sstream> #include <cstring> #include <cstdlib> #include <climits> #include <fstream> #include <cctype> #include <cstdio> #include <string> #include <vector> #include <queue> #include <stack> #include <cmath> #include <ctime> #include <map> #include <set> using namespace std; #define pb push_back #define mp make_pair #define Y second #define X first #define fi freopen("input.txt","r",stdin) #define fo freopen("output.txt","w",stdout) const double pi = acos(-1.0); const double eps = 1e-8; vector <string> parse(string s, string c) { int len = c.length(), p = -len, np; vector <string> ans; do { np = s.find(c, p+len); ans.push_back(s.substr(p+len, np - p - len)); p = np; } while (p != string::npos); return ans; } /*Solution code starts here */ class CyclicGame { public: double estimateBank(vector <int> cells) { int n=cells.size(); vector<double> dp(n,0),temp(n,0); double ans=0.0; for(int it=0;it<100000;it++) { for(int i=0;i<n;i++) { double tp=0; for(int j=1;j<=6;j++) { int k=(i+j)%n; tp+=(double)cells[k] +dp[k]; } tp=tp/6.0; tp=max(0.0,tp); temp[i]=tp; } dp=temp; ans=max(ans,dp[0]); } return ans; } }; double test0() { int t0[] = {-10, 1, 1, 1, 1, 1, 1, 1, 1}; vector <int> p0(t0, t0+sizeof(t0)/sizeof(int)); CyclicGame * obj = new CyclicGame(); clock_t start = clock(); double my_answer = obj->estimateBank(p0); clock_t end = clock(); delete obj; cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl; double p1 = 1.3611111111111112; cout <<"Desired answer: " <<endl; cout <<"\t" << p1 <<endl; cout <<"Your answer: " <<endl; cout <<"\t" << my_answer <<endl; if (p1 != my_answer) { cout <<"DOESN'T MATCH!!!!" <<endl <<endl; return -1; } else { cout <<"Match :-)" <<endl <<endl; return (double)(end-start)/CLOCKS_PER_SEC; } } double test1() { int t0[] = {-10, 7, -5, 7}; vector <int> p0(t0, t0+sizeof(t0)/sizeof(int)); CyclicGame * obj = new CyclicGame(); clock_t start = clock(); double my_answer = obj->estimateBank(p0); clock_t end = clock(); delete obj; cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl; double p1 = 0.30434782608695654; cout <<"Desired answer: " <<endl; cout <<"\t" << p1 <<endl; cout <<"Your answer: " <<endl; cout <<"\t" << my_answer <<endl; if (p1 != my_answer) { cout <<"DOESN'T MATCH!!!!" <<endl <<endl; return -1; } else { cout <<"Match :-)" <<endl <<endl; return (double)(end-start)/CLOCKS_PER_SEC; } } double test2() { int t0[] = {-1, -2, 2}; vector <int> p0(t0, t0+sizeof(t0)/sizeof(int)); CyclicGame * obj = new CyclicGame(); clock_t start = clock(); double my_answer = obj->estimateBank(p0); clock_t end = clock(); delete obj; cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl; double p1 = 0.0; cout <<"Desired answer: " <<endl; cout <<"\t" << p1 <<endl; cout <<"Your answer: " <<endl; cout <<"\t" << my_answer <<endl; if (p1 != my_answer) { cout <<"DOESN'T MATCH!!!!" <<endl <<endl; return -1; } else { cout <<"Match :-)" <<endl <<endl; return (double)(end-start)/CLOCKS_PER_SEC; } } double test3() { int t0[] = {-40, 9, 9, 9, 9, 9, -44, 9, 9, 9, 9, 9, -40, 15, 15}; vector <int> p0(t0, t0+sizeof(t0)/sizeof(int)); CyclicGame * obj = new CyclicGame(); clock_t start = clock(); double my_answer = obj->estimateBank(p0); clock_t end = clock(); delete obj; cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl; double p1 = 3.5653612433724144; cout <<"Desired answer: " <<endl; cout <<"\t" << p1 <<endl; cout <<"Your answer: " <<endl; cout <<"\t" << my_answer <<endl; if (p1 != my_answer) { cout <<"DOESN'T MATCH!!!!" <<endl <<endl; return -1; } else { cout <<"Match :-)" <<endl <<endl; return (double)(end-start)/CLOCKS_PER_SEC; } } double test4() { int t0[] = {-36, 95, -77, -95, 49, -52, 42, -34, -1, 98, -20, 96, -96, 23, -52}; vector <int> p0(t0, t0+sizeof(t0)/sizeof(int)); CyclicGame * obj = new CyclicGame(); clock_t start = clock(); double my_answer = obj->estimateBank(p0); clock_t end = clock(); delete obj; cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl; double p1 = 12.395613307567126; cout <<"Desired answer: " <<endl; cout <<"\t" << p1 <<endl; cout <<"Your answer: " <<endl; cout <<"\t" << my_answer <<endl; if (p1 != my_answer) { cout <<"DOESN'T MATCH!!!!" <<endl <<endl; return -1; } else { cout <<"Match :-)" <<endl <<endl; return (double)(end-start)/CLOCKS_PER_SEC; } } int main() { int time; bool errors = false; time = test0(); if (time < 0) errors = true; time = test1(); if (time < 0) errors = true; time = test2(); if (time < 0) errors = true; time = test3(); if (time < 0) errors = true; time = test4(); if (time < 0) errors = true; if (!errors) cout <<"You're a stud (at least on the example cases)!" <<endl; else cout <<"Some of the test cases had errors." <<endl; }
true
5437a12bafe9521850c5eca3eebedb2c4ed9e154
C++
nicoaraandrei/Flock-behaviour
/MovingEntity.h
UTF-8
2,469
2.671875
3
[]
no_license
#pragma once #define GLM_ENABLE_EXPERIMENTAL #include <glm/glm.hpp> #include <glm/gtx/norm.hpp> #include "SpriteBatch.h" #include "TileSheet.h" #include "BaseEntity.h" #include "SteeringBehaviors.h" class SteeringBehaviors; class MovingEntity : public BaseEntity { public: MovingEntity() : BaseEntity(0) {} MovingEntity(glm::vec2 pos, float rotation, glm::vec2 velocity, float mass, float maxForce, float maxSpeed, float maxTurnRate, float scale, const std::string& texturePath); ~MovingEntity(); void init(glm::vec2 pos, float rotation, glm::vec2 velocity, float mass, float maxForce, float maxSpeed, float maxTurnRate, float scale, const std::string& texturePath); void draw(SpriteBatch& spriteBatch); //return true when the life time is zero void update(float deltaTime); glm::vec2 getVelocity()const { return _velocity; } void setVelocity(glm::vec2 newVel) { _velocity = newVel; } float getMass()const { return _mass; } glm::vec2 getSide()const { return _side; } float getMaxSpeed()const { return _maxSpeed; } void setMaxSpeed(float newSpeed) { _maxSpeed = newSpeed; } float getMaxForce()const { return _maxForce; } void setMaxForce(float newForce) { _maxForce = newForce; } bool isSpeedMaxedOut() const { return _maxSpeed * _maxSpeed >= glm::length2(_velocity); } float getSpeed()const { return _velocity.length(); } float getSpeedSq()const { return glm::length2(_velocity); } glm::vec2 getDirection()const { return _direction; } void setDirection(glm::vec2 direction); bool rotateDirectionToFacePosition(glm::vec2 target); float getMaxTurnRate()const { return _maxTurnRate; } void setMaxTurnRate(float val) { _maxTurnRate = val; } void setTarget(glm::vec2 target) { _target = target; } glm::vec2 getTarget()const { return _target; } void setTargetEntity(MovingEntity* targetEntity) { _targetEntity = targetEntity; } MovingEntity* getTargetEntity()const { return _targetEntity; } SteeringBehaviors* getSteering()const { return _steering; } private: //float _speed; glm::vec2 _velocity; glm::vec2 _direction; //perpendicular with the direction vector glm::vec2 _side; glm::vec2 _target; MovingEntity* _targetEntity; float _mass; float _maxSpeed; //maximum force this entity can produce to move itself float _maxForce; //maximum rate(radians per second) can this entity rotate float _maxTurnRate; SteeringBehaviors* _steering; TileSheet _texture; float _animTime = 0.0f; float _animSpeed = 0.1f; };
true
633bb8364f62c9be7dccd4a9157f9080e08a06f4
C++
hubartstephane/Code
/libraries/chaos/src/Deprecated/BitmapFontTextMeshBuilder.cpp
UTF-8
4,726
2.796875
3
[]
no_license
#include "chaos/ChaosPCH.h" #include "chaos/ChaosInternals.h" namespace chaos { void BitmapFontTextMeshBuilder::InsertVertexComponent(std::vector<float> & vertices, glm::vec2 const & v, glm::vec2 const & t) { vertices.push_back(v.x); vertices.push_back(v.y); vertices.push_back(t.x); vertices.push_back(1.0f - t.y); // the characters in the bitmap are in the direction of reading (top to bottom). That's not the texture coordinates } box2 BitmapFontTextMeshBuilder::BuildBuffer(char const * msg, BitmapFontTextMeshBuilder::Params const & params, std::vector<float> & vertices) const { assert(msg != nullptr); size_t initial_vertex_count = vertices.size(); box2 result; int char_in_line = 0; float tex_size_x = 1.0f / (float)params.font_characters_per_line; float tex_size_y = 1.0f / (float)params.font_characters_line_count; float x = params.position.x; float y = params.position.y; float dx = params.character_size.x; float dy = -params.character_size.y; float next_char = params.character_size.x + params.spacing.x; float next_line = -params.character_size.y - params.spacing.y; // we want the Y = 0 to be the TOPLEFT position of the text. To match natural OpenGL system, the remining characters are in negative Y axix float next_tab = next_char * (float)(params.tab_size); vertices.reserve(vertices.size() + 6 * 4 * strlen(msg)); // 6 vertex per characters, 4 float per vertex for (int i = 0 ; msg[i] != 0 ; ++i) // each characters of the final string { char c = msg[i]; if (c == '\r') // ignore chariot return (UNIX/WINDOWS differences) continue; if (c == '\n') // next line { x = params.position.x; y = y + next_line; char_in_line = 0; continue; } if (c == '\t') // tabulations { if (params.line_limit <= 0) x += next_tab; else { for (int j = 0 ; j < params.tab_size ; ++j) { if (++char_in_line >= params.line_limit) { x = params.position.x; y = y + next_line; char_in_line = 0; } else x += next_char; } } continue; } char const * tmp = strchr(&params.font_characters[0], c); if (tmp != nullptr) { size_t char_index = (tmp - &params.font_characters[0]); size_t char_x = (char_index % params.font_characters_per_line); size_t char_y = (char_index / params.font_characters_per_line); float a = ((float)char_x) * tex_size_x; float b = ((float)char_y) * tex_size_y; // compute the 4 texture coordinates glm::vec2 tb = glm::vec2(a, b); float cx = params.crop_texture.x; float cy = params.crop_texture.y; glm::vec2 t1 = tb + glm::vec2(cx , cy); glm::vec2 t2 = tb + glm::vec2(tex_size_x - cx, cy); glm::vec2 t3 = tb + glm::vec2(tex_size_x - cx, tex_size_y - cy); glm::vec2 t4 = tb + glm::vec2(cx , tex_size_y - cy); // compute the 4 vertex coordinates glm::vec2 v1 = glm::vec2(x, y); glm::vec2 v2 = v1 + glm::vec2(dx, 0.0f); glm::vec2 v3 = v2 + glm::vec2(0.0f, dy); glm::vec2 v4 = v1 + glm::vec2(0.0f, dy); // insert the triangles InsertVertexComponent(vertices, v1, t1); InsertVertexComponent(vertices, v3, t3); InsertVertexComponent(vertices, v2, t2); InsertVertexComponent(vertices, v1, t1); InsertVertexComponent(vertices, v4, t4); InsertVertexComponent(vertices, v3, t3); ExtendBox(result, v1); ExtendBox(result, v3); } // next character x = x + next_char; if (params.line_limit > 0) { if (++char_in_line >= params.line_limit) { x = params.position.x; y = y + next_line; char_in_line = 0; } } } // recenter the whole box glm::vec2 offset(0.0f, 0.0f); if ((int(params.hotpoint) & int(Hotpoint::RIGHT)) != 0) offset.x = -2.0f * result.half_size.x; else if ((int(params.hotpoint) & int(Hotpoint::LEFT)) == 0) // horizontal middle offset.x = -result.half_size.x; if ((int(params.hotpoint) & int(Hotpoint::BOTTOM)) != 0) offset.y = 2.0f * result.half_size.y; else if ((int(params.hotpoint) & int(Hotpoint::TOP)) == 0) // vertical middle offset.y = result.half_size.y; if (offset.x != 0.0f || offset.y != 0.0f) ApplyVertexOffset(vertices, offset, initial_vertex_count, vertices.size()); return result; } void BitmapFontTextMeshBuilder::ApplyVertexOffset(std::vector<float> & vertices, glm::vec2 const & offset, size_t start, size_t end) { int const PER_VERTEX_COMPONENT = 4; for (size_t i = start ; i < end ; i += PER_VERTEX_COMPONENT) { vertices[i + 0] += offset.x; vertices[i + 1] += offset.y; } } }; // namespace chaos
true
a8568c5963299fc7af77f6e1dd0d5726bd5a047a
C++
kdurant/qt_study
/src/motor/PusiController.cpp
UTF-8
19,730
2.984375
3
[]
no_license
/* * 1. 具有两个限位开关,分别对应着EXT1, 和EXT2 * 2. 当电机运动到限位开关,触发EXT1或EXT2,此时断电。 * 再重启后,还往限位开关所在的方向运动,会导致电机抖动,且不触发EXT1或EXT2信号 * 3. 运动方向设置为方向时,对应限位开关为EXT1 * 4. 上电读取电机位置为0, 不同的运动方向会导致数据溢出 */ #include "PusiController.h" MotorController::MOTOR_STATUS PusiController::init() { return NO_FEATURE; } MotorController::MOTOR_STATUS PusiController::run(quint16 speed) { return NO_FEATURE; } /** * @brief 步进电机,以当前位置为起点,移动指定step * * @param postion * @param direct, 1, 正向; 0, 反向 * * @return */ MotorController::MOTOR_STATUS PusiController::moveToPosition(double postion, int direct) { if(direct) setMoveDirect(PusiController::POSITIVE); else setMoveDirect(PusiController::NEGTIVE); turnStepsByNum(postion); return MOTOR_STATUS::SUCCESS; } bool PusiController::moveToHome() { bool status; int postion; int reSendCnt = 0; writeBlockTriggerValue(0xff); writeBlockLen(0x2f); writeBlockRegister(0x01); clearExit1MarkBit(); clearExit2MarkBit(); setMaxTurnSpeed(2000); postion = readCurrentPosition(); qDebug() << "step1: 反转,找EXT1"; setMoveDirect(PusiController::NEGTIVE); // 找EXT1 turnStepsByNum(2000); readControl1(reg1); if(reg1.bit1_ext1 == 1) { qDebug() << "step1-a: 找到EXT1"; clearExit1MarkBit(); goto start_pos; } qDebug() << "step2: 正转,找EXT2"; setMoveDirect(PusiController::POSITIVE); // 找EXT2 turnStepsByNum(2000); readControl1(reg1); if(reg1.bit2_ext2 == 1) { qDebug() << "step2-a: 找到EXT2"; clearExit2MarkBit(); } qDebug() << "step3: 一直反转,直到找到EXT1"; setMoveDirect(PusiController::NEGTIVE); reSendCnt = 0; while(reg1.bit1_ext1 == 0) { status = turnStepsByNum(50000); // 刚好是从EXT2到EXT1需要的步数 readControl1(reg1); reSendCnt++; if(reSendCnt > 10) { return false; } } reSendCnt = 0; while(reg1.bit1_ext1 == 1 || reg1.bit2_ext2 == 1) { clearExit1MarkBit(); clearExit2MarkBit(); qDebug() << "step3-a: 清除EXT1,EXT2"; Common::sleepWithoutBlock(500); readControl1(reg1); reSendCnt++; if(reSendCnt > 10) { return false; } } start_pos: qDebug() << "step4: 正转1864step, 归零完成"; setMoveDirect(PusiController::POSITIVE); turnStepsByNum(1864); setCurrentPosition(0); return true; } bool PusiController::moveFixSpeed(quint32 speed) { return false; } qint32 PusiController::getActualVelocity() { return 0; } qint32 PusiController::getActualPosition() { return static_cast<int>(readCurrentPosition()); } /** * @brief 控制电机运动指定的步数 * @param nSteps * @return 如果电机实际运动的步数过小,说明碰到了限位开关 * 如果限位开关标志被置1,正常 * 如果限位开关标志没有被置1,说明上次刚好停在限位开关位置 */ bool PusiController::turnStepsByNum(qint32 nSteps) { if(nSteps < 1) nSteps = 1; if(nSteps > 0x7fffffff) nSteps = 0x7fffffff; qDebug() << " ------------运动起始位置:" << readCurrentPosition(); QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::TURN_STEPS, nSteps); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); readControl1(reg1); while(reg1.bit0_status != 0) // 等待电机运动结束 { Common::sleepWithoutBlock(500); readControl1(reg1); } qDebug() << " ############运动停止位置:" << readCurrentPosition(); return true; } bool PusiController::setSteps(qint32 nSteps) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_SUB_DIVISION, nSteps); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::clearBlockStatus(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::CLEAR_BLOCK_STATUS, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::saveAllParas() { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SAVE_ALL_PARA, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } qint32 PusiController::readCurrentPosition(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_CURRENT_POSITION, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); if(isRecvNewData) { isRecvNewData = false; if(compareCheckSum(recvData)) { if(getCommand(recvData) == 0xff) return getData(recvData); } } return -1; } bool PusiController::setMoveDirect(MOVE_DIRECT direct) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_MOVE_DIRECT, direct); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setMaxTurnSpeed(qint32 nSpeed) { if(nSpeed < 1) nSpeed = 1; if(nSpeed > 16000) nSpeed = 16000; QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_MAX_SPEED, nSpeed); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::ReadReduceCoeff(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_DECELE_COEFF, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::readAcceCoeff(qint8 cAddr) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_ACCE_COEFF, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setMaxElectric(qint32 nElectric) { if(nElectric < 200) nElectric = 200; if(nElectric > 4000) nElectric = 4000; QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_MAX_ELECTRIC, nElectric); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setOutStopEnable(qint32 nStopEnable) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_OUT_STOP_ENABLE, nStopEnable); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } qint32 PusiController::readElectricValue(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_ELECTRIC_VALUE, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return 0; } qint32 PusiController::readSubDiviSion(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_SUB_DIVISION, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); if(isRecvNewData) { isRecvNewData = false; if(compareCheckSum(recvData)) { if(getCommand(recvData) == 0xff) return getData(recvData); } } return -1; } // 0x71 qint32 PusiController::readSpeedSetting(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_SPEED_SETTING, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); if(isRecvNewData) { isRecvNewData = false; if(compareCheckSum(recvData)) { if(getCommand(recvData) == 0xff) return getData(recvData); } } return -1; } bool PusiController::setReduceCoeff(qint32 coeff) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_REDUCE_COEFF, coeff); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setAutoElectricReduceEnable(WORK_STATUS status) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_AUTO_ELECTRIC_REDUCE_ENABLE, status); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setOfflineEnable(WORK_STATUS status) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_OFFLINE_ENABLE, status); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setCurrentPosition(qint32 nCurrentPosition) { if(nCurrentPosition < 0) nCurrentPosition = 0; if(nCurrentPosition > 0x7fffffff) nCurrentPosition = 0x7fffffff; QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_CURRENT_POSITION, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } qint32 PusiController::readControl1(Status_Reg1& ret) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_CONTROL_STATUS1, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); if(isRecvNewData) { isRecvNewData = false; if(compareCheckSum(recvData)) { if(getCommand(recvData) == 0xff) { quint32 data = getData(recvData); ret.bit0_status = data & 0x01; ret.bit1_ext1 = (data >> 1) & 0x01; ret.bit2_ext2 = (data >> 2) & 0x01; ret.bit3_auto_dec = (data >> 3) & 0x01; ret.bit4_stall = (data >> 4) & 0x01; return 0; } } } return -1; } void PusiController::clearExit2MarkBit(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::CLEAR_EXT_STOP2_FLAG, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); } void PusiController::clearExit1MarkBit(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::CLEAR_EXT_STOP1_FLAG, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); } bool PusiController::readIO(qint32 nAddr) { if(nAddr < 0) nAddr = 0; if(nAddr > 0x3ff) nAddr = 0x3ff; QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_IO_VALUE, nAddr); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::writeIO(qint32 nAddr) { if(nAddr < 0) nAddr = 0; if(nAddr > 0xff) nAddr = 0xff; QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::WRITE_IO_VALUE, nAddr); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::writeDriveAddr(qint8 cAddr, qint32 nAddr) { if(nAddr < 1) nAddr = 1; if(nAddr > 120) nAddr = 120; QByteArray frame; frame.append(0xA5); frame.append(cAddr); frame.append(0x77); frame.append(nAddr); frame.append(nAddr >> 8); frame.append(nAddr >> 16); frame.append(nAddr >> 24); frame.append(calcFieldCRC(frame)); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setAcceCoeff(qint32 nAcceCoeff) { if(nAcceCoeff < 0) nAcceCoeff = 0; if(nAcceCoeff > 5) nAcceCoeff = 5; QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_ACCE_COEFF, nAcceCoeff); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::stopTurning(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::STOP_CURRENT_TURN, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setOutTriggerMode(qint32 nTriggerMode) { if(nTriggerMode < 0) nTriggerMode = 0; if(nTriggerMode > 3) nTriggerMode = 3; QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_OUT_TRIGGER_MODE, nTriggerMode); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } qint32 PusiController::readOutTriggerMode(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::GET_OUT_TRIGGER_MODE, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return 0; } bool PusiController::setOfflineAutoRun(WORK_STATUS status) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_OFFLINE_AUTO_RUN, WORK_STATUS::ENABLE); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } qint32 PusiController::readHardwareVersion(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_HARDWARE_VERSION, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setStartTurnSpeed(qint32 nStartSpeed) { if(nStartSpeed != 0) { if(nStartSpeed < 65) nStartSpeed = 65; if(nStartSpeed > 3000) nStartSpeed = 3000; } QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_START_SPEED, nStartSpeed); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setElectricCompensatoryFactor(qint32 nElectricCompensatoryFactor) { if(nElectricCompensatoryFactor != 0) { if(nElectricCompensatoryFactor < 100) nElectricCompensatoryFactor = 100; if(nElectricCompensatoryFactor > 1200) nElectricCompensatoryFactor = 1200; } QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_ELECTRIC_COMPENSATORY_FACTOR, nElectricCompensatoryFactor); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setSpeedMode(WORK_STATUS status) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_SPEED_MODE_ENABLE, status); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } qint32 PusiController::readControl2(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_CONTROL_STATUS2, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return 0; } bool PusiController::setSpeedCompensatoryFactor(qint32 data) { if(data != 0) //=0为读取 { if(data < 300) data = 300; if(data > 2000) data = 2000; } QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_SPEED_COMPENSATORY_FACTOR, data); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setAutoElectricReduceCoeff(qint32 nReduceCoeff) { if(nReduceCoeff < 1) nReduceCoeff = 1; if(nReduceCoeff > 4) nReduceCoeff = 4; QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_AUTO_ELECTRIC_REDUCE_COEFF, nReduceCoeff); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } qint32 PusiController::readBlockLen(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::WRITE_OR_READ_BLOCK_LENGTH, 0x4f); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); if(isRecvNewData) { isRecvNewData = false; if(compareCheckSum(recvData)) { if(getCommand(recvData) == 0xff) return getData(recvData); } } return -1; return true; } // 2. 使用0x54设置堵转触发值 bool PusiController::writeBlockLen(qint32 len) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::WRITE_OR_READ_BLOCK_LENGTH, len); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } bool PusiController::setStopSpeed(qint32 nStopSpeed) { if(nStopSpeed != 0) { if(nStopSpeed < 65) nStopSpeed = 65; if(nStopSpeed > 3000) nStopSpeed = 3000; } QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::SET_STOP_SPEED, nStopSpeed); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } // 4. 使用0x58命令读取指令位置 qint32 PusiController::readBlockPosition(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_BLOCK_POSITION, 1); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); if(isRecvNewData) { isRecvNewData = false; if(compareCheckSum(recvData)) { if(getCommand(recvData) == 0xff) return getData(recvData); } } return -1; } qint32 PusiController::readBlockRegister() { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::WRITE_OR_READ_BLOCK_REGISTER, 0x0f); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); if(isRecvNewData) { isRecvNewData = false; if(compareCheckSum(recvData)) { if(getCommand(recvData) == 0xff) return getData(recvData); } } return -1; } // 3. 使用0x59设置堵转寄存器 bool PusiController::writeBlockRegister(qint32 reg) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::WRITE_OR_READ_BLOCK_REGISTER, reg); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } qint32 PusiController::readBlockTriggerValue(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::WRITE_OR_READ_BLOCK_TRIGGER_VALUE, 1024); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); if(isRecvNewData) { isRecvNewData = false; if(compareCheckSum(recvData)) { if(getCommand(recvData) == 0xff) return getData(recvData); } } return -1; } // 1. 使用0x5a设置堵转触发值 bool PusiController::writeBlockTriggerValue(qint32 value) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::WRITE_OR_READ_BLOCK_TRIGGER_VALUE, value); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; } qint32 PusiController::ReadAutoElectricReduceCoeff(void) { QByteArray frame = encode(deviceAddr, INSTRUCTION_SET::READ_AUTO_REDUCE_COEFF, 0); emit sendDataReady(MasterSet::MOTOR_PENETRATE, frame.length(), frame); waitResponse(delayMs); return true; }
true
6d6658a1fac91814bdd5f7f6d6126b78ce236e94
C++
getov/TopCoder
/TopCoder SRM solutions/SRM 238 DIV 2 Level One (250)/ArrayHash.cpp
UTF-8
800
3.515625
4
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; class ArrayHash { public: int getHash(vector<string>); }; int ArrayHash::getHash(vector<string> input) { int hash = 0; for (int i = 0; i < input.size(); ++i) { for (int j = 0; j < input[i].size(); ++j) { hash += (input[i][j] - 65) + i + j; } } return hash; } int main() { vector<string> coll; coll.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); coll.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); coll.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); coll.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); coll.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); coll.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); ArrayHash test; cout << test.getHash(coll) << endl; return EXIT_SUCCESS; }
true
d22b9e14d7f92910b0d37476118eff934479fd1a
C++
zhangscth/Tflite
/gemm_support.h
UTF-8
1,485
2.625
3
[]
no_license
#ifndef TENSORFLOW_CONTRIB_LITE_KERNELS_GEMM_SUPPORT_H_ #define TENSORFLOW_CONTRIB_LITE_KERNELS_GEMM_SUPPORT_H_ #include "gemmlowp.h" #include "context.h" namespace tflite { namespace gemm_support { // Returns the GemmContext stored in 'context', allowing multiple ops to // share a single object, as long as they share a TfLiteContext. The caller // must ensure that this is called between IncrementUsageCounter() and // DecrementUsageCounter(). For example, in the implementation of an op: // void* Init(TfLiteContext* context, const char*, size_t) { // gemm_support::IncrementUsageCounter(context); // return nullptr; // } // void Free(TfLiteContext* context, void*) { // gemm_support::DecrementUsageCounter(context); // } // TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { // auto* gemm_context = gemm_support::GetFromContext(context); // } gemmlowp::GemmContext* GetFromContext(TfLiteContext* context); // Let the framework know that the GemmContext stored in 'context' will be used // by an op. If necessary a new GemmContext is created and placed in 'context'. void IncrementUsageCounter(TfLiteContext* context); // Let the framework know that the op stopped using the GemmContext stored in // 'context'. If there are no more usages the GemmContext will be deleted. void DecrementUsageCounter(TfLiteContext* context); } // namespace gemm_support } // namespace tflite #endif // TENSORFLOW_CONTRIB_LITE_KERNELS_GEMM_SUPPORT_H_
true
94aaf5ed51fa248f6acd39137f9ccb3373b7cdbe
C++
matheusmollon/ArduinoProjects
/CofreDigital/configuracao_cofre.ino
UTF-8
1,401
2.875
3
[]
no_license
/* Projeto Confre digital simples * Componentes: Display LCD 16X2, Teclado matricial 4X3, Buzzer e led RGB. * Autor: Matheus Fernando Mollon * Data: 16/02/2016 * Versão: 1.0 * Observações: este código é open-source. Logo, é permitido sua utilização e alteração, * sendo proibida venda deste projeto ou parte do mesmo. */ #include <EEPROM.h> // importa a biblioteca da EEPROM int estaFechado = 1; // cofre está fechado em uma situação inicial int endereco = 0; // percorre os endereços para leitura e escrita na EEPROM int senhaPadrao[6] = {0, 0, 0, 0, 0, 0}; // vetor de senha int value; // exibir os dados da EEPROM void setup() { //Gravar status padrão do cofre EEPROM.write(endereco, estaFechado); // grava o estado inicial do cofre endereco++; // Gravando a senha padrão while (endereco < 7) { EEPROM.write(endereco, senhaPadrao[endereco - 1]); // grava a senha padrão do cofre endereco++; } //Ativando serial para leitura Serial.begin(9600); endereco = 0; while (endereco < 7) { // percorre os endereços em que os dados foram armazenados, exibindo seus conteúdos. // lê o byte no endereço atual da EEPROM value = EEPROM.read(endereco); // envia o valor lido para o computador pela porta serial Serial.print(endereco); Serial.print("\t"); Serial.print(value); Serial.println(); endereco++; } } void loop() {}
true
ebb6de93a9f0119ee8f644469d240aae973d993c
C++
LiuXiahong/test
/c++/src/树状数组/tree.cpp
UTF-8
378
2.828125
3
[]
no_license
#include<stdio.h> int n; int a[100]; int c[100]; int lowbit(int i) { return i&(-i); } int sum(int m) { int s=0; while(m>0) { s+=c[m]; m-=lowbit(m); } return s; } void update(int i,int value) { while(i<=n) { c[i]+=value; i+=lowbit(i); } } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&a[i]); update(i,a[i]); } printf("%d",sum(3)); }
true
89442a1208d06d06cbad44f00b5711920524250c
C++
Athorcis/athorrent-backend
/include/TorrentManager.h
UTF-8
1,708
2.515625
3
[]
no_license
#ifndef TORRENT_MANAGER_H #define TORRENT_MANAGER_H #include <libtorrent/session.hpp> #include <string> #include <vector> class AlertManager; class ResumeDataManager; class TorrentManager { public: TorrentManager(const std::string & port); void createTorrent(const libtorrent::torrent_handle & handle); libtorrent::session & getSession(); AlertManager & getAlertManager(); ResumeDataManager & getResumeDataManager(); const std::string & getResumeDataPath() const; void writeBencodedTree(const std::string & path, const libtorrent::entry & entry); bool hasTorrent(libtorrent::sha1_hash hash) const; bool hasTorrent(const std::string & hash) const; libtorrent::torrent_handle getTorrent(libtorrent::sha1_hash hash) const; libtorrent::torrent_handle getTorrent(const std::string & hash) const; std::vector<libtorrent::torrent_handle> getTorrents(); bool pauseTorrent(const std::string & hash); bool resumeTorrent(const std::string & hash); bool removeTorrent(const std::string & hash); std::string addTorrentFromFile(const std::string & path, bool resumeData = false); void addTorrentsFromDirectory(const std::string & path); std::string addTorrentFromMagnet(const std::string & uri); private: std::string m_torrentsPath = "cache/torrents"; std::string m_resumeDataPath = "cache/fastresume"; std::string m_filesPath = "files"; libtorrent::session m_session; ResumeDataManager * m_resumeDataManager; AlertManager * m_alertManager; }; #endif /* TORRENT_MANAGER_H */
true
662de39325fe4db8375d529e461ed35afd539cbb
C++
Koutarouu/CPP-Codes
/Poo5.cpp
ISO-8859-2
1,581
3.84375
4
[]
no_license
//Crear un programa que tenga la siguiente jerarquia de clases y hacer polimorfismo con el mtodo comer() #include<iostream> #include<stdlib.h> using namespace std; class Animal{ private: string nombre; int edad; public: Animal(string,int); virtual void comer(); }; class Humano : public Animal{ private: string comidafav; public: Humano(string,int,string); void comer(); }; class Perro : public Animal{ private: string comidafav; string raza; public: Perro(string,int,string,string); void comer(); }; Animal::Animal(string _nombre, int _edad){ nombre = _nombre; edad = _edad; } void Animal::comer(){ cout<<"El animal con el nombre de: "<<nombre<<" esta comiendo:"<<endl; } Humano::Humano(string _nombre,int _edad,string _comidafav) : Animal(_nombre,_edad){ comidafav = _comidafav; } void Humano::comer(){ Animal::comer(); cout<<"Su comida favorita la cual es: "<<comidafav<<" y come con cubiertos."<<endl; } Perro::Perro(string _nombre,int _edad,string _comidafav,string _raza) : Animal(_nombre,_edad){ comidafav = _comidafav; raza = _raza; } void Perro::comer(){ Animal::comer(); cout<<"Su comida favorita la cual es: "<<comidafav<<" y como es un perro come en el piso."<<endl; cout<<"Y su raza es "<<raza<<endl; } int main(){ Animal *vector[3]; vector[0] = new Humano("Diego",18,"vegetales"); vector[1] = new Humano("Perro",33,"noc"); vector[2] = new Perro("Perroperro",5,"zanahorias","Dalmata"); vector[0]->comer(); cout<<endl; vector[1]->comer(); cout<<endl; vector[2]->comer(); system("pause"); return 0; }
true
00b3b331100df53fced7304dae9ad1216f4d6fc6
C++
Opehline/CPP_V2
/Basiskurs Hausaufgabendateien/HA2_Praepozessorzeug.cpp
WINDOWS-1252
1,387
3.59375
4
[]
no_license
// Tanja TTreffler // Hausaufgabe von Dienstag // Aufgaben aus ppt /* + Ein Programm schreiben das typedef, const, Schalter und auto enthlt. + Es soll zwei float Zahlen multiplizieren: x=a*b; + Die Faktoren sollen mit gleitkommazahl deklariert werden: gleitkommazahl a, b; + Das Resultat soll durch auto bestimmt sein: auto x; ~ Es soll der Datentyp von x auf dem Bildschirm ausgegeben werden. + Es soll die Lsung auf dem Bildschirm ausgegeben werden. + Alle Ausgaben in einer Funktion verlegen. + Fortgeschritten: Es soll mglich sein die Ausgabe des Datentyps auszuschalten mit einem Schalter: #if ... #endif */ // #if // Fallunterschiedung aufgrund eines koonstanten Ausdrucks (0 oder nicht 0) #include <iostream> #include <cstdlib> #include <typeinfo> #define schalten 4 // #define: Setzt einen Schlater // #undef Setzt schalter zurck // wenn !0 Datentypausgabe void ausgaben(auto x){ #if schalten // Bei 0 keine Ausgabe, sonst schon // Datentypausgabe std::cout << "Der Datentyp des Produkts ist " << typeid(x).name() << std::endl; #endif // 0 std::cout << "Das Produkt von der Multiplikation ist " << x << "." << std::endl; } int main(int argc, char **argv){ typedef float gleitkommazahl; gleitkommazahl b; const gleitkommazahl a = 3.5; b = 234.5; // Multiplikation auto x = a * b; ausgaben(x); return 0; }
true
4e3f4301eedded5c2c1079ae8d1869bcf7802f6a
C++
bericp1/csci-1300-assignment10-create-a-world
/foreground_map_plot.cpp
UTF-8
540
2.59375
3
[ "MIT" ]
permissive
#include "foreground_map_plot.h" // Forward to ForegroundMapPlo::pull_from_file ForegroundMapPlot::ForegroundMapPlot(std::ifstream& file_stream) {this->pull_from_file(file_stream);} void ForegroundMapPlot::pull_from_file(std::ifstream& file_stream){ // Read the next line from the stream and store it as the type std::getline(file_stream, this->type_); // Pass the rest off to MapPlot::generate_from_file this->data(MapPlot::generate_from_file(file_stream)); } std::string ForegroundMapPlot::type(){ return this->type_; }
true
ab99367f628c82edc152e2a2274d59855d89881d
C++
98teg/LearningOpenGL
/Ep22-23-24/tests/TestTexture2D.hpp
UTF-8
1,727
2.609375
3
[]
no_license
#include "Test.hpp" #include "../Texture.hpp" #ifndef TESTTEXTURE2D_HPP #define TESTTEXTURE2D_HPP namespace test{ class TestTexture2D: public Test{ private: glm::vec3 TranslationA; glm::vec3 TranslationB; glm::mat4 Proj; glm::mat4 View; Shader ThisShader; VertexArray* Vertex_array; VertexBuffer* Vertex_buffer; IndexBuffer* Index_buffer; Texture ThisTexture; Renderer renderer; inline glm::vec3 GetTranslationA() const{return TranslationA;}; inline glm::vec3 GetTranslationB() const{return TranslationB;}; inline float* GetPtrTranslationA() {return &(TranslationA.x);}; inline float* GetPtrTranslationB() {return &(TranslationB.x);}; inline Shader* GetShader() {return &ThisShader;}; inline VertexArray* GetVertexArray() {return Vertex_array;}; inline VertexBuffer* GetVertexBuffer() {return Vertex_buffer;}; inline IndexBuffer* GetIndexBuffer() {return Index_buffer;}; inline glm::mat4 GetProj() const{return Proj;}; inline glm::mat4 GetView() const{return View;}; inline void SetTranslationA(const glm::vec3& trans) {TranslationA = trans;}; inline void SetTranslationB(const glm::vec3& trans) {TranslationB = trans;}; inline void SetProj(const glm::mat4& proj) {Proj = proj;}; inline void SetView(const glm::mat4& view) {View = view;}; inline void SetVertexArray(VertexArray* vertex_array) {Vertex_array = vertex_array;}; inline void SetVertexBuffer(VertexBuffer* vertex_buffer) {Vertex_buffer = vertex_buffer;}; inline void SetIndexBuffer(IndexBuffer* index_buffer) {Index_buffer = index_buffer;}; public: TestTexture2D(); ~TestTexture2D(); void OnRender() override; void OnImGuiRender() override; }; } #endif
true