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
23f779c2899c0ad952c77c7e27bc35d025ab0160
270
hpp
C++
libs/core/include/tone/core/variant_helpers.hpp
zfzackfrost/tone-lang
928ac09dc061da2fb076fdc201ed2d4409fdcd96
[ "MIT" ]
null
null
null
libs/core/include/tone/core/variant_helpers.hpp
zfzackfrost/tone-lang
928ac09dc061da2fb076fdc201ed2d4409fdcd96
[ "MIT" ]
null
null
null
libs/core/include/tone/core/variant_helpers.hpp
zfzackfrost/tone-lang
928ac09dc061da2fb076fdc201ed2d4409fdcd96
[ "MIT" ]
null
null
null
#pragma once namespace tone::core { // Credit: https://en.cppreference.com/w/cpp/utility/variant/visit template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; }
30
70
0.611111
zfzackfrost
23f7d04300b60e6c921ec28016db99d865bb3ebc
48,395
cpp
C++
shared/test/unit_test/os_interface/linux/drm_engine_info_prelim_tests.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
shared/test/unit_test/os_interface/linux/drm_engine_info_prelim_tests.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
shared/test/unit_test/os_interface/linux/drm_engine_info_prelim_tests.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/helpers/engine_node_helper.h" #include "shared/source/helpers/hw_info.h" #include "shared/source/memory_manager/memory_banks.h" #include "shared/source/os_interface/linux/engine_info.h" #include "shared/test/common/helpers/debug_manager_state_restore.h" #include "shared/test/common/helpers/default_hw_info.h" #include "shared/test/common/helpers/variable_backup.h" #include "shared/test/common/libult/linux/drm_mock_helper.h" #include "shared/test/common/libult/linux/drm_query_mock.h" #include "shared/test/common/test_macros/test.h" using namespace NEO; using DrmTestXeHPAndLater = ::testing::Test; using DrmTestXeHPCAndLater = ::testing::Test; TEST(DrmTest, givenEngineQuerySupportedWhenQueryingEngineInfoThenEngineInfoIsInitialized) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); ASSERT_NE(nullptr, drm); drm->queryEngineInfo(); auto haveLocalMemory = hwInfo->gtSystemInfo.MultiTileArchInfo.IsValid; EXPECT_EQ(haveLocalMemory ? 3u : 2u, drm->ioctlCallsCount); ASSERT_NE(nullptr, drm->engineInfo); auto renderEngine = EngineHelpers::remapEngineTypeToHwSpecific(aub_stream::EngineType::ENGINE_RCS, *hwInfo); auto engineInfo = drm->engineInfo.get(); auto pEngine = engineInfo->getEngineInstance(0, renderEngine); ASSERT_NE(nullptr, pEngine); EXPECT_EQ(I915_ENGINE_CLASS_RENDER, pEngine->engineClass); EXPECT_EQ(0, DrmMockHelper::getIdFromEngineOrMemoryInstance(pEngine->engineInstance)); EXPECT_EQ(0u, engineInfo->getEngineTileIndex(*pEngine)); auto numberOfCCS = hwInfo->gtSystemInfo.CCSInfo.NumberOfCCSEnabled; EXPECT_EQ(numberOfCCS > 0u, hwInfo->featureTable.flags.ftrCCSNode); for (auto i = 0u; i < numberOfCCS; i++) { auto engineType = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_CCS + i); pEngine = engineInfo->getEngineInstance(0, engineType); ASSERT_NE(nullptr, pEngine); EXPECT_EQ(DrmPrelimHelper::getComputeEngineClass(), pEngine->engineClass); EXPECT_EQ(i, DrmMockHelper::getIdFromEngineOrMemoryInstance(pEngine->engineInstance)); } pEngine = engineInfo->getEngineInstance(10, renderEngine); EXPECT_EQ(nullptr, pEngine); pEngine = engineInfo->getEngineInstance(42, aub_stream::ENGINE_CCS); EXPECT_EQ(nullptr, pEngine); pEngine = engineInfo->getEngineInstance(0, aub_stream::ENGINE_VECS); EXPECT_EQ(nullptr, pEngine); EngineClassInstance engineTest = {}; engineTest.engineClass = DrmPrelimHelper::getComputeEngineClass(); engineTest.engineInstance = 20; EXPECT_EQ(0u, engineInfo->getEngineTileIndex(engineTest)); } TEST(DrmTest, givenEngineQueryNotSupportedWhenQueryingEngineInfoThenFailGracefully) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); ASSERT_NE(nullptr, drm); drm->i915QuerySuccessCount = 0; drm->queryEngineInfo(); EXPECT_EQ(1u, drm->ioctlCallsCount); EXPECT_EQ(nullptr, drm->engineInfo); } TEST(DrmTest, givenMemRegionQueryNotSupportedWhenQueryingMemRegionInfoThenFailGracefully) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); ASSERT_NE(nullptr, drm); drm->i915QuerySuccessCount = 1; drm->queryEngineInfo(); EXPECT_EQ(2u, drm->ioctlCallsCount); EXPECT_EQ(nullptr, drm->engineInfo); } TEST(DrmTest, givenDistanceQueryNotSupportedWhenQueryingDistanceInfoThenFailGracefully) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); ASSERT_NE(nullptr, drm); drm->i915QuerySuccessCount = 2; drm->queryEngineInfo(); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); auto haveLocalMemory = hwInfo->gtSystemInfo.MultiTileArchInfo.IsValid; if (haveLocalMemory) { EXPECT_EQ(3u, drm->ioctlCallsCount); EXPECT_EQ(nullptr, drm->engineInfo); } else { EXPECT_EQ(2u, drm->ioctlCallsCount); EXPECT_NE(nullptr, drm->engineInfo); } } TEST(DrmTest, givenDistanceQueryFailsWhenQueryingDistanceInfoThenFailGracefully) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); ASSERT_NE(nullptr, drm); drm->context.failDistanceInfoQuery = true; drm->queryEngineInfo(); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); auto haveLocalMemory = hwInfo->gtSystemInfo.MultiTileArchInfo.IsValid; if (haveLocalMemory) { EXPECT_EQ(3u, drm->ioctlCallsCount); for (uint32_t i = 0; i < hwInfo->gtSystemInfo.MultiTileArchInfo.TileCount; i++) { EXPECT_NO_THROW(drm->memoryInfo->getMemoryRegionClassAndInstance((1 << i), *drm->context.hwInfo)); } } else { EXPECT_EQ(2u, drm->ioctlCallsCount); } } static void givenEngineTypeWhenBindingDrmContextThenContextParamEngineIsSet(std::unique_ptr<DrmQueryMock> &drm, aub_stream::EngineType engineType, uint16_t engineClass) { drm->queryEngineInfo(); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); auto haveLocalMemory = hwInfo->gtSystemInfo.MultiTileArchInfo.IsValid; EXPECT_EQ(haveLocalMemory ? 3u : 2u, drm->ioctlCallsCount); ASSERT_NE(nullptr, drm->engineInfo); auto drmContextId = 42u; auto engineFlag = drm->bindDrmContext(drmContextId, 0u, engineType, false); I915_DEFINE_CONTEXT_PARAM_ENGINES(enginesStruct, 1){}; EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(haveLocalMemory ? 4u : 3u, drm->ioctlCallsCount); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); EXPECT_EQ(ptrDiff(enginesStruct.engines + 1u, &enginesStruct), drm->receivedContextParamRequest.size); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_EQ(0ull, extensions); EXPECT_EQ(engineClass, drm->receivedContextParamEngines.engines[0].engine_class); EXPECT_EQ(0u, DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextParamEngines.engines[0].engine_instance)); } TEST(DrmTest, givenRcsEngineWhenBindingDrmContextThenContextParamEngineIsSet) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); auto renderEngine = EngineHelpers::remapEngineTypeToHwSpecific(aub_stream::EngineType::ENGINE_RCS, *hwInfo); givenEngineTypeWhenBindingDrmContextThenContextParamEngineIsSet(drm, renderEngine, I915_ENGINE_CLASS_RENDER); } static void givenBcsEngineTypeWhenBindingDrmContextThenContextParamEngineIsSet(std::unique_ptr<DrmQueryMock> &drm, aub_stream::EngineType engineType, size_t numBcsSiblings, unsigned int engineIndex, uint32_t tileId) { auto drmContextId = 42u; drm->receivedContextParamRequestCount = 0u; auto engineFlag = drm->bindDrmContext(drmContextId, tileId, engineType, false); EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_NE(0ull, extensions); EXPECT_EQ(ptrDiff(drm->receivedContextParamEngines.engines + 1 + numBcsSiblings, &drm->receivedContextParamEngines), drm->receivedContextParamRequest.size); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_INVALID), drm->receivedContextParamEngines.engines[0].engine_class); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_INVALID_NONE), drm->receivedContextParamEngines.engines[0].engine_instance); EXPECT_EQ(static_cast<__u32>(I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE), drm->receivedContextEnginesLoadBalance.base.name); EXPECT_EQ(numBcsSiblings, drm->receivedContextEnginesLoadBalance.num_siblings); for (auto balancedEngine = 0u; balancedEngine < numBcsSiblings; balancedEngine++) { EXPECT_EQ(I915_ENGINE_CLASS_COPY, drm->receivedContextEnginesLoadBalance.engines[balancedEngine].engine_class); auto engineInstance = engineIndex ? balancedEngine + 1 : balancedEngine; EXPECT_EQ(engineInstance, DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextEnginesLoadBalance.engines[balancedEngine].engine_instance)); EXPECT_EQ(I915_ENGINE_CLASS_COPY, drm->receivedContextParamEngines.engines[1 + balancedEngine].engine_class); EXPECT_EQ(engineInstance, DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextParamEngines.engines[1 + balancedEngine].engine_instance)); auto engineTile = DrmMockHelper::getTileFromEngineOrMemoryInstance(drm->receivedContextEnginesLoadBalance.engines[balancedEngine].engine_instance); EXPECT_EQ(engineTile, tileId); } } HWCMDTEST_F(IGFX_XE_HP_CORE, DrmTestXeHPAndLater, givenBcsEngineWhenBindingDrmContextThenContextParamEngineIsSet) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); givenEngineTypeWhenBindingDrmContextThenContextParamEngineIsSet(drm, aub_stream::ENGINE_BCS, I915_ENGINE_CLASS_COPY); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); EXPECT_EQ(1u, hwInfo->featureTable.ftrBcsInfo.to_ulong()); } HWCMDTEST_F(IGFX_XE_HP_CORE, DrmTestXeHPAndLater, givenLinkBcsEngineWhenBindingSingleTileDrmContextThenContextParamEngineIsSet) { HardwareInfo localHwInfo = *defaultHwInfo; localHwInfo.gtSystemInfo.MultiTileArchInfo.IsValid = false; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileCount = 0; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileMask = 0; auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0], &localHwInfo); drm->supportedCopyEnginesMask = maxNBitValue(9); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); EXPECT_EQ(drm->supportedCopyEnginesMask.count(), hwInfo->featureTable.ftrBcsInfo.count()); for (auto engineIndex = 0u; engineIndex < drm->supportedCopyEnginesMask.size(); engineIndex++) { auto engineType = aub_stream::ENGINE_BCS; auto numBcsSiblings = drm->supportedCopyEnginesMask.count(); if (engineIndex > 0) { engineType = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_BCS1 + engineIndex - 1); numBcsSiblings -= 1; } givenBcsEngineTypeWhenBindingDrmContextThenContextParamEngineIsSet(drm, engineType, numBcsSiblings, engineIndex, 0u); } } HWCMDTEST_F(IGFX_XE_HP_CORE, DrmTestXeHPAndLater, givenLinkBcsEngineWithoutMainCopyEngineWhenBindingSingleTileDrmContextThenContextParamEngineIsSet) { HardwareInfo localHwInfo = *defaultHwInfo; localHwInfo.gtSystemInfo.MultiTileArchInfo.IsValid = false; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileCount = 0; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileMask = 0; auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0], &localHwInfo); drm->supportedCopyEnginesMask = maxNBitValue(9); drm->supportedCopyEnginesMask.set(0, false); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); EXPECT_EQ(drm->supportedCopyEnginesMask.count(), hwInfo->featureTable.ftrBcsInfo.count()); for (auto engineIndex = 0u; engineIndex < drm->supportedCopyEnginesMask.size(); engineIndex++) { drm->receivedContextParamRequestCount = 0u; auto drmContextId = 42u; auto engineType = aub_stream::ENGINE_BCS; auto numBcsSiblings = drm->supportedCopyEnginesMask.count(); if (engineIndex > 0) { engineType = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_BCS1 + engineIndex - 1); numBcsSiblings -= 1; } auto engineFlag = drm->bindDrmContext(drmContextId, 0u, engineType, false); if (engineIndex == 0) { EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_BLT), engineFlag); EXPECT_EQ(0u, drm->receivedContextParamRequestCount); } else { EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_NE(0ull, extensions); EXPECT_EQ(ptrDiff(drm->receivedContextParamEngines.engines + 1 + numBcsSiblings, &drm->receivedContextParamEngines), drm->receivedContextParamRequest.size); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_INVALID), drm->receivedContextParamEngines.engines[0].engine_class); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_INVALID_NONE), drm->receivedContextParamEngines.engines[0].engine_instance); EXPECT_EQ(static_cast<__u32>(I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE), drm->receivedContextEnginesLoadBalance.base.name); EXPECT_EQ(numBcsSiblings, drm->receivedContextEnginesLoadBalance.num_siblings); } } } HWCMDTEST_F(IGFX_XE_HP_CORE, DrmTestXeHPAndLater, giveNotAllLinkBcsEnginesWhenBindingSingleTileDrmContextThenContextParamEngineIsSet) { HardwareInfo localHwInfo = *defaultHwInfo; localHwInfo.gtSystemInfo.MultiTileArchInfo.IsValid = false; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileCount = 0; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileMask = 0; auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0], &localHwInfo); drm->supportedCopyEnginesMask = maxNBitValue(9); drm->supportedCopyEnginesMask.set(2, false); drm->supportedCopyEnginesMask.set(7, false); drm->supportedCopyEnginesMask.set(8, false); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); EXPECT_EQ(drm->supportedCopyEnginesMask.count(), hwInfo->featureTable.ftrBcsInfo.count()); for (auto engineIndex = 0u; engineIndex < drm->supportedCopyEnginesMask.size(); engineIndex++) { auto numBcsSiblings = drm->supportedCopyEnginesMask.count(); auto engineType = aub_stream::ENGINE_BCS; if (engineIndex > 0) { engineType = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_BCS1 + engineIndex - 1); numBcsSiblings -= 1; } auto drmContextId = 42u; drm->receivedContextParamRequestCount = 0u; auto engineFlag = drm->bindDrmContext(drmContextId, 0u, engineType, false); if (drm->supportedCopyEnginesMask.test(engineIndex)) { EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_NE(0ull, extensions); EXPECT_EQ(ptrDiff(drm->receivedContextParamEngines.engines + 1 + numBcsSiblings, &drm->receivedContextParamEngines), drm->receivedContextParamRequest.size); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_INVALID), drm->receivedContextParamEngines.engines[0].engine_class); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_INVALID_NONE), drm->receivedContextParamEngines.engines[0].engine_instance); EXPECT_EQ(static_cast<__u32>(I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE), drm->receivedContextEnginesLoadBalance.base.name); EXPECT_EQ(numBcsSiblings, drm->receivedContextEnginesLoadBalance.num_siblings); } else { EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_BLT), engineFlag); EXPECT_EQ(0u, drm->receivedContextParamRequestCount); } } } HWCMDTEST_F(IGFX_XE_HP_CORE, DrmTestXeHPAndLater, givenLinkBcsEngineWhenBindingMultitileDrmContextThenContextParamEngineIsSet) { auto localHwInfo = *defaultHwInfo; localHwInfo.gtSystemInfo.MultiTileArchInfo.IsValid = true; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileCount = 4; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileMask = 0b1111; auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0], &localHwInfo); drm->supportedCopyEnginesMask = maxNBitValue(9); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); EXPECT_EQ(drm->supportedCopyEnginesMask.count(), hwInfo->featureTable.ftrBcsInfo.count()); for (auto tileId = 0; tileId < hwInfo->gtSystemInfo.MultiTileArchInfo.TileCount; tileId++) { for (auto engineIndex = 0u; engineIndex < drm->supportedCopyEnginesMask.count(); engineIndex++) { auto numBcsSiblings = drm->supportedCopyEnginesMask.count(); auto engineType = aub_stream::ENGINE_BCS; if (engineIndex > 0) { engineType = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_BCS1 + engineIndex - 1); numBcsSiblings -= 1; } givenBcsEngineTypeWhenBindingDrmContextThenContextParamEngineIsSet(drm, engineType, numBcsSiblings, engineIndex, static_cast<uint32_t>(tileId)); } } } HWTEST2_F(DrmTestXeHPCAndLater, givenBcsVirtualEnginesEnabledWhenCreatingContextThenEnableLoadBalancing, IsAtLeastXeHpcCore) { DebugManagerStateRestore restore; DebugManager.flags.UseDrmVirtualEnginesForBcs.set(1); HardwareInfo localHwInfo = *defaultHwInfo; localHwInfo.gtSystemInfo.MultiTileArchInfo.IsValid = false; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileCount = 0; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileMask = 0; auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0], &localHwInfo); drm->supportedCopyEnginesMask = maxNBitValue(9); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); EXPECT_EQ(drm->supportedCopyEnginesMask.count(), hwInfo->featureTable.ftrBcsInfo.count()); auto numBcs = drm->supportedCopyEnginesMask.count(); auto engineBase = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_BCS); auto numBcsSiblings = numBcs; for (auto engineIndex = 0u; engineIndex < numBcs; engineIndex++) { if (engineIndex > 0u) { engineBase = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_BCS1 - 1); numBcsSiblings = numBcs - 1; } auto engineType = static_cast<aub_stream::EngineType>(engineBase + engineIndex); givenBcsEngineTypeWhenBindingDrmContextThenContextParamEngineIsSet(drm, engineType, numBcsSiblings, engineIndex, 0u); } } HWTEST2_F(DrmTestXeHPCAndLater, givenBcsVirtualEnginesEnabledWhenCreatingContextThenEnableLoadBalancingLimitedToMaxCount, IsAtLeastXeHpcCore) { DebugManagerStateRestore restore; DebugManager.flags.UseDrmVirtualEnginesForBcs.set(1); DebugManager.flags.LimitEngineCountForVirtualBcs.set(3); HardwareInfo localHwInfo = *defaultHwInfo; localHwInfo.gtSystemInfo.MultiTileArchInfo.IsValid = false; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileCount = 0; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileMask = 0; auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0], &localHwInfo); drm->supportedCopyEnginesMask = maxNBitValue(9); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); EXPECT_EQ(drm->supportedCopyEnginesMask.count(), hwInfo->featureTable.ftrBcsInfo.count()); auto numBcs = 3u; auto engineBase = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_BCS); auto numBcsSiblings = numBcs; for (auto engineIndex = 0u; engineIndex < numBcs; engineIndex++) { if (engineIndex > 0u) { engineBase = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_BCS1 - 1); numBcsSiblings = numBcs - 1; } auto engineType = static_cast<aub_stream::EngineType>(engineBase + engineIndex); givenBcsEngineTypeWhenBindingDrmContextThenContextParamEngineIsSet(drm, engineType, numBcsSiblings, engineIndex, 0u); } } HWTEST2_F(DrmTestXeHPCAndLater, givenBcsVirtualEnginesDisabledWhenCreatingContextThenDisableLoadBalancing, IsAtLeastXeHpcCore) { DebugManagerStateRestore restore; DebugManager.flags.UseDrmVirtualEnginesForBcs.set(0); HardwareInfo localHwInfo = *defaultHwInfo; localHwInfo.gtSystemInfo.MultiTileArchInfo.IsValid = false; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileCount = 0; localHwInfo.gtSystemInfo.MultiTileArchInfo.TileMask = 0; auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0], &localHwInfo); ASSERT_NE(nullptr, drm); drm->supportedCopyEnginesMask = maxNBitValue(9); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); EXPECT_EQ(drm->supportedCopyEnginesMask.count(), hwInfo->featureTable.ftrBcsInfo.count()); auto numBcs = drm->supportedCopyEnginesMask.count(); auto engineBase = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_BCS); for (auto engineIndex = 0u; engineIndex < numBcs; engineIndex++) { if (engineIndex > 0u) { engineBase = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_BCS1 - 1); } drm->receivedContextParamRequestCount = 0u; auto drmContextId = 42u; auto engineType = static_cast<aub_stream::EngineType>(engineBase + engineIndex); auto engineFlag = drm->bindDrmContext(drmContextId, 0u, engineType, false); EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); EXPECT_EQ(ptrDiff(drm->receivedContextParamEngines.engines + 1, &drm->receivedContextParamEngines), drm->receivedContextParamRequest.size); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_EQ(0ull, extensions); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_COPY), drm->receivedContextParamEngines.engines[0].engine_class); EXPECT_EQ(static_cast<__u16>(engineIndex), DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextParamEngines.engines[0].engine_instance)); } } TEST(DrmTest, givenOneCcsEngineWhenBindingDrmContextThenContextParamEngineIsSet) { auto &ccsInfo = defaultHwInfo->gtSystemInfo.CCSInfo; if (ccsInfo.IsValid && ccsInfo.NumberOfCCSEnabled == 1u) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); givenEngineTypeWhenBindingDrmContextThenContextParamEngineIsSet(drm, aub_stream::ENGINE_CCS, DrmPrelimHelper::getComputeEngineClass()); } } TEST(DrmTest, givenVirtualEnginesEnabledWhenCreatingContextThenEnableLoadBalancing) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); auto &ccsInfo = drm->rootDeviceEnvironment.getMutableHardwareInfo()->gtSystemInfo.CCSInfo; ccsInfo.IsValid = true; ccsInfo.NumberOfCCSEnabled = 4; auto numberOfCCS = ccsInfo.NumberOfCCSEnabled; ASSERT_NE(nullptr, drm); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); for (auto engineIndex = 0u; engineIndex < numberOfCCS; engineIndex++) { drm->receivedContextParamRequestCount = 0u; auto drmContextId = 42u; auto engineType = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_CCS + engineIndex); auto engineFlag = drm->bindDrmContext(drmContextId, 0u, engineType, false); EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); EXPECT_EQ(ptrDiff(drm->receivedContextParamEngines.engines + 1 + numberOfCCS, &drm->receivedContextParamEngines), drm->receivedContextParamRequest.size); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_NE(0ull, extensions); EXPECT_EQ(static_cast<__u32>(I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE), drm->receivedContextEnginesLoadBalance.base.name); EXPECT_EQ(numberOfCCS, drm->receivedContextEnginesLoadBalance.num_siblings); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_INVALID), drm->receivedContextParamEngines.engines[0].engine_class); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_INVALID_NONE), drm->receivedContextParamEngines.engines[0].engine_instance); for (auto balancedEngine = 0u; balancedEngine < numberOfCCS; balancedEngine++) { EXPECT_EQ(DrmPrelimHelper::getComputeEngineClass(), drm->receivedContextEnginesLoadBalance.engines[balancedEngine].engine_class); EXPECT_EQ(balancedEngine, DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextEnginesLoadBalance.engines[balancedEngine].engine_instance)); EXPECT_EQ(DrmPrelimHelper::getComputeEngineClass(), drm->receivedContextParamEngines.engines[1 + balancedEngine].engine_class); EXPECT_EQ(balancedEngine, DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextParamEngines.engines[1 + balancedEngine].engine_instance)); } } } TEST(DrmTest, givenVirtualEnginesEnabledWhenCreatingContextThenEnableLoadBalancingOnlyBelowDebugVar) { DebugManagerStateRestore restorer; DebugManager.flags.LimitEngineCountForVirtualCcs.set(2); auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); auto &ccsInfo = drm->rootDeviceEnvironment.getMutableHardwareInfo()->gtSystemInfo.CCSInfo; ccsInfo.IsValid = true; ccsInfo.NumberOfCCSEnabled = 4; auto numberOfCCS = 2u; ASSERT_NE(nullptr, drm); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); for (auto engineIndex = 0u; engineIndex < numberOfCCS; engineIndex++) { drm->receivedContextParamRequestCount = 0u; auto drmContextId = 42u; auto engineType = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_CCS + engineIndex); auto engineFlag = drm->bindDrmContext(drmContextId, 0u, engineType, false); EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); EXPECT_EQ(ptrDiff(drm->receivedContextParamEngines.engines + 1 + numberOfCCS, &drm->receivedContextParamEngines), drm->receivedContextParamRequest.size); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_NE(0ull, extensions); EXPECT_EQ(static_cast<__u32>(I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE), drm->receivedContextEnginesLoadBalance.base.name); EXPECT_EQ(numberOfCCS, drm->receivedContextEnginesLoadBalance.num_siblings); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_INVALID), drm->receivedContextParamEngines.engines[0].engine_class); EXPECT_EQ(static_cast<__u16>(I915_ENGINE_CLASS_INVALID_NONE), drm->receivedContextParamEngines.engines[0].engine_instance); for (auto balancedEngine = 0u; balancedEngine < numberOfCCS; balancedEngine++) { EXPECT_EQ(DrmPrelimHelper::getComputeEngineClass(), drm->receivedContextEnginesLoadBalance.engines[balancedEngine].engine_class); EXPECT_EQ(balancedEngine, DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextEnginesLoadBalance.engines[balancedEngine].engine_instance)); EXPECT_EQ(DrmPrelimHelper::getComputeEngineClass(), drm->receivedContextParamEngines.engines[1 + balancedEngine].engine_class); EXPECT_EQ(balancedEngine, DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextParamEngines.engines[1 + balancedEngine].engine_instance)); } } } TEST(DrmTest, givenDisabledCcsSupportWhenQueryingThenResetHwInfoParams) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); drm->context.disableCcsSupport = true; auto hwInfo = drm->rootDeviceEnvironment.getMutableHardwareInfo(); hwInfo->gtSystemInfo.CCSInfo.IsValid = true; hwInfo->gtSystemInfo.CCSInfo.NumberOfCCSEnabled = 4; hwInfo->gtSystemInfo.CCSInfo.Instances.CCSEnableMask = 0b1111; hwInfo->capabilityTable.defaultEngineType = aub_stream::EngineType::ENGINE_CCS; drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); EXPECT_FALSE(hwInfo->gtSystemInfo.CCSInfo.IsValid); EXPECT_EQ(0u, hwInfo->gtSystemInfo.CCSInfo.NumberOfCCSEnabled); EXPECT_EQ(0u, hwInfo->gtSystemInfo.CCSInfo.Instances.CCSEnableMask); EXPECT_EQ(EngineHelpers::remapEngineTypeToHwSpecific(aub_stream::EngineType::ENGINE_RCS, *hwInfo), hwInfo->capabilityTable.defaultEngineType); } TEST(DrmTest, givenVirtualEnginesDisabledWhenCreatingContextThenDontEnableLoadBalancing) { DebugManagerStateRestore restore; DebugManager.flags.UseDrmVirtualEnginesForCcs.set(0); auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); auto &ccsInfo = drm->rootDeviceEnvironment.getMutableHardwareInfo()->gtSystemInfo.CCSInfo; ccsInfo.IsValid = true; ccsInfo.NumberOfCCSEnabled = 4; auto numberOfCCS = ccsInfo.NumberOfCCSEnabled; ASSERT_NE(nullptr, drm); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); for (auto engineIndex = 0u; engineIndex < numberOfCCS; engineIndex++) { drm->receivedContextParamRequestCount = 0u; auto drmContextId = 42u; auto engineType = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_CCS + engineIndex); auto engineFlag = drm->bindDrmContext(drmContextId, 0u, engineType, false); EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); EXPECT_EQ(ptrDiff(drm->receivedContextParamEngines.engines + 1, &drm->receivedContextParamEngines), drm->receivedContextParamRequest.size); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_EQ(0ull, extensions); EXPECT_EQ(static_cast<__u16>(DrmPrelimHelper::getComputeEngineClass()), drm->receivedContextParamEngines.engines[0].engine_class); EXPECT_EQ(static_cast<__u16>(engineIndex), DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextParamEngines.engines[0].engine_instance)); } } TEST(DrmTest, givenEngineInstancedDeviceWhenCreatingContextThenDontUseVirtualEngines) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); auto &ccsInfo = drm->rootDeviceEnvironment.getMutableHardwareInfo()->gtSystemInfo.CCSInfo; ccsInfo.IsValid = true; ccsInfo.NumberOfCCSEnabled = 4; auto numberOfCCS = ccsInfo.NumberOfCCSEnabled; ASSERT_NE(nullptr, drm); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); for (auto engineIndex = 0u; engineIndex < numberOfCCS; engineIndex++) { drm->receivedContextParamRequestCount = 0u; auto drmContextId = 42u; auto engineType = static_cast<aub_stream::EngineType>(aub_stream::ENGINE_CCS + engineIndex); auto engineFlag = drm->bindDrmContext(drmContextId, 0u, engineType, true); EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); EXPECT_EQ(ptrDiff(drm->receivedContextParamEngines.engines + 1, &drm->receivedContextParamEngines), drm->receivedContextParamRequest.size); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_EQ(0ull, extensions); EXPECT_EQ(static_cast<__u16>(DrmPrelimHelper::getComputeEngineClass()), drm->receivedContextParamEngines.engines[0].engine_class); EXPECT_EQ(static_cast<__u16>(engineIndex), DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextParamEngines.engines[0].engine_instance)); } } TEST(DrmTest, givenVirtualEnginesEnabledAndNotEnoughCcsEnginesWhenCreatingContextThenDontEnableLoadBalancing) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); auto &ccsInfo = drm->rootDeviceEnvironment.getMutableHardwareInfo()->gtSystemInfo.CCSInfo; ccsInfo.IsValid = true; ccsInfo.NumberOfCCSEnabled = 1; drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); drm->receivedContextParamRequestCount = 0u; auto drmContextId = 42u; auto engineFlag = drm->bindDrmContext(drmContextId, 0u, aub_stream::ENGINE_CCS, false); EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); EXPECT_EQ(ptrDiff(drm->receivedContextParamEngines.engines + 1, &drm->receivedContextParamEngines), drm->receivedContextParamRequest.size); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_EQ(0ull, extensions); EXPECT_EQ(DrmPrelimHelper::getComputeEngineClass(), drm->receivedContextParamEngines.engines[0].engine_class); EXPECT_EQ(0, DrmMockHelper::getIdFromEngineOrMemoryInstance(drm->receivedContextParamEngines.engines[0].engine_instance)); } TEST(DrmTest, givenVirtualEnginesEnabledAndNonCcsEnginesWhenCreatingContextThenDontEnableLoadBalancing) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); drm->rootDeviceEnvironment.getMutableHardwareInfo()->featureTable.ftrBcsInfo = 1; drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); drm->receivedContextParamRequestCount = 0u; auto drmContextId = 42u; auto engineFlag = drm->bindDrmContext(drmContextId, 0u, aub_stream::ENGINE_BCS, false); EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(1u, drm->receivedContextParamRequestCount); EXPECT_EQ(drmContextId, drm->receivedContextParamRequest.ctx_id); EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_ENGINES), drm->receivedContextParamRequest.param); EXPECT_EQ(ptrDiff(drm->receivedContextParamEngines.engines + 1, &drm->receivedContextParamEngines), drm->receivedContextParamRequest.size); auto extensions = drm->receivedContextParamEngines.extensions; EXPECT_EQ(0ull, extensions); EXPECT_EQ(I915_ENGINE_CLASS_COPY, drm->receivedContextParamEngines.engines[0].engine_class); } TEST(DrmTest, givenInvalidTileWhenBindingDrmContextThenErrorIsReturned) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); ASSERT_NE(nullptr, drm); drm->queryEngineInfo(); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); auto haveLocalMemory = hwInfo->gtSystemInfo.MultiTileArchInfo.IsValid; EXPECT_EQ(haveLocalMemory ? 3u : 2u, drm->ioctlCallsCount); ASSERT_NE(nullptr, drm->engineInfo); auto engineFlag = drm->bindDrmContext(42u, 20u, aub_stream::ENGINE_CCS, false); EXPECT_EQ(static_cast<unsigned int>(I915_EXEC_DEFAULT), engineFlag); EXPECT_EQ(haveLocalMemory ? 3u : 2u, drm->ioctlCallsCount); EXPECT_EQ(0u, drm->receivedContextParamRequestCount); } TEST(DrmTest, givenInvalidEngineTypeWhenBindingDrmContextThenExceptionIsThrown) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); ASSERT_NE(nullptr, drm); drm->queryEngineInfo(); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); auto haveLocalMemory = hwInfo->gtSystemInfo.MultiTileArchInfo.IsValid; EXPECT_EQ(haveLocalMemory ? 3u : 2u, drm->ioctlCallsCount); ASSERT_NE(nullptr, drm->engineInfo); EXPECT_THROW(drm->bindDrmContext(42u, 0u, aub_stream::ENGINE_VCS, false), std::exception); EXPECT_EQ(haveLocalMemory ? 3u : 2u, drm->ioctlCallsCount); EXPECT_EQ(0u, drm->receivedContextParamRequestCount); } TEST(DrmTest, givenSetParamEnginesFailsWhenBindingDrmContextThenCallUnrecoverable) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); ASSERT_NE(nullptr, drm); drm->queryEngineInfo(); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); auto haveLocalMemory = hwInfo->gtSystemInfo.MultiTileArchInfo.IsValid; EXPECT_EQ(haveLocalMemory ? 3u : 2u, drm->ioctlCallsCount); ASSERT_NE(nullptr, drm->engineInfo); auto renderEngine = EngineHelpers::remapEngineTypeToHwSpecific(aub_stream::EngineType::ENGINE_RCS, *hwInfo); drm->storedRetValForSetParamEngines = -1; auto drmContextId = 42u; EXPECT_ANY_THROW(drm->bindDrmContext(drmContextId, 0u, renderEngine, false)); } TEST(DrmTest, whenQueryingEngineInfoThenMultiTileArchInfoIsUnchanged) { auto originalMultiTileArchInfo = defaultHwInfo->gtSystemInfo.MultiTileArchInfo; auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); ASSERT_NE(nullptr, drm); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); auto hwInfo = drm->rootDeviceEnvironment.getHardwareInfo(); EXPECT_EQ(originalMultiTileArchInfo.IsValid, hwInfo->gtSystemInfo.MultiTileArchInfo.IsValid); auto tileCount = hwInfo->gtSystemInfo.MultiTileArchInfo.TileCount; EXPECT_EQ(originalMultiTileArchInfo.TileCount, tileCount); auto tileMask = hwInfo->gtSystemInfo.MultiTileArchInfo.TileMask; EXPECT_EQ(originalMultiTileArchInfo.TileMask, tileMask); } TEST(DrmTest, givenNewMemoryInfoQuerySupportedWhenQueryingEngineInfoThenEngineInfoIsInitialized) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get()); auto drm = std::make_unique<DrmQueryMock>(*executionEnvironment->rootDeviceEnvironments[0]); ASSERT_NE(nullptr, drm); drm->queryEngineInfo(); EXPECT_NE(nullptr, drm->engineInfo); } struct DistanceQueryDrmTests : ::testing::Test { struct MyDrm : DrmQueryMock { using DrmQueryMock::DrmQueryMock; bool supportDistanceInfoQuery = true; bool handleQueryItem(void *arg) override { auto *queryItem = reinterpret_cast<drm_i915_query_item *>(arg); if (queryItem->query_id == DrmPrelimHelper::getDistanceInfoQueryId() && !supportDistanceInfoQuery) { queryItem->length = -EINVAL; return true; // successful query with incorrect length } return DrmQueryMock::handleQueryItem(queryItem); } }; void SetUp() override { executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); rootDeviceEnvironment = executionEnvironment->rootDeviceEnvironments[0].get(); rootDeviceEnvironment->setHwInfo(NEO::defaultHwInfo.get()); } std::unique_ptr<MyDrm> createDrm(bool supportDistanceInfoQuery) { auto drm = std::make_unique<MyDrm>(*rootDeviceEnvironment, rootDeviceEnvironment->getHardwareInfo()); drm->supportDistanceInfoQuery = supportDistanceInfoQuery; return drm; } void setTileCount(size_t tileCount) { GT_MULTI_TILE_ARCH_INFO &multiTileArch = rootDeviceEnvironment->getMutableHardwareInfo()->gtSystemInfo.MultiTileArchInfo; multiTileArch.IsValid = (tileCount > 0); multiTileArch.TileCount = tileCount; multiTileArch.TileMask = static_cast<uint8_t>(maxNBitValue(tileCount)); } void verifyEngineInfo(const Drm &drm) { GT_MULTI_TILE_ARCH_INFO &multiTileArch = rootDeviceEnvironment->getMutableHardwareInfo()->gtSystemInfo.MultiTileArchInfo; const uint32_t tileCount = multiTileArch.IsValid ? multiTileArch.TileCount : 1u; std::vector<size_t> engineCounts(tileCount); auto engineInfo = drm.getEngineInfo(); for (uint32_t tile = 0; tile < tileCount; tile++) { std::vector<EngineClassInstance> engines = {}; engineInfo->getListOfEnginesOnATile(tile, engines); engineCounts[tile] = engines.size(); EXPECT_NE(0u, engines.size()); } const bool areAllTilesEqual = std::equal(engineCounts.begin(), engineCounts.end(), engineCounts.begin()); EXPECT_TRUE(areAllTilesEqual); } std::unique_ptr<ExecutionEnvironment> executionEnvironment; RootDeviceEnvironment *rootDeviceEnvironment; }; HWTEST_F(DistanceQueryDrmTests, givenDistanceQueryNotSupportedWhenQueryingEngineInfoThen) { setTileCount(0); auto drm = createDrm(false); EXPECT_TRUE(drm->queryEngineInfo()); verifyEngineInfo(*drm); setTileCount(1); drm = createDrm(false); EXPECT_TRUE(drm->queryEngineInfo()); verifyEngineInfo(*drm); } HWTEST_F(DistanceQueryDrmTests, givenDistanceQuerySupportedAndZeroTilesWhenQueryingEngineInfoThen) { setTileCount(0); auto drm = createDrm(true); EXPECT_TRUE(drm->queryEngineInfo()); verifyEngineInfo(*drm); } HWTEST_F(DistanceQueryDrmTests, givenDistanceQuerySupportedAndTilesDetectedWhenQueryingEngineInfoThen) { setTileCount(1); auto drm = createDrm(true); EXPECT_TRUE(drm->queryEngineInfo()); verifyEngineInfo(*drm); setTileCount(4); drm = createDrm(true); EXPECT_TRUE(drm->queryEngineInfo()); verifyEngineInfo(*drm); }
56.207898
217
0.765265
mattcarter2017
671387e41a1459fa690a29216fb91c5abdb61996
2,669
cpp
C++
src/mainwindow/searchwidget/searchwidget.cpp
fengleyl/NetEase
1dbcea741bd294da633233c766b24113c293f94e
[ "MIT" ]
35
2015-06-18T14:11:46.000Z
2020-12-01T10:06:17.000Z
src/mainwindow/searchwidget/searchwidget.cpp
StevennyZhang/NetEase
1dbcea741bd294da633233c766b24113c293f94e
[ "MIT" ]
1
2015-09-15T13:09:58.000Z
2016-05-09T05:47:24.000Z
src/mainwindow/searchwidget/searchwidget.cpp
StevennyZhang/NetEase
1dbcea741bd294da633233c766b24113c293f94e
[ "MIT" ]
10
2015-05-28T15:19:18.000Z
2018-06-26T17:54:31.000Z
#include "searchwidget.h" #include "../../toolwidgets/funcbutton.h" #include "../../configure/configure.h" #include "../../toolwidgets/titlewidget.h" #include <QLineEdit> #include <QHBoxLayout> #include <QCheckBox> #include <QLabel> SearchWidget::SearchWidget(QWidget *parent) : BasedWidget(parent) { setFixedSize(searchWidgetSize); setObjectName("SearchWidget"); initUi(); initConnect(); } void SearchWidget::searchClicked() { QString _search = m_searLineEdit->text(); if (!m_musicSearch->isChecked() || (_search == "")) return; emit search(_search); hide(); } void SearchWidget::initUi() { m_title = new TitleWidget(false, this); m_title->setFixedSize(searchTitleSize); m_title->move(0, 0); FuncButton *searchButton = new FuncButton(":/buttons/search_btn", this); connect(searchButton, SIGNAL(clicked()), this, SLOT(searchClicked())); searchButton->setCapturEnterEvent(false); m_searLineEdit = new QLineEdit(this); m_searLineEdit->setFixedWidth(searchWidgetSize.width() * 0.85); QHBoxLayout *searLayout = new QHBoxLayout; searLayout->addWidget(m_searLineEdit, 0, Qt::AlignLeft | Qt::AlignVCenter); searLayout->addWidget(searchButton, 0, Qt::AlignVCenter); searLayout->addStretch(); m_musicSearch = new QCheckBox("单曲搜索", this); m_aritlsSearch = new QCheckBox("歌手搜索", this); m_albumSearch = new QCheckBox("专辑搜索", this); m_lyricSearch = new QCheckBox("歌词搜索", this); m_listsSearch = new QCheckBox("歌单搜索", this); m_ownerSearch = new QCheckBox("主播电台", this); m_musicSearch->setChecked(true); QHBoxLayout *searCheck1 = new QHBoxLayout; searCheck1->addWidget(m_musicSearch, 0, Qt::AlignLeft | Qt::AlignVCenter); searCheck1->addWidget(m_aritlsSearch, 0, Qt::AlignVCenter); searCheck1->addWidget(m_albumSearch, 0, Qt::AlignRight | Qt::AlignVCenter); searCheck1->setContentsMargins(0, 5, 5, 0); QHBoxLayout *searCheck2 = new QHBoxLayout; searCheck2->addWidget(m_listsSearch, 0, Qt::AlignLeft | Qt::AlignVCenter); searCheck2->addWidget(m_lyricSearch, 0, Qt::AlignVCenter); searCheck2->addWidget(m_ownerSearch, 0, Qt::AlignRight | Qt::AlignVCenter); searCheck2->setContentsMargins(0, 5, 5, 0); QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->addSpacing(searchTitleSize.height() + 10); mainLayout->addLayout(searLayout); mainLayout->addLayout(searCheck1); mainLayout->addLayout(searCheck2); QLabel *label = new QLabel("<font color='red' size=5>当前只实现单曲查找...</font>", this); mainLayout->addWidget(label, 0, Qt::AlignRight | Qt::AlignVCenter); mainLayout->setContentsMargins(10, 0, 10, 10); } void SearchWidget::initConnect() { connect(m_title, SIGNAL(closeClicked()), this, SLOT(hide())); }
26.959596
82
0.736231
fengleyl
671469a337c114745eed61415549e82732f8f9f0
2,016
hpp
C++
app/ui/GLCanvas.hpp
modelflat/fractalexplorer
b2799362851b830ab8e9f69d9c3178785a9757c6
[ "MIT" ]
null
null
null
app/ui/GLCanvas.hpp
modelflat/fractalexplorer
b2799362851b830ab8e9f69d9c3178785a9757c6
[ "MIT" ]
null
null
null
app/ui/GLCanvas.hpp
modelflat/fractalexplorer
b2799362851b830ab8e9f69d9c3178785a9757c6
[ "MIT" ]
null
null
null
#ifndef FRACTALEXPLORER_GLCANVAS_HPP #define FRACTALEXPLORER_GLCANVAS_HPP #include <QOpenGLWidget> #include <QOpenGLContext> #include <QOpenGLFunctions> #include <QOpenGLTexture> #include <CL/cl.hpp> class OpenCLBackend { public: cl::Context currentContext(); bool interoperableWith(QOpenGLContext* context); }; class OpenCLImageWidget : public QOpenGLWidget { std::shared_ptr<OpenCLBackend> backend_; public: OpenCLImageWidget(std::shared_ptr<OpenCLBackend> backend); cl::Image& image(); protected: virtual void initializeGL() { auto* glContext = QOpenGLContext::currentContext(); if (backend_->interoperableWith(glContext)) { GLuint image = backend_.acquireImage(image_); // redraw fast using GL interop redrawGLImage(); // backend_.releaseImage(image_); } else { ??? image = backend_.acquireImageNoInterop(image_); // redraw copied buffer backend_.releaseImageNoInterop(image_); } } virtual void resizeGL(int w, int h) { } virtual void paintGL() { } private: void redrawGLImage(); }; using real = double; class GLCanvas : public QOpenGLWidget { Settings settings; cl::CommandQueue queue; cl::Context clContext; cl::ImageGL imageCL; QOpenGLTexture* texture; bool saveScreenshotOnce = false; unsigned int postClearProgram; unsigned int program; unsigned int vertexBufferObject; NewtonKernelWrapper newtonKernelWrapper; ClearKernelWrapper clearKernelWrapper; std::vector<int> buffer; size_t width_, height_; void initCLSide(QOpenGLContext* context); void initGLSide(QOpenGLFunctions* gl, std::vector<int>& buffer); public: void initWithCL(cl::Context); protected: virtual void initializeGL() override; virtual void resizeGL(int w, int h) override; virtual void paintGL() override; }; #endif //FRACTALEXPLORER_GLCANVAS_HPP
18.841121
68
0.68006
modelflat
671ea385c2c5126f4431115cc0ae6dc31637162f
351
hpp
C++
include/hit.hpp
core-exe/NonEuclideanRayTracing
4316fa118af6b29c86c99bd4d863dfba1f089c7c
[ "MIT" ]
1
2021-12-02T06:25:54.000Z
2021-12-02T06:25:54.000Z
include/hit.hpp
core-exe/NonEuclideanRayTracing
4316fa118af6b29c86c99bd4d863dfba1f089c7c
[ "MIT" ]
null
null
null
include/hit.hpp
core-exe/NonEuclideanRayTracing
4316fa118af6b29c86c99bd4d863dfba1f089c7c
[ "MIT" ]
null
null
null
# pragma once # include <vecmath.h> # include <vector> using namespace std; class Texture; class Ray4; class Hit4 { public: float t; vector<Ray4> ray_out; Vector3f hit_pos_texture, normal; float in_cosine; float importance; vector<float> out_cosine, out_importance; Texture* hit_texture; Hit4(); ~Hit4(){} };
17.55
45
0.663818
core-exe
672261b07327a8154e56225ac3937413a9ece764
606
cpp
C++
project2D/main.cpp
Jeffrey-W23/AIE-CodeFolio
c1820d0a228a6111011b2d10daf885753e6d302d
[ "MIT" ]
null
null
null
project2D/main.cpp
Jeffrey-W23/AIE-CodeFolio
c1820d0a228a6111011b2d10daf885753e6d302d
[ "MIT" ]
null
null
null
project2D/main.cpp
Jeffrey-W23/AIE-CodeFolio
c1820d0a228a6111011b2d10daf885753e6d302d
[ "MIT" ]
null
null
null
#include "Application2D.h" #include <crtdbg.h> #include <iostream> #include "FunctionPointerExampleClass.h" using namespace std; // Function pointer example //void Cat(float cat) //{ // cout << "Your number is: " << cat << endl; //} int main() { // Function pointer example /*FunctionPointerExampleClass tc; tc.SetFunction(&Cat); tc.Callfunction();*/ // Memory leak check _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // allocation auto app = new Application2D(); // initialise and loop app->run("AIE", 1280, 720, false); // deallocation delete app; return 0; }
18.363636
62
0.691419
Jeffrey-W23
6724a7c1abb8283e5b0b2f8e7ab9f19db08ed470
1,285
cc
C++
code/addons/ui/ceui/ceuirendertarget.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/addons/ui/ceui/ceuirendertarget.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/addons/ui/ceui/ceuirendertarget.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // ceuirendertarget.cc // (C) 2009 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "sui/ceui/ceuirendertarget.h" namespace CEUI { //------------------------------------------------------------------------------ /** */ CEUIRenderTarget::CEUIRenderTarget(const CEUIRenderer& owner) : area(CEGUI::Point(),CEGUI::Size()), owner(owner) { // empty } //------------------------------------------------------------------------------ /** */ CEUIRenderTarget::~CEUIRenderTarget() { // empty } //------------------------------------------------------------------------------ /** */ void CEUIRenderTarget::activate() { //n_error("NOT yet implemented!\n"); } //------------------------------------------------------------------------------ /** */ void CEUIRenderTarget::deactivate() { //n_error("NOT yet implemented!\n"); } //------------------------------------------------------------------------------ /** */ void CEUIRenderTarget::unprojectPoint(const CEGUI::GeometryBuffer& buff, const CEGUI::Vector2& p_in, CEGUI::Vector2& p_out) const { n_error("NOT yet implemented!\n"); } } // namespace CEUI
22.54386
124
0.368872
gscept
67310c8e9d82d6c1af1ab0467aef425e2cc0ccf0
2,567
cpp
C++
modules/svg/src/SkSVGFeMorphology.cpp
borodust/skia
bbbf1a7f50a303bd76163793bd5968c72f5f4432
[ "BSD-3-Clause" ]
1
2022-03-10T08:41:28.000Z
2022-03-10T08:41:28.000Z
modules/svg/src/SkSVGFeMorphology.cpp
borodust/skia
bbbf1a7f50a303bd76163793bd5968c72f5f4432
[ "BSD-3-Clause" ]
null
null
null
modules/svg/src/SkSVGFeMorphology.cpp
borodust/skia
bbbf1a7f50a303bd76163793bd5968c72f5f4432
[ "BSD-3-Clause" ]
1
2021-06-06T21:31:52.000Z
2021-06-06T21:31:52.000Z
/* * Copyright 2020 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/effects/SkImageFilters.h" #include "modules/svg/include/SkSVGAttributeParser.h" #include "modules/svg/include/SkSVGFeMorphology.h" #include "modules/svg/include/SkSVGFilterContext.h" #include "modules/svg/include/SkSVGRenderContext.h" #include "modules/svg/include/SkSVGValue.h" bool SkSVGFeMorphology::parseAndSetAttribute(const char* name, const char* value) { return INHERITED::parseAndSetAttribute(name, value) || this->setOperator(SkSVGAttributeParser::parse<SkSVGFeMorphology::Operator>( "operator", name, value)) || this->setRadius(SkSVGAttributeParser::parse<SkSVGFeMorphology::Radius>( "radius", name, value)); } sk_sp<SkImageFilter> SkSVGFeMorphology::onMakeImageFilter(const SkSVGRenderContext& ctx, const SkSVGFilterContext& fctx) const { const SkRect cropRect = this->resolveFilterSubregion(ctx, fctx); const SkSVGColorspace colorspace = this->resolveColorspace(ctx, fctx); sk_sp<SkImageFilter> input = fctx.resolveInput(ctx, this->getIn(), colorspace); SkScalar rx = fRadius.fX; SkScalar ry = fRadius.fY; if (fctx.primitiveUnits().type() == SkSVGObjectBoundingBoxUnits::Type::kObjectBoundingBox) { SkASSERT(ctx.node()); const SkRect objBounds = ctx.node()->objectBoundingBox(ctx); rx *= objBounds.width(); ry *= objBounds.height(); } switch (fOperator) { case Operator::kErode: return SkImageFilters::Erode(rx, ry, input, cropRect); case Operator::kDilate: return SkImageFilters::Dilate(rx, ry, input, cropRect); } SkUNREACHABLE; } template <> bool SkSVGAttributeParser::parse<SkSVGFeMorphology::Operator>(SkSVGFeMorphology::Operator* op) { static constexpr std::tuple<const char*, SkSVGFeMorphology::Operator> gMap[] = { { "dilate", SkSVGFeMorphology::Operator::kDilate }, { "erode" , SkSVGFeMorphology::Operator::kErode }, }; return this->parseEnumMap(gMap, op) && this->parseEOSToken(); } template <> bool SkSVGAttributeParser::parse<SkSVGFeMorphology::Radius>(SkSVGFeMorphology::Radius* radius) { std::vector<SkSVGNumberType> values; if (!this->parse(&values)) { return false; } radius->fX = values[0]; radius->fY = values.size() > 1 ? values[1] : values[0]; return true; }
37.202899
97
0.671601
borodust
67387605a1294603125aacc297fc5aa5a4f5f963
2,199
cpp
C++
#23_merge-k-sorted-lists/merge-k-sorted-lists.cpp
o-oppang/lets-solve-algorithm
9983a112736ce48bbd309a9af16d1fd68b9420da
[ "MIT" ]
null
null
null
#23_merge-k-sorted-lists/merge-k-sorted-lists.cpp
o-oppang/lets-solve-algorithm
9983a112736ce48bbd309a9af16d1fd68b9420da
[ "MIT" ]
null
null
null
#23_merge-k-sorted-lists/merge-k-sorted-lists.cpp
o-oppang/lets-solve-algorithm
9983a112736ce48bbd309a9af16d1fd68b9420da
[ "MIT" ]
null
null
null
/** * 23. Merge k Sorted Lists ( Hard ) * You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. * Merge all the linked-lists into one sorted linked-list and return it. */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { if( lists.size() == 0 ) return nullptr; ListNode* dest = nullptr; for(auto node : lists) { if( node == nullptr ) continue; if( dest == nullptr ) dest = sorting( node ); else dest = mergeList(dest, sorting( node )); } return dest; } private: ListNode* sorting(ListNode* node) { auto next = node->next; node->next = nullptr; return mergeList( node, next ); } ListNode* mergeList(ListNode* dest, ListNode* target) { // dest와 target은 sorting 되어 들어온다고 가정 assert( dest != nullptr ); auto lDest = dest, lTarget = target; while( lTarget != nullptr) { if( lDest->val > lTarget->val ) { // lTarget이 작은 경우 lTarget의 뒤에 lDest를 붙혀줌 auto tmp = lTarget->next; lTarget->next = lDest; dest = lDest = lTarget; lTarget = tmp; } else if(lDest -> next == nullptr) { // lDest가 소진된 경우 lTarget을 뒤에 다 붙혀줌 lDest->next = lTarget; break; } else if( lDest->next->val >= lTarget->val ) { // lDest의 뒤에 lTarget을 붙혀줌 auto tmp = lTarget->next; lTarget->next = lDest->next; lDest->next = lTarget; lTarget = tmp; } else { // 추가되지 못하는 경우 lDest = lDest->next; } } return dest; } }; // Runtime: 144 ms, faster than 25.45% of C++ online submissions for Merge k Sorted Lists. // Memory Usage: 13.3 MB, less than 5.28% of C++ online submissions for Merge k Sorted Lists.
35.467742
97
0.541155
o-oppang
6746207e4c2949611f3fe85db7b038171125f1c0
149
cpp
C++
src/outputs/Output.cpp
neogenie/iqlogger
7a3866046dd30282a35ce954dc4fd301452aa924
[ "Apache-2.0" ]
1
2020-08-17T12:22:36.000Z
2020-08-17T12:22:36.000Z
src/outputs/Output.cpp
neogenie/iqlogger
7a3866046dd30282a35ce954dc4fd301452aa924
[ "Apache-2.0" ]
null
null
null
src/outputs/Output.cpp
neogenie/iqlogger
7a3866046dd30282a35ce954dc4fd301452aa924
[ "Apache-2.0" ]
null
null
null
// // Output.cpp // ~~~~~~~~~~~~~~~~ // // Copyright (C) 2018 IQOption Software, Inc. // // #include "Output.h" using namespace iqlogger::outputs;
12.416667
45
0.57047
neogenie
67538b3be230df90eab6dc178121b3ea773f0e37
10,534
cpp
C++
development/Common/Utility/source/sqlite/SQLite.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
null
null
null
development/Common/Utility/source/sqlite/SQLite.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
44
2018-06-28T03:01:44.000Z
2022-03-20T19:53:00.000Z
development/Common/Utility/source/sqlite/SQLite.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
null
null
null
#include "sqlite/SQLite.h" #include "sqlite/sqlite3.h" #include "App/AppUtilities.h" #include "App/FileUtilities.h" #include "Fmt/format.h" #include "Logger/YLog.h" #include "Streams/Guid.h" namespace { int SqlQueryCallback(void *userData, int argc, char **argv, char **columnNames) { if (userData) { yaget::SQLite::QueryCallback *callback = static_cast<yaget::SQLite::QueryCallback*>(userData); return (*callback)(argc, argv, columnNames); } else { return -1; } } } // namespace yaget::SQLite::SQLite() : mDatabase(nullptr) { } yaget::SQLite::~SQLite() { Close(); } bool yaget::SQLite::Open(const char* fileName, DatabaseType openDatabaseAsType, InitializeSchema_t initializeSchemaCallback) { const bool serializedModel = false; mErrorMessage = ""; Close(); int dbFlags = serializedModel ? SQLITE_OPEN_FULLMUTEX : 0; if (openDatabaseAsType == DatabaseType::New) { dbFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; if (io::file::IsFileExists(fileName) && std::remove(fileName) != 0) { mErrorMessage = fmt::format("Could not delete SQLite Database: '{}'.", fileName); return false; } } else if (openDatabaseAsType == DatabaseType::Append || openDatabaseAsType == DatabaseType::InMemory) { dbFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; } else { dbFlags |= SQLITE_OPEN_READONLY; } int result = sqlite3_open_v2(fileName, &mDatabase, dbFlags, NULL); if (result == SQLITE_OK) { ExecuteStatement("PRAGMA foreign_keys = ON;", nullptr); Batcher batcher(*this); if (initializeSchemaCallback && initializeSchemaCallback(*this, mDatabase)) { YLOG_INFO("SQL", "SQLite Database '%s' created. Version: '%s'", fileName, SQLITE_VERSION); } else { result = SQLITE_ERROR; if (mErrorMessage.empty()) { mErrorMessage = fmt::format("Could not initialize Database Schema: '{}'. {}", fileName, sqlite3_errmsg(mDatabase)); } Close(); } } else { mErrorMessage = fmt::format("Could not open/create SQLite Database: '{}'. Error: '{}'.", fileName, sqlite3_errmsg(mDatabase)); Close(); } return result == SQLITE_OK; } void yaget::SQLite::Close() { for (auto&& it : mStatements) { Statement& statement = it.second; sqlite3_finalize(statement.mStm); statement.mStm = nullptr; } mStatements.clear(); sqlite3_close(mDatabase); mDatabase = nullptr; } bool yaget::SQLite::ExecuteStatement(const std::string& command, QueryCallback *callback) { YAGET_ASSERT(mDatabase, ("SQLite::ExecuteStatement: '%s' called, but sqlite db is not created yet.", command.c_str())); mErrorMessage = ""; bool result = false; if (mDatabase) { if (command.size() < SQLite::MAX_COMMAND_LEN) { char* errorTest = nullptr; int execResult = sqlite3_exec(mDatabase, command.c_str(), (callback ? SqlQueryCallback : nullptr), callback, &errorTest); if (execResult == SQLITE_OK || execResult == SQLITE_ABORT) { sqlite3_free(errorTest); result = true; } else { mErrorMessage = fmt::format("Last command: {}. Error: {}", command.c_str(), errorTest ? errorTest : ""); sqlite3_free(errorTest); result = false; } } else { mErrorMessage = fmt::format("Command '%s' with len: '{}' exceeded size limit. Maximum length of command is '{}'.", command.c_str(), command.size(), SQLite::MAX_COMMAND_LEN); result = false; } } else { mErrorMessage = fmt::format("Error executing command {}. There is no Database created.", command.c_str()); result = false; } return result; } void yaget::SQLite::StatementBinder<yaget::null_marker_t>::Bind(sqlite3* database, sqlite3_stmt* statement, yaget::null_marker_t /*value*/, int index) { int result = sqlite3_bind_null(statement, index); const char* errorMessage = sqlite3_errmsg(database); YAGET_ASSERT(result == SQLITE_OK, "Bind null statement failed: %s.", errorMessage ? errorMessage : ""); } void yaget::SQLite::StatementBinder<int>::Bind(sqlite3* database, sqlite3_stmt* statement, int value, int index) { int result = sqlite3_bind_int(statement, index, value); const char* errorMessage = sqlite3_errmsg(database); YAGET_ASSERT(result == SQLITE_OK, "Bind int statement failed: %s.", errorMessage ? errorMessage : ""); } void yaget::SQLite::StatementBinder<int64_t>::Bind(sqlite3* database, sqlite3_stmt* statement, int64_t value, int index) { int result = sqlite3_bind_int64(statement, index, value); const char* errorMessage = sqlite3_errmsg(database);; YAGET_ASSERT(result == SQLITE_OK, "Bind int statement failed: %s.", errorMessage ? errorMessage : ""); } void yaget::SQLite::StatementBinder<uint64_t>::Bind(sqlite3* database, sqlite3_stmt* statement, uint64_t value, int index) { StatementBinder<int64_t>::Bind(database, statement, static_cast<int64_t>(value), index); //int result = sqlite3_bind_int64(statement, index, value); //const char* errorMessage = sqlite3_errmsg(database);; //YAGET_ASSERT(result == SQLITE_OK, "Bind int statement failed: %s.", errorMessage ? errorMessage : ""); } void yaget::SQLite::StatementBinder<bool>::Bind(sqlite3* database, sqlite3_stmt* statement, bool value, int index) { int result = sqlite3_bind_int(statement, index, value); const char* errorMessage = sqlite3_errmsg(database); YAGET_ASSERT(result == SQLITE_OK, "Bind bool (int) statement failed: %s.", errorMessage ? errorMessage : ""); } void yaget::SQLite::StatementBinder<float>::Bind(sqlite3* database, sqlite3_stmt* statement, float value, int index) { int result = sqlite3_bind_double(statement, index, value); const char* errorMessage = sqlite3_errmsg(database); YAGET_ASSERT(result == SQLITE_OK, "Bind float statement failed: %s.", errorMessage ? errorMessage : ""); } void yaget::SQLite::StatementBinder<yaget::Guid>::Bind(sqlite3* database, sqlite3_stmt* statement, yaget::Guid value, int index) { StatementBinder<std::string>::Bind(database, statement, value.str(), index); } void yaget::SQLite::StatementBinder<std::vector<std::string>>::Bind(sqlite3* database, sqlite3_stmt* statement, const std::vector<std::string>& value, int index) { StatementBinder<std::string>::Bind(database, statement, conv::Convertor<std::vector<std::string>>::ToString(value), index); } void yaget::SQLite::StatementBinder<math3d::Vector3>::Bind(sqlite3* database, sqlite3_stmt* statement, const math3d::Vector3& value, int index) { StatementBinder<std::string>::Bind(database, statement, conv::Convertor<math3d::Vector3>::ToString(value), index); } void yaget::SQLite::StatementBinder<math3d::Quaternion>::Bind(sqlite3* database, sqlite3_stmt* statement, const math3d::Quaternion& value, int index) { StatementBinder<std::string>::Bind(database, statement, conv::Convertor<math3d::Quaternion>::ToString(value), index); } void yaget::SQLite::StatementBinder<std::string>::Bind(sqlite3* database, sqlite3_stmt* statement, const std::string& value, int index) { int result = sqlite3_bind_text(statement, index, value.c_str(), -1, SQLITE_TRANSIENT); const char* errorMessage = sqlite3_errmsg(database); YAGET_ASSERT(result == SQLITE_OK, "Bind string statement failed: %s.", errorMessage ? errorMessage : ""); } yaget::SQLite::Statement::Statement(sqlite3* database, const std::string& command) : mDatabase(database) { int result = sqlite3_prepare_v2(mDatabase, command.c_str(), static_cast<int>(command.size()), &mStm, 0); const char* errorMessage = sqlite3_errmsg(mDatabase); YAGET_ASSERT(result == SQLITE_OK, "SQLite Statement prepare failed: %s.", errorMessage ? errorMessage : ""); } void yaget::SQLite::Statement::ResetBindings() { sqlite3_reset(mStm); sqlite3_clear_bindings(mStm); } bool yaget::SQLite::ExecuteStatement(Statement* statement) { int result = sqlite3_step(statement->mStm); if (result == SQLITE_OK || result == SQLITE_DONE) { return true; } mErrorMessage = fmt::format("Execute prepared statement error: {}", sqlite3_errmsg(mDatabase)); return false; } std::vector<std::string> yaget::SQLite::GetErrors() const { std::vector<std::string> errors; if (mErrorMessage.size()) { errors.push_back(mErrorMessage); } return errors; } bool yaget::SQLite::Backup(const char *fileName) const { sqlite3* pFile = nullptr;; int rc = sqlite3_open(fileName, &pFile); if (rc == SQLITE_OK) { if (sqlite3_backup* pBackup = sqlite3_backup_init(pFile, "main", mDatabase, "main")) { sqlite3_backup_step(pBackup, -1); sqlite3_backup_finish(pBackup); return true; } } return false; } void yaget::SQLite::Log(const std::string& messageType, const std::string& message) { using LogRecord = std::tuple<std::string /*Type*/, std::string /*Message*/, std::string /*SessionId*/>; LogRecord logRecord(messageType, message, util::ApplicationRuntimeId().str()); ExecuteStatementTuple("MessageAdd", "Logs", logRecord, { "Type", "Message", "SessionId" }, SQLite::Behaviour::Insert, SQLite::TimeStamp::Yes); } //------------------------------------------------------------------------------------------------------------------------------------ yaget::db::Transaction::Transaction(SQLite& database) : mDatabase(database) { const auto result = mDatabase.ExecuteStatement("BEGIN", nullptr); YAGET_ASSERT(result, "BEGIN TRANSCATION failed. %s", ParseErrors(mDatabase).c_str()); } void yaget::db::Transaction::Rollback() { mCommit = false; } yaget::db::Transaction::~Transaction() { if (mCommit) { const auto result = mDatabase.ExecuteStatement("END", nullptr); YAGET_ASSERT(result, "END TRANSCATION failed. %s", ParseErrors(mDatabase).c_str()); } else { const auto result = mDatabase.ExecuteStatement("ROLLBACK", nullptr); YAGET_ASSERT(result, "ROLLBACK TRANSCATION failed. %s", ParseErrors(mDatabase).c_str()); } }
34.424837
185
0.652459
eglowacki
6755552a13c79f2dbe55e83976f2454a2a579638
219
cpp
C++
docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_27.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_27.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_27.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
// typedef CStringT<TCHAR, StrTraitATL<TCHAR, ChTraitsCRT<TCHAR>>> CAtlString; CAtlString s1(_T("cat")), s2(_T("f")), s3(_T("horse")); ASSERT(s1 != _T("dog")); ASSERT(s2 != _T('t')); ASSERT(s1 != s2);
36.5
81
0.579909
bobbrow
675ffdb41a930477058ac8772f50e43697f1f2c4
610
cpp
C++
test/rrt_test.cpp
mxgrey/ccrrt
28680511e8f212ad8a771ea3b1af8214027b765c
[ "BSD-3-Clause" ]
3
2019-03-13T09:54:04.000Z
2019-08-04T17:40:08.000Z
test/rrt_test.cpp
mxgrey/ccrrt
28680511e8f212ad8a771ea3b1af8214027b765c
[ "BSD-3-Clause" ]
null
null
null
test/rrt_test.cpp
mxgrey/ccrrt
28680511e8f212ad8a771ea3b1af8214027b765c
[ "BSD-3-Clause" ]
null
null
null
#include "../ccrrt/RRTManager.h" #include "../ccrrt/Drawer.h" using namespace ccrrt; int main(int argc, char* argv[]) { RRTManager rrt; Eigen::VectorXd limits(2); limits << 5, 5; rrt.setDomain(-limits,limits); Eigen::VectorXd p(2); p << -3, 0; rrt.addStartTree(p); p << 3, -1; rrt.addGoalTree(p); RRT_Result_t result = RRT_NOT_FINISHED; while(RRT_NOT_FINISHED == result) { result = rrt.growTrees(); std::cout << result << std::endl; } Drawer draw; draw.draw_rrts(rrt); draw.run(); return 0; }
17.428571
43
0.555738
mxgrey
67676117e12d8cb226bc4886ca81a51d9f5386c1
1,468
hpp
C++
libs/python/include/python/network/py_tcp_client.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
3
2019-07-11T08:49:27.000Z
2021-09-07T16:49:15.000Z
libs/python/include/python/network/py_tcp_client.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
null
null
null
libs/python/include/python/network/py_tcp_client.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
2
2019-07-13T12:45:22.000Z
2021-03-12T08:48:57.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "network/tcp_client.hpp" #include "fetch_pybind.hpp" namespace fetch { namespace network { void BuildTCPClient(pybind11::module &module) { namespace py = pybind11; py::class_<TCPClient>(module, "TCPClient") .def(py::init<const std::string &, const std::string &, fetch::network::TCPClient::network_manager_ptr_type>()) .def(py::init<const std::string &, const uint16_t &, fetch::network::TCPClient::network_manager_ptr_type>()) .def("handle", &TCPClient::handle) .def("Send", &TCPClient::Send) .def("Address", &TCPClient::Address); } }; // namespace network }; // namespace fetch
35.804878
80
0.604905
devjsc
676afc7bf136f0770c816ad9f7537d4669d1688c
383
cpp
C++
cpp03/cpp03_set_get_data.cpp
ValentinoVizner/CPP_OpenCV_Playground
809fa501e056cddeb9e0af3cb7f0ba0925f389d0
[ "MIT" ]
null
null
null
cpp03/cpp03_set_get_data.cpp
ValentinoVizner/CPP_OpenCV_Playground
809fa501e056cddeb9e0af3cb7f0ba0925f389d0
[ "MIT" ]
null
null
null
cpp03/cpp03_set_get_data.cpp
ValentinoVizner/CPP_OpenCV_Playground
809fa501e056cddeb9e0af3cb7f0ba0925f389d0
[ "MIT" ]
null
null
null
#include <string> class Student { public: Student(int id, std::string name) : id_{id}, name_{name} {} // This is initializer list int id() const { return id_; } const std::string & name() const // whatever you do after this const all private variables will be // interpreted as const { return name_; } private: int id_; std::string name_; };
22.529412
80
0.629243
ValentinoVizner
676d789ff76dba0c7526723b3d58fc42d1a90c2c
8,756
cpp
C++
methods/mexDenseSIFT/Matrix.cpp
jjcharles/personalizedpose
227086992f198c04f30923f21b1e74a807f261f0
[ "CC-BY-4.0" ]
null
null
null
methods/mexDenseSIFT/Matrix.cpp
jjcharles/personalizedpose
227086992f198c04f30923f21b1e74a807f261f0
[ "CC-BY-4.0" ]
null
null
null
methods/mexDenseSIFT/Matrix.cpp
jjcharles/personalizedpose
227086992f198c04f30923f21b1e74a807f261f0
[ "CC-BY-4.0" ]
null
null
null
#include "Matrix.h" #include "memory.h" #include <iostream> using namespace std; bool Matrix::IsDispInfo=false; Matrix::Matrix(void) { nRow=nCol=0; pData=NULL; } Matrix::Matrix(int nrow,int ncol,double* data) { nRow=nrow; nCol=ncol; pData=new double[nRow*nCol]; if(data==NULL) memset(pData,0,sizeof(double)*nRow*nCol); else memcpy(pData,data,sizeof(double)*nRow*nCol); } Matrix::Matrix(const Matrix& matrix) { nRow=nCol=0; pData=NULL; copyData(matrix); } Matrix::~Matrix(void) { releaseData(); } void Matrix::releaseData() { if(pData!=NULL) delete pData; pData=NULL; nRow=nCol=0; } void Matrix::copyData(const Matrix &matrix) { if(!dimMatch(matrix)) allocate(matrix); memcpy(pData,matrix.pData,sizeof(double)*nRow*nCol); } bool Matrix::dimMatch(const Matrix& matrix) const { if(nCol==matrix.nCol && nRow==matrix.nRow) return true; else return false; } bool Matrix::dimcheck(const Matrix& matrix) const { if(!dimMatch(matrix)) { cout<<"The dimensions of the matrices don't match!"<<endl; return false; } return true; } void Matrix::reset() { if(pData!=NULL) memset(pData,0,sizeof(double)*nRow*nCol); } void Matrix::allocate(int nrow,int ncol) { releaseData(); nRow=nrow; nCol=ncol; if(nRow*nCol>0) pData=new double[nRow*nCol]; } void Matrix::allocate(const Matrix& matrix) { allocate(matrix.nRow,matrix.nCol); } void Matrix::loadData(int _nrow, int _ncol, double *data) { if(!matchDimension(_nrow,_ncol)) allocate(_nrow,_ncol); memcpy(pData,data,sizeof(double)*nRow*nCol); } void Matrix::printMatrix() { for(int i=0;i<nRow;i++) { for(int j=0;j<nCol;j++) cout<<pData[i*nCol+j]<<" "; cout<<endl; } } void Matrix::identity(int ndim) { allocate(ndim,ndim); reset(); for(int i=0;i<ndim;i++) pData[i*ndim+i]=1; } //-------------------------------------------------------------------------------------------------- // functions to check dimensionalities //-------------------------------------------------------------------------------------------------- bool Matrix::checkDimRight(const Vector& vect) const { if(nCol==vect.dim()) return true; else { cout<<"The matrix and vector don't match in multiplication!"<<endl; return false; } } bool Matrix::checkDimRight(const Matrix &matrix) const { if(nCol==matrix.nrow()) return true; else { cout<<"The matrix and matrix don't match in multiplication!"<<endl; return false; } } bool Matrix::checkDimLeft(const Vector& vect) const { if(nRow==vect.dim()) return true; else { cout<<"The vector and matrix don't match in multiplication!"<<endl; return false; } } bool Matrix::checkDimLeft(const Matrix &matrix) const { if(nRow==matrix.ncol()) return true; else { cout<<"The matrix and matrix don't match in multiplication!"<<endl; return false; } } //-------------------------------------------------------------------------------------------------- // functions for numerical computation //-------------------------------------------------------------------------------------------------- void Matrix::Multiply(Vector &result, const Vector &vect) const { checkDimRight(vect); if(result.dim()!=nRow) result.allocate(nRow); for(int i=0;i<nRow;i++) { double temp=0; for(int j=0;j<nCol;j++) temp+=pData[i*nCol+j]*vect.data()[j]; result.data()[i]=temp; } } void Matrix::Multiply(Matrix &result, const Matrix &matrix) const { checkDimRight(matrix); if(!result.matchDimension(nRow,matrix.nCol)) result.allocate(nRow,matrix.nCol); for(int i=0;i<nRow;i++) for(int j=0;j<matrix.nCol;j++) { double temp=0; for(int k=0;k<nCol;k++) temp+=pData[i*nCol+k]*matrix.pData[k*matrix.nCol+j]; result.pData[i*matrix.nCol+j]=temp; } } void Matrix::transpose(Matrix &result) const { if(!result.matchDimension(nCol,nRow)) result.allocate(nCol,nRow); for(int i=0;i<nCol;i++) for(int j=0;j<nRow;j++) result.pData[i*nRow+j]=pData[j*nCol+i]; } void Matrix::fromVector(const Vector &vect) { if(!matchDimension(vect.dim(),1)) allocate(vect.dim(),1); memcpy(pData,vect.data(),sizeof(double)*vect.dim()); } double Matrix::norm2() const { if(pData==NULL) return 0; double temp=0; for(int i=0;i<nCol*nRow;i++) temp+=pData[i]*pData[i]; return temp; } //-------------------------------------------------------------------------------------------------- // operators //-------------------------------------------------------------------------------------------------- Matrix& Matrix::operator=(const Matrix& matrix) { copyData(matrix); return *this; } Matrix& Matrix::operator +=(double val) { for(int i=0;i<nCol*nRow;i++) pData[i]+=val; return *this; } Matrix& Matrix::operator -=(double val) { for(int i=0;i<nCol*nRow;i++) pData[i]-=val; return *this; } Matrix& Matrix::operator *=(double val) { for(int i=0;i<nCol*nRow;i++) pData[i]*=val; return *this; } Matrix& Matrix::operator /=(double val) { for(int i=0;i<nCol*nRow;i++) pData[i]/=val; return *this; } Matrix& Matrix::operator +=(const Matrix &matrix) { dimcheck(matrix); for(int i=0;i<nCol*nRow;i++) pData[i]+=matrix.pData[i]; return *this; } Matrix& Matrix::operator -=(const Matrix &matrix) { dimcheck(matrix); for(int i=0;i<nCol*nRow;i++) pData[i]-=matrix.pData[i]; return *this; } Matrix& Matrix::operator *=(const Matrix &matrix) { dimcheck(matrix); for(int i=0;i<nCol*nRow;i++) pData[i]*=matrix.pData[i]; return *this; } Matrix& Matrix::operator /=(const Matrix &matrix) { dimcheck(matrix); for(int i=0;i<nCol*nRow;i++) pData[i]/=matrix.pData[i]; return *this; } Vector operator*(const Matrix& matrix,const Vector& vect) { Vector result; matrix.Multiply(result,vect); return result; } Matrix operator*(const Matrix& matrix1,const Matrix& matrix2) { Matrix result; matrix1.Multiply(result,matrix2); return result; } //-------------------------------------------------------------------------------------------------- // function for conjugate gradient method //-------------------------------------------------------------------------------------------------- void Matrix::ConjugateGradient(Vector &result, const Vector &b) const { if(nCol!=nRow) { cout<<"Error: when solving Ax=b, A is not square!"<<endl; return; } checkDimRight(b); if(!result.matchDimension(b)) result.allocate(b); Vector r(b),p,q; result.reset(); int nIterations=nRow*5; Vector rou(nIterations); for(int k=0;k<nIterations;k++) { rou[k]=r.norm2(); if(IsDispInfo) cout<<rou[k]<<endl; if(rou[k]<1E-20) break; if(k==0) p=r; else { double ratio=rou[k]/rou[k-1]; p=r+p*ratio; } Multiply(q,p); double alpha=rou[k]/innerproduct(p,q); result+=p*alpha; r-=q*alpha; } } void Matrix::SolveLinearSystem(Vector &result, const Vector &b) const { if(nCol==nRow) { ConjugateGradient(result,b); return; } if(nRow<nCol) { cout<<"Not enough observations for parameter estimation!"<<endl; return; } Matrix AT,ATA; transpose(AT); AT.Multiply(ATA,*this); Vector ATb; AT.Multiply(ATb,b); ATA.ConjugateGradient(result,ATb); } #ifdef _QT bool Matrix::writeMatrix(QFile &file) const { file.write((char *)&nRow,sizeof(int)); file.write((char *)&nCol,sizeof(int)); if(file.write((char *)pData,sizeof(double)*nRow*nCol)!=sizeof(double)*nRow*nCol) return false; return true; } bool Matrix::readMatrix(QFile &file) { releaseData(); file.read((char *)&nRow,sizeof(int)); file.read((char *)&nCol,sizeof(int)); if(nRow*nCol>0) { allocate(nRow,nCol); if(file.read((char *)pData,sizeof(double)*nRow*nCol)!=sizeof(double)*nRow*nCol) return false; } return true; } #endif #ifdef _MATLAB void Matrix::readMatrix(const mxArray* prhs) { if(pData!=NULL) delete pData; int nElements = mxGetNumberOfDimensions(prhs); if(nElements>2) mexErrMsgTxt("A matrix is expected to be loaded!"); const int* dims = mxGetDimensions(prhs); allocate(dims[0],dims[1]); double* data = (double*)mxGetData(prhs); for(int i =0; i<nRow; i++) for(int j =0; j<nCol; j++) pData[i*nCol+j] = data[j*nRow+i]; } void Matrix::writeMatrix(mxArray*& plhs) const { int dims[2]; dims[0]=nRow;dims[1]=nCol; plhs=mxCreateNumericArray(2, dims,mxDOUBLE_CLASS, mxREAL); double* data = (double *)mxGetData(plhs); for(int i =0; i<nRow; i++) for(int j =0; j<nCol; j++) data[j*nRow+i] = pData[i*nCol+j]; } #endif
20.897375
101
0.578917
jjcharles
67704a83d1179d9c9b142d0448c1cf3198edae79
3,251
hpp
C++
source/modus_core/window/ContextSettings.hpp
Gurman8r/modus
5c97a89f77c1c5733793dddc20c5ce4afe1fd134
[ "MIT" ]
null
null
null
source/modus_core/window/ContextSettings.hpp
Gurman8r/modus
5c97a89f77c1c5733793dddc20c5ce4afe1fd134
[ "MIT" ]
null
null
null
source/modus_core/window/ContextSettings.hpp
Gurman8r/modus
5c97a89f77c1c5733793dddc20c5ce4afe1fd134
[ "MIT" ]
null
null
null
#ifndef _ML_CONTEXT_SETTINGS_HPP_ #define _ML_CONTEXT_SETTINGS_HPP_ #include <modus_core/detail/Debug.hpp> // CONTEXT API namespace ml { // context api enum context_api_ : int32 { context_api_unknown , // unknown context_api_opengl , // opengl context_api_vulkan , // vulkan context_api_directx , // directx }; inline void from_json(json const & j, context_api_ & v) { if (j.is_number()) { v = (context_api_)j.get<int32>(); } else if (j.is_string()) { switch (auto const s{ j.get<string>() }; hashof(util::to_lower(s))) { case hashof("unknown" ): v = context_api_unknown ; break; case hashof("opengl" ): v = context_api_opengl ; break; case hashof("vulkan" ): v = context_api_vulkan ; break; case hashof("directx" ): v = context_api_directx ; break; } } } inline void to_json(json & j, context_api_ const & v) { switch (v) { case context_api_unknown: j = "unknown" ; break; case context_api_opengl : j = "opengl" ; break; case context_api_vulkan : j = "vulkan" ; break; case context_api_directx: j = "directx" ; break; } } } // CONTEXT PROFILE namespace ml { // context profile enum context_profile_ : int32 { context_profile_any , // any context_profile_core , // core context_profile_compat , // compat context_profile_debug , // debug }; inline void from_json(json const & j, context_profile_ & v) { if (j.is_number()) { v = (context_profile_)j.get<int32>(); } else if (j.is_string()) { switch (auto const s{ j.get<string>() }; hashof(util::to_lower(s))) { case hashof("any" ): v = context_profile_any ; break; case hashof("core" ): v = context_profile_core ; break; case hashof("compat"): v = context_profile_compat ; break; case hashof("debug" ): v = context_profile_debug ; break; } } } inline void to_json(json & j, context_profile_ const & v) { switch (v) { case context_profile_any : j = "any" ; break; case context_profile_core : j = "core" ; break; case context_profile_compat : j = "compat" ; break; case context_profile_debug : j = "debug" ; break; } } } // CONTEXT SETTINGS namespace ml { // context settings struct ML_NODISCARD context_settings { int32 api { context_api_opengl }; int32 major { 4 }; int32 minor { 6 }; int32 profile { context_profile_compat }; int32 depth_bits { 24 }; int32 stencil_bits { 8 }; bool multisample { true }; bool srgb_capable { false }; }; inline void from_json(json const & j, context_settings & v) { j["api" ].get_to((context_api_ & )v.api); j["major" ].get_to(v.major); j["minor" ].get_to(v.minor); j["profile" ].get_to((context_profile_ &)v.profile); j["depth_bits" ].get_to(v.depth_bits); j["stencil_bits"].get_to(v.stencil_bits); j["multisample" ].get_to(v.multisample); j["srgb_capable"].get_to(v.srgb_capable); } inline void to_json(json & j, context_settings const & v) { j["api" ] = (context_api_)v.api; j["major" ] = v.major; j["minor" ] = v.minor; j["profile" ] = (context_profile_)v.profile; j["depth_bits" ] = v.depth_bits; j["stencil_bits"] = v.stencil_bits; j["multisample" ] = v.multisample; j["srgb_capable"] = v.srgb_capable; } } #endif // !_ML_CONTEXT_SETTINGS_HPP_
26.008
70
0.659797
Gurman8r
677c04cae633e9411c2f70475228865b36925f76
104
cpp
C++
src/Aurora/Logger/Logger.cpp
sjuhyeon/Aurora
9a6249bcac9beb0ac9792137b522160156e1dd71
[ "MIT" ]
1
2022-02-23T17:42:51.000Z
2022-02-23T17:42:51.000Z
src/Aurora/Logger/Logger.cpp
sjuhyeon/Aurora
9a6249bcac9beb0ac9792137b522160156e1dd71
[ "MIT" ]
null
null
null
src/Aurora/Logger/Logger.cpp
sjuhyeon/Aurora
9a6249bcac9beb0ac9792137b522160156e1dd71
[ "MIT" ]
null
null
null
#include "Logger.hpp" namespace Aurora { std::vector<std::shared_ptr<Logger::Sink>> Logger::m_Sinks; }
17.333333
60
0.730769
sjuhyeon
677c767e7b81159817a8e8fe88d0d995ccd9da9e
151
cpp
C++
src/graph/graph.cpp
mangosroom/cv-graph
6c02cf196b2b05ddc55d6b3285f471d4cd0146ab
[ "Apache-2.0" ]
null
null
null
src/graph/graph.cpp
mangosroom/cv-graph
6c02cf196b2b05ddc55d6b3285f471d4cd0146ab
[ "Apache-2.0" ]
null
null
null
src/graph/graph.cpp
mangosroom/cv-graph
6c02cf196b2b05ddc55d6b3285f471d4cd0146ab
[ "Apache-2.0" ]
null
null
null
/** * @file graph.cpp * @author mango (2321544362@qq.com) * @brief * @version 0.1 * @date 2021-12-08 * * @copyright Copyright (c) 2021 * */
15.1
36
0.576159
mangosroom
6784f28ecd14de5c41038861fbd16307438f3fa1
2,925
hpp
C++
lib/atlas/server/async/SecureSession.hpp
aphenriques/atlas
9967f58005015a39ece8f7dfdfa91d45759dd042
[ "MIT" ]
null
null
null
lib/atlas/server/async/SecureSession.hpp
aphenriques/atlas
9967f58005015a39ece8f7dfdfa91d45759dd042
[ "MIT" ]
null
null
null
lib/atlas/server/async/SecureSession.hpp
aphenriques/atlas
9967f58005015a39ece8f7dfdfa91d45759dd042
[ "MIT" ]
null
null
null
// // server/async/SecureSession.hpp // atlas // // MIT License // // Copyright (c) 2021 André Pereira Henriques (aphenriques (at) outlook (dot) 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 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 atlas_server_async_SecureSession_hpp #define atlas_server_async_SecureSession_hpp #include <boost/beast/core/tcp_stream.hpp> #include <boost/beast/ssl/ssl_stream.hpp> #include "SessionBase.hpp" namespace atlas::server::async { class SecureSession : public SessionBase<SecureSession, boost::beast::ssl_stream<boost::beast::tcp_stream>> { public: SecureSession(boost::asio::ip::tcp::socket &&socket, boost::asio::ssl::context &sslContext); template<typename OnHandshake> void asyncHandshake(OnHandshake &&onHandshake); template<typename OnShutdown> void asyncShutdown(OnShutdown &&onShutdown); }; //-- template<typename OnHandshake> void SecureSession::SecureSession::asyncHandshake(OnHandshake &&onHandshake) { getStream().async_handshake( boost::asio::ssl::stream_base::server, [ sessionSharedPointer = this->shared_from_this(), // attention! forwarded onHandshake onHandshakeCopy = std::forward<OnHandshake>(onHandshake) ](boost::system::error_code errorCode) { onHandshakeCopy(*sessionSharedPointer, errorCode); } ); } template<typename OnShutdown> void SecureSession::asyncShutdown(OnShutdown &&onShutdown) { getStream().async_shutdown( [ sessionSharedPointer = this->shared_from_this(), // attention! forwarded onShutdown onCloseCopy = std::forward<OnShutdown>(onShutdown) ](boost::system::error_code errorCode) { onCloseCopy(errorCode); } ); } } #endif
37.987013
113
0.689573
aphenriques
6785490ffa3d8ed95f0c05c6bfe7a74b3c19f822
8,348
cpp
C++
src/krnl/term.cpp
maximsmol/nos
386b4166b3fd1701b734bfcd50ace1b9e1ea38ee
[ "MIT" ]
1
2019-04-29T05:10:52.000Z
2019-04-29T05:10:52.000Z
src/krnl/term.cpp
maximsmol/nos
386b4166b3fd1701b734bfcd50ace1b9e1ea38ee
[ "MIT" ]
null
null
null
src/krnl/term.cpp
maximsmol/nos
386b4166b3fd1701b734bfcd50ace1b9e1ea38ee
[ "MIT" ]
1
2021-12-06T23:49:27.000Z
2021-12-06T23:49:27.000Z
#include "hpp/term.hpp" #include <stdarg.h> #include "hpp/typ.hpp" namespace term { static int posX; static int posY; static volatile char* vmem_woffset; void clear() { vmem_woffset = vmem_base; for (int x = 0; x < width; ++x) for (int y = 0; y < height; ++y) { *vmem_woffset++ = ' '; *vmem_woffset++ = 7; } posX = 0; posY = 0; vmem_woffset = vmem_base; } void clearLine() { moveAbs(0, posY); for (int x = 0; x < width; ++x) { *vmem_woffset++ = ' '; *vmem_woffset++ = 7; } moveAbs(0, posY); } void init() { posX = 0; posY = 0; vmem_woffset = vmem_base; } int getX() { return posX; } int getY() { return posY; } void moveAbs(int x, int y) { posX = x%width; posY = y%height + x/width; vmem_woffset = vmem_base + (posY*width + posX)*2; // (char, style) } void moveRel(int dx, int dy) { moveAbs(posX+dx, posY+dy); } void nl() { moveAbs(0, posY+1); } void putch(const char c) { if (c == '\n') { nl(); return; } else if (c == '\r') { moveAbs(0, posY); return; } *vmem_woffset++ = c; *vmem_woffset++ = 7; moveRel(1, 0); } void puts(const char* str) { while (*str != '\0') putch(*str++); } constexpr char lcase_alphabet[] = "0123456789abcdef"; constexpr char ucase_alphabet[] = "0123456789ABCDEF"; template<class T, const char* alphabet = lcase_alphabet> typ::enable_if< typ::unsigned_::pred<T> > putnum(T x, const T base = 10) { // if (base == 16) // puts("0x"); // else if (base == 2) // puts("0b"); if (x == 0) putch('0'); else { // if (base == 8) // putch('0'); volatile char* start = vmem_woffset; for (;x > 0; x /= base) putch(alphabet[x%base]); // reverse the number volatile char* cur = vmem_woffset-2; /*take last char*/ while (cur > start) { char tmp = *cur; *cur = *start; *start = tmp; cur -= 2; /*(char, style)*/ start += 2; } } } template<class T, const char* alphabet = lcase_alphabet> typ::enable_if< typ::signed_::pred<T> > putnum(const T x, const T base = 10) { using unsignedT = typ::unsigned_::make<T>; if (x >= 0) { putnum<unsignedT, alphabet>(static_cast<unsignedT>(x), static_cast<unsignedT>(base)); return; } putch('-'); putnum<unsignedT, alphabet>(static_cast<unsignedT>(-x), static_cast<unsignedT>(base)); } template void putnum<signed char>(signed char x, const signed char base); template void putnum<short>(short x, const short base); template void putnum<int>(int x, const int base); template void putnum<long>(long x, const long base); // template void putnum<long long>(long long x, const long long base); template void putnum<unsigned char>(unsigned char x, const unsigned char base); template void putnum<unsigned short>(unsigned short x, const unsigned short base); template void putnum<unsigned int>(unsigned int x, const unsigned int base); template void putnum<unsigned long>(unsigned long x, const unsigned long base); // template void putnum<unsigned long long>(unsigned long long x, const unsigned long long base); void putsln(const char* str) { puts(str); putch('\n'); } void printf(const char* fmt...) { va_list args; va_start(args, fmt); for (;*fmt != '\0'; ++fmt) { if (*fmt == '%') { ++fmt; bool ljustify = false; bool force_sign = false; bool alt = false; bool padw0 = false; while (true) { if (*fmt == '-') ljustify = true; else if (*fmt == '+') force_sign = true; else if (*fmt == '#') alt = true; else if (*fmt == '0') padw0 = true; else break; ++fmt; } int minw = -1; if (*fmt == '*') { minw = va_arg(args, int); ++fmt; } else if ('0' <= *fmt && *fmt <= '9') { minw = 0; while ('0' <= *fmt && *fmt <= '9') { minw *= 10; minw += *fmt - '0'; ++fmt; } } int prec = -1; if (*fmt == '.') { prec = 0; ++fmt; if (*fmt == '*') { prec = va_arg(args, int); ++fmt; } else while ('0' <= *fmt && *fmt <= '9') { prec *= 10; prec += *fmt - '0'; ++fmt; } } bool hh = false; bool h = false; bool l = false; bool ll = false; if (*fmt == 'h') { h = true; ++fmt; if (*fmt == 'h') { hh = true; ++fmt; } } else if (*fmt == 'l') { l = true; ++fmt; if (*fmt == 'l') { ll = true; ++fmt; } } // // note: va_args: types < int as targets are undefbeh // if (*fmt == '%') putch('%'); else if (*fmt == 'c') putch( static_cast<const char>(va_arg(args, int)) ); else if (*fmt == 's') puts(va_arg(args, const char*)); else if (*fmt == 'd' || *fmt == 'i') { if (hh) putnum<signed char>( static_cast<signed char>(va_arg(args, int)) ); else if (h) putnum<short>( static_cast<short>(va_arg(args, int)) ); // else if (ll) // putnum<long long>(va_arg(args, long long)); else if (l) putnum<long>(va_arg(args, long)); else putnum<int>(va_arg(args, int)); } else if (*fmt == 'o') { if (hh) putnum<unsigned char>( static_cast<unsigned char>(va_arg(args, unsigned int)), 8); else if (h) putnum<unsigned short>( static_cast<unsigned short>(va_arg(args, unsigned int)), 8); // else if (ll) // putnum<unsigned long long>(va_arg(args, unsigned long long), 8); else if (l) putnum<unsigned long>(va_arg(args, unsigned long), 8); else putnum<unsigned int>(va_arg(args, unsigned int), 8); } else if (*fmt == 'x' || *fmt == 'p') { if (hh) putnum<unsigned char>( static_cast<unsigned char>(va_arg(args, unsigned int)), 16); else if (h) putnum<unsigned short>( static_cast<unsigned short>(va_arg(args, unsigned int)), 16); // else if (ll) // putnum<unsigned long long>(va_arg(args, unsigned long long), 16); else if (l) putnum<unsigned long>(va_arg(args, unsigned long), 16); else putnum<unsigned int>(va_arg(args, unsigned int), 16); } else if (*fmt == 'X') { if (hh) putnum<unsigned char, ucase_alphabet>( static_cast<unsigned char>(va_arg(args, unsigned int)), 16); else if (h) putnum<unsigned short, ucase_alphabet>( static_cast<unsigned short>(va_arg(args, unsigned int)), 16); // else if (ll) // putnum<unsigned long long, ucase_alphabet>(va_arg(args, unsigned long long), 16); else if (l) putnum<unsigned long, ucase_alphabet>(va_arg(args, unsigned long), 16); else putnum<unsigned int, ucase_alphabet>(va_arg(args, unsigned int), 16); } else if (*fmt == 'u') { if (hh) putnum<unsigned char>( static_cast<unsigned char>(va_arg(args, unsigned int)) ); else if (h) putnum<unsigned short>( static_cast<unsigned short>(va_arg(args, unsigned int)) ); // else if (ll) // putnum<unsigned long long>(va_arg(args, unsigned long long)); else if (l) putnum<unsigned long>(va_arg(args, unsigned long)); else putnum<unsigned int>(va_arg(args, unsigned int)); } // else // invalid format character } else putch(*fmt); } va_end(args); } void panicln(const char* str) { asm volatile("cli" : : ); puts("PANIC: "); putsln(str); asm volatile("hlt" : : ); } }
27.016181
113
0.498563
maximsmol
678fc6ca24a705fa9c66b7e1b3966b4b0584e0ed
1,168
cpp
C++
lib/main.cpp
NathanHoekstra/NRF24L01
ba7e0ed5afec3cfd0dfd0baf49ac552c1efc3b9f
[ "BSL-1.0" ]
null
null
null
lib/main.cpp
NathanHoekstra/NRF24L01
ba7e0ed5afec3cfd0dfd0baf49ac552c1efc3b9f
[ "BSL-1.0" ]
null
null
null
lib/main.cpp
NathanHoekstra/NRF24L01
ba7e0ed5afec3cfd0dfd0baf49ac552c1efc3b9f
[ "BSL-1.0" ]
null
null
null
#include "hwlib.hpp" #include "rf24.hpp" #include "nrf24l01.hpp" #include "rf_test.hpp" int main( void ){ // kill the watchdog WDT->WDT_MR = WDT_MR_WDDIS; namespace target = hwlib::target; // NRF24L01+ Chip 1 definition auto MISO = target::pin_in(target::pins::miso); auto MOSI = target::pin_out(target::pins::mosi); auto SCK = target::pin_out(target::pins::sck); auto CE = target::pin_out(target::pins::d7); auto CSN = target::pin_out(target::pins::d8); // NRF24L01+ Chip 2 definition auto MISO_2 = target::pin_in(target::pins::d6); auto MOSI_2 = target::pin_out(target::pins::d4); auto SCK_2 = target::pin_out(target::pins::d5); auto CE_2 = target::pin_out(target::pins::d3); auto CSN_2 = target::pin_out(target::pins::d2); auto spi_bus = hwlib::spi_bus_bit_banged_sclk_mosi_miso(SCK, MOSI, MISO); auto spi_bus_2 = hwlib::spi_bus_bit_banged_sclk_mosi_miso(SCK_2, MOSI_2, MISO_2); rf24 radio(spi_bus, CE, CSN); rf24 radio_2(spi_bus_2, CE_2, CSN_2); hwlib::wait_ms(500); rf_test test(radio, radio_2); test.test_spi_communication(); //test.test_write_functions(); //test.test_read_write(); //radio.print_details(); }
29.2
82
0.702911
NathanHoekstra
096175132cc77778e576ee0e88c6de9dd5b5a14d
7,542
cpp
C++
src/dslang-scheme-context.cpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
src/dslang-scheme-context.cpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
src/dslang-scheme-context.cpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
// vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab : /* * Copyright (c) 2014-2017, Ryan V. Bissell * All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause * See the enclosed "LICENSE" file for exact license terms. */ #define CX_TRACE_SECTION "dslang" #include "dslang-scheme-context.hpp" #include "dslang-exception.hpp" #include "dslang-keywords.hpp" #include "sexpr-void.hpp" #include "sexpr-literal-bool.hpp" #include "sexpr-cons.hpp" #include "sexpr-ident.hpp" #include "dslang-dialect.hpp" #include "dslang-lexer.hpp" using DSL::SexprIDENT; using namespace DSL::detail; #include <string> using std::string; // --------------------------------------------------------------------- CX_CONSTRUCTOR6(DSL::detail::Context::Context, : Scheme(), nil_(new SexprCons(this)), void_(new SexprVoid(this)), true_(new SexprBool(this)), false_(new SexprBool(this)), env_(new SexprEnv(this,nullptr))) // NIL & VOID registrations SexprCons::NIL = nil_.get(); SexprVoid::VOID = void_.get(); // bool registration SexprBool::TRUE = true_.get(); SexprBool::FALSE = false_.get(); // TODO HACK: bind 'else' to TRUE env_->SetVariable("else", SexprBool::TRUE); // keyword registration #define SPECIAL(name) SPECIAL2(name, #name) #define SPECIAL2(name, str) KEYWORD(name, str, CallType::SPECIAL) #define REGULAR(name) REGULAR2(name, #name) #define REGULAR2(name, str) KEYWORD(name, str, CallType::REGULAR) #define KEYWORD(name, str, special) \ { str, special, DSL::detail::keyword__##name }, struct KeywordDef { const char* name; CallType type; Keyword* func; }; KeywordDef temp[] = { DSL_KEYWORDS }; #undef KEYWORD #undef REGULAR2 #undef REGULAR #undef SPECIAL2 #undef SPECIAL for (const auto k: temp) addKeyword(k.name, k.type, k.func); CX_ENDMETHOD CX_METHOD(void DSL::detail::Context::Register, Sexpr const* that) registry_.insert(that); CX_ENDMETHOD CX_METHOD(void DSL::detail::Context::Deregister, Sexpr const* that) registry_.erase(that); CX_ENDMETHOD // TODO: this is just test code void DSL::detail::Context::report() { CX_TOPICOUT(dslang, " === Here is the registry of %lu sexprs still remaining:\n", registry_.size()); for (Sexpr const* item : registry_) { CX_TOPICOUT(dslang, "serial = %lu, refcount = %lu, value = '%s'\n", item->serial_, (size_t)item->refcount_, item->Write().c_str()); } CX_TOPICOUT(dslang, " --- There are still %lu sexprs remaining.\n", Sexpr::extant_); } CX_DESTRUCTOR(DSL::detail::Context::~Context) CX_TOPICOUT(dslang, "Destructing context: total sexpr count = %lu, " "remaining = %lu\n", Sexpr::numsexprs_, Sexpr::extant_); /////keywords_.clear(); report(); gc(); report(); symbols_.clear(); report(); env_->clear(); report(); CX_ENDMETHOD CX_METHOD(void DSL::detail::Context::gc_symbols) std::lock_guard<std::mutex> lock(symlock_); for (auto item = symbols_.cbegin(); item != symbols_.cend();) { bool moribund = item->second->Disowned(); item->second->Adopted(); // yes, really. if (moribund) { auto next = symbols_.erase(item); item = next; } else ++item; } CX_ENDMETHOD CX_METHOD(void DSL::detail::Context::gc) SexprCons::NIL->Mark(); SexprVoid::VOID->Mark(); SexprBool::TRUE->Mark(); SexprBool::FALSE->Mark(); // the root environment itself is in the object registry, // and may not have any other references. We certainly don't // want to GC it! env_->Mark(); // protect our keywords for (auto item : keywords_) item.second->Mark(); gc_symbols(); // see NOTE below for (auto item = registry_.cbegin(); item != registry_.cend();) { if ((*item)->IsMarked()) { (*item)->ClearMark(); ++item; } else { CX_TOPICOUT(dslang, "GC: serial = %lu, refcount = %lu, value = '%s'\n", (*item)->serial_, (size_t)(*item)->refcount_, (*item)->Write().c_str()); auto next = registry_.erase(item); delete *item; item = next; // NOTE that some of the things we might have just deleted // are things in the symbol_ map, and consequently gc_symbols() // would crash if we called it after this. } } gc_symbols(); // see NOTE below CX_ENDMETHOD CX_METHOD(Sexpr const* DSL::detail::Context::read, char const** input) lexer::skip_any_whitespace(input); if (!**input) CX_RETURN(nullptr); // #<void> TokenHandler const* handler = dialect().GetTokenHandler(*input); if (!handler) { char const* begin = *input; lexer::skip_non_whitespace(input); string const& bad = lexer::duplicate_text(begin, *input); CX_THROW( DSL::Exception, DSL::Error::UNDEFINED, "Unknown handler encountered: '%s'", bad.c_str() ); } CX_RETURN(handler->parse(this, input)); CX_ENDMETHOD CX_CONSTMETHOD(U32 DSL::detail::Context::hashSymbolName, string const& name) U32 result; result = std::hash<std::string>{}(name); CX_RETURN(result); CX_ENDMETHOD CX_CONSTMETHOD(SexprIdent const* DSL::detail::Context::getSymbol, string const& name, U32* hash) // NOTE this routine requires that its caller has already // taken the symlock_ mutex *hash = hashSymbolName(name); U32 count = symbols_.count(*hash); if (count) { auto const& range = symbols_.equal_range(*hash); for (auto it=range.first; it != range.second; ++it) { SexprIdent const* that = it->second.get(); if (name == that->Write()) CX_RETURN(that); } } CX_RETURN(nullptr); CX_ENDMETHOD CX_METHOD(void DSL::detail::Context::AddSymbol, SexprIdent const* ident) std::lock_guard<std::mutex> lock(symlock_); string const& name = ident->Write(); U32 hash; SexprIdent const* exists = getSymbol(name, &hash); if (exists) CX_ASSERT(false); // TODO, exception symbols_.insert(std::pair<U32,SexprIDENT const>(hash, ident)); CX_ENDMETHOD CX_CONSTMETHOD(SexprIdent const* DSL::detail::Context::GetSymbol, string const& ident) std::lock_guard<std::mutex> lock(symlock_); U32 hash; CX_RETURN(getSymbol(ident, &hash)); CX_ENDMETHOD CX_METHOD(void DSL::detail::Context::addKeyword, string const& name, CallType type, Keyword handler) // no check for existing keyword; this permits overloading / // overriding of keywords by derived implementations SexprKeyword const* keyword = new SexprKeyword(this, name, handler, type); keywords_[name] = keyword; CX_ENDMETHOD CX_CONSTMETHOD(SexprKeyword const* DSL::detail::Context::GetKeyword, string const& name) auto item = keywords_.find(name); if (item != keywords_.end()) CX_RETURN(item->second.get()); CX_RETURN(nullptr); CX_ENDMETHOD
23.206154
90
0.591355
ryanvbissell
09636513f6e465d3766e61cf2f74fab1a6205df1
535
cpp
C++
AtCoder/abc124/c/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/abc124/c/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/abc124/c/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { string S; cin >> S; int N = S.length(); string a = "", b = ""; for (int i = 0; i < N; i++) { if (i % 2 == 0) a += '1'; else a += '0'; } for (int i = 0; i < N; i++) { if (i % 2 == 0) b += '0'; else b += '1'; } int x = 0, y = 0; for (int i = 0; i < N; i++) { if (S[i] != a[i]) x++; if (S[i] != b[i]) y++; } cout << min(x, y) << endl; }
22.291667
33
0.379439
H-Tatsuhiro
096c70805639663c1213492faaa136d00331aa8b
681
cpp
C++
Expriments/LearningOpenCV3/Example2_3/main.cpp
weixi2008/lab
d42143ddbd0b9ce8ec17716ea6745e59b278f29e
[ "MIT" ]
null
null
null
Expriments/LearningOpenCV3/Example2_3/main.cpp
weixi2008/lab
d42143ddbd0b9ce8ec17716ea6745e59b278f29e
[ "MIT" ]
null
null
null
Expriments/LearningOpenCV3/Example2_3/main.cpp
weixi2008/lab
d42143ddbd0b9ce8ec17716ea6745e59b278f29e
[ "MIT" ]
null
null
null
#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; const char EXAMPLE_WINDOW[] = "Example2_3"; int main(int argc, char** argv) { namedWindow(EXAMPLE_WINDOW, cv::WINDOW_AUTOSIZE); VideoCapture cap; cap.open("C:\\Users\\weixi\\Pictures\\MachineLearningIntroduction.mp4"); Mat frame; for (;;) { cap >> frame; if (frame.empty()) break; imshow(EXAMPLE_WINDOW, frame); int userkey = waitKey(33); cout << userkey << endl; //在3.2.0的版本上有Bug,在无外部按键下,会返回255,从而使下述语句break //if (waitKey(33) >= 0) break; } destroyWindow(EXAMPLE_WINDOW); return 0; }
23.482759
74
0.676946
weixi2008
096df220a1f6bd9c11bff0464549a75065dfd75d
3,321
cpp
C++
vktrace/vktrace_common/compression/compressor.cpp
luopan007/vktrace-arm
0b44f2ad599bff3707ca748179275085b8241a03
[ "Apache-2.0" ]
8
2019-07-17T13:57:15.000Z
2022-01-21T03:49:27.000Z
vktrace/vktrace_common/compression/compressor.cpp
QPC-database/vktrace-arm
50300888e0254eaf2c3f35cc31fa9893d1628730
[ "Apache-2.0" ]
2
2022-01-22T06:49:59.000Z
2022-01-22T06:56:35.000Z
vktrace/vktrace_common/compression/compressor.cpp
luopan007/vktrace-arm
0b44f2ad599bff3707ca748179275085b8241a03
[ "Apache-2.0" ]
10
2019-10-31T12:02:43.000Z
2021-08-06T04:57:23.000Z
/* * (C) COPYRIGHT 2020 ARM Limited * ALL RIGHTS RESERVED * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "compressor.h" #include "lz4compressor.h" #include "snpcompressor.h" compressor::~compressor() { } compressor* create_compressor(VKTRACE_COMPRESS_TYPE type) { if (type == VKTRACE_COMPRESS_TYPE_LZ4) { return new lz4compressor; } else if (type == VKTRACE_COMPRESS_TYPE_SNAPPY) { return new snpcompressor; } return nullptr; } int compress_packet(compressor *g_compressor, vktrace_trace_packet_header* &pPacketHeader) { if (pPacketHeader->tracer_id == VKTRACE_TID_VULKAN_COMPRESSED) { vktrace_LogWarning("Packet %d is already a compressed one, so it won't be compressed.", pPacketHeader->global_packet_index); return 0; } int orig_data_size = pPacketHeader->size - sizeof(vktrace_trace_packet_header); int buffer_size = g_compressor->getMaxCompressedLength(orig_data_size); vktrace_trace_packet_header* pCompressPacketHeader = (vktrace_trace_packet_header*)vktrace_malloc(sizeof(vktrace_trace_packet_header) + sizeof(vktrace_trace_packet_header_compression_ext) + buffer_size); pPacketHeader->pBody = (uintptr_t)(pPacketHeader + 1); char *compress_buffer = (char *)pCompressPacketHeader + sizeof(vktrace_trace_packet_header) + sizeof(vktrace_trace_packet_header_compression_ext); int compressed_data_size = g_compressor->compress((char*)pPacketHeader->pBody, orig_data_size, compress_buffer, buffer_size); if (compressed_data_size <= 0) { vktrace_LogError("Compression error: %d\n", compressed_data_size); return -1; } else if (compressed_data_size >= orig_data_size) { vktrace_LogWarning("The data after compression becomes even larger (%d bytes to %d bytes), so it won't be compressed.\n", orig_data_size, compressed_data_size); return 0; } else { uint64_t compressed_packet_size = sizeof(vktrace_trace_packet_header) + sizeof(vktrace_trace_packet_header_compression_ext) + compressed_data_size; memcpy(pCompressPacketHeader, pPacketHeader, sizeof(vktrace_trace_packet_header)); pCompressPacketHeader->pBody = (uintptr_t)(pCompressPacketHeader + 1); pCompressPacketHeader->tracer_id = VKTRACE_TID_VULKAN_COMPRESSED; pCompressPacketHeader->size = compressed_packet_size; reinterpret_cast<vktrace_trace_packet_header_compression_ext*>(pCompressPacketHeader->pBody)->decompressed_size = orig_data_size; reinterpret_cast<vktrace_trace_packet_header_compression_ext*>(pCompressPacketHeader->pBody)->pBody = (uintptr_t)compress_buffer; g_compressor->compress_packet_counter++; vktrace_free(pPacketHeader); pPacketHeader = pCompressPacketHeader; return 0; } }
45.493151
207
0.752484
luopan007
09724199617cefe173bb672383c3c0bdc49bac7d
1,563
cpp
C++
Ejercicios LP1/Proyecto/menu.cpp
IrisVH/cpp
2abeca0df70cfdc6e95e8b07160062b66e4b2799
[ "MIT" ]
null
null
null
Ejercicios LP1/Proyecto/menu.cpp
IrisVH/cpp
2abeca0df70cfdc6e95e8b07160062b66e4b2799
[ "MIT" ]
null
null
null
Ejercicios LP1/Proyecto/menu.cpp
IrisVH/cpp
2abeca0df70cfdc6e95e8b07160062b66e4b2799
[ "MIT" ]
null
null
null
#include <iostream> #include "clientes.h" using namespace std; void menu(){ bool salir=false; while(salir==false){ int opcion=0; cout<<"MENU PRINCIPAL"<<endl; cout<<"***********************"<<endl; cout<<"1-Clientes"<<endl; cout<<"2-libro diario"<<endl; cout<<"3-libro mayor"<<endl; cout<<"4-libro de inventarios"<<endl; cout<<"5-reportes"<<endl; cout<<"6-Transaccion"<<endl; cout<<"7-Salir"<<endl; cout<<endl; cout<<endl; cout<<"Seleccione una opcion:"; cin >>opcion; switch (opcion) { case 1: mostrarClientes(); system("pause"); break; case 2: system("pause"); break; case 3: system("pause"); break; case 4: system("pause"); break; case 5: system("pause"); break; case 6: system("pause"); break; case 7: salir=true; system("pause"); break; default: system("pause"); break; system("cls"); } } }
15.63
45
0.333333
IrisVH
0973147d02225f20ac6728b22a146bf3dcb0203e
1,104
cpp
C++
PATA1039.cpp
Geeks-Z/PAT-Advanced-Level-Practice
6b25d07ae602310215e46c951638b93080b382bf
[ "MIT" ]
null
null
null
PATA1039.cpp
Geeks-Z/PAT-Advanced-Level-Practice
6b25d07ae602310215e46c951638b93080b382bf
[ "MIT" ]
null
null
null
PATA1039.cpp
Geeks-Z/PAT-Advanced-Level-Practice
6b25d07ae602310215e46c951638b93080b382bf
[ "MIT" ]
null
null
null
/* * @Descripttion: https://www.liuchuo.net/archives/2145 * @version: 1.0 * @Author: Geeks_Z * @Date: 2021-05-31 10:50:24 * @LastEditors: Geeks_Z * @LastEditTime: 2021-05-31 10:50:56 */ //string、cin、cout会超时,可以使用hash(26*26*26*10+10) //将学生姓名变为int型,然后存储在vector里面 #include <cstdio> #include <vector> #include <algorithm> using namespace std; int getid(char *name) { int id = 0; for (int i = 0; i < 3; i++) id = 26 * id + (name[i] - 'A'); id = id * 10 + (name[3] - '0'); return id; } const int maxn = 26 * 26 * 26 * 10 + 10; vector<int> v[maxn]; int main() { int n, k, no, num, id = 0; char name[5]; scanf("%d %d", &n, &k); for (int i = 0; i < k; i++) { scanf("%d %d", &no, &num); for (int j = 0; j < num; j++) { scanf("%s", name); id = getid(name); v[id].push_back(no); } } for (int i = 0; i < n; i++) { scanf("%s", name); id = getid(name); sort(v[id].begin(), v[id].end()); printf("%s %lu", name, v[id].size()); for (int j = 0; j < v[id].size(); j++) printf(" %d", v[id][j]); printf("\n"); } return 0; }
21.230769
55
0.511775
Geeks-Z
09739731a0e897786307acc69a6738ae05a54c4b
2,162
cpp
C++
main.cpp
Ivan-Sandro/Fire_Doom_Algorithm
f33af2826f8d16cd8b8cc6086f8ba8b3ba21733f
[ "MIT" ]
null
null
null
main.cpp
Ivan-Sandro/Fire_Doom_Algorithm
f33af2826f8d16cd8b8cc6086f8ba8b3ba21733f
[ "MIT" ]
null
null
null
main.cpp
Ivan-Sandro/Fire_Doom_Algorithm
f33af2826f8d16cd8b8cc6086f8ba8b3ba21733f
[ "MIT" ]
null
null
null
#include <ctime> #include <iostream> #include <string> #include "Sistema_Allegro5.0.h" #include "Fogo.h" #include "Painel.h" using namespace std; constexpr short int Largura_Tela = 1080 ; constexpr short int Altura_Tela = 720 ; int main() { srand(time(NULL)); bool EXIT_PROGRAM = false; unsigned char Clicando = false; DISPLAY Janela; ALLEGRO_EVENT evento; FOGO fg_Display; BOTAO Botoes[12]; _Iniciar_Sistema_Allegro(); _Definir_Botoes(Botoes, Largura_Tela); Janela._Push_FPS(15); Janela._Criar_Sistema_Allegro(Largura_Tela, Altura_Tela); Janela._Registrar_Eventos(); _Carregar_Fonte_BOTAO("QumpellkaNo12.OTF", 24); fg_Display._Get_Paleta_Regular_Cor("Fire_DOOM.PNG", 0, 0, 1, 1, 36, 1); fg_Display._Definir_Matriz_Fogo(Largura_Tela, Altura_Tela, 10); al_start_timer(Janela._Get_Timer()); while(!EXIT_PROGRAM) { al_wait_for_event(Janela._Get_Event_Queue(), &evento); switch(evento.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: EXIT_PROGRAM = true; break; case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: _Verificar_Click_Botoes(evento.mouse.x, evento.mouse.y, Botoes); Clicando = true; break; case ALLEGRO_EVENT_MOUSE_BUTTON_UP: _Desativar_Botoes_MOUSE_BUTTON_UP(Botoes); Clicando = false; break; case ALLEGRO_EVENT_MOUSE_AXES: if(Clicando) fg_Display._Desenhar_Com_Mouse(evento.mouse.x, evento.mouse.y); break; case ALLEGRO_EVENT_TIMER: fg_Display._Mover_Fogo(); _Eventos_Se_BOTAO_Ativo(Botoes, fg_Display); al_clear_to_color(al_map_rgb(0, 0, 0)); fg_Display._Desenhar_Fogo(); _Desenhar_Botoes(Botoes); al_flip_display(); break; } } Janela._Destuir_Sistema_Allegro(); _Destruir_Fonte_BOTAO(); return 0; }
24.568182
84
0.592044
Ivan-Sandro
0973bb8c3d5a2b04aec2c1b573ec412a9a030b74
742
hpp
C++
H3D/Graphics/Drawable.hpp
heinhel/H3D-Engine
5e638683486f9b083aaaf1a433d5eed361adfa79
[ "MIT" ]
null
null
null
H3D/Graphics/Drawable.hpp
heinhel/H3D-Engine
5e638683486f9b083aaaf1a433d5eed361adfa79
[ "MIT" ]
null
null
null
H3D/Graphics/Drawable.hpp
heinhel/H3D-Engine
5e638683486f9b083aaaf1a433d5eed361adfa79
[ "MIT" ]
null
null
null
#pragma once #if defined DLL_EXPORT #define H3D_API __declspec(dllexport) #else #define H3D_API __declspec(dllimport) #endif #include "../../H3D/MemoryMng/pool_alloc.hpp" #include "../../H3D/Math/Vector.hpp" #include "Texture.hpp" #include "../../H3D/Model/3DModel.hpp" #include "../../H3D/System/Window.hpp" ///////////////////////////////////////////////////////////////// // Drawable ///////////////////////////////////////////////////////////////// namespace h3d { typedef h3d::Vec3<h3d::Vec2<float>> AABB; class Drawable { AABB aabb; enum class Type { static_, dynamic_ }; Type type; //h3d::Texture tex; //h3d::Model3D model; public: Drawable(); ~Drawable(); virtual void draw(h3d::Window &win) = 0; }; }
19.526316
65
0.551213
heinhel
0974c627e603a100666c7fcefed84a6affcf7790
3,805
cpp
C++
SpatialGDK/Source/SpatialGDKFunctionalTests/SpatialGDK/SpatialTestPossession/NoneCrossServerPossessionTest.cpp
cyberbibby/UnrealGDK
9502a1ba11d21b3cb64978ba7ea178c63371cdd0
[ "MIT" ]
null
null
null
SpatialGDK/Source/SpatialGDKFunctionalTests/SpatialGDK/SpatialTestPossession/NoneCrossServerPossessionTest.cpp
cyberbibby/UnrealGDK
9502a1ba11d21b3cb64978ba7ea178c63371cdd0
[ "MIT" ]
null
null
null
SpatialGDK/Source/SpatialGDKFunctionalTests/SpatialGDK/SpatialTestPossession/NoneCrossServerPossessionTest.cpp
cyberbibby/UnrealGDK
9502a1ba11d21b3cb64978ba7ea178c63371cdd0
[ "MIT" ]
null
null
null
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "NoneCrossServerPossessionTest.h" #include "Containers/Array.h" #include "CrossServerPossessionGameMode.h" #include "EngineClasses/SpatialNetDriver.h" #include "GameFramework/PlayerController.h" #include "SpatialFunctionalTestFlowController.h" #include "SpatialGDKFunctionalTests/SpatialGDK/TestActors/TestPossessionPawn.h" #include "TestPossessionPlayerController.h" #include "TestWorkerSettings.h" /** * This test tests 1 Controller possess over 1 Pawn. * * This test expects a load balancing grid and ACrossServerPossessionGameMode * Recommend to use 2*2 load balancing grid because the position is written in the code * The client workers begin with a player controller and their default pawns, which they initially possess. * The flow is as follows: * Recommend to use LocalControllerPossessPawnGym.umap in UnrealGDKTestGyms project which ready for tests. * - Setup: * - Specify `GameMode Override` as ACrossServerPossessionGameMode * - Specify `Multi Worker Settings Class` as Zoning 2x2(e.g. BP_Possession_Settings_Zoning2_2 of UnrealGDKTestGyms) * - Set `Num Required Clients` as 1 * - Test: * - Create a Pawn in 4th quadrant * - Create 1 Controller in 4th quadrant, the position is determined by ACrossServerPossessionGameMode * - Wait for Pawn in right worker. * - The Controller possess the Pawn in server-side * - Result Check: * - ATestPossessionPlayerController::OnPossess should be called == 1 times */ ANoneCrossServerPossessionTest::ANoneCrossServerPossessionTest() : Super(EMapCategory::CI_NIGHTLY_SPATIAL_ONLY, 1) { Author = "Ken.Yu"; Description = TEXT("Test Local Possession via RemotePossessionComponent"); LocationOfPawn = FVector(-500.0f, -500.0f, 50.0f); } void ANoneCrossServerPossessionTest::CreateCustomContentForMap() { GetWorldSettingsForMap()->SetMultiWorkerSettingsClass(UTest2x2FullInterestWorkerSettings::StaticClass()); GetWorldSettingsForMap()->DefaultGameMode = ACrossServerPossessionGameMode::StaticClass(); } void ANoneCrossServerPossessionTest::PrepareTest() { Super::PrepareTest(); AddStep(TEXT("Possession"), FWorkerDefinition::AllServers, nullptr, /*StartEvent*/ [this]() { ATestPossessionPawn* Pawn = GetPawn(); AssertIsValid(Pawn, TEXT("Test requires a Pawn")); for (ASpatialFunctionalTestFlowController* FlowController : GetFlowControllers()) { if (FlowController->WorkerDefinition.Type == ESpatialFunctionalTestWorkerType::Client) { ATestPossessionPlayerController* PlayerController = Cast<ATestPossessionPlayerController>(FlowController->GetOwner()); if (PlayerController != nullptr && PlayerController->HasAuthority()) { AssertTrue(PlayerController->HasAuthority(), TEXT("PlayerController should HasAuthority"), PlayerController); AssertTrue(Pawn->HasAuthority(), TEXT("Pawn should HasAuthority"), Pawn); PlayerController->UnPossess(); PlayerController->RemotePossessOnServer(Pawn); } } } FinishStep(); }); AddStep( TEXT("Check test result"), FWorkerDefinition::Server(1), [this]() -> bool { return ATestPossessionPlayerController::OnPossessCalled == 1; }, /*StartEvent*/ [this]() { for (ASpatialFunctionalTestFlowController* FlowController : GetFlowControllers()) { if (FlowController->WorkerDefinition.Type == ESpatialFunctionalTestWorkerType::Client) { ATestPossessionPlayerController* PlayerController = Cast<ATestPossessionPlayerController>(FlowController->GetOwner()); if (PlayerController != nullptr && PlayerController->HasAuthority()) { AssertFalse(PlayerController->HasMigrated(), TEXT("PlayerController shouldn't have migrated"), PlayerController); } } } FinishStep(); }); AddCleanupSteps(); }
39.635417
123
0.762681
cyberbibby
0979a6c4fde8b3f3573e11d63d6ab1a4608c183e
2,170
cpp
C++
provant_simulator_utils/provant_simulator_sdf_parser/src/sdf_status.cpp
Guiraffo/ProVANT_Simulator
ef2260204b13f39a9f83ad2ab88a9552a0699bff
[ "MIT" ]
null
null
null
provant_simulator_utils/provant_simulator_sdf_parser/src/sdf_status.cpp
Guiraffo/ProVANT_Simulator
ef2260204b13f39a9f83ad2ab88a9552a0699bff
[ "MIT" ]
null
null
null
provant_simulator_utils/provant_simulator_sdf_parser/src/sdf_status.cpp
Guiraffo/ProVANT_Simulator
ef2260204b13f39a9f83ad2ab88a9552a0699bff
[ "MIT" ]
null
null
null
/* * This file is part of the ProVANT simulator project. * Licensed under the terms of the MIT open source license. More details at * https://github.com/Guiraffo/ProVANT-Simulator/blob/master/LICENSE.md */ /** * @file sdf_status.cpp * @brief This file contains the implementation of the SDFStatus classes. * * @author Júnio Eduardo de Morais Aquino */ #include "provant_simulator_sdf_parser/sdf_status.h" #include <sstream> SDFStatus::SDFStatus(bool isError, const std::string msg) : std::runtime_error(msg.c_str()), _isError(isError), _msg(msg) { } SDFStatus::~SDFStatus() { } const char* SDFStatus::what() const noexcept { return _msg.c_str(); } bool SDFStatus::isError() const { return _isError; } const std::string& SDFStatus::errorMessage() const { return _msg; } OkStatus::OkStatus() : SDFStatus(false, ""){}; NotFoundError::NotFoundError(const std::string& name, const std::string& type) : SDFStatus(true) { std::stringstream str; str << "The " << type << " named \"" << name << "\" was not found in this plugin SDF description. Please verify that if this " << type << " is correctly defined and try again."; _msg = str.str(); } ElementNotFoundError::ElementNotFoundError(const std::string& name) : NotFoundError(name, "element") { } AttributeNotFoundError::AttributeNotFoundError(const std::string& name) : NotFoundError(name, "attribute") { } XMLSyntaxError::XMLSyntaxError(const std::string& msg) : SDFStatus(true, msg) { } ConversionError::ConversionError(const std::string& element, const std::string& originalContent, const std::string& type, const std::string& extraMsg) : SDFStatus(true) { std::stringstream str; str << "An error ocurred while trying to convert the value (" << originalContent << ") of the " << element << " element to a " << type << "."; if (!extraMsg.empty()) { str << " " << extraMsg; } _msg = str.str(); } NullPointerError::NullPointerError(const std::string& method) : SDFStatus(true) { std::stringstream str; str << "A nullpointer was passed as the output parameter to the " << method << " method."; _msg = str.str(); }
25.833333
108
0.680645
Guiraffo
098367871119dd1867604845a2008ad262bb999a
72,386
cpp
C++
src/masterx-evolution.cpp
redux-project/redux
55101ab1f6776ff50014bebb36f5d78e2ffa1edb
[ "MIT" ]
null
null
null
src/masterx-evolution.cpp
redux-project/redux
55101ab1f6776ff50014bebb36f5d78e2ffa1edb
[ "MIT" ]
null
null
null
src/masterx-evolution.cpp
redux-project/redux
55101ab1f6776ff50014bebb36f5d78e2ffa1edb
[ "MIT" ]
null
null
null
// Copyright (c) 2015-2016 The Redux developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "init.h" #include "masterx-evolution.h" #include "masterx.h" #include "stealthx.h" #include "masterxman.h" #include "masterx-sync.h" #include "util.h" #include "addrman.h" #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> CEvolutionManager evolution; CCriticalSection cs_evolution; std::map<uint256, int64_t> askedForSourceProposalOrEvolution; std::vector<CEvolutionProposalBroadcast> vecImmatureEvolutionProposals; std::vector<CFinalizedEvolutionBroadcast> vecImmatureFinalizedEvolutions; int GetEvolutionPaymentCycleBlocks(){ // Amount of blocks in a months period of time (using 2.6 minutes per) = (60*24*30)/2.6 if(Params().NetworkID() == CBaseChainParams::MAIN) return 16616; //for testing purposes return 50; //ten times per day } bool IsEvolutionCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf) { CTransaction txCollateral; uint256 nBlockHash; if(!GetTransaction(nTxCollateralHash, txCollateral, nBlockHash, true)){ strError = strprintf("Can't find collateral tx %s", txCollateral.ToString()); LogPrintf ("CEvolutionProposalBroadcast::IsEvolutionCollateralValid - %s\n", strError); return false; } if(txCollateral.vout.size() < 1) return false; if(txCollateral.nLockTime != 0) return false; CScript findScript; findScript << OP_RETURN << ToByteVector(nExpectedHash); bool foundOpReturn = false; BOOST_FOREACH(const CTxOut o, txCollateral.vout){ if(!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()){ strError = strprintf("Invalid Script %s", txCollateral.ToString()); LogPrintf ("CEvolutionProposalBroadcast::IsEvolutionCollateralValid - %s\n", strError); return false; } if(o.scriptPubKey == findScript && o.nValue >= EVOLUTION_FEE_TX) foundOpReturn = true; } if(!foundOpReturn){ strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString()); LogPrintf ("CEvolutionProposalBroadcast::IsEvolutionCollateralValid - %s\n", strError); return false; } // RETRIEVE CONFIRMATIONS AND NTIME /* - nTime starts as zero and is passed-by-reference out of this function and stored in the external proposal - nTime is never validated via the hashing mechanism and comes from a full-validated source (the blockchain) */ int conf = GetIXConfirmations(nTxCollateralHash); if (nBlockHash != uint256(0)) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; nTime = pindex->nTime; } } } nConf = conf; //if we're syncing we won't have instantX information, so accept 1 confirmation if(conf >= EVOLUTION_FEE_CONFIRMATIONS){ return true; } else { strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", EVOLUTION_FEE_CONFIRMATIONS, conf); LogPrintf ("CEvolutionProposalBroadcast::IsEvolutionCollateralValid - %s - %d confirmations\n", strError, conf); return false; } } void CEvolutionManager::CheckOrphanVotes() { LOCK(cs); std::string strError = ""; std::map<uint256, CEvolutionVote>::iterator it1 = mapOrphanMasterXEvolutionVotes.begin(); while(it1 != mapOrphanMasterXEvolutionVotes.end()){ if(evolution.UpdateProposal(((*it1).second), NULL, strError)){ LogPrintf("CEvolutionManager::CheckOrphanVotes - Proposal/Evolution is known, activating and removing orphan vote\n"); mapOrphanMasterXEvolutionVotes.erase(it1++); } else { ++it1; } } std::map<uint256, CFinalizedEvolutionVote>::iterator it2 = mapOrphanFinalizedEvolutionVotes.begin(); while(it2 != mapOrphanFinalizedEvolutionVotes.end()){ if(evolution.UpdateFinalizedEvolution(((*it2).second),NULL, strError)){ LogPrintf("CEvolutionManager::CheckOrphanVotes - Proposal/Evolution is known, activating and removing orphan vote\n"); mapOrphanFinalizedEvolutionVotes.erase(it2++); } else { ++it2; } } } void CEvolutionManager::SubmitFinalEvolution() { static int nSubmittedHeight = 0; // height at which final evolution was submitted last time int nCurrentHeight; { TRY_LOCK(cs_main, locked); if(!locked) return; if(!chainActive.Tip()) return; nCurrentHeight = chainActive.Height(); } int nBlockStart = nCurrentHeight - nCurrentHeight % GetEvolutionPaymentCycleBlocks() + GetEvolutionPaymentCycleBlocks(); if(nSubmittedHeight >= nBlockStart) return; if(nBlockStart - nCurrentHeight > 576*2) return; // allow submitting final evolution only when 2 days left before payments std::vector<CEvolutionProposal*> vEvolutionProposals = evolution.GetEvolution(); std::string strEvolutionName = "main"; std::vector<CTxEvolutionPayment> vecTxEvolutionPayments; for(unsigned int i = 0; i < vEvolutionProposals.size(); i++){ CTxEvolutionPayment txEvolutionPayment; txEvolutionPayment.nProposalHash = vEvolutionProposals[i]->GetHash(); txEvolutionPayment.payee = vEvolutionProposals[i]->GetPayee(); txEvolutionPayment.nAmount = vEvolutionProposals[i]->GetAllotted(); vecTxEvolutionPayments.push_back(txEvolutionPayment); } if(vecTxEvolutionPayments.size() < 1) { LogPrintf("CEvolutionManager::SubmitFinalEvolution - Found No Proposals For Period\n"); return; } CFinalizedEvolutionBroadcast tempEvolution(strEvolutionName, nBlockStart, vecTxEvolutionPayments, 0); if(mapSeenFinalizedEvolutions.count(tempEvolution.GetHash())) { LogPrintf("CEvolutionManager::SubmitFinalEvolution - Evolution already exists - %s\n", tempEvolution.GetHash().ToString()); nSubmittedHeight = nCurrentHeight; return; //already exists } //create fee tx CTransaction tx; uint256 txidCollateral; if(!mapCollateralTxids.count(tempEvolution.GetHash())){ CWalletTx wtx; if(!pwalletMain->GetEvolutionSystemCollateralTX(wtx, tempEvolution.GetHash(), false)){ LogPrintf("CEvolutionManager::SubmitFinalEvolution - Can't make collateral transaction\n"); return; } // make our change address CReserveKey reservekey(pwalletMain); //send the tx to the network pwalletMain->CommitTransaction(wtx, reservekey, "ix"); tx = (CTransaction)wtx; txidCollateral = tx.GetHash(); mapCollateralTxids.insert(make_pair(tempEvolution.GetHash(), txidCollateral)); } else { txidCollateral = mapCollateralTxids[tempEvolution.GetHash()]; } int conf = GetIXConfirmations(tx.GetHash()); CTransaction txCollateral; uint256 nBlockHash; if(!GetTransaction(txidCollateral, txCollateral, nBlockHash, true)) { LogPrintf ("CBudgetManager::SubmitFinalBudget - Can't find collateral tx %s", txidCollateral.ToString()); return; } if (nBlockHash != uint256(0)) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; } } } /* Wait will we have 1 extra confirmation, otherwise some clients might reject this feeTX -- This function is tied to NewBlock, so we will propagate this evolution while the block is also propagating */ if(conf < EVOLUTION_FEE_CONFIRMATIONS+1){ LogPrintf ("CEvolutionManager::SubmitFinalEvolution - Collateral requires at least %d confirmations - %s - %d confirmations\n", EVOLUTION_FEE_CONFIRMATIONS+1, txidCollateral.ToString(), conf); return; } //create the proposal incase we're the first to make it CFinalizedEvolutionBroadcast finalizedEvolutionBroadcast(strEvolutionName, nBlockStart, vecTxEvolutionPayments, txidCollateral); std::string strError = ""; if(!finalizedEvolutionBroadcast.IsValid(strError)){ LogPrintf("CEvolutionManager::SubmitFinalEvolution - Invalid finalized evolution - %s \n", strError); return; } LOCK(cs); mapSeenFinalizedEvolutions.insert(make_pair(finalizedEvolutionBroadcast.GetHash(), finalizedEvolutionBroadcast)); finalizedEvolutionBroadcast.Relay(); evolution.AddFinalizedEvolution(finalizedEvolutionBroadcast); nSubmittedHeight = nCurrentHeight; LogPrintf("CEvolutionManager::SubmitFinalEvolution - Done! %s\n", finalizedEvolutionBroadcast.GetHash().ToString()); } // // CEvolutionDB // CEvolutionDB::CEvolutionDB() { pathDB = GetDataDir() / "evolution.dat"; strMagicMessage = "MasterXEvolution"; } bool CEvolutionDB::Write(const CEvolutionManager& objToSave) { LOCK(objToSave.cs); int64_t nStart = GetTimeMillis(); // serialize, checksum data up to that point, then append checksum CDataStream ssObj(SER_DISK, CLIENT_VERSION); ssObj << strMagicMessage; // masterx cache file specific magic message ssObj << FLATDATA(Params().MessageStart()); // network specific magic number ssObj << objToSave; uint256 hash = Hash(ssObj.begin(), ssObj.end()); ssObj << hash; // open output file, and associate with CAutoFile FILE *file = fopen(pathDB.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathDB.string()); // Write and commit header, data try { fileout << ssObj; } catch (std::exception &e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); LogPrintf("Written info to evolution.dat %dms\n", GetTimeMillis() - nStart); return true; } CEvolutionDB::ReadResult CEvolutionDB::Read(CEvolutionManager& objToLoad, bool fDryRun) { LOCK(objToLoad.cs); int64_t nStart = GetTimeMillis(); // open input file, and associate with CAutoFile FILE *file = fopen(pathDB.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) { error("%s : Failed to open file %s", __func__, pathDB.string()); return FileError; } // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathDB); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char *)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception &e) { error("%s : Deserialize or I/O error - %s", __func__, e.what()); return HashReadError; } filein.fclose(); CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssObj.begin(), ssObj.end()); if (hashIn != hashTmp) { error("%s : Checksum mismatch, data corrupted", __func__); return IncorrectHash; } unsigned char pchMsgTmp[4]; std::string strMagicMessageTmp; try { // de-serialize file header (masterx cache file specific magic message) and .. ssObj >> strMagicMessageTmp; // ... verify the message matches predefined one if (strMagicMessage != strMagicMessageTmp) { error("%s : Invalid masterx cache magic message", __func__); return IncorrectMagicMessage; } // de-serialize file header (network specific magic number) and .. ssObj >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) { error("%s : Invalid network magic number", __func__); return IncorrectMagicNumber; } // de-serialize data into CEvolutionManager object ssObj >> objToLoad; } catch (std::exception &e) { objToLoad.Clear(); error("%s : Deserialize or I/O error - %s", __func__, e.what()); return IncorrectFormat; } LogPrintf("Loaded info from evolution.dat %dms\n", GetTimeMillis() - nStart); LogPrintf(" %s\n", objToLoad.ToString()); if(!fDryRun) { LogPrintf("Evolution manager - cleaning....\n"); objToLoad.CheckAndRemove(); LogPrintf("Evolution manager - result:\n"); LogPrintf(" %s\n", objToLoad.ToString()); } return Ok; } void DumpEvolutions() { int64_t nStart = GetTimeMillis(); CEvolutionDB evolutiondb; CEvolutionManager tempEvolution; LogPrintf("Verifying evolution.dat format...\n"); CEvolutionDB::ReadResult readResult = evolutiondb.Read(tempEvolution, true); // there was an error and it was not an error on file opening => do not proceed if (readResult == CEvolutionDB::FileError) LogPrintf("Missing evolutions file - evolution.dat, will try to recreate\n"); else if (readResult != CEvolutionDB::Ok) { LogPrintf("Error reading evolution.dat: "); if(readResult == CEvolutionDB::IncorrectFormat) LogPrintf("magic is ok but data has invalid format, will try to recreate\n"); else { LogPrintf("file format is unknown or invalid, please fix it manually\n"); return; } } LogPrintf("Writting info to evolution.dat...\n"); evolutiondb.Write(evolution); LogPrintf("Evolution dump finished %dms\n", GetTimeMillis() - nStart); } bool CEvolutionManager::AddFinalizedEvolution(CFinalizedEvolution& finalizedEvolution) { std::string strError = ""; if(!finalizedEvolution.IsValid(strError)) return false; if(mapFinalizedEvolutions.count(finalizedEvolution.GetHash())) { return false; } mapFinalizedEvolutions.insert(make_pair(finalizedEvolution.GetHash(), finalizedEvolution)); return true; } bool CEvolutionManager::AddProposal(CEvolutionProposal& evolutionProposal) { LOCK(cs); std::string strError = ""; if(!evolutionProposal.IsValid(strError)) { LogPrintf("CEvolutionManager::AddProposal - invalid evolution proposal - %s\n", strError); return false; } if(mapProposals.count(evolutionProposal.GetHash())) { return false; } mapProposals.insert(make_pair(evolutionProposal.GetHash(), evolutionProposal)); return true; } void CEvolutionManager::CheckAndRemove() { LogPrintf("CEvolutionManager::CheckAndRemove\n"); std::string strError = ""; LogPrintf("CEvolutionManager::CheckAndRemove - mapFinalizedEvolutions cleanup - size: %d\n", mapFinalizedEvolutions.size()); std::map<uint256, CFinalizedEvolution>::iterator it = mapFinalizedEvolutions.begin(); while(it != mapFinalizedEvolutions.end()) { CFinalizedEvolution* pfinalizedEvolution = &((*it).second); pfinalizedEvolution->fValid = pfinalizedEvolution->IsValid(strError); LogPrintf("CEvolutionManager::CheckAndRemove - pfinalizedEvolution->IsValid - strError: %s\n", strError); if(pfinalizedEvolution->fValid) { pfinalizedEvolution->AutoCheck(); } ++it; } LogPrintf("CEvolutionManager::CheckAndRemove - mapProposals cleanup - size: %d\n", mapProposals.size()); std::map<uint256, CEvolutionProposal>::iterator it2 = mapProposals.begin(); while(it2 != mapProposals.end()) { CEvolutionProposal* pevolutionProposal = &((*it2).second); pevolutionProposal->fValid = pevolutionProposal->IsValid(strError); ++it2; } LogPrintf("CEvolutionManager::CheckAndRemove - PASSED\n"); } void CEvolutionManager::FillBlockPayee(CMutableTransaction& txNew, CAmount nFees) { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) return; int nHighestCount = 0; CScript payee; CAmount nAmount = 0; // ------- Grab The Highest Count std::map<uint256, CFinalizedEvolution>::iterator it = mapFinalizedEvolutions.begin(); while(it != mapFinalizedEvolutions.end()) { CFinalizedEvolution* pfinalizedEvolution = &((*it).second); if(pfinalizedEvolution->GetVoteCount() > nHighestCount && pindexPrev->nHeight + 1 >= pfinalizedEvolution->GetBlockStart() && pindexPrev->nHeight + 1 <= pfinalizedEvolution->GetBlockEnd() && pfinalizedEvolution->GetPayeeAndAmount(pindexPrev->nHeight + 1, payee, nAmount)){ nHighestCount = pfinalizedEvolution->GetVoteCount(); } ++it; } CAmount blockValue = GetBlockValue(pindexPrev->nBits, pindexPrev->nHeight, nFees); //miners get the full amount on these blocks txNew.vout[0].nValue = blockValue; if(nHighestCount > 0){ txNew.vout.resize(2); //these are super blocks, so their value can be much larger than normal txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrintf("CEvolutionManager::FillBlockPayee - Evolution payment to %s for %lld\n", address2.ToString(), nAmount); } } CFinalizedEvolution *CEvolutionManager::FindFinalizedEvolution(uint256 nHash) { if(mapFinalizedEvolutions.count(nHash)) return &mapFinalizedEvolutions[nHash]; return NULL; } CEvolutionProposal *CEvolutionManager::FindProposal(const std::string &strProposalName) { //find the prop with the highest yes count int nYesCount = -99999; CEvolutionProposal* pevolutionProposal = NULL; std::map<uint256, CEvolutionProposal>::iterator it = mapProposals.begin(); while(it != mapProposals.end()){ if((*it).second.strProposalName == strProposalName && (*it).second.GetYeas() > nYesCount){ pevolutionProposal = &((*it).second); nYesCount = pevolutionProposal->GetYeas(); } ++it; } if(nYesCount == -99999) return NULL; return pevolutionProposal; } CEvolutionProposal *CEvolutionManager::FindProposal(uint256 nHash) { LOCK(cs); if(mapProposals.count(nHash)) return &mapProposals[nHash]; return NULL; } bool CEvolutionManager::IsEvolutionPaymentBlock(int nBlockHeight) { int nHighestCount = -1; std::map<uint256, CFinalizedEvolution>::iterator it = mapFinalizedEvolutions.begin(); while(it != mapFinalizedEvolutions.end()) { CFinalizedEvolution* pfinalizedEvolution = &((*it).second); if(pfinalizedEvolution->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedEvolution->GetBlockStart() && nBlockHeight <= pfinalizedEvolution->GetBlockEnd()){ nHighestCount = pfinalizedEvolution->GetVoteCount(); } ++it; } /* If evolution doesn't have 5% of the network votes, then we should pay a masterx instead */ if(nHighestCount > gmineman.CountEnabled(MIN_EVOLUTION_PEER_PROTO_VERSION)/20) return true; return false; } bool CEvolutionManager::HasNextFinalizedEvolution() { CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) return false; if(masterxSync.IsEvolutionFinEmpty()) return true; int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetEvolutionPaymentCycleBlocks() + GetEvolutionPaymentCycleBlocks(); if(nBlockStart - pindexPrev->nHeight > 576*2) return true; //we wouldn't have the evolution yet if(evolution.IsEvolutionPaymentBlock(nBlockStart)) return true; LogPrintf("CEvolutionManager::HasNextFinalizedEvolution() - Client is missing evolution - %lli\n", nBlockStart); return false; } bool CEvolutionManager::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs); int nHighestCount = 0; std::vector<CFinalizedEvolution*> ret; // ------- Grab The Highest Count std::map<uint256, CFinalizedEvolution>::iterator it = mapFinalizedEvolutions.begin(); while(it != mapFinalizedEvolutions.end()) { CFinalizedEvolution* pfinalizedEvolution = &((*it).second); if(pfinalizedEvolution->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedEvolution->GetBlockStart() && nBlockHeight <= pfinalizedEvolution->GetBlockEnd()){ nHighestCount = pfinalizedEvolution->GetVoteCount(); } ++it; } /* If evolution doesn't have 5% of the network votes, then we should pay a masterx instead */ if(nHighestCount < gmineman.CountEnabled(MIN_EVOLUTION_PEER_PROTO_VERSION)/20) return false; // check the highest finalized evolutions (+/- 10% to assist in consensus) it = mapFinalizedEvolutions.begin(); while(it != mapFinalizedEvolutions.end()) { CFinalizedEvolution* pfinalizedEvolution = &((*it).second); if(pfinalizedEvolution->GetVoteCount() > nHighestCount - gmineman.CountEnabled(MIN_EVOLUTION_PEER_PROTO_VERSION)/10){ if(nBlockHeight >= pfinalizedEvolution->GetBlockStart() && nBlockHeight <= pfinalizedEvolution->GetBlockEnd()){ if(pfinalizedEvolution->IsTransactionValid(txNew, nBlockHeight)){ return true; } } } ++it; } //we looked through all of the known evolutions return false; } std::vector<CEvolutionProposal*> CEvolutionManager::GetAllProposals() { LOCK(cs); std::vector<CEvolutionProposal*> vEvolutionProposalRet; std::map<uint256, CEvolutionProposal>::iterator it = mapProposals.begin(); while(it != mapProposals.end()) { (*it).second.CleanAndRemove(false); CEvolutionProposal* pevolutionProposal = &((*it).second); vEvolutionProposalRet.push_back(pevolutionProposal); ++it; } return vEvolutionProposalRet; } // // Sort by votes, if there's a tie sort by their feeHash TX // struct sortProposalsByVotes { bool operator()(const std::pair<CEvolutionProposal*, int> &left, const std::pair<CEvolutionProposal*, int> &right) { if( left.second != right.second) return (left.second > right.second); return (left.first->nFeeTXHash > right.first->nFeeTXHash); } }; //Need to review this function std::vector<CEvolutionProposal*> CEvolutionManager::GetEvolution() { LOCK(cs); // ------- Sort evolutions by Yes Count std::vector<std::pair<CEvolutionProposal*, int> > vEvolutionPorposalsSort; std::map<uint256, CEvolutionProposal>::iterator it = mapProposals.begin(); while(it != mapProposals.end()){ (*it).second.CleanAndRemove(false); vEvolutionPorposalsSort.push_back(make_pair(&((*it).second), (*it).second.GetYeas()-(*it).second.GetNays())); ++it; } std::sort(vEvolutionPorposalsSort.begin(), vEvolutionPorposalsSort.end(), sortProposalsByVotes()); // ------- Grab The Evolutions In Order std::vector<CEvolutionProposal*> vEvolutionProposalsRet; CAmount nEvolutionAllocated = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return vEvolutionProposalsRet; int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetEvolutionPaymentCycleBlocks() + GetEvolutionPaymentCycleBlocks(); int nBlockEnd = nBlockStart + GetEvolutionPaymentCycleBlocks() - 1; CAmount nTotalEvolution = GetTotalEvolution(nBlockStart); std::vector<std::pair<CEvolutionProposal*, int> >::iterator it2 = vEvolutionPorposalsSort.begin(); while(it2 != vEvolutionPorposalsSort.end()) { CEvolutionProposal* pevolutionProposal = (*it2).first; //prop start/end should be inside this period if(pevolutionProposal->fValid && pevolutionProposal->nBlockStart <= nBlockStart && pevolutionProposal->nBlockEnd >= nBlockEnd && pevolutionProposal->GetYeas() - pevolutionProposal->GetNays() > gmineman.CountEnabled(MIN_EVOLUTION_PEER_PROTO_VERSION)/10 && pevolutionProposal->IsEstablished()) { if(pevolutionProposal->GetAmount() + nEvolutionAllocated <= nTotalEvolution) { pevolutionProposal->SetAllotted(pevolutionProposal->GetAmount()); nEvolutionAllocated += pevolutionProposal->GetAmount(); vEvolutionProposalsRet.push_back(pevolutionProposal); } else { pevolutionProposal->SetAllotted(0); } } ++it2; } return vEvolutionProposalsRet; } struct sortFinalizedEvolutionsByVotes { bool operator()(const std::pair<CFinalizedEvolution*, int> &left, const std::pair<CFinalizedEvolution*, int> &right) { return left.second > right.second; } }; std::vector<CFinalizedEvolution*> CEvolutionManager::GetFinalizedEvolutions() { LOCK(cs); std::vector<CFinalizedEvolution*> vFinalizedEvolutionsRet; std::vector<std::pair<CFinalizedEvolution*, int> > vFinalizedEvolutionsSort; // ------- Grab The Evolutions In Order std::map<uint256, CFinalizedEvolution>::iterator it = mapFinalizedEvolutions.begin(); while(it != mapFinalizedEvolutions.end()) { CFinalizedEvolution* pfinalizedEvolution = &((*it).second); vFinalizedEvolutionsSort.push_back(make_pair(pfinalizedEvolution, pfinalizedEvolution->GetVoteCount())); ++it; } std::sort(vFinalizedEvolutionsSort.begin(), vFinalizedEvolutionsSort.end(), sortFinalizedEvolutionsByVotes()); std::vector<std::pair<CFinalizedEvolution*, int> >::iterator it2 = vFinalizedEvolutionsSort.begin(); while(it2 != vFinalizedEvolutionsSort.end()) { vFinalizedEvolutionsRet.push_back((*it2).first); ++it2; } return vFinalizedEvolutionsRet; } std::string CEvolutionManager::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs); std::string ret = "unknown-evolution"; std::map<uint256, CFinalizedEvolution>::iterator it = mapFinalizedEvolutions.begin(); while(it != mapFinalizedEvolutions.end()) { CFinalizedEvolution* pfinalizedEvolution = &((*it).second); if(nBlockHeight >= pfinalizedEvolution->GetBlockStart() && nBlockHeight <= pfinalizedEvolution->GetBlockEnd()){ CTxEvolutionPayment payment; if(pfinalizedEvolution->GetEvolutionPaymentByBlock(nBlockHeight, payment)){ if(ret == "unknown-evolution"){ ret = payment.nProposalHash.ToString(); } else { ret += ","; ret += payment.nProposalHash.ToString(); } } else { LogPrintf("CEvolutionManager::GetRequiredPaymentsString - Couldn't find evolution payment for block %d\n", nBlockHeight); } } ++it; } return ret; } CAmount CEvolutionManager::GetTotalEvolution(int nHeight) { if(chainActive.Tip() == NULL) return 0; //get min block value and calculate from that CAmount nSubsidy = 5 * COIN; if(Params().NetworkID() == CBaseChainParams::TESTNET){ for(int i = 210240; i <= nHeight; i += 210240) nSubsidy -= nSubsidy/14; } else { // yearly decline of production by 7.1% per year, projected 21.3M coins max by year 2050. for(int i = 210240; i <= nHeight; i += 210240) nSubsidy -= nSubsidy/14; } // Amount of blocks in a months period of time (using 2.6 minutes per) = (60*24*30)/2.6 if(Params().NetworkID() == CBaseChainParams::MAIN) return ((nSubsidy/100)*10)*576*30; //for testing purposes return ((nSubsidy/100)*10)*50; } void CEvolutionManager::NewBlock() { TRY_LOCK(cs, fEvolutionNewBlock); if(!fEvolutionNewBlock) return; if (masterxSync.RequestedMasterXAssets <= MASTERX_SYNC_EVOLUTION) return; if (strEvolutionMode == "suggest") { //suggest the evolution we see SubmitFinalEvolution(); } //this function should be called 1/6 blocks, allowing up to 100 votes per day on all proposals if(chainActive.Height() % 6 != 0) return; // incremental sync with our peers if(masterxSync.IsSynced()){ LogPrintf("CEvolutionManager::NewBlock - incremental sync started\n"); if(chainActive.Height() % 600 == rand() % 600) { ClearSeen(); ResetSync(); } LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if(pnode->nVersion >= MIN_EVOLUTION_PEER_PROTO_VERSION) Sync(pnode, 0, true); MarkSynced(); } CheckAndRemove(); //remove invalid votes once in a while (we have to check the signatures and validity of every vote, somewhat CPU intensive) LogPrintf("CEvolutionManager::NewBlock - askedForSourceProposalOrEvolution cleanup - size: %d\n", askedForSourceProposalOrEvolution.size()); std::map<uint256, int64_t>::iterator it = askedForSourceProposalOrEvolution.begin(); while(it != askedForSourceProposalOrEvolution.end()){ if((*it).second > GetTime() - (60*60*24)){ ++it; } else { askedForSourceProposalOrEvolution.erase(it++); } } LogPrintf("CEvolutionManager::NewBlock - mapProposals cleanup - size: %d\n", mapProposals.size()); std::map<uint256, CEvolutionProposal>::iterator it2 = mapProposals.begin(); while(it2 != mapProposals.end()){ (*it2).second.CleanAndRemove(false); ++it2; } LogPrintf("CEvolutionManager::NewBlock - mapFinalizedEvolutions cleanup - size: %d\n", mapFinalizedEvolutions.size()); std::map<uint256, CFinalizedEvolution>::iterator it3 = mapFinalizedEvolutions.begin(); while(it3 != mapFinalizedEvolutions.end()){ (*it3).second.CleanAndRemove(false); ++it3; } LogPrintf("CEvolutionManager::NewBlock - vecImmatureEvolutionProposals cleanup - size: %d\n", vecImmatureEvolutionProposals.size()); std::vector<CEvolutionProposalBroadcast>::iterator it4 = vecImmatureEvolutionProposals.begin(); while(it4 != vecImmatureEvolutionProposals.end()) { std::string strError = ""; int nConf = 0; if(!IsEvolutionCollateralValid((*it4).nFeeTXHash, (*it4).GetHash(), strError, (*it4).nTime, nConf)){ ++it4; continue; } if(!(*it4).IsValid(strError)) { LogPrintf("mprop (immature) - invalid evolution proposal - %s\n", strError); it4 = vecImmatureEvolutionProposals.erase(it4); continue; } CEvolutionProposal evolutionProposal((*it4)); if(AddProposal(evolutionProposal)) {(*it4).Relay();} LogPrintf("mprop (immature) - new evolution - %s\n", (*it4).GetHash().ToString()); it4 = vecImmatureEvolutionProposals.erase(it4); } LogPrintf("CEvolutionManager::NewBlock - vecImmatureFinalizedEvolutions cleanup - size: %d\n", vecImmatureFinalizedEvolutions.size()); std::vector<CFinalizedEvolutionBroadcast>::iterator it5 = vecImmatureFinalizedEvolutions.begin(); while(it5 != vecImmatureFinalizedEvolutions.end()) { std::string strError = ""; int nConf = 0; if(!IsEvolutionCollateralValid((*it5).nFeeTXHash, (*it5).GetHash(), strError, (*it5).nTime, nConf)){ ++it5; continue; } if(!(*it5).IsValid(strError)) { LogPrintf("fbs (immature) - invalid finalized evolution - %s\n", strError); it5 = vecImmatureFinalizedEvolutions.erase(it5); continue; } LogPrintf("fbs (immature) - new finalized evolution - %s\n", (*it5).GetHash().ToString()); CFinalizedEvolution finalizedEvolution((*it5)); if(AddFinalizedEvolution(finalizedEvolution)) {(*it5).Relay();} it5 = vecImmatureFinalizedEvolutions.erase(it5); } LogPrintf("CEvolutionManager::NewBlock - PASSED\n"); } void CEvolutionManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { // lite mode is not supported if(fLiteMode) return; if(!masterxSync.IsBlockchainSynced()) return; LOCK(cs_evolution); if (strCommand == "gmvs") { //MasterX vote sync uint256 nProp; vRecv >> nProp; if(Params().NetworkID() == CBaseChainParams::MAIN){ if(nProp == 0) { if(pfrom->HasFulfilledRequest("gmvs")) { LogPrintf("gmvs - peer already asked me for the list\n"); Misbehaving(pfrom->GetId(), 20); return; } pfrom->FulfilledRequest("gmvs"); } } Sync(pfrom, nProp); LogPrintf("gmvs - Sent MasterX votes to %s\n", pfrom->addr.ToString()); } if (strCommand == "mprop") { //MasterX Proposal CEvolutionProposalBroadcast evolutionProposalBroadcast; vRecv >> evolutionProposalBroadcast; if(mapSeenMasterXEvolutionProposals.count(evolutionProposalBroadcast.GetHash())){ masterxSync.AddedEvolutionItem(evolutionProposalBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if(!IsEvolutionCollateralValid(evolutionProposalBroadcast.nFeeTXHash, evolutionProposalBroadcast.GetHash(), strError, evolutionProposalBroadcast.nTime, nConf)){ LogPrintf("Proposal FeeTX is not valid - %s - %s\n", evolutionProposalBroadcast.nFeeTXHash.ToString(), strError); if(nConf >= 1) vecImmatureEvolutionProposals.push_back(evolutionProposalBroadcast); return; } mapSeenMasterXEvolutionProposals.insert(make_pair(evolutionProposalBroadcast.GetHash(), evolutionProposalBroadcast)); if(!evolutionProposalBroadcast.IsValid(strError)) { LogPrintf("mprop - invalid evolution proposal - %s\n", strError); return; } CEvolutionProposal evolutionProposal(evolutionProposalBroadcast); if(AddProposal(evolutionProposal)) {evolutionProposalBroadcast.Relay();} masterxSync.AddedEvolutionItem(evolutionProposalBroadcast.GetHash()); LogPrintf("mprop - new evolution - %s\n", evolutionProposalBroadcast.GetHash().ToString()); //We might have active votes for this proposal that are valid now CheckOrphanVotes(); } if (strCommand == "mvote") { //MasterX Vote CEvolutionVote vote; vRecv >> vote; vote.fValid = true; if(mapSeenMasterXEvolutionVotes.count(vote.GetHash())){ masterxSync.AddedEvolutionItem(vote.GetHash()); return; } CMasterX* pgm = gmineman.Find(vote.vin); if(pgm == NULL) { LogPrint("gmevolution", "mvote - unknown masterx - vin: %s\n", vote.vin.ToString()); gmineman.AskForGM(pfrom, vote.vin); return; } mapSeenMasterXEvolutionVotes.insert(make_pair(vote.GetHash(), vote)); if(!vote.SignatureValid(true)){ LogPrintf("mvote - signature invalid\n"); if(masterxSync.IsSynced()) Misbehaving(pfrom->GetId(), 20); // it could just be a non-synced masterx gmineman.AskForGM(pfrom, vote.vin); return; } std::string strError = ""; if(UpdateProposal(vote, pfrom, strError)) { vote.Relay(); masterxSync.AddedEvolutionItem(vote.GetHash()); } LogPrintf("mvote - new evolution vote - %s\n", vote.GetHash().ToString()); } if (strCommand == "fbs") { //Finalized Evolution Suggestion CFinalizedEvolutionBroadcast finalizedEvolutionBroadcast; vRecv >> finalizedEvolutionBroadcast; if(mapSeenFinalizedEvolutions.count(finalizedEvolutionBroadcast.GetHash())){ masterxSync.AddedEvolutionItem(finalizedEvolutionBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if(!IsEvolutionCollateralValid(finalizedEvolutionBroadcast.nFeeTXHash, finalizedEvolutionBroadcast.GetHash(), strError, finalizedEvolutionBroadcast.nTime, nConf)){ LogPrintf("Finalized Evolution FeeTX is not valid - %s - %s\n", finalizedEvolutionBroadcast.nFeeTXHash.ToString(), strError); if(nConf >= 1) vecImmatureFinalizedEvolutions.push_back(finalizedEvolutionBroadcast); return; } mapSeenFinalizedEvolutions.insert(make_pair(finalizedEvolutionBroadcast.GetHash(), finalizedEvolutionBroadcast)); if(!finalizedEvolutionBroadcast.IsValid(strError)) { LogPrintf("fbs - invalid finalized evolution - %s\n", strError); return; } LogPrintf("fbs - new finalized evolution - %s\n", finalizedEvolutionBroadcast.GetHash().ToString()); CFinalizedEvolution finalizedEvolution(finalizedEvolutionBroadcast); if(AddFinalizedEvolution(finalizedEvolution)) {finalizedEvolutionBroadcast.Relay();} masterxSync.AddedEvolutionItem(finalizedEvolutionBroadcast.GetHash()); //we might have active votes for this evolution that are now valid CheckOrphanVotes(); } if (strCommand == "fbvote") { //Finalized Evolution Vote CFinalizedEvolutionVote vote; vRecv >> vote; vote.fValid = true; if(mapSeenFinalizedEvolutionVotes.count(vote.GetHash())){ masterxSync.AddedEvolutionItem(vote.GetHash()); return; } CMasterX* pgm = gmineman.Find(vote.vin); if(pgm == NULL) { LogPrint("gmevolution", "fbvote - unknown masterx - vin: %s\n", vote.vin.ToString()); gmineman.AskForGM(pfrom, vote.vin); return; } mapSeenFinalizedEvolutionVotes.insert(make_pair(vote.GetHash(), vote)); if(!vote.SignatureValid(true)){ LogPrintf("fbvote - signature invalid\n"); if(masterxSync.IsSynced()) Misbehaving(pfrom->GetId(), 20); // it could just be a non-synced masterx gmineman.AskForGM(pfrom, vote.vin); return; } std::string strError = ""; if(UpdateFinalizedEvolution(vote, pfrom, strError)) { vote.Relay(); masterxSync.AddedEvolutionItem(vote.GetHash()); LogPrintf("fbvote - new finalized evolution vote - %s\n", vote.GetHash().ToString()); } else { LogPrintf("fbvote - rejected finalized evolution vote - %s - %s\n", vote.GetHash().ToString(), strError); } } } bool CEvolutionManager::PropExists(uint256 nHash) { if(mapProposals.count(nHash)) return true; return false; } //mark that a full sync is needed void CEvolutionManager::ResetSync() { LOCK(cs); std::map<uint256, CEvolutionProposalBroadcast>::iterator it1 = mapSeenMasterXEvolutionProposals.begin(); while(it1 != mapSeenMasterXEvolutionProposals.end()){ CEvolutionProposal* pevolutionProposal = FindProposal((*it1).first); if(pevolutionProposal && pevolutionProposal->fValid){ //mark votes std::map<uint256, CEvolutionVote>::iterator it2 = pevolutionProposal->mapVotes.begin(); while(it2 != pevolutionProposal->mapVotes.end()){ (*it2).second.fSynced = false; ++it2; } } ++it1; } std::map<uint256, CFinalizedEvolutionBroadcast>::iterator it3 = mapSeenFinalizedEvolutions.begin(); while(it3 != mapSeenFinalizedEvolutions.end()){ CFinalizedEvolution* pfinalizedEvolution = FindFinalizedEvolution((*it3).first); if(pfinalizedEvolution && pfinalizedEvolution->fValid){ //send votes std::map<uint256, CFinalizedEvolutionVote>::iterator it4 = pfinalizedEvolution->mapVotes.begin(); while(it4 != pfinalizedEvolution->mapVotes.end()){ (*it4).second.fSynced = false; ++it4; } } ++it3; } } void CEvolutionManager::MarkSynced() { LOCK(cs); /* Mark that we've sent all valid items */ std::map<uint256, CEvolutionProposalBroadcast>::iterator it1 = mapSeenMasterXEvolutionProposals.begin(); while(it1 != mapSeenMasterXEvolutionProposals.end()){ CEvolutionProposal* pevolutionProposal = FindProposal((*it1).first); if(pevolutionProposal && pevolutionProposal->fValid){ //mark votes std::map<uint256, CEvolutionVote>::iterator it2 = pevolutionProposal->mapVotes.begin(); while(it2 != pevolutionProposal->mapVotes.end()){ if((*it2).second.fValid) (*it2).second.fSynced = true; ++it2; } } ++it1; } std::map<uint256, CFinalizedEvolutionBroadcast>::iterator it3 = mapSeenFinalizedEvolutions.begin(); while(it3 != mapSeenFinalizedEvolutions.end()){ CFinalizedEvolution* pfinalizedEvolution = FindFinalizedEvolution((*it3).first); if(pfinalizedEvolution && pfinalizedEvolution->fValid){ //mark votes std::map<uint256, CFinalizedEvolutionVote>::iterator it4 = pfinalizedEvolution->mapVotes.begin(); while(it4 != pfinalizedEvolution->mapVotes.end()){ if((*it4).second.fValid) (*it4).second.fSynced = true; ++it4; } } ++it3; } } void CEvolutionManager::Sync(CNode* pfrom, uint256 nProp, bool fPartial) { LOCK(cs); /* Sync with a client on the network -- This code checks each of the hash maps for all known evolution proposals and finalized evolution proposals, then checks them against the evolution object to see if they're OK. If all checks pass, we'll send it to the peer. */ int nInvCount = 0; std::map<uint256, CEvolutionProposalBroadcast>::iterator it1 = mapSeenMasterXEvolutionProposals.begin(); while(it1 != mapSeenMasterXEvolutionProposals.end()){ CEvolutionProposal* pevolutionProposal = FindProposal((*it1).first); if(pevolutionProposal && pevolutionProposal->fValid && (nProp == 0 || (*it1).first == nProp)){ pfrom->PushInventory(CInv(MSG_EVOLUTION_PROPOSAL, (*it1).second.GetHash())); nInvCount++; //send votes std::map<uint256, CEvolutionVote>::iterator it2 = pevolutionProposal->mapVotes.begin(); while(it2 != pevolutionProposal->mapVotes.end()){ if((*it2).second.fValid){ if((fPartial && !(*it2).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_EVOLUTION_VOTE, (*it2).second.GetHash())); nInvCount++; } } ++it2; } } ++it1; } pfrom->PushMessage("ssc", MASTERX_SYNC_EVOLUTION_PROP, nInvCount); LogPrintf("CEvolutionManager::Sync - sent %d items\n", nInvCount); nInvCount = 0; std::map<uint256, CFinalizedEvolutionBroadcast>::iterator it3 = mapSeenFinalizedEvolutions.begin(); while(it3 != mapSeenFinalizedEvolutions.end()){ CFinalizedEvolution* pfinalizedEvolution = FindFinalizedEvolution((*it3).first); if(pfinalizedEvolution && pfinalizedEvolution->fValid && (nProp == 0 || (*it3).first == nProp)){ pfrom->PushInventory(CInv(MSG_EVOLUTION_FINALIZED, (*it3).second.GetHash())); nInvCount++; //send votes std::map<uint256, CFinalizedEvolutionVote>::iterator it4 = pfinalizedEvolution->mapVotes.begin(); while(it4 != pfinalizedEvolution->mapVotes.end()){ if((*it4).second.fValid) { if((fPartial && !(*it4).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_EVOLUTION_FINALIZED_VOTE, (*it4).second.GetHash())); nInvCount++; } } ++it4; } } ++it3; } pfrom->PushMessage("ssc", MASTERX_SYNC_EVOLUTION_FIN, nInvCount); LogPrintf("CEvolutionManager::Sync - sent %d items\n", nInvCount); } bool CEvolutionManager::UpdateProposal(CEvolutionVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if(!mapProposals.count(vote.nProposalHash)){ if(pfrom){ // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if(!masterxSync.IsSynced()) return false; LogPrintf("CEvolutionManager::UpdateProposal - Unknown proposal %d, asking for source proposal\n", vote.nProposalHash.ToString()); mapOrphanMasterXEvolutionVotes[vote.nProposalHash] = vote; if(!askedForSourceProposalOrEvolution.count(vote.nProposalHash)){ pfrom->PushMessage("gmvs", vote.nProposalHash); askedForSourceProposalOrEvolution[vote.nProposalHash] = GetTime(); } } strError = "Proposal not found!"; return false; } return mapProposals[vote.nProposalHash].AddOrUpdateVote(vote, strError); } bool CEvolutionManager::UpdateFinalizedEvolution(CFinalizedEvolutionVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if(!mapFinalizedEvolutions.count(vote.nEvolutionHash)){ if(pfrom){ // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if(!masterxSync.IsSynced()) return false; LogPrintf("CEvolutionManager::UpdateFinalizedEvolution - Unknown Finalized Proposal %s, asking for source evolution\n", vote.nEvolutionHash.ToString()); mapOrphanFinalizedEvolutionVotes[vote.nEvolutionHash] = vote; if(!askedForSourceProposalOrEvolution.count(vote.nEvolutionHash)){ pfrom->PushMessage("gmvs", vote.nEvolutionHash); askedForSourceProposalOrEvolution[vote.nEvolutionHash] = GetTime(); } } strError = "Finalized Evolution not found!"; return false; } return mapFinalizedEvolutions[vote.nEvolutionHash].AddOrUpdateVote(vote, strError); } CEvolutionProposal::CEvolutionProposal() { strProposalName = "unknown"; nBlockStart = 0; nBlockEnd = 0; nAmount = 0; nTime = 0; fValid = true; } CEvolutionProposal::CEvolutionProposal(std::string strProposalNameIn, std::string strURLIn, int nBlockStartIn, int nBlockEndIn, CScript addressIn, CAmount nAmountIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; nBlockEnd = nBlockEndIn; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; fValid = true; } CEvolutionProposal::CEvolutionProposal(const CEvolutionProposal& other) { strProposalName = other.strProposalName; strURL = other.strURL; nBlockStart = other.nBlockStart; nBlockEnd = other.nBlockEnd; address = other.address; nAmount = other.nAmount; nTime = other.nTime; nFeeTXHash = other.nFeeTXHash; mapVotes = other.mapVotes; fValid = true; } bool CEvolutionProposal::IsValid(std::string& strError, bool fCheckCollateral) { if(GetNays() - GetYeas() > gmineman.CountEnabled(MIN_EVOLUTION_PEER_PROTO_VERSION)/10){ strError = "Active removal"; return false; } if(nBlockStart < 0) { strError = "Invalid Proposal"; return false; } if(nBlockEnd < nBlockStart) { strError = "Invalid nBlockEnd"; return false; } if(nAmount < 1*COIN) { strError = "Invalid nAmount"; return false; } if(address == CScript()) { strError = "Invalid Payment Address"; return false; } if(fCheckCollateral){ int nConf = 0; if(!IsEvolutionCollateralValid(nFeeTXHash, GetHash(), strError, nTime, nConf)){ return false; } } /* TODO: There might be an issue with multisig in the coinbase on mainnet, we will add support for it in a future release. */ if(address.IsPayToScriptHash()) { strError = "Multisig is not currently supported."; return false; } //if proposal doesn't gain traction within 2 weeks, remove it // nTime not being saved correctly // -- TODO: We should keep track of the last time the proposal was valid, if it's invalid for 2 weeks, erase it // if(nTime + (60*60*24*2) < GetAdjustedTime()) { // if(GetYeas()-GetNays() < (gmineman.CountEnabled(MIN_EVOLUTION_PEER_PROTO_VERSION)/10)) { // strError = "Not enough support"; // return false; // } // } //can only pay out 10% of the possible coins (min value of coins) if(nAmount > evolution.GetTotalEvolution(nBlockStart)) { strError = "Payment more than max"; return false; } CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) {strError = "Tip is NULL"; return true;} if(GetBlockEnd() < pindexPrev->nHeight - GetEvolutionPaymentCycleBlocks()/2 ) return false; return true; } bool CEvolutionProposal::AddOrUpdateVote(CEvolutionVote& vote, std::string& strError) { LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); if(mapVotes.count(hash)){ if(mapVotes[hash].nTime > vote.nTime){ strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("gmevolution", "CEvolutionProposal::AddOrUpdateVote - %s\n", strError); return false; } if(vote.nTime - mapVotes[hash].nTime < EVOLUTION_VOTE_UPDATE_MIN){ strError = strprintf("time between votes is too soon - %s - %lli\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime); LogPrint("gmevolution", "CEvolutionProposal::AddOrUpdateVote - %s\n", strError); return false; } } if(vote.nTime > GetTime() + (60*60)){ strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60*60)); LogPrint("gmevolution", "CEvolutionProposal::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; return true; } // If masterx voted for a proposal, but is now invalid -- remove the vote void CEvolutionProposal::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CEvolutionVote>::iterator it = mapVotes.begin(); while(it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } double CEvolutionProposal::GetRatio() { int yeas = 0; int nays = 0; std::map<uint256, CEvolutionVote>::iterator it = mapVotes.begin(); while(it != mapVotes.end()) { if ((*it).second.nVote == VOTE_YES) yeas++; if ((*it).second.nVote == VOTE_NO) nays++; ++it; } if(yeas+nays == 0) return 0.0f; return ((double)(yeas) / (double)(yeas+nays)); } int CEvolutionProposal::GetYeas() { int ret = 0; std::map<uint256, CEvolutionVote>::iterator it = mapVotes.begin(); while(it != mapVotes.end()){ if ((*it).second.nVote == VOTE_YES && (*it).second.fValid) ret++; ++it; } return ret; } int CEvolutionProposal::GetNays() { int ret = 0; std::map<uint256, CEvolutionVote>::iterator it = mapVotes.begin(); while(it != mapVotes.end()){ if ((*it).second.nVote == VOTE_NO && (*it).second.fValid) ret++; ++it; } return ret; } int CEvolutionProposal::GetAbstains() { int ret = 0; std::map<uint256, CEvolutionVote>::iterator it = mapVotes.begin(); while(it != mapVotes.end()){ if ((*it).second.nVote == VOTE_ABSTAIN && (*it).second.fValid) ret++; ++it; } return ret; } int CEvolutionProposal::GetBlockStartCycle() { //end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockStart - nBlockStart % GetEvolutionPaymentCycleBlocks(); } int CEvolutionProposal::GetBlockCurrentCycle() { CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return -1; if(pindexPrev->nHeight >= GetBlockEndCycle()) return -1; return pindexPrev->nHeight - pindexPrev->nHeight % GetEvolutionPaymentCycleBlocks(); } int CEvolutionProposal::GetBlockEndCycle() { //end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockEnd - GetEvolutionPaymentCycleBlocks()/2; } int CEvolutionProposal::GetTotalPaymentCount() { return (GetBlockEndCycle() - GetBlockStartCycle()) / GetEvolutionPaymentCycleBlocks(); } int CEvolutionProposal::GetRemainingPaymentCount() { // If this evolution starts in the future, this value will be wrong int nPayments = (GetBlockEndCycle() - GetBlockCurrentCycle()) / GetEvolutionPaymentCycleBlocks() - 1; // Take the lowest value return std::min(nPayments, GetTotalPaymentCount()); } CEvolutionProposalBroadcast::CEvolutionProposalBroadcast(std::string strProposalNameIn, std::string strURLIn, int nPaymentCount, CScript addressIn, CAmount nAmountIn, int nBlockStartIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; int nCycleStart = nBlockStart - nBlockStart % GetEvolutionPaymentCycleBlocks(); //calculate the end of the cycle for this vote, add half a cycle (vote will be deleted after that block) nBlockEnd = nCycleStart + GetEvolutionPaymentCycleBlocks() * nPaymentCount + GetEvolutionPaymentCycleBlocks()/2; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; } void CEvolutionProposalBroadcast::Relay() { CInv inv(MSG_EVOLUTION_PROPOSAL, GetHash()); RelayInv(inv, MIN_EVOLUTION_PEER_PROTO_VERSION); } CEvolutionVote::CEvolutionVote() { vin = CTxIn(); nProposalHash = 0; nVote = VOTE_ABSTAIN; nTime = 0; fValid = true; fSynced = false; } CEvolutionVote::CEvolutionVote(CTxIn vinIn, uint256 nProposalHashIn, int nVoteIn) { vin = vinIn; nProposalHash = nProposalHashIn; nVote = nVoteIn; nTime = GetAdjustedTime(); fValid = true; fSynced = false; } void CEvolutionVote::Relay() { CInv inv(MSG_EVOLUTION_VOTE, GetHash()); RelayInv(inv, MIN_EVOLUTION_PEER_PROTO_VERSION); } bool CEvolutionVote::Sign(CKey& keyMasterX, CPubKey& pubKeyMasterX) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); if(!spySendSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasterX)) { LogPrintf("CEvolutionVote::Sign - Error upon calling SignMessage"); return false; } if(!spySendSigner.VerifyMessage(pubKeyMasterX, vchSig, strMessage, errorMessage)) { LogPrintf("CEvolutionVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CEvolutionVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); CMasterX* pgm = gmineman.Find(vin); if(pgm == NULL) { LogPrint("gmevolution", "CEvolutionVote::SignatureValid() - Unknown MasterX - %s\n", vin.ToString()); return false; } if(!fSignatureCheck) return true; if(!spySendSigner.VerifyMessage(pgm->pubkey2, vchSig, strMessage, errorMessage)) { LogPrintf("CEvolutionVote::SignatureValid() - Verify message failed\n"); return false; } return true; } CFinalizedEvolution::CFinalizedEvolution() { strEvolutionName = ""; nBlockStart = 0; vecEvolutionPayments.clear(); mapVotes.clear(); nFeeTXHash = 0; nTime = 0; fValid = true; fAutoChecked = false; } CFinalizedEvolution::CFinalizedEvolution(const CFinalizedEvolution& other) { strEvolutionName = other.strEvolutionName; nBlockStart = other.nBlockStart; vecEvolutionPayments = other.vecEvolutionPayments; mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; nTime = other.nTime; fValid = true; fAutoChecked = false; } bool CFinalizedEvolution::AddOrUpdateVote(CFinalizedEvolutionVote& vote, std::string& strError) { LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); if(mapVotes.count(hash)){ if(mapVotes[hash].nTime > vote.nTime){ strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("gmevolution", "CFinalizedEvolution::AddOrUpdateVote - %s\n", strError); return false; } if(vote.nTime - mapVotes[hash].nTime < EVOLUTION_VOTE_UPDATE_MIN){ strError = strprintf("time between votes is too soon - %s - %lli\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime); LogPrint("gmevolution", "CFinalizedEvolution::AddOrUpdateVote - %s\n", strError); return false; } } if(vote.nTime > GetTime() + (60*60)){ strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60*60)); LogPrint("gmevolution", "CFinalizedEvolution::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; return true; } //evaluate if we should vote for this. MasterX only void CFinalizedEvolution::AutoCheck() { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) return; LogPrintf("CFinalizedEvolution::AutoCheck - %lli - %d\n", pindexPrev->nHeight, fAutoChecked); if(!fMasterX || fAutoChecked) return; //do this 1 in 4 blocks -- spread out the voting activity on mainnet // -- this function is only called every sixth block, so this is really 1 in 24 blocks if(Params().NetworkID() == CBaseChainParams::MAIN && rand() % 4 != 0) { LogPrintf("CFinalizedEvolution::AutoCheck - waiting\n"); return; } fAutoChecked = true; //we only need to check this once if(strEvolutionMode == "auto") //only vote for exact matches { std::vector<CEvolutionProposal*> vEvolutionProposals = evolution.GetEvolution(); for(unsigned int i = 0; i < vecEvolutionPayments.size(); i++){ LogPrintf("CFinalizedEvolution::AutoCheck - nProp %d %s\n", i, vecEvolutionPayments[i].nProposalHash.ToString()); LogPrintf("CFinalizedEvolution::AutoCheck - Payee %d %s\n", i, vecEvolutionPayments[i].payee.ToString()); LogPrintf("CFinalizedEvolution::AutoCheck - nAmount %d %lli\n", i, vecEvolutionPayments[i].nAmount); } for(unsigned int i = 0; i < vEvolutionProposals.size(); i++){ LogPrintf("CFinalizedEvolution::AutoCheck - nProp %d %s\n", i, vEvolutionProposals[i]->GetHash().ToString()); LogPrintf("CFinalizedEvolution::AutoCheck - Payee %d %s\n", i, vEvolutionProposals[i]->GetPayee().ToString()); LogPrintf("CFinalizedEvolution::AutoCheck - nAmount %d %lli\n", i, vEvolutionProposals[i]->GetAmount()); } if(vEvolutionProposals.size() == 0) { LogPrintf("CFinalizedEvolution::AutoCheck - Can't get Evolution, aborting\n"); return; } if(vEvolutionProposals.size() != vecEvolutionPayments.size()) { LogPrintf("CFinalizedEvolution::AutoCheck - Evolution length doesn't match\n"); return; } for(unsigned int i = 0; i < vecEvolutionPayments.size(); i++){ if(i > vEvolutionProposals.size() - 1) { LogPrintf("CFinalizedEvolution::AutoCheck - Vector size mismatch, aborting\n"); return; } if(vecEvolutionPayments[i].nProposalHash != vEvolutionProposals[i]->GetHash()){ LogPrintf("CFinalizedEvolution::AutoCheck - item #%d doesn't match %s %s\n", i, vecEvolutionPayments[i].nProposalHash.ToString(), vEvolutionProposals[i]->GetHash().ToString()); return; } // if(vecEvolutionPayments[i].payee != vEvolutionProposals[i]->GetPayee()){ -- triggered with false positive if(vecEvolutionPayments[i].payee.ToString() != vEvolutionProposals[i]->GetPayee().ToString()){ LogPrintf("CFinalizedEvolution::AutoCheck - item #%d payee doesn't match %s %s\n", i, vecEvolutionPayments[i].payee.ToString(), vEvolutionProposals[i]->GetPayee().ToString()); return; } if(vecEvolutionPayments[i].nAmount != vEvolutionProposals[i]->GetAmount()){ LogPrintf("CFinalizedEvolution::AutoCheck - item #%d payee doesn't match %lli %lli\n", i, vecEvolutionPayments[i].nAmount, vEvolutionProposals[i]->GetAmount()); return; } } LogPrintf("CFinalizedEvolution::AutoCheck - Finalized Evolution Matches! Submitting Vote.\n"); SubmitVote(); } } // If masterx voted for a proposal, but is now invalid -- remove the vote void CFinalizedEvolution::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CFinalizedEvolutionVote>::iterator it = mapVotes.begin(); while(it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } CAmount CFinalizedEvolution::GetTotalPayout() { CAmount ret = 0; for(unsigned int i = 0; i < vecEvolutionPayments.size(); i++){ ret += vecEvolutionPayments[i].nAmount; } return ret; } std::string CFinalizedEvolution::GetProposals() { LOCK(cs); std::string ret = ""; BOOST_FOREACH(CTxEvolutionPayment& evolutionPayment, vecEvolutionPayments){ CEvolutionProposal* pevolutionProposal = evolution.FindProposal(evolutionPayment.nProposalHash); std::string token = evolutionPayment.nProposalHash.ToString(); if(pevolutionProposal) token = pevolutionProposal->GetName(); if(ret == "") {ret = token;} else {ret += "," + token;} } return ret; } std::string CFinalizedEvolution::GetStatus() { std::string retBadHashes = ""; std::string retBadPayeeOrAmount = ""; for(int nBlockHeight = GetBlockStart(); nBlockHeight <= GetBlockEnd(); nBlockHeight++) { CTxEvolutionPayment evolutionPayment; if(!GetEvolutionPaymentByBlock(nBlockHeight, evolutionPayment)){ LogPrintf("CFinalizedEvolution::GetStatus - Couldn't find evolution payment for block %lld\n", nBlockHeight); continue; } CEvolutionProposal* pevolutionProposal = evolution.FindProposal(evolutionPayment.nProposalHash); if(!pevolutionProposal){ if(retBadHashes == ""){ retBadHashes = "Unknown proposal hash! Check this proposal before voting" + evolutionPayment.nProposalHash.ToString(); } else { retBadHashes += "," + evolutionPayment.nProposalHash.ToString(); } } else { if(pevolutionProposal->GetPayee() != evolutionPayment.payee || pevolutionProposal->GetAmount() != evolutionPayment.nAmount) { if(retBadPayeeOrAmount == ""){ retBadPayeeOrAmount = "Evolution payee/nAmount doesn't match our proposal! " + evolutionPayment.nProposalHash.ToString(); } else { retBadPayeeOrAmount += "," + evolutionPayment.nProposalHash.ToString(); } } } } if(retBadHashes == "" && retBadPayeeOrAmount == "") return "OK"; return retBadHashes + retBadPayeeOrAmount; } bool CFinalizedEvolution::IsValid(std::string& strError, bool fCheckCollateral) { //must be the correct block for payment to happen (once a month) if(nBlockStart % GetEvolutionPaymentCycleBlocks() != 0) {strError = "Invalid BlockStart"; return false;} if(GetBlockEnd() - nBlockStart > 100) {strError = "Invalid BlockEnd"; return false;} if((int)vecEvolutionPayments.size() > 100) {strError = "Invalid evolution payments count (too many)"; return false;} if(strEvolutionName == "") {strError = "Invalid Evolution Name"; return false;} if(nBlockStart == 0) {strError = "Invalid BlockStart == 0"; return false;} if(nFeeTXHash == 0) {strError = "Invalid FeeTx == 0"; return false;} //can only pay out 10% of the possible coins (min value of coins) if(GetTotalPayout() > evolution.GetTotalEvolution(nBlockStart)) {strError = "Invalid Payout (more than max)"; return false;} std::string strError2 = ""; if(fCheckCollateral){ int nConf = 0; if(!IsEvolutionCollateralValid(nFeeTXHash, GetHash(), strError2, nTime, nConf)){ {strError = "Invalid Collateral : " + strError2; return false;} } } //TODO: if N cycles old, invalid, invalid CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return true; if(nBlockStart < pindexPrev->nHeight-100) {strError = "Older than current blockHeight"; return false;} return true; } bool CFinalizedEvolution::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { int nCurrentEvolutionPayment = nBlockHeight - GetBlockStart(); if(nCurrentEvolutionPayment < 0) { LogPrintf("CFinalizedEvolution::IsTransactionValid - Invalid block - height: %d start: %d\n", nBlockHeight, GetBlockStart()); return false; } if(nCurrentEvolutionPayment > (int)vecEvolutionPayments.size() - 1) { LogPrintf("CFinalizedEvolution::IsTransactionValid - Invalid block - current evolution payment: %d of %d\n", nCurrentEvolutionPayment + 1, (int)vecEvolutionPayments.size()); return false; } bool found = false; BOOST_FOREACH(CTxOut out, txNew.vout) { if(vecEvolutionPayments[nCurrentEvolutionPayment].payee == out.scriptPubKey && vecEvolutionPayments[nCurrentEvolutionPayment].nAmount == out.nValue) found = true; } if(!found) { CTxDestination address1; ExtractDestination(vecEvolutionPayments[nCurrentEvolutionPayment].payee, address1); CBitcoinAddress address2(address1); LogPrintf("CFinalizedEvolution::IsTransactionValid - Missing required payment - %s: %d\n", address2.ToString(), vecEvolutionPayments[nCurrentEvolutionPayment].nAmount); } return found; } void CFinalizedEvolution::SubmitVote() { CPubKey pubKeyMasterX; CKey keyMasterX; std::string errorMessage; if(!spySendSigner.SetKey(strMasterXPrivKey, errorMessage, keyMasterX, pubKeyMasterX)){ LogPrintf("CFinalizedEvolution::SubmitVote - Error upon calling SetKey\n"); return; } CFinalizedEvolutionVote vote(activeMasterX.vin, GetHash()); if(!vote.Sign(keyMasterX, pubKeyMasterX)){ LogPrintf("CFinalizedEvolution::SubmitVote - Failure to sign."); return; } std::string strError = ""; if(evolution.UpdateFinalizedEvolution(vote, NULL, strError)){ LogPrintf("CFinalizedEvolution::SubmitVote - new finalized evolution vote - %s\n", vote.GetHash().ToString()); evolution.mapSeenFinalizedEvolutionVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); } else { LogPrintf("CFinalizedEvolution::SubmitVote : Error submitting vote - %s\n", strError); } } CFinalizedEvolutionBroadcast::CFinalizedEvolutionBroadcast() { strEvolutionName = ""; nBlockStart = 0; vecEvolutionPayments.clear(); mapVotes.clear(); vchSig.clear(); nFeeTXHash = 0; } CFinalizedEvolutionBroadcast::CFinalizedEvolutionBroadcast(const CFinalizedEvolution& other) { strEvolutionName = other.strEvolutionName; nBlockStart = other.nBlockStart; BOOST_FOREACH(CTxEvolutionPayment out, other.vecEvolutionPayments) vecEvolutionPayments.push_back(out); mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; } CFinalizedEvolutionBroadcast::CFinalizedEvolutionBroadcast(std::string strEvolutionNameIn, int nBlockStartIn, std::vector<CTxEvolutionPayment> vecEvolutionPaymentsIn, uint256 nFeeTXHashIn) { strEvolutionName = strEvolutionNameIn; nBlockStart = nBlockStartIn; BOOST_FOREACH(CTxEvolutionPayment out, vecEvolutionPaymentsIn) vecEvolutionPayments.push_back(out); mapVotes.clear(); nFeeTXHash = nFeeTXHashIn; } void CFinalizedEvolutionBroadcast::Relay() { CInv inv(MSG_EVOLUTION_FINALIZED, GetHash()); RelayInv(inv, MIN_EVOLUTION_PEER_PROTO_VERSION); } CFinalizedEvolutionVote::CFinalizedEvolutionVote() { vin = CTxIn(); nEvolutionHash = 0; nTime = 0; vchSig.clear(); fValid = true; fSynced = false; } CFinalizedEvolutionVote::CFinalizedEvolutionVote(CTxIn vinIn, uint256 nEvolutionHashIn) { vin = vinIn; nEvolutionHash = nEvolutionHashIn; nTime = GetAdjustedTime(); vchSig.clear(); fValid = true; fSynced = false; } void CFinalizedEvolutionVote::Relay() { CInv inv(MSG_EVOLUTION_FINALIZED_VOTE, GetHash()); RelayInv(inv, MIN_EVOLUTION_PEER_PROTO_VERSION); } bool CFinalizedEvolutionVote::Sign(CKey& keyMasterX, CPubKey& pubKeyMasterX) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nEvolutionHash.ToString() + boost::lexical_cast<std::string>(nTime); if(!spySendSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasterX)) { LogPrintf("CFinalizedEvolutionVote::Sign - Error upon calling SignMessage"); return false; } if(!spySendSigner.VerifyMessage(pubKeyMasterX, vchSig, strMessage, errorMessage)) { LogPrintf("CFinalizedEvolutionVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CFinalizedEvolutionVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nEvolutionHash.ToString() + boost::lexical_cast<std::string>(nTime); CMasterX* pgm = gmineman.Find(vin); if(pgm == NULL) { LogPrint("gmevolution", "CFinalizedEvolutionVote::SignatureValid() - Unknown MasterX\n"); return false; } if(!fSignatureCheck) return true; if(!spySendSigner.VerifyMessage(pgm->pubkey2, vchSig, strMessage, errorMessage)) { LogPrintf("CFinalizedEvolutionVote::SignatureValid() - Verify message failed\n"); return false; } return true; } std::string CEvolutionManager::ToString() const { std::ostringstream info; info << "Proposals: " << (int)mapProposals.size() << ", Evolutions: " << (int)mapFinalizedEvolutions.size() << ", Seen Evolutions: " << (int)mapSeenMasterXEvolutionProposals.size() << ", Seen Evolution Votes: " << (int)mapSeenMasterXEvolutionVotes.size() << ", Seen Final Evolutions: " << (int)mapSeenFinalizedEvolutions.size() << ", Seen Final Evolution Votes: " << (int)mapSeenFinalizedEvolutionVotes.size(); return info.str(); }
35.379277
207
0.660722
redux-project
09885103cfdc6946b74cb6407bebb8425f3fd270
5,891
cpp
C++
src/cpp3ds/Window/GlContext.cpp
cpp3ds/cpp3ds
7813714776e2134bd75b9f3869ed142c1d4eeaaf
[ "MIT" ]
98
2015-08-26T16:49:29.000Z
2022-03-03T10:15:43.000Z
src/cpp3ds/Window/GlContext.cpp
Naxann/cpp3ds
1932e798306ec6d910c6a5b9e85e9d8f02fb815f
[ "MIT" ]
10
2016-02-26T21:30:51.000Z
2020-07-12T20:48:09.000Z
src/cpp3ds/Window/GlContext.cpp
Naxann/cpp3ds
1932e798306ec6d910c6a5b9e85e9d8f02fb815f
[ "MIT" ]
15
2015-10-16T06:22:37.000Z
2020-10-01T08:52:48.000Z
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <cpp3ds/Window/GlContext.hpp> #include <cpp3ds/System/ThreadLocalPtr.hpp> #include <cpp3ds/System/Mutex.hpp> #include <cpp3ds/System/Lock.hpp> #include <cpp3ds/System/Err.hpp> #include <cpp3ds/OpenGL.hpp> #include <set> #include <cstdlib> #include <cstring> #include "../Graphics/CitroHelpers.hpp" typedef cpp3ds::priv::GlContext ContextType; namespace { cpp3ds::priv::GlContext* currentContext(NULL); } namespace cpp3ds { namespace priv { //////////////////////////////////////////////////////////// void GlContext::globalInit() { } //////////////////////////////////////////////////////////// void GlContext::globalCleanup() { } //////////////////////////////////////////////////////////// void GlContext::ensureContext() { } //////////////////////////////////////////////////////////// GlContext* GlContext::create() { // Create the context GlContext* context = new ContextType(NULL); context->initialize(); return context; } //////////////////////////////////////////////////////////// GlContext* GlContext::create(const ContextSettings& settings, unsigned int width, unsigned int height) { // Create the context GlContext* context = new ContextType(NULL, settings, width, height); context->initialize(); context->checkSettings(settings); return context; } //////////////////////////////////////////////////////////// GlContext::~GlContext() { } //////////////////////////////////////////////////////////// bool GlContext::makeCurrent() { return true; } //////////////////////////////////////////////////////////// void GlContext::setVerticalSyncEnabled(bool enabled) { } //////////////////////////////////////////////////////////// void GlContext::display() { } //////////////////////////////////////////////////////////// const ContextSettings& GlContext::getSettings() const { return m_settings; } //////////////////////////////////////////////////////////// int GlContext::getHandle() const { return m_context; } //////////////////////////////////////////////////////////// bool GlContext::setActive(bool active) { if (active) { if (this != currentContext) { // Activate the context if (makeCurrent()) { // Set it as the new current context for this thread currentContext = this; return true; } else { return false; } } else { // This context is already the active one on this thread, don't do anything return true; } } else { currentContext = nullptr; return true; } } //////////////////////////////////////////////////////////// GlContext::GlContext(GlContext* shared) { m_settings = ContextSettings(); } GlContext::GlContext(GlContext* shared, const ContextSettings& settings, unsigned int width, unsigned int height) { m_settings = settings; } //////////////////////////////////////////////////////////// int GlContext::evaluateFormat(unsigned int bitsPerPixel, const ContextSettings& settings, int colorBits, int depthBits, int stencilBits, int antialiasing, bool accelerated) { int colorDiff = static_cast<int>(bitsPerPixel) - colorBits; int depthDiff = static_cast<int>(settings.depthBits) - depthBits; int stencilDiff = static_cast<int>(settings.stencilBits) - stencilBits; int antialiasingDiff = static_cast<int>(settings.antialiasingLevel) - antialiasing; // Weight sub-scores so that better settings don't score equally as bad as worse settings colorDiff *= ((colorDiff > 0) ? 100000 : 1); depthDiff *= ((depthDiff > 0) ? 100000 : 1); stencilDiff *= ((stencilDiff > 0) ? 100000 : 1); antialiasingDiff *= ((antialiasingDiff > 0) ? 100000 : 1); // Aggregate the scores int score = std::abs(colorDiff) + std::abs(depthDiff) + std::abs(stencilDiff) + std::abs(antialiasingDiff); // Make sure we prefer hardware acceleration over features if (!accelerated) score += 100000000; return score; } //////////////////////////////////////////////////////////// void GlContext::initialize() { m_settings.attributeFlags = ContextSettings::Default; } //////////////////////////////////////////////////////////// void GlContext::checkSettings(const ContextSettings& requestedSettings) { // Perform checks to inform the user if they are getting a context they might not have expected } } // namespace priv } // namespace cpp3ds
26.899543
172
0.531489
cpp3ds
098b203ed47ea2f83904ec142e8243af2693b5c2
425
hpp
C++
src/uml/src_gen/uml/TransitionKind.hpp
dataliz9r/MDE4CPP
9c5ce01c800fb754c371f1a67f648366eeabae49
[ "MIT" ]
12
2017-02-17T10:33:51.000Z
2022-03-01T02:48:10.000Z
src/uml/src_gen/uml/TransitionKind.hpp
dataliz9r/MDE4CPP
9c5ce01c800fb754c371f1a67f648366eeabae49
[ "MIT" ]
28
2017-10-17T20:23:52.000Z
2021-03-04T16:07:13.000Z
src/uml/src_gen/uml/TransitionKind.hpp
vallesch/MDE4CPP
7f8a01dd6642820913b2214d255bef2ea76be309
[ "MIT" ]
22
2017-03-24T19:03:58.000Z
2022-03-31T12:10:07.000Z
//******************************************************************** //* //* Warning: This file was generated by ecore4CPP Generator //* //******************************************************************** #ifndef UML_TRANSITIONKIND_HPP #define UML_TRANSITIONKIND_HPP namespace uml { enum TransitionKind { EXTERNAL = 2 , INTERNAL = 0 , LOCAL = 1 }; } #endif /* end of include guard: TRANSITIONKIND_HPP */
20.238095
70
0.463529
dataliz9r
0995fe279f06b8839dcfdc735d9afb8c2abeb8d0
301
cpp
C++
codes/c++/69.cpp
YuanweiZHANG/Leetcode
14a083528431bc65ada8f8265a5ef9d0fae40ecd
[ "MIT" ]
null
null
null
codes/c++/69.cpp
YuanweiZHANG/Leetcode
14a083528431bc65ada8f8265a5ef9d0fae40ecd
[ "MIT" ]
null
null
null
codes/c++/69.cpp
YuanweiZHANG/Leetcode
14a083528431bc65ada8f8265a5ef9d0fae40ecd
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; /** * 2020-04-10 * Veronica */ class Solution { public: int mySqrt(int x) { long long i = 1; while (i*i <= x) { i++; } return i - 1; } }; int main() { Solution solution; int x = 2147395600; cout << solution.mySqrt(x) << endl; return 0; }
10.75
36
0.578073
YuanweiZHANG
09980aeac67f7a1a8528444b824a41170a25512d
584
cpp
C++
source/Animation.cpp
GoldenBunny/Millibox
34fcd59bd1e5c1a97c1058032aefba0b11d8e48a
[ "MIT" ]
1
2017-12-15T01:14:06.000Z
2017-12-15T01:14:06.000Z
source/Animation.cpp
GoldenBunny/Millibox
34fcd59bd1e5c1a97c1058032aefba0b11d8e48a
[ "MIT" ]
null
null
null
source/Animation.cpp
GoldenBunny/Millibox
34fcd59bd1e5c1a97c1058032aefba0b11d8e48a
[ "MIT" ]
null
null
null
#include"Animation.h" AnimationID animationGetID() { static AnimationID id = 0; return id++; } Animation::Animation() { id_ = animationGetID(); } Animation::~Animation() { } void Animation::update() { } void Animation::render() { } void Animation::setFrame(Frame& frame) { currentFrame_ = &frame; } Frame& Animation::addFrame() { frames_.emplace_back(std::make_unique<Frame>()); return *frames_.back(); } decltype(*Animation::currentFrame_)& Animation::getFrame() { return *currentFrame_; } decltype(Animation::frames_)& Animation::getFrameList() { return frames_; }
16.222222
60
0.703767
GoldenBunny
0999d0168753ba7c55d45a97979d1868f368ffaa
426
hxx
C++
inc/html5xx.d/Th.hxx
astrorigin/html5xx
cbaaeb232597a713630df7425752051036cf0cb2
[ "MIT" ]
null
null
null
inc/html5xx.d/Th.hxx
astrorigin/html5xx
cbaaeb232597a713630df7425752051036cf0cb2
[ "MIT" ]
null
null
null
inc/html5xx.d/Th.hxx
astrorigin/html5xx
cbaaeb232597a713630df7425752051036cf0cb2
[ "MIT" ]
null
null
null
/* * */ #ifndef _HTML5XX_TH_HXX_ #define _HTML5XX_TH_HXX_ #include "Element.hxx" #include "LineElement.hxx" using namespace std; namespace html { class Th: public Element { public: Th(): Element(InlineBlock, "th") {} Th( const string& text ): Element(InlineBlock, "th") { put(new LineElement(text)); } }; } // end namespace html #endif // _HTML5XX_TH_HXX_ // vi: set ai et sw=2 sts=2 ts=2 :
11.513514
34
0.643192
astrorigin
099ac66307ebad5646ad1a6c96e5befc8730a2d5
904
cpp
C++
55_Jump_Game.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
55_Jump_Game.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
55_Jump_Game.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
/* 55. Jump Game Medium You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. Example 1: Input: nums = [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: nums = [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 105 */ class Solution { public: bool canJump(vector<int>& nums) { int n=nums.size(); int i=0; for(int reach=0;i<n && i<=reach;i++){ reach=max(i+nums[i],reach); } return i==n; } };
21.52381
177
0.651549
AvadheshChamola
099ca926ae8826321fdccd4b02250d97515e334d
2,045
cpp
C++
backtracking/leetcode_backtracking/palindrome_permutation_2.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
backtracking/leetcode_backtracking/palindrome_permutation_2.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
backtracking/leetcode_backtracking/palindrome_permutation_2.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:04.000Z
2020-10-12T19:18:04.000Z
// // palindrome_permutation_2.cpp // leetcode_backtracking // // Created by Hadley on 24.08.20. // Copyright © 2020 Hadley. All rights reserved. // #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <stack> #include <cstring> #include <queue> #include <functional> #include <numeric> #include <map> using namespace std; class Solution { public: void permutation(string h,int l,vector<string>&res){ if(l==h.length()-1){ res.push_back(h); }else{ for(int i=l;i<h.length();i++){ if(i==l||h[i]!=h[l]){ swap(h[i],h[l]); permutation(h, l+1, res); } } } } void palindromeGeneration(string h, vector<string>&res, char mid, bool even){ permutation(h, 0, res); if(even){ for(int i=0;i<res.size();i++){ string temp=res[i]; reverse(temp.begin(), temp.end()); res[i]=res[i]+temp; } }else{ for(int i=0;i<res.size();i++){ string temp=res[i]; reverse(temp.begin(), temp.end()); res[i].push_back(mid); res[i]+=temp; } } } vector<string> generatePalindromes(string s) { if(s.length()<=1)return {s}; bool even=((s.length()&1)==0)?true:false; string half; unordered_map<char, int>map; for(int i=0;i<s.length();i++){ map[s[i]]++; if((map[s[i]]&1)==0)half.push_back(s[i]); } sort(half.begin(),half.end()); char mid=s[s.length()/2]; int count=0; for(auto x:map){ if(x.second&1){ count++; mid=x.first; } } if(count>1)return {}; vector<string>res; palindromeGeneration(half, res, mid,even); return res; } };
24.638554
81
0.476284
Hadleyhzy
09a171be83c094ec30e3aedd37d69703e5f1102c
4,202
hpp
C++
src/logistic_sim/include/OnlineDCOPTaskPlanner.hpp
Astuxx/RMAPD
4d1c5f5d2e1ffa56094bbe79f818a536d0a48d52
[ "Apache-2.0" ]
2
2021-11-14T13:55:42.000Z
2022-03-30T03:22:40.000Z
src/logistic_sim/include/OnlineDCOPTaskPlanner.hpp
Astuxx/RMAPD
4d1c5f5d2e1ffa56094bbe79f818a536d0a48d52
[ "Apache-2.0" ]
5
2020-05-13T17:09:36.000Z
2020-06-11T17:02:21.000Z
src/logistic_sim/include/OnlineDCOPTaskPlanner.hpp
antonellocontini/LogisticAgent
5686bdd76462b6a0144d29295d449b29b76a8966
[ "Apache-2.0" ]
null
null
null
#pragma once #include "OnlineTaskPlanner.hpp" #include "logistic_sim/ChangeEdge.h" namespace onlinedcoptaskplanner { struct edge_modification_plan { uint from; uint to; uint timestep; int type; //1 == removal, 0 == addition const static int REMOVAL = 1; const static int ADDITION = 0; }; class OnlineDCOPTaskPlanner : public onlinetaskplanner::OnlineTaskPlanner { public: OnlineDCOPTaskPlanner(ros::NodeHandle &nh_, const std::string &name = "OnlineDCOPTaskPlanner"); void init(int argc, char **argv) override; void token_callback(const logistic_sim::TokenConstPtr &msg) override; protected: std::mt19937 gen; double total_search_duration = 0.0; uint last_mapf_timestep; uint mapf_attempts, max_mapf_attempts = 30; std::vector<std::vector<uint> > previous_attempts_configs; std::vector<double> astar_durations; std::vector<uint> astar_attempts, astar_timesteps; std::list<edge_modification_plan> edge_list; bool first_missions_sent = false; uint first_valid_timestep = 0; // std::chrono::system_clock::time_point last_edge_removal; ros::Time last_edge_removal; ros::ServiceServer change_edge_service; void print_graph(); // for test void advertise_change_edge_service(ros::NodeHandle &nh) override; bool change_edge(logistic_sim::ChangeEdge::Request &msg, logistic_sim::ChangeEdge::Response &res); // edges that must be removed in the next token cycle std::vector<logistic_sim::Edge> removed_edges, added_edges; boost::mutex edges_mutex; // used to avoid conflicts with the token thread and the main thread std::vector<bool> _check_conflict_free_impl(uint task_endpoint, std::vector<uint> *homes = nullptr); bool check_conflict_free_property(std::vector<uint> *homes = nullptr, double *reachability_factor = nullptr, bool print = true); void write_statistics(const logistic_sim::Token &msg, bool consider_current_search = false); // check if a configuration is good for recovery bool check_valid_recovery_configuration(const std::vector<uint> &configuration , const std::vector<uint> &robot_ids , const std::vector<std::vector<uint> > &waypoints , double* reachability_factor = nullptr , std::vector<uint> *reached_per_robot = nullptr , std::vector<uint> *destinations_per_robot = nullptr); std::vector<std::vector<uint> > find_all_recovery_configs(const std::vector<std::vector<uint> > &waypoints, const std::vector<uint> &robot_ids); std::vector<uint> find_best_recovery_config(const std::vector<std::vector<uint> > &waypoints , const std::vector<uint> &robot_ids , const std::vector<uint> &current_config , const std::vector<std::vector<uint> > &other_paths); void _generate_near_configs_impl(std::vector<std::vector<uint> > &result, const std::vector<uint> &s, std::vector<uint> &temp_state, unsigned int robot_i = 0); std::vector<std::vector<uint> > generate_near_configs(const std::vector<uint> &config); std::vector<uint> create_random_config(const std::vector<uint> &valid_vertices, uint robot_number, const std::set<std::vector<uint>, std::function<bool(const std::vector<uint> &, const std::vector<uint> &)>> &visited_states); std::vector<uint> local_search_recovery_config(const std::vector<std::vector<uint> > &waypoints , const std::vector<uint> &robot_ids , const std::vector<std::vector<uint> > &other_paths , std::chrono::duration<double> *search_duration = nullptr); void init_token(const logistic_sim::TokenConstPtr &msg, logistic_sim::Token &token); void multi_agent_repair(const logistic_sim::TokenConstPtr &msg, logistic_sim::Token &token); std::vector<std::vector<unsigned int>> map_graph, fw_matrix; std::vector<std::vector<unsigned int> > build_graph(); void build_fw_matrix(); }; }
45.673913
161
0.672061
Astuxx
09a4a4443b0c7a13047d459f5642b11aa145f8f6
1,654
hpp
C++
include/axl.gl/gfx/texture/Texture.hpp
Defalt8/axl.gl
0028bcad1a86b048831e5fd61a436663fd38a763
[ "MIT" ]
6
2020-11-20T08:29:33.000Z
2021-12-13T14:41:52.000Z
include/axl.gl/gfx/texture/Texture.hpp
Defalt8/axl.gl
0028bcad1a86b048831e5fd61a436663fd38a763
[ "MIT" ]
null
null
null
include/axl.gl/gfx/texture/Texture.hpp
Defalt8/axl.gl
0028bcad1a86b048831e5fd61a436663fd38a763
[ "MIT" ]
null
null
null
#pragma once #include "../../lib.hpp" #include "../../ContextObject.hpp" #include <axl.glfl/gl.hpp> #include <axl.math/vec/Vec2i.hpp> namespace axl { namespace gl { namespace gfx { class AXLGLCXXAPI Texture : public ContextObject { public: enum class Type { TT_1D = 1, TT_2D = 2, TT_3D = 3 }; public: Texture(axl::gl::Context* ptr_context = (axl::gl::Context*)0); virtual ~Texture(); virtual Type type() const = 0; protected: virtual bool iCreate() = 0; virtual bool iDestroy() = 0; public: virtual bool isValid() const = 0; virtual axl::glfl::GLuint getId() const = 0; virtual bool bind() const = 0; virtual bool bind(axl::glfl::GLuint texture_slot) const = 0; virtual bool unbind() const = 0; virtual bool unbind(axl::glfl::GLuint texture_slot) const = 0; virtual bool setParami(axl::glfl::GLenum tex_param, axl::glfl::GLint value) = 0; virtual bool setParamf(axl::glfl::GLenum tex_param, axl::glfl::GLfloat value) = 0; virtual bool setParamiv(axl::glfl::GLenum tex_param, const axl::glfl::GLint* value) = 0; virtual bool setParamfv(axl::glfl::GLenum tex_param, const axl::glfl::GLfloat* value) = 0; virtual bool getParamiv(axl::glfl::GLenum tex_param, axl::glfl::GLint* value) = 0; virtual bool getParamfv(axl::glfl::GLenum tex_param, axl::glfl::GLfloat* value) = 0; virtual bool getLevelParamiv(axl::glfl::GLint level, axl::glfl::GLenum tex_param, axl::glfl::GLint* value) = 0; virtual bool getLevelParamfv(axl::glfl::GLint level, axl::glfl::GLenum tex_param, axl::glfl::GLfloat* value) = 0; protected: axl::glfl::GLuint txr_id; }; } // namespace axl.gl.gfx } // namespace axl.gl } // namespace axl
36.755556
115
0.697703
Defalt8
09a4c0c0325b8991137daf61041a995f1da1ae41
3,118
hpp
C++
src/cg.hpp
spinicist/riesling
fa98ef1380345aa47d57ba91c970f37fe8fc5405
[ "MIT" ]
14
2021-02-08T21:28:37.000Z
2022-03-16T08:08:50.000Z
src/cg.hpp
spinicist/riesling
fa98ef1380345aa47d57ba91c970f37fe8fc5405
[ "MIT" ]
29
2021-02-19T11:59:33.000Z
2022-02-24T20:45:57.000Z
src/cg.hpp
spinicist/riesling
fa98ef1380345aa47d57ba91c970f37fe8fc5405
[ "MIT" ]
3
2021-07-29T14:54:25.000Z
2022-01-14T10:59:05.000Z
#pragma once #include "log.h" #include "tensorOps.h" #include "threads.h" #include "types.h" /* Conjugate gradients as described in K. P. Pruessmann, M. Weiger, M. B. Scheidegger, and P. * Boesiger, ‘SENSE: Sensitivity encoding for fast MRI’, Magnetic Resonance in Medicine, vol. 42, * no. 5, pp. 952–962, 1999. */ template <typename Op> void cg(Index const &max_its, float const &thresh, Op const &op, typename Op::Input &x, Log &log) { log.info(FMT_STRING("Starting Conjugate Gradients, threshold {}"), thresh); auto dev = Threads::GlobalDevice(); float const norm_x0 = Norm2(x); // Allocate all memory using T = typename Op::Input; auto const dims = x.dimensions(); T q(dims); T p(dims); T r(dims); q.setZero(); op.AdjA(x, r); r.device(dev) = x - r; p.device(dev) = r; float r_old = Norm2(r); for (Index icg = 0; icg < max_its; icg++) { op.AdjA(p, q); log.image(p, fmt::format(FMT_STRING("cg-p-{:02}.nii"), icg)); log.image(q, fmt::format(FMT_STRING("cg-q-{:02}.nii"), icg)); log.image(x, fmt::format(FMT_STRING("cg-x-{:02}.nii"), icg)); log.image(r, fmt::format(FMT_STRING("cg-r-{:02}.nii"), icg)); float const alpha = r_old / std::real(Dot(p, q)); x.device(dev) = x + p * p.constant(alpha); r.device(dev) = r - q * q.constant(alpha); float const r_new = Norm2(r); float const beta = r_new / r_old; p.device(dev) = r + p * p.constant(beta); float const delta = r_new / norm_x0; log.info(FMT_STRING("CG {}: ɑ {} β {} δ {}"), icg, alpha, beta, delta); if (delta < thresh) { log.info(FMT_STRING("Reached convergence threshold")); break; } r_old = r_new; } } template <typename Op> void cgvar( Index const &max_its, float const &thresh, float const &pre0, float const &pre1, Op &op, typename Op::Input &x, Log &log) { log.info(FMT_STRING("Starting Variably Preconditioned Conjugate Gradients")); auto dev = Threads::GlobalDevice(); // Allocate all memory using T = typename Op::Input; auto const dims = x.dimensions(); T b(dims); T q(dims); T p(dims); T r(dims); T r1(dims); b.setZero(); q.setZero(); p = x; r = x; float const a2 = Norm2(x); for (Index icg = 0; icg < max_its; icg++) { float const prog = static_cast<float>(icg) / ((max_its == 1) ? 1. : (max_its - 1.f)); float const pre = std::exp(std::log(pre1) * prog + std::log(pre0) * (1.f - prog)); op.setPreconditioning(pre); op.AdjA(p, q); r1 = r; float const r_old = Norm2(r1); float const alpha = r_old / std::real(Dot(p, q)); b.device(dev) = b + p * p.constant(alpha); r.device(dev) = r - q * q.constant(alpha); float const r_new = std::real(Dot(r, r - r1)); float const beta = r_new / r_old; p.device(dev) = r + p * p.constant(beta); float const delta = r_new / a2; log.image(b, fmt::format(FMT_STRING("cg-b-{:02}.nii"), icg)); log.info(FMT_STRING("CG {}: ɑ {} β {} δ {} pre {}"), icg, alpha, beta, delta, pre); if (delta < thresh) { log.info(FMT_STRING("Reached convergence threshold")); break; } } x = b; }
30.568627
97
0.603592
spinicist
09a705bb22d5d6b4b1e90882b1afa8d4d9e82d83
5,797
cpp
C++
dbms/src/Storages/DeltaMerge/ColumnFile/ColumnFile_V2.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
85
2022-03-25T09:03:16.000Z
2022-03-25T09:45:03.000Z
dbms/src/Storages/DeltaMerge/ColumnFile/ColumnFile_V2.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
7
2022-03-25T08:59:10.000Z
2022-03-25T09:40:13.000Z
dbms/src/Storages/DeltaMerge/ColumnFile/ColumnFile_V2.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
11
2022-03-25T09:15:36.000Z
2022-03-25T09:45:07.000Z
// Copyright 2022 PingCAP, Ltd. // // 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 <Storages/DeltaMerge/ColumnFile/ColumnFileBig.h> #include <Storages/DeltaMerge/ColumnFile/ColumnFileDeleteRange.h> #include <Storages/DeltaMerge/ColumnFile/ColumnFileTiny.h> namespace DB { namespace DM { struct ColumnFileV2 { UInt64 rows = 0; UInt64 bytes = 0; BlockPtr schema; RowKeyRange delete_range; PageId data_page_id = 0; bool isDeleteRange() const { return !delete_range.none(); } }; using ColumnFileV2Ptr = std::shared_ptr<ColumnFileV2>; using ColumnFileV2s = std::vector<ColumnFileV2Ptr>; inline ColumnFilePersisteds transform_V2_to_V3(const ColumnFileV2s & column_files_v2) { ColumnFilePersisteds column_files_v3; for (const auto & f : column_files_v2) { ColumnFilePersistedPtr f_v3; if (f->isDeleteRange()) f_v3 = std::make_shared<ColumnFileDeleteRange>(std::move(f->delete_range)); else f_v3 = std::make_shared<ColumnFileTiny>(f->schema, f->rows, f->bytes, f->data_page_id); column_files_v3.push_back(f_v3); } return column_files_v3; } inline ColumnFileV2s transformSaved_V3_to_V2(const ColumnFilePersisteds & column_files_v3) { ColumnFileV2s column_files_v2; for (const auto & f : column_files_v3) { auto * f_v2 = new ColumnFileV2(); if (auto * f_delete = f->tryToDeleteRange(); f_delete) { f_v2->delete_range = f_delete->getDeleteRange(); } else if (auto * f_tiny_file = f->tryToTinyFile(); f_tiny_file) { f_v2->rows = f_tiny_file->getRows(); f_v2->bytes = f_tiny_file->getBytes(); f_v2->schema = f_tiny_file->getSchema(); f_v2->data_page_id = f_tiny_file->getDataPageId(); } else { throw Exception("Unexpected column file type", ErrorCodes::LOGICAL_ERROR); } column_files_v2.push_back(std::shared_ptr<ColumnFileV2>(f_v2)); } return column_files_v2; } inline void serializeColumnFile_V2(const ColumnFileV2 & column_file, const BlockPtr & schema, WriteBuffer & buf) { writeIntBinary(column_file.rows, buf); writeIntBinary(column_file.bytes, buf); column_file.delete_range.serialize(buf); writeIntBinary(column_file.data_page_id, buf); if (schema) { writeIntBinary(static_cast<UInt32>(schema->columns()), buf); for (auto & col : *column_file.schema) { writeIntBinary(col.column_id, buf); writeStringBinary(col.name, buf); writeStringBinary(col.type->getName(), buf); } } else { writeIntBinary(static_cast<UInt32>(0), buf); } } void serializeSavedColumnFiles_V2(WriteBuffer & buf, const ColumnFileV2s & column_files) { writeIntBinary(column_files.size(), buf); BlockPtr last_schema; for (const auto & column_file : column_files) { // Do not encode the schema if it is the same as previous one. if (column_file->isDeleteRange()) serializeColumnFile_V2(*column_file, nullptr, buf); else { if (unlikely(!column_file->schema)) throw Exception("A data pack without schema", ErrorCodes::LOGICAL_ERROR); if (column_file->schema != last_schema) { serializeColumnFile_V2(*column_file, column_file->schema, buf); last_schema = column_file->schema; } else { serializeColumnFile_V2(*column_file, nullptr, buf); } } } } void serializeSavedColumnFilesInV2Format(WriteBuffer & buf, const ColumnFilePersisteds & column_files) { serializeSavedColumnFiles_V2(buf, transformSaved_V3_to_V2(column_files)); } inline ColumnFileV2Ptr deserializeColumnFile_V2(ReadBuffer & buf, UInt64 version) { auto column_file = std::make_shared<ColumnFileV2>(); readIntBinary(column_file->rows, buf); readIntBinary(column_file->bytes, buf); switch (version) { case DeltaFormat::V1: { HandleRange range; readPODBinary(range, buf); column_file->delete_range = RowKeyRange::fromHandleRange(range); break; } case DeltaFormat::V2: column_file->delete_range = RowKeyRange::deserialize(buf); break; default: throw Exception("Unexpected version: " + DB::toString(version), ErrorCodes::LOGICAL_ERROR); } readIntBinary(column_file->data_page_id, buf); column_file->schema = deserializeSchema(buf); return column_file; } ColumnFilePersisteds deserializeSavedColumnFilesInV2Format(ReadBuffer & buf, UInt64 version) { size_t size; readIntBinary(size, buf); ColumnFileV2s column_files; BlockPtr last_schema; for (size_t i = 0; i < size; ++i) { auto column_file = deserializeColumnFile_V2(buf, version); if (!column_file->isDeleteRange()) { if (!column_file->schema) column_file->schema = last_schema; else last_schema = column_file->schema; } column_files.push_back(column_file); } return transform_V2_to_V3(column_files); } } // namespace DM } // namespace DB
31.677596
112
0.661549
solotzg
09a8f94ff7fc25dae5fb4875da7d70ec2e24222c
7,666
cpp
C++
shared-code/kICMP.cpp
MythicMadTesla/Pumpkin
6e7e413ca364d79673e523c09767c18e7cff1bec
[ "MIT" ]
6
2017-01-23T18:18:03.000Z
2022-01-31T06:07:02.000Z
shared-code/kICMP.cpp
hacker/T42
025f8c9b1a478eed9dcb9e0ac13b9e26e955860a
[ "MIT" ]
null
null
null
shared-code/kICMP.cpp
hacker/T42
025f8c9b1a478eed9dcb9e0ac13b9e26e955860a
[ "MIT" ]
3
2016-10-24T03:32:35.000Z
2022-03-13T21:00:38.000Z
#include "../stdafx.h" #include "kICMP.h" CICMP::_mechanismus CICMP::m_mechanismus = CICMP::_icmpUndetermined; BOOL CICMPDll::Initialize() { if(m_hICMP!=INVALID_HANDLE_VALUE || m_hICMPDLL) Deinitialize(); m_hICMPDLL = ::LoadLibraryEx("ICMP",NULL,0); if(!m_hICMPDLL) return FALSE; *(FARPROC*)&m_icmpCF = ::GetProcAddress(m_hICMPDLL,"IcmpCreateFile"); *(FARPROC*)&m_icmpSE = ::GetProcAddress(m_hICMPDLL,"IcmpSendEcho"); *(FARPROC*)&m_icmpCH = ::GetProcAddress(m_hICMPDLL,"IcmpCloseHandle"); if(!(m_icmpCF && m_icmpSE && m_icmpCH)){ Deinitialize(); return FALSE; } m_hICMP = (*m_icmpCF)(); if(m_hICMP==INVALID_HANDLE_VALUE){ Deinitialize(); return FALSE; } TRACE0("ICMP-DLL Initialized\n"); return TRUE; } void CICMPDll::Deinitialize() { if(m_hICMPDLL){ if(m_hICMP!=INVALID_HANDLE_VALUE && m_icmpCH) (*m_icmpCH)(m_hICMP); ::FreeLibrary(m_hICMPDLL); m_hICMPDLL = NULL; m_icmpCF = NULL; m_icmpSE = NULL; m_icmpCH = NULL; } m_hICMP=INVALID_HANDLE_VALUE; if(m_sizeOut && m_bsOut){ delete m_bsOut; m_bsOut = NULL; m_sizeOut = 0; } if(m_sizeIn && m_bsIn){ delete m_bsIn; m_bsIn = NULL; m_sizeIn = 0; } } LONG CICMPDll::Ping(const in_addr host,const UINT packetSize, const UINT timeOut,LPINT pStatus) { if(!(m_hICMP && m_hICMPDLL && m_icmpSE)){ if(pStatus) (*pStatus) = icmpNotInitialized; return -1; } VERIFY(AdjustBuffers(packetSize)); IPINFO ipi; memset(&ipi,0,sizeof(ipi)); ipi.Ttl = 30; for(UINT tmp=0;tmp<packetSize;tmp++) m_bsOut[tmp]=tmp&0xFF; LPICMPECHO pRep = (LPICMPECHO)m_bsIn; pRep->Status = 0xFFFFFFFFl; if((*m_icmpSE)(m_hICMP,host.s_addr,m_bsOut,packetSize, &ipi,pRep,m_sizeIn,timeOut)) TRACE0("ICMP-SendEcho succeeded\n"); else TRACE0("ICMP-SendEcho failed\n"); LONG lrv = -1; INT rv = ipUnknown; switch(pRep->Status){ case IP_SUCCESS: lrv = pRep->RTTime; rv = ipSuccess; break; case IP_BUF_TOO_SMALL: rv = ipBuffTooSmall; break; case IP_DEST_NET_UNREACHABLE: rv = ipDestNetUnreachable; break; case IP_DEST_HOST_UNREACHABLE: rv = ipDestHostUnreachable; break; case IP_DEST_PROT_UNREACHABLE: rv = ipDestProtUnreachable; break; case IP_DEST_PORT_UNREACHABLE: rv = ipDestPortUnreachable; break; case IP_NO_RESOURCES: rv = ipNoResources; break; case IP_BAD_OPTION: rv = ipBadOption; break; case IP_HW_ERROR: rv = ipHWError; break; case IP_PACKET_TOO_BIG: rv = ipPacketTooBig; break; case IP_REQ_TIMED_OUT: rv = ipTimeOut; break; case IP_BAD_REQ: rv = ipBadRequest; break; case IP_BAD_ROUTE: rv = ipBadRoute; break; case IP_TTL_EXPIRED_TRANSIT: rv = ipTTLExpiredInTransit; break; case IP_TTL_EXPIRED_REASSEM: rv = ipTTLExpiredInReasm; break; case IP_PARAM_PROBLEM: rv = ipParamProblem; break; case IP_SOURCE_QUENCH: rv = ipSourceQuench; break; case IP_OPTION_TOO_BIG: rv = ipOptionTooBig; break; case IP_BAD_DESTINATION: rv = ipBadDest; break; } if(pStatus) (*pStatus)=rv; return lrv; } BOOL CICMPDll::AdjustBuffers(UINT packetSize) { if(!packetSize) packetSize=1; if(packetSize>m_sizeOut){ if(m_sizeOut && m_bsOut) delete m_bsOut; m_bsOut = new BYTE[m_sizeOut=packetSize]; if(!m_bsOut) return FALSE; } UINT sin = sizeof(ICMPECHO)+SIZE_ICMP_HDR+packetSize; if(sin>m_sizeIn){ if(m_sizeIn && m_bsIn) delete m_bsIn; m_bsIn = new BYTE[m_sizeIn=sin]; if(!m_bsIn) return FALSE; } return TRUE; } WORD CICMPWS::m_icmpSeq = 0; BOOL CICMPWS::Initialize() { if(m_socket!=INVALID_SOCKET) Deinitialize(); m_socket = socket(AF_INET,SOCK_RAW,1/*ICMP*/); if(m_socket==INVALID_SOCKET) return FALSE; TRACE0("ICMP-WS Initialized\n"); return TRUE; } void CICMPWS::Deinitialize() { if(m_socket!=INVALID_SOCKET){ closesocket(m_socket); m_socket=INVALID_SOCKET; } if(m_sizeOut && m_bsOut){ delete m_bsOut; m_bsOut = NULL; m_sizeOut = 0; } if(m_sizeIn && m_bsIn){ delete m_bsIn; m_bsIn = NULL; m_sizeIn = 0; } } LONG CICMPWS::Ping(const in_addr host,const UINT packetSize, const UINT timeOut,LPINT pStatus) { if(m_socket==INVALID_SOCKET){ if(pStatus) (*pStatus)=icmpNotInitialized; } VERIFY(AdjustBuffers(packetSize)); icmp* pPacket = (icmp*)m_bsOut; memset(pPacket,0,m_sizeOut); pPacket->icmp_type = ICMP_ECHO; pPacket->icmp_seq = m_icmpSeq++; pPacket->icmp_id = (WORD)(::GetCurrentThreadId()&0xFFFF); for(UINT tmp=0;tmp<packetSize;tmp++) pPacket->icmp_data[tmp]=tmp&0xFF; pPacket->icmp_cksum = cksum(pPacket,SIZE_ICMP_HDR+packetSize); sockaddr_in to; memset(&to,0,sizeof(to)); to.sin_addr.s_addr = host.s_addr; to.sin_family = AF_INET; if(sendto(m_socket,(char*)pPacket,SIZE_ICMP_HDR+packetSize,0, (SOCKADDR*)&to,sizeof(to)) != (int)(SIZE_ICMP_HDR+packetSize)){ TRACE1("sendto: %lu\n",WSAGetLastError()); if(pStatus) (*pStatus)=icmpSocketError; return -1; } DWORD sentTime = ::GetTickCount(); sockaddr_in from; memset(&from,0,sizeof(from)); from.sin_family=AF_INET; from.sin_addr.s_addr=INADDR_ANY; fd_set fds; FD_ZERO(&fds); FD_SET(m_socket,&fds); long lrv = -1; INT rv = ipTimeOut; for(;;){ DWORD ct = ::GetTickCount(); if((ct-sentTime)>=timeOut){ TRACE0("Timeout\n"); break; } timeval tv = { (timeOut-ct+sentTime)/1000, (timeOut-ct+sentTime)%1000 }; // tv_sec, tv_usec (secs,microsecs) if(!select(m_socket,&fds,NULL,NULL,&tv)){ TRACE1("select: %d\n",WSAGetLastError()); break; } DWORD rtime = ::GetTickCount(); ASSERT(FD_ISSET(m_socket,&fds)); int fl = sizeof(from); int rb = recvfrom(m_socket,(char*)m_bsIn,m_sizeIn,0,(SOCKADDR*)&from,&fl); ip* pIP = (ip*)m_bsIn; icmp* pICMP = (icmp*)&m_bsIn[sizeof(ip)]; if(pICMP->icmp_id!=pPacket->icmp_id) continue; if(pICMP->icmp_seq!=pPacket->icmp_seq) continue; if(from.sin_addr.s_addr!=host.s_addr) continue; if(pICMP->icmp_type==ICMP_ECHOREPLY){ lrv=rtime-sentTime; rv=ipSuccess; break; } rv = ipUnknown; // *** break; } if(pStatus) (*pStatus)=rv; return lrv; } BOOL CICMPWS::AdjustBuffers(UINT packetSize) { if(!packetSize) packetSize=0; UINT osize = packetSize+SIZE_ICMP_HDR; if(m_sizeOut<osize){ if(m_sizeOut && m_bsOut) delete m_bsOut; m_bsOut = new BYTE[m_sizeOut=osize]; if(!m_bsOut) return FALSE; } UINT isize = osize+sizeof(ip); if(m_sizeIn<isize){ if(m_sizeIn && m_bsIn) delete m_bsIn; m_bsIn = new BYTE[m_sizeIn=isize]; if(!m_bsIn) return FALSE; } return TRUE; } WORD CICMPWS::cksum(LPVOID data,int count) { long lSum = 0; WORD *pData = (WORD*)data; while(count>0){ if(count>1){ lSum+=*(pData++); count-=2; }else{ lSum+=((WORD)*(BYTE*)pData)&0xFF; count--; } } lSum = (lSum&0xFFFF)+(lSum>>16); lSum += (lSum>>16); return (~lSum)&0xFFFF; } CICMP* CICMP::CreateICMP() { if(m_mechanismus==_icmpUndetermined) GuessMechanismus(); switch(m_mechanismus){ case _icmpWinsock: return new CICMPWS; break; case _icmpDLL: return new CICMPDll; break; } return NULL; } void CICMP::GuessMechanismus() { m_mechanismus=_icmpUndetermined; SOCKET testSocket = socket(AF_INET,SOCK_RAW,1); if(testSocket!=INVALID_SOCKET){ closesocket(testSocket); m_mechanismus=_icmpWinsock; }else{ HINSTANCE hICMP = ::LoadLibraryEx("ICMP",NULL,0); if(!hICMP) return; BOOL isThere = ( ::GetProcAddress(hICMP,"IcmpCreateFile") && ::GetProcAddress(hICMP,"IcmpSendEcho") && ::GetProcAddress(hICMP,"IcmpCloseHandle") ); ::FreeLibrary(hICMP); if(isThere) m_mechanismus=_icmpDLL; } }
25.553333
76
0.67845
MythicMadTesla
09aa022aa668f3b3c590df2a4d7f0013c725b9c5
584
cpp
C++
Labs/Lab10/Apoio/NaoInicializado.cpp
JudsonSS/ProgComp
6435c3e31a4b0715805feaf890223838161d11f0
[ "MIT" ]
11
2021-03-04T03:58:09.000Z
2022-02-27T16:32:41.000Z
Labs/Lab10/Apoio/NaoInicializado.cpp
JudsonSS/ProgComp
6435c3e31a4b0715805feaf890223838161d11f0
[ "MIT" ]
null
null
null
Labs/Lab10/Apoio/NaoInicializado.cpp
JudsonSS/ProgComp
6435c3e31a4b0715805feaf890223838161d11f0
[ "MIT" ]
7
2021-03-02T22:34:33.000Z
2022-03-06T21:18:15.000Z
#include <iostream> using namespace std; int main() { int v[3]; // cria vetor de 3 elementos cout << "Conteudo da posicao 0: " << v[0] << endl; cout << "Conteudo da posicao 1: " << v[1] << endl; cout << "Conteudo da posicao 2: " << v[2] << endl << endl; v[0] = 0; v[1] = 0; v[2] = 0; cout << "Conteudo da posicao 0: " << v[0] << endl; cout << "Conteudo da posicao 1: " << v[1] << endl; cout << "Conteudo da posicao 2: " << v[2] << endl; cout << "\nO vetor tem " << sizeof v << " bytes.\n"; cout << "Um elemento tem " << sizeof v[0] << " bytes.\n"; return 0; }
26.545455
59
0.532534
JudsonSS
09ac28c4ba8f62d1ccbf68ad5d6c2f9e6a895343
529
cpp
C++
Chapter-6-Functions/Review Questions and Exercises/Algorithm Workbench/35.cpp
jesushilarioh/C-Plus-Plus
bbff921460ac4267af48558f040c7d82ccf42d5e
[ "MIT" ]
3
2019-10-28T01:12:46.000Z
2021-10-16T09:16:31.000Z
Chapter-6-Functions/Review Questions and Exercises/Algorithm Workbench/35.cpp
jesushilarioh/C-Plus-Plus
bbff921460ac4267af48558f040c7d82ccf42d5e
[ "MIT" ]
null
null
null
Chapter-6-Functions/Review Questions and Exercises/Algorithm Workbench/35.cpp
jesushilarioh/C-Plus-Plus
bbff921460ac4267af48558f040c7d82ccf42d5e
[ "MIT" ]
4
2020-04-10T17:22:17.000Z
2021-11-04T14:34:00.000Z
/******************************************************************** * * 35. Write a function named timesTen that accepts an argument. * When the function is called, it should display the * product of its argument multiplied times 10. * * Jesus Hilario Hernandez * December 3, 2018 * ********************************************************************/ #include <iostream> using namespace std; void timesTen(double num) { cout << num * 10 << endl; } int main() { timesTen(29); return 0; }
21.16
69
0.476371
jesushilarioh
09bb578416867c3e8b94ff4658b03785186c763a
11,683
cpp
C++
qabstractitemview_c.cpp
mariuszmaximus/qt5pas-aarch64-linux-gnu
c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b
[ "Apache-2.0" ]
null
null
null
qabstractitemview_c.cpp
mariuszmaximus/qt5pas-aarch64-linux-gnu
c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b
[ "Apache-2.0" ]
null
null
null
qabstractitemview_c.cpp
mariuszmaximus/qt5pas-aarch64-linux-gnu
c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b
[ "Apache-2.0" ]
null
null
null
//****************************************************************************** // Copyright (c) 2005-2013 by Jan Van hijfte // // See the included file COPYING.TXT for details about the copyright. // // 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. //****************************************************************************** #include "qabstractitemview_c.h" void QAbstractItemView_setModel(QAbstractItemViewH handle, QAbstractItemModelH model) { ((QAbstractItemView *)handle)->setModel((QAbstractItemModel*)model); } QAbstractItemModelH QAbstractItemView_model(QAbstractItemViewH handle) { return (QAbstractItemModelH) ((QAbstractItemView *)handle)->model(); } void QAbstractItemView_setSelectionModel(QAbstractItemViewH handle, QItemSelectionModelH selectionModel) { ((QAbstractItemView *)handle)->setSelectionModel((QItemSelectionModel*)selectionModel); } QItemSelectionModelH QAbstractItemView_selectionModel(QAbstractItemViewH handle) { return (QItemSelectionModelH) ((QAbstractItemView *)handle)->selectionModel(); } void QAbstractItemView_setItemDelegate(QAbstractItemViewH handle, QAbstractItemDelegateH delegate) { ((QAbstractItemView *)handle)->setItemDelegate((QAbstractItemDelegate*)delegate); } QAbstractItemDelegateH QAbstractItemView_itemDelegate(QAbstractItemViewH handle) { return (QAbstractItemDelegateH) ((QAbstractItemView *)handle)->itemDelegate(); } void QAbstractItemView_setSelectionMode(QAbstractItemViewH handle, QAbstractItemView::SelectionMode mode) { ((QAbstractItemView *)handle)->setSelectionMode(mode); } QAbstractItemView::SelectionMode QAbstractItemView_selectionMode(QAbstractItemViewH handle) { return (QAbstractItemView::SelectionMode) ((QAbstractItemView *)handle)->selectionMode(); } void QAbstractItemView_setSelectionBehavior(QAbstractItemViewH handle, QAbstractItemView::SelectionBehavior behavior) { ((QAbstractItemView *)handle)->setSelectionBehavior(behavior); } QAbstractItemView::SelectionBehavior QAbstractItemView_selectionBehavior(QAbstractItemViewH handle) { return (QAbstractItemView::SelectionBehavior) ((QAbstractItemView *)handle)->selectionBehavior(); } void QAbstractItemView_currentIndex(QAbstractItemViewH handle, QModelIndexH retval) { *(QModelIndex *)retval = ((QAbstractItemView *)handle)->currentIndex(); } void QAbstractItemView_rootIndex(QAbstractItemViewH handle, QModelIndexH retval) { *(QModelIndex *)retval = ((QAbstractItemView *)handle)->rootIndex(); } void QAbstractItemView_setEditTriggers(QAbstractItemViewH handle, unsigned int triggers) { ((QAbstractItemView *)handle)->setEditTriggers((QAbstractItemView::EditTriggers)triggers); } unsigned int QAbstractItemView_editTriggers(QAbstractItemViewH handle) { return (unsigned int) ((QAbstractItemView *)handle)->editTriggers(); } void QAbstractItemView_setVerticalScrollMode(QAbstractItemViewH handle, QAbstractItemView::ScrollMode mode) { ((QAbstractItemView *)handle)->setVerticalScrollMode(mode); } QAbstractItemView::ScrollMode QAbstractItemView_verticalScrollMode(QAbstractItemViewH handle) { return (QAbstractItemView::ScrollMode) ((QAbstractItemView *)handle)->verticalScrollMode(); } void QAbstractItemView_setHorizontalScrollMode(QAbstractItemViewH handle, QAbstractItemView::ScrollMode mode) { ((QAbstractItemView *)handle)->setHorizontalScrollMode(mode); } QAbstractItemView::ScrollMode QAbstractItemView_horizontalScrollMode(QAbstractItemViewH handle) { return (QAbstractItemView::ScrollMode) ((QAbstractItemView *)handle)->horizontalScrollMode(); } void QAbstractItemView_setAutoScroll(QAbstractItemViewH handle, bool enable) { ((QAbstractItemView *)handle)->setAutoScroll(enable); } bool QAbstractItemView_hasAutoScroll(QAbstractItemViewH handle) { return (bool) ((QAbstractItemView *)handle)->hasAutoScroll(); } void QAbstractItemView_setAutoScrollMargin(QAbstractItemViewH handle, int margin) { ((QAbstractItemView *)handle)->setAutoScrollMargin(margin); } int QAbstractItemView_autoScrollMargin(QAbstractItemViewH handle) { return (int) ((QAbstractItemView *)handle)->autoScrollMargin(); } void QAbstractItemView_setTabKeyNavigation(QAbstractItemViewH handle, bool enable) { ((QAbstractItemView *)handle)->setTabKeyNavigation(enable); } bool QAbstractItemView_tabKeyNavigation(QAbstractItemViewH handle) { return (bool) ((QAbstractItemView *)handle)->tabKeyNavigation(); } void QAbstractItemView_setDropIndicatorShown(QAbstractItemViewH handle, bool enable) { ((QAbstractItemView *)handle)->setDropIndicatorShown(enable); } bool QAbstractItemView_showDropIndicator(QAbstractItemViewH handle) { return (bool) ((QAbstractItemView *)handle)->showDropIndicator(); } void QAbstractItemView_setDragEnabled(QAbstractItemViewH handle, bool enable) { ((QAbstractItemView *)handle)->setDragEnabled(enable); } bool QAbstractItemView_dragEnabled(QAbstractItemViewH handle) { return (bool) ((QAbstractItemView *)handle)->dragEnabled(); } void QAbstractItemView_setDragDropOverwriteMode(QAbstractItemViewH handle, bool overwrite) { ((QAbstractItemView *)handle)->setDragDropOverwriteMode(overwrite); } bool QAbstractItemView_dragDropOverwriteMode(QAbstractItemViewH handle) { return (bool) ((QAbstractItemView *)handle)->dragDropOverwriteMode(); } void QAbstractItemView_setDragDropMode(QAbstractItemViewH handle, QAbstractItemView::DragDropMode behavior) { ((QAbstractItemView *)handle)->setDragDropMode(behavior); } QAbstractItemView::DragDropMode QAbstractItemView_dragDropMode(QAbstractItemViewH handle) { return (QAbstractItemView::DragDropMode) ((QAbstractItemView *)handle)->dragDropMode(); } void QAbstractItemView_setDefaultDropAction(QAbstractItemViewH handle, Qt::DropAction dropAction) { ((QAbstractItemView *)handle)->setDefaultDropAction(dropAction); } Qt::DropAction QAbstractItemView_defaultDropAction(QAbstractItemViewH handle) { return (Qt::DropAction) ((QAbstractItemView *)handle)->defaultDropAction(); } void QAbstractItemView_setAlternatingRowColors(QAbstractItemViewH handle, bool enable) { ((QAbstractItemView *)handle)->setAlternatingRowColors(enable); } bool QAbstractItemView_alternatingRowColors(QAbstractItemViewH handle) { return (bool) ((QAbstractItemView *)handle)->alternatingRowColors(); } void QAbstractItemView_setIconSize(QAbstractItemViewH handle, const QSizeH size) { ((QAbstractItemView *)handle)->setIconSize(*(const QSize*)size); } void QAbstractItemView_iconSize(QAbstractItemViewH handle, PSize retval) { *(QSize *)retval = ((QAbstractItemView *)handle)->iconSize(); } void QAbstractItemView_setTextElideMode(QAbstractItemViewH handle, Qt::TextElideMode mode) { ((QAbstractItemView *)handle)->setTextElideMode(mode); } Qt::TextElideMode QAbstractItemView_textElideMode(QAbstractItemViewH handle) { return (Qt::TextElideMode) ((QAbstractItemView *)handle)->textElideMode(); } void QAbstractItemView_keyboardSearch(QAbstractItemViewH handle, PWideString search) { QString t_search; copyPWideStringToQString(search, t_search); ((QAbstractItemView *)handle)->keyboardSearch(t_search); } void QAbstractItemView_visualRect(QAbstractItemViewH handle, PRect retval, const QModelIndexH index) { QRect t_retval; t_retval = ((QAbstractItemView *)handle)->visualRect(*(const QModelIndex*)index); copyQRectToPRect(t_retval, retval); } void QAbstractItemView_scrollTo(QAbstractItemViewH handle, const QModelIndexH index, QAbstractItemView::ScrollHint hint) { ((QAbstractItemView *)handle)->scrollTo(*(const QModelIndex*)index, hint); } void QAbstractItemView_indexAt(QAbstractItemViewH handle, QModelIndexH retval, const QPointH point) { *(QModelIndex *)retval = ((QAbstractItemView *)handle)->indexAt(*(const QPoint*)point); } void QAbstractItemView_sizeHintForIndex(QAbstractItemViewH handle, PSize retval, const QModelIndexH index) { *(QSize *)retval = ((QAbstractItemView *)handle)->sizeHintForIndex(*(const QModelIndex*)index); } int QAbstractItemView_sizeHintForRow(QAbstractItemViewH handle, int row) { return (int) ((QAbstractItemView *)handle)->sizeHintForRow(row); } int QAbstractItemView_sizeHintForColumn(QAbstractItemViewH handle, int column) { return (int) ((QAbstractItemView *)handle)->sizeHintForColumn(column); } void QAbstractItemView_openPersistentEditor(QAbstractItemViewH handle, const QModelIndexH index) { ((QAbstractItemView *)handle)->openPersistentEditor(*(const QModelIndex*)index); } void QAbstractItemView_closePersistentEditor(QAbstractItemViewH handle, const QModelIndexH index) { ((QAbstractItemView *)handle)->closePersistentEditor(*(const QModelIndex*)index); } void QAbstractItemView_setIndexWidget(QAbstractItemViewH handle, const QModelIndexH index, QWidgetH widget) { ((QAbstractItemView *)handle)->setIndexWidget(*(const QModelIndex*)index, (QWidget*)widget); } QWidgetH QAbstractItemView_indexWidget(QAbstractItemViewH handle, const QModelIndexH index) { return (QWidgetH) ((QAbstractItemView *)handle)->indexWidget(*(const QModelIndex*)index); } void QAbstractItemView_setItemDelegateForRow(QAbstractItemViewH handle, int row, QAbstractItemDelegateH delegate) { ((QAbstractItemView *)handle)->setItemDelegateForRow(row, (QAbstractItemDelegate*)delegate); } QAbstractItemDelegateH QAbstractItemView_itemDelegateForRow(QAbstractItemViewH handle, int row) { return (QAbstractItemDelegateH) ((QAbstractItemView *)handle)->itemDelegateForRow(row); } void QAbstractItemView_setItemDelegateForColumn(QAbstractItemViewH handle, int column, QAbstractItemDelegateH delegate) { ((QAbstractItemView *)handle)->setItemDelegateForColumn(column, (QAbstractItemDelegate*)delegate); } QAbstractItemDelegateH QAbstractItemView_itemDelegateForColumn(QAbstractItemViewH handle, int column) { return (QAbstractItemDelegateH) ((QAbstractItemView *)handle)->itemDelegateForColumn(column); } QAbstractItemDelegateH QAbstractItemView_itemDelegate2(QAbstractItemViewH handle, const QModelIndexH index) { return (QAbstractItemDelegateH) ((QAbstractItemView *)handle)->itemDelegate(*(const QModelIndex*)index); } void QAbstractItemView_inputMethodQuery(QAbstractItemViewH handle, QVariantH retval, Qt::InputMethodQuery query) { *(QVariant *)retval = ((QAbstractItemView *)handle)->inputMethodQuery(query); } void QAbstractItemView_reset(QAbstractItemViewH handle) { ((QAbstractItemView *)handle)->reset(); } void QAbstractItemView_setRootIndex(QAbstractItemViewH handle, const QModelIndexH index) { ((QAbstractItemView *)handle)->setRootIndex(*(const QModelIndex*)index); } void QAbstractItemView_doItemsLayout(QAbstractItemViewH handle) { ((QAbstractItemView *)handle)->doItemsLayout(); } void QAbstractItemView_selectAll(QAbstractItemViewH handle) { ((QAbstractItemView *)handle)->selectAll(); } void QAbstractItemView_edit(QAbstractItemViewH handle, const QModelIndexH index) { ((QAbstractItemView *)handle)->edit(*(const QModelIndex*)index); } void QAbstractItemView_clearSelection(QAbstractItemViewH handle) { ((QAbstractItemView *)handle)->clearSelection(); } void QAbstractItemView_setCurrentIndex(QAbstractItemViewH handle, const QModelIndexH index) { ((QAbstractItemView *)handle)->setCurrentIndex(*(const QModelIndex*)index); } void QAbstractItemView_scrollToTop(QAbstractItemViewH handle) { ((QAbstractItemView *)handle)->scrollToTop(); } void QAbstractItemView_scrollToBottom(QAbstractItemViewH handle) { ((QAbstractItemView *)handle)->scrollToBottom(); } void QAbstractItemView_update(QAbstractItemViewH handle, const QModelIndexH index) { ((QAbstractItemView *)handle)->update(*(const QModelIndex*)index); }
33.096317
120
0.805101
mariuszmaximus
09c0367b4e8144139b5fd63ac1ed0628c1ba92f9
6,348
cpp
C++
src/tdmms_stamper/tdmms_autostamp/tdmms_autostamp_autofocus_action/src/tdmms_autostamp_autofocus_action_node.cpp
tdmms/tdmms
1bd779bb3d6fe6451cdc08dcd5b15a1bcbd03b35
[ "BSD-3-Clause" ]
16
2018-04-28T07:34:04.000Z
2022-01-27T02:46:43.000Z
src/tdmms_stamper/tdmms_autostamp/tdmms_autostamp_autofocus_action/src/tdmms_autostamp_autofocus_action_node.cpp
tdmms/tdmms
1bd779bb3d6fe6451cdc08dcd5b15a1bcbd03b35
[ "BSD-3-Clause" ]
1
2018-10-16T08:41:55.000Z
2018-10-16T08:44:33.000Z
src/tdmms_stamper/tdmms_autostamp/tdmms_autostamp_autofocus_action/src/tdmms_autostamp_autofocus_action_node.cpp
tdmms/tdmms
1bd779bb3d6fe6451cdc08dcd5b15a1bcbd03b35
[ "BSD-3-Clause" ]
2
2018-04-17T14:03:15.000Z
2020-05-12T04:59:43.000Z
// Copyright 2016 by S. Masubuchi #include <ros/ros.h> #include <std_msgs/Empty.h> #include <std_srvs/Empty.h> #include <std_msgs/UInt8.h> #include <std_msgs/UInt32.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Point.h> #include <stamper_sample_z/velocity.h> #include <actionlib/server/simple_action_server.h> #include <tdmms_autostamp_autofocus_action/AutoFocusAction.h> #include <stamper_sample_xy/velocity.h> #include <image_transport/image_transport.h> #include <opencv2/highgui/highgui.hpp> #include <halcon_bridge/halcon_bridge.h> #include <string> #include "Halcon.h" #include "hlib/CIOFrameGrab.h" #include "hlib/HInstance.h" #include "hlib/HpThread.h" using namespace HalconCpp; class autostamp_autofocus_class { protected: ros::NodeHandle node_; ros::Publisher stamper_nikon_cmd_z_abs; ros::Publisher stamper_nikon_revolv_set; ros::Subscriber image_subscriber_main; ros::Publisher stamper_sample_z_cmd_stp; ros::Publisher stamper_sample_z_cmd_vel; ros::Publisher stamper_sample_z_cmd_abs; ros::Publisher stamper_nic_100a_cmd_inten; ros::ServiceClient stamper_sample_z_wait_for_stop_client; actionlib::SimpleActionServer< tdmms_autostamp_autofocus_action::AutoFocusAction> as_; std::string action_name_; tdmms_autostamp_autofocus_action::AutoFocusFeedback feedback_; tdmms_autostamp_autofocus_action::AutoFocusResult result_; HObject ho_Image, ho_Image_buf; HTuple hv_WindowHandle_main, hv_WindowHandle_sub, hv_DeviceIdentifiers; public: autostamp_autofocus_class(std::string name) : as_(node_, name, boost::bind(&autostamp_autofocus_class::executeAutoFocus, this, _1), false), action_name_(name) { stamper_nikon_revolv_set = node_.advertise<std_msgs::UInt8>( "/stamper_nikon_master/cmd_revolv_set", 1); node_.advertise<std_msgs::UInt8>("/stamper_nic_100a/cmd_inten", 1); stamper_nikon_cmd_z_abs = node_.advertise<std_msgs::UInt32>("/stamper_nikon_master/cmd_z_abs", 1); stamper_sample_z_cmd_stp = node_.advertise<geometry_msgs::Point>( "/stamper_sample_z_master/cmd_stp_move", 1); stamper_sample_z_cmd_vel = node_.advertise<stamper_sample_z::velocity>( "/stamper_sample_z_master/cmd_vel", 1); stamper_sample_z_cmd_abs = node_.advertise<geometry_msgs::Point>( "/stamper_sample_z_master/cmd_abs_move", 1); stamper_nic_100a_cmd_inten = node_.advertise<std_msgs::UInt8>("/stamper_nic_100a/cmd_inten", 1); stamper_sample_z_wait_for_stop_client = node_.serviceClient<std_srvs::Empty>( "/stamper_sample_z_master/wait_for_stop"); as_.start(); } ~autostamp_autofocus_class(void) {} void imageStreamCallback(const sensor_msgs::Image::ConstPtr &Image) { halcon_bridge::toHObject(Image, &ho_Image_buf); ho_Image = ho_Image_buf; } void executeAutoFocus( const tdmms_autostamp_autofocus_action::AutoFocusGoalConstPtr & goalparam) { // as_.acceptNewGoal(); std_srvs::Empty emp_srv; geometry_msgs::Point pnt; pnt.x = 585000; pnt.y = 0; stamper_sample_z_cmd_abs.publish(pnt); ros::Duration(0.1).sleep(); stamper_sample_z_wait_for_stop_client.call(emp_srv); image_subscriber_main = node_.subscribe("/autostamp_camera_streamer/image_main", 1, &autostamp_autofocus_class::imageStreamCallback, this); ros::Duration(1).sleep(); //////////////////////////////////////// /// Set Objective Lens Tartlet to 5X //////////////////////////////////////// std_msgs::UInt8 pos; pos.data = 1; stamper_nikon_revolv_set.publish(pos); ros::Duration(0.1).sleep(); std_msgs::UInt8 light_inten; light_inten.data = 5; stamper_nic_100a_cmd_inten.publish(light_inten); ros::Duration(1).sleep(); /////////////////////////////////////// /// Set Z stage of Optical Microscope ////////////////////////////////////// std_msgs::UInt32 z_stage_pos; z_stage_pos.data = goalparam->start.data; stamper_nikon_cmd_z_abs.publish(z_stage_pos); geometry_msgs::Point point; // Local iconic variables HObject ho_Highpass, ho_Rect; HObject ho_ImageGray; // Local control variables HTuple hv_Index, hv_Width, hv_Height, hv_Mean; HTuple hv_Deviation, hv_deviation_tuple, hv_max_dev, hv_ind; HTuple hv_Deviation_prev; ros::Duration(2).sleep(); int i; for (i = 1; i <= goalparam->stepno.data; i += 1) { try { z_stage_pos.data = goalparam->start.data + (i - 1) * goalparam->delta_z.data; stamper_nikon_cmd_z_abs.publish(z_stage_pos); ros::Duration(0.3).sleep(); Rgb1ToGray(ho_Image, &ho_ImageGray); HighpassImage(ho_ImageGray, &ho_Highpass, 9, 9); GetImageSize(ho_Highpass, &hv_Width, &hv_Height); GenRectangle1(&ho_Rect, 0, 0, hv_Height, hv_Width); Intensity(ho_Rect, ho_Highpass, &hv_Mean, &hv_Deviation); hv_deviation_tuple[i] = hv_Deviation; if (as_.isPreemptRequested() || !ros::ok()) { ROS_INFO("%s: Preempted", action_name_.c_str()); // set the action state to preempted as_.setPreempted(); return; } ROS_INFO("deviation: %f", static_cast<double>(hv_deviation_tuple[i])); } catch (HalconCpp::HException &HDevExpDefaultException) { continue; } } ros::Duration(0.5).sleep(); for (i = 1; i <= goalparam->stepno.data - 1; i++) { if (hv_deviation_tuple[i + 1] - hv_deviation_tuple[i] > 1.0) { hv_deviation_tuple[i + 1] = 0.0; i++; } } TupleMax(hv_deviation_tuple, &hv_max_dev); TupleFind(hv_deviation_tuple, hv_max_dev, &hv_ind); z_stage_pos.data = (goalparam->start.data) + (static_cast<int>(hv_ind) - 1) * goalparam->delta_z.data; stamper_nikon_cmd_z_abs.publish(z_stage_pos); image_subscriber_main.shutdown(); result_.focuspos.data = z_stage_pos.data; ROS_INFO("%s: Succeeded", action_name_.c_str()); as_.setSucceeded(result_); } }; int main(int argc, char **argv) { ros::init(argc, argv, "tdmms_autostamp_autofocus_action"); autostamp_autofocus_class autofocus(ros::this_node::getName()); ROS_INFO("%s", ros::this_node::getName().c_str()); ros::spin(); return 0; }
35.071823
80
0.68305
tdmms
09c28f0640091347929ccc8fccfbd7ca14b099aa
348
cc
C++
kattis/differentdistances.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
kattis/differentdistances.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
kattis/differentdistances.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://open.kattis.com/problems/differentdistances #include <cmath> #include <iostream> using namespace std; int main() { while (true) { double x1, y1, x2, y2, p; cin >> x1; if (!x1) break; cin >> y1 >> x2 >> y2 >> p; cout << pow(pow(abs(x1 - x2), p) + pow(abs(y1 - y2), p), 1 / p) << endl; } }
23.2
80
0.511494
Ashindustry007
09c645719ac0202fd7df492ccab960fc05253e96
1,988
cpp
C++
mp2p_icp/src/Parameters.cpp
MOLAorg/mp2_icp
e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb
[ "BSD-3-Clause" ]
82
2019-06-09T15:33:07.000Z
2022-03-22T11:04:09.000Z
mp2p_icp/src/Parameters.cpp
MOLAorg/mp2_icp
e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb
[ "BSD-3-Clause" ]
null
null
null
mp2p_icp/src/Parameters.cpp
MOLAorg/mp2_icp
e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb
[ "BSD-3-Clause" ]
19
2019-06-19T10:05:08.000Z
2021-07-28T08:37:34.000Z
/* ------------------------------------------------------------------------- * A repertory of multi primitive-to-primitive (MP2P) ICP algorithms in C++ * Copyright (C) 2018-2021 Jose Luis Blanco, University of Almeria * See LICENSE for license information. * ------------------------------------------------------------------------- */ #include <mp2p_icp/Parameters.h> #include <mrpt/serialization/CArchive.h> #include <mrpt/serialization/stl_serialization.h> IMPLEMENTS_MRPT_OBJECT(Parameters, mrpt::serialization::CSerializable, mp2p_icp) using namespace mp2p_icp; // Implementation of the CSerializable virtual interface: uint8_t Parameters::serializeGetVersion() const { return 0; } void Parameters::serializeTo(mrpt::serialization::CArchive& out) const { out << maxIterations << minAbsStep_trans << minAbsStep_rot; out << generateDebugFiles << debugFileNameFormat; out << debugPrintIterationProgress; } void Parameters::serializeFrom( mrpt::serialization::CArchive& in, uint8_t version) { *this = Parameters(); switch (version) { case 0: { in >> maxIterations >> minAbsStep_trans >> minAbsStep_rot; in >> generateDebugFiles >> debugFileNameFormat; in >> debugPrintIterationProgress; } break; default: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version); }; } void Parameters::load_from(const mrpt::containers::yaml& p) { MCP_LOAD_REQ(p, maxIterations); MCP_LOAD_OPT(p, minAbsStep_trans); MCP_LOAD_OPT(p, minAbsStep_rot); MCP_LOAD_OPT(p, generateDebugFiles); MCP_LOAD_OPT(p, debugFileNameFormat); MCP_LOAD_OPT(p, debugPrintIterationProgress); } void Parameters::save_to(mrpt::containers::yaml& p) const { MCP_SAVE(p, maxIterations); MCP_SAVE(p, minAbsStep_trans); MCP_SAVE(p, minAbsStep_rot); MCP_SAVE(p, generateDebugFiles); MCP_SAVE(p, debugFileNameFormat); MCP_SAVE(p, debugPrintIterationProgress); }
33.133333
80
0.65996
MOLAorg
09c9bd9b13d66629443dce80ac037aa34a8fb77e
6,256
cpp
C++
src/joystick_js.cpp
chmutoff/esp-tank
ecb2a14317112e54001ff232a836e915b6ef2a6c
[ "MIT" ]
null
null
null
src/joystick_js.cpp
chmutoff/esp-tank
ecb2a14317112e54001ff232a836e915b6ef2a6c
[ "MIT" ]
null
null
null
src/joystick_js.cpp
chmutoff/esp-tank
ecb2a14317112e54001ff232a836e915b6ef2a6c
[ "MIT" ]
null
null
null
#include <pgmspace.h> static const char JOYSTICK_HTML[] PROGMEM = R"(/* * Name : joy.js * @author : Roberto D'Amico (Bobboteck) * Last modified : 09.06.2020 * Revision : 2.0.0 * * Modification History: * Date Version Modified By Description * 2021-12-21 2.0.0 Roberto D'Amico New version of the project that integrates the callback functions, while * maintaining compatibility with previous versions. Fixed Issue #27 too, * thanks to @artisticfox8 for the suggestion. * 2020-06-09 1.1.6 Roberto D'Amico Fixed Issue #10 and #11 * 2020-04-20 1.1.5 Roberto D'Amico Correct: Two sticks in a row, thanks to @liamw9534 for the suggestion * 2020-04-03 Roberto D'Amico Correct: InternalRadius when change the size of canvas, thanks to * @vanslipon for the suggestion * 2020-01-07 1.1.4 Roberto D'Amico Close #6 by implementing a new parameter to set the functionality of * auto-return to 0 position * 2019-11-18 1.1.3 Roberto D'Amico Close #5 correct indication of East direction * 2019-11-12 1.1.2 Roberto D'Amico Removed Fix #4 incorrectly introduced and restored operation with touch * devices * 2019-11-12 1.1.1 Roberto D'Amico Fixed Issue #4 - Now JoyStick work in any position in the page, not only * at 0,0 * * The MIT License (MIT) * * This file is part of the JoyStick Project (https://github.com/bobboteck/JoyStick). * Copyright (c) 2015 Roberto D'Amico (Bobboteck). * * 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. */ let StickStatus={xPosition:0,yPosition:0,x:0,y:0,cardinalDirection:"C"};var JoyStick=function(t,e,i){var o=void 0===(e=e||{}).title?"joystick":e.title,n=void 0===e.width?0:e.width,a=void 0===e.height?0:e.height,r=void 0===e.internalFillColor?"#00AA00":e.internalFillColor,c=void 0===e.internalLineWidth?2:e.internalLineWidth,s=void 0===e.internalStrokeColor?"#003300":e.internalStrokeColor,d=void 0===e.externalLineWidth?2:e.externalLineWidth,u=void 0===e.externalStrokeColor?"#008000":e.externalStrokeColor,h=void 0===e.autoReturnToCenter||e.autoReturnToCenter;i=i||function(t){};var S=document.getElementById(t);S.style.touchAction="none";var f=document.createElement("canvas");f.id=o,0===n&&(n=S.clientWidth),0===a&&(a=S.clientHeight),f.width=n,f.height=a,S.appendChild(f);var l=f.getContext("2d"),k=0,g=2*Math.PI,x=(f.width-(f.width/2+10))/2,v=x+5,P=x+30,m=f.width/2,C=f.height/2,p=f.width/10,y=-1*p,w=f.height/10,L=-1*w,F=m,E=C;function W(){l.beginPath(),l.arc(m,C,P,0,g,!1),l.lineWidth=d,l.strokeStyle=u,l.stroke()}function T(){l.beginPath(),F<x&&(F=v),F+x>f.width&&(F=f.width-v),E<x&&(E=v),E+x>f.height&&(E=f.height-v),l.arc(F,E,x,0,g,!1);var t=l.createRadialGradient(m,C,5,m,C,200);t.addColorStop(0,r),t.addColorStop(1,s),l.fillStyle=t,l.fill(),l.lineWidth=c,l.strokeStyle=s,l.stroke()}function D(){let t="",e=F-m,i=E-C;return i>=L&&i<=w&&(t="C"),i<L&&(t="N"),i>w&&(t="S"),e<y&&("C"===t?t="W":t+="W"),e>p&&("C"===t?t="E":t+="E"),t}"ontouchstart"in document.documentElement?(f.addEventListener("touchstart",function(t){k=1},!1),document.addEventListener("touchmove",function(t){1===k&&t.targetTouches[0].target===f&&(F=t.targetTouches[0].pageX,E=t.targetTouches[0].pageY,"BODY"===f.offsetParent.tagName.toUpperCase()?(F-=f.offsetLeft,E-=f.offsetTop):(F-=f.offsetParent.offsetLeft,E-=f.offsetParent.offsetTop),l.clearRect(0,0,f.width,f.height),W(),T(),StickStatus.xPosition=F,StickStatus.yPosition=E,StickStatus.x=((F-m)/v*100).toFixed(),StickStatus.y=((E-C)/v*100*-1).toFixed(),StickStatus.cardinalDirection=D(),i(StickStatus))},!1),document.addEventListener("touchend",function(t){k=0,h&&(F=m,E=C);l.clearRect(0,0,f.width,f.height),W(),T(),StickStatus.xPosition=F,StickStatus.yPosition=E,StickStatus.x=((F-m)/v*100).toFixed(),StickStatus.y=((E-C)/v*100*-1).toFixed(),StickStatus.cardinalDirection=D(),i(StickStatus)},!1)):(f.addEventListener("mousedown",function(t){k=1},!1),document.addEventListener("mousemove",function(t){1===k&&(F=t.pageX,E=t.pageY,"BODY"===f.offsetParent.tagName.toUpperCase()?(F-=f.offsetLeft,E-=f.offsetTop):(F-=f.offsetParent.offsetLeft,E-=f.offsetParent.offsetTop),l.clearRect(0,0,f.width,f.height),W(),T(),StickStatus.xPosition=F,StickStatus.yPosition=E,StickStatus.x=((F-m)/v*100).toFixed(),StickStatus.y=((E-C)/v*100*-1).toFixed(),StickStatus.cardinalDirection=D(),i(StickStatus))},!1),document.addEventListener("mouseup",function(t){k=0,h&&(F=m,E=C);l.clearRect(0,0,f.width,f.height),W(),T(),StickStatus.xPosition=F,StickStatus.yPosition=E,StickStatus.x=((F-m)/v*100).toFixed(),StickStatus.y=((E-C)/v*100*-1).toFixed(),StickStatus.cardinalDirection=D(),i(StickStatus)},!1)),W(),T(),this.GetWidth=function(){return f.width},this.GetHeight=function(){return f.height},this.GetPosX=function(){return F},this.GetPosY=function(){return E},this.GetX=function(){return((F-m)/v*100).toFixed()},this.GetY=function(){return((E-C)/v*100*-1).toFixed()},this.GetDir=function(){return D()}}; )";
122.666667
3,415
0.683824
chmutoff
09cb458642a2dafb2b0629b730e9dbdc3aaf7a17
1,915
cc
C++
src/lhco.cc
cbpark/CLHCO
4f6f73dc7a3a4dc25bfc7d7be9d34d5dd59fb9f0
[ "BSD-3-Clause" ]
null
null
null
src/lhco.cc
cbpark/CLHCO
4f6f73dc7a3a4dc25bfc7d7be9d34d5dd59fb9f0
[ "BSD-3-Clause" ]
null
null
null
src/lhco.cc
cbpark/CLHCO
4f6f73dc7a3a4dc25bfc7d7be9d34d5dd59fb9f0
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2015, 2017, Chan Beom Park <cbpark@gmail.com> */ #include "lhco.h" #include <cmath> #include <vector> #include "kinematics.h" namespace lhco { template <typename T> int numOfParticles(const Pt &pt, const Eta &eta, const std::vector<T> &ps) { int count = 0; for (const auto &p : ps) { if (p.pt() > pt.value && std::abs(p.eta()) < eta.value) { ++count; } } return count; } int numPhoton(const Event &ev) { return ev.photon().size(); } int numPhoton(const Pt &pt, const Eta &eta, const Event &ev) { return numOfParticles(pt, eta, ev.photon()); } int numElectron(const Event &ev) { return ev.electron().size(); } int numElectron(const Pt &pt, const Eta &eta, const Event &ev) { return numOfParticles(pt, eta, ev.electron()); } int numMuon(const Event &ev) { return ev.muon().size(); } int numMuon(const Pt &pt, const Eta &eta, const Event &ev) { return numOfParticles(pt, eta, ev.muon()); } int numTau(const Event &ev) { return ev.tau().size(); } int numTau(const Pt &pt, const Eta &eta, const Event &ev) { return numOfParticles(pt, eta, ev.tau()); } int numNormalJet(const Event &ev) { return ev.jet().size(); } int numNormalJet(const Pt &pt, const Eta &eta, const Event &ev) { return numOfParticles(pt, eta, ev.jet()); } int numBjet(const Event &ev) { return ev.bjet().size(); } int numBjet(const Pt &pt, const Eta &eta, const Event &ev) { return numOfParticles(pt, eta, ev.bjet()); } int numAllJet(const Event &ev) { return numNormalJet(ev) + numBjet(ev); } int numAllJet(const Pt &pt, const Eta &eta, const Event &ev) { return numNormalJet(pt, eta, ev) + numBjet(pt, eta, ev); } double missingET(const Event &ev) { return ev.met().pt(); } double invariantMass(const Visibles &ps) { Visible vis{Energy(0.0), Px(0.0), Py(0.0), Pz(0.0)}; for (const auto &p : ps) { vis += p; } return vis.mass(); } } // namespace lhco
28.161765
76
0.643342
cbpark
09cd1788e5cc2e597e58e3029bcf0543c0ed3020
13,402
inl
C++
src/render/scene.inl
hyungman/SpRay
96380740dd88e6fbc21c0fdbf232cff357b1235d
[ "Apache-2.0" ]
7
2018-10-22T17:13:36.000Z
2020-04-17T08:28:55.000Z
src/render/scene.inl
hyungman/SpRay
96380740dd88e6fbc21c0fdbf232cff357b1235d
[ "Apache-2.0" ]
null
null
null
src/render/scene.inl
hyungman/SpRay
96380740dd88e6fbc21c0fdbf232cff357b1235d
[ "Apache-2.0" ]
1
2018-11-01T14:53:22.000Z
2018-11-01T14:53:22.000Z
// ========================================================================== // // Copyright (c) 2017-2018 The University of Texas at Austin. // // All rights reserved. // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // A copy of the License is included with this software in the file LICENSE. // // If your copy does not contain the License, you may obtain a copy of the // // License at: // // // // https://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. // // // // ========================================================================== // #if !defined(SPRAY_SCENE_INL_) #error An implementation of Scene #endif #define DEBUG_SCENE #undef DEBUG_SCENE namespace spray { template <typename CacheT, typename SurfaceBufT> void Scene<CacheT, SurfaceBufT>::init(const std::string& desc_filename, const std::string& ply_path, const std::string& storage_basepath, int cache_size, int view_mode, bool insitu_mode, int num_partitions) { // load .domain file SceneLoader loader; loader.load(desc_filename, ply_path, &domains_, &lights_); // merge domain bounds and find the scene bounds std::size_t max_num_vertices, max_num_faces; mergeDomainBounds(&max_num_vertices, &max_num_faces); insitu_ = false; if (view_mode == VIEW_MODE_PARTITION) { partition_num_ = 0; num_partitions_ = num_partitions; // partition data if in-situ mode partition_.partition(getNumDomains(), getDomains(), getBound(), num_partitions); } else if (insitu_mode) { insitu_ = true; // partition data if in-situ mode partition_.partition(getNumDomains(), getDomains(), getBound(), mpi::size()); #ifdef SPRAY_GLOG_CHECK LOG(INFO) << "<<<<<INSITU MODE>>>>>>"; for (auto& r : partition_.getDomains(mpi::rank())) { LOG(INFO) << "rank " << mpi::rank() << " domain " << r; } #endif // NOTE: override cache size cache_size = partition_.getNumDomains(mpi::rank()); } // copy to local disk if (!storage_basepath.empty()) { storage_basepath_ = storage_basepath; copyAllDomainsToLocalDisk(storage_basepath, insitu_mode); } // initialize cache if (!(view_mode == VIEW_MODE_DOMAIN || view_mode == VIEW_MODE_PARTITION)) { cache_.init(domains_.size(), cache_size, insitu_mode); // initialize mesh buffer surface_buf_.init(cache_.getCacheSize(), max_num_vertices, max_num_faces, true /* compute_normals */); // warm up cache if (view_mode == VIEW_MODE_FILM || view_mode == VIEW_MODE_GLFW) { if (insitu_mode) { const std::list<int>& domains = partition_.getDomains(mpi::rank()); for (int id : domains) load(id); } else if (cache_size < 0) { for (std::size_t id = 0; id < domains_.size(); ++id) load(id); } } } wbvh_.init(getBound(), getDomains()); // for domain vis. glfw_domain_idx_ = 0; } template <typename CacheT, typename SurfaceBufT> void Scene<CacheT, SurfaceBufT>::buildWbvh() { #if defined(SPRAY_ISECT_PACKET1) wbvh_.build(WbvhEmbree::NORMAL1); #elif defined(SPRAY_ISECT_PACKET8) #if !defined(SPRAY_AVX2) #warning Use AVX2 for a packet of 8 rays. #endif wbvh_.build(WbvhEmbree::NORMAL8); #elif defined(SPRAY_ISECT_PACKET16) #if !defined(SPRAY_AVX512) #error unsupported #warning Use AVX512 for a packet of 16 rays. #endif wbvh_.build(WbvhEmbree::NORMAL16); #elif defined(SPRAY_ISECT_STREAM_1M) wbvh_.build(WbvhEmbree::STREAM_1M); #else #error unsupported #endif } template <typename CacheT, typename SurfaceBufT> void Scene<CacheT, SurfaceBufT>::load(int id) { int cache_block; if (cache_.load(id, &cache_block)) { #ifdef DEBUG_SCENE LOG(INFO) << "loading cached domain " << id << " cache block " << cache_block << " $size " << cache_.getSize() << " $capacity " << cache_.getCacheSize(); #endif scene_ = surface_buf_.get(cache_block); } else { #ifdef DEBUG_SCENE LOG(INFO) << "loading uncached domain " << id << " cache block " << cache_block << " $size " << cache_.getSize() << " $capacity " << cache_.getCacheSize(); #endif const glm::mat4& x = domains_[id].transform; bool apply_transform = (x != glm::mat4(1.0)); scene_ = surface_buf_.load(domains_[id].filename, cache_block, x, apply_transform); // cache_.setLoaded(cache_block); } cache_block_ = cache_block; } template <typename CacheT, typename SurfaceBufT> void Scene<CacheT, SurfaceBufT>::load(int id, SceneInfo* sinfo) { int cache_block; if (cache_.load(id, &cache_block)) { #ifdef DEBUG_SCENE LOG(INFO) << "loading cached domain " << id << " cache block " << cache_block << " $size " << cache_.getSize() << " $capacity " << cache_.getCacheSize(); #endif scene_ = surface_buf_.get(cache_block); } else { #ifdef DEBUG_SCENE LOG(INFO) << "loading uncached domain " << id << " cache block " << cache_block << " $size " << cache_.getSize() << " $capacity " << cache_.getCacheSize(); #endif const glm::mat4& x = domains_[id].transform; bool apply_transform = (x != glm::mat4(1.0)); scene_ = surface_buf_.load(domains_[id].filename, cache_block, x, apply_transform); // cache_.setLoaded(cache_block); } sinfo->rtc_scene = scene_; sinfo->cache_block = cache_block; } template <typename CacheT, typename SurfaceBufT> bool Scene<CacheT, SurfaceBufT>::intersect(RTCScene rtc_scene, int cache_block, RTCRayIntersection* isect) const { rtcIntersect(rtc_scene, (RTCRay&)(*isect)); if (isect->geomID != RTC_INVALID_GEOMETRY_ID) { surface_buf_.updateIntersection(cache_block, isect); return true; } return false; } template <typename CacheT, typename SurfaceBufT> bool Scene<CacheT, SurfaceBufT>::occluded(RTCScene rtc_scene, RTCRay* ray) const { rtcOccluded(rtc_scene, *ray); if (ray->geomID != RTC_INVALID_GEOMETRY_ID) { // occluded return true; } return false; // unoccluded } // copy only those domains mapped to this process. // we don't have to copy everything in some cases. template <typename CacheT, typename SurfaceBufT> void Scene<CacheT, SurfaceBufT>::copyAllDomainsToLocalDisk( const std::string& dest_path, bool insitu_mode) { // clean up existing folder // std::string stuff_to_remove = dest_path + "/*"; // std::string cmd_cleanup = "rm -rf " + stuff_to_remove; // std::cout << "cleaning up exiting files in " + dest_path << "\n"; // std::system(cmd_cleanup.c_str()); std::vector<int> ids; std::size_t domain_size; if (insitu_mode) { const std::list<int>& domains = partition_.getDomains(mpi::rank()); ids.reserve(domains.size()); for (int id : domains) { ids.push_back(id); } } else { ids.reserve(domains_.size()); for (std::size_t i = 0; i < domains_.size(); ++i) { ids.push_back(i); } } int res; // for (std::size_t i = 0; i < domains_.size(); ++i) { for (std::size_t i = 0; i < ids.size(); ++i) { int id = ids[i]; Domain& domain = domains_[id]; CHECK_EQ(id, domain.id); // create a new folder std::string new_dir = dest_path + "/proc" + std::to_string(mpi::rank()) + "_domain" + std::to_string(id); std::string cmd_make_dir = "mkdir " + new_dir; res = std::system(cmd_make_dir.c_str()); #ifdef SPRAY_GLOG_CHECK LOG(INFO) << cmd_make_dir << " " << res; #endif std::cout << cmd_make_dir << " " << res << std::endl; CHECK_EQ(res, 0); // extract basename std::string bname = std::string(util::getFilename(domain.filename.c_str())); std::string destination_file = new_dir + "/" + bname; // cp model file to local disk std::string cmd_copy_domain = "cp " + domain.filename + " " + destination_file; int res = std::system(cmd_copy_domain.c_str()); #ifdef SPRAY_GLOG_CHECK LOG(INFO) << cmd_copy_domain << " " << res; #endif std::cout << cmd_copy_domain << " " << res << std::endl; CHECK_EQ(res, 0); // update the descriptor so it now points to the copied model file domain.filename = destination_file; } } template <typename CacheT, typename SurfaceBufT> void Scene<CacheT, SurfaceBufT>::deleteAllDomainsFromLocalDisk() { CHECK_EQ(storage_basepath_.empty(), false); int res; for (std::size_t i = 0; i < domains_.size(); ++i) { // create a new folder std::string new_dir = storage_basepath_ + "/proc" + std::to_string(mpi::rank()) + "_domain" + std::to_string(i); std::string cmd_rm_dir = "rm -rf " + new_dir; res = std::system(cmd_rm_dir.c_str()); } } template <typename CacheT, typename SurfaceBufT> void Scene<CacheT, SurfaceBufT>::mergeDomainBounds( std::size_t* max_num_vertices, std::size_t* max_num_faces) { Aabb world_space_bound; std::size_t num_domains = domains_.size(); domains_.resize(num_domains); #if defined(PRINT_DOMAIN_BOUNDS) && defined(SPRAY_GLOG_CHECK) std::size_t total_faces = 0; #endif // evaluate bound and number of primitives std::size_t num_vertices = 0, num_faces = 0; for (std::size_t id = 0; id < num_domains; ++id) { Domain& d = domains_[id]; // let's enforce that that domain world-space bound and // the number of faces are provided through preprocessing. CHECK_EQ(d.world_aabb.isValid(), true); CHECK_GT(d.num_vertices, 0); CHECK_GT(d.num_faces, 0); // maximum values if (d.num_vertices > num_vertices) num_vertices = d.num_vertices; if (d.num_faces > num_faces) num_faces = d.num_faces; #if defined(PRINT_DOMAIN_BOUNDS) && defined(SPRAY_GLOG_CHECK) if (mpi::isRootProcess()) { total_faces += d.num_faces; LOG(INFO) << "[domain " << id << "] [bounds " << d.world_aabb << "] [faces " << d.num_faces << "]"; } #endif world_space_bound.merge(d.world_aabb); #if defined(PRINT_DOMAIN_BOUNDS) && defined(SPRAY_GLOG_CHECK) LOG(INFO) << " [Scene::load()] [domain " << domains_[id].id << "] bound: " << domains_[id].world_aabb; #endif } *max_num_vertices = num_vertices; *max_num_faces = num_faces; bound_ = world_space_bound; CHECK(bound_.isValid()); #if defined(PRINT_DOMAIN_BOUNDS) && defined(SPRAY_GLOG_CHECK) LOG_IF(INFO, mpi::isRootProcess()) << "total faces: " << total_faces; LOG_IF(INFO, mpi::isRootProcess()) << "world bound: " << bound_; #endif } template <typename CacheT, typename SurfaceBufT> void Scene<CacheT, SurfaceBufT>::drawDomains() { glPushAttrib(GL_ENABLE_BIT | GL_LINE_BIT); glDisable(GL_LIGHTING); glLineWidth(.1); glEnable(GL_DEPTH_TEST); glPolygonOffset(1.0, 1.0); glDepthMask(GL_FALSE); glm::vec4 color(0.3f, 0.3f, 0.3f, 0.5f); glm::vec4 select(0.0f, 1.0f, 1.0f, .5f); for (std::size_t i = 0; i < domains_.size(); ++i) { const Domain& d = domains_[i]; if (i != glfw_domain_idx_) { d.world_aabb.draw(color); } } glLineWidth(2.0); for (std::size_t i = 0; i < domains_.size(); ++i) { const Domain& d = domains_[i]; if (i == glfw_domain_idx_) { d.world_aabb.draw(select); } } glDepthMask(GL_TRUE); glPopAttrib(); } template <typename CacheT, typename SurfaceBufT> void Scene<CacheT, SurfaceBufT>::drawPartitions() { glPushAttrib(GL_ENABLE_BIT | GL_LINE_BIT); glDisable(GL_LIGHTING); glLineWidth(.1); glEnable(GL_DEPTH_TEST); glPolygonOffset(1.0, 1.0); glDepthMask(GL_FALSE); glm::vec4 color(0.3f, 0.3f, 0.3f, 0.5f); glm::vec4 select(0.0f, 1.0f, 1.0f, .5f); std::vector<int> domain_to_partition; domain_to_partition = partition_.computePartition(num_partitions_); for (std::size_t i = 0; i < domains_.size(); ++i) { const Domain& d = domains_[i]; if (domain_to_partition[d.id] != partition_num_) { d.world_aabb.draw(color); } } glLineWidth(2.0); for (std::size_t i = 0; i < domains_.size(); ++i) { const Domain& d = domains_[i]; if (domain_to_partition[d.id] == partition_num_) { d.world_aabb.draw(select); } } glDepthMask(GL_TRUE); glPopAttrib(); } } // namespace spray
31.909524
80
0.606178
hyungman
09daa83999e0ab186cc26ed886845e78c830da83
343
cpp
C++
physics/BtShape.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
physics/BtShape.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
physics/BtShape.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#include "BtShape.hpp" #include "BtWorld.hpp" BEGIN_INANITY_PHYSICS BtShape::BtShape(ptr<BtWorld> world, btCollisionShape* collisionShape) : Shape(world), collisionShape(collisionShape) {} BtShape::~BtShape() { delete collisionShape; } btCollisionShape* BtShape::GetInternalObject() const { return collisionShape; } END_INANITY_PHYSICS
17.15
70
0.787172
quyse
09df9723e53e1a24433f5b53e07938041882814c
2,135
cc
C++
zoltan/apfZoltanMesh.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
138
2015-01-05T15:50:20.000Z
2022-02-25T01:09:58.000Z
zoltan/apfZoltanMesh.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
337
2015-08-07T18:24:58.000Z
2022-03-31T14:39:03.000Z
zoltan/apfZoltanMesh.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
70
2015-01-17T00:58:41.000Z
2022-02-13T04:58:20.000Z
/* * Copyright (C) 2014 Scientific Computation Research Center * * This work is open source software, licensed under the terms of the * BSD license as described in the LICENSE file in the top-level directory. */ #include "apfZoltanMesh.h" #include "apfZoltanCallbacks.h" #include "apfZoltan.h" #include <PCU.h> #include <pcu_util.h> namespace apf { ZoltanMesh::ZoltanMesh(Mesh* mesh_, bool isLocal_, int method_, int approach_, bool dbg) { mesh = mesh_; weights = 0; isLocal = isLocal_; method = method_; approach = approach_; debug = dbg; tolerance = 0; multiple = 0; local = 0; global = 0; opposite = 0; } ZoltanMesh::~ZoltanMesh() { if (local) destroyNumbering(local); if (global) destroyGlobalNumbering(global); if (opposite) { const int sideDim = mesh->getDimension() - 1; removeTagFromDimension(mesh, opposite, sideDim); mesh->destroyTag(opposite); } } static void getElements(ZoltanMesh* b) { Mesh* m = b->mesh; b->elements.setSize(m->count(m->getDimension())); MeshIterator* it = m->begin(m->getDimension()); MeshEntity* e; size_t i = 0; while ((e = m->iterate(it))) b->elements[i++] = e; PCU_ALWAYS_ASSERT(i == b->elements.getSize()); m->end(it); } static void setupNumberings(ZoltanMesh* b) { b->local = numberElements(b->mesh, "zoltan_element"); if (!b->isLocal) { Numbering* tmp = numberElements(b->mesh, "zoltan"); b->global = makeGlobal(tmp); } } static Migration* convertResult(ZoltanMesh* b, ZoltanData* ztn) { Migration* plan = new Migration(b->mesh); //fill out the plan from zoltan class ztn->get(int localId) for (int ind=0;ind<ztn->getNumExported();ind++) { int lid; int exportPart; ztn->getExport(ind,&lid,&exportPart); plan->send(b->elements[lid],exportPart); } return plan; } Migration* ZoltanMesh::run(MeshTag* w, double tol, int mult) { weights = w; tolerance = tol; multiple = mult; setupNumberings(this); getElements(this); if (!isLocal) opposite = tagOpposites(global, "zb_opposite"); ZoltanData ztn(this); ztn.run(); return convertResult(this, &ztn); } }
22.473684
78
0.668384
cwsmith
09ea2db98bbe498e910f00466b9e4dbe4a8397f7
4,230
cpp
C++
Src/VC/bcgcbpro/BCGPStaticGaugeImpl.cpp
iclosure/smartsoft
62eaed49efd8306642b928ef4f2d96e36aca6527
[ "MIT" ]
null
null
null
Src/VC/bcgcbpro/BCGPStaticGaugeImpl.cpp
iclosure/smartsoft
62eaed49efd8306642b928ef4f2d96e36aca6527
[ "MIT" ]
null
null
null
Src/VC/bcgcbpro/BCGPStaticGaugeImpl.cpp
iclosure/smartsoft
62eaed49efd8306642b928ef4f2d96e36aca6527
[ "MIT" ]
1
2020-05-11T05:36:49.000Z
2020-05-11T05:36:49.000Z
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of the BCGControlBar Library // Copyright (C) 1998-2012 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPStaticGaugeImpl.cpp: implementation of the CBCGPStaticGaugeImpl class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "bcgcbpro.h" #include "BCGPStaticGaugeImpl.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif UINT BCGM_ON_GAUGE_CLICK = ::RegisterWindowMessage (_T("BCGM_ON_GAUGE_CLICK")); IMPLEMENT_DYNAMIC(CBCGPStaticGaugeImpl, CBCGPGaugeImpl) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBCGPStaticGaugeImpl::CBCGPStaticGaugeImpl(CBCGPVisualContainer* pContainer) : CBCGPGaugeImpl(pContainer) { AddData(new CBCGPGaugeDataObject); m_nFlashTime = 0; m_bOff = FALSE; m_bIsPressed = FALSE; } //******************************************************************************* CBCGPStaticGaugeImpl::~CBCGPStaticGaugeImpl() { } //******************************************************************************* void CBCGPStaticGaugeImpl::StartFlashing(UINT nTime) { if (IsFlashing() || nTime == 0) { return; } m_arData[0]->SetAnimationID((UINT) ::SetTimer (NULL, 0, nTime, AnimTimerProc)); g_cs.Lock (); m_mapAnimations.SetAt (m_arData[0]->GetAnimationID(), this); g_cs.Unlock (); m_nFlashTime = nTime; } //******************************************************************************* void CBCGPStaticGaugeImpl::StopFlashing() { if (m_arData[0]->GetAnimationID() > 0) { ::KillTimer(NULL, m_arData[0]->GetAnimationID()); m_arData[0]->SetAnimationID(0); m_bOff = FALSE; Redraw(); } } //******************************************************************************* CWnd* CBCGPStaticGaugeImpl::SetOwner(CWnd* pWndOwner, BOOL bRedraw) { BOOL bIsFlashing = IsFlashing(); CWnd* pWndRes = CBCGPGaugeImpl::SetOwner(pWndOwner, bRedraw); if (bIsFlashing) { StartFlashing(m_nFlashTime); } return pWndRes; } //******************************************************************************* BOOL CBCGPStaticGaugeImpl::OnMouseDown(int nButton, const CBCGPPoint& pt) { if (!m_bIsInteractiveMode || nButton != 0) { return CBCGPGaugeImpl::OnMouseDown(nButton, pt); } m_bIsPressed = TRUE; return TRUE; } //******************************************************************************* void CBCGPStaticGaugeImpl::OnMouseUp(int nButton, const CBCGPPoint& pt) { if (!m_bIsInteractiveMode || nButton != 0) { CBCGPGaugeImpl::OnMouseUp(nButton, pt); return; } if (!m_bIsPressed) { return; } m_bIsPressed = FALSE; if (m_rect.PtInRect(pt)) { FireClickEvent(pt); } } //******************************************************************************* void CBCGPStaticGaugeImpl::OnMouseMove(const CBCGPPoint& pt) { if (!m_bIsPressed) { CBCGPGaugeImpl::OnMouseMove(pt); } } //******************************************************************************* void CBCGPStaticGaugeImpl::OnCancelMode() { if (!m_bIsPressed) { CBCGPGaugeImpl::OnCancelMode(); return; } m_bIsPressed = FALSE; } //******************************************************************************* void CBCGPStaticGaugeImpl::FireClickEvent(const CBCGPPoint& pt) { if (m_pWndOwner->GetSafeHwnd() == NULL) { return; } CWnd* pOwner = m_pWndOwner->GetOwner(); if (pOwner->GetSafeHwnd() == NULL) { return; } m_pWndOwner->GetOwner()->SendMessage(BCGM_ON_GAUGE_CLICK, (WPARAM)GetID(), MAKELPARAM(pt.x, pt.y)); } //******************************************************************************* BOOL CBCGPStaticGaugeImpl::OnSetMouseCursor(const CBCGPPoint& pt) { if (m_bIsInteractiveMode) { ::SetCursor (globalData.GetHandCursor()); return TRUE; } return CBCGPGaugeImpl::OnSetMouseCursor(pt); }
25.329341
100
0.520567
iclosure
09eb7ea30cbf59a6eb696c77f2d09f7d3c44c12a
2,297
cpp
C++
src/tbdmud_server.cpp
charleslucas/tbdmud
58023c9af23dd69e6de93bb5295dc9047a7b3998
[ "MIT" ]
null
null
null
src/tbdmud_server.cpp
charleslucas/tbdmud
58023c9af23dd69e6de93bb5295dc9047a7b3998
[ "MIT" ]
null
null
null
src/tbdmud_server.cpp
charleslucas/tbdmud
58023c9af23dd69e6de93bb5295dc9047a7b3998
[ "MIT" ]
null
null
null
#include <iostream> #include <boost/asio.hpp> #include <boost/bind/bind.hpp> #include <boost/algorithm/string.hpp> #include <optional> #include <queue> #include <unordered_set> #include <events.h> #include <entities.h> #include <session.h> #include <world.h> #include <tbdmud_server.h> // Call the tick function of the world approximately once a second (doesn't have to be exact) void async_tick(const boost::system::error_code& /*e*/, io::steady_timer* t, tbdmud::world* w) { w->tick(); // Move the expiration time of our timer up by one second and set it again t->expires_at(t->expiry() + io::chrono::seconds(1)); t->async_wait(boost::bind(async_tick, io::placeholders::error, t, w)); } // Handle events from the queue that precede or are equal to the current time void async_handle_queue(const boost::system::error_code& /*e*/, io::deadline_timer* t, tbdmud::world* w) { w->process_events(); // Move the expiration time of our timer up by one millisecond and set it again t->expires_from_now(boost::posix_time::milliseconds(1)); // Run as often as possible t->async_wait(boost::bind(async_handle_queue, io::placeholders::error, t, w)); } int main() { io::io_context io_context; io::steady_timer ticktimer(io_context, io::chrono::seconds(1)); io::deadline_timer queuetimer(io_context); tbdmud::world world; server srv(io_context, 15001, &world); // Tasks to be asynchronously run by the server srv.async_accept(); // Asynchronously accept incoming TCP traffic ticktimer.async_wait(boost::bind(async_tick, io::placeholders::error, &ticktimer, &world)); // Asynchronously but regularly trigger a tick update queuetimer.expires_from_now(boost::posix_time::milliseconds(100)); // Run as often as possible, it's fine if queue handling longer than this to run queuetimer.async_wait(boost::bind(async_handle_queue, io::placeholders::error, &queuetimer, &world)); io_context.run(); // Invoke the completion handlers //world.save_to_disk; // TODO: The world is a separate top-level object so it can ensure all the data is saved to disk before the program exits return 0; }
42.537037
178
0.679147
charleslucas
09ecb487e1831adec8bfb3925ca00f20b7d77c95
20,459
hpp
C++
2d/extra/MeshR2.hpp
danston/gbc
0cb1ae062919b053edc1558bdf41757460703eca
[ "MIT" ]
16
2016-12-06T10:35:46.000Z
2022-01-19T01:20:56.000Z
2d/extra/MeshR2.hpp
danston/sbc
e53deb997bc6c119bfacd6da6a234f64068efc1e
[ "MIT" ]
1
2020-02-11T10:45:30.000Z
2021-03-12T11:08:03.000Z
2d/extra/MeshR2.hpp
danston/sbc
e53deb997bc6c119bfacd6da6a234f64068efc1e
[ "MIT" ]
3
2018-05-10T14:34:35.000Z
2021-12-20T10:01:21.000Z
// Copyright Dmitry Anisimov danston@ymail.com (c) 2016-2017. // README: /* Implementation of the triangle/quad mesh in R2. This class depends on: 1. VertexExpressionsR2.hpp 2. VertexR2.hpp 3. TriangleCoordinatesR2.hpp 4. Face.hpp 5. Halfedge.hpp 6. MeanValueR2.hpp */ #ifndef GBC_MESHR2_HPP #define GBC_MESHR2_HPP // STL includes. #include <fstream> #include <cassert> #include <vector> #include <string> #include <map> // Local includes. #include "VertexR2.hpp" #include "TriangleCoordinatesR2.hpp" #include "Face.hpp" #include "Halfedge.hpp" #include "../coords/MeanValueR2.hpp" namespace gbc { // Mesh (triangle or quad-based) class in R2. class MeshR2 { public: // Constructor. MeshR2() : _fn(0), _rval(0), _v(), _he(), _f(), _tol(1.0e-10) { } // Load mesh from a file. void load(const std::string &path) { clear(); if (path.empty()) { std::cerr << "ERROR: The mesh file is not provided!\n" << std::endl; exit(EXIT_FAILURE); } std::ifstream readFile(path.c_str(), std::ios_base::in); if (!readFile) { std::cerr << "ERROR: Error reading an .obj file!\n" << std::endl; exit(EXIT_FAILURE); } std::string flag; double x, y, z; size_t i1, i2, i3, i4; VertexR2 tmpV; Face tmpF; // Read an .obj file. // Here we always ignore the third "z" coordinate. while (!readFile.eof()) { readFile >> flag; // Vertex flag. if (flag == "v") { readFile >> x >> y >> z; tmpV.x() = x; tmpV.y() = y; _v.push_back(tmpV); } // Face flag. if (flag == "f") { readFile >> i1 >> i2 >> i3; assert(i1 > 0 && i2 >0 && i3 > 0); tmpF.v[0] = i1 - 1; tmpF.v[1] = i2 - 1; tmpF.v[2] = i3 - 1; if (readFile.peek() == 32) { readFile >> i4; assert(i4 > 0); tmpF.v[3] = i4 - 1; } _f.push_back(tmpF); } } assert(_v.size() != 0); assert(_f.size() != 0); readFile.close(); setMeshFlags(_f); initializeHalfedges(_f); buildHEConnectivity(); } // Load barycentric coordinates from a file. void loadBarycentricCoordinates(const std::string &path) { std::ifstream readFile(path.c_str(), std::ios_base::in); if (!readFile) { std::cerr << "ERROR: Error loading file!\n" << std::endl; exit(EXIT_FAILURE); } size_t numV, numC; readFile >> numV; readFile >> numC; assert(_v.size() == numV); for (size_t i = 0; i < numV; ++i) { _v[i].b().resize(numC); for (size_t j = 0; j < numC; ++j) readFile >> _v[i].b()[j]; } readFile.close(); } // Initialize mesh. void initialize(const std::vector<VertexR2> &v, const std::vector<Face> &f) { clear(); // Set defaults. setMeshFlags(f); const size_t numV = v.size(); const size_t numF = f.size(); assert(numV != 0 && numF != 0); _v.resize(numV); _f.resize(numF); // Copy vertices. for (size_t i = 0; i < numV; ++i) { // Assertions. assert(v[i].val == 0); assert(v[i].out == -1); assert(v[i].alpha == -1.0); assert(v[i].type == INTERIOR); _v[i] = v[i]; } // Copy faces. for (size_t i = 0; i < numF; ++i) { // Assertions. assert(f[i].f[0] == -1); assert(f[i].f[1] == -1); assert(f[i].f[2] == -1); assert(f[i].f[3] == -1); _f[i] = f[i]; } // Initialize halfedges. initializeHalfedges(f); // Build the halfedge connectivity. buildHEConnectivity(); } // Initialize barycentric coordinates. void initializeBarycentricCoordinates(const std::vector< std::vector<double> > &bb) { const size_t numV = numVertices(); assert(bb.size() == numV); const size_t numC = bb[0].size(); for (size_t i = 0; i < numV; ++i) { _v[i].b().resize(numC); for (size_t j = 0; j < numC; ++j) _v[i].b()[j] = bb[i][j]; } } // Get a one ring neighbourhood around the vertex. void getRing(const size_t vInd, std::vector<int> &neighs) const { size_t nSize = 0; int prev, curr, next; // Find neighbours of the vertex. curr = next = _v[vInd].out; assert(_v[vInd].val > 0); neighs.resize((size_t) _v[vInd].val); do { neighs[nSize] = _he[curr].dest; prev = _he[curr].prev; curr = _he[prev].neigh; nSize++; } while ((curr >= 0) && (curr != next)); // Add one more neighbour for boundary vertices. if (curr < 0) { curr = _he[prev].prev; neighs[nSize] = _he[curr].dest; } } // Create faces in the mesh. void createFaces(const bool makeFaceNeighbours = true) { const size_t numHE = numHalfedges(); const size_t numF = numHE / _fn; _f.resize(numF); assert(numHE != 0 && numF != 0); const int first = _he[0].next; // Create faces. if (first == 1) { size_t indHE = 0; for (size_t i = 0; i < numF; ++i) for (size_t j = 0; j < _fn; ++j) _f[i].v[j] = _he[_he[indHE++].prev].dest; } else { size_t indHE = 0; for (size_t i = 0; i < numF; ++i) { int ind = _he[indHE].prev; for (size_t j = 0; j < _fn; ++j) { _f[i].v[j] = _he[ind].dest; ind = _he[ind].next; } indHE++; } } // Create face neighbours. // Slow code, turn it off if it is not necessary! if (makeFaceNeighbours) { size_t indHE = 0; for (size_t i = 0; i < numF; ++i) { for (size_t j = 0; j < _fn; ++j) { const int neigh = _he[indHE++].neigh; _f[i].f[j] = findFaceFromHE(neigh); } } } } // Find face that contains the query point. inline int findFace(const VertexR2 &query) const { std::vector<double> lambda; return findFace(query, lambda); } // Find face that contains the query point and return // the corresponding barycentric coordinates. int findFace(const VertexR2 &query, std::vector<double> &lambda) const { if (isTriangleMesh()) { const size_t numF = numFaces(); for (size_t i = 0; i < numF; ++i) { const int i0 = _f[i].v[0]; const int i1 = _f[i].v[1]; const int i2 = _f[i].v[2]; const VertexR2 &v0 = _v[i0]; const VertexR2 &v1 = _v[i1]; const VertexR2 &v2 = _v[i2]; TriangleCoordinatesR2 tc(v0, v1, v2); tc.compute(query, lambda); if (lambda[0] >= 0.0 && lambda[1] >= 0.0 && lambda[2] >= 0.0) return (int) i; } } else if (isQuadMesh()) { const size_t numF = numFaces(); for (size_t i = 0; i < numF; ++i) { const int i0 = _f[i].v[0]; const int i1 = _f[i].v[1]; const int i2 = _f[i].v[2]; const int i3 = _f[i].v[3]; std::vector<VertexR2> quad(4); quad[0] = _v[i0]; quad[1] = _v[i1]; quad[2] = _v[i2]; quad[3] = _v[i3]; MeanValueR2 mvc(quad); mvc.compute(query, lambda); if (lambda[0] >= 0.0 && lambda[1] >= 0.0 && lambda[2] >= 0.0 && lambda[3] >= 0.0) return (int) i; } } return -1; } // Get halfedges that are shared between the face with the index faceInd // and its neighbouring faces. // The function returns the number of obtained neighbours. size_t getFaceNeighbours(const size_t faceInd, std::vector<size_t> &neighs) const { if (isQuadMesh()) { // This functionality is not yet implemented! assert(false); return 0; } assert(numFaces() != 0); int heInd = (int) faceInd * 3; if (heInd >= 0 && _he[heInd].neigh != -1) neighs.push_back((size_t) heInd); heInd = _he[heInd].next; if (heInd >= 0 && _he[heInd].neigh != -1) neighs.push_back((size_t) heInd); heInd = _he[heInd].next; if (heInd >= 0 && _he[heInd].neigh != -1) neighs.push_back((size_t) heInd); return neighs.size(); } // Subdivision. // Initialize mesh with a polygon. // In principle, any set of vertices can be used. virtual void setFromPolygon(const std::vector<VertexR2>&) { // Override me for the corresponding subdivision scheme. } // Vertex adjustment near the polygon's corners. virtual void preprocess(const bool) { // Override me for the corresponding subdivision scheme. } // Subdivide mesh. inline void subdivide(const size_t timesToSubdivide, const bool midpoint = false) { for (size_t i = 0; i < timesToSubdivide; ++i) subdivideMesh(midpoint); } // Do one subdivision step. virtual void subdivideMesh(const bool) { // Override me for the corresponding subdivision scheme. } // Internal data. // Return vertices of the mesh. inline std::vector<VertexR2> &vertices() { return _v; } // Return const vertices of the mesh. inline const std::vector<VertexR2> &vertices() const { return _v; } // Return halfedges of the mesh. inline std::vector<Halfedge> &halfedges() { return _he; } // Return const halfedges of the mesh. inline const std::vector<Halfedge> &halfedges() const { return _he; } // Return faces of the mesh. inline std::vector<Face> &faces() { return _f; } // Return const faces of the mesh. inline const std::vector<Face> &faces() const { return _f; } // Return number of vertices in the mesh. inline size_t numVertices() const { return _v.size(); } // Return number of halfedges in the mesh. inline size_t numHalfedges() const { return _he.size(); } // Return number of faces in the mesh. inline size_t numFaces() const { return _f.size(); } // Return number of edges in the mesh. inline size_t numEdges() const { return numVertices() + (numHalfedges() / _fn) - 1; } // Clear mesh. inline void clear() { _fn = _rval = 0; _v.clear(); _he.clear(); _f.clear(); } // Check if mesh is empty. inline bool isEmpty() const { return _v.empty(); } // Tolerance. // Tolerance used internally in the class. inline double tolerance() const { return _tol; } // Set new user-defined tolerance. inline void setTolerance(const double newTol) { _tol = newTol; } // Type of the mesh. // Triangle-based mesh. inline bool isTriangleMesh() const { return _fn == 3; } // Quad-based mesh. inline bool isQuadMesh() const { return _fn == 4; } protected: // Number of face vertices. size_t _fn; // Regular vertex valency. size_t _rval; // Mesh. std::vector<VertexR2> _v; // stores vertices of the mesh std::vector<Halfedge> _he; // stores halfedges of the mesh std::vector<Face> _f; // stores faces of the mesh // Tolerance. double _tol; // Functions. // Set mesh flags. void setMeshFlags(const std::vector<Face> &f) { assert(f[0].v[0] != -1); assert(f[0].v[1] != -1); assert(f[0].v[2] != -1); _fn = 0; for (size_t i = 0; i < 4; ++i) if (f[0].v[i] != -1) ++_fn; assert(_fn == 3 || _fn == 4); if (_fn == 3) _rval = 6; else _rval = 4; } // Initialize halfedges. void initializeHalfedges(const std::vector<Face> &f) { // Copy vertex indices of each triangle in the mesh. assert(_fn > 2); const size_t numF = f.size(); const size_t numHE = _fn * numF; _he.resize(numHE); std::vector<int> vIndices; vIndices.resize(numHE); size_t ind = 0; for (size_t i = 0; i < numF; ++i) for (size_t j = 0; j < _fn; ++j) vIndices[ind++] = f[i].v[j]; size_t base, indV = 0, indE = 0; for (size_t i = 0; i < numF; i++) { base = indE; for (size_t j = 0; j < _fn; j++) { _he[indE].prev = int(base + (j + _fn - 1) % _fn); _he[indE].next = int(base + (j + 1) % _fn); _he[indE++].dest = vIndices[indV++]; } } } // Build the halfedge connectivity. void buildHEConnectivity() { const int numV = (int) numVertices(); const int numHE = (int) numHalfedges(); typedef std::map<int, int> halfedgeList; std::vector<halfedgeList> halfedgeTable((size_t) numV); halfedgeList *destList; int source, dest; // Build the halfedge connectivity. for (int i = 0; i < numHE; ++i) { // Source and destination of the current halfedge. source = _he[_he[i].prev].dest; dest = _he[i].dest; // Is halfedge from destination to source already in the edge table? destList = &(halfedgeTable[dest]); std::map<int, int>::iterator it = destList->find(source); if (it != destList->end()) { _he[i].neigh = it->second; _he[it->second].neigh = i; destList->erase(it); } else { // Put a halfedge in the edge table. halfedgeTable[source].insert(std::make_pair(dest, i)); } } // Determine valency and some outgoing halfedge for each vertex. // Mark and count the boundary vertices. VertexR2 *destV; for (int i = 0; i < numHE; ++i) { // Destination vertex of the current halfedge. destV = &(_v[_he[i].dest]); // Increase valency of destination vertex. destV->val++; // Take next of the current halfedge as the outgoing halfedge. destV->out = _he[i].next; if (_he[i].neigh < 0) { // NOTE: boundary vertices have one more neighbour than the outgoing edges. destV->type = FLAT; // FLAT vertices, that is collinear destV->val++; } } // Get the "rightmost" outgoing halfedge for boundary vertices. for (int i = 0; i < numV; ++i) { if (_v[i].type != INTERIOR) { while (_he[_v[i].out].neigh >= 0) { // Move the outgoing halfedge "one to the right". _v[i].out = _he[_he[_v[i].out].neigh].next; } } } // Update type of each boundary vertex in the mesh. VertexR2 *prevV; VertexR2 *nextV; for (int i = 0; i < numHE; ++i) { if (_he[i].neigh < 0) { destV = &(_v[_he[i].dest]); const int prev = destV->out; prevV = &(_v[_he[prev].dest]); const int next = _he[i].prev; nextV = &(_v[_he[next].dest]); defineBoundaryVertexType(prevV, destV, nextV); } } } // Set barycentric coordinates with respect to the Lagrange property. void setInitialBarycentricCoordinates() { const size_t numV = numVertices(); for (size_t i = 0; i < numV; ++i) { _v[i].b().resize(numV, 0.0); _v[i].b()[i] = 1.0; } } private: // Functions. // Define type of a vertex on the mesh boundary. void defineBoundaryVertexType(VertexR2 *prevV, VertexR2 *destV, VertexR2 *nextV) const { const double x1 = prevV->x(); const double y1 = prevV->y(); const double x2 = destV->x(); const double y2 = destV->y(); const double x3 = nextV->x(); const double y3 = nextV->y(); // Compute the following determinant: // // | x1 y1 1 | // det = | x2 y2 1 | // | x3 y3 1 | // // det = 0 if three points are collinear; // det > 0 if they create a concave corner; // det < 0 if they create a convex corner; const double det = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); // Compute the external signed angle for each corner. const double dotProd = (x1 - x2) * (x3 - x2) + (y1 - y2) * (y3 - y2); const double extAngle = atan2(det, dotProd); // positive in case of concave and negative in case of convex corner const double eps = tolerance(); if (det > eps) { // CONCAVE corner destV->type = CONCAVE; destV->alpha = extAngle; // external angle } else { // CONVEX corner destV->type = CONVEX; destV->alpha = 2.0 * M_PI + extAngle; // internal angle } } // Given a halfedge, find a face to which it belongs. int findFaceFromHE(const int indHE) const { const size_t numF = numFaces(); int tmpHE = 0; for (size_t i = 0; i < numF; ++i) for (size_t j = 0; j < (size_t) _fn; ++j) { if (indHE == tmpHE) return (int) i; tmpHE++; } return -1; } }; } // namespace gbc #endif // GBC_MESHR2_HPP
29.227143
125
0.446454
danston
09f020354d81d5d99721066d40c5df880ef27319
1,461
cpp
C++
apps/opencs/view/render/overlaymask.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/opencs/view/render/overlaymask.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/opencs/view/render/overlaymask.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#include "overlaymask.hpp" #include <OgreOverlayManager.h> #include <OgreOverlayContainer.h> #include "textoverlay.hpp" #include "../../model/world/cellcoordinates.hpp" namespace CSVRender { // ideas from http://www.ogre3d.org/forums/viewtopic.php?f=5&t=44828#p486334 OverlayMask::OverlayMask(std::map<CSMWorld::CellCoordinates, TextOverlay *> &overlays, Ogre::Viewport* viewport) : mTextOverlays(overlays), mViewport(viewport) { } OverlayMask::~OverlayMask() { } void OverlayMask::setViewport(Ogre::Viewport *viewport) { mViewport = viewport; } void OverlayMask::preViewportUpdate(const Ogre::RenderTargetViewportEvent &event) { if(event.source == mViewport) { Ogre::OverlayManager &overlayMgr = Ogre::OverlayManager::getSingleton(); for(Ogre::OverlayManager::OverlayMapIterator iter = overlayMgr.getOverlayIterator(); iter.hasMoreElements();) { Ogre::Overlay* item = iter.getNext(); for(Ogre::Overlay::Overlay2DElementsIterator it = item->get2DElementsIterator(); it.hasMoreElements();) { Ogre::OverlayContainer* container = it.getNext(); if(container) container->hide(); } } std::map<CSMWorld::CellCoordinates, TextOverlay *>::iterator it = mTextOverlays.begin(); for(; it != mTextOverlays.end(); ++it) { it->second->show(true); } } } }
27.566038
112
0.64271
Bodillium
09f52a0992418ee119a6bf9ba0798c516fd1ecf4
2,106
hpp
C++
WinApiFramework/Framework/Mouse.hpp
TonSharp/OpenWAPI
d61a8f006ea866c399e68f338c2661e9ef624369
[ "MS-PL" ]
3
2021-09-17T07:54:28.000Z
2021-09-18T08:28:33.000Z
WinApiFramework/Framework/Mouse.hpp
TonSharp/WAPITIS
d61a8f006ea866c399e68f338c2661e9ef624369
[ "MS-PL" ]
21
2021-09-19T18:13:55.000Z
2021-12-14T10:28:53.000Z
WinApiFramework/Framework/Mouse.hpp
TonSharp/OpenWAPI
d61a8f006ea866c399e68f338c2661e9ef624369
[ "MS-PL" ]
null
null
null
#pragma once #include "Elements/Args.hpp" class Mouse { private: static float x, y; static float dx, dy; static bool cursorLock; static Window* linkedWindow; public: static void LockCursor() { cursorLock = true; if (linkedWindow != nullptr) SetCapture(linkedWindow->Get()); } static void UnlockCursor() { cursorLock = false; ReleaseCapture(); } static void SetCursorLock(bool lock) { cursorLock = lock; if (cursorLock && linkedWindow != NULL) SetCapture(linkedWindow->Get()); } static void Link(Window* wnd) { linkedWindow = wnd; if (cursorLock) SetCapture(linkedWindow->Get()); } static void Update() { RECT rect; auto point = new POINT(); GetCursorPos(point); float centerX = point->x; float centerY = point->y; if (linkedWindow != nullptr) { GetWindowRect(linkedWindow->Get(), &rect); centerX = (rect.right - rect.left) / 2; centerY = (rect.bottom - rect.top) / 2; } dx = x - point->x; dy = point->y - y; x = point->x; y = point->y; if (cursorLock && linkedWindow != nullptr && GetFocus() == linkedWindow->Get()) SetCursorPos(centerX, centerY); x = centerX; y = centerY; } static float GetDX() { return dx; } static float GetDY() { return dy; } static void HideCursor() { ShowCursor(FALSE); } static void SetCursorVisiblity(bool visible) { ShowCursor(visible); } static bool IsLeftButtonDown(CallbackArgs args) { return args.Msg == WM_LBUTTONDOWN; } static bool IsLeftButtonUp(CallbackArgs args) { return args.Msg == WM_LBUTTONUP; } static bool IsLeftDoubleClick(CallbackArgs args) { return args.Msg == WM_LBUTTONDBLCLK; } static bool IsRightButtodDown(CallbackArgs args) { return args.Msg == WM_RBUTTONDOWN; } static bool IsRightButtonUp(CallbackArgs args) { return args.Msg == WM_RBUTTONUP; } static bool IsRightDoubleClick(CallbackArgs args) { return args.Msg == WM_RBUTTONDBLCLK; } }; bool Mouse::cursorLock = false; float Mouse::dx = 0; float Mouse::dy = 0; float Mouse::x = 0; float Mouse::y = 0; Window* Mouse::linkedWindow = nullptr;
16.453125
81
0.671415
TonSharp
09f7f7081953fcbbf81323b057c90420492039c3
284
cpp
C++
URI_1013.cpp
UmamaZakir/URI-Online-Judge.-begginer
b0a6d60b48b64790a0a502bbbcbc5c604b09826b
[ "MIT" ]
1
2021-07-11T17:00:52.000Z
2021-07-11T17:00:52.000Z
URI_1013.cpp
UmamaZakir/URI-Online-Judge.-begginer
b0a6d60b48b64790a0a502bbbcbc5c604b09826b
[ "MIT" ]
null
null
null
URI_1013.cpp
UmamaZakir/URI-Online-Judge.-begginer
b0a6d60b48b64790a0a502bbbcbc5c604b09826b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long a,b,c,mab,m; cin>>a>>b>>c; mab=(a+b+abs(a-b))/2; m=(mab+c+abs(mab-c))/2; cout<<m<<" eh o maior"<<"\n"; return 0; }
16.705882
38
0.507042
UmamaZakir
09f8dcb967908e96d6d9ebaa23391b332c95004b
4,260
cpp
C++
usb_492/USB_Device.cpp
dl8dtl/tek492
4303c6db2a4fe19c5a0129b831354ff6f04a1a6e
[ "Beerware" ]
1
2021-03-24T08:33:45.000Z
2021-03-24T08:33:45.000Z
usb_492/USB_Device.cpp
dl8dtl/tek492
4303c6db2a4fe19c5a0129b831354ff6f04a1a6e
[ "Beerware" ]
null
null
null
usb_492/USB_Device.cpp
dl8dtl/tek492
4303c6db2a4fe19c5a0129b831354ff6f04a1a6e
[ "Beerware" ]
1
2021-03-24T08:33:46.000Z
2021-03-24T08:33:46.000Z
/* * This is mostly taken from circuitben's original software which * is believed to be public domain. * * http://www.circuitben.net/node/4 */ /* * As this application uses Qt, any redistribution is bound to the * terms of either the GNU Lesser General Public License v. 3 ("LGPL"), * or to any commercial Qt license. */ /* * This application uses the Qwt extensions to Qt, which are also * provided under the terms of LGPL v2.1. However, the Qwt license * explicitly disclaims many common use cases as not constituting a * "derived work" (in the LGPL sense), so it is generally less * demanding about the redistribution policy than Qt itself. */ /* $Id$ */ #include "usb_492/USB_Device.hpp" bool USB_Device::inited = false; USB_Device *USB_Device::find_first(uint16_t vendor, uint16_t product) { init(); for (struct usb_bus *bus = usb_busses; bus; bus = bus->next) { for (struct usb_device *dev = bus->devices; dev; dev = dev->next) { if (dev->descriptor.idVendor == vendor && dev->descriptor.idProduct == product) { return new USB_Device(dev); } } } return 0; } void USB_Device::find_all(std::vector<USB_Device *> &devs, uint16_t vendor, uint16_t product) { init(); for (struct usb_bus *bus = usb_busses; bus; bus = bus->next) { for (struct usb_device *dev = bus->devices; dev; dev = dev->next) { if (dev->descriptor.idVendor == vendor && dev->descriptor.idProduct == product) { devs.push_back(new USB_Device(dev)); } } } } void USB_Device::init() { if (!inited) { usb_init(); usb_find_busses(); usb_find_devices(); inited = true; } } USB_Device::USB_Device(struct usb_device *dev) { _dev = dev; _handle = 0; } USB_Device::~USB_Device() { if (_handle) { usb_close(_handle); _handle = 0; } } bool USB_Device::open() { if (!_dev) { return false; } if (_handle) { return true; } _handle = usb_open(_dev); return _handle != 0; } bool USB_Device::set_configuration(int n) { return usb_set_configuration(_handle, n) == 0; } bool USB_Device::set_altinterface(int n) { return usb_set_altinterface(_handle, n) == 0; } bool USB_Device::claim_interface(int n) { return usb_claim_interface(_handle, n) == 0; } bool USB_Device::release_interface(int n) { return usb_release_interface(_handle, n) == 0; } bool USB_Device::set_default() { if (!_dev || !_dev->config || !_dev->config->interface || !_dev->config->interface->altsetting) { return false; } int config = _dev->config->bConfigurationValue; int interface = _dev->config->interface->altsetting->bInterfaceNumber; int alt = _dev->config->interface->altsetting->bAlternateSetting; return set_configuration(config) && claim_interface(interface) && set_altinterface(alt); } bool USB_Device::control(uint8_t type, uint8_t request, uint16_t value, uint16_t index, void *data, int size, int timeout, int *bytes_done) { int ret = usb_control_msg(_handle, type, request, value, index, (char *)data, size, timeout); if (bytes_done) { if (ret >= 0) { *bytes_done = ret; } else { *bytes_done = 0; } } return ret == size; } bool USB_Device::bulk_write(int endpoint, void *data, unsigned int size, int timeout, unsigned int *bytes_done) { int ret = usb_bulk_write(_handle, endpoint, (char *)data, size, timeout); if (bytes_done) { if (ret >= 0) { *bytes_done = ret; } else { *bytes_done = 0; } } return ret == (int)size; } bool USB_Device::bulk_read(int endpoint, void *data, unsigned int size, int timeout, unsigned int *bytes_done) { int ret = usb_bulk_read(_handle, endpoint, (char *)data, size, timeout); if (bytes_done) { if (ret >= 0) { *bytes_done = ret; } else { *bytes_done = 0; } } return ret == (int)size; }
22.539683
139
0.595305
dl8dtl
09f987f5d6bee75ded3745752a6f3152b9159537
3,449
cpp
C++
letstry/server.cpp
MarcusM94/Vehicles-in-IoT-Environments
5f885ff826a57b5c6ca4a67582e7ea11e4f15116
[ "MIT" ]
null
null
null
letstry/server.cpp
MarcusM94/Vehicles-in-IoT-Environments
5f885ff826a57b5c6ca4a67582e7ea11e4f15116
[ "MIT" ]
null
null
null
letstry/server.cpp
MarcusM94/Vehicles-in-IoT-Environments
5f885ff826a57b5c6ca4a67582e7ea11e4f15116
[ "MIT" ]
null
null
null
#include <qsocket.h> #include <qserversocket.h> #include <qapplication.h> #include <qvbox.h> #include <qtextview.h> #include <qlabel.h> #include <qpushbutton.h> #include <qtextstream.h> #include <stdlib.h> /* The ClientSocket class provides a socket that is connected with a client. For every client that connects to the server, the server creates a new instance of this class. */ class ClientSocket : public QSocket { Q_OBJECT public: ClientSocket( int sock, QObject *parent=0, const char *name=0 ) : QSocket( parent, name ) { line = 0; connect( this, SIGNAL(readyRead()), SLOT(readClient()) ); connect( this, SIGNAL(connectionClosed()), SLOT(deleteLater()) ); setSocket( sock ); } ~ClientSocket() { } signals: void logText( const QString& ); private slots: void readClient() { QTextStream ts( this ); while ( canReadLine() ) { QString str = ts.readLine(); emit logText( tr("Read: '%1'\n").arg(str) ); ts << line << ": " << str << endl; emit logText( tr("Wrote: '%1: %2'\n").arg(line).arg(str) ); line++; } } private: int line; }; /* The SimpleServer class handles new connections to the server. For every client that connects, it creates a new ClientSocket -- that instance is now responsible for the communication with that client. */ class SimpleServer : public QServerSocket { Q_OBJECT public: SimpleServer( QObject* parent=0 ) : QServerSocket( 4242, 1, parent ) { if ( !ok() ) { qWarning("Failed to bind to port 4242"); exit(1); } } ~SimpleServer() { } void newConnection( int socket ) { ClientSocket *s = new ClientSocket( socket, this ); emit newConnect( s ); } signals: void newConnect( ClientSocket* ); }; /* The ServerInfo class provides a small GUI for the server. It also creates the SimpleServer and as a result the server. */ class ServerInfo : public QVBox { Q_OBJECT public: ServerInfo() { SimpleServer *server = new SimpleServer( this ); QString itext = tr( "This is a small server example.\n" "Connect with the client now." ); QLabel *lb = new QLabel( itext, this ); lb->setAlignment( AlignHCenter ); infoText = new QTextView( this ); QPushButton *quit = new QPushButton( tr("Quit") , this ); connect( server, SIGNAL(newConnect(ClientSocket*)), SLOT(newConnect(ClientSocket*)) ); connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) ); } ~ServerInfo() { } private slots: void newConnect( ClientSocket *s ) { infoText->append( tr("New connection\n") ); connect( s, SIGNAL(logText(const QString&)), infoText, SLOT(append(const QString&)) ); connect( s, SIGNAL(connectionClosed()), SLOT(connectionClosed()) ); } void connectionClosed() { infoText->append( tr("Client closed connection\n") ); } private: QTextView *infoText; }; int main( int argc, char** argv ) { QApplication app( argc, argv ); ServerInfo info; app.setMainWidget( &info ); info.show(); return app.exec(); } #include "server.moc"
22.396104
79
0.578718
MarcusM94
09fbd4a43d5bf687eb79687d7d84cc59a3f6f59e
1,272
cpp
C++
LeetCode/ThousandOne/0398-random_pick_idx.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0398-random_pick_idx.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0398-random_pick_idx.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 398. 随机数索引 给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。 注意: 数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。 示例: int[] nums = new int[] {1,2,3,3,3}; Solution solution = new Solution(nums); // pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。 solution.pick(3); // pick(1) 应该返回 0。因为只有nums[0]等于1。 solution.pick(1); */ // 讨论里面说应该用蓄水池抽样 class Solution { vector<int> idx; vector<int>& nums; std::mt19937 mt; public: Solution(vector<int>& _nums) : nums(_nums) { std::random_device rd; mt.seed(rd()); idx.resize(nums.size()); std::iota(idx.begin(), idx.end(), 0); std::sort(idx.begin(), idx.end(), [this](int x, int y) -> bool { return nums[x] < nums[y]; }); std::sort(nums.begin(), nums.end()); } int pick(int target) { // 题目说了保证 target 在里面 ptrdiff_t x = std::lower_bound(nums.begin(), nums.end(), target) - nums.begin(); ptrdiff_t y = std::upper_bound(nums.begin(), nums.end(), target) - nums.begin(); x += static_cast<ptrdiff_t>(mt() % (y - x)); return idx[x]; } }; int main() { vector<int> nums = { 1, 2, 3, 3, 3 }; Solution sln(nums); OutExpr(sln.pick(1), "%d"); OutExpr(sln.pick(3), "%d"); OutExpr(sln.pick(3), "%d"); OutExpr(sln.pick(3), "%d"); OutExpr(sln.pick(3), "%d"); OutExpr(sln.pick(3), "%d"); }
19.569231
82
0.618711
Ginkgo-Biloba
6702b32cf7c4725d68afc34f7283d8d9aaee55ec
1,120
cpp
C++
cpp/021-030/Substring with Concatenation of All Words.cpp
KaiyuWei/leetcode
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
[ "MIT" ]
150
2015-04-04T06:53:49.000Z
2022-03-21T13:32:08.000Z
cpp/021-030/Substring with Concatenation of All Words.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
1
2015-04-13T15:15:40.000Z
2015-04-21T20:23:16.000Z
cpp/021-030/Substring with Concatenation of All Words.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
64
2015-06-30T08:00:07.000Z
2022-01-01T16:44:14.000Z
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> res; unordered_map<string, int> dict; int len = words[0].size(); int n = s.length(), m = words.size(); for (const string& word : words) { dict[word]++; } for (int i = 0; i < len; i++) { int cnt = 0; unordered_map<string, int> copy = dict; for (int j = i; j <= n - len; j += len) { string cur = s.substr(j, len); copy[cur]--; if (copy[cur] >= 0) { cnt++; } int pop_start = j - m * len; if (pop_start >= 0) { string pop_word = s.substr(pop_start, len); copy[pop_word]++; if (copy[pop_word] > 0) { cnt--; } } if (cnt == m) { res.push_back(pop_start + len); } } } return res; } };
30.27027
64
0.365179
KaiyuWei
6703f667d66470d39ed449a681aa7e3a6c55d286
2,735
cpp
C++
source/material/material.cpp
suVrik/path_tracer
9c1a75914e67e75ed4169468c4db87b4498c27f0
[ "MIT" ]
null
null
null
source/material/material.cpp
suVrik/path_tracer
9c1a75914e67e75ed4169468c4db87b4498c27f0
[ "MIT" ]
null
null
null
source/material/material.cpp
suVrik/path_tracer
9c1a75914e67e75ed4169468c4db87b4498c27f0
[ "MIT" ]
null
null
null
#include "material.h" #include <algorithm> #include <cassert> double fresnel_dielectric(double incident_cos_theta, double incident_ior, double transmitted_ior) { assert(incident_cos_theta >= -1.0 && incident_cos_theta != 0.0 && incident_cos_theta <= 1.0); assert(incident_ior >= 1.0); assert(transmitted_ior >= 1.0); if (incident_cos_theta < 0.0) { std::swap(incident_ior, transmitted_ior); incident_cos_theta = -incident_cos_theta; } double incident_sin_theta = std::sqrt(1.0 - sqr(incident_cos_theta)); double transmitted_sin_theta = incident_ior / transmitted_ior * incident_sin_theta; if (transmitted_sin_theta >= 1.0) { return 1.0; } double transmitted_cos_theta = std::sqrt(1.0 - sqr(transmitted_sin_theta)); double reflectance_parallel = ((transmitted_ior * incident_cos_theta) - (incident_ior * transmitted_cos_theta)) / ((transmitted_ior * incident_cos_theta) + (incident_ior * transmitted_cos_theta)); double reflectance_perpendicular = ((incident_ior * incident_cos_theta) - (transmitted_ior * transmitted_cos_theta)) / ((incident_ior * incident_cos_theta) + (transmitted_ior * transmitted_cos_theta)); return (sqr(reflectance_parallel) + sqr(reflectance_perpendicular)) / 2.0; } float3 faceforward(const float3& n, const float3& v) { return (dot(n, v) < 0.0) ? -n : n; } bool refract(const float3& incident, const float3& normal, double ior, float3& transmitted) { double incident_cos_theta = dot(normal, incident); double incident_sin2_theta = std::max(0.0, 1.0 - sqr(incident_cos_theta)); double transmitted_sin2_theta = incident_sin2_theta * sqr(ior); if (transmitted_sin2_theta >= 1.0) { transmitted = float3(-incident.x, -incident.y, incident.z); return false; } double transmitted_cos_theta = std::sqrt(std::max(0.0, 1.0 - transmitted_sin2_theta)); transmitted = -incident * ior + normal * (incident_cos_theta * ior - transmitted_cos_theta); return true; } float3 Material::bsdf(float3& ingoing, const float3& outgoing, double& pdf, const float2& random) const { assert(equal(length(outgoing), 1.0)); assert(random[0] >= 0.0 && random[0] < 1.0); assert(random[1] >= 0.0 && random[1] < 1.0); ingoing = float3(-outgoing.x, -outgoing.y, outgoing.z); pdf = 0.0; return float3(); } float3 Material::bsdf(const float3& ingoing, const float3& outgoing, double& pdf) const { assert(equal(length(ingoing), 1.0)); assert(equal(length(outgoing), 1.0)); pdf = 0.0; return float3(); } float3 Material::emissive() const { return float3(); } bool Material::is_specular() const { return false; }
33.353659
105
0.683364
suVrik
67072c23a0bcecfef584808eed187fac7af289cc
4,328
cpp
C++
pi/android/jni/Nanaka.cpp
mathall/nanaka
0304f444702318a83d221645d4e5f3622082c456
[ "BSD-2-Clause" ]
2
2017-03-31T19:01:22.000Z
2017-05-18T08:14:37.000Z
pi/android/jni/Nanaka.cpp
mathall/nanaka
0304f444702318a83d221645d4e5f3622082c456
[ "BSD-2-Clause" ]
null
null
null
pi/android/jni/Nanaka.cpp
mathall/nanaka
0304f444702318a83d221645d4e5f3622082c456
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2013, Mathias Hällman. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "Nanaka.h" #include <cassert> #include <memory> #include <android/native_window_jni.h> #include "nanaka/main/Nanaka.h" #include "nanaka/renderer/Renderer.h" #include "nanaka/input/InputEvent.h" #include "Application.h" #include "FileManagerImpl.h" #include "JNIHelper.h" #include "NanakaNativeWindowImpl.h" std::unique_ptr<Nanaka> g_nanaka; std::unique_ptr<AndroidApplication> g_application; std::unique_ptr<NanakaNativeWindowImpl> g_window; JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *pvt) { JNIEnv *env; if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_4) != JNI_OK) { return -1; } initJNIHelper(vm); return JNI_VERSION_1_4; } JNIEXPORT void JNICALL Java_com_madhobo_nanaka_Nanaka_Initialize( JNIEnv* env, jobject obj, jstring apkFilePath, jobject application) { const char* apkFilePathCStr; jboolean isCopy; apkFilePathCStr = env->GetStringUTFChars(apkFilePath, &isCopy); g_APK = zip_open(apkFilePathCStr, 0, NULL); g_application = std::unique_ptr<AndroidApplication>( new AndroidApplication(env->NewGlobalRef(application))); g_nanaka = std::unique_ptr<Nanaka>(new Nanaka(*g_application)); } JNIEXPORT void JNICALL Java_com_madhobo_nanaka_Nanaka_Start( JNIEnv* env, jobject obj) { g_nanaka->StartThread(); } JNIEXPORT void JNICALL Java_com_madhobo_nanaka_Nanaka_OnPause( JNIEnv* env, jobject obj) { g_nanaka->OnPause(); } JNIEXPORT void JNICALL Java_com_madhobo_nanaka_Nanaka_OnResume( JNIEnv* env, jobject obj) { g_nanaka->OnResume(); } JNIEXPORT void JNICALL Java_com_madhobo_nanaka_Nanaka_OnShutdown( JNIEnv* env, jobject obj) { g_nanaka->KillThread(); g_nanaka = nullptr; g_application = nullptr; } JNIEXPORT void JNICALL Java_com_madhobo_nanaka_Nanaka_OnSurfaceCreated( JNIEnv* env, jobject obj, jobject surface) { assert(surface); assert(!g_window); g_window = std::unique_ptr<NanakaNativeWindowImpl>( new NanakaNativeWindowImpl(*ANativeWindow_fromSurface(env, surface))); g_renderer->OnWindowCreated(g_window.get()); } JNIEXPORT void JNICALL Java_com_madhobo_nanaka_Nanaka_OnSurfaceDestroyed( JNIEnv* env, jobject obj) { assert(g_window); g_renderer->OnWindowDestroyed(); ANativeWindow_release(&g_window->m_window); g_window = nullptr; } JNIEXPORT void JNICALL Java_com_madhobo_nanaka_Nanaka_OnSurfaceChanged( JNIEnv* env, jobject obj, int w, int h, float dpi) { assert(g_window); DisplayProperties displayProps; displayProps.m_realSize = Vec2f(w, h); displayProps.m_size = Vec2f(w, h); displayProps.m_dpi = dpi; g_nanaka->SetDisplayProperties(displayProps); g_renderer->OnWindowChanged(); } JNIEXPORT void JNICALL Java_com_madhobo_nanaka_Nanaka_AddInputEvent( JNIEnv* env, jobject obj, float x, float y, int action, int pointerId) { InputEvent event; event.m_type = MotionInputEventType; event.m_action = static_cast<InputEventAction>(action); event.m_position = Vec2f(x, y); event.m_pointerId = pointerId; g_nanaka->AddInputEvent(event); }
30.695035
79
0.778651
mathall
670d29e702689c1cb56d67a1c307eedc1fef3fac
633
cpp
C++
Engine/Managers/AIManager.cpp
gaspardpetit/INF740-GameEngine
075b6563204fb3d1cf7531599f30dd296c2c9239
[ "Apache-2.0" ]
null
null
null
Engine/Managers/AIManager.cpp
gaspardpetit/INF740-GameEngine
075b6563204fb3d1cf7531599f30dd296c2c9239
[ "Apache-2.0" ]
null
null
null
Engine/Managers/AIManager.cpp
gaspardpetit/INF740-GameEngine
075b6563204fb3d1cf7531599f30dd296c2c9239
[ "Apache-2.0" ]
1
2015-09-25T22:24:16.000Z
2015-09-25T22:24:16.000Z
#include "Precompiled.h" #include "Core/Components/IIAInterface.h" #include "AIManager.h" #include <algorithm> #include <assert.h> namespace engine { void AIManager::createComponent( IAIInterface *iAIInstance ) { _aiInstances.emplace_back(iAIInstance); } void AIManager::removeComponent( IAIInterface *iAIInstance ) { auto wFound = std::find(_aiInstances.begin(), _aiInstances.end(), iAIInstance); ASSERT(wFound != _aiInstances.end()); _aiInstances.erase(wFound); } void AIManager::update() { for (auto iter = _aiInstances.begin(); iter != _aiInstances.end(); ++iter) { (*iter)->updateAI(); } } } // namespace engine
19.78125
80
0.725118
gaspardpetit
670e3dd684597fd50a4e4df332f58f3f8d241dbb
15,911
cpp
C++
test/kernel/manager_test.cpp
correaa/metall
f58728a5e963a6e77b68c1853d3d1ba1fe6a58b4
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
test/kernel/manager_test.cpp
correaa/metall
f58728a5e963a6e77b68c1853d3d1ba1fe6a58b4
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
test/kernel/manager_test.cpp
correaa/metall
f58728a5e963a6e77b68c1853d3d1ba1fe6a58b4
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
// Copyright 2019 Lawrence Livermore National Security, LLC and other Metall Project Developers. // See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (Apache-2.0 OR MIT) #include "gtest/gtest.h" #include <unordered_set> #include <boost/container/scoped_allocator.hpp> #include <boost/interprocess/containers/vector.hpp> #include <boost/unordered_map.hpp> #include <metall/metall.hpp> #include <metall/kernel/object_size_manager.hpp> #include "../test_utility.hpp" namespace { using namespace metall::detail; using chunk_no_type = uint32_t; static constexpr std::size_t k_chunk_size = 1 << 21; using manager_type = metall::basic_manager<chunk_no_type, k_chunk_size>; template <typename T> using allocator_type = typename manager_type::allocator_type<T>; using object_size_mngr = metall::kernel::object_size_manager<k_chunk_size, 1ULL << 48>; constexpr std::size_t k_min_object_size = object_size_mngr::at(0); const std::string &dir_path() { const static std::string path(test_utility::make_test_dir_path("ManagerTest")); return path; } TEST(ManagerTest, CreateAndOpenModes) { { manager_type::remove(dir_path().c_str()); { manager_type manager(metall::create_only, dir_path().c_str()); [[maybe_unused]] int *a = manager.construct<int>("int")(10); } { manager_type manager(metall::create_only, dir_path().c_str()); auto ret = manager.find<int>("int"); ASSERT_EQ(ret.first, nullptr); } } { manager_type::remove(dir_path().c_str()); { manager_type manager(metall::create_only, dir_path().c_str()); [[maybe_unused]] int *a = manager.construct<int>("int")(10); } { manager_type manager(metall::open_only, dir_path().c_str()); auto ret = manager.find<int>("int"); ASSERT_NE(ret.first, nullptr); ASSERT_EQ(*(static_cast<int *>(ret.first)), 10); } } { manager_type::remove(dir_path().c_str()); { manager_type manager(metall::open_or_create, dir_path().c_str()); [[maybe_unused]] int *a = manager.construct<int>("int")(10); } { manager_type manager(metall::open_or_create, dir_path().c_str()); auto ret = manager.find<int>("int"); ASSERT_NE(ret.first, nullptr); ASSERT_EQ(*(static_cast<int *>(ret.first)), 10); } } { manager_type::remove(dir_path().c_str()); { manager_type manager(metall::create_only, dir_path().c_str()); [[maybe_unused]] int *a = manager.construct<int>("int")(10); } { manager_type manager(metall::open_read_only, dir_path().c_str()); auto ret = manager.find<int>("int"); ASSERT_NE(ret.first, nullptr); ASSERT_EQ(*(static_cast<int *>(ret.first)), 10); } { manager_type manager(metall::open_only, dir_path().c_str()); auto ret = manager.find<int>("int"); ASSERT_NE(ret.first, nullptr); ASSERT_EQ(*(static_cast<int *>(ret.first)), 10); } } } TEST(ManagerTest, Consistency) { manager_type::remove(dir_path().c_str()); { manager_type manager(metall::create_only, dir_path().c_str()); // Must be inconsistent before closing ASSERT_FALSE(manager_type::consistent(dir_path().c_str())); [[maybe_unused]] int *a = manager.construct<int>("dummy")(10); } ASSERT_TRUE(manager_type::consistent(dir_path().c_str())); { // To make sure the consistent mark is cleared even after creating a new data store using an old dir path manager_type manager(metall::create_only, dir_path().c_str()); ASSERT_FALSE(manager_type::consistent(dir_path().c_str())); [[maybe_unused]] int *a = manager.construct<int>("dummy")(10); } ASSERT_TRUE(manager_type::consistent(dir_path().c_str())); { manager_type manager(metall::open_only, dir_path().c_str()); ASSERT_FALSE(manager_type::consistent(dir_path().c_str())); } ASSERT_TRUE(manager_type::consistent(dir_path().c_str())); { manager_type manager(metall::open_read_only, dir_path().c_str()); // Still consistent if it is opened with the read-only mode ASSERT_TRUE(manager_type::consistent(dir_path().c_str())); } ASSERT_TRUE(manager_type::consistent(dir_path().c_str())); } TEST(ManagerTest, TinyAllocation) { manager_type manager(metall::create_only, dir_path().c_str()); const std::size_t alloc_size = k_min_object_size / 2; // To make sure that there is no duplicated allocation std::unordered_set<void *> set; for (uint64_t i = 0; i < k_chunk_size / k_min_object_size; ++i) { auto addr = static_cast<char *>(manager.allocate(alloc_size)); ASSERT_EQ(set.count(addr), 0); set.insert(addr); } for (auto add : set) { manager.deallocate(add); } } TEST(ManagerTest, SmallAllocation) { manager_type manager(metall::create_only, dir_path().c_str()); const std::size_t alloc_size = k_min_object_size; // To make sure that there is no duplicated allocation std::unordered_set<void *> set; for (uint64_t i = 0; i < k_chunk_size / k_min_object_size; ++i) { auto addr = static_cast<char *>(manager.allocate(alloc_size)); ASSERT_EQ(set.count(addr), 0); set.insert(addr); } for (auto add : set) { manager.deallocate(add); } } TEST(ManagerTest, MaxSmallAllocation) { manager_type manager(metall::create_only, dir_path().c_str()); // Max small allocation size const std::size_t alloc_size = object_size_mngr::at(object_size_mngr::num_small_sizes() - 1); // This test will fail if the ojbect cache is enabled to cache alloc_size char *base_addr = nullptr; for (uint64_t i = 0; i < k_chunk_size / alloc_size; ++i) { auto addr = static_cast<char *>(manager.allocate(alloc_size)); if (i == 0) { base_addr = addr; } ASSERT_EQ((addr - base_addr) % k_chunk_size, i * alloc_size); } for (uint64_t i = 0; i < k_chunk_size / alloc_size; ++i) { char *addr = base_addr + i * alloc_size; manager.deallocate(addr); } for (uint64_t i = 0; i < k_chunk_size / alloc_size; ++i) { auto addr = static_cast<char *>(manager.allocate(alloc_size)); ASSERT_EQ((addr - base_addr) % k_chunk_size, i * alloc_size); } } TEST(ManagerTest, MixedSmallAllocation) { manager_type manager(metall::create_only, dir_path().c_str()); const std::size_t alloc_size1 = k_min_object_size * 2; const std::size_t alloc_size2 = k_min_object_size * 4; const std::size_t alloc_size3 = object_size_mngr::at(object_size_mngr::num_small_sizes() - 1); // Max small object num_blocks // To make sure that there is no duplicated allocation std::unordered_set<void *> set; for (uint64_t i = 0; i < k_chunk_size / alloc_size1; ++i) { { auto addr = static_cast<char *>(manager.allocate(alloc_size1)); ASSERT_EQ(set.count(addr), 0); set.insert(addr); } { auto addr = static_cast<char *>(manager.allocate(alloc_size2)); ASSERT_EQ(set.count(addr), 0); set.insert(addr); } { auto addr = static_cast<char *>(manager.allocate(alloc_size3)); ASSERT_EQ(set.count(addr), 0); set.insert(addr); } } for (auto add : set) { manager.deallocate(add); } } TEST(ManagerTest, LargeAllocation) { manager_type manager(metall::create_only, dir_path().c_str()); // Assume the object cache is not used for large allocation char *base_addr = nullptr; { auto addr1 = static_cast<char *>(manager.allocate(k_chunk_size)); base_addr = addr1; auto addr2 = static_cast<char *>(manager.allocate(k_chunk_size * 2)); ASSERT_EQ((addr2 - base_addr), 1 * k_chunk_size); auto addr3 = static_cast<char *>(manager.allocate(k_chunk_size)); ASSERT_EQ((addr3 - base_addr), 3 * k_chunk_size); manager.deallocate(base_addr); manager.deallocate(base_addr + k_chunk_size); manager.deallocate(base_addr + k_chunk_size * 3); } { auto addr1 = static_cast<char *>(manager.allocate(k_chunk_size)); ASSERT_EQ((addr1 - base_addr), 0); auto addr2 = static_cast<char *>(manager.allocate(k_chunk_size * 2)); ASSERT_EQ((addr2 - base_addr), 1 * k_chunk_size); auto addr3 = static_cast<char *>(manager.allocate(k_chunk_size)); ASSERT_EQ((addr3 - base_addr), 3 * k_chunk_size); } } TEST(ManagerTest, StlAllocator) { manager_type manager(metall::create_only, dir_path().c_str()); allocator_type<uint64_t> stl_allocator_instance(manager.get_allocator<uint64_t>()); // To make sure that there is no duplicated allocation std::unordered_set<uint64_t *> set; for (uint64_t i = 0; i < k_chunk_size / k_min_object_size; ++i) { auto addr = stl_allocator_instance.allocate(1).get(); ASSERT_EQ(set.count(addr), 0); set.insert(addr); } for (auto add : set) { stl_allocator_instance.deallocate(add, 1); } } TEST(ManagerTest, Container) { manager_type manager(metall::create_only, dir_path().c_str()); using element_type = std::pair<uint64_t, uint64_t>; boost::interprocess::vector<element_type, allocator_type<element_type>> vector(manager.get_allocator<>()); for (uint64_t i = 0; i < k_chunk_size / sizeof(element_type); ++i) { vector.emplace_back(element_type(i, i * 2)); } for (uint64_t i = 0; i < k_chunk_size / sizeof(element_type); ++i) { ASSERT_EQ(vector[i], element_type(i, i * 2)); } } TEST(ManagerTest, NestedContainer) { using element_type = uint64_t; using vector_type = boost::interprocess::vector<element_type, typename manager_type::allocator_type<element_type>>; using map_type = boost::unordered_map<element_type, // Key vector_type, // Value std::hash<element_type>, // Hash function std::equal_to<element_type>, // Equal function boost::container::scoped_allocator_adaptor<allocator_type<std::pair<const element_type, vector_type>>>>; manager_type manager(metall::create_only, dir_path().c_str()); map_type map(manager.get_allocator<>()); for (uint64_t i = 0; i < k_chunk_size / sizeof(element_type); ++i) { map[i % 8].push_back(i); } for (uint64_t i = 0; i < k_chunk_size / sizeof(element_type); ++i) { ASSERT_EQ(map[i % 8][i / 8], i); } } TEST(ManagerTest, PersistentConstructFind) { using element_type = uint64_t; using vector_type = boost::interprocess::vector<element_type, typename manager_type::allocator_type<element_type>>; { manager_type manager(metall::create_only, dir_path().c_str()); int *a = manager.construct<int>("int")(10); ASSERT_EQ(*a, 10); vector_type *vec = manager.construct<vector_type>("vector_type")(manager.get_allocator<vector_type>()); vec->emplace_back(10); vec->emplace_back(20); } { manager_type manager(metall::open_only, dir_path().c_str()); const auto ret1 = manager.find<int>("int"); ASSERT_NE(ret1.first, nullptr); ASSERT_EQ(ret1.second, 1); int *a = ret1.first; ASSERT_EQ(*a, 10); const auto ret2 = manager.find<vector_type>("vector_type"); ASSERT_NE(ret2.first, nullptr); ASSERT_EQ(ret2.second, 1); vector_type *vec = ret2.first; ASSERT_EQ(vec->at(0), 10); ASSERT_EQ(vec->at(1), 20); } { manager_type manager(metall::open_only, dir_path().c_str()); ASSERT_TRUE(manager.destroy<int>("int")); ASSERT_FALSE(manager.destroy<int>("int")); ASSERT_TRUE(manager.destroy<vector_type>("vector_type")); ASSERT_FALSE(manager.destroy<vector_type>("vector_type")); } } TEST(ManagerTest, PersistentConstructOrFind) { using element_type = uint64_t; using vector_type = boost::interprocess::vector<element_type, typename manager_type::allocator_type<element_type>>; { manager_type manager(metall::create_only, dir_path().c_str()); int *a = manager.find_or_construct<int>("int")(10); ASSERT_EQ(*a, 10); vector_type *vec = manager.find_or_construct<vector_type>("vector_type")(manager.get_allocator<vector_type>()); vec->emplace_back(10); vec->emplace_back(20); } { manager_type manager(metall::open_only, dir_path().c_str()); int *a = manager.find_or_construct<int>("int")(20); ASSERT_EQ(*a, 10); vector_type *vec = manager.find_or_construct<vector_type>("vector_type")(manager.get_allocator<vector_type>()); ASSERT_EQ(vec->at(0), 10); ASSERT_EQ(vec->at(1), 20); } { manager_type manager(metall::open_only, dir_path().c_str()); ASSERT_TRUE(manager.destroy<int>("int")); ASSERT_FALSE(manager.destroy<int>("int")); ASSERT_TRUE(manager.destroy<vector_type>("vector_type")); ASSERT_FALSE(manager.destroy<vector_type>("vector_type")); } } TEST(ManagerTest, PersistentNestedContainer) { using element_type = uint64_t; using vector_type = boost::interprocess::vector<element_type, typename manager_type::allocator_type<element_type>>; using map_type = boost::unordered_map<element_type, // Key vector_type, // Value std::hash<element_type>, // Hash function std::equal_to<element_type>, // Equal function boost::container::scoped_allocator_adaptor<allocator_type<std::pair<const element_type, vector_type>>>>; { manager_type manager(metall::create_only, dir_path().c_str()); map_type *map = manager.construct<map_type>("map")(manager.get_allocator<>()); (*map)[0].emplace_back(1); (*map)[0].emplace_back(2); } { manager_type manager(metall::open_only, dir_path().c_str()); map_type *map; std::size_t n; std::tie(map, n) = manager.find<map_type>("map"); ASSERT_EQ((*map)[0][0], 1); ASSERT_EQ((*map)[0][1], 2); (*map)[1].emplace_back(3); } { manager_type manager(metall::open_only, dir_path().c_str()); map_type *map; std::size_t n; std::tie(map, n) = manager.find<map_type>("map"); ASSERT_EQ((*map)[0][0], 1); ASSERT_EQ((*map)[0][1], 2); ASSERT_EQ((*map)[1][0], 3); } } TEST(ManagerTest, Flush) { using element_type = uint64_t; using vector_type = boost::interprocess::vector<element_type, typename manager_type::allocator_type<element_type>>; manager_type manager(metall::create_only, dir_path().c_str()); int *a = manager.construct<int>("int")(10); manager.flush(); ASSERT_FALSE(manager_type::consistent(dir_path().c_str())); } TEST(ManagerTest, AnonymousConstruct) { manager_type *manager; manager = new manager_type(metall::create_only, dir_path().c_str()); int *const a = manager->construct<int>(metall::anonymous_instance)(); ASSERT_NE(a, nullptr); // They have to be fail (return false values) const auto ret = manager->find<int>(metall::anonymous_instance); ASSERT_EQ(ret.first, nullptr); ASSERT_EQ(ret.second, 0); ASSERT_EQ(manager->destroy<int>(metall::anonymous_instance), false); manager->deallocate(a); delete manager; } TEST(ManagerTest, UniqueConstruct) { manager_type *manager; manager = new manager_type(metall::create_only, dir_path().c_str()); int *const a = manager->construct<int>(metall::unique_instance)(); ASSERT_NE(a, nullptr); double *const b = manager->find_or_construct<double>(metall::unique_instance)(); ASSERT_NE(b, nullptr); const auto ret_a = manager->find<int>(metall::unique_instance); ASSERT_EQ(ret_a.first, a); ASSERT_EQ(ret_a.second, 1); const auto ret_b = manager->find<double>(metall::unique_instance); ASSERT_EQ(ret_b.first, b); ASSERT_EQ(ret_b.second, 1); ASSERT_EQ(manager->destroy<int>(metall::unique_instance), true); ASSERT_EQ(manager->destroy<double>(metall::unique_instance), true); delete manager; } }
32.208502
127
0.663629
correaa
e2546d1c24a7e3e0e7d20e6501afb07c0543a152
3,579
cpp
C++
Project/Engine/Source/DataStream.cpp
lcomstive/Graphics-Assessment
bc52f41b31646ca5d2bb20669704db83c4f77361
[ "MIT-0" ]
null
null
null
Project/Engine/Source/DataStream.cpp
lcomstive/Graphics-Assessment
bc52f41b31646ca5d2bb20669704db83c4f77361
[ "MIT-0" ]
null
null
null
Project/Engine/Source/DataStream.cpp
lcomstive/Graphics-Assessment
bc52f41b31646ca5d2bb20669704db83c4f77361
[ "MIT-0" ]
1
2022-03-23T00:28:52.000Z
2022-03-23T00:28:52.000Z
#include <string> #include <iostream> #include <Engine/Utilities.hpp> #include <Engine/DataStream.hpp> using namespace std; using namespace Engine; const size_t DataStream::s_InitialStreamSize = 4096; // 4KB DataStream::DataStream(size_t initialSize) : m_Writing(true), m_Index(0), m_Length(initialSize), m_Data(new unsigned char[initialSize]) { } DataStream::DataStream(const DataStream& other) : m_Index(0), m_Writing(false) { m_Length = other.GetLength(); m_Data = new unsigned char[m_Length]; memcpy(m_Data, other.m_Data, (size_t)m_Length); } DataStream::DataStream(DataStream* other) : m_Index(0), m_Writing(false) { m_Length = (unsigned int)other->GetLength(); m_Data = new unsigned char[m_Length]; memcpy(m_Data, other->m_Data, (size_t)m_Length); } DataStream::DataStream(vector<unsigned char> GetData, size_t length) : m_Index(0), m_Writing(false) { m_Length = length > 0 ? length : (unsigned int)GetData.size(); m_Data = new unsigned char[m_Length]; memcpy(m_Data, GetData.data(), (size_t)m_Length); } DataStream::DataStream(unsigned char* GetData, size_t length) : m_Index(0), m_Writing(false) { if (length <= 0) throw std::runtime_error("Length is not assigned"); m_Length = length > 0 ? length : (unsigned int)length; m_Data = new unsigned char[m_Length]; memcpy(m_Data, GetData, (size_t)m_Length); } DataStream::DataStream(string path) : DataStream(Engine::Read(path)) { } DataStream::~DataStream() { delete[] m_Data; } void DataStream::SaveTo(string path) { Engine::Write(path, vector<unsigned char>(m_Data, m_Data + m_Index)); } DataStream DataStream::ReadFrom(string path) { return DataStream(Engine::Read(path)); } void DataStream::SetReading() { m_Writing = false; m_Length = m_Index; m_Index = 0; } void DataStream::SetWriting() { m_Writing = true; m_Index = 0; } void DataStream::Reserve(size_t additionalLength) { size_t newLength = m_Length + additionalLength; unsigned char* newData = new unsigned char[newLength]; memcpy(newData, m_Data, m_Length); delete[] m_Data; m_Data = newData; m_Length = newLength; } void DataStream::InternalWrite(StreamType type, unsigned char* GetData, size_t length) { if (!m_Writing) { #ifndef NDEBUG cerr << "Tried to write to DataStream in reading mode" << endl; #endif throw std::runtime_error("Tried to write to DataStream that was in reading mode"); } if ((length + m_Index + 1) > m_Length) Reserve((size_t)(m_Length * 1.25f) + length * 2); m_Data[m_Index++] = (unsigned char)type; if (type == StreamType::STRING || type == StreamType::CHARARRAY) { memcpy(m_Data + m_Index, &length, sizeof(unsigned int)); m_Index += sizeof(unsigned int); } memcpy(m_Data + m_Index, GetData, length); m_Index += length; } unsigned char* DataStream::InternalRead(StreamType expectedType, size_t length) { return InternalReadArray(expectedType, &length); } unsigned char* DataStream::InternalReadArray(StreamType expectedType, size_t* length) { if (m_Writing) { #ifndef NDEBUG cerr << "Tried reading DataStream while in write mode" << endl; #endif throw std::runtime_error("Tried reading DataStream but is in writing mode"); } StreamType type = (StreamType)m_Data[m_Index++]; if (type != expectedType) { #ifndef NDEBUG cerr << "Read wrong type, aborting..." << endl; #endif throw std::runtime_error("Read wrong type, aborting..."); } if (type == StreamType::STRING || type == StreamType::CHARARRAY) { memcpy(length, m_Data + m_Index, sizeof(unsigned int)); m_Index += sizeof(unsigned int); } m_Index += *length; return m_Data + m_Index - *length; }
28.404762
139
0.721989
lcomstive
e25854af1f5a7eb696b6e89f9a6a291a5e61d380
534
cpp
C++
thirdparty/simdjson/src/arm64/stage2.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
1
2021-11-17T21:39:49.000Z
2021-11-17T21:39:49.000Z
src/arm64/stage2.cpp
lemire/simdjson_cxxopts_tools
91016c31bdba68fa5920e8d0012a2ded9d7347b6
[ "Apache-2.0" ]
1
2020-05-29T09:28:02.000Z
2020-05-29T09:28:02.000Z
src/arm64/stage2.cpp
lemire/simdjson_cxxopts_tools
91016c31bdba68fa5920e8d0012a2ded9d7347b6
[ "Apache-2.0" ]
1
2020-05-28T13:57:15.000Z
2020-05-28T13:57:15.000Z
#ifndef SIMDJSON_ARM64_STAGE2_H #define SIMDJSON_ARM64_STAGE2_H #include "simdjson.h" #include "arm64/implementation.h" #include "arm64/stringparsing.h" #include "arm64/numberparsing.h" namespace simdjson { namespace arm64 { #include "generic/stage2/logger.h" #include "generic/stage2/atomparsing.h" #include "generic/stage2/structural_iterator.h" #include "generic/stage2/structural_parser.h" #include "generic/stage2/streaming_structural_parser.h" } // namespace arm64 } // namespace simdjson #endif // SIMDJSON_ARM64_STAGE2_H
24.272727
55
0.801498
liftchampion
e25ab94ca0dce9a8770721ca2d3151c46d74493f
555
inl
C++
Src/AGZUtils/Math/SwizzleVec2.inl
AirGuanZ/Utils
6ededbd838697682430a2c0746bfd3b36ff14a5b
[ "MIT" ]
10
2018-10-30T14:19:57.000Z
2021-12-06T07:46:59.000Z
Src/AGZUtils/Math/SwizzleVec2.inl
AirGuanZ/Utils
6ededbd838697682430a2c0746bfd3b36ff14a5b
[ "MIT" ]
null
null
null
Src/AGZUtils/Math/SwizzleVec2.inl
AirGuanZ/Utils
6ededbd838697682430a2c0746bfd3b36ff14a5b
[ "MIT" ]
3
2019-04-24T13:42:02.000Z
2021-06-28T08:17:28.000Z
#define SWIZZLE2(A, B) _SWIZZLE2(A, B) #define SWIZZLE3(A, B, C) _SWIZZLE3(A, B, C) #define SWIZZLE4(A, B, C, D) _SWIZZLE4(A, B, C, D) #define _SWIZZLE2(A, B) Vec2<T> A##B() const { return Vec2<T>(A, B); } #define _SWIZZLE3(A, B, C) Vec3<T> A##B##C() const { return Vec3<T>(A, B, C); } #define _SWIZZLE4(A, B, C, D) Vec4<T> A##B##C##D() const { return Vec4<T>(A, B, C, D); } SWIZZLE2(x, x) SWIZZLE2(x, y) SWIZZLE2(y, y) SWIZZLE2(y, x) #undef SWIZZLE2 #undef SWIZZLE3 #undef SWIZZLE4 #undef _SWIZZLE2 #undef _SWIZZLE3 #undef _SWIZZLE4
27.75
88
0.618018
AirGuanZ
e25af265b0a86a613701620396130a8b2f54dea7
6,579
cpp
C++
LIA_RAL_3.0/LIA_SpkDet/EigenVoice/src/EigenVoice.cpp
ibillxia/VoicePrintReco
20bf32f183abcd483fe1da451b4c75cf995b5f26
[ "MIT" ]
83
2015-01-18T01:20:37.000Z
2022-03-02T20:15:27.000Z
LIA_RAL_3.0/LIA_SpkDet/EigenVoice/src/EigenVoice.cpp
Dystopiaz/VoicePrintReco
20bf32f183abcd483fe1da451b4c75cf995b5f26
[ "MIT" ]
4
2016-03-03T08:43:00.000Z
2019-03-08T06:20:56.000Z
LIA_RAL_3.0/LIA_SpkDet/EigenVoice/src/EigenVoice.cpp
Dystopiaz/VoicePrintReco
20bf32f183abcd483fe1da451b4c75cf995b5f26
[ "MIT" ]
59
2015-02-02T03:07:37.000Z
2021-11-22T12:05:42.000Z
/* This file is part of LIA_RAL which is a set of software based on ALIZE toolkit for speaker recognition. ALIZE toolkit is required to use LIA_RAL. LIA_RAL project is a development project was initiated by the computer science laboratory of Avignon / France (Laboratoire Informatique d'Avignon - LIA) [http://lia.univ-avignon.fr <http://lia.univ-avignon.fr/>]. Then it was supported by two national projects of the French Research Ministry: - TECHNOLANGUE program [http://www.technolangue.net] - MISTRAL program [http://mistral.univ-avignon.fr] LIA_RAL 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 3 of the License, or any later version. LIA_RAL 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 LIA_RAL. If not, see [http://www.gnu.org/licenses/]. The LIA team as well as the LIA_RAL project team wants to highlight the limits of voice authentication in a forensic context. The "Person Authentification by Voice: A Need of Caution" paper proposes a good overview of this point (cf. "Person Authentification by Voice: A Need of Caution", Bonastre J.F., Bimbot F., Boe L.J., Campbell J.P., Douglas D.A., Magrin- chagnolleau I., Eurospeech 2003, Genova]. The conclusion of the paper of the paper is proposed bellow: [Currently, it is not possible to completely determine whether the similarity between two recordings is due to the speaker or to other factors, especially when: (a) the speaker does not cooperate, (b) there is no control over recording equipment, (c) recording conditions are not known, (d) one does not know whether the voice was disguised and, to a lesser extent, (e) the linguistic content of the message is not controlled. Caution and judgment must be exercised when applying speaker recognition techniques, whether human or automatic, to account for these uncontrolled factors. Under more constrained or calibrated situations, or as an aid for investigative purposes, judicious application of these techniques may be suitable, provided they are not considered as infallible. At the present time, there is no scientific process that enables one to uniquely characterize a persones voice or to identify with absolute certainty an individual from his or her voice.] Copyright (C) 2004-2010 Laboratoire d'informatique d'Avignon [http://lia.univ-avignon.fr] LIA_RAL admin [alize@univ-avignon.fr] Jean-Francois Bonastre [jean-francois.bonastre@univ-avignon.fr] */ #if !defined(ALIZE_EigenVoice_cpp) #define ALIZE_EigenVoice_cpp #include <iostream> #include <fstream> #include <cstdio> #include <cassert> #include <cmath> #include <liatools.h> #include "EigenVoice.h" using namespace std; using namespace alize; //----------------------------------------------------------------------------------------------------------------------------------------------------------- int EigenVoice(Config & config){ //Read the NDX file String ndxFilename = config.getParam("ndxFilename"); //Create and initialise the accumulator JFAAcc jfaAcc(ndxFilename, config,"EigenVoice"); //Option used to check the Likelihood at each iteration bool _checkLLK = false; if (config.existsParam("checkLLK")) _checkLLK= config.getParam("checkLLK").toBool(); else if (verboseLevel >2) _checkLLK= true; //Statistics if((config.existsParam("loadAccs")) && config.getParam("loadAccs").toBool()){ //load pre-computed statistics cout<<" (EigenVoice)Load Accumulators"<<endl; jfaAcc.loadN(config); jfaAcc.loadN_h(config); jfaAcc.loadF_X(config); jfaAcc.loadF_X_h(config); } else{ //Compute statistics if they don't exists jfaAcc.computeAndAccumulateJFAStat(config); jfaAcc.saveAccs(config); } //Initialise the EV Matrix bool loadInitEigenVoiceMatrix = false; if(config.existsParam("loadInitEigenVoiceMatrix")) loadInitEigenVoiceMatrix = config.getParam("loadInitEigenVoiceMatrix").toBool(); if(loadInitEigenVoiceMatrix){ //Load the EV matrix when existing jfaAcc.loadEV(config.getParam("initEigenVoiceMatrix"), config); } else{ //Initialise the EV matrix randomly if does not exists jfaAcc.initEV(config); } //Save the initial V matrix to be able restart the process with the same initialisation if(config.existsParam("saveInitEigenVoiceMatrix") && config.getParam("saveInitEigenVoiceMatrix").toBool()){ String initV = config.getParam("eigenVoiceMatrix")+"_init"; jfaAcc.saveV(initV, config); cout<<" (EigenVoice) Save the initial EigenVoice Matrix in "<<initV<<endl; } //iteratively retrain the EV matrix unsigned long nbIt = config.getParam("nbIt").toULong(); jfaAcc.storeAccs(); for(unsigned long it=0; it<nbIt; it++){ cout<<" (EigenVoices) --------- start iteration "<<it<<" --------"<<endl; //On calcules les matrices vEvT jfaAcc.estimateVEVT(config); //On calcules les matrices L et on les inverse (on integre la boucle sur tous les locuteurs dans cette fonction) jfaAcc.estimateAndInverseL_EV(config); //On soustrait les statistiques du locuteur (M+DZ)*Ns pour chaque locuteur jfaAcc.substractMplusDZ(config); //On soustrait pour chaque locuteur la composante canal de chaque session jfaAcc.substractUX(config); //On update Y pour tous les locuteurs jfaAcc.estimateYandV(config); if (_checkLLK) jfaAcc.verifyEMLK(config); //Update _V jfaAcc.updateVestimate(); //If the option is on, orthonormalize the matrix V if(config.existsParam("orthonormalizeV") && (config.getParam("orthonormalizeV").toBool())){ if(verboseLevel > 0) cerr<<"Orthonormalize EV matrix"<<endl; jfaAcc.orthonormalizeV(); } //Reinitialise the accumulators jfaAcc.resetTmpAcc("EigenVoice"); jfaAcc.restoreAccs(); //Save the V matrix at the end of the iteration bool saveAllEVMatrices = false; if(config.existsParam("saveAllEVMatrices")) saveAllEVMatrices=config.getParam("saveAllEVMatrices").toBool(); if(saveAllEVMatrices){ String s; String output = config.getParam("eigenVoiceMatrix") + s.valueOf(it); jfaAcc.saveV(output, config); } } cout<<" (EigenVoices) --------- save EigenVoices Matrix --------"<<endl; jfaAcc.saveV(config.getParam("eigenVoiceMatrix"), config); cout<<" (EigenVoices) --------- end of process --------"<<endl; return 0; } #endif
38.25
157
0.738714
ibillxia
e263fe91ac589101548d684bb3d377352e6c30d8
322
cpp
C++
C++/functions.cpp
tonmarcondes/UNIVESP
a66a623d4811e8f3f9e2999f09e38a4470035ae2
[ "MIT" ]
null
null
null
C++/functions.cpp
tonmarcondes/UNIVESP
a66a623d4811e8f3f9e2999f09e38a4470035ae2
[ "MIT" ]
null
null
null
C++/functions.cpp
tonmarcondes/UNIVESP
a66a623d4811e8f3f9e2999f09e38a4470035ae2
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int sum(int n1, int n2){ return (n1 + n2); } int sub(int n1, int n2){ return (n1 - n2); } int mult(int n1, int n2){ return (n1 * n2); } int divi(int n1, int n2){ return (n1 / n2); } int main(){ int a = 5, b = 3; }
15.333333
29
0.47205
tonmarcondes
e265b2420512b8600bc2c47fea6ea6a321c2b56c
218
hpp
C++
src/so_dll_file_execute/SharedLibrary.hpp
hahn-will/simple-cpp-unit
bf77c066ac881dfceffb5f1cbd3ab92e63b9229f
[ "MIT" ]
null
null
null
src/so_dll_file_execute/SharedLibrary.hpp
hahn-will/simple-cpp-unit
bf77c066ac881dfceffb5f1cbd3ab92e63b9229f
[ "MIT" ]
null
null
null
src/so_dll_file_execute/SharedLibrary.hpp
hahn-will/simple-cpp-unit
bf77c066ac881dfceffb5f1cbd3ab92e63b9229f
[ "MIT" ]
null
null
null
#ifndef SHARED_LIBRARY_HPP__ #define SHARED_LIBRARY_HPP__ class SharedLibrary { public: SharedLibrary(const char *); ~SharedLibrary(); void Execute(const char *); private: void *handle; }; #endif
15.571429
32
0.701835
hahn-will
e26b229dcf12e3eb516c74d6cf19463a496c5808
5,979
cpp
C++
test/info/iterators/iterator_impl/dereference.cpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
1
2020-10-20T06:53:05.000Z
2020-10-20T06:53:05.000Z
test/info/iterators/iterator_impl/dereference.cpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
null
null
null
test/info/iterators/iterator_impl/dereference.cpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
1
2020-08-13T17:46:40.000Z
2020-08-13T17:46:40.000Z
/** * @file * @author Marcel Breyer * @date 2020-08-04 * @copyright This file is distributed under the MIT License. * * @brief Test cases for the dereference operations of the @ref mpicxx::info::iterator and @ref mpicxx::info::const_iterator class. * @details Testsuite: *InfoIteratorImplTest* * | test case name | test case description | * |:----------------------|:-------------------------------------------------------------------------------------------------------------------------------------------| * | DereferenceValid | dereference valid iterator via [member access operators](https://en.cppreference.com/w/cpp/language/operator_member_access) | * | ConstDereferenceValid | dereference valid const_iterator via [member access operators](https://en.cppreference.com/w/cpp/language/operator_member_access) | * | DereferenceInvalid | dereference invalid iterator via [member access operators](https://en.cppreference.com/w/cpp/language/operator_member_access) (death test) | */ #include <mpicxx/info/info.hpp> #include <gtest/gtest.h> #include <mpi.h> TEST(InfoIteratorImplTest, DereferenceValid) { // create info object and add [key, value]-pairs mpicxx::info info; MPI_Info_set(info.get(), "key1", "value1"); MPI_Info_set(info.get(), "key2", "value2"); // using operator[] { // check if the retrieved [key, value]-pair is correct and can be changed mpicxx::info::iterator it = info.begin(); auto key_value_pair = it[1]; EXPECT_STREQ(key_value_pair.first.c_str(), "key2"); EXPECT_STREQ(static_cast<std::string>(key_value_pair.second).c_str(), "value2"); key_value_pair.second = "value2_override"; EXPECT_STREQ(static_cast<std::string>(key_value_pair.second).c_str(), "value2_override"); // check if the internal value changed char value[MPI_MAX_INFO_VAL]; int flag; MPI_Info_get(info.get(), "key2", 15, value, &flag); EXPECT_TRUE(static_cast<bool>(flag)); EXPECT_STREQ(value, "value2_override"); } // using operator* { // check if the retrieved [key, value]-pair is correct and can be changed mpicxx::info::iterator it = info.begin(); auto key_value_pair = *it; EXPECT_STREQ(key_value_pair.first.c_str(), "key1"); EXPECT_STREQ(static_cast<std::string>(key_value_pair.second).c_str(), "value1"); key_value_pair.second = "value1_override"; EXPECT_STREQ(static_cast<std::string>(key_value_pair.second).c_str(), "value1_override"); // check if the internal value changed char value[MPI_MAX_INFO_VAL]; int flag; MPI_Info_get(info.get(), "key1", 15, value, &flag); EXPECT_TRUE(static_cast<bool>(flag)); EXPECT_STREQ(value, "value1_override"); } // using operator-> { // check if the retrieved [key, value]-pair is correct and can be changed mpicxx::info::iterator it = info.begin(); EXPECT_STREQ(it->first.c_str(), "key1"); EXPECT_STREQ(static_cast<std::string>(it->second).c_str(), "value1_override"); it->second = "value1"; EXPECT_STREQ(static_cast<std::string>(it->second).c_str(), "value1"); // check if the internal value changed char value[MPI_MAX_INFO_VAL]; int flag; MPI_Info_get(info.get(), "key1", 15, value, &flag); EXPECT_TRUE(static_cast<bool>(flag)); EXPECT_STREQ(value, "value1"); } } TEST(InfoIteratorImplTest, ConstDereferenceValid) { // create info object and add [key, value]-pairs mpicxx::info info; MPI_Info_set(info.get(), "key1", "value1"); MPI_Info_set(info.get(), "key2", "value2"); // using operator[] { // check if the retrieved [key, value]-pair is correct mpicxx::info::const_iterator it = info.cbegin(); auto key_value_pair = it[1]; EXPECT_STREQ(key_value_pair.first.c_str(), "key2"); EXPECT_STREQ(key_value_pair.second.c_str(), "value2"); } // using operator* { // check if the retrieved [key, value]-pair is correct mpicxx::info::const_iterator it = info.cbegin(); auto key_value_pair = *it; EXPECT_STREQ(key_value_pair.first.c_str(), "key1"); EXPECT_STREQ(key_value_pair.second.c_str(), "value1"); } // using operator-> { // check if the retrieved [key, value]-pair is correct mpicxx::info::const_iterator it = info.cbegin(); EXPECT_STREQ(it->first.c_str(), "key1"); EXPECT_STREQ(it->second.c_str(), "value1"); } } TEST(InfoIteratorImplDeathTest, DereferenceInvalid) { // create info object and add [key, value]-pairs mpicxx::info info_null; mpicxx::info::iterator info_null_it = info_null.begin(); info_null = mpicxx::info(MPI_INFO_NULL, false); mpicxx::info info; MPI_Info_set(info.get(), "key", "value"); mpicxx::info::iterator it = info.begin(); mpicxx::info::iterator sit; // dereference using operator[] using res_t = mpicxx::info::iterator::reference; EXPECT_DEATH( [[maybe_unused]] res_t res = sit[0] , ""); EXPECT_DEATH( [[maybe_unused]] res_t res = info_null_it[0] , ""); EXPECT_DEATH( [[maybe_unused]] res_t res = it[-1] , ""); EXPECT_DEATH( [[maybe_unused]] res_t res = it[1] , ""); // dereference using operator* EXPECT_DEATH( [[maybe_unused]] res_t res = *sit , ""); EXPECT_DEATH( [[maybe_unused]] res_t res = *info_null_it , ""); EXPECT_DEATH( [[maybe_unused]] res_t res = *(it - 1) , ""); EXPECT_DEATH( [[maybe_unused]] res_t res = *(it + 1) , ""); // dereference using operator-> EXPECT_DEATH( sit->first , ""); EXPECT_DEATH( info_null_it->first , ""); EXPECT_DEATH( (it - 2)->first , ""); EXPECT_DEATH( (it + 2)->first , ""); }
43.326087
169
0.61231
arkantos493
e26d0eff4ad1ffcf518e272e05423dd74d565745
1,012
hpp
C++
src/core/output_interface.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
11
2016-03-31T17:46:15.000Z
2022-02-14T01:07:56.000Z
src/core/output_interface.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2016-04-04T16:40:47.000Z
2019-10-16T22:22:54.000Z
src/core/output_interface.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2019-10-16T22:20:15.000Z
2019-11-28T11:59:03.000Z
/* Copyright 2016 Mitchell Young 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. */ #pragma once #include "util/h5file.hpp" namespace mocc { /** * This simply specifies an interface for outputing "stuff" to and HDF5 * file. Any class extending it must implement the output() method, which * adds its data to the H5File instance passed to it. */ class HasOutput { public: /** * \brief Output relevant data to an HDF5 file node. */ virtual void output(H5Node &file) const = 0; }; }
28.914286
75
0.720356
tp-ntouran
e27125c6ff564461d081589d3a3f736b0a5f4a14
6,271
cpp
C++
MARS geofencing/Library/PackageCache/com.unity.mars-ar-foundation-providers@1.3.1/NativePlugin~/Source/TrackingProvider.cpp
bsides44/MARSGeofencing
23f1ff88ac8be3db558f43d68813528a587225bf
[ "Apache-2.0" ]
null
null
null
MARS geofencing/Library/PackageCache/com.unity.mars-ar-foundation-providers@1.3.1/NativePlugin~/Source/TrackingProvider.cpp
bsides44/MARSGeofencing
23f1ff88ac8be3db558f43d68813528a587225bf
[ "Apache-2.0" ]
null
null
null
MARS geofencing/Library/PackageCache/com.unity.mars-ar-foundation-providers@1.3.1/NativePlugin~/Source/TrackingProvider.cpp
bsides44/MARSGeofencing
23f1ff88ac8be3db558f43d68813528a587225bf
[ "Apache-2.0" ]
null
null
null
#include "TrackingProvider.h" #include "ProviderContext.h" #include "XR/UnitySubsystemTypes.h" static UnityXRPose sPose; UnitySubsystemErrorCode MARSTrackingProvider::Initialize() { return kUnitySubsystemErrorCodeSuccess; } UnitySubsystemErrorCode MARSTrackingProvider::Start() { m_Ctx.input->InputSubsystem_DeviceConnected(m_Handle, kInputDeviceHMD); return kUnitySubsystemErrorCodeSuccess; } static float s_Time = 0.0f; void MARSTrackingProvider::OnNewInputFrame() { // Latch poses for sim } void MARSTrackingProvider::FillDeviceDefinition(UnityXRInternalInputDeviceId deviceId, UnityXRInputDeviceDefinition* definition) { // Fill in your connected device information here when requested. Used to create customized device states. auto& input = *m_Ctx.input; input.DeviceDefinition_SetName(definition, "MARS XR Subsystem camera tracking"); input.DeviceDefinition_SetRole(definition, kUnityXRInputDeviceRoleGeneric); input.DeviceDefinition_SetManufacturer(definition, "Unity"); // Add basic feature usages for 1-element tracking to match Input Systems XRHMD input.DeviceDefinition_AddFeatureWithUsage(definition, "IsTracked", kUnityXRInputFeatureTypeBinary, kUnityXRInputFeatureUsageIsTracked); input.DeviceDefinition_AddFeatureWithUsage(definition, "TrackingState", kUnityXRInputFeatureTypeDiscreteStates, kUnityXRInputFeatureUsageTrackingState); input.DeviceDefinition_AddFeatureWithUsage(definition, "centerEyePosition", kUnityXRInputFeatureTypeAxis3D, kUnityXRInputFeatureUsageCenterEyePosition); input.DeviceDefinition_AddFeatureWithUsage(definition, "centerEyeRotation", kUnityXRInputFeatureTypeRotation, kUnityXRInputFeatureUsageCenterEyeRotation); } UnitySubsystemErrorCode MARSTrackingProvider::UpdateDeviceState(UnityXRInternalInputDeviceId deviceId, UnityXRInputUpdateType updateType, UnityXRInputDeviceState* state) { /// Called by Unity when it needs a current device snapshot auto& input = *m_Ctx.input; if (deviceId == kInputDeviceHMD) { UnityXRInputFeatureIndex featureIdx = 0; input.DeviceState_SetBinaryValue(state, featureIdx++, true); input.DeviceState_SetDiscreteStateValue(state, featureIdx++, kUnityXRInputTrackingStatePosition | kUnityXRInputTrackingStateRotation); input.DeviceState_SetAxis3DValue(state, featureIdx++, sPose.position); input.DeviceState_SetRotationValue(state, featureIdx++, sPose.rotation); } return kUnitySubsystemErrorCodeSuccess; } UnitySubsystemErrorCode MARSTrackingProvider::HandleEvent(UnityXRInputEventType eventType, UnityXRInternalInputDeviceId deviceId, void* buffer, unsigned int size) { /// Return kUnitySubsystemErrorCodeFailure on all unhandled events so the calling code knows we didn't modify the returned buffer. return kUnitySubsystemErrorCodeFailure; } void MARSTrackingProvider::Stop() { m_Ctx.input->InputSubsystem_DeviceDisconnected(m_Handle, kInputDeviceHMD); } void MARSTrackingProvider::Shutdown() { } // Binding to C-API below here extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API MARSXRSubsystem_SetCameraPose( float pos_x, float pos_y, float pos_z, float rot_x, float rot_y, float rot_z, float rot_w) { sPose.position.x = pos_x; sPose.position.y = pos_y; sPose.position.z = pos_z; sPose.rotation.x = rot_x; sPose.rotation.y = rot_y; sPose.rotation.z = rot_z; sPose.rotation.w = rot_w; } static UnitySubsystemErrorCode UNITY_INTERFACE_API Input_Initialize(UnitySubsystemHandle handle, void* userData) { auto& ctx = GetProviderContext(userData); ctx.trackingProvider = new MARSTrackingProvider(ctx, handle); UnityXRInputProvider inputProvider{}; inputProvider.userData = &ctx; inputProvider.OnNewInputFrame = [](UnitySubsystemHandle handle, void* userData) -> void { auto& ctx = GetProviderContext(userData); ctx.trackingProvider->OnNewInputFrame(); }; inputProvider.FillDeviceDefinition = [](UnitySubsystemHandle handle, void* userData, UnityXRInternalInputDeviceId deviceId, UnityXRInputDeviceDefinition* definition) -> void { auto& ctx = GetProviderContext(userData); ctx.trackingProvider->FillDeviceDefinition(deviceId, definition); }; inputProvider.UpdateDeviceState = [](UnitySubsystemHandle handle, void* userData, UnityXRInternalInputDeviceId deviceId, UnityXRInputUpdateType updateType, UnityXRInputDeviceState* state) -> UnitySubsystemErrorCode { auto& ctx = GetProviderContext(userData); return ctx.trackingProvider->UpdateDeviceState(deviceId, updateType, state); }; inputProvider.HandleEvent = [](UnitySubsystemHandle handle, void* userData, UnityXRInputEventType eventType, UnityXRInternalInputDeviceId deviceId, void* buffer, unsigned int size) -> UnitySubsystemErrorCode { auto& ctx = GetProviderContext(userData); return ctx.trackingProvider->HandleEvent(eventType, deviceId, buffer, size); }; ctx.input->RegisterInputProvider(handle, &inputProvider); return ctx.trackingProvider->Initialize(); } UnitySubsystemErrorCode Load_Input(ProviderContext& ctx) { ctx.input = ctx.interfaces->Get<IUnityXRInputInterface>(); if (ctx.input == nullptr) { return kUnitySubsystemErrorCodeFailure; } UnityLifecycleProvider inputLifecycleHandler{}; inputLifecycleHandler.userData = &ctx; inputLifecycleHandler.Initialize = &Input_Initialize; inputLifecycleHandler.Start = [](UnitySubsystemHandle handle, void* userData) -> UnitySubsystemErrorCode { auto& ctx = GetProviderContext(userData); auto r = ctx.trackingProvider->Start(); return r; }; inputLifecycleHandler.Stop = [](UnitySubsystemHandle handle, void* userData) -> void { auto& ctx = GetProviderContext(userData); ctx.trackingProvider->Stop(); }; inputLifecycleHandler.Shutdown = [](UnitySubsystemHandle handle, void* userData) -> void { auto& ctx = GetProviderContext(userData); ctx.trackingProvider->Shutdown(); delete ctx.trackingProvider; }; return ctx.input->RegisterLifecycleProvider("MARS XR Plugin", "MARS Head Tracking", &inputLifecycleHandler); }
39.19375
218
0.768617
bsides44
e27bcbb19af91529576fdd0421f79b906c2dd3b6
245
cpp
C++
test/linqcppTestFixture.cpp
baguapro/linqcpp
8caa1f6c57f87e618eab8d01a95e348013c1ac7d
[ "MIT" ]
null
null
null
test/linqcppTestFixture.cpp
baguapro/linqcpp
8caa1f6c57f87e618eab8d01a95e348013c1ac7d
[ "MIT" ]
null
null
null
test/linqcppTestFixture.cpp
baguapro/linqcpp
8caa1f6c57f87e618eab8d01a95e348013c1ac7d
[ "MIT" ]
null
null
null
#include "linqcppTestFixture.h" namespace linqcpp_test_fixture { bool operator==(const LinqTest::person &lhs, const LinqTest::person &rhs) { return (lhs.first_name_ == rhs.first_name_ && lhs.last_name_ == rhs.last_name_); } }
18.846154
73
0.697959
baguapro
e28ce1928781247e12aa0ddc482cfcb689a258d5
2,240
cpp
C++
software/src/master/src/kernel/Vca_VInterfaceMember.cpp
c-kuhlman/vision
46b25f7c0da703c059acc8f0a2eac1d5badf9f6d
[ "BSD-3-Clause" ]
30
2016-10-07T15:23:35.000Z
2020-03-25T20:01:30.000Z
src/kernel/Vca_VInterfaceMember.cpp
MichaelJCaruso/vision-software-src-master
12b1b4f12a7531fe6e3cbb6861b40ac8e1985b92
[ "BSD-3-Clause" ]
30
2016-10-31T19:48:08.000Z
2021-04-28T01:31:53.000Z
software/src/master/src/kernel/Vca_VInterfaceMember.cpp
c-kuhlman/vision
46b25f7c0da703c059acc8f0a2eac1d5badf9f6d
[ "BSD-3-Clause" ]
15
2016-10-07T16:44:13.000Z
2021-06-21T18:47:55.000Z
/***** Vca_VInterfaceMember Implementation *****/ /************************ ************************ ***** Interfaces ***** ************************ ************************/ /******************** ***** System ***** ********************/ #include "Vk.h" /****************** ***** Self ***** ******************/ #include "Vca_VInterfaceMember.h" /************************ ***** Supporting ***** ************************/ #include "Vca_CompilerHappyPill.h" #include "Vca_VTypeInfoHolder.h" /*********************************** *********************************** ***** ***** ***** Vca::VInterfaceMember ***** ***** ***** *********************************** ***********************************/ /************************** ************************** ***** Construction ***** ************************** **************************/ Vca::VInterfaceMember::VInterfaceMember (char const *pName, unsigned int xMember) : m_pName (pName), m_xMember (xMember), m_pSuccessor (0) { } Vca::VInterfaceMember::VInterfaceMember (Initializer const &rInitializer) : m_pName (rInitializer.m_pName), m_xMember (rInitializer.m_xMember) { } /************************* ************************* ***** Destruction ***** ************************* *************************/ Vca::VInterfaceMember::~VInterfaceMember () { } /********************************* ********************************* ***** Member Registration ***** ********************************* *********************************/ void Vca::VInterfaceMember::registerWithTypeInfoHolder ( VTypeInfoHolderInstance &rTypeInfoHolderInstance ) { rTypeInfoHolderInstance.registerMember (this); } /*************************** *************************** ***** Member Lookup ***** *************************** ***************************/ Vca::VInterfaceMember const *Vca::VInterfaceMember::firstMemberWithSignature ( VTypeInfo::ParameterSignature const &rParameterSignature ) const { for (VInterfaceMember const *pMember = this; pMember; pMember = pMember->successor ()) if (pMember->parameterSignature_() == rParameterSignature) return pMember; return 0; }
24.888889
90
0.394196
c-kuhlman
e29c17244aa2d5558191758b3e6850e35433a2fd
797
cpp
C++
test/utils/wasm_engine.cpp
herobank110/fizzy
b58d6e6f7e6c26a07600f10d267695b00cf49470
[ "Apache-2.0" ]
1
2022-03-19T05:59:46.000Z
2022-03-19T05:59:46.000Z
test/utils/wasm_engine.cpp
herobank110/fizzy
b58d6e6f7e6c26a07600f10d267695b00cf49470
[ "Apache-2.0" ]
null
null
null
test/utils/wasm_engine.cpp
herobank110/fizzy
b58d6e6f7e6c26a07600f10d267695b00cf49470
[ "Apache-2.0" ]
null
null
null
// Fizzy: A fast WebAssembly interpreter // Copyright 2020 The Fizzy Authors. // SPDX-License-Identifier: Apache-2.0 #include "wasm_engine.hpp" #include <stdexcept> #include <string> namespace fizzy::test { WasmEngine::~WasmEngine() noexcept = default; void validate_function_signature(std::string_view signature) { if (signature.find_first_of(':') == std::string::npos) throw std::runtime_error{"Missing ':' delimiter"}; if (signature.find_first_of(':') != signature.find_last_of(':')) throw std::runtime_error{"Multiple occurrences of ':' found in signature"}; // Only allow i (i32) I (i64) as types if (signature.find_first_not_of(":iI") != std::string::npos) throw std::runtime_error{"Invalid type found in signature"}; } } // namespace fizzy::test
33.208333
83
0.697616
herobank110
e2a650d576f92bb53e312764dd95f29a464338bf
12,479
cc
C++
main/src/PolygonTriangularization/poly_triang.cc
marcomanno/ploygon_triangulation
c98b99e3f9598252ffc27eb202939f0183ac872b
[ "Apache-2.0" ]
null
null
null
main/src/PolygonTriangularization/poly_triang.cc
marcomanno/ploygon_triangulation
c98b99e3f9598252ffc27eb202939f0183ac872b
[ "Apache-2.0" ]
null
null
null
main/src/PolygonTriangularization/poly_triang.cc
marcomanno/ploygon_triangulation
c98b99e3f9598252ffc27eb202939f0183ac872b
[ "Apache-2.0" ]
null
null
null
#include "poly_triang.hh" #include "Geo/area.hh" #include "Geo/entity.hh" #include "Geo/plane_fitting.hh" #include "Geo/linear_system.hh" #include "Geo/point_in_polygon.hh" #include "Geo/tolerance.hh" #include "Utils/circular.hh" #include "Utils/statistics.hh" #include <Utils/error_handling.hh> #include <numeric> //#define DEBUG_PolygonTriangularization #include "Import/import.hh" namespace Geo { struct PolygonTriangulation : public IPolygonTriangulation { virtual void add(const std::vector<Geo::VectorD3>& _plgn) override; virtual const std::vector<std::array<size_t, 3>>& triangles() override { compute(); return sol_.tris_; } const std::vector<Geo::VectorD3>& polygon() override { compute(); return loops_[0]; } virtual double area() override { compute(); return sol_.area_; } private: struct Solution { void compute(const std::vector<Geo::VectorD3>& _pos, std::vector<size_t>& _indcs, const double _tols, Geo::VectorD<3>& _norm); bool concave(size_t _i) const { return _i < concav_.size() && concav_[_i]; } bool contain_concave(size_t _inds[3], Geo::VectorD3 _vects[2], const std::vector<Geo::VectorD3>& _pts) const; bool find_concave(const std::vector<Geo::VectorD3>& _pts, std::vector<bool>& _concav) const; std::vector<std::array<size_t, 3>> tris_; double area_ = 0; std::vector<bool> concav_; }; void compute(); typedef std::vector<Geo::VectorD3> Polygon; typedef std::vector<Polygon> PolygonVector; PolygonVector loops_; Solution sol_; }; std::shared_ptr<IPolygonTriangulation> IPolygonTriangulation::make() { return std::make_shared<PolygonTriangulation>(); } void PolygonTriangulation::add( const std::vector<Geo::VectorD3>& _plgn) { loops_.push_back(_plgn); sol_.area_ = 0; } void PolygonTriangulation::compute() { if (sol_.area_ > 0 || loops_.empty()) return; // Triangulation already computed. auto pl_fit = Geo::IPlaneFit::make(); auto pts_nmbr = loops_[0].size(); for (int i = 0; ++i < loops_.size(); ) pts_nmbr += loops_[i].size(); pl_fit->init(pts_nmbr); for (const auto& loop : loops_) for (const auto& pt : loop) pl_fit->add_point(pt); Geo::VectorD<3> centr, norm; pl_fit->compute(centr, norm); Utils::StatisticsT<double> tol_max; for (const auto& loop : loops_) for (const auto& pt : loop) tol_max.add(Geo::epsilon_sq(pt - centr)); const auto tol = tol_max.max() * 10; if (loops_.size() > 1) { // Put the outer loop at the begin of the list. auto pt = loops_[0][0]; for (auto loop_it = std::next(loops_.begin()); loop_it != loops_.end(); ++loop_it) { auto where = Geo::PointInPolygon::classify(*loop_it, pt, tol, &norm); if (where == Geo::PointInPolygon::Inside) { std::swap(loops_.front(), *loop_it); break; } } while (loops_.size() > 1) { Utils::StatisticsT<double> stats; auto pt0 = loops_[0].back(); struct ConnInfo { Polygon::iterator near_bnd_v, near_isl_v; PolygonVector::iterator near_island; double near_par = 0; } ci, bci; // connection info and best connection info for (ci.near_bnd_v = loops_[0].begin(); ci.near_bnd_v != loops_[0].end(); pt0 = *(ci.near_bnd_v++)) { Geo::Segment seg = { pt0, *ci.near_bnd_v }; for (ci.near_island = std::next(loops_.begin()); ci.near_island != loops_.end(); ++ci.near_island) { for (ci.near_isl_v = ci.near_island->begin(); ci.near_isl_v != ci.near_island->end(); ++ci.near_isl_v) { double dist_sq; if (!Geo::closest_point(seg, *ci.near_isl_v, nullptr, &ci.near_par, &dist_sq)) { continue; } if (stats.add(dist_sq) & stats.Smallest) bci = ci; } } } if (bci.near_par < 0.5) { if (bci.near_bnd_v == loops_[0].begin()) bci.near_bnd_v = loops_[0].end(); --bci.near_bnd_v; } std::rotate(bci.near_island->begin(), bci.near_isl_v, bci.near_island->end()); bci.near_island->push_back(bci.near_island->front()); bci.near_island->push_back(*bci.near_bnd_v); loops_[0].insert(std::next(bci.near_bnd_v), bci.near_island->cbegin(), bci.near_island->cend()); loops_.erase(bci.near_island); } } // creates the indexvector removing duplicates. std::vector<rsize_t> indcs; indcs.reserve(loops_[0].size()); for (size_t i = 0, j; i < loops_[0].size(); ++i) { for (j = 0; j < i; ++j) if (loops_[0][i] == loops_[0][j]) { loops_[0].erase(loops_[0].begin() + (i--)); break; } indcs.push_back(j); } sol_.compute(loops_[0], indcs, tol, norm); } void PolygonTriangulation::Solution::compute( const std::vector<Geo::VectorD3>& _pts, std::vector<size_t>& _indcs, const double, Geo::VectorD<3>&) { auto valid_triangle = [&_indcs, &_pts](const size_t _i, const std::vector<Geo::VectorD3>& proj_poly, const Geo::VectorD3& _norm, const double& _tol) { auto next = _i; auto idx = Utils::decrease(_i, _indcs.size()); auto prev = Utils::decrease(idx, _indcs.size()); std::vector<Geo::VectorD3> tmp_poly(3); tmp_poly[0] = _pts[_indcs[prev]]; tmp_poly[1] = _pts[_indcs[idx]]; tmp_poly[2] = _pts[_indcs[next]]; // Check that one other vertex is not isnide thetriangle. // Just to be shure that the rest of the chain is not completely // inside the new triangle. for (auto i : _indcs) { if (i == _indcs[next] || i == _indcs[prev] || i == _indcs[idx]) continue; auto where = Geo::PointInPolygon::classify(tmp_poly, _pts[i], _tol, &_norm); if (where != Geo::PointInPolygon::Outside) return false; } for (auto frac : { 0.5, 0.25, 0.75 }) { auto pt_in = proj_poly[prev] * frac + proj_poly[next] * (1 - frac); auto where = Geo::PointInPolygon::classify( proj_poly, pt_in, Geo::epsilon(pt_in), &_norm); if (where == Geo::PointInPolygon::Outside) return false; if (where == Geo::PointInPolygon::Inside) break; } auto j = proj_poly.size() - 1; Geo::Segment seg = { proj_poly[prev], proj_poly[next] }; for (size_t i = 0; i < proj_poly.size(); j = i++) { if (_indcs[i] == _indcs[next] || _indcs[i] == _indcs[prev]) continue; double dist_sq = 0; //const auto prec = std::numeric_limits<double>::epsilon() * 100; //double tol_sq = prec * std::max(Geo::length_square(seg[0]), Geo::length_square(seg[1])); double tol_sq = std::max(Geo::epsilon_sq(seg[0]), Geo::epsilon_sq(seg[1])); if (Geo::closest_point(seg, proj_poly[i], nullptr, nullptr, &dist_sq) && dist_sq <= tol_sq) return false; if (_indcs[j] == _indcs[next] || _indcs[j] == _indcs[prev]) continue; Geo::Segment seg1 = { proj_poly[i], proj_poly[j] }; //tol_sq = std::max(tol_sq, prec * std::max(Geo::length_square(seg1[0]), Geo::length_square(seg1[1]))); if (Geo::closest_point(seg, seg1, nullptr, nullptr, &dist_sq) && dist_sq <= tol_sq) { return false; } } return true; }; while (_indcs.size() > 3) { #ifdef DEBUG_PolygonTriangularization std::string flnm("debug_poly_"); flnm += std::to_string(_indcs.size()) + ".obj"; IO::save_obj(flnm.c_str(), _pts, &_indcs); #endif Geo::VectorD3 vects[2], centre; size_t inds[3] = { *(_indcs.end() - 2), _indcs.back(), 0 }; vects[0] = _pts[inds[0]] - _pts[inds[1]]; auto norm = Geo::point_polygon_normal(_pts.begin(), _pts.end(), &centre); std::vector<Geo::VectorD3> proj_poly; Utils::StatisticsT<double> tol_max; for (auto ii : _indcs) { auto pt = _pts[ii] - centre; pt -= (pt * norm) * norm; proj_poly.push_back(pt); tol_max.add(Geo::epsilon_sq(pt)); } auto tol = sqrt(9 * tol_max.max()); std::vector<double> angles; const auto invalid_double = std::numeric_limits<double>::max(); for (size_t i = 0; i < _indcs.size(); ++i) { inds[2] = _indcs[i]; vects[1] = _pts[inds[2]] - _pts[inds[1]]; if (inds[0] != inds[2] && valid_triangle(i, proj_poly, norm, tol)) angles.push_back(Geo::signed_angle(vects[1], vects[0], norm)); else angles.push_back(invalid_double); inds[0] = inds[1]; inds[1] = inds[2]; vects[0] = -vects[1]; } for (auto& ang : angles) if (ang < 0) ang += M_PI; std::vector<double> scores(angles); for (size_t i = 0; i < scores.size(); ++i) { if (angles[i] == invalid_double) { scores[Utils::decrease(i, scores.size())] -= M_PI; scores[Utils::increase(i, scores.size())] -= M_PI; } } Utils::StatisticsT<double> min_ang; for (size_t i = 0; i < scores.size(); ++i) min_ang.add(scores[i], i); if (min_ang.min() == invalid_double) { IO::save_obj("No_good_triangle_found", _pts, &_indcs); THROW("No good triangle found."); } std::array<size_t, 3> tri; tri[2] = min_ang.min_idx(); tri[1] = Utils::decrease(tri[2], _indcs.size()); auto to_rem = tri[1]; tri[0] = Utils::decrease(tri[1], _indcs.size()); for (auto& pt_ind : tri) pt_ind = _indcs[pt_ind]; tris_.push_back(tri); _indcs.erase(_indcs.begin() + to_rem); } if (_indcs.size() == 3) { std::array<size_t, 3> tri = { 0, 1, 2 }; for (auto& pt_ind : tri) pt_ind = _indcs[pt_ind]; tris_.push_back(tri); } area_ = 0.; for (const auto& tri : tris_) area_ += Geo::area(_pts[tri[0]], _pts[tri[1]], _pts[tri[2]]); } namespace { // return 0 - outside, 1 - on boundary, 2 - inside size_t inside_triangle( const Geo::VectorD3 _vert[2], const Geo::VectorD3& _test_pt) { double A[2][2], B[2], X[2]; for (int i = 0; i < 2; ++i) { for (int j = i; j < 2; ++j) A[i][j] = A[j][i] = _vert[i] * _vert[j]; B[i] = _vert[i] * _test_pt; } if (!Geo::solve_2x2(A, X, B)) return 0; size_t result = 0; if (X[0] >= 0 && X[1] >= 0 && (X[0] + X[1]) <= 1) { ++result; if (X[0] > 0 && X[1] > 0 && (X[0] + X[1]) < 1) ++result; } return result; } size_t inside_triangle(const Geo::VectorD3& _pt, const Geo::VectorD3& _vrt0, const Geo::VectorD3& _vrt1, const Geo::VectorD3& _vrt2 ) { const Geo::VectorD3 verts[2] = { _vrt1 - _vrt0, _vrt2 - _vrt0 }; return inside_triangle(verts, _pt - _vrt0); } } bool PolygonTriangulation::Solution::find_concave( const std::vector<Geo::VectorD3>& _pts, std::vector<bool>& _concav) const { bool achange = false; _concav.resize(_pts.size()); for (size_t i = 0; i < _pts.size(); ++i) { _concav[i] = concave(i); size_t inside = 0; for (const auto& tri : tris_) { if (std::find(tri.begin(), tri.end(), i) != tri.end()) continue; inside += inside_triangle( _pts[i], _pts[tri[0]], _pts[tri[1]], _pts[tri[2]]); if (inside > 1) { _concav[i] = !_concav[i]; achange = true; break; } } } return achange; } bool PolygonTriangulation::Solution::contain_concave( size_t _inds[3], Geo::VectorD3 _vects[2], const std::vector<Geo::VectorD3>& _pts) const { for (auto i = 0; i < concav_.size(); ++i) { if (i == _inds[0] || i == _inds[2] || !concav_[i]) continue; if (inside_triangle(_vects, _pts[i] - _pts[_inds[1]])) return true; } return false; } } // namespace Geo
30.36253
110
0.551006
marcomanno
e2aa237e30f08292db1a198cd79e25426fb72683
4,686
hpp
C++
Matrix.hpp
7Mersenne/NNplusplus
6387a73fcfe1a77ad703799272664f3a5d4cb0ff
[ "MIT" ]
266
2016-08-26T04:43:42.000Z
2022-03-31T17:54:29.000Z
Matrix.hpp
7Mersenne/NNplusplus
6387a73fcfe1a77ad703799272664f3a5d4cb0ff
[ "MIT" ]
2
2016-08-29T14:23:31.000Z
2022-01-07T13:50:41.000Z
Matrix.hpp
stagadish/NNplusplus
12d1916d7e5fc0f15226f2472e96f0e9754ec02b
[ "MIT" ]
40
2016-08-26T23:26:40.000Z
2020-07-17T07:31:14.000Z
// // Matrix.hpp // Neural Net // // A matrix object, which includes basic operations such as // matrix transpose and dot product. // // Created by Gil Dekel on 8/19/16. // Last edited by Gil Dekel on 8/30/16. // #ifndef MATRIX_HPP_ #define MATRIX_HPP_ #include <iostream> #include <utility> // std::swap and std::move #include <vector> #include <cmath> // INFINITY #include "MatrixExceptions.hpp" class Matrix { public: /********************************************************** * Constructors **********************************************************/ // Basic ctor to inisialize a matrix of size m by n. // All matrix positions will be initialized to 0. Matrix(size_t m = 0, size_t n = 0); // COPY ctor Matrix(const Matrix &rhs); // Copy assignment operator Matrix& operator=(const Matrix &rhs); // MOVE ctor Matrix(Matrix &&rhs); // Move assignment operator Matrix& operator=(Matrix &&rhs); // dealloc matrix_ (dtor) ~Matrix(); /********************************************************** * Operator Overloads **********************************************************/ // A substitute to operator[] for a 2D arrays double& operator()(size_t row, size_t col); const double& operator()(size_t row, size_t col) const; // ADDITION Matrix& operator+=(const Matrix & rhs); Matrix& operator+=(double scalar); // Term by term addition operator for two matricies. friend Matrix operator+(Matrix lhs, const Matrix &rhs); // Term by term addition operator for matrix and scalar. friend Matrix operator+(Matrix lhs, double scalar); // Allowing for the scalar addition commutative property. friend Matrix operator+(double scalar, Matrix rhs); // SUBTRACTION Matrix& operator-=(const Matrix & rhs); Matrix& operator-=(double scalar); // Term by term subtraction operator for two matricies. friend Matrix operator-(Matrix lhs, const Matrix &rhs); // Term by term subtraction operator for matrix and scalar. friend Matrix operator-(Matrix lhs, double scalar); // Term by term subtraction operator for scalar and matrix. friend Matrix operator-(double scalar, Matrix rhs); // MULTIPLICATION Matrix& operator*=(const Matrix & rhs); Matrix& operator*=(double scalar); // "Regular", term by term multiplication operator. // See function dot(Matrix &rhs) for dot product. friend Matrix operator*(Matrix lhs, const Matrix &rhs); // "Regular" scalar multiplication over matrix. friend Matrix operator*(Matrix lhs, double scalar); // Allowing for the scalar multiplication commutative property. friend Matrix operator*(double scalar, Matrix rhs); //DIVISION Matrix& operator/=(const Matrix & rhs); Matrix& operator/=(double scalar); // Term by term division operator for two matricies. friend Matrix operator/(Matrix lhs, const Matrix &rhs); // Term by term division operator for matrix and scalar. friend Matrix operator/(Matrix lhs, double scalar); // Term by term division operator for scalar and matrix. friend Matrix operator/(double scalar, Matrix rhs); // Unary minus operator for Matrix term by term negation Matrix operator-() const; /********************************************************** * Other Functions **********************************************************/ // A simple matrix algebra dot product operation. // Return a 0 by 0 matrix if the dimensions do not match. // See operator*(Matrix &rhs) for term by term multiplication. Matrix dot(const Matrix& rhs) const; // Get number of rows (M)xN size_t getNumOfRows() const; // Get number of columns Mx(N) size_t getNumOfCols() const; // Transpose the matrix MxN -> NxM Matrix T() const; // Get the coordinates of the largest value in the matrix. // Will return the coordinates of the earliest larger val. std::pair<size_t, size_t> getMaxVal() const; // Print the matrix to std::cout void printMtrx() const; private: size_t m_size_; // (M)xN size_t n_size_; // Mx(N) double *matrix_; // A pointer to the array. double **rowPtrs_; // An array of row pointers. // used to avoid repeated arithmetics // at each access to the matrix. }; #endif /* MATRIX_HPP_ */
27.727811
67
0.580026
7Mersenne
e2ab32a047a7ae5f821192bce53efc7594f8a447
5,471
cxx
C++
src/dgate/dicomlib/safemem.cxx
theorose49/conquest-dicom-server
aba35e1da51d7bb288ecde0f31d6963f47b8252c
[ "Apache-2.0" ]
null
null
null
src/dgate/dicomlib/safemem.cxx
theorose49/conquest-dicom-server
aba35e1da51d7bb288ecde0f31d6963f47b8252c
[ "Apache-2.0" ]
6
2021-06-09T19:39:27.000Z
2021-09-30T16:41:40.000Z
radiomicsfeatureextractionpipeline/conquest/src/dgate/dicomlib/safemem.cxx
Maastro-CDS-Imaging-Group/SQLite4Radiomics
e3a7afc181eec0fe04c18da00edc3772064e6758
[ "Apache-2.0" ]
null
null
null
/* 20010720 ljz Changed 'printf' to 'fprintf(stderr,...)' */ /**************************************************************************** Copyright (C) 1995, University of California, Davis THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH THE USER. Copyright of the software and supporting documentation is owned by the University of California, and free access is hereby granted as a license to use this software, copy this software and prepare derivative works based upon this software. However, any distribution of this software source code or supporting documentation or derivative works (source code and supporting documentation) must include this copyright notice. ****************************************************************************/ /*************************************************************************** * * University of California, Davis * UCDMC DICOM Network Transport Libraries * Version 0.1 Beta * * Technical Contact: mhoskin@ucdavis.edu * ***************************************************************************/ # include "dicom.hpp" #ifdef DEBUG_VERSION SafeMemory SF; // For the init / de-init # include <stddef.h> # include <stdlib.h> typedef struct _MemAction { int AllocOrDelete; int LineNumber; char *FileName; int MemSize; void *vptr; struct _MemAction *Related; struct _MemAction *Prev, *Next; } MemAction; static char TempFileName[1024]; static int TempLineNumber; MemAction *MemorySegments; MemAction *CreateMemAction ( char *FileName, int LineNumber, int Action, int Size, void *vptr) { MemAction *MA; MA = (MemAction*)malloc(sizeof(MemAction)); memset((void*)MA, 0, sizeof(MemAction)); MA->FileName = (char*)malloc(strlen(FileName)+1); strcpy(MA->FileName, FileName); MA->AllocOrDelete = Action; MA->vptr = vptr; MA->MemSize = Size; MA->LineNumber = LineNumber; return ( MA ); } BOOL FreeMemAction ( MemAction *MA ) { /* very destructive */ if ( ! MA ) return ( FALSE ); FreeMemAction(MA->Prev); FreeMemAction(MA->Next); FreeMemAction(MA->Related); if ( MA->FileName ) free (MA->FileName); free( MA ); return ( TRUE ); } BOOL InitMemoryWatch() { UINT Index; MemorySegments = NULL; return ( TRUE ); } static BOOL __s_isascii( char ch ) { if ( (ch>='A')&&(ch<='Z')) return ( TRUE ); if ( (ch>='a')&&(ch<='z')) return ( TRUE ); if ( (ch>='0')&&(ch<='9')) return ( TRUE ); return ( FALSE ); } BOOL PrintUnfreed(void *data, UINT Size) { UINT32 *p32; UINT16 *p16; UINT Index; char *pc; switch ( Size ) { case 2: p16 = (UINT16*) data; fprintf(stderr, "%4.4 / %d ",*p16,*p16); break; case 4: p32 = (UINT32*) data; fprintf(stderr, "%8.8x / %d ",*p32,*p32); break; } Index = 0; pc = (char*)data; while ( Index < Size ) { if ( Index > 50 ) break; if(__s_isascii(*pc)) fprintf(stderr, "%2.2x(%c),", *pc, *pc); else fprintf(stderr, "%2.2x(.),", *pc); ++pc; ++Index; } fprintf(stderr, "\n"); return ( TRUE ); } BOOL CloseMemoryWatch() { UINT Index; UINT Count; MemAction *MA; Index = 0; Count = 0; MA = MemorySegments; while ( MA ) { fprintf (stderr, "%s/%d Memory : %8.8x Size : %8.8x : %d Not Freed\n", MA->FileName, MA->LineNumber, MA->vptr, MA->MemSize); fflush ( stderr ); PrintUnfreed(MA->vptr, MA->MemSize); MA = MA->Next; ++Count; } FreeMemAction(MemorySegments); return ( Count ); } BOOL RegisterMemory (size_t Size, void *vptr) { UINT Index; MemAction *MA; MA = CreateMemAction(TempFileName, TempLineNumber, 1, Size, vptr); MA->Next = MemorySegments; if (MemorySegments) MemorySegments->Prev = MA; MemorySegments = MA; return ( FALSE ); } BOOL UnRegisterMemory ( void *vptr ) { UINT Index; MemAction *MA; MA = MemorySegments; while ( MA ) { if ( MA->vptr == vptr ) { if ( MemorySegments == MA ) MemorySegments = MA->Next; if ( MA->Prev ) MA->Prev->Next = MA->Next; if ( MA->Next ) MA->Next->Prev = MA->Prev; MA->Next = MA->Prev = NULL; FreeMemAction(MA); return ( TRUE ); } MA = MA->Next; } return ( FALSE ); } #undef new #undef delete void * operator new(size_t x) { void *vptr; if ( ! x ) { fprintf(stderr, "Attempt to allocate zero length block in %s/%d\n", TempFileName, TempLineNumber); return ( NULL ); } vptr = malloc(x); RegisterMemory (x, vptr); return ( vptr ); } void operator delete ( void *vptr ) { if ( ! vptr ) { fprintf(stderr, "Attempt to delete NULL pointer %s/%d\n", TempFileName, TempLineNumber); return; } if (!UnRegisterMemory(vptr)) { fprintf(stderr, "Possible Duplicate Delete in File: %s Line %d vptr=%x\n", TempFileName, TempLineNumber, vptr); } free(vptr); } int snew( char *file, int line) { strcpy(TempFileName, file); TempLineNumber = line; return(0); // make the else part go.. } int sdelete ( char *file, int line ) { strcpy(TempFileName, file); TempLineNumber = line; return(0); // make the else part go.. } #endif
20.262963
77
0.595504
theorose49
e2abd3e067035ea7c9ffd7dd2a3b4bafac9ff8a2
3,465
hpp
C++
Sources/DSPHeaders/include/DSPHeaders/SampleBuffer.hpp
bradhowes/AUv3Support
828258715de2144914ef08434a9db78ca62b5484
[ "MIT" ]
1
2022-03-15T04:54:16.000Z
2022-03-15T04:54:16.000Z
Sources/DSPHeaders/include/DSPHeaders/SampleBuffer.hpp
bradhowes/AUv3Support
828258715de2144914ef08434a9db78ca62b5484
[ "MIT" ]
null
null
null
Sources/DSPHeaders/include/DSPHeaders/SampleBuffer.hpp
bradhowes/AUv3Support
828258715de2144914ef08434a9db78ca62b5484
[ "MIT" ]
null
null
null
// Copyright © 2021 Brad Howes. All rights reserved. #pragma once #import <string> #import <os/log.h> #import <AudioToolbox/AudioToolbox.h> #import <AudioUnit/AudioUnit.h> #import <AVFoundation/AVFoundation.h> #import "DSPHeaders/BufferFacet.hpp" namespace DSPHeaders { /** Maintains a buffer of PCM samples which can be used to save samples from an upstream node. Internally uses an `AVAudioPCMBuffer` to deal with specifics involving the audio format. */ struct SampleBuffer { SampleBuffer() noexcept {} /** Set the format of the buffer to use. @param format the format of the samples @param maxFrames the maximum number of frames to be found in the upstream output */ void allocate(AVAudioFormat* format, AUAudioFrameCount maxFrames) noexcept { maxFramesToRender_ = maxFrames; buffer_ = [[AVAudioPCMBuffer alloc] initWithPCMFormat: format frameCapacity: maxFrames]; mutableAudioBufferList_ = buffer_.mutableAudioBufferList; } /** Forget any allocated buffer. */ void release() { if (buffer_ == nullptr) { throw std::runtime_error("buffer_ == nullptr"); } buffer_ = nullptr; mutableAudioBufferList_ = nullptr; } /** Obtain samples from an upstream node. Output is stored in internal buffer. @param actionFlags render flags from the host @param timestamp the current transport time of the samples @param frameCount the number of frames to process @param inputBusNumber the bus to pull from @param pullInputBlock the function to call to do the pulling */ AUAudioUnitStatus pullInput(AudioUnitRenderActionFlags* actionFlags, AudioTimeStamp const* timestamp, AVAudioFrameCount frameCount, NSInteger inputBusNumber, AURenderPullInputBlock pullInputBlock) noexcept { if (pullInputBlock == nullptr) { return kAudioUnitErr_NoConnection; } if (frameCount > maxFramesToRender_) { return kAudioUnitErr_TooManyFramesToProcess; } setFrameCount(frameCount); auto status = pullInputBlock(actionFlags, timestamp, frameCount, inputBusNumber, mutableAudioBufferList_); return status; } /** Update the buffer to reflect that has or will hold frameCount frames. NOTE: this value must be <= max value given in the `allocate` method. @param frameCount the number of frames to expect to place in the buffer */ void setFrameCount(AVAudioFrameCount frameCount) noexcept { assert(frameCount <= maxFramesToRender_ && mutableAudioBufferList_ != nullptr); UInt32 byteSize = frameCount * sizeof(AUValue); for (UInt32 channel = 0; channel < mutableAudioBufferList_->mNumberBuffers; ++channel) { mutableAudioBufferList_->mBuffers[channel].mDataByteSize = byteSize; } } /// Obtain the maximum size of the input buffer AUAudioFrameCount capacity() const noexcept { return maxFramesToRender_; } /// Obtain a mutable version of the internal AudioBufferList. AudioBufferList* mutableAudioBufferList() const noexcept { return mutableAudioBufferList_; } /// Obtain the number of channels in the buffer size_t channelCount() const noexcept { return mutableAudioBufferList_ != nullptr ? mutableAudioBufferList_->mNumberBuffers : 0; } private: AUAudioFrameCount maxFramesToRender_; AVAudioPCMBuffer* buffer_{nullptr}; AudioBufferList* mutableAudioBufferList_{nullptr}; }; } // end namespace DSPHeaders
31.788991
119
0.730447
bradhowes
e2add83da5f3ee4ff9a541f3af4de11074dd6d8c
1,931
cpp
C++
files/source/mischacks.cpp
Luminyx1/NewerSMBU
66c719b0afab0c5db5e26b8114d3fc02c15c7300
[ "MIT" ]
7
2021-05-22T21:59:42.000Z
2022-01-03T16:33:03.000Z
files/source/mischacks.cpp
Luminyx1/NewerSMBU
66c719b0afab0c5db5e26b8114d3fc02c15c7300
[ "MIT" ]
null
null
null
files/source/mischacks.cpp
Luminyx1/NewerSMBU
66c719b0afab0c5db5e26b8114d3fc02c15c7300
[ "MIT" ]
2
2021-05-24T03:38:18.000Z
2021-08-12T01:25:36.000Z
#include "game.h" #include "neweru.h" #include "zlib.h" void *allocZlib(void *opaque, uInt items, uInt size) { return ((sead::Heap *)opaque)->tryAlloc(items * size, 2); } void freeZlib(void *opaque, void *address) { ((sead::Heap *)opaque)->free(address); } int decompZlib(Byte *outPtr, u32 outSize, Byte *inPtr, u32 inSize, sead::Heap *heap) { if (*(u32 *)inPtr != 0x5A6C6962) { //"Zlib" return sead::SZSDecompressor::decomp(outPtr, outSize, inPtr, inSize); } int decompSize = sead::SZSDecompressor::getDecompSize(inPtr); if (outSize < decompSize) return -2; z_stream stream; //I don't think this is the right way to clear it __gh_memclr32(&stream, 14); stream.opaque = heap; stream.zalloc = &allocZlib; stream.zfree = &freeZlib; inflateInit2(&stream, 15); stream.next_in = inPtr + 12; stream.avail_in = inSize - 12; stream.next_out = outPtr; stream.avail_out = outSize; inflate(&stream, Z_FINISH); inflateEnd(&stream); return decompSize; } float getWrappedYPos(float ypos) { //Reading the wrap flag can be done more efficiently //by adding another field to the AreaTask class LevelArea *area = Level::instance->getArea(LevelInfo::instance->area); AreaSettings *settings = (AreaSettings *)area->blockPtrs[LevelArea::AreaSettings]; if (settings->flags & 2) { float top = AreaTask::instance->zoneRect.top; float bottom = AreaTask::instance->zoneRect.bottom - 32; float height = top - bottom; while (ypos > top) { ypos -= height; } while (ypos < bottom) { ypos += height; } } return ypos; } u16 getWrappedYPos(u16 ypos) { return -getWrappedYPos(-(float)ypos); } void doVerticalWrap(StageActor *actor) { float wrappedPos = getWrappedYPos(actor->position3.Y); float wrappedDiff = actor->position3.Y - wrappedPos; actor->position.Y = wrappedPos; if (wrappedDiff > 0.0001 || wrappedDiff < -0.0001) { //A wrap occurred actor->position2.Y += wrappedDiff; } }
25.746667
86
0.695495
Luminyx1
e2af83b20b9544095709d083018acc3f1af13b0d
3,410
cpp
C++
src/main.cpp
huckor/BER_TLV
e7ccc1981368ac5f1f5bdcd6fa6f04e5c6ff049f
[ "MIT" ]
2
2017-03-15T18:05:18.000Z
2021-05-14T05:16:46.000Z
src/main.cpp
huckor/BER_TLV
e7ccc1981368ac5f1f5bdcd6fa6f04e5c6ff049f
[ "MIT" ]
1
2017-03-15T18:37:26.000Z
2017-03-20T14:19:08.000Z
src/main.cpp
huckor/BER_TLV
e7ccc1981368ac5f1f5bdcd6fa6f04e5c6ff049f
[ "MIT" ]
null
null
null
#include <iostream> #include "BerTlv.h" #include "Conv.h" #include "Global.h" #include <sys/time.h> //Add to vector starting byte of 2 bytes long tags std::vector<std::string> GetTwoBytesTags() { std::vector<std::string> Return; Return.push_back("9F"); Return.push_back("5F"); Return.push_back("BF"); Return.push_back("7F"); Return.push_back("DF"); Return.push_back("FF"); return Return; } //Add to vector first and second byte of 3 bytes long tags std::vector<std::string> GetThreeBytesTags() { std::vector<std::string> Return; Return.push_back("DF81"); Return.push_back("FF81"); return Return; } //Add to vector first and second and third byte of 4 bytes long tags std::vector<std::string> GetFourBytesTags() { std::vector<std::string> Return; Return.push_back("DF8281"); Return.push_back("FF8281"); return Return; } //Add to vector nested tags (tags which can contains additional TLV) std::vector<std::string> GetNestedTags() { std::vector<std::string> Return; Return.push_back("FF8105"); Return.push_back("E1"); return Return; } int main(int argc, const char * argv[]) { BerTlv Tlv; std::vector<unsigned char> Value; std::string Tag; std::string Output; //Setup TLV engine - THIS IS ALFA & OMEGA because withot knowing of which tags //are 2, 3 and 4 bytes long this engine won't working Tlv.SetTwoBytesTags(GetTwoBytesTags()); Tlv.SetThreeBytesTags(GetThreeBytesTags()); Tlv.SetFourBytesTags(GetFourBytesTags()); //OPTIONAL - set nested tags (tags which can contains TVL) Tlv.SetNestedTags(GetNestedTags()); //Example how to add tags and values to TLV Tlv.Add("9F40", Conv::AsciiToBin("31323334353637")); Tlv.Add("FF30", Conv::AsciiToBin("31323334353637")); Tlv.Add("1F", Conv::AsciiToBin("31323334353637")); Tlv.Add("81", Conv::AsciiToBin("31323334353637")); Tlv.Add("5A", Conv::AsciiToBin("31323334353637")); Tlv.Add("DF8126", Conv::AsciiToBin("31323334353637")); //Retrieval of created TLV collection std::cout << "Created TLV struct:\n"; std::cout << Conv::BinToAscii(Tlv.GetTlv()); //Clear TLV collection Tlv.GetTlv().clear(); //Add example TLV collection Tlv.SetTlv(Conv::AsciiToBin("9f1a020764FF81050E9f1a0207649f02060000000010009f02060000000010005f2a0207649a031612209c0100950500000000009f37040095055b820220009f2608ab07b02018d87dc89f2701409f100706010a039000009f360200069f6604320040009f03060000000000009f34031f00009f45009f4c0200065a0847617390010100105f3401045f2403221231500b564953412043524544495456009b0200005f201741445654205156534443205445535420434152442030345f28009f07009f0d009f0e009f0f009f51009f3901079f33030068c01f1901089f42008407a00000000310109f5d009f6c0210009f74009f12104361727465204465204372656469746f5f2d009f0607a00000000310105f25009f21031714228f01929f1e082d3433332d313930")); std::cout << "\n\nTLV struct:\n"; std::cout << Conv::BinToAscii(Tlv.GetTlv()); //Retrieve value of tag Tag = "9F02"; if(Tlv.GetValue(Tag, &Value, true) == OK) { std::cout << "\n\nValue of tag: " + Tag + "\n"; std::cout << Conv::BinToAscii(Value); } std::cout << "\n\n"; //Dump from TLV collection Tlv.DumpAllTagsAndValues(&Output, true); std::cout << Output; return 0; }
31.574074
633
0.695894
huckor
e2afc92603892aba5b80fe3a791e2afd512a9104
3,089
hpp
C++
tuple/apply.hpp
5cript/mpl14
4c6da6b8bce1f57b0df8c4ef456fe03a61982cad
[ "MIT" ]
null
null
null
tuple/apply.hpp
5cript/mpl14
4c6da6b8bce1f57b0df8c4ef456fe03a61982cad
[ "MIT" ]
null
null
null
tuple/apply.hpp
5cript/mpl14
4c6da6b8bce1f57b0df8c4ef456fe03a61982cad
[ "MIT" ]
null
null
null
#ifndef MPLEX_TUPLE_APPLY_HPP_INCLUDED #define MPLEX_TUPLE_APPLY_HPP_INCLUDED #include <utility> #include "back.hpp" #include "front.hpp" #include "pop_back.hpp" #include "pop_front.hpp" // Can be used to apply tuples as parameters to variadic templates. namespace mplex { /** @param Tuple A tuple. * @param Function A variadic template receiving the elements of "Tuple" as parameters. * * @return basically Function<TupleElements...>. */ template <typename Tuple, template <typename...> class Function> struct apply { }; template <template <typename...> class Function, typename... List> struct apply <std::tuple <List...>, Function> { using type = Function <List...>; }; template <typename Tuple, template <typename...> class Function> using apply_t = typename apply <Tuple, Function>::type; struct apply_a { template <typename Tuple, template <typename...> class Function> struct apply {}; }; template <typename... List, template <typename...> class Function> struct apply_a::apply <std::tuple <List...>, Function> { using type = Function <List...>; }; template <typename ValueT, typename Sequence, template <ValueT...> class Function> struct apply_values { static_assert(std::is_same_v<Sequence,Sequence>, "Could not apply specialization with std::integer_sequence"); }; template <typename ValueT, template <ValueT...> class Function, ValueT... List> struct apply_values <ValueT, std::integer_sequence <ValueT, List...>, Function> { using type = Function <List...>; }; struct apply_values_a { template <typename ValueT, typename Sequence, template <ValueT...> class Function> struct apply {}; }; template <typename ValueT, template <ValueT...> class Function, ValueT... List> struct apply_values_a::apply <ValueT, std::integer_sequence <ValueT, List...>, Function> { using type = Function <List...>; }; struct apply_af { template <typename Tuple, typename Functor> struct apply {}; }; template <typename... List, typename Functor> struct apply_af::apply <std::tuple <List...>, Functor> { using type = typename Functor::template apply <List...>; }; // APPLY_REVERSE template <typename Tuple, template <typename...> class Function, typename... AccumList> struct apply_reverse { using type = typename apply_reverse <pop_back_t <Tuple>, Function, back_t <Tuple>, AccumList...>::type; }; template <template <typename...> class Function, typename... AccumList> struct apply_reverse <std::tuple <>, Function, AccumList...> { using type = Function <AccumList...>; }; template <typename Tuple, template <typename...> class Function, typename... AccumList> using apply_reverse_t = typename apply_reverse <Tuple, Function, AccumList...>::type; } #endif // MPLEX_TUPLE_APPLY_HPP_INCLUDED
34.322222
119
0.64066
5cript
e2b4da49f111abc7c299c97f5772b5396271244e
1,914
cpp
C++
src/day2.cpp
ajpocus/advent-of-code-2020
1252a723c82efd37ce19a174843db04b81d2eae7
[ "CC-BY-4.0" ]
1
2021-04-10T05:49:05.000Z
2021-04-10T05:49:05.000Z
src/day2.cpp
ajpocus/advent-of-code-2020
1252a723c82efd37ce19a174843db04b81d2eae7
[ "CC-BY-4.0" ]
null
null
null
src/day2.cpp
ajpocus/advent-of-code-2020
1252a723c82efd37ce19a174843db04b81d2eae7
[ "CC-BY-4.0" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <regex> using namespace std; regex parser_regex("(\\d+)-(\\d+) (\\w): (\\w+)"); int count_passwords(vector<string> input) { int cnt = 0; for (string line: input) { smatch matches; regex_match(line, matches, parser_regex); int lower_bound = stoi(matches[1]); int upper_bound = stoi(matches[2]); string chr = matches[3]; string pass = matches[4]; size_t char_count = count(pass.begin(), pass.end(), chr[0]); if (char_count >= lower_bound && char_count <= upper_bound) { ++cnt; } } return cnt; } int valid_pass_chars(vector<string> input) { int cnt = 0; for (string line: input) { smatch matches; regex_match(line, matches, parser_regex); int idx1 = stoi(matches[1]) - 1; int idx2 = stoi(matches[2]) - 1; string chr_str = matches[3]; char chr = chr_str[0]; string pass = matches[4]; char first_char = pass[idx1]; char other_char = pass[idx2]; if (!(first_char == chr && other_char == chr) && ((first_char == chr && other_char != chr) || (first_char != chr && other_char == chr))) { ++cnt; } } return cnt; } int main() { vector<string> test_input_vec; test_input_vec.push_back("1-3 a: abcde"); test_input_vec.push_back("1-3 b: cdefg"); test_input_vec.push_back("2-9 c: ccccccccc"); int test_count = count_passwords(test_input_vec); assert(test_count == 2); ifstream input_file; input_file.open("input/day2.txt", ios::in); // get input string line; vector<string> input; while (getline(input_file, line)) { input.push_back(line); } int valid_count = count_passwords(input); cout << valid_count << "\n"; int test_valid_count = valid_pass_chars(test_input_vec); assert(test_valid_count == 1); int new_valid_count = valid_pass_chars(input); cout << new_valid_count << "\n"; return 0; }
23.341463
142
0.640543
ajpocus
e2bbd2131fa29795e20dfc5fb57d095031751bc7
15,341
cpp
C++
material_io.cpp
2-tuple/Engine
5bae92a379caafa93db912802a3790305c8b85d3
[ "MIT" ]
1
2019-06-20T21:44:19.000Z
2019-06-20T21:44:19.000Z
material_io.cpp
2-tuple/Engine
5bae92a379caafa93db912802a3790305c8b85d3
[ "MIT" ]
null
null
null
material_io.cpp
2-tuple/Engine
5bae92a379caafa93db912802a3790305c8b85d3
[ "MIT" ]
null
null
null
#include "material_io.h" #include "file_io.h" #include "shader_def.h" #include "stack_alloc.h" #include "shader_def.h" #include "profile.h" #include <stdio.h> #include <string.h> int32_t GetLine(char** Line, int* LineLength, char* CharArray, int ArraySize, int* CharCounter) { *Line = &CharArray[*CharCounter]; *LineLength = 0; while((CharArray[*CharCounter] != '\n') /*&& (CharArray[*CharCounter] != '\0')*/) { ++(*LineLength); ++(*CharCounter); if(*CharCounter >= ArraySize) { //*Line = NULL; //*LineLength = -1; return -1; } } ++(*CharCounter); return *LineLength; } material ImportPhongMaterial_Deprecated(debug_read_file_result FileData, Resource::resource_manager* Resources) { material Material = {}; Material.Common.ShaderType = SHADER_Phong; bool LoadingMaterial = false; int CharCounter = 0; char* Line = NULL; int LineLength = 0; while(GetLine(&Line, &LineLength, (char*)FileData.Contents, FileData.ContentsSize, &CharCounter) != -1) { int Offset = 0; rid RID; while((Line[Offset] == ' ') || (Line[Offset] == '\t')) { ++Offset; } if(Offset + 2 <= LineLength) { if((Line[Offset] == 'N') && (Line[Offset + 1] == 's')) { Offset += strlen("Ns"); sscanf(&Line[Offset], " %f", &Material.Phong.Shininess); continue; } else if((Line[Offset] == 'K') && (Line[Offset + 1] == 'a')) { Offset += strlen("Ka"); sscanf(&Line[Offset], " %f %f %f", &Material.Phong.AmbientColor.R, &Material.Phong.AmbientColor.G, &Material.Phong.AmbientColor.B); continue; } else if((Line[Offset] == 'K') && (Line[Offset + 1] == 'd')) { Offset += strlen("Kd"); sscanf(&Line[Offset], " %f %f %f", &Material.Phong.DiffuseColor.R, &Material.Phong.DiffuseColor.G, &Material.Phong.DiffuseColor.B); continue; } else if((Line[Offset] == 'K') && (Line[Offset + 1] == 's')) { Offset += strlen("Ks"); sscanf(&Line[Offset], " %f %f %f", &Material.Phong.SpecularColor.R, &Material.Phong.SpecularColor.G, &Material.Phong.SpecularColor.B); continue; } else if(Line[Offset] == 'd') { Offset += strlen("d"); sscanf(&Line[Offset], " %f", &Material.Phong.DiffuseColor.A); continue; } } if(Offset + 5 <= LineLength) { if(strncmp(&Line[Offset], "blend", strlen("blend")) == 0) { Material.Common.UseBlending = true; continue; } } if(Offset + 6 <= LineLength) { if(strncmp(&Line[Offset], "newmtl", strlen("newmtl")) == 0) { assert((!LoadingMaterial) && "There can be only one material in single file!\n"); Offset += strlen("newmtl"); LoadingMaterial = true; continue; } else if(strncmp(&Line[Offset], "map_Kd", strlen("map_Kd")) == 0) { Material.Phong.Flags |= PHONG_UseDiffuseMap; Offset += strlen("map_Kd"); while((Line[Offset] == ' ') || (Line[Offset] == '\t')) { ++Offset; } if(Offset >= LineLength) { printf("Line\n%s contains no path\n", Line); assert(0); } path Path = {}; size_t PathLength = strcspn(&Line[Offset], " \t\n"); if(PathLength >= PATH_MAX_LENGTH) { printf("Path in line\n%sis too long\n", Line); } assert(PathLength < PATH_MAX_LENGTH); strncpy(Path.Name, &Line[Offset], PathLength); Path.Name[PathLength] = '\0'; if(Resources->GetTexturePathRID(&RID, Path.Name)) { Material.Phong.DiffuseMapID = RID; } else { Material.Phong.DiffuseMapID = Resources->RegisterTexture(Path.Name); } continue; } else if(strncmp(&Line[Offset], "map_Ks", strlen("map_Ks")) == 0) { Material.Phong.Flags |= PHONG_UseSpecularMap; Offset += strlen("map_Ks"); while((Line[Offset] == ' ') || (Line[Offset] == '\t')) { ++Offset; } if(Offset >= LineLength) { printf("Line\n%s contains no path\n", Line); assert(0); } path Path; size_t PathLength = strcspn(&Line[Offset], " \t\n"); if(PATH_MAX_LENGTH <= PathLength) { printf("Path in line\n%sis too long\n", Line); } assert(PathLength < PATH_MAX_LENGTH); strncpy(Path.Name, &Line[Offset], PathLength); Path.Name[PathLength] = '\0'; if(Resources->GetTexturePathRID(&RID, Path.Name)) { Material.Phong.SpecularMapID = RID; } else { Material.Phong.SpecularMapID = Resources->RegisterTexture(Path.Name); } continue; } } if(Offset + 7 <= LineLength) { if(strncmp(&Line[Offset], "skeletal", strlen("skeletal")) == 0) { Material.Common.IsSkeletal = true; Material.Phong.Flags |= PHONG_UseSkeleton; continue; } } if(Offset + 9 <= LineLength) { if(strncmp(&Line[Offset], "map_normal", strlen("map_normal")) == 0) { Material.Phong.Flags |= PHONG_UseNormalMap; Offset += strlen("map_normal"); while((Line[Offset] == ' ') || (Line[Offset] == '\t')) { ++Offset; } if(Offset >= LineLength) { printf("Line\n%s contains no path\n", Line); assert(0); } path Path; size_t PathLength = strcspn(&Line[Offset], " \t\n"); if(PATH_MAX_LENGTH <= PathLength) { printf("Path in line\n%sis too long\n", Line); } assert(PathLength < PATH_MAX_LENGTH); strncpy(Path.Name, &Line[Offset], PathLength); Path.Name[PathLength] = '\0'; if(Resources->GetTexturePathRID(&RID, Path.Name)) { Material.Phong.NormalMapID = RID; } else { Material.Phong.NormalMapID = Resources->RegisterTexture(Path.Name); } } continue; } Line = NULL; LineLength = 0; } return Material; } material ImportMaterial(Memory::stack_allocator* Allocator, Resource::resource_manager* Resources, const char* Path) { BEGIN_TIMED_BLOCK(LoadMaterial); // Make sure file extension is correct if(strlen(Path) <= strlen(".mat")) { printf("%s is not a .mat file!\n", Path); assert(0); } else if(!strcmp(&Path[strlen(Path) - strlen(".mat") - 1], ".mat")) { printf("%s is not a .mat file!\n", Path); assert(0); } // Read File Into Memory debug_read_file_result FileData = Platform::ReadEntireFile(Allocator, Path); if(FileData.ContentsSize <= 0) { printf("File %s is empty!\n", Path); assert(FileData.ContentsSize > 0); } char* Line = NULL; int LineLength = 0; int CharCounter = 0; material Material = {}; Material.Common.ShaderType = -1; struct shader_def* ShaderDefinition = NULL; char LineBuffer[100]; // Checking if file not empty if(GetLine(&Line, &LineLength, (char*)FileData.Contents, FileData.ContentsSize, &CharCounter) != -1) { const char* TypeParamString = "type: "; const size_t TypeParamStringLength = strlen(TypeParamString); if(LineLength >= TypeParamStringLength && strncmp(TypeParamString, Line, TypeParamStringLength) == 0) { const char* const ShaderNameStart = Line + TypeParamStringLength; size_t ShaderNameStringLength = LineLength - TypeParamStringLength; strncpy(LineBuffer, ShaderNameStart, ShaderNameStringLength); LineBuffer[ShaderNameStringLength] = '\0'; assert(GetShaderDef(&ShaderDefinition, LineBuffer)); Material.Common.ShaderType = GetShaderType(ShaderDefinition); assert(0 <= Material.Common.ShaderType); } else { // USING OLD IMPORTER IF FAILED TO FIND "type: " field Material = ImportPhongMaterial_Deprecated(FileData, Resources); } } // Parse with shader def available while(ShaderDefinition && GetLine(&Line, &LineLength, (char*)FileData.Contents, FileData.ContentsSize, &CharCounter) != -1) { path ParamName; sscanf(Line, "%[^:]: ", (char*)ParamName.Name); const char* RestOfLine = Line + strlen(ParamName.Name) + strlen(": "); shader_param_def ParamDef = {}; assert(GetShaderParamDef(&ParamDef, ShaderDefinition, ParamName.Name)); uint8_t* ParamLocation = (((uint8_t*)&Material) + ParamDef.OffsetIntoMaterial); switch(ParamDef.Type) { case SHADER_PARAM_TYPE_Int: { int32_t Value; assert(sscanf(RestOfLine, "%d", &Value) == 1); *((int32_t*)ParamLocation) = Value; } break; case SHADER_PARAM_TYPE_Bool: { int32_t Value; assert(sscanf(RestOfLine, "%d", &Value) == 1); *((bool*)ParamLocation) = (bool)Value; } break; case SHADER_PARAM_TYPE_Float: { float Value; assert(sscanf(RestOfLine, "%f", &Value) == 1); *((float*)ParamLocation) = Value; } break; case SHADER_PARAM_TYPE_Vec3: { vec3 Value; assert(sscanf(RestOfLine, "%f %f %f", &Value.X, &Value.Y, &Value.Z) == 3); *((vec3*)ParamLocation) = Value; } break; case SHADER_PARAM_TYPE_Vec4: { vec4 Value; assert(sscanf(RestOfLine, "%f %f %f %f", &Value.X, &Value.Y, &Value.Z, &Value.W) == 4); *((vec4*)ParamLocation) = Value; } break; case SHADER_PARAM_TYPE_Map: { rid RID; path Path = {}; size_t PathLength = strcspn(RestOfLine, " \t\n"); if(PATH_MAX_LENGTH <= PathLength) { printf("Path in line\n%sis too long\n", Line); } assert(PathLength < PATH_MAX_LENGTH); strncpy(Path.Name, RestOfLine, PathLength); Path.Name[PathLength] = '\0'; if(Resources->GetTexturePathRID(&RID, Path.Name)) { *((rid*)ParamLocation) = RID; } else { *((rid*)ParamLocation) = Resources->RegisterTexture(Path.Name); } } break; } } assert(Material.Common.ShaderType >= 0); END_TIMED_BLOCK(LoadMaterial); return Material; } void ExportPhongMaterial(Resource::resource_manager* ResourceManager, const material* Material, const char* Path) { assert(Path); assert(strncmp("data/materials/", Path, strlen("data/materials/")) == 0); char FileName[30]; FILE* FilePointer = fopen(Path, "w"); fprintf(FilePointer, "newmtl %s\n", Path + strlen("data/materials/")); if(Material->Common.ShaderType == SHADER_Phong) { fprintf(FilePointer, "\tNs %f\n", Material->Phong.Shininess); fprintf(FilePointer, "\tNi %f\n", 1.0f); fprintf(FilePointer, "\tKa %f %f %f\n", Material->Phong.AmbientColor.R, Material->Phong.AmbientColor.G, Material->Phong.AmbientColor.B); fprintf(FilePointer, "\tKd %f %f %f\n", Material->Phong.DiffuseColor.R, Material->Phong.DiffuseColor.G, Material->Phong.DiffuseColor.B); fprintf(FilePointer, "\tKs %f %f %f\n", Material->Phong.SpecularColor.R, Material->Phong.SpecularColor.G, Material->Phong.SpecularColor.B); fprintf(FilePointer, "\td %f\n", Material->Phong.DiffuseColor.A); if(Material->Phong.Common.IsSkeletal) { fprintf(FilePointer, "\tskeletal\n"); } if(Material->Phong.Common.UseBlending) { fprintf(FilePointer, "\tblend\n"); } if(Material->Phong.Flags & PHONG_UseDiffuseMap) { fprintf(FilePointer, "\tmap_Kd %s\n", ResourceManager ->TexturePaths[ResourceManager->GetTexturePathIndex(Material->Phong.DiffuseMapID)] .Name); } if(Material->Phong.Flags & PHONG_UseSpecularMap) { fprintf(FilePointer, "\tmap_Ks %s\n", ResourceManager ->TexturePaths[ResourceManager->GetTexturePathIndex(Material->Phong.SpecularMapID)] .Name); } if(Material->Phong.Flags & PHONG_UseNormalMap) { fprintf(FilePointer, "\tmap_normal %s\n", ResourceManager ->TexturePaths[ResourceManager->GetTexturePathIndex(Material->Phong.NormalMapID)] .Name); } } else if(Material->Common.ShaderType == SHADER_Color) { fprintf(FilePointer, "\tNi %f\n", 1.0f); fprintf(FilePointer, "\tKa %f %f %f\n", Material->Color.Color.R, Material->Color.Color.G, Material->Color.Color.B); fprintf(FilePointer, "\tKd %f %f %f\n", Material->Color.Color.R, Material->Color.Color.G, Material->Color.Color.B); fprintf(FilePointer, "\tKs %f %f %f\n", 0.0f, 0.0f, 0.0f); fprintf(FilePointer, "\td %f\n", Material->Color.Color.A); } fprintf(FilePointer, "\n"); fclose(FilePointer); } void ExportMaterial(Resource::resource_manager* ResourceManager, const material* Material, const char* Path) { assert(Path); assert(strncmp("data/materials/", Path, strlen("data/materials/")) == 0); #define PHONG_IS_SPECIAL_SNOWFLAKE 1 #if PHONG_IS_SPECIAL_SNOWFLAKE if(Material->Common.ShaderType == SHADER_Phong) { ExportPhongMaterial(ResourceManager, Material, Path); return; } #endif struct shader_def* ShaderDef; assert(GetShaderDef(&ShaderDef, Material->Common.ShaderType)); const char* ShaderName = GetShaderName(ShaderDef); FILE* FilePointer = fopen(Path, "w"); fprintf(FilePointer, "type: %s\n", ShaderName); ResetShaderDefIterator(ShaderDef); named_shader_param_def ParamDef = {}; while(GetNextShaderParam(&ParamDef, ShaderDef)) { fprintf(FilePointer, "%s: ", ParamDef.Name); uint8_t* ParamLocation = (((uint8_t*)Material) + ParamDef.OffsetIntoMaterial); switch(ParamDef.Type) { case SHADER_PARAM_TYPE_Int: { int32_t Value = *((int32_t*)ParamLocation); fprintf(FilePointer, "%d\n", Value); } break; case SHADER_PARAM_TYPE_Bool: { bool Value = *((bool*)ParamLocation); fprintf(FilePointer, "%d\n", (int32_t)Value); } break; case SHADER_PARAM_TYPE_Float: { float Value = *((float*)ParamLocation); fprintf(FilePointer, "%.3f\n", Value); } break; case SHADER_PARAM_TYPE_Vec3: { vec3 Value = *((vec3*)ParamLocation); fprintf(FilePointer, "%.3f %.3f %.3f\n", Value.X, Value.Y, Value.Z); } break; case SHADER_PARAM_TYPE_Vec4: { vec4 Value = *((vec4*)ParamLocation); fprintf(FilePointer, "%.3f %.3f %.3f %.3f\n", Value.X, Value.Y, Value.Z, Value.W); } break; case SHADER_PARAM_TYPE_Map: { rid RIDValue = *((rid*)ParamLocation); fprintf(FilePointer, "%s\n", ResourceManager->TexturePaths[ResourceManager->GetTexturePathIndex(RIDValue)].Name); } break; } } fclose(FilePointer); }
28.728464
100
0.57656
2-tuple
e2be1b56d969615e5fe024dd6b2aa53d3114230b
558
cpp
C++
EJERCICIOS/EJERCICIO C++/ejercicio34-nombre completo.cpp
dianaM182/cpp
45b0e688b00f5a6f4483aba13904b5d760806726
[ "MIT" ]
null
null
null
EJERCICIOS/EJERCICIO C++/ejercicio34-nombre completo.cpp
dianaM182/cpp
45b0e688b00f5a6f4483aba13904b5d760806726
[ "MIT" ]
null
null
null
EJERCICIOS/EJERCICIO C++/ejercicio34-nombre completo.cpp
dianaM182/cpp
45b0e688b00f5a6f4483aba13904b5d760806726
[ "MIT" ]
null
null
null
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; string nombrecompleto(string nombre, string apellido){ return nombre+apellido; } int main(int argc, char** argv) { string primernombre=" "; string primerapellido=" "; cout<<"Ingrese su primer nombre:"; cin>>primernombre; cout<<"Ingrese su primer apellido:"; cin>>primerapellido; cout<<endl; cout<<"nombre completo:"<<nombrecompleto(primernombre,primerapellido); return 0; }
25.363636
101
0.697133
dianaM182
e2ca2e50fa5d2828ef6489287119592c8664b1fa
2,395
cpp
C++
src/game/projectile/laser.cpp
runouw/Starfox-School-Project
5645f76ecf4f642080c08b594531ab3072879827
[ "Apache-2.0" ]
1
2017-06-30T00:28:31.000Z
2017-06-30T00:28:31.000Z
src/game/projectile/laser.cpp
runouw/Starfox-School-Project
5645f76ecf4f642080c08b594531ab3072879827
[ "Apache-2.0" ]
null
null
null
src/game/projectile/laser.cpp
runouw/Starfox-School-Project
5645f76ecf4f642080c08b594531ab3072879827
[ "Apache-2.0" ]
null
null
null
#include "projectiles.h" #include <rtools\ai\model.h> #include <rtools\ai\mesh.h> #include <rtools\ai\material.h> #include <rtools\utils.h> #include <game\models\arwing.h> #include <rtools\post\deferred.h> #include <game\engine.h> #include <game\particle\particlebank.h> #include <game\models\model_laser.h> #include <vector> Laser::Laser(const GsVec p, const GsVec dir){ pos = p; this->dir = dir; vel = 260.0f; life = 0; exists = true; } void onHit(const DamageData& data, const Enemy* enemy){ Laser* laser = (Laser*)data.sender; laser->exists = false; } void Laser::idle(float dt){ pos += dir * vel * dt; life += dt; DamageData data = DamageData(1, 0, dir * .1f, this, onHit); for (float d = 0; d < 1; d += .03f){ for (size_t i = 0; i < Engine::enemies.size(); i++){ if (Engine::enemies[i]->projectileCollisionCheck(pos + dir * d * 20.0f, 1, data)) break; } } float intersection = Engine::scene->intersect(pos, pos + dir * 20.0f); if (intersection >= 0){ GLTexture* tex = Textures::get("../res/models/arwing/starfox_147_GfoxJet.bmp"); std::vector<Particle*>* list = ParticleUtils::getParticleList(Engine::particles, tex->texId); for (int i = 0; i < 25; i++){ GsVec rndvel = GsVec((float)(gs_randomd() * 2 - 1), (float)(gs_randomd() * 2 - 1), (float)(gs_randomd() * 2 - 1)); rndvel.normalize(); rndvel *= (float)(gs_randomd()*gs_randomd() * 2.0f); float rndsize = (float)(gs_randomd() * .3f) + .1f; float rndlife = (float)(gs_randomd() * gs_randomd() * 5.4f) + .2f; Particle_SimpleDecay* particle = (ParticleBank::simpleDecay[ParticleBank::simpleDecay_num++]); if (ParticleBank::simpleDecay_num >= PARTICLEBANK_NUM_SIMPLEDECAY){ ParticleBank::simpleDecay_num = 0; } particle->exists = true; particle->del = false; particle->pos = pos + intersection*dir; particle->initialSize = rndsize; particle->color = RColor(.2f, .8f, .4f, (float)gs_randomd()); particle->vel = rndvel; particle->duration = rndlife; particle->t = 0; list->push_back(particle); } exists = false; } if (life > 4){ exists = false; } } void Laser::addDraw(const GsMat& tr, const GsMat& pr){ Model_Laser::addDraw(tr, pr, RColor(0, 1, 0, 1), pos, dir * 15, .15f); } void Laser::putLights(){ DeferredUtils::addLight(Light(pos + dir*1.0f, 10 + (10.0f / (life * 10.0f + 1.0f)), RColor(0.7f, 1, 0.7f, 1))); }
24.438776
117
0.643424
runouw
e2d03f3e5dcf16aa945914d7f012edbe0cbf058e
1,980
hpp
C++
src/data/vData.hpp
danielnavarrogomez/Anaquin
563dbeb25aff15a55e4309432a967812cbfa0c98
[ "BSD-3-Clause" ]
null
null
null
src/data/vData.hpp
danielnavarrogomez/Anaquin
563dbeb25aff15a55e4309432a967812cbfa0c98
[ "BSD-3-Clause" ]
null
null
null
src/data/vData.hpp
danielnavarrogomez/Anaquin
563dbeb25aff15a55e4309432a967812cbfa0c98
[ "BSD-3-Clause" ]
null
null
null
#ifndef VCF_DATA_HPP #define VCF_DATA_HPP #include "tools/tools.hpp" //#include "data/standard.hpp" #include "parsers/parser_vcf.hpp" namespace Anaquin { typedef long VarKey; struct VDataData { std::map<Base, Variant> b2v; std::map<Variation, std::set<Variant>> m2v; }; struct VCFData : public std::map<ChrID, VDataData> { inline std::set<Variant> vars() const { std::set<Variant> x; for (const auto &i : *this) { for (const auto &j : i.second.m2v) { for (const auto &k : j.second) { x.insert(k); } } } return x; } inline const Variant * findVar(const ChrID &id, const Locus &l) { if (!count(id)) { return nullptr; } else if (at(id).b2v.count(l.start)) { return &(at(id).b2v.at(l.start)); } return nullptr; } inline Counts count_(const ChrID &cID, Variation m) const { return count(cID) && at(cID).m2v.count(m) ? at(cID).m2v.at(m).size() : 0; } inline Counts count_(Variation m) const { return countMap(*this, [&](const ChrID &cID, const VDataData &) { return count_(cID, m); }); } }; template <typename F> VCFData readVFile(const Reader &r, F f) { VCFData c2d; ParserVCF::parse(r, [&](const Variant &x) { c2d[x.cID].b2v[x.l.start] = x; c2d[x.cID].m2v[x.type()].insert(x); f(x); }); return c2d; } inline VCFData readVFile(const Reader &r) { return readVFile(r, [](const Variant &) {}); } } #endif
22.758621
85
0.441919
danielnavarrogomez
e2d4c1d5afa55aa534cd6fae29f6636e2c70e85b
38,149
cxx
C++
osprey/common/com/dwarf_DST_dump.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/common/com/dwarf_DST_dump.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/common/com/dwarf_DST_dump.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2003, 2004, 2005, 2006 PathScale, Inc. All Rights Reserved. */ /* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ #ifdef _KEEP_RCS_ID static const char source_file[] = __FILE__; static const char rcs_id[] = "$Source: common/com/SCCS/s.dwarf_DST_dump.cxx $ $Revision: 1.13 $"; #endif #include <stdio.h> #include <cmplrs/rcodes.h> #define USE_DST_INTERNALS #include "dwarf_DST.h" #include "dwarf_DST_dump.h" #include "errors.h" #define DST_DUMP_LINELENGTH 1024 #define DST_TMP_BUF_LENGTH 256 /* This truth value takes into account that we need one character * at the end of as line for " ...\n". */ #define DST_CHARS_DO_FIT(n) (n <= (DST_DUMP_LINELENGTH - next_char - 5)) static char line_buffer[DST_DUMP_LINELENGTH]; static char tmp_buffer[DST_TMP_BUF_LENGTH]; static UINT32 next_char; /* Index into line_buffer */ static FILE *dumpf = NULL; static char *dumpf_name = NULL; static BOOL end_of_line = FALSE; #define DST_ASSERT(truth, msg) Is_True(truth, (msg)) /*--------------------------------------- * Some general purpose writing routines *---------------------------------------*/ /* The current contents of the line buffer is written to file and the * next_char is again the first element in the buffer. */ static void DST_write_line(void) { size_t status; line_buffer[next_char] = '\n'; status = fwrite(line_buffer, sizeof(char), next_char + 1, dumpf); DST_ASSERT(status >= next_char, "Write error while dumping DST"); next_char = 0; end_of_line = FALSE; } static void DST_line_overflow(void) { line_buffer[next_char++] = ' '; line_buffer[next_char++] = '.'; line_buffer[next_char++] = '.'; line_buffer[next_char++] = '.'; end_of_line = TRUE; } static void DST_nput_char(size_t n, const char c) { size_t c_idx; if (!end_of_line) { if (DST_CHARS_DO_FIT(n)) { for (c_idx = 0; c_idx < n; c_idx += 1) { line_buffer[next_char + c_idx] = c; } next_char = next_char + n; } else DST_line_overflow(); } } static void DST_put_string(const char *c) { size_t length, c_idx; if (!end_of_line) { if (c != NULL) { length = strlen(c); if (DST_CHARS_DO_FIT(length)) { for (c_idx = 0; c_idx < length; c_idx += 1) { line_buffer[next_char + c_idx] = c[c_idx]; } next_char = next_char + length; } else DST_line_overflow(); } else { if (DST_CHARS_DO_FIT(2)) { line_buffer[next_char++] = '<'; line_buffer[next_char++] = '>'; } else DST_line_overflow(); } } } static void DST_put_idx(DST_IDX i) { sprintf(&tmp_buffer[0], "[%d,%d]", i.block_idx, i.byte_idx); DST_put_string(&tmp_buffer[0]); } static void DST_put_st_id (INT32 level, INT32 index) { sprintf(&tmp_buffer[0], "(%d,%d)", level, index); DST_put_string(&tmp_buffer[0]); } static void DST_put_string_attribute(const char *at_name, DST_STR_IDX istr) { if (!DST_IS_NULL(istr)) { DST_put_string(at_name); DST_nput_char(1, '('); DST_put_string(DST_STR_IDX_TO_PTR(istr)); DST_nput_char(1, ')'); } } static void DST_put_idx_attribute(const char *at_name, DST_IDX i, BOOL is_type) { if (DST_IS_FOREIGN_OBJ(i)) { DST_put_string(at_name); DST_put_string("[foreign]"); } else if (!DST_IS_NULL(i)) { DST_put_string(at_name); DST_put_idx(i); } else if (is_type) { DST_put_string(at_name); DST_put_string("(void)"); } } static void DST_put_hex64_attribute(const char *at_name, UINT64 num) { DST_put_string(at_name); sprintf(&tmp_buffer[0], "(0x%llx)", num); DST_put_string(&tmp_buffer[0]); } static void DST_put_INT32_attribute(const char *at_name, INT32 num) { DST_put_string(at_name); sprintf(&tmp_buffer[0], "(%d)", num); DST_put_string(&tmp_buffer[0]); } static void DST_put_UINT32_attribute(const char *at_name, UINT32 num) { DST_put_string(at_name); sprintf(&tmp_buffer[0], "(%u)", num); DST_put_string(&tmp_buffer[0]); } #ifdef KEY static void DST_put_C4_attribute(const char *at_name, UINT32 real, UINT32 imag) { DST_put_string(at_name); sprintf(&tmp_buffer[0], "(%u, %u)", real, imag); DST_put_string(&tmp_buffer[0]); } static void DST_put_C8_attribute(const char *at_name, UINT64 real, UINT64 imag) { DST_put_string(at_name); sprintf(&tmp_buffer[0], "(%llu, %llu)", real, imag); DST_put_string(&tmp_buffer[0]); } #endif // KEY static void DST_put_INT64_attribute(const char *at_name, INT64 num) { DST_put_string(at_name); sprintf(&tmp_buffer[0], "(%lld)", num); DST_put_string(&tmp_buffer[0]); } static void DST_put_UINT64_attribute(const char *at_name, UINT64 num) { DST_put_string(at_name); sprintf(&tmp_buffer[0], "(%llu)", num); DST_put_string(&tmp_buffer[0]); } static void DST_put_inline_attribute(const char *at_name, DST_inline inlin) { DST_put_string(at_name); DST_nput_char(1, '('); switch (inlin) { case DW_INL_not_inlined: DST_put_string ("DW_INL_not_inlined"); break; case DW_INL_inlined: DST_put_string ("DW_INL_inlined"); break; case DW_INL_declared_not_inlined: DST_put_string ("DW_INL_declared_not_inlined"); break; case DW_INL_declared_inlined: DST_put_string ("DW_INL_declared_inlined"); break; } DST_nput_char(1, ')'); } static void DST_put_virtuality_attribute(const char *at_name, DST_virtuality virtuality) { DST_put_string(at_name); DST_nput_char(1, '('); switch (virtuality) { case DW_VIRTUALITY_none: DST_put_string ("DW_VIRTUALITY_none"); break; case DW_VIRTUALITY_virtual: DST_put_string("DW_VIRTUALITY_virtual"); break; case DW_VIRTUALITY_pure_virtual: DST_put_string ("DW_VIRTUALITY_pure_virtual"); break; } DST_nput_char(1, ')'); } #ifdef KEY static void DST_put_accessibility_attribute(const char *at_name, DST_accessibility accessibility) { DST_put_string(at_name); DST_nput_char(1, '('); switch (accessibility) { case DW_ACCESS_public: DST_put_string("DW_ACCESS_public"); break; case DW_ACCESS_private: DST_put_string("DW_ACCESS_private"); break; case DW_ACCESS_protected: DST_put_string("DW_ACCESS_protected"); break; } DST_nput_char(1, ')'); } #endif static void DST_put_language_attribute(const char *at_name, DST_language lang_code) { DST_put_string(at_name); DST_nput_char(1, '('); switch (lang_code) { case DW_LANG_C89: DST_put_string("C89"); break; case DW_LANG_Ada83: DST_put_string("Ada83"); break; case DW_LANG_C_plus_plus: DST_put_string("C_plus_plus"); break; case DW_LANG_Cobol74: DST_put_string("Cobol74"); break; case DW_LANG_Cobol85: DST_put_string("Cobol85"); break; case DW_LANG_Fortran77: DST_put_string("Fortran77"); break; case DW_LANG_Fortran90: DST_put_string("Fortran90"); break; case DW_LANG_Pascal83: DST_put_string("Pascal83"); break; case DW_LANG_Modula2: DST_put_string("Modula2"); break; } DST_nput_char(1, ')'); } static void DST_put_id_case_attribute(const char *at_name, DST_identifier_case id_case) { DST_put_string(at_name); DST_nput_char(1, '('); switch (id_case) { case DW_ID_case_sensitive: DST_put_string("case_sensitive"); break; case DW_ID_up_case: DST_put_string("upper_case"); break; case DW_ID_down_case: DST_put_string("lower_case"); break; case DW_ID_case_insensitive: DST_put_string("case_insensitive"); break; } DST_nput_char(1, ')'); } static void DST_put_decl(USRCPOS decl) { DST_put_UINT32_attribute(" file", (UINT32)USRCPOS_filenum(decl)); DST_put_UINT32_attribute(" line", (UINT32)USRCPOS_linenum(decl)); DST_put_UINT32_attribute(" column", (UINT32)USRCPOS_column(decl)); } static void DST_put_assoc(const char *at_name, DST_flag flag, DST_ASSOC_INFO assoc) { DST_put_string(at_name); DST_nput_char(1, '('); { DST_put_string("ST"); DST_put_st_id (DST_ASSOC_INFO_st_level(assoc), DST_ASSOC_INFO_st_index(assoc)); } DST_nput_char(1, ')'); } static void DST_put_const_attribute(const char *at_name, DST_CONST_VALUE cval) { switch(DST_CONST_VALUE_form(cval)) { case DST_FORM_STRING: DST_put_idx_attribute(at_name, DST_CONST_VALUE_form_string(cval), FALSE); break; case DST_FORM_DATA1: DST_put_UINT32_attribute(at_name, (UINT32)DST_CONST_VALUE_form_data1(cval)); break; case DST_FORM_DATA2: DST_put_UINT32_attribute(at_name, (UINT32)DST_CONST_VALUE_form_data2(cval)); break; case DST_FORM_DATA4: DST_put_UINT32_attribute(at_name, (UINT32)DST_CONST_VALUE_form_data4(cval)); break; case DST_FORM_DATA8: DST_put_UINT64_attribute(at_name, (UINT64)DST_CONST_VALUE_form_data8(cval)); break; #ifdef KEY case DST_FORM_DATAC4: DST_put_C4_attribute(at_name, (UINT32)DST_CONST_VALUE_form_crdata4(cval), (UINT32)DST_CONST_VALUE_form_cidata4(cval)); break; case DST_FORM_DATAC8: DST_put_C8_attribute(at_name, (UINT64)DST_CONST_VALUE_form_crdata8(cval), (UINT64)DST_CONST_VALUE_form_cidata8(cval)); break; #endif // KEY } } /*---------------------------------- * One put routine for each DW_TAG *----------------------------------*/ static void DST_put_compile_unit(DST_flag flag, DST_COMPILE_UNIT *attr) { DST_put_string(":compile_unit:"); DST_put_string_attribute(" name", DST_COMPILE_UNIT_name(attr)); DST_put_string_attribute(" comp_dir", DST_COMPILE_UNIT_comp_dir(attr)); DST_put_string_attribute(" producer", DST_COMPILE_UNIT_producer(attr)); DST_put_language_attribute(" language", DST_COMPILE_UNIT_language(attr)); DST_put_id_case_attribute(" case", DST_COMPILE_UNIT_identifier_case(attr)); } #ifdef KEY /* Bug 3507 */ static void DST_put_module(DST_flag flag, DST_MODULE *attr) { DST_put_string(":module:"); DST_put_decl(DST_MODULE_decl(attr)); DST_put_string_attribute(" name", DST_MODULE_name(attr)); } static void DST_put_imported_decl(DST_flag flag, DST_IMPORTED_DECL *attr) { DST_put_string(":imported declaration"); DST_put_string_attribute(" name", DST_IMPORTED_DECL_name(attr)); DST_put_assoc(" import", flag, DST_IMPORTED_DECL_import(attr)); } #endif /* KEY Bug 3507 */ static void DST_put_subprogram(DST_flag flag, DST_SUBPROGRAM *attr) { DST_put_string(":subprogram:"); if (DST_IS_memdef(flag)) /* Not yet supported */ { DST_put_string(" a class member with AT_specification!"); } else if (DST_IS_declaration(flag)) { DST_put_decl(DST_SUBPROGRAM_decl_decl(attr)); DST_put_string_attribute(" name", DST_SUBPROGRAM_decl_name(attr)); DST_put_string_attribute(" linkage_name", DST_SUBPROGRAM_decl_linkage_name(attr)); DST_put_string(" declaration"); if (DST_IS_external(flag)) DST_put_string(" external"); if (DST_IS_prototyped(flag)) DST_put_string(" prototyped"); DST_put_idx_attribute(" type", DST_SUBPROGRAM_decl_type(attr), TRUE); DST_put_idx_attribute(" origin", DST_SUBPROGRAM_decl_origin(attr), FALSE); DST_put_inline_attribute (" inline", DST_SUBPROGRAM_decl_inline(attr)); DST_put_virtuality_attribute(" virtuality", DST_SUBPROGRAM_decl_virtuality(attr)); DST_put_INT32_attribute(" vtable_elem_location", DST_SUBPROGRAM_decl_vtable_elem_location(attr)); } else /* definition */ { DST_put_decl(DST_SUBPROGRAM_def_decl(attr)); DST_put_string_attribute(" name", DST_SUBPROGRAM_def_name(attr)); DST_put_string_attribute(" linkage_name", DST_SUBPROGRAM_def_linkage_name(attr)); DST_put_string_attribute(" pubname", DST_SUBPROGRAM_def_pubname(attr)); if (DST_IS_external(flag)) DST_put_string(" external"); if (DST_IS_prototyped(flag)) DST_put_string(" prototyped"); DST_put_idx_attribute(" type", DST_SUBPROGRAM_def_type(attr), TRUE); DST_put_idx_attribute(" specification", DST_SUBPROGRAM_def_specification(attr), TRUE); DST_put_idx_attribute(" clone_origin", DST_SUBPROGRAM_def_clone_origin(attr), FALSE); DST_put_inline_attribute (" inline", DST_SUBPROGRAM_def_inline(attr)); DST_put_virtuality_attribute(" virtuality", DST_SUBPROGRAM_def_virtuality(attr)); DST_put_INT32_attribute(" vtable_elem_location", DST_SUBPROGRAM_def_vtable_elem_location(attr)); DST_put_assoc(" pc", flag, DST_SUBPROGRAM_def_st(attr)); } } static void DST_put_inlined_subroutine(DST_flag flag, DST_INLINED_SUBROUTINE *attr) { DST_put_string(":inlined_subroutine:"); if (DST_IS_FOREIGN_OBJ(DST_INLINED_SUBROUTINE_abstract_origin(attr))) DST_put_decl(DST_INLINED_SUBROUTINE_decl(attr)); DST_put_assoc(" low_pc", flag, DST_INLINED_SUBROUTINE_low_pc(attr)); DST_put_assoc(" high_pc", flag, DST_INLINED_SUBROUTINE_high_pc(attr)); DST_put_idx_attribute(" abstract_origin", DST_INLINED_SUBROUTINE_abstract_origin(attr), FALSE); if (DST_IS_FOREIGN_OBJ(DST_INLINED_SUBROUTINE_abstract_origin(attr))) DST_put_string_attribute(" abstract_name", DST_INLINED_SUBROUTINE_abstract_name(attr)); } static void DST_put_entry_point(DST_flag flag, DST_ENTRY_POINT *attr) { DST_put_string(":entry point:"); DST_put_decl(DST_ENTRY_POINT_decl(attr)); DST_put_string_attribute(" name", DST_ENTRY_POINT_name(attr)); DST_put_idx_attribute(" type", DST_ENTRY_POINT_type(attr), TRUE); DST_put_assoc(" pc", flag, DST_ENTRY_POINT_st(attr)); } static void DST_put_common_block(DST_flag flag, DST_COMMON_BLOCK *attr) { DST_put_string(":common blk:"); DST_put_string_attribute(" name", DST_ENTRY_POINT_name(attr)); DST_put_assoc(" pc", flag, DST_ENTRY_POINT_st(attr)); } static void DST_put_common_inclusion(DST_flag flag, DST_COMMON_INCL *attr) { DST_put_string(":common incl:"); DST_put_decl(DST_COMMON_INCL_decl(attr)); DST_put_idx_attribute(" type", DST_COMMON_INCL_com_blk(attr), TRUE); } static void DST_put_lexical_block(DST_flag flag, DST_LEXICAL_BLOCK *attr) { DST_put_string(":lexical_block:"); DST_put_string_attribute(" name", DST_LEXICAL_BLOCK_name(attr)); DST_put_assoc(" low_pc", flag, DST_LEXICAL_BLOCK_low_pc(attr)); DST_put_assoc(" high_pc", flag, DST_LEXICAL_BLOCK_high_pc(attr)); } static void DST_put_label(DST_flag flag, DST_LABEL *attr) { DST_put_string(":label:"); DST_put_string_attribute(" name", DST_LABEL_name(attr)); DST_put_assoc(" low_pc", flag, DST_LABEL_low_pc(attr)); } static void DST_put_variable(DST_flag flag, DST_VARIABLE *attr) { DST_put_string(":variable:"); if (DST_IS_artificial(flag)) DST_put_string(" artificial"); if (DST_IS_const(flag)) /* Not yet supported */ { #ifdef KEY /* Bug 3507 */ DST_put_decl(DST_VARIABLE_decl_decl(attr)); DST_put_string_attribute(" name", DST_VARIABLE_decl_name(attr)); #endif /* KEY Bug 3507 */ DST_put_string(" a constant variable!"); } else if (DST_IS_comm(flag)) { DST_put_string("var in common:"); if (DST_IS_deref(flag)) DST_put_string(" deref"); if (DST_IS_f90_pointer(flag)) DST_put_string(" f90_pointer"); if (DST_IS_allocatable(flag)) DST_put_string(" allocatable"); if (DST_IS_assumed_shape(flag)) DST_put_string(" assumed_shape"); if (DST_IS_assumed_size(flag)) DST_put_string(" assumed_size"); DST_put_decl(DST_VARIABLE_comm_decl(attr)); DST_put_string_attribute(" name", DST_VARIABLE_comm_name(attr)); DST_put_idx_attribute(" type", DST_VARIABLE_comm_type(attr), TRUE); DST_put_UINT64_attribute(" offset", DST_VARIABLE_comm_offs(attr)); DST_put_assoc(" location", flag, DST_VARIABLE_comm_st(attr)); DST_put_idx_attribute(" dopetype", DST_VARIABLE_comm_dopetype(attr),TRUE); } else if (DST_IS_memdef(flag)) /* Not yet supported */ { DST_put_string(" a class member with AT_specification!"); } else if (DST_IS_declaration(flag)) { DST_put_decl(DST_VARIABLE_decl_decl(attr)); DST_put_string_attribute(" name", DST_VARIABLE_decl_name(attr)); DST_put_string(" declaration"); if (DST_IS_external(flag)) DST_put_string(" external"); if (DST_IS_automatic(flag)) DST_put_string(" <auto>"); DST_put_idx_attribute(" type", DST_VARIABLE_decl_type(attr), TRUE); #ifdef KEY DST_put_string_attribute(" linkage_name", DST_VARIABLE_decl_linkage_name(attr)); #endif } else /* definition */ { DST_put_decl(DST_VARIABLE_def_decl(attr)); DST_put_string_attribute(" name", DST_VARIABLE_def_name(attr)); if (DST_IS_external(flag)) DST_put_string(" external"); if (DST_IS_automatic(flag)) DST_put_string(" <auto>"); if (DST_IS_deref(flag)) DST_put_string(" deref"); if (DST_IS_base_deref(flag)) DST_put_string(" base_deref"); if (DST_IS_f90_pointer(flag)) DST_put_string(" f90_pointer"); if (DST_IS_allocatable(flag)) DST_put_string(" allocatable"); if (DST_IS_assumed_shape(flag)) DST_put_string(" assumed shape"); if (DST_IS_assumed_size(flag)) DST_put_string(" assumed_size"); DST_put_UINT64_attribute(" offset", DST_VARIABLE_def_offs(attr)); DST_put_idx_attribute(" type", DST_VARIABLE_def_type(attr), TRUE); DST_put_assoc(" location", flag, DST_VARIABLE_def_st(attr)); DST_put_idx_attribute(" abstract_origin", DST_VARIABLE_def_abstract_origin(attr), FALSE); DST_put_idx_attribute(" dopetype", DST_VARIABLE_def_dopetype(attr), TRUE); #ifdef KEY DST_put_string_attribute(" linkage_name", DST_VARIABLE_def_linkage_name(attr)); #endif } } static void DST_put_formal_parameter(DST_flag flag, DST_FORMAL_PARAMETER *attr) { DST_put_string(":formal_parameter:"); if (DST_IS_artificial(flag)) DST_put_string(" artificial"); if (DST_IS_base_deref(flag)) DST_put_string(" base_deref"); if (DST_IS_deref(flag)) DST_put_string(" deref"); if (DST_IS_f90_pointer(flag)) DST_put_string(" f90_pointer"); if (DST_IS_allocatable(flag)) DST_put_string(" allocatable"); if (DST_IS_assumed_shape(flag)) DST_put_string(" assumed shape"); if (DST_IS_assumed_size(flag)) DST_put_string(" assumed_size"); DST_put_decl(DST_FORMAL_PARAMETER_decl(attr)); DST_put_string_attribute(" name", DST_FORMAL_PARAMETER_name(attr)); if (DST_IS_optional_parm(flag)) DST_put_string(" is_optional"); if (DST_IS_variable_parm(flag)) DST_put_string(" variable_parameter"); DST_put_idx_attribute(" type", DST_FORMAL_PARAMETER_type(attr), TRUE); DST_put_idx_attribute(" default_value", DST_FORMAL_PARAMETER_default_val(attr), FALSE); DST_put_idx_attribute(" abstract_origin", DST_FORMAL_PARAMETER_abstract_origin(attr), FALSE); DST_put_assoc(" location", flag, DST_FORMAL_PARAMETER_st(attr)); DST_put_idx_attribute(" dopetype", DST_FORMAL_PARAMETER_dopetype(attr),TRUE); } static void DST_put_unspecified_parameters(DST_flag flag, DST_UNSPECIFIED_PARAMETERS *attr) { DST_put_string(":unspecified_parameters:"); DST_put_decl(DST_FORMAL_PARAMETER_decl(attr)); } static void DST_put_basetype(DST_flag flag, DST_BASETYPE *attr) { DST_put_string(":basetype:"); DST_put_string_attribute(" name", DST_FORMAL_PARAMETER_name(attr)); DST_put_INT32_attribute(" encoding", DST_BASETYPE_encoding(attr)); DST_put_INT32_attribute(" byte_size", DST_BASETYPE_byte_size(attr)); } static void DST_put_const_type(DST_flag flag, DST_CONST_TYPE *attr) { DST_put_string(":const_type:"); DST_put_idx_attribute(" type", DST_CONST_TYPE_type(attr), TRUE); } static void DST_put_constant(DST_flag flag, DST_CONSTANT *attr) { DST_put_string(":constant:"); DST_put_decl(DST_CONSTANT_def_decl(attr)); DST_put_string_attribute(" name", DST_CONSTANT_def_name(attr)); DST_put_idx_attribute(" type", DST_CONSTANT_def_type(attr), TRUE); DST_put_const_attribute(" value", DST_CONSTANT_def_cval(attr)); } static void DST_put_volatile_type(DST_flag flag, DST_VOLATILE_TYPE *attr) { DST_put_string(":volatile_type:"); DST_put_idx_attribute(" type", DST_VOLATILE_TYPE_type(attr), TRUE); } static void DST_put_pointer_type(DST_flag flag, DST_POINTER_TYPE *attr) { DST_put_string(":pointer_type:"); DST_put_idx_attribute(" type", DST_POINTER_TYPE_type(attr), TRUE); DST_put_INT32_attribute(" address_class", DST_POINTER_TYPE_address_class(attr)); DST_put_INT32_attribute(" byte_size", DST_POINTER_TYPE_byte_size(attr)); } static void DST_put_reference_type(DST_flag flag, DST_REFERENCE_TYPE *attr) { DST_put_string(":reference_type:"); DST_put_idx_attribute(" type", DST_REFERENCE_TYPE_type(attr), TRUE); DST_put_INT32_attribute(" address_class", DST_REFERENCE_TYPE_address_class(attr)); DST_put_INT32_attribute(" byte_size", DST_REFERENCE_TYPE_byte_size(attr)); } static void DST_put_typedef(DST_flag flag, DST_TYPEDEF *attr) { DST_put_string(":typedef:"); DST_put_decl(DST_TYPEDEF_decl(attr)); DST_put_string_attribute(" name", DST_TYPEDEF_name(attr)); DST_put_idx_attribute(" type", DST_TYPEDEF_type(attr), TRUE); DST_put_idx_attribute(" abstract_origin", DST_TYPEDEF_abstract_origin(attr), FALSE); } static void DST_put_array_type(DST_flag flag, DST_ARRAY_TYPE *attr) { DST_put_string(":array_type:"); DST_put_decl(DST_ARRAY_TYPE_decl(attr)); DST_put_string_attribute(" name", DST_ARRAY_TYPE_name(attr)); DST_put_idx_attribute(" type", DST_ARRAY_TYPE_type(attr), TRUE); DST_put_INT32_attribute(" byte_size", DST_ARRAY_TYPE_byte_size(attr)); DST_put_idx_attribute(" abstract_origin", DST_ARRAY_TYPE_abstract_origin(attr), FALSE); if (DST_IS_declaration(flag)) DST_put_string(" declaration"); #ifdef TARG_X8664 if (DST_IS_GNU_vector(flag)) DST_put_string(" GNU_vector"); #endif } static void DST_put_subrange_type(DST_flag flag, DST_SUBRANGE_TYPE *attr) { const char * p; DST_put_string(":subrange_type:"); if (DST_IS_lb_cval(flag)) DST_put_INT32_attribute(" lower", DST_SUBRANGE_TYPE_lower_cval(attr)); else DST_put_idx_attribute(" lower", DST_SUBRANGE_TYPE_lower_ref(attr), FALSE); p = " upper"; if (DST_IS_count(flag)) p = " count"; if (DST_IS_ub_cval(flag)) DST_put_INT32_attribute(p, DST_SUBRANGE_TYPE_upper_cval(attr)); else DST_put_idx_attribute(p, DST_SUBRANGE_TYPE_upper_ref(attr), FALSE); if (DST_IS_stride_1byte(flag)) p = " stride_1byte" ; else if (DST_IS_stride_2byte(flag)) p = " stride_2byte" ; else p = " stride" ; DST_put_idx_attribute(p,DST_SUBRANGE_TYPE_stride_ref(attr), FALSE); } static void DST_put_string_type(DST_flag flag, DST_STRING_TYPE *attr) { DST_put_string(":string_type:"); DST_put_decl(DST_STRING_TYPE_decl(attr)); DST_put_string_attribute(" name", DST_STRING_TYPE_name(attr)); if (DST_IS_cval(flag)) DST_put_INT32_attribute(" length", DST_STRING_TYPE_len_cval(attr)); else DST_put_idx_attribute(" length", DST_STRING_TYPE_len_ref(attr), FALSE); } static void DST_put_structure_type(DST_flag flag, DST_STRUCTURE_TYPE *attr) { DST_put_string(":structure_type:"); DST_put_decl(DST_STRUCTURE_TYPE_decl(attr)); DST_put_string_attribute(" name", DST_STRUCTURE_TYPE_name(attr)); DST_put_INT32_attribute(" byte_size", DST_STRUCTURE_TYPE_byte_size(attr)); DST_put_idx_attribute(" abstract_origin", DST_STRUCTURE_TYPE_abstract_origin(attr), FALSE); if (DST_IS_declaration(flag)) DST_put_string(" declaration"); } static void DST_put_class_type(DST_flag flag, DST_CLASS_TYPE *attr) { DST_put_string(":class_type:"); DST_put_decl(DST_CLASS_TYPE_decl(attr)); DST_put_string_attribute(" name", DST_CLASS_TYPE_name(attr)); DST_put_INT32_attribute(" byte_size", DST_CLASS_TYPE_byte_size(attr)); DST_put_idx_attribute(" abstract_origin", DST_CLASS_TYPE_abstract_origin(attr), FALSE); if (DST_IS_declaration(flag)) DST_put_string(" declaration"); } static void DST_put_union_type(DST_flag flag, DST_UNION_TYPE *attr) { DST_put_string(":union_type:"); DST_put_decl(DST_UNION_TYPE_decl(attr)); DST_put_string_attribute(" name", DST_UNION_TYPE_name(attr)); DST_put_INT32_attribute(" byte_size", DST_UNION_TYPE_byte_size(attr)); DST_put_idx_attribute(" abstract_origin", DST_UNION_TYPE_abstract_origin(attr), FALSE); if (DST_IS_declaration(flag)) DST_put_string(" declaration"); } static void DST_put_member(DST_flag flag, DST_MEMBER *attr) { DST_put_string(":member:"); DST_put_decl(DST_MEMBER_decl(attr)); DST_put_string_attribute(" name", DST_MEMBER_name(attr)); DST_put_idx_attribute(" type", DST_MEMBER_type(attr), TRUE); DST_put_INT32_attribute(" data_member_location", DST_MEMBER_memb_loc(attr)); DST_put_idx_attribute(" dopetype", DST_MEMBER_dopetype(attr),TRUE); if (DST_IS_bitfield(flag)) { DST_put_INT32_attribute(" byte_size", DST_MEMBER_byte_size(attr)); DST_put_INT32_attribute(" bit_offset", DST_MEMBER_bit_offset(attr)); DST_put_INT32_attribute(" bit_size", DST_MEMBER_bit_size(attr)); } if (DST_IS_declaration(flag)) DST_put_string(" declaration"); if (DST_IS_f90_pointer(flag)) DST_put_string(" f90_pointer"); if (DST_IS_allocatable(flag)) DST_put_string(" allocatable"); if (DST_IS_assumed_shape(flag)) DST_put_string(" assumed shape"); } static void DST_put_inheritance(DST_flag flag, DST_INHERITANCE *attr) { DST_put_string(":inheritance:"); DST_put_idx_attribute(" type", DST_INHERITANCE_type(attr), TRUE); DST_put_INT32_attribute(" data_member_location", DST_INHERITANCE_memb_loc(attr)); #ifdef KEY DST_put_accessibility_attribute(" accessibility", DST_INHERITANCE_accessibility(attr)); #endif } static void DST_put_template_type_param(DST_flag flag, DST_TEMPLATE_TYPE_PARAMETER *attr) { DST_put_string(":template_type_param:"); DST_put_string_attribute(" name", DST_TEMPLATE_TYPE_PARAMETER_name(attr)); DST_put_idx_attribute(" type", DST_TEMPLATE_TYPE_PARAMETER_type(attr), TRUE); } static void DST_put_template_value_param(DST_flag flag, DST_TEMPLATE_VALUE_PARAMETER *attr) { DST_put_string(":template_value_param:"); DST_put_string_attribute(" name", DST_TEMPLATE_VALUE_PARAMETER_name(attr)); DST_put_const_attribute(" value", DST_TEMPLATE_VALUE_PARAMETER_cval(attr)); } static void DST_put_enumeration_type(DST_flag flag, DST_ENUMERATION_TYPE *attr) { DST_put_string(":enumeration_type:"); DST_put_decl(DST_ENUMERATION_TYPE_decl(attr)); DST_put_string_attribute(" name", DST_ENUMERATION_TYPE_name(attr)); DST_put_INT32_attribute(" byte_size", DST_ENUMERATION_TYPE_byte_size(attr)); DST_put_idx_attribute(" abstract_origin", DST_ENUMERATION_TYPE_abstract_origin(attr), FALSE); if (DST_IS_declaration(flag)) DST_put_string(" declaration"); } static void DST_put_enumerator(DST_flag flag, DST_ENUMERATOR *attr) { DST_put_string(":enumerator:"); DST_put_decl(DST_ENUMERATOR_decl(attr)); DST_put_string_attribute(" name", DST_ENUMERATOR_name(attr)); DST_put_const_attribute(" const_value", DST_ENUMERATOR_cval(attr)); } static void DST_put_subroutine_type(DST_flag flag, DST_SUBROUTINE_TYPE *attr) { DST_put_string(":subroutine_type:"); DST_put_decl(DST_SUBROUTINE_TYPE_decl(attr)); DST_put_string_attribute(" name", DST_SUBROUTINE_TYPE_name(attr)); DST_put_idx_attribute(" type", DST_SUBROUTINE_TYPE_type(attr), TRUE); DST_put_idx_attribute(" abstract_origin", DST_SUBROUTINE_TYPE_abstract_origin(attr), FALSE); if (DST_IS_prototyped(flag)) DST_put_string(" prototyped"); } /*------------------------------------------------ * Dump routines for info, and include files/dirs *------------------------------------------------*/ static INT32 DST_dump_info(INT32 indentation, DST_DW_tag tag, DST_flag flag, DST_ATTR_IDX iattr, DST_INFO_IDX iinfo) { DST_write_line(); if (indentation > 80) { DST_put_string("infinite loop while dumping DST?"); DST_write_line(); exit(RC_INTERNAL_ERROR); } /* Put the index for this info */ DST_nput_char(indentation, ' '); DST_put_idx(iinfo); switch (tag) { case DW_TAG_compile_unit: DST_put_compile_unit(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_COMPILE_UNIT)); break; #ifdef KEY /* Bug 3507 */ case DW_TAG_module: DST_put_module(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_MODULE)); break; case DW_TAG_imported_declaration: DST_put_imported_decl(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_IMPORTED_DECL)); break; #endif /* KEY Bug 3507 */ case DW_TAG_subprogram: DST_put_subprogram(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_SUBPROGRAM)); break; case DW_TAG_inlined_subroutine: DST_put_inlined_subroutine(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_INLINED_SUBROUTINE)); break; case DW_TAG_entry_point: DST_put_entry_point(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_ENTRY_POINT)); break; case DW_TAG_common_block: DST_put_common_block(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_COMMON_BLOCK)); break; case DW_TAG_common_inclusion: DST_put_common_inclusion(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_COMMON_INCL)); break; case DW_TAG_lexical_block: DST_put_lexical_block(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_LEXICAL_BLOCK)); break; case DW_TAG_label: DST_put_label(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_LABEL)); break; case DW_TAG_variable: DST_put_variable(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_VARIABLE)); break; case DW_TAG_formal_parameter: DST_put_formal_parameter( flag, DST_ATTR_IDX_TO_PTR(iattr, DST_FORMAL_PARAMETER)); break; case DW_TAG_unspecified_parameters: DST_put_unspecified_parameters( flag, DST_ATTR_IDX_TO_PTR(iattr, DST_UNSPECIFIED_PARAMETERS)); break; case DW_TAG_base_type: DST_put_basetype(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_BASETYPE)); break; case DW_TAG_const_type: DST_put_const_type(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_CONST_TYPE)); break; case DW_TAG_constant: DST_put_constant(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_CONSTANT)); break; case DW_TAG_volatile_type: DST_put_volatile_type(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_VOLATILE_TYPE)); break; case DW_TAG_pointer_type: DST_put_pointer_type(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_POINTER_TYPE)); break; case DW_TAG_reference_type: DST_put_reference_type(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_REFERENCE_TYPE)); break; case DW_TAG_typedef: DST_put_typedef(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_TYPEDEF)); break; case DW_TAG_array_type: DST_put_array_type(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_ARRAY_TYPE)); break; case DW_TAG_subrange_type: DST_put_subrange_type(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_SUBRANGE_TYPE)); break; case DW_TAG_string_type: DST_put_string_type(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_STRING_TYPE)); break; case DW_TAG_structure_type: DST_put_structure_type(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_STRUCTURE_TYPE)); break; case DW_TAG_class_type: DST_put_class_type(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_CLASS_TYPE)); break; case DW_TAG_union_type: DST_put_union_type(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_UNION_TYPE)); break; case DW_TAG_member: DST_put_member(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_MEMBER)); break; case DW_TAG_inheritance: DST_put_inheritance(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_INHERITANCE)); break; case DW_TAG_template_type_param: DST_put_template_type_param(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_TEMPLATE_TYPE_PARAMETER)); break; case DW_TAG_template_value_param: DST_put_template_value_param(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_TEMPLATE_VALUE_PARAMETER)); break; case DW_TAG_enumeration_type: DST_put_enumeration_type( flag, DST_ATTR_IDX_TO_PTR(iattr, DST_ENUMERATION_TYPE)); break; case DW_TAG_enumerator: DST_put_enumerator(flag, DST_ATTR_IDX_TO_PTR(iattr, DST_ENUMERATOR)); break; case DW_TAG_subroutine_type: DST_put_subroutine_type( flag, DST_ATTR_IDX_TO_PTR(iattr, DST_SUBROUTINE_TYPE)); break; default: DST_put_INT32_attribute(">>> Unprintable DW_TAG", tag); break; } DST_write_line(); return indentation + 2; } static void DST_dump_include_dirs(DST_DIR_IDX dir_idx, INT32 indentation) { DST_DIR_IDX idx = dir_idx; mUINT16 num = 0; DST_INCLUDE_DIR *dir; DST_write_line(); if (!DST_IS_NULL(idx)) dir = DST_DIR_IDX_TO_PTR(idx); else dir = NULL; while(dir != NULL) { num += 1; DST_put_idx(idx); DST_put_UINT32_attribute(" ordinal", num); DST_put_string_attribute(" path", DST_INCLUDE_DIR_path(dir)); DST_write_line(); idx = DST_INCLUDE_DIR_next(dir); if (!DST_IS_NULL(idx)) dir = DST_DIR_IDX_TO_PTR(idx); else dir = NULL; } } static void DST_dump_files(DST_FILE_IDX file_idx, INT32 indentation) { DST_FILE_IDX idx = file_idx; mUINT16 num = 0; DST_FILE_NAME *f; DST_write_line(); if (!DST_IS_NULL(idx)) f = DST_FILE_IDX_TO_PTR(idx); else f = NULL; while(f != NULL) { num += 1; DST_put_idx(idx); DST_put_UINT32_attribute(" ordinal", num); DST_put_string_attribute(" name", DST_FILE_NAME_name(f)); DST_put_UINT32_attribute(" path", DST_FILE_NAME_dir(f)); DST_put_UINT64_attribute(" size", DST_FILE_NAME_size(f)); DST_put_UINT64_attribute(" modt", DST_FILE_NAME_modt(f)); DST_write_line(); idx = DST_FILE_NAME_next(f); if (!DST_IS_NULL(idx)) f = DST_FILE_IDX_TO_PTR(idx); else f = NULL; } } static void DST_dump_block_kind (DST_BLOCK_KIND k) { switch (k) { case DST_include_dirs_block: DST_put_string("include_dirs"); break; case DST_file_names_block: DST_put_string("file_names"); break; case DST_macro_info_block: DST_put_string("macro_info"); break; case DST_file_scope_block: DST_put_string("file_scope"); break; case DST_local_scope_block: DST_put_string("local_scope"); break; } } /* The main dumping routine! */ void DST_dump(DST_DIR_IDX incl_dirs, DST_FILE_IDX files, DST_INFO_IDX compile_unit) { DST_BLOCK_IDX i; /* Initialization */ next_char = 0; if (dumpf_name != NULL) { dumpf = fopen(dumpf_name, "w"); } DST_ASSERT(dumpf, "Cannot open DST dump file"); /* Write the stuff */ if (!DST_IS_NULL(incl_dirs)) { DST_write_line(); DST_put_string("------------ INCLUDE_DIRECTORIES ------------"); DST_write_line(); DST_dump_include_dirs(incl_dirs, 0); } if (!DST_IS_NULL(files)) { DST_write_line(); DST_put_string("------------<<<<<<< FILES >>>>>>>------------"); DST_write_line(); DST_dump_files(files, 0); } if (!DST_IS_NULL(compile_unit)) { DST_write_line(); DST_put_string("------------<<<<<< DST INFO >>>>>------------"); DST_write_line(); DST_preorder_visit(compile_unit, 0, &DST_dump_info); } DST_put_string("------------<<<< BLOCK INFO >>>------------"); DST_write_line(); FOREACH_DST_BLOCK(i) { sprintf(&tmp_buffer[0], "block %d: ", i); DST_put_string(&tmp_buffer[0]); DST_dump_block_kind (((DST_Type *)Current_DST)->dst_blocks[i].kind); sprintf(&tmp_buffer[0], ", size = %d", ((DST_Type *)Current_DST)->dst_blocks[i].size); DST_put_string(&tmp_buffer[0]); DST_write_line(); } /* (void)fclose(dumpf); */ } /* alternate entry to dump routine, finds idx values implicitly. */ void Dump_DST (FILE *f) { DST_IDX inc, fn, cmp; if (f == NULL) dumpf = stdout; else dumpf = f; inc = DST_get_include_dirs(); fn = DST_get_file_names(); cmp = DST_get_compile_unit(); DST_dump (inc, fn, cmp); } void DST_set_dump_filename(char *file_name) { dumpf_name = file_name; }
28.112749
97
0.705576
sharugupta
e2d7fb49e17edc6fad629d3b02ce7490643c93cb
1,486
hpp
C++
sample/sample_mandelbrot.hpp
matazure/mtensor
4289284b201cb09ed1dfc49f44d6738751affd63
[ "MIT" ]
82
2020-04-11T09:33:36.000Z
2022-03-23T03:47:25.000Z
sample/sample_mandelbrot.hpp
Lexxos/mtensor
feb120923dad3fb4ae3b31dd09931622a63c3d06
[ "MIT" ]
28
2017-04-26T17:12:35.000Z
2019-04-08T04:05:24.000Z
sample/sample_mandelbrot.hpp
Lexxos/mtensor
feb120923dad3fb4ae3b31dd09931622a63c3d06
[ "MIT" ]
22
2017-01-10T14:57:29.000Z
2019-12-17T08:55:59.000Z
#pragma once #include <mtensor.hpp> #include <stdexcept> #include "image_helper.hpp" #include "sample_mandelbrot.hpp" using namespace matazure; struct mandelbrot_functor { mandelbrot_functor(pointi<2> shape) : shape(shape) {} //曼德勃罗算子, MATAZURE_GENERAL可以同时支持host和device MATAZURE_GENERAL point<byte, 3> operator()(pointi<2> idx) const { pointf<2> c = point_cast<float>(idx) / point_cast<float>(shape) * pointf<2>{3.25f, 2.5f} - pointf<2>{2.0f, 1.25f}; auto z = pointf<2>::all(0.0f); auto norm = 0.0f; int_t value = 0; while (norm <= 4.0f && value < max_iteration) { float tmp = z[0] * z[0] - z[1] * z[1] + c[0]; z[1] = 2 * z[0] * z[1] + c[1]; z[0] = tmp; ++value; norm = z[0] * z[0] + z[1] * z[1]; } //返回rgb的像素值 float t = float(value) / max_iteration; auto r = static_cast<byte>(36 * (1 - t) * t * t * t * 255); auto g = static_cast<byte>(60 * (1 - t) * (1 - t) * t * t * 255); auto b = static_cast<byte>(38 * (1 - t) * (1 - t) * (1 - t) * t * 255); return point<byte, 3>{r, g, b}; } private: pointi<2> shape; int_t max_iteration = 256 * 16; }; template <typename runtime_type> auto mandelbrot(pointi<2> shape, runtime_type mem_tag) -> decltype(make_lambda(shape, mandelbrot_functor(shape), mem_tag)) { return make_lambda(shape, mandelbrot_functor(shape), mem_tag); }
33.022222
98
0.558546
matazure
e2d9ec25a61c54b250a6387ac7cdbc990b216574
686
cpp
C++
SGE/src/SGE/Renderer/VertexArray.cpp
Stealthhyy/SGE
e56560a93a4d7c9aac2a525240be6d4d9ba3d4e7
[ "Apache-2.0" ]
1
2021-04-25T05:45:28.000Z
2021-04-25T05:45:28.000Z
SGE/src/SGE/Renderer/VertexArray.cpp
Stealthhyy/SGE
e56560a93a4d7c9aac2a525240be6d4d9ba3d4e7
[ "Apache-2.0" ]
null
null
null
SGE/src/SGE/Renderer/VertexArray.cpp
Stealthhyy/SGE
e56560a93a4d7c9aac2a525240be6d4d9ba3d4e7
[ "Apache-2.0" ]
null
null
null
#include "sgepch.h" #include "VertexArray.h" #include "Renderer.h" #include "Platform/OpenGL/OpenGLVertexArray.h" #include "Platform/Vulkan/VulkanVertexArray.h" namespace SGE { void VertexArray::Bind() const { } void VertexArray::Unbind() const { } Ref<VertexArray> VertexArray::Create() { switch (Renderer::GetAPI()) { case RendererAPI::API::None: SGE_CORE_ASSERT(false, "RendererAPI::None is not supported!"); return nullptr; case RendererAPI::API::OpenGL: return std::make_shared<OpenGLVertexArray>(); case RendererAPI::API::Vulkan: return std::make_shared<VulkanVertexArray>(); } SGE_CORE_ASSERT(false, "Unknown Renderer API!"); return nullptr; } }
20.176471
109
0.72449
Stealthhyy
e2e22341f47b237ac66f05e31e0b9460ffd37c2f
6,905
cpp
C++
src/ui/Display.cpp
mcmatrix/cnc3018-offline-controller
604e63a1f39e0742ba4f8c7e4cf2bad8d5b67e47
[ "MIT" ]
14
2021-09-10T18:33:43.000Z
2022-02-12T12:00:20.000Z
src/ui/Display.cpp
mcmatrix/cnc3018-offline-controller
604e63a1f39e0742ba4f8c7e4cf2bad8d5b67e47
[ "MIT" ]
7
2021-10-02T13:00:01.000Z
2022-03-31T10:15:04.000Z
src/ui/Display.cpp
mcmatrix/cnc3018-offline-controller
604e63a1f39e0742ba4f8c7e4cf2bad8d5b67e47
[ "MIT" ]
4
2021-09-15T11:56:24.000Z
2022-02-14T12:11:30.000Z
#include "Display.h" #include <Arduino.h> #include "Screen.h" #include "../devices/GrblDevice.h" Display * Display::inst = nullptr; uint16_t Display::buttStates; Display* Display::getDisplay() { return inst; } void Display::setScreen(Screen *screen) { if(cScreen != nullptr) cScreen->onHide(); cScreen = screen; if(cScreen != nullptr) cScreen->onShow(); selMenuItem = 0; menuShown=false; dirty=true; } void Display::loop() { if(cScreen!=nullptr) cScreen->loop(); draw(); } constexpr int VISIBLE_MENUS = 5; void Display::ensureSelMenuVisible() { if(selMenuItem >= cScreen->firstDisplayedMenuItem+VISIBLE_MENUS) cScreen->firstDisplayedMenuItem = selMenuItem - VISIBLE_MENUS + 1; if(selMenuItem < cScreen->firstDisplayedMenuItem) { cScreen->firstDisplayedMenuItem = selMenuItem; } } void Display::processInput() { processButtons(); } void Display::processButtons() { decltype(buttStates) changed = buttStates ^ prevStates; if (cScreen == nullptr) return; ButtonEvent evt; for(int i=0; i<N_BUTTONS; i++) { bool down = bitRead(buttStates, i); if(bitRead(changed, i) ) { if(i==BT_STEP && down && cScreen->menuItems.size()>0 ) { menuShown = !menuShown; setDirty(); } else { evt = down ? ButtonEvent::DOWN : ButtonEvent::UP; if(down) menuShownWhenDown = menuShown; // don't propagate events to screen if the click was in the menu if(menuShown) { processMenuButton(i, evt); } else if(!menuShownWhenDown) { cScreen->onButton(i, evt); } } holdCounter[i] = 0; } else if(down) { holdCounter[i]++; if(holdCounter[i] == HOLD_COUNT) { evt = ButtonEvent::HOLD; if(menuShown) { processMenuButton(i, evt); } else { cScreen->onButton(i, evt); } holdCounter[i] = 0; } } } prevStates = buttStates; } void Display::processMenuButton(uint8_t bt, ButtonEvent evt) { if(! (evt==ButtonEvent::DOWN || evt==ButtonEvent::HOLD) ) return; size_t menuLen = cScreen->menuItems.size(); if(menuLen!=0) { if(bt==BT_UP) { selMenuItem = selMenuItem>0 ? selMenuItem-1 : menuLen-1; ensureSelMenuVisible(); setDirty(); } if(bt==BT_DOWN) { selMenuItem = (selMenuItem+1) % menuLen; ensureSelMenuVisible(); setDirty(); } if(bt==BT_CENTER) { MenuItem& item = cScreen->menuItems[selMenuItem]; if(!item.togglalbe) { item.on = !item.on; } item.cmd(item); menuShown = false; setDirty(); } //cScreen->onMenuItemSelected(cScreen->menuItems[selMenuItem]); } } void Display::draw() { if(!dirty) return; u8g2.clearBuffer(); if(cScreen!=nullptr) cScreen->drawContents(); drawStatusBar(); if(menuShown) drawMenu(); //char str[15]; sprintf(str, "%lu", millis() ); u8g2.drawStr(20,20, str); //char str[15]; sprintf(str, "%4d %4d", potVal[0], potVal[1] ); u8g2.drawStr(5,110, str); //char str[15]; sprintf(str, "%d", encVal ); u8g2.drawStr(5,110, str); u8g2.sendBuffer(); dirty = false; } #include "../assets/locked.XBM" #include "../assets/connected.XBM" void Display::drawStatusBar() { GrblDevice *dev = static_cast<GrblDevice*>( GCodeDevice::getDevice() ); //u8g2.setFont(u8g2_font_5x8_tr); u8g2.setDrawColor(1); u8g2.setFont(u8g2_font_nokiafc22_tr); constexpr int LEN=25; char str[LEN]; int x=2, y=-1; //snprintf(str, 25, "DET:%c", digitalRead(PIN_DET)==0 ? '0' : '1' ); if(dev==nullptr || !dev->isConnected()) { u8g2.drawGlyph(x, y, 'X' ); } else if(dev->isLocked() ) { u8g2.drawXBM(x,0, locked_width, locked_height, (const uint8_t*)locked_bits); } else { u8g2.drawXBM(x,0, connected_width, connected_height, (const uint8_t*)connected_bits); } if(dev==nullptr) return; u8g2.drawStr(12, y, dev->getStatusStr()); //snprintf(str, 100, "u:%c bt:%d", digitalRead(PIN_DET)==0 ? 'n' : 'y', buttStates); //u8g2.drawStr(sx, 7, str); //job status Job &job = Job::getJob(); if(job.isValid() ) { float p = job.getCompletion()*100; /*if(p<10) snprintf(str, 20, " %.1f%%", p ); else */snprintf(str, LEN, " %d%%", (int)p ); if(job.isPaused() ) str[0] = 'p'; int w = u8g2.getStrWidth(str); u8g2.drawStr(u8g2.getWidth()-w-4, y, str); }// else strncpy(str, " ---%", LEN); } void Display::drawMenu() { if(cScreen==nullptr) return; u8g2.setFont(u8g2_font_nokiafc22_tr); const size_t len = cScreen->menuItems.size(); size_t onscreenLen = len - cScreen->firstDisplayedMenuItem; if (onscreenLen>VISIBLE_MENUS) onscreenLen=VISIBLE_MENUS; const int w = 80, x=20, lh=8, h=onscreenLen*lh; int y = 6; u8g2.setDrawColor(0); u8g2.drawBox(x,y, w, lh+h+4); u8g2.setDrawColor(1); u8g2.drawFrame(x,y, w, lh+h+4); char str[20]; snprintf(str, 20, "Menu [%d/%d]", selMenuItem+1, len); u8g2.drawStr(x+2, y+1, str); y = 16; for(size_t i=0; i<onscreenLen; i++) { size_t idx = cScreen->firstDisplayedMenuItem + i; if(selMenuItem == idx) { u8g2.setDrawColor(1); u8g2.drawBox(x, y+i*lh, w, lh); } MenuItem &item = cScreen->menuItems[idx]; //uint16_t c = item.glyph; if(item.font != nullptr) u8g2.setFont(item.font); u8g2.setDrawColor(2); //u8g2.drawGlyph(x+2, y+i*lh-1, c); u8g2.drawStr(x+2, y+i*lh-1, item.text.c_str() ); } u8g2.setDrawColor(0); int xx = x + w-5; u8g2.drawBox(xx-1, y, 5, h); u8g2.setDrawColor(1); u8g2.drawFrame(xx, y, 5, h); if(len>VISIBLE_MENUS) { const int hh = (h-2) * VISIBLE_MENUS / len; const int sy = (h-hh) * cScreen->firstDisplayedMenuItem / (len-VISIBLE_MENUS); u8g2.drawBox(xx+1, y+1 + sy, 3, hh); } }
31.674312
124
0.515858
mcmatrix
e2e4d3c4a223f1b813a2feed1faf79388e1d1ad7
539
hpp
C++
libs/renderer/include/sge/renderer/vf/part_from_list.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/renderer/include/sge/renderer/vf/part_from_list.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/renderer/include/sge/renderer/vf/part_from_list.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_RENDERER_VF_PART_FROM_LIST_HPP_INCLUDED #define SGE_RENDERER_VF_PART_FROM_LIST_HPP_INCLUDED #include <sge/renderer/vf/part.hpp> #include <fcppt/mpl/list/as.hpp> namespace sge::renderer::vf { template <typename List> using part_from_list = fcppt::mpl::list::as<sge::renderer::vf::part, List>; } #endif
25.666667
75
0.74026
cpreh
e2e7a440c89a7f7784d300a9b4b0cab46cc33f6d
11,667
cpp
C++
CPPCodeAnalyzer/CPPParser/parser.cpp
amin-amani/CPPCodeAnalyzer
0a9eedc56dd87efb7460ca77a82fdc7732306e0f
[ "MIT" ]
null
null
null
CPPCodeAnalyzer/CPPParser/parser.cpp
amin-amani/CPPCodeAnalyzer
0a9eedc56dd87efb7460ca77a82fdc7732306e0f
[ "MIT" ]
null
null
null
CPPCodeAnalyzer/CPPParser/parser.cpp
amin-amani/CPPCodeAnalyzer
0a9eedc56dd87efb7460ca77a82fdc7732306e0f
[ "MIT" ]
null
null
null
#include "parser.h" //=============================================================================== Parser::Parser() { } //=============================================================================== Parser::Parser(QString fileName) { _fileName=fileName; QFile file; file.setFileName(_fileName); if(!file.open(QFile::ReadOnly)) return; _fileContent= file.readAll(); file.close(); } //=============================================================================== void Parser::SetFileName(QString fileName) { _fileName=fileName; QFile file; file.setFileName(_fileName); if(!file.open(QFile::ReadOnly)) return; _fileContent= file.readAll(); } //=============================================================================== QStringList Parser::GetIncludes(QString content) { QStringList result; QStringList fileLines=content.split('\n'); for (int line=0;line<fileLines.count();line++) { QString currentLine=fileLines[line].trimmed().replace(" ",""); int startIndex= currentLine.indexOf("#include",0); if(startIndex<0)continue; for(int i=startIndex;i<currentLine.length();i++) { if(currentLine[i]=='>') { //result.append(currentLine.mid(startIndex,i-startIndex+1)); result.append(fileLines[line]); } } } return result; } //=============================================================================== QStringList Parser::GetIncludeGaurds(QString content) { QStringList result; QStringList fileLines=content.split('\n'); for (int line=0;line<fileLines.count();line++) { QString currentLine=fileLines[line].trimmed(); int idx1= currentLine.indexOf("#ifndef",0); int idx2= currentLine.indexOf("#endif",0); if(idx1<0 && idx2<0)continue; result.append(currentLine); } return result; } //=============================================================================== QStringList Parser::GetDefines(QString content) { QStringList result; QStringList fileLines=content.split('\n'); for (int line=0;line<fileLines.count();line++) { QString currentLine=fileLines[line].trimmed(); int idx1= currentLine.indexOf("#define",0); if(idx1<0)continue; result.append(currentLine); } return result; } //=============================================================================== QStringList Parser::GetBraces(QString input) { QStringList result; if(input.isEmpty())return result; QVector<int> braceStarts,braceEnds; QVector<QPoint> posPoints; int index=0; while (index>=0) { index=input.indexOf("{",index); if(index<0)break; braceStarts.append(index); index++; } //qDebug()<<"input="<<input; index=0; while (index>=0) { index=input.indexOf("}",index); if(index<0)break; braceEnds.append(index); index++; } for (int j=0;j<braceStarts.count();j++) { int currentStartBrace=braceStarts[braceStarts.count()-j-1]; for (int i=0;i<braceEnds.count();i++) { //qDebug()<<"braceEnd["<<i<<"]="<<braceEnds[i]; if(currentStartBrace<braceEnds[i]) { QPoint temp; temp.setX(currentStartBrace); temp.setY(braceEnds[i]); posPoints.append(temp); braceEnds[i]=-1; break; } } } for (int i=0;i<posPoints.count();i++) { QString str=input.mid(posPoints[i].x(),posPoints[i].y()-posPoints[i].x()+1); // qDebug()<<"answer["<<i<<"]="<<str; result.append(str); } return result; } //=============================================================================== QStringList Parser::GetLineComments(QString content) { QStringList result; QStringList fileLines=content.split('\n'); for (int i=0;i<fileLines.count();i++) { int startIndex=fileLines[i].indexOf("//"); if(startIndex<0)continue; result.append(fileLines[i].mid(startIndex,fileLines[i].count()-startIndex)); } return result; } //=============================================================================== QStringList Parser::GetBlockComments(QString content) { QStringList result; int startInex=-1; QString comment=""; for (int i=0;i<content.count()-1;i++) { if(content[i]=='/' && content[i+1]=='*' && startInex<0) { startInex=i; } if(content[i]=='*' && content[i+1]=='/' && startInex>=0 && comment.length()>3) { comment=comment+content[i]+content[i+1]; result.append(comment); startInex=-1; comment=""; } if(startInex>=0)comment+=content[i]; } return result; } QString Parser::ReplaceEndlineTolinuxFormat(QString content) { return content.replace("\r\n","\n"); } QString Parser::RemoveEmptyLines(QString content) { QStringList fileLines=content.split('\n'); QString result; foreach(QString line ,fileLines) { if(line.isEmpty())continue ; result+=line.trimmed(); } return result; } //=============================================================================== CPPClass Parser::GetClassInheritances(QString content) { CPPClass result; if(!content.contains("class ")) return result; content=content.split("class ")[1]; content=content.split("{")[0]; result.Name=content.split(":")[0].trimmed(); if(!content.contains(":")) { return result; } QString inheritances=content.split(":")[1]; foreach(QString item, inheritances.split(",")) { if(item.contains("public ")) { result.PulicParents.append(item.split("public ")[1].trimmed()); } if(item.contains("private ")) { result.PrivateParents.append(item.split("private ")[1].trimmed()); } if(item.contains("protected ")) { result.ProtectedParents.append(item.split("protected ")[1].trimmed()); } if(!item.contains("public ") && !item.contains("protcted ") && !item.contains("private ")) { result.PrivateParents.append(item.trimmed()); } } return result; } //=============================================================================== QStringList Parser::GetClassesFromText(QString content) { QStringList result; QList<QPoint> parentBraces=GetParentBraces(content); if(parentBraces.count()<1) { return result; } QString line=content.mid(0,parentBraces[0].x()); if(line.contains("class")) { result.append(line.mid(line.lastIndexOf("class "))); } for(int i=0;i<parentBraces.count()-1;i++){ QString line=content.mid(parentBraces[i].y(),parentBraces[1+i].x()); if(line.contains("class")) { result.append(line.mid(line.lastIndexOf("class "))); } } return result; } QList <CPPClass> Parser::GetClassSignature(QString content) { CPPClass result; QList <CPPClass> resultList; if(content.isNull())return resultList; if(content.isEmpty())return resultList; QStringList classes= GetClassesFromText(content); foreach(QString temp ,classes) { CPPClass signatureResult=GetClassInheritances(temp); result.Name=signatureResult.Name; result.PulicParents=signatureResult.PulicParents; result.PrivateParents=signatureResult.PrivateParents; result.ProtectedParents=signatureResult.ProtectedParents; resultList.append(result); } return resultList; } //=============================================================================== QString Parser::GetClasses(QString contect) { QStringList classtext= contect.split("class "); if(classtext.length()>0) { QStringList classDef= classtext[1].split("{"); if(classDef.length()>0) { qDebug()<<classDef[0]; } } return ""; } //=============================================================================== QList<CPPClass> Parser::GetAllClasses() { QList<CPPClass> result; QString text; if(_fileContent.isNull())return result; if(_fileContent.isEmpty())return result; text=_fileContent; text=ReplaceEndlineTolinuxFormat(text); // QFile out("out.txt"); // out.open(QFile::ReadWrite); // out.write(text.toLatin1()); // out.close(); QStringList bcomments= GetBlockComments(text); foreach (QString bcomment, bcomments) { text=text.replace(bcomment,""); } QStringList comments= GetLineComments(text); foreach (QString commnet, comments) { text=text.replace(commnet,""); } QStringList Includes= GetIncludes(text); foreach (QString include, Includes) { text=text.replace(include,""); } QStringList gaurds= GetIncludeGaurds(text); foreach (QString gaurd, gaurds) { text=text.replace(gaurd,""); } QStringList defines= GetDefines(text); foreach (QString define, defines) { text=text.replace(define,""); } text=RemoveEmptyLines(text); //qDebug()<<"==========================="<<text; QList<CPPClass> cs= GetClassSignature(text); return cs; } //=============================================================================== QStringList Parser::GetFunctionNames() { QStringList result; QString text; if(_fileContent.isNull())return result; if(_fileContent.isEmpty())return result; text=_fileContent; QStringList bcomments= GetBlockComments(text); foreach (QString bcomment, bcomments) { text=text.replace(bcomment,""); } QStringList comments= GetLineComments(text); foreach (QString commnet, comments) { text=text.replace(commnet,""); } QStringList Includes= GetIncludes(text); foreach (QString include, Includes) { text=text.replace(include,""); } QList<QPoint> parentBraces=GetParentBraces(text); QStringList bracesTexts; for (int i=0;i<parentBraces.count();i++) { bracesTexts.append(text.mid(parentBraces[i].x(),parentBraces[i].y()-parentBraces[i].x()+1)); } foreach (QString brace, bracesTexts) { text.replace(brace,"{}"); } QStringList ans; ans.append( text.split("{}")); //regex for{}-> \{\s*} //between two()-> \((.*?)\) for (int i=0;i<result.count();i++) { ans[i]=ans[i].trimmed(); if(ans[i].contains("\n"))ans[i]=""; } for (int i=0;i<ans.count();i++) { if(ans.isEmpty())continue; QString str=ans[i].trimmed(); if(!str.isEmpty()) result.append(str); } //result.append(text); return result; } //=============================================================================== QList<QPoint> Parser::GetParentBraces(QString input) { QList< QPoint> result; int openCount=-1; QPoint point; for (int i=0;i<input.count();i++) { if(input[i]=='{' ) { if(openCount<0){ openCount++; point.setX(i); } openCount++; } if(input[i]=='}') { point.setY(i); openCount--; } if(openCount==0){ result.append(point); openCount--; } } return result; }
24.613924
100
0.521471
amin-amani