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
3285ced39627529296aba41651b68e56f040d59b
C++
FusionBolt/CraftUI
/utils/Timer.h
UTF-8
807
2.609375
3
[ "MIT" ]
permissive
// // Created by fusionbolt on 2020-01-24. // #ifndef GWUI_TIMER_H #define GWUI_TIMER_H namespace Craft { class Timer { public: //初始化变量 Timer() noexcept; //各种时钟动作 void Start() noexcept; void Stop() noexcept; void Pause() noexcept; void UnPause() noexcept; //获取计时器时间 int GetTicks() noexcept; //检查计时器状态 bool IsStarted() noexcept; bool IsPaused() noexcept; private: int _GetTicks() noexcept; //计时器启动时的时间 int _startTicks; //计时器暂停时保存的滴答数 int _pausedTicks; //计时器状态 bool _paused; bool _started; }; } #endif //GWUI_TIMER_H
true
e5cc95d527f2217fd4eea99451179d6a683a31fd
C++
a567w/AriaGame
/KsEngine/system/collections/KsArray.h
SHIFT_JIS
6,134
3.15625
3
[ "MIT" ]
permissive
/************************************************************************************************/ /** * @file KsArray.h * @brief •ϒz * @author Tsukasa Kato * @date 2008/02/06 * @since 2008/02/06 * @version 1.0.0 */ /************************************************************************************************/ #ifndef __KSARRAY_H__ #define __KSARRAY_H__ /*==============================================================================================*/ /* << CN[h >> */ /*==============================================================================================*/ /*==============================================================================================*/ /* << ` >> */ /*==============================================================================================*/ /*==============================================================================================*/ /* << 錾 >> */ /*==============================================================================================*/ /************************************************************************************************/ /** * •ϒz * @class KsArray * @brief •ϒz * @since 2008/02/06 * @author Tsukasa Kato */ /************************************************************************************************/ template <typename T> class KsArray { public: /** * RXgN^ */ KsArray() : m_data( 0 ), m_allocSize( 0 ), m_size( 0 ) {} /** * RXgN^ * @param size mۂTCY */ KsArray( KsUInt32 size ) : m_data( 0 ), m_allocSize( 0 ), m_size( 0 ){ this->arrayRalloc( size ); } /** * fXgN^ */ ~KsArray(){ if( m_data ){ delete [] m_data; } } /** * ( operator ) * @param other z */ void operator = ( const KsArray< T >& other ) { if( m_data ){ delete [] m_data; } // TCY`FbN if( other.m_allocSize == 0 ) { m_data = 0; } else { m_data = new T[ other.m_allocSize ]; } // JEg m_size = other.m_size; // mۃTCY m_allocSize = other.m_allocSize; for( KsUInt32 i=0; i<other.m_size; ++i ){ m_data[ i ] = other.m_data[ i ]; } } /** * z̗vf擾( operator ) * @param index 擾CfbNX */ T& operator []( KsUInt32 index ) { return m_data[ index ]; } /** * z̗vf擾( operator ) * @param index 擾CfbNX */ const T& operator []( KsUInt32 index ) const { return m_data[ index ]; } /** * V[mۂȂ * @param size VmۂTCY */ void arrayRalloc( KsUInt32 size ) { T* temp = m_data; m_data = new T[ size ]; m_allocSize = size; KsUInt32 end = m_size < size ? m_size : size; if( m_allocSize < m_size ){ m_size = m_allocSize; } if( temp ) { for( KsUInt32 i=0; i<end; ++i ){ m_data[ i ] = temp[ i ]; } delete [] temp; } } /** * zɌ납vflj * @param data ljvf */ void push_back( const T& data ) { if( m_size + 1 > m_allocSize ) { this->arrayRalloc( m_size * 2 + 1 ); } m_data[ m_size++ ] = data; } /** * zɌ납vflj * @param index ljf[^̃CfbNX * @param data ljvf */ void insert( KsUInt32 index, const T& data ) { if( index + 1 > m_allocSize ) { this->arrayRalloc( m_size * 2 + 1 ); } if( m_size + 1 > m_allocSize ) { this->arrayRalloc( m_size * 2 + 1 ); } if( m_size > 0 ) { // wCfbNX̃f[^ăf[^l߂ for ( KsUInt32 i=m_size-1; i>=index; i-- ) { m_data[ i+1 ] = m_data[ i ]; } } m_data[ index ] = data; //if( m_size >= index ) //{ ++m_size; //} //else //{ //m_size = index + 1; //} } /** * z񂩂폜 * @param index f[^̃CfbNX */ void erase( KsUInt32 index ) { // wCfbNX̃f[^ăf[^l߂ for ( KsUInt32 i=index+1; i<m_size; ++i ) { m_data[ i-1 ] = m_data[ i ]; } --m_size; } /** * z񂩂폜 * @param index f[^̃CfbNX * @param count wCfbNX */ void erase( KsUInt32 index, KsUInt32 count ) { for( KsUInt32 i=(index + count); i<m_size; ++i ){ m_data[ i-count ] = m_data[ i ]; } m_size -= count; } /** * Zbg */ void reset() { m_size = 0; } /** * zNA[ */ void clear() { if( m_data ){ delete [] m_data; } m_data = 0; m_allocSize = 0; m_size = 0; } /** * |C^擾 * @return z̃|C^ */ T* pointer() { return m_data; } /** * z񂪋󂩂ǂ`FbN * @retval ksTRUE z͋ * @retval ksFALSE 󂶂Ȃ */ KsBool empty() const { return ( m_size == 0 ); } /** * mۂTCY * @return mۂĂz̐ */ KsUInt32 getAllocSize() const { return m_allocSize; } /** * JEg擾 * @return gĂz̐ */ KsUInt32 size() const { return m_size; } private: T* m_data; /**< f[^擾 */ KsUInt32 m_allocSize; /**< mۃTCY擾 */ KsUInt32 m_size; /**< z̗vf擾 */ }; #endif /* __KSARRAY_H__ */
true
5b2cb233abeb95b15dda401a1d64d239235f8428
C++
jaybroker/dstore
/dstore/network/connection.h
UTF-8
1,459
2.828125
3
[ "MIT" ]
permissive
#ifndef DSTORE_NETWORK_CONNECTION_H_ #define DSTORE_NETWORK_CONNECTION_H_ #include <list> #include <memory> #include "event_loop.h" #include "socket.h" #include "inet_addr.h" #include "buffer.h" namespace dstore { namespace network { class InetAddr; class Message; class Buffer; class Connection { public: enum Status { INVALID = 0, ACTIVE, CONNECTING, SHUTDOWN_READ, SHUTDOWN_WRITE, }; Connection(const InetAddr &peer, std::shared_ptr<Event> e); int init(EventLoop *loop); void set_event(const Event &e); Event &get_event(void); Buffer &get_read_buffer(void); Buffer &get_write_buffer(void); Socket &get_socket(void); int remove_write(void); int add_write(void); int remove_read(void); int add_read(void); void add_message(Message *); void remove_message(Message *); void set_status(const Connection::Status s); Connection::Status get_status(void); void close(void); bool pending_write(void); bool is_connect_ok(void); std::list<Message *> &get_message_list(void); void clear_message_list(void); Connection &operator=(const Connection &) = delete; Connection(const Connection &) = delete; private: Status status_; std::shared_ptr<Event> e_; EventLoop *loop_; Socket socket_; InetAddr peer_; std::list<Message *> message_list_; Buffer read_buffer_; Buffer write_buffer_; }; } // end namespace network } // end namespace dstore #endif // DSTORE_NETWORK_CONNECTION_H_
true
b8fd09a4710e493077db67c6504f3ab8847ba3fc
C++
cfromknecht/lattice
/test/HelperTest.cpp
UTF-8
603
3.1875
3
[]
no_license
#include <lattice/Helper.hpp> #include <gtest/gtest.h> TEST( HelperTest, makeUnique ) { // create new pointer to 42 auto sizePtr = lattice::make_unique<size_t>( 42 ); // test that pointer is not null and that value is set to 42 ASSERT_NE( nullptr, sizePtr ); ASSERT_EQ( size_t(42), *sizePtr ); // move ownership to new unique_ptr auto newSizePtr = std::move( sizePtr ); // test that old pointer is null ASSERT_EQ( nullptr, sizePtr ); // test that new pointer is not null, and that value is still 42 ASSERT_NE( nullptr, newSizePtr ); ASSERT_EQ( size_t(42), *newSizePtr ); }
true
f12ab01c34987ee7031e86b3164755443f04ff35
C++
danielhstahl/GaussNewton
/Newton.h
UTF-8
11,720
2.875
3
[]
no_license
#ifndef __NEWTON_H_INCLUDED__ #define __NEWTON_H_INCLUDED__ #include <vector> #include <array> #include <cmath> #include <iostream> #include <complex> #include "TupleUtilities.h" #include "AutoDiff.h" #include "FunctionalUtilities.h" namespace newton{ template<typename Val, typename Obj, typename Deriv> auto iterateStep(Val&& val, Obj&& obj, Deriv&& deriv){ return val-obj/deriv; } constexpr int totalOptimizationSize=3; template<typename T> using OptimizationObject = std::array<T, totalOptimizationSize>; constexpr int functionOutputIndex=0; constexpr int previousInputIndex=1; constexpr int currentInputIndex=2; template<typename OptObj, typename T> auto setOptimizationObject(OptObj&& optObj, const T& functionOutput, const T& previousInput, const T& currentInput){ optObj[functionOutputIndex]=functionOutput; optObj[previousInputIndex]=previousInput; optObj[currentInputIndex]=currentInput; return std::move(optObj); } template<typename T> auto createOptimizationObject(const T& functionOutput, const T& previousInput, const T& currentInput){ OptimizationObject<T> optObj; optObj[functionOutputIndex]=functionOutput; optObj[previousInputIndex]=previousInput; optObj[currentInputIndex]=currentInput; return optObj; } template<typename OptObj, typename T> auto checkPrecision(const OptObj& optObj, const T& precision1, const T& precision2){ return fabs(optObj[functionOutputIndex])>precision1&&fabs(optObj[currentInputIndex]-optObj[previousInputIndex])*.5>precision2; } template<typename OptObj> auto printResults(const OptObj& optObj){ std::cout<<"Function evaluation: "<<optObj[functionOutputIndex]<<", Previous input: "<<optObj[previousInputIndex]<<", Current Input: "<<optObj[currentInputIndex]<<std::endl; } template<typename Index> auto printIteration(const Index& index){ std::cout<<"Iteration: "<<index<<", "; } template<typename OptObj> auto getCurrent(const OptObj& optObj){ return optObj[currentInputIndex]; } template<typename OptObj> auto getPrevious(const OptObj& optObj){ return optObj[previousInputIndex]; } template<typename OptObj> auto getOutput(const OptObj& optObj){ return optObj[functionOutputIndex]; } template<typename OBJFUNC, typename DERIV, typename Guess, typename Index> //one dimension auto zeros(OBJFUNC&& objective, DERIV&& derivative, const Guess& guess, const Guess& precision1, const Guess& precision2, const Index& maxNum){ //({2.0, guess+1.0, guess}) return getCurrent(futilities::recurse_move(maxNum, createOptimizationObject(2.0, guess+1.0, guess), [&](auto&& value, const auto& index){ const auto guess=getCurrent(value); const auto result=objective(guess); #ifdef VERBOSE_FLAG printIteration(index); #endif return setOptimizationObject(value, result, guess, iterateStep(guess, result, derivative(guess))); }, [&](const auto& value){ #ifdef VERBOSE_FLAG printResults(value); #endif return checkPrecision(value, precision1, precision2); })); } template<typename OBJFUNC, typename Guess, typename Index> //one dimension auto zeros(OBJFUNC&& objective, const Guess& guess, const Guess& precision1, const Guess& precision2, const Index& maxNum){ AutoDiff<Guess> aGuess=AutoDiff<Guess>(guess, 1.0); auto getNewtonCoef=[](const auto& val, auto&& objResult){ return AutoDiff<Guess>(iterateStep(val.getStandard(), objResult.getStandard(), objResult.getDual()), 1.0); }; return getCurrent(futilities::recurse_move(maxNum, createOptimizationObject(AutoDiff<Guess>(2.0, 0.0), aGuess+1.0, aGuess), [&](auto&& value, const auto& index){ const auto guess=getCurrent(value); auto result=objective(guess); #ifdef VERBOSE_FLAG printIteration(index); #endif return setOptimizationObject(value, result, guess, getNewtonCoef(guess, result)); }, [&](const auto& value){ #ifdef VERBOSE_FLAG printResults(value); #endif return checkPrecision(value, precision1, precision2); })).getStandard(); } /**base case*/ template<typename FNC, typename T> auto gradientHelper(FNC&& fnc, std::vector<T>&& val){ return std::move(val); } /**recursive case*/ template<typename FNC, typename T, typename...Ts> auto gradientHelper(FNC&& fnc, std::vector<T>&& val, const T& current, const Ts&... others){ val.emplace_back(fnc(AutoDiff<T>(current, 1.0), others...).getDual()); return gradientHelper( [&](const auto&... remaining){ return fnc(current, remaining...); }, std::move(val), others...); } /**calling case*/ template<typename FNC, typename T, typename...Ts> auto gradient(const FNC& fnc, const T& current, const Ts&... others){ return gradientHelper(fnc, std::vector<T>(), current, others...); } /**base case*/ template<typename FNC, typename...Tr> auto gradientHelperTuple(FNC&& fnc, std::tuple<Tr...>&& myResult){ return std::move(myResult); } /**recursive case*/ template<typename FNC, typename T, typename...Ts, typename...Tr> auto gradientHelperTuple(FNC&& fnc, std::tuple<Tr...>&& myResult, const T& current, const Ts&... myparms){ return gradientHelperTuple( [&](const auto&... remaining){ return fnc(current, remaining...); }, std::tuple_cat(myResult, std::make_tuple(fnc(AutoDiff<T>(current, 1.0), myparms...).getDual())), myparms...); } /**NOTE that the gradientTuple is not used, but is kept here because I find the implementation interesting*/ template<typename FNC, typename...Ts> auto gradientTuple(FNC&& fnc, const Ts&... myparms){ return gradientHelperTuple(fnc, std::make_tuple(), myparms...); } /**returns tuple of tuples*/ template<typename FNC, typename T> auto gradientIterate(FNC&& fnc, const T& tuple){ return tutilities::for_each(tuple, [&](const auto& val, const auto& index, auto&& priorTuple, auto&& nextTuple){ return std::make_tuple( fnc( std::tuple_cat( priorTuple, std::make_tuple(AutoDiff<std::remove_const_t<std::remove_reference_t<decltype(val)> > >(val, 1.0)), nextTuple ) ).getDual(), val ); }); } /**returns tuple of tuples*/ template<typename FNC, typename T> auto gradientIterateApprox(FNC&& fnc, const T& tuple, double perterb){ return tutilities::for_each(tuple, [&](const auto& val, const auto& index, auto&& priorTuple, auto&& nextTuple){ return std::make_tuple( (fnc( std::tuple_cat( priorTuple, std::make_tuple(val+perterb), //perterb nextTuple ) )-fnc( std::tuple_cat( priorTuple, std::make_tuple(val-perterb), //perterb nextTuple ) ))/(2.0*perterb), val ); }); } /**base case*/ template<typename T> auto pack_params(std::vector<T>&& val){ return std::move(val); } /**recursive case*/ template<typename T, typename...Ts> auto pack_params(std::vector<T>&& val, const T& current, const Ts&... others){ return pack_params(std::move(val), others...); } template<typename Theta, typename Alpha, typename Gradient> auto gradientDescentObjective(const Theta& theta, const Alpha& alpha, const Gradient& grad){ return theta-alpha*grad; } /**This is for gradDescentPack*/ constexpr int GRAD=0; constexpr int PARAMVAL=1; /**This is for updatedTheta*/ constexpr int PARAMPACK=0; constexpr int ERRORVAL=1; constexpr int OBJVAL=2; template<typename FNC, typename GFN, typename Index, typename Precision,typename T, typename...Params> auto gradientDescentGeneric(const GFN& gradientIter, const FNC& fnc, const Index& maxNum, const Precision& precision, const T& alpha, const Params&... params){ auto tupleFnc=[&](const auto& tuple){ //this converts the incoming function into one that takes tuples return tutilities::apply_tuple(fnc, tuple); }; return std::get<PARAMPACK>(futilities::recurse_move( maxNum, std::make_tuple(std::make_tuple(params...), precision+1.0, 5.0), ///inital guess, initial "error", initial value [&](auto&& updatedTheta, const auto& numberOfAttempts){ #ifdef VERBOSE_FLAG printIteration(numberOfAttempts); #endif double error=0; return std::make_tuple(tutilities::for_each( gradientIter(tupleFnc, std::get<PARAMPACK>(updatedTheta)), //gradient at updatedTheta [&](const auto& gradDescentPack, const auto& index, auto&& priorTuple, auto&& nextTuple){ error+=futilities::const_power(std::get<GRAD>(gradDescentPack), 2); return gradientDescentObjective(std::get<PARAMVAL>(gradDescentPack), alpha, std::get<GRAD>(gradDescentPack)); } ), error, tupleFnc(std::get<PARAMPACK>(updatedTheta))); }, [&](const auto& updatedTheta){ auto error=std::get<ERRORVAL>(updatedTheta); #ifdef VERBOSE_FLAG auto objFn=std::get<OBJVAL>(updatedTheta); std::cout<<"Error Val: "<<error; std::cout<<", Obj Val: "<<objFn<<std::endl; #endif return error>precision; } )); } template<typename FNC, typename Index, typename Precision,typename T, typename...Params> auto gradientDescent(const FNC& fnc, const Index& maxNum, const Precision& precision, const T& alpha, const Params&... params){ return gradientDescentGeneric( [](const auto& tupleFnc, const auto& updatedGradient){ return gradientIterate(tupleFnc, updatedGradient); }, fnc, maxNum, precision, alpha, params... ); } template<typename FNC, typename Index, typename Precision,typename T, typename...Params> auto gradientDescentApprox(const FNC& fnc, const Index& maxNum, const Precision& precision, const Precision& peterbation, const T& alpha, const Params&... params){ return gradientDescentGeneric( [&](const auto& tupleFnc, const auto& updatedGradient){ return gradientIterateApprox(tupleFnc, updatedGradient, peterbation); },fnc, maxNum, precision, alpha, params... ); } template<typename T, typename S> auto isSameSign(const T& x1, const S& x2){ return x1*x2>0; } template<typename T, typename S> auto isEndBiggerThanBeginning(const T& x1, const S& x2){ return x2>x1; } template< typename OBJFUNC> //one dimension auto bisect(OBJFUNC&& objective, double begin, double end, double precision1, double precision2){ double beginResult=objective(begin); double endResult=objective(end); double prec=2; auto maxNum=10000;//will get there befre 10000 return isSameSign(beginResult, endResult)&&isEndBiggerThanBeginning(begin, end)?begin:getCurrent(futilities::recurse_move(maxNum, createOptimizationObject(beginResult, begin, end), [&](auto&& value, const auto& index){ auto c=(getPrevious(value)+getCurrent(value))*.5; auto result=objective(c); #ifdef VERBOSE_FLAG printIteration(index); #endif if(isSameSign(result, getOutput(value))){ return setOptimizationObject(value, result, c, getCurrent(value)); } else{ return setOptimizationObject(value, result, c, getPrevious(value)); } }, [&](const auto& value){ #ifdef VERBOSE_FLAG printResults(value); #endif return checkPrecision(value, precision1, precision2); })); } } #endif
true
0b8635bff6a24243b6c3e41b70b49f9d3b18ef17
C++
yqliving/Practice
/54-Spiral-Matrix/solution.cpp
UTF-8
1,423
3
3
[]
no_license
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; int rowSize = matrix.size(); if (rowSize == 0) return res; int colSize = matrix[0].size(); int leftb = 0, rightb = colSize - 1; int upb = 0, downb = rowSize - 1; int d = 0; int row = 0, col = 0; while (leftb <= rightb && upb <= downb) { res.push_back(matrix[row][col]); switch (d) { case 0: //right if (col >= rightb) { d = 1; row ++; upb ++; } else col ++; break; case 1: //down if (row >= downb) { d = 2; col --; rightb --; } else row ++; break; case 2: //left if (col <= leftb) { d = 3; row --; downb --; } else col --; break; case 3: //up if (row <= upb) { d = 0; col ++; leftb ++; } else row --; } } return res; } };
true
a28b67a121c1949d3cb84eac49ade5151788b519
C++
SayaUrobuchi/uvachan
/Kattis/licensetolaunch.cpp
UTF-8
258
2.515625
3
[]
no_license
#include <stdio.h> int main() { int n, i, ans, best, t; while (scanf("%d", &n) == 1) { for (i=0, ans=0, best=2147483647; i<n; i++) { scanf("%d", &t); if (t < best) { best = t; ans = i; } } printf("%d\n", ans); } return 0; }
true
065f490d262c6aae739f5ddb96baf7b305f9a5fe
C++
hysmun/InpresAiportChat
/cpp/SocketException.h
UTF-8
964
3.046875
3
[]
no_license
#ifndef __SOCKETEXCEPTION_H__ #define __SOCKETEXCEPTION_H__ #include <exception> using namespace std; class SocketException : public exception { protected: char *msg; int nbrErr; int setMsg(const char *tmp); int setNbrErr(int n) {nbrErr = n; return 1;}; public: //init SocketException() {msg = NULL; nbrErr=0;}; SocketException(const char *tmp) {msg = NULL; nbrErr=0; setMsg(tmp);}; SocketException(const char *tmp, int n) {msg = NULL; nbrErr=0; setMsg(tmp); setNbrErr(n);}; SocketException(int n); SocketException(const SocketException &tmp); ~SocketException() throw(); char *getMsg() const {return msg;}; int getNbrErr() const {return nbrErr;}; static const int ERRORINIT = 1; static const int ERRORCONNECT = 2; static const int ERRORLISTEN = 3; static const int ERRORACCEPT = 4; static const int ERRORMSGRCV = 5; static const int ERRORMSGSEND = 6; }; #endif
true
88e0d23c8b7aec52f43542773b238bcf9a2a00a9
C++
personaluser01/Algorithm-problems
/20131209/AM/131209_tests/subway/check/subway2.cpp
UTF-8
862
3.25
3
[]
no_license
#include <algorithm> #include <iostream> #include <set> #include <string> #include <vector> using namespace std; string canonical(const string& s) { vector<string> parts; int zeros = 0; int ones = 0; int current_start = 1; for (size_t i = 0; i < s.size(); ++i) { if (s[i] == '0') { zeros += 1; } else { ones += 1; } if (zeros == ones) { parts.push_back("0" + canonical(s.substr(current_start, i-current_start+1)) + "1"); current_start = i + 2; } } string ans; sort(parts.begin(), parts.end()); for (size_t i = 0; i < parts.size(); ++i) { ans += parts[i]; } return ans; } int main(int argc, char** argv) { int n; cin >> n; set<string> unique; for (int i = 0; i < n; ++i) { string s; cin >> s; unique.insert(canonical(s)); } cout << unique.size() << endl; }
true
a76fa0af2b9e55305519445c0ae39f95a65a86c0
C++
EnDronist/BreakOut-Engine
/Engine/Keyboard.cpp
UTF-8
3,592
2.59375
3
[]
no_license
/****************************************************************************************** * Chili DirectX Framework Version 16.07.20 * * Keyboard.cpp * * Copyright 2016 PlanetChili.net <http://www.planetchili.net> * * * * This file is part of The Chili DirectX Framework. * * * * The Chili DirectX Framework is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * The Chili DirectX Framework 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 General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with The Chili DirectX Framework. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************************/ #include "Keyboard.h" bool Keyboard::KeyIsPressed( unsigned char keycode ) const{ return keystates[keycode]; } Keyboard::Event Keyboard::ReadKey() { if( keybuffer.size() > 0u ) { Keyboard::Event e = keybuffer.front(); keybuffer.pop(); return e; } else { return Keyboard::Event(); } } bool Keyboard::KeyIsEmpty() const { return keybuffer.empty(); } char Keyboard::ReadChar() { if ( charbuffer.size() > 0u ) { unsigned char charcode = charbuffer.front(); charbuffer.pop(); return charcode; } else { return 0; } } bool Keyboard::CharIsEmpty() const { return charbuffer.empty(); } void Keyboard::FlushKey() { keybuffer = std::queue<Event>(); } void Keyboard::FlushChar() { charbuffer = std::queue<char>(); } void Keyboard::Flush() { FlushKey(); FlushChar(); } void Keyboard::EnableAutorepeat() { autorepeatEnabled = true; } void Keyboard::DisableAutorepeat() { autorepeatEnabled = false; } bool Keyboard::AutorepeatIsEnabled() const { return autorepeatEnabled; } void Keyboard::OnKeyPressed( unsigned char keycode ) { keystates[ keycode ] = true; keybuffer.push( Keyboard::Event( Keyboard::Event::Press,keycode ) ); TrimBuffer( keybuffer ); } void Keyboard::OnKeyReleased( unsigned char keycode ) { keystates[ keycode ] = false; keybuffer.push( Keyboard::Event( Keyboard::Event::Release,keycode ) ); TrimBuffer( keybuffer ); } void Keyboard::OnChar( char character ) { charbuffer.push( character ); TrimBuffer( charbuffer ); } template<typename T> void Keyboard::TrimBuffer( std::queue<T>& buffer ) { while( buffer.size() > bufferSize ) { buffer.pop(); } } void Keyboard::ToString(std::string &object_text) const { // std::bitset<nKeys> keystates object_text += std::to_string(keystates.to_string().size()); object_text += " "; for (int i = 0; i < keystates.to_string().size(); i++) { object_text += keystates[i]?'1':'0'; } } void Keyboard::FromString(std::string &object_text) { int char_count; // std::bitset<nKeys> keystates char_count = atoi(object_text.substr(size_t(0), object_text.find(' ')).c_str()); object_text.erase(0, object_text.find(' ') + 1); for (int i = 0; i < char_count; i++) { this->keystates[i] = ((bool)atoi(object_text.substr(i, 1).c_str()) == true) ? true : false; } object_text.erase(0, size_t(char_count)); }
true
1d546585578f5c503852b0c859a43d03630e5478
C++
chanaAkerman/AI_FinalProject
/First/Bullet.cpp
UTF-8
3,014
3
3
[]
no_license
#include "Bullet.h" #include "GLUT.H" #include <math.h> #include <stdio.h> Bullet::Bullet() { } Bullet::Bullet(double x, double y) { double len; this->x = x; this->y = y; this->originalX = x; this->originalY = y; this->pre_i = -1; this->pre_j = -1; this->originTeam = 0; dirx = (rand() % 101)-50; diry = (rand() % 101)-50; len = sqrt(dirx*dirx + diry * diry); dirx /= len; diry /= len; isMoving = false; } Bullet::~Bullet() { } void Bullet::showMe() { glColor3d(0, 0, 0); glBegin(GL_POLYGON); glVertex2d(x - 0.01, y); glVertex2d(x , y+ 0.01); glVertex2d(x + 0.01, y); glVertex2d(x, y - 0.01); glEnd(); } void Bullet::SetIsMoving(bool move) { isMoving = move; } bool Bullet::GetIsMoving() { return isMoving; } void Bullet::setOriginTeam(int team) { this->originTeam = team; } void Bullet::move(Node maze[MSZ][MSZ]) { int i, j; i = MSZ * (y + 1) / 2; j = MSZ * (x + 1) / 2; if (isMoving && maze[i][j].GetValue() == SPACE) { x += 0.002*dirx; y += 0.002*diry; if (!(pre_i == -1 && pre_j == -1)) { maze[this->pre_i][pre_j].SetValue(SPACE); } maze[i][j].SetValue(BULLET); this->pre_i = i; this->pre_j = j; } else if (isMoving && maze[i][j].GetValue()==BULLET) { // continue in that path x += 0.002*dirx; y += 0.002*diry; } else if (isMoving && ( (originTeam == 1 && maze[i][j].GetValue() == PLAYER_1) || (originTeam == 2 && maze[i][j].GetValue() == PLAYER_2))) { // might be the exact origin where the player shot // or hit the other team player // check this by distance double distance = getDistanceFronOriginal(); if (distance < 0.02) { // origin location x += 0.002*dirx; y += 0.002*diry; } else { // hit team player - make the bullet inactive isMoving = false; } } else if (isMoving && ((originTeam == 2 && maze[i][j].GetValue() == PLAYER_1) || (originTeam == 1 && maze[i][j].GetValue() == PLAYER_2)) ) { // hit. check the damage double distance = getDistanceFronOriginal(); isMoving = false; // 3-hard damage 2-medium damage 1-light damage 0-no damage if (distance < 0.020) { // hard damage printf("hard %f\n", distance); maze[i][j].setHit(30); } else if (distance < 0.040) { // medium damage printf("medium %f\n", distance); maze[i][j].setHit(20); } else { // light damage printf("light %f\n", distance); maze[i][j].setHit(10); } } } double Bullet::getX() { return x; } double Bullet::getY() { return y; } void Bullet::SetDir(double angle) { dirx = cos(angle); diry = sin(angle); } double Bullet::getDistanceFronOriginal() { // sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2)); return sqrt((originalX-x)*(originalX-x) + (originalY-y)*(originalY-y)); } void Bullet::SimulateMotion(double map[MSZ][MSZ], Node maze[MSZ][MSZ]) { int i, j; i = MSZ * (y + 1) / 2; j = MSZ * (x + 1) / 2; while(maze[i][j].GetValue() == SPACE) { map[i][j] += delta; x += 0.001*dirx; y += 0.001*diry; i = MSZ * (y + 1) / 2; j = MSZ * (x + 1) / 2; } }
true
6e57382b18932e9b67d05b7e8115ed530b17eacc
C++
a-laine/GolemFactory
/Sources/Utiles/FileWatcher.h
UTF-8
396
2.8125
3
[]
no_license
#pragma once #include <string> class FileWatcher { public: // Default FileWatcher(const std::string& name); // // Setter / getter std::string getFilemane() const; size_t getLastChangeHash() const; void setFilename(const std::string& name); void setLastChangeHash(const size_t& hash); // protected: // Attributes size_t lastChangeHash; std::string filename; // };
true
611ce8774b42a09a262c8c5fc1d693147676906b
C++
lineCode/HM4
/net/iobuffer.h
UTF-8
1,789
3.1875
3
[]
no_license
#ifndef _IO_BUFFER_H #define _IO_BUFFER_H #include <string> #include <string_view> #include <cstdio> #include <cassert> namespace net{ class IOBuffer{ private: using container_type = std::string; using size_type = container_type::size_type; private: size_type head_ = 0; container_type buffer_; public: void clear(){ buffer_.clear(); head_ = 0; } // ================================== const char *data() const{ const char *s = buffer_.data(); return & s[head_]; } size_t size() const{ return buffer_.size() - head_; } explicit operator std::string_view(){ return std::string_view{ data(), size() }; } // ================================== bool push(const char c){ buffer_.push_back(c); return true; } bool push(const char *p){ return push(std::string_view{ p }); } bool push(std::string_view const sv){ if (sv.size()) return push_(sv.size(), sv.data()); return false; } bool push(size_t const len, const char *ptr){ if (ptr && len) return push_(len, ptr); return false; } bool pop(size_t const len){ if (len == 0) return false; auto const available = size(); if (available < len) return false; if (available == len){ clear(); return true; } head_ = head_ + len; return true; } // ================================== void print() const{ printf("h: %3zu | s: %3zu | %.*s\n", head_, size(), (int) size(), buffer_.data() ); } private: bool push_(size_t const len, const char *ptr){ assert(ptr); assert(len); buffer_.append(ptr, len); return true; } }; } // namespace #endif #if 0 bool push(ssize_t const len, const char *ptr){ return push(narrow<size_t>(len), ptr); } bool pop(ssize_t const len){ return pop(narrow<size_t>(len)); } #endif
true
d4a740f88fbde235d08b2173446e26f62703c0c1
C++
piperarmstrong/origami
/treemaker/tmEdge.cpp
WINDOWS-1252
5,682
2.734375
3
[]
no_license
/******************************************************************************* File: tmEdge.cpp Project: TreeMaker 5.x Purpose: Implementation file for tmEdge class Author: Robert J. Lang Modified by: Created: 2003-11-25 Copyright: 2003 Robert J. Lang. All Rights Reserved. *******************************************************************************/ #include "tmEdge.h" #include "tmModel.h" using namespace std; /********** class tmEdge Class that represents an edge of the tree graph, and thus corresponds to a flap or segment of a flap in the folded base. **********/ /***** Static POD initialization *****/ const tmFloat tmEdge::MIN_EDGE_LENGTH = 0.01; /***** Common initialization *****/ void tmEdge::InitEdge() { // Register with tmTree mTree->mEdges.push_back(this); mIndex = mTree->mEdges.size(); // Set settings mLength = 0; strcpy(mLabel, ""); mStrain = 0; mStiffness = 1; // Set flags mIsPinnedEdge = false; mIsConditionedEdge = false; // Clear owner mEdgeOwner = 0; } /***** Bare constructor. *****/ tmEdge::tmEdge(tmTree* aTree) : tmPart(aTree), tmDpptrTarget() { InitEdge(); } /***** Full constructor *****/ tmEdge::tmEdge(tmTree* aTree, tmNode* node1, tmNode* node2, tmFloat aLength, const char* aLabel) : tmPart(aTree), tmDpptrTarget() { InitEdge(); // Register with Owner mEdgeOwner = aTree; mEdgeOwner->mOwnedEdges.push_back(this); // Set settings mLength = aLength; strcpy(mLabel, aLabel); // Fill with tmNode references mNodes.push_back(node1); node1->mEdges.push_back(this); mNodes.push_back(node2); node2->mEdges.push_back(this); } /***** Return the strained length of this edge in tree units. *****/ const tmFloat tmEdge::GetStrainedLength() const { return mLength * (1 + mStrain); } /***** Return the strained length of this edge scaled to paper units. *****/ const tmFloat tmEdge::GetStrainedScaledLength() const { return mLength * (1 + mStrain) * mTree->mScale; } /***** Change the label. Users should do their own range-checking on the length of the string, but if they don't, the actual label will be truncated to fit available space. *****/ void tmEdge::SetLabel(const char* aLabel) { TMASSERT(strlen(aLabel) <= MAX_LABEL_LEN); strncpy(mLabel, aLabel, MAX_LABEL_LEN); } /***** Change the length. Users should range-check the length to be greater than zero. *****/ void tmEdge::SetLength(const tmFloat& aLength) { if (mLength == aLength) return; tmTreeCleaner tc(mTree); TMASSERT(aLength > 0); mLength = aLength; } /***** Change the strain. *****/ void tmEdge::SetStrain(const tmFloat& aStrain) { if (mStrain == aStrain) return; tmTreeCleaner tc(mTree); mStrain = aStrain; } /***** Change the stiffness. *****/ void tmEdge::SetStiffness(const tmFloat& aStiffness) { if (mStiffness == aStiffness) return; tmTreeCleaner tc(mTree); mStiffness = aStiffness; } /***** Return the node at the opposite end of the edge from this one. *****/ tmNode* tmEdge::GetOtherNode(tmNode* aNode) const { TMASSERT(mNodes.size() == 2); TMASSERT(mNodes.front() == aNode || mNodes.back() == aNode); if (mNodes.front() == aNode) return mNodes.back(); else return mNodes.front(); } /***** STATIC Return true if any of the edges in this list have nonzero strain. *****/ bool tmEdge::ContainsStrainedEdges(const tmArray<tmEdge*>& elist) { for (size_t i = 0; i < elist.size(); ++i) if (elist[i]->GetStrain() != 0.0) return true; return false; } /***** Put a tmEdge in version 5 format. *****/ void tmEdge::Putv5Self(ostream& os) { PutPOD(os, GetTagStr()); PutPOD(os, mIndex); PutPOD(os, mLabel); PutPOD(os, mLength); PutPOD(os, mStrain); PutPOD(os, mStiffness); PutPOD(os, mIsPinnedEdge); PutPOD(os, mIsConditionedEdge); mTree->PutPtrArray(os, mNodes); mTree->PutOwnerPtr(os, mEdgeOwner); } /***** Get a tmEdge in version 5 format. *****/ void tmEdge::Getv5Self(istream& is) { CheckTagStr<tmEdge>(is); GetPOD(is, mIndex); GetPOD(is, mLabel); GetPOD(is, mLength); GetPOD(is, mStrain); GetPOD(is, mStiffness); GetPOD(is, mIsPinnedEdge); GetPOD(is, mIsConditionedEdge); mTree->GetPtrArray(is, mNodes); mTree->GetOwnerPtr(is, mEdgeOwner); } /***** Put a tmEdge in version 4 format. *****/ void tmEdge::Putv4Self(ostream& os) { PutPOD(os, GetTagStr()); PutPOD(os, mIndex); PutPOD(os, mLabel); PutPOD(os, mLength); PutPOD(os, mStrain); PutPOD(os, mStiffness); PutPOD(os, mIsPinnedEdge); PutPOD(os, mIsConditionedEdge); mTree->PutPtrArray(os, mNodes); mTree->PutOwnerPtr(os, mEdgeOwner); } /***** Get a tmEdge in version 4 format. *****/ void tmEdge::Getv4Self(istream& is) { CheckTagStr<tmEdge>(is); GetPOD(is, mIndex); GetPOD(is, mLabel); GetPOD(is, mLength); GetPOD(is, mStrain); GetPOD(is, mStiffness); // It's not allowed to have zero stiffness but some older files have that for // unknown reason. If we read a zero, replace it with 1.0 (the default). if (mStiffness == 0.0) mStiffness = 1.0; GetPOD(is, mIsPinnedEdge); GetPOD(is, mIsConditionedEdge); mTree->GetPtrArray(is, mNodes); mTree->GetOwnerPtr(is, mEdgeOwner); } /***** Get a tmEdge in version 3 format. *****/ void tmEdge::Getv3Self(istream& is) { CheckTagStr<tmEdge>(is); GetPOD(is, mIndex); GetPOD(is, mLabel); GetPOD(is, mLength); GetPOD(is, mIsPinnedEdge); mIsConditionedEdge = false; mTree->GetPtrArray(is, mNodes); // Fill in additional fields mStrain = 0.0; mStiffness = 0.0; // Set ownership mTree->mOwnedEdges.push_back(this); mEdgeOwner = mTree; } /***** Dynamic type implementation *****/ TM_IMPLEMENT_TAG(tmEdge, "edge")
true
f943b636e8cd89bff2994f527423721f26d75208
C++
rockkingjy/Inference_RGB2D_caffe
/depth_camera.cpp
UTF-8
6,833
2.625
3
[]
no_license
#include <caffe/caffe.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <algorithm> #include <iosfwd> #include <memory> #include <string> #include <utility> #include <vector> using namespace caffe; // NOLINT(build/namespaces) using namespace cv; using std::string; class Classifier { public: Classifier(const string& model_file, const string& trained_file); cv::Mat Predict(const cv::Mat& img); private: void WrapInputLayer(std::vector<cv::Mat>* input_channels); void Preprocess(const cv::Mat& img, std::vector<cv::Mat>* input_channels); private: shared_ptr<Net<float> > net_; cv::Size input_geometry_; int num_channels_; }; Classifier::Classifier(const string& model_file, const string& trained_file) { #ifdef CPU_ONLY Caffe::set_mode(Caffe::CPU); #else Caffe::set_mode(Caffe::GPU); #endif /* Load the network. */ net_.reset(new Net<float>(model_file, TEST)); net_->CopyTrainedLayersFrom(trained_file); CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input."; CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output."; Blob<float>* input_layer = net_->input_blobs()[0]; num_channels_ = input_layer->channels(); CHECK(num_channels_ == 3 || num_channels_ == 1) << "Input layer should have 1 or 3 channels."; input_geometry_ = cv::Size(input_layer->width(), input_layer->height()); //Blob<float>* output_layer = net_->output_blobs()[0]; } /* Wrap the input layer of the network in separate cv::Mat objects * (one per channel). This way we save one memcpy operation and we * don't need to rely on cudaMemcpy2D. The last preprocessing * operation will write the separate channels directly to the input * layer. */ void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels) { Blob<float>* input_layer = net_->input_blobs()[0]; int width = input_layer->width(); int height = input_layer->height(); float* input_data = input_layer->mutable_cpu_data(); for (int i = 0; i < input_layer->channels(); ++i) { cv::Mat channel(height, width, CV_32FC1, input_data);//data saved for each channel input_channels->push_back(channel); input_data += width * height; } } void Classifier::Preprocess(const cv::Mat& img, std::vector<cv::Mat>* input_channels) { /* Convert the input image to the input image format of the network. */ cv::Mat sample; if (img.channels() == 3 && num_channels_ == 1) cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY); else if (img.channels() == 4 && num_channels_ == 1) cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY); else if (img.channels() == 4 && num_channels_ == 3) cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR); else if (img.channels() == 1 && num_channels_ == 3) cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR); else sample = img; cv::Mat sample_resized; if (sample.size() != input_geometry_) cv::resize(sample, sample_resized, input_geometry_); else sample_resized = sample; cv::Mat sample_float; if (num_channels_ == 3) sample_resized.convertTo(sample_float, CV_32FC3); else sample_resized.convertTo(sample_float, CV_32FC1); /* cv::Mat sample_normalized; cv::subtract(sample_float, mean_, sample_normalized); */ /* This operation will write the separate BGR planes directly to the * input layer of the network because it is wrapped by the cv::Mat * objects in input_channels. */ cv::split(sample_float, *input_channels); /* check the copy is correct */ CHECK(reinterpret_cast<float*>(input_channels->at(0).data) == net_->input_blobs()[0]->cpu_data()) << "Input channels are not wrapping the input layer of the network."; } cv::Mat Classifier::Predict(const cv::Mat& img) { Blob<float>* input_layer = net_->input_blobs()[0]; input_layer->Reshape(1, num_channels_, input_geometry_.height, input_geometry_.width); std::cout << "Input channels:" << num_channels_ << ",Input height:" << input_layer->height() << ",Input width:" << input_layer->width() << std::endl; /* Forward dimension change to all layers. */ net_->Reshape(); std::vector<cv::Mat> input_channels; WrapInputLayer(&input_channels);//bound input_channels to input of net_ Preprocess(img, &input_channels); //preporcess the image into input_channels; net_->Forward(); /* Copy the output layer to a std::vector */ Blob<float>* output_layer = net_->output_blobs()[0]; std::cout << "Output Channels:" << output_layer->channels() << ",Output height:" << output_layer->height() << ",Output width:" << output_layer->width() << std::endl; int width = output_layer->width(); int height = output_layer->height(); float* output_data = output_layer->mutable_cpu_data(); cv::Mat mat(height, width, CV_32FC1, output_data); vector<int> compression_params; compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); return mat; } int main(int argc, char** argv) { string model_file = argv[1]; string trained_file = argv[2]; Classifier classifier(model_file, trained_file);//ini /* string file = argv[3]; std::cout << "---------- Prediction for " << file << " ----------" << std::endl; cv::Mat img = cv::imread(file, -1); CHECK(!img.empty()) << "Unable to decode image " << file; Mat depth_mat = classifier.Predict(img);//run net cv::imwrite("depth_result.png", mat, compression_params); */ //Open camera VideoCapture cap(0); // open the default camera if(!cap.isOpened()) // check if we succeeded return -1; for(;;) { Mat frame; cap >> frame; // get a new frame from camera Mat depth = classifier.Predict(frame); //run the net, return CV_32FC1 cv::log(depth,depth); depth = 2 * 0.179581 * depth + 1; //depth = np.clip(depth, 0.001, 1000) //return np.clip(2 * 0.179581 * np.log(depth) + 1, 0, 1) //convert the frame from CV_8C3 to CV_32FC3 Mat frame_convert; frame.convertTo(frame_convert, CV_32FC3); // this is just a copy frame_convert /= 255; //divided bye 0xff, it can be showed; //change the depth from CV_32FC1 to CV_32FC3 and then resize; Mat depth_convert; cv::cvtColor(depth, depth_convert, cv::COLOR_GRAY2BGR); resize(depth_convert, depth_convert, Size(frame.cols,frame.rows), 0, 0, INTER_CUBIC); //to show the two images side by side Mat win_mat(cv::Size(2*frame.cols, frame.rows), CV_32FC3); frame_convert.copyTo(win_mat(cv::Rect( 0, 0, frame.cols, frame.rows))); depth_convert.copyTo(win_mat(cv::Rect(frame.cols, 0, frame.cols, frame.rows))); imshow("Images", win_mat); if(waitKey(30) >= 0) break; } }
true
8295dbae939792f9d9b050f4c8561591568f5b3f
C++
LeeKangW/CPP_Study
/STL_Univ/STL_Univ/실습 1 알파벳 문자의 사용 횟수 확인.cpp
UHC
823
3.3125
3
[ "MIT" ]
permissive
#include"default.h" #include<string> #include<fstream> #include<map> #include <iomanip> int main() { cout << " - "; string file; cin >> file; ifstream in(file); if (!in) { cout << file << " ." << endl; } map<char, int> alpha; char str; while (in >> str) { if (isalpha(str)) { str = tolower(str); alpha[str]++; } } cout << " ĺ - " << alpha.size() << endl; int count = 0; for (const pair<char,int>& a : alpha) { count += a.second; } cout << " ĺ -" << count<<endl; cout << " ĺ Ƚ" << endl; count = 0; for (const auto& a : alpha) { if (count % 5 == 0 && count != 0) { cout << endl; count = 0; } cout << a.first << " - " << right << setw(5) << a.second<<" "; ++count; } }
true
2b2587076a3f4984fde4a78dd410ca8b24a55063
C++
JoshGuempel/Fabricated-Files-n-Folders
/file_system.cpp
UTF-8
8,407
3.234375
3
[]
no_license
#include "file_system.h" //List files in current directory void shell::ls(const std::string& args) { //Return if folder is empty or if dir pointer isnt pointing to anything if(curr_dir->files.empty() && curr_dir->folders.empty()) { return; } if(curr_dir == nullptr) { std::cerr << "Something went wrong, the shell object isnt pointing to a folder for some reason..." << std::endl; return; } if(args == "-l") { for (auto const& file : curr_dir->files) { std::cout << file.second->permissions << " 1 pbg user 0 " << file.second->date << " " << file.second->name << std::endl; } for (auto const& folder : curr_dir->folders) { std::cout << folder.second->permissions << " 1 pbg user 0 " << folder.second->date << " " << folder.second->name << std::endl; } } else { for (auto const& file : curr_dir->files) { std::cout << file.first << " "; } for (auto const& folder : curr_dir->folders) { std::cout << folder.first << " "; } } std::cout << std::endl; } //Connect to another directory void shell::cd(const std::string& args) { if(args == ".." || args == "../") { //Move up a level if(curr_dir->parent != nullptr) curr_dir = curr_dir->parent; return; } if(curr_dir->folders.count(args) == 0) { std::cout << "Folder doesn't exist." << std::endl; return; } //Move the curr_dir pointer to the folder curr_dir = curr_dir->folders[args].get(); } //Prints directory and parents void shell::pwd() { std::stack<std::string> parents; for(folder* i = curr_dir; i != nullptr; i = i->parent) parents.push(i->name); std::cout << "user:~/"; if(!parents.empty()) parents.pop(); while(!parents.empty()) { std::cout << parents.top() << "/"; parents.pop(); } std::cout << std::endl; } //print directory for shell (slightly different than pwd) void shell::print_dir_for_shell() { std::stack<std::string> parents; for(folder* i = curr_dir; i != nullptr; i = i->parent) parents.push(i->name); std::cout << "user:~/"; if(!parents.empty()) parents.pop(); while(!parents.empty()) { std::cout << parents.top() << "/"; parents.pop(); } std::cout << "$ "; } //Makes folder in current directory void shell::mkdir(const std::string& args) { if(curr_dir->folders.count(args) == 1) { std::cout << "Folder already exists." << std::endl; return; } curr_dir->folders[args] = std::make_shared<folder>(args, curr_dir); } //Removes folder in current directory void shell::rmdir(const std::string& args) { if(curr_dir->folders.count(args) == 0) { std::cout << "Folder does not exist." << std::endl; return; } curr_dir->folders.erase(args); } //removes file in current directory void shell::rm(const std::string& args) { if(curr_dir->files.count(args) == 0) { std::cout << "File does not exist." << std::endl; return; } curr_dir->files.erase(args); } //Change permissions of a file void shell::chmod(const std::string& args, const std::string& args1) { if(curr_dir->files.count(args1) == 0 && curr_dir->folders.count(args1) == 0) { std::cout << "File does not exist." << std::endl; return; } //Need to convert XXX to -rwxrwxrwx by first converting XXX in octal to binary auto permissions_binary = octal_to_binary(args); std::string p_777 = "-rwxrwxrwx"; std::string new_p = "----------"; for(unsigned int i = 0; i < permissions_binary.size(); i++) { if(permissions_binary[i] == 1) { new_p[i+1] = p_777[i+1]; } } if(curr_dir->files.count(args1)) { //it's a file curr_dir->files[args1]->permissions curr_dir->files[args1]->permissions = new_p; } else { //it's a folder, curr_dir->folders[args1]->permissions curr_dir->folders[args1]->permissions = new_p; } } //Creates file in current directory void shell::touch(const std::string& args) { if(curr_dir->files.count(args)) { //If file is already there just update the date curr_dir->files[args]->date = get_date(); } else { curr_dir->files[args] = std::make_shared<file>(args); } } //Quit. void shell::quit() { return; } shell::shell(folder& root_dir) { root_folder = root_dir; curr_dir = &root_folder; } folder::folder(const std::string& folder_name, folder* folder_parent) { name = folder_name; parent = folder_parent; permissions = "-rw-r--r--"; date = get_date(); } file::file(const std::string& file_name) { name = file_name; permissions = "-rw-r--r--"; date = get_date(); } void shell::process_command(const std::string& args) { std::vector<std::string> args_sep; std::string arg_buf = ""; for(const auto& c : args) { if(c == ' ') { if(arg_buf.length() > 0) { args_sep.push_back(arg_buf); } arg_buf = ""; } else { arg_buf += c; } } if(arg_buf.length() > 0) { args_sep.push_back(arg_buf); } arg_buf = ""; if(args_sep.size() == 0) { std::cerr << "Error, no command was read through input." << std::endl; return; } //C++ doesn't support switchcases on strings, RIP //ls if(args_sep[0] == "ls") { if(args_sep.size() == 2) { if(args_sep[1] == "-l") { ls("-l"); } else { std::cout << "Invalid syntax" << std::endl; } } else if(args_sep.size() == 1) { ls(""); } else { std::cout << "Invalid syntax" << std::endl; } //cd } else if(args_sep[0] == "cd") { if(args_sep.size() != 2) { std::cout << "too many arguments" << std::endl; return; } else { cd(args_sep[1]); } //pwd } else if (args_sep[0] == "pwd") { pwd(); //mkdir } else if (args_sep[0] == "mkdir") { //fg++ gives compiler warnings if i var isnt unsigned... so I made it unsigned for(unsigned int i = 1; i < args_sep.size(); i++) { mkdir(args_sep[i]); } //rmdir } else if (args_sep[0] == "rmdir") { for(unsigned int i = 1; i < args_sep.size(); i++) { rmdir(args_sep[i]); } //rm } else if (args_sep[0] == "rm") { for(unsigned int i = 1; i < args_sep.size(); i++) { rm(args_sep[i]); } //chmod } else if (args_sep[0] == "chmod") { if(args_sep.size() != 3) { std::cout << "invalid syntax" << std::endl; } else { chmod(args_sep[1], args_sep[2]); } //touch } else if (args_sep[0] == "touch") { for(unsigned int i = 1; i < args_sep.size(); i++) { touch(args_sep[i]); } //quit } else if (args_sep[0] == "quit" || args_sep[0] == "exit") { quit(); } else { std::cout << args_sep[0] << ": Command not found" << std::endl; } } //get date in a formatted string. std::string get_date() { time_t time_now = time(0); std::string date_time = ctime(&time_now); int i = date_time.size() - 1; while(i >= 0 && date_time[i] != ':') i--; date_time.erase(i,date_time.size()); i = 0; while(date_time[i] != ' ' && i < date_time.size()) i++; date_time.erase(0, i+1); return date_time; } //Convert octal number into binary number. (successive divion) std::vector<int> octal_to_binary(std::string octal_num) { std::vector<int> binary_num; int octal_num_b10 = 0; int index = octal_num.length()-1; //Convert octal_num to b10 for(unsigned int i = 0; i < octal_num.length(); i++) { octal_num_b10 += (octal_num[i] - '0') * pow(8,index); index--; } if(octal_num_b10 == 0) { binary_num.push_back(0); } else { while(octal_num_b10 > 0) { int remainder = octal_num_b10 % 2; binary_num.push_back(remainder); octal_num_b10 /= 2; } } std::reverse(binary_num.begin(), binary_num.end()); return binary_num; }
true
469b217380c6cf36569acd53d73a8d32e2a9ece8
C++
dcoretti/ControlDeck
/include/ControlDeck/PPU/PPU2C02.h
UTF-8
4,433
2.609375
3
[]
no_license
#pragma once #include "PPUComponents.h" #include "ColorPalette.h" #include "../cartridge.h" #include "../Render.h" namespace NES { // Starting cycle in scan line state enum class ScanLineState { Idle = 0, //0 TileFetch = 1, //1-256 SpriteFetch = 257, //257-320 FirstTwoTileFetch = 321, //321-336 NameTableByteFetch = 337, //337-340 }; // Frame rendering state transitions between scan lines for a total of 262 scan lines per frame, 240 of which // are visible. enum class RenderState { VisibleScanLines = 0, //0-239 PostRenderScanLine = 240, //240 VerticalBlank = 241, //241-260 PreRenderScanLine = 261, //261 }; class Ppu2C02 { public: void setPowerUpState(); void doPpuCycle(); void handleScrolling(); Pixel getScreenPixel(); /////////////////////////////////////////////////////////////////////// // PPU Memory Mapper static const uint16_t patternTableBoundary = 0x4000; static const uint16_t nameTableBoundary = 0x3f00; uint8_t doMemoryOperation(uint16_t address, uint8_t write, bool read = true); uint8_t getByte(uint16_t address) { return doMemoryOperation(address, 0); } bool isAddressInPaletteRange(uint16_t address); /////////////////////////////////////////////////////////////////////// // CPU Memory-mapped register read/write uint8_t readRegister(PPURegister ppuRegister); void writeRegister(PPURegister ppuRegister, uint8_t val); // scanline-triggered resets of various register components void doRegisterUpdates(); RenderState getRenderState(); // CPU poll API for NMI. Only ever active if PPU reaches vblank and PPUCTRL bit 7 set (generate NMI) bool pollNMI(); //////////////////////////////////////////// // Registers and memory components // Registers accessible to CPU through memory mapper PPUMemoryComponents ppuMemory{}; // Internal rendering state registers/memory (not directly connected to memory mapper) // used to render sprites in a given frame/scanline PPURenderingRegisters renderingRegisters{}; SpriteMemory spriteMemory{}; BackgroundTileMemory bkrndTileMemory{}; Cartridge *cartridge; RenderBuffer renderBuffer; bool disabled{ false }; // for easier testing to cause goPpuCycle to nop private: // Rendering state uint16_t curScanLine{ 0 }; // Active scan line (of 262 total) uint32_t cycle{ 0 }; // Overall cycle counter uint16_t scanLineCycle{ 0 }; // one cycle per pixel (35 uint16_t ppuAddr; uint8_t ppuData; // Scan line produced data pending load into registers for rendering uint16_t currentNameTable{ 0 }; uint8_t patternL{ 0 }; // current high bit pattern table entry uint8_t patternR{ 0 }; // current low bit pattern table entry uint8_t attrTableEntry{ 0 }; bool flagNmi{ false }; /** * Iterate primary OAM to determine which objects are in Y-range for the NEXT scan line from highest priority (0) * to lowest. Set sprite overflow flag in status register if more than 8 are found. * See "In-range object evaluation" http://nesdev.com/2C02%20technical%20reference.TXT */ void populateSecondaryOam(); /** * Set up pattern table data for sprites drawn on the next scan line. * For each sprite (8 total) * 1-2. ?? Reuse of hardware for playfield/background population causes wasted cycles * 3. pattern table bitmap 0 fetch for sprite * 4. pattern table bitmap 1 fetch for sprite * * cycles 129-160 */ void populateSpritePatterns(); /** * Fetch background data for first two tiles to be rendered on next scanline (BackgroundLineContext). * For each tile (2 total) * 1. Get name table byte * 2. Get attribute table byte * 3. Get pattern table bitmap 0 * 4. Get pattern table bitmap 1 * cycle 161-168 */ void populateBackgroundPatterns(); void fetchNameTableByte(); bool isDmaActive; }; }
true
d44785270dbe98234b77b8c230e192ae539d8d46
C++
365460/CMP
/CMP/simulator/Error.cpp
UTF-8
671
2.796875
3
[]
no_license
#include "Error.h" Error::Error(){ } Error::Error(std::string s):illegal(s), halt(true){ } void Error::addError(int id){ switch (id) { case WriteTo0: message.push_back("Write $0 Error"); break; case NumOverF: message.push_back("Number Overflow"); break; case OverWriteHI: message.push_back("Overwrite HI-LO registers"); break; case MemAddOverF: message.push_back("Address Overflow"); halt = true; break; case DataMisaligned: message.push_back("Misalignment Error"); halt = true; break; default: // just halt halt = true; } }
true
2293e72f3f1af34747d19b56d41aa110108cc445
C++
SPriyal/work
/github/c++/Message_Folder(c++primer13.4)/Message.h
UTF-8
392
2.59375
3
[]
no_license
#ifndef MESSAGE #define MESSAGE #include <set> #include <string> using namespace std; class Folder; class Message { public: Message(string content); Message(const Message & m); Message operator=(const Message & m); void save(Folder * f); void remove(Folder * f); ~Message(); private: set<Folder*>folders; string content; void addToFolders(); void removeFromFolders(); }; #endif
true
1db2aa75d5d083a5790d242ce7cbf2c0b2b8a6cc
C++
jarquile/ICS-45C
/Lab 2/calculator.cpp
UTF-8
908
3.0625
3
[]
no_license
#include "calculator.hpp" double calculateTotal(double score, double total, double weight) { return (score / total)*weight; } void calculateFinalGrade(unsigned int number, Artifacts *artifacts, Student* students) { for (int x = 0; x < number; x++) { if (students[x].gradeOpt == 'G') { if (students[x].totalScore >= artifacts->gradePoints[0]) students[x].finalGrades = 'A'; else if ( students[x].totalScore >=artifacts->gradePoints[1]) students[x].finalGrades = 'B'; else if (students[x].totalScore >= artifacts->gradePoints[2]) students[x].finalGrades = 'C'; else if (students[x].totalScore >= artifacts->gradePoints[3]) students[x].finalGrades = 'D'; else students[x].finalGrades = 'F'; } else { if (students[x].totalScore >= artifacts->gradePoints[2]) { students[x].finalGrades = 'P'; } else students[x].finalGrades = "NP"; } } }
true
cf08d5c35b297a286104cbae8fd087bc3919272a
C++
wildpea/Fit
/fit/function.h
UTF-8
2,339
2.8125
3
[]
no_license
/*============================================================================= Copyright (c) 2014 Paul Fultz II function.h Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef FIT_GUARD_FUNCTION_FUNCTION_H #define FIT_GUARD_FUNCTION_FUNCTION_H /// FIT_STATIC_FUNCTION /// =================== /// /// Description /// ----------- /// /// The `FIT_STATIC_FUNCTION` macro allows initializing a function object from /// a `constexpr` expression. It also ensures that the function object will /// have a unique address across translation units. This helps to avoid ODR /// violations. As such, the object that is deduced is default constructed. /// /// Example /// ------- /// /// struct sum_f /// { /// template<class T, class U> /// T operator()(T x, U y) const /// { /// return x+y; /// } /// }; /// /// FIT_STATIC_FUNCTION(sum) = sum_f(); /// FIT_STATIC_FUNCTION(partial_sum) = fit::partial(sum_f()); /// assert(sum(1, 2) == partial_sum(1)(2)); /// #include <fit/reveal.h> #include <fit/detail/static_constexpr.h> #include <fit/detail/static_const_var.h> #include <fit/detail/constexpr_deduce.h> namespace fit { namespace detail { struct reveal_static_const_factory { constexpr reveal_static_const_factory() {} #if FIT_NO_UNIQUE_STATIC_VAR template<class F> constexpr reveal_adaptor<F> operator=(const F& f) const { static_assert(is_default_constructible<F>::value, "Static functions must be default constructible"); return reveal_adaptor<F>(f); } #else template<class F> constexpr const reveal_adaptor<F>& operator=(const F&) const { static_assert(is_default_constructible<F>::value, "Static functions must be default constructible"); return static_const_var<reveal_adaptor<F>>(); } #endif }; }} #if FIT_NO_UNIQUE_STATIC_VAR #define FIT_STATIC_FUNCTION(name) FIT_STATIC_CONSTEXPR auto name = FIT_DETAIL_MSVC_CONSTEXPR_DEDUCE fit::detail::reveal_static_const_factory() #else #define FIT_STATIC_FUNCTION(name) FIT_STATIC_AUTO_REF name = fit::detail::reveal_static_const_factory() #endif #endif
true
dec397182433ce9de3781dd6569482ee961486f9
C++
itohdak/AtCoder
/ABC/old/previous/11-/119/B.cpp
UTF-8
431
2.59375
3
[]
no_license
#include <iostream> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <numeric> // accumulate(v.begin(), v.end(), 0) using namespace std; #define ll long long int main(){ int N; cin >> N; double sum = 0; for(int i=0; i<N; i++) { double x; string u; cin >> x >> u; if(u == "JPY") sum += x; else sum += 380000 * x; } cout << sum << endl; return 0; }
true
bcd9ef5c74aa0111627ac26d2bd963d98ec776b0
C++
weitianpaxi/Learning_Cpp
/Code_By_Dev-Cpp/test_012.cpp
GB18030
447
3.65625
4
[]
no_license
//test_012.cpp--ʹÑԶxmain()KݔһҪ{ÃɴΡ #include <iostream> void outline_a(); void outline_b(); int main() { outline_a(); outline_a(); outline_b(); outline_b(); return 0; } void outline_a() { //using std::cout; std::cout<<"Three bliand mice"<<std::endl; } void outline_b() { //using std::cout; std::cout<<"See how they run"<<std::endl; }
true
36e1debaa5af62eb0af9dc429f8cbe37e28fe669
C++
jazztext/VRRayTracing
/src/Util/FPSTimer.h
UTF-8
604
2.953125
3
[ "MIT" ]
permissive
// FPSTimer.h #pragma once #include "Timer.h" #include <vector> ///@brief Keeps a history of elapsed frame times for calculating average FPS. class FPSTimer { public: FPSTimer(); virtual ~FPSTimer(); void OnFrame(); void Reset(); float GetFPS() const; float GetInstantaneousFPS() const; protected: Timer m_timer; unsigned int m_count; ///< Number of samples in history std::vector<double> m_frameTimes; unsigned int m_ringPtr; private: // Disallow copy ctor and assignment operator FPSTimer(const FPSTimer&); FPSTimer& operator=(const FPSTimer&); };
true
4fbdf11f52a5b0ecbed20b57e1fb9d0b9770e035
C++
labyrinth6843/Necrodancer
/01_WinMain/Ground.h
UTF-8
1,132
2.59375
3
[]
no_license
#pragma once #include "GameObject.h" #include "Wall.h" class Ground : public GameObject { wstring mFileName; Image* mBack; vector<vector<AlphaTile>> mGroundList; //Test00.txt int mMapSizeX; int mMapSizeY; int mMinIndexX; int mMinIndexY; int mMaxIndexX; int mMaxIndexY; POINT mOddFrame; //홀수 프레임 POINT mEvenFrame;//짝수 프레임 int mSightCall; public: Ground(const string &name, const wstring& filename, int startx = 0, int starty = 0); virtual void Init(); virtual void Release(); virtual void Update(); virtual void Render(HDC hdc); public: bool GetSight(int targetX, int targetY, int level); bool GetAlpha(int indexX, int indexY, float& alpha); //Wall 클래스에서 호출할 함수 bool GetAlpha(float posX, float posY, float & alpha); bool IsMove(int indexX, int indexY); //이동하고자 하는 바닥타일의 인덱스를 인자로 받는다 void GetShowArea(int &minx, int &miny, int &maxx, int &maxy); void SightCall(); bool NextStage(int indexX, int indexY); POINT GetMapSize() { POINT pt = { mMapSizeX, mMapSizeY }; return pt; } private: void SetMinMax(); };
true
e0d21b6b95d80858fc0c18f0d36c8602b118923b
C++
toolittlecakes/draft2Dengine
/draft/objects/dog.h
UTF-8
890
2.75
3
[]
no_license
#ifndef DRAFT_BOX_H #define DRAFT_BOX_H #include "object.h" #include "player.h" //class Dog final : public Object { //public: // Dog(float x, float y, Image image) : Object(x, y, std::move(image)) {} // // void update(const Input &input, std::vector<std::unique_ptr<Object>> &objects) override { // for (auto &object : objects) { // if (typeid(*object) == typeid(Player)) { // coords += (object->coords - coords).norm() / sqrtf((object->coords - coords).abs()/100); // } // if ((coords - object->coords).abs() < (object->image.shape.abs() + image.shape.abs()) / 2 / 1.4) { // coords = object->coords + (coords - object->coords).norm() * // (object->image.shape.abs() + image.shape.abs()) / 2 / 1.4; // } // } // // // } //}; #endif //DRAFT_BOX_H
true
f8bce679a304bbac24f05cc6a41512686cfd3d05
C++
danykim57/c-study
/mapPractice.cpp
UTF-8
540
3.46875
3
[]
no_license
#include<iostream> #include<map> #include<string> using namespace std; int main() { map<string, int>m; m.insert(make_pair("a", 1)); m.insert(make_pair("b", 2)); m["c"] = 6; m.erase("c"); m.erase(m.find("b")); if (!m.empty()) cout << "size of m is " << m.size() << endl; cout << "a: " << m.find("a")->second << endl; cout << "The number of a is " << m.count("a") << endl; cout << "Go through" << endl; for (auto i = m.begin(); i != m.end(); i++) { cout << "Key: " << i->first << "\t value: " << i->second << endl; } }
true
a97a3ff39df2ea4ee61f1150bdb406b9007e8b9d
C++
T4g1/ZombieHeadToPlay
/trunk/src/data/Animation.h
ISO-8859-1
575
2.953125
3
[]
no_license
/** \file Animation.h * \brief Dfinit la classe Animation */ #ifndef ANIMATION_H #define ANIMATION_H #include <SDL/SDL.h> /** \class Animation * \brief Classe permettant la gestion des Animation */ class Animation { public: Animation(); virtual ~Animation(); bool addFrame(int x, int y, int w, int h); protected: private: SDL_Rect* l_frames; // Liste des coordonnes des images composant l'animation int frameCount; // Nombre de frame composant l'animation int currentFrame; // Frame affiche }; #endif // SPRITE_H
true
f02b05177dec614ad755f16c6d5af525f6ccd40a
C++
kanglanglang/danei
/CSD1404(待补充)/c++(CSD1404,GAJ)/day07/08muti_inheri.cpp
UTF-8
1,143
3.296875
3
[]
no_license
#include <iostream> using namespace std; class Product{ double price; public: double getPrice(){return price;} Product(double price=0.0):price(price){ } }; class Phone:virtual public Product{ public: Phone(double price=0.0):Product(price){ cout << "Phone()" << endl; } void phone(){ cout << "打电话" << endl; } }; class Camera:virtual public Product{ public: Camera(double price=0.0):Product(price){ } void camerafun(){ cout << "拍视频" << endl; } }; class Mp3:virtual public Product{ public: Mp3(double price=0.0):Product(price){ } void mp3fun(){ cout << "播放音乐" << endl; } }; class IPhone:public Phone,public Mp3, public Camera{ public: IPhone(double p=0,double m=0, double c=0):Product(p+m+c){ } }; int main(){ cout << sizeof(Phone) << endl; cout << sizeof(Camera) << endl; Camera camera(1999.5); cout << camera.getPrice() << endl; IPhone iphone6(1500,50.5,3500); /* 只复制了最高层类的一份数据 不会冲突 */ cout << iphone6.getPrice() << endl; cout << sizeof(iphone6) << endl; }
true
014b76c99db7ae214e0969fa982765bb6ba7b03a
C++
BrychDaneel/mtran
/compiler/tokens/stringtoken.cpp
UTF-8
436
2.859375
3
[]
no_license
#include "stringtoken.h" const int StringToken::TYPE = 402; const std::string StringToken::REGEX = "'..+?'" ; const std::string StringToken::NAME = "String"; StringToken::StringToken(const std::string lexem) { this->lexem = lexem; value = lexem.substr(1, lexem.size()-2); } Token *StringToken::create(const std::string lexem) { return new StringToken(lexem); } std::string StringToken::getValue() { return value; }
true
68152d5422f6f58decefcea1ada870c186acdd7a
C++
ofxyz/ofxBranchesPrimitive
/src/ofxBranchCylinder.h
UTF-8
6,707
2.703125
3
[]
no_license
#pragma once #include "ofMain.h" #include "ofxBranch.h" struct ofxBranchCylinderOptions{ bool cap; float radiusBottom; float radiusTop; int resolution; int textureRepeat; float padding; }; static const ofxBranchCylinderOptions defaultBranchOptions = { false, 5.0, 5.0, 16, 1, 0 }; class ofxBranchCylinder{ public: template <typename BRANCH> static void putIntoMesh(shared_ptr<BRANCH> branch, ofMesh& mesh){ add(branch, mesh, defaultBranchOptions); }; template <typename BRANCH> static void putIntoMesh(shared_ptr<BRANCH> branch, ofMesh& mesh, ofxBranchCylinderOptions options){ add(branch, mesh, options); }; private: template <typename BRANCH> static void add(shared_ptr<BRANCH> branch, ofMesh& mesh, ofxBranchCylinderOptions opt){ glm::vec4 startPos = branch->getStartPos(); glm::vec4 endPos; // add an empty space between the branches, if padding > 0 if (opt.padding > 0) { endPos = branch->getEndPos() - glm::vec4((branch->getEndDirection() * opt.padding), 1.0); } else { endPos = branch->getEndPos(); } glm::quat startOrientation = branch->getStartOrientation(); glm::quat endOrientation = branch->getEndOrientation(); glm::vec3 endDirection = branch->getEndDirection(); bool addVertexColor = true;//turn on/off vertex colors bool cap = opt.cap; int resolution = opt.resolution; int textureRepeat = opt.textureRepeat; float length = glm::distance(startPos, endPos); float radius = opt.radiusBottom; float scaledRadius; if (opt.radiusTop <= 0.03) { scaledRadius = 0.03; } else { scaledRadius = opt.radiusTop; } // these variables are used to do not stretch the texture float circumferenceBottom = radius * 3.1415926f; float ratio = circumferenceBottom/length; float ratioCap = scaledRadius/length; float xWrapLimit = circumferenceBottom/(length/textureRepeat); float wrapLimitCap = ratioCap * textureRepeat; glm::mat4x4 rotMatBottom = glm::toMat4(startOrientation); glm::mat4 tranMatBottom = glm::translate(glm::vec3(startPos)); //top glm::mat4x4 rotMatTop = glm::toMat4(endOrientation); glm::mat4 tranMatTop = glm::translate(glm::vec3(endPos)); // Cylinder body //mesh.enableIndices(); int first = mesh.getNumVertices(); for (int i = 0; i < resolution; i++) { mesh.addIndex(first+(i*2)); mesh.addIndex(first+(i*2)+3); mesh.addIndex(first+(i*2)+2); mesh.addIndex(first+(i*2)); mesh.addIndex(first+(i*2)+1); mesh.addIndex(first+(i*2)+3); } ofFloatColor colorTop(ofRandom(1.0f),ofRandom(1.0f), ofRandom(1.0f)); ofFloatColor colorBottom(ofRandom(1.0f),ofRandom(1.0f), ofRandom(1.0f)); for (int i = 0; i <= resolution; i++) { //the circle, this is the element that will be moved float theta = 2.0f * 3.1415926f * float(i) / float(resolution); float x = radius * cosf(theta); float z = radius * sinf(theta); float x_scaled = scaledRadius * cosf(theta); float z_scaled = scaledRadius * sinf(theta); glm::vec4 circleCenter = glm::vec4(0.0f, 0.0f, 0.0f,1.0); glm::vec4 circle = glm::vec4(x, 0.0f, z, 1.0f); glm::vec4 circle_scaled = glm::vec4(x_scaled, 0.0f, z_scaled, 1.0f); glm::vec4 circleBottom = tranMatBottom * rotMatBottom * circle; glm::vec4 circleTop = tranMatTop * rotMatTop * circle_scaled; glm::vec4 normalTop = glm::normalize( (rotMatTop * circle_scaled ) - (rotMatTop * circleCenter) ); glm::vec4 normalBottom = glm::normalize( (rotMatBottom * circle ) - (rotMatBottom * circleCenter) ); glm::vec2 tcoord; tcoord.x = ofMap(i, 0.f, resolution, 0.f, xWrapLimit); // bottom tcoord.y = 0; mesh.addVertex(glm::vec3(circleBottom)); mesh.addNormal(glm::vec3(normalBottom)); mesh.addTexCoord(tcoord); if (addVertexColor) { mesh.addColor(colorBottom); } //top tcoord.y = textureRepeat; mesh.addVertex(glm::vec3(circleTop)); mesh.addNormal(glm::vec3(normalTop)); mesh.addTexCoord(tcoord); if (addVertexColor) { mesh.addColor(colorTop); } } // Cylinder cap if (cap) { int topMiddlePoint = mesh.getNumVertices(); glm::vec3 topDir = endDirection; mesh.addVertex(glm::vec3(endPos)); mesh.addNormal(topDir); mesh.addTexCoord(glm::vec2(wrapLimitCap/2,wrapLimitCap/2)); if (addVertexColor) { mesh.addColor(colorTop); } for (int i = 0; i <= resolution; i++) { if (i == resolution) { //closing triangle mesh.addIndex(topMiddlePoint); mesh.addIndex(topMiddlePoint+ i + 1); mesh.addIndex(topMiddlePoint+1); } else { //indices mesh.addIndex(topMiddlePoint); mesh.addIndex(topMiddlePoint+ i + 1); mesh.addIndex(topMiddlePoint+ i + 2); } float theta = 2.0f * 3.1415926f * float(i) / float(resolution); float x = scaledRadius * cosf(theta); float z = scaledRadius * sinf(theta); glm::vec4 circle = glm::vec4(x, 0.0f, z, 1.0f); glm::vec4 circleTop = tranMatTop * rotMatTop * circle; glm::vec2 capTcoord; capTcoord.x = ofMap(x, -scaledRadius, scaledRadius, 0.f, wrapLimitCap); capTcoord.y = ofMap(z, -scaledRadius, scaledRadius, 0.f, wrapLimitCap); mesh.addVertex(glm::vec3(circleTop)); mesh.addNormal(topDir); mesh.addTexCoord(capTcoord); if (addVertexColor) { mesh.addColor(colorTop); } } } }; };
true
078c3234593dd52fdd639ad55da185c9a3183e6d
C++
JiayaoWu/MLH
/Task.h
UTF-8
287
2.84375
3
[]
no_license
#ifndef TASK_H #define TASK_H #include<string> using std::string; class Task { public: Task(const string &, const double, const double); void print() const; double getLabor() const; double getPart() const; private: string name; double costofLabor; double costofPart; }; #endif
true
480098f365d6826c8f8270021f9b967b61444fbc
C++
ThomasFuser/BibliotecaP2
/VIEW/listaop.cpp
UTF-8
3,785
2.734375
3
[]
no_license
#include"listaop.h" listaOp::listaOp(DataBase* db): Widget_Padre(db){ table=new QTableWidget(); //inserisco la tabella nel layout del widget layout_table=new QVBoxLayout(); layout_table->addWidget(table); set_style(); setLayout(layout_table); costruisci_contenuto(); connect(table,SIGNAL(cellDoubleClicked(int,int)),this,SLOT(doppio_click(int))); //doppio click connect(table,SIGNAL(cellClicked(int,int)),this,SLOT(click_singolo(int))); //click singolo } void listaOp::costruisci_contenuto(){ aggiorna_vista(); } void listaOp::aggiorna_vista(){ int row=0; DataBase* ciao=get_model(); if(!((get_model())->vuoto())) { int id; QString i; container::iteratore it; for(it=(get_model())->db_begin(); it!=(get_model())->db_end(); it++) { table->setRowCount(row+1); id=(*it)->Get_Id(); i.setNum(id); QTableWidgetItem *ID = new QTableWidgetItem(i); QTableWidgetItem *valore = new QTableWidgetItem((*it)->GetTitolo()); QTableWidgetItem *tipo = new QTableWidgetItem((*it)->get_Tipo()); table->setItem(row,0,ID); table->setItem(row,1,valore); table->setItem(row,2,tipo); row++; } } else{ table->setRowCount(row); emit tabella_vuota(); } } void listaOp::set_style(){ Widget_Padre::set_style(); //set numero righe e colonne della tabella table->setColumnCount(3); table->setRowCount(0); //set dimensioni tabella table->setMinimumWidth(700); table->setColumnWidth(0,50); table->setColumnWidth(1,505); table->setColumnWidth(2,100); table->setMaximumWidth(700); table->setMinimumHeight(300); table->setMaximumHeight(600); //intestazione tabella QStringList tabHeader; tabHeader<<"ID"<<"Titolo"<<"Tipologia"; table->setHorizontalHeaderLabels(tabHeader); //comportamento nel momento in cui si seleziona un item table->setSelectionMode(QAbstractItemView::SingleSelection); table->setEditTriggers(QAbstractItemView::NoEditTriggers); table->setSelectionBehavior(QAbstractItemView::SelectRows); } void listaOp::build_Nuova(const container& lista){ int row=0; if(!(lista.empty())) { int id; QString i; container::iteratore it; for(it=lista.begin(); it!=lista.end(); it++) { table->setRowCount(row+1); id=(*it)->Get_Id(); i.setNum(id); QTableWidgetItem *ID = new QTableWidgetItem(i); QTableWidgetItem *valore = new QTableWidgetItem((*it)->GetTitolo()); QTableWidgetItem *tipo = new QTableWidgetItem((*it)->get_Tipo()); table->setItem(row,0,ID); table->setItem(row,1,valore); table->setItem(row,2,tipo); row++; } } else{ table->setRowCount(row); emit tabella_vuota(); } } void listaOp::doppio_click(int r){ select_opera=table->item(r,0)->text().toInt(); emit richiesta_info(select_opera); } void listaOp::click_singolo(int r){ select_opera=table->item(r,0)->text().toInt(); emit selezione(select_opera); } listaOp::~listaOp(){ delete table; delete layout_table; } void listaOp::abilita_doppio_click(){ connect(table,SIGNAL(cellDoubleClicked(int,int)),this,SLOT(doppio_click(int))); emit abilita_funzioni(); } void listaOp::disabilita_doppio_click(){ disconnect(table,SIGNAL(cellDoubleClicked(int,int)),this,SLOT(doppio_click(int))); emit disabilita_funzioni(); }
true
5dc5a994fdbca144cc041d16b7beaade99855e1b
C++
RitzyDatta/Graphics
/bresenham.cpp
UTF-8
1,220
2.890625
3
[]
no_license
#include<graphics.h> #include<conio.h> #include<stdio.h> #include<math.h> #define fx(x) (getmaxx()/2 + x) #define fy(y) (getmaxy()/2 - y) void initial(int, int); void bres(int,int,int,int); main() { int x1,y1,x2,y2,x; printf("\nenter starting coordinates: "); scanf("%d %d", &x1,&y1); printf("\nenter ending coordinates: "); scanf("%d %d", &x2,&y2); bres(x1,y1,x2,y2); getch(); } void bres(int x1, int y1, int x2, int y2) { initial(640,480); int dx,dy,di,ds,dt,x,y,s; dx=(abs)(x2-x1); dy=(abs)(y2-y1); di=2*dy-dx; ds=2*dy; dt=2*(dy-dx); if(x1>x2) { x=x2; y=y2; s=x1; } else { x=x1; y=y1; s=x2; } putpixel(fx(x),fy(y),10); while(x<s) { x++; if(di<0) di=di+ds; else { y++; di=di+dt; } putpixel(fx(x),fy(y),10); delay(10); } } void initial(int x, int y) { initwindow(x,y); line(0,getmaxy()/2,getmaxx(),getmaxy()/2); line(getmaxx()/2,0,getmaxx()/2,getmaxy()); }
true
1d33bad035e83ff2139d219b3bf3d6c69d1331e8
C++
HsiangYangChu/RayTracer
/src/objects/triangle_mesh.h
UTF-8
662
2.671875
3
[]
no_license
#ifndef TRIANGLE_MESH_H #define TRIANGLE_MESH_H #include <objects/grid.h> #include <mesh.h> typedef enum { FLAT_TRIANGLE, SMOOTH_TRIANGLE } TriangleType; class TriangleMesh: public Grid { public: typedef std::shared_ptr<Mesh> Mesh_ptr; TriangleMesh(const std::string &name); ~TriangleMesh() {} void loadFromPlyFile(const char *, TriangleType, bool reverse_normals = false); virtual void deserialize(TiXmlElement *); virtual Object *clone() const { return new TriangleMesh(*this); } private: static TriangleMesh prototype; Mesh_ptr mesh; void setupVertexNormals(); }; #endif // TRIANGLE_MESH_H
true
7e4df0b1c6bdf0c4242252031d2364fea8f3a713
C++
Mcgode/kryne-engine
/kryne-engine/src/Light/DirectionalLight.cpp
UTF-8
3,763
2.71875
3
[]
no_license
/** * @file * @author Max Godefroy * @date 06/04/2021. */ #include "kryne-engine/Light/DirectionalLight.hpp" DirectionalLight::DirectionalLight(Process *process, const vec3 &color, float intensity, const vec3 &direction) : Light(process, LightType::DirectionalLight), color(color), intensity(intensity), direction(normalize(direction)), worldDirection(normalize(direction)) { this->name = "DirectionalLight"; } void DirectionalLight::transformDidUpdate() { Entity::transformDidUpdate(); worldDirection = this->getTransform()->getNormalMatrix() * this->direction; } void DirectionalLight::renderEntityDetails() { Entity::renderEntityDetails(); if (ImGui::BeginTable("DirectionalLightParams", 2)) { ImGui::TableSetupColumn("##labels", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("##values", ImGuiTableColumnFlags_WidthStretch); { auto col = this->color; ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Text("Color:"); ImGui::TableNextColumn(); ImGui::ColorEdit3("##color", value_ptr(col), ImGuiColorEditFlags_NoInputs); if (ImGui::IsItemEdited()) this->setColor(col); } { ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Text("Intensity: "); ImGui::TableNextColumn(); ImGui::DragFloat("##intensity", &intensity, 0.03f, 0.f, FLT_MAX, "%.2f"); } { vec3 dir = this->direction; ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Text("Direction: "); ImGui::TableNextColumn(); ImGui::DragFloat3("##direction", value_ptr(dir), 0.01, -1, 1); if (ImGui::IsItemEdited()) this->setDirection(dir); } { bool cs = this->castShadow; ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Text("Cast shadow: "); ImGui::TableNextColumn(); ImGui::Checkbox("##castShadow", &cs); if (cs != this->castShadow) this->setCastShadow(cs); } if (this->castShadow) { { float maxDist = this->maxShadowDistance; ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Text("Max shadow distance: "); ImGui::TableNextColumn(); ImGui::DragFloat("##maxDist", &maxDist, 0.1, 0, 1000, "%.1f"); if (ImGui::IsItemEdited()) this->setMaxShadowDistance(maxDist); } { float minDepth = this->minShadowDepth; ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Text("Min shadow depth: "); ImGui::TableNextColumn(); ImGui::DragFloat("##minDepth", &minDepth, 0.1, 0, 1000, "%.1f"); if (ImGui::IsItemEdited()) this->setMinShadowDepth(minDepth); } { int csm = this->cascadedShadowMaps; ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Text("Shadow cascades: "); ImGui::TableNextColumn(); ImGui::DragInt("##csm", &csm, 0.01, 0, 4); if (ImGui::IsItemEdited()) this->setCascadedShadowMaps(csm); } } ImGui::EndTable(); } }
true
c417282e83c12134fda883710f39ab72388158b6
C++
NirTaly/DataStructures
/wet2/library2.cpp
UTF-8
1,584
2.671875
3
[]
no_license
#include "library2.h" #include "agency_managment.h" using namespace DS; void *Init() { AgencyManager* DS = new AgencyManager(); return (void*)DS; } StatusType AddAgency(void *DS) { if (!DS) { return FAILURE; } try { ((AgencyManager*)DS)->AddAgency(); } catch(const std::bad_alloc&) { return ALLOCATION_ERROR; } catch(const InvalidInput&) { return INVALID_INPUT; } return SUCCESS; } StatusType SellCar(void *DS, int agencyID, int typeID, int k) { if (!DS) { return FAILURE; } try { ((AgencyManager*)DS)->SellCar(agencyID, typeID, k); } catch(const std::bad_alloc&) { return ALLOCATION_ERROR; } catch(const InvalidInput&) { return INVALID_INPUT; } catch(const Failure&) { return FAILURE; } return SUCCESS; } StatusType UniteAgencies(void *DS, int agencyID1, int agencyID2) { if (!DS) { return FAILURE; } try { ((AgencyManager*)DS)->UniteAgencies(agencyID1, agencyID2); } catch(const std::bad_alloc&) { return ALLOCATION_ERROR; } catch(const InvalidInput&) { return INVALID_INPUT; } catch(const Failure&) { return FAILURE; } return SUCCESS; } StatusType GetIthSoldType(void *DS, int agencyID, int i, int* res) { if (!DS) { return FAILURE; } try { ((AgencyManager*)DS)->GetIthSoldType(agencyID, i, res); } catch(const std::bad_alloc&) { return ALLOCATION_ERROR; } catch(const InvalidInput&) { return INVALID_INPUT; } catch(const Failure&) { return FAILURE; } return SUCCESS; } void Quit(void** DS) { if (DS) { delete ((AgencyManager*)*DS); *DS = NULL; } }
true
67d62054450f14570d71ee5a412178a60753fb59
C++
corri108/CorrtexEngine
/CorrtexEngine/CorrtexTetrahedron.cpp
UTF-8
1,198
2.78125
3
[]
no_license
#include "stdafx.h" #include "CorrtexTetrahedron.h" //a basic tetrahedron primitive CorrtexTetrahedron::CorrtexTetrahedron() : CorrtexTetrahedron::CorrtexTetrahedron(vec3(0), 1.0f) { } CorrtexTetrahedron::CorrtexTetrahedron(vec3 pos, float size) { //transform / matrix stuff this->position = pos; this->startingPosition = pos; SetScaleUniform(size); this->startingScale = vec3(size); //vertex / drawing stuff for creating a tetrehedron this->vertexCount = 12; this->vertexBufferData = new GLfloat[this->vertexCount * 3] { 0,0, 0.35f,//1 -0.5f, 0, -0.5f,//2 0.5f, 0, -0.5f,//3 0,0.5f, -0.2125f,//4 -0.5f, 0, -0.5f,//2 0.5f, 0, -0.5f,//3 0,0.5f, -0.2125f,//4 0,0, 0.35f,//1 0.5f, 0, -0.5f,//3 0,0.5f, -0.2125f,//4 0,0, 0.35f,//1 -0.5f, 0, -0.5f//2 }; this->colorBufferData = new GLfloat[this->vertexCount * 3] { 0, 0, 0.5f, 0.5f, 0, 0.5f, 0.5f, 0, 0.5f, 0, 0, 0.5f, 0.5f, 0, 0.5f, 0.5f, 0, 0.5f, 0, 0, 0.5f, 0.5f, 0, 0.5f, 0.5f, 0, 0.5f, 0, 0, 0.5f, 0.5f, 0, 0.5f, 0.5f, 0, 0.5f }; this->name = "CorrtexTetrahedron Instance"; this->UVBufferData = NULL; this->UVCoordCount = 0; } CorrtexTetrahedron::~CorrtexTetrahedron() { }
true
4a42fcdf908884e213788148d08f1309c66a07c7
C++
dezed/mantid
/Framework/Geometry/src/MDGeometry/QLab.cpp
UTF-8
1,354
2.515625
3
[]
no_license
#include "MantidGeometry/MDGeometry/QLab.h" #include "MantidGeometry/MDGeometry/MDFrame.h" namespace Mantid { namespace Geometry { //---------------------------------------------------------------------------------------------- /** Constructor */ QLab::QLab() : m_unit(new Mantid::Kernel::InverseAngstromsUnit) {} const std::string QLab::QLabName = "QLab"; Kernel::UnitLabel QLab::getUnitLabel() const { // Forward request on return m_unit->getUnitLabel(); } const Kernel::MDUnit &QLab::getMDUnit() const { return *m_unit; } bool QLab::canConvertTo(const Mantid::Kernel::MDUnit &otherUnit) const { /* Inter frame conversion is possible, but requires additional information. Forbidden for time being. */ return *this->m_unit == otherUnit; } std::string QLab::name() const { return QLab::QLabName; } QLab *QLab::clone() const { return new QLab; } Mantid::Kernel::SpecialCoordinateSystem QLab::equivalientSpecialCoordinateSystem() const { return Mantid::Kernel::SpecialCoordinateSystem::QLab; } bool QLab::isQ() const { return true; } bool QLab::isSameType(const MDFrame &frame) const { auto isSameType = true; try { const auto &tmp = dynamic_cast<const QLab &>(frame); UNUSED_ARG(tmp); } catch (std::bad_cast &) { isSameType = false; } return isSameType; } } // namespace Geometry } // namespace Mantid
true
2dcd6141087c49b4fe205868b2220764f3feabff
C++
ImSahilShaikh/Data-Structures-and-Algorithm
/STL-CPP/stl_unorderedset.cpp
UTF-8
541
3.359375
3
[]
no_license
#include<iostream> #include<unordered_set> using namespace std; int main() { //similar to set but order is not maintained //uses bucket //hashing is used to insert into buckets //insertion, deletion and search has average constant time unordered_set<int> s{1,5,1,6,2,5,2,3,4}; auto search = s.find(2); if(search!=s.end()) { cout<<"found"<<endl; } else { cout<<"not found"<<endl; } for(auto &e : s) { cout<<e<<"\t"; } cout<<endl; return 0; }
true
47e56449ce6461b3c6f98f5c281bf064a7279ebf
C++
shashwat286/IPMP
/Week8/tree_43.cpp
UTF-8
483
4.03125
4
[]
no_license
TreeNode* trimBST(TreeNode* root, int low, int high) { if(root==NULL) return NULL; root->left=trimBST(root->left,low,high); root->right=trimBST(root->right,low,high); if(root->val<low) { TreeNode* rChild=root->right; return rChild; } if(root->val>high) { TreeNode* lChild=root->left; return lChild; } return root; }
true
72f77f816230793f614203cf21106fb105950982
C++
flankersky/vector_ap_bsw
/amsr-vector-fs-libosabstraction/lib/libosabstraction-interface/include/osabstraction/io/net/address/socket_address_interface.h
UTF-8
3,903
2.53125
3
[]
no_license
/********************************************************************************************************************** * COPYRIGHT * ------------------------------------------------------------------------------------------------------------------- * \verbatim * Copyright (c) 2018 by Vector Informatik GmbH. All rights reserved. * * This software is copyright protected and proprietary to Vector Informatik GmbH. * Vector Informatik GmbH grants to you only those rights as set out in the license conditions. * All other rights remain with Vector Informatik GmbH. * \endverbatim * ------------------------------------------------------------------------------------------------------------------- * FILE DESCRIPTION * -----------------------------------------------------------------------------------------------------------------*/ /** \file * \brief Abstract interface to work with socket addresses. * * \details - * *********************************************************************************************************************/ #ifndef LIB_LIBOSABSTRACTION_INTERFACE_INCLUDE_OSABSTRACTION_IO_NET_ADDRESS_SOCKET_ADDRESS_INTERFACE_H_ #define LIB_LIBOSABSTRACTION_INTERFACE_INCLUDE_OSABSTRACTION_IO_NET_ADDRESS_SOCKET_ADDRESS_INTERFACE_H_ /********************************************************************************************************************** * INCLUDES *********************************************************************************************************************/ #include <sys/socket.h> // sockaddr #include <cstddef> // size_t #include <string> #include <utility> // pair namespace osabstraction { namespace io { namespace net { namespace address { /** Socket address families. */ enum class SocketAddressFamily { kUnspecified, /**< Unspecified socket address family. */ kIpc, /**< IPC socket address family. */ kInet4, /**< IPv4 socket address family. */ kInet6 /**< IPv6 socket address family. */ }; /* Forward declaration for concrete socket address. */ class SocketAddress; /** * \brief Abstract interface for socket addresses. * Shall be implemented by \ref SocketAddress. */ class SocketAddressInterface { public: /** * \brief Destructor. */ virtual ~SocketAddressInterface() = default; /** * \brief Returns length of the socket address. * * \return The length of the socket address. */ virtual std::size_t Length() const = 0; /** * \brief Returns the socket address family. * * \return The socket address family. */ virtual SocketAddressFamily GetAddressFamily() const = 0; /** * \brief Returns a string with the representation of a socket address. * * \return A string representing a socket address. */ virtual std::string toString() const = 0; /** * \brief Converter to sockaddr. * TODO(visasl): This function should be moved to IPV*SocketAddress. * * \return A pointer to sockaddr. */ virtual const struct sockaddr* toSockAddr() const = 0; /** * \brief Returns a pair of strings representing a socket address. * TODO(visasl): This function should be moved to IPV*SocketAddress. It does not make sense for IPC sockets. * * \return A pair of strings representing a socket address. */ virtual std::pair<std::string, std::string> toAddressPortStrings() const = 0; /** * \brief Compares two socket addresses. * * \param other A socket address to compare to. * \return true if both socket addresses are equal and false otherwise. */ virtual bool operator==(const SocketAddress& other) const = 0; }; } // namespace address } // namespace net } // namespace io } // namespace osabstraction #endif // LIB_LIBOSABSTRACTION_INTERFACE_INCLUDE_OSABSTRACTION_IO_NET_ADDRESS_SOCKET_ADDRESS_INTERFACE_H_
true
7885d00172daa005d0741fd50ecb0561ad33bff1
C++
jhpy1024/QuadTree
/src/QuadTreeRenderer.cpp
UTF-8
2,101
3.171875
3
[ "MIT" ]
permissive
#include "QuadTreeRenderer.hpp" QuadTreeRenderer::QuadTreeRenderer(sf::RenderWindow& window, QuadTree* quadTree) : m_Window(window) , m_QuadTree(quadTree) , m_QuadColor(4, 130, 219) , m_QuadOutlineColor(sf::Color::Black) , m_PointColor(219, 93, 4) , m_PointRadius(3.f) , m_QuadOutlineThickness(2.f) { } void QuadTreeRenderer::draw() { draw(m_QuadTree); } void QuadTreeRenderer::setQuadColor(const sf::Color& color) { m_QuadColor = color; } void QuadTreeRenderer::setQuadOutlineColor(const sf::Color& color) { m_QuadOutlineColor = color; } void QuadTreeRenderer::setPointColor(const sf::Color& color) { m_PointColor = color; } void QuadTreeRenderer::setPointRadius(float radius) { m_PointRadius = radius; } void QuadTreeRenderer::setQuadOutlineThickness(float thickness) { m_QuadOutlineThickness = thickness; } void QuadTreeRenderer::draw(QuadTree* node) { if (node == nullptr) return; drawQuad(node); draw(node->m_NorthWest); draw(node->m_NorthEast); draw(node->m_SouthWest); draw(node->m_SouthEast); // We draw the points after drawing the quads so that // they don't get covered up by the quads drawPoints(node); } void QuadTreeRenderer::drawQuad(QuadTree* node) { sf::RectangleShape quad; quad.setPosition(node->m_Bounds.left, node->m_Bounds.top); quad.setSize(sf::Vector2f(node->m_Bounds.width, node->m_Bounds.height)); quad.setFillColor(m_QuadColor); quad.setOutlineColor(m_QuadOutlineColor); quad.setOutlineThickness(m_QuadOutlineThickness); m_Window.draw(quad); } void QuadTreeRenderer::drawPoints(QuadTree* node) { sf::CircleShape pointShape; pointShape.setRadius(m_PointRadius); pointShape.setFillColor(m_PointColor); for (auto& point : node->m_Points) { pointShape.setOrigin(pointShape.getLocalBounds().left + pointShape.getLocalBounds().width / 2.f, pointShape.getLocalBounds().top + pointShape.getLocalBounds().height / 2.f); pointShape.setPosition(point.x, point.y); m_Window.draw(pointShape); } }
true
77ab65d420e29670eb361a3136d01d5c032d3461
C++
stfuanu/cpp
/code/exp.cpp
UTF-8
388
3.375
3
[]
no_license
#include <iostream> #include <string.h> using namespace std; int main(){ string x; cout<<"Type the word 'samosa' in capital letter : "; cin>>x; try { if (x == "SAMOSA"){ cout<<"\nOKAY , it works . You know what are capital letters "<<endl; }else{ throw x; } } catch(string something){ cout<<"Wrong , Catch message executed "<<endl; } }
true
7403c96504bf74ade355ec60ea0bf9f04587125e
C++
flick-archieve/oop
/OOP_lab_4-5/HardworkingStudent.cpp
UTF-8
601
3.046875
3
[]
no_license
// // Created by olehh on 16-Apr-21. // #include "HardworkingStudent.h" void HardworkingStudent::handInAllAssignments() { while (!assignments.empty()) { doTask(); } cout << "All assignments done!"; } HardworkingStudent::HardworkingStudent() { std::cout<<"Hardworking student created"<<std::endl; } HardworkingStudent::~HardworkingStudent() { cout << "HardWorkingStudent was deleted"<<std::endl; } HardworkingStudent::HardworkingStudent(Student *student) : Student(student) {} void HardworkingStudent::doBestOnExams() { cout << "Exam result is 100/100. Easy!"; }
true
d5bf73b1216002b5225568303dc1afa25e779596
C++
20k/net_code_webassembly
/runtime_types.hpp
UTF-8
20,441
2.828125
3
[]
no_license
#ifndef RUNTIME_TYPES_HPP_INCLUDED #define RUNTIME_TYPES_HPP_INCLUDED #include "types.hpp" #include <optional> #include <functional> #include "template_args_helper.hpp" #include "wasm_interop_context.hpp" struct module; namespace runtime { struct addr : types::integral<uint32_t, addr>{}; struct funcaddr : addr {friend bool operator<(const funcaddr& one, const funcaddr& two);}; struct tableaddr : addr {}; struct memaddr : addr {}; struct globaladdr : addr {}; inline bool operator<(const runtime::funcaddr& one, const runtime::funcaddr& two) { return one.val < two.val; } struct externval { std::variant<funcaddr, tableaddr, memaddr, globaladdr> val; }; struct exportinst { types::name name; externval value; }; struct webasm_func { types::code funct; }; struct store; struct value; struct host_func { //void(*ptr)(void); std::function<std::optional<runtime::value>(const types::vec<runtime::value>&, runtime::store*)> ptr; }; ///uuh ///this probably should be a pointer or something to moduleinst struct funcinst { types::functype type; //moduleinst module; ///do this implicitly at runtime? std::variant<host_func, webasm_func> funct; }; struct funcelem { std::optional<funcaddr> addr; }; struct tableinst { types::vec<funcelem> elem; std::optional<types::u32> max; }; struct meminst { types::vec<uint8_t> dat; std::optional<types::u32> max; }; struct store; ///hmm ///might be better to hold a uint64_t ///and then just cast on the fly ///using a union is not better apparently struct value { std::variant<types::i32, types::i64, types::f32, types::f64> v; void from_valtype(const types::valtype& type) { switch(type.which) { case 0x7F: v = types::i32{0}; return; case 0x7E: v = types::i64{0}; return; case 0x7D: v = types::f32{0}; return; case 0x7C: v = types::f64{0}; return; default: throw std::runtime_error("Invalid value in which"); } } template<typename T> value(const T& in) { set(in); } value() = default; void set(uint32_t t) { v = types::i32{t}; } void set(int32_t t) { v = types::i32{(uint32_t)t}; } void set(uint64_t t) { v = types::i64{t}; } void set(int64_t t) { v = types::i64{(uint64_t)t}; } void set(float t) { v = types::f32{t}; } void set(double t) { v = types::f64{t}; } void set(const types::i32& in) { v = in; } void set(const types::i64& in) { v = in; } void set(const types::f32& in) { v = in; } void set(const types::f64& in) { v = in; } /*explicit operator uint32_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator int32_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator uint16_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator int16_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator uint8_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator int8_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator bool() const noexcept {return std::get<types::i32>(v).val;} explicit operator uint64_t() const noexcept {return std::get<types::i64>(v).val;} explicit operator int64_t() const noexcept {return std::get<types::i64>(v).val;} explicit operator float() const noexcept {return std::get<types::f32>(v).val;} explicit operator double() const noexcept {return std::get<types::f64>(v).val;}*/ template<typename T> auto apply(const T& t) const { if(std::holds_alternative<types::i32>(v)) return t(std::get<types::i32>(v).val); else if(std::holds_alternative<types::i64>(v)) return t(std::get<types::i64>(v).val); else if(std::holds_alternative<types::f32>(v)) return t(std::get<types::f32>(v).val); else if(std::holds_alternative<types::f64>(v)) return t(std::get<types::f64>(v).val); throw std::runtime_error("nope"); } std::string friendly_val() const { return apply([](auto concrete){return std::to_string(concrete);}); } std::string friendly() const { if(std::holds_alternative<types::i32>(v)) return "i32"; else if(std::holds_alternative<types::i64>(v)) return "i64"; else if(std::holds_alternative<types::f32>(v)) return "f32"; else if(std::holds_alternative<types::f64>(v)) return "f64"; else return "empty"; } bool is_i32() { return std::holds_alternative<types::i32>(v); } }; struct globalinst; struct moduleinst; struct store { types::vec<funcinst> funcs; types::vec<tableinst> tables; types::vec<meminst> mems; types::vec<globalinst> globals; wasm_interop_context interop_context; funcaddr allocfunction(const module& m, size_t idx); funcaddr allochostfunction(const types::functype& type, const std::function<std::optional<runtime::value>(const types::vec<runtime::value>&, runtime::store* s)>& ptr); tableaddr alloctable(const types::tabletype& type); memaddr allocmem(const types::memtype& type); globaladdr allocglobal(const types::globaltype& type, const value& v); types::vec<runtime::value> invoke(const funcaddr& address, moduleinst& minst, const types::vec<value>& vals); types::vec<runtime::value> invoke_by_name(const std::string& imported, moduleinst& minst, const types::vec<value>& vals); uint8_t* get_memory_base_ptr(); uint32_t get_memory_base_size(); }; struct wasi_ctx { static inline thread_local runtime::store* cstore = nullptr; }; template<typename T> struct wasi_ptr_t { uint32_t val = 0; constexpr static bool is_ptr = true; wasi_ptr_t() { } wasi_ptr_t(uint32_t in) { val = in; } T* operator->() const { assert(wasi_ctx::cstore); wasi_ctx::cstore->mems[0].dat.check(val); wasi_ctx::cstore->mems[0].dat.check(val + sizeof(T)); return (T*)&wasi_ctx::cstore->mems[0].dat[val]; } template<typename T1 = T, typename = std::enable_if<!std::is_same_v<T, void>>> T1& operator*() const { assert(wasi_ctx::cstore); wasi_ctx::cstore->mems[0].dat.check(val); wasi_ctx::cstore->mems[0].dat.check(val + sizeof(T)); return *(T*)&wasi_ctx::cstore->mems[0].dat[val]; } template<typename T1 = T, typename = std::enable_if<!std::is_same_v<T, void>>> T1& operator[](int idx) const { assert(val + idx * sizeof(T) + sizeof(T) <= wasi_ctx::cstore->mems[0].dat.size()); assert(val + idx >= 0); return *(T*)&wasi_ctx::cstore->mems[0].dat[val + idx * sizeof(T)]; } }; /*template<typename T> struct is_wasi_ptr { template<typename U> static constexpr decltype(std::declval<U>()::is_ptr, bool()) test_ptr(int) { return true; } template<typename U> static constexpr bool test_ptr(...) { return false; } static constexpr bool value = test_ptr<T>(int()); };*/ template<typename T, typename = int> struct is_wasi_ptr : std::false_type {}; template<typename T> struct is_wasi_ptr<T, decltype((void)T::is_ptr, 0)> : std::true_type{}; template<typename T> T get(const runtime::value& v, runtime::meminst& minst, T dummy) { if constexpr(std::is_same_v<T, uint32_t>) { return std::get<types::i32>(v.v).val; } if constexpr(std::is_same_v<T, int32_t>) { return std::get<types::i32>(v.v).val; } if constexpr(std::is_same_v<T, uint16_t>) { return std::get<types::i32>(v.v).val; } if constexpr(std::is_same_v<T, int16_t>) { return std::get<types::i32>(v.v).val; } if constexpr(std::is_same_v<T, uint8_t>) { return std::get<types::i32>(v.v).val; } if constexpr(std::is_same_v<T, int8_t>) { return std::get<types::i32>(v.v).val; } if constexpr(std::is_same_v<T, bool>) { return std::get<types::i32>(v.v).val; } if constexpr(std::is_same_v<T, uint64_t>) { return std::get<types::i64>(v.v).val; } if constexpr(std::is_same_v<T, int64_t>) { return std::get<types::i64>(v.v).val; } if constexpr(std::is_same_v<T, float>) { return std::get<types::f32>(v.v).val; } if constexpr(std::is_same_v<T, double>) { return std::get<types::f64>(v.v).val; } } template<typename T> T* get(const runtime::value& v, runtime::meminst& minst, T* dummy) { uint32_t ptr = get(v, minst, uint32_t()); if(ptr + sizeof(T) > minst.dat.size()) throw std::runtime_error("Ptr out of bounds"); return (T*)&minst.dat[ptr]; } template<typename T> wasi_ptr_t<T> get(const runtime::value& v, runtime::meminst& minst, wasi_ptr_t<T> dummy) { uint32_t ptr = get(v, minst, uint32_t()); if constexpr(std::is_same_v<T, void>) { if(ptr > minst.dat.size()) throw std::runtime_error("Ptr out of bounds"); } if constexpr(!std::is_same_v<T, void>) { if(ptr + sizeof(T) > minst.dat.size()) throw std::runtime_error("Ptr out of bounds"); } wasi_ptr_t<T> ret; ret.val = ptr; return ret; } namespace detail { template<typename T, typename... U> inline constexpr bool has_runtime(T(*func)(U... args)) { int iruntime_c = 0; ((iruntime_c += (int)std::is_same_v<U, runtime::store*>), ...); return iruntime_c > 0; } template<typename T> void type_push(types::vec<types::valtype>& in) { types::valtype type; if(std::is_same_v<T, void>) return; if(std::is_same_v<T, runtime::store*>) return; if(is_wasi_ptr<T>()) { type.set<types::i32>(); } else { type.set<T>(); } in.push_back(type); } template<typename T, typename... U> inline constexpr types::functype get_functype(T(*func)(U... args)) { types::functype ret; ((type_push<U>(ret.params)), ...); type_push<T>(ret.results); return ret; } template<typename tup, std::size_t... Is> void set_args(tup& t, const types::vec<runtime::value>& v, std::index_sequence<Is...>, runtime::store* s) { //std::tuple_element_t<Is, tup> //.get(s, std::tuple_element_t<Is, tup>()) ((std::get<Is>(t) = runtime::get(v.get<Is>(), s->mems[0], std::tuple_element_t<Is, tup>())), ...); } template<typename V, V& v, typename return_type, typename... args_type> std::optional<runtime::value> host_shim_impl(const types::vec<runtime::value>& vals, runtime::store* s) { std::tuple<args_type...> args; std::index_sequence_for<args_type...> iseq; set_args(args, vals, iseq, s); if constexpr(std::is_same_v<return_type, void>) { std::apply(v, args); return std::nullopt; } if constexpr(!std::is_same_v<return_type, void>) { return std::apply(v, args); } } template<auto& v, typename T, typename... U> auto host_shim(T(*func)(U... args)) { return &host_shim_impl<decltype(v), v, T, U...>; } template<auto& t> constexpr auto base_shim() { return host_shim<t>(t); } template<typename V, V& v, typename return_type, typename rstore, typename... args_type> std::optional<runtime::value> host_shim_impl_with_runtime(const types::vec<runtime::value>& vals, runtime::store* s) { std::tuple<args_type...> args; std::index_sequence_for<args_type...> iseq; set_args(args, vals, iseq, s); std::tuple<runtime::store*> first; std::get<0>(first) = s; if constexpr(std::is_same_v<return_type, void>) { std::apply(v, std::tuple_cat(first, args)); return std::nullopt; } if constexpr(!std::is_same_v<return_type, void>) { return std::apply(v, std::tuple_cat(first, args)); } } template<auto& v, typename T, typename... U> auto host_shim_with_runtime(T(*func)(U... args)) { return &host_shim_impl_with_runtime<decltype(v), v, T, U...>; } template<auto& t> constexpr auto base_shim_with_runtime() { return host_shim_with_runtime<t>(t); } } inline bool same_type(const value& v1, const value& v2) { if(std::holds_alternative<types::i32>(v1.v) && std::holds_alternative<types::i32>(v2.v)) return true; if(std::holds_alternative<types::i64>(v1.v) && std::holds_alternative<types::i64>(v2.v)) return true; if(std::holds_alternative<types::f32>(v1.v) && std::holds_alternative<types::f32>(v2.v)) return true; if(std::holds_alternative<types::f64>(v1.v) && std::holds_alternative<types::f64>(v2.v)) return true; return false; } template<typename T> inline auto apply(const T& t, const value& u, const value& v) { if(!same_type(u, v)) throw std::runtime_error("Not same type"); if(std::holds_alternative<types::i32>(u.v)) return t(std::get<types::i32>(u.v).val, std::get<types::i32>(v.v).val); else if(std::holds_alternative<types::i64>(u.v)) return t(std::get<types::i64>(u.v).val, std::get<types::i64>(v.v).val); else if(std::holds_alternative<types::f32>(u.v)) return t(std::get<types::f32>(u.v).val, std::get<types::f32>(v.v).val); else if(std::holds_alternative<types::f64>(u.v)) return t(std::get<types::f64>(u.v).val, std::get<types::f64>(v.v).val); else throw std::runtime_error("apply bad type"); //return t(u, v); } template<typename T> inline auto apply(const T& t, const value& u) { if(std::holds_alternative<types::i32>(u.v)) return t(std::get<types::i32>(u.v).val); else if(std::holds_alternative<types::i64>(u.v)) return t(std::get<types::i64>(u.v).val); else if(std::holds_alternative<types::f32>(u.v)) return t(std::get<types::f32>(u.v).val); else if(std::holds_alternative<types::f64>(u.v)) return t(std::get<types::f64>(u.v).val); else throw std::runtime_error("apply bad type"); //return t(u, v); } struct globalinst { value val; types::mut mut; }; struct moduleinst; ///create a wrapper for allochostfunction which deduces type and automatically creates a shim ///ok so we're up to simple arg values now ///need to automatically shim the vectorof values we get to the input function when we call it ///not 100% sure how to do that template<auto& t> funcaddr allochostsimplefunction(runtime::store& s) { types::functype type = detail::get_functype(t); if constexpr(!detail::has_runtime(t)) { auto shim = detail::base_shim<t>(); return s.allochostfunction(type, shim); } if constexpr(detail::has_runtime(t)) { auto shim = detail::base_shim_with_runtime<t>(); return s.allochostfunction(type, shim); } } template<typename T> inline types::vec<T> filter_type(const types::vec<externval>& vals) { types::vec<T> ret; for(const externval& val : vals) { if(std::holds_alternative<T>(val.val)) { ret.push_back(std::get<T>(val.val)); } } return ret; } inline types::vec<funcaddr> filter_func(const types::vec<externval>& vals) { return filter_type<funcaddr>(vals); } inline types::vec<tableaddr> filter_table(const types::vec<externval>& vals) { return filter_type<tableaddr>(vals); } inline types::vec<memaddr> filter_mem(const types::vec<externval>& vals) { return filter_type<memaddr>(vals); } inline types::vec<globaladdr> filter_global(const types::vec<externval>& vals) { return filter_type<globaladdr>(vals); } struct preserved_data_segment { uint32_t do_i = 0; uint32_t dend = 0; types::vec<uint8_t> bytes; }; struct func_descriptor { types::typeidx tidx; std::string name; std::string module; }; ///so this is constructed from our module ///which is the section representation we constructed earlier struct moduleinst { types::vec<types::functype> typel; types::vec<funcaddr> funcaddrs; types::vec<tableaddr> tableaddrs; types::vec<memaddr> memaddrs; types::vec<globaladdr> globaladdrs; std::map<funcaddr, func_descriptor> funcdescs; types::vec<exportinst> exports; types::vec<preserved_data_segment> data_segment; }; constexpr size_t page_size = 64*1024; ///128 MB constexpr size_t sandbox_mem_cap = 128 * 1024 * 1024; } /*explicit operator uint32_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator int32_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator uint16_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator int16_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator uint8_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator int8_t() const noexcept {return std::get<types::i32>(v).val;} explicit operator bool() const noexcept {return std::get<types::i32>(v).val;} explicit operator uint64_t() const noexcept {return std::get<types::i64>(v).val;} explicit operator int64_t() const noexcept {return std::get<types::i64>(v).val;} explicit operator float() const noexcept {return std::get<types::f32>(v).val;} explicit operator double() const noexcept {return std::get<types::f64>(v).val;}*/ /*template<> uint32_t runtime::value::get<uint32_t>(runtime::store* s) { return std::get<types::i32>(v).val; }*/ #endif // RUNTIME_TYPES_HPP_INCLUDED
true
87d408e663353a863132f4ef54f328c93ce23745
C++
hanselcheong/CS122
/Labs/Lab11/Lab11/task1.h
UTF-8
393
2.9375
3
[ "MIT" ]
permissive
// .h part #include <iostream> using std::cin; using std::cout; using std::endl; class Base { public: virtual void testFunction (); }; class Derived : public Base { public: void testFunction (); }; // .cpp part void Base::testFunction () { cout << "Base class" << endl; } void Derived::testFunction () { cout << "Derived class" << endl; }
true
733bd6e31df4927698f29c212ba39537a800d149
C++
AsmitaSethiya/Cpp_Practice_Questions
/check_trangle.cpp
UTF-8
539
3.59375
4
[]
no_license
#include<iostream> using namespace std; int main() { int sidea, sideb, sidec; cout<<"Enter side a: "; cin>>sidea; cout<<"Enter side b: "; cin>>sideb; cout<<"Enter side c: "; cin>>sidec; if(sidea == sideb && sideb == sidec) { cout<<"This is an equilateral triangle. \n"; } else if(sidea == sideb || sidea == sidec || sideb == sidec) { cout<<"This is an isosceles traingle. \n"; } else { cout<<"This is a scalence traingle. \n"; } return 0; }
true
74d1ffba77b16b1f3f9f65b4c8504cc8f976ecb8
C++
EndBug/olinfo-solutions
/semiprimo/semiprimo.cpp
UTF-8
937
3.203125
3
[ "MIT" ]
permissive
#include <iostream> #include <fstream> #include <math.h> using namespace std; bool isPrime(int n) { if (n <= 1) return false; else if (n <= 3) return true; else if (n%2 == 0 || n%3 == 0) return false; int i = 5; while (i*i <= n) { if (n%i == 0 || n%(i+2) == 0) return false; i += 6; } return true; } int main() { ifstream in("input.txt"); ofstream out("output.txt"); int n, f[2]; in >> n; if (isPrime(n)) { f[0] = -1; f[1] = 0; } else { int first = -1, second = 0; for (int i = 1; i < n/2; i++) { double dn = static_cast<double>(n); if (isPrime(i) && isPrime(n/i) && n % i == 0) { first = i; second = n/i; break; } } f[0] = first; f[1] = second; } out << f[0]; if (f[1] != 0) out << " " << f[1]; return 0; }
true
1444ef3388c12ce4db810ecebf5525dd3a73a510
C++
mathieumg/hockedu
/trunk/Sources/C++/Arbre/ArbreRendu.h
ISO-8859-1
3,923
2.6875
3
[]
no_license
/////////////////////////////////////////////////////////////////////////////// /// @file ArbreRendu.h /// @author Martin Bisson /// @date 2007-01-28 /// @version 1.0 /// /// @addtogroup razergame RazerGame /// @{ /////////////////////////////////////////////////////////////////////////////// #ifndef __ARBRE_ARBRERENDU_H__ #define __ARBRE_ARBRERENDU_H__ #include "NoeudComposite.h" #ifndef __APPLE__ #include <unordered_map> #define HashMap std::unordered_map #else #include <ext/hash_map> #define HashMap __gnu_cxx::hash_map namespace __gnu_cxx { template<> struct hash< std::string > { size_t operator()( const std::string& x ) const { return hash< const char* >()( x.c_str() ); } }; } #endif class NoeudAbstrait; class UsineNoeud; class TerrainTest; /////////////////////////////////////////////////////////////////////////// /// @class ArbreRendu /// @brief Classe d'arbre de rendu qui contient la racine de l'arbre de /// rendu avec les usines qui permettent d'ajouter des noeuds /// cet arbre. /// /// La profondeur de cet arbre est limite par la taille de la pile /// des matrices et la taille de la pile des noms pour la slection /// OpenGL, tant donn que chaque niveau de l'arbre effectue un /// "push" sur chacune de ces piles lors du rendu. L'arbre ne /// vrifie pas que la profondeur reste sous la limite, mais il /// offre des fonctions permettant de le vrifier aisment. /// /// @author Martin Bisson /// @date 2007-01-28 /////////////////////////////////////////////////////////////////////////// class ArbreRendu : public NoeudComposite { public: friend TerrainTest; /// Constructeur par dfaut. ArbreRendu(class Terrain* pField); /// Destructeur. virtual ~ArbreRendu(); /// Ajoute une usine associe un type de noeud. inline void ajouterUsine( const RazerKey type, const UsineNoeud* usine ); /// Cre un nouveau noeud. NoeudAbstrait* creerNoeud( const RazerKey typeNouveauNoeud ) const; /// Cre et ajoute un nouveau noeud l'arbre. NoeudAbstrait* ajouterNouveauNoeud( const RazerKey nomParent, const RazerKey typeNouveauNoeud ); /// Calcule la profondeur maximale possible pour l'arbre de rendu. static unsigned int calculerProfondeurMaximale(); virtual const ArbreRendu* GetTreeRoot() const {return this;} /// Initialisation du NoeudAbstrait partir d'un element XML virtual bool initFromXml(const XmlElement* element); /// Creation du noeud XML du Noeud virtual XmlElement* createXmlNode(); private: /// Dfinition du type pour l'association du nom d'un type vers l'usine /// correspondante. typedef HashMap< RazerKey, const UsineNoeud* > RegistreUsines; /// Association du nom d'un type vers l'usine correspondante. RegistreUsines usines_; }; //////////////////////////////////////////////////////////////////////// /// /// @fn inline void ArbreRendu::ajouterUsine(const std::string& type, const UsineNoeud* usine) /// /// Cette fonction permet d'ajouter une usine qui sera ensuite utilise /// pour crer de nouveaux noeuds. /// /// @param[in] type : La chane qui identifie le type de noeuds crer /// avec cette usine. /// @param[in] usine : L'usine ajoute. /// /// @return Aucune. /// //////////////////////////////////////////////////////////////////////// inline void ArbreRendu::ajouterUsine( const RazerKey type, const UsineNoeud* usine ) { usines_[type] = usine; } #endif // __ARBRE_ARBRERENDU_H__ /////////////////////////////////////////////////////////////////////////////// /// @} ///////////////////////////////////////////////////////////////////////////////
true
c9f856210915b2a9451414eba4065d4f774de38d
C++
MatrixDeity/Problems
/Codeforces_447B/main.cpp
WINDOWS-1251
1,923
3.34375
3
[]
no_license
/** : DZY , . c DZY wc. s = s1 s2... s|s| (|s| - ) f(s), f(s) = SUM(1, |s|, wsi * i). DZY s. k , . ? : s (1 <= |s| <= 10^3). k (0 <= k <= 10^3). wa wz. 1000. : - , DZY . */ #include <iostream> #include <algorithm> using namespace std; const int LETTERS = 26; string str; int weight[LETTERS]; int k, ans(0), maxW(0), len; int main() { cin >> str >> k; len = str.size(); for (int i = 0; i < LETTERS; ++i) { cin >> weight[i]; maxW = max(maxW, weight[i]); } for (int i = 0; i < len; ++i) ans += (i + 1) * weight[str[i] - 'a']; for (int i = len; i < len + k; ++i) ans += maxW * (i + 1); cout << ans; return 0; }
true
4eb6b5ad68fc10ec8893fa2e319047cc7c4ab4b4
C++
lld2006/my-c---practice-project
/060/060.old.cpp
UTF-8
2,972
2.859375
3
[]
no_license
#include "../lib/tools.h" #include "../lib/typedef.h" #include <cassert> #include <cstdio> #include <algorithm> int limit = 20000; bool isPrimeJoint(int p1, int p2, vector<int>& primes){ if(p1%3==1 && p2%3==2) return false; if(p1%3==2 && p2%3==1) return false; int prod = 1; while(prod < p1){ prod *=10; p2 *= 10; } int px = p1 + p2; return isPrime(px, primes); } int main(){ vector<int> primes; int upper = 10000; primeWithin(primes, limit);//2 3 5 7 primes[2] = 3;// ignore 2 5 which could not be primejointer; int cnt = 0; for(unsigned int i = 2; i< primes.size(); ++i){ if(primes[i] < upper) ++cnt; else break; } //candidates are picked for each number vector<vector<int> > plist (cnt, IntVec() ); for(int i =2; i < cnt +2; ++i){ int px = primes[i]; for(int j= i+1; j < cnt +2; ++j){ if(isPrimeJoint(px, primes[j], primes) && isPrimeJoint(primes[j], px, primes)) plist[i-2].push_back(primes[j]); } } vector<int> v12, v123, v1234; for(unsigned int i1 = 0; i1 < plist.size(); ++i1){ //start of all the list int p1 = primes[i1+2]; // first prime owner for(unsigned int i2 =0; i2 < plist[i1].size(); ++i2){ int p2=plist[i1][i2]; int pi2 = binary_find(p2, primes); assert( pi2 > 0); v12.clear(); set_intersection(plist[i1].begin(), plist[i1].end(), plist[pi2-2].begin(), plist[pi2-2].end(), back_inserter(v12)); if(v12.size() < 3) continue; for(unsigned int i3 =0 ; i3 < v12.size(); ++i3){ int p3 = v12[i3]; int pi3 = binary_find(p3, primes); assert(pi3 >0); v123.clear(); set_intersection(plist[pi3-2].begin(), plist[pi3-2].end(), v12.begin(), v12.end(), back_inserter(v123)); if(v123.size() < 2 ) continue; for(unsigned int i4 = 0; i4 < v123.size(); ++i4){ int p4 = v123[i4]; int pi4 = binary_find(p4, primes); assert(pi4 > 0); v1234.clear(); set_intersection(plist[pi4-2].begin(), plist[pi4-2].end(), v123.begin(), v123.end(), back_inserter(v1234)); if( v1234.empty()) continue; else{ int p5 = v1234.front(); printf("%d %d %d %d %d %d\n",p1, p2, p3, p4, p5, p1+p2+p3+p4+p5); } } } } } }
true
5da8b337c9ac91fce12586b3becd6a1cbdcd282d
C++
herbberg/utm
/tmXsd/gen-xsd-type/complex-bin.hh
UTF-8
2,115
2.65625
3
[]
no_license
/** * @author Takashi Matsushita * Created: 19 Aug 2014 */ /** @todo nope */ #ifndef complex_bin_hh #define complex_bin_hh /*====================================================================* * declarations *====================================================================*/ /*-----------------------------------------------------------------* * headers *-----------------------------------------------------------------*/ #include <string> #include <vector> #include <iostream> /*-----------------------------------------------------------------* * constants *-----------------------------------------------------------------*/ /* nope */ namespace tmxsd { /** * This struct implements data structure for bin complex type */ struct bin { /** constructor */ bin() : number_(), minimum_(), maximum_(), bin_id_(), scale_id_(), debug_() { if (debug_) std::cout << "bin::ctor" << std::endl; } /** destructor */ virtual ~bin() { if (debug_) std::cout << "bin::dtor" << std::endl; } // setters and getters const std::string& minimum() const { return minimum_; } void minimum(const std::string& x) { minimum_ = x; } const std::string& maximum() const { return maximum_; } void maximum(const std::string& x) { maximum_ = x; } unsigned int number() const { return number_; } void number(const unsigned int x) { number_ = x; } unsigned int bin_id() const { return bin_id_; } void bin_id(const unsigned int x) { bin_id_ = x; } unsigned int scale_id() const { return scale_id_; } void scale_id(const unsigned int x) { scale_id_ = x; } bool debug() const { return debug_; } void debug(const bool x) { debug_ = x; } private: unsigned int number_; /**< bin number */ std::string minimum_; /**< bin minimum */ std::string maximum_; /**< bin maximum */ unsigned int bin_id_; /**< bin_id in DB */ unsigned int scale_id_; /**< scale_id in DB */ bool debug_; /**< debug flag */ }; // struct bin } // namespace tmxsd #endif // complex_bin_hh /* eof */
true
9d5c3fb4fb8d2c08ebd2087c735257b35d45f90e
C++
flyforhigh/vendor_mediatek_proprietary_hardware
/audio/common/include/SpeechDriverFactory.h
UTF-8
1,436
2.75
3
[ "Apache-2.0" ]
permissive
#ifndef ANDROID_SPEECH_DRIVER_FACTORY_H #define ANDROID_SPEECH_DRIVER_FACTORY_H #include <utils/Vector.h> #include "AudioType.h" #include "SpeechDriverInterface.h" namespace android { class SpeechDriverFactory { public: virtual ~SpeechDriverFactory(); static SpeechDriverFactory *GetInstance(); SpeechDriverInterface *GetSpeechDriver(); SpeechDriverInterface *GetSpeechDriverByIndex(const modem_index_t modem_index); modem_index_t GetActiveModemIndex() const; status_t SetActiveModemIndex(const modem_index_t modem_index); status_t SetActiveModemIndexByAudioMode(const audio_mode_t audio_mode); protected: SpeechDriverFactory(); /** * sub factory class can override this function * to create types of speech driver instances */ virtual status_t CreateSpeechDriverInstances(); virtual status_t DestroySpeechDriverInstances(); /** * centralized management of speech drivers */ modem_index_t mActiveModemIndex; SpeechDriverInterface *mSpeechDriver1; // for modem 1 SpeechDriverInterface *mSpeechDriver2; // for modem 2 SpeechDriverInterface *mSpeechDriverExternal; // for modem External private: /** * singleton pattern */ static SpeechDriverFactory *mSpeechDriverFactory; }; } // end namespace android #endif // end of ANDROID_SPEECH_DRIVER_FACTORY_H
true
d27e9ce3b8416d6569ec14edb95826ab9dae0996
C++
NatalyTinoco/Proyectos_academicos
/Arduino/JUegodemesacondados.ino
UTF-8
4,548
2.90625
3
[]
no_license
// Wire Master Reader // by Nicholas Zambetti <http://www.zambetti.com> // Demonstrates use of the Wire library // Reads data from an I2C/TWI slave device // Refer to the "Wire Slave Sender" example for use with this // Created 29 March 2006 // This example code is in the public domain. #include <Wire.h> int a=22; int b=24; int c=26; int d=28; int e=30; int f=32; int g=34; int a1=31; int b1=33; int c1=35; int d1=37; int e1=39; int f1=41; int g1=43; int jugador1=0; int jugador2=0; int jugador3=0; int jugador4=0; int dado1; int dado2; int ganador; void setup() { Wire.begin(); // join i2c bus (address optional for master) Serial.begin(9600); // start serial for output pinMode (a,OUTPUT); //declaramos el led como salida pinMode (b,OUTPUT); pinMode (c,OUTPUT); pinMode (d,OUTPUT); pinMode (e,OUTPUT); pinMode (f,OUTPUT); pinMode (g,OUTPUT); pinMode (a1,OUTPUT); pinMode (b1,OUTPUT); pinMode (c1,OUTPUT); pinMode (d1,OUTPUT); pinMode (e1,OUTPUT); pinMode (f1,OUTPUT); pinMode (g1,OUTPUT); } void loop() { Wire.requestFrom(8, 6); // request 6 bytes from slave device #8 while (Wire.available()) // slave may send less than requested { int dado1 = Wire.read(); // receive a byte as character Serial.print(dado1); // print the character switch(dado1){ case 1: digitalWrite(e,HIGH); delay(1000); digitalWrite(e,LOW); delay(1000); break; case 2: digitalWrite(a,HIGH); digitalWrite(g,HIGH); delay(1000); digitalWrite(a,LOW); digitalWrite(g,LOW); break; case 3: digitalWrite (a,HIGH); digitalWrite (g,HIGH); digitalWrite (e,HIGH); delay ( 1000); digitalWrite (a,LOW); digitalWrite (g,LOW); digitalWrite (e,LOW); break; case 4: digitalWrite (a,HIGH); digitalWrite (c,HIGH); digitalWrite (d,HIGH); digitalWrite (g,HIGH); delay ( 1000); digitalWrite (a,LOW); digitalWrite (c,LOW); digitalWrite (d,LOW); digitalWrite (g,LOW); break; case 5: digitalWrite (a,HIGH); digitalWrite (c,HIGH); digitalWrite (d,HIGH); digitalWrite (g,HIGH); digitalWrite (e,HIGH); delay (1000); digitalWrite (a,LOW); digitalWrite (c,LOW); digitalWrite (d,LOW); digitalWrite (g,LOW); digitalWrite (e,LOW); break; case 6: digitalWrite (a,HIGH); digitalWrite (b,HIGH); digitalWrite (c,HIGH); digitalWrite (d,HIGH); digitalWrite (g,HIGH); digitalWrite (f,HIGH); delay (1000); digitalWrite (a,LOW); digitalWrite (b,LOW); digitalWrite (c,LOW); digitalWrite (d,LOW); digitalWrite (g,LOW); digitalWrite (f,LOW); break; } //delay(10); Wire.requestFrom(9, 6); } while (Wire.available()) // slave may send less than requested { int dado2 = Wire.read(); // receive a byte as character Serial.print(dado2); // print the character switch(dado2){ case 1: digitalWrite(e1,HIGH); delay(1000); digitalWrite(e1,LOW); delay(1000); break; case 2: digitalWrite(a1,HIGH); digitalWrite(g1,HIGH); delay(1000); digitalWrite(a1,LOW); digitalWrite(g1,LOW); break; case 3: digitalWrite (a1,HIGH); digitalWrite (g1,HIGH); digitalWrite (e1,HIGH); delay ( 1000); digitalWrite (a1,LOW); digitalWrite (g1,LOW); digitalWrite (e1,LOW); break; case 4: digitalWrite (a1,HIGH); digitalWrite (c1,HIGH); digitalWrite (d1,HIGH); digitalWrite (g1,HIGH); delay ( 1000); digitalWrite (a1,LOW); digitalWrite (c1,LOW); digitalWrite (d1,LOW); digitalWrite (g1,LOW); break; case 5: digitalWrite (a1,HIGH); digitalWrite (c1,HIGH); digitalWrite (d1,HIGH); digitalWrite (g1,HIGH); digitalWrite (e1,HIGH); delay (1000); digitalWrite (a1,LOW); digitalWrite (c1,LOW); digitalWrite (d1,LOW); digitalWrite (g1,LOW); digitalWrite (e1,LOW); break; case 6: digitalWrite (a1,HIGH); digitalWrite (b1,HIGH); digitalWrite (c1,HIGH); digitalWrite (d1,HIGH); digitalWrite (g1,HIGH); digitalWrite (f1,HIGH); delay (1000); digitalWrite (a1,LOW); digitalWrite (b1,LOW); digitalWrite (c1,LOW); digitalWrite (d1,LOW); digitalWrite (g1,LOW); digitalWrite (f1,LOW); break; } } while (ganador==0){ jugador1=dado1+dado2; jugador2=dado1+dado2; jugador3=dado1+dado2; jugador4=dado1+dado2; if (jugador1==100){ ganador=jugador1; ganador=1; } if(jugador2==100){ ganador=jugador2; ganador=1; } if(jugador3==100){ ganador=jugador3; ganador=1; } if(jugador4==100){ ganador=jugador4; ganador=1; } } }
true
dbff3a5e009888b0aa5f31ac4c7825f4aa813611
C++
dracohan/code
/code_book/Thinking C++/master1/Chapter 8/Ex/Ex19.cpp
WINDOWS-1251
471
3.0625
3
[]
no_license
//: EX08:Ex19.cpp // float. // // . class X { float f1; const float cf1; public: X(); ~X(); }; X::X() : f1(0.6f), cf1(0.7f) { } X::~X() {} int main() { X float_x; }
true
da391fae73d4d82f3f3c5e4e743a3b0fa51b7296
C++
Senka2112/squirrel_manipulation
/squirrel_object_manipulation/src/utils/math_utils.cpp
UTF-8
4,625
3.40625
3
[]
no_license
#include "squirrel_object_manipulation/math_utils.hpp" using namespace std; using namespace arma; double distancePoints(double x1, double y1, double z1, double x2, double y2, double z2){ return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) + (z1-z2)*(y1-y2)); } double distancePoints(double x1, double y1, double x2, double y2){ return distancePoints (x1, y1, 0, x2, y2, 0); } // angle defined with three points with point 2 as center double angle3PointsAbs(double x1, double y1, double x2, double y2, double x3, double y3){ double d12 = distancePoints(x1, y1, x2, y2); double d13 = distancePoints(x1, y1, x3, y3); double d23 = distancePoints(x3, y3, x2, y2); //angle point1 - point2 - point3 double angle = acos((d12 * d12 + d23 * d23 - d13 * d13) / (2 * d12 * d23)); if (angle > 3.14) angle = angle - 2*3.14; if (angle< -3.14) angle = angle + 2*3.14; if (isnan(angle)) angle = 0; return angle; } // angle defined with three points 1-2-3 double angle3Points(double x1, double y1, double x2, double y2, double x3, double y3){ //angle between first and second point double a12 = atan2(y1 - y2, x1 -x2); if (isnan(a12)) a12 = 0; //angle between third and second point double a32 = atan2(y3 - y2, x3 -x2); if (isnan(a32)) a32 = 0; return a32 - a12; } // distance of point 0 from line defined by points 1 and 2 double distance2Line(double x0, double y0, double x1, double y1, double x2, double y2){ return fabs((x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1)) / distancePoints(x1, y1, x2, y2); } vec closestPointOnLine(double x0, double y0, double x1, double y1, double x2, double y2){ vec result(2); //slope first line double m1 = (y2 - y1)/(x2 - x1); //intercept first line double b1 = y1 - m1 * x1; //perpendicular line slope double m2 = - 1 / m1; //perpendicular line intercept - conatining x0 double b2 = y0 - m2 * x0; //intersection point result(0) = -(b1 - b2)/(m1 - m2); result(1) = m2 * result(0) + b2; return result; } vec rotate2DVector(double x, double y, double angle){ vec rot_vec_(2); rot_vec_(0) = x * cos(angle) - y * sin(angle); rot_vec_(1) = x * sin(angle) + y * cos(angle); return rot_vec_; } vec rotate2DVector(vec vec_, double angle){ return rotate2DVector(vec_(0), vec_(1), angle); } //get vector norm double getNorm(vec v){ return distancePoints (v(0), v(1), 0, 0, 0, 0); } //reflection of point p1 over the point p2 vec reflectPointOverPoint(double x0, double y0, double x1, double y1){ vec result(2); result(0) = 2 * x0 - x1; result(1) = 2 * y0 - y1; return result; } //angle difference for rotation double rotationDifference(double angle, double theta_robot){ double err_th = angle - theta_robot; if(err_th > M_PI) err_th = - (2 * M_PI - err_th); if(err_th < -M_PI) err_th = 2 * M_PI + err_th; return err_th; } // angle of a vector (x,y) double getVectorAngle(double x, double y){ double th = atan2(y,x); if (isnan(th)) th = 0.0; return th; } double getGaussianVal(double x, double sigma, double mi){ double r = exp( - pow( x - mi, 2) / (2 * pow(sigma, 2))); if (isnan(r)) r = 1.0; return r; } int sign(const double z) { return (z > 0.0) ? 1 : - 1; } vec pointsOnLineWithDistanceFromPoint(double x1, double y1, double x2, double y2, double d){ //slope double m = (y2 - y1)/(x2 - x1); //intercept line double b = y1 - m * x1; vec points(4); points(0) = x1 + d / sqrt(1 + m * m); points(1) = m * points(0) + b; points(2) = x1 - d / sqrt(1 + m * m); points(3) = m * points(2) + b; return points; } vec pointOnLineWithDistanceFromPointInner(double x1, double y1, double x2, double y2, double d){ vec points = pointsOnLineWithDistanceFromPoint(x1, y1, x2, y2, d); vec point(2); if (distancePoints(points(0), points(1), x2, y2) < distancePoints(points(2), points(3), x2, y2)){ point(0) = points(0); point(1) = points(1); } else{ point(0) = points(2); point(1) = points(3); } return point; } vec pointOnLineWithDistanceFromPointOuter(double x1, double y1, double x2, double y2, double d){ vec points = pointsOnLineWithDistanceFromPoint(x1, y1, x2, y2, d); vec point(2); if (distancePoints(points(0), points(1), x2, y2) > distancePoints(points(2), points(3), x2, y2)){ point(0) = points(0); point(1) = points(1); } else{ point(0) = points(2); point(1) = points(3); } return point; }
true
124770cc83ecd7987a73f0b33f9a528a5718c2ca
C++
Dawidsoni/programming-competitions
/OI/XX/mul/Multidrink.cpp
UTF-8
3,561
2.796875
3
[]
no_license
#include<stdio.h> #include<vector> using namespace std; enum rodzaj {bialy,lacznik,sciezka}; class kopiec { public: vector<kopiec*> polacz; bool czy_jest, czy_sciezka; int numer; static int licznik; kopiec() : czy_jest(true), czy_sciezka(false) {numer = licznik++;} operator int() { return numer; } void dodaj_polaczenie(kopiec * ktory) { polacz.push_back(ktory); } }; int kopiec::licznik = 0; kopiec graf[500001]; int wynik[500000]; int n, wcz1, wcz2, hierarchia = 100, ile = 0; kopiec * wsk = &graf[1], * nastepny = NULL; bool czy_mozna = true; void ustaw_sciezke(kopiec & punkt,kopiec & ktory_nie) { static bool czy_rek = true; if(punkt==n) czy_rek = false; if(czy_rek) { for(int i=0;i<punkt.polacz.size();i++) { if(*punkt.polacz[i]!=ktory_nie&&czy_rek) ustaw_sciezke(*punkt.polacz[i],punkt); } } if(!czy_rek) { punkt.czy_sciezka = true; } } rodzaj jaki_rodzaj(kopiec & punkt) { if(punkt.czy_sciezka) return sciezka; if(punkt.polacz.size()>2) return lacznik; return bialy; } int ust_hierar_przez(kopiec & punkt, kopiec & przez) { rodzaj r_przez = jaki_rodzaj(przez), r_punkt = jaki_rodzaj(punkt); if(punkt==n) return 10; if(r_przez!=sciezka&&r_punkt!=sciezka&&punkt.polacz.size()<2) return 1; if(r_przez!=sciezka&&r_punkt!=sciezka) return 3; if(r_punkt!=sciezka&&punkt.polacz.size()<2) return 6; if(r_punkt!=sciezka) return 7; return 9; } int ust_hierar(kopiec & punkt, kopiec & zrodlo) { rodzaj r_punkt = jaki_rodzaj(punkt); if(punkt==n) return 10; if(r_punkt!=sciezka&&punkt.polacz.size()<2&&zrodlo.polacz.size()<3) return 2; if(r_punkt!=sciezka&&punkt.polacz.size()<2) return 4; if(r_punkt!=sciezka) return 5; return 8; } int main() { scanf("%d",&n); for(int i=0;i+1<n;i++) { scanf("%d%d",&wcz1,&wcz2); graf[wcz1].dodaj_polaczenie(&graf[wcz2]); graf[wcz2].dodaj_polaczenie(&graf[wcz1]); } ustaw_sciezke(graf[1],graf[0]); //graf[n].czy_sciezka = graf[1].czy_sciezka = false; for(;;ile++) { wynik[ile] = *wsk; wsk->czy_jest = false; hierarchia = 100; nastepny = NULL; for(vector<kopiec*>::iterator it = wsk->polacz.begin();it!= wsk->polacz.end();it++) { for(vector<kopiec*>::iterator it2 = (*it)->polacz.begin(); it2!=(*it)->polacz.end();it2++){ if((*it2)->czy_jest==false) continue; int hier = ust_hierar_przez(*(*it2),*(*it)); if(hier<hierarchia) { hierarchia = hier; nastepny = *it2; } } if((*it)->czy_jest==false) continue; int hier = ust_hierar(*(*it),*wsk); if(hier<hierarchia) { hierarchia = hier; nastepny = *it; } } if(nastepny==NULL) { czy_mozna =false; break; } else if(ile+2==n&&(*nastepny==n)) { break; } else if((hierarchia==10)||ile==n) { czy_mozna = false; break; } wsk = nastepny; } if(czy_mozna) { for(int i=0;i-1<ile;i++) { printf("%d\n",wynik[i]); } printf("%d\n",n); }else { printf("BRAK\n"); } return 0; }
true
279a40f44888ddc83aa40ec54f561c642f49ad99
C++
Codefiring/Data-structures-learning-in-college
/数据结构实验任选 (学生)vc6/习题6/交换左右子树的主程序文件.cpp
GB18030
334
2.6875
3
[]
no_license
//ļ.cpp #include<iostream.h> #include<stdio.h> #include"ĽṹͶ.h" #include"Ľ.h" #include".h" #include".h" void main() { bitree*pb; pb=creattree(); preorder(pb); cout<<endl; swap(pb); preorder(pb); cout<<endl; }
true
faf634f0e5ef24278085a56ef691cacf4cb17942
C++
hau-tao/CS13-Advanced-Computer-Programming-Labs-Assignments
/assignment04/BBoard.h
UTF-8
2,407
3.359375
3
[]
no_license
// =============== BEGIN ASSESSMENT HEADER ================ /// @file main.cpp /// @brief assignment03/asignment3.cpp /// /// @author htao001 [htao001@ucr.edu] /// @date August 8, 2014 /// /// @par Plagiarism Section /// I hereby certify that I have not received assistance on assignment, /// or used code, from ANY outside source other than the instruction team. // ================== END ASSESSMENT HEADER =============== #ifndef __BBOARD_H_ #define __BBOARD_H_ #include <iostream> #include <vector> #include <string> #include "Message.h" #include "User.h" using namespace std; class BBoard { private: string title; vector<User> user_list; User current_user; vector<Message> message_list; public: BBoard(); BBoard(const string &ttl); void setup(const string &input_file); void login(); void run(); private: void add_user(istream &infile, const string &name, const string &pass); bool user_exists(const string &name, const string &pass) const; User get_user (const string &name) const; void display () const; void add_message(); }; #endif //bboard.h #ifndef __BBOARD_H_ //inclusion guard #define __BBOARD_H_ #include "user.h" //include user.h #include "message.h"//include message.h #include <iostream>//iostream and vector #include <vector> using namespace std; //standard namespace class Bboard { //Bboard class private: string title; //title of Bboard vector<User> user_list; //vector or users User current_user; //current user logged in vector<Message> message_list; //message list vector public: Bboard(); //defauly constructor Bboard( const string &ttl ); //constructor void setup(); //setup function void login(); //login function void run(); //run function private: void add_user(const string& name, const string& pass); //adds user to the user_list vector bool user_exists(const string& name, const string& pass) const; //checks if the user is a valid user User get_user(const string& name) const; //gets a user with the name void display() const; //displays the format for the messages void add_message( const string &name ); //adds a message into the message vector }; #endif //__BBOARD_H_
true
852f8aeb7497dd70787e001c812eb33f22e75315
C++
mipopov/Class-String
/main.cpp
UTF-8
6,636
3.59375
4
[]
no_license
#include "mystring.h" #include <stdio.h> #include <assert.h> void test1(); void test2(); void test3(); void test4(); void test5(); void test6(); void test7(); void test8(); void test9(); void test10(); void test11(); void test12(); void test13(); void test14(); void test15(); void test16(); void test17(); int main() { test1(); test2(); test3(); test4(); test5(); test6(); test7(); test8(); test9(); test10(); test11(); test12(); test13(); test14(); test15(); test16(); test17(); return 0; } void test1() { printf("Test 1: Default Constructor\n"); MyString s; assert(s[0] == '\0'); printf("%c\n", s[0]); printf("Test1 succesfully done\n"); printf("\n"); } void test2() { printf("Test 2: Constructor: MyString S (Hello)\n"); MyString s("HELLO"); assert(s[0] == 'H'); assert(s[1] == 'E'); assert(s[2] == 'L'); assert(s[3] == 'L'); assert(s[4] == 'O'); std::cout << s << std::endl; printf("Test2 succesfully done\n"); printf("\n"); } void test3() { printf("Test 3: Constructor: MyString S (MyString)\n"); MyString s("HELLO"); MyString Str(s); assert(s[0] == 'H'); assert(s[1] == 'E'); assert(s[2] == 'L'); assert(s[3] == 'L'); assert(s[4] == 'O'); std::cout << s << std::endl; printf("Test3 succesfully done\n"); printf("\n"); } void test4() { printf("Test 4: Size()\n"); MyString s("HELLO"); assert(s.Size() == 5); std::cout << s.Size() << std::endl; printf("Test4 succesfully done\n"); printf("\n"); } void test5(){ printf("Test 5: Comparing MyStrings, operator ==\n"); MyString s("HELLO"); MyString v("HELLo"); if (s == v){ std::cout << s << " " << v << std::endl; } else printf("Strings are not equal\n"); printf("Test5 succesfully done\n"); printf("\n"); } void test6(){ printf("Test 6: Equaling\n"); MyString s("HELLO"); MyString v("HELLO world!!!"); std::cout << s << std::endl; s = v; assert(s[0] == 'H'); assert(s[1] == 'E'); assert(s[2] == 'L'); assert(s[3] == 'L'); assert(s[4] == 'O'); assert(s[5] == ' '); assert(s[6] == 'w'); assert(s[7] == 'o'); assert(s[8] == 'r'); assert(s[9] == 'l'); assert(s[10] == 'd'); assert(s[11] == '!'); assert(s[12] == '!'); assert(s[13] == '!'); assert(s.Size() == 14); std::cout << s << std::endl; printf("Test6 succesfully done\n"); printf("\n"); } void test7(){ printf("Test 7: MyString + MyString\n"); MyString s("world "); MyString v("HELLO world!!!"); std::cout << s << " " << v << std::endl; s += v; assert(s[0] == 'w'); assert(s[1] == 'o'); assert(s[2] == 'r'); assert(s[3] == 'l'); assert(s[4] == 'd'); assert(s[5] == ' '); assert(s[6] == 'H'); assert(s[7] == 'E'); assert(s[8] == 'L'); assert(s[9] == 'L'); assert(s[10] == 'O'); assert(s[11] == ' '); assert(s[12] == 'w'); assert(s[13] == 'o'); assert(s[14] == 'r'); assert(s[15] == 'l'); assert(s[16] == 'd'); assert(s[17] == '!'); assert(s[18] == '!'); assert(s[19] == '!'); assert(s.Size() == 20); std::cout << s << std::endl; printf("Test7 succesfully done\n"); printf("\n"); } void test8(){ printf("Test 8: Comparing MyStrings, operator !=\n"); MyString s("HELLO"); MyString v("Jam"); if (s != v){ std::cout << s << " " << v << std::endl; } else printf("Strings are equal\n"); printf("Test8 succesfully done\n"); printf("\n"); } void test9(){ printf("Test 9: Empty function\n"); MyString s; assert(s[0] == '\0'); if (s.Empty()) printf("Yes, String is empry\n"); else printf("No, string aren't empry\n"); printf("Test9 succesfully done\n"); printf("\n"); } void test10(){ printf("Test 10: Front && Back functions\n"); MyString s("World in peace"); assert(s.Front() == 'W'); assert(s.Back() == 'e'); std::cout << s.Front() << " " << s.Back() << std::endl; printf("Test10 succesfully done\n"); printf("\n"); } void test11(){ printf("Test 11: Clear function\n"); MyString s("Hello World"); std::cout << s << std::endl; s.Clear(); if (s.Empty()) printf("Yes, String is empry\n"); else printf("No, string aren't empry\n"); printf("Test11 succesfully done\n"); printf("\n"); } void test12(){ printf("Test 12: Comparing MyStrings, operator <=\n"); MyString s("HELLO"); MyString v("He"); if (v <= s){ std::cout << s << " " << v << std::endl; } else printf("String1 are not <= than String2\n"); printf("Test12 succesfully done\n"); printf("\n"); } void test13(){ printf("Test 13: Comparing MyStrings, operator >=\n"); MyString s("HELLO"); MyString v("He"); if (s >= v){ std::cout << s << " " << v << std::endl; } else printf("String1 are not >= than String2\n"); printf("Test13 succesfully done\n"); printf("\n"); } void test14(){ printf("Test14: Operator +\n"); MyString S1("HELLO "); MyString S2("world!!!"); MyString s; s = S1 + S2; assert(s[0] == 'H'); assert(s[1] == 'E'); assert(s[2] == 'L'); assert(s[3] == 'L'); assert(s[4] == 'O'); assert(s[5] == ' '); assert(s[6] == 'w'); assert(s[7] == 'o'); assert(s[8] == 'r'); assert(s[9] == 'l'); assert(s[10] == 'd'); assert(s[11] == '!'); assert(s[12] == '!'); assert(s[13] == '!'); std::cout << s << std::endl; printf("Test14 succesfully done\n"); printf("\n"); } void test15() { printf("Test 15: Constructor MyString(5)\n"); MyString s(5); assert(s.Size() == 5); printf("Test15 succesfully done\n"); printf("\n"); } void test16() { printf("Test 16: Push_back function\n"); MyString s("Worl"), s1; s1 = s.Push_back('d'); assert(s1[4] == 'd'); std::cout << s1 << std::endl; printf("Test16 succesfully done\n"); printf("\n"); } void test17() { printf("Test 17: Pop_back function\n"); MyString s("Peacef"), s1; s1 = s.Pop_back(); std::cout << s1 << std::endl; printf("Test17 succesfully done\n"); printf("\n"); }
true
4a7d82500c23ee8fd6b5ea7f3f17bdf357ba4e7a
C++
Wait021/Course-Reviwe
/面向对象程序设计/历年卷/《面向对象程序设计》近3年试卷/17级OOP试题/OOP17/OOP17-Exam05.cpp
GB18030
6,007
3.59375
4
[]
no_license
// OOP17-Exam05.cpp #include <iostream> using namespace std; template <typename T> class Stack { private: T *x; int top, max; public: Stack(int Max=5); // ٹ캯 Stack(const Stack &s); // ڿ캯 ~Stack(); // Stack & operator=(const Stack &s); // ֵܸ int Size() const; // ݻȡջеǰӵеԪظ bool Empty() const; // ޵ջΪʱtrue򷵻false bool Top(T &t) const; // ߵջΪǿʱtrueͨȡջԪأ򷵻false bool Push(const T &t); // ൱ջʱfalse򷵻true t ѹջ bool Pop(T &t); // ᵱջΪʱfalse򷵻trueջԪسջջԪش t }; ////////////////////////////////// template <typename T> Stack<T>::Stack(int Max): x(NULL),top(-1),max(0) // ٹ캯 { if(Max<=0) return; x = new T[max=Max]; } template <typename T> Stack<T>::Stack(const Stack &s): x(NULL),top(-1),max(0) // ڿ캯 { *this = s; } template <typename T> Stack<T>::~Stack() // { if(x!=NULL) delete [] x; top = -1; max = 0; } template <typename T> Stack<T> & Stack<T>::operator=(const Stack<T> &s) // ֵܸ { if(this==&s) return *this; if(x!=NULL) delete [] x; top = s.top; max = s.max; if(s.x!=NULL) { x = new T[max]; for(int i=0; i<=top; i++) // ջϵ븴 x[i] = s.x[i]; } else x = NULL; } template <typename T> int Stack<T>::Size() const // ݻȡջеǰӵеԪظ { return top + 1; } template <typename T> bool Stack<T>::Empty() const // ޵ջΪʱtrue򷵻false { return top == -1; } template <typename T> bool Stack<T>::Top(T &t) const // ߵջΪǿʱtrueͨȡջԪأ򷵻false { if(top >= 0) { t = x[top]; return true; } return false; } template <typename T> bool Stack<T>::Push(const T &t) // ൱ջʱfalse򷵻true t ѹջ { if(top < max-1) { x[++top] = t; return true; } return false; } template <typename T> bool Stack<T>::Pop(T &t) // ᵱջΪʱfalse򷵻trueջԪسջջԪش t { if(top >= 0) { t = x[top--]; return true; } return false; } ////////////////////////////////////////// int main0501() { int x[] = {0, 1, 1, 1, 1, 1, 1, 0, 0, 0}; int y[] = {47, 26, 71, 38, 69, 12, 67, 99, 35, 94}; int n = sizeof(x)/sizeof(*x); int m = sizeof(y)/sizeof(*y); Stack<int> s; int i, j, z; for(i=j=0; i<n; i++,j%=m) { if(x[i]==1) { if(s.Push(y[j])) cout << y[j++] << " ջ" << endl; else cout << "ջ޷ջ" << endl; } else { if(s.Pop(z)) cout << z << " ջ" << endl; else cout << "ջѿգԪسջ" << endl; } } return 0; } ////////////////////////////////////////// bool Trans1(unsigned int n, int Base=2) // ʮƷǸתBase(BaseΪ2,3,...,36) { if(n==0) { cout << 0 << endl; return true; } char BASE[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int x; Stack<int> s; for( ; n!=0; n/=Base) if(!s.Push(n%Base)) return false; while(s.Size()>0) { s.Pop(x); cout << BASE[x]; } return true; } int main0502() { int base[] = {2, 3, 4, 5, 8, 10, 16, 36}; int n = sizeof(base)/sizeof(*base), x=255; for(int i=0; i<n; i++) { cout << '(' << x << ")_10 = ("; if(!Trans1(x, base[i])) cout << "ջ޷ת"; cout << ")_" << base[i] << endl; } return 0; } //////////////////////////////////////////// int Pos(char c, const char *str); // Ѿ壬˴ int Matching1(const char *str) { Stack<char> s; char c; for(int i=0; str[i]!='\0'; i++) { if(Pos(str[i], "([{")>=0) { if(s.Push(str[i])==false) // ջ return -1; } if(Pos(str[i], ")]}")>=0) { if(s.Pop(c)==false) // ջѿ return -2; if(str[i]==')' && c!='(' || str[i]==']' && c!='[' || str[i]=='}' && c!='{') return -3; // Ųƥ } } return s.Empty()?0:-4; // ַѴϣջǷδƥŶ } int main0503() { char a[][100] = {"(())abc{[(])}", "(()))abc{[]}", "((((((((((()", ")(", "(()()abc{[]}", "(())abc{[]()}", "abc", "int main()\n{\n\tint array[10];\n\treturn(0);\n}\n" }; int n = sizeof(a)/sizeof(*a); for(int i=0; i<n; i++) { cout << a[i]; switch(Matching1(a[i])) { case -1: cout << " ջռ̫С޷жϡ" << endl; break; case -2: cout << " ջѿգ˵ʱŶš" << endl; break; case -3: cout << " ಻ƥ䡣" << endl; break; case -4: cout << " ַϣûƥꡣ" << endl; break; default: cout << " ƥȷ" << endl; break; } } return 0; } //////////////////////////////////////// #include <cmath> double cube(double x); int main0504() // ָָ { Stack<double(*)(double)> fs; double (*f)(double);// ָfָijһຯڵַ˴fָһdoubleβΣҷΪdoubleĺ fs.Push(sin); // Ϊڵַ fs.Push(cos); fs.Push(sqrt); fs.Push(exp); fs.Push(cube); fs.Pop(f); cout << f(2) << endl; fs.Pop(f); cout << f(1) << endl; fs.Pop(f); cout << f(2) << endl; fs.Pop(f); cout << f(0) << endl; fs.Pop(f); cout << f(0) << endl; return 0; } int main05() { main0501(); cout << endl; main0502(); cout << endl; main0503(); cout << endl; main0504(); cout << endl; return 0; }
true
b6f487006cb4de7e7d49a19086cd6672f25eac84
C++
loupus/pgfe
/lib/dmitigr/pgfe/sql_string.hpp
UTF-8
15,021
2.6875
3
[ "Zlib" ]
permissive
// -*- C++ -*- // Copyright (C) Dmitry Igrishin // For conditions of distribution and use, see files LICENSE.txt or pgfe.hpp #ifndef DMITIGR_PGFE_SQL_STRING_HPP #define DMITIGR_PGFE_SQL_STRING_HPP #include "dmitigr/pgfe/basics.hpp" #include "dmitigr/pgfe/composite.hpp" #include "dmitigr/pgfe/dll.hpp" #include "dmitigr/pgfe/parameterizable.hpp" #include "dmitigr/pgfe/types_fwd.hpp" #include <algorithm> #include <cassert> #include <cstdint> #include <list> #include <locale> #include <optional> #include <string> #include <string_view> #include <utility> #include <vector> namespace dmitigr::pgfe { /** * @ingroup utilities * * @brief A preparsed SQL strings. * * A dollar sign ("$") followed by digits is used to denote a parameter with * explicitly specified position. A colon (":") followed by alphanumerics is * used to denote a named parameter with automatically assignable position. * The valid parameter positions range is [1, max_parameter_count()]. * * Examples of valid SQL strings: * * - the SQL string without parameters: * @code{sql} SELECT 1 @endcode * * - the SQL string with the positional and named parameters: * @code{sql} SELECT 2, $1::int, :name::text @endcode * * - the SQL string with named parameter: * @code{sql} WHERE :name = 'Dmitry Igrishin' @endcode */ class Sql_string final : public Parameterizable { public: /// @name Constructors /// @{ /// Default-constructible. (Constructs an empty instance.) Sql_string() = default; /** * @brief The constructor. * * @param text Any part of SQL statement, which may contain multiple * commands and comments. Comments can contain an associated extra data. * * @remarks While the SQL input may contain multiple commands, the parser * stops on either first top-level semicolon or zero character. * * @see extra(). */ DMITIGR_PGFE_API Sql_string(std::string_view text); /// @overload DMITIGR_PGFE_API Sql_string(const std::string& text); /// @overload DMITIGR_PGFE_API Sql_string(const char* text); /// Copy-constructible. DMITIGR_PGFE_API Sql_string(const Sql_string& rhs); /// Copy-assignable. DMITIGR_PGFE_API Sql_string& operator=(const Sql_string& rhs); /// Move-constructible. DMITIGR_PGFE_API Sql_string(Sql_string&& rhs) noexcept; /// Move-assignable. DMITIGR_PGFE_API Sql_string& operator=(Sql_string&& rhs) noexcept; /// Swaps the instances. DMITIGR_PGFE_API void swap(Sql_string& rhs) noexcept; /// @} /// @see Parameterizable::positional_parameter_count(). std::size_t positional_parameter_count() const noexcept override { return positional_parameters_.size(); } /// @see Parameterizable::named_parameter_count(). std::size_t named_parameter_count() const noexcept override { return named_parameters_.size(); } /// @see Parameterizable::parameter_count(). std::size_t parameter_count() const noexcept override { return (positional_parameter_count() + named_parameter_count()); } /// @see Parameterizable::has_positional_parameters(). bool has_positional_parameters() const noexcept override { return !positional_parameters_.empty(); } /// @see Parameterizable::has_named_parameters(). bool has_named_parameters() const noexcept override { return !named_parameters_.empty(); } /// @see Parameterizable::has_parameters(). bool has_parameters() const noexcept override { return (has_positional_parameters() || has_named_parameters()); } /// @see Parameterizable::parameter_name(). std::string_view parameter_name(const std::size_t index) const noexcept override { assert(positional_parameter_count() <= index && index < parameter_count()); return (named_parameters_[index - positional_parameter_count()])->str; } /// @see Parameterizable::parameter_index(). std::size_t parameter_index(const std::string_view name) const noexcept override { return named_parameter_index(name); } /// @returns `true` if this SQL string is empty. bool is_empty() const noexcept { return fragments_.empty(); } /// @returns `true` if this SQL string is consists only of comments and blank line(-s). DMITIGR_PGFE_API bool is_query_empty() const noexcept; /** * @returns `false` if the parameter at specified `index` is missing. For * example, the SQL string * @code{sql} SELECT :p, $3 @endcode * has two missing parameters at indexes `0` and `1`. * * @par Requires * `(index < positional_parameter_count())`. * * @remarks Missing parameters can only be eliminated by using methods append() * or replace_parameter(). Thus, by replacing the parameter `p` with `$2, $1` * in the example above, missing parameters will be eliminated because the * statement will become the following: * @code{sql} SELECT $2, $1, $3 @endcode * * @see append(), replace_parameter(). */ bool is_parameter_missing(const std::size_t index) const noexcept { assert(index < positional_parameter_count()); return !positional_parameters_[index]; } /** * @returns `true` if this SQL string has a positional parameter with the * index `i` such that `(is_parameter_missing(i) == false)`. * * @see is_parameter_missing(). */ bool has_missing_parameters() const noexcept { return any_of(cbegin(positional_parameters_), cend(positional_parameters_), [](const auto is_present) { return !is_present; }); } /** * @brief Appends the specified SQL string. * * @par Effects * This instance contains the given `appendix`. If `(is_query_empty() == true)` * before calling this method, then extra data of `appendix` is appended to the * extra data of this instance. * * @par Exception safety guarantee * Strong. */ DMITIGR_PGFE_API void append(const Sql_string& appendix); /** * @brief Replaces the parameter named by the `name` with the specified * `replacement`. * * @par Requires * `(has_parameter(name) && &replacement != this)`. * * @par Effects * This instance contains the given `replacement` instead of the parameter * named by the `name`. The extra data will *not* be affected. * * @par Exception safety guarantee * Strong. * * @see has_parameter(). */ DMITIGR_PGFE_API void replace_parameter(std::string_view name, const Sql_string& replacement); /// @returns The result of conversion of this instance to the instance of type `std::string`. DMITIGR_PGFE_API std::string to_string() const; /// @returns The query string that's actually passed to a PostgreSQL server. DMITIGR_PGFE_API std::string to_query_string() const; /// @returns The extra data associated with this instance. /// /// An any data can be associated with an object of type Sql_string. The /// initial associations can be specified in the *related comments*. The /// related comments - are comments that have no more than one newline /// character in between themselves and the content following them. The /// content following the related comments should be neither named parameter /// nor positional parameter nor consisting only of spaces nor empty. /// /// Consider the example of the SQL input: /// @code{sql} /// -- This is the unrelated comment (because 2 new line feeds follows after it). /// -- $id$unrelated$id$ /// /// -- This is the related one line comment 1 /// -- $id$select-all$id$ /// /* $where$ /// * num > 0 /// * AND num < :num /// * $where$ /// */ /// -- This is the related one line comment 2 /// SELECT * FROM table WHERE :where; /// @endcode /// The SQL code above contains just one actual query: /// @code{sql}SELECT * FROM table WHERE :where@endcode /// This query has seven related comments and two unrelated comments (at the /// beginning) because there are two newline characters following them. Next, /// there are two data associations specified as a dollar-quoted string /// constants tagged as `id` and `where`. The valid characters of the tags /// are: alphanumerics, the underscore character and the dash. /// Please, note, that the content in between the named tags might consist to /// multiple lines. There are rules of the content formatting in such cases: /// 1. The leading and trailing newline characters are always ignored and other /// newline characters are always preserved; /// 2. If the content begins with non newline character, then the content is /// associated exactly as provided, i.e. all indentations are preserved; /// 3. If the content begins with a newline character then the following lines /// will be left-aligned relative the *most left non space character*. In case /// of the sequence of one-line comments, the most left non space character are /// always follows the one-line comment marker ("--"). In case of the multi-line /// comment, the most left non space character can be a character that follows the /// asterisk with a space ("* "), or just the most left character. /// /// Examples: /// /// Example 1. The misaligned content of the association specified in the multi-line comment /// /// @code{sql} /// /* /// * $text1$ /// * one /// * two /// * three /// * $text1$ /// */ /// SELECT 1, 2, 3 /// @endcode /// /// The content of the `text1` association is "one\n * two\nthree". /// /// Example 2. The aligned content of the association specified in the multi-line comment /// /// @code{sql} /// /* /// * $text2$ /// * one /// * two /// * three /// * $text2$ /// */ /// SELECT 1, 2, 3 /// @endcode /// /// The content of the `text2` association is "one\ntwo\nthree". /// /// Example 3. The content of the association specified in the sequence of one-line comments /// /// @code{sql} /// -- $text3$ /// --one /// -- two /// -- three /// -- $text3$ /// SELECT 1, 2, 3 /// @endcode /// /// The content of the `text3` association is "one\n two\n three". Composite& extra() noexcept { return const_cast<Composite&>(static_cast<const Sql_string*>(this)->extra()); } /// @overload DMITIGR_PGFE_API const Composite& extra() const; private: friend Sql_vector; static DMITIGR_PGFE_API std::pair<Sql_string, std::string_view::size_type> parse_sql_input(std::string_view, const std::locale& loc); struct Fragment final { enum class Type { text, one_line_comment, multi_line_comment, named_parameter, positional_parameter }; Fragment(const Type tp, const std::string& s) : type(tp) , str(s) {} Type type; std::string str; }; using Fragment_list = std::list<Fragment>; std::locale loc_; Fragment_list fragments_; std::vector<bool> positional_parameters_; // cache std::vector<Fragment_list::const_iterator> named_parameters_; // cache mutable bool is_extra_data_should_be_extracted_from_comments_{true}; mutable std::optional<Composite> extra_; // cache bool is_invariant_ok() const noexcept override { const bool positional_parameters_ok = ((positional_parameter_count() > 0) == has_positional_parameters()); const bool named_parameters_ok = ((named_parameter_count() > 0) == has_named_parameters()); const bool parameters_ok = ((parameter_count() > 0) == has_parameters()); const bool parameters_count_ok = (parameter_count() == (positional_parameter_count() + named_parameter_count())); const bool empty_ok = !is_empty() || !has_parameters(); const bool extra_ok = is_extra_data_should_be_extracted_from_comments_ || extra_; const bool parameterizable_ok = Parameterizable::is_invariant_ok(); return positional_parameters_ok && named_parameters_ok && parameters_ok && parameters_count_ok && empty_ok && extra_ok && parameterizable_ok; } // --------------------------------------------------------------------------- // Initializers // --------------------------------------------------------------------------- void push_back_fragment(const Fragment::Type type, const std::string& str) { fragments_.emplace_back(type, str); assert(is_invariant_ok()); } void push_text(const std::string& str) { push_back_fragment(Fragment::Type::text, str); } void push_one_line_comment(const std::string& str) { push_back_fragment(Fragment::Type::one_line_comment, str); } void push_multi_line_comment(const std::string& str) { push_back_fragment(Fragment::Type::multi_line_comment, str); } void push_positional_parameter(const std::string& str); void push_named_parameter(const std::string& str); // --------------------------------------------------------------------------- // Updaters // --------------------------------------------------------------------------- // Exception safety guarantee: strong. void update_cache(const Sql_string& rhs); // --------------------------------------------------------------------------- // Generators // --------------------------------------------------------------------------- std::vector<Fragment_list::const_iterator> unique_fragments(Fragment::Type type) const; std::size_t unique_fragment_index( const std::vector<Fragment_list::const_iterator>& unique_fragments, const std::string_view str) const noexcept; std::size_t named_parameter_index(const std::string_view name) const noexcept { return positional_parameter_count() + unique_fragment_index(named_parameters_, name); } std::vector<Fragment_list::const_iterator> named_parameters() const { return unique_fragments(Fragment::Type::named_parameter); } // --------------------------------------------------------------------------- // Predicates // --------------------------------------------------------------------------- static bool is_space(const char c, const std::locale& loc) noexcept { return isspace(c, loc); } static bool is_blank_string(const std::string& str, const std::locale& loc) noexcept { return all_of(cbegin(str), cend(str), [&loc](const auto& c){return is_space(c, loc);}); } static bool is_comment(const Fragment& f) noexcept { return (f.type == Fragment::Type::one_line_comment || f.type == Fragment::Type::multi_line_comment); } static bool is_text(const Fragment& f) noexcept { return (f.type == Fragment::Type::text); } // --------------------------------------------------------------------------- // Extra data // --------------------------------------------------------------------------- /// Represents an API for extraction the extra data from the comments. struct Extra; }; /// Sql_string is swappable. inline void swap(Sql_string& lhs, Sql_string& rhs) noexcept { lhs.swap(rhs); } } // namespace dmitigr::pgfe #ifdef DMITIGR_PGFE_HEADER_ONLY #include "dmitigr/pgfe/sql_string.cpp" #endif #endif // DMITIGR_PGFE_SQL_STRING_HPP
true
e4445ac1b450736696fd84d5f52be7386d1f61a2
C++
dquangit/GenericKnapsack
/GA.cpp
UTF-8
5,276
2.734375
3
[]
no_license
#include <iostream> #include <cstdio> #include <fstream> #include <stack> #include <algorithm> #include <ctime> #define maximum 100001 #define num_of_individual 40 using namespace std; fstream file; struct datatype { char* filename; }; datatype data[100]; struct __item { int w; int v; }; __item item[10000]; struct __individual { bool selection[maximum]; int value; int weight; }; __individual individual[50]; bool myfunction(__individual a,__individual b) { if (a.value>b.value) return true; return false; } int n,max_value,min_value; float capacity; void get_data() { data[0].filename="data/s10.txt"; data[1].filename="data/s10-1.txt"; data[2].filename="data/s50.txt"; data[3].filename="data/s50-1.txt"; data[4].filename="data/s100.txt"; data[5].filename="data/s100-1.txt"; data[6].filename="data/s500.txt"; data[7].filename="data/s500-1.txt"; data[8].filename="data/s1000.txt"; data[9].filename="data/s1000-1.txt"; data[10].filename="data/s5000.txt"; data[11].filename="data/s5000-1.txt"; data[12].filename="data/s10000.txt"; data[13].filename="data/s10000-1.txt"; data[14].filename="data/s100000.txt"; data[15].filename="data/u10.txt"; data[16].filename="data/u50.txt"; data[17].filename="data/u100.txt"; data[18].filename="data/u500.txt"; data[19].filename="data/u1000.txt"; data[20].filename="data/wc10.txt"; data[21].filename="data/wc50.txt"; data[22].filename="data/wc1000.txt"; data[23].filename="data/wc5000.txt"; data[24].filename="data/wc10000.txt"; } int f_size(char* filename) { float capicity; file.open(filename,ios::in); file>>capicity; int t; int d=0; while(file) { file>>t; d++; } file.close(); return d/2; } void input(char* filename) { n=f_size(filename); file.open(filename,ios::in); file>>capacity; cout<<"input: "<<endl; cout<<"number of items: "<<n<<endl; cout<<"capacity:\t "<<capacity<<endl; for (int i=1;i<=n;i++) { file>>item[i].v; } for (int i=1;i<=n;i++) { file>>item[i].w; } file.close(); } void create_individual(__individual &a) { int tmp; a.value=0; a.weight=0; for (int j=1;j<=n;j++) { tmp=rand()%2; a.selection[j]=tmp; if (tmp==1) { a.weight+=item[j].w; a.value+=item[j].v; } } } void create_individual_population() { srand(time(NULL)); max_value=min_value=0; for (int i=0;i<=num_of_individual;i++) { do { create_individual(individual[i]); } while (individual[i].weight>capacity); if (individual[max_value].value<individual[i].value) max_value=i; if (individual[min_value].value>individual[i].value) min_value=i; } sort(individual,individual+num_of_individual+1,myfunction); } __individual crossover(__individual a,__individual b) { __individual tmp; do { tmp.value=tmp.weight=0; for (int i=1;i<=n;i++) { if (rand()%2==0) tmp.selection[i]=a.selection[i]; else tmp.selection[i]=b.selection[i]; if (tmp.selection[i]==1) { tmp.value+=item[i].v; tmp.weight+=item[i].w; } } } while (tmp.weight>capacity); return tmp; } __individual mutation(__individual a) { __individual tmp=a; do { int tmp=rand()%n+1; if (a.selection[tmp]==1) { a.selection[tmp]=0; a.value-=item[tmp].v; a.weight-=item[tmp].w; } else { a.selection[tmp]=1; a.value+=item[tmp].v; a.weight+=item[tmp].w; } } while (a.weight>capacity); return a; } void selection(__individual tmp_individual) { if (tmp_individual.value>individual[num_of_individual].value) { individual[num_of_individual]=tmp_individual; sort(individual,individual+num_of_individual+1,myfunction); } } void Genetic_Algorithm() { int tmp1,tmp2,tmp3; int d=0; __individual tmp_individual; do { tmp1=rand()%(num_of_individual+1); tmp2=rand()%(num_of_individual+1); tmp3=rand()%(num_of_individual+1); tmp_individual=crossover(individual[tmp1],individual[tmp2]); selection(tmp_individual); tmp_individual=mutation(individual[tmp3]); selection(tmp_individual); d++; //cout<<d<<endl; if (d==100000) break; } //while (true); while (individual[num_of_individual].value!=individual[0].value); cout<<d<<endl; } void output() { /* for (int i=1;i<=n;i++) { cout<<item[i].v<<"\t"<<item[i].w<<"\t"<<endl; } */ cout<<endl; for (int i=0;i<=num_of_individual;i++) { for (int j=1;j<=n;j++) cout<<individual[i].selection[j]; cout<<"\t"<<individual[i].value<<"\t"<<individual[i].weight; cout<<endl; } //cout<<max_value<<" "<<min_value<<endl; } int main() { get_data(); input(data[10].filename); create_individual_population(); //output(); cout<<endl; Genetic_Algorithm(); cout<<individual[0].value<<" "<<individual[0].weight<<endl; cout<<endl; //output(); }
true
d9510085735d4e8761c3f2e4c6e28af7d7a95894
C++
mpzadmin/yuc
/Yousefi/class1.cpp
UTF-8
697
3.53125
4
[]
no_license
#include <iostream> #include <string> using namespace std; class Car { public: string brand; string model; int year; Car(); Car(string b, string m, int y); ~Car(); }; Car::Car() { cout << "car class init"<< endl; } Car::Car(string b, string m, int y) { brand = b; model = m; year = y; cout << "car class init"<<endl; cout<< brand << " " << model << " " << year <<endl; } Car:: ~Car() { cout<< "Destrcut Car class" << endl; } int main(int argc, char const *argv[]) { Car Bmw("BMW","X4",2016); Car* ford; ford= new Car [1]; Car ford ("ford","mustung", 1976); delete ford; return 0; }
true
a9866b13c3ba90dac412608018cf3860b63ce483
C++
maxim1um/SortingMethod
/SortingAlgorithm/Source/Common.cpp
UTF-8
94
2.53125
3
[ "MIT" ]
permissive
#include "Common.h" void Swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; }
true
8a2e3b252f975eb3d7717d78b057083355032423
C++
MdAhsan101/Practice-Programs
/Graph_TUF_Djikstra_SingleSourceShortestPath.cpp
UTF-8
1,657
3.671875
4
[]
no_license
#include<bits/stdc++.h> using namespace std; void Djikstra(vector<pair<int,int>> G[], int n, int src) { vector<int> dist(n+1,INT_MAX); // Data Structure for Min Heap of pair<dist,node> priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> min_heap; dist[src]=0; min_heap.push({0,src}); while(!min_heap.empty()) { pair<int,int> cur_node= min_heap.top(); min_heap.pop(); int u= cur_node.second; for(auto v: G[u]) { if(dist[v.first]>(dist[u]+v.second)) { dist[v.first]=dist[u]+v.second; min_heap.push({dist[v.first],v.first}); } } } cout<<endl; cout<<"Distance from source "<<src<<" are : "; for(int i=1; i<=n; i++) { cout<<dist[i]<<" "; } } int main() { cout<<"Enter no. of nodes and edges resp. for directed graph:"; int n,m; cin>>n>>m; vector<pair<int,int>> G[n+1]; int dist[n+1]; for(int i=0; i<=n; i++) dist[i]=INT_MAX; cout<<"Now input all the "<< m <<" edges of directed graph (start node, end node, weight):\n"; int u,v,wt; for(int i=1; i<=m; i++) { cin>>u>>v>>wt; G[u].push_back({v,wt}); G[v].push_back({u,wt}); } int src; cout<<"Enter the source node: "; cin>>src; Djikstra(G,n,src); } /* Output: Enter no. of nodes and edges resp. for directed graph:5 6 Now input all the 6 edges of directed graph (start node, end node, weight): 1 2 2 1 4 1 2 5 5 2 3 4 4 3 3 3 5 1 Enter the source node: 1 Distance from source 1 are : 0 2 4 1 5 */
true
1bafd1933572c0e79f60172c384ff20e7900295c
C++
jjimenezg93/ai-state_machines
/game/SM/transition.cpp
UTF-8
482
2.609375
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "transition.h" #include "condition.h" #include "action.h" #include "state.h" Transition::Transition(Condition * condition, State * targetState, Action * action): m_condition(condition), m_targetState(targetState), m_triggerAction(action) {} Transition::~Transition() {} bool Transition::CanTrigger() const { return m_condition->Check(); } State * Transition::Trigger() { m_triggerAction->Run(); m_targetState->OnEnter(); return m_targetState; }
true
b29ea21bdd9b35ef3989f4f3e4062d61a7bb595a
C++
lzz5235/leetcode
/src/InsertionSortList.cpp
UTF-8
1,783
3.546875
4
[ "MIT" ]
permissive
//Sort a linked list using insertion sort. #include <iostream> #include <algorithm> #include <stack> #include <string> #include <vector> #include <stdint.h> #include <assert.h> #include <queue> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *insertionSortList(ListNode *head) { ListNode dummy(INT32_MIN); //dummy.next = head; ListNode *current = head; while(current!=NULL){ auto pos = findpos(&dummy,current->val); ListNode *temp = current->next; current->next = pos->next; pos->next = current; current = temp; } return dummy.next; } private: ListNode *findpos(ListNode *head,int value){ ListNode *pre=NULL; ListNode *current = head; for(;current!=NULL&&current->val <=value; pre = current,current = current->next); return pre; } }; int main() { ListNode *a1 = new ListNode(1); ListNode *a2 = new ListNode(8); ListNode *c1 = new ListNode(5); ListNode *c2 = new ListNode(9); ListNode *c3 = new ListNode(11); ListNode *b1 = new ListNode(2); ListNode *b2 = new ListNode(6); ListNode *b3 = new ListNode(9); ListNode *d1 = new ListNode(0); ListNode *d2 = new ListNode(1); ListNode *d3 = new ListNode(3); a1->next = a2; a2->next = c1; c1->next = c2; c2->next = c3; c3->next = NULL; b1->next = b2; b2->next = b3; b3->next = NULL; d1->next = d2; d2->next = d3; d3->next = NULL; vector<ListNode *> lists; lists.push_back(a1); lists.push_back(b1); lists.push_back(d1); Solution solute; ListNode * head = solute.insertionSortList(a1); while(head!=NULL){ printf("%d\t",head->val); head = head->next; } return 0; }
true
a833f956d7cef8758458c9f5f36ab38f340fc048
C++
0sorose/thermal
/thermal/src/thermal.ino
UTF-8
6,701
2.96875
3
[]
no_license
#include "Arduino.h" #include "EEPROM.h" #include "SPI.h" // pin def #define encodeA 2 #define encodeB 3 #define encodeP 4 #define holster_air 7 #define holster_irn 8 #define sel_air 9 #define sel_irn 0 #define fan_detect 1 #define temp_air A7 #define temp_irn A6 #define heat_air 6 #define heat_irn 5 #define ss 14 #define mosi 15 #define miso 16 #define sck 17 #define sda 27 #define scl 28 /* * Settings are stored in EEPROM: * 0 - Soldering temp * 1 - Soldering idle temp * 2 - Soldering idle timeout * 3 - Air temp * 4 - Air idle temp * 5 - Air idle timeout * 6 - Degrees Celcius or Farenheit * * They should not be overwritten unless the value is different to what's there */ #define display_framerate_divider 4 /* limits processing spent updating screen 0 = 1ms per frame, 1 = 2ms per frame, 2 = 4ms, 3 = 8ms, 4 = 16ms, etc.*/ using namespace std; /* Global Variables */ const uint8_t duty_log_depth = 32; uint16_t lastsetting[6]; uint16_t last_display_calc = 0; uint16_t duty_log_times[duty_log_depth]; uint8_t duty_log_act[duty_log_depth]; uint16_t iron_temp_target = 0; uint8_t settings[7]; uint16_t prev_duty_time = 0; uint8_t duty_cyc = 0; bool irn_active = false; /* Global Variable ends*/ /* TO DO: * Change duty_log time calculations to record change times rather than 1 sample per ms * Set up uart user interface * Set up visual interface once screen technology is known * Set up & test control loop functions */ void display_init(){ // set up display for use } void settings_init(){ // configure initial device settings // idea: imediately start heater for quick time to max temp? } void setup(){ // arduino setup function pinMode(encodeA, INPUT); pinMode(encodeB, INPUT); pinMode(encodeP, INPUT); pinMode(holster_air, INPUT); pinMode(holster_irn, INPUT); pinMode(sel_air, INPUT); pinMode(sel_irn, INPUT); pinMode(fan_detect, INPUT); pinMode(temp_air, INPUT); pinMode(temp_irn, INPUT); pinMode(heat_air, OUTPUT); pinMode(heat_irn, OUTPUT); analogReference(INTERNAL); analogRead(temp_irn); analogRead(temp_irn); analogRead(temp_irn); /* flushing inaccurate readings*/ digitalWrite(heat_irn, HIGH); Serial.begin(19200); display_init(); } uint16_t iron_temp_cel() // reads resistance from thermistor, returns temp in celcius { float reading = (float) analogRead(temp_irn); float work = ((reading * 0.6988) - 267.73); /* the two formula coefficients based on resistor selection go in here */ Serial.print("Iron temp reading: "); /* printing results */ Serial.print(reading); Serial.print(" count to Celcius = "); Serial.println(work); return (uint16_t) work; } uint16_t cel_to_far(uint16_t cel) // converts temp in Celcius to Farenheit { return (uint16_t) ((cel*9)/5 + 32); } uint8_t duty_log() // returns percentage duty over a number of readings given by 'duty_log_depth' { if(millis() == prev_duty_time) //only calculates once per ms { return duty_cyc; } /*to anylize what Percent of the time the iron is active*/ /*add active times, add inactive times, calculate fraction etc.*/ float act_time = 0; float inact_time = 0; float fraction = 0; uint8_t duty = 0; for (uint8_t i = 0; i < (duty_log_depth-1); i++) { /* need to run calculations for every entry up to last one inside for loop, from last entry to current time handled outside */ act_time += ((float) (duty_log_times[i + 1] - duty_log_times[i]) * (float) (duty_log_act[i]) / 256); act_time += ((float) (duty_log_times[i + 1] - duty_log_times[i]) * (float) (duty_log_act[i]) / 256); //act_time += (duty_log_times[i+1] - duty_log_times[i]); //inact_time += (duty_log_times[i+1] - duty_log_times[i]); } /* now we handle from the most recent entry from the current time */ act_time += ((float) (millis() - duty_log_times[duty_log_depth]) * (float) duty_log_act[duty_log_depth] / 256); /* >> 8 == div by 256 */ inact_time += ((float) (millis() - duty_log_times[duty_log_depth]) * (float) (256 - duty_log_act[duty_log_depth]) / 256); fraction = (float) act_time / (float) inact_time; duty = (uint8_t) (fraction * 100); Serial.println("Duty cycle calculation:\n"); Serial.print("Active time : "); Serial.println(act_time); Serial.print("Inactive time : "); Serial.println(inact_time); Serial.print("Gives duty of : "); Serial.println(fraction); /* Itterate all the duty measurements */ for (uint8_t c = 0; c < (duty_log_depth - 1); c++) { duty_log_times[c] = duty_log_times[c + 1]; duty_log_act[c] = duty_log_act[c + 1]; } duty_log_times[(duty_log_depth - 1)] = millis(); duty_log_act[(duty_log_depth - 1)] = irn_active; prev_duty_time = millis(); duty_cyc = duty; return duty_cyc; } int menu_mem(uint8_t menu){ switch (menu) { case 20: return 0; break; case 210: return 1; break; case 211: return 2; break; case 22: return 3; break; case 23: return 4; break; case 24: return 5; break; default: return 0; break; } } uint8_t eeprom(uint8_t menu){ uint8_t address = menu_mem(menu); return EEPROM.read(address); } void eeprom(uint8_t menu, uint8_t value){ uint8_t address = menu_mem(menu); EEPROM.update(address, value); if (eeprom(menu) != value) { /* eeprom address is faulty */ Serial.print("EEPROM write error address: "); Serial.println(address); } } void disp_currenttemp(uint16_t current){ /* draw large text of current iron temp and degrees C or F*/ } void disp_target_temp(uint16_t target){ /* draw small text below current temp with target in terms of same units as currenttemp*/ } void displayOut() /* Reads system state and displays relevent info on screen */{ /* Need a large active temp display, Smaller target temperature */ /* only calculate a new frame every 2^n ms, n = display_framerate_divider */ if ((last_display_calc >> display_framerate_divider) == (millis() >> display_framerate_divider)) { } } void iron_heater(uint16_t target){ if (iron_temp_cel() < iron_temp_target) { if ((iron_temp_target - iron_temp_cel()) > 16 ) { analogWrite(heat_irn, 255); } else { analogWrite(heat_irn, (((iron_temp_target - iron_temp_cel()) << 4) -1)); } } else { analogWrite(heat_irn, 0); } } void serialEvent(){ // takes valid chars from serial buff String inputString = ""; bool reading = true; while (Serial.available() && reading) { char inChar = (char)Serial.read(); if ((uint8_t)inChar < 0x20) { Serial.print("Message recieved: "); Serial.println(inputString); reading = false; } else{ inputString += inChar; } } //serial_interface(inputString); } // The loop function is called in an endless loop void loop(){ }
true
ae54f0ca43540a12c8c02b585fbbe8db0441a6c4
C++
mfarina1/pa1
/main.cpp
UTF-8
3,097
3.546875
4
[]
no_license
#include <iostream> #include <sstream> #include <regex> #include <iterator> #include <string> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <fstream> #include <vector> #include <cstdlib> using namespace std; struct Node { string value; Node *next; }; class LinkedList { public: Node *head; int listLength; Node *prevNode; Node *insert(int index, string text) { if (index < 0 || index > listLength) { // for invalid index // TODO: remove throw "index out of range"; } Node *newNode = new Node(); newNode->value = text; if (index == 0) { //insert at beginning of list if (head != NULL) { newNode->next = head; } head = newNode; listLength++; } // insert past index 0 if (index > 0) { //TODO: change to else? newNode = prevNode->next; newNode->next = prevNode->next->next; prevNode->next = newNode; head = newNode; } return head; } void remove(int index) { } Node *search(string text) { return nullptr; } LinkedList(vector<string> vecStrs) { if (vecStrs.size() == 0) { return; } //if empty list Node *localHead = new Node(); localHead->value = vecStrs[0]; Node *prevNode = localHead; for (int i = 1; i < vecStrs.size(); i++) { Node *currentNode = new Node(); prevNode->next = currentNode; currentNode->value = vecStrs[i]; prevNode = currentNode; } head = localHead; listLength = vecStrs.size(); //remember to update when you delete nodes } friend ostream &operator<<(ostream &os, const LinkedList &list) { auto currentNode = list.head; //os << "list length: " << list.listLength << endl; for (int i = 0; i < list.listLength; i++) { os << currentNode->value << endl; currentNode = currentNode->next; } return os; } }; class Editor { public: LinkedList *ll; void insertEnd(string text) { ll->insert(ll->listLength, text); } void insertAt(int index, string text) { ll->insert(index, text); } }; void tests() { vector<string> strs = {}; LinkedList *l = new LinkedList(strs); l->insert(0, string("Aa")); l->insert(0,string("Bb")); l->insert(0,string("Cc")); cout << (*l); l->insert(1,string("Dd")); cout << (*l); /*strs = {"max is great"}; l = new LinkedList(strs); l->insert(0, string("madeline is great")); cout << (*l);*/ // strs = {"max is great"}; // l = new LinkedList(strs); // l->insert(-1, string("madeline is great")); // cout << (*l); // strs = {"max is great"}; // l = new LinkedList(strs); // l->insert(10, string("madeline is great")); // cout << (*l); } int main() { tests(); return 0; }
true
9ea84fb2914245c2611c22a1bc74e57aa32b379d
C++
RobotLocomotion/drake
/multibody/tree/spatial_inertia.cc
UTF-8
24,048
2.953125
3
[ "BSD-3-Clause" ]
permissive
#include "drake/multibody/tree/spatial_inertia.h" #include <string> #include "drake/common/fmt_eigen.h" namespace drake { namespace multibody { namespace { template <typename T> const boolean<T> is_positive_finite(const T& value) { using std::isfinite; return isfinite(value) && value > 0; } template <typename T> const boolean<T> is_nonnegative_finite(const T& value) { using std::isfinite; return isfinite(value) && value >= 0; } template<typename T> void ThrowUnlessValueIsPositiveFinite(const T& value, std::string_view value_name, std::string_view function_name) { if (!is_positive_finite(value)) { DRAKE_DEMAND(!value_name.empty()); DRAKE_DEMAND(!function_name.empty()); const std::string error_message = fmt::format( "{}(): {} is not positive and finite: {}.", function_name, value_name, value); throw std::logic_error(error_message); } } // Throws unless ‖unit_vector‖ is within ≈ 5.5 bits of 1.0. // Note: 1E-14 ≈ 2^5.5 * std::numeric_limits<double>::epsilon(); // Note: This function is a no-op when type T is symbolic::Expression. template<typename T> void ThrowUnlessVectorIsMagnitudeOne(const Vector3<T>& unit_vector, std::string_view function_name) { if constexpr (scalar_predicate<T>::is_bool) { using std::abs; constexpr double kTolerance = 1E-14; if (abs(unit_vector.norm() - 1) > kTolerance) { DRAKE_DEMAND(!function_name.empty()); const std::string error_message = fmt::format("{}(): The unit_vector argument {} is not a unit vector.", function_name, fmt_eigen(unit_vector.transpose())); throw std::logic_error(error_message); } } } } // namespace template <typename T> SpatialInertia<T> SpatialInertia<T>::MakeFromCentralInertia(const T& mass, const Vector3<T>& p_PScm_E, const RotationalInertia<T>& I_SScm_E) { UnitInertia<T> G_SScm_E; G_SScm_E.SetFromRotationalInertia(I_SScm_E, mass); // The next line checks that M_SScm_E is physically valid. const SpatialInertia<T> M_SScm_E(mass, Vector3<T>::Zero(), G_SScm_E); return M_SScm_E.ShiftFromCenterOfMass(-p_PScm_E); // Shift to M_SP_E. } template <typename T> SpatialInertia<T> SpatialInertia<T>::MakeUnitary() { const T mass = 1; const Vector3<T> p_BoBcm_B = Vector3<T>::Zero(); // Position from Bo to Bcm. const UnitInertia<T> G_BBo_B(/* Ixx = */ 1, /* Iyy = */ 1, /* Izz = */ 1); return SpatialInertia<T>(mass, p_BoBcm_B, G_BBo_B); } template <typename T> SpatialInertia<T> SpatialInertia<T>::PointMass( const T& mass, const Vector3<T>& position) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); // Upgrade to monogram notation: position is the position vector from // point P to particle Q expressed in a frame B. const Vector3<T> p_PQ_B = position; // Form particle Q's unit inertia about point P, expressed in frame B. const UnitInertia<T> G_QP_B = UnitInertia<T>::PointMass(p_PQ_B); // Return particle Q's spatial inertia about point P, expressed in frame B. return SpatialInertia<T>(mass, p_PQ_B, G_QP_B); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidBoxWithDensity( const T& density, const T& lx, const T& ly, const T& lz) { ThrowUnlessValueIsPositiveFinite(density, "density", __func__); ThrowUnlessValueIsPositiveFinite(lx, "x-length", __func__); ThrowUnlessValueIsPositiveFinite(ly, "y-length", __func__); ThrowUnlessValueIsPositiveFinite(lz, "z-length", __func__); const T volume = lx * ly * lz; const T mass = density * volume; return SpatialInertia<T>::SolidBoxWithMass(mass, lx, ly, lz); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidBoxWithMass( const T& mass, const T& lx, const T& ly, const T& lz) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); ThrowUnlessValueIsPositiveFinite(lx, "x-length", __func__); ThrowUnlessValueIsPositiveFinite(ly, "y-length", __func__); ThrowUnlessValueIsPositiveFinite(lz, "z-length", __func__); const Vector3<T> p_BoBcm_B = Vector3<T>::Zero(); const UnitInertia<T> G_BBo_B = UnitInertia<T>::SolidBox(lx, ly, lz); return SpatialInertia<T>(mass, p_BoBcm_B, G_BBo_B); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidCubeWithDensity( const T& density, const T& length) { ThrowUnlessValueIsPositiveFinite(density, "density", __func__); ThrowUnlessValueIsPositiveFinite(length, "length", __func__); const T volume = length * length * length; const T mass = density * volume; return SolidCubeWithMass(mass, length); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidCubeWithMass( const T& mass, const T& length) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); ThrowUnlessValueIsPositiveFinite(length, "length", __func__); const Vector3<T> p_BoBcm_B = Vector3<T>::Zero(); const UnitInertia<T> G_BBo_B = UnitInertia<T>::SolidCube(length); return SpatialInertia<T>(mass, p_BoBcm_B, G_BBo_B); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidCapsuleWithDensity( const T& density, const T& radius, const T& length, const Vector3<T>& unit_vector) { ThrowUnlessValueIsPositiveFinite(density, "density", __func__); ThrowUnlessValueIsPositiveFinite(radius, "radius", __func__); ThrowUnlessValueIsPositiveFinite(length, "length", __func__); ThrowUnlessVectorIsMagnitudeOne(unit_vector, __func__); // Volume = π r² L + 4/3 π r³ const T pi_r_squared = M_PI * radius * radius; const T volume = pi_r_squared * length + (4.0 / 3.0) * pi_r_squared * radius; const T mass = density * volume; return SolidCapsuleWithMass(mass, radius, length, unit_vector); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidCapsuleWithMass( const T& mass, const T& radius, const T& length, const Vector3<T>& unit_vector) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); ThrowUnlessValueIsPositiveFinite(radius, "radius", __func__); ThrowUnlessValueIsPositiveFinite(length, "length", __func__); ThrowUnlessVectorIsMagnitudeOne(unit_vector, __func__); const Vector3<T> p_BoBcm_B = Vector3<T>::Zero(); const UnitInertia<T> G_BBo_B = UnitInertia<T>::SolidCapsule(radius, length, unit_vector); return SpatialInertia<T>(mass, p_BoBcm_B, G_BBo_B); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidCylinderWithDensity( const T& density, const T& radius, const T& length, const Vector3<T>& unit_vector) { ThrowUnlessValueIsPositiveFinite(density, "density", __func__); ThrowUnlessValueIsPositiveFinite(radius, "radius", __func__); ThrowUnlessValueIsPositiveFinite(length, "length", __func__); ThrowUnlessVectorIsMagnitudeOne(unit_vector, __func__); const T volume = M_PI * radius * radius * length; // π r² l const T mass = density * volume; return SolidCylinderWithMass(mass, radius, length, unit_vector); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidCylinderWithMass( const T& mass, const T& radius, const T& length, const Vector3<T>& unit_vector) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); ThrowUnlessValueIsPositiveFinite(radius, "radius", __func__); ThrowUnlessValueIsPositiveFinite(length, "length", __func__); ThrowUnlessVectorIsMagnitudeOne(unit_vector, __func__); const Vector3<T> p_BoBcm_B = Vector3<T>::Zero(); const UnitInertia<T> G_BBo_B = UnitInertia<T>::SolidCylinder(radius, length, unit_vector); return SpatialInertia<T>(mass, p_BoBcm_B, G_BBo_B); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidCylinderWithDensityAboutEnd( const T& density, const T& radius, const T& length, const Vector3<T>& unit_vector) { ThrowUnlessValueIsPositiveFinite(density, "density", __func__); ThrowUnlessValueIsPositiveFinite(radius, "radius", __func__); ThrowUnlessValueIsPositiveFinite(length, "length", __func__); ThrowUnlessVectorIsMagnitudeOne(unit_vector, __func__); const T volume = M_PI * radius * radius * length; // π r² l const T mass = density * volume; return SolidCylinderWithMassAboutEnd(mass, radius, length, unit_vector); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidCylinderWithMassAboutEnd( const T& mass, const T& radius, const T& length, const Vector3<T>& unit_vector) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); ThrowUnlessValueIsPositiveFinite(radius, "radius", __func__); ThrowUnlessValueIsPositiveFinite(length, "length", __func__); ThrowUnlessVectorIsMagnitudeOne(unit_vector, __func__); const Vector3<T> p_BpBcm_B = 0.5 * length * unit_vector; const UnitInertia<T> G_BBp_B = UnitInertia<T>::SolidCylinderAboutEnd(radius, length, unit_vector); return SpatialInertia(mass, p_BpBcm_B, G_BBp_B); // Returns M_BBp_B. } template <typename T> SpatialInertia<T> SpatialInertia<T>::ThinRodWithMass( const T& mass, const T& length, const Vector3<T>& unit_vector) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); ThrowUnlessValueIsPositiveFinite(length, "length", __func__); ThrowUnlessVectorIsMagnitudeOne(unit_vector, __func__); const UnitInertia<T> G_BBcm_B = UnitInertia<T>::ThinRod(length, unit_vector); const Vector3<T> p_BoBcm_B = Vector3<T>::Zero(); return SpatialInertia<T>(mass, p_BoBcm_B, G_BBcm_B); } template <typename T> SpatialInertia<T> SpatialInertia<T>::ThinRodWithMassAboutEnd( const T& mass, const T& length, const Vector3<T>& unit_vector) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); ThrowUnlessValueIsPositiveFinite(length, "length", __func__); ThrowUnlessVectorIsMagnitudeOne(unit_vector, __func__); SpatialInertia<T> M_BBcm_B = SpatialInertia<T>::ThinRodWithMass(mass, length, unit_vector); const Vector3<T> p_BcmBp_B = -0.5 * length * unit_vector; M_BBcm_B.ShiftFromCenterOfMassInPlace(p_BcmBp_B); return M_BBcm_B; // Due to shift, this actually returns M_BBp_B. } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidEllipsoidWithDensity( const T& density, const T& a, const T& b, const T& c) { ThrowUnlessValueIsPositiveFinite(density, "density", __func__); ThrowUnlessValueIsPositiveFinite(a, "semi-axis a", __func__); ThrowUnlessValueIsPositiveFinite(b, "semi-axis b", __func__); ThrowUnlessValueIsPositiveFinite(c, "semi-axis c", __func__); const T volume = (4.0 / 3.0) * M_PI * a * b * c; // 4/3 π a b c const T mass = density * volume; return SolidEllipsoidWithMass(mass, a, b, c); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidEllipsoidWithMass( const T& mass, const T& a, const T& b, const T& c) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); ThrowUnlessValueIsPositiveFinite(a, "semi-axis a", __func__); ThrowUnlessValueIsPositiveFinite(b, "semi-axis b", __func__); ThrowUnlessValueIsPositiveFinite(c, "semi-axis c", __func__); const Vector3<T> p_BoBcm_B = Vector3<T>::Zero(); const UnitInertia<T> G_BBo_B = UnitInertia<T>::SolidEllipsoid(a, b, c); return SpatialInertia<T>(mass, p_BoBcm_B, G_BBo_B); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidSphereWithDensity( const T& density, const T& radius) { ThrowUnlessValueIsPositiveFinite(density, "density", __func__); ThrowUnlessValueIsPositiveFinite(radius, "radius", __func__); const T volume = (4.0 / 3.0) * M_PI * radius * radius * radius; // 4/3 π r³ const T mass = density * volume; return SolidSphereWithMass(mass, radius); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidSphereWithMass( const T& mass, const T& radius) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); ThrowUnlessValueIsPositiveFinite(radius, "radius", __func__); const Vector3<T> p_BoBcm_B = Vector3<T>::Zero(); const UnitInertia<T> G_BBo_B = UnitInertia<T>::SolidSphere(radius); return SpatialInertia<T>(mass, p_BoBcm_B, G_BBo_B); } template <typename T> SpatialInertia<T> SpatialInertia<T>::HollowSphereWithDensity( const T& area_density, const T& radius) { ThrowUnlessValueIsPositiveFinite(area_density, "area_density", __func__); ThrowUnlessValueIsPositiveFinite(radius, "radius", __func__); const T area = 4.0 * M_PI * radius * radius; // 4 π r² const T mass = area_density * area; return HollowSphereWithMass(mass, radius); } template <typename T> SpatialInertia<T> SpatialInertia<T>::HollowSphereWithMass( const T& mass, const T& radius) { ThrowUnlessValueIsPositiveFinite(mass, "mass", __func__); ThrowUnlessValueIsPositiveFinite(radius, "radius", __func__); const Vector3<T> p_BoBcm_B = Vector3<T>::Zero(); const UnitInertia<T> G_BBo_B = UnitInertia<T>::HollowSphere(radius); return SpatialInertia<T>(mass, p_BoBcm_B, G_BBo_B); } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidTetrahedronAboutPointWithDensity( const T& density, const Vector3<T>& p0, const Vector3<T>& p1, const Vector3<T>& p2, const Vector3<T>& p3) { ThrowUnlessValueIsPositiveFinite(density, "density", __func__); // This method calculates a tetrahedron B's spatial inertia M_BA about a // point A by forming 3 new position vectors, namely the position vectors // from B's vertex B0 to vertices B1, B2, B3 (B's other three vertices). const Vector3<T> p_B0B1 = p1 - p0; // Position from vertex B0 to vertex B1. const Vector3<T> p_B0B2 = p2 - p0; // Position from vertex B0 to vertex B2. const Vector3<T> p_B0B3 = p3 - p0; // Position from vertex B0 to vertex B3. // Form B's spatial inertia about vertex B0 and then shifts to point A. SpatialInertia<T> M_BB0 = SpatialInertia<T>::SolidTetrahedronAboutVertexWithDensity( density, p_B0B1, p_B0B2, p_B0B3); const Vector3<T>& p_AB0 = p0; // Alias for position from point A to B0. M_BB0.ShiftInPlace(-p_AB0); return M_BB0; // Since M_BB0 was shifted, this actually returns M_BA. } template <typename T> SpatialInertia<T> SpatialInertia<T>::SolidTetrahedronAboutVertexWithDensity( const T& density, const Vector3<T>& p1, const Vector3<T>& p2, const Vector3<T>& p3) { ThrowUnlessValueIsPositiveFinite(density, "density", __func__); using std::abs; const T volume = (1.0 / 6.0) * abs(p1.cross(p2).dot(p3)); const T mass = density * volume; // Get position from tetrahedron B's vertex at Bo to Bcm (B's center of mass). const Vector3<T> p_BoBcm = 0.25 * (p1 + p2 + p3); const UnitInertia<T> G_BBo = UnitInertia<T>::SolidTetrahedronAboutVertex(p1, p2, p3); return SpatialInertia<T>(mass, p_BoBcm, G_BBo); } template <typename T> boolean<T> SpatialInertia<T>::IsPhysicallyValid() const { // This spatial inertia is not physically valid if the mass is negative or // non-finite or the center of mass or unit inertia matrix have NaN elements. boolean<T> ret_value = is_nonnegative_finite(mass_); if (ret_value) { // Form a rotational inertia about the body's center of mass and then use // the well-documented tests in RotationalInertia to test validity. const UnitInertia<T> G_SScm_E = G_SP_E_.ShiftToCenterOfMass(p_PScm_E_); const RotationalInertia<T> I_SScm_E = G_SScm_E.MultiplyByScalarSkipValidityCheck(mass_); ret_value = I_SScm_E.CouldBePhysicallyValid(); } return ret_value; } template <typename T> void SpatialInertia<T>::ThrowNotPhysicallyValid() const { std::string error_message = fmt::format( "Spatial inertia fails SpatialInertia::IsPhysicallyValid()."); const T& mass = get_mass(); if (!is_positive_finite(mass)) { error_message += fmt::format( "\nmass = {} is not positive and finite.\n", mass); } else { error_message += fmt::format("{}", *this); WriteExtraCentralInertiaProperties(&error_message); } throw std::runtime_error(error_message); } template <typename T> SpatialInertia<T>& SpatialInertia<T>::operator+=( const SpatialInertia<T>& M_BP_E) { const T total_mass = get_mass() + M_BP_E.get_mass(); if (total_mass != 0) { p_PScm_E_ = (CalcComMoment() + M_BP_E.CalcComMoment()) / total_mass; G_SP_E_.SetFromRotationalInertia( CalcRotationalInertia() + M_BP_E.CalcRotationalInertia(), total_mass); } else { // Compose the spatial inertias of two massless bodies in the limit when // the two bodies have the same mass. In this limit, p_PScm_E_ and G_SP_E_ // are the arithmetic mean of the constituent COMs and unit inertias. p_PScm_E_ = 0.5 * (get_com() + M_BP_E.get_com()); G_SP_E_.SetFromRotationalInertia( get_unit_inertia() + M_BP_E.get_unit_inertia(), 2.0); } mass_ = total_mass; return *this; } template <typename T> SpatialInertia<T>& SpatialInertia<T>::ShiftFromCenterOfMassInPlace( const Vector3<T>& p_ScmP_E) { DRAKE_ASSERT(p_PScm_E_ == Vector3<T>::Zero()); G_SP_E_.ShiftFromCenterOfMassInPlace(p_ScmP_E); p_PScm_E_ = -p_ScmP_E; return *this; // On entry, `this` is M_SScm_E. On return, `this` is M_SP_E. } template <typename T> SpatialInertia<T> SpatialInertia<T>::ShiftFromCenterOfMass( const Vector3<T>& p_ScmP_E) const { return SpatialInertia(*this).ShiftFromCenterOfMassInPlace(p_ScmP_E); } template <typename T> SpatialInertia<T>& SpatialInertia<T>::ShiftInPlace(const Vector3<T>& p_PQ_E) { const Vector3<T> p_QScm_E = p_PScm_E_ - p_PQ_E; // The following two lines apply the parallel axis theorem (in place) so that: // G_SQ = G_SP + px_QScm² - px_PScm² G_SP_E_.ShiftFromCenterOfMassInPlace(p_QScm_E); G_SP_E_.ShiftToCenterOfMassInPlace(p_PScm_E_); p_PScm_E_ = p_QScm_E; // Note: It would be a implementation bug if a shift starts with a valid // spatial inertia and the shift produces an invalid spatial inertia. // Hence, no need to use DRAKE_ASSERT_VOID(CheckInvariants()). return *this; } template <typename T> SpatialForce<T> SpatialInertia<T>::operator*( const SpatialAcceleration<T>& A_WB_E) const { const Vector3<T>& alpha_WB_E = A_WB_E.rotational(); const Vector3<T>& a_WBo_E = A_WB_E.translational(); const Vector3<T>& mp_BoBcm_E = CalcComMoment(); // = m * p_BoBcm // Return (see class's documentation): // ⌈ tau_Bo_E ⌉ ⌈ I_Bo_E | m * p_BoBcm× ⌉ ⌈ alpha_WB_E ⌉ // | | = | | | * | | // ⌊ f_Bo_E ⌋ ⌊ -m * p_BoBcm× | m * Id ⌋ ⌊ a_WBo_E ⌋ return SpatialForce<T>( /* rotational */ CalcRotationalInertia() * alpha_WB_E + mp_BoBcm_E.cross(a_WBo_E), /* translational: notice the order of the cross product is the reversed * of the documentation above and thus no minus sign is needed. */ alpha_WB_E.cross(mp_BoBcm_E) + get_mass() * a_WBo_E); } template <typename T> SpatialMomentum<T> SpatialInertia<T>::operator*( const SpatialVelocity<T>& V_WBp_E) const { const Vector3<T>& w_WB_E = V_WBp_E.rotational(); const Vector3<T>& v_WP_E = V_WBp_E.translational(); const Vector3<T>& mp_BoBcm_E = CalcComMoment(); // = m * p_BoBcm // Return (see class's documentation): // ⌈ h_WB ⌉ ⌈ I_Bp | m * p_BoBcm× ⌉ ⌈ w_WB ⌉ // | | = | | | * | | // ⌊ l_WBp ⌋ ⌊ -m * p_BoBcm× | m * Id ⌋ ⌊ v_WP ⌋ return SpatialMomentum<T>( // Rotational CalcRotationalInertia() * w_WB_E + mp_BoBcm_E.cross(v_WP_E), // Translational: notice the order of the cross product is the reversed // of the documentation above and thus no minus sign is needed. w_WB_E.cross(mp_BoBcm_E) + get_mass() * v_WP_E); } template <typename T> std::pair<Vector3<double>, drake::math::RigidTransform<double>> SpatialInertia<T>::CalcPrincipalHalfLengthsAndPoseForEquivalentShape( double inertia_shape_factor) const { // Get position vector from P (`this` spatial inertia's about point) to // Scm (`this` spatial inertia's center of mass), expressed in frame E. const Vector3<T>& p_PScm_E = get_com(); // Shift `this` spatial inertia's unit inertia from P to Scm. const UnitInertia<T>& G_SP_E = get_unit_inertia(); const UnitInertia<T> G_SScm_E = G_SP_E.ShiftToCenterOfMass(p_PScm_E); // Form the principal semi-diameters (half-lengths) and rotation matrix R_EA // that contains the associated principal axes directions Ax, Ay, Az. const auto [abc, R_EA] = G_SScm_E.CalcPrincipalHalfLengthsAndAxesForEquivalentShape( inertia_shape_factor); // Since R_EA is of type double and X_EA must also be of type double, // create a position vector from P to Scm that is of type double. const double xcm = ExtractDoubleOrThrow(p_PScm_E(0)); const double ycm = ExtractDoubleOrThrow(p_PScm_E(1)); const double zcm = ExtractDoubleOrThrow(p_PScm_E(2)); const Vector3<double> p_PAo_E(xcm, ycm, zcm); // Note: Point Ao is at Scm. const drake::math::RigidTransform<double> X_EA(R_EA, p_PAo_E); return std::pair(abc, X_EA); } template <typename T> void SpatialInertia<T>::WriteExtraCentralInertiaProperties( std::string* message) const { DRAKE_DEMAND(message != nullptr); const T& mass = get_mass(); const Vector3<T>& p_PBcm = get_com(); // Get G_BP (unit inertia about point P) and use it to calculate G_BBcm (unit // inertia about Bcm). Use G_BBcm to calculate I_BBcm (rotational inertia // about Bcm) without validity checks such as IsPhysicallyValid(). // Hence, this method works for error messages. const UnitInertia<T>& G_BP = get_unit_inertia(); const UnitInertia<T> G_BBcm = G_BP.ShiftToCenterOfMass(p_PBcm); const RotationalInertia<T> I_BBcm = G_BBcm.MultiplyByScalarSkipValidityCheck(mass); // If point P is not at Bcm, write B's rotational inertia about Bcm. const boolean<T> is_position_zero = (p_PBcm == Vector3<T>::Zero()); if (!is_position_zero) { *message += fmt::format( " Inertia about center of mass, I_BBcm =\n{}", I_BBcm); } // Write B's principal moments of inertia about Bcm. if constexpr (scalar_predicate<T>::is_bool) { const Vector3<double> eig = I_BBcm.CalcPrincipalMomentsOfInertia(); const double Imin = eig(0), Imed = eig(1), Imax = eig(2); *message += fmt::format( " Principal moments of inertia about Bcm (center of mass) =" "\n[{} {} {}]\n", Imin, Imed, Imax); } } template <typename T> std::ostream& operator<<(std::ostream& out, const SpatialInertia<T>& M) { // Write the data associated with the spatial inertia M of a body // (or composite body) B about a point P, expressed in a frame E. // Typically point P is either Bo (B's origin) or Bcm (B's center of mass) // and frame E is usually the body frame B. More spatial inertia information // can be written via SpatialInertia::WriteExtraCentralInertiaProperties(). const T& mass = M.get_mass(); const Vector3<T>& p_PBcm = M.get_com(); const T& x = p_PBcm.x(); const T& y = p_PBcm.y(); const T& z = p_PBcm.z(); // TODO(jwnimmer-tri) Rewrite this to use fmt to our advantage. if constexpr (scalar_predicate<T>::is_bool) { out << "\n" << fmt::format(" mass = {}\n", mass) << fmt::format(" Center of mass = [{} {} {}]\n", x, y, z); } else { // Print symbolic results. out << " mass = " << mass << "\n" << fmt::format(" Center of mass = {}\n", fmt_eigen(p_PBcm.transpose())); } // Get G_BP (unit inertia about point P) and use it to calculate I_BP // (rotational inertia about P) without validity checks such as // IsPhysicallyValid(). Hence, this method works for error messages. const UnitInertia<T>& G_BP = M.get_unit_inertia(); const RotationalInertia<T> I_BP = G_BP.MultiplyByScalarSkipValidityCheck(mass); // Write B's rotational inertia about point P. out << " Inertia about point P, I_BP =\n" << I_BP; return out; } DRAKE_DEFINE_FUNCTION_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(( static_cast<std::ostream&(*)(std::ostream&, const SpatialInertia<T>&)>( &operator<< ) )) } // namespace multibody } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class drake::multibody::SpatialInertia)
true
16ef4106469b7c8701adc2dc6f88327fc9d20e85
C++
cwscx/ms_auto_suggest_check
/predict.cpp
UTF-8
2,105
3.15625
3
[]
no_license
#include "util.hpp" #include "DictionaryTrie.hpp" #include <fstream> #include <string> #include <vector> #include <time.h> void autoSuggest(int size, int stepSize, int iterations, std::string fileName, std::string input, int num_completions) { //load all words in fileName into vector //then randomly add words from vector to 3 dicts std::vector<std::string> v; std::ifstream in; in.open(fileName, std::ios::binary); Utils::load_dict(v, in); std::vector<std::string> uselessWords; uselessWords.push_back(input); //create 3 dicts DictionaryTrie d_trie; std::vector<std::pair<int,long long int>> trie; Timer T; long long time_duration; srand (time(NULL)); unsigned int randomNum; for(int i=0; i < iterations; i++) { for (int j=0; j<stepSize; j++) { randomNum = rand() % v.size(); d_trie.insert(v[randomNum],0); } //now benchmark the tree find times T.begin_timer(); for(auto it=uselessWords.begin(); it!= uselessWords.end();it++) { d_trie.find(*it); } time_duration = T.end_timer(); trie.push_back(std::make_pair((i+1)*stepSize,time_duration)); } std::vector<std::string> predictions = d_trie.predictCompletions(input, num_completions); for(int i = 0; i < predictions.size(); i++) { std::cout << predictions[i] << std::endl; } } int main(int argc, char *argv[]) { if(argc < 5){ std::cout << "Incorrect number of arguments. (required 4)" << std::endl; std::cout << "\t 1:The minimum size of the dictionary you want to test" << std::endl; std::cout << "\t 2:The step size (how much to increase the dictionary size each iteration)" << std::endl; std::cout << "\t 3:The number of iterations (e.g. how many times do you want to increase your dictionary size" << std::endl; std::cout << "\t 4:The name of a dictionary file to use" << std::endl; std::cout << "\t 5:The word for auto suggestion" << std::endl; std::cout << "\t 6:The number of completions" << std::endl; std::cout << std::endl; exit(-1); } autoSuggest(atoi(argv[1]),atoi(argv[2]),atoi(argv[3]),argv[4], argv[5], atoi(argv[6])); }
true
c27d8a07e99bdc78b4fab36bc867d46dd5f7ad52
C++
Adriianooo/pilha_dinamica
/linkedlist.h
UTF-8
677
2.75
3
[]
no_license
//Adriano Pinheiro Fernandes TIA: 32055161 #ifndef __LINKED_LIST_H__ #define __LINKED_LIST_H__ #include <string> using namespace std; struct Node { float numero; Node* next; }; struct linkedlist { int count; Node* top; Node* tail; }; linkedlist* Create(); void Append(linkedlist* list, float numero); void InsertFront(linkedlist* list, float numero); bool IsEmpty(const linkedlist* list); int Count(const linkedlist* list); void Clear(linkedlist* list); Node* RemoveNode(linkedlist* list, float numero); Node* RemoveTail(linkedlist* list); Node* RemoveHead(linkedlist* list); Node* GetHead(const linkedlist* list); Node* GetNode(const linkedlist* list, float numero); #endif
true
ef446bcc9ae621309a810e17416474c026babe56
C++
guilhermeleobas/maratona
/URI/uri1225.cc
UTF-8
432
2.78125
3
[]
no_license
#include <iostream> #include <vector> #include <cmath> using namespace std; int main (){ while (true){ int n; cin >> n; if (not cin) break; vector<int> v (n); int s = 0; for (int i=0; i<n; i++){ cin >> v[i]; s += v[i]; } int diff = 0; int k = s/n; for (int i=0; i<n; i++) diff += abs(k-v[i]); if (s % n == 0) cout << (diff/2) + 1 << endl; else cout << "-1\n"; } return 0; }
true
1d2fe3ad594e6c777a673d5eb75d17e233ca8da7
C++
Iluxa147/EducationalTasks
/MemoryManagement.h
UTF-8
1,837
3.390625
3
[]
no_license
#pragma once /* represents memory different types of memory allocations */ //#define PlacementNew #ifdef PlacementNew void PlacementExample() { const int Buf = 512; const int N = 5; char buffer[Buf]; //int i; std::cout << "1st new and placement new" << std::endl; double *pd1, *pd2; pd1 = new double[N]; //new mem in heap for N doubles pd2 = new (buffer) double[N]; // placement new at buffer adress with [N] size for (size_t i = 0; i < N; ++i) { pd2[i] = pd1[i] = 1000 + 20.0*i; } std::cout << "Memory addresses: \n" << "heap: "<< pd1 << " static: " << (void*)buffer << std::endl; std::cout << "Memory contents: \n"; for (size_t i = 0; i < N; ++i) { std::cout << pd1[i] << " at " << &pd1[i] << "; "; std::cout << pd2[i] << " at " << &pd2[i] << "; \n"; } std::cout << "2nd new and placement new" << std::endl; double *pd3, *pd4; pd3 = new double[N]; //new mem in heap for N doubles pd4 = new (buffer) double[N]; // placement new at buffer adress with [N] size for (size_t i = 0; i < N; ++i) { pd4[i] = pd3[i] = 1000 + 40.0*i; } std::cout << "Memory contents: \n"; for (size_t i = 0; i < N; ++i) { std::cout << pd3[i] << " at " << &pd3[i] << "; "; std::cout << pd4[i] << " at " << &pd4[i] << "; \n"; } std::cout << "3rd new and placement new" << std::endl; delete[] pd1; pd1 = new double[N]; //new mem in heap for N doubles pd2 = new (buffer+N*sizeof(double)) double[N]; // placement new at buffer adress with [N] size for (size_t i = 0; i < N; ++i) { pd2[i] = pd1[i] = 1000 + 60.0*i; } std::cout << "Memory contents: \n"; for (size_t i = 0; i < N; ++i) { std::cout << pd1[i] << " at " << &pd1[i] << "; "; std::cout << pd2[i] << " at " << &pd2[i] << "; \n"; } delete[] pd1; //delete[] pd2; //an error cause pd2 is in stack as a buffer var delete[] pd3; } #endif PlacementNew
true
633717cf797a0a4217c593b767e54d35c6578dac
C++
helloworld1983/CxxUtilities
/includes/CxxUtilities/Date.hh
UTF-8
1,388
2.75
3
[]
no_license
/* * Date.hh * * Created on: Dec 15, 2014 * Author: yuasa */ #ifndef DATE_HH_ #define DATE_HH_ #include "CxxUtilities/CommonHeader.hh" namespace CxxUtilities { class Date { public: uint16_t year; uint8_t month; uint8_t day; uint8_t hour; uint8_t min; uint8_t sec; public: static CxxUtilities::Date parseYYYYMMDD_HHMMSS(std::string yyyymmdd_hhmmss) { CxxUtilities::Date result; if (yyyymmdd_hhmmss.size() == 15) { result.year = atoi(yyyymmdd_hhmmss.substr(0, 4).c_str()); result.month = atoi(yyyymmdd_hhmmss.substr(4, 2).c_str()); result.day = atoi(yyyymmdd_hhmmss.substr(6, 2).c_str()); result.hour = atoi(yyyymmdd_hhmmss.substr(9, 2).c_str()); result.min = atoi(yyyymmdd_hhmmss.substr(11, 2).c_str()); result.sec = atoi(yyyymmdd_hhmmss.substr(13, 2).c_str()); return result; } else { using namespace std; cerr << "CxxUtilities::Date::parseYYYYMMDD_HHMMSS(yyyymmdd_hhmmss): invailid yyyymmdd_hhmmss " << yyyymmdd_hhmmss << endl; return result; } } public: std::string toString() { using namespace std; std::stringstream ss; ss << setfill('0') << setw(4) << (uint32_t)this->year << setw(2) << (uint32_t)this->month << setw(2) << (uint32_t)this->day << "_" << setw(2) << (uint32_t)this->hour << setw(2) << (uint32_t)this->min << setw(2) << (uint32_t)this->sec; return ss.str(); } }; } #endif /* DATE_HH_ */
true
e3e0a4ffa4501fbf85a9522c765ad8a3ba8bfa49
C++
Naooki/stroustrup_ppp_exercises
/Chapter-16/Function_window.h
UTF-8
3,186
2.734375
3
[]
no_license
#include "GUI.h" using namespace Graph_lib; struct Function_window : Window { Function_window(Point xy, int w, int h, const string& title); private: Axis ox; Axis oy; Button draw_button; Button funcs_button; Menu funcs_menu; In_box min_inbox; In_box max_inbox; In_box pts_num_inbox; In_box xscale_inbox; In_box yscale_inbox; // store function pointer Fct* fct_pointer; Func flex_function; void show_func_menu() { funcs_button.hide(); funcs_menu.show(); } void func_pressed(Fct f) { funcs_menu.hide(); funcs_button.show(); fct_pointer = f; } void draw_pressed(); }; Function_window::Function_window(Point xy, int w, int h, const string& title) : Window(xy, w, h, title), draw_button(Point(450, 0), 100, 60, "Draw function", [](Address, Address pw) { reference_to<Function_window>(pw).draw_pressed(); }), funcs_button(Point(250, 0), 100, 30, "Functions", [](Address, Address pw) { reference_to<Function_window>(pw).show_func_menu(); }), funcs_menu(Point(250, 0), 100, 30, Menu::vertical, "Functions"), ox(Axis::x, Point(50, y_max() / 2), x_max() - 100, 20, "Axis X"), oy(Axis::y, Point(x_max() / 2, y_max() - 50), y_max() - 100, 20, "Axis Y"), min_inbox(Point(100, 0), 100, 20, "Min x: "), max_inbox(Point(100, 25), 100, 20, "Max x: "), pts_num_inbox(Point(100, 50), 100, 20, "Number of pts: "), xscale_inbox(Point(100, 75), 100, 20, "X scale: "), yscale_inbox(Point(100,100), 100, 20, "Y scale: "), flex_function(sqrt, -10, 10, Point(x_max() / 2, y_max() /2)) { attach(ox); attach(oy); attach(draw_button); attach(funcs_button); attach(funcs_menu); attach(min_inbox); attach(max_inbox); attach(pts_num_inbox); attach(xscale_inbox); attach(yscale_inbox); funcs_menu.attach(new Button(Point(0, 0), 0, 0, "sin", [](Address, Address pw) { reference_to<Function_window>(pw).func_pressed(sin); })); funcs_menu.attach(new Button(Point(0, 0), 0, 0, "cos", [](Address, Address pw) { reference_to<Function_window>(pw).func_pressed(cos); })); funcs_menu.attach(new Button(Point(0, 0), 0, 0, "log", [](Address, Address pw) { reference_to<Function_window>(pw).func_pressed(log); })); funcs_menu.attach(new Button(Point(0, 0), 0, 0, "exp", [](Address, Address pw) { reference_to<Function_window>(pw).func_pressed(exp); })); attach(funcs_menu); funcs_menu.hide(); fct_pointer = sqrt; flex_function.set_color(Color::invisible); attach(flex_function); } void Function_window::draw_pressed() { if (min_inbox.get_string() == "" && max_inbox.get_string() == "") return; int new_r1 = min_inbox.get_int(); int new_r2 = max_inbox.get_int(); if (new_r1 < 0) new_r1 = 0; flex_function.set_range(new_r1, new_r2); if (pts_num_inbox.get_string() != "") //default = 100 flex_function.set_points_num(pts_num_inbox.get_int()); if (xscale_inbox.get_string() != "" && yscale_inbox.get_string() != "") { //default = 25 int new_xscale = xscale_inbox.get_int(); int new_yscale = yscale_inbox.get_int(); flex_function.set_scales(new_xscale, new_yscale); } flex_function.set_function(fct_pointer); flex_function.set_color(Color::red); redraw(); }
true
a629fd537c40512616fc8968a04424b2809e05e2
C++
feinstofflicher/myVulkan
/src/vulkan/vertexbuffer.cpp
UTF-8
5,956
2.890625
3
[]
no_license
#include "vertexbuffer.h" #include "vulkanhelper.h" #include "device.h" const static bool useStaging = true; namespace { VkFormat getAttributeFormat(uint32_t numVertices) { switch (numVertices) { case 1: return VK_FORMAT_R32_SFLOAT; case 2: return VK_FORMAT_R32G32_SFLOAT; case 3: return VK_FORMAT_R32G32B32_SFLOAT; default: assert(!"Unknown number of vertices"); return VK_FORMAT_UNDEFINED; } } } void VertexBuffer::init(Device* device, const std::vector<AttributeDescription>& descriptions) { if (descriptions.size() == 0) return; m_device = device; m_numVertices = descriptions[0].vertexCount; auto totalSize = 0; m_attributesDescriptions.resize(descriptions.size()); m_bindingDescriptions.resize(descriptions.size()); for (auto i = 0; i < descriptions.size(); i++) { const auto& desc = descriptions[i]; assert(m_numVertices == desc.vertexCount); VkVertexInputAttributeDescription& attribDesc = m_attributesDescriptions[i]; attribDesc.binding = i; attribDesc.location = desc.location; attribDesc.format = getAttributeFormat(desc.componentCount); attribDesc.offset = totalSize; const auto attributeSize = desc.componentCount * 4; VkVertexInputBindingDescription& bindingDesc = m_bindingDescriptions[i]; bindingDesc.binding = i; bindingDesc.stride = attributeSize; bindingDesc.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; totalSize += desc.vertexCount * attributeSize; } auto memcpyFunc = [&](void *mappedMemory) { auto data = reinterpret_cast<float*>(mappedMemory); for (auto& desc : descriptions) { const auto attributeSize = desc.componentCount * desc.vertexCount; memcpy(data, desc.vertexData, attributeSize * 4); data += attributeSize; } }; createBuffer(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, totalSize, m_vertexBuffer, m_vertexBufferMemory, memcpyFunc); } void VertexBuffer::createBuffer(VkBufferUsageFlags usage, uint32_t size, VkBuffer& buffer, VkDeviceMemory& bufferMemory, const MemcpyFunc& memcpyFunc) { if (useStaging) { // TODO: use single persistent staging buffer? VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; m_device->createBuffer(size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); mapMemory(stagingBufferMemory, memcpyFunc); m_device->createBuffer(size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, buffer, bufferMemory); m_device->copyBuffer(stagingBuffer, buffer, size); vkDestroyBuffer(m_device->getVkDevice(), stagingBuffer, nullptr); vkFreeMemory(m_device->getVkDevice(), stagingBufferMemory, nullptr); } else { m_device->createBuffer(size, usage, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, buffer, bufferMemory); mapMemory(bufferMemory, memcpyFunc); } } void VertexBuffer::mapMemory(VkDeviceMemory bufferMemory, const MemcpyFunc& memcpyFunc) { void* mappedMemory; VK_CHECK_RESULT(vkMapMemory(m_device->getVkDevice(), bufferMemory, 0, VK_WHOLE_SIZE, 0, &mappedMemory)); memcpyFunc(mappedMemory); vkUnmapMemory(m_device->getVkDevice(), bufferMemory); } void VertexBuffer::setIndices(const uint16_t *indices, uint32_t numIndices) { createIndexBuffer(indices, numIndices, VK_INDEX_TYPE_UINT16); } void VertexBuffer::setIndices(const uint32_t *indices, uint32_t numIndices) { createIndexBuffer(indices, numIndices, VK_INDEX_TYPE_UINT32); } void VertexBuffer::createIndexBuffer(const void *indices, uint32_t numIndices, VkIndexType indexType) { m_numIndices = numIndices; m_indexType = indexType; const uint32_t size = numIndices * (indexType == VK_INDEX_TYPE_UINT16 ? sizeof(uint16_t) : sizeof(uint32_t)); auto memcpyFunc = [=](void *mappedMemory) { memcpy(mappedMemory, indices, size); }; createBuffer(VK_BUFFER_USAGE_INDEX_BUFFER_BIT, size, m_indexBuffer, m_indexBufferMemory, memcpyFunc); } void VertexBuffer::draw(VkCommandBuffer commandBuffer) const { const VkDeviceSize offset = 0; for (auto i = 0; i < m_bindingDescriptions.size(); i++) { vkCmdBindVertexBuffers(commandBuffer, i, 1, &m_vertexBuffer, &offset); } if (m_indexBuffer != VK_NULL_HANDLE) { vkCmdBindIndexBuffer(commandBuffer, m_indexBuffer, 0, m_indexType); vkCmdDrawIndexed(commandBuffer, m_numIndices, 1, 0, 0, 0); } else { vkCmdDraw(commandBuffer, m_numVertices, 1, 0, 0); } } const std::vector<VkVertexInputAttributeDescription>& VertexBuffer::getAttributeDescriptions() const { return m_attributesDescriptions; } const std::vector<VkVertexInputBindingDescription>& VertexBuffer::getBindingDescriptions() const { return m_bindingDescriptions; } void VertexBuffer::destroy() { vkDestroyBuffer(m_device->getVkDevice(), m_vertexBuffer, nullptr); m_vertexBuffer = VK_NULL_HANDLE; vkFreeMemory(m_device->getVkDevice(), m_vertexBufferMemory, nullptr); m_vertexBufferMemory = VK_NULL_HANDLE; if (m_indexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(m_device->getVkDevice(), m_indexBuffer, nullptr); m_indexBuffer = VK_NULL_HANDLE; vkFreeMemory(m_device->getVkDevice(), m_indexBufferMemory, nullptr); m_indexBufferMemory = VK_NULL_HANDLE; } }
true
ff4d4081053dd6aadf53dd347ed51f009d6fe995
C++
c-cash/c-cash
/src/parser/Statement.cpp
UTF-8
502
2.859375
3
[]
no_license
#include "Statement.hpp" #include <iostream> namespace parser { using namespace std; void Statement::DebugPrint(size_t indent){ cout << string(indent, '\t') << "\u001B[36m" << sStatementKindStrings[int(mKind)] << " "; cout << "\u001B[33m" << mType.mName << " " << "\u001B[32m" << mName << "\u001B[0m" << " (\n"; for(Statement statement : mStatements){ statement.DebugPrint(indent + 1); } cout << string(indent, '\t') << ")" << endl; } }
true
0a3553ae53d017f8c527df767c58486d5f47b3db
C++
javasuki/RJava
/NXDO.Mixed.V2015/NXDO.RJava.Core/larray.h
GB18030
6,500
2.640625
3
[ "MIT" ]
permissive
#include "jni.h" #include <stdlib.h> #include <string.h> #include "JParamValue.h" #pragma once using namespace NXDO::RJava; class larray { private: /// <summary> /// (java.lang.Class), Class[] /// </summary> /// <param name="jniClassName">jni, ʹ/ָ, : java/lang/Integer</param> static jobjectArray createObjectArray(int size, System::String^ jniClassName); /// <summary> /// תjavaԪֵ(ԪֵΪ)C#ֵ,ӵָļ. /// <para>ͼͱתC#ͬ.</para> /// </summary> /// <param name="gList">ͼ϶ӦǷ͵ļ</param> /// <param name="">C#(ǿ,int?,int),תC#ֵ</param> static void addRefObjectToList(jobject ary, System::Collections::IList^ gList, Type^ type); public: larray(void); ~larray(void); #pragma region תjava /// <summary> /// c# bool[]/bool?[] ת java bool[]/Boolean[] /// <para>жԪ,boolΪjava, bool?Ϊjava.lang.Boolean</para> /// </summary> static jobjectArray toJBoolArray(System::Array^ ary); /// <summary> /// c# byte[]/byte?[] ת java byte[]/Byte[] /// <para>жԪ,byteΪjava, bool?Ϊjava.lang.Byte</para> /// </summary> static jobjectArray toJByteArray(System::Array^ ary); /// <summary> /// c# char[]/char?[] ת java char[]/Character[] /// <para>жԪ,charΪjava, char?Ϊjava.lang.Character</para> /// </summary> static jobjectArray toJCharArray(System::Array^ ary); /// <summary> /// c# short[]/short?[] ת java short[]/Short[] /// <para>жԪ,shortΪjava, short?Ϊjava.lang.Short</para> /// </summary> static jobjectArray toJShortArray(System::Array^ ary); /// <summary> /// c# int[]/int?[] ת java int[]/Integer[] /// <para>жԪ,intΪjava, int?Ϊjava.lang.Integer</para> /// </summary> static jobjectArray toJIntArray(System::Array^ ary); /// <summary> /// c# long[]/long?[] ת java long[]/Long[] /// <para>жԪ,longΪjava, long?Ϊjava.lang.Long</para> /// </summary> static jobjectArray toJLongArray(System::Array^ ary); /// <summary> /// c# float[]/float?[] ת java float[]/Float[] /// <para>жԪ,floatΪjava, float?Ϊjava.lang.Float</para> /// </summary> static jobjectArray toJFloatArray(System::Array^ ary); /// <summary> /// c# double[]/double?[] ת java double[]/Double[] /// <para>жԪ,doubleΪjava, double?Ϊjava.lang.Double</para> /// </summary> static jobjectArray toJDoubleArray(System::Array^ ary); /// <summary> /// c# string[] ת java.lang.String[] /// <para>жԪ,doubleΪjava, double?Ϊjava.lang.String</para> /// </summary> static jobjectArray toJStringArray(System::Array^ ary); /// <summary> /// c# JObject[] ת java.lang.Object[]/java.lang.Object[] /// <para>( aryElemClass )</para> /// </summary> /// <param name="aryElemClass">javaԪ<param> static jobjectArray toJavaObjectArray(System::Array^ ary, jclass aryElemClass); /// <summary> /// c#ķ ת javaӦIJ /// <para>0= java java.lang.Class&lt;?&gt;[]</para> /// <para>1= javaֵ java.lang.Object[]</para> /// </summary> static array<jobjectArray>^ toJavaMethodArray(array<IParamValue^>^ ary); #pragma endregion #pragma region תCShape /// <summary> /// java bool[]/Boolean[] ת c# bool[]/bool?[] /// </summary> /// <param name="elemIsObject">trueΪjava.lang.Boolean (תbool?), falseΪjava (תbool)</param> static System::Array^ toNBoolArray(jobject ary, bool elemIsObject); /// <summary> /// java byte[]/Byte[] ת c# byte[]/byte?[] /// </summary> /// <param name="elemIsObject">trueΪjava.lang.Byte (תbyte?), falseΪjava (תbyte)</param> static System::Array^ toNByteArray(jobject ary, bool elemIsObject); /// <summary> /// java char[]/Character[] ת c# char[]/char?[] /// </summary> /// <param name="elemIsObject">trueΪjava.lang.Character (תchar?), falseΪjava (תchar)</param> static System::Array^ toNCharArray(jobject ary, bool elemIsObject); /// <summary> /// java short[]/Short[] ת c# short[]/short?[] /// </summary> /// <param name="elemIsObject">trueΪjava.lang.Short (תshort?), falseΪjava (תshort)</param> static System::Array^ toNShortArray(jobject ary, bool elemIsObject); /// <summary> /// java int[]/Integer[] ת c# int[]/int?[] /// </summary> /// <param name="elemIsObject">trueΪjava.lang.Integer (תint?), falseΪjava (תint)</param> static System::Array^ toNIntArray(jobject ary, bool elemIsObject); /// <summary> /// java long[]/Long[] ת c# long[]/long?[] /// </summary> /// <param name="elemIsObject">trueΪjava.lang.Long (תlong?), falseΪjava (תlong)</param> static System::Array^ toNLongArray(jobject ary, bool elemIsObject); /// <summary> /// java float[]/Float[] ת c# float[]/float?[] /// </summary> /// <param name="elemIsObject">trueΪjava.lang.Float (תfloat?), falseΪjava (תfloat)</param> static System::Array^ toNFloatArray(jobject ary, bool elemIsObject); /// <summary> /// java double[]/Double[] ת c# double[]/double?[] /// </summary> /// <param name="elemIsObject">trueΪjava.lang.Double (תdouble?), falseΪjava (תdouble)</param> static System::Array^ toNDoubleArray(jobject ary, bool elemIsObject); /// <summary> /// java.lang.String[] ת c# string[] /// </summary> static System::Array^ toNStringArray(jobject ary); /// <summary> /// java.lang.Object[] ת c# NXDO.JRuntime.JVM.JObject[] /// </summary> static System::Array^ toNSubofJObjectArray(jobject ary, Type^ JObjType); static System::Array^ toNBoxPtrArray(jobject ary); #pragma endregion static jobjectArray CreateObjectParamsArray(int size); static void AddObjectParamsArray(jobjectArray ary, jobject obj, int index); };
true
58d4c6bfa8bd17ffe8b898334d9cf9039e23cc69
C++
wigasper/spdrnn
/src/utils.h
UTF-8
15,472
3.125
3
[]
no_license
#include <algorithm> #include <filesystem> #include <fstream> #include <iostream> #include <math.h> #include <random> #include <regex> #include <stdlib.h> #include <string> #include <tuple> #include <vector> namespace fs = std::filesystem; typedef double element_type; typedef size_t dim; typedef std::tuple<std::vector<element_type>, dim> matrix; std::random_device RANDOM_DEVICE; std::mt19937 generator(RANDOM_DEVICE()); // prints the matrix, currently only used for debugging void print_matrix(const matrix &m) { std::vector<element_type> vals = std::get<0>(m); dim dimension = std::get<1>(m); size_t idx = 0; for (element_type val : vals) { std::cout << val << " "; idx++; if (idx % dimension == 0) { std::cout << "\n"; } } std::cout << "\n"; } // generates a random matrix appropriate for the tanh activation function matrix gen_random_matrix(size_t m, size_t n, size_t prior_layer_dim) { std::vector<element_type> vals_out; element_type min = -1 * (1 / sqrt(prior_layer_dim)); element_type max = 1 / sqrt(prior_layer_dim); std::uniform_real_distribution<element_type> distribution(min, max); for (size_t _idx = 0; _idx < (m * n); _idx++) { vals_out.push_back(distribution(generator)); } return std::make_tuple(vals_out, n); } // generates a matrix of 0s matrix gen_zeros_matrix(size_t m, size_t n) { std::vector<element_type> vals_out; for (size_t _idx = 0; _idx < (m * n); _idx++) { vals_out.push_back(0); } return std::make_tuple(vals_out, n); } // matrix multiplication matrix dot(const matrix &a, const matrix &b) { dim a_dim = std::get<1>(a); std::vector<element_type> a_vals = std::get<0>(a); dim b_dim = std::get<1>(b); std::vector<element_type> b_vals = std::get<0>(b); dim b_n_rows = b_vals.size() / b_dim; // num cols & rows in output matrix // n_rows from a x n_cols from b size_t n_cols = b_dim; size_t n_rows = std::get<0>(a).size() / a_dim; std::vector<element_type> vals_out; vals_out.reserve(n_cols * n_rows); // check to make sure conformable, a_cols = b_rows if (a_dim != b_n_rows) { size_t a_0 = a_vals.size() / a_dim; size_t a_1 = a_dim; size_t b_0 = b_vals.size() / b_dim; size_t b_1 = b_dim; // this is fairly improper std::cout << "utils::dot - matrices are not comformable\n"; std::cout << "matrix a: " << a_0 << " x " << a_1 << "\n"; std::cout << "matrix b: " << b_0 << " x " << b_1 << "\n"; exit(EXIT_FAILURE); } else { // is there a faster way to do this?? for (size_t row = 0; row < n_rows; row++) { for (size_t col = 0; col < n_cols; col++) { element_type sum = 0; // keep track of a and b important indices size_t a_begin = row * a_dim; size_t a_end = (row * a_dim) + a_dim; size_t b_idx = col; for (size_t a_idx = a_begin; a_idx < a_end; a_idx++) { sum += (a_vals.at(a_idx) * b_vals.at(b_idx)); b_idx += b_dim; } vals_out.push_back(sum); } } } return std::make_tuple(vals_out, n_cols); } // element-wise tanh void tanh_e_wise(matrix &a) { std::vector<element_type> *a_vals = &std::get<0>(a); for (size_t idx = 0; idx < (*a_vals).size(); idx++) { (*a_vals).at(idx) = tanh((*a_vals).at(idx)); } } // transposes a matrix matrix transpose(matrix &m) { std::vector<element_type> m_vals = std::get<0>(m); dim m_dim = std::get<1>(m); std::vector<element_type> vals_out; size_t n_rows = m_vals.size() / m_dim; for (size_t col = 0; col < m_dim; col++) { for (size_t row = 0; row < n_rows; row++) { vals_out.push_back(m_vals.at(row * m_dim + col)); } } return std::make_tuple(vals_out, n_rows); } // gets row i from matrix m // returns a 1xn matrix matrix get_row(const matrix &m, const size_t &i) { std::vector<element_type> vec_out; dim m_dim = std::get<1>(m); std::vector<element_type> m_vals = std::get<0>(m); auto iter_begin = m_vals.begin() + (i * m_dim); auto iter_end = m_vals.begin() + (i * m_dim) + m_dim; for (auto iter = iter_begin; iter != iter_end; ++iter) { vec_out.push_back(*iter); } return std::make_tuple(vec_out, m_dim); } // gets col j from matrix m // returns a mx1 matrix matrix get_col(const matrix &m, const size_t &j) { std::vector<element_type> vals_out; dim m_dim = std::get<1>(m); std::vector<element_type> m_vals = std::get<0>(m); size_t n_rows = m_vals.size() / m_dim; for (size_t row = 0; row < n_rows; row++) { vals_out.push_back(m_vals.at(row * m_dim + j)); } return std::make_tuple(vals_out, 1); } // sigmoid activation function void sigmoid(matrix &a) { std::vector<element_type> *a_vals = &std::get<0>(a); for (size_t idx = 0; idx < (*a_vals).size(); idx++) { (*a_vals).at(idx) = 1 / (1 + exp(-1 * ((*a_vals).at(idx)))); } } // adds matrix b to matrix a element wise without allocating // new memory. a is lost void add_in_place(matrix &a, const matrix &b) { dim *a_dim = &std::get<1>(a); std::vector<element_type> *a_vals = &std::get<0>(a); size_t a_n_rows = (*a_vals).size() / *a_dim; dim b_dim = std::get<1>(b); std::vector<element_type> b_vals = std::get<0>(b); size_t b_n_rows = std::get<0>(b).size() / b_dim; if (*a_dim == b_dim && a_n_rows == b_n_rows) { for (size_t idx = 0; idx < (*a_vals).size(); idx++) { (*a_vals).at(idx) = ((*a_vals).at(idx) + b_vals.at(idx)); } } else { std::cout << "utils::add_in_place - matrices are not same dims\n"; std::cout << "matrix a: " << (*a_vals).size() / *a_dim << " x " << *a_dim << "\n"; std::cout << "matrix b: " << b_vals.size() / b_dim << " x " << b_dim << "\n"; exit(EXIT_FAILURE); } } // subtracts matrix b from matrix a element wise without allocating // new memory. a is lost void subtract_in_place(matrix &a, const matrix &b) { dim *a_dim = &std::get<1>(a); std::vector<element_type> *a_vals = &std::get<0>(a); size_t a_n_rows = (*a_vals).size() / *a_dim; dim b_dim = std::get<1>(b); std::vector<element_type> b_vals = std::get<0>(b); size_t b_n_rows = std::get<0>(b).size() / b_dim; if (*a_dim == b_dim && a_n_rows == b_n_rows) { for (size_t idx = 0; idx < (*a_vals).size(); idx++) { (*a_vals).at(idx) = ((*a_vals).at(idx) - b_vals.at(idx)); } } else { std::cout << "utils::subtract_in_place - matrices are not same dims\n"; std::cout << "matrix a: " << (*a_vals).size() / *a_dim << " x " << *a_dim << "\n"; std::cout << "matrix b: " << b_vals.size() / b_dim << " x " << b_dim << "\n"; exit(EXIT_FAILURE); } } // element-wise clipping for all values in m void clip(matrix &m, element_type min, element_type max) { std::vector<element_type> *m_vals = &std::get<0>(m); for (size_t idx = 0; idx < (*m_vals).size(); idx++) { if ((*m_vals).at(idx) < min) { (*m_vals).at(idx) = min; } else if ((*m_vals).at(idx) > max) { (*m_vals).at(idx) = max; } } } // take all elements in the matrix to the power power void pow_e_wise(matrix &m, const double power) { std::vector<element_type> *m_vals = &std::get<0>(m); for (size_t idx = 0; idx < (*m_vals).size(); idx++) { (*m_vals).at(idx) = powl((*m_vals).at(idx), power); } } // add a scalar to all values in the matrix void add_scalar(matrix &m, const double scalar) { std::vector<element_type> *m_vals = &std::get<0>(m); for (size_t idx = 0; idx < (*m_vals).size(); idx++) { (*m_vals).at(idx) = (*m_vals).at(idx) + scalar; } } // multiply all values in the matrix m by a scalar void multiply_scalar(matrix &m, const double scalar) { std::vector<element_type> *m_vals = &std::get<0>(m); for (size_t idx = 0; idx < (*m_vals).size(); idx++) { (*m_vals).at(idx) = (*m_vals).at(idx) * scalar; } } // element-wise multiplication applied to the first void multiply(matrix &a, const matrix &b) { dim *a_dim = &std::get<1>(a); std::vector<element_type> *a_vals = &std::get<0>(a); size_t a_n_rows = (*a_vals).size() / *a_dim; dim b_dim = std::get<1>(b); std::vector<element_type> b_vals = std::get<0>(b); size_t b_n_rows = b_vals.size() / b_dim; if (a_n_rows == b_n_rows && *a_dim == b_dim) { for (size_t idx = 0; idx < (*a_vals).size(); idx++) { (*a_vals).at(idx) = (*a_vals).at(idx) * b_vals.at(idx); } } else { std::cout << "utils::multiply - matrices are not same dims\n"; std::cout << "matrix a: " << (*a_vals).size() / *a_dim << " x " << *a_dim << "\n"; std::cout << "matrix b: " << b_vals.size() / b_dim << " x " << b_dim << "\n"; } } // append b columns to a, returning a new matrix matrix append_cols(const matrix &a, const matrix &b) { dim a_dim = std::get<1>(a); std::vector<element_type> a_vals = std::get<0>(a); size_t a_n_rows = a_vals.size() / a_dim; dim b_dim = std::get<1>(b); std::vector<element_type> b_vals = std::get<0>(b); size_t b_n_rows = b_vals.size() / b_dim; std::vector<element_type> vals_out; if (b_n_rows == a_n_rows) { for (size_t row = 0; row < a_n_rows; row++) { for (size_t a_idx = row * a_dim; a_idx < row * a_dim + a_dim; a_idx++) { vals_out.push_back(a_vals.at(a_idx)); } for (size_t b_idx = row * b_dim; b_idx < row * b_dim + b_dim; b_idx++) { vals_out.push_back(b_vals.at(b_idx)); } } } else { std::cout << "utils::append_cols - a_n_rows != b_n_rows !!!\n"; } return std::make_tuple(vals_out, a_dim + b_dim); } // append b rows to a without allocating memory for an entire // new matrix, a is lost void append_rows(matrix &a, const matrix &b) { dim a_dim = std::get<1>(a); std::vector<element_type> *a_vals = &std::get<0>(a); dim b_dim = std::get<1>(b); std::vector<element_type> b_vals = std::get<0>(b); if (a_dim == b_dim) { for (element_type val : b_vals) { (*a_vals).push_back(val); } } else { std::cout << "utils::append_matrix - a_dim != b_dim!!!!"; } } // round all the values in m based on a rounding threshold void round(matrix &m, const double &threshold) { std::vector<element_type> *m_vals = &std::get<0>(m); for (size_t idx = 0; idx < (*m_vals).size(); idx++) { if ((*m_vals).at(idx) < threshold) { (*m_vals).at(idx) = 0.0; } else { (*m_vals).at(idx) = 1.0; } } } // trims whitespace from a string std::string trim_whitespace(std::string a_string) { size_t first = a_string.find_first_not_of(' '); if (first == std::string::npos) { return ""; } size_t last = a_string.find_last_not_of(' '); return a_string.substr(first, (last - first + 1)); } // parses a single line of a comma delimited input // file std::vector<std::string> parse_line(std::string line) { std::vector<std::string> vec_out; std::string delim = "|"; std::regex delim_regex(","); line = std::regex_replace(line, delim_regex, delim); size_t index = 0; std::string element; std::string trimmed_element; while ((index = line.find(delim)) != std::string::npos) { element = line.substr(0, index); trimmed_element = trim_whitespace(element); if (!trimmed_element.empty()) { vec_out.push_back(trim_whitespace(element)); } line.erase(0, index + delim.length()); } trimmed_element = trim_whitespace(line); if (!trimmed_element.empty()) { vec_out.push_back(line); } return vec_out; } // loads in the matrix from a string representing a file path std::tuple<matrix, matrix> load_sample(const std::string file_path) { bool dimension_known = false; dim dimension; std::vector<element_type> x_vals; std::vector<element_type> y_vals; std::fstream file_in; file_in.open(file_path, std::ios::in); std::string line; while (getline(file_in, line)) { std::vector<std::string> elements = parse_line(line); if (!dimension_known) { dimension = elements.size(); dimension_known = true; } else { if (elements.size() != dimension) { printf("Not every row has same dimension as first row\n"); exit(EXIT_FAILURE); } } for (size_t idx = 0; idx < elements.size() - 1; idx++) { x_vals.push_back(std::stod(elements.at(idx))); } y_vals.push_back(std::stod(elements.at(elements.size() - 1))); } matrix x = std::make_tuple(x_vals, dimension - 1); matrix y = std::make_tuple(y_vals, 1); file_in.close(); return std::make_tuple(x, y); } // loads dataets from the directory passed as dir_path std::tuple<std::vector<matrix>, std::vector<matrix>> load_from_dir(const std::string dir_path) { std::vector<matrix> X; std::vector<matrix> Y; // std::cout << "starting load loop\n"; for (const auto &entry : fs::directory_iterator(dir_path)) { std::tuple<matrix, matrix> matrices = load_sample(entry.path().string()); X.push_back(std::get<0>(matrices)); Y.push_back(std::get<1>(matrices)); } return std::make_tuple(X, Y); } // write a matrix to file void write(const matrix &m, const std::string file_path) { std::ofstream file_out; file_out.open(file_path); std::vector<element_type> m_vals = std::get<0>(m); dim m_dim = std::get<1>(m); size_t idx = 0; for (element_type val : m_vals) { idx++; if (idx != 0 && idx % m_dim == 0) { file_out << val << "\n"; } else { file_out << val << ","; } } file_out.close(); } // loads a weights matrix matrix load_weights_matrix(const std::string file_path, const dim m_dim, const dim n_dim) { std::vector<element_type> m_vals; size_t n_rows = 0; std::fstream file_in; file_in.open(file_path, std::ios::in); std::string line; while (getline(file_in, line)) { std::vector<std::string> elements = parse_line(line); if (elements.size() != n_dim) { printf("utils::load_weights_matrix - bad dimension\n"); exit(EXIT_FAILURE); } for (std::string element : elements) { m_vals.push_back(std::stod(element)); } if (elements.size() != 0) { n_rows++; } } if (n_rows != m_dim) { std::cout << "utils::load_weights_matrix - bad m dim\n"; exit(EXIT_FAILURE); } file_in.close(); matrix m = std::make_tuple(m_vals, n_dim); return m; } // randomly shuffle a vector of matrices void shuffle(std::vector<matrix> matrices) { std::shuffle(matrices.begin(), matrices.end(), generator); } // A special matrix multiplication function. // multiplies the first matrix by the transpose // of the second matrix. avoids a memory allocation matrix dott(const matrix &a, const matrix &b) { dim a_dim = std::get<1>(a); std::vector<element_type> a_vals = std::get<0>(a); dim b_dim = std::get<1>(b); std::vector<element_type> b_vals = std::get<0>(b); std::vector<element_type> vals_out; vals_out.reserve(b_vals.size() / b_dim * a_vals.size() / a_dim); // check to make sure conformable, a_rows = b_rows if (a_dim != b_dim) { std::cout << "utils::dott - matrices are not comformable\n"; exit(EXIT_FAILURE); } else { // is there a faster way to do this?? for (size_t a_row = 0; a_row < a_vals.size() / a_dim; a_row++) { for (size_t b_row = 0; b_row < b_vals.size() / b_dim; b_row++) { element_type sum = 0; size_t a_idx = a_row * a_dim; size_t b_idx = b_row * b_dim; for (size_t col = 0; col < a_dim; col++) { sum += (a_vals.at(a_idx + col) * b_vals.at(b_idx + col)); } vals_out.push_back(sum); } } } return std::make_tuple(vals_out, b_vals.size() / b_dim); }
true
762c3400dd4af24ceaaa04d56b119a5a59780891
C++
xiexnot/LeetCode
/501-600/LeetCode 516 Longest Palindromic Subsequence.cpp
UTF-8
808
2.9375
3
[]
no_license
class Solution { public: int longestPalindromeSubseq(string s) { vector< vector<int> > LongestSubsequence; int n = s.size(); if (s.size()<=1) return s.size(); LongestSubsequence.resize(n); for (int i=0;i<s.size();i++) LongestSubsequence[i].resize(n); for (int i=0;i<s.size()-1;i++) LongestSubsequence[i][i] = 1; for (int i=0;i<s.size()-1;i++) if (s[i] == s[i+1]) LongestSubsequence[i][i+1] = 2; else LongestSubsequence[i][i+1] = 1; int j; for (int k=2;k<s.size();k++) for (int i=0;i<s.size()-k;i++){ j = i + k; if (s[i] == s[j]) LongestSubsequence[i][j] = LongestSubsequence[i+1][j-1] + 2; else LongestSubsequence[i][j] = max(LongestSubsequence[i+1][j], LongestSubsequence[i][j-1]); } return LongestSubsequence[0][s.size()-1]; } };
true
491891d954913d5b968ab4ac8c6e85222825d13d
C++
WuZixing/Geo3DML-CPP
/src/geo3dml/Map.cpp
UTF-8
1,200
2.640625
3
[ "MIT" ]
permissive
#include <geo3dml/Map.h> using namespace geo3dml; Map::Map() { } Map::~Map() { std::vector<Layer*>::const_iterator layerItor = layers_.cbegin(); while (layerItor != layers_.cend()) { delete *layerItor; ++layerItor; } } void Map::SetName(const std::string& name) { name_ = name; } std::string Map::GetName() const { return name_; } void Map::SetDescription(const std::string& s) { description_ = s; } std::string Map::GetDescription() const { return description_; } void Map::SetParentProject(const std::string& id) { parentProjectId_ = id; } std::string Map::GetParentProject() const { return parentProjectId_; } void Map::AddLayer(Layer* layer) { std::vector<Layer*>::const_iterator citor = layers_.cbegin(); while (citor != layers_.cend()) { if (*citor == layer) { return; } ++citor; } layer->SetParentMap(GetID()); layers_.push_back(layer); } int Map::GetLayerCount() const { return (int)layers_.size(); } Layer* Map::GetLayerAt(int i) const { return layers_.at(i); } Box3D Map::GetMinimumBoundingRectangle() const { Box3D box; for (size_t i = 0; i < layers_.size(); ++i) { box.UnionWith(layers_[i]->GetMinimumBoundingRectangle()); } return box; }
true
b1083682e4f568369948499bc1191dbf2eb09cb0
C++
Kvazar3S273/Cpp-2020
/DZ20/DZ20/TZ.cpp
WINDOWS-1251
4,668
3.046875
3
[]
no_license
/*TASK 1 ; ( ) , '; ( ' , -- pop() / push() ); , -- , ' (, ) Node. (" " ", ' ' ") :*/ /* - , , . ( ) 쳺 70 % . , 30 . 쳺 : ( "") () 쳺 : - 1 , , , ( , , "") */ /*TASK 2 (class BusList). (class Bus) : ; ; . BusList AutoPark : : , ; , . , , , . , , , . AutoPark . : -- -- -- -- : , ( / ) */
true
89b20a7b9577013517bdf117b17d07e193ce3624
C++
zhanhang2014/pat-advanced
/2015-03-14(1092-1095)/1094.cpp
UTF-8
916
2.90625
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct Node{ int id; vector<int> child; }; vector<Node> node; vector<int> gen; vector<bool> isleave; int maxdepth = 0; void dfs(int root, int depth){ gen[depth]++; maxdepth = max(maxdepth, depth); if (isleave[root]) return; for (int i = 0; i < node[root].child.size(); i++){ dfs(node[root].child[i], depth+1); } } int main(){ int n, m; cin >> n >> m; node.resize(n + 1); gen.assign(n + 1, 0); isleave.assign(n + 1, true); int r, k, c; for (int i = 0; i < m; i++){ cin >> r >> k; isleave[r] = false; for (int j = 0; j < k; j++){ cin >> c; node[r].child.push_back(c); } } if (n == 1) { cout << "1 1\n"; return 0; } dfs(1, 0); int large = 0, dp = 0; for (int i = 1; i <= maxdepth; i++){ if (gen[i]>large){ large = gen[i]; dp = i; } } cout << large << ' ' << dp+1 << endl; return 0; }
true
bf3c4a268c3b98dc999d27601597e69d4472bce7
C++
SKantar/CrackingTheCoodingInterview
/01. Arrays&Strings/1_9.cpp
UTF-8
609
3.46875
3
[]
no_license
/** * String Rotation:Assumeyou have a method isSubstringwhich checks if one word is a substring * of another. Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one * call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat"). **/ #include <cstdio> #include <cstdlib> #include <cstring> #define MAXN 256 using namespace std; int main(){ char str1[MAXN]; char str2[MAXN]; strcpy(str1, "erbottlewat"); strcpy(str2, "waterbottle"); strcat(str1, str1); printf("%s\n", strstr(str1, str2) == NULL ? "No" : "Yes"); return 0; }
true
dbe30232bb54a9e36aa794e2f34e020d40249058
C++
Zhaozzy-hub/LeetCode_Problems
/Solutions/canIWin464.cpp
UTF-8
896
2.984375
3
[]
no_license
#include <vector> #include <iostream> #include <map> using namespace std; bool solve2(int state, int desiredTotal, vector<char>& m, int maxChoosableInteger) { if (desiredTotal <= 0) return false; if (m[state]) { return m[state] == 1; } for (int i = 0; i < maxChoosableInteger; i++) { if (state & (1 << i))continue; if (!solve2(state | (1 << i), desiredTotal - i - 1, m, maxChoosableInteger)) { return m[state] = 1; } } m[state] = -1; return false; } bool canIWin(int maxChoosableInteger, int desiredTotal) { if ((1 + maxChoosableInteger) * maxChoosableInteger / 2 < desiredTotal) { return false; } if (desiredTotal <= 0) return true; vector<char>m(1 << maxChoosableInteger, 0); return solve2(0, desiredTotal, m, maxChoosableInteger); } //int main() { // cout << canIWin(20, 152) << endl; //}
true
5fdb25c6c2cd4efec1638bbc029c1b5db21eb7ac
C++
itstepP12814/Himbitski
/HW12/HW12-1/12Hw1.cpp
UTF-8
496
3.265625
3
[]
no_license
#include <iostream> #include <ctime> using namespace std; void swap(int *a,int *b){ int tmp; tmp = *a; *a = *b; *b = tmp; } void main() { const int size = 20; int mass[size]; int *pa = mass; srand(time(NULL)); for (int i = 0; i < size; ++i) { mass[i] = rand() % 20; cout << mass[i] << " "; } cout << endl; for (int i = 0; i < size - 1; i = i + 2) { swap(pa + i, pa + i + 1); } cout << endl; for (int i = 0; i < size; ++i) { cout << mass[i] << " "; } cout << endl; }
true
92094151fc9c6fc2e598b0ca99b52eb1a12d4270
C++
westernLoser/cpp-primer-5th
/chapter 15/15.7.h
UTF-8
676
3.015625
3
[]
no_license
/* author : szz date : 2019/07/20 */ #ifndef C_15_7_H #define C_15_7_H #include<string> #include"15.3.h" class Bulk_quote_II: public Quote { public: Bulk_quote_II() = default; Bulk_quote_II(const std::string &s, double p, size_t qty, double disc): Quote(s, p), max_qty(qty), discount(disc) { } double net_price(std::size_t n) const override { double ret = 0; if (n > max_qty) { ret = price * ((n - max_qty) + max_qty * (1 - discount)); } else { ret = price * n * (1 - discount); } return ret; } private: size_t max_qty = 0; double discount = 0.0; }; #endif
true
19d3d96668e420d595c0a6ad4db5a2f5cd547c06
C++
noshbar/HotdogPI
/main.cpp
UTF-8
4,838
3.03125
3
[]
no_license
/* This simple program was thrown together to see if tossing thousands of sausages at lines can be used to calculate PI, described here: http://www.wikihow.com/Calculate-Pi-by-Throwing-Frozen-Hot-Dogs Basically you take a sausage of length N, draw a bunch of lines that are distance N apart, and throw some sausages towards the line. For every throw, increment a throw counter TC, and for every hotdog that comes to rest crossing a line, increment a cross counter CC. After you're tired of manhandling sausages, calculate PI by doing: pi = TC * (2 / CC) There are many better ways to do this, this was simply the quickest way I knew to code it up for instant gratification. For what it's worth, this had PI accurate to 6 digits after a few million iterations (and was no better off after a few trillion) NOTE: It turns out that adjusting the hotdogWidth to be anything but 0.0f tosses the estimate/convergence out quite a bit. so for now, we're throwing _really_ thin needles instead. (instead of a width of 0, I guess you could make a really long and thin needle too) */ #define _USE_MATH_DEFINES //to calculate some things, and compare our answer to M_PI, we need to set this define, so that math.h exposes it #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdint.h> //for int64 support int main(int argc, char *argv[]) { uint64_t tosses = 0; //total number of tosses uint64_t crosses = 0; //how many hotdogs came to rest crossing a line double hotdogWidth = 0.0f; //the width of the hotdog, defines the radius of the cap at the end double capRadius = hotdogWidth / 2.0f; //the radius of the round bits/cap at the end double shaftLength = 1.0f; //the length of the hotdog shaft, that is, only of the straight parts, excluding the curved ends double halfShaft = shaftLength / 2.0f; //we're working with circles centered around 0, so it makes sense to have some radius's pre-calculated double totalLength = shaftLength + (2 * capRadius); //the total length is the length of the shaft, plus both caps on the end int output = 0; //a toggle we use to show output double best = 0; //the best estimate of PI so far, could be a random one off chance, but meh double bestDifference = 1000; //the difference between the best PI and real PI, start high so that our first hit should be lower uint64_t bestToss = 0; //the iteration the best mostly-PI happened on //kick off the random number generator srand(time(NULL)); while (1) { //pick a random position double x = (rand() / (double)RAND_MAX) * totalLength; double y = (rand() / (double)RAND_MAX) * totalLength; //pick a random angle, where angle = (random percent * PI), seeing as cos and sin use radians. double angle = (rand() / (double)RAND_MAX) * M_PI; //we center our hotdog around 0 initially, meaning that the tip of one end rotated at our random angle will be at cos(angle) and sin(angle) //we only use halfShaft as the length, we will cater for the caps later double xOffset = (cos(angle) * halfShaft); double yOffset = (sin(angle) * halfShaft); //seeing as we only calculated one tip, we need to find the opposite one. as we were rotating around zero, we can simply invert the points in space by multiplying them by -1. //also in this step, we move them to our random position double x1 = x - xOffset; double y1 = y - yOffset; double x2 = x + xOffset; double y2 = y + yOffset; //now we have the positions of the two ends of the _shaft_, from these points, we can simply add the radius of the caps either way and see if they cross a line if ( (x1 + capRadius >= totalLength) || (x2 + capRadius >= totalLength) || (x1 - capRadius <= 0) || (x2 - capRadius <= 0) ) crosses++; //now work our sort-of PI out using the magic formula double kindaPi = tosses * (2 / (double)crosses); double difference = M_PI - kindaPi; //if this is our best PI yet, store it for safe keeping if (fabs(difference) < fabs(bestDifference)) { best = kindaPi; bestDifference = difference; bestToss = tosses - 1; } tosses++; output++; if (output == 10000000) { printf("tosses\t\t= %lld\n", tosses); printf("crosses\t\t= %lld\n", crosses); printf("~pi\t\t= %.15f\n", kindaPi); printf("pi\t\t= %.15f\n", M_PI); printf("difference\t= %f\n", difference); printf("best so far\t= %.15f (difference: %.15f @ %lld)\n", best, fabs(bestDifference), bestToss); printf("\n"); output = 0; } } return 0; }
true
6ea1cf58778b54e1ce88bca93c6d21e880af6870
C++
claudiocabral/contemporary_cpp
/language/auto.cpp
UTF-8
481
3.03125
3
[]
no_license
// C++11 changed the meaning of the auto keyword void f() { auto a = some_func(); decltype(auto) b = some_func(); auto * c = some_func(); auto & d = some_func(); const auto & e = some_func(); } // on function signatures can be used with trailing return types auto f() -> void {} // can be inferred from C++14 onwards auto f() {} // on C++20 can be used as a shorthand for templates void f(auto a, auto b); // equivalent to template<class T, class U> void f(T a, U b);
true
aa38c8f9f6344e10cfd9111a490f1a8d88893fe9
C++
thesyntaxninja/20.6-concatenating-lists
/main.cpp
UTF-8
1,048
3.984375
4
[]
no_license
// 20.6 main.cpp // Description: Problem 2 of 2 due week 9 // Programmer: Parker Esmay // Date: 03/23/2015 // (Concatenating Lists) Write a program that concatenates two linked list objects of characters. The program // should include function concatenate, which takes references to both list objects as arguments and concatenates // the second list to the first list. #include <iostream> #include <cstdlib> #include <conio.h> #include "List.h" using namespace std; int main(int argc, char** argv) { List<char> firstList; List<char> secondList; char c; // assign characters for (c = 'a'; c <= 'g'; c++) firstList.insertFront(c); // insert at front of list // call function print to print the list firstList.print(); // assign from f to j into second list for (c = 'f'; c <= 'j'; c++) secondList.insertBack(c); // insert in back of list secondList.print(); // concatenate secondList to the firstList concatenate(firstList, secondList); cout << "firstList after concatenation:\n"; firstList.print(); getch(); return 0; }
true
9717ffbcac29fcea546aa02a577f19329c8890ec
C++
Jadiepie-658/CSC17A-47827
/Homework/Code E Problems/Assignment 2 of Code E/PROBLEM 4 Sum-Dynamic Memory Allocation/main.cpp
UTF-8
1,520
4.0625
4
[]
no_license
#include <iostream> using namespace std; int *getData(int &); int *sumAry(const int *, int); void prntAry(const int *, int); int main(){ int size; int *data; // to retrieve array int *add; //to get sum data array data = getData(size); add = sumAry(data, size); prntAry(add, size); return 0; } int *getData(int &size) { //input size cin >> size; //create dynamically allocated array int *array = new int[size]; //input values of the integer array for(int i = 0; i < size; i++) { cin >> array[i]; if(i == size - 1) { cout << array[i]; break; } cout << array[i]; } cout << endl; return array; } int *sumAry(const int *arr, int size) { //new dynamically allocated array int *arr2 = new int[size]; int count = 0; //copy first array to second array for(int i = 0; i < size; i++) { arr2[i] = arr[i]; } for(int i = 0; i < size; i++) { count = count + arr[i]; //adding each number to each other in the array arr2[i] = count; //assigns new array with the sum array } cout << endl; return arr2; //return new array } void prntAry(const int *sum, int size) { for(int i = 0; i < size; i++) { if(i == size - 1) //need if statement for correct spacing { cout << sum[i]; break; } cout << sum[i] << " "; } }
true
ad4c18d902239f88adc3559918833adbb86403c8
C++
gregmedlock/roadrunnerwork
/source/rrEvent.cpp
UTF-8
1,440
2.90625
3
[ "Apache-2.0" ]
permissive
#ifdef USE_PCH #include "rr_pch.h" #endif #pragma hdrstop #include "rrEvent.h" #include "rrRandom.h" //--------------------------------------------------------------------------- namespace rr { Event::Event(const int& id, const double& prior, const double& delay) : mID(id), mPriority(prior), mDelay(delay) {} Event::Event(const Event& rhs) { (*this) = rhs; } Event& Event::operator=(const Event& rhs) { if(this != &rhs) { (*this).mID = rhs.mID; (*this).mPriority = rhs.mPriority; (*this).mDelay = rhs.mDelay; } return *this; } int Event::GetID() const { return mID; } void Event::SetPriority(const double& prior) { mPriority = prior; } double Event::GetPriority() const { return mPriority; } //Friend functions bool operator==(const Event &e1, const Event &e2) { if(e1.mID == e1.mID && e1.mPriority == e2.mPriority && e1.mDelay == e2.mDelay) { return true; } return false; } bool operator<(const Event &e1, const Event &e2) { if(e1.mPriority == e2.mPriority && e1.mPriority !=0 && e1.mID != e2.mID) { //Random toss... return (e1.mRandom.NextDouble() > 0.5) ? false : true; } return e1.mPriority >= e2.mPriority; //Used in sorting algorithm } ostream& operator<<(ostream& str, const Event& event) { str<<"Event ID: "<<event.mID<<" Priority: "<<event.mPriority; return str; } }
true
d809978633e00897226bdabf1a2688f1ec955ec7
C++
kevincoxwork/cpp-patterns-mvc-framework
/ProjectLibrary/singleton.cpp
UTF-8
1,659
2.9375
3
[]
no_license
/*! \singleton.cpp \author Kevin Cox \date 2019-01-19 \version 1.0.0 \note Last edited for Project 1 \brief Implementation of singleton.hpp methods. */ #include <cox\patterns\singleton.hpp> #include <iostream> #include <exception> using namespace std; /*! Process entry point. Calls the SingletonPattern singleton's wmain. */ int wmain(int argc, wchar_t* argv[]) try { #ifdef _DEBUG // Enable CRT memory leak checking. int dbgFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); dbgFlags |= _CRTDBG_CHECK_ALWAYS_DF; dbgFlags |= _CRTDBG_DELAY_FREE_MEM_DF; dbgFlags |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(dbgFlags); #endif return SingletonPattern::thisApp_sm->wmain(argc, argv); } catch (char const * msg) { wcerr << L"exception string: " << msg << endl; } catch (exception const& e) { wcerr << L"std::exception: " << e.what() << endl; } catch (...) { wcerr << L"Error: an exception has been caught...\n"; return EXIT_FAILURE; } /*! SingletonPattern singleton instance pointer. */ SingletonPattern* SingletonPattern::thisApp_sm = nullptr; /*! main configures the application. */ int SingletonPattern::wmain(int argc, wchar_t* argv[]) { args_m.assign(argv, argv + argc); return execute(); } /*! Singleton initialization and confirmation. Throws a logic_error if multiple instances are created. */ SingletonPattern::SingletonPattern() { if (thisApp_sm) throw std::logic_error("Error: Singleton Pattern has already been initialized!"); thisApp_sm = this; } /*! execute the application. Override this method in the derived class. */ int SingletonPattern::execute() { wcout << "Singleton Pattern Framework - Kevin Cox\n"; return EXIT_SUCCESS; }
true
ed13c0e8d09814690f89b0b50ea81c8afba9a80e
C++
ligianovacean/Arduino-Car
/CarControl/ReadSensor.cpp
UTF-8
564
2.8125
3
[]
no_license
#pragma once #include "ReadSensor.h" void initSensor() { pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } int computeDistance() { // Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds long duration = pulseIn(echoPin, HIGH, 30000); int distance= duration*0.034/2; delay(100); return distance; }
true
9ce4a8b36045c34d38779df453687de4629813ac
C++
allannielsen/termhub
/key-tokenizer/src/action.cxx
UTF-8
1,365
2.78125
3
[]
no_license
#include "key-tokenizer/action.hxx" namespace KeyTokenizer { Action operator%(const Action &a, const Action &b) { Action res; // least common represantant res.consume_data = std::min(a.consume_data, b.consume_data); // prioritize two complete matches if (a.complete() && b.complete()) { // first match wins if (a.consume_data < b.consume_data) { return a; } else if (b.consume_data < a.consume_data) { return b; } else { // match start at same place, longest match wins if (a.consume_token > b.consume_token) return a; else return b; } } // timed completion overrules partial matches! if (a.complete_timed() || b.complete_timed()) { if (a.consume_token > b.consume_token) return a; else return b; } // one or more partial matches implies result is partial if (a.partial_match || b.partial_match) { res.partial_match = true; // leave consume_token at zero! return res; } // no partial complete or multiple - just a single match if (a.complete()) { return a; } else if (b.complete()) { return b; } // consume the data nobody wants return res; } } // namespace KeyTokenizer
true
1e12e8056caf98a2273bb0e5abb6761f1e8a3abd
C++
Stasich/learning_cpp
/Lafore_exercises/411_times.cpp
UTF-8
1,056
3.75
4
[]
no_license
// 410_times.cpp #include <iostream> #include <iomanip> using namespace std; struct times { int hours, minutes, seconds; }; int main() { times t1, t2, t_sum; unsigned long totalsecs_sum; char ch = ':'; cout << "Ввидите первое значение времени в формате чч:мм:сс : "; cin >> t1.hours >> ch >> t1.minutes >> ch >> t1.seconds; cout << "Ввидите второе значение времени в формате чч:мм:сс : "; cin >> t2.hours >> ch >> t2.minutes >> ch >> t2.seconds; totalsecs_sum = t1.hours * 3600 + t1.minutes * 60 + t1.seconds + t2.hours * 3600 + t2.minutes * 60 + t2.seconds; t_sum.hours = totalsecs_sum / 3600; t_sum.minutes = totalsecs_sum % 3600 / 60; t_sum.seconds = totalsecs_sum % 3600 % 60; cout << "Сумма времени: " << setw(2) << setfill('0') << t_sum.hours << ch << setw(2) << setfill('0') << t_sum.minutes << ch << setw(2) << setfill('0') << t_sum.seconds << endl; return 0; }
true