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
108
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
67k
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
10e56a5e55e1c3d338d4b3c492b43a236d0e59f9
6,264
cpp
C++
cpgf/test/reflection/test_reflection_enum.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
null
null
null
cpgf/test/reflection/test_reflection_enum.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
null
null
null
cpgf/test/reflection/test_reflection_enum.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
1
2018-12-31T17:01:56.000Z
2018-12-31T17:01:56.000Z
#include "test_reflection_common.h" #define CLASS TestClass_Enum #define NAME_CLASS GPP_STRINGIZE(CLASS) #define ENUM(f) pointerAssign(en, metaClass->getEnum(# f)) using namespace std; using namespace cpgf; namespace Test_Enum { namespace { class CLASS { public: enum EnumFirst { ws1, ws2, ws3, ws4 }; enum EnumSecond { bs1 = 1, bs2 = 3, bs3 = 5, bs4 = 7, bs5 = 0x1fffffff, }; }; // class CLASS G_AUTO_RUN_BEFORE_MAIN() { using namespace cpgf; GDefineMetaClass<CLASS> ::define(NAME_CLASS) ._enum<CLASS::EnumFirst>("EnumFirst") ._element("ws1", CLASS::ws1) ._element("ws2", CLASS::ws2) ._element("ws3", CLASS::ws3) ._element("ws4", CLASS::ws4) ._enum<CLASS::EnumSecond>("EnumSecond") ._element("bs1", CLASS::bs1) ._element("bs2", CLASS::bs2) ._element("bs3", CLASS::bs3) ._element("bs4", CLASS::bs4) ._element("bs5", CLASS::bs5) ; } GTEST(Lib_Exists) { const GMetaClass * metaClass = findMetaClass(NAME_CLASS); GCHECK(metaClass); const GMetaEnum * en; ENUM(EnumFirst); GCHECK(en); ENUM(EnumSecond); GCHECK(en); } GTEST(API_Exists) { GScopedInterface<IMetaService> service(createDefaultMetaService()); GCHECK(service); GScopedInterface<IMetaClass> metaClass(service->findClassByName(NAME_CLASS)); GCHECK(metaClass); GScopedInterface<IMetaEnum> en; ENUM(EnumFirst); GCHECK(en); ENUM(EnumSecond); GCHECK(en); } GTEST(Lib_GetCount) { const GMetaClass * metaClass = findMetaClass(NAME_CLASS); GCHECK(metaClass); const GMetaEnum * en; ENUM(EnumFirst); GEQUAL(en->getCount(), 4); ENUM(EnumSecond); GEQUAL(en->getCount(), 5); } GTEST(API_GetCount) { GScopedInterface<IMetaService> service(createDefaultMetaService()); GCHECK(service); GScopedInterface<IMetaClass> metaClass(service->findClassByName(NAME_CLASS)); GCHECK(metaClass); GScopedInterface<IMetaEnum> en; ENUM(EnumFirst); GEQUAL(en->getCount(), 4); ENUM(EnumSecond); GEQUAL(en->getCount(), 5); } GTEST(Lib_GetKey) { const GMetaClass * metaClass = findMetaClass(NAME_CLASS); GCHECK(metaClass); const GMetaEnum * en; ENUM(EnumFirst); GEQUAL(en->getKey(0), string("ws1")); GEQUAL(en->getKey(1), string("ws2")); GEQUAL(en->getKey(2), string("ws3")); GEQUAL(en->getKey(3), string("ws4")); GEQUAL(en->getKey(5), NULL); ENUM(EnumSecond); GEQUAL(en->getKey(0), string("bs1")); GEQUAL(en->getKey(1), string("bs2")); GEQUAL(en->getKey(2), string("bs3")); GEQUAL(en->getKey(3), string("bs4")); GEQUAL(en->getKey(4), string("bs5")); GEQUAL(en->getKey(5), NULL); } GTEST(API_GetKey) { GScopedInterface<IMetaService> service(createDefaultMetaService()); GCHECK(service); GScopedInterface<IMetaClass> metaClass(service->findClassByName(NAME_CLASS)); GCHECK(metaClass); GScopedInterface<IMetaEnum> en; ENUM(EnumFirst); GEQUAL(en->getKey(0), string("ws1")); GEQUAL(en->getKey(1), string("ws2")); GEQUAL(en->getKey(2), string("ws3")); GEQUAL(en->getKey(3), string("ws4")); GEQUAL(en->getKey(5), NULL); ENUM(EnumSecond); GEQUAL(en->getKey(0), string("bs1")); GEQUAL(en->getKey(1), string("bs2")); GEQUAL(en->getKey(2), string("bs3")); GEQUAL(en->getKey(3), string("bs4")); GEQUAL(en->getKey(4), string("bs5")); GEQUAL(en->getKey(5), NULL); } GTEST(Lib_GetValue) { const GMetaClass * metaClass = findMetaClass(NAME_CLASS); GCHECK(metaClass); const GMetaEnum * en; ENUM(EnumFirst); GEQUAL(fromVariant<int>(en->getValue(0)), CLASS::ws1); GEQUAL(fromVariant<int>(en->getValue(1)), CLASS::ws2); GEQUAL(fromVariant<int>(en->getValue(2)), CLASS::ws3); GEQUAL(fromVariant<int>(en->getValue(3)), CLASS::ws4); ENUM(EnumSecond); GEQUAL(fromVariant<int>(en->getValue(0)), CLASS::bs1); GEQUAL(fromVariant<int>(en->getValue(1)), CLASS::bs2); GEQUAL(fromVariant<int>(en->getValue(2)), CLASS::bs3); GEQUAL(fromVariant<int>(en->getValue(3)), CLASS::bs4); GEQUAL(fromVariant<long long>(en->getValue(4)), CLASS::bs5); } GTEST(API_GetValue) { GScopedInterface<IMetaService> service(createDefaultMetaService()); GCHECK(service); GScopedInterface<IMetaClass> metaClass(service->findClassByName(NAME_CLASS)); GCHECK(metaClass); GScopedInterface<IMetaEnum> en; ENUM(EnumFirst); GEQUAL(fromVariant<int>(metaGetEnumValue(en.get(), 0)), CLASS::ws1); GEQUAL(fromVariant<int>(metaGetEnumValue(en.get(), 1)), CLASS::ws2); GEQUAL(fromVariant<int>(metaGetEnumValue(en.get(), 2)), CLASS::ws3); GEQUAL(fromVariant<int>(metaGetEnumValue(en.get(), 3)), CLASS::ws4); ENUM(EnumSecond); GEQUAL(fromVariant<int>(metaGetEnumValue(en.get(), 0)), CLASS::bs1); GEQUAL(fromVariant<int>(metaGetEnumValue(en.get(), 1)), CLASS::bs2); GEQUAL(fromVariant<int>(metaGetEnumValue(en.get(), 2)), CLASS::bs3); GEQUAL(fromVariant<int>(metaGetEnumValue(en.get(), 3)), CLASS::bs4); GEQUAL(fromVariant<long long>(metaGetEnumValue(en.get(), 4)), CLASS::bs5); } GTEST(Lib_FindKey) { const GMetaClass * metaClass = findMetaClass(NAME_CLASS); GCHECK(metaClass); const GMetaEnum * en; ENUM(EnumFirst); GEQUAL(en->findKey("ws1"), 0); GEQUAL(en->findKey("ws2"), 1); GEQUAL(en->findKey("ws3"), 2); GEQUAL(en->findKey("ws4"), 3); GEQUAL(en->findKey("no"), -1); ENUM(EnumSecond); GEQUAL(en->findKey("bs1"), 0); GEQUAL(en->findKey("bs2"), 1); GEQUAL(en->findKey("bs3"), 2); GEQUAL(en->findKey("bs4"), 3); GEQUAL(en->findKey("bs5"), 4); GEQUAL(en->findKey("no"), -1); } GTEST(API_FindKey) { GScopedInterface<IMetaService> service(createDefaultMetaService()); GCHECK(service); GScopedInterface<IMetaClass> metaClass(service->findClassByName(NAME_CLASS)); GCHECK(metaClass); GScopedInterface<IMetaEnum> en; ENUM(EnumFirst); GEQUAL(en->findKey("ws1"), 0); GEQUAL(en->findKey("ws2"), 1); GEQUAL(en->findKey("ws3"), 2); GEQUAL(en->findKey("ws4"), 3); GEQUAL(en->findKey("no"), -1); ENUM(EnumSecond); GEQUAL(en->findKey("bs1"), 0); GEQUAL(en->findKey("bs2"), 1); GEQUAL(en->findKey("bs3"), 2); GEQUAL(en->findKey("bs4"), 3); GEQUAL(en->findKey("bs5"), 4); GEQUAL(en->findKey("no"), -1); } } }
23.2
79
0.662835
mousepawmedia
10e64d7aa88521a403a2effb753e355d74f9ec54
2,063
cpp
C++
Samples/DMUnitTest/TestCase/DMRes_Test.cpp
Watch-Later/REDM
bf0672e015bb0c9088b4c10f14d5c5ebcac734f2
[ "MIT" ]
38
2020-06-23T00:29:22.000Z
2022-03-24T07:48:22.000Z
Samples/DMUnitTest/TestCase/DMRes_Test.cpp
Watch-Later/REDM
bf0672e015bb0c9088b4c10f14d5c5ebcac734f2
[ "MIT" ]
9
2020-06-23T02:50:59.000Z
2021-03-25T12:17:22.000Z
Samples/DMUnitTest/TestCase/DMRes_Test.cpp
Watch-Later/REDM
bf0672e015bb0c9088b4c10f14d5c5ebcac734f2
[ "MIT" ]
20
2020-06-23T01:29:23.000Z
2021-09-15T01:32:30.000Z
//------------------------------------------------------- // Copyright (c) DuiMagic // All rights reserved. // // File Name: DMRes_Test.cpp // File Des: 测试资源打包方式的测试用例 // File Summary: // Cur Version: 1.0 // Author: // Create Data: // History: // <Author> <Time> <Version> <Des> // guoyou 2015-1-11 1.0 //------------------------------------------------------- #pragma once #include "DMUintTestAfx.h" class DMResTest:public::testing::Test { public: virtual void SetUp() { } virtual void TearDown() { } }; TEST_F(DMResTest,测试Res文件夹打包) { EXPECT_EQ(DMSUCCEEDED(g_pDMApp->LoadResPack((WPARAM)L"UTRes",NULL,"DMResFolderImpl")),true); // 测试内置的DMResFolderImpl类是否正常 DMSmartPtrT<IDMRes> m_pRes; EXPECT_EQ(DMSUCCEEDED(g_pDMApp->GetDefRegObj((void**)&m_pRes, DMREG_Res)),true); //EXPECT_EQ(DMSUCCEEDED(g_pDMApp->CreateRegObj((void**)&m_pRes,L"DMResFolderImpl",DMREG_Res)),true); // 解包功能 EXPECT_EQ(DMSUCCEEDED(m_pRes->LoadResPack((WPARAM)(L"UTRes"),NULL)),true); // 判断layout中的XML_MAINWND是否存在 EXPECT_EQ(DMSUCCEEDED(m_pRes->IsItemExists(RES_LAYOUT,"dui_main")),true); EXPECT_EQ(DMSUCCEEDED(m_pRes->IsItemExists(RES_LAYOUT,"dui_main1")),false); // 判断theme中的Btn_Restore是否存在 EXPECT_EQ(DMSUCCEEDED(m_pRes->IsItemExists("png","Btn_Restore")),true); // 取得default主题下的btn_menu unsigned long size1 = 0; EXPECT_EQ(DMSUCCEEDED(m_pRes->GetItemSize("png","Btn_Menu",size1)),true); DMBufT<byte>pBuf;; EXPECT_EQ(DMSUCCEEDED(m_pRes->GetItemBuf("png","Btn_Menu",pBuf,&size1)),true); EXPECT_EQ(DMSUCCEEDED(m_pRes->SetCurTheme("theme1")),true); EXPECT_EQ(DMSUCCEEDED(m_pRes->IsItemExists("png","Btn_Restore")),true); EXPECT_EQ(DMSUCCEEDED(m_pRes->GetItemSize("png","Btn_Menu",size1)),true); EXPECT_EQ(DMSUCCEEDED(m_pRes->GetItemSize("png","Btn_Restore",size1)),true); // 外部加载皮肤功能 EXPECT_EQ(DMSUCCEEDED(m_pRes->LoadTheme((WPARAM)L"theme2",(LPARAM)L"UTRes\\themes\\theme2\\dmindex.xml")),true); EXPECT_EQ(DMSUCCEEDED(m_pRes->SetCurTheme("theme2")),true); EXPECT_EQ(DMSUCCEEDED(m_pRes->GetItemSize("png","Btn_Menu",size1)),true); }
28.652778
113
0.690742
Watch-Later
10e685ac1b1e881d975152a1b52cb827140e6c96
795
cpp
C++
C++ Primer/chapter-9/9.27.cpp
grasslog/github-blog
1e09025f068774659b4bc26b7f0ad4aa1a3fbd43
[ "MIT" ]
1
2019-05-16T07:51:12.000Z
2019-05-16T07:51:12.000Z
C++ Primer/chapter-9/9.27.cpp
grasslog/github-blog
1e09025f068774659b4bc26b7f0ad4aa1a3fbd43
[ "MIT" ]
null
null
null
C++ Primer/chapter-9/9.27.cpp
grasslog/github-blog
1e09025f068774659b4bc26b7f0ad4aa1a3fbd43
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> #include <forward_list> using namespace std; int main(int argc, char **argv) { int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89}; forward_list<int> forward_list1(ia, ia+9); forward_list<int>::iterator it1 = forward_list1.begin(); forward_list<int>::iterator it2 = forward_list1.before_begin(); while(it1 != forward_list1.end()) { if((*it1)%2 == 1) { it1 = forward_list1.erase_after(it2); } else { it2 = it1; ++it1; } } forward_list<int>::iterator it4 = forward_list1.begin(); for(it4; it4 != forward_list1.end(); ++it4) { cout << *it4 << " "; } return 0; }
20.921053
67
0.54717
grasslog
10e8650fe8ef68bfbb745245a81a0f49829b167c
3,001
cpp
C++
src/providers/CIM_DiskDrive/CIM_DiskDrive_Provider.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
4
2015-12-16T06:43:14.000Z
2020-01-24T06:05:47.000Z
src/providers/CIM_DiskDrive/CIM_DiskDrive_Provider.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
src/providers/CIM_DiskDrive/CIM_DiskDrive_Provider.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
#include "CIM_DiskDrive_Provider.h" CIMPLE_NAMESPACE_BEGIN CIM_DiskDrive_Provider::CIM_DiskDrive_Provider() { } CIM_DiskDrive_Provider::~CIM_DiskDrive_Provider() { } Load_Status CIM_DiskDrive_Provider::load() { return LOAD_OK; } Unload_Status CIM_DiskDrive_Provider::unload() { return UNLOAD_OK; } Get_Instance_Status CIM_DiskDrive_Provider::get_instance( const CIM_DiskDrive* model, CIM_DiskDrive*& instance) { return GET_INSTANCE_UNSUPPORTED; } Enum_Instances_Status CIM_DiskDrive_Provider::enum_instances( const CIM_DiskDrive* model, Enum_Instances_Handler<CIM_DiskDrive>* handler) { return ENUM_INSTANCES_OK; } Create_Instance_Status CIM_DiskDrive_Provider::create_instance( CIM_DiskDrive* instance) { return CREATE_INSTANCE_UNSUPPORTED; } Delete_Instance_Status CIM_DiskDrive_Provider::delete_instance( const CIM_DiskDrive* instance) { return DELETE_INSTANCE_UNSUPPORTED; } Modify_Instance_Status CIM_DiskDrive_Provider::modify_instance( const CIM_DiskDrive* model, const CIM_DiskDrive* instance) { return MODIFY_INSTANCE_UNSUPPORTED; } Invoke_Method_Status CIM_DiskDrive_Provider::RequestStateChange( const CIM_DiskDrive* self, const Property<uint16>& RequestedState, CIM_ConcreteJob*& Job, const Property<Datetime>& TimeoutPeriod, Property<uint32>& return_value) { return INVOKE_METHOD_UNSUPPORTED; } Invoke_Method_Status CIM_DiskDrive_Provider::SetPowerState( const CIM_DiskDrive* self, const Property<uint16>& PowerState, const Property<Datetime>& Time, Property<uint32>& return_value) { return INVOKE_METHOD_UNSUPPORTED; } Invoke_Method_Status CIM_DiskDrive_Provider::Reset( const CIM_DiskDrive* self, Property<uint32>& return_value) { return INVOKE_METHOD_UNSUPPORTED; } Invoke_Method_Status CIM_DiskDrive_Provider::EnableDevice( const CIM_DiskDrive* self, const Property<boolean>& Enabled, Property<uint32>& return_value) { return INVOKE_METHOD_UNSUPPORTED; } Invoke_Method_Status CIM_DiskDrive_Provider::OnlineDevice( const CIM_DiskDrive* self, const Property<boolean>& Online, Property<uint32>& return_value) { return INVOKE_METHOD_UNSUPPORTED; } Invoke_Method_Status CIM_DiskDrive_Provider::QuiesceDevice( const CIM_DiskDrive* self, const Property<boolean>& Quiesce, Property<uint32>& return_value) { return INVOKE_METHOD_UNSUPPORTED; } Invoke_Method_Status CIM_DiskDrive_Provider::SaveProperties( const CIM_DiskDrive* self, Property<uint32>& return_value) { return INVOKE_METHOD_UNSUPPORTED; } Invoke_Method_Status CIM_DiskDrive_Provider::RestoreProperties( const CIM_DiskDrive* self, Property<uint32>& return_value) { return INVOKE_METHOD_UNSUPPORTED; } Invoke_Method_Status CIM_DiskDrive_Provider::LockMedia( const CIM_DiskDrive* self, const Property<boolean>& Lock, Property<uint32>& return_value) { return INVOKE_METHOD_UNSUPPORTED; } CIMPLE_NAMESPACE_END
23.084615
64
0.784738
LegalizeAdulthood
10ebaf8f0371d9ab8cf9a5fc19805763e3b53d75
3,097
cpp
C++
impl/jamtemplate/common/tilemap/tile_layer.cpp
runvs/Alakajam14
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
[ "CC0-1.0" ]
null
null
null
impl/jamtemplate/common/tilemap/tile_layer.cpp
runvs/Alakajam14
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
[ "CC0-1.0" ]
null
null
null
impl/jamtemplate/common/tilemap/tile_layer.cpp
runvs/Alakajam14
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
[ "CC0-1.0" ]
null
null
null
#include "tile_layer.hpp" #include "conversions.hpp" #include "drawable_helpers.hpp" #include "shape.hpp" #include <memory> namespace jt { namespace tilemap { TileLayer::TileLayer( std::vector<TileInfo> const& tileInfo, std::vector<std::shared_ptr<jt::Sprite>> tileSetSprites) : m_tileSetSprites { tileSetSprites } , m_tiles { tileInfo } { } TileLayer::TileLayer( std::tuple<std::vector<TileInfo> const&, std::vector<std::shared_ptr<jt::Sprite>>> mapInfo) : TileLayer { std::get<0>(mapInfo), std::get<1>(mapInfo) } { } bool TileLayer::isTileVisible(TileInfo const& tile) const { if (m_screenSizeHint.x == 0 && m_screenSizeHint.y == 0) { return true; } jt::Vector2f const camOffset = getStaticCamOffset(); if (tile.position.x + camOffset.x + tile.size.x < 0) { return false; } if (tile.position.y + camOffset.y + tile.size.y < 0) { return false; } if (tile.position.x + camOffset.x >= this->m_screenSizeHint.x + tile.size.x) { return false; } if (tile.position.y + camOffset.y >= this->m_screenSizeHint.y + tile.size.y) { return false; } return true; } void TileLayer::doDraw(std::shared_ptr<jt::RenderTarget> const sptr) const { if (!sptr) { return; } auto const posOffset = m_position + getShakeOffset() + getOffset(); for (auto const& tile : m_tiles) { // optimization: don't draw tiles which are not visible in this frame if (!isTileVisible(tile)) { continue; } auto const pixelPosForTile = tile.position + posOffset; auto const id = tile.id; this->m_tileSetSprites.at(id)->setPosition(jt::Vector2f { pixelPosForTile.x * this->m_scale.x, pixelPosForTile.y * this->m_scale.y }); this->m_tileSetSprites.at(id)->setScale(this->m_scale); this->m_tileSetSprites.at(id)->update(0.0f); this->m_tileSetSprites.at(id)->draw(sptr); } } void TileLayer::doDrawFlash(std::shared_ptr<jt::RenderTarget> const /*sptr*/) const { } void TileLayer::doDrawShadow(std::shared_ptr<jt::RenderTarget> const /*sptr*/) const { } void TileLayer::doUpdate(float /*elapsed*/) { } void TileLayer::setColor(jt::Color const& col) { for (auto& ts : m_tileSetSprites) { ts->setColor(col); } m_color = col; } jt::Color TileLayer::getColor() const { return m_color; } void TileLayer::setPosition(jt::Vector2f const& pos) { m_position = pos; } jt::Vector2f TileLayer::getPosition() const { return m_position; } jt::Rectf TileLayer::getGlobalBounds() const { return jt::Rectf {}; } jt::Rectf TileLayer::getLocalBounds() const { return jt::Rectf {}; } void TileLayer::setScale(jt::Vector2f const& scale) { m_scale = scale; } jt::Vector2f TileLayer::getScale() const { return m_scale; } void TileLayer::setOrigin(jt::Vector2f const& origin) { m_origin = origin; } jt::Vector2f TileLayer::getOrigin() const { return m_origin; } void TileLayer::doRotate(float /*rot*/) { } bool TileLayer::isVisible() const { return true; } } // namespace tilemap } // namespace jt
30.97
99
0.658379
runvs
10ec694f24a5389f27139a32b47b5eae1c58b3dd
70,515
cpp
C++
debug/client/wince/WinCESystem.cpp
myArea51/binnavi
021e62dcb7c3fae2a99064b0ea497cb221dc7238
[ "Apache-2.0" ]
3,083
2015-08-19T13:31:12.000Z
2022-03-30T09:22:21.000Z
debug/client/wince/WinCESystem.cpp
Jason-Cooke/binnavi
b98b191d8132cbde7186b486d23a217fcab4ec44
[ "Apache-2.0" ]
99
2015-08-19T14:42:49.000Z
2021-04-13T10:58:32.000Z
debug/client/wince/WinCESystem.cpp
Jason-Cooke/binnavi
b98b191d8132cbde7186b486d23a217fcab4ec44
[ "Apache-2.0" ]
613
2015-08-19T14:15:44.000Z
2022-03-26T04:40:55.000Z
// Copyright 2011-2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "WinCESystem.hpp" #include <algorithm> #include <iostream> #include <winnt.h> #include <winbase.h> #include <psapi.h> #include <tlhelp32.h> //#include <pkfuncs.h> #include <zycon/src/zycon.h> #include "../errors.hpp" #include "../DebuggerOptions.hpp" #include "../logger.hpp" #include "gdb_arm.h" /* * SetProcPermissions is a kernel api available on WM 5.0 and below, giving the * calling process extended rights. * Since its not defined in the standard sdk's header files the following * construction is necesarry. */ extern "C" { DWORD GetCurrentPermissions(void); DWORD SetProcPermissions(DWORD newperms); BOOL WINAPI SetKMode(BOOL fMode); } /* Flags for CacheSync/CacheRangeFlush */ #define CACHE_SYNC_DISCARD 0x001 /* write back & discard all cached data */ #define CACHE_SYNC_INSTRUCTIONS 0x002 /* discard all cached instructions */ #define CACHE_SYNC_WRITEBACK 0x004 /* write back but don't discard data \ cache*/ #define CACHE_SYNC_FLUSH_I_TLB 0x008 /* flush I-TLB */ #define CACHE_SYNC_FLUSH_D_TLB 0x010 /* flush D-TLB */ #define CACHE_SYNC_FLUSH_TLB \ (CACHE_SYNC_FLUSH_I_TLB | CACHE_SYNC_FLUSH_D_TLB) /* flush all TLB */ #define CACHE_SYNC_L2_WRITEBACK 0x020 /* write-back L2 Cache */ #define CACHE_SYNC_L2_DISCARD 0x040 /* discard L2 Cache */ #define CACHE_SYNC_ALL 0x07F /* sync and discard everything in Cache/TLB */ /* * The CacheSync and CacheRangeFlush functions are locatet in recent versions of * the coredll.dll */ extern "C" { void CacheSync(int flags); void CacheRangeFlush(void* pAddr, unsigned long dwLength, unsigned long dwFlags); } /* ARM Type Breakpoint */ #define BPX_ARM 0xE6000010 #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif /** * Conversion function that takes a TCHAR and converts it to a std::string */ std::string TCharToString(LPCTSTR t) { // Handy for converting TCHAR to std::string (char) // If the conversion fails, an empty string is returned. std::string str; #ifdef UNICODE // calculate the size of the char string required // Note: If wcstombs encounters a wide character it cannot convert // to a multibyte character, it returns 1. int len = 1 + wcstombs(0, t, 0); if (0 == len) return str; char* c = new char[len]; c[0] = '\0'; wcstombs(c, t, len); str = c; delete[] c; #else str = t; #endif return str; } /* * Conversion function that takes a LPWSTR and converts it to a std::string */ bool LPWSTRToString(std::string& s, const LPWSTR pw, UINT codepage = CP_ACP) { bool res = false; char* p = 0; int bsz; bsz = WideCharToMultiByte(codepage, 0, pw, -1, 0, 0, 0, 0); if (bsz > 0) { p = new char[bsz]; int rc = WideCharToMultiByte(codepage, 0, pw, -1, p, bsz, 0, 0); if (rc != 0) { p[bsz - 1] = 0; s = p; res = true; } } delete[] p; return res; } void dbg_echo_MEMORY_BASIC_INFORMATION(MEMORY_BASIC_INFORMATION* m) { msglog->log(LOG_VERBOSE, "Base: %lx", m->BaseAddress); msglog->log(LOG_VERBOSE, "AllocationBase: %lx", m->AllocationBase); msglog->log(LOG_VERBOSE, "AllocationProtect: %lx", m->AllocationProtect); msglog->log(LOG_VERBOSE, "RegionSize: %lx", m->RegionSize); msglog->log(LOG_VERBOSE, "state: %lx", m->State); msglog->log(LOG_VERBOSE, "Protect: %lx", m->Protect); msglog->log(LOG_VERBOSE, "Type: %lx", m->Type); } /** * DLL load / unload handler * * @param LPVOID moduleBaseAddress The Base Address of the module in the debug * event. * @param DWORD processID The process id of the process that created the debug * event. * @param CPUADDRESS imageNamePtr An address ptr pointing to the name of the * module. * @param int isUnicode indication from the debug event if the name Ptr is * unicode. * @param bool load indication if the debug event is a load event or an unload * event. */ NaviError WinCESystem::dllDebugEventHandler(LPVOID moduleBaseAddress, DWORD processID, CPUADDRESS imageNamePtr, int isUnicode, bool load) { // String to hold the complete path infromation about the newly loaded DLL TCHAR moduleName[MAX_PATH] = L"\0"; // String that has the information about the module in std::string format std::string moduleNameString; // Module handle HMODULE hModule = NULL; // Get the filename of the loaded DLL by the handle from the debug event PtrToString(processID, imageNamePtr, MAX_PATH - 1, isUnicode, moduleName); DWORD moduleBaseSize = 23; // Convert the recieved name to a std::string if (!LPWSTRToString(moduleNameString, moduleName, 0)) { msglog->log(LOG_VERBOSE, "Error: conversion from LPWSTR to std::string failed at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::COULDNT_FIND_DATA; } Module currentModule(moduleNameString, moduleNameString, (CPUADDRESS) moduleBaseAddress, moduleBaseSize); if (load) { NaviError moduleLoadingError = moduleLoaded(currentModule); if (moduleLoadingError) { msglog->log(LOG_ALWAYS, "Error: Could not handle module (un)loading at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::COULDNT_FIND_DATA; } this->modules.push_back(currentModule); } else { // unload case. for (std::vector<Module>::iterator Iter = this->modules.begin(); Iter != this->modules.end(); ++Iter) { if (currentModule == *Iter) { this->modules.erase(Iter); NaviError moduleLoadingError = moduleUnloaded(currentModule); if (moduleLoadingError) { msglog->log(LOG_ALWAYS, "Error: Could not handle module (un)loading at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::COULDNT_FIND_DATA; } } } } return NaviErrors::SUCCESS; } /** * Makes a page of the target process memory writable. * * @param hProcess The handle of the target process. * @param offset The offset whose page should be made restored. * @param oldProtection The original protection level of the page. */ bool makePageWritable(HANDLE hProcess, CPUADDRESS offset, DWORD& oldProtection) { MEMORY_BASIC_INFORMATION mem; // Check if the location is read-only int returned = VirtualQuery(reinterpret_cast<void*>(offset), &mem, sizeof(mem)); if (returned != sizeof(mem)) { msglog->log(LOG_VERBOSE, "Error: Invalid return value of VirtualQuery at %s:%d", __FUNCTION__, __LINE__); return false; } if (!(mem.AllocationProtect & PAGE_READWRITE)) { if (!VirtualProtect(reinterpret_cast<void*>(offset), 4, PAGE_EXECUTE_READWRITE, &oldProtection)) { msglog->log(LOG_VERBOSE, "Error: VirtualProtect failed at %s:%d with (%d)", __FUNCTION__, __LINE__, GetLastError()); return false; } } return true; } /** * Restores the old protection level of a page of the target process memory. * * @param hProcess The handle of the target process. * @param offset The offset whose page should be made restored. * @param oldProtection The original protection level of the page. */ NaviError restoreMemoryProtection(HANDLE hProcess, CPUADDRESS offset, DWORD oldProtection) { msglog->log(LOG_ALL, "Info: old protection level: %08X", oldProtection); DWORD oldProtection2 = 0; if (!VirtualProtect(reinterpret_cast<void*>(offset), 4, oldProtection, &oldProtection2)) { msglog->log( LOG_VERBOSE, "Error: Resetting VirtualProtect state failed at %s:%d with (%d)", __FUNCTION__, __LINE__, GetLastError()); return NaviErrors::PAGE_NOT_WRITABLE; } return NaviErrors::SUCCESS; } /** * Helper function that writes a vector of bytes to the process memory of the * target process. * */ NaviError writeBytes(HANDLE hProcess, CPUADDRESS offset, std::vector<char> data) { DWORD oldPermission = 0; DWORD oldProtection = 0; // Save the old permissions to later restore them oldPermission = GetCurrentPermissions(); // Set the permissions for full access on all threads SetProcPermissions(0xFFFFFFFF); // Try to make the page writable for us if (!makePageWritable(hProcess, offset, oldProtection)) { msglog->log(LOG_VERBOSE, "Error: Couldn't make page read/writable at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::PAGE_NOT_WRITABLE; } SIZE_T writtenbytes = 0; // Write the byte to the target process memory if (!WriteProcessMemory(hProcess, reinterpret_cast<void*>(offset), &data[0], data.size(), &writtenbytes)) { msglog->log(LOG_VERBOSE, "Error: WriteProcessMemory failed at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::COULDNT_WRITE_MEMORY; } // CacheSync invalidates the cache and makes the written data usable // See http://msdn.microsoft.com/en-us/library/aa911523.aspx //CacheSync(CACHE_SYNC_ALL); if (!FlushInstructionCache(hProcess, 0, 0)) { msglog->log( LOG_VERBOSE, "Error: Couldn't flush instruction cache at %s:%d with (Code: %d) ", __FUNCTION__, __LINE__, GetLastError()); return NaviErrors::UNSUPPORTED; } if (restoreMemoryProtection(hProcess, offset, oldProtection)) { msglog->log(LOG_VERBOSE, "Error: Couldn't restore old memory protection at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::PAGE_NOT_WRITABLE; } // restore the access permissions SetProcPermissions(oldPermission); return NaviErrors::SUCCESS; } /** * Helper function that writes a single byte to the process memory of the target * process. * * @param hProcess Process handle of the target process. * @param offset Memory offset to write to. * @param b Byte to write to the target process memory. * * @return A NaviError code that describes whether the operation was successful * or not. */ NaviError writeByte(HANDLE hProcess, CPUADDRESS offset, char b) { DWORD oldPermission = 0; DWORD oldProtection = 0; // Save the old permissions to later restore them oldPermission = GetCurrentPermissions(); // Set the permissions for full access on all threads SetProcPermissions(0xFFFFFFFF); // Try to make the page writable for us if (!makePageWritable(hProcess, offset, oldProtection)) { msglog->log(LOG_VERBOSE, "Error: Couldn't make page read/writable at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::PAGE_NOT_WRITABLE; } SIZE_T writtenbytes = 0; // Write the byte to the target process memory if (!WriteProcessMemory(hProcess, reinterpret_cast<void*>(offset), &b, 1, &writtenbytes)) { msglog->log(LOG_VERBOSE, "Error: WriteProcessMemory failed at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::COULDNT_WRITE_MEMORY; } // CacheSync invalidates the cache and makes the written data usable // See http://msdn.microsoft.com/en-us/library/aa911523.aspx //CacheSync(CACHE_SYNC_ALL); if (!FlushInstructionCache(hProcess, 0, 0)) { msglog->log( LOG_VERBOSE, "Error: Couldn't flush instruction cache at %s:%d with (Code: %d) ", __FUNCTION__, __LINE__, GetLastError()); return NaviErrors::UNSUPPORTED; } if (restoreMemoryProtection(hProcess, offset, oldProtection)) { msglog->log(LOG_VERBOSE, "Error: Couldn't restore old memory protection at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::PAGE_NOT_WRITABLE; } // restore the access permissions SetProcPermissions(oldPermission); return NaviErrors::SUCCESS; } /** * Helper function that writes a single DWORD to the process memory of the target * process. * * @param hProcess Process handle of the target process. * @param offset Memory offset to write to. * @param d DWORD to write to the target process memory. * * @return A NaviError code that describes whether the operation was successful * or not. */ NaviError writeDWORD(HANDLE hProcess, CPUADDRESS offset, unsigned int d) { // std::cout << "Entering: " << __FUNCTIONW__ << std::endl; DWORD oldPermission = 0; DWORD oldProtection = 0; // Save the old permissions to later restore them oldPermission = GetCurrentPermissions(); // Set the permissions for full access on all threads SetProcPermissions(0xFFFFFFFF); // Try to make page writable for us if (!makePageWritable(hProcess, offset, oldProtection)) { msglog->log(LOG_VERBOSE, "Error: Couldn't make page read/writable at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::PAGE_NOT_WRITABLE; } SIZE_T writtenbytes = 0; // Write the DWORD to the target process memory if (!WriteProcessMemory(hProcess, reinterpret_cast<void*>(offset), &d, 4, &writtenbytes)) { msglog->log(LOG_VERBOSE, "Error: WriteProcessMemory failed at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::COULDNT_WRITE_MEMORY; } // CacheSync invalidates the cache and makes the written data usable // See http://msdn.microsoft.com/en-us/library/aa911523.aspx //CacheSync(CACHE_SYNC_ALL); if (!FlushInstructionCache(hProcess, 0, 0)) { msglog->log( LOG_VERBOSE, "Error: Couldn't flush instruction cache at %s:%d with (Code: %d) ", __FUNCTION__, __LINE__, GetLastError()); return NaviErrors::UNSUPPORTED; } if (restoreMemoryProtection(hProcess, offset, oldProtection)) { msglog->log(LOG_VERBOSE, "Error: Couldn't restore old memory protection at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::PAGE_NOT_WRITABLE; } // Restore the thread access permissions SetProcPermissions(oldPermission); // std::cout << "Exiting: " << __FUNCTIONW__ << std::endl; return NaviErrors::SUCCESS; } NaviError WinCESystem::readMemoryData(char* buffer, CPUADDRESS offset, CPUADDRESS size) { return readMemoryDataInternal(buffer, offset, size, false); } NaviError WinCESystem::readMemoryDataInternal(char* buffer, CPUADDRESS offset, CPUADDRESS size, bool silent) { // SIZE_T outlen; msglog->log(LOG_VERBOSE, "Trying to read %d bytes from memory address %X", size, offset); // Make sure the entire region from addr to addr2 is paged // VirtualQuery(ntohl(addr->low32bits), & meminf, ntohl(addr2->low32bits) - // nothl(addr->low32bits)); DWORD oldPermission = 0; DWORD oldProtection = 0; // Save the old permissions to later restore them oldPermission = GetCurrentPermissions(); // Set the permissions for full access on all threads SetProcPermissions(0xFFFFFFFF); if (!makePageWritable(hProcess, offset, oldProtection)) { msglog->log(LOG_VERBOSE, "Error: Couldn't make page read/writable at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::PAGE_NOT_READABLE; } if (ReadProcessMemory(hProcess, reinterpret_cast<void*>(offset), buffer, size, &outlen) == 0) { if (!silent) { msglog->log(LOG_ALWAYS, "Error: ReadProcessMemory failed (Error Code: %d)", GetLastError()); } return NaviErrors::COULDNT_READ_MEMORY; } restoreMemoryProtection(hProcess, offset, oldProtection); // Restore the thread access permissions SetProcPermissions(oldPermission); return NaviErrors::SUCCESS; } /** * Helper function that reads a WString from the process memory of the target * process. * * @param hProcess Process handle of the target process. * @param offset Memory offset to read from. * @param len in TCHAR to be read from memory max 1023. * @param d The read WString is stored here. * * @return A NaviError code that describes whether the operation was successful * or not. */ NaviError readWString(HANDLE hProcess, CPUADDRESS offset, int len, TCHAR* d) { // DWORD oldPermission = 0; DWORD oldProtection = 0; // Save the old permissions to later restore them oldPermission = GetCurrentPermissions(); // Set the permissions for full access on all threads SetProcPermissions(0xFFFFFFFF); SIZE_T bytesRead = 0; // Try to read the WString from memory if (!ReadProcessMemory(hProcess, reinterpret_cast<void*>(offset), d, len, &bytesRead)) { msglog->log(LOG_VERBOSE, "Error: Couldn't read WString from memory at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::COULDNT_READ_MEMORY; } // restore the thread access permissions SetProcPermissions(oldPermission); return NaviErrors::SUCCESS; } /** * Helper function that reads a WString from the process memory of the target * process. * * @param hProcess Process handle of the target process. * @param offset Memory offset to read from. * @param len in char to be read from memory max 1023. * @param d The read WString is stored here. * * @return A NaviError code that describes whether the operation was successful * or not. */ NaviError readString(HANDLE hProcess, CPUADDRESS offset, int len, char& d) { // DWORD oldPermission = 0; DWORD oldProtection = 0; // Save the old permissions to later restore them oldPermission = GetCurrentPermissions(); // Set the permissions for full access on all threads SetProcPermissions(0xFFFFFFFF); // Try to make page writable for us if (!makePageWritable(hProcess, offset, oldProtection)) { msglog->log(LOG_VERBOSE, "Error: Couldn't make page read/writable at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::PAGE_NOT_READABLE; } SIZE_T bytesRead = 0; // Try to read the WString from memory if (!ReadProcessMemory(hProcess, reinterpret_cast<void*>(offset), &d, min(len, sizeof(d) - 1), &bytesRead)) { restoreMemoryProtection(hProcess, offset, oldProtection); msglog->log(LOG_VERBOSE, "Error: Couldn't read WString from memory at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::COULDNT_READ_MEMORY; } // End the string //d[bytesRead] = 0; restoreMemoryProtection(hProcess, offset, oldProtection); // restore the thread access permissions SetProcPermissions(oldPermission); return NaviErrors::SUCCESS; } /** * Helper function that reads a single DWORD from the process memory of the * target process. * * @param hProcess Process handle of the target process. * @param offset Memory offset to read from. * @param d The read DWORD is stored here. * * @return A NaviError code that describes whether the operation was successful * or not. */ NaviError readDWORD(HANDLE hProcess, CPUADDRESS offset, unsigned int& d) { // DWORD oldPermission = 0; DWORD oldProtection = 0; // Save the old permissions to later restore them oldPermission = GetCurrentPermissions(); // Set the permissions for full access on all threads SetProcPermissions(0xFFFFFFFF); // Try to make page writable for us if (!makePageWritable(hProcess, offset, oldProtection)) { msglog->log(LOG_VERBOSE, "Error: Couldn't make page read/writable at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::PAGE_NOT_READABLE; } SIZE_T bytesRead = 0; // Try to read the DWORD from if (!ReadProcessMemory(hProcess, reinterpret_cast<void*>(offset), &d, 4, &bytesRead)) { restoreMemoryProtection(hProcess, offset, oldProtection); msglog->log(LOG_VERBOSE, "Error: Couldn't read DWORD from memory at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::COULDNT_READ_MEMORY; } restoreMemoryProtection(hProcess, offset, oldProtection); // restore the thread access permissions SetProcPermissions(oldPermission); // std::cout << "Exiting: " << __FUNCTIONW__ << std::endl; return NaviErrors::SUCCESS; } NaviError WinCESystem::writeMemory(CPUADDRESS address, const std::vector<char>& data) { return writeBytes(hProcess, address, data); } /** * Reads a string from memory address ptr * * @param DWORD processID Process ID from whoms memory should be read * @param CPUADDRESS *address AddressPTR from where the string in memory is to * be read * @param int len Length of string to be read from memory * @param int isUnicode determines if the string to be read is a unicode string * or not * @param TCHAR string String which holds the result */ NaviError WinCESystem::PtrToString(DWORD dwProcessId, CPUADDRESS address, int len, int uni, TCHAR* tbuf) { // if (address == NULL) { return NaviErrors::COULDNT_READ_MEMORY; } else if (uni) { readWString((HANDLE) dwProcessId, address, len, tbuf); if (tbuf == NULL) { msglog->log(LOG_ALL, "Error: string is NULL %s", __FUNCTION__); return NaviErrors::COULDNT_READ_MEMORY; } return NaviErrors::SUCCESS; } else { static char buf[1024]; // readString((HANDLE) dwProcessId, address, len, *buf); if (buf == NULL) { msglog->log(LOG_ALL, "Error: string is NULL %s", __FUNCTION__); return NaviErrors::COULDNT_READ_MEMORY; } // convert the char[] to TCHAR[] // _sntprintf(&tbuf, 256, L"%hs", buf); return NaviErrors::SUCCESS; } } /** * Starts a new process for debugging. * * @param path The path to the executable of the process. * @param arguments The vector of arguments passed to the process. * @param tids The thread IDs of the threads that belong to the target process. * @param modules The vector of modules loaded by the target process. * * @return A NaviError code that describes whether the operation was successful * or not. */ NaviError WinCESystem::startProcess( const wchar_t* path, const std::vector<const wchar_t*>& arguments, std::vector<Thread>& tids, std::vector<Module>& modules) { // // Enable full kernel mode BOOL bMode = SetKMode(TRUE); // Save the current permissions so they can be restored DWORD orgPermissions = GetCurrentPermissions(); // Set the permissions with full access to all threads SetProcPermissions(0xFFFFFFFF); PROCESS_INFORMATION pi; if (!CreateProcessW(path, NULL, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, NULL, &pi)) { msglog->log(LOG_VERBOSE, "Error: Couldn't start target process at %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); return NaviErrors::COULDNT_OPEN_TARGET_PROCESS; } // Keep track of the process hanlde of the target process hProcess = OpenProcess(1, false, pi.dwProcessId); setPID(pi.dwProcessId); // Restore permissions to the stored value. SetProcPermissions(orgPermissions); // Keep track of the last thread that caused a debug event setActiveThread(pi.dwThreadId); DEBUG_EVENT dbg_evt; // Wait & skip over all initial messages until the first "real" exception is // hit for (;;) { if (!WinCE_arm_wait_for_debug_event(&dbg_evt, INFINITE)) { // Waiting for a debug event failed => We will no be able to debug msglog->log(LOG_VERBOSE, "Error: WaitForDebugEvent() failed - aborting at %s:%d", __FUNCTION__, __LINE__); CloseHandle(hProcess); return NaviErrors::WAITING_FOR_DEBUG_EVENTS_FAILED; } // Store the id of the last thread that caused the last debug event setActiveThread(dbg_evt.dwThreadId); msglog->log(LOG_VERBOSE, "Received debug event %d", dbg_evt.dwDebugEventCode); if (dbg_evt.dwDebugEventCode == EXCEPTION_DEBUG_EVENT) { msglog->log(LOG_VERBOSE, "Initial debug event received - starting debug loop."); if (dllDebugEventHandler(dbg_evt.u.LoadDll.lpBaseOfDll, dbg_evt.dwProcessId, (CPUADDRESS) dbg_evt.u.LoadDll.lpImageName, dbg_evt.u.LoadDll.fUnicode, true)) { return false; } CloseHandle(hProcess); return NaviErrors::SUCCESS; } else if (dbg_evt.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT) { CREATE_PROCESS_DEBUG_INFO* info = &dbg_evt.u.CreateProcessInfo; hThread = info->hThread; setBaseOfImage((unsigned int) info->lpBaseOfImage); Thread ts(dbg_evt.dwThreadId, SUSPENDED); tids.push_back(ts); this->tids.push_back(ts); return NaviErrors::SUCCESS; } else { msglog->log(LOG_VERBOSE, "Error: Unexpected debug event %d at %s:%d", dbg_evt.dwDebugEventCode, __FUNCTION__, __LINE__); WinCE_arm_resume(dbg_evt.dwThreadId, DBG_EXCEPTION_NOT_HANDLED); } } // std::cout << "Exiting: " << __FUNCTIONW__ << std::endl; return NaviErrors::SUCCESS; } NaviError WinCESystem::attachToProcess(std::vector<Thread>& tids, std::vector<Module>& modules) { // DWORD oldPermission = 0; // Store the current thread access permissions oldPermission = GetCurrentPermissions(); // Set thread access permissions SetProcPermissions(0xFFFFFFFF); // TODO: hProcess must be closed somewhere later msglog->log(LOG_VERBOSE, "Info: Opening process (PID: %d)", getPID()); // Try to open the target process HANDLE hProcess = OpenProcess(0, false, getPID()); if (hProcess == NULL) { msglog->log( LOG_VERBOSE, "Error: failed to OpenProcess() - aborting at %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); // Restore old thread access permissions SetProcPermissions(oldPermission); CloseHandle(hProcess); return NaviErrors::COULDNT_OPEN_TARGET_PROCESS; } msglog->log(LOG_VERBOSE, "Debugging process (PID: %d)", getPID()); // Try to get debugging rights for the target process if (!DebugActiveProcess(getPID())) { msglog->log(LOG_VERBOSE, "Error: DebugActiceProcess() failed - aborting at " "%s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); // Restore old thread access permissions SetProcPermissions(oldPermission); CloseHandle(hProcess); return NaviErrors::COULDNT_DEBUG_TARGET_PROCESS; } DEBUG_EVENT dbg_evt; // Wait & skip over all initial messages until the first "real" exception is // hit for (;;) { if (!WinCE_arm_wait_for_debug_event(&dbg_evt, INFINITE)) { msglog->log(LOG_VERBOSE, "Error: WaitForDebugEvent() failed - aborting at %s:%d", __FUNCTION__, __LINE__); // Restore old thread access permissions SetProcPermissions(oldPermission); CloseHandle(hProcess); return NaviErrors::WAITING_FOR_DEBUG_EVENTS_FAILED; } // Store the id of the last thread that caused the last debug event setActiveThread(dbg_evt.dwThreadId); if (dbg_evt.dwDebugEventCode == EXCEPTION_DEBUG_EVENT) { msglog->log( LOG_VERBOSE, "Info: initial debug event received - starting debug loop at %s:%d", __FUNCTION__, __LINE__); // The initial debug event is caused by a thread that does not really // belong to the target process tids.erase(std::remove_if(tids.begin(), tids.end(), Thread::MakeThreadIdComparator(dbg_evt.dwThreadId)), tids.end()); this->tids.erase( std::remove_if(this->tids.begin(), this->tids.end(), Thread::MakeThreadIdComparator(dbg_evt.dwThreadId)), this->tids.end()); // Resume the target thread WinCE_arm_resume(dbg_evt.dwThreadId, DBG_CONTINUE); // Fill the list of loaded modules dllDebugEventHandler(dbg_evt.u.LoadDll.lpBaseOfDll, dbg_evt.dwProcessId, (CPUADDRESS) dbg_evt.u.LoadDll.lpImageName, dbg_evt.u.LoadDll.fUnicode, true); // Restore old thread access permissions SetProcPermissions(oldPermission); return NaviErrors::SUCCESS; } else { // Store the thread id of the thread that caused the event, but make sure // that no duplicates are stored if (std::find_if(tids.begin(), tids.end(), Thread::MakeThreadIdComparator(dbg_evt.dwThreadId)) == tids.end()) { Thread ts(dbg_evt.dwThreadId, RUNNING); tids.push_back(ts); this->tids.push_back(ts); } // Restore old thread access permissions SetProcPermissions(oldPermission); WinCE_arm_resume(dbg_evt.dwThreadId, DBG_CONTINUE); } } // std::cout << "Exiting: " << __FUNCTIONW__ << std::endl; return NaviErrors::SUCCESS; } bool WinCESystem::WinCE_arm_wait_for_debug_event(LPDEBUG_EVENT lpDebugEvent, DWORD dwMilliseconds) { // DWORD counter = 0; bool exit = false; bool ret = false; while ((counter < dwMilliseconds) && (exit == false) && (ret == false)) { ret = (WaitForDebugEvent(lpDebugEvent, 0) != 0); counter += 100; exit = (WaitForSingleObject(hEventExit, 0) == WAIT_OBJECT_0); } if (exit == true) { clearBreakpoints(bpxlist, BPX_simple); clearBreakpoints(ebpxlist, BPX_echo); clearBreakpoints(sbpxlist, BPX_stepping); ResumeThread(hThread); ExitThread(0); } // std::cout << "Exiting: " << __FUNCTIONW__ << std::endl; return ret; } /** * @return True, if the function succeeds. False, otherwise. */ bool WinCESystem::WinCE_arm_resume(unsigned int tid, DWORD mode) { // msglog->log(LOG_VERBOSE, "Resuming thread %X in process %X", tid, getPID()); if (!ContinueDebugEvent(getPID(), tid, mode)) { LPVOID message; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) & message, 0, NULL); msglog->log( LOG_VERBOSE, "Error: ContinueDebugEvent() failed with error: (Message: %s) at %s:%d", message, __FUNCTION__, __LINE__); LocalFree(message); return false; } // std::cout << "Exiting: " << __FUNCTIONW__ << std::endl; return true; } NaviError WinCESystem::setBreakpoint(const BREAKPOINT& breakpoint, bool) { return writeDWORD(hProcess, breakpoint.addr + baseOfImage, BPX_ARM); } bool WinCESystem::WinCE_arm_is_dbg_event_available() { DEBUG_EVENT dbg_evt; // Now process all debug events we can get while (WinCE_arm_wait_for_debug_event(&dbg_evt, 1000)) { msglog->log(LOG_VERBOSE, "Info: received debug event (Code: %d)", dbg_evt.dwDebugEventCode); // Store the last thread that caused a debug event setActiveThread(dbg_evt.dwThreadId); DBGEVT dbgevt; nextContinue = DBG_CONTINUE; // Get the debug event code we are dealing with switch (dbg_evt.dwDebugEventCode) { case EXCEPTION_DEBUG_EVENT: { // Handle the case of exceptions msglog->log(LOG_VERBOSE, "Info: received exception code %08X at %08X.", dbg_evt.u.Exception.ExceptionRecord.ExceptionCode, dbg_evt.u.Exception.ExceptionRecord.ExceptionAddress); DWORD code = dbg_evt.u.Exception.ExceptionRecord.ExceptionCode; CPUADDRESS address = (CPUADDRESS) dbg_evt.u.Exception.ExceptionRecord .ExceptionAddress; if (code == EXCEPTION_ACCESS_VIOLATION) { nextContinue = DBG_EXCEPTION_NOT_HANDLED; exceptionRaised(dbg_evt.dwThreadId, address, ProcessExceptions::ACCESS_VIOLATION); return true; } else if (code == EXCEPTION_ILLEGAL_INSTRUCTION) { nextContinue = DBG_EXCEPTION_NOT_HANDLED; exceptionRaised(dbg_evt.dwThreadId, address, ProcessExceptions::ILLEGAL_INSTRUCTION); return true; } else if (code == EXCEPTION_IN_PAGE_ERROR) { nextContinue = DBG_EXCEPTION_NOT_HANDLED; exceptionRaised(dbg_evt.dwThreadId, address, ProcessExceptions::PAGE_ERROR); return true; } else if (code == EXCEPTION_INT_DIVIDE_BY_ZERO) { nextContinue = DBG_EXCEPTION_NOT_HANDLED; exceptionRaised(dbg_evt.dwThreadId, address, ProcessExceptions::DIVIDE_BY_ZERO); return true; } else if (code == EXCEPTION_INT_OVERFLOW) { nextContinue = DBG_EXCEPTION_NOT_HANDLED; exceptionRaised(dbg_evt.dwThreadId, address, ProcessExceptions::INTEGER_OVERFLOW); return true; } else if (code == EXCEPTION_NONCONTINUABLE_EXCEPTION) { nextContinue = DBG_EXCEPTION_NOT_HANDLED; exceptionRaised(dbg_evt.dwThreadId, address, ProcessExceptions::NONCONTINUABLE_EXCEPTION); return true; } else if (code == EXCEPTION_PRIV_INSTRUCTION) { nextContinue = DBG_EXCEPTION_NOT_HANDLED; exceptionRaised(dbg_evt.dwThreadId, address, ProcessExceptions::PRIVILEDGED_INSTRUCTION); return true; } else if (code == EXCEPTION_STACK_OVERFLOW) { nextContinue = DBG_EXCEPTION_NOT_HANDLED; exceptionRaised(dbg_evt.dwThreadId, address, ProcessExceptions::STACK_OVERFLOW); return true; } else if (code == EXCEPTION_BREAKPOINT) { // Handle breakpoint events std::string tmp = cpuAddressToString( (CPUADDRESS) dbg_evt.u.Exception.ExceptionRecord .ExceptionAddress); // Tell the base system that a breakpoint was hit NaviError hitResult = breakpointHit(tmp, dbg_evt.dwThreadId, true /* resume on echo bp */); if (hitResult) { // What could have happened here? Maybe a breakpoint was hit that // wasn't // set by the debugger. TODO: Care more about error codes. msglog->log(LOG_ALWAYS, "Error: Breakpoint handler failed at %s:%d", __FUNCTION__, __LINE__); // Tell the program that we couldn't handle the breakpoint exception ContinueDebugEvent(dbg_evt.dwProcessId, dbg_evt.dwThreadId, DBG_EXCEPTION_NOT_HANDLED); continue; } return true; } else if (code == 0xE06D7363) { msglog->log(LOG_ALL, "Info: C++ exception was hit", code); // Ignore C++ exceptions for now ContinueDebugEvent(dbg_evt.dwProcessId, dbg_evt.dwThreadId, DBG_EXCEPTION_NOT_HANDLED); return false; } else { msglog->log(LOG_VERBOSE, "Info: Unknown exception with code %d was " "thrown by the target process", code); // Handle unknown exceptions nextContinue = DBG_EXCEPTION_NOT_HANDLED; exceptionRaised(dbg_evt.dwThreadId, address, ProcessExceptions::UNKNOWN_EXCEPTION); return true; } } case LOAD_DLL_DEBUG_EVENT: { WinCE_arm_resume(dbg_evt.dwThreadId, DBG_EXCEPTION_NOT_HANDLED); if (dllDebugEventHandler(dbg_evt.u.LoadDll.lpBaseOfDll, dbg_evt.dwProcessId, (CPUADDRESS) dbg_evt.u.LoadDll.lpImageName, dbg_evt.u.LoadDll.fUnicode, true)) { return false; } return true; } case UNLOAD_DLL_DEBUG_EVENT: { WinCE_arm_resume(dbg_evt.dwThreadId, DBG_EXCEPTION_NOT_HANDLED); if (dllDebugEventHandler(dbg_evt.u.LoadDll.lpBaseOfDll, dbg_evt.dwProcessId, (CPUADDRESS) dbg_evt.u.LoadDll.lpImageName, dbg_evt.u.LoadDll.fUnicode, false)) { return false; } return true; } case CREATE_THREAD_DEBUG_EVENT: { // Handle thread creation events msglog->log(LOG_VERBOSE, "Info: created new thread with TID %d at %s:%d", dbg_evt.dwThreadId, __FUNCTION__, __LINE__); // Save the thread in the internal list Thread ts(dbg_evt.dwThreadId, SUSPENDED); tids.push_back(ts); // Tell the system about the new thread NaviError ctResult = threadCreated(dbg_evt.dwThreadId, SUSPENDED); if (ctResult) { msglog->log(LOG_VERBOSE, "Error: Couldn't handle thread creation at %s:%d", __FUNCTION__, __LINE__); } WinCE_arm_resume(dbg_evt.dwThreadId, DBG_EXCEPTION_NOT_HANDLED); return true; } case EXIT_THREAD_DEBUG_EVENT: { // Handle the threads exit events msglog->log(LOG_VERBOSE, "Info: thread with TID %d exited at %s:%d", dbg_evt.dwThreadId, __FUNCTION__, __LINE__); // Remove the thread from the internal list tids.erase( std::remove_if(tids.begin(), tids.end(), Thread::MakeThreadIdComparator(dbg_evt.dwThreadId)), tids.end()); // tell the system about the exited thread NaviError ctResult = threadExit(dbg_evt.dwThreadId); if (ctResult) { msglog->log(LOG_VERBOSE, "Error: Couldn't handle thread creation at %s:%d", __FUNCTION__, __LINE__); } WinCE_arm_resume(dbg_evt.dwThreadId, DBG_EXCEPTION_NOT_HANDLED); return true; } case EXIT_PROCESS_DEBUG_EVENT: { // Handle the event that the target process exited msglog->log(LOG_VERBOSE, "Info: target process exited at %s:%d", __FUNCTION__, __LINE__); // Tell the base system that the process exited processExit(); return true; } default: { // Unknown debug event => tell the target process that we couldn't // handle it. WinCE_arm_resume(dbg_evt.dwThreadId, DBG_EXCEPTION_NOT_HANDLED); } } } return false; } NaviError WinCESystem::readDebugEvents() { return WinCE_arm_is_dbg_event_available() ? NaviErrors::SUCCESS : NaviErrors::WAITING_FOR_DEBUG_EVENTS_FAILED; } NaviError WinCESystem::removeBreakpoint(const BREAKPOINT& bp_in, bool) { unsigned int writtenbytes = 0; char tmp[50]; sprintf(tmp, ADDRESS_FORMAT_MASK, bp_in.addr); if (originalDWORDs.find(tmp) == originalDWORDs.end()) { msglog->log(LOG_VERBOSE, "Error: Trying to restore a breakpoint with " "unknown original byte at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::ORIGINAL_DATA_NOT_AVAILABLE; } unsigned int d = originalDWORDs[tmp]; msglog->log(LOG_VERBOSE, "Writing byte %lx to address %lx\n", d, bp_in.addr); // std::cout << "Exiting: " << __FUNCTIONW__ << std::endl; return writeDWORD(hProcess, bp_in.addr, d); } std::vector<char> WinCESystem::readPointedMemory(CPUADDRESS address) { unsigned int currentSize = 128; while (currentSize != 0) { std::vector<char> memory(currentSize, 0); if (readMemoryDataInternal(&memory[0], address, memory.size(), true) == NaviErrors::SUCCESS) { return memory; } currentSize /= 2; } return std::vector<char>(); } NaviError WinCESystem::setInstructionPointer(unsigned int tid, CPUADDRESS address) { // std::cout << "Entering: " << __FUNCTIONW__ << std::endl; DWORD oldPermission = 0; CONTEXT threadContext; threadContext.ContextFlags = CONTEXT_FULL; // save the current thread access permissions oldPermission = GetCurrentPermissions(); // get full access to all threads SetProcPermissions(0xFFFFFFFF); if (!GetThreadContext(hThread, &threadContext)) { msglog->log(LOG_VERBOSE, "Error: GetThreadContext failed at %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); SetProcPermissions(oldPermission); return NaviErrors::COULDNT_READ_REGISTERS; } threadContext.Pc = address; if (!SetThreadContext(hThread, &threadContext)) { msglog->log(LOG_VERBOSE, "Error: SetThreadContext failed at %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); SetProcPermissions(oldPermission); NaviErrors::COULDNT_WRITE_REGISTERS; } // restore old thread access permissions SetProcPermissions(oldPermission); return NaviErrors::SUCCESS; } /** * Helper function that reads a single byte from the process memory of the target * process. * * @param hProcess Process handle of the target process. * @param offset Memory offset to read from. * @param b The read byte is stored here. * * @return A NaviError code that describes whether the operation was successful * or not. */ NaviError readByte(HANDLE hProcess, CPUADDRESS offset, char& b) { DWORD oldProtection = 0; // Try to make the page writable for us if (!makePageWritable(hProcess, offset, oldProtection)) { msglog->log(LOG_VERBOSE, "Error: Couldn't make page read/writable at", __FUNCTION__, __LINE__); return NaviErrors::PAGE_NOT_READABLE; } SIZE_T writtenbytes = 0; // Try to read the byte from process memory if (!ReadProcessMemory(hProcess, reinterpret_cast<void*>(offset), &b, 1, &writtenbytes)) { restoreMemoryProtection(hProcess, offset, oldProtection); msglog->log(LOG_VERBOSE, "Error: Couldn't read process memory at %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); return NaviErrors::COULDNT_READ_MEMORY; } restoreMemoryProtection(hProcess, offset, oldProtection); // std::cout << "Exiting: " << __FUNCTIONW__ << std::endl; return NaviErrors::SUCCESS; } NaviError WinCESystem::storeOriginalData(const BREAKPOINT& bp_in) { char tmp[50]; sprintf(tmp, ADDRESS_FORMAT_MASK, bp_in.addr); if (originalDWORDs.find(tmp) != originalDWORDs.end()) { // Original data already stored return NaviErrors::SUCCESS; } unsigned int d; NaviError result = readDWORD(hProcess, bp_in.addr, d); if (result) { msglog->log(LOG_VERBOSE, "Error: Couldn't read byte from address %X at %s:%d", bp_in.addr, __FUNCTION__, __LINE__); return result; } originalDWORDs[tmp] = d; return NaviErrors::SUCCESS; } NaviError WinCESystem::readRegisters(RegisterContainer& registers) { msglog->log(LOG_VERBOSE, "Info: reading the register values of %d threads", tids.size()); for (std::vector<Thread>::iterator Iter = tids.begin(); Iter != tids.end(); ++Iter) { unsigned int tid = Iter->tid; Thread thread(tid, SUSPENDED); // Open the selected thread HANDLE hThread = (HANDLE) tid; if (!hThread) { msglog->log(LOG_VERBOSE, "Opening thread %d failed at %s:%d", tid, __FUNCTION__, __LINE__); } CONTEXT ctx; ctx.ContextFlags = CONTEXT_FULL; DWORD oldPermission = 0; // Save the old permissions for later retore oldPermission = GetCurrentPermissions(); // Get full thread access SetProcPermissions(0xFFFFFFFF); // Read the values of the registers of the thread if (GetThreadContext(hThread, &ctx) == FALSE) { msglog->log(LOG_ALWAYS, "Error: GetThreadContext failed at %s:%d with (Code: %d).", __FUNCTION__, __LINE__, GetLastError()); CloseHandle(hThread); SetProcPermissions(oldPermission); return NaviErrors::COULDNT_READ_REGISTERS; } // Restore old thread access permissions SetProcPermissions(oldPermission); msglog->log(LOG_VERBOSE, "Info: assigning register values of thread %d", tid); thread.registers.push_back( makeRegisterValue("R0", zylib::zycon::toHexString(ctx.R0), readPointedMemory(ctx.R0))); thread.registers.push_back( makeRegisterValue("R1", zylib::zycon::toHexString(ctx.R1), readPointedMemory(ctx.R1))); thread.registers.push_back( makeRegisterValue("R2", zylib::zycon::toHexString(ctx.R2), readPointedMemory(ctx.R2))); thread.registers.push_back( makeRegisterValue("R3", zylib::zycon::toHexString(ctx.R3), readPointedMemory(ctx.R3))); thread.registers.push_back( makeRegisterValue("R4", zylib::zycon::toHexString(ctx.R4), readPointedMemory(ctx.R4))); thread.registers.push_back( makeRegisterValue("R5", zylib::zycon::toHexString(ctx.R5), readPointedMemory(ctx.R5))); thread.registers.push_back( makeRegisterValue("R6", zylib::zycon::toHexString(ctx.R6), readPointedMemory(ctx.R6))); thread.registers.push_back( makeRegisterValue("R7", zylib::zycon::toHexString(ctx.R7), readPointedMemory(ctx.R7))); thread.registers.push_back( makeRegisterValue("R8", zylib::zycon::toHexString(ctx.R8), readPointedMemory(ctx.R8))); thread.registers.push_back( makeRegisterValue("R9", zylib::zycon::toHexString(ctx.R9), readPointedMemory(ctx.R9))); thread.registers.push_back( makeRegisterValue("R10", zylib::zycon::toHexString(ctx.R10), readPointedMemory(ctx.R10))); thread.registers.push_back( makeRegisterValue("R11", zylib::zycon::toHexString(ctx.R11), readPointedMemory(ctx.R11))); thread.registers.push_back( makeRegisterValue("R12", zylib::zycon::toHexString(ctx.R12), readPointedMemory(ctx.R12))); // mark SP as stack pointer thread.registers.push_back( makeRegisterValue("R13(SP)", zylib::zycon::toHexString(ctx.Sp), readPointedMemory(ctx.Sp), false, true)); thread.registers.push_back( makeRegisterValue("R14(LR)", zylib::zycon::toHexString(ctx.Lr), readPointedMemory(ctx.Lr))); // mark PC as instruction pointer thread.registers.push_back( makeRegisterValue("R15(PC)", zylib::zycon::toHexString(ctx.Pc), readPointedMemory(ctx.Pc), true)); thread.registers.push_back( makeRegisterValue("R16(PSR)", zylib::zycon::toHexString(ctx.Psr))); thread.registers.push_back( makeRegisterValue("N", zylib::zycon::toHexString((ctx.Psr >> 31) & 1))); thread.registers.push_back( makeRegisterValue("Z", zylib::zycon::toHexString((ctx.Psr >> 30) & 1))); thread.registers.push_back( makeRegisterValue("C", zylib::zycon::toHexString((ctx.Psr >> 29) & 1))); thread.registers.push_back( makeRegisterValue("V", zylib::zycon::toHexString((ctx.Psr >> 28) & 1))); thread.registers.push_back( makeRegisterValue("I", zylib::zycon::toHexString((ctx.Psr >> 7) & 1))); thread.registers.push_back( makeRegisterValue("F", zylib::zycon::toHexString((ctx.Psr >> 6) & 1))); thread.registers.push_back( makeRegisterValue("T", zylib::zycon::toHexString((ctx.Psr >> 5) & 1))); thread.registers.push_back( makeRegisterValue("MODE", zylib::zycon::toHexString(ctx.Psr & 0x1F))); registers.addThread(thread); CloseHandle(hThread); } return NaviErrors::SUCCESS; } void getFiles(const std::wstring& path, std::vector<std::wstring>& files, std::vector<std::wstring>& dirs) { return; } NaviError WinCESystem::readProcessList(ProcessListContainer& processList) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot == INVALID_HANDLE_VALUE) { return NaviErrors::COULDNT_GET_PROCESSLIST; } PROCESSENTRY32 pe; pe.dwSize = sizeof(PROCESSENTRY32); BOOL retval = Process32First(hSnapshot, &pe); while (retval) { unsigned long pid = pe.th32ProcessID; std::string name = TCharToString(pe.szExeFile); ProcessDescription process(pid, name); processList.push_back(process); pe.dwSize = sizeof(PROCESSENTRY32); retval = Process32Next(hSnapshot, &pe); } CloseToolhelp32Snapshot(hSnapshot); return NaviErrors::SUCCESS; } NaviError WinCESystem::readFiles(FileListContainer& fileList) { return NaviErrors::COULDNT_GET_FILELIST; } NaviError WinCESystem::readFiles(FileListContainer& fileList, const std::string& path) { return NaviErrors::SUCCESS; } NaviError WinCESystem::getInstructionPointer(unsigned int threadId, CPUADDRESS& addr) { CONTEXT threadContext; threadContext.ContextFlags = CONTEXT_FULL; DWORD oldPermission = 0; // Save old thread access permissions oldPermission = GetCurrentPermissions(); // Set full thread access permissions SetProcPermissions(0xFFFFFFFF); if (GetThreadContext(hThread, &threadContext) == FALSE) { msglog->log(LOG_VERBOSE, "Error: GetThreadContext failed %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); SetProcPermissions(oldPermission); return NaviErrors::COULDNT_READ_REGISTERS; } // restore old thread access permissions SetProcPermissions(oldPermission); addr = threadContext.Pc; return NaviErrors::SUCCESS; } NaviError WinCESystem::resumeThread(unsigned int tid) { return WinCE_arm_resume(tid, DBG_CONTINUE) ? NaviErrors::SUCCESS : NaviErrors::COULDNT_RESUME_THREAD; } NaviError WinCESystem::suspendThread(unsigned int tid) { HANDLE handle = (HANDLE) tid; if (!handle) { return NaviErrors::COULDNT_SUSPEND_THREAD; } if (SuspendThread(handle) == -1) { return NaviErrors::COULDNT_SUSPEND_THREAD; } CloseHandle(handle); return NaviErrors::SUCCESS; } /** * Terminates the target process. * * @return A NaviError code that describes whether the operation was successful * or not. */ NaviError WinCESystem::terminateProcess() { DWORD orgPermissions = GetCurrentPermissions(); SetProcPermissions(0xFFFFFFFF); if (!DebugActiveProcessStop(getPID())) { msglog->log( LOG_VERBOSE, "Error: Couldn't stop receiving debug events at %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); return NaviErrors::COULDNT_TERMINATE_TARGET_PROCESS; } if (!TerminateProcess(hProcess, 0)) { msglog->log( LOG_VERBOSE, "Error: Coudn't terminate the target process at %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); return NaviErrors::COULDNT_TERMINATE_TARGET_PROCESS; } SetProcPermissions(orgPermissions); return NaviErrors::SUCCESS; } NaviError WinCESystem::doSingleStep(unsigned int& tid, CPUADDRESS& address) { CPUADDRESS nextpc; if (getNextInstructionAddress(tid, nextpc)) return NaviErrors::COULDNT_SINGLE_STEP; BREAKPOINT bp; bp.addr = nextpc; bp.bpx_type = BPX_stepping; unsigned int opcode; if (readDWORD(hProcess, nextpc, opcode)) return NaviErrors::COULDNT_SINGLE_STEP; if (setBreakpoint(bp)) return NaviErrors::COULDNT_SINGLE_STEP; Sleep(100); NaviError resumeResult = resumeThread(tid); // Keep track of the last thread that caused the last debug event setActiveThread(tid); // writeDWORD uses CacheSync which we believe take a while :) Sleep(100); if (resumeResult) { msglog->log(LOG_VERBOSE, "Error: Couldn't resume thread at %s:%d", __FUNCTION__, __LINE__); return resumeResult; } DEBUG_EVENT dbg_evt; // Attempt to catch the next exception (single-step event) if (!WinCE_arm_wait_for_debug_event(&dbg_evt, 1000)) { msglog->log(LOG_VERBOSE, "Error: The single step event did not occur in time at %s:%d", __FUNCTION__, __LINE__); return NaviErrors::COULDNT_SINGLE_STEP; } if (dbg_evt.dwDebugEventCode != EXCEPTION_DEBUG_EVENT) { msglog->log( LOG_VERBOSE, "Error: should've gotten EXCEPTION_BREAKPOINT, but got %d at %s:%d", dbg_evt.dwDebugEventCode, __FUNCTION__, __LINE__); return NaviErrors::COULDNT_SINGLE_STEP; } if (dbg_evt.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT) { msglog->log(LOG_VERBOSE, "Error: Non BPX at %08X, continuing at %s:%d", dbg_evt.u.Exception.ExceptionRecord.ExceptionAddress, __FUNCTION__, __LINE__); return NaviErrors::COULDNT_SINGLE_STEP; } writeDWORD(hProcess, nextpc, opcode); address = nextpc; return NaviErrors::SUCCESS; } /** * Returns register descriptions of the target platform. * * @return The list of register descriptions. */ std::vector<RegisterDescription> WinCESystem::getRegisterNames() const { std::vector < RegisterDescription > regNames; RegisterDescription r0("R0", 4, true); RegisterDescription r1("R1", 4, true); RegisterDescription r2("R2", 4, true); RegisterDescription r3("R3", 4, true); RegisterDescription r4("R4", 4, true); RegisterDescription r5("R5", 4, true); RegisterDescription r6("R6", 4, true); RegisterDescription r7("R7", 4, true); RegisterDescription r8("R8", 4, true); RegisterDescription r9("R9", 4, true); RegisterDescription r10("R10", 4, true); RegisterDescription r11("R11", 4, true); RegisterDescription r12("R12", 4, true); RegisterDescription sp("R13(SP)", 4, true); RegisterDescription lr("R14(LR)", 4, true); RegisterDescription pc("R15(PC)", 4, true); RegisterDescription psr("R16(PSR)", 4, true); RegisterDescription nflag("N", 0, true); RegisterDescription zflag("Z", 0, true); RegisterDescription cflag("C", 0, true); RegisterDescription vflag("V", 0, true); RegisterDescription iflag("I", 0, true); RegisterDescription fflag("F", 0, true); RegisterDescription tflag("T", 0, true); RegisterDescription mode("MODE", 1, true); regNames.push_back(r0); regNames.push_back(r1); regNames.push_back(r2); regNames.push_back(r3); regNames.push_back(r4); regNames.push_back(r5); regNames.push_back(r6); regNames.push_back(r7); regNames.push_back(r8); regNames.push_back(r9); regNames.push_back(r10); regNames.push_back(r11); regNames.push_back(r12); regNames.push_back(lr); regNames.push_back(sp); regNames.push_back(pc); regNames.push_back(psr); regNames.push_back(nflag); regNames.push_back(zflag); regNames.push_back(cflag); regNames.push_back(vflag); regNames.push_back(iflag); regNames.push_back(fflag); regNames.push_back(tflag); regNames.push_back(mode); return regNames; } NaviError WinCESystem::setRegister(unsigned int tid, unsigned int index, CPUADDRESS address) { CONTEXT threadContext; threadContext.ContextFlags = CONTEXT_FULL; DWORD oldPermission = 0; // Save old thread access permissions oldPermission = GetCurrentPermissions(); // Get full thread access permissions SetProcPermissions(0xFFFFFFFF); if (GetThreadContext(hThread, &threadContext) == FALSE) { msglog->log(LOG_VERBOSE, "Error: GetThreadContext failed %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); SetProcPermissions(oldPermission); return NaviErrors::COULDNT_READ_REGISTERS; } switch (index) { case 0: threadContext.R0 = address; break; case 1: threadContext.R1 = address; break; case 2: threadContext.R2 = address; break; case 3: threadContext.R3 = address; break; case 4: threadContext.R4 = address; break; case 5: threadContext.R5 = address; break; case 6: threadContext.R6 = address; break; case 7: threadContext.R7 = address; break; case 8: threadContext.R8 = address; break; case 9: threadContext.R9 = address; break; case 10: threadContext.R10 = address; break; case 11: threadContext.R11 = address; break; case 12: threadContext.R12 = address; break; case 13: threadContext.Sp = address; break; case 14: threadContext.Lr = address; break; case 15: threadContext.Pc = address; break; case 16: threadContext.Psr = address; break; default: return NaviErrors::INVALID_REGISTER_INDEX; } if (!SetThreadContext(hThread, &threadContext)) { msglog->log(LOG_VERBOSE, "Error: SetThreadContext failed at %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); SetProcPermissions(oldPermission); return NaviErrors::COULDNT_WRITE_REGISTERS; } // Restore old thread access permissions SetProcPermissions(oldPermission); return NaviErrors::SUCCESS; } NaviError WinCESystem::getValidMemory(CPUADDRESS start, CPUADDRESS& from, CPUADDRESS& to) { // TODO: Improve - What if just a single page is allocated? unsigned int PAGE_SIZE = 0x1000; CPUADDRESS startOffset = start & (~(PAGE_SIZE - 1)); CPUADDRESS current = startOffset; CPUADDRESS low = (unsigned int) current; CPUADDRESS high = (unsigned int) current; MEMORY_BASIC_INFORMATION mem; do { //TODO: ensure correct address is querried if (!VirtualQuery(reinterpret_cast<void*>(current), &mem, sizeof(MEMORY_BASIC_INFORMATION))) { break; } if (mem.State != MEM_COMMIT) { break; } current -= PAGE_SIZE; } while (true); if (current == startOffset) { // No valid memory return NaviErrors::NO_VALID_MEMORY; } low = current + PAGE_SIZE; current = startOffset; do { //TODO: ensure correct address is querried if (!VirtualQuery(reinterpret_cast<void*>(current), &mem, sizeof(MEMORY_BASIC_INFORMATION))) { break; } if (mem.State != MEM_COMMIT) { break; } current += PAGE_SIZE; } while (true); high = current; from = low; to = high; return low != high ? NaviErrors::SUCCESS : NaviErrors::NO_VALID_MEMORY; } unsigned int WinCESystem::getAddressSize() const { return 32; } NaviError WinCESystem::getMemmap(std::vector<CPUADDRESS>& addresses) { unsigned int consecutiveRegions = 0; unsigned int address = 0x00010000; // first accessable address in slot0 MEMORY_BASIC_INFORMATION mem; memset(&mem, 0, sizeof(mem)); while (VirtualQuery(reinterpret_cast<void*>(address), &mem, sizeof(mem))) { if (mem.State == MEM_COMMIT) { ++consecutiveRegions; if (consecutiveRegions == 1) { msglog->log(LOG_VERBOSE, "Found memory section between %X and %X", (CPUADDRESS) mem.BaseAddress, (CPUADDRESS) mem.BaseAddress + mem.RegionSize - 1); addresses.push_back((CPUADDRESS) mem.BaseAddress); addresses.push_back( ((CPUADDRESS) mem.BaseAddress + mem.RegionSize - 1)); } else { msglog->log( LOG_VERBOSE, "Extending memory section to %X", addresses[addresses.size() - 1] + (CPUADDRESS) mem.RegionSize); addresses[addresses.size() - 1] += (CPUADDRESS) mem.RegionSize; } } else { consecutiveRegions = 0; } address = (unsigned int) mem.BaseAddress + mem.RegionSize; } msglog->log(LOG_VERBOSE, "VirtualQuery() failed with %X", GetLastError()); return NaviErrors::SUCCESS; } /** * Detaches from the target process. * * @return A NaviError code that describes whether the operation was successful * or not. */ NaviError WinCESystem::detach() { // Make sure to resume suspended processes before detaching // Otherwise it's going to crash if (getActiveThread()) { resumeThread(getActiveThread()); } // Don't kill the process when detaching DebugSetProcessKillOnExit(false); // Stop receiving debug events from the target process DebugActiveProcessStop(getPID()); return NaviErrors::SUCCESS; } DebuggerOptions WinCESystem::getDebuggerOptions() const { DebuggerOptions empty; empty.canMultithread = false; SYSTEM_INFO system_info; GetSystemInfo(&system_info); empty.pageSize = system_info.dwPageSize; return empty; } /** * Resumes the thread with the given thread ID. * * @param tid The thread ID of the thread. * * @return A NaviError code that describes whether the operation was successful * or not. */ NaviError WinCESystem::resumeProcess() { // Tricky: We have to ignore tid here because we always // have to resume the process with the thread that caused // the last debug event. return WinCE_arm_resume(getActiveThread(), nextContinue) ? NaviErrors::SUCCESS : NaviErrors::COULDNT_RESUME_THREAD; } NaviError WinCESystem::getRegisterTable(unsigned int* registers) { CONTEXT ctx; ctx.ContextFlags = CONTEXT_FULL; DWORD oldPermission = 0; // Save old thread access permissions oldPermission = GetCurrentPermissions(); // Get full thread access permissions SetProcPermissions(0xFFFFFFFF); if (GetThreadContext(hThread, &ctx) == FALSE) { msglog->log(LOG_VERBOSE, "Error: GetThreadContext failed at %s:%d with (Code: %d)", __FUNCTION__, __LINE__, GetLastError()); SetProcPermissions(oldPermission); return NaviErrors::COULDNT_READ_REGISTERS; } // Restore old thread access permissions SetProcPermissions(oldPermission); registers[0] = ctx.R0; registers[1] = ctx.R1; registers[2] = ctx.R2; registers[3] = ctx.R3; registers[4] = ctx.R4; registers[5] = ctx.R5; registers[6] = ctx.R6; registers[7] = ctx.R7; registers[8] = ctx.R8; registers[9] = ctx.R8; registers[10] = ctx.R10; registers[11] = ctx.R11; registers[12] = ctx.R12; registers[13] = ctx.Sp; registers[14] = ctx.Lr; registers[15] = ctx.Pc; registers[16] = ctx.Psr; registers[17] = ctx.Fpscr; registers[18] = ctx.FpExc; registers[18] = ctx.FpExc; return NaviErrors::SUCCESS; } //taken from arm-tdep.c of the gdb project NaviError WinCESystem::getNextInstructionAddress(unsigned int tid, CPUADDRESS& address) { unsigned int pc_val; unsigned int this_instr; unsigned int status; unsigned int registers[sizeof(CONTEXT) / sizeof(unsigned int) - 1]; CPUADDRESS nextpc; CPUADDRESS pc; //TODO: implement thumb_get_next_pc /*if (arm_pc_is_thumb (pc)) return thumb_get_next_pc (pc); */ if (getRegisterTable(registers)) return NaviErrors::COULDNT_READ_REGISTERS; pc = registers[15]; status = registers[16]; pc_val = (unsigned int) pc; readDWORD(hProcess, pc, this_instr); nextpc = (CPUADDRESS)(pc_val + 4); /* Default case */ if (condition_true(bits(this_instr, 28, 31), status)) { switch (bits(this_instr, 24, 27)) { case 0x0: case 0x1: /* data processing */ case 0x2: case 0x3: { unsigned int operand1, operand2, result = 0; unsigned int rn; int c; if (bits(this_instr, 12, 15) != 15) break; if (bits(this_instr, 22, 25) == 0 && bits(this_instr, 4, 7) == 9) msglog->log(LOG_VERBOSE, "ERROR: invalid update to pc at %s:%d", __FUNCTION__, __LINE__); /* BX <reg>, BLX <reg> */ if (bits(this_instr, 4, 28) == 0x12fff1 || bits(this_instr, 4, 28) == 0x12fff3) { rn = bits(this_instr, 0, 3); result = (rn == 15) ? pc_val + 8 : registers[rn]; nextpc = (CPUADDRESS) arm_addr_bits_remove(result); if (nextpc == pc) msglog->log(LOG_VERBOSE, "ERROR: infinite loop detected at %s:%d", __FUNCTION__, __LINE__); address = nextpc; return NaviErrors::SUCCESS; } /* Multiply into PC */ c = (status & FLAG_C) ? 1 : 0; rn = bits(this_instr, 16, 19); operand1 = (rn == 15) ? pc_val + 8 : registers[rn]; if (bit(this_instr, 25)) { unsigned int immval = bits(this_instr, 0, 7); unsigned int rotate = 2 * bits(this_instr, 8, 11); operand2 = ((immval >> rotate) | (immval << (32 - rotate))) & 0xffffffff; } else { /* operand 2 is a shifted register */ operand2 = shifted_reg_val(this_instr, c, pc_val, status, registers); } switch (bits(this_instr, 21, 24)) { case 0x0: /*and */ result = operand1 & operand2; break; case 0x1: /*eor */ result = operand1 ^ operand2; break; case 0x2: /*sub */ result = operand1 - operand2; break; case 0x3: /*rsb */ result = operand2 - operand1; break; case 0x4: /*add */ result = operand1 + operand2; break; case 0x5: /*adc */ result = operand1 + operand2 + c; break; case 0x6: /*sbc */ result = operand1 - operand2 + c; break; case 0x7: /*rsc */ result = operand2 - operand1 + c; break; case 0x8: case 0x9: case 0xa: case 0xb: /* tst, teq, cmp, cmn */ result = (unsigned int) nextpc; break; case 0xc: /*orr */ result = operand1 | operand2; break; case 0xd: /*mov */ /* Always step into a function. */ result = operand2; break; case 0xe: /*bic */ result = operand1 & ~operand2; break; case 0xf: /*mvn */ result = ~operand2; break; } nextpc = (CPUADDRESS) arm_addr_bits_remove(result); if (nextpc == pc) msglog->log(LOG_VERBOSE, "ERROR: infinite loop detected at %s:%d", __FUNCTION__, __LINE__); break; } case 0x4: case 0x5: /* data transfer */ case 0x6: case 0x7: if (bit(this_instr, 20)) { /* load */ if (bits(this_instr, 12, 15) == 15) { /* rd == pc */ unsigned int rn; unsigned int base; if (bit(this_instr, 22)) msglog->log(LOG_VERBOSE, "Error: infinite loop detected at %s:%d", __FUNCTION__, __LINE__); /* byte write to PC */ rn = bits(this_instr, 16, 19); base = (rn == 15) ? pc_val + 8 : registers[rn]; if (bit(this_instr, 24)) { /* pre-indexed */ int c = (status & FLAG_C) ? 1 : 0; unsigned int offset = ( bit(this_instr, 25) ? shifted_reg_val(this_instr, c, pc_val, status, registers) : bits(this_instr, 0, 11)); if (bit(this_instr, 23)) base += offset; else base -= offset; } readDWORD(hProcess, (CPUADDRESS) base, nextpc); nextpc = arm_addr_bits_remove(nextpc); if (nextpc == pc) msglog->log(LOG_VERBOSE, "Error: infinite loop detected at %s:%d", __FUNCTION__, __LINE__); } } break; case 0x8: case 0x9: /* block transfer */ if (bit(this_instr, 20)) { /* LDM */ if (bit(this_instr, 15)) { /* loading pc */ int offset = 0; if (bit(this_instr, 23)) { /* up */ unsigned int reglist = bits(this_instr, 0, 14); offset = bitcount(reglist) * 4; if (bit(this_instr, 24)) /* pre */ offset += 4; } else if (bit(this_instr, 24)) offset = -4; { unsigned int rn_val = registers[bits(this_instr, 16, 19)]; readDWORD(hProcess, (CPUADDRESS)(rn_val + offset), nextpc); } nextpc = arm_addr_bits_remove(nextpc); if (nextpc == pc) msglog->log(LOG_VERBOSE, "Error: infinite loop detected at %s:%d", __FUNCTION__, __LINE__); } } break; case 0xb: /* branch & link */ case 0xa: /* branch */ { nextpc = BranchDest(pc, this_instr); /* BLX */ if (bits(this_instr, 28, 31) == INST_NV) nextpc |= bit(this_instr, 24) << 1; nextpc = arm_addr_bits_remove(nextpc); if (nextpc == pc) msglog->log(LOG_VERBOSE, "Error: infinite loop detected at %s:%d", __FUNCTION__, __LINE__); break; } case 0xc: case 0xd: case 0xe: /* coproc ops */ case 0xf: /* SWI */ break; default: msglog->log(LOG_VERBOSE, "Error: bad bit field extraction at %s:%d", __FUNCTION__, __LINE__); address = pc; } } address = nextpc; return NaviErrors::SUCCESS; }
31.009235
84
0.637623
myArea51
10ee4e43d27c92ba8d077a527064e30657eb9dad
7,443
cc
C++
chrome/browser/gtk/extension_install_prompt2_gtk.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/browser/gtk/extension_install_prompt2_gtk.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/gtk/extension_install_prompt2_gtk.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gtk/gtk.h> #include "app/l10n_util.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/common/extensions/extension.h" #include "gfx/gtk_util.h" #include "grit/generated_resources.h" #include "skia/ext/image_operations.h" class Profile; namespace { const int kRightColumnMinWidth = 290; const int kImageSize = 69; // Padding on all sides of each permission in the permissions list. const int kPermissionsPadding = 8; // Make a GtkLabel with |str| as its text, using the formatting in |format|. GtkWidget* MakeMarkupLabel(const char* format, const std::string& str) { GtkWidget* label = gtk_label_new(NULL); char* markup = g_markup_printf_escaped(format, str.c_str()); gtk_label_set_markup(GTK_LABEL(label), markup); g_free(markup); // Left align it. gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5); return label; } void OnDialogResponse(GtkDialog* dialog, int response_id, ExtensionInstallUI::Delegate* delegate) { if (response_id == GTK_RESPONSE_ACCEPT) { delegate->InstallUIProceed(); } else { delegate->InstallUIAbort(); } gtk_widget_destroy(GTK_WIDGET(dialog)); } void ShowInstallPromptDialog2(GtkWindow* parent, SkBitmap* skia_icon, const Extension* extension, ExtensionInstallUI::Delegate *delegate, const std::vector<string16>& permissions) { // Build the dialog. GtkWidget* dialog = gtk_dialog_new_with_buttons( l10n_util::GetStringUTF8(IDS_EXTENSION_INSTALL_PROMPT_TITLE).c_str(), parent, GTK_DIALOG_MODAL, NULL); GtkWidget* close_button = gtk_dialog_add_button(GTK_DIALOG(dialog), GTK_STOCK_CANCEL, GTK_RESPONSE_CLOSE); gtk_dialog_add_button(GTK_DIALOG(dialog), l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_INSTALL_BUTTON).c_str(), GTK_RESPONSE_ACCEPT); gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE); // Create a two column layout. GtkWidget* content_area = GTK_DIALOG(dialog)->vbox; gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing); GtkWidget* icon_hbox = gtk_hbox_new(FALSE, gtk_util::kContentAreaSpacing); gtk_box_pack_start(GTK_BOX(content_area), icon_hbox, TRUE, TRUE, 0); // Resize the icon if necessary. SkBitmap scaled_icon = *skia_icon; if (scaled_icon.width() > kImageSize || scaled_icon.height() > kImageSize) { scaled_icon = skia::ImageOperations::Resize(scaled_icon, skia::ImageOperations::RESIZE_LANCZOS3, kImageSize, kImageSize); } // Put Icon in the left column. GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&scaled_icon); GtkWidget* icon = gtk_image_new_from_pixbuf(pixbuf); g_object_unref(pixbuf); gtk_box_pack_start(GTK_BOX(icon_hbox), icon, FALSE, FALSE, 0); // Top justify the image. gtk_misc_set_alignment(GTK_MISC(icon), 0.5, 0.0); // Create a new vbox for the right column. GtkWidget* right_column_area = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); gtk_box_pack_start(GTK_BOX(icon_hbox), right_column_area, TRUE, TRUE, 0); std::string heading_text = l10n_util::GetStringFUTF8( IDS_EXTENSION_INSTALL_PROMPT_HEADING, UTF8ToUTF16(extension->name())); GtkWidget* heading_label = MakeMarkupLabel("<span weight=\"bold\">%s</span>", heading_text); gtk_misc_set_alignment(GTK_MISC(heading_label), 0.0, 0.5); bool show_permissions = !permissions.empty(); // If we are not going to show the permissions, vertically center the title. gtk_box_pack_start(GTK_BOX(right_column_area), heading_label, !show_permissions, !show_permissions, 0); if (show_permissions) { GtkWidget* warning_label = gtk_label_new(l10n_util::GetStringUTF8( IDS_EXTENSION_PROMPT_WILL_HAVE_ACCESS_TO).c_str()); gtk_misc_set_alignment(GTK_MISC(warning_label), 0.0, 0.5); gtk_util::SetLabelWidth(warning_label, kRightColumnMinWidth); gtk_box_pack_start(GTK_BOX(right_column_area), warning_label, FALSE, FALSE, 0); GtkWidget* frame = gtk_frame_new(NULL); gtk_box_pack_start(GTK_BOX(right_column_area), frame, FALSE, FALSE, 0); GtkWidget* text_view = gtk_text_view_new(); gtk_container_add(GTK_CONTAINER(frame), text_view); gtk_text_view_set_editable(GTK_TEXT_VIEW(text_view), FALSE); gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text_view), kPermissionsPadding); gtk_text_view_set_right_margin(GTK_TEXT_VIEW(text_view), kPermissionsPadding); gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text_view), GTK_WRAP_WORD); GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_view)); GtkTextTagTable* tag_table = gtk_text_buffer_get_tag_table(buffer); GtkTextTag* padding_below_tag = gtk_text_tag_new(NULL); g_object_set(G_OBJECT(padding_below_tag), "pixels-below-lines", kPermissionsPadding, NULL); g_object_set(G_OBJECT(padding_below_tag), "pixels-below-lines-set", TRUE, NULL); gtk_text_tag_table_add(tag_table, padding_below_tag); g_object_unref(padding_below_tag); GtkTextTag* padding_above_tag = gtk_text_tag_new(NULL); g_object_set(G_OBJECT(padding_above_tag), "pixels-above-lines", kPermissionsPadding, NULL); g_object_set(G_OBJECT(padding_above_tag), "pixels-above-lines-set", TRUE, NULL); gtk_text_tag_table_add(tag_table, padding_above_tag); g_object_unref(padding_above_tag); GtkTextIter end_iter; gtk_text_buffer_get_end_iter(buffer, &end_iter); for (std::vector<string16>::const_iterator iter = permissions.begin(); iter != permissions.end(); ++iter) { if (iter != permissions.begin()) gtk_text_buffer_insert(buffer, &end_iter, "\n", -1); gtk_text_buffer_insert_with_tags( buffer, &end_iter, UTF16ToUTF8(*iter).c_str(), -1, padding_below_tag, iter == permissions.begin() ? padding_above_tag : NULL, NULL); } } g_signal_connect(dialog, "response", G_CALLBACK(OnDialogResponse), delegate); gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CLOSE); gtk_widget_show_all(dialog); gtk_widget_grab_focus(close_button); } } // namespace void ExtensionInstallUI::ShowExtensionInstallUIPrompt2Impl( Profile* profile, Delegate* delegate, const Extension* extension, SkBitmap* icon, const std::vector<string16>& permissions) { Browser* browser = BrowserList::GetLastActiveWithProfile(profile); if (!browser) { delegate->InstallUIAbort(); return; } BrowserWindowGtk* browser_window = static_cast<BrowserWindowGtk*>( browser->window()); if (!browser_window) { delegate->InstallUIAbort(); return; } ShowInstallPromptDialog2(browser_window->window(), icon, extension, delegate, permissions); }
38.564767
80
0.720005
Gitman1989
10eec7895b1c658cd3e5c24a7cc8d9f70106e046
16,423
cpp
C++
src/petuum_ps/thread/ssp_aggr_bg_worker.cpp
daiwei89/wdai_petuum_public
4068859897061201d0a63630a3da6011b0d0f75f
[ "BSD-3-Clause" ]
370
2015-06-30T09:46:17.000Z
2017-01-21T07:14:00.000Z
src/petuum_ps/thread/ssp_aggr_bg_worker.cpp
daiwei89/wdai_petuum_public
4068859897061201d0a63630a3da6011b0d0f75f
[ "BSD-3-Clause" ]
3
2016-11-08T19:45:19.000Z
2016-11-11T13:21:19.000Z
src/petuum_ps/thread/ssp_aggr_bg_worker.cpp
daiwei89/wdai_petuum_public
4068859897061201d0a63630a3da6011b0d0f75f
[ "BSD-3-Clause" ]
159
2015-07-03T05:58:31.000Z
2016-12-29T20:59:01.000Z
#include <petuum_ps/thread/ssp_aggr_bg_worker.hpp> #include <petuum_ps/thread/trans_time_estimate.hpp> #include <petuum_ps_common/util/stats.hpp> namespace petuum { void SSPAggrBgWorker::SetWaitMsg() { WaitMsg_ = WaitMsgTimeOut; } void SSPAggrBgWorker::PrepareBeforeInfiniteLoop() { msg_send_timer_.restart(); } void SSPAggrBgWorker::FinalizeTableStats() { for (const auto &table_pair : (*tables_)) { min_table_staleness_ = std::min(min_table_staleness_, table_pair.second->get_staleness()); } } long SSPAggrBgWorker::ResetBgIdleMilli() { return GlobalContext::get_bg_idle_milli(); } void SSPAggrBgWorker::ReadTableOpLogsIntoOpLogMeta(int32_t table_id, ClientTable *table) { // Get OpLog index cuckoohash_map<int32_t, bool> *new_table_oplog_index_ptr = table->GetAndResetOpLogIndex(my_comm_channel_idx_); AbstractOpLog &table_oplog = table->get_oplog(); TableOpLogMeta *table_oplog_meta = oplog_meta_.Get(table_id); if (table_oplog_meta == 0) { const AbstractRow *sample_row = table->get_sample_row(); table_oplog_meta = oplog_meta_.AddTableOpLogMeta(table_id, sample_row); } for (auto oplog_index_iter = new_table_oplog_index_ptr->cbegin(); !oplog_index_iter.is_end(); oplog_index_iter++) { int32_t row_id = oplog_index_iter->first; RowOpLogMeta row_oplog_meta; bool found = table_oplog.GetInvalidateOpLogMeta(row_id, &row_oplog_meta); if (!found || (row_oplog_meta.get_clock() == -1)) { continue; } table_oplog_meta->InsertMergeRowOpLogMeta(row_id, row_oplog_meta); } delete new_table_oplog_index_ptr; } size_t SSPAggrBgWorker::ReadTableOpLogMetaUpToClock( int32_t table_id, ClientTable *table, int32_t clock_to_push, TableOpLogMeta *table_oplog_meta, GetSerializedRowOpLogSizeFunc GetSerializedRowOpLogSize, BgOpLogPartition *bg_table_oplog) { if (clock_to_push < 0) return 0; size_t accum_table_oplog_bytes = 0; AbstractOpLog &table_oplog = table->get_oplog(); int32_t row_id; row_id = table_oplog_meta->InitGetUptoClock(clock_to_push); while (row_id >= 0) { AbstractRowOpLog* row_oplog = 0; bool found = table_oplog.GetEraseOpLog(row_id, &row_oplog); if (found && row_oplog != 0) { size_t serialized_oplog_size = CountRowOpLogToSend( row_id, row_oplog, &table_num_bytes_by_server_, bg_table_oplog, GetSerializedRowOpLogSize); accum_table_oplog_bytes += serialized_oplog_size; } row_id = table_oplog_meta->GetAndClearNextUptoClock(); } return accum_table_oplog_bytes; } size_t SSPAggrBgWorker::ReadTableOpLogMetaUpToClockNoReplay( int32_t table_id, ClientTable *table, int32_t clock_to_push, TableOpLogMeta *table_oplog_meta, RowOpLogSerializer *row_oplog_serializer) { if (clock_to_push < 0) return 0; size_t accum_table_oplog_bytes = 0; AbstractOpLog &table_oplog = table->get_oplog(); int32_t row_id; row_id = table_oplog_meta->InitGetUptoClock(clock_to_push); while (row_id >= 0) { OpLogAccessor oplog_accessor; bool found = table_oplog.FindAndLock(row_id, &oplog_accessor); if (found) { AbstractRowOpLog* row_oplog = oplog_accessor.get_row_oplog(); if (row_oplog != 0) { size_t serialized_oplog_size = row_oplog_serializer->AppendRowOpLog(row_id, row_oplog); row_oplog->Reset(); MetaRowOpLog *meta_row_oplog = dynamic_cast<MetaRowOpLog*>(row_oplog); meta_row_oplog->InvalidateMeta(); meta_row_oplog->ResetImportance(); accum_table_oplog_bytes += serialized_oplog_size; } row_id = table_oplog_meta->GetAndClearNextUptoClock(); } } return accum_table_oplog_bytes; } size_t SSPAggrBgWorker::ReadTableOpLogMetaUpToCapacity( int32_t table_id, ClientTable *table, size_t bytes_accumulated, TableOpLogMeta *table_oplog_meta, GetSerializedRowOpLogSizeFunc GetSerializedRowOpLogSize, BgOpLogPartition *bg_table_oplog) { size_t accum_table_oplog_bytes = bytes_accumulated; AbstractOpLog &table_oplog = table->get_oplog(); table_oplog_meta->Sort(); int32_t row_id; row_id = table_oplog_meta->GetAndClearNextInOrder(); while (row_id >= 0) { AbstractRowOpLog* row_oplog = 0; bool found = table_oplog.GetEraseOpLog(row_id, &row_oplog); if (found && row_oplog != 0) { size_t serialized_oplog_size = CountRowOpLogToSend( row_id, row_oplog, &table_num_bytes_by_server_, bg_table_oplog, GetSerializedRowOpLogSize); accum_table_oplog_bytes += serialized_oplog_size; if (accum_table_oplog_bytes >= GlobalContext::get_oplog_push_upper_bound_kb()*k1_Ki) break; } row_id = table_oplog_meta->GetAndClearNextInOrder(); } return accum_table_oplog_bytes; } size_t SSPAggrBgWorker::ReadTableOpLogMetaUpToCapacityNoReplay( int32_t table_id, ClientTable *table, size_t bytes_accumulated, TableOpLogMeta *table_oplog_meta, RowOpLogSerializer *row_oplog_serializer) { size_t accum_table_oplog_bytes = bytes_accumulated; AbstractOpLog &table_oplog = table->get_oplog(); table_oplog_meta->Sort(); int32_t row_id; row_id = table_oplog_meta->GetAndClearNextInOrder(); while (row_id >= 0) { OpLogAccessor oplog_accessor; bool found = table_oplog.FindAndLock(row_id, &oplog_accessor); if (found) { AbstractRowOpLog* row_oplog = oplog_accessor.get_row_oplog(); if (row_oplog != 0) { size_t serialized_oplog_size = row_oplog_serializer->AppendRowOpLog(row_id, row_oplog); row_oplog->Reset(); MetaRowOpLog *meta_row_oplog = dynamic_cast<MetaRowOpLog*>(row_oplog); meta_row_oplog->InvalidateMeta(); meta_row_oplog->ResetImportance(); accum_table_oplog_bytes += serialized_oplog_size; if (accum_table_oplog_bytes >= GlobalContext::get_oplog_push_upper_bound_kb()*k1_Ki) break; } row_id = table_oplog_meta->GetAndClearNextInOrder(); } } return accum_table_oplog_bytes; } BgOpLogPartition* SSPAggrBgWorker::PrepareOpLogsNormal( int32_t table_id, ClientTable *table, int32_t clock_to_push) { GetSerializedRowOpLogSizeFunc GetSerializedRowOpLogSize; if (table->oplog_dense_serialized()) { GetSerializedRowOpLogSize = GetDenseSerializedRowOpLogSize; } else { GetSerializedRowOpLogSize = GetSparseSerializedRowOpLogSize; } ReadTableOpLogsIntoOpLogMeta(table_id, table); for (const auto &server_id : server_ids_) { table_num_bytes_by_server_[server_id] = 0; } size_t table_update_size = table->get_sample_row()->get_update_size(); BgOpLogPartition *bg_table_oplog = new BgOpLogPartition( table_id, table_update_size, my_comm_channel_idx_); TableOpLogMeta *table_oplog_meta = oplog_meta_.Get(table_id); size_t accum_table_oplog_bytes = ReadTableOpLogMetaUpToClock( table_id, table, clock_to_push, table_oplog_meta, GetSerializedRowOpLogSize, bg_table_oplog); ReadTableOpLogMetaUpToCapacity( table_id, table, accum_table_oplog_bytes, table_oplog_meta, GetSerializedRowOpLogSize, bg_table_oplog); return bg_table_oplog; } BgOpLogPartition* SSPAggrBgWorker::PrepareOpLogsAppendOnly( int32_t table_id, ClientTable *table, int32_t clock_to_push) { LOG(FATAL) << "Not yet supported!"; return 0; } void SSPAggrBgWorker::PrepareOpLogsNormalNoReplay( int32_t table_id, ClientTable *table, int32_t clock_to_push) { auto serializer_iter = row_oplog_serializer_map_.find(table_id); if (serializer_iter == row_oplog_serializer_map_.end()) { RowOpLogSerializer *row_oplog_serializer = new RowOpLogSerializer(table->oplog_dense_serialized(), my_comm_channel_idx_); row_oplog_serializer_map_.insert(std::make_pair(table_id, row_oplog_serializer)); serializer_iter = row_oplog_serializer_map_.find(table_id); } RowOpLogSerializer *row_oplog_serializer = serializer_iter->second; ReadTableOpLogsIntoOpLogMeta(table_id, table); TableOpLogMeta *table_oplog_meta = oplog_meta_.Get(table_id); size_t accum_table_oplog_bytes = ReadTableOpLogMetaUpToClockNoReplay( table_id, table, clock_to_push, table_oplog_meta, row_oplog_serializer); ReadTableOpLogMetaUpToCapacityNoReplay( table_id, table, accum_table_oplog_bytes, table_oplog_meta, row_oplog_serializer); for (const auto &server_id : server_ids_) { table_num_bytes_by_server_[server_id] = 0; } row_oplog_serializer->GetServerTableSizeMap(&table_num_bytes_by_server_); } void SSPAggrBgWorker::PrepareOpLogsAppendOnlyNoReplay( int32_t table_id, ClientTable *table, int32_t clock_to_push) { LOG(FATAL) << "Not yet supported!"; } BgOpLog *SSPAggrBgWorker::PrepareOpLogsToSend(int32_t clock_to_push) { BgOpLog *bg_oplog = new BgOpLog; for (const auto &table_pair : (*tables_)) { int32_t table_id = table_pair.first; if (table_pair.second->get_no_oplog_replay()) { if (table_pair.second->get_oplog_type() == Sparse || table_pair.second->get_oplog_type() == Dense) PrepareOpLogsNormalNoReplay(table_id, table_pair.second, clock_to_push); else if (table_pair.second->get_oplog_type() == AppendOnly) PrepareOpLogsAppendOnlyNoReplay(table_id, table_pair.second, clock_to_push); else LOG(FATAL) << "Unknown oplog type = " << table_pair.second->get_oplog_type(); } else { BgOpLogPartition *bg_table_oplog = 0; if (table_pair.second->get_oplog_type() == Sparse || table_pair.second->get_oplog_type() == Dense) bg_table_oplog = PrepareOpLogsNormal(table_id, table_pair.second, clock_to_push); else if (table_pair.second->get_oplog_type() == AppendOnly) bg_table_oplog = PrepareOpLogsAppendOnly(table_id, table_pair.second, clock_to_push); else LOG(FATAL) << "Unknown oplog type = " << table_pair.second->get_oplog_type(); bg_oplog->Add(table_id, bg_table_oplog); } FinalizeOpLogMsgStats(table_id, &table_num_bytes_by_server_, &server_table_oplog_size_map_); } return bg_oplog; } long SSPAggrBgWorker::HandleClockMsg(bool clock_advanced) { if (!clock_advanced) return GlobalContext::get_bg_idle_milli(); int32_t clock_to_push = client_clock_ - min_table_staleness_ + GlobalContext::get_oplog_push_staleness_tolerance(); if (clock_to_push > client_clock_) clock_to_push = client_clock_; if (clock_to_push >= 0) clock_has_pushed_ = clock_to_push; BgOpLog *bg_oplog = PrepareOpLogsToSend(clock_to_push); CreateOpLogMsgs(bg_oplog); size_t sent_size = SendOpLogMsgs(true); TrackBgOpLog(bg_oplog); oplog_send_milli_sec_ = TransTimeEstimate::EstimateTransMillisec(sent_size); msg_send_timer_.restart(); STATS_BG_ACCUM_IDLE_SEND_END(); STATS_BG_ACCUM_IDLE_OPLOG_SENT_BYTES(sent_size); VLOG(0) << "BgIdle send bytes = " << sent_size << " send milli sec = " << oplog_send_milli_sec_ << " bg_id = " << my_id_; return oplog_send_milli_sec_; } BgOpLog *SSPAggrBgWorker::PrepareBgIdleOpLogs() { BgOpLog *bg_oplog = new BgOpLog; for (const auto &table_pair : (*tables_)) { int32_t table_id = table_pair.first; if (table_pair.second->get_no_oplog_replay()) { if (table_pair.second->get_oplog_type() == Sparse || table_pair.second->get_oplog_type() == Dense) PrepareBgIdleOpLogsNormalNoReplay(table_id, table_pair.second); else if (table_pair.second->get_oplog_type() == AppendOnly) PrepareBgIdleOpLogsAppendOnlyNoReplay(table_id, table_pair.second); else LOG(FATAL) << "Unknown oplog type = " << table_pair.second->get_oplog_type(); } else { BgOpLogPartition *bg_table_oplog = 0; if (table_pair.second->get_oplog_type() == Sparse || table_pair.second->get_oplog_type() == Dense) bg_table_oplog = PrepareBgIdleOpLogsNormal(table_id, table_pair.second); else if (table_pair.second->get_oplog_type() == AppendOnly) bg_table_oplog = PrepareBgIdleOpLogsAppendOnly(table_id, table_pair.second); else LOG(FATAL) << "Unknown oplog type = " << table_pair.second->get_oplog_type(); bg_oplog->Add(table_id, bg_table_oplog); } FinalizeOpLogMsgStats(table_id, &table_num_bytes_by_server_, &server_table_oplog_size_map_); } return bg_oplog; } BgOpLogPartition* SSPAggrBgWorker::PrepareBgIdleOpLogsNormal(int32_t table_id, ClientTable *table) { GetSerializedRowOpLogSizeFunc GetSerializedRowOpLogSize; if (table->oplog_dense_serialized()) { GetSerializedRowOpLogSize = GetDenseSerializedRowOpLogSize; } else { GetSerializedRowOpLogSize = GetSparseSerializedRowOpLogSize; } ReadTableOpLogsIntoOpLogMeta(table_id, table); for (const auto &server_id : server_ids_) { table_num_bytes_by_server_[server_id] = 0; } size_t table_update_size = table->get_sample_row()->get_update_size(); BgOpLogPartition *bg_table_oplog = new BgOpLogPartition( table_id, table_update_size, my_comm_channel_idx_); TableOpLogMeta *table_oplog_meta = oplog_meta_.Get(table_id); ReadTableOpLogMetaUpToCapacity( table_id, table, 0, table_oplog_meta, GetSerializedRowOpLogSize, bg_table_oplog); return bg_table_oplog; } void SSPAggrBgWorker::PrepareBgIdleOpLogsNormalNoReplay(int32_t table_id, ClientTable *table) { auto serializer_iter = row_oplog_serializer_map_.find(table_id); if (serializer_iter == row_oplog_serializer_map_.end()) { RowOpLogSerializer *row_oplog_serializer = new RowOpLogSerializer(table->oplog_dense_serialized(), my_comm_channel_idx_); row_oplog_serializer_map_.insert(std::make_pair(table_id, row_oplog_serializer)); serializer_iter = row_oplog_serializer_map_.find(table_id); } RowOpLogSerializer *row_oplog_serializer = serializer_iter->second; ReadTableOpLogsIntoOpLogMeta(table_id, table); TableOpLogMeta *table_oplog_meta = oplog_meta_.Get(table_id); ReadTableOpLogMetaUpToCapacityNoReplay( table_id, table, 0, table_oplog_meta, row_oplog_serializer); for (const auto &server_id : server_ids_) { table_num_bytes_by_server_[server_id] = 0; } row_oplog_serializer->GetServerTableSizeMap(&table_num_bytes_by_server_); } BgOpLogPartition *SSPAggrBgWorker::PrepareBgIdleOpLogsAppendOnly(int32_t table_id, ClientTable *table) { LOG(FATAL) << "Operation not supported!"; return 0; } void SSPAggrBgWorker::PrepareBgIdleOpLogsAppendOnlyNoReplay(int32_t table_id, ClientTable *table) { LOG(FATAL) << "Operation not supported!"; } long SSPAggrBgWorker::BgIdleWork() { STATS_BG_IDLE_INVOKE_INC_ONE(); bool found_oplog = false; // check if last msg has been sent out if (oplog_send_milli_sec_ > 1) { double send_elapsed_milli = msg_send_timer_.elapsed() * kOneThousand; if (oplog_send_milli_sec_ > send_elapsed_milli + 1) return (oplog_send_milli_sec_ - send_elapsed_milli); } if (oplog_meta_.OpLogMetaExists()) found_oplog = true; else { for (const auto &table_pair : (*tables_)) { if (table_pair.second->GetNumRowOpLogs(my_comm_channel_idx_) > 0) { found_oplog = true; break; } } } if (!found_oplog) { oplog_send_milli_sec_ = 0; return GlobalContext::get_bg_idle_milli(); } STATS_BG_IDLE_SEND_INC_ONE(); STATS_BG_ACCUM_IDLE_SEND_BEGIN(); BgOpLog *bg_oplog = PrepareBgIdleOpLogs(); CreateOpLogMsgs(bg_oplog); size_t sent_size = SendOpLogMsgs(false); TrackBgOpLog(bg_oplog); oplog_send_milli_sec_ = TransTimeEstimate::EstimateTransMillisec(sent_size); msg_send_timer_.restart(); STATS_BG_ACCUM_IDLE_SEND_END(); STATS_BG_ACCUM_IDLE_OPLOG_SENT_BYTES(sent_size); VLOG(0) << "BgIdle send bytes = " << sent_size << " send milli sec = " << oplog_send_milli_sec_ << " bg_id = " << ThreadContext::get_id(); return oplog_send_milli_sec_; } }
32.585317
93
0.720088
daiwei89
10f0abd161d4857d3f25979ec03258465137d1bc
7,761
cpp
C++
src/CUDA/xx_decomposition_prototype/test/simulation_unittest.cpp
csrhau/DiffusionOptimisationStudy
77fb718123d18c8358ccab4e958382b760901d55
[ "MIT" ]
null
null
null
src/CUDA/xx_decomposition_prototype/test/simulation_unittest.cpp
csrhau/DiffusionOptimisationStudy
77fb718123d18c8358ccab4e958382b760901d55
[ "MIT" ]
null
null
null
src/CUDA/xx_decomposition_prototype/test/simulation_unittest.cpp
csrhau/DiffusionOptimisationStudy
77fb718123d18c8358ccab4e958382b760901d55
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "common.h" #include "simulation.h" TEST(SimulationTests, OneEqualsOne) { EXPECT_EQ(1, 1); } TEST(SimulationTests, ConservationOfEnergyHost) { const double nu = 0.05; const double sigma = 0.25; const double width = 2; const double height = 2; const double dx = width / (IMAX-1); const double dy = height / (JMAX-1); const double dz = height / (KMAX-1); const double dt = sigma * dx * dy * dz / nu; const double cx = (nu * dt / (dx * dx)); const double cy = (nu * dt / (dy * dy)); const double cz = (nu * dt / (dz * dz)); // Initialize state double *state[2]; state[0] = (double *) malloc(IMAX * JMAX * KMAX * sizeof(double)); state[1] = (double *) malloc(IMAX * JMAX * KMAX * sizeof(double)); // Host Data Initialization for (int k = 0; k < KMAX; ++k) { for (int j = 0; j < JMAX; ++j) { for (int i = 0; i < IMAX; ++i) { size_t center = k * JMAX * IMAX + j * IMAX + i; if (i < HOTCORNER_IMAX && j < HOTCORNER_JMAX && k < HOTCORNER_KMAX) { state[0][center] = 2.0; } else { state[0][center] = 1.0; } } } } const unsigned long all_cells = (IMAX-2) * (JMAX-2) * (KMAX-2); const unsigned long hot_cells = (HOTCORNER_IMAX-1) * (HOTCORNER_JMAX-1) * (HOTCORNER_KMAX-1); double expected = hot_cells * 2.0 + (all_cells-hot_cells) * 1.0; RecursiveTrapezoidHost(state, cx, cy, cz, 0, TIMESTEPS, 1, 0, IMAX-1, 0, IMAX, 1, 0, JMAX-1, 0, JMAX, 1, 0, KMAX-1, 0, KMAX); double temperature = 0.0; for (int k = 1; k < KMAX-1; ++k) { for (int j = 1; j < JMAX-1; ++j) { for (int i = 1; i < IMAX-1; ++i) { size_t center = k * JMAX * IMAX + j * IMAX + i; temperature += state[TIMESTEPS & 1][center]; } } } EXPECT_NEAR(expected, temperature, 1.0E-7); } TEST(SimulationTests, HostConservationOfEnergy) { const double nu = 0.05; const double sigma = 0.25; const double width = 2; const double height = 2; const double dx = width / (IMAX-1); const double dy = height / (JMAX-1); const double dz = height / (KMAX-1); const double dt = sigma * dx * dy * dz / nu; const double cx = (nu * dt / (dx * dx)); const double cy = (nu * dt / (dy * dy)); const double cz = (nu * dt / (dz * dz)); // Initialize state double *state[2]; state[0] = (double *) malloc(IMAX * JMAX * KMAX * sizeof(double)); state[1] = (double *) malloc(IMAX * JMAX * KMAX * sizeof(double)); // Host Data Initialization for (int k = 0; k < KMAX; ++k) { for (int j = 0; j < JMAX; ++j) { for (int i = 0; i < IMAX; ++i) { size_t center = k * JMAX * IMAX + j * IMAX + i; if (i < HOTCORNER_IMAX && j < HOTCORNER_JMAX && k < HOTCORNER_KMAX) { state[0][center] = 2.0; } else { state[0][center] = 1.0; } } } } const unsigned long all_cells = (IMAX-2) * (JMAX-2) * (KMAX-2); const unsigned long hot_cells = (HOTCORNER_IMAX-1) * (HOTCORNER_JMAX-1) * (HOTCORNER_KMAX-1); double expected = hot_cells * 2.0 + (all_cells-hot_cells) * 1.0; RecursiveTrapezoidHost(state, cx, cy, cz, 0, TIMESTEPS, 1, 0, IMAX-1, 0, IMAX, 1, 0, JMAX-1, 0, JMAX, 1, 0, KMAX-1, 0, KMAX); double temperature = 0.0; for (int k = 1; k < KMAX-1; ++k) { for (int j = 1; j < JMAX-1; ++j) { for (int i = 1; i < IMAX-1; ++i) { size_t center = k * JMAX * IMAX + j * IMAX + i; temperature += state[TIMESTEPS & 1][center]; } } } EXPECT_NEAR(expected, temperature, 1.0E-7); } TEST(SimulationTests, DeviceConservationOfEnergy) { const double nu = 0.05; const double sigma = 0.25; const double width = 2; const double height = 2; const double dx = width / (IMAX-1); const double dy = height / (JMAX-1); const double dz = height / (KMAX-1); const double dt = sigma * dx * dy * dz / nu; const double cx = (nu * dt / (dx * dx)); const double cy = (nu * dt / (dy * dy)); const double cz = (nu * dt / (dz * dz)); // Initialize state double *state[2]; state[0] = (double *) malloc(IMAX * JMAX * KMAX * sizeof(double)); state[1] = (double *) malloc(IMAX * JMAX * KMAX * sizeof(double)); // Host Data Initialization for (int k = 0; k < KMAX; ++k) { for (int j = 0; j < JMAX; ++j) { for (int i = 0; i < IMAX; ++i) { size_t center = k * JMAX * IMAX + j * IMAX + i; if (i < HOTCORNER_IMAX && j < HOTCORNER_JMAX && k < HOTCORNER_KMAX) { state[0][center] = 2.0; } else { state[0][center] = 1.0; } } } } const unsigned long all_cells = (IMAX-2) * (JMAX-2) * (KMAX-2); const unsigned long hot_cells = (HOTCORNER_IMAX-1) * (HOTCORNER_JMAX-1) * (HOTCORNER_KMAX-1); double expected = hot_cells * 2.0 + (all_cells-hot_cells) * 1.0; RecursiveTrapezoid(state, cx, cy, cz, 0, TIMESTEPS, 1, 0, IMAX-1, 0, IMAX, 1, 0, JMAX-1, 0, JMAX, 1, 0, KMAX-1, 0, KMAX); double temperature = 0.0; for (int k = 1; k < KMAX-1; ++k) { for (int j = 1; j < JMAX-1; ++j) { for (int i = 1; i < IMAX-1; ++i) { size_t center = k * JMAX * IMAX + j * IMAX + i; temperature += state[TIMESTEPS & 1][center]; } } } EXPECT_NEAR(expected, temperature, 1.0E-7); } TEST(SimulationTests, HostDeviceEquivalence) { const double nu = 0.05; const double sigma = 0.25; const double width = 2; const double height = 2; const double dx = width / (IMAX-1); const double dy = height / (JMAX-1); const double dz = height / (KMAX-1); const double dt = sigma * dx * dy * dz / nu; const double cx = (nu * dt / (dx * dx)); const double cy = (nu * dt / (dy * dy)); const double cz = (nu * dt / (dz * dz)); // Initialize state double *state_host[2]; double *state_device[2]; state_host[0] = (double *) malloc(IMAX * JMAX * KMAX * sizeof(double)); state_host[1] = (double *) malloc(IMAX * JMAX * KMAX * sizeof(double)); state_device[0] = (double *) malloc(IMAX * JMAX * KMAX * sizeof(double)); state_device[1] = (double *) malloc(IMAX * JMAX * KMAX * sizeof(double)); // Host Data Initialization for (int k = 0; k < KMAX; ++k) { for (int j = 0; j < JMAX; ++j) { for (int i = 0; i < IMAX; ++i) { size_t center = k * JMAX * IMAX + j * IMAX + i; if (i < HOTCORNER_IMAX && j < HOTCORNER_JMAX && k < HOTCORNER_KMAX) { state_host[0][center] = 2.0; state_device[0][center] = 2.0; } else { state_host[0][center] = 1.0; state_device[0][center] = 1.0; } } } } RecursiveTrapezoidHost(state_host, cx, cy, cz, 0, TIMESTEPS, 1, 0, IMAX-1, 0, IMAX, 1, 0, JMAX-1, 0, JMAX, 1, 0, KMAX-1, 0, KMAX); RecursiveTrapezoid(state_device, cx, cy, cz, 0, TIMESTEPS, 1, 0, IMAX-1, 0, IMAX, 1, 0, JMAX-1, 0, JMAX, 1, 0, KMAX-1, 0, KMAX); for (int k = 1; k < KMAX-1; ++k) { for (int j = 1; j < JMAX-1; ++j) { for (int i = 1; i < IMAX-1; ++i) { size_t center = k * JMAX * IMAX + j * IMAX + i; ASSERT_NEAR(state_host[0][center], state_device[0][center], 1.0E-7); ASSERT_NEAR(state_host[1][center], state_device[1][center], 1.0E-7); } } } }
35.438356
95
0.51849
csrhau
10f13b1c047fa6a2760ca8c2237bfacde6411eec
3,421
cpp
C++
Source/src/ezcard/parameter/image_type.cpp
ProtonMail/cpp-openpgp
b47316c51357b8d15eb3bcc376ea5e59a6a9a108
[ "MIT" ]
5
2019-10-30T06:10:10.000Z
2020-04-25T16:52:06.000Z
Source/src/ezcard/parameter/image_type.cpp
ProtonMail/cpp-openpgp
b47316c51357b8d15eb3bcc376ea5e59a6a9a108
[ "MIT" ]
null
null
null
Source/src/ezcard/parameter/image_type.cpp
ProtonMail/cpp-openpgp
b47316c51357b8d15eb3bcc376ea5e59a6a9a108
[ "MIT" ]
2
2019-11-27T23:47:54.000Z
2020-01-13T16:36:03.000Z
// // image_type.cpp // OpenPGP // // Created by Yanfeng Zhang on 1/10/17. // // The MIT License // // Copyright (c) 2019 Proton Technologies AG // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "image_type.hpp" #include "string_util.hpp" MediaTypeCaseClasses<ImageType> ImageType::enums; const ImageType::Ptr ImageType::GIF = std::make_shared<ImageType>("GIF", "image/gif", "gif"); const ImageType::Ptr ImageType::JPEG = std::make_shared<ImageType>("JPEG", "image/jpeg", "jpg"); const ImageType::Ptr ImageType::PNG = std::make_shared<ImageType>("PNG", "image/png", "png"); ImageType::ImageType(const std::string& value, const std::string& mediaType, const std::string& extension) : MediaTypeParameter(value, mediaType, extension) { } /** * Searches for a parameter value that is defined as a static constant in * this class. * @param type the TYPE parameter value to search for (e.g. "JPEG") or null * to not search by this value * @param mediaType the media type to search for (e.g. "image/png") or null * to not search by this value * @param extension the file extension to search for (excluding the ".", * e.g. "jpg") or null to not search by this value * @return the object or null if not found */ ImageType::Ptr ImageType::find(const std::string& type, const std::string& mediaType, const std::string& extension) { return enums.find({type, mediaType, extension}); } /** * Searches for a parameter value and creates one if it cannot be found. All * objects are guaranteed to be unique, so they can be compared with * {@code ==} equality. * @param type the TYPE parameter value to search for (e.g. "JPEG") or null * to not search by this value * @param mediaType the media type to search for (e.g. "image/png") or null * to not search by this value * @param extension the file extension to search for (excluding the ".", * e.g. "jpg") or null to not search by this value * @return the object */ ImageType::Ptr ImageType::get(const std::string& type, const std::string& mediaType, const std::string& extension) { return enums.get({type, mediaType, extension}); } // // /** // * Gets all of the parameter values that are defined as static constants in // * this class. // * @return the parameter values // */ // public static Collection<ImageType> all() { // return enums.all(); // } //}
40.72619
117
0.710319
ProtonMail
10f62f1ab4e775ba10d4203cbd11d5697d89c72c
1,727
cpp
C++
ALGORITHM/WEEK 6 DYNAMIC PROGRAMMING 2/3/placing_parentheses.cpp
Mohit-007/DSA-UCDS-COURSERA
f5826a6f393e3b69ed8cf1c47df4d7a319b2d1fd
[ "MIT" ]
null
null
null
ALGORITHM/WEEK 6 DYNAMIC PROGRAMMING 2/3/placing_parentheses.cpp
Mohit-007/DSA-UCDS-COURSERA
f5826a6f393e3b69ed8cf1c47df4d7a319b2d1fd
[ "MIT" ]
null
null
null
ALGORITHM/WEEK 6 DYNAMIC PROGRAMMING 2/3/placing_parentheses.cpp
Mohit-007/DSA-UCDS-COURSERA
f5826a6f393e3b69ed8cf1c47df4d7a319b2d1fd
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> #include <string> #include <vector> #include <bits/stdc++.h> #include <cstdlib> using std::vector; using std::string; using std::max; using std::min; using namespace std; long long eval(long long a, long long b, char op) { if (op == '*') { return a * b; } else if (op == '+') { return a + b; } else if (op == '-') { return a - b; } else { assert(0); } } long long get_maximum_value(const string &exp) { //write your code here int n = exp.size(); int operands = (n + 1) / 2; long long mini[operands][operands]; long long maxi[operands][operands]; // memset(min, 0, sizeof(min)); // initialize to 0 // memset(max, 0, sizeof(max)); // initialize to 0 for(int i=0;i<operands;i++) { for(int j=0;j<operands;j++) { mini[i][j] = 0; maxi[i][j] = 0; } } for(int i=0;i<operands;i++) { mini[i][i] = strtoull(exp.substr(2 * i, 1)); maxi[i][i] = stol(exp.substr(2 * i, 1)); } for(int s=0; s<operands-1;s++) { for(int i=0;i<operands-s-1;i++) { int j = i + s + 1; long long min_value = LLONG_MAX; long long max_value = LLONG_MIN; for(int k=i;k<j;k++) { long long a = eval(mini[i][k], mini[k + 1][j], exp[2 * k + 1]); long long b = eval(mini[i][k], maxi[k + 1][j], exp[2 * k + 1]); long long c = eval(maxi[i][k], mini[k + 1][j], exp[2 * k + 1]); long long d = eval(maxi[i][k], maxi[k + 1][j], exp[2 * k + 1]); min_value = min(min_value, min(a, min(b, min(c, d)))); max_value = max(max_value, max(a, max(b, max(c, d)))); } mini[i][j] = min_value; maxi[i][j] = max_value; } } return 0; } int main() { string s; std::cin >> s; std::cout << get_maximum_value(s) << '\n'; }
20.317647
66
0.549508
Mohit-007
10f71273a383889fee38e89f0f9fba5deaa2c854
300
cpp
C++
tests/tr1/tests/cvt/cp856/test.cpp
isra-fel/STL
6ae9a578b4f52193dc523922c943a2214a873577
[ "Apache-2.0" ]
8,232
2019-09-16T22:51:24.000Z
2022-03-31T03:55:39.000Z
tests/tr1/tests/cvt/cp856/test.cpp
isra-fel/STL
6ae9a578b4f52193dc523922c943a2214a873577
[ "Apache-2.0" ]
2,263
2019-09-17T05:19:55.000Z
2022-03-31T21:05:47.000Z
tests/tr1/tests/cvt/cp856/test.cpp
isra-fel/STL
6ae9a578b4f52193dc523922c943a2214a873577
[ "Apache-2.0" ]
1,276
2019-09-16T22:51:40.000Z
2022-03-31T03:30:05.000Z
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "tdefs.h" #include <cvt/cp856> #define NCHARS 0x100 #define MYWC_MAX 0xffff #define MYFILE "cp856" #define MYNAME stdext::cvt::codecvt_cp856<wchar_t> #include <cvt_xtest.h>
25
59
0.72
isra-fel
10f7760fece65fb3bc48e3fdf0099b45f678e670
628
cpp
C++
BIT Manipulation/CUPC/swaping.cpp
mushahadur/Home-Work
2e885bc4bfa1a14a86ec858d4e6316fac68c1da6
[ "Apache-2.0" ]
null
null
null
BIT Manipulation/CUPC/swaping.cpp
mushahadur/Home-Work
2e885bc4bfa1a14a86ec858d4e6316fac68c1da6
[ "Apache-2.0" ]
null
null
null
BIT Manipulation/CUPC/swaping.cpp
mushahadur/Home-Work
2e885bc4bfa1a14a86ec858d4e6316fac68c1da6
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { cout<<"Normal Swoaping "<<endl; int num1,num2; cin>>num1>>num2; cout<<"Number1 = :"<<num1<<endl<<"Number2 = :"<<num2<<endl; num1 = num1+num2; num2=num1-num2; num1=num1-num2; cout<<"After Swoap "<<endl; cout<<"Number1 = :"<<num1<<endl<<"Number2 = :"<<num2<<endl; cout<<"Bitwaish Swoaping "<<endl; int a,b; cin>>a>>b; cout<<"Number1 = :"<<a<<endl<<"Number2 = :"<<b<<endl; a=(a^b); b=(a^b); a=(a^b); cout<<"After Swoap "<<endl; cout<<"Number1 = :"<<a<<endl<<"Number2 = :"<<b<<endl; return 0; }
22.428571
63
0.525478
mushahadur
10f8fd573a0af11d90390f982049c10d8f1514d0
22,070
cpp
C++
Sources/Elastos/LibCore/src/elastos/sql/sqlite/CStmt.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/LibCore/src/elastos/sql/sqlite/CStmt.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/LibCore/src/elastos/sql/sqlite/CStmt.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "CStmt.h" #include "sqlitejni.h" #include "elastos/core/CoreUtils.h" using Elastos::Core::CoreUtils; using Elastos::Core::IInteger64; using Elastos::Core::IDouble; using Elastos::Core::EIID_IByte; namespace Elastos { namespace Sql { namespace SQLite { CAR_OBJECT_IMPL(CStmt) CAR_INTERFACE_IMPL(CStmt, Object, IStmt) CStmt::CStmt() : mHandle(0) , mError_code(0) { } CStmt::~CStmt() { Finalize(); } ECode CStmt::Prepare( /* [out] */ Boolean* value) { VALIDATE_NOT_NULL(value); #if HAVE_SQLITE3 hvm *v = (hvm *)mHandle; void *svm = 0; char *tail; Int32 ret; if (v && v->vm) { sqlite3_finalize((sqlite3_stmt *) v->vm); v->vm = 0; } if (v && v->h && v->h->sqlite) { if (!v->tail) { *value = FALSE; return NOERROR; } #if HAVE_SQLITE3_PREPARE16_V2 ret = sqlite3_prepare16_v2((sqlite3 *) v->h->sqlite, v->tail, -1, (sqlite3_stmt **) &svm, (const char **) &tail); #else ret = sqlite3_prepare((sqlite3 *) v->h->sqlite, v->tail, -1, (sqlite3_stmt **) &svm, (const char **) &tail); #endif if (ret != SQLITE_OK) { if (svm) { sqlite3_finalize((sqlite3_stmt *) svm); svm = 0; } } if (ret != SQLITE_OK) { const char *err = sqlite3_errmsg((sqlite3*)v->h->sqlite); mError_code = (Int32)err; v->tail = 0; *value = FALSE; return E_SQL_EXCEPTION; } if (!svm) { v->tail = 0; *value = FALSE; return NOERROR; } v->vm = svm; v->tail = (char *) tail; v->hh.row1 = 1; *value = TRUE; } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::Step( /* [out] */ Boolean* value) { VALIDATE_NOT_NULL(value); #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ret = 0; ret = sqlite3_step((sqlite3_stmt *) v->vm); if (ret == SQLITE_ROW) { *value = TRUE; return NOERROR; } if (ret != SQLITE_DONE) { const char *err = sqlite3_errmsg((sqlite3*)v->h->sqlite); mError_code = (Int32)err; return E_SQL_EXCEPTION; } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif *value = FALSE; return NOERROR; } ECode CStmt::Close() { #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ret = 0; ret = sqlite3_finalize((sqlite3_stmt *) v->vm); v->vm = 0; if (ret != SQLITE_OK) { const char *err = sqlite3_errmsg((sqlite3*)v->h->sqlite); mError_code = (Int32)err; return E_SQL_EXCEPTION; } return NOERROR; } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::Reset() { #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { sqlite3_reset((sqlite3_stmt *) v->vm); } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::ClearBindings() { #if HAVE_SQLITE3 && HAVE_SQLITE3_CLEAR_BINDINGS hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { sqlite3_clear_bindings((sqlite3_stmt *) v->vm); } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::Bind( /* [in] */ Int32 pos, /* [in] */ Int32 value) { #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 npar = sqlite3_bind_parameter_count((sqlite3_stmt *) v->vm); Int32 ret = 0; if (pos < 1 || pos > npar) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } ret = sqlite3_bind_int((sqlite3_stmt *) v->vm, pos, value); if (ret != SQLITE_OK) { mError_code = ret; return E_SQL_EXCEPTION; } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::Bind( /* [in] */ Int32 pos, /* [in] */ Int64 value) { #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 npar = sqlite3_bind_parameter_count((sqlite3_stmt *) v->vm); Int32 ret = 0; if (pos < 1 || pos > npar) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } ret = sqlite3_bind_int64((sqlite3_stmt *) v->vm, pos, value); if (ret != SQLITE_OK) { mError_code = ret; return E_SQL_EXCEPTION; } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::Bind( /* [in] */ Int32 pos, /* [in] */ Double value) { #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 npar = sqlite3_bind_parameter_count((sqlite3_stmt *) v->vm); Int32 ret = 0; if (pos < 1 || pos > npar) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } ret = sqlite3_bind_double((sqlite3_stmt *) v->vm, pos, value); if (ret != SQLITE_OK) { mError_code = ret; return E_SQL_EXCEPTION; } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::Bind( /* [in] */ Int32 pos, /* [in] */ const ArrayOf<Byte>& value) { #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 npar = sqlite3_bind_parameter_count((sqlite3_stmt *) v->vm); Int32 ret = 0; Int32 len = 0; if (pos < 1 || pos > npar) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (value.GetPayload()) { len = value.GetLength(); if (len > 0) { ret = sqlite3_bind_blob((sqlite3_stmt *) v->vm, pos, value.GetPayload(), len, sqlite3_free); } else { ret = sqlite3_bind_blob((sqlite3_stmt *) v->vm, pos, "", 0, SQLITE_STATIC); } } else { ret = sqlite3_bind_null((sqlite3_stmt *) v->vm, pos); } if (ret != SQLITE_OK) { mError_code = ret; return E_SQL_EXCEPTION; } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::Bind( /* [in] */ Int32 pos, /* [in] */ const String& value) { #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 npar = sqlite3_bind_parameter_count((sqlite3_stmt *) v->vm); Int32 ret = 0; UInt32 len = 0; if (pos < 1 || pos > npar) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (!value.IsNull()) { len = value.GetByteLength(); if (len > 0) { ret = sqlite3_bind_text((sqlite3_stmt *) v->vm, pos, value.string(), len, sqlite3_free); } else { ret = sqlite3_bind_text((sqlite3_stmt *) v->vm, pos, "", 0, SQLITE_STATIC); } } else { ret = sqlite3_bind_null((sqlite3_stmt *) v->vm, pos); } if (ret != SQLITE_OK) { mError_code = ret ; return E_SQL_EXCEPTION; } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::Bind( /* [in] */ Int32 pos) { #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 npar = sqlite3_bind_parameter_count((sqlite3_stmt *) v->vm); Int32 ret = 0; if (pos < 1 || pos > npar) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } ret = sqlite3_bind_null((sqlite3_stmt *) v->vm, pos); if (ret != SQLITE_OK) { mError_code = ret; return E_SQL_EXCEPTION; } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::BindZeroblob( /* [in] */ Int32 pos, /* [in] */ Int32 length) { #if HAVE_SQLITE3 && HAVE_SQLITE3_BIND_ZEROBLOB hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 npar = sqlite3_bind_parameter_count((sqlite3_stmt *) v->vm); Int32 ret = 0; if (pos < 1 || pos > npar) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } ret = sqlite3_bind_zeroblob((sqlite3_stmt *) v->vm, pos, len); if (ret != SQLITE_OK) { mError_code = ret; return E_SQL_EXCEPTION; } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::BindParameterCount( /* [out] */ Int32* count) { VALIDATE_NOT_NULL(count); #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { *count = sqlite3_bind_parameter_count((sqlite3_stmt *) v->vm); } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::BindParameterName( /* [in] */ Int32 pos, /* [out] */ String* str) { VALIDATE_NOT_NULL(str); #if HAVE_SQLITE3 && HAVE_SQLITE3_BIND_PARAMETER_NAME hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 npar = sqlite3_bind_parameter_count((sqlite3_stmt *) v->vm); const char *name = NULL; if (pos < 1 || pos > npar) { *str = String(NULL) ; return E_ILLEGAL_ARGUMENT_EXCEPTION; } name = sqlite3_bind_parameter_name((sqlite3_stmt *) v->vm, pos); if (name) { *str = String(name); } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::BindParameterIndex( /* [in] */ const String& name, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index); #if HAVE_SQLITE3 && HAVE_SQLITE3_BIND_PARAMETER_INDEX hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 pos = 0; const char *n = NULL; n = name.string(); pos = sqlite3_bind_parameter_index((sqlite3_stmt *) v->vm, n); *index = pos; } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::ColumnInt( /* [in] */ Int32 col, /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value); #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ncol = sqlite3_data_count((sqlite3_stmt *) v->vm); if (col < 0 || col >= ncol) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } *value = sqlite3_column_int((sqlite3_stmt *) v->vm, col); } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::ColumnLong( /* [in] */ Int32 col, /* [out] */ Int64* value) { VALIDATE_NOT_NULL(value); #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ncol = sqlite3_data_count((sqlite3_stmt *) v->vm); if (col < 0 || col >= ncol) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } *value = sqlite3_column_int64((sqlite3_stmt *) v->vm, col); } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::ColumnDouble( /* [in] */ Int32 col, /* [out] */ Double* value) { VALIDATE_NOT_NULL(value); #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ncol = sqlite3_data_count((sqlite3_stmt *) v->vm); if (col < 0 || col >= ncol) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } *value = sqlite3_column_double((sqlite3_stmt *) v->vm, col); } else { return E_SQL_SQLITE_THROWEX_EXCEPTION; } #else return E_SQL_SQLITE_THROWEX_EXCEPTION; #endif return NOERROR; } ECode CStmt::ColumnBytes( /* [in] */ Int32 col, /* [out, callee] */ ArrayOf<Byte>** array) { VALIDATE_NOT_NULL(array); #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ncol = sqlite3_data_count((sqlite3_stmt *) v->vm); Int32 nbytes = 0; const unsigned char *data = NULL; if (col < 0 || col >= ncol) { *array = NULL; return E_ILLEGAL_ARGUMENT_EXCEPTION; } data = (const unsigned char *)sqlite3_column_blob((sqlite3_stmt *) v->vm, col); if (data) { nbytes = sqlite3_column_bytes((sqlite3_stmt *) v->vm, col); } else { *array = NULL; return E_SQL_EXCEPTION; } AutoPtr<ArrayOf<Byte> > outchar = ArrayOf<Byte>::Alloc(nbytes); outchar->Copy(data, nbytes); *array = outchar; } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::ColumnString( /* [in] */ Int32 col, /* [out] */ String* str) { VALIDATE_NOT_NULL(str); #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ncol = sqlite3_data_count((sqlite3_stmt *) v->vm); const char *data = NULL; if (col < 0 || col >= ncol) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } data = (const char *)sqlite3_column_text((sqlite3_stmt *) v->vm, col); if (data == NULL) { *str = String(NULL); return E_SQL_EXCEPTION; } *str = String((char *)data); } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::ColumnType( /* [in] */ Int32 col, /* [out] */ Int32* type) { VALIDATE_NOT_NULL(type); #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ncol = sqlite3_data_count((sqlite3_stmt *) v->vm); if (col < 0 || col >= ncol) { *type = 0; return E_ILLEGAL_ARGUMENT_EXCEPTION; } *type = sqlite3_column_type((sqlite3_stmt *) v->vm, col); } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::ColumnCount( /* [out] */ Int32* count) { VALIDATE_NOT_NULL(count); #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { *count = sqlite3_column_count((sqlite3_stmt *) v->vm); } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::Column( /* [in] */ Int32 col, /* [out] */ IInterface** obj) { VALIDATE_NOT_NULL(obj); Int32 type = 0; ColumnType(col,&type); switch (type) { case SQLITE_INTEGER: { Int64 value = 0; ColumnLong(col, &value); AutoPtr<IInteger64> val = CoreUtils::Convert(value); *obj = val.Get(); REFCOUNT_ADD(*obj) } break; case SQLITE_FLOAT: { Double value = 0.0; ColumnDouble(col,&value); AutoPtr<IDouble> val = CoreUtils::Convert(value); *obj = val.Get(); REFCOUNT_ADD(*obj) } break; case SQLITE_BLOB: { AutoPtr<ArrayOf<Byte> > value; ColumnBytes(col,(ArrayOf<Byte>**)&value); AutoPtr<IArrayOf> array; CArrayOf::New(EIID_IByte, value->GetLength(), (IArrayOf**)&array); for (Int32 i = 0; i < value->GetLength(); ++i) { AutoPtr<IByte> b = CoreUtils::ConvertByte((*value)[i]); array->Set(i, b.Get()); } *obj = array.Get(); REFCOUNT_ADD(*obj) } break; case SQLITE3_TEXT: { String value; ColumnString(col,&value); AutoPtr<ICharSequence> val = CoreUtils::Convert(value); *obj = val.Get(); REFCOUNT_ADD(*obj) } break; } return NOERROR; } ECode CStmt::ColumnTableName( /* [in] */ Int32 col, /* [out] */ String* str) { VALIDATE_NOT_NULL(str); #if HAVE_SQLITE3 && HAVE_SQLITE3_COLUMN_TABLE_NAME16 hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ncol = sqlite3_column_count((sqlite3_stmt *) v->vm); const char *strchar = NULL; if (col < 0 || col >= ncol) { *str = String(NULL); return E_ILLEGAL_ARGUMENT_EXCEPTION; } strchar = (const char *)sqlite3_column_database_name((sqlite3_stmt *) v->vm, col); if (strchar) { *str = String(strchar); } } else { return E_ILLEGAL_ARGUMENT_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::ColumnDatabaseName( /* [in] */ Int32 col, /* [out] */ String* str) { VALIDATE_NOT_NULL(str); #if HAVE_SQLITE3 && HAVE_SQLITE3_COLUMN_DATABASE_NAME16 hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ncol = sqlite3_column_count((sqlite3_stmt *) v->vm); const char *strchar; if (col < 0 || col >= ncol) { *str = String(NULL); return E_ILLEGAL_ARGUMENT_EXCEPTION; } strchar = sqlite3_column_database_name((sqlite3_stmt *) v->vm, col); if (strchar) { *str = String(strchar); } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::ColumnDecltype( /* [in] */ Int32 col, /* [out] */ String* str) { VALIDATE_NOT_NULL(str); #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ncol = sqlite3_column_count((sqlite3_stmt *) v->vm); const char *strchar; if (col < 0 || col >= ncol) { *str = String(NULL); return E_ILLEGAL_ARGUMENT_EXCEPTION; } strchar = (const char *)sqlite3_column_decltype((sqlite3_stmt *) v->vm, col); if (strchar) { *str = String((char *)strchar); } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::ColumnOriginName( /* [in] */ Int32 col, /* [out] */ String* str) { VALIDATE_NOT_NULL(str); #if HAVE_SQLITE3 && HAVE_SQLITE3_COLUMN_ORIGIN_NAME16 hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { Int32 ncol = sqlite3_column_count((sqlite3_stmt *) v->vm); const char *strchar; if (col < 0 || col >= ncol) { *str = String(NULL); return E_ILLEGAL_ARGUMENT_EXCEPTION; } strchar = sqlite3_column_origin_name((sqlite3_stmt *) v->vm, col); if (strchar) { *str = String(strchar)); } } else { return E_NULL_POINTER_EXCEPTION; } #else return E_SQL_FEATURE_NOT_SUPPORTED_EXCEPTION; #endif return NOERROR; } ECode CStmt::Status( /* [in] */ Int32 op, /* [in] */ Boolean flg, /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value); Int32 count = 0; #if HAVE_SQLITE3 && HAVE_SQLITE3_STMT_STATUS hvm *v = (hvm *)mHandle; if (v && v->vm && v->h) { count = sqlite3_stmt_status((sqlite3_stmt *) v->vm, op, flg == TRUE); } #endif *value = count; return NOERROR; } ECode CStmt::Finalize() { #if HAVE_SQLITE3 && HAVE_SQLITE_COMPILE hvm *v = (hvm *)mHandle; if (v) { if (v->h) { handle *h = v->h; hvm *vv, **vvp; vvp = &h->vms; vv = *vvp; while (vv) { if (vv == v) { *vvp = vv->next; break; } vvp = &vv->next; vv = *vvp; } } if (v->vm) { sqlite3_finalize((sqlite3_stmt *) v->vm); } v->vm = 0; free(v); mHandle = 0; } #endif return NOERROR; } } // namespace SQLite } // namespace Sql } // namespace Elastos
24.853604
90
0.55845
jingcao80
10f911f83e849bde222afe4788744c1d27482882
899
cpp
C++
tests/core/gui/TextTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
null
null
null
tests/core/gui/TextTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
29
2020-10-21T07:34:55.000Z
2021-01-12T15:15:53.000Z
tests/core/gui/TextTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
1
2020-10-19T19:30:40.000Z
2020-10-19T19:30:40.000Z
#include <catch2/catch.hpp> #include "core/gui/Text.h" TEST_CASE("[Text]") { ire::core::gui::Text text; SECTION("HorizontalAlignment") { REQUIRE(text.getHorizontalAlign() == ire::core::gui::Text::HorizontalAlignment::Center); text.setHorizontalAlign(ire::core::gui::Text::HorizontalAlignment::Left); REQUIRE(text.getHorizontalAlign() == ire::core::gui::Text::HorizontalAlignment::Left); } SECTION("VerticalAlignment") { REQUIRE(text.getVerticalAlign() == ire::core::gui::Text::VerticalAlignment::Center); text.setVerticalAlign(ire::core::gui::Text::VerticalAlignment::Bottom); REQUIRE(text.getVerticalAlign() == ire::core::gui::Text::VerticalAlignment::Bottom); } SECTION("Visibilitty") { REQUIRE(text.isVisible() == false); text.setVisible(true); REQUIRE(text.isVisible() == true); } }
35.96
96
0.649611
Kubaaa96
10fbc59ffdda178d9bf3a7efefcc24f33d6eb079
1,360
cpp
C++
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/imageview.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/imageview.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/imageview.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
// // imageview.cpp // MDStudio // // Created by Daniel Cliche on 2014-07-15. // Copyright (c) 2014-2020 Daniel Cliche. All rights reserved. // #include "imageview.h" #include <math.h> #include "draw.h" using namespace MDStudio; // --------------------------------------------------------------------------------------------------------------------- ImageView::ImageView(const std::string& name, void* owner, std::shared_ptr<Image> image, bool isStretched) : _image(image), _isStretched(isStretched), View(name, owner) { _color = whiteColor; } // --------------------------------------------------------------------------------------------------------------------- ImageView::~ImageView() {} // --------------------------------------------------------------------------------------------------------------------- void ImageView::draw() { DrawContext* dc = drawContext(); if (_image) { Rect r = _isStretched ? bounds() : makeCenteredRectInRect(bounds(), floorf(_image->size().width), floorf(_image->size().height)); dc->drawImage(r, _image, _color); } } // --------------------------------------------------------------------------------------------------------------------- void ImageView::setImage(std::shared_ptr<Image> image) { _image = image; setDirty(); }
31.627907
120
0.408088
dcliche
10fcb69233b3531647312d2f824d66dcc1921eda
337
hpp
C++
source/ashes/renderer/GlRenderer/Command/Commands/GlDrawIndirectCommand.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
source/ashes/renderer/GlRenderer/Command/Commands/GlDrawIndirectCommand.hpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
source/ashes/renderer/GlRenderer/Command/Commands/GlDrawIndirectCommand.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
/* This file belongs to Ashes. See LICENSE file in root folder */ #pragma once #include "renderer/GlRenderer/Command/Commands/GlCommandBase.hpp" namespace ashes::gl { void buildDrawIndirectCommand( VkBuffer buffer , VkDeviceSize offset , uint32_t drawCount , uint32_t stride , VkPrimitiveTopology mode , CmdList & list ); }
18.722222
65
0.756677
DragonJoker
10fd90847f0149ef1041ca034a8751cf0bc4150d
599
cc
C++
pixel-standalone/main_cuda.cc
lauracappelli/pixeltrack-standalone-test-oneapi
5832b6680ea0327f124afcfac801addbea458203
[ "Apache-2.0" ]
null
null
null
pixel-standalone/main_cuda.cc
lauracappelli/pixeltrack-standalone-test-oneapi
5832b6680ea0327f124afcfac801addbea458203
[ "Apache-2.0" ]
null
null
null
pixel-standalone/main_cuda.cc
lauracappelli/pixeltrack-standalone-test-oneapi
5832b6680ea0327f124afcfac801addbea458203
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <memory> #include "analyzer_cuda.h" #include "input.h" #include "modules.h" #include "output.h" int main(int argc, char** argv) { Input input = read_input(); std::cout << "Got " << input.cablingMap.size << " for cabling, wordCounter " << input.wordCounter << std::endl; std::unique_ptr<Output> output = std::make_unique<Output>(); double totaltime = 0; cuda::analyze(input, *output, totaltime); std::cout << "Output: " << countModules(output->moduleInd, input.wordCounter) << " modules in " << totaltime << " us" << std::endl; return 0; }
27.227273
119
0.647746
lauracappelli
800b89559fa8c25641afa66383c52d14fd764e4c
6,134
hpp
C++
firmware/library/L2_HAL/displays/oled/ssd1306.hpp
Adam-D-Sanchez/SJSU-Dev2
ecb5bb01912f6f85a76b6715d0e72f2d3062ceed
[ "Apache-2.0" ]
null
null
null
firmware/library/L2_HAL/displays/oled/ssd1306.hpp
Adam-D-Sanchez/SJSU-Dev2
ecb5bb01912f6f85a76b6715d0e72f2d3062ceed
[ "Apache-2.0" ]
null
null
null
firmware/library/L2_HAL/displays/oled/ssd1306.hpp
Adam-D-Sanchez/SJSU-Dev2
ecb5bb01912f6f85a76b6715d0e72f2d3062ceed
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstddef> #include <cstdint> #include "config.hpp" #include "L1_Drivers/gpio.hpp" #include "L1_Drivers/ssp.hpp" #include "L2_HAL/displays/pixel_display.hpp" #include "utility/log.hpp" class Ssd1306 : public PixelDisplayInterface { public: static constexpr size_t kColumns = 128; static constexpr size_t kWidth = kColumns; // pixels static constexpr size_t kColumnHeight = 8; // bits static constexpr size_t kHeight = 64; // pixels static constexpr size_t kPages = kHeight / kColumnHeight; // rows static constexpr size_t kRows = kPages; enum class Transaction { kCommand = 0, kData = 1 }; constexpr Ssd1306() : ssp_(&ssp1_), cs_(&cs_gpio_), dc_(&dc_gpio_), ssp1_(Ssp::Peripheral::kSsp1), cs_gpio_(1, 22), dc_gpio_(1, 25), bitmap_{} { } constexpr Ssd1306(Ssp * ssp, Gpio * cs, Gpio * dc) : ssp_(ssp), cs_(cs), dc_(dc), ssp1_(), cs_gpio_(1, 22), dc_gpio_(1, 25), bitmap_{} { } size_t GetWidth() final override { return kWidth; } size_t GetHeight() final override { return kHeight; } Color_t AvailableColors() final override { return Color_t(/* Red = */ 1, /* Green = */ 1, /* Blue = */ 1, /* Alpha = */ 1, /* Color Bits = */ 1, /* Monochrome = */ true); } void Write(uint32_t data, Transaction transaction, size_t size = 1) { dc_->Set(static_cast<Gpio::State>(transaction)); cs_->SetLow(); for (size_t i = 0; i < size; i++) { uint8_t send = static_cast<uint8_t>(data >> (((size - 1) - i) * 8)); if (transaction == Transaction::kCommand) { LOG_DEBUG("send = 0x%X", send); } ssp_->Transfer(send); } cs_->SetHigh(); } void InitializationPanel() { // This sequence of commands was found in: // datasheets/OLED-display/ER-OLED0.96-1_Series_Datasheet.pdf, page 15 // turn off oled panel Write(0xAE, Transaction::kCommand); // set display clock divide ratio/oscillator frequency // set divide ratio Write(0xD5'80, Transaction::kCommand, 2); // set multiplex ratio(1 to 64) // 1/64 duty Write(0xA8'3F, Transaction::kCommand, 2); // set display offset = not offset Write(0xD3'00, Transaction::kCommand, 2); // Set display start line Write(0x40, Transaction::kCommand); // Disable Charge Pump Write(0x8D'14, Transaction::kCommand, 2); // set segment re-map 128 to 0 Write(0xA1, Transaction::kCommand); // Set COM Output Scan Direction 64 to 0 Write(0xC8, Transaction::kCommand); // set com pins hardware configuration Write(0xDA'12, Transaction::kCommand, 2); // set contrast control register Write(0x81'CF, Transaction::kCommand, 2); // Set pre-charge period Write(0xD9'F1, Transaction::kCommand, 2); // Set Vcomh Write(0xDB'40, Transaction::kCommand, 2); SetHorizontalAddressMode(); // Enable entire display Write(0xA4, Transaction::kCommand); // Set display to normal colors Write(0xA6, Transaction::kCommand); // Set Display On Write(0xAF, Transaction::kCommand); } void Initialize() final override { cs_->SetAsOutput(); dc_->SetAsOutput(); cs_->SetHigh(); dc_->SetHigh(); ssp_->SetPeripheralMode(Ssp::MasterSlaveMode::kMaster, Ssp::FrameMode::kSpi, Ssp::DataSize::kEight); // Set speed to 1Mhz by dividing by 1 * ClockFrequencyInMHz. ssp_->SetClock(false, false, 100, config::kSystemClockRateMhz); ssp_->Initialize(); Clear(); InitializationPanel(); } void SetHorizontalAddressMode() { // Set Addressing mode // Addressing mode = Horizontal Mode (0b00) Write(0x20'00, Transaction::kCommand, 2); // Set Column Addresses // Set Column Address start = Column 0 // Set Column Address start = Column 127 Write(0x21'00'7F, Transaction::kCommand, 3); // Set Page Addresses // Set Page Address start = Page 0 // Set Page Address start = Page 7 Write(0x22'00'07, Transaction::kCommand, 3); } /// Clears the internal bitmap_ to zero (or a user defined clear_value) void Clear() final override { memset(bitmap_, 0x00, sizeof(bitmap_)); } void Fill() { memset(bitmap_, 0xFF, sizeof(bitmap_)); } void DrawPixel(int32_t x, int32_t y, Color_t color) final override { // The 3 least significant bits hold the bit position within the byte uint32_t bit_position = y & 0b111; // Each byte makes up a vertical column. // Shifting by 3, which also divides by 8 (the 8-bits of a column), will // be the row that we need to edit. uint32_t row = y >> 3; // Mask to clear the bit uint32_t clear_mask = ~(1 << bit_position); // Mask to set the bit, if color.alpha != 0 bool pixel_is_on = (color.alpha != 0); uint32_t set_mask = pixel_is_on << bit_position; // Address of the pixel column to edit uint8_t * pixel_column = &(bitmap_[row][x]); // Read pixel column and update the pixel uint32_t result = (*pixel_column & clear_mask) | set_mask; // Update pixel with the result of this operation *pixel_column = static_cast<uint8_t>(result); } /// Writes internal bitmap_ to the screen void Update() final override { SetHorizontalAddressMode(); for (size_t row = 0; row < kRows; row++) { for (size_t column = 0; column < kColumns; column++) { Write(bitmap_[row][column], Transaction::kData); } } } void InvertScreenColor() __attribute__((used)) { Write(0xA7, Transaction::kCommand); } void NormalScreenColor() __attribute__((used)) { Write(0xA6, Transaction::kCommand); } private: Ssp * ssp_; Gpio * cs_; Gpio * dc_; Ssp ssp1_; Gpio cs_gpio_; Gpio dc_gpio_; uint8_t bitmap_[kRows + 5][kColumns + 5]; };
26.669565
80
0.610205
Adam-D-Sanchez
800dde40d565d7c0a93918f0b54ebdc223576c86
864
cpp
C++
source/FAST/Examples/DataImport/clariusStreaming.cpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
source/FAST/Examples/DataImport/clariusStreaming.cpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
source/FAST/Examples/DataImport/clariusStreaming.cpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
/** * @example clariusStreaming.cpp */ #include <FAST/Streamers/ClariusStreamer.hpp> #include <FAST/Visualization/SimpleWindow.hpp> #include <FAST/Visualization/ImageRenderer/ImageRenderer.hpp> #include <FAST/Tools/CommandLineParser.hpp> using namespace fast; int main(int argc, char**argv) { CommandLineParser parser("Clarius streaming example"); parser.addVariable("port", "5858", "Port to use for clarius connection"); parser.addVariable("ip", "192.168.1.1", "Address to use for clarius connection"); parser.parse(argc, argv); auto streamer = ClariusStreamer::create(parser.get("ip"), parser.get<int>("port")); auto renderer = ImageRenderer::create() ->connect(streamer); auto window = SimpleWindow2D::create() ->connect(renderer); window->getView()->setAutoUpdateCamera(true); window->run(); }
33.230769
87
0.701389
andreped
800def1166e8d585db0ff3ee0995134949bc6a9f
2,459
cpp
C++
UVa Online Judge/1056 - Degrees of Separation.cpp
SamanKhamesian/ACM-ICPC-Problems
c68c04bee4de9ba9f30e665cd108484e0fcae4d7
[ "Apache-2.0" ]
2
2019-03-19T23:59:48.000Z
2019-03-21T20:13:12.000Z
UVa Online Judge/1056 - Degrees of Separation.cpp
SamanKhamesian/ACM-ICPC-Problems
c68c04bee4de9ba9f30e665cd108484e0fcae4d7
[ "Apache-2.0" ]
null
null
null
UVa Online Judge/1056 - Degrees of Separation.cpp
SamanKhamesian/ACM-ICPC-Problems
c68c04bee4de9ba9f30e665cd108484e0fcae4d7
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <algorithm> #include <string> #include <queue> #include <map> #include <vector> using namespace std; int n, q, v, w, degree = 0; string firstName, secondName; vector<vector<int>> list; queue<int> endof; vector <bool> marked; void dfs(int b) { marked[b] = true; for (int i = 0; i < list[b].size(); i++) { if (!marked[list[b][i]]) { dfs(list[b][i]); } } } int bfs(int a) { int m = 0, counter = 0; vector<int> parent; vector<bool> visited; queue<int> bfsq; parent.resize(n + 1); visited.resize(n + 1); visited[a] = true; bfsq.push(a); parent[a] = -1; while (!bfsq.empty()) { int temp = bfsq.front(); bfsq.pop(); for (int i = 0; i < list[temp].size(); i++) { if (!visited[list[temp][i]]) { bfsq.push(list[temp][i]); visited[list[temp][i]] = true; parent[list[temp][i]] = temp; } } } for (int i = 1; i <= n; i++) { int j = i; while (parent[j] != -1) { counter++; j = parent[j]; } m = max(counter, m); counter = 0; } return m; } int main() { int test = 0; bool ok = true; cin >> n >> q; while (n != 0 && q != 0) { test++; map <string, int> names; list.resize(n + 1); marked.resize(n + 1); int index = 1; for (int i = 1; i <= q; i++) { cin >> firstName >> secondName; if (names[firstName] == 0) { v = index++; names[firstName] = v; } else { v = names[firstName]; } if (names[secondName] == 0) { w = index++; names[secondName] = w; } else { w = names[secondName]; } list[v].push_back(w); list[w].push_back(v); } dfs(1); for (int i = 1; i <= n; i++) { if (!marked[i]) { ok = false; } } if (ok) { for (int i = 1; i <= n; i++) { degree = max(bfs(i), degree); } endof.push(degree); } else { endof.push(-1); } for (int i = 1; i <= n; i++) { list.pop_back(); marked[i] = false; } cin >> n >> q; ok = true; degree = 0; } for (int i = 1; i <= test ; i++) { cout << "Network " << i << ": "; if (endof.front() != -1) { cout << endof.front() << endl << endl; } else { cout << "DISCONNECTED" << endl << endl; } endof.pop(); } }
12.356784
46
0.445303
SamanKhamesian
801015bf1c7bc7153e57400a0fa9be4abb286cd6
4,199
cc
C++
plugins/src/PairConvFilter.cc
omar-moreno/simulation-formerly-known-as-slic
331d0452d05762e2f4554f0ace6fe46922a7333c
[ "BSD-3-Clause-LBNL" ]
null
null
null
plugins/src/PairConvFilter.cc
omar-moreno/simulation-formerly-known-as-slic
331d0452d05762e2f4554f0ace6fe46922a7333c
[ "BSD-3-Clause-LBNL" ]
null
null
null
plugins/src/PairConvFilter.cc
omar-moreno/simulation-formerly-known-as-slic
331d0452d05762e2f4554f0ace6fe46922a7333c
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "PairConvFilter.hh" //------------// // Geant4 // //------------// #include "G4RunManager.hh" namespace slic { G4ClassificationOfNewTrack PairConvFilter::stackingClassifyNewTrack( const G4Track *track, const G4ClassificationOfNewTrack &currentTrackClass) { if (track == currentTrack_) { currentTrack_ = nullptr; // std::cout << "[ PairConvFilter ]: Pushing track to waiting stack." // << std::endl; return fWaiting; } // Use current classification by default so values from other plugins are // not overridden. return currentTrackClass; } void PairConvFilter::stepping(const G4Step *step) { if (hasPairConv_) return; // Get the track associated with this step. auto track{step->GetTrack()}; // Get the particle type. auto particleName{track->GetParticleDefinition()->GetParticleName()}; // Get the kinetic energy of the particle. auto incidentParticleEnergy{step->GetPostStepPoint()->GetTotalEnergy()}; auto pdgID{track->GetParticleDefinition()->GetPDGEncoding()}; // Get the volume the particle is in. auto volume{track->GetVolume()}; auto volumeName{volume->GetName()}; /* std::cout << "*******************************" << std::endl; std::cout << "* Step " << track->GetCurrentStepNumber() << std::endl; std::cout << "********************************\n" << "\tTotal energy of " << particleName << " ( PDG ID: " << pdgID << " ) : " << incidentParticleEnergy << " MeV\n" << "\tTrack ID: " << track->GetTrackID() << "\n" << "\tParticle currently in " << volumeName << "\n" << "\tPost step process: " << step->GetPostStepPoint()->GetStepStatus() << std::endl;*/ // Get the PDG ID of the track and make sure it's a photon. If another // particle type is found, push it to the waiting stack until the photon has // been processed. if (pdgID != 22) { currentTrack_ = track; track->SetTrackStatus(fSuspend); return; } // Only conversions that happen in the target, and layers 1-3 // of the tracker are of interest. If the photon has propagated past // the second layer and didn't convert, kill the event. // TODO: OM: This really should be done with regions. if (volumeName.find("module_L4") != std::string::npos) { // std::cout << "[ PairConvFilter ]: Photon is beyond the sensitive" // << " detectors of interest. Killing event." << std::endl; track->SetTrackStatus(fKillTrackAndSecondaries); G4RunManager::GetRunManager()->AbortEvent(); return; } else if ((volumeName.find("module_L1") == std::string::npos) && (volumeName.find("module_L2") == std::string::npos) && (volumeName.find("module_L3") == std::string::npos)) { // std::cout << "[ PairConvFilter ]: Photon is not within sensitive " // << " detectors of interest." << std::endl; return; } // Check if any secondaries were produced in the volume. const std::vector<const G4Track *> *secondaries = step->GetSecondaryInCurrentStep(); // std::cout << "[ PairConvFilter ]: " // << particleName << " produced " << secondaries->size() // << " secondaries." << std::endl; // If the particle didn't produce any secondaries, stop processing // the event. if (secondaries->size() == 0) { // std::cout << "[ PairConvFilter ]: " // << "Primary did not produce secondaries!" // << std::endl; return; } auto processName{(*secondaries)[0]->GetCreatorProcess()->GetProcessName()}; if (processName.compareTo("conv") == 0) { hasPairConv_ = true; ++pairConvCount_; std::cout << "[ PairConvFilter ]: " << "WAB converted in " << volumeName << std::endl; } else { track->SetTrackStatus(fKillTrackAndSecondaries); G4RunManager::GetRunManager()->AbortEvent(); return; } } void PairConvFilter::endEvent(const G4Event *) { hasPairConv_ = false; } void PairConvFilter::endRun(const G4Run *run) { std::cout << "[ PairConvFilter ]: " << "Total number of pair conversions: " << pairConvCount_ << std::endl; } } // namespace slic DECLARE_PLUGIN(slic, PairConvFilter)
34.418033
80
0.618242
omar-moreno
80101ec74538ebee838e07fdc1b0c6f743f94c2a
438
cpp
C++
Chapter16/cfgdemo/cfgdemo.cpp
fengjixuchui/Win10SysProgBookSamples
360aff30a19da2ea4c9be6f41c481aa8bf39a2b0
[ "MIT" ]
249
2019-07-09T17:14:43.000Z
2022-03-28T01:54:26.000Z
Chapter16/cfgdemo/cfgdemo.cpp
fengjixuchui/Win10SysProgBookSamples
360aff30a19da2ea4c9be6f41c481aa8bf39a2b0
[ "MIT" ]
8
2019-07-12T21:08:29.000Z
2022-01-04T12:32:00.000Z
Chapter16/cfgdemo/cfgdemo.cpp
isabella232/Win10SysProgBookSamples
97e479a9a4923ecf94866bae516a76bde02ef71e
[ "MIT" ]
70
2019-07-10T02:14:55.000Z
2022-03-08T00:53:07.000Z
// cfgdemo.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> class A { public: virtual ~A() = default; virtual void DoWork(int x) { printf("A::DoWork %d\n", x); } }; class B : public A { public: void DoWork(int x) override { printf("B::DoWork %d\n", x); } }; int main() { A a; a.DoWork(10); B b; b.DoWork(20); A* pA = new B; pA->DoWork(30); delete pA; }
12.882353
97
0.605023
fengjixuchui
80113427fd80ee179df6ecd8a9649896a9ca6f07
413
cc
C++
sentinel-core/test/mock/flow/mock.cc
windrunner123/sentinel-cpp
7957e692466db0b7b83b7218602757113e9f2d22
[ "Apache-2.0" ]
121
2019-02-22T06:50:31.000Z
2022-01-22T23:23:42.000Z
sentinel-core/test/mock/flow/mock.cc
windrunner123/sentinel-cpp
7957e692466db0b7b83b7218602757113e9f2d22
[ "Apache-2.0" ]
24
2019-05-07T08:58:38.000Z
2022-01-26T02:36:06.000Z
sentinel-core/test/mock/flow/mock.cc
windrunner123/sentinel-cpp
7957e692466db0b7b83b7218602757113e9f2d22
[ "Apache-2.0" ]
36
2019-03-19T09:46:08.000Z
2021-11-24T13:20:56.000Z
#include "sentinel-core/test/mock/flow/mock.h" namespace Sentinel { namespace Flow { MockTrafficShapingChecker::MockTrafficShapingChecker() = default; MockTrafficShapingChecker::~MockTrafficShapingChecker() = default; MockTrafficShapingCalculator::MockTrafficShapingCalculator() = default; MockTrafficShapingCalculator::~MockTrafficShapingCalculator() = default; } // namespace Flow } // namespace Sentinel
29.5
72
0.813559
windrunner123
80135360f9ed8dac2676aee65e4550af78b0ca6b
6,104
cpp
C++
build/qCC/CloudCompare_autogen/include_Debug/EWIEGA46WW/moc_ccOverlayDialog.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
build/qCC/CloudCompare_autogen/include_Debug/EWIEGA46WW/moc_ccOverlayDialog.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
build/qCC/CloudCompare_autogen/include_Debug/EWIEGA46WW/moc_ccOverlayDialog.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
1
2019-02-03T12:19:42.000Z
2019-02-03T12:19:42.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'ccOverlayDialog.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../../../qCC/ccOverlayDialog.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'ccOverlayDialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.11.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_ccOverlayDialog_t { QByteArrayData data[9]; char stringdata0[100]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ccOverlayDialog_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ccOverlayDialog_t qt_meta_stringdata_ccOverlayDialog = { { QT_MOC_LITERAL(0, 0, 15), // "ccOverlayDialog" QT_MOC_LITERAL(1, 16, 15), // "processFinished" QT_MOC_LITERAL(2, 32, 0), // "" QT_MOC_LITERAL(3, 33, 8), // "accepted" QT_MOC_LITERAL(4, 42, 17), // "shortcutTriggered" QT_MOC_LITERAL(5, 60, 3), // "key" QT_MOC_LITERAL(6, 64, 5), // "shown" QT_MOC_LITERAL(7, 70, 22), // "onLinkedWindowDeletion" QT_MOC_LITERAL(8, 93, 6) // "object" }, "ccOverlayDialog\0processFinished\0\0" "accepted\0shortcutTriggered\0key\0shown\0" "onLinkedWindowDeletion\0object" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ccOverlayDialog[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 5, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 3, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 39, 2, 0x06 /* Public */, 4, 1, 42, 2, 0x06 /* Public */, 6, 0, 45, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 7, 1, 46, 2, 0x09 /* Protected */, 7, 0, 49, 2, 0x29 /* Protected | MethodCloned */, // signals: parameters QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Int, 5, QMetaType::Void, // slots: parameters QMetaType::Void, QMetaType::QObjectStar, 8, QMetaType::Void, 0 // eod }; void ccOverlayDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { ccOverlayDialog *_t = static_cast<ccOverlayDialog *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->processFinished((*reinterpret_cast< bool(*)>(_a[1]))); break; case 1: _t->shortcutTriggered((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: _t->shown(); break; case 3: _t->onLinkedWindowDeletion((*reinterpret_cast< QObject*(*)>(_a[1]))); break; case 4: _t->onLinkedWindowDeletion(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (ccOverlayDialog::*)(bool ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ccOverlayDialog::processFinished)) { *result = 0; return; } } { using _t = void (ccOverlayDialog::*)(int ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ccOverlayDialog::shortcutTriggered)) { *result = 1; return; } } { using _t = void (ccOverlayDialog::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ccOverlayDialog::shown)) { *result = 2; return; } } } } QT_INIT_METAOBJECT const QMetaObject ccOverlayDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_ccOverlayDialog.data, qt_meta_data_ccOverlayDialog, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *ccOverlayDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ccOverlayDialog::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_ccOverlayDialog.stringdata0)) return static_cast<void*>(this); return QDialog::qt_metacast(_clname); } int ccOverlayDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 5) qt_static_metacall(this, _c, _id, _a); _id -= 5; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 5) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 5; } return _id; } // SIGNAL 0 void ccOverlayDialog::processFinished(bool _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void ccOverlayDialog::shortcutTriggered(int _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void ccOverlayDialog::shown() { QMetaObject::activate(this, &staticMetaObject, 2, nullptr); } QT_WARNING_POP QT_END_MOC_NAMESPACE
33.723757
106
0.589613
ohanlonl
8013b7bf5844cbc6699c712c489a2f5c058078f5
29,989
cc
C++
visitor/variant.test.cc
jssmith/stigdb
4b4ade62299f8c6bc1d1aaf5f93dd4b77aa23104
[ "Apache-2.0" ]
null
null
null
visitor/variant.test.cc
jssmith/stigdb
4b4ade62299f8c6bc1d1aaf5f93dd4b77aa23104
[ "Apache-2.0" ]
null
null
null
visitor/variant.test.cc
jssmith/stigdb
4b4ade62299f8c6bc1d1aaf5f93dd4b77aa23104
[ "Apache-2.0" ]
1
2020-01-03T20:13:50.000Z
2020-01-03T20:13:50.000Z
/* <visitor/variant.test.cc> Unit test for <visitor/variant.h>. Copyright 2010-2014 Stig LLC 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 <visitor/variant.h> #include <array> #include <condition_variable> #include <iostream> #include <future> #include <list> #include <mutex> #include <sstream> #include <string> #include <type_traits> #include <vector> #include <mpl/and.h> #include <mpl/contains.h> #include <mpl/get_union.h> #include <mpl/type_set.h> #include <visitor/visitor.h> #include <test/kit.h> using namespace Visitor; class FooFamily; using TFoo = TVariant<FooFamily>; namespace Visitor { template <> struct TVariant<FooFamily>::Members { using All = Mpl::TTypeSet<int, std::string, std::vector<TFoo>>; }; // TVariant<FooFamily>::Members } // Visitor template <typename TMember> using IsFoo = Mpl::Contains<TFoo::Members::All, c14::decay_t<TMember>>; FIXTURE(Stateless) { TFoo variant; EXPECT_FALSE(variant); } FIXTURE(Stateful) { TFoo variant = TFoo::New(42); EXPECT_TRUE(variant); variant.Reset(); EXPECT_FALSE(variant); } /** * void return type, no extra parameters. **/ // print_name.h struct TPrintName { void operator()(int) const; void operator()(const std::string &) const; void operator()(const std::vector<TFoo> &) const; }; // TPrintName template <typename TMember> requires<IsFoo<TMember>::value, void> PrintName(TMember &&member) { TPrintName()(std::forward<TMember>(member)); } void PrintName(const TFoo &that); // print_name.cc void TPrintName::operator()(int) const { std::cout << "int" << std::endl; } void TPrintName::operator()(const std::string &) const { std::cout << "std::string" << std::endl; } void TPrintName::operator()(const std::vector<TFoo> &) const { std::cout << "std::vector<TFoo>" << std::endl; } void PrintName(const TFoo &that) { Single::Accept<TFoo::TApplier<TPrintName>>(that); }; // print_name.test.cc FIXTURE(PrintName) { /* int */ { TFoo variant = TFoo::New(0); PrintName(variant); } /* std::string */ { TFoo variant = TFoo::New(std::string("Hello")); PrintName(variant); } /* std::vector<TFoo> */ { TFoo variant = TFoo::New( std::vector<TFoo>{TFoo::New(42), TFoo::New(std::string("Hello")), TFoo::New(24), TFoo::New(std::vector<TFoo>{})}); PrintName(variant); } } /** * non-void return type, no extra parameters. **/ // get_int.h struct TGetInt { int operator()(int that) const; int operator()(const std::string &that) const; int operator()(const std::vector<TFoo> &that) const; }; // TGetInt template <typename TMember> requires<IsFoo<TMember>::value, int> GetInt(TMember &&member) { return TGetInt()(std::forward<TMember>(member)); } int GetInt(const TFoo &that); // get_int.cc int TGetInt::operator()(int that) const { return that; } int TGetInt::operator()(const std::string &that) const { assert(&that); return stoi(that); } int TGetInt::operator()(const std::vector<TFoo> &that) const { assert(&that); int result = 0; for (const auto &variant : that) { result += GetInt(variant); } return result; } int GetInt(const TFoo &that) { return Single::Accept<TFoo::TApplier<TGetInt>>(that); } // get_int.test.cc FIXTURE(GetInt) { /* int */ { TFoo variant = TFoo::New(42); EXPECT_EQ(GetInt(variant), 42); } /* std::string */ { TFoo variant = TFoo::New(std::string("42")); EXPECT_EQ(GetInt(variant), 42); } /* std::vector<TFoo> */ { TFoo variant = TFoo::New(std::vector<TFoo>{ TFoo::New(23), TFoo::New(std::string("42")), TFoo::New(5), TFoo::New( std::vector<TFoo>{TFoo::New(9), TFoo::New(std::string("22"))})}); EXPECT_EQ(GetInt(variant), 101); } } /** * void return type, extra parameters. **/ // write_name.h struct TWriteName { std::ostream &operator()(int, std::ostream &strm) const; std::ostream &operator()(const std::string &, std::ostream &strm) const; std::ostream &operator()(const std::vector<TFoo> &, std::ostream &strm) const; }; // TWriteName template <typename TMember> requires<IsFoo<TMember>::value, std::ostream &> WriteName(TMember &&member, std::ostream &strm) { return TWriteName()(std::forward<TMember>(member), strm); } std::ostream &WriteName(const TFoo &that, std::ostream &strm); // write_name.cc std::ostream &TWriteName::operator()(int, std::ostream &strm) const { return strm << "int"; }; std::ostream &TWriteName::operator()(const std::string &, std::ostream &strm) const { return strm << "std::string"; } std::ostream &TWriteName::operator()(const std::vector<TFoo> &, std::ostream &strm) const { return strm << "std::vector<TFoo>"; } std::ostream &WriteName(const TFoo &that, std::ostream &strm) { return Single::Accept<TFoo::TApplier<TWriteName>>(that, strm); }; // write_name.test.cc FIXTURE(WriteName) { /* int */ { std::ostringstream strm; TFoo variant = TFoo::New(0); WriteName(variant, strm); EXPECT_EQ(strm.str(), "int"); } /* std::string */ { std::ostringstream strm; TFoo variant = TFoo::New(std::string("Hello")); WriteName(variant, strm); EXPECT_EQ(strm.str(), "std::string"); } /* std::vector<TFoo> */ { std::ostringstream strm; TFoo variant = TFoo::New( std::vector<TFoo>{TFoo::New(std::string("Hello")), TFoo::New(42)}); WriteName(variant, strm); EXPECT_EQ(strm.str(), "std::vector<TFoo>"); } } /** * non-void return type, extra parameters. **/ // get_area_and_write_vector.h struct TGetIntAndWriteVector { int operator()(int that, std::ostream &strm, const std::vector<int> &ints) const; int operator()(const std::string &that, std::ostream &strm, const std::vector<int> &ints) const; int operator()(const std::vector<TFoo> &that, std::ostream &strm, const std::vector<int> &ints) const; }; // TGetIntAndWriteVector template <typename TMember> requires<IsFoo<TMember>::value, int> GetIntAndWriteVector(TMember &&member, std::ostream &strm, const std::vector<int> &ints) { return TGetIntAndWriteVector()(std::forward<TMember>(member), strm, ints); } int GetIntAndWriteVector(const TFoo &that, std::ostream &strm, const std::vector<int> &ints); // get_area_and_write_vector.cc int TGetIntAndWriteVector::operator()(int that, std::ostream &strm, const std::vector<int> &ints) const { for (const auto &i : ints) { strm << i; } return GetInt(that); } int TGetIntAndWriteVector::operator()(const std::string &that, std::ostream &strm, const std::vector<int> &ints) const { assert(&that); for (const auto &i : ints) { strm << i; } return GetInt(that); } int TGetIntAndWriteVector::operator()(const std::vector<TFoo> &that, std::ostream &strm, const std::vector<int> &ints) const { assert(&that); for (const auto &i : ints) { strm << i; } return GetInt(that); } int GetIntAndWriteVector(const TFoo &that, std::ostream &strm, const std::vector<int> &ints) { using applier_t = TFoo::TApplier<TGetIntAndWriteVector>; return Single::Accept<applier_t>(that, strm, ints); } // get_area_and_write_vector.test.cc FIXTURE(GetIntAndWriteVector) { /* int */ { std::ostringstream strm; TFoo variant = TFoo::New(101); EXPECT_EQ(GetIntAndWriteVector(variant, strm, {0, 1, 2, 3, 4}), 101); EXPECT_EQ(strm.str(), "01234"); } /* std::string */ { std::ostringstream strm; TFoo variant = TFoo::New(std::string("101")); EXPECT_EQ(GetIntAndWriteVector(variant, strm, {5, 6, 7, 8, 9}), 101); EXPECT_EQ(strm.str(), "56789"); } /* std::vector<TFoo> */ { std::ostringstream strm; TFoo variant = TFoo::New( std::vector<TFoo>{TFoo::New(std::string("11")), TFoo::New(88), TFoo::New(std::vector<TFoo>{}), TFoo::New(2)}); EXPECT_EQ(GetIntAndWriteVector(variant, strm, std::vector<int>{}), 101); EXPECT_EQ(strm.str(), ""); } } /* Multiple families and ToString(int) and ToString(std::string) being shared. */ class BarFamily; using TBar = TVariant<BarFamily>; namespace Visitor { template <> struct TVariant<BarFamily>::Members { using All = Mpl::TTypeSet<int, std::string, std::list<TBar>>; }; // TVariant<BarFamily>::Members } // Visitor template <typename TMember> using IsFooBar = Mpl::Contains<Mpl::TGetUnion<TFoo::Members::All, TBar::Members::All>, c14::decay_t<TMember>>; // to_string.h struct TToString { std::string operator()(int that) const; std::string operator()(const std::string &that) const; std::string operator()(const std::vector<TFoo> &that) const; std::string operator()(const std::list<TBar> &that) const; }; // TToString template <typename TMember> requires<IsFooBar<TMember>::value, std::string> ToString(TMember &&member) { return TToString()(std::forward<TMember>(member)); } std::string ToString(const TFoo &that); std::string ToString(const TBar &that); // to_string.cc std::string TToString::operator()(int that) const { std::ostringstream strm; strm << that; return strm.str(); } std::string TToString::operator()(const std::string &that) const { assert(&that); return "'" + that + "'"; } std::string TToString::operator()(const std::vector<TFoo> &that) const { assert(&that); std::ostringstream strm; strm << '['; bool sep = false; for (const auto &variant : that) { sep ? strm << ", " : sep = true; strm << ToString(variant); } strm << ']'; return strm.str(); } std::string TToString::operator()(const std::list<TBar> &that) const { assert(&that); std::ostringstream strm; strm << '['; bool sep = false; for (const auto &variant : that) { sep ? strm << ", " : sep = true; strm << ToString(variant); } strm << ']'; return strm.str(); } std::string ToString(const TFoo &that) { return Single::Accept<TFoo::TApplier<TToString>>(that); } std::string ToString(const TBar &that) { return Single::Accept<TBar::TApplier<TToString>>(that); } FIXTURE(MultipleFamilies) { TFoo x; EXPECT_FALSE(x); x = TFoo::New(42); EXPECT_EQ(ToString(x), "42"); TBar bar = TBar::New(std::list<TBar>{TBar::New(4), TBar::New(std::string("World"))}); EXPECT_EQ(ToString(bar), "[4, 'World']"); } FIXTURE(ChangingType) { TFoo variant = TFoo::New(101); EXPECT_EQ(ToString(variant), "101"); variant = TFoo::New(std::string("mofo")); EXPECT_EQ(ToString(variant), "'mofo'"); } FIXTURE(Move) { TFoo a = TFoo::New(101); TFoo b; b = std::move(a); EXPECT_FALSE(a); EXPECT_EQ(ToString(b), "101"); } FIXTURE(Copy) { TFoo a = TFoo::New(101); TFoo b; b = a; EXPECT_EQ(ToString(a), "101"); EXPECT_EQ(ToString(b), "101"); } /* Disabled for now. Refer to <visitor/variant.h> for details. */ #if 0 FIXTURE(Share) { struct TGetAddress { const void *operator()(int) const { return nullptr; } const void *operator()(const std::string &that) const { return &that; } const void *operator()(const std::vector<TFoo> &that) const { return &that; } }; // TGetAddress struct TShare { TFoo operator()(int that) const { return TFoo::New(that); } TFoo operator()(const std::string &that) const { return TFoo::Share(that); } TFoo operator()(const std::vector<TFoo> &that) const { return TFoo::Share(that); } }; // TShare TFoo lhs = TFoo::New(std::string("hello")); auto *lhs_addr = Single::Accept<TFoo::TApplier<TGetAddress>>(lhs); TFoo rhs = Single::Accept<TFoo::TApplier<TShare>>(lhs); auto *rhs_addr = Single::Accept<TFoo::TApplier<TGetAddress>>(rhs); EXPECT_EQ(lhs_addr, rhs_addr); } #endif // set_default.h struct TSetDefault { void operator()(int &that) const; void operator()(std::string &that) const; void operator()(std::vector<TFoo> &that) const; }; // TSetDefault template <typename TMember> requires<IsFoo<TMember>::value, void> SetDefault(TMember &&member) { TSetDefault()(std::forward<TMember>(member)); } void SetDefault(TFoo &that); // set_default.cc void TSetDefault::operator()(int &that) const { assert(&that); that = 0; } void TSetDefault::operator()(std::string &that) const { assert(&that); that.clear(); } void TSetDefault::operator()(std::vector<TFoo> &that) const { assert(&that); for (auto &variant : that) { SetDefault(variant); } } void SetDefault(TFoo &that) { return Single::Accept<TFoo::TMutatingApplier<TSetDefault>>(that); } FIXTURE(Mutation) { /* int */ { TFoo variant = TFoo::New(101); SetDefault(variant); EXPECT_EQ(ToString(variant), "0"); } /* std::string */ { TFoo variant = TFoo::New(std::string("Foo")); SetDefault(variant); EXPECT_EQ(ToString(variant), "''"); } /* std::vector<TFoo> */ { TFoo variant = TFoo::New( std::vector<TFoo>{TFoo::New(std::string("11")), TFoo::New(88), TFoo::New(std::vector<TFoo>{}), TFoo::New(2)}); SetDefault(variant); EXPECT_EQ(ToString(variant), "['', 0, [], 0]"); } } // set_default_template.h struct TSetDefaultTemplate { using Signature = void (); template <typename TMember> void operator()(TMember &that) const { assert(&that); that = TMember{}; } }; // TSetDefaultTemplate template <typename TMember> requires<IsFoo<TMember>::value, void> SetDefaultTemplate(TMember &&member) { TSetDefaultTemplate()(std::forward<TMember>(member)); } void SetDefaultTemplate(TFoo &that); void SetDefaultTemplate(TFoo &that) { return Single::Accept<TFoo::TMutatingApplier<TSetDefaultTemplate>>(that); } // set_default_template.test.cc FIXTURE(SetDefaultTemplate) { /* int */ { TFoo variant = TFoo::New(101); SetDefaultTemplate(variant); EXPECT_EQ(ToString(variant), "0"); } /* std::string */ { TFoo variant = TFoo::New(std::string("Foo")); SetDefaultTemplate(variant); EXPECT_EQ(ToString(variant), "''"); } /* std::vector<TFoo> */ { TFoo variant = TFoo::New( std::vector<TFoo>{TFoo::New(std::string("11")), TFoo::New(88), TFoo::New(std::vector<TFoo>{}), TFoo::New(2)}); SetDefaultTemplate(variant); EXPECT_EQ(ToString(variant), "[]"); } } // write_name_double.h struct TWriteNameDouble { void operator()(int, int, std::ostream &) const; void operator()(int, const std::string &, std::ostream &) const; void operator()(int, const std::list<TBar> &, std::ostream &) const; void operator()(int, const std::vector<TFoo> &, std::ostream &) const; void operator()(const std::string &, int, std::ostream &) const; void operator()(const std::string &, const std::string &, std::ostream &) const; void operator()(const std::string &, const std::list<TBar> &, std::ostream &) const; void operator()(const std::string &, const std::vector<TFoo> &, std::ostream &) const; void operator()(const std::vector<TFoo> &, int, std::ostream &) const; void operator()(const std::vector<TFoo> &, const std::string &, std::ostream &) const; void operator()(const std::vector<TFoo> &, const std::list<TBar> &, std::ostream &) const; void operator()(const std::vector<TFoo> &, const std::vector<TFoo> &, std::ostream &) const; void operator()(const std::list<TBar> &, int, std::ostream &) const; void operator()(const std::list<TBar> &, const std::string &, std::ostream &) const; void operator()(const std::list<TBar> &, const std::vector<TFoo> &, std::ostream &) const; void operator()(const std::list<TBar> &, const std::list<TBar> &, std::ostream &) const; }; // TWriteNameDouble template <typename TLhs, typename TRhs> requires<IsFooBar<TLhs>::value && IsFooBar<TRhs>::value, void> WriteNameDouble(TLhs &&lhs, TRhs &&rhs, std::ostream &strm) { TWriteNameDouble()(std::forward<TLhs>(lhs), std::forward<TRhs>(rhs), strm); } void WriteNameDouble(const TFoo &, const TFoo &, std::ostream &); void WriteNameDouble(const TFoo &, const TBar &, std::ostream &); void WriteNameDouble(const TBar &, const TFoo &, std::ostream &); void WriteNameDouble(const TBar &, const TBar &, std::ostream &); // write_name_double.cc void TWriteNameDouble::operator()(int, int, std::ostream &strm) const { strm << "(int, int)"; } void TWriteNameDouble::operator()(int, const std::string &, std::ostream &strm) const { strm << "(int, const std::string &)"; } void TWriteNameDouble::operator()(int, const std::list<TBar> &, std::ostream &strm) const { strm << "(int, const std::list<TBar> &)"; } void TWriteNameDouble::operator()(int, const std::vector<TFoo> &, std::ostream &strm) const { strm << "(int, const std::vector<TFoo> &)"; } void TWriteNameDouble::operator()(const std::string &, int, std::ostream &strm) const { strm << "(const std::string &, int)"; } void TWriteNameDouble::operator()(const std::string &, const std::string &, std::ostream &strm) const { strm << "(const std::string &, const std::string &)"; } void TWriteNameDouble::operator()(const std::string &, const std::list<TBar> &, std::ostream &strm) const { strm << "(const std::string &, const std::list<TBar> &)"; } void TWriteNameDouble::operator()(const std::string &, const std::vector<TFoo> &, std::ostream &strm) const { strm << "(const std::string &, const std::vector<TFoo> &)"; } void TWriteNameDouble::operator()(const std::vector<TFoo> &, int, std::ostream &strm) const { strm << "(const std::vector<TFoo> &, int)"; } void TWriteNameDouble::operator()(const std::vector<TFoo> &, const std::string &, std::ostream &strm) const { strm << "(const std::vector<TFoo> &, const std::string &)"; } void TWriteNameDouble::operator()(const std::vector<TFoo> &, const std::list<TBar> &, std::ostream &strm) const { strm << "(const std::vector<TFoo> &, const std::list<TBar> &)"; } void TWriteNameDouble::operator()(const std::vector<TFoo> &, const std::vector<TFoo> &, std::ostream &strm) const { strm << "(const std::vector<TFoo> &, const std::vector<TFoo> &)"; } void TWriteNameDouble::operator()(const std::list<TBar> &, int, std::ostream &strm) const { strm << "(const std::list<TBar> &, int)"; } void TWriteNameDouble::operator()(const std::list<TBar> &, const std::string &, std::ostream &strm) const { strm << "(const std::list<TBar> &, const std::string &)"; } void TWriteNameDouble::operator()(const std::list<TBar> &, const std::vector<TFoo> &, std::ostream &strm) const { strm << "(const std::list<TBar> &, const std::vector<TFoo> &)"; } void TWriteNameDouble::operator()(const std::list<TBar> &, const std::list<TBar> &, std::ostream &strm) const { strm << "(const std::list<TBar> &, const std::list<TBar> &)"; } void WriteNameDouble(const TFoo &lhs, const TFoo &rhs, std::ostream &strm) { return Double::Accept<TFoo::TDoubleApplier<TWriteNameDouble>>(lhs, rhs, strm); } void WriteNameDouble(const TFoo &lhs, const TBar &rhs, std::ostream &strm) { using applier_t = TFoo::TDoubleApplier<TWriteNameDouble, TBar::TVisitor>; return Double::Accept<applier_t>(lhs, rhs, strm); } void WriteNameDouble(const TBar &lhs, const TFoo &rhs, std::ostream &strm) { using applier_t = TBar::TDoubleApplier<TWriteNameDouble, TFoo::TVisitor>; return Double::Accept<applier_t>(lhs, rhs, strm); } void WriteNameDouble(const TBar &lhs, const TBar &rhs, std::ostream &strm) { return Double::Accept<TBar::TDoubleApplier<TWriteNameDouble>>(lhs, rhs, strm); } // write_name_double.test.cc FIXTURE(FooFoo) { std::ostringstream strm; TFoo lhs = TFoo::New(std::string("yo")); TFoo rhs = TFoo::New( std::vector<TFoo>{TFoo::New(101), TFoo::New(std::string("heh")), TFoo::New(202), TFoo::New(std::vector<TFoo>{})}); WriteNameDouble(lhs, rhs, strm); EXPECT_EQ(strm.str(), "(const std::string &, const std::vector<TFoo> &)"); } FIXTURE(FooBar) { std::ostringstream strm; TFoo lhs = TFoo::New(101); TBar rhs = TBar::New(std::string("hello")); WriteNameDouble(lhs, rhs, strm); EXPECT_EQ(strm.str(), "(int, const std::string &)"); } FIXTURE(BarFoo) { std::ostringstream strm; TBar lhs = TBar::New( std::list<TBar>{TBar::New(std::string("list")), TBar::New(505)}); TFoo rhs = TFoo::New(std::vector<TFoo>{TFoo::New(101), TFoo::New(202), TFoo::New(std::string("heh"))}); WriteNameDouble(lhs, rhs, strm); EXPECT_EQ(strm.str(), "(const std::list<TBar> &, const std::vector<TFoo> &)"); } FIXTURE(BarBar) { std::ostringstream strm; TBar lhs = TBar::New( std::list<TBar>{TBar::New(std::string("list")), TBar::New(505)}); TBar rhs = TBar::New(101); WriteNameDouble(lhs, rhs, strm); EXPECT_EQ(strm.str(), "(const std::list<TBar> &, int)"); } // Reference counting tests. class TObj { public: static std::atomic_int_fast32_t ConstructCount; static std::atomic_int_fast32_t MoveCount; static std::atomic_int_fast32_t CopyCount; static std::atomic_int_fast32_t DestroyCount; static void Reset() { TObj::ConstructCount = 0; TObj::MoveCount = 0; TObj::CopyCount = 0; TObj::DestroyCount = 0; } TObj() { ++ConstructCount; } TObj(TObj &&) { ++MoveCount; } TObj(const TObj &) { ++CopyCount; } ~TObj() { ++DestroyCount; } }; // TObj std::atomic_int_fast32_t TObj::ConstructCount(0); std::atomic_int_fast32_t TObj::MoveCount(0); std::atomic_int_fast32_t TObj::CopyCount(0); std::atomic_int_fast32_t TObj::DestroyCount(0); class TrackerFamily; using TTracker = TVariant<TrackerFamily>; namespace Visitor { template <> struct TVariant<TrackerFamily>::Members { using All = Mpl::TTypeSet<TObj>; }; // TVariant<TrackerFamily>::Members } // Visitor FIXTURE(SingleThreadedNoCopy) { TObj::Reset(); /* scope */ { // Assign tracker with an instance of TObj. TTracker tracker = TTracker::New(TObj{}); // tracker is non-empty, ie. is valid. EXPECT_TRUE(tracker); // Ref-count up with an instance of tracker_copy which "copies" tracker. TTracker tracker_copy = tracker; EXPECT_TRUE(tracker); // Release tracker. tracker.Reset(); // tracker isn't valid, but the reference is still held by y. EXPECT_FALSE(tracker); EXPECT_TRUE(tracker_copy); tracker_copy.Reset(); EXPECT_FALSE(tracker); EXPECT_FALSE(tracker_copy); } // scope EXPECT_EQ(TObj::ConstructCount, 1); // TObj constructs once. EXPECT_EQ(TObj::MoveCount, 1); // TObj moves into TState EXPECT_EQ(TObj::CopyCount, 0); // TObj does not get copied. EXPECT_EQ(TObj::DestroyCount, TObj::ConstructCount + TObj::MoveCount + TObj::CopyCount); } // mutate.h struct TMutate { void operator()(TObj &) const; }; // TMutate template <typename TMember> requires<IsFoo<TMember>::value, void> Mutate(TMember &&member) { TMutate()(std::forward<TMember>(member)); } void Mutate(TTracker &that); // mutate.cc void TMutate::operator()(TObj &) const {} void Mutate(TTracker &that) { return Single::Accept<TTracker::TMutatingApplier<TMutate>>(that); } FIXTURE(SingleThreadedCopy) { TObj::Reset(); /* scope */ { // Assign tracker with an instance of TObj. TTracker tracker = TTracker::New(TObj{}); // tracker is non-empty, ie. is valid. EXPECT_TRUE(tracker); // Mutate tracker, there should be no copy since tracker is the only holder. Mutate(tracker); TTracker tracker_copy = tracker; // Now there are multiple holders of the TObj instance. // Mutating tracker should produce one copy. Mutate(tracker); } // scope EXPECT_EQ(TObj::ConstructCount, 1); // TObj constructs once. EXPECT_EQ(TObj::MoveCount, 1); // TObj moves into TState EXPECT_EQ(TObj::CopyCount, 1); // TObj gets copied once. EXPECT_EQ(TObj::DestroyCount, TObj::ConstructCount + TObj::MoveCount + TObj::CopyCount); } FIXTURE(MultiThreadedNoCopy) { TObj::Reset(); /* scope */ { std::mutex mutex; std::condition_variable cv; int ready = 0; const int num_threads = 50; TTracker tracker = TTracker::New(TObj{}); EXPECT_TRUE(tracker); /* The job of each thread is to copy the tracker in, then signal ready. Once the threads have signalled, the threads can keep copying the object within a loop, and none of these should be creating copies. */ auto job = [&cv, &mutex, &ready, &tracker ]()->void { TTracker tracker_copy = tracker; /* scope */ { std::lock_guard<std::mutex> lock(mutex); ++ready; } // scope cv.notify_one(); for (int i = 0; i < 1000; ++i) { EXPECT_TRUE(tracker_copy); TTracker copy = tracker_copy; EXPECT_TRUE(copy); } // for }; // Launch num_threads threads with jobs. std::vector<std::future<void>> futures(num_threads); for (auto &future : futures) { future = std::async(std::launch::async, job); } // for /* scope */ { std::unique_lock<std::mutex> lock(mutex); cv.wait(lock, [&ready, &num_threads]() { return ready == num_threads; }); } // Release the original tracker since it's all been copied to the threads. tracker.Reset(); for (const auto &future : futures) { future.wait(); } // for } // scope EXPECT_EQ(TObj::ConstructCount, 1); // TObj constructs once. EXPECT_EQ(TObj::MoveCount, 1); // TObj moves into TState EXPECT_EQ(TObj::CopyCount, 0); // TObj does not get copied. EXPECT_EQ(TObj::DestroyCount, TObj::ConstructCount + TObj::MoveCount + TObj::CopyCount); } FIXTURE(MultiThreadedCopy) { TObj::Reset(); /* scope */ { std::mutex mutex; std::condition_variable cv; int ready = 0; const int num_threads = 50; TTracker tracker = TTracker::New(TObj{}); EXPECT_TRUE(tracker); /* The job of each thread is to copy the tracker in, then signal ready. Once the threads have signalled, the threads can keep copying the object within a loop, and none of these should be creating copies. */ auto job = [&cv, &mutex, &ready, &tracker]() -> void { for (int i = 0; i < 100; ++i) { TTracker tracker_copy = tracker; Mutate(tracker_copy); } // for }; // Launch num_threads threads with jobs. std::vector<std::future<void>> futures(num_threads); for (auto &future : futures) { future = std::async(std::launch::async, job); } // for for (const auto &future : futures) { future.wait(); } // for } // scope EXPECT_EQ(TObj::ConstructCount, 1); // TObj constructs once. EXPECT_EQ(TObj::MoveCount, 1); // TObj moves into TState EXPECT_EQ(TObj::CopyCount, 5000); // TObj does not get copied. EXPECT_EQ(TObj::DestroyCount, TObj::ConstructCount + TObj::MoveCount + TObj::CopyCount); } FIXTURE(AcrossFamilyCopy) { /* Success. */ { TFoo foo = TFoo::New(42); TBar bar(foo); EXPECT_EQ(ToString(foo), "42"); EXPECT_EQ(ToString(bar), "42"); } /* Failure. */ { EXPECT_THROW(std::bad_cast, []() { TFoo foo = TFoo::New(std::vector<TFoo>{TFoo::New(23)}); TBar bar(foo); }); } } FIXTURE(AcrossFamilyMove) { /* Success. */ { TFoo foo = TFoo::New(42); TBar bar(std::move(foo)); EXPECT_FALSE(foo); EXPECT_EQ(ToString(bar), "42"); } /* Failure. */ { EXPECT_THROW(std::bad_cast, []() { TFoo foo = TFoo::New(std::vector<TFoo>{TFoo::New(23)}); TBar bar(std::move(foo)); }); } }
29.574951
81
0.600954
jssmith
8015799e7c2ea7a9160385aaf2808ed69370238e
1,708
cpp
C++
jni/application/Crosshair.cpp
clarkdonald/eecs494explore3d
fd4086d2c5482a289d51ef71c5f1ae20347db80a
[ "BSD-2-Clause" ]
null
null
null
jni/application/Crosshair.cpp
clarkdonald/eecs494explore3d
fd4086d2c5482a289d51ef71c5f1ae20347db80a
[ "BSD-2-Clause" ]
null
null
null
jni/application/Crosshair.cpp
clarkdonald/eecs494explore3d
fd4086d2c5482a289d51ef71c5f1ae20347db80a
[ "BSD-2-Clause" ]
null
null
null
// // Crosshair.cpp // game // // Created by Donald Clark on 10/27/13. // // #include "Crosshair.h" #include "Utility.h" #include "Player.h" #include <zenilib.h> using namespace Zeni; Crosshair::Crosshair() : radius(25.0f) {} Crosshair::~Crosshair() {} void Crosshair::render(const bool &is_wielding_weapon, Player* player) { String texture = is_wielding_weapon ? "weapon_crosshair" : "normal_crosshair"; float center_x = VIDEO_DIMENSION.second.x/2; float center_y = VIDEO_DIMENSION.second.y/2; render_image(texture, Point2f(center_x-radius, center_y-radius), Point2f(center_x+radius, center_y+radius)); //render the hearts float x_val = 0.0f; int k; for(k = 0; k < player->get_health(); k++){ render_image("filled_heart", Point2f(x_val, 0.0f), Point2f(x_val + 32.0f, 32.0f)); x_val += 32.0f; } while(k < 5){ render_image("empty_heart", Point2f(x_val, 0.0f), Point2f(x_val + 32.0f, 32.0f)); x_val += 32; k++; } x_val = 0; if(player -> can_lift()){ render_image("yellow_pill", Point2f(x_val, 32.0f), Point2f(x_val + 32.0f, 64.0f)); x_val += 32; } if(player -> can_walk_through_fire()){ render_image("blue_pill", Point2f(x_val, 32.0f), Point2f(x_val + 32.0f, 64.0f)); x_val += 32; } if(player -> can_walk_through_terrain()){ render_image("white_pill", Point2f(x_val, 32.0f), Point2f(x_val + 32.0f, 64.0f)); x_val += 32; } if(player -> can_jump()){ render_image("green_pill", Point2f(x_val, 32.0f), Point2f(x_val + 32.0f, 64.0f)); x_val += 32; } if(player -> is_lifting_terrain()){ render_image("CRATE.PNG", Point2f(x_val, 32.0f), Point2f(x_val + 32.0f, 64.0f)); x_val += 32; } }
26.276923
86
0.641101
clarkdonald
801de1b0109f88522baa11fb2b6ff42cfc9b85f6
1,597
cpp
C++
src/distance_widget.cpp
michaelscales88/Qt-GuiApp
b66d017b00b7a94d9a697fa5a70a600564c9a251
[ "MIT" ]
null
null
null
src/distance_widget.cpp
michaelscales88/Qt-GuiApp
b66d017b00b7a94d9a697fa5a70a600564c9a251
[ "MIT" ]
1
2018-06-26T21:39:39.000Z
2018-06-26T21:39:39.000Z
src/distance_widget.cpp
michaelscales88/Qt-GuiApp
b66d017b00b7a94d9a697fa5a70a600564c9a251
[ "MIT" ]
null
null
null
/* Graphical User Interface Assignment Interface3 (I3) * Developer: Michael Scales */ #include "distance_widget.h" DistanceWidget::DistanceWidget(QWidget *parent) : Base(parent) { // Configure view QLabel *viewLabel = new QLabel( tr("Select the maximum distance you are willing to travel:")); viewDisplay = new QLineEdit(this); QDial *viewDial = new QDial(this); viewDial->setMinimum(0); viewDial->setMaximum(10001); viewDisplay->setReadOnly(true); QHBoxLayout *displayLayout = new QHBoxLayout; displayLayout->addWidget(viewLabel); displayLayout->addWidget(viewDisplay); QVBoxLayout *layout = new QVBoxLayout; layout->addLayout(displayLayout); layout->addWidget(viewDial); setLayout(layout); // Configure the output area wigOutput = new QHBoxLayout; QLabel *outputLabel = new QLabel(tr("Maximum distance:")); outputDisplay = new QLineEdit; outputDisplay->setReadOnly(true); // Update the display with the selection from the combobox connect(viewDial, SIGNAL(valueChanged(int)), this, SLOT(updateDisplay(int))); viewDial->setValue(50); wigOutput->addWidget(outputLabel); wigOutput->addWidget(outputDisplay); } QHBoxLayout *DistanceWidget::getOutput() { return wigOutput; } void DistanceWidget::updateDisplay(int value) { QString text; if (value < 1) text = QString("< 1 mi"); else if (value > 10000) text = QString("> 10,0000 mi"); else text = QString("%1 mi").arg(value); viewDisplay->setText(text); outputDisplay->setText(text); }
30.132075
81
0.686913
michaelscales88
801ff9d16ae2b4b5dc73660bd69ff45251b5c18d
93
cpp
C++
keyword/extern/main.cpp
learnMachining/cplus2test
8cc0048627724bb967f27d5cd9860dbb5804a7d9
[ "Apache-2.0" ]
null
null
null
keyword/extern/main.cpp
learnMachining/cplus2test
8cc0048627724bb967f27d5cd9860dbb5804a7d9
[ "Apache-2.0" ]
null
null
null
keyword/extern/main.cpp
learnMachining/cplus2test
8cc0048627724bb967f27d5cd9860dbb5804a7d9
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; extern double PI; int main() { cout<<PI<<endl; }
10.333333
20
0.677419
learnMachining
80218a628bb37821b34b2d14050b4b3d67a7a68e
8,076
cpp
C++
Code/WolfEngine/Math/Matrix.cpp
Wolfos/WolfEngine
8034c2f5456c34b59be68f2855d4a6cab3b829f2
[ "Apache-2.0" ]
4
2015-01-09T00:11:54.000Z
2021-03-29T13:17:24.000Z
Code/WolfEngine/Math/Matrix.cpp
Wolfos/WolfEngine
8034c2f5456c34b59be68f2855d4a6cab3b829f2
[ "Apache-2.0" ]
2
2015-01-28T14:06:39.000Z
2017-08-02T06:54:34.000Z
Code/WolfEngine/Math/Matrix.cpp
Wolfos/WolfEngine
8034c2f5456c34b59be68f2855d4a6cab3b829f2
[ "Apache-2.0" ]
null
null
null
// // Created by Robin on 01/01/2018. // #include "Matrix.h" #include <cstring> #include "WolfMath.h" Matrix::Matrix() { SetIdentity(); } const float* Matrix::GetData() const { return data; } void Matrix::SetIdentity() { memset(data, 0, sizeof(float) * 16); data[0] = 1; data[5] = 1; data[10] = 1; data[15] = 1; } void Matrix::SetPerspective(float angle, float aspect, float clipMin, float clipMax) { float tangent = WolfMath::Tan(WolfMath::DegToRad(angle / 2)); memset(data, 0, sizeof(float) * 16); data[0] = 0.5f / tangent; data[5] = 0.5f * aspect / tangent; data[10] = -(clipMax + clipMin) / (clipMax - clipMin); data[11] = -1; data[14] = (-2 * clipMax * clipMin) / (clipMax - clipMin); } void Matrix::SetOrtho(float left, float right, float top, float bottom, float clipMin, float clipMax) { memset(data, 0, sizeof(float) * 16); data[0] = 2 / (right - left); data[5] = 2 / (bottom - top); data[10] = -2 / (clipMax - clipMin); data[15] = 1; } void Matrix::ViewInverse() { data[0] = -data[0]; data[1] = -data[1]; data[2] = -data[2]; data[4] = -data[4]; data[5] = -data[5]; data[6] = -data[6]; data[8] = -data[8]; data[9] = -data[9]; data[10] = -data[10]; data[12] = -data[12]; data[13] = -data[13]; data[14] = -data[14]; } void Matrix::Invert() { Matrix temp; float det; int i; temp.data[0] = data[5] * data[10] * data[15] - data[5] * data[11] * data[14] - data[9] * data[6] * data[15] + data[9] * data[7] * data[14] + data[13] * data[6] * data[11] - data[13] * data[7] * data[10]; temp.data[4] = -data[4] * data[10] * data[15] + data[4] * data[11] * data[14] + data[8] * data[6] * data[15] - data[8] * data[7] * data[14] - data[12] * data[6] * data[11] + data[12] * data[7] * data[10]; temp.data[8] = data[4] * data[9] * data[15] - data[4] * data[11] * data[13] - data[8] * data[5] * data[15] + data[8] * data[7] * data[13] + data[12] * data[5] * data[11] - data[12] * data[7] * data[9]; temp.data[12] = -data[4] * data[9] * data[14] + data[4] * data[10] * data[13] + data[8] * data[5] * data[14] - data[8] * data[6] * data[13] - data[12] * data[5] * data[10] + data[12] * data[6] * data[9]; temp.data[1] = -data[1] * data[10] * data[15] + data[1] * data[11] * data[14] + data[9] * data[2] * data[15] - data[9] * data[3] * data[14] - data[13] * data[2] * data[11] + data[13] * data[3] * data[10]; temp.data[5] = data[0] * data[10] * data[15] - data[0] * data[11] * data[14] - data[8] * data[2] * data[15] + data[8] * data[3] * data[14] + data[12] * data[2] * data[11] - data[12] * data[3] * data[10]; temp.data[9] = -data[0] * data[9] * data[15] + data[0] * data[11] * data[13] + data[8] * data[1] * data[15] - data[8] * data[3] * data[13] - data[12] * data[1] * data[11] + data[12] * data[3] * data[9]; temp.data[13] = data[0] * data[9] * data[14] - data[0] * data[10] * data[13] - data[8] * data[1] * data[14] + data[8] * data[2] * data[13] + data[12] * data[1] * data[10] - data[12] * data[2] * data[9]; temp.data[2] = data[1] * data[6] * data[15] - data[1] * data[7] * data[14] - data[5] * data[2] * data[15] + data[5] * data[3] * data[14] + data[13] * data[2] * data[7] - data[13] * data[3] * data[6]; temp.data[6] = -data[0] * data[6] * data[15] + data[0] * data[7] * data[14] + data[4] * data[2] * data[15] - data[4] * data[3] * data[14] - data[12] * data[2] * data[7] + data[12] * data[3] * data[6]; temp.data[10] = data[0] * data[5] * data[15] - data[0] * data[7] * data[13] - data[4] * data[1] * data[15] + data[4] * data[3] * data[13] + data[12] * data[1] * data[7] - data[12] * data[3] * data[5]; temp.data[14] = -data[0] * data[5] * data[14] + data[0] * data[6] * data[13] + data[4] * data[1] * data[14] - data[4] * data[2] * data[13] - data[12] * data[1] * data[6] + data[12] * data[2] * data[5]; temp.data[3] = -data[1] * data[6] * data[11] + data[1] * data[7] * data[10] + data[5] * data[2] * data[11] - data[5] * data[3] * data[10] - data[9] * data[2] * data[7] + data[9] * data[3] * data[6]; temp.data[7] = data[0] * data[6] * data[11] - data[0] * data[7] * data[10] - data[4] * data[2] * data[11] + data[4] * data[3] * data[10] + data[8] * data[2] * data[7] - data[8] * data[3] * data[6]; temp.data[11] = -data[0] * data[5] * data[11] + data[0] * data[7] * data[9] + data[4] * data[1] * data[11] - data[4] * data[3] * data[9] - data[8] * data[1] * data[7] + data[8] * data[3] * data[5]; temp.data[15] = data[0] * data[5] * data[10] - data[0] * data[6] * data[9] - data[4] * data[1] * data[10] + data[4] * data[2] * data[9] + data[8] * data[1] * data[6] - data[8] * data[2] * data[5]; det = data[0] * temp.data[0] + data[1] * temp.data[4] + data[2] * temp.data[8] + data[3] * temp.data[12]; if (det == 0) return; det = 1.0 / det; for (i = 0; i < 16; i++) data[i] = temp.data[i] * det; } void Matrix::Translate(Vector3<float> direction) { data[12] += direction.x; data[13] += direction.y; data[14] += direction.z; } void Matrix::Scale(Vector3<float> scale) { data[0] = scale.x; data[5] = scale.y; data[10] = scale.z; } Matrix Matrix::operator * (const Matrix& m) const { Matrix ret; ret.data[0] = ((data[0]*m.data[0])+(data[1]*m.data[4])+(data[2]*m.data[8])+(data[3]*m.data[12])); ret.data[1] = ((data[0]*m.data[1])+(data[1]*m.data[5])+(data[2]*m.data[9])+(data[3]*m.data[13])); ret.data[2] = ((data[0]*m.data[2])+(data[1]*m.data[6])+(data[2]*m.data[10])+(data[3]*m.data[14])); ret.data[3] = ((data[0]*m.data[3])+(data[1]*m.data[7])+(data[2]*m.data[11])+(data[3]*m.data[15])); ret.data[4] = ((data[4]*m.data[0])+(data[5]*m.data[4])+(data[6]*m.data[8])+(data[7]*m.data[12])); ret.data[5] = ((data[4]*m.data[1])+(data[5]*m.data[5])+(data[6]*m.data[9])+(data[7]*m.data[13])); ret.data[6] = ((data[4]*m.data[2])+(data[5]*m.data[6])+(data[6]*m.data[10])+(data[7]*m.data[14])); ret.data[7] = ((data[4]*m.data[3])+(data[5]*m.data[7])+(data[6]*m.data[11])+(data[7]*m.data[15])); ret.data[8] = ((data[8]*m.data[0])+(data[9]*m.data[4])+(data[10]*m.data[8])+(data[11]*m.data[12])); ret.data[9] = ((data[8]*m.data[1])+(data[9]*m.data[5])+(data[10]*m.data[9])+(data[11]*m.data[13])); ret.data[10] = ((data[8]*m.data[2])+(data[9]*m.data[6])+(data[10]*m.data[10])+(data[11]*m.data[14])); ret.data[11] = ((data[8]*m.data[3])+(data[9]*m.data[7])+(data[10]*m.data[11])+(data[11]*m.data[15])); ret.data[12] = ((data[12]*m.data[0])+(data[13]*m.data[4])+(data[14]*m.data[8])+(data[15]*m.data[12])); ret.data[13] = ((data[12]*m.data[1])+(data[13]*m.data[5])+(data[14]*m.data[9])+(data[15]*m.data[13])); ret.data[14] = ((data[12]*m.data[2])+(data[13]*m.data[6])+(data[14]*m.data[10])+(data[15]*m.data[14])); ret.data[15] = ((data[12]*m.data[3])+(data[13]*m.data[7])+(data[14]*m.data[11])+(data[15]*m.data[15])); return ret; } void Matrix::FromQuat(Quaternion *q, Vector3<float> pivot) { SetIdentity(); float sqw = q->w*q->w; float sqx = q->x*q->x; float sqy = q->y*q->y; float sqz = q->z*q->z; data[0] = sqx - sqy - sqz + sqw; // since sqw + sqx + sqy + sqz =1 data[5] = -sqx + sqy - sqz + sqw; data[10] = -sqx - sqy + sqz + sqw; float tmp1 = q->x*-q->y; float tmp2 = q->z*q->w; data[4] = 2 * (tmp1 + tmp2); data[1] = 2 * (tmp1 - tmp2); tmp1 = q->x*q->z; tmp2 = q->y*q->w; data[8] = 2 * (tmp1 - tmp2); data[2] = 2 * (tmp1 + tmp2); tmp1 = q->y*q->z; tmp2 = q->x*q->w; data[9] = 2 * (tmp1 + tmp2); data[6] = 2 * (tmp1 - tmp2); float a1 = pivot.x; float a2 = pivot.y; float a3 = pivot.z; data[12] = a1 - a1 * data[0] - a2 * data[4] - a3 * data[8]; data[13] = a2 - a1 * data[1] - a2 * data[5] - a3 * data[9]; data[14] = a3 - a1 * data[2] - a2 * data[6] - a3 * data[10]; data[3] = data[7] = data[11] = 0.0; data[15] = 1.0; }
29.911111
106
0.516097
Wolfos
8022ca8af65bfc936232603461e0c41b86a2e65b
1,336
cpp
C++
O2020_HUST/O2020CNTDIV.cpp
trannguyenhan01092000/WorkspaceAlgorithm
6ad3f12d55c7675184a8c15c5388ee8422e15a16
[ "MIT" ]
8
2020-11-26T03:36:49.000Z
2020-11-28T14:33:07.000Z
O2020_HUST/O2020CNTDIV.cpp
trannguyenhan/WorkspaceAlgorithm
6ad3f12d55c7675184a8c15c5388ee8422e15a16
[ "MIT" ]
null
null
null
O2020_HUST/O2020CNTDIV.cpp
trannguyenhan/WorkspaceAlgorithm
6ad3f12d55c7675184a8c15c5388ee8422e15a16
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; const int MAX = 1000005; int snt[MAX]; int phantich[MAX]; // Sang so nguyen to void sieve(int N) { bool isPrime[N+1]; for(int i = 0; i <= N;++i) { isPrime[i] = true; } isPrime[0] = false; isPrime[1] = false; int cnt = 0; for(int i = 2; i * i <= N; ++i) { if(isPrime[i] == true) { // Mark all the multiples of i as composite numbers snt[cnt] = i; cnt++; for(int j = i * i; j <= N; j += i) isPrime[j] = false; } } } // Phan tich N ra thanh tich cac thua so nguyen to void phanTichSNT(int N){ int i = 0; int cnt = 0; while(N > 0){ if(snt[i] != 0) if(N % snt[i] == 0){ N = N / snt[i]; phantich[snt[i]]++; } else { i++; } else break; } } int solve(int N){ phanTichSNT(N); phanTichSNT(N+1); phanTichSNT(N+2); int sum = 1; for(int i=0; i<N; i++) if(phantich[snt[i]] != 0) sum = sum*(phantich[snt[i]]*2-phantich[snt[i]]); return sum; } int main(){ int Q; cin >> Q; sieve(MAX); while(Q>0){ int N; cin >> N; cout << solve(N) << endl; Q--; } return 0; }
19.647059
64
0.431886
trannguyenhan01092000
8022e8f3acdb43eec1bf00a7fdde581e3651bf66
3,544
cpp
C++
tests/nameof.cpp
RodrigoHolztrattner/ctti
b4d5dc59a412c1dc28dd4480df28cb20e7fffcb1
[ "MIT" ]
471
2015-08-05T04:20:11.000Z
2022-03-17T10:10:28.000Z
tests/nameof.cpp
RodrigoHolztrattner/ctti
b4d5dc59a412c1dc28dd4480df28cb20e7fffcb1
[ "MIT" ]
31
2015-08-05T18:35:17.000Z
2021-07-09T13:13:39.000Z
tests/nameof.cpp
RodrigoHolztrattner/ctti
b4d5dc59a412c1dc28dd4480df28cb20e7fffcb1
[ "MIT" ]
51
2015-08-05T13:43:46.000Z
2021-11-30T13:09:25.000Z
#include <ctti/nameof.hpp> #include "catch.hpp" using namespace ctti; namespace foo { struct Foo {}; namespace bar { struct Bar {}; } inline namespace inline_quux { struct Quux {}; } } namespace bar { struct Bar {}; constexpr ctti::detail::cstring ctti_nameof(ctti::type_tag<Bar>) { return "Bar"; // without namespace } enum class Enum { A, B, C }; constexpr ctti::detail::cstring ctti_nameof(CTTI_STATIC_VALUE(Enum::C)) { return "Enum::Si"; } } class MyClass { public: class InnerClass {}; }; struct MyStruct { struct InnerStruct {}; }; enum ClassicEnum { A, B, C }; enum class EnumClass { A, B, C }; TEST_CASE("nameof") { SECTION("basic types") { REQUIRE(nameof<int>() == "int"); REQUIRE(nameof<bool>() == "bool"); REQUIRE(nameof<char>() == "char"); REQUIRE(nameof<void>() == "void"); } SECTION("class types") { REQUIRE(nameof<MyClass>() == "MyClass"); REQUIRE(nameof<MyClass::InnerClass>() == "MyClass::InnerClass"); } SECTION("struct types") { REQUIRE(nameof<MyStruct>() == "MyStruct"); REQUIRE(nameof<MyStruct::InnerStruct>() == "MyStruct::InnerStruct"); } SECTION("enum types") { REQUIRE(nameof<ClassicEnum>() == "ClassicEnum"); REQUIRE(nameof<EnumClass>() == "EnumClass"); } SECTION("with namespaces") { REQUIRE(nameof<foo::Foo>() == "foo::Foo"); REQUIRE(nameof<foo::bar::Bar>() == "foo::bar::Bar"); SECTION("inline namespaces") { REQUIRE(nameof<foo::inline_quux::Quux>() == "foo::inline_quux::Quux"); REQUIRE(nameof<foo::Quux>() == "foo::inline_quux::Quux"); } SECTION("std") { REQUIRE(nameof<std::string>() == "std::string"); } } SECTION("with custom ctti_nameof()") { SECTION("intrusive customize") { struct Foo { static constexpr const char* ctti_nameof() { return "Foobar"; } }; REQUIRE(nameof<Foo>() == "Foobar"); } SECTION("non-intrusive customize") { REQUIRE(nameof<bar::Bar>() == "Bar"); REQUIRE(nameof<CTTI_STATIC_VALUE(bar::Enum::C)>() == "Enum::Si"); } } #ifdef CTTI_HAS_VARIABLE_TEMPLATES SECTION("variable templates") { REQUIRE(ctti::nameof_v<int> == nameof<int>()); REQUIRE(ctti::nameof_value_v<int, 42> == nameof<int, 42>()); } #endif // CTTI_HAS_VARIABLE_TEMPLATES } TEST_CASE("nameof.enums", "[!mayfail]") { #ifdef CTTI_HAS_ENUM_AWARE_PRETTY_FUNCTION SECTION("enum values") { REQUIRE(nameof<CTTI_STATIC_VALUE(ClassicEnum::A)>() == "ClassicEnum::A"); REQUIRE(nameof<CTTI_STATIC_VALUE(EnumClass::A)>() == "EnumClass::A"); REQUIRE(nameof<CTTI_STATIC_VALUE(ClassicEnum::A)>() == "ClassicEnum::A"); } #else SECTION("enum values") { WARN("Thie section may fail in GCC due to 'u' suffix in integer literals. " "It seems that some GCC versions use unsigned int as default enum underlying type"); REQUIRE(nameof<CTTI_STATIC_VALUE(ClassicEnum::A)>() == "(ClassicEnum)0"); REQUIRE(nameof<CTTI_STATIC_VALUE(EnumClass::A)>() == "(EnumClass)0"); REQUIRE(nameof<CTTI_STATIC_VALUE(ClassicEnum::A)>() == "(ClassicEnum)0"); } #endif }
23.012987
96
0.55474
RodrigoHolztrattner
802480bde22ab44c61985d44dcefd7c1721ff411
2,794
cc
C++
services/network/private_network_access_check.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
services/network/private_network_access_check.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
services/network/private_network_access_check.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/network/private_network_access_check.h" #include "base/metrics/histogram_functions.h" #include "services/network/public/cpp/ip_address_space_util.h" #include "services/network/public/mojom/client_security_state.mojom.h" #include "services/network/public/mojom/ip_address_space.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" namespace network { namespace { using Policy = mojom::PrivateNetworkRequestPolicy; using Result = PrivateNetworkAccessCheckResult; Result PrivateNetworkAccessCheckInternal( const mojom::ClientSecurityState* client_security_state, mojom::IPAddressSpace target_address_space, int32_t url_load_options, mojom::IPAddressSpace resource_address_space) { if (url_load_options & mojom::kURLLoadOptionBlockLocalRequest && IsLessPublicAddressSpace(resource_address_space, mojom::IPAddressSpace::kPublic)) { return Result::kBlockedByLoadOption; } if (target_address_space != mojom::IPAddressSpace::kUnknown) { return resource_address_space == target_address_space ? Result::kAllowedByTargetIpAddressSpace : Result::kBlockedByTargetIpAddressSpace; } if (!client_security_state) { return Result::kAllowedMissingClientSecurityState; } if (!IsLessPublicAddressSpace(resource_address_space, client_security_state->ip_address_space)) { return Result::kAllowedNoLessPublic; } // We use a switch statement to force this code to be amended when values are // added to the `PrivateNetworkRequestPolicy` enum. switch (client_security_state->private_network_request_policy) { case Policy::kAllow: return Result::kAllowedByPolicyAllow; case Policy::kWarn: return Result::kAllowedByPolicyWarn; case Policy::kBlock: return Result::kBlockedByPolicyBlock; case Policy::kPreflightWarn: return Result::kBlockedByPolicyPreflightWarn; case Policy::kPreflightBlock: return Result::kBlockedByPolicyPreflightBlock; } } } // namespace Result PrivateNetworkAccessCheck( const mojom::ClientSecurityState* client_security_state, mojom::IPAddressSpace target_address_space, int32_t url_load_options, mojom::IPAddressSpace resource_address_space) { Result result = PrivateNetworkAccessCheckInternal( client_security_state, target_address_space, url_load_options, resource_address_space); base::UmaHistogramEnumeration("Security.PrivateNetworkAccess.CheckResult", result); return result; } } // namespace network
36.285714
79
0.753758
zealoussnow
8025bc84a4d49f5ee822183d4792b22f6a4ecdda
4,313
cpp
C++
gui/text/alter/ignoretab.cpp
fourier/frostbite
47b00c5b93a949300e5b387e38d6ab77afc799d9
[ "MIT" ]
27
2016-03-25T19:15:34.000Z
2021-10-17T14:39:00.000Z
gui/text/alter/ignoretab.cpp
fourier/frostbite
47b00c5b93a949300e5b387e38d6ab77afc799d9
[ "MIT" ]
109
2016-09-02T08:13:58.000Z
2022-03-28T05:45:51.000Z
gui/text/alter/ignoretab.cpp
fourier/frostbite
47b00c5b93a949300e5b387e38d6ab77afc799d9
[ "MIT" ]
20
2016-06-30T15:29:25.000Z
2021-04-05T16:47:17.000Z
#include "ignoretab.h" #include "text/alter/alterdialog.h" #include "text/alter/altersettingsentry.h" #include "text/alter/ignoresettings.h" #include "globaldefines.h" #include <QHeaderView> IgnoreTab::IgnoreTab(QObject *parent) : QObject(parent), AbstractTableTab() { alterDialog = (AlterDialog*)parent; ignoreTable = alterDialog->getIgnoreTable(); addButton = alterDialog->getIgnoreAddButton(); removeButton = alterDialog->getIgnoreRemoveButton(); ignoreEnabled = alterDialog->getIgnoreEnabled(); settings = IgnoreSettings::getInstance(); QStringList labels; labels << "Regular expression"; ignoreTable->setColumnCount(labels.count()); ignoreTable->setHorizontalHeaderLabels(labels); ignoreTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ignoreTable->setSelectionBehavior(QAbstractItemView::SelectRows); ignoreTable->setSelectionMode(QAbstractItemView::SingleSelection); ignoreTable->setContextMenuPolicy(Qt::CustomContextMenu); ignoreEnabled->setChecked(settings->getEnabled()); connect(addButton, SIGNAL(clicked()), this, SLOT(addNewTableRow())); connect(removeButton, SIGNAL(clicked()), this, SLOT(removeTableRow())); connect(ignoreTable, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(displayMenu(QPoint))); connect(ignoreTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(updateEntry(QTableWidgetItem*))); connect(ignoreEnabled, SIGNAL(stateChanged(int)), this, SLOT(enabledChanged(int))); this->initIgnoreList(); } void IgnoreTab::print(QString text) { qDebug() << text; } void IgnoreTab::updateSettings() { settings = IgnoreSettings::getInstance(); this->initIgnoreList(); } void IgnoreTab::addNewTableRow() { AbstractTableTab::addNewTableRow(QStringList()); } void IgnoreTab::removeTableRow() { AbstractTableTab::removeTableRow(); } void IgnoreTab::enabledChanged(int state) { settings->setEnabled(state == Qt::Checked); alterDialog->reloadSettings(); } void IgnoreTab::updateEntry(QTableWidgetItem* item) { AbstractTableTab::updateEntry(item); } void IgnoreTab::displayMenu(QPoint pos) { AbstractTableTab::displayMenu(pos); } void IgnoreTab::initIgnoreList() { this->setSettingEntries(settings->getIgnores()); ignoreTable->blockSignals(true); ignoreTable->clearContents(); ignoreTable->setRowCount(this->getSettingEntries().size()); for(int i = 0; i < this->getSettingEntries().size(); i++) { AlterSettingsEntry entry = getSettingEntries().at(i); this->populateTableRow(i, entry); } ignoreTable->blockSignals(false); } void IgnoreTab::populateTableRow(int row, AlterSettingsEntry entry) { QTableWidgetItem* patternItem = new QTableWidgetItem(entry.pattern); patternItem->setData(Qt::UserRole, "pattern"); if(QRegularExpression(entry.pattern).isValid()) { patternItem->setBackgroundColor(QColor(Qt::transparent)); } else { patternItem->setBackgroundColor(QColor(REGEX_ERROR_COLOR_HEX)); } ignoreTable->setItem(row, 0, patternItem); } void IgnoreTab::saveChanges() { // rewrite all settings if any remove events if(this->hasAny(this->getChangeEvents(), TableChangeEvent::Remove)) { settings->setSettings(this->getSettingEntries()); } else { for(int id : this->getChangeEvents().keys()) { AlterSettingsEntry entry = this->getSettingEntries().at(id); QList<TableChangeEvent> changeEvents = this->getChangeEvents().value(id); if(changeEvents.contains(TableChangeEvent::Add)) { settings->addParameter(entry); } else if(changeEvents.contains(TableChangeEvent::Update)) { settings->setParameter(entry); } } } this->getChangeEvents().clear(); } void IgnoreTab::cancelChanges() { if(this->getChangeEvents().size() > 0) { this->initIgnoreList(); this->getChangeEvents().clear(); } } QTableWidget* IgnoreTab::getTable() { return alterDialog->getIgnoreTable(); } QPushButton* IgnoreTab::getApplyButton() { return alterDialog->getApplyButton(); } QList<QDockWidget*> IgnoreTab::getDockWindows() { return alterDialog->getDockWindows(); } IgnoreTab::~IgnoreTab() { }
30.807143
109
0.704846
fourier
8028d2add352db7f39ceccb7f5d3a8e9f0ead6d7
4,904
hpp
C++
samples/golf/src/icon.hpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
41
2017-08-29T12:14:36.000Z
2022-02-04T23:49:48.000Z
samples/golf/src/icon.hpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
11
2017-09-02T15:32:45.000Z
2021-12-27T13:34:56.000Z
samples/golf/src/icon.hpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
5
2020-01-25T17:51:45.000Z
2022-03-01T05:20:30.000Z
static const unsigned char icon[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xc8, 0xb8, 0x9f, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xff, 0xf8, 0xe1, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0xc8, 0xb8, 0x9f, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
272.444444
360
0.576468
fallahn
802af22302204a6bf086d0dffd01d52ed60258c0
3,300
cpp
C++
xyuv/src/config-parser/minicalc/operations.cpp
stian-svedenborg/xyuv
c725b4f926ef3c5311878b0b8b9c4dacbbf0db34
[ "MIT" ]
5
2015-08-13T18:46:45.000Z
2018-04-18T18:51:43.000Z
xyuv/src/config-parser/minicalc/operations.cpp
stian-svedenborg/xyuv
c725b4f926ef3c5311878b0b8b9c4dacbbf0db34
[ "MIT" ]
18
2015-08-19T13:25:30.000Z
2017-05-08T10:55:48.000Z
xyuv/src/config-parser/minicalc/operations.cpp
stian-svedenborg/xyuv
c725b4f926ef3c5311878b0b8b9c4dacbbf0db34
[ "MIT" ]
3
2016-07-21T12:18:06.000Z
2018-05-19T05:32:32.000Z
/* * The MIT License (MIT) * * Copyright (c) 2015 Stian Valentin Svedenborg * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdexcept> #include "operations.h" // Evaluator functions: int minicalc_add(int lhs, int rhs) { return lhs + rhs; } int minicalc_sub(int lhs, int rhs) { return lhs - rhs; } int minicalc_mul(int lhs, int rhs) { return lhs * rhs; } int minicalc_div(int lhs, int rhs) { if (rhs == 0) { throw std::runtime_error("Divide by 0"); } return lhs / rhs; } int minicalc_mod(int lhs, int rhs) { if (rhs == 0) { throw std::runtime_error("Divide by 0"); } return lhs % rhs; } int minicalc_pow(int base, int exponent) { int result = 1; while (exponent > 0) { result *= base; --exponent; } return result; } int minicalc_negate(int v) { return -v; } int minicalc_next_multiple(int base, int multiplier) { int quotient_ceil = (base + (multiplier-1)) / multiplier; return quotient_ceil*multiplier; } int minicalc_abs(int v) { return v < 0 ? -v : v; } int minicalc_gcd(int lhs, int rhs) { if (lhs <= 0 || rhs <=0 ) { throw std::runtime_error("gcd() must have positive, non-zero operands"); } if (lhs > rhs) { return minicalc_gcd(lhs-rhs, rhs); } else if (lhs < rhs) { return minicalc_gcd(lhs, rhs-lhs); } else { return lhs; } } int minicalc_lcm(int lhs, int rhs) { if (lhs <= 0 || rhs <=0 ) { throw std::runtime_error("lcm() must have positive, non-zero operands"); } return lhs * rhs / minicalc_gcd(lhs, rhs); } int minicalc_logic_eq(int lhs, int rhs) { return int(lhs == rhs); } int minicalc_logic_ne(int lhs, int rhs) { return int(lhs != rhs); } int minicalc_logic_lt(int lhs, int rhs) { return int(lhs < rhs); } int minicalc_logic_gt(int lhs, int rhs) { return int(lhs > rhs); } int minicalc_logic_le(int lhs, int rhs) { return int(lhs <= rhs); } int minicalc_logic_ge(int lhs, int rhs) { return int(lhs >= rhs); } int minicalc_logic_and(int lhs, int rhs){ return int(lhs && rhs); } int minicalc_logic_or(int lhs, int rhs) { return int(lhs || rhs); } int minicalc_logic_neg(int bool_expr) { return int(!bool_expr); }
25.984252
80
0.662727
stian-svedenborg
802c70a16d628df48df1a84173cbfbf23d88e632
24,188
cpp
C++
src/MorphologyTrainer/MorphologyTrainerMain.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/MorphologyTrainer/MorphologyTrainerMain.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/MorphologyTrainer/MorphologyTrainerMain.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright 2009 by BBN Technologies Corp. // All Rights Reserved. #include "Generic/common/leak_detection.h" #include "Generic/common/limits.h" #include "Generic/common/ParamReader.h" #include "Generic/common/UTF8InputStream.h" #include "Generic/common/Sexp.h" #include "Generic/theories/Lexicon.h" #include "Generic/common/FileSessionLogger.h" #include "Generic/common/UnrecoverableException.h" #include "Generic/morphAnalysis/MorphologicalAnalyzer.h" #include "Generic/morphAnalysis/SessionLexicon.h" #include "Generic/morphSelection/MorphModel.h" #include "Generic/morphSelection/MorphDecoder.h" #include "Generic/morphSelection/MorphSelector.h" #include "Generic/normalizer/MTNormalizer.h" #include "Generic/tokens/Tokenizer.h" #include "Generic/tokens/SymbolSubstitutionMap.h" #include "Generic/theories/TokenSequence.h" #include "Generic/theories/Token.h" #include "Generic/theories/LexicalTokenSequence.h" #include "Generic/theories/LexicalToken.h" #include "Generic/names/NameClassTags.h" #include "Generic/common/version.h" #include "Generic/common/FeatureModule.h" #include <boost/scoped_ptr.hpp> #define MAX_LINE_LENGTH 15000 wchar_t line[MAX_LINE_LENGTH]; void print_usage() { std::cout << "Training Usage: MorphologyTrainer -t PARAM_FILE TRAIN_FILE MULT (MODEL_PREFIX)" << std::endl; std::cout << "Decode Usage (Untokenized Input): MorphologyTrainer -d PARAM_FILE [<input-file> <output-file>]" << std::endl; std::cout << "Decode Usage (for name-training sexp input): MorphologyTrainer -dsexp PARAM_FILE [<input-file> <output-file>]" << std::endl; std::cout << "Decode Usage (Pre-Tokenized and Analyzed Input): MorphologyTrainer -a PARAM_FILE" << std::endl; std::cout << "Tokenizer Usage: MorphologyTrainer -tok PARAM_FILE" << std::endl; } bool readSentence(UTF8InputStream& uis, LocatedString* loc) { int len, start, end; len = 0; while (!uis.eof()) { uis.getLine(line, MAX_LINE_LENGTH); len = static_cast<int>(wcslen(line)); if (len == 0) continue; start = 0; end = len-1; while((start < len) && iswspace(line[start])) start++; while((end > 0) && iswspace(line[end])) end--; if (start != end) break; } if (len == 0) { loc = 0; return false; } if (line[start] != L'(') { throw UnexpectedInputException("MorphologyTrainerMain::readSentence()", "Test sentence doesn't start with '('"); } if (line[end] != L')') { throw UnexpectedInputException("MorphologyTrainerMain::readSentence()", "Test sentence doesn't end with ')'"); } start++; end++; LocatedString* temp = _new LocatedString(line); temp->trim(); start = temp->indexOf(L"("); end = temp->indexOf(L")"); loc = temp->substring(start+1, end); loc->replace(L"-LRB-",L"("); loc->replace(L"-RRB-",L")"); delete temp; return true; } bool readTokenizedAndAnalyzedSentence(UTF8InputStream& uis, TokenSequence** tokens, LocatedString &tokenString) { FeatureValueStructure *fvs = 0; Token **origTokens = _new Token*[MAX_SENTENCE_TOKENS]; Token **morphTokens = _new Token*[MAX_SENTENCE_TOKENS]; Sexp *sentence = _new Sexp(uis); int n_lex = 0; if (sentence->isVoid()) return false; if (sentence->getNumChildren() != 2) throw UnexpectedInputException("MorphologyTrainerMain::readTokenizedAndAnalyzedSentence()", "Encountered improper sexp format."); Sexp *tokenList = sentence->getFirstChild(); Sexp *morphList = sentence->getSecondChild(); tokenString = LocatedString(tokenList->to_token_string().c_str()); int n_tokens = tokenList->getNumChildren() < MAX_SENTENCE_TOKENS ? tokenList->getNumChildren() : MAX_SENTENCE_TOKENS; if (morphList->getNumChildren() != tokenList->getNumChildren()) throw UnexpectedInputException("MorphologyTrainerMain::readTokenizedAndAnalyzedSentence()", "Encountered improper sexp format."); int curr_char = 0; for (int i = 0; i < n_tokens; i++) { Sexp *analysisList = morphList->getNthChild(i); int n_analyses = analysisList->getNumChildren(); LexicalEntry **analyses = _new LexicalEntry*[n_analyses]; for (int j = 0; j < n_analyses; j++) { Sexp *analysis = analysisList->getNthChild(j); int n_morphs = analysis->getNumChildren(); LexicalEntry **morphEntries = _new LexicalEntry*[n_morphs]; for (int k = 0; k < n_morphs; k++) { Sexp *morph = analysis->getNthChild(k); fvs = FeatureValueStructure::build(); // TODO: fix this morphEntries[k] = _new LexicalEntry(n_lex++, morph->getValue(), fvs, NULL, 0); } fvs = FeatureValueStructure::build(); // TODO: fix this analyses[j] = _new LexicalEntry(n_lex++, tokenList->getNthChild(i)->getValue(), fvs, morphEntries, n_morphs); } std::wstring token_str = wstring(tokenList->getNthChild(i)->getValue().to_string()); size_t token_len = token_str.length(); OffsetGroup startGroup = OffsetGroup(CharOffset(curr_char), EDTOffset(curr_char)); OffsetGroup endGroup = OffsetGroup(CharOffset(curr_char + token_len - 1), EDTOffset(curr_char + token_len - 1)); //#if defined(ARABIC_LANGUAGE) || defined(KOREAN_LANGUAGE) if (SerifVersion::isArabic() || SerifVersion::isKorean()) { origTokens[i] = _new LexicalToken(startGroup, endGroup, tokenList->getNthChild(i)->getValue(), i); morphTokens[i] = _new LexicalToken(startGroup, endGroup, tokenList->getNthChild(i)->getValue(), i, n_analyses, analyses); } //#endif curr_char += token_len + 1; // add an extra character for whitespace delete [] analyses; } //#if defined(ARABIC_LANGUAGE) || defined(KOREAN_LANGUAGE) if (SerifVersion::isArabic() || SerifVersion::isKorean()) { tokens[0] = _new LexicalTokenSequence(0, n_tokens, origTokens); } else { //#else tokens[0] = _new TokenSequence(0, n_tokens, origTokens); } //#endif tokens[0]->retokenize(n_tokens, morphTokens); delete [] origTokens; delete [] morphTokens; delete sentence; return true; } void runTraining(int argc, char* argv[]) { try { char mprefix[500]; if (argc != 5 && argc != 6) { print_usage(); return; } const char* pfile = argv[2]; const char* tfile = argv[3]; const char* mbuffer = argv[4]; int mult = atoi(mbuffer); ParamReader::readParamFile(pfile); FeatureModule::load(); if (argc == 6) { strncpy(mprefix, argv[5], 500); } else if (argc == 5) { ParamReader::getRequiredParam("MorphModel", mprefix, 500); } std::cout << "Model Prefix: " << mprefix << " Mult: " << mult << std::endl; //Create a default session logger since the lexicon assumes its there std::wstringstream buffer; buffer << mprefix << ".trainSession.log"; SessionLogger* sessionLogger = _new FileSessionLogger(buffer.str().c_str(), 0, 0); SessionLogger::logger = sessionLogger; MorphModel *m = MorphModel::build(); m->setMultiplier(mult); m->trainOnSingleFile(tfile, mprefix); delete m; delete sessionLogger; } catch (UnrecoverableException e) { std::cout << "Exception: " << e.getSource() << " " << e.getMessage() << std::endl; } } void runTokenizer(int argc, char* argv[]) { try { const char* pfile = argv[2]; ParamReader::readParamFile(pfile); FeatureModule::load(); std::string dfile = ParamReader::getRequiredParam("input_file"); std::cout << "Input File: " << dfile << std::endl; std::string ofile = ParamReader::getRequiredParam("output_file"); std::cout << "Output File: " << ofile << std::endl; std::string map = ParamReader::getRequiredParam("reverse_subst_map"); SymbolSubstitutionMap* reverseSubs = _new SymbolSubstitutionMap(map.c_str()); LocatedString *sentenceString = 0; Tokenizer *tokenizer = Tokenizer::build(); TokenSequence *tokens[1]; //Create a default session logger since the lexicon assumes its there std::wstring log(ofile.begin(), ofile.end()); log.append(L"-tokenize.log"); SessionLogger* sessionLogger = _new FileSessionLogger(log.c_str(), 0, 0); SessionLogger::logger = sessionLogger; boost::scoped_ptr<UTF8InputStream> uis_scoped_ptr(UTF8InputStream::build(dfile.c_str())); UTF8InputStream& uis(*uis_scoped_ptr); UTF8OutputStream uos(ofile.c_str()); int linecount = 0; while (!uis.eof()) { linecount++; if ((linecount % 250) == 0) { std::cout << "Read Line " << linecount << std::endl; } uis.getLine(line, MAX_LINE_LENGTH); if (wcslen(line) == 0) continue; sentenceString = _new LocatedString(line); tokenizer->getTokenTheories(tokens, 1, sentenceString); for (int j = 0; j < tokens[0]->getNTokens(); j++) { Symbol out = reverseSubs->replace(tokens[0]->getToken(j)->getSymbol()); uos << out.to_string() << " "; } uos << L"\n"; delete tokens[0]; delete sentenceString; } uis.close(); uos.close(); delete tokenizer; delete sessionLogger; delete reverseSubs; } catch (UnrecoverableException e) { std::cout << "Exception: " << e.getSource() << " " << e.getMessage() << std::endl; } } void runDecoderNameTraining(int argc, char* argv[]){ // Expects input of the form ((word1 NONE-ST) (word2 GPE-ST) ... ) // Outputs the same form. try { if (argc != 3 && argc != 5) { print_usage(); return; } const char* pfile = argv[2]; ParamReader::readParamFile(pfile); FeatureModule::load(); char dfile[600]; char ofile[600]; if (argc == 3) { ParamReader::getRequiredParam("input_file", dfile, 600); ParamReader::getRequiredParam("output_file", ofile, 600); } else { strncpy(dfile, argv[3], 600); strncpy(ofile, argv[4], 600); } std::cout << "Input File: " << dfile << std::endl; std::cout << "Output File: " << ofile << std::endl; //Create a default session logger since the lexicon assumes its there std::wstringstream buffer; buffer << ofile << "-tokenize.log"; SessionLogger* sessionLogger = _new FileSessionLogger(buffer.str().c_str(), 0, 0); SessionLogger::logger = sessionLogger; Symbol *origTags = _new Symbol[MAX_SENTENCE_TOKENS]; MorphologicalAnalyzer *morphAnalysis = MorphologicalAnalyzer::build(); std::cout << "Initialized Morphological Analyzer" << std::endl; MorphSelector *morphSelector = _new MorphSelector(); std::cout << "Initialized Morphological Selector" << std::endl; NameClassTags *nameClassTags = _new NameClassTags(); MTNormalizer *mtNormalizer; bool do_mt_normalization = ParamReader::isParamTrue("do_mt_normalization"); if(do_mt_normalization) mtNormalizer = MTNormalizer::build(); boost::scoped_ptr<UTF8InputStream> uis_scoped_ptr(UTF8InputStream::build(dfile)); UTF8InputStream& uis(*uis_scoped_ptr); UTF8OutputStream uos(ofile); int linecount = 0; TokenSequence *tokenSequenceBuf; Token **origTokens; origTokens = _new Token*[MAX_SENTENCE_TOKENS]; while (!uis.eof()) { linecount++; if ((linecount % 250) == 0) { std::cout << "Read Line " << linecount << std::endl; // This line appears to fix a memory leak that causes a crash after about 23000 sentences. SessionLexicon::getInstance().getLexicon()->clearDynamicEntries(); } Sexp sentence(uis); if(sentence.isVoid()) continue; int n_tokens = sentence.getNumChildren() < MAX_SENTENCE_TOKENS ? sentence.getNumChildren() : MAX_SENTENCE_TOKENS; int curr_char = 0; for (int i = 0; i < n_tokens; i++) { Sexp *pair = sentence.getNthChild(i); std::wstring token_str = wstring(pair->getFirstChild()->getValue().to_string()); size_t token_len = token_str.length(); OffsetGroup startGroup = OffsetGroup(CharOffset(curr_char), EDTOffset(curr_char)); OffsetGroup endGroup = OffsetGroup(CharOffset(curr_char + token_len - 1), EDTOffset(curr_char + token_len - 1)); //#if defined(ARABIC_LANGUAGE) || defined(KOREAN_LANGUAGE) if (SerifVersion::isArabic() || SerifVersion::isKorean()) { origTokens[i] = _new LexicalToken(startGroup, endGroup, pair->getFirstChild()->getValue(), i); } //#endif origTags[i] = pair->getSecondChild()->getValue(); curr_char += token_len + 1; // add an extra character for whitespace } //#if defined(ARABIC_LANGUAGE) || defined(KOREAN_LANGUAGE) if (SerifVersion::isArabic() || SerifVersion::isKorean()) { tokenSequenceBuf = _new LexicalTokenSequence(0, n_tokens, origTokens); } else { //#else tokenSequenceBuf = _new TokenSequence(0, n_tokens, origTokens); } //#endif LocatedString *sentenceString = _new LocatedString(sentence.to_token_string().c_str()); morphAnalysis->getMorphTheories(tokenSequenceBuf); morphSelector->selectTokenization(sentenceString, tokenSequenceBuf); if(do_mt_normalization){ int numTokensBeforeNormalization = tokenSequenceBuf->getNTokens(); mtNormalizer->normalize(tokenSequenceBuf); int numTokensAfterNormalization = tokenSequenceBuf->getNTokens(); if(numTokensBeforeNormalization != numTokensAfterNormalization){ // In the rare event that a token is deleted, it could cause a problem like the first tag being NONE-CO. // Rather than fixing the tag, we just skip the sentence. std::cout << "Number of tokens changed during normalization. Skipping line.\n"; delete tokenSequenceBuf; morphAnalysis->resetForNewSentence(); morphAnalysis->resetDictionary(); morphSelector->resetForNewSentence(); mtNormalizer->resetForNewSentence(); continue; } } //#if defined(ARABIC_LANGUAGE) || defined(KOREAN_LANGUAGE) if (SerifVersion::isArabic() || SerifVersion::isKorean()) { uos << "( " ; for (int i = 0; i < tokenSequenceBuf->getNTokens(); i++) { const LexicalToken *out_token = dynamic_cast<const LexicalToken*>(tokenSequenceBuf->getToken(i)); Symbol out_tag = origTags[out_token->getOriginalTokenIndex()]; // If out_token is not at the beginning of an original token, replace out_tag with it's -CO form if(i > 0) if(out_token->getOriginalTokenIndex() == dynamic_cast<const LexicalToken*>(tokenSequenceBuf->getToken(i-1))->getOriginalTokenIndex()) out_tag = nameClassTags->getTagSymbol(nameClassTags->getContinueForm(nameClassTags->getIndexForTag(out_tag))); uos << "( " << out_token->getSymbol().to_string() << " " << out_tag.to_string() << " )"; } uos << " )" << L"\n"; } //#endif delete tokenSequenceBuf; delete sentenceString; morphAnalysis->resetForNewSentence(); morphAnalysis->resetDictionary(); morphSelector->resetForNewSentence(); if(do_mt_normalization){ mtNormalizer->resetForNewSentence(); } } uis.close(); uos.close(); delete sessionLogger; delete [] origTokens; delete [] origTags; delete morphAnalysis; delete morphSelector; delete nameClassTags; if(do_mt_normalization) delete mtNormalizer; } catch (UnrecoverableException e) { std::cout << "Exception: " << e.getSource() << " " << e.getMessage() << std::endl; } } void runDecoder(int argc, char* argv[]) { try { if (argc != 3 && argc != 5) { print_usage(); return; } const char* pfile = argv[2]; ParamReader::readParamFile(pfile); FeatureModule::load(); char dfile[600]; char ofile[600]; if (argc == 3) { ParamReader::getRequiredParam("input_file", dfile, 600); ParamReader::getRequiredParam("output_file", ofile, 600); } else { strncpy(dfile, argv[3], 600); strncpy(ofile, argv[4], 600); } std::cout << "Input File: " << dfile << std::endl; std::cout << "Output File: " << ofile << std::endl; // Cluster training doesn't need sexp, just text. bool output_for_cluster_training = ParamReader::isParamTrue("output_for_cluster_training"); LocatedString *sentenceString = 0; Tokenizer *tokenizer = Tokenizer::build(); TokenSequence *tokens[1]; Symbol words[MAX_SENTENCE_TOKENS]; Symbol sentence[MAX_SENTENCE_TOKENS]; //Create a default session logger since the lexicon assumes its there std::string expt_dir = ParamReader::getRequiredParam("experiment_dir"); std::wstring log_file(expt_dir.begin(), expt_dir.end()); log_file.append(L"/decode.log"); SessionLogger* sessionLogger = _new FileSessionLogger(log_file.c_str(), 0, 0); SessionLogger::logger = sessionLogger; MorphologicalAnalyzer *morphAnalyzer = MorphologicalAnalyzer::build(); std::cout << "Initialized Morphological Analyzer" << std::endl; MorphSelector *morphSelector = _new MorphSelector(); std::cout << "Initialized Morphological Selector" << std::endl; MTNormalizer *mtNormalizer; bool do_mt_normalization = ParamReader::isParamTrue("do_mt_normalization"); if(do_mt_normalization) mtNormalizer = MTNormalizer::build(); boost::scoped_ptr<UTF8InputStream> uis_scoped_ptr(UTF8InputStream::build(dfile)); UTF8InputStream& uis(*uis_scoped_ptr); UTF8OutputStream uos(ofile); int linecount = 0; while (!uis.eof()) { linecount++; if ((linecount % 250) == 0) { std::cout << "Read Line " << linecount << std::endl; // This line fixes a memory leak in runDecoderNameTraining(), and was added here out of caution. SessionLexicon::getInstance().getLexicon()->clearDynamicEntries(); } uis.getLine(line, MAX_LINE_LENGTH); if (wcslen(line) == 0){ std::cout << "Blank line " << linecount << std::endl; continue; } sentenceString = _new LocatedString(line); tokenizer->getTokenTheories(tokens, 1, sentenceString); morphAnalyzer->getMorphTheories(tokens[0]); morphSelector->selectTokenization(sentenceString, tokens[0]); if(do_mt_normalization) mtNormalizer->normalize(tokens[0]); int num_tokens = tokens[0]->getNTokens(); if(!output_for_cluster_training) uos<< "( "; for (int j = 0; j < num_tokens; j++) { uos << tokens[0]->getToken(j)->getSymbol().to_string() << " "; } if(!output_for_cluster_training) uos << L" )"; uos << "\n"; delete tokens[0]; delete sentenceString; morphAnalyzer->resetDictionary(); morphSelector->resetForNewSentence(); if(do_mt_normalization) mtNormalizer->resetForNewSentence(); } uis.close(); uos.close(); delete tokenizer; delete sessionLogger; delete morphAnalyzer; delete morphSelector; if(do_mt_normalization) delete mtNormalizer; } catch (UnrecoverableException e) { std::cout << "Exception: " << e.getSource() << " " << e.getMessage() << std::endl; } } void runDecoderPretokenized(int argc, char* argv[]) { try { char buffer[700]; const char* pfile = argv[2]; ParamReader::readParamFile(pfile); FeatureModule::load(); ParamReader::getParam("reverse_subst_map", buffer, 700); SymbolSubstitutionMap* reverseSubs = _new SymbolSubstitutionMap(buffer); //Create a default session logger since the lexicon assumes its there std::string log_file = ParamReader::getRequiredParam("log_file"); SessionLogger* sessionLogger = _new FileSessionLogger(std::wstring(log_file.begin(), log_file.end()).c_str(), 0, 0); SessionLogger::logger = sessionLogger; TokenSequence **tokens = _new TokenSequence*[1]; LocatedString sentenceString(L""); Symbol words[MAX_SENTENCE_TOKENS]; int map[MAX_SENTENCE_TOKENS]; MorphDecoder *morphDecoder = MorphDecoder::build(); std::cout << "Initialized Morphological Decoder" << std::endl; if (ParamReader::isParamTrue("list_mode")) { char file_list[600]; char dfile[600]; char ofile[600]; ParamReader::getRequiredParam("input_file_list", file_list, 600); std::cout << "Input File List: " << file_list << std::endl; std::basic_ifstream<char> in; in.open(file_list); if (in.fail()) { throw UnexpectedInputException("MorphologyTrainerMain::main()", "could not open input file list"); } while (!in.eof()) { in.getline(dfile, 600); sprintf(ofile, "%s.morph", dfile); if (strcmp(dfile, "") == 0) break; std::cout << "Input File: " << dfile << std::endl; std::cout << "Output File: " << ofile << std::endl; boost::scoped_ptr<UTF8InputStream> uis_scoped_ptr(UTF8InputStream::build(dfile)); UTF8InputStream& uis(*uis_scoped_ptr); UTF8OutputStream uos(ofile); int linecount = 0; while (readTokenizedAndAnalyzedSentence(uis, tokens, sentenceString)) { linecount++; if ((linecount % 250) == 0) { std::cout << "Read Line " << linecount << std::endl; } int num_tokens = morphDecoder->getBestWordSequence(sentenceString, tokens[0], words, map, MAX_SENTENCE_TOKENS); //morphDecoder->printTrellis(uos); int map_idx = 0; uos << "( ("; for (int j = 0; j < num_tokens; j++) { Symbol out = reverseSubs->replace(words[j]); if (map_idx != map[j]) { uos << ") ("; // mark tokens where decoder had >1 analysis to choose from //#if defined(ARABIC_LANGUAGE) || defined(KOREAN_LANGUAGE) if (SerifVersion::isArabic() || SerifVersion::isKorean()) { if (dynamic_cast<const LexicalToken*>(tokens[0]->getToken(map[j]))->getNLexicalEntries() > 1) uos << "*"; } //#endif map_idx = map[j]; } uos << words[j].to_string(); if ((j != num_tokens - 1) && (map[j] == map[j+1])) uos << "+"; } uos << L") )\n"; delete tokens[0]; } uis.close(); uos.close(); } in.close(); } else { char dfile[600]; ParamReader::getRequiredParam("input_file", dfile, 600); std::cout << "Input File: " << dfile << std::endl; char ofile[600]; ParamReader::getRequiredParam("output_file", ofile, 600); std::cout << "Output File: " << ofile << std::endl; boost::scoped_ptr<UTF8InputStream> uis_scoped_ptr(UTF8InputStream::build(dfile)); UTF8InputStream& uis(*uis_scoped_ptr); UTF8OutputStream uos(ofile); int linecount = 0; while (readTokenizedAndAnalyzedSentence(uis, tokens, sentenceString)) { linecount++; if ((linecount % 250) == 0) { std::cout << "Read Line " << linecount << std::endl; } int num_tokens = morphDecoder->getBestWordSequence(sentenceString, tokens[0], words, map, MAX_SENTENCE_TOKENS); //morphDecoder->printTrellis(uos); int map_idx = 0; uos << "( ("; for (int j = 0; j < num_tokens; j++) { Symbol out = reverseSubs->replace(words[j]); if (map_idx != map[j]) { uos << ") ("; // mark tokens where decoder had >1 analysis to choose from //#if defined(ARABIC_LANGUAGE) || defined(KOREAN_LANGUAGE) if (SerifVersion::isArabic() || SerifVersion::isKorean()) { if (dynamic_cast<const LexicalToken*>(tokens[0]->getToken(map[j]))->getNLexicalEntries() > 1) uos << "*"; } //#endif map_idx = map[j]; } uos << words[j].to_string(); if ((j != num_tokens - 1) && (map[j] == map[j+1])) uos << "+"; } uos << L") )\n"; delete tokens[0]; } uis.close(); uos.close(); } delete sessionLogger; delete reverseSubs; delete morphDecoder; } catch (UnrecoverableException e) { std::cout << "Exception: " << e.getSource() << " " << e.getMessage() << std::endl; } } int main(int argc, char* argv[]) { std::cout << "MorphologyTrainerMain v2.0" << std::endl; if (argc != 3 && argc != 5 && argc != 6) { print_usage(); return 0; } if (strcmp(argv[1], "-t") == 0) { runTraining(argc, argv); } else if (strcmp(argv[1], "-tok") == 0) { runTokenizer(argc, argv); } else if (strcmp(argv[1], "-dsexp") == 0) { runDecoderNameTraining(argc, argv); } else if (strcmp(argv[1], "-d") == 0) { runDecoder(argc, argv); } else if (strcmp(argv[1], "-a") == 0) { runDecoderPretokenized(argc, argv); } else { print_usage(); return 0; } return 0; }
33.54785
140
0.655408
BBN-E
802e48289708f2cf57236d5b295089aef1c3bf34
1,293
hh
C++
include/WCSimFitterInterface.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
include/WCSimFitterInterface.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
include/WCSimFitterInterface.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
/* * WCSimFitterInterface.hh * * Created on: 31 Oct 2014 * Author: andy */ #pragma once #include <TString.h> #include "WCSimTrackParameterEnums.hh" class WCSimLikelihoodFitter; class WCSimFitterConfig; class WCSimFitterPlots; class WCSimOutputTree; class WCSimPiZeroFitter; class WCSimCosmicFitter; class WCSimFitterInterface { public: virtual ~WCSimFitterInterface(); WCSimFitterInterface(); void SetInputFileName(const char *inputfile, bool modifyFile); void SetMakeFits(bool makeFits); void AddFitterConfig(WCSimFitterConfig *config); void AddFitterPlots(WCSimFitterPlots *plots); void InitFitter(WCSimFitterConfig *config); void LoadWCSimData(); void InitFitterPlots(TString outputName, WCSimFitterConfig *config); void Run(); private: // Fit configuration parameters int fNumFits; std::vector<WCSimFitterConfig *> fFitterConfigs; // Input file parameters bool fModifyInputFile; TString fFileName; TString fOutputName; // Fitters, selections, particle identification, output etc... WCSimLikelihoodFitter *fFitter; WCSimPiZeroFitter *fPiZeroFitter; WCSimCosmicFitter *fCosmicFitter; WCSimOutputTree *fOutputTree; bool fMakeFits; bool fMakePlots; TString fPlotsName; WCSimFitterPlots *fFitterPlots; ClassDef(WCSimFitterInterface, 0) };
19.892308
69
0.78809
chipsneutrino
80335799b0d21634a27b9f502d332eba67a1516e
6,078
cc
C++
o3d/core/cross/event_manager.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
o3d/core/cross/event_manager.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
o3d/core/cross/event_manager.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This file contains the implementation for the EventManager class. #include "core/cross/event_manager.h" #include "core/cross/client.h" #include "core/cross/error.h" namespace o3d { void EventManager::ProcessQueue() { // Process up to one event per frame. // If we've removed all callbacks by clearing event_callbacks_, we're shutting // down, so we can't process any late-added events. if (valid_ && !event_queue_.empty()) { #ifndef NDEBUG DCHECK(!processing_event_queue_); processing_event_queue_ = true; #endif Event event = event_queue_.front(); // Pop the event before invoking the callback; the callback might invoke // Client::CleanUp, which empties the event queue. This can happen in Chrome // if it invokes the unload handler when control enters JavaScript. event_queue_.pop_front(); event_callbacks_[event.type()].Run(event); #ifndef NDEBUG processing_event_queue_ = false; #endif } } void EventManager::SetEventCallback(Event::Type type, EventCallback* event_callback) { DCHECK(Event::ValidType(type)); if (valid_) event_callbacks_[type].Set(event_callback); } void EventManager::ClearEventCallback(Event::Type type) { DCHECK(Event::ValidType(type)); if (valid_) event_callbacks_[type].Clear(); } void EventManager::AddEventToQueue(const Event& event) { // If we're shutting down or there's no callback registered to handle // this event type, we drop it. // NOTE:If we have a callback registered for the click event then we allow // MOUSEDOWN and MOUSEUP events through. if (valid_ && (event_callbacks_[event.type()].IsSet() || (event_callbacks_[Event::TYPE_CLICK].IsSet() && (event.type() == Event::TYPE_MOUSEDOWN || event.type() == Event::TYPE_MOUSEUP)))) { if (!event_queue_.empty()) { switch (event.type()) { case Event::TYPE_MOUSEMOVE: if (event_queue_.back().type() == Event::TYPE_MOUSEMOVE) { // Just keep the last MOUSEMOVE; there's no need to queue up lots // of them. event_queue_.back() = event; return; } break; case Event::TYPE_KEYPRESS: // If we're backed up with keydowns and keypresses [which alternate // on key repeat], just throw away the new ones. Throwing them away // one at a time could lead to aliased repeat patterns in which we // throw away more keydowns than keypresses, so we have to detect the // pair together and throw them both away. This means that we won't // start chucking stuff until there are at least 4 events backed up [3 // in the queue plus the new one], but that'll keep us from getting // more than a few frames behind. if (event_queue_.size() >= 3) { EventQueue::reverse_iterator iter = event_queue_.rbegin(); const Event& event3 = *iter; if (event3.type() != Event::TYPE_KEYDOWN) { break; } const Event& event2 = *++iter; if (event2 != event) { break; } const Event& event1 = *++iter; if (event1 != event3) { break; } event_queue_.pop_back(); // Throw away the keydown. return; // Throw away the keypress. } break; default: break; } } if (event.type() == Event::TYPE_MOUSEDOWN) { if (event.in_plugin()) { mousedown_in_plugin_ = true; } else { mousedown_in_plugin_ = false; return; // Why did we even get this event? } } if (event_callbacks_[event.type()].IsSet()) event_queue_.push_back(event); if (event.type() == Event::TYPE_MOUSEUP) { if (mousedown_in_plugin_ && event.in_plugin()) { Event temp = event; temp.set_type(Event::TYPE_CLICK); event_queue_.push_back(temp); if (temp.button() == Event::BUTTON_RIGHT) { temp.set_type(Event::TYPE_CONTEXTMENU); temp.clear_modifier_state(); temp.clear_button(); event_queue_.push_back(temp); } } mousedown_in_plugin_ = false; } } } void EventManager::ClearAll() { valid_ = false; for (unsigned int i = 0; i < arraysize(event_callbacks_); ++i) { event_callbacks_[i].Clear(); } event_queue_.clear(); } } // namespace o3d
36.614458
80
0.648898
rwatson
803423d1e5c719bda57888babcca905836a0c056
2,334
cpp
C++
src/main.cpp
Embedded-AMS/EmbeddedProto_Example_Makefile
4e8440c887835f27b8343baa95193618eaf9b6c7
[ "CECILL-B" ]
4
2020-11-11T15:17:28.000Z
2021-06-12T10:25:10.000Z
src/main.cpp
Embedded-AMS/EmbeddedProto_Example_Makefile
4e8440c887835f27b8343baa95193618eaf9b6c7
[ "CECILL-B" ]
null
null
null
src/main.cpp
Embedded-AMS/EmbeddedProto_Example_Makefile
4e8440c887835f27b8343baa95193618eaf9b6c7
[ "CECILL-B" ]
1
2020-11-11T17:16:25.000Z
2020-11-11T17:16:25.000Z
// Includes #include <stm32f4xx.h> #include <main.h> #include <reply.h> #include <request.h> #include <DemoWriteBuffer.h> #include <DemoReadBuffer.h> // Construction of the messages. demo::reply reply_msg; demo::request request_msg; // Construction of the write and read buffer objects. demo::WriteBuffer<50> send_buffer; demo::ReadBuffer read_buffer; int main(void) { SystemInit(); uint32_t request_counter = 0; while (1) { // Increment the request counter each iteration and alternate between request A and B. request_msg.set_msgId(++request_counter); request_msg.set_selection((request_counter & 0x01) ? demo::types::A : demo::types::B); if(request_msg.serialize(send_buffer)) { // Serialization is successful. We can now use the buffer to send the data via a peripheral. } else { // Serialization failed for some reason. } // For demo purposes manually set the demo data. if(request_counter & 0x01) { // Data for A constexpr uint32_t RESPONS_SIZE_A = 10; uint8_t demo_response_A[RESPONS_SIZE_A] = {0x08, 0x01, 0x12, 0x06, 0x08, 0x0A, 0x10, 0x14, 0x18, 0x1E}; read_buffer.set_demo_data(demo_response_A, RESPONS_SIZE_A); } else { // Data for B constexpr uint32_t RESPONS_SIZE_B = 31; uint8_t demo_response_B[RESPONS_SIZE_B] = {0x08, 0x02, 0x1A, 0x1B, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x69, 0x40, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x72, 0x40}; read_buffer.set_demo_data(demo_response_B, RESPONS_SIZE_B); } // Obtain from the buffer the reply message. if(reply_msg.deserialize(read_buffer)) { // Now we can use it. switch(reply_msg.get_which_type()) { case demo::reply::id::A: { // Do something with the data. uint32_t ans_a = reply_msg.a().x() + reply_msg.a().y() + reply_msg.a().z(); break; } case demo::reply::id::B: { // Do something with the data. uint32_t ans_b = reply_msg.b().u() * reply_msg.b().v() * reply_msg.b().w(); break; } default: break; } } } }
26.224719
98
0.606255
Embedded-AMS
8036fc4b63770a35dee077bfd84863330de05316
413
cpp
C++
Chapter 9. Sequential Containers/Codes/9.31_1 Solution.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
null
null
null
Chapter 9. Sequential Containers/Codes/9.31_1 Solution.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
null
null
null
Chapter 9. Sequential Containers/Codes/9.31_1 Solution.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
1
2021-09-30T14:08:03.000Z
2021-09-30T14:08:03.000Z
#include <iostream> #include <list> int main() { std::list<int> myList{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto iter = myList.begin(); while (iter != myList.end()) { if (*iter % 2) { iter = myList.insert(iter, *iter); std::advance(iter, 2); } else { iter = myList.erase(iter); } } for (const int element : myList) { std::cout << element << ' '; } return 0; }
17.208333
55
0.510896
Yunxiang-Li
80384bdac5914041b43cdf7a3d960e6ad18d31c1
368
cpp
C++
Pbinfo/cifra_control_comuna.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
7
2019-01-06T19:10:14.000Z
2021-10-16T06:41:23.000Z
Pbinfo/cifra_control_comuna.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
null
null
null
Pbinfo/cifra_control_comuna.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
6
2019-01-06T19:17:30.000Z
2020-02-12T22:29:17.000Z
#include <iostream> using namespace std; int sum_cifra_control(int a, int b){ int k=0; if(a>b) swap(b, a); if(a==9){ for(int i=a; i<=b; i++) if(i%9==0) k++; } else for(int i=a; i<=b; i++) if(i%9==a) k++; return k; } int main() { int a, b; cin>>a>>b; cout<<sum_cifra_control(a, b); return 0; }
13.142857
36
0.464674
Al3x76
803940a0f9b1a9944436c3b9a19dad52aec0b80e
2,896
cpp
C++
src/Kononov/Common/Scene/CubeMesh.cpp
sadads1337/fit-gl
88d9ae1f1935301d71ae6e090aff24e6829a7580
[ "MIT" ]
2
2021-04-25T15:18:40.000Z
2022-02-27T15:44:04.000Z
src/Kononov/Common/Scene/CubeMesh.cpp
sadads1337/fit-gl
88d9ae1f1935301d71ae6e090aff24e6829a7580
[ "MIT" ]
31
2021-02-17T21:12:59.000Z
2021-05-26T07:06:59.000Z
src/Kononov/Common/Scene/CubeMesh.cpp
sadads1337/fit-gl
88d9ae1f1935301d71ae6e090aff24e6829a7580
[ "MIT" ]
9
2021-02-08T08:52:51.000Z
2022-02-27T15:43:55.000Z
#include "CubeMesh.hpp" namespace Kononov { const std::vector<Kononov::RegularVertex> cubeVertices = { {{-1.0F, -1.0F, 1.0F}, {0, 0, 1}, {0.0F, 0.0F}}, // v0 {{1.0F, -1.0F, 1.0F}, {0, 0, 1}, {0.333F, 0.0F}}, // v1 {{-1.0F, 1.0F, 1.0F}, {0, 0, 1}, {0.0F, 0.5F}}, // v2 {{1.0F, 1.0F, 1.0F}, {0, 0, 1}, {0.333F, 0.5F}}, // v3 // Vertex data for face 1 {{1.0F, -1.0F, 1.0F}, {1, 0, 0}, {0.0F, 0.5F}}, // v4 {{1.0F, -1.0F, -1.0F}, {1, 0, 0}, {0.333F, 0.5F}}, // v5 {{1.0F, 1.0F, 1.0F}, {1, 0, 0}, {0.0F, 1.0F}}, // v6 {{1.0F, 1.0F, -1.0F}, {1, 0, 0}, {0.333F, 1.0F}}, // v7 // Vertex data for face 2 {{1.0F, -1.0F, -1.0F}, {0, 0, -1}, {0.666F, 0.5F}}, // v8 {{-1.0F, -1.0F, -1.0F}, {0, 0, -1}, {1.0F, 0.5F}}, // v9 {{1.0F, 1.0F, -1.0F}, {0, 0, -1}, {0.666F, 1.0F}}, // v10 {{-1.0F, 1.0F, -1.0F}, {0, 0, -1}, {1.0F, 1.0F}}, // v11 // Vertex data for face 3 {{-1.0F, -1.0F, -1.0F}, {-1, 0, 0}, {0.666F, 0.0F}}, // v12 {{-1.0F, -1.0F, 1.0F}, {-1, 0, 0}, {1.0F, 0.0F}}, // v13 {{-1.0F, 1.0F, -1.0F}, {-1, 0, 0}, {0.666F, 0.5F}}, // v14 {{-1.0F, 1.0F, 1.0F}, {-1, 0, 0}, {1.0F, 0.5F}}, // v15 // Vertex data for face 4 {{-1.0F, -1.0F, -1.0F}, {0, -1, 0}, {0.333F, 0.0F}}, // v16 {{1.0F, -1.0F, -1.0F}, {0, -1, 0}, {0.666F, 0.0F}}, // v17 {{-1.0F, -1.0F, 1.0F}, {0, -1, 0}, {0.333F, 0.5F}}, // v18 {{1.0F, -1.0F, 1.0F}, {0, -1, 0}, {0.666F, 0.5F}}, // v19 // Vertex data for face 5 {{-1.0F, 1.0F, 1.0F}, {0, 1, 0}, {0.333F, 0.5F}}, // v20 {{1.0F, 1.0F, 1.0F}, {0, 1, 0}, {0.666F, 0.5F}}, // v21 {{-1.0F, 1.0F, -1.0F}, {0, 1, 0}, {0.333F, 1.0F}}, // v22 {{1.0F, 1.0F, -1.0F}, {0, 1, 0}, {0.666F, 1.0F}}, // v23 }; // Indices for drawing cube faces using triangle strips. // Triangle strips can be connected by duplicating indices // between the strips. If connecting strips have opposite // vertex order then last index of the first strip and first // index of the second strip needs to be duplicated. If // connecting strips have same vertex order then only last // index of the first strip needs to be duplicated. const std::vector<GLuint> cubeStripeIndices = { 0, 1, 2, 3, 3, // Face 0 - triangle strip ( v0, v1, v2, v3) 4, 4, 5, 6, 7, 7, // Face 1 - triangle strip ( v4, v5, v6, v7) 8, 8, 9, 10, 11, 11, // Face 2 - triangle strip ( v8, v9, v10, v11) 12, 12, 13, 14, 15, 15, // Face 3 - triangle strip (v12, v13, v14, v15) 16, 16, 17, 18, 19, 19, // Face 4 - triangle strip (v16, v17, v18, v19) 20, 20, 21, 22, 23 // Face 5 - triangle strip (v20, v21, v22, v23) }; const std::vector<GLuint> cubeTrianglesIndices = { 0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7, 8, 9, 10, 10, 9, 11, 12, 13, 14, 14, 13, 15, 16, 17, 18, 18, 17, 19, 20, 21, 22, 22, 21, 23, }; } // namespace Kononov
46.709677
75
0.477901
sadads1337
8039a5613e3d99d4b6c17c084c5b584c0c66a22e
231
hpp
C++
packets/PKT_SPM_RemoveListener.hpp
HoDANG/OGLeague2
21efea8ea480972a6d686c4adefea03d57da5e9d
[ "MIT" ]
1
2022-03-27T10:21:41.000Z
2022-03-27T10:21:41.000Z
packets/PKT_SPM_RemoveListener.hpp
HoDANG/OGLeague2
21efea8ea480972a6d686c4adefea03d57da5e9d
[ "MIT" ]
null
null
null
packets/PKT_SPM_RemoveListener.hpp
HoDANG/OGLeague2
21efea8ea480972a6d686c4adefea03d57da5e9d
[ "MIT" ]
3
2019-07-20T03:59:10.000Z
2022-03-27T10:20:09.000Z
#ifndef HPP_110_PKT_SPM_RemoveListener_HPP #define HPP_110_PKT_SPM_RemoveListener_HPP #include "base.hpp" #pragma pack(push, 1) struct PKT_SPM_RemoveListener_s : DefaultPacket<PKT_SPM_RemoveListener> { }; #pragma pack(pop) #endif
21
71
0.831169
HoDANG
d9a2d2d4c3d82150466ecd93f0e234bbe514155f
5,494
cpp
C++
AndroidClient/math/collision/BoundingBox.cpp
aviskumar/speedo
758e8ac1fdeeb0b72c3a57742032ca5c79f0b2fa
[ "BSD-3-Clause" ]
77
2015-01-28T17:21:49.000Z
2022-02-17T17:59:21.000Z
AndroidClient/math/collision/BoundingBox.cpp
aviskumar/speedo
758e8ac1fdeeb0b72c3a57742032ca5c79f0b2fa
[ "BSD-3-Clause" ]
5
2015-03-22T23:14:54.000Z
2020-09-18T13:26:03.000Z
AndroidClient/math/collision/BoundingBox.cpp
aviskumar/speedo
758e8ac1fdeeb0b72c3a57742032ca5c79f0b2fa
[ "BSD-3-Clause" ]
24
2015-02-12T04:34:37.000Z
2021-06-19T17:05:23.000Z
/* Copyright 2011 Aevum Software aevum @ aevumlab.com 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. @author Victor Vicente de Carvalho victor.carvalho@aevumlab.com @author Ozires Bortolon de Faria ozires@aevumlab.com */ #include <algorithm> #include <limits> #include <sstream> #include <string> #include "BoundingBox.hpp" #include "gdx-cpp/math/Vector3.hpp" namespace gdx { class Matrix4; } // namespace gdx using namespace gdx; BoundingBox::BoundingBox() { crn_dirty = true; for (int l_idx = 0; l_idx < 8; l_idx++) { crn.push_back(Vector3()); } clr(); } BoundingBox::BoundingBox (const BoundingBox& bounds) : crn_dirty(true) { this->crn.reserve(8); this->set(bounds); } Vector3& BoundingBox::getCenter () { return cnt; } void BoundingBox::updateCorners () { if (!crn_dirty) return; crn[0].set(min.x, min.y, min.z); crn[1].set(max.x, min.y, min.z); crn[2].set(max.x, max.y, min.z); crn[3].set(min.x, max.y, min.z); crn[4].set(min.x, min.y, max.z); crn[5].set(max.x, min.y, max.z); crn[6].set(max.x, max.y, max.z); crn[7].set(min.x, max.y, max.z); crn_dirty = false; } const std::vector< Vector3 >& BoundingBox::getCorners () { updateCorners(); return crn; } Vector3& BoundingBox::getDimensions () { return dim; } Vector3& BoundingBox::getMin () { return min; } Vector3& BoundingBox::getMax () { return max; } BoundingBox& BoundingBox::set (const BoundingBox& bounds) { crn_dirty = true; return this->set(bounds.min, bounds.max); } BoundingBox& BoundingBox::set (const Vector3& minimum,const Vector3& maximum) { min.set(minimum.x < maximum.x ? minimum.x : maximum.x, minimum.y < maximum.y ? minimum.y : maximum.y, minimum.z < maximum.z ? minimum.z : maximum.z); max.set(minimum.x > maximum.x ? minimum.x : maximum.x, minimum.y > maximum.y ? minimum.y : maximum.y, minimum.z > maximum.z ? minimum.z : maximum.z); cnt.set(min).add(max).mul(0.5f); dim.set(max).sub(min); crn_dirty = true; return *this; } BoundingBox& BoundingBox::set (const std::vector<Vector3>& points) { this->inf(); auto it = points.begin(); auto end = points.end(); for (; it != end; ++it) this->ext(*it); crn_dirty = true; return *this; } BoundingBox& BoundingBox::inf () { //TODO: not sure if this works min.set(std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()); max.set(-std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity()); cnt.set(0, 0, 0); dim.set(0, 0, 0); crn_dirty = true; return *this; } BoundingBox& BoundingBox::ext (const Vector3& point) { crn_dirty = true; return this->set(min.set(_min(min.x, point.x), _min(min.y, point.y), _min(min.z, point.z)), max.set(std::max(max.x, point.x), std::max(max.y, point.y), std::max(max.z, point.z))); } BoundingBox& BoundingBox::clr () { crn_dirty = true; return this->set(min.set(0, 0, 0), max.set(0, 0, 0)); } bool BoundingBox::isValid () { return !(min.x == max.x && min.y == max.y && min.z == max.z); } BoundingBox& BoundingBox::ext (const BoundingBox& a_bounds) { crn_dirty = true; return this->set(min.set(_min(min.x, a_bounds.min.x), _min(min.y, a_bounds.min.y), _min(min.z, a_bounds.min.z)), max.set(_max(max.x, a_bounds.max.x), _max(max.y, a_bounds.max.y), _max(max.z, a_bounds.max.z))); } BoundingBox& BoundingBox::mul (const Matrix4& matrix) { updateCorners(); this->inf(); for ( int i = 0; i < 8; ++i) { crn[i].mul(matrix); min.set(_min(min.x, crn[i].x), _min(min.y, crn[i].y), _min(min.z, crn[i].z)); max.set(_max(max.x, crn[i].x), _max(max.y, crn[i].y), _max(max.z, crn[i].z)); } crn_dirty = true; return this->set(min, max); } bool BoundingBox::contains (const BoundingBox& bounds) { if (!isValid()) return true; if (min.x > bounds.max.x) return false; if (min.y > bounds.max.y) return false; if (min.z > bounds.max.z) return false; if (max.x < bounds.min.x) return false; if (max.y < bounds.min.y) return false; if (max.z < bounds.min.z) return false; return true; } bool BoundingBox::contains (const Vector3& v) { if (min.x > v.x) return false; if (max.x < v.x) return false; if (min.y > v.y) return false; if (max.y < v.y) return false; if (min.z > v.z) return false; if (max.z < v.z) return false; return true; } std::string BoundingBox::toString () { std::stringstream ss; ss << "[" + min.toString() << "|" + max.toString() << "]"; return ss.str(); } BoundingBox& BoundingBox::ext (float x,float y,float z) { crn_dirty = true; return this->set(min.set(_min(min.x, x), _min(min.y, y), _min(min.z, z)), max.set(_max(max.x, x), _max(max.y, y), _max(max.z, z))); }
28.915789
135
0.626866
aviskumar
d9a3207d357980280637637846369c3263cc35a9
22
cpp
C++
src/Game/zNPCGlyph.cpp
DarkRTA/bfbbdecomp
e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e
[ "OLDAP-2.7" ]
null
null
null
src/Game/zNPCGlyph.cpp
DarkRTA/bfbbdecomp
e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e
[ "OLDAP-2.7" ]
6
2022-01-16T05:29:01.000Z
2022-01-18T01:10:29.000Z
src/Game/zNPCGlyph.cpp
DarkRTA/bfbbdecomp
e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e
[ "OLDAP-2.7" ]
1
2022-01-16T00:04:23.000Z
2022-01-16T00:04:23.000Z
#include "zNPCGlyph.h"
22
22
0.772727
DarkRTA
d9a32c2b5d789fbea9b80b1a68abdd706713bfd8
130
hpp
C++
opencv2.framework/Versions/A/Headers/videostab/global_motion.hpp
osis/nostalgia-scanner-ios
100163e3c09f0dfe4483fb6a708522c750b46c52
[ "MIT" ]
15
2018-02-02T12:15:59.000Z
2022-03-31T00:11:49.000Z
opencv2.framework/Versions/A/Headers/videostab/global_motion.hpp
osis/nostalgia-scanner-ios
100163e3c09f0dfe4483fb6a708522c750b46c52
[ "MIT" ]
null
null
null
opencv2.framework/Versions/A/Headers/videostab/global_motion.hpp
osis/nostalgia-scanner-ios
100163e3c09f0dfe4483fb6a708522c750b46c52
[ "MIT" ]
5
2018-07-24T12:13:33.000Z
2019-08-15T09:26:42.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:cbbe8c77eae2a764e2a4ff88b6c272cb27c1c323992374907239fb20849c9539 size 10724
32.5
75
0.884615
osis
d9a5f9e8791b9e4055bc100df05bf5a4cc14875a
1,346
cpp
C++
luves/buffer.cpp
Leviathan1995/Luves
c8c64faf7130cd0dc58a1ffd2c7be24caedecbd2
[ "MIT" ]
19
2016-07-27T14:23:17.000Z
2021-03-14T08:10:45.000Z
luves/buffer.cpp
Leviathan1995/Luves
c8c64faf7130cd0dc58a1ffd2c7be24caedecbd2
[ "MIT" ]
1
2016-09-25T18:03:24.000Z
2016-10-01T06:29:59.000Z
luves/buffer.cpp
Leviathan1995/Luves
c8c64faf7130cd0dc58a1ffd2c7be24caedecbd2
[ "MIT" ]
5
2016-08-02T06:55:19.000Z
2021-05-05T14:15:20.000Z
// // Buffer.cpp // Luves // // Created by leviathan on 16/6/1. // Copyright © 2016年 leviathan. All rights reserved. // #include "buffer.h" namespace luves { // //Buffer // void Buffer::Append(Buffer & buffer) { buffer_.insert(buffer_.end(), buffer.buffer_[buffer.GetReadIndex()], buffer.buffer_[0]); write_index_ += buffer.GetReadIndex(); INFO_LOG("Append %d bytes to buffer.", buffer.GetReadIndex() ); } void Buffer::Append(const std::string & msg) { for (auto s:msg) { buffer_[read_index_] = s; write_index_++; } INFO_LOG("Append %d bytes to buffer.", msg.length()); } int Buffer::ReadImp(int fd) // in { buffer_.clear(); read_index_ = 0; int n = int(read(fd, &buffer_[0], 1024)); INFO_LOG("Receive %d bytes.",n); if(n>0) read_index_ += n; return n; } int Buffer::WriteImp(int fd) // out { int n = int(write(fd, buffer_.data(), write_index_)); INFO_LOG("Write %d bytes.", n); buffer_.clear(); write_index_ = 0; return n; } std::ostream & operator <<(std::ostream & os, Buffer & buffer) { for (auto data:buffer.buffer_) os<<data; return os; } }
21.709677
96
0.52526
Leviathan1995
d9a765f8ec2fa70f87ced8555fed9461a218ae41
6,144
cpp
C++
tls-diff-testing/middleman/src/TransportRelay.cpp
sizaif/tls-diff-testing
4eae4e8de6ebd1b791e32fca44b8189b04a2ea10
[ "BSD-3-Clause" ]
12
2017-11-10T05:39:47.000Z
2021-06-03T10:44:40.000Z
tls-diff-testing/middleman/src/TransportRelay.cpp
sizaif/tls-diff-testing
4eae4e8de6ebd1b791e32fca44b8189b04a2ea10
[ "BSD-3-Clause" ]
1
2019-02-05T14:13:28.000Z
2019-02-05T14:13:28.000Z
tls-diff-testing/middleman/src/TransportRelay.cpp
sizaif/tls-diff-testing
4eae4e8de6ebd1b791e32fca44b8189b04a2ea10
[ "BSD-3-Clause" ]
6
2017-10-12T06:03:09.000Z
2021-07-02T07:14:13.000Z
/* * Copyright (C) 2017 * Andreas Walz [andreas.walz@hs-offenburg.de] * Offenburg University of Applied Sciences * Institute of Reliable Embedded Systems and Communications Electronics (ivESK) * [https://ivesk.hs-offenburg.de/] * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "TransportRelay.h" #include "errno.h" #include "String_.h" #include "TCPServerSocket.h" #include "TCPClientSocket.h" /* * ___________________________________________________________________________ */ TransportRelay::TransportRelay( int inPort, const string& destAddr, int destPort) : serverSocket_(*(new TCPServerSocket(inPort))), outSocket_(*(new TCPClientSocket(destAddr, destPort))), inSocket_(0) { serverSocket_.setNonBlocking(true); outSocket_.setNonBlocking(true); } /* * ___________________________________________________________________________ */ void TransportRelay::bufferToVector( uint8_t* buffer, size_t bufferLen, vector<uint8_t>& data) { for (size_t i = 0; i < bufferLen; i++) { data.push_back(buffer[i]); } } /* * ___________________________________________________________________________ */ void TransportRelay::setLogPrefix(string prefix) { logPrefix_ = prefix; } /* * ___________________________________________________________________________ */ void TransportRelay::setLogLevel(int logLevel) { logLevel_ = logLevel; } /* * ___________________________________________________________________________ */ int TransportRelay::getLogLevel() const { return logLevel_; } /* * ___________________________________________________________________________ */ void TransportRelay::log(int minLevel, const string& msg) { if (logLevel_ >= minLevel) { printf("%s%s\n", logPrefix_.c_str(), msg.c_str()); } } /* * ___________________________________________________________________________ */ bool TransportRelay::process() { bool requestClose = false; /* accept incoming connection */ if (inSocket_ == 0) { inSocket_ = serverSocket_.accept(); if (inSocket_ != 0 && inSocket_->isConnected()) { inSocket_->setNonBlocking(true); log(2, "Client ---> [CONNECT]"); } } if (inSocket_ == 0 || !inSocket_->isConnected()) { return true; } /* establish outgoing connection */ if (!outSocket_.isConnected()) { outSocket_.connect(); if (outSocket_.isConnected()) { log(2, "[CONNECT] ---> Server"); } } if (!outSocket_.isConnected()) { return true; } /* * Client ---> Server */ vector<uint8_t> data; *inSocket_ >> data; if (data.size() > 0) { log(2, String::format( "Client ---> [%d bytes] > Server", data.size())); if (!this->interceptToServer(data)) { requestClose = true; } outSocket_ << data; } /* * Client <--- Server */ data.clear(); outSocket_ >> data; if (data.size() > 0) { log(2, String::format( "Client < [%d bytes] <--- Server", data.size())); if (!this->interceptToClient(data)) { requestClose = true; } *inSocket_ << data; } if (requestClose) { log(2, "Client <--- [CLOSE] ---> Server"); outSocket_.disconnect(); inSocket_->disconnect(); return false; } else { if (!inSocket_->isConnected()) { log(2, "Client ---> [CLOSE] ---> Server"); outSocket_.disconnect(); return false; } if (!outSocket_.isConnected()) { log(2, "Client <--- [CLOSE] <--- Server"); inSocket_->disconnect(); return false; } } return true; } /* * ___________________________________________________________________________ */ bool TransportRelay::close() { if (inSocket_ != 0) { inSocket_->close(); delete inSocket_; } serverSocket_.close(); outSocket_.close(); return true; } /* * ___________________________________________________________________________ */ ssize_t TransportRelay::injectToServer(vector<uint8_t>& data) { return -1; } /* * ___________________________________________________________________________ */ ssize_t TransportRelay::injectToClient(vector<uint8_t>& data) { return -1; } /* * ___________________________________________________________________________ */ bool TransportRelay::interceptToServer(vector<uint8_t>& data) { /* returning false would close the connection */ return true; } /* * ___________________________________________________________________________ */ bool TransportRelay::interceptToClient(vector<uint8_t>& data) { /* returning false would close the connection */ return true; } /* * ___________________________________________________________________________ */ TransportRelay::~TransportRelay() { this->close(); delete &serverSocket_; delete &outSocket_; }
24.094118
81
0.721842
sizaif
d9a7a5ffc12d6c001e55bfbef3eeddee1a46f3d6
2,993
hpp
C++
INCLUDE/Vcl/httputil.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
1
2022-01-13T01:03:55.000Z
2022-01-13T01:03:55.000Z
INCLUDE/Vcl/httputil.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
INCLUDE/Vcl/httputil.hpp
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'HTTPUtil.pas' rev: 6.00 #ifndef HTTPUtilHPP #define HTTPUtilHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <Classes.hpp> // Pascal unit #include <Types.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Httputil { //-- type declarations ------------------------------------------------------- __interface IStringTokenizer; typedef System::DelphiInterface<IStringTokenizer> _di_IStringTokenizer; __interface INTERFACE_UUID("{8C216E9D-984E-4E38-893F-0A222AC547DA}") IStringTokenizer : public IInterface { public: virtual int __fastcall getTokenCounts(void) = 0 ; virtual bool __fastcall hasMoreTokens(void) = 0 ; virtual WideString __fastcall nextToken(void) = 0 ; __property int countTokens = {read=getTokenCounts}; }; __interface IStreamLoader; typedef System::DelphiInterface<IStreamLoader> _di_IStreamLoader; __interface INTERFACE_UUID("{395CDFB2-1D10-4A37-AC16-393D569676F0}") IStreamLoader : public IInterface { public: virtual void __fastcall Load(const WideString WSDLFileName, Classes::TMemoryStream* Stream) = 0 ; virtual AnsiString __fastcall GetProxy(void) = 0 ; virtual void __fastcall SetProxy(const AnsiString Proxy) = 0 ; virtual AnsiString __fastcall GetUserName(void) = 0 ; virtual void __fastcall SetUserName(const AnsiString UserName) = 0 ; virtual AnsiString __fastcall GetPassword(void) = 0 ; virtual void __fastcall SetPassword(const AnsiString Password) = 0 ; __property AnsiString Proxy = {read=GetProxy, write=SetProxy}; __property AnsiString UserName = {read=GetUserName, write=SetUserName}; __property AnsiString Password = {read=GetPassword, write=SetPassword}; }; //-- var, const, procedure --------------------------------------------------- extern PACKAGE _di_IStreamLoader __fastcall GetDefaultStreamLoader(); extern PACKAGE bool __fastcall StartsWith(const AnsiString str, const AnsiString sub); extern PACKAGE int __fastcall FirstDelimiter(const AnsiString delimiters, const AnsiString Str)/* overload */; extern PACKAGE int __fastcall FirstDelimiter(const WideString delimiters, const WideString Str)/* overload */; extern PACKAGE _di_IStringTokenizer __fastcall StringTokenizer(const AnsiString str, const AnsiString delim); extern PACKAGE TStringDynArray __fastcall StringToStringArray(const AnsiString str, const AnsiString delim); extern PACKAGE AnsiString __fastcall HTMLEscape(const AnsiString Str); } /* namespace Httputil */ using namespace Httputil; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // HTTPUtil
42.757143
111
0.709322
earthsiege2
d9a8e28858aac3a8c270c5d48362e8309aed7fa2
1,614
cpp
C++
FastInverseSqrt.cpp
ubdussamad/x86-Vectorization-and-related
442ec6149729ae4ca26ca2da83c0fddf15164762
[ "CC0-1.0" ]
null
null
null
FastInverseSqrt.cpp
ubdussamad/x86-Vectorization-and-related
442ec6149729ae4ca26ca2da83c0fddf15164762
[ "CC0-1.0" ]
null
null
null
FastInverseSqrt.cpp
ubdussamad/x86-Vectorization-and-related
442ec6149729ae4ca26ca2da83c0fddf15164762
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <cmath> // This only works if IEE754 fp is being used for default float // Just for calculating log, 0.0683365F works for meeeeeeeee. // Tryin somethin pahneey // I am just using it for taking bianry log. // // author: ubussamad float fastFloatLog() __attribute_warn_unused_result__; int ffltest() { float num = 4.568; float stdlog = std::log2f(num); float nu = ((float)((*(unsigned int *)&num))) / (float)(1 << 23); float lg = (nu) + 0.0683365 - 127; std::cout << "Average diff is: " << std::abs(stdlog - lg) << std::endl; std::cout << "stdlog is: " << stdlog << "| mylog: " << lg << std::endl; return 0; } float fastFloatLog() { float min_diff_chi = 0.0; float min_diff = 1.0; int a = 0; __builtin_prefetch(&min_diff_chi); // Usually done with irreg accessed arrays for (float chi = 0.0F; chi < 1.0F; chi += 0.000001) { float avg_diff = 0.0; for (float num = 0.1F; num < 100.0; num += 0.5F) { float stdlog = std::log2f(num); float nu = ((float)((*(unsigned int *)&num))) / (float)(1 << 23); // Type punning bad :( float lg = (nu) + chi - 127; avg_diff += std::abs(stdlog - lg); } avg_diff /= 9900; // std::cout << "Avg diff: " << avg_diff << std::endl; if (avg_diff < min_diff) { min_diff = avg_diff; min_diff_chi = chi; } } std::cout << min_diff_chi << " | Min diff is: " << min_diff << std::endl; return min_diff_chi; } int main() { fastFloatLog(); }
26.032258
100
0.551425
ubdussamad
d9a9e4ea676155d885986bb4cfddc9c0710ff345
2,347
hpp
C++
liblogger/include/shs_manager.hpp
Parrot-Developers/logger
250b8e83f2c93434d6f613f1000a6ae9891aa567
[ "BSD-3-Clause" ]
null
null
null
liblogger/include/shs_manager.hpp
Parrot-Developers/logger
250b8e83f2c93434d6f613f1000a6ae9891aa567
[ "BSD-3-Clause" ]
null
null
null
liblogger/include/shs_manager.hpp
Parrot-Developers/logger
250b8e83f2c93434d6f613f1000a6ae9891aa567
[ "BSD-3-Clause" ]
1
2021-03-31T10:04:52.000Z
2021-03-31T10:04:52.000Z
/** * Copyright (c) 2019-2020 Parrot Drones SAS * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Parrot Drones SAS Company nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PARROT DRONES SAS COMPANY 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. */ #ifndef SHSMANAGER_HPP #define SHSMANAGER_HPP #include <shs.h> namespace loggerd { class ShsManager : public SettingsManager { public: ShsManager(struct pomp_loop *loop, const std::string &shsRoot); ShsManager(); virtual ~ShsManager(); public: virtual void initSettings(LogManager *manager) override; virtual void cleanSettings() override; virtual void startSettings() override; virtual void configureSettings(Plugin *plugin) override; private: static void pluginSettingsCb(struct shs_ctx *ctx, enum shs_evt evt, const struct shs_entry *old_entries, const struct shs_entry *new_entries, size_t count, void *userdata); private: struct shs_ctx *mShsCtx; std::string mShsRoot; }; } /* namespace loggerd */ #endif
37.253968
80
0.752024
Parrot-Developers
d9b000386041b16f5b4c6c1b773db1722d224b75
2,758
cpp
C++
src/parser.cpp
hanilr/ed
38c66d2376aa08fe20686d129cd901423aad1a46
[ "MIT" ]
1
2021-12-22T07:30:05.000Z
2021-12-22T07:30:05.000Z
src/parser.cpp
hanilr/ed
38c66d2376aa08fe20686d129cd901423aad1a46
[ "MIT" ]
null
null
null
src/parser.cpp
hanilr/ed
38c66d2376aa08fe20686d129cd901423aad1a46
[ "MIT" ]
null
null
null
// PARSER MAIN FILE // // STANDARD LIBRARY #include <iostream> #include <algorithm> // DIY LIBRARY #include "lib/parser.hpp" #include "lib/util.hpp" #include "lib/config.hpp" std::string parser_term(std::string term) { std::replace(term.begin(), term.end(), 46, 13); return term; } int parser_int(char const *rule_name, int line, int temp_state) { std::string rule = fetchr(rule_name, line); int rule_number = (int) rule[2] - 48; if(linstr(rule, "+") == 0) { return (temp_state + rule_number); } if(linstr(rule, "-") == 0) { return (temp_state - rule_number); } if(linstr(rule, "*") == 0) { return (temp_state * rule_number); } if(linstr(rule, "/") == 0) { return (temp_state / rule_number); } if(linstr(rule, "#") == 0) { return (temp_state); } } int reverse_parser_int(char const *rule_name, int line, int temp_state) { std::string rule = fetchr(rule_name, line); int rule_number = (int) rule[2] - 48; if(linstr(rule, "+") == 0) { return (temp_state - rule_number); } if(linstr(rule, "-") == 0) { return (temp_state + rule_number); } if(linstr(rule, "*") == 0) { return (temp_state / rule_number); } if(linstr(rule, "/") == 0) { return (temp_state * rule_number); } if(linstr(rule, "#") == 0) { return (temp_state); } } std::string parser_str(char const *rule_name, int line, std::string temp_state) { std::string temp_conv, rule = fetchr(rule_name, line); int temp_int, state_len = temp_state.length(), rule_number = (int) rule[2] - 48; for(int i = 0; state_len>i; i+=1) { temp_int = temp_state[i]; if(linstr(rule, "+") == 0) { temp_int += rule_number; } if(linstr(rule, "-") == 0) { temp_int -= rule_number; } if(linstr(rule, "*") == 0) { temp_int *= rule_number; } if(linstr(rule, "/") == 0) { temp_int /= rule_number; } if(linstr(rule, "#") == 0) { temp_int += 0; } temp_conv += temp_int; } return temp_conv; } std::string reverse_parser_str(char const *rule_name, int line, std::string temp_state) { std::string temp_conv, rule = fetchr(rule_name, line); int temp_int, state_len = temp_state.length(), rule_number = (int) rule[2] - 48; for(int i = 0; state_len>i; i+=1) { temp_int = temp_state[i]; if(linstr(rule, "+") == 0) { temp_int -= rule_number; } if(linstr(rule, "-") == 0) { temp_int += rule_number; } if(linstr(rule, "*") == 0) { temp_int /= rule_number; } if(linstr(rule, "/") == 0) { temp_int *= rule_number; } if(linstr(rule, "#") == 0) { temp_int += 0; } temp_conv += temp_int; } return temp_conv; } // MADE BY @hanilr //
34.475
88
0.573604
hanilr
d9b3f8c78faec9e298ccbd90b4008ac908dbd36a
13,758
cpp
C++
src/frameworks/wilhelm/src/ThreadPool.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/wilhelm/src/ThreadPool.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/wilhelm/src/ThreadPool.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2010 The Android Open Source Project * * 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. */ /* ThreadPool */ #include "sles_allinclusive.h" // Entry point for each worker thread static void *ThreadPool_start(void *context) { ThreadPool *tp = (ThreadPool *) context; assert(NULL != tp); for (;;) { Closure *pClosure = ThreadPool_remove(tp); // closure is NULL when thread pool is being destroyed if (NULL == pClosure) { break; } // make a copy of parameters, then free the parameters const Closure closure = *pClosure; free(pClosure); // extract parameters and call the right method depending on kind ClosureKind kind = closure.mKind; void *context1 = closure.mContext1; void *context2 = closure.mContext2; int parameter1 = closure.mParameter1; switch (kind) { case CLOSURE_KIND_PPI: { ClosureHandler_ppi handler_ppi = closure.mHandler.mHandler_ppi; assert(NULL != handler_ppi); (*handler_ppi)(context1, context2, parameter1); } break; case CLOSURE_KIND_PPII: { ClosureHandler_ppii handler_ppii = closure.mHandler.mHandler_ppii; assert(NULL != handler_ppii); int parameter2 = closure.mParameter2; (*handler_ppii)(context1, context2, parameter1, parameter2); } break; case CLOSURE_KIND_PIIPP: { ClosureHandler_piipp handler_piipp = closure.mHandler.mHandler_piipp; assert(NULL != handler_piipp); int parameter2 = closure.mParameter2; void *context3 = closure.mContext3; (*handler_piipp)(context1, parameter1, parameter2, context2, context3); } break; default: SL_LOGE("Unexpected callback kind %d", kind); assert(false); break; } } return NULL; } #define INITIALIZED_NONE 0 #define INITIALIZED_MUTEX 1 #define INITIALIZED_CONDNOTFULL 2 #define INITIALIZED_CONDNOTEMPTY 4 #define INITIALIZED_ALL 7 static void ThreadPool_deinit_internal(ThreadPool *tp, unsigned initialized, unsigned nThreads); // Initialize a ThreadPool // maxClosures defaults to CLOSURE_TYPICAL if 0 // maxThreads defaults to THREAD_TYPICAL if 0 SLresult ThreadPool_init(ThreadPool *tp, unsigned maxClosures, unsigned maxThreads) { assert(NULL != tp); memset(tp, 0, sizeof(ThreadPool)); tp->mShutdown = SL_BOOLEAN_FALSE; unsigned initialized = INITIALIZED_NONE; // which objects were successfully initialized unsigned nThreads = 0; // number of threads successfully created int err; SLresult result; // initialize mutex and condition variables err = pthread_mutex_init(&tp->mMutex, (const pthread_mutexattr_t *) NULL); result = err_to_result(err); if (SL_RESULT_SUCCESS != result) goto fail; initialized |= INITIALIZED_MUTEX; err = pthread_cond_init(&tp->mCondNotFull, (const pthread_condattr_t *) NULL); result = err_to_result(err); if (SL_RESULT_SUCCESS != result) goto fail; initialized |= INITIALIZED_CONDNOTFULL; err = pthread_cond_init(&tp->mCondNotEmpty, (const pthread_condattr_t *) NULL); result = err_to_result(err); if (SL_RESULT_SUCCESS != result) goto fail; initialized |= INITIALIZED_CONDNOTEMPTY; // use default values for parameters, if not specified explicitly tp->mWaitingNotFull = 0; tp->mWaitingNotEmpty = 0; if (0 == maxClosures) maxClosures = CLOSURE_TYPICAL; tp->mMaxClosures = maxClosures; if (0 == maxThreads) maxThreads = THREAD_TYPICAL; tp->mMaxThreads = maxThreads; // initialize circular buffer for closures if (CLOSURE_TYPICAL >= maxClosures) { tp->mClosureArray = tp->mClosureTypical; } else { tp->mClosureArray = (Closure **) malloc((maxClosures + 1) * sizeof(Closure *)); if (NULL == tp->mClosureArray) { result = SL_RESULT_RESOURCE_ERROR; goto fail; } } tp->mClosureFront = tp->mClosureArray; tp->mClosureRear = tp->mClosureArray; // initialize thread pool if (THREAD_TYPICAL >= maxThreads) { tp->mThreadArray = tp->mThreadTypical; } else { tp->mThreadArray = (pthread_t *) malloc(maxThreads * sizeof(pthread_t)); if (NULL == tp->mThreadArray) { result = SL_RESULT_RESOURCE_ERROR; goto fail; } } unsigned i; for (i = 0; i < maxThreads; ++i) { int err = pthread_create(&tp->mThreadArray[i], (const pthread_attr_t *) NULL, ThreadPool_start, tp); result = err_to_result(err); if (SL_RESULT_SUCCESS != result) goto fail; ++nThreads; } tp->mInitialized = initialized; // done return SL_RESULT_SUCCESS; // here on any kind of error fail: ThreadPool_deinit_internal(tp, initialized, nThreads); return result; } static void ThreadPool_deinit_internal(ThreadPool *tp, unsigned initialized, unsigned nThreads) { int ok; assert(NULL != tp); // Destroy all threads if (0 < nThreads) { assert(INITIALIZED_ALL == initialized); ok = pthread_mutex_lock(&tp->mMutex); assert(0 == ok); tp->mShutdown = SL_BOOLEAN_TRUE; ok = pthread_cond_broadcast(&tp->mCondNotEmpty); assert(0 == ok); ok = pthread_cond_broadcast(&tp->mCondNotFull); assert(0 == ok); ok = pthread_mutex_unlock(&tp->mMutex); assert(0 == ok); unsigned i; for (i = 0; i < nThreads; ++i) { ok = pthread_join(tp->mThreadArray[i], (void **) NULL); assert(ok == 0); } // Empty out the circular buffer of closures ok = pthread_mutex_lock(&tp->mMutex); assert(0 == ok); Closure **oldFront = tp->mClosureFront; while (oldFront != tp->mClosureRear) { Closure **newFront = oldFront; if (++newFront == &tp->mClosureArray[tp->mMaxClosures + 1]) newFront = tp->mClosureArray; Closure *pClosure = *oldFront; assert(NULL != pClosure); *oldFront = NULL; tp->mClosureFront = newFront; ok = pthread_mutex_unlock(&tp->mMutex); assert(0 == ok); free(pClosure); ok = pthread_mutex_lock(&tp->mMutex); assert(0 == ok); } ok = pthread_mutex_unlock(&tp->mMutex); assert(0 == ok); // Note that we can't be sure when mWaitingNotFull will drop to zero } // destroy the mutex and condition variables if (initialized & INITIALIZED_CONDNOTEMPTY) { ok = pthread_cond_destroy(&tp->mCondNotEmpty); assert(0 == ok); } if (initialized & INITIALIZED_CONDNOTFULL) { ok = pthread_cond_destroy(&tp->mCondNotFull); assert(0 == ok); } if (initialized & INITIALIZED_MUTEX) { ok = pthread_mutex_destroy(&tp->mMutex); assert(0 == ok); } tp->mInitialized = INITIALIZED_NONE; // release the closure circular buffer if (tp->mClosureTypical != tp->mClosureArray && NULL != tp->mClosureArray) { free(tp->mClosureArray); tp->mClosureArray = NULL; } // release the thread pool if (tp->mThreadTypical != tp->mThreadArray && NULL != tp->mThreadArray) { free(tp->mThreadArray); tp->mThreadArray = NULL; } } void ThreadPool_deinit(ThreadPool *tp) { ThreadPool_deinit_internal(tp, tp->mInitialized, tp->mMaxThreads); } // Enqueue a closure to be executed later by a worker thread. // Note that this raw interface requires an explicit "kind" and full parameter list. // There are convenience methods below that make this easier to use. SLresult ThreadPool_add(ThreadPool *tp, ClosureKind kind, ClosureHandler_generic handler, void *context1, void *context2, void *context3, int parameter1, int parameter2) { assert(NULL != tp); assert(NULL != handler); Closure *closure = (Closure *) malloc(sizeof(Closure)); if (NULL == closure) { return SL_RESULT_RESOURCE_ERROR; } closure->mKind = kind; switch (kind) { case CLOSURE_KIND_PPI: closure->mHandler.mHandler_ppi = (ClosureHandler_ppi)handler; break; case CLOSURE_KIND_PPII: closure->mHandler.mHandler_ppii = (ClosureHandler_ppii)handler; break; case CLOSURE_KIND_PIIPP: closure->mHandler.mHandler_piipp = (ClosureHandler_piipp)handler; break; default: SL_LOGE("ThreadPool_add() invalid closure kind %d", kind); assert(false); } closure->mContext1 = context1; closure->mContext2 = context2; closure->mContext3 = context3; closure->mParameter1 = parameter1; closure->mParameter2 = parameter2; int ok; ok = pthread_mutex_lock(&tp->mMutex); assert(0 == ok); // can't enqueue while thread pool shutting down if (tp->mShutdown) { ok = pthread_mutex_unlock(&tp->mMutex); assert(0 == ok); free(closure); return SL_RESULT_PRECONDITIONS_VIOLATED; } for (;;) { Closure **oldRear = tp->mClosureRear; Closure **newRear = oldRear; if (++newRear == &tp->mClosureArray[tp->mMaxClosures + 1]) newRear = tp->mClosureArray; // if closure circular buffer is full, then wait for it to become non-full if (newRear == tp->mClosureFront) { ++tp->mWaitingNotFull; ok = pthread_cond_wait(&tp->mCondNotFull, &tp->mMutex); assert(0 == ok); // can't enqueue while thread pool shutting down if (tp->mShutdown) { assert(0 < tp->mWaitingNotFull); --tp->mWaitingNotFull; ok = pthread_mutex_unlock(&tp->mMutex); assert(0 == ok); free(closure); return SL_RESULT_PRECONDITIONS_VIOLATED; } continue; } assert(NULL == *oldRear); *oldRear = closure; tp->mClosureRear = newRear; // if a worker thread was waiting to dequeue, then suggest that it try again if (0 < tp->mWaitingNotEmpty) { --tp->mWaitingNotEmpty; ok = pthread_cond_signal(&tp->mCondNotEmpty); assert(0 == ok); } break; } ok = pthread_mutex_unlock(&tp->mMutex); assert(0 == ok); return SL_RESULT_SUCCESS; } // Called by a worker thread when it is ready to accept the next closure to execute Closure *ThreadPool_remove(ThreadPool *tp) { Closure *pClosure; int ok; ok = pthread_mutex_lock(&tp->mMutex); assert(0 == ok); for (;;) { // fail if thread pool is shutting down if (tp->mShutdown) { pClosure = NULL; break; } Closure **oldFront = tp->mClosureFront; // if closure circular buffer is empty, then wait for it to become non-empty if (oldFront == tp->mClosureRear) { ++tp->mWaitingNotEmpty; ok = pthread_cond_wait(&tp->mCondNotEmpty, &tp->mMutex); assert(0 == ok); // try again continue; } // dequeue the closure at front of circular buffer Closure **newFront = oldFront; if (++newFront == &tp->mClosureArray[tp->mMaxClosures + 1]) { newFront = tp->mClosureArray; } pClosure = *oldFront; assert(NULL != pClosure); *oldFront = NULL; tp->mClosureFront = newFront; // if a client thread was waiting to enqueue, then suggest that it try again if (0 < tp->mWaitingNotFull) { --tp->mWaitingNotFull; ok = pthread_cond_signal(&tp->mCondNotFull); assert(0 == ok); } break; } ok = pthread_mutex_unlock(&tp->mMutex); assert(0 == ok); return pClosure; } // Convenience methods for applications SLresult ThreadPool_add_ppi(ThreadPool *tp, ClosureHandler_ppi handler, void *context1, void *context2, int parameter1) { // function pointers are the same size so this is a safe cast return ThreadPool_add(tp, CLOSURE_KIND_PPI, (ClosureHandler_generic) handler, context1, context2, NULL, parameter1, 0); } SLresult ThreadPool_add_ppii(ThreadPool *tp, ClosureHandler_ppii handler, void *context1, void *context2, int parameter1, int parameter2) { // function pointers are the same size so this is a safe cast return ThreadPool_add(tp, CLOSURE_KIND_PPII, (ClosureHandler_generic) handler, context1, context2, NULL, parameter1, parameter2); } SLresult ThreadPool_add_piipp(ThreadPool *tp, ClosureHandler_piipp handler, void *cntxt1, int param1, int param2, void *cntxt2, void *cntxt3) { // function pointers are the same size so this is a safe cast return ThreadPool_add(tp, CLOSURE_KIND_PIIPP, (ClosureHandler_generic) handler, cntxt1, cntxt2, cntxt3, param1, param2); }
34.918782
96
0.619567
dAck2cC2
d9b6b0ce1b6f9e664e1e8f739cd8375097c6b43c
4,102
cpp
C++
projects/Test_ComputeShader/src/main.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
11
2016-08-30T12:01:35.000Z
2021-12-29T15:34:03.000Z
projects/Test_ComputeShader/src/main.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
9
2016-05-19T03:14:22.000Z
2021-01-17T05:45:52.000Z
projects/Test_ComputeShader/src/main.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
null
null
null
#include "pathos/core_minimal.h" #include "pathos/shader/shader.h" using namespace pathos; #include <stdio.h> void initComputeShader(); int main(int argc, char** argv) { EngineConfig config; config.windowWidth = 800; config.windowHeight = 600; config.rendererType = ERendererType::Deferred; config.title = "Test: Compute Shader"; Engine::init(argc, argv, config); initComputeShader(); gEngine->start(); return 0; } void initComputeShader() { // benchmark GLint workGroupSizeX, workGroupSizeY, workGroupSizeZ; glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 0, &workGroupSizeX); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 1, &workGroupSizeY); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 2, &workGroupSizeZ); GLint maxInvocation; glGetIntegerv(GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS, &maxInvocation); GLint sharedVariableLimit; glGetIntegerv(GL_MAX_COMPUTE_SHARED_MEMORY_SIZE, &sharedVariableLimit); //void glBindImageTexture(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); //glBindImageTexture(0, tex_input, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA32F) //glBindImageTexture(1, tex_output, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F) LOG(LogInfo, "===== Compute Shader Capabilities ====="); LOG(LogInfo, "max work group size: (%d, %d, %d)", workGroupSizeX, workGroupSizeY, workGroupSizeZ); LOG(LogInfo, "max work group invocations: %d", maxInvocation); LOG(LogInfo, "max shared memory (kb): %d", sharedVariableLimit); LOG(LogInfo, "======================================="); /* backup string cshader = R"( #version 430 core layout (local_size_x = 32, local_size_y = 32) in; //layout (binding = 0, rgba32f) uniform image2D img_in; //layout (binding = 1) uniform image2D img_out; void main() { //ivec2 p = ivec2(gl_GlobalInvocationID.xy); //vec4 texel = imageLoad(img_in, p); //texel = vec4(1.0) - texel; //imageStore(img_out, p, texel); } )"; */ // test compute shader std::string cshader = R"( #version 430 core layout (local_size_x = 128) in; layout (binding = 0) coherent buffer block1 { uint input_data[gl_WorkGroupSize.x]; }; layout (binding = 1) coherent buffer block2 { uint output_data[gl_WorkGroupSize.x]; }; shared uint shared_data[gl_WorkGroupSize.x * 2]; void main() { uint id = gl_LocalInvocationID.x; uint rd_id, wr_id, mask; const uint steps = uint(log2(gl_WorkGroupSize.x)) + 1; uint step = 0; shared_data[id * 2] = input_data[id * 2]; shared_data[id * 2 + 1] = input_data[id * 2 + 1]; barrier(); memoryBarrierShared(); for(step = 0; step < steps ; step++){ mask = (1 << step) - 1; rd_id = ((id >> step) << (step + 1)) + mask; wr_id = rd_id + 1 + (id & mask); shared_data[wr_id] += shared_data[rd_id]; barrier(); memoryBarrierShared(); } output_data[id * 2] = shared_data[id * 2]; output_data[id * 2 + 1] = shared_data[id * 2 + 1]; } )"; GLuint computeProgram = pathos::createComputeProgram(cshader, "CS_Test"); CHECK(computeProgram); // test data std::vector<GLuint> subsum_data(128, 1); GLuint buf_in; glGenBuffers(1, &buf_in); glBindBuffer(GL_SHADER_STORAGE_BUFFER, buf_in); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(GLuint) * subsum_data.size(), &subsum_data[0], GL_DYNAMIC_COPY); GLuint buf_out; glGenBuffers(1, &buf_out); glBindBuffer(GL_SHADER_STORAGE_BUFFER, buf_out); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(GLuint) * subsum_data.size(), NULL, GL_DYNAMIC_COPY); // run subsum shader glUseProgram(computeProgram); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, buf_in); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, buf_out); glDispatchCompute(128, 1, 1); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0); // validation glBindBuffer(GL_SHADER_STORAGE_BUFFER, buf_out); GLuint* subsum_result = reinterpret_cast<GLuint*>(glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY)); for (int i = 0; i < 128; ++i) { //assert(subsum_result[i] == i + 1); printf("%d ", subsum_result[i]); } puts(""); glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); }
29.092199
131
0.720868
codeonwort
d9b7acec85a4d822bc3dfb7218676ea89f7a9bfa
1,605
cpp
C++
src/Qt5Network/QSslKey.cpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
128
2015-01-07T19:47:09.000Z
2022-01-22T19:42:14.000Z
src/Qt5Network/QSslKey.cpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
null
null
null
src/Qt5Network/QSslKey.cpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
24
2015-01-07T19:47:10.000Z
2022-01-25T17:42:37.000Z
#include "QSslKey.hpp" #include "../convert/callable.hpp" #include "../thread.hpp" #include <QSslKey> #include "../Qt5Core/QByteArray.hpp" #include "../Qt5Core/Qt.hpp" #include "QSsl.hpp" int QSslKey_toDer(lua_State* const state) { return 0; } int QSslKey_toPem(lua_State* const state) { return 0; } void lua::QSslKey_metatable(lua_State* const state, const int pos) { lua::index mt(state, pos); mt["algorithm"] = &QSslKey::algorithm; mt["clear"] = &QSslKey::clear; mt["handle"] = &QSslKey::handle; mt["isNull"] = &QSslKey::isNull; mt["length"] = &QSslKey::length; mt["swap"] = &QSslKey::swap; mt["toDer"] = QSslKey_toDer; mt["toPem"] = QSslKey_toPem; mt["type"] = &QSslKey::type; } int QSslKey_new(lua_State* const state) { // QSslKey() // QSslKey(const QByteArray & encoded, QSsl::KeyAlgorithm algorithm, QSsl::EncodingFormat encoding = QSsl::Pem, QSsl::KeyType type = QSsl::PrivateKey, const QByteArray & passPhrase = QByteArray()) // QSslKey(QIODevice * device, QSsl::KeyAlgorithm algorithm, QSsl::EncodingFormat encoding = QSsl::Pem, QSsl::KeyType type = QSsl::PrivateKey, const QByteArray & passPhrase = QByteArray()) // QSslKey(Qt::HANDLE handle, QSsl::KeyType type = QSsl::PrivateKey) // QSslKey(const QSslKey & other) lua::make<QSslKey>(state); // TODO Set up object-specific methods return 1; } int luaopen_Qt5Network_QSslKey(lua_State* const state) { lua::thread env(state); env["QSslKey"] = lua::value::table; env["QSslKey"]["new"] = QSslKey_new; auto t = env["QSslKey"]; return 0; }
28.157895
200
0.666667
dafrito
d9b881e155db767076c9396697b46290c9f2ff5b
291
cpp
C++
arduino-libs/Pacman/src/IGameState.cpp
taylorsmithatnominet/BSidesCBR-2021-Badge
df3f13d780d6fb1b6d03d08e9bdd72f507f69aa6
[ "MIT" ]
null
null
null
arduino-libs/Pacman/src/IGameState.cpp
taylorsmithatnominet/BSidesCBR-2021-Badge
df3f13d780d6fb1b6d03d08e9bdd72f507f69aa6
[ "MIT" ]
null
null
null
arduino-libs/Pacman/src/IGameState.cpp
taylorsmithatnominet/BSidesCBR-2021-Badge
df3f13d780d6fb1b6d03d08e9bdd72f507f69aa6
[ "MIT" ]
null
null
null
#include "IGameState.h" #include "ServiceLocator.h" #include "DrawManager.h" namespace pacman { IGameState::IGameState(GameStateData * p_data) : m_datawPtr(p_data) { m_drawManagerwPtr = ServiceLocator<DrawManager>::GetService(); } IGameState::~IGameState() { } }; // namespace pacman
15.315789
63
0.742268
taylorsmithatnominet
d9b9c31e843efbbd08c65d935240a4df46964f82
2,873
cpp
C++
Game/Client/CEGUIFalagardEx/FalImageListProperties.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/CEGUIFalagardEx/FalImageListProperties.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/CEGUIFalagardEx/FalImageListProperties.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "falagardimagelistitem.h" #include "FalImageListProperties.h" #include "CEGUIPropertyHelper.h" #include <stdio.h> namespace CEGUI { namespace FalagardImageListBoxProperties { ////////////////////////////////////////////////////////////////////////////////////// String ImageNormal::get(const PropertyReceiver* receiver) const { return "";//PropertyHelper::imageToString(static_cast<const FalagardImageListBox*>(receiver)->setNormalImage()); } void ImageNormal::set(PropertyReceiver* receiver, const String& value) { static_cast<FalagardImageListBox*>(receiver)->setNormalImage(PropertyHelper::stringToImage(value)); } ////////////////////////////////////////////////////////////////////////////////////// String ImageHorver::get(const PropertyReceiver* receiver) const { return "";//PropertyHelper::boolToString(static_cast<const FalagardImageListBox*>(receiver)->setHorverImage()); } void ImageHorver::set(PropertyReceiver* receiver, const String& value) { static_cast<FalagardImageListBox*>(receiver)->setHorverImage(PropertyHelper::stringToImage(value)); } ////////////////////////////////////////////////////////////////////////////////////// String ImageChecked::get(const PropertyReceiver* receiver) const { return "";//PropertyHelper::boolToString(static_cast<const FalagardImageListBox*>(receiver)->isEmpty()); } void ImageChecked::set(PropertyReceiver* receiver, const String& value) { static_cast<FalagardImageListBox*>(receiver)->setCheckedImage(PropertyHelper::stringToImage(value)); } ////////////////////////////////////////////////////////////////////////////////////// String ImageDisable::get(const PropertyReceiver* receiver) const { return "";//PropertyHelper::boolToString(static_cast<const FalagardImageListBox*>(receiver)->isEmpty()); } void ImageDisable::set(PropertyReceiver* receiver, const String& value) { static_cast<FalagardImageListBox*>(receiver)->setDisabledImage(PropertyHelper::stringToImage(value)); } //////////////////////////////////////////////////////////////////////////////////////// String AddItem::get(const PropertyReceiver* receiver) const { return ""; } void AddItem::set(PropertyReceiver* receiver, const String& value) { char text[128]; int nID = 0; sscanf(value.c_str(), "id=%d text=%s", &nID, text ); FalagardImageListBoxItem* pItem = new FalagardImageListBoxItem( text, nID ); FalagardImageListBox *pParent = static_cast<FalagardImageListBox*>(receiver); if( pItem && pParent ) { pItem->SetNormalImage( (Image*)pParent->getNormalImage() ); pItem->SetHorverImage( (Image*)pParent->getHorverImage() ); pItem->SetCheckedImage( (Image*)pParent->getCheckedImage() ); pItem->SetDisableImage( (Image*)pParent->getDisabledImage() ); pParent->addItem( pItem ); } } } }
37.311688
115
0.626523
hackerlank
d9bb54e82f921ac2851cf90c1629d9e1fcdb21e6
5,147
cpp
C++
src/RenderFarmUI/RF_TerraTool.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
71
2015-12-15T19:32:27.000Z
2022-02-25T04:46:01.000Z
src/RenderFarmUI/RF_TerraTool.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
19
2016-07-09T19:08:15.000Z
2021-07-29T10:30:20.000Z
src/RenderFarmUI/RF_TerraTool.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
42
2015-12-14T19:13:02.000Z
2022-03-01T15:15:03.000Z
/* * Copyright (c) 2004, Laminar Research. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "RF_TerraTool.h" #include "RF_MapZoomer.h" #include "PCSBSocket.h" #include "TerraServer.h" #include "GUI_GraphState.h" #if APL #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif class AsyncImage; inline long long hash_xy(int x, int y) { return ((long long) x << 32) + (long long) y; } RF_TerraTool::RF_TerraTool(RF_MapZoomer * inZoomer) : RF_MapTool(inZoomer) { static bool first_time = true; if (first_time) PCSBSocket::StartupNetworking(true); first_time = false; mPool = new AsyncConnectionPool(4,5); mLocator = new AsyncImageLocator(mPool); mHas = 0; mRes = 4; mData = "1"; } RF_TerraTool::~RF_TerraTool() { for (map<long long, AsyncImage *>::iterator i = mImages.begin(); i != mImages.end(); ++i) delete i->second; delete mLocator; } void RF_TerraTool::DrawFeedbackUnderlay( GUI_GraphState * inState, bool inCurrent) { if (!inCurrent && !mHas) return; double s, n, e, w; GetZoomer()->GetMapVisibleBounds(w, s, e, n); string status; if (mLocator->GetLocation(ResString(), mData.c_str(), w, s, e, n, mX1, mX2, mY1, mY2, mDomain, status)) { mHas = 1; for (int x = mX1; x < mX2; ++x) for (int y = mY1; y < mY2; ++y) { long long h = hash_xy(x,y); if (mImages.count(h) == 0) { mImages[h] = new AsyncImage(mPool, ResString(), mData.c_str(), mDomain, x, y); } AsyncImage * i = mImages[h]; if (!i->HasErr()) { ImageInfo * bits = i->GetImage(); if (bits) { double coords[4][2]; if (i->GetCoords(coords)) { for (int n = 0; n < 4; ++n) { coords[n][0] = GetZoomer()->LatToYPixel(coords[n][0]); coords[n][1] = GetZoomer()->LonToXPixel(coords[n][1]); } i->Draw(coords,inState); } } } } } else mHas = 0; } void RF_TerraTool::DrawFeedbackOverlay( GUI_GraphState * inState, bool inCurrent) { } bool RF_TerraTool::HandleClick( XPLMMouseStatus inStatus, int inX, int inY, int inButton, GUI_KeyFlags inModifiers) { return false; } int RF_TerraTool::GetNumProperties(void) { return 1; } void RF_TerraTool::GetNthPropertyName(int n, string& s) { s = "Res (m):"; } double RF_TerraTool::GetNthPropertyValue(int) { return mRes; } void RF_TerraTool::SetNthPropertyValue(int, double v) { mRes = v; if (mRes < 1) mRes = 1; NthButtonPressed(1); } int RF_TerraTool::GetNumButtons(void) { return 5; } void RF_TerraTool::GetNthButtonName(int n, string& s) { switch(n) { case 0: s = "Retry"; break; case 1: s = "Clear"; break; case 2: s = "Photo"; break; case 3: s = "Ortho"; break; case 4: s = "Urban"; break; } } void RF_TerraTool::NthButtonPressed(int n) { set<long long> nuke; switch(n) { case 0: { for (map<long long, AsyncImage *>::iterator i = mImages.begin(); i != mImages.end(); ++i) if (i->second->HasErr()) { delete i->second; nuke.insert(i->first); } for (set<long long>::iterator j = nuke.begin(); j != nuke.end(); ++j) mImages.erase(*j); } break; case 1: case 2: case 3: case 4: { mLocator->Purge(); mHas = 0; for (map<long long, AsyncImage *>::iterator i = mImages.begin(); i != mImages.end(); ++i) delete i->second; mImages.clear(); switch(n) { case 2: mData = "1"; break; case 3: mData = "2"; break; case 4: mData = "4"; break; } } break; } } char * RF_TerraTool::GetStatusText(int x, int y) { int total = 0, done = 0, pending = 0, bad = 0; for (map<long long, AsyncImage *>::iterator i = mImages.begin(); i != mImages.end(); ++i) { if (i->second->HasErr()) ++bad; else if (i->second->IsDone()) ++done; else ++pending; ++total; } static char buf[1024]; if (mHas) sprintf(buf, "Domain=%d, X=%d-%d,Y=%d-%d Done=%d Pending=%d Bad=%d Total=%d", mDomain, mX1,mX2,mY1,mY2, done, pending, bad, total); else sprintf(buf, "No area established."); return buf; } const char * RF_TerraTool::ResString(void) { static char resbuf[256]; sprintf(resbuf, "%dm", mRes); return resbuf; }
23.395455
133
0.642704
rromanchuk
d9bd35e18e8d8d40091d67985382764a270e1a65
1,359
cpp
C++
src/pacman/EventRunner.cpp
197708156EQUJ5/pac-man
30501ac43b9bcdd94b3cbb848c597882fc268492
[ "MIT" ]
null
null
null
src/pacman/EventRunner.cpp
197708156EQUJ5/pac-man
30501ac43b9bcdd94b3cbb848c597882fc268492
[ "MIT" ]
null
null
null
src/pacman/EventRunner.cpp
197708156EQUJ5/pac-man
30501ac43b9bcdd94b3cbb848c597882fc268492
[ "MIT" ]
null
null
null
#include "pacman/EventRunner.hpp" namespace pacman { EventRunner::~EventRunner() { board->release(); release(); } bool EventRunner::init() { board = std::make_unique<Board>(); if (board->init()) { renderer = board->getRenderer(); return true; } return true; } void EventRunner::gameLoop() { std::cout << "Entering game loop" << std::endl; bool quit = false; SDL_Event event; while (!quit) { SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); SDL_RenderClear(renderer); //Handle events on queue while(SDL_PollEvent(&event) != 0) { switch(event.type) { /* Keyboard event */ /* Pass the event data onto PrintKeyInfo() */ case SDL_KEYDOWN: case SDL_KEYUP: //PrintKeyInfo( &event.key ); break; /* SDL_QUIT event (window release) */ case SDL_QUIT: quit = 1; break; default: break; } board->paintComponents(); } //Update screen SDL_RenderPresent(renderer); } } void EventRunner::release() { renderer = NULL; } } // namespace pacman
19.985294
65
0.486387
197708156EQUJ5
d9be3f062da62c24c3c0cfeb3347895b14b38587
436
hpp
C++
library/ATF/$012304FDD17B496AFBE8BAC81FBABAAE.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/$012304FDD17B496AFBE8BAC81FBABAAE.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/$012304FDD17B496AFBE8BAC81FBABAAE.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <tagBinaryParam.hpp> START_ATF_NAMESPACE union $012304FDD17B496AFBE8BAC81FBABAAE { char *AnsiString; wchar_t *UnicodeString; int LVal; __int16 SVal; unsigned __int64 PVal; tagBinaryParam BVal; }; END_ATF_NAMESPACE
21.8
108
0.690367
lemkova
d9c110c62db0fcb3bab06f65812a06e6fc48c527
1,646
cpp
C++
plugins/robots/generators/generatorBase/src/converters/switchConditionsMerger.cpp
anastasia143/qreal
9bd224b41e569c9c50ab88848a5746a010c65ad7
[ "Apache-2.0" ]
6
2017-07-03T13:55:35.000Z
2018-11-28T03:39:51.000Z
plugins/robots/generators/generatorBase/src/converters/switchConditionsMerger.cpp
anastasia143/qreal
9bd224b41e569c9c50ab88848a5746a010c65ad7
[ "Apache-2.0" ]
27
2017-06-29T09:36:37.000Z
2017-11-25T14:50:04.000Z
plugins/robots/generators/generatorBase/src/converters/switchConditionsMerger.cpp
anastasia143/qreal
9bd224b41e569c9c50ab88848a5746a010c65ad7
[ "Apache-2.0" ]
null
null
null
/* Copyright 2007-2015 QReal Research Group * * 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 "switchConditionsMerger.h" using namespace generatorBase::converters; SwitchConditionsMerger::SwitchConditionsMerger(const QStringList &pathsToTemplates , const ConverterInterface * const systemVariablesConverter , const QStringList &values) : TemplateParametrizedConverter(pathsToTemplates) , mSystemVariablesConverter(systemVariablesConverter) , mValues(values) { } SwitchConditionsMerger::~SwitchConditionsMerger() { delete mSystemVariablesConverter; } QString SwitchConditionsMerger::convert(const QString &expression) const { const QString convertedExpression = mSystemVariablesConverter->convert(expression); const QString oneCondition = readTemplate("switch/oneCase.t"); const QString conditionsSeparator = readTemplate("switch/conditionsSeparator.t"); QStringList conditions; for (const QString &value : mValues) { QString condition = oneCondition; conditions << condition.replace("@@EXPRESSION@@", convertedExpression).replace("@@VALUE@@", value); } return conditions.join(conditionsSeparator); }
35.021277
101
0.784933
anastasia143
d9c45f6eb15f5af50e85aa681f77aa59a475ace3
1,466
cpp
C++
source-code/Classes/LateBinding/stats_main.cpp
gjbex/Scientific-C-
d7aeb88743ffa2a43b1df1569a9200b2447f401c
[ "CC-BY-4.0" ]
115
2015-03-23T13:34:42.000Z
2022-03-21T00:27:21.000Z
source-code/Classes/LateBinding/stats_main.cpp
gjbex/Scientific-C-
d7aeb88743ffa2a43b1df1569a9200b2447f401c
[ "CC-BY-4.0" ]
56
2015-02-25T15:04:26.000Z
2022-01-03T07:42:48.000Z
source-code/Classes/LateBinding/stats_main.cpp
gjbex/Scientific-C-
d7aeb88743ffa2a43b1df1569a9200b2447f401c
[ "CC-BY-4.0" ]
59
2015-11-26T11:44:51.000Z
2022-03-21T00:27:22.000Z
#include <iostream> #include <memory> #include "stats.h" #include "median_stats.h" int main(int argc, char* argv[]) { std::unique_ptr<Stats> stats {nullptr}; if (argc == 1) { stats = std::make_unique<Stats>(); } else if (argc == 2) { std::string arg(argv[1]); if (arg != "-m") { std::cerr << "### error: unknown command line option '" << arg << "'" << std::endl; std::exit(1); } stats = std::make_unique<MedianStats>(); } else { std::cerr << "### usage: stats.exe [-m]" << std::endl; std::exit(1); } std::cerr << "before parse: " << *stats << std::endl; double value; while (std::cin >> value) stats->add(value); std::cerr << "after parse: " << *stats << std::endl; try { std::cout << "mean: " << stats->mean() << std::endl; std::cout << "stddev: " << stats->stddev() << std::endl; std::cout << "min: " << stats->min() << std::endl; std::cout << "max: " << stats->max() << std::endl; { MedianStats* mstats = dynamic_cast<MedianStats*>(stats.get()); if (mstats) std::cout << "median: " << mstats->median() << std::endl; } std::cout << "n: " << stats->nr_values() << std::endl; } catch (std::out_of_range& e) { std::cerr << "### error: " << e.what() << std::endl; std::exit(2); } return 0; }
32.577778
74
0.469986
gjbex
d9c480255af42617191d0d4230211b898f3941f4
1,692
cpp
C++
Framework/Platforms/Source/DCM/NaoRobot/SoundControl.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
Framework/Platforms/Source/DCM/NaoRobot/SoundControl.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
Framework/Platforms/Source/DCM/NaoRobot/SoundControl.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#include "SoundControl.h" #include <Tools/ThreadUtil.h> #include <iostream> #include <cstdlib> using namespace naoth; using namespace std; SoundControl::SoundControl() : stopping(false), media_path("Media/") { playThread = std::thread([this] {this->play();}); ThreadUtil::setPriority(playThread, ThreadUtil::Priority::lowest); ThreadUtil::setName(playThread, "SoundControl"); } SoundControl::~SoundControl() { stopping = true; std::cout << "[SoundControl] stop wait" << std::endl; // NOTE: wake up the thread in case it was waiting for the new data new_data_avaliable.notify_one(); // wait for the thread to stop if necessary if(playThread.joinable()) { playThread.join(); } std::cout << "[SoundControl] stop done" << std::endl; } void SoundControl::setSoundData(const SoundPlayData& theSoundData) { // try to get the lock on the data // if we cannot get the lock, the the thread is still working std::unique_lock<std::mutex> lock(dataMutex, std::try_to_lock); if(theSoundData.soundFile == "" || !lock.owns_lock()) { return; } filename = media_path + theSoundData.soundFile; // release the data lock and notify the waiting thread lock.unlock(); new_data_avaliable.notify_one(); } void SoundControl::play() { while(!stopping) { //std::cout << "[SoundControl] wait for new data to play" << std::endl; std::unique_lock<std::mutex> lock(dataMutex); new_data_avaliable.wait(lock); std::cout << "[SoundControl] play " << filename << std::endl; std::string cmd = "/usr/bin/paplay " + filename; std::system(cmd.c_str()); filename = ""; // NOTE: should we unlock here? // lock.unlock(); } }
24.882353
75
0.673759
tarsoly
d9cf293f3eab99383b4ccc21d94936107c4d39fe
582
cpp
C++
_includes/leet638/leet638_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
_includes/leet638/leet638_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
8
2019-12-19T04:46:05.000Z
2022-02-26T03:45:22.000Z
_includes/leet638/leet638_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
class Solution { public: int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) { int res = 0; int n = needs.size(); for (int i = 0; i < n; i++) { res += price[i] * needs[i]; } for (int i = 0; i < special.size(); i++) { bool ok = true; for (int j = 0; j < n; j++) { if (needs[j] < special[i][j]) ok = false; needs[j] -= special[i][j]; } if (ok) { res = min(res, special[i][n] + shoppingOffers(price, special, needs)); } for (int j = 0; j < n; j++) needs[j] += special[i][j]; } return res; } };
26.454545
94
0.517182
mingdaz
d9cfd8789dbfee41741e5eddd84bcf31bc4e77a6
3,023
cpp
C++
src/transactions/test/test_helper/SetOptionsTestHelper.cpp
RomanTkachenkoDistr/SwarmCore
db0544758e7bb3c879778cfdd6946b9a72ba23ab
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/transactions/test/test_helper/SetOptionsTestHelper.cpp
RomanTkachenkoDistr/SwarmCore
db0544758e7bb3c879778cfdd6946b9a72ba23ab
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/transactions/test/test_helper/SetOptionsTestHelper.cpp
RomanTkachenkoDistr/SwarmCore
db0544758e7bb3c879778cfdd6946b9a72ba23ab
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
#include "SetOptionsTestHelper.h" #include "ledger/ReviewableRequestHelper.h" #include "transactions/SetOptionsOpFrame.h" #include "test/test_marshaler.h" namespace stellar { namespace txtest { SetOptionsTestHelper::SetOptionsTestHelper(TestManager::pointer testManager) : TxHelper(testManager) { } TransactionFramePtr SetOptionsTestHelper::createSetOptionsTx(Account &source, ThresholdSetter *thresholdSetter, Signer *signer, TrustData *trustData, LimitsUpdateRequestData *limitsUpdateRequestData) { Operation op; op.body.type(OperationType::SET_OPTIONS); SetOptionsOp& setOptionsOp = op.body.setOptionsOp(); if (thresholdSetter) { if (thresholdSetter->masterWeight) setOptionsOp.masterWeight.activate() = *thresholdSetter->masterWeight; if (thresholdSetter->lowThreshold) setOptionsOp.lowThreshold.activate() = *thresholdSetter->lowThreshold; if (thresholdSetter->medThreshold) setOptionsOp.medThreshold.activate() = *thresholdSetter->medThreshold; if (thresholdSetter->highThreshold) setOptionsOp.highThreshold.activate() = *thresholdSetter->highThreshold; } if (signer) setOptionsOp.signer.activate() = *signer; if (trustData) setOptionsOp.trustData.activate() = *trustData; if (limitsUpdateRequestData) setOptionsOp.limitsUpdateRequestData.activate() = *limitsUpdateRequestData; return TxHelper::txFromOperation(source, op, nullptr); } void SetOptionsTestHelper::applySetOptionsTx(Account &source, ThresholdSetter *thresholdSetter, Signer *signer, TrustData *trustData, LimitsUpdateRequestData *limitsUpdateRequestData, SetOptionsResultCode expectedResult, SecretKey *txSigner) { Database& db = mTestManager->getDB(); TransactionFramePtr txFrame; txFrame = createSetOptionsTx(source, thresholdSetter, signer, trustData, limitsUpdateRequestData); if (txSigner) { txFrame->getEnvelope().signatures.clear(); txFrame->addSignature(*txSigner); } mTestManager->applyCheck(txFrame); if(limitsUpdateRequestData) { auto txResult = txFrame->getResult(); auto opResult = txResult.result.results()[0]; SetOptionsResult setOptionsResult = opResult.tr().setOptionsResult(); auto limitsUpdateRequestID = setOptionsResult.success().limitsUpdateRequestID; auto request = ReviewableRequestHelper::Instance()->loadRequest(limitsUpdateRequestID, db); REQUIRE(!!request); } REQUIRE(SetOptionsOpFrame::getInnerCode( txFrame->getResult().result.results()[0]) == expectedResult); } } }
37.320988
116
0.640754
RomanTkachenkoDistr
d9d1072c6cab88f061fe52382162364f6575baa1
849
cpp
C++
src/libais/ais10.cpp
SkyTruth/libais
b9e10156d99994d18ce11c43ec04e7b0875db135
[ "Apache-2.0" ]
null
null
null
src/libais/ais10.cpp
SkyTruth/libais
b9e10156d99994d18ce11c43ec04e7b0875db135
[ "Apache-2.0" ]
null
null
null
src/libais/ais10.cpp
SkyTruth/libais
b9e10156d99994d18ce11c43ec04e7b0875db135
[ "Apache-2.0" ]
null
null
null
// : UTC and date query #include "ais.h" namespace libais { Ais10::Ais10(const char *nmea_payload, const size_t pad) : AisMsg(nmea_payload, pad), spare(0), dest_mmsi(0), spare2(0) { assert(message_id == 10); if (pad != 0 || num_chars != 12) { status = AIS_ERR_BAD_BIT_COUNT; return; } AisBitset bs; const AIS_STATUS r = bs.ParseNmeaPayload(nmea_payload, pad); if (r != AIS_OK) { status = r; return; } bs.SeekTo(38); spare = bs.ToUnsignedInt(38, 2); dest_mmsi = bs.ToUnsignedInt(40, 30); spare2 = bs.ToUnsignedInt(70, 2); assert(bs.GetRemaining() == 0); status = AIS_OK; } ostream& operator<< (ostream &o, const Ais10 &msg) { return o << msg.message_id << ": " << msg.mmsi << " dest=" << msg.dest_mmsi << " " << msg.spare << " " << msg.spare2; } } // namespace libais
20.707317
68
0.599529
SkyTruth
d9d2b75dc44d2ea053bfdb7994f68aaefe1503a4
5,316
cpp
C++
test/src/test_csv_line_reader.cpp
mguid65/csvio
933c11e71d3f796932808da879c89524688b3895
[ "MIT" ]
null
null
null
test/src/test_csv_line_reader.cpp
mguid65/csvio
933c11e71d3f796932808da879c89524688b3895
[ "MIT" ]
3
2019-07-16T23:53:29.000Z
2019-09-20T03:28:13.000Z
test/src/test_csv_line_reader.cpp
mguid65/csvio
933c11e71d3f796932808da879c89524688b3895
[ "MIT" ]
3
2019-07-10T20:09:28.000Z
2019-07-16T21:00:46.000Z
/* * MIT License * * Copyright (c) 2019 Matthew Guidry * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <sstream> #include "csv_io.hpp" #include "gtest/gtest.h" namespace { TEST(CSVLineReaderTest, ConstructorFromIStream) { std::istringstream data(""); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ(0u, csv_lr.lcount()); EXPECT_EQ(true, csv_lr.good()); EXPECT_EQ("", csv_lr.readline()); } TEST(CSVLineReaderTest, ReadOneBlankLine) { std::istringstream data(""); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ("", csv_lr.readline()); EXPECT_EQ(1u, csv_lr.lcount()); EXPECT_EQ(false, csv_lr.good()); } TEST(CSVLineReaderTest, ReadOneSampleCSVLine) { std::istringstream data("1,1,1,1,1,1,1,1\n"); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ("1,1,1,1,1,1,1,1\n", csv_lr.readline()); EXPECT_EQ(1u, csv_lr.lcount()); EXPECT_EQ(false, csv_lr.good()); } TEST(CSVLineReaderTest, ReadOneSampleNoNewline) { std::istringstream data("1,1,1,1,1,1,1,1"); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ("1,1,1,1,1,1,1,1", csv_lr.readline()); EXPECT_EQ(1u, csv_lr.lcount()); EXPECT_EQ(false, csv_lr.good()); } TEST(CSVLineReaderTest, CheckGood) { std::istringstream data("1,1,1,1,1,1,1,1\n"); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ("1,1,1,1,1,1,1,1\n", csv_lr.readline()); EXPECT_EQ("", csv_lr.readline()); EXPECT_EQ(2u, csv_lr.lcount()); // not sure if I should let this be 1 or 2 EXPECT_EQ(false, csv_lr.good()); } TEST(CSVLineReaderTest, ReadTwoSampleCSVLines) { std::istringstream data( "1,1,1,1,1,1,1,1\n" "2,2,2,2,2,2,2,2\n"); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ("1,1,1,1,1,1,1,1\n", csv_lr.readline()); EXPECT_EQ("2,2,2,2,2,2,2,2\n", csv_lr.readline()); EXPECT_EQ(2u, csv_lr.lcount()); EXPECT_EQ(false, csv_lr.good()); } TEST(CSVLineReaderTest, ReadOneSampleCSVLineAllNewLines) { std::istringstream data("\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\"\n"); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ("\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\"\n", csv_lr.readline()); EXPECT_EQ(1u, csv_lr.lcount()); EXPECT_EQ(false, csv_lr.good()); } TEST(CSVLineReaderTest, ReadOneSampleLineHardParse) { std::istringstream data( "\"\"\"one\"\"\",\"tw\n" "o\",\"\"\"th,r\n" "ee\"\"\",\"\"\"fo\n" "u\"\"r\"\"\",5,6,7,8\n"); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ( "\"\"\"one\"\"\",\"tw\n" "o\",\"\"\"th,r\n" "ee\"\"\",\"\"\"fo\n" "u\"\"r\"\"\",5,6,7,8\n", csv_lr.readline()); EXPECT_EQ("", csv_lr.readline()); EXPECT_EQ(2u, csv_lr.lcount()); EXPECT_EQ(false, csv_lr.good()); } TEST(CSVLineReaderTest, ReadOnePrematureEOF) { std::istringstream data("1,1,1,\"1\n"); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ("", csv_lr.readline()); EXPECT_EQ(0u, csv_lr.lcount()); EXPECT_EQ(false, csv_lr.good()); } TEST(CSVLineReaderTest, ReadMultiMixed) { std::istringstream data( "\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\"\n" "1,1,1,1,1,1,1,1\n" "2,2,2,2,2,2,2,2\n" "\"\"\"one\"\"\",\"tw\n" "o\",\"\"\"th,r\n" "ee\"\"\",\"\"\"fo\n" "u\"\"r\"\"\",5,6,7,8\n"); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ("\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\",\"1\n\"\n", csv_lr.readline()); EXPECT_EQ("1,1,1,1,1,1,1,1\n", csv_lr.readline()); EXPECT_EQ("2,2,2,2,2,2,2,2\n", csv_lr.readline()); EXPECT_EQ( "\"\"\"one\"\"\",\"tw\n" "o\",\"\"\"th,r\n" "ee\"\"\",\"\"\"fo\n" "u\"\"r\"\"\",5,6,7,8\n", csv_lr.readline()); EXPECT_EQ("", csv_lr.readline()); EXPECT_EQ(5u, csv_lr.lcount()); EXPECT_EQ(false, csv_lr.good()); } TEST(CSVLineReaderTest, ReadTwoLinesCRLF) { std::istringstream data( "1,1,1,1,1,1,1,1\r\n" "2,2,2,2,2,2,2,2\r\n"); csvio::util::CSVLineReader csv_lr(data); EXPECT_EQ("1,1,1,1,1,1,1,1\r\n", csv_lr.readline()); EXPECT_EQ("2,2,2,2,2,2,2,2\r\n", csv_lr.readline()); EXPECT_EQ(2u, csv_lr.lcount()); EXPECT_EQ(false, csv_lr.good()); } } // namespace int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
30.906977
100
0.626223
mguid65
d9d68dc37e878c506047a12804f6c23a03ac6c95
4,319
cpp
C++
service/nametag/piles.cpp
zostay/Mysook
3611ddf0a116d18ebc58a3050f9fe35c2684c906
[ "Artistic-2.0" ]
3
2019-06-30T04:15:18.000Z
2019-12-19T17:32:07.000Z
service/nametag/piles.cpp
zostay/Mysook
3611ddf0a116d18ebc58a3050f9fe35c2684c906
[ "Artistic-2.0" ]
null
null
null
service/nametag/piles.cpp
zostay/Mysook
3611ddf0a116d18ebc58a3050f9fe35c2684c906
[ "Artistic-2.0" ]
null
null
null
#include <inttypes.h> #include "ops.h" #define PILES 6 #define UPDATE_PIXEL 1 uint32_t program[] = { OP_SUB, 1, OP_PUSH, 3, OP_READARG, OP_PUSH, 0, OP_EQ, OP_NOT, OP_PUSH, 2, OP_CMP, OP_PUSH, 0, OP_FOREGROUND, OP_SUB, 2, OP_PUSH, 3, OP_READARG, OP_PUSH, 1, OP_EQ, OP_NOT, OP_PUSH, 3, OP_CMP, OP_PUSH, 255, OP_FOREGROUND, OP_SUB, 3, OP_PUSH, 3, OP_READARG, OP_PUSH, 2, OP_EQ, OP_NOT, OP_PUSH, 4, OP_CMP, OP_PUSH, 16776960, OP_FOREGROUND, OP_SUB, 4, OP_PUSH, 3, OP_READARG, OP_PUSH, 3, OP_EQ, OP_NOT, OP_PUSH, 5, OP_CMP, OP_PUSH, 16711680, OP_FOREGROUND, OP_SUB, 5, OP_PUSH, 1, OP_READARG, OP_PUSH, 2, OP_READARG, OP_PIXEL, OP_RETURN, OP_SUB, 6, OP_PUSH, 0, OP_PUSH, 0, OP_PUSH, 0, OP_WIDTH, OP_HEIGHT, OP_MUL, OP_PUSH, 0, OP_SWAP, OP_ALLOC, OP_PUSH, 10, OP_BRIGHTNESS, OP_PUSH, 1, OP_URGENCY, OP_PUSH, 0, OP_FOREGROUND, OP_FILL, OP_TICK, OP_SUB, 7, OP_RAND, OP_WIDTH, OP_MOD, OP_PUSH, 0, OP_WRITE, OP_RAND, OP_HEIGHT, OP_MOD, OP_PUSH, 1, OP_WRITE, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_READ, OP_WIDTH, OP_MUL, OP_ADD, OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_ADD, OP_SWAP, OP_PUSH, 3, OP_ADD, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_READ, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_GOSUB, OP_POP, OP_POP, OP_POP, OP_PUSH, 0, OP_PUSH, 1, OP_WRITE, OP_SUB, 9, OP_PUSH, 1, OP_READ, OP_HEIGHT, OP_GE, OP_NOT, OP_PUSH, 11, OP_CMP, OP_PUSH, 10, OP_GOTO, OP_SUB, 11, OP_PUSH, 0, OP_PUSH, 0, OP_WRITE, OP_SUB, 12, OP_PUSH, 0, OP_READ, OP_WIDTH, OP_GE, OP_NOT, OP_PUSH, 14, OP_CMP, OP_PUSH, 13, OP_GOTO, OP_SUB, 14, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_READ, OP_WIDTH, OP_MUL, OP_ADD, OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 4, OP_GE, OP_NOT, OP_PUSH, 15, OP_CMP, OP_PUSH, 2, OP_READ, OP_PUSH, 0, OP_SWAP, OP_PUSH, 3, OP_ADD, OP_WRITE, OP_PUSH, 0, OP_READ, OP_PUSH, 0, OP_GT, OP_NOT, OP_PUSH, 16, OP_CMP, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_MIN, OP_PUSH, 1, OP_READ, OP_WIDTH, OP_MUL, OP_ADD, OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_ADD, OP_SWAP, OP_PUSH, 3, OP_ADD, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_READ, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_MIN, OP_PUSH, 1, OP_GOSUB, OP_POP, OP_POP, OP_POP, OP_SUB, 16, OP_PUSH, 1, OP_READ, OP_PUSH, 0, OP_GT, OP_NOT, OP_PUSH, 17, OP_CMP, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_READ, OP_PUSH, 1, OP_MIN, OP_WIDTH, OP_MUL, OP_ADD, OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_ADD, OP_SWAP, OP_PUSH, 3, OP_ADD, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_READ, OP_PUSH, 1, OP_MIN, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_GOSUB, OP_POP, OP_POP, OP_POP, OP_SUB, 17, OP_PUSH, 0, OP_READ, OP_WIDTH, OP_PUSH, 1, OP_MIN, OP_LT, OP_NOT, OP_PUSH, 18, OP_CMP, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_ADD, OP_PUSH, 1, OP_READ, OP_WIDTH, OP_MUL, OP_ADD, OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_ADD, OP_SWAP, OP_PUSH, 3, OP_ADD, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_READ, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_ADD, OP_PUSH, 1, OP_GOSUB, OP_POP, OP_POP, OP_POP, OP_SUB, 18, OP_PUSH, 1, OP_READ, OP_HEIGHT, OP_PUSH, 1, OP_MIN, OP_LT, OP_NOT, OP_PUSH, 19, OP_CMP, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_READ, OP_PUSH, 1, OP_ADD, OP_WIDTH, OP_MUL, OP_ADD, OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_ADD, OP_SWAP, OP_PUSH, 3, OP_ADD, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_READ, OP_PUSH, 1, OP_ADD, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_GOSUB, OP_POP, OP_POP, OP_POP, OP_SUB, 19, OP_SUB, 15, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_ADD, OP_PUSH, 0, OP_WRITE, OP_PUSH, 12, OP_GOTO, OP_SUB, 13, OP_PUSH, 1, OP_READ, OP_PUSH, 1, OP_ADD, OP_PUSH, 1, OP_WRITE, OP_PUSH, 9, OP_GOTO, OP_SUB, 10, OP_TICK, OP_PUSH, 7, OP_GOTO, OP_SUB, 8, OP_RETURN, OP_HALT, OP_HALT };
65.439394
78
0.686038
zostay
d9d8b47a3e9273e2c318a7487a4d9aff5c8d8dc6
301
cpp
C++
vehicle/Transprotobot/PlanningAndControlLayer.cpp
mnemonia/transprotobot
8fc85c0eb5f4cd587cd6ca8ada4593bb36cb27cd
[ "Apache-2.0" ]
null
null
null
vehicle/Transprotobot/PlanningAndControlLayer.cpp
mnemonia/transprotobot
8fc85c0eb5f4cd587cd6ca8ada4593bb36cb27cd
[ "Apache-2.0" ]
null
null
null
vehicle/Transprotobot/PlanningAndControlLayer.cpp
mnemonia/transprotobot
8fc85c0eb5f4cd587cd6ca8ada4593bb36cb27cd
[ "Apache-2.0" ]
null
null
null
#include "PlanningAndControlLayer.h" PlanningAndControlLayer::PlanningAndControlLayer(GlobalServicesLayer* gsl, VehicleInterfaceLayer* vil): sc(gsl, vil), tc(gsl, vil) { } void PlanningAndControlLayer::on() { Serial.println("PlanningAndControlLayer on"); this->sc.on(); this->tc.on(); }
21.5
103
0.737542
mnemonia
d9da38530ac9b7e28f6f2a4f4907aaedebe8ecae
6,299
cpp
C++
src/renderer-backend-egl.cpp
ceyusa/WPEBackend-fdo
e4c578f23359dba4d5abbd14b108f59e1b0701c1
[ "BSD-2-Clause" ]
16
2018-06-26T13:37:04.000Z
2022-03-11T14:08:22.000Z
src/renderer-backend-egl.cpp
ceyusa/WPEBackend-fdo
e4c578f23359dba4d5abbd14b108f59e1b0701c1
[ "BSD-2-Clause" ]
118
2018-03-07T11:01:45.000Z
2022-02-01T19:44:14.000Z
src/renderer-backend-egl.cpp
ceyusa/WPEBackend-fdo
e4c578f23359dba4d5abbd14b108f59e1b0701c1
[ "BSD-2-Clause" ]
16
2018-02-20T19:31:13.000Z
2021-02-23T21:10:57.000Z
/* * Copyright (C) 2017, 2018 Igalia S.L. * * 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 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Should be included early to force through the Wayland EGL platform #include <wayland-egl.h> #include <epoxy/egl.h> #include <wpe/wpe-egl.h> #include "egl-client.h" #include "egl-client-dmabuf-pool.h" #include "egl-client-wayland.h" #include "interfaces.h" #include "ws-client.h" namespace { class Backend final : public WS::BaseBackend { public: Backend(int hostFD) : WS::BaseBackend(hostFD) { switch (type()) { case WS::ClientImplementationType::Invalid: g_error("Backend: invalid valid client implementation"); break; case WS::ClientImplementationType::DmabufPool: m_impl = WS::EGLClient::BackendImpl::create<WS::EGLClient::BackendDmabufPool>(*this); break; case WS::ClientImplementationType::Wayland: m_impl = WS::EGLClient::BackendImpl::create<WS::EGLClient::BackendWayland>(*this); break; } } ~Backend() = default; using WS::BaseBackend::display; std::unique_ptr<WS::EGLClient::BackendImpl> m_impl; }; class Target final : public WS::BaseTarget, public WS::BaseTarget::Impl { public: Target(struct wpe_renderer_backend_egl_target* target, int hostFD) : WS::BaseTarget(hostFD, *this) , m_target(target) { } ~Target() { m_impl = nullptr; m_target = nullptr; } void initialize(Backend& backend, uint32_t width, uint32_t height) { WS::BaseTarget::initialize(backend); switch (backend.type()) { case WS::ClientImplementationType::Invalid: g_error("Target: invalid valid client implementation"); break; case WS::ClientImplementationType::DmabufPool: m_impl = WS::EGLClient::TargetImpl::create<WS::EGLClient::TargetDmabufPool>(*this, width, height); break; case WS::ClientImplementationType::Wayland: m_impl = WS::EGLClient::TargetImpl::create<WS::EGLClient::TargetWayland>(*this, width, height); break; } } using WS::BaseTarget::requestFrame; std::unique_ptr<WS::EGLClient::TargetImpl> m_impl; private: // WS::BaseTarget::Impl void dispatchFrameComplete() override { wpe_renderer_backend_egl_target_dispatch_frame_complete(m_target); } struct wpe_renderer_backend_egl_target* m_target { nullptr }; }; } // namespace struct wpe_renderer_backend_egl_interface fdo_renderer_backend_egl = { // create [](int host_fd) -> void* { return new Backend(host_fd); }, // destroy [](void* data) { auto* backend = reinterpret_cast<Backend*>(data); delete backend; }, // get_native_display [](void* data) -> EGLNativeDisplayType { auto& backend = *reinterpret_cast<Backend*>(data); return backend.m_impl->nativeDisplay(); }, // get_platform [](void* data) -> uint32_t { auto& backend = *reinterpret_cast<Backend*>(data); return backend.m_impl->platform(); }, }; struct wpe_renderer_backend_egl_target_interface fdo_renderer_backend_egl_target = { // create [](struct wpe_renderer_backend_egl_target* target, int host_fd) -> void* { return new Target(target, host_fd); }, // destroy [](void* data) { auto* target = reinterpret_cast<Target*>(data); delete target; }, // initialize [](void* data, void* backend_data, uint32_t width, uint32_t height) { auto& target = *reinterpret_cast<Target*>(data); auto& backend = *reinterpret_cast<Backend*>(backend_data); target.initialize(backend, width, height); }, // get_native_window [](void* data) -> EGLNativeWindowType { auto& target = *reinterpret_cast<Target*>(data); return target.m_impl->nativeWindow(); }, // resize [](void* data, uint32_t width, uint32_t height) { auto& target = *reinterpret_cast<Target*>(data); target.m_impl->resize(width, height); }, // frame_will_render [](void* data) { auto& target = *reinterpret_cast<Target*>(data); target.m_impl->frameWillRender(); }, // frame_rendered [](void* data) { auto& target = *reinterpret_cast<Target*>(data); target.m_impl->frameRendered(); }, #if WPE_CHECK_VERSION(1,9,1) // deinitialize [](void* data) { auto& target = *reinterpret_cast<Target*>(data); target.m_impl->deinitialize(); }, #endif }; struct wpe_renderer_backend_egl_offscreen_target_interface fdo_renderer_backend_egl_offscreen_target = { // create []() -> void* { return nullptr; }, // destroy [](void* data) { }, // initialize [](void* data, void* backend_data) { }, // get_native_window [](void* data) -> EGLNativeWindowType { return nullptr; }, };
29.995238
110
0.650897
ceyusa
d9da41d2f43b5ba0a2435a25eaa4a251c1d86462
14,038
cpp
C++
src/statistics_sweep.cpp
cepellotti/phoebe
3fa935b29c93aa15df89a2ab0fcea4d7a3c56502
[ "MIT" ]
null
null
null
src/statistics_sweep.cpp
cepellotti/phoebe
3fa935b29c93aa15df89a2ab0fcea4d7a3c56502
[ "MIT" ]
null
null
null
src/statistics_sweep.cpp
cepellotti/phoebe
3fa935b29c93aa15df89a2ab0fcea4d7a3c56502
[ "MIT" ]
null
null
null
#include "statistics_sweep.h" #include <algorithm> #include <cmath> #include <iomanip> #include "bandstructure.h" #include "constants.h" #include "context.h" #include "mpiHelper.h" #include "utilities.h" StatisticsSweep::StatisticsSweep(Context &context, FullBandStructure *fullBandStructure) : particle(fullBandStructure != nullptr ? fullBandStructure->getParticle() : Particle(Particle::phonon)), isDistributed(fullBandStructure != nullptr ? fullBandStructure->getIsDistributed() : false) { Eigen::VectorXd temperatures = context.getTemperatures(); nTemp = int(temperatures.size()); if (nTemp == 0) { double minTemperature = context.getMinTemperature(); double maxTemperature = context.getMaxTemperature(); double deltaTemperature = context.getDeltaTemperature(); if (std::isnan(minTemperature) || std::isnan(maxTemperature) || std::isnan(deltaTemperature)) { Error("Temperatures haven't been set in user input"); } int i = 0; while (minTemperature <= maxTemperature) { temperatures.conservativeResize(i + 1); temperatures(i) = minTemperature; minTemperature += deltaTemperature; ++i; } nTemp = int(temperatures.size()); } if (particle.isPhonon()) { nDop = 1; nChemPot = 1; numCalculations = nTemp * std::max(nChemPot, nDop); infoCalculations = Eigen::MatrixXd::Zero(numCalculations, 3); for (int it = 0; it < nTemp; it++) { double temp = temperatures(it); infoCalculations(it, 0) = temp; // note: the other two columns are set to zero above } } else { // isElectron() // in this case, the class is more complicated, as it is tasked with // the calculation of the chemical potential or the doping // so, we first load parameters to compute these quantities bool hasSpinOrbit = context.getHasSpinOrbit(); if (hasSpinOrbit) { spinFactor = 1.; } else { // count spin degeneracy spinFactor = 2.; } volume = fullBandStructure->getPoints().getCrystal().getVolumeUnitCell(); // flatten the energies (easier to work with) numPoints = fullBandStructure->getNumPoints(); // local # of points numBands = fullBandStructure->getNumBands(); energies = Eigen::VectorXd::Zero(numBands * numPoints); // this is written to handle a distributed band structure. It is important // to use the getStateIndices method, because getEnergy(stateIndex) expects // a global energies idx, and looping over getNumStates will only cover // [0,numLocalStates]. getStateIndices provides a list of global state // indices which belong to this process. std::vector<std::tuple<WavevectorIndex, BandIndex>> stateList = fullBandStructure->getStateIndices(); for (int is = 0; is < fullBandStructure->getNumStates(); is++) { auto isk = std::get<0>(stateList[is]); auto isb = std::get<1>(stateList[is]); energies(is) = fullBandStructure->getEnergy(isk, isb); } // full # of points in grid numPoints = fullBandStructure->getNumPoints(true); // determine ground state properties // i.e. we define the number of filled bands and the fermi energy occupiedStates = context.getNumOccupiedStates(); if (std::isnan(occupiedStates)) { // in this case we try to compute it from the Fermi-level fermiLevel = context.getFermiLevel(); if (std::isnan(fermiLevel)) { Error("Must provide either the Fermi level or the number of" " occupied states"); } occupiedStates = 0.; for (int i = 0; i < energies.size(); i++) { if (energies(i) < fermiLevel) { occupiedStates += 1.; } } occupiedStates /= double(numPoints); if (isDistributed) { mpi->allReduceSum(&occupiedStates); } } else { occupiedStates /= spinFactor; // initial guess for chemical potential will be Ef // if distributed, all processes need this guess if (isDistributed) { double eSum = energies.sum(); mpi->allReduceSum(&eSum); // calculate mean of distributed energies fermiLevel = eSum / double(numBands * numPoints); } else { fermiLevel = energies.mean(); } // refine this guess at zero temperature and zero doping fermiLevel = findChemicalPotentialFromDoping(0., 0.); } // load input sweep parameters Eigen::VectorXd dopings = context.getDopings(); Eigen::VectorXd chemicalPotentials = context.getChemicalPotentials(); nChemPot = int(chemicalPotentials.size()); nDop = int(dopings.size()); // if chemical potentials and dopings are not supplied, // check for a min/max mu and dmu energy spacing in the input file if ((nDop == 0) && (nChemPot == 0)) { double minChemicalPotential = context.getMinChemicalPotential(); double maxChemicalPotential = context.getMaxChemicalPotential(); double deltaChemicalPotential = context.getDeltaChemicalPotential(); if (std::isnan(minChemicalPotential) || std::isnan(maxChemicalPotential) || std::isnan(deltaChemicalPotential)) { Error("Didn't find chemical potentials or doping in input"); } // set up energy grid of chemical potentials between min and max, // spaced by dmu int i = 0; while (minChemicalPotential <= maxChemicalPotential) { chemicalPotentials.conservativeResize(i + 1); chemicalPotentials(i) = minChemicalPotential; minChemicalPotential += deltaChemicalPotential; ++i; } nChemPot = int(chemicalPotentials.size()); } // now have two cases: // if doping is passed in input, compute chemical potential // or vice versa Eigen::MatrixXd calcTable(nTemp * std::max(nChemPot, nDop), 3); calcTable.setZero(); // in this case, I have dopings, and want to find chemical potentials if (nChemPot == 0) { nChemPot = nDop; for (int it = 0; it < nTemp; it++) { for (int id = 0; id < nDop; id++) { double temp = temperatures(it); double doping = dopings(id); double chemPot = findChemicalPotentialFromDoping(doping, temp); int iCalc = compress2Indices(it, id, nTemp, nDop); calcTable(iCalc, 0) = temp; calcTable(iCalc, 1) = chemPot; calcTable(iCalc, 2) = doping; } } // in this case, I have chemical potentials } else if (nDop == 0) { nDop = nChemPot; for (int it = 0; it < nTemp; it++) { for (int imu = 0; imu < nChemPot; imu++) { double temp = temperatures(it); double chemPot = chemicalPotentials(imu); double doping = findDopingFromChemicalPotential(chemPot, temp); int iCalc = compress2Indices(it, imu, nTemp, nChemPot); calcTable(iCalc, 0) = temp; calcTable(iCalc, 1) = chemPot; calcTable(iCalc, 2) = doping; } } } // clean memory energies = Eigen::VectorXd::Zero(1); // save potentials and dopings infoCalculations = calcTable; numCalculations = int(calcTable.rows()); } printInfo(); } // copy constructor StatisticsSweep::StatisticsSweep(const StatisticsSweep &that) : particle(that.particle) { numCalculations = that.numCalculations; infoCalculations = that.infoCalculations; nTemp = that.nTemp; nChemPot = that.nChemPot; nDop = that.nDop; } // copy assignment StatisticsSweep &StatisticsSweep::operator=(const StatisticsSweep &that) { if (this != &that) { particle = that.particle; numCalculations = that.numCalculations; infoCalculations = that.infoCalculations; nTemp = that.nTemp; nChemPot = that.nChemPot; nDop = that.nDop; } return *this; } double StatisticsSweep::fPop(const double &chemPot, const double &temp) { // fPop = 1/NK \sum_\mu FermiDirac(\mu) - N // Note that I don`t normalize the integral, which is the same thing I did // for computing the particle number double fPop_ = 0.; #pragma omp parallel for reduction(+ : fPop_) default(none) shared(temp,chemPot) for (int i = 0; i < energies.size(); i++) { fPop_ += particle.getPopulation(energies(i), temp, chemPot); } // in the distributed case, this needs to be summed over all processes, // and also needs to be available to all processes for calculation of next // iteration's chem potential if (isDistributed) mpi->allReduceSum(&fPop_); fPop_ /= double(numPoints); fPop_ = numElectronsDoped - fPop_; return fPop_; } double StatisticsSweep::findChemicalPotentialFromDoping(const double &doping, const double &temperature) { // given the carrier concentration, finds the fermi energy // temperature is set inside glob // To find fermi energy, I must find the root of \sum_s f(s) - N = 0 // the root is found with a bisection algorithm // Might be numerically unstable for VERY small doping concentration // numElectronsDoped is the total number of electrons in the unit cell // numElectrons is the number of electrons in the unit cell before doping // doping > 0 means p-doping (fermi level in the valence band) numElectronsDoped = occupiedStates - doping * volume * pow(distanceBohrToCm, 3) / spinFactor; // bisection method: I need to find the root of N - \int fermi dirac = 0 // initial guess double chemicalPotential = fermiLevel; // Corner cases // if numElectronsDoped > numBands, it's a non-valid doping if (numElectronsDoped > float(numBands)) { Error("The number of occupied states is larger than the " "bands present in the Hamiltonian"); } if (numElectronsDoped < 0.) { Error("The number of occupied states is negative"); } // if we are looking for the fermi level at T=0 and n=0, we have a corner case // when we have completely empty bands or completely full bands. if (doping==0. && temperature == 0.) { // case of computing fermi level if (numElectronsDoped == 0.) { fermiLevel = energies.minCoeff(); chemicalPotential = fermiLevel; return chemicalPotential; } else if (numElectronsDoped == float(numBands)) { fermiLevel = energies.maxCoeff(); chemicalPotential = fermiLevel; return chemicalPotential; } } // I choose the following (generous) boundaries double aX = energies.minCoeff() - 1.; double bX = energies.maxCoeff() + 1.; // note: +-1 Ry = 13 eV should work for most dopings and temperatures, // even in corner cases // if energies are distributed, each process needs to have the global // minimum and maximum of the energies if (isDistributed) { mpi->allReduceMin(&aX); mpi->allReduceMax(&bX); } double aY = fPop(aX, temperature); double bY = fPop(bX, temperature); // check if starting values are bad if (sgn(aY) == sgn(bY)) { Error("I should revisit the boundary limits for bisection method"); } for (int iter = 0; iter < maxIter; iter++) { if (mpi->mpiHead() && iter == maxIter - 1) { Error("Max iteration reached in finding mu"); } // x value is midpoint of prior values double cX = (aX + bX) / 2.; double cY = fPop(cX, temperature); // exit condition: the guess is exact or didn't change much if ((cY == 0.) || (abs(bX - aX) < 1.0e-8)) { chemicalPotential = cX; break; // go out of the loop } // check the sign if (sgn(cY) == sgn(aY)) { aX = cX; } else { bX = cX; } } return chemicalPotential; } double StatisticsSweep::findDopingFromChemicalPotential( const double &chemicalPotential, const double &temperature) { double fPop = 0.; for (int i = 0; i < energies.size(); i++) { fPop += particle.getPopulation(energies(i), temperature, chemicalPotential); } if (isDistributed) mpi->allReduceSum(&fPop); fPop /= double(numPoints); double doping = (occupiedStates - fPop); // if both are all reduced, this should be consistent. doping *= spinFactor / volume / pow(distanceBohrToCm, 3); return doping; } CalcStatistics StatisticsSweep::getCalcStatistics(const int &index) { CalcStatistics sc = {}; sc.temperature = infoCalculations(index, 0); sc.chemicalPotential = infoCalculations(index, 1); // chemical potential sc.doping = infoCalculations(index, 2); // doping return sc; } CalcStatistics StatisticsSweep::getCalcStatistics(const TempIndex &iTemp, const ChemPotIndex &iChemPot) { int index = compress2Indices(iTemp.get(), iChemPot.get(), nTemp, nChemPot); return getCalcStatistics(index); } int StatisticsSweep::getNumCalculations() const { return numCalculations; } int StatisticsSweep::getNumChemicalPotentials() const { return nChemPot; } int StatisticsSweep::getNumTemperatures() const { return nTemp; } void StatisticsSweep::printInfo() { if (!mpi->mpiHead()) return; std::cout << "\n"; std::cout << "Statistical parameters for the calculation\n"; if (particle.isElectron()) { std::cout << "Fermi level: " << fermiLevel * energyRyToEv << " (eV)" << std::endl; } std::cout << "Index, temperature, chemical potential, doping concentration\n"; for (int iCalc = 0; iCalc < numCalculations; iCalc++) { double temp = infoCalculations(iCalc, 0); double chemPot = infoCalculations(iCalc, 1); double doping = infoCalculations(iCalc, 2); std::cout << std::fixed << std::setprecision(6); std::cout << "iCalc = " << iCalc << ", T = " << temp * temperatureAuToSi << " (K)"; if (particle.isPhonon()) { std::cout << "\n"; } else { std::cout << ", mu = " << chemPot * energyRyToEv << " (eV)" << ", n = " << std::scientific << doping << " (cm^-3)" << std::endl; } } std::cout << std::endl; }
34.920398
80
0.644323
cepellotti
d9defd706fc158d22c70ec08eb89617f14f9cd4b
35,644
cpp
C++
Nana.Cpp03/source/gui/programming_interface.cpp
gfannes/nana
3b8d33f9a98579684ea0440b6952deabe61bd978
[ "BSL-1.0" ]
1
2018-02-09T21:25:13.000Z
2018-02-09T21:25:13.000Z
Nana.Cpp03/source/gui/programming_interface.cpp
gfannes/nana
3b8d33f9a98579684ea0440b6952deabe61bd978
[ "BSL-1.0" ]
null
null
null
Nana.Cpp03/source/gui/programming_interface.cpp
gfannes/nana
3b8d33f9a98579684ea0440b6952deabe61bd978
[ "BSL-1.0" ]
null
null
null
/* * Nana GUI Programming Interface Implementation * Copyright(C) 2003-2013 Jinhao(cnjinhao@hotmail.com) * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * @file: nana/gui/programming_interface.cpp */ #include <nana/gui/programming_interface.hpp> #include <nana/system/platform.hpp> namespace nana{ namespace gui{ //restrict // this name is only visible for this compiling-unit namespace restrict { typedef gui::detail::bedrock::core_window_t core_window_t; typedef gui::detail::bedrock::interface_type interface_type; gui::detail::bedrock& bedrock = gui::detail::bedrock::instance(); gui::detail::bedrock::window_manager_t& window_manager = bedrock.wd_manager; } namespace effects { class effects_accessor { public: static bground_interface * create(const bground_factory_interface& factory) { return factory.create(); } }; } namespace API { void effects_edge_nimbus(window wd, effects::edge_nimbus::t en) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { restrict::core_window_t::edge_nimbus_container & cont = iwd->root_widget->other.attribute.root->effects_edge_nimbus; if(en) { if(iwd->effect.edge_nimbus == effects::edge_nimbus::none) { restrict::core_window_t::edge_nimbus_action act = {iwd}; cont.push_back(act); } iwd->effect.edge_nimbus = static_cast<effects::edge_nimbus::t>(iwd->effect.edge_nimbus | en); } else { if(iwd->effect.edge_nimbus) { for(restrict::core_window_t::edge_nimbus_container::iterator i = cont.begin(); i != cont.end(); ++i) { if(i->window == iwd) { cont.erase(i); break; } } } iwd->effect.edge_nimbus = effects::edge_nimbus::none; } } } } effects::edge_nimbus::t effects_edge_nimbus(window wd) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) return iwd->effect.edge_nimbus; } return effects::edge_nimbus::none; } void effects_bground(window wd, const effects::bground_factory_interface& factory, double fade_rate) { if(0 == wd) return; restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { effects::bground_interface* new_effect_ptr = effects::effects_accessor::create(factory); if(0 == new_effect_ptr) return; delete iwd->effect.bground; iwd->effect.bground = new_effect_ptr; iwd->effect.bground_fade_rate = fade_rate; restrict::window_manager.enable_effects_bground(iwd, true); API::refresh_window(wd); } } bground_mode::t effects_bground_mode(window wd) { if(0 == wd) return bground_mode::none; restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && iwd->effect.bground) return (iwd->effect.bground_fade_rate <= 0.009 ? bground_mode::basic : bground_mode::blend); return bground_mode::none; } void effects_bground_remove(window wd) { if(0 == wd) return; restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { delete iwd->effect.bground; iwd->effect.bground = 0; iwd->effect.bground_fade_rate = 0; restrict::window_manager.enable_effects_bground(iwd, false); API::refresh_window(wd); } } namespace dev { void attach_drawer(window wd, drawer_trigger& dr) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { iwd->drawer.graphics.make(iwd->dimension.width, iwd->dimension.height); iwd->drawer.graphics.rectangle(iwd->color.background, true); iwd->drawer.attached(dr); make_drawer_event<events::size>(wd); iwd->drawer.refresh(); //Always redrawe no matter it is visible or invisible. This can make the graphics data correctly. } } } void detach_drawer(window wd) { if(wd) { internal_scope_guard isg; if(restrict::window_manager.available(reinterpret_cast<restrict::core_window_t*>(wd))) reinterpret_cast<restrict::core_window_t*>(wd)->drawer.detached(); } } void umake_drawer_event(window wd) { restrict::bedrock.evt_manager.umake(wd, true); } nana::string window_caption(window wd) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { if(iwd->other.category == category::flags::root) return restrict::interface_type::window_caption(iwd->root); return iwd->title; } } return nana::string(); } void window_caption(window wd, const nana::string& title) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { iwd->title = title; if(iwd->other.category == category::flags::root) restrict::interface_type::window_caption(iwd->root, title); } restrict::window_manager.update(iwd, true, false); } } window create_window(window owner, bool nested, const rectangle& r, const appearance& ap) { return reinterpret_cast<window>(restrict::window_manager.create_root(reinterpret_cast<restrict::core_window_t*>(owner), nested, r, ap)); } window create_widget(window parent, const rectangle& r) { return reinterpret_cast<window>(restrict::window_manager.create_widget(reinterpret_cast<restrict::core_window_t*>(parent), r, false)); } window create_lite_widget(window parent, const rectangle& r) { return reinterpret_cast<window>(restrict::window_manager.create_widget(reinterpret_cast<restrict::core_window_t*>(parent), r, true)); } window create_frame(window parent, const rectangle& r) { return reinterpret_cast<window>(restrict::window_manager.create_frame(reinterpret_cast<restrict::core_window_t*>(parent), r)); } paint::graphics * window_graphics(window wd) { if(wd) { internal_scope_guard isg; if(restrict::window_manager.available(reinterpret_cast<restrict::core_window_t*>(wd))) return &reinterpret_cast<restrict::core_window_t*>(wd)->drawer.graphics; } return 0; } }//end namespace dev //exit //close all windows in current thread void exit() { internal_scope_guard isg; std::vector<restrict::core_window_t*> v; restrict::window_manager.all_handles(v); if(v.size()) { std::vector<native_window_type> roots; native_window_type root = 0; unsigned tid = nana::system::this_thread_id(); for(std::vector<restrict::core_window_t*>::iterator i = v.begin(), end = v.end(); i != end; ++i) { restrict::core_window_t * wd = *i; if((wd->thread_id == tid) && (wd->root != root)) { root = wd->root; if(roots.end() == std::find(roots.begin(), roots.end(), root)) roots.push_back(root); } } std::for_each(roots.begin(), roots.end(), restrict::interface_type::close_window); } } //transform_shortkey_text //@brief: This function searchs whether the text contains a '&' and removes the character for transforming. // If the text contains more than one '&' charachers, the others are ignored. e.g // text = "&&a&bcd&ef", the result should be "&abcdef", shortkey = 'b', and pos = 2. //@param, text: the text is transformed. //@param, shortkey: the character which indicates a short key. //@param, skpos: retrives the shortkey position if it is not a null_ptr; nana::string transform_shortkey_text(nana::string text, nana::string::value_type &shortkey, nana::string::size_type *skpos) { shortkey = 0; nana::string::size_type off = 0; while(true) { nana::string::size_type pos = text.find_first_of('&', off); if(pos != nana::string::npos) { text.erase(pos, 1); if(shortkey == 0 && pos < text.length()) { shortkey = text.at(pos); if(shortkey == '&') //This indicates the text contains "&&", it means the symbol have to be ignored. shortkey = 0; else if(skpos) *skpos = pos; } off = pos + 1; } else break; } return text; } bool register_shortkey(window wd, unsigned long key) { return restrict::window_manager.register_shortkey(reinterpret_cast<restrict::core_window_t*>(wd), key); } void unregister_shortkey(window wd) { restrict::window_manager.unregister_shortkey(reinterpret_cast<restrict::core_window_t*>(wd)); } nana::size screen_size() { return restrict::interface_type::screen_size(); } rectangle screen_area_from_point(const point& pos) { return restrict::interface_type::screen_area_from_point(pos); } point cursor_position() { return restrict::interface_type::cursor_position(); } rectangle make_center(unsigned width, unsigned height) { nana::size screen = restrict::interface_type::screen_size(); nana::rectangle result( width > screen.width? 0: (screen.width - width)>>1, height > screen.height? 0: (screen.height - height)>> 1, width, height ); return result; } nana::rectangle make_center(window wd, unsigned width, unsigned height) { nana::rectangle r = make_center(width, height); nana::point pos(r.x, r.y); calc_window_point(wd, pos); r.x = pos.x; r.y = pos.y; return r; } void window_icon_default(const paint::image& img) { restrict::window_manager.default_icon(img); } void window_icon(window wd, const paint::image& img) { restrict::window_manager.icon(reinterpret_cast<restrict::core_window_t*>(wd), img); } bool empty_window(window wd) { return (restrict::window_manager.available(reinterpret_cast<restrict::core_window_t*>(wd)) == false); } native_window_type root(window wd) { return restrict::bedrock.root(reinterpret_cast<restrict::core_window_t*>(wd)); } window root(native_window_type wd) { return reinterpret_cast<window>(restrict::window_manager.root(wd)); } bool enabled_double_click(window wd, bool dbl) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { bool result = iwd->flags.dbl_click; iwd->flags.dbl_click = dbl; return result; } } return false; } void fullscreen(window wd, bool v) { if(wd) { internal_scope_guard isg; if(restrict::window_manager.available(reinterpret_cast<restrict::core_window_t*>(wd))) reinterpret_cast<restrict::core_window_t*>(wd)->flags.fullscreen = v; } } bool insert_frame(window frame, native_window_type native_window) { return restrict::window_manager.insert_frame(reinterpret_cast<restrict::core_window_t*>(frame), native_window); } native_window_type frame_container(window frame) { if(frame) { internal_scope_guard isg; if(reinterpret_cast<restrict::core_window_t*>(frame)->other.category == category::flags::frame) return reinterpret_cast<restrict::core_window_t*>(frame)->other.attribute.frame->container; } return 0; } native_window_type frame_element(window frame, unsigned index) { if(frame) { internal_scope_guard isg; if(reinterpret_cast<restrict::core_window_t*>(frame)->other.category == category::flags::frame) { if(index < reinterpret_cast<restrict::core_window_t*>(frame)->other.attribute.frame->attach.size()) return reinterpret_cast<restrict::core_window_t*>(frame)->other.attribute.frame->attach.at(index); } } return 0; } void close_window(window wd) { restrict::window_manager.close(reinterpret_cast<restrict::core_window_t*>(wd)); } void show_window(window wd, bool show) { restrict::window_manager.show(reinterpret_cast<restrict::core_window_t*>(wd), show); } bool visible(window wd) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { if(iwd->other.category == category::flags::root) return restrict::interface_type::is_window_visible(iwd->root); return iwd->visible; } } return false; } void restore_window(window wd) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { if(iwd->other.category == category::flags::root) restrict::interface_type::restore_window(iwd->root); } } } void zoom_window(window wd, bool ask_for_max) { if(wd) { restrict::core_window_t* core_wd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard lock; if(restrict::window_manager.available(core_wd)) { if(category::flags::root == core_wd->other.category) restrict::interface_type::zoom_window(core_wd->root, ask_for_max); } } } window get_parent_window(window wd) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) return reinterpret_cast<window>(iwd->other.category == category::flags::root ? iwd->owner : iwd->parent); } return 0; } window get_owner_window(window wd) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && (iwd->other.category == category::flags::root)) { native_window_type owner = restrict::interface_type::get_owner_window(iwd->root); if(owner) return reinterpret_cast<window>(restrict::window_manager.root(owner)); } } return 0; } void umake_event(window wd) { restrict::bedrock.evt_manager.umake(wd, false); } void umake_event(event_handle eh) { restrict::bedrock.evt_manager.umake(eh); } nana::point window_position(window wd) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { return ( (iwd->other.category == category::flags::root) ? restrict::interface_type::window_position(iwd->root) : iwd->pos_owner); } } return nana::point(); } void move_window(window wd, int x, int y) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.move(iwd, x, y, false)) { if(category::flags::root != iwd->other.category) iwd = reinterpret_cast<restrict::core_window_t*>(API::get_parent_window(wd)); restrict::window_manager.update(iwd, false, false); } } void move_window(window wd, int x, int y, unsigned width, unsigned height) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.move(iwd, x, y, width, height)) { if(category::flags::root != iwd->other.category) iwd = reinterpret_cast<restrict::core_window_t*>(API::get_parent_window(wd)); restrict::window_manager.update(iwd, false, false); } } bool set_window_z_order(window wd, window wd_after, z_order_action::t action_if_no_wd_after) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { if(category::flags::root == iwd->other.category) { if(wd_after) { restrict::core_window_t * const iwd_after = reinterpret_cast<restrict::core_window_t*>(wd_after); if(restrict::window_manager.available(iwd_after) && (iwd_after->other.category == category::flags::root)) { restrict::interface_type::set_window_z_order(iwd->root, iwd_after->root, z_order_action::none); return true; } } else { restrict::interface_type::set_window_z_order(iwd->root, 0, action_if_no_wd_after); return true; } } } } return false; } nana::size window_size(window wd) { nana::rectangle r; API::window_rectangle(wd, r); return nana::size(r.width, r.height); } void window_size(window wd, unsigned width, unsigned height) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.size(iwd, width, height, false, false)) { if(category::flags::root != iwd->other.category) iwd = reinterpret_cast<restrict::core_window_t*>(API::get_parent_window(wd)); restrict::window_manager.update(iwd, false, false); } } bool window_rectangle(window wd, rectangle& r) { if(0 == wd) return false; restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(false == restrict::window_manager.available(iwd)) return false; r = iwd->pos_owner; r = iwd->dimension; return true; } bool track_window_size(window wd, const nana::size& sz, bool true_for_max) { if(0 == wd) return false; restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) == false) return false; nana::size & ts = (true_for_max ? iwd->max_track_size : iwd->min_track_size); if(sz.width && sz.height) { if(true_for_max) { if(iwd->min_track_size.width <= sz.width && iwd->min_track_size.height <= sz.height) { ts = restrict::interface_type::check_track_size(sz, iwd->extra_width, iwd->extra_height, true); return true; } } else { if((iwd->max_track_size.width == 0 && iwd->max_track_size.height == 0) || (iwd->max_track_size.width >= sz.width && iwd->max_track_size.height >= sz.height)) { ts = restrict::interface_type::check_track_size(sz, iwd->extra_width, iwd->extra_height, false); return true; } } return false; } else ts.width = ts.height = 0; return true; } void window_enabled(window wd, bool enabled) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && (iwd->flags.enabled != enabled)) { iwd->flags.enabled = enabled; restrict::window_manager.update(iwd, true, false); if(category::flags::root == iwd->other.category) restrict::interface_type::enable_window(iwd->root, enabled); } } } bool window_enabled(window wd) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; return (restrict::window_manager.available(iwd) ? iwd->flags.enabled : false); } return false; } //lazy_refresh: //@brief: A widget drawer draws the widget surface in answering an event. This function will tell the drawer to copy the graphics into window after event answering. void lazy_refresh() { restrict::bedrock.thread_context_lazy_refresh(); } //refresh_window //@brief: Refresh the window and display it immediately. void refresh_window(window wd) { restrict::window_manager.update(reinterpret_cast<restrict::core_window_t*>(wd), true, false); } void refresh_window_tree(window wd) { restrict::window_manager.refresh_tree(reinterpret_cast<restrict::core_window_t*>(wd)); } //update_window //@brief: it displays a window immediately without refreshing. void update_window(window wnd) { restrict::window_manager.update(reinterpret_cast<restrict::core_window_t*>(wnd), false, true); } void window_caption(window wd, const nana::string& title) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) restrict::window_manager.signal_fire_caption(iwd, title.c_str()); } } nana::string window_caption(window wd) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) return restrict::window_manager.signal_fire_caption(iwd); } return nana::string(); } void window_cursor(window wd, cursor::t cur) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { iwd->predef_cursor = cur; restrict::bedrock.update_cursor(iwd); } } } cursor::t window_cursor(window wd) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) return iwd->predef_cursor; } return cursor::arrow; } bool tray_insert(native_window_type wd, const nana::char_t* tip, const nana::char_t* ico) { return restrict::interface_type::notify_icon_add(wd, tip, ico); } bool tray_delete(native_window_type wd) { return restrict::interface_type::notify_icon_delete(wd); } void tray_tip(native_window_type wd, const char_t* text) { restrict::interface_type::notify_tip(wd, text); } void tray_icon(native_window_type wd, const char_t* icon) { restrict::interface_type::notify_icon(wd, icon); } bool tray_make_event(native_window_type wd, unsigned identifier, const nana::functor<void(const eventinfo&)> & f) { return restrict::window_manager.tray_make_event(wd, identifier, f); } void tray_umake_event(native_window_type wd) { restrict::window_manager.tray_umake_event(wd); } bool is_focus_window(window wd) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) return (iwd->root_widget->other.attribute.root->focus == iwd); } return false; } window focus_window() { internal_scope_guard isg; return reinterpret_cast<window>(restrict::bedrock.focus()); } void focus_window(window wd) { restrict::window_manager.set_focus(reinterpret_cast<restrict::core_window_t*>(wd)); restrict::window_manager.update(reinterpret_cast<restrict::core_window_t*>(wd), false, false); } window capture_window() { return reinterpret_cast<window>(restrict::window_manager.capture_window()); } window capture_window(window wd, bool value) { return reinterpret_cast<window>( restrict::window_manager.capture_window(reinterpret_cast<restrict::core_window_t*>(wd), value) ); } void capture_ignore_children(bool ignore) { restrict::window_manager.capture_ignore_children(ignore); } void modal_window(window wd) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; wd = 0; if(restrict::window_manager.available(iwd)) { if((iwd->other.category == category::flags::root) && (iwd->flags.modal == false)) { iwd->flags.modal = true; #if defined(NANA_X11) restrict::interface_type::set_modal(iwd->root); #endif restrict::window_manager.show(iwd, true); wd = reinterpret_cast<window>(iwd); } } } if(wd) { //modal has to guarantee that does not lock the wnd_mgr_lock_ before invokeing the pump_event, //otherwise, the modal will prevent the other thread access the window. restrict::bedrock.pump_event(wd); } } nana::color_t foreground(window wd) { if(wd) { internal_scope_guard isg; if(restrict::window_manager.available(reinterpret_cast<restrict::core_window_t*>(wd))) return reinterpret_cast<restrict::core_window_t*>(wd)->color.foreground; } return 0; } color_t foreground(window wd, color_t col) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { color_t prev = iwd->color.foreground; if(prev != col) { iwd->color.foreground = col; restrict::window_manager.update(iwd, true, false); } return prev; } } return 0; } color_t background(window wd) { if(wd) { internal_scope_guard isg; if(restrict::window_manager.available(reinterpret_cast<restrict::core_window_t*>(wd))) return reinterpret_cast<restrict::core_window_t*>(wd)->color.background; } return 0; } color_t background(window wd, color_t col) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { color_t prev = iwd->color.background; if(prev != col) { iwd->color.background = col; restrict::window_manager.update(iwd, true, false); } return prev; } } return 0; } color_t active(window wd) { if(wd) { internal_scope_guard isg; if(restrict::window_manager.available(reinterpret_cast<restrict::core_window_t*>(wd))) return reinterpret_cast<restrict::core_window_t*>(wd)->color.active; } return 0; } color_t active(window wd, color_t col) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { color_t prev = iwd->color.active; if(prev != col) { iwd->color.active = col; restrict::window_manager.update(iwd, true, false); } return prev; } } return 0; } void create_caret(window wd, unsigned width, unsigned height) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && (0 == iwd->together.caret)) iwd->together.caret = new detail::caret_descriptor(iwd, width, height); } } void destroy_caret(window wd) { if(wd) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { detail::caret_descriptor* p = iwd->together.caret; iwd->together.caret = 0; delete p; } } } void caret_pos(window wd, int x, int y) { if(wd) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && iwd->together.caret) iwd->together.caret->position(x, y); } } nana::point caret_pos(window wd) { if(wd) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && iwd->together.caret) return iwd->together.caret->position(); } return point(); } void caret_effective_range(window wd, const nana::rectangle& rect) { if(wd) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && iwd->together.caret) iwd->together.caret->effective_range(rect); } } void caret_size(window wd, const nana::size& sz) { if(wd) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && iwd->together.caret) iwd->together.caret->size(sz); } } nana::size caret_size(window wd) { if(wd) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && iwd->together.caret) return iwd->together.caret->size(); } return nana::size(); } void caret_visible(window wd, bool is_show) { if(wd) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && iwd->together.caret) iwd->together.caret->visible(is_show); } } bool caret_visible(window wd) { if(wd) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && iwd->together.caret) return iwd->together.caret->visible(); } return false; } void tabstop(window wnd) { restrict::window_manager.tabstop(reinterpret_cast<restrict::core_window_t*>(wnd)); } //eat_tabstop //@brief: set a eating tab window that it processes a pressing of tab itself void eat_tabstop(window wd, bool eat) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { if(eat) iwd->flags.tab |= detail::tab_type::eating; else iwd->flags.tab &= ~detail::tab_type::eating; } } } window move_tabstop(window wd, bool next) { restrict::core_window_t* ts_wd; if(next) ts_wd = restrict::window_manager.tabstop_next(reinterpret_cast<restrict::core_window_t*>(wd)); else ts_wd = restrict::window_manager.tabstop_prev(reinterpret_cast<restrict::core_window_t*>(wd)); restrict::window_manager.set_focus(ts_wd); restrict::window_manager.update(ts_wd, false, false); return reinterpret_cast<window>(ts_wd); } //glass_window //@brief: Test a window whether it is a glass attribute. bool glass_window(window wd) { return (bground_mode::basic == effects_bground_mode(wd)); } bool glass_window(window wd, bool isglass) { if(isglass) effects_bground(wd, effects::bground_transparent(0), 0); else effects_bground_remove(wd); return true; } void take_active(window wd, bool active, window take_if_active_false) { if(wd) { restrict::core_window_t * const iwd = reinterpret_cast<restrict::core_window_t*>(wd); restrict::core_window_t * take_if_false = reinterpret_cast<restrict::core_window_t*>(take_if_active_false); internal_scope_guard isg; if(active || (take_if_false && (restrict::window_manager.available(take_if_false) == false))) take_if_false = 0; if(restrict::window_manager.available(iwd) == false) return; iwd->flags.take_active = active; iwd->other.active_window = take_if_false; } } bool window_graphics(window wd, nana::paint::graphics& graph) { return restrict::window_manager.get_graphics(reinterpret_cast<restrict::core_window_t*>(wd), graph); } bool root_graphics(window wd, nana::paint::graphics& graph) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { graph = *(iwd->root_graph); return true; } } return false; } bool get_visual_rectangle(window wd, nana::rectangle& r) { return restrict::window_manager.get_visual_rectangle(reinterpret_cast<restrict::core_window_t*>(wd), r); } void typeface(window wd, const nana::paint::font& font) { if(wd) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { iwd->drawer.graphics.typeface(font); restrict::window_manager.update(iwd, true, false); } } } nana::paint::font typeface(window wd) { if(wd) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) return iwd->drawer.graphics.typeface(); } return nana::paint::font(); } bool calc_screen_point(window wd, nana::point& pos) { if(wd) { restrict::core_window_t* iwd = reinterpret_cast<restrict::core_window_t*>(wd); internal_scope_guard isg; if(restrict::window_manager.available(iwd)) { pos.x += iwd->pos_root.x; pos.y += iwd->pos_root.y; return restrict::interface_type::calc_screen_point(iwd->root, pos); } } return false; } bool calc_window_point(window wd, nana::point& pos) { return restrict::window_manager.calc_window_point(reinterpret_cast<restrict::core_window_t*>(wd), pos); } window find_window(const nana::point& pos) { native_window_type wd = restrict::interface_type::find_window(pos.x, pos.y); if(wd) { nana::point clipos(pos.x, pos.y); restrict::interface_type::calc_window_point(wd, clipos); return reinterpret_cast<window>( restrict::window_manager.find_window(wd, clipos.x, clipos.y)); } return 0; } void register_menu_window(window wd, bool has_keyboard) { if(wd) { internal_scope_guard isg; if(restrict::window_manager.available(reinterpret_cast<restrict::core_window_t*>(wd))) restrict::bedrock.set_menu(reinterpret_cast<restrict::core_window_t*>(wd)->root, has_keyboard); } } bool attach_menubar(window menubar) { if(menubar) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(menubar); internal_scope_guard isg; if(restrict::window_manager.available(iwd) && (0 == iwd->root_widget->other.attribute.root->menubar)) { iwd->root_widget->other.attribute.root->menubar = iwd; return true; } } return false; } void detach_menubar(window menubar) { if(menubar) { restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(menubar); internal_scope_guard isg; if(restrict::window_manager.available(iwd) == false) return; if(iwd->root_widget->other.attribute.root->menubar == iwd) iwd->root_widget->other.attribute.root->menubar = 0; } } void restore_menubar_taken_window() { restrict::core_window_t * wd = restrict::bedrock.get_menubar_taken(); if(wd) { internal_scope_guard isg; restrict::window_manager.set_focus(wd); restrict::window_manager.update(wd, true, false); } } bool is_window_zoomed(window wd, bool ask_for_max) { internal_scope_guard isg; restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); if(restrict::window_manager.available(iwd)) return detail::bedrock::interface_type::is_window_zoomed(iwd->root, ask_for_max); return false; } gui::mouse_action::t mouse_action(window wd) { internal_scope_guard isg; restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); if(restrict::window_manager.available(iwd)) return iwd->flags.action; return nana::gui::mouse_action::normal; } nana::gui::element_state::t element_state(window wd) { internal_scope_guard isg; restrict::core_window_t * iwd = reinterpret_cast<restrict::core_window_t*>(wd); if(restrict::window_manager.available(iwd)) { const bool is_focused = (iwd->root_widget->other.attribute.root->focus == iwd); switch(iwd->flags.action) { case gui::mouse_action::normal: return (is_focused ? gui::element_state::focus_normal : gui::element_state::normal); case gui::mouse_action::over: return (is_focused ? gui::element_state::focus_hovered : gui::element_state::hovered); case gui::mouse_action::pressed: return gui::element_state::pressed; default: if(false == iwd->flags.enabled) return gui::element_state::disabled; } } return gui::element_state::normal; } }//end namespace API }//end namespace gui }//end namespace nana
27.229947
165
0.70441
gfannes
d9e6fa82ad49f15ac3fddfc821eb45cf42bf2d37
132
cc
C++
udemy/modern_cpp/06-more-bazel-concepts/e01/src/Main.cc
e-dnx/courses
d21742a51447496f541dc8ec32b0df79d709dbff
[ "MIT" ]
null
null
null
udemy/modern_cpp/06-more-bazel-concepts/e01/src/Main.cc
e-dnx/courses
d21742a51447496f541dc8ec32b0df79d709dbff
[ "MIT" ]
null
null
null
udemy/modern_cpp/06-more-bazel-concepts/e01/src/Main.cc
e-dnx/courses
d21742a51447496f541dc8ec32b0df79d709dbff
[ "MIT" ]
null
null
null
#include "e01/Greeter.h" #include <iostream> int main() { Greeter greeter; greeter.sayHello(); return EXIT_SUCCESS; }
11
24
0.659091
e-dnx
d9e803ff49925b27ef8ec609f69a9a2a79ba81e5
3,056
cpp
C++
core123/ut/ut_datetimeutils.cpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
22
2019-04-10T18:05:35.000Z
2021-12-30T12:26:39.000Z
core123/ut/ut_datetimeutils.cpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
13
2019-04-09T00:19:29.000Z
2021-11-04T15:57:13.000Z
core123/ut/ut_datetimeutils.cpp
fennm/fs123
559b97659352620ce16030824f9acd26f590f4e1
[ "BSD-3-Clause" ]
4
2019-04-07T16:33:44.000Z
2020-07-02T02:58:51.000Z
#include "core123/sew.hpp" #include "core123/datetimeutils.hpp" #include "core123/strutils.hpp" #include <iostream> #include <vector> #include <utility> using core123::str; using core123::timet_to_httpdate; using core123::httpdate_to_timet; namespace sew = core123::sew; int main(int, char **) { struct timespec now1, now2, now3; sew::clock_gettime(CLOCK_REALTIME, &now1); auto s1 = str(now1); now2 = now1; auto s2 = str(now2); if (now1 == now2) { if (s1 != s2) throw std::runtime_error("timespec string mismatch \""+s1+"\" != \""+s2+"\""); sew::clock_gettime(CLOCK_REALTIME, &now3); auto s3 = str(now3); if (now1 != now3) { if (now1 < now3) { std::cout << "OK, timespec \"" << s1 << "\" < \"" << s3 << "\"\n"; } else { throw std::runtime_error("timespec failed lt \"" + s1 + "\" \"" + s3 + "\"\n"); } } else { throw std::runtime_error("timespec failed ne \"" + s1 + "\" \"" + s3 + "\"\n"); } } else { throw std::runtime_error("timespec fail eq \""+s1+"\" \""+s2+"\""); } // Enhancement request: this should work // str("the time is now: ", std::chrono::system_clock::now()); // but it doesn't. We have to str-ify the time_point. str("the time is now: ", str(std::chrono::system_clock::now())); // The fix is *possibly* a partial specialization of // 'core123::detail::insertone' for time_point (and duration), but // it seems to require a bit of re-engineering of insertone. // date -u '%s %c' => 1524747193 Thu 26 Apr 2018 12:53:13 PM UTC const std::vector<std::pair<time_t,std::string> > tests{ {1524747193, "Thu, 26 Apr 2018 12:53:13 GMT"}, {0, "Thu, 01 Jan 1970 00:00:00 GMT"}, {1, "Thu, 01 Jan 1970 00:00:01 GMT"}, {86400, "Fri, 02 Jan 1970 00:00:00 GMT"}, {INT32_MAX, "Tue, 19 Jan 2038 03:14:07 GMT"}, }; for (const auto &t : tests) { auto s = timet_to_httpdate(t.first); if (s != t.second) { std::cerr << "ERROR: timet_to_httpdate mismatch, got " << s << " for " << t.first << '\n'; std::cerr << " expected " << t.second << std::endl; return 1; } auto tt = httpdate_to_timet(t.second.c_str()); if(tt != t.first) { std::cerr << "ERROR: httpdate_to_timet mismatch, got " << s << " for " << t.first << '\n'; std::cerr << " expected " << t.second << std::endl; return 1; } } bool caught = false; try{ httpdate_to_timet("19 Jan 2038 03:14:07"); }catch(std::system_error& se){ caught = true; std::cout << "OK, intentionally bad call to httpdate_timet threw: what:" << se.what() << "\n"; } if(!caught){ std::cerr << "ERROR: expected httpdate_to_timet to throw"; return 1; } std::cout << "OK, " << tests.size() << " tests passed" << std::endl; return 0; }
36.380952
102
0.531741
fennm
d9ef31332220085090a44d4acde4ef960c6fbf7d
505
cpp
C++
LeetCode/C++/1389. Create Target Array in the Given Order.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/1389. Create Target Array in the Given Order.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/1389. Create Target Array in the Given Order.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Create Target Array in the Given Order. //Memory Usage: 8.5 MB, less than 100.00% of C++ online submissions for Create Target Array in the Given Order. class Solution { public: vector<int> createTargetArray(vector<int>& nums, vector<int>& index) { vector<int> ans; for(int i = 0; i < index.size(); i++){ ans.insert(ans.begin() + index[i], nums[i]); } return ans; } };
33.666667
111
0.6
shreejitverma
d9ef562f5553a943567d02dd8e10f99dcfaef609
209
cpp
C++
src/netlist/gate_library/enums/pin_direction.cpp
emsec/HAL
608e801896e1b5254b28ce0f29d4d898b81b0f77
[ "MIT" ]
407
2019-04-26T10:45:52.000Z
2022-03-31T15:52:30.000Z
src/netlist/gate_library/enums/pin_direction.cpp
emsec/HAL
608e801896e1b5254b28ce0f29d4d898b81b0f77
[ "MIT" ]
219
2019-04-29T16:42:01.000Z
2022-03-11T22:57:41.000Z
src/netlist/gate_library/enums/pin_direction.cpp
emsec/HAL
608e801896e1b5254b28ce0f29d4d898b81b0f77
[ "MIT" ]
53
2019-05-02T21:23:35.000Z
2022-03-11T19:46:05.000Z
#include "hal_core/netlist/gate_library/enums/pin_direction.h" namespace hal { template<> std::vector<std::string> EnumStrings<PinDirection>::data = {"none", "input", "output", "inout", "internal"}; }
29.857143
112
0.698565
emsec
d9f18d04d6f5427f9daab2f153fe102f3fae6d75
3,299
cpp
C++
InteractionBase/src/handlers/HWebBrowserItem.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
75
2015-01-18T13:29:43.000Z
2022-01-14T08:02:01.000Z
InteractionBase/src/handlers/HWebBrowserItem.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
364
2015-01-06T10:20:21.000Z
2018-12-17T20:12:28.000Z
InteractionBase/src/handlers/HWebBrowserItem.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
14
2015-01-09T00:44:24.000Z
2022-02-22T15:01:44.000Z
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "HWebBrowserItem.h" #include "VisualizationBase/src/items/ViewItem.h" #include "VisualizationBase/src/CustomSceneEvent.h" #include "VisualizationBase/src/VisualizationManager.h" namespace Interaction { HWebBrowserItem::HWebBrowserItem() {} HWebBrowserItem* HWebBrowserItem::instance() { static HWebBrowserItem h; return &h; } void HWebBrowserItem::keyPressEvent(Visualization::Item* target, QKeyEvent *event) { if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_Escape && (!target->parent() || target->parent()->typeId() == Visualization::ViewItem::typeIdStatic())) { auto mainScene = Visualization::VisualizationManager::instance().mainScene(); QApplication::postEvent(mainScene, new Visualization::CustomSceneEvent{[=](){SAFE_DELETE_ITEM(target);}}); } else GenericHandler::keyPressEvent(target, event); // TODO: Is it OK to propagate events to parents or should we just accept all events? //Propagating at least some events is necessary for updating an InfoNode } void HWebBrowserItem::mousePressEvent(Visualization::Item* target, QGraphicsSceneMouseEvent* event) { if (target->parent()) GenericHandler::mousePressEvent(target, event); else HMovableItem::mousePressEvent(target, event); } void HWebBrowserItem::mouseMoveEvent(Visualization::Item* target, QGraphicsSceneMouseEvent* event) { if (target->parent()) GenericHandler::mouseMoveEvent(target, event); else HMovableItem::mouseMoveEvent(target, event); } }
48.514706
120
0.707184
dimitar-asenov
d9f1d5d53ef635cbc1830031389a67d30b6146e9
1,167
cxx
C++
painty/core/test/src/ThreadPoolTest.cxx
lindemeier/painty
792cac6655b3707805ffc68d902f0e675a7770b8
[ "MIT" ]
15
2020-04-22T15:18:28.000Z
2022-03-24T07:48:28.000Z
painty/core/test/src/ThreadPoolTest.cxx
lindemeier/painty
792cac6655b3707805ffc68d902f0e675a7770b8
[ "MIT" ]
25
2020-04-18T18:55:50.000Z
2021-05-30T21:26:39.000Z
painty/core/test/src/ThreadPoolTest.cxx
lindemeier/painty
792cac6655b3707805ffc68d902f0e675a7770b8
[ "MIT" ]
2
2020-09-16T05:55:54.000Z
2021-01-09T12:09:43.000Z
/** * @file ThreadPoolTest.cxx * @author thomas lindemeier * * @brief * * @date 2020-10-20 * */ #include "gtest/gtest.h" #include "painty/core/ThreadPool.hxx" TEST(ThreadPoolTest, Construct) { { painty::ThreadPool singleThread(1U); std::cout << "Hello World from main thread: " << std::this_thread::get_id() << std::endl; std::vector<std::future<void>> futures; for (auto i = 0U; i < 10U; i++) { futures.push_back(singleThread.add_back([]() { std::cout << "Hello World from thread: " << std::this_thread::get_id() << std::endl; })); } for (const auto& f : futures) { f.wait(); } } { painty::ThreadPool multiThread(10U); std::cout << "Hello World from main thread: " << std::this_thread::get_id() << std::endl; std::vector<std::future<void>> futures; for (auto i = 0U; i < 10U; i++) { futures.push_back(multiThread.add_back([]() { std::cout << "Hello World from thread: " << std::this_thread::get_id() << std::endl; })); } for (const auto& f : futures) { f.wait(); } } }
22.018868
79
0.538132
lindemeier
d9f261c82987f6f3bb6b6b2b18753e62122b77d2
23,237
cpp
C++
src/third_party/mozjs-45/extract/js/src/jit/arm64/Assembler-arm64.cpp
EdwardPrentice/wrongo
1e7c9136f5fab7040b5bd5df51b4946876625c88
[ "Apache-2.0" ]
72
2020-06-12T06:33:41.000Z
2021-03-22T03:15:56.000Z
src/third_party/mozjs-45/extract/js/src/jit/arm64/Assembler-arm64.cpp
EdwardPrentice/wrongo
1e7c9136f5fab7040b5bd5df51b4946876625c88
[ "Apache-2.0" ]
9
2020-07-02T09:36:49.000Z
2021-03-25T23:54:00.000Z
src/third_party/mozjs-45/extract/js/src/jit/arm64/Assembler-arm64.cpp
EdwardPrentice/wrongo
1e7c9136f5fab7040b5bd5df51b4946876625c88
[ "Apache-2.0" ]
14
2020-06-12T03:08:03.000Z
2021-02-03T11:43:09.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "jit/arm64/Assembler-arm64.h" #include "mozilla/DebugOnly.h" #include "mozilla/MathAlgorithms.h" #include "jscompartment.h" #include "jsutil.h" #include "gc/Marking.h" #include "jit/arm64/Architecture-arm64.h" #include "jit/arm64/MacroAssembler-arm64.h" #include "jit/ExecutableAllocator.h" #include "jit/JitCompartment.h" using namespace js; using namespace js::jit; using mozilla::CountLeadingZeroes32; using mozilla::DebugOnly; // Note this is used for inter-AsmJS calls and may pass arguments and results // in floating point registers even if the system ABI does not. ABIArg ABIArgGenerator::next(MIRType type) { switch (type) { case MIRType_Int32: case MIRType_Pointer: if (intRegIndex_ == NumIntArgRegs) { current_ = ABIArg(stackOffset_); stackOffset_ += sizeof(uintptr_t); break; } current_ = ABIArg(Register::FromCode(intRegIndex_)); intRegIndex_++; break; case MIRType_Float32: case MIRType_Double: if (floatRegIndex_ == NumFloatArgRegs) { current_ = ABIArg(stackOffset_); stackOffset_ += sizeof(double); break; } current_ = ABIArg(FloatRegister(floatRegIndex_, type == MIRType_Double ? FloatRegisters::Double : FloatRegisters::Single)); floatRegIndex_++; break; default: MOZ_CRASH("Unexpected argument type"); } return current_; } const Register ABIArgGenerator::NonArgReturnReg0 = r8; const Register ABIArgGenerator::NonArgReturnReg1 = r9; const Register ABIArgGenerator::NonVolatileReg = r1; const Register ABIArgGenerator::NonArg_VolatileReg = r13; const Register ABIArgGenerator::NonReturn_VolatileReg0 = r2; const Register ABIArgGenerator::NonReturn_VolatileReg1 = r3; namespace js { namespace jit { void Assembler::finish() { armbuffer_.flushPool(); // The extended jump table is part of the code buffer. ExtendedJumpTable_ = emitExtendedJumpTable(); Assembler::FinalizeCode(); // The jump relocation table starts with a fixed-width integer pointing // to the start of the extended jump table. // Space for this integer is allocated by Assembler::addJumpRelocation() // before writing the first entry. // Don't touch memory if we saw an OOM error. if (jumpRelocations_.length() && !oom()) { MOZ_ASSERT(jumpRelocations_.length() >= sizeof(uint32_t)); *(uint32_t*)jumpRelocations_.buffer() = ExtendedJumpTable_.getOffset(); } } BufferOffset Assembler::emitExtendedJumpTable() { if (!pendingJumps_.length() || oom()) return BufferOffset(); armbuffer_.flushPool(); armbuffer_.align(SizeOfJumpTableEntry); BufferOffset tableOffset = armbuffer_.nextOffset(); for (size_t i = 0; i < pendingJumps_.length(); i++) { // Each JumpTableEntry is of the form: // LDR ip0 [PC, 8] // BR ip0 // [Patchable 8-byte constant low bits] // [Patchable 8-byte constant high bits] DebugOnly<size_t> preOffset = size_t(armbuffer_.nextOffset().getOffset()); ldr(vixl::ip0, ptrdiff_t(8 / vixl::kInstructionSize)); br(vixl::ip0); DebugOnly<size_t> prePointer = size_t(armbuffer_.nextOffset().getOffset()); MOZ_ASSERT_IF(!oom(), prePointer - preOffset == OffsetOfJumpTableEntryPointer); brk(0x0); brk(0x0); DebugOnly<size_t> postOffset = size_t(armbuffer_.nextOffset().getOffset()); MOZ_ASSERT_IF(!oom(), postOffset - preOffset == SizeOfJumpTableEntry); } if (oom()) return BufferOffset(); return tableOffset; } void Assembler::executableCopy(uint8_t* buffer) { // Copy the code and all constant pools into the output buffer. armbuffer_.executableCopy(buffer); // Patch any relative jumps that target code outside the buffer. // The extended jump table may be used for distant jumps. for (size_t i = 0; i < pendingJumps_.length(); i++) { RelativePatch& rp = pendingJumps_[i]; if (!rp.target) { // The patch target is nullptr for jumps that have been linked to // a label within the same code block, but may be repatched later // to jump to a different code block. continue; } Instruction* target = (Instruction*)rp.target; Instruction* branch = (Instruction*)(buffer + rp.offset.getOffset()); JumpTableEntry* extendedJumpTable = reinterpret_cast<JumpTableEntry*>(buffer + ExtendedJumpTable_.getOffset()); if (branch->BranchType() != vixl::UnknownBranchType) { if (branch->IsTargetReachable(target)) { branch->SetImmPCOffsetTarget(target); } else { JumpTableEntry* entry = &extendedJumpTable[i]; branch->SetImmPCOffsetTarget(entry->getLdr()); entry->data = target; } } else { // Currently a two-instruction call, it should be possible to optimize this // into a single instruction call + nop in some instances, but this will work. } } } BufferOffset Assembler::immPool(ARMRegister dest, uint8_t* value, vixl::LoadLiteralOp op, ARMBuffer::PoolEntry* pe) { uint32_t inst = op | Rt(dest); const size_t numInst = 1; const unsigned sizeOfPoolEntryInBytes = 4; const unsigned numPoolEntries = sizeof(value) / sizeOfPoolEntryInBytes; return allocEntry(numInst, numPoolEntries, (uint8_t*)&inst, value, pe); } BufferOffset Assembler::immPool64(ARMRegister dest, uint64_t value, ARMBuffer::PoolEntry* pe) { return immPool(dest, (uint8_t*)&value, vixl::LDR_x_lit, pe); } BufferOffset Assembler::immPool64Branch(RepatchLabel* label, ARMBuffer::PoolEntry* pe, Condition c) { MOZ_CRASH("immPool64Branch"); } BufferOffset Assembler::fImmPool(ARMFPRegister dest, uint8_t* value, vixl::LoadLiteralOp op) { uint32_t inst = op | Rt(dest); const size_t numInst = 1; const unsigned sizeOfPoolEntryInBits = 32; const unsigned numPoolEntries = dest.size() / sizeOfPoolEntryInBits; return allocEntry(numInst, numPoolEntries, (uint8_t*)&inst, value); } BufferOffset Assembler::fImmPool64(ARMFPRegister dest, double value) { return fImmPool(dest, (uint8_t*)&value, vixl::LDR_d_lit); } BufferOffset Assembler::fImmPool32(ARMFPRegister dest, float value) { return fImmPool(dest, (uint8_t*)&value, vixl::LDR_s_lit); } void Assembler::bind(Label* label, BufferOffset targetOffset) { // Nothing has seen the label yet: just mark the location. // If we've run out of memory, don't attempt to modify the buffer which may // not be there. Just mark the label as bound to the (possibly bogus) // targetOffset. if (!label->used() || oom()) { label->bind(targetOffset.getOffset()); return; } // Get the most recent instruction that used the label, as stored in the label. // This instruction is the head of an implicit linked list of label uses. BufferOffset branchOffset(label); while (branchOffset.assigned()) { // Before overwriting the offset in this instruction, get the offset of // the next link in the implicit branch list. BufferOffset nextOffset = NextLink(branchOffset); // Linking against the actual (Instruction*) would be invalid, // since that Instruction could be anywhere in memory. // Instead, just link against the correct relative offset, assuming // no constant pools, which will be taken into consideration // during finalization. ptrdiff_t relativeByteOffset = targetOffset.getOffset() - branchOffset.getOffset(); Instruction* link = getInstructionAt(branchOffset); // This branch may still be registered for callbacks. Stop tracking it. vixl::ImmBranchType branchType = link->BranchType(); vixl::ImmBranchRangeType branchRange = Instruction::ImmBranchTypeToRange(branchType); if (branchRange < vixl::NumShortBranchRangeTypes) { BufferOffset deadline(branchOffset.getOffset() + Instruction::ImmBranchMaxForwardOffset(branchRange)); armbuffer_.unregisterBranchDeadline(branchRange, deadline); } // Is link able to reach the label? if (link->IsPCRelAddressing() || link->IsTargetReachable(link + relativeByteOffset)) { // Write a new relative offset into the instruction. link->SetImmPCOffsetTarget(link + relativeByteOffset); } else { // This is a short-range branch, and it can't reach the label directly. // Verify that it branches to a veneer: an unconditional branch. MOZ_ASSERT(getInstructionAt(nextOffset)->BranchType() == vixl::UncondBranchType); } branchOffset = nextOffset; } // Bind the label, so that future uses may encode the offset immediately. label->bind(targetOffset.getOffset()); } void Assembler::bind(RepatchLabel* label) { // Nothing has seen the label yet: just mark the location. // If we've run out of memory, don't attempt to modify the buffer which may // not be there. Just mark the label as bound to nextOffset(). if (!label->used() || oom()) { label->bind(nextOffset().getOffset()); return; } int branchOffset = label->offset(); Instruction* inst = getInstructionAt(BufferOffset(branchOffset)); inst->SetImmPCOffsetTarget(inst + nextOffset().getOffset() - branchOffset); } void Assembler::trace(JSTracer* trc) { for (size_t i = 0; i < pendingJumps_.length(); i++) { RelativePatch& rp = pendingJumps_[i]; if (rp.kind == Relocation::JITCODE) { JitCode* code = JitCode::FromExecutable((uint8_t*)rp.target); TraceManuallyBarrieredEdge(trc, &code, "masmrel32"); MOZ_ASSERT(code == JitCode::FromExecutable((uint8_t*)rp.target)); } } // TODO: Trace. #if 0 if (tmpDataRelocations_.length()) ::TraceDataRelocations(trc, &armbuffer_, &tmpDataRelocations_); #endif } void Assembler::addJumpRelocation(BufferOffset src, Relocation::Kind reloc) { // Only JITCODE relocations are patchable at runtime. MOZ_ASSERT(reloc == Relocation::JITCODE); // The jump relocation table starts with a fixed-width integer pointing // to the start of the extended jump table. But, we don't know the // actual extended jump table offset yet, so write a 0 which we'll // patch later in Assembler::finish(). if (!jumpRelocations_.length()) jumpRelocations_.writeFixedUint32_t(0); // Each entry in the table is an (offset, extendedTableIndex) pair. jumpRelocations_.writeUnsigned(src.getOffset()); jumpRelocations_.writeUnsigned(pendingJumps_.length()); } void Assembler::addPendingJump(BufferOffset src, ImmPtr target, Relocation::Kind reloc) { MOZ_ASSERT(target.value != nullptr); if (reloc == Relocation::JITCODE) addJumpRelocation(src, reloc); // This jump is not patchable at runtime. Extended jump table entry requirements // cannot be known until finalization, so to be safe, give each jump and entry. // This also causes GC tracing of the target. enoughMemory_ &= pendingJumps_.append(RelativePatch(src, target.value, reloc)); } size_t Assembler::addPatchableJump(BufferOffset src, Relocation::Kind reloc) { MOZ_CRASH("TODO: This is currently unused (and untested)"); if (reloc == Relocation::JITCODE) addJumpRelocation(src, reloc); size_t extendedTableIndex = pendingJumps_.length(); enoughMemory_ &= pendingJumps_.append(RelativePatch(src, nullptr, reloc)); return extendedTableIndex; } void PatchJump(CodeLocationJump& jump_, CodeLocationLabel label, ReprotectCode reprotect) { MOZ_CRASH("PatchJump"); } void Assembler::PatchDataWithValueCheck(CodeLocationLabel label, PatchedImmPtr newValue, PatchedImmPtr expected) { Instruction* i = (Instruction*)label.raw(); void** pValue = i->LiteralAddress<void**>(); MOZ_ASSERT(*pValue == expected.value); *pValue = newValue.value; } void Assembler::PatchDataWithValueCheck(CodeLocationLabel label, ImmPtr newValue, ImmPtr expected) { PatchDataWithValueCheck(label, PatchedImmPtr(newValue.value), PatchedImmPtr(expected.value)); } void Assembler::ToggleToJmp(CodeLocationLabel inst_) { Instruction* i = (Instruction*)inst_.raw(); MOZ_ASSERT(i->IsAddSubImmediate()); // Refer to instruction layout in ToggleToCmp(). int imm19 = (int)i->Bits(23, 5); MOZ_ASSERT(vixl::is_int19(imm19)); b(i, imm19, Always); } void Assembler::ToggleToCmp(CodeLocationLabel inst_) { Instruction* i = (Instruction*)inst_.raw(); MOZ_ASSERT(i->IsCondB()); int imm19 = i->ImmCondBranch(); // bit 23 is reserved, and the simulator throws an assertion when this happens // It'll be messy to decode, but we can steal bit 30 or bit 31. MOZ_ASSERT(vixl::is_int18(imm19)); // 31 - 64-bit if set, 32-bit if unset. (OK!) // 30 - sub if set, add if unset. (OK!) // 29 - SetFlagsBit. Must be set. // 22:23 - ShiftAddSub. (OK!) // 10:21 - ImmAddSub. (OK!) // 5:9 - First source register (Rn). (OK!) // 0:4 - Destination Register. Must be xzr. // From the above, there is a safe 19-bit contiguous region from 5:23. Emit(i, vixl::ThirtyTwoBits | vixl::AddSubImmediateFixed | vixl::SUB | Flags(vixl::SetFlags) | Rd(vixl::xzr) | (imm19 << vixl::Rn_offset)); } void Assembler::ToggleCall(CodeLocationLabel inst_, bool enabled) { const Instruction* first = reinterpret_cast<Instruction*>(inst_.raw()); Instruction* load; Instruction* call; // There might be a constant pool at the very first instruction. first = first->skipPool(); // Skip the stack pointer restore instruction. if (first->IsStackPtrSync()) first = first->InstructionAtOffset(vixl::kInstructionSize)->skipPool(); load = const_cast<Instruction*>(first); // The call instruction follows the load, but there may be an injected // constant pool. call = const_cast<Instruction*>(load->InstructionAtOffset(vixl::kInstructionSize)->skipPool()); if (call->IsBLR() == enabled) return; if (call->IsBLR()) { // If the second instruction is blr(), then wehave: // ldr x17, [pc, offset] // blr x17 MOZ_ASSERT(load->IsLDR()); // We want to transform this to: // adr xzr, [pc, offset] // nop int32_t offset = load->ImmLLiteral(); adr(load, xzr, int32_t(offset)); nop(call); } else { // We have: // adr xzr, [pc, offset] (or ldr x17, [pc, offset]) // nop MOZ_ASSERT(load->IsADR() || load->IsLDR()); MOZ_ASSERT(call->IsNOP()); // Transform this to: // ldr x17, [pc, offset] // blr x17 int32_t offset = (int)load->ImmPCRawOffset(); MOZ_ASSERT(vixl::is_int19(offset)); ldr(load, ScratchReg2_64, int32_t(offset)); blr(call, ScratchReg2_64); } } class RelocationIterator { CompactBufferReader reader_; uint32_t tableStart_; uint32_t offset_; uint32_t extOffset_; public: explicit RelocationIterator(CompactBufferReader& reader) : reader_(reader) { // The first uint32_t stores the extended table offset. tableStart_ = reader_.readFixedUint32_t(); } bool read() { if (!reader_.more()) return false; offset_ = reader_.readUnsigned(); extOffset_ = reader_.readUnsigned(); return true; } uint32_t offset() const { return offset_; } uint32_t extendedOffset() const { return extOffset_; } }; static JitCode* CodeFromJump(JitCode* code, uint8_t* jump) { const Instruction* inst = (const Instruction*)jump; uint8_t* target; // We're expecting a call created by MacroAssembler::call(JitCode*). // It looks like: // // ldr scratch, [pc, offset] // blr scratch // // If the call has been toggled by ToggleCall(), it looks like: // // adr xzr, [pc, offset] // nop // // There might be a constant pool at the very first instruction. // See also ToggleCall(). inst = inst->skipPool(); // Skip the stack pointer restore instruction. if (inst->IsStackPtrSync()) inst = inst->InstructionAtOffset(vixl::kInstructionSize)->skipPool(); if (inst->BranchType() != vixl::UnknownBranchType) { // This is an immediate branch. target = (uint8_t*)inst->ImmPCOffsetTarget(); } else if (inst->IsLDR()) { // This is an ldr+blr call that is enabled. See ToggleCall(). mozilla::DebugOnly<const Instruction*> nextInst = inst->InstructionAtOffset(vixl::kInstructionSize)->skipPool(); MOZ_ASSERT(nextInst->IsNOP() || nextInst->IsBLR()); target = (uint8_t*)inst->Literal64(); } else if (inst->IsADR()) { // This is a disabled call: adr+nop. See ToggleCall(). mozilla::DebugOnly<const Instruction*> nextInst = inst->InstructionAtOffset(vixl::kInstructionSize)->skipPool(); MOZ_ASSERT(nextInst->IsNOP()); ptrdiff_t offset = inst->ImmPCRawOffset() << vixl::kLiteralEntrySizeLog2; // This is what Literal64 would do with the corresponding ldr. memcpy(&target, inst + offset, sizeof(target)); } else { MOZ_CRASH("Unrecognized jump instruction."); } // If the jump is within the code buffer, it uses the extended jump table. if (target >= code->raw() && target < code->raw() + code->instructionsSize()) { MOZ_ASSERT(target + Assembler::SizeOfJumpTableEntry <= code->raw() + code->instructionsSize()); uint8_t** patchablePtr = (uint8_t**)(target + Assembler::OffsetOfJumpTableEntryPointer); target = *patchablePtr; } return JitCode::FromExecutable(target); } void Assembler::TraceJumpRelocations(JSTracer* trc, JitCode* code, CompactBufferReader& reader) { RelocationIterator iter(reader); while (iter.read()) { JitCode* child = CodeFromJump(code, code->raw() + iter.offset()); TraceManuallyBarrieredEdge(trc, &child, "rel32"); MOZ_ASSERT(child == CodeFromJump(code, code->raw() + iter.offset())); } } static void TraceDataRelocations(JSTracer* trc, uint8_t* buffer, CompactBufferReader& reader) { while (reader.more()) { size_t offset = reader.readUnsigned(); Instruction* load = (Instruction*)&buffer[offset]; // The only valid traceable operation is a 64-bit load to an ARMRegister. // Refer to movePatchablePtr() for generation. MOZ_ASSERT(load->Mask(vixl::LoadLiteralMask) == vixl::LDR_x_lit); uintptr_t* literalAddr = load->LiteralAddress<uintptr_t*>(); uintptr_t literal = *literalAddr; // All pointers on AArch64 will have the top bits cleared. // If those bits are not cleared, this must be a Value. if (literal >> JSVAL_TAG_SHIFT) { jsval_layout layout; layout.asBits = literal; Value v = IMPL_TO_JSVAL(layout); TraceManuallyBarrieredEdge(trc, &v, "ion-masm-value"); *literalAddr = JSVAL_TO_IMPL(v).asBits; // TODO: When we can, flush caches here if a pointer was moved. continue; } // No barriers needed since the pointers are constants. TraceManuallyBarrieredGenericPointerEdge(trc, reinterpret_cast<gc::Cell**>(literalAddr), "ion-masm-ptr"); // TODO: Flush caches at end? } } void Assembler::TraceDataRelocations(JSTracer* trc, JitCode* code, CompactBufferReader& reader) { ::TraceDataRelocations(trc, code->raw(), reader); } void Assembler::FixupNurseryObjects(JSContext* cx, JitCode* code, CompactBufferReader& reader, const ObjectVector& nurseryObjects) { MOZ_ASSERT(!nurseryObjects.empty()); uint8_t* buffer = code->raw(); bool hasNurseryPointers = false; while (reader.more()) { size_t offset = reader.readUnsigned(); Instruction* ins = (Instruction*)&buffer[offset]; uintptr_t* literalAddr = ins->LiteralAddress<uintptr_t*>(); uintptr_t literal = *literalAddr; if (literal >> JSVAL_TAG_SHIFT) continue; // This is a Value. if (!(literal & 0x1)) continue; uint32_t index = literal >> 1; JSObject* obj = nurseryObjects[index]; *literalAddr = uintptr_t(obj); // Either all objects are still in the nursery, or all objects are tenured. MOZ_ASSERT_IF(hasNurseryPointers, IsInsideNursery(obj)); if (!hasNurseryPointers && IsInsideNursery(obj)) hasNurseryPointers = true; } if (hasNurseryPointers) cx->runtime()->gc.storeBuffer.putWholeCell(code); } void Assembler::PatchInstructionImmediate(uint8_t* code, PatchedImmPtr imm) { MOZ_CRASH("PatchInstructionImmediate()"); } void Assembler::UpdateBoundsCheck(uint32_t heapSize, Instruction* inst) { int32_t mask = ~(heapSize - 1); unsigned n, imm_s, imm_r; if (!IsImmLogical(mask, 32, &n, &imm_s, &imm_r)) MOZ_CRASH("Could not encode immediate!?"); inst->SetImmR(imm_r); inst->SetImmS(imm_s); inst->SetBitN(n); } void Assembler::retarget(Label* label, Label* target) { if (label->used()) { if (target->bound()) { bind(label, BufferOffset(target)); } else if (target->used()) { // The target is not bound but used. Prepend label's branch list // onto target's. BufferOffset labelBranchOffset(label); // Find the head of the use chain for label. BufferOffset next = NextLink(labelBranchOffset); while (next.assigned()) { labelBranchOffset = next; next = NextLink(next); } // Then patch the head of label's use chain to the tail of target's // use chain, prepending the entire use chain of target. SetNextLink(labelBranchOffset, BufferOffset(target)); target->use(label->offset()); } else { // The target is unbound and unused. We can just take the head of // the list hanging off of label, and dump that into target. DebugOnly<uint32_t> prev = target->use(label->offset()); MOZ_ASSERT((int32_t)prev == Label::INVALID_OFFSET); } } label->reset(); } } // namespace jit } // namespace js
33.823872
103
0.649438
EdwardPrentice
d9f5287e841f12ba254ead77dac377cbbbed193a
1,027
hpp
C++
src/xrGame/LevelGraphDebugRender.hpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
2
2015-02-23T10:43:02.000Z
2015-06-11T14:45:08.000Z
src/xrGame/LevelGraphDebugRender.hpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
17
2022-01-25T08:58:23.000Z
2022-03-28T17:18:28.000Z
src/xrGame/LevelGraphDebugRender.hpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
1
2015-06-05T20:04:00.000Z
2015-06-05T20:04:00.000Z
#pragma once #ifdef DEBUG #include "xrCore/xrCore.h" #include "Include/xrRender/DebugShader.h" class CGameGraph; class CLevelGraph; class CCoverPoint; class LevelGraphDebugRender { private: CGameGraph* gameGraph; CLevelGraph* levelGraph; debug_shader debugShader; int currentLevelId; bool currentActual; Fvector currentCenter; Fvector currentRadius; xr_vector<CCoverPoint*> coverPointCache; private: Fvector ConvertPosition(const Fvector& pos); void DrawEdge(int vid1, int vid2); void DrawVertex(int vid); void DrawStalkers(int vid); void DrawObjects(int vid); void UpdateCurrentInfo(); void DrawNodes(); void DrawRestrictions(); void DrawCovers(); void DrawGameGraph(); void DrawObjects(); void DrawDebugNode(); void Modify(int vid, Fbox& bbox); public: LevelGraphDebugRender(); ~LevelGraphDebugRender(); void SetupCurrentLevel(int levelId); void Render(CGameGraph& gameGraph, CLevelGraph& levelGraph); }; #endif // DEBUG
23.340909
64
0.719572
clayne
d9f52f06a2cef864a54e8a7fe3d34112f354a7ae
318
cpp
C++
Ass3/Q4.cpp
nitishgarg2002/DSA-assignments
34ec3e77e6bb00bc2ab86d2960a18d9e53300c06
[ "MIT" ]
null
null
null
Ass3/Q4.cpp
nitishgarg2002/DSA-assignments
34ec3e77e6bb00bc2ab86d2960a18d9e53300c06
[ "MIT" ]
null
null
null
Ass3/Q4.cpp
nitishgarg2002/DSA-assignments
34ec3e77e6bb00bc2ab86d2960a18d9e53300c06
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int factorial(int n){ if (n == 0) return 1; return n * factorial(n - 1); } int nCr(int n,int r){ return factorial(n) / (factorial(r) * factorial(n - r)); } int main() { int n,r; cin>>n>>r; if(n>=r){ cout<<nCr(n,r); } else { cout<<"Invalid values"; } }
14.454545
57
0.562893
nitishgarg2002
d9f5dac229134746071f859ba31ca5650c3c6390
2,558
cpp
C++
firmware/robot2015/hw-test/i2c-test.cpp
JNeiger/robocup-firmware
c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e
[ "Apache-2.0" ]
1
2018-09-25T20:28:58.000Z
2018-09-25T20:28:58.000Z
firmware/robot2015/hw-test/i2c-test.cpp
JNeiger/robocup-firmware
c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e
[ "Apache-2.0" ]
null
null
null
firmware/robot2015/hw-test/i2c-test.cpp
JNeiger/robocup-firmware
c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e
[ "Apache-2.0" ]
null
null
null
#include <mbed.h> #include <rtos.h> #include <vector> #include <algorithm> #include <helper-funcs.hpp> #include "robot-devices.hpp" DigitalOut good(LED1, 0); DigitalOut bad1(LED2, 0); DigitalOut bad2(LED3, 0); DigitalOut pwr(LED4, 1); Serial pc(RJ_SERIAL_RXTX); I2C i2c(RJ_I2C_BUS); bool testPass = false; bool batchedResult = false; std::vector<unsigned int> freq1; std::vector<unsigned int> freq2; int main() { char buf[2] = {0x00}; pc.baud(57600); pc.printf("START========= STARTING TEST =========\r\n\r\n"); pwr = 0; RtosTimer live_light(imAlive, osTimerPeriodic, (void*)&pwr); live_light.start(250); pc.printf("-- Testing address space using 100kHz\r\n"); // Test on low bus frequency i2c.frequency(100000); for (unsigned int i = 0; i < 0xFF; i++) { bool ack, nack = false; ack = i2c.write(i); nack = i2c.read(i, buf, 2); if (ack && !nack) { freq1.push_back(i); } } pc.printf("-- Testing address space using 400kHz\r\n"); // Test on high bus frequency i2c.frequency(400000); for (unsigned int i = 0; i < 0xFF; i++) { bool ack, nack = false; ack = i2c.write(i); nack = i2c.read(i, buf, 2); if (ack && !nack) { freq2.push_back(i); } } // Test results pc.printf("\r\n100kHz Test:\t%s\r\n", freq1.empty() ? "FAIL" : "PASS"); pc.printf("400kHz Test:\t%s\r\n", freq2.empty() ? "FAIL" : "PASS"); // Merge the 2 vectors together & remove duplicate values freq1.insert(freq1.end(), freq2.begin(), freq2.end()); sort(freq1.begin(), freq1.end()); freq1.erase(unique(freq1.begin(), freq1.end()), freq1.end()); pc.printf("ADDRS PASS:\t%u\r\nADDRS FAIL:\t%u\r\n", freq1.size(), 0xFF - freq1.size()); if (freq1.size() > 0xF0) { batchedResult = true; } for (std::vector<unsigned int>::iterator it = freq1.begin(); it != freq1.end(); ++it) pc.printf(" 0x%02X\r\n", *it); // Final results of the test testPass = (!freq1.empty()) && (!batchedResult); pc.printf("\r\n=================================\r\n"); pc.printf("========== TEST %s ==========\r\n", testPass ? "PASSED" : "FAILED"); pc.printf("=================================DONE"); // Turn on the corresponding LED(s) good = testPass; bad1 = !testPass; bad2 = !testPass; live_light.stop(); pwr = testPass; while (true) { // Never return wait(2.0); } }
24.834951
75
0.543002
JNeiger
d9f8e71da0995d3e41d80a2ba36c51c5d7e6c6f1
831
cpp
C++
BaekJoon/14569.cpp
falconlee236/Algorithm_Practice
4e6e380a0e6c840525ca831a05c35253eeaaa25c
[ "MIT" ]
null
null
null
BaekJoon/14569.cpp
falconlee236/Algorithm_Practice
4e6e380a0e6c840525ca831a05c35253eeaaa25c
[ "MIT" ]
null
null
null
BaekJoon/14569.cpp
falconlee236/Algorithm_Practice
4e6e380a0e6c840525ca831a05c35253eeaaa25c
[ "MIT" ]
null
null
null
/*14569*/ /*Got it!*/ /*39:42*/ #include <iostream> using namespace std; typedef unsigned long long ull; int main(){ ios_base::sync_with_stdio(false); cin.tie(0); ull sub[1001] = {0, }; ull student[10001] = {0, }; int n; cin >> n; for(int i = 0; i < n; i++){ int num; cin >> num; for(int j = 0; j < num; j++){ int p; cin >> p; sub[i] |= ((ull)1 << p); } } int m; cin >> m; for(int i = 0; i < m; i++){ int num; cin >> num; for(int j = 0; j < num; j++){ int p; cin >> p; student[i] |= ((ull)1 << p); } } for(int i = 0; i < m; i++){ int ans = 0; for(int j = 0; j < n; j++){ if(sub[j] == (student[i] & sub[j])) ans++; } cout << ans << "\n"; } }
22.459459
54
0.391095
falconlee236
d9f9d9d60882dde41977388426afaf1aadf52383
1,285
cpp
C++
PRACTICE/KPRIME.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
PRACTICE/KPRIME.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
PRACTICE/KPRIME.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; /* OBJECTIVE:- The game is called Count K-Primes. A number is a k-prime if it has exactly k distinct prime factors. The game is quite simple. Alice will give three numbers A, B & K to Bob. Bob needs to tell Alice the number of K-prime numbers between A & B (both inclusive). If Bob gives the correct answer, he gets a point. If not, Alice gets a point. They play this game T times. INPUT:- First line of input contains a single integer T, the number of times they play. Each game is described in a single line containing the three numbers A,B & K. OUTPUT:- For each game, output on a separate line the number of K-primes between A & B. Constraints: 1 ≤ T ≤ 10000 2 ≤ A ≤ B ≤ 100000 1 ≤ K ≤ 5 */ int main() { int rounds=1; cin>> rounds; while(rounds--) { int a,b,kp; a=b=kp=0; cin>>a>>b>>kp; int p_factors[b+1] = { 0 }; int count=0; for (int p = 2; p <= b; p++) if (p_factors[p] == 0) for (int i = p; i <= b; i += p) p_factors[i]++; for (int i = a; i <= b; i++) if (p_factors[i] == kp) count++; cout<<count<<endl; } return 0; }
23.796296
101
0.557198
prasantmahato
d9fa353463b6068760b36ddb7ff99c0df133ebca
1,956
cpp
C++
src/apps/orbiter/orbiter.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-10-27T15:18:28.000Z
2022-02-09T11:13:07.000Z
src/apps/orbiter/orbiter.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
4
2019-12-09T11:49:11.000Z
2020-07-30T17:34:45.000Z
src/apps/orbiter/orbiter.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-06-10T20:05:30.000Z
2020-12-18T04:59:19.000Z
// orbiter.cpp // // by Anton Betten // // started: 4/3/2020 // #include "orbiter.h" using namespace std; using namespace orbiter; using namespace orbiter::top_level; int build_number = #include "../../../build_number" ; int main(int argc, const char **argv) { //cout << "orbiter.out main" << endl; orbiter_top_level_session Top_level_session; int i; The_Orbiter_top_level_session = &Top_level_session; // setup: cout << "Welcome to Orbiter! Your build number is " << build_number << "." << endl; cout << "A user's guide is available here: " << endl; cout << "https://www.math.colostate.edu/~betten/orbiter/users_guide.pdf" << endl; cout << "The sources are available here: " << endl; cout << "https://github.com/abetten/orbiter" << endl; cout << "An example makefile with many commands from the user's guide is here: " << endl; cout << "https://github.com/abetten/orbiter/tree/master/examples/users_guide/makefile" << endl; #ifdef SYSTEMUNIX cout << "SYSTEMUNIX is defined" << endl; #endif #ifdef SYSTEMWINDOWS cout << "SYSTEMWINDOWS is defined" << endl; #endif #ifdef SYSTEM_IS_MACINTOSH cout << "SYSTEM_IS_MACINTOSH is defined" << endl; #endif cout << "sizeof(int)=" << sizeof(int) << endl; cout << "sizeof(long int)=" << sizeof(long int) << endl; std::string *Argv; string_tools ST; ST.convert_arguments(argc, argv, Argv); // argc has changed! i = Top_level_session.startup_and_read_arguments(argc, Argv, 1); int verbose_level; verbose_level = Top_level_session.Orbiter_session->verbose_level; //int f_v = (verbose_level > 1); if (FALSE) { cout << "main, before Top_level_session.handle_everything" << endl; } Top_level_session.handle_everything(argc, Argv, i, verbose_level); if (FALSE) { cout << "main, after Top_level_session.handle_everything" << endl; } cout << "Orbiter session is finished." << endl; cout << "User time: "; the_end(Top_level_session.Orbiter_session->t0); }
21.494505
96
0.692229
abetten
d9faa845153642cf03657a1c95a0f4b2ae74fe51
516
cpp
C++
src/drawablecomponentmanager.cpp
sch-gamedev/hentes
7381ebc25d0db4ad528deb876afe81059d7e2118
[ "Zlib" ]
1
2018-08-01T12:16:45.000Z
2018-08-01T12:16:45.000Z
src/drawablecomponentmanager.cpp
sch-gamedev/hentes
7381ebc25d0db4ad528deb876afe81059d7e2118
[ "Zlib" ]
null
null
null
src/drawablecomponentmanager.cpp
sch-gamedev/hentes
7381ebc25d0db4ad528deb876afe81059d7e2118
[ "Zlib" ]
null
null
null
/* Copyright (C) 2012 KSZK GameDev * For conditions of distribution and use, see copyright notice in main.cpp */ #include "drawablecomponentmanager.h" void DrawableComponentManager::Update() { RemoveMarkedComponents(); for( std::list<DrawableComponent*>::iterator i = Components.begin(); i != Components.end(); i++ ) { (*i)->Update(); } } void DrawableComponentManager::Draw() { for( std::list<DrawableComponent*>::iterator i = Components.begin(); i != Components.end(); i++ ) { (*i)->Draw(); } }
22.434783
98
0.676357
sch-gamedev
d9fb4dca8d35aa85aa05ffcd83a90fd7ac520370
857
hpp
C++
resources/kate/flow/execs/Compiler.hpp
advancedwebdeveloper/flow9
26e19216495bcb948d00aaea6b5c190e30fc6e3f
[ "MIT" ]
null
null
null
resources/kate/flow/execs/Compiler.hpp
advancedwebdeveloper/flow9
26e19216495bcb948d00aaea6b5c190e30fc6e3f
[ "MIT" ]
null
null
null
resources/kate/flow/execs/Compiler.hpp
advancedwebdeveloper/flow9
26e19216495bcb948d00aaea6b5c190e30fc6e3f
[ "MIT" ]
null
null
null
#pragma once #include <QDir> #include "Runner.hpp" namespace flow { struct Compiler { Compiler(QString file, QString flowdir); enum Type { FLOW, FLOWC1, FLOWC2, DEFAULT = FLOW }; Type type() const { return type_; } QStringList includeArgs() const; QStringList debugArgs(Runner) const; QStringList targetArgs(Runner) const; QStringList compileArgs(QString) const; QString invocation() const; QString flowfile() const { return file_; } QString flowdir() const { return flowdir_; } QString confdir() const { return confFile_.dir().path(); } QFileInfo confFile() const { return confFile_; } QString include() const { return include_; } QString compiler() const; const ConfigFile& config() const { return config_; } private: Type type_; QString file_; QString include_; QString flowdir_; QFileInfo confFile_; ConfigFile config_; }; }
25.205882
59
0.733956
advancedwebdeveloper
d9ff35ef9a0cb951f1957346dd6f86098a62ef18
13,926
cpp
C++
src/misaxx-tissue/algorithms/segmentation2d/segmentation2d_klingberg_1.cpp
applied-systems-biology/misaxx-tissue
47c18547c7b5692d427a4e0d34432c9497668f04
[ "BSD-2-Clause" ]
null
null
null
src/misaxx-tissue/algorithms/segmentation2d/segmentation2d_klingberg_1.cpp
applied-systems-biology/misaxx-tissue
47c18547c7b5692d427a4e0d34432c9497668f04
[ "BSD-2-Clause" ]
null
null
null
src/misaxx-tissue/algorithms/segmentation2d/segmentation2d_klingberg_1.cpp
applied-systems-biology/misaxx-tissue
47c18547c7b5692d427a4e0d34432c9497668f04
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright by Ruman Gerst * Research Group Applied Systems Biology - Head: Prof. Dr. Marc Thilo Figge * https://www.leibniz-hki.de/en/applied-systems-biology.html * HKI-Center for Systems Biology of Infection * Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Insitute (HKI) * Adolf-Reichwein-Straße 23, 07745 Jena, Germany * * This code is licensed under BSD 2-Clause * See the LICENSE file provided with this code for the full license. */ #include "segmentation2d_klingberg_1.h" #include <misaxx/ome/attachments/misa_ome_pixel_count.h> using namespace misaxx; using namespace misaxx::ome; using namespace misaxx_tissue; namespace cv::images { using mask = cv::Mat1b; using grayscale32f = cv::Mat1f; using labels = cv::Mat1i; } namespace { template<typename T> std::vector<T> get_sorted_pixels(const cv::Mat_<T> &img) { std::vector<T> pixels; pixels.reserve(img.rows * img.cols); for(int y = 0; y < img.rows; ++y) { const auto *row = img[y]; for(int x = 0; x < img.cols; ++x) { pixels.push_back(row[x]); } } std::sort(pixels.begin(), pixels.end()); return pixels; } /** * Gets percentiles (linear interpolation) * @tparam T * @param pixels * @param percentiles * @return */ template<typename T> std::vector<double> get_percentiles(const std::vector<T> &pixels, const std::vector<double> &percentiles) { std::vector<double> result; for(double percentile : percentiles) { double rank = percentile / 100.0 * (pixels.size() - 1); size_t lower_rank = static_cast<size_t>(std::floor(rank)); size_t higher_rank = static_cast<size_t>(std::ceil(rank)); double frac = rank - lower_rank; // fractional section double p = pixels[lower_rank] + (pixels[higher_rank] - pixels[lower_rank]) * frac; result.push_back(p); } return result; } double get_max_value(const cv::Mat &img) { double max; cv::minMaxLoc(img, nullptr, &max); return max; } void normalize_by_max(cv::images::mask &img) { const double max = get_max_value(img); for(int y = 0; y < img.rows; ++y) { auto *row = img[y]; for(int x = 0; x < img.cols; ++x) { row[x] = static_cast<uchar>(row[x] * 255.0 / max); } } } void normalize_by_max(cv::images::grayscale32f &img) { const double max = get_max_value(img); for(int y = 0; y < img.rows; ++y) { auto *row = img[y]; for(int x = 0; x < img.cols; ++x) { row[x] = static_cast<float>(row[x] / max); } } } // void normalize_by_minmax(cv::images::mask &img) { // double dmin; // double dmax; // cv::minMaxLoc(img, &dmin, &dmax); // for(int y = 0; y < img.rows; ++y) { // auto *row = img[y]; // for(int x = 0; x < img.cols; ++x) { // row[x] = static_cast<uchar>(std::clamp((row[x] - dmin) / (dmax - dmin) * 255, 0.0, 255.0)); // } // } // } // void normalize_by_percentile_and_min_signal(cv::images::mask &img, double percentile, double min_signal) { // if(percentile < 100) { // const auto pixels = get_sorted_pixels(img); // auto percentiles = get_percentiles(pixels, { percentile, 100.0 - percentile }); // double upper_percentile = percentiles[0]; // double lower_percentile = percentiles[1]; // // if(upper_percentile > min_signal) { // img = img - lower_percentile; // cv::threshold(img.clone(), img, upper_percentile - lower_percentile, 0, cv::THRESH_TRUNC); // normalize_by_max(img); // } // else { // img = 0; // } // } // else { // if(get_max_value(img) < min_signal) { // img = 0; // } // else { // // Percentile converges to max(image) with increasing percentile // // Collapses into MINMAX normalization // normalize_by_minmax(img); // } // } // } void remove_low_average_intensity_objects(cv::images::mask &img_mask, const cv::images::grayscale32f &img_reference, float min_intensity) { cv::images::labels objects; cv::connectedComponents(img_mask, objects, 4, CV_32S); std::unordered_map<int, float> counts; std::unordered_map<int, float> intensities; for(int y = 0; y < objects.rows; ++y) { const int *row = objects[y]; const float *row_reference = img_reference[y]; for (int x = 0; x < objects.cols; ++x) { if (row[x] > 0) { counts[row[x]] += 1; intensities[row[x]] += row_reference[x]; } } } for(int y = 0; y < objects.rows; ++y) { const int *row = objects[y]; uchar *row_mask = img_mask[y]; for (int x = 0; x < objects.cols; ++x) { if (row[x] > 0) { float mean = intensities[row[x]] / counts[row[x]]; // std::cout << std::to_string(mean) << " < " << std::to_string(min_intensity) << std::endl; if(mean < min_intensity) row_mask[x] = 0; } } } } cv::images::grayscale32f get_as_grayscale_float_copy(const cv::Mat &img) { if(img.type() == CV_32F) { return img.clone(); } else if(img.type() == CV_64F) { cv::images::grayscale32f result; img.convertTo(result, CV_32F, 1); return result; } else if(img.type() == CV_8U) { cv::images::grayscale32f result; img.convertTo(result, CV_32F, 1.0 / 255.0); return result; } else if(img.type() == CV_16U) { cv::images::grayscale32f result; img.convertTo(result, CV_32F, 1.0 / std::numeric_limits<ushort>::max()); return result; } else { throw std::runtime_error("Unsupported image depth: " + std::to_string(img.type())); } } void close_holes(cv::images::mask &img) { using T = uchar; const uchar white = 255; const uchar black = 0; cv::images::mask buffer { img.size(), 0 }; std::vector<cv::Point> neighbors; neighbors.emplace_back(cv::Point(-1,0)); neighbors.emplace_back(cv::Point(1,0)); neighbors.emplace_back(cv::Point(0,1)); neighbors.emplace_back(cv::Point(0,-1)); std::stack<cv::Point> stack; // Find the points in x direction (1st dimension) cv::Point pos(0,0); int rows = img.rows; int cols = img.cols; for(int i = 0; i < rows; ++i) { pos.x = 0; if(img.at<T>(pos) == 0 && buffer.at<T>(pos) == 0) { buffer.at<T>(pos) = white; stack.push(pos); } pos.x = cols - 1; if(img.at<T>(pos) == 0 && buffer.at<T>(pos) == 0) { buffer.at<T>(pos) = white; stack.push(pos); } // Increase counter of y if(pos.y < rows) { ++pos.y; } else { pos.y = 0; } } pos = cv::Point(0,0); // Find the points in y direction (2nd dimension) for(int i = 0; i < cols; ++i) { pos.y = 0; if(img.at<T>(pos) == 0 && buffer.at<T>(pos) == 0) { buffer.at<T>(pos) = white; stack.push(pos); } pos.y = rows - 1; if(img.at<T>(pos) == 0 && buffer.at<T>(pos) == 0) { buffer.at<T>(pos) = white; stack.push(pos); } // Increase counter of y if(pos.x < cols) { ++pos.x; } else { pos.x = 0; } } // Apply while(!stack.empty()) { cv::Point pos2 = stack.top(); stack.pop(); for(const cv::Point & rel_neighbor : neighbors) { cv::Point absolute = rel_neighbor + pos2; if(absolute.x >= 0 && absolute.y >= 0 && absolute.x < img.cols && absolute.y < img.rows) { if(img.at<T>(absolute) == 0 && buffer.at<T>(absolute) == 0) { buffer.at<T>(absolute) = white; stack.push(absolute); } } } } // Invert the image for(int i = 0; i < buffer.rows; ++i) { auto *row = buffer.ptr<T>(i); for(int j = 0; j < buffer.cols; ++j) { row[j] = white - row[j]; } } img = buffer; } cv::images::mask to_mask(const cv::images::grayscale32f &img, double threshold) { cv::images::grayscale32f tmp; cv::threshold(img, tmp, threshold, 255, cv::THRESH_BINARY); cv::images::mask result; tmp.convertTo(result, CV_8U, 1); return result; } cv::images::mask create_disk(int radius) { cv::images::mask result { cv::Size(radius * 2 + 1, radius * 2 + 1), 0 }; const int c = result.rows / 2; for(int y = 0; y < result.rows; ++y) { auto *row = result[y]; for(int x = 0; x < result.cols; ++x) { if(std::pow(x - c, 2) + std::pow(y - c, 2) < radius * radius) { row[x] = 255; } } } return result; } int interpolation_from_string(const std::string interpolation_name) { if(interpolation_name == "cubic") { return cv::INTER_CUBIC; } else if(interpolation_name == "linear") { return cv::INTER_LINEAR; } else { throw std::runtime_error("Unsupported interpolation"); } } } void segmentation2d_klingberg_1::create_parameters(misa_parameter_builder &t_parameters) { segmentation2d_base::create_parameters(t_parameters); m_median_filter_size = t_parameters.create_algorithm_parameter<int>("median-filter-size", 3); m_downscale_factor = t_parameters.create_algorithm_parameter<int>("downscale-factor", 10); m_thresholding_percentile = t_parameters.create_algorithm_parameter<double>("thresholding-percentile", 40); m_thresholding_percentile_factor = t_parameters.create_algorithm_parameter<double>("thresholding-percentile-factor", 1.5); m_morph_disk_radius = t_parameters.create_algorithm_parameter<int>("morph-disk-radius", 5); m_label_min_percentile = t_parameters.create_algorithm_parameter<double>("label-min-percentile", 2); m_resize_interpolation = t_parameters.create_algorithm_parameter<std::string>("resize-interpolation", "cubic"); m_resize_interpolation.schema->make_enum<std::string>({ "cubic", "linear" }); } void segmentation2d_klingberg_1::work() { auto module = get_module_as<module_interface>(); cv::images::grayscale32f img = get_as_grayscale_float_copy(m_input_autofluoresence.access_readonly().get()); // Median filtering + normalization cv::medianBlur(img.clone(), img, m_median_filter_size.query()); normalize_by_max(img); // Generated parameters const double xsize = module->m_voxel_size.get_size_xy().get_value(); const double gauss_sigma = 3.0 / xsize; cv::Size img_original_size = img.size(); // Downscale cv::images::grayscale32f img_small; cv::resize(img, img_small, cv::Size(img.size().width / m_downscale_factor.query(), img.size().height / m_downscale_factor.query()), 0,0, interpolation_from_string(m_resize_interpolation.query())); // Gauss filter cv::GaussianBlur(img_small.clone(), img_small,cv::Size(), gauss_sigma, gauss_sigma); // Find a percentile we later use const double tissue_percentile = get_percentiles(get_sorted_pixels(img_small), { m_thresholding_percentile.query() })[0]; // std::cout << m_output_segmented2d.get_plane_location().z << ": Tissue percentile: " << (tissue_percentile * 255) << std::endl; // Binarize using percentile based threshold cv::images::mask small_mask = to_mask(img_small, tissue_percentile * m_thresholding_percentile_factor.query()); // Morphological operations (dilation, hole closing, eroding) { const auto disk = create_disk(m_morph_disk_radius.query()); cv::morphologyEx(small_mask.clone(), small_mask, cv::MORPH_DILATE, disk, cv::Point(-1,-1), 1, cv::BORDER_CONSTANT, cv::Scalar::all(0)); close_holes(small_mask); cv::morphologyEx(small_mask.clone(), small_mask, cv::MORPH_ERODE, disk, cv::Point(-1,-1), 1, cv::BORDER_CONSTANT, cv::Scalar::all(0)); } // // // First find all distinct objects in the mask // // Then remove all objects from the mask where the average intensity of pixels within img_reference // // is < k * tissue_percentile remove_low_average_intensity_objects(small_mask, img_small, static_cast<float>(tissue_percentile * m_label_min_percentile.query())); // Upscale, normalize & fully binarize cv::images::mask full_mask; cv::resize(small_mask, full_mask, img_original_size, 0,0,cv::INTER_CUBIC); cv::threshold(full_mask.clone(), full_mask, 0, 255,cv::THRESH_OTSU); // Count pixels for later m_output_segmented2d.attach(misaxx::ome::misa_ome_pixel_count(cv::countNonZero(full_mask))); // Save the mask m_output_segmented2d.write(std::move(full_mask)); }
35.891753
143
0.556369
applied-systems-biology
8a0023422cd9f9a674c49bd670e9f8eb09105361
17,435
cpp
C++
emulator/src/mame/drivers/microvsn.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/drivers/microvsn.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/drivers/microvsn.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Wilbert Pol /*************************************************************************** Milton Bradley MicroVision To Do: * Add support for the paddle control * Finish support for i8021 based cartridges Since the microcontrollers were on the cartridges it was possible to have different clocks on different games. The Connect Four I8021 game is clocked at around 2MHz. The TMS1100 versions of the games were clocked at around 500KHz, 550KHz, or 300KHz. ****************************************************************************/ #include "emu.h" #include "bus/generic/carts.h" #include "bus/generic/slot.h" #include "cpu/mcs48/mcs48.h" #include "cpu/tms1000/tms1100.h" #include "sound/dac.h" #include "sound/volt_reg.h" #include "rendlay.h" #include "softlist.h" #include "screen.h" #include "speaker.h" #define LOG 0 class microvision_state : public driver_device { public: microvision_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_dac( *this, "dac" ), m_i8021( *this, "maincpu1" ), m_tms1100( *this, "maincpu2" ), m_cart(*this, "cartslot") { } uint32_t screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); DECLARE_PALETTE_INIT(microvision); DECLARE_MACHINE_START(microvision); DECLARE_MACHINE_RESET(microvision); DECLARE_WRITE_LINE_MEMBER(screen_vblank); DECLARE_DEVICE_IMAGE_LOAD_MEMBER( microvsn_cart ); // i8021 interface DECLARE_WRITE8_MEMBER(i8021_p0_write); DECLARE_WRITE8_MEMBER(i8021_p1_write); DECLARE_WRITE8_MEMBER(i8021_p2_write); DECLARE_READ_LINE_MEMBER(i8021_t1_read); DECLARE_READ8_MEMBER(i8021_bus_read); // TMS1100 interface DECLARE_READ8_MEMBER(tms1100_read_k); DECLARE_WRITE16_MEMBER(tms1100_write_o); DECLARE_WRITE16_MEMBER(tms1100_write_r); // enums enum cpu_type { CPU_TYPE_I8021, CPU_TYPE_TMS1100 }; enum pcb_type { PCB_TYPE_4952_REV_A, PCB_TYPE_4952_9_REV_B, PCB_TYPE_4971_REV_C, PCB_TYPE_7924952D02, PCB_TYPE_UNKNOWN }; enum rc_type { RC_TYPE_100PF_21_0K, RC_TYPE_100PF_23_2K, RC_TYPE_100PF_39_4K, RC_TYPE_UNKNOWN }; cpu_type m_cpu_type; pcb_type m_pcb_type; rc_type m_rc_type; void microvision(machine_config &config); protected: required_device<dac_byte_interface> m_dac; required_device<cpu_device> m_i8021; required_device<tms1100_cpu_device> m_tms1100; required_device<generic_slot_device> m_cart; // Timers static const device_timer_id TIMER_PADDLE = 0; emu_timer *m_paddle_timer; virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) override; // i8021 variables uint8_t m_p0; uint8_t m_p2; uint8_t m_t1; // tms1100 variables uint16_t m_r; uint16_t m_o; // generic variables void update_lcd(); void lcd_write(uint8_t control, uint8_t data); bool m_pla; uint8_t m_lcd_latch[8]; uint8_t m_lcd_holding_latch[8]; uint8_t m_lcd_latch_index; uint8_t m_lcd[16][16]; uint8_t m_lcd_control_old; }; PALETTE_INIT_MEMBER(microvision_state,microvision) { palette.set_pen_color( 15, 0x00, 0x00, 0x00 ); palette.set_pen_color( 14, 0x11, 0x11, 0x11 ); palette.set_pen_color( 13, 0x22, 0x22, 0x22 ); palette.set_pen_color( 12, 0x33, 0x33, 0x33 ); palette.set_pen_color( 11, 0x44, 0x44, 0x44 ); palette.set_pen_color( 10, 0x55, 0x55, 0x55 ); palette.set_pen_color( 9, 0x66, 0x66, 0x66 ); palette.set_pen_color( 8, 0x77, 0x77, 0x77 ); palette.set_pen_color( 7, 0x88, 0x88, 0x88 ); palette.set_pen_color( 6, 0x99, 0x99, 0x99 ); palette.set_pen_color( 5, 0xaa, 0xaa, 0xaa ); palette.set_pen_color( 4, 0xbb, 0xbb, 0xbb ); palette.set_pen_color( 3, 0xcc, 0xcc, 0xcc ); palette.set_pen_color( 2, 0xdd, 0xdd, 0xdd ); palette.set_pen_color( 1, 0xee, 0xee, 0xee ); palette.set_pen_color( 0, 0xff, 0xff, 0xff ); } MACHINE_START_MEMBER(microvision_state, microvision) { m_paddle_timer = timer_alloc(TIMER_PADDLE); save_item(NAME(m_p0)); save_item(NAME(m_p2)); save_item(NAME(m_t1)); save_item(NAME(m_r)); save_item(NAME(m_o)); save_item(NAME(m_lcd_latch)); save_item(NAME(m_lcd_latch_index)); save_item(NAME(m_lcd)); save_item(NAME(m_lcd_control_old)); save_item(NAME(m_pla)); save_item(NAME(m_lcd_holding_latch)); } MACHINE_RESET_MEMBER(microvision_state, microvision) { for (auto & elem : m_lcd_latch) { elem = 0; } for (auto & elem : m_lcd) { for (int j = 0; j < 16; j++) { elem[j] = 0; } } m_o = 0; m_r = 0; m_p0 = 0; m_p2 = 0; m_t1 = 0; m_paddle_timer->adjust(attotime::never); switch (m_cpu_type) { case CPU_TYPE_I8021: m_i8021->resume(SUSPEND_REASON_DISABLE); m_tms1100->suspend(SUSPEND_REASON_DISABLE, 0); break; case CPU_TYPE_TMS1100: m_i8021->suspend(SUSPEND_REASON_DISABLE, 0); m_tms1100->resume(SUSPEND_REASON_DISABLE); switch (m_rc_type) { case RC_TYPE_100PF_21_0K: m_tms1100->set_clock(550000); break; case RC_TYPE_100PF_23_2K: case RC_TYPE_UNKNOWN: // Default to most occurring setting m_tms1100->set_clock(500000); break; case RC_TYPE_100PF_39_4K: m_tms1100->set_clock(300000); break; } break; } } void microvision_state::update_lcd() { uint16_t row = ( m_lcd_holding_latch[0] << 12 ) | ( m_lcd_holding_latch[1] << 8 ) | ( m_lcd_holding_latch[2] << 4 ) | m_lcd_holding_latch[3]; uint16_t col = ( m_lcd_holding_latch[4] << 12 ) | ( m_lcd_holding_latch[5] << 8 ) | ( m_lcd_holding_latch[6] << 4 ) | m_lcd_holding_latch[7]; if (LOG) logerror("row = %04x, col = %04x\n", row, col ); for ( int i = 0; i < 16; i++ ) { uint16_t temp = row; for (auto & elem : m_lcd) { if ( ( temp & col ) & 0x8000 ) { elem[i] = 15; } temp <<= 1; } col <<= 1; } } uint32_t microvision_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { for ( uint8_t i = 0; i < 16; i++ ) { for ( uint8_t j = 0; j < 16; j++ ) { bitmap.pix16(i,j) = m_lcd [i] [j]; } } return 0; } WRITE_LINE_MEMBER(microvision_state::screen_vblank) { if ( state ) { for (auto & elem : m_lcd) { for ( int j= 0; j < 16; j++ ) { if ( elem[j] ) { elem[j]--; } } } update_lcd(); } } /* control is signals LCD5 LCD4 LCD5 = -Data Clk on 0488 LCD4 = Latch pulse on 0488 LCD3 = Data 0 LCD2 = Data 1 LCD1 = Data 2 LCD0 = Data 3 data is signals LCD3 LCD2 LCD1 LCD0 */ void microvision_state::lcd_write(uint8_t control, uint8_t data) { // Latch pulse, when high, resets the %8 latch address counter if ( control & 0x01 ) { m_lcd_latch_index = 0; } // The addressed latches load when -Data Clk is low if ( ! ( control & 0x02 ) ) { m_lcd_latch[ m_lcd_latch_index & 0x07 ] = data & 0x0f; } // The latch address counter is incremented on rising edges of -Data Clk if ( ( ! ( m_lcd_control_old & 0x02 ) ) && ( control & 0x02 ) ) { // Check if Latch pule is low if ( ! ( control & 0x01 ) ) { m_lcd_latch_index++; } } // A parallel transfer of data from the addressed latches to the holding latches occurs // whenever Latch Pulse is high and -Data Clk is high if ( control == 3 ) { for ( int i = 0; i < 8; i++ ) { m_lcd_holding_latch[i] = m_lcd_latch[i]; } update_lcd(); } m_lcd_control_old = control; } void microvision_state::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) { switch ( id ) { case TIMER_PADDLE: m_t1 = 0; break; } } /* x--- ---- KEY3 -x-- ---- KEY4 --x- ---- KEY5 ---x ---- KEY6 ---- x--- ---- -x-- KEY0 ---- --x- KEY1 ---- ---x KEY2 */ WRITE8_MEMBER( microvision_state::i8021_p0_write ) { if (LOG) logerror( "p0_write: %02x\n", data ); m_p0 = data; } /* x--- ---- LCD3 -x-- ---- LCD2 --x- ---- LCD1 ---x ---- LCD0 ---- --x- LCD5 ---- ---x LCD4 */ WRITE8_MEMBER( microvision_state::i8021_p1_write ) { if (LOG) logerror( "p1_write: %02x\n", data ); lcd_write( data & 0x03, data >> 4 ); } /* ---- xx-- CAP2 (paddle) ---- --x- SPKR1 ---- ---x SPKR0 */ WRITE8_MEMBER( microvision_state::i8021_p2_write ) { if (LOG) logerror( "p2_write: %02x\n", data ); m_p2 = data; m_dac->write(m_p2 & 0x03); if ( m_p2 & 0x0c ) { m_t1 = 1; // Stop paddle timer m_paddle_timer->adjust( attotime::never ); } else { // Start paddle timer (min is 160uS, max is 678uS) uint8_t paddle = 255 - ioport("PADDLE")->read(); m_paddle_timer->adjust( attotime::from_usec(160 + ( 518 * paddle ) / 255 ) ); } } READ_LINE_MEMBER( microvision_state::i8021_t1_read ) { return m_t1; } READ8_MEMBER( microvision_state::i8021_bus_read ) { uint8_t data = m_p0; uint8_t col0 = ioport("COL0")->read(); uint8_t col1 = ioport("COL1")->read(); uint8_t col2 = ioport("COL2")->read(); // Row scanning if ( ! ( m_p0 & 0x80 ) ) { uint8_t t = ( ( col0 & 0x01 ) << 2 ) | ( ( col1 & 0x01 ) << 1 ) | ( col2 & 0x01 ); data &= ( t ^ 0xFF ); } if ( ! ( m_p0 & 0x40 ) ) { uint8_t t = ( ( col0 & 0x02 ) << 1 ) | ( col1 & 0x02 ) | ( ( col2 & 0x02 ) >> 1 ); data &= ( t ^ 0xFF ); } if ( ! ( m_p0 & 0x20 ) ) { uint8_t t = ( col0 & 0x04 ) | ( ( col1 & 0x04 ) >> 1 ) | ( ( col2 & 0x04 ) >> 2 ); data &= ( t ^ 0xFF ); } if ( ! ( m_p0 & 0x10 ) ) { uint8_t t = ( ( col0 & 0x08 ) >> 1 ) | ( ( col1 & 0x08 ) >> 2 ) | ( ( col2 & 0x08 ) >> 3 ); data &= ( t ^ 0xFF ); } return data; } READ8_MEMBER( microvision_state::tms1100_read_k ) { uint8_t data = 0; if (LOG) logerror("read_k\n"); if ( m_r & 0x100 ) { data |= ioport("COL0")->read(); } if ( m_r & 0x200 ) { data |= ioport("COL1")->read(); } if ( m_r & 0x400 ) { data |= ioport("COL2")->read(); } return data; } WRITE16_MEMBER( microvision_state::tms1100_write_o ) { if (LOG) logerror("write_o: %04x\n", data); m_o = data; lcd_write( ( m_r >> 6 ) & 0x03, m_o & 0x0f ); } /* x-- ---- ---- KEY2 -x- ---- ---- KEY1 --x ---- ---- KEY0 --- x--- ---- LCD5 --- -x-- ---- LCD4 --- ---- --x- SPKR0 --- ---- ---x SPKR1 */ WRITE16_MEMBER( microvision_state::tms1100_write_r ) { if (LOG) logerror("write_r: %04x\n", data); m_r = data; m_dac->write((BIT(m_r, 0) << 1) | BIT(m_r, 1)); lcd_write( ( m_r >> 6 ) & 0x03, m_o & 0x0f ); } static const u16 microvision_output_pla_0[0x20] = { /* O output PLA configuration currently unknown */ 0x00, 0x08, 0x04, 0x0C, 0x02, 0x0A, 0x06, 0x0E, 0x01, 0x09, 0x05, 0x0D, 0x03, 0x0B, 0x07, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const u16 microvision_output_pla_1[0x20] = { /* O output PLA configuration currently unknown */ /* Reversed bit order */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; DEVICE_IMAGE_LOAD_MEMBER(microvision_state, microvsn_cart) { uint8_t *rom1 = memregion("maincpu1")->base(); uint8_t *rom2 = memregion("maincpu2")->base(); uint32_t file_size = m_cart->common_get_size("rom"); m_pla = 0; if ( file_size != 1024 && file_size != 2048 ) { image.seterror(IMAGE_ERROR_UNSPECIFIED, "Invalid rom file size"); return image_init_result::FAIL; } /* Read cartridge */ if (!image.loaded_through_softlist()) { if (image.fread(rom1, file_size) != file_size) { image.seterror(IMAGE_ERROR_UNSPECIFIED, "Unable to fully read from file"); return image_init_result::FAIL; } } else { // Copy rom contents memcpy(rom1, image.get_software_region("rom"), file_size); // Get PLA type const char *pla = image.get_feature("pla"); if (pla) m_pla = 1; m_tms1100->set_output_pla(m_pla ? microvision_output_pla_1 : microvision_output_pla_0); // Set default setting for PCB type and RC type m_pcb_type = microvision_state::PCB_TYPE_UNKNOWN; m_rc_type = microvision_state::RC_TYPE_UNKNOWN; // Detect settings for PCB type const char *pcb = image.get_feature("pcb"); if (pcb) { static const struct { const char *pcb_name; microvision_state::pcb_type pcbtype; } pcb_types[] = { { "4952 REV-A", microvision_state::PCB_TYPE_4952_REV_A }, { "4952-79 REV-B", microvision_state::PCB_TYPE_4952_9_REV_B }, { "4971-REV-C", microvision_state::PCB_TYPE_4971_REV_C }, { "7924952D02", microvision_state::PCB_TYPE_7924952D02 } }; for (int i = 0; i < ARRAY_LENGTH(pcb_types) && m_pcb_type == microvision_state::PCB_TYPE_UNKNOWN; i++) { if (!core_stricmp(pcb, pcb_types[i].pcb_name)) { m_pcb_type = pcb_types[i].pcbtype; } } } // Detect settings for RC types const char *rc = image.get_feature("rc"); if (rc) { static const struct { const char *rc_name; microvision_state::rc_type rctype; } rc_types[] = { { "100pf/21.0K", microvision_state::RC_TYPE_100PF_21_0K }, { "100pf/23.2K", microvision_state::RC_TYPE_100PF_23_2K }, { "100pf/39.4K", microvision_state::RC_TYPE_100PF_39_4K } }; for (int i = 0; i < ARRAY_LENGTH(rc_types) && m_rc_type == microvision_state::RC_TYPE_UNKNOWN; i++) { if (!core_stricmp(rc, rc_types[i].rc_name)) { m_rc_type = rc_types[i].rctype; } } } } // Mirror rom data to maincpu2 region memcpy(rom2, rom1, file_size); // Based on file size select cpu: // - 1024 -> I8021 // - 2048 -> TI TMS1100 switch (file_size) { case 1024: m_cpu_type = microvision_state::CPU_TYPE_I8021; break; case 2048: m_cpu_type = microvision_state::CPU_TYPE_TMS1100; break; } return image_init_result::PASS; } static INPUT_PORTS_START( microvision ) PORT_START("COL0") PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_BUTTON1) PORT_CODE(KEYCODE_3) PORT_NAME("B01") PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_BUTTON4) PORT_CODE(KEYCODE_E) PORT_NAME("B04") PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_BUTTON7) PORT_CODE(KEYCODE_D) PORT_NAME("B07") PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_BUTTON10) PORT_CODE(KEYCODE_C) PORT_NAME("B10") PORT_START("COL1") PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_BUTTON2) PORT_CODE(KEYCODE_4) PORT_NAME("B02") PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_BUTTON5) PORT_CODE(KEYCODE_R) PORT_NAME("B05") PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_BUTTON8) PORT_CODE(KEYCODE_F) PORT_NAME("B08") PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_BUTTON11) PORT_CODE(KEYCODE_V) PORT_NAME("B11") PORT_START("COL2") PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_BUTTON3) PORT_CODE(KEYCODE_5) PORT_NAME("B03") PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_BUTTON6) PORT_CODE(KEYCODE_T) PORT_NAME("B06") PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_BUTTON9) PORT_CODE(KEYCODE_G) PORT_NAME("B09") PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_BUTTON12) PORT_CODE(KEYCODE_B) PORT_NAME("B12") PORT_START("PADDLE") PORT_BIT( 0xff, 0x80, IPT_PADDLE) PORT_PLAYER(1) PORT_SENSITIVITY(30) PORT_KEYDELTA(20) PORT_MINMAX(0, 255) INPUT_PORTS_END MACHINE_CONFIG_START(microvision_state::microvision) MCFG_CPU_ADD("maincpu1", I8021, 2000000) // approximately MCFG_MCS48_PORT_BUS_OUT_CB(WRITE8(microvision_state, i8021_p0_write)) MCFG_MCS48_PORT_P1_OUT_CB(WRITE8(microvision_state, i8021_p1_write)) MCFG_MCS48_PORT_P2_OUT_CB(WRITE8(microvision_state, i8021_p2_write)) MCFG_MCS48_PORT_T1_IN_CB(READLINE(microvision_state, i8021_t1_read)) MCFG_MCS48_PORT_BUS_IN_CB(READ8(microvision_state, i8021_bus_read)) MCFG_CPU_ADD("maincpu2", TMS1100, 500000) // most games seem to be running at approximately this speed MCFG_TMS1XXX_OUTPUT_PLA( microvision_output_pla_0 ) MCFG_TMS1XXX_READ_K_CB( READ8( microvision_state, tms1100_read_k ) ) MCFG_TMS1XXX_WRITE_O_CB( WRITE16( microvision_state, tms1100_write_o ) ) MCFG_TMS1XXX_WRITE_R_CB( WRITE16( microvision_state, tms1100_write_r ) ) MCFG_SCREEN_ADD("screen", LCD) MCFG_SCREEN_REFRESH_RATE(60) MCFG_SCREEN_VBLANK_TIME(0) MCFG_QUANTUM_TIME(attotime::from_hz(60)) MCFG_MACHINE_START_OVERRIDE(microvision_state, microvision ) MCFG_MACHINE_RESET_OVERRIDE(microvision_state, microvision ) MCFG_SCREEN_UPDATE_DRIVER(microvision_state, screen_update) MCFG_SCREEN_VBLANK_CALLBACK(WRITELINE(microvision_state, screen_vblank)) MCFG_SCREEN_SIZE(16, 16) MCFG_SCREEN_VISIBLE_AREA(0, 15, 0, 15) MCFG_SCREEN_PALETTE("palette") MCFG_PALETTE_ADD("palette", 16) MCFG_PALETTE_INIT_OWNER(microvision_state,microvision) MCFG_DEFAULT_LAYOUT(layout_lcd) /* sound hardware */ MCFG_SPEAKER_STANDARD_MONO("speaker") MCFG_SOUND_ADD("dac", DAC_2BIT_BINARY_WEIGHTED_ONES_COMPLEMENT, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "speaker", 0.25) // unknown DAC MCFG_DEVICE_ADD("vref", VOLTAGE_REGULATOR, 0) MCFG_VOLTAGE_REGULATOR_OUTPUT(5.0) MCFG_SOUND_ROUTE_EX(0, "dac", 1.0, DAC_VREF_POS_INPUT) MCFG_SOUND_ROUTE_EX(0, "dac", -1.0, DAC_VREF_NEG_INPUT) MCFG_GENERIC_CARTSLOT_ADD("cartslot", generic_plain_slot, "microvision_cart") MCFG_GENERIC_MANDATORY MCFG_GENERIC_LOAD(microvision_state, microvsn_cart) /* Software lists */ MCFG_SOFTWARE_LIST_ADD("cart_list","microvision") MACHINE_CONFIG_END ROM_START( microvsn ) ROM_REGION( 0x800, "maincpu1", ROMREGION_ERASE00 ) ROM_REGION( 0x800, "maincpu2", ROMREGION_ERASE00 ) ROM_REGION( 867, "maincpu2:mpla", 0 ) ROM_LOAD( "tms1100_default_mpla.pla", 0, 867, CRC(62445fc9) SHA1(d6297f2a4bc7a870b76cc498d19dbb0ce7d69fec) ) // verified for: pinball, blockbuster, bowling ROM_REGION( 365, "maincpu2:opla", ROMREGION_ERASE00 ) ROM_END CONS( 1979, microvsn, 0, 0, microvision, microvision, microvision_state, 0, "Milton Bradley", "MicroVision", MACHINE_NOT_WORKING )
25.086331
156
0.686263
rjw57
8a009bd4e6de03372f9217e87a4c92ea355e2b19
1,230
cc
C++
caffe2/operators/unsafe_coalesce.cc
raven38/pytorch
3a56758e1fdbc928be3754d5b60e63c7fc55ea45
[ "Intel" ]
7
2021-05-29T16:31:51.000Z
2022-02-21T18:52:25.000Z
caffe2/operators/unsafe_coalesce.cc
raven38/pytorch
3a56758e1fdbc928be3754d5b60e63c7fc55ea45
[ "Intel" ]
1
2021-05-10T01:18:33.000Z
2021-05-10T01:18:33.000Z
caffe2/operators/unsafe_coalesce.cc
raven38/pytorch
3a56758e1fdbc928be3754d5b60e63c7fc55ea45
[ "Intel" ]
1
2021-12-26T23:20:06.000Z
2021-12-26T23:20:06.000Z
#include "caffe2/operators/unsafe_coalesce.h" namespace caffe2 { // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) OPERATOR_SCHEMA(UnsafeCoalesce) .NumInputsOutputs([](int inputs, int outputs) { return inputs + 1 == outputs; }) .AllowInplace([](int input, int output) { return input == output; }) .SetDoc(R"DOC( Coalesce the N inputs into N outputs and a single coalesced output blob. This allows operations that operate over multiple small kernels (e.g. biases in a deep CNN) to be coalesced into a single larger operation, amortizing the kernel launch overhead, synchronization costs for distributed computation, etc. The operator: - computes the total size of the coalesced blob by summing the input sizes - allocates the coalesced output blob as the total size - copies the input vectors into the coalesced blob, at the correct offset. - aliases each Output(i) to- point into the coalesced blob, at the corresponding offset for Input(i). This is 'unsafe' as the output vectors are aliased, so use with caution. )DOC"); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR(UnsafeCoalesce, UnsafeCoalesceOp<CPUContext>); } // namespace caffe2
41
101
0.773171
raven38
8a0293953680b037cfdd3de5074709eab487e381
294
cpp
C++
QuickPushQuizWin/MouseController.cpp
AinoMegumi/QuickPushQuiz
7fc858d898001b2ac31e9c1e4778c4dc548430d9
[ "MIT" ]
null
null
null
QuickPushQuizWin/MouseController.cpp
AinoMegumi/QuickPushQuiz
7fc858d898001b2ac31e9c1e4778c4dc548430d9
[ "MIT" ]
null
null
null
QuickPushQuizWin/MouseController.cpp
AinoMegumi/QuickPushQuiz
7fc858d898001b2ac31e9c1e4778c4dc548430d9
[ "MIT" ]
null
null
null
#include "MouseController.hpp" #include "DxLib.h" void MouseController::UpdateCurrentPos() { GetMousePoint(&this->Current.x, &this->Current.y); } bool MouseController::Clicked() { return Core::LeftHandMouse ? GetMouseInput() & MOUSE_INPUT_RIGHT : GetMouseInput() & MOUSE_INPUT_LEFT; }
22.615385
51
0.741497
AinoMegumi
8a052f0375fdd07c275f90c44e76293d0eedc7dd
1,281
cpp
C++
src/clipMaker/src/main.cpp
kothiga/Embodied-Social-Interface
4545e07b3d575f48dea5b42cde93ef81484e9567
[ "MIT" ]
null
null
null
src/clipMaker/src/main.cpp
kothiga/Embodied-Social-Interface
4545e07b3d575f48dea5b42cde93ef81484e9567
[ "MIT" ]
null
null
null
src/clipMaker/src/main.cpp
kothiga/Embodied-Social-Interface
4545e07b3d575f48dea5b42cde93ef81484e9567
[ "MIT" ]
null
null
null
/* ================================================================================ * Copyright: (C) 2022, SIRRL Social and Intelligent Robotics Research Laboratory, * University of Waterloo, All rights reserved. * * Authors: * Austin Kothig <austin.kothig@uwaterloo.ca> * * CopyPolicy: Released under the terms of the MIT License. * See the accompanying LICENSE file for details. * ================================================================================ */ #include <iostream> #include <map> #include <memory> #include <string> #include <yarp/os/Network.h> #include <yarp/os/LogStream.h> #include <clipMaker.hpp> int main (int argc, char **argv) { //-- Init the yarp network. yarp::os::Network yarp; if (!yarp.checkNetwork()) { yError() << "Cannot make connection with the YARP server!!"; return EXIT_FAILURE; } //-- Config the resource finder. yarp::os::ResourceFinder rf; rf.setVerbose(false); rf.setDefaultConfigFile("config.ini"); // overridden by --from parameter rf.setDefaultContext("clip_maker"); // overridden by --context parameter rf.configure(argc,argv); //-- Run the interface and return its status. ClipMaker clip_maker; return clip_maker.runModule(rf); }
29.113636
83
0.587041
kothiga
8a06019dd7e7f45e61e314f5c580f04449ad390c
7,229
hpp
C++
include/smooth/internal/se2.hpp
NamDinhRobotics/smooth
137008de5d68af459db2c7802e05cdabd166c424
[ "MIT" ]
1
2021-11-29T10:28:18.000Z
2021-11-29T10:28:18.000Z
include/smooth/internal/se2.hpp
NamDinhRobotics/smooth
137008de5d68af459db2c7802e05cdabd166c424
[ "MIT" ]
null
null
null
include/smooth/internal/se2.hpp
NamDinhRobotics/smooth
137008de5d68af459db2c7802e05cdabd166c424
[ "MIT" ]
null
null
null
// smooth: Lie Theory for Robotics // https://github.com/pettni/smooth // // Licensed under the MIT License <http://opensource.org/licenses/MIT>. // // Copyright (c) 2021 Petter Nilsson // // 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 SMOOTH__IMPL__SE2_HPP_ #define SMOOTH__IMPL__SE2_HPP_ #include <Eigen/Core> #include "common.hpp" #include "so2.hpp" namespace smooth { /** * @brief SE(2) Lie Group represented as C^1 ⋉ R^2 * * Memory layout * ------------- * Group: x y qz qw * Tangent: vx vy Ωz * * Lie group Matrix form * --------------------- * [ qw -qz x ] * [ qz qw y ] * [ 0 0 1 ] * * Lie algebra Matrix form * ----------------------- * [ 0 -Ωz vx ] * [ Ωz 0 vy ] * [ 0 0 0 ] * * Constraints * ----------- * Group: qz * qz + qw * qw = 1 * Tangent: -pi < Ωz <= pi */ template<typename _Scalar> class SE2Impl { public: using Scalar = _Scalar; static constexpr Eigen::Index RepSize = 4; static constexpr Eigen::Index Dim = 3; static constexpr Eigen::Index Dof = 3; SMOOTH_DEFINE_REFS; static void setIdentity(GRefOut g_out) { g_out << Scalar(0), Scalar(0), Scalar(0), Scalar(1); } static void setRandom(GRefOut g_out) { g_out.template head<2>().setRandom(); SO2Impl<Scalar>::setRandom(g_out.template tail<2>()); } static void matrix(GRefIn g_in, MRefOut m_out) { m_out.setIdentity(); SO2Impl<Scalar>::matrix(g_in.template tail<2>(), m_out.template topLeftCorner<2, 2>()); m_out.template topRightCorner<2, 1>() = g_in.template head<2>(); } static void composition(GRefIn g_in1, GRefIn g_in2, GRefOut g_out) { SO2Impl<Scalar>::composition( g_in1.template tail<2>(), g_in2.template tail<2>(), g_out.template tail<2>()); Eigen::Matrix<Scalar, 2, 2> R1; SO2Impl<Scalar>::matrix(g_in1.template tail<2>(), R1); g_out.template head<2>() = R1 * g_in2.template head<2>() + g_in1.template head<2>(); } static void inverse(GRefIn g_in, GRefOut g_out) { Eigen::Matrix<Scalar, 2, 1> so2inv; SO2Impl<Scalar>::inverse(g_in.template tail<2>(), so2inv); Eigen::Matrix<Scalar, 2, 2> Rinv; SO2Impl<Scalar>::matrix(so2inv, Rinv); g_out.template head<2>() = -Rinv * g_in.template head<2>(); g_out.template tail<2>() = so2inv; } static void log(GRefIn g_in, TRefOut a_out) { using std::tan; Eigen::Matrix<Scalar, 1, 1> so2_log; SO2Impl<Scalar>::log(g_in.template tail<2>(), so2_log); const Scalar th = so2_log(0); const Scalar th2 = th * th; const Scalar B = th / Scalar(2); Scalar A; if (th2 < Scalar(eps2)) { // https://www.wolframalpha.com/input/?i=series+x+%2F+tan+x+at+x%3D0 A = Scalar(1) - th2 / Scalar(12); } else { A = B / tan(B); } Eigen::Matrix<Scalar, 2, 2> Sinv; Sinv(0, 0) = A; Sinv(1, 1) = A; Sinv(0, 1) = B; Sinv(1, 0) = -B; a_out.template head<2>() = Sinv * g_in.template head<2>(); a_out(2) = th; } static void Ad(GRefIn g_in, TMapRefOut A_out) { SO2Impl<Scalar>::matrix(g_in.template tail<2>(), A_out.template topLeftCorner<2, 2>()); A_out(0, 2) = g_in(1); A_out(1, 2) = -g_in(0); A_out(2, 0) = Scalar(0); A_out(2, 1) = Scalar(0); A_out(2, 2) = Scalar(1); } static void exp(TRefIn a_in, GRefOut g_out) { using std::cos, std::sin; const Scalar th = a_in.z(); const Scalar th2 = th * th; Scalar A, B; if (th2 < Scalar(eps2)) { // https://www.wolframalpha.com/input/?i=series+sin+x+%2F+x+at+x%3D0 A = Scalar(1) - th2 / Scalar(6); // https://www.wolframalpha.com/input/?i=series+%28cos+x+-+1%29+%2F+x+at+x%3D0 B = -th / Scalar(2) + th * th2 / Scalar(24); } else { A = sin(th) / th; B = (cos(th) - Scalar(1)) / th; } Eigen::Matrix<Scalar, 2, 2> S; S(0, 0) = A; S(1, 1) = A; S(0, 1) = B; S(1, 0) = -B; g_out.template head<2>() = S * a_in.template head<2>(); SO2Impl<Scalar>::exp(a_in.template tail<1>(), g_out.template tail<2>()); } static void hat(TRefIn a_in, MRefOut A_out) { A_out.setZero(); SO2Impl<Scalar>::hat(a_in.template tail<1>(), A_out.template topLeftCorner<2, 2>()); A_out.template topRightCorner<2, 1>() = a_in.template head<2>(); } static void vee(MRefIn A_in, TRefOut a_out) { SO2Impl<Scalar>::vee(A_in.template topLeftCorner<2, 2>(), a_out.template tail<1>()); a_out.template head<2>() = A_in.template topRightCorner<2, 1>(); } static void ad(TRefIn a_in, TMapRefOut A_out) { A_out.setZero(); SO2Impl<Scalar>::hat(a_in.template tail<1>(), A_out.template topLeftCorner<2, 2>()); A_out(0, 2) = a_in.y(); A_out(1, 2) = -a_in.x(); } static void dr_exp(TRefIn a_in, TMapRefOut A_out) { using TangentMap = Eigen::Matrix<Scalar, 3, 3>; using std::sin, std::cos; const Scalar th2 = a_in.z() * a_in.z(); Scalar A, B; if (th2 < Scalar(eps2)) { // https://www.wolframalpha.com/input/?i=series+%281-cos+x%29+%2F+x%5E2+at+x%3D0 A = Scalar(1) / Scalar(2) - th2 / Scalar(24); // https://www.wolframalpha.com/input/?i=series+%28x+-+sin%28x%29%29+%2F+x%5E3+at+x%3D0 B = Scalar(1) / Scalar(6) - th2 / Scalar(120); } else { const Scalar th = a_in.z(); A = (Scalar(1) - cos(th)) / th2; B = (th - sin(th)) / (th2 * th); } TangentMap ad_a; ad(a_in, ad_a); A_out = TangentMap::Identity() - A * ad_a + B * ad_a * ad_a; } static void dr_expinv(TRefIn a_in, TMapRefOut A_out) { using TangentMap = Eigen::Matrix<Scalar, 3, 3>; using std::sin, std::cos; const Scalar th = a_in.z(); const Scalar th2 = th * th; Scalar A; if (th2 < Scalar(eps2)) { // https://www.wolframalpha.com/input/?i=series+1%2Fx%5E2+-+%281+%2B+cos+x%29+%2F+%282+*+x+*+sin+x%29+at+x%3D0 A = Scalar(1) / Scalar(12) + th2 / Scalar(720); } else { A = (Scalar(1) / th2) - (Scalar(1) + cos(th)) / (Scalar(2) * th * sin(th)); } TangentMap ad_a; ad(a_in, ad_a); A_out = TangentMap::Identity() + ad_a / 2 + A * ad_a * ad_a; } }; } // namespace smooth #endif // SMOOTH__IMPL__SE2_HPP_
29.506122
116
0.608383
NamDinhRobotics
8a084ae985f5aecf82771e2f66800875a29f1b6c
2,251
cpp
C++
ProblemSum/Problem_Time.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
ProblemSum/Problem_Time.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
ProblemSum/Problem_Time.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Problem_Time.cpp - write the problem time file //********************************************************* #include "ProblemSum.hpp" //--------------------------------------------------------- // Problem_Time //--------------------------------------------------------- void ProblemSum::Problem_Time (void) { int i, j, time, type, num, total, num_inc, *num_time, nout; int type_field, time_field, start_field; char buffer [FIELD_BUFFER]; Range_Data *range_ptr; //---- summarize the problem times ---- type_field = problem_db.Required_Field ("PROBLEM", "STATUS"); time_field = problem_db.Optional_Field ("TIME", "TOD"); start_field = problem_db.Optional_Field ("START", "START_TIME"); Show_Message ("Writing %s -- Record", time_file.File_Type ()); Set_Progress (10000); nout = 0; num_inc = times.Num_Ranges (); num_time = new int [num_inc]; i = ((num_types > 1) ? 0 : 1); for (; i < MAX_PROBLEM; i++) { if (num_problems [i] == 0) continue; num = 0; memset (num_time, '\0', num_inc * sizeof (int)); problem_db.Rewind (); while (problem_db.Read_Record ()) { if (i > 0) { problem_db.Get_Field (type_field, &type); if (i != type) continue; } if (time_field > 0) { problem_db.Get_Field (time_field, buffer); time = times.Step (buffer); } else { time = 0; } if (time == 0) { problem_db.Get_Field (start_field, buffer); time = times.Step (buffer); } time = times.In_Increment (time) - 1; if (num_time [time] == 0) num++; num_time [time]++; } if (num == 0) continue; total = num_problems [i]; for (j=0; j < num_inc; j++) { Show_Progress (); range_ptr = times [j+1]; time_file.Put_Field (1, i); time_file.Put_Field (2, times.Format_Step (range_ptr->Low ())); time_file.Put_Field (3, times.Format_Step (range_ptr->High () + 1)); time_file.Put_Field (4, num_time [j]); time_file.Put_Field (5, ((100.0 * num_time [j]) / total)); if (!time_file.Write ()) { Error ("Writing %s", time_file.File_Type ()); } nout++; } } End_Progress (); time_file.Close (); delete [] num_time; Print (2, "Number of %s Records = %d", time_file.File_Type (), nout); }
24.204301
71
0.557086
kravitz
8a092f62819ba59c2f2fb5cbedc7dff5b916f172
6,573
hpp
C++
src/impl/meta_utils.hpp
thequickf/graph
fff8f514b3cb3e48f4b6dfd1dd4679bcf102e7de
[ "MIT" ]
3
2021-01-26T08:42:17.000Z
2021-02-15T11:55:05.000Z
src/impl/meta_utils.hpp
thequickf/graph
fff8f514b3cb3e48f4b6dfd1dd4679bcf102e7de
[ "MIT" ]
5
2021-01-23T20:44:39.000Z
2021-02-18T08:09:12.000Z
src/impl/meta_utils.hpp
thequickf/graph
fff8f514b3cb3e48f4b6dfd1dd4679bcf102e7de
[ "MIT" ]
null
null
null
#ifndef IMPL_META_UTILS_HPP #define IMPL_META_UTILS_HPP #include <graph_traits.hpp> #include <impl/graph_traits.hpp> #include <concepts> #include <type_traits> namespace graph_meta { template<typename...> struct list; template<typename Node> using abstract_trait_replacements = list< list<graph::Net, graph_impl::Net<Node> > >; template<typename, typename> struct list_concat_impl; template<typename... LHTs, typename... RHTs> struct list_concat_impl<list<LHTs...>, list<RHTs...>> { using type = list<LHTs..., RHTs...>; }; template<template<typename> class, typename...> struct filter_impl; template<template<typename> class Condition> struct filter_impl<Condition> { using type = list<>; }; template<template<typename> class Condition, typename Head, typename... Tail> struct filter_impl<Condition, Head, Tail...> { using type = typename list_concat_impl< std::conditional_t< Condition<Head>::value, list<Head>, list<> >, typename filter_impl<Condition, Tail...>::type >::type; }; template<template<typename> class Condition, typename... Ts> using filter_t = typename filter_impl<Condition, Ts...>::type; template<template<typename> class, typename> struct filter_list_impl; template<template<typename> class Condition, typename... Ts> struct filter_list_impl<Condition, list<Ts...> > { using type = filter_t<Condition, Ts...>; }; template<template<typename> class Condition, typename List> using filter_list_t = filter_list_impl<Condition, List>::type; template<typename, typename, typename...> struct replace_impl; template<typename SourceT, typename TargetT> struct replace_impl<SourceT, TargetT> { using type = list<>; }; template<typename SourceT, typename TargetT, typename Head, typename... Tail> struct replace_impl<SourceT, TargetT, Head, Tail...> { using type = typename list_concat_impl< std::conditional_t< std::is_same_v<Head, SourceT>, list<TargetT>, list<Head> >, typename replace_impl<SourceT, TargetT, Tail...>::type >::type; }; template<typename, typename, typename> struct replace; template<typename SourceT, typename TargetT, typename... Ts> struct replace<SourceT, TargetT, list<Ts...> > { using type = replace_impl<SourceT, TargetT, Ts...>::type; }; template<typename SourceT, typename TargetT, typename List> using replace_t = replace<SourceT, TargetT, List>::type; template<typename, typename...> struct replace_all_impl; template<typename TraitList> struct replace_all_impl<TraitList> { using type = TraitList; }; template< typename TraitList, typename SourceT, typename TargetT, typename... Tail> struct replace_all_impl<TraitList, list<SourceT, TargetT>, Tail...> { using type = replace_all_impl<replace_t<SourceT, TargetT, TraitList>, Tail...>::type; }; template<typename, typename> struct replace_all; template<typename TraitList, typename... Replacements> struct replace_all<TraitList, list<Replacements...> > { using type = replace_all_impl<TraitList, Replacements...>::type; }; template<typename TraitList, typename... Replacements> using replace_all_t = replace_all<TraitList, Replacements...>::type; template<typename, typename, typename...> struct contains_type_impl; template<typename Result, typename T> struct contains_type_impl<Result, T> { using value = Result; }; template<typename Result, typename T, typename Head, typename... Tail> struct contains_type_impl<Result, T, Head, Tail...> { using value = contains_type_impl< std::disjunction<Result, std::is_same<T, Head> >, T, Tail...>::value; }; template<typename Node, typename TraitList> using replace_abstract_traits = replace_all<TraitList, abstract_trait_replacements<Node> >; template<typename Node, typename TraitList> using replace_abstract_traits_t = replace_all_t<TraitList, abstract_trait_replacements<Node> >; template<class Derived> using graph_trait_condition = std::is_base_of<graph::GraphTrait, Derived>; template<class Derived> using edge_trait_condition = std::is_base_of<graph::EdgeTrait, Derived>; template<class Derived> using constructible_trait_condition = std::negation<std::is_base_of<graph::NoConstructorTrait, Derived> >; template<typename T, typename... Ts> using contains_type = contains_type_impl<std::false_type, T, Ts...>::value; template <typename T, typename... Ts> inline constexpr bool contains_type_v = contains_type<T, Ts...>::value; template<typename Node, typename... Traits> using build_graph_traits = replace_abstract_traits_t< Node, filter_t<graph_trait_condition, Traits...> >; template<typename Node, typename... Traits> using build_edge_traits = replace_abstract_traits_t< Node, filter_t<edge_trait_condition, Traits...> >; template<typename Node, typename... Traits> using constructible_graph_traits = filter_list_t<constructible_trait_condition, build_graph_traits<Node, Traits...> >; template<typename Node, typename... Traits> using constructible_edge_traits = filter_list_t<constructible_trait_condition, build_edge_traits<Node, Traits...> >; template<typename T> concept EdgeTrait = std::is_base_of_v<graph::EdgeTrait, T>; template<typename T> concept GraphTrait = std::is_base_of_v<graph::GraphTrait, T>; template<typename T> concept Trait = GraphTrait<T> || EdgeTrait<T>; template<typename T> concept Hashable = requires(const std::remove_reference_t<T>& a, const std::remove_reference_t<T>& b) { { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>; { a == b } -> std::convertible_to<bool>; }; template<typename T> concept Comparable = requires(const std::remove_reference_t<T>& a, const std::remove_reference_t<T>& b) { { a < b } -> std::convertible_to<bool>; }; template<typename Node, typename... GraphTraits> concept HashBaseConsistent = Hashable<Node> && contains_type_v<graph::HashTableBased, GraphTraits...>; template<typename Node, typename... GraphTraits> concept RBTreeBaseConsistent = Comparable<Node> && !contains_type_v<graph::HashTableBased, GraphTraits...>; template<typename Node, typename... GraphTraits> concept BaseConsistent = HashBaseConsistent<Node, GraphTraits...> || RBTreeBaseConsistent<Node, GraphTraits...>; template<typename... Traits> concept CorrectDSUTraits = sizeof...(Traits) == 0 || sizeof...(Traits) == 1 && contains_type_v<graph::HashTableBased, Traits...>; } // graph_meta #endif // IMPL_META_UTILS_HPP
29.742081
80
0.726761
thequickf
8a0a7d33d2fdce20335c993ef4ee73f18de6b426
4,382
cpp
C++
source/rt_stark.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/rt_stark.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/rt_stark.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
/* This file is part of Cloudy and is copyright (C)1978-2019 by Gary J. Ferland and * others. For conditions of distribution and use see copyright notice in license.txt */ /*RT_stark compute stark broadening escape probabilities using Puetter formalism */ #include "cddefines.h" #include "iso.h" #include "dense.h" #include "phycon.h" #include "rt.h" STATIC realnum strkar( long nLo, long nHi ); void RT_stark(void) { long int ipLo, ipHi; double aa , ah, stark, strkla; DEBUG_ENTRY( "RT_stark()" ); /* only evaluate one time per zone */ static long int nZoneEval=-1; if( nzone==nZoneEval ) return; nZoneEval = nzone; for( long ipISO=ipH_LIKE; ipISO<NISO; ++ipISO ) { /* loop over all iso-electronic sequences */ for( long nelem=ipISO; nelem<LIMELM; ++nelem ) { if( !dense.lgElmtOn[nelem] ) continue; t_iso_sp* sp = &iso_sp[ipISO][nelem]; if( !rt.lgStarkON ) { for( ipHi=0; ipHi < sp->numLevels_max; ipHi++ ) { for( ipLo=0; ipLo < sp->numLevels_max; ipLo++ ) { sp->ex[ipHi][ipLo].pestrk = 0.; sp->ex[ipHi][ipLo].pestrk_up = 0.; } } continue; } /* evaluate Stark escape probability from * >>ref Puetter Ap.J. 251, 446. */ /* coefficients for Stark broadening escape probability * to be Puetters AH, equation 9b, needs factor of (Z^-4.5 * (nu*nl)^3 * xl) */ ah = 6.9e-6*1000./1e12/(phycon.sqrte*phycon.te10*phycon.te10* phycon.te03*phycon.te01*phycon.te01)*dense.eden; /* include Z factor */ ah *= powpq( (double)(nelem+1), -9, 2 ); /* coefficient for all lines except Ly alpha */ /* equation 10b, except missing tau^-0.6 */ stark = 0.264*pow(ah,0.4); /* coefficient for Ly alpha */ /* first few factors resemble equation 13c...what about the rest? */ strkla = 0.538*ah*4.*9.875*(phycon.sqrte/phycon.te10/phycon.te03); long ipHi = iso_ctrl.nLyaLevel[ipISO]; /* Lyman lines always have outer optical depths */ /* >>chng 02 mar 31, put in max, crashed on some first iteration * with negative optical depths, * NB did not understand why neg optical depths started */ aa = (realnum)max(0.,sp->trans(ipHi,0).Emis().TauIn()); aa = powpq( aa, -3, 4 ); sp->ex[ipHi][0].pestrk_up = strkla/2.*MAX2(1.,aa); /**\todo 2 - Stark is disabled for now since Lya escape causes density dependent * feedback on the radiative transfer. Would need to redo the escape * probs every time the electron density is updated - see blr89.in for an * example */ sp->ex[ipHi][0].pestrk_up = MIN2(.01,sp->ex[ipHi][0].pestrk_up); sp->ex[ipHi][0].pestrk_up = 0.; sp->ex[ipHi][0].pestrk = sp->ex[ipHi][0].pestrk_up * sp->trans(ipHi,0).Emis().Aul(); /* >>chng 06 aug 28, from numLevels_max to _local. */ for( ipHi=3; ipHi < sp->numLevels_local; ipHi++ ) { if( sp->trans(ipHi,0).ipCont() <= 0 ) continue; sp->ex[ipHi][0].pestrk_up = stark / 2. * strkar( sp->st[0].n(), sp->st[ipHi].n() ) * powpq(MAX2(1.,sp->trans(ipHi,0).Emis().TauIn()),-3,4); sp->ex[ipHi][0].pestrk_up = MIN2(.01,sp->ex[ipHi][0].pestrk_up); sp->ex[ipHi][0].pestrk = sp->trans(ipHi,0).Emis().Aul()* sp->ex[ipHi][0].pestrk_up; } /* zero out rates above iso.numLevels_local */ for( ipHi=sp->numLevels_local; ipHi < sp->numLevels_max; ipHi++ ) { sp->ex[ipHi][0].pestrk_up = 0.; sp->ex[ipHi][0].pestrk = 0.; } /* all other lines */ for( ipLo=ipH2s; ipLo < (sp->numLevels_local - 1); ipLo++ ) { for( ipHi=ipLo + 1; ipHi < sp->numLevels_local; ipHi++ ) { if( sp->trans(ipHi,ipLo).ipCont() <= 0 ) continue; aa = stark * strkar( sp->st[ipLo].n(), sp->st[ipHi].n() ) * powpq(MAX2(1.,sp->trans(ipHi,ipLo).Emis().TauIn()),-3,4); sp->ex[ipHi][ipLo].pestrk_up = (realnum)MIN2(.01,aa); sp->ex[ipHi][ipLo].pestrk = sp->trans(ipHi,ipLo).Emis().Aul()* sp->ex[ipHi][ipLo].pestrk_up; } } /* zero out rates above iso.numLevels_local */ for( ipLo=(sp->numLevels_local - 1); ipLo<(sp->numLevels_max - 1); ipLo++ ) { for( ipHi=ipLo + 1; ipHi < sp->numLevels_max; ipHi++ ) { sp->ex[ipHi][ipLo].pestrk_up = 0.; sp->ex[ipHi][ipLo].pestrk = 0.; } } } } return; } STATIC realnum strkar( long nLo, long nHi ) { return (realnum)pow((realnum)( nLo * nHi ),(realnum)1.2f); }
29.019868
89
0.606801
cloudy-astrophysics
8a0aad71238b49ec961a34ce84ac3b43ead05882
3,211
cpp
C++
SeqScript.cpp
Sgw32/R3E
8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd
[ "MIT" ]
7
2017-11-27T15:15:08.000Z
2021-03-29T16:53:22.000Z
SeqScript.cpp
Sgw32/R3E
8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd
[ "MIT" ]
null
null
null
SeqScript.cpp
Sgw32/R3E
8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd
[ "MIT" ]
4
2017-11-28T02:53:19.000Z
2021-01-29T10:37:52.000Z
///////////////////////////////////////////////////////////////////// ///////////////Original file by:Fyodor Zagumennov aka Sgw32////////// ///////////////Copyright(c) 2010 Fyodor Zagumennov ////////// ///////////////////////////////////////////////////////////////////// #include "SeqScript.h" //#include "Event.h" SeqScript::SeqScript() { time = 0; tim2=0; mInf=false; started =false; wait_before_start=0; disposed = false; first=false; elapsedt=0; lastt=0; time=0; } SeqScript::~SeqScript() { } void SeqScript::assign(Vector3 pos,Real length,String name,bool freezebefore,bool unfreezeafter,bool splineanims,bool hidehud) { mName = name; this->length=length; mStartPosition =pos; fb=freezebefore; unfreeze=unfreezeafter; //mCamera->setPosition(pos); mSceneMgr = global::getSingleton().getSceneManager(); // Spline it for nice curves // Create a track to animate the camera's node hhud=hidehud; } String SeqScript::getname() { return mName; } void SeqScript::setWait(Real wait) { wait_before_start = wait; } void SeqScript::addFrame(Real seconds) { } void SeqScript::start() { first=true; started =true; time=0; } void SeqScript::stop() { if (started) { time=0; started=false; } } bool SeqScript::frameStarted(const Ogre::FrameEvent &evt) { // if we called START /*if (started) mAnimState->addTime(evt.timeSinceLastFrame); if (!(tim2>wait_before_start)) tim2=tim2+evt.timeSinceLastFrame; if (tim2>wait_before_start) { if (!started) start(); time=time+evt.timeSinceLastFrame; if (!(time>length)) { } if (time>length) { dispose(); } }*/ if (wait_before_start==0) { if (started) { /*if (first) {*/ vector<Real>::iterator j; vector<String>::iterator k; for (i=0;i!=scripts.size();i++) { if (time>scripts_s[i]) { LogManager::getSingleton().logMessage("SeqScript: Running lua script!"); RunLuaScript(global::getSingleton().getLuaState(), scripts[i].c_str()); scripts_s[i]=-1; //first=false; } } bool stop=true; while (stop) { stop=false; i=0; for (j=scripts_s.begin();j!=scripts_s.end();j++) { if (!stop) { if ((*j)==-1) { LogManager::getSingleton().logMessage("Erasing a lua script..."); scripts_s.erase(j); k=scripts.begin(); advance(k,i); scripts.erase(k); stop=true; } i++; if (stop) break; } } } //} if (evt.timeSinceLastFrame<3.0f) //discrapency!!! time+=evt.timeSinceLastFrame; //} if ((time>=length)&&!mInf) { dispose(); } if ((time>length)&&mInf) { time=0.1f; } } } else { if (!(tim2>wait_before_start)) tim2+=evt.timeSinceLastFrame; if (tim2>wait_before_start) { start(); wait_before_start=0; } } return true; } void SeqScript::dispose() { if (!disposed) { if (first) { LogManager::getSingleton().logMessage("Disposing SeqScript. It has been used ingame"); started =false; disposed=true; } else { LogManager::getSingleton().logMessage("Disposing SeqScript. It wasn't used ingame"); disposed=true; } } }
16.723958
126
0.580193
Sgw32
8a0ea18187e60ea7f6ee587e479ce6ef684cdab2
1,594
hpp
C++
include/visualization/scorep_substrate_rrl.hpp
umbreensabirmain/readex-rrl
0cb73b3a3c6948a8dbdce96c240b24d8e992c2fe
[ "BSD-3-Clause" ]
1
2019-10-09T09:15:47.000Z
2019-10-09T09:15:47.000Z
include/visualization/scorep_substrate_rrl.hpp
readex-eu/readex-rrl
ac8722c44f84d65668e2a60e4237ebf51b298c9b
[ "BSD-3-Clause" ]
null
null
null
include/visualization/scorep_substrate_rrl.hpp
readex-eu/readex-rrl
ac8722c44f84d65668e2a60e4237ebf51b298c9b
[ "BSD-3-Clause" ]
1
2018-07-13T11:31:05.000Z
2018-07-13T11:31:05.000Z
/* * scorep_substrate_rrl.hpp * * Created on: Feb 21, 2017 * Author: mian */ #ifndef INCLUDE_VISUALIZATION_SCOREP_SUBSTRATE_RRL_HPP_ #define INCLUDE_VISUALIZATION_SCOREP_SUBSTRATE_RRL_HPP_ #include <scorep/plugin/plugin.hpp> namespace spp = scorep::plugin::policy; using scorep_clock = scorep::chrono::measurement_clock; using scorep::plugin::log::logging; namespace rrl { // Our metric handle. struct visualization_metric { visualization_metric(const std::string &name_, int value_) : name(name_), value(value_) { } std::string name; int value; }; template <typename T, typename P> using visualization_object_id = spp::object_id<visualization_metric, T, P>; class scorep_substrate_rrl : public scorep::plugin::base<scorep_substrate_rrl, spp::per_process, spp::sync, spp::scorep_clock, visualization_object_id> { public: scorep_substrate_rrl(); ~scorep_substrate_rrl(); void add_metric(visualization_metric &handle); template <typename P> void get_optional_value(visualization_metric &handle, P &proxy); std::vector<scorep::plugin::metric_property> get_metric_properties( const std::string &metric_name); private: std::hash<std::string> metric_name_hash; /**< function to hash the names of the metrics */ static const std::string atp_prefix_; scorep::plugin::metric_property add_metric_property(const std::string &name); }; } #endif /* INCLUDE_VISUALIZATION_SCOREP_SUBSTRATE_RRL_HPP_ */
31.88
94
0.69197
umbreensabirmain
8a18f59907a1f99ab38f599025f1ddd08fa8e14b
11,693
cpp
C++
src/core/OTData.cpp
grealish/opentxs
614999063079f5843428abcaa62974f5f19f88a1
[ "Apache-2.0" ]
1
2015-01-23T13:24:07.000Z
2015-01-23T13:24:07.000Z
src/core/OTData.cpp
grealish/opentxs
614999063079f5843428abcaa62974f5f19f88a1
[ "Apache-2.0" ]
null
null
null
src/core/OTData.cpp
grealish/opentxs
614999063079f5843428abcaa62974f5f19f88a1
[ "Apache-2.0" ]
null
null
null
/************************************************************ * * OTData.cpp * */ /************************************************************ -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 * OPEN TRANSACTIONS * * Financial Cryptography and Digital Cash * Library, Protocol, API, Server, CLI, GUI * * -- Anonymous Numbered Accounts. * -- Untraceable Digital Cash. * -- Triple-Signed Receipts. * -- Cheques, Vouchers, Transfers, Inboxes. * -- Basket Currencies, Markets, Payment Plans. * -- Signed, XML, Ricardian-style Contracts. * -- Scripted smart contracts. * * Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym) * * EMAIL: * FellowTraveler@rayservers.net * * BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ * * KEY FINGERPRINT (PGP Key in license file): * 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E * * OFFICIAL PROJECT WIKI(s): * https://github.com/FellowTraveler/Moneychanger * https://github.com/FellowTraveler/Open-Transactions/wiki * * WEBSITE: * http://www.OpenTransactions.org/ * * Components and licensing: * -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3 * -- otlib.........A class library.......LICENSE:...LAGPLv3 * -- otapi.........A client API..........LICENSE:...LAGPLv3 * -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3 * -- otserver......Server Application....LICENSE:....AGPLv3 * Github.com/FellowTraveler/Open-Transactions/wiki/Components * * All of the above OT components were designed and written by * Fellow Traveler, with the exception of Moneychanger, which * was contracted out to Vicky C (bitcointrader4@gmail.com). * The open-source community has since actively contributed. * * ----------------------------------------------------- * * LICENSE: * This program is free software: you can redistribute it * and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your * option) any later version. * * ADDITIONAL PERMISSION under the GNU Affero GPL version 3 * section 7: (This paragraph applies only to the LAGPLv3 * components listed above.) If you modify this Program, or * any covered work, by linking or combining it with other * code, such other code is not for that reason alone subject * to any of the requirements of the GNU Affero GPL version 3. * (==> This means if you are only using the OT API, then you * don't have to open-source your code--only your changes to * Open-Transactions itself must be open source. Similar to * LGPLv3, except it applies to software-as-a-service, not * just to distributing binaries.) * * Extra WAIVER for OpenSSL, Lucre, and all other libraries * used by Open Transactions: This program is released under * the AGPL with the additional exemption that compiling, * linking, and/or using OpenSSL is allowed. The same is true * for any other open source libraries included in this * project: complete waiver from the AGPL is hereby granted to * compile, link, and/or use them with Open-Transactions, * according to their own terms, as long as the rest of the * Open-Transactions terms remain respected, with regard to * the Open-Transactions code itself. * * Lucre License: * This code is also "dual-license", meaning that Ben Lau- * rie's license must also be included and respected, since * the code for Lucre is also included with Open Transactions. * See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt * The Laurie requirements are light, but if there is any * problem with his license, simply remove the Lucre code. * Although there are no other blind token algorithms in Open * Transactions (yet. credlib is coming), the other functions * will continue to operate. * See Lucre on Github: https://github.com/benlaurie/lucre * ----------------------------------------------------- * You should have received a copy of the GNU Affero General * Public License along with this program. If not, see: * http://www.gnu.org/licenses/ * * If you would like to use this software outside of the free * software license, please contact FellowTraveler. * (Unfortunately many will run anonymously and untraceably, * so who could really stop them?) * * DISCLAIMER: * This program is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for * more details. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1 sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd kamH0Y/n11lCvo1oQxM+ =uSzz -----END PGP SIGNATURE----- **************************************************************/ #include <opentxs/core/OTData.hpp> #include <opentxs/core/crypto/OTASCIIArmor.hpp> #include <opentxs/core/crypto/OTPassword.hpp> #include <opentxs/core/util/Assert.hpp> #include <utility> #include <cstring> #include <cstdint> namespace opentxs { OTData::OTData() : data_(nullptr) , position_(0) , size_(0) { } OTData::OTData(const OTData& source) : data_(nullptr) , position_(0) , size_(0) { Assign(source); } OTData::OTData(const OTASCIIArmor& source) : data_(nullptr) , position_(0) , size_(0) { if (source.Exists()) { source.GetData(*this); } } OTData::OTData(const void* data, uint32_t size) : data_(nullptr) , position_(0) , size_(0) { Assign(data, size); } OTData::~OTData() { Release(); } bool OTData::operator==(const OTData& rhs) const { if (size_ != rhs.size_) { return false; } if (size_ == 0 && rhs.size_ == 0) { return true; } // TODO security: replace memcmp with a more secure // version. Still, though, I am managing it internal to // the class. if (std::memcmp(data_, rhs.data_, size_) == 0) { return true; } return false; } bool OTData::operator!=(const OTData& rhs) const { return !operator==(rhs); } // First use reset() to set the internal position to 0. // Then you pass in the buffer where the results go. // You pass in the length of that buffer. // It returns how much was actually read. // If you start at position 0, and read 100 bytes, then // you are now on position 100, and the next OTfread will // proceed from that position. (Unless you reset().) uint32_t OTData::OTfread(uint8_t* data, uint32_t size) { OT_ASSERT(data != nullptr && size > 0); uint32_t sizeToRead = 0; if (data_ != nullptr && position_ < GetSize()) { // If the size is 20, and position is 5 (I've already read the first 5 // bytes) then the size remaining to read is 15. That is, GetSize() // minus position_. sizeToRead = GetSize() - position_; if (size < sizeToRead) { sizeToRead = size; } OTPassword::safe_memcpy( data, size, static_cast<uint8_t*>(data_) + position_, sizeToRead); position_ += sizeToRead; } return sizeToRead; } void OTData::zeroMemory() const { if (data_ != nullptr) { OTPassword::zeroMemory(data_, size_); } } void OTData::Release() { if (data_ != nullptr) { // For security reasons, we clear the memory to 0 when deleting the // object. (Seems smart.) OTPassword::zeroMemory(data_, size_); delete[] static_cast<uint8_t*>(data_); // If data_ was already nullptr, no need to re-Initialize(). Initialize(); } } OTData& OTData::operator=(OTData rhs) { swap(rhs); return *this; } void OTData::swap(OTData& rhs) { std::swap(data_, rhs.data_); std::swap(position_, rhs.position_); std::swap(size_, rhs.size_); } void OTData::Assign(const OTData& source) { // can't assign to self. if (&source == this) { return; } if (!source.IsEmpty()) { Assign(source.data_, source.size_); } else { // Otherwise if it's empty, then empty this also. Release(); } } bool OTData::IsEmpty() const { return size_ < 1; } void OTData::Assign(const void* data, uint32_t size) { // This releases all memory and zeros out all members. Release(); if (data != nullptr && size > 0) { data_ = static_cast<void*>(new uint8_t[size]); OT_ASSERT(data_ != nullptr); OTPassword::safe_memcpy(data_, size, data, size); size_ = size; } // TODO: else error condition. Could just ASSERT() this. } bool OTData::Randomize(uint32_t size) { Release(); // This releases all memory and zeros out all members. if (size > 0) { data_ = static_cast<void*>(new uint8_t[size]); OT_ASSERT(data_ != nullptr); if (!OTPassword::randomizeMemory_uint8(static_cast<uint8_t*>(data_), size)) { // randomizeMemory already logs, so I'm not logging again twice // here. delete[] static_cast<uint8_t*>(data_); data_ = nullptr; return false; } size_ = size; return true; } // else error condition. Could just ASSERT() this. return false; } void OTData::Concatenate(const void* data, uint32_t size) { OT_ASSERT(data != nullptr); OT_ASSERT(size > 0); if (size == 0) { return; } if (size_ == 0) { Assign(data, size); return; } void* newData = nullptr; uint32_t newSize = GetSize() + size; if (newSize > 0) { newData = static_cast<void*>(new uint8_t[newSize]); OT_ASSERT(newData != nullptr); OTPassword::zeroMemory(newData, newSize); } // If there's a new memory buffer (for the combined..) if (newData != nullptr) { // if THIS object has data inside of it... if (!IsEmpty()) { // Copy THIS object into the new // buffer, starting at the // beginning. OTPassword::safe_memcpy(newData, newSize, data_, GetSize()); } // Next we copy the data being appended... OTPassword::safe_memcpy(static_cast<uint8_t*>(newData) + GetSize(), newSize - GetSize(), data, size); } if (data_ != nullptr) { delete[] static_cast<uint8_t*>(data_); } data_ = newData; size_ = newSize; } OTData& OTData::operator+=(const OTData& rhs) { if (rhs.GetSize() > 0) { Concatenate(rhs.data_, rhs.GetSize()); } return *this; } void OTData::SetSize(uint32_t size) { Release(); if (size > 0) { data_ = static_cast<void*>(new uint8_t[size]); OT_ASSERT(data_ != nullptr); OTPassword::zeroMemory(data_, size); size_ = size; } } } // namespace opentxs
29.829082
78
0.635252
grealish