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
a4956972a8be12c230d4022ef8350c8c8fb1c61b
C++
Chrinkus/wumpus
/src/Random_utils.h
UTF-8
2,063
3.4375
3
[ "MIT" ]
permissive
// // Created by Chris Schick on 2018-06-05. // #ifndef WUMPUS_RANDOM_UTILS_H #define WUMPUS_RANDOM_UTILS_H #include <random> #include <chrono> #include <vector> class Random_int { public: Random_int() : ran{static_cast<unsigned int>(std::chrono::system_clock::now() .time_since_epoch().count())} { } int operator()(int min, int max) { return std::uniform_int_distribution<>{min, max}(ran); } private: std::minstd_rand ran; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * template<typename T> // requires incrementable value class Assignment_table { // A sorted vector of T values to randomly grab from public: Assignment_table(size_t sz, T start) : table{std::vector<T>(sz)} { for (auto& val : table) val = start++; } T get_value(T low, T high); T get_value(); const auto& view_table() const { return table; } // aids debugging private: std::vector<int> table; Random_int random_index; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * template<typename T> T Assignment_table<T>::get_value(T low, T high) // find iterators to values not lower than low and one higher than high // calculate a random offset based on their distance - 1 // remove the value from the table and return it { auto it_min = std::lower_bound(std::begin(table), std::end(table), low); auto it_max = std::upper_bound(std::begin(table), std::end(table), high); auto dist = std::distance(it_min, it_max); auto offset = random_index(0, dist - 1); auto it_val = it_min + offset; auto value = *it_val; table.erase(it_val); return value; } template<typename T> T Assignment_table<T>::get_value() // grab a random value from the table, remove and return it { auto offset = random_index(0, table.size() - 1); auto it_val = std::begin(table) + offset; auto value = *it_val; table.erase(it_val); return value; } #endif //WUMPUS_RANDOM_UTILS_H
true
a5b88958feb8fa67225fcccb69e90e55156abb97
C++
pahowes/hash-test
/include/murmur_hash.hpp
UTF-8
3,660
2.734375
3
[ "Apache-2.0" ]
permissive
/** * @file murmur_hash.hpp */ #pragma once #include "hash_base.hpp" #include "MurmurHash1.h" #include "MurmurHash2.h" #include "MurmurHash3.h" class murmurhash1 : public hash_base<murmurhash1, uint32_t> { public: std::string do_name() { return "MurmerHash1"; } uint32_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { return MurmurHash1(data, data_length, seed); } }; class murmurhash1_aligned : public hash_base<murmurhash1_aligned, uint32_t> { public: std::string do_name() { return "MurmerHash1Aligned"; } uint32_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { return MurmurHash1Aligned(data, data_length, seed); } }; class murmurhash2 : public hash_base<murmurhash2, uint32_t> { public: std::string do_name() { return "MurmurHash2"; } uint32_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { return MurmurHash2(data, data_length, seed); } }; class murmurhash64a : public hash_base<murmurhash64a, uint64_t> { public: std::string do_name() { return "MurmurHash64A"; } uint64_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { return MurmurHash64A(data, data_length, seed); } }; class murmurhash64b : public hash_base<murmurhash64b, uint64_t> { public: std::string do_name() { return "MurmurHash64B"; } uint64_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { return MurmurHash64B(data, data_length, seed); } }; class murmurhash2a : public hash_base<murmurhash2a, uint32_t> { public: std::string do_name() { return "MurmurHash2A"; } uint32_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { return MurmurHash2A(data, data_length, seed); } }; class murmurhashneutral2 : public hash_base<murmurhashneutral2, uint32_t> { public: std::string do_name() { return "MurmurHashNeutral2"; } uint32_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { return MurmurHashNeutral2(data, data_length, seed); } }; class murmurhashaligned2 : public hash_base<murmurhashaligned2, uint32_t> { public: std::string do_name() { return "MurmurHashAligned2"; } uint32_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { return MurmurHashAligned2(data, data_length, seed); } }; class murmurhash3_x86_32 : public hash_base<murmurhash3_x86_32, uint32_t> { public: std::string do_name() { return "MurmurHash3 x86 32-bit"; } uint32_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { uint32_t hash; MurmurHash3_x86_32(data, data_length, seed, &hash); return hash; } }; class murmurhash3_x86_128 : public hash_base<murmurhash3_x86_128, uint32_t> { public: std::string do_name() { return "MurmurHash3 x86 128-bit"; } uint32_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { uint32_t hash; MurmurHash3_x86_128(data, data_length, seed, &hash); return hash; } }; class murmurhash3_x64_128 : public hash_base<murmurhash3_x64_128, uint64_t> { public: std::string do_name() { return "MurmurHash3 x64 128-bit"; } uint64_t do_hash(const void* data, const uint32_t data_length, const uint32_t seed) { uint64_t hash; MurmurHash3_x64_128(data, data_length, seed, &hash); return hash; } };
true
9d726405ab9ffc3bb8879be0090b57aec3e0af45
C++
sssphil/openeb
/sdk/modules/core/cpp/include/metavision/sdk/core/algorithms/flip_y_algorithm.h
UTF-8
4,501
2.609375
3
[]
no_license
/********************************************************************************************************************** * Copyright (c) Prophesee S.A. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed * * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and limitations under the License. * **********************************************************************************************************************/ #ifndef METAVISION_SDK_CORE_FLIP_Y_ALGORITHM_H #define METAVISION_SDK_CORE_FLIP_Y_ALGORITHM_H #include <memory> #include <sstream> #include "metavision/sdk/base/utils/sdk_log.h" #include "metavision/sdk/core/algorithms/detail/internal_algorithms.h" #include "metavision/sdk/base/events/event2d.h" namespace Metavision { /// @brief Class that allows to mirror the Y axis of an event stream. /// /// The transfer function of this filter impacts only the Y coordinates of the Event2d by:\n /// y = height_minus_one - y class FlipYAlgorithm { public: /// @brief Builds a new FlipYAlgorithm object with the given height /// @param height_minus_one Maximum Y coordinate of the events inline explicit FlipYAlgorithm(std::int16_t height_minus_one); /// Default destructor ~FlipYAlgorithm() = default; /// @brief Applies the Flip Y filter to the given input buffer storing the result in the output buffer /// @tparam InputIt Read-Only input event iterator type. Works for iterators over buffers of @ref EventCD /// or equivalent /// @tparam OutputIt Read-Write output event iterator type. Works for iterators over containers of @ref EventCD /// or equivalent /// @param it_begin Iterator to first input event /// @param it_end Iterator to the past-the-end event /// @param inserter Output iterator or back inserter template<class InputIt, class OutputIt> inline void process_events(InputIt it_begin, InputIt it_end, OutputIt inserter) { detail::transform(it_begin, it_end, inserter, std::ref(*this)); } /// @note process(...) is deprecated since version 2.2.0 and will be removed in later releases. /// Please use process_events(...) instead template<class InputIt, class OutputIt> // clang-format off [[deprecated("process(...) is deprecated since version 2.2.0 and will be removed in later releases. " "Please use process_events(...) instead")]] inline void process(InputIt first, InputIt last, OutputIt d_first) // clang-format on { static bool warning_already_logged = false; if (!warning_already_logged) { std::ostringstream oss; oss << "FlipYAlgorithm::process(...) is deprecated since version 2.2.0 "; oss << "and will be removed in later releases. "; oss << "Please use FlipYAlgorithm::process_events(...) instead" << std::endl; MV_SDK_LOG_WARNING() << oss.str(); warning_already_logged = true; } process_events(first, last, d_first); } /// @brief Returns the maximum Y coordinate of the events /// @return Maximum Y coordinate of the events inline std::int16_t height_minus_one() const; /// @brief Sets the maximum Y coordinate of the events /// @param height_minus_one Maximum Y coordinate of the events inline void set_height_minus_one(std::int16_t height_minus_one); /// @brief Applies the Flip y filter to the given input buffer storing the result in the output buffer. /// @param ev Event2d to be updated inline void operator()(Event2d &ev) const; private: std::int16_t height_minus_one_{0}; }; } // namespace Metavision #include "detail/flip_y_algorithm_impl.h" #endif // METAVISION_SDK_CORE_FLIP_Y_ALGORITHM_H
true
1441005a66f8185c739323389772ce25bd855dcf
C++
Mervap/ITMO
/LabsDM/term1/3/Z2/Z2.cpp
UTF-8
724
2.84375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <fstream> using namespace std; int main() { freopen("gray.in", "r", stdin); freopen("gray.out", "w", stdout); int n; cin >> n; vector<string> a; a.push_back("0"); a.push_back("1"); for (int i = 1; i < n; i++) { for (int j = (int) a.size() - 1; j >= 0; --j) { a.push_back(a[j]); } for (int j = 0; j < (int) a.size() / 2; ++j) { a[j] = "0" + a[j]; } for (int j = (int) a.size() / 2; j < (int) a.size(); ++j) { a[j] = "1" + a[j]; } } for (int i = 0; i < (int) a.size(); ++i) { cout << a[i] << "\n"; } return 0; }
true
fd3d5e4030ee296fed549fd803b595c9020769f6
C++
Funto/Tohoku-Engine
/src/glm/BACKUP/core/type_mat3x3.inl
UTF-8
16,054
3.140625
3
[]
no_license
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2005-01-27 // Updated : 2008-08-25 // Licence : This source is under MIT License // File : glm/core/type_mat3x3.inl /////////////////////////////////////////////////////////////////////////////////////////////////// namespace glm{ namespace detail{ template <typename valType> typename tmat3x3<valType>::size_type tmat3x3<valType>::value_size() { return typename tmat3x3<valType>::size_type(3); } template <typename valType> typename tmat3x3<valType>::size_type tmat3x3<valType>::col_size() { return typename tmat3x3<valType>::size_type(3); } template <typename valType> typename tmat3x3<valType>::size_type tmat3x3<valType>::row_size() { return typename tmat3x3<valType>::size_type(3); } template <typename valType> bool tmat3x3<valType>::is_matrix() { return true; } ////////////////////////////////////// // Accesses template <typename valType> detail::tvec3<valType>& tmat3x3<valType>::operator[](typename tmat3x3<valType>::size_type i) { assert( i >= typename tmat3x3<valType>::size_type(0) && i < tmat3x3<valType>::col_size()); return value[i]; } template <typename valType> const detail::tvec3<valType>& tmat3x3<valType>::operator[](typename tmat3x3<valType>::size_type i) const { assert( i >= typename tmat3x3<valType>::size_type(0) && i < tmat3x3<valType>::col_size()); return value[i]; } ////////////////////////////////////////////////////////////// // mat3 constructors template <typename T> inline tmat3x3<T>::tmat3x3() { this->value[0] = detail::tvec3<T>(1, 0, 0); this->value[1] = detail::tvec3<T>(0, 1, 0); this->value[2] = detail::tvec3<T>(0, 0, 1); } template <typename T> inline tmat3x3<T>::tmat3x3(const T f) { this->value[0] = detail::tvec3<T>(f, 0, 0); this->value[1] = detail::tvec3<T>(0, f, 0); this->value[2] = detail::tvec3<T>(0, 0, f); } template <typename T> inline tmat3x3<T>::tmat3x3 ( const T x0, const T y0, const T z0, const T x1, const T y1, const T z1, const T x2, const T y2, const T z2 ) { this->value[0] = detail::tvec3<T>(x0, y0, z0); this->value[1] = detail::tvec3<T>(x1, y1, z1); this->value[2] = detail::tvec3<T>(x2, y2, z2); } template <typename T> inline tmat3x3<T>::tmat3x3 ( const detail::tvec3<T>& v0, const detail::tvec3<T>& v1, const detail::tvec3<T>& v2 ) { this->value[0] = v0; this->value[1] = v1; this->value[2] = v2; } ////////////////////////////////////////////////////////////// // mat3 conversions template <typename T> template <typename U> inline tmat3x3<T>::tmat3x3(const tmat3x3<U>& m) { this->value[0] = detail::tvec3<T>(m[0]); this->value[1] = detail::tvec3<T>(m[1]); this->value[2] = detail::tvec3<T>(m[2]); } template <typename T> inline tmat3x3<T>::tmat3x3(tmat2x2<T> const & m) { this->value[0] = detail::tvec3<T>(m[0], T(0)); this->value[1] = detail::tvec3<T>(m[1], T(0)); this->value[2] = detail::tvec3<T>(detail::tvec2<T>(0), T(1)); } template <typename T> inline tmat3x3<T>::tmat3x3(const tmat4x4<T>& m) { this->value[0] = detail::tvec3<T>(m[0]); this->value[1] = detail::tvec3<T>(m[1]); this->value[2] = detail::tvec3<T>(m[2]); } template <typename T> inline tmat3x3<T>::tmat3x3(const tmat2x3<T>& m) { this->value[0] = m[0]; this->value[1] = m[1]; this->value[2] = detail::tvec3<T>(detail::tvec2<T>(0), T(1)); } template <typename T> inline tmat3x3<T>::tmat3x3(const tmat3x2<T>& m) { this->value[0] = detail::tvec3<T>(m[0], T(0)); this->value[1] = detail::tvec3<T>(m[1], T(0)); this->value[2] = detail::tvec3<T>(m[2], T(1)); } template <typename T> inline tmat3x3<T>::tmat3x3(const tmat2x4<T>& m) { this->value[0] = detail::tvec3<T>(m[0]); this->value[1] = detail::tvec3<T>(m[1]); this->value[2] = detail::tvec3<T>(detail::tvec2<T>(0), T(1)); } template <typename T> inline tmat3x3<T>::tmat3x3(const tmat4x2<T>& m) { this->value[0] = detail::tvec3<T>(m[0], T(0)); this->value[1] = detail::tvec3<T>(m[1], T(0)); this->value[2] = detail::tvec3<T>(m[2], T(1)); } template <typename T> inline tmat3x3<T>::tmat3x3(const tmat3x4<T>& m) { this->value[0] = detail::tvec3<T>(m[0]); this->value[1] = detail::tvec3<T>(m[1]); this->value[2] = detail::tvec3<T>(m[2]); } template <typename T> inline tmat3x3<T>::tmat3x3(const tmat4x3<T>& m) { this->value[0] = m[0]; this->value[1] = m[1]; this->value[2] = m[2]; } /* template <typename T> inline tmat3x3<T>::tmat3x3(const T* a) { this->value[0] = detail::tvec3<T>(a[0], a[1], a[2]); this->value[1] = detail::tvec3<T>(a[3], a[4], a[5]); this->value[2] = detail::tvec3<T>(a[6], a[7], a[8]); } */ /* // GL_GTX_euler_angles template <typename T> inline tmat3x3<T>::tmat3x3(const detail::tvec3<T> & angles) { T ch = cos(angles.x); T sh = sin(angles.x); T cp = cos(angles.y); T sp = sin(angles.y); T cb = cos(angles.z); T sb = sin(angles.z); value[0][0] = ch * cb + sh * sp * sb; value[0][1] = sb * cp; value[0][2] = -sh * cb + ch * sp * sb; value[1][0] = -ch * sb + sh * sp * cb; value[1][1] = cb * cp; value[1][2] = sb * sh + ch * sp * cb; value[2][0] = sh * cp; value[2][1] = -sp; value[2][2] = ch * cp; } */ ////////////////////////////////////////////////////////////// // mat3 conversions /* template <typename T> inline tmat3x3<T>::tmat3x3(const tquat<T> & q) { this->value[0][0] = 1 - 2 * q.y * q.y - 2 * q.z * q.z; this->value[0][1] = 2 * q.x * q.y + 2 * q.w * q.z; this->value[0][2] = 2 * q.x * q.z - 2 * q.w * q.y; this->value[1][0] = 2 * q.x * q.y - 2 * q.w * q.z; this->value[1][1] = 1 - 2 * q.x * q.x - 2 * q.z * q.z; this->value[1][2] = 2 * q.y * q.z + 2 * q.w * q.x; this->value[2][0] = 2 * q.x * q.z + 2 * q.w * q.y; this->value[2][1] = 2 * q.y * q.z - 2 * q.w * q.x; this->value[2][2] = 1 - 2 * q.x * q.x - 2 * q.y * q.y; } */ ////////////////////////////////////////////////////////////// // mat3 operators template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator=(const tmat3x3<T>& m) { this->value[0] = m[0]; this->value[1] = m[1]; this->value[2] = m[2]; return *this; } template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator+= (const T & s) { this->value[0] += s; this->value[1] += s; this->value[2] += s; return *this; } template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator+= (const tmat3x3<T>& m) { this->value[0] += m[0]; this->value[1] += m[1]; this->value[2] += m[2]; return *this; } template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator-= (const T & s) { this->value[0] -= s; this->value[1] -= s; this->value[2] -= s; return *this; } template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator-= (const tmat3x3<T>& m) { this->value[0] -= m[0]; this->value[1] -= m[1]; this->value[2] -= m[2]; return *this; } template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator*= (const T & s) { this->value[0] *= s; this->value[1] *= s; this->value[2] *= s; return *this; } template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator*= (const tmat3x3<T>& m) { return (*this = *this * m); } template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator/= (const T & s) { this->value[0] /= s; this->value[1] /= s; this->value[2] /= s; return *this; } template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator/= (const tmat3x3<T>& m) { return (*this = *this / m); } template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator++ () { this->value[0]++; this->value[1]++; this->value[2]++; return *this; } template <typename T> inline tmat3x3<T>& tmat3x3<T>::operator-- () { this->value[0]--; this->value[1]--; this->value[2]--; return *this; } template <typename T> inline tmat3x3<T> tmat3x3<T>::_inverse() const { T S00 = value[0][0]; T S01 = value[0][1]; T S02 = value[0][2]; T S10 = value[1][0]; T S11 = value[1][1]; T S12 = value[1][2]; T S20 = value[2][0]; T S21 = value[2][1]; T S22 = value[2][2]; tmat3x3<T> Inverse( + (S11 * S22 - S21 * S12), - (S10 * S22 - S20 * S12), + (S10 * S21 - S20 * S11), - (S01 * S22 - S21 * S02), + (S00 * S22 - S20 * S02), - (S00 * S21 - S20 * S01), + (S01 * S12 - S11 * S02), - (S00 * S12 - S10 * S02), + (S00 * S11 - S10 * S01)); T Determinant = S00 * (S11 * S22 - S21 * S12) - S10 * (S01 * S22 - S21 * S02) + S20 * (S01 * S12 - S11 * S02); Inverse /= Determinant; return Inverse; } ////////////////////////////////////////////////////////////// // Binary operators template <typename T> inline tmat3x3<T> operator+ (const tmat3x3<T>& m, const T & s) { return tmat3x3<T>( m[0] + s, m[1] + s, m[2] + s); } template <typename T> inline tmat3x3<T> operator+ (const T & s, const tmat3x3<T>& m) { return tmat3x3<T>( m[0] + s, m[1] + s, m[2] + s); } //template <typename T> //inline tvec3<T> operator+ (const tmat3x3<T>& m, const tvec3<T>& v) //{ //} //template <typename T> //inline tvec3<T> operator+ (const tvec3<T>& v, const tmat3x3<T>& m) //{ //} template <typename T> inline tmat3x3<T> operator+ (const tmat3x3<T>& m1, const tmat3x3<T>& m2) { return tmat3x3<T>( m1[0] + m2[0], m1[1] + m2[1], m1[2] + m2[2]); } template <typename T> inline tmat3x3<T> operator- (const tmat3x3<T>& m, const T & s) { return tmat3x3<T>( m[0] - s, m[1] - s, m[2] - s); } template <typename T> inline tmat3x3<T> operator- (const T & s, const tmat3x3<T>& m) { return tmat3x3<T>( s - m[0], s - m[1], s - m[2]); } //template <typename T> //inline detail::tvec3<T> operator- (const tmat3x3<T>& m, const detail::tvec3<T>& v) //{ //} //template <typename T> //inline detail::tvec3<T> operator- (const detail::tvec3<T>& v, const tmat3x3<T>& m) //{ //} template <typename T> inline tmat3x3<T> operator- (const tmat3x3<T>& m1, const tmat3x3<T>& m2) { return tmat3x3<T>( m1[0] - m2[0], m1[1] - m2[1], m1[2] - m2[2]); } template <typename T> inline tmat3x3<T> operator* (const tmat3x3<T>& m, const T & s) { return tmat3x3<T>( m[0] * s, m[1] * s, m[2] * s); } template <typename T> inline tmat3x3<T> operator* (const T & s, const tmat3x3<T>& m) { return tmat3x3<T>( m[0] * s, m[1] * s, m[2] * s); } template <typename T> inline detail::tvec3<T> operator* (const tmat3x3<T>& m, const detail::tvec3<T>& v) { return detail::tvec3<T>( m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z, m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z, m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z); } template <typename T> inline detail::tvec3<T> operator* (const detail::tvec3<T>& v, const tmat3x3<T>& m) { return detail::tvec3<T>( m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z, m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z, m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z); } template <typename T> inline tmat3x3<T> operator* (const tmat3x3<T>& m1, const tmat3x3<T>& m2) { const T SrcA00 = m1[0][0]; const T SrcA01 = m1[0][1]; const T SrcA02 = m1[0][2]; const T SrcA10 = m1[1][0]; const T SrcA11 = m1[1][1]; const T SrcA12 = m1[1][2]; const T SrcA20 = m1[2][0]; const T SrcA21 = m1[2][1]; const T SrcA22 = m1[2][2]; const T SrcB00 = m2[0][0]; const T SrcB01 = m2[0][1]; const T SrcB02 = m2[0][2]; const T SrcB10 = m2[1][0]; const T SrcB11 = m2[1][1]; const T SrcB12 = m2[1][2]; const T SrcB20 = m2[2][0]; const T SrcB21 = m2[2][1]; const T SrcB22 = m2[2][2]; tmat3x3<T> Result; Result[0][0] = SrcA00 * SrcB00 + SrcA10 * SrcB01 + SrcA20 * SrcB02; Result[0][1] = SrcA01 * SrcB00 + SrcA11 * SrcB01 + SrcA21 * SrcB02; Result[0][2] = SrcA02 * SrcB00 + SrcA12 * SrcB01 + SrcA22 * SrcB02; Result[1][0] = SrcA00 * SrcB10 + SrcA10 * SrcB11 + SrcA20 * SrcB12; Result[1][1] = SrcA01 * SrcB10 + SrcA11 * SrcB11 + SrcA21 * SrcB12; Result[1][2] = SrcA02 * SrcB10 + SrcA12 * SrcB11 + SrcA22 * SrcB12; Result[2][0] = SrcA00 * SrcB20 + SrcA10 * SrcB21 + SrcA20 * SrcB22; Result[2][1] = SrcA01 * SrcB20 + SrcA11 * SrcB21 + SrcA21 * SrcB22; Result[2][2] = SrcA02 * SrcB20 + SrcA12 * SrcB21 + SrcA22 * SrcB22; return Result; } template <typename T> inline tmat3x3<T> operator/ (const tmat3x3<T>& m, const T & s) { return tmat3x3<T>( m[0] / s, m[1] / s, m[2] / s); } template <typename T> inline tmat3x3<T> operator/ (const T & s, const tmat3x3<T>& m) { return tmat3x3<T>( s / m[0], s / m[1], s / m[2]); } template <typename T> inline detail::tvec3<T> operator/ ( tmat3x3<T> const & m, tvec3<T> const & v ) { return m._inverse() * v; } template <typename T> inline detail::tvec3<T> operator/ ( tvec3<T> const & v, tmat3x3<T> const & m ) { return v * m._inverse(); } template <typename T> inline tmat3x3<T> operator/ ( tmat3x3<T> const & m1, tmat3x3<T> const & m2 ) { return m1 * m2._inverse(); } // Unary constant operators template <typename valType> inline tmat3x3<valType> const operator- ( tmat3x3<valType> const & m ) { return tmat3x3<valType>( -m[0], -m[1], -m[2]); } template <typename valType> inline tmat3x3<valType> const operator++ ( tmat3x3<valType> const & m, int ) { return tmat3x3<valType>( m[0] + valType(1), m[1] + valType(1), m[2] + valType(1)); } template <typename valType> inline tmat3x3<valType> const operator-- ( tmat3x3<valType> const & m, int ) { return tmat3x3<valType>( m[0] - valType(1), m[1] - valType(1), m[2] - valType(1)); } } //namespace detail } //namespace glm
true
c15eca2d816f57d02d03def26b61cf8e961f6eac
C++
ChaoXs08201991/Information-Theory-Source-Coding
/C++ Source Code/Shannon Fano/fano.h
UTF-8
7,784
3.1875
3
[]
no_license
#include <iostream> #include <vector> #include <fstream> #include <algorithm> using namespace std; class Fano { public: struct FanoNode { unsigned char value; // 字符 struct FanoNode *Lchild = NULL; //左孩子 struct FanoNode *Rchild = NULL; //右孩子 }; private: struct CountVector { unsigned char value; int frequency = 0; struct FanoNode *nodeAddress = NULL; }; private: struct FanoCode { unsigned char value; int frequency; string code; int codelen; }; private: static bool mysortfunction(CountVector A, CountVector B) { //排序函数 return A.frequency > B.frequency; } public: FanoNode *root; //存储树的结构 string fileAddress; long int NumOfChar; vector<CountVector> charFrequency; //字符频率 vector<FanoCode> FanoCodeVec; //存储Fano码, 包括码长,码字 Fano(); void count(); void open(string add); void CreateTree(vector<CountVector> charFrequency, FanoNode *rootNode); void GetFanoCode(FanoNode* root, int depth); void WriteCode(vector<FanoCode> HFCode); void Decode(string sourcefile, string dstfile); private: void splitVec(vector<CountVector> charFr, vector<CountVector> &charFr1, vector<CountVector> &charFr2); }; Fano::Fano() { NumOfChar = 0; } void Fano::open(string add) { fileAddress = add; } void Fano::count() { ifstream readfile; readfile.open(fileAddress, ios::in | ios::binary); unsigned char *now = new unsigned char; //´æ´¢µ±Ç°¶ÁÈ¡µ½µÄ×Ö·û while (!readfile.eof()) { CountVector *presentChar = new CountVector; //¶ÁÈ¡µ½µÄ×Ö·ûÐÅÏ¢ readfile.read((char*)now, sizeof(unsigned char)); int flag = 0; //±êÖ¾ÊÇ·ñÊÇгöÏÖµÄ×Ö·û for (int i = 0; i < charFrequency.size(); i++) { if (*now == charFrequency[i].value) { charFrequency[i].frequency++; NumOfChar++; flag = 1; } } if (flag == 0) { presentChar->value = *now; presentChar->frequency++; NumOfChar++; charFrequency.push_back(*presentChar); } } readfile.close(); } void Fano::CreateTree(vector<CountVector> charFr, FanoNode *rootNode) { vector<CountVector> buildtree = charFr; if (buildtree.size() == 1) { //root->Lchild = new FanoNode; //root->Rchild = new FanoNode; rootNode->Lchild = NULL; rootNode->Rchild = NULL; rootNode->value = buildtree[0].value; } else { sort(buildtree.begin(), buildtree.end(), mysortfunction); vector<CountVector> charFr1, charFr2; splitVec(buildtree, charFr1, charFr2); rootNode->Lchild = new FanoNode; CreateTree(charFr1, rootNode->Lchild); rootNode->Rchild = new FanoNode; CreateTree(charFr2, rootNode->Rchild); rootNode->value = 0; } return; } void Fano::splitVec(vector<CountVector> charFr, vector<CountVector> &charFr1, vector<CountVector> &charFr2) { int length = charFr.size(); if (length == 1) { cout << "拆分的数组长度不够" << endl; } long int NumOfCharf = 0; for (int i = 0; i < length; i++) { NumOfCharf = NumOfCharf + charFr[i].frequency; } double ratio = 0; int splitIndex = 0; //切割处的索引 for (int i = 0; i < length; i++) { ratio = ratio + double(charFr[i].frequency / NumOfCharf); if (ratio > 0.5) { if (i > 0) { splitIndex = i - 1; break; } else { splitIndex = i; break; } } } for (int i = 0; i < splitIndex + 1; i++) { charFr1.push_back(charFr[i]); } for (int i = splitIndex + 1; i < charFr.size(); i++) { charFr2.push_back(charFr[i]); } } void Fano::GetFanoCode(FanoNode* root, int depth) { static char code[512]; //ÅжÏ×ó¶ù×Ó if (root->Lchild != NULL) { code[depth] = '0'; code[depth + 1] = '\0'; GetFanoCode(root->Lchild, depth + 1); } if (root->Rchild != NULL) { code[depth] = '1'; code[depth + 1] = '\0'; GetFanoCode(root->Rchild, depth + 1); } else { FanoCode insertCode; int codelength = 0; for (int i = 0; i < charFrequency.size(); i++) { if (root->value == charFrequency[i].value) { insertCode.code = code; insertCode.value = charFrequency[i].value; insertCode.frequency = charFrequency[i].frequency; } } for (int j = 0; code[j] != '\0'; j++) { codelength++; } insertCode.codelen = codelength; FanoCodeVec.push_back(insertCode); } } void Fano::WriteCode(vector<FanoCode> HFCode) { //读取文件并写入数据 int codeNum = HFCode.size(); string address = fileAddress; ofstream writecode; ifstream read; read.open(address, ios::in | ios::binary); //以二进制方式读取 writecode.open(address + ".dada", ios::out | ios::binary); //以二进制方式写入 unsigned char *now = new unsigned char; //存储字符值 unsigned char save = 0; //保存当前字符 int len = 0; long int totalLen = 0; //总长 int last; //结尾字符长度 for (int i = 0; i < HFCode.size(); i++) { totalLen = totalLen + HFCode[i].codelen; } last = totalLen % 8; // char head = '>'; writecode.write((char*)&head, sizeof(char)); writecode.write((char *)&codeNum, sizeof(int)); writecode.write((char *)& last, sizeof(int)); //дÈë×îºóÒ»´ÎдÈëµÄλÊý for (int i = 0; i < codeNum; i++) { //дÈë×Ö·ûÖµºÍƵÊý writecode.write((char*)&HFCode[i].value, sizeof(HFCode[i].value)); writecode.write((char*)&HFCode[i].frequency, sizeof(HFCode[i].frequency)); } //read.read((char*)now, 1); read.read((char*)now, sizeof(unsigned char)); while (!read.eof()) { int flag = 0; for (int i = 0; i < HFCode.size(); i++) { if (*now == HFCode[i].value) { flag = 1; for (int j = 0; j < HFCode[i].codelen; j++) { if (len != 0) save = save << 1; save = save | (HFCode[i].code[j] - '0'); len++; if (len == 8) { writecode.write((char *)&save, sizeof(unsigned char)); save = 0; len = 0; } } } } if (flag == 0) { cout << *now << "没有找到该字符属性" << endl; } read.read((char*)now, sizeof(unsigned char)); //*now = read.get(); } if (len != 0) { writecode.write((char*)&save, sizeof(unsigned char)); } read.close(); writecode.close(); } void Fano::Decode(string sourcefile, string dstfile) { ifstream read; ofstream write; vector<CountVector> arr; unsigned char now; //读取的当前字符 int last = 0; //最后一次读取的位数 int n; //字符种数 read.open(sourcefile, ios::in | ios::binary); //读取解码文件 write.open(dstfile, ios::out | ios::binary); //打开解码后的文件 read.read((char*)&now, sizeof(now)); if (!(now == '>')) { cout << "该文件的Huffman编码格式不正确" << endl << endl; read.close(); return; } read.read((char*)&n, sizeof(int)); read.read((char*)&last, sizeof(last)); for (int i = 0; i < n; i++) { CountVector *insert = new CountVector; read.read((char*)&(insert->value), sizeof(unsigned char)); read.read((char*)&(insert->frequency), sizeof(int)); arr.push_back(*insert); } this->root = new FanoNode; CreateTree(arr, root); GetFanoCode(root, 0); FanoNode *pNow = root; unsigned char *temp = new unsigned char; //每次读一个字节 read.read((char*)temp, sizeof(unsigned char)); while (!read.eof()) { unsigned char *ifLast = new unsigned char; //用于判断是否读到文件末尾 read.read((char*)ifLast, sizeof(unsigned char)); int i; if (read.eof()) { i = last - 1; } else { i = 7; } for (; i >= 0; i--) { if ((*temp >> i & 1) == 0) //向右移动7位判断读出的是0 还是1 pNow = pNow->Lchild; else pNow = pNow->Rchild; if (pNow->Lchild == NULL && pNow->Rchild == NULL) { write.write((char*)&(pNow->value), sizeof(unsigned char)); pNow = root; } } temp = ifLast; } read.close(); write.close(); }
true
8a4d3d3f9293183128ec088d6c419c9784aaa003
C++
Dakimakura/Homework-ICS-2
/1337 [BA1002] The Account class/Latest Submission/source.h
UTF-8
626
4.03125
4
[]
no_license
class Account{ private: int id; double balance, rate; public: Account(){ id = 0; balance = 0; rate = 0; } Account(int a, double b, double c){ id = a; balance = b; rate = c; } double getMonthlyInterestRate(){ return rate/12; } void setId(int a){ id = a; } void setBalance(double b){ balance = b; } void setAnnualInterestRate(double c){ rate = c; } int getId(){ return id; } double getBalance(){ return balance; } };
true
7056d0ed09345494a36c4aade6a699255394a779
C++
ZSShen/IntrospectiveProgramming
/LintCode/Foundation/DataStructures_II/139_Subarray_Sum_Closest.cpp
UTF-8
1,678
3.453125
3
[]
no_license
class Solution { public: /* * @param nums: A list of integers * @return: A list of integers includes the index of the first number and the index of the last number */ vector<int> subarraySumClosest(vector<int> &nums) { // write your code here int size = nums.size(); if (size == 0) { return {-1, -1}; } if (size == 1) { return {0, 0}; } std::vector<std::pair<int, int>> records; records.push_back(std::make_pair(nums[0], 0)); int sum = nums[0]; for (int i = 1 ; i < size ; ++i) { sum += nums[i]; records.push_back(std::make_pair(sum, i)); } std::sort(records.begin(), records.end(), [] (const std::pair<int, int>& src, const std::pair<int, int>& dst) -> bool { return src.first < dst.first; }); int diff = INT_MAX; int bgn, end; for (int i = 1 ; i < size ; ++i) { int temp = std::abs(records[i].first - records[i - 1].first); if (temp < diff) { bgn = i - 1; end = i; diff = temp; } } std::vector<int> ans; ans.push_back(records[bgn].second); ans.push_back(records[end].second); std::sort(ans.begin(), ans.end()); ++ans[0]; return ans; /** * -3, 1, 1, -3, 5 * * (-3, 0) (-4, 3) * (-2, 1) (-3, 0) (1 3) * (-1, 2) => (-2, 1) * (-4, 3) (-1, 2) * ( 1, 4) ( 1, 4) */ } };
true
94b036029e3f79121f3ac7a551282949475e5ca7
C++
FerreyJ/estructuras-repetitivas-en-cpp
/ejercicio 7 seccion 4 Joseph.cpp
UTF-8
348
3.546875
4
[]
no_license
/*7. Escriba un programa que calcule el valor de: 1+2+3+...+n.*/ #include<iostream> #include<conio.h> using namespace std; int main(){ int n,suma=0; cout<<"Introduzca el valor del ultimo numero a sumar: ";cin>>n; for(int i=1;i<=n;i++){ suma+=i; } cout<<"\nLa suma total de "<<n<<" numeros es: "<<suma<<endl; getch(); return 0; }
true
954545fe9516860596d9edabf552739b94093ce8
C++
ming5656/uva
/00271.cpp
UTF-8
1,018
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { char input[1024]; while(cin>>input) { int len=strlen(input),num(0); bool ans(true); for(int i=len-1;i>=0;i--) { if(input[i]>='p'&&input[i]<='z') { num++; } else if(input[i]=='N') { if(!num) { ans=false; break; } } else if(input[i]=='I'||input[i]=='C'||input[i]=='D'||input[i]=='E') { if(num<2) { ans=false; break; } num--; } else { ans=false; break; } } if(ans&&num==1) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
true
71b9d14923e78270720cff1d6597845a8e110d2e
C++
SpectrumIM/spectrum2
/include/transport/ThreadPool.h
UTF-8
2,016
2.890625
3
[ "BSL-1.0" ]
permissive
#pragma once #include <boost/bind.hpp> #include <boost/signals2.hpp> #include <boost/thread.hpp> #include <boost/thread/mutex.hpp> #include <queue> #include <iostream> #include "Swiften/EventLoop/EventLoop.h" namespace Transport { /* * Thread serves as a base class for any code that has to be excuted as a thread * by the ThreadPool class. The run method defines the code that has to be run * as a theard. For example, code in run could be sendinga request to a server * waiting for the response and storing the response. When the thread finishes * execution, the ThreadPool invokes finalize where one could have the code necessary * to collect all the responses and release any resources. * * NOTE: The object of the Thread class must be valid (in scope) throughout the * execution of the thread. */ class Thread { int threadID; public: Thread() {} virtual ~Thread() {} virtual void run() = 0; virtual void finalize() {} int getThreadID() {return threadID;} void setThreadID(int tid) {threadID = tid;} }; /* * ThreadPool provides the interface to manage a pool of threads. It schedules jobs * on free threads and when the thread completes it automatically deletes the object * corresponding to a Thread. If free threads are not available, the requests are * added to a queue and scheduled later when threads become available. */ class ThreadPool { const int MAX_THREADS; int activeThreads; std::queue<int> freeThreads; std::queue<Thread*> requestQueue; boost::thread **worker; boost::mutex count_lock; boost::mutex pool_lock; boost::mutex criticalregion; Swift::EventLoop *loop; boost::signals2::signal < void () > onWorkerAvailable; public: ThreadPool(Swift::EventLoop *loop, int maxthreads); ~ThreadPool(); void runAsThread(Thread *t); int getActiveThreadCount(); void updateActiveThreadCount(int k); void cleandUp(Thread *, int); void scheduleFromQueue(); int getFreeThread(); void releaseThread(int i); void workerBody(Thread *t, int wid); }; }
true
b68eb5ced91c571dcd01775137a3fc104954abc4
C++
stefankurz1/pepper_emotion
/emotional_system/theatre_bot/src/Parameters/SpeakParameters/Speak.h
UTF-8
641
2.546875
3
[]
no_license
/////////////////////////////////////////////////////////// // Speak.h // Implementation of the Class Speak // Created on: 04-dic-2014 04:42:42 p.m. // Original author: julian /////////////////////////////////////////////////////////// #if !defined(SPEAK_H_) #define SPEAK_H_ #include "../Parameter.h" /** * I don't know a lot of this part, but I know that it could be have many things * as pitch, etc. */ class Speak : public Parameter { public: Speak(); virtual ~Speak(); void setText(std::string text); std::string getText(); private: std::string text; }; #endif // !defined(SPEAK_H_)
true
beab033f0dcb4ed184d77a23c80c4501bed420f2
C++
joydeeps/boost.asio
/network_programming/threaded_async_client_server/threaded_async_client_server---Example-1---Version-1/my_connection.hpp
UTF-8
1,199
2.5625
3
[]
no_license
#include <boost/asio.hpp> #include <boost/shared_ptr.hpp> #include <boost/thread.hpp> class my_connection { public: my_connection() // constructor { close = false; // create new socket into which to receive the new connection this->socket = boost::shared_ptr<boost::asio::ip::tcp::socket>( new boost::asio::ip::tcp::socket(this->io_service) ); } // we must have a new io_service for EVERY THREAD! boost::asio::io_service io_service; // where we receive the accepted socket and endpoint boost::shared_ptr<boost::asio::ip::tcp::socket> socket; boost::asio::ip::tcp::endpoint endpoint; // keep track of the thread for this connection boost::shared_ptr<boost::thread> thread; // keep track of the acceptor io_service so we can call stop() on it! boost::asio::io_service *master_io_service; // boolean to indicate a desire to kill this connection bool close; // NOTE: you can add other variables here that store connection-specific // data, such as received HTML headers, or logged in username, or whatever // else you want to keep track of over a connection };
true
98615058ade55d967538e67de89b2db02225f6d8
C++
zhengweifu2018/fungame
/src/fungame/math/Matrix4.cpp
UTF-8
6,329
2.671875
3
[]
no_license
// // Matrix4.cpp // fungame_libs // // Created by zwf on 11/12/2015. // Copyright © 2015 com.zwf. All rights reserved. // #include "fungame/math/Matrix4.h" #include "fungame/math/Vector3.h" #include <math.h> namespace fungame { namespace math { Matrix4::Matrix4() { identity(); } Matrix4& Matrix4::set(float n11, float n12, float n13, float n14, float n21, float n22, float n23, float n24, float n31, float n32, float n33, float n34, float n41, float n42, float n43, float n44) { elements[0] = n11; elements[4] = n12; elements[8] = n13; elements[12] = n14; elements[1] = n21; elements[5] = n22; elements[9] = n23; elements[13] = n24; elements[2] = n31; elements[6] = n32; elements[10] = n33; elements[14] = n34; elements[3] = n41; elements[7] = n42; elements[11] = n43; elements[15] = n44; return *this; } Matrix4& Matrix4::identity() { set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); return *this; } Matrix4& Matrix4::copy(const Matrix4 &m4) { std::copy_n(m4.elements, 16, elements); return *this; } Matrix4 Matrix4::clone() { Matrix4 m4; m4.copy(*this); return m4; } Matrix4& Matrix4::multiply(const Matrix4 &m4) { auto& ae = elements; const auto& be = m4.elements; float a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; float a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; float a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; float a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; float b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; float b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; float b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; float b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; ae[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; ae[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; ae[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; ae[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; ae[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; ae[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; ae[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; ae[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; ae[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; ae[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; ae[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; ae[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; ae[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; ae[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; ae[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; ae[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; return *this; } Matrix4& Matrix4::operator*=(const Matrix4 &right) { return multiply(right); } Matrix4& operator*(Matrix4 &left, const Matrix4 &right) { return left.multiply(right); } Matrix4& makeTranslate(Matrix4 &m4, const Vector3 &position) { m4.set(1, 0, 0, position.x, 0, 1, 0, position.y, 0, 0, 1, position.z, 0, 0, 0, 1); return m4; } Matrix4& makeRotate(Matrix4 &m4, float angle, const Vector3 &axis) { float c = cos(angle); float s = sin(angle); float t = 1 - c; float x = axis.x, y = axis.y, z = axis.z; float tx = t * x, ty = t * y; m4.set( tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1); return m4; } Matrix4& makeScale(Matrix4 &m4, const Vector3 &scale) { m4.set(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1); return m4; } Matrix4& makeOrthographic(Matrix4 &m4, float left, float right, float top, float bottom, float near, float far) { float RsubtractL = right - left; float RaddL = right + left; float TsubtractB = top - bottom; float TaddB = top + bottom; float FsubtractN = far - near; float FaddN = far + near; m4.set(2/RsubtractL, 0, 0, -RaddL/RsubtractL, 0, 2/TsubtractB, 0, -TaddB/TsubtractB, 0, 0, -2/FsubtractN, -FaddN/FsubtractN, 0, 0, 0, 1); return m4; } Matrix4& makePerspective(Matrix4 &m4, float fov, float aspect, float far, float near) { float t = tan(fov/2); float FSN = far - near; float FAN = far + near; float FMN_2 = 2 * far * near; m4.set(1/(aspect * t), 0, 0, 0, 0, 1/t, 0, 0, 0, 0, -FAN/FSN, FMN_2/FSN, 0, 0, -1, 0); return m4; } std::ostream& operator<<(std::ostream &ostream, const Matrix4 &m4) { ostream << "Matrix4(" << m4.elements[0] << ", " << m4.elements[1] << ", " << m4.elements[2] << ", " << m4.elements[3] << ", " << m4.elements[4] << ", " << m4.elements[5] << ", " << m4.elements[6] << ", " << m4.elements[7] << ", " << m4.elements[8] << ", " << m4.elements[9] << ", " << m4.elements[10] << ", " << m4.elements[11] << ", " << m4.elements[12] << ", " << m4.elements[13] << ", " << m4.elements[14] << ", " << m4.elements[15] << ")"; return ostream; } }}
true
da6bf02117ef907660462b40b74acc63723ad267
C++
MatteoSalvalaggio/Cplusplus_exercises
/practical_7_exercise_2.cpp
UTF-8
1,513
3.78125
4
[]
no_license
#include <iostream> using namespace std; template <typename T> class StackI { public: virtual void push(T t) = 0; virtual void pop () =0; virtual T top() = 0; virtual bool isEmpty() = 0; virtual void print() = 0; }; template <typename T> class Stack:StackI<T>{ protected: int firstindex; int elements; int size; T a []; public: Stack(){ a[20]; firstindex=0; elements = 0; size=20; } Stack(int n) { a[n]; firstindex =0; elements = 0; size=n; } void push(T t){ if (elements<size){ a[firstindex++]=t; elements++; } else cout << "The stack is full" << endl; } void pop(){ if(elements==0) cout << "The stack is empty" << endl; else { firstindex--; elements--; } } T top() { if(elements>0){ return a[firstindex]; } else cout << "The stack is empty" << endl; } void print(){ if (elements==0){ cout << "The stack is empty"<<endl; } else { cout << "["; for(int i = firstindex -1; i >=0; i--){ cout << a[i]; } cout << "]" <<endl; } } bool isEmpty() { return (elements ==0)? true:false; } }; int main () { Stack<int> a = Stack<int>(4); a.print(); a.push(7); a.push(5); a.push(8); a.push(6); a.print(); a.pop(); a.print(); a.push(7); a.print(); a.pop(); a.print(); a.pop(); a.print(); a.pop(); a.print(); a.pop(); a.print(); return 0; }
true
5a63e9228339245d38b57e6f4567027142b82326
C++
janranz/college
/CS311/studentRecordsDB/menu.hpp
UTF-8
880
2.9375
3
[]
no_license
#pragma once #include <fstream> #include <iostream> #include <vector> #include <algorithm> #include "student.hpp" using std::string; using std::vector; using std::ofstream; using std::cout; using std::cin; using std::endl; using std::sort; class Menu { private: bool yayNay = false; // general I/O int selector = 0; // switch-case string userBuffer; int userToInt = 0; ofstream dump; vector<Student*>_vf; int DEX = -1; string menText = "\n\nDatabase Main Menu:\n\n1.Add New Student\n2.Remove Student\n3.Search Student Record\n4.List All Students\n5.Save Student Records to File\n6. Exit\n\nEnter Choice: "; public: Menu(vector<Student*>&vf); ~Menu(); void showMenu(); void addStudent(); void removeStudent(); void searchStudent(); void listStudent(); void dumpStudent(); };
true
75d884cb577ba3944caaab0b95cd0476b05a9210
C++
BoneLord/CreatorCharacterDND4
/character/characteristics/deity/typeDeity/ioun/ioun.cpp
UTF-8
759
2.640625
3
[]
no_license
#include "character/characteristics/deity/typeDeity/ioun/ioun.h" Ioun * Ioun::pIoun = 0; IounDestroyer Ioun::destroyer; Ioun::Ioun() { mAlignment = unaligned; } Ioun::Ioun(const Ioun& b) { } Ioun& Ioun::operator=(const Ioun& b) { return *this; } Ioun::~Ioun() { } Ioun& Ioun::getInstance() { if (!pIoun) { pIoun = new Ioun(); destroyer.initialize(pIoun); } return *pIoun; } bool Ioun::isCompatibleAlignment(Alignment alignment) const { if (mAlignment == alignment || alignment == good || alignment == evil) { return true; } return false; } const char * Ioun::toString() const { char name[] = "Ioun"; char *pName = new char[strlen(name) + 1]; strcpy(pName, name); return pName; }
true
931f4279c08e3cf6a5d6f840c57458a94afcf275
C++
eracs/toy_jvm
/src/classpath/DirClasspathEntry.cpp
UTF-8
1,115
2.671875
3
[ "MIT" ]
permissive
#include <utility> #include "DirClasspathEntry.h" #include "../file_reader/file_reader.h" #include "../utils/string_utils.h" #include "spdlog/spdlog.h" using namespace std; using namespace string_util; DirClasspathEntry::~DirClasspathEntry() { } DirClasspathEntry::DirClasspathEntry(std::string dirPath) : dirPath(std::move(dirPath)) {} uint8 *DirClasspathEntry::readClass(const std::string &className, size_t &length) const { auto logger = spdlog::get("Logger"); logger->debug("From dir readClass, className={0}, path={1} ", className, this->dirPath); //convert classname to filepath string classFilePath(className); auto entryName = replace_all(classFilePath, get_dot_separator(), get_path_separator()); entryName = entryName + get_class_file_ext(); string fileName = this->dirPath + get_path_separator() + entryName; auto data = readFileEntry(fileName, length); if (length == 0) { return nullptr; } logger->debug("ReadClass finished, className={0}, path={1}, dataSize={2}", className, this->dirPath, length); return data; }
true
2b972b5b46adf9074dd0742dde5968ba8f422445
C++
JuanGonzalez9/Cucurucho
/src/EscuchadorDeAcciones.cpp
UTF-8
2,390
2.859375
3
[]
no_license
/* * EscuchadorDeAcciones.cpp * * Created on: Oct 15, 2018 * Author: juan */ #include "EscuchadorDeAcciones.h" EscuchadorDeAcciones::EscuchadorDeAcciones() { jugando = true; if (SDL_Init (SDL_INIT_VIDEO) < 0) { cout<<"No se pudo inicializar SDL"<<endl; jugando = false; } } string EscuchadorDeAcciones::obtenerAcciones(){ SDL_PumpEvents(); acciones.reset(); const Uint8 *state = SDL_GetKeyboardState(NULL); if(apretandoDerecha(state)){ acciones.set(Constantes::derecha); //pone el bit 0 en 1 indicando que se esta apretando la tecla derecha } if(apretandoIzquierda(state)){ acciones.set(Constantes::izquierda); } if(apretandoArriba(state)){ acciones.set(Constantes::arriba); } if(apretandoAbajo(state)){ acciones.set(Constantes::abajo); } if(apretandoDisparo(state)){ acciones.set(Constantes::disparo); } if(apretandoSalto(state)){ acciones.set(Constantes::salto); } if(apretandoAgacharse(state)){ acciones.set(Constantes::agacharse); } if(apretandoNivel2(state)){ acciones.set(Constantes::nivel2); } if(apretandoNivel3(state)){ acciones.set(Constantes::nivel3); } return acciones.to_string(); } bool EscuchadorDeAcciones::enAccion(){ return jugando; } bool EscuchadorDeAcciones::apretandoDerecha(const Uint8* state){ //controla tambien que no este la tecla izquierda return (state[SDL_SCANCODE_RIGHT] && !state[SDL_SCANCODE_LEFT]); } bool EscuchadorDeAcciones::apretandoIzquierda(const Uint8* state){ //controla tambien que no este la tecla derecha return (state[SDL_SCANCODE_LEFT] && !state[SDL_SCANCODE_RIGHT]); } bool EscuchadorDeAcciones::apretandoArriba(const Uint8* state){ return state[SDL_SCANCODE_UP]; } bool EscuchadorDeAcciones::apretandoDisparo(const Uint8* state){ return state[SDL_SCANCODE_Z]; } bool EscuchadorDeAcciones::apretandoSalto(const Uint8* state){ return state[SDL_SCANCODE_X]; } bool EscuchadorDeAcciones::apretandoAbajo(const Uint8* state){ return state[SDL_SCANCODE_DOWN]; } bool EscuchadorDeAcciones::apretandoAgacharse(const Uint8* state){ return state[SDL_SCANCODE_C]; } //Cambia de nivel bool EscuchadorDeAcciones::apretandoNivel2(const Uint8* state){ return state[SDL_SCANCODE_Q]; } //sube al jugador bool EscuchadorDeAcciones::apretandoNivel3(const Uint8* state){ return state[SDL_SCANCODE_W]; } EscuchadorDeAcciones::~EscuchadorDeAcciones() { SDL_Quit(); }
true
b2b0484f105ca68b182b8d74601a1d040a307d9b
C++
lsa-src/ArduinoBible
/본문소스/CH_27_18/CH_27_18.ino
UTF-8
1,193
3.0625
3
[]
no_license
#include <SPI.h> #define DELAY_BETWEEN_TRANSFER_US 100 // transfer 함수 사이 시간 간격 void setup (void) { SPI.begin (); // SPI 통신 초기화 Serial.begin(9600); } void loop (void) { uint8_t from_slave; // 슬레이브로부터의 수신 데이터 String receive_data = ""; // 수신 데이터 버퍼 // 안정적인 전송을 위해 전송 속도를 1MHz로 낮춤 SPI.beginTransaction( SPISettings(1000000, MSBFIRST, SPI_MODE0) ); digitalWrite(SS, LOW); // 슬레이브 선택 from_slave = SPI.transfer('$'); // 전송 시작 신호 전송 delayMicroseconds(DELAY_BETWEEN_TRANSFER_US); receive_data += (char)from_slave; for (int pos = 0; pos < 5; pos++) { // 5 자리 문자열로 변환된 정수 수신 from_slave = SPI.transfer(0); delayMicroseconds(DELAY_BETWEEN_TRANSFER_US); receive_data += (char)from_slave; } digitalWrite(SS, HIGH); // 슬레이브 선택 해제 SPI.endTransaction(); // 전송 종료 Serial.print("슬레이브 카운터 : ["); Serial.print(receive_data + "] "); Serial.println(receive_data.substring(1).toInt()); delay(2000); // 2초에 한 번 요청 }
true
225c510d307cf747e3dfedbf15990a4c12a55dd2
C++
cdcurtis/BioSystem
/Headers/Operations/Output.h
UTF-8
1,566
2.859375
3
[]
no_license
/* * Output.h * * Created on: Jun 2, 2017 * Author: chriscurtis */ #ifndef HEADERS_OPERATIONS_Output_H_ #define HEADERS_OPERATIONS_Output_H_ #include "Operation.h" #include <vector> namespace BioCoder { class Output:public BioCoder::Operation{ Container* __inputs; std::vector<Property*> __properties; bool isWaste; public: Output(Container* c1, bool isWaste=false){ this->__inputs = c1; this->isWaste = isWaste; } OPERATION_TYPE GetType(){ if(this->isWaste) return WASTE; return OUTPUT; } std::string toString(std::string buffer) { std::string ret=buffer + "\"OPERATION\" : {\n"; std::string buf = buffer + '\t'; ret += buf + "\"NAME\" : \"Output\"\n"; ret += buf + "\"ID\" :" + '0' /*getID*/+ "\n"; ret += buf + "\"CLASSIFICATION\" : \"OUTPUT\"\n"; ret += buf + "\"NAME\" : \"Output\"\n"; ret += buf + "\"INPUTS\" : [\n"; ret += buf + "\t{\n"; ret += buf + "\t\t" + "\"INPUT_TYPE\" : \"VARIABLE\",\n"; ret += __inputs->toString(buf + "\t\t"); ret += buf +"\t}"; if(this->__properties.size() > 0) { ret+=",\n"; for(int i = 0; i < this->__properties.size(); ++i){ Property* p = this->__properties.at(i); ret += buf + "\t{\n"; ret += buf + "\t\t" + "\"INPUT_TYPE\" : \"PROPERTY\",\n"; ret += p->toString(buf+"\t\t"); if(i < this->__properties.size()-1) ret += buf + "\t},\n"; else ret += buf + "\t}\n"; } } else ret += "\n"; ret += buf + "]\n"; ret += buffer +"}"; return ret; } }; } #endif /* HEADERS_OPERATIONS_FLUIDICOPERATION_H_ */
true
718eef7bb22f88e94ec5edf95624e85e2a187bdb
C++
Javanater/utilities
/src/utilities.cpp
UTF-8
2,468
2.84375
3
[]
no_license
/* * utilities.cpp * * Created on: Apr 15, 2016 * Author: Madison */ #include <utilities/utilities.hpp> #include <utilities/Monitor.hpp> #include <map> using namespace std; using boost::posix_time::ptime; using boost::posix_time::time_input_facet; using boost::posix_time::time_facet; using boost::gregorian::date; using boost::posix_time::time_duration; using boost::posix_time::seconds; namespace flabs { mutex sleepMonitorMutex; map<thread::id, Monitor> sleepMonitors; ptime epoch(date(1970, 1, 1)); ptime parseDateTime(string dateTime, string format, locale locale1) { locale locale2(locale1, new time_input_facet(format)); istringstream is(dateTime); is.imbue(locale2); ptime pt; is >> pt; return pt; } time_t secondsSinceEpoch(const ptime& pt) { time_duration diff = pt - epoch; return diff.ticks() / time_duration::rep_type::ticks_per_second; } ptime toPTime(const time_t& secondsSinceEpoch) { time_duration dur = seconds(secondsSinceEpoch); return epoch + dur; } time_t secondsSinceEpoch(string dateTime, string format, locale locale1) { return secondsSinceEpoch(parseDateTime(dateTime, format, locale1)); } time_t ticksSinceEpoch(const ptime& pt) { time_duration diff = pt - epoch; return diff.ticks(); } time_t ticksSinceEpoch(string dateTime, string format, locale locale1) { return ticksSinceEpoch(parseDateTime(dateTime, format, locale1)); } /** * %d - day of month zero padded * %m - month number, 0 padded, January=1 * %B - month full name * %b - month abr. * %a - day of week abr. * * http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.format_flags * * @param secondsSinceEpoch * @param format * @param locale1 * @return */ string formatTime(time_t secondsSinceEpoch, string format, locale locale1) { locale locale2(locale1, new time_facet(format.c_str())); ostringstream os; os.imbue(locale2);; ptime pt = toPTime(secondsSinceEpoch); os << pt; return os.str(); } void sleepMillis(uint64_t millis) { this_thread::sleep_for(chrono::milliseconds(millis)); } bool isleep(uint64_t millis) { Monitor* monitor; { unique_lock<mutex> lock(sleepMonitorMutex); monitor = &sleepMonitors[this_thread::get_id()]; } return monitor->wait(millis); } void interrupt(thread::id id) { Monitor* monitor; { unique_lock<mutex> lock(sleepMonitorMutex); monitor = &sleepMonitors[id]; } monitor->notifyAll(); } }
true
949ed4f9731f2588f1d16e9ed042581501e924bf
C++
msrai92/Linked-List-Addition-and-Multiplication
/hw1/main.cpp
UTF-8
1,696
3.21875
3
[]
no_license
// // main.cpp // hw1 // // Created by Manvir Rai on 6/8/17. // Copyright © 2017 Manvir Rai. All rights reserved. // #include <iostream> #include "ArgumentManager.h" #include "DoubleLinkedList.h" #include <fstream> int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: infinitearithmetic \"input=xyz.txt;digitsPerNode=<number>\"\n"; } ArgumentManager am(argc, argv); std::string filename = am.get("input"); int digitsPerNode = std::stoi(am.get("digitsPerNode")); std::ifstream ifs(filename.c_str()); std::string line; while (getline(ifs, line)){ std::string num1; std::string num2; char op; num1.clear(); num2.clear(); // replace op with space for (char& c : line) //this for loop was given by kaoji { if(!isdigit(c)){ op = c; c = ' '; break; } } std::stringstream ss(line); //now that operand is removed extract both numbers ss >> num1 >> num2; DoubleLinkedList l1(num1, digitsPerNode); // DoubleLinkedList(const std::string& num, int digitsPerNode) DoubleLinkedList l2(num2, digitsPerNode); DoubleLinkedList l(digitsPerNode); if(op == '+'){ l = l1+l2; //if operand is + add std::cout << num1 << op << num2 << "="; l.Print(); } else if(op=='*'){ l = l1*l2; std::cout << num1 << op << num2 << "="; l.Print(); //if operand is * mulitply } } return 0; }
true
3165910e1789afd80c687273082ae1c2f1f24366
C++
ebadusb/Common
/tools/config_parse/unit_test/test1/test1_main.cpp
UTF-8
32,564
2.859375
3
[]
no_license
// $Header$ // // Main program for config_parse unit test 1 // // $Log: test1_main.cpp $ // Revision 1.1 2005/05/11 15:15:03Z jl11312 // Initial revision // Revision 1.2 2005/01/24 16:01:26Z jl11312 // - updated for new version of configuration parse utility // Revision 1.1 2004/07/21 19:00:38Z jl11312 // Initial revision // #include <vxWorks.h> #include <unistd.h> #include <sys/stat.h> #include "test1.h" #include <iostream> #include <string> #include <fstream> const int MaxLineSize = 256; bool checkDouble(double d1, double d2) { double low; double high; if ( d2 < 0 ) { low = d2*1.00001; high = d2*0.99999; } else { low = d2*0.99999; high = d2*1.00001; } return ( d1 >= low && d1 <= high ); } // This operation will search for the override-user-config tag left in the config tool output // It will verify that the correct section and parameter contain the tag and then remove the tag // from the dat file so that the dat file read operation does not fail. bool checkUserConfigOverride(const char * fileName, const char * sectionName, const char * paramName) { bool retVal = false; const string overrideKey("@{override-user-config@}"); // Input File Stream used to read in the dat file contents std::ifstream inputFile(fileName, std::ios::in); // Output File Stream Used to write out the contents after the @{override-user-config@} tag is removed std::ofstream outFile("./temp.txt", std::ios::out); // temp string used for intermediate string operations during processing. string line; // Keep track of the last Section encountered while parsing the file string currentSection; // The last Parameter Name encountered while parsing string currentParam; // Verify that the dat file could be opened if ( inputFile.is_open() ) { // Loop over the dat file contents while (std::getline(inputFile, line) ) { try { // See if the line contains the '[' and ']' delimiters if (line.find('[') != string::npos && line.find(']') != string::npos) { size_t begin = line.find('[') + 1; size_t end = line.find(']') - begin; // Parse out just the section name of interest currentSection.assign( line.substr(begin, end) ); } } catch(...) { fprintf(stderr, "Caught Unknown exception trying to find the current section"); } try { // See if the current line contains the override tag if (line.find(overrideKey.c_str()) != string::npos) { // Grab the parameter name from in front of the '=' currentParam.assign(line.substr(0, line.find('='))); // See if the section and param being parsed match the expected Section/Param passed in // If they match the correct section and parameter contained the override tag if (!currentParam.compare(paramName)&& !currentSection.compare(sectionName)) { retVal = true; // Remove the override line.erase(line.find("@{"), overrideKey.length() ); } } } catch(...) { fprintf(stderr, "Caught Unknown exception trying to parse the param."); } // Copy the parsed line to the temp output file outFile << line << endl; } // Reset the File Pointer to the beginning of the file inputFile.seekg (0, ios::beg); int fileSize = inputFile.tellg(); inputFile.close(); outFile.close(); } else { fprintf(stderr, "File open FAILED for %s\n", fileName); } // If the override-user-config tag was found overwrite the dat // file with the temp file contents if (retVal) { remove(fileName); inputFile.open("./temp.txt"); outFile.open(fileName, std::ios::out); line.erase(); // Copy each line of the temp file back into a dat file with the same // name as the file passed in. while(std::getline(inputFile, line)) { outFile << line << endl; } inputFile.close(); remove("./temp.txt"); outFile.close(); } return retVal; } int test1_main(void) { // Verify types of all generated config items. Reference assignment will cause // a compiler error if any of the types are incorrect. // Test1::Test1_A_Data data_a; Test1::Test1_B_Data data_b; Test1::Test1_C_Data data_c; Test1::TParam1 & ref1 = data_a.Section1.Param1; Test1::TParam2 & ref2 = data_a.Section1.Param2; bool & ref3 = data_a.Section2.Param3; bool & ref4 = data_a.Section2.Param4; const char *& ref5 = data_a.Section2.Param5; const char *& ref6 = data_a.Section2.Param6; long & ref7 = data_a.Section2.Param7; long & ref8 = data_a.Section2.Param8; long & ref9 = data_a.Section2.Param9; long & ref10 = data_a.Section2.Param10; long & ref11 = data_a.Section2.Param11; double & ref12 = data_a.Section2.Param12; double & ref13 = data_a.Section2.Param13; double & ref14 = data_a.Section2.Param14; double & ref15 = data_a.Section2.Param15; double & ref16 = data_a.Section2.Param16; Test1::TParam101 & ref17 = data_b.Section1.Param101; Test1::TParam201 & ref18 = data_c.Section1.Param201; // Check class names // fprintf(stderr, "Test 1.1 ...\n"); if ( strcmp(Test1::Test1_A_Access.name(), "Test1_A") != 0 || strcmp(Test1::Test1_B_Access.name(), "Test1_B") != 0 || strcmp(Test1::Test1_C_Access.name(), "Test1_C") != 0 || strcmp(Test1::Test1_D_Access.name(), "Test1_D") != 0 || strcmp(Test1::Test1_E_Access.name(), "Test1_E") != 0 || strcmp(Test1::Test1_F_Access.name(), "Test1_F") != 0 || strcmp(Test1::Test1_G_Access.name(), "Test1_G") != 0 || strcmp(Test1::Test1_H_Access.name(), "Test1_H") != 0 || strcmp(Test1::Test1_I_Access.name(), "Test1_I") != 0 || strcmp(Test1::Test1_J_Access.name(), "Test1_J") != 0 || strcmp(Test1::Test1_K_Access.name(), "Test1_K") != 0 || strcmp(Test1::Test1_L_Access.name(), "Test1_L") != 0 || strcmp(Test1::Test1_M_Access.name(), "Test1_M") != 0 || strcmp(Test1::Test1_O_Access.name(), "Test1_O") != 0 || strcmp(Test1::Test1_P_Access.name(), "Test1_P") != 0 || strcmp(Test1::Test1_Q_Access.name(), "Test1_Q") != 0 || strcmp(Test1::Test1_S_Access.name(), "Test1_S") != 0 ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Check section names // fprintf(stderr, "Test 1.2 ...\n"); if ( strcmp(Test1::Test1_A_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_A_Access.Section2.name(), "Section2") != 0 || strcmp(Test1::Test1_B_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_C_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_C_Access.Section2.name(), "Section2") != 0 || strcmp(Test1::Test1_D_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_E_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_F_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_G_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_H_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_I_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_J_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_K_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_L_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_L_Access.Section2.name(), "Section2") != 0 || strcmp(Test1::Test1_M_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_O_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_P_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_P_Access.Section2.name(), "Section2") != 0 || strcmp(Test1::Test1_Q_Access.Section1.name(), "Section1") != 0 || strcmp(Test1::Test1_Q_Access.Section2.name(), "Section2") != 0 || strcmp(Test1::Test1_Q_Access.Section3.name(), "Section3") != 0 || strcmp(Test1::Test1_S_Access.Section1.name(), "Section1") != 0) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Check parameter names // fprintf(stderr, "Test 1.3 ...\n"); if ( strcmp(Test1::Test1_A_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_A_Access.Section1.Param2.name(), "Param2") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param3.name(), "Param3") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param4.name(), "Param4") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param5.name(), "Param5") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param6.name(), "Param6") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param7.name(), "Param7") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param8.name(), "Param8") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param9.name(), "Param9") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param10.name(), "Param10") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param11.name(), "Param11") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param12.name(), "Param12") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param13.name(), "Param13") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param14.name(), "Param14") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param15.name(), "Param15") != 0 || strcmp(Test1::Test1_A_Access.Section2.Param16.name(), "Param16") != 0 || strcmp(Test1::Test1_B_Access.Section1.Param101.name(), "Param101") != 0 || strcmp(Test1::Test1_C_Access.Section1.Param201.name(), "Param201") != 0 || strcmp(Test1::Test1_C_Access.Section2.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_C_Access.Section2.Param2.name(), "Param2") != 0 || strcmp(Test1::Test1_C_Access.Section2.Param3.name(), "Param3") != 0 || strcmp(Test1::Test1_C_Access.Section2.Param4.name(), "Param4") != 0 || strcmp(Test1::Test1_C_Access.Section2.Param5.name(), "Param5") != 0 || strcmp(Test1::Test1_C_Access.Section2.Param6.name(), "Param6") != 0 || strcmp(Test1::Test1_D_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_E_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_F_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_G_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_H_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_I_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_J_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_J_Access.Section1.Param2.name(), "Param2") != 0 || strcmp(Test1::Test1_K_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_L_Access.Section1.ParamK.name(), "ParamK") != 0 || strcmp(Test1::Test1_L_Access.Section2.ParamK.name(), "ParamK") != 0 || strcmp(Test1::Test1_M_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_M_Access.Section1.Param2.name(), "Param2") != 0 || strcmp(Test1::Test1_O_Access.Section1.ParamO.name(), "ParamO") != 0 || strcmp(Test1::Test1_P_Access.Section1.P1.name(), "P1") != 0 || strcmp(Test1::Test1_P_Access.Section1.P2.name(), "P2") != 0 || strcmp(Test1::Test1_P_Access.Section1.P3.name(), "P3") != 0 || strcmp(Test1::Test1_P_Access.Section2.ParamP.name(), "ParamP") != 0 || strcmp(Test1::Test1_P_Access.Section1.P1.name(), "P1") != 0 || strcmp(Test1::Test1_P_Access.Section1.P2.name(), "P2") != 0 || strcmp(Test1::Test1_P_Access.Section1.P3.name(), "P3") != 0 || strcmp(Test1::Test1_Q_Access.Section1.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_Q_Access.Section2.Param1.name(), "Param1") != 0 || strcmp(Test1::Test1_Q_Access.Section3.Param2.name(), "Param2") != 0 || strcmp(Test1::Test1_S_Access.Section1.Param1.name(), "Param1") != 0) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Check format versions // fprintf(stderr, "Test 1.4 ...\n"); if ( strcmp(Test1::Test1_A_Access.formatVersion(), "1a") != 0 || strcmp(Test1::Test1_B_Access.formatVersion(), "1b") != 0 || strcmp(Test1::Test1_C_Access.formatVersion(), "1c") != 0 || strcmp(Test1::Test1_D_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_D_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_E_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_F_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_G_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_H_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_I_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_J_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_K_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_L_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_M_Access.formatVersion(), "1m") != 0 || strcmp(Test1::Test1_O_Access.formatVersion(), "1") != 0 || strcmp(Test1::Test1_P_Access.formatVersion(), "1p") != 0 || strcmp(Test1::Test1_Q_Access.formatVersion(), "1.1c") != 0 || strcmp(Test1::Test1_S_Access.formatVersion(), "1") != 0) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Check file read operation // fprintf(stderr, "Test 1.5 ...\n"); if ( Test1::Test1_A_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadOK ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.6 ...\n"); if ( Test1::Test1_A().Section1.Param1 != Test1::enum1_id2 || Test1::Test1_A().Section1.Param2 != Test1::enum2_id1 ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.7 ...\n"); if ( Test1::Test1_A().Section2.Param3 != true || Test1::Test1_A().Section2.Param4 != false ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.8 ...\n"); if ( strcmp(Test1::Test1_A().Section2.Param5, "\tstring\n") != 0 || strcmp(Test1::Test1_A().Section2.Param6, "\"string \"with embedded quotes and comment # characters\"\"") != 0 ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.9 ...\n"); if ( Test1::Test1_A().Section2.Param7 != 5 || Test1::Test1_A().Section2.Param8 != -1 || Test1::Test1_A().Section2.Param9 != 0x33 || Test1::Test1_A().Section2.Param10 != 0x12345 || Test1::Test1_A().Section2.Param11 != -123456 ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.10 ...\n"); if ( !checkDouble(Test1::Test1_A().Section2.Param12, 0.1) || !checkDouble(Test1::Test1_A().Section2.Param13, -0.1) || !checkDouble(Test1::Test1_A().Section2.Param14, 1e17) || !checkDouble(Test1::Test1_A().Section2.Param15, -1.0e2) || !checkDouble(Test1::Test1_A().Section2.Param16, 1.0e2) ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Test range check, validate check fails as expected // fprintf(stderr, "Test 1.11 ...\n"); if ( Test1::Test1_D_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadFailed || Test1::Test1_E_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadFailed || Test1::Test1_F_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadFailed ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.12 ...\n"); if ( Test1::Test1_G_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadFailed || Test1::Test1_H_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadFailed || Test1::Test1_I_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadFailed ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.13 ...\n"); if ( Test1::Test1_J_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadFailed ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.14 ...\n"); if ( Test1::Test1_K_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadFailed ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.15 ...\n"); if ( Test1::Test1_L_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadFailed ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Cleanup files from previous test run (if any) // unlink(CONFIG_PATH "/file1_b.dat"); unlink(CONFIG_PATH "/crc/file1_b.crc"); unlink(CONFIG_PATH "/backup/file1_b.dat"); unlink(CONFIG_PATH "/backup/crc/file1_b.crc"); // Test reading file with CRC protection // FILE * fp = fopen(CONFIG_PATH "/file1_b.dat", "w"); fprintf(fp, "[Version]\n"); fprintf(fp, "FormatVersion=\"1b\"\n"); fprintf(fp, "DataVersion=\"d1b\"\n"); fprintf(fp, "[FileInfo]\n"); fprintf(fp, "ReadOnly=true\n"); fprintf(fp, "FileName=\"/config/file1_b.dat\"\n"); fprintf(fp, "[Section1]\n"); fprintf(fp, "Param101=enum3_id3\n"); fclose(fp); mkdir(CONFIG_PATH "/crc"); fp = fopen(CONFIG_PATH "/crc/file1_b.crc", "w"); fprintf(fp, "0xa4fd4310\n"); fclose(fp); fprintf(stderr, "Test 1.16 ...\n"); if ( Test1::Test1_B_Access.readFile(&log_level_critical, &log_level_critical) != ConfigFile::ReadOK ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Test CRC check // fp = fopen(CONFIG_PATH "/crc/file1_b.crc", "w"); fprintf(fp, "0xa4fd4301\n"); // incorrect CRC fclose(fp); unlink(CONFIG_PATH "/backup/file1_b.dat"); unlink(CONFIG_PATH "/backup/crc/file1_b.crc"); fprintf(stderr, "Test 1.17 ...\n"); if ( Test1::Test1_B_Access.readFile(&log_level_critical, &log_level_critical) != ConfigFile::ReadFailed ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Test use of backup file // mkdir(CONFIG_PATH "/backup"); fp = fopen(CONFIG_PATH "/backup/file1_b.dat", "w"); fprintf(fp, "[Version]\n"); fprintf(fp, "FormatVersion=\"1b\"\n"); fprintf(fp, "DataVersion=\"d1b\"\n"); fprintf(fp, "[FileInfo]\n"); fprintf(fp, "ReadOnly=true\n"); fprintf(fp, "FileName=\"/config/file1_b.dat\"\n"); fprintf(fp, "[Section1]\n"); fprintf(fp, "Param101=enum3_id1\n"); fclose(fp); mkdir(CONFIG_PATH "/backup/crc"); fp = fopen(CONFIG_PATH "/backup/crc/file1_b.crc", "w"); fprintf(fp, "0x96cb2192\n"); fclose(fp); fprintf(stderr, "Test 1.18 ...\n"); if ( Test1::Test1_B_Access.readFile(&log_level_critical, &log_level_critical) != ConfigFile::ReadBackupOK ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Test format version check // unlink(CONFIG_PATH "/backup/file1_b.dat"); fp = fopen(CONFIG_PATH "/file1_b.dat", "w"); fprintf(fp, "[Version]\n"); fprintf(fp, "FormatVersion=\"1c\"\n"); fprintf(fp, "DataVersion=\"d1b\"\n"); fprintf(fp, "[FileInfo]\n"); fprintf(fp, "ReadOnly=true\n"); fprintf(fp, "FileName=\"/config/file1_b.dat\"\n"); fprintf(fp, "[Section1]\n"); fprintf(fp, "Param101=enum3_id3\n"); fclose(fp); fp = fopen(CONFIG_PATH "/crc/file1_b.crc", "w"); fprintf(fp, "0xe2e4492a\n"); fclose(fp); fprintf(stderr, "Test 1.19 ...\n"); if ( Test1::Test1_B_Access.readFile(&log_level_critical, &log_level_critical) != ConfigFile::ReadFailed ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Test setting parameters for read/write files // fprintf(stderr, "Test 1.20 ...\n"); if ( !Test1::Test1_C_Access.Version.FormatVersion.set(Test1::Test1_C_Access.formatVersion()) || !Test1::Test1_C_Access.Version.DataVersion.set("1") || !Test1::Test1_C_Access.FileInfo.ReadOnly.set(false) || !Test1::Test1_C_Access.FileInfo.FileName.set("/config/file1_c.dat") || !Test1::Test1_C_Access.Section1.Param201.set(Test1::enum4_id1) || !Test1::Test1_C_Access.Section2.Param1.set(1) || !Test1::Test1_C_Access.Section2.Param2.set(-1) || !Test1::Test1_C_Access.Section2.Param3.set(-1) || !Test1::Test1_C_Access.Section2.Param4.set(-1) || !Test1::Test1_C_Access.Section2.Param5.set(2) || !Test1::Test1_C_Access.Section2.Param6.set(2) ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Test file write // fprintf(stderr, "Test 1.21 ...\n"); if ( Test1::Test1_C_Access.writeFile(&log_level_critical, &log_level_critical) != ConfigFile::WriteOK ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Test file read-back // Test1::Test1_C_Access.Version.FormatVersion.set("0"); Test1::Test1_C_Access.Version.DataVersion.set("0"); Test1::Test1_C_Access.FileInfo.ReadOnly.set(true); Test1::Test1_C_Access.FileInfo.FileName.set("0"); Test1::Test1_C_Access.Section1.Param201.set(Test1::enum4_id2); Test1::Test1_C_Access.Section2.Param1.set(2); Test1::Test1_C_Access.Section2.Param2.set(-2); Test1::Test1_C_Access.Section2.Param3.set(-2); Test1::Test1_C_Access.Section2.Param4.set(0); Test1::Test1_C_Access.Section2.Param5.set(1); Test1::Test1_C_Access.Section2.Param6.set(1); fprintf(stderr, "Test 1.22 ...\n"); if ( Test1::Test1_C_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadOK || strcmp(Test1::Test1_C().Version.FormatVersion, "1c") != 0 || strcmp(Test1::Test1_C().Version.DataVersion, "1") != 0 || Test1::Test1_C().FileInfo.ReadOnly != false || strcmp(Test1::Test1_C().FileInfo.FileName, "/config/file1_c.dat") != 0 || Test1::Test1_C().Section1.Param201 != Test1::enum4_id1 || Test1::Test1_C().Section2.Param1 != 1 || Test1::Test1_C().Section2.Param2 != -1 || Test1::Test1_C().Section2.Param3 != -1 || Test1::Test1_C().Section2.Param4 != -1 || Test1::Test1_C().Section2.Param5 != 2 || Test1::Test1_C().Section2.Param6 != 2 ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Test file backup // Test1::Test1_C_Access.Version.FormatVersion.set("0"); Test1::Test1_C_Access.Version.DataVersion.set("0"); Test1::Test1_C_Access.FileInfo.ReadOnly.set(true); Test1::Test1_C_Access.FileInfo.FileName.set("0"); Test1::Test1_C_Access.Section1.Param201.set(Test1::enum4_id2); Test1::Test1_C_Access.Section2.Param1.set(2); Test1::Test1_C_Access.Section2.Param2.set(-2); Test1::Test1_C_Access.Section2.Param3.set(-2); Test1::Test1_C_Access.Section2.Param4.set(0); Test1::Test1_C_Access.Section2.Param5.set(1); Test1::Test1_C_Access.Section2.Param6.set(1); fprintf(stderr, "Test 1.23 ...\n"); if ( Test1::Test1_C_Access.writeFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::WriteOK ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.24 ...\n"); unlink(CONFIG_PATH "/file1_c.dat"); if ( Test1::Test1_C_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadBackupOK || strcmp(Test1::Test1_C().Version.FormatVersion, "1c") != 0 || strcmp(Test1::Test1_C().Version.DataVersion, "1") != 0 || Test1::Test1_C().FileInfo.ReadOnly != false || strcmp(Test1::Test1_C().FileInfo.FileName, "/config/file1_c.dat") != 0 || Test1::Test1_C().Section1.Param201 != Test1::enum4_id1 || Test1::Test1_C().Section2.Param1 != 1 || Test1::Test1_C().Section2.Param2 != -1 || Test1::Test1_C().Section2.Param3 != -1 || Test1::Test1_C().Section2.Param4 != -1 || Test1::Test1_C().Section2.Param5 != 2 || Test1::Test1_C().Section2.Param6 != 2 ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); // Test range functions // fprintf(stderr, "Test 1.25 ...\n"); long min, max; if ( !Test1::Test1_C_Access.Section2.Param1.getRange(min, max) || min != 1 || max != 2 || !Test1::Test1_C_Access.Section2.Param1.set(1) || !Test1::Test1_C_Access.Section2.Param1.set(2) || Test1::Test1_C_Access.Section2.Param1.set(0) || Test1::Test1_C_Access.Section2.Param1.set(3) || Test1::Test1_C_Access.Section2.Param1.set(-1) ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.26 ...\n"); if ( !Test1::Test1_C_Access.Section2.Param2.getRange(min, max) || min != -2 || max != -1 || !Test1::Test1_C_Access.Section2.Param2.set(-1) || !Test1::Test1_C_Access.Section2.Param2.set(-2) || Test1::Test1_C_Access.Section2.Param2.set(0) || Test1::Test1_C_Access.Section2.Param2.set(1) || Test1::Test1_C_Access.Section2.Param2.set(-3) ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.27 ...\n"); if ( Test1::Test1_C_Access.Section2.Param3.getRange(min, max) || !Test1::Test1_C_Access.Section2.Param3.set(-1) || !Test1::Test1_C_Access.Section2.Param3.set(-2) || !Test1::Test1_C_Access.Section2.Param3.set(0) || !Test1::Test1_C_Access.Section2.Param3.set(1) || !Test1::Test1_C_Access.Section2.Param3.set(-3) ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.28 ...\n"); if ( !Test1::Test1_C_Access.Section2.Param4.getRange(min, max) || min != -1 || max != 1 || !Test1::Test1_C_Access.Section2.Param4.set(-1) || !Test1::Test1_C_Access.Section2.Param4.set(0) || Test1::Test1_C_Access.Section2.Param4.set(1) || Test1::Test1_C_Access.Section2.Param4.set(2) || Test1::Test1_C_Access.Section2.Param4.set(-2) ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.29 ...\n"); if ( !Test1::Test1_C_Access.Section2.Param5.getRange(min, max) || min != -2 || max != 2 || !Test1::Test1_C_Access.Section2.Param5.set(1) || !Test1::Test1_C_Access.Section2.Param5.set(2) || Test1::Test1_C_Access.Section2.Param5.set(3) || Test1::Test1_C_Access.Section2.Param5.set(0) || Test1::Test1_C_Access.Section2.Param5.set(-1) || Test1::Test1_C_Access.Section2.Param5.set(-3) ) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "Test 1.30 ...\n"); if ( Test1::Test1_C_Access.Section2.Param6.getRange(min, max) || !Test1::Test1_C_Access.Section2.Param6.set(1) || !Test1::Test1_C_Access.Section2.Param6.set(2) || !Test1::Test1_C_Access.Section2.Param6.set(3) || Test1::Test1_C_Access.Section2.Param6.set(0) || Test1::Test1_C_Access.Section2.Param6.set(-1) || Test1::Test1_C_Access.Section2.Param6.set(-3) ) { fprintf(stderr, "test failed\n"); return -1; } else { fprintf(stderr, "test passed\n"); } fprintf(stderr, "Test 1.31 ...\n"); if ( Test1::Test1_Q_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadOK || Test1::Test1_Q().Section1.Param1 != 0 || Test1::Test1_Q().Section2.Param1 != -4 || Test1::Test1_Q().Section3.Param2 != 10 || true != Test1::Test1_Q_Access.Section1.Param1.getRange(min,max) || min != -1 || max != 0) { fprintf(stderr, "test failed"); return -1; } else { fprintf(stderr, "test passed\n"); } fprintf(stderr, "Test 1.32 ...\n"); if ( Test1::Test1_P_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadOK || Test1::Test1_P().Section1.P1 != Test1::enumP_id1 || Test1::Test1_P().Section1.P2 != Test1::enumP_id2 || Test1::Test1_P().Section1.P3 != Test1::enumP_id3 || Test1::Test1_P().Section2.P1 != Test1::enumP_id1 || Test1::Test1_P().Section2.P2 != Test1::enumP_id2 || Test1::Test1_P().Section2.P3 != Test1::enumP_id3 || Test1::Test1_P().Section2.ParamP != Test1::enumP_id1 || !Test1::Test1_P_Access.Section1.P1.set((Test1::TParamP)Test1::enumP_id2) || !Test1::Test1_P_Access.Section1.P3.set(Test1::enumP_id1)|| !Test1::Test1_P_Access.Section2.ParamP.set(Test1::enumP_id2) || !Test1::Test1_P_Access.Section2.P2.set(Test1::enumP_id3) || !Test1::Test1_P_Access.Section2.P3.set((Test1::TParamP)Test1::enumP_id1)) { fprintf(stderr, "test failed\n"); return -1; } else { fprintf(stderr, "test passed\n"); } fprintf(stderr, "Test 1.33 ...\n"); if ( Test1::Test1_S_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) != ConfigFile::ReadOK || Test1::Test1_S().Section1.Param1 != 0 || Test1::Test1_S_Access.Section1.Param1.getRange(min,max) == false || min != -1 || max != 0) { fprintf(stderr, "test failed\n"); return -1; } else { fprintf(stderr, "test passed\n"); } fprintf(stderr, "Test 1.34 ...\n"); // Verify that the test1_a.dat file doesn't contain the override-user-config tag. It should be ingnored // because it's a read-only file. // Verify that the test1_m.dat contains the override tag for the section1 param1 entry // Verify that the test1_m.dat file can be read and that the section1 param1 value is as expected. if ( checkUserConfigOverride(Test1::Test1_C_Access.defaultFileName(), "Section2", "Param2") || checkUserConfigOverride(Test1::Test1_A_Access.fileName(), "Section2", "Param7") || !checkUserConfigOverride(Test1::Test1_M_Access.defaultFileName(), "Section1", "Param1") || ConfigFile::ReadDefaultOK != Test1::Test1_M_Access.readFile(&log_level_config_data_info, &log_level_config_data_error) || Test1::Test1_M().Section1.Param1 != 0.4) { fprintf(stderr, "test failed\n"); return -1; } fprintf(stderr, "test passed\n"); fprintf(stderr, "All Tests passed\n"); return 0; }
true
bd45df162fefe44999e9870bcb2e84f216ff519e
C++
acnokego/LeetCode
/389_Find_the_Difference/hash.cpp
UTF-8
532
3.21875
3
[]
no_license
class Solution { /* * Complexity: O(n) * Space: O(n) */ public: char findTheDifference(string s, string t) { unordered_map<char, int>occurrence; for(auto& c:s){ occurrence[c] += 1; } for(auto& c:t){ auto it = occurrence.find(c); if(it == occurrence.end()){ return c; } else{ if(--it -> second == 0){ occurrence.erase(it); } } } } };
true
e682289cd057c361c0bd97231cc3fc2e6a6f48f7
C++
lyonsno/cubes
/collisionPlane.cpp
UTF-8
3,357
2.875
3
[]
no_license
#include "collisionPlane.h" CollisionPlane::CollisionPlane() : depth(10), camera(new Camera()){} CollisionPlane::CollisionPlane(float depth, Camera* camera) : depth(depth), camera(camera) { } glm::vec4 CollisionPlane::worldFromScreenCoords(float winX, float winY) { std::cout<<"getWorld"<<std::endl; float aspect = float(camera->getClientWidth()) / float(camera->getClientHeight()); std::cout<<"aspect: "<<aspect<<std::endl; // float normX = (winX / camera->getClientWidth()) -0.5f; // float normY = -1.0 * ((winY / camera->getClientHeight()) -0.5f); // glm::vec3 imagePoint = normX * camera->getRight() + normY * camera->getUp() + camera->getPosition() + camera->getDirection(); // std::cout<<imagePoint.x<<","<<imagePoint.y<<","<<imagePoint.z<<std::endl; // glm::vec3 rayDirection = imagePoint - camera->getPosition(); // std::cout<<rayDirection.x<<","<<rayDirection.y<<","<<rayDirection.z<<std::endl; float halfWidth = camera->getClientWidth() / 2.0; float halfHeight = camera->getClientHeight() / 2.0; double x = tanf(camera->getFov() * 0.5f) * (-(winX / halfWidth) + 1.0f ) * aspect; double y = tanf(camera->getFov() * 0.5f) * (-1.0f + (winY / halfHeight)); // float x = (2.0 * winX / camera->getClientWidth()) -1.0; // float y = (-2.0 * winY / camera->getClientHeight()) + 1.0; // glm::vec4 worldPosition = glm::vec4(x, y, 0.01, 1.0); // std::cout<<worldPosition.x<<","<<worldPosition.y<<","<<worldPosition.z<<std::endl; // glm::mat4 invVPMat = glm::inverse(camera->getProjectionMatrix() * camera->getViewMatrix()); // worldPosition = worldPosition * invVPMat; // worldPosition /= worldPosition.w; // // glm::vec4 finalPosition = glm::vec4(worldPosition.x / worldPosition.w, worldPosition.y / worldPosition.w, depth, 1.0); // std::cout<<worldPosition.x<<","<<worldPosition.y<<","<<worldPosition.z<<std::endl; // return worldPosition; float near = camera->getNear(); float far = camera->getFar(); glm::vec3 pNear = glm::vec3(x * near, y * near, near); glm::vec3 pFar = glm::vec3(x * far, y * far, far); glm::mat4 viewProjectionInverse = glm::inverse(camera->getViewMatrix()); pNear = glm::vec3(glm::vec4(pNear, 1.0) * viewProjectionInverse); pFar = glm::vec3(glm::vec4(pFar, 1.0) * viewProjectionInverse); // pNear = glm::vec3(glm::vec4(camera->getPosition(), 1.0) * viewProjectionInverse); glm::vec3 ray = pFar - pNear; return cameraRayIntersection(ray, camera->getPosition()); // glm::vec4 dir = glm::transpose(viewProjectionInverse) * glm::vec4(x, y, 1, 1); // // dir /= viewProjectionInverse[3] + viewProjectionInverse[7] + viewProjectionInverse[11] + viewProjectionInverse[15]; // dir -= glm::vec4(camera->getPosition(), 1.0); // float factor = depth / dir.z; // glm::vec3 point = glm::vec3(dir.x * factor, dir.y * factor, dir.z * factor); // // glm::vec4 point = glm::vec4(winX,winY,0.5,1); // // glm::vec4 temp = viewProjectionInverse * point; // std::cout<<point.x<<","<<point.y<<","<<point.z<<std::endl; // return glm::vec4(point, 1); } glm::vec4 CollisionPlane::cameraRayIntersection(glm::vec3 ray, glm::vec3 p0) { ray = glm::normalize(ray); float t = ( -1 * (glm::dot(p0, glm::vec3(0,0,-1)) + depth) ) / (glm::dot(ray, glm::vec3(0.0,0.0,-1.0))); glm::vec3 temp = p0 + t * ray; std::cout<<temp.x<<","<<temp.y<<","<<temp.z<<std::endl; return glm::vec4(p0 + (t * ray), 1.0); }
true
d65bbe3b4497c5473f98fa521d953a6219396c0f
C++
bshkola/StreetSimulator
/common/traffic/pedestrian.h
UTF-8
536
2.546875
3
[]
no_license
//Author: Wojciech Ceret //Represent move object on the board #ifndef PEDESTRIAN_H #define PEDESTRIAN_H #include "trafficparticipant.h" #include "../../view/items/pedestrianitem.h" struct Pedestrian : public TrafficParticipant { Pedestrian(int id, float speed, std::pair<int, int> start_point, std::pair<int, int> target_point): TrafficParticipant(id, speed, start_point, target_point) {} ITrafficParticipantItem* createItem(const QRectF& rect) { return new PedestrianItem(rect); } }; #endif // PEDESTRIAN_H
true
5cf820193a3d0e5ba2bc804a76a6b1de5e52ce09
C++
chubbymaggie/irreg-simd
/euler/seq-tiling/tile_euler.cpp
UTF-8
2,955
2.546875
3
[]
no_license
#include <atomic> #include <unordered_map> #include <fstream> #include <iostream> #include <math.h> #include <omp.h> #include <sstream> #include <thread> #include <tuple> #include <vector> #include <x86intrin.h> #include "SSE_API_Package/SSE_Template/sse_api.h" #include "conf.h" #include "../../tools/csr_loader.h" #include "../../tools/ds.h" #include "../../tools/load_tile_from_file.h" #include "../../tools/tiling.h" #include "util.h" using namespace std; #define DENSITY 0.83134 #define cutoffRadius 3.0 #define POW(a,b) pow(a,b) #define TOLERANCE 1.2 ThreeDSoa<float>* LoadCoo(string coo_file) { ifstream input(coo_file.c_str()); vector<tuple<float, float, float> > coos; string line; float x, y, z; while (getline(input, line)) { istringstream iss(line); iss >> x; iss >> y; iss >> z; coos.push_back(make_tuple(x, y, z)); } input.close(); ThreeDSoa<float>* soa = new ThreeDSoa<float>(coos.size()); soa->SetXyz(coos); return soa; } // Do in multi-thread fashion. template <class ValueType> void DoEuler(const PaddedNnz<ValueType>& nnzs, const ThreeDSoa<float>* velocities, ThreeDSoa<float>* forces) { double before = rtclock(); float a0,a1,a2; float r0,r1,r2; int n0, n1; for (int ii = 0; ii < nnzs.nnz; ++ii) { n0 = nnzs.rows[ii]; n1 = nnzs.cols[ii]; a0 = (nnzs.vals[ii] * velocities->x[n0] + nnzs.vals[ii] * velocities->y[n0] + nnzs.vals[ii] * velocities->z[n0])/3.0; a1 = (nnzs.vals[ii] * velocities->x[n1] + nnzs.vals[ii] * velocities->y[n1] + nnzs.vals[ii] * velocities->z[n1])/3.0; r0 = a0*velocities->x[n0] + a1*velocities->x[n1] + nnzs.vals[ii]; r1 = a0*velocities->y[n0] + a1*velocities->y[n1] + nnzs.vals[ii]; r2 = a0*velocities->z[n0] + a1*velocities->z[n1] + nnzs.vals[ii]; forces->x[n0] += r0; forces->y[n0] += r1; forces->z[n0] += r2; forces->x[n1] -= r0; forces->y[n1] -= r1; forces->z[n1] -= r2; } double after = rtclock(); cout << RED << "[****Result****] ========> *Serial Tiling* Euler time: " << after - before << " secs." << RESET << endl; } int main(int argc, char** argv) { double begin = rtclock(); cout << "NNZ file: " << string(argv[1]) << endl; cout << "XYZ file: " << string(argv[2]) << endl; // Load NNZs. PaddedNnz<int>* nnzs; LoadTileFromFile(string(argv[1]), nnzs); double after_nnz = rtclock(); cout << "NNZ load done, at time of " << after_nnz - begin << endl; cout << "Total NNZ: " << nnzs->nnz << endl; // Load velocities. ThreeDSoa<float>* velocities = LoadCoo(string(argv[2])); ThreeDSoa<float>* forces = new ThreeDSoa<float>(velocities->num_nodes); double after_coo = rtclock(); cout << "Velocities load done, at time of " << after_coo - begin << endl; DoEuler(*nnzs, velocities, forces); cout << "Done." << endl; delete velocities; delete forces; delete nnzs; return 0; }
true
905fbfb3df7cb15f177168f6e706b0d9d08fe75e
C++
allipurHari/DataStructure
/queue/evaluate-expression.cpp
UTF-8
763
3.3125
3
[]
no_license
// https://www.interviewbit.com/problems/evaluate-expression/ int Solution::evalRPN(vector<string> &A) { stack<string>s; int len = A.size(), first, second, temp; for(int i = 0;i < len;i++){ if(A[i] == "+" || A[i] == "-" || A[i] == "*" || A[i] == "/"){ second = stoi(s.top());s.pop(); first = stoi(s.top());s.pop(); if(A[i] == "+") temp = first + second; else if(A[i] == "-") temp = first - second; else if(A[i] == "*") temp = first * second; else if(A[i] == "/") temp = first / second; s.push(to_string(temp)); } else s.push(A[i]); } return stoi(s.top()); }
true
cfcd6405f51a6b54ef10814c9f39ae71f0f9b5fb
C++
eeeeeta/inebriated-cpp-edition
/rand.cpp
UTF-8
1,832
3.03125
3
[]
no_license
/* * Random number generation, weighting, and all that good stuff(tm) */ #include "rand.hpp" #include <iostream> using namespace Markov; Key *Rand::randomKey(Key *kp) { int wt_sum = 0; for (auto k : *kp) { #ifdef DEBUG std::cout << "MDB: weight for " << k->ptr->val << " is " << k->ptr->getWeight() << "\n"; #endif wt_sum += (k->ptr->getWeight()); } int rand = (wt_sum > 0 ? std::rand() % wt_sum : -1); for (auto k : *kp) { #ifdef DEBUG std::cout << "MDB: rand " << rand << " curk " << k->ptr->val << "\n"; #endif if (rand < (k->ptr->getWeight())) { return k->ptr; } rand -= (k->ptr->getWeight()); } throw std::runtime_error("Weighted random number generator derped"); }; DB::ssdb_objtype Rand::randomSsdbObj(std::vector<DB::ssdb_objtype>* vec) { int wt_sum = 0; for (auto obj : *vec) wt_sum += obj.second; int rand = (wt_sum > 0 ? std::rand() % wt_sum : -1); for (auto obj : *vec) { if (rand < obj.second) return obj; rand -= obj.second; } throw std::runtime_error("Weighted random number generator derped"); }; float Rand::weightForKey(Key *key, DB::kvdb_type *kvdb) { float weight_so_far = 0.0; for (;;) { /* weight += amount of choices in current linked list - magical constant */ #ifdef DEBUG std::cout << "RAND: keylength " << key->length() << "\n"; #endif weight_so_far += ((float) key->length()); /* vk = choose random key from current linked list */ Key *vk = Rand::randomKey(key); auto iter = kvdb->find(vk->val); if (iter == kvdb->end()) break; else key = iter->second; /* if we found one, continue */ } #ifdef DEBUG std::cout << "RAND: wt = " << weight_so_far << "\n"; #endif return weight_so_far; };
true
489d1f7b5683d19cedd0e4ae92c266b6c276ce04
C++
LBNL-UCB-STI/routing-framework
/Tools/Bitwise.h
UTF-8
3,144
3.5
4
[ "MIT", "GPL-3.0-only" ]
permissive
#pragma once #include <bitset> #include <cassert> #include <limits> namespace bitwise { // We add an overloaded version of __builtin_clz. inline int builtin_clz(const unsigned int x) { return __builtin_clz(x); } inline int builtin_clz(const unsigned long x) { return __builtin_clzl(x); } inline int builtin_clz(const unsigned long long x) { return __builtin_clzll(x); } // We add an overloaded version of __builtin_ctz. inline int builtin_ctz(const unsigned int x) { return __builtin_ctz(x); } inline int builtin_ctz(const unsigned long x) { return __builtin_ctzl(x); } inline int builtin_ctz(const unsigned long long x) { return __builtin_ctzll(x); } } // Returns the bit with the specified index in val. template <typename UIntT> inline bool getBit(const UIntT val, const int bitIndex) { assert(bitIndex >= 0); assert(bitIndex < std::numeric_limits<UIntT>::digits); return (val >> bitIndex) & 1; } // Sets the bit with the specified index in val to bitValue. template <typename UIntT> inline void setBit(UIntT& val, const int bitIndex, const bool bitValue = true) { assert(bitIndex >= 0); assert(bitIndex < std::numeric_limits<UIntT>::digits); val ^= (-bitValue ^ val) & (UIntT{1} << bitIndex); } // Returns the number of zero-bits preceding the highest-order one-bit in val. template <typename UIntT> inline int numLeadingZeros(const UIntT val) { // A good compiler will generate a single LZCNT instruction for the following. if (val == 0) return std::numeric_limits<UIntT>::digits; return bitwise::builtin_clz(val); } // Returns the number of zero-bits following the lowest-order one-bit in val. template <typename UIntT> inline int numTrailingZeros(const UIntT val) { // A good compiler will generate a single TZCNT instruction for the following. if (val == 0) return std::numeric_limits<UIntT>::digits; return bitwise::builtin_ctz(val); } // Returns the number of one-bits in the value representation of val. template <typename UIntT> inline int bitCount(const UIntT val) { // A good compiler will generate a single POPCNT instruction for the following. return std::bitset<std::numeric_limits<UIntT>::digits>(val).count(); } // Returns the number of one-bits in val that occur before the specified index. template <typename UIntT> inline int bitCountBeforeIndex(const UIntT val, const int bitIndex) { assert(bitIndex >= 0); assert(bitIndex < std::numeric_limits<UIntT>::digits); return bitCount(val & ((UIntT{1} << bitIndex) - 1)); } // Returns the index of the highest-order one-bit in val, or -1 if val is zero. template <typename UIntT> inline int highestOneBit(const UIntT val) { return std::numeric_limits<UIntT>::digits - numLeadingZeros(val) - 1; } // Returns the index of the lowest-order one-bit in val, or -1 if val is zero. template <typename UIntT> inline int lowestOneBit(const UIntT val) { if (val == 0) return -1; return numTrailingZeros(val); } // Returns the index of the highest-order differing bit, or -1 if x and y are equal. template <typename UIntT> inline int highestDifferingBit(const UIntT x, const UIntT y) { return highestOneBit(x ^ y); }
true
cb1beb0d248acace9af6a298a0cff976d0e36f39
C++
katarinasupe/NapredniCpp
/hash/src/lookup-seq-main.cpp
UTF-8
3,232
3.453125
3
[]
no_license
#include "lookup-seq.h" #include <string> #include <iostream> bool predicate_function_key(std::pair<std::string, int> bucket_value) { return bucket_value.first == "Katarina"; } bool predicate_function_value(std::pair<std::string, int> bucket_value) { return bucket_value.second == 989898; } //testiranje pomocu print() funkcije za provjeru valjanosti testova int main(){ HashTable<std::string, int> *hash_table = new HashTable<std::string, int>(); hash_table->add_or_update("Goran", 919191); hash_table->add_or_update("Katarina", 888888); hash_table->add_or_update("Darko", 989898); hash_table->add_or_update("Kata", 989898); hash_table->add_or_update("Goran", 919192); std::cout << "HashTable: " << std::endl; hash_table->print(std::cout); std::cout << "Testiranje value: " << std::endl; if(hash_table->value("Goran").has_value()){ std::cout << "Vrijednost od 'Goran': " << hash_table->value("Goran").value() <<std::endl; } else{ std::cout << "Ne postoji Goran u imeniku!" << std::endl; } if(hash_table->value("Katarina").has_value()){ std::cout << "Vrijednost od 'Katarina': " << hash_table->value("Katarina").value() <<std::endl; } else{ std::cout << "Ne postoji Katarina u imeniku!" << std::endl; } std::cout << "Velicina hash tablice: " << hash_table->size() << std::endl; std::cout << "Testiranje predikata za find if na key (ako je key == 'Katarina'): " << std::endl; if(hash_table->find_if(predicate_function_key).has_value()) { std::pair<std::string, int> bucket_value = hash_table->find_if(predicate_function_key).value(); std::cout <<"Key: " << bucket_value.first << std::endl; std::cout <<"Value: " << bucket_value.second << std::endl; } else{ std::cout << "Za nijedan element predikat ne vraca true." << std::endl; } std::cout << "Testiranje predikata za find if na value (ako je value == '989898'): " << std::endl; if(hash_table->find_if(predicate_function_value).has_value()) { std::pair<std::string, int> bucket_value = hash_table->find_if(predicate_function_value).value(); std::cout <<"Key: " << bucket_value.first << std::endl; std::cout <<"Value: " << bucket_value.second << std::endl; } else{ std::cout << "Za nijedan element predikat ne vraca true." << std::endl; } std::cout << "Testiranje predikata za find all_if (ako je value == '989898'): " << std::endl; if(!hash_table->find_all_if(predicate_function_value).empty()) { //ispisi listu parova std::list<std::pair<std::string,int>> bucket_values = hash_table->find_all_if(predicate_function_value); for(std::pair<std::string,int> pair : bucket_values) { std::cout << "Key: " << pair.first << std::endl; std::cout << "Value: " << pair.second << std::endl; } } else{ std::cout << "Za nijedan element predikat ne vraca true." << std::endl; } hash_table->remove("Kata"); std::cout << "Nova HashTable (nakon uklanjanja elementa s key-em 'Kata'): " << std::endl; hash_table->print(std::cout); return 0; }
true
bfa8c00cf1069d7a64b3552c5cc04f61cf296904
C++
niyaznigmatullin/nncontests
/utils/IdeaProject/archive/unsorted/2015.05/2015.05.03 - Yandex Algorithm 2015 Warm up Round/e.cpp
UTF-8
2,097
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct state { signed char x1; signed char y1; signed char x2; signed char y2; }; vector<pair<int, int> > get(int p1, int q1) { return {{-p1, -q1}, {-p1, q1}, {p1, -q1}, {p1, q1}, {-q1, -p1}, {-q1, p1}, {q1, -p1}, {q1, p1}}; } int from[55][55][55][55]; bool was[55][55][55][55]; state q[55 * 55 * 55 * 55]; int main() { int n, m; scanf("%d%d", &n, &m); int p1, q1, p2, q2; scanf("%d%d%d%d", &p1, &q1, &p2, &q2); int x1, y1, x2, y2; scanf("%d%d%d%d", &x1, &y1, &x2, &y2); --x1; --y1; --x2; --y2; int head = 0; int tail = 0; q[tail++] = {x1, y1, x2, y2}; vector<pair<int, int> > m1 = get(p1, q1), m2 = get(p2, q2); was[x1][y1][x2][y2] = true; from[x1][y1][x2][y2] = -1; while (head < tail) { state v = q[head++]; if (v.x1 == v.x2 && v.y1 == v.y2) { vector<state> ans; while (true) { ans.push_back(v); if (from[v.x1][v.y1][v.x2][v.y2] < 0) break; v = q[from[v.x1][v.y1][v.x2][v.y2]]; } reverse(ans.begin(), ans.end()); printf("%d\n", (int) ans.size() - 1); for (state & e : ans) { printf("%d %d %d %d\n", e.x1 + 1, e.y1 + 1, e.x2 + 1, e.y2 + 1); } return 0; } for (pair<int, int> d1 : m1) { int nx1 = v.x1 + d1.first; int ny1 = v.y1 + d1.second; if (nx1 < 0 || ny1 < 0 || nx1 >= n || ny1 >= m) continue; for (pair<int, int> d2 : m2) { int nx2 = v.x2 + d2.first; int ny2 = v.y2 + d2.second; if (nx2 < 0 || ny2 < 0 || nx2 >= n || ny2 >= m) continue; if (was[nx1][ny1][nx2][ny2]) continue; q[tail++] = {nx1, ny1, nx2, ny2}; was[nx1][ny1][nx2][ny2] = true; from[nx1][ny1][nx2][ny2] = head - 1; } } } puts("-1"); }
true
5cc112741f016928d53aa82c564c35943c3c7dad
C++
rafalzuk/HPC_copy
/burgers.cpp
UTF-8
51,140
2.875
3
[]
no_license
#include "BURGERS.h" #include "cblas.h" //#include <array> //#include <numeric> Burgers::Burgers(const Model& model) { /*Import some parameters, to avoid calling getters of Model class every time these are needed, thus boost performance */ Dx = model.GetDx(); Dy = model.GetDy(); Dt = model.GetDt(); // Physical Constants ax = model.GetAx(); ay = model.GetAy(); b = model.GetB(); c = model.GetC(); /* Values determining size of arrays and time integration points */ sizeX = model.GetNx(); sizeY = model.GetNy(); sizeXY = sizeX*sizeY; Px = model.GetPx(); Py = model.GetPy(); Nt = model.GetNt(); /* Halves of the domain size */ Lx_half = model.GetLx() / 2; Ly_half = model.GetLy() / 2; } // Defalut constructor Burgers::Burgers() { cout << "Please provide a model as an argument! " << endl; } // Destructor Burgers::~Burgers() { } void Burgers::SpaceVectors(int rank, int size) { // Build local X vectors for each process if(sizeX%Px == 0) // If divides evenly { local_sizeX = (sizeX/Px); const int LOCALSIZEX = local_sizeX; X_local = new double[LOCALSIZEX]; for (int j = 0 ; j < local_sizeX ; j++ ) { X_local[j] = -Lx_half + j*Dx + (rank%Px)*(sizeX/Px)*Dx; } } else // Divides with remainder { if((rank+1)%Px != 0) // If is not the last process in the x dimension { local_sizeX = (int)(sizeX/Px); const int LOCALSIZEX = local_sizeX; X_local = new double[LOCALSIZEX]; for (int j = 0 ; j < local_sizeX ; j++ ) { X_local[j] = -Lx_half + j*Dx + (rank%Px) *local_sizeX * Dx; } } else // If the last process in the x dimension { local_sizeX = sizeX - (int)(sizeX/Px)*(Px-1); const int LOCALSIZEX = local_sizeX; X_local = new double[LOCALSIZEX]; for (int j = 0 ; j < local_sizeX ; j++ ) { X_local[j] = -Lx_half + j*Dx + (rank%Px) * (int)(sizeX/Px) * Dx; } } } // Similarly build local Y vector for each process if(sizeY%Py == 0) { local_sizeY = (sizeY/Py); const int LOCALSIZEY = local_sizeY; Y_local = new double[LOCALSIZEY]; for (int j = 0 ; j < local_sizeY ; j++ ) { Y_local[j] = -Ly_half + j*Dy + (rank/Px)*local_sizeY*Dy; } } else { if( ((rank/Px)+1) != Py) { local_sizeY = (int)(sizeY/Py); const int LOCALSIZEY = local_sizeY; Y_local = new double[LOCALSIZEY]; for (int j = 0 ; j < local_sizeY ; j++ ) { Y_local[j] = -Ly_half + j*Dy + (rank/Px)*local_sizeY * Dy; } } else { local_sizeY = sizeY - (int)(sizeY/Py)*(Py-1); const int LOCALSIZEY = local_sizeY; Y_local = new double[LOCALSIZEY]; for (int j = 0 ; j < local_sizeY ; j++ ) { Y_local[j] = -Ly_half + j*Dy + (rank/Px)*(int)(sizeY/Py) * Dy; } } } } void Burgers::VelocityVectors(int size) { /* Conditions below determine the outermost points * (counting in absolute values i.e. from 1) * which might be affected by initial condition * i.e. become non-zero in unit central circle. * This helps to reduce computational power required * to implement initial veolcity field, as computer won't * need to compute radius everywhere in the domain. */ if(size == 1) { if (Lx_half > 1 && (sizeX%2 == 0)) { max_xID = sizeX/2 + ceil(1/Dx); min_xID = sizeX/2 + 1 - ceil(1/Dx); } else if (Lx_half > 1 && (sizeX%2 != 0)) { max_xID = (sizeX+1)/2 + ceil(1/Dx); min_xID = (sizeX+1)/2 - ceil(1/Dx); } else { max_xID = sizeX; min_xID = 1; } if (Ly_half > 1 && (sizeY%2 == 0)) { max_yID = sizeY/2 + ceil(1/Dy); min_yID = sizeY/2 + 1 - ceil(1/Dy); } else if (Ly_half > 1 && (sizeY%2 !=0)) { max_yID = (sizeY+1)/2 + ceil(1/Dy); min_yID = (sizeY+1)/2 - ceil(1/Dy); } else { max_yID = sizeY; min_yID = 1; } const int SizeXY = sizeXY; U = new double[SizeXY]; V = new double[SizeXY]; U_next = new double[SizeXY]; V_next = new double[SizeXY]; // intialise velocity field by putting zeros for (int i = 0; i < sizeXY; i++) { U[i] = 0; V[i] = 0; U_next[i] = 0; V_next[i] = 0; } /* Now assign initial velocity field in the reduced domain * noting that array indexes are counted with 0 and max/min_ID's * were with 1 for convenience*/ for(int j = (min_yID - 1); j < max_yID ; j++ ) { for(int i = (min_xID - 1); i < max_xID ; i++ ) { radius = pow( X_local[i]*X_local[i] + Y_local[j]*Y_local[j] , 0.5); if (radius <= 1.0) { // These are unit circle Velocities at time 0 U[i+j*sizeX] = 2 * pow( (1-radius) , 4) * (4*radius + 1); V[i+j*sizeX] = 2 * pow( (1-radius) , 4) * (4*radius + 1); } } } } else // Now solution for multi-process computation { const int localSize = local_sizeX*local_sizeY; U = new double[localSize]; V = new double[localSize]; U_next = new double[localSize]; V_next = new double[localSize]; for(int j = 0; j < local_sizeY ; j++ ) { for(int i = 0; i < local_sizeX ; i++ ) { U_next[i+j*local_sizeX] = 0; V_next[i+j*local_sizeX] = 0; radius = pow( X_local[i]*X_local[i] + Y_local[j]*Y_local[j] , 0.5); if (radius <= 1.0) { // These are unit circle Velocities at time 0 U[i+j*local_sizeX] = 2 * pow( (1-radius) , 4) * (4*radius + 1); V[i+j*local_sizeX] = 2 * pow( (1-radius) , 4) * (4*radius + 1); } else { U[i+j*local_sizeX] = 0; V[i+j*local_sizeX] = 0; } } } } } void Burgers::Integrate(int rank, int size) { if(size == 1) // This single-process case exists to avoid if statements present in multi-process part { for(int t = 1; t < Nt; t++) // for every time point, after 0th which was defined above { for(int y = 1; y < (sizeY-1) ; y++) // for every y direction point, execpt for boundaries { for(int x = 1; x < (sizeX-1) ; x++) // for every x direction point, execpt for boundaries { // 'next' refers to the next time point U_next[x+y*sizeX] = Dt * ( c*( U[x+1+y*sizeX] - 2*U[x+y*sizeX] + U[x-1+y*sizeX] ) / (Dx*Dx) + c*( U[x+(y+1)*sizeX] - 2*U[x+y*sizeX] + U[x+(y-1)*sizeX] ) / (Dy*Dy) - (ay + b*V[x+y*sizeX]) * (U[x+y*sizeX] - U[x+(y-1)*sizeX]) / Dy - (ax + b*U[x+y*sizeX]) * (U[x+y*sizeX] - U[x-1+y*sizeX]) / Dx ) + U[x+y*sizeX]; V_next[x+y*sizeX] = Dt * ( c*( V[x+1+y*sizeX] - 2*V[x+y*sizeX] + V[x-1+y*sizeX] ) / (Dx*Dx) + c*( V[x+(y+1)*sizeX] - 2*V[x+y*sizeX] + V[x+(y-1)*sizeX] ) / (Dy*Dy) - (ay + b*V[x+y*sizeX]) * (V[x+y*sizeX] - V[x+(y-1)*sizeX]) / Dy - (ax + b*U[x+y*sizeX]) * (V[x+y*sizeX] - V[x-1+y*sizeX]) / Dx ) + V[x+y*sizeX]; } } // Prepare arrays for next time iteration for (int i = 0; i < sizeXY; i++) { U[i] = U_next[i]; V[i] = V_next[i]; } } } //Close single process procedure else // Now consider multi-process computation { // First check for boundary processes if(rank%Px == 0) // processes on the left edge of domain { if(rank == 0) //bottom left corner { // If the number of processses in a dimension is one, then do not send anything in this dimension // Also adjust local domain size accordingly for sending data in the perpendicular directoin tempYsize = (Py == 1) ? (local_sizeY-1) : local_sizeY; if(Px == 1) { tempXsize = (local_sizeX-1); } else { tempXsize = (local_sizeX); //Variables used for data sending and receiving U_right_send = new double[tempYsize-1]; V_right_send = new double[tempYsize-1]; U_right_import = new double[tempYsize-1]; V_right_import = new double[tempYsize-1]; } if(Py != 1) { //Variables used for data sending and receiving U_up_send = new double[tempXsize-1]; V_up_send = new double[tempXsize-1]; V_up_import = new double[tempXsize-1]; U_up_import = new double[tempXsize-1]; } for(int T = 1; T < Nt; T++) { for(int y = 1; y < tempYsize; y++) { for (int x = 1; x < tempXsize ; x++) { // Input which may change depending on process location in the domain if(x == 1 && y == 1 && Px != 1) // exchange data with right process { // Create data packagae to be sent for(int i = 0; i < tempYsize-1; i++) { U_right_send[i] = U[(y+i)*local_sizeX+(local_sizeX-1)]; V_right_send[i] = V[(y+i)*local_sizeX+(local_sizeX-1)]; } // Send data MPI_Send(U_right_send, tempYsize-1, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD); MPI_Send(V_right_send, tempYsize-1, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_right_import, tempYsize-1, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_right_import, tempYsize-1, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } // If on the boundary, use received data if(x == (local_sizeX-1)) { u_right = U_right_import[y-1]; v_right = V_right_import[y-1]; } else{ u_right = U[x+1+y*local_sizeX]; v_right = V[x+1+y*local_sizeX]; } if(y == 1 && x == 1 && Py != 1) // exchange data with above process { for(int i = 0; i < tempXsize-1; i++) { U_up_send[i] = U[(local_sizeY-1)*local_sizeX+i+x]; V_up_send[i] = V[(local_sizeY-1)*local_sizeX+i+x]; } MPI_Send(U_up_send, tempXsize-1, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD); MPI_Send(V_up_send, tempXsize-1, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_up_import, tempXsize-1, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_up_import, tempXsize-1, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == (local_sizeY-1)) { u_up = U_up_import[x-1]; v_up = V_up_import[x-1]; } else{ u_up = U[x+(1+y)*local_sizeX]; v_up = V[x+(1+y)*local_sizeX]; } // Now integrate U_next[x+y*local_sizeX] = Dt * ( c*( u_right - 2*U[x+y*local_sizeX] + U[x-1+y*local_sizeX] ) / (Dx*Dx) + c*( u_up - 2*U[x+y*local_sizeX] + U[x+(y-1)*local_sizeX] ) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (U[x+y*local_sizeX] - U[x+(y-1)*local_sizeX]) / Dy - (ax + b*U[x+y*local_sizeX]) * (U[x+y*local_sizeX] - U[x-1+y*local_sizeX]) / Dx ) + U[x+y*local_sizeX]; V_next[x+y*local_sizeX] = Dt * ( c*( v_right - 2*V[x+y*local_sizeX] + V[x-1+y*local_sizeX] ) / (Dx*Dx) + c*( v_up - 2*V[x+y*local_sizeX] + V[x+(y-1)*local_sizeX] ) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (V[x+y*local_sizeX] - V[x+(y-1)*local_sizeX]) / Dy - (ax + b*U[x+y*local_sizeX]) * (V[x+y*local_sizeX] - V[x-1+y*local_sizeX]) / Dx ) + V[x+y*local_sizeX]; } } // Prepare vector for next time interation for (int i = 0; i < local_sizeX*local_sizeY; i++) { U[i] = U_next[i]; V[i] = V_next[i]; } } } // Close bottom left corner else if(rank == Px*(Py-1)) // Process in the top left corner of the domain { if(Px == 1) { tempXsize = (local_sizeX-1); } else { tempXsize = (local_sizeX); U_right_send = new double[local_sizeY-1]; V_right_send = new double[local_sizeY-1]; U_right_import = new double[local_sizeY-1]; V_right_import = new double[local_sizeY-1]; } U_down_send = new double[tempXsize-1]; V_down_send = new double[tempXsize-1]; U_down_import = new double[tempXsize-1]; V_down_import = new double[tempXsize-1]; for(int T = 1; T < Nt; T++) { for (int y = 0; y < local_sizeY - 1 ; y++) { for(int x = 1; x < tempXsize; x++) { if(x == 1 && y == 0 && Px != 1) // exchange data with right process { for(int i = 0; i < local_sizeY-1; i++) { U_right_send[i] = U[(y+i)*local_sizeX+(local_sizeX-1)]; V_right_send[i] = V[(y+i)*local_sizeX+(local_sizeX-1)]; } MPI_Send(U_right_send, local_sizeY-1, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD); MPI_Send(V_right_send, local_sizeY-1, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_right_import, local_sizeY-1, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_right_import, local_sizeY-1, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == (local_sizeX-1)) { u_right = U_right_import[y]; v_right = V_right_import[y]; } else{ u_right = U[x+1+y*local_sizeX]; v_right = V[x+1+y*local_sizeX]; } if(y == 0 && x == 1) // exchange data with below process { for(int i = 0; i < tempXsize-1; i++) { U_down_send[i] = U[x+i]; V_down_send[i] = V[x+i]; } MPI_Send(U_down_send, tempXsize-1, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD); MPI_Send(V_down_send, tempXsize-1, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_down_import, tempXsize-1, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_down_import, tempXsize-1, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == 0) { u_down = U_down_import[x-1]; v_down = V_down_import[x-1]; } else{ u_down = U[x+(y-1)*local_sizeX]; v_down = V[x+(y-1)*local_sizeX]; } U_next[x+y*local_sizeX] = Dt * ( c*( u_right - 2*U[x+y*local_sizeX] + U[x-1+y*local_sizeX] ) / (Dx*Dx) + c*( U[x+(y+1)*local_sizeX] - 2*U[x+y*local_sizeX] + u_down ) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (U[x+y*local_sizeX] - U[x-1+y*local_sizeX]) / Dx ) + U[x+y*local_sizeX]; V_next[x+y*local_sizeX] = Dt * ( c*( v_right - 2*V[x+y*local_sizeX] + V[x-1+y*local_sizeX] ) / (Dx*Dx) + c*( V[x+(y+1)*local_sizeX] - 2*V[x+y*local_sizeX] + v_down) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (V[x+y*local_sizeX] - v_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (V[x+y*local_sizeX] - V[x-1+y*local_sizeX]) / Dx ) + V[x+y*local_sizeX]; } } for (int i = 0; i < local_sizeX*local_sizeY; i++) { U[i] = U_next[i]; V[i] = V_next[i]; } } } // Close top left corner else // Remaining Processes in the left side of domain (w/o corner processes) { if(Px == 1) { tempXsize = (local_sizeX-1); } else { tempXsize = (local_sizeX); U_right_send = new double[local_sizeY]; V_right_send = new double[local_sizeY]; U_right_import = new double[local_sizeY]; V_right_import = new double[local_sizeY]; } U_down_send = new double[tempXsize-1]; V_down_send = new double[tempXsize-1]; U_down_import = new double[tempXsize-1]; V_down_import = new double[tempXsize-1]; U_up_send = new double[tempXsize-1]; V_up_send = new double[tempXsize-1]; U_up_import = new double[tempXsize-1]; V_up_import = new double[tempXsize-1]; for(int T = 1; T < Nt; T++) { for (int y = 0; y < local_sizeY ; y++) { for(int x = 1; x < tempXsize; x++) { if(x == 1 && y == 0 && Px != 1) // exchange data with right process { for(int i = 0; i < local_sizeY; i++) { U_right_send[i] = U[(y+i)*local_sizeX+(local_sizeX-1)]; V_right_send[i] = V[(y+i)*local_sizeX+(local_sizeX-1)]; } MPI_Send(U_right_send, local_sizeY, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD); MPI_Send(V_right_send, local_sizeY, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_right_import, local_sizeY, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_right_import, local_sizeY, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == local_sizeX-1) { u_right = U_right_import[y]; v_right = V_right_import[y]; } else{ u_right = U[x+1+y*local_sizeX]; v_right = V[x+1+y*local_sizeX]; } if(y == 0 && x == 1) // exchange data with below process { for(int i = 0; i < tempXsize-1; i++) { U_down_send[i] = U[y*local_sizeX+x+i]; V_down_send[i] = V[y*local_sizeX+x+i]; } MPI_Send(U_down_send, tempXsize-1, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD); MPI_Send(V_down_send, tempXsize-1, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_down_import, tempXsize-1, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_down_import, tempXsize-1, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == 0) { u_down = U_down_import[x-1]; v_down = V_down_import[x-1]; } else{ u_down = U[x+(y-1)*local_sizeX]; v_down = V[x+(y-1)*local_sizeX]; } if(y == 0 && x == 1) // exchange data with above process { for(int i = 0; i < tempXsize-1; i++) { U_up_send[i] = U[(local_sizeY-1)*local_sizeX+x+i]; V_up_send[i] = V[(local_sizeY-1)*local_sizeX+x+i]; } MPI_Send(U_up_send, tempXsize-1, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD); MPI_Send(V_up_send, tempXsize-1, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_up_import, tempXsize-1, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_up_import, tempXsize-1, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == local_sizeY -1) { u_up = U_up_import[x-1]; v_up = V_up_import[x-1]; } else{ u_up = U[x+(y+1)*local_sizeX]; v_up = V[x+(y+1)*local_sizeX]; } U_next[x+y*local_sizeX] = Dt * ( c*( u_right - 2*U[x+y*local_sizeX] + U[x-1+y*local_sizeX] ) / (Dx*Dx) + c*( u_up - 2*U[x+y*local_sizeX] + u_down ) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (U[x+y*local_sizeX] - U[x-1+y*local_sizeX]) / Dx ) + U[x+y*local_sizeX]; V_next[x+y*local_sizeX] = Dt * ( c*( v_right - 2*V[x+y*local_sizeX] + V[x-1+y*local_sizeX] ) / (Dx*Dx) + c*( v_up - 2*V[x+y*local_sizeX] + v_down) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (V[x+y*local_sizeX] - v_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (V[x+y*local_sizeX] - V[x-1+y*local_sizeX]) / Dx ) + V[x+y*local_sizeX]; } } for (int i = 0; i < local_sizeX*local_sizeY; i++) { U[i] = U_next[i]; V[i] = V_next[i]; } } } // Close processes on the left edge w/o corners } //Close processes on the left edge else if((rank+1)%Px == 0)// Now consider the domain's right edge processes { if(rank == Px-1) // right lower corner process { if(Py == 1) { tempYsize = local_sizeY-1; } else { tempYsize = local_sizeY; U_up_send = new double[local_sizeX -1]; V_up_send = new double[local_sizeX -1]; U_up_import = new double[local_sizeX -1]; V_up_import = new double[local_sizeX -1]; } U_left_send = new double[tempYsize -1]; V_left_send = new double[tempYsize -1]; U_left_import = new double[tempYsize -1]; V_left_import = new double[tempYsize -1]; for(int T = 1; T < Nt; T++) { for(int y = 1; y < tempYsize; y++) { for (int x = 0; x < local_sizeX - 1; x++) { if(x == 0 && y == 1) // exchange data with left process { for(int i = 0; i < tempYsize-1; i++) { U_left_send[i] = U[(y+i)*local_sizeX+x]; V_left_send[i] = V[(y+i)*local_sizeX+x]; } MPI_Send(U_left_send, tempYsize -1, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD); MPI_Send(V_left_send, tempYsize -1, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_left_import, tempYsize -1, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_left_import, tempYsize -1, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == 0) { u_left = U_left_import[y-1]; v_left = V_left_import[y-1]; } else{ u_left = U[x-1+y*local_sizeX]; v_left = V[x-1+y*local_sizeX]; } if(y == 1 && x == 0 && Py != 1) // exchange data with above process { for(int i = 0; i < local_sizeX -1; i++) { U_up_send[i] = U[(local_sizeY-1)*local_sizeX+x+i]; V_up_send[i] = V[(local_sizeY-1)*local_sizeX+x+i]; } MPI_Send(U_up_send, local_sizeX -1, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD); MPI_Send(V_up_send, local_sizeX -1, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_up_import, local_sizeX -1, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_up_import, local_sizeX -1, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == local_sizeY -1) { u_up = U_up_import[x]; v_up = V_up_import[x]; } else{ u_up = U[x+(1+y)*local_sizeX]; v_up = V[x+(1+y)*local_sizeX]; } U_next[x+y*local_sizeX] = Dt * ( c*( U[x+1+y*local_sizeX] - 2*U[x+y*local_sizeX] + u_left ) / (Dx*Dx) + c*( u_up - 2*U[x+y*local_sizeX] + U[x+(y-1)*local_sizeX] ) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (U[x+y*local_sizeX] - U[x+(y-1)*local_sizeX]) / Dy - (ax + b*U[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_left) / Dx ) + U[x+y*local_sizeX]; V_next[x+y*local_sizeX] = Dt * ( c*( V[x+1+y*local_sizeX] - 2*V[x+y*local_sizeX] + v_left ) / (Dx*Dx) + c*( v_up - 2*V[x+y*local_sizeX] + V[x+(y-1)*local_sizeX]) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (V[x+y*local_sizeX] - V[x+(y-1)*local_sizeX]) / Dy - (ax + b*U[x+y*local_sizeX]) * (V[x+y*local_sizeX] - v_left) / Dx ) + V[x+y*local_sizeX]; } } for (int i = 0; i < local_sizeX*local_sizeY; i++) { U[i] = U_next[i]; V[i] = V_next[i]; } } } // Close bottom right corner else if(rank == (Px*Py-1)) // right top corner { U_left_send = new double[local_sizeY -1]; V_left_send = new double[local_sizeY -1]; U_left_import = new double[local_sizeY -1]; V_left_import = new double[local_sizeY -1]; U_down_send = new double[local_sizeX -1]; V_down_send = new double[local_sizeX -1]; U_down_import = new double[local_sizeX -1]; V_down_import = new double[local_sizeX -1]; for(int T = 1; T < Nt; T++) { for(int y = 0; y < local_sizeY-1; y++) { for (int x = 0; x < local_sizeX -1 ; x++) { if(y == 0 && x == 0) // call left adjacent process { for(int i = 0; i < local_sizeY -1; i++) { U_left_send[i] = U[(y+i)*local_sizeX+x]; V_left_send[i] = V[(y+i)*local_sizeX+x]; } MPI_Send(U_left_send, local_sizeY -1, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD); MPI_Send(V_left_send, local_sizeY -1, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_left_import, local_sizeY -1, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_left_import, local_sizeY -1, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == 0) { u_left = U_left_import[y]; v_left = V_left_import[y]; } else{ u_left = U[x-1+y*local_sizeX]; v_left = V[x-1+y*local_sizeX]; } if(y == 0 && x == 0) // calling down adjacent process { for(int i = 0; i < local_sizeX -1; i++) { U_down_send[i] = U[y*local_sizeX+x+i]; V_down_send[i] = V[y*local_sizeX+x+i]; } MPI_Send(U_down_send, local_sizeX -1, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD); MPI_Send(V_down_send, local_sizeX -1, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_down_import, local_sizeX -1, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_down_import, local_sizeX -1, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == 0) { u_down = U_down_import[x]; v_down = V_down_import[x]; } else{ u_down = U[x+(y-1)*local_sizeX]; v_down = V[x+(y-1)*local_sizeX]; } U_next[x+y*local_sizeX] = Dt * ( c*( U[x+1+y*local_sizeX] - 2*U[x+y*local_sizeX] + u_left ) / (Dx*Dx) + c*( U[x+(y+1)*local_sizeX] - 2*U[x+y*local_sizeX] + u_down ) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_left) / Dx ) + U[x+y*local_sizeX]; V_next[x+y*local_sizeX] = Dt * ( c*( V[x+1+y*local_sizeX] - 2*V[x+y*local_sizeX] + v_left ) / (Dx*Dx) + c*( V[x+(y+1)*local_sizeX] - 2*V[x+y*local_sizeX] + v_down) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (V[x+y*local_sizeX] - v_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (V[x+y*local_sizeX] - v_left) / Dx ) + V[x+y*local_sizeX]; } } for (int i = 0; i < local_sizeX*local_sizeY; i++) { U[i] = U_next[i]; V[i] = V_next[i]; } } } // Close right top corner else // Processes on the right side w/o corners { for(int T = 1; T < Nt; T++) { for (int y = 0; y < local_sizeY ; y++) { for(int x = 0; x < local_sizeX-1; x++) { if(x == 0 && y == 0) // exchange data with left process { U_left_send = new double[local_sizeY]; V_left_send = new double[local_sizeY]; U_left_import = new double[local_sizeY]; V_left_import = new double[local_sizeY]; for(int i = 0; i < local_sizeY; i++) { U_left_send[i] = U[(y+i)*local_sizeX+x]; V_left_send[i] = V[(y+i)*local_sizeX+x]; } MPI_Send(U_left_send, local_sizeY, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD); MPI_Send(V_left_send, local_sizeY, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_left_import, local_sizeY, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_left_import, local_sizeY, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == 0) { u_left = U_left_import[y]; v_left = V_left_import[y]; } else{ u_left = U[x-1+y*local_sizeX]; v_left = V[x-1+y*local_sizeX]; } if(y == 0 && x == 0) // calling down adjacent process { U_down_send = new double[local_sizeX -1]; V_down_send = new double[local_sizeX -1]; U_down_import = new double[local_sizeX -1]; V_down_import = new double[local_sizeX -1]; for(int i = 0; i < local_sizeX -1; i++) { U_down_send[i] = U[y*local_sizeX+x+i]; V_down_send[i] = V[y*local_sizeX+x+i]; } MPI_Send(U_down_send, local_sizeX -1, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD); MPI_Send(V_down_send, local_sizeX -1, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_down_import, local_sizeX -1, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_down_import, local_sizeX -1, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == 0) { u_down = U_down_import[x]; v_down = V_down_import[x]; } else{ u_down = U[x+(y-1)*local_sizeX]; v_down = V[x+(y-1)*local_sizeX]; } if(y == 0 && x == 0) // exchange data with above process { U_up_send = new double[local_sizeX -1]; V_up_send = new double[local_sizeX -1]; U_up_import = new double[local_sizeX -1]; V_up_import = new double[local_sizeX -1]; for(int i = 0; i < local_sizeX -1; i++) { U_up_send[i] = U[(local_sizeY-1)*local_sizeX+x+i]; V_up_send[i] = V[(local_sizeY-1)*local_sizeX+x+i]; } MPI_Send(U_up_send, local_sizeX -1, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD); MPI_Send(V_up_send, local_sizeX -1, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_up_import, local_sizeX -1, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_up_import, local_sizeX -1, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == local_sizeY -1) { u_up = U_up_import[x]; v_up = V_up_import[x]; } else{ u_up = U[x+(1+y)*local_sizeX]; v_up = V[x+(1+y)*local_sizeX]; } U_next[x+y*local_sizeX] = Dt * ( c*( U[x+1+y*local_sizeX] - 2*U[x+y*local_sizeX] + u_left ) / (Dx*Dx) + c*( u_up - 2*U[x+y*local_sizeX] + u_down ) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_left) / Dx ) + U[x+y*local_sizeX]; V_next[x+y*local_sizeX] = Dt * ( c*( V[x+1+y*local_sizeX] - 2*V[x+y*local_sizeX] + v_left) / (Dx*Dx) + c*( v_up - 2*V[x+y*local_sizeX] + v_down) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (V[x+y*local_sizeX] -v_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (V[x+y*local_sizeX] - v_left) / Dx ) + V[x+y*local_sizeX]; } } for (int i = 0; i < local_sizeX*local_sizeY; i++) { U[i] = U_next[i]; V[i] = V_next[i]; } } } // Close right edge processes w/o corners } // Close processes on the right edge of domain else if(rank > 0 && rank < Px-1) // Now consider bottom edge processes, w/o corners { if(Py == 1) { tempYsize = local_sizeY-1; } else { tempYsize = local_sizeY; U_up_send = new double[local_sizeX]; V_up_send = new double[local_sizeX]; U_up_import = new double[local_sizeX]; V_up_import = new double[local_sizeX]; } U_left_send = new double[tempYsize -1]; V_left_send = new double[tempYsize -1]; U_left_import = new double[tempYsize -1]; V_left_import = new double[tempYsize -1]; U_right_send = new double[tempYsize -1]; V_right_send = new double[tempYsize -1]; U_right_import = new double[tempYsize -1]; V_right_import = new double[tempYsize -1]; for(int T = 1; T < Nt; T++) { for (int y = 1; y < tempYsize ; y++) { for(int x = 0; x < local_sizeX; x++) { if(y == 1 && x == 0 && Py != 1) // calling above adjacent process { for(int i = 0; i < local_sizeX ; i++) { U_up_send[i] = U[(local_sizeY-1)*local_sizeX+x+i]; V_up_send[i] = V[(local_sizeY-1)*local_sizeX+x+i]; } MPI_Send(U_up_send, local_sizeX, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD); MPI_Send(V_up_send, local_sizeX, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_up_import, local_sizeX, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_up_import, local_sizeX, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == local_sizeY-1) { u_up = U_up_import[x]; v_up = V_up_import[x]; } else{ u_up = U[x+(y+1)*local_sizeX]; v_up = V[x+(y+1)*local_sizeX]; } if(y == 1 && x == 0) // calling left adjacent process { for(int i = 0; i < tempYsize -1; i++) { U_left_send[i] = U[(y+i)*local_sizeX+x]; V_left_send[i] = V[(y+i)*local_sizeX+x]; } MPI_Send(U_left_send, tempYsize -1, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD); MPI_Send(V_left_send, tempYsize -1, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_left_import, tempYsize -1, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_left_import, tempYsize -1, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == 0) { u_left = U_left_import[y-1]; v_left = V_left_import[y-1]; } else{ u_left = U[x-1+y*local_sizeX]; v_left = V[x-1+y*local_sizeX]; } if(y == 1 && x == 0) // calling right adjacent process { for(int i = 0; i < tempYsize -1; i++) { U_right_send[i] = U[(y+i)*local_sizeX+local_sizeX-1]; V_right_send[i] = V[(y+i)*local_sizeX+local_sizeX-1]; } MPI_Send(U_right_send, tempYsize -1, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD); MPI_Send(V_right_send, tempYsize -1, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_right_import, tempYsize -1, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_right_import, tempYsize -1, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == local_sizeX-1) { u_right = U_right_import[y-1]; v_right = V_right_import[y-1]; } else{ u_right = U[x+1+y*local_sizeX]; v_right = V[x+1+y*local_sizeX]; } U_next[x+y*local_sizeX] = Dt * ( c*( u_right - 2*U[x+y*local_sizeX] + u_left ) / (Dx*Dx) + c*( u_up - 2*U[x+y*local_sizeX] + U[x+(y-1)*local_sizeX] ) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (U[x+y*local_sizeX] - U[x+(y-1)*local_sizeX]) / Dy - (ax + b*U[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_left) / Dx ) + U[x+y*local_sizeX]; V_next[x+y*local_sizeX] = Dt * ( c*( v_right - 2*V[x+y*local_sizeX] + v_left) / (Dx*Dx) + c*( v_up - 2*V[x+y*local_sizeX] + V[x+(y-1)*local_sizeX]) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (V[x+y*local_sizeX] -V[x+(y-1)*local_sizeX]) / Dy - (ax + b*U[x+y*local_sizeX]) * (V[x+y*local_sizeX] - v_left) / Dx ) + V[x+y*local_sizeX]; } } for (int i = 0; i < local_sizeX*local_sizeY; i++) { U[i] = U_next[i]; V[i] = V_next[i]; } } } // Close lower edge processes w/o corners else if(rank > (Py-1)*Px && rank < Py*Px-1 ) // top edge processes w/o corners processes { U_down_send = new double[local_sizeX]; V_down_send = new double[local_sizeX]; U_down_import = new double[local_sizeX]; V_down_import = new double[local_sizeX]; U_left_send = new double[local_sizeY -1]; V_left_send = new double[local_sizeY -1]; U_left_import = new double[local_sizeY -1]; V_left_import = new double[local_sizeY -1]; U_right_send = new double[local_sizeY -1]; V_right_send = new double[local_sizeY -1]; U_right_import = new double[local_sizeY -1]; V_right_import = new double[local_sizeY -1]; for(int T = 1; T < Nt; T++) { for (int y = 0; y < local_sizeY-1 ; y++) { for(int x = 0; x < local_sizeX; x++) { if(y == 0 && x == 0) // calling below adjacent process { for(int i = 0; i < local_sizeX ; i++) { U_down_send[i] = U[y*local_sizeX+x+i]; V_down_send[i] = V[y*local_sizeX+x+i]; } MPI_Send(U_down_send, local_sizeX, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD); MPI_Send(V_down_send, local_sizeX, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_down_import, local_sizeX, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_down_import, local_sizeX, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == 0) { u_down = U_down_import[x]; v_down = V_down_import[x]; } else{ u_down = U[x+(y-1)*local_sizeX]; v_down = V[x+(y-1)*local_sizeX]; } if(y == 0 && x == 0) // calling left adjacent process { for(int i = 0; i < local_sizeY -1; i++) { U_left_send[i] = U[(y+i)*local_sizeX+x]; V_left_send[i] = V[(y+i)*local_sizeX+x]; } MPI_Send(U_left_send, local_sizeY -1, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD); MPI_Send(V_left_send, local_sizeY -1, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_left_import, local_sizeY -1, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_left_import, local_sizeY -1, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == 0) { u_left = U_left_import[y]; v_left = V_left_import[y]; } else{ u_left = U[x-1+y*local_sizeX]; v_left = V[x-1+y*local_sizeX]; } if(y == 0 && x == 0) // calling right adjacent process { for(int i = 0; i < local_sizeY -1; i++) { U_right_send[i] = U[(y+i)*local_sizeX+local_sizeX-1]; V_right_send[i] = V[(y+i)*local_sizeX+local_sizeX-1]; } MPI_Send(U_right_send, local_sizeY -1, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD); MPI_Send(V_right_send, local_sizeY -1, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_right_import, local_sizeY -1, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_right_import, local_sizeY -1, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == local_sizeX-1) { u_right = U_right_import[y]; v_right = V_right_import[y]; } else{ u_right = U[x+1+y*local_sizeX]; v_right = V[x+1+y*local_sizeX]; } U_next[x+y*local_sizeX] = Dt * ( c*( u_right - 2*U[x+y*local_sizeX] + u_left ) / (Dx*Dx) + c*( U[x+(y+1)*local_sizeX] - 2*U[x+y*local_sizeX] + u_down ) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_left) / Dx ) + U[x+y*local_sizeX]; V_next[x+y*local_sizeX] = Dt * ( c*( v_right - 2*V[x+y*local_sizeX] + v_left) / (Dx*Dx) + c*( V[x+(y+1)*local_sizeX] - 2*V[x+y*local_sizeX] + v_down) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (V[x+y*local_sizeX] -v_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (V[x+y*local_sizeX] - v_left) / Dx ) + V[x+y*local_sizeX]; // Integrate } } for (int i = 0; i < local_sizeX*local_sizeY; i++) { U[i] = U_next[i]; V[i] = V_next[i]; } } } // Close ranks whoch belong to the top edge w/o corners else // At last consider the middle processes, those inside domain (not boundary) { U_right_send = new double[local_sizeY]; V_right_send = new double[local_sizeY]; U_right_import = new double[local_sizeY]; V_right_import = new double[local_sizeY]; U_left_send = new double[local_sizeY]; V_left_send = new double[local_sizeY]; U_left_import = new double[local_sizeY]; V_left_import = new double[local_sizeY]; U_down_send = new double[local_sizeX]; V_down_send = new double[local_sizeX]; U_down_import = new double[local_sizeX]; V_down_import = new double[local_sizeX]; U_up_send = new double[local_sizeX]; V_up_send = new double[local_sizeX]; U_up_import = new double[local_sizeX]; V_up_import = new double[local_sizeX]; for(int T = 1; T < Nt; T++) { for (int y = 0; y < local_sizeY ; y++) { for(int x = 0; x < local_sizeX; x++) { if(y == 0 && x == 0) // calling right adjacent process { for(int i = 0; i < local_sizeY; i++) { U_right_send[i] = U[(y+i)*local_sizeX+local_sizeX-1]; V_right_send[i] = V[(y+i)*local_sizeX+local_sizeX-1]; } MPI_Send(U_right_send, local_sizeY , MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD); MPI_Send(V_right_send, local_sizeY , MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_right_import, local_sizeY, MPI_DOUBLE, rank+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_right_import, local_sizeY, MPI_DOUBLE, rank+1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == local_sizeX-1) { u_right = U_right_import[y]; v_right = V_right_import[y]; } else{ u_right = U[x+1+y*local_sizeX]; v_right = V[x+1+y*local_sizeX]; } if(y == 0 && x == 0) // calling left adjacent process { for(int i = 0; i < local_sizeY; i++) { U_left_send[i] = U[(y+i)*local_sizeX+x]; V_left_send[i] = V[(y+i)*local_sizeX+x]; } MPI_Send(U_left_send, local_sizeY, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD); MPI_Send(V_left_send, local_sizeY, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_left_import, local_sizeY, MPI_DOUBLE, rank-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_left_import, local_sizeY, MPI_DOUBLE, rank-1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(x == 0) { u_left = U_left_import[y]; v_left = V_left_import[y]; } else{ u_left = U[x-1+y*local_sizeX]; v_left = V[x-1+y*local_sizeX]; } if(y == 0 && x == 0) // calling below adjacent process { for(int i = 0; i < local_sizeX ; i++) { U_down_send[i] = U[y*local_sizeX+x+i]; V_down_send[i] = V[y*local_sizeX+x+i]; } MPI_Send(U_down_send, local_sizeX, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD); MPI_Send(V_down_send, local_sizeX, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_down_import, local_sizeX, MPI_DOUBLE, rank-Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_down_import, local_sizeX, MPI_DOUBLE, rank-Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == 0) { u_down = U_down_import[x]; v_down = V_down_import[x]; } else{ u_down = U[x+(y-1)*local_sizeX]; v_down = V[x+(y-1)*local_sizeX]; } if(y == 0 && x == 0) // exchange data with above process { for(int i = 0; i < local_sizeX; i++) { U_up_send[i] = U[(local_sizeY-1)*local_sizeX+x+i]; V_up_send[i] = V[(local_sizeY-1)*local_sizeX+x+i]; } MPI_Send(U_up_send, local_sizeX, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD); MPI_Send(V_up_send, local_sizeX, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD); // MPI_Recv( var, count, type, src, tag, comm, status) MPI_Recv(U_up_import, local_sizeX, MPI_DOUBLE, rank+Px, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_up_import, local_sizeX, MPI_DOUBLE, rank+Px, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(y == local_sizeY -1) { u_up = U_up_import[x]; v_up = V_up_import[x]; } else{ u_up = U[x+(1+y)*local_sizeX]; v_up = V[x+(1+y)*local_sizeX]; } U_next[x+y*local_sizeX] = Dt * ( c*( u_right - 2*U[x+y*local_sizeX] + u_left ) / (Dx*Dx) + c*( u_up - 2*U[x+y*local_sizeX] + u_down ) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (U[x+y*local_sizeX] - u_left) / Dx ) + U[x+y*local_sizeX]; V_next[x+y*local_sizeX] = Dt * ( c*( v_right - 2*V[x+y*local_sizeX] + v_left) / (Dx*Dx) + c*( v_up - 2*V[x+y*local_sizeX] + v_down) / (Dy*Dy) - (ay + b*V[x+y*local_sizeX]) * (V[x+y*local_sizeX] -v_down) / Dy - (ax + b*U[x+y*local_sizeX]) * (V[x+y*local_sizeX] - v_left) / Dx ) + V[x+y*local_sizeX]; } } for (int i = 0; i < local_sizeX*local_sizeY; i++) { U[i] = U_next[i]; V[i] = V_next[i]; } } // Close integration Loop } // Close domain rank scanning delete[] U_next; delete[] V_next; } // Close multi-process integration } // Close integration function void Burgers::WriteToFile(int rank, int size) { if(size == 1) // This method is tailored for single-process, as it omits unnecessary MPI_Send and MPI_Recv { ofstream plik("VelocityField.txt", ios::out| ios::trunc); if (!plik.is_open()) { cout << "Failed to open an output file" << endl; } else { if (plik.good()) { plik << setw(16) << "X" << setw(16) << "Y" << setw(16) << "U" << setw(16) << "V" << endl; plik << endl; // make space in the output to improve readibility for (int j = 0; j < sizeY; j++) { for(int i = 0; i < sizeX; i++) { plik.precision(4); plik << setw(16) << X_local[i] << setw(16) << Y_local[j] << setw(16) << U[i+j*sizeX] << setw(16) << V[i+j*sizeX] << endl; } plik << endl; } plik.close(); } } } else// For multiple-process computation { // Each process except 0, sends its arrays to the root process if(rank != 0) { MPI_Send(&local_sizeX, 1 , MPI_INT, 0 ,0, MPI_COMM_WORLD); MPI_Send(&local_sizeY, 1 , MPI_INT, 0 ,1, MPI_COMM_WORLD); MPI_Send(U,local_sizeX*local_sizeY , MPI_DOUBLE, 0 ,2, MPI_COMM_WORLD); MPI_Send(V,local_sizeX*local_sizeY , MPI_DOUBLE, 0 ,3, MPI_COMM_WORLD); MPI_Send(X_local, local_sizeX , MPI_DOUBLE, 0 ,4, MPI_COMM_WORLD); MPI_Send(Y_local, local_sizeY , MPI_DOUBLE, 0 ,5, MPI_COMM_WORLD); } if(rank == 0) { ofstream plik("VelocityField.txt", ios::out| ios::trunc); if (!plik.is_open()) { cout << "Failed to open an output file" << endl; } else { if (plik.good()) { //plik << setw(16) << "X" << setw(16) << "Y" << setw(16) << "U" << setw(16) << "V" << endl; plik << endl; for (int j = 0; j < local_sizeY; j++) { for(int i = 0; i < local_sizeX; i++) { plik.precision(4); plik << setw(16) << fixed << X_local[i] << setw(16) << fixed<< Y_local[j] << setw(16)<< fixed << U[i+j*local_sizeX] << setw(16) << fixed << V[i+j*local_sizeX] << endl; } plik << endl; } } for(int p = 1; p < size; p++) { MPI_Recv(&import_xSize, 1, MPI_INT, p, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&import_ySize, 1, MPI_INT, p, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); U_import = new double[import_xSize*import_ySize]; V_import = new double[import_xSize*import_ySize]; X_import = new double[import_xSize]; Y_import = new double[import_ySize]; MPI_Recv(U_import, import_xSize*import_ySize , MPI_DOUBLE, p, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(V_import, import_xSize*import_ySize , MPI_DOUBLE, p, 3, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(X_import, import_xSize , MPI_DOUBLE, p, 4, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(Y_import, import_ySize , MPI_DOUBLE, p, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); for (int j = 0; j < import_ySize; j++) { for(int i = 0; i < import_xSize; i++) { if (plik.good()) { plik.precision(4); plik << setw(16) << fixed << X_import[i] << setw(16) << fixed << Y_import[j] << setw(16)<< fixed << U_import[i+j*import_xSize] << setw(16) << fixed<< V_import[i+j*import_xSize] << endl; } } plik << endl; // make space in the output to improve readibility } // Free memory and prepare for next iteeration delete[] X_import; delete[] Y_import; delete[] U_import; delete[] V_import; } plik.close(); } } } } void Burgers::CalcEnergy(int rank, int size) { if(size == 1) // This method is for single-process as it omits MPI, hence is quicker { // This is the quickest way to get the energy, explained in the report ALLuNorm = cblas_dnrm2(sizeXY,U,1); ALLvNorm = cblas_dnrm2(sizeXY,V,1); Total_Energy = 0.5 * (pow(ALLuNorm,2) + pow(ALLvNorm,2)) *Dx*Dy; cout << "Total energy is: " << Total_Energy << endl; } else // This method is for multi-process computation { ALLuNorm = cblas_dnrm2(local_sizeX*local_sizeY,U,1); ALLvNorm = cblas_dnrm2(local_sizeX*local_sizeY,V,1); Energy = 0.5 * (pow(ALLuNorm,2) + pow(ALLvNorm,2)) *Dx*Dy; MPI_Reduce(&Energy, &Total_Energy, 1, MPI_DOUBLE, MPI_SUM , 0, MPI_COMM_WORLD); if (rank == 0) { cout << endl << "Total energy is: " << Total_Energy << endl; } } }
true
a19cb09eabb8e5e8d70134533fe1906da894ccac
C++
nathan-mhk/COMP_2012_PA4
/utils.cpp
UTF-8
5,117
3.109375
3
[]
no_license
#include "utils.h" Utils::Utils() {} Utils::~Utils() { tree.release(); } bool Utils::loadDictionary(const string& text_dic) { // load the file with name text_dic, and save all characters in this->content ifstream load_file(text_dic); if (!load_file.is_open()) { cout << "Failed to load the article. Exit." << endl; return false; } ostringstream buf; char ch; while (buf && load_file.get(ch)) buf.put(ch); this->content = buf.str(); // move out the end useless '\r' of a file this->content.pop_back(); load_file.close(); // scan the string this->content, calculate the frequency table // insert your code here ... for (string::const_iterator itr = content.begin(); itr != content.end(); ++itr) { if (frequency_table.find(*itr) != frequency_table.end()) ++frequency_table[*itr]; else frequency_table[*itr] = 1; } return true; } void Utils::buildTree() { tree.loadMap(frequency_table); } void Utils::setEncodedTable() { tree.encode(encoded_table); } inline int power(int pow) { int value = 1; while (pow != 0) { value *= 2; --pow; } return value; } // Convert an 8-bit binary string to dec int binToDec(const string& binString) { int decimal = 0; string::const_iterator itr = binString.begin(); for (int i = 7; i >= 0; --i, ++itr) { if (*itr == '1') decimal += power(i); } return decimal; } // Convert decimal to 8-bit zero extende binary string void decToBin(int decimal, string& binString) { while (decimal != 0) { binString = ((decimal % 2 == 0) ? "0" : "1") + binString; decimal /= 2; } while (binString.length() != 8) binString = "0" + binString; } void Utils::saveBinDictionary(const string& bin_file) { // load key file ifstream ifile("xor_key.bin", ios::binary); if (!ifile.is_open()) { cout << "cannot load key file, exit." << endl; return; } ofstream ofile(bin_file, ios::binary); // assuming that the length of bin_code is multiple of 8 // so just for every 8 continuous {0,1} characters, intepret it as a binary byte number // for last byte you write, its valid length may be less than 8, fill the invalid bits with 0 // eg., last byte contains only 3 valid bits, 110. You should fill it as 1100 0000, and then // you need to write integer 3 (bin form: 0000 0011) as one byte at the beginning of your binary file. // after saving data into .bin file, you should print out its hex form in command line // insert your code here ... // binCode stores only 0 and 1 string binCode = ""; // Store the Huffman code of all of the char in content into binCode for (string::const_iterator itr = content.begin(); itr != content.end(); ++itr) binCode += encoded_table.find(*itr)->second; int cutOffNum = binCode.length() % 8; if (cutOffNum != 0) { // Fill (8 - cutOffNum) 0s to the end for (int i = 0; i < (8 - cutOffNum); ++i) binCode += "0"; // Convert cutOffNum to binary header string header = ""; decToBin(cutOffNum, header); binCode = header + binCode; } char key; int i = 0; while (ifile.get(key)) { // Convert the binary string to decimal byte by byte unsigned char bin = binToDec(binCode.substr(i, 8)); // XOR encryption, write to file, then print written value in hex bin = bin ^ (unsigned char)key; ofile << bin; cout << setfill('0') << setw(2) << hex << (int)bin; i += 8; } cout << dec << "\n" << endl; ofile.close(); ifile.close(); } void Utils::decode(const string& bin_file) { ifstream ifile(bin_file, ios::binary); if (!ifile.is_open()) { cout << "cannot open .bin file, stop decoding." << endl; return; } ifstream key_file("xor_key.bin", ios::binary); if (!key_file.is_open()) { cout << "cannot load key file, exit." << endl; return; } // the string used to search on huffman tree to decode as plaintext string bit_str = ""; // bin_file: stores a binary huffman code with possible extra bits at the end // key_file: decryption XOR key // search in the encoded table // insert your code here ... char byte; char key; while (key_file.get(key)) { ifile.get(byte); // XOR decrpytion, convert it to binary string, then stored it into bit_str unsigned code = (unsigned char)byte ^ (unsigned char)key; string binString = ""; decToBin((int)code, binString); bit_str += binString; } // Handle the cut off int cutOffLength = bit_str.length() - 8 - binToDec(bit_str.substr(0, 8)); bit_str = bit_str.substr(8, cutOffLength); ifile.close(); key_file.close(); // using huffman tree you've built before to decode the bit string string plaintext = tree.decode(bit_str); cout << plaintext << endl << endl; }
true
a3f79f149a6857dc364ff5c0fc5adbc9fc1499ec
C++
bobbyshashin/tesla_coding_challenge
/challenge/supercharger_graph.h
UTF-8
3,135
3.140625
3
[]
no_license
#ifndef SUPERCHARGER_GRAPH_H_ #define SUPERCHARGER_GRAPH_H_ #include <cmath> #include <limits> #include <memory> #include <queue> #include <string> #include <unordered_map> #include <vector> #include "network.h" class SuperchargerGraph { public: // delete the default constructor SuperchargerGraph() = delete; // static Maker function static std::unique_ptr<SuperchargerGraph> Make(double discretization_factor, double max_range, double speed); // Generate the graph void generateGraph(); // Given the start and goal, search for an optimal path void search(const std::string& start, const std::string& goal); private: // Private constructor SuperchargerGraph(double discretization_factor, double max_range, double speed); // Backtrace to find and output the optimal path void backtracePath(int goal_id); // Given latitude and longtitude of two superchargers, calculate the distance // between them along the great arc of earth surface double calcDistance(double lat1, double lon1, double lat2, double lon2) const; // Calculate heuristics given two superchargers' id double calcHeuristics(int id1, int id2) const; // Helper function to query the id of a supercharger given its name // return -1 if charger not found in the network int findChargerID(const std::string& name) const; // Helper function to query the name of a supercharger given its id // return empty string if charger not found in the network std::string findChargerName(int id) const; // Helper function to convert degrees to radians inline double deg2Rad(double deg) const { return deg * M_PI / 180; } // Helper functions to convert a discretized node id to the corresponding // charger id / range id (how much portion it is charged) inline int getChargerID(int node_id) const { return node_id / discretization_factor_; } inline int getRangeID(int node_id) const { return node_id % discretization_factor_; } // assuming earth is a sphere with radius 6356.752km double earth_radius_ = 6356.752; // the total number of superchargers in the network int num_chargers_; // the resolution of discretization, for example: // max_range = 320km, discretization_factor = 81 // the discretized unit range for charging is 320 / (81-1) = 4km // (0, 4, 8, ..., 316, 320) int discretization_factor_; int num_nodes_; // the maximum range (km) of the fully-charged vehicle double max_range_; // the discretized unit range (km) double unit_range_; // maximum speed (km/h) of the vehicle while travelling from charger A to B double speed_; typedef std::pair<double, int> CostID; // components for graph searching std::vector<std::vector<double>> distances_; std::unordered_map<int, std::vector<CostID>> edges_; std::vector<double> costs_; std::vector<bool> visited_; std::vector<int> parents_; std::priority_queue<std::pair<double, int>, std::vector<CostID>, std::greater<CostID>> open_list_; }; #endif
true
063bd6b34ef2f7b730ee6150dd6b086d05e1fec8
C++
akalsi87/pcsh
/include/pcsh/arena.hpp
UTF-8
1,789
2.796875
3
[]
no_license
/** * \file arena.hpp * \date Jan 28, 2016 */ #ifndef PCSH_ARENA_HPP #define PCSH_ARENA_HPP #include "pcsh/exportsym.h" #include <algorithm> #include <cstring> #include <new> #include <type_traits> namespace pcsh { ////////////////////////////////////////////////////////////////////////// /// arena ////////////////////////////////////////////////////////////////////////// class PCSH_API arena { public: arena(size_t sz = 1024); ~arena(); inline const char* create_string(const char* str) { return create_string(str, ::strlen(str)); } inline const char* create_string(const char* str, size_t len) { auto arr = create_array<char>(len + 1); ::memcpy(arr, str, len); arr[len] = '\0'; return arr; } template <class T, class... Args> inline T* create(Args&&... args) { static const bool trivialdtor = std::is_trivially_destructible<T>::value; void* mem = allocate(sizeof(T), (trivialdtor ? nullptr : &destroyer<T>::act)); return new (mem) T(std::forward<Args>(args)...); } template <class T> inline T* create_array(size_t n) { void* mem = allocate(sizeof(T) * n, nullptr); return reinterpret_cast<T*>(mem); } typedef void (*destroyfn)(void*); private: struct impl; template <class T> struct destroyer { inline static void act(void* ptr) { static_cast<T*>(ptr)->~T(); } }; void* allocate(size_t sz, destroyfn fn); impl* impl_; }; }//namespace pcsh #endif/*PCSH_ARENA_HPP*/
true
1cca477a2459cfeddecad1d118fa6aa55c6388ec
C++
patilsatish/local_beamforming
/tdoa-test.cc
UTF-8
1,507
2.546875
3
[]
no_license
/* Created on 2016-08-16 * Author: Zhang Binbin */ #include <stdio.h> #include <string.h> #include "tdoa.h" #include "ds.h" #include "data.h" static void DelaySequence(float *in_data, int num, int delay, float *out_data) { for (int i = 0; i < num; i++) { if (i - delay >= 0 && i - delay < num) { out_data[i] = in_data[i - delay]; } else { out_data[i] = 0; } } } #define NUM_CHANNEL 3 int main() { // When test this, first modify beamforming.h drop the hamming window float *delay_data1 = (float *)calloc(sizeof(float), NUM_DATA); float *delay_data2 = (float *)calloc(sizeof(float), NUM_DATA); DelaySequence(g_data, NUM_DATA, 10, delay_data1); DelaySequence(g_data, NUM_DATA, -5, delay_data2); float *all_data = (float *)calloc(sizeof(float), NUM_DATA * NUM_CHANNEL); memcpy(all_data, g_data, sizeof(float) * NUM_DATA); memcpy(all_data + NUM_DATA, delay_data1, sizeof(float) * NUM_DATA); memcpy(all_data + 2 * NUM_DATA, delay_data2, sizeof(float) * NUM_DATA); float tdoa[NUM_CHANNEL] = {0}; GccPhatTdoa(all_data, NUM_CHANNEL, NUM_DATA, 0, NUM_DATA / 2, tdoa); for (int i = 0; i < NUM_CHANNEL; i++) { printf("%d\n", tdoa[i]); } float *out = (float *)calloc(sizeof(float), NUM_DATA); DelayAndSum(all_data, NUM_CHANNEL, NUM_DATA, tdoa, out); free(delay_data1); free(delay_data2); free(all_data); free(out); printf("Done\n"); return 0; }
true
4f380f91f5568ba15a3b55f9eee6e725188917b0
C++
trarck/mylibs
/yh/io/Buffer.h
UTF-8
25,907
2.59375
3
[]
no_license
#ifndef YH_IO_BUFFER_H_ #define YH_IO_BUFFER_H_ #include "../YHMacros.h" #include "../base/Ref.h" #include "../platform/Internals.h" #include "../platform/YHStdC.h" #include "IOMacros.h" #include "IeeeHalfPrecision.h" NS_YH_IO_BEGIN /** * 字节操作类 */ class Buffer:public Ref { public: Buffer(); Buffer(size_t size); Buffer(unsigned char* data,size_t size); Buffer(unsigned char* data,size_t size,bool dataOwner); ~Buffer(); /** * @brief 读取一段数据 * 是其它读取方法的基础 * * @param position 要读取的偏移位置,从开头算起。 * @param buf 读取后要放入的地方 * @param size 要读取的数据大小 * * @return 实际读取的大小。如果大小为0,则读取错误 */ size_t readBytes(size_t position, unsigned char* buf,size_t size); /** * @brief 不安全的读取一段数据 * 主要是使用memcpy代替memmove * * @param position 要读取的偏移位置,从开头算起。 * @param buf 读取后要放入的地方 * @param size 要读取的数据大小 * * @return 实际读取的大小。如果大小为0,则读取错误 */ size_t readBytesSafe(size_t position, void* buf, size_t size); inline unsigned char readByte(size_t position) { YHASSERT(position<m_size, "Buffer::readByte out index"); return *(m_data+position); } //////////////////////////////////////////////////////////////// // unsigned //////////////////////////////////////////////////////////////// /** * @brief 读取无符号的8位整型 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline uint8_t readUInt8(size_t position) { YHASSERT(position<m_size,"Buffer::readUInt8 out index"); return *(m_data+position); } /** * @brief 读取无符号的16位整型 * 数据在data中使用小端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline uint16_t readUInt16LE(size_t position) { YHASSERT(position+YH_IO_SHORT_SIZE<=m_size,"Buffer::readUInt16LE out index"); return (*(m_data+position+1) << 8) | *(m_data+position); } /** * @brief 读取无符号的16位整型 * 数据在data中使用大端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline uint16_t readUInt16BE(size_t position) { YHASSERT(position+YH_IO_SHORT_SIZE<=m_size,"Buffer::readUInt16BE out index"); return (*(m_data+position) << 8) | *(m_data+position+1); } /** * @brief 读取无符号的32位整型 * 数据在data中使用小端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ uint32_t readUInt32LE(size_t position); /** * @brief 读取无符号的32位整型 * 数据在data中使用大端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ uint32_t readUInt32BE(size_t position); /** * @brief 读取无符号的64位整型 * 数据在data中使用小端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ uint64_t readUInt64LE(size_t position); /** * @brief 读取无符号的64位整型 * 数据在data中使用大端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ uint64_t readUInt64BE(size_t position); //////////////////////////////////////////////////////////////// // signed //////////////////////////////////////////////////////////////// /** * @brief 读取有符号的8位整型 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline int8_t readInt8(size_t position) { YHASSERT(position<m_size,"Buffer::readInt8 out index"); return (int8_t)(*(m_data+position)); // uint8_t val=readUInt8(position); // return (val & 0x80)?val:(0xff-val+1)*-1; } /** * @brief 读取有符号的16位整型 * 数据在data中使用小端保存 * 在内存中,可以直接把无符号的数转成有符号 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline int16_t readInt16LE(size_t position) { YHASSERT(position+YH_IO_SHORT_SIZE<=m_size,"Buffer::readInt16 out index"); return (int16_t)readUInt16LE(position); } /** * @brief 读取有符号的16位整型 * 数据在data中使用大端保存 * 在内存中,可以直接把无符号的数转成有符号 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline int16_t readInt16BE(size_t position) { YHASSERT(position+YH_IO_SHORT_SIZE<=m_size,"Buffer::readInt16BE out index"); return (int16_t)readUInt16BE(position); } /** * @brief 读取有符号的32位整型 * 数据在data中使用小端保存 * 在内存中,可以直接把无符号的数转成有符号 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline int32_t readInt32LE(size_t position) { YHASSERT(position+YH_IO_INT_SIZE<=m_size,"Buffer::readInt32 out index"); return (int32_t)readUInt32LE(position); } /** * @brief 读取有符号的32位整型 * 数据在data中使用大端保存 * 在内存中,可以直接把无符号的数转成有符号 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline int32_t readInt32BE(size_t position) { YHASSERT(position+YH_IO_INT_SIZE<=m_size,"Buffer::readInt32 out index"); return (int32_t)readUInt32BE(position); } /** * @brief 读取有符号的64位整型 * 数据在data中使用小端保存 * 在内存中,可以直接把无符号的数转成有符号 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline int64_t readInt64LE(size_t position) { YHASSERT(position+YH_IO_LONG_SIZE<=m_size,"Buffer::readInt64 out index"); return (int64_t)readUInt64LE(position); } /** * @brief 读取有符号的64位整型 * 数据在data中使用大端保存 * 在内存中,可以直接把无符号的数转成有符号 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline int64_t readInt64BE(size_t position) { YHASSERT(position+YH_IO_LONG_SIZE<=m_size,"Buffer::readInt64 out index"); return (int64_t)readUInt64BE(position); } //////////////////////////////////////////////////////////////// // float //////////////////////////////////////////////////////////////// /** * @brief 读取半精度的浮点数,占用2个字节 * 数据在data中使用小端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ float readFloat16LE(size_t position); /** * @brief 读取半精度的浮点数,占用2个字节 * 数据在data中使用大端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ float readFloat16BE(size_t position); /** * @brief 读取单精度的浮点数 * 数据在data中使用小端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline float readFloatLE(size_t position) { YHASSERT(position+YH_IO_INT_SIZE<=m_size,"Buffer::readFloatLE out index"); return byteToFloat<float,kLittleEndian>(m_data+position); } /** * @brief 读取单精度的浮点数 * 数据在data中使用大端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline float readFloatBE(size_t position) { YHASSERT(position+YH_IO_INT_SIZE<=m_size,"Buffer::readFloatBE out index"); return byteToFloat<float,kBigEndian>(m_data+position); } /** * @brief 读取双精度的浮点数 * 数据在data中使用小端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline double readDoubleLE(size_t position) { YHASSERT(position+8<=m_size,"Buffer::readDoubleLE out index"); return byteToFloat<double,kLittleEndian>(m_data+position); } /** * @brief 读取双精度的浮点数 * 数据在data中使用大端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline double readDoubleBE(size_t position) { YHASSERT(position+8<=m_size,"Buffer::readDoubleBE out index"); return byteToFloat<double,kBigEndian>(m_data+position); } //////////////////////////////////////////////////////////////// // fixed float 整型表示浮点数 //////////////////////////////////////////////////////////////// /** * @brief 读取8位整型浮点数,占用2个字节.8.8 * 数据在data中使用小端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline float readFixed8LE(size_t position) { return (float)readUInt16LE(position)/0x100; } /** * @brief 读取8位整型浮点数,占用2个字节 * 数据在data中使用大端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline float readFixed8BE(size_t position) { return (float)readUInt16BE(position)/0x100; } /** * @brief 读取整型浮点数,占用4个字节16.16 * 数据在data中使用小端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline float readFixedLE(size_t position) { return (float)readUInt32LE(position)/0x10000; } /** * @brief 读取整型浮点数,占用4个字节 * 数据在data中使用大端保存 * * @param position 要读取的偏移位置,从开头算起。 * * @return 读取的值 */ inline float readFixedBE(size_t position) { return (float)readUInt32BE(position)/0x10000; } // //////////////////////////////////////////////////////////////// // // 使用字节操作 // //////////////////////////////////////////////////////////////// // inline size_t readUInt8(size_t position,uint8_t* val) // { // return readBytes(position, val, sizeof(uint8_t)); // } // // inline size_t readUInt16LE(size_t position,uint16_t* val) // { // unsigned char buf[2]; // // size_t ret=readBytes(position, buf, sizeof(uint16_t)); // // if (kLittleEndian!=getEndianness()) { // swizzle(buf, 2); // } // // *val=*buf; // // return ret; // } // // inline size_t readUInt16BE(size_t position,uint16_t* val) // { // unsigned char buf[2]; // // size_t ret=readBytes(position, buf, sizeof(uint16_t)); // // if (kBigEndian!=getEndianness()) { // swizzle(buf, 2); // } // // *val=*buf; // // return ret; // } /** * @brief 写入一段数据 * @param position 要写入的偏移位置,从开头算起。 * @param buf 要写入的数据 * @param size 要写入的数据大小 * * @return 实际写入的大小。如果大小为0,则写入错误 */ size_t writeBytes(size_t position, unsigned char* buf,size_t size); /** * @brief 不安全写入一段数据 * 主要使用memcpy代替memmove * @param position 要写入的偏移位置,从开头算起。 * @param buf 要写入的数据 * @param size 要写入的数据大小 * * @return 实际写入的大小。如果大小为0,则写入错误 */ size_t writeBytesSafe(size_t position, unsigned char* buf,size_t size); /** * @brief 写入一个字节 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeByte(unsigned char value,size_t position) { if (position < m_size) { *(m_data + position) = value; return YH_IO_BYTE_SIZE; } return 0; } /** * @brief 写入无符号的8位整型 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeUInt8(uint8_t value,size_t position) { return writeByte(value,position); } /** * @brief 写入无符号的16位整型 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ size_t writeUInt16LE(uint16_t value, size_t position); /** * @brief 写入无符号的16位整型 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ size_t writeUInt16BE(uint16_t value, size_t position); /** * @brief 写入无符号的32位整型 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ size_t writeUInt32LE(uint32_t value, size_t position); /** * @brief 写入无符号的32位整型 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ size_t writeUInt32BE(uint32_t value, size_t position); /** * @brief 写入无符号的64位整型 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ size_t writeUInt64LE(uint64_t value,size_t position); /** * @brief 写入无符号的64位整型 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ size_t writeUInt64BE(uint64_t value,size_t position); /** * @brief 写入无符号的8位整型 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeInt8(int8_t value,size_t position) { return writeUInt8((uint8_t)value, position); } /** * @brief 写入无符号的16位整型 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeInt16LE(int16_t value,size_t position) { return writeUInt16LE((uint16_t)value, position); } /** * @brief 写入无符号的16位整型 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeInt16BE(uint16_t value,size_t position) { return writeUInt16BE((uint16_t)value, position); } /** * @brief 写入无符号的32位整型 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeInt32LE(int32_t value,size_t position) { return writeUInt32LE((uint32_t)value, position); } /** * @brief 写入无符号的32位整型 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeInt32BE(int32_t value,size_t position) { return writeUInt32BE((uint32_t)value, position); } /** * @brief 写入无符号的64位整型 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeInt64LE(int64_t value,size_t position) { return writeUInt64LE((uint64_t)value, position); } /** * @brief 写入无符号的64位整型 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeInt64BE(int64_t value,size_t position) { return writeUInt64BE((uint64_t)value, position); } /** * @brief 写入半精度浮点数 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeFloat16LE(float value,size_t position) { uint16_t halfInt=0; singles2halfp(&halfInt, &value); return writeUInt16LE(halfInt, position); } /** * @brief 写入半精度浮点数 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeFloat16BE(float value,size_t position) { uint16_t halfInt=0; singles2halfp(&halfInt, &value); return writeUInt16BE(halfInt, position); } /** * @brief 写入单精度浮点数 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeFloatLE(float value,size_t position) { unsigned char buf[4]; floatToByte<float, kLittleEndian>(value, buf); return writeBytes(position, buf, 4); } /** * @brief 写入单精度浮点数 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeFloatBE(float value,size_t position) { unsigned char buf[4]; floatToByte<float, kBigEndian>(value, buf); return writeBytes(position, buf, 4); } /** * @brief 写入双精度浮点数 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeDoubleLE(float value,size_t position) { unsigned char buf[8]; floatToByte<double, kLittleEndian>(value, buf); return writeBytes(position, buf, 8); } /** * @brief 写入双精度浮点数 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeDoubleBE(float value,size_t position) { unsigned char buf[8]; floatToByte<double, kBigEndian>(value, buf); return writeBytes(position, buf, 8); } /** * @brief 写入8.8固定浮点数 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeFixed8LE(float value,size_t position) { uint16_t fixedInt= (uint16_t)(value * 0x100); return writeUInt16LE(fixedInt, position); } /** * @brief 写入8.8固定浮点数 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeFixed8BE(float value,size_t position) { uint16_t fixedInt= (uint16_t)(value * 0x100); return writeUInt16BE(fixedInt, position); } /** * @brief 写入16.16固定浮点数 * 使用小端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeFixedLE(float value,size_t position) { uint32_t fixedInt= (uint32_t)(value * 0x10000); return writeUInt32LE(fixedInt, position); } /** * @brief 写入16.16固定浮点数 * 使用大端表示写入后的数据 * @param value 要写入的数据 * @param position 要写入的偏移位置,从开头算起。 * * @return 实际写入的大小。如果大小为0,则写入错误 */ inline size_t writeFixedBE(float value,size_t position) { uint32_t fixedInt= (uint32_t)(value * 0x10000); return writeUInt32BE(fixedInt, position); } /** * @brief 用固定值填充缓冲区 * 会写入开始位置,但不会写入结束位置 * @param value 要填充的数据 * @param start 开始位置,从开头算起。 * @param end 结束的位置,从开头算起。 */ void fill(unsigned char value,size_t start,size_t end); inline void fill(unsigned char value,size_t start) { fill(value, start, m_size); } inline void fill(unsigned char value) { fill(value, 0, m_size); } /** * @brief 把当前缓存区的内容copy到目标缓存区 * 包含开始位置,但不包含结束位置 * @param target 目标缓存区 * @param targetStart 目标缓存区开始位置 * @param sourceStart 当前缓存区的开始位置。 * @param sourceEnd 当前缓存区结束位置。 */ void copy(Buffer* target,size_t targetStart,size_t sourceStart,size_t sourceEnd); /** * @brief 在当前缓存区数据截取一段 * * @param start 截取的开始位置。 * @param end 截取的结束位置。 * @param size 截取的大小。 * * @return 截取段的开始指针。注意不是副本。也就是说不用删除。 */ unsigned char* slice(size_t start,size_t* size); void setData(unsigned char* data, size_t size,bool dataOwner=true); public: inline size_t getSize() { return m_size; } inline unsigned char* getData() { return m_data; } inline bool isDataOwner() { return m_dataOwner; } protected: size_t m_size; unsigned char* m_data; //表明data是否是由当前buffer创建,如果是则在buffer销毁时把data删除。 //主要用于读取大data数据时,不想重复分配内存,而buffer不会长时间存在 bool m_dataOwner; }; NS_YH_IO_END #endif // YH_IO_BUFFER_H_
true
16dc443131d0907bf3ef6b96b6a9723415dc2d6c
C++
southern-yan/OJ_code
/求最大连续bit数.cpp
GB18030
549
3.34375
3
[]
no_license
Ŀ һbyteֶӦĶ13ĶΪ0000001121 #include <iostream> #include <algorithm> using namespace std; int main() { int n; while(cin>>n) { int count=0,maxcount=0; while(n) { if(n&1) { count++; maxcount=max(count,maxcount); } else count=0; n=n>>1; } cout<<maxcount<<endl; } return 0; }
true
e40f28fd99e79808f4ccb489f222622276223353
C++
Sabuj-Kumar/Problem_Solve
/lightoj online/Light Oj Beginner/Light oj 1212 - Double Ended Queue.cpp
UTF-8
1,682
3.28125
3
[]
no_license
#include<stdio.h> #include<bits/stdc++.h> using namespace std; int main() { int test,value,i,j; scanf("%d",&test); for(i = 1; i <= test; i++) { deque<int> input; int s,limit; cout<<"Case " << i <<":\n"; cin>>s; cin>>limit; for(j = 0; j < limit; j++) { string a; cin>>a; if(a == "pushLeft" || a == "pushRight") { cin>>value; if(input.size() < s) { if(a == "pushLeft") { input.push_front(value); cout<<"Pushed in left: "<<input.front()<<"\n"; } else { input.push_back(value); cout<<"Pushed in right: "<<input.back()<<"\n"; } } else cout<<"The queue is full\n"; } else if(a == "popLeft" || a == "popRight") { if(input.size() > 0) { if(a == "popLeft") { cout<<"Popped from left: "<<input.front()<<"\n"; input.pop_front(); } else { cout<<"Popped from right: "<<input.back()<<"\n"; input.pop_back(); } } else cout<<"The queue is empty\n"; } } } return 0; }
true
6c6a5bd044d94ee3d96f711e5b4af3f4b0aae45a
C++
LUS1N/EAAA_ProgrammingLanguagesExam_CPP
/ProgLangExamCpp/Crate.cpp
UTF-8
866
3.203125
3
[]
no_license
#include "stdafx.h" #include "Crate.h" Crate::Crate() { } Crate::~Crate() { for (auto const& value : *this->products) { delete value; } } float Crate::calculatePrice() { float basePrice = calculateBasePrice(); int bonus = calculateBonusPercentage(); basePrice += basePrice / 100.0 * bonus; return basePrice; } vector<Product*>* Crate::getProducts() { return products; } void Crate::setProducts(vector<Product*>*products) { this->products = products; } float Crate::calculateBasePrice() { float price = 0; for (auto const& product: *this->products) { price += product->price; } return price; } int Crate::calculateBonusPercentage() { int products = this->products->size(); if (products > 15) return 10; if (products > 10) return 7; if (products > 5) return 5; return 0; }
true
eee25c7e29596c8286d6ec3d02b569803584e51d
C++
Passw/BPlusTreeBase
/src/BPlusTreeBaseInternalNode.hpp
UTF-8
12,479
2.984375
3
[ "MIT" ]
permissive
#ifndef BPLUSTREEBASEINTERNALNODE_H #define BPLUSTREEBASEINTERNALNODE_H #include <vector> #include <memory> #include <functional> #include "BPlusTreeBaseNode.hpp" __B_PLUS_TREE_NODE_TEMPLATE__ class BPlusTreeBaseInternalNode : public __B_PLUS_TREE_BASENODE_CLASS__ { typedef __B_PLUS_TREE_BASENODE_CLASS__ Node; typedef __B_PLUS_TREE_BASEINTERNALNODE_CLASS__ InternalNode; typedef std::shared_ptr<Node> node_ptr; typedef std::vector<Key> keys_type; typedef std::vector<node_ptr> nodes_type; typedef typename nodes_type::iterator nodes_type_iterator; typedef typename keys_type::iterator keys_type_iterator; public: BPlusTreeBaseInternalNode(); BPlusTreeBaseInternalNode(keys_type* keys, nodes_type* nodes); ~BPlusTreeBaseInternalNode(); void release_node(node_ptr node); void set_keys(keys_type* keys); void set_nodes(nodes_type* nodes); keys_type* get_keys(); nodes_type* get_nodes(); void add_keys(int ind, Key key); void add_keys(int ind, keys_type_iterator s, keys_type_iterator e); void add_nodes(int ind, node_ptr node); void add_nodes(int ind, nodes_type_iterator s, nodes_type_iterator e); void remove_keys(int ind); void remove_keys(keys_type_iterator s, keys_type_iterator e); void remove_nodes(int ind); void remove_nodes(nodes_type_iterator s, nodes_type_iterator e); void shift_left(node_ptr parent); void shift_right(node_ptr parent); void join_left(node_ptr parent); void join_right(node_ptr parent); void split(node_ptr node, node_ptr parent); node_ptr get_node(int index); int size(); int keys_size(); int nodes_size(); int get_index(const Key& key, bool to_lower = false); int get_index(Node* node); node_ptr first_child_node(); node_ptr last_child_node(); node_ptr find(const Key& key); node_ptr find_next(const Key& key); node_ptr find_prev(const Key& key); keys_type_iterator keys_iterator(); keys_type_iterator keys_iterator_end(); nodes_type_iterator nodes_iterator(); nodes_type_iterator nodes_iterator_end(); bool is_leaf(); protected: keys_type* child_keys = nullptr; nodes_type* child_nodes = nullptr; }; __B_PLUS_TREE_NODE_TEMPLATE__ __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::BPlusTreeBaseInternalNode() { child_keys = new keys_type(); child_nodes = new nodes_type(); } __B_PLUS_TREE_NODE_TEMPLATE__ __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::BPlusTreeBaseInternalNode(keys_type* keys, nodes_type* nodes) { set_keys(keys); set_nodes(nodes); } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::keys_type* __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::get_keys() { return child_keys; } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::nodes_type* __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::get_nodes() { return child_nodes; } __B_PLUS_TREE_NODE_TEMPLATE__ __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::~BPlusTreeBaseInternalNode() { if(child_keys){ delete child_keys; } if(child_nodes){ for(int i=0;i<nodes_size();i++){ release_node((*child_nodes)[i]); } delete child_nodes; } } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::release_node(node_ptr node) { // TODO: replace with allocator methods // No need to delete smart ptr // delete node; } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::set_keys(keys_type* keys) { child_keys = keys; } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::set_nodes(nodes_type* nodes) { child_nodes = nodes; } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::add_keys(int ind, Key key) { child_keys->insert(child_keys->begin()+ind, key); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::add_keys(int ind, keys_type_iterator s, keys_type_iterator e) { child_keys->insert(child_keys->begin()+ind, s, e); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::remove_keys(int ind) { child_keys->erase(child_keys->begin()+ind); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::remove_keys(keys_type_iterator s, keys_type_iterator e) { child_keys->erase(s, e); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::add_nodes(int ind, node_ptr node) { child_nodes->insert(child_nodes->begin()+ind, node); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::add_nodes(int ind, nodes_type_iterator s, nodes_type_iterator e){ child_nodes->insert(child_nodes->begin()+ind, s, e); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::remove_nodes(int ind) { child_nodes->erase(child_nodes->begin()+ind); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::remove_nodes(nodes_type_iterator s, nodes_type_iterator e) { child_nodes->erase(s, e); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::shift_right(node_ptr parent) { // Get index of shift node int index = parent->get_index(this)+1; // Get Node to shift node_ptr next = parent->get_node(index); // Get key iterator between nodes to shift keys_type_iterator divider = parent->keys_iterator()+(index-1); // Get key between nodes Key shift_key = *divider; // Add divide key to this node this->add_keys(this->keys_size(), shift_key); // Add new child from next node this->add_nodes(this->nodes_size(), next->first_child_node()); // Update key between nodes *divider = *(next->keys_iterator()); // Remove shifted items from next node next->remove_keys(0); next->remove_nodes(0); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::shift_left(node_ptr parent) { // Get index of shift node int index = parent->get_index(this)-1; // Get Node to shift node_ptr prev = parent->get_node(index); // Get key iterator between nodes to shift keys_type_iterator divider = parent->keys_iterator()+(index); // Get key between nodes Key shift_key = *divider; // Add divide key to this node this->add_keys(0, shift_key); // Add new child from prev node this->add_nodes(0, prev->last_child_node()); // Update key between nodes *divider = *(--prev->keys_iterator_end()); // Remove shifted items from prev node prev->remove_keys(prev->keys_size()-1); prev->remove_nodes(prev->nodes_size()-1); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::join_left(node_ptr parent) { // Get index of join node int index = parent->get_index(this)-1; // Get Node to join node_ptr prev = parent->get_node(index); // Get key iterator between nodes to join keys_type_iterator divider = parent->keys_iterator()+(index); // Get key between nodes Key join_key = *divider; // Add divide key to this node this->add_keys(0, join_key); // Move all items from left node this->add_keys(0, prev->keys_iterator(), prev->keys_iterator_end()); this->add_nodes(0, prev->nodes_iterator(), prev->nodes_iterator_end()); prev->remove_nodes(prev->nodes_iterator(), prev->nodes_iterator_end()); // Delete joined items form parent parent->remove_keys(index); parent->remove_nodes(index); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::join_right(node_ptr parent) { // Get index of join node int index = parent->get_index(this)+1; // Get Node to join node_ptr next = parent->get_node(index); // Get key iterator between nodes to join keys_type_iterator divider = parent->keys_iterator()+(index-1); // Get key between nodes Key join_key = *divider; // Add divide key to this node this->add_keys(keys_size(), join_key); // Join all items from left node this->add_keys(keys_size(), next->keys_iterator(), next->keys_iterator_end()); this->add_nodes(nodes_size(), next->nodes_iterator(), next->nodes_iterator_end()); next->remove_nodes(next->nodes_iterator(), next->nodes_iterator_end()); // Delete joined items form parent parent->remove_keys(index-1); parent->remove_nodes(index); } __B_PLUS_TREE_NODE_TEMPLATE__ void __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::split(node_ptr node, node_ptr parent) { // Get iterators to move to new node keys_type_iterator kstart = keys_iterator(); keys_type_iterator kend = keys_iterator() + keys_size()/2; nodes_type_iterator nstart = nodes_iterator(); nodes_type_iterator nend = nodes_iterator() + nodes_size()/2; // Copy items to another node node->add_keys(0, kstart, kend); node->add_nodes(0, nstart, nend); // Get the return key Key ret = *kend; // Remove moved items remove_keys(kstart, kend + 1); remove_nodes(nstart, nend); // Insert to parent int index = parent->get_index(this); parent->add_keys(index, ret); parent->add_nodes(index, node); } __B_PLUS_TREE_NODE_TEMPLATE__ inline bool __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::is_leaf() { return false; } __B_PLUS_TREE_NODE_TEMPLATE__ int __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::get_index(const Key& key, bool to_lower) { int mn=0,mx=keys_size()-1,md; int res = keys_size(); while(mn<=mx){ md = (mn+mx)/2; if((*child_keys)[md] <= key){ mn = md+1; } else{ mx = md-1; res = md; } } return res; } __B_PLUS_TREE_NODE_TEMPLATE__ int __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::get_index(Node* node) { int sz = nodes_size(); for(int i=0;i<sz;i++){ if((*child_nodes)[i].get() == node) return i; } return sz; } __B_PLUS_TREE_NODE_TEMPLATE__ int __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::size() { return nodes_size(); } __B_PLUS_TREE_NODE_TEMPLATE__ int __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::keys_size() { return child_keys->size(); } __B_PLUS_TREE_NODE_TEMPLATE__ int __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::nodes_size() { return child_nodes->size(); } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::node_ptr __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::find(const Key& key) { int index = get_index(key); return get_node(index); } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::node_ptr __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::find_next(const Key& key) { int index = get_index(key); index++; if(index > nodes_size()-1) return nullptr; return get_node(index); } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::node_ptr __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::find_prev(const Key& key) { int index = get_index(key); index--; if(index < 0) return nullptr; return get_node(index); } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::node_ptr __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::first_child_node() { return get_node(0); } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::node_ptr __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::last_child_node() { return get_node(nodes_size()-1); } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::node_ptr __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::get_node(int index) { return (*child_nodes)[index]; } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::keys_type_iterator __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::keys_iterator() { return child_keys->begin(); } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::keys_type_iterator __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::keys_iterator_end() { return child_keys->end(); } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::nodes_type_iterator __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::nodes_iterator() { return child_nodes->begin(); } __B_PLUS_TREE_NODE_TEMPLATE__ typename __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::nodes_type_iterator __B_PLUS_TREE_BASEINTERNALNODE_CLASS__::nodes_iterator_end() { return child_nodes->end(); } #endif // BPLUSTREEBASEINTERNALNODE_H
true
1618e05a9474a95fa4b4d794093792aa20efcb7c
C++
mmmim24/CP
/random_CF/1332C.cpp
UTF-8
923
2.515625
3
[]
no_license
#include <string.h> #include <stdio.h> #define MAX(a,b) ((a>b)?a:b) using namespace std; char s[1000000], chars_c[100000], maxs[100000]; int tochange, n, k, max, chars[27]; char check(int i, char gg){ printf("checking %c - ", gg); int count = 0; for(int ix=i; ix<n; ix+=k){ if(s[ix]==gg) count++; printf("%c ", s[ix]); } printf("%d\n", count); return count; } int main(){ int t; scanf("%d", &t); while(t--){ tochange = 0; scanf("%d %d", &n, &k); scanf("%s", s); for(int i=0; i<((k%2==0)?k/2:k/2+1); i++){ max=0; memset(chars, 0, sizeof(chars)); for(int ix=i; ix<n; ix+=k){ chars[s[ix]-'a']++; if(k%2!=0 && i==k/2){ }else chars[s[(ix/k)*k+k-(ix%k)-1]-'a']++; } for(int ix=0; ix<27; ix++){ max = MAX(chars[ix], max); } int gg = (((k%2!=0 && i==k/2)?1:2)*n); tochange += gg/k - max; } printf("%d\n", tochange); } }
true
81e6530e17f457a3cc61fcde2eb91c94924ebfac
C++
Zyrst/Fallen-Stars
/Fallen Stars/SpriteSheet.h
UTF-8
893
3.046875
3
[]
no_license
#pragma once #include <SFML/System/Vector2.hpp> #include <SFML/Graphics/Rect.hpp> #include <vector> /* Note: This is a helper class for generating frames and doesn't actually contain a texture. * * Can be used to split a sprite sheet into separate frame rectangles. It simplifies generating * frames by treating the spritesheet as a grid and refering to the frames by their index. It * also makes it possible to generate a whole set of frames at once. */ class SpriteSheet { public: SpriteSheet(sf::Vector2i spriteSize, sf::Vector2i spriteSheetSize); int getFrameCount(); sf::IntRect getFrame(int index); std::vector<sf::IntRect> getFrames(int startIndex, int frameCount); std::vector<sf::IntRect> getAllFrames(); private: /* Size of one animation frame from the spritesheet */ sf::Vector2i mSpriteSize; /* Number of tiles in both axes */ sf::Vector2i mTiles; };
true
18adcc127f59e5b92030a6cd83b326a523c8e1f8
C++
techtim/trippybird
/app/src/main/jni/Utils.hpp
UTF-8
8,119
2.59375
3
[]
no_license
// // Created by Timofey Tavlintsev on 4/27/16. // #pragma once #include <EGL/egl.h> #include <GLES/gl.h> #include <vector> #include <math.h> #include <stdlib.h> #define FLT_EPSILON 1.19209290E-07F #define BUFFER_OFFSET(i) ((char*)NULL + (i)) enum SHADER_ATTRIBUTES { ATTRIB_VERTEX, ATTRIB_NORMAL, ATTRIB_UV, }; enum OBJECT_TYPES { TYPE_CYLINDER, TYPE_BIRD, TYPE_LINE, TYPE_PLANE }; struct SHADER_PARAMS { GLuint program_; GLuint light0_; GLuint material_diffuse_; GLuint material_ambient_; GLuint material_specular_; GLuint matrix_projection_; GLuint matrix_view_; GLuint object_type; GLuint color_gradient_1; GLuint color_gradient_2; }; //struct MATERIALS { // float diffuse_color[3]; // float specular_color[4]; // float ambient_color[3]; //}; struct MATERIALS { std::array<float, 3> diffuse_color; std::array<float, 4> specular_color; std::array<float, 3> ambient_color; }; struct VERTEX { std::array<float, 3> pos; std::array<float, 3> normal; std::array<float, 2> uv; }; struct CIRCLE { float x,y,z; float r; }; struct RECT_WH { float x,y,z; float width; float height; }; struct OBSTACLE { ndk_helper::Mat4 model_view; ndk_helper::Vec3 pos; RECT_WH rect; }; struct SAVED_STATE { std::vector<OBSTACLE> obstacles; ndk_helper::Vec3 birdPos; }; inline bool intersects(CIRCLE circle, RECT_WH rect) { float dist_x = fabsf(circle.x - rect.x-rect.width/2); float dist_y = fabsf(circle.y - rect.y - rect.height/2); if (dist_x > (rect.width/2 + circle.r)) { return false; } if (dist_y > (rect.height/2 + circle.r)) { return false; } if (dist_x <= (rect.width/2)) { return true; } if (dist_y <= (rect.height/2)) { return true; } double cornerDistance_sq = pow(dist_x - rect.width/2, 2) + pow(dist_y - rect.height/2, 2); return (cornerDistance_sq <= pow(circle.r, 2)); } template <class T> inline void glBufferDataFromVector(GLenum target, const std::vector<T>& v, GLenum usage) { glBufferData(target, v.size() * sizeof(T), &v[0], usage); } inline float valueMap(float value, float inputMin, float inputMax, float outputMin, float outputMax) { // , bool clamp = false if (fabs(inputMin - inputMax) < FLT_EPSILON){ return outputMin; } else { float outVal = ((value - inputMin) / (inputMax - inputMin) * (outputMax - outputMin) + outputMin); // if( clamp ){ // if(outputMax < outputMin){ // if( outVal < outputMax )outVal = outputMax; // else if( outVal > outputMin )outVal = outputMin; // }else{ // if( outVal > outputMax )outVal = outputMax; // else if( outVal < outputMin )outVal = outputMin; // } // } return outVal; } } inline ndk_helper::Vec3 rotateRad(float angle, const ndk_helper::Vec3& vec, const ndk_helper::Vec3& axis ) { ndk_helper::Vec3 v = vec; float x, y, z; v.Value(x,y,z); ndk_helper::Vec3 ax = axis; ax.Normalize(); float ax_x,ax_y,ax_z; ax.Value(ax_x,ax_y,ax_z); float sina = sin( angle ); float cosa = cos( angle ); float cosb = 1.0f - cosa; float nx= x*(ax_x*ax_x*cosb + cosa) + y*(ax_x*ax_y*cosb - ax_z*sina) + z*(ax_x*ax_z*cosb + ax_y*sina); float ny = x*(ax_y*ax_x*cosb + ax_z*sina) + y*(ax_y*ax_y*cosb + cosa) + z*(ax_y*ax_z*cosb - ax_x*sina); float nz = x*(ax_z*ax_x*cosb - ax_y*sina) + y*(ax_z*ax_y*cosb + ax_x*sina) + z*(ax_z*ax_z*cosb + cosa); return ndk_helper::Vec3(nx,ny,nz); } struct LINE_VERTEX { float pos[3]; float color[4]; }; inline void drawAxis( float size ) { GLuint vbo_; LINE_VERTEX vertices[] = { {{0,0,0}, {1.f,0,0,1.f}}, {{size,0,0}, {1,0,0,1.f}}, {{0,0,0}, {0,1.f,0,1.f}}, {{0,size,0}, {0,1.f,0,1.f}}, {{0,0,0}, {0,0,1.f,1.f}}, {{0,0,size}, {0,0,1.f,1.f}} }; glGenBuffers(1, &vbo_); glBindBuffer(GL_ARRAY_BUFFER, vbo_); glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(LINE_VERTEX), &vertices[0], GL_STATIC_DRAW); glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, sizeof(LINE_VERTEX), BUFFER_OFFSET(0)); glEnableVertexAttribArray(ATTRIB_VERTEX); // glVertexAttribPointer(ATTRIB_NORMAL, 3, GL_FLOAT, GL_FALSE, sizeof(LINE_VERTEX), // BUFFER_OFFSET(3 * sizeof(GLfloat))); // glEnableVertexAttribArray(ATTRIB_NORMAL); glDrawArrays(GL_LINES, 0, 6); glBindBuffer(GL_ARRAY_BUFFER, 0); glDeleteBuffers(1, &vbo_); } static float HueToRGB(float v1, float v2, float vH) { if (vH < 0) vH += 1; if (vH > 1) vH -= 1; if ((6 * vH) < 1) return (v1 + (v2 - v1) * 6 * vH); if ((2 * vH) < 1) return v2; if ((3 * vH) < 2) return (v1 + (v2 - v1) * ((2.0f / 3) - vH) * 6); return v1; } inline ndk_helper::Vec3 hueToRGB(float hue) { float v1, v2; // v2 = (hsl.L < 0.5) ? (hsl.L * (1 + hsl.S)) : ((hsl.L + hsl.S) - (hsl.L * hsl.S)); // v1 = 2 * hsl.L - v2; v2 = ((0.5 + 1.f) - (0.5 * 1.f)); v1 = 2 * 0.5 - v2; ndk_helper::Vec3 color( HueToRGB(v1, v2, hue + (1.0f / 3)), HueToRGB(v1, v2, hue), HueToRGB(v1, v2, hue - (1.0f / 3)) ); return color; } //Frustum(Matrix *result, float left, float right, float bottom, float top, float nearZ, float farZ) //{ // float deltaX = right - left; // float deltaY = top - bottom; // float deltaZ = farZ - nearZ; // Matrix frustum; // // if ((nearZ <= 0.0f) || (farZ <= 0.0f) || // (deltaX <= 0.0f) || (deltaY <= 0.0f) || (deltaZ <= 0.0f)) // { // return; // } // // frustum.m[0][0] = 2.0f * nearZ / deltaX; // frustum.m[0][1] = frustum.m[0][2] = frustum.m[0][3] = 0.0f; // // frustum.m[1][1] = 2.0f * nearZ / deltaY; // frustum.m[1][0] = frustum.m[1][2] = frustum.m[1][3] = 0.0f; // // frustum.m[2][0] = (right + left) / deltaX; // frustum.m[2][1] = (top + bottom) / deltaY; // frustum.m[2][2] = -(nearZ + farZ) / deltaZ; // frustum.m[2][3] = -1.0f; // // frustum.m[3][2] = -2.0f * nearZ * farZ / deltaZ; // frustum.m[3][0] = frustum.m[3][1] = frustum.m[3][3] = 0.0f; // // Multiply(result, &frustum, result); //} //struct PackedVertex{ // ndk_helper::Vec3 position; // ndk_helper::Vec2 uv; // ndk_helper::Vec3 normal; // bool operator<(const PackedVertex that) const{ // return memcmp((void*)this, (void*)&that, sizeof(PackedVertex))>0; // }; //}; //bool getSimilarVertexIndex_fast( // PackedVertex & packed, // std::map<PackedVertex,unsigned short> & VertexToOutIndex, // unsigned short & result //){ // std::map<PackedVertex,unsigned short>::iterator it = VertexToOutIndex.find(packed); // if ( it == VertexToOutIndex.end() ){ // return false; // }else{ // result = it->second; // return true; // } //} // //void indexVBO( // std::vector<ndk_helper::Vec3> & in_vertices, // std::vector<ndk_helper::Vec2> & in_uvs, // std::vector<ndk_helper::Vec3> & in_normals, // // std::vector<uint16_t> & out_indices, // std::vector<ndk_helper::Vec3> & out_vertices, // std::vector<ndk_helper::Vec2> & out_uvs, // std::vector<ndk_helper::Vec3> & out_normals //){ // std::map<PackedVertex,unsigned short> VertexToOutIndex; // // // For each input vertex // for ( unsigned int i=0; i<in_vertices.size(); i++ ){ // // PackedVertex packed = {in_vertices[i], in_uvs[i], in_normals[i]}; // // // // Try to find a similar vertex in out_XXXX // uint16_t index; // bool found = getSimilarVertexIndex_fast( packed, VertexToOutIndex, index); // // if ( found ){ // A similar vertex is already in the VBO, use it instead ! // out_indices.push_back( index ); // }else{ // If not, it needs to be added in the output data. // out_vertices.push_back( in_vertices[i]); // out_uvs .push_back( in_uvs[i]); // out_normals .push_back( in_normals[i]); // uint16_t newindex = (uint16_t)out_vertices.size() - 1; // out_indices .push_back( newindex ); // VertexToOutIndex[ packed ] = newindex; // } // } //}
true
8a305734a38a1b6fc2d40a1050adb16c117e9a3d
C++
LeviMollison/GameProgramming
/Relearning C++/Practice/Practice/classes.cpp
UTF-8
510
2.984375
3
[]
no_license
// // classes.cpp // Practice // // Created by Levi Mollison on 2/2/16. // Copyright © 2016 Levi. All rights reserved. // #include <stdio.h> #include <string> #include <iostream> using namespace std; class Simplest {}; class Simple{ public: void display(){ cout << "Displaying a simple object\n"; } }; class Vorlon{ public: Vorlon(const string& aName) : myName(aName) {} void display() const {cout << "Displaying a Vorlon named " << myName << endl;} private: string myName; };
true
c4c54bc44244ad7f81036824104efb90738f96ef
C++
JosnickCB/AED
/aed_list.cpp
UTF-8
9,812
3.484375
3
[]
no_license
#include <iostream> using namespace std; template <class Type> struct nodeType{ Type info; nodeType<Type> *link; }; template <class Type> class linkedListIterator{ public: linkedListIterator(); linkedListIterator(nodeType<Type> *ptr); Type operator*(); linkedListIterator<Type> operator++(); bool operator==(const linkedListIterator<Type>& right) const; bool operator!=(const linkedListIterator<Type>& right) const; private: nodeType<Type> *current; }; template <class Type> linkedListIterator<Type>::linkedListIterator(){ current = NULL; } template <class Type>linkedListIterator<Type>::linkedListIterator(nodeType<Type> *ptr){ current = ptr; } template <class Type> Type linkedListIterator<Type>::operator*(){ return current->info; } template <class Type> linkedListIterator<Type> linkedListIterator<Type>::operator++(){ current = current->link; return *this; } template <class Type> bool linkedListIterator<Type>::operator==(const linkedListIterator<Type>& right) const{ return (current == right.current); } template <class Type> bool linkedListIterator<Type>::operator!=(const linkedListIterator<Type>& right) const{ return (current != right.current); } template <class Type> class linkedListType{ public: const linkedListType<Type>& operator=(const linkedListType<Type>&); void initializeList(); bool isEmptyList() const; void print() const; int length() const; void destroyList(); Type front() const; Type back() const; virtual bool search(const Type& searchItem) const = 0; virtual void insertFirst(const Type& newItem) = 0; virtual void insertLast(const Type& newItem) = 0; virtual void deleteNode(const Type& deleteItem) = 0; linkedListIterator<Type> begin(); linkedListIterator<Type> end(); linkedListType(); linkedListType(const linkedListType<Type>& otherList); ~linkedListType(); protected: int count; nodeType<Type> *first; nodeType<Type> *last; private: void copyList(const linkedListType<Type>& otherList); }; template <class Type> bool linkedListType<Type>::isEmptyList() const{ return (first == NULL); } template <class Type> linkedListType<Type>::linkedListType(){ first = NULL; last = NULL; count = 0; } template <class Type> void linkedListType<Type>::destroyList(){ nodeType<Type> *temp; while (first != NULL){ temp = first; first = first->link; delete temp; } last = NULL; count = 0; } template <class Type> void linkedListType<Type>::initializeList(){ destroyList(); } template <class Type> void linkedListType<Type>::print() const{ nodeType<Type> *current; current = first; cout<<"[ "; if(current == NULL) cout<<"No hay nada\n"; while (current != NULL){ cout << current->info << " "; current = current->link; } cout<<"] "; } template <class Type> int linkedListType<Type>::length() const{ return count; } template <class Type> Type linkedListType<Type>::front() const{ assert(first != NULL); return first->info; } template <class Type> Type linkedListType<Type>::back() const{ assert(last != NULL); return last->info; } template <class Type> linkedListIterator<Type> linkedListType<Type>::begin(){ linkedListIterator<Type> temp(first); return temp; } template <class Type> linkedListIterator<Type> linkedListType<Type>::end(){ linkedListIterator<Type> temp(NULL); return temp; } template <class Type> void linkedListType<Type>::copyList(const linkedListType<Type>& otherList){ nodeType<Type> *newNode; nodeType<Type> *current; if (first != NULL) destroyList(); if (otherList.first == NULL){ first = NULL; last = NULL; count = 0; }else{ current = otherList.first; count = otherList.count; first = new nodeType<Type>; first->info = current->info; first->link = NULL; last = first; current = current->link; while (current != NULL){ newNode = new nodeType<Type>; newNode->info = current->info; newNode->link = NULL; last->link = newNode; last = newNode; current = current->link; } } } template <class Type> linkedListType<Type>::~linkedListType(){ destroyList(); } template <class Type> linkedListType<Type>::linkedListType(const linkedListType<Type>& otherList){ first = NULL; copyList(otherList); } template <class Type> const linkedListType<Type>& linkedListType<Type>::operator=(const linkedListType<Type>& otherList){ if (this != &otherList){ copyList(otherList); } return *this; } // // LISTA DESORDENADA // template <class Type> class unorderedLinkedList: public linkedListType<Type>{ public: bool search(const Type& searchItem) const; void insertFirst(const Type& newItem); void insertLast(const Type& newItem); void deleteNode(const Type& deleteItem); }; template <class Type> bool unorderedLinkedList<Type>::search(const Type& searchItem) const{ nodeType<Type> *current; bool found = false; current = this->first; while (current != NULL && !found) if (current->info == searchItem) found = true; else current = current->link; return found; } template <class Type> void unorderedLinkedList<Type>::insertFirst(const Type& newItem){ nodeType<Type> *newNode; newNode = new nodeType<Type>; newNode->info = newItem; newNode->link = this->first; this->first = newNode; this->count++; if (this->last == NULL) this->last = newNode; } template <class Type> void unorderedLinkedList<Type>::insertLast(const Type& newItem){ nodeType<Type> *newNode; newNode = new nodeType<Type>; newNode->info = newItem; newNode->link = NULL; if (this->first == NULL){ this->first = newNode; this->last = newNode; this->count++; }else{ this->last->link = newNode; this->last = newNode; this->count++; } } template <class Type> void unorderedLinkedList<Type>::deleteNode(const Type& deleteItem){ nodeType<Type> *current; nodeType<Type> *trailCurrent; bool found; if (this->first == NULL) cout << "No se puede eliminar de una lista vacía."<< endl; else{ if (this->first->info == deleteItem){ current = this->first; this->first = this->first->link; this->count--; if (this->first == NULL) this->last = NULL; delete current; }else{ found = false; trailCurrent = this->first; current = this->first->link; while (current != NULL && !found){ if (current->info != deleteItem){ trailCurrent = current; current = current-> link; }else found = true; } if (found){ trailCurrent->link = current->link; this->count--; if (this->last == current) this->last = trailCurrent; delete current; } else cout << "El item a ser eliminado no está en la lista." << endl; } } } // // LISTA ORDENADA // template <class Type> class orderedLinkedList: public linkedListType<Type>{ public: bool search(const Type& searchItem) const; void insert(const Type& newItem); void insertFirst(const Type& newItem); void insertLast(const Type& newItem); void deleteNode(const Type& deleteItem); }; template <class Type> bool orderedLinkedList<Type>::search(const Type& searchItem) const{ bool found = false; nodeType<Type> *current; current = this->first; while (current != NULL && !found) if (current->info >= searchItem) found = true; else current = current->link; if (found) found = (current->info == searchItem); return found; } template <class Type> void orderedLinkedList<Type>::insert(const Type& newItem){ nodeType<Type> *current; nodeType<Type> *trailCurrent; nodeType<Type> *newNode; bool found; newNode = new nodeType<Type>; newNode->info = newItem; newNode->link = NULL; if (this->first == NULL){ this->first = newNode; this->last = newNode; this->count++; }else{ current = this->first; found = false; while (current != NULL && !found) if (current->info >= newItem) found = true; else{ trailCurrent = current; current = current->link; } if (current == this->first){ newNode->link = this->first; this->first = newNode; this->count++; }else{ trailCurrent->link = newNode; newNode->link = current; if (current == NULL) this->last = newNode; this->count++; } } } template <class Type> void orderedLinkedList<Type>::insertFirst(const Type& newItem){ insert(newItem); } template <class Type> void orderedLinkedList<Type>::insertLast(const Type& newItem){ insert(newItem); } template <class Type> void orderedLinkedList<Type>::deleteNode(const Type& deleteItem){ nodeType<Type> *current; nodeType<Type> *trailCurrent; bool found; if (this->first == NULL) cout << "No se puede eliminar de una lista vacia" << endl; else{ current = this->first; found = false; while (current != NULL && !found) if (current->info >= deleteItem) found = true; else{ trailCurrent = current; current = current->link; } if (current == NULL) cout << "El elemento a ser eliminado no está en la lista"<< endl; else if (current->info == deleteItem){ if (this->first == current){ this->first = this->first->link; if (this->first == NULL) this->last = NULL; delete current; }else{ trailCurrent->link = current->link; if (current == this->last) this->last = trailCurrent; delete current; } this->count--; }else cout << "El elemento a ser eliminado no está en la lista" << endl; } } int main(){ orderedLinkedList<int> list1, list2; int num; cout << "Ingrese números terminando con -999." << endl; cin >> num; while (num != -999){ list1.insert(num); cin >> num; } cout << endl; cout << "Lista 1: "; list1.print(); cout << endl; list2 = list1; cout << "Lista 2: "; list2.print(); cout << endl; cout << "Ingrese número a ser eliminado: "; cin >> num; cout << endl; list2.deleteNode(num); cout << "Despues de eliminar \" "<< num << " \" \nLista 2: "; list2.print(); cout << endl; return 0; }
true
9c222d3c1158c932451dc895c9c22f468317c183
C++
Minumu/CPP-Rush00
/Ship.cpp
UTF-8
679
2.875
3
[]
no_license
#include "Ship.hpp" Ship::Ship() { _size = 1; _hp = 3; _who = "}"; } Ship::Ship(int size, int hp, std::string who) : _size(size), _hp(hp), _who(who) { } Ship::~Ship() { } Ship::Ship( Ship const & src) { *this = src; } Ship & Ship::operator=(Ship const & rhs) { _hp = rhs.getHp(); _size = rhs.getSize(); return (*this); } void Ship::shipMoved(int y, int x, const char *who, short color) { wattron(stdscr, COLOR_PAIR(color)); mvprintw(y, x, who); wattroff(stdscr, COLOR_PAIR(color)); refresh(); } int Ship::getHp() const { return _hp; } void Ship::setHp(int hp) { _hp = hp; } int Ship::getSize() const { return _size; }
true
f04ce0e2923c6c20d6a486aa99b76f7f61a3443a
C++
yushiyaogg/backup
/practice/algorithm_practise/algorithm_design/Fulkerson.h
UTF-8
1,366
3.046875
3
[]
no_license
//Fulkerson.h header file //Standard Ford-Fulkerson Algorithm //Author: Fengdong #include <stack> #include <list> using namespace std; typedef pair<int,int> flowPair; typedef struct _node { int number; int C; int F; struct _node* next; _node(int _number,int _C) { number = _number; C = _C; F = 0; next = NULL; } }Node; typedef struct _headNode { Node* next; _headNode() { next = NULL; } }headNode; class FordFulkerson { public: FordFulkerson(); ~FordFulkerson(); void getMaxFlow(); void displayInfo(); private: void mark(); void init(); void constructAdjList(); //construct adjacent table void pop(int number); // pop stack void adjustFlow(); // adjust flow if target node marked Node* findNode(Node* _current); //which node should be pushed into the stack Node* getAdjustedNode(int number,int _target); //change F value when adjust flow private: static const int headCount = 7; flowPair currentState[headCount]; int Qs; // how many flow increased int augmentingPath ; // how many "augmenting path" headNode nodes[headCount]; stack<Node*>* nodeStack; int current; int source ; int target; };
true
61048a865509152aa7afe76aaec7150e6ca4946e
C++
AnnVita/i-love-oop
/Car/tests/carTests.cpp
UTF-8
4,292
3.1875
3
[]
no_license
#include "stdafx.h" #include "../Car/car.h" struct CarFixture { CCar car; }; BOOST_FIXTURE_TEST_SUITE(Car, CarFixture) BOOST_AUTO_TEST_SUITE(when_the_newly_constructed) BOOST_AUTO_TEST_CASE(engine_is_turned_off_by_default) { BOOST_CHECK(!car.IsTurnedOn()); } BOOST_AUTO_TEST_CASE(speed_is_zero_by_default) { BOOST_CHECK(car.GetSpeed() == 0); } BOOST_AUTO_TEST_CASE(direction_is_NONE_by_default) { BOOST_CHECK(car.GetDirection() == Direction::NONE); } BOOST_AUTO_TEST_CASE(gear_is_NEUTRAL_by_default) { BOOST_CHECK(car.GetGear() == Gear::NEUTRAL); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(if_car_engine_is_turned_off) BOOST_AUTO_TEST_CASE(engine_can_be_turned_on) { BOOST_CHECK(car.TurnOnEngine()); } BOOST_AUTO_TEST_CASE(engine_cannot_be_turned_off_when_it_already_off) { BOOST_CHECK(!car.TurnOffEngine()); } BOOST_AUTO_TEST_CASE(impossible_to_change_speed_when_engine_off) { BOOST_CHECK(!car.SetSpeed(20)); } BOOST_AUTO_TEST_CASE(impossible_to_change_gear_when_engine_off) { BOOST_CHECK(!car.SetGear(Gear::FIRST)); } BOOST_AUTO_TEST_SUITE_END() struct when_engine_turned_on_ : CarFixture { when_engine_turned_on_() { car.TurnOnEngine(); } }; BOOST_FIXTURE_TEST_SUITE(when_engine_turned_on, when_engine_turned_on_) BOOST_AUTO_TEST_CASE(speed_is_zero_immediately_after_turning_on) { BOOST_CHECK(car.GetSpeed() == 0); } BOOST_AUTO_TEST_CASE(direction_is_NONE_immediately_after_turning_on) { BOOST_CHECK(car.GetDirection() == Direction::NONE); } BOOST_AUTO_TEST_CASE(gear_is_NEUTRAL_immediately_after_turning_on) { BOOST_CHECK(car.GetGear() == Gear::NEUTRAL); } BOOST_AUTO_TEST_CASE(engine_can_be_turned_off_immediately_after_turning_on) { BOOST_CHECK(car.TurnOffEngine()); } BOOST_AUTO_TEST_CASE(gear_can_be_changed_to_REVERSE_immediately_after_turning_on) { BOOST_CHECK(car.SetGear(Gear::REVERSE)); } BOOST_AUTO_TEST_CASE(gear_can_be_changed_to_FIRST_immediately_after_turning_on) { BOOST_CHECK(car.SetGear(Gear::FIRST)); } BOOST_AUTO_TEST_CASE(gear_cant_be_changed_for_more_than_FIRST_gear_value_immediately_after_turning_on) { BOOST_CHECK(!car.SetGear(Gear::SECOND)); } BOOST_AUTO_TEST_CASE(engine_cannot_be_turned_on_when_it_already_on) { BOOST_CHECK(!car.TurnOnEngine()); } BOOST_AUTO_TEST_CASE(impossible_to_change_speed_to_negative_value) { BOOST_CHECK(!car.SetSpeed(-2)); } BOOST_AUTO_TEST_CASE(impossible_to_accelerate_if_gear_is_NEUTRAL) { BOOST_CHECK(!car.SetSpeed(20)); } BOOST_AUTO_TEST_CASE(gear_can_be_changed_to_REVERSE_if_speed_is_zero_and_gear_is_NEUTRAL) { BOOST_CHECK(car.GetSpeed() == 0); BOOST_CHECK(car.SetGear(Gear::REVERSE)); } BOOST_AUTO_TEST_CASE(gear_can_be_changed_to_FIRST_from_NEUTRAL) { BOOST_CHECK(car.SetGear(Gear::FIRST)); } BOOST_AUTO_TEST_CASE(accelerate_if_gear_is_not_NEUTRAL) { BOOST_CHECK(car.SetGear(Gear::FIRST)); BOOST_CHECK(car.SetSpeed(30)); BOOST_CHECK(car.GetSpeed() == 30); } BOOST_AUTO_TEST_CASE(slow_down_if_gear_is_not_NEUTRAL) { BOOST_CHECK(car.SetGear(Gear::FIRST)); BOOST_CHECK(car.SetSpeed(30)); BOOST_CHECK(car.GetSpeed() == 30); BOOST_CHECK(car.SetSpeed(10)); BOOST_CHECK(car.GetSpeed() == 10); } BOOST_AUTO_TEST_CASE(slow_down_if_gear_NEUTRAL) { BOOST_CHECK(car.SetGear(Gear::FIRST)); BOOST_CHECK(car.SetSpeed(30)); BOOST_CHECK(car.GetSpeed() == 30); BOOST_CHECK(car.SetGear(Gear::NEUTRAL)); BOOST_CHECK(car.SetSpeed(10)); BOOST_CHECK(car.GetSpeed() == 10); } BOOST_AUTO_TEST_CASE(impossible_accelerate_to_the_appropriate_gear_speed) { BOOST_CHECK(car.SetGear(Gear::FIRST)); BOOST_CHECK(!car.SetSpeed(50)); } BOOST_AUTO_TEST_CASE(impossible_slow_down_to_the_appropriate_gear_speed) { BOOST_CHECK(car.SetGear(Gear::FIRST)); BOOST_CHECK(car.SetSpeed(30)); BOOST_CHECK(car.SetGear(Gear::SECOND)); BOOST_CHECK(!car.SetSpeed(19)); } BOOST_AUTO_TEST_CASE(impossible_change_gear_to_REVERSE_if_speed_is_not_zero) { BOOST_CHECK(car.SetGear(Gear::FIRST)); BOOST_CHECK(car.SetSpeed(30)); BOOST_CHECK(!car.SetGear(Gear::REVERSE)); } BOOST_AUTO_TEST_SUITE_END(); BOOST_AUTO_TEST_SUITE_END()
true
dba4570200f152c637277cd16b0e1617236d6967
C++
luqian2017/Algorithm
/LintCode/1125_Jump-Pillar/1125_Jump-Pillar.cpp
UTF-8
926
2.984375
3
[]
no_license
class Solution { public: /** * @param h: the height of n pillar * @param k: the limit * @return: Xiao Yi can or can't reach the n-th pillar */ bool jumpPillar(vector<int> &h, int k) { int len = h.size(); vector<vector<int>> dp(len, vector<int>(2, 0)); //dp[i][j] = 1 shows if jump to i is possible, 0 impossible. // j = 0, the super power is unused, j = 1 used. dp[0][0] = 1; for (int i = 0; i < len; ++i) { for (int j = i + 1; j <= min(len - 1, i + k); ++j) { if (h[i] >= h[j]) { dp[j][0] = max(dp[j][0], dp[i][0]); dp[j][1] = max(dp[j][1], dp[i][0]); } dp[j][1] = max(dp[j][1], dp[i][0]); } } if (dp[len - 1][0] == 1 || dp[len - 1][1] == 1) return true; return false; } };
true
ad868c5a59264ad470d78e1ee72929cffc797b8e
C++
jiramateGitHub/LAB-88814459
/LAB_09/LAB_9-1/BankAccount.cpp
UTF-8
719
3.296875
3
[]
no_license
#include "BankAccount.h" BankAccount::BankAccount() { name = ""; } int BankAccount::initial_value(string n,double m){ name = n; if(m >= 500){ balance = m; cout << "Deposit " << balance << " Complete. " << endl; printInfo(); return 1; }else{ cout << "Can't Deposit " << m << endl; } } void BankAccount::deposit(double m){ balance += m; cout << "Deposit " << m << " Complete. " << endl; printInfo(); } void BankAccount::withdraw(double m){ if(m < balance){ balance -= m; cout << "Withdraw " << m << " Complete. " << endl; }else{ cout << "Can't Withdraw " << m << endl; } printInfo(); } void BankAccount::printInfo(){ cout << "Name : " << name << " | Balance : " << balance << endl; }
true
82c6009822769f7cc25fcbde73b925416e33429d
C++
sky-cfw/comm
/test/performance/test_false_sharing.cpp
UTF-8
3,084
3.203125
3
[]
no_license
/* 参考:https://github.com/MJjainam/falseSharing/blob/master/parallelComputing.c */ #include <sys/times.h> #include <time.h> #include <stdio.h> #include <pthread.h> struct timespec tpBegin1,tpEnd1,tpBegin2,tpEnd2,tpBegin3,tpEnd3; //These are inbuilt structures to store the time related activities double compute(struct timespec start,struct timespec end) //computes time in milliseconds given endTime and startTime timespec structures. { double t; t=(end.tv_sec-start.tv_sec)*1000; t+=(end.tv_nsec-start.tv_nsec)*0.000001; return t; } int array[100]; void *expensive_function(void *param) { int index = *((int*)param); int i; for (i = 0; i < 100000000; i++) array[index]+=1; return NULL; } int main(int argc, char *argv[]) { int first_elem = 0; int bad_elem = 1; int good_elem = 99; double time1; double time2; double time3; pthread_t thread_1; pthread_t thread_2; //---------------------------START--------Serial Computation--------------------------------------------- clock_gettime(CLOCK_REALTIME,&tpBegin1); expensive_function((void*)&first_elem); expensive_function((void*)&bad_elem); clock_gettime(CLOCK_REALTIME,&tpEnd1); //---------------------------END----------Serial Computation--------------------------------------------- //---------------------------START--------parallel computation with False Sharing---------------------------- clock_gettime(CLOCK_REALTIME,&tpBegin2); pthread_create(&thread_1, NULL,expensive_function, (void*)&first_elem); pthread_create(&thread_2, NULL,expensive_function, (void*)&bad_elem); pthread_join(thread_1, NULL); pthread_join(thread_2, NULL); clock_gettime(CLOCK_REALTIME,&tpEnd2); //---------------------------END----------parallel computation with False Sharing---------------------------- //---------------------------START--------parallel computation without False Sharing------------------------ clock_gettime(CLOCK_REALTIME,&tpBegin3); pthread_create(&thread_1, NULL,expensive_function, (void*)&first_elem); pthread_create(&thread_2, NULL,expensive_function, (void*)&good_elem); pthread_join(thread_1, NULL); pthread_join(thread_2, NULL); clock_gettime(CLOCK_REALTIME,&tpEnd3); //---------------------------END--------parallel computation without False Sharing------------------------ //--------------------------START------------------OUTPUT STATS-------------------------------------------- printf("array[first_element]: %d\t\t array[bad_element]: %d\t\t array[good_element]: %d\n\n\n", array[first_elem],array[bad_elem],array[good_elem]); time1 = compute(tpBegin1,tpEnd1); time2 = compute(tpBegin2,tpEnd2); time3 = compute(tpBegin3,tpEnd3); printf("Time take with false sharing : %f ms\n", time2); printf("Time taken without false sharing : %f ms\n", time3); printf("Time taken in Sequential computing : %f ms\n", time1); //--------------------------END------------------OUTPUT STATS-------------------------------------------- return 0; }
true
17d9b6acbd4eadbd59862870aa0cf3a4ab9bbacd
C++
habiss/syntax_checker
/GenStack.cpp
UTF-8
618
3.140625
3
[]
no_license
/* #include "GenStack.h" using namespace std; GenStack::GenStack(int maxSize) { Stack = new char[maxSize]; max = maxSize; top = -1; size= 0; } GenStack::~GenStack() { //need to delete array cout << "object destroyed" << endl; } void GenStack::push(char data) { //error checking (is the array full?) size++; myArray[++top] = data; } char GenStack::pop() { //error checking: check if the element exist return Stack[top--]; size--; } char GenStack::peek() { return Stack[top]; } int GenStack::isFull() { return (top == max-1); } int GenStack::isEmpty() { return (top == -1); } */
true
4dbb83c494659151049682322f87a277ed98a46a
C++
hadesbox/arduino-legacy-projects
/libraries/ORSINI_ARPEGGIO/examples/ORSINI_ARPEGGIO/control.ino
UTF-8
7,121
2.546875
3
[]
no_license
#include <Bounce.h> byte debounce= 5; // Debounce Time in ms Bounce channel_mode_up= Bounce( 2, debounce); Bounce channel_mode_down= Bounce( 3, debounce ); Bounce scale_part_up= Bounce( 4, debounce ); Bounce scale_part_down= Bounce( 5, debounce ); Bounce shift= Bounce( 6, debounce ); bool checkAnalog(byte analogIn) { if( changeAnalogVal[analogIn]<analogRead(analogIn)-100 || changeAnalogVal[analogIn]>analogRead(analogIn)+100 ){ changeAnalogBool[analogIn] = true; return true; }else{ return false; } } void resetAnalog(){ for(int ch=0; ch<6;ch++){ changeAnalogBool[ch] = false ; changeAnalogVal[ch]=analogRead(ch); } } void control(){ //shift.update ( ); if (shift.update()){ // SHIFT int shiftVal = shift.read(); if ( shiftVal == HIGH) { shiftOn=0; //resetAnalog(); } else { shiftOn=1; resetAnalog(); } } if (channel_mode_up.update()) { if (channel_mode_up.read() == LOW) { ///ON SHIFT if(shiftOn==1){//part channel change up if(selected_part==0){ if(part.channel_select<16){ part.channel_select = (part.channel_select+1); } }else{ if(part.channel_select<16){ part.channel_select = (part.channel_select+1); } } }else{ //part mode change if(selected_part==0){ if(part.mode_select<part.mode.n_modes){ part.modeSelekt(part.mode_select+1); } }else{ if(part.mode_select<part.mode.n_modes){ part.modeSelekt(part.mode_select+1); } } } } } if (channel_mode_down.update()) { if (channel_mode_down.read() == LOW) {///ON SHIFT if(shiftOn==1){//part channel change down if(selected_part==0){ if(part.channel_select>=0){ part.channel_select = (part.channel_select-1); } }else{ if(part.channel_select>=0){ part.channel_select = (part.channel_select-1); } } }else{ if(selected_part==0){ if(part.mode_select>0){ part.modeSelekt(part.mode_select-1); } }else{ if(part.mode_select>0){ part.modeSelekt(part.mode_select-1); } } //part mode change } } } ///SCALE UP if (scale_part_up.update()) { if (scale_part_up.read() == LOW) { // resetAnalog(); if(shiftOn==1){ if(midiIn==true){ midiIn=false; }else{ midiIn=true; } //midiIn = !midiIn; }else{ //scale change up if(selected_part==0){ if(part.scale_select<14){ part.scale_select = (part.scale_select+1); } }else{ if(part.scale_select<14){ part.scale_select = (part.scale_select+1); } } } } } ///SCALE DOWN if (scale_part_down.update()) { if (scale_part_down.read() == LOW) { for(int ch=0; ch<6;ch++){ changeAnalogBool[ch] = false ; changeAnalogVal[ch]=analogRead(ch); } if(shiftOn==1){ //part select restartSequence(); if(selected_part==0){ //restartSequence(); }else{ //selected_part=0; } }else{ //scale change down if(selected_part==0){ if(part.scale_select>0){ part.scale_select = (part.scale_select-1); } }else{ if(part.scale_select>0){ part.scale_select = (part.scale_select-1); } } } } } checkAnalog(0); checkAnalog(1); checkAnalog(2); checkAnalog(3); checkAnalog(4); checkAnalog(5); ///UPDATE IF ANALOG READ CHANGED AND PART CHANGED SO NO CHANGES WHEN COMING FROM OTHER PART if(selected_part==0){ byte n=0; ///OCTAVE FROM OUTSIDE OF THE SEQUENCE FOR IMMEDIATE CHANGE if( changeAnalogBool[n] ){ byte m1=map( analogRead(n) ,0,1024,2,16); //OCTSEL part.octave_select=m1; }; for(int c=0;c<6;c++){ n=c+(shiftOn*6); if( changeAnalogBool[c] ){ part.update(c, n); }; } /* //REST OF ANALOG INS FROM 1 with SHIFT OPTION if(shiftOn==0){ if( changeAnalogBool[0] ){ part.update(0, 0); }; if( changeAnalogBool[1] ){ part.update(1, 1); }; if( changeAnalogBool[2] ){ part.update(2, 2); }; if( changeAnalogBool[3] ){ part.update(3, 3); }; if( changeAnalogBool[4] ){ part.update(4, 4); }; if( changeAnalogBool[5] ){ part.update(5, 5); }; }else if(shiftOn!=0){ // if( changeAnalogBool[0] ){ part.update(0, 6); }; if( changeAnalogBool[1] ){ part.update(1, 7); }; if( changeAnalogBool[2] ){ part.update(2, 8); }; if( changeAnalogBool[3] ){ part.update(3, 9); }; if( changeAnalogBool[4] ){ part.update(4, 10); }; if( changeAnalogBool[5] ){ part.update(5, 11); }; }*/ /*byte m1=map( checkAnalog( 0, analogRead(0) ), 0, 1023, part.mode.arpeggio.MAP_VALUES[0][0], part.mode.arpeggio.MAP_VALUES[0][1]); // mode select byte m2 =map( checkAnalog( 1, analogRead(1) ), 0, 1023, part.mode.arpeggio.MAP_VALUES[1][0], part.mode.arpeggio.MAP_VALUES[1][1]); // mode select byte m3=map( checkAnalog( 3, analogRead(3) ), 0, 1023, part.mode.arpeggio.MAP_VALUES[3][0], part.mode.arpeggio.MAP_VALUES[3][1]); // mode select byte m [4]=map( checkAnalog( 4, analogRead(4) ), 0, 1023, part.mode.arpeggio.MAP_VALUES[4][0], part.mode.arpeggio.MAP_VALUES[4][1]); // mode select part.mode.clockDivider=map( checkAnalog(5, analogRead(5) ), 0, 1023, part.mode.arpeggio.MAP_VALUES[5][0], part.mode.arpeggio.MAP_VALUES[5][1])*3; */ }else{ byte n=0; if( changeAnalogBool[n] ){ byte m1=map( analogRead(n) ,0,1024,2,16); //OCTSEL part.octave_select=m1; }; for(int c=0;c<6;c++){ n=c+(shiftOn*6); part.update(c, n); } /* n=1; if( changeAnalogBool[n] ){ part.update(n); }; n=2; if( changeAnalogBool[n] ){ part.update(n); }; n=3; if( changeAnalogBool[n] ){ part.update(n); }; n=4; if( changeAnalogBool[n] ){ part.update(n); }; n=5; if( changeAnalogBool[n] ){ part.update(n); };*/ /* part.octave_select=map(checkAnalog( 0, analogRead(2) ),0,1024,2,9); part.mode.MAPPED_ARGS[0]=map(checkAnalog( 0, analogRead(0) ), 0, 1023, part.mode.arpeggio.MAP_VALUES[0][0], part.mode.arpeggio.MAP_VALUES[0][1]); // mode select part.mode.MAPPED_ARGS[1]=map(checkAnalog( 1, analogRead(1) ), 0, 1023, part.mode.arpeggio.MAP_VALUES[1][0], part.mode.arpeggio.MAP_VALUES[1][1]); // mode select part.mode.MAPPED_ARGS[3]=map(checkAnalog( 3, analogRead(3) ), 0, 1023, part.mode.arpeggio.MAP_VALUES[3][0], part.mode.arpeggio.MAP_VALUES[3][1]); // mode select part.mode.MAPPED_ARGS[4]=map(checkAnalog( 4, analogRead(4) ), 0, 1023, part.mode.arpeggio.MAP_VALUES[4][0], part.mode.arpeggio.MAP_VALUES[4][1]); // mode select part.mode.clockDivider=map(checkAnalog( 5, analogRead(5) ), 0, 1023, part.mode.arpeggio.MAP_VALUES[5][0], part.mode.arpeggio.MAP_VALUES[5][1])*3; */ } }
true
c39bd8ab9975718b19c0b910a35f0a3ff64c92a2
C++
checkoutb/LeetCodeCCpp
/daily_challenge/2021/LT_2021-07-07_Reduce_Array_Size_to_The_Half.cpp
UTF-8
1,258
3.21875
3
[]
no_license
#include "../../header/myheader.h" class LT { public: // D D // sort后,遍历能直接知道个数(==前面就++,不等于的时候就是前值的个数)。 然后个数再sort。 // // 看到一个桶排序,然后看到限制: arr.length is even. 不过值最高要10^5,桶排序有点不太好吧。。 // for(int i = 0; i < arr.size(); ++i) // { // int count = 1; // while(i < arr.size()-1 && arr[i+1] == arr[i] ) // count++, i++; // pq.push(count); // } // 。。while.. //multiset<int, greater <int>> s; // 和priority_queue的作用一样。 // AC int lta(vector<int>& arr) { unordered_map<int, int> map2; priority_queue<int> priq; for (int i : arr) map2[i]++; for (auto& p : map2) { priq.push(p.second); } int ans = 0; int sz1 = arr.size(); int t2 = 0; while (t2 < (sz1 + 1) / 2) { ans++; t2 += priq.top(); priq.pop(); } return ans; } }; int main() { // myvi v = {3,3,3,3,5,5,5,2,2,7}; myvi v = {1,2,3,4,5,6,7,8,9}; LT lt; cout<<lt.lta(v)<<endl; return 0; }
true
8c079132181e01bce88b977302793ac2f8a764d3
C++
Chris443/GeKo
/GeKo/Applications/K_Application/Data.h
UTF-8
821
2.578125
3
[]
no_license
#pragma once #include <vector> //Data for a Cube float vertices[] = { //Front //positions //colors 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,// top right 0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,// bottom right -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,// bottom left -0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f,// top left //Back , 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,// top right 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,// bottom right - 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,// bottom left - 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f// top left }; std::vector<unsigned int> indices = { 0, 1, 2, 3, 0, 2, 4,5,6, 7,4,6, 7,3,2, 2,6,7, 0,1,5, 5,4,0, 1,2,5, 2,5,6, 3,7,4, 4,0,3 };
true
62aa62fdd1420b67093967426876aa58d9c01f6a
C++
Newpersonhere/cuphead-1
/entity/entity.h
UTF-8
1,115
2.765625
3
[ "MIT" ]
permissive
#pragma once #include "animation/animation.h" #include "util/vector2d/vector2d.h" #include "events/eventemitter.h" #include <SDL2/SDL.h> #include <map> class Entity : public EventEmitter { public: Entity(const float& x, const float& y); virtual ~Entity(){} int speed = 5; Vector2D velocity; Vector2D position; std::map<std::string, Animation> animations; std::string currentAnimation = "idle"; std::string currentSkill = "ray"; auto draw() -> void; auto flipAnimation(const bool shouldFlip) -> void; auto play(const std::string& animatioName, const bool force = false) -> void; auto move(const std::string& direction) -> void; auto receiveDamage(const int amount) -> void; auto update() -> void; auto isOnGround() -> bool; auto isAnimationFlipped() const -> bool; auto isDead() const -> bool; auto setHealth(const int amount) -> void; auto getHealth() const -> int; auto getDimensions() -> Vector2D; auto getCurrentAnimation() -> Animation&; private: int health = 3; SDL_RendererFlip flip = SDL_FLIP_NONE; };
true
b5ebfb8440ef4df0111869aa3ab161911f819198
C++
jcamilom/aire
/source/main-test.cpp
UTF-8
1,512
3.171875
3
[]
no_license
#include "select-demo.h" #include "mbed.h" // Creates an event bound to the specified event queue #if DEMO == DEMO_TEST //counter handlers class Counter { public: Counter(PinName pin) : _interrupt(pin) { // create the InterruptIn on the pin specified to Counter _interrupt.rise(callback(this, &Counter::increment)); // attach increment function of this counter instance } void increment() { _count++; } int read() { return _count; } void reset_count(){ _count = 0; } private: InterruptIn _interrupt; volatile int _count; }; Counter counter(SW2); //events handlers EventQueue queue; void handler(int count); Event<void(int)> event(&queue, handler); void handler(int count) { printf("Count so far: %d\r\n", counter.read_ms()); counter.reset_count(); return; } void Thread_main(void) { event.post(1); } // main int main() { Thread event_thread; // The event can be manually configured for special timing requirements // specified in milliseconds event.delay(100); // Starting delay - 100 msec event.period(2000); // Delay between each evet - 200msec event_thread.start(callback(Thread_main)); // Posted events are dispatched in the context of the queue's // dispatch function queue.dispatch(-1); // Dispatch time - 400msec // 400 msec - Only 2 set of events will be dispatched as period is 200 msec event_thread.join(); } #endif
true
31225ca25e685287c58ce168a87cd5443530b9b3
C++
AnastasiaYiChen/cPlusPlus_COGS
/PROG2100/A3_afterPWP/main.cpp
UTF-8
2,570
3.390625
3
[]
no_license
/*Alice's Chess somewhat inspired by Lewis Carroll's Through the Looking Glass This kind game of chess is played on a chessboard, at least 8x8 in size, but sizes like 8x10, or 20x10 are OK too. At least two players are needed, each one controlling her/his "army" of chess pieces - where such antagonistic "armies" are build of pieces of the same colour. Using a subset of standard chess pieces (excluding pawns!) is possible and suggested; but you may come up with your own pieces, obeying their own set of movement rules. The game starts by secretly arranging pieces by each player within their designated parts of the board. No more than 2 pieces of a given kind can be used, and the total number of pieces used by each player might be limited too (sensibly). Players execute moves in an interleaving fashion, requesting a move by specifying the start and the end position on the board. The following may happen as a result of a move request: • absolutely nothing, iff: ◦ the start position was empty ◦ the piece at the start position is not yours (i.e. it is an enemy piece) ◦ the piece at the start position would not be able to reach the target (end) position following its movement rules, even on an empty board ◦ a friendly piece is blocking the move ◦ the start and the end positions specified are the same • the piece position changes, yet the target/end position is not reached, iff: ◦ an enemy piece on the path to target was blocking the access; that enemy piece is taken out, and its position becomes the new position of the piece on the move ◦ a friendly piece was blocking the access; then the moving piece stops right before reaching the blocking piece (hence, no "friendly fire" allowed) • the target (end) position is reached, possibly taking out an enemy piece that occupied that target position The goal is to take out all enemy pieces. Alternate versions to consider. • allowing for more than 2 players • allowing for multiple move requests at each turn • allowing for concurrent placing move requests */ #include <iostream> using namespace std; using namespace std; #include <array> #include "Board.h" #include "Ninja.h" #include "Rook.h" /*implemented Rook and Ninja not do Queen and King stc. */ int main() { cout << "Alice Chess"<< endl; Board board; Piece * R{new Rook}; /*new a Rook*/ board.place(R, 1, 3); /*move rook to x, y position in the 2d array*/ board.print(); R->goTo(7,6); board.print(); Piece * N{new Ninja}; board.place(N, 2, 2); board.print(); return 0; }
true
e045fc15b61ccd676deeedb0978424c92b2f0589
C++
jk983294/Store
/DataBus/Include/CUDPReceiver.h
GB18030
873
2.84375
3
[]
no_license
/************************************************** Receiver ˵ ִ߳йѭȡӦ˿ڣҽݷװΪ ӦĽṹյԭʼݣԭʼݴ洢ڻ **************************************************/ class CUDPReceiver:public CReceiver { public: CUDPReceiver(SOCKET s ); ~CUDPReceiver(); /* * øýӿڵõ洢buffer_еԭʼݡͨźsema_Զд * ͬ */ int Receive(TopicID& topic, char*& data , int& length); /* UDP鲥ʼ */ int Init_multicast(); private: //SOCKET SOCKET s_; //洢ǰԭʼݵĻ char buffer_[UDP_HEADER_LEN]; //ǰij int buffer_len_; struct sockaddr_in from;//ԷϢ int addrlen;//sockaddr_in length };
true
923a37b771142e24a23048bb39d15c78a4230a7c
C++
Blue-Latios/A_N_T_I
/Trial1/randomer.cpp
UTF-8
606
2.859375
3
[]
no_license
#include "randomer.hpp" #include <ctime> #include <random> std::mt19937 G(time(0)); //Seed dengan time(0) int randomInt(int min, int max) { std::uniform_int_distribution<> D(min, max); return D(G); } double randomDouble(double min, double max) { //random pakai mersenne_twister ///Note: Tidak error saat min > max std::uniform_real_distribution<double> D(min, max); return D(G); } float randomFloat(float min, float max) { //random pakai mersenne_twister ///Note: Tidak error saat min > max std::uniform_real_distribution<float> D(min, max); return D(G); }
true
ae36bd29f7a8f33159dfcfb5a0187ac9664ba159
C++
gael42r/DactyloChuteFaurieRiou
/DactyloChuteFaurieRiou/Main.cpp
ISO-8859-1
669
3.046875
3
[]
no_license
#include "Menu.h" int main() { //Cration du menu Menu menu; //Chargement des scores menu.load(); //Ecran titre menu.title(); //Boucle du menu for (;;) { //Affichage du menu menu.display(); //Choix de navigation int choice = 0; while (choice < 1 || choice > 4) { choice = menu.enterChoice(); } switch (choice) { case 1: //Jouer menu.play(); break; case 2: //Changer la difficult menu.setUp(); break; case 3: //Tableau des scores menu.goToScoreboard(); break; case 4: //Quitter menu.save(); return 0; break; default: break; return 0; } system("CLS"); } system("PAUSE"); return 0; }
true
e26ea65b22cf1a680702db223c35b6faf0261f20
C++
Buanderie/CauchyCaterpillar
/tests/SiameseTools.h
UTF-8
11,036
2.5625
3
[ "BSD-3-Clause" ]
permissive
/** \file \brief Siamese FEC Implementation: Tools \copyright Copyright (c) 2017 Christopher A. Taylor. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Siamese nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once /** Tools: + System headers + Debug breakpoints/asserts + Compiler-specific code wrappers + PCGRandom implementation + Microsecond timing + Windowed minimum/maximum */ #include <stdint.h> // uint32_t #include <string.h> // memcpy #include <new> // std::nothrow //------------------------------------------------------------------------------ // Portability macros // Compiler-specific debug break #if defined(_DEBUG) || defined(DEBUG) #define SIAMESE_DEBUG #ifdef _WIN32 #define SIAMESE_DEBUG_BREAK() __debugbreak() #else #define SIAMESE_DEBUG_BREAK() __builtin_trap() #endif #define SIAMESE_DEBUG_ASSERT(cond) { if (!(cond)) { SIAMESE_DEBUG_BREAK(); } } #else #define SIAMESE_DEBUG_BREAK() do {} while (false); #define SIAMESE_DEBUG_ASSERT(cond) do {} while (false); #endif // Compiler-specific force inline keyword #ifdef _MSC_VER #define SIAMESE_FORCE_INLINE inline __forceinline #else #define SIAMESE_FORCE_INLINE inline __attribute__((always_inline)) #endif namespace siamese { //------------------------------------------------------------------------------ // PCG PRNG /// From http://www.pcg-random.org/ class PCGRandom { public: void Seed(uint64_t y, uint64_t x = 0) { State = 0; Inc = (y << 1u) | 1u; Next(); State += x; Next(); } uint32_t Next() { const uint64_t oldstate = State; State = oldstate * UINT64_C(6364136223846793005) + Inc; const uint32_t xorshifted = (uint32_t)(((oldstate >> 18) ^ oldstate) >> 27); const uint32_t rot = oldstate >> 59; return (xorshifted >> rot) | (xorshifted << ((uint32_t)(-(int32_t)rot) & 31)); } uint64_t State = 0, Inc = 0; }; //------------------------------------------------------------------------------ // Timing /// Platform independent high-resolution timers uint64_t GetTimeUsec(); uint64_t GetTimeMsec(); //------------------------------------------------------------------------------ // LightVector /** Super light-weight replacement for std::vector class Features: + Tuned for Siamese allocation needs. + Never shrinks memory usage. + Minimal well-defined API: Only functions used several times. + Preallocates some elements to improve speed of short runs. + Uses normal allocator. + Growing the vector does not initialize the new elements for speed. + Does not throw on out-of-memory error. */ template<typename T> class LightVector { /// Number of preallocated elements static const unsigned kPreallocated = 25; // Tuned for Siamese T PreallocatedData[kPreallocated]; /// Size of vector: Count of elements in the vector unsigned Size = 0; /// Vector data T* DataPtr = nullptr; /// Number of elements allocated unsigned Allocated = kPreallocated; public: /// Resize the vector to the given number of elements. /// After this call, all elements are Uninitialized. /// If new size is greater than preallocated size, /// it will allocate a new buffer that is 1.5x larger. /// Returns false if memory could not be allocated bool SetSize_NoCopy(unsigned elements) { SIAMESE_DEBUG_ASSERT(Size <= Allocated); // If it is actually expanding, and it needs to grow: if (elements > Allocated) { const unsigned newAllocated = (elements * 3) / 2; T* newData = new(std::nothrow) T[newAllocated]; if (!newData) return false; T* oldData = DataPtr; Allocated = newAllocated; DataPtr = newData; // Delete old data without copying if (oldData != &PreallocatedData[0]) delete[] oldData; } Size = elements; return true; } /// Resize the vector to the given number of elements. /// If new size is smaller than current size, it will truncate. /// If new size is greater than current size, new elements will be Uninitialized. /// And if new size is greater than preallocated size, it will allocate a new /// buffer that is 1.5x larger and that will keep the existing data, /// leaving any new elements Uninitialized. /// Returns false if memory could not be allocated bool SetSize_Copy(unsigned elements) { SIAMESE_DEBUG_ASSERT(Size <= Allocated); // If it is actually expanding, and it needs to grow: if (elements > Allocated) { const unsigned newAllocated = (elements * 3) / 2; T* newData = new(std::nothrow) T[newAllocated]; if (!newData) return false; T* oldData = DataPtr; Allocated = newAllocated; DataPtr = newData; // Copy data before deletion memcpy(newData, oldData, sizeof(T) * Size); if (oldData != &PreallocatedData[0]) delete[] oldData; } Size = elements; return true; } /// Expand as needed and add one element to the end. /// Returns false if memory could not be allocated SIAMESE_FORCE_INLINE bool Append(const T& rhs) { const unsigned newSize = Size + 1; if (!SetSize_Copy(newSize)) return false; DataPtr[newSize - 1] = rhs; return true; } /// Set size to zero SIAMESE_FORCE_INLINE void Clear() { Size = 0; } /// Get current size (initially 0) SIAMESE_FORCE_INLINE unsigned GetSize() const { return Size; } /// Return a reference to an element SIAMESE_FORCE_INLINE T& GetRef(int index) const { return DataPtr[index]; } /// Return a pointer to an element SIAMESE_FORCE_INLINE T* GetPtr(int index = 0) const { return DataPtr + index; } /// Initialize preallocated data SIAMESE_FORCE_INLINE LightVector() { DataPtr = &PreallocatedData[0]; } }; //------------------------------------------------------------------------------ // WindowedMinMax template<typename T> struct WindowedMinCompare { SIAMESE_FORCE_INLINE bool operator()(const T x, const T y) const { return x <= y; } }; template<typename T> struct WindowedMaxCompare { SIAMESE_FORCE_INLINE bool operator()(const T x, const T y) const { return x >= y; } }; /// Templated class that calculates a running windowed minimum or maximum with /// a fixed time and resource cost. template<typename T, class CompareT> class WindowedMinMax { public: typedef uint64_t TimeT; CompareT Compare; struct Sample { /// Sample value T Value; /// Timestamp of data collection TimeT Timestamp; /// Default values and initializing constructor explicit Sample(T value = 0, TimeT timestamp = 0) : Value(value) , Timestamp(timestamp) { } /// Check if a timeout expired inline bool TimeoutExpired(TimeT now, TimeT timeout) { return (TimeT)(now - Timestamp) > timeout; } }; static const unsigned kSampleCount = 3; Sample Samples[kSampleCount]; bool IsValid() const { return Samples[0].Value != 0; ///< ish } T GetBest() const { return Samples[0].Value; } void Reset(const Sample sample = Sample()) { Samples[0] = Samples[1] = Samples[2] = sample; } void Update(T value, TimeT timestamp, const TimeT windowLengthTime) { const Sample sample(value, timestamp); // On the first sample, new best sample, or if window length has expired: if (!IsValid() || Compare(value, Samples[0].Value) || Samples[2].TimeoutExpired(sample.Timestamp, windowLengthTime)) { Reset(sample); return; } // Insert the new value into the sorted array if (Compare(value, Samples[1].Value)) Samples[2] = Samples[1] = sample; else if (Compare(value, Samples[2].Value)) Samples[2] = sample; // Expire best if it has been the best for a long time if (Samples[0].TimeoutExpired(sample.Timestamp, windowLengthTime)) { // Also expire the next best if needed if (Samples[1].TimeoutExpired(sample.Timestamp, windowLengthTime)) { Samples[0] = Samples[2]; Samples[1] = sample; } else { Samples[0] = Samples[1]; Samples[1] = Samples[2]; } Samples[2] = sample; return; } // Quarter of window has gone by without a better value - Use the second-best if (Samples[1].Value == Samples[0].Value && Samples[1].TimeoutExpired(sample.Timestamp, windowLengthTime / 4)) { Samples[2] = Samples[1] = sample; return; } // Half the window has gone by without a better value - Use the third-best one if (Samples[2].Value == Samples[1].Value && Samples[2].TimeoutExpired(sample.Timestamp, windowLengthTime / 2)) { Samples[2] = sample; } } }; } // namespace siamese
true
0c91f432522b2dbca7c0b2a2a4daba6d93b6996c
C++
wcmonty/sw
/385/hw1/child.cpp
UTF-8
7,040
3.140625
3
[]
no_license
/* * William Montgomery * wmontg2@uic.edu * ACCC account - wmontgom * CS 385 - Fall 2013 * Homework 1 - statsh * */ #include <sys/wait.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <iostream> #include "child.h" using namespace std; /*! * \brief Constructor used for commands that are NOT to be piped or redirected. * \param f a char* to a command */ Child::Child (char *f){ // Copy the command so we can initialize while (*f == ' '){ f++; } file = (char *) malloc(strlen(f) + 1); strcpy(file, f); tokenizeArgs(); // Initialize instance variables completed = false; exit_status = -1; in = -1; out = -1; next = -1; inputFile = NULL; outputFile = NULL; background = false; pid = -1; usageValid = false; } /*! * \brief Constructor used for commands that are to be piped or redirected. * \param f a char* to a command * \param inPipe an int representing the incoming pipe * \param outPipe an int representing the outgoing pipe * \param nextPipe and int representing the next pipe * \param back a boolean representing whether the command is to be run in the background */ Child::Child (char *f, int inPipe, int outPipe, int nextPipe, bool back){ // Copy the file so that we can tokenize while (*f == ' '){ f++; } file = (char *) malloc(strlen(f) + 1); strcpy(file, f); // Initialize instance variables completed = false; exit_status = -1; in = inPipe; out = outPipe; next = nextPipe; background = back; inputFile = NULL; outputFile = NULL; pid = -1; usageValid = false; // Tokenize and parse the command tokenizeArgs(); parseArgs(); } /*! * \brief Destructor * */ Child::~Child () { free (file); } /*! * \brief Child::createFork Creates a fork for the given command. * */ int Child::createFork () { /* fork a child process */ pid = fork(); if (pid < 0) { /* error occurred */ fprintf(stderr, "Fork Failed"); return 1; } else if (pid == 0) { /* child process */ doChild(); } else { /* parent process */ doParent(); } return pid; } /*! * \brief Child::doChild performs the actions as a child, including exec'ing */ void Child::doChild(){ if (next > 0) close(next); // Open inputFile and outputFile if they exist if (inputFile) { in = open(inputFile, O_RDONLY); if(in == -1) { perror("open() failed with error: "); } } if (outputFile) { out = open(outputFile, O_WRONLY|O_CREAT, S_IRWXU); if(out == -1) { perror("open() failed with error: "); } } // Dup the file descriptors if (in > 0){ dup2(in, 0); close(in); } if (out > 0){ dup2(out, 1); close(out); } // Exec the command if (execvp(file, args) < 0) { perror("Could not execute command"); } _exit(-1); } /*! * \brief Child::doParent performs the actions as a parent, including waiting for the process to end */ void Child::doParent(){ // Close unused file descriptors if (in > 0) { close(in); in = -1; } if (out > 0) { close(out); out = -1; } // Wait for the process to come back if (background) { wait4(pid, &exit_status, WNOHANG, &usage); } else { wait4(pid, &exit_status, 0, &usage); } // There was some error usageValid = true; if (!WIFEXITED(exit_status)) { // Error happened completed = true; cout << file << " exited with error code: " << exit_status << endl; } } /*! * \brief Child::tokenizeArgs Tokenizes the input string */ void Child::tokenizeArgs() { args[0] = file; strtok(file, " "); int i = 0; do { i++; args[i] = strtok(NULL, " "); } while (args[i]); numberArgs = i; } /*! * \brief Child::parseArgs Parses the arguments array for redirection */ void Child::parseArgs() { for (int i = 0; i < numberArgs; i++){ if (*(args[i]) == '<') { args[i] = NULL; inputFile = args[i + 1]; } else if (*(args[i]) == '>'){ args[i] = NULL; outputFile = args[i + 1]; } } } /*! * \brief Child::printStats prints relevant stats for the process */ void Child::printStats(){ printf (" "); printf ("%10.6f ", userTime()); printf ("%10.6f ", systemTime()); printf ("%8lu ", volContextSwitches()); printf ("%8lu ", involContextSwitches()); printf ("%8lu", swaps()); printf ("%8lu", pageFaults()); printf (" %-20s ", file); cout << endl; } /*! * \brief Child::isComplete returns whether the process has completed (only really applicable for * background processes). * \return true if the process is complete, false otherwise */ bool Child::isComplete(){ return completed; } /*! * \brief Child::updateUsage updates the usage for the entire process (should only be used to update the shell process) */ void Child::updateUsage(){ getrusage(RUSAGE_SELF, &usage); } /*! * \brief Child::userTime parses the user time from the rusage struct * \return A float value representing the user time */ float Child::userTime() { if (usageValid) { return (float) (usage.ru_utime.tv_sec + (usage.ru_utime.tv_usec * .000001)); } return 0.0; } /*! * \brief Child::systeTime parses the system time from the rusage struct * \return A float value representing the system time */ float Child::systemTime() { if (usageValid) { return (float) (usage.ru_stime.tv_sec + (usage.ru_stime.tv_usec * .000001)); } return 0.0; } /*! * \brief Child::volContextSwitches parses the rusage struct for the voluntary context switches * \return The number of context switches incurred */ unsigned long Child::volContextSwitches() { if (usageValid) { return usage.ru_nvcsw; } return 0; } /*! * \brief Child::involContextSwitches parses the rusage struct for the involuntary context switches * \return The number of involuntary context switches incurred */ unsigned long Child::involContextSwitches() { if (usageValid) { return usage.ru_nivcsw; } return 0; } /*! * \brief Child::swaps Read the number of swaps from the rusage struct * \return The number of swap */ unsigned long Child::swaps() { if (usageValid) { return usage.ru_nswap; } return 0; } /*! * \brief Child::pageFaults Read the number of page faults from the rusage struct * \return The number of (hard) page faults */ unsigned long Child::pageFaults() { if (usageValid) { return usage.ru_majflt; } return 0; } /*! * \brief Child::print Prints a copy of the child to stdout for debugging. */ void Child::print(){ cout << "Child for " << file << endl; cout << "in is " << in << endl; cout << "out is " << out << endl; cout << "next is " << next << endl; }
true
8c2315fceb85f0440190c52c1ee5bf26a4240223
C++
LenchMay/Practice
/9_Square.cpp
UTF-8
327
3.65625
4
[]
no_license
#include <iostream> using namespace std; int main() { cout << "Difference between 1^2 + 2^2 + ... + 100^2 and (1 + 2 + ... + 100)^2 is:\n"; int sum1 = 0, sum2 = 0; for (int i = 1; i <= 100; i++) { sum1 = sum1 + i * i; sum2 += i; } int prod = abs(sum1 - sum2 * sum2); cout << prod << endl; return 0; }
true
dd6de7001b454615d86f8b485e8ec0afcbba2c2c
C++
arnoud67/disruptorcpp
/test/support/long_event.h
UTF-8
504
2.875
3
[]
no_license
#ifndef DISRUPTOR_TEST_LONG_EVENT_H_ #define DISRUPTOR_TEST_LONG_EVENT_H_ class LongEvent { public: LongEvent(int64_t value = 0) : value_(value) { } int64_t value() const { return value_; } void set_value(int64_t value) { value_ = value; } private: int64_t value_; }; class LongEventFactory { public: LongEvent* NewInstance(const int& size) const { return new LongEvent[size]; } LongEvent* operator()() { return new LongEvent(); } }; #endif // DISRUPTOR_TEST_LONG_EVENT_H_
true
2ae5375ac1e58b52117678bad607ffc71a821165
C++
Kadzugi/projectToDoList
/ProjectMertex/ProjectMertex.cpp
UTF-8
8,018
3
3
[]
no_license
// ProjectMertex.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> #include <vector> #include <String> #include <regex> using namespace std; struct MyToDo { string description; string date; void print() { cout << date << " - " << description << endl; } }; int check(vector<MyToDo> ToDoList, string act, int flag) { int location = 0; for (size_t i = 0; i < ToDoList.size(); i++) { if (ToDoList[i].date == act.substr(act.length() - 16) && flag == 1) { location = i + 1; break; } else if (ToDoList[i].date < act.substr(act.length() - 16) && flag == 2) { location += 1; } else if (ToDoList[i].date > act.substr(act.length() - 16) && flag == 3) { location = i + 1; break; } else if (ToDoList[i].date <= act.substr(act.length() - 16) && flag == 4) { location += 1; } else if (ToDoList[i].date >= act.substr(act.length() - 16) && flag == 5) { location += 1; } } return location; }; int main() { setlocale(LC_ALL, "ru"); cout << "Вас приветствует консольное приложение To Do List." << endl; bool exitToDo = false; vector<MyToDo> ToDoList; string act; regex regular_add("(add) ([\\w\\s\\d\\Q.?()+{}*^'\\E\\\\\"\\/\\|\\!\\$\\[\\],;:-_-@#№%&<>=])* (\\d{4})-(0[1-9]|1[0-2])-(3[0-1]|[1-2][0-9]|0[1-9]) ([0-1][0-9]|2[0-3]):([0-5][0-9])"); regex regular_update("(update) ([\\w\\s\\d\\Q.?()+{}*^'\\E\\\\\"\\/\\|\\!\\$\\[\\],;:-_-@#№%&<>=])* (\\d{4})-(0[1-9]|1[0-2])-(3[0-1]|[1-2][0-9]|0[1-9]) ([0-1][0-9]|2[0-3]):([0-5][0-9])"); regex regular_delete("(delete) (\\d{4})-(0[1-9]|1[0-2])-(3[0-1]|[1-2][0-9]|0[1-9]) ([0-1][0-9]|2[0-3]):([0-5][0-9])"); regex regular_select_date("(select) (where date) (<|>|=|<=|>=) (\\d{4})-(0[1-9]|1[0-2])-(3[0-1]|[1-2][0-9]|0[1-9]) ([0-1][0-9]|2[0-3]):([0-5][0-9])"); regex regular_select_descriptor("(select) (where descriptor hase) ([\\w\\s\\d\\Q.?()+{}*^'\\E\\\\\"\\/\\|\\!\\$\\[\\],;:-_-@#№%&<>=])*"); regex regular_select("(select \\*)"); regex regular_help("(help)"); regex regular_exit("(exit)"); while (!exitToDo) { cout << "Доступны следующие команды: add, delete, update, select, help, exit." << endl << "Формат даты и времени(гггг-мм-дд 00:00)." << endl << endl; getline(cin, act); cout << endl; if (regex_match(act.c_str(), regular_add)) { act.erase(0, 4); if (ToDoList.empty() == true || check(ToDoList, act, 1) == 0) { MyToDo m; m.date = act.substr(act.length() - 16); m.description = act.substr(0, act.length() - 16); ToDoList.insert(ToDoList.cbegin() + check(ToDoList, act, 2), m); act.clear(); cout << "Задача создана!" << endl; } else { cout << "Задача с указанными датой и временем уже создана, пожалуйста введите другую дату и время." << endl << "Или измените существующую задачу." << endl; } } else if (regex_match(act.c_str(), regular_update)) { act.erase(0, 7); if (check(ToDoList, act, 1) > 0) { ToDoList[check(ToDoList, act, 1) - 1].description = act.substr(0, act.length() - 16); act.clear(); cout << "Задача обновлена!" << endl; } else { cout << "За указзанную дату и время активных задач не найдено." << endl; } } else if (regex_match(act.c_str(), regular_delete)) { act.erase(0, 7); if (check(ToDoList, act, 1) > 0) { ToDoList.erase(ToDoList.cbegin() + check(ToDoList, act, 1) - 1); act.clear(); cout << "Задача удалена!" << endl; } else { cout << "За указзанную дату и время активных задач не найдено." << endl; } } else if (regex_match(act.c_str(), regular_select_date)) { act.erase(0, 7); if (act.substr(act.length() - 19, 2) == " =") { if (check(ToDoList, act, 1) != 0) { ToDoList[check(ToDoList, act, 1) - 1].print(); } else { cout << "Нет задач соответствующих выбранным условиям." << endl; } } else if (act.substr(act.length() - 18, 1) == "<") { if (check(ToDoList, act, 2) != 0) { for (int i = 0; i < check(ToDoList, act, 2); i++) { ToDoList[i].print(); } } else { cout << "Нет задач соответствующих выбранным условиям." << endl; } } else if (act.substr(act.length() - 18, 1) == ">") { if (check(ToDoList, act, 3) != 0) { for (size_t i = check(ToDoList, act, 3) - 1; i < ToDoList.size(); i++) { ToDoList[i].print(); } } else { cout << "Нет задач соответствующих выбранным условиям." << endl; } } else if (act.substr(act.length() - 19, 2) == "<=") { if (check(ToDoList, act, 4) != 0) { for (int i = 0; i < check(ToDoList, act, 4); i++) { ToDoList[i].print(); } } else { cout << "Нет задач соответствующих выбранным условиям." << endl; } } else if (act.substr(act.length() - 19, 2) == ">=") { if (check(ToDoList, act, 5) != 0) { for (size_t i = check(ToDoList, act, 5) - 1; i < ToDoList.size(); i++) { ToDoList[i].print(); } } else { cout << "Нет задач соответствующих выбранным условиям." << endl; } } else { cout << "Нет задач соответствующих выбранным условиям." << endl; } } else if (regex_match(act.c_str(), regular_select_descriptor)) { int c = 0; if (ToDoList.empty() != true) { for (size_t i = 0; i < ToDoList.size(); i++) { if (ToDoList[i].description.find(act.substr(29)) != string::npos) { ToDoList[i].print(); c++; } } } else { cout << "Список задач пуст." << endl; } if (c == 0) { cout << "Задач с таким содержимым нет." << endl; } } else if (regex_match(act.c_str(), regular_select)) { if (ToDoList.empty() != true) { for (size_t i = 0; i < ToDoList.size(); i++) { ToDoList[i].print(); } } else { cout << "Список задач пуст." << endl; } } else if (regex_match(act.c_str(), regular_help)) { cout << "Команды вводятся в следующем формате:" << endl; cout << "add: add descriptor date (add text 2020-12-12 00:00) - добавить задачу на дату 2020-12-12 00:00" << endl; cout << "update: update descriptor date (update text 2020-12-12 00:00) - обновить задачу за дату 2020-12-12 00:00" << endl; cout << "delete: delete date (delete 2020-12-12 00:00) - удалить задачу за дату 2020-12-12 00:00" << endl; cout << "select: select * - вывод всех задач" << endl; cout << "select: select where date <; >; =; <=; >= date (select where date <= 2020-12-12 00:00) - вывод всех задач которые <= 2020-12-12 00:00" << endl; cout << "select: select where descriptor hase string (select where descriptor hase text) - вывод всех задач где в описании содержиться text" << endl; cout << "help: help - помощь" << endl; cout << "exit: exit - выход" << endl; } else if (regex_match(act.c_str(), regular_exit)) { cout << "Спасибо, за использование программы!" << endl; exitToDo = true; } else { cout << "Некорректный формат ввода или неверная команда." << endl; } } }
true
89995998a69047affd445a9ffb46f8370c91f246
C++
RyanAlameddine/Cpp-Data-Structures
/Graphs/Graphs/UUVertex.tpp
UTF-8
162
2.640625
3
[]
no_license
template<typename TValue> void UUVertex<TValue>::Connect(UUVertex<TValue>* target) { this->connections.push_back(target); target.connections.push_back(this); }
true
b2f31e8e53bd76f4e2469dcdc6614da4a86031c5
C++
yangcyself/CS385cpp
/cnn/layers.h
UTF-8
3,449
2.875
3
[]
no_license
#ifndef LAYERS_H_ #define LAYERS_H_ #include <cnn/basicOps.h> #include <Eigen/Dense> #include <Eigen/Core> #include <memory> //std::shared_ptr namespace convnn{ /** * layers are also operators, but with more complex functions * implemented layers are: * conv layer * fc layer * relu layer * max pooling layer * sigmoid layer * TODO: add bias in these layers */ /** * convlayer contains a variable as kernel, * it is just a wraper of Conv, together with its own variable * the forward and backward operations all works on kernel */ class ConvLayer:public Operator{ private: std::shared_ptr<Operator> a; Variable kernel; Conv convolution; public: /** * arguments * aa: input operator * inC: input channel number * outC: output channel number * K: the kernel size K*K * pad: padding * stride: stride * initRange: the variance to initialize the variable */ ConvLayer(Operator& aa, int inC, int outC, int K, int pad, int stride, double initRange) :a(&aa,&null_deleter),kernel(),convolution(aa,kernel,pad,stride) {kernel.initData(Tensor(matrix::Random(outC,inC*K*K )*initRange, K,K ));} ~ConvLayer(){} Tensor forward(){return convolution.forward();} Variable ker()const{return kernel;} void backward(const Tensor& in){ convolution.backward(in);} void train(){convolution.train();} void test(){convolution.test();} }; /** * FcLayer is a special case of conv layer where the kernel size equals to the input size * in most case, their size are all one. */ class FcLayer:public Operator{ private: std::shared_ptr<Operator> a; Variable kernel; Conv convolution; public: FcLayer(Operator& aa, int inC, int outC, double initRange) :a(&aa,&null_deleter),kernel(),convolution(aa,kernel,0,1) {kernel.initData(Tensor(matrix::Random(outC,inC*1*1 )*initRange, 1,1 ));} ~FcLayer(){} Tensor forward(){return convolution.forward();} void backward(const Tensor& in){convolution.backward(in);} void train(){convolution.train();} void test(){convolution.test();} }; /** * relulayer ... */ class ReluLayer:public Operator{ private: std::shared_ptr<Operator> a; Tensor ca; Tensor reluMask(const Tensor& in)const; public: ReluLayer(Operator& aa):a(&aa,&null_deleter){} ~ReluLayer(){} Tensor forward(); void backward(const Tensor& in); void train(){a->train();} void test(){a->test();} }; /** * maxpooling layer ... */ class MaxpoolLayer:public Operator{ private: std::shared_ptr<Operator> a; Eigen::VectorXi indevx; // the indexs for pooling Eigen::VectorXi indevy; // the indexs for pooling int K; int inputh, inputw; int inH, inW; void indexVector(Tensor& in); public: MaxpoolLayer(Operator& aa, int k):a(&aa,&null_deleter),K(k){} ~MaxpoolLayer(){} Tensor forward(); void backward(const Tensor& in); void train(){a->train();} void test(){a->test();} }; /** * sigmoid layer ... * The input a shoud have the shape N 1 1 1 */ class SigmoidLayer:public Operator{ private: std::shared_ptr<Operator> a; matrix ca; public: SigmoidLayer(Operator& aa):a(&aa,&null_deleter){} ~SigmoidLayer(){} Tensor forward(); void backward(const Tensor& in); void train(){a->train();} void test(){a->test();} }; } /* namespace convnn */ #endif //LAYERS_H_
true
af8758136da0f67f8c50cf88191416b338bbd3f8
C++
p4plus2/shex
/character_mapper.cpp
UTF-8
2,692
2.765625
3
[]
no_license
#include <QFile> #include <QRegExp> #include "character_mapper.h" #include "debug.h" bool character_mapper::load_map(QString map_file_path) { if(map == nullptr){ map = new QMap<unsigned char, unsigned char>(); }else{ map->clear(); } QFile map_file(map_file_path); if(!map_file.open(QIODevice::ReadOnly | QIODevice::Text)){ return (map_state = false); } while(!map_file.atEnd()){ QString line = map_file.readLine().trimmed(); int seperator = line.remove(QRegExp("//.*")).lastIndexOf('='); if(line.isEmpty()){ continue; } QString right = line.right(line.length()-seperator-1).trimmed(); QString left = line.left(seperator).trimmed().leftJustified(1, ' '); bool status; unsigned char value = right.toInt(&status, 16); if(seperator == -1 || left.length() != 1 || right.length() != 2 || !status){ return (map_state = false); } map->insert(left.at(0).toLatin1(), value); } return (map_state = true); } void character_mapper::save_map(QString map_file_path) { if(map == nullptr){ return; } QFile map_file(map_file_path); if(!map_file.open(QIODevice::WriteOnly | QIODevice::Text)){ return; } const QList<unsigned char> keys = map->keys(); const QList<unsigned char> values = map->values(); int count = keys.count(); for(int i = 0; i < count; i++){ QString line = QString((char)keys[i]) + "=" + QString::number(values[i], 16) + "\n"; map_file.write(line.toLatin1()); } } void character_mapper::set_map(QMap<unsigned char, unsigned char> *dialog_mapper) { if(map != nullptr && map != dialog_mapper){ delete map; } map = dialog_mapper; map_state = true; } unsigned char character_mapper::decode(unsigned char input) { if(map != nullptr && map->contains(input) && map_state){ return map->value(input); } return input; } QByteArray character_mapper::decode(QByteArray input) { if(map != nullptr && map_state){ for(int i = input.length() - 1; i > -1; i--){ unsigned char current = input.at(i); input[i] = map->contains(current) ? map->value(current) : current; } } return input; } unsigned char character_mapper::encode(unsigned char input) { if(map != nullptr && map->key(input) && map_state){ return map->key(input); } return input; } QByteArray character_mapper::encode(QByteArray input) { if(map != nullptr && map_state){ for(int i = input.length() - 1; i > -1; i--){ unsigned char current = input.at(i); input[i] = map->key(current) ? map->key(current) : current; } } return input; } void character_mapper::delete_active_map() { if(map != nullptr){ delete map; } } QMap<unsigned char, unsigned char> *character_mapper::map = nullptr; bool character_mapper::map_state = false;
true
51283f2ad028a20f4bf1f43772c02d6f695981c0
C++
Sanket-Mathur/100-days-of-code
/Language Fundamental/RandomNumbers.cpp
UTF-8
1,142
3.09375
3
[]
no_license
#include <iostream> #include <random> #include <time.h> #include <string.h> using namespace std; int main() { // simple pseudo random number generator srand(time(NULL)); for(int i = 0; i < 10; i++) { cout << rand() % 10 << " "; } cout << endl; // true random number generator random_device crypto_random_generator; uniform_int_distribution<int> int_distribution(0,9); int actual_distribution[10] = {0,0,0,0,0,0,0,0,0,0}; for(int i = 0; i < 10000; i++) { int result = int_distribution(crypto_random_generator); actual_distribution[result]++; } for(int i = 0; i < 10; i++) { cout << actual_distribution[i] << " "; } cout << endl; // pseudo random number generator memset(actual_distribution, 0, sizeof(actual_distribution)); default_random_engine pseudo_random_generator; for(int i = 0; i < 10000; i++) { int result = int_distribution(pseudo_random_generator); actual_distribution[result]++; } for(int i = 0; i < 10; i++) { cout << actual_distribution[i] << " "; } cout << endl; return 0; }
true
75a1f9284d33a94176acb87e74c4b4d20f6da495
C++
royvandewater/arduino-countdown-timer
/src/countdown-timer.ino
UTF-8
1,013
3.125
3
[ "MIT" ]
permissive
#define ONE_MINUTE (1 * 10 * 1000) #define ON true #define OFF false void setup() { for(int i = 0; i < 13; i++) { pinMode(i, OUTPUT); } } void blink_for_one_second(int pin) { digitalWrite(pin, LOW); delay(900); digitalWrite(pin, HIGH); delay(100); } void blink_all_lights_for_one_second() { for(int i = 0; i < 13; i++ ){ digitalWrite(i, LOW); } delay(400); for(int i = 0; i < 13; i++ ){ digitalWrite(i, HIGH); } delay(100); for(int i = 0; i < 13; i++ ){ digitalWrite(i, LOW); } delay(400); for(int i = 0; i < 13; i++ ) { digitalWrite(i, HIGH); } delay(100); } void turn_all_lights(bool on) { int state = on ? HIGH : LOW; for(int i = 0; i < 13; i++) { digitalWrite(i, state); } } void loop() { int i = 0; for(int i = 0; i < 2; i++) { for(int j = 0; j < 5; j++) { blink_for_one_second(i); } digitalWrite(i, HIGH); } for(int i = 0; i < 10; i ++) { blink_all_lights_for_one_second(); } turn_all_lights(OFF); }
true
28ed07cb7ea3b928618c09d4d1775e1c3d76a676
C++
yzq986/cntt2016-hw1
/TC-SRM-592-div1-300/yyt16384.cpp
UTF-8
587
3.765625
4
[]
no_license
#include <string> class LittleElephantAndBalls { public: int getNumber(std::string s); }; int LittleElephantAndBalls::getNumber(std::string s) { int ans = 0; int cr = 0; int cg = 0; int cb = 0; for (auto c : s) { // For every color, put the first ball in the left part and the // second ball in the right part ans += cr + cg + cb; if (c == 'R' && cr < 2) { cr++; } else if (c == 'G' && cg < 2) { cg++; } else if (c == 'B' && cb < 2) { cb++; } } return ans; }
true
ed5ff89aa50231221f551c162e4310923f287087
C++
taha7ussein007/The-Astronauts
/Space Ship_Rockets-launcher/Space Ship_Rockets-launcher/Stack.h
UTF-8
3,501
3.25
3
[]
no_license
#pragma once ///////////////////////////////////////////////////////////////////////// template<typename T> class Node{ ///////////////////////////////////////////////////////////////////// public: T info; //Node* next; Node* prev; ///////////////////////////////////////////////////////////////////// }; ///////////////////////////////////////////////////////////////////////// template<class type> class Stack{ ///////////////////////////////////////////////////////////////////////// private: Node<type> *Top; unsigned int Size; ///////////////////////////////////////////////////////////////////// public: Stack<type>(){ Top = nullptr; Size = 0; } ///////////////////////////////////////////////////////////////////// void push(type obj){ // Node<type>* tmpn = new Node<type>; tmpn->info = obj; // if (!this->Top) { tmpn->prev = nullptr; this->Top = tmpn; } else { tmpn->prev = this->Top; this->Top = tmpn; } this->Size++; } ///////////////////////////////////////////////////////////////////// void push(type obj, int index){ // Node<type>* tmpn = new Node<type>; tmpn->info = obj; // if (!this->Top) { tmpn->prev = nullptr; this->Top = tmpn; } else { Node<type>* target = this->Top; int i; for (i = (this->Size - 1) - index; i > 0; i--) target = target->prev; tmpn->prev = target->prev; target->prev = tmpn; } this->Size++; } ///////////////////////////////////////////////////////////////////// void assign(type obj, int index){ Node<type>* tmpn = this->Top; int i; for (i = (this->Size - 1) - index; i > 0; i--) tmpn = tmpn->prev; tmpn->info = obj; } ///////////////////////////////////////////////////////////////////// void pop(){ Node<type>* tmpn = this->Top; this->Top = this->Top->prev; delete tmpn; this->Size--; } ///////////////////////////////////////////////////////////////////// type top(){ return this->Top->info; } ///////////////////////////////////////////////////////////////////// type at(unsigned int index) { Node<type>* tmpn = this->Top; unsigned int i; for (i = (this->Size - 1) - index; i > 0; i--) tmpn = tmpn->prev; return tmpn->info; } ///////////////////////////////////////////////////////////////////// void swap(unsigned fromIndex, unsigned ToIndex){ type tmp = this->at(ToIndex); this->assign(this->at(fromIndex), ToIndex); this->assign(tmp, fromIndex); } ///////////////////////////////////////////////////////////////////// bool empty(){ return (this->Top == nullptr); } ///////////////////////////////////////////////////////////////////// unsigned int size(){ return this->Size; } ///////////////////////////////////////////////////////////////////// void remove(unsigned int index){ Node<type>* before = this->Top; if (index == this->Size - 1){ this->Top = this->Top->prev; delete before; } else { Node<type>* eraser; unsigned int i; for (i = (this->Size - 1) - index; i > 1; i--) before = before->prev; eraser = before->prev; before->prev = before->prev->prev; delete eraser; } this->Size--; } ///////////////////////////////////////////////////////////////////// void clear(){ while (this->Top){ Node<type>* tmpn = this->Top; this->Top = this->Top->prev; delete tmpn; } this->Size = 0; } ///////////////////////////////////////////////////////////////////////// }; /////////////////////////////////////////////////////////////////////////
true
cda9b89ce2276c717e113d548426493a8a9d027f
C++
dacuster/GameAI
/shared/DeanLib/PerformanceTracker.cpp
UTF-8
1,723
3.03125
3
[]
no_license
#include "PerformanceTracker.h" using namespace std; PerformanceTracker::PerformanceTracker() { } PerformanceTracker::~PerformanceTracker() { map<string,Timer*>::iterator iter; for( iter = mTimers.begin(); iter != mTimers.end(); ++iter ) { delete iter->second; } } void PerformanceTracker::startTracking( const string& trackerName ) { Timer* pTimer = NULL; //find if tracker already exists map<string,Timer*>::iterator iter = mTimers.find( trackerName ); if( iter != mTimers.end() ) { pTimer = iter->second; } else { pTimer = new Timer(); pTimer->start(); mTimers[trackerName] = pTimer; } pTimer->pause(false); } void PerformanceTracker::stopTracking( const string& trackerName ) { //make sure timer already exists map<string,Timer*>::iterator iter = mTimers.find( trackerName ); if( iter != mTimers.end() ) { iter->second->pause(true); } } double PerformanceTracker::getElapsedTime( const string& trackerName ) { //make sure timer already exists map<string,Timer*>::iterator iter = mTimers.find( trackerName ); if( iter != mTimers.end() ) { return iter->second->getElapsedTime(); } else return 0.0; } void PerformanceTracker::removeTracker( const std::string& trackerName ) { //find the existing timer map<string,Timer*>::iterator iter = mTimers.find( trackerName ); if( iter != mTimers.end() ) { delete iter->second; mTimers.erase( iter ); } } void PerformanceTracker::clearTracker( const std::string& trackerName ) { //find if tracker already exists map<string,Timer*>::iterator iter = mTimers.find( trackerName ); if( iter != mTimers.end() ) { iter->second->start(); } }
true
188067829b14da6d77bee9f54e82a4e7358a1cca
C++
Lancern/caf
/include/Infrastructure/Optional.h
UTF-8
4,179
3.921875
4
[]
no_license
#ifndef CAF_OPTIONAL_H #define CAF_OPTIONAL_H #include <cassert> #include <new> #include <utility> #include <type_traits> namespace caf { /** * @brief A monad representing an optional value. * * This class resembles the `Maybe` type class in Haskell and `Option` enum in Rust. * * @tparam T the type of the object contained in the optional value. */ template <typename T> class Optional { public: /** * @brief Construct a new Optional object that contains no values. * */ explicit Optional() : _hasValue(false) { } /** * @brief Construct a new Optional object that contains the given object. * * @param value the object to be contained in the constructed @see Optional<T> object. */ explicit Optional(T value) : _hasValue(false) { emplace(std::move(value)); } Optional(const Optional<T>& another) : _hasValue(false) { static_assert(std::is_copy_constructible<T>::value, "T is not copy constructible."); if (another.hasValue()) { emplace(another.value()); } } Optional(Optional<T>&& another) noexcept : _hasValue(false) { static_assert(std::is_move_constructible<T>::value, "T is not move constructible."); if (another.hasValue()) { emplace(another.take()); } } ~Optional() { drain(); } Optional<T>& operator=(const Optional<T>& another) { static_assert(std::is_copy_assignable<T>::value, "T is not copy assignable."); drain(); if (another.hasValue()) { emplace(another.value()); } return *this; } Optional<T>& operator=(Optional<T>&& another) { static_assert(std::is_move_assignable<T>::value, "T is not move assignable."); drain(); if (another.hasValue()) { emplace(another.take()); } return *this; } /** * @brief Determine whether this @see Optional<T> object contains a value. * * @return true if this @see Optional<T> object contains a value. * @return false if this @see Optional<T> object does not contain a value. */ bool hasValue() const { return _hasValue; } explicit operator bool() const { return hasValue(); } /** * @brief Destroy the old contained value and construct a new value using the given arguments in * place. * * @tparam Args types of arguments. * @param args arguments that will be passed to the constructor of T to construct a new value of * T in place. */ template <typename ...Args> void emplace(Args&&... args) { drain(); new(_value) T(std::forward<Args>(args)...); _hasValue = true; } /** * @brief Destroy the old contained value and moves the given value into this @see Optional<T> * instance. * * @param value the value to be moved in. */ void set(T value) { emplace(std::move(value)); } /** * @brief Destroy the old contained value, if there is one. After calling this function, this * @see Optional<T> object will be an empty container. * */ void drain() { if (_hasValue) { value().~T(); _hasValue = false; } } /** * @brief Take out the contained value, leave an empty Optional object behind. * * @return T the contained value. */ T take() { assert(_hasValue && "Trying to take an empty Optional object."); auto ret = std::move(value()); _hasValue = false; return ret; } /** * @brief Get a reference to the contained value. * * @return T& a reference to the contained value. */ T& value() { return *reinterpret_cast<T *>(static_cast<char *>(_value)); } /** * @brief Get a constant reference to the contained value. * * @return const T& a constant reference to the contained value. */ const T& value() const { return *reinterpret_cast<const T *>(static_cast<const char *>(_value)); } T& operator*() { return value(); } const T& operator*() const { return value(); } T* operator->() { return &value(); } const T* operator->() const { return &value(); } private: alignas(alignof(T)) char _value[sizeof(T)]; bool _hasValue; // _value contains raw data of an object of T which might be uninitialized. }; // class Optional } // namespace caf #endif
true
c8be33b634c7c4325a11957c48e70da83d6c6e5c
C++
samanseifi/Tahoe
/toolbox/src/C1functions/CosinePlusT.cpp
UTF-8
6,129
2.6875
3
[ "BSD-3-Clause" ]
permissive
/* $Id: CosinePlusT.cpp,v 1.4 2011/12/01 20:25:15 bcyansfn Exp $ */ #include "CosinePlusT.h" #include "dArrayT.h" #include <cmath> using namespace Tahoe; /* constructor */ CosinePlusT::CosinePlusT(double t0, double t1, double a, double b, double c, double d, double e, double f, double g, double p, double q): ft0(t0), ft1(t1), fa(a), fb(b), fc(c), fd(d), fe(e), ff(f), fg(g), fp(p), fq(q) { SetName("cosine_plus"); } CosinePlusT::CosinePlusT(void): ft0(0.0), ft1(0.0), fa(0.0), fb(0.0), fc(0.0), fd(0.0), fe(0.0), ff(0.0), fg(0.0), fp(0.0), fq(0.0) { SetName("cosine_plus"); } /** evaluate function */ double CosinePlusT::Function(double x) const { double fRamp = 1.0; if (ft0==0.0 && ft1==0.0) { fRamp = 1.0; } else if (x<ft0) { fRamp = 0.0; } else if (x>=ft0 && x<=ft1) { fRamp = (x-ft0)/(ft1-ft0); } else if (x>ft1) { fRamp = 1.0; } return fRamp*(fa + fb*cos(fc*x) + fd*sin(fe*x) + ff*x*cos(fg*x) + fp*x*sin(fq*x)); } /** evaluate first derivative function */ double CosinePlusT::DFunction(double x) const { double fRamp = 1.0; double fRampD = 0.0; if (ft0==0.0 && ft1==0.0) { fRamp = 1.0; fRampD = 0.0; } else if (x<ft0) { fRamp = 0.0; fRampD = 0.0; } else if (x>=ft0 && x<=ft1) { fRamp = (x-ft0)/(ft1-ft0); fRampD = 1/(ft1-ft0); } else if (x>ft1) { fRamp = 1.0; fRampD = 0.0; } return fRampD*(fa + fb*cos(fc*x) + fd*sin(fe*x) + ff*x*cos(fg*x) + fp*x*sin(fq*x)) + fRamp*(-fb*fc*sin(fc*x) + fd*fe*cos(fe*x) + ff*cos(fg*x) - ff*fg*x*sin(fg*x) + fp*sin(fq*x) + fp*fq*x*cos(fq*x)); } /** evaluate second derivative function */ double CosinePlusT::DDFunction(double x) const { double fRamp = 1.0; double fRampD = 0.0; if (ft0==0.0 && ft1==0.0) { fRamp = 1.0; fRampD = 0.0; } else if (x<ft0) { fRamp = 0.0; fRampD = 0.0; } else if (x>=ft0 && x<=ft1) { fRamp = (x-ft0)/(ft1-ft0); fRampD = 1/(ft1-ft0); } else if (x>ft1) { fRamp = 1.0; fRampD = 0.0; } return 2*fRampD*(-fb*fc*sin(fc*x) + fd*fe*cos(fe*x) + ff*cos(fg*x) - ff*fg*x*sin(fg*x) + fp*sin(fq*x) + fp*fq*x*cos(fq*x)) + fRamp*(-fb*fc*fc*cos(fc*x) - fd*fe*fe*sin(fe*x) - 2*ff*fg*sin(fg*x) - ff*fg*fg*x*cos(fg*x) + 2*fp*fq*cos(fq*x) - fp*fq*fq*x*sin(fq*x)); } /* Returning values in groups */ /** multiple function evaluations */ dArrayT& CosinePlusT::MapFunction(const dArrayT& in, dArrayT& out) const { #if __option(extended_errorcheck) /* dimension checks */ if (in.Length() != out.Length()) ExceptionT::GeneralFail("CosinePlusT::MapFunction("); #endif int length = in.Length(); double* y = out.Pointer(); const double* x = in.Pointer(); for (int i = 0; i < length; i++) { double r = *x++; double fRamp = 1.0; if (ft0==0.0 && ft1==0.0) { fRamp = 1.0; } else if (r<ft0) { fRamp = 0.0; } else if (r>=ft0 && r<=ft1) { fRamp = (r-ft0)/(ft1-ft0); } else if (r>ft1) { fRamp = 1.0; } *y++ = fRamp*(fa + fb*cos(fc*r) + fd*sin(fe*r) + ff*r*cos(fg*r) + fp*r*sin(fq*r)); } return out; } /** multiple first derivative evaluations */ dArrayT& CosinePlusT::MapDFunction(const dArrayT& in, dArrayT& out) const { #if __option(extended_errorcheck) /* dimension checks */ if (in.Length() != out.Length()) ExceptionT::GeneralFail("CosinePlusT::MapDFunction("); #endif int length = in.Length(); double* y = out.Pointer(); const double* x = in.Pointer(); for (int i = 0; i < length; i++) { double r = *x++; double fRamp = 1.0; double fRampD = 0.0; if (ft0==0.0 && ft1==0.0) { fRamp = 1.0; fRampD = 0.0; } else if (r<ft0) { fRamp = 0.0; fRampD = 0.0; } else if (r>=ft0 && r<=ft1) { fRamp = (r-ft0)/(ft1-ft0); fRampD = 1/(ft1-ft0); } else if (r>ft1) { fRamp = 1.0; fRampD = 0.0; } *y++ = fRampD*(fa + fb*cos(fc*r) + fd*sin(fe*r) + ff*r*cos(fg*r) + fp*r*sin(fq*r)) + fRamp*(-fb*fc*sin(fc*r) + fd*fe*cos(fe*r) + ff*cos(fg*r) - ff*fg*r*sin(fg*r) + fp*sin(fq*r) + fp*fq*r*cos(fq*r)); } return out; } /** multiple second derivative evaluations */ dArrayT& CosinePlusT::MapDDFunction(const dArrayT& in, dArrayT& out) const { #if __option(extended_errorcheck) /* dimension checks */ if (in.Length() != out.Length()) ExceptionT::GeneralFail("CosinePlusT::MapDDFunction("); #endif int length = in.Length(); double* y = out.Pointer(); const double* x = in.Pointer(); for (int i = 0; i < length; i++) { double r = *x++; double fRamp = 1.0; double fRampD = 0.0; if (ft0==0.0 && ft1==0.0) { fRamp = 1.0; fRampD = 0.0; } else if (r<ft0) { fRamp = 0.0; fRampD = 0.0; } else if (r>=ft0 && r<=ft1) { fRamp = (r-ft0)/(ft1-ft0); fRampD = 1/(ft1-ft0); } else if (r>ft1) { fRamp = 1.0; fRampD = 0.0; } *y++ = 2*fRampD*(-fb*fc*sin(fc*r) + fd*fe*cos(fe*r) + ff*cos(fg*r) - ff*fg*r*sin(fg*r) + fp*sin(fq*r) + fp*fq*r*cos(fq*r)) + fRamp*(-fb*fc*fc*cos(fc*r) - fd*fe*fe*sin(fe*r) - 2*ff*fg*sin(fg*r) - ff*fg*fg*r*cos(fg*r) + 2*fp*fq*cos(fq*r) - fp*fq*fq*r*sin(fq*r)); } return out; } /* describe the parameters needed by the interface */ void CosinePlusT::DefineParameters(ParameterListT& list) const { /* inherited */ C1FunctionT::DefineParameters(list); list.AddParameter(ft0, "t0"); list.AddParameter(ft1, "t1"); list.AddParameter(fa, "a"); list.AddParameter(fb, "b"); list.AddParameter(fc, "c"); list.AddParameter(fd, "d"); list.AddParameter(fe, "e"); list.AddParameter(ff, "f"); list.AddParameter(fg, "g"); list.AddParameter(fp, "p"); list.AddParameter(fq, "q"); /* set the description */ list.SetDescription("f(t) = H(t,t1-t0)*(a + b cos(c t) + d sin(e t) + f t cos(g t) + p t sin(q t))"); } /* accept parameter list */ void CosinePlusT::TakeParameterList(const ParameterListT& list) { /* inherited */ C1FunctionT::TakeParameterList(list); ft0 = list.GetParameter("t0"); ft1 = list.GetParameter("t1"); fa = list.GetParameter("a"); fb = list.GetParameter("b"); fc = list.GetParameter("c"); fd = list.GetParameter("d"); fe = list.GetParameter("e"); ff = list.GetParameter("f"); fg = list.GetParameter("g"); fp = list.GetParameter("p"); fq = list.GetParameter("q"); }
true
416b67b8ea3cc80b9ca68899527f616776dfe7e1
C++
maxidea1024/fun
/fun/sql/meta_column.h
UTF-8
2,879
2.828125
3
[]
no_license
// TODO accessor �̸��� �����ؾ��ұ�?? #pragma once #include <cstddef> #include "fun/sql/sql.h" namespace fun { namespace sql { /** * MetaColumn class contains column metadata information. */ class FUN_SQL_API MetaColumn { public: enum ColumnDataType { FDT_BOOL, FDT_INT8, FDT_UINT8, FDT_INT16, FDT_UINT16, FDT_INT32, FDT_UINT32, FDT_INT64, FDT_UINT64, FDT_FLOAT, FDT_DOUBLE, FDT_STRING, FDT_WSTRING, FDT_BLOB, FDT_CLOB, FDT_DATE, FDT_TIME, FDT_TIMESTAMP, FDT_UNKNOWN }; /** * Creates the MetaColumn. */ MetaColumn(); /** * Creates the MetaColumn. */ explicit MetaColumn(size_t position, const String& name = "", ColumnDataType type = FDT_UNKNOWN, size_t length = 0, size_t precision = 0, bool nullable = false); /** * Destroys the MetaColumn. */ virtual ~MetaColumn(); /** * Returns column name. */ const String& name() const; /** * Returns column maximum length. */ size_t length() const; /** * Returns column precision. * Valid for floating point fields only * (zero for other data types). */ size_t precision() const; /** * Returns column position. */ size_t position() const; /** * Returns column type. */ ColumnDataType type() const; /** * Returns true if column allows null values, false otherwise. */ bool IsNullable() const; protected: /** * Sets the column name. */ void SetName(const String& name); /** * Sets the column length. */ void SetLength(size_t length); /** * Sets the column precision. */ void SetPrecision(size_t precision); /** * Sets the column data type. */ void SetType(ColumnDataType type); /** * Sets the column nullability. */ void SetNullable(bool nullable); private: String name_; size_t length_; size_t precision_; size_t position_; ColumnDataType type_; bool nullable_; }; // // inlines // inline const String& MetaColumn::name() const { return name_; } inline size_t MetaColumn::length() const { return length_; } inline size_t MetaColumn::precision() const { return precision_; } inline size_t MetaColumn::position() const { return position_; } inline MetaColumn::ColumnDataType MetaColumn::type() const { return type_; } inline bool MetaColumn::IsNullable() const { return nullable_; } inline void MetaColumn::SetName(const String& name) { name_ = name; } inline void MetaColumn::SetLength(size_t length) { length_ = length; } inline void MetaColumn::SetPrecision(size_t precision) { precision_ = precision; } inline void MetaColumn::SetType(ColumnDataType type) { type_ = type; } inline void MetaColumn::SetNullable(bool nullable) { nullable_ = nullable; } } // namespace sql } // namespace fun
true
d5e72024a8a644bd4f68f1b5ac9e99a870656613
C++
mangesh-kurambhatti/CPP
/CDAC_CPP_PRACTICE/DAY_7/Day_7.1_inheritance_without_inheriting/main.cpp
UTF-8
2,128
3.71875
4
[]
no_license
/* * main.cpp * * Created on: 11-Mar-2019 * Author: sunbeam */ #include<iostream> #include<string> using namespace std; class Date { private: int day; int month; int year; public: Date(void) { this->day=0; this->month=0; this->year=0; } Date(int day,int month,int year):day(day),month(month),year(year) { cout<<"Date(int day,int month,int year):day(day),month(month),year(year)"<<endl; } void AcceptRecord(void) { cout<<"Day : "; cin>>this->day; cout<<"Month :"; cin>>this->month; cout<<"Year : "; cin>>this->year; } void PrintRecord(void) { cout<<this->day<<"/"<<this->month<<"/"<<this->year<<endl; } }; class Employee{ private : string name; int empid; float salary; Date JoinDate; public: Employee(void) { cout<<"Employee(void)"<<endl; this->name=""; this->empid=0; this->salary=0.0; //this->JoinDate=0; } Employee(string name,int empid,float salary,Date JoinDate):name(name),empid(empid),salary(salary),JoinDate(JoinDate) { cout<<" Employee(void)"<<endl; } Employee(string name,int empid,float salary,int day,int month,int year):name(name),empid(empid),salary(salary),JoinDate(day,month,year) { cout<<"Employee(string name,int empid,float salary,int day,int month,int year):name(name),empid(empid),salary(salary),JoinDate(day,month,year)"<<endl; } void AcceptRecord() { cout<<"Name : "; cin>>this->name; cout<<"Empid :"; cin>>this->empid; cout<<"salary :"; cin>>this->salary; cout<<"JoinDate :"; JoinDate.AcceptRecord(); } void ShowRecord() { cout<<"Name : "<<this->name<<endl; cout<<"Empid : "<<this->empid<<endl; cout<<"Salary : "<<this->salary<<endl; cout<<"JoinDate : "; this->JoinDate.PrintRecord(); } }; int main() { Employee e; e.AcceptRecord(); e.ShowRecord(); return 0; } int main3() { Employee e("abc",12,12345,12,12,1996); e.ShowRecord(); return 0; } int main2() { string name="abc"; int age=12; float salary=1.234; Date JoinDate(17,12,1996); Employee e(name,age,salary,JoinDate); e.ShowRecord(); return 0; } int main1() { Employee e; e.ShowRecord(); return 0; }
true
6b6faa5ded7804101175e20efac4d59de3e71963
C++
d-nery/InfoBuraco
/InfoBuraco/DAO/UsuarioDAO.cpp
UTF-8
3,470
2.65625
3
[]
no_license
#include <msclr/marshal_cppstd.h> #include "MySQL.h" #include "UsuarioDAO.h" #include "CargoDAO.h" namespace InfoBuraco { UsuarioDAO::UsuarioDAO() { } Usuario* UsuarioDAO::getUser(std::string login, std::string password) { CargoDAO cargoDAO; Usuario* usuario = nullptr; sql::Connection* conn = nullptr; sql::PreparedStatement* pstmt; sql::ResultSet* resultSet; try { conn = mySQL.getConnection(); if (password.empty()) { pstmt = conn->prepareStatement("SELECT * FROM usuario WHERE login = ?;"); pstmt->setString(1, login.data()); } else { pstmt = conn->prepareStatement("SELECT * FROM usuario WHERE login = ? and senha = UNHEX(SHA2(?, 256));"); pstmt->setString(1, login.data()); pstmt->setString(2, password.data()); } resultSet = pstmt->executeQuery(); if (resultSet->next()) { usuario = new Usuario; usuario->login = resultSet->getString("login").c_str(); usuario->name = resultSet->getString("nome").c_str(); usuario->cargo = cargoDAO.getCargo(resultSet->getInt("cargo_id")); } } catch (sql::SQLException& e) { if (conn != nullptr) conn->close(); System::Diagnostics::Debug::Print("Erro getUser"); System::Diagnostics::Debug::Print(msclr::interop::marshal_as<System::String^>(e.what())); } return usuario; } std::vector<Usuario*>* UsuarioDAO::getAll() { CargoDAO cargoDAO; std::vector<Usuario*>* ret = new std::vector<Usuario*>; sql::Connection* conn = nullptr; sql::ResultSet* resultSet; sql::PreparedStatement* pstmt; int temp_int; std::string temp_str; try { conn = mySQL.getConnection(); pstmt = conn->prepareStatement("SELECT * FROM usuario;"); resultSet = pstmt->executeQuery(); while (resultSet->next()) { Usuario* usuario = new Usuario; usuario->login = resultSet->getString("login").c_str(); usuario->name = resultSet->getString("nome").c_str(); usuario->cargo = cargoDAO.getCargo(resultSet->getInt("cargo_id")); ret->push_back(usuario); } } catch (sql::SQLException& e) { if (conn != nullptr) conn->close(); System::Diagnostics::Debug::Print(msclr::interop::marshal_as<System::String^>(e.what())); } return ret; } void UsuarioDAO::insertUsuario(Usuario* usuario, std::string password) { CargoDAO cargoDAO; sql::Connection* conn = nullptr; sql::PreparedStatement* pstmt; try { conn = mySQL.getConnection(); pstmt = conn->prepareStatement("INSERT INTO usuario VALUES (?, UNHEX(SHA2(?)), ?, ?);"); pstmt->setString(1, usuario->login); pstmt->setString(2, password); pstmt->setString(3, usuario->name); pstmt->setInt(3, usuario->cargo->getId()); pstmt->executeUpdate(); } catch (sql::SQLException& e) { if (conn != nullptr) conn->close(); System::Diagnostics::Debug::Print(msclr::interop::marshal_as<System::String^>(e.what())); } } UsuarioDAO::~UsuarioDAO() { } }
true
062bb33526c7ad5357e15ca4c93114f185e58df8
C++
zhuhk/test-toys
/cpp/t_c11.cpp
UTF-8
23,491
2.59375
3
[]
no_license
#include <iostream> // std::cout #include <thread> // std::thread #include <future> // std::promise, std::future #include <unistd.h> #include <vector> #include <atomic> #include <cstdio> #include <memory> #include <mutex> #include <set> #include <map> #include <unordered_map> #include <future> #include <functional> #include <queue> #include "misc.h" #include <sparsehash/sparse_hash_map> #include <sparsehash/dense_hash_map> #include <stdarg.h> using namespace std; using namespace google; #define COUT \ cout << __FUNCTION__ << ":" << __LINE__ << " " int async_run(int i){ cout << "threadId " << std::this_thread::get_id() << " id" << i << endl; sleep(30); return i; } void test_async(){ vector<future<int>> futs(10000); for(int i=0; i<10000;i++){ // futs[i] = async(launch::async, async_run, i); futs[i] = async(async_run, i); } cout << "start sleep 10s" <<endl; sleep(10); cout << "wait" <<endl; for(int i=0; i<10000; i++){ cout << "result " << i << " " << futs[i].get() << endl; } } uint64_t total1; mutex mtx1; atomic<uint64_t> total2; atomic_long total3; void atomic1(uint64_t cnt){ for(uint64_t i=0; i<cnt; i++){ ++total1; --total1; } } void atomic2(uint64_t cnt){ for(uint64_t i=0; i<cnt; i++){ total2.fetch_add(1); total2.fetch_sub(1); //total2++; } } void atomic1_load(uint64_t cnt){ for(uint64_t i=0; i<cnt; i++){ if(total1>0){ } } } void atomic2_load(uint64_t cnt){ for(uint64_t i=0; i<cnt; i++){ if(total2>0){ } } } void atomic3(uint64_t cnt){ for(uint64_t i=0; i<cnt; i++){ ++total3; --total3; } } void atomic1_lock(uint64_t cnt){ for(uint64_t i=0; i<cnt; i++){ lock_guard<mutex> lock(mtx1); total1++; } } void test_atomic(){ time_t begin = 0; thread t[10]; total1 = 0; begin = PR_Now(); for(int i=0; i<10; i++){ t[i] = thread(atomic1_lock, 1000000); } for(int i=0; i<10; i++){ t[i].join(); } cout << "atomic1_lock time:" << PR_Now() - begin << "ms " << "total:" << total1 <<endl; total1 = 0; begin = PR_Now(); for(int i=0; i<10; i++){ t[i] = thread(atomic1, 1000000); } for(int i=0; i<10; i++){ t[i].join(); } cout << "atomic1 time:" << PR_Now() - begin << "ms " << "total:" << total1 <<endl; total2 = 0; begin = PR_Now(); for(int i=0; i<10; i++){ t[i] = thread(atomic2, 1000000); } for(int i=0; i<10; i++){ t[i].join(); } cout << "atomic2 - time:" << PR_Now() - begin << "ms " << "total:" << total2 <<endl; total3 = 0; begin = PR_Now(); for(int i=0; i<10; i++){ t[i] = thread(atomic3, 1000000); } for(int i=0; i<10; i++){ t[i].join(); } cout << "atomic3 - time:" << PR_Now() - begin << "ms " << "total:" << total3 <<endl; total3 = 0; begin = PR_Now(); for(int i=0; i<10; i++){ t[i] = thread(atomic1_load, 1000000); } for(int i=0; i<10; i++){ t[i].join(); } cout << "atomic1_load - time:" << PR_Now() - begin << "ms " << "total:" << total3 <<endl; total3 = 0; begin = PR_Now(); for(int i=0; i<10; i++){ t[i] = thread(atomic2_load, 1000000); } for(int i=0; i<10; i++){ t[i].join(); } cout << "atomic2_load - time:" << PR_Now() - begin << "ms " << "total:" << total3 <<endl; } shared_future<bool> fut; promise<bool> prom; void fut_wait(){ thread::id tid = this_thread::get_id(); while(fut.valid()){ fut.wait(); bool ret = fut.get(); COUT << tid << " ret:" << ret << endl; } } void t_future(){ //NOTICE("fut.get"); //fut.get(); NOTICE("fut.wait"); fut.wait(); thread t1(fut_wait), t2(fut_wait), t3(fut_wait); while(true){ prom = promise<bool>(); fut = prom.get_future(); sleep(2); prom.set_value(false); sleep(3); } t1.join(); t2.join(); t3.join(); } void t_set_del(){ set<uint64_t> values; for(uint64_t i=0; i<10; i++){ values.insert(i); } for(set<uint64_t>::iterator it=values.begin(); it!=values.end();){ printf("%lu\n", *it); values.erase(it++); } } void t_vec(){ vector<int> v; for(int i=0; i<10; i++){ v.push_back(i); } for(auto i : v){ cout << i << endl; i = 3; } for(int i=0; i<10; i++){ cout << "after " << v[i] <<endl; } for(auto& i : v){ cout << i << endl; i = 3; } for(int i=0; i<10; i++){ cout << "after " << v[i] <<endl; } } shared_ptr<int> g_sptr1(new int); shared_ptr<int> g_sptrs[100]; void sptr_thread(){ for(int i=0;i<10000000;i++){ int k = 10; k = k + i; } shared_ptr<int> sptr2 = g_sptr1; cout << "thread:" << g_sptr1.use_count() << " " << sptr2.use_count() << endl; sleep(3); } void sptr_perf_thread(int p){ time_t start = PR_Now(); int j = 0; int k = 0; for(int i=0;i<100000;i++){ shared_ptr<int> &sptr = g_sptrs[p]; int *ptr = sptr.get(); //int *ptr = &k; for(int j = 0; j<1; j++){ *ptr = j + i; } continue; //int *ptr = sptr.get(); } cout << "thread perf:" << PR_Now() - start << endl; } void t_shared_ptr(){ shared_ptr<int> sptr1(new int); *sptr1 = 1; shared_ptr<int> sptr2 = sptr1; shared_ptr<int> sptr3 = sptr2; sptr1.reset(new int); *sptr1 = 2; shared_ptr<int> sptr4 = sptr2; shared_ptr<int> sptr5 = sptr1; cout << sptr1.use_count() << " " << sptr2.use_count() << " " << sptr3.use_count() << " " << sptr4.use_count() << " " << sptr5.use_count() << endl; cout << *sptr1 << " " << *sptr2 << " " << *sptr3 << " " << *sptr4 << " " << *sptr5 << endl; thread t[10]; for(int i=0; i<sizeof(t)/sizeof(thread); i++){ g_sptrs[i].reset(new int); //t[i] = thread(sptr_thread); t[i] = thread(sptr_perf_thread, i); } /* for(int i=0; i<10; i++){ cout << g_sptr1.use_count() << endl; sleep(1); } */ for(int i=0; i<sizeof(t)/sizeof(thread); i++){ // cout << g_sptr1.use_count() << endl; t[i].join(); } for(int i=0; i<1; i++){ t[i] = thread(sptr_perf_thread, i); } for(int i=0; i<1; i++){ t[i].join(); } } void t_hash(){ char arr1[] = "test"; char arr2[] = "test"; string str1 = "test"; string str2 = "test"; hash<char*> arrHash; hash<string> strHash; cout << arrHash(arr1) <<endl; cout << arrHash(arr2) <<endl; cout << strHash(str1) <<endl; cout << strHash(str2) <<endl; } struct TestCopy{ atomic<int> v1; TestCopy & operator=( TestCopy &input){ v1 = input.v1.load(); return *this; } }; void t_copy(){ TestCopy a1; TestCopy a2; a1.v1 = 100; a2.v1 = 2; a1 = a2; cout << "a1=" << a1.v1 << endl; } //typedef std::unique_ptr<std::FILE, int (*)(std::FILE *)> unique_file_ptr_t; void test_autofile(){ for(int i=0;i<10000;i++){ unique_ptr<std::FILE, int (*)(std::FILE *)> uniqFile(std::fopen("test.txt", "w+"), std::fclose); if(!uniqFile){ NOTICE("fail"); }else{ fprintf(uniqFile.get(), "%d\n", i); } } } void test_map_perf(){ unordered_map<string,string> aaa; aaa[""] = "123"; return; map<int64_t, double> dict; unordered_map<int64_t, float> hashDict; //map<int64_t, float> hashDict; NOTICE("sizeof(map<int64_t,double>):%lu", sizeof(map<int64_t,double>)); NOTICE("sizeof(map<int64_t,float>):%lu", sizeof(map<int64_t,float>)); NOTICE("sizeof(unordered_map<int64_t,float>):%lu", sizeof(unordered_map<int64_t,double>)); NOTICE("sizeof(unordered_map<int64_t,float>):%lu", sizeof(unordered_map<int64_t,float>)); NOTICE("sizeof(string):%lu", sizeof(string)); NOTICE("build dict"); for(int i=0; i<5000000; i++){ dict[i*7+1] = i * 111.0; } sleep(2); NOTICE("clean dict. size:%lu", dict.size()); //dict.clear(); sleep(2); NOTICE("build hash dict"); for(int i=0; i<5000000; i++){ hashDict[i*7+1] = i * 113.0; } sleep(2); NOTICE("clean hash dict. size:%lu", hashDict.size()); //hashDict.clear(); sleep(2); sparse_hash_map<int64_t, double> smap; dense_hash_map<int64_t, double> dmap; dmap.set_empty_key(0); NOTICE("build sparse hash map"); for(int i=0; i<5000000; i++){ smap[i*7+1] = i * 111.0; } sleep(2); NOTICE("finish dict. size:%lu", smap.size()); sleep(2); NOTICE("build dense hash map"); for(int i=0; i<5000000; i++){ dmap[i*7+1] = i * 111.0; } sleep(2); NOTICE("finish dense dict. size:%lu", dmap.size()); sleep(2); time_t begin; for(int j=0; j<10; j++){ begin = PR_Now(); for(int i=0;i<10000;i++){ dict.find(i*7+1); } NOTICE("map:%lu", PR_Now() - begin); begin = PR_Now(); for(int i=0;i<10000;i++){ hashDict.find(i*7+1); } NOTICE("unordered_map:%lu", PR_Now() - begin); begin = PR_Now(); for(int i=0;i<10000;i++){ smap.find(i*7+1); } NOTICE("sparse hash map:%lu", PR_Now() - begin); begin = PR_Now(); for(int i=0;i<10000;i++){ dmap.find(i*7+1); } NOTICE("dense hash map:%lu", PR_Now() - begin); begin = PR_Now(); for(int i=0;i<10000;i++){ dict.find(i*7+2); } NOTICE("miss map:%lu", PR_Now() - begin); begin = PR_Now(); for(int i=0;i<10000;i++){ hashDict.find(i*7+2); } NOTICE("miss unordered_map:%lu", PR_Now() - begin); begin = PR_Now(); for(int i=0;i<10000;i++){ smap.find(i*7+2); } NOTICE("miss sparse hash map:%lu", PR_Now() - begin); begin = PR_Now(); for(int i=0;i<10000;i++){ dmap.find(i*7+2); } NOTICE("miss dense hash map:%lu", PR_Now() - begin); NOTICE(""); } } void test_priority_queue(){ priority_queue<int, vector<int>, greater<int> > q; q.push(10); q.push(11); q.push(12); q.push(13); cout << q.top() << endl; q.pop(); cout << q.top() << endl; q.pop(); cout << q.top() << endl; q.pop(); cout << q.top() << endl; q.pop(); } void test_heap(){ vector<int> v; v.push_back(1); push_heap(v.begin(),v.end()); v.push_back(7); push_heap(v.begin(),v.end()); v.push_back(3); push_heap(v.begin(),v.end()); v.push_back(9); push_heap(v.begin(),v.end()); for (unsigned i=0; i<v.size(); i++) std::cout << ' ' << v[i]; cout << endl; } struct SetItem{ time_t created; string data; bool operator < (const SetItem &rhs) const{ return created<rhs.created || (created==rhs.created && data<rhs.data); } }; void test_set(){ set<SetItem> s; SetItem item; for(int i = 0; i<10; i++){ item.created = PR_Now() % 10000; item.data = "data" + to_string(i); s.insert(item); } item.data = "data" + to_string(13); cout << "item:" << item.created << " " << item.data << endl; s.insert(item); cout << "item:" << item.created << " " << item.data << endl; for(auto &i: s){ cout << "set: " << i.created << " " << i.data << endl; } auto j = s.begin(); cout << "first:" << j->created << " " << j->data << endl; cout << "item:" << item.created << " " << item.data << endl; auto k = s.find(item); if(k != s.end()){ cout << "found " << k->created << " " << k->data << endl; }else{ cout << "not found " << item.created << item.data << endl; } cout << "item:" << item.created << " " << item.data << endl; s.erase(item); k = s.find(item); if(k != s.end()){ cout << "found " << k->created << " " << k->data << endl; }else{ cout << "not found " << item.created << item.data << endl; } } void test_map(){ map<string, string> m; m["k1"] = "v1"; m["k2"] = "v2"; m["k3"] = "v3"; for(auto item: m){ cout << "key:" << item.first << " value:" << item.second << endl; } } class C{ public: ~C(){ cout << "release C" << endl; } }; void test_shared_ptr(){ C c; { shared_ptr<C> ptr(&c); } cout << "after" << endl; } void test_gdb_map(){ map<int, int> m; m[0] = 1; m[1] = 1; m[2] = 1; string str("1234"); string str1("1234"); return; } void test_map_perf1(){ unordered_map<string, string> a1; a1["s1"] = "v1"; a1["s2"] = "v2"; vector<pair<string,string>> va1; for(auto &item:a1){ va1.push_back(std::move(item)); } for(auto &item:a1){ cout << "a1:" << item.first << item.second << endl; } unordered_map<string, vector<string>> aaa({ {"ag", {"602", "603"}}, {"cmi", {"20736"}}, {"crowd", {"902", "913"}}, {"", {"501"}}, {"rtst", {"peC5GS", "g6jY35", "Ltkoz3", "qd2CMs", "MTxQba", "4nW41X", "G7tmEX", "12BMi1", "cQoB8E", "OWz98F"}}, {"rtuhy",{"1x118x123x126"}}, {"rtuhy1",{"1"}}, {"rtuhy2", {"1x118"}}, {"rtuhy3", {"1x118x123"}}, {"sti", {"80301", "80103"}}, {"uch1",{"sina_home", "hdphoto", "cmnt", "sports", "kandian", "so", "sc", "news", "plan", "survey"}}, {"uch2", {"blog_dpool", "sports_nba", "sc_news", "news_sh", "sc_null", "proc_cmnt", "finance_china", "survey_null", "news_news_zt", "sports_sports_zt"}}, {"uit", {"20736"}} }); cout << "aaa:" << aaa[""][0] << endl; cout << "aaa:" << aaa["ag"][0] << endl; unordered_map<int,string> m; unordered_map<int,string> m1; unordered_map<int,string> m2; time_t begin; begin = PR_Now(); for(int i=0; i<1000; i++){ m[i] = "123"; m[1000-i] = "123"; } cout << "m[i]=123:" << PR_Now() - begin << endl; begin = PR_Now(); for(int i=0; i<1000; i++){ m1.insert(make_pair(i, "123")); m1.insert(make_pair(1000-i, "123")); } cout << "insert(make_pair):" << PR_Now() - begin << endl; begin = PR_Now(); for(int i=0; i<1000; i++){ m1.insert(std::move(make_pair(i, "123"))); m2.insert(std::move(make_pair(1000-i, "123"))); } cout << "insert(move(make_pair)):" << PR_Now() - begin << endl; string str1("str1"), str2("str2"); str2 = std::move(str1); cout << "str1:"<< str1 << " str2:" << str2 << endl; char arr[1000][10]; vector<const char*> vec; unordered_map<int, const char*> m3; for(int i=0;i<10;i++){ vec.push_back(NULL); m3[i] = NULL; } const char *pch; begin = PR_Now(); for(int i=1000000; i>0; i--){ pch = m3[i%10]+1; } pch += 1; cout << "unordered_map:" << PR_Now() - begin << endl; begin = PR_Now(); for(int i=10000000; i>0; i--){ pch = vec[i%10]+1; } pch += 1; cout << "vec:" << PR_Now() - begin << endl; begin = PR_Now(); for(int i=10000000; i>0; i--){ pch = arr[i%10]+1; } pch += 1; cout << "arr:" << PR_Now() - begin << endl; vector<int> v1, v2; for(int i=0;i<10;i++){ v1.push_back(i); v2.push_back(10-i); } v1 = std::move(v2); cout << v1.size() << " " << v2.size() << endl; map<string, vector<string>> features, newFeatures; features["1"].push_back("1"); features["1"].push_back("1"); features["1"].push_back("1"); features["2"].push_back("2"); features["2"].push_back("2"); features["2"].push_back("2"); for (const auto& feature: features) { vector<string> vec(std::move(feature.second)); cout << "feature: "<< feature.first << ":" << feature.second.size() << endl; } } string f1(){ static string str("123"); string &str1 = str; return str; } void test_vec_perf1(){ vector< pair<string,vector<string> > > m; vector< pair<string,vector<string> > > m1; vector< pair<string,vector<string> > > m2; vector< pair<string,vector<string> > > m3; vector< pair<string,vector<string> > > m4; string s1 = std::move(f1()); string s2 = std::move(f1()); string s3 = std::move(f1()); string s4 = std::move(s3.substr(1,2)); cout << "s1:" << s1 << endl; cout << "s2:" << s2 << endl; cout << "s3:" << s3 << endl; cout << "s4:" << s4 << endl; time_t begin; begin = PR_Now(); string str("123"); for(int i=0; i<10000; i++){ pair<string, vector<string> > p(str, {"321"}); m.push_back(p); } cout << "m.push_back:" << PR_Now() - begin << endl; begin = PR_Now(); str = "3214"; for(int i=0; i<10000; i++){ pair<string, vector<string> > p; p.first = str; p.second.push_back("123"); m1.push_back(p); } cout << "m1.push_back(str):" << PR_Now() - begin << endl; begin = PR_Now(); str = "321"; for(int i=0; i<10000; i++){ pair<string, vector<string> > p; p.first = str; p.second.push_back("123"); m2.push_back(std::move(p)); if(i==9999){ cout << "p:" << p.first << "=" << p.second.size() << endl; } } cout << "m2.push_back(move str):" << PR_Now() - begin << endl; begin = PR_Now(); str = "321"; for(int i=0; i<10000; i++){ pair<string, vector<string> > p; p.first = "111"; p.second.push_back("123"); m4.push_back(std::move(p)); } cout << "m2.push_back(move char):" << PR_Now() - begin << endl; begin = PR_Now(); str = "3213"; for(int i=0; i<10000; i++){ pair<string, vector<string> > p; p.first = str; m3.push_back(std::move(p)); m3.back().second.push_back("123"); } cout << "m3.push_back(move back):" << PR_Now() - begin << endl; } void test_substr(){ string url = "http://abc"; auto startPos = url.find("://"); if(startPos != string::npos){ startPos += 3; } else{ startPos = 0; } auto slashPos = url.find("/", startPos); string ret = url.substr(startPos, slashPos - startPos); cout << ret << endl; } void test_refstr(){ string str1="123", str2="456"; const string & s = str1 + str2; cout << s << endl; printf("%p %p %p\n", &str1, &str2, &s); } int NumberOfSetBits(int i){ // Java: use >>> instead of >> // C or C++: use uint32_t i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; } void test_bitcount(){ time_t b,e; b = PR_Now(); for(int i=0;i<10000;i++){ __builtin_popcount(i); } e = PR_Now(); cout << "builtin_popcount:" << e - b << endl; b = PR_Now(); for(int i=0;i<10000;i++){ NumberOfSetBits(i); } e = PR_Now(); cout << "NumberOfSetBits:" << e - b << endl; for(int i=0;i<1000000;i++){ int i1 = __builtin_popcount(i); int i2 = NumberOfSetBits(i); if(i1 != i2){ cout << "diff: i1=" << i1 << " i2=" << i2 << endl; } } } class G{ public: int m = 0; string dName = "name"; }; template <class T> class F : public G{ T n; }; template <class T> class D : public F<T>{ public: void print(){ cout << "m:" << this->m << endl; cout << "name:" << this->dName << endl; } }; void test_tpl_inherit(){ D<int> d; d.print(); } int Snprintf(char *buf, size_t buf_size, const char *fmt, ...) { va_list ap; va_start (ap, fmt); int real_size = vsnprintf(buf, buf_size, fmt, ap); va_end (ap); if(real_size < 0){ real_size = 0; } if(real_size > buf_size){ real_size = buf_size; } return real_size; } void test_snprintf(){ char buf[20]; int off = 0; for(int i=0; i<20; i++){ off += Snprintf(buf+off, 9-off, "%d", i); printf("%d %s %d %d %d\n", off, buf, buf[9], buf[10],buf[11]); } string a; printf("%p %lu\n", a.c_str(), a.capacity()); a.reserve(1024); printf("%p %lu\n", a.c_str(), a.capacity()); } static void SortTopK(const unordered_map<string, float>& feature_weight, uint32_t topK, vector<string>* features) { if (topK >= feature_weight.size()) { for (const auto& it : feature_weight) { features->push_back(it.first); } return; } typedef std::pair<string, float> qMember; auto comparator = [](qMember a, qMember b){ if(a.second == b.second){ cout << "k:" << a.second << " " << b.second << " " << a.first << " " << b.first<< endl; return a.first > b.first; }else{ cout << "gt:" << a.second << " " << b.second << endl; return a.second > b.second; } }; priority_queue<qMember, vector<qMember>, decltype(comparator)> pqueue(comparator); for (const auto& it : feature_weight) { // sort with priority queue and select topK if (pqueue.size() < topK) { pqueue.push(it); cout << "push:" << it.first << endl; } else { if (comparator(it, pqueue.top())) { cout << "replace:" << pqueue.top().first << " with " << it.first << endl; pqueue.pop(); pqueue.push(it); }else{ cout << "skip:" << it.first << endl; } } } while (!pqueue.empty()) { features->push_back(pqueue.top().first); pqueue.pop(); } } void t_sort(){ unordered_map<string, float> feature_weight = { {"1x244",1.0}, {"2x244",10.0}, {"3x244",11.0}, {"4x244",8.0} }; vector<string> features; //SortTopK(feature_weight, 2, &features); for(auto f: features){ cout << "f:" << f << endl; } /*unordered_map<string, float> feature_weight1 = { {"244x286x345x",1.0}, {"244x286x530x",1.0}, {"1x43x101x103",1.0}, {"244x286x337x529",1.0}, {"1x174x510x",1.0} }; */ unordered_map<string, float> feature_weight1 = { {"21270", 0.40651} ,{"20951",0.06775} ,{"20320",0.06775} ,{"21275",0.06775} ,{"20319",0.06775} ,{"20318",0.06775} ,{"20317",0.06775} ,{"20634",0.06775} ,{"20955",0.0663} ,{"20216",0.05293} }; features.clear(); SortTopK(feature_weight1, 3, &features); for(auto f: features){ cout << "f1:" << f << endl; } } #define add(a,b) a+b void t_ptr(){ int x[5]={1,2,3,4,5}; int *ptr=(int *)(&x+1); cout<<*(x+1)<<*(ptr-1) << endl; printf("%d\n", 7*add(3,4)); int a[] = {0,1,2,3,4,5 }, *p = a+1; cout << "ptr:" << endl; cout << *(++p) << endl; } class LogMessageVoidify { public: LogMessageVoidify() { } // This has to be an operator with a precedence lower than << but // higher than ?: void operator&(std::ostream&) { } }; #define TEST_IF_T 1 #define TEST_IF_F 0 void t_if(){ #if TEST_IF_T cout << "if T is true" <<endl; #else cout << "if T is false" <<endl; #endif #if TEST_IF_F cout << "if F is true" <<endl; #else cout << "if F is false" <<endl; #endif } class TestFunc{ public: static void foo(){ cout << 123 << endl; } }; void t_map(){ map<string, string> dict = { {"key","value"}, {"key1","value3"}, {"key1","value1"}, {"key2","value2"} }; for(auto &item: dict){ cout << item.first << " " << item.second << endl; } } void t_move(){ vector<string> origin = {"abc","bcd","efg"}; vector<string> dist; for(auto &value: origin){ dist.push_back(std::move(value)); } cout << "origin:" << endl; for(auto &val: origin){ if(val.empty()){ continue; } cout << " " << val << endl; } cout << "dist:" << endl; for(auto &val: dist){ cout << " " << val << endl; } map<string, string> m_origin{ {"key-abc","abc"}, {"key-bcd","bcd"}, {"key-efg","efg"} }; map<string,string> m_dist; for(auto &value: m_origin){ m_dist[std::move(value.first)] = std::move(value.second); } } int main () { t_move(); return 0; t_map(); return 0; void (*ptr)() = &TestFunc::foo; ptr(); return 0; t_if(); return 0; false ? (void) 0 : LogMessageVoidify() & cout << "abc"; return 0; // int i; for(i=1;i<10; i++) cout<<i<<endl; // int i=1; for(int j=0;i<10&&j<10; i++, j++)cout<<i+j<<endl; cout<<i; // int i=0; for(;i<10;i++)cout<<i; // for(int i=0,j=0;i<10&&j<10;i++,j++) cout<<i+j; cout<<i; t_ptr(); return 0; t_sort(); return 0; string a; double b = 0.1; a += to_string(b); cout << "a=" << a << endl; return 0; test_snprintf(); return 0; test_tpl_inherit(); return 0; test_bitcount(); return 0; test_refstr(); return 0; test_substr(); return 0; test_map_perf1(); return 0; test_vec_perf1(); return 0; }
true
a27c9f77cae9ebfbc9922a0ed341abd718dfa3a8
C++
rohithrangaraju/MissionRnD-C-BinarySearchTree-Worksheet
/src/HeightofBST.cpp
UTF-8
1,999
3.71875
4
[]
no_license
/* 1)Given a BST ,Find its Maximum Height Height of a NULL BST is 0 Height of a BST which has only one node is 1 Ex Input : 10 /\ 5 80 / / 2 50 \ 4 Height of above Tree is 4 Ex Output : Return the Height of the Tree , -1 if Invalid 2) Get Sum of Left subtree gets the sum of all nodes ,in the left subtree of the given node Ex : get_sum_left for 10 in above Tree ,returns 11 get_sum_left for 80 returns 0 Return -1 for invalid inputs 3) Get Sum of Left subtree gets the sum of all nodes ,in the left subtree of the given node Ex : get_sum_left for 10 in above Tree ,returns 130 get_sum_left for 80 returns 0 Return -1 for invalid inputs */ #include <stdlib.h> #include <stdio.h> //#include<malloc.h> struct node{ struct node * left; int data; struct node *right; }; int height(struct node *root1, int traverseLevel, int* Mainlevel){ if (root1 == NULL){ return 0; } if (traverseLevel > (*Mainlevel)) (*Mainlevel) = traverseLevel; height(root1->left, traverseLevel+1, Mainlevel); height(root1->right, traverseLevel+1, Mainlevel); return *Mainlevel; } int get_height(struct node *root){ if (root == NULL)return -1; int *mainLevel = (int*)calloc(1, sizeof(int)); int n = height(root, 1, mainLevel); free(mainLevel); return n; } int leftSum(struct node *root, int *sum){ if (root == NULL) return 0; (*sum) += root->data; leftSum(root->left, sum); leftSum(root->right, sum); return *sum; } int get_left_subtree_sum(struct node *root){ if (root == NULL)return -1; int *addLeft = (int*)calloc(1, sizeof(int)); int lsum = leftSum(root->left, addLeft); free(addLeft); return lsum; } int rightSum(struct node* root, int* sum) { if (root == NULL) return 0; (*sum) += root->data; rightSum(root->left, sum); rightSum(root->right, sum); return *sum; } int get_right_subtree_sum(struct node *root){ // return 0; if (root == NULL)return -1; int *addRight = (int*)calloc(1, sizeof(int)); int rsum = rightSum(root->right, addRight); free(addRight); return rsum; }
true
319797442937b0fe09cee4bd1bb3f8b8a376a8df
C++
litcoderr/ALOHA_PS
/Lecture/day1/star.cpp
UTF-8
437
3.15625
3
[]
no_license
#include <iostream> using namespace std; void somefunction(){ for(int i=0;i<10;i++){ printf("Hello world"); } } int main(){ int n = 0; scanf("%d",&n); for(int i=0;i<n;i++){ for(int j=0;j<(n-i-1);j++){ //print gong bak printf(" "); } for(int j=0;j<(2*i+1);j++){ //print star printf("*"); } printf("\n");//go to next line } return 0; }
true
ce714546de307820f183ff077ce92b3a172e62f1
C++
Rose-code/C-Portfolio
/SumoCubes.cpp
UTF-8
721
3.6875
4
[]
no_license
/********************************************************************************* Morgan Hughes CS 317 Dr. Brady Rimes 11 March 2019 Sum of Digits Program This program calculates what three numbers can be represented by the sum of the cubes of their digits. ***********************************************************************************/ #include <iostream> #include <iomanip> #include <fstream> #include <cmath> using namespace std; int main() { int n; int sum; int digit; for (int i = 154; i <= 450; i++) { n = i; sum = 0; while (n > 0) { digit = n % 10; sum += pow(digit, 3.0); n /= 10; } if (sum == i) { cout << i << endl; } } return 0; }
true
b600a7835a615d71c40a4c0b97535fdf1b40c073
C++
furkanicer/Programming-Principles-and-Practice-Using-Cpp-
/Part I The Basics/4. Computation/Exercises/10.cpp
UTF-8
3,393
3.921875
4
[ "MIT" ]
permissive
#include <iostream> #include <string> #include <vector> using namespace std; // gonna implement our own randomness system without using rand. // it is not a "real" randomness function btw. it repeats itself. enum class Move { rock = 1, paper = 2, scissors = 3 }; int get_seed() // getting seed for feeding our randomness function. { int seed{}; do { cout << "enter seed value: "; cin >> seed; } while (cin && seed == 0); // safety checks. if (!cin) // safety check again. { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } return seed; } vector<Move> get_computer_moves(int seed, int num_rounds) { if (num_rounds <= 0) // checking for round number, if it is not positive we are not playing. { cerr << "number of round must be positive."; return{}; // https://stackoverflow.com/questions/39487065/what-does-return-statement-mean-in-c11 } vector<Move> moves{}; // object creating. for (int i = 0; i < num_rounds; ++i, ++seed) { // thats where randomness happens. we are feeding it with seed value. moves.push_back(static_cast<Move>(abs(seed) % 3 + 1)); } // abs -> absolute value of an integer. we are making sure seed is positive. // %3 + 1 makes sure it stays in range 1 - 3 return moves; } int main() { int playerMove; int seed = get_seed(); // getting seed value for randomness function. auto computer = get_computer_moves(seed, 5); for (auto i : computer) { cout << "What is your move? 1 = paper, 2 = rock, 3 = scissors." << endl; cin >> playerMove; switch (i) { case Move::paper: cout << "Computer's move is paper." << endl; if (playerMove == 1) { cout << "tie" << endl; } else if (playerMove == 2) { cout << "lose" << endl; } else if (playerMove == 3) { cout << "win" << endl; } else { cout << "something is wrong with your input." << endl; } break; case Move::rock: cout << "Computer's move is rock." << endl; if (playerMove == 1) { cout << "win" << endl; } else if (playerMove == 2) { cout << "tie" << endl; } else if (playerMove == 3) { cout << "loss" << endl; } else { cout << "something is wrong with your input." << endl; } break; case Move::scissors: cout << "Computer's move is scissors." << endl; if (playerMove == 1) { cout << "loss" << endl; } else if (playerMove == 2) { cout << "win" << endl; } else if (playerMove == 3) { cout << "tie" << endl; } else { cout << "something is wrong with your input." << endl; } break; default: break; } } system("pause"); return 0; } /* 10. Write a program that plays the game “Rock, Paper, Scissors.” If you are not familiar with the game do some research (e.g., on the web using Google). Research is a common task for programmers. Use a switch-statement to solve this exercise. Also, the machine should give random answers (i.e., select the next rock, paper, or scissors randomly). Real randomness is too hard to provide just now, so just build a vector with a sequence of values to be used as “the next value.” If you build the vector into the program, it will always play the same game, so maybe you should let the user enter some values. Try variations to make it less easy for the user to guess which move the machine will make next. */
true
1c734c423441c6266d1ba2bb486e9f2bfc9b321e
C++
kensou24/CppStandardV2
/test/source/string/string3.cpp
UTF-8
1,349
2.96875
3
[ "Unlicense" ]
permissive
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference, 2nd Edition" * by Nicolai M. Josuttis, Addison-Wesley, 2012 * * (C) Copyright Nicolai M. Josuttis 2012. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <locale> #include <doctest/doctest.h> using namespace std; TEST_CASE("string3") { string input; // don't skip leading whitespaces cin.unsetf (ios::skipws); istringstream dataStream("12 34567890"); // read all characters while compressing whitespaces const locale& loc(cin.getloc()); // locale unique_copy(istream_iterator<char>(dataStream), // beginning of source istream_iterator<char>(), // end of source back_inserter(input), // destination [=] (char c1, char c2) { // criterion for adj. duplicates return isspace(c1,loc) && isspace(c2,loc); }); // process input // - here: write it to the standard output cout << input; }
true
8f3a0906be5fd8c7d190f349ddbd7d05a1a0d84a
C++
adityachoudharyclg/codingFinalYear
/Graphs/Graphs 1/bfs.cpp
UTF-8
1,131
3.0625
3
[]
no_license
#include <bits/stdc++.h> #include <iostream> using namespace std; void printBFS(int **edges, int V, int sv) { queue<int> pend; bool *visited = new bool[V]; for (int i = 0; i < V; i++) { visited[i] = false; } pend.push(sv); visited[sv] = true; while (!pend.empty()) { int topper = pend.front(); pend.pop(); cout << topper << " "; for (int j = 0; j < V; j++) { if (j == topper) { continue; } if (edges[topper][j] == 1 && !visited[j]) { pend.push(j); visited[j] = true; } } } } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int V, E; cin >> V >> E; int **edge = new int *[V]; for (int i = 0; i < V; i++) { edge[i] = new int[V]; for (int k = 0; k < V; k++) { edge[i][k] = 0; } } for (int p = 0; p < E; p++) { int f, s; cin >> f >> s; edge[f][s] = 1; edge[s][f] = 1; } printBFS(edge, V, 0); return 0; }
true
af79e5333fe713ac040eaf5e3fdba1b0ae3512a0
C++
OC-MCS/lab7-tasks-JLoganDick
/Retail/RetailItem.h
UTF-8
309
2.609375
3
[]
no_license
#pragma once #include<iostream> #include <string> using namespace std; class RetailItem { private: string description; int unitsOnHand; double price; public: RetailItem(string desc, int inv, double cost); string getDescription(); int getUnitsOnHand(); double getPrice(); float getStockValue(); };
true
d196708715d9a3c9606d1ff90de78946a4efee78
C++
misterpink14/byu_course_work
/computer_science/142-intro_to_computer_programming/SmallInheritanceExample/blah/Animal.cpp
UTF-8
167
2.609375
3
[]
no_license
#include "Animal.h" Animal::Animal(string name) { this->name = name; } string Animal::getName() { return this->name; } Animal::~Animal(void) { }
true
bcb58679272bd617986254eb106d0627d8ee6b44
C++
Kevin-MN/CISC-205-CITY-Williams
/PA_11.cpp
UTF-8
10,944
3.828125
4
[]
no_license
/* Kevin Morales Nguyen Chapter 11 Programming assignment 3/22/2021 */ #include <iostream> #include <iomanip> #include <string> #include <limits> using namespace std; const int SIZE = 10; //Customer struct used on place of parrallel arrays struct Customer { std::string name, boat_name; // string variables float contract, paid_to_date; // float variables }; //function prototypes void menu_driver(Customer [], int&); int display_menu(); //four main methods used throughout program, have been changed to handle an array of Customers void create_customer(Customer [], int&); void edit_customer(Customer [], int&); void search_contract(Customer[], int&); void display_contracts(Customer [], int&); //methods that help get valid input std::string get_string(std::string); float get_float(std::string); int main() { //create the single array that holds the Customer data type Customer custs[SIZE]; //create counter to keep track of boat count int number_of_boats = 0; menu_driver(custs, number_of_boats); return 0; } //function definitions // ******************************************************** // name: menu_driver // called by: main // passed: cust_arr[],int &num_boats // returns: nothing // calls: display_menu,create_customer,edit_customer,search_contract,display_contracts // This method serves as th "driver" for selecting and calling * // the various functions used throughout the program to operate * // on the array holding Customers. * // ******************************************************** void menu_driver(Customer cust_arr[], int& num_boats) { int choice = 0; while (choice != 5) { //get user choice choice = display_menu(); //switch appropriatly and call respective function switch (choice) { case 1: if (num_boats < SIZE) { // check size of array create_customer(cust_arr, num_boats); } else { std::cout << "\nContract list is full!\n\n"; } break; case 2: edit_customer(cust_arr, num_boats); break; case 3: search_contract(cust_arr, num_boats); break; case 4: display_contracts(cust_arr, num_boats); break; //exit case 5: break; // bad input, ask user to re-enter valid input default: std::cout << "Please enter valid menu choice.\n\n"; std::cout.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } } // ******************************************************** // name: display_menu // called by: menu_driver // passed: none // returns: int // calls: none // This function helps get a valid menu option. * // ******************************************************** int display_menu() { int choice = 0; bool selecting = true; //promt user for valid menu choice while (selecting) { std::cout << "1. Input a customer's information\n" << "2. Edit a customer's information\n" << "3. Search for contracts by value\n" << "4. Display all contract information\n" << "5. Exit\n\n" << ">> "; std::cin >> choice; std::cout << "\n"; //invalid input, handle by clearing fail bit and flushing buffer if (std::cin.fail()) { std::cout << "Please input a valid integer.\n\n"; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } else { return choice; } } } // ******************************************************** // name: create_customer // called by: menu_driver // passed: cust_arr[],int &num_boats // returns: none // calls: get_string. get_float // This function is used to create a customer by initializing the data inside a customer data type that is // in the array passed to function. * // ******************************************************** void create_customer(Customer cust_arr[], int& numboats) { if (numboats < SIZE) { std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // gather customer information and store in variables std::string name_var = get_string("Name"); std::string boat_name_var = get_string("Boat name"); float contract_var = get_float("Contract"); float paid_date_var = get_float("Paid to date"); // assign data in repective element of customer array cust_arr[numboats].name = name_var; cust_arr[numboats].boat_name = boat_name_var; cust_arr[numboats].contract = contract_var; cust_arr[numboats].paid_to_date = paid_date_var; numboats++; // increment boat count so we keep track } else { // if boat count > 10 then this exectes std::cout << "\nContract list is full!\n\n"; } std::cout << "\n"; } // ******************************************************** // name: edit_customer // called by: menu_driver // passed: cust_arr[],int &num_boats // returns: none // calls: get_string. get_float // This function is used to edit the information customer and contract amounts. * // ******************************************************** void edit_customer(Customer cust_arr[], int& numboats) { std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //search by getting customers name std::string customer = get_string("Customer name"); int index; bool found = false; //search names by accessing data from elements for customer by name for (int i = 0; i < numboats; i++) { if (cust_arr[i].name == customer) { found = true; index = i; // save index as this is where we will make the change } } //if not found exit if (!found) { std::cout << "\nCustomer was now found.\n\n"; return; } //initialize variables outside while and switch, use for editing customer info std::string new_name, new_boat_name; float new_contract, new_paid_date; int choice = 0; bool selecting = true; //select which customer field to edit while (selecting) { std::cout << "\n1. Edit customer name\n" << "2. Edit customer's boat name\n" << "3. Edit contract \n" << "4. Edit Pait-to-date\n" << ">> "; std::cin >> choice; std::cout << "\n"; if (std::cin.fail() || choice < 1 || choice > 4) { std::cout << "Please input a valid integer.\n\n"; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } else { std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //switch to apprporiate choice and make the change in the repsective array and correct index switch (choice) { case 1: new_name = get_string("New name"); cust_arr[index].name = new_name; std::cout << "\n\n"; return; break; case 2: new_boat_name = get_string("New boat name"); cust_arr[index].boat_name = new_boat_name; std::cout << "\n\n"; return; break; case 3: new_contract = get_float("New contract amount"); cust_arr[index].contract = new_contract; std::cout << "\n\n"; return; break; case 4: new_paid_date = get_float("New contract paid-to-date"); cust_arr[index].paid_to_date = new_paid_date; std::cout << "\n\n"; return; break; default: std::cout << "Invalid edit selection.\n\n"; break; } } } } // ******************************************************** // name: search_contract // called by: menu_driver // passed: cust_arr[],int &num_boats // returns: none // calls: get_float // This function is used to print out contracts at or above a specified contract amount. * // ******************************************************** void search_contract(Customer cust_arr[], int& numboats) { float search = get_float("Contract amount"); std::cout << "\n\n" << std::left << std::setw(16) << "Name" << std::left << std::setw(18) << "Boat Name" << std::setw(22) << "Contract Value" << "Paid-to-Date\n\n"; for (int i = 0; i < numboats; i++) { if (cust_arr[i].contract >= search) { std::cout << std::fixed << std::setprecision(2) << std::setw(20) << cust_arr[i].boat_name << std::left << std::setw(20) << cust_arr[i].boat_name << "$" << std::left << std::setw(20) << cust_arr[i].contract << "$" << std::left << std::setw(20) << cust_arr[i].paid_to_date << "\n\n"; } } } // ******************************************************** // name: display_contract // called by: menu_driver // passed: cust_arr[], int &num_boats // returns: none // calls: none // This function is used to print out all of the customer and contract information that has been stored so far, via accessing // data members in elements. * // ******************************************************** void display_contracts(Customer cust_arr[], int& numboats) { float total = 0; std::cout << std::left << std::setw(16) << "Name" << std::left << std::setw(18) << "Boat Name" << std::setw(22) << "Contract Value" << "Paid-to-Date\n\n"; for (int i = 0; i < numboats; i++) { std::cout << std::fixed << std::setprecision(2) << std::setw(17) << cust_arr[i].name << std::left << std::setw(20) << cust_arr[i].boat_name << "$" << std::left << std::setw(20) << cust_arr[i].contract << "$" << std::left << std::setw(20) << cust_arr[i].paid_to_date << "\n\n"; total += cust_arr[i].contract; } std::cout << "Total of all contracts: $" << total << "\n\n"; } // ******************************************************** // name: get_string // called by: menu_driver // passed: string prompt // returns: none // calls: creat_customer, edit_customer // This function is used to gather valid string inputs specified by >= 15 chars and > 0 * // ******************************************************** std::string get_string(std::string prompt) { std::string temp; bool collect = true; while (collect) { std::cout << prompt << ": "; getline(std::cin, temp); if (temp.length() > 15 || temp == "" || temp.length() == 0) { std::cout << "\nPlease enter " << prompt << " no more than 15 charaters and not empty.\n\n"; } else { return temp; } } return ""; } // ******************************************************** // name: get_float // called by: menu_driver // passed: string prompt // returns: none // calls: creat_customer, edit_customer, search_contract // This function is used to gather valid float inputs that are >= 0 * // ******************************************************** float get_float(std::string prompt) { float temp; bool collect = true; while (collect) { std::cout << prompt << ": "; std::cin >> temp; if (!std::cin.fail() && temp >= 0) { return temp; } else { std::cout << "\nPlease enter " << prompt << " that is greater than or equal to zero.\n\n"; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } return 0; }
true
6936c5c29ae8b1a609223548826d13da70b1b1a9
C++
sizzle0121/leetcode
/Top 100 Liked Questions/p287-find the duplicate number.cpp
UTF-8
1,590
3.71875
4
[]
no_license
/* Solve by sorting or set is trivial (see solution 1 & 2) Time complexity: O(nlogn) for sorting, O(n) for set Space complexity: O(1) for sorting, O(n) for set Solve by Floyd's Tortoise and Hare Use two pointers, fast and slow, one moves two steps a time, the other moves one step a time The value of array[i] is the node linked from i, e.g. nums[5]=2 -> node 5 link to node 2 Starting from index 0, the slow and fast will finally meet (since there is a ring in the linked list) Then set another pointer from index 0 to move 1 step a time together with the slow pointer moving from the meeting point When they meet, the node they point to will be our answer (the duplicate number) Time complexity: O(n) Space complexity: O(1) */ #include <iostream> #include <vector> #include <algorithm> #include <set> using namespace std; int Solution1(vector<int> &nums){ sort(nums.begin(), nums.end()); for(int i=1; i<nums.size(); i++) if(nums[i] == nums[i-1]) return nums[i]; return 0; } int Solution2(vector<int> &nums){ set<int> pool; for(int i=0; i<nums.size(); i++){ if(pool.find(nums[i]) != pool.end()) return nums[i]; else pool.insert(nums[i]); } return 0; } int Solution3(vector<int> &nums){ int fast = 0, slow = 0; bool flag = false; while(slow != fast || !flag){ flag = true; slow = nums[slow]; fast = nums[nums[fast]]; } fast = 0; while(slow != fast){ slow = nums[slow]; fast = nums[fast]; } return slow; } int main(){ int T; cin >> T; vector<int> nums(T); for(int i=0; i<T; i++) cin >> nums[i]; cout << Solution3(nums) << endl; }
true
afc9759ba4d87afac7f11050fc27d3e8114b2b55
C++
alextnlr/ProjectTacticalRPG
/main.cpp
UTF-8
5,058
3.21875
3
[]
no_license
#include <iostream> #include <ctime> #include "Character.h" #include "Terrain.h" #include "Display.h" #include "Fight.h" using namespace std; //The main is commented a little too much to avoid annoying comments on the other more importants parts int main(int argc, char** argv) { //Initialisation of the random seed std::srand(std::time(nullptr)); //Creation of all the classes Display display = Display(); Fight fight = Fight(); Terrain map = Terrain(); //We stock the map inside a local variable, even if it's contrary to the principles of OOP it's really easier for now MaptabP mapInt = map.getMapInt(); //Creation of Random Characters vector<Character> characters = fight.createCharacter(&mapInt); //Creation of all the local variables int xmouse; int ymouse; SDL_Event event; bool end = false; //Checking if the game is ending bool freeze = false; //Checking if the user can interact bool waitTurn = false; //Checking if all the animations are completed before going on an other turn int roll = 0; //Current roll, by default 0 to not display anything int victory = -1; //Checking if one team is victorious //Game Loop while(!end) { display.clearRenderer(); //Always cleaning the screen on every frames SDL_GetMouseState(&xmouse,&ymouse); //Stocking the position of the mouse every frames display.setFrame(); //Checking if this frame is a physical frame victory = fight.checkForVictory(characters); //Checking if the game is over if (victory < 0) { //Drawing on screen Terrain, Character and spell range (if active) display.displayTerrain(&mapInt); display.displaySpellRange(characters, &mapInt); display.displayCharacters(characters); //Drawing info card and menu but only if there's no major animation going on if (!freeze) { display.displayInfoCard(characters, xmouse, ymouse); display.displayMenu(characters, &mapInt); } //Checking if there is animation going on waitTurn = display.displayDamages(characters, roll); freeze = display.displayRoll(roll); //Checking if the temp playing has nothing left to do if (!waitTurn) { fight.autoNewTurn(characters); freeze = display.displayTeam(fight.getTeam(), roll); } } else { //Displaying the end card display.displayEndMenu(victory); } fight.decreaseWait(); //Checking for inputs SDL_PollEvent(&event); switch(event.type) { case SDL_QUIT: //Window cross end = 1; break; case SDL_KEYDOWN: if (!freeze) { switch (event.key.keysym.sym) { case SDLK_ESCAPE: //Cancel or quit if (!fight.cancel(characters)) { end = true; } break; case SDLK_z: case SDLK_UP: fight.move(characters, 0, &mapInt); break; case SDLK_s: case SDLK_DOWN: fight.move(characters, 1, &mapInt); break; case SDLK_d: case SDLK_RIGHT: fight.move(characters, 2, &mapInt); break; case SDLK_q: case SDLK_LEFT: fight.move(characters, 3, &mapInt); break; case SDLK_SPACE: if (!roll) //if to avoid cancelling the roll animation { roll = fight.shiftAction(characters, &mapInt); } break; case SDLK_RETURN: //Manually switch turn fight.switchTeams(characters); break; } } case SDL_MOUSEBUTTONDOWN: { if (!freeze) { switch (event.button.button) { case SDL_BUTTON_LEFT: fight.select(characters, xmouse, ymouse); //Select with the mouse (may change) break; case SDL_BUTTON_RIGHT: fight.cancel(characters); break; } } } } display.displayRenderer(); //Update the window } display.desallouer(); //Yeeting the SDL thingies return 0; }
true
2ef77c38f69d0dfda840ece93066af62426fa92d
C++
PavelGubanov/Laba1_list
/ConventerFunctor.cpp
WINDOWS-1251
221
2.546875
3
[]
no_license
#include "ConventerFunctor.h" ConventerFunctor::ConventerFunctor(int sum) { _sum = sum; } // void ConventerFunctor::operator()(int& x) { x -= _sum; }
true
7acf111ed7767ce1991bf06ac7f99e2ed393bb4e
C++
gkagm2/cpppractise
/cpptraining/ch1/ProgrammingForGameDeveloper/CToCPP_VirtualFunc.cpp
UTF-8
2,826
2.59375
3
[]
no_license
#include <windows.h> #include <iostream> using namespace std; LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam); ////////////////////////// CObject class CObject { protected: static WCHAR szAppName[]; HWND hwnd; MSG msg; WNDCLASSEX wndclass; public: void InitInstance(HINSTANCE hInstance, PSTR szCmdLine, int iCmdShow); void Run(); WPARAM ExitInstance(); virtual void OnCreate() = 0; virtual void OnDraw() = 0; virtual void OnDestroy() = 0; virtual void OnLButtonDown() = 0; }; void CObject::InitInstance(HINSTANCE hInstance, PSTR szCmdLine, int iCmdShow) { wndclass.cbSize = sizeof(wndclass); wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szAppName; wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); RegisterClassEx(&wndclass); hwnd = CreateWindow(szAppName, // window class name L"The Hello Program", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, iCmdShow); UpdateWindow(hwnd); } void CObject::Run() { while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } WPARAM CObject::ExitInstance() { return msg.wParam; } WCHAR CObject::szAppName[] = L"HelloWin"; CObject* pCObject; ////////////////////////// CView class CView : public CObject { public: void OnCreate(); void OnDraw(); void OnDestroy(); void OnLButtonDown(); }; // Event Handler void CView::OnCreate() { } void CView::OnDraw() { HDC hdc; PAINTSTRUCT ps; RECT rect; hdc = BeginPaint(hwnd, &ps); GetClientRect(hwnd, &rect); DrawText(hdc, L"Hello, Windows 95!", -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER); EndPaint(hwnd, &ps); } void CView::OnDestroy() { PostQuitMessage(0); } void CView::OnLButtonDown() { MessageBox(NULL, L"MESSAGE", L"TITLE", MB_ICONEXCLAMATION | MB_OK); } // Global object CView app; LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { switch (iMsg) { case WM_CREATE: pCObject->OnCreate(); return 0; case WM_PAINT: pCObject->OnDraw(); return 0; case WM_DESTROY: pCObject->OnDestroy(); return 0; case WM_LBUTTONDOWN: pCObject->OnLButtonDown(); return 0; } return DefWindowProc(hwnd, iMsg, wParam, lParam); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { pCObject = &app; pCObject->InitInstance(hInstance, szCmdLine, iCmdShow); pCObject->Run(); return pCObject->ExitInstance(); }
true
539449adfb979692c38cc62f2347605465ad42eb
C++
revsolid/polyminis-game-server
/src/Game/SpaceExploration/PlanetManager.cpp
UTF-8
1,391
3.125
3
[]
no_license
#include "PlanetManager.h" Planet PlanetManager::USELESS = Planet(0, 0, -1); PlanetManager::PlanetManager(const std::initializer_list<std::pair<float, float>>& list) : mNextPlanetId(0) { for (auto i : list) { unsigned int id = GetNextPlanetId(); mPlanets.push_back(Planet(i.first, i.second, id)); } } Planet& PlanetManager::GetPlanet(unsigned int inId) { for (auto& p : mPlanets) { if (p.GetID() == inId) { return p; } } return PlanetManager::USELESS; } Planet& PlanetManager::GetPlanet(Coord point) { float threshold = 0.1f; for (auto& p : mPlanets) { if (Coord::Distance(p.GetPos(), point) < threshold) { return p; } } return PlanetManager::USELESS; } void PlanetManager::AddPlanet(Planet inPlanet) { mNextPlanetId = inPlanet.GetID() + 1; mPlanets.push_back(inPlanet); } void PlanetManager::AddPlanet(float x, float y, unsigned int id) { AddPlanet(Planet(x, y, id)); } picojson::array PlanetManager::GetVisiblePlanets(Coord inCoord, float distance) { picojson::array retVal; for (auto p : mPlanets) { if (p.IsVisible(inCoord, distance)) { retVal.push_back(picojson::value(p.ToJson())); } } return retVal; } int PlanetManager::GetNextPlanetId() { return mNextPlanetId++; }
true
71eed83b10c18607bcb6aaeb4a12d42525e0d0ee
C++
MarcoAurelioIrias/Trabajos
/Trabajo 5.cpp
UTF-8
304
3.09375
3
[]
no_license
#include <iostream> using namespace std; int numero; /* Ingresar un numero y determinar su rango 1-50,51-100 y mayor a 100 */ int main() cout << "Ingresar un Numero"; cin >> numero; if ((numero >=1) and (numero<=50)) {cout<<"Numero esta entre 1-50"; } else if (("Numero esta entre 51-100"; {cout< }
true
a9d3b63636a523259bbbb18a3aa4b04efac63247
C++
QuocAnhLe935/GameEngine
/GameEngine/Engine/FX/LightSource.h
UTF-8
582
2.875
3
[]
no_license
#ifndef LIGHTSOURCE_H #define LIGHTSOURCE_H #include <glm/glm.hpp> class LightSource { public: LightSource(); ~LightSource(); float getAmbient() const; float getDiffuse() const; float getSpecular() const; glm::vec3 getPosition() const; glm::vec3 getLightColor() const; void setAmbient(float Ambient_); void setDiffuse(float Diffuse_); void setSpecular(float Specular_); void setPosition(glm::vec3 position_); void setLightColor(glm::vec3 lightcolor_); private: glm::vec3 position; float ambient; float diffuse; float specular; glm::vec3 lightColor; }; #endif
true
d0d9b4c0e142fff6b467e3da09ed05fcf2e350c8
C++
JustWhit3/matrixop
/include/matrixop.h
UTF-8
924
2.671875
3
[ "MIT" ]
permissive
#ifndef MATRIXOP_H #define MATRIXOP_H #include <iostream> //MaxPtr template function declaration: template <class A> A MaxPtr (A *ptr, int a); //Matrixop class declaration: class matrixop { public: matrixop () {}; matrixop (int); ~matrixop (); void inverse (); void reset (); void trace (); void determinant (); void linear_system (); void transpose (); void print_I (double **ptr); void print_data (double data); void print_sol (double *vet); void rank (); void matrix_norm (); double zero (); const matrixop& operator += (const matrixop &A); const matrixop& operator -= (const matrixop &A); const matrixop& operator *= (const matrixop &A); double t, d, rg, norm_1, norm_2, norm_3, zero_; double **k, **w, **I, **S, *mtr, *v, *V; int a; }; //Operator << redefinition declaration: std::ostream& operator << (std::ostream& os, matrixop &A); #endif
true