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
a296b35be2337b4352431af89274aefbefe74de7
1,211
cpp
C++
src/SMLMat1x4.cpp
aceoyale/SML
513d60be40f1e2629b4475cfdf1b4913c1a5154a
[ "MIT" ]
1
2020-10-08T09:31:54.000Z
2020-10-08T09:31:54.000Z
src/SMLMat1x4.cpp
aceoyale/SML
513d60be40f1e2629b4475cfdf1b4913c1a5154a
[ "MIT" ]
null
null
null
src/SMLMat1x4.cpp
aceoyale/SML
513d60be40f1e2629b4475cfdf1b4913c1a5154a
[ "MIT" ]
null
null
null
#include "SMLMat1x4.h" #include "SMLMat4x1.h" #include "SMLMat4x4.h" SML::Mat1x4::Mat1x4(const float& A, const float& B, const float& C, const float& D) { a = A; b = B; c = C; d = D; } SML::Mat1x4::Mat1x4(const Vector& v) { a = v.x; b = v.y; c = v.z; } SML::Mat1x4::Mat1x4(const Point& v) { a = v.x; b = v.y; c = v.z; d = 1; } SML::Mat1x4 SML::Mat1x4::operator*(const float& s) const { return Mat1x4(s * a, s * b, s * c, s * d); } SML::Mat1x4 SML::Mat1x4::operator/(const float& s) const { return Mat1x4(a / s, b / s, c / s, d / s); } SML::Mat1x4 SML::Mat1x4::operator+(const Mat1x4& m) const { return Mat1x4(a + m.a, b + m.b, c + m.c, d + m.d); } SML::Mat1x4 SML::Mat1x4::operator-(const Mat1x4& m) const { return Mat1x4(a - m.a, b - m.b, c - m.c, d - m.d); } SML::Mat1x4 SML::Mat1x4::operator*(const Mat4x4& m) const { return Mat1x4 ( (a * m.m[0][0] + b * m.m[1][0] + c * m.m[2][0] + d * m.m[3][0]), (a * m.m[0][1] + b * m.m[1][1] + c * m.m[2][1] + d * m.m[3][1]), (a * m.m[0][2] + b * m.m[1][2] + c * m.m[2][2] + d * m.m[3][2]), (a * m.m[0][3] + b * m.m[1][3] + c * m.m[2][3] + d * m.m[3][3]) ); } SML::Mat4x1 SML::Mat1x4::transpose() const { return Mat4x1(a, b, c, d); }
19.222222
83
0.521883
aceoyale
a29787ec9e004ced64d1d9853a224deb3bed19c7
10,922
hpp
C++
test/gemm/device/mma_sync_multi_lds.hpp
dlangbe/rocWMMA
8dd5c1cd4de202e556e338223e17071daac65987
[ "MIT" ]
null
null
null
test/gemm/device/mma_sync_multi_lds.hpp
dlangbe/rocWMMA
8dd5c1cd4de202e556e338223e17071daac65987
[ "MIT" ]
null
null
null
test/gemm/device/mma_sync_multi_lds.hpp
dlangbe/rocWMMA
8dd5c1cd4de202e556e338223e17071daac65987
[ "MIT" ]
null
null
null
/******************************************************************************* * * MIT License * * Copyright 2021-2022 Advanced Micro Devices, Inc. * * 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. * *******************************************************************************/ #ifndef ROCWMMA_DEVICE_MMA_SYNC_MULTI_LDS_HPP #define ROCWMMA_DEVICE_MMA_SYNC_MULTI_LDS_HPP #include <algorithm> #include <array> #include <utility> // The testing interface instantiates fp64 typed tests for all // target devices. MI-100 mfma needs to be instantiated at compile time, // but it doesn't do anything except provide a deprecation warning (e.g. not supported). // A run-time check will abort the MI-100 fp64 tests anyway. // Silence this warning for MmaSyncTests, as test coverage is needed // for fp64 on all other targets which succeed MI-100. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include "lds_mapping_util.hpp" #include <rocwmma/rocwmma.hpp> #include <rocwmma/rocwmma_coop.hpp> #pragma GCC diagnostic pop namespace rocwmma { template <uint32_t BlockM, uint32_t BlockN, uint32_t BlockK, typename InputT, typename OutputT, typename ComputeT, typename LayoutA, typename LayoutB, typename LayoutC, typename LayoutD, typename LayoutLds, typename GemmConfig, uint32_t BlocksX = 1, uint32_t BlocksY = 1> __global__ void __launch_bounds__(256) mmaSyncMultiLds(uint32_t m, uint32_t n, uint32_t k, InputT const* a, InputT const* b, OutputT const* c, OutputT* d, uint32_t lda, uint32_t ldb, uint32_t ldc, uint32_t ldd, ComputeT alpha, ComputeT beta) { /// /// Assemble the gemm driver from the incoming gemm configuration /// using GlobalMapping = typename GemmConfig::template GlobalMapping<BlockM, BlockN, BlockK, InputT, OutputT, ComputeT, LayoutA, LayoutB, LayoutC, LayoutD, BlocksX, BlocksY>; using LdsMapping = typename GemmConfig::template LdsMapping<GlobalMapping, LayoutLds>; using GemmDriver = typename GemmConfig::template GemmDriver<GlobalMapping, LdsMapping, typename GemmConfig::CoopSchedulerA, typename GemmConfig::CoopSchedulerB>; // Global fragments used in pre-fetching using GRFragA = typename GlobalMapping::GRFragA; using GRFragB = typename GlobalMapping::GRFragB; // Fragments for mfma using MfmaFragA = typename GlobalMapping::MfmaFragA; using MfmaFragB = typename GlobalMapping::MfmaFragB; using MfmaFragC = typename GlobalMapping::MfmaFragC; using MfmaFragD = typename GlobalMapping::MfmaFragD; using MfmaFragAcc = typename GlobalMapping::MfmaFragAcc; // Mapping utils for each fragment type using DataMappingA = typename GetIOShape_t<MfmaFragA>::DataLayout; using DataMappingB = typename GetIOShape_t<MfmaFragB>::DataLayout; using DataMappingC = typename GetIOShape_t<MfmaFragC>::DataLayout; using DataMappingD = typename GetIOShape_t<MfmaFragD>::DataLayout; using DataMappingLds = typename LdsMapping::DataLayout; /// /// Target starting C / D macro tile matrix coordinate on 2D grid /// auto matrixCoordC = GlobalMapping::matrixCoordC(); // Bounds check if((std::get<0>(matrixCoordC) + BlocksX * BlockM) > m || (std::get<1>(matrixCoordC) + BlocksY * BlockN) > n || (BlockK > k)) { return; } /// /// Setup global addressing offsets /// auto globalOffsetA = DataMappingA::fromMatrixCoord(GlobalMapping::matrixCoordA(), lda); auto globalOffsetB = DataMappingB::fromMatrixCoord(GlobalMapping::matrixCoordB(), ldb); auto globalOffsetC = DataMappingC::fromMatrixCoord(matrixCoordC, ldc); auto globalOffsetD = DataMappingD::fromMatrixCoord(matrixCoordC, ldd); auto kStepOffsetA = DataMappingA::fromMatrixCoord(GlobalMapping::kStepA(), lda); auto kStepOffsetB = DataMappingB::fromMatrixCoord(GlobalMapping::kStepB(), ldb); /// /// Start global prefetch /// typename GlobalMapping::GRBuffA grBuffA; typename GlobalMapping::GRBuffB grBuffB; GemmDriver::globalReadCoopA(grBuffA, a + globalOffsetA, lda); GemmDriver::globalReadCoopB(grBuffB, b + globalOffsetB, ldb); globalOffsetA += kStepOffsetA; globalOffsetB += kStepOffsetB; /// /// Setup LDS addressing /// This kernel will use 2 separate LDS blocks /// for pipelining in the accumulation loop /// HIP_DYNAMIC_SHARED(void*, localMemPtr); auto sizeLds = LdsMapping::sizeLds(); auto* ldsPtrLo = reinterpret_cast<InputT*>(localMemPtr); auto* ldsPtrHi = ldsPtrLo + std::get<0>(sizeLds) * std::get<1>(sizeLds); auto ldlds = LdsMapping::ldLds(); auto ldsOffsetA = DataMappingLds::fromMatrixCoord(LdsMapping::matrixCoordA(), ldlds); auto ldsOffsetB = DataMappingLds::fromMatrixCoord(LdsMapping::matrixCoordB(), ldlds); /// /// Write prefetch to local /// GemmDriver::localWriteCoopA(ldsPtrLo + ldsOffsetA, grBuffA, ldlds); GemmDriver::localWriteCoopB(ldsPtrLo + ldsOffsetB, grBuffB, ldlds); /// /// Initialize accumulation frags /// typename GlobalMapping::MfmaBuffAcc fragsAcc; GemmDriver::fill(fragsAcc, static_cast<ComputeT>(0)); /// /// Synchronize waves and memory /// GemmDriver::syncWorkgroup(); /// /// Accumulate A * B /// if(alpha) { for(int currentK = BlockK; currentK < k; currentK += BlockK) { typename GlobalMapping::MfmaBuffA fragsA; typename GlobalMapping::MfmaBuffB fragsB; // Local read mfma frags GemmDriver::localReadA(fragsA, ldsPtrLo + ldsOffsetA, ldlds); GemmDriver::localReadB(fragsB, ldsPtrLo + ldsOffsetB, ldlds); // Start fetching next round of frags GemmDriver::globalReadCoopA(grBuffA, a + globalOffsetA, lda); GemmDriver::globalReadCoopB(grBuffB, b + globalOffsetB, ldb); // Advance offsets to next k step globalOffsetA += kStepOffsetA; globalOffsetB += kStepOffsetB; // accum(A * B) GemmDriver::mfma(fragsAcc, fragsA, fragsB, fragsAcc); GemmDriver::localWriteCoopA(ldsPtrHi + ldsOffsetA, grBuffA, ldlds); GemmDriver::localWriteCoopB(ldsPtrHi + ldsOffsetB, grBuffB, ldlds); // Make sure that all waves have finished reading / writing to lds. GemmDriver::syncWorkgroup(); // Swap Lds buffers auto* tmp = ldsPtrLo; ldsPtrLo = ldsPtrHi; ldsPtrHi = tmp; } } /// /// Start loading C /// typename GlobalMapping::MfmaBuffC fragsC; if(beta) { GemmDriver::globalReadC(fragsC, c + globalOffsetC, ldc); } else { GemmDriver::fill(fragsC, 0); } /// /// Clean up tail A * B /// typename GlobalMapping::MfmaBuffA fragsA; typename GlobalMapping::MfmaBuffB fragsB; GemmDriver::localReadA(fragsA, ldsPtrLo + ldsOffsetA, ldlds); GemmDriver::localReadB(fragsB, ldsPtrLo + ldsOffsetB, ldlds); GemmDriver::mfma(fragsAcc, fragsA, fragsB, fragsAcc); /// /// D = alpha * accum + beta * C /// typename GlobalMapping::MfmaBuffD fragsD; GemmDriver::uniformFma(fragsD, alpha, fragsAcc, beta, fragsC); GemmDriver::globalWriteD(d + globalOffsetD, fragsD, ldd); } } // namespace rocwmma #endif // ROCWMMA_DEVICE_MMA_SYNC_MULTI_LDS_HPP
42.664063
95
0.53113
dlangbe
a297f34621582815afd49a1334691ef4307559b4
751
hpp
C++
inc/rand_source.hpp
jimmycao/libga_mpi
39f223891b1474b1b190a0033576f30723051f17
[ "MIT" ]
1
2020-06-14T08:28:01.000Z
2020-06-14T08:28:01.000Z
inc/rand_source.hpp
jimmycao/libga_mpi
39f223891b1474b1b190a0033576f30723051f17
[ "MIT" ]
null
null
null
inc/rand_source.hpp
jimmycao/libga_mpi
39f223891b1474b1b190a0033576f30723051f17
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // rand_source.hpp //------------------------------------------------------------------------------ #pragma once #include <cassert> #include <type_traits> #include <random> #include <ctime> namespace libga_mpi { namespace detail { template< typename T > class rand_source { public: static_assert(std::is_floating_point< T >::value , "T must be a floating-point element"); using value_type = T; rand_source() { mt_.seed(static_cast<unsigned int>(std::time(nullptr))); } ~rand_source() {} value_type operator () () { return dist_(mt_); } private: std::mt19937 mt_; std::uniform_real_distribution< value_type > dist_; }; } }
19.25641
80
0.527297
jimmycao
a29a8036d696db7977bd698afbf7398d40a98d4a
1,395
cpp
C++
04.MinimumCut/main.cpp
shunjilin/AlgorithmsSpecialization
554996a0ce131139917dd02604ce0660ad6d2c2d
[ "MIT" ]
1
2019-05-08T04:20:58.000Z
2019-05-08T04:20:58.000Z
04.MinimumCut/main.cpp
shunjilin/AlgorithmsSpecialization
554996a0ce131139917dd02604ce0660ad6d2c2d
[ "MIT" ]
null
null
null
04.MinimumCut/main.cpp
shunjilin/AlgorithmsSpecialization
554996a0ce131139917dd02604ce0660ad6d2c2d
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <random> #include <cmath> #include <limits> #include "KargersMinCut.hpp" #include "SteadyClockTimer.hpp" int main(int argc, char *argv[]) { Kargers::Edgelist edge_list; unsigned n_nodes = 0; if (argc > 1) { std::ifstream ifile(argv[1]); if (!ifile) { std::cerr << "Unable to open file: " << argv[1] << std::endl; exit(1); } std::string line; while (std::getline(ifile, line)) { std::istringstream iss(line); int u, v; iss >> u; while (iss >> v) { if (u < v) edge_list.emplace_back(u-1, v-1); } ++n_nodes; } } else { std::cerr << "No input given!" << std::endl; exit(1); } std::random_device rd; std::mt19937 gen = std::mt19937(rd()); unsigned n_trials = pow(n_nodes, 2) * log(n_nodes); unsigned min_edges = std::numeric_limits<unsigned>::max(); for (unsigned i = 0; i < n_trials; ++i) { auto edges = Kargers:: getEdgeCountFromRandomContract(n_nodes, edge_list, gen); if (edges < min_edges) { min_edges = edges; std::cout << "Smallest # edges in cut so far: " << min_edges << "\n"; } } }
27.9
73
0.510394
shunjilin
a29a8ff45ace148b29571e145d144309dd91bcc6
207
hpp
C++
projects/codility/min_avg_two_slice/include/MinAvgTwoSlice.hpp
antaljanosbenjamin/miscellaneous
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
[ "MIT" ]
2
2021-06-24T21:46:56.000Z
2021-09-24T07:51:04.000Z
projects/codility/min_avg_two_slice/include/MinAvgTwoSlice.hpp
antaljanosbenjamin/miscellaneous
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
[ "MIT" ]
null
null
null
projects/codility/min_avg_two_slice/include/MinAvgTwoSlice.hpp
antaljanosbenjamin/miscellaneous
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
[ "MIT" ]
null
null
null
#pragma once #include <vector> namespace MinAvgTwoSlice { // https://app.codility.com/programmers/lessons/5-prefix_sums/min_avg_two_slice/ int solution(std::vector<int> &A); } // namespace MinAvgTwoSlice
20.7
80
0.768116
antaljanosbenjamin
94704ab3c83cf4f5bbeae0ff067feb7ffc04163d
239
cpp
C++
tests/test_point.cpp
a20r/Dodger
6e2525f4701031d4e946fcd04c508655fa67c8ea
[ "Apache-2.0" ]
1
2021-11-30T11:19:56.000Z
2021-11-30T11:19:56.000Z
tests/test_point.cpp
a20r/Dodger
6e2525f4701031d4e946fcd04c508655fa67c8ea
[ "Apache-2.0" ]
null
null
null
tests/test_point.cpp
a20r/Dodger
6e2525f4701031d4e946fcd04c508655fa67c8ea
[ "Apache-2.0" ]
null
null
null
#include "point.hpp" #include <iostream> int main() { Dodger::Point p1 = Dodger::Point::get_random_point_2d(5, 5); Dodger::Point p2 = Dodger::Point::get_random_point_2d(5, 5); std::cout << p1.euclid_dist(p2); return 0; }
21.727273
64
0.65272
a20r
94755399e711e0cf86cb40caf8a22492dd6ae8d6
9,279
cpp
C++
projects/abuild/cache/cache_impl.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
projects/abuild/cache/cache_impl.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
projects/abuild/cache/cache_impl.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
#ifndef __clang__ export module abuild.cache:cache_impl; export import :cache_data; import :cache_index; #endif namespace abuild { export class CacheImpl; //! \private auto read_cache(const std::filesystem::path &path, CacheImpl &cache) -> void; //! \private auto write_cache(const CacheData &data) -> void; //! The CacheImpl class stores all the build //! information. //! //! The Cache indexes all of its content for //! querying. It is constructed with a path to the //! cache file and uses YAML format. If the path //! exists the cache is populated by the data from //! the file. Upon destruction the cache data are //! written back to the file. //! //! When loaded from a cache file all non-existent //! files are skipped. export class CacheImpl { public: //! Constructs the `Cache` with file `path`. //! If the `path` exists it will read the data //! from it and populate the cache and build //! all the indexes. explicit CacheImpl(std::filesystem::path path) : data{.filePath = std::move(path)} { if (std::filesystem::exists(this->data.filePath)) { ::abuild::read_cache(this->data.filePath, *this); } } //! Deleted copy constructor. CacheImpl(const CacheImpl &other) = delete; //! Move constructor. CacheImpl(CacheImpl &&other) noexcept = default; //! Destructs the Cache and writes its data to //! the file passed in the constructor. ~CacheImpl() { try { ::abuild::write_cache(this->data); } catch (...) { } } //! Returns the list of flags to be passed to all //! archiver calls. [[nodiscard]] auto archiver_flags() const noexcept -> const std::vector<Flag> & { return this->data.archiverFlags; } //! Returns the list of flags to be passed to //! all compiler calls. [[nodiscard]] auto compiler_flags() const noexcept -> const std::vector<Flag> & { return this->data.compilerFlags; } //! Returns the configuration name. [[nodiscard]] auto configuration_name() const noexcept -> const std::string & { return this->data.configurationName; } //! Returns the list of flags to be passed to //! every linker call. [[nodiscard]] auto linker_flags() const noexcept -> const std::vector<Flag> & { return this->data.linkerFlags; } //! Returns the list of defines. [[nodiscard]] auto defines() const noexcept -> const std::vector<DefineToken> & { return this->data.defines; } //! Adds header `file` to the Cache. auto add_header_file(const std::filesystem::path &path) -> HeaderFile * { HeaderFile *file = this->data.headers.emplace_back(std::make_unique<HeaderFile>()).get(); file->path = path; this->index.insert(file); return file; } //! Adds header unit `file` to the Cache. auto add_header_unit(HeaderFile *file) -> HeaderUnit * { HeaderUnit *unit = this->data.headerUnits.emplace_back(std::make_unique<HeaderUnit>()).get(); unit->headerFile = file; this->index.insert(unit); return unit; } //! Adds module `name` to the Cache. auto add_module(const std::string &name) -> Module * { Module *mod = this->data.modules.emplace_back(std::make_unique<Module>()).get(); mod->name = name; this->index.insert(mod); return mod; } //! Adds module partition `name` to the cache. //! Note that you should associate it with a //! module. auto add_module_partition(const std::string &name) -> ModulePartition * { ModulePartition *partition = this->data.modulePartitions.emplace_back(std::make_unique<ModulePartition>()).get(); partition->name = name; return partition; } //! Adds project `name` to the cache. auto add_project(std::string name) -> Project * { Project *proj = this->data.projects.emplace_back(std::make_unique<Project>()).get(); proj->name = std::move(name); this->index.insert(proj); return proj; } //! Adds source `file` to the Cache. auto add_source_file(std::filesystem::path path) -> SourceFile * { SourceFile *file = this->data.sources.emplace_back(std::make_unique<SourceFile>()).get(); file->path = std::move(path); this->index.insert(file); return file; } //! Returns path directory of the cache file. [[nodiscard]] auto build_root() const -> std::filesystem::path { return this->data.filePath.parent_path(); } //! Finds the header with the exact `path` and //! returns it or `nullptr` if not found. [[nodiscard]] auto exact_header_file(const std::filesystem::path &path) const -> HeaderFile * { return this->index.exact_header_file(path); } //! Finds the source with the exact `path` and //! returns it or `nullptr` if not found. [[nodiscard]] auto exact_source_file(const std::filesystem::path &path) const -> SourceFile * { return this->index.exact_source_file(path); } //! Finds the first header matching the `path` //! such that the `path` is a subpath of the //! matched file. E.g. searching for //! `include/my_header.hpp` could match //! `project1/include/my_header.hpp`, //! `project2/include/my_header.hpp` etc. If //! there are multiple matching files their //! order is unspecified. If no file is //! matched returns `nullptr`. [[nodiscard]] auto header_file(const std::filesystem::path &path) const -> HeaderFile * { return this->index.header_file(path); } //! Finds the header unit associated with the //! `file` or `nullptr` if not found. [[nodiscard]] auto header_unit(HeaderFile *file) const -> HeaderUnit * { return this->index.header_unit(file); } //! Finds the module `name` or `nullptr` if //! not found. [[nodiscard]] auto module_(const std::string &name) const -> Module * // NOLINT(readability-identifier-naming) { return this->index.module_(name); } //! Find the project with `name`. If no such //! project is found returns `nullptr`. [[nodiscard]] auto project(const std::string &name) const -> Project * { return this->index.project(name); } //! Returns the source (project) directory //! root. [[nodiscard]] auto project_root() const noexcept -> const std::filesystem::path & { return this->data.projectRoot; } //! Returns the list of projects. [[nodiscard]] auto projects() const noexcept -> const std::vector<std::unique_ptr<Project>> & { return this->data.projects; } //! Returns the internal read-only Settings //! struct. [[nodiscard]] auto settings() const noexcept -> const Settings & { return this->data.settings; } //! Sets the flags to be passed to the //! archiver calls. auto set_archiver_flags(std::vector<Flag> flags) noexcept -> void { this->data.archiverFlags = std::move(flags); } //! Returns the configuration name. auto set_configuration_name(const std::string &name) -> void { this->data.configurationName = name; } //! Sets the defines. auto set_defines(std::vector<DefineToken> values) noexcept -> void { this->data.defines = std::move(values); } //! Sets the flags to be passed to the //! compiler calls. auto set_compiler_flags(std::vector<Flag> flags) noexcept -> void { this->data.compilerFlags = std::move(flags); } //! Sets the flags to be passed to the linker //! calls. auto set_linker_flags(std::vector<Flag> flags) noexcept -> void { this->data.linkerFlags = std::move(flags); } //! Sets the source (project) root. auto set_project_root(std::filesystem::path path) noexcept -> void { this->data.projectRoot = std::move(path); } //! Sets the settings. auto set_settings(Settings settings) -> void { this->data.settings = std::move(settings); } //! Sets the toolchain. auto set_toolchain(Toolchain toolchain) -> void { this->data.toolchain = std::move(toolchain); } //! Returns the toolchain. [[nodiscard]] auto toolchain() const noexcept -> const Toolchain & { return this->data.toolchain; } //! Finds the first source matching the `path` //! such that the `path` is a subpath of the //! matched file. E.g. searching for //! `main.cpp` could match //! `project1/main.cpp`, `project2/main.cpp` //! etc. If there are multiple matching files //! their order is unspecified. If no file is //! matched returns `nullptr`. [[nodiscard]] auto source_file(const std::filesystem::path &path) const -> SourceFile * { return this->index.source_file(path); } //! Deleted copy assignment. auto operator=(const CacheImpl &other) -> CacheImpl & = delete; //! Move assignment. auto operator=(CacheImpl &&other) noexcept -> CacheImpl & = default; private: CacheData data; CacheIndex index; }; }
30.323529
121
0.621942
agnesoft
94783a178f5c202c66619b636e25d0b7a814158e
7,377
cpp
C++
landmass/src/Render.cpp
DATX02-16-86/Code
70cf4537cf30633a3ab538d3bf0df1d374c88860
[ "MIT" ]
1
2016-05-01T22:54:25.000Z
2016-05-01T22:54:25.000Z
landmass/src/Render.cpp
DATX02-16-86/Code
70cf4537cf30633a3ab538d3bf0df1d374c88860
[ "MIT" ]
10
2016-01-26T10:39:45.000Z
2016-02-29T13:34:21.000Z
landmass/src/Render.cpp
DATX02-16-86/Code
70cf4537cf30633a3ab538d3bf0df1d374c88860
[ "MIT" ]
null
null
null
#include <GLUT/glut.h> #include <iostream> #include "Voronoi.h" #include "../../noise/Simplex/simplex.h" #include "Generate.h" ChunkMap hexChunks; void color(double clr) { glColor3d(clr, clr, clr); } void render() { glClear(GL_COLOR_BUFFER_BIT); std::cout << "render cells!\n"; for (auto& kv : hexChunks) { auto& chunk = kv.second; if (!(chunk.state == ChunkState::BIOMES)) { continue; } std::cout << "render " << chunk.x << ", " << chunk.y << "\n"; for (size_t i = 0; i < chunk.cellmetas.size(); ++i) { glBegin(GL_POLYGON); auto meta = chunk.cellmetas[i]; double avarageHeight = meta.avarageheight; double avarageMoisture = meta.avarageMoisture; if (meta.biome == Biome::lake) { glColor3f(40.f / 255.f, 120.f / 255.f, 0.8f); } else if (meta.biome == Biome::sea) { glColor3f(35.f / 255.f, 115.f / 255.f, 0.5); }/* else if (meta.biome == Biome::beach) { glColor3f(246.f / 255.f, 223.f / 255.f, 179.f / 255.f); } else if (avarageHeight < 0.5 && avarageMoisture < 0.4) { glColor3d(210 / 255.f, 180 / 255.f, 140 / 255.f); } else if (avarageHeight < 0.5) { glColor3f(44.f / 255.f, 104.f / 255.f, 3.f / 255.f); } else if (avarageHeight < 0.6) { glColor3f(53.f / 255.f, 114.f / 255.f, 13.f / 255.f); } else if (avarageHeight < 0.7) { glColor3f(70.f / 255.f, 138.f / 255.f, 13.f / 255.f); } else if (avarageHeight < 0.8) { glColor3f(80.f / 255.f, 166.f / 255.f, 21.f / 255.f); } else if (avarageHeight < 0.9) { glColor3f(94.f / 255.f, 181.f / 255.f, 30.f / 255.f); }*/ else { color(avarageMoisture); } const auto& edgeIndexes = chunk.cellEdges[i]; size_t edgeCount = edgeIndexes.size(); // Vertex old; // ChunkWithIndexes* oldC; // Probably unneccessary check if (edgeCount < 2) { continue; } for (int j = 0; j < edgeCount; ++j) { const auto& ei = edgeIndexes[j]; const auto& edgeChunk = findChunkWithChunkIndex(hexChunks, chunk, ei.chunkIndex); const auto& edge = edgeChunk.edges[ei.index]; const auto& nexti = edgeIndexes[(j + 1) % edgeCount]; const auto& nextChunk = findChunkWithChunkIndex(hexChunks, chunk, nexti.chunkIndex); const auto& next = nextChunk.edges[nexti.index]; VertexIndex ind = sharedVertexIndex(edge, next, chunkIndex(edgeChunk, nextChunk)); Vertex vertex = findChunkWithChunkIndex(hexChunks, edgeChunk, ind.chunkIndex).vertices[ind.index]; glVertex2d(vertex.x, vertex.y); } glEnd(); } } std::cout << "cells done!\n"; std::cout << "render lines around cells!\n"; // Lines around cells for (auto& kv : hexChunks) { auto& chunk = kv.second; if (!(chunk.state >= ChunkState::RIVERS)) { continue; } for (size_t i = 0; i < chunk.edges.size(); ++i) { auto edgemeta = chunk.edgemetas[i]; if (edgemeta.isRiver) { std::cout << "River!"; glLineWidth(2); glColor3f(60.f / 255.f, 140.f / 255.f, 1); } else { glLineWidth(1); glColor3f(180.f / 255.f, 60.f / 255.f, 50.f / 255.f); } glBegin(GL_LINES); auto edge = chunk.edges[i]; Vertex a = getVertex(hexChunks, chunk, edge.a); Vertex b = getVertex(hexChunks, chunk, edge.b); glVertex2d(a.x, a.y); glVertex2d(b.x, b.y); glEnd(); } } std::cout << "lines around cells done!\n"; std::cout << "render water points!\n"; for (auto& kv : hexChunks) { auto& chunk = kv.second; if (!(chunk.state >= ChunkState::RIVERS)) { continue; } glPointSize(5.0f); glBegin(GL_POINTS); color(1); for (size_t i = 0; i < chunk.vertices.size(); ++i) { auto meta = chunk.vertexmetas[i]; auto vertex = chunk.vertices[i]; if (meta.wt == WaterType::lake) { glColor3f(0.f / 255.f, 255.f / 255.f, 255.f / 255.f); glVertex2d(vertex.x, vertex.y); } if (meta.wt == WaterType::river) { glColor3f(255.f / 255.f, 0.f / 255.f, 255.f / 255.f); glVertex2d(vertex.x, vertex.y); } } glEnd(); } std::cout << "water points done!\n"; std::cout << "render boxes!\n"; for (auto& kv : hexChunks) { auto& chunk = kv.second; if (!(chunk.state >= ChunkState::RIVERS)) { continue; } glLineWidth(2); glColor3f(255.f / 255.f, 0.f / 255.f, 0.f / 255.f); glBegin(GL_LINES); glVertex2d(chunk.x * CHUNK_SIZE, chunk.y * CHUNK_SIZE); glVertex2d((chunk.x + 1) * CHUNK_SIZE, chunk.y * CHUNK_SIZE); glVertex2d((chunk.x + 1) * CHUNK_SIZE, chunk.y * CHUNK_SIZE); glVertex2d((chunk.x + 1) * CHUNK_SIZE, (chunk.y + 1) * CHUNK_SIZE); glVertex2d((chunk.x + 1) * CHUNK_SIZE, (chunk.y + 1) * CHUNK_SIZE); glVertex2d(chunk.x * CHUNK_SIZE, (chunk.y + 1) * CHUNK_SIZE); glVertex2d(chunk.x * CHUNK_SIZE, (chunk.y + 1) * CHUNK_SIZE); glVertex2d(chunk.x * CHUNK_SIZE, chunk.y * CHUNK_SIZE); glEnd(); } std::cout << "flush!\n"; glFlush(); } int main(int argc, char* argv[]) { // Min/max chunks that are drawable int minX = -1; int maxX = 3; int minY = -1; int maxY = 3; NoiseContext a(120); // Create chunks // Chunks used for padding in voronoi are added as well for (int x = minX - 4; x <= maxX + 4; ++x) { for (int y = minY - 4; y <= maxY + 4; ++y) { ChunkWithIndexes chunk{ x, y }; std::pair<int, int> pos{ x, y }; hexChunks.insert({ pos, std::move(chunk) }); } } for (auto& kv : hexChunks) { auto& chunk = kv.second; if (chunk.x >= minX && chunk.x <= maxX && chunk.y >= minY && chunk.y <= maxY) { addMoisture(hexChunks, chunk); } } for (auto& kv : hexChunks) { auto& chunk = kv.second; if (chunk.x >= minX && chunk.x <= maxX && chunk.y >= minY && chunk.y <= maxY) { addBiomes(hexChunks, chunk); } } int width = 1600, height = 800; glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE); glutInitWindowSize(width, height); glutInitWindowPosition(100, 100); glutCreateWindow("Compelling Landscape"); glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, width, height, 0, 1, -1); glMatrixMode(GL_MODELVIEW); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glShadeModel(GL_SMOOTH); glLoadIdentity(); glutDisplayFunc(render); glutMainLoop(); return 0; }
30.7375
114
0.516335
DATX02-16-86
94857c70d11429b50807f78b330c01aa5153c1a4
2,903
hpp
C++
app/signal_current_candle_trigger/include/offcenter/trading/signalcurrentcandletrigger/SignalCurrentCandleTriggerOptions.hpp
CodeRancher/offcenter_trading
68526fdc0f27d611f748b2fa20f49e743d3ee5eb
[ "Apache-2.0" ]
null
null
null
app/signal_current_candle_trigger/include/offcenter/trading/signalcurrentcandletrigger/SignalCurrentCandleTriggerOptions.hpp
CodeRancher/offcenter_trading
68526fdc0f27d611f748b2fa20f49e743d3ee5eb
[ "Apache-2.0" ]
4
2021-12-27T17:56:21.000Z
2022-01-05T00:05:01.000Z
app/signal_current_candle_trigger/include/offcenter/trading/signalcurrentcandletrigger/SignalCurrentCandleTriggerOptions.hpp
CodeRancher/offcenter_trading
68526fdc0f27d611f748b2fa20f49e743d3ee5eb
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Scott Brauer * * 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 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 SignalCurrentCandleTriggerOptions.hpp * @author Scott Brauer * @date 10-24-2021 */ #ifndef OFFCENTER_TRADING_SIGNALCURRENTCANDLETRIGGER_SIGNALCURRENTCANDLETRIGGEROPTIONS__H_ #define OFFCENTER_TRADING_SIGNALCURRENTCANDLETRIGGER_SIGNALCURRENTCANDLETRIGGEROPTIONS__H_ #include <string> #include <vector> #include "../../../../../../lib/data_types/include/offcenter/trading/datatypes/common/ForexDateTime.hpp" namespace offcenter { namespace trading { namespace signalcurrentcandletrigger { class SignalCurrentCandleTriggerOptions { public: explicit SignalCurrentCandleTriggerOptions(): m_accessToken(""), m_userAccount(""), m_fxtrade(false), m_instrument(), m_granularity(), m_startTime(), m_endTime() {} virtual ~SignalCurrentCandleTriggerOptions() {} const std::string accessToken() const { return m_accessToken; } const std::string userAccount() const { return m_userAccount; } bool fxtrade() const { return m_fxtrade; } const std::string instrument() const { return m_instrument; } const std::string granularity() const { return m_granularity; } offcenter::common::UTCDateTime startTime() const { return m_startTime; } const std::string startTimeAsString() const { return offcenter::common::UTCDateTimeToISO8601(m_startTime); } offcenter::common::UTCDateTime endTime() const { return m_endTime; } const std::string endTimeAsString() const { return offcenter::common::UTCDateTimeToISO8601(m_endTime); } const std::string broker() const { return "oanda"; } const std::string brokerServer() const { return m_fxtrade ? "fxtrade" : "fxpractice"; } void setStart(const std::string value) { m_startTime = offcenter::common::make_UTCDateTimeFromISO8601(value); } void setEnd(const std::string value) { m_endTime = offcenter::common::make_UTCDateTimeFromISO8601(value); } friend class SignalCurrentCandleTriggerProgramOptions; private: std::string m_accessToken; std::string m_userAccount; bool m_fxtrade; std::string m_instrument; std::string m_granularity; offcenter::common::UTCDateTime m_startTime; offcenter::common::UTCDateTime m_endTime; }; } /* namespace signalcurrentcandletrigger */ } /* namespace trading */ } /* namespace offcenter */ #endif /* OFFCENTER_TRADING_SIGNALCURRENTCANDLETRIGGER_SIGNALCURRENTCANDLETRIGGEROPTIONS__H_ */
33.367816
109
0.766793
CodeRancher
9487378dfe3d61009dac8db974a6b78dcce1529b
2,469
cpp
C++
test/training_data/plag_original_codes/arc093_b_12283183_536_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
13
2021-01-20T19:53:16.000Z
2021-11-14T16:30:32.000Z
test/training_data/plag_original_codes/arc093_b_12283183_536_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
test/training_data/plag_original_codes/arc093_b_12283183_536_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
/* 引用元:https://atcoder.jp/contests/arc093/tasks/arc093_b D - Grid ComponentsEditorial // ソースコードの引用元 : https://atcoder.jp/contests/arc093/submissions/12283183 // 提出ID : 12283183 // 問題ID : arc093_b // コンテストID : arc093 // ユーザID : xryuseix // コード長 : 2967 // 実行時間 : 2 */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <cfloat> #include <climits> #include <cmath> #include <cstdio> #include <iomanip> #include <iostream> #include <list> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <unordered_set> #include <vector> #pragma GCC optimize("Ofast") using namespace std; typedef long double ld; typedef long long int ll; typedef unsigned long long int ull; typedef vector<int> vi; typedef vector<char> vc; typedef vector<bool> vb; typedef vector<double> vd; typedef vector<string> vs; typedef vector<ll> vll; typedef vector<pair<int, int>> vpii; typedef vector<pair<ll, ll>> vpll; typedef vector<vector<int>> vvi; typedef vector<vector<char>> vvc; typedef vector<vector<string>> vvs; typedef vector<vector<ll>> vvll; typedef map<int, int> mii; typedef set<int> si; #define rep(i, n) for (int i = 0; i < (n); ++i) #define rrep(i, n) for (int i = 1; i <= (n); ++i) #define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++) #define drep(i, n) for (int i = (n)-1; i >= 0; --i) #define fin(ans) cout << (ans) << '\n' #define STLL(s) strtoll(s.c_str(), NULL, 10) #define mp(p, q) make_pair(p, q) #define pb(n) push_back(n) const int INF = INT_MAX; const ll LLINF = 1LL << 60; const ll MOD = 1000000007; const double EPS = 1e-9; int main() { int a, b; cin >> a >> b; a--; b--; vvc v(100, vc(100, '#')); rep(i, 100) { rep(j, 50) { v[i][j] = '.'; } } for (int i = 0; i < 101 - 1; i += 1 + 1) { for (int j = 0; j < 50 - 1 + 1; j += 1 + 1) { if (b > 0) { v[i][j] = '#'; b--; } } } for (int i = 0; i < 99 + 1; i += 2) { for (int j = 100 - 1; j > 50 + 0; j -= 1 + 1) { if (a > 0) { v[i][j] = '.'; a--; } } } cout << "100 100" << endl; rep(i, 100 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0) { rep(j, 100 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 - 0) cout << v[i][j]; cout << endl; } }
24.69
80
0.536655
xryuseix
9487cb7830fa96662a96efade4191446a51a794d
1,371
cpp
C++
src/functions/functionreplace.cpp
IngwiePhoenix/IceTea_old
8a49b7c77bde123da2f4bae830362b0e791f03f4
[ "BSD-3-Clause" ]
1
2015-01-16T05:00:53.000Z
2015-01-16T05:00:53.000Z
src/functions/functionreplace.cpp
IngwiePhoenix/IceTea_old
8a49b7c77bde123da2f4bae830362b0e791f03f4
[ "BSD-3-Clause" ]
null
null
null
src/functions/functionreplace.cpp
IngwiePhoenix/IceTea_old
8a49b7c77bde123da2f4bae830362b0e791f03f4
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2007-2014 Xagasoft, All rights reserved. * * This file is part of the Xagasoft Build and is released under the * terms of the license contained in the file LICENSE. */ #include "functionreplace.h" #include <bu/plugger.h> PluginInterface3( pluginFunctionReplace, replace, FunctionReplace, Function, "Mike Buland", 0, 1 ); FunctionReplace::FunctionReplace() { } FunctionReplace::~FunctionReplace() { } Bu::String FunctionReplace::getName() const { return "replace"; } Variable FunctionReplace::call( Variable &input, VarList lParams ) { Bu::String sA, sB; sA = lParams.first().getString(); sB = lParams.last().getString(); switch( input.getType() ) { case Variable::typeString: { Variable vOut( input.getString().replace( sA, sB ) ); return vOut; } break; case Variable::typeList: { Variable vOut( Variable::typeList ); for( VarList::iterator i = input.begin(); i; i++ ) { vOut.append( (*i).getString().replace( sA, sB ) ); } return vOut; } break; default: break; } throw Bu::ExceptionBase( "replace does not work on non-string or non-list types."); }
23.237288
76
0.560175
IngwiePhoenix
94885731deaa372f39e71c178678f7b8bc153374
11,775
cpp
C++
implementation/cpl_guisystem/cpl_controller/cpl_controllermanager.cpp
cayprogram/cpl_main
9cc8f4c8cf33465506bdb18ddc84340992b16494
[ "MIT" ]
null
null
null
implementation/cpl_guisystem/cpl_controller/cpl_controllermanager.cpp
cayprogram/cpl_main
9cc8f4c8cf33465506bdb18ddc84340992b16494
[ "MIT" ]
null
null
null
implementation/cpl_guisystem/cpl_controller/cpl_controllermanager.cpp
cayprogram/cpl_main
9cc8f4c8cf33465506bdb18ddc84340992b16494
[ "MIT" ]
null
null
null
#include "cpl_controllerframeincludes.h" //local includes. #include <cpl_guiengine/cpl_guiengineframe/cpl_guiengineframeincludes.h> #include "cpl_controller_items/cpl_scriptproxy.h" #include "cpl_controller_items/cpl_plugintreeproxy.h" #include "cpl_controller_items/cpl_fileioproxy.h" #include "cpl_controller_items/cpl_multifileioproxy.h" #include "cpl_controller_items/cpl_luaproxy.h" #include "cpl_controller_items/cpl_sessionproxy.h" #include "cpl_controller_items/cpl_iconproxy.h" #include "cpl_controller_items/cpl_imageproxy.h" //script.. //local includes. #include <lua.hpp> #include <lunar.h> #include "cpl_controllermanagerluawrapper.h" //----------------------------------------------------------------------------- // class cpl_ControllerManager //----------------------------------------------------------------------------- // cpl_ControllerManager * cpl_ControllerManager::New() { return cpl_ControllerObjectFactory::Instance()->CreateControlManager(); } //----------------------------------------------------------------------------- void cpl_ControllerManager::LoadServices() { //initialize controllers cpl_ScriptProxy* scriptHandler = cpl_ScriptProxy::New(); scriptHandler->SetControllerManager(this); scriptHandler->DoInitialization(); this->InsertNextItem(scriptHandler); this->pControllerScript = scriptHandler; //initialize LUA proxy cpl_LuaProxy* luaProxy = cpl_LuaProxy::New(); luaProxy->SetControllerManager(this); luaProxy->DoInitialization(); this->InsertNextItem(luaProxy); this->pControllerLuaScript = luaProxy; this->pControllerLuaScript->CreateScriptContext(); //register lib this->RegisterScriptLib(); //initialize plugin tree proxy cpl_PluginTreeProxy* pluginTreeHandler = cpl_PluginTreeProxy::New(); pluginTreeHandler->SetControllerManager(this); pluginTreeHandler->DoInitialization(); pluginTreeHandler->Parse("plugins"); pluginTreeHandler->SetLuaState(luaProxy->GetMainLuaState()); pluginTreeHandler->LoadLuaScriptPackage(); pluginTreeHandler->LoadLuaRuntimePackage(); this->InsertNextItem(pluginTreeHandler); this->pControllerPluginTree = pluginTreeHandler; //initial session proxy cpl_SessionProxy* sessionHandler = cpl_SessionProxy::New(); assert(sessionHandler != NULL); sessionHandler->DoInitialization(); this->InsertNextItem(sessionHandler); this->pControllerSession = sessionHandler; //initialize image proxy cpl_ImageProxy* imageHandler = cpl_ImageProxy::New(); assert(imageHandler != NULL); imageHandler->DoInitialization(); imageHandler->SetPluginTreeProxy(this->pControllerPluginTree); imageHandler->SetLuaScriptProxy(this->pControllerLuaScript); imageHandler->LoadPluginImages(); this->InsertNextItem(imageHandler); this->pControllerImage = imageHandler; //initialize icon proxy cpl_IconProxy* iconHandler = cpl_IconProxy::New(); assert(iconHandler != NULL); iconHandler->DoInitialization(); iconHandler->SetPluginTreeProxy(this->pControllerPluginTree); iconHandler->SetLuaScriptProxy(this->pControllerLuaScript); iconHandler->LoadPluginIcons(); this->InsertNextItem(iconHandler); this->pControllerIcon = iconHandler; //register lua script. lua_State* _pVM = (lua_State*)luaProxy->GetMainLuaState(); Lunar<cpl_ControllerManagerLuaWrapper>::Register(_pVM); this->luaWrapper = new cpl_ControllerManagerLuaWrapper(NULL); this->luaWrapper->DoInitialization(this); int userdata_index = Lunar<cpl_ControllerManagerLuaWrapper>::push(_pVM, this->luaWrapper); lua_pushliteral(_pVM, "cpl_app"); lua_pushvalue(_pVM, userdata_index); lua_settable(_pVM, LUA_GLOBALSINDEX); } //----------------------------------------------------------------------------- void cpl_ControllerManager::DoInitialization(int argc, char ** argv) { //@@preconditions assert(this->pControllerScript != NULL); assert(this->pControllerPluginTree != NULL); assert(this->pControllerIcon != NULL); assert(this->pControllerImage != NULL); //@@end preconditions //initialize GUI engine. this->mainGUIEngine = cpl_GUIEngine::New(); this->mainGUIEngine->SetControllerManager(this); this->mainGUIEngine->SetMainScripHandler(this->pControllerScript->GetScriptHandler()); this->mainGUIEngine->SetMainPluginTree(this->pControllerPluginTree->GetPluginTree()); this->mainGUIEngine->SetMainImageProxy(this->pControllerImage->GetImageProxy()); this->mainGUIEngine->SetMainIconProxy(this->pControllerIcon->GetIconProxy()); this->mainGUIEngine->Initialize(argc, argv); this->mainGUIEngine->ShowMainWindow(true); //load gui proxy. cpl_FileIOController* pFileIOProxy = cpl_FileIOController::New(); pFileIOProxy->SetControllerManager(this); pFileIOProxy->DoInitialization(); this->InsertNextItem(pFileIOProxy); this->pControllerFileIO = pFileIOProxy; cpl_MultiFileIOController* pMultiFileIOProxy = cpl_MultiFileIOController::New(); pMultiFileIOProxy->SetControllerManager(this); pMultiFileIOProxy->DoInitialization(); this->InsertNextItem(pMultiFileIOProxy); this->pControllerMultiFileIO = pMultiFileIOProxy; } //----------------------------------------------------------------------------- void cpl_ControllerManager::DoCleanup() { //@@preconditions assert(this->mainGUIEngine != NULL); //@@end preconditions //release resource for main gui engine this->mainGUIEngine->Cleanup(); //cleanup. if (this->luaWrapper != NULL) { this->luaWrapper->DoCleanup(); delete this->luaWrapper; this->luaWrapper = NULL; } //call superclass. cpl_ControllerSet::DoCleanup(); cpl_ObjectFactory::DeInit(); } //----------------------------------------------------------------------------- void cpl_ControllerManager::EnterEventLoop() { //@@preconditions assert(this->mainGUIEngine != NULL); //@@end preconditions this->mainGUIEngine->EnterMainLoop(); } //----------------------------------------------------------------------------- void cpl_ControllerManager::SetBreakFlagOn() { //@@preconditions assert(this->mainGUIEngine != NULL); //@@end preconditions this->mainGUIEngine->SetBreakFlagOn(); } //----------------------------------------------------------------------------- cpl_GUIEngine* cpl_ControllerManager::GetGUIEngine() { //@@preconditions assert(this->mainGUIEngine != NULL); //@@end preconditions return this->mainGUIEngine; } //----------------------------------------------------------------------------- int cpl_ControllerManager::RegisterInterfaces(char* path_name, char* name, void* data) { //@@preconditions assert(path_name != NULL); assert(name != NULL); assert(this->pControllerPluginTree != NULL); //@@end preconditions IPluginTree* pluginTree = this->pControllerPluginTree->GetPluginTree(); assert(pluginTree != NULL); IPluginTreePath* path = pluginTree->GetTreePath(path_name); if (path == NULL) { path = pluginTree->CreateTreePath(path_name); } assert(path != NULL); path->SetUserData(data); return 0; } //----------------------------------------------------------------------------- void* cpl_ControllerManager::GetPluginTree() { //@@preconditions assert(this->pControllerPluginTree != NULL); //@@end preconditions return this->pControllerPluginTree->GetPluginTree(); } //----------------------------------------------------------------------------- void* cpl_ControllerManager::GetFileIOHandler() { //@@preconditions assert(this->pControllerFileIO != NULL); //@@end preconditions return this->pControllerFileIO->GetImplementation(); } //----------------------------------------------------------------------------- void* cpl_ControllerManager::GetMultiFileIOHandler() { //@@preconditions assert(this->pControllerMultiFileIO != NULL); //@@end preconditions return this->pControllerMultiFileIO->GetImplementation(); } //----------------------------------------------------------------------------- void* cpl_ControllerManager::GetLuaScript() { //@@preconditions assert(this->pControllerLuaScript != NULL); //@@end preconditions return this->pControllerLuaScript->GetImplementation(); } //----------------------------------------------------------------------------- void* cpl_ControllerManager::GetSessionProxy() { //@@preconditions assert(this->pControllerSession != NULL); //@@end preconditions return this->pControllerSession->GetImplementation(); } //----------------------------------------------------------------------------- void* cpl_ControllerManager::GetIconProxy() { //@@preconditions assert(this->pControllerIcon != NULL); //@@end preconditions return this->pControllerIcon->GetIconProxy(); } //----------------------------------------------------------------------------- void* cpl_ControllerManager::GetImageProxy() { //@@preconditions assert(this->pControllerImage != NULL); //@@end preconditions return this->pControllerImage->GetImageProxy(); } //----------------------------------------------------------------------------- void cpl_ControllerManager::RunLuaScriptFile(const char* fname) { //@@preconditions assert(this->pControllerLuaScript != NULL); assert(fname != NULL); //@@end preconditions this->pControllerLuaScript->RunScriptFile(fname); } //----------------------------------------------------------------------------- void cpl_ControllerManager::RunLuaScriptCommand(const char* buffer) { //@@preconditions assert(this->pControllerLuaScript != NULL); assert(buffer != NULL); //@@end preconditions this->pControllerLuaScript->Execute(buffer); } //----------------------------------------------------------------------------- int cpl_ControllerManager::SetEnabled(int state) { int old = this->IsEnabled; this->IsEnabled = state; return old; } //----------------------------------------------------------------------------- int cpl_ControllerManager::GetEnabled() { return this->IsEnabled; } //----------------------------------------------------------------------------- // EVENT HANDLER //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int cpl_ControllerManager::DoCommand(char* scriptcomand, void* userData, char* cmdData) { //@@preconditions assert(scriptcomand != NULL); assert(strlen(scriptcomand) > 0); //@@end preconditions return 0; } //----------------------------------------------------------------------------- cpl_ControllerManager::cpl_ControllerManager() { this->ObjectCreator = NULL; this->mainGUIEngine = NULL; this->IsInitialized = 0; this->IsEnabled = 0; // this->luaWrapper = NULL; //controller items. this->pControllerScript = NULL; this->pControllerLuaScript = NULL; this->pControllerPluginTree = NULL; this->pControllerSession = NULL; this->pControllerFileIO = NULL; this->pControllerIcon = NULL; this->pControllerImage = NULL; } //----------------------------------------------------------------------------- cpl_ControllerManager::~cpl_ControllerManager() { if (this->mainGUIEngine != NULL) { this->mainGUIEngine->Release(); this->mainGUIEngine = NULL; } if (this->ObjectCreator != NULL) { this->ObjectCreator->Release(); this->ObjectCreator = NULL; } }
34.632353
94
0.594395
cayprogram
949bfc103304f85c9960f1e26b6d03f5dd748bdd
1,271
cc
C++
HDU/1532_Drainage Ditches/1532.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
1
2019-05-05T03:51:20.000Z
2019-05-05T03:51:20.000Z
HDU/1532_Drainage Ditches/1532.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
null
null
null
HDU/1532_Drainage Ditches/1532.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct Edge { int v, cap, rev; Edge (int _v, int _c, int _r) : v(_v), cap(_c), rev(_r) {} }; const int MAXN = 210; const int INF = 1e8; vector<Edge> E[MAXN]; bool used[MAXN]; int dfs(int s, int t, int f) { if (s == t) return f; used[s] = true; for (int i = 0; i != E[s].size(); ++i) { int &v = E[s][i].v, &cap = E[s][i].cap, &rev = E[s][i].rev; if (not used[v] and cap > 0) { int d = dfs(v, t, min(f, cap)); if (d > 0) { cap -= d; E[v][rev].cap += d; return d; } } } return 0; } int max_flow(int s, int t) { int flow = 0, f = 0; do { memset(used, 0, sizeof(used)); f = dfs(s, t, INF); flow += f; } while (f != 0); return flow; } int main() { int n, m; while (cin >> n >> m) { for (int i = 0; i != MAXN; ++i) E[i].clear(); for (int i = 0; i != n; ++i) { int u, v, cap; cin >> u >> v >> cap; E[u].push_back(Edge(v, cap, E[v].size())); E[v].push_back(Edge(u, 0, E[u].size() - 1)); } cout << max_flow(1, m) << endl; } return 0; }
21.542373
67
0.402832
pdszhh
94ab6ed9e914585f85c1ed5efa48fb6d11c08486
11,738
hxx
C++
opencascade/gp_Cone.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/gp_Cone.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/gp_Cone.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _gp_Cone_HeaderFile #define _gp_Cone_HeaderFile #include <gp_Ax1.hxx> #include <gp_Ax3.hxx> #include <gp_Pnt.hxx> //! Defines an infinite conical surface. //! A cone is defined by its half-angle (can be negative) at the apex and //! positioned in space with a coordinate system (a gp_Ax3 //! object) and a "reference radius" where: //! - the "main Axis" of the coordinate system is the axis of revolution of the cone, //! - the plane defined by the origin, the "X Direction" and //! the "Y Direction" of the coordinate system is the //! reference plane of the cone; the intersection of the //! cone with this reference plane is a circle of radius //! equal to the reference radius, //! if the half-angle is positive, the apex of the cone is on //! the negative side of the "main Axis" of the coordinate //! system. If the half-angle is negative, the apex is on the positive side. //! This coordinate system is the "local coordinate system" of the cone. //! Note: when a gp_Cone cone is converted into a //! Geom_ConicalSurface cone, some implicit properties of //! its local coordinate system are used explicitly: //! - its origin, "X Direction", "Y Direction" and "main //! Direction" are used directly to define the parametric //! directions on the cone and the origin of the parameters, //! - its implicit orientation (right-handed or left-handed) //! gives the orientation (direct or indirect) of the //! Geom_ConicalSurface cone. //! See Also //! gce_MakeCone which provides functions for more //! complex cone constructions //! Geom_ConicalSurface which provides additional //! functions for constructing cones and works, in particular, //! with the parametric equations of cones gp_Ax3 class gp_Cone { public: DEFINE_STANDARD_ALLOC //! Creates an indefinite Cone. gp_Cone() : radius (RealLast()), semiAngle (M_PI * 0.25) {} //! Creates an infinite conical surface. theA3 locates the cone //! in the space and defines the reference plane of the surface. //! Ang is the conical surface semi-angle. Its absolute value is in range //! ]0, PI/2[. //! theRadius is the radius of the circle in the reference plane of //! the cone. //! theRaises ConstructionError //! * if theRadius is lower than 0.0 //! * Abs(theAng) < Resolution from gp or Abs(theAng) >= (PI/2) - Resolution. gp_Cone (const gp_Ax3& theA3, const Standard_Real theAng, const Standard_Real theRadius); //! Changes the symmetry axis of the cone. Raises ConstructionError //! the direction of theA1 is parallel to the "XDirection" //! of the coordinate system of the cone. void SetAxis (const gp_Ax1& theA1) { pos.SetAxis (theA1); } //! Changes the location of the cone. void SetLocation (const gp_Pnt& theLoc) { pos.SetLocation (theLoc); } //! Changes the local coordinate system of the cone. //! This coordinate system defines the reference plane of the cone. void SetPosition (const gp_Ax3& theA3) { pos = theA3; } //! Changes the radius of the cone in the reference plane of //! the cone. //! Raised if theR < 0.0 void SetRadius (const Standard_Real theR) { Standard_ConstructionError_Raise_if (theR < 0.0, "gp_Cone::SetRadius() - radius should be positive number"); radius = theR; } //! Changes the semi-angle of the cone. //! Semi-angle can be negative. Its absolute value //! Abs(theAng) is in range ]0,PI/2[. //! Raises ConstructionError if Abs(theAng) < Resolution from gp or Abs(theAng) >= PI/2 - Resolution void SetSemiAngle (const Standard_Real theAng); //! Computes the cone's top. The Apex of the cone is on the //! negative side of the symmetry axis of the cone. gp_Pnt Apex() const { gp_XYZ aCoord = pos.Direction().XYZ(); aCoord.Multiply (-radius / Tan (semiAngle)); aCoord.Add (pos.Location().XYZ()); return gp_Pnt (aCoord); } //! Reverses the U parametrization of the cone //! reversing the YAxis. void UReverse() { pos.YReverse(); } //! Reverses the V parametrization of the cone reversing the ZAxis. void VReverse() { pos.ZReverse(); semiAngle = -semiAngle; } //! Returns true if the local coordinate system of this cone is right-handed. Standard_Boolean Direct() const { return pos.Direct(); } //! returns the symmetry axis of the cone. const gp_Ax1& Axis() const { return pos.Axis(); } //! Computes the coefficients of the implicit equation of the quadric //! in the absolute cartesian coordinates system : //! theA1.X**2 + theA2.Y**2 + theA3.Z**2 + 2.(theB1.X.Y + theB2.X.Z + theB3.Y.Z) + //! 2.(theC1.X + theC2.Y + theC3.Z) + theD = 0.0 Standard_EXPORT void Coefficients (Standard_Real& theA1, Standard_Real& theA2, Standard_Real& theA3, Standard_Real& theB1, Standard_Real& theB2, Standard_Real& theB3, Standard_Real& theC1, Standard_Real& theC2, Standard_Real& theC3, Standard_Real& theD) const; //! returns the "Location" point of the cone. const gp_Pnt& Location() const { return pos.Location(); } //! Returns the local coordinates system of the cone. const gp_Ax3& Position() const { return pos; } //! Returns the radius of the cone in the reference plane. Standard_Real RefRadius() const { return radius; } //! Returns the half-angle at the apex of this cone. //! Attention! Semi-angle can be negative. Standard_Real SemiAngle() const { return semiAngle; } //! Returns the XAxis of the reference plane. gp_Ax1 XAxis() const { return gp_Ax1 (pos.Location(), pos.XDirection()); } //! Returns the YAxis of the reference plane. gp_Ax1 YAxis() const { return gp_Ax1 (pos.Location(), pos.YDirection()); } Standard_EXPORT void Mirror (const gp_Pnt& theP); //! Performs the symmetrical transformation of a cone //! with respect to the point theP which is the center of the //! symmetry. Standard_NODISCARD Standard_EXPORT gp_Cone Mirrored (const gp_Pnt& theP) const; Standard_EXPORT void Mirror (const gp_Ax1& theA1); //! Performs the symmetrical transformation of a cone with //! respect to an axis placement which is the axis of the //! symmetry. Standard_NODISCARD Standard_EXPORT gp_Cone Mirrored (const gp_Ax1& theA1) const; Standard_EXPORT void Mirror (const gp_Ax2& theA2); //! Performs the symmetrical transformation of a cone with respect //! to a plane. The axis placement theA2 locates the plane of the //! of the symmetry : (Location, XDirection, YDirection). Standard_NODISCARD Standard_EXPORT gp_Cone Mirrored (const gp_Ax2& theA2) const; void Rotate (const gp_Ax1& theA1, const Standard_Real theAng) { pos.Rotate (theA1, theAng); } //! Rotates a cone. theA1 is the axis of the rotation. //! Ang is the angular value of the rotation in radians. Standard_NODISCARD gp_Cone Rotated (const gp_Ax1& theA1, const Standard_Real theAng) const { gp_Cone aCone = *this; aCone.pos.Rotate (theA1, theAng); return aCone; } void Scale (const gp_Pnt& theP, const Standard_Real theS); //! Scales a cone. theS is the scaling value. //! The absolute value of theS is used to scale the cone Standard_NODISCARD gp_Cone Scaled (const gp_Pnt& theP, const Standard_Real theS) const; void Transform (const gp_Trsf& theT); //! Transforms a cone with the transformation theT from class Trsf. Standard_NODISCARD gp_Cone Transformed (const gp_Trsf& theT) const; void Translate (const gp_Vec& theV) { pos.Translate (theV); } //! Translates a cone in the direction of the vector theV. //! The magnitude of the translation is the vector's magnitude. Standard_NODISCARD gp_Cone Translated (const gp_Vec& theV) const { gp_Cone aCone = *this; aCone.pos.Translate (theV); return aCone; } void Translate (const gp_Pnt& theP1, const gp_Pnt& theP2) { pos.Translate (theP1, theP2); } //! Translates a cone from the point P1 to the point P2. Standard_NODISCARD gp_Cone Translated (const gp_Pnt& theP1, const gp_Pnt& theP2) const { gp_Cone aCone = *this; aCone.pos.Translate (theP1, theP2); return aCone; } private: gp_Ax3 pos; Standard_Real radius; Standard_Real semiAngle; }; // ======================================================================= // function : gp_Cone // purpose : // ======================================================================= inline gp_Cone::gp_Cone (const gp_Ax3& theA3, const Standard_Real theAng, const Standard_Real theRadius) : pos (theA3), radius (theRadius), semiAngle (theAng) { Standard_Real aVal = theAng; if (aVal < 0) { aVal = -aVal; } Standard_ConstructionError_Raise_if (theRadius < 0. || aVal <= gp::Resolution() || M_PI * 0.5 - aVal <= gp::Resolution(), "gp_Cone() - invalid construction parameters"); } // ======================================================================= // function : SetSemiAngle // purpose : // ======================================================================= inline void gp_Cone::SetSemiAngle (const Standard_Real theAng) { Standard_Real aVal = theAng; if (aVal < 0) { aVal = -aVal; } Standard_ConstructionError_Raise_if (aVal <= gp::Resolution() || M_PI * 0.5 - aVal <= gp::Resolution(), "gp_Cone::SetSemiAngle() - invalid angle range"); semiAngle = theAng; } // ======================================================================= // function : Scale // purpose : // ======================================================================= inline void gp_Cone::Scale (const gp_Pnt& theP, const Standard_Real theS) { pos.Scale (theP, theS); radius *= theS; if (radius < 0) { radius = -radius; } } // ======================================================================= // function : Scaled // purpose : // ======================================================================= inline gp_Cone gp_Cone::Scaled (const gp_Pnt& theP, const Standard_Real theS) const { gp_Cone aC = *this; aC.pos.Scale (theP, theS); aC.radius *= theS; if (aC.radius < 0) { aC.radius = -aC.radius; } return aC; } // ======================================================================= // function : Transform // purpose : // ======================================================================= inline void gp_Cone::Transform (const gp_Trsf& theT) { pos.Transform (theT); radius *= theT.ScaleFactor(); if (radius < 0) { radius = -radius; } } // ======================================================================= // function : Transformed // purpose : // ======================================================================= inline gp_Cone gp_Cone::Transformed (const gp_Trsf& theT) const { gp_Cone aC = *this; aC.pos.Transform (theT); aC.radius *= theT.ScaleFactor(); if (aC.radius < 0) { aC.radius = -aC.radius; } return aC; } #endif // _gp_Cone_HeaderFile
36.006135
130
0.635457
mgreminger
94b05095f020c09ed466e871062eb8f8aff90a12
8,425
cpp
C++
src/win32/oaPixelFormat.cpp
GPUOpen-Tools/common-src-AMDTOSAPIWrappers
7bef652893dde91ccacaa88c17f4940ed5ebf28a
[ "MIT" ]
1
2017-01-28T14:13:25.000Z
2017-01-28T14:13:25.000Z
src/win32/oaPixelFormat.cpp
GPUOpen-Tools/common-src-AMDTOSAPIWrappers
7bef652893dde91ccacaa88c17f4940ed5ebf28a
[ "MIT" ]
null
null
null
src/win32/oaPixelFormat.cpp
GPUOpen-Tools/common-src-AMDTOSAPIWrappers
7bef652893dde91ccacaa88c17f4940ed5ebf28a
[ "MIT" ]
1
2019-11-01T23:07:22.000Z
2019-11-01T23:07:22.000Z
//===================================================================== // Copyright 2016 (c), Advanced Micro Devices, Inc. All rights reserved. // /// \author AMD Developer Tools Team /// \file oaPixelFormat.cpp /// //===================================================================== //------------------------------ oaPixelFormat.cpp ------------------------------ // Win32: #define WIN32_LEAN_AND_MEAN 1 #include <Windows.h> // Infra: #include <AMDTBaseTools/Include/gtAssert.h> // Local: #include <AMDTOSAPIWrappers/Include/oaPixelFormat.h> // --------------------------------------------------------------------------- // Name: oaCalcPixelFormatHardwareSupport // Description: Calculates the hardware acceleration mode of an input pixel format // Author: AMD Developer Tools Team // Date: 6/12/2003 // --------------------------------------------------------------------------- oaPixelFormat::HardwareSupport oaCalcPixelFormatHardwareSupport(const PIXELFORMATDESCRIPTOR& pixelFormatDescriptior) { oaPixelFormat::HardwareSupport retVal = oaPixelFormat::NO_HARDWARE_ACCELERATION; // Get the pixel buffer format flags: unsigned long bufferFlags = pixelFormatDescriptior.dwFlags; // ------------------------------------------------------------------ // Notice: The below code is very sensitive - edit it with care !!!!! // ------------------------------------------------------------------ // Is this pixel format rendered by a software generic renderer ? // In these days (December 2003), it is usually one of the below: // a. The software renderer that comes with the Windows OS by Microsoft. // b. The software renderer for Windows by SGI (Not supported anymore by SGI). bool isSoftwareDriver = ((bufferFlags & PFD_GENERIC_FORMAT) && !(bufferFlags & PFD_GENERIC_ACCELERATED)); // Is the generic implementation supplemented by hardware acceleration ? // True usually means that an MCD (Mini Client Driver) is at work. // (An MCD is a small driver that only exposes the rasterization interface of the // underlying hardware). bool isMiniClientDriver = ((bufferFlags & PFD_GENERIC_FORMAT) && (bufferFlags & PFD_GENERIC_ACCELERATED)); // Is OpenGL fully implemented by the graphic harware ? // True usually means that an ICD (Installable Client Driver) is at work. // (An ICD is a full OpenGL implementation by a hardware vendor driver) bool isInstallableClientDriver = (!(bufferFlags & PFD_GENERIC_FORMAT) && !(bufferFlags & PFD_GENERIC_ACCELERATED)); // Map the above options the HardwareSupport enumeration: if (isInstallableClientDriver) { retVal = oaPixelFormat::FULL_HARDWARE_ACCELERATION; } else if (isMiniClientDriver) { retVal = oaPixelFormat::PARTIAL_HARDWARE_ACCELERATION; } else if (isSoftwareDriver) { retVal = oaPixelFormat::NO_HARDWARE_ACCELERATION; } else { // We encountered a bufferFlags bit combination that we do not expect: GT_ASSERT(0); retVal = oaPixelFormat::NO_HARDWARE_ACCELERATION; } return retVal; } // --------------------------------------------------------------------------- // Name: oaCalcPixelType // Description: Calculate the pixel type in an input pixel format. // Author: AMD Developer Tools Team // Date: 6/12/2003 // --------------------------------------------------------------------------- oaPixelFormat::PixelType oaCalcPixelType(const PIXELFORMATDESCRIPTOR& pixelFormatDescriptior) { oaPixelFormat::PixelType retVal = oaPixelFormat::RGBA; if (pixelFormatDescriptior.iPixelType == PFD_TYPE_COLORINDEX) { retVal = oaPixelFormat::COLOR_INDEX; } else if (pixelFormatDescriptior.iPixelType == PFD_TYPE_RGBA) { retVal = oaPixelFormat::RGBA; } else { // An unknown pixel type: GT_ASSERT(0); } return retVal; } // --------------------------------------------------------------------------- // Name: oaPixelFormat::oaPixelFormat // Description: Constructor - Buld this representation out of a given // Win32 pixel format. // Arguments: hDC - A handle to the device context in which this pixel format resides. // pixelFormatIndex - The index of the pixel format in this context. // Author: AMD Developer Tools Team // Date: 2/6/2003 // Implementation Notes: // // --------------------------------------------------------------------------- oaPixelFormat::oaPixelFormat(oaDeviceContextHandle hDC, oaPixelFormatId pixelFormatIndex) : _hDC(hDC), _nativeId(pixelFormatIndex), _isInitialized(false), _supportsOpenGL(false), _supportsNativeRendering(false), _isDoubleBuffered(false), _isStereoscopic(false), _hardwareSupport(NO_HARDWARE_ACCELERATION), _pixelType(RGBA), _amountOfColorBits(0), _amountOfRedBits(0), _amountOfGreenBits(0), _amountOfBlueBits(0), _amountOfAlphaBits(0), _amountOfZBufferBits(0), _amountOfAccumulationBufferBits(0), _amountOfStencilBufferBits(0) { } // --------------------------------------------------------------------------- // Name: oaPixelFormat::~oaPixelFormat // Description: Destructor // Author: AMD Developer Tools Team // Date: 2/1/2006 // --------------------------------------------------------------------------- oaPixelFormat::~oaPixelFormat() { } // --------------------------------------------------------------------------- // Name: oaPixelFormat::initialize // Description: Initializes oaPixelFormat attributes from the corresponding // Win32 PIXELFORMATDESCRIPTOR. // Return Val: bool - Success / failure. // Author: AMD Developer Tools Team // Date: 6/12/2003 // --------------------------------------------------------------------------- bool oaPixelFormat::initialize() { // Get the Win32 PixelFormat description: PIXELFORMATDESCRIPTOR pixelFormatDescriptior; int rc = ::DescribePixelFormat(_hDC, _nativeId, sizeof(PIXELFORMATDESCRIPTOR), &pixelFormatDescriptior); GT_IF_WITH_ASSERT(rc != 0) { // Fill the pixel format attributes: _supportsOpenGL = ((pixelFormatDescriptior.dwFlags & PFD_SUPPORT_OPENGL) != 0); _supportsNativeRendering = ((pixelFormatDescriptior.dwFlags & PFD_SUPPORT_GDI) != 0); _isDoubleBuffered = ((pixelFormatDescriptior.dwFlags & PFD_DOUBLEBUFFER) != 0); _isStereoscopic = ((pixelFormatDescriptior.dwFlags & PFD_STEREO) != 0); _hardwareSupport = oaCalcPixelFormatHardwareSupport(pixelFormatDescriptior); _pixelType = oaCalcPixelType(pixelFormatDescriptior); _amountOfColorBits = pixelFormatDescriptior.cColorBits; _amountOfRedBits = pixelFormatDescriptior.cRedBits; _amountOfGreenBits = pixelFormatDescriptior.cGreenBits; _amountOfBlueBits = pixelFormatDescriptior.cBlueBits; _amountOfAlphaBits = pixelFormatDescriptior.cAlphaBits; _amountOfZBufferBits = pixelFormatDescriptior.cDepthBits; _amountOfAccumulationBufferBits = pixelFormatDescriptior.cAccumBits; _amountOfStencilBufferBits = pixelFormatDescriptior.cStencilBits; _isInitialized = true; } return _isInitialized; } // --------------------------------------------------------------------------- // Name: oaPixelFormat::initializeGLESPixelFormatWithChannelValues // Description: Initializes the Pixel format objects using default values and values // obtained from OpenGL ES. Should only be used by EAGL (iPhone). // Return Val: bool - Success / failure. // Author: AMD Developer Tools Team // Date: 23/5/2010 // --------------------------------------------------------------------------- bool oaPixelFormat::initializeGLESPixelFormatWithChannelValues(int amountOfRBits, int amountOfGBits, int amountOfBBits, int amountOfABits, int amountOfDepBits, int amountOfStenBits) { GT_UNREFERENCED_PARAMETER(amountOfRBits); GT_UNREFERENCED_PARAMETER(amountOfGBits); GT_UNREFERENCED_PARAMETER(amountOfBBits); GT_UNREFERENCED_PARAMETER(amountOfABits); GT_UNREFERENCED_PARAMETER(amountOfDepBits); GT_UNREFERENCED_PARAMETER(amountOfStenBits); // We should not get here on non-EAGL implementations: GT_ASSERT(false); return _isInitialized; }
42.125
181
0.609496
GPUOpen-Tools
94b1598339c66d4afa9c5d327b1dbf6c0ca7539f
4,718
cpp
C++
Engine/Core/Clock.cpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
Engine/Core/Clock.cpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
Engine/Core/Clock.cpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
//============================================================================================================== //Clock.cpp //by Albert Chen Oct-20-2015. //============================================================================================================== #include "Clock.hpp" //=========================================================================================================== Clock* Clock::s_SystemClock = NULL; Clock* Clock::s_GameClock = NULL; bool g_isGameClockPaused = false; //=========================================================================================================== ///---------------------------------------------------------------------------------------------------------- ///constructors Clock::Clock(){ //do nothing } //----------------------------------------------------------------------------------------------------------- Clock::Clock(const std::string& name, Clock* parent) : m_name(name), m_id(GetStringID(name)), m_parent(parent) { // if (m_parent) { // AddChild(m_parent); // } m_timers.clear(); } //----------------------------------------------------------------------------------------------------------- Clock::~Clock(){ //do nothing //Clean up clock hierarchy ptrs //redirect child pts if (m_parent) { m_parent->RemoveChild(this); for (Clock* child : m_children) { m_parent->AddChild(child); } } } //----------------------------------------------------------------------------------------------------------- Clock* Clock::GetChild(const std::string& name){ Clock* outClock = NULL; if (m_children.size() > 0){ for (ClocksIterator it = m_children.begin(); it != m_children.end(); ++it){ Clock* clock = (*it); if (clock->m_id == GetStringID(name)){ outClock = clock; break; } }//end of for } return outClock; } //----------------------------------------------------------------------------------------------------------- void Clock::AdvanceTime(double deltaSeconds){ //timescale it first deltaSeconds *= m_timeScale; //set to 0 if (m_isPaused) deltaSeconds = 0.0; m_deltaSeconds = deltaSeconds; //advance time m_currentTime += m_deltaSeconds; UpdateTimers(m_deltaSeconds, m_timers); for (ClocksIterator it = m_children.begin(); it != m_children.end(); ++it){ Clock* clock = (*it); if (clock) { //advance time on children clock->AdvanceTime(m_deltaSeconds); } } } //----------------------------------------------------------------------------------------------------------- ///---------------------------------------------------------------------------------------------------------- ///timer map helpers void Clock::SetElapsedTimer() { //adds a timer to the map Timer* newElapsedTimer = new Timer(0.0f); m_timers.push_back(newElapsedTimer); m_elapsedTimerHandle = newElapsedTimer; } void Clock::SetCountdownTimer(const std::string& name, const float& countdownFromSeconds, EventCallbackFunc* callback, void* data){ //adds a timer to the map m_timers.push_back( new Timer(countdownFromSeconds, name, callback, data, false) ); } void Clock::SetPeriodicTimer(const std::string& name, const float& countdownFromSeconds, EventCallbackFunc* callback, void* data){ //adds a timer to the map m_timers.push_back( new Timer(countdownFromSeconds, name, callback, data, true) ); } void Clock::KillTimer(const std::string& name){ //kills a timer Timer* timerToKill = FindTimerByName(name, m_timers); if (timerToKill){ timerToKill->Kill(); } } //=========================================================================================================== ///---------------------------------------------------------------------------------------------------------- ///friend methods void InitializeClockSystem(){ Clock::s_SystemClock = new Clock("MasterSystemClock", NULL); Clock::s_GameClock = new Clock("GameClock", Clock::s_SystemClock); Clock::s_GameClock->SetElapsedTimer(); Clock::s_SystemClock->AddChild(Clock::s_GameClock); //kill the timer for now, revive it when the game starts Timer* gameElapsedTimer = GetGameClock().GetElapsedTimer(); if (gameElapsedTimer) { gameElapsedTimer->Kill(); } //InitializeEntitiesClock(); } //delete all clocks and stuff void Clock::ShutDown(){ //ShutDownEntitiesClock(); // if (Clock::s_GameClock){ // delete Clock::s_GameClock; // Clock::s_GameClock = NULL; // } if (Clock::s_SystemClock){ delete Clock::s_SystemClock; Clock::s_SystemClock = NULL; } } //=========================================================================================================== //===========================================================================================================
27.91716
131
0.453794
achen889
94b3bc32aed040e4244eff2656868bc46f9c1ff9
5,874
cpp
C++
src/Components.cpp
leiradel/lrcpp
17e5d833886e642ca4af16e255a5ca58b170a324
[ "MIT" ]
8
2021-01-10T00:44:34.000Z
2021-11-26T02:03:43.000Z
src/Components.cpp
leiradel/lrcpp
17e5d833886e642ca4af16e255a5ca58b170a324
[ "MIT" ]
null
null
null
src/Components.cpp
leiradel/lrcpp
17e5d833886e642ca4af16e255a5ca58b170a324
[ "MIT" ]
null
null
null
#include <lrcpp/Components.h> #include <string.h> #include <stdlib.h> void lrcpp::Logger::debug(char const* format, ...) { va_list args; va_start(args, format); vprintf(RETRO_LOG_DEBUG, format, args); va_end(args); } void lrcpp::Logger::info(char const* format, ...) { va_list args; va_start(args, format); vprintf(RETRO_LOG_INFO, format, args); va_end(args); } void lrcpp::Logger::warn(char const* format, ...) { va_list args; va_start(args, format); vprintf(RETRO_LOG_WARN, format, args); va_end(args); } void lrcpp::Logger::error(char const* format, ...) { va_list args; va_start(args, format); vprintf(RETRO_LOG_ERROR, format, args); va_end(args); } bool lrcpp::Config::setVariables(struct retro_variable const* const variables) { size_t count = 0; size_t totalLength = 0; for (count = 0; variables[count].key != nullptr; count++) { totalLength += strlen(variables[count].key) + 1; totalLength += strlen(variables[count].value) + 1; } retro_core_option_definition* const defs = (retro_core_option_definition*)malloc((count + 1) * sizeof(*defs)); char* const strings = (char*)malloc(totalLength); if (defs == nullptr || strings == nullptr) { free(defs); free(strings); return false; } char* ptr = strings; for (size_t i = 0; i < count; i++) { retro_core_option_definition* const def = defs + i; def->key = variables[i].key; char const* option = strchr(variables[i].value, ';'); if (option == nullptr) { free(defs); free(strings); return false; } def->desc = ptr; def->info = nullptr; memcpy(ptr, variables[i].value, option - variables[i].value); ptr += option - variables[i].value; *ptr++ = 0; option++; while (*option == ' ' || *option == '\t') { option++; } if (*option == 0) { free(defs); free(strings); return false; } size_t j = 0; for (; j < RETRO_NUM_CORE_OPTION_VALUES_MAX - 1; j++) { char const* const pipe = strchr(option, '|'); def->values[j].value = ptr; if (pipe == nullptr) { strcpy(ptr, option); ptr += strlen(ptr) + 1; } else { memcpy(ptr, option, pipe - option); ptr += pipe - option; *ptr++ = 0; } def->values[j].label = nullptr; if (pipe == nullptr) { break; } option = pipe + 1; } if (j == RETRO_NUM_CORE_OPTION_VALUES_MAX - 1) { free(defs); free(strings); return false; } def->values[j + 1].value = def->values[j + 1].label = nullptr; def->default_value = def->values[0].value; } defs[count].key = nullptr; defs[count].desc = nullptr; defs[count].info = nullptr; defs[count].values[0].value = nullptr; defs[count].values[0].label = nullptr; defs[count].default_value = nullptr; bool const ok = setCoreOptions(defs); free(strings); free(defs); return ok; } bool lrcpp::Config::getCoreOptionsVersion(unsigned* const version) { *version = 1; return true; } static size_t addBitsDown(size_t n) { n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; if (sizeof(size_t) > 4) { // double shift to avoid warnings on 32bit n |= n >> 16 >> 16; } return n; } static size_t inflate(size_t addr, size_t mask) { while (mask) { size_t tmp = (mask - 1) & ~mask; // to put in an 1 bit instead, OR in tmp+1 addr = ((addr & ~tmp) << 1) | (addr & tmp); mask = mask & (mask - 1); } return addr; } static size_t reduce(size_t addr, size_t mask) { while (mask) { size_t tmp = (mask - 1) & ~mask; addr = (addr & tmp) | ((addr >> 1) & ~tmp); mask = (mask & (mask - 1)) >> 1; } return addr; } static size_t highestBit(size_t n) { n = addBitsDown(n); return n ^ (n >> 1); } bool lrcpp::Config::preprocessMemoryDescriptors(struct retro_memory_descriptor* descriptors, unsigned count) { size_t disconnect_mask; size_t top_addr = 1; for (unsigned i = 0; i < count; i++) { struct retro_memory_descriptor* const desc = descriptors + i; if (desc->select != 0) { top_addr |= desc->select; } else { top_addr |= desc->start + desc->len - 1; } } top_addr = addBitsDown(top_addr); for (unsigned i = 0; i < count; i++) { struct retro_memory_descriptor* const desc = descriptors + i; if (desc->select == 0) { if (desc->len == 0) { return false; } if ((desc->len & (desc->len - 1)) != 0) { return false; } desc->select = top_addr & ~inflate(addBitsDown(desc->len - 1), desc->disconnect); } if (desc->len == 0) { desc->len = addBitsDown(reduce(top_addr & ~desc->select, desc->disconnect)) + 1; } if (desc->start & ~desc->select) { return false; } while (reduce(top_addr & ~desc->select, desc->disconnect) >> 1 > desc->len - 1) { desc->disconnect |= highestBit(top_addr & ~desc->select & ~desc->disconnect); } disconnect_mask = addBitsDown(desc->len - 1); desc->disconnect &= disconnect_mask; while ((~disconnect_mask) >> 1 & desc->disconnect) { disconnect_mask >>= 1; desc->disconnect &= disconnect_mask; } } return true; }
24.995745
114
0.524345
leiradel
94b5668affd22cd4696cbeef739a2c6a6adab12d
213
cpp
C++
014.cpp
Jalanjii/Algorithms
6b6b01e18c5c6c4bcfa122a269fdab8a47f09b7b
[ "MIT" ]
1
2021-02-01T03:44:33.000Z
2021-02-01T03:44:33.000Z
014.cpp
Jalanjii/Algorithms
6b6b01e18c5c6c4bcfa122a269fdab8a47f09b7b
[ "MIT" ]
null
null
null
014.cpp
Jalanjii/Algorithms
6b6b01e18c5c6c4bcfa122a269fdab8a47f09b7b
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n1, n2; cin >> n1 >> n2; if ((n1 % 2) != 0) cout << n1; else cout << n2; }
15.214286
36
0.558685
Jalanjii
94b804fb2886ffa4591ceacdc3fd0a90626c8ea3
7,275
cpp
C++
util/processinfo_osx.cpp
RedBeard0531/mongo_utils
402c2023df7d67609ce9da8e405bf13cdd270e20
[ "Apache-2.0" ]
1
2018-03-14T21:48:43.000Z
2018-03-14T21:48:43.000Z
util/processinfo_osx.cpp
RedBeard0531/mongo_utils
402c2023df7d67609ce9da8e405bf13cdd270e20
[ "Apache-2.0" ]
null
null
null
util/processinfo_osx.cpp
RedBeard0531/mongo_utils
402c2023df7d67609ce9da8e405bf13cdd270e20
[ "Apache-2.0" ]
null
null
null
// processinfo_darwin.cpp /* Copyright 2009 10gen Inc. * * 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. */ #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kControl #include "mongo/platform/basic.h" #include <boost/none.hpp> #include <boost/optional.hpp> #include <iostream> #include <mach/mach_host.h> #include <mach/mach_init.h> #include <mach/mach_traps.h> #include <mach/task.h> #include <mach/task_info.h> #include <mach/vm_map.h> #include <mach/vm_statistics.h> #include <sys/mman.h> #include <sys/sysctl.h> #include <sys/types.h> #include "mongo/db/jsobj.h" #include "mongo/util/log.h" #include "mongo/util/processinfo.h" using namespace std; namespace mongo { ProcessInfo::ProcessInfo(ProcessId pid) : _pid(pid) {} ProcessInfo::~ProcessInfo() {} bool ProcessInfo::supported() { return true; } // get the number of CPUs available to the scheduler boost::optional<unsigned long> ProcessInfo::getNumCoresForProcess() { long nprocs = sysconf(_SC_NPROCESSORS_ONLN); if (nprocs) return nprocs; return boost::none; } int ProcessInfo::getVirtualMemorySize() { task_t result; mach_port_t task; if ((result = task_for_pid(mach_task_self(), _pid.toNative(), &task)) != KERN_SUCCESS) { cout << "error getting task\n"; return 0; } #if !defined(__LP64__) task_basic_info_32 ti; #else task_basic_info_64 ti; #endif mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT; if ((result = task_info(task, TASK_BASIC_INFO, (task_info_t)&ti, &count)) != KERN_SUCCESS) { cout << "error getting task_info: " << result << endl; return 0; } return (int)((double)ti.virtual_size / (1024.0 * 1024)); } int ProcessInfo::getResidentSize() { task_t result; mach_port_t task; if ((result = task_for_pid(mach_task_self(), _pid.toNative(), &task)) != KERN_SUCCESS) { cout << "error getting task\n"; return 0; } #if !defined(__LP64__) task_basic_info_32 ti; #else task_basic_info_64 ti; #endif mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT; if ((result = task_info(task, TASK_BASIC_INFO, (task_info_t)&ti, &count)) != KERN_SUCCESS) { cout << "error getting task_info: " << result << endl; return 0; } return (int)(ti.resident_size / (1024 * 1024)); } double ProcessInfo::getSystemMemoryPressurePercentage() { return 0.0; } void ProcessInfo::getExtraInfo(BSONObjBuilder& info) { struct task_events_info taskInfo; mach_msg_type_number_t taskInfoCount = TASK_EVENTS_INFO_COUNT; if (KERN_SUCCESS != task_info(mach_task_self(), TASK_EVENTS_INFO, (integer_t*)&taskInfo, &taskInfoCount)) { cout << "error getting extra task_info" << endl; return; } info.append("page_faults", taskInfo.pageins); } /** * Get a sysctl string value by name. Use string specialization by default. */ typedef long long NumberVal; template <typename Variant> Variant getSysctlByName(const char* sysctlName) { string value; size_t len; int status; // NB: sysctlbyname is called once to determine the buffer length, and once to copy // the sysctl value. Retry if the buffer length grows between calls. do { status = sysctlbyname(sysctlName, NULL, &len, NULL, 0); if (status == -1) break; value.resize(len); status = sysctlbyname(sysctlName, &*value.begin(), &len, NULL, 0); } while (status == -1 && errno == ENOMEM); if (status == -1) { // unrecoverable error from sysctlbyname log() << sysctlName << " unavailable"; return ""; } // Drop any trailing NULL bytes by constructing Variant from a C string. return value.c_str(); } /** * Get a sysctl integer value by name (specialization) */ template <> long long getSysctlByName<NumberVal>(const char* sysctlName) { long long value = 0; size_t len = sizeof(value); if (sysctlbyname(sysctlName, &value, &len, NULL, 0) < 0) { log() << "Unable to resolve sysctl " << sysctlName << " (number) "; } if (len > 8) { log() << "Unable to resolve sysctl " << sysctlName << " as integer. System returned " << len << " bytes."; } return value; } void ProcessInfo::SystemInfo::collectSystemInfo() { osType = "Darwin"; osName = "Mac OS X"; osVersion = getSysctlByName<string>("kern.osrelease"); addrSize = (getSysctlByName<NumberVal>("hw.cpu64bit_capable") ? 64 : 32); memSize = getSysctlByName<NumberVal>("hw.memsize"); numCores = getSysctlByName<NumberVal>("hw.ncpu"); // includes hyperthreading cores pageSize = static_cast<unsigned long long>(sysconf(_SC_PAGESIZE)); cpuArch = getSysctlByName<string>("hw.machine"); hasNuma = checkNumaEnabled(); BSONObjBuilder bExtra; bExtra.append("versionString", getSysctlByName<string>("kern.version")); bExtra.append("alwaysFullSync", static_cast<int>(getSysctlByName<NumberVal>("vfs.generic.always_do_fullfsync"))); bExtra.append( "nfsAsync", static_cast<int>(getSysctlByName<NumberVal>("vfs.generic.nfs.client.allow_async"))); bExtra.append("model", getSysctlByName<string>("hw.model")); bExtra.append("physicalCores", static_cast<int>(getSysctlByName<NumberVal>("machdep.cpu.core_count"))); bExtra.append( "cpuFrequencyMHz", static_cast<int>((getSysctlByName<NumberVal>("hw.cpufrequency") / (1000 * 1000)))); bExtra.append("cpuString", getSysctlByName<string>("machdep.cpu.brand_string")); bExtra.append("cpuFeatures", getSysctlByName<string>("machdep.cpu.features") + string(" ") + getSysctlByName<string>("machdep.cpu.extfeatures")); bExtra.append("pageSize", static_cast<int>(getSysctlByName<NumberVal>("hw.pagesize"))); bExtra.append("scheduler", getSysctlByName<string>("kern.sched")); _extraStats = bExtra.obj(); } bool ProcessInfo::checkNumaEnabled() { return false; } bool ProcessInfo::blockCheckSupported() { return true; } bool ProcessInfo::blockInMemory(const void* start) { char x = 0; if (mincore(alignToStartOfPage(start), getPageSize(), &x)) { log() << "mincore failed: " << errnoWithDescription(); return 1; } return x & 0x1; } bool ProcessInfo::pagesInMemory(const void* start, size_t numPages, vector<char>* out) { out->resize(numPages); if (mincore(alignToStartOfPage(start), numPages * getPageSize(), &out->front())) { log() << "mincore failed: " << errnoWithDescription(); return false; } for (size_t i = 0; i < numPages; ++i) { (*out)[i] &= 0x1; } return true; } }
31.223176
99
0.663368
RedBeard0531
94b82c58694b5425ff49653f6dc49f7d7933b862
3,066
cpp
C++
netvid_slice.cpp
trylle/netvid
ae3f6a54a195b43777654fecc44b431668274da2
[ "MIT" ]
null
null
null
netvid_slice.cpp
trylle/netvid
ae3f6a54a195b43777654fecc44b431668274da2
[ "MIT" ]
null
null
null
netvid_slice.cpp
trylle/netvid
ae3f6a54a195b43777654fecc44b431668274da2
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <chrono> #include <boost/program_options.hpp> #include <boost/asio/steady_timer.hpp> #include "check.h" #include "protocol.h" #include "net.h" using namespace boost; using namespace boost::asio; using namespace boost::asio::ip; namespace po=boost::program_options; typedef std::chrono::high_resolution_clock network_clock_t; int main(int argc, char **argv) { try { po::options_description desc("Allowed options"); std::string in_filename; std::string out_filename; int seek; int stop; desc.add_options() ("help", "produce help message") ("input-file,i", po::value<std::string>(&in_filename)->required(), "input file [filename]") ("output-file,o", po::value<std::string>(&out_filename)->required(), "output file [filename]") ("seek", po::value<int>(&seek)->default_value(0), "seek [frame]") ("stop", po::value<int>(&stop)->default_value(-1), "stop [frame]") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); if (vm.count("help")) { std::cout << desc << std::endl; return 1; } po::notify(vm); std::ifstream ifs_file; std::istream *pifs=&std::cin; if (in_filename!="-") { ifs_file.open(in_filename, std::ios::binary); pifs=&ifs_file; } std::istream &ifs=*pifs; std::ofstream ofs_real; std::ostream *pofs=&ofs_real; if (out_filename!="-") ofs_real.open(out_filename, std::ios::binary); else pofs=&std::cout; std::ostream &ofs=*pofs; struct packet_t { network_clock_t::duration time; std::string payload; }; bool peeked=false; packet_t current_packet; netvid::chunk_validator validator; auto process_packet=[&] () -> bool { if (peeked) { peeked=false; return true; } std::uint32_t payload_size; ifs.read(reinterpret_cast<char *>(&current_packet.time), sizeof(current_packet.time)); ifs.read(reinterpret_cast<char *>(&payload_size), sizeof(payload_size)); if (ifs.eof() || ifs.bad() || ifs.fail()) return false; current_packet.payload.resize(payload_size); ifs.read(&current_packet.payload[0], payload_size); validator.process(reinterpret_cast<const std::uint8_t *>(current_packet.payload.data()), reinterpret_cast<const std::uint8_t *>(current_packet.payload.data()+payload_size), boost::asio::ip::udp::endpoint()); if (stop>=0 && validator.frame_id && *validator.frame_id>=stop) return false; return true; }; for (; seek>0;) { if (!process_packet()) break; if (!validator.frame_id || *validator.frame_id<seek) continue; peeked=true; break; } while (process_packet()) { auto sz=std::uint32_t(current_packet.payload.size()); ofs.write(reinterpret_cast<const char *>(&current_packet.time), sizeof(current_packet.time)); ofs.write(reinterpret_cast<const char *>(&sz), sizeof(sz)); ofs.write(reinterpret_cast<const char *>(current_packet.payload.data()), sz); } } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } return 0; }
21.9
210
0.667645
trylle
94bd4f3685478255ef7e686c8701cb6030b395d3
1,030
cpp
C++
src/caesarify.cpp
urlordjames/caesargui
0a382f7887365adab07016ff3f26d5cb10343d1e
[ "MIT" ]
null
null
null
src/caesarify.cpp
urlordjames/caesargui
0a382f7887365adab07016ff3f26d5cb10343d1e
[ "MIT" ]
null
null
null
src/caesarify.cpp
urlordjames/caesargui
0a382f7887365adab07016ff3f26d5cb10343d1e
[ "MIT" ]
null
null
null
#include <iostream> #include "caesarify.h" Caesar::Caesar() { auto build_error = program.build(); if (build_error != 0) { std::cout << "BUILD ERROR: " << build_error << std::endl; std::string log; program.getBuildInfo(device, CL_PROGRAM_BUILD_LOG, &log); std::cout << log << std::endl; } } std::string Caesar::caesarify(std::string *stringin, int offset) { //const char *chars = stringin->c_str(); char chars[stringin->length()]; strcpy(chars, stringin->c_str()); cl::Buffer strBuf(context, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, sizeof(chars), &chars); cl::Buffer argument(context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(int), &offset); cl::Kernel kernel(program, "caesar"); kernel.setArg(0, strBuf); kernel.setArg(1, argument); cl::CommandQueue queue(context, device); queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(strlen(chars))); queue.enqueueReadBuffer(strBuf, false, 0, sizeof(chars), &chars); queue.finish(); return std::string(chars); }
27.837838
93
0.68835
urlordjames
94bfc43209acc9d7e4aa16a87436fee814725559
607
hpp
C++
GoPokemon/Entitites/Pokeball.hpp
jesusmartinoza/GoPokemon
99985cd87414d4232698231a08a909e630fc4b9b
[ "MIT" ]
1
2021-01-28T19:46:05.000Z
2021-01-28T19:46:05.000Z
GoPokemon/Entitites/Pokeball.hpp
jesusmartinoza/GoPokemon
99985cd87414d4232698231a08a909e630fc4b9b
[ "MIT" ]
null
null
null
GoPokemon/Entitites/Pokeball.hpp
jesusmartinoza/GoPokemon
99985cd87414d4232698231a08a909e630fc4b9b
[ "MIT" ]
null
null
null
// // Pokeball.hpp // GoPokemon // // Created by Jesús Martínez on 23/03/17. // Copyright © 2017 Jesús Alberto Martínez Mendoza. All rights reserved. // #ifndef Pokeball_hpp #define Pokeball_hpp #include <stdio.h> #include "ObjModel.hpp" class Pokeball: public ObjModel { private: vector<ObjVertex> pathPoints; ObjVertex p1, p4, r1, r4; int n; int pathPointIndex; int direction; public: Pokeball(); Pokeball(std::string fileName); vector<ObjVertex> getPathPoints(); void calculatePath(); bool update(); void reorderObjects(); }; #endif /* Pokeball_hpp */
18.96875
73
0.678748
jesusmartinoza
94c91e002d67e4a69f6248b6a86806eee688b682
1,711
cc
C++
flare/net/cos/ops/object/get_object.cc
AriCheng/flare
b2c84588fe4ac52f0875791d22284d7e063fd057
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
868
2021-05-28T04:00:22.000Z
2022-03-31T08:57:14.000Z
flare/net/cos/ops/object/get_object.cc
AriCheng/flare
b2c84588fe4ac52f0875791d22284d7e063fd057
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
33
2021-05-28T08:44:47.000Z
2021-09-26T13:09:21.000Z
flare/net/cos/ops/object/get_object.cc
AriCheng/flare
b2c84588fe4ac52f0875791d22284d7e063fd057
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
122
2021-05-28T08:22:23.000Z
2022-03-29T09:52:09.000Z
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "flare/net/cos/ops/object/get_object.h" #include "flare/base/encoding/percent.h" namespace flare { bool CosGetObjectRequest::PrepareTask(cos::CosTask* task, ErasedPtr* context) const { task->set_method(HttpMethod::Get); auto uri = Format("https://{}.cos.{}.myqcloud.com/{}?", task->options().bucket, task->options().region, EncodePercent(key)); if (!version_id.empty()) { uri += Format("versionId={}&", version_id); } task->set_uri(uri); if (traffic_limit) { task->AddHeader(Format("x-cos-traffic-limit: {}", traffic_limit)); } return true; } bool CosGetObjectResult::ParseResult(cos::CosTaskCompletion completion, ErasedPtr context) { auto&& hdrs = *completion.headers(); storage_class = hdrs.TryGet("x-cos-storage-class").value_or(""); storage_tier = hdrs.TryGet("x-cos-storage-tier").value_or(""); version_id = hdrs.TryGet("x-cos-version-id").value_or(""); bytes = std::move(*completion.body()); return true; } } // namespace flare
34.22
80
0.674459
AriCheng
94d14cfc34bac6738838e924021fd68708994cff
2,873
cpp
C++
tests/test-time-precise.cpp
Lord-KA/Matrix
eedb363b98e9bcb1a993802d214c9708bafe1842
[ "MIT" ]
1
2021-07-03T19:04:41.000Z
2021-07-03T19:04:41.000Z
tests/test-time-precise.cpp
Lord-KA/Matrix
eedb363b98e9bcb1a993802d214c9708bafe1842
[ "MIT" ]
null
null
null
tests/test-time-precise.cpp
Lord-KA/Matrix
eedb363b98e9bcb1a993802d214c9708bafe1842
[ "MIT" ]
null
null
null
#include "../Matrix.hpp" #include <chrono> #include <vector> #include <iostream> static size_t counter = -1; static constexpr size_t basicSize = 1e4; static constexpr size_t passes = 1e1; void test_0() { Matrix<int> M1(basicSize, basicSize), M2(basicSize, basicSize), M3; M1.FillMatrixRandom(); M2.FillMatrixRandom(); auto start = std::chrono::high_resolution_clock::now(); for (size_t cnt=0; cnt < passes; ++cnt){ M3 = M1 + M2; } auto end = std::chrono::high_resolution_clock::now(); ++counter; std::cout << "Test " << counter << " took " << std::chrono::duration<double, std::milli>(end - start).count() / passes << "ms\n"; } void test_1() { Matrix<int> M1(basicSize, basicSize), M2(basicSize, basicSize), M3; M1.FillMatrixRandom(); M2.FillMatrixRandom(); auto start = std::chrono::high_resolution_clock::now(); for (size_t cnt=0; cnt < passes; ++cnt){ M3 = M2 - M1; } auto end = std::chrono::high_resolution_clock::now(); ++counter; std::cout << "Test " << counter << " took " << std::chrono::duration<double, std::milli>(end - start).count() / passes << "ms\n"; } void test_2() { Matrix<int> M1(basicSize, basicSize), M2(basicSize, basicSize), M3; M1.FillMatrixRandom(); M2.FillMatrixRandom(); auto start = std::chrono::high_resolution_clock::now(); for (size_t cnt=0; cnt < passes; ++cnt){ M3 = M1 * M2; } auto end = std::chrono::high_resolution_clock::now(); ++counter; std::cout << "Test " << counter << " took " << std::chrono::duration<double, std::milli>(end - start).count() / passes << "ms\n"; } void test_3() { Matrix<int> M1(basicSize, basicSize), M2(basicSize, basicSize), M3; M1.FillMatrixRandom(); M2.FillMatrixRandom(); auto start = std::chrono::high_resolution_clock::now(); for (size_t cnt=0; cnt < passes; ++cnt){ M3 = M1; } auto end = std::chrono::high_resolution_clock::now(); ++counter; std::cout << "Test " << counter << " took " << std::chrono::duration<double, std::milli>(end - start).count() / passes << "ms\n"; } void test_4() { Matrix<int> M1(1e3, 1e3), M2(1e3, 1e3), M3; M1.FillMatrixRandom(); M2.FillMatrixRandom(); auto start = std::chrono::high_resolution_clock::now(); M3 = M2; auto end = std::chrono::high_resolution_clock::now(); ++counter; std::cout << "Test " << counter << " took " << std::chrono::duration<double, std::milli>(end - start).count() << "ms\n"; } int main() { #ifndef NTHREADS setThreadNum(4); std::cout << "Test runs in " << getThreadNum() << " threads\n"; #else std::cout << "Test runs in one thread\n"; #endif test_0(); test_1(); test_2(); test_3(); test_4(); }
24.347458
133
0.584058
Lord-KA
94d1a776cb829eb0e66fefdbc619e409cbe2eb7a
3,072
cpp
C++
src/core/cpp/resource/SoundHolder.cpp
NeroGames/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
26
2020-09-02T18:14:36.000Z
2022-02-08T18:28:36.000Z
src/core/cpp/resource/SoundHolder.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
14
2020-08-30T01:37:04.000Z
2021-07-19T20:47:29.000Z
src/core/cpp/resource/SoundHolder.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
6
2020-09-02T18:14:57.000Z
2021-12-31T00:32:09.000Z
//////////////////////////////////////////////////////////// // Nero Game Engine // Copyright (c) 2016-2020 Sanou A. K. Landry //////////////////////////////////////////////////////////// ///////////////////////////HEADERS/////////////////////////// //NERO #include <Nero/core/cpp/resource/SoundHolder.h> #include <Nero/core/cpp/utility/Utility.h> //BOOST #include <experimental/filesystem> //////////////////////////////////////////////////////////// namespace nero { SoundHolder::SoundHolder() { } SoundHolder::SoundHolder(const Setting& setting) : ResourceHolder (setting) { } SoundHolder::~SoundHolder() { destroy(); }; void SoundHolder::destroy() { } bool SoundHolder::addSoundBuffer(std::string name, std::unique_ptr<sf::SoundBuffer> soundBuffer) { auto inserted = m_SoundBufferMap.insert(std::make_pair(name, std::move(soundBuffer))); if(!inserted.second) { nero_log("failed to store sound " + name); return false; } m_SoundBufferTable.push_back(name); return true; } sf::SoundBuffer& SoundHolder::getSoundBuffer(std::string name) { auto found = m_SoundBufferMap.find(name); assert(found != m_SoundBufferMap.end()); return *found->second; } const sf::SoundBuffer& SoundHolder::getSoundBuffer(std::string name) const { auto found = m_SoundBufferMap.find(name); assert(found != m_SoundBufferMap.end()); return *found->second; } const std::vector<std::string>& SoundHolder::getSoundBufferTable() const { return m_SoundBufferTable; } bool SoundHolder::loadFile(const std::string& file) { std::experimental::filesystem::path filePath(file); std::unique_ptr<sf::SoundBuffer> soundBuffer = std::make_unique<sf::SoundBuffer>(); const std::string name = filePath.filename().stem().string(); if (!soundBuffer->loadFromFile(filePath.string())) { nero_log("unable to load sound : " + name); return false; } addSoundBuffer(name, std::move(soundBuffer)); nero_log("loaded : " + name); return true; } void SoundHolder::loadDirectory() { if(m_SelectedDirectory == StringPool.BLANK) { nero_log("failed to load directory"); return; } nero_log("resource path : " + m_SelectedDirectory); std::experimental::filesystem::path folderPath(m_SelectedDirectory); if(!file::directoryExist(m_SelectedDirectory)) { nero_log("unable to load sound resource"); nero_log("folder not found : " + m_SelectedDirectory); assert(false); } std::experimental::filesystem::directory_iterator it{folderPath}; while(it != std::experimental::filesystem::directory_iterator{}) { if(file::checkExtention(it->path().extension().string(), m_Setting.getStringTable("extension"))) { loadFile(it->path().string()); } it++; } } void SoundHolder::clear() { //clear parent ResourceHolder::clear(); //clear current m_SoundBufferMap.clear(); m_SoundBufferTable.clear(); } }
22.925373
99
0.607747
NeroGames
94d8e4121cf6801cd4280ba102d7fafd35ec0115
13,314
cpp
C++
driver/umd/src/job_base.cpp
dejsha01/armchina-zhouyi
5de86bbdb5dc4184df4348d64cd152db0dbf9a96
[ "MIT" ]
null
null
null
driver/umd/src/job_base.cpp
dejsha01/armchina-zhouyi
5de86bbdb5dc4184df4348d64cd152db0dbf9a96
[ "MIT" ]
null
null
null
driver/umd/src/job_base.cpp
dejsha01/armchina-zhouyi
5de86bbdb5dc4184df4348d64cd152db0dbf9a96
[ "MIT" ]
null
null
null
/********************************************************************************** * This file is CONFIDENTIAL and any use by you is subject to the terms of the * agreement between you and Arm China or the terms of the agreement between you * and the party authorised by Arm China to disclose this file to you. * The confidential and proprietary information contained in this file * may only be used by a person authorised under and to the extent permitted * by a subsisting licensing agreement from Arm China. * * (C) Copyright 2020 Arm Technology (China) Co. Ltd. * All rights reserved. * * This entire notice must be reproduced on all copies of this file and copies of * this file may only be made by a person if such person is permitted to do so * under the terms of a subsisting license agreement from Arm China. * *********************************************************************************/ /** * @file job_base.cpp * @brief AIPU User Mode Driver (UMD) job base module implementation */ #include <cstring> #include <assert.h> #include "job_base.h" #include "utils/helper.h" aipudrv::JobBase::JobBase(const GraphBase& graph, DeviceBase* dev): m_graph(graph), m_dev(dev) { m_mem = m_dev->get_mem(); m_rodata.reset(); m_descriptor.reset(); } aipudrv::JobBase::~JobBase() { } aipu_status_t aipudrv::JobBase::get_status(aipu_job_status_t* status) { aipu_status_t ret = AIPU_STATUS_SUCCESS; std::vector<aipu_job_status_desc> jobs_status; ret = convert_ll_status(m_dev->get_status(jobs_status, 1)); if (ret != AIPU_STATUS_SUCCESS) { return ret; } if (jobs_status.size() != 0) { m_status = jobs_status[0].state; } if ((m_status == AIPU_JOB_STATUS_DONE) || (m_status == AIPU_JOB_STATUS_EXCEPTION)) { *status = (aipu_job_status_t)m_status; dump_job_private_buffers_after_run(m_rodata, m_descriptor); } else { *status = AIPU_JOB_STATUS_NO_STATUS; } return ret; } aipu_status_t aipudrv::JobBase::get_status_blocking(aipu_job_status_t* status, int32_t time_out) { aipu_status_t ret = AIPU_STATUS_SUCCESS; std::vector<aipu_job_status_desc> jobs_status; ret = convert_ll_status(m_dev->poll_status(jobs_status, 1, time_out, true)); if (ret != AIPU_STATUS_SUCCESS) { return ret; } if (jobs_status.size() != 0) { m_status = jobs_status[0].state; } if ((m_status == AIPU_JOB_STATUS_DONE) || (m_status == AIPU_JOB_STATUS_EXCEPTION)) { *status = (aipu_job_status_t)m_status; dump_job_private_buffers_after_run(m_rodata, m_descriptor); } else { *status = AIPU_JOB_STATUS_NO_STATUS; } return ret; } aipu_status_t aipudrv::JobBase::load_tensor(uint32_t tensor, const void* data) { if (nullptr == data) { return AIPU_STATUS_ERROR_NULL_PTR; } if (tensor >= m_inputs.size()) { return AIPU_STATUS_ERROR_INVALID_TENSOR_ID; } /* Applications cannot load tensors if a job is not in the to-be-scheduled status */ if ((m_status != AIPU_JOB_STATUS_INIT) && (m_status != AIPU_JOB_STATUS_DONE) && (m_status != AIPU_JOB_STATUS_BIND)) { return AIPU_STATUS_ERROR_INVALID_OP; } assert(m_mem->write(m_inputs[tensor].pa, (const char*)data, m_inputs[tensor].size) == (int)m_inputs[tensor].size); return AIPU_STATUS_SUCCESS; } aipu_status_t aipudrv::JobBase::get_tensor(aipu_tensor_type_t type, uint32_t tensor, void* data) { DEV_PA_64 pa = 0; uint64_t size = 0; if (nullptr == data) { return AIPU_STATUS_ERROR_NULL_PTR; } /* Applications cannot get tensors if a job is not done status */ if (m_status != AIPU_JOB_STATUS_DONE) { return AIPU_STATUS_ERROR_INVALID_OP; } if (AIPU_TENSOR_TYPE_INPUT == type) { if (tensor >= m_inputs.size()) { return AIPU_STATUS_ERROR_INVALID_TENSOR_ID; } pa = m_inputs[tensor].pa; size = m_inputs[tensor].size; } else if (AIPU_TENSOR_TYPE_OUTPUT == type) { if (tensor >= m_outputs.size()) { return AIPU_STATUS_ERROR_INVALID_TENSOR_ID; } pa = m_outputs[tensor].pa; size = m_outputs[tensor].size; } else if (AIPU_TENSOR_TYPE_PRINTF == type) { if (tensor >= m_printf.size()) { return AIPU_STATUS_ERROR_INVALID_TENSOR_ID; } pa = m_printf[tensor].pa; size = m_printf[tensor].size; } else if (AIPU_TENSOR_TYPE_PROFILER == type) { if (tensor >= m_profiler.size()) { return AIPU_STATUS_ERROR_INVALID_TENSOR_ID; } pa = m_profiler[tensor].pa; size = m_profiler[tensor].size; } assert(m_mem->read(pa, (char*)data, size) == (int)size); return AIPU_STATUS_SUCCESS; } aipu_status_t aipudrv::JobBase::setup_rodata( const std::vector<struct GraphParamMapLoadDesc>& param_map, const std::vector<BufferDesc>& reuse_buf, const std::vector<BufferDesc>& static_buf, BufferDesc rodata, BufferDesc dcr ) { aipu_status_t ret = AIPU_STATUS_SUCCESS; char* ro_va = nullptr; char* dcr_va = nullptr; m_mem->pa_to_va(rodata.pa, rodata.size, &ro_va); if (dcr.size != 0) { m_mem->pa_to_va(dcr.pa, dcr.size, &dcr_va); } for (uint32_t i = 0; i < param_map.size(); i++) { char* entry = nullptr; uint32_t init_val = 0; uint32_t finl_val = 0; uint32_t ref_iter = param_map[i].ref_section_iter; uint32_t sec_offset = param_map[i].sub_section_offset; uint32_t sub_sec_pa_32 = 0; if (param_map[i].offset_in_map < rodata.req_size) { entry = ro_va + param_map[i].offset_in_map; } else { if (dcr.size == 0) { ret = AIPU_STATUS_ERROR_INVALID_GBIN; goto finish; } entry = dcr_va + param_map[i].offset_in_map - rodata.req_size; } if (param_map[i].load_type == PARAM_MAP_LOAD_TYPE_REUSE) { if (ref_iter >= reuse_buf.size()) { ret = AIPU_STATUS_ERROR_INVALID_SIZE; goto finish; } sub_sec_pa_32 = get_low_32(reuse_buf[ref_iter].pa) + sec_offset; } else if (param_map[i].load_type == PARAM_MAP_LOAD_TYPE_STATIC) { if (ref_iter >= static_buf.size()) { ret = AIPU_STATUS_ERROR_INVALID_SIZE; goto finish; } sub_sec_pa_32 = get_low_32(static_buf[ref_iter].pa + sec_offset); } memcpy(&init_val, entry, 4); finl_val = ((sub_sec_pa_32 & param_map[i].addr_mask) | (init_val & (~param_map[i].addr_mask))); memcpy(entry, &finl_val, 4); LOG(LOG_CLOSE, "param %u: write addr/final_val 0x%x/0x%x (%s section %u offset 0x%x) into %s", i, sub_sec_pa_32, finl_val, (param_map[i].load_type == PARAM_MAP_LOAD_TYPE_REUSE) ? "reuse" : "weight", ref_iter, sec_offset, (param_map[i].offset_in_map < rodata.req_size) ? "rodata" : "descriptor"); } finish: return ret; } aipudrv::DEV_PA_64 aipudrv::JobBase::get_base_pa(int sec_type, BufferDesc& rodata, BufferDesc& descriptor) { DEV_PA_64 pa = 0; if (sec_type == SECTION_TYPE_RODATA) { pa = rodata.pa; } else if (sec_type == SECTION_TYPE_DESCRIPTOR) { pa = descriptor.pa; } else if (sec_type == SECTION_TYPE_TEXT) { pa = get_graph().m_text.pa; } return pa; } void aipudrv::JobBase::setup_remap(BufferDesc& rodata, BufferDesc& descriptor) { for (uint32_t i = 0; i < get_graph().m_remap.size(); i++) { DEV_PA_64 dest = get_base_pa(get_graph().m_remap[i].type, rodata, descriptor) + get_graph().m_remap[i].next_addr_entry_offset; DEV_PA_32 pa = get_base_pa(get_graph().m_remap[i].next_type, rodata, descriptor) + get_graph().m_remap[i].next_offset; assert(m_mem->write32(dest, pa) == 4); } } void aipudrv::JobBase::create_io_buffers(std::vector<struct JobIOBuffer>& bufs, const std::vector<GraphIOTensorDesc>& desc, const std::vector<BufferDesc>& reuses) { uint32_t cnt = desc.size(); for (uint32_t i = 0; i < cnt; i++) { uint32_t sec_iter = desc[i].ref_section_iter; DEV_PA_64 pa = reuses[sec_iter].pa + desc[i].offset_in_section; JobIOBuffer iobuf; iobuf.init(desc[i].id, desc[i].size, pa); bufs.push_back(iobuf); } } void aipudrv::JobBase::create_io_buffers(const struct GraphIOTensors& io, const std::vector<BufferDesc>& reuses) { create_io_buffers(m_inputs, io.inputs, reuses); create_io_buffers(m_outputs, io.outputs, reuses); create_io_buffers(m_inter_dumps, io.inter_dumps, reuses); create_io_buffers(m_profiler, io.profiler, reuses); create_io_buffers(m_printf, io.printf, reuses); create_io_buffers(m_layer_counter, io.layer_counter, reuses); } void aipudrv::JobBase::dump_buffer(DEV_PA_64 pa, const char* bin_va, uint32_t size, const char* name) { char file_name[4096]; if (bin_va != nullptr) { snprintf(file_name, 4096, "%s/Graph_0x%lx_Job_0x%lx_%s_Dump_in_Binary_Size_0x%x.bin", m_dump_dir.c_str(), get_graph().m_id, m_id, name, size); umd_dump_file_helper(file_name, bin_va, size); } snprintf(file_name, 4096, "%s/Graph_0x%lx_Job_0x%lx_%s_Dump_in_DRAM_PA_0x%lx_Size_0x%x.bin", m_dump_dir.c_str(), get_graph().m_id, m_id, name, pa, size); m_mem->dump_file(pa, file_name, size); } aipu_status_t aipudrv::JobBase::config_mem_dump(uint64_t types, const aipu_job_config_dump_t* config) { aipu_status_t ret = AIPU_STATUS_SUCCESS; if ((nullptr != config) && (nullptr != config->dump_dir)) { m_dump_dir = config->dump_dir; } if ((nullptr != config) && (nullptr != config->prefix)) { m_dump_prefix = config->prefix; } m_dump_text = types & AIPU_JOB_CONFIG_TYPE_DUMP_TEXT; m_dump_weight = types & AIPU_JOB_CONFIG_TYPE_DUMP_WEIGHT; m_dump_rodata = types & AIPU_JOB_CONFIG_TYPE_DUMP_RODATA; m_dump_dcr = types & AIPU_JOB_CONFIG_TYPE_DUMP_DESCRIPTOR; m_dump_input = types & AIPU_JOB_CONFIG_TYPE_DUMP_INPUT; m_dump_output = types & AIPU_JOB_CONFIG_TYPE_DUMP_OUTPUT; m_dump_tcb = types & AIPU_JOB_CONFIG_TYPE_DUMP_TCB_CHAIN; m_dump_emu = types & AIPU_JOB_CONFIG_TYPE_DUMP_EMULATION; return ret; } void aipudrv::JobBase::dump_job_shared_buffers() { DEV_PA_64 dump_pa; uint32_t dump_size; const char* bin_va = nullptr; if (m_dump_text) { dump_pa = get_graph().m_text.pa; bin_va = get_graph().m_btext.va; dump_size = get_graph().m_btext.size; dump_buffer(dump_pa, bin_va, dump_size, "Text"); } if (m_dump_weight) { dump_pa = get_graph().m_weight.pa; bin_va = get_graph().m_bweight.va; dump_size = get_graph().m_bweight.size; if (dump_size != 0) { dump_buffer(dump_pa, bin_va, dump_size, "Weight"); } } } void aipudrv::JobBase::dump_job_private_buffers(BufferDesc& rodata, BufferDesc& descriptor) { DEV_PA_64 dump_pa; uint32_t dump_size; const char* bin_va = nullptr; if (m_dump_rodata) { dump_pa = rodata.pa; bin_va = get_graph().m_brodata.va; dump_size = get_graph().m_brodata.size; if (dump_size != 0) { dump_buffer(dump_pa, bin_va, dump_size, "Rodata"); } } if (m_dump_dcr) { dump_pa = descriptor.pa; bin_va = get_graph().m_bdesc.va; dump_size = get_graph().m_bdesc.size; if (dump_size != 0) { dump_buffer(dump_pa, bin_va, dump_size, "Descriptor"); } } if (m_dump_input) { for (uint32_t i = 0; i < m_inputs.size(); i++) { char name[32]; dump_pa = m_inputs[i].pa; dump_size = m_inputs[i].size; snprintf(name, 32, "Input%u", m_inputs[i].id); if (dump_size != 0) { dump_buffer(dump_pa, nullptr, dump_size, name); } } } } void aipudrv::JobBase::dump_job_private_buffers_after_run(BufferDesc& rodata, BufferDesc& descriptor) { DEV_PA_64 dump_pa; uint32_t dump_size; if (m_dump_output) { for (uint32_t i = 0; i < m_outputs.size(); i++) { char name[32]; dump_pa = m_outputs[i].pa; dump_size = m_outputs[i].size; snprintf(name, 32, "Output%u", m_outputs[i].id); if (dump_size != 0) { dump_buffer(dump_pa, nullptr, dump_size, name); } } } } aipu_status_t aipudrv::JobBase::validate_schedule_status() { if ((m_status == AIPU_JOB_STATUS_INIT) || (m_status == AIPU_JOB_STATUS_DONE)) { return AIPU_STATUS_SUCCESS; } return AIPU_STATUS_ERROR_INVALID_OP; }
28.943478
103
0.614842
dejsha01
94dd9e840b5fa259bc99a63f5aa06f9894a5fe09
652
hpp
C++
src/standard/bits/DD_GetPackBack.hpp
iDingDong/libDDCPP-old
841260fecc84330ff3bfffba7263f5318f0b4655
[ "BSD-3-Clause" ]
1
2018-06-01T03:29:34.000Z
2018-06-01T03:29:34.000Z
src/standard/bits/DD_GetPackBack.hpp
iDingDong/libDDCPP-old
841260fecc84330ff3bfffba7263f5318f0b4655
[ "BSD-3-Clause" ]
null
null
null
src/standard/bits/DD_GetPackBack.hpp
iDingDong/libDDCPP-old
841260fecc84330ff3bfffba7263f5318f0b4655
[ "BSD-3-Clause" ]
null
null
null
// DDCPP/standard/bits/DD_GetPackBack.hpp #ifndef DD_GET_PACK_BACK_HPP_INCLUDED_ # define DD_GET_PACK_BACK_HPP_INCLUDED_ 1 # if __cplusplus < 201103L # error ISO/IEC 14882:2011 or a later version support is required for'DD::GetPackBack'. # endif # include "DD_global_definitions.hpp" DD_BEGIN_ template <typename ObjectT_, typename... ObjectsT_> struct GetPackBack : GetPackBack<ObjectsT_...> { }; template <typename ObjectT_> struct GetPackBack<ObjectT_> { using Type = ObjectT_; }; template <typename ObjectT_, typename... ObjectsT_> using GetPackBackType = typename GetPackBack<ObjectT_, ObjectsT_...>::Type; DD_END_ #endif
15.162791
88
0.76227
iDingDong
94de103ab215f5bd98846c02496034e16e52e1d8
3,134
cpp
C++
src/GdfEdit2/MainFrm.cpp
hogsy/xtread
9d4eaf2778b8b687256788c7617b19542986bf32
[ "MIT" ]
1
2019-07-20T12:10:20.000Z
2019-07-20T12:10:20.000Z
src/GdfEdit2/MainFrm.cpp
hogsy/xtread
9d4eaf2778b8b687256788c7617b19542986bf32
[ "MIT" ]
null
null
null
src/GdfEdit2/MainFrm.cpp
hogsy/xtread
9d4eaf2778b8b687256788c7617b19542986bf32
[ "MIT" ]
null
null
null
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "GdfEdit2.h" #include "MainFrm.h" #include "Splash.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CCJMDIFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CCJMDIFrameWnd) //{{AFX_MSG_MAP(CMainFrame) ON_WM_CREATE() ON_WM_CLOSE() //}}AFX_MSG_MAP END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, ID_SEPARATOR, // status line indicator ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; ///////////////////////////////////////////////////////////////////////////// // CMainFrame construction/destruction CMainFrame::CMainFrame() { } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndToolBar.Create(this, WS_CHILD | WS_VISIBLE | CBRS_TOOLTIPS | CBRS_TOP | CBRS_FLYBY | CBRS_SIZE_DYNAMIC, IDR_MAINFRAME) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } if (!m_wndOptionsBar.Create(this, WS_CHILD | WS_VISIBLE | CBRS_TOOLTIPS | CBRS_TOP | CBRS_FLYBY | CBRS_SIZE_DYNAMIC, IDR_TOOLBAR_TOOLS) || !m_wndOptionsBar.LoadToolBar(IDR_TOOLBAR_TOOLS)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); m_wndOptionsBar.EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndOptionsBar); // install/load cool menus m_menuManager.Install(this); m_menuManager.LoadToolbar(IDR_MAINFRAME); m_menuManager.LoadToolbar(IDR_TOOLBAR_TOOLS); LoadBarState(_T("Docking\\GDFEdit2")); // CG: The following line was added by the Splash Screen component. CGdfEdit2App* pApp = (CGdfEdit2App*)AfxGetApp(); pApp->AttachStatusBar(&m_wndStatusBar); m_wndStatusBar.SetPaneInfo(1, ID_SEPARATOR, SBPS_NORMAL, 64); m_wndStatusBar.SetPaneText(1, ""); CSplashWnd::ShowSplashScreen(this); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CCJMDIFrameWnd::PreCreateWindow(cs) ) return FALSE; return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CCJMDIFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CCJMDIFrameWnd::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CMainFrame message handlers void CMainFrame::OnClose() { // TODO: Add your message handler code here and/or call default SaveBarState(_T("Docking\\GDFEdit2")); CCJMDIFrameWnd::OnClose(); }
23.214815
88
0.666879
hogsy
94dffeab13fe3f118ad3cb894df08fa3013e49be
1,758
cpp
C++
gcd_lcm/gcd_sum/abc162_e.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
gcd_lcm/gcd_sum/abc162_e.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
gcd_lcm/gcd_sum/abc162_e.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) using namespace std; using ll = long long; using P = pair<int, int>; /* 参考リンク ABC 162 E - Sum of gcd of Tuples (Hard) https://atcoder.jp/contests/abc162/tasks/abc162_e */ const int mod = 1000000007; struct mint { ll x; // typedef long long ll; mint(ll x = 0) : x((x % mod + mod) % mod) {} mint operator-() const { return mint(-x); } mint& operator+=(const mint a) { if ((x += a.x) >= mod) x -= mod; return *this; } mint& operator-=(const mint a) { if ((x += mod - a.x) >= mod) x -= mod; return *this; } mint& operator*=(const mint a) { (x *= a.x) %= mod; return *this; } mint operator+(const mint a) const { return mint(*this) += a; } mint operator-(const mint a) const { return mint(*this) -= a; } mint operator*(const mint a) const { return mint(*this) *= a; } mint pow(ll t) const { if (!t) return 1; mint a = pow(t >> 1); a *= a; if (t & 1) a *= *this; return a; } // for prime mod mint inv() const { return pow(mod - 2); } mint& operator/=(const mint a) { return *this *= a.inv(); } mint operator/(const mint a) const { return mint(*this) /= a; } }; istream& operator>>(istream& is, const mint& a) { return is >> a.x; } ostream& operator<<(ostream& os, const mint& a) { return os << a.x; } int main() { int n, k; cin >> n >> k; mint ans; // d[i]: gcd(A) = iとなる個数 vector<mint> d(k + 1); for (int i = k; i >= 1; --i) { // gcd(A) = iの倍数となる個数を計算 d[i] = mint(k / i).pow(n); for (int j = i * 2; j <= k; j += i) { // iの倍数であり,i自身ではない個数を引く d[i] -= d[j]; } } for (int i = 1; i <= k; ++i) ans += d[i] * i; cout << ans.x << endl; return 0; }
25.114286
69
0.527304
Takumi1122
94eae3b4d50e2696f4c8a78637329bcde007b08c
1,333
cpp
C++
OverlordEditor/Materials/Deferred/DiffuseMaterial_Deferred.cpp
Ruvah/Overlord-Editor
3193b4986b10edb0fa8fdbc493ee3b05fdea217d
[ "Apache-2.0" ]
1
2018-11-28T12:30:13.000Z
2018-11-28T12:30:13.000Z
OverlordEditor/Materials/Deferred/DiffuseMaterial_Deferred.cpp
Ruvah/Overlord-Editor
3193b4986b10edb0fa8fdbc493ee3b05fdea217d
[ "Apache-2.0" ]
null
null
null
OverlordEditor/Materials/Deferred/DiffuseMaterial_Deferred.cpp
Ruvah/Overlord-Editor
3193b4986b10edb0fa8fdbc493ee3b05fdea217d
[ "Apache-2.0" ]
2
2019-12-28T12:34:51.000Z
2021-03-08T08:37:33.000Z
#include "stdafx.h" #include "DiffuseMaterial_Deferred.h" #include "..\OverlordEngine\ContentManager.h" #include "..\OverlordEngine\TextureData.h" ID3DX11EffectShaderResourceVariable* DiffuseMaterial_Deferred::m_pDiffuseSRVvariable = nullptr; DiffuseMaterial_Deferred::DiffuseMaterial_Deferred() : Material(L"./Resources/Effects/Deferred/PosNormTex3D_Deferred.fx"), m_pDiffuseTexture(nullptr) { } DiffuseMaterial_Deferred::~DiffuseMaterial_Deferred() { } void DiffuseMaterial_Deferred::SetDiffuseTexture(const std::wstring& assetFile) { m_pDiffuseTexture = ContentManager::Load<TextureData>(assetFile); } void DiffuseMaterial_Deferred::LoadEffectVariables() { if (!m_pDiffuseSRVvariable) { m_pDiffuseSRVvariable = GetEffect()->GetVariableByName("gDiffuseMap")->AsShaderResource(); if (!m_pDiffuseSRVvariable->IsValid()) { Logger::LogWarning(L"DiffuseMaterial::LoadEffectVariables() > \'gDiffuseMap\' variable not found!"); m_pDiffuseSRVvariable = nullptr; } } } void DiffuseMaterial_Deferred::UpdateEffectVariables(const GameContext& gameContext, ModelComponent* pModelComponent) { UNREFERENCED_PARAMETER(gameContext); UNREFERENCED_PARAMETER(pModelComponent); if (m_pDiffuseTexture && m_pDiffuseSRVvariable) { m_pDiffuseSRVvariable->SetResource(m_pDiffuseTexture->GetShaderResourceView()); } }
26.66
117
0.80045
Ruvah
94f66dbf8aed330a17508647a1740f8b220076e0
4,597
cpp
C++
host/run.cpp
Zottel/opencl_scad_experiment
9226de57b05958f0299de5c2b7a8c197590f1500
[ "Apache-2.0" ]
null
null
null
host/run.cpp
Zottel/opencl_scad_experiment
9226de57b05958f0299de5c2b7a8c197590f1500
[ "Apache-2.0" ]
null
null
null
host/run.cpp
Zottel/opencl_scad_experiment
9226de57b05958f0299de5c2b7a8c197590f1500
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 Julius Roob <julius@juliusroob.de> // // 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 <cstdio> #include <cstdlib> #include <vector> #include <string> #include <list> #include <iostream> #include <fstream> #include <thread> #include <chrono> #define CL_USE_DEPRECATED_OPENCL_1_2_APIS #define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #include "util.hpp" #include "machine.hpp" #include "assembly.hpp" #include "common/instructions.h" using namespace scad; void print_scad_vector(std::vector<scad_data, AlignedAllocator<scad_data>> data) { std::cout << std::hex << "["; bool first = true; for(auto const& value: data) { if(first) { first = false; } else { std::cout << ", "; } std::cout << value.integer; } std::cout << "]"; } int main (int argc, char *argv[]) { // Have openCL kernels not buffer debug messages. setbuf(stdout, NULL); std::vector<std::string> args(argv+1, argv+argc); std::string description_filename = "", aocx_filename = "", assembly_filename = ""; switch(args.size()) { case 3: description_filename = args[0]; aocx_filename = args[1]; assembly_filename = args[2]; break; default: std::cerr << "usage: run <processor_description> <processor_aocx> <assembly program>" << std::endl; exit(1); } // Processor description is used by assembler to map unit names to addresses. processor_description proc(description_filename); // Read assembly program into string. std::ifstream assembly_stream(assembly_filename); std::string assembly_src((std::istreambuf_iterator<char>(assembly_stream)), std::istreambuf_iterator<char>()); // Parse and link assembly source into vector of scad instructions. scad::assembly assembly(proc); assembly.parse(assembly_src); std::vector<struct scad_instruction> prog_unaligned = assembly.build(); // Align program for transfer to buffer. std::vector<struct scad_instruction, AlignedAllocator<struct scad_instruction>> prog; // Copy unaligned to aligned memory. std::copy(prog_unaligned.begin(), prog_unaligned.end(), std::back_inserter(prog)); // Only run on FPGA platform. #if AOC_VERSION == 17 cl::Platform platform = cl_find_platform("Intel(R) FPGA SDK for OpenCL(TM)"); #else cl::Platform platform = cl_find_platform("Altera SDK for OpenCL"); #endif std::vector<cl::Device> devices; platform.getDevices(CL_DEVICE_TYPE_ALL, &devices); scad::machine machine(platform, devices[0], aocx_filename); // TODO: Temporary workaround to get emulator to run workgroup. // Normally, the interconnect should be an autorun kernel. if(machine.has_component("interconnect")) { machine.get_component("interconnect")->start(); } // INPUT/OUTPUT MEMORY std::vector<scad_data, AlignedAllocator<scad_data>> data(256, (scad_data){.integer = 0}); //for(size_t i = 0; i < data.size(); i++) data[i] = (scad_data){.integer = i}; std::cout << "input: "; print_scad_vector(data); std::cout << std::endl; auto data_buff = machine.buffer_for(CL_MEM_READ_ONLY, data); auto lsu = machine.get_component("lsu"); lsu->write_buffer(data_buff, data); std::cout << "starting data buffer transfer" << std::endl; lsu->start(data_buff, (cl_uint) data.size()); std::cout << "starting lsu" << std::endl; // Finally - execute our program. auto control = machine.get_component("cu"); auto prog_buff = machine.buffer_for(prog); std::cout << "starting program buffer transfer" << std::endl; control->write_buffer(prog_buff, prog); std::cout << "control unit: start" << std::endl; control->start(prog_buff, (cl_uint) prog.size()); std::cout << "starting data transfer back" << std::endl; lsu->read_buffer(data_buff, data); std::cout << "data transfer back done" << std::endl; lsu->wait(); std::cout << "lsu unit: wait" << std::endl; // Print output to stdout. // TODO: write to file. std::cout << "output: "; print_scad_vector(data); std::cout << std::endl; control->wait(); std::cout << "control unit: done" << std::endl; }
30.443709
88
0.693061
Zottel
94fbde35b52820a84c9cf9ae1cf170b361c1b524
3,266
cpp
C++
source/unit_tests/regex_crossword_solver_exception.unit_tests.cpp
antoine-trux/regex-crossword-solver
3d4cfe3b973e44f5250f5438ce6b4b696ecd3cd7
[ "MIT" ]
6
2016-10-28T10:24:47.000Z
2021-02-23T00:44:02.000Z
source/unit_tests/regex_crossword_solver_exception.unit_tests.cpp
antoine-trux/regex-crossword-solver
3d4cfe3b973e44f5250f5438ce6b4b696ecd3cd7
[ "MIT" ]
null
null
null
source/unit_tests/regex_crossword_solver_exception.unit_tests.cpp
antoine-trux/regex-crossword-solver
3d4cfe3b973e44f5250f5438ce6b4b696ecd3cd7
[ "MIT" ]
2
2017-03-09T09:19:29.000Z
2021-02-23T00:44:13.000Z
// Copyright (c) 2016 Antoine Trux // // The original version is available at // http://solving-regular-expression-crosswords.blogspot.com // // 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, the above original version 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 "disable_warnings_from_gtest.hpp" #include "regex_crossword_solver_exception.hpp" #include "regex_crossword_solver_test.hpp" using namespace std; class RegexCrosswordSolverExceptionTest : public RegexCrosswordSolverTest { }; TEST_F(RegexCrosswordSolverExceptionTest, alphabet_exception) { AlphabetException exc("error message"); EXPECT_STREQ("ERROR:\n" " error message", exc.what()); } TEST_F(RegexCrosswordSolverExceptionTest, command_line_exception) { CommandLineException exc("error message"); EXPECT_STREQ("ERROR:\n" " error message\n" "\n" "For information on command line usage:\n" " program --help", exc.what()); } TEST_F(RegexCrosswordSolverExceptionTest, grid_structure_exception) { GridStructureException exc("error message"); EXPECT_STREQ("ERROR:\n" " error message", exc.what()); } TEST_F(RegexCrosswordSolverExceptionTest, input_file_exception_1) { InputFileException exc("error message"); EXPECT_STREQ("ERROR:\n" " error message", exc.what()); } TEST_F(RegexCrosswordSolverExceptionTest, input_file_exception_2) { InputFileException exc("path/to/file", 10, "line content", "error message"); EXPECT_STREQ("ERROR:\n" " in 'path/to/file', line 10:\n" " 'line content'\n" " error message", exc.what()); } TEST_F(RegexCrosswordSolverExceptionTest, regex_parse_exception) { const size_t error_position = 1; RegexParseException exc("some error message", "ABC", error_position); EXPECT_STREQ("ERROR:\n" " some error message:\n" " 'ABC'\n" " ^", exc.what()); } TEST_F(RegexCrosswordSolverExceptionTest, regex_structure_exception) { RegexStructureException exc("error message"); EXPECT_STREQ("ERROR:\n" " error message", exc.what()); }
34.378947
80
0.687385
antoine-trux
94fe68fb560050eadd38c624aa3e1cc23bc01ec3
9,644
cc
C++
fuzzers/tint_regex_fuzzer/regex_fuzzer_tests.cc
haocxy/mirror-googlesource-dawn-tint
44a0adf9b47c22a7b2f392f30aaf59811f56d6ee
[ "Apache-2.0" ]
null
null
null
fuzzers/tint_regex_fuzzer/regex_fuzzer_tests.cc
haocxy/mirror-googlesource-dawn-tint
44a0adf9b47c22a7b2f392f30aaf59811f56d6ee
[ "Apache-2.0" ]
null
null
null
fuzzers/tint_regex_fuzzer/regex_fuzzer_tests.cc
haocxy/mirror-googlesource-dawn-tint
44a0adf9b47c22a7b2f392f30aaf59811f56d6ee
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The Tint 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 <string> #include "gtest/gtest.h" #include "fuzzers/tint_regex_fuzzer/wgsl_mutator.h" namespace tint { namespace fuzzers { namespace regex_fuzzer { namespace { // Swaps two non-consecutive regions in the edge TEST(SwapRegionsTest, SwapIntervalsEdgeNonConsecutive) { std::string R1 = ";region1;", R2 = ";regionregion2;", R3 = ";regionregionregion3;"; std::string all_regions = R1 + R2 + R3; // this call should swap R1 with R3. SwapIntervals(0, R1.length(), R1.length() + R2.length(), R3.length(), all_regions); ASSERT_EQ(R3 + R2 + R1, all_regions); } // Swaps two non-consecutive regions not in the edge TEST(SwapRegionsTest, SwapIntervalsNonConsecutiveNonEdge) { std::string R1 = ";region1;", R2 = ";regionregion2;", R3 = ";regionregionregion3;", R4 = ";regionregionregionregion4;", R5 = ";regionregionregionregionregion5;"; std::string all_regions = R1 + R2 + R3 + R4 + R5; // this call should swap R2 with R4. SwapIntervals(R1.length(), R2.length(), R1.length() + R2.length() + R3.length(), R4.length(), all_regions); ASSERT_EQ(R1 + R4 + R3 + R2 + R5, all_regions); } // Swaps two consecutive regions not in the edge (sorrounded by other // regions) TEST(SwapRegionsTest, SwapIntervalsConsecutiveEdge) { std::string R1 = ";region1;", R2 = ";regionregion2;", R3 = ";regionregionregion3;", R4 = ";regionregionregionregion4;", R5 = ";regionregionregionregionregion5;"; std::string all_regions = R1 + R2 + R3 + R4; // this call should swap R2 with R3. SwapIntervals(R1.length(), R2.length(), R1.length() + R2.length(), R3.length(), all_regions); ASSERT_EQ(R1 + R3 + R2 + R4, all_regions); } // Swaps two consecutive regions not in the edge (not sorrounded by other // regions) TEST(SwapRegionsTest, SwapIntervalsConsecutiveNonEdge) { std::string R1 = ";region1;", R2 = ";regionregion2;", R3 = ";regionregionregion3;", R4 = ";regionregionregionregion4;", R5 = ";regionregionregionregionregion5;"; std::string all_regions = R1 + R2 + R3 + R4 + R5; // this call should swap R4 with R5. SwapIntervals(R1.length() + R2.length() + R3.length(), R4.length(), R1.length() + R2.length() + R3.length() + R4.length(), R5.length(), all_regions); ASSERT_EQ(R1 + R2 + R3 + R5 + R4, all_regions); } // Deletes the first region. TEST(DeleteRegionTest, DeleteFirstRegion) { std::string R1 = ";region1;", R2 = ";regionregion2;", R3 = ";regionregionregion3;", R4 = ";regionregionregionregion4;", R5 = ";regionregionregionregionregion5;"; std::string all_regions = R1 + R2 + R3 + R4 + R5; // This call should delete R1. DeleteInterval(0, R1.length(), all_regions); ASSERT_EQ(";" + R2 + R3 + R4 + R5, all_regions); } // Deletes the last region. TEST(DeleteRegionTest, DeleteLastRegion) { std::string R1 = ";region1;", R2 = ";regionregion2;", R3 = ";regionregionregion3;", R4 = ";regionregionregionregion4;", R5 = ";regionregionregionregionregion5;"; std::string all_regions = R1 + R2 + R3 + R4 + R5; // This call should delete R5. DeleteInterval(R1.length() + R2.length() + R3.length() + R4.length(), R5.length(), all_regions); ASSERT_EQ(R1 + R2 + R3 + R4 + ";", all_regions); } // Deletes the middle region. TEST(DeleteRegionTest, DeleteMiddleRegion) { std::string R1 = ";region1;", R2 = ";regionregion2;", R3 = ";regionregionregion3;", R4 = ";regionregionregionregion4;", R5 = ";regionregionregionregionregion5;"; std::string all_regions = R1 + R2 + R3 + R4 + R5; // This call should delete R3. DeleteInterval(R1.length() + R2.length(), R3.length(), all_regions); ASSERT_EQ(R1 + R2 + ";" + R4 + R5, all_regions); } TEST(InsertRegionTest, InsertRegionTest1) { std::string R1 = ";region1;", R2 = ";regionregion2;", R3 = ";regionregionregion3;", R4 = ";regionregionregionregion4;", R5 = ";regionregionregionregionregion5;"; std::string all_regions = R1 + R2 + R3 + R4 + R5; // This call should insert R2 after R4. DuplicateInterval(R1.length(), R2.length(), R1.length() + R2.length() + R3.length() + R4.length() - 1, all_regions); ASSERT_EQ(R1 + R2 + R3 + R4 + R2.substr(1, R2.size() - 1) + R5, all_regions); } TEST(InsertRegionTest, InsertRegionTest2) { std::string R1 = ";region1;", R2 = ";regionregion2;", R3 = ";regionregionregion3;", R4 = ";regionregionregionregion4;", R5 = ";regionregionregionregionregion5;"; std::string all_regions = R1 + R2 + R3 + R4 + R5; // This call should insert R3 after R1. DuplicateInterval(R1.length() + R2.length(), R3.length(), R1.length() - 1, all_regions); ASSERT_EQ(R1 + R3.substr(1, R3.length() - 1) + R2 + R3 + R4 + R5, all_regions); } TEST(InsertRegionTest, InsertRegionTest3) { std::string R1 = ";region1;", R2 = ";regionregion2;", R3 = ";regionregionregion3;", R4 = ";regionregionregionregion4;", R5 = ";regionregionregionregionregion5;"; std::string all_regions = R1 + R2 + R3 + R4 + R5; // This call should insert R2 after R5. DuplicateInterval(R1.length(), R2.length(), all_regions.length() - 1, all_regions); ASSERT_EQ(R1 + R2 + R3 + R4 + R5 + R2.substr(1, R2.length() - 1), all_regions); } TEST(ReplaceIdentifierTest, ReplaceIdentifierTest1) { std::string R1 = "|region1|", R2 = "; region2;", R3 = "---------region3---------", R4 = "++region4++", R5 = "***region5***"; std::string all_regions = R1 + R2 + R3 + R4 + R5; // Replaces R3 with R1. ReplaceRegion(0, R1.length(), R1.length() + R2.length(), R3.length(), all_regions); ASSERT_EQ(R1 + R2 + R1 + R4 + R5, all_regions); } TEST(ReplaceIdentifierTest, ReplaceIdentifierTest2) { std::string R1 = "|region1|", R2 = "; region2;", R3 = "---------region3---------", R4 = "++region4++", R5 = "***region5***"; std::string all_regions = R1 + R2 + R3 + R4 + R5; // Replaces R5 with R3. ReplaceRegion(R1.length() + R2.length(), R3.length(), R1.length() + R2.length() + R3.length() + R4.length(), R5.length(), all_regions); ASSERT_EQ(R1 + R2 + R3 + R4 + R3, all_regions); } TEST(GetIdentifierTest, GetIdentifierTest1) { std::string wgsl_code = "fn clamp_0acf8f() {" "var res: vec2<f32> = clamp(vec2<f32>(), vec2<f32>(), vec2<f32>());}" "[[stage(vertex)]]" "fn vertex_main() -> [[builtin(position)]] vec4<f32> {" " clamp_0acf8f();" " return vec4<f32>();}" "[[stage(fragment)]]" "fn fragment_main() {" " clamp_0acf8f();}" "[[stage(compute), workgroup_size(1)]]" "fn compute_main() {" "var<private> foo: f32 = 0.0;" " clamp_0acf8f();}"; std::vector<std::pair<size_t, size_t>> identifiers_pos = GetIdentifiers(wgsl_code); std::vector<std::pair<size_t, size_t>> ground_truth = { std::make_pair(3, 12), std::make_pair(19, 3), std::make_pair(28, 4), std::make_pair(40, 5), std::make_pair(51, 3), std::make_pair(59, 4), std::make_pair(72, 4), std::make_pair(88, 5), std::make_pair(103, 2), std::make_pair(113, 4), std::make_pair(125, 7), std::make_pair(145, 4), std::make_pair(158, 12), std::make_pair(175, 6), std::make_pair(187, 3), std::make_pair(197, 5), std::make_pair(214, 2), std::make_pair(226, 4), std::make_pair(236, 12), std::make_pair(254, 5), std::make_pair(270, 14), std::make_pair(289, 2), std::make_pair(300, 4), std::make_pair(308, 3), std::make_pair(321, 3), std::make_pair(326, 3), std::make_pair(338, 12)}; ASSERT_EQ(ground_truth, identifiers_pos); } TEST(TestGetLiteralsValues, TestGetLiteralsValues1) { std::string wgsl_code = "fn clamp_0acf8f() {" "var res: vec2<f32> = clamp(vec2<f32>(), vec2<f32>(), vec2<f32>());}" "[[stage(vertex)]]" "fn vertex_main() -> [[builtin(position)]] vec4<f32> {" " clamp_0acf8f();" "var foo_1: i32 = 3;" " return vec4<f32>();}" "[[stage(fragment)]]" "fn fragment_main() {" " clamp_0acf8f();}" "[[stage(compute), workgroup_size(1)]]" "fn compute_main() {" "var<private> foo: f32 = 0.0;" "var foo_2: i32 = 10;" " clamp_0acf8f();}" "foo_1 = 5 + 7;" "var foo_3 : i32 = -20;"; std::vector<std::pair<size_t, size_t>> literals_pos = GetIntLiterals(wgsl_code); std::vector<std::string> ground_truth = {"3", "10", "5", "7", "-20"}; std::vector<std::string> result; for (auto pos : literals_pos) { result.push_back(wgsl_code.substr(pos.first, pos.second)); } ASSERT_EQ(ground_truth, result); } } // namespace } // namespace regex_fuzzer } // namespace fuzzers } // namespace tint
36.11985
80
0.607735
haocxy
94fee021c5db08375ed9717e0bfcf13702b3f5fc
2,365
cpp
C++
game/client/sdk/ios_pitchtextureproxy.cpp
IOSoccer/IOS
f572c993c8c551cb87facfc68388f3dd368d1d9f
[ "MIT" ]
6
2015-02-24T04:25:14.000Z
2016-06-26T16:04:57.000Z
game/client/sdk/ios_pitchtextureproxy.cpp
IOSoccer/IOS
f572c993c8c551cb87facfc68388f3dd368d1d9f
[ "MIT" ]
184
2015-01-01T09:40:16.000Z
2016-06-26T14:18:33.000Z
game/client/sdk/ios_pitchtextureproxy.cpp
IOSoccer/IOS
f572c993c8c551cb87facfc68388f3dd368d1d9f
[ "MIT" ]
5
2015-07-26T10:09:33.000Z
2015-12-29T23:25:35.000Z
#include "cbase.h" #include "BaseAnimatedTextureProxy.h" #include "materialsystem/IMaterial.h" #include "materialsystem/IMaterialVar.h" #include "materialsystem/ITexture.h" #include "tier1/KeyValues.h" #include "toolframework_client.h" #include "sdk_gamerules.h" #include "ProxyEntity.h" #include "materialsystem/IMaterial.h" #include "materialsystem/IMaterialVar.h" #include "materialsystem/ITexture.h" #include "c_ball.h" #include "c_ios_replaymanager.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" class CPitchTextureProxy : public IMaterialProxy { public: CPitchTextureProxy(); ~CPitchTextureProxy(); virtual bool Init(IMaterial *pMaterial, KeyValues *pKeyValues); virtual void OnBind(void *pC_BaseEntity); virtual void Release(); virtual IMaterial *GetMaterial() { return m_pBaseTextureVar->GetOwningMaterial(); } private: IMaterialVar *m_pBaseTextureVar; // variable for our base texture ITexture *m_pDefaultTexture; // default texture ITexture *m_pNewTexture; // default texture }; CPitchTextureProxy::CPitchTextureProxy() { m_pBaseTextureVar = NULL; m_pDefaultTexture = NULL; m_pNewTexture = NULL; } CPitchTextureProxy::~CPitchTextureProxy() { // Do nothing } void CPitchTextureProxy::Release() { m_pBaseTextureVar = NULL; m_pDefaultTexture = NULL; m_pNewTexture = NULL; delete this; } bool CPitchTextureProxy::Init(IMaterial *pMaterial, KeyValues *pKeyValues) { #ifdef ALLPROXIESFAIL return false; #endif // Check for $basetexture variable m_pBaseTextureVar = pMaterial->FindVar( "$basetexture", NULL ); if ( !m_pBaseTextureVar ) return false; // Set default texture and make sure its not an error texture m_pDefaultTexture = m_pBaseTextureVar->GetTextureValue(); if ( IsErrorTexture( m_pDefaultTexture ) ) return false; return true; } void CPitchTextureProxy::OnBind(void *pC_BaseEntity) { // Bail if no base variable if ( !m_pBaseTextureVar ) return; char texture[64]; Q_snprintf(texture, sizeof(texture), "pitch/textures/%s/pitch.vtf", SDKGameRules()->m_szPitchTextureName.Get()); m_pNewTexture = materials->FindTexture(texture, NULL, true); m_pBaseTextureVar->SetTextureValue(m_pNewTexture); //GetMaterial()->RecomputeStateSnapshots(); } EXPOSE_INTERFACE(CPitchTextureProxy, IMaterialProxy, "PitchTexture" IMATERIAL_PROXY_INTERFACE_VERSION);
25.706522
113
0.770402
IOSoccer
a2000b23b7e72954683d774af2745d9516d0a567
971
cpp
C++
test/test_auto_buffer.cpp
yiyuanzhong/flinter
c52655ea5f8e48244fdb59bdf34b915faee57a6e
[ "Apache-2.0" ]
29
2016-01-29T09:31:09.000Z
2021-07-11T12:00:31.000Z
test/test_auto_buffer.cpp
yiyuanzhong/flinter
c52655ea5f8e48244fdb59bdf34b915faee57a6e
[ "Apache-2.0" ]
2
2015-03-30T09:59:51.000Z
2017-03-13T09:35:18.000Z
test/test_auto_buffer.cpp
yiyuanzhong/flinter
c52655ea5f8e48244fdb59bdf34b915faee57a6e
[ "Apache-2.0" ]
17
2015-03-28T09:24:53.000Z
2021-08-07T10:09:10.000Z
#include <gtest/gtest.h> #include <stdio.h> #include <vector> #include <flinter/types/auto_buffer.h> #include <flinter/logger.h> TEST(AutoBufferTest, TestCompileWithType) { LOG(INFO) << "BEGIN"; flinter::AutoBuffer<char> buffer(128 * 1024 * 1024); char *p = buffer.get(); printf("%p\n", p); buffer[0] = 'a'; buffer[1] = '\0'; printf("%s\n", &buffer[0]); LOG(INFO) << "END"; } TEST(AutoBufferTest, TestCompileWithoutType) { LOG(INFO) << "BEGIN"; flinter::AutoBuffer<> buffer(128 * 1024 * 1024); unsigned char *p = buffer.get(); printf("%p\n", p); buffer[0] = 'a'; buffer[1] = '\0'; printf("%s\n", &buffer[0]); LOG(INFO) << "END"; } TEST(AutoBufferTest, TestComparedToVector) { LOG(INFO) << "BEGIN"; std::vector<char> buffer(128 * 1024 * 1024); char *p = &buffer[0]; printf("%p\n", p); buffer[0] = 'a'; buffer[1] = '\0'; printf("%s\n", &buffer[0]); LOG(INFO) << "END"; }
21.577778
56
0.563337
yiyuanzhong
a20180f2b4b3f7834b8bc0b47dce6d3be0f3138f
21,756
cpp
C++
DT3Android/HAL.cpp
9heart/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2016-01-27T13:17:18.000Z
2019-03-19T09:18:25.000Z
DT3Android/HAL.cpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
1
2016-01-28T14:39:49.000Z
2016-01-28T22:12:07.000Z
DT3Android/HAL.cpp
adderly/DT3
e2605be091ec903d3582e182313837cbaf790857
[ "MIT" ]
3
2016-01-25T16:44:51.000Z
2021-01-29T19:59:45.000Z
//============================================================================== /// /// File: HAL.cpp /// /// Copyright (C) 2000-2013 by Smells Like Donkey, 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 "DT3Android/HAL.hpp" #include "DT3Core/System/StaticInitializer.hpp" #include "DT3Core/Types/FileBuffer/FilePath.hpp" #include "DT3Core/Types/Utility/DisplayMode.hpp" #include "DT3Core/Types/Utility/Error.hpp" #include "DT3Core/Types/Utility/MoreStrings.hpp" #include "DT3Core/Types/Utility/Assert.hpp" #include "DT3Core/Types/Utility/ConsoleStream.hpp" #include "DT3Core/Types/Network/URL.hpp" #include "DT3Core/System/Globals.hpp" #include <thread> #include <sys/time.h> #include <android/log.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #define LOG_TAG "JNI" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) //============================================================================== //============================================================================== namespace DT3 { //============================================================================== //============================================================================== GLOBAL_STATIC_INITIALIZATION(0,HAL::initialize()) GLOBAL_STATIC_DESTRUCTION(0,HAL::destroy()) //============================================================================== //============================================================================== JavaVM* gJavaVM = NULL; jobject gJavaObjActivity; jobject gJavaObjContext; //============================================================================== //============================================================================== jclass load_class (JNIEnv* env, const char *clazz) { jclass c_activity = env->GetObjectClass(gJavaObjActivity); ASSERT(c_activity); jclass c_class_loader = env->FindClass("java/lang/ClassLoader"); ASSERT(c_class_loader); jmethodID m_get_class_loader = env->GetMethodID(c_activity, "getClassLoader", "()Ljava/lang/ClassLoader;"); ASSERT(m_get_class_loader); jobject o_class_loader = env->CallObjectMethod(gJavaObjActivity, m_get_class_loader); ASSERT(o_class_loader); jmethodID m_load_class = env->GetMethodID(c_class_loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;"); ASSERT(m_load_class); jstring o_clazz = env->NewStringUTF(clazz); jclass c_clazz = (jclass)(env->CallObjectMethod(o_class_loader, m_load_class, o_clazz)); ASSERT(c_clazz); return c_clazz; } //============================================================================== //============================================================================== void HAL::initialize (void) { } void HAL::destroy (void) { gJavaVM->DetachCurrentThread(); } //============================================================================== //============================================================================== void HAL::initialize (JavaVM* vm, jobject activity) { gJavaVM = vm; JNIEnv* env = NULL; DTboolean needs_detach = false; int env_stat = gJavaVM->GetEnv( (void**) &env, JNI_VERSION_1_6); if (env_stat == JNI_EDETACHED) { gJavaVM->AttachCurrentThread(&env, 0); needs_detach = true; } ASSERT(env); gJavaObjActivity = env->NewGlobalRef(activity); // Get current context jclass c_activity = env->GetObjectClass(activity); jmethodID m_context = env->GetMethodID(c_activity, "getApplicationContext", "()Landroid/content/Context;"); gJavaObjContext = env->NewGlobalRef(env->CallObjectMethod(activity, m_context)); if (needs_detach) gJavaVM->DetachCurrentThread(); } //============================================================================== //============================================================================== void HAL::log (const std::string &message) { LOGE(message.c_str()); } //============================================================================== //============================================================================== DTdouble HAL::program_running_time(void) { struct timeval now; gettimeofday(&now, NULL); return (DTdouble)( (DTdouble) now.tv_sec + (DTdouble) now.tv_usec/1000000.0); } //============================================================================== //============================================================================== void HAL::run_on_command_line (const std::string &command, const std::vector<std::string> &args) { } //============================================================================== //============================================================================== void HAL::display_modes (std::map<DTint, std::vector<DisplayMode>> &modes) { modes.clear(); } void HAL::switch_display_mode (DTint display, DisplayMode mode) { } void HAL::display_rect (DTint display, DTint &x, DTint &y, DTint &width, DTint &height) { } //============================================================================== //============================================================================== void HAL::launch_browser (const URL &url) { // Java: // final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url)); // _context.startActivity(intent); JNIEnv* env = NULL; DTboolean needs_detach = false; int env_stat = gJavaVM->GetEnv( (void**) &env, JNI_VERSION_1_6); if (env_stat == JNI_EDETACHED) { gJavaVM->AttachCurrentThread(&env, 0); needs_detach = true; } ASSERT(env); jstring o_url = env->NewStringUTF(url.full_url().c_str()); ASSERT(o_url); jclass c_uri = env->FindClass("android/net/Uri"); ASSERT(c_uri); jmethodID m_parse = env->GetStaticMethodID(c_uri, "parse", "(Ljava/lang/String;)Landroid/net/Uri;"); ASSERT(m_parse); jobject o_uri = (jstring) env->CallStaticObjectMethod(c_uri, m_parse, o_url); ASSERT(o_uri); jclass c_intent = env->FindClass("android/content/Intent"); ASSERT(c_intent); jfieldID f_ACTION_VIEW = env->GetStaticFieldID(c_intent, "ACTION_VIEW", "Ljava/lang/String;"); ASSERT(f_ACTION_VIEW); jobject o_ACTION_VIEW = env->GetStaticObjectField(c_intent, f_ACTION_VIEW); ASSERT(o_ACTION_VIEW); jmethodID m_new_intent = env->GetMethodID(c_intent, "<init>", "(Ljava/lang/String;Landroid/net/Uri;)V"); ASSERT(m_new_intent); jobject o_intent = env->AllocObject(c_intent); ASSERT(o_intent); env->CallVoidMethod(o_intent, m_new_intent, o_ACTION_VIEW, o_uri); jclass c_activity = env->FindClass("android/app/Activity"); ASSERT(c_activity); jmethodID m_start_activity = env->GetMethodID(c_activity, "startActivity", "(Landroid/content/Intent;)V"); ASSERT(m_start_activity); env->CallVoidMethod(gJavaObjActivity,m_start_activity,o_intent); if (needs_detach) gJavaVM->DetachCurrentThread(); } //============================================================================== //============================================================================== void HAL::launch_editor (const FilePath &path) { } //============================================================================== //============================================================================== DTuint HAL::num_CPU_cores (void) { return std::thread::hardware_concurrency(); } //============================================================================== //============================================================================== DTboolean HAL::move_file (const FilePath &from, const FilePath &to) { if (link(from.full_path().c_str(), to.full_path().c_str()) == -1) return false; if (unlink(from.full_path().c_str()) == -1) return false; return true; } DTboolean HAL::delete_file (const FilePath &file) { if (unlink(file.full_path().c_str()) == -1) return false; return true; } DTuint64 HAL::modification_date (const FilePath &file) { struct stat buffer; if (stat(file.full_path().c_str(), &buffer)) return 0; return (DTuint) buffer.st_mtime; } DTboolean HAL::is_dir (const FilePath &file) { struct stat buffer; if (stat(file.full_path().c_str(), &buffer)) return 0; return (DTboolean) S_ISDIR(buffer.st_mode); } std::string HAL::path_separator (void) { return "/"; } void HAL::list_directory (const FilePath &pathname, DTboolean recursive, std::vector<FilePath> &paths) { // set up and run platform specific iteration routines // Prime the queue std::list<std::string> dir_queue; dir_queue.push_back(pathname.full_path()); while (dir_queue.size()) { std::string dir = dir_queue.back(); dir_queue.pop_back(); // Build the name list struct dirent **namelist = NULL; DTint n = scandir(dir.c_str(), &namelist, NULL, NULL); // process and free the name list for (DTint i = 0; i < n; ++i) { // Skip invisible files if (namelist[i]->d_name[0] != '.') { if (namelist[i]->d_type == DT_DIR) { std::string entry = dir + "/" + namelist[i]->d_name; paths.push_back(FilePath(entry)); if (recursive) { dir_queue.push_back(entry); } } else { std::string entry = dir + "/" + namelist[i]->d_name; paths.push_back(FilePath(entry)); } } ::free(namelist[i]); } if (namelist) ::free(namelist); } } FilePath HAL::app_dir (void) { // Java: // return context.getFilesDir().tostd::string(); JNIEnv* env = NULL; DTboolean needs_detach = false; int env_stat = gJavaVM->GetEnv( (void**) &env, JNI_VERSION_1_6); if (env_stat == JNI_EDETACHED) { gJavaVM->AttachCurrentThread(&env, 0); needs_detach = true; } ASSERT(env); jclass c_context = env->FindClass("android/content/Context"); ASSERT(c_context); jmethodID m_getFilesDir = env->GetMethodID(c_context, "getFilesDir", "()Ljava/io/File;"); jobject o_dir = (jstring) env->CallObjectMethod(gJavaObjContext, m_getFilesDir); jclass c_file = env->FindClass("java/io/File"); ASSERT(c_file); jmethodID m_toString = env->GetMethodID(c_file, "toString", "()Ljava/lang/String;"); jstring s_dir = (jstring) env->CallObjectMethod(o_dir, m_toString); // Convert to UTF-8 FilePath path = FilePath(env->GetStringUTFChars(s_dir, 0)); if (needs_detach) gJavaVM->DetachCurrentThread(); return path; } FilePath HAL::save_dir (void) { // Java: // return context.getFilesDir().toString(); JNIEnv* env = NULL; DTboolean needs_detach = false; int env_stat = gJavaVM->GetEnv( (void**) &env, JNI_VERSION_1_6); if (env_stat == JNI_EDETACHED) { gJavaVM->AttachCurrentThread(&env, 0); needs_detach = true; } ASSERT(env); jclass c_context = env->FindClass("android/content/Context"); ASSERT(c_context); jmethodID m_getFilesDir = env->GetMethodID(c_context, "getFilesDir", "()Ljava/io/File;"); ASSERT(m_getFilesDir); jobject o_dir = env->CallObjectMethod(gJavaObjContext, m_getFilesDir); jclass c_file = env->FindClass("java/io/File"); ASSERT(c_file); jmethodID m_toString = env->GetMethodID(c_file, "toString", "()Ljava/lang/String;"); ASSERT(m_toString); jstring s_dir = (jstring) env->CallObjectMethod(o_dir, m_toString); // Convert to UTF-8 FilePath path = FilePath(env->GetStringUTFChars(s_dir, 0)); if (needs_detach) gJavaVM->DetachCurrentThread(); return path; } //============================================================================== //============================================================================== std::string HAL::region (void) { // Java: // return Locale.getDefault().getISO3Country(); JNIEnv* env = NULL; DTboolean needs_detach = false; int env_stat = gJavaVM->GetEnv( (void**) &env, JNI_VERSION_1_6); if (env_stat == JNI_EDETACHED) { gJavaVM->AttachCurrentThread(&env, 0); needs_detach = true; } ASSERT(env); // Get Locale class jclass c_Locale = env->FindClass("java/util/Locale"); ASSERT(c_Locale); // Call getDefault jmethodID m_getDefault = env->GetStaticMethodID(c_Locale, "getDefault", "()Ljava/util/Locale;"); jobject o_Locale = env->CallStaticObjectMethod(c_Locale, m_getDefault); // Call getISO3Country jmethodID m_getISO3Country = env->GetMethodID(c_Locale, "getISO3Country", "()Ljava/lang/String;"); jstring s_region = (jstring) env->CallObjectMethod(o_Locale, m_getISO3Country); // Convert to UTF-8 std::string s = std::string(env->GetStringUTFChars(s_region, 0)); if (needs_detach) gJavaVM->DetachCurrentThread(); return s; } std::string HAL::language (void) { // Java: // return Locale.getDefault().getISO3Language(); JNIEnv* env = NULL; DTboolean needs_detach = false; int env_stat = gJavaVM->GetEnv( (void**) &env, JNI_VERSION_1_6); if (env_stat == JNI_EDETACHED) { gJavaVM->AttachCurrentThread(&env, 0); needs_detach = true; } ASSERT(env); // Get Locale class jclass c_Locale = env->FindClass("java/util/Locale"); ASSERT(c_Locale); // Call getDefault jmethodID m_getDefault = env->GetStaticMethodID(c_Locale, "getDefault", "()Ljava/util/Locale;"); jobject o_Locale = env->CallStaticObjectMethod(c_Locale, m_getDefault); // Call getISO3Country jmethodID m_getISO3Language = env->GetMethodID(c_Locale, "getISO3Language", "()Ljava/lang/String;"); jstring s_language = (jstring) env->CallObjectMethod(o_Locale, m_getISO3Language); // Convert to UTF-8 std::string s = std::string(env->GetStringUTFChars(s_language, 0)); if (needs_detach) gJavaVM->DetachCurrentThread(); return s; } //============================================================================== //============================================================================== std::map<StringCopier, Globals::GlobalsEntry> HAL::load_globals (void) { // Java: // SharedPreferences settings; // SharedPreferences.Editor editor; // Map<String,String> globals = new TreeMap(); // settings = _context.getSharedPreferences(PREFS_NAME, 0); // Map<String,?> mp = settings.getAll(); // Iterator it = mp.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pairs = (Map.Entry)it.next(); // globals.put( (String) pairs.getKey(), (String) pairs.getValue() ); // } // return globals; JNIEnv* env = NULL; DTboolean needs_detach = false; int env_stat = gJavaVM->GetEnv( (void**) &env, JNI_VERSION_1_6); if (env_stat == JNI_EDETACHED) { gJavaVM->AttachCurrentThread(&env, 0); needs_detach = true; } ASSERT(env); jstring o_prefs_name = env->NewStringUTF(PROJECT_NAME); // settings = _context.getSharedPreferences(PREFS_NAME, 0); jclass c_context = env->FindClass("android/content/Context"); ASSERT(c_context); jmethodID m_get_shared_preferences = env->GetMethodID(c_context, "getSharedPreferences", "(Ljava/lang/String;I)Landroid/content/SharedPreferences;"); ASSERT(m_get_shared_preferences); jobject o_settings = env->CallObjectMethod(gJavaObjContext, m_get_shared_preferences, o_prefs_name, 0); ASSERT(o_settings); // Map<String,?> mp = settings.getAll(); jclass c_shared_preferences = env->FindClass("android/content/SharedPreferences"); ASSERT(c_shared_preferences); jmethodID m_get_all = env->GetMethodID(c_shared_preferences, "getAll", "()Ljava/util/Map;"); ASSERT(m_get_all); jobject o_mp = env->CallObjectMethod(o_settings, m_get_all); ASSERT(o_mp); // Iterator it = mp.entrySet().iterator(); jclass c_map = env->FindClass("java/util/Map"); ASSERT(c_map); jmethodID m_entry_set = env->GetMethodID(c_map, "entrySet", "()Ljava/util/Set;"); ASSERT(m_entry_set); jclass c_set = env->FindClass("java/util/Set"); ASSERT(c_set); jmethodID m_iterator = env->GetMethodID(c_set, "iterator", "()Ljava/util/Iterator;"); ASSERT(m_iterator); jclass c_iterator = env->FindClass("java/util/Iterator"); ASSERT(c_iterator); jclass c_entry = env->FindClass("java/util/Map$Entry"); ASSERT(c_entry); jmethodID m_has_next = env->GetMethodID(c_iterator, "hasNext", "()Z"); jmethodID m_next = env->GetMethodID(c_iterator, "next", "()Ljava/lang/Object;"); jmethodID m_get_key = env->GetMethodID(c_entry, "getKey", "()Ljava/lang/Object;"); jmethodID m_get_value = env->GetMethodID(c_entry, "getValue", "()Ljava/lang/Object;"); jobject o_set = env->CallObjectMethod(o_mp, m_entry_set); jobject o_iter = env->CallObjectMethod(o_set, m_iterator); std::map<StringCopier, Globals::GlobalsEntry> globals; // while (it.hasNext()) { while (env->CallBooleanMethod(o_iter, m_has_next)) { jobject o_entry = env->CallObjectMethod(o_iter, m_next); jstring o_key = (jstring) env->CallObjectMethod(o_entry, m_get_key); jstring o_value = (jstring) env->CallObjectMethod(o_entry, m_get_value); const char *name_c = env->GetStringUTFChars(o_key, 0); const char *value_c = env->GetStringUTFChars(o_value, 0); std::string name(name_c); std::string value(value_c); DTuint lifetime = Globals::PERSISTENT; if (name[0] == '-') { name.erase(0,1); value = MoreStrings::from_obfuscated(name,value); lifetime = Globals::PERSISTENT_OBFUSCATED; } log("Reading persistent value: " + name + " = " + value); Globals::GlobalsEntry e; e.name = name; e.value = value; e.lifetime = lifetime; globals[name] = e; env->DeleteLocalRef(o_entry); env->DeleteLocalRef(o_key); env->DeleteLocalRef(o_value); } if (needs_detach) gJavaVM->DetachCurrentThread(); return globals; } void HAL::save_globals (std::map<StringCopier, Globals::GlobalsEntry> globals) { // Java: // SharedPreferences settings; // SharedPreferences.Editor editor; // settings = _context.getSharedPreferences(PREFS_NAME, 0); // editor = settings.edit(); // Iterator it = globals.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pairs = (Map.Entry)it.next(); // editor.putString( (String) pairs.getKey(), (String) pairs.getValue()); // } // editor.commit(); JNIEnv* env = NULL; DTboolean needs_detach = false; int env_stat = gJavaVM->GetEnv( (void**) &env, JNI_VERSION_1_6); if (env_stat == JNI_EDETACHED) { gJavaVM->AttachCurrentThread(&env, 0); needs_detach = true; } ASSERT(env); jstring o_prefs_name = env->NewStringUTF(PROJECT_NAME); // settings = _context.getSharedPreferences(PREFS_NAME, 0); jclass c_context = env->FindClass("android/content/Context"); ASSERT(c_context); jmethodID m_get_shared_preferences = env->GetMethodID(c_context, "getSharedPreferences", "(Ljava/lang/String;I)Landroid/content/SharedPreferences;"); ASSERT(m_get_shared_preferences); jobject o_settings = env->CallObjectMethod(gJavaObjContext, m_get_shared_preferences, o_prefs_name, 0); ASSERT(o_settings); // editor = settings.edit(); jclass c_shared_preferences = env->FindClass("android/content/SharedPreferences"); ASSERT(c_shared_preferences); jmethodID m_edit = env->GetMethodID(c_shared_preferences, "edit", "()Landroid/content/SharedPreferences$Editor;"); ASSERT(m_edit); jobject o_editor = env->CallObjectMethod(o_settings, m_edit); ASSERT(o_editor); jclass c_editor = env->FindClass("android/content/SharedPreferences$Editor"); ASSERT(c_editor); jmethodID m_put_string = env->GetMethodID(c_editor, "putString", "(Ljava/lang/String;Ljava/lang/String;)Landroid/content/SharedPreferences$Editor;"); ASSERT(m_put_string); // Iterate through all globals for (auto &i : globals) { if (i.second.lifetime == Globals::PERSISTENT || i.second.lifetime == Globals::PERSISTENT_OBFUSCATED) { std::string name = i.second.name; std::string value = i.second.value; if (name.size() <= 0 || value.size() <= 0) continue; if (i.second.lifetime == Globals::PERSISTENT_OBFUSCATED) { value = MoreStrings::to_obfuscated(name, value); name = "-" + name; log("Writing persistent value: " + name + " = " + std::string(i.second.value) + " (Obfuscated form is " + value + ")"); } else { log("Writing persistent value: " + name + " = " + value); } jstring j_name = env->NewStringUTF( name.c_str() ); jstring j_value = env->NewStringUTF( value.c_str() ); env->CallObjectMethod(o_editor, m_put_string, j_name, j_value); env->DeleteLocalRef(j_name); env->DeleteLocalRef(j_value); } } // editor.commit(); jmethodID m_commit = env->GetMethodID(c_editor, "commit", "()Z"); ASSERT(m_put_string); env->CallBooleanMethod(o_editor, m_commit); if (needs_detach) gJavaVM->DetachCurrentThread(); } //============================================================================== //============================================================================== } // DT3
32.375
153
0.579564
9heart
a205c22aed8585f1f228c1ebb0be6a9815b423b6
1,868
hpp
C++
src/mfx/pi/param/MapPseudoLog.hpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
69
2017-01-17T13:17:31.000Z
2022-03-01T14:56:32.000Z
src/mfx/pi/param/MapPseudoLog.hpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
1
2020-11-03T14:52:45.000Z
2020-12-01T20:31:15.000Z
src/mfx/pi/param/MapPseudoLog.hpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
8
2017-02-08T13:30:42.000Z
2021-12-09T08:43:09.000Z
/***************************************************************************** MapPseudoLog.hpp Author: Laurent de Soras, 2016 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if ! defined (mfx_pi_param_MapPseudoLog_CODEHEADER_INCLUDED) #define mfx_pi_param_MapPseudoLog_CODEHEADER_INCLUDED /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "fstb/def.h" #include "fstb/fnc.h" #include <cassert> #include <cmath> namespace mfx { namespace pi { namespace param { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ void MapPseudoLog::config (double val_min, double val_max) { fstb::unused (val_min); assert (val_min == 0); assert (val_min < val_max); _a = val_max; _ai = 1.0 / _a; } void MapPseudoLog::set_curvature (double c) { assert (c > 0); _c = c; } double MapPseudoLog::conv_norm_to_nat (double norm) const { const double nat = fstb::pseudo_exp (norm, _c) * _a; return nat; } double MapPseudoLog::conv_nat_to_norm (double nat) const { const double nrm = fstb::pseudo_log (nat * _ai, _c); return nrm; } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ } // namespace param } // namespace pi } // namespace mfx #endif // mfx_pi_param_MapPseudoLog_CODEHEADER_INCLUDED /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
17.961538
78
0.518201
mikelange49
a2067596101a56b51688434b9cb6947939177bec
35,317
cpp
C++
build/linux-build/Sources/src/zpp_nape/geom/ZPP_PartitionVertex.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/geom/ZPP_PartitionVertex.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/geom/ZPP_PartitionVertex.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
// Generated by Haxe 4.0.0-preview.5 #include <hxcpp.h> #ifndef INCLUDED_zpp_nape_geom_ZPP_GeomVert #include <hxinc/zpp_nape/geom/ZPP_GeomVert.h> #endif #ifndef INCLUDED_zpp_nape_geom_ZPP_PartitionVertex #include <hxinc/zpp_nape/geom/ZPP_PartitionVertex.h> #endif #ifndef INCLUDED_zpp_nape_util_ZNPList_ZPP_PartitionVertex #include <hxinc/zpp_nape/util/ZNPList_ZPP_PartitionVertex.h> #endif #ifndef INCLUDED_zpp_nape_util_ZNPNode_ZPP_PartitionVertex #include <hxinc/zpp_nape/util/ZNPNode_ZPP_PartitionVertex.h> #endif #ifndef INCLUDED_zpp_nape_util_ZPP_Set_ZPP_PartitionVertex #include <hxinc/zpp_nape/util/ZPP_Set_ZPP_PartitionVertex.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_8da00814ed838b44_174_new,"zpp_nape.geom.ZPP_PartitionVertex","new",0x2a87476a,"zpp_nape.geom.ZPP_PartitionVertex.new","zpp_nape/geom/PartitionedPoly.hx",174,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_216_alloc,"zpp_nape.geom.ZPP_PartitionVertex","alloc",0xd8da71ff,"zpp_nape.geom.ZPP_PartitionVertex.alloc","zpp_nape/geom/PartitionedPoly.hx",216,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_219_free,"zpp_nape.geom.ZPP_PartitionVertex","free",0x06974e62,"zpp_nape.geom.ZPP_PartitionVertex.free","zpp_nape/geom/PartitionedPoly.hx",219,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_272_copy,"zpp_nape.geom.ZPP_PartitionVertex","copy",0x04996d6b,"zpp_nape.geom.ZPP_PartitionVertex.copy","zpp_nape/geom/PartitionedPoly.hx",272,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_314_sort,"zpp_nape.geom.ZPP_PartitionVertex","sort",0x0f2cd914,"zpp_nape.geom.ZPP_PartitionVertex.sort","zpp_nape/geom/PartitionedPoly.hx",314,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_230_get,"zpp_nape.geom.ZPP_PartitionVertex","get",0x2a81f7a0,"zpp_nape.geom.ZPP_PartitionVertex.get","zpp_nape/geom/PartitionedPoly.hx",230,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_493_rightdistance,"zpp_nape.geom.ZPP_PartitionVertex","rightdistance",0x74d5429b,"zpp_nape.geom.ZPP_PartitionVertex.rightdistance","zpp_nape/geom/PartitionedPoly.hx",493,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_510_vert_lt,"zpp_nape.geom.ZPP_PartitionVertex","vert_lt",0xae5048a0,"zpp_nape.geom.ZPP_PartitionVertex.vert_lt","zpp_nape/geom/PartitionedPoly.hx",510,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_518_edge_swap,"zpp_nape.geom.ZPP_PartitionVertex","edge_swap",0x1a0ddb9f,"zpp_nape.geom.ZPP_PartitionVertex.edge_swap","zpp_nape/geom/PartitionedPoly.hx",518,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_523_edge_lt,"zpp_nape.geom.ZPP_PartitionVertex","edge_lt",0x25b57494,"zpp_nape.geom.ZPP_PartitionVertex.edge_lt","zpp_nape/geom/PartitionedPoly.hx",523,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_176_boot,"zpp_nape.geom.ZPP_PartitionVertex","boot",0x03f035e8,"zpp_nape.geom.ZPP_PartitionVertex.boot","zpp_nape/geom/PartitionedPoly.hx",176,0x0d312f3a) HX_LOCAL_STACK_FRAME(_hx_pos_8da00814ed838b44_185_boot,"zpp_nape.geom.ZPP_PartitionVertex","boot",0x03f035e8,"zpp_nape.geom.ZPP_PartitionVertex.boot","zpp_nape/geom/PartitionedPoly.hx",185,0x0d312f3a) namespace zpp_nape{ namespace geom{ void ZPP_PartitionVertex_obj::__construct(){ HX_GC_STACKFRAME(&_hx_pos_8da00814ed838b44_174_new) HXLINE( 517) this->node = null(); HXLINE( 210) this->prev = null(); HXLINE( 209) this->next = null(); HXLINE( 184) this->rightchain = false; HXLINE( 183) this->helper = null(); HXLINE( 182) this->type = 0; HXLINE( 181) this->diagonals = null(); HXLINE( 180) this->forced = false; HXLINE( 179) this->y = ((Float)0.0); HXLINE( 178) this->x = ((Float)0.0); HXLINE( 177) this->mag = ((Float)0); HXLINE( 175) this->id = 0; HXLINE( 212) this->id = ::zpp_nape::geom::ZPP_PartitionVertex_obj::nextId++; HXLINE( 213) this->diagonals = ::zpp_nape::util::ZNPList_ZPP_PartitionVertex_obj::__alloc( HX_CTX ); } Dynamic ZPP_PartitionVertex_obj::__CreateEmpty() { return new ZPP_PartitionVertex_obj; } void *ZPP_PartitionVertex_obj::_hx_vtable = 0; Dynamic ZPP_PartitionVertex_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ZPP_PartitionVertex_obj > _hx_result = new ZPP_PartitionVertex_obj(); _hx_result->__construct(); return _hx_result; } bool ZPP_PartitionVertex_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x213c1838; } void ZPP_PartitionVertex_obj::alloc(){ HX_STACKFRAME(&_hx_pos_8da00814ed838b44_216_alloc) } HX_DEFINE_DYNAMIC_FUNC0(ZPP_PartitionVertex_obj,alloc,(void)) void ZPP_PartitionVertex_obj::free(){ HX_STACKFRAME(&_hx_pos_8da00814ed838b44_219_free) HXDLIN( 219) this->helper = null(); } HX_DEFINE_DYNAMIC_FUNC0(ZPP_PartitionVertex_obj,free,(void)) ::zpp_nape::geom::ZPP_PartitionVertex ZPP_PartitionVertex_obj::copy(){ HX_GC_STACKFRAME(&_hx_pos_8da00814ed838b44_272_copy) HXLINE( 273) ::zpp_nape::geom::ZPP_PartitionVertex ret; HXLINE( 275) if (hx::IsNull( ::zpp_nape::geom::ZPP_PartitionVertex_obj::zpp_pool )) { HXLINE( 276) ret = ::zpp_nape::geom::ZPP_PartitionVertex_obj::__alloc( HX_CTX ); } else { HXLINE( 282) ret = ::zpp_nape::geom::ZPP_PartitionVertex_obj::zpp_pool; HXLINE( 283) ::zpp_nape::geom::ZPP_PartitionVertex_obj::zpp_pool = ret->next; HXLINE( 284) ret->next = null(); } HXLINE( 291) { HXLINE( 292) ret->x = this->x; HXLINE( 293) ret->y = this->y; } HXLINE( 311) ret->forced = this->forced; HXLINE( 312) return ret; } HX_DEFINE_DYNAMIC_FUNC0(ZPP_PartitionVertex_obj,copy,return ) void ZPP_PartitionVertex_obj::sort(){ HX_STACKFRAME(&_hx_pos_8da00814ed838b44_314_sort) HXLINE( 315) Float ux = ((Float)0.0); HXLINE( 316) Float uy = ((Float)0.0); HXLINE( 317) Float vx = ((Float)0.0); HXLINE( 318) Float vy = ((Float)0.0); HXLINE( 320) { HXLINE( 321) ux = (this->prev->x - this->x); HXLINE( 322) uy = (this->prev->y - this->y); } HXLINE( 324) { HXLINE( 325) vx = (this->next->x - this->x); HXLINE( 326) vy = (this->next->y - this->y); } HXLINE( 328) Float ret = ((vy * ux) - (vx * uy)); HXLINE( 319) int vorient; HXLINE( 329) if ((ret > 0)) { HXLINE( 319) vorient = -1; } else { HXLINE( 329) if ((ret == 0)) { HXLINE( 319) vorient = 0; } else { HXLINE( 319) vorient = 1; } } HXLINE( 339) { HXLINE( 340) ::zpp_nape::util::ZNPList_ZPP_PartitionVertex xxlist = this->diagonals; HXLINE( 341) bool _hx_tmp; HXDLIN( 341) if (hx::IsNotNull( xxlist->head )) { HXLINE( 341) _hx_tmp = hx::IsNotNull( xxlist->head->next ); } else { HXLINE( 341) _hx_tmp = false; } HXDLIN( 341) if (_hx_tmp) { HXLINE( 342) ::zpp_nape::util::ZNPNode_ZPP_PartitionVertex head = xxlist->head; HXLINE( 343) ::zpp_nape::util::ZNPNode_ZPP_PartitionVertex tail = null(); HXLINE( 344) ::zpp_nape::util::ZNPNode_ZPP_PartitionVertex left = null(); HXLINE( 345) ::zpp_nape::util::ZNPNode_ZPP_PartitionVertex right = null(); HXLINE( 346) ::zpp_nape::util::ZNPNode_ZPP_PartitionVertex nxt = null(); HXLINE( 347) int listSize = 1; HXLINE( 348) int numMerges; HXDLIN( 348) int leftSize; HXDLIN( 348) int rightSize; HXLINE( 349) while(true){ HXLINE( 350) numMerges = 0; HXLINE( 351) left = head; HXLINE( 352) head = null(); HXDLIN( 352) tail = head; HXLINE( 353) while(hx::IsNotNull( left )){ HXLINE( 354) numMerges = (numMerges + 1); HXLINE( 355) right = left; HXLINE( 356) leftSize = 0; HXLINE( 357) rightSize = listSize; HXLINE( 358) while(true){ HXLINE( 358) bool _hx_tmp1; HXDLIN( 358) if (hx::IsNotNull( right )) { HXLINE( 358) _hx_tmp1 = (leftSize < listSize); } else { HXLINE( 358) _hx_tmp1 = false; } HXDLIN( 358) if (!(_hx_tmp1)) { HXLINE( 358) goto _hx_goto_6; } HXLINE( 359) leftSize = (leftSize + 1); HXLINE( 360) right = right->next; } _hx_goto_6:; HXLINE( 362) while(true){ HXLINE( 362) bool _hx_tmp2; HXDLIN( 362) if ((leftSize <= 0)) { HXLINE( 362) if ((rightSize > 0)) { HXLINE( 362) _hx_tmp2 = hx::IsNotNull( right ); } else { HXLINE( 362) _hx_tmp2 = false; } } else { HXLINE( 362) _hx_tmp2 = true; } HXDLIN( 362) if (!(_hx_tmp2)) { HXLINE( 362) goto _hx_goto_7; } HXLINE( 363) if ((leftSize == 0)) { HXLINE( 364) nxt = right; HXLINE( 365) right = right->next; HXLINE( 366) rightSize = (rightSize - 1); } else { HXLINE( 368) bool _hx_tmp3; HXDLIN( 368) if ((rightSize != 0)) { HXLINE( 368) _hx_tmp3 = hx::IsNull( right ); } else { HXLINE( 368) _hx_tmp3 = true; } HXDLIN( 368) if (_hx_tmp3) { HXLINE( 369) nxt = left; HXLINE( 370) left = left->next; HXLINE( 371) leftSize = (leftSize - 1); } else { HXLINE( 373) bool _hx_tmp4; HXDLIN( 373) if ((vorient == 1)) { HXLINE( 376) { HXLINE( 377) ux = (left->elt->x - this->x); HXLINE( 378) uy = (left->elt->y - this->y); } HXLINE( 380) { HXLINE( 381) vx = (right->elt->x - this->x); HXLINE( 382) vy = (right->elt->y - this->y); } HXLINE( 384) Float ret1 = ((vy * ux) - (vx * uy)); HXLINE( 375) int _hx_tmp5; HXLINE( 385) if ((ret1 > 0)) { HXLINE( 375) _hx_tmp5 = -1; } else { HXLINE( 385) if ((ret1 == 0)) { HXLINE( 375) _hx_tmp5 = 0; } else { HXLINE( 375) _hx_tmp5 = 1; } } HXLINE( 373) _hx_tmp4 = (_hx_tmp5 == 1); } else { HXLINE( 390) { HXLINE( 391) ux = (this->prev->x - this->x); HXLINE( 392) uy = (this->prev->y - this->y); } HXLINE( 394) { HXLINE( 395) vx = (left->elt->x - this->x); HXLINE( 396) vy = (left->elt->y - this->y); } HXLINE( 398) Float ret2 = ((vy * ux) - (vx * uy)); HXLINE( 389) int d1; HXLINE( 399) if ((ret2 > 0)) { HXLINE( 389) d1 = -1; } else { HXLINE( 399) if ((ret2 == 0)) { HXLINE( 389) d1 = 0; } else { HXLINE( 389) d1 = 1; } } HXLINE( 402) { HXLINE( 403) ux = (this->prev->x - this->x); HXLINE( 404) uy = (this->prev->y - this->y); } HXLINE( 406) { HXLINE( 407) vx = (right->elt->x - this->x); HXLINE( 408) vy = (right->elt->y - this->y); } HXLINE( 410) Float ret3 = ((vy * ux) - (vx * uy)); HXLINE( 401) int d2; HXLINE( 411) if ((ret3 > 0)) { HXLINE( 401) d2 = -1; } else { HXLINE( 411) if ((ret3 == 0)) { HXLINE( 401) d2 = 0; } else { HXLINE( 401) d2 = 1; } } HXLINE( 413) bool _hx_tmp6; HXDLIN( 413) if (((d1 * d2) != 1)) { HXLINE( 413) if (((d1 * d2) == 0)) { HXLINE( 413) if ((d1 != 1)) { HXLINE( 413) _hx_tmp6 = (d2 == 1); } else { HXLINE( 413) _hx_tmp6 = true; } } else { HXLINE( 413) _hx_tmp6 = false; } } else { HXLINE( 413) _hx_tmp6 = true; } HXDLIN( 413) if (_hx_tmp6) { HXLINE( 415) { HXLINE( 416) ux = (left->elt->x - this->x); HXLINE( 417) uy = (left->elt->y - this->y); } HXLINE( 419) { HXLINE( 420) vx = (right->elt->x - this->x); HXLINE( 421) vy = (right->elt->y - this->y); } HXLINE( 423) Float ret4 = ((vy * ux) - (vx * uy)); HXLINE( 414) int _hx_tmp7; HXLINE( 424) if ((ret4 > 0)) { HXLINE( 414) _hx_tmp7 = -1; } else { HXLINE( 424) if ((ret4 == 0)) { HXLINE( 414) _hx_tmp7 = 0; } else { HXLINE( 414) _hx_tmp7 = 1; } } HXLINE( 373) _hx_tmp4 = (_hx_tmp7 == 1); } else { HXLINE( 427) bool _hx_tmp8; HXDLIN( 427) if ((d1 != -1)) { HXLINE( 427) _hx_tmp8 = (d2 == -1); } else { HXLINE( 427) _hx_tmp8 = true; } HXDLIN( 427) if (_hx_tmp8) { HXLINE( 373) _hx_tmp4 = (d2 == -1); } else { HXLINE( 430) bool _hx_tmp9; HXDLIN( 430) if ((d1 == 0)) { HXLINE( 430) _hx_tmp9 = (d2 == 0); } else { HXLINE( 430) _hx_tmp9 = false; } HXDLIN( 430) if (_hx_tmp9) { HXLINE( 431) { HXLINE( 432) ux = (this->x - this->prev->x); HXLINE( 433) uy = (this->y - this->prev->y); } HXLINE( 435) { HXLINE( 436) vx = (left->elt->x - this->x); HXLINE( 437) vy = (left->elt->y - this->y); } HXLINE( 439) Float d11 = ((ux * vx) + (uy * vy)); HXLINE( 440) { HXLINE( 441) vx = (right->elt->x - this->x); HXLINE( 442) vy = (right->elt->y - this->y); } HXLINE( 444) Float d21 = ((ux * vx) + (uy * vy)); HXLINE( 445) bool _hx_tmp10; HXDLIN( 445) if ((d11 < 0)) { HXLINE( 445) _hx_tmp10 = (d21 > 0); } else { HXLINE( 445) _hx_tmp10 = false; } HXDLIN( 445) if (_hx_tmp10) { HXLINE( 373) _hx_tmp4 = true; } else { HXLINE( 445) bool _hx_tmp11; HXDLIN( 445) if ((d21 < 0)) { HXLINE( 445) _hx_tmp11 = (d11 > 0); } else { HXLINE( 445) _hx_tmp11 = false; } HXDLIN( 445) if (_hx_tmp11) { HXLINE( 373) _hx_tmp4 = false; } else { HXLINE( 373) _hx_tmp4 = true; } } } else { HXLINE( 373) _hx_tmp4 = true; } } } } HXDLIN( 373) if (_hx_tmp4) { HXLINE( 470) nxt = left; HXLINE( 471) left = left->next; HXLINE( 472) leftSize = (leftSize - 1); } else { HXLINE( 475) nxt = right; HXLINE( 476) right = right->next; HXLINE( 477) rightSize = (rightSize - 1); } } } HXLINE( 479) if (hx::IsNotNull( tail )) { HXLINE( 479) tail->next = nxt; } else { HXLINE( 480) head = nxt; } HXLINE( 481) tail = nxt; } _hx_goto_7:; HXLINE( 483) left = right; } HXLINE( 485) tail->next = null(); HXLINE( 486) listSize = (listSize << 1); HXLINE( 349) if (!((numMerges > 1))) { HXLINE( 349) goto _hx_goto_4; } } _hx_goto_4:; HXLINE( 489) { HXLINE( 489) xxlist->head = head; HXDLIN( 489) xxlist->modified = true; HXDLIN( 489) xxlist->pushmod = true; } } } } HX_DEFINE_DYNAMIC_FUNC0(ZPP_PartitionVertex_obj,sort,(void)) int ZPP_PartitionVertex_obj::nextId; ::zpp_nape::geom::ZPP_PartitionVertex ZPP_PartitionVertex_obj::zpp_pool; ::zpp_nape::geom::ZPP_PartitionVertex ZPP_PartitionVertex_obj::get( ::zpp_nape::geom::ZPP_GeomVert x){ HX_GC_STACKFRAME(&_hx_pos_8da00814ed838b44_230_get) HXLINE( 231) ::zpp_nape::geom::ZPP_PartitionVertex ret; HXLINE( 233) if (hx::IsNull( ::zpp_nape::geom::ZPP_PartitionVertex_obj::zpp_pool )) { HXLINE( 234) ret = ::zpp_nape::geom::ZPP_PartitionVertex_obj::__alloc( HX_CTX ); } else { HXLINE( 240) ret = ::zpp_nape::geom::ZPP_PartitionVertex_obj::zpp_pool; HXLINE( 241) ::zpp_nape::geom::ZPP_PartitionVertex_obj::zpp_pool = ret->next; HXLINE( 242) ret->next = null(); } HXLINE( 249) { HXLINE( 250) ret->x = x->x; HXLINE( 251) ret->y = x->y; } HXLINE( 269) return ret; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(ZPP_PartitionVertex_obj,get,return ) Float ZPP_PartitionVertex_obj::rightdistance( ::zpp_nape::geom::ZPP_PartitionVertex edge, ::zpp_nape::geom::ZPP_PartitionVertex vert){ HX_STACKFRAME(&_hx_pos_8da00814ed838b44_493_rightdistance) HXLINE( 494) bool flip = (edge->next->y > edge->y); HXLINE( 495) Float ux = ((Float)0.0); HXLINE( 496) Float uy = ((Float)0.0); HXLINE( 497) { HXLINE( 498) ux = (edge->next->x - edge->x); HXLINE( 499) uy = (edge->next->y - edge->y); } HXLINE( 501) Float vx = ((Float)0.0); HXLINE( 502) Float vy = ((Float)0.0); HXLINE( 503) { HXLINE( 504) vx = (vert->x - edge->x); HXLINE( 505) vy = (vert->y - edge->y); } HXLINE( 507) Float _hx_tmp; HXDLIN( 507) if (flip) { HXLINE( 507) _hx_tmp = ((Float)-1.0); } else { HXLINE( 507) _hx_tmp = ((Float)1.0); } HXDLIN( 507) return (_hx_tmp * ((vy * ux) - (vx * uy))); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(ZPP_PartitionVertex_obj,rightdistance,return ) bool ZPP_PartitionVertex_obj::vert_lt( ::zpp_nape::geom::ZPP_PartitionVertex edge, ::zpp_nape::geom::ZPP_PartitionVertex vert){ HX_STACKFRAME(&_hx_pos_8da00814ed838b44_510_vert_lt) HXDLIN( 510) bool _hx_tmp; HXDLIN( 510) if (hx::IsNotEq( vert,edge )) { HXDLIN( 510) _hx_tmp = hx::IsEq( vert,edge->next ); } else { HXDLIN( 510) _hx_tmp = true; } HXDLIN( 510) if (_hx_tmp) { HXDLIN( 510) return true; } else { HXDLIN( 510) if ((edge->y == edge->next->y)) { HXLINE( 511) Float x = edge->x; HXLINE( 512) Float y = edge->next->x; HXLINE( 510) Float _hx_tmp1; HXLINE( 513) if ((x < y)) { HXDLIN( 510) _hx_tmp1 = x; } else { HXDLIN( 510) _hx_tmp1 = y; } HXDLIN( 510) return (_hx_tmp1 <= vert->x); } else { HXLINE( 515) return (::zpp_nape::geom::ZPP_PartitionVertex_obj::rightdistance(edge,vert) <= ((Float)0.0)); } } HXLINE( 510) return false; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(ZPP_PartitionVertex_obj,vert_lt,return ) void ZPP_PartitionVertex_obj::edge_swap( ::zpp_nape::geom::ZPP_PartitionVertex p, ::zpp_nape::geom::ZPP_PartitionVertex q){ HX_STACKFRAME(&_hx_pos_8da00814ed838b44_518_edge_swap) HXLINE( 519) ::zpp_nape::util::ZPP_Set_ZPP_PartitionVertex t = p->node; HXLINE( 520) p->node = q->node; HXLINE( 521) q->node = t; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(ZPP_PartitionVertex_obj,edge_swap,(void)) bool ZPP_PartitionVertex_obj::edge_lt( ::zpp_nape::geom::ZPP_PartitionVertex p, ::zpp_nape::geom::ZPP_PartitionVertex q){ HX_STACKFRAME(&_hx_pos_8da00814ed838b44_523_edge_lt) HXLINE( 524) bool _hx_tmp; HXDLIN( 524) if (hx::IsEq( p,q )) { HXLINE( 524) _hx_tmp = hx::IsEq( p->next,q->next ); } else { HXLINE( 524) _hx_tmp = false; } HXDLIN( 524) if (_hx_tmp) { HXLINE( 533) return false; } HXLINE( 535) if (hx::IsEq( p,q->next )) { HXLINE( 535) return !(::zpp_nape::geom::ZPP_PartitionVertex_obj::vert_lt(p,q)); } else { HXLINE( 536) if (hx::IsEq( q,p->next )) { HXLINE( 536) return ::zpp_nape::geom::ZPP_PartitionVertex_obj::vert_lt(q,p); } else { HXLINE( 537) if ((p->y == p->next->y)) { HXLINE( 538) if ((q->y == q->next->y)) { HXLINE( 539) Float x = p->x; HXLINE( 540) Float y = p->next->x; HXLINE( 538) Float _hx_tmp1; HXLINE( 541) if ((x > y)) { HXLINE( 538) _hx_tmp1 = x; } else { HXLINE( 538) _hx_tmp1 = y; } HXLINE( 543) Float x1 = q->x; HXLINE( 544) Float y1 = q->next->x; HXLINE( 542) Float _hx_tmp2; HXLINE( 545) if ((x1 > y1)) { HXLINE( 542) _hx_tmp2 = x1; } else { HXLINE( 542) _hx_tmp2 = y1; } HXLINE( 538) return (_hx_tmp1 > _hx_tmp2); } else { HXLINE( 546) if (!((::zpp_nape::geom::ZPP_PartitionVertex_obj::rightdistance(q,p) > ((Float)0.0)))) { HXLINE( 546) return (::zpp_nape::geom::ZPP_PartitionVertex_obj::rightdistance(q,p->next) > ((Float)0.0)); } else { HXLINE( 546) return true; } } } else { HXLINE( 549) Float qRight = ::zpp_nape::geom::ZPP_PartitionVertex_obj::rightdistance(p,q); HXLINE( 550) Float qNextRight = ::zpp_nape::geom::ZPP_PartitionVertex_obj::rightdistance(p,q->next); HXLINE( 551) bool _hx_tmp3; HXDLIN( 551) if ((qRight == 0)) { HXLINE( 551) _hx_tmp3 = (qNextRight == 0); } else { HXLINE( 551) _hx_tmp3 = false; } HXDLIN( 551) if (_hx_tmp3) { HXLINE( 553) Float x2 = p->x; HXLINE( 554) Float y2 = p->next->x; HXLINE( 552) Float _hx_tmp4; HXLINE( 555) if ((x2 > y2)) { HXLINE( 552) _hx_tmp4 = x2; } else { HXLINE( 552) _hx_tmp4 = y2; } HXLINE( 557) Float x3 = q->x; HXLINE( 558) Float y3 = q->next->x; HXLINE( 556) Float _hx_tmp5; HXLINE( 559) if ((x3 > y3)) { HXLINE( 556) _hx_tmp5 = x3; } else { HXLINE( 556) _hx_tmp5 = y3; } HXLINE( 552) return (_hx_tmp4 > _hx_tmp5); } HXLINE( 562) if (((qRight * qNextRight) >= 0)) { HXLINE( 562) if (!((qRight < 0))) { HXLINE( 562) return (qNextRight < 0); } else { HXLINE( 562) return true; } } HXLINE( 563) Float pRight = ::zpp_nape::geom::ZPP_PartitionVertex_obj::rightdistance(q,p); HXLINE( 564) Float pNextRight = ::zpp_nape::geom::ZPP_PartitionVertex_obj::rightdistance(q,p->next); HXLINE( 573) if (((pRight * pNextRight) >= 0)) { HXLINE( 573) if (!((pRight > 0))) { HXLINE( 573) return (pNextRight > 0); } else { HXLINE( 573) return true; } } HXLINE( 582) return false; } } } HXLINE( 535) return false; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(ZPP_PartitionVertex_obj,edge_lt,return ) hx::ObjectPtr< ZPP_PartitionVertex_obj > ZPP_PartitionVertex_obj::__new() { hx::ObjectPtr< ZPP_PartitionVertex_obj > __this = new ZPP_PartitionVertex_obj(); __this->__construct(); return __this; } hx::ObjectPtr< ZPP_PartitionVertex_obj > ZPP_PartitionVertex_obj::__alloc(hx::Ctx *_hx_ctx) { ZPP_PartitionVertex_obj *__this = (ZPP_PartitionVertex_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ZPP_PartitionVertex_obj), true, "zpp_nape.geom.ZPP_PartitionVertex")); *(void **)__this = ZPP_PartitionVertex_obj::_hx_vtable; __this->__construct(); return __this; } ZPP_PartitionVertex_obj::ZPP_PartitionVertex_obj() { } void ZPP_PartitionVertex_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ZPP_PartitionVertex); HX_MARK_MEMBER_NAME(id,"id"); HX_MARK_MEMBER_NAME(mag,"mag"); HX_MARK_MEMBER_NAME(x,"x"); HX_MARK_MEMBER_NAME(y,"y"); HX_MARK_MEMBER_NAME(forced,"forced"); HX_MARK_MEMBER_NAME(diagonals,"diagonals"); HX_MARK_MEMBER_NAME(type,"type"); HX_MARK_MEMBER_NAME(helper,"helper"); HX_MARK_MEMBER_NAME(rightchain,"rightchain"); HX_MARK_MEMBER_NAME(next,"next"); HX_MARK_MEMBER_NAME(prev,"prev"); HX_MARK_MEMBER_NAME(node,"node"); HX_MARK_END_CLASS(); } void ZPP_PartitionVertex_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(id,"id"); HX_VISIT_MEMBER_NAME(mag,"mag"); HX_VISIT_MEMBER_NAME(x,"x"); HX_VISIT_MEMBER_NAME(y,"y"); HX_VISIT_MEMBER_NAME(forced,"forced"); HX_VISIT_MEMBER_NAME(diagonals,"diagonals"); HX_VISIT_MEMBER_NAME(type,"type"); HX_VISIT_MEMBER_NAME(helper,"helper"); HX_VISIT_MEMBER_NAME(rightchain,"rightchain"); HX_VISIT_MEMBER_NAME(next,"next"); HX_VISIT_MEMBER_NAME(prev,"prev"); HX_VISIT_MEMBER_NAME(node,"node"); } hx::Val ZPP_PartitionVertex_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"x") ) { return hx::Val( x ); } if (HX_FIELD_EQ(inName,"y") ) { return hx::Val( y ); } break; case 2: if (HX_FIELD_EQ(inName,"id") ) { return hx::Val( id ); } break; case 3: if (HX_FIELD_EQ(inName,"mag") ) { return hx::Val( mag ); } break; case 4: if (HX_FIELD_EQ(inName,"type") ) { return hx::Val( type ); } if (HX_FIELD_EQ(inName,"next") ) { return hx::Val( next ); } if (HX_FIELD_EQ(inName,"prev") ) { return hx::Val( prev ); } if (HX_FIELD_EQ(inName,"free") ) { return hx::Val( free_dyn() ); } if (HX_FIELD_EQ(inName,"copy") ) { return hx::Val( copy_dyn() ); } if (HX_FIELD_EQ(inName,"sort") ) { return hx::Val( sort_dyn() ); } if (HX_FIELD_EQ(inName,"node") ) { return hx::Val( node ); } break; case 5: if (HX_FIELD_EQ(inName,"alloc") ) { return hx::Val( alloc_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"forced") ) { return hx::Val( forced ); } if (HX_FIELD_EQ(inName,"helper") ) { return hx::Val( helper ); } break; case 9: if (HX_FIELD_EQ(inName,"diagonals") ) { return hx::Val( diagonals ); } break; case 10: if (HX_FIELD_EQ(inName,"rightchain") ) { return hx::Val( rightchain ); } } return super::__Field(inName,inCallProp); } bool ZPP_PartitionVertex_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"get") ) { outValue = get_dyn(); return true; } break; case 6: if (HX_FIELD_EQ(inName,"nextId") ) { outValue = ( nextId ); return true; } break; case 7: if (HX_FIELD_EQ(inName,"vert_lt") ) { outValue = vert_lt_dyn(); return true; } if (HX_FIELD_EQ(inName,"edge_lt") ) { outValue = edge_lt_dyn(); return true; } break; case 8: if (HX_FIELD_EQ(inName,"zpp_pool") ) { outValue = ( zpp_pool ); return true; } break; case 9: if (HX_FIELD_EQ(inName,"edge_swap") ) { outValue = edge_swap_dyn(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"rightdistance") ) { outValue = rightdistance_dyn(); return true; } } return false; } hx::Val ZPP_PartitionVertex_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"x") ) { x=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"y") ) { y=inValue.Cast< Float >(); return inValue; } break; case 2: if (HX_FIELD_EQ(inName,"id") ) { id=inValue.Cast< int >(); return inValue; } break; case 3: if (HX_FIELD_EQ(inName,"mag") ) { mag=inValue.Cast< Float >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"type") ) { type=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"next") ) { next=inValue.Cast< ::zpp_nape::geom::ZPP_PartitionVertex >(); return inValue; } if (HX_FIELD_EQ(inName,"prev") ) { prev=inValue.Cast< ::zpp_nape::geom::ZPP_PartitionVertex >(); return inValue; } if (HX_FIELD_EQ(inName,"node") ) { node=inValue.Cast< ::zpp_nape::util::ZPP_Set_ZPP_PartitionVertex >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"forced") ) { forced=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"helper") ) { helper=inValue.Cast< ::zpp_nape::geom::ZPP_PartitionVertex >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"diagonals") ) { diagonals=inValue.Cast< ::zpp_nape::util::ZNPList_ZPP_PartitionVertex >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"rightchain") ) { rightchain=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } bool ZPP_PartitionVertex_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"nextId") ) { nextId=ioValue.Cast< int >(); return true; } break; case 8: if (HX_FIELD_EQ(inName,"zpp_pool") ) { zpp_pool=ioValue.Cast< ::zpp_nape::geom::ZPP_PartitionVertex >(); return true; } } return false; } void ZPP_PartitionVertex_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("id",db,5b,00,00)); outFields->push(HX_("mag",93,0a,53,00)); outFields->push(HX_("x",78,00,00,00)); outFields->push(HX_("y",79,00,00,00)); outFields->push(HX_("forced",19,fc,86,fd)); outFields->push(HX_("diagonals",de,d1,db,fe)); outFields->push(HX_("type",ba,f2,08,4d)); outFields->push(HX_("helper",6e,7d,4e,04)); outFields->push(HX_("rightchain",a5,0b,4b,b5)); outFields->push(HX_("next",f3,84,02,49)); outFields->push(HX_("prev",f3,be,5e,4a)); outFields->push(HX_("node",02,0a,0a,49)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo ZPP_PartitionVertex_obj_sMemberStorageInfo[] = { {hx::fsInt,(int)offsetof(ZPP_PartitionVertex_obj,id),HX_("id",db,5b,00,00)}, {hx::fsFloat,(int)offsetof(ZPP_PartitionVertex_obj,mag),HX_("mag",93,0a,53,00)}, {hx::fsFloat,(int)offsetof(ZPP_PartitionVertex_obj,x),HX_("x",78,00,00,00)}, {hx::fsFloat,(int)offsetof(ZPP_PartitionVertex_obj,y),HX_("y",79,00,00,00)}, {hx::fsBool,(int)offsetof(ZPP_PartitionVertex_obj,forced),HX_("forced",19,fc,86,fd)}, {hx::fsObject /* ::zpp_nape::util::ZNPList_ZPP_PartitionVertex */ ,(int)offsetof(ZPP_PartitionVertex_obj,diagonals),HX_("diagonals",de,d1,db,fe)}, {hx::fsInt,(int)offsetof(ZPP_PartitionVertex_obj,type),HX_("type",ba,f2,08,4d)}, {hx::fsObject /* ::zpp_nape::geom::ZPP_PartitionVertex */ ,(int)offsetof(ZPP_PartitionVertex_obj,helper),HX_("helper",6e,7d,4e,04)}, {hx::fsBool,(int)offsetof(ZPP_PartitionVertex_obj,rightchain),HX_("rightchain",a5,0b,4b,b5)}, {hx::fsObject /* ::zpp_nape::geom::ZPP_PartitionVertex */ ,(int)offsetof(ZPP_PartitionVertex_obj,next),HX_("next",f3,84,02,49)}, {hx::fsObject /* ::zpp_nape::geom::ZPP_PartitionVertex */ ,(int)offsetof(ZPP_PartitionVertex_obj,prev),HX_("prev",f3,be,5e,4a)}, {hx::fsObject /* ::zpp_nape::util::ZPP_Set_ZPP_PartitionVertex */ ,(int)offsetof(ZPP_PartitionVertex_obj,node),HX_("node",02,0a,0a,49)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo ZPP_PartitionVertex_obj_sStaticStorageInfo[] = { {hx::fsInt,(void *) &ZPP_PartitionVertex_obj::nextId,HX_("nextId",ae,27,64,72)}, {hx::fsObject /* ::zpp_nape::geom::ZPP_PartitionVertex */ ,(void *) &ZPP_PartitionVertex_obj::zpp_pool,HX_("zpp_pool",81,5d,d4,38)}, { hx::fsUnknown, 0, null()} }; #endif static ::String ZPP_PartitionVertex_obj_sMemberFields[] = { HX_("id",db,5b,00,00), HX_("mag",93,0a,53,00), HX_("x",78,00,00,00), HX_("y",79,00,00,00), HX_("forced",19,fc,86,fd), HX_("diagonals",de,d1,db,fe), HX_("type",ba,f2,08,4d), HX_("helper",6e,7d,4e,04), HX_("rightchain",a5,0b,4b,b5), HX_("next",f3,84,02,49), HX_("prev",f3,be,5e,4a), HX_("alloc",75,a4,93,21), HX_("free",ac,9c,c2,43), HX_("copy",b5,bb,c4,41), HX_("sort",5e,27,58,4c), HX_("node",02,0a,0a,49), ::String(null()) }; static void ZPP_PartitionVertex_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(ZPP_PartitionVertex_obj::nextId,"nextId"); HX_MARK_MEMBER_NAME(ZPP_PartitionVertex_obj::zpp_pool,"zpp_pool"); }; #ifdef HXCPP_VISIT_ALLOCS static void ZPP_PartitionVertex_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ZPP_PartitionVertex_obj::nextId,"nextId"); HX_VISIT_MEMBER_NAME(ZPP_PartitionVertex_obj::zpp_pool,"zpp_pool"); }; #endif hx::Class ZPP_PartitionVertex_obj::__mClass; static ::String ZPP_PartitionVertex_obj_sStaticFields[] = { HX_("nextId",ae,27,64,72), HX_("zpp_pool",81,5d,d4,38), HX_("get",96,80,4e,00), HX_("rightdistance",11,db,56,00), HX_("vert_lt",96,84,93,7d), HX_("edge_swap",15,81,90,ad), HX_("edge_lt",8a,b0,f8,f4), ::String(null()) }; void ZPP_PartitionVertex_obj::__register() { ZPP_PartitionVertex_obj _hx_dummy; ZPP_PartitionVertex_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("zpp_nape.geom.ZPP_PartitionVertex",78,0a,69,89); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &ZPP_PartitionVertex_obj::__GetStatic; __mClass->mSetStaticField = &ZPP_PartitionVertex_obj::__SetStatic; __mClass->mMarkFunc = ZPP_PartitionVertex_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(ZPP_PartitionVertex_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(ZPP_PartitionVertex_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ZPP_PartitionVertex_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = ZPP_PartitionVertex_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ZPP_PartitionVertex_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ZPP_PartitionVertex_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void ZPP_PartitionVertex_obj::__boot() { { HX_STACKFRAME(&_hx_pos_8da00814ed838b44_176_boot) HXDLIN( 176) nextId = 0; } { HX_STACKFRAME(&_hx_pos_8da00814ed838b44_185_boot) HXDLIN( 185) zpp_pool = null(); } } } // end namespace zpp_nape } // end namespace geom
38.346363
227
0.588838
HedgehogFog
a20887c0f0817c9eff6cad1a40075c4e768633a6
1,277
cpp
C++
sources/Application/Model/Phrase.cpp
haiko21/LittleGPTracker
0f137aa67dfd86379b830cc51ba900b9423127ce
[ "BSD-3-Clause" ]
66
2015-01-29T09:12:51.000Z
2022-03-23T19:20:49.000Z
sources/Application/Model/Phrase.cpp
haiko21/LittleGPTracker
0f137aa67dfd86379b830cc51ba900b9423127ce
[ "BSD-3-Clause" ]
18
2015-08-19T19:50:31.000Z
2021-10-12T02:33:09.000Z
sources/Application/Model/Phrase.cpp
haiko21/LittleGPTracker
0f137aa67dfd86379b830cc51ba900b9423127ce
[ "BSD-3-Clause" ]
20
2015-08-19T00:46:57.000Z
2022-03-14T13:44:49.000Z
#include "Phrase.h" #include "System/System/System.h" #include <stdlib.h> #include <string.h> Phrase::Phrase() { int size=PHRASE_COUNT*16 ; // PHRASE_COUNT phrases of 0x10 steps note_=(unsigned char *)SYS_MALLOC(size) ; memset(note_,0xFF,size) ; instr_=(unsigned char *)SYS_MALLOC(size) ; memset(instr_,0xFF,size) ; cmd1_=(FourCC *)SYS_MALLOC(size*sizeof(FourCC)) ; memset(cmd1_,'-',size*sizeof(FourCC)) ; param1_=(unsigned short *)SYS_MALLOC(size*sizeof(short)) ; memset(param1_,0x00,size*sizeof(short)) ; cmd2_=(FourCC *)SYS_MALLOC(size*sizeof(FourCC)) ; memset(cmd2_,'-',size*sizeof(FourCC)) ; param2_=(unsigned short *)SYS_MALLOC(size*sizeof(short)) ; memset(param2_,0x00,size*sizeof(short)) ; for (int i=0;i<PHRASE_COUNT;i++) { isUsed_[i]=false ; } } ; Phrase::~Phrase() { if (note_) SYS_FREE(note_) ; if (instr_) SYS_FREE(instr_) ; /* CMDS_HERE if (cmd_) SYS_FREE(cmd_) ; if (cmdData_) SYS_FREE(cmdData_) ; */ } ; unsigned short Phrase::GetNext() { for (int i=0;i<PHRASE_COUNT;i++) { if (!isUsed_[i]) { isUsed_[i]=true ; return i ; } } return NO_MORE_PHRASE ; } ; void Phrase::SetUsed(unsigned char c) { isUsed_[c]=true ; } void Phrase::ClearAllocation() { for (int i=0;i<PHRASE_COUNT;i++) { isUsed_[i]=false ; } } ;
22.017241
65
0.670321
haiko21
a20db2b15be5a51a85167c4bb1c948c5cc45ade1
10,192
cpp
C++
tests/kfdtest/src/KFDDBGTest.cpp
candrews/ROCT-Thunk-Interface
4872523c79daaaf6f2c117ebe2e79629d51357da
[ "AMDPLPA" ]
null
null
null
tests/kfdtest/src/KFDDBGTest.cpp
candrews/ROCT-Thunk-Interface
4872523c79daaaf6f2c117ebe2e79629d51357da
[ "AMDPLPA" ]
null
null
null
tests/kfdtest/src/KFDDBGTest.cpp
candrews/ROCT-Thunk-Interface
4872523c79daaaf6f2c117ebe2e79629d51357da
[ "AMDPLPA" ]
null
null
null
/* * Copyright (C) 2016-2018 Advanced Micro Devices, Inc. All Rights Reserved. * * 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 "KFDDBGTest.hpp" #include <sys/ptrace.h> #include "KFDQMTest.hpp" #include "PM4Queue.hpp" #include "PM4Packet.hpp" #include "Dispatch.hpp" static const char* loop_inc_isa = \ "\ shader loop_inc_isa\n\ asic(VI)\n\ type(CS)\n\ vgpr_count(16)\n\ trap_present(1)\n\ /* TODO Enable here Address Watch Exception: */ \n\ /*copy the parameters from scalar registers to vector registers*/\n\ v_mov_b32 v0, s0\n\ v_mov_b32 v1, s1\n\ v_mov_b32 v2, s2\n\ v_mov_b32 v3, s3\n\ v_mov_b32 v5, 0 \n\ /*Iteration 1*/\n\ v_mov_b32 v4, -1\n\ flat_atomic_inc v5, v[0:1], v4 glc \n\ s_waitcnt vmcnt(0)&lgkmcnt(0)\n\ flat_load_dword v8, v[2:3] \n\ s_waitcnt vmcnt(0)&lgkmcnt(0)\n\ v_cmp_gt_u32 vcc, 2, v5 \n\ /*Iteration 2*/\n\ v_mov_b32 v4, -1\n\ flat_atomic_inc v5, v[0:1], v4 glc \n\ s_waitcnt vmcnt(0)&lgkmcnt(0)\n\ flat_load_dword v8, v[2:3] \n\ s_waitcnt vmcnt(0)&lgkmcnt(0)\n\ v_cmp_gt_u32 vcc, 2, v5 \n\ /*Epilogue*/\n\ v_mov_b32 v5, 0 \n\ s_endpgm\n\ \n\ end\n\ "; static const char* iterate_isa_gfx9 = \ "\ shader iterate_isa\n\ asic(GFX9)\n\ type(CS)\n\ /*copy the parameters from scalar registers to vector registers*/\n\ v_mov_b32 v0, s0\n\ v_mov_b32 v1, s1\n\ v_mov_b32 v2, s2\n\ v_mov_b32 v3, s3\n\ flat_load_dword v4, v[0:1] slc /*load target iteration value*/\n\ s_waitcnt vmcnt(0)&lgkmcnt(0)\n\ v_mov_b32 v5, 0\n\ LOOP:\n\ v_add_co_u32 v5, vcc, 1, v5\n\ s_waitcnt vmcnt(0)&lgkmcnt(0)\n\ /*compare the result value (v5) to iteration value (v4), and jump if equal (i.e. if VCC is not zero after the comparison)*/\n\ v_cmp_lt_u32 vcc, v5, v4\n\ s_cbranch_vccnz LOOP\n\ flat_store_dword v[2,3], v5\n\ s_waitcnt vmcnt(0)&lgkmcnt(0)\n\ s_endpgm\n\ end\n\ "; void KFDDBGTest::SetUp() { ROUTINE_START KFDBaseComponentTest::SetUp(); m_pIsaGen = IsaGenerator::Create(m_FamilyId); ROUTINE_END } void KFDDBGTest::TearDown() { ROUTINE_START if (m_pIsaGen) delete m_pIsaGen; m_pIsaGen = NULL; /* Reset the user trap handler */ hsaKmtSetTrapHandler(m_NodeInfo.HsaDefaultGPUNode(), 0, 0, 0, 0); KFDBaseComponentTest::TearDown(); ROUTINE_END } TEST_F(KFDDBGTest, BasicAddressWatch) { TEST_START(TESTPROFILE_RUNALL) if (m_FamilyId >= FAMILY_VI) { int defaultGPUNode = m_NodeInfo.HsaDefaultGPUNode(); static const unsigned int TMA_TRAP_COUNT_OFFSET = 3; static const unsigned int TMA_TRAP_COUNT_VALUE = 3; ASSERT_GE(defaultGPUNode, 0) << "failed to get default GPU Node"; // Allocate Buffers on System Memory HsaMemoryBuffer trapHandler(PAGE_SIZE*2, defaultGPUNode, true/*zero*/, false/*local*/, true/*exec*/); HsaMemoryBuffer isaBuf(PAGE_SIZE, defaultGPUNode, true/*zero*/, false/*local*/, true/*exec*/); HsaMemoryBuffer dstBuf(PAGE_SIZE*4, defaultGPUNode, true, false, false); HsaMemoryBuffer tmaBuf(PAGE_SIZE, defaultGPUNode, false, false, false); // Get Address Watch TrapHandler m_pIsaGen->GetAwTrapHandler(trapHandler); ASSERT_SUCCESS(hsaKmtSetTrapHandler(defaultGPUNode, trapHandler.As<void *>(), 0x1000, tmaBuf.As<void*>(), 0x1000)); m_pIsaGen->CompileShader(loop_inc_isa, "loop_inc_isa", isaBuf); PM4Queue queue, queue_flush; ASSERT_SUCCESS(queue.Create(defaultGPUNode)); ASSERT_SUCCESS(queue_flush.Create(defaultGPUNode)); // Set Address Watch Params // TODO: Set WatchMode[1] to Atomic in case we want to test this mode. HSA_DBG_WATCH_MODE WatchMode[2]; HSAuint64 WatchAddress[2]; HSAuint64 WatchMask[2]; HSAKMT_STATUS AddressWatchSuccess; HSAuint64 AddressMask64 = 0x0; unsigned char *secDstBuf = (unsigned char *)dstBuf.As<void*>() + 8192; WatchMode[0] = HSA_DBG_WATCH_ALL; WatchAddress[0] = (HSAuint64) dstBuf.As<void*>() & (~AddressMask64); WatchMask[0] = ~AddressMask64; WatchMode[1] = HSA_DBG_WATCH_ALL; WatchAddress[1] = (HSAuint64)secDstBuf & (~AddressMask64); WatchMask[1] = ~AddressMask64; queue_flush.PlaceAndSubmitPacket(PM4WriteDataPacket(dstBuf.As<unsigned int*>(), 0x0, 0x0)); queue_flush.PlaceAndSubmitPacket(PM4WriteDataPacket((unsigned int *)secDstBuf, 0x0, 0x0)); Delay(50); ASSERT_SUCCESS(hsaKmtDbgRegister(defaultGPUNode)); AddressWatchSuccess = hsaKmtDbgAddressWatch( defaultGPUNode, // IN 2, // # watch points &WatchMode[0], // IN reinterpret_cast<void **>(&WatchAddress[0]), // IN &WatchMask[0], // IN, optional NULL); // IN, optional EXPECT_EQ(AddressWatchSuccess, HSAKMT_STATUS_SUCCESS); Dispatch dispatch(isaBuf); dispatch.SetArgs(dstBuf.As<void*>(), reinterpret_cast<void *>(secDstBuf)); dispatch.SetDim(1, 1, 1); /* TODO: Use Memory ordering rules w/ atomics for host-GPU memory syncs. * Set to std::memory_order_seq_cst */ dispatch.Submit(queue); Delay(50); dispatch.Sync(g_TestTimeOut); // Check that we got trap handler calls due to add watch triggers EXPECT_GE(*(tmaBuf.As<unsigned int*>()+ TMA_TRAP_COUNT_OFFSET), TMA_TRAP_COUNT_VALUE); EXPECT_SUCCESS(hsaKmtDbgUnregister(defaultGPUNode)); EXPECT_SUCCESS(queue.Destroy()); EXPECT_SUCCESS(queue_flush.Destroy()); } else { LOG() << "Skipping test: Test not supported on family ID 0x" << m_FamilyId << "." << std::endl; } TEST_END } TEST_F(KFDDBGTest, BasicDebuggerSuspendResume) { TEST_START(TESTPROFILE_RUNALL) if (m_FamilyId >= FAMILY_AI) { int defaultGPUNode = m_NodeInfo.HsaDefaultGPUNode(); ASSERT_GE(defaultGPUNode, 0) << "failed to get default GPU Node"; HSAuint32 Flags = 0; HsaMemoryBuffer isaBuffer(PAGE_SIZE, defaultGPUNode, true/*zero*/, false/*local*/, true/*exec*/); HsaMemoryBuffer iterateBuf(PAGE_SIZE, defaultGPUNode, true, false, false); HsaMemoryBuffer resultBuf(PAGE_SIZE, defaultGPUNode, true, false, false); unsigned int* iter = iterateBuf.As<unsigned int*>(); unsigned int* result = resultBuf.As<unsigned int*>(); int suspendTimeout = 500; int syncStatus; m_pIsaGen->CompileShader(iterate_isa_gfx9, "iterate_isa", isaBuffer); PM4Queue queue1; HsaQueueResource *qResources; HSA_QUEUEID queue_ids[2]; ASSERT_SUCCESS(queue1.Create(defaultGPUNode)); Dispatch *dispatch1; dispatch1 = new Dispatch(isaBuffer); dispatch1->SetArgs(&iter[0], &result[0]); dispatch1->SetDim(1, 1, 1); // Need a loop large enough so we don't finish before we call Suspend. // 150000000 takes between 5 and 6 seconds, which is long enough // to test the suspend/resume. iter[0] = 150000000; ASSERT_EQ(ptrace(PTRACE_TRACEME, 0, 0, 0), 0); ASSERT_SUCCESS(hsaKmtEnableDebugTrap(defaultGPUNode, INVALID_QUEUEID)); // Submit the shader, queue1 dispatch1->Submit(queue1); qResources = queue1.GetResource(); queue_ids[0] = qResources->QueueId; ASSERT_SUCCESS(hsaKmtQueueSuspend( INVALID_PID, 1, // one queue queue_ids, 10, // grace period Flags)); syncStatus = dispatch1->SyncWithStatus(suspendTimeout); ASSERT_NE(syncStatus, HSAKMT_STATUS_SUCCESS); ASSERT_NE(iter[0], result[0]); // The shader hasn't finished, we will wait for 20 seconds, // and then check if it has finished. If it was suspended, // it should not have finished. Delay(20000); // Check that the shader has not finished yet. syncStatus = dispatch1->SyncWithStatus(suspendTimeout); ASSERT_NE(syncStatus, HSAKMT_STATUS_SUCCESS); ASSERT_NE(iter[0], result[0]); ASSERT_SUCCESS(hsaKmtQueueResume( INVALID_PID, 1, // Num queues queue_ids, Flags)); dispatch1->Sync(); ASSERT_EQ(iter[0], result[0]); EXPECT_SUCCESS(queue1.Destroy()); ASSERT_SUCCESS(hsaKmtDisableDebugTrap(defaultGPUNode)); } else { LOG() << "Skipping test: Test not supported on family ID 0x" << m_FamilyId << "." << std::endl; } TEST_END }
34.90411
130
0.624019
candrews
a20ec08e2ed2f6f95bc0caf5d1a16ed4471af97a
6,834
cpp
C++
src/ReadProvider.cpp
monsanto-pinheiro/ngmlr
8d7677929001d1d13c6b4593c409a52044180dca
[ "MIT" ]
239
2017-01-18T15:14:34.000Z
2022-03-09T10:44:08.000Z
src/ReadProvider.cpp
monsanto-pinheiro/ngmlr
8d7677929001d1d13c6b4593c409a52044180dca
[ "MIT" ]
96
2017-01-13T15:03:29.000Z
2022-02-07T14:27:18.000Z
src/ReadProvider.cpp
monsanto-pinheiro/ngmlr
8d7677929001d1d13c6b4593c409a52044180dca
[ "MIT" ]
44
2017-03-17T20:31:08.000Z
2021-12-02T07:27:09.000Z
/** * Contact: philipp.rescheneder@gmail.com */ #include "ReadProvider.h" #include <zlib.h> #include <stdio.h> #include <algorithm> #include <cmath> #include <limits.h> #include "IConfig.h" #include "Log.h" #include "Timing.h" #include "CS.h" #include "MappedRead.h" #include "FastxParser.h" //#include "BamParser.h" #include "SamParser.h" using NGMNames::ReadStatus; #undef module_name #define module_name "INPUT" ReadProvider::ReadProvider() : //bufferLength based on max read length of 1MB and read part length of readPartLength readPartLength(Config.getReadPartLength()), bufferLength(2000), parsedReads(0), /*readBuffer( new MappedRead *[bufferLength]),*/readsInBuffer(0), parser1(0) { } uint ReadProvider::init() { typedef void (*PrefixIterationFn)(ulong prefix, uloc pos, ulong mutateFrom, ulong mutateTo, void* data); char const * const fileName1 = Config.getQueryFile(); Log.Verbose("Initializing ReadProvider"); Log.Message("Opening query file %s", fileName1); size_t maxLen = readPartLength + 16; parser1 = DetermineParser(fileName1, maxLen); return 0; } ReadProvider::~ReadProvider() { if (parser1 != 0) { delete parser1; parser1 = 0; } } void ReadProvider::splitRead(MappedRead * read) { int splitNumber = read->length / readPartLength; // int splitNumber = read->length / (readPartLength / 2); int nameLength = strlen(read->name); ReadGroup * group = new ReadGroup(); group->fullRead = read; group->readId = read->ReadId; group->bestScoreSum = 0; group->fwdMapped = 0; group->reverseMapped = 0; group->readsFinished = 0; read->group = group; if (splitNumber == 0) { splitNumber = 1; group->readNumber = splitNumber; group->reads = new MappedRead *[splitNumber]; MappedRead * readPart = new MappedRead(read->ReadId + 1, readPartLength + 16); // readPart->name = new char[nameLength + 1]; strcpy(readPart->name, read->name); int length = read->length; readPart->length = length; if ((readPartLength + 16) <= length) { Log.Message("ERror ereroeroeroeor"); } readPart->Seq = new char[readPartLength + 16]; memset(readPart->Seq, '\0', readPartLength + 16); // memset(readPart->Seq, 'N', readPartLength); strncpy(readPart->Seq, read->Seq, length); //readPart->qlty = new char[readPartLength + 1]; //memset(readPart->qlty, '\0', readPartLength + 1); //strncpy(readPart->qlty, read->qlty + i * readPartLength, length); readPart->qlty = 0; readPart->group = group; group->reads[0] = readPart; } else { group->readNumber = splitNumber; group->reads = new MappedRead *[splitNumber]; memset(group->reads, 0, sizeof(MappedRead *) * splitNumber); for (int i = splitNumber - 1; i >= 0; --i) { MappedRead * readPart = new MappedRead(read->ReadId + i, readPartLength + 16); strcpy(readPart->name, read->name); int length = std::min(readPartLength, read->length - i * readPartLength); readPart->length = length; readPart->Seq = new char[readPartLength + 16]; memset(readPart->Seq, '\0', readPartLength + 16); strncpy(readPart->Seq, read->Seq + i * readPartLength, length); // strncpy(readPart->Seq, read->Seq + i * (readPartLength / 2), length); readPart->qlty = 0; readPart->group = group; readPart->group->reads[i] = readPart; } } } MappedRead * ReadProvider::NextRead(IParser * parser, int const id) { int l = 0; // if (readsInBuffer == 0 && ++parsedReads <= 20) { // if (readsInBuffer == 0) { try { static int const qryMaxLen = readPartLength + 16; MappedRead * read = new MappedRead(id, qryMaxLen); l = parser->parseRead(read); // Log.Message("Parsing next read: %s (%d)", read->name, read->length); if (l >= 0) { Log.Debug(2, "READ_%d\tINPUT\t%s", id, read->name); Log.Debug(16384, "READ_%d\tINPUT_DETAILS\t%s\t%s\t%s\t%s", id, read->Seq, read->qlty, read->AdditionalInfo); if(l > readPartLength) { splitRead(read); } else { read->group = 0; } NGM.AddReadRead(read->ReadId); NGM.Stats->readsInProcess += 1; return read; } else { Log.Debug(2, "READ_%d\tINPUT\t%s error while reading", id, read->name); if(l == -2) { Log.Error("Read %s: Length of read not equal length of quality values.", read->name); } else if (l != -1) { //TODO correct number when paired Log.Error("Unknown error while parsing read number %d (error code: %d)", id + 1, l); } } delete read; read = 0; } catch (char * ex) { Log.Error("%s", ex); } // } // if (readsInBuffer == 0) { return 0; // } else { //// Log.Message("Sending already paresed read %d", readBuffer[readsInBuffer - 1]->ReadId); // return readBuffer[readsInBuffer-- - 1]; // } } IParser * ReadProvider::DetermineParser(char const * fileName, int const qryMaxLen) { IParser * parser = 0; parser = new FastXParser(qryMaxLen); parser->init(fileName); // gzFile fp = gzopen(fileName, "r"); // if (fp == 0) { // //File does not exist // Log.Error("File %s does not exist!",fileName); // throw "File not found."; // } else { // char * buffer = new char[1000]; // while (gzgets(fp, buffer, 1000) > 0 && buffer[0] == '@') { // } // // int count = 0; // for (size_t i = 0; i < 1000 && buffer[i] != '\0' && buffer[i] != '\n'; // i++) { // if (buffer[i] == '\t') { // count++; // } // } // if (count >= 10) { // Log.Message("Input is SAM"); // parser = new SamParser(qryMaxLen); // } else { // if (strncmp(buffer, "BAM", 3) == 0) { //// Log.Message("Input is BAM"); //// parser= new BamParser(qryMaxLen); // Log.Error("BAM input is currently not supported!"); // } else { // if (buffer[0] == '>') { // Log.Message("Input is Fasta"); // } else { // Log.Message("Input is Fastq"); // } // parser = new FastXParser(qryMaxLen); // } // } // gzclose(fp); // delete[] buffer; // buffer = 0; // parser->init(fileName); // } return parser; } MappedRead * ReadProvider::GenerateSingleRead(int const readid) { MappedRead * read = 0; read = NextRead(parser1, readid); // return read; } // Sequential (important for pairs!) read generation bool ReadProvider::GenerateRead(int const readid1, MappedRead * & read1, int const readid2, MappedRead * & read2) { read1 = GenerateSingleRead(readid1); // Log.Message("Readseq: %s", read1->Seq); return read1 != 0; } void ReadProvider::DisposeRead(MappedRead * read) { // Log.Message("Disposing read %s", read->name); if (read->group != 0) { for (int j = 0; j < read->group->readNumber; ++j) { if (read->group->reads[j] != 0) { delete read->group->reads[j]; read->group->reads[j] = 0; } } delete[] read->group->reads; read->group->reads = 0; Log.Verbose("Deleting group"); delete read->group; read->group = 0; } // Single mode or no existing pair delete read; NGM.Stats->readsInProcess -= 1; }
24.494624
111
0.635353
monsanto-pinheiro
a2194dc212cac9393c009ba3a6d09d5ce07b0c01
2,858
cpp
C++
SRM628/CircuitsConstruction.cpp
CanoeFZH/SRM
02e3eeaa6044b14640e450725f68684e392009cb
[ "MIT" ]
null
null
null
SRM628/CircuitsConstruction.cpp
CanoeFZH/SRM
02e3eeaa6044b14640e450725f68684e392009cb
[ "MIT" ]
null
null
null
SRM628/CircuitsConstruction.cpp
CanoeFZH/SRM
02e3eeaa6044b14640e450725f68684e392009cb
[ "MIT" ]
null
null
null
// BEGIN CUT HERE // END CUT HERE #include <sstream> #include <cstdio> #include <cstdlib> #include <iostream> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <map> #include <string> #include <set> #include <algorithm> using namespace std; class CircuitsConstruction { public: string s; int index; int gao() { char type = s[index++]; if (type == 'X') { return 1; } else if (type == 'A') { return gao() + gao(); } else { return max(gao(), gao()); } } int maximizeResistance(string circuit, vector <int> conductors) { s = circuit; sort(conductors.rbegin(), conductors.rend()); index = 0; int number = gao(); int ret = 0; for (int i = 0; i < number; i++) { ret += conductors[i]; } return ret; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "BXBXX"; int Arr1[] = {8, 2, 3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 8; verify_case(0, Arg2, maximizeResistance(Arg0, Arg1)); } void test_case_1() { string Arg0 = "AAXXAXAXX"; int Arr1[] = {1, 1, 2, 8, 10}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 22; verify_case(1, Arg2, maximizeResistance(Arg0, Arg1)); } void test_case_2() { string Arg0 = "AXBXX"; int Arr1[] = {8, 2, 3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 11; verify_case(2, Arg2, maximizeResistance(Arg0, Arg1)); } void test_case_3() { string Arg0 = "BAAXBXXBXAXXBBAXXBXXAAXXX"; int Arr1[] = {17, 7, 21, 102, 56, 72, 88, 15, 9, 192, 16, 8, 30}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 454; verify_case(3, Arg2, maximizeResistance(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main(){ CircuitsConstruction ___test; ___test.run_test(-1); return 0; } // END CUT HERE
41.42029
308
0.557383
CanoeFZH
b8c4b1fc318ac457e0fe04dd1953fa207f50517b
584
hpp
C++
src/traderlib/core/bom/currenciesparameters.hpp
AndreaCitrolo/Trader
5ebaff6d5661471357cb827d3b0c61adafc24b50
[ "MIT" ]
null
null
null
src/traderlib/core/bom/currenciesparameters.hpp
AndreaCitrolo/Trader
5ebaff6d5661471357cb827d3b0c61adafc24b50
[ "MIT" ]
1
2019-11-06T23:15:30.000Z
2019-11-11T10:04:32.000Z
src/traderlib/core/bom/currenciesparameters.hpp
AndreaCitrolo/Trader
5ebaff6d5661471357cb827d3b0c61adafc24b50
[ "MIT" ]
1
2019-11-10T00:01:07.000Z
2019-11-10T00:01:07.000Z
#ifndef CURRENCIESPARAMETERS_HPP #define CURRENCIESPARAMETERS_HPP #include <QMetaType> #include <boost/optional.hpp> #include "basictypes.h" namespace bitinvest { namespace core { namespace bom { struct CurrenciesParameters { CurrenciesParameters(): mId("") {} CurrenciesParameters(const CurrencyId & iId): mId(iId) {} CurrenciesParameters(const CurrenciesParameters & other): mId(other.mId) {} CurrencyId mId; }; } } } Q_DECLARE_METATYPE(bitinvest::core::bom::CurrenciesParameters) #endif // CURRENCIESPARAMETERS_HPP
15.783784
62
0.702055
AndreaCitrolo
b8c4e3c791c62d32c08131fce8004b3201f97611
907
cpp
C++
Extensions/ImGui/ImGui.cpp
LinkClinton/MinesweeperVersus
fc5d4fa8aa7e2b6d4fd798d52a1614c243f4e308
[ "MIT" ]
1
2019-11-30T07:12:32.000Z
2019-11-30T07:12:32.000Z
Extensions/ImGui/ImGui.cpp
LinkClinton/MinesweeperVersus
fc5d4fa8aa7e2b6d4fd798d52a1614c243f4e308
[ "MIT" ]
null
null
null
Extensions/ImGui/ImGui.cpp
LinkClinton/MinesweeperVersus
fc5d4fa8aa7e2b6d4fd798d52a1614c243f4e308
[ "MIT" ]
null
null
null
#include "ImGui.hpp" void ImGui::BeginPropertyTable(const char* name) { Columns(2, name); Separator(); } void ImGui::Property(const char* name, const std::function<void()>& contentCall) { AlignTextToFramePadding(); Text(name); NextColumn(); AlignTextToFramePadding(); contentCall(); NextColumn(); } void ImGui::AxisProperty(const size_t axisCount, size_t& currentAxis) { assert(axisCount <= 3); static const char* AxesName[] = { "X", "Y", "Z" }; BeginPropertyTable("Combo"); Property("Axis", [&]() { if (BeginCombo("##Axis", AxesName[currentAxis])) { for (size_t index = 0; index < axisCount; index++) { const auto selected = (currentAxis == index); if (Selectable(AxesName[index], selected)) currentAxis = index; if (selected) SetItemDefaultFocus(); } EndCombo(); } }); } void ImGui::EndPropertyTable() { Columns(1); Separator(); }
17.784314
80
0.647189
LinkClinton
b8c672a3c45e3adc9548893af7c5003f8fc78eee
295
cpp
C++
Source/Core/GL_Classes/UBO.cpp
swr06/Glide3D
f37ba0365b8a6131996d966f0472f7d50d4f303f
[ "MIT" ]
37
2020-09-10T17:45:10.000Z
2022-02-16T10:59:41.000Z
Source/Core/GL_Classes/UBO.cpp
swr06/Glide3D
f37ba0365b8a6131996d966f0472f7d50d4f303f
[ "MIT" ]
1
2022-02-16T11:00:46.000Z
2022-02-16T11:00:46.000Z
Source/Core/GL_Classes/UBO.cpp
swr06/Glide3D
f37ba0365b8a6131996d966f0472f7d50d4f303f
[ "MIT" ]
1
2022-02-28T01:42:42.000Z
2022-02-28T01:42:42.000Z
#include "UBO.h" namespace Glide3D { UBO::UBO(GLsizeiptr size) { glGenBuffers(1, &m_UBO); glBindBuffer(GL_UNIFORM_BUFFER, m_UBO); glBufferData(GL_UNIFORM_BUFFER, size, nullptr, GL_STATIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); } UBO::~UBO() { glDeleteBuffers(1, &m_UBO); } }
17.352941
65
0.711864
swr06
b8ca5c4d434abc40847e9f55d90373f4fdcfaa3c
9,773
hpp
C++
Sources/epoch_config/Configs/CfgMissions/CfgmissionMilitary.hpp
Schalldampfer/Epoch
9c222bb556c704e4640daba6a5195e2e55df36e1
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2018-07-05T22:14:29.000Z
2018-07-05T22:14:29.000Z
Sources/epoch_config/Configs/CfgMissions/CfgmissionMilitary.hpp
Schalldampfer/Epoch
9c222bb556c704e4640daba6a5195e2e55df36e1
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
Sources/epoch_config/Configs/CfgMissions/CfgmissionMilitary.hpp
Schalldampfer/Epoch
9c222bb556c704e4640daba6a5195e2e55df36e1
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
class milMissionAccepted{ author = "axeman"; title = "Military Crash Site"; desc = ""; img = ""; simpleTask = 0; triggerCondition = ""; taskLimit = 3; taskCheckTime = 16; triggerDelay = 3; items[] = {""}; itemSpawn = 0; markerType = 0; markerRadius = 250; markerText = ""; initfsm = ""; initsqf = ""; initcall = ""; callEventBinTask = 0; callEventCondition1 = ""; callEventCondition2 = ""; callEventCondition3 = ""; callEventCALL1 = ""; callEventFSM1 = ""; callEventSQF1 = ""; callEventTask1 = ""; callEventCALL2 = ""; callEventFSM2 = ""; callEventSQF2 = ""; callEventTask2 = ""; callEventCALL3 = ""; callEventFSM3 = ""; callEventSQF3 = ""; callEventTask3 = ""; diag1Condition = "true"; dialogue1[] = {"A militia group has stolen military aircraft from a nearby airfield.","A stolen military aircraft has just taken off from an airport nearby.","I have received word that a splinter group are stealing an aircraft."}; diagSquelch = 30; diag2Condition = ""; dialogue2[] = {""}; diag3Condition = ""; dialogue3[] = {""}; failedCondition = ""; abandonDist = -1; abandonTime = 480; failed[] = {""}; failedFSM = ""; failedSQF = ""; failedCall = ""; failedTask[] = {""}; cleanUp = 0; cleanUpCalls[] = {}; completeCondition = "true"; reward[] = {""}; completed1[] = {""}; completed2[] = {""}; completedCALL = ""; reminder[] = {""}; nextTask[] = {"milSpawnCrashSite"}; }; class milSpawnCrashSite{ author = "axeman"; title = "Military Spawn Crash Site"; desc = ""; img = ""; simpleTask = 0; triggerCondition = ""; taskLimit = 3; taskCheckTime = 16; triggerDelay = 0; items[] = {""}; itemSpawn = 0; markerType = 0; markerRadius = 250; markerText = ""; initfsm = ""; initsqf = ""; initcall = "[] spawn {milCrashPos = [position player, 1000, 2550, 0, 0, 1000, 0] call BIS_fnc_findSafePos;terminate _thisScript;};"; callEventBinTask = 0; callEventCondition1 = "(diag_tickTime - EPOCH_task_startTime) > 12"; callEventCondition2 = ""; callEventCondition3 = ""; callEventCALL1 = "[player,Epoch_personalToken,selectRandom [""B_Plane_CAS_01_F"",""O_Heli_Attack_02_black_F"",""B_UAV_02_CAS_F"",""I_Plane_Fighter_03_AA_F ""],milCrashPos,objNull,false,""CAN_COLLIDE"","""","""","""","""",true] remoteExec [""EPOCH_Server_createObject"",2];"; callEventFSM1 = ""; callEventSQF1 = ""; callEventTask1 = ""; callEventCALL2 = ""; callEventFSM2 = ""; callEventSQF2 = ""; callEventTask2 = ""; callEventCALL3 = ""; callEventFSM3 = ""; callEventSQF3 = ""; callEventTask3 = ""; diag1Condition = "(diag_tickTime - EPOCH_task_startTime) > 6"; dialogue1[] = {"As suspected, the aircraft was sabotaged and has crashed.","An inept theft attempt, the aircraft has gone down.","Something went wrong, my UAV has spotted the aircraft, it has crashed nearby."}; diagSquelch = 15; diag2Condition = "true"; dialogue2[] = {}; diag3Condition = ""; dialogue3[] = {""}; failedCondition = ""; abandonDist = -1; abandonTime = 480; failed[] = {""}; failedFSM = ""; failedSQF = ""; failedCall = ""; failedTask[] = {""}; cleanUp = 0; cleanUpCalls[] = {}; completeCondition = "(diag_tickTime - EPOCH_task_startTime) > 18"; reward[] = {""}; completed1[] = {""}; completed2[] = {""}; completedCALL = "true"; reminder[] = {"Wait 10, I am triangulating the position.","Hold your position and wait for the location","I am calculating the location of the crash site."}; nextTask[] = {"milMarkCrashSite"}; }; class milMarkCrashSite{ author = "axeman"; title = "Mark Military Crash Site"; desc = ""; img = ""; simpleTask = 0; triggerCondition = ""; taskLimit = 3; taskCheckTime = 16; triggerDelay = 3; items[] = {""}; itemSpawn = 0; markerType = 0; markerRadius = 500; markerText = "Crash Site"; initfsm = ""; initsqf = ""; initcall = "[[1,player],milCrashPos,""ELLIPSE"",""mil_dot"",""Crash Site"",""ColorRed"",[800,800], ""SolidBorder"", 42, 0.6, ""milMarkCrashSite""] remoteExec [""EPOCH_server_makeMarker"",2];"; callEventBinTask = 0; callEventCondition1 = "true"; callEventCondition2 = "true"; callEventCondition3 = "true"; callEventCALL1 = "milWH1 = createVehicle[""groundWeaponHolder"", milCrashPos, [], 4, ""CAN_COLLIDE""];removeFromRemainsCollector [milWH1];[milWH1,""Pelican_EPOCH""] remoteExec [""EPOCH_serverLootObject"",2];"; callEventFSM1 = ""; callEventSQF1 = ""; callEventTask1 = ""; callEventCALL2 = "milWH2 = createVehicle[""groundWeaponHolder"", milCrashPos, [], 4, ""CAN_COLLIDE""];removeFromRemainsCollector [milWH2];[milWH2,""ToolRack_EPOCH""] remoteExec [""EPOCH_serverLootObject"",2];"; callEventFSM2 = ""; callEventSQF2 = ""; callEventTask2 = ""; callEventCALL3 = "milWH3 = createVehicle[""groundWeaponHolder"", milCrashPos, [], 4, ""CAN_COLLIDE""];removeFromRemainsCollector [milWH3];[milWH3,""AirDrop_Payout1""] remoteExec [""EPOCH_serverLootObject"",2];"; callEventFSM3 = ""; callEventSQF3 = ""; callEventTask3 = ""; diag1Condition = "(diag_tickTime - EPOCH_task_startTime) > 6"; dialogue1[] = {"Check your map, I have marked the site in red for your team.","Your map has been marked.","I have added a marker for your team."}; diagSquelch = 30; diag2Condition = "(diag_tickTime - EPOCH_task_startTime) > 31"; dialogue2[] = {"Reports are it was last spotted in that area..","Search the area, it was seen coming down from that location.","Be sure to search the area, the marker is the last know location."}; diag3Condition = "(diag_tickTime - EPOCH_task_startTime) > 128"; dialogue3[] = {"Be careful, I have spotted another UAV.","An enemy UAV is scouting the location","Keep a low profile, the enemy are scouting the area."}; failedCondition = ""; abandonDist = -1; abandonTime = 1280; failed[] = {""}; failedFSM = ""; failedSQF = ""; failedCall = ""; failedTask[] = {""}; cleanUp = 0; cleanUpCalls[] = {}; completeCondition = "(diag_tickTime - EPOCH_task_startTime) > 60"; reward[] = {""}; completed1[] = {""}; completed2[] = {""}; completedCALL = ""; reminder[] = {""}; nextTask[] = {"milFindCrashSite"}; }; class milFindCrashSite{ author = "axeman"; title = "Military Crash Site Hunt"; desc = ""; img = ""; simpleTask = 0; triggerCondition = ""; taskLimit = 3; taskCheckTime = 16; triggerDelay = 20; items[] = {""}; itemSpawn = 0; markerType = 0; markerRadius = 250; markerText = ""; initfsm = ""; initsqf = ""; initcall = "milDoUAV = false;"; callEventBinTask = 0; callEventCondition1 = "count (units group player select {_x distance milCrashPos < 800}) > 0"; callEventCondition2 = "count (units group player select {_x distance milCrashPos < 480}) > 0 && random 100 < 12"; callEventCondition3 = ""; callEventCALL1 = "_diag = format [""Great work the UAV has spotted %1 nearly on-site."",name ((units group player select {_x distance milCrashPos < 800}) select 0)];[_diag, 5,[[0,0,0,0.5],[1,0.5,0,1]]] call Epoch_message;"; callEventFSM1 = ""; callEventSQF1 = ""; callEventTask1 = ""; callEventCALL2 = "[(selectRandom (units group player select {_x distance milCrashPos < 480}))] execVM ""epoch_code\compile\missions\tasks\mission_spawnUAV.sqf"";milDoUAV = true;"; callEventFSM2 = ""; callEventSQF2 = ""; callEventTask2 = ""; callEventCALL3 = ""; callEventFSM3 = ""; callEventSQF3 = ""; callEventTask3 = ""; diag1Condition = "count (units group player select {_x distance milCrashPos < 1000}) > 0"; dialogue1[] = {"Keep going you are getting close now","You are closing in on the target.","You are nearly there. Keep it up."}; diagSquelch = 60; diag2Condition = "milDoUAV"; dialogue2[] = {"Enemy UAV spotted, you've got company.","You've got another UAV in the area, keep low.","Find a spot to hide, enemy UAV incoming."}; diag3Condition = "count (units group player select {_x distance milCrashPos < 60}) > 0"; dialogue3[] = {"You've made it, find any loot.","Search the area, there will be loot around","There should be plenty to scavange."}; failedCondition = ""; abandonDist = -1; abandonTime = 4800; failed[] = {""}; failedFSM = ""; failedSQF = ""; failedCall = ""; failedTask[] = {""}; cleanUp = 0; cleanUpCalls[] = {}; completeCondition = "(diag_tickTime - EPOCH_task_startTime) > 4600 || count (units group player select {_x distance milWH1 < 60}) > 0"; reward[] = {""}; completed1[] = {""}; completed2[] = {""}; completedCALL = ""; reminder[] = {""}; nextTask[] = {"milEndCrashSite"}; }; class milEndCrashSite{ author = "axeman"; title = ""; desc = ""; img = ""; simpleTask = 0; triggerCondition = ""; taskLimit = 3; taskCheckTime = 16; triggerDelay = 16; items[] = {""}; itemSpawn = 1; markerType = 0; markerRadius = 50; markerText = ""; initfsm = ""; initsqf = ""; initcall = ""; callEventBinTask = 0; callEventCondition1 = ""; callEventCondition2 = ""; callEventCondition3 = ""; callEventCALL1 = ""; callEventFSM1 = ""; callEventSQF1 = ""; callEventTask1 = ""; callEventCALL2 = ""; callEventFSM2 = ""; callEventSQF2 = ""; callEventTask2 = ""; callEventCALL3 = ""; callEventFSM3 = ""; callEventSQF3 = ""; callEventTask3 = ""; diag1Condition = "true"; dialogue1[] = {"Well done, that was a good find","You are an official scavenger now, congratulations.","Your loot is welcome at my store any time."}; diagSquelch = 60; diag2Condition = ""; dialogue2[] = {""}; diag3Condition = ""; dialogue3[] = {""}; failedCondition = ""; abandonDist = 100; abandonTime = 240; failed[] = {""}; failedFSM = ""; failedSQF = ""; failedCall = ""; failedTask[] = {""}; cleanUp = 1; cleanUpCalls[] = {}; completeCondition = "true"; reward[] = {""}; completed1[] = {""}; completed2[] = {""}; completedCALL = "[player,1,""milMarkCrashSite""] remoteExec [""EPOCH_server_removeMarker"",2];"; reminder[] = {""}; nextTask[] = {""}; };
32.905724
275
0.657935
Schalldampfer
b8cac45d6ebb93700e518a743d05ed66389eb4fa
12,097
cpp
C++
src/pipeline/pipelineBuilder.cpp
haddenkim/hush
c003fa327874cf3890da50e8914730974c648f3f
[ "MIT" ]
2
2019-04-28T19:49:15.000Z
2020-06-29T06:04:51.000Z
src/pipeline/pipelineBuilder.cpp
haddenkim/hush
c003fa327874cf3890da50e8914730974c648f3f
[ "MIT" ]
5
2020-03-15T20:17:58.000Z
2020-03-15T21:05:31.000Z
src/pipeline/pipelineBuilder.cpp
haddenkim/hush
c003fa327874cf3890da50e8914730974c648f3f
[ "MIT" ]
null
null
null
#include "pipelineBuilder.h" #include "pipeline/pipeline.h" #include "pipelineBuffer/buffer.h" #include "renderPass/denoise/atrousDenoiserPass.h" #include "renderPass/post/toneMapPass.h" #include "renderPass/raster/rasterGBufferPass.h" #include "renderPass/raster/ssAmbientPass.h" #include "renderPass/raster/ssLightPass.h" #include "renderPass/ray/pathTracePass.h" #include "renderPass/renderToScreenPass.h" #include "pipelineBuffer/buffer.h" #include "pipelineBuffer/bufferSync.h" #include "pipelineBuffer/cpuBuffer.h" #include "pipelineBuffer/gpuBuffer.h" #include "pipelineBuffer/spectrumBuffer.h" #include "pipelineBuffer/vec3fBuffer.h" PipelineBuilder::PipelineBuilder(Pipeline& pipeline) : m_pipeline(pipeline) { } bool PipelineBuilder::createPipeline(const BuildPipeline& buildPipeline) { // set pipeline properties m_pipeline.m_width = buildPipeline.width; m_pipeline.m_height = buildPipeline.height; m_pipeline.m_scene = buildPipeline.scene; m_pipeline.m_camera = buildPipeline.camera; // for each stage in pipeline for (const BuildStage& buildStage : buildPipeline.stages) { // index of next stage uint stageIndex = m_pipeline.m_stages.size(); // add an empty pipeline stage m_pipeline.m_stages.emplace_back(); // retrieve reference to new stage PipelineStage& pipelineStage = m_pipeline.m_stages.back(); // create the stage bool stageSuccess = createStage(buildStage, stageIndex, pipelineStage); // return false if failed to create stage if (!stageSuccess) { printPipeline(); assert(!"pipeline build failed"); return false; } } printPipeline(); return true; } bool PipelineBuilder::createStage(const BuildStage& buildStage, uint stageIndex, PipelineStage& pipelineStage) { // create empty pipeline pass pipelineStage.m_passes.emplace_back(); // retrieve reference to new pass PipelinePass& pipelinePass = pipelineStage.m_passes.back(); // for each pass in stage for (const BuildPass& buildPass : buildStage.passes) { // create the pass bool passSuccess = createPass(buildPass, stageIndex, pipelinePass); // return false if failed to create pass if (!passSuccess) { assert(!"stage build failed"); return false; } } return true; } bool PipelineBuilder::createPass(const BuildPass& buildPass, uint stageIndex, PipelinePass& pipelinePass) { // for each link in pass for (const BuildLink& buildLink : buildPass.links) { // create empty pipeline link pipelinePass.m_links.emplace_back(); // retrieve reference to new link PipelineIOLink& pipelineLink = pipelinePass.m_links.back(); // create the link bool linkSuccess = createLink(buildLink, pipelineLink); // return false if failed to create link if (!linkSuccess) { assert(!"pass build failed"); return false; } } // create the pass switch (buildPass.type) { case RASTER_GBUFFER: pipelinePass.m_renderPass = new RasterGBufferPass(m_pipeline.m_scene, m_pipeline.m_camera, static_cast<GpuBuffer*>(createOutputBuffer(GPU, G_POSITION, pipelinePass)), static_cast<GpuBuffer*>(createOutputBuffer(GPU, G_NORMAL, pipelinePass)), static_cast<GpuBuffer*>(createOutputBuffer(GPU, G_MAT_AMBIENT, pipelinePass)), static_cast<GpuBuffer*>(createOutputBuffer(GPU, G_MAT_DIFFUSE, pipelinePass)), static_cast<GpuBuffer*>(createOutputBuffer(GPU, G_MAT_SPECULAR, pipelinePass))); break; case SS_DIRECT_LIGHT: pipelinePass.m_renderPass = new SsLightPass(m_pipeline.m_scene, m_pipeline.m_camera, static_cast<GpuBuffer*>(requestInputBuffer(GPU, G_POSITION, stageIndex, pipelinePass)), static_cast<GpuBuffer*>(requestInputBuffer(GPU, G_NORMAL, stageIndex, pipelinePass)), static_cast<GpuBuffer*>(requestInputBuffer(GPU, G_MAT_DIFFUSE, stageIndex, pipelinePass)), static_cast<GpuBuffer*>(requestInputBuffer(GPU, G_MAT_SPECULAR, stageIndex, pipelinePass)), m_pipeline.m_canvasVAO, static_cast<GpuBuffer*>(createOutputBuffer(GPU, COLOR, pipelinePass))); break; case SS_AMBIENT: pipelinePass.m_renderPass = new SsAmbientPass(static_cast<GpuBuffer*>(requestInputBuffer(GPU, COLOR, stageIndex, pipelinePass)), static_cast<GpuBuffer*>(requestInputBuffer(GPU, G_MAT_AMBIENT, stageIndex, pipelinePass)), static_cast<GpuBuffer*>(requestInputBuffer(GPU, G_MAT_DIFFUSE, stageIndex, pipelinePass)), m_pipeline.m_canvasVAO, static_cast<GpuBuffer*>(createOutputBuffer(GPU, COLOR, pipelinePass))); break; case RT_FULL_GI: pipelinePass.m_renderPass = new PathTracePass(m_pipeline.m_scene, m_pipeline.m_camera, m_pipeline.m_width, m_pipeline.m_height, static_cast<SpectrumBuffer*>(createOutputBuffer(CPU, COLOR, pipelinePass)), static_cast<Vec3fBuffer*>(createOutputBuffer(CPU, G_POSITION, pipelinePass)), static_cast<Vec3fBuffer*>(createOutputBuffer(CPU, G_NORMAL, pipelinePass)), static_cast<SpectrumBuffer*>(createOutputBuffer(CPU, G_MAT_DIFFUSE, pipelinePass))); break; case DENOISE_ATROUS: pipelinePass.m_renderPass = new AtrousDenoiserPass(static_cast<GpuBuffer*>(requestInputBuffer(GPU, COLOR, stageIndex, pipelinePass)), static_cast<GpuBuffer*>(requestInputBuffer(GPU, G_POSITION, stageIndex, pipelinePass)), static_cast<GpuBuffer*>(requestInputBuffer(GPU, G_NORMAL, stageIndex, pipelinePass)), m_pipeline.m_width, m_pipeline.m_canvasVAO, static_cast<GpuBuffer*>(createOutputBuffer(GPU, COLOR, pipelinePass))); break; case PP_TONE_MAP: pipelinePass.m_renderPass = new ToneMapPass(static_cast<GpuBuffer*>(requestInputBuffer(GPU, COLOR, stageIndex, pipelinePass)), m_pipeline.m_canvasVAO, static_cast<GpuBuffer*>(createOutputBuffer(GPU, COLOR, pipelinePass))); break; case TO_SCREEN: // special case - set pipeline display buffer { const PipelineIOLink& lastLink = pipelinePass.m_links.back(); PipelineIO lastType = lastLink.m_types.back(); m_pipeline.m_displayBuffer = findOutBuffer(GPU, lastType, lastLink.m_fromStage, lastLink.m_fromPass); pipelinePass.m_renderPass = new RenderToScreenPass(&m_pipeline.m_displayBuffer, m_pipeline.m_canvasVAO); } break; default: assert(!"RenderPassType not implemented in builder"); return false; } return true; } bool PipelineBuilder::createLink(const BuildLink& buildLink, PipelineIOLink& pipelineLink) { // validate inputs exist if (!validateDependencies(buildLink)) { assert(!"link build failed"); return false; } pipelineLink.m_fromStage = buildLink.fromStage; pipelineLink.m_fromPass = buildLink.fromPass; for (PipelineIO ioType : buildLink.ioTypes) { pipelineLink.m_types.emplace_back(ioType); } return true; } bool PipelineBuilder::validateDependencies(const BuildLink& buildLink) { uint fromStage = buildLink.fromStage; uint fromPass = buildLink.fromPass; // check stage count if (fromStage >= m_pipeline.m_stages.size()) { assert(!"dependency validation failed"); return false; } const PipelineStage& fromPipelineStage = m_pipeline.m_stages[buildLink.fromStage]; // check pass count if (fromPass >= fromPipelineStage.m_passes.size()) { assert(!"dependency validation failed"); return false; } const PipelinePass& fromPipelinePass = fromPipelineStage.m_passes[buildLink.fromPass]; // get reference to buffer list at desired pass in desired stage const std::vector<Buffer*>& fromPipelinePassBuffers = fromPipelinePass.m_buffers; // verify all iotypes exist for (PipelineIO ioType : buildLink.ioTypes) { bool isThisTypeFound = false; // search the buffer list for this ioType for (Buffer* buffer : fromPipelinePassBuffers) { if (ioType == buffer->m_type) { isThisTypeFound = true; break; } } if (!isThisTypeFound) { assert(!"dependency validation failed"); return false; } } return true; } Buffer* PipelineBuilder::createOutputBuffer(PipelineHW hw, PipelineIO type, PipelinePass& pipelinePass) { Buffer* buffer = createBuffer(hw, type); pipelinePass.m_buffers.push_back(buffer); return buffer; } Buffer* PipelineBuilder::requestInputBuffer(PipelineHW hw, PipelineIO type, uint stageIndex, PipelinePass& pipelinePass) { // determine output buffer location uint fromStage; uint fromPass; bool isFound = false; for (const PipelineIOLink pipelineLink : pipelinePass.m_links) { for (PipelineIO ioType : pipelineLink.m_types) { if (type == ioType) { fromStage = pipelineLink.m_fromStage; fromPass = pipelineLink.m_fromPass; isFound = true; break; } } if (isFound) { break; } } assert(isFound); // should not fail because of prior validateDependencies // find the output buffer Buffer* outBuffer = findOutBuffer(hw, type, fromStage, fromPass); if (outBuffer->m_hardware == hw) { // same type & hw return outBuffer; } else { // same type but diff hw return createBufferSync(hw, type, outBuffer, stageIndex); } } Buffer* PipelineBuilder::createBufferSync(PipelineHW hw, PipelineIO type, Buffer* fromBuffer, uint stageIndex) { Buffer* toBuffer = createBuffer(hw, type); m_pipeline.m_stages[stageIndex].m_bufferSyncs.emplace_back(new BufferSync(fromBuffer, toBuffer)); return toBuffer; } Buffer* PipelineBuilder::createBuffer(PipelineHW hw, PipelineIO type) { Buffer* buffer; if (hw == GPU) { buffer = new GpuBuffer(type, m_pipeline.m_width, m_pipeline.m_height); } else { // CPU switch (type) { case G_MAT_DIFFUSE: case COLOR: buffer = new SpectrumBuffer(type, m_pipeline.m_width, m_pipeline.m_height); break; case G_POSITION: case G_NORMAL: buffer = new Vec3fBuffer(type, m_pipeline.m_width, m_pipeline.m_height); break; default: assert(!"hw + io type not implemented in builder"); break; } } return buffer; } Buffer* PipelineBuilder::findOutBuffer(PipelineHW hw, PipelineIO type, uint fromStage, uint fromPass) { std::vector<Buffer*>& outBuffers = m_pipeline.m_stages[fromStage].m_passes[fromPass].m_buffers; // search for matching buffer type Buffer* fromBuffer; for (Buffer* outBuffer : outBuffers) { if (outBuffer->m_type == type) { // continue to check for matching hw in case output buffers contain both if (outBuffer->m_hardware == hw) { // same type & hw return outBuffer; } else { // same type but diff hw fromBuffer = outBuffer; } } } return fromBuffer; } void PipelineBuilder::printPipeline() { printf("Pipeline \n"); for (size_t s = 0; s < m_pipeline.m_stages.size(); s++) { const PipelineStage& stage = m_pipeline.m_stages[s]; uint numBS = stage.m_bufferSyncs.size(); uint numRP = stage.m_passes.size(); printf("Stage %lu\n", s); printf("\tBufferSyncs %i\n", numBS); for (size_t bs = 0; bs < numBS; bs++) { const BufferSync* bufferSync = stage.m_bufferSyncs[bs]; printf("\t\t%lu: \t", bs); Buffer* fromBuffer = bufferSync->m_fromBuffer; printf("From: %s %s\t", PipelineHWNames[fromBuffer->m_hardware], PipelineIONames[fromBuffer->m_type]); Buffer* toBuffer = bufferSync->m_toBuffer; printf("To : %s %s\n", PipelineHWNames[toBuffer->m_hardware], PipelineIONames[toBuffer->m_type]); } printf("\tRenderPasses %i\n", numRP); for (size_t p = 0; p < numRP; p++) { const PipelinePass& pass = stage.m_passes[p]; const RenderPass* renderPass = pass.m_renderPass; printf("\t\t%lu: %s\n", p, renderPass->m_name.c_str()); for (Buffer* buffer : pass.m_buffers) { printf("\t\tOut: %s %s\n", PipelineHWNames[buffer->m_hardware], PipelineIONames[buffer->m_type]); } for (const PipelineIOLink& pipeLink : pass.m_links) { printf("\t\tIn : %i %i ", pipeLink.m_fromStage, pipeLink.m_fromPass); for (PipelineIO io : pipeLink.m_types) { printf("%s, ", PipelineIONames[io]); } printf("\n"); } } } printf("\n"); }
30.703046
135
0.716872
haddenkim
b8d2dd013a617ba1d952baf69de99106d1898f42
553
cpp
C++
Codeforces/616A.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
Codeforces/616A.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
Codeforces/616A.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ string s,s2; cin>>s>>s2; if ( s.size()>s2.size()){ reverse ( s2.begin(),s2.end()); while ( s.size()>s2.size()) s2.push_back('0'); reverse ( s2.begin(),s2.end()); } else if ( s2.size()>s.size()){ reverse ( s.begin(),s.end()); while ( s2.size()>s.size()) s.push_back('0'); reverse ( s.begin(),s.end()); } for ( int i = 0 ; s.size()> i ; i++){ if ( s[i]>s2[i]){ cout<<">"; return 0; } else if ( s2[i]>s[i]){ cout<<"<"; return 0 ; } } cout<<"="; }
19.068966
38
0.490054
Alipashaimani
b8d2e6db63e230045d63e9812d70e66896c672b1
433
hpp
C++
graph/ir.hpp
jitMatrix/xiuxian
ba52d11f39957dd14ca34b51ccb5fadb422e6833
[ "Apache-2.0" ]
3
2021-03-08T06:17:55.000Z
2021-04-09T12:50:21.000Z
graph/ir.hpp
jitMatrix/xiuxian
ba52d11f39957dd14ca34b51ccb5fadb422e6833
[ "Apache-2.0" ]
null
null
null
graph/ir.hpp
jitMatrix/xiuxian
ba52d11f39957dd14ca34b51ccb5fadb422e6833
[ "Apache-2.0" ]
null
null
null
#ifndef IR_HPP #define IR_HPP #include <vector> using namespace std; class node { public: int val; vector<node*> neighbors; node() { val = 0; neighbors = vector<node*>(); } node(int _val) { val = _val; neighbors = vector<node*>(); } node(int _val, vector<node*> _neighbors) { val = _val; neighbors = _neighbors; } }; #endif // IR_HPP
14.433333
46
0.52194
jitMatrix
b8e2ca8edde474dea2540be789f6d2e6e98c256e
868
cpp
C++
test/son_functional_test.cpp
pdebus/MTVMTL
65a7754b34d1f6a1e86d15e3c2d4346b9418414f
[ "MIT" ]
3
2017-05-08T12:40:46.000Z
2019-06-02T05:11:01.000Z
test/son_functional_test.cpp
pdebus/MTVMTL
65a7754b34d1f6a1e86d15e3c2d4346b9418414f
[ "MIT" ]
null
null
null
test/son_functional_test.cpp
pdebus/MTVMTL
65a7754b34d1f6a1e86d15e3c2d4346b9418414f
[ "MIT" ]
null
null
null
#include <iostream> #define TV_DATA_DEBUG #define TV_FUNC_DEBUG_VERBOSE #define TVMTL_TVMIN_DEBUG_VERBOSE #include <mtvmtl/core/algo_traits.hpp> #include <mtvmtl/core/data.hpp> #include <mtvmtl/core/functional.hpp> int main(int argc, const char *argv[]) { using namespace tvmtl; /* if (argc != 2){ std::cerr << "Usage : " << argv[0] << " image" << std::endl; return 1; } */ typedef Manifold< SO, 3 > mf_t; typedef Data< mf_t, 2> data_t; typedef Functional<FIRSTORDER, ISO, mf_t, data_t> func_t; data_t myData = data_t(); myData.create_nonsmooth_son(30,35); myData.output_matval_img("son_img.csv"); double lam=0.1; func_t myFunc(lam, myData); myFunc.seteps2(1e-10); func_t::result_type result = 0.0; //Functional evaluation result = myFunc.evaluateJ(); //Gradient myFunc.evaluateDJ(); //Hessian myFunc.evaluateHJ(); return 0; }
19.727273
65
0.698157
pdebus
b8e5606f8bf3de9743323739af0b762f1169319d
747
cpp
C++
plugins/matchmaker/clientsrc/matchmaker_client.cpp
pretty-wise/link
16a4241c4978136d8c4bd1caab20bdf37df9caaf
[ "Unlicense" ]
null
null
null
plugins/matchmaker/clientsrc/matchmaker_client.cpp
pretty-wise/link
16a4241c4978136d8c4bd1caab20bdf37df9caaf
[ "Unlicense" ]
5
2019-12-27T05:51:10.000Z
2022-02-12T02:24:58.000Z
plugins/matchmaker/clientsrc/matchmaker_client.cpp
pretty-wise/link
16a4241c4978136d8c4bd1caab20bdf37df9caaf
[ "Unlicense" ]
null
null
null
/* * Copywrite 2014-2015 Krzysztof Stasik. All rights reserved. */ #include "plugin/matchmaker/matchmaker_client.h" #include "base/core/macro.h" #include "common/protobuf_stream.h" //#include "protocol/gate.pb.h" namespace Link { namespace Matchmaker { static const Base::LogChannel kMatchLog("match_client"); struct context_t { Gate::context_t* server; }; struct context_t* Create(Gate::context_t* ctx, void* udata) { if(ctx == nullptr) { return nullptr; } context_t* context = new context_t(); context->server = ctx; BASE_INFO(kMatchLog, "created %p", context); return context; } void Destory(struct context_t* ctx) { delete ctx; BASE_INFO(kMatchLog, "destroyed %p", ctx); } } // namespace Matchmaker } // namespace Link
19.657895
61
0.717537
pretty-wise
b8e5bc86d88a238786c4eb8bbed4545ee7363d36
336
cpp
C++
GLTFSDK/Source/Extension.cpp
ninerdelta/glTF-SDK
db5c8dfd02f1a027cea63194a6472574cfe8d723
[ "MIT" ]
243
2019-05-22T04:35:22.000Z
2022-03-30T21:04:37.000Z
GLTFSDK/Source/Extension.cpp
ninerdelta/glTF-SDK
db5c8dfd02f1a027cea63194a6472574cfe8d723
[ "MIT" ]
43
2019-05-07T17:37:13.000Z
2022-03-17T12:47:30.000Z
GLTFSDK/Source/Extension.cpp
ninerdelta/glTF-SDK
db5c8dfd02f1a027cea63194a6472574cfe8d723
[ "MIT" ]
64
2019-05-24T14:09:28.000Z
2022-03-13T02:24:27.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include <GLTFSDK/Extension.h> using namespace Microsoft::glTF; bool Extension::operator==(const Extension& rhs) const { return IsEqual(rhs); } bool Extension::operator!=(const Extension& rhs) const { return !operator==(rhs); }
19.764706
60
0.723214
ninerdelta
b8e63b16977d0b2045bb61a09d27080c0688a224
1,879
cpp
C++
UIFrameWork2.6/msgbox.cpp
zlj9328/emokit
113e4841278a4bc970aaea08bc89e0a6d14ec2e4
[ "MIT" ]
null
null
null
UIFrameWork2.6/msgbox.cpp
zlj9328/emokit
113e4841278a4bc970aaea08bc89e0a6d14ec2e4
[ "MIT" ]
null
null
null
UIFrameWork2.6/msgbox.cpp
zlj9328/emokit
113e4841278a4bc970aaea08bc89e0a6d14ec2e4
[ "MIT" ]
null
null
null
#include "msgbox.h" #include "ui_msgbox.h" #include <QFile> #include "IcoHelper/iconhelper.h" MsgBox::MsgBox(QWidget *parent) : QDialog(parent), ui(new Ui::MsgBox) { ui->setupUi(this); this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinMaxButtonsHint); ui->titleWidget->titleInit(tr("MessageBox"), false, true); connect(ui->OKButton,SIGNAL(clicked()),this,SLOT(accept())); connect(ui->CannelButton,SIGNAL(clicked()),this,SLOT(reject())); } MsgBox::~MsgBox() { delete ui; } /** * @brief MsgBox::SetInfoIcon * @param c * @param color */ void MsgBox::SetInfoIcon(QChar c, const QColor &color) { QPalette palette; palette.setColor(QPalette::WindowText, color); ui->infoIcon->setPalette(palette); IconHelper::Instance()->SetIcon(ui->infoIcon, c, 45); } /** * @brief MsgBox::SetInfo * @param str */ void MsgBox::SetInfo(const QString str) { ui->Info->setText(str); } /** * @brief MsgBox::SetTitle * @param str */ void MsgBox::SetTitle(const QString str) { ui->titleWidget->setTitleName(str); } /** * @brief MsgBox::Waring * @param str */ void MsgBox::Waring(const QString str) { SetInfoIcon(WARING_MSG, Qt::red); ui->Info->setText(str); ui->titleWidget->setTitleName(tr("Waring")); // ui->CannelButton->hide(); ui->OKButton->setFocus(); } /** * @brief MsgBox::Information * @param str */ void MsgBox::Information(const QString str) { SetInfoIcon(INFORMATION_MSG, Qt::green); ui->Info->setText(str); ui->titleWidget->setTitleName(tr("Information")); ui->CannelButton->hide(); ui->OKButton->setFocus(); } /** * @brief MsgBox::Question * @param str */ void MsgBox::Question(const QString str) { SetInfoIcon(QUESTION_MSG, Qt::yellow); ui->Info->setText(str); ui->titleWidget->setTitleName(tr("Question")); ui->CannelButton->setFocus(); }
19.989362
80
0.656732
zlj9328
b8e69be951f5164208d9d02ebaacb268b706ac8d
15,235
cpp
C++
XivAlexander/DllMain.cpp
retaker/XivAlexander
03b64118500c3e6e7c3a035af473ef2bd0303bff
[ "Apache-2.0" ]
345
2021-02-08T18:11:24.000Z
2022-03-25T04:01:23.000Z
XivAlexander/DllMain.cpp
retaker/XivAlexander
03b64118500c3e6e7c3a035af473ef2bd0303bff
[ "Apache-2.0" ]
376
2021-02-12T07:23:57.000Z
2022-03-31T00:05:35.000Z
XivAlexander/DllMain.cpp
retaker/XivAlexander
03b64118500c3e6e7c3a035af473ef2bd0303bff
[ "Apache-2.0" ]
65
2021-02-12T05:47:14.000Z
2022-03-25T03:08:23.000Z
#include "pch.h" #include "DllMain.h" #include <XivAlexander/XivAlexander.h> #include <XivAlexanderCommon/Sqex_CommandLine.h> #include <XivAlexanderCommon/Utils_Win32_Resource.h> #include "App_ConfigRepository.h" #include "App_Misc_CrashMessageBoxHandler.h" #include "App_Misc_Hooks.h" #include "resource.h" #include "App_Misc_GameInstallationDetector.h" static Utils::Win32::LoadedModule s_hModule; static Utils::Win32::ActivationContext s_hActivationContext; static std::string s_dllUnloadDisableReason; static bool s_bLoadedAsDependency = false; static bool s_bLoadedFromEntryPoint = false; static std::unique_ptr<App::Misc::CrashMessageBoxHandler> s_crashMessageBoxHandler; const Utils::Win32::LoadedModule& Dll::Module() { return s_hModule; } const Utils::Win32::ActivationContext& Dll::ActivationContext() { return s_hActivationContext; } const char* XivAlexDll::LoaderActionToString(LoaderAction val) { switch (val) { case LoaderAction::Interactive: return "interactive"; case LoaderAction::Web: return "web"; case LoaderAction::Ask: return "ask"; case LoaderAction::Load: return "load"; case LoaderAction::Unload: return "unload"; case LoaderAction::Launcher: return "launcher"; case LoaderAction::UpdateCheck: return "update-check"; case LoaderAction::Install: return "install"; case LoaderAction::Uninstall: return "uninstall"; case LoaderAction::Internal_Update_DependencyDllMode: return "_internal_update_dependencydllmode"; case LoaderAction::Internal_Update_Step2_ReplaceFiles: return "_internal_update_step2_replacefiles"; case LoaderAction::Internal_Update_Step3_CleanupFiles: return "_internal_update_step3_cleanupfiles"; case LoaderAction::Internal_Inject_HookEntryPoint: return "_internal_inject_hookentrypoint"; case LoaderAction::Internal_Inject_LoadXivAlexanderImmediately: return "_internal_inject_loadxivalexanderimmediately"; case LoaderAction::Internal_Inject_UnloadFromHandle: return "_internal_inject_unloadfromhandle"; } return "<invalid>"; } DWORD XivAlexDll::LaunchXivAlexLoaderWithTargetHandles( const std::vector<Utils::Win32::Process>& hSources, LoaderAction action, bool wait, const Utils::Win32::Process& waitForBeforeStarting, WhichLoader which, const std::filesystem::path& loaderPath) { const auto companionPath = loaderPath.empty() ? ( lstrcmpiW(Utils::Win32::Process::Current().PathOf().filename().wstring().c_str(), XivAlexDll::GameExecutableNameW) == 0 ? App::Config::Acquire()->Init.ResolveXivAlexInstallationPath() : Dll::Module().PathOf().parent_path() ) : loaderPath; const wchar_t* whichLoader; switch (which) { case Current: whichLoader = XivAlexDll::XivAlexLoaderNameW; break; case Opposite: whichLoader = XivAlexDll::XivAlexLoaderOppositeNameW; break; case Force32: whichLoader = XivAlexDll::XivAlexLoader32NameW; break; case Force64: whichLoader = XivAlexDll::XivAlexLoader64NameW; break; default: throw std::invalid_argument("Invalid which"); } const auto companion = companionPath / whichLoader; if (!exists(companion)) throw std::runtime_error(Utils::ToUtf8(std::format(FindStringResourceEx(Dll::Module(), IDS_ERROR_LOADER_NOT_FOUND) + 1, companion))); Utils::Win32::Process companionProcess; { Utils::Win32::ProcessBuilder creator; creator.WithPath(companion) .WithArgument(true, L"") .WithAppendArgument(L"--handle-instead-of-pid") .WithAppendArgument(L"--action") .WithAppendArgument(LoaderActionToString(action)); if (waitForBeforeStarting) creator.WithAppendArgument("--wait-process") .WithAppendArgument("{}", creator.Inherit(waitForBeforeStarting).Value()); for (const auto& h : hSources) creator.WithAppendArgument("{}", creator.Inherit(h).Value()); companionProcess = creator.Run().first; } if (!wait) return 0; else { DWORD retCode = 0; companionProcess.Wait(); if (!GetExitCodeProcess(companionProcess, &retCode)) throw Utils::Win32::Error("GetExitCodeProcess"); return retCode; } } static std::wstring s_originalCommandLine; static bool s_originalCommandLineIsObfuscated; static void CheckObfuscatedArguments() { const auto& process = Utils::Win32::Process::Current(); auto filename = process.PathOf().filename().wstring(); CharLowerW(&filename[0]); if (filename != XivAlexDll::GameExecutableNameW) return; // not the game process try { auto params = Sqex::CommandLine::FromString(Dll::GetOriginalCommandLine(), &s_originalCommandLineIsObfuscated); if (Dll::IsLanguageRegionModifiable()) { auto config = App::Config::Acquire(); Sqex::CommandLine::WellKnown::SetLanguage(params, config->Runtime.RememberedGameLaunchLanguage); Sqex::CommandLine::WellKnown::SetRegion(params, config->Runtime.RememberedGameLaunchRegion); OutputDebugStringW(std::format(L"Parameters modified (language={} region={})\n", static_cast<int>(config->Runtime.RememberedGameLaunchLanguage.Value()), static_cast<int>(config->Runtime.RememberedGameLaunchRegion.Value())).c_str()); } // Once this function is called, it means that this dll will stick to the process until it exits, // so it's safe to store stuff into static variables. static auto newlyCreatedArgumentsW = std::format(L"\"{}\" {}", process.PathOf().wstring(), Sqex::CommandLine::ToString(params, false)); static auto newlyCreatedArgumentsA = Utils::ToUtf8(newlyCreatedArgumentsW, CP_OEMCP); static App::Misc::Hooks::ImportedFunction<LPWSTR> GetCommandLineW("kernel32!GetCommandLineW", "kernel32.dll", "GetCommandLineW"); static const auto h1 = GetCommandLineW.SetHook([]() -> LPWSTR { return &newlyCreatedArgumentsW[0]; }); static App::Misc::Hooks::ImportedFunction<LPSTR> GetCommandLineA("kernel32!GetCommandLineA", "kernel32.dll", "GetCommandLineA"); static const auto h2 = GetCommandLineA.SetHook([]() -> LPSTR { return &newlyCreatedArgumentsA[0]; }); } catch (const std::exception& e) { OutputDebugStringW(std::format(L"Error in CheckObfuscatedArguments: {}\n", e.what()).c_str()); } } BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, LPVOID lpReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: { s_bLoadedAsDependency = !!lpReserved; // non-null for static loads s_originalCommandLine = GetCommandLineW(); try { s_hModule.Attach(hInstance, Utils::Win32::LoadedModule::Null, false, "Instance attach failed <cannot happen>"); s_hActivationContext = Utils::Win32::ActivationContext(ACTCTXW{ .cbSize = static_cast<ULONG>(sizeof ACTCTXW), .dwFlags = ACTCTX_FLAG_HMODULE_VALID | ACTCTX_FLAG_RESOURCE_NAME_VALID, .lpResourceName = MAKEINTRESOURCE(IDR_RT_MANIFEST_LATE_ACTIVATION), .hModule = Dll::Module(), }); if (s_bLoadedAsDependency && lstrcmpiW(Utils::Win32::Process::Current().PathOf().filename().wstring().c_str(), XivAlexDll::GameExecutableNameW) == 0) { GetEnvironmentVariableW(L"XIVALEXANDER_DISABLE", nullptr, 0); if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) { Dll::DisableUnloading(std::format("Loaded as DLL dependency in place of {}", Dll::Module().PathOf().filename()).c_str()); const auto params = XivAlexDll::PatchEntryPointForInjection(GetCurrentProcess()); params->SkipFree = true; params->LoadInstalledXivAlexDllOnly = true; } } else { MH_Initialize(); CheckObfuscatedArguments(); s_crashMessageBoxHandler = std::make_unique<App::Misc::CrashMessageBoxHandler>(); } } catch (const std::exception& e) { Utils::Win32::DebugPrint(L"DllMain({:x}, DLL_PROCESS_ATTACH, {}) Error: {}", reinterpret_cast<size_t>(hInstance), reinterpret_cast<size_t>(lpReserved), e.what()); return FALSE; } return TRUE; } case DLL_PROCESS_DETACH: { auto fail = false; s_crashMessageBoxHandler.reset(); if (const auto res = MH_Uninitialize(); res != MH_OK && res != MH_ERROR_NOT_INITIALIZED) { fail = true; Utils::Win32::DebugPrint(L"MH_Uninitialize error: {}", MH_StatusToString(res)); } if (fail) TerminateProcess(GetCurrentProcess(), -1); return TRUE; } } return TRUE; } size_t __stdcall XivAlexDll::DisableAllApps(void*) { if (s_bLoadedAsDependency) return -1; EnableXivAlexander(0); EnableInjectOnCreateProcess(0); return 0; } void __stdcall XivAlexDll::CallFreeLibrary(void*) { FreeLibraryAndExitThread(Dll::Module(), 0); } [[nodiscard]] XivAlexDll::CheckPackageVersionResult XivAlexDll::CheckPackageVersion() { const auto dir = Utils::Win32::Process::Current().PathOf().parent_path(); std::vector<std::pair<std::string, std::string>> modules; try { modules = { Utils::Win32::FormatModuleVersionString(dir / XivAlexDll::XivAlexLoader32NameW), Utils::Win32::FormatModuleVersionString(dir / XivAlexDll::XivAlexLoader64NameW), Utils::Win32::FormatModuleVersionString(dir / XivAlexDll::XivAlexDll32NameW), Utils::Win32::FormatModuleVersionString(dir / XivAlexDll::XivAlexDll64NameW), }; } catch (const Utils::Win32::Error& e) { if (e.Code() == ERROR_FILE_NOT_FOUND) return CheckPackageVersionResult::MissingFiles; throw; } for (size_t i = 1; i < modules.size(); ++i) { if (modules[0].first != modules[i].first || modules[0].second != modules[i].second) return CheckPackageVersionResult::VersionMismatch; } return CheckPackageVersionResult::OK; } size_t Dll::DisableUnloading(const char* pszReason) { if (s_bLoadedAsDependency) return -1; s_dllUnloadDisableReason = pszReason ? pszReason : "(reason not specified)"; Module().SetPinned(); return 0; } const char* Dll::GetUnloadDisabledReason() { return s_dllUnloadDisableReason.empty() ? nullptr : s_dllUnloadDisableReason.c_str(); } bool Dll::IsLoadedAsDependency() { return s_bLoadedAsDependency; } const wchar_t* Dll::GetGenericMessageBoxTitle() { static std::wstring buf; if (buf.empty()) { buf = std::format(L"{} {}", GetStringResFromId(IDS_APP_NAME), Utils::Win32::FormatModuleVersionString(Module().PathOf()).second); } return buf.data(); } int Dll::MessageBoxF(HWND hWnd, UINT uType, const std::wstring& text) { return MessageBoxF(hWnd, uType, text.c_str()); } int Dll::MessageBoxF(HWND hWnd, UINT uType, const std::string& text) { return MessageBoxF(hWnd, uType, Utils::FromUtf8(text)); } int Dll::MessageBoxF(HWND hWnd, UINT uType, const wchar_t* text) { return MessageBoxW(hWnd, text, GetGenericMessageBoxTitle(), uType); } int Dll::MessageBoxF(HWND hWnd, UINT uType, const char* text) { return MessageBoxF(hWnd, uType, Utils::FromUtf8(text)); } LPCWSTR Dll::GetStringResFromId(UINT resId) { try { const auto conf = App::Config::Acquire(); return conf->Runtime.GetStringRes(resId); } catch (...) { return 1 + FindStringResourceEx(Module(), resId); } } int Dll::MessageBoxF(HWND hWnd, UINT uType, UINT stringResId) { return MessageBoxF(hWnd, uType, GetStringResFromId(stringResId)); } std::wstring Dll::GetOriginalCommandLine() { return s_originalCommandLine; } bool Dll::IsOriginalCommandLineObfuscated() { return s_originalCommandLineIsObfuscated; } bool Dll::IsLanguageRegionModifiable() { static std::optional<bool> s_modifiable; if (!s_modifiable.has_value()) { try { s_modifiable = App::Misc::GameInstallationDetector::GetGameReleaseInfo().Region == Sqex::GameReleaseRegion::International; } catch (...) { s_modifiable = false; } } return *s_modifiable; } void Dll::SetLoadedFromEntryPoint() { s_bLoadedFromEntryPoint = true; } bool Dll::IsLoadedFromEntryPoint() { return s_bLoadedFromEntryPoint; } HWND Dll::FindGameMainWindow(bool throwOnError) { HWND hwnd = nullptr; while ((hwnd = FindWindowExW(nullptr, hwnd, L"FFXIVGAME", nullptr))) { DWORD pid; GetWindowThreadProcessId(hwnd, &pid); if (pid == GetCurrentProcessId()) break; } if (hwnd == nullptr && throwOnError) throw std::runtime_error(Utils::ToUtf8(FindStringResourceEx(Module(), IDS_ERROR_GAME_WINDOW_NOT_FOUND) + 1)); return hwnd; } XivAlexDll::VersionInformation XivAlexDll::CheckUpdates() { std::ostringstream os; curlpp::Easy req; req.setOpt(curlpp::options::Url("https://api.github.com/repos/Soreepeong/XivAlexander/releases/latest")); req.setOpt(curlpp::options::UserAgent("Mozilla/5.0")); req.setOpt(curlpp::options::FollowLocation(true)); if (WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyInfo{}; WinHttpGetIEProxyConfigForCurrentUser(&proxyInfo)) { std::wstring proxy; std::vector<std::wstring> proxyBypass; if (proxyInfo.lpszProxy) { proxy = proxyInfo.lpszProxy; GlobalFree(proxyInfo.lpszProxy); } if (proxyInfo.lpszProxyBypass) { proxyBypass = Utils::StringSplit<std::wstring>(Utils::StringReplaceAll<std::wstring>(proxyInfo.lpszProxyBypass, L";", L" "), L" "); GlobalFree(proxyInfo.lpszProxyBypass); } if (proxyInfo.lpszAutoConfigUrl) GlobalFree(proxyInfo.lpszAutoConfigUrl); bool noProxy = proxy.empty(); for (const auto& v : proxyBypass) { if (lstrcmpiW(&v[0], L"api.github.com") == 0) { noProxy = true; } } if (!noProxy) { req.setOpt(curlpp::options::Proxy(Utils::ToUtf8(proxy))); } } os << req; const auto parsed = nlohmann::json::parse(os.str()); const auto assets = parsed.at("assets"); if (assets.empty()) throw std::runtime_error("Could not detect updates. Please try again at a later time."); const auto item = assets[0]; std::istringstream in(parsed.at("published_at").get<std::string>()); std::chrono::sys_seconds tp; from_stream(in, "%FT%TZ", tp); if (in.fail()) throw std::format_error(std::format("Failed to parse datetime string \"{}\"", in.str())); return { .Name = parsed.at("name").get<std::string>(), .Body = parsed.at("body").get<std::string>(), .PublishDate = std::chrono::zoned_time(std::chrono::current_zone(), tp), .DownloadLink = item.at("browser_download_url").get<std::string>(), .DownloadSize = item.at("size").get<size_t>(), }; } bool XivAlexDll::IsXivAlexanderDll(const std::filesystem::path& dllPath) { DWORD verHandle = 0; std::vector<BYTE> block; block.resize(GetFileVersionInfoSizeW(dllPath.c_str(), &verHandle)); if (block.empty()) { const auto err = GetLastError(); if (err == ERROR_RESOURCE_TYPE_NOT_FOUND) return false; throw Utils::Win32::Error(err, "GetFileVersionInfoSizeW"); } if (!GetFileVersionInfoW(dllPath.c_str(), 0, static_cast<DWORD>(block.size()), &block[0])) throw Utils::Win32::Error("GetFileVersionInfoW"); struct LANGANDCODEPAGE { WORD wLanguage; WORD wCodePage; } * lpTranslate; UINT cbTranslate; if (!VerQueryValueW(&block[0], TEXT("\\VarFileInfo\\Translation"), reinterpret_cast<LPVOID*>(&lpTranslate), &cbTranslate)) return false; for (size_t i = 0; i < (cbTranslate / sizeof(struct LANGANDCODEPAGE)); i++) { wchar_t* buf = nullptr; UINT size = 0; if (!VerQueryValueW(&block[0], std::format(L"\\StringFileInfo\\{:04x}{:04x}\\FileDescription", lpTranslate[i].wLanguage, lpTranslate[i].wCodePage).c_str(), reinterpret_cast<LPVOID*>(&buf), &size)) continue; auto currName = std::wstring_view(buf, size); while (!currName.empty() && currName.back() == L'\0') currName = currName.substr(0, currName.size() - 1); if (currName.empty()) continue; if (currName == L"XivAlexander Main DLL") return true; } return false; }
34.468326
155
0.732786
retaker
b8f7e5fa5d687eac4bfceca514391ac8b42c9151
671
hpp
C++
include/experimental/fundamental/v3/strong/initializer_tags.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
105
2015-01-24T13:26:41.000Z
2022-02-18T15:36:53.000Z
include/experimental/fundamental/v3/strong/initializer_tags.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
37
2015-09-04T06:57:10.000Z
2021-09-09T18:01:44.000Z
include/experimental/fundamental/v3/strong/initializer_tags.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
23
2015-01-27T11:09:18.000Z
2021-10-04T02:23:30.000Z
// 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) // // Copyright (C) 2017 Vicente J. Botet Escriba #error #ifndef JASEL_FUNDAMENTAL_V3_STRONG_INITIALIZER_TAGS_HPP #define JASEL_FUNDAMENTAL_V3_STRONG_INITIALIZER_TAGS_HPP namespace std { namespace experimental { inline namespace fundamental_v3 { //! tag used to explicitly default initialize struct default_initialized_t {}; //! tag used to explicitly don't initialize struct uninitialized_t {}; //! tag used to explicitly zero initialize struct zero_initialized_t {}; } } } #endif // header
20.96875
66
0.76304
jwakely
b8f8496b15af8546ec2b37abb675962d90aefdad
190
cpp
C++
main.cpp
CrafterKolyan/sandbox
ebcec01bf71afddc13a96cd34714bae227731941
[ "MIT" ]
null
null
null
main.cpp
CrafterKolyan/sandbox
ebcec01bf71afddc13a96cd34714bae227731941
[ "MIT" ]
null
null
null
main.cpp
CrafterKolyan/sandbox
ebcec01bf71afddc13a96cd34714bae227731941
[ "MIT" ]
null
null
null
#include <unistd.h> #include <sys/syscall.h> const char message[] = "Hello CrafterKolyan!\n"; int main() { syscall(SYS_write, STDOUT_FILENO, message, sizeof(message) - 1); return 0; }
19
66
0.689474
CrafterKolyan
b8f892c9c1e8a7f65b27ccc016ae05e581cd3968
225
cpp
C++
src/ol/events/EventTarget.cpp
yyk99/olqt
9efbee3c4169a4429dc5c0939cd5c65f52ea6028
[ "Apache-2.0" ]
null
null
null
src/ol/events/EventTarget.cpp
yyk99/olqt
9efbee3c4169a4429dc5c0939cd5c65f52ea6028
[ "Apache-2.0" ]
null
null
null
src/ol/events/EventTarget.cpp
yyk99/olqt
9efbee3c4169a4429dc5c0939cd5c65f52ea6028
[ "Apache-2.0" ]
null
null
null
// // // #include <ol/events/EventTarget.h> ol::events::EventTarget::EventTarget() { } ol::events::EventTarget::~EventTarget() { dispose(); } void ol::events::EventTarget::disposeInternal() { // TODO: implement }
11.25
47
0.644444
yyk99
b8fde86455501b8a86505c5124412573369c7132
10,314
cpp
C++
OpenGL-Laboratory/Src/GLCore/Core/TestsLayerManager.cpp
ishanshLal-tRED/OpenGL-TestSite
6887725e0c268f9949050547578509e06be83eae
[ "Apache-2.0" ]
null
null
null
OpenGL-Laboratory/Src/GLCore/Core/TestsLayerManager.cpp
ishanshLal-tRED/OpenGL-TestSite
6887725e0c268f9949050547578509e06be83eae
[ "Apache-2.0" ]
null
null
null
OpenGL-Laboratory/Src/GLCore/Core/TestsLayerManager.cpp
ishanshLal-tRED/OpenGL-TestSite
6887725e0c268f9949050547578509e06be83eae
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "GLCore/Core/TestBase.h" #include "GLCore/Util/Core/Framebuffer.h" #include "TestsLayerManager.h" #include "GLCore/Core/Application.h" #include "imgui/imgui.h" #include "imgui/imgui_internal.h" namespace GLCore { TestsLayerManager::~TestsLayerManager () { for (uint16_t i = 0; i < g_MaxNumOfAllowedTests; i++) { if (m_ActiveTests[i]) { m_ActiveTests[i]->OnDetach (); m_ActiveTests[i] = nullptr; } if (m_ActiveTestFramebuffers[i]) { delete m_ActiveTestFramebuffers[i]; m_ActiveTestFramebuffers[i] = nullptr; } } { for (uint16_t i = 0; i < m_AllTests.size (); i++) delete m_AllTests[i]; m_AllTests.clear (); } } void TestsLayerManager::PushTest (TestBase *test) { for (TestBase *_test: m_AllTests) { if (test->GetName () == _test->GetName ()) { LOG_ERROR ( "Similar Named Test: {0} Already Exists, Please resolve name conflict EXITING APPLICATION", test->GetName ()); Application::Get ().ApplicationClose (); return; } } m_AllTests.emplace_back (test); } void TestsLayerManager::UpdateActiveLayers (Timestep deltatime) { uint8_t testIndex = 0; for (TestBase *test : m_ActiveTests) { if (test) { //// // Here Will be code for frame buffer //// m_ActiveTestFramebuffers[testIndex]->Bind (); test->OnUpdate (deltatime); m_ActiveTestFramebuffers[testIndex]->Unbind (); } else break; testIndex++; } } void TestsLayerManager::ImGuiRender () { {// DockSpace static bool dockspaceOpen = true; static bool showImGuiDemoWindow = false; static constexpr bool optFullscreenPersistant = true; bool optFullscreen = optFullscreenPersistant; static ImGuiDockNodeFlags dockspaceFlags = ImGuiDockNodeFlags_None; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, // because it would be confusing to have two docking targets within each others. ImGuiWindowFlags windowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; if (optFullscreen) { ImGuiViewport *viewPort = ImGui::GetMainViewport (); ImGui::SetNextWindowPos (viewPort->Pos); ImGui::SetNextWindowSize (viewPort->Size); ImGui::SetNextWindowViewport (viewPort->ID); ImGui::PushStyleVar (ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar (ImGuiStyleVar_WindowBorderSize, 0.0f); windowFlags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } // when using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background and handle the pass-thru hole, so we ask Begin() to not render background. if (dockspaceFlags & ImGuiDockNodeFlags_PassthruCentralNode) windowFlags |= ImGuiWindowFlags_NoBackground; // Important: note that we proceed even if Begin() return false (i.e window is collapsed). // This is because we want to keep our DockSpace() active. If a DockSpace is inactive, // all active windows docked into it will lose their parent and become undocked. // any change of dockspce/settings would lead towindows being stuck in limbo and never being visible. ImGui::PushStyleVar (ImGuiStyleVar_WindowPadding, ImVec2 (0.0f, 0.0f)); ImGui::Begin ("Main DockSpace", &dockspaceOpen, windowFlags); ImGui::PopStyleVar (); if (optFullscreen) ImGui::PopStyleVar (2); // DockSpace ImGuiIO &io = ImGui::GetIO (); ImGuiStyle &style = ImGui::GetStyle (); float defaultMinWinSize = style.WindowMinSize.x; style.WindowMinSize.x = 280; if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { m_DockspaceID = ImGui::GetID ("Main DockSpace"); ImGui::DockSpace (m_DockspaceID, ImVec2 (0.0f, 0.0f), dockspaceFlags); } style.WindowMinSize.x = defaultMinWinSize; // DockSpace's MenuBar if (ImGui::BeginMenuBar ()) { if (ImGui::BeginMenu ("Main")) { if (ImGui::MenuItem ("Show Demo Window")) showImGuiDemoWindow = true; ImGui::Separator (); if (ImGui::MenuItem ("Show Tests Menu")) m_ShowTestMenu = true; ImGui::Separator (); if (ImGui::MenuItem ("Exit")) Application::Get ().ApplicationClose (); ImGui::EndMenu (); } { for (TestBase *test : m_ActiveTests) { if (test) { ImGui::PushID (ImGuiLayer::UniqueName ("--Menu")); ImGui::Bullet (); test->ImGuiMenuOptions (); ImGui::PopID (); } else break; } } ImGui::EndMenuBar (); } if (showImGuiDemoWindow) { ImGui::ShowDemoWindow (&showImGuiDemoWindow); } ShowTestMenu (); // Here goes Stuff that will be put inside DockSpace OnImGuiRenderAll (); ImGui::End (); } } void TestsLayerManager::OnImGuiRenderAll () { int8_t closeTestID = -1; { ImVec2 mainViewportPosn = ImGui::GetMainViewport ()->Pos; TestBase::s_MainViewportPosn.x = mainViewportPosn.x; TestBase::s_MainViewportPosn.y = mainViewportPosn.y; } // name_conflict-fix uint16_t test_index = 0; for (TestBase *test : m_ActiveTests) { if (test) { //// // Here Will be code for framebuffer-out -> view-port_Window, new-ImGuiWindow(a persistant one that will force your viewport-window to-be attached to itself), pop-on-close-buttonpress etc. //// // TODO: fixing multiple tests problem ImGui::SetNextWindowDockID (m_DockspaceID, ImGuiCond_Once); bool closeTest = true; ImGui::Begin (ImGuiLayer::UniqueName(test->GetName ()), &closeTest); { ImGui::PushID (ImGuiLayer::UniqueName ("--Test")); if (!closeTest) { LayerCloseEvent event; test->OnEvent (event); closeTestID = test_index; } ImGuiID dockspace_id; dockspace_id = ImGui::GetID (ImGuiLayer::UniqueName("MyDockspace")); ImGui::DockSpace (dockspace_id); ImGui::SetNextWindowDockID (dockspace_id, ImGuiCond_Always); ImGui::PushStyleVar (ImGuiStyleVar_WindowPadding, ImVec2 (0, 0)); ImGui::Begin (ImGuiLayer::UniqueName("Viewport"), NULL, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize); { ImVec2 ContentRegionAvail = ImGui::GetContentRegionAvail (); ImVec2 ContentDrawStartPos = ImGui::GetCursorScreenPos (); ImGui::Image (reinterpret_cast<void *>(m_ActiveTestFramebuffers[test_index]->GetColorAttachmentRendererID ()), ContentRegionAvail, ImVec2{ 0, 1 }, ImVec2{ 1, 0 }); test->FlagSetter (TestBase::Viewport_Focused, ImGui::IsWindowFocused ()); test->FlagSetter (TestBase::Viewport_Hovered, ImGui::IsWindowHovered ()); if (test->This_ViewportSize (ContentRegionAvail.x, ContentRegionAvail.y)) { m_ActiveTestFramebuffers[test_index]->Resize ((uint32_t)test->m_ViewPortSize.x, (uint32_t)test->m_ViewPortSize.y); } test->m_ViewportPosnRelativeToMain.x = ContentDrawStartPos.x - TestBase::s_MainViewportPosn.x; test->m_ViewportPosnRelativeToMain.y = ContentDrawStartPos.y - TestBase::s_MainViewportPosn.y; } ImGui::End (); ImGui::PopStyleVar (); ImGui::SetNextWindowDockID (dockspace_id, ImGuiCond_FirstUseEver); test->OnImGuiRender (); ImGui::PopID (); } ImGui::End (); }else break; test_index++; } if (closeTestID > -1) { DeActivateTest (closeTestID); } } void TestsLayerManager::ProcessEvent (Event &event) { for (TestBase *test : m_ActiveTests) { if (test && !event.Handled) { test->FilteredEvent (event); } else break; } } void TestsLayerManager::ActivateTest (uint16_t posn) { for (uint16_t i = 0; i < g_MaxNumOfAllowedTests; i++) { if (m_ActiveTests[i] == m_AllTests[posn]) { LOG_WARN ("test Already running"); return; } if (m_ActiveTests[i] != nullptr) { continue; } m_ActiveTests[i] = m_AllTests[posn]; m_ActiveTests[i]->OnAttach (); if (m_ActiveTestFramebuffers[i]) m_ActiveTestFramebuffers[i]->Resize ((uint32_t)m_ActiveTests[i]->m_ViewPortSize.x, (uint32_t)m_ActiveTests[i]->m_ViewPortSize.y); else m_ActiveTestFramebuffers[i] = new Utils::Framebuffer (Utils::FramebufferSpecification{ (uint32_t)m_ActiveTests[i]->m_ViewPortSize.x, (uint32_t)m_ActiveTests[i]->m_ViewPortSize.y, { Utils::FramebufferTextureFormat::RGBA8, Utils::FramebufferTextureFormat::Depth } }); return; } LOG_WARN ("!! No more Active tests allowed !!"); } void TestsLayerManager::DeActivateTest (uint16_t posn) { if (posn < g_MaxNumOfAllowedTests) { if (m_ActiveTests[posn] != nullptr) { for (uint16_t i = posn; i < (g_MaxNumOfAllowedTests - 1); i++) { m_ActiveTests[i] = m_ActiveTests[i + 1]; } m_ActiveTests[g_MaxNumOfAllowedTests - 1] = nullptr; return; } else { LOG_WARN ("!! nullptr found at: posn {0}", posn); return; } } LOG_WARN ("!! Out of bounds: posn {0}, Active_Tests_stack_size {1} !!", posn, g_MaxNumOfAllowedTests); } void TestsLayerManager::ShowTestMenu () { if (m_ActiveTests[0] != nullptr && !m_ShowTestMenu) return; ImGuiWindowFlags flags; if (m_ActiveTests[0] == nullptr) ImGui::SetNextWindowDockID (m_DockspaceID, ImGuiCond_Always), flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove; else ImGui::SetNextWindowSizeConstraints (ImVec2(300, 200), ImVec2(ImGui::GetWindowWidth () * 0.7f, ImGui::GetWindowHeight () * 0.7f)), flags = ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_AlwaysAutoResize; ImGui::Begin ("Tests Menu", &m_ShowTestMenu, flags); const ImVec2 RegionSize = ImGui::GetContentRegionAvail (); uint16_t i = 0; for (TestBase *test: m_AllTests) { ImGui::PushID (i); ImGui::SetNextItemWidth (RegionSize.x/2.0f); bool un_collapsed = ImGui::CollapsingHeader (test->GetName ().c_str (), NULL, ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_DefaultOpen); ImGui::SameLine (); { float x = RegionSize.x/2.0f; float _x = ImGui::GetCursorPosX (); ImGui::SameLine (x > _x ? x : _x); } if (ImGui::Button ("Start Test")) { ActivateTest (i); m_ShowTestMenu = false; } if (un_collapsed) { ImGui::Indent (); ImGui::Text (test->GetDiscription ().c_str ()); ImGui::Unindent (); } ImGui::PopID (); i++; } ImGui::End (); } }
33.927632
269
0.69013
ishanshLal-tRED
770384cb1e9a934299b71b68f4a4acd0af3e0a2c
9,170
cpp
C++
SOURCES/sim/aircraft/ins.cpp
IsraelyFlightSimulator/Negev-Storm
86de63e195577339f6e4a94198bedd31833a8be8
[ "Unlicense" ]
1
2021-02-19T06:06:31.000Z
2021-02-19T06:06:31.000Z
src/sim/aircraft/ins.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
null
null
null
src/sim/aircraft/ins.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
2
2019-08-20T13:35:13.000Z
2021-04-24T07:32:04.000Z
#include "stdhdr.h" #include "aircrft.h" #include "fack.h" #include "airframe.h" #include "otwdrive.h" #include "cpmanager.h" #include "phyconst.h" #include "flightData.h" #include "navsystem.h" void AircraftClass::RunINS(void) { if(INSAlign && INSState(INS_AlignNorm) || INSState(INS_AlignFlight)) { if((OnGround() && GetKias() <= 2.0F && !INS60kts) || INSState(INS_AlignFlight)) DoINSAlign(); else INSAlign = FALSE; } else if(INSState(INS_AlignNorm) && !INS60kts) { INSAlign = TRUE; } if(INSStatus <= 90) { //ADI OFF Flag goes away INSOn(AircraftClass::INS_ADI_OFF_IN); INSOn(AircraftClass::INS_HUD_STUFF); INSOn(AircraftClass::INS_HSI_OFF_IN); INSOn(AircraftClass::INS_HSD_STUFF); } else if(!HasAligned) { //ADI OFF Flag goes away INSOff(AircraftClass::INS_ADI_OFF_IN); INSOff(AircraftClass::INS_HUD_STUFF); INSOff(AircraftClass::INS_HSI_OFF_IN); INSOff(AircraftClass::INS_HSD_STUFF); } if(INSStatus <= 79) { //ADI AUX Flag goes away INSOn(AircraftClass::INS_ADI_AUX_IN); } else INSOff(AircraftClass::INS_ADI_AUX_IN); if(INSStatus <= 70) HasAligned = TRUE; else HasAligned = FALSE; if(INSStatus <= 10) INSOn(INS_Aligned); else INSOff(INS_Aligned); CheckINSStatus(); if(INSState(INS_Nav)) CalcINSDrift(); else INSLatDrift = 0.0F; if(GetKias() >= 60 && OnGround() && INSState(INS_AlignNorm)) INS60kts = TRUE; //needs to be turned off //Check for power if(currentPower == PowerNone) //Emergency bus { //SwitchINSToOff(); INSAlignmentTimer = 0.0F; INSAlignmentStart = vuxGameTime; INSAlign = FALSE; HasAligned = FALSE; INSStatus = 99; INSTimeDiff = 0.0F; INS60kts = FALSE; HasAligned = FALSE; CheckUFC = TRUE; } } void AircraftClass::DoINSAlign(void) { //if they enter the coords after 2 mins of alignment, we start from the beginning if(CheckUFC) { if(OTWDriver.pCockpitManager && OTWDriver.pCockpitManager->mpIcp && OTWDriver.pCockpitManager->mpIcp->INSEnterPush()) { CheckUFC = FALSE; OTWDriver.pCockpitManager->mpIcp->ClearINSEnter(); if(INSAlignmentTimer >= 120) INSAlignmentTimer = 0; } } if(INSAlignmentTimer >= 120) CheckUFC = TRUE; //Dont align if the UFC isn't powered if(!HasPower(UFCPower)) return; if(INSState(INS_AlignFlight)) INSAlignmentTimer += 8 * SimLibMajorFrameTime; //reach 480 in 1 min else INSAlignmentTimer += SimLibMajorFrameTime; if(INSAlignmentTimer >= 12) //12 seconds INSStatus = 90; if(INSAlignmentTimer >= 60) //60 Seconds INSStatus = 79; if(INSAlignmentTimer >= 90) //90 seconds INSStatus = 70; if(INSAlignmentTimer >= 155) //every 65 seconds one step less INSStatus = 60; if(INSAlignmentTimer >= 220) INSStatus = 50; if(INSAlignmentTimer >= 285) INSStatus = 40; if(INSAlignmentTimer >= 350) INSStatus = 30; if(INSAlignmentTimer >= 415) INSStatus = 20; if(INSAlignmentTimer >= 480) //8 minutes INSStatus = 10; } void AircraftClass::SwitchINSToOff(void) { //it all goes down here INSFlags = 0; INSOn(INS_PowerOff); INSAlignmentTimer = 0.0F; INSAlignmentStart = vuxGameTime; INSAlign = FALSE; HasAligned = FALSE; INSStatus = 99; INSTimeDiff = 0.0F; INS60kts = FALSE; HasAligned = FALSE; CheckUFC = TRUE; OTWDriver.pCockpitManager->mpIcp->ClearStrings(); } void AircraftClass::SwitchINSToAlign(void) { if(INSState(INS_PowerOff)) { INSAlignmentTimer = 0.0F; HasAligned = FALSE; } INSOn(INS_AlignNorm); INSOff(INS_PowerOff); INSOff(INS_Nav); INSOff(INS_AlignFlight); INSAlignmentStart = vuxGameTime; INSAlign = TRUE; //Set the UFC if(OTWDriver.pCockpitManager && OTWDriver.pCockpitManager->mpIcp) { OTWDriver.pCockpitManager->mpIcp->ClearStrings(); OTWDriver.pCockpitManager->mpIcp->LeaveCNI(); OTWDriver.pCockpitManager->mpIcp->SetICPFlag(ICPClass::MODE_LIST); OTWDriver.pCockpitManager->mpIcp->SetICPSecondaryMode(23); //SIX Button, INS Page OTWDriver.pCockpitManager->mpIcp->INSLine = 0; } } void AircraftClass::SwitchINSToNav(void) { INSOn(INS_Nav); INSOff(INS_AlignNorm); INSOff(INS_PowerOff); INSOff(INS_AlignFlight); CalcINSOffset(); //entered wrong INS coords? INSAlign = FALSE; INSAlignmentStart = vuxGameTime; } void AircraftClass::SwitchINSToInFLT(void) { /*if(INSState(INS_PowerOff)) { INSAlignmentTimer = 0.0F; HasAligned = FALSE; }*/ if(OnGround()) return; INSOn(INS_AlignFlight); INSOff(INS_AlignNorm); INSOff(INS_PowerOff); INSOff(INS_Nav); INSAlignmentStart = vuxGameTime; INSAlign = TRUE; INSAlignmentTimer = 0.0F; HasAligned = FALSE; INSStatus = 99; INSTimeDiff = 0.0F; //Set the UFC if(OTWDriver.pCockpitManager && OTWDriver.pCockpitManager->mpIcp) { OTWDriver.pCockpitManager->mpIcp->ClearStrings(); OTWDriver.pCockpitManager->mpIcp->LeaveCNI(); OTWDriver.pCockpitManager->mpIcp->SetICPFlag(ICPClass::MODE_LIST); OTWDriver.pCockpitManager->mpIcp->SetICPSecondaryMode(23); //SIX Button, INS Page OTWDriver.pCockpitManager->mpIcp->INSLine = 3; } } void AircraftClass::CheckINSStatus(void) { if(INSState(AircraftClass::INS_PowerOff) || (INSState(AircraftClass::INS_Nav) && !HasAligned)) { INSOff(AircraftClass::INS_ADI_OFF_IN); INSOff(AircraftClass::INS_ADI_AUX_IN); INSOff(AircraftClass::INS_HSI_OFF_IN); INSOff(AircraftClass::INS_HUD_FPM); INSOff(AircraftClass::INS_HUD_STUFF); INSOff(AircraftClass::INS_HSD_STUFF); } else if(INSState(AircraftClass::INS_Nav) && HasAligned) { INSOn(AircraftClass::INS_HUD_FPM); INSOn(AircraftClass::INS_HUD_STUFF); INSOn(AircraftClass::INS_HSD_STUFF); } if(INSState(AircraftClass::INS_PowerOff) || INSState(AircraftClass::INS_AlignNorm) || !HasAligned) INSOff(AircraftClass::INS_HUD_FPM); else INSOn(AircraftClass::INS_HUD_FPM); } void AircraftClass::CalcINSDrift(void) { /*ok do this. after 6min make it drift with 0.1 nm pr hour in a randon direction. after 12 min - 0.2 18 min - 0.3 ........ 60min 1.0 after 8min...if they take it after 2 min then add 10% to the drift speeds ie 6min - 0.11 nm/hour */ //check for changing direction INSDriftDirectionTimer -= SimLibMajorFrameTime; if(INSDriftDirectionTimer <= 0.0F) { if(rand()%11 > 5) INSDriftLatDirection = 1; else INSDriftLatDirection = -1; if(rand()%11 > 5) INSDriftLongDirection = 1; else INSDriftLongDirection = -1; INSDriftDirectionTimer = 300.0F; } //difference from alignment till now INSTimeDiff = (float)vuxGameTime - INSAlignmentStart; INSTimeDiff /= 1000; //to get seconds INSTimeDiff /= 60; //minutes #ifndef _DEBUG //no drift when GPS is powered if(HasPower(GPSPower)) INSAlignmentStart = vuxGameTime; #endif if(INSStatus <= 10) { //per 6 minutes 0.1NM drift -> 0.01666666666NM per minute INSLatDrift = 0.01666666666F * INSTimeDiff; //get it in feet INSLatDrift *= NM_TO_FT; INSLongDrift = INSLatDrift; //drift in random direction INSLatDrift *= INSDriftLatDirection; INSLongDrift *= INSDriftLongDirection; } else { //10% more drift per hour float Factor = 10; //find our alignment status and calculate how much more drift we have Factor = (float)(10 - ((100 - INSStatus)/10)); //"precise drift" INSLatDrift = 0.01666666666F * INSTimeDiff; //add the additional drift factor, in percent, 10% max //60 equals 100% (70-10) INSLatDrift += (INSLatDrift/60) * Factor; //get it in feet INSLatDrift *= NM_TO_FT; INSLongDrift = INSLatDrift; //drifts the same in both directions //drift in random direction INSLatDrift *= INSDriftLatDirection; INSLongDrift *= INSDriftLongDirection; } } static const unsigned long const1 = 6370000; static const float const2 = PI; static const float const3 = const1/90; void AircraftClass::CalcINSOffset(void) { if(OTWDriver.pCockpitManager && OTWDriver.pCockpitManager->mpIcp) { float Curlatitude = (FALCON_ORIGIN_LAT * FT_PER_DEGREE + cockpitFlightData.x) / EARTH_RADIUS_FT; float CosCurlat = (float)cos(Curlatitude); float Curlongitude = ((FALCON_ORIGIN_LONG * DTR * EARTH_RADIUS_FT * CosCurlat) + cockpitFlightData.y) / (EARTH_RADIUS_FT * CosCurlat); Curlatitude *= RTD; Curlongitude *= RTD; //from our initial alignment position, to where we are now float DiffLat = fabs(OTWDriver.pCockpitManager->mpIcp->StartLat - Curlatitude); float DiffLong = fabs(OTWDriver.pCockpitManager->mpIcp->StartLong - Curlongitude); OTWDriver.pCockpitManager->mpIcp->INSLATDiff += DiffLat; OTWDriver.pCockpitManager->mpIcp->INSLONGDiff += DiffLong; Curlatitude = 90 - Curlatitude; //to be formula "compatible", we need the opposing value //find how many feet our degree is at the current lat //Lat is N/S and one degree is about 60 NM INSLatOffset = (OTWDriver.pCockpitManager->mpIcp->INSLATDiff * 60) * NM_TO_FT; //find how many feet a degree is in longitude, at our current latitude float radius = Curlatitude * (const1/90); float circumfence = 2 * const2 * radius; float feetperdeg = circumfence * 3.281f/360.0f; //in Longitude INSLongOffset = OTWDriver.pCockpitManager->mpIcp->INSLONGDiff * feetperdeg; INSAltOffset = OTWDriver.pCockpitManager->mpIcp->INSALTDiff; //not used yet //INSHDGOffset = OTWDriver.pCockpitManager->mpIcp->INSHDGDiff; } }
26.57971
136
0.726718
IsraelyFlightSimulator
7705dedcc564861937bf04728ac1ba619966db65
4,386
cpp
C++
Source/Framework/Core/Material/TeShaderVariation.cpp
GameDevery/TweedeFrameworkRedux
69a28fe171db33d00066b97b9b6bf89f6ef3e3a4
[ "MIT" ]
14
2022-02-25T15:52:35.000Z
2022-03-30T18:44:29.000Z
Source/Framework/Core/Material/TeShaderVariation.cpp
GameDevery/TweedeFrameworkRedux
69a28fe171db33d00066b97b9b6bf89f6ef3e3a4
[ "MIT" ]
null
null
null
Source/Framework/Core/Material/TeShaderVariation.cpp
GameDevery/TweedeFrameworkRedux
69a28fe171db33d00066b97b9b6bf89f6ef3e3a4
[ "MIT" ]
1
2022-02-28T09:24:05.000Z
2022-02-28T09:24:05.000Z
#include "TeShaderVariation.h" namespace te { void ShaderDefines::Set(const String& name, float value) { _defines[name] = ToString(value); } void ShaderDefines::Set(const String& name, INT32 value) { _defines[name] = ToString(value); } void ShaderDefines::Set(const String& name, UINT32 value) { _defines[name] = ToString(value); } void ShaderDefines::Set(const String& name, const String& value) { _defines[name] = value; } ShaderVariation::ShaderVariation() : Serializable(TID_ShaderVariation) { } ShaderVariation::ShaderVariation(const Vector<Param>& params) : Serializable(TID_ShaderVariation) { for (auto& entry : params) _params[entry.Name] = entry; } INT32 ShaderVariation::GetInt(const StringID& name) { auto iterFind = _params.find(name); if (iterFind == _params.end()) return 0; else return iterFind->second.I; } UINT32 ShaderVariation::GetUInt(const StringID& name) { auto iterFind = _params.find(name); if (iterFind == _params.end()) return 0; else return iterFind->second.Ui; } float ShaderVariation::GetFloat(const StringID& name) { auto iterFind = _params.find(name); if (iterFind == _params.end()) return 0.0f; else return iterFind->second.F; } bool ShaderVariation::GetBool(const StringID& name) { auto iterFind = _params.find(name); if (iterFind == _params.end()) return false; else return iterFind->second.I > 0 ? true : false; } void ShaderVariation::SetInt(const StringID& name, INT32 value) { AddParam(Param(name, value)); } void ShaderVariation::SetUInt(const StringID& name, UINT32 value) { AddParam(Param(name, value)); } void ShaderVariation::SetFloat(const StringID& name, float value) { AddParam(Param(name, value)); } void ShaderVariation::SetBool(const StringID& name, bool value) { AddParam(Param(name, value)); } Vector<String> ShaderVariation::GetParamNames() const { Vector<String> params; params.reserve(_params.size()); for (auto& entry : _params) params.push_back(entry.first); return params; } ShaderDefines ShaderVariation::GetDefines() const { ShaderDefines defines; for (auto& entry : _params) { switch (entry.second.Type) { case Int: case Bool: defines.Set(entry.first.c_str(), entry.second.I); break; case UInt: defines.Set(entry.first.c_str(), entry.second.Ui); break; case Float: defines.Set(entry.first.c_str(), entry.second.F); break; } } return defines; } bool ShaderVariation::Matches(const ShaderVariation& other, bool exact) const { for (auto& entry : other._params) { const auto iterFind = _params.find(entry.first); if (iterFind == _params.end()) return false; if (entry.second.I != iterFind->second.I) return false; } if (exact) { for (auto& entry : _params) { const auto iterFind = other._params.find(entry.first); if (iterFind == other._params.end()) return false; if (entry.second.I != iterFind->second.I) return false; } } return true; } bool ShaderVariation::operator==(const ShaderVariation& rhs) const { return Matches(rhs, true); } void ShaderVariations::Add(const ShaderVariation& variation) { variation._idx = _nextIdx++; _variations.push_back(variation); } UINT32 ShaderVariations::Find(const ShaderVariation& variation) const { UINT32 idx = 0; for (auto& entry : _variations) { if (entry == variation) return idx; idx++; } return (UINT32)-1; } }
24.366667
81
0.544688
GameDevery
7706c54d3abcbe4973f64b5b51e748082c0c17d3
1,402
cpp
C++
References/Competitive Programming 3/ch8/UVa11065.cpp
eashwaranRaghu/Data-Structures-and-Algorithms
3aad0f1da3d95b572fbb1950c770198bd042a80f
[ "MIT" ]
6
2020-01-29T14:05:56.000Z
2021-04-24T04:37:27.000Z
References/Competitive Programming 3/ch8/UVa11065.cpp
eashwaranRaghu/Data-Structures-and-Algorithms
3aad0f1da3d95b572fbb1950c770198bd042a80f
[ "MIT" ]
null
null
null
References/Competitive Programming 3/ch8/UVa11065.cpp
eashwaranRaghu/Data-Structures-and-Algorithms
3aad0f1da3d95b572fbb1950c770198bd042a80f
[ "MIT" ]
1
2020-05-22T06:37:20.000Z
2020-05-22T06:37:20.000Z
// Gentlemen Agreement #include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for (int i=(a),_b=(b); i<=_b; i++) #define FORD(i,a,b) for (int i=(a),_b=(b); i>=_b; i--) #define REP(i,n) for (int i=0,_n=(n); i<_n; i++) #define MAXI 62 long long AM[MAXI], dpcon[MAXI]; int V, E, nS, mxS; void backtracking(int i, long long used, int depth) { if (used == (1<<V)-1) { // all intersections are visited nS++; // one more possible set mxS = max(mxS, depth); // size of the set } else { for (int j = i; j < V; j++) if (!(used & (1<<j))) // if intersection i is not yet used backtracking(j+1, used|AM[j], depth+1); // use i and its neighbors } } int main() { int TC; scanf("%d", &TC); while (TC--) { scanf("%d %d", &V, &E); // a more powerful, bit-wise adjacency list (for faster set operations) for (int i = 0; i < V; i++) AM[i] = (1 << i); // i to itself for (int i = 0; i < E; i++) { int a, b; scanf("%d %d", &a, &b); AM[a] |= (1<<b); AM[b] |= (1<<a); } // speed up dpcon[V] = 0; FORD (i, V-1, 0) dpcon[i] = AM[i] | dpcon[i + 1]; nS = mxS = 0; backtracking(0, 0, 0); // just a backtracking with bitmask/subset printf("%d\n%d\n", nS, mxS); } return 0; }
28.04
75
0.470756
eashwaranRaghu
7709c68620d96fa7b37301a97c8354df9a6573a2
373
cpp
C++
Lecture_Learning/3/1_divisible.cpp
Swapnil-Singh-99/CPP-DSA-Apni-Kaksha
e31d2b4926a3fba7ebeff07419e1ded68c8c73f7
[ "MIT" ]
1
2021-10-11T02:55:05.000Z
2021-10-11T02:55:05.000Z
Lecture_Learning/3/1_divisible.cpp
Swapnil-Singh-99/CPP-DSA-Apni-Kaksha
e31d2b4926a3fba7ebeff07419e1ded68c8c73f7
[ "MIT" ]
null
null
null
Lecture_Learning/3/1_divisible.cpp
Swapnil-Singh-99/CPP-DSA-Apni-Kaksha
e31d2b4926a3fba7ebeff07419e1ded68c8c73f7
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; // continue - it is used to go to the next iteration of the loop // break - it is used to break the loop means stop the loop and get out of it int main(){ // here the numbers divisible by 3 will not get printed for(int i = 0 ; i<=100 ; i++){ if(i%3==0){ continue; } cout<<i<<endl; } }
26.642857
77
0.589812
Swapnil-Singh-99
77114e5446845b4defbd35281398a6c0621021ee
1,704
cpp
C++
src/interfaces/tui-napalm/main.cpp
Helios-vmg/napalm
15f61c742a4488304583865f35cb286e777112fe
[ "BSD-2-Clause" ]
null
null
null
src/interfaces/tui-napalm/main.cpp
Helios-vmg/napalm
15f61c742a4488304583865f35cb286e777112fe
[ "BSD-2-Clause" ]
null
null
null
src/interfaces/tui-napalm/main.cpp
Helios-vmg/napalm
15f61c742a4488304583865f35cb286e777112fe
[ "BSD-2-Clause" ]
null
null
null
#include <curses.h> #include <Player.h> class Curses{ public: Curses(){ initscr(); start_color(); use_default_colors(); keypad(stdscr, true); noecho(); } ~Curses(){ endwin(); } } curses; const short selected = 2; const short unselected = 1; void f(){ auto window = newwin(10, 20, 10, 10); while (true){ wrefresh(window); auto input = getch(); if (input == 'q') break; } delwin(window); } int main(){ init_pair(1, COLOR_WHITE, COLOR_BLACK); init_pair(2, COLOR_BLACK, COLOR_WHITE); int i = 0; while (true){ wclear(stdscr); if (i == 0) wcolor_set(stdscr, selected, nullptr); else wcolor_set(stdscr, unselected, nullptr); mvwprintw(stdscr, 3, 10, "[LOAD]"); if (i == 1) wcolor_set(stdscr, selected, nullptr); else wcolor_set(stdscr, unselected, nullptr); mvwprintw(stdscr, 4, 10, "[PLAY]"); if (i == 2) wcolor_set(stdscr, selected, nullptr); else wcolor_set(stdscr, unselected, nullptr); mvwprintw(stdscr, 5, 10, "[PAUSE]"); if (i == 3) wcolor_set(stdscr, selected, nullptr); else wcolor_set(stdscr, unselected, nullptr); mvwprintw(stdscr, 6, 10, "[STOP]"); auto input = getch(); switch (input){ case 'q': return 0; case '\n': if (!i){ f(); } break; case KEY_DOWN: i = (i + 1) % 4; break; case KEY_UP: i = (i + 3) % 4; break; case KEY_RESIZE: resize_term(0, 0); //wmove(stdscr, y/2, x/2); //wprintw(stdscr, "%d, %d", x, y); //mvprintw(0, 0, "%d, %d", x, y); } //wmove(stdscr, 0, 0); mvwprintw(stdscr, 0, 0, " "); wrefresh(stdscr); } return 0; }
19.586207
44
0.555751
Helios-vmg
7716712cd240d04a5ca444d2f67c6a09e6404c58
13,834
cpp
C++
cwhttp/HttpClient.cpp
hssaaannnn/cwhttp
8faedb45971ab85279987f7fbb0db5ce63d9b401
[ "MIT" ]
null
null
null
cwhttp/HttpClient.cpp
hssaaannnn/cwhttp
8faedb45971ab85279987f7fbb0db5ce63d9b401
[ "MIT" ]
null
null
null
cwhttp/HttpClient.cpp
hssaaannnn/cwhttp
8faedb45971ab85279987f7fbb0db5ce63d9b401
[ "MIT" ]
1
2019-04-16T12:58:35.000Z
2019-04-16T12:58:35.000Z
#include <curl/curl.h> #include "HttpClient.h" #include "ScopedCurl.h" #include "Method.h" #include "Request.h" #include "Response.h" #include "ScopedSList.h" #include "StringUtils.h" #include "Header.h" #include "Logger.h" #include "Cookie.h" #include "CookieJar.h" #include "HeaderContainer.h" #include "ResponseBody.h" namespace cwhttp { class CurlInitializer { public: CurlInitializer() { curl_global_init(CURL_GLOBAL_DEFAULT); } ~CurlInitializer() { curl_global_cleanup(); } }; static const CurlInitializer CURL_INITIALIZER; constexpr const char* UA_CURL = "libcurl/"; HttpClient::HttpClient() : m_IsDebug(false) , m_UserAgent(getDefaultUserAgent()) , m_CaBundle() , m_ProxyHost() , m_ProxyPort(0) , m_ConnectionTimeout(0) , m_pCookieJar(nullptr) { } HttpClient::WriteControl::WriteControl(Response* pR, bool follow, CookieList* pC) : pResponse(pR) , lastCode(0) , followRedirect(follow) , isInited(false) , pReceivedCookies(pC) { } bool HttpClient::WriteControl::isRedirect() const { return lastCode != 0 && (300 <= lastCode && lastCode < 400); } bool HttpClient::WriteControl::shallWrite() const { return followRedirect ? !isRedirect() : true; } static int getStatusCode(const std::string& line) { std::istringstream s(line); std::string protocol; s >> protocol; if (!s.good() || !StringUtils::hasPrefix(protocol, "HTTP/")) return 0; int code; s >> code; return s.good() ? code : 0; } void HttpClient::constructResponse(Response* pResponse, const std::string& name, const std::string& value) { if (name.compare(HEADER_CONTENT_LENGTH) == 0) { std::istringstream is(value); std::size_t cl; is >> cl; pResponse->setContentLength(cl); } else if (name.compare(HEADER_CONTENT_TYPE) == 0) { pResponse->setContentType(value); } } std::size_t HttpClient::onCurlWriteHeader(const char* pData, std::size_t size, std::size_t n, void* pUserData) { HttpClient::WriteControl* pControl = static_cast<HttpClient::WriteControl*>(pUserData); HeaderContainer* pHeaders = pControl->pResponse->getModifiableHeaders(); const std::size_t length = size * n; std::string line(pData, length); // ignore CR LF if (line.compare("\x0D\x0A") == 0) return length; const int code = getStatusCode(line); if (code != 0) { pControl->lastCode = code; } std::string name; std::string value; if (HeaderContainer::parseLine(line, name, value)) { if (pControl->shallWrite()) { pHeaders->addTrimmed(name, value); constructResponse(pControl->pResponse, name, value); } if (name.compare(HEADER_SET_COOKIE) == 0) { const Cookie c(value); if (c.isValid()) { pControl->pReceivedCookies->emplace_back(c); } } } return length; } std::size_t HttpClient::onCurlWriteBody(const char* pData, std::size_t size, std::size_t n, void* pUserData) { HttpClient::WriteControl* pControl = static_cast<HttpClient::WriteControl*>(pUserData); const std::size_t length = size * n; if (pControl->shallWrite()) { if (!pControl->isInited) { pControl->isInited = true; if (!pControl->pResponse->startWrite()) { return 0; } } return pControl->pResponse->executeWrite(pData, length); } else { return length; } } std::string HttpClient::buildCookieHeader(const CookieList& cookies) { std::string header; for (auto it = cookies.begin(); it != cookies.end();) { header += it->getName(); header += "="; header += it->getValue(); ++it; if (it != cookies.end()) { header += "; "; } } return header; } int HttpClient::onCurlSeekBody(void* pUserData, int64_t offset, int origin) { Request* pRequest = static_cast<Request*>(pUserData); int ret; switch (origin) { case SEEK_SET: ret = pRequest->executeSeek(offset) ? CURL_SEEKFUNC_OK : CURL_SEEKFUNC_FAIL; break; case SEEK_CUR: case SEEK_END: default: ret = CURL_SEEKFUNC_FAIL; break; } return ret; } std::size_t HttpClient::onCurlReadBody(char* pBuffer, std::size_t size, std::size_t n, void* pUserData) { Request* pRequest = static_cast<Request*>(pUserData); const std::size_t atMost = size * n; return pRequest->executeRead(pBuffer, atMost); } struct DebugConfig { bool traceSslData = false; }; constexpr int MAX_LOG_LENGTH = 512; static int onDebugDataReceived(CURL* pCurl, curl_infotype type, const char* pData, const std::size_t size, void* pUserData) { const bool shallTruncate = size > MAX_LOG_LENGTH; std::size_t logSize = shallTruncate ? MAX_LOG_LENGTH : size; std::string data(pData, logSize); if (StringUtils::hasSuffix(data, "\x0D\x0A\x0D\x0A")) { data.resize(data.size() - 4); } else if (StringUtils::hasSuffix(data, "\x0D\x0A")) { data.resize(data.size() - 2); } else if (*data.rbegin() == '\x0D' || *data.rbegin() == '\x0A') { data.pop_back(); } std::transform(data.begin(), data.end(), data.begin(), [](char c) { if (std::isprint(c) || c == '\x0D' || c == '\x0A' || c == '\x09') { return c; } else { return '.'; } }); if (shallTruncate) { data += " ...and more"; } DebugConfig* pConfig = static_cast<DebugConfig*>(pUserData); const char* pText; switch (type) { case CURLINFO_TEXT: LOGD("== Info: %s", data.c_str()); default: /* in case a new one is introduced to shock us */ return 0; case CURLINFO_HEADER_OUT: pText = "=> Send header"; break; case CURLINFO_DATA_OUT: pText = "=> Send data"; break; case CURLINFO_SSL_DATA_OUT: if (!pConfig->traceSslData) return 0; pText = "=> Send SSL data"; break; case CURLINFO_HEADER_IN: pText = "<= Recv header"; break; case CURLINFO_DATA_IN: pText = "<= Recv data"; break; case CURLINFO_SSL_DATA_IN: if (!pConfig->traceSslData) return 0; pText = "<= Recv SSL data"; break; } LOGD("%s, %10.10ld bytes (0x%8.8lX)", pText, (long) size, (long) size); LOGD("%s", data.c_str()); return 0; } bool HttpClient::execute(const Request& request, Response& response) const { const ScopedCurl curl; if (!curl.isValid()) { return false; } DebugConfig debugConfig; if (m_IsDebug) { curl_easy_setopt(curl(), CURLOPT_DEBUGFUNCTION, onDebugDataReceived); curl_easy_setopt(curl(), CURLOPT_DEBUGDATA, &debugConfig); curl_easy_setopt(curl(), CURLOPT_VERBOSE, 1L); } if (m_CaBundle.length() != 0) { curl_easy_setopt(curl(), CURLOPT_CAINFO, m_CaBundle.c_str()); } if (m_ProxyHost.length() != 0) { curl_easy_setopt(curl(), CURLOPT_PROXY, m_ProxyHost.c_str()); if (m_ProxyPort > 0) { curl_easy_setopt(curl(), CURLOPT_PROXYPORT, static_cast<long>(m_ProxyPort)); } } if (m_ConnectionTimeout > 0) { curl_easy_setopt(curl(), CURLOPT_CONNECTTIMEOUT, static_cast<long>(m_ConnectionTimeout)); } curl_easy_setopt(curl(), CURLOPT_USERAGENT, m_UserAgent.c_str()); curl_easy_setopt(curl(), CURLOPT_FOLLOWLOCATION, request.isFollowRedirect() ? 1L : 0L); curl_easy_setopt(curl(), CURLOPT_URL, request.getUrl().c_str()); CookieList receivedCookies; WriteControl control(&response, request.isFollowRedirect(), &receivedCookies); curl_easy_setopt(curl(), CURLOPT_HEADERFUNCTION, onCurlWriteHeader); curl_easy_setopt(curl(), CURLOPT_HEADERDATA, &control); curl_easy_setopt(curl(), CURLOPT_WRITEFUNCTION, onCurlWriteBody); curl_easy_setopt(curl(), CURLOPT_WRITEDATA, &control); ScopedSList headerLines; request.getHeaders()->iterateAllLines([&headerLines](const std::string& headerLine) { headerLines.append(headerLine.c_str()); }); if (request.hasBody()) { headerLines.append(HeaderContainer::buildLine(HEADER_CONTENT_TYPE, request.getContentType()).c_str()); if (request.isChunked()) { headerLines.append(HeaderContainer::buildLine(HEADER_TRANSFER_ENCODING, "chunked").c_str()); } } curl_easy_setopt(curl(), CURLOPT_HTTPHEADER, headerLines()); if (m_pCookieJar != nullptr) { CookieList cookiesToSend; m_pCookieJar->loadForRequest(request.getUrl(), cookiesToSend); if (cookiesToSend.size() != 0) { std::string cookieString = buildCookieHeader(cookiesToSend); curl_easy_setopt(curl(), CURLOPT_COOKIE, cookieString.c_str()); } } switch (request.getMethod()) { case Method::GET: curl_easy_setopt(curl(), CURLOPT_HTTPGET, 1L); break; case Method::POST: curl_easy_setopt(curl(), CURLOPT_POST, 1L); curl_easy_setopt(curl(), CURLOPT_SEEKFUNCTION, onCurlSeekBody); curl_easy_setopt(curl(), CURLOPT_SEEKDATA, &request); curl_easy_setopt(curl(), CURLOPT_READFUNCTION, onCurlReadBody); curl_easy_setopt(curl(), CURLOPT_READDATA, &request); if (!request.isChunked()) { const curl_off_t contentLength = request.getContentLength(); curl_easy_setopt(curl(), CURLOPT_POSTFIELDSIZE_LARGE, contentLength); } break; case Method::PUT: curl_easy_setopt(curl(), CURLOPT_UPLOAD, 1L); curl_easy_setopt(curl(), CURLOPT_SEEKFUNCTION, onCurlSeekBody); curl_easy_setopt(curl(), CURLOPT_SEEKDATA, &request); curl_easy_setopt(curl(), CURLOPT_READFUNCTION, onCurlReadBody); curl_easy_setopt(curl(), CURLOPT_READDATA, &request); if (!request.isChunked()) { const curl_off_t contentLength = request.getContentLength(); curl_easy_setopt(curl(), CURLOPT_INFILESIZE_LARGE, contentLength); } break; case Method::PATCH: curl_easy_setopt(curl(), CURLOPT_POST, 1L); curl_easy_setopt(curl(), CURLOPT_SEEKFUNCTION, onCurlSeekBody); curl_easy_setopt(curl(), CURLOPT_SEEKDATA, &request); curl_easy_setopt(curl(), CURLOPT_READFUNCTION, onCurlReadBody); curl_easy_setopt(curl(), CURLOPT_READDATA, &request); if (!request.isChunked()) { const curl_off_t contentLength = request.getContentLength(); curl_easy_setopt(curl(), CURLOPT_POSTFIELDSIZE_LARGE, contentLength); } curl_easy_setopt(curl(), CURLOPT_CUSTOMREQUEST, METHOD_PATCH); break; case Method::DEL: curl_easy_setopt(curl(), CURLOPT_CUSTOMREQUEST, METHOD_DELETE); break; case Method::HEAD: curl_easy_setopt(curl(), CURLOPT_NOBODY, 1L); break; } CURLcode res = curl_easy_perform(curl()); if (res != CURLE_OK) { LOGW("curl_easy_perform() failed %d: %s\n", res, curl_easy_strerror(res)); return false; } if (m_pCookieJar != nullptr && receivedCookies.size() != 0) { m_pCookieJar->saveFromResponse(request.getUrl(), receivedCookies); } long statusCode; curl_easy_getinfo(curl(), CURLINFO_RESPONSE_CODE, &statusCode); if (control.isInited) { response.endWrite(); } response.setCode(static_cast<int32_t>(statusCode)); return true; } bool HttpClient::isDebug() const { return m_IsDebug; } void HttpClient::setDebug(bool value) { m_IsDebug = value; } std::string HttpClient::getDefaultUserAgent() { const curl_version_info_data* pData = curl_version_info(CURLVERSION_NOW); return std::string(UA_CURL).append(pData->version); } const std::string& HttpClient::getUserAgent() const { return m_UserAgent; } void HttpClient::setUserAgent(const std::string& userAgent) { if (m_UserAgent.length() == 0) return; m_UserAgent = userAgent; } void HttpClient::setCaBundle(const std::string& caBundle) { m_CaBundle = caBundle; } void HttpClient::setProxy(const std::string& host, std::int32_t port) { m_ProxyHost = host; m_ProxyPort = port; } void HttpClient::setConnectionTimeout(std::int32_t connectionTimeout) { m_ConnectionTimeout = connectionTimeout; } void HttpClient::setCookieJar(CookieJar* pCookieJar) { m_pCookieJar = pCookieJar; } }
34.846348
116
0.579876
hssaaannnn
77174de038c23acc56803595107cf040975399fe
1,471
hpp
C++
lib/heif/Srcs/common/avcconfigurationbox.hpp
anzksdk/tifig-by
17a306b27e6e2dd2992e1c0896312047541f4be0
[ "Apache-2.0" ]
null
null
null
lib/heif/Srcs/common/avcconfigurationbox.hpp
anzksdk/tifig-by
17a306b27e6e2dd2992e1c0896312047541f4be0
[ "Apache-2.0" ]
null
null
null
lib/heif/Srcs/common/avcconfigurationbox.hpp
anzksdk/tifig-by
17a306b27e6e2dd2992e1c0896312047541f4be0
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2017, Nokia Technologies Ltd. * All rights reserved. * * Licensed under the Nokia High-Efficiency Image File Format (HEIF) License (the "License"). * * You may not use the High-Efficiency Image File Format except in compliance with the License. * The License accompanies the software and can be found in the file "LICENSE.TXT". * * You may also obtain the License at: * https://nokiatech.github.io/heif/license.txt */ #ifndef AVCCONFIGURATIONBOX_HPP #define AVCCONFIGURATIONBOX_HPP #include "avcdecoderconfigrecord.hpp" #include "bbox.hpp" /// @brief AVC Configuration Box class /// @details 'avcC' box implementation. This is used by tracks as a part of AVC Sample Entry implementation, and by /// items as a decoder configuration property. class AvcConfigurationBox : public Box { public: AvcConfigurationBox(); virtual ~AvcConfigurationBox() = default; /// @return Contained AvcDecoderConfigurationRecord const AvcDecoderConfigurationRecord& getConfiguration() const; /// @param [in] config New AVC decoder configuration. void setConfiguration(const AvcDecoderConfigurationRecord& config); /// @see Box::writeBox() virtual void writeBox(BitStream& bitstr); /// @see Box::parseBox() virtual void parseBox(BitStream& bitstr); private: AvcDecoderConfigurationRecord mAvcConfig; ///< AVCConfigurationBox field AVCConfig }; #endif /* end of include guard: AVCCONFIGURATIONBOX_HPP */
31.978261
115
0.742352
anzksdk
7718dd845ba35459ee42529b261dd9df55e2a0cf
3,162
hpp
C++
rusql/mysql/error_checked.hpp
Wassasin/librusql
207919e5da1e9e49d4c575c81699fcb1d8cd6204
[ "BSD-3-Clause" ]
2
2018-01-16T18:05:21.000Z
2021-02-02T05:04:51.000Z
rusql/mysql/error_checked.hpp
Wassasin/librusql
207919e5da1e9e49d4c575c81699fcb1d8cd6204
[ "BSD-3-Clause" ]
null
null
null
rusql/mysql/error_checked.hpp
Wassasin/librusql
207919e5da1e9e49d4c575c81699fcb1d8cd6204
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <stdexcept> #include <mysql.h> #include <boost/optional.hpp> namespace rusql { namespace mysql { struct SQLError : std::runtime_error { SQLError(std::string msg) : std::runtime_error(msg) {} SQLError(std::string const & function, std::string const & s) : std::runtime_error(function + ": " + s) {} }; struct Connection; void clear_mysql_error(MYSQL *connection); struct ErrorCheckerConnection { MYSQL* connection; char const * function; ErrorCheckerConnection(MYSQL* connection, char const * f); ~ErrorCheckerConnection(); void check_and_throw(std::string const function); }; struct Statement; struct ErrorCheckerStatement { MYSQL_STMT* statement; char const * function; ErrorCheckerStatement(MYSQL_STMT* statement, char const * f); ~ErrorCheckerStatement(); void check_and_throw(std::string const function); }; void thread_init(void); void thread_end(void); MYSQL* init(MYSQL* connection); void close(MYSQL* connection); int ping(MYSQL* connection); MYSQL_RES* use_result(MYSQL* connection); size_t field_count(MYSQL* connection); MYSQL_STMT* stmt_init(MYSQL* connection); //! There's no difference for us between connect and "real_connect", so we just have one version: connect. MYSQL* connect( MYSQL* connection, boost::optional<std::string const> host, boost::optional<std::string const> user, boost::optional<std::string const> password, boost::optional<std::string const> database, unsigned long const port, boost::optional<std::string const> unix_socket, unsigned long client_flags ); void query(MYSQL* connection, std::string const query); //! Doesn't return errors MYSQL_FIELD* fetch_field(MYSQL_RES* result); //! Doesn't return errors MYSQL_FIELD_OFFSET field_seek(MYSQL_RES* result, MYSQL_FIELD_OFFSET offset); //! Doesn't return errors unsigned long* fetch_lengths(MYSQL_RES* result); //! Doesn't return errors unsigned int num_fields(MYSQL_RES* result); //! Doesn't return errors void free_result(MYSQL_RES* result); //! Needs a connection for error checking MYSQL_ROW fetch_row(MYSQL* connection, MYSQL_RES* result); unsigned long long insert_id(MYSQL *connection); unsigned long long num_rows(MYSQL *connection, MYSQL_RES *result); //! Doesn't return errors unsigned long stmt_param_count(MYSQL_STMT* statement); unsigned long stmt_field_count(MYSQL_STMT* statement); my_bool stmt_bind_param(MYSQL_STMT* statement, MYSQL_BIND* binds); my_bool stmt_bind_result(MYSQL_STMT* statement, MYSQL_BIND* binds); void stmt_fetch_column(MYSQL_STMT* statement, MYSQL_BIND* bind, unsigned int column, unsigned long offset); my_bool stmt_close(MYSQL_STMT* statement); int stmt_execute(MYSQL_STMT* statement); int stmt_prepare(MYSQL_STMT* statement, std::string q); unsigned long long stmt_insert_id(MYSQL_STMT* statement); void stmt_store_result(MYSQL_STMT *statement); unsigned long long stmt_num_rows(MYSQL_STMT* statement); //! Returns non-zero when there are no more rows to fetch int stmt_fetch(MYSQL_STMT* statement); MYSQL_RES *stmt_result_metadata(MYSQL_STMT *statement); }}
27.025641
108
0.751423
Wassasin
771cb7ed394aef806a1b409d25de91bbf71888f1
172
hpp
C++
include/Utilities/UI.hpp
InDieTasten/IDT.EXP
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
null
null
null
include/Utilities/UI.hpp
InDieTasten/IDT.EXP
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
56
2017-03-30T14:45:29.000Z
2017-03-30T14:46:29.000Z
include/Utilities/UI.hpp
InDieTasten-Legacy/--EXP-old-
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
1
2015-05-08T19:23:51.000Z
2015-05-08T19:23:51.000Z
#ifndef _UI_hpp_ #define _UI_hpp_ #include <SFML\Graphics.hpp> namespace utils { bool hovering(sf::FloatRect object, sf::Vector2i mouse); } #endif // !_UI_hpp_
17.2
58
0.703488
InDieTasten
771cbe14a7cc436cd9c202012543597380b21f4a
1,726
cpp
C++
query_strategies/merge_sum.cpp
shalijiang/efficient-nonmyopic-active-search
6ac08c088dd903ef8a39381380f533889537b9ba
[ "MIT" ]
8
2019-04-17T05:06:44.000Z
2021-02-04T16:57:55.000Z
query_strategies/merge_sum.cpp
shalijiang/efficient-nonmyopic-active-search
6ac08c088dd903ef8a39381380f533889537b9ba
[ "MIT" ]
null
null
null
query_strategies/merge_sum.cpp
shalijiang/efficient-nonmyopic-active-search
6ac08c088dd903ef8a39381380f533889537b9ba
[ "MIT" ]
3
2019-11-06T21:08:59.000Z
2020-06-18T15:20:17.000Z
#include "mex.h" #define P_ARG prhs[0] #define Q_ARG prhs[1] #define TOP_IND_ARG prhs[2] #define REM_GOAL prhs[3] #define SUM_ARG plhs[0] #define ALL_ARG plhs[1] #define P_IND ((int)(top_ind[j]) - 1) void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *p, *q, *top_ind, utility; int remaining_goal, i, j, k; double cost; size_t n, m; /* get input */ p = mxGetPr(P_ARG); q = mxGetPr(Q_ARG); top_ind = mxGetPr(TOP_IND_ARG); remaining_goal = (int)(mxGetScalar(REM_GOAL)); n = mxGetNumberOfElements(Q_ARG); m = mxGetNumberOfElements(P_ARG); utility = 0; cost = 0; i = 0; j = 0; while (p[P_IND] == 0) j++; k = 0; double last_p; while ((j < m) && (k < n)) { if (p[P_IND] > q[k]) { utility += p[P_IND]; last_p = p[P_IND]; do { j++; } while (p[P_IND] == 0); } else { utility += q[k]; last_p = q[k]; k++; } cost += 1; if (utility >= remaining_goal){ break; } } if (utility < remaining_goal){ while (j < m) { utility += p[P_IND]; last_p = p[P_IND]; do { j++; } while (p[P_IND] == 0); cost += 1; if (utility >= remaining_goal){ break; } } while (k < n) { utility += q[k]; last_p = q[k]; k++; cost += 1; if (utility >= remaining_goal){ break; } } } if (utility < remaining_goal){ cost = m-1; } else{ // corretion by subtracting the extra utility cost = cost - (utility - remaining_goal)/last_p; //mexPrintf("cost: %f\n", cost); } SUM_ARG = mxCreateDoubleScalar(cost); }
18.76087
54
0.511008
shalijiang
77211d2d41ef39815b3fe06b57875a717a82d084
19,140
cpp
C++
nvgpu/OffsetOps.cpp
uasys/ACF-Coalescing-LLVM
db811bda15bb7c4a951644130ab55f5cb5848351
[ "MIT" ]
1
2020-06-23T00:18:56.000Z
2020-06-23T00:18:56.000Z
nvgpu/OffsetOps.cpp
uasys/ACF-Coalescing-LLVM
db811bda15bb7c4a951644130ab55f5cb5848351
[ "MIT" ]
null
null
null
nvgpu/OffsetOps.cpp
uasys/ACF-Coalescing-LLVM
db811bda15bb7c4a951644130ab55f5cb5848351
[ "MIT" ]
null
null
null
#include "ThreadDepAnalysis.h" #include "OffsetOps.h" using namespace llvm; using namespace std; namespace gpucheck { OffsetValPtr negateCondition(OffsetValPtr& cond) { assert(isa<BinOpOffsetVal>(cond.get())); auto b=dyn_cast<BinOpOffsetVal>(cond.get()); OffsetValPtr lhs = b->lhs; OffsetValPtr rhs = b->rhs; // Logical conditionals, apply DeMorgan's laws. if (b->op == OffsetOperator::And) return make_shared<BinOpOffsetVal>(negateCondition(lhs), OffsetOperator::Or, negateCondition(rhs)); else if (b->op == OffsetOperator::Or) return make_shared<BinOpOffsetVal>(negateCondition(lhs), OffsetOperator::And, negateCondition(rhs)); // Comparison conditions are negated by flipping the operator. OffsetOperator flipped; switch(b->op) { case OffsetOperator::Eq: flipped = Neq; break; case OffsetOperator::Neq: flipped = Eq; break; case OffsetOperator::SLT: flipped = SGE; break; case OffsetOperator::SGE: flipped = SLT; break; case OffsetOperator::SLE: flipped = SGT; break; case OffsetOperator::SGT: flipped = SLE; break; case OffsetOperator::ULT: flipped = UGE; break; case OffsetOperator::UGE: flipped = ULT; break; case OffsetOperator::ULE: flipped = UGT; break; case OffsetOperator::UGT: flipped = ULE; break; default: flipped = end; break; } assert(flipped != OffsetOperator::end); return make_shared<BinOpOffsetVal>(b->lhs, flipped, b->rhs); } OffsetValPtr sumOfProducts(OffsetValPtr ov) { OffsetValPtr tmp = ov; OffsetValPtr res = sumOfProductsPass(ov); while (!matchingOffsets(tmp, res)) { tmp = res; res = sumOfProductsPass(tmp); } return res; } OffsetValPtr sumOfProductsPass(OffsetValPtr ov) { auto bo=dyn_cast<BinOpOffsetVal>(&*ov); if(bo == nullptr) return ov; // We're working with a binary operator OffsetValPtr lhs = sumOfProductsPass(bo->lhs); OffsetValPtr rhs = sumOfProductsPass(bo->rhs); if(bo->op == OffsetOperator::Mul) { auto lhs_bo=dyn_cast<BinOpOffsetVal>(&*lhs); if(lhs_bo != nullptr && (lhs_bo->op == OffsetOperator::Add || lhs_bo->op == OffsetOperator::Sub)) { // Multiply RHS into LHS operands auto new_lhs = make_shared<BinOpOffsetVal>(lhs_bo->lhs, bo->op, rhs); auto new_rhs = make_shared<BinOpOffsetVal>(lhs_bo->rhs, bo->op, rhs); return make_shared<BinOpOffsetVal>(new_lhs, lhs_bo->op, new_rhs); } auto rhs_bo=dyn_cast<BinOpOffsetVal>(&*rhs); if(rhs_bo != nullptr && (rhs_bo->op == OffsetOperator::Add || rhs_bo->op == OffsetOperator::Sub)) { // Multiply LHS into RHS operands auto new_lhs = make_shared<BinOpOffsetVal>(lhs, bo->op, rhs_bo->lhs); auto new_rhs = make_shared<BinOpOffsetVal>(lhs, bo->op, rhs_bo->rhs); return make_shared<BinOpOffsetVal>(new_lhs, rhs_bo->op, new_rhs); } } else if (bo->op == OffsetOperator::SDiv || bo->op == OffsetOperator::UDiv) { auto lhs_bo=dyn_cast<BinOpOffsetVal>(&*lhs); if(lhs_bo != nullptr && (lhs_bo->op == OffsetOperator::Add || lhs_bo->op == OffsetOperator::Sub)) { auto new_lhs = make_shared<BinOpOffsetVal>(lhs_bo->lhs, bo->op, rhs); auto new_rhs = make_shared<BinOpOffsetVal>(lhs_bo->rhs, bo->op, rhs); return make_shared<BinOpOffsetVal>(new_lhs, lhs_bo->op, new_rhs); } } // Just return the sum-of-productsed operands return make_shared<BinOpOffsetVal>(lhs, bo->op, rhs); } OffsetValPtr simplifyConditions(OffsetValPtr lhs, OffsetOperator op, OffsetValPtr rhs) { // Convert (cond_1 - cond_2) to (cond_1*(!cond_2)) if(auto bo_lhs=dyn_cast<BinOpOffsetVal>(&*lhs)) { if(auto bo_rhs=dyn_cast<BinOpOffsetVal>(&*rhs)) { if(bo_lhs->isCompare() && bo_rhs->isCompare() && op == OffsetOperator::Sub) { return make_shared<BinOpOffsetVal>(lhs, OffsetOperator::Mul, negateCondition(rhs)); } } } return nullptr; } OffsetValPtr simplifyConstantVal(OffsetValPtr lhs, OffsetOperator op, OffsetValPtr rhs) { assert(lhs->isConst() && rhs->isConst()); APInt lhsi = lhs->constVal(); APInt rhsi = rhs->constVal(); // Always just work in the larger bitwidth if(lhsi.getBitWidth() > rhsi.getBitWidth()) rhsi = rhsi.zext(lhsi.getBitWidth()); if(rhsi.getBitWidth() > lhsi.getBitWidth()) lhsi = lhsi.zext(rhsi.getBitWidth()); APInt out; switch(op) { case OffsetOperator::Add: out = lhsi + rhsi; break; case OffsetOperator::Sub: out = lhsi - rhsi; break; case OffsetOperator::Mul: out = lhsi * rhsi; break; case OffsetOperator::SDiv: out = lhsi.sdiv(rhsi); break; case OffsetOperator::UDiv: out = lhsi.udiv(rhsi); break; case OffsetOperator::SRem: out = lhsi.srem(rhsi); break; case OffsetOperator::URem: out = lhsi.urem(rhsi); break; //case OffsetOperator::And: out = lhsi.And(rhsi); break; //case OffsetOperator::Or: out = lhsi.Or(rhsi); break; //case OffsetOperator::Xor: out = lhsi.Xor(rhsi); break; case OffsetOperator::Eq: out = lhsi.eq(rhsi); break; case OffsetOperator::Neq: out = lhsi.ne(rhsi); break; case OffsetOperator::SLT: out = lhsi.slt(rhsi); break; case OffsetOperator::SLE: out = lhsi.sle(rhsi); break; case OffsetOperator::ULT: out = lhsi.ult(rhsi); break; case OffsetOperator::ULE: out = lhsi.ule(rhsi); break; case OffsetOperator::SGT: out = lhsi.sgt(rhsi); break; case OffsetOperator::SGE: out = lhsi.sge(rhsi); break; case OffsetOperator::UGT: out = lhsi.ugt(rhsi); break; case OffsetOperator::UGE: out = lhsi.uge(rhsi); break; case OffsetOperator::end: assert(false); break; } return make_shared<ConstOffsetVal>(out); } OffsetValPtr simplifyOffsetVal(OffsetValPtr ov) { auto bo=dyn_cast<BinOpOffsetVal>(&*ov); if(bo == nullptr) return ov; OffsetValPtr lhs = simplifyOffsetVal(bo->lhs); OffsetValPtr rhs = simplifyOffsetVal(bo->rhs); if(lhs->isConst() && rhs->isConst()) return simplifyConstantVal(lhs, bo->op, rhs); switch(bo->op) { case OffsetOperator::Add: { // Adding zero does nothing if(rhs->isConst() && rhs->constVal() == 0) return lhs; if(lhs->isConst() && lhs->constVal() == 0) return rhs; } case OffsetOperator::Sub: { if(rhs->isConst() && rhs->constVal() == 0) return lhs; if(auto new_bo = simplifyConditions(lhs, bo->op, rhs)) return simplifyOffsetVal(new_bo); } case OffsetOperator::Mul: { // Zeroes destroy the entire tree if(rhs->isConst() && rhs->constVal() == 0) return rhs; if(lhs->isConst() && lhs->constVal() == 0) return lhs; // Ones have no effect if(rhs->isConst() && rhs->constVal() == 1) return lhs; if(lhs->isConst() && lhs->constVal() == 1) return rhs; } case OffsetOperator::SDiv: case OffsetOperator::UDiv: { // Dividing by one does nothing if(rhs->isConst() && rhs->constVal() == 1) return lhs; // 0/anything is zero if(lhs->isConst() && lhs->constVal() == 0) return lhs; } case OffsetOperator::SRem: case OffsetOperator::URem: { // 0%anything is always 0 if (lhs->isConst() && lhs->constVal() == 0) return lhs; // 1%anything is always 1 if (lhs->isConst() && lhs->constVal() == 1) return lhs; // anything%1 is always 0 if (rhs->isConst() && rhs->constVal() == 1) return make_shared<ConstOffsetVal>(0); } } if (OffsetValPtr simp = simplifyConstantSubExpressions(lhs, bo->op, rhs)) { return simp; } // Just return the simplified components return make_shared<BinOpOffsetVal>(lhs, bo->op, rhs); } OffsetValPtr simplifyConstantSubExpressions(OffsetValPtr lhs, OffsetOperator op, OffsetValPtr rhs) { bool boAdd = (op == OffsetOperator::Add); bool boSub = (op == OffsetOperator::Sub); if (isa<BinOpOffsetVal>(&*lhs) && rhs->isConst() && (boAdd || boSub)) { auto lhsBinop = dyn_cast<BinOpOffsetVal>(&*lhs); OffsetValPtr llhs = lhsBinop->lhs; OffsetValPtr lrhs = lhsBinop->rhs; if (lrhs->isConst()) { switch (lhsBinop->op) { case OffsetOperator::Add: { APInt newConst = boAdd ? lrhs->constVal() + rhs->constVal() : lrhs->constVal() - rhs->constVal(); OffsetValPtr result = make_shared<BinOpOffsetVal>(llhs, lhsBinop->op, make_shared<ConstOffsetVal>(newConst)); return simplifyOffsetVal(result); } break; case OffsetOperator::Sub: { APInt newConst = boAdd ? lrhs->constVal() - rhs->constVal() : lrhs->constVal() + rhs->constVal(); OffsetValPtr result = make_shared<BinOpOffsetVal>(llhs, lhsBinop->op, make_shared<ConstOffsetVal>(newConst)); return simplifyOffsetVal(result); break; } } } else if (llhs->isConst()) { switch (lhsBinop->op) { case OffsetOperator::Sub: case OffsetOperator::Add: { APInt newConst = boAdd ? llhs->constVal() + rhs->constVal() : llhs->constVal() - rhs->constVal(); OffsetValPtr result = make_shared<BinOpOffsetVal>(make_shared<ConstOffsetVal>(newConst), lhsBinop->op, lrhs); return simplifyOffsetVal(result); } break; } } } if (isa<BinOpOffsetVal>(&*rhs) && lhs->isConst() && (boAdd || boSub)) { auto rhsBinop = dyn_cast<BinOpOffsetVal>(&*rhs); OffsetValPtr rlhs = rhsBinop->lhs; OffsetValPtr rrhs = rhsBinop->rhs; if (rlhs->isConst()) { switch (rhsBinop->op) { case OffsetOperator::Add: { APInt newConst = boAdd ? lhs->constVal() + rlhs->constVal() : lhs->constVal() - rlhs->constVal(); OffsetOperator newOp = boAdd ? rhsBinop->op : OffsetOperator::Sub; OffsetValPtr result = make_shared<BinOpOffsetVal>(make_shared<ConstOffsetVal>(newConst), newOp, rrhs); return simplifyOffsetVal(result); } break; case OffsetOperator::Sub: { APInt newConst = boAdd ? lhs->constVal() + rlhs->constVal() : lhs->constVal() - rlhs->constVal(); OffsetOperator newOp = boAdd ? rhsBinop->op : OffsetOperator::Add; OffsetValPtr result = make_shared<BinOpOffsetVal>(make_shared<ConstOffsetVal>(newConst), newOp, rrhs); return simplifyOffsetVal(result); } break; } } if (rrhs->isConst()) { switch (rhsBinop->op) { case OffsetOperator::Add: { APInt newConst = boAdd ? lhs->constVal() + rrhs->constVal() : lhs->constVal() - rrhs->constVal(); OffsetOperator newOp = boAdd ? rhsBinop->op : OffsetOperator::Sub; OffsetValPtr result = make_shared<BinOpOffsetVal>(make_shared<ConstOffsetVal>(newConst), newOp, rlhs); return simplifyOffsetVal(result); } break; case OffsetOperator::Sub: { APInt newConst = boAdd ? lhs->constVal() - rrhs->constVal() : lhs->constVal() + rrhs->constVal(); OffsetOperator newOp = boAdd ? rhsBinop->op : OffsetOperator::Sub; OffsetValPtr result = make_shared<BinOpOffsetVal>(make_shared<ConstOffsetVal>(newConst), newOp, rlhs); return simplifyOffsetVal(result); } break; } } } return nullptr; } bool matchingOffsets(OffsetValPtr lhs, OffsetValPtr rhs) { assert(lhs != nullptr); assert(rhs != nullptr); if(lhs->isConst() && rhs->isConst()) { APInt lhs_c = lhs->constVal(); APInt rhs_c = rhs->constVal(); uint64_t bitwidth = max(lhs_c.getBitWidth(), rhs_c.getBitWidth()); return lhs_c.sextOrSelf(bitwidth) == rhs_c.sextOrSelf(bitwidth); } auto i_lhs = dyn_cast<InstOffsetVal>(&*lhs); auto i_rhs = dyn_cast<InstOffsetVal>(&*rhs); if(i_lhs && i_rhs) { return (i_lhs->inst == i_rhs->inst); } auto a_lhs = dyn_cast<ArgOffsetVal>(&*lhs); auto a_rhs = dyn_cast<ArgOffsetVal>(&*rhs); if(a_lhs && a_rhs) { return (a_lhs->arg == a_rhs->arg); } auto u_lhs = dyn_cast<UnknownOffsetVal>(&*lhs); auto u_rhs = dyn_cast<UnknownOffsetVal>(&*rhs); if(u_lhs && u_rhs) { return (u_lhs->cause == u_rhs->cause); } auto bo_lhs = dyn_cast<BinOpOffsetVal>(&*lhs); auto bo_rhs = dyn_cast<BinOpOffsetVal>(&*rhs); if(bo_lhs && bo_rhs) { return bo_lhs->op == bo_rhs->op && matchingOffsets(bo_lhs->lhs, bo_rhs->lhs) && matchingOffsets(bo_lhs->rhs, bo_rhs->rhs); } return false; } bool equalOffsets(OffsetValPtr lhs, OffsetValPtr rhs, ThreadDependence& td) { assert(lhs != nullptr); assert(rhs != nullptr); if(lhs->isConst() && rhs->isConst()) { APInt lhs_c = lhs->constVal(); APInt rhs_c = rhs->constVal(); uint64_t bitwidth = max(lhs_c.getBitWidth(), rhs_c.getBitWidth()); return lhs_c.sextOrSelf(bitwidth) == rhs_c.sextOrSelf(bitwidth); } auto i_lhs = dyn_cast<InstOffsetVal>(&*lhs); auto i_rhs = dyn_cast<InstOffsetVal>(&*rhs); if(i_lhs && i_rhs) { if(i_lhs->inst == i_rhs->inst) return !td.isDependent(const_cast<Instruction *>(i_lhs->inst)); } auto a_lhs = dyn_cast<ArgOffsetVal>(&*lhs); auto a_rhs = dyn_cast<ArgOffsetVal>(&*rhs); if(a_lhs && a_rhs) { if(a_lhs->arg == a_rhs->arg) return !td.isDependent(const_cast<Argument *>(a_lhs->arg)); } auto u_lhs = dyn_cast<UnknownOffsetVal>(&*lhs); auto u_rhs = dyn_cast<UnknownOffsetVal>(&*rhs); if(u_lhs && u_rhs) { if(u_lhs->cause == u_rhs->cause) return !td.isDependent(const_cast<Value *>(u_lhs->cause)); } auto bo_lhs = dyn_cast<BinOpOffsetVal>(&*lhs); auto bo_rhs = dyn_cast<BinOpOffsetVal>(&*rhs); if(bo_lhs && bo_rhs) { return bo_lhs->op == bo_rhs->op && equalOffsets(bo_lhs->lhs, bo_rhs->lhs, td) && equalOffsets(bo_lhs->rhs, bo_rhs->rhs, td); } return false; } void addToVector(const OffsetValPtr& ov, vector<OffsetValPtr>& add, vector<OffsetValPtr>&sub, bool isSub = false) { assert(ov != nullptr); auto bo = dyn_cast<BinOpOffsetVal>(&*ov); if(bo != nullptr) { if(bo->op == Add) { addToVector(bo->lhs, add, sub, isSub); addToVector(bo->rhs, add, sub, isSub); return; } if(bo->op == Sub) { addToVector(bo->lhs, add, sub, isSub); addToVector(bo->rhs, add, sub, !isSub); return; } } if(isSub) { sub.push_back(ov); } else { add.push_back(ov); } } OffsetValPtr cancelDiffs(OffsetValPtr ov, ThreadDependence& td) { assert(ov != nullptr); OffsetValPtr sop = sumOfProducts(ov); // Convert from binary tree to n-ary addition and subtraction vector<OffsetValPtr> added; vector<OffsetValPtr> subtracted; added.clear(); subtracted.clear(); addToVector(ov, added, subtracted); // Cancel any matching trees in the sums bool changed = true; while(changed) { changed = false; for(auto o_a=added.begin(),e_a=added.end(); o_a!=e_a; ++o_a) { for(auto o_s=subtracted.begin(),e_s=subtracted.end(); o_s!=e_s; ++o_s) { assert(*o_s != nullptr); if(equalOffsets(*o_a, *o_s, td)) { added.erase(o_a); subtracted.erase(o_s); changed = true; break; } if (OffsetValPtr simp = simplifyDifferenceOfProducts(*o_a, *o_s, td)) { added.erase(o_a); subtracted.erase(o_s); changed = true; addToVector(simp, added,subtracted); break; } } if(changed) break; } } // Rebuild the binary tree OffsetValPtr ret = (added.size() == 0) ? make_shared<ConstOffsetVal>(0) : added.back(); if(added.size() > 0) added.pop_back(); while(added.size() > 0) { ret = make_shared<BinOpOffsetVal>(ret, Add, added.back()); added.pop_back(); } while(subtracted.size() > 0) { ret = make_shared<BinOpOffsetVal>(ret, Sub, subtracted.back()); subtracted.pop_back(); } return simplifyOffsetVal(ret); } OffsetValPtr replaceComponents(const OffsetValPtr& orig, std::unordered_map<OffsetValPtr, OffsetValPtr>& rep) { // Our loose definition of equality is a problem here for(auto r=rep.begin(),e=rep.end(); r!=e; ++r) { // Perform a tree-match if(matchingOffsets(orig, r->first)) return r->second; } auto bo = dyn_cast<BinOpOffsetVal>(&*orig); if(!bo) return orig; // This is a leaf node that didn't match OffsetValPtr lhs = replaceComponents(bo->lhs, rep); OffsetValPtr rhs = replaceComponents(bo->rhs, rep); // Attempt to avoid re-allocation if possible if(lhs == bo->lhs && rhs == bo->rhs) return orig; // No changes were made else return make_shared<BinOpOffsetVal>(lhs, bo->op, rhs); } // Returns NULL if unable to change anything OffsetValPtr simplifyDifferenceOfProducts(OffsetValPtr addt, OffsetValPtr subt, ThreadDependence& td) { auto bo_a = dyn_cast<BinOpOffsetVal>(&*addt); auto bo_s = dyn_cast<BinOpOffsetVal>(&*subt); if (bo_a && bo_s && bo_a->op == OffsetOperator::Mul && bo_s->op == OffsetOperator::Mul) { OffsetValPtr a_lhs = bo_a->lhs, s_lhs = bo_s->lhs; OffsetValPtr a_rhs = bo_a->rhs, s_rhs = bo_s->rhs; if (equalOffsets(a_rhs, s_rhs, td)) { // ax-bx OffsetValPtr origDiff = make_shared<BinOpOffsetVal>(addt, OffsetOperator::Sub, subt); // (a-b) OffsetValPtr lhsDiff = make_shared<BinOpOffsetVal>(a_lhs, OffsetOperator::Sub, s_lhs); // cancellDiff on (a-b) OffsetValPtr new_lhs = cancelDiffs(lhsDiff, td); OffsetValPtr new_binop = make_shared<BinOpOffsetVal>(new_lhs, OffsetOperator::Mul, s_rhs); OffsetValPtr newsop = sumOfProducts(new_binop); OffsetValPtr oldsop = sumOfProducts(origDiff); // Did not achieve anything, important for termination. if (matchingOffsets(simplifyOffsetVal(newsop), simplifyOffsetVal(oldsop))) return nullptr; else return newsop; } else if (equalOffsets(a_lhs, s_lhs, td)) { OffsetValPtr origDiff = make_shared<BinOpOffsetVal>(addt, OffsetOperator::Sub, subt); OffsetValPtr rhsDiff = make_shared<BinOpOffsetVal>(a_rhs, OffsetOperator::Sub, s_rhs); OffsetValPtr new_rhs = cancelDiffs(rhsDiff, td); OffsetValPtr new_binop = make_shared<BinOpOffsetVal>(s_lhs, OffsetOperator::Mul, new_rhs); OffsetValPtr newsop = sumOfProducts(new_binop); OffsetValPtr oldsop = sumOfProducts(origDiff); if (matchingOffsets(simplifyOffsetVal(newsop), simplifyOffsetVal(oldsop))) return nullptr; else return newsop; } } return nullptr; } }
38.05169
119
0.621891
uasys
7723eae9b2045d7dbcf632fd16493296ef52a85e
1,395
cpp
C++
p/1k/1598/main.cpp
josedelinux/luogu
f9ce86b8623224512aa3f9e1eecc45d3c89c74e4
[ "MIT" ]
null
null
null
p/1k/1598/main.cpp
josedelinux/luogu
f9ce86b8623224512aa3f9e1eecc45d3c89c74e4
[ "MIT" ]
null
null
null
p/1k/1598/main.cpp
josedelinux/luogu
f9ce86b8623224512aa3f9e1eecc45d3c89c74e4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define REDIn #define DEBUGn #ifdef DEBUG #define REDI #endif #define MAXROW 400 using namespace std; map<char, int> m; char histogram[MAXROW + 1][26]; // extra 1 for '\0' int main() { #ifdef REDI freopen("input.txt", "r", stdin); #endif int cnt = 0; char ch; while (cin >> ch) { m[ch]++; cnt++; } // find max row int maxrow = 0; for (int i = 0; i < 26; i++) { maxrow = max(m[i + 'A'], maxrow); } #ifdef DEBUG // print counts for (int i = 0; i < 26; i++) { cout << m[i + 'A'] << " "; } cout << endl; #endif // write to histogram for (int row = MAXROW; cnt > 0 && row >= MAXROW - maxrow; row--) { for (int col = 0; cnt > 0 && col < 26; col++) { if (m[col + 'A'] != 0) { histogram[row][col] = '*'; m[col + 'A']--; cnt--; } else { histogram[row][col] = ' '; } } } // print histogram for (int row = MAXROW - maxrow + 1; row <= MAXROW; row++) { for (int col = 0; col < 26; col++) { if (histogram[row][col] == '*') { printf("* "); } else if (histogram[row][col] == ' ') { printf(" "); } } putchar('\n'); } #ifdef DEBUG // print counts for (int i = 0; i < 26; i++) { cout << m[i + 'A'] << " "; } cout << endl; #endif puts("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"); return 0; }
18.116883
68
0.467384
josedelinux
77256b1fcab4cbb4f543c7d51afab7e4f336272f
28,945
hpp
C++
include/xtensor-fftw/common.hpp
michaelbacci/xtensor-fftw
0c463ab759d7664a9b25c4382987138151ad74c3
[ "BSD-3-Clause" ]
13
2019-12-13T08:38:55.000Z
2021-06-18T09:01:23.000Z
include/xtensor-fftw/common.hpp
michaelbacci/xtensor-fftw
0c463ab759d7664a9b25c4382987138151ad74c3
[ "BSD-3-Clause" ]
13
2019-11-07T12:15:38.000Z
2022-02-23T14:33:00.000Z
include/xtensor-fftw/common.hpp
michaelbacci/xtensor-fftw
0c463ab759d7664a9b25c4382987138151ad74c3
[ "BSD-3-Clause" ]
5
2019-11-07T11:57:36.000Z
2021-05-15T22:38:37.000Z
/* * xtensor-fftw * Copyright (c) 2017, Patrick Bos * * Distributed under the terms of the BSD 3-Clause License. * * The full license is in the file LICENSE, distributed with this software. * * common.hpp: * Defines the commons datas and functions to wrap original FFTW library. * */ #ifndef XTENSOR_FFTW_COMMON_HPP #define XTENSOR_FFTW_COMMON_HPP #include <xtensor/xarray.hpp> #include "xtensor/xcomplex.hpp" #include "xtensor/xeval.hpp" #include <xtl/xcomplex.hpp> #include <complex> #include <tuple> #include <type_traits> #include <exception> #include <mutex> // for product accumulate: #include <numeric> #include <functional> #include <fftw3.h> #include "xtensor-fftw_config.hpp" #ifdef __CLING__ #pragma cling load("fftw3") #endif namespace xt { namespace fftw { // The implementations must be inline to avoid multiple definition errors due to multiple compilations (e.g. when // including this header multiple times in a project, or when it is explicitly compiled itself and included too). // Note: multidimensional complex-to-real transforms by default destroy the input data! See: // http://www.fftw.org/fftw3_doc/One_002dDimensional-DFTs-of-Real-Data.html#One_002dDimensional-DFTs-of-Real-Data // reinterpret_casts below suggested by http://www.fftw.org/fftw3_doc/Complex-numbers.html // We use the convention that the inverse fft divides by N, like numpy does. // FFTW is not thread-safe, so we need to guard around its functions (except fftw_execute). namespace detail { inline std::mutex& fftw_global_mutex() { static std::mutex m; return m; } } /////////////////////////////////////////////////////////////////////////////// // General: templates defining the basic interaction logic with fftw. These // will be specialized for all fft families, precisions and // dimensionalities. /////////////////////////////////////////////////////////////////////////////// // aliases for the fftw precision-dependent types: template <typename T> struct fftw_t { static_assert(sizeof(T) == 0, "Only specializations of fftw_t can be used"); }; // and subclass alias for when calling with a complex type: template <typename T> struct fftw_t< std::complex<T> > : public fftw_t<T> {}; // convert std::complex to fftwX_complex with right precision X; non-complex floats stay themselves: template <typename regular_or_complex_t> using fftw_number_t = std::conditional_t< xtl::is_complex<regular_or_complex_t>::value, typename fftw_t< xtl::complex_value_type_t<regular_or_complex_t> >::complex, xtl::complex_value_type_t<regular_or_complex_t> >; // short-hand for precision for template arguments template <typename in_or_output_t> using prec_t = xtl::complex_value_type_t<in_or_output_t>; // dimension-dependent function signatures of fftw planning functions template <typename input_t, typename output_t, std::size_t dim, int fftw_direction, bool fftw_123dim> struct fftw_plan_dft_signature {}; template <typename input_t, typename output_t, std::size_t dim> struct fftw_plan_dft_signature<input_t, output_t, dim, 0, false> { using type = typename fftw_t<input_t>::plan (&)(int rank, const int *n, fftw_number_t<input_t> *, fftw_number_t<output_t> *, unsigned int); }; template <typename input_t, typename output_t> struct fftw_plan_dft_signature<input_t, output_t, 1, 0, true> { using type = typename fftw_t<input_t>::plan (&)(int n1, fftw_number_t<input_t> *, fftw_number_t<output_t> *, unsigned int); }; template <typename input_t, typename output_t> struct fftw_plan_dft_signature<input_t, output_t, 2, 0, true> { using type = typename fftw_t<input_t>::plan (&)(int n1, int n2, fftw_number_t<input_t> *, fftw_number_t<output_t> *, unsigned int); }; template <typename input_t, typename output_t> struct fftw_plan_dft_signature<input_t, output_t, 3, 0, true> { using type = typename fftw_t<input_t>::plan (&)(int n1, int n2, int n3, fftw_number_t<input_t> *, fftw_number_t<output_t> *, unsigned int); }; template <typename input_t, typename output_t, std::size_t dim, int fftw_direction> struct fftw_plan_dft_signature<input_t, output_t, dim, fftw_direction, false> { using type = typename fftw_t<input_t>::plan (&)(int rank, const int *n, fftw_number_t<input_t> *, fftw_number_t<output_t> *, int, unsigned int); }; template <typename input_t, typename output_t, int fftw_direction> struct fftw_plan_dft_signature<input_t, output_t, 1, fftw_direction, true> { using type = typename fftw_t<input_t>::plan (&)(int n1, fftw_number_t<input_t> *, fftw_number_t<output_t> *, int, unsigned int); }; template <typename input_t, typename output_t, int fftw_direction> struct fftw_plan_dft_signature<input_t, output_t, 2, fftw_direction, true> { using type = typename fftw_t<input_t>::plan (&)(int n1, int n2, fftw_number_t<input_t> *, fftw_number_t<output_t> *, int, unsigned int); }; template <typename input_t, typename output_t, int fftw_direction> struct fftw_plan_dft_signature<input_t, output_t, 3, fftw_direction, true> { using type = typename fftw_t<input_t>::plan (&)(int n1, int n2, int n3, fftw_number_t<input_t> *, fftw_number_t<output_t> *, int, unsigned int); }; // all_true, from https://stackoverflow.com/a/28253503/1199693 template <bool...> struct bool_pack; template <bool... v> using all_true = std::is_same< bool_pack<true, v...>, bool_pack<v..., true> >; // conditionals for correct combinations of dimensionality parameters namespace dimensional { template <std::size_t dim, bool fftw_123dim> struct is_1 : public std::false_type {}; template <> struct is_1<1, true> : public std::true_type {}; template <std::size_t dim, bool fftw_123dim> struct is_2 : public std::false_type {}; template <> struct is_2<2, true> : public std::true_type {}; template <std::size_t dim, bool fftw_123dim> struct is_3 : public std::false_type {}; template <> struct is_3<3, true> : public std::true_type {}; template <std::size_t dim, bool fftw_123dim> struct is_123 : public std::conditional_t< is_1<dim, fftw_123dim>::value || is_2<dim, fftw_123dim>::value || is_3<dim, fftw_123dim>::value, std::true_type, std::false_type > {}; template <std::size_t dim, bool fftw_123dim> struct is_n : public std::false_type {}; template <std::size_t dim> struct is_n<dim, false> : public std::true_type {}; } // input vs output shape conversion template <typename output_t> inline auto output_shape_from_input(const xt::xarray<output_t, xt::layout_type::row_major>& input, bool half_plus_one_out, bool half_plus_one_in, bool odd_last_dim = false) { auto output_shape = input.shape(); if (half_plus_one_out) { // r2c auto n = output_shape.size(); output_shape[n-1] = output_shape[n-1]/2 + 1; } else if (half_plus_one_in) { // c2r auto n = output_shape.size(); if (!odd_last_dim) { output_shape[n - 1] = (output_shape[n - 1] - 1) * 2; } else { output_shape[n - 1] = (output_shape[n - 1] - 1) * 2 + 1; } } return output_shape; } // output to DFT-dimensions conversion template <typename output_t> inline auto dft_dimensions_from_output(const xt::xarray<output_t, xt::layout_type::row_major>& output, bool half_plus_one_out, bool odd_last_dim = false) { auto dft_dimensions = output.shape(); if (half_plus_one_out) { // r2c auto n = dft_dimensions.size(); if (!odd_last_dim) { dft_dimensions[n - 1] = (dft_dimensions[n - 1] - 1) * 2; } else { dft_dimensions[n - 1] = (dft_dimensions[n - 1] - 1) * 2 + 1; } } return dft_dimensions; } // Callers for fftw_plan_dft, since they have different call signatures and the // way shape information is extracted from xtensor differs for different dimensionalities. // REGULAR FFT N-dim template <std::size_t dim, int fftw_direction, bool fftw_123dim, typename input_t, typename output_t, typename fftw_plan_dft_signature<input_t, output_t, dim, fftw_direction, fftw_123dim>::type fftw_plan_dft, bool half_plus_one_out, bool half_plus_one_in> inline auto fftw_plan_dft_caller(const xt::xarray<input_t, layout_type::row_major> &input, xt::xarray<output_t, layout_type::row_major> &output, unsigned int flags, bool /*odd_last_dim*/ = false) -> std::enable_if_t<dimensional::is_n<dim, fftw_123dim>::value && (fftw_direction != 0), typename fftw_t<input_t>::plan> { using fftw_input_t = fftw_number_t<input_t>; using fftw_output_t = fftw_number_t<output_t>; auto dft_dimensions_unsigned = dft_dimensions_from_output(output, half_plus_one_out); std::vector<int> dft_dimensions; dft_dimensions.reserve(dft_dimensions_unsigned.size()); std::transform(dft_dimensions_unsigned.begin(), dft_dimensions_unsigned.end(), std::back_inserter(dft_dimensions), [&](std::size_t d) { return static_cast<int>(d); }); std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); return fftw_plan_dft(static_cast<int>(dim), dft_dimensions.data(), const_cast<fftw_input_t *>(reinterpret_cast<const fftw_input_t *>(input.data())), reinterpret_cast<fftw_output_t *>(output.data()), fftw_direction, flags); }; // REGULAR FFT 1D template <std::size_t dim, int fftw_direction, bool fftw_123dim, typename input_t, typename output_t, typename fftw_plan_dft_signature<input_t, output_t, dim, fftw_direction, fftw_123dim>::type fftw_plan_dft, bool half_plus_one_out, bool half_plus_one_in> inline auto fftw_plan_dft_caller(const xt::xarray<input_t, layout_type::row_major> &input, xt::xarray<output_t, layout_type::row_major> &output, unsigned int flags, bool /*odd_last_dim*/ = false) -> std::enable_if_t<dimensional::is_1<dim, fftw_123dim>::value && (fftw_direction != 0), typename fftw_t<input_t>::plan> { using fftw_input_t = fftw_number_t<input_t>; using fftw_output_t = fftw_number_t<output_t>; auto dft_dimensions_unsigned = dft_dimensions_from_output(output, half_plus_one_out); std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); return fftw_plan_dft(static_cast<int>(dft_dimensions_unsigned[0]), const_cast<fftw_input_t *>(reinterpret_cast<const fftw_input_t *>(input.data())), reinterpret_cast<fftw_output_t *>(output.data()), fftw_direction, flags); }; // REGULAR FFT 2D template <std::size_t dim, int fftw_direction, bool fftw_123dim, typename input_t, typename output_t, typename fftw_plan_dft_signature<input_t, output_t, dim, fftw_direction, fftw_123dim>::type fftw_plan_dft, bool half_plus_one_out, bool half_plus_one_in> inline auto fftw_plan_dft_caller(const xt::xarray<input_t, layout_type::row_major> &input, xt::xarray<output_t, layout_type::row_major> &output, unsigned int flags, bool /*odd_last_dim*/ = false) -> std::enable_if_t<dimensional::is_2<dim, fftw_123dim>::value && (fftw_direction != 0), typename fftw_t<input_t>::plan> { using fftw_input_t = fftw_number_t<input_t>; using fftw_output_t = fftw_number_t<output_t>; auto dft_dimensions_unsigned = dft_dimensions_from_output(output, half_plus_one_out); std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); return fftw_plan_dft(static_cast<int>(dft_dimensions_unsigned[0]), static_cast<int>(dft_dimensions_unsigned[1]), const_cast<fftw_input_t *>(reinterpret_cast<const fftw_input_t *>(input.data())), reinterpret_cast<fftw_output_t *>(output.data()), fftw_direction, flags); }; // REGULAR FFT 3D template <std::size_t dim, int fftw_direction, bool fftw_123dim, typename input_t, typename output_t, typename fftw_plan_dft_signature<input_t, output_t, dim, fftw_direction, fftw_123dim>::type fftw_plan_dft, bool half_plus_one_out, bool half_plus_one_in> inline auto fftw_plan_dft_caller(const xt::xarray<input_t, layout_type::row_major> &input, xt::xarray<output_t, layout_type::row_major> &output, unsigned int flags, bool /*odd_last_dim*/ = false) -> std::enable_if_t<dimensional::is_3<dim, fftw_123dim>::value && (fftw_direction != 0), typename fftw_t<input_t>::plan> { using fftw_input_t = fftw_number_t<input_t>; using fftw_output_t = fftw_number_t<output_t>; auto dft_dimensions_unsigned = dft_dimensions_from_output(output, half_plus_one_out); std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); return fftw_plan_dft(static_cast<int>(dft_dimensions_unsigned[0]), static_cast<int>(dft_dimensions_unsigned[1]), static_cast<int>(dft_dimensions_unsigned[2]), const_cast<fftw_input_t *>(reinterpret_cast<const fftw_input_t *>(input.data())), reinterpret_cast<fftw_output_t *>(output.data()), fftw_direction, flags); }; // REAL FFT N-dim template <std::size_t dim, int fftw_direction, bool fftw_123dim, typename input_t, typename output_t, typename fftw_plan_dft_signature<input_t, output_t, dim, 0, fftw_123dim>::type fftw_plan_dft, bool half_plus_one_out, bool half_plus_one_in> inline auto fftw_plan_dft_caller(const xt::xarray<input_t, layout_type::row_major> &input, xt::xarray<output_t, layout_type::row_major> &output, unsigned int flags, bool odd_last_dim = false) -> std::enable_if_t<dimensional::is_n<dim, fftw_123dim>::value && (fftw_direction == 0), typename fftw_t<input_t>::plan> { using fftw_input_t = fftw_number_t<input_t>; using fftw_output_t = fftw_number_t<output_t>; auto dft_dimensions_unsigned = dft_dimensions_from_output(output, half_plus_one_out, odd_last_dim); std::vector<int> dft_dimensions; dft_dimensions.reserve(dft_dimensions_unsigned.size()); std::transform(dft_dimensions_unsigned.begin(), dft_dimensions_unsigned.end(), std::back_inserter(dft_dimensions), [&](std::size_t d) { return static_cast<int>(d); }); std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); return fftw_plan_dft(static_cast<int>(dim), dft_dimensions.data(), const_cast<fftw_input_t *>(reinterpret_cast<const fftw_input_t *>(input.data())), reinterpret_cast<fftw_output_t *>(output.data()), flags); }; // REAL FFT 1D template <std::size_t dim, int fftw_direction, bool fftw_123dim, typename input_t, typename output_t, typename fftw_plan_dft_signature<input_t, output_t, dim, 0, fftw_123dim>::type fftw_plan_dft, bool half_plus_one_out, bool half_plus_one_in> inline auto fftw_plan_dft_caller(const xt::xarray<input_t, layout_type::row_major> &input, xt::xarray<output_t, layout_type::row_major> &output, unsigned int flags, bool odd_last_dim = false) -> std::enable_if_t<dimensional::is_1<dim, fftw_123dim>::value && (fftw_direction == 0), typename fftw_t<input_t>::plan> { using fftw_input_t = fftw_number_t<input_t>; using fftw_output_t = fftw_number_t<output_t>; auto dft_dimensions_unsigned = dft_dimensions_from_output(output, half_plus_one_out, odd_last_dim); std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); return fftw_plan_dft(static_cast<int>(dft_dimensions_unsigned[0]), const_cast<fftw_input_t *>(reinterpret_cast<const fftw_input_t *>(input.data())), reinterpret_cast<fftw_output_t *>(output.data()), flags); }; // REAL FFT 2D template <std::size_t dim, int fftw_direction, bool fftw_123dim, typename input_t, typename output_t, typename fftw_plan_dft_signature<input_t, output_t, dim, 0, fftw_123dim>::type fftw_plan_dft, bool half_plus_one_out, bool half_plus_one_in> inline auto fftw_plan_dft_caller(const xt::xarray<input_t, layout_type::row_major> &input, xt::xarray<output_t, layout_type::row_major> &output, unsigned int flags, bool odd_last_dim = false) -> std::enable_if_t<dimensional::is_2<dim, fftw_123dim>::value && (fftw_direction == 0), typename fftw_t<input_t>::plan> { using fftw_input_t = fftw_number_t<input_t>; using fftw_output_t = fftw_number_t<output_t>; auto dft_dimensions_unsigned = dft_dimensions_from_output(output, half_plus_one_out, odd_last_dim); std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); return fftw_plan_dft(static_cast<int>(dft_dimensions_unsigned[0]), static_cast<int>(dft_dimensions_unsigned[1]), const_cast<fftw_input_t *>(reinterpret_cast<const fftw_input_t *>(input.data())), reinterpret_cast<fftw_output_t *>(output.data()), flags); }; // REAL FFT 3D template <std::size_t dim, int fftw_direction, bool fftw_123dim, typename input_t, typename output_t, typename fftw_plan_dft_signature<input_t, output_t, dim, 0, fftw_123dim>::type fftw_plan_dft, bool half_plus_one_out, bool half_plus_one_in> inline auto fftw_plan_dft_caller(const xt::xarray<input_t, layout_type::row_major> &input, xt::xarray<output_t, layout_type::row_major> &output, unsigned int flags, bool odd_last_dim = false) -> std::enable_if_t<dimensional::is_3<dim, fftw_123dim>::value && (fftw_direction == 0), typename fftw_t<input_t>::plan> { using fftw_input_t = fftw_number_t<input_t>; using fftw_output_t = fftw_number_t<output_t>; auto dft_dimensions_unsigned = dft_dimensions_from_output(output, half_plus_one_out, odd_last_dim); std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); return fftw_plan_dft(static_cast<int>(dft_dimensions_unsigned[0]), static_cast<int>(dft_dimensions_unsigned[1]), static_cast<int>(dft_dimensions_unsigned[2]), const_cast<fftw_input_t *>(reinterpret_cast<const fftw_input_t *>(input.data())), reinterpret_cast<fftw_output_t *>(output.data()), flags); }; //// // General: xarray templates //// // template<typename input_t, typename output_t, typename...> // inline xt::xarray<output_t> _fft_ (const xt::xarray<input_t, layout_type::row_major> &input) { // static_assert(sizeof(prec_t<input_t>) == 0, "Only specializations of _fft_ can be used"); // } // // template<typename input_t, typename output_t, typename...> // inline xt::xarray<output_t> _ifft_ (const xt::xarray<input_t, layout_type::row_major> &input) { // static_assert(sizeof(prec_t<input_t>) == 0, "Only specializations of _ifft_ can be used"); // } template < typename input_t, typename output_t, std::size_t dim, int fftw_direction, bool fftw_123dim, bool half_plus_one_out, bool half_plus_one_in, typename fftw_plan_dft_signature<input_t, output_t, dim, fftw_direction, fftw_123dim>::type fftw_plan_dft, void (&fftw_execute)(typename fftw_t<input_t>::plan), void (&fftw_destroy_plan)(typename fftw_t<input_t>::plan), typename = std::enable_if_t< std::is_same< prec_t<input_t>, prec_t<output_t> >::value // input and output precision must be the same && std::is_floating_point< prec_t<input_t> >::value // numbers must be float, double or long double && (dimensional::is_123<dim, fftw_123dim>::value // dimensionality must match fftw_123dim || dimensional::is_n<dim, fftw_123dim>::value) > > inline xt::xarray<output_t> _fft_(const xt::xarray<input_t, layout_type::row_major> &input) { auto output_shape = output_shape_from_input(input, half_plus_one_out, half_plus_one_in, false); xt::xarray<output_t, layout_type::row_major> output(output_shape); bool odd_last_dim = (input.shape()[input.shape().size()-1] % 2 != 0); auto plan = fftw_plan_dft_caller<dim, fftw_direction, fftw_123dim, input_t, output_t, fftw_plan_dft, half_plus_one_out, half_plus_one_in>(input, output, FFTW_ESTIMATE, odd_last_dim); if (plan == nullptr) { XTENSOR_FFTW_THROW(std::runtime_error, "Plan creation returned nullptr. This usually means FFTW cannot create a plan for the given arguments (e.g. a non-destructive multi-dimensional real FFT is impossible in FFTW)."); } fftw_execute(plan); { std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); fftw_destroy_plan(plan); } return output; }; template < typename input_t, typename output_t, std::size_t dim, int fftw_direction, bool fftw_123dim, bool half_plus_one_out, bool half_plus_one_in, typename fftw_plan_dft_signature<input_t, output_t, dim, fftw_direction, fftw_123dim>::type fftw_plan_dft, void (&fftw_execute)(typename fftw_t<input_t>::plan), void (&fftw_destroy_plan)(typename fftw_t<input_t>::plan), typename = std::enable_if_t< std::is_same< prec_t<input_t>, prec_t<output_t> >::value // input and output precision must be the same && std::is_floating_point< prec_t<input_t> >::value // numbers must be float, double or long double && (dimensional::is_123<dim, fftw_123dim>::value // dimensionality must match fftw_123dim || dimensional::is_n<dim, fftw_123dim>::value) > > inline xt::xarray<output_t> _ifft_(const xt::xarray<input_t, layout_type::row_major> &input, bool odd_last_dim = false) { auto output_shape = output_shape_from_input(input, half_plus_one_out, half_plus_one_in, odd_last_dim); xt::xarray<output_t, layout_type::row_major> output(output_shape); auto plan = fftw_plan_dft_caller<dim, fftw_direction, fftw_123dim, input_t, output_t, fftw_plan_dft, half_plus_one_out, half_plus_one_in>(input, output, FFTW_ESTIMATE, odd_last_dim); if (plan == nullptr) { XTENSOR_FFTW_THROW(std::runtime_error, "Plan creation returned nullptr. This usually means FFTW cannot create a plan for the given arguments (e.g. a non-destructive multi-dimensional real FFT is impossible in FFTW)."); } fftw_execute(plan); { std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); fftw_destroy_plan(plan); } auto dft_dimensions = dft_dimensions_from_output(output, half_plus_one_out, odd_last_dim); auto N_dft = static_cast<prec_t<output_t> >(std::accumulate(dft_dimensions.begin(), dft_dimensions.end(), static_cast<size_t>(1u), std::multiplies<size_t>())); return output / N_dft; }; template < typename input_t, typename output_t, std::size_t dim, int fftw_direction, bool fftw_123dim, bool half_plus_one_out, bool half_plus_one_in, typename fftw_plan_dft_signature<input_t, output_t, dim, fftw_direction, fftw_123dim>::type fftw_plan_dft, void (&fftw_execute)(typename fftw_t<input_t>::plan), void (&fftw_destroy_plan)(typename fftw_t<input_t>::plan), typename = std::enable_if_t< std::is_same< prec_t<input_t>, prec_t<output_t> >::value // input and output precision must be the same && std::is_floating_point< prec_t<input_t> >::value // numbers must be float, double or long double && (dimensional::is_123<dim, fftw_123dim>::value // dimensionality must match fftw_123dim || dimensional::is_n<dim, fftw_123dim>::value) > > inline xt::xarray<output_t> _hfft_(const xt::xarray<input_t, layout_type::row_major> &input) { auto output_shape = output_shape_from_input(input, half_plus_one_out, half_plus_one_in); xt::xarray<output_t, layout_type::row_major> output(output_shape); xt::xarray<input_t, layout_type::row_major> input_conj = xt::conj(input); auto plan = fftw_plan_dft_caller<dim, fftw_direction, fftw_123dim, input_t, output_t, fftw_plan_dft, half_plus_one_out, half_plus_one_in>(input_conj, output, FFTW_ESTIMATE); if (plan == nullptr) { XTENSOR_FFTW_THROW(std::runtime_error, "Plan creation returned nullptr. This usually means FFTW cannot create a plan for the given arguments (e.g. a non-destructive multi-dimensional real FFT is impossible in FFTW)."); } fftw_execute(plan); { std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); fftw_destroy_plan(plan); } return output; }; template < typename input_t, typename output_t, std::size_t dim, int fftw_direction, bool fftw_123dim, bool half_plus_one_out, bool half_plus_one_in, typename fftw_plan_dft_signature<input_t, output_t, dim, fftw_direction, fftw_123dim>::type fftw_plan_dft, void (&fftw_execute)(typename fftw_t<input_t>::plan), void (&fftw_destroy_plan)(typename fftw_t<input_t>::plan), typename = std::enable_if_t< std::is_same< prec_t<input_t>, prec_t<output_t> >::value // input and output precision must be the same && std::is_floating_point< prec_t<input_t> >::value // numbers must be float, double or long double && (dimensional::is_123<dim, fftw_123dim>::value // dimensionality must match fftw_123dim || dimensional::is_n<dim, fftw_123dim>::value) > > inline xt::xarray<output_t> _ihfft_(const xt::xarray<input_t, layout_type::row_major> &input) { auto output_shape = output_shape_from_input(input, half_plus_one_out, half_plus_one_in); xt::xarray<output_t, layout_type::row_major> output(output_shape); auto plan = fftw_plan_dft_caller<dim, fftw_direction, fftw_123dim, input_t, output_t, fftw_plan_dft, half_plus_one_out, half_plus_one_in>(input, output, FFTW_ESTIMATE); if (plan == nullptr) { XTENSOR_FFTW_THROW(std::runtime_error, "Plan creation returned nullptr. This usually means FFTW cannot create a plan for the given arguments (e.g. a non-destructive multi-dimensional real FFT is impossible in FFTW)."); } fftw_execute(plan); { std::lock_guard<std::mutex> guard(detail::fftw_global_mutex()); fftw_destroy_plan(plan); } output = xt::conj(output); auto dft_dimensions = dft_dimensions_from_output(output, half_plus_one_out); auto N_dft = static_cast<prec_t<output_t> >(std::accumulate(dft_dimensions.begin(), dft_dimensions.end(), static_cast<size_t>(1u), std::multiplies<size_t>())); return output / N_dft; }; //// // General: xtensor templates //// // template<typename real_t, std::size_t dim, typename fftw_plan_t> // xt::xtensor< std::complex<real_t>, dim > _fft_(const xt::xtensor<real_t, dim> &input) { // static_assert(sizeof(real_t) == 0, "Only specializations of fft can be used"); // // xt::xtensor<std::complex<real_t>, dim> output(input.shape(), input.strides()); // // fftw_plan_t plan = fftwXXXXX_plan_dft_r2c_1d(static_cast<int>(input.size()), // const_cast<real_t *>(input.data()), // reinterpret_cast<fftwXXXXXXX_complex*>(output.data()), // FFTW_ESTIMATE); // // fftwXXXXX_execute(plan); // fftwXXXXX_destroy_plan(plan); // return output; // }; // // template<typename real_t, std::size_t dim, typename fftw_plan_t> // xt::xtensor<real_t, dim> _ifft_(const xt::xtensor< std::complex<real_t>, dim > &input) { // static_assert(sizeof(real_t) == 0, "Only specializations of ifft can be used"); // // xt::xtensor<real_t, dim> output(input.shape(), input.strides()); // // fftw_plan_t plan = fftwXXXXX_plan_dft_c2r_1d(static_cast<int>(input.size()), // const_cast<fftwXXXXX_complex *>(reinterpret_cast<const fftwXXXXX_complex *>(input.data())), // output.data(), // FFTW_ESTIMATE | FFTW_PRESERVE_INPUT); // // fftwXXXXX_execute(plan); // fftwXXXXX_destroy_plan(plan); // return output / output.size(); // }; } //namespace fftw } //namespace xt #endif //XTENSOR_FFTW_COMMON_HPP
55.663462
259
0.680774
michaelbacci
77287d0087ccb1084c8c55c60899596cbf8beb31
2,537
cpp
C++
sdl2/AdventureInSDL2/TtfScene.cpp
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
sdl2/AdventureInSDL2/TtfScene.cpp
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
sdl2/AdventureInSDL2/TtfScene.cpp
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
/* TtfScene.cpp * * Copyright (C) 2013 Michael Imamura * * 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 "Conversation.h" #include "Level.h" #include "LevelDecor.h" #include "PagedTextDecor.h" #include "Player.h" #include "ResStr.h" #include "Sound.h" #include "SpriteMap.h" #include "TtfScene.h" namespace AISDL { TtfScene::TtfScene(Director &director, Display &display) : SUPER(director, display, "SDL_ttf") { } TtfScene::~TtfScene() { } void TtfScene::OnWalkOffEdgeLeft(std::shared_ptr<Player> player) { player->SetPos(511, player->GetPosY()); } void TtfScene::OnWalkOffEdgeRight(std::shared_ptr<Player> player) { player->SetPos(-31, player->GetPosY()); } void TtfScene::OnInteract() { convo->Next(); } void TtfScene::OnAction() { if (!ttfTxt->NextPage(PagedTextDecor::Anim::FLING_UP)) { display.res.doorSound->Play(); director.RequestNextScene(); } } void TtfScene::OnCancel() { ttfTxt->PrevPage(); } void TtfScene::Preload() { SUPER::Preload(); level = Level::Load(display.res.resDir + "/levels/ttf"); levelDecor.reset(new LevelDecor(display, level, display.res.interiorTile)); const std::string dir = display.res.resDir + "/text/ttf/"; ttfTxt.reset(new PagedTextDecor(display, display.res.bodyFont, ResStr::Load(dir + "ttf.txt"), 864)); convo.reset(new Conversation(ResStr::Load(dir + "dialog.txt"))); } void TtfScene::Reload() { SUPER::Reload(); level->Reload(); } void TtfScene::Reset() { SUPER::Reset(); ttfTxt->FirstPage(PagedTextDecor::Anim::FLING_UP); auto player = director.GetMainPlayer(); player->SetPos(40, 320); convo->Start(player); } void TtfScene::Advance(Uint32 lastTick, Uint32 tick) { SUPER::Advance(lastTick, tick); ttfTxt->Advance(tick); } void TtfScene::RenderContent() { SDL_SetRenderDrawColor(display.renderer, 0x00, 0x00, 0x00, 0xff); SDL_RenderClear(display.renderer); display.SetLowRes(); levelDecor->Render(); SUPER::RenderContent(); display.SetHighRes(); ttfTxt->Render(80, 40); } } // namespace AISDL
20.459677
80
0.714229
pdpdds
772bb0aef80fd8f0e86d570c82da8e9e0c2b3faf
18,869
cpp
C++
Game/OGRE/OgreMain/src/OgrePlatformInformation.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/OGRE/OgreMain/src/OgrePlatformInformation.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/OGRE/OgreMain/src/OgrePlatformInformation.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgrePlatformInformation.h" #include "OgreLog.h" #include "OgreStringConverter.h" #if OGRE_COMPILER == OGRE_COMPILER_MSVC #include <excpt.h> // For SEH values #if _MSC_VER >= 1400 #include <intrin.h> #endif #elif OGRE_COMPILER == OGRE_COMPILER_GNUC #include <signal.h> #include <setjmp.h> #endif // Yes, I known, this file looks very ugly, but there hasn't other ways to do it better. namespace Ogre { #if OGRE_CPU == OGRE_CPU_X86 //--------------------------------------------------------------------- // Struct for store CPUID instruction result, compiler-independent //--------------------------------------------------------------------- struct CpuidResult { // Note: DO NOT CHANGE THE ORDER, some code based on that. uint _eax; uint _ebx; uint _edx; uint _ecx; }; //--------------------------------------------------------------------- // Compiler-dependent routines //--------------------------------------------------------------------- #if OGRE_COMPILER == OGRE_COMPILER_MSVC #pragma warning(push) #pragma warning(disable: 4035) // no return value #endif //--------------------------------------------------------------------- // Detect whether CPU supports CPUID instruction, returns non-zero if supported. static int _isSupportCpuid(void) { #if OGRE_COMPILER == OGRE_COMPILER_MSVC // Visual Studio 2005 & 64-bit compilers always supports __cpuid intrinsic // note that even though this is a build rather than runtime setting, all // 64-bit CPUs support this so since binary is 64-bit only we're ok #if _MSC_VER >= 1400 && defined(_M_X64) return true; #else // If we can modify flag register bit 21, the cpu is supports CPUID instruction __asm { // Read EFLAG pushfd pop eax mov ecx, eax // Modify bit 21 xor eax, 0x200000 push eax popfd // Read back EFLAG pushfd pop eax // Restore EFLAG push ecx popfd // Check bit 21 modifiable xor eax, ecx neg eax sbb eax, eax // Return values in eax, no return statment requirement here for VC. } #endif #elif OGRE_COMPILER == OGRE_COMPILER_GNUC unsigned oldFlags, newFlags; __asm__ ( "pushfl \n\t" "pop %0 \n\t" "mov %0, %1 \n\t" "xor %2, %0 \n\t" "push %0 \n\t" "popfl \n\t" "pushfl \n\t" "pop %0 \n\t" "push %1 \n\t" "popfl \n\t" : "=r" (oldFlags), "=r" (newFlags) : "n" (0x200000) ); return oldFlags != newFlags; #else // TODO: Supports other compiler return false; #endif } //--------------------------------------------------------------------- // Performs CPUID instruction with 'query', fill the results, and return value of eax. static uint _performCpuid(int query, CpuidResult& result) { #if OGRE_COMPILER == OGRE_COMPILER_MSVC #if _MSC_VER >= 1400 int CPUInfo[4]; __cpuid(CPUInfo, query); result._eax = CPUInfo[0]; result._ebx = CPUInfo[1]; result._ecx = CPUInfo[2]; result._edx = CPUInfo[3]; return result._eax; #else __asm { mov edi, result mov eax, query cpuid mov [edi]._eax, eax mov [edi]._ebx, ebx mov [edi]._edx, edx mov [edi]._ecx, ecx // Return values in eax, no return statment requirement here for VC. } #endif #elif OGRE_COMPILER == OGRE_COMPILER_GNUC __asm__ ( "pushl %%ebx \n\t" "cpuid \n\t" "movl %%ebx, %%edi \n\t" "popl %%ebx \n\t" : "=a" (result._eax), "=D" (result._ebx), "=c" (result._ecx), "=d" (result._edx) : "a" (query) ); return result._eax; #else // TODO: Supports other compiler return 0; #endif } #if OGRE_COMPILER == OGRE_COMPILER_MSVC #pragma warning(pop) #endif //--------------------------------------------------------------------- // Detect whether or not os support Streaming SIMD Extension. #if OGRE_COMPILER == OGRE_COMPILER_GNUC static jmp_buf sIllegalJmpBuf; static void _illegalHandler(int x) { (void)(x); // Unused longjmp(sIllegalJmpBuf, 1); } #endif static bool _checkOperatingSystemSupportSSE(void) { #if OGRE_COMPILER == OGRE_COMPILER_MSVC /* The FP part of SSE introduces a new architectural state and therefore requires support from the operating system. So even if CPUID indicates support for SSE FP, the application might not be able to use it. If CPUID indicates support for SSE FP, check here whether it is also supported by the OS, and turn off the SSE FP feature bit if there is no OS support for SSE FP. Operating systems that do not support SSE FP return an illegal instruction exception if execution of an SSE FP instruction is performed. Here, a sample SSE FP instruction is executed, and is checked for an exception using the (non-standard) __try/__except mechanism of Microsoft Visual C/C++. */ // Visual Studio 2005, Both AMD and Intel x64 support SSE // note that even though this is a build rather than runtime setting, all // 64-bit CPUs support this so since binary is 64-bit only we're ok #if _MSC_VER >= 1400 && defined(_M_X64) return true; #else __try { __asm orps xmm0, xmm0 return true; } __except(EXCEPTION_EXECUTE_HANDLER) { return false; } #endif #elif OGRE_COMPILER == OGRE_COMPILER_GNUC // Does gcc have __try/__except similar mechanism? // Use signal, setjmp/longjmp instead. void (*oldHandler)(int); oldHandler = signal(SIGILL, _illegalHandler); if (setjmp(sIllegalJmpBuf)) { signal(SIGILL, oldHandler); return false; } else { __asm__ __volatile__ ("orps %xmm0, %xmm0"); signal(SIGILL, oldHandler); return true; } #else // TODO: Supports other compiler, assumed is supported by default return true; #endif } //--------------------------------------------------------------------- // Compiler-independent routines //--------------------------------------------------------------------- static uint queryCpuFeatures(void) { #define CPUID_STD_FPU (1<<0) #define CPUID_STD_TSC (1<<4) #define CPUID_STD_CMOV (1<<15) #define CPUID_STD_MMX (1<<23) #define CPUID_STD_SSE (1<<25) #define CPUID_STD_SSE2 (1<<26) #define CPUID_STD_HTT (1<<28) // EDX[28] - Bit 28 set indicates Hyper-Threading Technology is supported in hardware. #define CPUID_STD_SSE3 (1<<0) // ECX[0] - Bit 0 of standard function 1 indicate SSE3 supported #define CPUID_FAMILY_ID_MASK 0x0F00 // EAX[11:8] - Bit 11 thru 8 contains family processor id #define CPUID_EXT_FAMILY_ID_MASK 0x0F00000 // EAX[23:20] - Bit 23 thru 20 contains extended family processor id #define CPUID_PENTIUM4_ID 0x0F00 // Pentium 4 family processor id #define CPUID_EXT_3DNOW (1<<31) #define CPUID_EXT_AMD_3DNOWEXT (1<<30) #define CPUID_EXT_AMD_MMXEXT (1<<22) uint features = 0; // Supports CPUID instruction ? if (_isSupportCpuid()) { CpuidResult result; // Has standard feature ? if (_performCpuid(0, result)) { // Check vendor strings if (memcmp(&result._ebx, "GenuineIntel", 12) == 0) { if (result._eax > 2) features |= PlatformInformation::CPU_FEATURE_PRO; // Check standard feature _performCpuid(1, result); if (result._edx & CPUID_STD_FPU) features |= PlatformInformation::CPU_FEATURE_FPU; if (result._edx & CPUID_STD_TSC) features |= PlatformInformation::CPU_FEATURE_TSC; if (result._edx & CPUID_STD_CMOV) features |= PlatformInformation::CPU_FEATURE_CMOV; if (result._edx & CPUID_STD_MMX) features |= PlatformInformation::CPU_FEATURE_MMX; if (result._edx & CPUID_STD_SSE) features |= PlatformInformation::CPU_FEATURE_MMXEXT | PlatformInformation::CPU_FEATURE_SSE; if (result._edx & CPUID_STD_SSE2) features |= PlatformInformation::CPU_FEATURE_SSE2; if (result._ecx & CPUID_STD_SSE3) features |= PlatformInformation::CPU_FEATURE_SSE3; // Check to see if this is a Pentium 4 or later processor if ((result._eax & CPUID_EXT_FAMILY_ID_MASK) || (result._eax & CPUID_FAMILY_ID_MASK) == CPUID_PENTIUM4_ID) { // Check hyper-threading technology if (result._edx & CPUID_STD_HTT) features |= PlatformInformation::CPU_FEATURE_HTT; } } else if (memcmp(&result._ebx, "AuthenticAMD", 12) == 0) { features |= PlatformInformation::CPU_FEATURE_PRO; // Check standard feature _performCpuid(1, result); if (result._edx & CPUID_STD_FPU) features |= PlatformInformation::CPU_FEATURE_FPU; if (result._edx & CPUID_STD_TSC) features |= PlatformInformation::CPU_FEATURE_TSC; if (result._edx & CPUID_STD_CMOV) features |= PlatformInformation::CPU_FEATURE_CMOV; if (result._edx & CPUID_STD_MMX) features |= PlatformInformation::CPU_FEATURE_MMX; if (result._edx & CPUID_STD_SSE) features |= PlatformInformation::CPU_FEATURE_SSE; if (result._edx & CPUID_STD_SSE2) features |= PlatformInformation::CPU_FEATURE_SSE2; if (result._ecx & CPUID_STD_SSE3) features |= PlatformInformation::CPU_FEATURE_SSE3; // Has extended feature ? if (_performCpuid(0x80000000, result) > 0x80000000) { // Check extended feature _performCpuid(0x80000001, result); if (result._edx & CPUID_EXT_3DNOW) features |= PlatformInformation::CPU_FEATURE_3DNOW; if (result._edx & CPUID_EXT_AMD_3DNOWEXT) features |= PlatformInformation::CPU_FEATURE_3DNOWEXT; if (result._edx & CPUID_EXT_AMD_MMXEXT) features |= PlatformInformation::CPU_FEATURE_MMXEXT; } } } } return features; } //--------------------------------------------------------------------- static uint _detectCpuFeatures(void) { uint features = queryCpuFeatures(); const uint sse_features = PlatformInformation::CPU_FEATURE_SSE | PlatformInformation::CPU_FEATURE_SSE2 | PlatformInformation::CPU_FEATURE_SSE3; if ((features & sse_features) && !_checkOperatingSystemSupportSSE()) { features &= ~sse_features; } return features; } //--------------------------------------------------------------------- static String _detectCpuIdentifier(void) { // Supports CPUID instruction ? if (_isSupportCpuid()) { CpuidResult result; uint nExIds; char CPUString[0x20]; char CPUBrandString[0x40]; StringUtil::StrStreamType detailedIdentStr; // Has standard feature ? if (_performCpuid(0, result)) { memset(CPUString, 0, sizeof(CPUString)); memset(CPUBrandString, 0, sizeof(CPUBrandString)); *((int*)CPUString) = result._ebx; *((int*)(CPUString+4)) = result._edx; *((int*)(CPUString+8)) = result._ecx; detailedIdentStr << CPUString; // Calling _performCpuid with 0x80000000 as the query argument // gets the number of valid extended IDs. nExIds = _performCpuid(0x80000000, result); for (uint i=0x80000000; i<=nExIds; ++i) { _performCpuid(i, result); // Interpret CPU brand string and cache information. if (i == 0x80000002) { memcpy(CPUBrandString + 0, &result._eax, sizeof(result._eax)); memcpy(CPUBrandString + 4, &result._ebx, sizeof(result._ebx)); memcpy(CPUBrandString + 8, &result._ecx, sizeof(result._ecx)); memcpy(CPUBrandString + 12, &result._edx, sizeof(result._edx)); } else if (i == 0x80000003) { memcpy(CPUBrandString + 16 + 0, &result._eax, sizeof(result._eax)); memcpy(CPUBrandString + 16 + 4, &result._ebx, sizeof(result._ebx)); memcpy(CPUBrandString + 16 + 8, &result._ecx, sizeof(result._ecx)); memcpy(CPUBrandString + 16 + 12, &result._edx, sizeof(result._edx)); } else if (i == 0x80000004) { memcpy(CPUBrandString + 32 + 0, &result._eax, sizeof(result._eax)); memcpy(CPUBrandString + 32 + 4, &result._ebx, sizeof(result._ebx)); memcpy(CPUBrandString + 32 + 8, &result._ecx, sizeof(result._ecx)); memcpy(CPUBrandString + 32 + 12, &result._edx, sizeof(result._edx)); } } String brand(CPUBrandString); StringUtil::trim(brand); if (!brand.empty()) detailedIdentStr << ": " << brand; return detailedIdentStr.str(); } } return "X86"; } #else // OGRE_CPU == OGRE_CPU_X86 //--------------------------------------------------------------------- static uint _detectCpuFeatures(void) { return 0; } //--------------------------------------------------------------------- static String _detectCpuIdentifier(void) { return "Unknown"; } #endif // OGRE_CPU //--------------------------------------------------------------------- // Platform-independent routines, but the returns value are platform-dependent //--------------------------------------------------------------------- const String& PlatformInformation::getCpuIdentifier(void) { static const String sIdentifier = _detectCpuIdentifier(); return sIdentifier; } //--------------------------------------------------------------------- uint PlatformInformation::getCpuFeatures(void) { static const uint sFeatures = _detectCpuFeatures(); return sFeatures; } //--------------------------------------------------------------------- bool PlatformInformation::hasCpuFeature(CpuFeatures feature) { return (getCpuFeatures() & feature) != 0; } //--------------------------------------------------------------------- void PlatformInformation::log(Log* pLog) { pLog->logMessage("CPU Identifier & Features"); pLog->logMessage("-------------------------"); pLog->logMessage( " * CPU ID: " + getCpuIdentifier()); #if OGRE_CPU == OGRE_CPU_X86 if(_isSupportCpuid()) { pLog->logMessage( " * SSE: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_SSE), true)); pLog->logMessage( " * SSE2: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_SSE2), true)); pLog->logMessage( " * SSE3: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_SSE3), true)); pLog->logMessage( " * MMX: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_MMX), true)); pLog->logMessage( " * MMXEXT: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_MMXEXT), true)); pLog->logMessage( " * 3DNOW: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_3DNOW), true)); pLog->logMessage( " * 3DNOWEXT: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_3DNOWEXT), true)); pLog->logMessage( " * CMOV: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_CMOV), true)); pLog->logMessage( " * TSC: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_TSC), true)); pLog->logMessage( " * FPU: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_FPU), true)); pLog->logMessage( " * PRO: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_PRO), true)); pLog->logMessage( " * HT: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_HTT), true)); } #endif pLog->logMessage("-------------------------"); } }
36.009542
135
0.54041
hackerlank
7733435e7143ebda874971007f51e93d338fdac9
1,235
cpp
C++
p1807_1.cpp
Alex-Amber/LuoguAlgorithmProblems
ae8abdb6110badc9faf03af1af42ea562ca1170c
[ "MIT" ]
null
null
null
p1807_1.cpp
Alex-Amber/LuoguAlgorithmProblems
ae8abdb6110badc9faf03af1af42ea562ca1170c
[ "MIT" ]
null
null
null
p1807_1.cpp
Alex-Amber/LuoguAlgorithmProblems
ae8abdb6110badc9faf03af1af42ea562ca1170c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<vector<pair<int, int>>> adj_list; vector<int> ind, dists; int main() { ios::sync_with_stdio(false); cin.tie(0); int N, M, u, v, w; cin >> N >> M; adj_list.assign(N, vector<pair<int, int>>()); ind.assign(N, 0); dists.assign(N, INT_MIN); while (M--) { cin >> u >> v >> w; u--; v--; adj_list[u].push_back(make_pair(v, w)); ind[v]++; } deque<int> dq; for (int i = 0; i < ind.size(); i++) if (!ind[i] && i) dq.push_back(i); while (!dq.empty()) { u = dq.front(); dq.pop_front(); for (auto p: adj_list[u]) { v = p.first; w = p.second; if (!(--ind[v]) && v) dq.push_back(v); } } dq.push_back(0); dists[0] = 0; while (!dq.empty()) { u = dq.front(); dq.pop_front(); for (auto p: adj_list[u]) { v = p.first; w = p.second; dists[v] = max(dists[v], dists[u] + w); if (!(--ind[v])) dq.push_back(v); } } cout << (dists.back() == INT_MIN ? -1 : dists.back()) << "\n"; return 0; }
23.75
66
0.425911
Alex-Amber
77361c500e55c8d5444907c6cb026fbaa6548d79
731
cpp
C++
codeforces/a.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
codeforces/a.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
codeforces/a.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int c[10005], a[10005], n; int main() { long long res = 0LL; scanf("%d", &n); for(int i = 1; i <= n; i++) scanf("%d", &a[i]); for(int i = 1; i <= n; i++) { if(a[i] == 1) { int c = 0; res = 1LL; int pos; for(int j = n; j >= i; j--) { if(a[j] == 1) { pos = j; break; } } for(int j = i + 1; j <= pos; j++) { if(a[j] == 0) { c++; } else { res *= (c + 1); c = 0; } } return cout<<res<<endl,0; } } cout << res << endl; return 0; }
19.756757
50
0.302326
Shisir
774250248eeab8ddf549e55bb77e82c4fb54447b
1,171
cpp
C++
CharChange.cpp
briangreenery/useless-text-editor
3e0bf11a9f833b88a0a69f2e6f564743b2f9e5b3
[ "Unlicense" ]
4
2018-05-17T11:17:26.000Z
2021-12-01T00:48:43.000Z
CharChange.cpp
briangreenery/useless-text-editor
3e0bf11a9f833b88a0a69f2e6f564743b2f9e5b3
[ "Unlicense" ]
null
null
null
CharChange.cpp
briangreenery/useless-text-editor
3e0bf11a9f833b88a0a69f2e6f564743b2f9e5b3
[ "Unlicense" ]
1
2021-05-31T19:08:00.000Z
2021-05-31T19:08:00.000Z
// CharChange.cpp #include "CharChange.h" #include <algorithm> CharChange::CharChange() : m_start( 0 ) , m_end( 0 ) , m_delta( 0 ) { } CharChange::CharChange( size_t start, size_t count, Type type ) { if ( type == kInsertion ) { m_start = start; m_end = start; m_delta = static_cast<int32_t>( count ); } else if ( type == kDeletion ) { m_start = start; m_end = m_start + count; m_delta = -static_cast<int32_t>( count ); } else { m_start = start; m_end = m_start + count; m_delta = 0; } } void CharChange::Add( const CharChange& change ) { if ( m_start == m_end && m_delta == 0 ) { m_start = change.start(); m_end = change.end(); m_delta = change.delta(); } else { size_t changeStart = change.start(); size_t changeEnd = change.end(); if ( changeStart > m_start ) changeStart -= std::min<int32_t>( changeStart - m_start, m_delta ); if ( changeEnd > m_start ) changeEnd -= std::min<int32_t>( changeEnd - m_start, m_delta ); m_start = std::min( start, changeStart ); m_end = std::max( end, changeEnd ); delta += change.delta; } }
19.847458
73
0.590948
briangreenery
7748882f0590b9f2fd1b6e995f06f6b5951591d4
2,211
cpp
C++
ceppengine/src/ceppengine/modules/windows/windowsinputmodule.cpp
Winded/ceppengine
52a9c1723dc45aba4d85d50e4c919ec8016c8d94
[ "MIT" ]
2
2017-11-13T11:29:03.000Z
2017-11-13T12:09:12.000Z
ceppengine/src/ceppengine/modules/windows/windowsinputmodule.cpp
Winded/ceppengine
52a9c1723dc45aba4d85d50e4c919ec8016c8d94
[ "MIT" ]
null
null
null
ceppengine/src/ceppengine/modules/windows/windowsinputmodule.cpp
Winded/ceppengine
52a9c1723dc45aba4d85d50e4c919ec8016c8d94
[ "MIT" ]
null
null
null
#include "windowsinputmodule.h" namespace cepp { WindowsInputModule::WindowsInputModule() : mMouseScrollDelta(0) { mLastMousePos.x = 0; mLastMousePos.y = 0; for(int i = 0; i < 255; i++) { mKeysPressed[i] = false; mKeysDown[i] = false; mKeysReleased[i] = false; } for(int i = 0; i < 3; i++) { mMButtonsPressed[i] = false; mMButtonsDown[i] = false; mMButtonsReleased[i] = false; } } Vector3 WindowsInputModule::mousePosition() const { return mMousePos; } float WindowsInputModule::mouseScrollDelta() const { return mMouseScrollDelta; } bool WindowsInputModule::isKeyPressed(int key) const { return mKeysPressed[key]; } bool WindowsInputModule::isKeyDown(int key) const { return mKeysDown[key]; } bool WindowsInputModule::isKeyReleased(int key) const { return mKeysReleased[key]; } bool WindowsInputModule::isMouseButtonPressed(int key) const { return mMButtonsPressed[key]; } bool WindowsInputModule::isMouseButtonDown(int key) const { return mMButtonsDown[key]; } bool WindowsInputModule::isMouseButtonReleased(int key) const { return mMButtonsReleased[key]; } void WindowsInputModule::updateMousePosition(const POINT &newPoint) { mMousePos = Vector3((float)newPoint.x, (float)newPoint.y, 0); } void WindowsInputModule::updateMouseDelta(float delta) { mMouseScrollDelta = delta; } void WindowsInputModule::setKeyDown(int key) { mKeysPressed[key] = true; mKeysDown[key] = true; } void WindowsInputModule::setKeyUp(int key) { mKeysReleased[key] = true; mKeysDown[key] = false; } void WindowsInputModule::setMouseButtonDown(int button) { mMButtonsPressed[button] = true; mMButtonsDown[button] = true; } void WindowsInputModule::setMouseButtonUp(int button) { mMButtonsReleased[button] = true; mMButtonsDown[button] = false; } void WindowsInputModule::postUpdate(float deltaTime) { mMouseScrollDelta = 0; for(int i = 0; i < 255; i++) { mKeysPressed[i] = false; mKeysReleased[i] = false; } for(int i = 0; i < 3; i++) { mMButtonsPressed[i] = false; mMButtonsReleased[i] = false; } } } // namespace cepp
20.1
67
0.683401
Winded
7748e2a4123bb3f4c95c0fea82b540dff0b2e7a3
554
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR/Cryptography.KeyNumber/cpp/sample.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_CLR/Cryptography.KeyNumber/cpp/sample.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_CLR/Cryptography.KeyNumber/cpp/sample.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
using namespace System; using namespace System::IO; using namespace System::Text; using namespace System::Security::Cryptography; int main() { //<SNIPPET1> // Create a new CspParameters object. CspParameters^ cspParams = gcnew CspParameters(); // Specify an exchange key. cspParams->KeyNumber = (int) KeyNumber::Exchange; // Initialize the RSACryptoServiceProvider // with the CspParameters object. RSACryptoServiceProvider^ RSACSP = gcnew RSACryptoServiceProvider(cspParams); //</SNIPPET1> };
26.380952
82
0.698556
hamarb123
774bf088889c0f77b1479435b754b9e7ab8a73c4
16,784
cpp
C++
Arc/src/Arc/Scene/SceneSerializer.cpp
MohitSethi99/AGE
4291ebeaa4af5b60518bc55eae079fd2cfe55d8f
[ "Apache-2.0" ]
null
null
null
Arc/src/Arc/Scene/SceneSerializer.cpp
MohitSethi99/AGE
4291ebeaa4af5b60518bc55eae079fd2cfe55d8f
[ "Apache-2.0" ]
null
null
null
Arc/src/Arc/Scene/SceneSerializer.cpp
MohitSethi99/AGE
4291ebeaa4af5b60518bc55eae079fd2cfe55d8f
[ "Apache-2.0" ]
null
null
null
#include "arcpch.h" #include "Arc/Scene/SceneSerializer.h" #include "Arc/Scene/Entity.h" #include "Arc/Scene/Components.h" #include <fstream> #include <yaml-cpp/yaml.h> namespace YAML { template<> struct convert<glm::vec2> { static Node encode(const glm::vec2& rhs) { Node node; node.push_back(rhs.x); node.push_back(rhs.y); return node; } static bool decode(const Node& node, glm::vec2& rhs) { if (!node.IsSequence() || node.size() != 2) return false; rhs.x = node[0].as<float>(); rhs.y = node[1].as<float>(); return true; } }; template<> struct convert<glm::vec3> { static Node encode(const glm::vec3& rhs) { Node node; node.push_back(rhs.x); node.push_back(rhs.y); node.push_back(rhs.z); return node; } static bool decode(const Node& node, glm::vec3& rhs) { if (!node.IsSequence() || node.size() != 3) return false; rhs.x = node[0].as<float>(); rhs.y = node[1].as<float>(); rhs.z = node[2].as<float>(); return true; } }; template<> struct convert<glm::vec4> { static Node encode(const glm::vec4& rhs) { Node node; node.push_back(rhs.x); node.push_back(rhs.y); node.push_back(rhs.z); node.push_back(rhs.w); return node; } static bool decode(const Node& node, glm::vec4& rhs) { if (!node.IsSequence() || node.size() != 4) return false; rhs.x = node[0].as<float>(); rhs.y = node[1].as<float>(); rhs.z = node[2].as<float>(); rhs.w = node[3].as<float>(); return true; } }; } namespace ArcEngine { YAML::Emitter& operator<<(YAML::Emitter& out, const glm::vec2& v) { out << YAML::Flow; out << YAML::BeginSeq << v.x << v.y << YAML::EndSeq; return out; } YAML::Emitter& operator<<(YAML::Emitter& out, const glm::vec3& v) { out << YAML::Flow; out << YAML::BeginSeq << v.x << v.y << v.z << YAML::EndSeq; return out; } YAML::Emitter& operator<<(YAML::Emitter& out, const glm::vec4& v) { out << YAML::Flow; out << YAML::BeginSeq << v.x << v.y << v.z << v.w << YAML::EndSeq; return out; } SceneSerializer::SceneSerializer(const Ref<Scene>& scene) : m_Scene(scene) { } static void SerializeEntity(YAML::Emitter& out, Entity entity) { ARC_CORE_ASSERT(entity.HasComponent<IDComponent>()); out << YAML::BeginMap; // Entity out << YAML::Key << "Entity" << YAML::Value << entity.GetUUID(); if (entity.HasComponent<TagComponent>()) { out << YAML::Key << "TagComponent"; out << YAML::BeginMap; // TagComponent auto& tag = entity.GetComponent<TagComponent>().Tag; out << YAML::Key << "Tag" << YAML::Value << tag.c_str(); out << YAML::EndMap; // TagComponent } if (entity.HasComponent<TransformComponent>()) { out << YAML::Key << "TransformComponent"; out << YAML::BeginMap; // TransformComponent auto& tc = entity.GetComponent<TransformComponent>(); out << YAML::Key << "Translation" << YAML::Value << tc.Translation; out << YAML::Key << "Rotation" << YAML::Value << tc.Rotation; out << YAML::Key << "Scale" << YAML::Value << tc.Scale; out << YAML::EndMap; // TransformComponent } if (entity.HasComponent<RelationshipComponent>()) { out << YAML::Key << "RelationshipComponent"; out << YAML::BeginMap; // RelationshipComponent auto& tc = entity.GetComponent<RelationshipComponent>(); out << YAML::Key << "Parent" << YAML::Value << tc.Parent; out << YAML::Key << "ChildrenCount" << YAML::Value << tc.Children.size(); out << YAML::Key << "Children"; out << YAML::BeginMap; // Children for (size_t i = 0; i < tc.Children.size(); i++) out << YAML::Key << i << YAML::Value << tc.Children[i]; out << YAML::EndMap; // Children out << YAML::EndMap; // RelationshipComponent } if (entity.HasComponent<CameraComponent>()) { out << YAML::Key << "CameraComponent"; out << YAML::BeginMap; // CameraComponent auto& cameraComponent = entity.GetComponent<CameraComponent>(); auto& camera = cameraComponent.Camera; out << YAML::Key << "Camera" << YAML::Value; out << YAML::BeginMap; // Camera out << YAML::Key << "ProjectionType" << YAML::Value << (int)camera.GetProjectionType(); out << YAML::Key << "PerspectiveFOV" << YAML::Value << camera.GetPerspectiveVerticalFOV(); out << YAML::Key << "PerspectiveNear" << YAML::Value << camera.GetPerspectiveNearClip(); out << YAML::Key << "PerspectiveFar" << YAML::Value << camera.GetPerspectiveFarClip(); out << YAML::Key << "OrthographicSize" << YAML::Value << camera.GetOrthographicSize(); out << YAML::Key << "OrthographicNear" << YAML::Value << camera.GetOrthographicNearClip(); out << YAML::Key << "OrthographicFar" << YAML::Value << camera.GetOrthographicFarClip(); out << YAML::EndMap; // Camera out << YAML::Key << "Primary" << YAML::Value << cameraComponent.Primary; out << YAML::Key << "FixedAspectRatio" << YAML::Value << cameraComponent.FixedAspectRatio; out << YAML::EndMap; // CameraComponent } if (entity.HasComponent<SpriteRendererComponent>()) { out << YAML::Key << "SpriteRendererComponent"; out << YAML::BeginMap; // SpriteRendererComponent auto& spriteRendererComponent = entity.GetComponent<SpriteRendererComponent>(); out << YAML::Key << "Color" << YAML::Value << spriteRendererComponent.Color; out << YAML::Key << "TextureFilepath" << YAML::Value << spriteRendererComponent.TextureFilepath.c_str(); out << YAML::Key << "TilingFactor" << YAML::Value << spriteRendererComponent.TilingFactor; out << YAML::EndMap; // SpriteRendererComponent } if (entity.HasComponent<SkyLightComponent>()) { out << YAML::Key << "SkyLightComponent"; out << YAML::BeginMap; // MeshComponent auto& skyLightComponent = entity.GetComponent<SkyLightComponent>(); out << YAML::Key << "TextureFilepath" << YAML::Value << (skyLightComponent.Texture ? skyLightComponent.Texture->GetPath().c_str() : ""); out << YAML::Key << "Intensity" << YAML::Value << skyLightComponent.Intensity; out << YAML::EndMap; // SkyLightComponent } if (entity.HasComponent<LightComponent>()) { out << YAML::Key << "LightComponent"; out << YAML::BeginMap; // LightComponent auto& lightComponent = entity.GetComponent<LightComponent>(); out << YAML::Key << "Type" << YAML::Value << (int) lightComponent.Type; out << YAML::Key << "Color" << YAML::Value << lightComponent.Color; out << YAML::Key << "Intensity" << YAML::Value << lightComponent.Intensity; out << YAML::Key << "Radius" << YAML::Value << lightComponent.Range; out << YAML::Key << "CutOffAngle" << YAML::Value << lightComponent.CutOffAngle; out << YAML::Key << "OuterCutOffAngle" << YAML::Value << lightComponent.OuterCutOffAngle; out << YAML::EndMap; // LightComponent } if (entity.HasComponent<Rigidbody2DComponent>()) { out << YAML::Key << "Rigidbody2DComponent"; out << YAML::BeginMap; // Rigidbody2DComponent auto& rb2d = entity.GetComponent<Rigidbody2DComponent>(); out << YAML::Key << "Type" << YAML::Value << (int) rb2d.Type; out << YAML::Key << "AutoMass" << YAML::Value << rb2d.AutoMass; out << YAML::Key << "Mass" << YAML::Value << rb2d.Mass; out << YAML::Key << "LinearDrag" << YAML::Value << rb2d.LinearDrag; out << YAML::Key << "AngularDrag" << YAML::Value << rb2d.AngularDrag; out << YAML::Key << "AllowSleep" << YAML::Value << rb2d.AllowSleep; out << YAML::Key << "Awake" << YAML::Value << rb2d.Awake; out << YAML::Key << "Continuous" << YAML::Value << rb2d.Continuous; out << YAML::Key << "FreezeRotation" << YAML::Value << rb2d.FreezeRotation; out << YAML::Key << "GravityScale" << YAML::Value << rb2d.GravityScale; out << YAML::EndMap; // Rigidbody2DComponent } if (entity.HasComponent<BoxCollider2DComponent>()) { out << YAML::Key << "BoxCollider2DComponent"; out << YAML::BeginMap; // BoxCollider2DComponent auto& bc2d = entity.GetComponent<BoxCollider2DComponent>(); out << YAML::Key << "Size" << YAML::Value << bc2d.Size; out << YAML::Key << "Offset" << YAML::Value << bc2d.Offset; out << YAML::Key << "Density" << YAML::Value << bc2d.Density; out << YAML::Key << "Friction" << YAML::Value << bc2d.Friction; out << YAML::Key << "Restitution" << YAML::Value << bc2d.Restitution; out << YAML::Key << "RestitutionThreshold" << YAML::Value << bc2d.RestitutionThreshold; out << YAML::EndMap; // BoxCollider2DComponent } if (entity.HasComponent<CircleCollider2DComponent>()) { out << YAML::Key << "CircleCollider2DComponent"; out << YAML::BeginMap; // CircleCollider2DComponent auto& cc2d = entity.GetComponent<CircleCollider2DComponent>(); out << YAML::Key << "Radius" << YAML::Value << cc2d.Radius; out << YAML::Key << "Offset" << YAML::Value << cc2d.Offset; out << YAML::Key << "Density" << YAML::Value << cc2d.Density; out << YAML::Key << "Friction" << YAML::Value << cc2d.Friction; out << YAML::Key << "Restitution" << YAML::Value << cc2d.Restitution; out << YAML::Key << "RestitutionThreshold" << YAML::Value << cc2d.RestitutionThreshold; out << YAML::EndMap; // CircleCollider2DComponent } out << YAML::EndMap; // Entity } void SceneSerializer::Serialize(const eastl::string& filepath) { YAML::Emitter out; out << YAML::BeginMap; out << YAML::Key << "Scene" << YAML::Value << "Untitled"; out << YAML::Key << "Entities" << YAML::Value << YAML::BeginSeq; m_Scene->m_Registry.each([&](auto entityID) { Entity entity = { entityID, m_Scene.get() }; if (!entity) return; SerializeEntity(out, entity); }); out << YAML::EndSeq; out << YAML::EndMap; std::ofstream fout(filepath.c_str()); fout << out.c_str(); } void SceneSerializer::SerializeRuntime(const eastl::string& filepath) { // Not implemented ARC_CORE_ASSERT(false); } #define TryGet(x, outType, defValue) ((x) ? x.as<outType>() : defValue) bool SceneSerializer::Deserialize(const eastl::string& filepath) { std::ifstream stream(filepath.c_str()); std::stringstream strStream; strStream << stream.rdbuf(); YAML::Node data = YAML::Load(strStream.str()); if (!data["Scene"]) return false; eastl::string sceneName = data["Scene"].as<std::string>().c_str(); ARC_CORE_TRACE("Deserializing scene '{0}'", sceneName); auto entities = data["Entities"]; if (entities) { for (auto entity : entities) { uint64_t uuid = entity["Entity"].as<uint64_t>(); eastl::string name; auto tagComponent = entity["TagComponent"]; if (tagComponent) name = tagComponent["Tag"].as<std::string>().c_str(); ARC_CORE_TRACE("Deserialized entity with ID = {0}, name = {1}", uuid, name); Entity deserializedEntity = m_Scene->CreateEntityWithUUID(uuid, name); auto transformComponent = entity["TransformComponent"]; if (transformComponent) { // Entities always have transforms auto& tc = deserializedEntity.GetComponent<TransformComponent>(); tc.Translation = transformComponent["Translation"].as<glm::vec3>(); tc.Rotation = transformComponent["Rotation"].as<glm::vec3>(); tc.Scale = transformComponent["Scale"].as<glm::vec3>(); } auto relationshipComponent = entity["RelationshipComponent"]; if (relationshipComponent) { // Entities always have transforms auto& tc = deserializedEntity.GetComponent<RelationshipComponent>(); tc.Parent = relationshipComponent["Parent"].as<uint64_t>(); size_t childCount = relationshipComponent["ChildrenCount"].as<size_t>(); tc.Children.clear(); tc.Children.reserve(childCount); auto children = relationshipComponent["Children"]; if (children && childCount > 0) { for (size_t i = 0; i < childCount; i++) tc.Children.push_back(children[i].as<uint64_t>()); } } auto cameraComponent = entity["CameraComponent"]; if (cameraComponent) { auto& cc = deserializedEntity.AddComponent<CameraComponent>(); auto& cameraProps = cameraComponent["Camera"]; cc.Camera.SetViewportSize(1, 1); cc.Camera.SetProjectionType((SceneCamera::ProjectionType)TryGet(cameraProps["ProjectionType"], int, 0)); cc.Camera.SetPerspectiveVerticalFOV(TryGet(cameraProps["PerspectiveFOV"], float, 45.0f)); cc.Camera.SetPerspectiveNearClip(TryGet(cameraProps["PerspectiveNear"], float, 0.03f)); cc.Camera.SetPerspectiveFarClip(TryGet(cameraProps["PerspectiveFar"], float, 1000.0f)); cc.Camera.SetOrthographicSize(TryGet(cameraProps["OrthographicSize"], float, 10.0f)); cc.Camera.SetOrthographicNearClip(TryGet(cameraProps["OrthographicNear"], float, -1.0f)); cc.Camera.SetOrthographicFarClip(TryGet(cameraProps["OrthographicFar"], float, 1.0f)); cc.Primary = TryGet(cameraComponent["Primary"], bool, true); cc.FixedAspectRatio = TryGet(cameraComponent["FixedAspectRatio"], bool, false); } auto spriteRendererComponent = entity["SpriteRendererComponent"]; if (spriteRendererComponent) { auto& src = deserializedEntity.AddComponent<SpriteRendererComponent>(); src.Color = TryGet(spriteRendererComponent["Color"], glm::vec4, glm::vec4(1.0f)); eastl::string textureFilepath = TryGet(spriteRendererComponent["TextureFilepath"], std::string, "").c_str(); if(!textureFilepath.empty()) src.SetTexture(textureFilepath); src.TilingFactor = TryGet(spriteRendererComponent["TilingFactor"], float, 1.0f); } auto skyLightComponent = entity["SkyLightComponent"]; if (skyLightComponent) { auto& src = deserializedEntity.AddComponent<SkyLightComponent>(); eastl::string textureFilepath = TryGet(skyLightComponent["TextureFilepath"], std::string, "").c_str(); if(!textureFilepath.empty()) src.SetTexture(textureFilepath); src.Intensity = TryGet(skyLightComponent["Intensity"], float, 1.0f); } auto lightComponent = entity["LightComponent"]; if (lightComponent) { auto& src = deserializedEntity.AddComponent<LightComponent>(); src.Type = (LightComponent::LightType) TryGet(lightComponent["Type"], int, 1); src.Color = TryGet(lightComponent["Color"], glm::vec3, glm::vec3(1.0f)); src.Intensity = TryGet(lightComponent["Intensity"], float, 10.0f); src.Range = TryGet(lightComponent["Radius"], float, 1.0f); src.CutOffAngle = TryGet(lightComponent["CutOffAngle"], float, 12.5f); src.OuterCutOffAngle = TryGet(lightComponent["OuterCutOffAngle"], float, 17.5f); } auto rb2dCpmponent = entity["Rigidbody2DComponent"]; if (rb2dCpmponent) { auto& src = deserializedEntity.AddComponent<Rigidbody2DComponent>(); src.Type = (Rigidbody2DComponent::BodyType) TryGet(rb2dCpmponent["Type"], int, 0); src.AutoMass = TryGet(rb2dCpmponent["AutoMass"], bool, true); src.Mass = TryGet(rb2dCpmponent["Mass"], float, 1.0f); src.LinearDrag = TryGet(rb2dCpmponent["LinearDrag"], float, 0.0f); src.AngularDrag = TryGet(rb2dCpmponent["AngularDrag"], float, 0.05f); src.AllowSleep = TryGet(rb2dCpmponent["AllowSleep"], bool, true); src.Awake = TryGet(rb2dCpmponent["Awake"], bool, true); src.Continuous = TryGet(rb2dCpmponent["Continuous"], bool, false); src.FreezeRotation = TryGet(rb2dCpmponent["FreezeRotation"], bool, false); src.GravityScale = TryGet(rb2dCpmponent["GravityScale"], float, 1.0f); } auto bc2dCpmponent = entity["BoxCollider2DComponent"]; if (bc2dCpmponent) { auto& src = deserializedEntity.AddComponent<BoxCollider2DComponent>(); src.Size = TryGet(bc2dCpmponent["Size"], glm::vec2, glm::vec2(0.5f)); src.Offset = TryGet(bc2dCpmponent["Offset"], glm::vec2, glm::vec2(0.0f)); src.Density = TryGet(bc2dCpmponent["Density"], float, 1.0f); src.Friction = TryGet(bc2dCpmponent["Friction"], float, 0.5f); src.Restitution = TryGet(bc2dCpmponent["Restitution"], float, 0.0f); src.RestitutionThreshold = TryGet(bc2dCpmponent["RestitutionThreshold"], float, 0.5f); } auto cc2dCpmponent = entity["CircleCollider2DComponent"]; if (cc2dCpmponent) { auto& src = deserializedEntity.AddComponent<CircleCollider2DComponent>(); src.Radius = TryGet(cc2dCpmponent["Radius"], float, 0.5f); src.Offset = TryGet(cc2dCpmponent["Offset"], glm::vec2, glm::vec2(0.0f)); src.Density = TryGet(cc2dCpmponent["Density"], float, 1.0f); src.Friction = TryGet(cc2dCpmponent["Friction"], float, 0.5f); src.Restitution = TryGet(cc2dCpmponent["Restitution"], float, 0.0f); src.RestitutionThreshold = TryGet(cc2dCpmponent["RestitutionThreshold"], float, 0.5f); } } } return true; } bool SceneSerializer::DeserializeRuntime(const eastl::string& filepath) { // Not implemented ARC_CORE_ASSERT(false); return false; } }
35.260504
139
0.65908
MohitSethi99
775d46e07c109be26bf81f1dfbb3b3d5529d49fc
398
cpp
C++
06_files_and_io/dll_path_example/main.cpp
Man-Ji/cmake_examples
ba715bdbb6e0e0eb97e37a09f351d9cae1b8da01
[ "MIT" ]
1
2022-02-27T17:38:31.000Z
2022-02-27T17:38:31.000Z
06_files_and_io/dll_path_example/main.cpp
Man-Ji/cmake_examples
ba715bdbb6e0e0eb97e37a09f351d9cae1b8da01
[ "MIT" ]
null
null
null
06_files_and_io/dll_path_example/main.cpp
Man-Ji/cmake_examples
ba715bdbb6e0e0eb97e37a09f351d9cae1b8da01
[ "MIT" ]
null
null
null
#include <GL/freeglut.h> void display() { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glFlush(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutCreateWindow("Simple"); glutDisplayFunc(display); glutMainLoop(); return 0; }
22.111111
34
0.605528
Man-Ji
7760b2b67ebac92d345c3ceb38a0807d21f042be
1,843
cpp
C++
canny_transform/src/CannyTransform.cpp
facontidavide/Exercise_2
b56e432badb2494433c9f3d735483cdc0c99c046
[ "MIT" ]
null
null
null
canny_transform/src/CannyTransform.cpp
facontidavide/Exercise_2
b56e432badb2494433c9f3d735483cdc0c99c046
[ "MIT" ]
null
null
null
canny_transform/src/CannyTransform.cpp
facontidavide/Exercise_2
b56e432badb2494433c9f3d735483cdc0c99c046
[ "MIT" ]
null
null
null
#include <canny_transform/CannyTransform.hpp> const char* WINDOW_NAME = "EdgeDetection"; //#define DEBUG_WINDOW ImageCannyConverter::ImageCannyConverter(ros::NodeHandle& nodehanle) : nh_(nodehanle), it_(nodehanle), low_threshold_(30) { // Subscribe to input video feed and publish output video feed image_sub_ = it_.subscribe("/cv_camera/image_raw", 1, &ImageCannyConverter::imageCallback, this); image_pub_ = it_.advertise("/canny_converter/output_video", 1); // if present, use the ros parameter, otherwise the default value nh_.getParam("/canny_transform_low_threshold", low_threshold_); #ifdef DEBUG_WINDOW cv::namedWindow( WINDOW_NAME ); #endif } ImageCannyConverter::~ImageCannyConverter() { #ifdef DEBUG_WINDOW cv::destroyWindow( WINDOW_NAME ); #endif } void ImageCannyConverter::imageCallback(const sensor_msgs::ImageConstPtr& msg) { using namespace cv; cv_bridge::CvImagePtr image_ptr; cv::Mat image_gray; //NOTE: you might want to make these parameters configurable an NOT //hardcoded. To do that you can use either a rosparam or command line arguments. const int KERNEL_SIZE = 3; const int RATIO = 3; try { image_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } cvtColor( image_ptr->image, image_gray, COLOR_BGR2GRAY ); blur( image_gray, image_gray, Size(3,3) ); Canny( image_gray, image_ptr->image, low_threshold_, low_threshold_*RATIO, KERNEL_SIZE ); image_ptr->encoding = sensor_msgs::image_encodings::MONO8; #ifdef DEBUG_WINDOW imshow( WINDOW_NAME, image_ptr->image ); waitKey(3); #endif image_pub_.publish(image_ptr->toImageMsg()); }
26.710145
93
0.705914
facontidavide
77629daf528a8be25ea3c4cbca692556cabf4d38
8,241
cpp
C++
algo/src/algo_sort.cpp
alex011235/algo
ce36c2673e037a12278117cb036550bee82ecadf
[ "MIT" ]
2
2015-08-16T23:45:23.000Z
2015-10-13T08:12:00.000Z
algo/src/algo_sort.cpp
alex011235/algorithm
ce36c2673e037a12278117cb036550bee82ecadf
[ "MIT" ]
1
2021-03-21T16:33:53.000Z
2021-03-21T16:33:53.000Z
algo/src/algo_sort.cpp
alex011235/algo
ce36c2673e037a12278117cb036550bee82ecadf
[ "MIT" ]
null
null
null
/// /// \brief Source file for sort algorithms. /// \author alex011235 /// \link <a href=https://github.com/alex011235/algo>Algo, Github</a> /// #include "algo_sort.hpp" #include <algorithm> #include <cmath> #include <list> namespace algo::sort { ///////////////////////////////////////////// /// Bubble-sort ///////////////////////////////////////////// template<typename T> void Bubble(std::vector<T>& vec) { if (vec.empty()) { return; } size_t n{vec.size()}; for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < n - 1; j++) { if (vec[j] > vec[j + 1]) { std::swap(vec[j], vec[j + 1]); } } } } // Defines what types may be used for Bubble-sort. template void Bubble<unsigned>(std::vector<unsigned>& vec); template void Bubble<signed>(std::vector<signed>& vec); template void Bubble<double>(std::vector<double>& vec); template void Bubble<std::string>(std::vector<std::string>& vec); ///////////////////////////////////////////// /// Bucket-sort ///////////////////////////////////////////// template<typename T> void Bucket(std::vector<T>& vec) { if (vec.empty()) { return; } if (std::any_of(vec.begin(), vec.end(), [](T t) { return t < 0; })) { return; } auto max_elem_ptr = std::max_element(vec.begin(), vec.end()); int nbrOfBuckets{static_cast<int>(sqrt(*max_elem_ptr))}; std::vector<std::vector<T>> buckets(nbrOfBuckets + 1); // Put in buckets for (const T& x : vec) { buckets[static_cast<T>(sqrt(x))].push_back(x); } // Put back elements int count{0}; for (const std::vector<T>& bucket : buckets) { for (T e : bucket) { vec[count++] = e; } } // Insertion sort (Bentley 1993) for (size_t i = 1; i < vec.size(); i++) { for (size_t j = i; j > 0 && vec[j - 1] > vec[j]; j--) std::swap(vec[j], vec[j - 1]); } } // Defines what types may be used for Bucket-sort. template void Bucket<unsigned>(std::vector<unsigned>& vec); template void Bucket<int>(std::vector<int>& vec); template void Bucket<double>(std::vector<double>& vec); ///////////////////////////////////////////// /// Gnome-sort ///////////////////////////////////////////// template<typename T> void Gnome(std::vector<T>& vec) { int i{0}; size_t n{vec.size()}; while (static_cast<size_t>(i) < n) { if (i == 0) i++; if (vec[i] >= vec[i - 1]) i++; else { std::swap(vec[i], vec[i - 1]); i--; } } } // Defines what types may be used for Gnome-sort. template void Gnome<unsigned>(std::vector<unsigned>& vec); template void Gnome<int>(std::vector<int>& vec); template void Gnome<double>(std::vector<double>& vec); template void Gnome<std::string>(std::vector<std::string>& vec); ///////////////////////////////////////////// /// Heap-sort ///////////////////////////////////////////// /// \brief Sift-down operation for binary heaps. Puts new elements to the appropriate indices. /// \tparam T Type in vector. /// \param vec the vector to arrange the elements. /// \param start The starting position. /// \param len The length. /// \link <a href=https://en.wikipedia.org/wiki/Binary_heap#Extract>SiftDown, Wikipedia.</> template<typename T> void Siftdown(std::vector<T>& vec, int start, int len) { int root{start}; while (root * 2 + 1 <= len) { int child{root * 2 + 1}; int swap{root}; if (vec[swap] < vec[child]) { swap = child; } if (child + 1 <= len && vec[swap] < vec[child + 1]) { swap = child + 1; } if (swap == root) { return; } else { T t{vec[root]}; vec[root] = vec[swap]; vec[swap] = t; root = swap; } } } /// \brief Builds the heap vector, largest value at the root. /// \tparam T Type in vector. /// \param vec The vector to heapify. /// \param len Number of elements. template<typename T> void Heapify(std::vector<T>& vec, size_t len) { int start = floor((len - 2.0) / 2.0); while (start >= 0) { Siftdown(vec, start, len - 1); start--; } } /// \brief Internal function for the Heapsort algorithm. /// \tparam T Type in vector. /// \param vec The vector to be sorted. /// \param len Number of elements. template<typename T> void HeapSortPriv(std::vector<T>& vec, size_t len) { Heapify(vec, len); size_t end{len - 1}; while (end > 0) { std::swap(vec[end], vec[0]); end--; Siftdown(vec, 0, end); } } template<typename T> void Heap(std::vector<T>& vec) { if (vec.empty()) { return; } HeapSortPriv(vec, vec.size()); } // Defines what types may be used for Heap-sort. template void Heap<unsigned>(std::vector<unsigned>& vec); template void Heap<int>(std::vector<int>& vec); template void Heap<double>(std::vector<double>& vec); template void Heap<std::string>(std::vector<std::string>& vec); ///////////////////////////////////////////// /// Insertion-sort ///////////////////////////////////////////// template<typename T> void Insertion(std::vector<T>& vec) { if (vec.empty()) { return; } size_t N{vec.size()}; for (size_t i = 0; i < N; i++) { for (size_t j = i; j > 0 && vec[j - 1] > vec[j]; j--) std::swap(vec[j], vec[j - 1]); } } // Defines what types may be used for Insertion-sort. template void Insertion<unsigned>(std::vector<unsigned>& vec); template void Insertion<int>(std::vector<int>& vec); template void Insertion<double>(std::vector<double>& vec); template void Insertion<std::string>(std::vector<std::string>& vec); ///////////////////////////////////////////// /// Merge-sort ///////////////////////////////////////////// /// \brief Merge step. /// \tparam T Type in lists. /// \param A First list. /// \param B Second list. /// \return A sorted and merged vector. template<typename T> std::vector<T> merge(std::list<T>& A, std::list<T>& B) { std::vector<T> C; while (!A.empty() && !B.empty()) { if (A.front() > B.front()) { C.push_back(B.front()); B.pop_front(); } else { C.push_back(A.front()); A.pop_front(); } } while (!A.empty()) { C.push_back(A.front()); A.pop_front(); } while (!B.empty()) { C.push_back(B.front()); B.pop_front(); } return C; } template<typename T> std::vector<T> MergeSortPriv(const std::vector<T>& lst) { if (lst.empty()) { return lst; } size_t n{lst.size()}; // Base case if (n == 1) { return lst; } size_t half{n / 2}; std::vector<T> A, B; for (auto it = lst.begin(); it != (lst.begin() + half); ++it) { A.push_back(*it); } for (auto it = (lst.begin() + half); it != lst.end(); ++it) { B.push_back(*it); } A = MergeSortPriv(A); B = MergeSortPriv(B); std::list<T> Al(A.size()), Bl(B.size()); std::copy(A.begin(), A.end(), Al.begin()); std::copy(B.begin(), B.end(), Bl.begin()); return merge(Al, Bl); } template<typename T> void Merge(std::vector<T>& lst) { lst = MergeSortPriv(lst); } // Defines what types may be used for Merge-sort. template void Merge<unsigned>(std::vector<unsigned>& vec); template void Merge<int>(std::vector<int>& vec); template void Merge<double>(std::vector<double>& vec); template void Merge<std::string>(std::vector<std::string>& vec); ///////////////////////////////////////////// /// Quick-sort ///////////////////////////////////////////// template<typename T> int Partition(std::vector<T>& vec, int low, int high) { T x{vec[high]}; int i{low - 1}; for (int j = low; j != high; j++) { if (vec[j] <= x) { i++; std::swap(vec[j], vec[i]); } } std::swap(vec[i + 1], vec[high]); return i + 1; } // Start of the Quicksort algorithm template<typename T> void QuickSort(std::vector<T>& vec, int low, int high) { if (low < high) { int pivot{Partition(vec, low, high)}; QuickSort(vec, low, pivot - 1); QuickSort(vec, pivot + 1, high); } } template<typename T> void Quick(std::vector<T>& vec) { if (vec.empty()) { return; } QuickSort(vec, 0, vec.size() - 1); } // Defines what types may be used for Quick-sort. template void Quick<unsigned>(std::vector<unsigned>& vec); template void Quick<int>(std::vector<int>& vec); template void Quick<double>(std::vector<double>& vec); template void Quick<std::string>(std::vector<std::string>& vec); }// namespace algo::sort
23.545714
94
0.55685
alex011235
77664a641fb849526e079eba88c558d70f86b4fd
241
cpp
C++
inclusion exclusion principle/01_divisible_by_A_or_B.cpp
omkarugale7/cpp
21717ce36a4f0d88e850e8b7205470f812ca1d58
[ "MIT" ]
1
2022-02-23T17:27:42.000Z
2022-02-23T17:27:42.000Z
inclusion exclusion principle/01_divisible_by_A_or_B.cpp
omkarugale7/cpp
21717ce36a4f0d88e850e8b7205470f812ca1d58
[ "MIT" ]
null
null
null
inclusion exclusion principle/01_divisible_by_A_or_B.cpp
omkarugale7/cpp
21717ce36a4f0d88e850e8b7205470f812ca1d58
[ "MIT" ]
null
null
null
//divisible by A or B under n #include <iostream> using namespace std; int main() { int a, b, c; cin >> a >> b >> c; int an = c / a; int bn = c / b; int ex = c / (a * b); cout << an + bn - ex << endl; return 0; }
17.214286
33
0.477178
omkarugale7
776e0cc3896268c22e56f0a80e187d4dad3130fe
12,123
hpp
C++
include/simple_web_game_server/matchmaking_server.hpp
permutationlock/catacrawl
433c4fa2c48f959691ab8573fdab4c2190bb9422
[ "MIT" ]
6
2021-04-28T21:25:06.000Z
2022-01-23T21:57:28.000Z
include/simple_web_game_server/matchmaking_server.hpp
permutationlock/catacrawl
433c4fa2c48f959691ab8573fdab4c2190bb9422
[ "MIT" ]
null
null
null
include/simple_web_game_server/matchmaking_server.hpp
permutationlock/catacrawl
433c4fa2c48f959691ab8573fdab4c2190bb9422
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Daniel Aven Bross * * 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. */ #ifndef JWT_GAME_SERVER_MATCHMAKING_SERVER_HPP #define JWT_GAME_SERVER_MATCHMAKING_SERVER_HPP #include "base_server.hpp" #include <chrono> #include <functional> #include <tuple> namespace simple_web_game_server { // Time literals to initialize timestep variables using namespace std::chrono_literals; /// A matchmaking server built on the base_server class. /** * This class wraps an underlying base_server * and performs matchmaking between connected client sessions. */ template<typename matchmaker, typename jwt_clock, typename json_traits, typename server_config, typename close_reasons = default_close_reasons> class matchmaking_server { // type definitions private: using jwt_base_server = base_server< typename matchmaker::player_traits, jwt_clock, json_traits, server_config, close_reasons >; using combined_id = typename jwt_base_server::combined_id; using player_id = typename jwt_base_server::player_id; using session_id = typename jwt_base_server::session_id; template<typename value> using session_id_map = typename jwt_base_server::session_id_map<value>; using json = typename jwt_base_server::json; using clock = typename jwt_base_server::clock; using game = std::tuple<vector<session_id>, session_id, json>; using message = pair<session_id, std::string>; using session_data = typename matchmaker::session_data; using ssl_context_ptr = typename jwt_base_server::ssl_context_ptr; /// The data associated to a connecting or disconnecting client. struct connection_update { connection_update(const combined_id& i) : id(i), disconnection(true) {} connection_update(const combined_id& i, json&& d) : id(i), data(std::move(d)), disconnection(false) {} combined_id id; json data; bool disconnection; }; // main class body public: /// The constructor for the matchmaking_server class. /** * The parameters are * simply used to construct the underlying base_server. */ matchmaking_server( const jwt::verifier<jwt_clock, json_traits>& v, function<std::string(const combined_id&, const json&)> f, std::chrono::milliseconds t ) : m_jwt_server{v, f, t} { m_jwt_server.set_open_handler( bind( &matchmaking_server::player_connect, this, simple_web_game_server::_1, simple_web_game_server::_2 ) ); m_jwt_server.set_close_handler( bind( &matchmaking_server::player_disconnect, this, simple_web_game_server::_1 ) ); m_jwt_server.set_message_handler( bind( &matchmaking_server::process_message, this, simple_web_game_server::_1, simple_web_game_server::_2 ) ); } /// Constructs the underlying base_server with a default time-step. matchmaking_server( const jwt::verifier<jwt_clock, json_traits>& v, function<std::string(const combined_id&, const json&)> f ) : matchmaking_server{v, f, 3600s} {} /// Sets the tls_init_handler for the underlying base_server. void set_tls_init_handler(function<ssl_context_ptr(connection_hdl)> f) { m_jwt_server.set_tls_init_handler(f); } /// Runs the underlying base_server. void run(uint16_t port, bool unlock_address = false) { m_jwt_server.run(port, unlock_address); } /// Runs the process_messages loop on the underlying base_server. void process_messages() { m_jwt_server.process_messages(); } /// Stops, clears, and resets the server so it may be run again. void reset() { stop(); m_jwt_server.reset(); } /// Stops the server and clears all data and connections. void stop() { m_jwt_server.stop(); { lock_guard<mutex> guard(m_match_lock); m_session_data.clear(); m_session_players.clear(); m_connection_updates.second.clear(); } { lock_guard<mutex> guard(m_connection_update_list_lock); m_connection_updates.first.clear(); } m_match_condition.notify_one(); } /// Returns the number of verified clients connected. std::size_t get_player_count() { return m_jwt_server.get_player_count(); } bool is_running() { return m_jwt_server.is_running(); } /// Loop to match players. /** * Processes client connections and disconnections and matches connected * client sessions together. It may also send out any messages broadcast by * the matchmaking function. Should only be called by one thread. */ void match_players(std::chrono::milliseconds timestep) { auto time_start = clock::now(); pair<vector<session_id>, vector<session_id> > finished_sessions; while(m_jwt_server.is_running()) { unique_lock<mutex> match_lock(m_match_lock); if(!m_matchmaker.can_match(m_session_data)) { match_lock.unlock(); unique_lock<mutex> conn_lock(m_connection_update_list_lock); while(m_connection_updates.first.empty()) { m_match_condition.wait(conn_lock); if(!m_jwt_server.is_running()) { return; } } match_lock.lock(); } auto delta_time = std::chrono::duration_cast<std::chrono::milliseconds>( clock::now() - time_start ); const long dt_count = delta_time.count(); if(delta_time < timestep) { match_lock.unlock(); std::this_thread::sleep_for(std::min(1us, timestep-delta_time+1us)); } else { time_start = clock::now(); process_connection_updates(finished_sessions.second); // we remove data here to catch any possible players submitting // connections in the last timestep when the session ends for(const session_id& sid : finished_sessions.first) { spdlog::trace("erasing data for session {}", sid); m_session_data.erase(sid); m_session_players.erase(sid); } finished_sessions.first.clear(); std::swap(finished_sessions.first, finished_sessions.second); vector<game> games; { vector<pair<session_id, std::string> > messages; m_matchmaker.match(games, messages, m_session_data, dt_count); for(message& msg : messages) { auto session_players_it = m_session_players.find(msg.first); if(session_players_it != m_session_players.end()) { for(player_id pid : session_players_it->second) { m_jwt_server.send_message( { pid, msg.first }, std::move(msg.second) ); } } } } for(game& g : games) { vector<session_id> sessions; session_id game_sid; json game_data; std::tie(sessions, game_sid, game_data) = std::move(g); spdlog::trace("matched game: {}", game_data.dump()); for(session_id& sid : sessions) { m_jwt_server.complete_session( sid, game_sid, game_data ); finished_sessions.first.push_back(sid); } } } } } private: void process_connection_updates(vector<session_id>& finished_sessions) { { unique_lock<mutex> conn_lock(m_connection_update_list_lock); std::swap(m_connection_updates.first, m_connection_updates.second); } for(connection_update& update : m_connection_updates.second) { auto it = m_session_data.find(update.id.session); if(update.disconnection) { if(it != m_session_data.end()) { spdlog::trace( "processing disconnection for session {}", update.id.session ); m_jwt_server.complete_session( update.id.session, update.id.session, m_matchmaker.get_cancel_data() ); m_session_data.erase(it); m_session_players.erase(update.id.session); finished_sessions.push_back(update.id.session); } } else { spdlog::trace( "processing connection for session {}", update.id.session ); if(it == m_session_data.end()) { session_data data{update.data}; if(data.is_valid()) { m_session_data.emplace( update.id.session, std::move(data) ); m_session_players.emplace( update.id.session, set<player_id>{ update.id.player } ); } else { m_jwt_server.complete_session( update.id.session, update.id.session, m_matchmaker.get_cancel_data() ); finished_sessions.push_back(update.id.session); } } else { m_session_players.at(update.id.session).insert(update.id.player); } } } m_connection_updates.second.clear(); } // proper procedure for client to cancel matchmaking is to send a message // and wait for the server to close the connection; by acquiring the match // lock and marking the user as unavailable we avoid the situation where a // player disconnects after the match function is called, but before a game // token is successfully sent to them void process_message(const combined_id& id, std::string&& data) { { lock_guard<mutex> guard(m_connection_update_list_lock); m_connection_updates.first.emplace_back(id); } m_match_condition.notify_one(); } void player_connect(const combined_id& id, json&& data) { { lock_guard<mutex> guard(m_connection_update_list_lock); m_connection_updates.first.emplace_back( id, std::move(data) ); } m_match_condition.notify_one(); } void player_disconnect(const combined_id& id) { { lock_guard<mutex> guard(m_connection_update_list_lock); m_connection_updates.first.emplace_back(id); } m_match_condition.notify_one(); } // member variables matchmaker m_matchmaker; session_id_map<session_data> m_session_data; session_id_map<set<player_id> > m_session_players; mutex m_match_lock; pair< vector<connection_update>, vector<connection_update> > m_connection_updates; mutex m_connection_update_list_lock; condition_variable m_match_condition; jwt_base_server m_jwt_server; }; } #endif // JWT_GAME_SERVER_MATCHMAKING_SERVER_HPP
33.581717
81
0.633837
permutationlock
a5669b1fab7a6f7f6021df4c199a894a73432e0d
759
cpp
C++
05-unit-testing/boost/unit_tests.cpp
yangxl-2014-fe/cmake-examples
0675e0fcb7a4f70dc7ae179fcda520b42e83dd7d
[ "MIT" ]
8,249
2015-12-01T20:22:26.000Z
2022-03-31T09:32:28.000Z
05-unit-testing/boost/unit_tests.cpp
Star2510965709/cmake-examples
2b27fc75c40447c8cf9b371cc21224dd96d6ce45
[ "MIT" ]
43
2015-12-01T15:17:40.000Z
2022-03-18T11:40:54.000Z
05-unit-testing/boost/unit_tests.cpp
Star2510965709/cmake-examples
2b27fc75c40447c8cf9b371cc21224dd96d6ce45
[ "MIT" ]
2,016
2016-11-15T16:27:47.000Z
2022-03-31T07:11:43.000Z
#include <string> #include "Reverse.h" #include "Palindrome.h" #define BOOST_TEST_MODULE VsidCommonTest #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE( reverse_tests ) BOOST_AUTO_TEST_CASE( simple ) { std::string toRev = "Hello"; Reverse rev; std::string res = rev.reverse(toRev); BOOST_CHECK_EQUAL( res, "olleH" ); } BOOST_AUTO_TEST_CASE( empty ) { std::string toRev; Reverse rev; std::string res = rev.reverse(toRev); BOOST_CHECK_EQUAL( res, "" ); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE( palindrome_tests ) BOOST_AUTO_TEST_CASE( is_palindrome ) { std::string pal = "mom"; Palindrome pally; BOOST_CHECK_EQUAL( pally.isPalindrome(pal), true ); } BOOST_AUTO_TEST_SUITE_END()
16.148936
55
0.710145
yangxl-2014-fe
a569f1b2d7918a58878fb57ea66dbf515b550877
8,159
cc
C++
HealpixBaseExtended.cc
bjbuckman/galprop_bb_
076b168f7475b3ba9fb198b6ec2df7be66b1763c
[ "MIT" ]
null
null
null
HealpixBaseExtended.cc
bjbuckman/galprop_bb_
076b168f7475b3ba9fb198b6ec2df7be66b1763c
[ "MIT" ]
null
null
null
HealpixBaseExtended.cc
bjbuckman/galprop_bb_
076b168f7475b3ba9fb198b6ec2df7be66b1763c
[ "MIT" ]
null
null
null
#include "HealpixBaseExtended.h" #include "config.h" #ifdef HAVE_LSCONSTANTS_H #include "lsconstants.h" #endif #include <vector> #include <iterator> #include <algorithm> #include <set> #include <cmath> // this is in HEALPIX V3.11, not in V2.20a. But not needed. AWS20131202 /* int Healpix_Base::ring_above (double z) const { double az=fabs(z); if (az>twothird) // polar caps { int iring = int(nside_*sqrt(3*(1-az))); return (z>0) ? iring : 4*nside_-iring-1; } else // ----- equatorial region --------- return int(nside_*(2-1.5*z)); } */ //Select pixels from a region std::set<int> HealpixBaseExtended::regionToPixels(const SkyRegion & region) const { //The vector to store the pixel values std::set<int> pixSet; std::vector<int> listpix; //Check the region type switch (region.type()) { case DISC: //Use the query disk if (region.radius() > 0) { query_disc(region.center().healpixAng(), region.radius() * M_PI/180, listpix); std::copy(listpix.begin(), listpix.end(), std::inserter(pixSet, pixSet.begin())); } break; case RECTANGLE: if (region.deltal() > 0 && region.deltab() > 0) { //We need to split the region up if necessary and query them one by //one double dphi = region.deltal()/2 * M_PI/180; double dtheta = region.deltab()/2 * M_PI/180; // //Now we need to check for overshooting in the theta direction //North pole if (region.center().healpixAng().theta - dtheta < 0) { //We go over the pole, add the section on the other side double lowTheta = 0 - (region.center().healpixAng().theta - dtheta); double highTheta = 0; double lowPhi = region.center().healpixAng().phi - dphi + M_PI; double highPhi = region.center().healpixAng().phi + dphi + M_PI; if (highPhi > 2*M_PI) highPhi -= 2*M_PI; std::cout<<"Overshooding north pole "<<lowTheta<<", "<<highTheta<<", "<<lowPhi<<", "<<highPhi<<std::endl; query_rectangle(pointing(lowTheta, lowPhi), pointing(highTheta, highPhi), listpix); std::copy(listpix.begin(), listpix.end(), std::inserter(pixSet, pixSet.begin())); } //South pole if (region.center().healpixAng().theta + dtheta > M_PI) { //We go over the pole, add the section on the other side double lowTheta = M_PI; double highTheta = 2*M_PI - (region.center().healpixAng().theta + dtheta); double lowPhi = region.center().healpixAng().phi - dphi + M_PI; double highPhi = region.center().healpixAng().phi + dphi + M_PI; if (highPhi > 2*M_PI) highPhi -= 2*M_PI; std::cout<<"Overshooding south pole "<<lowTheta<<", "<<highTheta<<", "<<lowPhi<<", "<<highPhi<<std::endl; query_rectangle(pointing(lowTheta, lowPhi), pointing(highTheta, highPhi), listpix); std::copy(listpix.begin(), listpix.end(), std::inserter(pixSet, pixSet.begin())); } //The rest, things that don't loop double lowTheta = std::min(M_PI, region.center().healpixAng().theta+dtheta); double highTheta = std::max(0., region.center().healpixAng().theta-dtheta); double lowPhi = region.center().healpixAng().phi - dphi; double highPhi = region.center().healpixAng().phi + dphi; //Fix overshoot if (highPhi > 2*M_PI) highPhi -= 2*M_PI; if (lowPhi < 0) lowPhi += 2*M_PI; query_rectangle(pointing(lowTheta, lowPhi), pointing(highTheta, highPhi), listpix); std::copy(listpix.begin(), listpix.end(), std::inserter(pixSet, pixSet.begin())); } } return pixSet; } void HealpixBaseExtended::query_pixel(const Healpix_Base &hp, int pixel, std::vector<int> &listpix) const { listpix.clear(); //Find the difference in order between the two bases int dOrder = Order() - hp.Order(); //If dorder is <= 0, then the input is finer binned than the output and we //only have a single pixel if (dOrder <= 0) { listpix.push_back(ang2pix(hp.pix2ang(pixel))); } else { //Now we must loop over all the pixels covered by the bigger pixel //First find its index in nested int nestpix = hp.Scheme() == NEST ? pixel : hp.ring2nest(pixel); //Find the number of pixels under each pixel int npix = (1<<dOrder)*(1<<dOrder); listpix.resize(npix); //loop over all the pixels, in nest scheme for (int p = 0; p < npix; ++p) { listpix[p] = Scheme() == NEST ? p+nestpix*npix : nest2ring(p+nestpix*npix); } } } void HealpixBaseExtended::query_rectangle(const pointing &pointingll, const pointing &pointingur, std::vector<int> &listpix) const { //Clear all values from listpix listpix.clear(); //Begin by finding the rings we have to iterate over std::vector<int> rings; //Check if the lower limit is above the upper limit if (pointingll.theta > pointingur.theta) { //The normal way int ur = ring_above(cos(pointingur.theta))+1; int lr = ring_above(cos(pointingll.theta)); //Use the generator algorithm to insert the rings. rings.resize(lr-ur+1); std::generate(rings.begin(), rings.end(), counter(ur-1)); } else { //Looping from north to south int ur = ring_above(cos(pointingll.theta)); int lr = ring_above(cos(pointingur.theta))+1; rings.resize(ur+(4*nside_-1)-lr+1); //4*nside_-1 is the number of rings of the skymap std::generate(rings.begin(), rings.begin()+ur, counter(0)); std::generate(rings.begin()+ur, rings.end(), counter(lr-1)); } //Now we have to deal with the rings, selecting the correct pixels //The ring_info method only works for RING healpix bases, so we create one Healpix_Base hp(order_, RING); //First check if left side is really on the left side int startpix, ringpix; double theta; bool shifted; if (pointingll.phi < pointingur.phi) { //The normal way, no looping for (int i = 0; i < int(rings.size()); ++i) { hp.get_ring_info2(rings[i], startpix, ringpix, theta, shifted); //Find the location of the first pixel within the boundary. //The width of each pixel is 2\pi/ringpix double dl = 2.*pi/ringpix; int lp = int(ceil((pointingll.phi - shifted*dl/2)/dl)); int rp = std::min(int((pointingur.phi - shifted*dl/2)/dl), ringpix); listpix.reserve(listpix.size()+rp-lp+1); std::generate_n(std::back_inserter(listpix), rp-lp+1, counter(startpix + lp-1)); //In the case the right boundary is 2*pi, the ring is //not shifted and the left boundary is not 0, we must //add the first pixel of the ring. if (pointingll.phi != 0 && pointingur.phi == 2*pi && !shifted) listpix.push_back(startpix); } } else { //Looping over 2 \pi for (int i = 0; i < int(rings.size()); ++i) { hp.get_ring_info2(rings[i], startpix, ringpix, theta, shifted); //Find the location of the first pixel within the boundary. //The width of each pixel is 2\pi/ringpix double dl = 2.*pi/ringpix; int lp = int(floor((pointingur.phi - shifted*dl/2)/dl)); int rp = int(ceil((pointingll.phi - shifted*dl/2)/dl)); listpix.reserve(listpix.size()+lp+1+ringpix-rp); std::generate_n(std::back_inserter(listpix), lp+1, counter(startpix-1)); std::generate_n(std::back_inserter(listpix), ringpix-rp, counter(startpix+rp-1)); } } //Now we must check if the actual map is in a NESTED scheme and fix the list if (scheme_ == NEST) { std::transform(listpix.begin(), listpix.end(), listpix.begin(), std::bind1st(std::mem_fun(&Healpix_Base::ring2nest), this)); } }
45.837079
132
0.596887
bjbuckman
a56afe707632f49f877910d723b126e89bfb9c35
769
cpp
C++
LeetCode/GenerateParentheses/generateparentheses.cpp
sharmakarish/CPP-Questions-and-Solutions
a2cbcb7b7de4df2849af352af763a0904f834e56
[ "MIT" ]
42
2021-09-26T18:02:52.000Z
2022-03-15T01:52:15.000Z
LeetCode/GenerateParentheses/generateparentheses.cpp
sharmakarish/CPP-Questions-and-Solutions
a2cbcb7b7de4df2849af352af763a0904f834e56
[ "MIT" ]
404
2021-09-24T19:55:10.000Z
2021-11-03T05:47:47.000Z
LeetCode/GenerateParentheses/generateparentheses.cpp
sharmakarish/CPP-Questions-and-Solutions
a2cbcb7b7de4df2849af352af763a0904f834e56
[ "MIT" ]
140
2021-09-22T20:50:04.000Z
2022-01-22T16:59:09.000Z
#include<iostream> #include<vector> using namespace std; class Solution { public: // Member function will return the anwser of string datatype vector<string> result; vector<string> generateParenthesis(int n) { helper("", n, 0, 0); // Returning the finial answer return result; } void helper(string s, int n, int l, int r){ if (l < r || l > n || r > n) return; // exceed the bundary -> return if (l == n && r == n){ result.push_back(s); return; } helper(s + "(", n, l+1, r); helper(s + ")", n, l, r+1); } }; //Drive code starts. int main(){ Solution s; //calling method generateParentheses() with number. s.generateParenthesis(4); return 0; }
24.03125
77
0.555267
sharmakarish
a56c01b623c8fe6c153ce8e35d93f59e2cb9e6a3
2,262
hpp
C++
LevelBattle.hpp
PraiseHelix/Pocket-Animals
fe129e76128b8a986ae59b714b81fc72fde574de
[ "MIT" ]
null
null
null
LevelBattle.hpp
PraiseHelix/Pocket-Animals
fe129e76128b8a986ae59b714b81fc72fde574de
[ "MIT" ]
5
2019-02-01T13:48:16.000Z
2019-02-03T14:02:39.000Z
LevelBattle.hpp
PraiseHelix/PocketAnimals
fe129e76128b8a986ae59b714b81fc72fde574de
[ "MIT" ]
null
null
null
#pragma once #include "..\SGPE\Level.hpp" #include "..\SGPE\GameObject.hpp" #include "GraphicsSFML.hpp" #include "..\BattleSystem\TimeManager.hpp" #include "..\BattleSystem\BattleGraphics.hpp" #include "..\BattleSystem\BattleSystem.hpp" #include "..\BattleSystem\InterLevelData.hpp" #include "..\BattleSystem\BattlePlayer.hpp" class LevelBattle : public Level { private: TimeManager & timeManager; BattleGraphics & battleGraphics; std::shared_ptr <InterLevelData> interLevelData; std::shared_ptr<BattlePlayer> attacker; std::shared_ptr<BattlePlayer> defender; BattleSystem & battleSystem; std::shared_ptr<LevelManagerPocketAnimalsSync> sync; std::shared_ptr<sf::RenderWindow> window; std::vector<GameObject*> gameObjects; std::shared_ptr<GraphicsSFML> graphics; public: LevelBattle( TimeManager & timeManager, BattleGraphics & battleGraphics, std::shared_ptr <InterLevelData> interLevelData, std::shared_ptr<BattlePlayer> attacker, std::shared_ptr<BattlePlayer> defender, BattleSystem & battleSystem, std::shared_ptr<LevelManagerPocketAnimalsSync> sync, std::shared_ptr<sf::RenderWindow> window, std::vector<GameObject*> gameObjects, std::shared_ptr<GraphicsSFML> graphics) : Level(gameObjects, graphics, true), timeManager(timeManager), battleGraphics(battleGraphics), interLevelData(interLevelData), attacker(attacker), defender(defender), battleSystem(battleSystem), sync(sync), window(window), // TODO need to fix this priority level: jezus christ. gameObjects(gameObjects), graphics(graphics) { } void Update() { timeManager.onUpdate(); // update all graphics window->clear(); battleGraphics.onUpdate(); window->display(); // update pocketAnimals attacker->pocketAnimal->onUpdate(); defender->pocketAnimal->onUpdate(); // update the battleSystem battleSystem.onUpdate(); // check for a winner: if (interLevelData->winner != nullptr) { // shared space sync->change(2); // previous level } }; void Start() { battleSystem.onStart(); battleGraphics.onStart(); window->clear(); battleGraphics.onUpdate(); window->display(); // should have an init function if required }; void Render() { }; void Close() {} ~LevelBattle() {}; };
22.39604
72
0.730327
PraiseHelix
a56e5ae4a07ea758d45934bcc0962785127ba722
1,031
cpp
C++
tute02.cpp
SLIIT-FacultyOfComputing/tutorial-02b-IT21161360
60ce7414f7b72c0ea3831e90e8e18de8d9bd87cd
[ "MIT" ]
null
null
null
tute02.cpp
SLIIT-FacultyOfComputing/tutorial-02b-IT21161360
60ce7414f7b72c0ea3831e90e8e18de8d9bd87cd
[ "MIT" ]
null
null
null
tute02.cpp
SLIIT-FacultyOfComputing/tutorial-02b-IT21161360
60ce7414f7b72c0ea3831e90e8e18de8d9bd87cd
[ "MIT" ]
null
null
null
/*Exercise 2 - Selection Convert the C program given below which calculates an employee's salary to a C++ program. Input Type, Salary, otHours Type = 1 OtRate = 1000 Type = 2 OtRate = 1500 Type = 3 OtRate = 1700 Please Note that the input command in C++ is std::cin. This is a representation of the Keyboard.*/ #include <iostream> using namespace std; //main function begins for execution int main (void) { //declaring variables double salary, netSalary; int etype, otHrs, otRate; //Enter the employee type cout<<"Enter Employee Type : "; cin>>etype; //Enter the salary cout<<"Enter Salary : "; cin>>salary; //Enter the OThours cout<<"Enter OtHrs : "; cin>>otHrs; //Using switch case switch (etype) { //case 1 case 1 : otRate = 1000; break; //case 2 case 2 : otRate = 1500; break; //default default : otRate = 1700; break; } //Calculates Netsalary netSalary = salary + otHrs* otRate; //Display The net Salary cout<<"Net Salary is: "<<netSalary<<endl; //return type value return 0; }
15.621212
98
0.682832
SLIIT-FacultyOfComputing
a5727aefdb51e3fbbfef6e804339b75c777a0700
2,929
cpp
C++
SystemManager.cpp
dsedb/space_deadbeef2
74664f836a21b6ffa6a3944b4d41a8e39c7e5a67
[ "MIT" ]
1
2019-04-24T11:01:38.000Z
2019-04-24T11:01:38.000Z
SystemManager.cpp
dsedb/space_deadbeef2
74664f836a21b6ffa6a3944b4d41a8e39c7e5a67
[ "MIT" ]
null
null
null
SystemManager.cpp
dsedb/space_deadbeef2
74664f836a21b6ffa6a3944b4d41a8e39c7e5a67
[ "MIT" ]
null
null
null
/* -*- mode:C++; coding:utf-8-with-signature -*- * * SystemManager.cpp - Project PetitShooter * * Copyright (c) 2017 Yuji YASUHARA * * 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. * * since Thu Aug 17 09:22:07 2017 */ #include <Arduino.h> #include "Debug.h" #include "CollisionManager.h" #include "SystemManager.h" namespace UTJ { void SystemManager::init() { Debug::init(); random_.seed(12345); input_manager_.init(); render_manager_.init(); sound_.init(); bullet_manager_.init(); laser_manager_.init(); player_.init(); enemy_manager_.init(); game_manager_.init(); explosion_manager_.init(); frame_cnt_ = 0; boot_sequence(); } void SystemManager::update() { input_manager_.fetch(); sound_.update(); game_manager_.update(enemy_manager_, random_); player_.update(input_manager_, sound_, bullet_manager_, laser_manager_, enemy_manager_); bullet_manager_.update(); laser_manager_.update(player_); enemy_manager_.update(sound_, explosion_manager_, game_manager_.getScore()); explosion_manager_.update(); lockcursor_manager_.update(); CollisionManager::check(sound_, player_, bullet_manager_, enemy_manager_, lockcursor_manager_); } void SystemManager::render() { render_manager_.begin(); player_.render(render_manager_, frame_cnt_); bullet_manager_.render(render_manager_); laser_manager_.render(render_manager_); enemy_manager_.render(render_manager_); explosion_manager_.render(render_manager_); lockcursor_manager_.render(render_manager_); render_manager_.end(); render_manager_.display(player_.isHomingMode(), enemy_manager_.getLockedNum(), enemy_manager_.getLockMax(), game_manager_.getScore()); ++frame_cnt_; } void SystemManager::boot_sequence() { render_manager_.boot(); sound_.boot(); input_manager_.boot(); sound_.gameStart(); render_manager_.clear(); } } // namespace UTJ { /* * End of SystemManager.cpp */
27.895238
89
0.754524
dsedb
a574d35e51bce2a6f25705ea3d59646bfe900a3e
681
cpp
C++
src/MazeFactoryEasy.cpp
anqin-gh/minimaze
cfa3df279c75d5fe95a2e69af4569a3981a6f274
[ "MIT" ]
null
null
null
src/MazeFactoryEasy.cpp
anqin-gh/minimaze
cfa3df279c75d5fe95a2e69af4569a3981a6f274
[ "MIT" ]
null
null
null
src/MazeFactoryEasy.cpp
anqin-gh/minimaze
cfa3df279c75d5fe95a2e69af4569a3981a6f274
[ "MIT" ]
null
null
null
#include <new> #include <EnemyLR.h> #include <Goal.h> #include <MazeFactoryEasy.h> #include <Player.h> #include <WallNormal.h> namespace minimaze { Player* MazeFactoryEasy::create_player(int8_t x, int8_t y) const { Player* p = new Player(); p->set_location(x, y); return p; } Enemy* MazeFactoryEasy::create_enemy(int8_t x, int8_t y) const { Enemy* e = new EnemyLR(); e->set_location(x, y); return e; } Wall* MazeFactoryEasy::create_wall(int8_t x, int8_t y) const { Wall* w = new WallNormal(); w->set_location(x, y); return w; } Goal* MazeFactoryEasy::create_goal(int8_t x, int8_t y) const { Goal* g = new Goal(); g->set_location(x, y); return g; } } // minimaze
18.916667
66
0.688693
anqin-gh
a5757f9c7e62686478c045fe0c6f963ef1f00f2d
153
hpp
C++
include/nekoman.hpp
bonohub13/nekoman_speak
f60caa24ee2db88128263c92133a2e93dc9f51f6
[ "MIT" ]
null
null
null
include/nekoman.hpp
bonohub13/nekoman_speak
f60caa24ee2db88128263c92133a2e93dc9f51f6
[ "MIT" ]
null
null
null
include/nekoman.hpp
bonohub13/nekoman_speak
f60caa24ee2db88128263c92133a2e93dc9f51f6
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <string> #include <array> namespace nekoman { using namespace std; array<string, 9> get_nekoman(); }
12.75
35
0.69281
bonohub13
a5869e4ebe83dda4b34381154263277f82c30e23
1,919
cpp
C++
cpp/110.balanced-binary-tree.cpp
vermouth1992/Leetcode
0d7dda52b12f9e01d88fc279243742cd8b4bcfd1
[ "MIT" ]
null
null
null
cpp/110.balanced-binary-tree.cpp
vermouth1992/Leetcode
0d7dda52b12f9e01d88fc279243742cd8b4bcfd1
[ "MIT" ]
null
null
null
cpp/110.balanced-binary-tree.cpp
vermouth1992/Leetcode
0d7dda52b12f9e01d88fc279243742cd8b4bcfd1
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=110 lang=cpp * * [110] Balanced Binary Tree * * https://leetcode.com/problems/balanced-binary-tree/description/ * * algorithms * Easy (45.02%) * Total Accepted: 603.8K * Total Submissions: 1.3M * Testcase Example: '[3,9,20,null,null,15,7]' * * Given a binary tree, determine if it is height-balanced. * * For this problem, a height-balanced binary tree is defined as: * * * a binary tree in which the left and right subtrees of every node differ in * height by no more than 1. * * * * Example 1: * * * Input: root = [3,9,20,null,null,15,7] * Output: true * * * Example 2: * * * Input: root = [1,2,2,3,3,null,null,4,4] * Output: false * * * Example 3: * * * Input: root = [] * Output: true * * * * Constraints: * * * The number of nodes in the tree is in the range [0, 5000]. * -10^4 <= Node.val <= 10^4 * * */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ #include "common.hpp" class Solution { public: bool isBalanced(TreeNode* root) { bool result = true; this->height(root, result); return result; } private: int height(TreeNode* root, bool &result) { if (root == nullptr) { return 0; } int left = this->height(root->left, result); if (!result) return -1; // height doesn't matter int right = this->height(root->right, result); if (!result) return -1; // height doesn't matter if (abs(left - right) > 1) { result = false; } return std::max(left, right) + 1; } };
21.087912
93
0.565399
vermouth1992
a58886fc5d1553c994b7a6bdc2e62d18c227431d
6,513
cpp
C++
ModuleBanker.cpp
mindcrunch4u/Kernel-Simulator
bc3ffc603a9d2099ae2b3c7879f7e35f7ed5cbd5
[ "MIT" ]
null
null
null
ModuleBanker.cpp
mindcrunch4u/Kernel-Simulator
bc3ffc603a9d2099ae2b3c7879f7e35f7ed5cbd5
[ "MIT" ]
null
null
null
ModuleBanker.cpp
mindcrunch4u/Kernel-Simulator
bc3ffc603a9d2099ae2b3c7879f7e35f7ed5cbd5
[ "MIT" ]
null
null
null
#include <iomanip> #include <sstream> #include "ModuleBanker.h" #include "SystemStatus.h" #include <iostream> #include <utility> #include <vector> using namespace std; #define FALSE 0 #define TRUE 1 int ModuleBanker::findIndexById(int id){ for(int index=0; index<SystemStatus::Max.size(); index++){ if( SystemStatus::Max[index].first == id ){ return index; } } /* find index from max, because * max, allocation, need are deleted at the same time. * * return -1 when nothing's found */ return -1; } /*1. 接受request */ bool ModuleBanker::solveRequest(const Item &item, bool enabled_log ) { // std::unique_lock<std::mutex> guard(*vector_mutex); if(enabled_log){ showdata(); } stringstream stream; vector<int> request; for(int i=0;i<item.request.size();i++) request.push_back(item.request[i]); int id = item.id; int index = findIndexById(id); if(index<0) { ModuleBanker::log("crit","申请的进程id不在表中"); return false; } for (int j = 0; j < SystemStatus::available.size(); j++) { if(request[j]>SystemStatus::need[index].second[j]) { stream.str(""); stream<<id ; stream<<"号进程"; stream<<"申请的资源数>进程"; stream<<id ; stream<<"号进程还需要"; stream<<j; stream<<"类资源的资源量"<<endl; if(enabled_log){ ModuleBanker::print( stream.str() ); } return false; } else if (request[j]>SystemStatus::available[j]) { stream.str(""); stream<<"进程"; stream<<id; stream<<"申请的资源数大于系统可用"; stream<<j; stream<<"类资源的资源量"<<endl; if(enabled_log){ ModuleBanker::print( stream.str() ); } return false; } } //changedata()符合条件,开始试分配资源 for (int j = 0; j < request.size(); j++) { SystemStatus::available[j]=SystemStatus::available[j]-request[j]; SystemStatus::allocation[index].second[j]=SystemStatus::allocation[index].second[j]+request[j]; SystemStatus::need[index].second[j]=SystemStatus::need[index].second[j]-request[j]; } //分配资源完,检测安全性 if (chkerr(index)) { //不安全,回收资源rstordata(),返回false; for (int j = 0; j < request.size(); j++) { SystemStatus::available[j]=SystemStatus::available[j]+request[j]; SystemStatus::allocation[index].second[j]=SystemStatus::allocation[index].second[j]-request[j]; SystemStatus::need[index].second[j]=SystemStatus::need[index].second[j]+request[j]; } return false; } else{ return true;//安全,返回ture } } /* 2. 释放资源 */ void ModuleBanker::releaseResource( const Item &item, bool enabled_log ){ // 当进程结束后,释放所有 Allocation int id =item.id; int index = findIndexById(id); if(index<0) { ModuleBanker::log("crit","申请的进程id不在表中"); } else { for (int j = 0; j < SystemStatus::available.size(); j++) { SystemStatus::available[j]=SystemStatus::available[j]+SystemStatus::allocation[index].second[j];//可用资源回收,available增加 SystemStatus::allocation[index].second[j]=SystemStatus::allocation[index].second[j]-SystemStatus::allocation[index].second[j];//该进程的allocation清零 } /* remove it's table entry */ int delete_table_index = ModuleBanker::findIndexById( id ); if( delete_table_index != -1 ){ SystemStatus::Max.erase( SystemStatus::Max.begin() + delete_table_index ); SystemStatus::allocation.erase( SystemStatus::allocation.begin() + delete_table_index ); SystemStatus::need.erase( SystemStatus::need.begin() + delete_table_index ); } ModuleBanker::log("done","任务完成,已经释放资源"); if( enabled_log ){ showdata(); } } } //显示数组 void ModuleBanker::showdata(){ int i,j; stringstream stream; stream << endl; stream<< setw(20) << "[Available]\n"<< endl; stream<< " 资源类别:"; for(int resource_type_index=0; resource_type_index<SystemStatus::supportedResourceCount; resource_type_index++) { stream << setw(4) << (char)('A' + resource_type_index) << " | "; } stream << endl; stream<<" 资源数目:"; for (j=0;j<SystemStatus::available.size();j++) { stream << setw(4) << SystemStatus::available[j] << " | "; } stream<<endl; stream<<endl; stream<< setw(20) << "[NEED]\n" << endl; stream<<" 资源类别:"; for(int resource_type_index=0; resource_type_index<SystemStatus::supportedResourceCount; resource_type_index++) { stream << setw(4) << (char)('A' + resource_type_index) << " | "; } stream << endl; for (i=0;i<SystemStatus::need.size();i++) //need的行数 { stream << setw(3) << SystemStatus::need[i].first<<"号进程:"; //第i个索引的进程id for (j=0;j<SystemStatus::need[i].second.size();j++) //need资源的列数 { stream << setw(4) << SystemStatus::need[i].second[j] << " | "; } stream<<endl; } stream<<endl; //stream<<"各进程已经得到的资源量:" << endl; stream<< setw(20) << "[Allocation]\n" << endl; stream<<" 资源类别:"; for(int resource_type_index=0; resource_type_index<SystemStatus::supportedResourceCount; resource_type_index++) { stream << setw(4) << (char)('A' + resource_type_index) << " | "; } stream << endl; for (i = 0; i < SystemStatus::allocation.size(); i++) { stream<< setw(3) << SystemStatus::allocation[i].first <<"号进程:"; for (j=0;j<SystemStatus::allocation[i].second.size();j++) { stream << setw(4) << SystemStatus::allocation[i].second[j] << " | "; } stream<<endl; } stream<<endl; ModuleBanker::print( stream.str() ); } //安全性检查函数 输入进程的排队序号index int ModuleBanker::chkerr(int index){ vector<int> work; vector<int> finish; vector<int> temp; stringstream stream; int i=0,j=0,p=0; for(i=0;i<SystemStatus::need.size() ;i++) finish.push_back(FALSE);//将所有的进程标志置位false for(int r=0;r<SystemStatus::available.size();r++) //首先将available的值赋予work { int m =SystemStatus::available[r]; work.push_back(m); } i=index;//从申请资源的进程开始检查安全性 while(i<SystemStatus::need.size()){ if(finish[i]==FALSE){ //满足条件释放资源,并从头开始扫描进程集合 while (p <SystemStatus::available.size() && SystemStatus::need[i].second[p]<=work[p] ) p++; if (p ==SystemStatus::available.size()) //如果三个资源都满足 { for (int j = 0; j < SystemStatus::available.size(); j++) { work[j]=work[j]+SystemStatus::allocation[i].second[j]; } finish[i]=TRUE; int id = SystemStatus::need[i].first; temp.push_back(id); //记录分配资源给进程的id i=0; } else i++; p=0; } else { i++; } } for ( i = 0; i < SystemStatus::need.size(); i++) if (finish[i]==FALSE) { ModuleBanker::log("bad","系统不安全!本次资源申请不成功!"); return 1; } stream << endl; stream << "经安全性检查,系统安全,本次分配成功"; stream << "本次安全序列:"; stream << "进程id依次为"; for (int i = 0; i < SystemStatus::need.size(); i++) { stream << temp[i] << "->"; } stream << "\n" << endl; ModuleBanker::print( stream.str() ); return 0; }
24.393258
147
0.644096
mindcrunch4u
a590f320b058460b91c122deb556efa6fdd8d783
1,155
cc
C++
src/DeletableDc.cc
itsuart/win-cpp-wrappers
a5c85c96cde46a043a2a2d90fe6671e21e8b6253
[ "Unlicense" ]
1
2019-01-11T18:39:14.000Z
2019-01-11T18:39:14.000Z
src/DeletableDc.cc
itsuart/win-cpp-wrappers
a5c85c96cde46a043a2a2d90fe6671e21e8b6253
[ "Unlicense" ]
null
null
null
src/DeletableDc.cc
itsuart/win-cpp-wrappers
a5c85c96cde46a043a2a2d90fe6671e21e8b6253
[ "Unlicense" ]
null
null
null
#pragma comment(lib, "gdi32.lib") #include "DeletableDc.h" #include <utility> namespace helpers { void swap(DeletableDc& lhs, DeletableDc& rhs) noexcept { std::swap(lhs.m_hdc, rhs.m_hdc); } DeletableDc::DeletableDc(HDC hdc) noexcept : m_hdc(hdc) {} DeletableDc::~DeletableDc() noexcept { Delete(); } DeletableDc::DeletableDc(DeletableDc&& src) noexcept : m_hdc(src.m_hdc) { src.m_hdc = nullptr; } DeletableDc& DeletableDc::operator=(DeletableDc&& src) noexcept { if (&src != this) { Delete(); m_hdc = src.m_hdc; src.m_hdc = nullptr; } return *this; } void DeletableDc::Delete() noexcept { if (m_hdc) { ::DeleteDC(m_hdc); m_hdc = nullptr; } } HDC DeletableDc::Unwrap() const noexcept { return m_hdc; } DeletableDc::operator bool() const noexcept { return m_hdc != nullptr; } DeletableDc::operator HDC() const noexcept { return Unwrap(); } HDC* DeletableDc::p_hdc() noexcept { return &m_hdc; } }
19.913793
69
0.554978
itsuart
a5935f8a0d4c0faaa058063f6bef00f397bca125
1,679
cc
C++
leetcode/18/main.cc
jinzhao1994/ACM
5846032df31ab000deb57d8cbb8cb4c27c0e955b
[ "WTFPL" ]
2
2015-07-22T01:26:47.000Z
2015-08-30T11:33:19.000Z
leetcode/18/main.cc
jinzhao1994/ACM
5846032df31ab000deb57d8cbb8cb4c27c0e955b
[ "WTFPL" ]
null
null
null
leetcode/18/main.cc
jinzhao1994/ACM
5846032df31ab000deb57d8cbb8cb4c27c0e955b
[ "WTFPL" ]
null
null
null
/* Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: The solution set must not contain duplicate quadruplets. Example: Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ] */ #include <algorithm> #include <utility> using namespace std; class Solution { public: vector <vector<int>> fourSum(vector<int> &nums, int target) { vector <vector<int>> ans; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size();) { for (int j = i + 1; j < nums.size();) { for (int l = j + 1, r = nums.size() - 1; l < r;) { int sum = nums[i] + nums[j] + nums[l] + nums[r]; if (sum == target) { vector<int> tmp = {nums[i], nums[j], nums[l], nums[r]}; ans.emplace_back(tmp); do l++; while (l < r && nums[l] == nums[l - 1]); do r--; while (l < r && nums[r] == nums[r + 1]); } else if (sum > target) { do r--; while (l < r && nums[r] == nums[r + 1]); } else if (sum < target) { do l++; while (l < r && nums[l] == nums[l - 1]); }; } do j++; while (j < nums.size() && nums[j] == nums[j - 1]); } do i++; while (i < nums.size() && nums[i] == nums[i - 1]); } return ans; } };
29.982143
79
0.437761
jinzhao1994
a59a6aef12e8498cd2b3406c88c0a3dd900365eb
890
cpp
C++
src/LagrangianState.cpp
adegenna/HardSphereDynamics
0df9aefffbbc5c9c7b96fd689ccc4deb0f3e1507
[ "0BSD" ]
1
2021-09-22T11:22:00.000Z
2021-09-22T11:22:00.000Z
src/LagrangianState.cpp
adegenna/HardSphereDynamics
0df9aefffbbc5c9c7b96fd689ccc4deb0f3e1507
[ "0BSD" ]
null
null
null
src/LagrangianState.cpp
adegenna/HardSphereDynamics
0df9aefffbbc5c9c7b96fd689ccc4deb0f3e1507
[ "0BSD" ]
null
null
null
#include "LagrangianState.h" #include "Inputfile.hpp" #include <stdlib.h> #include <stdio.h> #include <iostream> #include <fstream> #include <istream> #include <random> #include <cmath> #include <iostream> #include <iterator> #include <omp.h> #include <sys/time.h> using namespace std; using namespace Eigen; LagrangianState::LagrangianState(const MatrixXd& initialstate) : XY_(initialstate.block(0,0,initialstate.rows(),2)), UV_(initialstate.block(0,2,initialstate.rows(),2)), R_(initialstate.block(0,4,initialstate.rows(),1)) { } LagrangianState::~LagrangianState() { } void LagrangianState::updateXY(const MatrixXd& DXY) { XY_ += DXY; } void LagrangianState::writeXY(const std::string& filename) const { const static IOFormat CSVFormat(StreamPrecision, DontAlignCols, ", ", "\n"); ofstream xyout(filename); xyout << XY_.format(CSVFormat); xyout.close(); }
21.707317
78
0.722472
adegenna
a5a2c388af876c7a6f194e5c1d7d9e7410419a75
4,548
cpp
C++
super-mario-dx10/05-SceneManager/main.cpp
HoangTuan0611/Game
64bbf4396ff38d17d3516c1eae687033f954d769
[ "MIT" ]
null
null
null
super-mario-dx10/05-SceneManager/main.cpp
HoangTuan0611/Game
64bbf4396ff38d17d3516c1eae687033f954d769
[ "MIT" ]
null
null
null
super-mario-dx10/05-SceneManager/main.cpp
HoangTuan0611/Game
64bbf4396ff38d17d3516c1eae687033f954d769
[ "MIT" ]
null
null
null
/* ============================================================= INTRODUCTION TO GAME PROGRAMMING SE102 SAMPLE 05 - SCENE MANAGER This sample illustrates how to: 1/ Read scene (textures, sprites, animations and objects) from files 2/ Handle multiple scenes in game Key classes/functions: CScene CPlayScene HOW TO INSTALL Microsoft.DXSDK.D3DX =================================== 1) Tools > NuGet package manager > Package Manager Console 2) execute command : Install-Package Microsoft.DXSDK.D3DX ================================================================ */ #include <windows.h> #include <d3d10.h> #include <d3dx10.h> #include <list> #include "debug.h" #include "Game.h" #include "GameObject.h" #include "Textures.h" #include "Animations.h" #include "Mario.h" #include "Brick.h" #include "Goomba.h" #include "Coin.h" #include "SampleKeyEventHandler.h" #include "AssetIDs.h" #define WINDOW_CLASS_NAME L"SampleWindow" #define MAIN_WINDOW_TITLE L"MARIO-DX10" #define WINDOW_ICON_PATH L"mario.ico" #define BACKGROUND_COLOR D3DXCOLOR(0, 0, 0, 1.0f) #define SCREEN_WIDTH 272 #define SCREEN_HEIGHT 256 LRESULT CALLBACK WinProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } /* Update world status for this frame dt: time period between beginning of last frame and beginning of this frame */ void Update(DWORD dt) { CGame::GetInstance()->GetCurrentScene()->Update(dt); } /* Render a frame */ void Render() { CGame* g = CGame::GetInstance(); ID3D10Device* pD3DDevice = g->GetDirect3DDevice(); IDXGISwapChain* pSwapChain = g->GetSwapChain(); ID3D10RenderTargetView* pRenderTargetView = g->GetRenderTargetView(); ID3DX10Sprite* spriteHandler = g->GetSpriteHandler(); pD3DDevice->ClearRenderTargetView(pRenderTargetView, BACKGROUND_COLOR); spriteHandler->Begin(D3DX10_SPRITE_SORT_TEXTURE); FLOAT NewBlendFactor[4] = { 0,0,0,0 }; pD3DDevice->OMSetBlendState(g->GetAlphaBlending(), NewBlendFactor, 0xffffffff); CGame::GetInstance()->GetCurrentScene()->Render(); spriteHandler->End(); pSwapChain->Present(0, 0); } HWND CreateGameWindow(HINSTANCE hInstance, int nCmdShow, int ScreenWidth, int ScreenHeight) { WNDCLASSEX wc; wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.hInstance = hInstance; wc.lpfnWndProc = (WNDPROC)WinProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hIcon = (HICON)LoadImage(hInstance, WINDOW_ICON_PATH, IMAGE_ICON, 0, 0, LR_LOADFROMFILE); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = WINDOW_CLASS_NAME; wc.hIconSm = NULL; RegisterClassEx(&wc); HWND hWnd = CreateWindow( WINDOW_CLASS_NAME, MAIN_WINDOW_TITLE, WS_OVERLAPPEDWINDOW, // WS_EX_TOPMOST | WS_VISIBLE | WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT, ScreenWidth, ScreenHeight, NULL, NULL, hInstance, NULL); if (!hWnd) { OutputDebugString(L"[ERROR] CreateWindow failed"); DWORD ErrCode = GetLastError(); return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return hWnd; } int Run() { MSG msg; int done = 0; ULONGLONG frameStart = GetTickCount64(); DWORD tickPerFrame = 1000 / MAX_FRAME_RATE; while (!done) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) done = 1; TranslateMessage(&msg); DispatchMessage(&msg); } ULONGLONG now = GetTickCount64(); // dt: the time between (beginning of last frame) and now // this frame: the frame we are about to render DWORD dt = (DWORD)(now - frameStart); if (dt >= tickPerFrame) { frameStart = now; CGame::GetInstance()->ProcessKeyboard(); Update(dt); Render(); CGame::GetInstance()->SwitchScene(); } else Sleep(tickPerFrame - dt); } return 1; } int WINAPI WinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow ) { HWND hWnd = CreateGameWindow(hInstance, nCmdShow, SCREEN_WIDTH, SCREEN_HEIGHT); SetDebugWindow(hWnd); LPGAME game = CGame::GetInstance(); game->Init(hWnd, hInstance); game->InitKeyboard(); //IMPORTANT: this is the only place where a hardcoded file name is allowed ! game->Load(L"Resources\\Scene\\mario-sample.txt"); SetWindowPos(hWnd, 0, 0, 0, SCREEN_WIDTH * 2, SCREEN_HEIGHT * 2, SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER); Run(); return 0; }
21.760766
113
0.69723
HoangTuan0611
a5a332f16de31f2a10f2003d1391d287a1e3a341
1,147
cpp
C++
src/homework/04_iteration/main.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-ryan-f1
d11ef12dda2bf441ad4fde38e7da5a0957a81bd6
[ "MIT" ]
null
null
null
src/homework/04_iteration/main.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-ryan-f1
d11ef12dda2bf441ad4fde38e7da5a0957a81bd6
[ "MIT" ]
null
null
null
src/homework/04_iteration/main.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-ryan-f1
d11ef12dda2bf441ad4fde38e7da5a0957a81bd6
[ "MIT" ]
null
null
null
//write include statements #include "dna.h" #include<iostream> //write using statements using std::cout; using std::cin; using std::string; /* Write code that prompts user to enter 1 for Get GC Content, or 2 for Get DNA Complement. The program will prompt user for a DNA string and call either get gc content or get dna complement function and display the result. Program runs as long as user enters a y or Y. */ int main() { char again; char choice; string entered_sequence; do { cout<<"Select mode\n"; cout<<"[1]: Get GC content of DNA\n"; cout<<"[2]: Get compliment of DNA\n"; cin>>choice; switch (choice) { case '1': cout<<"Enter a DNA string: "; cin>>entered_sequence; cout<<"The GC content of "<<entered_sequence<<"\nis: "<<get_gc_content(entered_sequence)<<"\n"; break; case '2': cout<<"Enter a DNA string: "; cin>>entered_sequence; cout<<"The compliment of "<<entered_sequence<<"\nis: "<<get_dna_complement(entered_sequence)<<"\n"; break; } cout<<"Press y to quit\nPress something else to use another mode\n"; cin>>again; } while (!(again == 'y')); return 0; }
23.895833
103
0.665214
acc-cosc-1337-spring-2021
a5a3c9cae05f8d8603b37bb290de0dae8cf56730
10,815
cpp
C++
qws/src/gui/QTableWidgetItem.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
42
2015-02-16T19:29:16.000Z
2021-07-25T11:09:03.000Z
qws/src/gui/QTableWidgetItem.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
1
2017-11-23T12:49:25.000Z
2017-11-23T12:49:25.000Z
qws/src/gui/QTableWidgetItem.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
5
2015-10-15T21:25:30.000Z
2017-11-22T13:18:24.000Z
///////////////////////////////////////////////////////////////////////////// // // File : QTableWidgetItem.cpp // Copyright : (c) David Harley 2010 // Project : qtHaskell // Version : 1.1.4 // Modified : 2010-09-02 17:02:00 // // Warning : this file is machine generated - do not modify. // ///////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <wchar.h> #include <qtc_wrp_core.h> #include <qtc_wrp_gui.h> #include <qtc_subclass.h> #include <gui/QTableWidgetItem_DhClass.h> extern "C" { QTCEXPORT(void*,qtc_QTableWidgetItem)() { DhQTableWidgetItem*tr = new DhQTableWidgetItem(); return (void*) tr; } QTCEXPORT(void*,qtc_QTableWidgetItem1)(int x1) { DhQTableWidgetItem*tr = new DhQTableWidgetItem((int)x1); return (void*) tr; } QTCEXPORT(void*,qtc_QTableWidgetItem2)(void* x1) { DhQTableWidgetItem*tr = new DhQTableWidgetItem((const QTableWidgetItem&)(*(QTableWidgetItem*)x1)); return (void*) tr; } QTCEXPORT(void*,qtc_QTableWidgetItem3)(wchar_t* x1) { DhQTableWidgetItem*tr = new DhQTableWidgetItem(from_method(x1)); return (void*) tr; } QTCEXPORT(void*,qtc_QTableWidgetItem4)(wchar_t* x1, int x2) { DhQTableWidgetItem*tr = new DhQTableWidgetItem(from_method(x1), (int)x2); return (void*) tr; } QTCEXPORT(void*,qtc_QTableWidgetItem5)(void* x1, wchar_t* x2) { DhQTableWidgetItem*tr = new DhQTableWidgetItem((const QIcon&)(*(QIcon*)x1), from_method(x2)); return (void*) tr; } QTCEXPORT(void*,qtc_QTableWidgetItem6)(void* x1, wchar_t* x2, int x3) { DhQTableWidgetItem*tr = new DhQTableWidgetItem((const QIcon&)(*(QIcon*)x1), from_method(x2), (int)x3); return (void*) tr; } QTCEXPORT(void*,qtc_QTableWidgetItem_background)(void* x0) { QBrush * tc = new QBrush(((QTableWidgetItem*)x0)->background()); return (void*)(tc); } QTCEXPORT(void*,qtc_QTableWidgetItem_backgroundColor)(void* x0) { QColor * tc = new QColor(((QTableWidgetItem*)x0)->backgroundColor()); return (void*)(tc); } QTCEXPORT(long,qtc_QTableWidgetItem_checkState)(void* x0) { return (long) ((QTableWidgetItem*)x0)->checkState(); } QTCEXPORT(void*,qtc_QTableWidgetItem_clone)(void* x0) { return (void*)((DhQTableWidgetItem*)x0)->Dhclone(); } QTCEXPORT(void*,qtc_QTableWidgetItem_clone_h)(void* x0) { return (void*)((DhQTableWidgetItem*)x0)->Dvhclone(); } QTCEXPORT(int,qtc_QTableWidgetItem_column)(void* x0) { return (int) ((QTableWidgetItem*)x0)->column(); } QTCEXPORT(void*,qtc_QTableWidgetItem_data)(void* x0, int x1) { QVariant * tc = new QVariant(((DhQTableWidgetItem*)x0)->Dhdata((int)x1)); return (void*)(tc); } QTCEXPORT(void*,qtc_QTableWidgetItem_data_h)(void* x0, int x1) { QVariant * tc = new QVariant(((DhQTableWidgetItem*)x0)->Dvhdata((int)x1)); return (void*)(tc); } QTCEXPORT(long,qtc_QTableWidgetItem_flags)(void* x0) { return (long) ((QTableWidgetItem*)x0)->flags(); } QTCEXPORT(void*,qtc_QTableWidgetItem_font)(void* x0) { QFont * tc = new QFont(((QTableWidgetItem*)x0)->font()); return (void*)(tc); } QTCEXPORT(void*,qtc_QTableWidgetItem_foreground)(void* x0) { QBrush * tc = new QBrush(((QTableWidgetItem*)x0)->foreground()); return (void*)(tc); } QTCEXPORT(void*,qtc_QTableWidgetItem_icon)(void* x0) { QIcon * tc = new QIcon(((QTableWidgetItem*)x0)->icon()); return (void*)(tc); } QTCEXPORT(int,qtc_QTableWidgetItem_isSelected)(void* x0) { return (int) ((QTableWidgetItem*)x0)->isSelected(); } QTCEXPORT(int,qtc_QTableWidgetItem_row)(void* x0) { return (int) ((QTableWidgetItem*)x0)->row(); } QTCEXPORT(void,qtc_QTableWidgetItem_setBackground)(void* x0, void* x1) { ((QTableWidgetItem*)x0)->setBackground((const QBrush&)(*(QBrush*)x1)); } QTCEXPORT(void,qtc_QTableWidgetItem_setBackgroundColor)(void* x0, void* x1) { ((QTableWidgetItem*)x0)->setBackgroundColor((const QColor&)(*(QColor*)x1)); } QTCEXPORT(void,qtc_QTableWidgetItem_setCheckState)(void* x0, long x1) { ((QTableWidgetItem*)x0)->setCheckState((Qt::CheckState)x1); } QTCEXPORT(void,qtc_QTableWidgetItem_setData)(void* x0, int x1, void* x2) { ((DhQTableWidgetItem*)x0)->DhsetData((int)x1, (const QVariant&)(*(QVariant*)x2)); } QTCEXPORT(void,qtc_QTableWidgetItem_setData_h)(void* x0, int x1, void* x2) { ((DhQTableWidgetItem*)x0)->DvhsetData((int)x1, (const QVariant&)(*(QVariant*)x2)); } QTCEXPORT(void,qtc_QTableWidgetItem_setFlags)(void* x0, long x1) { ((QTableWidgetItem*)x0)->setFlags((Qt::ItemFlags)x1); } QTCEXPORT(void,qtc_QTableWidgetItem_setFont)(void* x0, void* x1) { ((QTableWidgetItem*)x0)->setFont((const QFont&)(*(QFont*)x1)); } QTCEXPORT(void,qtc_QTableWidgetItem_setForeground)(void* x0, void* x1) { ((QTableWidgetItem*)x0)->setForeground((const QBrush&)(*(QBrush*)x1)); } QTCEXPORT(void,qtc_QTableWidgetItem_setIcon)(void* x0, void* x1) { ((QTableWidgetItem*)x0)->setIcon((const QIcon&)(*(QIcon*)x1)); } QTCEXPORT(void,qtc_QTableWidgetItem_setSelected)(void* x0, int x1) { ((QTableWidgetItem*)x0)->setSelected((bool)x1); } QTCEXPORT(void,qtc_QTableWidgetItem_setSizeHint)(void* x0, void* x1) { ((QTableWidgetItem*)x0)->setSizeHint((const QSize&)(*(QSize*)x1)); } QTCEXPORT(void,qtc_QTableWidgetItem_setSizeHint_qth)(void* x0, int x1_w, int x1_h) { QSize tx1(x1_w, x1_h); ((QTableWidgetItem*)x0)->setSizeHint(tx1); } QTCEXPORT(void,qtc_QTableWidgetItem_setStatusTip)(void* x0, wchar_t* x1) { ((QTableWidgetItem*)x0)->setStatusTip(from_method(x1)); } QTCEXPORT(void,qtc_QTableWidgetItem_setText)(void* x0, wchar_t* x1) { ((QTableWidgetItem*)x0)->setText(from_method(x1)); } QTCEXPORT(void,qtc_QTableWidgetItem_setTextAlignment)(void* x0, int x1) { ((QTableWidgetItem*)x0)->setTextAlignment((int)x1); } QTCEXPORT(void,qtc_QTableWidgetItem_setTextColor)(void* x0, void* x1) { ((QTableWidgetItem*)x0)->setTextColor((const QColor&)(*(QColor*)x1)); } QTCEXPORT(void,qtc_QTableWidgetItem_setToolTip)(void* x0, wchar_t* x1) { ((QTableWidgetItem*)x0)->setToolTip(from_method(x1)); } QTCEXPORT(void,qtc_QTableWidgetItem_setWhatsThis)(void* x0, wchar_t* x1) { ((QTableWidgetItem*)x0)->setWhatsThis(from_method(x1)); } QTCEXPORT(void*,qtc_QTableWidgetItem_sizeHint)(void* x0) { QSize * tc = new QSize(((QTableWidgetItem*)x0)->sizeHint()); return (void*)(tc); } QTCEXPORT(void,qtc_QTableWidgetItem_sizeHint_qth)(void* x0, int* _ret_w, int* _ret_h) { QSize tc = ((QTableWidgetItem*)x0)->sizeHint(); *_ret_w = tc.width(); *_ret_h = tc.height(); return; } QTCEXPORT(void*,qtc_QTableWidgetItem_statusTip)(void* x0) { QString * tq = new QString(((QTableWidgetItem*)x0)->statusTip()); return (void*)(tq); } QTCEXPORT(void*,qtc_QTableWidgetItem_tableWidget)(void* x0) { QTableWidget * tc = (QTableWidget*)(((QTableWidgetItem*)x0)->tableWidget()); QPointer<QTableWidget> * ttc = new QPointer<QTableWidget>(tc); return (void*)(ttc); } QTCEXPORT(void*,qtc_QTableWidgetItem_text)(void* x0) { QString * tq = new QString(((QTableWidgetItem*)x0)->text()); return (void*)(tq); } QTCEXPORT(int,qtc_QTableWidgetItem_textAlignment)(void* x0) { return (int) ((QTableWidgetItem*)x0)->textAlignment(); } QTCEXPORT(void*,qtc_QTableWidgetItem_textColor)(void* x0) { QColor * tc = new QColor(((QTableWidgetItem*)x0)->textColor()); return (void*)(tc); } QTCEXPORT(void*,qtc_QTableWidgetItem_toolTip)(void* x0) { QString * tq = new QString(((QTableWidgetItem*)x0)->toolTip()); return (void*)(tq); } QTCEXPORT(int,qtc_QTableWidgetItem_type)(void* x0) { return (int) ((QTableWidgetItem*)x0)->type(); } QTCEXPORT(void*,qtc_QTableWidgetItem_whatsThis)(void* x0) { QString * tq = new QString(((QTableWidgetItem*)x0)->whatsThis()); return (void*)(tq); } QTCEXPORT(void,qtc_QTableWidgetItem_finalizer)(void* x0) { ((DhQTableWidgetItem*)x0)->freeDynamicHandlers(); delete ((DhQTableWidgetItem*)x0); } QTCEXPORT(void*,qtc_QTableWidgetItem_getFinalizer)() { return (void*)(&qtc_QTableWidgetItem_finalizer); } QTCEXPORT(void,qtc_QTableWidgetItem_finalizer1)(void* x0) { delete ((QTableWidgetItem*)x0); } QTCEXPORT(void*,qtc_QTableWidgetItem_getFinalizer1)() { return (void*)(&qtc_QTableWidgetItem_finalizer1); } QTCEXPORT(void,qtc_QTableWidgetItem_delete)(void* x0) { ((DhQTableWidgetItem*)x0)->freeDynamicHandlers(); delete((DhQTableWidgetItem*)x0); } QTCEXPORT(void,qtc_QTableWidgetItem_delete1)(void* x0) { delete((QTableWidgetItem*)x0); } QTCEXPORT(void, qtc_QTableWidgetItem_userMethod)(void * evt_obj, int evt_typ) { void * te = evt_obj; ((DhQTableWidgetItem*)te)->userDefined(evt_typ); } QTCEXPORT(void*, qtc_QTableWidgetItem_userMethodVariant)(void * evt_obj, int evt_typ, void * xv) { void * te = evt_obj; return (void*)(((DhQTableWidgetItem*)te)->userDefinedVariant(evt_typ, (QVariant*)xv)); } QTCEXPORT(int, qtc_QTableWidgetItem_setUserMethod)(void * evt_obj, int evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { void * te = evt_obj; return (int) ((DhQTableWidgetItem*)te)->setDynamicQHandlerud(0, evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QTableWidgetItem_setUserMethodVariant)(void * evt_obj, int evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { void * te = evt_obj; return (int) ((DhQTableWidgetItem*)te)->setDynamicQHandlerud(1, evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QTableWidgetItem_unSetUserMethod)(void * evt_obj, int udm_typ, int evt_typ) { void * te = evt_obj; return (int) ((DhQTableWidgetItem*)te)->unSetDynamicQHandlerud(udm_typ, evt_typ); } QTCEXPORT(int, qtc_QTableWidgetItem_setHandler)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { void * te = evt_obj; QString tq_evt(from_method((wchar_t *)evt_typ)); QByteArray tqba_evt(tq_evt.toAscii()); return (int) ((DhQTableWidgetItem*)te)->setDynamicQHandler(evt_obj, tqba_evt.data(), rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QTableWidgetItem_unSetHandler)(void * evt_obj, wchar_t * evt_typ) { void * te = evt_obj; QString tq_evt(from_method((wchar_t *)evt_typ)); QByteArray tqba_evt(tq_evt.toAscii()); return (int) ((DhQTableWidgetItem*)te)->unSetDynamicQHandler(tqba_evt.data()); } QTCEXPORT(int, qtc_QTableWidgetItem_setHandler1)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QTableWidgetItem_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QTableWidgetItem_setHandler2)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QTableWidgetItem_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QTableWidgetItem_setHandler3)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QTableWidgetItem_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } }
33.586957
133
0.713731
keera-studios