hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
1539fab1fc1668eed8ad73910cf93a87afee1161
2,238
cpp
C++
tests/ModLoaderTests.cpp
Zemurin/commonItems
cda7c217c7b3433b61a17cd05ce8d3893b711bf7
[ "MIT" ]
7
2018-12-22T03:59:34.000Z
2021-06-10T22:42:37.000Z
tests/ModLoaderTests.cpp
IhateTrains/commonItems
759705dc41ff1595db9786d0a9facc0b336888c3
[ "MIT" ]
45
2018-12-04T04:51:20.000Z
2021-08-12T12:20:56.000Z
tests/ModLoaderTests.cpp
IhateTrains/commonItems
759705dc41ff1595db9786d0a9facc0b336888c3
[ "MIT" ]
15
2019-01-09T05:59:48.000Z
2020-08-27T09:08:09.000Z
#include "../ModLoader/ModLoader.h" #include "../OSCompatibilityLayer.h" #include "gtest/gtest.h" #include <gmock/gmock-matchers.h> using testing::UnorderedElementsAre; TEST(ModLoaderTests, ModsCanBeLocatedUnpackedAndUpdated) { Mods incomingMods; // this is what comes from the save incomingMods.emplace_back(Mod("Some mod", "mod/themod.mod")); // mod's in fact named "The Mod" in the file. commonItems::ModLoader modLoader; modLoader.loadMods("TestFiles", incomingMods); const auto mods = modLoader.getMods(); ASSERT_THAT(mods, UnorderedElementsAre(Mod("The Mod", "TestFiles/mod/themod/"))); EXPECT_THAT(mods[0].dependencies, UnorderedElementsAre("Packed Mod", "Missing Mod")); } TEST(ModLoaderTests, BrokenMissingAndNonexistentModsAreDiscarded) { Mods incomingMods; incomingMods.emplace_back(Mod("", "mod/themod.mod")); // no name given incomingMods.emplace_back(Mod("Broken mod", "mod/brokenmod.mod")); // no path incomingMods.emplace_back(Mod("Missing mod", "mod/missingmod.mod")); // missing directory incomingMods.emplace_back(Mod("Nonexistent mod", "mod/nonexistentmod.mod")); // doesn't exist. commonItems::ModLoader modLoader; modLoader.loadMods("TestFiles", incomingMods); const auto mods = modLoader.getMods(); EXPECT_THAT(mods, UnorderedElementsAre(Mod("The Mod", "TestFiles/mod/themod/"))); } TEST(ModLoaderTests, CompressedModsCanBeUnpacked) { Mods incomingMods; incomingMods.emplace_back(Mod("some packed mod", "mod/packedmod.mod")); commonItems::ModLoader modLoader; modLoader.loadMods("TestFiles", incomingMods); const auto mods = modLoader.getMods(); EXPECT_THAT(mods, UnorderedElementsAre(Mod("Packed Mod", "mods/packedmod/"))); EXPECT_TRUE(commonItems::DoesFolderExist("mods/packedmod/")); } TEST(ModLoaderTests, BrokenCompressedModsAreNotSkippedEvenThoughTheyShouldBe) { Mods incomingMods; incomingMods.emplace_back(Mod("broken packed mod", "mod/brokenpacked.mod")); commonItems::ModLoader modLoader; modLoader.loadMods("TestFiles", incomingMods); const auto mods = modLoader.getMods(); EXPECT_THAT(mods, UnorderedElementsAre(Mod("Broken Packed Mod", "mods/brokenpacked/"))); EXPECT_TRUE(commonItems::DoesFolderExist("mods/brokenpacked/")); }
37.3
108
0.758266
Zemurin
153a61e9019d7b15d28d88d3922dd9ac261ebd05
6,529
hpp
C++
includes/coff/string.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
140
2020-01-16T19:04:33.000Z
2022-03-10T02:54:01.000Z
includes/coff/string.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
4
2021-02-28T12:02:46.000Z
2022-02-14T01:41:57.000Z
includes/coff/string.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
38
2020-01-16T01:48:08.000Z
2022-03-12T16:52:20.000Z
// Copyright (c) 2020 Can Boluk // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 #include <string_view> #include <stdlib.h> #include <cstring> #include "../img_common.hpp" #pragma pack(push, COFF_STRUCT_PACKING) namespace coff { // String table. // union string_table_t { uint32_t size; char raw_data[ VAR_LEN ]; // Resolves a string given the offset. // const char* begin() const { return size > 4 ? &raw_data[ 0 ] : nullptr; } const char* end() const { return size > 4 ? &raw_data[ size ] : nullptr; } std::string_view resolve( size_t offset ) const { // Fail if invalid offset. // if ( offset < 4 ) return {}; // Search for the null terminator, return if found. // const char* start = begin() + offset; const char* lim = end(); for ( const char* it = start; it < lim; it++ ) if ( !*it ) return { start, ( size_t ) ( it - start ) }; // Invalid string. // return {}; } }; // External reference to string table. // struct string_t { union { char short_name[ LEN_SHORT_STR ]; // Name as inlined string. struct { uint32_t is_short; // If non-zero, name is inline'd into short_name, else has a long name. uint32_t long_name_offset; // Offset into string table. }; }; // Convert to string view given an optional string table. // std::string_view to_string( const string_table_t* tbl = nullptr ) const { if ( tbl && !is_short ) return tbl->resolve( long_name_offset ); size_t len = 0; while ( len != LEN_SHORT_STR && short_name[ len ] ) len++; return { short_name, len }; } // Array lookup, only available for short strings. // char& operator[]( size_t n ) { return const_cast<char&>( to_string()[ n ] ); } const char& operator[]( size_t n ) const { return to_string()[ n ]; } // Basic comparison primitive. // bool equals( const char* str, const string_table_t* tbl = nullptr ) const { return to_string( tbl ) == str; } // Short string comparison primitive. // template<size_t N> requires( N <= ( LEN_SHORT_STR + 1 ) ) bool equals_s( const char( &str )[ N ] ) const { // Compare with against empty string. // if constexpr ( N == 1 ) return ( !is_short && !long_name_offset ) || ( is_short && !short_name[ 0 ] ); // Can skip is short check since if string is not null, is short will be overwritten. // if constexpr ( N == ( LEN_SHORT_STR + 1 ) ) return !memcmp( short_name, str, LEN_SHORT_STR ); else return !memcmp( short_name, str, N ); } }; // Same as above but archive convention, used for section names. // struct scn_string_t { char short_name[ LEN_SHORT_STR ]; // Convert to string view given an optional string table. // std::string_view to_string( const string_table_t* tbl = nullptr ) const { if ( tbl && short_name[ 0 ] == '/' ) { char* end = ( char* ) std::end( short_name ); return tbl->resolve( strtoll( short_name + 1, &end, 10 ) ); } size_t len = 0; while ( len != LEN_SHORT_STR && short_name[ len ] ) len++; return { short_name, len }; } // Array lookup, only available for short strings. // char& operator[]( size_t n ) { return const_cast<char&>( to_string()[ n ] ); } const char& operator[]( size_t n ) const { return to_string()[ n ]; } // Basic comparison primitive. // bool equals( const char* str, const string_table_t* tbl = nullptr ) const { return to_string( tbl ) == str; } // Short string comparison primitive. // template<size_t N> requires( N <= ( LEN_SHORT_STR + 1 ) ) bool equals_s( const char( &str )[ N ] ) const { // Compare with against empty string. // if constexpr ( N == 1 ) return !short_name[ 0 ]; // Can skip is short check since if string is not null, is short will be overwritten. // if constexpr ( N == ( LEN_SHORT_STR + 1 ) ) return !memcmp( short_name, str, LEN_SHORT_STR ); else return !memcmp( short_name, str, N ); } }; }; #pragma pack(pop)
38.405882
134
0.559657
archercreat
153e7c40f2bc9bfd7b3574a1fb809f1b9ef5da28
3,750
hpp
C++
third_party/boost/simd/arch/x86/avx2/simd/function/shift_left.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/arch/x86/avx2/simd/function/shift_left.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/arch/x86/avx2/simd/function/shift_left.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /** Copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) **/ //================================================================================================== #ifndef BOOST_SIMD_ARCH_X86_AVX2_SIMD_FUNCTION_SHIFT_LEFT_HPP_INCLUDED #define BOOST_SIMD_ARCH_X86_AVX2_SIMD_FUNCTION_SHIFT_LEFT_HPP_INCLUDED #include <boost/simd/detail/overload.hpp> namespace boost { namespace simd { namespace ext { namespace bd = boost::dispatch; namespace bs = boost::simd; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0, typename A1) , bs::avx2_ , bs::pack_<bd::ints16_<A0>, bs::avx_> , bd::scalar_<bd::integer_<A1>> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A1 a1) const BOOST_NOEXCEPT { return _mm256_slli_epi16(a0, int(a1)); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0) , bs::avx2_ , bs::pack_<bd::ints32_<A0>, bs::avx_> , bs::pack_<bd::ints32_<A0>, bs::avx_> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT { return _mm256_sllv_epi32(a0, a1); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0, typename A1) , bs::avx2_ , bs::pack_<bd::ints32_<A0>, bs::avx_> , bd::scalar_<bd::integer_<A1>> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A1 a1) const BOOST_NOEXCEPT { return _mm256_slli_epi32(a0, int(a1)); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0) , bs::avx2_ , bs::pack_<bd::ints32_<A0>, bs::sse_> , bs::pack_<bd::ints32_<A0>, bs::sse_> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT { return _mm_sllv_epi32(a0, a1); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0) , bs::avx2_ , bs::pack_<bd::ints64_<A0>, bs::avx_> , bs::pack_<bd::ints64_<A0>, bs::avx_> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT { return _mm256_sllv_epi64(a0, a1); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0, typename A1) , bs::avx2_ , bs::pack_<bd::ints64_<A0>, bs::avx_> , bd::scalar_<bd::integer_<A1>> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A1 a1) const BOOST_NOEXCEPT { return _mm256_slli_epi64(a0, int(a1)); } }; BOOST_DISPATCH_OVERLOAD( shift_left_ , (typename A0) , bs::avx2_ , bs::pack_<bd::ints64_<A0>, bs::sse_> , bs::pack_<bd::ints64_<A0>, bs::sse_> ) { BOOST_FORCEINLINE A0 operator()(A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT { return _mm_sllv_epi64(a0, a1); } }; } } } #endif
33.482143
100
0.461333
SylvainCorlay
153f99ecd798218b9cb5ddf6ca547d6d87587629
2,400
cpp
C++
LiveCam/Core/Tracking/CaffeFaceDetector.cpp
KanSmith/LiveCam
8b863f55f08cb3ea5090e417c68ad82ded690743
[ "MIT" ]
null
null
null
LiveCam/Core/Tracking/CaffeFaceDetector.cpp
KanSmith/LiveCam
8b863f55f08cb3ea5090e417c68ad82ded690743
[ "MIT" ]
null
null
null
LiveCam/Core/Tracking/CaffeFaceDetector.cpp
KanSmith/LiveCam
8b863f55f08cb3ea5090e417c68ad82ded690743
[ "MIT" ]
null
null
null
#include "CaffeFaceDetector.h" #include <Common/CommonClasses.h> CaffeFaceDetector::CaffeFaceDetector() { capacity = MAX_TARGETS_COUNT; inputSize = cv::Size(300, 300); inputMean = cv::Scalar(104.0, 177.0, 123.0); inputName = "data"; outputName = "detection_out"; const cv::String trackerConfiguration = "Assets/model/caffe/deploy.prototxt"; const cv::String trackerBinary = "Assets/model/caffe/res10_300x300_ssd_iter_140000_fp16.caffemodel"; trackingNet = cv::dnn::readNetFromCaffe(trackerConfiguration, trackerBinary); //trackingNet.setPreferableBackend(cv::dnn::DNN_BACKEND_HALIDE); //trackingNet.setPreferableTarget(cv::dnn::DNN_TARGET_OPENCL); } CaffeFaceDetector::~CaffeFaceDetector() { } void CaffeFaceDetector::start() {} void CaffeFaceDetector::stop() {} void CaffeFaceDetector::setRefFrame(cv::Mat frame) {} cv::Mat CaffeFaceDetector::preProcess(cv::Mat frame) { if (frame.channels() == 4) { cv::Mat gray(frame.rows, frame.cols, CV_8UC3); cvtColor(frame, gray, cv::COLOR_BGRA2BGR); return gray; } return frame; } std::vector<cv::Rect> CaffeFaceDetector::scan(cv::Mat frame) { cv::Mat resizeFrame; std::vector<cv::Rect> results; if (!trackingNet.empty()) { cv::resize(frame, resizeFrame, inputSize); cv::Mat inputBlob = cv::dnn::blobFromImage(frame, activescale, inputSize, inputMean, inputSwapRB, inputCrop); trackingNet.setInput(inputBlob, inputName); cv::Mat detection = trackingNet.forward(outputName); cv::Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>()); for (int i = 0; i < detectionMat.rows; i++) { float confidence = detectionMat.at<float>(i, 2); if (confidence > CONFIDENCE_THRESHOLD) { int xLeftBottom = static_cast<int>(detectionMat.at<float>(i, 3) * frame.cols); int yLeftBottom = static_cast<int>(detectionMat.at<float>(i, 4) * frame.rows); int xRightTop = static_cast<int>(detectionMat.at<float>(i, 5) * frame.cols); int yRightTop = static_cast<int>(detectionMat.at<float>(i, 6) * frame.rows); cv::Rect object((int)xLeftBottom, (int)yLeftBottom, (int)(xRightTop - xLeftBottom), (int)(yRightTop - yLeftBottom)); results.push_back(object); } } } return results; } void CaffeFaceDetector::getPoints(std::array<cv::Point2f, TARGET_DETAIL_MODIFIER> &points) { } void CaffeFaceDetector::scale(double newscale) { activescale = newscale; }
27.272727
111
0.722917
KanSmith
1543882b2a28c40a8b2f7f37d65e700e15b4e2ee
2,979
hpp
C++
libs/visitor/Visitable.hpp
cesiumsolutions/dynamic_generic_visitor
da8fe928bf77270e1a64beae0051bfadba7ea256
[ "MIT" ]
null
null
null
libs/visitor/Visitable.hpp
cesiumsolutions/dynamic_generic_visitor
da8fe928bf77270e1a64beae0051bfadba7ea256
[ "MIT" ]
null
null
null
libs/visitor/Visitable.hpp
cesiumsolutions/dynamic_generic_visitor
da8fe928bf77270e1a64beae0051bfadba7ea256
[ "MIT" ]
null
null
null
#ifndef Visitable_hpp #define Visitable_hpp #include <functional> #include <typeinfo> // ---------------------------------------------------------------------------- // VisitableBase // ---------------------------------------------------------------------------- template<typename VisitorType, typename SignatureType> class VisitableBase; template<typename VisitorType, typename ReturnType, typename... ParameterTypes> class VisitableBase<VisitorType, ReturnType( ParameterTypes... )> { public: virtual ~VisitableBase() = default; virtual std::type_info const & typeInfo() const = 0; virtual ReturnType accept( VisitorType & visitor, ParameterTypes... parameters ) const = 0; }; // class VisitableBase<VisitorType, ReturnType (ParameterTypes...)> // ---------------------------------------------------------------------------- // Visitable // ---------------------------------------------------------------------------- template<typename VisiteeType, typename VisitorType, typename SignatureType = typename VisitorType::SignatureType> class Visitable; template<typename VisiteeType, typename VisitorType, typename ReturnType, typename... ParameterTypes> class Visitable<VisiteeType, VisitorType, ReturnType( ParameterTypes... )> : public VisitableBase<VisitorType, ReturnType( ParameterTypes... )> { public: Visitable( VisiteeType const & visitee ); std::type_info const & typeInfo() const override; ReturnType accept( VisitorType & visitor, ParameterTypes... parameters ) const override; private: VisiteeType mVisitee; }; // class Visitable<VisiteeType, VisitorType, ReturnType( ParameterTypes... )> template<typename VisitorType, typename SignatureType = typename VisitorType::SignatureType> using VisitableUPtr = std::unique_ptr<VisitableBase<VisitorType, SignatureType>>; template<typename VisitorType, typename SignatureType, typename VisiteeType> VisitableUPtr<VisitorType, SignatureType> makeUniqueVisitable( VisiteeType const & visitee ); template<typename VisitorType, typename VisiteeType> VisitableUPtr<VisitorType, typename VisitorType::SignatureType> makeUniqueVisitable( VisiteeType const & visitee ); template<typename VisitorType, typename SignatureType = typename VisitorType::SignatureType> using VisitableSPtr = std::shared_ptr<VisitableBase<VisitorType, SignatureType>>; template<typename VisitorType, typename SignatureType, typename VisiteeType> VisitableSPtr<VisitorType, SignatureType> makeSharedVisitable( VisiteeType const & visitee ); template<typename VisitorType, typename VisiteeType> VisitableSPtr<VisitorType, typename VisitorType::SignatureType> makeSharedVisitable( VisiteeType const & visitee ); #include <visitor/Visitable.tpp> #endif // Visitable_hpp
35.464286
83
0.65089
cesiumsolutions
1543a351fa8dec3493095c95e01a4b6449ff059e
1,117
cc
C++
lib/base/database/SPar.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
null
null
null
lib/base/database/SPar.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
3
2020-05-06T18:22:40.000Z
2020-05-26T14:00:23.000Z
lib/base/database/SPar.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
4
2021-02-11T10:44:29.000Z
2021-06-17T10:50:23.000Z
// @(#)lib/base:$Id$ // Author: Rafal Lalik 18/11/2017 /************************************************************************* * Copyright (C) 2017-2018, Rafał Lalik. * * All rights reserved. * * * * For the licensing terms see $SiFiSYS/LICENSE. * * For the list of contributors see $SiFiSYS/README/CREDITS. * *************************************************************************/ #include "SPar.h" /** * \class SPar \ingroup lib_base SPar is an abstract class to hold container and geometry parameters. It must be derivated and pure virtual members defined. The parameters are parsed from text file in SDatabase and stored in the SParContainer. The getParam() method reads content of the SParContainer and fills variables inside the SPar object. The putParam method allows to update parameters in the container and write to param file. \sa SFibersCalibratorPar \sa SFibersDigitizerPar \sa SFibersGeomPar */
36.032258
76
0.52641
SiFi-CC
154892726a064aa98f1dd9781fcd606859ade052
573
cpp
C++
task3_zad3.cpp
slaveya-nusheva/assignments8g
f082378f6d81f0ee6432c1f9e2d042daf7b6eb3d
[ "Apache-2.0" ]
null
null
null
task3_zad3.cpp
slaveya-nusheva/assignments8g
f082378f6d81f0ee6432c1f9e2d042daf7b6eb3d
[ "Apache-2.0" ]
null
null
null
task3_zad3.cpp
slaveya-nusheva/assignments8g
f082378f6d81f0ee6432c1f9e2d042daf7b6eb3d
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; void printLine (int star, int space)//function not returning any result is void { for (int i = 0; i < space; i++) { cout<<" "<<" "; } for (int i = 0; i < star; i++) { cout<<"*"<<" "; } cout<<endl; } int main() { int lines = 0; do { cout<<"Enter the number of lines (5-15): "; cin>>lines; } while (lines < 5 || lines > 15); for (int i = lines; i > 0; i--) { printLine(i, lines - i);//the smaller i the bigger lines-i } return 0; }
18.483871
79
0.481675
slaveya-nusheva
1549cbcd24f93a67ce4a96896a56c07c39ce7a62
318
cpp
C++
389.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
389.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
389.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
class Solution { public: char findTheDifference(string s, string t) { int res = 0; for (char c : s) { int ch = c - 'a'; res ^= ch; } for (char c : t) { int ch = c - 'a'; res ^= ch; } return (char)(res + 'a'); } };
19.875
48
0.367925
Alex-Amber
154de9e98f0aa68c49a924d63034fe984444059e
960
cxx
C++
src/DmwApplication.cxx
DmitrySemikin/das-mesh-workbench
35a4d3b8b6d51a2ea6dc7ebfd019ea89e4ae3fb6
[ "Apache-2.0" ]
null
null
null
src/DmwApplication.cxx
DmitrySemikin/das-mesh-workbench
35a4d3b8b6d51a2ea6dc7ebfd019ea89e4ae3fb6
[ "Apache-2.0" ]
null
null
null
src/DmwApplication.cxx
DmitrySemikin/das-mesh-workbench
35a4d3b8b6d51a2ea6dc7ebfd019ea89e4ae3fb6
[ "Apache-2.0" ]
null
null
null
#include <memory> #include <QApplication> #include <QSurfaceFormat> #include <QVTKOpenGLStereoWidget.h> #include "DmwKernel.hxx" #include "DmwApplication.hxx" using std::make_unique; DmwApplication::DmwApplication(int argc, char ** argv) : qApplication(nullptr) { // TODO: Move everything from constructor to `exec()` method. Constructor should stay empty. // Taken from VTK example "vtk/Examples/Gui/Qt/SimpleView" // needed to ensure appropriate OpenGL context is created for VTK rendering. // ! This call must be done before construction of QApplication (see docs of QSurfaceFormat::setDefaultFormat()) QSurfaceFormat::setDefaultFormat(QVTKOpenGLStereoWidget::defaultFormat()); qApplication = make_unique<QApplication>(argc, argv); } DmwApplication::~DmwApplication() noexcept { // Nothing to do yet } int DmwApplication::exec() { DmwKernel kernel; kernel.showMainWindow(); return qApplication->exec(); }
25.263158
116
0.739583
DmitrySemikin
1554fd5d21463a2a7b8ec2921d65099c3e46beaa
2,953
cc
C++
libLogging/test/LoggerTest.cc
marcbejerano/cpp-tools
9ef62064a5b826b8722ff96e423ffff2d85f49f1
[ "BSD-3-Clause" ]
null
null
null
libLogging/test/LoggerTest.cc
marcbejerano/cpp-tools
9ef62064a5b826b8722ff96e423ffff2d85f49f1
[ "BSD-3-Clause" ]
null
null
null
libLogging/test/LoggerTest.cc
marcbejerano/cpp-tools
9ef62064a5b826b8722ff96e423ffff2d85f49f1
[ "BSD-3-Clause" ]
null
null
null
#include "LoggerTest.h" #include <Logger> #include <sstream> using namespace hslib; class StringBufferAppender : public Appender { private: std::stringstream buffer; public: StringBufferAppender() : Appender(), buffer() { } StringBufferAppender(const StringBufferAppender& copy) : Appender(copy), buffer() { } virtual const size_t log(const LoggingEvent& event) { PatternLayout p(getLayout()); const std::string formatted = p.format(event); buffer << formatted; return formatted.length(); } const std::string str() { return buffer.str(); } }; void LoggerTest::testCtorArgs() { Logger logger("testCtorArgs"); } void LoggerTest::testCtorCopy() { Logger logger("testCtorCopy"); Logger copy(logger); CPPUNIT_ASSERT("testCtorCopy" == copy.getName()); } void LoggerTest::testAssignment() { Logger logger("testAssignment"); Logger copy = logger; CPPUNIT_ASSERT("testAssignment" == logger.getName()); } void LoggerTest::testGetName() { Logger logger("testGetName"); CPPUNIT_ASSERT("testGetName" == logger.getName()); } void LoggerTest::testGetMinimumLevel() { Logger logger("testGetMinimumLevel"); CPPUNIT_ASSERT(Level::INFO == logger.getMinimumLevel()); } void LoggerTest::testSetMinimumLevel() { Logger logger("testGetMinimumLevel"); CPPUNIT_ASSERT(Level::INFO == logger.getMinimumLevel()); logger.setMinimumLevel(Level::FATAL); CPPUNIT_ASSERT(Level::FATAL == logger.getMinimumLevel()); } void LoggerTest::testAddAppender() { StringBufferAppender ap; Logger logger("testAddAppender"); std::list<Appender*> a = logger.getAppenders(); CPPUNIT_ASSERT(a.size() == 0); logger.addAppender(&ap); a = logger.getAppenders(); CPPUNIT_ASSERT(a.size() == 1); } void LoggerTest::testGetAppenders() { StringBufferAppender ap; Logger logger("testGetAppenders"); std::list<Appender*> a = logger.getAppenders(); CPPUNIT_ASSERT(a.size() == 0); logger.addAppender(&ap); a = logger.getAppenders(); CPPUNIT_ASSERT(a.size() == 1); } void LoggerTest::testLog() { StringBufferAppender ap; Logger logger("testLog"); logger.addAppender(&ap); LoggingEvent event = LOGGING_EVENT(Level::INFO, "test"); logger.log(event); CPPUNIT_ASSERT("test\n" == ap.str()); } void LoggerTest::testOpLevel() { Logger logger("testOpLevel"); CPPUNIT_ASSERT(Level::INFO == logger.getMinimumLevel()); logger << Level::FATAL; CPPUNIT_ASSERT(Level::FATAL == logger.getMinimumLevel()); } void LoggerTest::testOpLoggingEvent() { StringBufferAppender ap; Logger logger("testLog"); logger.addAppender(&ap); LoggingEvent event = LOGGING_EVENT(Level::INFO, "test"); logger << Level::TRACE << event; CPPUNIT_ASSERT(ap.str().empty()); logger << Level::OFF << event; CPPUNIT_ASSERT("test\n" == ap.str()); }
25.678261
93
0.66678
marcbejerano
155fa02032a320e9d3cb6fd3537c6d2d5d9a129f
11,141
cc
C++
algorithms/map-optimization-legacy/src/ba-optimization-options.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
1,936
2017-11-27T23:11:37.000Z
2022-03-30T14:24:14.000Z
algorithms/map-optimization-legacy/src/ba-optimization-options.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
353
2017-11-29T18:40:39.000Z
2022-03-30T15:53:46.000Z
algorithms/map-optimization-legacy/src/ba-optimization-options.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
661
2017-11-28T07:20:08.000Z
2022-03-28T08:06:29.000Z
#include "map-optimization-legacy/ba-optimization-options.h" #include <glog/logging.h> #include <maplab-common/conversions.h> #include <maplab-common/gravity-provider.h> DEFINE_bool( lba_fix_ncamera_intrinsics, true, "Whether or not to fix the intrinsics of the ncamera(s)."); DEFINE_bool( lba_fix_ncamera_extrinsics_rotation, true, "Whether or not to fix the rotation extrinsics of the ncamera(s)."); DEFINE_bool( lba_fix_ncamera_extrinsics_translation, true, "Whether or not to fix the translation extrinsics of the ncamera(s)."); DEFINE_bool( lba_fix_landmark_positions, false, "Whether or not to fix the positions of the landmarks."); DEFINE_bool( lba_fix_vertex_poses, false, "Whether or not to fix the positions of the vertices."); DEFINE_bool( lba_fix_accel_bias, false, "Whether or not to fix the bias of the IMU accelerometer."); DEFINE_bool( lba_fix_gyro_bias, false, "Whether or not to fix the bias of the IMU gyroscope."); DEFINE_bool( lba_fix_velocity, false, "Whether or not to fix the velocity of the vertices."); DEFINE_bool( lba_add_pose_prior_for_fixed_vertices, false, "Whether or not to add a pose prior error-term for all fixed vertices."); DEFINE_bool( lba_remove_behind_camera_landmarks, true, "Whether or not to remove landmarks located behind the camera."); DEFINE_bool( lba_fix_landmark_positions_of_fixed_vertices, false, "Whether or " "not to fix the positions of landmarks based at fixed vertices."); DEFINE_bool( lba_include_wheel_odometry, false, "Whether or not to include wheel-odometry error-terms."); DEFINE_bool( lba_include_gps, false, "Whether or not to include GPS error-terms."); DEFINE_bool( lba_position_only_gps, false, "Whether or not to add GPS error-terms as constraints on the position only " "(3DoF)or as constrains on both position and orientation (6DoF)"); DEFINE_bool( lba_include_visual, true, "Whether or not to include visual error-terms."); DEFINE_bool( lba_include_inertial, true, "Whether or not to include IMU error-terms."); DEFINE_bool( lba_fix_wheel_odometry_extrinsics, true, "Whether or not to fix the extrinsics of the wheel-odometry."); DEFINE_bool( lba_visual_outlier_rejection, false, "If visual outlier rejection " "should be done in the bundle adjustment."); DEFINE_bool( lba_run_custom_post_iteration_callback_on_vi_map, true, "Whether or not to run a user-defined callback on the VIMap after " "every optimization iteration."); DEFINE_bool(lba_show_residual_statistics, false, "Show residual statistics."); DEFINE_bool( lba_apply_loss_function_for_residual_stats, false, "Apply loss function on residuals for the statistics."); DEFINE_int32( lba_min_num_visible_landmarks_at_vertex, 5, "Minimum number of " "landmarks visible at a vertex for it to be added to the problem."); DEFINE_int32( lba_update_visualization_every_n_iterations, 10, "Update the visualization every n optimization iterations."); DEFINE_int32( lba_num_visual_outlier_rejection_loops, 2, "Number of bundle_adjustment visual outlier rejection loops."); DEFINE_int32( lba_min_number_of_landmark_observer_missions, 0, "Minimum number of " "missions a landmark must be observed from to have its respective " "visual error-terms included."); DEFINE_int32( lba_num_iterations, 50, "Maximum number of optimization iterations to perform."); DEFINE_string( lba_fix_vertex_poses_except_of_mission, "", "Fixes all vertex " "poses except the vertex poses of the mission with the specified " "id."); DEFINE_double( lba_prior_position_std_dev_meters, 0.0316227766, "Std. dev. in meters used for position priors. Default: sqrt(0.001)"); DEFINE_double( lba_prior_orientation_std_dev_radians, 0.00174533, "Std. dev. in radians (default" " corresponds to 0.1deg.) used for orientation priors."); DEFINE_double( lba_prior_velocity_std_dev_meters_seconds, 0.1, "Std. dev. in meters per second used " "for priors on velocities."); DEFINE_double( lba_gravity_magnitude_meters_seconds_square, -1.0, "Gravity magnitude in meters per " "square seconds. If < 0.0, the GravityProvider is used to set " "the gravity magnitude."); DEFINE_bool( lba_add_pose_prior_on_camera_extrinsics, false, "Adding a prior on the pose of the camera extrinsics."); DEFINE_double( lba_camera_extrinsics_position_prior_std_dev_meters, 1.0, "Std. dev. of the position prior on the camera extrinsics pose [meters]."); DEFINE_double( lba_camera_extrinsics_orientation_prior_std_dev_degrees, 1.0, "Std. dev. of the orientation prior on the camera extrinsics pose " "[meters]."); DEFINE_bool( lba_add_pose_prior_on_wheel_odometry_extrinsics, false, "Adding a prior on the pose of the wheel odometry extrinsics."); DEFINE_double( lba_wheel_odometry_extrinsics_position_prior_std_dev_meters, 1.0, "Std. dev. of the position prior on the wheel odometry extrinsics pose " "[meters]."); DEFINE_double( lba_wheel_odometry_extrinsics_orientation_prior_std_dev_degrees, 1.0, "Std. dev. of the orientation prior on the wheel odometry extrinsics pose " "[meters]."); DEFINE_bool( lba_fix_wheel_odometry_extrinsics_position, false, "Fix the position of the wheel odometry extrinsics."); DEFINE_bool( lba_include_only_merged_landmarks, false, "If true, only landmarks with at least two " "global landmark IDs are included in the optimization."); DEFINE_bool( lba_fix_root_vertex, true, "Fix the root vertex of one of the " "missions for optimization."); DEFINE_bool(lba_fix_baseframes, false, "Fix the baseframe transformations."); DEFINE_bool( lba_include_loop_closure_edges, false, "Whether or not to include the loop-closure transformation error " "terms."); DEFINE_bool( lba_use_switchable_constraints_for_loop_closure_edges, true, "If true, the optimizer may dynamically downweight loop-closure " "error-terms that are considered outliers by adjusting the switch " "variable of the error-term."); DEFINE_double( lba_loop_closure_error_term_cauchy_loss, 10.0, "Cauchy loss parameter for the loop-closure error-terms. Note that the " "Cauchy loss is only used if the parameter is > 0 and the switch " "variable is not used."); namespace map_optimization_legacy { BaOptimizationOptions::BaOptimizationOptions() : fix_not_selected_missions(false), fix_ncamera_intrinsics(FLAGS_lba_fix_ncamera_intrinsics), fix_ncamera_extrinsics_rotation( FLAGS_lba_fix_ncamera_extrinsics_rotation), fix_ncamera_extrinsics_translation( FLAGS_lba_fix_ncamera_extrinsics_translation), fix_landmark_positions(FLAGS_lba_fix_landmark_positions), fix_vertex_poses(FLAGS_lba_fix_vertex_poses), fix_accel_bias(FLAGS_lba_fix_accel_bias), fix_gyro_bias(FLAGS_lba_fix_gyro_bias), fix_velocity(FLAGS_lba_fix_velocity), add_pose_prior_for_fixed_vertices( FLAGS_lba_add_pose_prior_for_fixed_vertices), remove_behind_camera_landmarks(FLAGS_lba_remove_behind_camera_landmarks), fix_landmark_positions_of_fixed_vertices( FLAGS_lba_fix_landmark_positions_of_fixed_vertices), include_wheel_odometry(FLAGS_lba_include_wheel_odometry), include_gps(FLAGS_lba_include_gps), position_only_gps(FLAGS_lba_position_only_gps), include_visual(FLAGS_lba_include_visual), include_inertial(FLAGS_lba_include_inertial), include_only_merged_landmarks(FLAGS_lba_include_only_merged_landmarks), fix_wheel_odometry_extrinsics(FLAGS_lba_fix_wheel_odometry_extrinsics), fix_root_vertex(FLAGS_lba_fix_root_vertex), fix_baseframes(FLAGS_lba_fix_baseframes), visual_outlier_rejection(FLAGS_lba_visual_outlier_rejection), run_custom_post_iteration_callback_on_vi_map( FLAGS_lba_run_custom_post_iteration_callback_on_vi_map), min_number_of_visible_landmarks_at_vertex( static_cast<size_t>(FLAGS_lba_min_num_visible_landmarks_at_vertex)), num_visual_outlier_rejection_loops( static_cast<size_t>(FLAGS_lba_num_visual_outlier_rejection_loops)), min_number_of_landmark_observer_missions( static_cast<size_t>( FLAGS_lba_min_number_of_landmark_observer_missions)), num_iterations(static_cast<size_t>(FLAGS_lba_num_iterations)), fix_vertex_poses_except_of_mission( FLAGS_lba_fix_vertex_poses_except_of_mission), prior_position_std_dev_meters(FLAGS_lba_prior_position_std_dev_meters), prior_orientation_std_dev_radians( FLAGS_lba_prior_orientation_std_dev_radians), prior_velocity_std_dev_meter_seconds( FLAGS_lba_prior_velocity_std_dev_meters_seconds), gravity_magnitude(FLAGS_lba_gravity_magnitude_meters_seconds_square), add_pose_prior_on_camera_extrinsics( FLAGS_lba_add_pose_prior_on_camera_extrinsics), camera_extrinsics_position_prior_std_dev_meters( FLAGS_lba_camera_extrinsics_position_prior_std_dev_meters), camera_extrinsics_orientation_prior_std_dev_radians( kDegToRad * FLAGS_lba_camera_extrinsics_orientation_prior_std_dev_degrees), add_pose_prior_on_wheel_odometry_extrinsics( FLAGS_lba_add_pose_prior_on_wheel_odometry_extrinsics), wheel_odometry_extrinsics_position_prior_std_dev_meters( FLAGS_lba_wheel_odometry_extrinsics_position_prior_std_dev_meters), wheel_odometry_extrinsics_orientation_prior_std_dev_radians( kDegToRad * FLAGS_lba_wheel_odometry_extrinsics_orientation_prior_std_dev_degrees), fix_wheel_odometry_extrinsics_position( FLAGS_lba_fix_wheel_odometry_extrinsics_position), include_loop_closure_edges(FLAGS_lba_include_loop_closure_edges), use_switchable_constraints_for_loop_closure_edges( FLAGS_lba_use_switchable_constraints_for_loop_closure_edges), loop_closure_error_term_cauchy_loss( FLAGS_lba_loop_closure_error_term_cauchy_loss) { CHECK_GE(FLAGS_lba_min_num_visible_landmarks_at_vertex, 0); CHECK_GE(FLAGS_lba_update_visualization_every_n_iterations, 0); CHECK_GE(FLAGS_lba_num_visual_outlier_rejection_loops, 0); CHECK_GE(FLAGS_lba_min_number_of_landmark_observer_missions, 0); CHECK_GE(FLAGS_lba_num_iterations, 0); if (gravity_magnitude < 0.0) { common::GravityProvider gravity_provider( common::locations::kAltitudeZurichMeters, common::locations::kLatitudeZurichDegrees); gravity_magnitude = gravity_provider.getGravityMagnitude(); } } BaIterationOptions::BaIterationOptions() : update_visualization_every_n_iterations( static_cast<size_t>( FLAGS_lba_update_visualization_every_n_iterations)), show_residual_statistics(FLAGS_lba_show_residual_statistics), apply_loss_function_for_residual_stats( FLAGS_lba_apply_loss_function_for_residual_stats) {} } // namespace map_optimization_legacy
45.105263
81
0.776322
AdronTech
1560bcd78ff0db310f8831074b2a41881b309ed0
991
hpp
C++
CaWE/GuiEditor/Commands/Create.hpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
CaWE/GuiEditor/Commands/Create.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
CaWE/GuiEditor/Commands/Create.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #ifndef CAFU_GUIEDITOR_COMMAND_CREATE_HPP_INCLUDED #define CAFU_GUIEDITOR_COMMAND_CREATE_HPP_INCLUDED #include "../../CommandPattern.hpp" #include "Templates/Pointer.hpp" namespace cf { namespace GuiSys { class WindowT; } } namespace GuiEditor { class GuiDocumentT; class CommandCreateT : public CommandT { public: CommandCreateT(GuiDocumentT* GuiDocument, IntrusivePtrT<cf::GuiSys::WindowT> Parent); // CommandT implementation. bool Do(); void Undo(); wxString GetName() const; private: GuiDocumentT* m_GuiDocument; IntrusivePtrT<cf::GuiSys::WindowT> m_Parent; IntrusivePtrT<cf::GuiSys::WindowT> m_NewWindow; const ArrayT< IntrusivePtrT<cf::GuiSys::WindowT> > m_OldSelection; }; } #endif
22.522727
93
0.67003
dns
15656440d6137938d28333ca28fd96f233563a26
650
cpp
C++
src/base/ev_base.cpp
chensoft/libxio
17345e500cca5085641b5392ce8ef7dc65369d69
[ "MIT" ]
6
2018-07-28T08:03:24.000Z
2022-03-31T08:56:57.000Z
src/base/ev_base.cpp
chensoft/libxio
17345e500cca5085641b5392ce8ef7dc65369d69
[ "MIT" ]
null
null
null
src/base/ev_base.cpp
chensoft/libxio
17345e500cca5085641b5392ce8ef7dc65369d69
[ "MIT" ]
2
2019-05-21T02:26:36.000Z
2020-04-13T16:46:20.000Z
/** * Created by Jian Chen * @since 2017.02.03 * @author Jian Chen <[email protected]> * @link http://chensoft.com */ #include "socket/base/ev_base.hpp" // ----------------------------------------------------------------------------- // ev_base const int chen::ev_base::Readable = 1 << 0; const int chen::ev_base::Writable = 1 << 1; const int chen::ev_base::Closed = 1 << 2; void chen::ev_base::onAttach(reactor *loop, int mode, int flag) { this->_ev_loop = loop; this->_ev_mode = mode; this->_ev_flag = flag; } void chen::ev_base::onDetach() { this->_ev_loop = nullptr; this->_ev_mode = 0; this->_ev_flag = 0; }
24.074074
80
0.556923
chensoft
15661111768fbcc964ff4b3df494d70d7904a1d5
340
cpp
C++
789.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
8
2018-10-31T11:00:19.000Z
2020-07-31T05:25:06.000Z
789.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
null
null
null
789.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
2
2018-05-31T11:29:22.000Z
2019-09-11T06:34:40.000Z
class Solution { public: bool escapeGhosts(vector<vector<int>>& ghosts, vector<int>& target) { int dist = abs(target[0]) + abs(target[1]); for(int i = 0; i < ghosts.size(); i++){ if (dist >= abs(ghosts[i][0] - target[0]) + abs(ghosts[i][1] - target[1])) return false; } return true; } };
30.909091
100
0.532353
zfang399
15663e00dc713f393337aa82e12adf2e2ad249e2
8,070
cpp
C++
dataAQ.cpp
LearnerDroid/cs32lab06
36a2cb19b51cc7796a4e9acbd6ac5fd41139e230
[ "MIT" ]
null
null
null
dataAQ.cpp
LearnerDroid/cs32lab06
36a2cb19b51cc7796a4e9acbd6ac5fd41139e230
[ "MIT" ]
null
null
null
dataAQ.cpp
LearnerDroid/cs32lab06
36a2cb19b51cc7796a4e9acbd6ac5fd41139e230
[ "MIT" ]
null
null
null
#include "dataAQ.h" #include "demogData.h" #include "comboDemogData.h" #include "comboHospitalData.h" #include "countyDemogData.h" #include "comboHospitalData.h" #include "hospitalData.h" #include "cityHospitalData.h" #include "parse.h" #include <iostream> #include <algorithm> #include <fstream> #include <sstream> #define DEBUG false using namespace std; /* Questions: What's the deal with region? Why do we need it? Is there a special input for region/county in parse? What is up with countyDemogData and cityHospitalData? How are we supposed to store our data in the maps? By region or state? How do we store the data in comboHospData? */ //function to aggregate the data - this CAN and SHOULD vary per student - depends on how they map void dataAQ::createStateDemogData(vector< shared_ptr<demogData> > theData) { string state = ""; for (shared_ptr<demogData> county : theData) { state = county->getState(); //if true, key is not found if (allStateDemogData.count(state) == 0) { allStateDemogData.insert(make_pair(state, make_shared<comboDemogData>(state, state))); //state and region names are the same } allStateDemogData.at(state)->addDemogtoRegion(county); } } void dataAQ::createStateHospData(std::vector<shared_ptr<hospitalData> > theData) { string state = ""; for (shared_ptr<hospitalData> hosp : theData) { state = hosp->getState(); //if true, key is not found if (allStateHospData.count(state) == 0) { allStateHospData.insert(make_pair(state, make_shared<comboHospitalData>("state", state))); //state and region names are the same } allStateHospData.at(state)->addHospitaltoRegion(hosp); } } void dataAQ::createCountyHospData(std::vector<shared_ptr<hospitalData>>& theHospitalData) { string cityKey = ""; string county = ""; string state = ""; for (shared_ptr<hospitalData> hosp : theHospitalData) { state = hosp->getState(); cityKey = hosp->getCity() + state; county = cityToCounty[cityKey]; county += " County"; //added cause the tester tests for the exytra "County" //if true, key is not found if (allCountyHData.count(county) == 0) { allCountyHData.insert(make_pair(county, make_shared<comboHospitalData>(county, state))); } allCountyHData.at(county)->addHospitaltoRegion(hosp); } } void dataAQ::sortHospRatingHighLow(vector<comboHospitalData*>& hospHighToLow, string regionType) { //adding elements from the hashmap to the vector for (map<string, shared_ptr<comboHospitalData>>::iterator i = allStateHospData.begin(); i != allStateHospData.end(); i++) { hospHighToLow.push_back(&(*i->second)); } sort(hospHighToLow.begin(), hospHighToLow.end(), &hospitalData::compareOV); //reverse reverse(hospHighToLow.begin(), hospHighToLow.end()); } void dataAQ::sortHospRatingLowHigh(vector<comboHospitalData*>& hospLowToHigh, string regionType) { for (map<string, shared_ptr<comboHospitalData>>::iterator i = allStateHospData.begin(); i != allStateHospData.end(); i++) { hospLowToHigh.push_back(&(*i->second)); } sort(hospLowToHigh.begin(), hospLowToHigh.end(), &hospitalData::compareOV); } void dataAQ::sortDemogPovLevelLowHigh(vector<demogData*>& povLevelLowHigh) { for (map<string, shared_ptr<comboDemogData>>::iterator i = allStateDemogData.begin(); i != allStateDemogData.end(); i++) { povLevelLowHigh.push_back(&(*i->second)); } sort(povLevelLowHigh.begin(), povLevelLowHigh.end(), &demogData::compareP); reverse(povLevelLowHigh.begin(), povLevelLowHigh.end()); } void dataAQ::sortDemogPovLevelHighLow(vector<demogData*>& povLevelHighLow) { for (map<string, shared_ptr<comboDemogData>>::iterator i = allStateDemogData.begin(); i != allStateDemogData.end(); i++) { povLevelHighLow.push_back(&(*i->second)); } sort(povLevelHighLow.begin(), povLevelHighLow.end(), &demogData::compareP); } //sorting counties void dataAQ::sortHospRatingHighLowForState(vector<comboHospitalData*>& hospHighToLow, string state) { for (map<string, shared_ptr<comboHospitalData>>::iterator i = allCountyHData.begin(); i != allCountyHData.end(); i++) { if(i->second->getState().compare(state) == 0) hospHighToLow.push_back(&(*i->second)); } sort(hospHighToLow.begin(), hospHighToLow.end(), &hospitalData::compareOV); reverse(hospHighToLow.begin(), hospHighToLow.end()); } //prints every state with a poverty level above the threshold void dataAQ::stateReport(double thresh) { visitorReport VR; int total = 0; for (map<string, shared_ptr<comboDemogData>>::iterator i = allStateDemogData.begin(); i != allStateDemogData.end(); i++) { cout << endl; if (i->second->getBelowPoverty() / i->second->getTotalPop() > thresh / 100) { cout << "Special report demog Data : \n"; allStateDemogData[i->first]->accept(VR); cout << "Special report hospital data : \n"; allStateHospData[i->first]->accept(VR); total++; } } cout << "Generated a report for a total of : " << total << "\n"; //Expected: \nSpecial report demog Data : \nDemographics Info(State) : MS\nEducation info : \n(% Bachelor degree or more) : 20.43\n(% high school or more) : 81.62\n % below poverty : 22.63\nSpecial report hospital data : \nHospital Info : MS\nOverall rating(out of 5) : 2.57\nGenerated a report for a total of : 1\n //aActual : \nSpecial report demog Data : \nDemographics Info(State) : MS\nEducation info : \n(% bachelor degree or more) : 20.43\n(% high school or more) : 81.62\n % below poverty : 22.63\nSpecial report hospital data : \nHospital Info : MS\nOverall rating(out of 5) : 2.57\nGenerated a report for a total of : 1' //Expected: \nSpecial report demog Data : \nDemographics Info(State) : MS\nEducation info : \n(% Bachelor degree or more) : 20.43\n(% high school or more) : 81.62\n % below poverty : 22.63\nSpecial report hospital data : \nHospital Info : MS\nOverall rating(out of 5) : 2.57\nSpecial report demog Data : \nDemographics Info(State) : NM\nEducation info : \n(% Bachelor degree or more) : 25.58\n(% high school or more) : 83.39\n % below poverty : 20.40\nSpecial report hospital data : \nHospital Info : NM\nOverall rating(out of 5) : 2.73\nGenerated a report for a total of : 2\n //Actusal : \nSpecial report demog Data : \nDemographics Info(State) : MS\nEducation info : \n(% bachelor degree or more) : 20.43\n(% high school or more) : 81.62\n % below poverty : 22.63\nSpecial report hospital data : \nHospital Info : MS\nOverall rating(out of 5) : 2.57\nSpecial report demog Data : \nDemographics Info(State) : NM\nEducation info : \n(% bachelor degree or more) : 25.58\n(% high school or more) : 83.39\n % below poverty : 20.40\nSpecial report hospital data : \nHospital Info : NM\nOverall rating(out of 5) : 2.73\nGenerated a report for a total of : 2 } ostream& operator<<(ostream &out, const dataAQ &AQ) { out << "bruh"; return out; } void dataAQ::read_csvCityCounty(string filename) { // Create an input filestream ifstream myFile(filename); // Make sure the file is open if (!myFile.is_open()) { throw std::runtime_error("Could not open file"); } if (myFile.good()) { consumeColumnNames(myFile); // Helper vars string line, state, junk; // Now read data, line by line and enter into the map while (getline(myFile, line)) { stringstream ss(line); string city = getFieldNQ(ss); state = getFieldNQ(ss); junk = getFieldNQ(ss); string county = getFieldNQ(ss); string cityKey = city + state; cityToCounty[cityKey] = county; //cout << "line: " << line << endl; //cout << "pair (city, county): " << city << ", " << county << " state " << junk << endl; } // Close file myFile.close(); } }
48.035714
577
0.669145
LearnerDroid
d080fb1b4f64a31c0d6a70bea15bfeba622e8b51
1,057
cpp
C++
sources/Emulator.cpp
NiwakaDev/NIWAKA_X86
ae07dcd5e006c6b48459c18efd4a65e4492ce7b4
[ "MIT" ]
2
2022-02-19T04:57:16.000Z
2022-02-19T05:45:39.000Z
sources/Emulator.cpp
NiwakaDev/NIWAKA_X86
ae07dcd5e006c6b48459c18efd4a65e4492ce7b4
[ "MIT" ]
1
2022-02-19T04:59:05.000Z
2022-02-19T11:02:17.000Z
sources/Emulator.cpp
NiwakaDev/NIWAKA_X86
ae07dcd5e006c6b48459c18efd4a65e4492ce7b4
[ "MIT" ]
null
null
null
#include "Memory.h" #include "Cpu.h" #include "IoManager.h" #include "Bios.h" #include "IntHandler.h" #include "Device.h" #include "Pic.h" #include "Emulator.h" Emulator::Emulator(Memory* memory, Bios* bios, Cpu* cpu, IoManager* io_manager){ this->mem = memory; this->bios = bios; this->cpu = cpu; this->io_manager = io_manager; this->int_handler = new IntHandler(cpu, (Pic*)this->io_manager->device_list[PIC]); this->emu_thread = new thread(&Emulator::Run, this); //this->Run(); } void Emulator::ShowSelf(){ cout << "Emulator Info" << endl; this->bios->ShowSelf(); this->mem->PrintMem(0x7c00, 512); this->mem->ShowSelf(); } void Emulator::Run(){ this->bios->LoadIpl(this->mem); int irq_num; while(1){ if(this->cpu->IsIF()){ if((irq_num=this->io_manager->device_list[PIC]->IsIrq())!=-1){ this->int_handler->Handle(irq_num); } } this->cpu->ExecuteSelf(); } this->ShowSelf(); fprintf(stdout, "stopped at Emulator::Run\n"); }
26.425
86
0.601703
NiwakaDev
d081f38d1e67e302c5b176c3b84bb67b317e771e
3,049
cc
C++
src/nodal_properties.cc
andrewsolis/mpm
c6ea73d3bac177a440f0aa0a5e66829c294a00e5
[ "MIT" ]
154
2017-11-29T06:41:18.000Z
2022-03-09T23:19:05.000Z
src/nodal_properties.cc
andrewsolis/mpm
c6ea73d3bac177a440f0aa0a5e66829c294a00e5
[ "MIT" ]
707
2017-08-30T16:12:59.000Z
2022-02-25T20:33:02.000Z
src/nodal_properties.cc
andrewsolis/mpm
c6ea73d3bac177a440f0aa0a5e66829c294a00e5
[ "MIT" ]
83
2017-11-22T15:22:07.000Z
2022-03-19T17:02:51.000Z
#include "nodal_properties.h" // Function to create new property with given name and size (rows x cols) bool mpm::NodalProperties::create_property(const std::string& property, unsigned rows, unsigned columns) { // Create a matrix with size of rows times columns and insert it to the // property database map Eigen::MatrixXd property_data = Eigen::MatrixXd::Zero(rows, columns); std::pair<std::map<std::string, Eigen::MatrixXd>::iterator, bool> status = properties_.insert( std::pair<std::string, Eigen::MatrixXd>(property, property_data)); return status.second; } // Return data in the nodal properties map at a specific index Eigen::MatrixXd mpm::NodalProperties::property(const std::string& property, unsigned node_id, unsigned mat_id, unsigned nprops) const { // Const pointer to location of property: node_id * nprops x mat_id const double* position = &properties_.at(property)(node_id * nprops, mat_id); mpm::MapProperty property_handle(position, nprops); return property_handle; } // Assign property value to a pair of node and material void mpm::NodalProperties::assign_property( const std::string& property, unsigned node_id, unsigned mat_id, const Eigen::MatrixXd& property_value, unsigned nprops) { // Assign a property value matrix to its proper location in the properties_ // matrix that stores all nodal properties properties_.at(property).block(node_id * nprops, mat_id, property_value.rows(), property_value.cols()) = property_value; } // Update property value according to a pair of node and material void mpm::NodalProperties::update_property( const std::string& property, unsigned node_id, unsigned mat_id, const Eigen::MatrixXd& property_value, unsigned nprops) { // Update a property value matrix with dimensions nprops x 1 considering its // proper location in the properties_ matrix that stores all nodal properties properties_.at(property).block(node_id * nprops, mat_id, nprops, 1) = property_value + this->property(property, node_id, mat_id, nprops); } // Initialise all the nodal values for all properties in the property pool void mpm::NodalProperties::initialise_nodal_properties() { // Iterate over all properties in the property map for (auto prop_itr = properties_.begin(); prop_itr != properties_.end(); ++prop_itr) { // Create Matrix with zero values that has same size of the current property // in the iteration. The referred size is equal to rows * cols, where: // rows = number of nodes * size of property (1 if property is scalar, Tdim // if property is vector) // cols = number of materials Eigen::MatrixXd zeroed_property = Eigen::MatrixXd::Zero(prop_itr->second.rows(), prop_itr->second.cols()); this->assign_property(prop_itr->first, 0, 0, zeroed_property); } }
49.177419
80
0.686783
andrewsolis
d084bc1c05e1bc0f984e99276c75a9657d0fee3a
11,365
cpp
C++
paint_board.cpp
sakky016/PaintBoardWithUndo
339cf6204e36252a6974181f14ce099f6f3fbb88
[ "Apache-2.0" ]
null
null
null
paint_board.cpp
sakky016/PaintBoardWithUndo
339cf6204e36252a6974181f14ce099f6f3fbb88
[ "Apache-2.0" ]
null
null
null
paint_board.cpp
sakky016/PaintBoardWithUndo
339cf6204e36252a6974181f14ce099f6f3fbb88
[ "Apache-2.0" ]
null
null
null
#include<conio.h> #include"paint_board.h" #include<iostream> //---------------------------------------------------------------------------------------------- // @name : PaintBoard // // @description : Constructor // // @returns : Nothing //---------------------------------------------------------------------------------------------- PaintBoard::PaintBoard(int width, int height) { m_width = width; m_height = height; m_cursorX = 0; m_cursorY = 0; m_nextCommand = CMD_NONE; MakeSnapshot(); } //---------------------------------------------------------------------------------------------- // @name : ~PaintBoard // // @description : Destructor // // @returns : Nothing //---------------------------------------------------------------------------------------------- PaintBoard::~PaintBoard() { } //---------------------------------------------------------------------------------------------- // @name : DisplayInstructions // // @description : Display instructions on screen // // @returns : Nothing //---------------------------------------------------------------------------------------------- void PaintBoard::DisplayInstructions() { printf("arrow keys : To move UP, DOWN, LEFT, RIGHT\n"); printf("<space> : Toggles paint on current co-ordinate\n"); printf("u : Undo\n"); printf("x : Terminate\n"); } //---------------------------------------------------------------------------------------------- // @name : DrawBoard // // @description : Creates the drawing board in the form of a matrix. The // symbol to be displayed at each coordinate depends upon // cursor location, blank space and painted area. // // @returns : Nothing //---------------------------------------------------------------------------------------------- void PaintBoard::DrawBoard() { // Clear the screen system("cls"); // Print the board for (int i = 0; i < m_height; i++) { for (int j = 0; j < m_width; j++) { int index = j * m_height + i; if (i == m_cursorY && j == m_cursorX && m_paintedArea[index] == true) { cout << PAINTED_CURSOR; } else if (i == m_cursorY && j == m_cursorX) { cout << CURSOR; } else if (m_paintedArea[index] == true) { cout << PAINTED; } else { cout << BLANK; } } // End of a row cout << endl; } // Display other info printf("\nx,y (%d, %d)\n", m_cursorX, m_cursorY); printf("Undo marks: %ld\n", m_paintedAreaSnapshots.size()); DisplayInstructions(); } //---------------------------------------------------------------------------------------------- // @name : MoveLeft // // @description : Move cursor to left // // @returns : Nothing //---------------------------------------------------------------------------------------------- bool PaintBoard::MoveLeft() { if (m_cursorX > 0) { m_cursorX--; return true; } return false; } //---------------------------------------------------------------------------------------------- // @name : MoveRight // // @description : Move cursor to right // // @returns : Nothing //---------------------------------------------------------------------------------------------- bool PaintBoard::MoveRight() { if (m_cursorX < m_width - 1) { m_cursorX++; return true; } return false; } //---------------------------------------------------------------------------------------------- // @name : MoveUp // // @description : Move cursor up // // @returns : Nothing //---------------------------------------------------------------------------------------------- bool PaintBoard::MoveUp() { if (m_cursorY > 0) { m_cursorY--; return true; } return false; } //---------------------------------------------------------------------------------------------- // @name : MoveDown // // @description : Move cursor down // // @returns : Nothing //---------------------------------------------------------------------------------------------- bool PaintBoard::MoveDown() { if (m_cursorY < m_height - 1) { m_cursorY++; return true; } return false; } //---------------------------------------------------------------------------------------------- // @name : FetchInput // // @description : Waits for fetching user input. Translates the given input // to a command and stores it. 2 types of inputs are processed // here. ch1 is the 1st character that user enters. This is // the input that he is feeding. But in case of arrow keys, // a sequence of 2 characters are received ch1 and ch2. ch1 // identifies that some arrow key was pressed, ch2 determines the // specific arrow key pressed. // // @returns : Nothing //---------------------------------------------------------------------------------------------- void PaintBoard::FetchInput() { unsigned char ch1 = _getch(); if (ch1 == KEY_ARROW_CHAR1) { // Some Arrow key was pressed, determine which? unsigned char ch2 = _getch(); switch (ch2) { case KEY_ARROW_UP: // code for arrow up m_nextCommand = CMD_MOVE_UP; cout << "KEY_ARROW_UP" << endl; break; case KEY_ARROW_DOWN: // code for arrow down m_nextCommand = CMD_MOVE_DOWN; cout << "KEY_ARROW_DOWN" << endl; break; case KEY_ARROW_LEFT: // code for arrow right m_nextCommand = CMD_MOVE_LEFT; cout << "KEY_ARROW_LEFT" << endl; break; case KEY_ARROW_RIGHT: // code for arrow left m_nextCommand = CMD_MOVE_RIGHT; cout << "KEY_ARROW_RIGHT" << endl; break; } } else { switch (ch1) { case KEY_SPACE: // Paint m_nextCommand = CMD_PAINT; cout << "KEY_SPACE" << endl; break; case KEY_STOP: // Stop m_nextCommand = CMD_STOP; cout << "KEY_STOP" << endl; break; case KEY_UNDO: // Undo m_nextCommand = CMD_UNDO; cout << "KEY_UNDO" << endl; break; } } } //---------------------------------------------------------------------------------------------- // @name : Process // // @description : Depending on the command present in m_nextCommand variable, // function is executed // // @returns : True, if processing is complete, i.e, user pressed terminate // button. // False, if application continues. //---------------------------------------------------------------------------------------------- bool PaintBoard::Process() { if (m_nextCommand != CMD_NONE) { switch (m_nextCommand) { case CMD_MOVE_UP: MoveUp(); break; case CMD_MOVE_DOWN: MoveDown(); break; case CMD_MOVE_LEFT: MoveLeft(); break; case CMD_MOVE_RIGHT: MoveRight(); break; case CMD_PAINT: PaintAtXY(m_cursorX, m_cursorY); break; case CMD_UNDO: Restore(); break; case CMD_STOP: // Processing done. Indicate the calling function return true; } m_nextCommand = CMD_NONE; } return false; } //---------------------------------------------------------------------------------------------- // @name : PaintAtXY // // @description : Stores the location of the painted (PAINTED) character. // Additionally, it creates a snapshot of the current painted // area of this board. This will later be used for undo operation. // // @returns : Nothing //---------------------------------------------------------------------------------------------- void PaintBoard::PaintAtXY(int x, int y) { int index = x * m_height + y; if (m_paintedArea[index] == true) { m_paintedArea[index] = false; } else { m_paintedArea[index] = true; } MakeSnapshot(); } //---------------------------------------------------------------------------------------------- // @name : MakeSnapshot // // @description : Creates a snapshot of the painted area and stores it in // a list. This list cannot grow beyond MAX_UNDO marks. // // @returns : Nothing //---------------------------------------------------------------------------------------------- void PaintBoard::MakeSnapshot() { if (m_paintedAreaSnapshots.size() >= MAX_UNDO) { m_paintedAreaSnapshots.pop_front(); } m_paintedAreaSnapshots.push_back(m_paintedArea); } //---------------------------------------------------------------------------------------------- // @name : Restore // // @description : Restores the painted area information as per the previous // undo mark. // // @returns : Nothing //---------------------------------------------------------------------------------------------- void PaintBoard::Restore() { // This reverts the current painted area, because after a paint operation // current painted area and the latest snapshot in the m_paintedAreaSnapshots // are basically same. if (m_paintedAreaSnapshots.size()) { m_paintedArea = m_paintedAreaSnapshots.back(); m_paintedAreaSnapshots.pop_back(); } // This reverts to the previous painted area. if (m_paintedAreaSnapshots.size()) { m_paintedArea = m_paintedAreaSnapshots.back(); m_paintedAreaSnapshots.pop_back(); } // Once we revert, we need to create a snapshot of this // operation as well. MakeSnapshot(); }
32.195467
101
0.368676
sakky016
d0874a1724f343d76a204d0d95f37594499c8190
6,208
hpp
C++
lib/inc/thinsqlitepp/impl/statement_impl.hpp
gershnik/thinsqlitepp
c132c83c7733c1cb6173b09039ccf48d62507e49
[ "BSD-3-Clause" ]
null
null
null
lib/inc/thinsqlitepp/impl/statement_impl.hpp
gershnik/thinsqlitepp
c132c83c7733c1cb6173b09039ccf48d62507e49
[ "BSD-3-Clause" ]
null
null
null
lib/inc/thinsqlitepp/impl/statement_impl.hpp
gershnik/thinsqlitepp
c132c83c7733c1cb6173b09039ccf48d62507e49
[ "BSD-3-Clause" ]
null
null
null
/* Copyright 2019 Eugene Gershnik Use of this source code is governed by a BSD-style license that can be found in the LICENSE file or at https://github.com/gershnik/thinsqlitepp/blob/main/LICENSE */ #ifndef HEADER_SQLITEPP_STATEMENT_IMPL_INCLUDED #define HEADER_SQLITEPP_STATEMENT_IMPL_INCLUDED #include "database_iface.hpp" #include "value_iface.hpp" namespace thinsqlitepp { inline std::unique_ptr<statement> statement::create(const class database & db, const string_param & sql #if SQLITE_VERSION_NUMBER >= 3020000 , unsigned int flags #endif ) { const char * tail = nullptr; sqlite3_stmt * ret = nullptr; #if SQLITE_VERSION_NUMBER >= 3020000 int res = sqlite3_prepare_v3(db.c_ptr(), sql.c_str(), -1, flags, &ret, &tail); #else int res = sqlite3_prepare_v2(db.c_ptr(), sql.c_str(), -1, &ret, &tail); #endif if (res != SQLITE_OK) throw exception(res, db); return std::unique_ptr<statement>(from(ret)); } inline std::unique_ptr<statement> statement::create(const class database & db, std::string_view & sql #if SQLITE_VERSION_NUMBER >= 3020000 , unsigned int flags #endif ) { const char * start = sql.size() ? &sql[0] : ""; const char * tail = nullptr; sqlite3_stmt * ret = nullptr; #if SQLITE_VERSION_NUMBER >= 3020000 int res = sqlite3_prepare_v3(db.c_ptr(), start, int(sql.size()), flags, &ret, &tail); #else int res = sqlite3_prepare_v2(db.c_ptr(), start, int(sql.size()), &ret, &tail); #endif if (res != SQLITE_OK) throw exception(res, db); sql.remove_prefix(tail - start); return std::unique_ptr<statement>(from(ret)); } inline bool statement::step() { int res = sqlite3_step(c_ptr()); if (res == SQLITE_DONE) return false; if (res == SQLITE_ROW) return true; throw exception(res, database()); } inline void statement::bind(int idx, const std::string_view & value) { check_error(sqlite3_bind_text(c_ptr(), idx, value.size() ? &value[0] : "", int(value.size()), SQLITE_TRANSIENT)); } inline void statement::bind_reference(int idx, const std::string_view & value) { check_error(sqlite3_bind_text(c_ptr(), idx, value.size() ? &value[0] : "", int(value.size()), SQLITE_STATIC)); } #if __cpp_char8_t >= 201811 inline void statement::bind(int idx, const std::u8string_view & value) { check_error(sqlite3_bind_text(c_ptr(), idx, value.size() ? (const char *)&value[0] : "", int(value.size()), SQLITE_TRANSIENT)); } inline void statement::bind_reference(int idx, const std::u8string_view & value) { check_error(sqlite3_bind_text(c_ptr(), idx, value.size() ? (const char *)&value[0] : "", int(value.size()), SQLITE_STATIC)); } #endif inline void statement::bind(int idx, const blob_view & value) { check_error(sqlite3_bind_blob(c_ptr(), idx, value.size() ? &value[0] : (const std::byte *)"", int(value.size()), SQLITE_TRANSIENT)); } inline void statement::bind_reference(int idx, const blob_view & value) { check_error(sqlite3_bind_blob(c_ptr(), idx, value.size() ? &value[0] : (const std::byte *)"", int(value.size()), SQLITE_STATIC)); } inline void statement::bind(int idx, const value & val) { check_error(sqlite3_bind_value(c_ptr(), idx, val.c_ptr())); } template<> inline std::string_view statement::column_value<std::string_view>(int idx) const noexcept { auto first = (const char *)sqlite3_column_text(c_ptr(), idx); auto size = (size_t)sqlite3_column_bytes(c_ptr(), idx); return std::string_view(first, size); } #if __cpp_char8_t >= 201811 template<> inline std::u8string_view statement::column_value<std::u8string_view>(int idx) const noexcept { auto first = (const char8_t *)sqlite3_column_text(c_ptr(), idx); auto size = (size_t)sqlite3_column_bytes(c_ptr(), idx); return std::u8string_view(first, size); } #endif template<> inline blob_view statement::column_value<blob_view>(int idx) const noexcept { auto first = (const std::byte *)sqlite3_column_blob(c_ptr(), idx); auto size = sqlite3_column_bytes(c_ptr(), idx); return blob_view(first, first + size); } #if SQLITE_VERSION_NUMBER >= 3014000 inline allocated_string statement::expanded_sql() const { auto ret = sqlite3_expanded_sql(c_ptr()); if (!ret) throw exception(SQLITE_NOMEM); return allocated_string(ret); } #endif inline void statement::check_error(int res) const { if (res != SQLITE_OK) throw exception(res, database()); } inline std::unique_ptr<statement> statement_parser::next() { while (!_sql.empty()) { auto stmt = statement::create(*_db, _sql); if (!stmt) //this happens for a comment or white-space continue; //trim whitespace after statement while (!_sql.empty() && isspace(_sql[0])) _sql.remove_prefix(1); return stmt; } return nullptr; } } #endif
33.376344
107
0.536082
gershnik
d0883a7b1b82cffcb3238d45cffc94598e9f15a8
754
cpp
C++
codes/codeforces/OmkarandCompletion.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/codeforces/OmkarandCompletion.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/codeforces/OmkarandCompletion.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
/* ************************************************ username : smmehrab fullname : s.m.mehrabul islam email : [email protected] institute : university of dhaka, bangladesh session : 2017-2018 ************************************************ */ #include <bits/stdc++.h> #include <stdio.h> #include <math.h> #include <stdbool.h> using namespace std; // Driver Code int main() { int testCaseCount; int testCase; int n; scanf("%d", &testCaseCount); for (testCase = 1; testCase <= testCaseCount; testCase++) { scanf("%d", &n); for(int i=0; i<n; i++){ cout << 1; if(i!=n-1) cout << " "; } cout << endl; } return 0; }
22.176471
61
0.460212
smmehrab
d08b77bb54317f62de909d6d66f83bb5501b9761
6,536
cpp
C++
src/Bloom.cpp
sltn011/OpenGL-Learning
7f3b8cd730ba9d300406cdd6608afb1db6d23b31
[ "MIT" ]
1
2020-10-26T17:53:33.000Z
2020-10-26T17:53:33.000Z
src/Bloom.cpp
sltn011/OpenGL-Learning
7f3b8cd730ba9d300406cdd6608afb1db6d23b31
[ "MIT" ]
null
null
null
src/Bloom.cpp
sltn011/OpenGL-Learning
7f3b8cd730ba9d300406cdd6608afb1db6d23b31
[ "MIT" ]
null
null
null
#include "Bloom.hpp" namespace OGL { Bloom::Bloom( Shader &&downsamplingShader, Shader &&horizontalBlurShader, Shader &&verticalBlurShader, Shader &&combineShader, glm::vec3 thresHold ) : m_downsamplingShader{ std::move(downsamplingShader) }, m_horizontalBlurShader{ std::move(horizontalBlurShader) }, m_verticalBlurShader{ std::move(verticalBlurShader) }, m_combineShader{ std::move(combineShader) }, m_thresHold{ thresHold }, m_resultWidth{ 0 }, m_resultHeight{ 0 } { } void Bloom::initFrameBuffers( int windowWidth, int windowHeight ) { initFramebuffer(m_result, windowWidth, windowHeight); initFramebuffer(m_temp, windowWidth, windowHeight); for (int i = 0; i < s_numMipmaps; ++i) { int fboWidth = static_cast<int>(windowWidth / std::pow(s_downscale, i + 1)); int fboHeight = static_cast<int>(windowHeight / std::pow(s_downscale, i + 1)); initFramebuffer(m_downsamples[i], fboWidth, fboHeight); initFramebuffer(m_intermediate[i], fboWidth, fboHeight); } m_resultWidth = windowWidth; m_resultHeight = windowHeight; } void Bloom::drawToResultFrameBuffer( FrameBufferObject &sceneFrameBuffer ) { glDisable(GL_DEPTH_TEST); blit(sceneFrameBuffer, m_result, m_resultWidth, m_resultHeight); setupDownsampleShader(true); resizeImage( m_result, m_downsamples[0], static_cast<int>(m_resultWidth / s_downscale), static_cast<int>(m_resultHeight / s_downscale) ); blurImage(0, static_cast<int>(m_resultWidth / s_downscale), static_cast<int>(m_resultHeight / s_downscale)); for (int i = 1; i < s_numMipmaps; ++i) { setupDownsampleShader(false); int sampleWidth = static_cast<int>(m_resultWidth / std::pow(s_downscale, i + 1)); int sampleHeight = static_cast<int>(m_resultHeight / std::pow(s_downscale, i + 1)); resizeImage( m_downsamples[i - 1], m_downsamples[i], sampleWidth, sampleHeight ); blurImage(i, sampleWidth, sampleHeight); } setupCombineShader(); for (int i = s_numMipmaps - 1; i > 0; --i) { int sampleWidth = static_cast<int>(m_resultWidth / std::pow(s_downscale, i)); int sampleHeight = static_cast<int>(m_resultHeight / std::pow(s_downscale, i)); combineImages( m_intermediate[i - 1], m_downsamples[i], m_downsamples[i - 1], sampleWidth, sampleHeight ); blit(m_intermediate[i - 1], m_downsamples[i - 1], sampleWidth, sampleHeight); } combineImages(m_temp, m_downsamples[0], m_result, m_resultWidth, m_resultHeight); blit(m_temp, m_result, m_resultWidth, m_resultHeight); glEnable(GL_DEPTH_TEST); } void Bloom::bindResultFrameBuffer( GLenum frameBufferType ) { m_result.bind(frameBufferType); } void Bloom::initFramebuffer( FrameBufferObject &fbo, int width, int height ) { fbo.bind(GL_FRAMEBUFFER); ColorBufferObject cbo; cbo.allocateStorage(width, height, GL_TEXTURE_2D, GL_RGBA16F, GL_RGBA, GL_FLOAT); fbo.attachColorBuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, std::move(cbo)); if (!fbo.isComplete(GL_FRAMEBUFFER)) { FrameBufferObject::unbind(GL_FRAMEBUFFER); throw Exception("Error creating FBO!"); } FrameBufferObject::unbind(GL_FRAMEBUFFER); } void Bloom::blit( FrameBufferObject &from, FrameBufferObject &to, int width, int height ) { from.bind(GL_READ_FRAMEBUFFER); to.bind(GL_DRAW_FRAMEBUFFER); glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_LINEAR); FrameBufferObject::unbind(GL_FRAMEBUFFER); } void Bloom::resizeImage( FrameBufferObject &from, FrameBufferObject &to, int newWidth, int newHeight ) { glViewport(0, 0, newWidth, newHeight); to.bind(GL_FRAMEBUFFER); from.drawQuad(GL_COLOR_ATTACHMENT0); } void Bloom::blurImage( int imageIndex, int imageWidth, int imageHeight ) { setupHorizontalBlurShader(imageWidth); m_intermediate[imageIndex].bind(GL_FRAMEBUFFER); m_downsamples[imageIndex].drawQuad(GL_COLOR_ATTACHMENT0); setupVerticalBlurShader(imageHeight); m_downsamples[imageIndex].bind(GL_FRAMEBUFFER); m_intermediate[imageIndex].drawQuad(GL_COLOR_ATTACHMENT0); FrameBufferObject::unbind(GL_FRAMEBUFFER); } void Bloom::combineImages( FrameBufferObject &dst, FrameBufferObject &fbo1, FrameBufferObject &fbo2, int dstWidth, int dstHeight ) { glViewport(0, 0, dstWidth, dstHeight); glActiveTexture(GL_TEXTURE0); fbo1.getColorBuffers().at(GL_COLOR_ATTACHMENT0).bindAsTexture(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE1); fbo2.getColorBuffers().at(GL_COLOR_ATTACHMENT0).bindAsTexture(GL_TEXTURE_2D); dst.bind(GL_FRAMEBUFFER); dst.drawQuadRaw(); FrameBufferObject::unbind(GL_FRAMEBUFFER); } void Bloom::setupDownsampleShader( bool bDoCutoff ) { m_downsamplingShader.use(); m_downsamplingShader.setUniformInt("fboTexture", 0); m_downsamplingShader.setUniformVec3("bloomThresHold", bDoCutoff ? m_thresHold : glm::vec3(0.0f)); } void Bloom::setupHorizontalBlurShader( int imageWidth ) { m_horizontalBlurShader.use(); m_horizontalBlurShader.setUniformInt("fboTexture", 0); m_horizontalBlurShader.setUniformInt("imageWidth", imageWidth); } void Bloom::setupVerticalBlurShader( int imageHeight ) { m_verticalBlurShader.use(); m_verticalBlurShader.setUniformInt("fboTexture", 0); m_verticalBlurShader.setUniformInt("imageHeight", imageHeight); } void Bloom::setupCombineShader( ) { m_combineShader.use(); m_combineShader.setUniformInt("fboTexture1", 0); m_combineShader.setUniformInt("fboTexture2", 1); } } // OGL
33.177665
116
0.626224
sltn011
d08f48515301709c5cccfcabeb509b06d4533129
9,122
cpp
C++
src/RTL/Component/SceneGraph/CIFXViewResource.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
44
2016-05-06T00:47:11.000Z
2022-02-11T06:51:37.000Z
src/RTL/Component/SceneGraph/CIFXViewResource.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
3
2016-06-27T12:37:31.000Z
2021-03-24T12:39:48.000Z
src/RTL/Component/SceneGraph/CIFXViewResource.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
15
2016-02-28T11:08:30.000Z
2021-06-01T03:32:01.000Z
//*************************************************************************** // // Copyright (c) 1999 - 2006 Intel Corporation // // 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. // //*************************************************************************** /* @file CIFXViewResource.cpp */ #include "IFXSceneGraphPCH.h" #include "CIFXViewResource.h" #include "IFXLightSet.h" #include "IFXPickObject.h" #include "IFXRenderable.h" #include "IFXModifierDataElementIter.h" #include "IFXModifierDataPacket.h" #include "IFXSimpleList.h" #include "IFXSpatialSetQuery.h" #include "IFXBoundSphereDataElement.h" #include "IFXDids.h" #include "IFXExportingCIDs.h" CIFXViewResource::CIFXViewResource() { m_uRefCount = 0; m_uQualityFactor = 0; m_layer = 0; m_uNumRenderPasses = 0; m_uCurrentPass = 0; m_ppRenderPass = NULL; AllocateRenderPasses(); FogEnable(FALSE); SetStencilEnabled( FALSE ); SetColorBufferEnabled( TRUE ); //currently does nothing GetRenderClear().SetColorCleared( TRUE ); GetRenderClear().SetColorValue( IFXVector3( 0,0,0 ) ); SetDepthTestEnabled( TRUE ); SetDepthWriteEnabled( TRUE ); GetRenderClear().SetDepthCleared( TRUE ); GetRenderClear().SetDepthValue( (F32)1.0 ); } CIFXViewResource::~CIFXViewResource() { } IFXRESULT IFXAPI_CALLTYPE CIFXViewResource_Factory(IFXREFIID riid, void **ppv) { IFXRESULT result; if ( ppv ) { // Create the CIFXClassName component. CIFXViewResource *pView = new CIFXViewResource; if ( pView ) { // Perform a temporary AddRef for our usage of the component. pView->AddRef(); // Attempt to obtain a pointer to the requested interface. result = pView->QueryInterface( riid, ppv ); // Perform a Release since our usage of the component is now // complete. Note: If the QI fails, this will cause the // component to be destroyed. pView->Release(); } else result = IFX_E_OUT_OF_MEMORY; } else result = IFX_E_INVALID_POINTER; return result; } // IFXUnknown U32 CIFXViewResource::AddRef() { return ++m_uRefCount; } U32 CIFXViewResource::Release() { if (m_uRefCount == 1) { DeallocateRenderPasses(); delete this ; return 0 ; } else return (--m_uRefCount); } IFXRESULT CIFXViewResource::QueryInterface(IFXREFIID interfaceId, void** ppInterface) { IFXRESULT result = IFX_OK; if ( ppInterface ) { if ( interfaceId == IID_IFXUnknown ) *ppInterface = ( IFXUnknown* ) this; else if ( interfaceId == IID_IFXMarker ) *ppInterface = ( IFXMarker* ) this; else if ( interfaceId == IID_IFXMarkerX ) *ppInterface = ( IFXMarkerX* ) this; else if ( interfaceId == IID_IFXViewResource ) *ppInterface = ( IFXViewResource* ) this; else if ( interfaceId == IID_IFXMetaDataX ) *ppInterface = ( IFXMetaDataX* ) this; else { *ppInterface = NULL; result = IFX_E_UNSUPPORTED; } if ( IFXSUCCESS( result ) ) AddRef(); } else result = IFX_E_INVALID_POINTER; return result; } // IFXMarker IFXRESULT CIFXViewResource::SetSceneGraph( IFXSceneGraph* pInSceneGraph ) { return CIFXMarker::SetSceneGraph( pInSceneGraph ); } // IFXMarkerX void CIFXViewResource::GetEncoderX(IFXEncoderX*& rpEncoderX) { CIFXMarker::GetEncoderX(CID_IFXViewResourceEncoder, rpEncoderX); } IFXRESULT CIFXViewResource::GetRootNode(U32* pNodeIndex, U32* pNodeInstance) { IFXRESULT result = IFX_OK; if ( pNodeIndex && pNodeInstance ) { *pNodeIndex = m_ppRenderPass[m_uCurrentPass]->m_nodeIndex; *pNodeInstance = m_ppRenderPass[m_uCurrentPass]->m_nodeInstance; } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT CIFXViewResource::SetRootNode(U32 nodeIndex, U32 nodeInstance) { IFXRESULT result = IFX_OK; result = m_ppRenderPass[m_uCurrentPass]->SetRootNode(nodeIndex, nodeInstance); // Make sure to set all rootnodes that are null U32 i; for( i = 0; IFXSUCCESS(result) && i < m_uNumRenderPasses; i++) if(m_ppRenderPass[i]->m_nodeSet == FALSE) result = m_ppRenderPass[i]->SetRootNode(nodeIndex, nodeInstance); return result; } void CIFXViewResource::ClearRootNode() { m_ppRenderPass[m_uCurrentPass]->ClearRootNode(); } IFXRenderClear& CIFXViewResource::GetRenderClear() { return m_ppRenderPass[m_uCurrentPass]->m_Clear; } // IFXViewResource IFXRESULT CIFXViewResource::AllocateRenderPasses(U32 uNumRenderPasses) { IFXRESULT rc = IFX_OK; IFXRenderPass** ppRenderPasses = new IFXRenderPass*[uNumRenderPasses]; if(NULL == ppRenderPasses) { rc = IFX_E_OUT_OF_MEMORY; } if(IFXSUCCESS(rc)) { if(m_uNumRenderPasses) { U32 uNumToCopy = m_uNumRenderPasses; if(uNumToCopy > uNumRenderPasses) uNumToCopy = uNumRenderPasses; U32 i; for( i = 0; i < uNumToCopy; i++) { ppRenderPasses[i] = m_ppRenderPass[i]; m_ppRenderPass[i] = 0; } } U32 i; for( i = m_uNumRenderPasses; i < uNumRenderPasses; i++) { ppRenderPasses[i] = new IFXRenderPass(); ppRenderPasses[i]->SetDefaults(i); // Assign new passes to have the same rootnode as the first pass if(i && ppRenderPasses[0]->m_nodeSet) ppRenderPasses[i]->SetRootNode( ppRenderPasses[0]->m_nodeIndex, ppRenderPasses[0]->m_nodeInstance); } IFXDELETE_ARRAY(m_ppRenderPass); m_ppRenderPass = ppRenderPasses; m_uNumRenderPasses = uNumRenderPasses; } return rc; } IFXRESULT CIFXViewResource::DeallocateRenderPasses() { U32 i; for( i = 0; i < m_uNumRenderPasses; i++ ) IFXDELETE( m_ppRenderPass[i] ); IFXDELETE_ARRAY(m_ppRenderPass); return IFX_OK; } // IFXViewResource IFXRESULT CIFXViewResource::GetFogEnableValue( BOOL* pbEnable ) { IFXRESULT result = IFX_OK; if ( NULL != pbEnable ) *pbEnable = m_ppRenderPass[m_uCurrentPass]->m_bFogEnabled; else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT CIFXViewResource::FogEnable( BOOL bEnable ) { m_ppRenderPass[m_uCurrentPass]->m_bFogEnabled = bEnable; return IFX_OK; } IFXRenderFog& CIFXViewResource::GetRenderFog() { return m_ppRenderPass[m_uCurrentPass]->m_Fog; } IFXRESULT CIFXViewResource::GetColorBufferEnabled(BOOL& bEnabled ) { bEnabled = m_ppRenderPass[m_uCurrentPass]->m_bColorBuffer; return IFX_OK; } IFXRESULT CIFXViewResource::SetColorBufferEnabled(BOOL bEnabled ) { m_ppRenderPass[m_uCurrentPass]->m_bColorBuffer = bEnabled; return IFX_OK; } IFXRESULT CIFXViewResource::GetDepthTestEnabled(BOOL& bEnabled ) { bEnabled = m_ppRenderPass[m_uCurrentPass]->m_bDepthTest; return IFX_OK; } IFXRESULT CIFXViewResource::SetDepthTestEnabled(BOOL bEnabled ) { m_ppRenderPass[m_uCurrentPass]->m_bDepthTest = bEnabled; return IFX_OK; } IFXRESULT CIFXViewResource::GetDepthWriteEnabled(BOOL& bEnabled ) { bEnabled = m_ppRenderPass[m_uCurrentPass]->m_bDepthWrite; return IFX_OK; } IFXRESULT CIFXViewResource::SetDepthWriteEnabled(BOOL bEnabled ) { m_ppRenderPass[m_uCurrentPass]->m_bDepthWrite = bEnabled; return IFX_OK; } IFXRESULT CIFXViewResource::GetDepthFunc(IFXenum & eDepthFunc ) { eDepthFunc = m_ppRenderPass[m_uCurrentPass]->m_eDepthFunc; return IFX_OK; } IFXRESULT CIFXViewResource::SetDepthFunc(IFXenum eDepthFunc ) { IFXRESULT rc = IFX_OK; switch(eDepthFunc) { case IFX_ALWAYS: case IFX_LESS: case IFX_LEQUAL: case IFX_GREATER: case IFX_GEQUAL: case IFX_EQUAL: case IFX_NOT_EQUAL: case IFX_NEVER: m_ppRenderPass[m_uCurrentPass]->m_eDepthFunc = eDepthFunc; break; default: rc = IFX_E_INVALID_RANGE; } return rc; } IFXRESULT CIFXViewResource::GetStencilEnabled( BOOL& bEnable ) { bEnable = m_ppRenderPass[m_uCurrentPass]->m_bStencilEnabled; return IFX_OK; } IFXRESULT CIFXViewResource::SetStencilEnabled( BOOL bEnable ) { m_ppRenderPass[m_uCurrentPass]->m_bStencilEnabled = bEnable; return IFX_OK; } IFXRenderStencil& CIFXViewResource::GetRenderStencil() { return m_ppRenderPass[m_uCurrentPass]->m_Stencil; } // Multipass support IFXRESULT CIFXViewResource::SetNumRenderPasses(U32 uNumPasses) { IFXRESULT rc = IFX_E_INVALID_RANGE; IFXASSERTBOX( uNumPasses <= 32, "Trying to use too many rendering passes - use less than 33" ); if(uNumPasses <= 32) { rc = AllocateRenderPasses(uNumPasses); } return rc; } U32 CIFXViewResource::GetNumRenderPasses(void) { return m_uNumRenderPasses; } IFXRESULT CIFXViewResource::SetCurrentRenderPass(U32 uRenderPass) { IFXRESULT rc = IFX_OK; IFXASSERTBOX( uRenderPass < m_uNumRenderPasses, "Setting invalid render pass number" ); if(uRenderPass >= m_uNumRenderPasses) rc = IFX_E_INVALID_RANGE; else m_uCurrentPass = uRenderPass; return rc; } U32 CIFXViewResource::GetCurrentRenderPass() { return m_uCurrentPass; } ///
21.822967
85
0.725828
alemuntoni
d092a46ac91962e86187d573f3cfc211ffd2c2a4
3,372
cc
C++
src/4env/env.cc
romz-pl/upscaledb
781206f75a9f49b67dc0cd2c0e191435e60f4693
[ "Apache-2.0" ]
null
null
null
src/4env/env.cc
romz-pl/upscaledb
781206f75a9f49b67dc0cd2c0e191435e60f4693
[ "Apache-2.0" ]
9
2018-05-05T08:01:58.000Z
2018-05-07T19:10:01.000Z
src/4env/env.cc
romz-pl/upscaledb
781206f75a9f49b67dc0cd2c0e191435e60f4693
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2005-2017 Christoph Rupp ([email protected]). * * 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. * * See the file COPYING for License information. */ #include "0root/root.h" // Always verify that a file of level N does not include headers > N! #include "4cursor/cursor.h" #include "4db/db.h" #include "4env/env.h" #ifndef UPS_ROOT_H # error "root.h was not included" #endif using namespace upscaledb; namespace upscaledb { Db * Env::create_db(DbConfig &config, const ups_parameter_t *param) { Db *db = do_create_db(config, param); assert(db != 0); // on success: store the open database in the environment's list of // opened databases _database_map[config.db_name] = db; // flush the environment to make sure that the header page is written // to disk ups_status_t st = flush(0); if (unlikely(st)) throw Exception(st); return db; } Db * Env::open_db(DbConfig &config, const ups_parameter_t *param) { // make sure that this database is not yet open if (unlikely(_database_map.find(config.db_name) != _database_map.end())) throw Exception(UPS_DATABASE_ALREADY_OPEN); Db *db = do_open_db(config, param); assert(db != 0); // on success: store the open database in the environment's list of // opened databases _database_map[config.db_name] = db; return db; } ups_status_t Env::close_db(Db *db, uint32_t flags) { uint16_t dbname = db->name(); // flush committed Txns ups_status_t st = flush(UPS_FLUSH_COMMITTED_TRANSACTIONS); if (unlikely(st)) return (st); st = db->close(flags); if (unlikely(st)) return (st); _database_map.erase(dbname); delete db; /* in-memory database: make sure that a database with the same name * can be re-created */ if (IS_SET(config.flags, UPS_IN_MEMORY)) erase_db(dbname, 0); return 0; } ups_status_t Env::close(uint32_t flags) { ups_status_t st = 0; ScopedLock lock(mutex); /* auto-abort (or commit) all pending transactions */ if (txn_manager.get()) { Txn *t; while ((t = txn_manager->oldest_txn())) { if (!t->is_aborted() && !t->is_committed()) { if (IS_SET(flags, UPS_TXN_AUTO_COMMIT)) st = txn_manager->commit(t); else /* if (flags & UPS_TXN_AUTO_ABORT) */ st = txn_manager->abort(t); if (unlikely(st)) return st; } txn_manager->flush_committed_txns(); } } /* close all databases */ Env::DatabaseMap::iterator it = _database_map.begin(); while (it != _database_map.end()) { Env::DatabaseMap::iterator it2 = it; it++; Db *db = it2->second; if (IS_SET(flags, UPS_AUTO_CLEANUP)) st = ups_db_close((ups_db_t *)db, flags | UPS_DONT_LOCK); else st = db->close(flags); if (unlikely(st)) return st; } _database_map.clear(); return do_close(flags); } } // namespace upscaledb
24.794118
75
0.674081
romz-pl
d0957ef912818acc8cea594b0348d71d21daf660
467
cpp
C++
2DProject2ndYear/main.cpp
ryan0432/AIE_PhysicsBS
0ed7181b2e0624174e28dfa7b2035f8f1e597198
[ "MIT" ]
null
null
null
2DProject2ndYear/main.cpp
ryan0432/AIE_PhysicsBS
0ed7181b2e0624174e28dfa7b2035f8f1e597198
[ "MIT" ]
null
null
null
2DProject2ndYear/main.cpp
ryan0432/AIE_PhysicsBS
0ed7181b2e0624174e28dfa7b2035f8f1e597198
[ "MIT" ]
null
null
null
#include "_2DProject2ndYearApp.h" #include "PhysicsEngineApp.h" #include "BrickTest.h" #include <vld.h> // visual leak detection #include <crtdbg.h> // traditional method to check memory leak #include <Imgui.h> int main() { // leak detection //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // allocation auto app = new PhysicsEngineApp(); // initialise and loop app->run("AIE", 1280, 720, false); // deallocation delete app; return 0; }
20.304348
64
0.721627
ryan0432
d096b820283b096111d61c95bab22b4f663a60ea
4,742
cpp
C++
codeforce/E53/E53G.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
5
2019-03-17T01:33:19.000Z
2021-06-25T09:50:45.000Z
codeforce/E53/E53G.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
codeforce/E53/E53G.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <tuple> #include <string> using namespace std; struct SuffixDataStructure { const std::vector<int> &a; std::vector<int> sa; std::vector<int> isa; std::vector<int> lcp; std::vector<int> lg; std::vector<std::vector<int> > rmq; // a[i]>=0 SuffixDataStructure(const std::vector<int> &a) : a(a) { sa = suffix_array(a); sa.insert(sa.begin(), a.size()); build_lcp(); build_rmq(); } int get_lcp(int i, int j) { if (i == j) { return a.size() - std::max(i, j); } i = isa[i]; j = isa[j]; if (i > j) { std::swap(i, j); } int k = __lg(j - i); return std::min(rmq[k][i], rmq[k][j - (1 << k)]); } vector<int> suffix_array(vector<int> a) { const int n = a.size(); if (n == 0) return {}; const int H = *max_element(begin(a), end(a)) + 1; vector<bool> s(n); vector<int> next(n), ss; for (int i = n - 2; i >= 0; i--) { s[i] = a[i] == a[i + 1] ? s[i + 1] : a[i] < a[i + 1]; if (!s[i] && s[i + 1]) ss.push_back(i + 1); } reverse(ss.begin(), ss.end()); for (int i = 0; i < ss.size(); i++) { next[ss[i]] = i + 1 < ss.size() ? ss[i + 1] : n; } auto induced_sort = [&]() { vector<int> sa(n, -1), L(H + 1); for (int i = 0; i < n; i++) L[a[i] + 1]++; for (int i = 0; i < H; i++) L[i + 1] += L[i]; auto S = L; for (int i = (int)ss.size() - 1; i >= 0; i--) { int j = ss[i]; sa[--S[a[j] + 1]] = j; } S = L; sa[L[a[n - 1]]++] = n - 1; for (int i = 0; i < n; i++) { int j = sa[i] - 1; if (j >= 0 && !s[j]) sa[L[a[j]]++] = j; } for (int i = n - 1; i >= 0; i--) { int j = sa[i] - 1; if (j >= 0 && s[j]) sa[--S[a[j] + 1]] = j; } return sa; }; vector<int> rank(n); int j = -1; for (int i : induced_sort()) { if (0 < i && s[i] && !s[i - 1]) { if (j != -1) rank[i] = rank[j] + (next[i] - i != next[j] - j || !equal(a.begin() + i, a.begin() + next[i], a.begin() + j)); j = i; } } vector<int> b; for (int i : ss) b.push_back(rank[i]); vector<int> tmp(ss); ss.clear(); for (int i : suffix_array(b)) ss.push_back(tmp[i]); return induced_sort(); } void build_lcp() { const int n = a.size(); isa.resize(n + 1); lcp.assign(n + 1, 0); for (int i = 0; i <= n; i++) { isa[sa[i]] = i; } int k = 0; for (int i = 0; i < n; i++) { int j = sa[isa[i] - 1]; k = std::max(0, k - 1); while (i + k < n && j + k < n && a[i + k] == a[j + k]) { k++; } lcp[isa[i] - 1] = k; } } void build_rmq() { const int n = lcp.size(); lg.resize(n + 1); for (int i = 2; i <= n; i++) { lg[i] = lg[i / 2] + 1; } const int m = lg[n]; rmq.assign(m + 1, std::vector<int>(n)); for (int i = 0; i < n; i++) { rmq[0][i] = lcp[i]; } for (int i = 0; i < m; i++) { for (int j = 0; j + (1 << i) < n; j++) { rmq[i + 1][j] = std::min(rmq[i][j], rmq[i][j + (1 << i)]); } } } }; const long long inf = 1e9; struct Stack { vector<pair<int, long long>> a; long long sum = 0; void push() { sum += inf; a.emplace_back(inf, 1); } void cut(int k) { long long s = 0; while (!a.empty() && a.back().first >= k) { s += a.back().second; sum -= a.back().first * a.back().second; a.pop_back(); } sum += s * k; a.emplace_back(k, s); } int total() { int s = 0; for (auto p : a) s += p.second; return s; } }; int main() { int n, q; cin >> n >> q; string s; cin >> s; vector<int> a; for (int i = 0; i < n; i++) { a.push_back(s[i] - 'a'); } SuffixDataStructure sa(a); while (q--) { int u, v; scanf("%d %d", &u, &v); vector<int> a(u); vector<int> b(v); for (int i = 0; i < u; i++) scanf("%d", &a[i]), a[i]--, a[i] = sa.isa[a[i]]; for (int i = 0; i < v; i++) scanf("%d", &b[i]), b[i]--, b[i] = sa.isa[b[i]]; sort(a.begin(), a.end()); sort(b.begin(), b.end()); int i = 0; int j = 0; Stack A, B; int p = -1; long long ans = 0; while (i < u || j < v) { if (j == v || (i < u && a[i] < b[j])) { int h = p == -1 ? 0 : sa.get_lcp(sa.sa[p], sa.sa[a[i]]); p = a[i]; A.cut(h); B.cut(h); ans += B.sum; A.push(); i++; } else { int h = p == -1 ? 0 : sa.get_lcp(sa.sa[p], sa.sa[b[j]]); p = b[j]; A.cut(h); B.cut(h); ans += A.sum; B.push(); j++; } } printf("%lld\n", ans); } }
23.475248
131
0.412273
heiseish
d097074d91e884566fb39e3e198fa2f261f1aca7
497
cpp
C++
boost.asio/chapter01/passive-socket/main.cpp
pvthuyet/books
bac5f754a68243e463ec7b0d93610be8807b31ac
[ "BSL-1.0" ]
null
null
null
boost.asio/chapter01/passive-socket/main.cpp
pvthuyet/books
bac5f754a68243e463ec7b0d93610be8807b31ac
[ "BSL-1.0" ]
null
null
null
boost.asio/chapter01/passive-socket/main.cpp
pvthuyet/books
bac5f754a68243e463ec7b0d93610be8807b31ac
[ "BSL-1.0" ]
null
null
null
#include <boost/asio.hpp> #include <iostream> int main() { namespace asio = boost::asio; // step 1 asio::io_service ios; // step 2 asio::ip::tcp protocal = asio::ip::tcp::v6(); // step 3 asio::ip::tcp::acceptor acceptor(ios); boost::system::error_code ec; acceptor.open(protocal, ec); if (ec.value() != 0) { std::cout << "Failed to open the acceptor socket! Error code = " << ec.value() << ". Message: " << ec.message() << std::endl; return ec.value(); } return EXIT_SUCCESS; }
23.666667
66
0.627767
pvthuyet
d09c65f9434d047f6393f2ab7424074d5f8682f2
30,055
cpp
C++
src/Button.cpp
cclark2a/SchmickleWorks
6945cc443c1a65426770b11f0de1b44b5fdcbd85
[ "Unlicense" ]
15
2018-02-19T19:45:32.000Z
2020-07-23T07:23:37.000Z
src/Button.cpp
cclark2a/SchmickleWorks
6945cc443c1a65426770b11f0de1b44b5fdcbd85
[ "Unlicense" ]
24
2018-08-09T13:49:40.000Z
2019-11-08T19:31:55.000Z
src/Button.cpp
cclark2a/SchmickleWorks
6945cc443c1a65426770b11f0de1b44b5fdcbd85
[ "Unlicense" ]
null
null
null
#include "Button.hpp" #include "Display.hpp" #include "Taker.hpp" #include "Wheel.hpp" #include "Widget.hpp" // try to get rest working as well as note void AdderButton::onDragEndPreamble(const event::DragEnd& e) { // insertLoc, shiftTime set by caller shiftLoc = insertLoc + 1; startTime = this->ntw()->n().notes[insertLoc].startTime; if (debugVerbose) DEBUG("insertLoc %u shiftLoc %u startTime %d", insertLoc, shiftLoc, startTime); } void AdderButton::onDragEnd(const event::DragEnd& e) { auto ntw = this->ntw(); auto& n = ntw->n(); if (shiftTime) { n.shift(shiftLoc, shiftTime, AddToChannels::all == addToChannels ? ALL_CHANNELS : this->ntw()->selectChannels); } n.sort(); ntw->selectButton->setOff(); NoteTakerButton::onDragEnd(e); ntw->invalAndPlay(Inval::cut); ntw->setSelect(insertLoc, insertLoc + 1); ntw->turnOffLEDButtons(); ntw->setWheelRange(); // range is larger ntw->displayBuffer->redraw(); } ButtonBuffer::ButtonBuffer(NoteTakerButton* button) { fb = new FramebufferWidget(); fb->dirty = true; this->addChild(fb); fb->addChild(button); } template<class TButton> std::string WidgetToolTip<TButton>::getDisplayValueString() { if (!widget) { return "!uninitialized"; } if (defaultLabel.empty()) { defaultLabel = label; } if (widget->ntw()->runButton->ledOn()) { label = "Play"; return widget->runningTooltip(); } else { label = defaultLabel; } return ""; } template struct WidgetToolTip<CutButton>; template struct WidgetToolTip<FileButton>; template struct WidgetToolTip<InsertButton>; template struct WidgetToolTip<KeyButton>; template struct WidgetToolTip<PartButton>; template struct WidgetToolTip<RestButton>; template struct WidgetToolTip<SelectButton>; template struct WidgetToolTip<SustainButton>; template struct WidgetToolTip<SlotButton>; template struct WidgetToolTip<TempoButton>; template struct WidgetToolTip<TieButton>; template struct WidgetToolTip<TimeButton>; void CutButton::draw(const DrawArgs& args) { const int af = animationFrame; EditButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 24); nvgText(vg, 4 + af, 41 - af, ";", NULL); } void CutButton::getState() { auto ntw = this->ntw(); if (ntw->runButton->ledOn()) { state = State::running; return; } if (ntw->fileButton->ledOn()) { state = State::cutAll; return; } if (ntw->partButton->ledOn()) { state = State::cutPart; return; } SelectButton* selectButton = ntw->selectButton; if (selectButton->editStart() && (ntw->slotButton->ledOn() ? ntw->storage.saveZero : selectButton->saveZero)) { state = State::clearClipboard; return; } if (selectButton->editEnd()) { state = State::cutToClipboard; return; } state = selectButton->editStart() ? State::insertCutAndShift : State::cutAndShift; } void CutButton::onDragEnd(const rack::event::DragEnd& e) { if (this->stageSlot(e)) { return; } this->getState(); auto ntw = this->ntw(); auto& n = ntw->n(); ntw->clipboardInvalid = true; NoteTakerButton::onDragEnd(e); if (State::cutAll == state) { SCHMICKLE(!ntw->slotButton->ledOn()); n.selectStart = 0; n.selectEnd = n.notes.size() - 1; ntw->copyNotes(); // allows add to undo accidental cut / clear all ntw->setScoreEmpty(); ntw->setSelectStart(n.atMidiTime(0)); ntw->selectButton->setSingle(); ntw->setWheelRange(); ntw->displayBuffer->redraw(); return; } if (State::cutPart == state) { SCHMICKLE(!ntw->slotButton->ledOn()); n.selectStart = 0; n.selectEnd = n.notes.size() - 1; ntw->copySelectableNotes(); ntw->setSelectableScoreEmpty(); ntw->setSelectStart(n.atMidiTime(0)); ntw->setWheelRange(); ntw->displayBuffer->redraw(); return; } bool slotOn = ntw->slotButton->ledOn(); if (State::clearClipboard == state) { ntw->clipboard.clear(slotOn); return; } unsigned start = slotOn ? ntw->storage.slotStart : n.selectStart; unsigned end = slotOn ? ntw->storage.slotEnd : n.selectEnd; if (!slotOn && (!start || end <= 1)) { DEBUG("*** selectButton should have been set to edit start, save zero"); _schmickled(); return; } if (State::insertCutAndShift != state) { slotOn ? ntw->copySlots() : ntw->copyNotes(); } if (slotOn) { if (0 == start && ntw->storage.size() <= end) { ++start; // always leave one slot } if (start >= end) { return; } ntw->storage.shiftSlots(start, end); if (ntw->storage.size() <= start) { --start; // move select to last remaining slot } ntw->storage.slotStart = start; ntw->storage.slotEnd = start + 1; } else { int shiftTime = n.notes[start].startTime - n.notes[end].startTime; if (State::cutToClipboard == state) { // to do : insert a rest if existing notes do not include deleted span shiftTime = 0; } else { SCHMICKLE(State::cutAndShift == state || State::insertCutAndShift == state); } // set selection to previous selectable note, or zero if none int vWheel = (int) ntw->verticalWheel->getValue(); if (vWheel) { float lo, hi; ntw->verticalWheel->getLimits(&lo, &hi); if (vWheel == (int) hi - 1) { --vWheel; } } if (vWheel) { unsigned selStart = ntw->edit.voices[vWheel - 1]; ntw->setSelect(selStart, selStart + 1); } else { int wheel = ntw->noteToWheel(start); unsigned previous = ntw->wheelToNote(std::max(0, wheel - 1)); ntw->setSelect(previous, previous < start ? start : previous + 1); } n.eraseNotes(start, end, ntw->selectChannels); if (shiftTime) { ntw->shiftNotes(start, shiftTime); } else { n.sort(); } ntw->invalAndPlay(Inval::cut); ntw->turnOffLEDButtons(); } ntw->selectButton->setSingle(); // range is smaller ntw->setWheelRange(); ntw->displayBuffer->redraw(); } void EditButton::onDragStart(const event::DragStart& e) { auto ntw = this->ntw(); if (ntw->runButton->ledOn()) { return; } NoteTakerButton::onDragStart(e); } void EditLEDButton::onDragEnd(const event::DragEnd& e) { if (this->stageSlot(e)) { return; } auto ntw = this->ntw(); NoteTakerButton::onDragEnd(e); ntw->turnOffLEDButtons(this); ntw->setWheelRange(); ntw->displayBuffer->redraw(); } void FileButton::draw(const DrawArgs& args) { const int af = animationFrame; EditLEDButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 24); nvgText(vg, 5 + af, 41 - af, ":", NULL); } // to do : change graphic on insert button to show what pressing the button will do // distinguish : add one note after / add multiple notes after / add one note above / // add multiple notes above // also change tooltips to describe this in words void InsertButton::draw(const DrawArgs& args) { const int af = animationFrame; EditButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 24); nvgText(vg, 8 + af, 41 - af, "H", NULL); } // allows tooltip to show what button is going to do without pressing it void InsertButton::getState() { auto ntw = this->ntw(); const auto& n = ntw->n(); if (ntw->runButton->ledOn()) { state = State::running; return; } auto selectButton = ntw->selectButton; bool useClipboard = selectButton->ledOn(); if (ntw->slotButton->ledOn()) { insertLoc = selectButton->editStart() ? ntw->storage.startToWheel() : ntw->storage.slotEnd; state = useClipboard && !ntw->clipboard.playback.empty() ? State::clipboardShift : State::dupShift; return; } span.clear(); // all notes on pushed on span stack require note off to be added as well lastEndTime = 0; insertTime = 0; if (!n.noteCount(ntw->selectChannels) && ntw->clipboard.notes.empty()) { insertLoc = n.atMidiTime(0); span.push_back(ntw->middleC()); Notes::AddNoteOff(span); state = State::middleCShift; return; } // select set to insert (start) or off: // Insert loc is where the new note goes, but not when the new note goes; // the new start time is 'last end time(insert loc)' // select set to extend (end): // Insert loc is select start; existing notes are not shifted, insert is transposed bool insertInPlace = selectButton->editEnd(); unsigned iStart = n.selectStart; if (!iStart) { iStart = insertLoc = ntw->wheelToNote(1); } else if (insertInPlace) { insertLoc = n.selectStart; } else { insertLoc = n.selectEnd; // A prior edit (e.g., changing a note duration) may invalidate using select end as the // insert location. Use select end to determine the last active note to insert after, // but not the location to insert after. for (unsigned index = 0; index < n.selectEnd; ++index) { const auto& note = n.notes[index]; if (note.isSelectable(ntw->selectChannels)) { lastEndTime = std::max(lastEndTime, note.endTime()); insertLoc = n.selectEnd; } if (note.isNoteOrRest() && note.startTime >= lastEndTime && index < insertLoc) { insertLoc = index; } } } while (NOTE_OFF == n.notes[insertLoc].type) { ++insertLoc; } insertTime = n.notes[insertLoc].startTime; if (!insertInPlace) { // insertLoc may be different channel, so can't use that start time by itself // shift to selectStart time, but not less than previous end (if any) on same channel while (insertTime < lastEndTime) { SCHMICKLE(TRACK_END != n.notes[insertLoc].type); ++insertLoc; SCHMICKLE(insertLoc < n.notes.size()); insertTime = n.notes[insertLoc].startTime; } } if (!useClipboard || ntw->clipboard.notes.empty() || !ntw->extractClipboard(&span)) { for (unsigned index = iStart; index < n.selectEnd; ++index) { const auto& note = n.notes[index]; if (note.isSelectable(ntw->selectChannels)) { // use lambda for this pattern span.push_back(note); span.back().cache = nullptr; } } state = insertInPlace ? State::dupInPlace : selectButton->editStart() ? State::dupLeft : State::dupShift; } else { state = insertInPlace ? State::clipboardInPlace : State::clipboardShift; } if (span.empty() || (1 == span.size() && NOTE_ON != span[0].type) || (span[0].isSignature() && n.notes[insertLoc].isSignature())) { span.clear(); state = insertInPlace ? State::dupInPlace : State::dupShift; for (unsigned index = iStart; index < n.notes.size(); ++index) { const auto& note = n.notes[index]; if (NOTE_ON == note.type && note.isSelectable(ntw->selectChannels)) { span.push_back(note); span.back().cache = nullptr; break; } } } if (span.empty()) { for (unsigned index = iStart; --index > 0; ) { const auto& note = n.notes[index]; if (NOTE_ON == note.type && note.isSelectable(ntw->selectChannels)) { span.push_back(note); span.back().cache = nullptr; break; } } } if (span.empty()) { const DisplayNote& midC = ntw->middleC(); span.push_back(midC); state = insertInPlace ? State::middleCInPlace : State::middleCShift; } if (1 == span.size()) { Notes::AddNoteOff(span); } } void InsertButton::onDragEnd(const event::DragEnd& e) { if (this->stageSlot(e)) { return; } this->getState(); auto ntw = this->ntw(); auto& n = ntw->n(); ntw->clipboardInvalid = true; ntw->turnOffLEDButtons(nullptr, true); // turn off pitch, file, sustain, etc but not slot if (debugVerbose) DEBUG("lastEndTime %d insertLoc %u", lastEndTime, insertLoc); bool slotOn = ntw->slotButton->ledOn(); if (debugVerbose) DEBUG("insertTime %d clipboard size %u", insertTime, slotOn ? ntw->clipboard.playback.size() : ntw->clipboard.notes.size()); vector<SlotPlay> pspan; if (State::middleCShift != state) { // select set to insert (start) or off: // Insert loc is where the new note goes, but not when the new note goes; // the new start time is 'last end time(insert loc)' // select set to extend (end): // Insert loc is select start; existing notes are not shifted, insert is transposed if (state != State::clipboardInPlace && state != State::clipboardShift) { if (debugVerbose) DEBUG(!n.selectStart ? "left of first note" : "duplicate selection"); ntw->clipboard.clear(slotOn); ntw->setClipboardLight(); if (slotOn) { pspan.assign(ntw->storage.playback.begin() + ntw->storage.slotStart, ntw->storage.playback.begin() + ntw->storage.slotEnd); } } else { if (slotOn) { pspan = ntw->clipboard.playback; } if (debugVerbose) slotOn ? DEBUG("clipboard to pspan (%u slots)", pspan.size()) : DEBUG("clipboard to span (%u notes)", span.size()); } } // insertInPlace mode disabled for now, for several reasons // it allows duplicating (a top note of) a phrase and transposing it, but the 'top note' part is buggy // the result is a non-continuous selection -- currently that isn't supported // it's an idea that is not uniformly supported: i.e., one can't copy and paste the top note of a phrase // or copy from one part to another // as mentioned, highest only is buggy and without it it would be odd to copy and transpose whole chords bool insertInPlace = false && !slotOn && ntw->selectButton->editEnd(); unsigned insertSize = slotOn ? pspan.size() : span.size(); int shiftTime = 0; if (insertInPlace) { // not sure what I was thinking -- already have a way to add single notes to chord // Notes::HighestOnly(span); // if edit end, remove all but highest note of chord if (!n.transposeSpan(span)) { DEBUG("** failed to transpose span"); return; } n.notes.insert(n.notes.begin() + insertLoc, span.begin(), span.end()); } else { if (slotOn) { ntw->storage.playback.insert(ntw->storage.playback.begin() + insertLoc, pspan.begin(), pspan.end()); ntw->stageSlot(pspan[0].index); } else { int nextStart = ntw->nextStartTime(insertLoc); if (Notes::ShiftNotes(span, 0, lastEndTime - span.front().startTime)) { std::sort(span.begin(), span.end()); } n.notes.insert(n.notes.begin() + insertLoc, span.begin(), span.end()); // include notes on other channels that fit within the start/end window // shift by span duration less next start (if any) on same channel minus selectStart time shiftTime = (lastEndTime - insertTime) + (Notes::LastEndTime(span) - span.front().startTime); int availableTime = nextStart - insertTime; if (debugVerbose) DEBUG("shift time %d available %d", shiftTime, availableTime); shiftTime = std::max(0, shiftTime - availableTime); } if (debugVerbose) DEBUG("insertLoc=%u insertSize=%u shiftTime=%d selectStart=%u" " selectEnd=%u", insertLoc, insertSize, shiftTime, slotOn ? ntw->storage.slotStart : n.selectStart, slotOn ? ntw->storage.slotEnd : n.selectEnd); if (debugVerbose) ntw->debugDump(false, true); } ntw->selectButton->setOff(); ntw->insertFinal(shiftTime, insertLoc, insertSize); NoteTakerButton::onDragEnd(e); } // insert key signature void KeyButton::onDragEnd(const event::DragEnd& e) { if (this->stageSlot(e)) { return; } auto ntw = this->ntw(); auto& n = ntw->n(); insertLoc = n.atMidiTime(n.notes[n.selectEnd].startTime); if (n.insertContains(insertLoc, KEY_SIGNATURE)) { return; } shiftTime = duration = 0; onDragEndPreamble(e); DisplayNote keySignature(KEY_SIGNATURE); n.notes.insert(n.notes.begin() + insertLoc, keySignature); shiftTime = duration = 0; AdderButton::onDragEnd(e); } void KeyButton::draw(const DrawArgs& args) { const int af = animationFrame; EditButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 24); nvgText(vg, 6 + af, 33 - af, "#", NULL); nvgText(vg, 10 + af, 41 - af, "$", NULL); } void NoteTakerButton::draw(const DrawArgs& args) { if (false && debugVerbose) { float t[6]; nvgCurrentTransform(args.vg, t); if (memcmp(lastTransform, t, sizeof(lastTransform))) { DEBUG("notetakerbutton xform %g %g %g %g %g %g", t[0], t[1], t[2], t[3], t[4], t[5]); memcpy(lastTransform, t, sizeof(lastTransform)); this->fb()->dirty = true; } } const int af = animationFrame; auto ntw = this->ntw(); auto nt = ntw->nt(); if (!nt || slotNumber >= SLOT_COUNT) { return; } auto runButton = ntw->runButton; if (runButton->dynamicRunTimer >= nt->getRealSeconds()) { this->fb()->dirty = true; } auto vg = args.vg; int alpha = std::max(0, (int) (255 * (runButton->dynamicRunTimer - nt->getRealSeconds()) / runButton->fadeDuration)); if (runButton->ledOn()) { alpha = 255 - alpha; } runButton->dynamicRunAlpha = alpha; if (ntw->storage.slots[slotNumber].n.isEmpty(ALL_CHANNELS)) { alpha /= 3; } nvgFillColor(vg, nvgRGBA(0, 0, 0, alpha)); std::string label = std::to_string(slotNumber + 1); nvgFontFaceId(vg, ntw->textFont()); nvgTextAlign(vg, NVG_ALIGN_CENTER); nvgFontSize(vg, 18); nvgText(vg, 10 + af, 32 - af, label.c_str(), NULL); } int NoteTakerButton::runAlpha() const { return 255 - ntw()->runButton->dynamicRunAlpha; } bool NoteTakerButton::stageSlot(const event::DragEnd& e) { if (e.button != GLFW_MOUSE_BUTTON_LEFT) { return true; } auto ntw = this->ntw(); if (!ntw->runButton->ledOn()) { return false; } if (ntw->storage.slots[slotNumber].n.isEmpty(ALL_CHANNELS)) { return true; } ntw->stageSlot(slotNumber); return true; } void PartButton::draw(const DrawArgs& args) { const int af = animationFrame; EditLEDButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 24); nvgText(vg, 8 + af, 41 - af, "\"", NULL); } void PartButton::onDragEnd(const event::DragEnd& e) { if (this->stageSlot(e)) { return; } NoteTakerButton::onDragEnd(e); auto ntw = this->ntw(); if (!ledOn()) { this->onTurnOff(); } else if (ntw->selectButton->editEnd()) { ntw->clipboardInvalid = true; ntw->copySelectableNotes(); } if (debugVerbose) DEBUG("part button onDragEnd ledOn %d part %d selectChannels %d unlocked %u", this->ledOn(), ntw->horizontalWheel->part(), ntw->selectChannels, ntw->unlockedChannel()); ntw->turnOffLEDButtons(this); // range is larger ntw->setWheelRange(); ntw->displayBuffer->redraw(); } void RestButton::draw(const DrawArgs& args) { const int af = animationFrame; EditButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 36); nvgText(vg, 8 + af, 41 - af, "t", NULL); } void RestButton::onDragEnd(const event::DragEnd& e) { if (this->stageSlot(e)) { return; } auto ntw = this->ntw(); auto& n = ntw->n(); ntw->turnOffLEDButtons(); // turn off pitch, file, sustain, etc if (!ntw->selectButton->editStart()) { event::DragEnd e; ntw->cutButton->onDragEnd(e); if (debugVerbose) ntw->debugDump(); } insertLoc = n.atMidiTime(n.notes[n.selectEnd].startTime); onDragEndPreamble(e); DisplayNote rest(REST_TYPE, startTime, n.ppq, (uint8_t) ntw->unlockedChannel()); shiftTime = rest.duration; n.notes.insert(n.notes.begin() + insertLoc, rest); AdderButton::onDragEnd(e); } void RunButton::onDragEnd(const event::DragEnd& e) { if (e.button != GLFW_MOUSE_BUTTON_LEFT) { return; } NoteTakerButton::onDragEnd(e); auto ntw = this->ntw(); auto nt = ntw->nt(); if (!this->ledOn()) { ntw->enableButtons(); dynamicRunAlpha = 255; nt->requests.push(RequestType::resetPlayStart); } else { nt->requests.push(RequestType::resetAndPlay); ntw->resetForPlay(); ntw->turnOffLEDButtons(this, true); ntw->disableEmptyButtons(); dynamicRunAlpha = 0; } dynamicRunTimer = nt->getRealSeconds() + fadeDuration; ntw->setWheelRange(); ntw->displayBuffer->redraw(); DEBUG("onDragEnd end af %d ledOn %d", animationFrame, ledOn()); } // to do : change drawn graphic to show the mode? edit / insert / select ? // (not crazy about this idea) void SelectButton::draw(const DrawArgs& args) { const int af = animationFrame; EditLEDButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 24); nvgText(vg, 4 + af, 41 - af, "<", NULL); // was \u00E0 } void SelectButton::onDragEnd(const event::DragEnd& e) { if (this->stageSlot(e)) { return; } auto ntw = this->ntw(); auto& n = ntw->n(); NoteTakerButton::onDragEnd(e); bool slotOn = ntw->slotButton->ledOn(); auto& storage = ntw->storage; if (this->isOff()) { SCHMICKLE(!this->ledOn()); slotOn ? ntw->copySlots() : ntw->copySelectableNotes(); } else if (this->isSingle()) { SCHMICKLE(this->ledOn()); if (slotOn) { if (debugVerbose) DEBUG("isSingle pre storage saveZero=%d s=%d e=%d", storage.saveZero, storage.slotStart, storage.slotEnd); // to do : leave slot end alone, and only look at slot start in insertion mode? storage.slotEnd = storage.slotStart + 1; if (debugVerbose) DEBUG("isSingle post storage saveZero=%d s=%d e=%d", storage.saveZero, storage.slotStart, storage.slotEnd); } else { if (ntw->edit.voice) { ntw->nt()->requests.push(RequestType::invalidateVoiceCount); ntw->edit.voice = false; } unsigned start = saveZero ? ntw->wheelToNote(0) : n.selectStart; ntw->setSelect(start, n.nextAfter(start, 1)); } } else { SCHMICKLE(this->isExtend()); SCHMICKLE(this->ledOn()); if (slotOn) { if (debugVerbose) DEBUG("isExtend pre storage saveZero=%d s=%d e=%d", storage.saveZero, storage.slotStart, storage.slotEnd); } else { if (ntw->edit.voice) { ntw->nt()->requests.push(RequestType::invalidateVoiceCount); ntw->edit.voice = false; } if (!n.horizontalCount(ntw->selectChannels)) { ntw->clipboard.notes.clear(); this->setState(State::single); // can't start selection if there's nothing to select } else { int wheelStart = ntw->noteToWheel(n.selectStart); saveZero = !wheelStart; int wheelIndex = std::max(1, wheelStart); selStart = ntw->wheelToNote(wheelIndex); SCHMICKLE(MIDI_HEADER != n.notes[selStart].type); SCHMICKLE(TRACK_END != n.notes[selStart].type); const auto& note = n.notes[selStart]; unsigned end = note.isSignature() ? selStart + 1 : n.nextAfter(selStart, 1); ntw->setSelect(selStart, end); } } } ntw->setClipboardLight(); ntw->turnOffLEDButtons(this, true); // if state is single, set to horz from -1 to size ntw->setWheelRange(); ntw->displayBuffer->redraw(); } // currently not called by anyone #if 0 void SelectButton::setExtend() { this->setState(State::extend); fb()->dirty = true; ntw()->setClipboardLight(); } #endif void SelectButton::setOff() { saveZero = false; this->setState(State::ledOff); fb()->dirty = true; ntw()->setClipboardLight(); } void SelectButton::setSingle() { auto ntw = this->ntw(); auto& n = ntw->n(); saveZero = !ntw->noteToWheel(n.selectStart); this->setState(State::single); fb()->dirty = true; ntw->setClipboardLight(); } void SlotButton::draw(const DrawArgs& args) { const int af = animationFrame; EditLEDButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 32); nvgText(vg, 1.5 + af, 41 - af, "?", NULL); } void SustainButton::draw(const DrawArgs& args) { const int af = animationFrame; EditLEDButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 24); nvgText(vg, 4 + af, 41 - af, "=", NULL); } void TempoButton::onDragEnd(const event::DragEnd& e) { if (this->stageSlot(e)) { return; } auto ntw = this->ntw(); auto& n = ntw->n(); insertLoc = n.atMidiTime(n.notes[n.selectEnd].startTime); if (n.insertContains(insertLoc, MIDI_TEMPO)) { return; } shiftTime = duration = 0; onDragEndPreamble(e); DisplayNote tempo(MIDI_TEMPO, startTime); n.notes.insert(n.notes.begin() + insertLoc, tempo); shiftTime = duration = 0; AdderButton::onDragEnd(e); } void TempoButton::draw(const DrawArgs& args) { const int af = animationFrame; EditButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 24); nvgText(vg, 5 + af, 41 - af, "@", NULL); } // to do : call body (minus inherited part) on json load to restore state? void TieButton::onDragEnd(const event::DragEnd& e) { // horz: no slur / original / all slur // vert: no triplet / original / all triplet // to do : if selection is too small to slur / trip, button should be disabled ? auto ntw = this->ntw(); ntw->edit.clear(); auto& n = ntw->n(); ntw->edit.init(n, ntw->selectChannels); setTie = n.slursOrTies(ntw->selectChannels, Notes::HowMany::set, &setSlur); setTriplet = n.triplets(ntw->selectChannels, Notes::HowMany::set); clearTie = n.slursOrTies(ntw->selectChannels, Notes::HowMany::clear, &clearSlur); clearTriplet = n.triplets(ntw->selectChannels, Notes::HowMany::clear); EditLEDButton::onDragEnd(e); } void TieButton::draw(const DrawArgs& args) { const int af = animationFrame; EditButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 24); nvgText(vg, 1 + af, 41 - af, ">", NULL); } // insert time signature void TimeButton::onDragEnd(const event::DragEnd& e) { if (this->stageSlot(e)) { return; } auto ntw = this->ntw(); auto& n = ntw->n(); insertLoc = n.atMidiTime(n.notes[n.selectEnd].startTime); if (n.insertContains(insertLoc, TIME_SIGNATURE)) { return; } shiftTime = duration = 0; onDragEndPreamble(e); DisplayNote timeSignature(TIME_SIGNATURE, startTime); n.notes.insert(n.notes.begin() + insertLoc, timeSignature); shiftTime = duration = 0; AdderButton::onDragEnd(e); } void TimeButton::draw(const DrawArgs& args) { const int af = animationFrame; EditButton::draw(args); NVGcontext* vg = args.vg; nvgFontFaceId(vg, ntw()->musicFont()); nvgTextAlign(vg, NVG_ALIGN_LEFT); nvgFillColor(vg, nvgRGBA(0, 0, 0, this->runAlpha())); nvgFontSize(vg, 24); nvgText(vg, 8 + af, 33 - af, "4", NULL); nvgText(vg, 8 + af, 41 - af, "4", NULL); }
35.950957
108
0.598669
cclark2a
d09e4be5225b159e0973d74a71e0c31dd158ee78
1,854
tpp
C++
rb_tree/includes/btree_delete.tpp
paulahemsi/ft_containers
c7d6c878c25bf4faeb60f86f977639c8a7006776
[ "MIT" ]
1
2022-03-02T15:14:16.000Z
2022-03-02T15:14:16.000Z
rb_tree/includes/btree_delete.tpp
paulahemsi/ft_containers
c7d6c878c25bf4faeb60f86f977639c8a7006776
[ "MIT" ]
73
2021-12-11T18:54:53.000Z
2022-03-28T01:32:52.000Z
rb_tree/includes/btree_delete.tpp
paulahemsi/ft_containers
c7d6c878c25bf4faeb60f86f977639c8a7006776
[ "MIT" ]
null
null
null
#ifndef BTREE_DELETE_TPP #define BTREE_DELETE_TPP #include "btree.tpp" #include "btree_create_node.tpp" #include "btree_delete_rules.tpp" template <class T> ft::btree<T> * find_neighbor(ft::btree<T> *node) { if (!is_nil(node->left)) return (find_predecessor_below(node->left)); else return (find_successor_below(node->right)); } template <class T> void replace_content(ft::btree<T> *node, ft::btree<T> *node_to_replace) { node->item = node_to_replace->item; } template <class T, class Alloc> void delete_leaf(ft::btree<T> *leaf, Alloc alloc) { alloc.deallocate(leaf->right, 1); alloc.deallocate(leaf->left, 1); alloc.deallocate(leaf, 1); } template <class T, class Alloc> void delete_node(ft::btree<T> *node, Alloc alloc) { check_delete_rules(node); if (is_left_child(node->parent, node)) node->parent->left = create_nil_node(node->parent, alloc); else node->parent->right = create_nil_node(node->parent, alloc); delete_leaf(node, alloc); } template <class T, class Alloc> void btree_delete_recursive(ft::btree<T> *node_to_delete, Alloc alloc) { if (is_leaf(node_to_delete)) return (delete_node(node_to_delete, alloc)); ft::btree<T> * node_to_replace = find_neighbor(node_to_delete); replace_content(node_to_delete, node_to_replace); return (btree_delete_recursive(node_to_replace, alloc)); } template <class T, class Compare, class Alloc> T * btree_delete(ft::btree<T> **root, T data_ref, Compare compare, Alloc alloc) { ft::btree<T> * node_to_delete = btree_search_node<T>(*root, data_ref, compare); if (!node_to_delete) return (NULL); const T * item_to_return = node_to_delete->item; if (is_last_node(node_to_delete)) { delete_leaf(node_to_delete, alloc); *root = NULL; } else { btree_delete_recursive(node_to_delete, alloc); update_root(root); } return (const_cast<T *>(item_to_return)); } #endif
25.054054
80
0.735707
paulahemsi
d0a12678e771de4ce7b18142dfdb630718a0f0ba
466
hpp
C++
transmission_interface_extensions/include/transmission_interface_extensions/common_namespaces.hpp
smilerobotics/ros_control_extensions
1eee21217708dcee80aa3d91b2c6415c1f4feffa
[ "MIT" ]
null
null
null
transmission_interface_extensions/include/transmission_interface_extensions/common_namespaces.hpp
smilerobotics/ros_control_extensions
1eee21217708dcee80aa3d91b2c6415c1f4feffa
[ "MIT" ]
null
null
null
transmission_interface_extensions/include/transmission_interface_extensions/common_namespaces.hpp
smilerobotics/ros_control_extensions
1eee21217708dcee80aa3d91b2c6415c1f4feffa
[ "MIT" ]
1
2021-10-14T06:37:36.000Z
2021-10-14T06:37:36.000Z
#ifndef TRANSMISSION_INTERFACE_EXTENSIONS_COMMON_NAMESPACES_HPP #define TRANSMISSION_INTERFACE_EXTENSIONS_COMMON_NAMESPACES_HPP namespace hardware_interface {} namespace hardware_interface_extensions {} namespace transmission_interface {} namespace transmission_interface_extensions { namespace hi = hardware_interface; namespace hie = hardware_interface_extensions; namespace ti = transmission_interface; } // namespace transmission_interface_extensions #endif
29.125
63
0.879828
smilerobotics
d0a285f3f8a5506ab698fd1dc084435df009c5ba
1,457
cpp
C++
slUtil.cpp
FigBug/slCommon
b49d31c4f2f131506fe5ac53f2ac6e47b3ee109b
[ "MIT" ]
null
null
null
slUtil.cpp
FigBug/slCommon
b49d31c4f2f131506fe5ac53f2ac6e47b3ee109b
[ "MIT" ]
null
null
null
slUtil.cpp
FigBug/slCommon
b49d31c4f2f131506fe5ac53f2ac6e47b3ee109b
[ "MIT" ]
null
null
null
#include "slUtil.h" LevelTracker::LevelTracker (float decayPerSecond) : decayRate (decayPerSecond) { } void LevelTracker::trackBuffer (AudioSampleBuffer& buffer) { for (int i = 0; i < buffer.getNumChannels(); i++) trackBuffer (buffer.getReadPointer (0), buffer.getNumSamples()); } void LevelTracker::trackBuffer (const float* buffer, int numSamples) { Range<float> range = FloatVectorOperations::findMinAndMax (buffer, numSamples); float v1 = std::fabs (range.getStart()); float v2 = std::fabs (range.getEnd()); float peakDB = Decibels::gainToDecibels (jmax (v1, v2)); if (peakDB > 0) clip = true; const float time = (Time::getMillisecondCounter() / 1000.0f); if (getLevel() < peakDB) { peakLevel = peakDB; peakTime = time; } } float LevelTracker::getLevel() { const float hold = 50.0f / 1000.0f; const float elapsed = (Time::getMillisecondCounter() / 1000.0f) - peakTime; if (elapsed < hold) return peakLevel; return peakLevel - (decayRate * (elapsed - hold)); } int versionStringToInt (const String& versionString) { StringArray parts; parts.addTokens (versionString, ".", ""); parts.trim(); parts.removeEmptyStrings(); int res = 0; for (auto part : parts) res = (res << 8) + part.getIntValue(); return res; }
24.694915
84
0.59849
FigBug
d0a5cbdbef2939103c237028f888b0bd3fe9c230
10,566
hpp
C++
generic_ext/comm_tool_scatter.hpp
Tokumasu-Lab/md_fdps
eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff
[ "MIT" ]
null
null
null
generic_ext/comm_tool_scatter.hpp
Tokumasu-Lab/md_fdps
eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff
[ "MIT" ]
null
null
null
generic_ext/comm_tool_scatter.hpp
Tokumasu-Lab/md_fdps
eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff
[ "MIT" ]
null
null
null
/**************************************************************************************************/ /** * @file comm_tool_scatter.hpp * @brief STL container wrapper for PS::Comm::scatter() */ /**************************************************************************************************/ #pragma once #include <cassert> #include <vector> #include <string> #include <tuple> #include <utility> #include <unordered_map> #include <particle_simulator.hpp> #include "comm_tool_SerDes.hpp" namespace COMM_TOOL { //===================== // wrapper functions //===================== /** * @brief wrapper for static size class. * @param[in] send_vec send target. * MUST NOT contain pointer member. * @param[out] recv_data recieve data. * @details send_vec[i] is send data to process rank i. */ template <class T> void scatter(const std::vector<T> &send_vec, T &recv_data, const PS::S32 root , MPI_Comm comm = MPI_COMM_WORLD){ #ifdef DEBUG_COMM_TOOL if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::vector<T>>" << std::endl; #endif const int n_proc = PS::Comm::getNumberOfProc(); assert(send_vec.size() >= static_cast<size_t>(n_proc)); assert(0 <= root && root < n_proc); #ifdef PARTICLE_SIMULATOR_MPI_PARALLEL MPI_Scatter(&send_vec[0], 1, PS::GetDataType<T>(), &recv_data , 1, PS::GetDataType<T>(), root, comm); #else recv_data = send_vec[0]; #endif } /** * @brief specialization for std::vector<T>. * @param[in] send_vec_vec send target. * MUST NOT contain pointer member. * @param[out] recv_vec recieve data. * @details send_vec_vec[i] is send data to process rank i. */ template <class T> void scatter(const std::vector<std::vector<T>> &send_vec_vec, std::vector<T> &recv_vec, const PS::S32 root, MPI_Comm comm = MPI_COMM_WORLD){ #ifdef DEBUG_COMM_TOOL if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::vector<std::vector<T>>>" << std::endl; #endif const PS::S32 n_proc = PS::Comm::getNumberOfProc(); assert(send_vec_vec.size() >= static_cast<size_t>(n_proc)); assert(0 <= root && root < n_proc); #ifdef PARTICLE_SIMULATOR_MPI_PARALLEL std::vector<PS::S32> n_send; n_send.resize(n_proc); for(PS::S32 i=0; i<n_proc; ++i){ n_send[i] = send_vec_vec[i].size(); } PS::S32 n_recv; scatter(n_send, n_recv, root); recv_vec.resize(n_recv); std::vector<T> send_data; std::vector<PS::S32> n_send_disp; serialize_vector_vector(send_vec_vec, send_data, n_send_disp); MPI_Scatterv(&send_data[0], &n_send[0], &n_send_disp[0], PS::GetDataType<T>(), &recv_vec[0] , n_recv , PS::GetDataType<T>(), root, comm); #else recv_vec.resize(1); recv_vec[0] = send_vec_vec[0]; #endif } /** * @brief specialization for std::string. * @param[in] send_vec_str send target. * @param[out] recv_str recieve data. * @details send_vec_str[i] is send data to process rank i. */ void scatter(const std::vector<std::string> &send_vec_str, std::string &recv_str, const PS::S32 root, MPI_Comm comm = MPI_COMM_WORLD){ #ifdef DEBUG_COMM_TOOL if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::vector<std::string>>>" << std::endl; #endif const PS::S32 n_proc = PS::Comm::getNumberOfProc(); assert(send_vec_str.size() >= static_cast<size_t>(n_proc)); assert(0 <= root && root < n_proc); std::vector<std::vector<char>> send_vec_vec_char; std::vector<char> recv_vec_char; send_vec_vec_char.resize(n_proc); for(PS::S32 i=0; i<n_proc; ++i){ serialize_string(send_vec_str[i], send_vec_vec_char[i]); } scatter(send_vec_vec_char, recv_vec_char, root, comm); deserialize_string(recv_vec_char, recv_str); } /** * @brief specialization for std::vector<std::string>. * @param[in] send_vec_vec_str send target. * @param[out] recv_vec_str recieve data. * @details send_vec_vec_str[i] is send data to process rank i. */ void scatter(const std::vector<std::vector<std::string>> &send_vec_vec_str, std::vector<std::string> &recv_vec_str, const PS::S32 root, MPI_Comm comm = MPI_COMM_WORLD){ #ifdef DEBUG_COMM_TOOL if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::std::vector<vector<std::string>>>" << std::endl; #endif const PS::S32 n_proc = PS::Comm::getNumberOfProc(); assert(send_vec_vec_str.size() >= static_cast<size_t>(n_proc)); assert(0 <= root && root < n_proc); std::vector<std::vector<char>> send_vec_vec_char; std::vector<char> recv_vec_char; send_vec_vec_char.resize(n_proc); for(PS::S32 i=0; i<n_proc; ++i){ serialize_vector_string(send_vec_vec_str[i], send_vec_vec_char[i]); } scatter(send_vec_vec_char, recv_vec_char, root, comm); deserialize_vector_string(recv_vec_char, recv_vec_str); } /** * @brief specialization for std::vector<std::vector<T>>. * @param[in] send_vec_vv send target. * MUST NOT contain pointer member. * @param[out] recv_vec_v recieve data. * @details send_vec_vec_str[i] is send data to process rank i. * @details devide std::vector<std::vector<T>> into std::vector<T> and std::vector<index>, then call scatterV() for std::vector<>. * @details class T accepts std::vector<>, std::string, or user-defined class WITHOUT pointer member. * @details If 4 or more nested std::vector<...> is passed, this function will call itself recurcively. */ template <class T> void scatter(const std::vector<std::vector<std::vector<T>>> &send_vec_vv, std::vector<std::vector<T>> &recv_vec_v, const PS::S32 root, MPI_Comm comm = MPI_COMM_WORLD){ #ifdef DEBUG_COMM_TOOL if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::vector<std::vector<std::vector<T>>>>" << std::endl; #endif const PS::S32 n_proc = PS::Comm::getNumberOfProc(); assert(send_vec_vv.size() >= static_cast<size_t>(n_proc)); assert(0 <= root && root < n_proc); std::vector<std::vector<T>> send_data; std::vector<std::vector<size_t>> send_index; send_data.resize(n_proc); send_index.resize(n_proc); for(PS::S32 i=0; i<n_proc; ++i){ serialize_vector_vector(send_vec_vv[i], send_data[i], send_index[i]); } std::vector<T> recv_data; std::vector<size_t> recv_index; scatter(send_data, recv_data , root, comm); scatter(send_index, recv_index, root, comm); deserialize_vector_vector(recv_data, recv_index, recv_vec_v ); } /** * @brief specialization for std::vector<std::pair<Ta, Tb>>. * @param[in] send_vec_vp send target. * MUST NOT contain pointer member. * @param[out] recv_vec_pair recieve data. * @details send_vec_vec_str[i] is send data to process rank i. * @details devide std::vector<std::pair<Ta, Tb>> into std::vector<Ta> and std::vector<Tb>, then call scatterV() for std::vector<T>. * @details class Ta and Tb accept std::vector<>, std::string, or user-defined class WITHOUT pointer member. */ template <class Ta, class Tb> void scatter(const std::vector<std::vector<std::pair<Ta, Tb>>> &send_vec_vp, std::vector<std::pair<Ta, Tb>> &recv_vec_pair, const PS::S32 root, MPI_Comm comm = MPI_COMM_WORLD){ #ifdef DEBUG_COMM_TOOL if(PS::Comm::getRank() == 0 ) std::cout << " *** scatter_<std::vector<std::vector<std::pair<Ta, Tb>>>>" << std::endl; #endif const PS::S32 n_proc = PS::Comm::getNumberOfProc(); assert(send_vec_vp.size() >= static_cast<size_t>(n_proc)); assert(0 <= root && root < n_proc); std::vector<std::vector<Ta>> send_vec_1st; std::vector<std::vector<Tb>> send_vec_2nd; send_vec_1st.resize(n_proc); send_vec_2nd.resize(n_proc); for(PS::S32 i=0; i<n_proc; ++i){ split_vector_pair(send_vec_vp[i], send_vec_1st[i], send_vec_2nd[i]); } std::vector<Ta> recv_vec_1st; std::vector<Tb> recv_vec_2nd; scatter(send_vec_1st, recv_vec_1st, root, comm); scatter(send_vec_2nd, recv_vec_2nd, root, comm); combine_vector_pair(recv_vec_1st, recv_vec_2nd, recv_vec_pair ); } /** * @brief specialization for returning type interface. * @param[in] send_vec send target. * @return recv_vec recieved data. * @detail wrapper for the use case: "auto recv_vec = COMM_TOOL::allToAll(vec);" * @detail recv_vec.size() = PS::Comm::getNumberOfProc(); * @detail send/recv_vec[i] is send/recieve data to/from process i. */ template <class T> T scatter(const std::vector<T> &send_vec, const PS::S32 root, MPI_Comm comm = MPI_COMM_WORLD){ T recv_data; scatter(send_vec, recv_data, root, comm); return recv_data; } }
39.27881
138
0.530475
Tokumasu-Lab
d0a772d51042d726237c37e9f95db81912eb93f5
382
cpp
C++
acm/contest/7.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
acm/contest/7.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
acm/contest/7.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <map> using namespace std; int main(int argc, char const *argv[]){ int a,b; cin>>a>>b; map<int,int> mp; for(int i=1;i<=b;i++){ for(int j=(a/i)*i;j<=b;j+=i){ mp[j]+=i; } } long long int sum=0; for(int i=a;i<=b;i++){ //cout<<i<<endl; sum+=mp[i]; } cout<<sum<<endl; return 0; }
15.916667
39
0.575916
AadityaJ
d0a868938d64c864bda8abfd03170595f625ed70
2,468
cpp
C++
moai/src/moaicore/MOAICollisionShape.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
moai/src/moaicore/MOAICollisionShape.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
moai/src/moaicore/MOAICollisionShape.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moaicore/MOAICollisionShape.h> //================================================================// // MOAICollisionShape //================================================================// //----------------------------------------------------------------// const USRect& MOAICollisionShape::GetRect () const { return *( USRect* )this->mRectBuffer; } //----------------------------------------------------------------// const USQuad& MOAICollisionShape::GetQuad () const { return *( USQuad* )this->mQuadBuffer; } //----------------------------------------------------------------// MOAICollisionShape::MOAICollisionShape () : mType ( NONE ) { } //----------------------------------------------------------------// MOAICollisionShape::~MOAICollisionShape () { } //----------------------------------------------------------------// bool MOAICollisionShape::Overlap ( const MOAICollisionShape& shape ) const { switch ( this->mType ) { case RECT: { switch ( shape.mType ) { case RECT: MOAICollisionShape::Overlap ( this->GetRect (), shape.GetRect ()); case QUAD: MOAICollisionShape::Overlap ( shape.GetQuad (), this->GetRect ()); } break; } case QUAD: { switch ( shape.mType ) { case RECT: MOAICollisionShape::Overlap ( this->GetQuad (), shape.GetRect ()); case QUAD: MOAICollisionShape::Overlap ( this->GetQuad (), shape.GetQuad ()); } break; } } return false; } //----------------------------------------------------------------// void MOAICollisionShape::Set ( const USRect& rect ) { memcpy ( this->mRectBuffer, &rect, sizeof ( USRect )); this->mType = RECT; } //----------------------------------------------------------------// void MOAICollisionShape::Set ( const USQuad& quad ) { memcpy ( this->mQuadBuffer, &quad, sizeof ( USQuad )); this->mType = QUAD; } //----------------------------------------------------------------// bool MOAICollisionShape::Overlap ( const USRect& s0, const USRect& s1 ) { return s0.Overlap ( s1 ); } //----------------------------------------------------------------// bool MOAICollisionShape::Overlap ( const USQuad& s0, const USRect& s1 ) { return s0.Overlap ( s1 ); } //----------------------------------------------------------------// bool MOAICollisionShape::Overlap ( const USQuad& s0, const USQuad& s1 ) { return s0.Overlap ( s1 ); }
29.035294
81
0.449757
jjimenezg93
d0a96f7199b16477408266572e239c0516121321
11,031
cpp
C++
data/8.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/8.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/8.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
int o3At,E7 ,NPTt ,yQV,oY ,rs3s//oDd , BJfEsB ,klq ,Dhv1 //j ,MQ , N2 ,QXu, nn4 , IlemB , MvE,/*vd6V*/ NZ ,X , nuYH, zAc,rwvjkO//U1Rd //k , WPltg ,Zd,AL , qndos , //GA26v IDDAh6, A ,/*zM72*/Po4hp , /*Q*/EaG, Y5ia , kH , LybZ , Af3M, l/*sV*/ , D2Rch, BhdS //Js3H , YeG ,Xc,yjc0 , Ou , Cj , H5X ,U56 ,acD9 , T1x;void f_f0(){ { return /*p3S*/ ;{ int i; volatile int Fg , W5w ,lToU6 ;; { { }return ; } { {} {} }i = lToU6 +Fg+ W5w;{{ } }} //ko return ; {//7P0 { if(true) { {/*B*/ for(int i=1; i<1 ;++i){ } if ( true ) ;//Bi else if (true) ;else return ; {} } } else if ( true); else return ; };/**/for (int i=1 /*r*/; i< /*jl*/ 2 ;++i ) return ;}}{ return ;return ;//AMKH { volatile int rT5x ,vDP , mVd ; ;return ; T1x = mVd /*n4*/+rT5x + vDP;for(int i=1 //4b ; i< 3 ;++i ){ {} ; if(true )//pCn for(int i=1 ;i< 4 ;++i )for (int i=1 ; i< 5 ;++i) {{ } } else { {volatile int I ; o3At/*YaI8Xv*/ = I ; }{ }} } /*fx*/return ; if//xh0 (true)for (int i=1 ; i<6 ;++i ){volatile int F ,xE , QbkA , /*2*/jfkY /**/ , D0 ; if ( true) //MA E7 =//3Z D0+F ;/*fI9*/ else {{ }} {if ( true)for (int i=1 ;i< 7;++i/*7X9*/){} else {if ( true){ } else{ } } return ; }if ( true) NPTt = xE +QbkA+ jfkY ;/*82*/ else { volatile int eWN ; if( true ){} else for (int i=1 ;i<8 ;++i /*Lfi*/ ) yQV = eWN;{/*9*/ /*RIp*/ return ; return ; }}}else for(int i=1 ; i< 9 ;++i ) {{ if ( true)return //uK ; else/*y3b*/{ return ; return ;{ } } } } }{// for//e9u (int i=1 ; i< 10 /*3*/;++i){{ }} ; return ; ; } for (int i=1; i< 11 ;++i )for(int i=1; // i<12 ;++i//eZ5X ) for(int i=1;//19 i< 13//P ;++i) return ;{ {for(int i=1; i<14;++i )//xl { }if ( true ) if ( true/*hPVN*/ ) { {{ {}} } for(int //RIRL i=1 ; i< 15 ;++i)/*I3rN*/for (int i=1/*zP8*/ ; i< 16 ;++i//CB ) {}} else{ { }}else return ;if(/*c*/true ) { for (int i=1;i< 17 ;++i //An )return ; } else ; } { { }{ } }//w4lI { ;{{ } } }{ {for (int i=1 ;//Z i< 18/*N*/ ;++i ) if/*SL541*/ ( true) { } else return ; }/*wm6u*/ }/*7qn*/} for (int i=1; i< 19;++i)return ; }return ; {int ijAAj ; volatile int WPm//7 , XHP, RNDRGW, jq , C2Lp ; return ; ijAAj =C2Lp + WPm /*ckky7ku*/ + XHP+ RNDRGW+ jq ; ; ; } {return ; { { { {} return ; } }; { { } }}/*nPu*/{ ;{ /*uU*/if ( true ) { }else{{} }/**/ { }} } { { { } }return ; } } {{ {volatile int hcV9 , Y1gs ,PBV8; oY = //NB PBV8 + hcV9+Y1gs ; }{ {}/*E*/} }return ; {{{ int//b3 /*L*/ RUCN ; volatile int Oxy , n7p6, Awts ; rs3s= Awts //FX //sGB ;if(true ) {//ZCJYE } else ; RUCN =Oxy +n7p6 ;/*Th*/} { } }return/*pt*/ ; //o }/*p1R*///N6mEx { int/*7cT*/ MszV;volatile int bd,S, c69 , AtSz , xPS, c ,Vz4PJl //ojm , f; return ; MszV= f + bd +S + c69// ;BJfEsB= AtSz +xPS+ c + Vz4PJl ; } { int wf61//4y ;volatile int lO3pP ,c1et , pyJ ,zK8aV , Pl;for(int /*81u*/i=1; i< 20 ;++i) { { return ;} } wf61= Pl +// lO3pP /*xP*/ + c1et+ pyJ +zK8aV ; } } ;return ;}void f_f1 (){{volatile int ZZfji ,XB,tBA0, /**/nAc9Fl, YmdvYb ;//R { {volatile int Pqh , iDHe/*R8*/ ;if (true) { volatile int DrsB , C2Xsp ;return ;for (int i=1; i< 21;++i ) if ( true/*UvmY*/) klq= C2Xsp;else //TSX {}/*HX*/for(int i=1 ; i< 22 ;++i ) Dhv1 =DrsB//g8 ;} else MQ= iDHe+ Pqh ; for (int i=1 ; i</*n*/ 23;++i)return ;} for (int i=1; i< 24 ;++i) if( true ) {//xBSHD { int t11 ;volatile int Iso, pOv ;; t11 =pOv+ Iso ; } { } if (true )return ; else for (int i=1 ;i< 25 ;++i) return ; {volatile int eAmsTj /*uO*/, m ; N2 = m +//8G eAmsTj ;} }else if ( true){ return ; }else {{ } } {{volatile int VwMH, LwoBQ; { } if( true ){}else{ } QXu = LwoBQ +VwMH ; } {} { { }}} }if( true )nn4=YmdvYb +ZZfji +XB +tBA0+ nAc9Fl// /*u1*/ ; else ; { int VnvtQ/*5*/; volatile int oPy , IGo , ZXdSTf, YF7 , U ; ; { for (int i=1 ; i< 26//yU // ;++i ){} { for(int i=1; i< 27;++i){ } // }; {/*r*/{ } { }//d }/*BIv*/ }for (int i=1 ; // i< 28 ;++i)VnvtQ =U// + oPy +IGo +ZXdSTf + YF7 ;{ { int X3QW ;// volatile int//LRJ BlJ2; X3QW =BlJ2 ; } {//2 { }} ;} } }; if ( true) ;else if ( true) ; else//WJXBO { volatile int DdCe, Tqy , b ,lKv ;IlemB =lKv +DdCe+Tqy +//ni b/*AVH*/; {for(int i=1/*8*/;i< 29;++i) for (int i=1 ;i<30 ;++i ){volatile int F1Mo , cpS ;{{ { } {//pAT } }{ } }for(int i=1;i< 31;++i)if( true ){ }else MvE= cpS +F1Mo ; {for(int i=1 ;i<32 ;++i ){}} }{return ; }if(// true) return //H ;else return/*y*/ ; }{ //e5 for(int i=1/*C*/ ; i<33 ;++i) for(int i=1 ; i<34 ;++i ) {{ { }} }{ {volatile int Ts,/*X5*/k ,b2H;NZ =b2H/*Ak*/+Ts+k; } for (int i=1 ;i< 35/*5O*/;++i// )return ; }/**/ } }//g4 {volatile int RYA, uKzkd, QMnE//DtS , Ug, KlKD ; X = KlKD + RYA +uKzkd +QMnE+ Ug;{return ; {int RqXp, G//M /*n*/;volatile int tlVrU , ee1Aiv, iB , yN8,KX6,WX; {return ; } { }G = WX+tlVrU+ ee1Aiv;if(true /*M*/)return ;else RqXp//Vx = iB + yN8+ KX6 ;}} ; } return//AQ9 ;/*sm*/ } void f_f2 () { { {volatile int B7X,L ,Qz, suiWl, NfyD , D1YwZ, jfw ;nuYH=jfw+ B7X +//wJ L + Qz; ; if (true/**/ ); else {int K8wm6PvOr; volatile int tIR, Nfe , nV7E ; ; {volatile int Ouc , C1// ,hYIh;zAc=hYIh+ Ouc+ C1;}{ return ;//dF } {{ } ;{}} if( true ) K8wm6PvOr=nV7E//K7 +tIR/*e*/+ Nfe ;else{ }}if( true) ; else rwvjkO=//Vule suiWl + NfyD+D1YwZ ; } {for (int i=1 ; i< 36;++i ){ {int U9fH; volatile int Q ,JWM, s, /**/vKur ;U9fH =vKur; WPltg//NL = Q+ JWM + s; }/*P*/{ int J;/*zh4*/volatile int pWs, S7 ; if(true ) {}else J= S7 +pWs ; for(int i=1 ;i< 37;++i ) {} } }{/**/int oSx ;volatile int t5i,q , NPl ;;oSx =NPl//5K + t5i+ q ; } /*sDlQAB*/ { { ;}}} return ; return ;{ { volatile int BE9/*lMk*/ ,dVyi; {/*UNh*/int rgxvY/*K*/;volatile int siA , ep;//lU1m if (true/*3T*/) // rgxvY = ep + siA /*5rS*/;else{/*w3*/}{} } { if (//3 true ) {} else ;}//4H1 if(/*sHc1*/true ) for (int i=1 ; i</*TMH*/38 ;++i)Zd =dVyi//l1 +BE9 ; else {}} {{{/*yOWzu*///nf if ( true ) //QNA ; else return ; } } {int zQS ; volatile int Lb/**///1 ,OqtQ , /*P6N*/E ; for /*BsMT*/(int i=1 ;i<39 ;++i ) zQS=E +Lb + //BCqz OqtQ;}} } { { {}/**/for//FIyY8 (int i=1 ; i< 40 ;++i ){{ } {}} }//xs {//FB6 int lU ; volatile int nt , xxTB ,ua3j; lU= ua3j + nt +xxTB;}}if ( true ) { { volatile int ipt, kF5,AthL ; AL = AthL + ipt +kF5 ;{/*3Rf*//*WYdw*/int /*X*/ fm ; volatile int D ,Jb ; { // }fm= //AJTy Jb+ D;{ //RZs } }}//h for(int i=1 ;i<41 ;++i) {//8J volatile int Tz//H ,e7GZ, KFx ; if ( true){ { return ; } //TJP }else if( true) qndos=KFx + Tz+e7GZ; else if (true )for(int i=1 ;i<42 ;++i ) return ; else//R {}}for(int i=1; i<43 ;++i ) { volatile int XHk, JXgy , v ;if( true ) //K IDDAh6= v/**/ + XHk +JXgy ; else ;}{ //7 { { } } } { ;} } /*ge*/else ;return ;}; { volatile int NivH ,ZMLP ,eLS,mRL /**/; { volatile int f8b, nk , mN7 ;{ volatile int cTVv, UaT , dQTe; ; {return ;{/**/} } if (true) { }else A =dQTe+cTVv + UaT ;; }Po4hp =mN7 /*hL*/+f8b + nk ; { ;} } { { if ( true) { } else{; /*W*/} ; }{; } { { volatile int vd ; for (int i=1 /*pf*/;i<44 /*1*///HT9 ;++i ) EaG = /*KFt*/vd;}//wF {} } } Y5ia= mRL+ NivH + /*3p6*/ZMLP+ eLS;for(int i=1; i< 45//1lRf ;++i )for /*wat*/ (int i=1 ;i<46 ;++i) for(int i=1; i< 47 ;++i ) return ;//YzC } {volatile int h6 /*ux*/,G4B, yTc , C , FRz,buDo ,Tw,fuJ , v4k ,C6N , A7//W8p ,aoy ,//h1 R, tH//Z4A ,vA , zrR6 ,WClLw , PFb;if( true )if (true) { { return ; }{{ } } {if ( //L true ){ } else for (int i=1; i< /*w*/48 /*b*/;++i) /*u*/{} { } } }else{ { {; } } return ;/*2v*/ }else kH = PFb+ /*hE*/h6+/**/G4B+ yTc+ C +FRz+ buDo ;/*ZPf*/if//r4 ( true) ; else if( true)// LybZ=Tw+// fuJ +v4k+C6N+/*pkHS*/ A7 /*w4*/ ; else return ; Af3M= aoy+R + tH+ vA + zrR6+WClLw; return ;{return//lF ; {{}{return ; {} for (int i=1 ; i< 49;++i )/*x*/{ for (int //SoTD i=1; i< 50;++i )/*g*/{} } }}}}/*KC9*//*VMFkM*/return ; }int main () { volatile int// QPW , tW8, /*21*/bt ,R7 , DMK ,xg , Y4, q8 ,lRMo3I,yXh , i2;if ( true /*ce*/) for (int i=1 ; i<51;++i ) l=/*8Xo*/i2 +QPW +tW8+//0iOQ bt + R7 + DMK; else { {//g3t return 1251288111 ; for (int i=1; i<52 ;++i){ for (int /*SC*/i=1 ;i<53;++i ) ; ;} if (true ) { { return 867038002; {/*pLW*/}//PhT }//2 /**/if(true) {}else{{ } }} else ; } { { {} } for (int i=1 ; i<//9E 54 ;++i ){{} ;}{ int tke ;volatile int Bmi,FLksQ , M9 , //CU kp//c ,/*uxU*/uN; { volatile int z ,yRM ,F3 ; D2Rch= F3+ z +yRM; { }} BhdS=uN + Bmi; if//r (true )//Lw { }else tke = FLksQ +M9+ kp;}} {volatile int iVf/*ms*/ , b2 ,Jt5Z ;YeG = Jt5Z+iVf+b2 ; ; } { for (int i=1 ; i<55 ;++i) { return//K 1765747176 ; return 2062316704; /*eHW*/ }if (true) //p return 808082939 ;else { { }{ } {{{ }{ }} } for//JQ (int i=1/**/; i< 56;++i ) {} }return // 384502502;;/*hC*/ } ; } Xc= /*oJ*/ xg+ Y4+ q8 + lRMo3I + /*88*/yXh /*SevI*/;{ return 1867852740; {{{ int X6 ;volatile int peuQ,y; for (int i=1 ; i<57;++i) X6 = y +peuQ ;} { } }{ {{}{ }}} { ;{if (true ) return 1081798268 ; else { } } { { ;}{ } } {for (int i=1 ; i<58;++i )for (int i=1 ; i< 59 ;++i) ;{for(int i=1/**/ ; i< 60 ;++i) { /*vSEM*/}}}if//abvS ( true) return 943161846;else ; } } return 1239660351; } return 608054594 ; {volatile int Ri6 ,//2NY FB , bvo , sa ; { { { {}} return/*PN*/ 786909423 ; /**/if(//3H /*G*/true) for(int i=1; i<61 /*ri*/;++i ) for (int i=1; i< 62 //Ff ;++i ) for (int i=1 //t ; i< 63/*rZV*/ ;++i ) {{ }} else //ci { volatile int t9Cf, dxd; { } //5 { }yjc0 = dxd +t9Cf; }}//te if( true ) if( true ) { {volatile int pw /**/, AILt;Ou = AILt+pw;} } else{ return 1955638066;{ } {//UT return 1293742239; } if ( true ) {{ {}} //w } else// ;}/*h*/else { { ; return 1814964128 ; } { }{ return 75363636 ; } { //06 } }};Cj = sa +Ri6+ FB + bvo/*FY*/ ;//i ; } if ( true) {return 1257669817 ; { { volatile int d30, c3BBm ; H5X= c3BBm + d30 ;};/*Tl*/ {for (int i=1; i< 64;++i){}return 1661774657 ; } }for //Q (int i=1;i< 65;++i) return 1603901541 ; } else { volatile int Zv,mR,GlG, qm1, AzQ,Hd5uA;//50W for (int i=1 //eq ;i<66/*d989*/ //Kfz ;++i//jm ) U56 = Hd5uA/**/ +Zv/*h*/+mR + GlG + qm1 + AzQ ;if ( true ){int Xd6 ;volatile int NyA , g , nw8S, hUhGd ; { { }} { for (int i=1 ; i<67 ;++i/*a*/) {} { {/*7QKx*/ } {//R /*CF2*/ } } }if ( true){{volatile int ZLfk ,Udyu , Z8sh; {} acD9 =//R1q4C7 Z8sh + ZLfk +Udyu; { } /*lZE*/;{ } }/*Tt*/}else//fa8 Xd6 //ldaj /*Ja*/ = hUhGd + NyA +//4f g+nw8S; }else{ ; /*Eh*/{ {{}} }} for (int i=1 ;i< 68 ;++i) { ; { {for (int i=1; i<69 ;++i ) {}}{ } {// }}}/**/} }
10.987052
76
0.458526
TianyiChen
d0af510f34f2f8a51519428af0ce2e5d1278127b
12,282
cpp
C++
src/lib/utils/meta_table_manager.cpp
nannancy/hyrise
a22d270b0692a24605fe02937cbd070ee4b8ebcb
[ "MIT" ]
null
null
null
src/lib/utils/meta_table_manager.cpp
nannancy/hyrise
a22d270b0692a24605fe02937cbd070ee4b8ebcb
[ "MIT" ]
11
2019-12-02T20:47:52.000Z
2020-02-04T23:19:31.000Z
src/lib/utils/meta_table_manager.cpp
nannancy/hyrise
a22d270b0692a24605fe02937cbd070ee4b8ebcb
[ "MIT" ]
null
null
null
#include "meta_table_manager.hpp" #include "constant_mappings.hpp" #include "hyrise.hpp" #include "resolve_type.hpp" #include "statistics/table_statistics.hpp" #include "storage/base_encoded_segment.hpp" #include "storage/dictionary_segment.hpp" #include "storage/fixed_string_dictionary_segment.hpp" #include "storage/segment_iterables/any_segment_iterable.hpp" #include "storage/table.hpp" #include "storage/table_column_definition.hpp" namespace { using namespace opossum; // NOLINT // TODO(anyone): #1968 introduced this namespace. With the expected growth of the meta table manager of time, there // might be a large number of helper function that are only loosely related to the core functionality // of the MetaTableManager. If this becomes the case, restructure and move the functions to other files. size_t get_distinct_value_count(const std::shared_ptr<BaseSegment>& segment) { auto distinct_value_count = size_t{0}; resolve_data_type(segment->data_type(), [&](auto type) { using ColumnDataType = typename decltype(type)::type; // For dictionary segments, an early (and much faster) exit is possible by using the dictionary size if (const auto dictionary_segment = std::dynamic_pointer_cast<const DictionarySegment<ColumnDataType>>(segment)) { distinct_value_count = dictionary_segment->dictionary()->size(); return; } else if (const auto fs_dictionary_segment = std::dynamic_pointer_cast<const FixedStringDictionarySegment<pmr_string>>(segment)) { distinct_value_count = fs_dictionary_segment->fixed_string_dictionary()->size(); return; } std::unordered_set<ColumnDataType> distinct_values; auto iterable = create_any_segment_iterable<ColumnDataType>(*segment); iterable.with_iterators([&](auto it, auto end) { for (; it != end; ++it) { const auto segment_item = *it; if (!segment_item.is_null()) { distinct_values.insert(segment_item.value()); } } }); distinct_value_count = distinct_values.size(); }); return distinct_value_count; } auto gather_segment_meta_data(const std::shared_ptr<Table>& meta_table, const MemoryUsageCalculationMode mode) { for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) { for (auto chunk_id = ChunkID{0}; chunk_id < table->chunk_count(); ++chunk_id) { for (auto column_id = ColumnID{0}; column_id < table->column_count(); ++column_id) { const auto& chunk = table->get_chunk(chunk_id); const auto& segment = chunk->get_segment(column_id); const auto data_type = pmr_string{data_type_to_string.left.at(table->column_data_type(column_id))}; const auto estimated_size = segment->memory_usage(mode); AllTypeVariant encoding = NULL_VALUE; AllTypeVariant vector_compression = NULL_VALUE; if (const auto& encoded_segment = std::dynamic_pointer_cast<BaseEncodedSegment>(segment)) { encoding = pmr_string{encoding_type_to_string.left.at(encoded_segment->encoding_type())}; if (encoded_segment->compressed_vector_type()) { std::stringstream ss; ss << *encoded_segment->compressed_vector_type(); vector_compression = pmr_string{ss.str()}; } } if (mode == MemoryUsageCalculationMode::Full) { const auto distinct_value_count = static_cast<int64_t>(get_distinct_value_count(segment)); meta_table->append({pmr_string{table_name}, static_cast<int32_t>(chunk_id), static_cast<int32_t>(column_id), pmr_string{table->column_name(column_id)}, data_type, distinct_value_count, encoding, vector_compression, static_cast<int64_t>(estimated_size)}); } else { meta_table->append({pmr_string{table_name}, static_cast<int32_t>(chunk_id), static_cast<int32_t>(column_id), pmr_string{table->column_name(column_id)}, data_type, encoding, vector_compression, static_cast<int64_t>(estimated_size)}); } } } } } } // namespace namespace opossum { MetaTableManager::MetaTableManager() { _methods["tables"] = &MetaTableManager::generate_tables_table; _methods["columns"] = &MetaTableManager::generate_columns_table; _methods["chunks"] = &MetaTableManager::generate_chunks_table; _methods["chunk_sort_orders"] = &MetaTableManager::generate_chunk_sort_orders_table; _methods["segments"] = &MetaTableManager::generate_segments_table; _methods["segments_accurate"] = &MetaTableManager::generate_accurate_segments_table; _table_names.reserve(_methods.size()); for (const auto& [table_name, _] : _methods) { _table_names.emplace_back(table_name); } std::sort(_table_names.begin(), _table_names.end()); } const std::vector<std::string>& MetaTableManager::table_names() const { return _table_names; } std::shared_ptr<Table> MetaTableManager::generate_table(const std::string& table_name) const { const auto table = _methods.at(table_name)(); table->set_table_statistics(TableStatistics::from_table(*table)); return table; } std::shared_ptr<Table> MetaTableManager::generate_tables_table() { const auto columns = TableColumnDefinitions{{"table_name", DataType::String, false}, {"column_count", DataType::Int, false}, {"row_count", DataType::Long, false}, {"chunk_count", DataType::Int, false}, {"max_chunk_size", DataType::Long, false}}; auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes); for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) { output_table->append({pmr_string{table_name}, static_cast<int32_t>(table->column_count()), static_cast<int64_t>(table->row_count()), static_cast<int32_t>(table->chunk_count()), static_cast<int64_t>(table->max_chunk_size())}); } return output_table; } std::shared_ptr<Table> MetaTableManager::generate_columns_table() { const auto columns = TableColumnDefinitions{{"table_name", DataType::String, false}, {"column_name", DataType::String, false}, {"data_type", DataType::String, false}, {"nullable", DataType::Int, false}}; auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes); for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) { for (auto column_id = ColumnID{0}; column_id < table->column_count(); ++column_id) { output_table->append({pmr_string{table_name}, static_cast<pmr_string>(table->column_name(column_id)), static_cast<pmr_string>(data_type_to_string.left.at(table->column_data_type(column_id))), static_cast<int32_t>(table->column_is_nullable(column_id))}); } } return output_table; } std::shared_ptr<Table> MetaTableManager::generate_chunks_table() { const auto columns = TableColumnDefinitions{{"table_name", DataType::String, false}, {"chunk_id", DataType::Int, false}, {"row_count", DataType::Long, false}, {"invalid_row_count", DataType::Long, false}, {"cleanup_commit_id", DataType::Long, true}}; auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes); for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) { for (auto chunk_id = ChunkID{0}; chunk_id < table->chunk_count(); ++chunk_id) { const auto& chunk = table->get_chunk(chunk_id); const auto cleanup_commit_id = chunk->get_cleanup_commit_id() ? AllTypeVariant{static_cast<int64_t>(*chunk->get_cleanup_commit_id())} : NULL_VALUE; output_table->append({pmr_string{table_name}, static_cast<int32_t>(chunk_id), static_cast<int64_t>(chunk->size()), static_cast<int64_t>(chunk->invalid_row_count()), cleanup_commit_id}); } } return output_table; } /** * At the moment, each chunk can be sorted by exactly one column or none. Hence, having a column within the chunk table * would be sufficient. However, this will change in the near future (e.g., when a sort-merge join evicts a chunk that * is sorted on two columns). To prepare for this change, this additional table stores the sort orders and allows a * chunk to have multiple sort orders. Cascading sort orders for chunks are currently not planned. */ std::shared_ptr<Table> MetaTableManager::generate_chunk_sort_orders_table() { const auto columns = TableColumnDefinitions{{"table_name", DataType::String, false}, {"chunk_id", DataType::Int, false}, {"column_id", DataType::Int, false}, {"order_mode", DataType::String, false}}; auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes); for (const auto& [table_name, table] : Hyrise::get().storage_manager.tables()) { for (auto chunk_id = ChunkID{0}; chunk_id < table->chunk_count(); ++chunk_id) { const auto& chunk = table->get_chunk(chunk_id); const auto ordered_by = chunk->ordered_by(); if (ordered_by) { std::stringstream order_by_mode_steam; order_by_mode_steam << ordered_by->second; output_table->append({pmr_string{table_name}, static_cast<int32_t>(chunk_id), static_cast<int32_t>(ordered_by->first), pmr_string{order_by_mode_steam.str()}}); } } } return output_table; } std::shared_ptr<Table> MetaTableManager::generate_segments_table() { const auto columns = TableColumnDefinitions{{"table_name", DataType::String, false}, {"chunk_id", DataType::Int, false}, {"column_id", DataType::Int, false}, {"column_name", DataType::String, false}, {"column_data_type", DataType::String, false}, {"encoding_type", DataType::String, true}, {"vector_compression_type", DataType::String, true}, {"estimated_size_in_bytes", DataType::Long, false}}; auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes); gather_segment_meta_data(output_table, MemoryUsageCalculationMode::Sampled); return output_table; } std::shared_ptr<Table> MetaTableManager::generate_accurate_segments_table() { PerformanceWarning("Accurate segment information are expensive to gather. Use with caution."); const auto columns = TableColumnDefinitions{ {"table_name", DataType::String, false}, {"chunk_id", DataType::Int, false}, {"column_id", DataType::Int, false}, {"column_name", DataType::String, false}, {"column_data_type", DataType::String, false}, {"distinct_value_count", DataType::Long, false}, {"encoding_type", DataType::String, true}, {"vector_compression_type", DataType::String, true}, {"size_in_bytes", DataType::Long, false}}; auto output_table = std::make_shared<Table>(columns, TableType::Data, std::nullopt, UseMvcc::Yes); gather_segment_meta_data(output_table, MemoryUsageCalculationMode::Full); return output_table; } bool MetaTableManager::is_meta_table_name(const std::string& name) { const auto prefix_len = META_PREFIX.size(); return name.size() > prefix_len && std::string_view{&name[0], prefix_len} == MetaTableManager::META_PREFIX; } } // namespace opossum
51.605042
120
0.650708
nannancy
d0b11866e091002fc395d58222a1a7109b90bafb
1,588
cpp
C++
aashishgahlawat/codeforces/E/166-E/166-E-32309345.cpp
aashishgahlawat/CompetetiveProgramming
12d6b2682765ae05b622968b9a26b0b519e170aa
[ "MIT" ]
null
null
null
aashishgahlawat/codeforces/E/166-E/166-E-32309345.cpp
aashishgahlawat/CompetetiveProgramming
12d6b2682765ae05b622968b9a26b0b519e170aa
[ "MIT" ]
null
null
null
aashishgahlawat/codeforces/E/166-E/166-E-32309345.cpp
aashishgahlawat/CompetetiveProgramming
12d6b2682765ae05b622968b9a26b0b519e170aa
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define mp make_pair #define pb push_back #define len(a) (int)a.size() #define all(a) (a.begin(),a.end()) #define fi first #define sc second #define ort(x,y) (x+y)/2 #define endl '\n' #define FAST ios_base::sync_with_stdio(false); #define d1(x) cerr<<#x<<":"<<x<<endl; #define d2(x,y) cerr<<#x<<":"<<x<<" "<<#y<<":"<<y<<endl; #define d3(x,y,z) cerr<<#x<<":"<<x<<" "<<#y<<":"<<y<<" "<<#z<<":"<<z<<endl; #define N (int) () #define inf (int) (1e7) #define p (1000000007) #define heap priority_queue #define mem(a,val) memset(a,val,sizeof(a)) #define y1 asdassa typedef long long int lli; typedef pair<int,int> pii; typedef pair<pair<int,int>,int> piii; int n; void multiply(lli F[2][2],lli M[2][2]) { lli R[2][2]={0}; for(int i=0;i<2;i++) for(int j=0;j<2;j++) for(int k=0;k<2;k++) R[i][j]=(R[i][j] + F[i][k] * M[k][j] %p )%p; for(int i=0;i<2;i++) for(int j=0;j<2;j++) F[i][j]=R[i][j]; } void power(lli F[2][2], int n) { if (n == 0 || n == 1) return; lli M[2][2] = {{0,3},{1,2}}; power(F, n / 2);//to lower ones multiply(F, F); if (n % 2 != 0)//odd case one additional multiply(F, M); } lli solve(lli n) { if(n==1) return 0;//no path lli F[2][2] = {{0,3},{1,2}};//why 03 12? what are base cases? //3 cases 1 case and 2 if (n == 0) return 0; power(F, n - 1); return F[0][1];//why not 00 } int main() { cin>>n; printf("%lld\n",solve(n)); } /* https://discuss.codechef.com/questions/116710/codeforces-166e-help-needed-binary-matrix-exponentiation-for-a-begineer */
24.8125
117
0.564232
aashishgahlawat
d0b415cc938c7f9172b5af466464ef30381115a5
35,033
cpp
C++
src/lib/operators/aggregate.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2021-04-14T11:16:52.000Z
2021-04-14T11:16:52.000Z
src/lib/operators/aggregate.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
null
null
null
src/lib/operators/aggregate.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2020-11-30T13:11:04.000Z
2020-11-30T13:11:04.000Z
#include "aggregate.hpp" #include <algorithm> #include <memory> #include <optional> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "constant_mappings.hpp" #include "resolve_type.hpp" #include "scheduler/abstract_task.hpp" #include "scheduler/current_scheduler.hpp" #include "scheduler/job_task.hpp" #include "storage/create_iterable_from_column.hpp" #include "type_comparison.hpp" #include "utils/assert.hpp" namespace opossum { Aggregate::Aggregate(const std::shared_ptr<AbstractOperator>& in, const std::vector<AggregateColumnDefinition>& aggregates, const std::vector<ColumnID>& groupby_column_ids) : AbstractReadOnlyOperator(OperatorType::Aggregate, in), _aggregates(aggregates), _groupby_column_ids(groupby_column_ids) { Assert(!(aggregates.empty() && groupby_column_ids.empty()), "Neither aggregate nor groupby columns have been specified"); } const std::vector<AggregateColumnDefinition>& Aggregate::aggregates() const { return _aggregates; } const std::vector<ColumnID>& Aggregate::groupby_column_ids() const { return _groupby_column_ids; } const std::string Aggregate::name() const { return "Aggregate"; } const std::string Aggregate::description(DescriptionMode description_mode) const { std::stringstream desc; desc << "[Aggregate] GroupBy ColumnIDs: "; for (size_t groupby_column_idx = 0; groupby_column_idx < _groupby_column_ids.size(); ++groupby_column_idx) { desc << _groupby_column_ids[groupby_column_idx]; if (groupby_column_idx + 1 < _groupby_column_ids.size()) { desc << ", "; } } desc << " Aggregates: "; for (size_t expression_idx = 0; expression_idx < _aggregates.size(); ++expression_idx) { const auto& aggregate = _aggregates[expression_idx]; desc << aggregate_function_to_string.left.at(aggregate.function); if (aggregate.column) { desc << "(Column #" << *aggregate.column << ")"; } else { desc << "(*)"; } if (aggregate.alias) { desc << " AS " << *aggregate.alias; } if (expression_idx + 1 < _aggregates.size()) { desc << ", "; } } return desc.str(); } std::shared_ptr<AbstractOperator> Aggregate::_on_recreate( const std::vector<AllParameterVariant>& args, const std::shared_ptr<AbstractOperator>& recreated_input_left, const std::shared_ptr<AbstractOperator>& recreated_input_right) const { return std::make_shared<Aggregate>(recreated_input_left, _aggregates, _groupby_column_ids); } void Aggregate::_on_cleanup() { _contexts_per_column.clear(); _keys_per_chunk.clear(); } /* Visitor context for the partitioning/grouping visitor */ struct GroupByContext : ColumnVisitableContext { GroupByContext(const std::shared_ptr<const Table>& t, ChunkID chunk, ColumnID column, const std::shared_ptr<std::vector<AggregateKey>>& keys) : table_in(t), chunk_id(chunk), column_id(column), hash_keys(keys) {} // constructor for use in ReferenceColumn::visit_dereferenced GroupByContext(const std::shared_ptr<BaseColumn>&, const std::shared_ptr<const Table>& referenced_table, const std::shared_ptr<ColumnVisitableContext>& base_context, ChunkID chunk_id, const std::shared_ptr<std::vector<ChunkOffset>>& chunk_offsets) : table_in(referenced_table), chunk_id(chunk_id), column_id(std::static_pointer_cast<GroupByContext>(base_context)->column_id), hash_keys(std::static_pointer_cast<GroupByContext>(base_context)->hash_keys), chunk_offsets_in(chunk_offsets) {} std::shared_ptr<const Table> table_in; ChunkID chunk_id; const ColumnID column_id; std::shared_ptr<std::vector<AggregateKey>> hash_keys; std::shared_ptr<std::vector<ChunkOffset>> chunk_offsets_in; }; /* Visitor context for the AggregateVisitor. */ template <typename ColumnType, typename AggregateType> struct AggregateContext : ColumnVisitableContext { AggregateContext() = default; explicit AggregateContext(const std::shared_ptr<GroupByContext>& base_context) : groupby_context(base_context) {} // constructor for use in ReferenceColumn::visit_dereferenced AggregateContext(const std::shared_ptr<BaseColumn>&, const std::shared_ptr<const Table>&, const std::shared_ptr<ColumnVisitableContext>& base_context, ChunkID chunk_id, const std::shared_ptr<std::vector<ChunkOffset>>& chunk_offsets) : groupby_context(std::static_pointer_cast<AggregateContext>(base_context)->groupby_context), results(std::static_pointer_cast<AggregateContext>(base_context)->results) { groupby_context->chunk_id = chunk_id; groupby_context->chunk_offsets_in = chunk_offsets; } std::shared_ptr<GroupByContext> groupby_context; std::shared_ptr<std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>, std::hash<AggregateKey>>> results; }; /* The following structs describe the different aggregate traits. Given a ColumnType and AggregateFunction, certain traits like the aggregate type can be deduced. */ template <typename ColumnType, AggregateFunction function, class Enable = void> struct AggregateTraits {}; // COUNT on all types template <typename ColumnType> struct AggregateTraits<ColumnType, AggregateFunction::Count> { using AggregateType = int64_t; static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Long; }; // COUNT(DISTINCT) on all types template <typename ColumnType> struct AggregateTraits<ColumnType, AggregateFunction::CountDistinct> { using AggregateType = int64_t; static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Long; }; // MIN/MAX on all types template <typename ColumnType, AggregateFunction function> struct AggregateTraits< ColumnType, function, typename std::enable_if_t<function == AggregateFunction::Min || function == AggregateFunction::Max, void>> { using AggregateType = ColumnType; static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Null; }; // AVG on arithmetic types template <typename ColumnType, AggregateFunction function> struct AggregateTraits< ColumnType, function, typename std::enable_if_t<function == AggregateFunction::Avg && std::is_arithmetic<ColumnType>::value, void>> { using AggregateType = double; static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Double; }; // SUM on integers template <typename ColumnType, AggregateFunction function> struct AggregateTraits< ColumnType, function, typename std::enable_if_t<function == AggregateFunction::Sum && std::is_integral<ColumnType>::value, void>> { using AggregateType = int64_t; static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Long; }; // SUM on floating point numbers template <typename ColumnType, AggregateFunction function> struct AggregateTraits< ColumnType, function, typename std::enable_if_t<function == AggregateFunction::Sum && std::is_floating_point<ColumnType>::value, void>> { using AggregateType = double; static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Double; }; // invalid: AVG on non-arithmetic types template <typename ColumnType, AggregateFunction function> struct AggregateTraits< ColumnType, function, typename std::enable_if_t<!std::is_arithmetic<ColumnType>::value && (function == AggregateFunction::Avg || function == AggregateFunction::Sum), void>> { using AggregateType = ColumnType; static constexpr DataType AGGREGATE_DATA_TYPE = DataType::Null; }; /* The AggregateFunctionBuilder is used to create the lambda function that will be used by the AggregateVisitor. It is a separate class because methods cannot be partially specialized. Therefore, we partially specialize the whole class and define the get_aggregate_function anew every time. */ template <typename ColumnType, typename AggregateType> using AggregateFunctor = std::function<std::optional<AggregateType>(ColumnType, std::optional<AggregateType>)>; template <typename ColumnType, typename AggregateType, AggregateFunction function> struct AggregateFunctionBuilder { AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() { Fail("Invalid aggregate function"); } }; template <typename ColumnType, typename AggregateType> struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::Min> { AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() { return [](ColumnType new_value, std::optional<AggregateType> current_aggregate) { if (!current_aggregate || value_smaller(new_value, *current_aggregate)) { // New minimum found return new_value; } return *current_aggregate; }; } }; template <typename ColumnType, typename AggregateType> struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::Max> { AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() { return [](ColumnType new_value, std::optional<AggregateType> current_aggregate) { if (!current_aggregate || value_greater(new_value, *current_aggregate)) { // New maximum found return new_value; } return *current_aggregate; }; } }; template <typename ColumnType, typename AggregateType> struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::Sum> { AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() { return [](ColumnType new_value, std::optional<AggregateType> current_aggregate) { // add new value to sum return new_value + (!current_aggregate ? 0 : *current_aggregate); // NOLINT - false positive hicpp-use-nullptr }; } }; template <typename ColumnType, typename AggregateType> struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::Avg> { AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() { return [](ColumnType new_value, std::optional<AggregateType> current_aggregate) { // add new value to sum return new_value + (!current_aggregate ? 0 : *current_aggregate); // NOLINT - false positive hicpp-use-nullptr }; } }; template <typename ColumnType, typename AggregateType> struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::Count> { AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() { return [](ColumnType, std::optional<AggregateType> current_aggregate) { return std::nullopt; }; } }; template <typename ColumnType, typename AggregateType> struct AggregateFunctionBuilder<ColumnType, AggregateType, AggregateFunction::CountDistinct> { AggregateFunctor<ColumnType, AggregateType> get_aggregate_function() { return [](ColumnType, std::optional<AggregateType> current_aggregate) { return std::nullopt; }; } }; template <typename ColumnDataType, AggregateFunction function> void Aggregate::_aggregate_column(ChunkID chunk_id, ColumnID column_index, const BaseColumn& base_column) { using AggregateType = typename AggregateTraits<ColumnDataType, function>::AggregateType; auto aggregator = AggregateFunctionBuilder<ColumnDataType, AggregateType, function>().get_aggregate_function(); auto& context = *std::static_pointer_cast<AggregateContext<ColumnDataType, AggregateType>>(_contexts_per_column[column_index]); auto& results = *context.results; auto& hash_keys = _keys_per_chunk[chunk_id]; resolve_column_type<ColumnDataType>( base_column, [&results, &hash_keys, chunk_id, aggregator](const auto& typed_column) { auto iterable = create_iterable_from_column<ColumnDataType>(typed_column); ChunkOffset chunk_offset{0}; // Now that all relevant types have been resolved, we can iterate over the column and build the aggregations. iterable.for_each([&, chunk_id, aggregator](const auto& value) { results[(*hash_keys)[chunk_offset]].row_id = RowID(chunk_id, chunk_offset); /** * If the value is NULL, the current aggregate value does not change. */ if (!value.is_null()) { // If we have a value, use the aggregator lambda to update the current aggregate value for this group results[(*hash_keys)[chunk_offset]].current_aggregate = aggregator(value.value(), results[(*hash_keys)[chunk_offset]].current_aggregate); // increase value counter ++results[(*hash_keys)[chunk_offset]].aggregate_count; if (function == AggregateFunction::CountDistinct) { // for the case of CountDistinct, insert this value into the set to keep track of distinct values results[(*hash_keys)[chunk_offset]].distinct_values.insert(value.value()); } } ++chunk_offset; }); }); } std::shared_ptr<const Table> Aggregate::_on_execute() { auto input_table = input_table_left(); for ([[maybe_unused]] const auto groupby_column_id : _groupby_column_ids) { DebugAssert(groupby_column_id < input_table->column_count(), "GroupBy column index out of bounds"); } // check for invalid aggregates for (const auto& aggregate : _aggregates) { if (!aggregate.column) { if (aggregate.function != AggregateFunction::Count) { Fail("Aggregate: Asterisk is only valid with COUNT"); } } else { DebugAssert(*aggregate.column < input_table->column_count(), "Aggregate column index out of bounds"); if (input_table->column_data_type(*aggregate.column) == DataType::String && (aggregate.function == AggregateFunction::Sum || aggregate.function == AggregateFunction::Avg)) { Fail("Aggregate: Cannot calculate SUM or AVG on string column"); } } } /* PARTITIONING PHASE First we partition the input chunks by the given group key(s). This is done by creating a vector that contains the AggregateKey for each row. It is gradually built by visitors, one for each group column. */ _keys_per_chunk = std::vector<std::shared_ptr<std::vector<AggregateKey>>>(input_table->chunk_count()); for (ChunkID chunk_id{0}; chunk_id < input_table->chunk_count(); ++chunk_id) { _keys_per_chunk[chunk_id] = std::make_shared<std::vector<AggregateKey>>(input_table->get_chunk(chunk_id)->size(), AggregateKey(_groupby_column_ids.size())); } std::vector<std::shared_ptr<AbstractTask>> jobs; jobs.reserve(_groupby_column_ids.size()); for (size_t group_column_index = 0; group_column_index < _groupby_column_ids.size(); ++group_column_index) { jobs.emplace_back(std::make_shared<JobTask>([&input_table, group_column_index, this]() { const auto column_id = _groupby_column_ids.at(group_column_index); const auto data_type = input_table->column_data_type(column_id); resolve_data_type(data_type, [&](auto type) { using ColumnDataType = typename decltype(type)::type; /* Store unique IDs for equal values in the groupby column (similar to dictionary encoding). The ID 0 is reserved for NULL values. The combined IDs build an AggregateKey for each row. */ auto id_map = std::unordered_map<ColumnDataType, uint64_t>(); uint64_t id_counter = 1u; for (ChunkID chunk_id{0}; chunk_id < input_table->chunk_count(); ++chunk_id) { const auto chunk_in = input_table->get_chunk(chunk_id); const auto base_column = chunk_in->get_column(column_id); resolve_column_type<ColumnDataType>(*base_column, [&](auto& typed_column) { auto iterable = create_iterable_from_column<ColumnDataType>(typed_column); ChunkOffset chunk_offset{0}; iterable.for_each([&](const auto& value) { if (value.is_null()) { (*_keys_per_chunk[chunk_id])[chunk_offset][group_column_index] = 0u; } else { auto inserted = id_map.try_emplace(value.value(), id_counter); // store either the current id_counter or the existing ID of the value (*_keys_per_chunk[chunk_id])[chunk_offset][group_column_index] = inserted.first->second; // if the id_map didn't have the value as a key and a new element was inserted if (inserted.second) ++id_counter; } ++chunk_offset; }); }); } }); })); jobs.back()->schedule(); } CurrentScheduler::wait_for_tasks(jobs); /* AGGREGATION PHASE */ _contexts_per_column = std::vector<std::shared_ptr<ColumnVisitableContext>>(_aggregates.size()); if (_aggregates.empty()) { /* Insert a dummy context for the DISTINCT implementation. That way, _contexts_per_column will always have at least one context with results. This is important later on when we write the group keys into the table. We choose int8_t for column type and aggregate type because it's small. */ auto context = std::make_shared<AggregateContext<DistinctColumnType, DistinctAggregateType>>(); context->results = std::make_shared<std::unordered_map<AggregateKey, AggregateResult<DistinctAggregateType, DistinctColumnType>, std::hash<AggregateKey>>>(); _contexts_per_column.push_back(context); } /** * Create an AggregateContext for each column in the input table that a normal (i.e. non-DISTINCT) aggregate is * created on. We do this here, and not in the per-chunk-loop below, because there might be no Chunks in the input * and _write_aggregate_output() needs these contexts anyway. */ for (ColumnID column_id{0}; column_id < _aggregates.size(); ++column_id) { const auto& aggregate = _aggregates[column_id]; if (!aggregate.column && aggregate.function == AggregateFunction::Count) { // SELECT COUNT(*) - we know the template arguments, so we don't need a visitor auto context = std::make_shared<AggregateContext<CountColumnType, CountAggregateType>>(); context->results = std::make_shared<std::unordered_map<AggregateKey, AggregateResult<CountAggregateType, CountColumnType>, std::hash<AggregateKey>>>(); _contexts_per_column[column_id] = context; continue; } auto data_type = input_table->column_data_type(*aggregate.column); _contexts_per_column[column_id] = _create_aggregate_context(data_type, aggregate.function); } // Process Chunks and perform aggregations for (ChunkID chunk_id{0}; chunk_id < input_table->chunk_count(); ++chunk_id) { auto chunk_in = input_table->get_chunk(chunk_id); auto& hash_keys = _keys_per_chunk[chunk_id]; if (_aggregates.empty()) { /** * DISTINCT implementation * * In Opossum we handle the SQL keyword DISTINCT by grouping without aggregation. * * For a query like "SELECT DISTINCT * FROM A;" * we would assume that all columns from A are part of 'groupby_columns', * respectively any columns that were specified in the projection. * The optimizer is responsible to take care of passing in the correct columns. * * How does this operation work? * Distinct rows are retrieved by grouping by vectors of values. Similar as for the usual aggregation * these vectors are used as keys in the 'column_results' map. * * At this point we've got all the different keys from the chunks and accumulate them in 'column_results'. * In order to reuse the aggregation implementation, we add a dummy AggregateResult. * One could optimize here in the future. * * Obviously this implementation is also used for plain GroupBy's. */ auto context = std::static_pointer_cast<AggregateContext<DistinctColumnType, DistinctAggregateType>>( _contexts_per_column[0]); auto& results = *context->results; for (ChunkOffset chunk_offset{0}; chunk_offset < chunk_in->size(); chunk_offset++) { results[(*hash_keys)[chunk_offset]].row_id = RowID(chunk_id, chunk_offset); } } else { ColumnID column_index{0}; for (const auto& aggregate : _aggregates) { /** * Special COUNT(*) implementation. * Because COUNT(*) does not have a specific target column, we use the maximum ColumnID. * We then basically go through the _keys_per_chunk map and count the occurrences of each group key. * The results are saved in the regular aggregate_count variable so that we don't need a * specific output logic for COUNT(*). */ if (!aggregate.column && aggregate.function == AggregateFunction::Count) { auto context = std::static_pointer_cast<AggregateContext<CountColumnType, CountAggregateType>>( _contexts_per_column[column_index]); auto& results = *context->results; // count occurrences for each group key for (ChunkOffset chunk_offset{0}; chunk_offset < chunk_in->size(); chunk_offset++) { results[(*hash_keys)[chunk_offset]].row_id = RowID(chunk_id, chunk_offset); ++results[(*hash_keys)[chunk_offset]].aggregate_count; } ++column_index; continue; } auto base_column = chunk_in->get_column(*aggregate.column); auto data_type = input_table->column_data_type(*aggregate.column); /* Invoke correct aggregator for each column */ resolve_data_type(data_type, [&, this, aggregate](auto type) { using ColumnDataType = typename decltype(type)::type; switch (aggregate.function) { case AggregateFunction::Min: _aggregate_column<ColumnDataType, AggregateFunction::Min>(chunk_id, column_index, *base_column); break; case AggregateFunction::Max: _aggregate_column<ColumnDataType, AggregateFunction::Max>(chunk_id, column_index, *base_column); break; case AggregateFunction::Sum: _aggregate_column<ColumnDataType, AggregateFunction::Sum>(chunk_id, column_index, *base_column); break; case AggregateFunction::Avg: _aggregate_column<ColumnDataType, AggregateFunction::Avg>(chunk_id, column_index, *base_column); break; case AggregateFunction::Count: _aggregate_column<ColumnDataType, AggregateFunction::Count>(chunk_id, column_index, *base_column); break; case AggregateFunction::CountDistinct: _aggregate_column<ColumnDataType, AggregateFunction::CountDistinct>(chunk_id, column_index, *base_column); break; } }); ++column_index; } } } // add group by columns for (const auto column_id : _groupby_column_ids) { _output_column_definitions.emplace_back(input_table->column_name(column_id), input_table->column_data_type(column_id)); auto groupby_column = make_shared_by_data_type<BaseColumn, ValueColumn>(input_table->column_data_type(column_id), true); _groupby_columns.push_back(groupby_column); _output_columns.push_back(groupby_column); } /** * Write group-by columns. * * 'results_per_column' always contains at least one element, since there are either GroupBy or Aggregate columns. * However, we need to look only at the first element, because the keys for all columns are the same. * * The following loop is used for both, actual GroupBy columns and DISTINCT columns. **/ if (_aggregates.empty()) { auto context = std::static_pointer_cast<AggregateContext<DistinctColumnType, DistinctAggregateType>>(_contexts_per_column[0]); auto pos_list = PosList(); pos_list.reserve(context->results->size()); for (auto& map : *context->results) { pos_list.push_back(map.second.row_id); } _write_groupby_output(pos_list); } /* Write the aggregated columns to the output */ ColumnID column_index{0}; for (const auto& aggregate : _aggregates) { const auto column = aggregate.column; // Output column for COUNT(*). int is chosen arbitrarily. const auto data_type = !column ? DataType::Int : input_table->column_data_type(*column); resolve_data_type( data_type, [&, column_index](auto type) { _write_aggregate_output(type, column_index, aggregate.function); }); ++column_index; } // Write the output auto output = std::make_shared<Table>(_output_column_definitions, TableType::Data); output->append_chunk(_output_columns); return output; } /* The following template functions write the aggregated values for the different aggregate functions. They are separate and templated to avoid compiler errors for invalid type/function combinations. */ // MIN, MAX, SUM write the current aggregated value template <typename ColumnType, typename AggregateType, AggregateFunction func> typename std::enable_if< func == AggregateFunction::Min || func == AggregateFunction::Max || func == AggregateFunction::Sum, void>::type write_aggregate_values(std::shared_ptr<ValueColumn<AggregateType>> column, std::shared_ptr<std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>, std::hash<AggregateKey>>> results) { DebugAssert(column->is_nullable(), "Aggregate: Output column needs to be nullable"); auto& values = column->values(); auto& null_values = column->null_values(); values.resize(results->size()); null_values.resize(results->size()); size_t i = 0; for (auto& kv : *results) { null_values[i] = !kv.second.current_aggregate; if (kv.second.current_aggregate) { values[i] = *kv.second.current_aggregate; } ++i; } } // COUNT writes the aggregate counter template <typename ColumnType, typename AggregateType, AggregateFunction func> typename std::enable_if<func == AggregateFunction::Count, void>::type write_aggregate_values( std::shared_ptr<ValueColumn<AggregateType>> column, std::shared_ptr< std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>, std::hash<AggregateKey>>> results) { DebugAssert(!column->is_nullable(), "Aggregate: Output column for COUNT shouldn't be nullable"); auto& values = column->values(); values.resize(results->size()); size_t i = 0; for (auto& kv : *results) { values[i] = kv.second.aggregate_count; ++i; } } // COUNT(DISTINCT) writes the number of distinct values template <typename ColumnType, typename AggregateType, AggregateFunction func> typename std::enable_if<func == AggregateFunction::CountDistinct, void>::type write_aggregate_values( std::shared_ptr<ValueColumn<AggregateType>> column, std::shared_ptr< std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>, std::hash<AggregateKey>>> results) { DebugAssert(!column->is_nullable(), "Aggregate: Output column for COUNT shouldn't be nullable"); auto& values = column->values(); values.resize(results->size()); size_t i = 0; for (auto& kv : *results) { values[i] = kv.second.distinct_values.size(); ++i; } } // AVG writes the calculated average from current aggregate and the aggregate counter template <typename ColumnType, typename AggregateType, AggregateFunction func> typename std::enable_if<func == AggregateFunction::Avg && std::is_arithmetic<AggregateType>::value, void>::type write_aggregate_values(std::shared_ptr<ValueColumn<AggregateType>> column, std::shared_ptr<std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>, std::hash<AggregateKey>>> results) { DebugAssert(column->is_nullable(), "Aggregate: Output column needs to be nullable"); auto& values = column->values(); auto& null_values = column->null_values(); values.resize(results->size()); null_values.resize(results->size()); size_t i = 0; for (auto& kv : *results) { null_values[i] = !kv.second.current_aggregate; if (kv.second.current_aggregate) { values[i] = *kv.second.current_aggregate / static_cast<AggregateType>(kv.second.aggregate_count); } ++i; } } // AVG is not defined for non-arithmetic types. Avoiding compiler errors. template <typename ColumnType, typename AggregateType, AggregateFunction func> typename std::enable_if<func == AggregateFunction::Avg && !std::is_arithmetic<AggregateType>::value, void>::type write_aggregate_values(std::shared_ptr<ValueColumn<AggregateType>>, std::shared_ptr<std::unordered_map<AggregateKey, AggregateResult<AggregateType, ColumnType>, std::hash<AggregateKey>>>) { Fail("Invalid aggregate"); } void Aggregate::_write_groupby_output(PosList& pos_list) { auto input_table = input_table_left(); for (size_t group_column_index = 0; group_column_index < _groupby_column_ids.size(); ++group_column_index) { auto base_columns = std::vector<std::shared_ptr<const BaseColumn>>(); for (const auto& chunk : input_table->chunks()) { base_columns.push_back(chunk->get_column(_groupby_column_ids[group_column_index])); } for (const auto row_id : pos_list) { _groupby_columns[group_column_index]->append((*base_columns[row_id.chunk_id])[row_id.chunk_offset]); } } } template <typename ColumnType> void Aggregate::_write_aggregate_output(boost::hana::basic_type<ColumnType> type, ColumnID column_index, AggregateFunction function) { switch (function) { case AggregateFunction::Min: write_aggregate_output<ColumnType, AggregateFunction::Min>(column_index); break; case AggregateFunction::Max: write_aggregate_output<ColumnType, AggregateFunction::Max>(column_index); break; case AggregateFunction::Sum: write_aggregate_output<ColumnType, AggregateFunction::Sum>(column_index); break; case AggregateFunction::Avg: write_aggregate_output<ColumnType, AggregateFunction::Avg>(column_index); break; case AggregateFunction::Count: write_aggregate_output<ColumnType, AggregateFunction::Count>(column_index); break; case AggregateFunction::CountDistinct: write_aggregate_output<ColumnType, AggregateFunction::CountDistinct>(column_index); break; } } template <typename ColumnType, AggregateFunction function> void Aggregate::write_aggregate_output(ColumnID column_index) { // retrieve type information from the aggregation traits typename AggregateTraits<ColumnType, function>::AggregateType aggregate_type; auto aggregate_data_type = AggregateTraits<ColumnType, function>::AGGREGATE_DATA_TYPE; const auto& aggregate = _aggregates[column_index]; if (aggregate_data_type == DataType::Null) { // if not specified, it’s the input column’s type aggregate_data_type = input_table_left()->column_data_type(*aggregate.column); } // use the alias or generate the name, e.g. MAX(column_a) std::string output_column_name; if (aggregate.alias) { output_column_name = *aggregate.alias; } else if (!aggregate.column) { output_column_name = "COUNT(*)"; } else { const auto& column_name = input_table_left()->column_name(*aggregate.column); if (aggregate.function == AggregateFunction::CountDistinct) { output_column_name = std::string("COUNT(DISTINCT ") + column_name + ")"; } else { output_column_name = aggregate_function_to_string.left.at(function) + "(" + column_name + ")"; } } constexpr bool NEEDS_NULL = (function != AggregateFunction::Count && function != AggregateFunction::CountDistinct); _output_column_definitions.emplace_back(output_column_name, aggregate_data_type, NEEDS_NULL); auto output_column = std::make_shared<ValueColumn<decltype(aggregate_type)>>(NEEDS_NULL); auto context = std::static_pointer_cast<AggregateContext<ColumnType, decltype(aggregate_type)>>( _contexts_per_column[column_index]); // write all group keys into the respective columns if (column_index == 0) { auto pos_list = PosList(); pos_list.reserve(context->results->size()); for (auto& map : *context->results) { pos_list.push_back(map.second.row_id); } _write_groupby_output(pos_list); } // write aggregated values into the column if (!context->results->empty()) { write_aggregate_values<ColumnType, decltype(aggregate_type), function>(output_column, context->results); } else if (_groupby_columns.empty()) { // If we did not GROUP BY anything and we have no results, we need to add NULL for most aggregates and 0 for count output_column->values().push_back(decltype(aggregate_type){}); if (function != AggregateFunction::Count && function != AggregateFunction::CountDistinct) { output_column->null_values().push_back(true); } } _output_columns.push_back(output_column); } std::shared_ptr<ColumnVisitableContext> Aggregate::_create_aggregate_context(const DataType data_type, const AggregateFunction function) const { std::shared_ptr<ColumnVisitableContext> context; resolve_data_type(data_type, [&](auto type) { using ColumnDataType = typename decltype(type)::type; switch (function) { case AggregateFunction::Min: context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::Min>(); break; case AggregateFunction::Max: context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::Max>(); break; case AggregateFunction::Sum: context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::Sum>(); break; case AggregateFunction::Avg: context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::Avg>(); break; case AggregateFunction::Count: context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::Count>(); break; case AggregateFunction::CountDistinct: context = _create_aggregate_context_impl<ColumnDataType, AggregateFunction::CountDistinct>(); break; } }); return context; } template <typename ColumnDataType, AggregateFunction aggregate_function> std::shared_ptr<ColumnVisitableContext> Aggregate::_create_aggregate_context_impl() const { const auto context = std::make_shared< AggregateContext<ColumnDataType, typename AggregateTraits<ColumnDataType, aggregate_function>::AggregateType>>(); context->results = std::make_shared<typename decltype(context->results)::element_type>(); return context; } } // namespace opossum
42.056423
120
0.706277
IanJamesMcKay
d0b8ce1cfba602d6ad9bd5cffcca7c37ee3c3ec9
442
cpp
C++
samples/unit_test/test.cpp
vagran/adk
1cf18aeca58444fc8ff59b29a4c25e22d5e50bb2
[ "BSD-3-Clause" ]
3
2015-10-12T06:06:00.000Z
2020-01-17T18:16:18.000Z
samples/unit_test/test.cpp
vagran/adk
1cf18aeca58444fc8ff59b29a4c25e22d5e50bb2
[ "BSD-3-Clause" ]
null
null
null
samples/unit_test/test.cpp
vagran/adk
1cf18aeca58444fc8ff59b29a4c25e22d5e50bb2
[ "BSD-3-Clause" ]
null
null
null
/* This file is a part of ADK library. * Copyright (c) 2012-2015, Artyom Lebedev <[email protected]> * All rights reserved. * See LICENSE file for copyright details. */ /** @file test.cpp * Sample unit test implementation. */ #include <adk_ut.h> #include "component/component.h" UT_TEST("Sample test") { UT(SampleString()) == UT("Sample string"); UT_CKPOINT("Multiplication"); UT(SampleMult(5, 3)) == UT(15); }
19.217391
69
0.667421
vagran
d0c327df56e5ab30e0b0660b5d1ce80c5951629c
52,074
cpp
C++
tests/RoundRectTest.cpp
NearTox/Skia
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
[ "BSD-3-Clause" ]
null
null
null
tests/RoundRectTest.cpp
NearTox/Skia
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
[ "BSD-3-Clause" ]
null
null
null
tests/RoundRectTest.cpp
NearTox/Skia
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkMatrix.h" #include "include/core/SkRRect.h" #include "include/pathops/SkPathOps.h" #include "include/utils/SkRandom.h" #include "src/core/SkPointPriv.h" #include "src/core/SkRRectPriv.h" #include "tests/Test.h" static void test_tricky_radii(skiatest::Reporter* reporter) { { // crbug.com/458522 SkRRect rr; const SkRect bounds = {3709, 3709, 3709 + 7402, 3709 + 29825}; const SkScalar rad = 12814; const SkVector vec[] = {{rad, rad}, {0, rad}, {rad, rad}, {0, rad}}; rr.setRectRadii(bounds, vec); } { // crbug.com//463920 SkRect r = SkRect::MakeLTRB(0, 0, 1009, 33554432.0); SkVector radii[4] = {{13.0f, 8.0f}, {170.0f, 2.0}, {256.0f, 33554432.0}, {110.0f, 5.0f}}; SkRRect rr; rr.setRectRadii(r, radii); REPORTER_ASSERT( reporter, (double)rr.radii(SkRRect::kUpperRight_Corner).fY + (double)rr.radii(SkRRect::kLowerRight_Corner).fY <= rr.height()); } } static void test_empty_crbug_458524(skiatest::Reporter* reporter) { SkRRect rr; const SkRect bounds = {3709, 3709, 3709 + 7402, 3709 + 29825}; const SkScalar rad = 40; rr.setRectXY(bounds, rad, rad); SkRRect other; SkMatrix matrix; matrix.setScale(0, 1); rr.transform(matrix, &other); REPORTER_ASSERT(reporter, SkRRect::kEmpty_Type == other.getType()); } // Test that all the SkRRect entry points correctly handle un-sorted and // zero-sized input rects static void test_empty(skiatest::Reporter* reporter) { static const SkRect oooRects[] = { // out of order {100, 0, 0, 100}, // ooo horizontal {0, 100, 100, 0}, // ooo vertical {100, 100, 0, 0}, // ooo both }; static const SkRect emptyRects[] = { {100, 100, 100, 200}, // empty horizontal {100, 100, 200, 100}, // empty vertical {100, 100, 100, 100}, // empty both {0, 0, 0, 0} // setEmpty-empty }; static const SkVector radii[4] = {{0, 1}, {2, 3}, {4, 5}, {6, 7}}; SkRRect r; for (size_t i = 0; i < SK_ARRAY_COUNT(oooRects); ++i) { r.setRect(oooRects[i]); REPORTER_ASSERT(reporter, !r.isEmpty()); REPORTER_ASSERT(reporter, r.rect() == oooRects[i].makeSorted()); r.setOval(oooRects[i]); REPORTER_ASSERT(reporter, !r.isEmpty()); REPORTER_ASSERT(reporter, r.rect() == oooRects[i].makeSorted()); r.setRectXY(oooRects[i], 1, 2); REPORTER_ASSERT(reporter, !r.isEmpty()); REPORTER_ASSERT(reporter, r.rect() == oooRects[i].makeSorted()); r.setNinePatch(oooRects[i], 0, 1, 2, 3); REPORTER_ASSERT(reporter, !r.isEmpty()); REPORTER_ASSERT(reporter, r.rect() == oooRects[i].makeSorted()); r.setRectRadii(oooRects[i], radii); REPORTER_ASSERT(reporter, !r.isEmpty()); REPORTER_ASSERT(reporter, r.rect() == oooRects[i].makeSorted()); } for (size_t i = 0; i < SK_ARRAY_COUNT(emptyRects); ++i) { r.setRect(emptyRects[i]); REPORTER_ASSERT(reporter, r.isEmpty()); REPORTER_ASSERT(reporter, r.rect() == emptyRects[i]); r.setOval(emptyRects[i]); REPORTER_ASSERT(reporter, r.isEmpty()); REPORTER_ASSERT(reporter, r.rect() == emptyRects[i]); r.setRectXY(emptyRects[i], 1, 2); REPORTER_ASSERT(reporter, r.isEmpty()); REPORTER_ASSERT(reporter, r.rect() == emptyRects[i]); r.setNinePatch(emptyRects[i], 0, 1, 2, 3); REPORTER_ASSERT(reporter, r.isEmpty()); REPORTER_ASSERT(reporter, r.rect() == emptyRects[i]); r.setRectRadii(emptyRects[i], radii); REPORTER_ASSERT(reporter, r.isEmpty()); REPORTER_ASSERT(reporter, r.rect() == emptyRects[i]); } r.setRect({SK_ScalarNaN, 10, 10, 20}); REPORTER_ASSERT(reporter, r == SkRRect::MakeEmpty()); r.setRect({0, 10, 10, SK_ScalarInfinity}); REPORTER_ASSERT(reporter, r == SkRRect::MakeEmpty()); } static const SkScalar kWidth = 100.0f; static const SkScalar kHeight = 100.0f; static void test_inset(skiatest::Reporter* reporter) { SkRRect rr, rr2; SkRect r = {0, 0, 100, 100}; rr.setRect(r); rr.inset(-20, -20, &rr2); REPORTER_ASSERT(reporter, rr2.isRect()); rr.inset(20, 20, &rr2); REPORTER_ASSERT(reporter, rr2.isRect()); rr.inset(r.width() / 2, r.height() / 2, &rr2); REPORTER_ASSERT(reporter, rr2.isEmpty()); rr.setRectXY(r, 20, 20); rr.inset(19, 19, &rr2); REPORTER_ASSERT(reporter, rr2.isSimple()); rr.inset(20, 20, &rr2); REPORTER_ASSERT(reporter, rr2.isRect()); } static void test_9patch_rrect( skiatest::Reporter* reporter, const SkRect& rect, SkScalar l, SkScalar t, SkScalar r, SkScalar b, bool checkRadii) { SkRRect rr; rr.setNinePatch(rect, l, t, r, b); REPORTER_ASSERT(reporter, SkRRect::kNinePatch_Type == rr.type()); REPORTER_ASSERT(reporter, rr.rect() == rect); if (checkRadii) { // This test doesn't hold if the radii will be rescaled by SkRRect SkRect ninePatchRadii = {l, t, r, b}; SkPoint rquad[4]; ninePatchRadii.toQuad(rquad); for (int i = 0; i < 4; ++i) { REPORTER_ASSERT(reporter, rquad[i] == rr.radii((SkRRect::Corner)i)); } } SkRRect rr2; // construct the same RR using the most general set function SkVector radii[4] = {{l, t}, {r, t}, {r, b}, {l, b}}; rr2.setRectRadii(rect, radii); REPORTER_ASSERT(reporter, rr2 == rr && rr2.getType() == rr.getType()); } // Test out the basic API entry points static void test_round_rect_basic(skiatest::Reporter* reporter) { // Test out initialization methods SkPoint zeroPt = {0, 0}; SkRRect empty; empty.setEmpty(); REPORTER_ASSERT(reporter, SkRRect::kEmpty_Type == empty.type()); REPORTER_ASSERT(reporter, empty.rect().isEmpty()); for (int i = 0; i < 4; ++i) { REPORTER_ASSERT(reporter, zeroPt == empty.radii((SkRRect::Corner)i)); } //---- SkRect rect = SkRect::MakeLTRB(0, 0, kWidth, kHeight); SkRRect rr1; rr1.setRect(rect); REPORTER_ASSERT(reporter, SkRRect::kRect_Type == rr1.type()); REPORTER_ASSERT(reporter, rr1.rect() == rect); for (int i = 0; i < 4; ++i) { REPORTER_ASSERT(reporter, zeroPt == rr1.radii((SkRRect::Corner)i)); } SkRRect rr1_2; // construct the same RR using the most general set function SkVector rr1_2_radii[4] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}}; rr1_2.setRectRadii(rect, rr1_2_radii); REPORTER_ASSERT(reporter, rr1_2 == rr1 && rr1_2.getType() == rr1.getType()); SkRRect rr1_3; // construct the same RR using the nine patch set function rr1_3.setNinePatch(rect, 0, 0, 0, 0); REPORTER_ASSERT(reporter, rr1_3 == rr1 && rr1_3.getType() == rr1.getType()); //---- SkPoint halfPoint = {SkScalarHalf(kWidth), SkScalarHalf(kHeight)}; SkRRect rr2; rr2.setOval(rect); REPORTER_ASSERT(reporter, SkRRect::kOval_Type == rr2.type()); REPORTER_ASSERT(reporter, rr2.rect() == rect); for (int i = 0; i < 4; ++i) { REPORTER_ASSERT( reporter, SkPointPriv::EqualsWithinTolerance(rr2.radii((SkRRect::Corner)i), halfPoint)); } SkRRect rr2_2; // construct the same RR using the most general set function SkVector rr2_2_radii[4] = { {halfPoint.fX, halfPoint.fY}, {halfPoint.fX, halfPoint.fY}, {halfPoint.fX, halfPoint.fY}, {halfPoint.fX, halfPoint.fY}}; rr2_2.setRectRadii(rect, rr2_2_radii); REPORTER_ASSERT(reporter, rr2_2 == rr2 && rr2_2.getType() == rr2.getType()); SkRRect rr2_3; // construct the same RR using the nine patch set function rr2_3.setNinePatch(rect, halfPoint.fX, halfPoint.fY, halfPoint.fX, halfPoint.fY); REPORTER_ASSERT(reporter, rr2_3 == rr2 && rr2_3.getType() == rr2.getType()); //---- SkPoint p = {5, 5}; SkRRect rr3; rr3.setRectXY(rect, p.fX, p.fY); REPORTER_ASSERT(reporter, SkRRect::kSimple_Type == rr3.type()); REPORTER_ASSERT(reporter, rr3.rect() == rect); for (int i = 0; i < 4; ++i) { REPORTER_ASSERT(reporter, p == rr3.radii((SkRRect::Corner)i)); } SkRRect rr3_2; // construct the same RR using the most general set function SkVector rr3_2_radii[4] = {{5, 5}, {5, 5}, {5, 5}, {5, 5}}; rr3_2.setRectRadii(rect, rr3_2_radii); REPORTER_ASSERT(reporter, rr3_2 == rr3 && rr3_2.getType() == rr3.getType()); SkRRect rr3_3; // construct the same RR using the nine patch set function rr3_3.setNinePatch(rect, 5, 5, 5, 5); REPORTER_ASSERT(reporter, rr3_3 == rr3 && rr3_3.getType() == rr3.getType()); //---- test_9patch_rrect(reporter, rect, 10, 9, 8, 7, true); { // Test out the rrect from skia:3466 SkRect rect2 = SkRect::MakeLTRB(0.358211994f, 0.755430222f, 0.872866154f, 0.806214333f); test_9patch_rrect( reporter, rect2, 0.926942348f, 0.642850280f, 0.529063463f, 0.587844372f, false); } //---- SkPoint radii2[4] = {{0, 0}, {0, 0}, {50, 50}, {20, 50}}; SkRRect rr5; rr5.setRectRadii(rect, radii2); REPORTER_ASSERT(reporter, SkRRect::kComplex_Type == rr5.type()); REPORTER_ASSERT(reporter, rr5.rect() == rect); for (int i = 0; i < 4; ++i) { REPORTER_ASSERT(reporter, radii2[i] == rr5.radii((SkRRect::Corner)i)); } // Test out == & != REPORTER_ASSERT(reporter, empty != rr3); REPORTER_ASSERT(reporter, rr3 != rr5); } // Test out the cases when the RR degenerates to a rect static void test_round_rect_rects(skiatest::Reporter* reporter) { SkRect r; //---- SkRRect empty; empty.setEmpty(); REPORTER_ASSERT(reporter, SkRRect::kEmpty_Type == empty.type()); r = empty.rect(); REPORTER_ASSERT(reporter, 0 == r.fLeft && 0 == r.fTop && 0 == r.fRight && 0 == r.fBottom); //---- SkRect rect = SkRect::MakeLTRB(0, 0, kWidth, kHeight); SkRRect rr1; rr1.setRectXY(rect, 0, 0); REPORTER_ASSERT(reporter, SkRRect::kRect_Type == rr1.type()); r = rr1.rect(); REPORTER_ASSERT(reporter, rect == r); //---- SkPoint radii[4] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}}; SkRRect rr2; rr2.setRectRadii(rect, radii); REPORTER_ASSERT(reporter, SkRRect::kRect_Type == rr2.type()); r = rr2.rect(); REPORTER_ASSERT(reporter, rect == r); //---- SkPoint radii2[4] = {{0, 0}, {20, 20}, {50, 50}, {20, 50}}; SkRRect rr3; rr3.setRectRadii(rect, radii2); REPORTER_ASSERT(reporter, SkRRect::kComplex_Type == rr3.type()); } // Test out the cases when the RR degenerates to an oval static void test_round_rect_ovals(skiatest::Reporter* reporter) { //---- SkRect oval; SkRect rect = SkRect::MakeLTRB(0, 0, kWidth, kHeight); SkRRect rr1; rr1.setRectXY(rect, SkScalarHalf(kWidth), SkScalarHalf(kHeight)); REPORTER_ASSERT(reporter, SkRRect::kOval_Type == rr1.type()); oval = rr1.rect(); REPORTER_ASSERT(reporter, oval == rect); } // Test out the non-degenerate RR cases static void test_round_rect_general(skiatest::Reporter* reporter) { //---- SkRect rect = SkRect::MakeLTRB(0, 0, kWidth, kHeight); SkRRect rr1; rr1.setRectXY(rect, 20, 20); REPORTER_ASSERT(reporter, SkRRect::kSimple_Type == rr1.type()); //---- SkPoint radii[4] = {{0, 0}, {20, 20}, {50, 50}, {20, 50}}; SkRRect rr2; rr2.setRectRadii(rect, radii); REPORTER_ASSERT(reporter, SkRRect::kComplex_Type == rr2.type()); } // Test out questionable-parameter handling static void test_round_rect_iffy_parameters(skiatest::Reporter* reporter) { // When the radii exceed the base rect they are proportionally scaled down // to fit SkRect rect = SkRect::MakeLTRB(0, 0, kWidth, kHeight); SkPoint radii[4] = {{50, 100}, {100, 50}, {50, 100}, {100, 50}}; SkRRect rr1; rr1.setRectRadii(rect, radii); REPORTER_ASSERT(reporter, SkRRect::kComplex_Type == rr1.type()); const SkPoint& p = rr1.radii(SkRRect::kUpperLeft_Corner); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(p.fX, 33.33333f)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(p.fY, 66.66666f)); // Negative radii should be capped at zero SkRRect rr2; rr2.setRectXY(rect, -10, -20); REPORTER_ASSERT(reporter, SkRRect::kRect_Type == rr2.type()); const SkPoint& p2 = rr2.radii(SkRRect::kUpperLeft_Corner); REPORTER_ASSERT(reporter, 0.0f == p2.fX); REPORTER_ASSERT(reporter, 0.0f == p2.fY); } // Move a small box from the start position by (stepX, stepY) 'numSteps' times // testing for containment in 'rr' at each step. static void test_direction( skiatest::Reporter* reporter, const SkRRect& rr, SkScalar initX, int stepX, SkScalar initY, int stepY, int numSteps, const bool* contains) { SkScalar x = initX, y = initY; for (int i = 0; i < numSteps; ++i) { SkRect test = SkRect::MakeXYWH( x, y, stepX ? SkIntToScalar(stepX) : SK_Scalar1, stepY ? SkIntToScalar(stepY) : SK_Scalar1); test.sort(); REPORTER_ASSERT(reporter, contains[i] == rr.contains(test)); x += stepX; y += stepY; } } // Exercise the RR's contains rect method static void test_round_rect_contains_rect(skiatest::Reporter* reporter) { static const int kNumRRects = 4; static const SkVector gRadii[kNumRRects][4] = { {{0, 0}, {0, 0}, {0, 0}, {0, 0}}, // rect {{20, 20}, {20, 20}, {20, 20}, {20, 20}}, // circle {{10, 10}, {10, 10}, {10, 10}, {10, 10}}, // simple {{0, 0}, {20, 20}, {10, 10}, {30, 30}} // complex }; SkRRect rrects[kNumRRects]; for (int i = 0; i < kNumRRects; ++i) { rrects[i].setRectRadii(SkRect::MakeWH(40, 40), gRadii[i]); } // First test easy outs - boxes that are obviously out on // each corner and edge static const SkRect easyOuts[] = { {-5, -5, 5, 5}, // NW {15, -5, 20, 5}, // N {35, -5, 45, 5}, // NE {35, 15, 45, 20}, // E {35, 45, 35, 45}, // SE {15, 35, 20, 45}, // S {-5, 35, 5, 45}, // SW {-5, 15, 5, 20} // W }; for (int i = 0; i < kNumRRects; ++i) { for (size_t j = 0; j < SK_ARRAY_COUNT(easyOuts); ++j) { REPORTER_ASSERT(reporter, !rrects[i].contains(easyOuts[j])); } } // Now test non-trivial containment. For each compass // point walk a 1x1 rect in from the edge of the bounding // rect static const int kNumSteps = 15; bool answers[kNumRRects][8][kNumSteps] = { // all the test rects are inside the degenerate rrect { // rect {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, }, // for the circle we expect 6 blocks to be out on the // corners (then the rest in) and only the first block // out on the vertical and horizontal axes (then // the rest in) { // circle {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, }, // for the simple round rect we expect 3 out on // the corners (then the rest in) and no blocks out // on the vertical and horizontal axes { // simple RR {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, }, // for the complex case the answer is different for each direction { // complex RR // all in for NW (rect) corner (same as rect case) {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, // only first block out for N (same as circle case) {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, // first 6 blocks out for NE (same as circle case) {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, // only first block out for E (same as circle case) {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, // first 3 blocks out for SE (same as simple case) {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, // first two blocks out for S {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, // first 9 blocks out for SW {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}, // first two blocks out for W (same as S) {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, }}; for (int i = 0; i < kNumRRects; ++i) { test_direction(reporter, rrects[i], 0, 1, 0, 1, kNumSteps, answers[i][0]); // NW test_direction(reporter, rrects[i], 19.5f, 0, 0, 1, kNumSteps, answers[i][1]); // N test_direction(reporter, rrects[i], 40, -1, 0, 1, kNumSteps, answers[i][2]); // NE test_direction(reporter, rrects[i], 40, -1, 19.5f, 0, kNumSteps, answers[i][3]); // E test_direction(reporter, rrects[i], 40, -1, 40, -1, kNumSteps, answers[i][4]); // SE test_direction(reporter, rrects[i], 19.5f, 0, 40, -1, kNumSteps, answers[i][5]); // S test_direction(reporter, rrects[i], 0, 1, 40, -1, kNumSteps, answers[i][6]); // SW test_direction(reporter, rrects[i], 0, 1, 19.5f, 0, kNumSteps, answers[i][7]); // W } } // Called for a matrix that should cause SkRRect::transform to fail. static void assert_transform_failure( skiatest::Reporter* reporter, const SkRRect& orig, const SkMatrix& matrix) { // The test depends on the fact that the original is not empty. SkASSERT(!orig.isEmpty()); SkRRect dst; dst.setEmpty(); const SkRRect copyOfDst = dst; const SkRRect copyOfOrig = orig; bool success = orig.transform(matrix, &dst); // This transform should fail. REPORTER_ASSERT(reporter, !success); // Since the transform failed, dst should be unchanged. REPORTER_ASSERT(reporter, copyOfDst == dst); // original should not be modified. REPORTER_ASSERT(reporter, copyOfOrig == orig); REPORTER_ASSERT(reporter, orig != dst); } #define GET_RADII \ const SkVector& origUL = orig.radii(SkRRect::kUpperLeft_Corner); \ const SkVector& origUR = orig.radii(SkRRect::kUpperRight_Corner); \ const SkVector& origLR = orig.radii(SkRRect::kLowerRight_Corner); \ const SkVector& origLL = orig.radii(SkRRect::kLowerLeft_Corner); \ const SkVector& dstUL = dst.radii(SkRRect::kUpperLeft_Corner); \ const SkVector& dstUR = dst.radii(SkRRect::kUpperRight_Corner); \ const SkVector& dstLR = dst.radii(SkRRect::kLowerRight_Corner); \ const SkVector& dstLL = dst.radii(SkRRect::kLowerLeft_Corner) // Called to test various transforms on a single SkRRect. static void test_transform_helper(skiatest::Reporter* reporter, const SkRRect& orig) { SkRRect dst; dst.setEmpty(); // The identity matrix will duplicate the rrect. bool success = orig.transform(SkMatrix::I(), &dst); REPORTER_ASSERT(reporter, success); REPORTER_ASSERT(reporter, orig == dst); // Skew and Perspective make transform fail. SkMatrix matrix; matrix.reset(); matrix.setSkewX(SkIntToScalar(2)); assert_transform_failure(reporter, orig, matrix); matrix.reset(); matrix.setSkewY(SkIntToScalar(3)); assert_transform_failure(reporter, orig, matrix); matrix.reset(); matrix.setPerspX(4); assert_transform_failure(reporter, orig, matrix); matrix.reset(); matrix.setPerspY(5); assert_transform_failure(reporter, orig, matrix); // Rotation fails. matrix.reset(); matrix.setRotate(SkIntToScalar(37)); assert_transform_failure(reporter, orig, matrix); // Translate will keep the rect moved, but otherwise the same. matrix.reset(); SkScalar translateX = SkIntToScalar(32); SkScalar translateY = SkIntToScalar(15); matrix.setTranslateX(translateX); matrix.setTranslateY(translateY); dst.setEmpty(); success = orig.transform(matrix, &dst); REPORTER_ASSERT(reporter, success); for (int i = 0; i < 4; ++i) { REPORTER_ASSERT(reporter, orig.radii((SkRRect::Corner)i) == dst.radii((SkRRect::Corner)i)); } REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().width()); REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().height()); REPORTER_ASSERT(reporter, dst.rect().left() == orig.rect().left() + translateX); REPORTER_ASSERT(reporter, dst.rect().top() == orig.rect().top() + translateY); // Keeping the translation, but adding skew will make transform fail. matrix.setSkewY(SkIntToScalar(7)); assert_transform_failure(reporter, orig, matrix); // Scaling in -x will flip the round rect horizontally. matrix.reset(); matrix.setScaleX(SkIntToScalar(-1)); dst.setEmpty(); success = orig.transform(matrix, &dst); REPORTER_ASSERT(reporter, success); { GET_RADII; // Radii have swapped in x. REPORTER_ASSERT(reporter, origUL == dstUR); REPORTER_ASSERT(reporter, origUR == dstUL); REPORTER_ASSERT(reporter, origLR == dstLL); REPORTER_ASSERT(reporter, origLL == dstLR); } // Width and height remain the same. REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().width()); REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().height()); // Right and left have swapped (sort of) REPORTER_ASSERT(reporter, orig.rect().right() == -dst.rect().left()); // Top has stayed the same. REPORTER_ASSERT(reporter, orig.rect().top() == dst.rect().top()); // Keeping the scale, but adding a persp will make transform fail. matrix.setPerspX(7); assert_transform_failure(reporter, orig, matrix); // Scaling in -y will flip the round rect vertically. matrix.reset(); matrix.setScaleY(SkIntToScalar(-1)); dst.setEmpty(); success = orig.transform(matrix, &dst); REPORTER_ASSERT(reporter, success); { GET_RADII; // Radii have swapped in y. REPORTER_ASSERT(reporter, origUL == dstLL); REPORTER_ASSERT(reporter, origUR == dstLR); REPORTER_ASSERT(reporter, origLR == dstUR); REPORTER_ASSERT(reporter, origLL == dstUL); } // Width and height remain the same. REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().width()); REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().height()); // Top and bottom have swapped (sort of) REPORTER_ASSERT(reporter, orig.rect().top() == -dst.rect().bottom()); // Left has stayed the same. REPORTER_ASSERT(reporter, orig.rect().left() == dst.rect().left()); // Scaling in -x and -y will swap in both directions. matrix.reset(); matrix.setScaleY(SkIntToScalar(-1)); matrix.setScaleX(SkIntToScalar(-1)); dst.setEmpty(); success = orig.transform(matrix, &dst); REPORTER_ASSERT(reporter, success); { GET_RADII; REPORTER_ASSERT(reporter, origUL == dstLR); REPORTER_ASSERT(reporter, origUR == dstLL); REPORTER_ASSERT(reporter, origLR == dstUL); REPORTER_ASSERT(reporter, origLL == dstUR); } // Width and height remain the same. REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().width()); REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().height()); REPORTER_ASSERT(reporter, orig.rect().top() == -dst.rect().bottom()); REPORTER_ASSERT(reporter, orig.rect().right() == -dst.rect().left()); // Scale in both directions. SkScalar xScale = SkIntToScalar(3); SkScalar yScale = 3.2f; matrix.reset(); matrix.setScaleX(xScale); matrix.setScaleY(yScale); dst.setEmpty(); success = orig.transform(matrix, &dst); REPORTER_ASSERT(reporter, success); // Radii are scaled. for (int i = 0; i < 4; ++i) { REPORTER_ASSERT( reporter, SkScalarNearlyEqual( dst.radii((SkRRect::Corner)i).fX, orig.radii((SkRRect::Corner)i).fX * xScale)); REPORTER_ASSERT( reporter, SkScalarNearlyEqual( dst.radii((SkRRect::Corner)i).fY, orig.radii((SkRRect::Corner)i).fY * yScale)); } REPORTER_ASSERT(reporter, SkScalarNearlyEqual(dst.rect().width(), orig.rect().width() * xScale)); REPORTER_ASSERT( reporter, SkScalarNearlyEqual(dst.rect().height(), orig.rect().height() * yScale)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(dst.rect().left(), orig.rect().left() * xScale)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(dst.rect().top(), orig.rect().top() * yScale)); // a-----b d-----a // | | -> | | // | | Rotate 90 | | // d-----c c-----b matrix.reset(); matrix.setRotate(SkIntToScalar(90)); dst.setEmpty(); success = orig.transform(matrix, &dst); REPORTER_ASSERT(reporter, success); { GET_RADII; // Radii have cycled clockwise and swapped their x and y axis. REPORTER_ASSERT(reporter, dstUL.x() == origLL.y()); REPORTER_ASSERT(reporter, dstUL.y() == origLL.x()); REPORTER_ASSERT(reporter, dstUR.x() == origUL.y()); REPORTER_ASSERT(reporter, dstUR.y() == origUL.x()); REPORTER_ASSERT(reporter, dstLR.x() == origUR.y()); REPORTER_ASSERT(reporter, dstLR.y() == origUR.x()); REPORTER_ASSERT(reporter, dstLL.x() == origLR.y()); REPORTER_ASSERT(reporter, dstLL.y() == origLR.x()); } // Width and height would get swapped. REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().height()); REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().width()); // a-----b b-----a c-----b // | | -> | | -> | | // | | Flip X | | Rotate 90 | | // d-----c c-----d d-----a matrix.reset(); matrix.setRotate(SkIntToScalar(90)); matrix.postScale(SkIntToScalar(-1), SkIntToScalar(1)); dst.setEmpty(); success = orig.transform(matrix, &dst); REPORTER_ASSERT(reporter, success); { GET_RADII; REPORTER_ASSERT(reporter, dstUL.x() == origLR.y()); REPORTER_ASSERT(reporter, dstUL.y() == origLR.x()); REPORTER_ASSERT(reporter, dstUR.x() == origUR.y()); REPORTER_ASSERT(reporter, dstUR.y() == origUR.x()); REPORTER_ASSERT(reporter, dstLR.x() == origUL.y()); REPORTER_ASSERT(reporter, dstLR.y() == origUL.x()); REPORTER_ASSERT(reporter, dstLL.x() == origLL.y()); REPORTER_ASSERT(reporter, dstLL.y() == origLL.x()); } // Width and height would get swapped. REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().height()); REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().width()); // a-----b d-----a c-----b // | | -> | | -> | | // | | Rotate 90 | | Flip Y | | // d-----c c-----b d-----a // // This is the same as Flip X and Rotate 90. matrix.reset(); matrix.setScale(SkIntToScalar(1), SkIntToScalar(-1)); matrix.postRotate(SkIntToScalar(90)); SkRRect dst2; dst2.setEmpty(); success = orig.transform(matrix, &dst2); REPORTER_ASSERT(reporter, success); REPORTER_ASSERT(reporter, dst == dst2); // a-----b b-----c c-----b // | | -> | | -> | | // | | Rotate 270 | | Flip X | | // d-----c a-----d d-----a matrix.reset(); matrix.setScale(SkIntToScalar(-1), SkIntToScalar(1)); matrix.postRotate(SkIntToScalar(270)); dst2.setEmpty(); success = orig.transform(matrix, &dst2); REPORTER_ASSERT(reporter, success); REPORTER_ASSERT(reporter, dst == dst2); // a-----b d-----c c-----b // | | -> | | -> | | // | | Flip Y | | Rotate 270 | | // d-----c a-----b d-----a matrix.reset(); matrix.setRotate(SkIntToScalar(270)); matrix.postScale(SkIntToScalar(1), SkIntToScalar(-1)); dst2.setEmpty(); success = orig.transform(matrix, &dst2); REPORTER_ASSERT(reporter, success); REPORTER_ASSERT(reporter, dst == dst2); // a-----b d-----a a-----d // | | -> | | -> | | // | | Rotate 90 | | Flip X | | // d-----c c-----b b-----c matrix.reset(); matrix.setScale(SkIntToScalar(-1), SkIntToScalar(1)); matrix.postRotate(SkIntToScalar(90)); dst.setEmpty(); success = orig.transform(matrix, &dst); REPORTER_ASSERT(reporter, success); { GET_RADII; REPORTER_ASSERT(reporter, dstUL.x() == origUL.y()); REPORTER_ASSERT(reporter, dstUL.y() == origUL.x()); REPORTER_ASSERT(reporter, dstUR.x() == origLL.y()); REPORTER_ASSERT(reporter, dstUR.y() == origLL.x()); REPORTER_ASSERT(reporter, dstLR.x() == origLR.y()); REPORTER_ASSERT(reporter, dstLR.y() == origLR.x()); REPORTER_ASSERT(reporter, dstLL.x() == origUR.y()); REPORTER_ASSERT(reporter, dstLL.y() == origUR.x()); } // Width and height would get swapped. REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().height()); REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().width()); // a-----b d-----c a-----d // | | -> | | -> | | // | | Flip Y | | Rotate 90 | | // d-----c a-----b b-----c // This is the same as rotate 90 and flip x. matrix.reset(); matrix.setRotate(SkIntToScalar(90)); matrix.postScale(SkIntToScalar(1), SkIntToScalar(-1)); dst2.setEmpty(); success = orig.transform(matrix, &dst2); REPORTER_ASSERT(reporter, success); REPORTER_ASSERT(reporter, dst == dst2); // a-----b b-----a a-----d // | | -> | | -> | | // | | Flip X | | Rotate 270 | | // d-----c c-----d b-----c matrix.reset(); matrix.setRotate(SkIntToScalar(270)); matrix.postScale(SkIntToScalar(-1), SkIntToScalar(1)); dst2.setEmpty(); success = orig.transform(matrix, &dst2); REPORTER_ASSERT(reporter, success); REPORTER_ASSERT(reporter, dst == dst2); // a-----b b-----c a-----d // | | -> | | -> | | // | | Rotate 270 | | Flip Y | | // d-----c a-----d b-----c matrix.reset(); matrix.setScale(SkIntToScalar(1), SkIntToScalar(-1)); matrix.postRotate(SkIntToScalar(270)); dst2.setEmpty(); success = orig.transform(matrix, &dst2); REPORTER_ASSERT(reporter, success); REPORTER_ASSERT(reporter, dst == dst2); // a-----b b-----a c-----d b-----c // | | -> | | -> | | -> | | // | | Flip X | | Flip Y | | Rotate 90 | | // d-----c c-----d b-----a a-----d // // This is the same as rotation by 270. matrix.reset(); matrix.setRotate(SkIntToScalar(90)); matrix.postScale(SkIntToScalar(-1), SkIntToScalar(-1)); dst.setEmpty(); success = orig.transform(matrix, &dst); REPORTER_ASSERT(reporter, success); { GET_RADII; // Radii have cycled clockwise and swapped their x and y axis. REPORTER_ASSERT(reporter, dstUL.x() == origUR.y()); REPORTER_ASSERT(reporter, dstUL.y() == origUR.x()); REPORTER_ASSERT(reporter, dstUR.x() == origLR.y()); REPORTER_ASSERT(reporter, dstUR.y() == origLR.x()); REPORTER_ASSERT(reporter, dstLR.x() == origLL.y()); REPORTER_ASSERT(reporter, dstLR.y() == origLL.x()); REPORTER_ASSERT(reporter, dstLL.x() == origUL.y()); REPORTER_ASSERT(reporter, dstLL.y() == origUL.x()); } // Width and height would get swapped. REPORTER_ASSERT(reporter, orig.rect().width() == dst.rect().height()); REPORTER_ASSERT(reporter, orig.rect().height() == dst.rect().width()); // a-----b b-----c // | | -> | | // | | Rotate 270 | | // d-----c a-----d // dst2.setEmpty(); matrix.reset(); matrix.setRotate(SkIntToScalar(270)); success = orig.transform(matrix, &dst2); REPORTER_ASSERT(reporter, success); REPORTER_ASSERT(reporter, dst == dst2); // a-----b b-----a c-----d d-----a // | | -> | | -> | | -> | | // | | Flip X | | Flip Y | | Rotate 270 | | // d-----c c-----d b-----a c-----b // // This is the same as rotation by 90 degrees. matrix.reset(); matrix.setRotate(SkIntToScalar(270)); matrix.postScale(SkIntToScalar(-1), SkIntToScalar(-1)); dst.setEmpty(); success = orig.transform(matrix, &dst); REPORTER_ASSERT(reporter, success); matrix.reset(); matrix.setRotate(SkIntToScalar(90)); dst2.setEmpty(); success = orig.transform(matrix, &dst2); REPORTER_ASSERT(reporter, dst == dst2); } static void test_round_rect_transform(skiatest::Reporter* reporter) { SkRRect rrect; { SkRect r = {0, 0, kWidth, kHeight}; rrect.setRectXY(r, SkIntToScalar(4), SkIntToScalar(7)); test_transform_helper(reporter, rrect); } { SkRect r = {SkIntToScalar(5), SkIntToScalar(15), SkIntToScalar(27), SkIntToScalar(34)}; SkVector radii[4] = { {0, SkIntToScalar(1)}, {SkIntToScalar(2), SkIntToScalar(3)}, {SkIntToScalar(4), SkIntToScalar(5)}, {SkIntToScalar(6), SkIntToScalar(7)}}; rrect.setRectRadii(r, radii); test_transform_helper(reporter, rrect); } } // Test out the case where an oval already off in space is translated/scaled // further off into space - yielding numerical issues when the rect & radii // are transformed separatly // BUG=skia:2696 static void test_issue_2696(skiatest::Reporter* reporter) { SkRRect rrect; SkRect r = {28443.8594f, 53.1428604f, 28446.7148f, 56.0000038f}; rrect.setOval(r); SkMatrix xform; xform.setAll(2.44f, 0.0f, 485411.7f, 0.0f, 2.44f, -438.7f, 0.0f, 0.0f, 1.0f); SkRRect dst; bool success = rrect.transform(xform, &dst); REPORTER_ASSERT(reporter, success); SkScalar halfWidth = SkScalarHalf(dst.width()); SkScalar halfHeight = SkScalarHalf(dst.height()); for (int i = 0; i < 4; ++i) { REPORTER_ASSERT(reporter, SkScalarNearlyEqual(dst.radii((SkRRect::Corner)i).fX, halfWidth)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(dst.radii((SkRRect::Corner)i).fY, halfHeight)); } } void test_read_rrect(skiatest::Reporter* reporter, const SkRRect& rrect, bool shouldEqualSrc) { // It would be cleaner to call rrect.writeToMemory into a buffer. However, writeToMemory asserts // that the rrect is valid and our caller may have fiddled with the internals of rrect to make // it invalid. const void* buffer = reinterpret_cast<const void*>(&rrect); SkRRect deserialized; size_t size = deserialized.readFromMemory(buffer, sizeof(SkRRect)); REPORTER_ASSERT(reporter, size == SkRRect::kSizeInMemory); REPORTER_ASSERT(reporter, deserialized.isValid()); if (shouldEqualSrc) { REPORTER_ASSERT(reporter, rrect == deserialized); } } static void test_read(skiatest::Reporter* reporter) { static const SkRect kRect = {10.f, 10.f, 20.f, 20.f}; static const SkRect kNaNRect = {10.f, 10.f, 20.f, SK_ScalarNaN}; static const SkRect kInfRect = {10.f, 10.f, SK_ScalarInfinity, 20.f}; SkRRect rrect; test_read_rrect(reporter, SkRRect::MakeEmpty(), true); test_read_rrect(reporter, SkRRect::MakeRect(kRect), true); // These get coerced to empty. test_read_rrect(reporter, SkRRect::MakeRect(kInfRect), true); test_read_rrect(reporter, SkRRect::MakeRect(kNaNRect), true); rrect.setRect(kRect); SkRect* innerRect = reinterpret_cast<SkRect*>(&rrect); SkASSERT(*innerRect == kRect); *innerRect = kInfRect; test_read_rrect(reporter, rrect, false); *innerRect = kNaNRect; test_read_rrect(reporter, rrect, false); test_read_rrect(reporter, SkRRect::MakeOval(kRect), true); test_read_rrect(reporter, SkRRect::MakeOval(kInfRect), true); test_read_rrect(reporter, SkRRect::MakeOval(kNaNRect), true); rrect.setOval(kRect); *innerRect = kInfRect; test_read_rrect(reporter, rrect, false); *innerRect = kNaNRect; test_read_rrect(reporter, rrect, false); test_read_rrect(reporter, SkRRect::MakeRectXY(kRect, 5.f, 5.f), true); // rrect should scale down the radii to make this legal test_read_rrect(reporter, SkRRect::MakeRectXY(kRect, 5.f, 400.f), true); static const SkVector kRadii[4] = {{0.5f, 1.f}, {1.5f, 2.f}, {2.5f, 3.f}, {3.5f, 4.f}}; rrect.setRectRadii(kRect, kRadii); test_read_rrect(reporter, rrect, true); SkScalar* innerRadius = reinterpret_cast<SkScalar*>(&rrect) + 6; SkASSERT(*innerRadius == 1.5f); *innerRadius = 400.f; test_read_rrect(reporter, rrect, false); *innerRadius = SK_ScalarInfinity; test_read_rrect(reporter, rrect, false); *innerRadius = SK_ScalarNaN; test_read_rrect(reporter, rrect, false); *innerRadius = -10.f; test_read_rrect(reporter, rrect, false); } static void test_inner_bounds(skiatest::Reporter* reporter) { // Because InnerBounds() insets the computed bounds slightly to correct for numerical inaccuracy // when finding the maximum inscribed point on a curve, we use a larger epsilon for comparing // expected areas. static constexpr SkScalar kEpsilon = 0.005f; // Test that an empty rrect reports empty inner bounds REPORTER_ASSERT(reporter, SkRRectPriv::InnerBounds(SkRRect::MakeEmpty()).isEmpty()); // Test that a rect rrect reports itself as the inner bounds SkRect r = SkRect::MakeLTRB(0, 1, 2, 3); REPORTER_ASSERT(reporter, SkRRectPriv::InnerBounds(SkRRect::MakeRect(r)) == r); // Test that a circle rrect has an inner bounds area equal to 2*radius^2 float radius = 5.f; SkRect inner = SkRRectPriv::InnerBounds(SkRRect::MakeOval(SkRect::MakeWH(2.f * radius, 2.f * radius))); REPORTER_ASSERT( reporter, SkScalarNearlyEqual(inner.width() * inner.height(), 2.f * radius * radius, kEpsilon)); float width = 20.f; float height = 25.f; r = SkRect::MakeWH(width, height); // Test that a rrect with circular corners has an area equal to: float expectedArea = (2.f * radius * radius) + // area in the 4 circular corners (width - 2.f * radius) * (height - 2.f * radius) + // inner area excluding corners and edges SK_ScalarSqrt2 * radius * (width - 2.f * radius) + // two horiz. rects between corners SK_ScalarSqrt2 * radius * (height - 2.f * radius); // two vert. rects between corners inner = SkRRectPriv::InnerBounds(SkRRect::MakeRectXY(r, radius, radius)); REPORTER_ASSERT( reporter, SkScalarNearlyEqual(inner.width() * inner.height(), expectedArea, kEpsilon)); // Test that a rrect with a small y radius but large x radius selects the horizontal interior SkRRect rr = SkRRect::MakeRectXY(r, 2.f * radius, 0.1f * radius); REPORTER_ASSERT( reporter, SkRRectPriv::InnerBounds(rr) == SkRect::MakeLTRB(0.f, 0.1f * radius, width, height - 0.1f * radius)); // And vice versa with large y and small x radii rr = SkRRect::MakeRectXY(r, 0.1f * radius, 2.f * radius); REPORTER_ASSERT( reporter, SkRRectPriv::InnerBounds(rr) == SkRect::MakeLTRB(0.1f * radius, 0.f, width - 0.1f * radius, height)); // Test a variety of complex round rects produce a non-empty rect that is at least contained, // and larger than the inner area avoiding all corners. SkRandom rng; for (int i = 0; i < 1000; ++i) { float maxRadiusX = rng.nextRangeF(0.f, 40.f); float maxRadiusY = rng.nextRangeF(0.f, 40.f); float innerWidth = rng.nextRangeF(0.f, 40.f); float innerHeight = rng.nextRangeF(0.f, 40.f); SkVector radii[4] = { {rng.nextRangeF(0.f, maxRadiusX), rng.nextRangeF(0.f, maxRadiusY)}, {rng.nextRangeF(0.f, maxRadiusX), rng.nextRangeF(0.f, maxRadiusY)}, {rng.nextRangeF(0.f, maxRadiusX), rng.nextRangeF(0.f, maxRadiusY)}, {rng.nextRangeF(0.f, maxRadiusX), rng.nextRangeF(0.f, maxRadiusY)}}; float maxLeft = std::max(radii[0].fX, radii[3].fX); float maxTop = std::max(radii[0].fY, radii[1].fY); float maxRight = std::max(radii[1].fX, radii[2].fX); float maxBottom = std::max(radii[2].fY, radii[3].fY); SkRect outer = SkRect::MakeWH(maxLeft + maxRight + innerWidth, maxTop + maxBottom + innerHeight); rr.setRectRadii(outer, radii); SkRect maxInner = SkRRectPriv::InnerBounds(rr); // Test upper limit on the size of 'maxInner' REPORTER_ASSERT(reporter, outer.contains(maxInner)); REPORTER_ASSERT(reporter, rr.contains(maxInner)); // Test lower limit on the size of 'maxInner' SkRect inner = SkRect::MakeXYWH(maxLeft, maxTop, innerWidth, innerHeight); inner.inset(kEpsilon, kEpsilon); if (inner.isSorted()) { REPORTER_ASSERT(reporter, maxInner.contains(inner)); } else { // Flipped from the inset, just test two points of inner float midX = maxLeft + 0.5f * innerWidth; float midY = maxTop + 0.5f * innerHeight; REPORTER_ASSERT(reporter, maxInner.contains(midX, maxTop)); REPORTER_ASSERT(reporter, maxInner.contains(midX, maxTop + innerHeight)); REPORTER_ASSERT(reporter, maxInner.contains(maxLeft, midY)); REPORTER_ASSERT(reporter, maxInner.contains(maxLeft + innerWidth, midY)); } } } namespace { // Helper to test expected intersection, relying on the fact that all round rect intersections // will have their bounds equal to the intersection of the bounds of the input round rects, and // their corner radii will be a one of A's, B's, or rectangular. enum CornerChoice : uint8_t { kA, kB, kRect }; static void verify_success( skiatest::Reporter* reporter, const SkRRect& a, const SkRRect& b, CornerChoice tl, CornerChoice tr, CornerChoice br, CornerChoice bl) { static const SkRRect kRect = SkRRect::MakeEmpty(); // has (0,0) for all corners // Compute expected round rect intersection given bounds of A and B, and the specified // corner choices for the 4 corners. SkRect expectedBounds; SkAssertResult(expectedBounds.intersect(a.rect(), b.rect())); SkVector radii[4] = { (tl == kA ? a : (tl == kB ? b : kRect)).radii(SkRRect::kUpperLeft_Corner), (tr == kA ? a : (tr == kB ? b : kRect)).radii(SkRRect::kUpperRight_Corner), (br == kA ? a : (br == kB ? b : kRect)).radii(SkRRect::kLowerRight_Corner), (bl == kA ? a : (bl == kB ? b : kRect)).radii(SkRRect::kLowerLeft_Corner)}; SkRRect expected; expected.setRectRadii(expectedBounds, radii); SkRRect actual = SkRRectPriv::ConservativeIntersect(a, b); // Intersections are commutative so ba and ab should be the same REPORTER_ASSERT(reporter, actual == SkRRectPriv::ConservativeIntersect(b, a)); // Intersection of the result with either A or B should remain the intersection REPORTER_ASSERT(reporter, actual == SkRRectPriv::ConservativeIntersect(actual, a)); REPORTER_ASSERT(reporter, actual == SkRRectPriv::ConservativeIntersect(actual, b)); // Bounds of intersection round rect should equal intersection of bounds of a and b REPORTER_ASSERT(reporter, actual.rect() == expectedBounds); // Use PathOps to confirm that the explicit round rect is correct. SkPath aPath, bPath, expectedPath; aPath.addRRect(a); bPath.addRRect(b); SkAssertResult(Op(aPath, bPath, kIntersect_SkPathOp, &expectedPath)); // The isRRect() heuristics in SkPath are based on having called addRRect(), so a path from // path ops that is a rounded rectangle will return false. However, if test XOR expected is // empty, then we know that the shapes were the same. SkPath testPath; testPath.addRRect(actual); SkPath empty; SkAssertResult(Op(testPath, expectedPath, kXOR_SkPathOp, &empty)); REPORTER_ASSERT(reporter, empty.isEmpty()); } static void verify_failure(skiatest::Reporter* reporter, const SkRRect& a, const SkRRect& b) { SkRRect intersection = SkRRectPriv::ConservativeIntersect(a, b); // Expected the intersection to fail (no intersection or complex intersection is not // disambiguated). REPORTER_ASSERT(reporter, intersection.isEmpty()); REPORTER_ASSERT(reporter, SkRRectPriv::ConservativeIntersect(b, a).isEmpty()); } } // namespace static void test_conservative_intersection(skiatest::Reporter* reporter) { // Helper to inline making an inset round rect auto make_inset = [](const SkRRect& r, float dx, float dy) { SkRRect i = r; i.inset(dx, dy); return i; }; // A is a wide, short round rect SkRRect a = SkRRect::MakeRectXY({0.f, 4.f, 16.f, 12.f}, 2.f, 2.f); // B is a narrow, tall round rect SkRRect b = SkRRect::MakeRectXY({4.f, 0.f, 12.f, 16.f}, 3.f, 3.f); // NOTE: As positioned by default, A and B intersect as the rectangle {4, 4, 12, 12}. // There is a 2 px buffer between the corner curves of A and the vertical edges of B, and // a 1 px buffer between the corner curves of B and the horizontal edges of A. Since the shapes // form a symmetric rounded cross, we can easily test edge and corner combinations by simply // flipping signs and/or swapping x and y offsets. // Successful intersection operations: // - for clarity these are formed by moving A around to intersect with B in different ways. // - the expected bounds of the round rect intersection is calculated automatically // in check_success, so all we have to specify are the expected corner radii // A and B intersect as a rectangle verify_success(reporter, a, b, kRect, kRect, kRect, kRect); // Move A to intersect B on a vertical edge, preserving two corners of A inside B verify_success(reporter, a.makeOffset(6.f, 0.f), b, kA, kRect, kRect, kA); verify_success(reporter, a.makeOffset(-6.f, 0.f), b, kRect, kA, kA, kRect); // Move B to intersect A on a horizontal edge, preserving two corners of B inside A verify_success(reporter, a, b.makeOffset(0.f, 6.f), kB, kB, kRect, kRect); verify_success(reporter, a, b.makeOffset(0.f, -6.f), kRect, kRect, kB, kB); // Move A to intersect B on a corner, preserving one corner of A and one of B verify_success(reporter, a.makeOffset(-7.f, -8.f), b, kB, kRect, kA, kRect); // TL of B verify_success(reporter, a.makeOffset(7.f, -8.f), b, kRect, kB, kRect, kA); // TR of B verify_success(reporter, a.makeOffset(7.f, 8.f), b, kA, kRect, kB, kRect); // BR of B verify_success(reporter, a.makeOffset(-7.f, 8.f), b, kRect, kA, kRect, kB); // BL of B // An inset is contained inside the original (note that SkRRect::inset modifies radii too) so // is returned unmodified when intersected. verify_success(reporter, a, make_inset(a, 1.f, 1.f), kB, kB, kB, kB); verify_success(reporter, make_inset(b, 2.f, 2.f), b, kA, kA, kA, kA); // A rectangle exactly matching the corners of the rrect bounds keeps the rrect radii, // regardless of whether or not it's the 1st or 2nd arg to ConservativeIntersect. SkRRect c = SkRRect::MakeRectXY({0.f, 0.f, 10.f, 10.f}, 2.f, 2.f); SkRRect cT = SkRRect::MakeRect({0.f, 0.f, 10.f, 5.f}); verify_success(reporter, c, cT, kA, kA, kRect, kRect); verify_success(reporter, cT, c, kB, kB, kRect, kRect); SkRRect cB = SkRRect::MakeRect({0.f, 5.f, 10.f, 10.}); verify_success(reporter, c, cB, kRect, kRect, kA, kA); verify_success(reporter, cB, c, kRect, kRect, kB, kB); SkRRect cL = SkRRect::MakeRect({0.f, 0.f, 5.f, 10.f}); verify_success(reporter, c, cL, kA, kRect, kRect, kA); verify_success(reporter, cL, c, kB, kRect, kRect, kB); SkRRect cR = SkRRect::MakeRect({5.f, 0.f, 10.f, 10.f}); verify_success(reporter, c, cR, kRect, kA, kA, kRect); verify_success(reporter, cR, c, kRect, kB, kB, kRect); // Failed intersection operations: // A and B's bounds do not intersect verify_failure(reporter, a.makeOffset(32.f, 0.f), b); // A and B's bounds intersect, but corner curves do not -> no intersection verify_failure(reporter, a.makeOffset(11.5f, -11.5f), b); // A is empty -> no intersection verify_failure(reporter, SkRRect::MakeEmpty(), b); // A is contained in B, but is too close to the corner curves for the conservative // approximations to construct a valid round rect intersection. verify_failure(reporter, make_inset(b, 0.3f, 0.3f), b); // A intersects a straight edge, but not far enough for B to contain A's corners verify_failure(reporter, a.makeOffset(2.5f, 0.f), b); verify_failure(reporter, a.makeOffset(-2.5f, 0.f), b); // And vice versa for B into A verify_failure(reporter, a, b.makeOffset(0.f, 1.5f)); verify_failure(reporter, a, b.makeOffset(0.f, -1.5f)); // A intersects a straight edge and part of B's corner verify_failure(reporter, a.makeOffset(5.f, -2.f), b); verify_failure(reporter, a.makeOffset(-5.f, -2.f), b); verify_failure(reporter, a.makeOffset(5.f, 2.f), b); verify_failure(reporter, a.makeOffset(-5.f, 2.f), b); // And vice versa verify_failure(reporter, a, b.makeOffset(3.f, -5.f)); verify_failure(reporter, a, b.makeOffset(-3.f, -5.f)); verify_failure(reporter, a, b.makeOffset(3.f, 5.f)); verify_failure(reporter, a, b.makeOffset(-3.f, 5.f)); // A intersects B on a corner, but the corner curves overlap each other verify_failure(reporter, a.makeOffset(8.f, 10.f), b); verify_failure(reporter, a.makeOffset(-8.f, 10.f), b); verify_failure(reporter, a.makeOffset(8.f, -10.f), b); verify_failure(reporter, a.makeOffset(-8.f, -10.f), b); // Another variant of corners overlapping, this is two circles of radius r that overlap by r // pixels (e.g. the leftmost point of the right circle touches the center of the left circle). // The key difference with the above case is that the intersection of the circle bounds have // corners that are contained in both circles, but because it is only r wide, can not satisfy // all corners having radii = r. float r = 100.f; a = SkRRect::MakeOval(SkRect::MakeWH(2 * r, 2 * r)); verify_failure(reporter, a, a.makeOffset(r, 0.f)); } DEF_TEST(RoundRect, reporter) { test_round_rect_basic(reporter); test_round_rect_rects(reporter); test_round_rect_ovals(reporter); test_round_rect_general(reporter); test_round_rect_iffy_parameters(reporter); test_inset(reporter); test_round_rect_contains_rect(reporter); test_round_rect_transform(reporter); test_issue_2696(reporter); test_tricky_radii(reporter); test_empty_crbug_458524(reporter); test_empty(reporter); test_read(reporter); test_inner_bounds(reporter); test_conservative_intersection(reporter); } DEF_TEST(RRect_fuzzer_regressions, r) { { unsigned char buf[] = {0x0a, 0x00, 0x00, 0xff, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x02, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x02, 0x00}; REPORTER_ASSERT(r, sizeof(buf) == SkRRect{}.readFromMemory(buf, sizeof(buf))); } { unsigned char buf[] = {0x5d, 0xff, 0xff, 0x5d, 0x0a, 0x60, 0x0a, 0x0a, 0x0a, 0x7e, 0x0a, 0x5a, 0x0a, 0x12, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x3a, 0x00, 0x00, 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x26, 0x0a, 0x0a, 0x0a, 0x0a, 0xff, 0xff, 0x0a, 0x0a}; REPORTER_ASSERT(r, sizeof(buf) == SkRRect{}.readFromMemory(buf, sizeof(buf))); } { unsigned char buf[] = {0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x04, 0xdd, 0xdd, 0x15, 0xfe, 0x00, 0x00, 0x04, 0x05, 0x7e, 0x00, 0x00, 0x00, 0xff, 0x08, 0x04, 0xff, 0xff, 0xfe, 0xfe, 0xff, 0x32, 0x32, 0x32, 0x32, 0x00, 0x32, 0x32, 0x04, 0xdd, 0x3d, 0x1c, 0xfe, 0x89, 0x04, 0x0a, 0x0e, 0x05, 0x7e, 0x0a}; REPORTER_ASSERT(r, sizeof(buf) == SkRRect{}.readFromMemory(buf, sizeof(buf))); } }
40.026134
100
0.634002
NearTox
d0c577cd46beffe2d8a2321287d9a7881fe253aa
1,777
cpp
C++
project/src/Leaderboard.cpp
lorenzovngl/progetto-grafica
0f222e62da703c323cdc0f7edb39ee89d3fe566a
[ "MIT" ]
null
null
null
project/src/Leaderboard.cpp
lorenzovngl/progetto-grafica
0f222e62da703c323cdc0f7edb39ee89d3fe566a
[ "MIT" ]
null
null
null
project/src/Leaderboard.cpp
lorenzovngl/progetto-grafica
0f222e62da703c323cdc0f7edb39ee89d3fe566a
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #endif #include "headers/Leaderboard.h" Leaderboard::Leaderboard(char *username){ setUsename(username); } char *Leaderboard::getUsename() { return mUsername; } void Leaderboard::setUsename(char *username) { strcpy(mUsername, username); } void Leaderboard::setNumBuoys(int num){ mNumBuoys = num; } Leaderboard::LBItem** Leaderboard::read(){ char name[50]; int num, score; FILE *file = fopen("leaderboard.txt","r"); int i = 0; while (fscanf(file, "%s\t%d\t%d\n", name, &num, &score) != EOF && i < LEADERBOARD_LENGHT){ int millis = score; int sec = millis/1000; int min = sec/60; items[i] = new LBItem(name, num, score); i++; }; while (i < LEADERBOARD_LENGHT){ items[i] = nullptr; i++; } fclose(file); return items; } void Leaderboard::insert(int timeScore) { read(); int i = 0, j; // Inserisco il punteggio nella posizione giusta per mantenere l'ordinamento decrescente while (i < LEADERBOARD_LENGHT && items[i] != nullptr && items[i]->time/items[i]->numBuoys <= timeScore/mNumBuoys){ i++; } for (j = LEADERBOARD_LENGHT - 1; j > i; j--){ items[j] = items[j-1]; } items[j] = new LBItem(mUsername, mNumBuoys, timeScore); FILE *file = fopen("leaderboard.txt","w"); for (i = 0; i < LEADERBOARD_LENGHT && items[i] != nullptr; i++){ fprintf(file, "%s\t%d\t%d\n", items[i]->name, items[i]->numBuoys, items[i]->time); } fclose(file); }
24.342466
118
0.608329
lorenzovngl
d0c98eb31a226532c4a5029954799c1c75cf8359
906
cpp
C++
CSES/Sorting And Searching/ArrayDivision.cpp
ShraxO1/OneDayOneAlgo
68fe90f642985680e4014fdd1fe2ecd30097661d
[ "MIT" ]
32
2020-05-23T07:40:31.000Z
2021-02-02T18:14:30.000Z
CSES/Sorting And Searching/ArrayDivision.cpp
ShraxO1/OneDayOneAlgo
68fe90f642985680e4014fdd1fe2ecd30097661d
[ "MIT" ]
45
2020-05-22T10:30:51.000Z
2020-12-28T08:17:13.000Z
CSES/Sorting And Searching/ArrayDivision.cpp
ShraxO1/OneDayOneAlgo
68fe90f642985680e4014fdd1fe2ecd30097661d
[ "MIT" ]
31
2020-05-22T10:18:16.000Z
2020-10-23T07:52:35.000Z
#include <iostream> #include<map> #include<vector> #include<algorithm> using namespace std; #define OJ \ freopen("input.txt", "r", stdin); \ freopen("output.txt", "w", stdout); #define FIO \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); #define ll long long int int n,k,a[500000]; bool ok(ll mid) { int num = 0, cur = 0; while (num < k && cur < n) { ll sum = 0; while (cur < n && sum+a[cur] <= mid) sum += a[cur++]; num ++; } return cur == n; } int main(){ //OJ; cin >> n >> k; ll sum = 0; for(ll i=0; i<n; i++){ cin >> a[i]; sum+=a[i]; } ll lo = 0, hi = 1e18; while (lo < hi) { ll mid = (lo+hi)/2; if (ok(mid)) hi = mid; else lo = mid+1; } cout << lo << endl;; return 0; }
19.695652
61
0.442605
ShraxO1
d0cbb04c1d00f83a39b1d1ab3677595c2e9d10ec
1,521
cpp
C++
Model-View/DataRole/main.cpp
BigWhiteCat/Qt-QML
7d601721db535167ea257e8baffc1de83cc0aa15
[ "MIT" ]
null
null
null
Model-View/DataRole/main.cpp
BigWhiteCat/Qt-QML
7d601721db535167ea257e8baffc1de83cc0aa15
[ "MIT" ]
null
null
null
Model-View/DataRole/main.cpp
BigWhiteCat/Qt-QML
7d601721db535167ea257e8baffc1de83cc0aa15
[ "MIT" ]
null
null
null
#include <QApplication> #include <QDebug> #include <QStandardItemModel> #include <QTreeView> int main(int argc, char **argv) { QApplication app(argc, argv); QStandardItemModel model; QStandardItem *parentItem = model.invisibleRootItem(); QStandardItem *item0 = new QStandardItem; item0->setText("A"); QPixmap pixmap0(50, 50); pixmap0.fill("red"); item0->setIcon(QIcon(pixmap0)); item0->setToolTip("indexA"); parentItem->appendRow(item0); parentItem = item0; QStandardItem *item1 = new QStandardItem; item1->setText("B"); QPixmap pixmap1(50, 50); pixmap1.fill("blue"); item1->setIcon(QIcon(pixmap1)); item1->setToolTip("indexB"); parentItem->appendRow(item1); QStandardItem *item2 = new QStandardItem; QPixmap pixmap2(50, 50); pixmap2.fill("green"); item2->setData("C", Qt::EditRole); item2->setData("indexC", Qt::ToolTipRole); item2->setData(QIcon(pixmap2), Qt::DisplayRole); parentItem->appendRow(item2); QTreeView treeView; treeView.setModel(&model); treeView.show(); QModelIndex indexA = model.index(0, 0, QModelIndex()); qDebug() << "indexA row count: " << model.rowCount(indexA); QModelIndex indexB = model.index(0, 0, indexA); qDebug() << "indexB row count: " << model.rowCount(indexB); qDebug() << "indexB text:" << model.data(indexB, Qt::EditRole).toString(); qDebug() << "indexB toolTip: " << model.data(indexB, Qt::ToolTipRole).toString(); return app.exec(); }
29.823529
85
0.65812
BigWhiteCat
d0d3fb20075e27b3eff9598a173568f29a0d07f8
4,613
cc
C++
asylo/test/loader/loader_test.cc
qinkunbao/asylo
6c6c4a185a1ee927996b43a060d924a49548d999
[ "Apache-2.0" ]
null
null
null
asylo/test/loader/loader_test.cc
qinkunbao/asylo
6c6c4a185a1ee927996b43a060d924a49548d999
[ "Apache-2.0" ]
null
null
null
asylo/test/loader/loader_test.cc
qinkunbao/asylo
6c6c4a185a1ee927996b43a060d924a49548d999
[ "Apache-2.0" ]
null
null
null
/* * * Copyright 2017 Asylo authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> #include <gtest/gtest.h> #include "absl/status/status.h" #include "asylo/client.h" #include "asylo/test/util/status_matchers.h" #include "asylo/util/status.h" #include "asylo/util/statusor.h" namespace asylo { namespace { using ::testing::Not; // Placeholder client implementation for a debug enclave. class TestClient : public EnclaveClient { public: TestClient() : EnclaveClient("test") {} Status EnterAndRun(const EnclaveInput &input, EnclaveOutput *output) override { return Status::OkStatus(); } private: Status EnterAndInitialize(const EnclaveConfig &config) override { return Status::OkStatus(); } Status EnterAndFinalize(const EnclaveFinal &final_input) override { return Status::OkStatus(); } Status DestroyEnclave() override { return Status::OkStatus(); } }; // Loader which always fails for testing. class FailingLoader : public EnclaveLoader { protected: StatusOr<std::unique_ptr<EnclaveClient>> LoadEnclave( absl::string_view name, void *base_address, const size_t enclave_size, const EnclaveConfig &config) const override { return Status(absl::StatusCode::kInvalidArgument, "Could not load enclave."); } EnclaveLoadConfig GetEnclaveLoadConfig() const override { EnclaveLoadConfig loader_config; return loader_config; } }; // Loads clients by default constructing T. template <typename T> class FakeLoader : public EnclaveLoader { public: ~FakeLoader() override = default; FakeLoader() = default; protected: StatusOr<std::unique_ptr<EnclaveClient>> LoadEnclave( absl::string_view name, void *base_address, const size_t enclave_size, const EnclaveConfig &config) const override { return std::unique_ptr<EnclaveClient>(new T()); } EnclaveLoadConfig GetEnclaveLoadConfig() const override { EnclaveLoadConfig loader_config; return loader_config; } }; class LoaderTest : public ::testing::Test { protected: void SetUp() override { EnclaveManager::Configure(EnclaveManagerOptions()); StatusOr<EnclaveManager *> manager_result = EnclaveManager::Instance(); if (!manager_result.ok()) { LOG(FATAL) << manager_result.status(); } manager_ = manager_result.ValueOrDie(); } EnclaveManager *manager_; FakeLoader<TestClient> loader_; }; // Basic overall test and demonstration of enclave lifecyle. TEST_F(LoaderTest, Overall) { Status status = manager_->LoadEnclave("/fake", loader_); ASSERT_THAT(status, IsOk()); EnclaveClient *client = manager_->GetClient("/fake"); ASSERT_NE(client, nullptr); EnclaveInput einput; status = client->EnterAndRun(einput, nullptr); ASSERT_THAT(status, IsOk()); EnclaveFinal efinal_input; status = manager_->DestroyEnclave(client, efinal_input); ASSERT_THAT(status, IsOk()); } // Ensure an enclave name cannot be reused. TEST_F(LoaderTest, DuplicateNamesFail) { Status status = manager_->LoadEnclave("/duplicate_names", loader_); ASSERT_THAT(status, IsOk()); // Check we can't load another enclave with the same path. status = manager_->LoadEnclave("/duplicate_names", loader_); ASSERT_THAT(status, Not(IsOk())); } // Ensure we can not fetch a client for a destroyed enclave. TEST_F(LoaderTest, FetchAfterDestroy) { Status status = manager_->LoadEnclave("/fetch_after_destroy", loader_); ASSERT_THAT(status, IsOk()); auto client = manager_->GetClient("/fetch_after_destroy"); ASSERT_NE(client, nullptr); EnclaveFinal final_input; status = manager_->DestroyEnclave(client, final_input); ASSERT_THAT(status, IsOk()); // Check we can't fetch a client to a destroyed enclave. client = manager_->GetClient("/fetch_after_destroy"); ASSERT_EQ(client, nullptr); } // Ensure that an error is reported on loading. TEST_F(LoaderTest, PropagateLoaderFailure) { FailingLoader loader; auto status = manager_->LoadEnclave("/fake", loader); ASSERT_THAT(status, Not(IsOk())); } }; // namespace }; // namespace asylo
28.83125
76
0.725775
qinkunbao
d0e2fd2f550b346519cc9e222304baaa651d8683
1,299
cpp
C++
ejercicios/cocineros/chef.cpp
jrinconada/cpp-examples
069e3cc910b2c2d0716af36bef28336003fb6d9e
[ "MIT" ]
1
2018-02-22T12:33:44.000Z
2018-02-22T12:33:44.000Z
ejercicios/cocineros/chef.cpp
jrinconada/cpp-examples
069e3cc910b2c2d0716af36bef28336003fb6d9e
[ "MIT" ]
null
null
null
ejercicios/cocineros/chef.cpp
jrinconada/cpp-examples
069e3cc910b2c2d0716af36bef28336003fb6d9e
[ "MIT" ]
null
null
null
#include <vector> #include <string> #include <mutex> #include "../../hilos/semaphore.cpp" #include "recipe.cpp" mutex knife; mutex oven; Semaphore semaphore; class Chef { void cut(Recipe* r) { lock_guard<mutex> guard(knife); for (int i = 0; i < r->cuttingTime; i++) { std::cout << name + " cortando " + r->name + ", " + to_string(i + 1) + " seg\n"; std::this_thread::sleep_for(std::chrono::seconds(1)); } } void bake(Recipe* r) { lock_guard<mutex> guard(oven); for (int i = 0; i < r->bakingTime; i++) { std::cout << name + " horneando " + r->name + ", " + to_string(i + 1) + " seg\n"; std::this_thread::sleep_for(std::chrono::seconds(1)); } r->prom.set_value(r->name); } public: vector<Recipe*> recipes; string name; string type; Chef(string n, string t = "") : name(n), type(t) {} void cook() { for (auto& r : recipes) { if (type == "cutter") { cut(r); semaphore.notify(); } else if (type == "baker") { semaphore.wait(); bake(r); } else { cut(r); bake(r); } } } };
24.980769
65
0.458814
jrinconada
d0e8105c9fc484adf8a360f7427a674672bb6d84
9,379
cpp
C++
src/chainsim/PuyoField.cpp
puyogg/puyo-chain-detector
b71811759c31dc5041d4f3b2d1c89bf7bec0d89f
[ "MIT" ]
5
2020-09-14T14:03:58.000Z
2022-01-21T04:03:08.000Z
src/chainsim/PuyoField.cpp
puyogg/puyo-chain-detector
b71811759c31dc5041d4f3b2d1c89bf7bec0d89f
[ "MIT" ]
5
2021-02-13T03:11:13.000Z
2022-03-12T00:54:25.000Z
src/chainsim/PuyoField.cpp
puyogg/puyo-chain-detector
b71811759c31dc5041d4f3b2d1c89bf7bec0d89f
[ "MIT" ]
2
2020-08-15T14:59:14.000Z
2020-08-15T16:34:53.000Z
#include "Fields.hpp" #include <queue> #include <iostream> namespace Chainsim { // Puyo Field class PuyoField::PuyoField() : Field<Color>(DEFAULT_ROWS, DEFAULT_COLS), m_hrows{ DEFAULT_HROWS }, m_puyoToPop{ DEFAULT_PUYOTOPOP } { m_data = std::vector<Color>(m_cols * m_rows, Color::NONE); m_bool = BoolField(m_rows, m_cols); m_chainLength = 0; } PuyoField::PuyoField(int rows, int cols) : Field<Color>(rows, cols), m_hrows{ DEFAULT_HROWS }, m_puyoToPop{ DEFAULT_PUYOTOPOP} { m_data = std::vector<Color>(m_cols * m_rows, Color::NONE); m_chainLength = 0; } PuyoField::PuyoField(int rows, int cols, int hrows) : Field<Color>(rows, cols), m_hrows{ hrows }, m_puyoToPop{ DEFAULT_PUYOTOPOP} { m_data = std::vector<Color>(m_cols * m_rows, Color::NONE); m_chainLength = 0; } PuyoField::PuyoField(int rows, int cols, int hrows, int puyoToPop) : Field<Color>(rows, cols), m_hrows{ hrows }, m_puyoToPop{ puyoToPop } { m_data = std::vector<Color>(m_cols * m_rows, Color::NONE); m_chainLength = 0; } void PuyoField::setIntField(std::vector<std::vector<int>> intVec2d) { int rows { static_cast<int>(intVec2d.size()) }; int cols { static_cast<int>(intVec2d.at(0).size()) }; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { Field<Color>::set(r, c, static_cast<Color>(intVec2d[r][c])); } } } void PuyoField::reset() { std::fill(m_data.begin(), m_data.end(), Color::NONE); } void PuyoField::dropPuyos() { // In each column... for (int c = 0; c < m_cols; c++) { int end = m_rows - 1; // Traverse the rows bottom to top for (int r = end; r >= 0; r--) { Color current = get(r, c); // If the current cell isn't empty... if (get(r, c) != Color::NONE) { // Move it to the cell currently marked as "end" set(end, c, current); // Empty the current cell if (r != end) set(r, c, Color::NONE); // Shift "end" to the next highest cell end--; } } } } bool PuyoField::isColoredAt(int row, int col) { Color cellColor{ get(row, col) }; return cellColor >= Color::RED && cellColor <= Color::PURPLE; } PopData PuyoField::checkPops() { PopCounts popCounts; PopColors popColors; PopPositions popPositions; m_bool.reset(); std::queue<Pos> checkQueue{}; // Find connected components for (int r = m_hrows; r < m_rows; r++) { for (int c = 0; c < m_cols; c++) { // If the cell has already been checked, or if it's empty, skip if (m_bool.get(r, c)) continue; Color color = get(r, c); // If the cell is empty or a garbage Puyo, skip if (color == Color::NONE || color == Color::GARBAGE) continue; // Otherwise, the cell is colored. Start a group search, starting // at the current position. std::vector<Pos> groupPositions{}; checkQueue.push(Pos{r, c}); while (checkQueue.size() > 0) { Pos current = checkQueue.front(); if (!m_bool.get(current.r, current.c)) { groupPositions.push_back(current); if (current.r > m_hrows && get(current.r - 1, current.c) == color) checkQueue.push(Pos{ current.r - 1, current.c }); if (current.r < m_rows - 1 && get(current.r + 1, current.c) == color) checkQueue.push(Pos{ current.r + 1, current.c }); if (current.c > 0 && get(current.r, current.c - 1) == color) checkQueue.push(Pos{ current.r, current.c - 1 }); if (current.c < m_cols - 1 && get(current.r, current.c + 1) == color) checkQueue.push(Pos{ current.r, current.c + 1 }); } checkQueue.pop(); // Mark the current cell as checked m_bool.set(current.r, current.c, true); } // Add data to lists if it meets the pop size if (static_cast<int>(groupPositions.size()) >= m_puyoToPop) { popCounts.push_back(static_cast<int>(groupPositions.size())); popColors.insert(color); popPositions.insert(popPositions.end(), groupPositions.begin(), groupPositions.end()); } } } bool hasPops{ static_cast<int>(popCounts.size()) > 0 }; // Check for adjacent Garbage Puyos and add those to pop positions std::vector<Pos> garbagePopPositions{}; for (Pos& pos : popPositions) { int r = pos.r; int c = pos.c; if (r > 0 && get(r - 1, c) == Color::GARBAGE) garbagePopPositions.push_back(Pos{ r - 1, c }); if (r < m_rows - 1 && get(r + 1, c) == Color::GARBAGE) garbagePopPositions.push_back(Pos{ r + 1, c }); if (c > 0 && get(r, c - 1) == Color::GARBAGE) garbagePopPositions.push_back(Pos{ r, c - 1 }); if (c < m_cols - 1 && get(r, c + 1) == Color::GARBAGE) garbagePopPositions.push_back(Pos{ r, c + 1 }); } popPositions.insert(popPositions.end(), garbagePopPositions.begin(), garbagePopPositions.end()); PopData result{ hasPops, popCounts, popColors, popPositions }; return result; } void PuyoField::applyPops(PopPositions& positions) { for (Pos& pos: positions) { set(pos.r, pos.c, Color::NONE); } } int PuyoField::simulate() { dropPuyos(); auto [hasPops, popCounts, popColors, popPositions] = checkPops(); if (hasPops) { m_chainLength++; applyPops(popPositions); simulate(); } return m_chainLength; } void PuyoField::removeFloaters() { for (int64_t c = 0; c < m_cols; c++) { for (int64_t r = m_rows - 2; r >= 0; r--) { bool isPuyo = get(r, c) != Color::NONE; bool belowIsNone = get(r + 1, c) == Color::NONE; if (isPuyo && belowIsNone) { set(r, c, Color::NONE); } } } } std::vector<Pos> PuyoField::surfacePositions() { // vector nesting: columns -> row std::vector<Pos> inds; for (int c = 0; c < m_cols; c++) { // Count the number of empty cells in a column int nones { -1 }; for (int r = 0; r < m_rows; r++) { if (get(r, c) == Color::NONE) nones++; } // Don't add columns that are completely full (-1) if (nones > -1) { Pos pos{ nones, c }; inds.push_back(pos); } } return inds; } std::vector<std::tuple<Pos, Color>> PuyoField::tryColorsAtPositions(std::vector<Pos>& positions) { std::vector<std::tuple<Pos, Color>> result; for (Pos& pos: positions) { int r = pos.r; int c = pos.c; // Try out colors based on the surrounding colors // Look left if (c > 0 && isColoredAt(r, c - 1)) { Pos tryPos{ r, c }; Color tryColor{ get(r, c - 1 ) }; result.push_back(std::tuple(tryPos, tryColor)); } // Look right if (c < m_cols - 1 && isColoredAt(r, c + 1)) { Pos tryPos{ r, c }; Color tryColor{ get(r, c + 1) }; result.push_back(std::tuple(tryPos, tryColor)); } // Look down if (r < m_rows - 1 && isColoredAt(r + 1, c)) { Pos tryPos{ r, c }; Color tryColor{ get(r + 1, c) }; result.push_back(std::tuple(tryPos, tryColor)); } } return result; } std::vector<PuyoField> PuyoField::fieldsToTry(std::vector<std::tuple<Pos, Color>>& colorsAtPositions) { std::vector<PuyoField> fields; for (auto& posCol : colorsAtPositions) { auto [pos, color] = posCol; PuyoField testField(m_rows, m_cols, m_hrows, m_puyoToPop); copyTo(testField); testField.set(pos.r, pos.c, color); // Try to add a second Puyo above to ensure a pop if (pos.r > 1) { testField.set(pos.r - 1, pos.c, color); } fields.push_back(testField); } return fields; } std::vector<std::tuple<Pos, Color, int>> PuyoField::searchForChains() { // Ignore floating Puyos removeFloaters(); // Calculate surface locations std::vector<Pos> positions{ surfacePositions() }; // Use those surface locations to find what colors to try at them std::vector<std::tuple<Pos, Color>> colorsAtPositions{ tryColorsAtPositions(positions) }; // Use the color+pos combination to generate fields. // Vector should be the same length as colorsAtPositions std::vector<PuyoField> tryFields{ fieldsToTry(colorsAtPositions) }; // Get the length of each chain std::vector<std::tuple<Pos, Color, int>> results; for (int i = 0; i < static_cast<int>(tryFields.size()); i++) { int length{ tryFields.at(i).simulate() }; if (length >= 2) { auto [pos, color] = colorsAtPositions.at(i); std::tuple<Pos, Color, int> result{ pos, color, length }; results.push_back(result); } } return results; } } // end Chainsim namespace
28.681957
139
0.549739
puyogg
d0e87fc80e8037fbf633aba724f01d79af7774ae
189
hh
C++
extern/polymesh/src/polymesh/detail/math.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/polymesh/src/polymesh/detail/math.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/polymesh/src/polymesh/detail/math.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once namespace polymesh::detail { template <class ScalarT> struct pos3 { ScalarT x; ScalarT y; ScalarT z; }; using pos3f = pos3<float>; using pos3d = pos3<double>; }
11.117647
27
0.666667
rovedit
d0ea73981db21847986e53689154cf0fbab6d01b
365
hpp
C++
Lodestar/aux/AlgebraicOperators.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
4
2020-06-05T14:08:23.000Z
2021-06-26T22:15:31.000Z
Lodestar/aux/AlgebraicOperators.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
2
2021-06-25T15:14:01.000Z
2021-07-01T17:43:20.000Z
Lodestar/aux/AlgebraicOperators.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
1
2021-06-16T03:15:23.000Z
2021-06-16T03:15:23.000Z
// // Created by Hamza El-Kebir on 6/12/21. // #ifndef LODESTAR_ALGEBRAICOPERATORS_HPP #define LODESTAR_ALGEBRAICOPERATORS_HPP enum class AlgebraicOperators { Addition, Subtraction, Multiplication, Division, Exponentiation }; template <AlgebraicOperators... TOps> struct AlgebraicOperatorsPack { }; #endif //LODESTAR_ALGEBRAICOPERATORS_HPP
16.590909
40
0.761644
helkebir
d0f692b7fa12559dfc2a02ac4e554c9e0949afcc
7,103
cpp
C++
src/grpc/quick/qquickgrpcsubscription.cpp
ddobrev/qtprotobuf
c31170f47341c1da9988f7a660be8261d6cdcc6e
[ "MIT" ]
null
null
null
src/grpc/quick/qquickgrpcsubscription.cpp
ddobrev/qtprotobuf
c31170f47341c1da9988f7a660be8261d6cdcc6e
[ "MIT" ]
null
null
null
src/grpc/quick/qquickgrpcsubscription.cpp
ddobrev/qtprotobuf
c31170f47341c1da9988f7a660be8261d6cdcc6e
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2020 Alexey Edelev <[email protected]> * * This file is part of qtprotobuf project https://git.semlanik.org/semlanik/qtprotobuf * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "qquickgrpcsubscription_p.h" #include <QGrpcSubscription> #include <QJSEngine> #include <QQmlEngine> using namespace QtProtobuf; QQuickGrpcSubscription::QQuickGrpcSubscription(QObject *parent) : QObject(parent) , m_enabled(false) , m_returnValue(nullptr) { } QQuickGrpcSubscription::~QQuickGrpcSubscription() { if (m_subscription) { m_subscription->cancel(); } delete m_returnValue; } void QQuickGrpcSubscription::updateSubscription() { if (m_subscription) { m_subscription->cancel(); m_subscription.reset(); } if (m_returnValue != nullptr) { m_returnValue->deleteLater(); //TODO: probably need to take care about return value cleanup other way. It's just reminder about weak memory management. m_returnValue = nullptr; returnValueChanged(); } if (m_client.isNull() || m_method.isEmpty() || !m_enabled || m_argument.isNull()) { return; } if (!subscribe()) { setEnabled(false); } } bool QQuickGrpcSubscription::subscribe() { QString uppercaseMethodName = m_method; uppercaseMethodName.replace(0, 1, m_method[0].toUpper()); const QMetaObject *metaObject = m_client->metaObject(); QMetaMethod method; for (int i = 0; i < metaObject->methodCount(); i++) { if (QString("qmlSubscribe%1Updates_p").arg(uppercaseMethodName) == metaObject->method(i).name()) { method = metaObject->method(i); break; } } QString errorString; if (!method.isValid()) { errorString = m_method + "is not either server or bidirectional stream."; qProtoWarning() << errorString; error({QGrpcStatus::Unimplemented, errorString}); return false; } if (method.parameterCount() < 2) { errorString = QString("Unable to call ") + method.name() + ". Invalid arguments set."; qProtoWarning() << errorString; error({QGrpcStatus::InvalidArgument, errorString}); return false; } QMetaType argumentPointerMetaType(method.parameterType(0)); if (argumentPointerMetaType.metaObject() != m_argument->metaObject()) { errorString = QString("Unable to call ") + method.name() + ". Argument type mismatch: '" + method.parameterTypes().at(0) + "' expected, '" + m_argument->metaObject()->className() + "' provided"; qProtoWarning() << errorString; error({QGrpcStatus::InvalidArgument, errorString}); return false; } QMetaType argumentMetaType(QMetaType::type(m_argument->metaObject()->className())); if (!argumentMetaType.isValid()) { errorString = QString("Argument of type '") + m_argument->metaObject()->className() + "' is not registred in metatype system"; qProtoWarning() << errorString; error({QGrpcStatus::InvalidArgument, errorString}); return false; } QObject *argument = reinterpret_cast<QObject*>(argumentMetaType.create(m_argument)); if (argument == nullptr) { errorString = "Unable to create argument copy. Unknown metatype system error"; qProtoWarning() << errorString; error({QGrpcStatus::InvalidArgument, errorString}); return false; } argument->deleteLater(); //TODO: probably need to take care about temporary argument value cleanup other way. It's just reminder about weak memory management. QMetaType returnPointerType(method.parameterType(1)); if (!returnPointerType.isValid()) { errorString = QString("Return type argument of type '") + method.parameterTypes().at(1) + "' is not registred in metatype system"; qProtoWarning() << errorString; error({QGrpcStatus::InvalidArgument, errorString}); return false; } QMetaType returnMetaType(QMetaType::type(returnPointerType.metaObject()->className())); if (!returnMetaType.isValid()) { errorString = QString("Unable to allocate return value. '") + returnPointerType.metaObject()->className() + "' is not registred in metatype system"; qProtoWarning() << errorString; error({QGrpcStatus::InvalidArgument, errorString}); return false; } m_returnValue = reinterpret_cast<QObject*>(returnMetaType.create()); qmlEngine(this)->setObjectOwnership(m_returnValue, QQmlEngine::CppOwnership); returnValueChanged(); if (m_returnValue == nullptr) { errorString = "Unable to allocate return value. Unknown metatype system error"; qProtoWarning() << errorString; error({QGrpcStatus::Unknown, errorString}); return false; } QGrpcSubscriptionShared subscription = nullptr; bool ok = method.invoke(m_client, Qt::DirectConnection, QGenericReturnArgument("QtProtobuf::QGrpcSubscriptionShared", static_cast<void *>(&subscription)), QGenericArgument(method.parameterTypes().at(0).data(), static_cast<const void *>(&argument)), QGenericArgument(method.parameterTypes().at(1).data(), static_cast<const void *>(&m_returnValue))); if (!ok || subscription == nullptr) { errorString = QString("Unable to call ") + m_method + " invalidate subscription."; qProtoWarning() << errorString; error({QGrpcStatus::Unknown, errorString}); return false; } m_subscription = subscription; connect(m_subscription.get(), &QGrpcSubscription::updated, this, [this](){ updated(qjsEngine(this)->toScriptValue(m_returnValue)); }); connect(m_subscription.get(), &QGrpcSubscription::error, this, &QQuickGrpcSubscription::error);//TODO: Probably it's good idea to disable subscription here connect(m_subscription.get(), &QGrpcSubscription::finished, this, [this](){ m_subscription.reset(); setEnabled(false); }); return true; }
40.129944
202
0.680276
ddobrev
d0fc826362cdafb1ef9725642c027f03f8041bf7
2,511
hpp
C++
include/range/v3/experimental/view/shared.hpp
berolinux/range-v3
d8ce45f1698931399fb09a322307eb95567be832
[ "MIT" ]
521
2016-02-14T00:39:01.000Z
2022-03-01T22:39:25.000Z
include/range/v3/experimental/view/shared.hpp
berolinux/range-v3
d8ce45f1698931399fb09a322307eb95567be832
[ "MIT" ]
8
2017-02-21T11:47:33.000Z
2018-11-01T09:37:14.000Z
include/range/v3/experimental/view/shared.hpp
berolinux/range-v3
d8ce45f1698931399fb09a322307eb95567be832
[ "MIT" ]
48
2017-02-21T10:18:13.000Z
2022-03-25T02:35:20.000Z
/// \file // Range v3 library // // Copyright Filip Matzner 2017 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_EXPERIMENTAL_VIEW_SHARED_HPP #define RANGES_V3_EXPERIMENTAL_VIEW_SHARED_HPP #include <memory> #include <type_traits> #include <meta/meta.hpp> #include <range/v3/range/access.hpp> #include <range/v3/range/concepts.hpp> #include <range/v3/range/primitives.hpp> #include <range/v3/view/all.hpp> namespace ranges { namespace experimental { template<typename Rng> struct shared_view : view_interface<shared_view<Rng>, range_cardinality<Rng>::value> { private: // shared storage std::shared_ptr<Rng> rng_ptr_; public: shared_view() = default; // construct from a range rvalue explicit shared_view(Rng && t) : rng_ptr_{std::make_shared<Rng>(std::move(t))} {} // use the stored range's begin and end iterator_t<Rng> begin() const { return ranges::begin(*rng_ptr_); } sentinel_t<Rng> end() const { return ranges::end(*rng_ptr_); } CPP_member auto CPP_fun(size)()(const requires sized_range<Rng>) { return ranges::size(*rng_ptr_); } }; /// \relates all /// \addtogroup group-views /// @{ namespace views { struct shared_fn : pipeable_base { public: template<typename Rng> auto operator()(Rng && t) const -> CPP_ret(shared_view<Rng>)( // requires range<Rng> && (!view_<Rng>)&&(!std::is_reference<Rng>::value)) { return shared_view<Rng>{std::move(t)}; } }; /// \relates all_fn /// \ingroup group-views RANGES_INLINE_VARIABLE(shared_fn, shared) template<typename Rng> using shared_t = detail::decay_t<decltype(shared(std::declval<Rng>()))>; } // namespace views /// @} } // namespace experimental } // namespace ranges #endif // include guard
27
84
0.545998
berolinux
cb9b706d6bd2c1b1d7243b87017c5e7361fd173c
443
cpp
C++
test/general/headers.cpp
komiga/Beard
059c7aed8c9d9818bcda2284c1e004309d70d2e1
[ "MIT" ]
3
2015-06-19T20:06:19.000Z
2019-04-11T20:04:00.000Z
test/general/headers.cpp
komiga/Beard
059c7aed8c9d9818bcda2284c1e004309d70d2e1
[ "MIT" ]
null
null
null
test/general/headers.cpp
komiga/Beard
059c7aed8c9d9818bcda2284c1e004309d70d2e1
[ "MIT" ]
null
null
null
#include <Beard/config.hpp> #include <Beard/utility.hpp> #include <Beard/ErrorCode.hpp> #include <Beard/aux.hpp> #include <Beard/String.hpp> #include <Beard/Error.hpp> #include <Beard/detail/gr_core.hpp> #include <Beard/detail/gr_ceformat.hpp> #include <Beard/detail/debug.hpp> #include <Beard/tty/Defs.hpp> #include <Beard/tty/Caps.hpp> #include <Beard/tty/TerminalInfo.hpp> #include <Beard/tty/Terminal.hpp> signed main() { return 0; }
20.136364
39
0.742664
komiga
cba1c45e531565fdd03678a71570e27ccb506fa4
5,693
cpp
C++
Simple++/Network/Server.cpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
Simple++/Network/Server.cpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
Simple++/Network/Server.cpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
#include "Server.h" namespace Network { Server::Server() : mIsBinded( false ) { } Server::~Server() { close(); } bool Server::listen( unsigned short port, SockType sockType, IpFamily ipFamily, int maxClients ) { return _listen( NULL, StringASCII( port ).getData(), sockType, ipFamily, maxClients ); } bool Server::listen( const StringASCII & address, const StringASCII & service, SockType sockType, IpFamily ipFamily, int maxClients ) { return _listen( address.getData(), service.getData(), sockType, ipFamily, maxClients ); } bool Server::listen( const StringASCII & address, unsigned int port, SockType sockType, IpFamily ipFamily, int maxClients ) { return _listen( address.getData(), StringASCII( port ).getData(), sockType, ipFamily, maxClients ); } bool Server::listen( const Address & address, int maxClients /*= 100*/ ) { if ( !Network::init() ) return false; AddrInfo thisAddrInfo( *( ( AddrInfo * ) &address ) ); if ( ( ( int ) _tryListen( &thisAddrInfo, maxClients ) ) == SOCKET_ERROR ) { error( StringASCII( "Unable to bind ip " ) << thisAddrInfo.getIpFamilyS() << " : " << thisAddrInfo.getNameInfo() << " on port " << thisAddrInfo.getPort() << " with protocol " << thisAddrInfo.getSockTypeS() ); return false; } updateFdSet(); this -> mIsBinded = true; return true; } bool Server::_listen( const char * ip, const char * service, SockType sockType, IpFamily ipFamily, int maxClients /*= 100*/ ) { if ( !Network::init() ) return false; AddrInfo hints( sockType, ipFamily ); hints.addFlag( Flags::Passive ); hints.addFlag( Flags::NumericHost ); struct addrinfo * addrResults; if ( ::getaddrinfo( ip, service, hints.getAddrInfoStruct(), &addrResults ) ) { error( StringASCII( "Unable to retreive address info on address " ) << ip << "@" << service ); return false; } if ( _tryListen( addrResults, maxClients ) == false ) { error( StringASCII( "Unable to bind on " ) << ( ( AddrInfo ) ( *addrResults ) ).getIpFamilyS() << " : " << ip << " on port " << service << " with Protocol " << ( ( AddrInfo ) ( *addrResults ) ).getSockTypeS() ); freeaddrinfo( addrResults ); return false; } freeaddrinfo( addrResults ); updateFdSet(); this -> mIsBinded = true; return true; } bool Server::_tryListen( const struct addrinfo * addrResults, int maxClients ) { Vector<const AddrInfo *> addrInfoVector; bool result = false; for ( const struct addrinfo * AI = addrResults; AI != NULL; AI = AI -> ai_next ) { AddrInfo * addrInfo = ( AddrInfo* ) AI; addrInfoVector.push( addrInfo ); if ( this -> mSocketVector.getSize() >= FD_SETSIZE ) { warn( "getaddrinfo returned more addresses than we could use.\n" ); break; } result = _tryListen( addrInfo, maxClients ) || result; } return result; } bool Server::_tryListen( AddrInfo * addrInfo, int maxClients ) { if ( addrInfo -> getIpFamily() == IpFamily::Undefined ) { addrInfo -> setIpFamily( IpFamily::IPv6 ); bool result2 = _tryListen( new Connection( *addrInfo ), maxClients ); addrInfo -> setIpFamily( IpFamily::IPv4 ); bool result1 = _tryListen( new Connection( *addrInfo ), maxClients ); return result2 || result1; } else { return _tryListen( new Connection( *addrInfo ), maxClients ); } return false; } bool Server::_tryListen( Connection * socket, int maxClients ) { if ( this -> mSocketVector.getSize() >= FD_SETSIZE ) { warn( "getaddrinfo returned more addresses than we could use.\n" ); return false; } if ( socket -> listen( maxClients ) ) { this -> mSocketVector.push( socket ); return true; } delete socket; return false; } bool Server::close() { if ( !this -> mIsBinded ) return false; for ( unsigned int i = 0; i < this -> mSocketVector.getSize(); i++ ) { this -> mSocketVector[i] -> close(); delete this -> mSocketVector[i]; } this -> mSocketVector.clear(); this -> mIsBinded = false; return true; } bool Server::accept( Connection * clientSocket ) { if ( getNumConnections() == 1 ) return this -> mSocketVector[0] -> accept( clientSocket ); Connection * selectedSocket = _select(); if ( selectedSocket ) return selectedSocket -> accept( clientSocket ); else return false; } void Server::updateFdSet() { this -> mFdSet.fd_count = ( u_int ) Math::min<Vector<Connection * >::Size>( this -> mSocketVector.getSize(), FD_SETSIZE ); for ( unsigned int i = 0; i < this -> mFdSet.fd_count; i++ ) { this -> mFdSet.fd_array[i] = this -> mSocketVector[i] -> getSocket(); } } typename Vector<Connection * >::Size Server::getNumConnections() const { return this -> mSocketVector.getSize(); } size_t Server::getMaximumNbConnections() { return FD_SETSIZE; } Connection * Server::_select() { if ( this -> mFdSet.fd_count > 0 ) { memcpy( &this -> mFdSetTmp, &this -> mFdSet, sizeof( fd_set ) ); if ( ::select( ( int ) getNumConnections(), &this -> mFdSetTmp, 0, 0, 0 ) == SOCKET_ERROR ) { error( "Select failed !" ); return NULL; } while ( this -> mFdSetTmp.fd_count > 0 ) { this -> mFdSetTmp.fd_count--; SOCKET activeSocket = this -> mFdSetTmp.fd_array[this -> mFdSetTmp.fd_count]; for ( auto i = this -> mSocketVector.begin(); i != this -> mSocketVector.end(); i++ ) { if ( ( *i ) -> getSocket() == activeSocket ) { return ( *i ); } } } } return NULL; } int Server::receive( char * buffer, int maxSize, Address * addressFrom ) { Connection * selectedSocket = _select(); if ( selectedSocket ) return selectedSocket -> receive( buffer, maxSize, addressFrom ); else return 0; } }
26.47907
214
0.645003
Oriode
cba2f72867e76b7d13524f329bd0189683090056
7,325
cpp
C++
src/lib/analysis/advisor/Inspection.cpp
GVProf/hpctoolkit
baf45028ead83ceba3e952bb8d0b14caf9ea5f78
[ "BSD-3-Clause" ]
null
null
null
src/lib/analysis/advisor/Inspection.cpp
GVProf/hpctoolkit
baf45028ead83ceba3e952bb8d0b14caf9ea5f78
[ "BSD-3-Clause" ]
null
null
null
src/lib/analysis/advisor/Inspection.cpp
GVProf/hpctoolkit
baf45028ead83ceba3e952bb8d0b14caf9ea5f78
[ "BSD-3-Clause" ]
2
2021-11-30T18:24:10.000Z
2022-02-13T18:13:17.000Z
//************************* System Include Files **************************** #include <fstream> #include <iostream> #include <iomanip> #include <climits> #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <stack> #include <typeinfo> #include <unordered_map> #include <sys/stat.h> //*************************** User Include Files **************************** #include <include/gcc-attr.h> #include <include/gpu-metric-names.h> #include <include/uint.h> #include "GPUOptimizer.hpp" #include "Inspection.hpp" using std::string; #include <lib/prof/CCT-Tree.hpp> #include <lib/prof/Metric-ADesc.hpp> #include <lib/prof/Metric-Mgr.hpp> #include <lib/prof/Struct-Tree.hpp> #include <lib/profxml/PGMReader.hpp> #include <lib/profxml/XercesUtil.hpp> #include <lib/prof-lean/hpcrun-metric.h> #include <lib/binutils/LM.hpp> #include <lib/binutils/VMAInterval.hpp> #include <lib/xml/xml.hpp> #include <lib/support/IOUtil.hpp> #include <lib/support/Logic.hpp> #include <lib/support/StrUtil.hpp> #include <lib/support/diagnostics.h> #include <iostream> #include <vector> namespace Analysis { std::stack<Prof::Struct::Alien *> InspectionFormatter::getInlineStack(Prof::Struct::ACodeNode *stmt) { std::stack<Prof::Struct::Alien *> st; Prof::Struct::Alien *alien = stmt->ancestorAlien(); while (alien) { st.push(alien); auto *stmt = alien->parent(); if (stmt) { alien = stmt->ancestorAlien(); } else { break; } }; return st; } std::string SimpleInspectionFormatter::formatInlineStack( std::stack<Prof::Struct::Alien *> &inline_stack) { std::stringstream ss; ss << "Inline stack: " << std::endl; while (inline_stack.empty() == false) { auto *inline_struct = inline_stack.top(); inline_stack.pop(); // Current inline stack line mapping information is not accurate //ss << "Line " << inline_struct->begLine() << ss << " " << inline_struct->fileName() << std::endl; } return ss.str(); } std::string SimpleInspectionFormatter::format(const Inspection &inspection) { std::stringstream ss; std::string sep = "------------------------------------------" "--------------------------------------------------"; std::string indent = " "; // Debug //std::cout << "Apply " << inspection.optimization << " optimization," << std::endl; // Overview ss << indent << "Apply " << inspection.optimization << " optimization,"; ss << std::fixed << std::setprecision(3); ss << " ratio " << inspection.ratios.back() * 100 << "%,"; ss << " estimate speedup " << inspection.speedups.back() << "x" << std::endl; indent += " "; ss << indent << inspection.hint << std::endl; // Specific suggestion if (inspection.active_warp_count.first != -1) { ss << indent << "Adjust #active_warps: " << inspection.active_warp_count.first; if (inspection.active_warp_count.second != -1) { ss << " to " << inspection.active_warp_count.second; } ss << std::endl; } if (inspection.thread_count.first != -1) { ss << indent << "Adjust #threads: " << inspection.thread_count.first; if (inspection.thread_count.second != -1) { ss << " to " << inspection.thread_count.second; } ss << std::endl; } if (inspection.block_count.first != -1) { ss << indent << "Adjust #blocks: " << inspection.block_count.first; if (inspection.block_count.second != -1) { ss << " to " << inspection.block_count.second; } ss << std::endl; } if (inspection.reg_count.first != -1) { ss << indent << "Adjust #regs: " << inspection.reg_count.first; if (inspection.reg_count.second != -1) { ss << " to " << inspection.reg_count.second; } ss << std::endl; } // Hot regions for (size_t index = 0; index < inspection.regions.size(); ++index) { auto &region_blame = inspection.regions[index]; auto ratio = 0.0; auto speedup = 0.0; if (inspection.loop) { ratio = inspection.ratios[index]; speedup = inspection.speedups[index]; } else { auto metric = inspection.stall ? region_blame.stall_blame : region_blame.lat_blame; ratio = metric / inspection.total; } ss << indent << index + 1 << ". Hot " << region_blame.blame_name << " code, ratio " << ratio * 100 << "%, "; if (speedup != 0.0) { ss << "speedup " << speedup << "x"; } if (inspection.density.size() != 0.0) { ss << ", density " << inspection.density[index] * 100 << "%"; } ss << std::endl; std::vector<InstructionBlame> inst_blames; if (inspection.hotspots.size() != 0) { inst_blames = inspection.hotspots[index]; } else { inst_blames.push_back(region_blame); } std::string prefix = " "; for (auto &inst_blame : inst_blames) { auto inst_blame_ratio = 0.0; auto inst_blame_metric = inspection.stall ? inst_blame.stall_blame : inst_blame.lat_blame; inst_blame_ratio = inst_blame_metric / inspection.total; ss << indent + prefix << "Hot " << inst_blame.blame_name << " code, ratio " << inst_blame_ratio * 100 << "%, distance " << inst_blame.distance << std::endl; auto *src_struct = inst_blame.src_struct; auto *dst_struct = inst_blame.dst_struct; auto *src_func = src_struct->ancestorProc(); auto *dst_func = dst_struct->ancestorProc(); auto src_vma = inst_blame.src_inst == NULL ? src_struct->vmaSet().begin()->beg() : (inst_blame.src_inst)->pc - src_func->vmaSet().begin()->beg(); auto dst_vma = inst_blame.dst_inst == NULL ? dst_struct->vmaSet().begin()->beg() : (inst_blame.dst_inst)->pc - dst_func->vmaSet().begin()->beg(); // Print inline call stack std::stack<Prof::Struct::Alien *> src_inline_stack = getInlineStack(src_struct); std::stack<Prof::Struct::Alien *> dst_inline_stack = getInlineStack(dst_struct); auto *src_file = src_struct->ancestorFile(); ss << indent + prefix + prefix << "From " << src_func->name() << " at " << src_file->name() << ":" << src_file->begLine() << std::endl; if (src_inline_stack.empty() == false) { ss << indent + prefix + prefix + prefix << formatInlineStack(src_inline_stack); } ss << indent + prefix + prefix + prefix << std::hex << "0x" << src_vma << std::dec << " at " << "Line " << src_struct->begLine(); if (inspection.loop) { auto *loop = src_struct->ancestorLoop(); if (loop) { ss << " in Loop at Line " << loop->begLine(); } } ss << std::endl; auto *dst_file = dst_struct->ancestorFile(); ss << indent + prefix + prefix << "To " << dst_func->name() << " at " << dst_file->name() << ":" << dst_file->begLine() << std::endl; if (dst_inline_stack.empty() == false) { ss << indent + prefix + prefix + prefix << formatInlineStack(dst_inline_stack); } ss << indent + prefix + prefix + prefix << std::hex << "0x" << dst_vma << std::dec << " at " << "Line " << dst_struct->begLine() << std::endl; } if (inspection.callback != NULL) { ss << inspection.callback(region_blame) << std::endl; } ss << std::endl; } ss << sep << std::endl; return ss.str(); }; } // namespace Analysis
29.53629
107
0.593857
GVProf
cba8b71b091fd3417882130d65401db0d0994a62
7,784
cpp
C++
DisPG/DisPG/util.cpp
hackflame/PgResarch
5a2bb5433aae617cf9737bd1efc1643886f6bcf5
[ "MIT" ]
228
2015-01-04T01:28:05.000Z
2022-03-28T01:37:46.000Z
DisPG/DisPG/util.cpp
zgz715/PgResarch
5a2bb5433aae617cf9737bd1efc1643886f6bcf5
[ "MIT" ]
3
2015-07-24T04:34:05.000Z
2018-10-07T06:08:57.000Z
DisPG/DisPG/util.cpp
zgz715/PgResarch
5a2bb5433aae617cf9737bd1efc1643886f6bcf5
[ "MIT" ]
111
2015-01-05T19:32:10.000Z
2021-11-24T03:07:26.000Z
// // This module implements auxiliary functions. These functions do not have // prefixes on their names. // #include "stdafx.h" #include "util.h" //////////////////////////////////////////////////////////////////////////////// // // macro utilities // //////////////////////////////////////////////////////////////////////////////// // // constants and macros // // Tag used for memory allocation APIs static const LONG UTIL_TAG = 'util'; // Change it to 0xCC when you want to install break points for patched code static const UCHAR UTIL_HOOK_ENTRY_CODE = 0x90; // Page table related #ifndef PXE_BASE #define PXE_BASE 0xFFFFF6FB7DBED000UI64 #define PPE_BASE 0xFFFFF6FB7DA00000UI64 #define PDE_BASE 0xFFFFF6FB40000000UI64 #define PTE_BASE 0xFFFFF68000000000UI64 #define PTI_SHIFT 12 #define PDI_SHIFT 21 #define PPI_SHIFT 30 #define PXI_SHIFT 39 #define PXE_PER_PAGE 512 #define PXI_MASK (PXE_PER_PAGE - 1) #endif //////////////////////////////////////////////////////////////////////////////// // // types // //////////////////////////////////////////////////////////////////////////////// // // prototypes // //////////////////////////////////////////////////////////////////////////////// // // variables // //////////////////////////////////////////////////////////////////////////////// // // implementations // // Disable the write protection EXTERN_C void Ia32DisableWriteProtect() { CR0_REG Cr0 = {}; Cr0.All = __readcr0(); Cr0.Field.WP = FALSE; __writecr0(Cr0.All); } // Enable the write protection EXTERN_C void Ia32EnableWriteProtect() { CR0_REG Cr0 = {}; Cr0.All = __readcr0(); Cr0.Field.WP = TRUE; __writecr0(Cr0.All); } // Return an address of PXE EXTERN_C PHARDWARE_PTE MiAddressToPxe( __in void* Address) { ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PXI_SHIFT - 3); Offset &= (PXI_MASK << 3); return reinterpret_cast<PHARDWARE_PTE>(PXE_BASE + Offset); } // Return an address of PPE EXTERN_C PHARDWARE_PTE MiAddressToPpe( __in void* Address) { ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PPI_SHIFT - 3); Offset &= (0x3FFFF << 3); return reinterpret_cast<PHARDWARE_PTE>(PPE_BASE + Offset); } // Return an address of PDE EXTERN_C PHARDWARE_PTE MiAddressToPde( __in void* Address) { ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PDI_SHIFT - 3); Offset &= (0x7FFFFFF << 3); return reinterpret_cast<PHARDWARE_PTE>(PDE_BASE + Offset); } // Return an address of PTE EXTERN_C PHARDWARE_PTE MiAddressToPte( __in void* Address) { ULONG64 Offset = reinterpret_cast<ULONG64>(Address) >> (PTI_SHIFT - 3); Offset &= (0xFFFFFFFFFULL << 3); return reinterpret_cast<PHARDWARE_PTE>(PTE_BASE + Offset); } // Return a number of processors EXTERN_C ULONG KeQueryActiveProcessorCountCompatible( __out_opt PKAFFINITY ActiveProcessors) { #if (NTDDI_VERSION >= NTDDI_VISTA) return KeQueryActiveProcessorCount(ActiveProcessors); #else ULONG numberOfProcessors = 0; KAFFINITY affinity = KeQueryActiveProcessors(); if (ActiveProcessors) { *ActiveProcessors = affinity; } for (; affinity; affinity >>= 1) { if (affinity & 1) { numberOfProcessors++; } } return numberOfProcessors; #endif } // Execute a given callback routine on all processors in DPC_LEVEL. Returns // STATUS_SUCCESS when all callback returned STATUS_SUCCESS as well. When // one of callbacks returns anything but STATUS_SUCCESS, this function stops // to call remaining callbacks and returns the value. EXTERN_C NTSTATUS ForEachProcessors( __in NTSTATUS(*CallbackRoutine)(void*), __in_opt void* Context) { const auto numberOfProcessors = KeQueryActiveProcessorCountCompatible(nullptr); for (ULONG processorNumber = 0; processorNumber < numberOfProcessors; processorNumber++) { // Switch the current processor KeSetSystemAffinityThread(static_cast<KAFFINITY>(1ull << processorNumber)); const auto oldIrql = KeRaiseIrqlToDpcLevel(); // Execute callback const auto status = CallbackRoutine(Context); KeLowerIrql(oldIrql); KeRevertToUserAffinityThread(); if (!NT_SUCCESS(status)) { return status; } } return STATUS_SUCCESS; } // Random memory version strstr() EXTERN_C void* MemMem( __in const void* SearchBase, __in SIZE_T SearchSize, __in const void* Pattern, __in SIZE_T PatternSize) { ASSERT(SearchBase); ASSERT(SearchSize); ASSERT(Pattern); ASSERT(PatternSize); if (PatternSize > SearchSize) { return nullptr; } auto searchBase = static_cast<const char*>(SearchBase); for (size_t i = 0; i <= SearchSize - PatternSize; i++) { if (!memcmp(Pattern, &searchBase[i], PatternSize)) { return const_cast<char*>(&searchBase[i]); } } return nullptr; } // Replaces placeholder (0xffffffffffffffff) in AsmHandler with a given // ReturnAddress. AsmHandler does not has to be writable. Race condition between // multiple processors should be taken care of by a programmer it exists; this // function does not care about it. EXTERN_C void FixupAsmCode( __in ULONG_PTR ReturnAddress, __in ULONG_PTR AsmHandler, __in ULONG_PTR AsmHandlerEnd) { ASSERT(AsmHandlerEnd > AsmHandler); SIZE_T asmHandlerSize = AsmHandlerEnd - AsmHandler; ULONG_PTR pattern = 0xffffffffffffffff; auto returnAddr = MemMem(reinterpret_cast<void*>(AsmHandler), asmHandlerSize, &pattern, sizeof(pattern)); ASSERT(returnAddr); PatchReal(returnAddr, &ReturnAddress, sizeof(ReturnAddress)); } // Install a hook on PatchAddress by overwriting original code with JMP code // that transfer execution to JumpDestination without modifying any registers. // PatchAddress does not has to be writable. Race condition between multiple // processors should be taken care of by a programmer it exists; this function // does not care about it. EXTERN_C void InstallJump( __in ULONG_PTR PatchAddress, __in ULONG_PTR JumpDestination) { // Code used to overwrite PatchAddress UCHAR patchCode[] = { UTIL_HOOK_ENTRY_CODE, // nop or int 3 0x50, // push rax 0x48, 0xB8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // mov rax, 0ffffffffffffffffh 0x48, 0x87, 0x04, 0x24, // xchg rax, [rsp] 0xC3, // ret }; C_ASSERT(sizeof(patchCode) == 17); // Replace placeholder (0xffffffffffffffff) located at offset 4 of patchCode // with JumpDestination *reinterpret_cast<ULONG_PTR*>(patchCode + 4) = JumpDestination; // And install patch PatchReal(reinterpret_cast<void*>(PatchAddress), patchCode, sizeof(patchCode)); } // Overwrites PatchAddr with PatchCode with disabling write protection and // raising IRQL in order to avoid race condition on this processor. EXTERN_C void PatchReal( __in void* PatchAddr, __in const void* PatchCode, __in SIZE_T PatchBytes) { const auto oldIrql = KeRaiseIrqlToDpcLevel(); Ia32DisableWriteProtect(); memcpy(PatchAddr, PatchCode, PatchBytes); __writecr3(__readcr3()); KeLowerIrql(oldIrql); Ia32EnableWriteProtect(); } // Returns true if the address is canonical address EXTERN_C bool IsCanonicalAddress( __in ULONG_PTR Address) { return ( (Address & 0xFFFF000000000000) == 0xFFFF000000000000 || (Address & 0xFFFF000000000000) == 0); }
26.297297
98
0.635149
hackflame
cba99ee10cd3b28bf2f9e3779c82bcf228c13d5e
13,472
cpp
C++
src/vidhrdw/lwings.cpp
pierrelouys/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
1
2021-01-25T20:16:33.000Z
2021-01-25T20:16:33.000Z
src/vidhrdw/lwings.cpp
pierrelouys/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
1
2021-05-24T20:28:35.000Z
2021-05-25T14:44:54.000Z
src/vidhrdw/lwings.cpp
PSP-Archive/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
null
null
null
/*************************************************************************** vidhrdw.c Functions to emulate the video hardware of the machine. ***************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" #include "osdepend.h" unsigned char *lwings_backgroundram; unsigned char *lwings_backgroundattribram; int lwings_backgroundram_size; unsigned char *lwings_scrolly; unsigned char *lwings_scrollx; unsigned char *trojan_scrolly; unsigned char *trojan_scrollx; unsigned char *trojan_bk_scrolly; unsigned char *trojan_bk_scrollx; static unsigned char *dirtybuffer2; static unsigned char *dirtybuffer4; static struct osd_bitmap *tmpbitmap2; static struct osd_bitmap *tmpbitmap3; /*************************************************************************** Start the video hardware emulation. ***************************************************************************/ int lwings_vh_start(void) { int i; if (generic_vh_start() != 0) return 1; if ((dirtybuffer2 = (unsigned char *)gp2x_malloc(lwings_backgroundram_size)) == 0) { generic_vh_stop(); return 1; } fast_memset(dirtybuffer2,1,lwings_backgroundram_size); if ((dirtybuffer4 = (unsigned char *)gp2x_malloc(lwings_backgroundram_size)) == 0) { generic_vh_stop(); return 1; } fast_memset(dirtybuffer4,1,lwings_backgroundram_size); /* the background area is twice as tall as the screen */ if ((tmpbitmap2 = osd_new_bitmap(2*Machine->drv->screen_width, 2*Machine->drv->screen_height,Machine->scrbitmap->depth)) == 0) { gp2x_free(dirtybuffer2); generic_vh_stop(); return 1; } #define COLORTABLE_START(gfxn,color_code) Machine->drv->gfxdecodeinfo[gfxn].color_codes_start + \ color_code * Machine->gfx[gfxn]->color_granularity #define GFX_COLOR_CODES(gfxn) Machine->gfx[gfxn]->total_colors #define GFX_ELEM_COLORS(gfxn) Machine->gfx[gfxn]->color_granularity fast_memset(palette_used_colors,PALETTE_COLOR_UNUSED,Machine->drv->total_colors * sizeof(unsigned char)); /* chars */ for (i = 0;i < GFX_COLOR_CODES(0);i++) { fast_memset(&palette_used_colors[COLORTABLE_START(0,i)], PALETTE_COLOR_USED, GFX_ELEM_COLORS(0)); palette_used_colors[COLORTABLE_START(0,i) + GFX_ELEM_COLORS(0)-1] = PALETTE_COLOR_TRANSPARENT; } /* bg tiles */ for (i = 0;i < GFX_COLOR_CODES(1);i++) { fast_memset(&palette_used_colors[COLORTABLE_START(1,i)], PALETTE_COLOR_USED, GFX_ELEM_COLORS(1)); } /* sprites */ for (i = 0;i < GFX_COLOR_CODES(2);i++) { fast_memset(&palette_used_colors[COLORTABLE_START(2,i)], PALETTE_COLOR_USED, GFX_ELEM_COLORS(2)); } return 0; } /*************************************************************************** Stop the video hardware emulation. ***************************************************************************/ void lwings_vh_stop(void) { osd_free_bitmap(tmpbitmap2); gp2x_free(dirtybuffer2); gp2x_free(dirtybuffer4); generic_vh_stop(); } void lwings_background_w(int offset,int data) { if (lwings_backgroundram[offset] != data) { lwings_backgroundram[offset] = data; dirtybuffer2[offset] = 1; } } void lwings_backgroundattrib_w(int offset,int data) { if (lwings_backgroundattribram[offset] != data) { lwings_backgroundattribram[offset] = data; dirtybuffer4[offset] = 1; } } /*************************************************************************** Draw the game screen in the given osd_bitmap. Do NOT call osd_update_display() from this function, it will be called by the main emulation engine. ***************************************************************************/ void lwings_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh) { int offs; if (palette_recalc()) { fast_memset(dirtybuffer2,1,lwings_backgroundram_size); fast_memset(dirtybuffer4,1,lwings_backgroundram_size); } for (offs = lwings_backgroundram_size - 1;offs >= 0;offs--) { int sx,sy, colour; /* Tiles ===== 0x80 Tile code MSB 0x40 Tile code MSB 0x20 Tile code MSB 0x10 X flip 0x08 Y flip 0x04 Colour 0x02 Colour 0x01 Colour */ colour=(lwings_backgroundattribram[offs] & 0x07); if (dirtybuffer2[offs] != 0 || dirtybuffer4[offs] != 0) { int code; dirtybuffer2[offs] = dirtybuffer4[offs] = 0; sx = offs / 32; sy = offs % 32; code=lwings_backgroundram[offs]; code+=((((int)lwings_backgroundattribram[offs]) &0xe0) <<3); drawgfx(tmpbitmap2,Machine->gfx[1], code, colour, (lwings_backgroundattribram[offs] & 0x08), (lwings_backgroundattribram[offs] & 0x10), 16 * sx,16 * sy, 0,TRANSPARENCY_NONE,0); } } /* copy the background graphics */ { int scrollx,scrolly; scrolly = -(lwings_scrollx[0] + 256 * lwings_scrollx[1]); scrollx = -(lwings_scrolly[0] + 256 * lwings_scrolly[1]); copyscrollbitmap(bitmap,tmpbitmap2,1,&scrollx,1,&scrolly,&Machine->drv->visible_area,TRANSPARENCY_NONE,0); } /* Draw the sprites. */ for (offs = spriteram_size - 4;offs >= 0;offs -= 4) { int code,sx,sy; /* Sprites ======= 0x80 Sprite code MSB 0x40 Sprite code MSB 0x20 Colour 0x10 Colour 0x08 Colour 0x04 Y flip 0x02 X flip 0x01 X MSB */ sx = spriteram[offs + 3] - 0x100 * (spriteram[offs + 1] & 0x01); sy = spriteram[offs + 2]; if (sx && sy) { code = spriteram[offs]; code += (spriteram[offs + 1] & 0xc0) << 2; drawgfx(bitmap,Machine->gfx[2], code, (spriteram[offs + 1] & 0x38) >> 3, spriteram[offs + 1] & 0x02,spriteram[offs + 1] & 0x04, sx,sy, &Machine->drv->visible_area,TRANSPARENCY_PEN,15); } } /* draw the frontmost playfield. They are characters, but draw them as sprites */ for (offs = videoram_size - 1;offs >= 0;offs--) { int sx,sy; sx = offs % 32; sy = offs / 32; drawgfx(bitmap,Machine->gfx[0], videoram[offs] + 4 * (colorram[offs] & 0xc0), colorram[offs] & 0x0f, colorram[offs] & 0x10,colorram[offs] & 0x20, 8*sx,8*sy, &Machine->drv->visible_area,TRANSPARENCY_PEN,3); } } /* TROJAN ====== Differences: Tile attribute (no y flip, possible priority) Sprite attribute (more sprites) Extra scroll layer */ int trojan_vh_start(void) { int i; if (generic_vh_start() != 0) return 1; if ((dirtybuffer2 = (unsigned char *)gp2x_malloc(lwings_backgroundram_size)) == 0) { generic_vh_stop(); return 1; } fast_memset(dirtybuffer2,1,lwings_backgroundram_size); if ((dirtybuffer4 = (unsigned char *)gp2x_malloc(lwings_backgroundram_size)) == 0) { generic_vh_stop(); return 1; } fast_memset(dirtybuffer4,1,lwings_backgroundram_size); if ((tmpbitmap3 = osd_new_bitmap(16*0x12, 16*0x12,Machine->scrbitmap->depth)) == 0) { gp2x_free(dirtybuffer4); gp2x_free(dirtybuffer2); generic_vh_stop(); return 1; } #define COLORTABLE_START(gfxn,color_code) Machine->drv->gfxdecodeinfo[gfxn].color_codes_start + \ color_code * Machine->gfx[gfxn]->color_granularity #define GFX_COLOR_CODES(gfxn) Machine->gfx[gfxn]->total_colors #define GFX_ELEM_COLORS(gfxn) Machine->gfx[gfxn]->color_granularity fast_memset(palette_used_colors,PALETTE_COLOR_UNUSED,Machine->drv->total_colors * sizeof(unsigned char)); /* chars */ for (i = 0;i < GFX_COLOR_CODES(0);i++) { fast_memset(&palette_used_colors[COLORTABLE_START(0,i)], PALETTE_COLOR_USED, GFX_ELEM_COLORS(0)); palette_used_colors[COLORTABLE_START(0,i) + GFX_ELEM_COLORS(0)-1] = PALETTE_COLOR_TRANSPARENT; } /* fg tiles */ for (i = 0;i < GFX_COLOR_CODES(1);i++) { fast_memset(&palette_used_colors[COLORTABLE_START(1,i)], PALETTE_COLOR_USED, GFX_ELEM_COLORS(1)); } /* sprites */ for (i = 0;i < GFX_COLOR_CODES(2);i++) { fast_memset(&palette_used_colors[COLORTABLE_START(2,i)], PALETTE_COLOR_USED, GFX_ELEM_COLORS(2)); } /* bg tiles */ for (i = 0;i < GFX_COLOR_CODES(3);i++) { fast_memset(&palette_used_colors[COLORTABLE_START(3,i)], PALETTE_COLOR_USED, GFX_ELEM_COLORS(3)); } return 0; } void trojan_vh_stop(void) { osd_free_bitmap(tmpbitmap3); gp2x_free(dirtybuffer4); gp2x_free(dirtybuffer2); generic_vh_stop(); } void trojan_render_foreground( struct osd_bitmap *bitmap, int scrollx, int scrolly, int priority ) { int scrlx = -(scrollx&0x0f); int scrly = -(scrolly&0x0f); int sx, sy; int offsy = (scrolly >> 4)-1; int offsx = (scrollx >> 4)*32-32; int transp0,transp1; if( priority ){ transp0 = 0xFFFF; /* draw nothing (all pens transparent) */ transp1 = 0xF00F; /* high priority half of tile */ } else { transp0 = 1; /* TRANSPARENCY_PEN, color 0 */ transp1 = 0x0FF0; /* low priority half of tile */ } for (sx=0; sx<0x12; sx++) { offsx&=0x03ff; for (sy=0; sy<0x12; sy++) { /* Tiles 0x80 Tile code MSB 0x40 Tile code MSB 0x20 Tile code MSB 0x10 X flip 0x08 Priority ???? 0x04 Colour 0x02 Colour 0x01 Colour */ int offset = offsx+( (sy+offsy)&0x1f ); int attribute = lwings_backgroundattribram[offset]; drawgfx(bitmap,Machine->gfx[1], lwings_backgroundram[offset] + ((attribute &0xe0) <<3), attribute & 0x07, attribute & 0x10, 0, 16 * sx+scrlx-16,16 * sy+scrly-16, &Machine->drv->visible_area, TRANSPARENCY_PENS,(attribute & 0x08)?transp1:transp0 ); } offsx+=0x20; } } void trojan_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh) { int offs, sx, sy, scrollx, scrolly; int offsy, offsx; if (palette_recalc()) { fast_memset(dirtybuffer2,1,lwings_backgroundram_size); fast_memset(dirtybuffer4,1,lwings_backgroundram_size); } { static int oldoffsy=0xffff; static int oldoffsx=0xffff; scrollx = (trojan_bk_scrollx[0]); scrolly = (trojan_bk_scrolly[0]); offsy = 0x20 * scrolly; offsx = (scrollx >> 4); scrollx = -(scrollx & 0x0f); scrolly = 0; /* Y doesn't scroll ??? */ if (oldoffsy != offsy || oldoffsx != offsx) { unsigned char *p=Machine->memory_region[4]; oldoffsx=offsx; oldoffsy=offsy; for (sy=0; sy < 0x11; sy++) { offsy &= 0x7fff; for (sx=0; sx<0x11; sx++) { int code, colour; int offset=offsy + ((2*(offsx+sx)) & 0x3f); code = *(p+offset); colour = *(p+offset+1); drawgfx(tmpbitmap3, Machine->gfx[3], code+((colour&0x80)<<1), colour & 0x07, colour&0x10, colour&0x20, 16 * sx,16 * sy, 0,TRANSPARENCY_NONE,0); } offsy += 0x800; } } copyscrollbitmap(bitmap,tmpbitmap3,1,&scrollx,1,&scrolly,&Machine->drv->visible_area,TRANSPARENCY_NONE,0); } scrollx = (trojan_scrollx[0] + 256 * trojan_scrollx[1]); scrolly = (trojan_scrolly[0] + 256 * trojan_scrolly[1]); trojan_render_foreground( bitmap, scrollx, scrolly, 0 ); /* Draw the sprites. */ for (offs = spriteram_size - 4;offs >= 0;offs -= 4) { int code,attrib; /* Sprites ======= 0x80 Sprite code MSB 0x40 Sprite code MSB 0x20 Sprite code MSB 0x10 X flip 0x08 Colour 0x04 colour 0x02 colour 0x01 X MSB */ attrib = spriteram[offs + 1]; sx = spriteram[offs + 3] - 0x100 * (attrib & 0x01); sy = spriteram[offs + 2]; if (sx && sy) { code = spriteram[offs]; if( attrib&0x40 ) code += 256; if( attrib&0x80 ) code += 256*4; if( attrib&0x20 ) code += 256*2; drawgfx(bitmap,Machine->gfx[2], code, (attrib & 0x0e) >> 1, attrib & 0x10,1, sx,sy, &Machine->drv->visible_area,TRANSPARENCY_PEN,15); } } trojan_render_foreground( bitmap, scrollx, scrolly, 1 ); /* draw the frontmost playfield. They are characters, but draw them as sprites */ for (offs = videoram_size - 1;offs >= 0;offs--) { sx = offs % 32; sy = offs / 32; drawgfx(bitmap,Machine->gfx[0], videoram[offs] + 4 * (colorram[offs] & 0xc0), colorram[offs] & 0x0f, colorram[offs] & 0x10,colorram[offs] & 0x20, 8*sx,8*sy, &Machine->drv->visible_area,TRANSPARENCY_PEN,3); } }
26.261209
151
0.565395
pierrelouys
cbb10b61d84d535032a741a75db84a9e87bee635
437
cpp
C++
tests/operation/out.cpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
17
2018-08-22T06:48:20.000Z
2022-02-22T21:20:09.000Z
tests/operation/out.cpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
null
null
null
tests/operation/out.cpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
null
null
null
// Copyright 2020 Oleksandr Bacherikov. // // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #include <actl/operation/scalar/all.hpp> #include "test.hpp" TEST_CASE("output parameter") { int res{}; CHECK(6 == (ac::out{res} = ac::add(2, 4)).x); CHECK(6 == res); ac::out{res} = ac::add(2, res); CHECK(8 == res); }
24.277778
60
0.638444
AlCash07
cbb29f4bd651a9f40f5f1ea413809f830d86f536
1,354
hpp
C++
include/Color.hpp
Crazy-Piri/Img2CPC
af748085b3e1d1d63697aedb12d7021236b1e8ff
[ "MIT" ]
6
2015-08-10T13:10:19.000Z
2020-06-06T08:15:34.000Z
include/Color.hpp
Crazy-Piri/Img2CPC
af748085b3e1d1d63697aedb12d7021236b1e8ff
[ "MIT" ]
5
2016-04-10T13:20:01.000Z
2021-06-23T06:36:32.000Z
include/Color.hpp
Crazy-Piri/Img2CPC
af748085b3e1d1d63697aedb12d7021236b1e8ff
[ "MIT" ]
4
2015-08-15T16:45:32.000Z
2020-08-15T19:57:54.000Z
#ifndef _COLOR_H_ #define _COLOR_H_ #include <cmath> #include <iostream> using namespace std; class Color { public: unsigned char A; unsigned char R; unsigned char G; unsigned char B; Color(): Color(0, 0,0,0) {}; Color(const unsigned char r, const unsigned char g, const unsigned b): A(255), R(r),G(g),B(b) { }; Color(const unsigned char a, const unsigned char r, const unsigned char g, const unsigned b): A(a), R(r),G(g),B(b) { }; unsigned int toInt() { return (this->A << 24) | (this->R << 16) | (this->G << 8) | (this->B); }; double Distance(const Color &other) { return Color::Distance(*this, other); }; void Dump() { cout << "{ a: " << (unsigned int) this->A ; cout << ", r: " << (unsigned int) this->R ; cout << ", g: " << (unsigned int) this->G ; cout << ", b: " << (unsigned int) this->B ; cout << " }"; }; static double Distance (const Color &col1, const Color &col2) { if(col1.A == 0 && col2.A == 0) { return 0.0; } else { int deltaA = col1.A - col2.A; int deltaR = col1.R - col2.R; int deltaG = col1.G - col2.G; int deltaB = col1.B - col2.B; return sqrt( (double)( (deltaA * deltaA) + (deltaR * deltaR) + (deltaG * deltaG) + (deltaB * deltaB) )); } }; }; #endif
22.949153
97
0.532496
Crazy-Piri
cbbb8834b87999c28a2ba680766a7a7a6f1e3e9b
98
hpp
C++
include/test_data.hpp
andrewkatson/json
c11ca0a075f2d4bb5b5b613b5319597cf15db11e
[ "MIT" ]
null
null
null
include/test_data.hpp
andrewkatson/json
c11ca0a075f2d4bb5b5b613b5319597cf15db11e
[ "MIT" ]
null
null
null
include/test_data.hpp
andrewkatson/json
c11ca0a075f2d4bb5b5b613b5319597cf15db11e
[ "MIT" ]
null
null
null
#define TEST_DATA_DIRECTORY "/home/andrew/DenariiServices/Core/external/json/json/json_test_data"
49
97
0.857143
andrewkatson
cbc32c5849ee5e01e91f5fa2d22eb64b8e2928e8
698
hpp
C++
src/arithmetic/bucket.hpp
r3c/tesca
e5ea2f4f2c4a35c47f38468a89f2f05038fb18d8
[ "MIT" ]
2
2016-06-01T14:44:21.000Z
2018-05-04T11:55:02.000Z
src/arithmetic/bucket.hpp
r3c/tesca
e5ea2f4f2c4a35c47f38468a89f2f05038fb18d8
[ "MIT" ]
1
2021-03-21T11:36:18.000Z
2021-03-21T14:49:17.000Z
src/arithmetic/bucket.hpp
r3c/tesca
e5ea2f4f2c4a35c47f38468a89f2f05038fb18d8
[ "MIT" ]
null
null
null
#ifndef __TESCA_ARITHMETIC_BUCKET_HPP #define __TESCA_ARITHMETIC_BUCKET_HPP #include "../../lib/glay/src/glay.hpp" #include "../storage/variant.hpp" namespace Tesca { namespace Arithmetic { class Bucket { public: Bucket (Bucket const&); Bucket (Glay::Int32u); ~Bucket (); Bucket& operator = (Bucket const&); Storage::Variant const& operator [] (Glay::Int32u) const; Glay::Int32u getLength () const; Glay::Int16s compare (Bucket const&) const; Bucket& keep (); void set (Glay::Int32u, Storage::Variant const&); private: Storage::Variant* buffer; Glay::Int32u length; }; bool operator < (Bucket const&, Bucket const&); } } #endif
18.368421
61
0.657593
r3c
cbc55c23aabd6be2d881a9136e18c06b287f1909
2,484
cpp
C++
win8.1/test/readme.cpp
panopticoncentral/jsrt-wrappers
9e6352240a00ff622bbf0726f1fba363977313b9
[ "Apache-2.0" ]
12
2015-08-17T12:59:12.000Z
2021-10-10T02:54:40.000Z
win8.1/test/readme.cpp
panopticoncentral/jsrt-wrappers
9e6352240a00ff622bbf0726f1fba363977313b9
[ "Apache-2.0" ]
null
null
null
win8.1/test/readme.cpp
panopticoncentral/jsrt-wrappers
9e6352240a00ff622bbf0726f1fba363977313b9
[ "Apache-2.0" ]
5
2019-03-08T04:13:44.000Z
2019-12-17T09:51:09.000Z
// Copyright 2013 Paul Vick // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "stdafx.h" #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace jsrtwrapperstest { TEST_CLASS(readme) { public: static double add(const jsrt::call_info &info, double a, double b) { return a + b; } MY_TEST_METHOD(samples, "Test readme samples.") { jsrt::runtime runtime = jsrt::runtime::create(); jsrt::context context = runtime.create_context(); { jsrt::context::scope scope(context); jsrt::pinned<jsrt::object> pinned_obj = jsrt::object::create(); jsrt::object obj = jsrt::object::create(); obj.set_property(jsrt::property_id::create(L"boolProperty"), true); bool bool_value = obj.get_property<bool>(jsrt::property_id::create(L"boolProperty")); obj.set_property(jsrt::property_id::create(L"stringProperty"), L"foo"); jsrt::array<double> darray = jsrt::array<double>::create(1); darray[0] = 10; darray[1] = 20; auto f = (jsrt::function<double, double, double>)jsrt::context::evaluate(L"function f(a, b) { return a + b; }; f;"); double a = f(jsrt::context::undefined(), 1, 2); auto nf = jsrt::function<double, double, double>::create(add); jsrt::context::global().set_property(jsrt::property_id::create(L"add"), nf); jsrt::context::run(L"add(1, 2)"); auto bf = jsrt::bound_function<jsrt::value, double, double, double>( jsrt::context::undefined(), (jsrt::function<double, double, double>)jsrt::context::evaluate(L"function f(a, b) { return a + b; }; f;")); double ba = bf(1, 2); } runtime.dispose(); } }; }
40.064516
132
0.5938
panopticoncentral
cbca8f819c06a57e7b04f6b80df354673bf4ef76
4,051
cpp
C++
modules/attention_segmentation/src/LocationMap.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
17
2015-11-16T14:21:10.000Z
2020-11-09T02:57:33.000Z
modules/attention_segmentation/src/LocationMap.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
35
2015-07-27T15:04:43.000Z
2019-08-22T10:52:35.000Z
modules/attention_segmentation/src/LocationMap.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
18
2015-08-06T09:26:27.000Z
2020-09-03T01:31:00.000Z
/** * Copyright (C) 2012 * Ekaterina Potapova * Automation and Control Institute * Vienna University of Technology * Gusshausstraße 25-29 * 1040 Vienna, Austria * potapova(at)acin.tuwien.ac.at * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/ */ #include "v4r/attention_segmentation/LocationMap.h" namespace v4r { LocationSaliencyMap::LocationSaliencyMap(): BaseMap() { reset(); } LocationSaliencyMap::~LocationSaliencyMap() { } void LocationSaliencyMap::reset() { BaseMap::reset(); location = AM_CENTER; center_point = cv::Point(0,0); mapName = "LocationSaliencyMap"; } void LocationSaliencyMap::print() { BaseMap::print(); printf("[%s]: location = %d\n",mapName.c_str(),location); printf("[%s]: center_point = (%d,%d)\n",mapName.c_str(),center_point.x,center_point.y); } void LocationSaliencyMap::setLocation(int location_) { location = location_; calculated = false; printf("[INFO]: %s: location is set to: %d\n",mapName.c_str(),location); } void LocationSaliencyMap::setCenter(cv::Point _center_point) { center_point = _center_point; calculated = false; printf("[INFO]: %s: center_point is set to: (%d,%d)\n",mapName.c_str(),center_point.x,center_point.y); } int LocationSaliencyMap::checkParameters() { if( (width == 0) || (height == 0) ) { printf("[ERROR]: %s: Seems like image is empty.\n",mapName.c_str()); return(AM_IMAGE); } if(!haveMask) mask = cv::Mat_<uchar>::ones(height,width); if((mask.cols != width) || (mask.rows != height)) { mask = cv::Mat_<uchar>::ones(height,width); } return(AM_OK); } int LocationSaliencyMap::calculate() { calculated = false; int rt_code = checkParameters(); if(rt_code != AM_OK) return(rt_code); printf("[INFO]: %s: Computation started.\n",mapName.c_str()); cv::Point center; float a = 1; float b = 1; switch(location) { case AM_CENTER: center = cv::Point(width/2,height/2); break; case AM_LEFT_CENTER: center = cv::Point(width/4,height/2); break; case AM_LEFT: center = cv::Point(width/4,height/4); b = 0; break; case AM_RIGHT_CENTER: center = cv::Point(4*width/4,height/2); break; case AM_RIGHT: center = cv::Point(3*width/4,3*height/2); b = 0; break; case AM_TOP_CENTER: center = cv::Point(width/2,height/4); break; case AM_TOP: center = cv::Point(width/2,height/4); a = 0; break; case AM_BOTTOM_CENTER: center = cv::Point(width/2,3*height/4); break; case AM_BOTTOM: center = cv::Point(width/2,3*height/4); a = 0; break; case AM_LOCATION_CUSTOM: center = center_point; break; default: center = cv::Point(width/2,height/2); break; } map = cv::Mat_<float>::zeros(height,width); for(int r = 0; r < height; ++r) { for(int c = 0; c < width; ++c) { if(mask.at<uchar>(r,c)) { float dx = c-center.x; dx = a*(dx/width); float dy = r-center.y; dy = b*(dy/height); float value = dx*dx + dy*dy; map.at<float>(r,c) = exp(-11*value); } } } cv::blur(map,map,cv::Size(filter_size,filter_size)); v4r::normalize(map,normalization_type); calculated = true; printf("[INFO]: %s: Computation succeed.\n",mapName.c_str()); return(AM_OK); } } //namespace v4r
23.690058
104
0.626265
ToMadoRe
cbcd0ef8bc515c65044757062273b32f0068437d
3,018
hpp
C++
include/blacknot/assert.hpp
yzt/blacknot
58f2bc4264aae8c4300159c33ac0929edf07d36c
[ "MIT" ]
16
2015-03-17T11:38:58.000Z
2019-06-07T16:59:17.000Z
include/blacknot/assert.hpp
yzt/blacknot
58f2bc4264aae8c4300159c33ac0929edf07d36c
[ "MIT" ]
1
2020-04-03T07:14:19.000Z
2020-04-03T07:14:19.000Z
include/blacknot/assert.hpp
yzt/blacknot
58f2bc4264aae8c4300159c33ac0929edf07d36c
[ "MIT" ]
null
null
null
//====================================================================== // This is part of Project Blacknot: // https://github.com/yzt/blacknot //====================================================================== #pragma once //====================================================================== #include <blacknot/config.hpp> #include <blacknot/macros.hpp> //====================================================================== #define BKNT_STATIC_ASSERT(cond, msg) static_assert ((cond), msg) #define BKNT_STATIC_ASSERT_SIZE(t, sz) static_assert (sizeof(t) == (sz), "Type " BKNT_STRINGIZE(t) " must be " BKNT_STRINGIZE(sz) " bytes.") //---------------------------------------------------------------------- #if defined(BKNT_ENABLE_FULL_ASSERTS) #if defined(BKNT_COMPILER_IS_VC) #define BKNT_ASSERT(cond, ...) do{if (!(cond))::Blacknot::Assert(false,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,__VA_ARGS__);}while(false) #define BKNT_ASSERT_REPAIR(cond, ...) (::Blacknot::Assert(cond,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,__VA_ARGS__)) #define BKNT_ASSERT_PTR_VALID(ptr, ...) BKNT_ASSERT(BKNT_PTR_VALID(ptr),__VA_ARGS__) #else #define BKNT_ASSERT(cond, ...) do{if (!(cond))::Blacknot::Assert(false,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,##__VA_ARGS__);}while(false) #define BKNT_ASSERT_REPAIR(cond, ...) (::Blacknot::Assert(cond,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,##__VA_ARGS__)) #define BKNT_ASSERT_PTR_VALID(ptr, ...) BKNT_ASSERT(BKNT_PTR_VALID(ptr),##__VA_ARGS__) #endif #else #define BKNT_ASSERT(cond, ...) /**/ #define BKNT_ASSERT_REPAIR(cond, ...) (cond) #define BKNT_ASSERT_PTR_VALID(ptr, ...) /**/ #endif #if defined(BKNT_COMPILER_IS_VC) #define BKNT_ASSERT_STRONG(cond, ...) do{if (!(cond))::Blacknot::Assert(false,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,__VA_ARGS__);}while(false) #define BKNT_ASSERT_PTR_VALID_STRONG(ptr, ...) BKNT_ASSERT_STRONG(BKNT_PTR_VALID(ptr),__VA_ARGS__) #else #define BKNT_ASSERT_STRONG(cond, ...) do{if (!(cond))::Blacknot::Assert(false,BKNT_STRINGIZE(cond),__FILE__,__LINE__,__FUNCTION__,##__VA_ARGS__);}while(false) #define BKNT_ASSERT_PTR_VALID_STRONG(ptr, ...) BKNT_ASSERT_STRONG(BKNT_PTR_VALID(ptr),##__VA_ARGS__) #endif //---------------------------------------------------------------------- //====================================================================== namespace Blacknot { //====================================================================== void DebugBreak (); //---------------------------------------------------------------------- bool Assert ( bool cond, char const * cond_str, char const * file, int line, char const * func, char const * fmt = nullptr, ... ); //---------------------------------------------------------------------- //====================================================================== } // namespace Blacknot //======================================================================
46.430769
161
0.523194
yzt
cbd103eb5bd48dc7858554b641a4486e3b9e8e3a
812
cpp
C++
1st/unique_binary_search_trees.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
1st/unique_binary_search_trees.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
1st/unique_binary_search_trees.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> using std::cout; using std::endl; class Solution { public: int numTrees(int n) { if (n <= 0) return 0; int *res = new int[n+1](); res[0] = 1; res[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 0; j < i; ++j) { res[i] += res[j]*res[i-j-1]; } } int ret = res[n]; delete [] res; return ret; //return numTrees(1, n); } int numTrees(int start, int end) { if (start >= end) return 1; int ret = 0; for (int i = start; i <= end; ++i) { ret += numTrees(start, i-1)*numTrees(i+1, end); } return ret; } }; int main(void) { cout << Solution().numTrees(3) << endl; return 0; }
20.3
59
0.415025
buptlxb
cbdb015e5e4ec0d145e6756c4930c1ecfb0a3957
1,931
cpp
C++
Source/VectorWarUE4/Private/VectorWar/Components/MovementComponent.cpp
hakansanli/VectorWarUE4
042c4321f0cab9f6ea2344e98d1db38a4b1ade06
[ "MIT" ]
null
null
null
Source/VectorWarUE4/Private/VectorWar/Components/MovementComponent.cpp
hakansanli/VectorWarUE4
042c4321f0cab9f6ea2344e98d1db38a4b1ade06
[ "MIT" ]
null
null
null
Source/VectorWarUE4/Private/VectorWar/Components/MovementComponent.cpp
hakansanli/VectorWarUE4
042c4321f0cab9f6ea2344e98d1db38a4b1ade06
[ "MIT" ]
null
null
null
#include "MovementComponent.h" #include "ECS/Entity.h" #include "InputReceiverComponent.h" #include "ComponentFactory.h" #include <math.h> #include "BodyComponent.h" #include "VectorWar/vectorwar.h" void MovementComponent::Update(Entity* entity) { auto inputReceiver=(InputReceiverComponent*)entity->GetComponent(ComponentTypes::InputReceiverComponentType); if(inputReceiver!=nullptr){ if (inputReceiver->GetData()->input & INPUT_ROTATE_RIGHT) { GetData()->heading = (GetData()->heading + ROTATE_INCREMENT) % 360; } else if (inputReceiver->GetData()->input & INPUT_ROTATE_LEFT) { GetData()->heading = (GetData()->heading - ROTATE_INCREMENT + 360) % 360; } if (inputReceiver->GetData()->input & INPUT_THRUST) { GetData()->thrust = SHIP_THRUST; } else if (inputReceiver->GetData()->input & INPUT_BREAK) { GetData()->thrust = -SHIP_THRUST; } else { GetData()->thrust = 0; } if (GetData()->thrust) { double dx = GetData()->thrust * ::cos(degtorad(GetData()->heading)); double dy = GetData()->thrust * ::sin(degtorad(GetData()->heading)); auto body=(BodyComponent*)entity->GetComponent(ComponentTypes::BodyComponentType); UE_LOG(LogTemp,Warning,TEXT("dx:%f - dy:%f")); body->GetData()->velocity.dx += dx; body->GetData()->velocity.dy += dy; double mag = sqrt(body->GetData()->velocity.dx * body->GetData()->velocity.dx + body->GetData()->velocity.dy * body->GetData()->velocity.dy); if (mag > SHIP_MAX_THRUST) { body->GetData()->velocity.dx = (body->GetData()->velocity.dx * SHIP_MAX_THRUST) / mag; body->GetData()->velocity.dy = (body->GetData()->velocity.dy * SHIP_MAX_THRUST) / mag; } } } }
37.862745
113
0.590368
hakansanli
cbe5463e3a4b4df6971d54efaad81d97df641544
499
cpp
C++
examples/imgui_demo/imgui_demo.cpp
L-Sun/game_engine
e153280dae975c2770a202ca3b55e672626a172e
[ "MIT" ]
52
2021-11-19T09:08:30.000Z
2022-03-28T00:53:43.000Z
examples/imgui_demo/imgui_demo.cpp
L-Sun/game_engine
e153280dae975c2770a202ca3b55e672626a172e
[ "MIT" ]
1
2021-10-30T06:55:35.000Z
2021-10-30T06:55:35.000Z
examples/imgui_demo/imgui_demo.cpp
L-Sun/game_engine
e153280dae975c2770a202ca3b55e672626a172e
[ "MIT" ]
2
2021-12-15T02:10:42.000Z
2022-01-08T17:50:25.000Z
#include "imgui_demo.hpp" #include <hitagi/gui/gui_manager.hpp> #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_color_sinks.h> using namespace hitagi; int ImGuiDemo::Initialize() { m_Logger = spdlog::stdout_color_mt("ImGuiDemo"); return 0; } void ImGuiDemo::Finalize() { m_Logger->info("ImGuiDemo Finalize"); m_Logger = nullptr; } void ImGuiDemo::Tick() { bool open = true; g_GuiManager->DrawGui([&]() -> void { ImGui::ShowDemoWindow(&open); }); }
19.192308
52
0.669339
L-Sun
cbe5566c3e0bc7613787e8eceba489f88000b3dc
8,179
cpp
C++
MagicianApprentice/MagicianApprentice/Player.cpp
vandalo/MagicianApprentice
d8f0419399fd6579960ad1b85028ecfc88a83e25
[ "MIT" ]
null
null
null
MagicianApprentice/MagicianApprentice/Player.cpp
vandalo/MagicianApprentice
d8f0419399fd6579960ad1b85028ecfc88a83e25
[ "MIT" ]
null
null
null
MagicianApprentice/MagicianApprentice/Player.cpp
vandalo/MagicianApprentice
d8f0419399fd6579960ad1b85028ecfc88a83e25
[ "MIT" ]
null
null
null
#include <iostream> #include "Utils.h" #include "Player.h" #include "Exit.h" #include "Room.h" #include "Item.h" #include "Spell.h" #include "Monster.h" #include <string> #include "World.h" Player::Player(const char* name, const char* description, Entity* parent, World* myWorld) : Creature(name, description, parent), myWorld(myWorld) { type = PLAYER; hp = 50; maxHp = 50; mana = 100; lvl = 1; shield = 0; } Player::~Player() {} bool Player::Update() { if (shield > 0) { shield--; } return false; } unsigned int Player::ReciveAtack(unsigned int damage) { if (shield > 0) { if (shield > damage) { shield -= damage; cout << "\nYou lose " + to_string(damage) + " shield points."; damage = 0; } else { cout << "\nYou lose " + to_string(shield) + " shield points."; damage -= shield; shield = 0; } } if (hp > damage) { hp -= damage; } else { hp = 0; } return damage; } void Player::UseSpell(const vector<string>& args) { Spell* spell = HaveSpellAndMana(args); if (spell != nullptr) { spell->effect(this); } } void Player::UpdateMana(int manaMod) { mana += manaMod; } void Player::UpdateHp(int hpMod) { int hpStart = hp; hp += hpMod; if(hp > maxHp) { hp = maxHp; cout << "You healed " << hp - hpStart <<" hp.\n"; } } void Player::UpdateShield(int shieldPoints) { shield += shieldPoints; } void Player::Use(const vector<string>& args) { list<Entity*> items; FindByTypeAndPropietary(ITEM, items, (Entity*)this); bool find = false; for (list<Entity*>::const_iterator it = items.begin(); it != items.cend() && find == false; ++it) { if (Same((*it)->name, args[1])) { Item* item = (Item*)(*it); item->Use(this, args); find = true; } } if (find == false) { list<Entity*> itemsInRoom; FindByTypeAndPropietary(ITEM, itemsInRoom, GetRoom()); for (list<Entity*>::const_iterator it = itemsInRoom.begin(); it != itemsInRoom.cend() && find == false; ++it) { if (Same((*it)->name, args[1])) { Item* item = (Item*)(*it); if (item->fixed == true) { item->Use(this, args); find = true; } } } } if (find == false) { cout << "You don\'t have this item!\n"; } } void Player::UseOn(const vector<string>& args) { list<Entity*> items; FindByTypeAndPropietary(ITEM, items, GetRoom()); bool find = false; for (list<Entity*>::const_iterator it = items.begin(); it != items.cend() && find == false; ++it) { if (Same((*it)->name, args[3])) { Item* item = (Item*)(*it); item->Use(this, args); find = true; } } if (find == false) { cout << "There aren't any " << args[3] << ".\n"; } } Spell * Player::HaveSpellAndMana(const vector<string>& args) const { bool haveSpell = false; Spell* ret = nullptr; list<Entity*> spells; FindByTypeAndPropietary(ITEM, spells, (Entity*)this); for (list<Entity*>::const_iterator it = spells.begin(); it != spells.cend(); ++it) { Item* item = (Item*)(*it); if (item->container.size() > 0) { for (list<Entity*>::const_iterator it = item->container.begin(); it != item->container.cend(); ++it) { if ((*it)->type == SPELL) { Spell* spell = (Spell*)(*it); if (Same(spell->nameSpell, args[0])) { haveSpell = true; if (mana > spell->mana) { if (spell->cdTime <= 0) { ret = spell; } else { cout << "This spell is in cooldown!\nYou have to wait " << spell->cdTime << " seconds to use it again.\n"; } } else { cout << "You have not enought mana!\n"; } } } } } } if (haveSpell == false) { cout << "You don\'t know this spell yet!\n"; } return ret; } void Player::Look(const vector<string>& args) const { if (args.size() > 1) { for (list<Entity*>::const_iterator it = parent->container.begin(); it != parent->container.cend(); ++it) { if (Same((*it)->name, args[1])) { if ((*it)->type == MONSTER) { Monster* monster = (Monster*)(*it); monster->Look(); } else { (*it)->Look(); } return; } } for (list<Entity*>::const_iterator it = container.begin(); it != container.cend(); ++it) { if (Same((*it)->name, args[1])) { (*it)->Look(); return; } } if (Same(args[1], "me")) { cout << name << "\n"; cout << description << "\n"; Stats(); } } else { parent->Look(); } } void Player::Stats() const { int lifePercent = hp * 100 / maxHp; //cout << "You are level " << lvl << endl; if (lifePercent > 75) { cout << "You are healthy, "; } else if (lifePercent > 25) { cout << "You are hurt, "; } else { cout << "You are almost death, "; } cout << "you have " << hp << "/" << maxHp << " hit points" << endl; cout << "You have " << mana << " mana points" << endl; if (shield > 0) { cout << "You have a shield of " << shield << " seconds.\n"; } } void Player::Inventory(const vector<string>& args) const { list<Entity*> items; FindByTypeAndPropietary(ITEM, items, (Entity*)this); for (list<Entity*>::const_iterator it = items.begin(); it != items.cend(); ++it) { (*it)->Look(); } } void Player::Open(const vector<string>& args) { list<Entity*> exits; FindByTypeAndPropietary(EXIT, exits, GetRoom()); for (list<Entity*>::const_iterator it = exits.begin(); it != exits.cend(); ++it) { Exit* exit = (Exit*)(*it); if (exit->name == args[1] || exit->GetDestination() == args[1]) { exit->Open(this); } } } void Player::Go(const vector<string>& args) { Exit* exit = GetRoom()->GetExitByName(args[1]); if (exit == nullptr) { cout << "There aren't anything on " + (args[1]) + ".\n"; } else { if (exit->closed == true) { cout << "You can't pass " + (args[1]) + " it's locked.\n"; } else if(exit->condition != nullptr && exit->condition->type == MONSTER) { Monster* monster = (Monster*)exit->condition; if (monster->IsAlive()) { cout << "You can not go " << exit->name << ", " << monster->name << " is blocking the acces.\n"; } else { ChangeParentTo(exit->GetDestinationByRoom(GetRoom())); parent->Look(); } } else { ChangeParentTo(exit->GetDestinationByRoom(GetRoom())); parent->Look(); } } } void Player::Take(const vector<string>& args) { Item* item = (Item*)GetRoom()->GetItemByName(args[1]); if (item == nullptr) { item = (Item*)GetItemByName(args[1]); if (item != nullptr) { cout << "You already have " + item->name + ".\n"; } else { cout << "There aren't any item called " + (args[1]) + ".\n"; } } else { item = (Item*)GetRoom()->GetItemByName(args[1]); if (item == nullptr) { cout << "There aren't any item called " + (args[1]) + ".\n"; } else if (item->fixed) { cout << "You can't take " + (args[1]) + ".\n"; } else { if (item->must == nullptr) { item->ChangeParentTo(this); cout << "You added the " + item->name + " to your inventory.\n"; } else { if (item->must->type == ITEM) { list<Entity*> items; FindByTypeAndPropietary(ITEM, items, (Entity*)this); FindByTypeAndPropietary(SPELL, items, (Entity*)this); bool find = false; for (list<Entity*>::const_iterator it = items.begin(); it != items.cend(); ++it) { if ((*it)->name == item->must->name) { item->ChangeParentTo(*it); cout << "You added " + item->name + " to your " + (*it)->name + ".\n"; find = true; } } if (find != true) { cout << "You can't take " + (args[1]) + ".\n"; } } else if (item->must->type == MONSTER) { Monster* monster = (Monster*)item->must; if (monster->IsAlive()) { cout << "You can't take " + (args[1]) + ", " << monster->name <<" is protecting it.\n"; } else { item->ChangeParentTo(this); cout << "You added " + item->name + " to your inventory.\n"; } } } } } } void Player::CreateBookpage3() const { myWorld->CreateBookpage3(); } void Player::CreateKey1() const { myWorld->CreateKey1(); } void Player::CreateSecretExit() const { myWorld->CreateSecretExit(); }
19.427553
114
0.55618
vandalo
cbebc3d40bb7e6b9c9568b642a68e529abf28cc1
2,765
cpp
C++
ehunter/genotyping/AlleleChecker.cpp
bw2/ExpansionHunter
6a6005a4bae2c49f56ec8997a301b70a75b042b6
[ "BSL-1.0", "Apache-2.0" ]
122
2017-01-06T16:19:31.000Z
2022-03-08T00:05:50.000Z
ehunter/genotyping/AlleleChecker.cpp
bw2/ExpansionHunter
6a6005a4bae2c49f56ec8997a301b70a75b042b6
[ "BSL-1.0", "Apache-2.0" ]
90
2017-01-04T00:23:34.000Z
2022-02-27T12:55:52.000Z
ehunter/genotyping/AlleleChecker.cpp
bw2/ExpansionHunter
6a6005a4bae2c49f56ec8997a301b70a75b042b6
[ "BSL-1.0", "Apache-2.0" ]
35
2017-03-02T13:39:58.000Z
2022-03-30T17:34:11.000Z
// // Expansion Hunter // Copyright 2016-2019 Illumina, Inc. // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // #include "genotyping/AlleleChecker.hh" #include <boost/math/special_functions/binomial.hpp> #include <boost/math/special_functions/gamma.hpp> #include <boost/math/special_functions/log1p.hpp> #include <numeric> namespace ehunter { namespace { double poissonLogPmf(double lambda, double count) { return count * log(lambda) - lambda - boost::math::lgamma(count + 1); } double logBeta(int a, int b) { return boost::math::lgamma(a) + boost::math::lgamma(b) - boost::math::lgamma(a + b); } double logBinomCoef(int n, int k) { return -boost::math::log1p(n) - logBeta(n - k + 1, k + 1); } double binomLogPmf(int n, double p, int count) { return logBinomCoef(n, count) + count * log(p) + (n - count) * boost::math::log1p(-p); } } AlleleCheckSummary AlleleChecker::check(double haplotypeDepth, int targetAlleleCount, int otherAlleleCount) const { if (haplotypeDepth <= 0) { throw std::runtime_error("Haplotype depth must be positive"); } if (targetAlleleCount < 0 || otherAlleleCount < 0) { throw std::runtime_error("Negative read counts are not allowed"); } const int totalReadCount = targetAlleleCount + otherAlleleCount; const double ll0 = (totalReadCount > 0) ? binomLogPmf(totalReadCount, errorRate_, targetAlleleCount) : 0; const double ll1 = poissonLogPmf(haplotypeDepth, targetAlleleCount); AlleleStatus status = AlleleStatus::kUncertain; double logLikelihoodRatio = (ll1 - ll0) / log(10); if (logLikelihoodRatio < -log10(likelihoodRatioThreshold_)) { status = AlleleStatus::kAbsent; } else if (logLikelihoodRatio > log10(likelihoodRatioThreshold_)) { status = AlleleStatus::kPresent; } return AlleleCheckSummary(status, logLikelihoodRatio); } std::ostream& operator<<(std::ostream& out, AlleleStatus status) { switch (status) { case AlleleStatus::kAbsent: out << "Absent"; break; case AlleleStatus::kPresent: out << "Present"; break; case AlleleStatus::kUncertain: out << "Uncertain"; break; } return out; } }
28.214286
117
0.688608
bw2
cbebd7bce4351504b038d57b0d9e7e92cb57a291
2,242
hpp
C++
src/deps/include/boost/url/rfc/query_bnf.hpp
sandmanhome/liuguang
73fb6ee06654d80f8c9dedee1ddfa4f9be2d5fb3
[ "Apache-2.0" ]
null
null
null
src/deps/include/boost/url/rfc/query_bnf.hpp
sandmanhome/liuguang
73fb6ee06654d80f8c9dedee1ddfa4f9be2d5fb3
[ "Apache-2.0" ]
null
null
null
src/deps/include/boost/url/rfc/query_bnf.hpp
sandmanhome/liuguang
73fb6ee06654d80f8c9dedee1ddfa4f9be2d5fb3
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/CPPAlliance/url // #ifndef BOOST_URL_RFC_QUERY_BNF_HPP #define BOOST_URL_RFC_QUERY_BNF_HPP #include <boost/url/detail/config.hpp> #include <boost/url/error.hpp> #include <boost/url/pct_encoding_types.hpp> #include <boost/url/string.hpp> #include <boost/url/bnf/range.hpp> #include <cstddef> namespace boost { namespace urls { struct query_param { pct_encoded_str key; pct_encoded_str value; bool has_value = false; }; /** BNF for query @par BNF @code query = *( pchar / "/" / "?" ) query-params = query-param *( "&" query-param ) query-param = key [ "=" value ] key = *qpchar value = *( qpchar / "=" ) qpchar = unreserved / pct-encoded / "!" / "$" / "'" / "(" / ")" / "*" / "+" / "," / ";" / ":" / "@" / "/" / "?" @endcode @see https://datatracker.ietf.org/doc/html/rfc3986#section-3.4 */ struct query_bnf : bnf::range { using value_type = query_param; query_bnf() : bnf::range(this) { } BOOST_URL_DECL static bool begin( char const*& it, char const* const end, error_code& ec, query_param& t) noexcept; BOOST_URL_DECL static bool increment( char const*& it, char const* const end, error_code& ec, query_param& t) noexcept; }; /** BNF for query-part @par BNF @code query-part = [ "?" query ] query = *( pchar / "/" / "?" ) @endcode @see https://datatracker.ietf.org/doc/html/rfc3986#section-3.4 */ struct query_part_bnf { bool has_query; query_bnf query; string_view query_part; BOOST_URL_DECL friend bool parse( char const*& it, char const* const end, error_code& ec, query_part_bnf& t); }; } // urls } // boost #endif
20.198198
79
0.554862
sandmanhome
cbedab134d53bff3e272b7a6b088b4fe8e192f68
1,506
cpp
C++
cpp/src/exercise/e0200/e0149.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0200/e0149.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0200/e0149.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
// https://leetcode-cn.com/problems/max-points-on-a-line/ #include "extern.h" typedef pair<int, int> pii; class S0149 { void gcd(pii& p) { int l = abs(p.first), r = abs(p.second); if (r == 0) p = make_pair(1, 0); else if (l == 0) p = make_pair(0, 1); else { if (l < r) swap(l, r); while (r != 0) { l -= (l / r) * r; swap(l, r); } if (p.first < 0) l *= -1; p.first /= l, p.second /= l; } } public: int maxPoints(vector<vector<int>>& points) { int ps = points.size(); if (ps == 0) return 0; int result = 1; map<pii, int> s; for (int i = 0; i < ps; ++i) { int rep_point = 1; s.clear(); for (int j = i + 1; j < ps; ++j) { pii k = make_pair(points[j][0] - points[i][0], points[j][1] - points[i][1]); if (k.first == 0 && k.second == 0) rep_point += 1; else { gcd(k); s[k] += 1; } } result = max(rep_point, result); for (auto& p : s) result = max(p.second + rep_point, result); } return result; } }; TEST(e0200, e0149) { vector<vector<int>> points; points = str_to_mat<int>("[[1,1],[2,2],[3,3]]"); ASSERT_EQ(S0149().maxPoints(points), 3); points = str_to_mat<int>("[[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]"); ASSERT_EQ(S0149().maxPoints(points), 4); }
29.529412
92
0.434263
ajz34
cbef4911f3ffa13f77cf15b9834b2717f9982061
1,271
cpp
C++
src/critics/goal_critic.cpp
doisyg/mppic
e9cd561c5e108061bd90cf157f0f73327b21e51a
[ "MIT" ]
null
null
null
src/critics/goal_critic.cpp
doisyg/mppic
e9cd561c5e108061bd90cf157f0f73327b21e51a
[ "MIT" ]
null
null
null
src/critics/goal_critic.cpp
doisyg/mppic
e9cd561c5e108061bd90cf157f0f73327b21e51a
[ "MIT" ]
null
null
null
// Copyright 2022 FastSense, Samsung Research #include "mppic/critics/goal_critic.hpp" namespace mppi::critics { void GoalCritic::initialize() { auto node = parent_.lock(); auto getParam = utils::getParamGetter(node, name_); getParam(power_, "goal_cost_power", 1); getParam(weight_, "goal_cost_weight", 20.0); RCLCPP_INFO( logger_, "GoalCritic instantiated with %d power and %f weight.", power_, weight_); } void GoalCritic::score( const geometry_msgs::msg::PoseStamped & /*robot_pose*/, const optimization::State & /*state*/, const xt::xtensor<double, 3> & trajectories, const xt::xtensor<double, 2> & path, xt::xtensor<double, 1> & costs, nav2_core::GoalChecker * /*goal_checker*/) { const auto goal_points = xt::view(path, -1, xt::range(0, 2)); auto trajectories_end = xt::view(trajectories, xt::all(), -1, xt::range(0, 2)); auto dim = trajectories_end.dimension() - 1; auto && dists_trajectories_end_to_goal = xt::norm_l2(std::move(trajectories_end) - goal_points, {dim}); costs += xt::pow(std::move(dists_trajectories_end_to_goal) * weight_, power_); } } // namespace mppi::critics #include <pluginlib/class_list_macros.hpp> PLUGINLIB_EXPORT_CLASS(mppi::critics::GoalCritic, mppi::critics::CriticFunction)
28.244444
80
0.707317
doisyg
cbf176038b5218527024600bf137be49963ea712
2,212
cpp
C++
Binary Tree/Diameter.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Binary Tree/Diameter.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Binary Tree/Diameter.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//Find the diameter of a tree /* approach 1: TC: O(n^2): We find the left height and right height also for the possibility that there might exist a subtree greater than the current left or right approach 2: TC:O(n): We find the height in the same recursive call only. */ #include<iostream> using namespace std; struct Node{ int data; Node* right; Node* left; }; //creates node Node* createNode(int data){ Node* node = new Node; if(node){ node->left = node->right = NULL; node->data = data; return node; } return NULL; } //preorder traversal void preOrderTraversal(Node* root){ if(!root) return; cout<<root->data<<" "; preOrderTraversal(root->left); preOrderTraversal(root->right); } //for finding the height of a tree int findHeight(Node* root){ if(!root) return 0; return max( findHeight(root->left), findHeight(root->right)) + 1; } //finds the diameter using separate height calls int findDiameter1(Node* root){ if(root == NULL) return 0; //find the left and right heights int lh = findHeight(root->left); int rh = findHeight(root->right); //find the left and right diameters int ld = findDiameter1(root->left); int rd = findDiameter1(root->right); //now decide whether the current subtree or the greatest subtree on left //or on right should be selected return max( lh + rh + 1, max(ld, rd) ); } //finds the diameter /* We update the height in each recursive call itself using pointers to them */ int findDiameter2(Node* root, int* h){ if(!root ) return 0; int lh = 0; int rh = 0; int ld = findDiameter2(root->left, &lh); int rd = findDiameter2(root->right, &rh); *h = max(lh ,rh) + 1; return max( lh +rh + 1, max(ld,rd)); } //finds the diameter using 2nd approach int findDiameter2Driver(Node* root){ int h = 0; int d = findDiameter2(root, &h); return d; } main(){ /* 1 / \ 2 3 / \ 4 5 */ Node *root = createNode(1); root->left = createNode(2); root->right = createNode(3); root->left->left = createNode(4); root->left->right = createNode(5); preOrderTraversal(root); cout<<endl; cout<< findDiameter1(root); cout<<endl; cout<< findDiameter2Driver(root); }
20.867925
74
0.657776
susantabiswas
cbf22d95707136e9855e8fcd66bb0aeab0f25db3
972
cpp
C++
Bit Manipulation/8divideWithoutUsingDivideOperator.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
1
2021-01-18T14:51:20.000Z
2021-01-18T14:51:20.000Z
Bit Manipulation/8divideWithoutUsingDivideOperator.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
Bit Manipulation/8divideWithoutUsingDivideOperator.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
// C++ implementation to Divide two // integers without using multiplication, // division and mod operator #include <bits/stdc++.h> using namespace std; // Function to divide a by b and // return floor value it int divide(long long dividend, long long divisor) { // Calculate sign of divisor i.e., // sign will be negative only iff // either one of them is negative // otherwise it will be positive int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // remove sign of operands dividend = abs(dividend); divisor = abs(divisor); // Initialize the quotient long long quotient = 0, temp = 0; // test down from the highest bit and // accumulate the tentative value for // valid bit for (int i = 31; i >= 0; --i) { if (temp + (divisor << i) <= dividend) { temp += divisor << i; quotient |= 1LL << i; } } return sign * quotient; } // Driver code int main() { int a = 10, b = 3; cout << divide(a, b) << "\n"; a = 43, b = -8; cout << divide(a, b); return 0; }
19.44
51
0.641975
Coderangshu
cbf57bcfe413d3b3dd58c1787f50c4eae5a8ebcc
14,503
cpp
C++
src/zlib/Win32app.cpp
FreeAllegiance/AllegianceDX7
3955756dffea8e7e31d3a55fcf6184232b792195
[ "MIT" ]
76
2015-08-18T19:18:40.000Z
2022-01-08T12:47:22.000Z
src/zlib/Win32app.cpp
StudentAlleg/Allegiance
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
[ "MIT" ]
37
2015-08-14T22:44:12.000Z
2020-01-21T01:03:06.000Z
src/zlib/Win32app.cpp
StudentAlleg/Allegiance
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
[ "MIT" ]
42
2015-08-13T23:31:35.000Z
2022-03-17T02:20:26.000Z
#include "Win32app.h" #include "regkey.h" #include "SlmVer.h" //Imago 7/10 #include <dbghelp.h> #include <crtdbg.h> #include "zstring.h" #include "VersionInfo.h" #include <ctime> #include "zmath.h" #include "window.h" #include "Logger.h" #ifndef NO_STEAM #include "steam_api.h" #endif ////////////////////////////////////////////////////////////////////////////// // // Some assertion functions // ////////////////////////////////////////////////////////////////////////////// Win32App *g_papp; // Patch for SetUnhandledExceptionFilter const uint8_t PatchBytes[5] = { 0x33, 0xC0, 0xC2, 0x04, 0x00 }; // Original bytes at the beginning of SetUnhandledExceptionFilter uint8_t OriginalBytes[5] = {0}; int GenerateDump(EXCEPTION_POINTERS* pExceptionPointers) { BOOL bMiniDumpSuccessful; char szPathName[MAX_PATH] = ""; GetModuleFileNameA(nullptr, szPathName, MAX_PATH); const char* p1 = strrchr(szPathName, '\\'); char* p = strrchr(szPathName, '\\'); if (!p) p = szPathName; else p++; if (!p1) p1 = "mini"; else p1++; ZString zApp = p1; uint32_t dwBufferSize = MAX_PATH; HANDLE hDumpFile; SYSTEMTIME stLocalTime; MINIDUMP_EXCEPTION_INFORMATION ExpParam; GetLocalTime(&stLocalTime); snprintf(p, szPathName + sizeof(szPathName) - p, "%s", (PCC)zApp); ZVersionInfo vi; ZString zInfo = (LPCSTR)vi.GetFileVersionString(); char* offsetString = p + zApp.GetLength(); snprintf(offsetString, szPathName + sizeof(szPathName) - offsetString, "-%s-%04d%02d%02d%02d%02d%02d-%ld-%ld.dmp", (PCC)zInfo, stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay, stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond, GetCurrentProcessId(), GetCurrentThreadId()); hDumpFile = CreateFileA(szPathName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, nullptr, CREATE_ALWAYS, 0, nullptr); ExpParam.ThreadId = GetCurrentThreadId(); ExpParam.ExceptionPointers = pExceptionPointers; ExpParam.ClientPointers = TRUE; MINIDUMP_TYPE mdt = (MINIDUMP_TYPE) (MiniDumpWithDataSegs | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithProcessThreadData); bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, mdt, &ExpParam, nullptr, nullptr); #ifndef NO_STEAM // BT - STEAM SteamAPI_SetMiniDumpComment(p); // The 0 here is a build ID, we don't set it SteamAPI_WriteMiniDump(0, pExceptionPointers, int(rup)); // Now including build and release number in steam errors. #endif return EXCEPTION_EXECUTE_HANDLER; } //Imago 6/10 int Win32App::GenerateDump(EXCEPTION_POINTERS* pExceptionPointers) { return ::GenerateDump(pExceptionPointers); } ////////////////////////////////////////////////////////////////////////////// // // Some assertion functions // ////////////////////////////////////////////////////////////////////////////// void ZAssertImpl(bool bSucceeded, const char* psz, const char* pszFile, int line, const char* pszModule) { if (!bSucceeded) { // // Just in case this was a Win32 error get the last error // uint32_t dwError = GetLastError(); #ifdef _MSC_VER if (!g_papp) { // Imago removed asm (x64) on ?/?, integrated with mini dump on 6/10 __try { (*(int*)nullptr) = 0; } __except(GenerateDump(GetExceptionInformation())) {} } else if (g_papp->OnAssert(psz, pszFile, line, pszModule)) { g_papp->OnAssertBreak(); } #else ::abort(); #endif } } std::string GetExecutablePath() { char pCharModulePath[MAX_PATH]; GetModuleFileName(nullptr, pCharModulePath, MAX_PATH); std::string pathFull = std::string(pCharModulePath); std::string pathDirectory = pathFull.substr(0, pathFull.find_last_of("\\", pathFull.size())); return pathDirectory; } std::shared_ptr<SettableLogger> g_pDebugFileLogger = std::make_shared<SettableLogger>(std::make_shared<FileLogger>(GetExecutablePath() + "/debug.log", false)); std::shared_ptr<SettableLogger> g_pDebugOutputLogger = std::make_shared<SettableLogger>(std::make_shared<OutputLogger>()); ILogger* g_pDebugLogger = new MultiLogger(std::vector<std::shared_ptr<ILogger>>({ g_pDebugOutputLogger, g_pDebugFileLogger })); void ZDebugOutputImpl(const char *psz) { g_pDebugLogger->Log(std::string(psz)); } void retailf(const char* format, ...) { const size_t size = 2048; //Avalance: Changed to log longer messages. (From 512) char bfr[size]; va_list vl; va_start(vl, format); _vsnprintf_s(bfr, size, (size - 1), format, vl); //Avalanche: Fix off by one error. va_end(vl); ZDebugOutputImpl(bfr); } // mmf log to file on SRVLOG define as well as _DEBUG #ifdef _DEBUG #define SRVLOG #endif #ifdef SRVLOG // mmf changed this from _DEBUG void ZWarningImpl(bool bSucceeded, const char* psz, const char* pszFile, int line, const char* pszModule) { if (!bSucceeded) { debugf("%s(%d) : ShouldBe failed: '%s'\n", pszFile, line, psz); } } bool ZFailedImpl(HRESULT hr, const char* pszFile, int line, const char* pszModule) { bool bFailed = FAILED(hr); ZAssertImpl(!bFailed, "Function Failed", pszFile, line, pszModule); return bFailed; } bool ZSucceededImpl(HRESULT hr, const char* pszFile, int line, const char* pszModule) { bool bSucceeded = SUCCEEDED(hr); ZAssertImpl(bSucceeded, "Function Failed", pszFile, line, pszModule); return bSucceeded; } #ifdef _TRACE bool g_bEnableTrace = false; ZString g_strSpaces; int g_indent = 0; int g_line = 0; void SetStrSpaces() { g_strSpaces = " " + ZString((float)g_indent, 2, 0) + ZString(' ', g_indent * 2 + 1); } void ZTraceImpl(const char* pcc) { if (g_bEnableTrace) { ZDebugOutput(ZString((float)g_line, 4, 0) + g_strSpaces + ZString(pcc) + "\n"); } g_line++; } void ZEnterImpl(const char* pcc) { ZTraceImpl("enter " + ZString(pcc)); g_indent += 1; SetStrSpaces(); } void ZExitImpl(const char* pcc) { g_indent -= 1; SetStrSpaces(); ZTraceImpl("exit " + ZString(pcc)); } void ZStartTraceImpl(const char* pcc) { g_indent = 0; g_line = 0; SetStrSpaces(); ZTraceImpl(pcc); } #endif void debugf(const char* format, ...) { const size_t size = 2048; //Avalanche: Changed to handle longer messages (from 512) char bfr[size]; va_list vl; va_start(vl, format); _vsnprintf_s(bfr, size, (size - 1), format, vl); //Avalanche: Fix off by one error. va_end(vl); ZDebugOutputImpl(bfr); } void GlobalConfigureLoggers(bool bLogToOutput, bool bLogToFile) { g_pDebugLogger->Log("Changing logging method based on configuration"); //on startup this is logging to a generic logfile if (bLogToFile) { g_pDebugFileLogger->Log("Stopping file log, logging continued in timestamped log file"); g_pDebugFileLogger->SetLogger( CreateTimestampedFileLogger(GetExecutablePath() + "/debug_") ); } else { g_pDebugFileLogger->Log("Stopping file log."); g_pDebugFileLogger->SetLogger( NullLogger::GetInstance() ); } //this is enabled on startup if (bLogToOutput == false) { g_pDebugFileLogger->Log("Stopping output log"); g_pDebugOutputLogger->SetLogger(NullLogger::GetInstance()); } g_pDebugLogger->Log("Logging configuration completed"); } #endif // SRVLOG or _DEBUG ////////////////////////////////////////////////////////////////////////////// // // Win32 Application // ////////////////////////////////////////////////////////////////////////////// Win32App::Win32App() { g_papp = this; } Win32App::~Win32App() { } HRESULT Win32App::Initialize(const ZString& strCommandLine) { return S_OK; } void Win32App::Terminate() { } void Win32App::Exit(int value) { _CrtSetDbgFlag(0); _exit(value); } int Win32App::OnException(uint32_t code, EXCEPTION_POINTERS* pdata) { GenerateDump(pdata); return EXCEPTION_CONTINUE_SEARCH; } //Imago 6/10 LONG __stdcall Win32App::ExceptionHandler( EXCEPTION_POINTERS* pep ) { GenerateDump(pep); return EXCEPTION_EXECUTE_HANDLER; } #ifdef MemoryOutput TList<ZString> g_listOutput; #endif void Win32App::DebugOutput(const char *psz) { #ifdef MemoryOutput g_listOutput.PushFront(ZString(psz)); if (g_listOutput.GetCount() > 100) { g_listOutput.PopEnd(); } #else g_pDebugLogger->Log(psz); #endif } bool Win32App::OnAssert(const char* psz, const char* pszFile, int line, const char* pszModule) { ZDebugOutput( ZString("assertion failed: '") + psz + "' (" + pszFile + ":" + ZString(line) + ")\n" ); //return _CrtDbgReport(_CRT_ASSERT, pszFile, line, pszModule, psz) == 1; return true; } void Win32App::OnAssertBreak() { #ifdef MemoryOutput ZString str; TList<ZString>::Iterator iter(g_listOutput); while (!iter.End()) { str = iter.Value() + str; iter.Next(); } #endif // // Cause an exception // // Imago integrated with mini dump on 6/10 #ifdef _MSC_VER __try { (*(int*)nullptr) = 0; } __except(GenerateDump(GetExceptionInformation())) {} #else ::abort(); #endif } // KGJV - added for DX9 behavior - default is false. override in parent to change this bool Win32App::IsBuildDX9() { return false; } bool Win32App::WriteMemory( uint8_t* pTarget, const uint8_t* pSource, uint32_t Size ) { uint32_t ErrCode = 0; // Check parameters if( pTarget == nullptr ) { _ASSERTE( !_T("Target address is null.") ); return false; } if( pSource == nullptr ) { _ASSERTE( !_T("Source address is null.") ); return false; } if( Size == 0 ) { _ASSERTE( !_T("Source size is null.") ); return false; } if( IsBadReadPtr( pSource, Size ) ) { _ASSERTE( !_T("Source is unreadable.") ); return false; } // Modify protection attributes of the target memory page uint32_t OldProtect = 0; if( !VirtualProtect( pTarget, Size, PAGE_EXECUTE_READWRITE, LPDWORD(&OldProtect) ) ) { ErrCode = GetLastError(); _ASSERTE( !_T("VirtualProtect() failed.") ); return false; } // Write memory memcpy( pTarget, pSource, Size ); // Restore memory protection attributes of the target memory page uint32_t Temp = 0; if( !VirtualProtect( pTarget, Size, OldProtect, LPDWORD(&Temp) ) ) { ErrCode = GetLastError(); _ASSERTE( !_T("VirtualProtect() failed.") ); return false; } // Success return true; } bool Win32App::EnforceFilter( bool bEnforce ) { uint32_t ErrCode = 0; // Obtain the address of SetUnhandledExceptionFilter HMODULE hLib = GetModuleHandle( _T("kernel32.dll") ); if( hLib == nullptr ) { ErrCode = GetLastError(); _ASSERTE( !_T("GetModuleHandle(kernel32.dll) failed.") ); return false; } uint8_t* pTarget = (uint8_t*)GetProcAddress( hLib, "SetUnhandledExceptionFilter" ); if( pTarget == nullptr ) { ErrCode = GetLastError(); _ASSERTE( !_T("GetProcAddress(SetUnhandledExceptionFilter) failed.") ); return false; } if( IsBadReadPtr( pTarget, sizeof(OriginalBytes) ) ) { _ASSERTE( !_T("Target is unreadable.") ); return false; } if( bEnforce ) { // Save the original contents of SetUnhandledExceptionFilter memcpy( OriginalBytes, pTarget, sizeof(OriginalBytes) ); // Patch SetUnhandledExceptionFilter if( !WriteMemory( pTarget, PatchBytes, sizeof(PatchBytes) ) ) return false; } else { // Restore the original behavior of SetUnhandledExceptionFilter if( !WriteMemory( pTarget, OriginalBytes, sizeof(OriginalBytes) ) ) return false; } // Success return true; } ////////////////////////////////////////////////////////////////////////////// // // Win Main // ////////////////////////////////////////////////////////////////////////////// __declspec(dllexport) int WINAPI Win32Main(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { HRESULT hr; // seed the random number generator with the current time // (GetTickCount may be semi-predictable on server startup, so we add the // clock time to shake things up a bit) srand(GetTickCount() + (int)time(nullptr)); // mmf why is this done? // shift the stack locals and the heap by a random amount. char* pzSpacer = new char[4 * (int)random(21, 256)]; pzSpacer[0] = *(char*)_alloca(4 * (int)random(1, 256)); //Imago 6/10 // BT - STEAM - Replacing this with steam logging. /*SetUnhandledExceptionFilter(Win32App::ExceptionHandler); g_papp->EnforceFilter( true ); __try { */ do { BreakOnError(hr = Window::StaticInitialize()); // BUILD_DX9 - KGJV use runtime dynamic instead at preprocessor level if (g_papp->IsBuildDX9()) { BreakOnError(hr = g_papp->Initialize(lpszCmdLine)); } else { // Don't throw an error, if the user selects cancel it can return E_FAIL. hr = g_papp->Initialize(lpszCmdLine); } // BUILD_DX9 // // Win32App::Initialize() return S_FALSE if this is a command line app and // we shouldn't run the message loop // if (SUCCEEDED(hr) && S_FALSE != hr) { Window::MessageLoop(); } g_papp->Terminate(); Window::StaticTerminate(); } while (false); // BT - STEAM - Replacing this with steam logging. /* } __except (g_papp->OnException(_exception_code(), (EXCEPTION_POINTERS*)_exception_info())){ } delete pzSpacer; if( !g_papp->EnforceFilter( false ) ) { debugf("EnforceFilter(false) failed.\n"); return 0; }*/ return 0; }
24.498311
159
0.605116
FreeAllegiance
02082b5d69c4264e74197730f982e43693fb3c1f
260
hpp
C++
Planets/Graph.hpp
GEslinger/PhysClass
5e34167c34ca0e8779e4002063d95ffa24a24c9d
[ "BSD-2-Clause" ]
null
null
null
Planets/Graph.hpp
GEslinger/PhysClass
5e34167c34ca0e8779e4002063d95ffa24a24c9d
[ "BSD-2-Clause" ]
null
null
null
Planets/Graph.hpp
GEslinger/PhysClass
5e34167c34ca0e8779e4002063d95ffa24a24c9d
[ "BSD-2-Clause" ]
null
null
null
#ifndef GRAPH_H #define GRAPH_H #include <vector> #include <utility> // Header file for the graphing file std::pair<double,double> extrema(std::vector<double> v); std::pair<double,double> getLeastSquares(std::vector<double> x, std::vector<double> y); #endif
23.636364
87
0.746154
GEslinger
02098a73feec75805920a6f0064ac723be0d6723
2,003
hh
C++
src/blas/utils.hh
hmatuschek/linalg
b4b8337ba001b24572f13349cc5804a416bfe5a7
[ "MIT" ]
1
2016-05-24T15:27:52.000Z
2016-05-24T15:27:52.000Z
src/blas/utils.hh
hmatuschek/linalg
b4b8337ba001b24572f13349cc5804a416bfe5a7
[ "MIT" ]
null
null
null
src/blas/utils.hh
hmatuschek/linalg
b4b8337ba001b24572f13349cc5804a416bfe5a7
[ "MIT" ]
null
null
null
/* * This file is part of the Linalg project, a C++ interface to BLAS and LAPACK. * * The source-code is licensed under the terms of the MIT license, read LICENSE for more details. * * (c) 2011, 2012 Hannes Matuschek <hmatuschek at gmail dot com> */ #ifndef __LINALG_BLAS_UTILS_HH__ #define __LINALG_BLAS_UTILS_HH__ /* * Some helper macros to simplify binding to Fortran code. */ /** * Creates an new view to the same array, but ensures that the new view is in column-major * (Fortran) from. * * @ingroup blas */ #define BLAS_ENSURE_COLUMN_MAJOR(A, trans) ({ if(A.isRowMajor()) {A = A.t(); trans=BLAS_TRANSPOSE(trans);} else {} A;}) /** * Is true, (for a @c TriMatrix) if the matrix is stored in the upper-triangular part of the matrix. * * It returns how the matrix is stored in the memory, not if the view is a upper-triangular matrix. * * @ingroup blas */ #define BLAS_IS_UPPER(T) (T.isUpper()) /** * Is true, (for a @c TriMatrix) if the matrix is stored in the lower-triangular part of the matrix. * * It returns how the matrix is stored in the memory, not if the view is a lower-triangular matrix. * * @ingroup blas */ #define BLAS_IS_LOWER(T) (!T.isUpper()) /** * Returns true if the @c TriMatrix has a unit diagonal. * * @ingroup blas */ #define BLAS_HAS_UNIT_DIAG(T) (T.hasUnitDiag()) #define BLAS_UPLO_FLAG(T) BLAS_IS_UPPER(T) ? 'U' : 'L' #define BLAS_UNIT_DIAG_FLAG(T) BLAS_HAS_UNIT_DIAG(T) ? 'U' : 'N' #define BLAS_NUM_COLS(A, trans) ('N'==trans ? A.cols() : A.rows()) #define BLAS_NUM_ROWS(A, trans) ('N'==trans ? A.rows() : A.cols()) #define BLAS_LEADING_DIMENSION(A) (A.isRowMajor() ? A.strides(0) : A.strides(1)) #define BLAS_TRANSPOSE(trans) ('N' == trans ? 'T' : 'N') #define BLAS_TRANSPOSE_UPLO(trans, uplo) ('T' == uplo ? ('U'==uplo ? 'L' : 'U') : uplo) #define BLAS_DIMENSION(x) (x.dim()) #define BLAS_INCREMENT(x) (x.strides(0)) #endif // __LINALG_BLAS_UTILS_HH__
32.306452
119
0.658013
hmatuschek
020a06c3b0386487bf769fdb51b8d0e5db94421b
3,157
cpp
C++
groups/csa/csamisc/csamisc_shortcompare.cpp
hyrosen/bde_verify
c2db13c9f1649806bfd9155e2bffcbbcf9d54918
[ "Apache-2.0" ]
null
null
null
groups/csa/csamisc/csamisc_shortcompare.cpp
hyrosen/bde_verify
c2db13c9f1649806bfd9155e2bffcbbcf9d54918
[ "Apache-2.0" ]
null
null
null
groups/csa/csamisc/csamisc_shortcompare.cpp
hyrosen/bde_verify
c2db13c9f1649806bfd9155e2bffcbbcf9d54918
[ "Apache-2.0" ]
null
null
null
// csamisc_donotuseendl.cpp -*-C++-*- #include <clang/AST/Expr.h> #include <clang/ASTMatchers/ASTMatchFinder.h> #include <clang/ASTMatchers/ASTMatchers.h> #include <csabase_analyser.h> #include <csabase_debug.h> #include <csabase_registercheck.h> #include <csabase_report.h> #include <csabase_util.h> #include <csabase_visitor.h> #include <string> #include <unordered_set> using namespace clang; using namespace clang::ast_matchers; using namespace csabase; static std::string const check_name("short-compare"); namespace { struct data { }; struct report : Report<data> { INHERIT_REPORT_CTOR(report, Report, data); void operator()(const BinaryOperator *expr); }; void report::operator()(const BinaryOperator *expr) { if (expr->isComparisonOp()) { const auto *lhs = llvm::dyn_cast<ImplicitCastExpr>(expr->getLHS()); const auto *rhs = llvm::dyn_cast<ImplicitCastExpr>(expr->getRHS()); if (lhs && rhs) { const auto *lt = lhs->getType().getTypePtr()->getAs<BuiltinType>(); const auto *rt = rhs->getType().getTypePtr()->getAs<BuiltinType>(); if (lt && lt->getKind() == lt->Int && rt && rt->getKind() == rt->Int) { const auto *ls = lhs->getSubExpr(); const auto *rs = rhs->getSubExpr(); const auto *lst = ls->getType().getTypePtr()->getAs<BuiltinType>(); const auto *rst = rs->getType().getTypePtr()->getAs<BuiltinType>(); if (lst && rst && ((lst->getKind() == lst->Short && rst->getKind() == rst->UShort) || (lst->getKind() == lst->UShort && rst->getKind() == rst->Short))) { a.report(expr, check_name, "US01", "Comparison between signed and unsigned short " "may cause unexpected behavior"); } } } } } void subscribe(Analyser& analyser, Visitor& visitor, PPObserver& observer) // Hook up the callback functions. { visitor.onBinaryOperator += report(analyser); } } // close anonymous namespace // ----------------------------------------------------------------------------- static RegisterCheck c1(check_name, &subscribe); // ---------------------------------------------------------------------------- // Copyright (C) 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
34.315217
80
0.560025
hyrosen
020a0fa22c0b7915b733150f7e2839eeba5c0058
26,548
hpp
C++
libs/fft/FFTRealFixed.hpp
constcut/mtherapp
20b8e32361ef492d5b7cb4ff150f0956e952fdef
[ "MIT" ]
2
2022-03-04T17:54:48.000Z
2022-03-28T06:20:31.000Z
libs/fft/FFTRealFixed.hpp
constcut/aurals
bb00fac92a3a919867fe2e482c37fc0abe5e6984
[ "MIT" ]
null
null
null
libs/fft/FFTRealFixed.hpp
constcut/aurals
bb00fac92a3a919867fe2e482c37fc0abe5e6984
[ "MIT" ]
null
null
null
#ifndef FFTREALFIXED_H #define FFTREALFIXED_H #include <cstdint> #include <cassert> #include <cmath> #include <type_traits> const double PI = 3.1415926535897932384626433832795; const double SQRT2 = 1.41421356237309514547462185873883; template <class T> class DynArray { public: DynArray (); explicit DynArray (uint32_t size); ~DynArray (); inline uint32_t size () const; inline void resize (uint32_t new_size); inline const T& operator [] (uint32_t pos) const; inline T& operator [] (uint32_t pos); DynArray(const DynArray& other) = delete; DynArray& operator = (const DynArray& other) = delete; bool operator == (const DynArray& other) = delete; bool operator != (const DynArray& other) = delete; private: T* _data_ptr; uint32_t _len; }; template <class T, long length> class Array { public: Array () = default; inline const T& operator [] (long pos) const; inline T& operator [] (long pos); static inline long size (); Array (const Array& other) = delete; Array& operator = (const Array& other) = delete; bool operator == (const Array& other) = delete; bool operator != (const Array& other) = delete; private: T _data_arr[length]; }; // class Array template <class T> class OscSinCos { public: OscSinCos (); inline void set_step (double angle_rad); inline T get_cos () const; inline T get_sin () const; inline void step (); inline void clear_buffers (); OscSinCos (const OscSinCos& other) = delete; OscSinCos& operator = (const OscSinCos& other) = delete; bool operator == (const OscSinCos& other) = delete; bool operator != (const OscSinCos& other) = delete; private: T _pos_cos; // Current phase expressed with sin and cos. [-1 ; 1] T _pos_sin; // - T _step_cos; // Phase increment per step, [-1 ; 1] T _step_sin; // - }; // class OscSinCos //Dynamic array implementation template <class T> DynArray <T>::DynArray() : _data_ptr (nullptr), _len (0) {} template <class T> DynArray <T>::DynArray(uint32_t size) : _data_ptr(nullptr), _len (size) { //static_assert (_len > 0, "DynArray zero len not expected"); _data_ptr = new T[_len]; } template <class T> DynArray <T>::~DynArray() { delete [] _data_ptr; _data_ptr = nullptr; _len = 0; } template <class T> uint32_t DynArray <T>::size() const { return (_len); } template <class T> void DynArray <T>::resize(uint32_t new_size) { assert (new_size > 0); _len = new_size; delete [] _data_ptr; _data_ptr = new T[_len]; } template <class T> const T& DynArray <T>::operator[] (uint32_t pos) const { assert (pos >= 0); assert (pos < _len); return (_data_ptr [pos]); } template <class T> T& DynArray <T>::operator[] (uint32_t pos) { assert (pos >= 0); assert (pos < _len); return (_data_ptr [pos]); } //Array implementation template <class T, long length> const T& Array <T, length>::operator [] (long pos) const { assert (pos >= 0); assert (pos < length); return (_data_arr [pos]); } template <class T, long length> T& Array <T, length>::operator [] (long pos) { assert (pos >= 0); assert (pos < length); return (_data_arr [pos]); } template <class T, long length> long Array <T, length>::size () { return (length); } //OscSinCos implementation template <class T> OscSinCos <T>::OscSinCos () : _pos_cos(1), _pos_sin (0), _step_cos(1), _step_sin (0) {} template <class T> void OscSinCos <T>::set_step (double angle_rad) { _step_cos = std::cos(angle_rad); _step_sin = std::sin(angle_rad); } template <class T> T OscSinCos <T>::get_cos () const { return _pos_cos; } template <class T> T OscSinCos <T>::get_sin () const { return _pos_sin; } template <class T> void OscSinCos <T>::step () { const T old_cos = _pos_cos; const T old_sin = _pos_sin; _pos_cos = old_cos * _step_cos - old_sin * _step_sin; _pos_sin = old_cos * _step_sin + old_sin * _step_cos; } template <class T> void OscSinCos <T>::clear_buffers () { if (std::is_same<float, T>()) { _pos_cos = 1.f; _pos_sin = 0.f; } if (std::is_same<double, T>()) { _pos_cos = 1.; _pos_sin = 0.; } } #define DataType float //First just fast copy template <int ALGO> class FFTRealUseTrigo { public: typedef OscSinCos <DataType> OscType; inline static void prepare (OscType &osc); inline static void iterate (OscType &osc, DataType &c, DataType &s, const DataType cos_ptr [], long index_c, long index_s); private: FFTRealUseTrigo (); ~FFTRealUseTrigo (); FFTRealUseTrigo (const FFTRealUseTrigo &other); FFTRealUseTrigo & operator = (const FFTRealUseTrigo &other); bool operator == (const FFTRealUseTrigo &other); bool operator != (const FFTRealUseTrigo &other); }; // class FFTRealUseTrigo template <int ALGO> void FFTRealUseTrigo <ALGO>::prepare (OscType &osc) { osc.clear_buffers (); } template <> inline void FFTRealUseTrigo <0>::prepare ([[maybe_unused]]OscType &osc) { // Nothing } template <int ALGO> void FFTRealUseTrigo <ALGO>::iterate (OscType &osc, DataType &c, DataType &s, [[maybe_unused]] const DataType cos_ptr [], [[maybe_unused]] long index_c, [[maybe_unused]] long index_s) { osc.step (); c = osc.get_cos (); s = osc.get_sin (); } template <> inline void FFTRealUseTrigo <0>::iterate ([[maybe_unused]] OscType &osc, DataType &c, DataType &s, const DataType cos_ptr [], long index_c, long index_s) { c = cos_ptr [index_c]; s = cos_ptr [index_s]; } template <int P> class FFTRealSelect { public: inline static float * sel_bin (float *e_ptr, float *o_ptr); private: FFTRealSelect (); ~FFTRealSelect (); FFTRealSelect (const FFTRealSelect &other); FFTRealSelect& operator = (const FFTRealSelect &other); bool operator == (const FFTRealSelect &other); bool operator != (const FFTRealSelect &other); }; // class FFTRealSelect template <int P> float * FFTRealSelect <P>::sel_bin ([[maybe_unused]] float *e_ptr, float *o_ptr) { return (o_ptr); } template <> inline float * FFTRealSelect <0>::sel_bin (float *e_ptr, [[maybe_unused]] float *o_ptr) { return (e_ptr); } template <int PASS> class FFTRealPassInverse { public: typedef OscSinCos <DataType> OscType; inline static void process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType f_ptr [], const DataType cos_ptr [], long cos_len, const uint32_t br_ptr [], OscType osc_list []); inline static void process_rec (long len, DataType dest_ptr [], DataType src_ptr [], const DataType cos_ptr [], long cos_len, const uint32_t br_ptr [], OscType osc_list []); inline static void process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType cos_ptr [], long cos_len, const uint32_t br_ptr [], OscType osc_list []); private: FFTRealPassInverse (); FFTRealPassInverse (const FFTRealPassInverse &other); FFTRealPassInverse & operator = (const FFTRealPassInverse &other); bool operator == (const FFTRealPassInverse &other); bool operator != (const FFTRealPassInverse &other); }; // class FFTRealPassInverse template <int PASS> void FFTRealPassInverse <PASS>::process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType f_ptr [], const DataType cos_ptr [], long cos_len, const uint32_t br_ptr [], OscType osc_list []) { process_internal ( len, dest_ptr, f_ptr, cos_ptr, cos_len, br_ptr, osc_list ); FFTRealPassInverse <PASS - 1>::process_rec ( len, src_ptr, dest_ptr, cos_ptr, cos_len, br_ptr, osc_list ); } template <int PASS> void FFTRealPassInverse <PASS>::process_rec (long len, DataType dest_ptr [], DataType src_ptr [], const DataType cos_ptr [], long cos_len, const uint32_t br_ptr [], OscType osc_list []) { process_internal ( len, dest_ptr, src_ptr, cos_ptr, cos_len, br_ptr, osc_list ); FFTRealPassInverse <PASS - 1>::process_rec ( len, src_ptr, dest_ptr, cos_ptr, cos_len, br_ptr, osc_list ); } template <> inline void FFTRealPassInverse <0>::process_rec ([[maybe_unused]] long len, [[maybe_unused]] DataType dest_ptr [], [[maybe_unused]] DataType src_ptr [], [[maybe_unused]] const DataType cos_ptr [], [[maybe_unused]] long cos_len, [[maybe_unused]] const uint32_t br_ptr [], [[maybe_unused]] OscType osc_list []) { // Stops recursion } template <int PASS> void FFTRealPassInverse <PASS>::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType cos_ptr [], long cos_len, [[maybe_unused]] const uint32_t br_ptr [], OscType osc_list []) { const uint32_t dist = 1L << (PASS - 1); const uint32_t c1_r = 0; const uint32_t c1_i = dist; const uint32_t c2_r = dist * 2; const uint32_t c2_i = dist * 3; const uint32_t cend = dist * 4; const uint32_t table_step = cos_len >> (PASS - 1); enum { TRIGO_OSC = PASS - 12 }; enum { TRIGO_DIRECT = (TRIGO_OSC >= 0) ? 1 : 0 }; uint32_t coef_index = 0; do { const DataType * const sf = src_ptr + coef_index; DataType * const df = dest_ptr + coef_index; // Extreme coefficients are always real df [c1_r] = sf [c1_r] + sf [c2_r]; df [c2_r] = sf [c1_r] - sf [c2_r]; df [c1_i] = sf [c1_i] * 2; df [c2_i] = sf [c2_i] * 2; FFTRealUseTrigo <TRIGO_DIRECT>::prepare (osc_list [TRIGO_OSC]); // Others are conjugate complex numbers for (uint32_t i = 1; i < dist; ++ i) { df [c1_r + i] = sf [c1_r + i] + sf [c2_r - i]; df [c1_i + i] = sf [c2_r + i] - sf [cend - i]; DataType c; DataType s; FFTRealUseTrigo <TRIGO_DIRECT>::iterate ( osc_list [TRIGO_OSC], c, s, cos_ptr, i * table_step, (dist - i) * table_step ); const DataType vr = sf [c1_r + i] - sf [c2_r - i]; const DataType vi = sf [c2_r + i] + sf [cend - i]; df [c2_r + i] = vr * c + vi * s; df [c2_i + i] = vi * c - vr * s; } coef_index += cend; } while (coef_index < len); } template <> inline void FFTRealPassInverse <2>::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], [[maybe_unused]] const DataType cos_ptr [], [[maybe_unused]] long cos_len, [[maybe_unused]] const uint32_t br_ptr [], [[maybe_unused]] OscType osc_list []) { // Antepenultimate pass const DataType sqrt2_2 = DataType (SQRT2 * 0.5); uint32_t coef_index = 0; do { dest_ptr [coef_index ] = src_ptr [coef_index] + src_ptr [coef_index + 4]; dest_ptr [coef_index + 4] = src_ptr [coef_index] - src_ptr [coef_index + 4]; dest_ptr [coef_index + 2] = src_ptr [coef_index + 2] * 2; dest_ptr [coef_index + 6] = src_ptr [coef_index + 6] * 2; dest_ptr [coef_index + 1] = src_ptr [coef_index + 1] + src_ptr [coef_index + 3]; dest_ptr [coef_index + 3] = src_ptr [coef_index + 5] - src_ptr [coef_index + 7]; const DataType vr = src_ptr [coef_index + 1] - src_ptr [coef_index + 3]; const DataType vi = src_ptr [coef_index + 5] + src_ptr [coef_index + 7]; dest_ptr [coef_index + 5] = (vr + vi) * sqrt2_2; dest_ptr [coef_index + 7] = (vi - vr) * sqrt2_2; coef_index += 8; } while (coef_index < len); } template <> inline void FFTRealPassInverse <1>::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], [[maybe_unused]] const DataType cos_ptr [], [[maybe_unused]] long cos_len, const uint32_t br_ptr [], [[maybe_unused]] OscType osc_list []) { // Penultimate and last pass at once const uint32_t qlen = len >> 2; uint32_t coef_index = 0; do { const uint32_t ri_0 = br_ptr [coef_index >> 2]; const DataType b_0 = src_ptr [coef_index ] + src_ptr [coef_index + 2]; const DataType b_2 = src_ptr [coef_index ] - src_ptr [coef_index + 2]; const DataType b_1 = src_ptr [coef_index + 1] * 2; const DataType b_3 = src_ptr [coef_index + 3] * 2; dest_ptr [ri_0 ] = b_0 + b_1; dest_ptr [ri_0 + 2 * qlen] = b_0 - b_1; dest_ptr [ri_0 + 1 * qlen] = b_2 + b_3; dest_ptr [ri_0 + 3 * qlen] = b_2 - b_3; coef_index += 4; } while (coef_index < len); } template <int PASS> class FFTRealPassDirect { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ public: typedef OscSinCos <DataType> OscType; inline static void process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [], const DataType cos_ptr [], long cos_len, const uint32_t br_ptr [], OscType osc_list []); private: FFTRealPassDirect (); FFTRealPassDirect (const FFTRealPassDirect &other); FFTRealPassDirect & operator = (const FFTRealPassDirect &other); bool operator == (const FFTRealPassDirect &other); bool operator != (const FFTRealPassDirect &other); }; // class FFTRealPassDirect template <> inline void FFTRealPassDirect <1>::process (long len, DataType dest_ptr [], [[maybe_unused]] DataType src_ptr [], const DataType x_ptr [], [[maybe_unused]] const DataType cos_ptr [], [[maybe_unused]] long cos_len, const uint32_t br_ptr [], [[maybe_unused]] OscType osc_list []) { // First and second pass at once const uint32_t qlen = len >> 2; uint32_t coef_index = 0; do { // To do: unroll the loop (2x). const uint32_t ri_0 = br_ptr [coef_index >> 2]; const uint32_t ri_1 = ri_0 + 2 * qlen; // bit_rev_lut_ptr [coef_index + 1]; const uint32_t ri_2 = ri_0 + 1 * qlen; // bit_rev_lut_ptr [coef_index + 2]; const uint32_t ri_3 = ri_0 + 3 * qlen; // bit_rev_lut_ptr [coef_index + 3]; DataType * const df2 = dest_ptr + coef_index; df2 [1] = x_ptr [ri_0] - x_ptr [ri_1]; df2 [3] = x_ptr [ri_2] - x_ptr [ri_3]; const DataType sf_0 = x_ptr [ri_0] + x_ptr [ri_1]; const DataType sf_2 = x_ptr [ri_2] + x_ptr [ri_3]; df2 [0] = sf_0 + sf_2; df2 [2] = sf_0 - sf_2; coef_index += 4; } while (coef_index < len); } template <> inline void FFTRealPassDirect <2>::process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [], const DataType cos_ptr [], long cos_len, const uint32_t br_ptr [], OscType osc_list []) { // Executes "previous" passes first. Inverts source and destination buffers FFTRealPassDirect <1>::process ( len, src_ptr, dest_ptr, x_ptr, cos_ptr, cos_len, br_ptr, osc_list ); // Third pass const DataType sqrt2_2 = SQRT2 * 0.5; DataType v; uint32_t coef_index = 0; do { dest_ptr [coef_index ] = src_ptr [coef_index] + src_ptr [coef_index + 4]; dest_ptr [coef_index + 4] = src_ptr [coef_index] - src_ptr [coef_index + 4]; dest_ptr [coef_index + 2] = src_ptr [coef_index + 2]; dest_ptr [coef_index + 6] = src_ptr [coef_index + 6]; v = (src_ptr [coef_index + 5] - src_ptr [coef_index + 7]) * sqrt2_2; dest_ptr [coef_index + 1] = src_ptr [coef_index + 1] + v; dest_ptr [coef_index + 3] = src_ptr [coef_index + 1] - v; v = (src_ptr [coef_index + 5] + src_ptr [coef_index + 7]) * sqrt2_2; dest_ptr [coef_index + 5] = v + src_ptr [coef_index + 3]; dest_ptr [coef_index + 7] = v - src_ptr [coef_index + 3]; coef_index += 8; } while (coef_index < len); } template <int PASS> void FFTRealPassDirect <PASS>::process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [], const DataType cos_ptr [], long cos_len, const uint32_t br_ptr [], OscType osc_list []) { // Executes "previous" passes first. Inverts source and destination buffers FFTRealPassDirect <PASS - 1>::process ( len, src_ptr, dest_ptr, x_ptr, cos_ptr, cos_len, br_ptr, osc_list ); const uint32_t dist = 1L << (PASS - 1); const uint32_t c1_r = 0; const uint32_t c1_i = dist; const uint32_t c2_r = dist * 2; const uint32_t c2_i = dist * 3; const uint32_t cend = dist * 4; const uint32_t table_step = cos_len >> (PASS - 1); enum { TRIGO_OSC = PASS - 12 }; enum { TRIGO_DIRECT = (TRIGO_OSC >= 0) ? 1 : 0 }; uint32_t coef_index = 0; do { const DataType * const sf = src_ptr + coef_index; DataType * const df = dest_ptr + coef_index; // Extreme coefficients are always real df [c1_r] = sf [c1_r] + sf [c2_r]; df [c2_r] = sf [c1_r] - sf [c2_r]; df [c1_i] = sf [c1_i]; df [c2_i] = sf [c2_i]; FFTRealUseTrigo <TRIGO_DIRECT>::prepare (osc_list [TRIGO_OSC]); // Others are conjugate complex numbers for (uint32_t i = 1; i < dist; ++ i) { DataType c; DataType s; FFTRealUseTrigo <TRIGO_DIRECT>::iterate ( osc_list [TRIGO_OSC], c, s, cos_ptr, i * table_step, (dist - i) * table_step ); const DataType sf_r_i = sf [c1_r + i]; const DataType sf_i_i = sf [c1_i + i]; const DataType v1 = sf [c2_r + i] * c - sf [c2_i + i] * s; df [c1_r + i] = sf_r_i + v1; df [c2_r - i] = sf_r_i - v1; const DataType v2 = sf [c2_r + i] * s + sf [c2_i + i] * c; df [c2_r + i] = v2 + sf_i_i; df [cend - i] = v2 - sf_i_i; } coef_index += cend; } while (coef_index < len); } template <int LL2> class FFTRealFixLen { typedef int CompileTimeCheck1 [(LL2 >= 0) ? 1 : -1]; typedef int CompileTimeCheck2 [(LL2 <= 30) ? 1 : -1]; /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ public: typedef OscSinCos <DataType> OscType; enum { FFT_LEN_L2 = LL2 }; enum { FFT_LEN = 1 << FFT_LEN_L2 }; FFTRealFixLen (); inline uint32_t get_length () const; void do_fft (DataType f [], const DataType x []); void do_ifft (const DataType f [], DataType x []); void rescale (DataType x []) const; /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ protected: /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ private: enum { TRIGO_BD_LIMIT = 12 }; enum { BR_ARR_SIZE_L2 = ((FFT_LEN_L2 - 3) < 0) ? 0 : (FFT_LEN_L2 - 2) }; enum { BR_ARR_SIZE = 1 << BR_ARR_SIZE_L2 }; enum { TRIGO_BD = ((FFT_LEN_L2 - TRIGO_BD_LIMIT) < 0) ? (int)FFT_LEN_L2 : (int)TRIGO_BD_LIMIT }; enum { TRIGO_TABLE_ARR_SIZE_L2 = (LL2 < 4) ? 0 : (TRIGO_BD - 2) }; enum { TRIGO_TABLE_ARR_SIZE = 1 << TRIGO_TABLE_ARR_SIZE_L2 }; enum { NBR_TRIGO_OSC = FFT_LEN_L2 - TRIGO_BD }; enum { TRIGO_OSC_ARR_SIZE = (NBR_TRIGO_OSC > 0) ? NBR_TRIGO_OSC : 1 }; void build_br_lut (); void build_trigo_lut (); void build_trigo_osc (); DynArray <DataType> _buffer; DynArray <uint32_t> _br_data; DynArray <DataType> _trigo_data; Array <OscType, TRIGO_OSC_ARR_SIZE> _trigo_osc; /*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ private: FFTRealFixLen (const FFTRealFixLen &other); FFTRealFixLen& operator = (const FFTRealFixLen &other); bool operator == (const FFTRealFixLen &other); bool operator != (const FFTRealFixLen &other); }; // class FFTRealFixLen template <int LL2> FFTRealFixLen <LL2>::FFTRealFixLen () : _buffer (FFT_LEN) , _br_data (BR_ARR_SIZE) , _trigo_data (TRIGO_TABLE_ARR_SIZE) , _trigo_osc () { build_br_lut (); build_trigo_lut (); build_trigo_osc (); } template <int LL2> uint32_t FFTRealFixLen<LL2>::get_length() const { return (FFT_LEN); } // General case template <int LL2> void FFTRealFixLen <LL2>::do_fft (DataType f [], const DataType x []) { assert (f != 0); assert (x != 0); assert (x != f); assert (FFT_LEN_L2 >= 3); // Do the transform in several passes const DataType * cos_ptr = &_trigo_data [0]; const uint32_t * br_ptr = &_br_data [0]; FFTRealPassDirect <FFT_LEN_L2 - 1>::process ( FFT_LEN, f, &_buffer [0], x, cos_ptr, TRIGO_TABLE_ARR_SIZE, br_ptr, &_trigo_osc [0] ); } // 4-point FFT template <> inline void FFTRealFixLen <2>::do_fft (DataType f [], const DataType x []) { assert (f != 0); assert (x != 0); assert (x != f); f [1] = x [0] - x [2]; f [3] = x [1] - x [3]; const DataType b_0 = x [0] + x [2]; const DataType b_2 = x [1] + x [3]; f [0] = b_0 + b_2; f [2] = b_0 - b_2; } // 2-point FFT template <> inline void FFTRealFixLen <1>::do_fft (DataType f [], const DataType x []) { assert (f != 0); assert (x != 0); assert (x != f); f [0] = x [0] + x [1]; f [1] = x [0] - x [1]; } // 1-point FFT template <> inline void FFTRealFixLen <0>::do_fft (DataType f [], const DataType x []) { assert (f != 0); assert (x != 0); f [0] = x [0]; } // General case template <int LL2> void FFTRealFixLen <LL2>::do_ifft (const DataType f [], DataType x []) { assert (f != 0); assert (x != 0); assert (x != f); assert (FFT_LEN_L2 >= 3); // Do the transform in several passes DataType * s_ptr = FFTRealSelect <FFT_LEN_L2 & 1>::sel_bin (&_buffer [0], x); DataType * d_ptr = FFTRealSelect <FFT_LEN_L2 & 1>::sel_bin (x, &_buffer [0]); const DataType * cos_ptr = &_trigo_data [0]; const uint32_t * br_ptr = &_br_data [0]; FFTRealPassInverse <FFT_LEN_L2 - 1>::process ( FFT_LEN, d_ptr, s_ptr, f, cos_ptr, TRIGO_TABLE_ARR_SIZE, br_ptr, &_trigo_osc [0] ); } // 4-point IFFT template <> inline void FFTRealFixLen <2>::do_ifft (const DataType f [], DataType x []) { assert (f != 0); assert (x != 0); assert (x != f); const DataType b_0 = f [0] + f [2]; const DataType b_2 = f [0] - f [2]; x [0] = b_0 + f [1] * 2; x [2] = b_0 - f [1] * 2; x [1] = b_2 + f [3] * 2; x [3] = b_2 - f [3] * 2; } // 2-point IFFT template <> inline void FFTRealFixLen <1>::do_ifft (const DataType f [], DataType x []) { assert (f != 0); assert (x != 0); assert (x != f); x [0] = f [0] + f [1]; x [1] = f [0] - f [1]; } // 1-point IFFT template <> inline void FFTRealFixLen <0>::do_ifft (const DataType f [], DataType x []) { assert (f != 0); assert (x != 0); assert (x != f); x [0] = f [0]; } template <int LL2> void FFTRealFixLen <LL2>::rescale (DataType x []) const { assert (x != 0); const DataType mul = 1.0 / FFT_LEN; if (FFT_LEN < 4) { long i = FFT_LEN - 1; do { x [i] *= mul; --i; } while (i >= 0); } else { assert ((FFT_LEN & 3) == 0); // Could be optimized with SIMD instruction sets (needs alignment check) long i = FFT_LEN - 4; do { x [i + 0] *= mul; x [i + 1] *= mul; x [i + 2] *= mul; x [i + 3] *= mul; i -= 4; } while (i >= 0); } } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ template <int LL2> void FFTRealFixLen <LL2>::build_br_lut () { _br_data [0] = 0; for (uint32_t cnt = 1; cnt < BR_ARR_SIZE; ++cnt) { uint32_t index = cnt << 2; uint32_t br_index = 0; int bit_cnt = FFT_LEN_L2; do { br_index <<= 1; br_index += (index & 1); index >>= 1; -- bit_cnt; } while (bit_cnt > 0); _br_data [cnt] = br_index; } } template <int LL2> void FFTRealFixLen <LL2>::build_trigo_lut () { const double mul = (0.5 * PI) / TRIGO_TABLE_ARR_SIZE; for (uint32_t i = 0; i < TRIGO_TABLE_ARR_SIZE; ++ i) { using namespace std; _trigo_data [i] = DataType (cos (i * mul)); } } template <int LL2> void FFTRealFixLen <LL2>::build_trigo_osc () { for (int i = 0; i < NBR_TRIGO_OSC; ++i) { OscType & osc = _trigo_osc [i]; const uint32_t len = (TRIGO_TABLE_ARR_SIZE) << (i + 1); const double mul = (0.5 * PI) / len; osc.set_step (mul); } } #endif // FFTREALFIXED_H
24.672862
183
0.548403
constcut
0215dc982e9b92fb0d9f4cc0303459c635969a42
3,885
cpp
C++
src/data_science/logistic_regression.cpp
arotem3/numerics
ba208d9fc0ccb9471cfec9927a21622eb3535f54
[ "Apache-2.0" ]
18
2019-04-18T17:34:49.000Z
2021-11-15T07:57:29.000Z
src/data_science/logistic_regression.cpp
arotem3/numerics
ba208d9fc0ccb9471cfec9927a21622eb3535f54
[ "Apache-2.0" ]
null
null
null
src/data_science/logistic_regression.cpp
arotem3/numerics
ba208d9fc0ccb9471cfec9927a21622eb3535f54
[ "Apache-2.0" ]
4
2019-12-02T04:04:21.000Z
2022-02-17T08:23:09.000Z
#include <numerics.hpp> void mult_coefs_serial(arma::mat& yh, const arma::vec& coefs, const arma::rowvec& b, const arma::mat& w, const arma::mat& x) { yh = arma::repmat(coefs.subvec(0,b.n_elem-1).as_row(), x.n_rows, 1); arma::uword start = b.n_elem; for (u_long i=0; i < w.n_rows; ++i) { for (u_long j=0; j < w.n_cols; ++j) { arma::uword ij = start + arma::sub2ind(arma::size(w), i, j); yh.col(j) += x.col(i) * coefs(ij); } } numerics::softmax_inplace(yh); } arma::vec grad_serial(const arma::mat& yh, const arma::vec& coefs, const arma::rowvec& b, const arma::mat& w, const arma::mat& x, const arma::mat& y, double L) { u_long size = x.n_cols + 1; size *= y.n_cols; arma::vec out(size); arma::mat res = y - yh; for (u_long i=0; i < b.n_elem; ++i) { out(i) = -arma::sum(res.col(i)); } arma::uword start = b.n_elem; for (u_long i=0; i < w.n_rows; ++i) { for (u_long j=0; j < w.n_cols; ++j) { arma::uword ij = start + arma::sub2ind(arma::size(w), i, j); out(ij) = -arma::dot(x.col(i), res.col(j)); out(ij) += L * coefs(ij); } } return out; } void fit_logreg(arma::mat& w, const arma::sp_mat& I, const arma::mat& P, const arma::mat& y, double L) { u_long n = P.n_cols-1; auto f = [&](const arma::vec& coefs) -> double { arma::mat W = arma::reshape(coefs, n+1, y.n_cols); arma::mat yh = P * W; numerics::softmax_inplace(yh); return 0.5*L*arma::trace(W.t()*I*W) - arma::accu(yh % y); }; auto grad_f = [&](const arma::vec& coefs) -> arma::vec { arma::mat W = arma::reshape(coefs, n+1, y.n_cols); arma::mat yh = P * W; numerics::softmax_inplace(yh); arma::mat df = L*I*W - P.t()*(y - yh); return df.as_col(); }; arma::vec coefs = w.as_col(); numerics::optimization::TrustMin fmin; fmin.minimize(coefs, f, grad_f); w = arma::reshape(coefs, n+1, y.n_cols); } arma::mat pred_logreg(const arma::mat& w, const arma::mat& P) { arma::mat yh = P*w; numerics::softmax_inplace(yh); return yh; } void numerics::LogisticRegression::fit(const arma::mat& x, const arma::uvec& y) { _check_xy(x, y); _dim = x.n_cols; u_long nobs = x.n_rows; _encoder.fit(y); arma::mat onehot = _encoder.encode(y); u_long n = x.n_cols; arma::mat P(nobs, n+1); arma::sp_mat I = arma::speye(n+1,n+1); I(0,0) = 0; P.col(0).ones(); P.cols(1,n) = x; arma::mat W = arma::zeros(n+1, onehot.n_cols); if (_lambda < 0) { u_short nfolds = 5; if (nobs / nfolds < 50) nfolds = 3; KFolds2Arr<double,double> split(nfolds); split.fit(P, onehot); auto cv = [&](double L) -> double { L = std::pow(10.0, L); double score = 0; for (u_short i=0; i < nfolds; ++i) { fit_logreg(W, I, split.trainX(i), split.trainY(i), L); arma::mat p = pred_logreg(W, split.testX(i)); score -= accuracy_score(_encoder.decode(split.testY(i)), _encoder.decode(p)); } return score; }; _lambda = optimization::fminbnd(cv, -5, 4, 0.1); _lambda = std::pow(10.0, _lambda); } fit_logreg(W, I, P, onehot, _lambda); _b = W.row(0); _w = W.rows(1,n); } arma::mat numerics::LogisticRegression::predict_proba(const arma::mat& x) const { _check_x(x); arma::mat yh = x * _w; yh.each_row() += _b; softmax_inplace(yh); return yh; } arma::uvec numerics::LogisticRegression::predict(const arma::mat& x) const { return _encoder.decode(predict_proba(x)); } double numerics::LogisticRegression::score(const arma::mat& x, const arma::uvec& y) const { _check_xy(x,y); return accuracy_score(y, predict(x)); }
29.656489
161
0.551094
arotem3
0217515b32bbeec62e4d1faf4e81d57b3d7b1c5f
2,409
cpp
C++
Lowest Common Ancestor (LCA-problem)/DISQUERY - Distance Query (sol. 2).cpp
yokeshrana/Fast_Algorithms_in_Data_Structures
2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2
[ "MIT" ]
4
2021-01-15T16:30:48.000Z
2021-08-12T03:17:00.000Z
Lowest Common Ancestor (LCA-problem)/DISQUERY - Distance Query (sol. 2).cpp
andy489/Fast_Algorithms_in_Data_Structures
0f28a75030df3367902f0aa859a34096ea2b2582
[ "MIT" ]
null
null
null
Lowest Common Ancestor (LCA-problem)/DISQUERY - Distance Query (sol. 2).cpp
andy489/Fast_Algorithms_in_Data_Structures
0f28a75030df3367902f0aa859a34096ea2b2582
[ "MIT" ]
2
2021-02-24T14:50:08.000Z
2021-02-28T17:39:41.000Z
/* github.com/andy489 Complexity: <O(n.log(n), log(n))> Link: http://www.spoj.com/problems/DISQUERY/ */ #include <stdio.h> #include <vector> using namespace std; #define pii pair<int,int> #define pb push_back #define f first #define s second const int mxN = 1e5 + 5; const int mxLog = 17; vector<pair<int, int>> adj[mxN]; // anc = ancestor, anc[v][k] stores 2^k-th ancestor of vertex v int anc[mxN][mxLog], dep[mxN], mini[mxN][mxLog], maxi[mxN][mxLog]; void dfs(int u = 1, int p = -1, int w = 0) { int i; anc[u][0] = p; if (p != -1) { dep[u] = dep[p] + 1; mini[u][0] = maxi[u][0] = w; } for (i = 1; i < mxLog; ++i) { if (anc[u][i - 1] != -1) { anc[u][i] = anc[anc[u][i - 1]][i - 1]; maxi[u][i] = max(maxi[u][i - 1], maxi[anc[u][i - 1]][i - 1]); mini[u][i] = min(mini[u][i - 1], mini[anc[u][i - 1]][i - 1]); } else break; } for (const auto &child : adj[u]) if (child.f ^ p) dfs(child.f, u, child.s); } pii lca(int u, int v) { int i; int ansMini = 1e9, ansMaxi = -1; if (dep[u] > dep[v]) swap(u, v); for (i = mxLog - 1; i >= 0; --i) { if (anc[v][i] != -1 and dep[anc[v][i]] >= dep[u]) { ansMini = min(ansMini, mini[v][i]); ansMaxi = max(ansMaxi, maxi[v][i]); v = anc[v][i]; } } if (v == u) return {ansMini, ansMaxi}; for (i = mxLog - 1; i >= 0; --i) { if (anc[v][i] != anc[u][i]) { ansMini = min(ansMini, min(mini[v][i],mini[u][i])); ansMaxi = max(ansMaxi, max(maxi[v][i],maxi[u][i])); v = anc[v][i]; u = anc[u][i]; } } ansMini = min(ansMini, min(mini[v][0], mini[u][0])); ansMaxi = max(ansMaxi, max(maxi[v][0],maxi[u][0])); return {ansMini, ansMaxi}; } int main() { int n, i, j, u, v, w; scanf("%d", &n); for (i = 1; i < n; ++i) { scanf("%d%d%d", &u, &v, &w); adj[u].pb({v, w}); adj[v].pb({u, w}); } for (i = 1; i <= n; ++i) { for (j = 0; j < mxLog; ++j) { anc[i][j] = -1; maxi[i][j] = -1; mini[i][j] = 1e9; } } dfs(); int q; scanf("%d", &q); while (q--) { scanf("%d%d", &u, &v); pii ans = lca(u, v); printf("%d %d\n", ans.f, ans.s); } return 0; }
24.581633
73
0.429639
yokeshrana
021cfde3788cdde45bee5f039475f69d25bb37e8
1,023
cpp
C++
FangameReader/DetectorMouseController.cpp
TheBiob/DeadSplit
2e29bae2b86fa689ed9c28d345f2e8743b10c115
[ "MIT" ]
3
2019-04-02T19:23:35.000Z
2021-04-30T03:57:15.000Z
FangameReader/DetectorMouseController.cpp
TheBiob/DeadSplit
2e29bae2b86fa689ed9c28d345f2e8743b10c115
[ "MIT" ]
1
2018-07-10T22:34:41.000Z
2018-07-10T22:52:43.000Z
FangameReader/DetectorMouseController.cpp
TheBiob/DeadSplit
2e29bae2b86fa689ed9c28d345f2e8743b10c115
[ "MIT" ]
3
2020-12-28T19:06:07.000Z
2021-01-30T10:09:56.000Z
#include <common.h> #pragma hdrstop #include <DetectorMouseController.h> #include <FangameDetectorState.h> #include <MouseTarget.h> #include <DetectorActionController.h> namespace Fangame { ////////////////////////////////////////////////////////////////////////// void CDetectorMouseController::OnMouseMove() { const auto pos = MousePixelPos(); detector.OnMouseAction( pos ); } void CDetectorMouseController::OnMouseLeave() { detector.ClearIconHighlight(); } void CDetectorMouseController::OnMouseClick() { const auto pos = MousePixelPos(); const auto target = detector.OnMouseAction( pos ); if( target != nullptr ) { target->OnMouseClick( detector.GetActionController() ); } } void CDetectorMouseController::OnMouseDClick() { const auto pos = MousePixelPos(); const auto target = detector.OnMouseAction( pos ); if( target != nullptr ) { target->OnMouseDClick( detector.GetActionController() ); } } ////////////////////////////////////////////////////////////////////////// } // namespace Fangame.
22.733333
74
0.638319
TheBiob
021d90eda0e13562cdffcd38536f0c49f8fc403f
38,617
hpp
C++
thirdparty/nark/gold_hash_map.hpp
ktprime/emhash
3b059cc5db31f3e3c4102b1b1bc46bbfc3313c37
[ "MIT" ]
92
2019-09-11T05:17:20.000Z
2022-03-31T09:54:06.000Z
thirdparty/nark/gold_hash_map.hpp
ktprime/emhash
3b059cc5db31f3e3c4102b1b1bc46bbfc3313c37
[ "MIT" ]
7
2019-11-23T16:24:03.000Z
2020-09-15T13:07:06.000Z
thirdparty/nark/gold_hash_map.hpp
ktprime/emhash
3b059cc5db31f3e3c4102b1b1bc46bbfc3313c37
[ "MIT" ]
5
2020-06-10T07:20:04.000Z
2022-03-01T08:43:18.000Z
#ifndef __nark_gold_hash_tab__ #define __nark_gold_hash_tab__ #ifdef _MSC_VER #if _MSC_VER < 1600 #include <hash_map> #define DEFAULT_HASH_FUNC stdext::hash #else #include <unordered_map> #define DEFAULT_HASH_FUNC std::hash #endif #elif defined(__GNUC__) && __GNUC__ * 1000 + __GNUC_MINOR__ < 4001 #include <ext/hash_map> #define DEFAULT_HASH_FUNC __gnu_cxx::hash #elif defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103 || defined(_LIBCPP_VERSION) #include <unordered_map> #define DEFAULT_HASH_FUNC std::hash #else #include <tr1/unordered_map> #define DEFAULT_HASH_FUNC std::tr1::hash #endif //#include <nark/parallel_lib.hpp> #include "hash_common.hpp" #include <utility> // for std::identity #if 0 #include <boost/ref.hpp> #include <boost/current_function.hpp> #include <boost/noncopyable.hpp> #include <boost/type_traits/has_trivial_constructor.hpp> #include <boost/type_traits/has_trivial_destructor.hpp> #endif namespace nark { #if 1 template<class T> struct nark_identity { typedef T value_type; const T& operator()(const T& x) const { return x; } }; #else #define nark_identity std::identity #endif template<class Key, class Object, size_t Offset> struct ExtractKeyByOffset { const Key& operator()(const Object& x) const { return *reinterpret_cast<const Key *>( reinterpret_cast<const char*>(&x) + Offset); } BOOST_STATIC_ASSERT(Offset >= 0); BOOST_STATIC_ASSERT(Offset <= sizeof(Object)-sizeof(Key)); }; template< class Key , class Elem = Key , class HashEqual = hash_and_equal<Key, DEFAULT_HASH_FUNC<Key>, std::equal_to<Key> > , class KeyExtractor = nark_identity<Elem> , class NodeLayout = node_layout<Elem, unsigned/*LinkTp*/ > , class HashTp = size_t > class gold_hash_tab : dummy_bucket<typename NodeLayout::link_t> { protected: typedef typename NodeLayout::link_t LinkTp; typedef typename NodeLayout::copy_strategy CopyStrategy; // BOOST_STATIC_ASSERT(sizeof(LinkTp) <= sizeof(Elem)); using dummy_bucket<LinkTp>::tail; using dummy_bucket<LinkTp>::delmark; static const intptr_t hash_cache_disabled = 8; // good if compiler aggressive optimize struct IsNotFree { bool operator()(LinkTp link_val) const { return delmark != link_val; } }; public: typedef typename NodeLayout:: iterator fast_iterator; typedef typename NodeLayout::const_iterator const_fast_iterator; typedef std::reverse_iterator< fast_iterator> fast_reverse_iterator; typedef std::reverse_iterator<const_fast_iterator> const_fast_reverse_iterator; #ifdef NARK_GOLD_HASH_MAP_ITERATOR_USE_FAST typedef fast_iterator iterator; typedef const_fast_iterator const_iterator; iterator get_iter(size_t idx) { return m_nl.begin() + idx; } const_iterator get_iter(size_t idx) const { return m_nl.begin() + idx; } #else class iterator; friend class iterator; class iterator { public: typedef Elem value_type; typedef gold_hash_tab* OwnerPtr; #define ClassIterator iterator #include "gold_hash_map_iterator.hpp" }; class const_iterator; friend class const_iterator; class const_iterator { public: typedef const Elem value_type; const_iterator(const iterator& y) : owner(y.get_owner()), index(y.get_index()) {} typedef const gold_hash_tab* OwnerPtr; #define ClassIterator const_iterator #include "gold_hash_map_iterator.hpp" }; iterator get_iter(size_t idx) { return iterator(this, idx); } const_iterator get_iter(size_t idx) const { return const_iterator(this, idx); } #endif typedef std::reverse_iterator< iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef ptrdiff_t difference_type; typedef size_t size_type; typedef Elem value_type; typedef Elem& reference; typedef const Key key_type; protected: NodeLayout m_nl; LinkTp* bucket; // index to m_nl HashTp* pHash; double load_factor; size_t nBucket; // may larger than LinkTp.max if LinkTp is small than size_t LinkTp nElem; LinkTp maxElem; LinkTp maxload; // cached guard for calling rehash LinkTp freelist_head; LinkTp freelist_size; LinkTp freelist_freq; bool is_sorted; HashEqual he; KeyExtractor keyExtract; private: void init() { new(&m_nl)NodeLayout(); nElem = 0; maxElem = 0; maxload = 0; if (!std::is_trivial_destructor<Elem>::value || sizeof(Elem) > sizeof(intptr_t)) pHash = NULL; else pHash = (HashTp*)(hash_cache_disabled); bucket = const_cast<LinkTp*>(&tail); // false start nBucket = 1; freelist_head = delmark; // don't use freelist freelist_size = 0; freelist_freq = 0; load_factor = 0.8; is_sorted = true; } void relink_impl(bool bFillHash) { LinkTp* pb = bucket; size_t nb = nBucket; NodeLayout nl = m_nl; // (LinkTp)tail is just used for coerce tail be passed by value // otherwise, tail is passed by reference, this cause g++ link error if (nb > 1) { assert(&tail != pb); std::fill_n(pb, nb, (LinkTp)tail); } else { assert(&tail == pb); return; } { // set delmark LinkTp i = freelist_head; while (i < delmark) { nl.link(i) = delmark; i = reinterpret_cast<LinkTp&>(nl.data(i)); } } if (intptr_t(pHash) == hash_cache_disabled) { if (0 == freelist_size) for (size_t j = 0, n = nElem; j < n; ++j) { size_t i = he.hash(keyExtract(nl.data(j))) % nb; nl.link(j) = pb[i]; pb[i] = LinkTp(j); } else for (size_t j = 0, n = nElem; j < n; ++j) { if (delmark != nl.link(j)) { size_t i = he.hash(keyExtract(nl.data(j))) % nb; nl.link(j) = pb[i]; pb[i] = LinkTp(j); } } } else if (bFillHash) { HashTp* ph = pHash; if (0 == freelist_size) for (size_t j = 0, n = nElem; j < n; ++j) { HashTp h = HashTp(he.hash(keyExtract(nl.data(j)))); size_t i = h % nb; ph[j] = h; nl.link(j) = pb[i]; pb[i] = LinkTp(j); } else for (size_t j = 0, n = nElem; j < n; ++j) { if (delmark != nl.link(j)) { HashTp h = HashTp(he.hash(keyExtract(nl.data(j)))); size_t i = h % nb; ph[j] = h; nl.link(j) = pb[i]; pb[i] = LinkTp(j); } } } else { const HashTp* ph = pHash; if (0 == freelist_size) for (size_t j = 0, n = nElem; j < n; ++j) { size_t i = ph[j] % nb; nl.link(j) = pb[i]; pb[i] = LinkTp(j); } else for (size_t j = 0, n = nElem; j < n; ++j) { if (delmark != nl.link(j)) { size_t i = ph[j] % nb; nl.link(j) = pb[i]; pb[i] = LinkTp(j); } } } } void relink() { relink_impl(false); } void relink_fill() { relink_impl(true); } void destroy() { NodeLayout nl = m_nl; if (!nl.is_null()) { if (!std::is_trivial_destructor<Elem>::value) { if (freelist_is_empty()) { for (size_t i = nElem; i > 0; --i) nl.data(i-1).~Elem(); } else { for (size_t i = nElem; i > 0; --i) if (delmark != nl.link(i-1)) nl.data(i-1).~Elem(); } } m_nl.free(); } if (intptr_t(pHash) != hash_cache_disabled && NULL != pHash) free(pHash); if (bucket && &tail != bucket) free(bucket); } public: explicit gold_hash_tab(HashEqual he = HashEqual() , KeyExtractor keyExtr = KeyExtractor()) : he(he), keyExtract(keyExtr) { init(); } explicit gold_hash_tab(size_t cap , HashEqual he = HashEqual() , KeyExtractor keyExtr = KeyExtractor()) : he(he), keyExtract(keyExtr) { init(); rehash(cap); } /// ensured not calling HashEqual and KeyExtractor gold_hash_tab(const gold_hash_tab& y) : he(y.he), keyExtract(y.keyExtract) { nElem = y.nElem; maxElem = y.nElem; maxload = y.maxload; nBucket = y.nBucket; pHash = NULL; freelist_head = y.freelist_head; freelist_size = y.freelist_size; freelist_freq = y.freelist_freq; load_factor = y.load_factor; is_sorted = y.is_sorted; if (0 == nElem) { // empty nBucket = 1; maxload = 0; bucket = const_cast<LinkTp*>(&tail); return; // not need to do deep copy } assert(y.bucket != &tail); m_nl.reserve(0, nElem); bucket = (LinkTp*)malloc(sizeof(LinkTp) * y.nBucket); if (NULL == bucket) { m_nl.free(); init(); throw std::bad_alloc(); } if (intptr_t(y.pHash) == hash_cache_disabled) { pHash = (HashTp*)(hash_cache_disabled); } else { pHash = (HashTp*)malloc(sizeof(HashTp) * nElem); if (NULL == pHash) { free(bucket); m_nl.free(); throw std::bad_alloc(); } memcpy(pHash, y.pHash, sizeof(HashTp) * nElem); } memcpy(bucket, y.bucket, sizeof(LinkTp) * nBucket); if (!std::is_trivial_copy<Elem>::value && freelist_size) { node_layout_copy_cons(m_nl, y.m_nl, nElem, IsNotFree()); } else // freelist is empty, copy all node_layout_copy_cons(m_nl, y.m_nl, nElem); } gold_hash_tab& operator=(const gold_hash_tab& y) { if (this != &y) { #if 1 // prefer performance, std::map is in this manner // this is exception-safe but not transactional // non-transactional: lose old content of *this on exception this->destroy(); new(this)gold_hash_tab(y); #else // exception-safe, but take more peak memory gold_hash_tab(y).swap(*this); #endif } return *this; } ~gold_hash_tab() { destroy(); } void swap(gold_hash_tab& y) { std::swap(pHash , y.pHash); std::swap(m_nl , y.m_nl); std::swap(nElem , y.nElem); std::swap(maxElem, y.maxElem); std::swap(maxload, y.maxload); std::swap(nBucket, y.nBucket); std::swap(bucket , y.bucket); std::swap(freelist_head, y.freelist_head); std::swap(freelist_size, y.freelist_size); std::swap(freelist_freq, y.freelist_freq); std::swap(load_factor, y.load_factor); std::swap(is_sorted , y.is_sorted); std::swap(he , y.he); std::swap(keyExtract , y.keyExtract); } // void setHashEqual(const HashEqual& he) { this->he = he; } // void setKeyExtractor(const KeyExtractor& kEx) { this->keyExtract = kEx; } const HashEqual& getHashEqual() const { return this->he; } const KeyExtractor& getKeyExtractor() const { return this->keyExtract; } void clear() { destroy(); init(); } void shrink_to_fit() { if (nElem < maxElem) reserve(nElem); } bool is_hash_cached() const { return intptr_t(pHash) != hash_cache_disabled; } void enable_hash_cache() { if (intptr_t(pHash) == hash_cache_disabled) { if (0 == maxElem) { pHash = NULL; } else { HashTp* ph = (HashTp*)malloc(sizeof(HashTp) * maxElem); if (NULL == ph) { throw std::bad_alloc(); } if (0 == freelist_size) { for (size_t i = 0, n = nElem; i < n; ++i) ph[i] = he.hash(keyExtract(m_nl.data(i))); } else { for (size_t i = 0, n = nElem; i < n; ++i) if (delmark != m_nl.link(i)) ph[i] = he.hash(keyExtract(m_nl.data(i))); } pHash = ph; } } assert(NULL != pHash || 0 == maxElem); } void disable_hash_cache() { if (intptr_t(pHash) == hash_cache_disabled) return; if (pHash) free(pHash); pHash = (HashTp*)(hash_cache_disabled); } void rehash(size_t newBucketSize) { newBucketSize = __hsm_stl_next_prime(newBucketSize); if (newBucketSize != nBucket) { // shrink or enlarge if (bucket != &tail) { assert(NULL != bucket); free(bucket); } bucket = (LinkTp*)malloc(sizeof(LinkTp) * newBucketSize); if (NULL == bucket) { // how to handle? assert(0); // immediately fail on debug mode destroy(); throw std::runtime_error("rehash failed, unrecoverable"); } nBucket = newBucketSize; relink(); maxload = LinkTp(newBucketSize * load_factor); } } // void resize(size_t n) { rehash(n); } void reserve(size_t cap) { reserve_nodes(cap); rehash(size_t(cap / load_factor + 1)); } void reserve_nodes(size_t cap) { // assert(cap >= maxElem); // could be shrink assert(cap >= nElem); assert(cap <= delmark); if (cap != (size_t)maxElem && cap != nElem) { if (intptr_t(pHash) != hash_cache_disabled) { HashTp* ph = (HashTp*)realloc(pHash, sizeof(HashTp) * cap); if (NULL == ph) throw std::bad_alloc(); pHash = ph; } if (freelist_size) m_nl.reserve(nElem, cap, IsNotFree()); else m_nl.reserve(nElem, cap); maxElem = LinkTp(cap); } } void set_load_factor(double fact) { if (fact >= 0.999) { throw std::logic_error("load factor must <= 0.999"); } load_factor = fact; maxload = &tail == bucket ? 0 : LinkTp(nBucket * fact); } double get_load_factor() const { return load_factor; } inline HashTp hash_i(size_t i) const { assert(i < nElem); if (intptr_t(pHash) == hash_cache_disabled) return HashTp(he.hash(keyExtract(m_nl.data(i)))); else return pHash[i]; } inline HashTp hash_v(const Elem& e) const { return HashTp(he.hash(keyExtract(e))); } bool empty() const { return nElem == freelist_size; } size_t size() const { return nElem - freelist_size; } size_t beg_i() const { size_t i; if (freelist_size == nElem) i = nElem; else if (freelist_size && delmark == m_nl.link(0)) i = next_i(0); else i = 0; return i; } size_t end_i() const { return nElem; } size_t rbeg_i() const { return freelist_size == nElem ? 0 : nElem; } size_t rend_i() const { return 0; } size_t next_i(size_t idx) const { size_t n = nElem; assert(idx < n); do ++idx; while (idx < n && delmark == m_nl.link(idx)); return idx; } size_t prev_i(size_t idx) const { assert(idx > 0); assert(idx <= nElem); do --idx; while (idx > 0 && delmark == m_nl.link(idx)); return idx; } size_t capacity() const { return maxElem; } size_t delcnt() const { return freelist_size; } iterator begin() { return get_iter(beg_i()); } const_iterator begin() const { return get_iter(beg_i()); } const_iterator cbegin() const { return get_iter(beg_i()); } iterator end() { return get_iter(nElem); } const_iterator end() const { return get_iter(nElem); } const_iterator cend() const { return get_iter(nElem); } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } const_reverse_iterator crend() const { return const_reverse_iterator(begin()); } fast_iterator fast_begin() { return m_nl.begin(); } const_fast_iterator fast_begin() const { return m_nl.begin(); } const_fast_iterator fast_cbegin() const { return m_nl.begin(); } fast_iterator fast_end() { return m_nl.begin() + nElem; } const_fast_iterator fast_end() const { return m_nl.begin() + nElem; } const_fast_iterator fast_cend() const { return m_nl.begin() + nElem; } fast_reverse_iterator fast_rbegin() { return fast_reverse_iterator(fast_end()); } const_fast_reverse_iterator fast_rbegin() const { return const_fast_reverse_iterator(fast_end()); } const_fast_reverse_iterator fast_crbegin() const { return const_fast_reverse_iterator(fast_end()); } fast_reverse_iterator fast_rend() { return fast_reverse_iterator(fast_begin()); } const_fast_reverse_iterator fast_rend() const { return const_fast_reverse_iterator(fast_begin()); } const_fast_reverse_iterator fast_crend() const { return const_fast_reverse_iterator(fast_begin()); } template<class CompatibleObject> std::pair<iterator, bool> insert(const CompatibleObject& obj) { std::pair<size_t, bool> ib = insert_i(obj); return std::pair<iterator, bool>(get_iter(ib.first), ib.second); } template<class Arg1> std::pair<iterator, bool> emplace(const Arg1& a1) { std::pair<size_t, bool> ib = insert_i(value_type(a1)); return std::pair<iterator, bool>(get_iter(ib.first), ib.second); } template<class Arg1, class Arg2> std::pair<iterator, bool> emplace(const Arg1& a1, const Arg2& a2) { std::pair<size_t, bool> ib = insert_i(value_type(a1, a2)); return std::pair<iterator, bool>(get_iter(ib.first), ib.second); } #if defined(HSM_HAS_MOVE) template<class... _Valty> std::pair<iterator, bool> emplace(_Valty&&... _Val) { std::pair<size_t, bool> ib = insert_i(value_type(std::forward<_Valty>(_Val)...)); return std::pair<iterator, bool>(get_iter(ib.first), ib.second); } #endif iterator find(const Key& key) { return get_iter(find_i(key)); } const_iterator find(const Key& key) const { return get_iter(find_i(key)); } // keep memory void erase_all() { NodeLayout nl = m_nl; if (!nl.is_null()) { if (!std::is_trivial_destructor<Elem>::value) { if (freelist_is_empty()) { for (size_t i = nElem; i > 0; --i) nl.data(i-1).~Elem(); } else { for (size_t i = nElem; i > 0; --i) if (delmark != nl.link(i-1)) nl.data(i-1).~Elem(); } } } if (freelist_head < delmark) { assert(freelist_head < nElem); freelist_head = tail; freelist_size = 0; freelist_freq = 0; } if (nElem) { std::fill_n(bucket, nBucket, (LinkTp)tail); nElem = 0; } } #ifndef NARK_GOLD_HASH_MAP_ITERATOR_USE_FAST void erase(iterator iter) { assert(iter.get_owner() == this); assert(!m_nl.is_null()); assert(iter.get_index() < nElem); erase_i(iter.get_index()); } #endif void erase(fast_iterator iter) { assert(!m_nl.is_null()); assert(iter >= m_nl.begin()); assert(iter < m_nl.begin() + nElem); erase_i(iter - m_nl.begin()); } private: // return erased elements count template<class Predictor> size_t erase_if_impl(Predictor pred, FastCopy) { if (freelist_size) // this extra scan should be eliminated, by some way revoke_deleted_no_relink(); NodeLayout nl = m_nl; size_t i = 0, n = nElem; for (; i < n; ++i) if (pred(nl.data(i))) goto DoErase; return 0; DoErase: HashTp* ph = pHash; nl.data(i).~Elem(); if (intptr_t(ph) == hash_cache_disabled) { for (size_t j = i + 1; j != n; ++j) if (pred(nl.data(j))) nl.data(j).~Elem(); else memcpy(&nl.data(i), &nl.data(j), sizeof(Elem)), ++i; } else { for (size_t j = i + 1; j != n; ++j) if (pred(nl.data(j))) nl.data(j).~Elem(); else { ph[i] = ph[j]; memcpy(&nl.data(i), &nl.data(j), sizeof(Elem)), ++i; } } nElem = i; if (0 == i) { // all elements are erased this->destroy(); this->init(); } return n - i; // erased elements count } template<class Predictor> size_t erase_if_impl(Predictor pred, SafeCopy) { if (freelist_size) // this extra scan should be eliminated, by some way revoke_deleted_no_relink(); NodeLayout nl = m_nl; size_t i = 0, n = nElem; for (; i < n; ++i) if (pred(nl.data(i))) goto DoErase; return 0; DoErase: HashTp* ph = pHash; if (intptr_t(ph) == hash_cache_disabled) { for (size_t j = i + 1; j != n; ++j) if (!pred(nl.data(j))) std::swap(nl.data(i), nl.data(j)), ++i; } else { for (size_t j = i + 1; j != n; ++j) if (!pred(nl.data(j))) { ph[i] = ph[j]; std::swap(nl.data(i), nl.data(j)), ++i; } } if (!std::is_trivial_destructor<Elem>::value) { for (size_t j = i; j != n; ++j) nl.data(j).~Elem(); } nElem = i; if (0 == i) { // all elements are erased this->destroy(); this->init(); } return n - i; // erased elements count } public: //@{ //@brief erase_if /// will invalidate saved id/index/iterator /// can be called even if freelist_is_using template<class Predictor> size_t erase_if(Predictor pred) { if (freelist_is_using()) return keepid_erase_if(pred); else { size_t nErased = erase_if_impl(pred, CopyStrategy()); if (nElem * 2 <= maxElem) shrink_to_fit(); else relink(); return nErased; } } template<class Predictor> size_t shrink_after_erase_if(Predictor pred) { size_t nErased = erase_if_impl(pred, CopyStrategy()); shrink_to_fit(); return nErased; } template<class Predictor> size_t no_shrink_after_erase_if(Predictor pred) { size_t nErased = erase_if_impl(pred, CopyStrategy()); relink(); return nErased; } //@} template<class Predictor> size_t keepid_erase_if(Predictor pred) { // should be much slower than erase_if assert(freelist_is_using()); size_t n = nElem; size_t erased = 0; NodeLayout nl = m_nl; if (freelist_is_empty()) { assert(0 == freelist_size); for (size_t i = 0; i != n; ++i) if (pred(nl.data(i))) erase_to_freelist(i), ++erased; } else { assert(0 != freelist_size); for (size_t i = 0; i != n; ++i) if (delmark != nl.link(i) && pred(nl.data(i))) erase_to_freelist(i), ++erased; } return erased; } // if return non-zero, all permanent id/index are invalidated size_t revoke_deleted() { assert(freelist_is_using()); // must be using/enabled if (freelist_size) { size_t erased = revoke_deleted_no_relink(); relink(); return erased; } else return 0; } bool is_deleted(size_t idx) const { assert(idx < nElem); assert(freelist_is_using()); return delmark == m_nl.link(idx); } //@{ /// default is disabled void enable_freelist() { if (delmark == freelist_head) { assert(0 == freelist_size); freelist_head = tail; } } /// @note this function may take O(n) time void disable_freelist() { if (delmark != freelist_head) { revoke_deleted(); freelist_head = delmark; } } bool freelist_is_empty() const { return freelist_head >= delmark; } bool freelist_is_using() const { return freelist_head != delmark; } //@} template<class CompatibleObject> std::pair<size_t, bool> insert_i(const CompatibleObject& obj) { const Key& key = keyExtract(obj); const HashTp h = HashTp(he.hash(key)); size_t i = h % nBucket; for (LinkTp p = bucket[i]; tail != p; p = m_nl.link(p)) { HSM_SANITY(p < nElem); if (he.equal(key, keyExtract(m_nl.data(p)))) return std::make_pair(p, false); } if (nark_unlikely(nElem - freelist_size >= maxload)) { rehash(nBucket + 1); // will auto find next prime bucket size i = h % nBucket; } size_t slot = risk_slot_alloc(); // here, no risk new(&m_nl.data(slot))Elem(obj); m_nl.link(slot) = bucket[i]; // newer at head bucket[i] = LinkTp(slot); // new head of i'th bucket if (intptr_t(pHash) != hash_cache_disabled) pHash[slot] = h; is_sorted = false; return std::make_pair(slot, true); } ///@{ low level operations /// the caller should pay the risk for gain /// LinkTp risk_slot_alloc() { LinkTp slot; if (freelist_is_empty()) { assert(0 == freelist_size); slot = nElem; if (nark_unlikely(nElem == maxElem)) reserve_nodes(0 == nElem ? 1 : 2*nElem); assert(nElem < maxElem); nElem++; } else { assert(freelist_head < nElem); assert(freelist_size > 0); slot = freelist_head; assert(delmark == m_nl.link(slot)); freelist_size--; freelist_head = reinterpret_cast<LinkTp&>(m_nl.data(slot)); } m_nl.link(slot) = tail; // for debug check&verify return slot; } /// precond: # Elem on slot is constructed /// # Elem on slot is not in the table: /// it is not reached through 'bucket' /// effect: destory the Elem on slot then free the slot void risk_slot_free(size_t slot) { assert(slot < nElem); assert(delmark != m_nl.link(slot)); if (nark_unlikely(nElem-1 == slot)) { m_nl.data(slot).~Elem(); --nElem; } else if (freelist_is_using()) { fast_slot_free(slot); is_sorted = false; } else { assert(!"When freelist is disabled, nElem-1==slot must be true"); throw std::logic_error(BOOST_CURRENT_FUNCTION); } } /// @note when calling this function: // 1. this->begin()[slot] must has been newly constructed by the caller // 2. this->begin()[slot] must not existed in the hash index size_t risk_insert_on_slot(size_t slot) { assert(slot < nElem); assert(delmark != m_nl.link(slot)); const Key& key = keyExtract(m_nl.data(slot)); const HashTp h = HashTp(he.hash(key)); size_t i = h % nBucket; for (LinkTp p = bucket[i]; tail != p; p = m_nl.link(p)) { assert(p != slot); // slot must not be reached HSM_SANITY(p < nElem); if (he.equal(key, keyExtract(m_nl.data(p)))) return p; } if (intptr_t(pHash) != hash_cache_disabled) pHash[slot] = h; if (nark_unlikely(nElem - freelist_size >= maxload)) { // must be >= // rehash will set the bucket&link for 'slot' rehash(nBucket + 1); // will auto find next prime bucket size } else { m_nl.link(slot) = bucket[i]; // newer at head bucket[i] = LinkTp(slot); // new head of i'th bucket } is_sorted = false; return slot; } void risk_size_inc(LinkTp n) { if (nark_unlikely(nElem + n > maxElem)) reserve_nodes(nElem + std::max(nElem, n)); assert(nElem + n <= maxElem); NodeLayout nl = m_nl; for (size_t i = n, j = nElem; i; --i, ++j) nl.link(j) = (LinkTp)tail; nElem += n; } void risk_size_dec(LinkTp n) { assert(nElem >= n); nElem -= n; } // BOOST_CONSTANT(size_t, risk_data_stride = NodeLayout::data_stride); //@} size_t find_i(const Key& key) const { const HashTp h = HashTp(he.hash(key)); const size_t i = h % nBucket; for (LinkTp p = bucket[i]; tail != p; p = m_nl.link(p)) { HSM_SANITY(p < nElem); if (he.equal(key, keyExtract(m_nl.data(p)))) return p; } return nElem; // not found } template<class CompatibleKey> size_t find_i(const CompatibleKey& key) const { const HashTp h = HashTp(he.hash(key)); const size_t i = h % nBucket; for (LinkTp p = bucket[i]; tail != p; p = m_nl.link(p)) { HSM_SANITY(p < nElem); if (he.equal(key, keyExtract(m_nl.data(p)))) return p; } return nElem; // not found } // return erased element count size_t erase(const Key& key) { const HashTp h = HashTp(he.hash(key)); const HashTp i = h % nBucket; for (LinkTp p = bucket[i]; tail != p; p = m_nl.link(p)) { HSM_SANITY(p < nElem); if (he.equal(key, keyExtract(m_nl.data(p)))) { erase_i_impl(p, i); return 1; } } return 0; } size_t count(const Key& key) const { return find_i(key) == nElem ? 0 : 1; } // return value is same with count(key), but type is different // this function is not stl standard, but more meaningful for app bool exists(const Key& key) const { return find_i(key) != nElem; } private: // if return non-zero, all permanent id/index are invalidated size_t revoke_deleted_no_relink() { assert(freelist_is_using()); // must be using/enabled assert(freelist_size > 0); NodeLayout nl = m_nl; size_t i = 0, n = nElem; for (; i < n; ++i) if (delmark == nl.link(i)) goto DoErase; assert(0); // would not go here DoErase: HashTp* ph = pHash; if (intptr_t(ph) == hash_cache_disabled) { for (size_t j = i + 1; j < n; ++j) if (delmark != nl.link(j)) CopyStrategy::move_cons(&nl.data(i), nl.data(j)), ++i; } else { for (size_t j = i + 1; j < n; ++j) if (delmark != nl.link(j)) { ph[i] = ph[j]; // copy cached hash value CopyStrategy::move_cons(&nl.data(i), nl.data(j)), ++i; } } nElem = i; freelist_head = tail; freelist_size = 0; return n - i; // erased elements count } // use erased elem as free list link HSM_FORCE_INLINE void fast_slot_free(size_t slot) { m_nl.link(slot) = delmark; m_nl.data(slot).~Elem(); reinterpret_cast<LinkTp&>(m_nl.data(slot)) = freelist_head; freelist_size++; freelist_freq++; // never decrease freelist_head = slot; } HSM_FORCE_INLINE void erase_to_freelist(const size_t slot) { HashTp const h = hash_i(slot); size_t const i = h % nBucket; HSM_SANITY(tail != bucket[i]); LinkTp* curp = &bucket[i]; LinkTp curr; // delete from collision list ... while (slot != (curr = *curp)) { curp = &m_nl.link(curr); HSM_SANITY(*curp < nElem); } *curp = m_nl.link(slot); // delete the idx'th node from collision list fast_slot_free(slot); } // bucket_idx == hash % nBucket void erase_i_impl(const size_t idx, const HashTp bucket_idx) { size_t n = nElem; HashTp*ph = pHash; HSM_SANITY(n >= 1); #if defined(_DEBUG) || !defined(NDEBUG) assert(idx < n); #else if (idx >= n) { throw std::invalid_argument(BOOST_CURRENT_FUNCTION); } #endif HSM_SANITY(tail != bucket[bucket_idx]); LinkTp* curp = &bucket[bucket_idx]; LinkTp curr; while (idx != (curr = *curp)) { curp = &m_nl.link(curr); HSM_SANITY(*curp < n); } *curp = m_nl.link(idx); // delete the idx'th node from collision list if (nark_unlikely(n-1 == idx)) { m_nl.data(idx).~Elem(); --nElem; } else if (freelist_is_using()) { assert(!is_deleted(idx)); fast_slot_free(idx); is_sorted = false; } else { // Move last Elem to slot idx // // delete last Elem from it's collision list const HashTp lastHash = hash_i(n-1); const size_t j = lastHash % nBucket; HSM_SANITY(tail != bucket[j]); curp = &bucket[j]; while (n-1 != (curr = *curp)) { curp = &m_nl.link(curr); HSM_SANITY(*curp < n); } *curp = m_nl.link(n-1); // delete the last node from link list // put last Elem to the slot idx and sync the link CopyStrategy::move_assign(&m_nl.data(idx), m_nl.data(n-1)); m_nl.link(idx) = bucket[j]; if (intptr_t(ph) != hash_cache_disabled) ph[idx] = lastHash; bucket[j] = LinkTp(idx); is_sorted = false; --nElem; } } public: void erase_i(const size_t idx) { assert(nElem >= 1); assert(idx < nElem); assert(delmark != m_nl.link(idx)); erase_i_impl(idx, hash_i(idx) % nBucket); } const Key& key(size_t idx) const { assert(nElem >= 1); assert(idx < nElem); assert(delmark != m_nl.link(idx)); return keyExtract(m_nl.data(idx)); } const Key& end_key(size_t idxEnd) const { assert(nElem >= 1); assert(idxEnd >= 1); assert(idxEnd <= nElem); assert(delmark != m_nl.link(nElem - idxEnd)); return keyExtract(m_nl.data(nElem - idxEnd)); } const Elem& elem_at(size_t idx) const { assert(nElem >= 1); assert(idx < nElem); assert(delmark != m_nl.link(idx)); return m_nl.data(idx); } Elem& elem_at(size_t idx) { assert(nElem >= 1); assert(idx < nElem); assert(delmark != m_nl.link(idx)); return m_nl.data(idx); } const Elem& end_elem(size_t idxEnd) const { assert(nElem >= 1); assert(idxEnd >= 1); assert(idxEnd <= nElem); assert(delmark != m_nl.link(nElem - idxEnd)); return m_nl.data(nElem - idxEnd); } Elem& end_elem(size_t idxEnd) { assert(nElem >= 1); assert(idxEnd >= 1); assert(idxEnd <= nElem); assert(delmark != m_nl.link(nElem - idxEnd)); return m_nl.data(nElem - idxEnd); } template<class OP> void for_each(OP op) { size_t n = nElem; NodeLayout nl = m_nl; if (freelist_size) { assert(freelist_is_using()); for (size_t i = 0; i != n; ++i) if (delmark != nl.link(i)) op(nl.data(i)); } else { for (size_t i = 0; i != n; ++i) op(nl.data(i)); } } template<class OP> void for_each(OP op) const { const size_t n = nElem; const NodeLayout nl = m_nl; if (freelist_size) { assert(freelist_is_using()); for (size_t i = 0; i != n; ++i) if (delmark != nl.link(i)) op(nl.data(i)); } else { for (size_t i = 0; i != n; ++i) op(nl.data(i)); } } template<class Compare> void sort(Compare comp) { if (freelist_size) revoke_deleted_no_relink(); fast_iterator beg_iter = m_nl.begin(); fast_iterator end_iter = beg_iter + nElem; nark_parallel_sort(beg_iter, end_iter, Compare(comp)); relink_fill(); is_sorted = true; } void sort() { sort(std::less<Elem>()); } size_t bucket_size() const { return nBucket; } template<class IntVec> void bucket_histogram(IntVec& hist) const { for (size_t i = 0, n = nBucket; i < n; ++i) { size_t listlen = 0; for (LinkTp j = bucket[i]; j != tail; j = m_nl.link(j)) ++listlen; if (hist.size() <= listlen) hist.resize(listlen+1); hist[listlen]++; } } protected: // DataIO support template<class DataIO> void dio_load_fast(DataIO& dio) { unsigned char cacheHash; clear(); typename DataIO::my_var_uint64_t size; dio >> size; dio >> load_factor; dio >> cacheHash; pHash = cacheHash ? NULL : (size_t*)(hash_cache_disabled); if (0 == size.t) return; if (NULL == pHash) { pHash = (HashTp*)malloc(sizeof(HashTp)*size.t); if (NULL == pHash) throw std::bad_alloc(); } m_nl.reserve(0, size.t); size_t i = 0, n = size.t; try { NodeLayout nl = m_nl; for (; i < n; ++i) { new(&nl.data(i))Elem(); dio >> nl.data(i); } if ((size_t*)(hash_cache_disabled) != pHash) { assert(NULL != pHash); for (size_t j = 0; j < n; ++j) pHash[j] = he.hash(keyExtract(nl.data(i))); } nElem = LinkTp(size.t); maxElem = nElem; maxload = nElem; //LinkTp(load_factor * nBucket); rehash(maxElem / load_factor); } catch (...) { nElem = i; // valid elem count clear(); throw; } } template<class DataIO> void dio_save_fast(DataIO& dio) const { dio << typename DataIO::my_var_uint64_t(nElem); dio << load_factor; dio << (unsigned char)(intptr_t(pHash) != hash_cache_disabled); const NodeLayout nl = m_nl; for (size_t i = 0, n = nElem; i < n; ++i) dio << nl.data(i); } // compatible format template<class DataIO> void dio_load(DataIO& dio) { typename DataIO::my_var_uint64_t Size; dio >> Size; this->clear(); this->reserve(Size.t); Elem e; for (size_t i = 0, n = Size.t; i < n; ++i) { this->insert_i(e); } } template<class DataIO> void dio_save(DataIO& dio) const { dio << typename DataIO::my_var_uint64_t(this->size()); if (this->freelist_size) { for (size_t i = 0, n = this->end_i(); i < n; ++i) if (this->is_deleted()) dio << m_nl.data(i); } else { for (size_t i = 0, n = this->end_i(); i < n; ++i) dio << m_nl.data(i); } } template<class DataIO> friend void DataIO_loadObject(DataIO& dio, gold_hash_tab& x) { x.dio_load(dio); } template<class DataIO> friend void DataIO_saveObject(DataIO& dio, const gold_hash_tab& x) { x.dio_save(dio); } }; template<class First> struct nark_get_first { template<class T> const First& operator()(const T& x) const { return x.first; } }; template< class Key , class Value , class HashFunc = DEFAULT_HASH_FUNC<Key> , class KeyEqual = std::equal_to<Key> , class NodeLayout = node_layout<std::pair<Key, Value>, unsigned> , class HashTp = size_t > class gold_hash_map : public gold_hash_tab<Key, std::pair<Key, Value> , hash_and_equal<Key, HashFunc, KeyEqual>, nark_get_first<Key> , NodeLayout , HashTp > { typedef gold_hash_tab<Key, std::pair<Key, Value> , hash_and_equal<Key, HashFunc, KeyEqual>, nark_get_first<Key> , NodeLayout , HashTp > super; public: // typedef std::pair<const Key, Value> value_type; typedef Value mapped_type; using super::insert; using super::insert_i; std::pair<size_t, bool> insert_i(const Key& key, const Value& val = Value()) { return this->insert_i(std::make_pair(key, val)); } Value& operator[](const Key& key) { // typedef boost::reference_wrapper<const Key> key_cref; typedef std::pair<key_cref , Value> key_by_ref; typedef std::pair<const Key, Value> key_by_val; std::pair<size_t, bool> ib = this->insert_i(key_by_val( key , Value())); return this->m_nl.data(ib.first).second; } Value& val(size_t idx) { assert(idx < this->nElem); assert(this->delmark != this->m_nl.link(idx)); return this->m_nl.data(idx).second; } const Value& val(size_t idx) const { assert(idx < this->nElem); assert(this->delmark != this->m_nl.link(idx)); return this->m_nl.data(idx).second; } const Value& end_val(size_t idxEnd) const { assert(this->nElem >= 1); assert(idxEnd >= 1); assert(idxEnd <= this->nElem); assert(this->delmark != this->m_nl.link(this->nElem - idxEnd)); return this->m_nl.data(this->nElem - idxEnd).second; } Value& end_val(size_t idxEnd) { assert(this->nElem >= 1); assert(idxEnd >= 1); assert(idxEnd <= this->nElem); assert(this->delmark != this->m_nl.link(this->nElem - idxEnd)); return this->m_nl.data(this->nElem - idxEnd).second; } // DataIO support template<class DataIO> friend void DataIO_loadObject(DataIO& dio, gold_hash_map& x) { x.dio_load(dio); } template<class DataIO> friend void DataIO_saveObject(DataIO& dio, const gold_hash_map& x) { x.dio_save(dio); } }; template< class Key , class Value , class HashFunc = DEFAULT_HASH_FUNC<Key> , class KeyEqual = std::equal_to<Key> , class Deleter = HSM_DefaultDeleter > class gold_hash_map_p : public nark_ptr_hash_map < gold_hash_map<Key, Value*, HashFunc, KeyEqual>, Value*, Deleter> {}; /////////////////////////////////////////////////////////////////////////////// template< class Key , class HashFunc = DEFAULT_HASH_FUNC<Key> , class KeyEqual = std::equal_to<Key> , class NodeLayout = node_layout<Key, unsigned> , class HashTp = size_t > class gold_hash_set : public gold_hash_tab<Key, Key , hash_and_equal<Key, HashFunc, KeyEqual>, nark_identity<Key> , NodeLayout, HashTp > { public: // DataIO support template<class DataIO> friend void DataIO_loadObject(DataIO& dio, gold_hash_set& x) { x.dio_load(dio); } template<class DataIO> friend void DataIO_saveObject(DataIO& dio, const gold_hash_set& x) { x.dio_save(dio); } }; } // namespace nark namespace std { // for std::swap template< class Key , class Elem , class HashEqual , class KeyExtractor , class NodeLayout , class HashTp > void swap(nark::gold_hash_tab<Key, Elem, HashEqual, KeyExtractor, NodeLayout, HashTp>& x, nark::gold_hash_tab<Key, Elem, HashEqual, KeyExtractor, NodeLayout, HashTp>& y) { x.swap(y); } template< class Key , class Value , class HashFunc , class KeyEqual , class NodeLayout , class HashTp > void swap(nark::gold_hash_map<Key, Value, HashFunc, KeyEqual, NodeLayout, HashTp>& x, nark::gold_hash_map<Key, Value, HashFunc, KeyEqual, NodeLayout, HashTp>& y) { x.swap(y); } template< class Key , class HashFunc , class KeyEqual , class NodeLayout , class HashTp > void swap(nark::gold_hash_set<Key, HashFunc, KeyEqual, NodeLayout, HashTp>& x, nark::gold_hash_set<Key, HashFunc, KeyEqual, NodeLayout, HashTp>& y) { x.swap(y); } } // namespace std #endif // __nark_gold_hash_tab__
27.842105
101
0.640081
ktprime
021f205bbd10b7ed975697de2501f90ec14fee0f
7,038
hpp
C++
src/Luddite/Graphics/ShaderAttributeList.hpp
Aquaticholic/Luddite-Engine
66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f
[ "Apache-2.0" ]
1
2021-06-03T05:46:46.000Z
2021-06-03T05:46:46.000Z
src/Luddite/Graphics/ShaderAttributeList.hpp
Aquaticholic/Luddite-Engine
66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f
[ "Apache-2.0" ]
null
null
null
src/Luddite/Graphics/ShaderAttributeList.hpp
Aquaticholic/Luddite-Engine
66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Luddite/Core/pch.hpp" #include "Luddite/Core/Core.hpp" #include "Luddite/Core/AssetTypes/Texture.hpp" #include "Luddite/Graphics/Color.hpp" #include "Luddite/Graphics/DiligentInclude.hpp" // #include "Luddite/Core/pch.hpp" // #include "Luddite/Platform/DiligentPlatform.hpp" // #include "Graphics/GraphicsEngine/interface/RenderDevice.h" // #include "Graphics/GraphicsEngine/interface/DeviceContext.h" // #include "Graphics/GraphicsEngine/interface/SwapChain.h" // #include "Common/interface/RefCntAutoPtr.hpp" // // #include "Luddite/Core/Core.hpp" namespace Luddite { struct LUDDITE_API ShaderBufferData { std::string Name{}; std::vector<Handle<Texture> > TexturesVertexShader; std::vector<Handle<Texture> > TexturesPixelShader; // std::unordered_map<std::string, Texture::Handle> texture_map; // Handle<Texture> GetTexture(const std::string& id) {return texture_map[id];} // void SetTexture(const std::string& id, const Texture::Handle handle) {texture_map[id] = handle;} char* Data = nullptr; std::size_t Size = 0; ~ShaderBufferData() { if (Data) free(Data); } ShaderBufferData& operator=(const ShaderBufferData& other) { if (this == &other) return *this; if (Size != other.Size) { if (Data) free(Data); Size = other.Size; Data = (char*)malloc(Size); } memcpy(Data, other.Data, Size); Name = other.Name; TexturesVertexShader = other.TexturesVertexShader; TexturesPixelShader = other.TexturesPixelShader; return *this; } }; //enum, name, typename, size #define VALUE_TYPES_DECLARE \ VALUE_TYPE_DECLARATION(Float, float, 0.f) \ VALUE_TYPE_DECLARATION(Int, int32_t, 0) \ VALUE_TYPE_DECLARATION(UInt, uint32_t, 0) \ VALUE_TYPE_DECLARATION(Vec2, glm::vec2, glm::vec2{0}) \ VALUE_TYPE_DECLARATION(IVec2, glm::ivec2, glm::ivec2{0}) \ VALUE_TYPE_DECLARATION(UVec2, glm::uvec2, glm::uvec2{0}) \ VALUE_TYPE_DECLARATION(Vec3, glm::vec3, glm::vec3{0}) \ VALUE_TYPE_DECLARATION(IVec3, glm::ivec3, glm::ivec3{0}) \ VALUE_TYPE_DECLARATION(UVec3, glm::uvec3, glm::uvec3{0}) \ VALUE_TYPE_DECLARATION(Vec4, glm::vec4, glm::vec4{0}) \ VALUE_TYPE_DECLARATION(Color, glm::vec4, glm::vec4{1}) \ VALUE_TYPE_DECLARATION(IVec4, glm::ivec4, glm::ivec4{0}) \ VALUE_TYPE_DECLARATION(UVec4, glm::uvec4, glm::uvec4{0}) \ VALUE_TYPE_DECLARATION(Mat3, glm::mat3, glm::identity<glm::mat3>()) \ VALUE_TYPE_DECLARATION(Mat4, glm::mat4, glm::identity<glm::mat3>()) struct LUDDITE_API ShaderBufferDescription { static const char* ValueTypeNames[]; enum class ValueType : uint32_t { #define VALUE_TYPE_DECLARATION(Name, Type, Default) Name, VALUE_TYPES_DECLARE #undef VALUE_TYPE_DECLARATION SIZE, NONE }; static constexpr uint32_t ValueTypeSizes[] = { #define VALUE_TYPE_DECLARATION(Name, Type, Default) sizeof(Type), VALUE_TYPES_DECLARE #undef VALUE_TYPE_DECLARATION 0, 0 }; struct BufferValue { ValueType type; std::size_t offset; }; std::map<std::string, BufferValue> Attributes; std::vector<std::string> TexturesVertexShader; std::vector<std::string> TexturesPixelShader; inline void AddTextureVertexShader(const std::string& name) {TexturesVertexShader.emplace_back(name);} inline void AddTexturePixelShader(const std::string& name) {TexturesPixelShader.emplace_back(name);} void SetTextureVertexShader(ShaderBufferData& data, const std::string& name, Handle<Texture> texture); void SetTexturePixelShader(ShaderBufferData& data, const std::string& name, Handle<Texture> texture); Handle<Texture> GetTextureVertexShader(ShaderBufferData& data, const std::string& name) const; Handle<Texture> GetTexturePixelShader(ShaderBufferData& data, const std::string& name) const; #define VALUE_TYPE_DECLARATION(Name, Type, Default) inline void Add ## Name(const std::string& name) \ { \ /*Perform byte alignment*/ \ constexpr int align = 16; \ if (m_Size / align != ((m_Size + sizeof(Type) - 1) / align) && m_Size % align != 0) \ {m_Size = ((m_Size / align) + 1) * align;} \ Attributes.insert({name, {ValueType::Name, m_Size}}); \ m_Size += sizeof(Type); \ } VALUE_TYPES_DECLARE #undef VALUE_TYPE_DECLARATION inline void Add(const std::string& name, const ValueType& type) { //Perform byte alignment constexpr int align = 16; if (m_Size / align != ((m_Size + ValueTypeSizes[static_cast<uint32_t>(type)] - 1) / align) && m_Size % align != 0) m_Size = ((m_Size / align) + 1) * align; Attributes.insert({name, {type, m_Size}}); m_Size += ValueTypeSizes[static_cast<uint32_t>(type)]; } ValueType GetTypenameFromString(const std::string& type) const; #define VALUE_TYPE_DECLARATION(Name, Type, Default) inline void Set ## Name(ShaderBufferData & data, const std::string& name, Type value) const \ { \ std::size_t offset = Attributes.find(name)->second.offset; \ Type value_ = value; \ memcpy(data.Data + offset, &value_, sizeof(Type)); \ } VALUE_TYPES_DECLARE #undef VALUE_TYPE_DECLARATION #define VALUE_TYPE_DECLARATION(Name, Type, Default) inline Type Get ## Name(ShaderBufferData & data, const std::string& name) const \ { \ std::size_t offset = Attributes.find(name)->second.offset; \ Type ret; \ memcpy(&ret, data.Data + offset, sizeof(Type)); \ return ret; \ } VALUE_TYPES_DECLARE #undef VALUE_TYPE_DECLARATION inline std::size_t GetSize() const { return m_Size; } void MapBuffer(ShaderBufferData & data, Diligent::RefCntAutoPtr<Diligent::IBuffer> buffer) const; void MapTextures(ShaderBufferData& data, Diligent::RefCntAutoPtr<Diligent::IShaderResourceBinding> srb) const; void SetDefaultAttribs(ShaderBufferData& data) const; void SetAttribsFromYaml(ShaderBufferData& data, const YAML::Node& yaml) const; ShaderBufferData CreateData(const std::string& name) const; private: std::size_t m_Size = 0; }; }
42.143713
153
0.603296
Aquaticholic
0226d207c2cff8ddfb0f5797b924142535f9ce20
6,045
cc
C++
src/engine/systems/collider_system.cc
hvonck/lambda-lilac
c4cf744356c2d2056e8f66da4f95d2268f7c25d0
[ "BSD-3-Clause" ]
1
2019-05-28T16:39:19.000Z
2019-05-28T16:39:19.000Z
src/engine/systems/collider_system.cc
hvonck/lambda-lilac
c4cf744356c2d2056e8f66da4f95d2268f7c25d0
[ "BSD-3-Clause" ]
null
null
null
src/engine/systems/collider_system.cc
hvonck/lambda-lilac
c4cf744356c2d2056e8f66da4f95d2268f7c25d0
[ "BSD-3-Clause" ]
1
2019-05-28T16:39:06.000Z
2019-05-28T16:39:06.000Z
#include "collider_system.h" #include "rigid_body_system.h" #include "transform_system.h" #include "utils/mesh_decimator.h" #include <platform/scene.h> namespace lambda { namespace components { namespace ColliderSystem { ColliderComponent addComponent(const entity::Entity& entity, scene::Scene& scene) { if (!TransformSystem::hasComponent(entity, scene)) TransformSystem::addComponent(entity, scene); scene.collider.add(entity); /** Init start */ auto& data = scene.collider.get(entity); RigidBodySystem::getPhysicsWorld(scene)->createCollisionBody(entity); return ColliderComponent(entity, scene); } ColliderComponent getComponent(const entity::Entity& entity, scene::Scene& scene) { return ColliderComponent(entity, scene); } bool hasComponent(const entity::Entity& entity, scene::Scene& scene) { return scene.collider.has(entity); } void removeComponent(const entity::Entity& entity, scene::Scene& scene) { scene.collider.remove(entity); } void collectGarbage(scene::Scene& scene) { if (!scene.collider.marked_for_delete.empty()) { for (entity::Entity entity : scene.collider.marked_for_delete) { const auto& it = scene.collider.entity_to_data.find(entity); if (it != scene.collider.entity_to_data.end()) { auto& data = scene.collider.data.at(it->second); uint32_t idx = it->second; scene.collider.unused_data_entries.push(idx); scene.collider.data_to_entity.erase(idx); scene.collider.entity_to_data.erase(entity); scene.collider.data[idx].valid = false; if (RigidBodySystem::hasComponent(entity, scene)) RigidBodySystem::removeComponent(entity, scene); RigidBodySystem::getPhysicsWorld(scene)->destroyCollisionBody(entity); } } scene.collider.marked_for_delete.clear(); } } void deinitialize(scene::Scene& scene) { Vector<entity::Entity> entities; for (const auto& it : scene.collider.entity_to_data) entities.push_back(it.first); for (const auto& entity : entities) removeComponent(entity, scene); collectGarbage(scene); } void makeBox(const entity::Entity& entity, scene::Scene& scene) { scene.rigid_body.physics_world->getCollisionBody(entity).makeBoxCollider(); } void makeSphere(const entity::Entity& entity, scene::Scene& scene) { scene.rigid_body.physics_world->getCollisionBody(entity).makeSphereCollider(); } void makeCapsule(const entity::Entity& entity, scene::Scene& scene) { scene.rigid_body.physics_world->getCollisionBody(entity).makeCapsuleCollider(); } void makeMeshCollider(const entity::Entity& entity, asset::VioletMeshHandle mesh, const uint32_t& sub_mesh_id, scene::Scene& scene) { scene.rigid_body.physics_world->getCollisionBody(entity).makeMeshCollider(mesh, sub_mesh_id); } uint16_t getLayers(const entity::Entity& entity, scene::Scene& scene) { return scene.rigid_body.physics_world->getCollisionBody(entity).getLayers(); } void setLayers(const entity::Entity& entity, const uint16_t& layers, scene::Scene& scene) { scene.rigid_body.physics_world->getCollisionBody(entity).setLayers(layers); } } // The system data. namespace ColliderSystem { Data& SystemData::add(const entity::Entity& entity) { uint32_t idx = 0ul; if (!unused_data_entries.empty()) { idx = unused_data_entries.front(); unused_data_entries.pop(); data[idx] = Data(entity); } else { idx = (uint32_t)data.size(); data.push_back(Data(entity)); data_to_entity[idx] = entity; } data_to_entity[idx] = entity; entity_to_data[entity] = idx; return data[idx]; } Data& SystemData::get(const entity::Entity& entity) { auto it = entity_to_data.find(entity); LMB_ASSERT(it != entity_to_data.end(), "COLLIDER: %llu does not have a component", entity); LMB_ASSERT(data[it->second].valid, "COLLIDER: %llu's data was not valid", entity); return data[it->second]; } void SystemData::remove(const entity::Entity& entity) { marked_for_delete.insert(entity); } bool SystemData::has(const entity::Entity& entity) { return entity_to_data.find(entity) != entity_to_data.end(); } } namespace ColliderSystem { Data::Data(const Data& other) { type = other.type; is_trigger = other.is_trigger; entity = other.entity; valid = other.valid; } Data& Data::operator=(const Data& other) { type = other.type; is_trigger = other.is_trigger; entity = other.entity; valid = other.valid; return *this; } } ColliderComponent::ColliderComponent(const entity::Entity& entity, scene::Scene& scene) : IComponent(entity), scene_(&scene) { } ColliderComponent::ColliderComponent(const ColliderComponent& other) : IComponent(other.entity_), scene_(other.scene_) { } ColliderComponent::ColliderComponent() : IComponent(entity::Entity()), scene_(nullptr) { } void ColliderComponent::makeBoxCollider() { ColliderSystem::makeBox(entity_, *scene_); } void ColliderComponent::makeSphereCollider() { ColliderSystem::makeSphere(entity_, *scene_); } void ColliderComponent::makeCapsuleCollider() { ColliderSystem::makeCapsule(entity_, *scene_); } void ColliderComponent::makeMeshCollider(asset::VioletMeshHandle mesh, const uint32_t& sub_mesh_id) { ColliderSystem::makeMeshCollider(entity_, mesh, sub_mesh_id, *scene_); } uint16_t ColliderComponent::getLayers() const { return ColliderSystem::getLayers(entity_, *scene_); } void ColliderComponent::setLayers(const uint16_t& layers) { ColliderSystem::setLayers(entity_, layers, *scene_); } } }
27.729358
135
0.66617
hvonck
02280e2bdcf0d36c1832ab5c74c6fbdd1c45cd52
2,421
cpp
C++
Sandbox/src/Player.cpp
Super-Shadow/RiseFlappyRocketGame
7ed3191823af77cd246940f6766f453c12dab601
[ "Apache-2.0" ]
null
null
null
Sandbox/src/Player.cpp
Super-Shadow/RiseFlappyRocketGame
7ed3191823af77cd246940f6766f453c12dab601
[ "Apache-2.0" ]
null
null
null
Sandbox/src/Player.cpp
Super-Shadow/RiseFlappyRocketGame
7ed3191823af77cd246940f6766f453c12dab601
[ "Apache-2.0" ]
null
null
null
#include "Player.h" #include "imgui/imgui.h" #include <glm/gtx/transform.hpp> using namespace Rise; Player::Player() { m_SmokeParticle.Position = {0.f, 0.f}; m_SmokeParticle.Velocity = {-2.f, 0.f}; m_SmokeParticle.VelocityVariation = { 4.f, 2.f}; m_SmokeParticle.SizeBegin = .35f; m_SmokeParticle.SizeEnd = 0.f; m_SmokeParticle.SizeVariation = .15f; m_SmokeParticle.ColourBegin = {.8f, .8f, .8f, 1.f}; m_SmokeParticle.ColourEnd = {.6f, .6f, .6f, 1.f}; m_SmokeParticle.LifeTime = 4.f; m_EngineParticle.Position = { 0.f, 0.f }; m_EngineParticle.Velocity = { -2.f, 0.f }; m_EngineParticle.VelocityVariation = { 3.f, 1.f }; m_EngineParticle.SizeBegin = .5f; m_EngineParticle.SizeEnd = 0.f; m_EngineParticle.SizeVariation = .3f; m_EngineParticle.ColourBegin = { 254 / 255.f, 109 / 255.f, 41 / 255.f, 1.f }; m_EngineParticle.ColourEnd = { 254 / 255.f, 212 / 255.f, 123 / 255.f, 1.f }; m_EngineParticle.LifeTime = 1.f; } void Player::LoadAssets() { m_ShipTexture = Texture2D::Create("assets/textures/ship.png"); } void Player::OnUpdate(const TimeStep timeStep) { m_Time += timeStep; if (Input::IsKeyPressed(RS_KEY_SPACE)) { m_Velocity.y += m_EnginePower; if (m_Velocity.y < 0.f) m_Velocity.y += m_EnginePower * 2.f; constexpr glm::vec2 emissionPoint = {0.f, -0.6f}; const auto rotation = glm::radians(GetRotation()); const glm::vec4 rotated = glm::rotate(glm::mat4(1.f), rotation, {.0f, .0f, 1.f}) * glm::vec4(emissionPoint, 0.f, 1.f); m_EngineParticle.Position = m_Position + glm::vec2{rotated.x, rotated.y}; m_EngineParticle.Velocity.y = -m_Velocity.y * .2f - .2f; m_ParticleSystem.Emit(m_EngineParticle); } else { m_Velocity.y -= m_Gravity; } m_Velocity.y = glm::clamp(m_Velocity.y, -20.f, 20.f); m_Position += m_Velocity * static_cast<float>(timeStep); if(m_Time > m_SmokeNextEmitTime) { m_SmokeParticle.Position = m_Position; m_ParticleSystem.Emit(m_SmokeParticle); m_SmokeNextEmitTime += m_SmokeEmitInterval; } m_ParticleSystem.OnUpdate(timeStep); } void Player::OnRender() { m_ParticleSystem.OnRender(); Renderer2D::DrawQuad({m_Position.x, m_Position.y, .5f}, glm::radians(GetRotation()), { .9f, 1.3f }, m_ShipTexture); } void Player::OnImGuiRender() { ImGui::DragFloat("Engine Power", &m_EnginePower, 0.1f); ImGui::DragFloat("Gravity", &m_Gravity, 0.1f); } void Player::Reset() { m_Position = { -10.f, 0.f }; m_Velocity = { 5.f, 0.f }; }
26.604396
120
0.693928
Super-Shadow
022b26afd6d361726223c70e6c3ffbcb736c160d
349
cpp
C++
CF/1611B.cpp
jawahiir98/CP
a32566554949cd12a62151f90ac3b82b67275cac
[ "MIT" ]
null
null
null
CF/1611B.cpp
jawahiir98/CP
a32566554949cd12a62151f90ac3b82b67275cac
[ "MIT" ]
null
null
null
CF/1611B.cpp
jawahiir98/CP
a32566554949cd12a62151f90ac3b82b67275cac
[ "MIT" ]
null
null
null
/* /\ In The Name Of Allah /\ Author : Jawahiir Nabhan */ #include <bits/stdc++.h> #define pb push_back using namespace std; typedef long long ll; const char nl = '\n'; int main() { int T; cin>> T; while(T--) { int a,b; cin>> a >> b; if(a > b) swap(a, b); cout<< min(min(a, b), (a + b)/4) << nl; } }
16.619048
47
0.495702
jawahiir98
022c8391657a0ed821ec91198f3e3811e7e6e97e
6,398
cpp
C++
DT3Core/System/Globals.cpp
9heart/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2018-10-05T15:03:27.000Z
2019-03-19T11:01:56.000Z
DT3Core/System/Globals.cpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
1
2016-01-28T14:39:49.000Z
2016-01-28T22:12:07.000Z
DT3Core/System/Globals.cpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2016-01-14T07:51:52.000Z
2021-08-21T08:02:51.000Z
//============================================================================== /// /// File: Globals.cpp /// /// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== #include "DT3Core/System/Globals.hpp" #include "DT3Core/System/StaticInitializer.hpp" #include "DT3Core/Types/Utility/MoreStrings.hpp" #include "DT3Core/Types/Utility/Error.hpp" #include "DT3Core/Types/Utility/ConsoleStream.hpp" #include DT3_HAL_INCLUDE_PATH //============================================================================== //============================================================================== namespace DT3 { //============================================================================== //============================================================================== std::mutex Globals::_globals_lock; std::map<StringCopier, Globals::GlobalsEntry> Globals::_globals; //============================================================================== //============================================================================== GLOBAL_STATIC_INITIALIZATION(0,Globals::initialize()) GLOBAL_STATIC_DESTRUCTION(0,Globals::destroy()) //============================================================================== //============================================================================== void Globals::initialize (void) { load(); } void Globals::destroy (void) { save(); } //============================================================================== //============================================================================== DTboolean Globals::has_global (const std::string &name_with_case) { std::string name = MoreStrings::lowercase(name_with_case); std::unique_lock<std::mutex> lock(_globals_lock); if (_globals.find(name) == _globals.end()) return false; else return true; } //============================================================================== //============================================================================== std::string Globals::global (const std::string &name_with_case) { // Convert name to lowercase std::string name = MoreStrings::lowercase(name_with_case); std::unique_lock<std::mutex> lock(_globals_lock); auto i = _globals.find(name); if (i != _globals.end()) return _globals[name].value; else return ""; } DTboolean Globals::global (const std::string &name_with_case, std::string &value) { // Convert name to lowercase std::string name = MoreStrings::lowercase(name_with_case); std::unique_lock<std::mutex> lock(_globals_lock); auto i = _globals.find(name); if (i != _globals.end()) { value = _globals[name].value; return true; } else { value = ""; return false; } } //============================================================================== //============================================================================== void Globals::set_global (const std::string &name_with_case, const std::string &value, const DTint lifetime) { // Convert name to lowercase std::string name = MoreStrings::lowercase(name_with_case); std::unique_lock<std::mutex> lock(_globals_lock); auto i = _globals.find(name); if ((i != _globals.end() && i->second.lifetime != READ_ONLY) || (i == _globals.end())) { GlobalsEntry entry; entry.lifetime = lifetime; entry.name = name; entry.value = value; _globals[name] = entry; } } //============================================================================== //============================================================================== void Globals::set_global_default (const std::string &name_with_case, const std::string &value, const DTint lifetime) { // Convert name to lowercase std::string name = MoreStrings::lowercase(name_with_case); std::unique_lock<std::mutex> lock(_globals_lock); auto i = _globals.find(name); if (i == _globals.end()) { GlobalsEntry entry; entry.lifetime = lifetime; entry.name = name; entry.value = value; _globals[name] = entry; } } //============================================================================== //============================================================================== std::string Globals::substitute_global (const std::string &s) { std::string value; DTboolean success = substitute_global (s, value); if (success) return value; else return s; } DTboolean Globals::substitute_global (const std::string &s, std::string &value) { value = s; for (DTuint i = 0; i < 100; ++i) { std::string::size_type first = value.find_last_of('{'); std::string::size_type last = value.find_first_of('}',first); // Check to see if a replacement has to be made if (first == std::string::npos || last == std::string::npos || last <= first) return true; std::string key = MoreStrings::lowercase(value.substr(first + 1, last - first - 1)); std::string replacement; // if global not found then return fail if (!global(key,replacement)) return false; // Do replacement value.replace(first, last-first+1, replacement); } WARNINGMSG("Exceeded maximum iterations. Infinite loop?"); return false; } //============================================================================== //============================================================================== void Globals::load (void) { std::unique_lock<std::mutex> lock(_globals_lock); auto globals = HAL::load_globals(); // Note: This doesn't overwrite existing elements so we have to manually copy below //_globals.insert(globals.begin(), globals.end()); for(auto& i : globals) _globals[i.first] = i.second; } void Globals::save (void) { std::unique_lock<std::mutex> lock(_globals_lock); HAL::save_globals(_globals); } //============================================================================== //============================================================================== } // DT3
29.897196
116
0.455924
9heart
0232334d11e4efc946c3ffad18c64a59c08d2b86
14,341
cpp
C++
src/asdxSkySphere.cpp
ProjectAsura/asdx11
67c3d4129f3e6d32e66c64ee9354d873f99d0eaf
[ "MIT" ]
null
null
null
src/asdxSkySphere.cpp
ProjectAsura/asdx11
67c3d4129f3e6d32e66c64ee9354d873f99d0eaf
[ "MIT" ]
null
null
null
src/asdxSkySphere.cpp
ProjectAsura/asdx11
67c3d4129f3e6d32e66c64ee9354d873f99d0eaf
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // File : asdxSkySphere.cpp // Desc : Sky Sphere Module. // Copyright(c) Project Asura. All right reserved. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------- #include <asdxSkySphere.h> #include <asdxLogger.h> #include <vector> namespace { #include "../res/shaders/Compiled/SkySphereVS.inc" #include "../res/shaders/Compiled/SkySpherePS.inc" #include "../res/shaders/Compiled/SkySphereFlowPS.inc" /////////////////////////////////////////////////////////////////////////////// // CbSkySphere structure /////////////////////////////////////////////////////////////////////////////// struct alignas(16) CbSkySphere { asdx::Matrix World; //!< ワールド行列. asdx::Matrix View; //!< ビュー行列. asdx::Matrix Proj; //!< 射影行列. float SphereSize; //!< スカイスフィアサイズ. float Padding[3]; }; /////////////////////////////////////////////////////////////////////////////// // CbSkySphereFlow structure /////////////////////////////////////////////////////////////////////////////// struct alignas(16) CbSkySphereFlow { asdx::Vector3 WindDirection; //!< 風の方向. float Padding0; asdx::Vector2 Offset; //!< オフセット. }; /////////////////////////////////////////////////////////////////////////////// // Vertex structure /////////////////////////////////////////////////////////////////////////////// struct Vertex { asdx::Vector3 Position; //!< 位置座標です. asdx::Vector2 Texcoord; //!< テクスチャ座標です. asdx::Vector3 Normal; //!< 法線ベクトルです. asdx::Vector3 Tangent; //!< 接線ベクトルです. }; } // namespace namespace asdx { /////////////////////////////////////////////////////////////////////////////// // SkySphere class /////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // コンストラクタです. //----------------------------------------------------------------------------- SkySphere::SkySphere() { ResetFlow(); } //----------------------------------------------------------------------------- // デストラクタです. //----------------------------------------------------------------------------- SkySphere::~SkySphere() { Term(); } //----------------------------------------------------------------------------- // 初期化処理を行います. //----------------------------------------------------------------------------- bool SkySphere::Init(ID3D11Device* pDevice, int tessellation) { HRESULT hr = S_OK; // 頂点シェーダ・入力レイアウトの生成. { hr = pDevice->CreateVertexShader(SkySphereVS, sizeof(SkySphereVS), nullptr, m_pVS.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateVertexShader() Failed."); return false; } D3D11_INPUT_ELEMENT_DESC elements[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA }, { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA } }; hr = pDevice->CreateInputLayout(elements, 4, SkySphereVS, sizeof(SkySphereVS), m_pIL.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateInputLayout() Failed."); return false; } } // ピクセルシェーダの生成. { hr = pDevice->CreatePixelShader(SkySpherePS, sizeof(SkySpherePS), nullptr, m_pPS.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreatePixelShader() Failed."); return false; } } // フロー用ピクセルシェーダの生成. { hr = pDevice->CreatePixelShader(SkySphereFlowPS, sizeof(SkySphereFlowPS), nullptr, m_pPSFlow.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreatePixelShader() Failed."); return false; } } // 定数バッファの生成. { D3D11_BUFFER_DESC desc = {}; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.ByteWidth = sizeof(CbSkySphere); desc.Usage = D3D11_USAGE_DEFAULT; hr = pDevice->CreateBuffer(&desc, nullptr, m_pCB.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateBuffer() Failed."); return false; } } // 定数バッファの生成. { D3D11_BUFFER_DESC desc = {}; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.ByteWidth = sizeof(CbSkySphereFlow); desc.Usage = D3D11_USAGE_DEFAULT; hr = pDevice->CreateBuffer(&desc, nullptr, m_pCBFlow.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateBuffer() Failed."); return false; } } // 頂点バッファとインデックスバッファの生成. { std::vector<Vertex> vertices; std::vector<uint32_t> indices; uint32_t verticalSegments = tessellation; uint32_t horizontalSegments = tessellation * 2; float radius = 1.0f; // Create rings of vertices at progressively higher latitudes. for (size_t i = 0; i <= verticalSegments; i++) { float v = 1 - (float)i / verticalSegments; float theta = (i * F_PI / verticalSegments) - F_PIDIV2; auto st = sin(theta); auto ct = cos(theta); // Create a single ring of vertices at this latitude. for (size_t j = 0; j <= horizontalSegments; j++) { float u = (float)j / horizontalSegments; float phi = j * F_2PI / horizontalSegments; auto sp = sin(phi); auto cp = cos(phi); auto normal = Vector3(sp * ct, st, cp * ct); auto uv = Vector2(u, v); auto l = normal.x * normal.x + normal.z * normal.z; Vector3 tangent; tangent.x = st * cp; tangent.y = st * sp; tangent.z = ct; Vertex vert; vert.Position = normal * radius; vert.Texcoord = uv; vert.Normal = normal; vert.Tangent = tangent; vertices.push_back(vert); } } // Fill the index buffer with triangles joining each pair of latitude rings. uint32_t stride = horizontalSegments + 1; for (auto i = 0u; i < verticalSegments; i++) { for (auto j = 0u; j <= horizontalSegments; j++) { auto nextI = i + 1; auto nextJ = (j + 1) % stride; indices.push_back(i * stride + j); indices.push_back(nextI * stride + j); indices.push_back(i * stride + nextJ); indices.push_back(i * stride + nextJ); indices.push_back(nextI * stride + j); indices.push_back(nextI * stride + nextJ); } } // 頂点バッファの生成. { auto vertexCount = uint32_t(vertices.size()); D3D11_BUFFER_DESC desc = {}; desc.Usage = D3D11_USAGE_DEFAULT; desc.ByteWidth = sizeof(Vertex) * vertexCount; desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA res = {}; res.pSysMem = &vertices[0]; hr = pDevice->CreateBuffer(&desc, &res, m_pVB.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateBuffer() Failed."); return false; } } // インデックスバッファの生成. { m_IndexCount = uint32_t(indices.size()); D3D11_BUFFER_DESC desc = {}; desc.Usage = D3D11_USAGE_DEFAULT; desc.ByteWidth = sizeof(uint32_t) * m_IndexCount; desc.BindFlags = D3D11_BIND_INDEX_BUFFER; D3D11_SUBRESOURCE_DATA res = {}; res.pSysMem = &indices[0]; hr = pDevice->CreateBuffer(&desc, &res, m_pIB.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateBuffer() Failed."); return false; } } } return true; } //----------------------------------------------------------------------------- // 終了処理を行います. //----------------------------------------------------------------------------- void SkySphere::Term() { m_pVB.Reset(); m_pIB.Reset(); m_pCB.Reset(); m_pIL.Reset(); m_pVS.Reset(); m_pPS.Reset(); m_pPSFlow.Reset(); m_pCBFlow.Reset(); } //----------------------------------------------------------------------------- // 描画処理を行います. //----------------------------------------------------------------------------- void SkySphere::Draw ( ID3D11DeviceContext* pContext, ID3D11ShaderResourceView* pSRV, ID3D11SamplerState* pSmp, float sphereSize, const Vector3& cameraPos, const Matrix& view, const Matrix& proj ) { auto stride = uint32_t(sizeof(Vertex)); auto offset = 0u; pContext->VSSetShader(m_pVS.GetPtr(), nullptr, 0); pContext->PSSetShader(m_pPS.GetPtr(), nullptr, 0); pContext->GSSetShader(nullptr, nullptr, 0); pContext->HSSetShader(nullptr, nullptr, 0); pContext->DSSetShader(nullptr, nullptr, 0); auto pCB = m_pCB.GetPtr(); { CbSkySphere buf = {}; buf.World = Matrix::CreateTranslation(cameraPos); buf.View = view; buf.Proj = proj; buf.SphereSize = sphereSize; pContext->UpdateSubresource(pCB, 0, nullptr, &buf, 0, 0); } pContext->VSSetConstantBuffers(0, 1, &pCB); pContext->PSSetShaderResources(0, 1, &pSRV); pContext->PSSetSamplers(0, 1, &pSmp); pContext->IASetInputLayout(m_pIL.GetPtr()); pContext->IASetIndexBuffer(m_pIB.GetPtr(), DXGI_FORMAT_R32_UINT, 0); pContext->IASetVertexBuffers(0, 1, m_pVB.GetAddress(), &stride, &offset); pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); pContext->DrawIndexed(m_IndexCount, 0, 0); ID3D11ShaderResourceView* pNullSRV[1] = { nullptr }; ID3D11SamplerState* pNullSmp[1] = { nullptr }; pContext->PSSetShaderResources(0, 1, pNullSRV); pContext->PSSetSamplers(0, 1, pNullSmp); pContext->VSSetShader(nullptr, nullptr, 0); pContext->PSSetShader(nullptr, nullptr, 0); } //----------------------------------------------------------------------------- // 描画処理を行います. //----------------------------------------------------------------------------- void SkySphere::DrawFlow ( ID3D11DeviceContext* pContext, ID3D11ShaderResourceView* pSRV, ID3D11SamplerState* pSmp, float sphereSize, const Vector3& cameraPos, const Matrix& view, const Matrix& proj, const Vector3& flowDir, float flowStep ) { auto stride = uint32_t(sizeof(Vertex)); auto offset = 0u; pContext->VSSetShader(m_pVS.GetPtr(), nullptr, 0); pContext->PSSetShader(m_pPSFlow.GetPtr(), nullptr, 0); pContext->GSSetShader(nullptr, nullptr, 0); pContext->HSSetShader(nullptr, nullptr, 0); pContext->DSSetShader(nullptr, nullptr, 0); auto pCB = m_pCB.GetPtr(); { CbSkySphere buf = {}; buf.World = Matrix::CreateRotationX(F_PIDIV2) * Matrix::CreateTranslation(cameraPos); buf.View = view; buf.Proj = proj; buf.SphereSize = sphereSize; pContext->UpdateSubresource(pCB, 0, nullptr, &buf, 0, 0); } auto pCBFlow = m_pCBFlow.GetPtr(); { CbSkySphereFlow buf = {}; buf.WindDirection = flowDir; buf.Offset.x = m_FlowOffset[0]; buf.Offset.y = m_FlowOffset[1]; m_FlowOffset[0] += flowStep; m_FlowOffset[1] += flowStep; if (m_FlowOffset[0] > 1.0f) { m_FlowOffset[0] -= 1.0f; } if (m_FlowOffset[1] > 1.0f) { m_FlowOffset[1] -= 1.0f; } pContext->UpdateSubresource(pCBFlow, 0, nullptr, &buf, 0, 0); } pContext->VSSetConstantBuffers(0, 1, &pCB); pContext->PSSetConstantBuffers(1, 1, &pCBFlow); pContext->PSSetShaderResources(0, 1, &pSRV); pContext->PSSetSamplers(0, 1, &pSmp); pContext->IASetInputLayout(m_pIL.GetPtr()); pContext->IASetIndexBuffer(m_pIB.GetPtr(), DXGI_FORMAT_R32_UINT, 0); pContext->IASetVertexBuffers(0, 1, m_pVB.GetAddress(), &stride, &offset); pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); pContext->DrawIndexed(m_IndexCount, 0, 0); ID3D11ShaderResourceView* pNullSRV[1] = { nullptr }; ID3D11SamplerState* pNullSmp[1] = { nullptr }; pContext->PSSetShaderResources(0, 1, pNullSRV); pContext->PSSetSamplers(0, 1, pNullSmp); pContext->VSSetShader(nullptr, nullptr, 0); pContext->PSSetShader(nullptr, nullptr, 0); } //----------------------------------------------------------------------------- // フローオフセットをリセットします. //----------------------------------------------------------------------------- void SkySphere::ResetFlow() { m_FlowOffset[0] = 0.0f; m_FlowOffset[1] = 0.5f; } } // namespace asdx
33.664319
122
0.473816
ProjectAsura
0238d577559be1aeeded0fdfb1e11de41c886a7b
718
hpp
C++
src/layout/composer.hpp
kounoike/hisui
7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce
[ "Apache-2.0" ]
null
null
null
src/layout/composer.hpp
kounoike/hisui
7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce
[ "Apache-2.0" ]
null
null
null
src/layout/composer.hpp
kounoike/hisui
7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce
[ "Apache-2.0" ]
null
null
null
#pragma once #include <array> #include <cstddef> #include <cstdint> #include <memory> #include <vector> #include "layout/cell_util.hpp" namespace hisui::layout { class Region; struct ComposerParameters { const std::vector<std::shared_ptr<Region>>& regions; const Resolution& resolution; }; class Composer { public: explicit Composer(const ComposerParameters&); ~Composer(); void compose(std::vector<unsigned char>*, const std::uint64_t); private: std::vector<std::shared_ptr<Region>> m_regions; Resolution m_resolution; std::array<unsigned char*, 3> m_planes; std::array<std::size_t, 3> m_plane_sizes; std::array<unsigned char, 3> m_plane_default_values; }; } // namespace hisui::layout
20.514286
65
0.729805
kounoike
0241e131febd400c95b44450a12d4a135b6f0489
1,007
cc
C++
Daily_Problem/2101/Beginning/210104_Fibonacci_Number/method2/solution.cc
sheriby/DandAInLeetCode
dd7f5029aa0c297ea82bb20f882b524789f35c96
[ "MIT" ]
1
2020-02-07T12:25:56.000Z
2020-02-07T12:25:56.000Z
Daily_Problem/2101/Beginning/210104_Fibonacci_Number/method2/solution.cc
sheriby/DandAInLeetCode
dd7f5029aa0c297ea82bb20f882b524789f35c96
[ "MIT" ]
null
null
null
Daily_Problem/2101/Beginning/210104_Fibonacci_Number/method2/solution.cc
sheriby/DandAInLeetCode
dd7f5029aa0c297ea82bb20f882b524789f35c96
[ "MIT" ]
null
null
null
#include <vector> using std::vector; class Solution { public: // 除去直接使用通项公式的方法,还有一种方法时间复杂度更低, // 1 1 ^n f(1) = f(n+1) // 1 0 f(0) f(n) using matrix_type = vector<vector<int>>; int fib(int n) { if (n < 2) return n; matrix_type a{{1, 1}, {1, 0}}; matrix_type r = matrix_pow(a, n - 1); return r[0][0]; } matrix_type matrix_pow(matrix_type& matrix, int n) { matrix_type result{{1, 0}, {0, 1}}; while (n) { if (n & 1) { result = matrix_multiply(result, matrix); } matrix = matrix_multiply(matrix, matrix); n >>= 1; } return result; } matrix_type matrix_multiply(matrix_type& a, matrix_type& b) { matrix_type c(2, vector<int>(2)); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j]; } } return c; } };
23.97619
65
0.454816
sheriby
0249b78204328624e2fdccb88e9a72f5398166e4
5,933
cpp
C++
platform-io/lib/zeromq/src/zeromq/esp8266/ZeroMQConnection.cpp
darvik80/rover-cpp
8da7b7f07efe7096843ae17536603277f55debea
[ "Apache-2.0" ]
2
2020-01-13T07:32:50.000Z
2020-03-03T14:32:25.000Z
platform-io/lib/zeromq/src/zeromq/esp8266/ZeroMQConnection.cpp
darvik80/rover-cpp
8da7b7f07efe7096843ae17536603277f55debea
[ "Apache-2.0" ]
16
2019-06-16T05:51:02.000Z
2020-02-03T01:59:23.000Z
platform-io/lib/zeromq/src/zeromq/esp8266/ZeroMQConnection.cpp
darvik80/rover-cpp
8da7b7f07efe7096843ae17536603277f55debea
[ "Apache-2.0" ]
1
2020-03-03T14:32:27.000Z
2020-03-03T14:32:27.000Z
// // Created by Ivan Kishchenko on 01.09.2021. // #ifdef ARDUINO_ARCH_ESP8266 #include "ZeroMQConnection.h" #include "../ZeroMQReader.h" #include <HardwareSerial.h> size_t ZeroMQDataMessage::ack(size_t len) { // If the whole message is now acked... if (_acked + len > _buf->size()) { // Return the number of extra bytes acked (they will be carried on to the next message) const size_t extra = _acked + len - _buf->size(); _acked = _buf->size(); return extra; } // Return that no extra bytes left. _acked += len; return 0; } size_t ZeroMQDataMessage::send(AsyncClient *client) { const size_t len = _buf->size() - _sent; if (client->space() < len) { return 0; } size_t sent = client->add((const char *) _buf->data(), len); if (client->canSend()) { client->send(); } _sent += sent; return sent; } ZeroMQDataMessage::ZeroMQDataMessage(std::shared_ptr<ZeroMQCharBuf> &buf) : _buf(std::move(buf)) { } ZeroMQConnection::ZeroMQConnection(AsyncClient *client) : _serverMode{true}, _client(client), _state{ZeroMQStatus::ZMQ_Idle} { _dec.onCommand([this](const ZeroMQCommand &cmd) { onCommand(cmd); }); _dec.onMessage([this](const ZeroMQMessage &msg) { onMessage(msg); }); _topics.insert("joystick"); } void ZeroMQConnection::onConnect() { _state = ZeroMQStatus::ZMQ_Idle; std::shared_ptr<ZeroMQCharBuf> buf(new ZeroMQBufFix<64>()); std::ostream out(buf.get()); ZeroMQGreeting reply(true); out << reply; send(buf); } void ZeroMQConnection::onError(int8_t error) { Serial.printf("%s: conn error: %s \n", _client->remoteIP().toString().c_str(), _client->errorToString(error)); } void ZeroMQConnection::onData(void *data, size_t len) { // Serial.printf("%s: recv: %d\n", _client->remoteIP().toString().c_str(), len); // Serial.println(ZeroMQUtils::netDump((uint8_t *) data, len).c_str()); _inc.sputn((const char *) data, (std::streamsize) len); onData(_inc); } void ZeroMQConnection::onData(ZeroMQCharBuf &incBuf) { while (incBuf.in_avail()) { switch (_state) { case ZeroMQStatus::ZMQ_Idle: case ZeroMQStatus::ZMQ_S_Wait_Greeting: { if (_inc.in_avail() < 64) { return; } ZeroMQReader inc(incBuf); std::array<uint8_t, 64> greeting{}; inc.readBinary<uint8_t, 64>(greeting); _inc.consume(64); _version.major = greeting[10]; _version.minor = greeting[11]; if (_version.major != 0x03) { Serial.printf("%s: unsupported version: %d:%d\n", getRemoteAddress().c_str(), _version.major, _version.minor); _client->close(); return; } Serial.printf("%s: version: %d:%d\n", getRemoteAddress().c_str(), _version.major, _version.minor); ZeroMQCommand reply(ZERO_MQ_CMD_READY); reply.props.emplace(ZERO_MQ_PROP_SOCKET_TYPE, "SUB"); std::shared_ptr<ZeroMQCharBuf> out(new ZeroMQBufFix<64>()); _enc.write(*out, reply); send(out); _state = ZeroMQStatus::ZMQ_Stream; break; } case ZeroMQStatus::ZMQ_Stream: { if (_dec.read(incBuf)) { return; } } break; default: break; } } } void ZeroMQConnection::onDisconnect() { } void ZeroMQConnection::onTimeOut(uint32_t time) { } void ZeroMQConnection::onPool() { runQueue(); } void ZeroMQConnection::onAck(size_t len) { if (!_out.empty()) { _out.front()->ack(len); } onPool(); } void ZeroMQConnection::send(std::shared_ptr<ZeroMQCharBuf> &msg) { // Serial.printf("send: %d\n", msg->size()); // Serial.println(msg->dump().c_str()); _out.emplace_back(new ZeroMQDataMessage(msg)); if (_client->canSend()) { runQueue(); } } void ZeroMQConnection::runQueue() { while (!_out.empty() && _out.front()->finished()) { _out.remove(_out.front()); } for (auto &buf: _out) { if (!buf->sent()) { buf->send(_client); } } } void ZeroMQConnection::onCommand(const ZeroMQCommand &cmd) { if (cmd.getName() == ZERO_MQ_CMD_READY) { Serial.printf("%s: %s\n", getRemoteAddress().c_str(), cmd.getName().c_str()); for (auto &prop: cmd.props) { Serial.printf("%s: %s %s\n", getRemoteAddress().c_str(), prop.first.c_str(), prop.second.c_str()); } // subscribe = %x00 short-size %d1 subscription for (auto &topic: _topics) { std::shared_ptr<ZeroMQCharBuf> out(new ZeroMQBufFix<64>()); if (_version.minor == 0x00) { std::ostream str(out.get()); str << (uint8_t) 0x00 << (uint8_t) (1 + 8) << (uint8_t) 0x01 << topic; } else if (_version.minor == 0x01) { ZeroMQCommand sub(ZERO_MQ_CMD_SUBSCRIBE); sub.props.emplace(ZERO_MQ_PROP_SUBSCRIPTION, topic); _enc.write(*out, sub); } send(out); } } else { Serial.printf("%s: %s unsupported\n", getRemoteAddress().c_str(), cmd.name.c_str()); } } void ZeroMQConnection::onMessage(const ZeroMQMessage &msg) { if (msg.data.size() == 2 && _topicEventHandler) { Serial.printf("%s: sub: %s:%s\n", getRemoteAddress().c_str(), msg.data.front().c_str(), msg.data.back().c_str()); _topicEventHandler(ZeroMQTopicEvent{msg.data.front(), msg.data.back()}); return; } for (const auto &item: msg.data) { Serial.printf("%s: msg %s\n", getRemoteAddress().c_str(), item.c_str()); } } #endif
30.116751
130
0.568178
darvik80
024fb820d76ab863416a6f3ad7ef02dae89eea3a
4,329
cpp
C++
VAlloc.cpp
nardinan/vulture
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
[ "FTL" ]
null
null
null
VAlloc.cpp
nardinan/vulture
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
[ "FTL" ]
null
null
null
VAlloc.cpp
nardinan/vulture
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
[ "FTL" ]
null
null
null
/* PSYCHO GAMES(C) STUDIOS - 2007 www.psychogames.net * Project: Vulture(c) * Author : Andrea Nardinocchi * eMail : [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "VAlloc.h" unsigned int memory = 0; unsigned int pointers = 0; allocationslist *allocationsroot = NULL; void *vmalloc(size_t size, const char *file, int line) { vcoords *coords = NULL; allocationslist *list = allocationsroot; int index; void *result = NULL; unsigned char *check = NULL; if ((result = malloc(size + sizeof (vcoords) + 20))) { pointers++; memory += size + sizeof (vcoords) + 20; check = (unsigned char *) ((char *) result + size); coords = (vcoords *) (check + 20); coords->file = file; coords->line = line; for (index = 0; index < size; index++) ((char *) result)[index] = '\0'; *((unsigned int *) check) = 0xdeadbeef; if (allocationsroot) { while (list->next) list = list->next; if ((list->next = (allocationslist *) malloc(sizeof (allocationslist)))) { list->next->pointer = result; list->next->buffersize = size; list->next->next = NULL; list->next->back = list; } else LOG_ERROR("unable to allocate node of the list"); } else { if ((allocationsroot = (allocationslist *) malloc(sizeof (allocationslist)))) { allocationsroot->pointer = result; allocationsroot->buffersize = size; allocationsroot->next = NULL; allocationsroot->back = NULL; } else LOG_ERROR("unable to allocate root of the list"); } } return result; } void *vrealloc(void *pointer, size_t size) { allocationslist *list = allocationsroot; void *result = NULL; while ((list) && (list->pointer != pointer)) list = list->next; if (list->pointer == pointer) { if ((result = pvmalloc(size))) { memcpy(result, pointer, list->buffersize); pvfree(pointer); } } return result; } void vfree(void *pointer) { allocationslist *list = allocationsroot; while ((list) && (list->pointer != pointer)) list = list->next; if ((list) && (list->pointer == pointer)) { pointers--; memory -= list->buffersize + sizeof (vcoords) + 20; if (list->next) list->next->back = list->back; if (list->back) list->back->next = list->next; else allocationsroot = list->next; free(list); free(pointer); } else LOG_ERROR("unable to find reference on pointers' list (double free!)"); } void vdeallocate(void) { vshow(); while (allocationsroot) pvfree(allocationsroot->pointer); } int vshow(void) { vcoords *coords = NULL; allocationslist *list = allocationsroot; unsigned char *check = NULL; unsigned int correct = 0, errors = 0; while (list) { check = (unsigned char *) (((char *) list->pointer) + (size_t) list->buffersize); coords = (vcoords *) (check + 20); if (*((unsigned int *) check) == 0xdeadbeef) correct++; else errors++; printf("\n[POINTER] %p at %s (row %d) 0xDEADBEEF (contain: %s) { %s }!", list->pointer, coords->file, coords->line, list->pointer, (*((unsigned int *) check) == 0xdeadbeef) ? "OK" : "ERROR"); list = list->next; } printf("\n[FINISH] I've found: %d correct pointers AND %d damaged pointers (%s)\n", correct, errors, ((errors == 0) ? "that's good for you!" : "uh-oh!")); return errors; }
37.318966
91
0.585355
nardinan
025a22a31abed79d345bca7e660f644db80de58c
571
cpp
C++
Stack.cpp
nyugoh/STL
3cd09e0be525e8951d7e28bc935fc0aa1971777c
[ "Apache-2.0" ]
null
null
null
Stack.cpp
nyugoh/STL
3cd09e0be525e8951d7e28bc935fc0aa1971777c
[ "Apache-2.0" ]
null
null
null
Stack.cpp
nyugoh/STL
3cd09e0be525e8951d7e28bc935fc0aa1971777c
[ "Apache-2.0" ]
null
null
null
#include <stack> #include <iostream> using namespace std; int main(){ stack<string> applications; //Adding elements to the stack applications.push("ASPOF-3435"); applications.push("AAKJDH2399"); applications.push("ADXKJQ2332"); applications.push("ASDWWE232"); applications.push("ASKLD923"); std::cout << "Use applications.pop() to remove the top element." << '\n'; std::cout << "Use applications.top() to return the top element." << '\n'; std::cout << "The first element :: "<< applications.top() << '\n'; return 0; }
25.954545
77
0.635727
nyugoh
025db52336b789ba6b08c8a68415287dcddffdec
2,699
hpp
C++
septem/include/communication.hpp
CalielOfSeptem/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
1
2017-03-30T14:31:33.000Z
2017-03-30T14:31:33.000Z
septem/include/communication.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
septem/include/communication.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
// ========================================================================== #ifndef SE7EN_COMMUNICATION_HPP_ #define SE7EN_COMMUNICATION_HPP_ #include <string> #include <boost/shared_ptr.hpp> namespace terminalpp { class string; } class client; class world_context; //* ========================================================================= /// \brief Send a text message to all connected players. //* ========================================================================= void send_to_all( boost::shared_ptr<world_context> &ctx , std::string const &text); //* ========================================================================= /// \brief Send a text message to all connected players. //* ========================================================================= void send_to_all( std::shared_ptr<world_context> &ctx , terminalpp::string const &text); //* ========================================================================= /// \brief Send a text message to a single player. //* ========================================================================= void send_to_player( std::shared_ptr<world_context> &ctx , char const *text , std::shared_ptr< client >& player); //* ========================================================================= /// \brief Send a text message to a single player. //* ========================================================================= void send_to_player( std::shared_ptr<world_context> &ctx , std::string const &text , std::shared_ptr<client> &player); //* ========================================================================= /// \brief Send a text message to a single player. //* ======================================================================== void send_to_player( std::shared_ptr<world_context> &ctx , terminalpp::string const &text , std::shared_ptr<client> &player); //* ========================================================================= /// \brief Send a text message to all players in the same room as player, /// but not to player. //* ========================================================================= void send_to_room( std::shared_ptr<world_context> &ctx , std::string const &text , std::shared_ptr<client> &player); //* ========================================================================= /// \brief Send a text message to all players in the same room as player, /// but not to player. //* ========================================================================= void send_to_room( std::shared_ptr<world_context> &ctx , terminalpp::string const &text , std::shared_ptr<client> &player); #endif
34.164557
77
0.399407
CalielOfSeptem
025ffbb15475ed2d03edf32bfe3b9fbf87e589d8
2,708
hpp
C++
src/nnfusion/core/kernels/hlsl/hlsl_kernel_emitter.hpp
LittleQili/nnfusion
6c1a25db5be459a1053798f1c75bfbd26863ed08
[ "MIT" ]
1
2021-05-14T08:10:30.000Z
2021-05-14T08:10:30.000Z
src/nnfusion/core/kernels/hlsl/hlsl_kernel_emitter.hpp
LittleQili/nnfusion
6c1a25db5be459a1053798f1c75bfbd26863ed08
[ "MIT" ]
null
null
null
src/nnfusion/core/kernels/hlsl/hlsl_kernel_emitter.hpp
LittleQili/nnfusion
6c1a25db5be459a1053798f1c75bfbd26863ed08
[ "MIT" ]
1
2021-08-11T09:09:53.000Z
2021-08-11T09:09:53.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "nnfusion/common/common.hpp" #include "nnfusion/common/languageunit.hpp" #include "nnfusion/core/kernels/antares_ke_imp.hpp" #include "nnfusion/core/kernels/kernel_emitter.hpp" #include "nnfusion/core/operators/generic_op/generic_op.hpp" DECLARE_string(fantares_codegen_server); namespace nnfusion { namespace kernels { namespace hlsl { class HLSLKernelEmitter : public KernelEmitter { public: HLSLKernelEmitter(shared_ptr<KernelContext> ctx) : KernelEmitter(ctx, "hlsl") { } virtual LanguageUnit_p emit_dependency() override; }; class AntaresHLSLKernelEmitter : public HLSLKernelEmitter { public: AntaresHLSLKernelEmitter(shared_ptr<KernelContext> ctx) : HLSLKernelEmitter(ctx) , m_antares_ke_imp(new AntaresKEImp) { if (!FLAGS_fantares_codegen_server.empty()) { ir = nnfusion::op::get_translation_v2(ctx->gnode); if (ir.empty()) ir = nnfusion::op::get_translation(ctx->gnode); if (!ir.empty()) { const char annotation[] = "## @annotation: "; int pos = ir.find(annotation); if (pos >= 0) { pos += sizeof(annotation) - 1; options = ir.substr(pos); } if (options.size() > 0) { if (options[0] != '|') options = "|" + options; if (options.back() != '|') options += "|"; } auto info = m_antares_ke_imp->autogen(ir); antares_code = info.first; m_is_tuned = info.second; } } } virtual LanguageUnit_p emit_function_body() override; virtual LanguageUnit_p emit_function_call() override; AntaresKEImp::Pointer m_antares_ke_imp; std::string antares_code; protected: std::string ir, options; }; } } }
34.717949
75
0.441654
LittleQili
026740d230641181e886680a0a7b6c846e76d76e
1,286
cpp
C++
first_round/easy/test/test_add_two_nums_smartptr.cpp
forwardkth/leetcode
af1ecf96ca0630b2124f06b0527088f91ee2dafe
[ "MIT" ]
1
2019-01-29T16:23:33.000Z
2019-01-29T16:23:33.000Z
first_round/easy/test/test_add_two_nums_smartptr.cpp
forwardkth/leetcode
af1ecf96ca0630b2124f06b0527088f91ee2dafe
[ "MIT" ]
null
null
null
first_round/easy/test/test_add_two_nums_smartptr.cpp
forwardkth/leetcode
af1ecf96ca0630b2124f06b0527088f91ee2dafe
[ "MIT" ]
null
null
null
#include "../include/add_two_nums_smartptr.h" #include <gtest/gtest.h> //Google Test cases TEST(AddTwoNums_sharedPtr_Test, testPos) { ListNodeShared* ls1 = new ListNodeShared(2); ls1->next = make_shared<ListNodeShared>(4); ls1->next->next = make_shared<ListNodeShared>(3); ListNodeShared* ls2 = new ListNodeShared(5); ls2->next = make_shared<ListNodeShared>(6); ls2->next->next = make_shared<ListNodeShared>(4); AddTwoNumsSolution2 ats2; ListNodeShared* result2 = ats2.AddTwoNums(ls1, ls2); EXPECT_EQ(7, result2->val); EXPECT_EQ(0, result2->next->val); EXPECT_EQ(8, result2->next->next->val); EXPECT_NO_THROW(ats2.AddTwoNums(ls1, ls2)); } TEST(AddTwoNums_fullySharedPtr_Test, testPos) { std::shared_ptr<ListNodeShared> ls1 = make_shared<ListNodeShared>(2); ls1->next = make_shared<ListNodeShared>(4); ls1->next->next = make_shared<ListNodeShared>(3); std::shared_ptr<ListNodeShared> ls2 = make_shared<ListNodeShared>(5); ls2->next = make_shared<ListNodeShared>(6); ls2->next->next = make_shared<ListNodeShared>(4); AddTwoNumsSolution3 ats3; auto result3 = ats3.AddTwoNums(ls1, ls2); EXPECT_EQ(7, result3->val); EXPECT_EQ(0, result3->next->val); EXPECT_EQ(8, result3->next->next->val); EXPECT_NO_THROW(ats3.AddTwoNums(ls1, ls2)); }
31.365854
71
0.730949
forwardkth
026d5be2cb1f5ab3247a0e0f36b008c1a18e59a0
4,124
cpp
C++
darwin/unix_adapter.cpp
mikecovlee/darwin
000bcfd31994be860a422fe2fb11dbced408da72
[ "Apache-2.0" ]
20
2016-12-12T12:07:44.000Z
2021-07-29T01:23:35.000Z
darwin/unix_adapter.cpp
mikecovlee/darwin
000bcfd31994be860a422fe2fb11dbced408da72
[ "Apache-2.0" ]
null
null
null
darwin/unix_adapter.cpp
mikecovlee/darwin
000bcfd31994be860a422fe2fb11dbced408da72
[ "Apache-2.0" ]
7
2016-12-17T12:52:19.000Z
2020-04-04T03:35:47.000Z
/* * Covariant Darwin Universal Character Graphics Library * * 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. * * Copyright (C) 2018 Michael Lee(李登淳) * Email: [email protected] * Github: https://github.com/mikecovlee */ #include "./module.hpp" #include "./graphics.hpp" #include "./unix_conio.hpp" #include <cstdio> #include <string> namespace darwin { class unix_adapter : public platform_adapter { bool mReady = false; picture mDrawable; public: unix_adapter() = default; virtual ~unix_adapter() = default; virtual status get_state() const override { if (mReady) return status::ready; else return status::leisure; } virtual results init() override { conio::reset(); //conio::clrscr(); conio::echo(false); mReady = true; return results::success; } virtual results stop() override { conio::reset(); //conio::clrscr(); conio::echo(true); mReady = false; return results::success; } virtual results exec_commands(commands c) override { switch (c) { case commands::echo_on: conio::echo(true); break; case commands::echo_off: conio::echo(false); break; case commands::reset_cursor: conio::gotoxy(0, 0); break; case commands::reset_attri: conio::reset(); break; case commands::clrscr: conio::clrscr(); break; } return results::success; } virtual bool is_kb_hit() override { return conio::kbhit(); } virtual int get_kb_hit() override { return conio::getch(); } virtual results fit_drawable() override { mDrawable.resize(conio::terminal_width(), conio::terminal_height()); return results::success; } virtual drawable *get_drawable() override { return &mDrawable; } virtual results update_drawable() override { conio::gotoxy(0, 0); std::size_t sw(std::min<std::size_t>(mDrawable.get_width(), conio::terminal_width())), sh( std::min<std::size_t>(mDrawable.get_height(), conio::terminal_height())); for (std::size_t y = 0; y < sh; ++y) { for (std::size_t x = 0; x < sw; ++x) { const pixel &pix = mDrawable.get_pixel(x, y); std::string cmd = "\e[0m\e["; switch (pix.get_front_color()) { case colors::white: cmd += "37;"; break; case colors::black: cmd += "30;"; break; case colors::red: cmd += "31;"; break; case colors::green: cmd += "32;"; break; case colors::blue: cmd += "34;"; break; case colors::pink: cmd += "35;"; break; case colors::yellow: cmd += "33;"; break; case colors::cyan: cmd += "36;"; break; default: return results::failure; break; } switch (pix.get_back_color()) { case colors::white: cmd += "47"; break; case colors::black: cmd += "40"; break; case colors::red: cmd += "41"; break; case colors::green: cmd += "42"; break; case colors::blue: cmd += "44"; break; case colors::pink: cmd += "45"; break; case colors::yellow: cmd += "43"; break; case colors::cyan: cmd += "46"; break; default: return results::failure; break; } if (pix.is_bright()) cmd += ";1"; if (pix.is_underline()) cmd += ";4"; cmd += "m"; printf("%s%c", cmd.c_str(), pix.get_char()); } conio::reset(); printf("\n"); } fflush(stdout); return results::success; } } dunixadapter; platform_adapter *module_resource() { return &dunixadapter; } }
21.591623
93
0.598206
mikecovlee
0276aff95eb79ef76baddcf8dac2319d4bf66be9
1,986
cpp
C++
parts/Drive.cpp
fdekruijff/Group-Project-TICT-V1GP-15
ec1de58bf3e5f22066f563e0014760e54d779159
[ "MIT" ]
null
null
null
parts/Drive.cpp
fdekruijff/Group-Project-TICT-V1GP-15
ec1de58bf3e5f22066f563e0014760e54d779159
[ "MIT" ]
null
null
null
parts/Drive.cpp
fdekruijff/Group-Project-TICT-V1GP-15
ec1de58bf3e5f22066f563e0014760e54d779159
[ "MIT" ]
null
null
null
#include <cmath> #include <iostream> #include <unistd.h> #include "./piprograms/BrickPi3.cpp" #include <thread> #include <signal.h> #include <vector> using namespace std; BrickPi3 BP; uint8_t s_contrast = PORT_2; // Light sensor uint8_t m_head = PORT_A; // Head motor uint8_t m_left = PORT_B; // Left motor uint8_t m_right = PORT_C; // Right motor void exit_signal_handler(int signo); //Stop void stop(void){ BP.set_motor_power(m_right, 0); BP.set_motor_power(m_left, 0); } //Drive void dodge(int turn_drive, int degrees, int distance){ //Makes Wall-E turn and drive straight int power =40; if(turn_drive== 0){ BP.set_motor_limits(m_left,35,1200); BP.set_motor_limits(m_right,35,1200); BP.set_motor_position_relative(m_left,degrees*5.95); BP.set_motor_position_relative(m_right,degrees*5.85*-1); }else if(turn_drive==1){ if(distance < 0){ distance *= -1; power *= -1; } BP.set_motor_power(m_left, power); BP.set_motor_power(m_right, power); usleep(76927*distance); stop(); } } int main(){ signal(SIGINT, exit_signal_handler); // register the exit function for Ctrl+C BP.detect(); // Make sure that the BrickPi3 is communicating and that the firmware is compatible with the drivers. BP.set_motor_limits(PORT_B, 60, 0); BP.set_motor_limits(PORT_C, 60, 0); char inp; while(true){ cout << "Press s (stop), d (drive): " << endl; cin >> inp; //Take input from the terminal if (inp=='d'){ //drive or steer, degrees, (rigth positive, left negative), distance int turn_drive = 0; int degrees = 90; int distance =-10; dodge(turn_drive, degrees, distance); }else if (inp=='s'){ stop(); } } return 0; } // Signal handler that will be called when Ctrl+C is pressed to stop the program void exit_signal_handler(int signo){ if(signo == SIGINT){ BP.reset_all(); // Reset everything so there are no run-away motors exit(-2); } }
24.219512
117
0.666163
fdekruijff
02773adfef90ebe52be74848f2315ef64a8c0346
1,822
cpp
C++
algorithms/recursion/twisted_tower_of_hanoi.cpp
adisakshya/dsa
5b40eb339b19cdec95dcfc645516d725f0cb6c74
[ "MIT" ]
null
null
null
algorithms/recursion/twisted_tower_of_hanoi.cpp
adisakshya/dsa
5b40eb339b19cdec95dcfc645516d725f0cb6c74
[ "MIT" ]
null
null
null
algorithms/recursion/twisted_tower_of_hanoi.cpp
adisakshya/dsa
5b40eb339b19cdec95dcfc645516d725f0cb6c74
[ "MIT" ]
null
null
null
/** * Twisted Tower of Hanoi (Recursive) * * Twisted Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. * The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: * 1) Only one disk can be moved at a time. * 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack * i.e. a disk can only be moved if it is the uppermost disk on a stack. * 3) No disk may be placed on top of a smaller disk. * 4) No disk can be moved directly from first rod to last rod * * Complexity * Time: * Worst Case: 3^N * Space: O(N) * */ #include <bits/stdc++.h> using namespace std; // Function to solve Tower of Hanoi void twisted_tower_of_hanoi(int disks, char from_rod, char to_rod, char aux_rod) { // Base condition if(disks == 1) { cout << "Disk 1 moved from " << from_rod << " to " << aux_rod << endl; cout << "Disk 1 moved from " << aux_rod << " to " << to_rod << endl; return; } // shift n-1 disks from from_rod to to_rod twisted_tower_of_hanoi(disks - 1, from_rod, to_rod, aux_rod); cout << "Disk " << disks << " moved from " << from_rod << " to " << aux_rod << endl; // shift n-1 disks from to_rod to from_rod twisted_tower_of_hanoi(disks - 1, to_rod, from_rod, aux_rod); cout << "Disk " << disks << " moved from " << aux_rod << " to " << to_rod << endl; // shift n-1 from from_rod to to_rod twisted_tower_of_hanoi(disks - 1, from_rod, to_rod, aux_rod); } int main() { int number_of_disks = 2; // A, B and C are name of rods twisted_tower_of_hanoi(number_of_disks, 'A', 'C', 'B'); return 0; }
35.72549
117
0.608672
adisakshya
02776f948c5fa197561eef3d5f575f85a41e012e
4,281
cpp
C++
ModuleProgram.cpp
raulgonzalezupc/FirstAssigment
9193de31049922787da966695340253d84439bf3
[ "MIT" ]
null
null
null
ModuleProgram.cpp
raulgonzalezupc/FirstAssigment
9193de31049922787da966695340253d84439bf3
[ "MIT" ]
null
null
null
ModuleProgram.cpp
raulgonzalezupc/FirstAssigment
9193de31049922787da966695340253d84439bf3
[ "MIT" ]
null
null
null
#include "ModuleProgram.h" #include "Application.h" #include "ModuleImgui.h" #include "Globals.h" #include "MathGeoLib/include/Math/float4x4.h" #include "SDL.h" ModuleProgram::ModuleProgram() { } ModuleProgram::~ModuleProgram() { } bool ModuleProgram::Init() { App->imgui->AddLog("\nSHADERS.\n\n"); //init vertex shader vs = createVertexShader(VERTEX_SHADER_PATH); fs = createFragmentShader(FRAGMENT_SHADER_PATH); defaultProgram = CreateProgram(vs, fs); sceneProgram = CreateProgram(vs, fs); //init skybox shader skyboxVertexShader = App->program->createVertexShader("Game/Skybox.vs"); skyboxFragmentShader = App->program->createFragmentShader("Game/Skybox.fs"); skyboxProgram = CreateProgram(skyboxVertexShader, skyboxFragmentShader); //set up the uniforms setUniformsBuffer(); return true; } update_status ModuleProgram::PreUpdate() { return UPDATE_CONTINUE; } update_status ModuleProgram::Update() { return UPDATE_CONTINUE; } update_status ModuleProgram::PostUpdate() { return UPDATE_CONTINUE; } bool ModuleProgram::CleanUp() { App->imgui->AddLog("Deleting vertex shader\n"); glDeleteShader(vertex_shader); App->imgui->AddLog("Deleting fragment shader\n"); glDeleteShader(fragment_shader); return true; } GLuint ModuleProgram::CreateProgram(unsigned int vs, unsigned int fs) { //Creating shader program shader_program = glCreateProgram(); //Attaching vertex shader to shader program glAttachShader(shader_program, vertex_shader); //Attaching fragment shader to shader program glAttachShader(shader_program, fragment_shader); //Linking shader program glLinkProgram(shader_program); GLint statusP = NULL; char charP[512]; glGetProgramiv(shader_program, GL_LINK_STATUS, &statusP); if (!statusP) { glGetProgramInfoLog(shader_program, 512, NULL, charP); App->imgui->AddLog("Program created wrong, code: %s\n", charP); } return shader_program; } const char* ModuleProgram::loadFile(const char* file_name) { char* data = nullptr; FILE* file = nullptr; fopen_s(&file, file_name, "rb"); if (file) { fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); data = (char*)malloc(size + 1); fread(data, 1, size, file); data[size] = 0; fclose(file); } return data; } unsigned int ModuleProgram::createVertexShader(const char * filename) { assert(filename != NULL); const char *vertex_shader_file = loadFile(VERTEX_SHADER_PATH); vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_file, NULL); delete vertex_shader_file; glCompileShader(vertex_shader); GLint statusV = NULL; char charV[512]; glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &statusV); if(!statusV) { glGetShaderInfoLog(vertex_shader, 512, NULL, charV); App->imgui->AddLog("Vertex shader created wrong, code: %s\n", charV); } else { App->imgui->AddLog("Vertex shader created correctly.\n"); } return vertex_shader; } unsigned int ModuleProgram::createFragmentShader(const char * filename) { assert(filename != NULL); const char *fragment_shader_file = loadFile(FRAGMENT_SHADER_PATH); fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_file, NULL); delete fragment_shader_file; glCompileShader(fragment_shader); GLint statusF = NULL; char charF[512]; glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &statusF); if (!statusF) { glGetShaderInfoLog(fragment_shader, 512, NULL, charF); App->imgui->AddLog("Fragment shader created wrong, code: %s\n", charF); } else { App->imgui->AddLog("Fragment shader created correctly.\n"); } return fragment_shader; } void ModuleProgram::setUniformsBuffer() { unsigned int uniformBlockIndexDefault = glGetUniformBlockIndex(defaultProgram, "Matrices"); glUniformBlockBinding(defaultProgram, uniformBlockIndexDefault, 0); unsigned int uniformSkybox = glGetUniformBlockIndex(skyboxProgram, "Skybox"); glUniformBlockBinding(skyboxProgram, uniformSkybox, 0); glGenBuffers(1, &uniformsBuffer); glBindBuffer(GL_UNIFORM_BUFFER, uniformsBuffer); glBufferData(GL_UNIFORM_BUFFER, 2 * sizeof(float4x4), NULL, GL_STATIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glBindBufferRange(GL_UNIFORM_BUFFER, 0, uniformsBuffer, 0, 2 * sizeof(float4x4)); }
24.186441
92
0.759402
raulgonzalezupc
0280219b9443179587297e57704c87cc4b7aa7f2
1,644
cpp
C++
src/algorithm/Algorithm.cpp
oldas1/Riner
492804079eb223e6d4ffd5f5f44283162eaf421b
[ "MIT" ]
null
null
null
src/algorithm/Algorithm.cpp
oldas1/Riner
492804079eb223e6d4ffd5f5f44283162eaf421b
[ "MIT" ]
null
null
null
src/algorithm/Algorithm.cpp
oldas1/Riner
492804079eb223e6d4ffd5f5f44283162eaf421b
[ "MIT" ]
null
null
null
// // #include "Algorithm.h" #include "grin/AlgoCuckatoo31Cl.h" #include "dummy/AlgoDummy.h" #include "ethash/AlgoEthashCL.h" #include <src/compute/DeviceId.h> #include <src/pool/WorkEthash.h> #include <src/pool/WorkCuckoo.h> namespace miner { /** * Register all Algorithm implementations here. * This is necessary so that the compiler includes the necessary code into a library * because only Algorithm is referenced by another compilation unit. */ static const Algorithm::Registry<AlgoCuckatoo31Cl> registryAlgoCuckatoo31Cl {"AlgoCuckatoo31Cl", HasPowTypeCuckatoo<31>::getPowType()}; static const Algorithm::Registry<AlgoDummy> regustryAlgoDummy {"AlgoDummy" , HasPowTypeEthash::getPowType()}; static const Algorithm::Registry<AlgoEthashCL> registryAlgoEthashCL {"AlgoEthashCL", HasPowTypeEthash::getPowType()}; unique_ptr<Algorithm> Algorithm::makeAlgo(AlgoConstructionArgs args, const std::string &implName) { if (auto entry = entryWithName(implName)) { return entry->makeFunc(std::move(args)); } return nullptr; } std::string Algorithm::powTypeForAlgoImplName(const std::string &algoImplName) { if (auto entry = entryWithName(algoImplName)) { return entry->powType; } return ""; //no matching algo type found } optional_ref<Algorithm::Entry> Algorithm::entryWithName(const std::string &algoImplName) { for (auto &entry : getEntries()) { if (entry.algoImplName == algoImplName) { return entry; } } return {}; } }
34.978723
139
0.667275
oldas1
0283b0332e6a4eb780ca44439332565d75e5dd1d
601
cpp
C++
two-sum.cpp
casper001207/leetcode
7b5c9b77078385fe67cb4ad5d0d52f9250cdfa30
[ "MIT" ]
null
null
null
two-sum.cpp
casper001207/leetcode
7b5c9b77078385fe67cb4ad5d0d52f9250cdfa30
[ "MIT" ]
null
null
null
two-sum.cpp
casper001207/leetcode
7b5c9b77078385fe67cb4ad5d0d52f9250cdfa30
[ "MIT" ]
null
null
null
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> v; for ( vector<int>::iterator it = nums.begin(); it != nums.end(); ++it ) { for ( vector<int>::iterator it2 = nums.begin() + distance(nums.begin(), it) + 1; it2 != nums.end(); ++it2 ) { if (*it + *it2 == target) { v.push_back(distance(nums.begin(), it)); v.push_back(distance(nums.begin(), it2)); return v; } } } return v; } };
37.5625
121
0.430948
casper001207