blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
046fe3a10da5fd7e0b5fa67d99c9a3c52e12f446
c4074e42d9120b42c5aa60f64f6cf0c7ade68f94
/Buckland_Chapter7 to 10_Raven/Goal_SeekToPosition_Z.h
09e3684a1c962e3e3734d1ac34e91552b3ff37ab
[]
no_license
azero18/RavenIAGv2
2466cde2796a184d9d3fe4e45199075a4c742057
dfda8c3fe4038c2b68ecddfb56042441c8aa50f8
refs/heads/master
2021-01-01T15:59:01.140864
2015-03-18T18:32:12
2015-03-18T18:35:05
32,476,189
0
0
null
2015-03-20T15:13:31
2015-03-18T18:15:37
C++
UTF-8
C++
false
false
776
h
Goal_SeekToPosition_Z.h
#ifndef GOAL_SEEK_TO_POSITIONZ_H #define GOAL_SEEK_TO_POSITIONZ_H #pragma warning (disable:4786) #include "Goal_Z.h" #include "2d/Vector2D.h" #include "Raven_Goal_Types_Z.h" #include "Raven_Bot_Z.h" class Goal_SeekToPosition_Z : public Goal_Z<Raven_Bot_Z> { private: //the position the bot is moving to Vector2D m_vPosition; //the approximate time the bot should take to travel the target location double m_dTimeToReachPos; //this records the time this goal was activated double m_dStartTime; //returns true if a bot gets stuck bool isStuck()const; public: Goal_SeekToPosition_Z(Raven_Bot_Z* pBot, Vector2D target); //the usual suspects void Activate(); int Process(); void Terminate(); void Render(); }; #endif
5a83efab961f82fe5cc7faefe0264a6a39166fac
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/CEF3/pristine/cef_source/libcef/browser/context.cc
e419d04012d1cca3b2870cd486c08012bdf815d1
[ "MIT", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
16,939
cc
context.cc
// Copyright (c) 2012 The Chromium Embedded Framework 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 "libcef/browser/context.h" #include "libcef/browser/browser_host_impl.h" #include "libcef/browser/browser_info.h" #include "libcef/browser/browser_info_manager.h" #include "libcef/browser/browser_main.h" #include "libcef/browser/browser_message_loop.h" #include "libcef/browser/chrome_browser_process_stub.h" #include "libcef/browser/thread_util.h" #include "libcef/browser/trace_subscriber.h" #include "libcef/common/cef_switches.h" #include "libcef/common/main_delegate.h" #include "libcef/common/widevine_loader.h" #include "libcef/renderer/content_renderer_client.h" #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/debug/debugger.h" #include "base/files/file_util.h" #include "base/synchronization/waitable_event.h" #include "content/app/content_service_manager_main_delegate.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" #include "services/service_manager/embedder/main.h" #include "ui/base/ui_base_switches.h" #if defined(OS_WIN) #include "base/strings/utf_string_conversions.h" #include "chrome_elf/chrome_elf_main.h" #include "content/public/app/sandbox_helper_win.h" #include "components/crash/content/app/crashpad.h" #include "sandbox/win/src/sandbox_types.h" #endif #if defined(OS_MACOSX) || defined(OS_WIN) #include "components/crash/content/app/crash_switches.h" #include "third_party/crashpad/crashpad/handler/handler_main.h" #endif namespace { CefContext* g_context = NULL; // Force shutdown when the process terminates if a context currently exists and // CefShutdown() has not been explicitly called. class CefForceShutdown { public: ~CefForceShutdown() { if (g_context) { g_context->Shutdown(); delete g_context; g_context = NULL; } } } g_force_shutdown; #if defined(OS_WIN) #if defined(ARCH_CPU_X86_64) // VS2013 only checks the existence of FMA3 instructions, not the enabled-ness // of them at the OS level (this is fixed in VS2015). We force off usage of // FMA3 instructions in the CRT to avoid using that path and hitting illegal // instructions when running on CPUs that support FMA3, but OSs that don't. void DisableFMA3() { static bool disabled = false; if (disabled) return; disabled = true; _set_FMA3_enable(0); } #endif // defined(ARCH_CPU_X86_64) // Signal chrome_elf to initialize crash reporting, rather than doing it in // DllMain. See https://crbug.com/656800 for details. void InitCrashReporter() { static bool initialized = false; if (initialized) return; initialized = true; SignalInitializeCrashReporting(); } #endif // defined(OS_WIN) #if defined(OS_MACOSX) || defined(OS_WIN) // Based on components/crash/content/app/run_as_crashpad_handler_win.cc // Remove the "--type=crashpad-handler" command-line flag that will otherwise // confuse the crashpad handler. // Chrome uses an embedded crashpad handler on Windows only and imports this // function via the existing "run_as_crashpad_handler" target defined in // components/crash/content/app/BUILD.gn. CEF uses an embedded handler on both // Windows and macOS so we define the function here instead of using the // existing target (because we can't use that target on macOS). int RunAsCrashpadHandler(const base::CommandLine& command_line) { base::CommandLine::StringVector argv = command_line.argv(); const base::CommandLine::StringType process_type = FILE_PATH_LITERAL("--type="); argv.erase(std::remove_if(argv.begin(), argv.end(), [&process_type](const base::CommandLine::StringType& str) { return base::StartsWith(str, process_type, base::CompareCase::SENSITIVE) || (!str.empty() && str[0] == L'/'); }), argv.end()); #if defined(OS_MACOSX) // HandlerMain on macOS uses the system version of getopt_long which expects // the first argument to be the program name. argv.insert(argv.begin(), command_line.GetProgram().value()); #endif std::unique_ptr<char* []> argv_as_utf8(new char*[argv.size() + 1]); std::vector<std::string> storage; storage.reserve(argv.size()); for (size_t i = 0; i < argv.size(); ++i) { #if defined(OS_WIN) storage.push_back(base::UTF16ToUTF8(argv[i])); #else storage.push_back(argv[i]); #endif argv_as_utf8[i] = &storage[i][0]; } argv_as_utf8[argv.size()] = nullptr; argv.clear(); return crashpad::HandlerMain(static_cast<int>(storage.size()), argv_as_utf8.get(), nullptr); } #endif // defined(OS_MACOSX) || defined(OS_WIN) bool GetColor(const cef_color_t cef_in, bool is_windowless, SkColor* sk_out) { // Windowed browser colors must be fully opaque. if (!is_windowless && CefColorGetA(cef_in) != SK_AlphaOPAQUE) return false; // Windowless browser colors may be fully transparent. if (is_windowless && CefColorGetA(cef_in) == SK_AlphaTRANSPARENT) { *sk_out = SK_ColorTRANSPARENT; return true; } // Ignore the alpha component. *sk_out = SkColorSetRGB(CefColorGetR(cef_in), CefColorGetG(cef_in), CefColorGetB(cef_in)); return true; } } // namespace int CefExecuteProcess(const CefMainArgs& args, CefRefPtr<CefApp> application, void* windows_sandbox_info) { #if defined(OS_WIN) #if defined(ARCH_CPU_X86_64) DisableFMA3(); #endif InitCrashReporter(); #endif base::CommandLine command_line(base::CommandLine::NO_PROGRAM); #if defined(OS_WIN) command_line.ParseFromString(::GetCommandLineW()); #else command_line.InitFromArgv(args.argc, args.argv); #endif // Wait for the debugger as early in process initialization as possible. if (command_line.HasSwitch(switches::kWaitForDebugger)) base::debug::WaitForDebugger(60, true); // If no process type is specified then it represents the browser process and // we do nothing. std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType); if (process_type.empty()) return -1; #if defined(OS_MACOSX) || defined(OS_WIN) if (process_type == crash_reporter::switches::kCrashpadHandler) return RunAsCrashpadHandler(command_line); #endif CefMainDelegate main_delegate(application); // Execute the secondary process. #if defined(OS_WIN) sandbox::SandboxInterfaceInfo sandbox_info = {0}; if (windows_sandbox_info == NULL) { content::InitializeSandboxInfo(&sandbox_info); windows_sandbox_info = &sandbox_info; } content::ContentMainParams params(&main_delegate); params.instance = args.instance; params.sandbox_info = static_cast<sandbox::SandboxInterfaceInfo*>(windows_sandbox_info); return content::ContentMain(params); #else content::ContentMainParams params(&main_delegate); params.argc = args.argc; params.argv = const_cast<const char**>(args.argv); return content::ContentMain(params); #endif } bool CefInitialize(const CefMainArgs& args, const CefSettings& settings, CefRefPtr<CefApp> application, void* windows_sandbox_info) { #if defined(OS_WIN) #if defined(ARCH_CPU_X86_64) DisableFMA3(); #endif InitCrashReporter(); #endif // Return true if the global context already exists. if (g_context) return true; if (settings.size != sizeof(cef_settings_t)) { NOTREACHED() << "invalid CefSettings structure size"; return false; } g_browser_process = new ChromeBrowserProcessStub(); // Create the new global context object. g_context = new CefContext(); // Initialize the global context. return g_context->Initialize(args, settings, application, windows_sandbox_info); } void CefShutdown() { // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } // Must always be called on the same thread as Initialize. if (!g_context->OnInitThread()) { NOTREACHED() << "called on invalid thread"; return; } // Shut down the global context. This will block until shutdown is complete. g_context->Shutdown(); // Delete the global context object. delete g_context; g_context = NULL; } void CefDoMessageLoopWork() { // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } // Must always be called on the same thread as Initialize. if (!g_context->OnInitThread()) { NOTREACHED() << "called on invalid thread"; return; } CefBrowserMessageLoop::current()->DoMessageLoopIteration(); } void CefRunMessageLoop() { // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } // Must always be called on the same thread as Initialize. if (!g_context->OnInitThread()) { NOTREACHED() << "called on invalid thread"; return; } CefBrowserMessageLoop::current()->RunMessageLoop(); } void CefQuitMessageLoop() { // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } // Must always be called on the same thread as Initialize. if (!g_context->OnInitThread()) { NOTREACHED() << "called on invalid thread"; return; } CefBrowserMessageLoop::current()->QuitWhenIdle(); } void CefSetOSModalLoop(bool osModalLoop) { #if defined(OS_WIN) // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } if (CEF_CURRENTLY_ON_UIT()) base::MessageLoop::current()->set_os_modal_loop(osModalLoop); else CEF_POST_TASK(CEF_UIT, base::Bind(CefSetOSModalLoop, osModalLoop)); #endif // defined(OS_WIN) } // CefContext CefContext::CefContext() : initialized_(false), shutting_down_(false), init_thread_id_(0) { } CefContext::~CefContext() { } // static CefContext* CefContext::Get() { return g_context; } bool CefContext::Initialize(const CefMainArgs& args, const CefSettings& settings, CefRefPtr<CefApp> application, void* windows_sandbox_info) { init_thread_id_ = base::PlatformThread::CurrentId(); settings_ = settings; #if !defined(OS_WIN) if (settings.multi_threaded_message_loop) { NOTIMPLEMENTED() << "multi_threaded_message_loop is not supported."; return false; } #endif #if defined(OS_WIN) // Signal Chrome Elf that Chrome has begun to start. SignalChromeElf(); #endif main_delegate_.reset(new CefMainDelegate(application)); browser_info_manager_.reset(new CefBrowserInfoManager); int exit_code; // Initialize the content runner. content::ContentMainParams params(main_delegate_.get()); #if defined(OS_WIN) sandbox::SandboxInterfaceInfo sandbox_info = {0}; if (windows_sandbox_info == NULL) { content::InitializeSandboxInfo(&sandbox_info); windows_sandbox_info = &sandbox_info; settings_.no_sandbox = true; } params.instance = args.instance; params.sandbox_info = static_cast<sandbox::SandboxInterfaceInfo*>(windows_sandbox_info); #else params.argc = args.argc; params.argv = const_cast<const char**>(args.argv); #endif sm_main_delegate_.reset( new content::ContentServiceManagerMainDelegate(params)); sm_main_params_.reset( new service_manager::MainParams(sm_main_delegate_.get())); exit_code = service_manager::MainInitialize(*sm_main_params_); DCHECK_LT(exit_code, 0); if (exit_code >= 0) return false; static_cast<ChromeBrowserProcessStub*>(g_browser_process)->Initialize( *base::CommandLine::ForCurrentProcess()); // Run the process. Results in a call to CefMainDelegate::RunProcess() which // will create the browser runner and message loop without blocking. exit_code = service_manager::MainRun(*sm_main_params_); initialized_ = true; if (CEF_CURRENTLY_ON_UIT()) { OnContextInitialized(); } else { // Continue initialization on the UI thread. CEF_POST_TASK(CEF_UIT, base::Bind(&CefContext::OnContextInitialized, base::Unretained(this))); } return true; } void CefContext::Shutdown() { // Must always be called on the same thread as Initialize. DCHECK(OnInitThread()); shutting_down_ = true; if (settings_.multi_threaded_message_loop) { // Events that will be used to signal when shutdown is complete. Start in // non-signaled mode so that the event will block. base::WaitableEvent uithread_shutdown_event( base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); // Finish shutdown on the UI thread. CEF_POST_TASK(CEF_UIT, base::Bind(&CefContext::FinishShutdownOnUIThread, base::Unretained(this), &uithread_shutdown_event)); /// Block until UI thread shutdown is complete. uithread_shutdown_event.Wait(); FinalizeShutdown(); } else { // Finish shutdown on the current thread, which should be the UI thread. FinishShutdownOnUIThread(NULL); FinalizeShutdown(); } } bool CefContext::OnInitThread() { return (base::PlatformThread::CurrentId() == init_thread_id_); } SkColor CefContext::GetBackgroundColor( const CefBrowserSettings* browser_settings, cef_state_t windowless_state) const { bool is_windowless = windowless_state == STATE_ENABLED ? true : (windowless_state == STATE_DISABLED ? false : !!settings_.windowless_rendering_enabled); // Default to opaque white if no acceptable color values are found. SkColor sk_color = SK_ColorWHITE; if (!browser_settings || !GetColor(browser_settings->background_color, is_windowless, &sk_color)) { GetColor(settings_.background_color, is_windowless, &sk_color); } return sk_color; } CefTraceSubscriber* CefContext::GetTraceSubscriber() { CEF_REQUIRE_UIT(); if (shutting_down_) return NULL; if (!trace_subscriber_.get()) trace_subscriber_.reset(new CefTraceSubscriber()); return trace_subscriber_.get(); } void CefContext::PopulateRequestContextSettings( CefRequestContextSettings* settings) { CefRefPtr<CefCommandLine> command_line = CefCommandLine::GetGlobalCommandLine(); CefString(&settings->cache_path) = CefString(&settings_.cache_path); settings->persist_session_cookies = settings_.persist_session_cookies || command_line->HasSwitch(switches::kPersistSessionCookies); settings->persist_user_preferences = settings_.persist_user_preferences || command_line->HasSwitch(switches::kPersistUserPreferences); settings->ignore_certificate_errors = settings_.ignore_certificate_errors || command_line->HasSwitch(switches::kIgnoreCertificateErrors); settings->enable_net_security_expiration = settings_.enable_net_security_expiration || command_line->HasSwitch(switches::kEnableNetSecurityExpiration); CefString(&settings->accept_language_list) = CefString(&settings_.accept_language_list); } void CefContext::OnContextInitialized() { CEF_REQUIRE_UIT(); static_cast<ChromeBrowserProcessStub*>(g_browser_process)-> OnContextInitialized(); #if defined(WIDEVINE_CDM_AVAILABLE) && BUILDFLAG(ENABLE_PEPPER_CDMS) CefWidevineLoader::GetInstance()->OnContextInitialized(); #endif // Notify the handler. CefRefPtr<CefApp> app = CefContentClient::Get()->application(); if (app.get()) { CefRefPtr<CefBrowserProcessHandler> handler = app->GetBrowserProcessHandler(); if (handler.get()) handler->OnContextInitialized(); } } void CefContext::FinishShutdownOnUIThread( base::WaitableEvent* uithread_shutdown_event) { CEF_REQUIRE_UIT(); browser_info_manager_->DestroyAllBrowsers(); if (trace_subscriber_.get()) trace_subscriber_.reset(NULL); static_cast<ChromeBrowserProcessStub*>(g_browser_process)->Shutdown(); if (uithread_shutdown_event) uithread_shutdown_event->Signal(); } void CefContext::FinalizeShutdown() { if (content::RenderProcessHost::run_renderer_in_process()) { // Blocks until RenderProcess cleanup is complete. CefContentRendererClient::Get()->RunSingleProcessCleanup(); } // Shut down the browser runner or UI thread. main_delegate_->ShutdownBrowser(); // Shut down the content runner. service_manager::MainShutdown(*sm_main_params_); browser_info_manager_.reset(NULL); sm_main_params_.reset(NULL); sm_main_delegate_.reset(NULL); main_delegate_.reset(NULL); }
6afb2cf600aa8ec505ba9fd2dd9fdb49525daad7
cf51ef762288c9033085783d2cad0389a452ff45
/cursesWindow.cpp
832dc867e0401279b6ff6fc183c0b2931077b133
[]
no_license
AdRiley/AquaAntelope
506137becc89d3c1bb307a4697a142118fd97c4f
e4b56a976e2234598cc5a1de2e295ee122e7dfd4
refs/heads/master
2020-04-17T21:55:08.243519
2014-09-29T16:54:23
2014-09-29T16:54:23
23,805,665
1
0
null
null
null
null
UTF-8
C++
false
false
1,529
cpp
cursesWindow.cpp
#include "cursesWindow.h" cursesWindow::cursesWindow() : m_win(initscr()) { if (!m_win) throw "Error initialising ncurses."; noecho(); // Turn off key echoing keypad(m_win, TRUE); // Enable the keypad for non-char keys curs_set(0); // Hide the cursor } cursesWindow::~cursesWindow() { curs_set(1); echo(); delwin(m_win); endwin(); refresh(); } /*static*/ void cursesWindow::DrawMap(const std::vector<std::vector<TileType>>& v) { int y = 0; for(auto yv : v) { int x = 0; for(auto t : yv) { mvaddstr(y, x, (t==TileType::Floor ? "." : "#")); ++x; } ++y; } } /*static*/ void cursesWindow::DrawPlayer(Player player) { mvaddstr(player.m_PosY, player.m_PosX, "@"); refresh(); } Command cursesWindow::GetCommand() { while (true) { int keyPress = getch(); switch( keyPress ) { case KEY_DOWN: return Command::Down; break; case KEY_LEFT: return Command::Left; break; case KEY_RIGHT: return Command::Right; break; case KEY_UP: return Command::Up; break; case KEY_BACKSPACE: return Command::Exit; break; default: break; } } } /*static*/ void cursesWindow::Clear() { clear(); }
d718532b5859b55691303e9ca4fdb6d02e025f38
4058a231a1087fe458092d071cf9dacba608c4a1
/Source/_Common/AI/BTTask_BP.h
03b1c078eaa10292712fff9d8ff450296d59fd5b
[]
no_license
piandpower/UEModule
99f54d8789e6e50bce686684753ce4db86567573
8c061f1d2a2476ab177bd154e4341123394f2e90
refs/heads/master
2021-05-15T00:36:22.786464
2017-09-12T15:56:40
2017-09-12T15:56:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,475
h
BTTask_BP.h
#pragma once #include "BehaviorTree/BTTaskNode.h" #include "BTTask_BP.generated.h" // this is for Blueprint's parent UCLASS(Abstract,Blueprintable) class _COMMON_API UBTTask_BP : public UBTTaskNode { GENERATED_BODY() public : UPROPERTY(editinstanceonly, Category=Description) bool IsShowPropertyDetails = true; protected : UFUNCTION( BlueprintImplementableEvent, meta=(BlueprintProtected, DisplayName="Execute Task")) bool _ExecuteTask( AController* pController, APawn* pPawn ); UFUNCTION( BlueprintNativeEvent, meta=(BlueprintProtected, DisplayName="Node Description")) FString _NodeDescription( FString& sParentNodeDesc ) const; FString _NodeDescription_Implementation( FString& sParentNodeDesc ){ return sParentNodeDesc; } protected : UBTTask_BP() { NodeName = "Task"; } public : virtual EBTNodeResult::Type ExecuteTask( UBehaviorTreeComponent& rBTComponent, uint8* pNodeMemory ) override { AController* pController = TL::Controller<AController>::Get( rBTComponent ); if( nullptr == pController ) return EBTNodeResult::Failed; return _ExecuteTask( pController, pController->GetPawn() ) ? EBTNodeResult::Succeeded : EBTNodeResult::Failed; } virtual void DescribeRuntimeValues(const UBehaviorTreeComponent& rBTComponent, uint8* pNodeMemory, EBTDescriptionVerbosity::Type Verbosity, TArray<FString>& Values) const override; virtual FString GetStaticDescription() const override; };
35af7b354422dbe51cc5a50220875d49655a94f4
3322c2fcce9a7791e649533054540a0ceb23ad8e
/Include/QTSDataFieldDefine.h
6e54c7c236f47f6a2f3b79d94d1956ba59daae00
[]
no_license
jeffreymu/GTA-QTS-API
052a8e4c3185c23b46b0a447ac3c5bf404ee02e1
0e6c22edd1f8f655a5b2eecf11674cbfa37a8fae
refs/heads/master
2022-12-09T19:21:30.739658
2020-09-15T04:23:45
2020-09-15T04:23:45
295,612,351
0
0
null
null
null
null
GB18030
C++
false
false
9,897
h
QTSDataFieldDefine.h
////////////////////////////////////////////////////////////////////////////// /// @file QTSDataFieldDefine.h /// @brief 数据类定义文件,包括数据缓存模板类,按字段访问类,字段数据类定义 /// @copyright Copyright (C), 2008-2014, GTA Information Tech. Co., Ltd. /// @version 2.0 /// @date 2014.7.18 ////////////////////////////////////////////////////////////////////////////// #ifndef GTA_QTS_DATA_FIELD_DEFINE_H_ #define GTA_QTS_DATA_FIELD_DEFINE_H_ #include <memory> #include "QTSDataType.h" #include "QTSStruct.h" /// 数据缓存模板,用于管理返回数据内存 template<class T> class GTA_API_EXPORT CDataBuffer { public: /// 构造函数 /// @param bAutoDel -- 对象析构时自动删除内存标志 CDataBuffer(bool bAutoDel = true) :m_DataBuffer(NULL),m_nSize(0),m_nStore(0),m_bAutoDel(bAutoDel){} virtual ~CDataBuffer() { if (NULL != m_DataBuffer && m_bAutoDel) { delete [] m_DataBuffer; } } /// 清空数据,重置缓存大小 void ReSize(int nSize) { m_nSize = nSize; if (nSize > m_nStore) { if (NULL != m_DataBuffer) { delete [] m_DataBuffer; m_DataBuffer = NULL; } m_nStore = nSize; m_DataBuffer = new T[nSize]; } memset(m_DataBuffer, 0, sizeof(T) * m_nStore); } /// 返回数据首地址 operator T *() { return m_DataBuffer; } T& operator [](int nIndex) { if (nIndex >= m_nSize || nIndex < 0) { nIndex = 0; } return m_DataBuffer[nIndex]; } int Size() { return m_nSize; } private: CDataBuffer(const CDataBuffer<T>& other){} CDataBuffer& operator = (const CDataBuffer<T> &other){} T* m_DataBuffer; ///< 数据指针 int m_nSize; ///< 实际数据大小 int m_nStore; ///< 缓存容量大小 bool m_bAutoDel; ///< 自动删除内存标志,C接口需要保留内存返回用户,单独接口调用删除内存 }; /// 公告数据缓存,用于管理返回数据内存 template<> class GTA_API_EXPORT CDataBuffer<SZSEL1_Bulletin> { public: /// 构造函数 /// @param bAutoDel -- 对象析构时自动删除内存标志 CDataBuffer(bool bAutoDel = true) :m_DataBuffer(NULL),m_nSize(0),m_nStore(0),m_bAutoDel(bAutoDel){} virtual ~CDataBuffer() { if (NULL != m_DataBuffer && m_bAutoDel) { delete [] (char*)m_DataBuffer; } } /// 返回数据首地址 operator SZSEL1_Bulletin *() { return m_DataBuffer; } int Size() { return m_nSize; } SZSEL1_Bulletin& operator [](int nIndex) { if (nIndex >= m_nSize || nIndex < 0) { nIndex = 0; } SZSEL1_Bulletin *pbuf = m_DataBuffer; for (int i = 0; i < nIndex; i++) { pbuf += sizeof(SZSEL1_BulletinHead) + pbuf->RawHead.RawDataLength; } return *pbuf; } /// 重置数据指针 /// @param buff 数据起始地址 /// @param nsize SZSEL1_Bulletin的个数 void Reset(void* buff, int nsize) { if (NULL != m_DataBuffer) { delete [] m_DataBuffer; m_DataBuffer = NULL; } m_DataBuffer = (SZSEL1_Bulletin*)buff; m_nSize = nsize; } private: CDataBuffer(const CDataBuffer<SZSEL1_Bulletin>& other){} CDataBuffer& operator = (const CDataBuffer<SZSEL1_Bulletin> &other){return *this;} SZSEL1_Bulletin* m_DataBuffer; ///< 数据指针 int m_nSize; ///< 实际数据大小 int m_nStore; ///< 缓存容量大小 bool m_bAutoDel; ///< 自动删除内存标志,C接口需要保留内存返回用户,单独接口调用删除内存 }; /// 字段数值存储结构 class IFieldValue { public: ///构造函数 IFieldValue(void* Data = NULL, FIELD_TYPE m_Type = Type_ERROR, FieldID FID = FID_ERROR, unsigned int len = 0); virtual ~IFieldValue(); /// 获取FieldID值 /// @return FieldID值 virtual FieldID GetFieldID() const; ///获取字段的类型 ///@return FieldType --返回字段的类型 virtual FIELD_TYPE GetFieldType() const; /// 获取char类型数值 /// @param cValue -- 返回数值 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetChar(char& cValue) const; /// 获取short类型数值 /// @param SValue -- 返回数值 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetShort(short& sValue) const; /// 获取int类型数值 /// @param nValue -- 返回数值 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetInt(int& nValue) const; /// 获取unsigned int类型数值 /// @param unValue -- 返回数值 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetUInt(unsigned int& unValue) const; /// 获取字符串类型数值 /// @param pValue -- 字符串内容 /// @param nSize -- 字符串大小,如小于实际大小,则返回实际大小并返回失败 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetString(char* pValue, unsigned int& nSize) const; /// 获取longlong字符类型数值 /// @param llValue -- 返回数值 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetLonglong(long long& llValue) const; /// 获取unsigned longlong字符类型数值 /// @param ullValue -- 返回数值 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetULonglong(unsigned long long& ullValue) const; /// 获取double类型数值 /// @param dbValue -- 返回数值 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetDouble(double& dbValue) const; /// 获取float类型数值 /// @param FValue -- 返回数值 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetFloat(float& FValue) const; /// 获取sequence类型数值(50档行情这种) /// @param sqValue -- 返回数值 /// @param len -- 行情档数, 如果小于实际的档数,返回实际档数并返回失败 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetSequence(unsigned int* sqValue, unsigned int &len) const; /// 获取sequence类型数值(50档行情这种) /// @param sqValue -- 返回数值 /// @param len -- 行情档数, 如果小于实际的档数,返回实际档数并返回失败 /// @return true -- 正确返回数据, false -- 数据类型错误 virtual bool GetSequenceDouble(double* sqValue, unsigned int &len) const; private: FieldID m_FildID; ///< 字段ID FIELD_TYPE m_Type; ///< 字段类型 void* m_pData; ///< 字段数据 unsigned int m_Strlen; ///< 字符串长度(如果不是字符串,则值为0) }; /// 行情数据,按字段返回数据结构 class IQuotationData { public: virtual ~IQuotationData(){} /// 获取当前数据的消息类型 /// @return MsgType -- 具体的数据类型 virtual MsgType GetMsgType() = 0; /// 字段个数 /// @return int -- 当前数据结构中的字段个数 virtual int Count() const = 0; /// 根据字段名称获取数值 /// @param FID -- 字段ID标志 /// @return IFieldValue -- 返回字段内容 virtual IFieldValue& GetFieldValue(FieldID FID) = 0; /// 顺序读取根据字段名称获取数值,重载下标操作符 /// @return IFieldValue -- 返回字段内容 virtual const IFieldValue& operator [](int nPos) = 0; /// 按顺序读写方式 virtual IFieldValue* SetFirstPos() = 0; /// 获取当前位置数值 virtual IFieldValue* GetCurPosValue() = 0; /// 移到下一个字段 virtual IFieldValue* SetNextPos() = 0; /// 访问数据迭代器类型定义 typedef IFieldValue* Iterator; /// 数据起始位置 virtual Iterator begin() = 0; /// 数据结束位置,此处无数据 virtual Iterator end() = 0; }; /// 释放IQuotationData数据,防止跨编译器等导致错误 void GTA_API_EXPORT DelIQuotationData(IQuotationData* pQuotationData); struct CQuotationDataPtr { public: CQuotationDataPtr():m_pData(NULL){} ~CQuotationDataPtr() { if (m_pData!=NULL) { DelIQuotationData(m_pData); m_pData = NULL; } } ///初始化结构体 /// @param pData -- 封装有行情数据的数据结构 void Init(IQuotationData* pData) { m_pData = pData; } ///< 重载解引用操作符,返回行情数据 ///< @return IQuotationData -- 行情数据 IQuotationData& operator*() const { return *m_pData; } ///< 重载指向操作符 ///< @return IQuotationData* -- 行情数据的指针 IQuotationData *operator->() const { return m_pData; } private: IQuotationData* m_pData; // 行情数据的数据结构 }; #endif // GTA_QTS_DATA_FIELD_DEFINE_H_
077c5ad080851ad237fdc5c70cd30beda95da2b6
aa2ac425a8bb957a26763ae17e50d50f1cce8956
/src/Addons/GeoWay/gwXML_StandardMetaData/type_gmd.CMD_TopologyLevelCode_PropertyType.h
d8a5fcf74e08ae79525ef01929178a0dcda0f229
[]
no_license
radtek/CGISS
c7289ed19d912c432aae81d0cdbb6b080b4f5458
3f7cfa19d8024a67a5350d51e3f2f40a5e203576
refs/heads/master
2023-03-16T21:23:56.948744
2017-06-17T14:14:09
2017-06-17T14:14:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,235
h
type_gmd.CMD_TopologyLevelCode_PropertyType.h
#ifndef _ALTOVA_INCLUDED_gie_ALTOVA_gmd_ALTOVA_CMD_TopologyLevelCode_PropertyType #define _ALTOVA_INCLUDED_gie_ALTOVA_gmd_ALTOVA_CMD_TopologyLevelCode_PropertyType namespace gie { namespace gmd { class CMD_TopologyLevelCode_PropertyType : public TypeBase { public: gie_EXPORT CMD_TopologyLevelCode_PropertyType(xercesc::DOMNode* const& init); gie_EXPORT CMD_TopologyLevelCode_PropertyType(CMD_TopologyLevelCode_PropertyType const& init); void operator=(CMD_TopologyLevelCode_PropertyType const& other) { m_node = other.m_node; } static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_gmd_altova_CMD_TopologyLevelCode_PropertyType); } MemberAttribute<string_type,_altova_mi_gmd_altova_CMD_TopologyLevelCode_PropertyType_altova_nilReason, 1, 5> nilReason; // nilReason CNilReasonType MemberElement<gco::CCodeListValue_Type, _altova_mi_gmd_altova_CMD_TopologyLevelCode_PropertyType_altova_MD_TopologyLevelCode> MD_TopologyLevelCode; struct MD_TopologyLevelCode { typedef Iterator<gco::CCodeListValue_Type> iterator; }; gie_EXPORT void SetXsiType(); }; } // namespace gmd } // namespace gie #endif // _ALTOVA_INCLUDED_gie_ALTOVA_gmd_ALTOVA_CMD_TopologyLevelCode_PropertyType
67ae21c95b3218616e6a90f961f4851c7f00822f
de1ab6916371c27873097ba2d7f888b4d29b1c53
/hanoi/mainwindow.hh
ef5f07f3102ed75b562b05211cb6743995f6d9b9
[]
no_license
byl484/Tower_of_Hanoi_game
a2ba4d2fbdf0fc0b38196f4faa380d840ebda84e
d39d10cb5117fd51b665e3a90a582cfcaf27db48
refs/heads/master
2021-03-21T16:07:38.997091
2021-01-17T22:36:38
2021-01-17T22:36:38
247,310,307
0
0
null
null
null
null
UTF-8
C++
false
false
3,816
hh
mainwindow.hh
/* Mainwindow * ------------ * * This class' contructor setups the mainwindow and game board * The game functionality is also defined in this class * the gui engine is also defined in this class * This class takes care of storing and deleting game * disks from vectors they are saved in * */ #ifndef MAINWINDOW_HH #define MAINWINDOW_HH #include <disk.hh> #include <game_info.hh> #include <QMainWindow> #include <QGraphicsRectItem> #include <QGraphicsScene> #include <QGraphicsItem> #include <QPushButton> #include <QMessageBox> #include <QKeyEvent> #include <string> #include <vector> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); //creates disk graphic //takes disk-object, and disk coordinates as //param void create_disk(Disk *disk, int x, int y); //moves disk on the game board //specific coordinates that are given as //params. Also the disk to be moved if given as //param. //this is also used //when creating disk. void move_disk(Disk *disk, int x, int y); //Moves disk to specific pole, //takes from pole and to pole as param, also takes to poles //coordinates as param. //This method also calls move_disk method void move_from_to_pole(std::vector<Disk*> *from, std::vector<Disk*> *to, int pole_coord); //This method disables illegal-move buttons and enables legal buttons void set_button_states(); void check_win_cond(); //This method setups the game void setup_game(); //This method deletes previous game and setups new game void reset_game(); //Buttons can also be pressed with number keys //Takes the pressed key as param void keyPressEvent(QKeyEvent *event); private slots: //self explanatory button clicks void on_push_button_a_b_clicked(); void on_push_button_a_c_clicked(); void on_push_button_b_a_clicked(); void on_push_button_b_c_clicked(); void on_push_button_c_a_clicked(); void on_push_button_c_b_clicked(); //calls reset_game-method void on_reset_button_clicked(); //calls reset_game-method with new diks amount from spin box //doesnt do anything if tries to set game with current //amount of disk to avoid user from resetting by accident void on_set_disks_button_clicked(); private: Ui::MainWindow *ui_; QGraphicsScene *scene_; Game_info *current_game; Disk *disk; //Every pole is a vector, which stores disk pointers //Every pole vectors pointer is also stored in vector std::vector<std::vector<Disk*>*> pole_vec_; std::vector<Disk*> pole_left_; std::vector<Disk*> pole_mid_; std::vector<Disk*> pole_right_; //Game-move button's pointers are stored std::vector<QPushButton*> button_vec_; int amount_of_disks_ = 6; int moves_done_ =0; int moves_left_; //Scene dimensions const int BORDER_UP = 0; const int BORDER_DOWN = 280; const int BORDER_LEFT = 0; const int BORDER_RIGHT = 680; //Pole locations on x-axis: const int POLE_LEFT =160; const int POLE_MID = 340; const int POLE_RIGHT = 520; //Pole dimensions: //Increase Widths if you want thicker poles or //thicker outlines and vice versa. //DECREASE TOP, if you want to make poles taller //Dont change BOTTOM, unless you want //the poles to float in the air. const int POLE_WIDTH = 8; const int POLE_OUTLINE_WIDTH = 1; const int POLE_TOP = 50; const int POLE_BOTTOM = 260; }; #endif // MAINWINDOW_HH
f67103be297160477696437f095ef4e26fc25af0
75fbbbc16015d62f7db76d9f20d14d71dc26b70b
/Labs/Lab14/Camera/Camera/Camera.h
4b15c93feafb2f3bc722f4a1c51668699b389181
[ "MIT" ]
permissive
TabacowPSOL/CG
c6a23da559e5cae60ad9f96b75618f41d25c7437
a082efef92149786a35b8bdd491f4effe1730c50
refs/heads/master
2023-08-19T13:05:14.553358
2021-10-24T16:22:18
2021-10-24T16:22:18
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,815
h
Camera.h
/********************************************************************************** // Camera (Arquivo de Cabeçalho) // // Criação: 27 Abr 2016 // Atualização: 26 Set 2021 // Compilador: Visual C++ 2019 // // Descrição: Controla a câmera em uma cena 3D // **********************************************************************************/ #ifndef CAMERA_H #define CAMERA_H #include "DXUT.h" #include <D3DCompiler.h> #include <DirectXMath.h> #include <DirectXColors.h> using namespace DirectX; // ------------------------------------------------------------------------------ struct Vertex { XMFLOAT3 Pos; XMFLOAT4 Color; }; // ------------------------------------------------------------------------------ struct ObjectConstants { XMFLOAT4X4 WorldViewProj = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; }; // ------------------------------------------------------------------------------ class Camera : public App { private: ID3D12RootSignature* rootSignature = nullptr; ID3D12PipelineState* pipelineState = nullptr; Mesh* geometry = nullptr; ID3D12DescriptorHeap* constantBufferHeap = nullptr; ID3D12Resource* constantBufferUpload = nullptr; BYTE* constantBufferData = nullptr; XMFLOAT4X4 World = {}; XMFLOAT4X4 View = {}; XMFLOAT4X4 Proj = {}; float theta = 0; float phi = 0; float radius = 0; float lastMousePosX = 0; float lastMousePosY = 0; public: void Init(); void Update(); void Draw(); void Finalize(); void BuildConstantBuffers(); void BuildGeometry(); void BuildRootSignature(); void BuildPipelineState(); }; // ------------------------------------------------------------------------------ #endif
ccf1969e13f9f17e67a58dcb0f028f9908fec71b
8f2e8a3320f8ab79a106ff7cf9c88eaa59f59257
/使用C++和Qt完成读文件,写MySQL/include/dao/smgdao/sysinfodaolib.h
c98794c073d817d6c40293f5d7156b698f56f80e
[]
no_license
KqSMea8/My_C_Project
1aa9b4793d3ecce6d7ea233b98786b1207a8e1f0
cb7555737b91707a4785d7392b26e600c4ae742d
refs/heads/master
2020-05-31T14:46:34.104077
2019-06-05T06:10:57
2019-06-05T06:10:57
null
0
0
null
null
null
null
GB18030
C++
false
false
518
h
sysinfodaolib.h
// sysinfodaolib.h: implement for the CSysInfoDao class. #ifndef _SYSINFODAOLIB_20130311_ZHANGPENG_H_ #define _SYSINFODAOLIB_20130311_ZHANGPENG_H_ #include "../../commgr/intfobjptrb.h" // for CIntfObjPtrB #include "../../../interface/dao/smgdao/isysinfodao.h"// for ISysInfoDao //DLL输出的接口对象引用 class CSysInfoDao : public CIntfObjPtrB<ISysInfoDao> { public: CSysInfoDao() : CIntfObjPtrB<ISysInfoDao> (SMGDAO_MODULE, SYSINFODAO_CLASSID, SYSINFODAO_INTFID) { } }; #endif
269b5055f48eb7f8996f5edc6e678c25155618ef
f12a6e334acb1c81741528df5928725f0a33bb69
/UbiGame_Blank/Source/Game/GameEntities/TimerEntity.h
deb9bdfb7742166c26ca0d81feb070defc260bf1
[ "MIT" ]
permissive
jlanson/Hungry-Frogge-HTN
e1de806c350cb893ec0d5973a227ea09f9dce160
f234bd1e46bd83f5c2a8af5535d3e795e0b8d985
refs/heads/main
2023-08-28T11:07:40.730247
2021-09-19T12:09:49
2021-09-19T12:09:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
543
h
TimerEntity.h
#pragma once #include "GameEngine/EntitySystem/Entity.h" #include "GameEngine/EntitySystem/Components/TextRenderComponent.h" namespace Game { class TimerEntity : public GameEngine::Entity { public: TimerEntity(); ~TimerEntity(); virtual void OnAddToWorld() override; virtual void OnRemoveFromWorld() override; virtual void Update() override; void setTime(int t); bool timeUp(); protected: GameEngine::TextRenderComponent *m_renderComponent; }; }
04480d96a272b07798cc03b3aadd7f990910b852
5c7024568da3071eb8f555661e53f38933fe20df
/Pixelater/MainWindow.cpp
2ce65f7c13f7371957ab5a6b8c22ea088d3cb2b9
[]
no_license
ohyonghao/CompVisCUDAKernels
86721edab73d8179710ebb1bc60fab3a2a89b52c
f14851284eab7ad8a94e5a171d4a2f238c99cb80
refs/heads/main
2023-02-20T18:55:43.772796
2021-01-27T17:19:55
2021-01-27T18:03:31
310,142,565
0
0
null
null
null
null
UTF-8
C++
false
false
9,110
cpp
MainWindow.cpp
#include "MainWindow.h" #include <QSpacerItem> #include <string> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), image{nullptr} { ui = new QWidget; setCentralWidget(ui); createMenu(); lQueued = new QLabel(); updateProcessLabel(0); createDisplayGroup(); createFilterGroup(); createSettingsGroup(); mainlayout = new QGridLayout; mainlayout->setMenuBar(menuBar); mainlayout->addWidget(gbDisplay,0,0,2,1); mainlayout->addWidget(gbSettings,0,1,1,1); mainlayout->addWidget(gbFilter,0,2,1,1); mainlayout->addWidget(lQueued,3,2,1,1); ui->setLayout(mainlayout); setWindowTitle(tr("Pixelater Qt2000")); } void MainWindow::createMenu(){ menuBar = new QMenuBar; fileMenu = new QMenu(tr("&File"), this); openAction = fileMenu->addAction(tr("&Open")); exitAction = fileMenu->addAction(tr("E&xit")); menuBar->addMenu(fileMenu); connect(openAction, &QAction::triggered, this, &MainWindow::openFile); connect(exitAction, &QAction::triggered, this, &QMainWindow::close); } void MainWindow::createDisplayGroup(){ gbDisplay = new QGroupBox(tr("Image")); QVBoxLayout *layout = new QVBoxLayout; // Image area slImage = new QStackedWidget; slImage->addWidget(new QWidget); layout->addWidget(slImage); gbDisplay->setLayout(layout); gbDisplay->setMinimumWidth(500); } void MainWindow::createFilterGroup(){ gbFilter = new QGroupBox(tr("Apply Filter")); QVBoxLayout *layout = new QVBoxLayout; // Add buttons pbPixFilter = new QPushButton(tr("Pixelate")); pbBlurFilter = new QPushButton(tr("Blur")); pbCUDABlur = new QPushButton(tr("CUDA Blur")); pbGrayFilter = new QPushButton(tr("Grayscale")); pbBinFilter = new QPushButton(tr("Binary Gray")); pbCelShade = new QPushButton(tr("Cel Shade")); pbScaleDown = new QPushButton(tr("Scale Down")); pbScaleUp = new QPushButton(tr("Scale Up")); pbRotate90 = new QPushButton(tr("Rotate 90")); pbRotate180 = new QPushButton(tr("Rotate 180")); pbRotate270 = new QPushButton(tr("Rotate 270")); pbReload = new QPushButton(tr("Reload")); layout->addWidget(pbPixFilter); layout->addWidget(pbBlurFilter); layout->addWidget(pbCUDABlur); layout->addWidget(pbGrayFilter); layout->addWidget(pbBinFilter); layout->addWidget(pbCelShade); layout->addWidget(pbScaleDown); layout->addWidget(pbScaleUp); layout->addWidget(pbRotate90); layout->addWidget(pbRotate180); layout->addWidget(pbRotate270); layout->addWidget(pbReload); layout->addStretch(); layout->setSizeConstraint(QLayout::SetFixedSize); gbFilter->setLayout(layout); // Connect slots } void MainWindow::createSettingsGroup(){ gbSettings = new QGroupBox(tr("Contour Settings")); QVBoxLayout *layout = new QVBoxLayout; QPushButton *incIsoArrow; QPushButton *decIsoArrow; QPushButton *incStepArrow; QPushButton *decStepArrow; // Add sliders QGroupBox *gbSliders = new QGroupBox(tr("Settings")); QGridLayout *glSliders = new QGridLayout; lIsovalue = new QLabel(tr("Isovalue")); sIsovalue = new QSlider(Qt::Horizontal); sIsovalue->setRange(0,255); sIsovalue->setValue(ISOVALUE); glSliders->addWidget(lIsovalue,0,0); decIsoArrow = new QPushButton(tr("<<")); glSliders->addWidget(decIsoArrow,0,1); //glSliders->addWidget(lIsovalueDisplayValue,0,1); glSliders->addWidget(sIsovalue,0,2); incIsoArrow = new QPushButton(tr(">>")); glSliders->addWidget(incIsoArrow,0,3); lStepSize = new QLabel; sStepsize = new QSlider(Qt::Horizontal); //lStepSizeDisplayValue = new QLabel(QString(STEPSIZE)); sStepsize->setRange(1,40); sStepsize->setValue(STEPSIZE); glSliders->addWidget(lStepSize,1,0); decStepArrow = new QPushButton(tr("<<")); glSliders->addWidget(decStepArrow, 1,1); //glSliders->addWidget(lStepSizeDisplayValue,1,1); glSliders->addWidget(sStepsize,1,2); incStepArrow = new QPushButton(tr(">>")); glSliders->addWidget(incStepArrow,1,3); gbSliders->setLayout(glSliders); connect(sIsovalue, &QSlider::valueChanged, this, &MainWindow::updateIsoValue); connect(sStepsize, &QSlider::valueChanged, this, &MainWindow::updateStepValue); connect(incIsoArrow, &QPushButton::pressed, this, &MainWindow::increaseIsoPressed); connect(decIsoArrow, &QPushButton::pressed, this, &MainWindow::decreaseIsoPressed); connect(incStepArrow, &QPushButton::pressed, this, &MainWindow::increaseStepPressed); connect(decStepArrow, &QPushButton::pressed, this, &MainWindow::decreaseStepPressed); updateIsoValue(ISOVALUE); updateStepValue(STEPSIZE); // Add radio buttons QGroupBox *gbContour = new QGroupBox(tr("Contour Back")); QVBoxLayout *rbLayout = new QVBoxLayout; rbBinary = new QRadioButton(tr("Binary")); rbGrayscale = new QRadioButton(tr("Grayscale")); rbBinary->setChecked(true); rbLayout->addWidget(rbBinary); rbLayout->addWidget(rbGrayscale); gbContour->setLayout(rbLayout); pbShowBinary = new QPushButton(tr("Show Binary")); pbShowOriginal = new QPushButton(tr("Show Original")); swShowImage = new QStackedWidget; swShowImage->addWidget(pbShowBinary); swShowImage->addWidget(pbShowOriginal); swShowImage->setCurrentIndex(0); connect(pbShowBinary, &QPushButton::pressed, this, &MainWindow::toggleBinary); connect(pbShowOriginal, &QPushButton::pressed, this, &MainWindow::toggleBinary); // Add to layout layout->addWidget(gbSliders); layout->addWidget(gbContour); layout->addWidget(swShowImage); layout->addStretch(); layout->setSizeConstraint(QLayout::SetFixedSize); gbSettings->setLayout(layout); } void MainWindow::setLayoutHeight(){ if(image){ gbDisplay->setMinimumSize(image->size()); } } void MainWindow::openFile(){ QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.jpg, *.bmp)") ); if(fileName.isEmpty()) return; if(image){ slImage->setCurrentIndex(0); slImage->removeWidget(image); delete image; } image = new ImageDisplay(fileName, sIsovalue->value(), sStepsize->value(), rbBinary->isChecked()); slImage->setCurrentIndex((slImage->addWidget(image))); createImageConnections(); setLayoutHeight(); } void MainWindow::updateIsoValue(int value){ lIsovalue->setText(tr("Isovalue( %1 )").arg(value)); } void MainWindow::updateStepValue(int value){ lStepSize->setText(tr("Stepsize( %1 )").arg(value)); } void MainWindow::createImageConnections(){ connect(sIsovalue, &QSlider::sliderReleased, this, &MainWindow::setIsoValue); connect(sStepsize, &QSlider::sliderReleased, this, &MainWindow::setStepSize); connect(pbBinFilter, &QPushButton::pressed, image, &ImageDisplay::BinaryGray ); connect(pbPixFilter, &QPushButton::pressed, image, &ImageDisplay::Pixelate ); connect(pbBlurFilter, &QPushButton::pressed, image, &ImageDisplay::Blur ); connect(pbCUDABlur, &QPushButton::pressed, image, &ImageDisplay::CUDABlur ); connect(pbCelShade, &QPushButton::pressed, image, &ImageDisplay::CelShade ); connect(pbGrayFilter, &QPushButton::pressed, image, &ImageDisplay::GrayScale); connect(pbShowBinary, &QPushButton::pressed, image, &ImageDisplay::toggleBinary); connect(pbShowOriginal, &QPushButton::pressed, image, &ImageDisplay::toggleBinary); connect(pbScaleDown, &QPushButton::pressed, image, &ImageDisplay::ScaleDown); connect(pbScaleUp, &QPushButton::pressed, image, &ImageDisplay::ScaleUp); connect(pbRotate90, &QPushButton::pressed, image, &ImageDisplay::Rot90); connect(pbRotate180, &QPushButton::pressed, image, &ImageDisplay::Rot180); connect(pbRotate270, &QPushButton::pressed, image, &ImageDisplay::Rot270); connect(pbReload, &QPushButton::pressed, image, &ImageDisplay::LoadImage); connect(rbBinary, &QRadioButton::toggled, image, &ImageDisplay::setBinaryInter); connect(image, &ImageDisplay::imageLoaded, this, &MainWindow::setLayoutHeight); connect(image, &ImageDisplay::processQueued, this, &MainWindow::updateProcessLabel); } void MainWindow::increaseIsoPressed(){ sIsovalue->setValue(sIsovalue->value()+1); setIsoValue(); } void MainWindow::decreaseIsoPressed(){ sIsovalue->setValue(sIsovalue->value()-1); setIsoValue(); } void MainWindow::increaseStepPressed(){ sStepsize->setValue(sStepsize->value()+1); setStepSize(); } void MainWindow::decreaseStepPressed(){ sStepsize->setValue(sStepsize->value()-1); setStepSize(); } void MainWindow::toggleBinary(){ swShowImage->setCurrentIndex(!swShowImage->currentIndex()); } void MainWindow::updateProcessLabel(int _size){ lQueued->setText(tr("Processes Queued: %1").arg(_size)); }
cba6188aff81e5c68df67b270dd90779733f8db8
0105cddfff93a37d26eda502754cefa0d04bab64
/EDPonteiros/src/include/EstruturaDeDados.h
a77a509ce3f7bce785e69264c661732b0646cfb3
[]
no_license
deciomoritz/EstruturaDeDados
088664e0cc7ee79a664e74ef21c8a62de9ba4391
fc7a84c0dbe956c925c7a6392e041179a40f14e7
refs/heads/master
2021-01-19T09:44:04.882781
2013-10-12T00:08:24
2013-10-12T00:08:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
729
h
EstruturaDeDados.h
template<typename Tipo> class EstruturaDeDados { public: /** @brief Adiciona elemento na estrutura de dados * * @param t é o elemento que será adicionado à estrutura * * @return void * * @remarks Essa função não pode ser chamada com a estrutura cheia */ virtual void adicionar(Tipo t) = 0; /** @brief Remove elemento da estrutura de dados e o retorna * * @return Tipo * * @remarks Essa função não pode ser chamada com a estrutura vazia */ virtual Tipo remover() = 0; /** @brief Retorna número de elementos da estrutura * * @return int * */ virtual int tamanho() = 0; /** @brief Retorna true se estrutura estiver vazia * * @return bool * */ virtual bool vazia() = 0; };
a9045cce16bc79e44a87983ee8fff15c8e324c31
5e78487a917dbaaeeb8051e1287c0146fdc3de86
/Hw5Camera.cpp
0bd951983a91e574a802dc91a3d584adebfcd9ec
[]
no_license
ElrickChen/3D-Game-Programming
ca5b319da83dad71aa8957d83bf085f95330d60e
f7f99d65c98a4513ec87590e2422ad67d3c9677c
refs/heads/master
2020-12-03T01:46:18.377727
2017-06-30T07:44:27
2017-06-30T07:44:27
95,862,869
0
0
null
null
null
null
BIG5
C++
false
false
7,017
cpp
Hw5Camera.cpp
#include <math.h> #ifdef _WIN64 #include <GL/freeglut.h> #else #include <GL/glut.h> #endif #include "Hw5Camera.h" #define PI 3.14159265358979323846f /*----------Culling----------*/ float plane[6 * 4]; // 上下左右近遠 Ax + By + Cz + D = 0 void mouseMove(int x, int y) { windowMove[0] += (x - XY[0]) / 3.f; float temp = (y - XY[1]) / 3.f; if (!(windowMove[1] > 87 && temp > 0) && !(windowMove[1] < -87 && temp < 0)) windowMove[1] += temp; eyePosition[0] = eyeRadius * sinf(windowMove[0] / 180 * PI); eyePosition[1] = eyeRadius * sinf(windowMove[1] / 180 * PI); eyePosition[2] = eyeRadius * cosf(windowMove[0] / 180 * PI); XY[0] = x; XY[1] = y; } void mouseWheel(int wheel, int direction, int x, int y) { if (direction == 1) // 向前 eyeRadius--; else if (direction == -1) // 向後 eyeRadius++; eyePosition[0] = eyeRadius * sinf(windowMove[0] / 180 * PI); eyePosition[1] = eyeRadius * sinf(windowMove[1] / 180 * PI); eyePosition[2] = eyeRadius * cosf(windowMove[0] / 180 * PI); } //void crossProduct(float vector1[3], float vector2[3], float product[3]) { // float i = vector1[1] * vector2[2] - vector1[2] * vector2[1]; // float j = vector1[2] * vector2[0] - vector1[0] * vector2[2]; // float k = vector1[0] * vector2[1] - vector1[1] * vector2[0]; // product[0] = i; // product[1] = j; // product[2] = k; // //printf("(%f, %f, %f)*(%f, %f, %f)\n", vector1[0], vector1[1], vector1[2], vector2[0], vector2[1], vector2[2]); // //printf("%fi + %fj + %fk\n", product[0], product[1], product[2]); //} //void setPlaneEquation(float point1[3], float point2[3], float point3[3], float *planeEquation) { // float vector1[3]; // for (int i = 0; i < 3; i++) // vector1[i] = point1[i] - point2[i]; // float vector2[3]; // for (int i = 0; i < 3; i++) // vector2[i] = point3[i] - point2[i]; // // float normal[3]; // crossProduct(vector1, vector2, normal); // // 正規化 // float length = 0; // for (int i = 0; i < 3; i++) // length += normal[i] * normal[i]; // length = sqrtf(length); // for (int i = 0; i < 3; i++) // normal[i] = normal[i] / length; // // d = -ax-by-cz // float distance = 0; // for (int i = 0; i < 3; i++) // distance -= normal[i] * point1[i]; // // planeEquation[0] = normal[0]; // planeEquation[1] = normal[1]; // planeEquation[2] = normal[2]; // planeEquation[3] = distance; //} //void computeViewVolumePlane(float fovy, float aspect, float zNear, float zFar) { // // compute the Z axis of camera // float cameraZ[3]; // float length = 0; // for (int i = 0; i < 3; i++) // length += eyePosition[i] * eyePosition[i]; // length = sqrtf(length); // for (int i = 0; i < 3; i++) // cameraZ[i] = eyePosition[i] / length; // //printf_s("cZ: (%f, %f, %f)\n", cameraZ[0], cameraZ[1], cameraZ[2]); // // X axis of camera with given "up" vector and Z axis // float up[] = { 0, 1, 0 }; // float cameraX[3]; // //printf_s("cX: (%f, %f, %f)\n", cameraX[0], cameraX[1], cameraX[2]); // crossProduct(up, cameraZ, cameraX); // // the real "up" vector is the cross product of Z and X // float cameraY[3]; // crossProduct(cameraZ, cameraX, cameraY); // // float tanTheta = (float)tan(fovy / 2 * PI / 180); // float nearHeight = zNear*tanTheta; // float nearWidth = nearHeight*aspect; // float farHeight = zFar*tanTheta; // float farWidth = farHeight*aspect; // // // compute the centers of the near and far planes // float nearCenter[3]; // for (int i = 0; i < 3; i++) // nearCenter[i] = eyePosition[i] + cameraZ[i] * zNear; // float farCenter[3]; // for (int i = 0; i < 3; i++) // farCenter[i] = eyePosition[i] + cameraZ[i] * zFar; // // // compute the 4 corners of the frustum on the near plane // float nearTopLeft[3]; // for (int i = 0; i < 3; i++) // nearTopLeft[i] = nearCenter[i] + cameraY[i] * nearHeight - cameraX[i] * nearWidth; // float nearTopRight[3]; // for (int i = 0; i < 3; i++) // nearTopRight[i] = nearCenter[i] + cameraY[i] * nearHeight + cameraX[i] * nearWidth; // float nearButtomLeft[3]; // for (int i = 0; i < 3; i++) // nearButtomLeft[i] = nearCenter[i] - cameraY[i] * nearHeight - cameraX[i] * nearWidth; // float nearButtomRight[3]; // for (int i = 0; i < 3; i++) // nearButtomRight[i] = nearCenter[i] - cameraY[i] * nearHeight + cameraX[i] * nearWidth; // // // compute the 4 corners of the frustum on the far plane // float farTopLeft[3]; // for (int i = 0; i < 3; i++) // farTopLeft[i] = farCenter[i] + cameraY[i] * farHeight - cameraX[i] * farWidth; // float farTopRight[3]; // for (int i = 0; i < 3; i++) // farTopRight[i] = farCenter[i] + cameraY[i] * farHeight + cameraX[i] * farWidth; // float farButtomLeft[3]; // for (int i = 0; i < 3; i++) // farButtomLeft[i] = farCenter[i] - cameraY[i] * farHeight - cameraX[i] * farWidth; // float farButtomRight[3]; // for (int i = 0; i < 3; i++) // farButtomRight[i] = farCenter[i] - cameraY[i] * farHeight + cameraX[i] * farWidth; // // // compute the six planes // // 都順時針給點 // setPlaneEquation(nearTopRight, nearTopLeft, farTopLeft, plane + 0 * 4); // setPlaneEquation(nearButtomLeft, nearButtomRight, farButtomRight, plane + 1 * 4); // setPlaneEquation(nearTopLeft, nearButtomLeft, farButtomLeft, plane + 2 * 4); // setPlaneEquation(nearButtomRight, nearTopRight, farButtomRight, plane + 3 * 4); // setPlaneEquation(nearTopLeft, nearTopRight, nearButtomRight, plane + 4 * 4); // setPlaneEquation(farTopRight, farTopLeft, farButtomLeft, plane + 5 * 4); //} //int isInFrustum(MyShape shape) { // float distance = 0; // int result = 1; // inside // // if (shape.type == 0) { // 球體 // float radius = sqrtf(shape.WidthHeightLong[0] * shape.WidthHeightLong[0] * 3); // for (int i = 0; i < 6; i++) { // // distance = pl[i].distance(p); // for (int j = 0; j < 3; j++) // distance += plane[i * 4 + j] * shape.position[j]; // distance += plane[i * 4 + 3]; // if (distance < -radius) // return -1; // outside // else if (distance < radius) // result = 0; // intersect // } // } // else { // // 每個頂點都要判斷 // float vertex[8][3]; // for (int i = 0; i < 8; i++) { // int x = i / 4; // int y = i / 2; // int z = i / 1; // x = (x % 2 == 0) ? 1 : -1; // y = (y % 2 == 0) ? 1 : -1; // z = (z % 2 == 0) ? 1 : -1; // // vertex[i][0] = shape.position[0] + x*shape.WidthHeightLong[0] / 2; // vertex[i][1] = shape.position[1] + y*shape.WidthHeightLong[1] / 2; // vertex[i][2] = shape.position[2] + z*shape.WidthHeightLong[2] / 2; // } // // // 判斷是否有頂點在裡面 // int in, out; // for (int i = 0; i < 6; i++) { // in = 0; out = 0; // for (int j = 0; j < 8 && (in == 0 || out == 0); j++) { // // the corner is outside or inside // for (int k = 0; j < 3; j++) // distance += plane[i * 4 + k] * vertex[j][k]; // distance += plane[i * 4 + 3]; // if (distance < 0) // out++; // else // in++; // } // //if all corners are out // if (!in) // return -1; // outside // // if some corners are out and others are in // else if (out) // result = 0; // intersect // } // } // return result; //}
e303551f025f1f32b5d89ca725289ae446a74f8c
1078476a28c14a0c9a528ba5c151ca9e020f9e97
/dynamics.hh
71feeb734b4eef993e8c4efb76d8ce2dbde31f56
[]
no_license
cjatkinson422/GNClib
a84d08a84e199c509645703b51ad33610b3c3e43
3a3c55104f7b34b7e1db642280eb740424a26e39
refs/heads/master
2022-12-14T07:58:10.271679
2020-09-18T05:31:29
2020-09-18T05:31:29
191,268,171
0
0
null
null
null
null
UTF-8
C++
false
false
80
hh
dynamics.hh
#pragma once #include "linalg.hh" namespace GNC{ mat4 cross_matrix(vec3); }
059a5d369865ef2c572a3733572f869d09b9b292
282ca0ddcea81678dcdc08029b636b0ee4fd36cd
/API-Samples/15-draw_cube/15-draw_cube.cpp
65950dba54ff0d31813a2fadd8970f598bb661b3
[ "BSD-3-Clause", "LicenseRef-scancode-kevlin-henney", "Apache-2.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
ViveStudiosCN/vulkan-openvr-sample
50145fec90419f771c01ef62386638b97581857c
5ad8a610ceb1c4592994fd2ebebd5e99c885dccc
refs/heads/master
2021-01-23T06:15:29.611118
2017-06-01T08:19:18
2017-06-01T08:19:18
93,013,772
1
0
null
null
null
null
UTF-8
C++
false
false
11,141
cpp
15-draw_cube.cpp
/* * Vulkan Samples * * Copyright (C) 2015-2016 Valve Corporation * Copyright (C) 2015-2016 LunarG, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* VULKAN_SAMPLE_SHORT_DESCRIPTION Draw Cube */ /* This is part of the draw cube progression */ #include <util_init.hpp> #include <assert.h> #include <string.h> #include <cstdlib> #include "cube_data.h" #include "CMainApplication.h" /* For this sample, we'll start with GLSL so the shader function is plain */ /* and then use the glslang GLSLtoSPV utility to convert it to SPIR-V for */ /* the driver. We do this for clarity rather than using pre-compiled */ /* SPIR-V */ static const char *vertShaderText = "#version 400\n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout (std140, binding = 0) uniform bufferVals {\n" " mat4 mvp;\n" "} myBufferVals;\n" "layout (location = 0) in vec4 pos;\n" "layout (location = 1) in vec4 inColor;\n" "layout (location = 0) out vec4 outColor;\n" "out gl_PerVertex { \n" " vec4 gl_Position;\n" "};\n" "void main() {\n" " outColor = inColor;\n" " gl_Position = myBufferVals.mvp * pos;\n" "}\n"; static const char *fragShaderText = "#version 400\n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout (location = 0) in vec4 color;\n" "layout (location = 0) out vec4 outColor;\n" "void main() {\n" " outColor = color;\n" "}\n"; glm::mat4 Matrix4Toglmmat4(Matrix4 mat); VkImage RenderScene(vr::Hmd_Eye nEye, CMainApplication* pMainApplication, sample_info info); int sample_main(int argc, char *argv[]) { CMainApplication *pMainApplication = new CMainApplication(argc, argv); pMainApplication->BInit(); #pragma region Vulkan Renderer VkResult U_ASSERT_ONLY res; struct sample_info info = {}; char sample_title[] = "Draw Cube"; const bool depthPresent = true; process_command_line_args(info, argc, argv); init_global_layer_properties(info); init_instance_extension_names(info); init_device_extension_names(info); init_instance(info, sample_title); init_enumerate_device(info); init_window_size(info, 500, 500); init_connection(info); init_window(info); init_swapchain_extension(info); init_device(info); init_command_pool(info); init_command_buffer(info); //execute_begin_command_buffer(info); init_device_queue(info); init_swap_chain(info); init_depth_buffer(info); //init_uniform_buffer(info, vr::Eye_Left); init_descriptor_and_pipeline_layouts(info, false); init_renderpass(info, depthPresent); init_renderpass(info, depthPresent, true, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); init_shaders(info, vertShaderText, fragShaderText); init_framebuffers(info, depthPresent); init_vertex_buffer(info, g_vb_solid_face_colors_Data, sizeof(g_vb_solid_face_colors_Data), sizeof(g_vb_solid_face_colors_Data[0]), false); //init_descriptor_pool(info, false); //init_descriptor_set(info, false); init_pipeline_cache(info); init_pipeline(info, depthPresent); while(1) { VkImage leftEyeImage = RenderScene(vr::Eye_Left, pMainApplication, info); VkImage rightEyeImage = RenderScene(vr::Eye_Right, pMainApplication, info); vr::VRVulkanTextureData_t leftEye = {}; //leftEye.m_nImage = (uint64_t)info.current_buffer; //leftEye.m_nImage = (uint64_t)info.buffers[info.current_buffer].view; leftEye.m_nImage = (uint64_t)leftEyeImage; leftEye.m_pDevice = info.device; leftEye.m_pPhysicalDevice = info.gpus[0]; leftEye.m_pInstance = info.inst; leftEye.m_pQueue = info.graphics_queue; leftEye.m_nQueueFamilyIndex = info.graphics_queue_family_index; leftEye.m_nWidth = info.width; leftEye.m_nHeight = info.height; leftEye.m_nFormat = info.format; leftEye.m_nSampleCount = 1; vr::VRVulkanTextureData_t rightEye = {}; rightEye.m_nImage = (uint64_t)rightEyeImage; rightEye.m_pDevice = info.device; rightEye.m_pPhysicalDevice = info.gpus[0]; rightEye.m_pInstance = info.inst; rightEye.m_pQueue = info.present_queue; rightEye.m_nQueueFamilyIndex = info.present_queue_family_index; rightEye.m_nWidth = info.width; rightEye.m_nHeight = info.height; rightEye.m_nFormat = info.format; rightEye.m_nSampleCount = 1; //uint32_t buffersize1; //buffersize1 = vr::VRCompositor()->GetVulkanInstanceExtensionsRequired(NULL, 0); //char* pValue1 = (char*)malloc(buffersize1); //vr::VRCompositor()->GetVulkanInstanceExtensionsRequired(pValue1, buffersize1); //uint32_t buffersize2; //buffersize2 = vr::VRCompositor()->GetVulkanDeviceExtensionsRequired(info.gpus[0], NULL, 0); //char* pValue2 = (char*)malloc(buffersize2); //vr::VRCompositor()->GetVulkanDeviceExtensionsRequired(info.gpus[0], pValue2, buffersize2); vr::Texture_t leftEyeTexture = { (void*)&leftEye, vr::TextureType_Vulkan, vr::ColorSpace_Gamma }; vr::VRCompositor()->Submit(vr::Eye_Left, &leftEyeTexture); vr::Texture_t rightEyeTexture = { (void*)&rightEye, vr::TextureType_Vulkan, vr::ColorSpace_Gamma }; vr::VRCompositor()->Submit(vr::Eye_Right, &rightEyeTexture); pMainApplication->UpdateHMDMatrixPose(); } //wait_seconds(10); ///* VULKAN_KEY_END */ //vkDestroySemaphore(info.device, imageAcquiredSemaphore, NULL); //vkDestroyFence(info.device, drawFence, NULL); //destroy_pipeline(info); //destroy_pipeline_cache(info); //destroy_descriptor_pool(info); //destroy_vertex_buffer(info); //destroy_framebuffers(info); //destroy_shaders(info); //destroy_renderpass(info); //destroy_descriptor_and_pipeline_layouts(info); //destroy_uniform_buffer(info); //destroy_depth_buffer(info); //destroy_swap_chain(info); //destroy_command_buffer(info); //destroy_command_pool(info); //destroy_device(info); //destroy_window(info); //destroy_instance(info); vr::VR_Shutdown(); return 0; } glm::mat4 Matrix4Toglmmat4(Matrix4 mat) { glm::mat4 glmMat; glmMat = glm::mat4(mat[0],mat[1],mat[2],mat[3], mat[4], mat[5], mat[6], mat[7], mat[8], mat[9], mat[10], mat[11], mat[12], mat[13], mat[14], mat[15] ); return glmMat; } VkImage RenderScene(vr::Hmd_Eye nEye, CMainApplication* pMainApplication, sample_info info) { Matrix4 mvp = pMainApplication->GetCurrentViewProjectionMatrix(nEye); init_uniform_buffer(info, Matrix4Toglmmat4(mvp)); //init_renderpass(info, depthPresent); //init_renderpass(info, depthPresent, true, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); //init_shaders(info, vertShaderText, fragShaderText); //init_framebuffers(info, depthPresent); //init_vertex_buffer(info, g_vb_solid_face_colors_Data, //sizeof(g_vb_solid_face_colors_Data), //sizeof(g_vb_solid_face_colors_Data[0]), false); init_descriptor_pool(info, false); init_descriptor_set(info, false); //init_pipeline_cache(info); //init_pipeline(info, depthPresent); execute_begin_command_buffer(info);//move from up posion to while{} /* VULKAN_KEY_START */ VkClearValue clear_values[2]; clear_values[0].color.float32[0] = 0.2f; clear_values[0].color.float32[1] = 0.2f; clear_values[0].color.float32[2] = 0.2f; clear_values[0].color.float32[3] = 0.2f; clear_values[1].depthStencil.depth = 1.0f; clear_values[1].depthStencil.stencil = 0; VkSemaphore imageAcquiredSemaphore; VkSemaphoreCreateInfo imageAcquiredSemaphoreCreateInfo; imageAcquiredSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; imageAcquiredSemaphoreCreateInfo.pNext = NULL; imageAcquiredSemaphoreCreateInfo.flags = 0; vkCreateSemaphore(info.device, &imageAcquiredSemaphoreCreateInfo, NULL, &imageAcquiredSemaphore); // Get the index of the next available swapchain image: vkAcquireNextImageKHR(info.device, info.swap_chain, UINT64_MAX, imageAcquiredSemaphore, VK_NULL_HANDLE, &info.current_buffer); // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR // return codes VkRenderPassBeginInfo rp_begin; rp_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; rp_begin.pNext = NULL; rp_begin.renderPass = info.render_pass; rp_begin.framebuffer = info.framebuffers[info.current_buffer]; rp_begin.renderArea.offset.x = 0; rp_begin.renderArea.offset.y = 0; rp_begin.renderArea.extent.width = info.width; rp_begin.renderArea.extent.height = info.height; rp_begin.clearValueCount = 2; rp_begin.pClearValues = clear_values; vkCmdBeginRenderPass(info.cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline); vkCmdBindDescriptorSets(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline_layout, 0, NUM_DESCRIPTOR_SETS, info.desc_set.data(), 0, NULL); const VkDeviceSize offsets[1] = { 0 }; vkCmdBindVertexBuffers(info.cmd, 0, 1, &info.vertex_buffer.buf, offsets); init_viewports(info); init_scissors(info); vkCmdDraw(info.cmd, 12 * 3, 1, 0, 0); vkCmdEndRenderPass(info.cmd); vkEndCommandBuffer(info.cmd); const VkCommandBuffer cmd_bufs[] = { info.cmd }; VkFenceCreateInfo fenceInfo; VkFence drawFence; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.pNext = NULL; fenceInfo.flags = 0; vkCreateFence(info.device, &fenceInfo, NULL, &drawFence); VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; VkSubmitInfo submit_info[1] = {}; submit_info[0].pNext = NULL; submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info[0].waitSemaphoreCount = 1; submit_info[0].pWaitSemaphores = &imageAcquiredSemaphore; submit_info[0].pWaitDstStageMask = &pipe_stage_flags; submit_info[0].commandBufferCount = 1; submit_info[0].pCommandBuffers = cmd_bufs; submit_info[0].signalSemaphoreCount = 0; submit_info[0].pSignalSemaphores = NULL; /* Queue the command buffer for execution */ vkQueueSubmit(info.graphics_queue, 1, submit_info, drawFence); /* Now present the image in the window */ VkPresentInfoKHR present; present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; present.pNext = NULL; present.swapchainCount = 1; present.pSwapchains = &info.swap_chain; present.pImageIndices = &info.current_buffer; present.pWaitSemaphores = NULL; present.waitSemaphoreCount = 0; present.pResults = NULL; /* Make sure command buffer is finished before presenting */ vkWaitForFences(info.device, 1, &drawFence, VK_TRUE, FENCE_TIMEOUT); //assert(res == VK_SUCCESS); vkQueuePresentKHR(info.present_queue, &present); //assert(res == VK_SUCCESS); return info.buffers[info.current_buffer].image; //if (info.save_images) //write_ppm(info, "drawcube"); }
9f366d33f9dcf872a21164cfe8ea8f8d25b6ce64
421a36394694042a4a99d75b1f9e5c0372177444
/include/xynet/socket/detail/async_operation.h
b2879091048f07ba25e72a5fbefff4cd1f68aaac
[ "MIT" ]
permissive
Le0ric/xynet
f1b1bfac096dcb26fcffa99eec0d4f3799b1f967
e3e7e457398aca230dba4c930b42a5d3054ffa0d
refs/heads/master
2022-07-01T11:18:11.529985
2020-05-06T03:41:02
2020-05-06T03:41:02
261,649,991
1
0
MIT
2020-05-06T04:16:54
2020-05-06T04:16:53
null
UTF-8
C++
false
false
2,185
h
async_operation.h
// // Created by xuanyi on 4/28/20. // #ifndef XYNET_SOCKET_ASYNC_OPERATION_H #define XYNET_SOCKET_ASYNC_OPERATION_H #include <chrono> #include "xynet/detail/timeout_storage.h" #include "xynet/async_operation_base.h" #include "xynet/io_service.h" namespace xynet { template< detail::FileDescriptorPolicy P, typename T, bool enable_timeout> class async_operation : public async_operation_base { public: async_operation() noexcept :async_operation_base{xynet::io_service::get_thread_io_service()} {} explicit async_operation(async_operation_base::callback_t callback) noexcept :async_operation_base{xynet::io_service::get_thread_io_service(), callback} {} template<typename Duration, bool enable_timeout2 = enable_timeout> requires (enable_timeout2 == true) explicit async_operation(Duration&& duration) noexcept :async_operation_base{xynet::io_service::get_thread_io_service()} ,m_timeout{std::forward<Duration&&>(duration)} {} template<typename Duration, bool enable_timeout2 = enable_timeout> requires (enable_timeout2 == true) async_operation(async_operation_base::callback_t callback, Duration&& duration) :async_operation_base{xynet::io_service::get_thread_io_service(), callback} ,m_timeout{std::forward<Duration&&>(duration)} {} bool await_ready() noexcept { return (get_service() == nullptr) && !(static_cast<T*>(this)->initial_check()); }; void await_suspend(std::coroutine_handle<> awaiting_coroutine) noexcept { set_awaiting_coroutine(awaiting_coroutine); submit(); } void submit() noexcept { if constexpr (!enable_timeout) { async_operation_base::get_service()->try_submit_io(static_cast<T *>(this)->try_start()); } else { static_assert(enable_timeout); async_operation_base::get_service()->try_submit_io(static_cast<T *>(this)->try_start(), m_timeout.get_timespec_ptr()); } } decltype(auto) await_resume() noexcept (detail::FileDescriptorPolicyUseErrorCode<P>) { return static_cast<T *>(this)->get_result(); } private: [[no_unique_address]] detail::timeout_storage<enable_timeout> m_timeout; }; } #endif //XYNET_ASYNC_OPERATION_H
7117964193472da3fbf9f267567ad0951dae32df
e51246b0e81039c1aa35e24ff2420db00ac64ad5
/include/asioext/error.hpp
502d83ddfb38556f46617807b9d3a8d2923eb235
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
zweistein-frm2/asio-extensions
0bfa987face655bbb5ff0f6dc444d2f213cf0559
bafea77c48d674930405cb7f93bdfe65539abc39
refs/heads/master
2022-06-20T18:15:51.593969
2020-05-05T09:01:47
2020-05-05T09:01:47
261,406,864
0
0
BSL-1.0
2020-05-05T08:58:59
2020-05-05T08:58:58
null
UTF-8
C++
false
false
1,850
hpp
error.hpp
/// @file /// Defines general error codes. /// /// @copyright Copyright (c) 2018 Tim Niederhausen (tim@rnc-ag.de) /// Distributed under the Boost Software License, Version 1.0. /// (See accompanying file LICENSE_1_0.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt) #ifndef ASIOEXT_ERROR_HPP #define ASIOEXT_ERROR_HPP #include "asioext/detail/config.hpp" #if ASIOEXT_HAS_PRAGMA_ONCE # pragma once #endif #include "asioext/error_code.hpp" ASIOEXT_NS_BEGIN /// @ingroup core /// @defgroup core_error Error handling /// @{ /// @brief URL handling errors enum class url_error { /// @brief No error. none = 0, /// Invalid character in URL string. invalid_character, /// URL is missing the host part. missing_host, /// Port value is too high. port_overflow, }; #if defined(ASIOEXT_ERRORCATEGORY_IN_HEADER) class url_error_category_impl : public error_category { public: #if defined(ASIOEXT_ERRORCATEGORY_CONSTEXPR_CTOR) constexpr url_error_category_impl() = default; #endif ASIOEXT_DECL const char* name() const ASIOEXT_NOEXCEPT; ASIOEXT_DECL std::string message(int value) const; }; #endif /// @brief Get the @c error_category for @c error ASIOEXT_DECLARE_ERRORCATEGORY(url_error_category_impl, url_error_category) inline error_code make_error_code(url_error e) ASIOEXT_NOEXCEPT { return error_code(static_cast<int>(e), url_error_category()); } /// @} ASIOEXT_NS_END #if defined(ASIOEXT_USE_BOOST_ASIO) namespace boost { namespace system { template <> struct is_error_code_enum<asioext::url_error> { static const bool value = true; }; } } #else namespace std { template <> struct is_error_code_enum<asioext::url_error> { static const bool value = true; }; } #endif #if defined(ASIOEXT_HEADER_ONLY) || defined(ASIOEXT_HAS_CONSTEXPR_ERRORCATEGORY) # include "asioext/impl/error.cpp" #endif #endif
7ee676429646aa8751ed700ba3adb49bd8a20ce5
1826cd13e527cbd312d000681728467730ff9aa4
/55.cpp
a766e4cfa5834a1f6599105f524d98dfbe18ed07
[]
no_license
gcc-tan/leetcode
3a9b21612e3c58f54ff20d72c254ca97c4039099
e70e60ccbc86a7cb52eaedd9ba4a4fb61bfade65
refs/heads/master
2021-01-23T16:25:56.020498
2018-08-23T09:14:04
2018-08-23T09:14:04
102,742,699
0
0
null
null
null
null
UTF-8
C++
false
false
1,571
cpp
55.cpp
//Jump Game /* Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For example: A = [2,3,1,1,4], return true. A = [3,2,1,0,4], return false. */ /* 题目的意思是给一个整数的数组,然后数组的每个元素大小表示能够向后跳动的最大长度,问初始在第一个元素的位置,问是否能跳到最后一个元素 ------------------------------------------------------------------------------------------------------------------------------------- 45题Jump Game II是问跳到最后一个需要的次数最小,这个题目只是问能否跳到最后一个元素。 主要的思想和之前的45题一样,用一个变量记录上一次跳动的最远距离,这个记录变量保证这次的点都可达,然后利用这个变量记录范围的点,更新下一次跳动的距离 */ class Solution { public: bool canJump(vector<int>& nums) { int last = 0, i, n = nums.size();//last表示当前一轮的最远距离 for(i = 0; i < n - 1 && i <= last; ++i) { if(i <= last)//保证扫描到的当前的i位置都能被覆盖 last = max(last, i + nums[i]); } return last >= n - 1 ? true : false; } }; //discuss里面的代码,想法差不多,比较简洁 bool canJump(int A[], int n) { int i = 0; for (int reach = 0; i < n && i <= reach; ++i) reach = max(i + A[i], reach); return i == n; }
c6fb26ee15a60666e500adbd505393c45e3499b6
e30d8e1c98a40273392efbe9a9eee6daf02df107
/码库/CF553E Kyoya and Train.cpp
8e23479c1e58c7ea6499a5c450544cd04dedc549
[]
no_license
zzctommy/public-source-code
c11099de0e1bac21a9db26ab6d83d8e15ffdf460
bf2cf1ea607f097952ccd059fb8fbbcce7b08466
refs/heads/master
2023-03-21T06:24:19.206752
2021-03-05T01:18:35
2021-03-05T01:18:35
277,446,660
1
0
null
null
null
null
UTF-8
C++
false
false
2,588
cpp
CF553E Kyoya and Train.cpp
#include<bits/stdc++.h> using namespace std; #define fi first #define se second #define mkp(x,y) make_pair(x,y) #define pb(x) push_back(x) #define sz(v) (int)v.size() typedef long long LL; typedef double db; template<class T>bool ckmax(T&x,T y){return x<y?x=y,1:0;} template<class T>bool ckmin(T&x,T y){return x>y?x=y,1:0;} #define rep(i,x,y) for(int i=x,i##end=y;i<=i##end;++i) #define per(i,x,y) for(int i=x,i##end=y;i>=i##end;--i) inline int read(){ int x=0,f=1;char ch=getchar(); while(!isdigit(ch)){if(ch=='-')f=0;ch=getchar();} while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); return f?x:-x; } const int V=55; const int E=105; const int N=20005; const int M=N<<2; const db inf=1e15; int n,m,t,X,a[E],b[E],c[E]; db p[E][N<<1],dis[V][V],f[E][N<<1]; namespace poly{ const db PI=acos(-1.0); int rev[M],lg,lim; db g[E][N<<1]; void init(const int&n){ for(lg=0,lim=1;lim<=n;++lg,lim<<=1); for(int i=0;i<lim;++i)rev[i]=(rev[i>>1]>>1)|((i&1)<<(lg-1)); } struct cp{ db x,y; cp(){x=y=0;} cp(db x_,db y_){x=x_,y=y_;} cp operator + (const cp&t)const{return cp(x+t.x,y+t.y);} cp operator - (const cp&t)const{return cp(x-t.x,y-t.y);} cp operator * (const cp&t)const{return cp(x*t.x-y*t.y,x*t.y+y*t.x);} }; void FFT(cp*a,int op){ for(int i=0;i<lim;++i) if(i>rev[i])swap(a[i],a[rev[i]]); for(int i=1;i<lim;i<<=1){ cp wn=cp(cos(PI/i),sin(PI/i)*(op?1:-1)); for(int j=0;j<lim;j+=i<<1){ cp w0=cp(1,0); for(int k=0;k<i;++k,w0=w0*wn){ const cp X=a[j+k],Y=w0*a[i+j+k]; a[j+k]=X+Y,a[i+j+k]=X-Y; } } } if(op)return; for(int i=0;i<lim;++i)a[i].x/=lim; } void CDQ_FFT(int l,int r){ if(l==t&&r==2*t-1)return; static cp A[M],B[M]; if(l==r){ rep(i,1,n-1)f[i][l]=inf; for(int i=1;i<=m;++i)if(a[i]!=n)ckmin(f[a[i]][l],g[i][l]+c[i]); return; } int mid=(l+r)>>1; CDQ_FFT(mid+1,r); init(r-l+r-mid); for(int i=1;i<=m;++i){ if(a[i]==n)continue; for(int j=0;j<lim;++j)A[j]=B[j]=cp(0,0); for(int j=0;j<=r-l;++j)A[j].x=p[i][j]; for(int j=mid+1;j<=r;++j)B[j-mid-1].x=f[b[i]][r-j+mid+1]; FFT(A,1),FFT(B,1); for(int j=0;j<lim;++j)A[j]=A[j]*B[j]; FFT(A,0); for(int j=l;j<=mid;++j)g[i][j]+=A[r-j].x; } CDQ_FFT(l,mid); } } signed main(){ n=read(),m=read(),t=read(),X=read(); rep(i,1,n)rep(j,1,n)dis[i][j]=i==j?0:inf; for(int i=1;i<=m;++i){ a[i]=read(),b[i]=read(),c[i]=dis[a[i]][b[i]]=read(); rep(j,1,t)p[i][j]=1.*read()/100000; } rep(k,1,n)rep(i,1,n)rep(j,1,n)ckmin(dis[i][j],dis[i][k]+dis[k][j]); rep(i,1,n-1)rep(j,t,t*2-1)f[i][j]=dis[i][n]+X; rep(i,0,t*2-1)f[n][i]=i<=t?0:X; poly::CDQ_FFT(0,t*2-1); printf("%.9lf\n",f[1][0]); return 0; }
04d7bea478005a689f1b669eef37d2fbb2c4ddf3
a42333839fe2aa38c28d0fd39cc4e72743e18967
/Engine/CubeMapGenerator.h
40b38a5fd6e3eb8b074ca80aff098f69a0050795
[]
no_license
ebithril/ModelViewer
d3f4bfe5eea998e96d6f2ce123f8934e92ae80d1
1f4414bd7d86e11b3a846a5107e513030d7053d7
refs/heads/master
2021-01-10T12:29:55.010567
2016-02-19T18:42:23
2016-02-19T18:42:23
52,108,402
0
0
null
null
null
null
UTF-8
C++
false
false
275
h
CubeMapGenerator.h
#pragma once #include "Texture.h" namespace GraphicsEngine { struct SceneRenderData; class CubeMapGenerator { public: CubeMapGenerator(); ~CubeMapGenerator(); static Texture GenerateCubeMap(const Vector3<float>& aPosition); }; } namespace GE = GraphicsEngine;
40c023097d2ca382f8f5fe8d8e61ff3af91beffc
a84b143f40d9e945b3ee81a2e4522706a381ca85
/PGR2project/src/main.cpp
8ea5490655b68adbbcf9486d62d692de6ae23e66
[]
no_license
kucerad/natureal
ed076b87001104d2817ade8f64a34e1571f53fc8
afa143975c54d406334dc1ee7af3f8ee26008334
refs/heads/master
2021-01-01T05:38:08.139120
2011-09-06T07:00:36
2011-09-06T07:00:36
35,802,274
0
0
null
null
null
null
UTF-8
C++
false
false
25,324
cpp
main.cpp
//----------------------------------------------------------------------------- // [PGR2] PGR2-Model Viewer // 14/02/2011 //----------------------------------------------------------------------------- // Controls: // [mouse-left] ... scene rotation // [l] ... (re)load model // [v] ... toggle vertex TNB vectors // [f] ... toggle face normal vectors // [t] ... toggle transparency (draw transparent model parts) // [w] ... toggle wire mode // [c] ... toggle face culling // [a], [A] ... increase/decrease alpha transparency threshold // [z], [Z] ... increase/decrease scene translation along z axis // [s], [S] ... increase/decrease scene scale //----------------------------------------------------------------------------- #define USE_ANTTWEAKBAR #define TEST 0 #include "../common/Vector4.h" #include "settings.h" bool g_ParallaxMappingEnabled = true; float g_ParallaxScale = 0.04; float g_ParallaxBias = -0.02; #define TERRAIN_INIT_BORDER_VAL v4(13.0f, 10.0f, 5.0f, -1.0f) #define TERRAIN_INIT_BORDER_WID v4(2.0f, 2.0f, 2.0f, 2.0f) v4 g_terrain_border_values = TERRAIN_INIT_BORDER_VAL; v4 g_terrain_border_widths = TERRAIN_INIT_BORDER_WID; float tree2min = TREE2_MIN_HEIGHT; float tree2max = TREE2_MAX_HEIGHT; float tree1min = TREE1_MIN_HEIGHT; float tree1max = TREE1_MAX_HEIGHT; float grassmin = GRASS_MIN_HEIGHT; float grassmax = GRASS_MAX_HEIGHT; CameraMode g_cameraMode = FREE; int g_WinWidth = 800; // Window width int g_WinHeight = 600; // Window height double g_time = 0.0; CTimer timer; Statistics g_Statistics; int g_Bumpmaps = 0; int g_Heightmaps = 0; int g_Specularmaps = 0; int g_Alphamaps = 0; #include "pgr2model.h" #include <assert.h> #include "../common/models/cube.h" #include "World.h" #include "globals.h" bool tqAvailable = false; GLuint tqid = 0; bool pqAvailable = false; GLuint pqid = 0; GLint result_available = 0; v3 g_light_position = LIGHT_POSITION; bool g_godraysEnabled = false; bool g_fastMode = false; bool g_drawingReflection = false; bool g_showTextures = false; bool g_ShadowMappingEnabled = false; m4 g_LightMVPCameraVInverseMatrix; m4 g_LightMVCameraVInverseMatrix; m4 g_LightPMatrix; Light* g_shadowLight; int g_GrassCount = GRASS_COUNT; int g_Tree1Count = TREE1_COUNT; int g_Tree2Count = TREE2_COUNT; // GLOBAL CONSTANTS____________________________________________________________ const GLfloat VECTOR_RENDER_SCALE = 0.20f; // GLOBAL VARIABLES____________________________________________________________ // Scene orientation (stored as a quaternion) GLfloat g_SceneRot[] = {0.0f, 0.0f, 0.0f, 1.0f}; GLfloat g_SceneTraZ = 10.0f; // Scene translation along z-axis GLfloat g_SceneScale = 1.0f; GLuint cube_vbo_id = 0; GLuint cube_ebo_id = 0; GLuint plane_vbo_id = 0; GLuint plane_ebo_id = 0; bool g_ShowVertexNormals = false; // Show vertex normal/tangent/binormal bool g_FaceNormals = false; // Show face normal bool g_Transparency = false; // Draw transparent meshes bool g_WireMode = false; // Wire mode enabled/disabled bool g_FaceCulling = true; // Face culling enabled/disabled GLfloat g_AlphaThreshold = 0.01f; // Alpha test threshold bool g_MouseModeANT = true; World world; #include "../common/common.h" // Model file name std::string g_ModelFileName = "models/DesertOasis/H1F.pgr2"; // FORWARD DECLARATIONS________________________________________________________ void initGUI(void); void TW_CALL loadNewModelCB(void* clientData); void TW_CALL copyStdStringToClient(std::string& dst, const std::string& src); //----------------------------------------------------------------------------- // Name: cbDisplay() // Desc: //----------------------------------------------------------------------------- void cbDisplay() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Setup OpenGL states according to user settings glAlphaFunc(GL_GEQUAL, g_AlphaThreshold); glPolygonMode(GL_FRONT_AND_BACK, g_WireMode ? GL_LINE : GL_FILL); //if (g_FaceCulling) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); // Setup camera //glLoadIdentity(); //glTranslatef(0.5f, -1.0f, -g_SceneTraZ); //pgr2AddQuaternionRotationToTransformation(g_SceneRot); //glScalef(g_SceneScale, g_SceneScale, g_SceneScale); g_time=timer.RealTime(); world.update(g_time); /* if (pqAvailable){ glBeginQuery(GL_PRIMITIVES_GENERATED, pqid); } */ // if timer query available if (tqAvailable){ // measure on GPU //if (result_available){ glBeginQuery(GL_TIME_ELAPSED, tqid); //} world.draw(); //if (result_available) glEndQuery(GL_TIME_ELAPSED); GLuint64EXT time = 0; glGetQueryObjectui64vEXT(tqid, GL_QUERY_RESULT, &time); // blocking CPU g_Statistics.fps = 1000000000.0/ double(time); //printf("FPS: %f\n",g_Statistics.fps); //glGetQueryObjectiv(tqid, GL_QUERY_RESULT_AVAILABLE, &result_available); //printf("avail: %s\n",result_available?"yes":"no"); } else { world.draw(); // must block CPU to measure time here glFinish(); double timeDiff = timer.RealTime() - g_time; g_Statistics.fps = 1.0 / (timeDiff); } /* if (pqAvailable){ glEndQuery(GL_PRIMITIVES_GENERATED); GLuint64EXT count = 0; glGetQueryObjectui64vEXT(pqid, GL_QUERY_RESULT, &count); // blocking CPU g_Statistics.primitives = count; } */ } void initApp() { #if TEST // TEST START // do whatever u want... system("PAUSE"); exit(1); // TEST END #endif timer.Reset(); timer.Start(); // set cube vbo initCube(); //set plane vbo initPlane(); world.init(); // timer query extension? if (isExtensionSupported(TIME_QUERY_EXTENSION)){ tqAvailable = true; glGenQueries(1, &tqid); } pqAvailable = true; glGenQueries(1, &pqid); } void deinitApp() { deletePlane(); deleteCube(); timer.Stop(); //world.~World(); if (tqAvailable){ glDeleteQueries(1, &tqid); } if (pqAvailable){ glDeleteQueries(1, &pqid); } printf("deinit done, bye\n"); //system("PAUSE"); } //----------------------------------------------------------------------------- // Name: cbInitGL() // Desc: //----------------------------------------------------------------------------- void cbInitGL() { // Init app GUI initGUI(); // Set OpenGL state variables glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, material_amd); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_amd); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_spe); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 128); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glShadeModel(GL_SMOOTH); glEnable(GL_LINE_SMOOTH); glEnable(GL_LIGHTING); glEnable(GL_CULL_FACE); glPointSize(1.f); glLineWidth(1.0f); // init app initApp(); // Load model //loadNewModelCB(&g_ModelFileName); } void TW_CALL cbSetTree2Count(const void *value, void *clientData) { g_Tree2Count = *(const int*)value; // for instance world.tree2_planter.plantVegetationCount(g_Tree2Count); } void TW_CALL cbGetTree2Count(void *value, void *clientData) { *(int *)value = world.tree2_planter.count; // for instance } void TW_CALL cbSetTree1Count(const void *value, void *clientData) { g_Tree1Count = *(const int*)value; // for instance world.tree1_planter.plantVegetationCount(g_Tree1Count); } void TW_CALL cbGetTree1Count(void *value, void *clientData) { *(int *)value = world.tree1_planter.count; // for instance } void TW_CALL cbSetGrassCount(const void *value, void *clientData) { g_GrassCount = *(const int*)value; // for instance world.grass_planter.plantVegetationCount(g_GrassCount); } void TW_CALL cbGetGrassCount(void *value, void *clientData) { *(int *)value = world.grass_planter.count; // for instance } //tree2 void TW_CALL cbSetTree2Min(const void *value, void *clientData) { tree2min = *(const float*)value; // for instance world.tree2_planter.setNewMin(tree2min); } void TW_CALL cbGetTree2Min(void *value, void *clientData) { *(float *)value = world.tree2_planter.height_min; // for instance } void TW_CALL cbSetTree2Max(const void *value, void *clientData) { tree2max = *(const float*)value; // for instance world.tree2_planter.setNewMax(tree2max); } void TW_CALL cbGetTree2Max(void *value, void *clientData) { *(float *)value = world.tree2_planter.height_max; // for instance } // tree1 void TW_CALL cbSetTree1Min(const void *value, void *clientData) { tree1min = *(const float*)value; // for instance world.tree1_planter.setNewMin(tree1min); } void TW_CALL cbGetTree1Min(void *value, void *clientData) { *(float *)value = world.tree1_planter.height_min; // for instance } void TW_CALL cbSetTree1Max(const void *value, void *clientData) { tree1max = *(const float*)value; // for instance world.tree1_planter.setNewMax(tree1max); } void TW_CALL cbGetTree1Max(void *value, void *clientData) { *(float *)value = world.tree1_planter.height_max; // for instance } // grass void TW_CALL cbSetGrassMin(const void *value, void *clientData) { grassmin = *(const float*)value; // for instance world.grass_planter.setNewMin(grassmin); } void TW_CALL cbGetGrassMin(void *value, void *clientData) { *(float *)value = world.grass_planter.height_min; // for instance } void TW_CALL cbSetGrassMax(const void *value, void *clientData) { grassmax = *(const float*)value; // for instance world.grass_planter.setNewMax(grassmax); } void TW_CALL cbGetGrassMax(void *value, void *clientData) { *(float *)value = world.grass_planter.height_max; // for instance } //----------------------------------------------------------------------------- // Name: initGUI() // Desc: //----------------------------------------------------------------------------- void initGUI() { #ifdef USE_ANTTWEAKBAR // Initialize AntTweakBar GUI if (!TwInit(TW_OPENGL, NULL)) { assert(0); } // Define the required callback function to copy a std::string // (see TwCopyStdStringToClientFunc documentation) TwCopyStdStringToClientFunc(copyStdStringToClient); TwWindowSize(g_WinWidth, g_WinHeight); TwBar *controlBar = TwNewBar("Controls"); TwDefine(" Controls position='10 10' size='250 370' refresh=0.1 \ valueswidth=80 "); TwAddVarRW(controlBar, "parallax", TW_TYPE_BOOLCPP, &g_ParallaxMappingEnabled, " help='Parallax mapping enabled' "); TwAddVarRW(controlBar, "parallaxScale", TW_TYPE_FLOAT, &g_ParallaxScale, " help='Parallax scale value' step=0.001"); TwAddVarRW(controlBar, "parallaxBias", TW_TYPE_FLOAT, &g_ParallaxBias, " help='Parallax bias value' step=0.001"); // camera mode TwEnumVal cam_mode[] = { { CameraMode::FREE , "Free" }, { CameraMode::TERRAIN_RESTRICTED , "Terrain restricted" }, { CameraMode::TERRAIN_CONNECTED , "Terrain connected" }, { CameraMode::WALK , "Walk" } }; TwType transport_type = TwDefineEnum("Camera mode", cam_mode, 4); TwAddVarRW(controlBar, "camera mode", transport_type, &g_cameraMode, " group='Camera' keyIncr=c \ help='Change camera movement mode.' "); TwAddVarRO(controlBar, "fps", TW_TYPE_FLOAT, &(g_Statistics.fps), " label='fps' group=Statistics help='frames per second' "); TwAddVarRO(controlBar, "primitives", TW_TYPE_INT32, &(g_Statistics.primitives), " label='primitives' group=Statistics help='primitives generated' "); // house 1 TwAddVarRO(controlBar, "house1_lod", TW_TYPE_INT32, &(g_Statistics.house1_lod), " label='house1_lod' group=Statistics help='house level of detail' "); TwAddVarRO(controlBar, "house1_samples", TW_TYPE_INT32, &(g_Statistics.house1_samples), " label='house1_samples' group=Statistics help='house samples generated on bbox' "); // house2 TwAddVarRO(controlBar, "house2_lod", TW_TYPE_INT32, &(g_Statistics.house2_lod), " label='house2_lod' group=Statistics help='house level of detail' "); TwAddVarRO(controlBar, "house2_samples", TW_TYPE_INT32, &(g_Statistics.house2_samples), " label='house2_samples' group=Statistics help='house samples generated on bbox' "); // bridge TwAddVarRO(controlBar, "bridge_lod", TW_TYPE_INT32, &(g_Statistics.bridge_lod), " label='bridge_lod' group=Statistics help='bridge level of detail' "); TwAddVarRO(controlBar, "bridge_samples", TW_TYPE_INT32, &(g_Statistics.bridge_samples), " label='bridge_samples' group=Statistics help='bridge samples generated on bbox' "); // tower 1 TwAddVarRO(controlBar, "tower1_lod", TW_TYPE_INT32, &(g_Statistics.tower1_lod), " label='tower1_lod' group=Statistics help='tower1 level of detail' "); TwAddVarRO(controlBar, "tower1_samples", TW_TYPE_INT32, &(g_Statistics.tower1_samples), " label='tower1_samples' group=Statistics help='tower1 samples generated on bbox' "); // tower 2 TwAddVarRO(controlBar, "tower2_lod", TW_TYPE_INT32, &(g_Statistics.tower2_lod), " label='tower2_lod' group=Statistics help='tower2 level of detail' "); TwAddVarRO(controlBar, "tower2_samples", TW_TYPE_INT32, &(g_Statistics.tower2_samples), " label='tower2_samples' group=Statistics help='tower2 samples generated on bbox' "); // eggbox TwAddVarRO(controlBar, "eggbox_lod", TW_TYPE_INT32, &(g_Statistics.eggbox_lod), " label='eggbox_lod' group=Statistics help='eggbox level of detail' "); TwAddVarRO(controlBar, "eggbox_samples", TW_TYPE_INT32, &(g_Statistics.eggbox_samples), " label='eggbox_samples' group=Statistics help='eggbox samples generated on bbox' "); // haywagon TwAddVarRO(controlBar, "haywagon_lod", TW_TYPE_INT32, &(g_Statistics.haywagon_lod), " label='haywagon_lod' group=Statistics help='haywagon level of detail' "); TwAddVarRO(controlBar, "haywagon_samples", TW_TYPE_INT32, &(g_Statistics.haywagon_samples), " label='haywagon_samples' group=Statistics help='haywagon samples generated on bbox' "); // well TwAddVarRO(controlBar, "well_lod", TW_TYPE_INT32, &(g_Statistics.well_lod), " label='well_lod' group=Statistics help='well level of detail' "); TwAddVarRO(controlBar, "well_samples", TW_TYPE_INT32, &(g_Statistics.well_samples), " label='well_samples' group=Statistics help='well samples generated on bbox' "); /*TwAddVarRW(controlBar, "x_translate", TW_TYPE_FLOAT, &(g_light_position.x), " label='x' group=Light help='x translation' "); TwAddVarRW(controlBar, "y_translate", TW_TYPE_FLOAT, &(g_light_position.y), " label='y' group=Light help='y translation' "); TwAddVarRW(controlBar, "z_translate", TW_TYPE_FLOAT, &(g_light_position.z), " label='z' group=Light help='z translation' "); */ TwAddVarRW(controlBar, "godrays", TW_TYPE_BOOLCPP, &(g_godraysEnabled), " label='God rays enabled' group=Light help='enable/disable god rays' "); TwAddVarRW(controlBar, "fbos", TW_TYPE_BOOLCPP, &(g_showTextures), " label='Show FBOs' group=Debug help='enable/disable FBO display' "); TwAddVarCB(controlBar, "Tree 2 count", TW_TYPE_INT16, cbSetTree2Count, cbGetTree2Count, NULL, " group='Vegetation' min=0 max=10000 step=1 "); TwAddVarCB(controlBar, "Tree 1 count", TW_TYPE_INT16, cbSetTree1Count, cbGetTree1Count, NULL, " group='Vegetation' min=0 max=10000 step=1 "); TwAddVarCB(controlBar, "Grass count", TW_TYPE_INT16, cbSetGrassCount, cbGetGrassCount, NULL, " group='Vegetation' min=0 max=10000 step=1 "); TwAddVarRW(controlBar, "Change1", TW_TYPE_FLOAT, &g_terrain_border_values.x, " group='Surfaces' label='Snow height' min=-5 max=30 step=0.5 help='Snow height' "); TwAddVarRW(controlBar, "Change1a", TW_TYPE_FLOAT, &g_terrain_border_widths.x, " group='Surfaces' label='Snow-rock transition' min=0 max=5 step=0.5 help='Transition 1' "); TwAddVarRW(controlBar, "Change2", TW_TYPE_FLOAT, &g_terrain_border_values.y, " group='Surfaces' label='Rock height' min=-5 max=30 step=0.5 help='Rock height' "); TwAddVarRW(controlBar, "Change2a", TW_TYPE_FLOAT, &g_terrain_border_widths.y, " group='Surfaces' label='Rock-grass transition' min=0 max=5 step=0.5 help='Transition 2' "); TwAddVarRW(controlBar, "Change3", TW_TYPE_FLOAT, &g_terrain_border_values.z, " group='Surfaces' label='Grass height' min=-5 max=30 step=0.5 help='Grass height' "); TwAddVarRW(controlBar, "Change3a", TW_TYPE_FLOAT, &g_terrain_border_widths.z, " group='Surfaces' label='Grass-clay transition' min=0 max=5 step=0.5 help='Transition 3' "); TwAddVarRW(controlBar, "Change4", TW_TYPE_FLOAT, &g_terrain_border_values.w, " group='Surfaces' label='Clay height' min=-5 max=30 step=0.5 help='Clay height' "); TwAddVarRW(controlBar, "Change4a", TW_TYPE_FLOAT, &g_terrain_border_widths.w, " group='Surfaces' label='Clay-ground transition' min=0 max=5 step=0.5 help='Transition 4' "); TwAddVarCB(controlBar, "Tree2 MIN", TW_TYPE_FLOAT, cbSetTree2Min, cbGetTree2Min, NULL, " group='Levels' min=-5 max=30 step=1 "); TwAddVarCB(controlBar, "Tree2 MAX", TW_TYPE_FLOAT, cbSetTree2Max, cbGetTree2Max, NULL, " group='Levels' min=-5 max=30 step=1 "); TwAddVarCB(controlBar, "Tree1 MIN", TW_TYPE_FLOAT, cbSetTree1Min, cbGetTree1Min, NULL, " group='Levels' min=-5 max=30 step=1 "); TwAddVarCB(controlBar, "Tree1 MAX", TW_TYPE_FLOAT, cbSetTree1Max, cbGetTree1Max, NULL, " group='Levels' min=-5 max=30 step=1 "); TwAddVarCB(controlBar, "Grass MIN", TW_TYPE_FLOAT, cbSetGrassMin, cbGetGrassMin, NULL, " group='Levels' min=-5 max=30 step=1 "); TwAddVarCB(controlBar, "Grass MAX", TW_TYPE_FLOAT, cbSetGrassMax, cbGetGrassMax, NULL, " group='Levels' min=-5 max=30 step=1 "); //TwAddVarRW(controlBar, "vertex_normals", TW_TYPE_BOOLCPP, // &g_ShowVertexNormals, " label='vertex normals' \ // group=Render help='Show vertex normal, tangent, binormal.' "); // //TwAddVarRW(controlBar, "face_normals", TW_TYPE_BOOLCPP, &g_FaceNormals, // " label='face normals' group=Render help='Show face normals.' "); //TwAddVarRW(controlBar, "transparency", TW_TYPE_BOOLCPP, &g_Transparency, // " label='transparency' group=Render \ // help='Render transparent meshes.'"); //TwAddVarRW(controlBar, "wiremode", TW_TYPE_BOOLCPP, &g_WireMode, // " label='wire mode' group=Render help='Toggle wire mode.' "); //TwAddVarRW(controlBar, "face_culling", TW_TYPE_BOOLCPP, &g_FaceCulling, // " label='face culling' group=Render help='Toggle face culling.' "); //TwAddVarRW(controlBar, "alpha_threshold", TW_TYPE_FLOAT, &g_AlphaThreshold, // " label='alpha threshold' group=Render min=0 max=1 step=0.01 \ // help='Alpha test threshold.' "); //TwAddVarRW(controlBar, "Translate", TW_TYPE_FLOAT, &g_SceneTraZ, // " group='Scene' label='translate Z' min=1 max=1000 step=0.5 \ // help='Scene translation.' "); //TwAddVarRW(controlBar, "Scale", TW_TYPE_FLOAT, &g_SceneScale, // " group='Scene' label='scale' min=0 max=10 step=0.01 \ // help='Scene scale.' "); //TwAddVarRW(controlBar, "SceneRotation", TW_TYPE_QUAT4F, &g_SceneRot, // " group='Scene' label='Scene rotation' open \ // help='Change the scene orientation.' "); #endif } //----------------------------------------------------------------------------- // Name: copyStdStringToClient() // Desc: Function called to copy the content of a std::string (souceString) // handled by the AntTweakBar library to destinationClientString handled // by our application //----------------------------------------------------------------------------- void TW_CALL copyStdStringToClient(std::string& dst, const std::string& src) { dst = src; } //----------------------------------------------------------------------------- // Name: loadNewModelCB() // Desc: Callback function to load new model //----------------------------------------------------------------------------- void TW_CALL loadNewModelCB(void* clientData) { /* const std::string* file_name = &g_ModelFileName;//(const std::string *)(clientData); printf("RELOAD MODEL\n"); if (!file_name->empty()) { PGR2Model* pOldModel = g_pModel; printf("LOAD: %s\n", (*file_name).c_str()); g_pModel = PGR2Model::loadFromFile(file_name->c_str()); if (g_pModel != NULL) { delete pOldModel; } else { g_pModel = pOldModel; } } */ } //----------------------------------------------------------------------------- // Name: cbWindowSizeChanged() // Desc: //----------------------------------------------------------------------------- void cbWindowSizeChanged(int width, int height) { g_WinWidth = width; g_WinHeight = height; world.windowSizeChanged(width,height); } void activateANTMouse() { glfwEnable( GLFW_MOUSE_CURSOR ); } void activateGLFWMouse() { //glfwDisable( GLFW_MOUSE_CURSOR ); glfwSetMousePos(g_WinWidth/2, g_WinHeight/2); } //----------------------------------------------------------------------------- // Name: cbKeyboardChanged() // Desc: //----------------------------------------------------------------------------- void cbKeyboardChanged(int key, int action) { if (!g_MouseModeANT){ // apply to camera first... if (world.p_activeCamera->handleKeyDown(key, action)){ return; } } switch (key) { // DA use 'z' instead of 't' /* case 'z' : g_SceneTraZ += 0.5f; break; case 'Z' : g_SceneTraZ -= (g_SceneTraZ > 0.5) ? 0.5f : 0.0f; break; case 's' : g_SceneScale *= 1.01; break; case 'S' : g_SceneScale *= 0.99; break; case 'v' : g_ShowVertexNormals = !g_ShowVertexNormals; break; case 'f' : g_FaceNormals != g_FaceNormals; break; case 't' : g_Transparency = !g_Transparency; break; case 'w' : g_WireMode = !g_WireMode; break; case 'c' : g_FaceCulling = !g_FaceCulling; break; case 'a' : if(g_AlphaThreshold < 0.99f) g_AlphaThreshold += 0.01f; break; case 'A' : if(g_AlphaThreshold > 0.01f) g_AlphaThreshold -= 0.01f; break; */ case ' ' : g_MouseModeANT = !g_MouseModeANT; if (g_MouseModeANT){ activateANTMouse(); } else { activateGLFWMouse(); } break; } } bool g_MouseRotationEnabled = false; //----------------------------------------------------------------------------- // Name: cbMouseButtonChanged() // Desc: internal //----------------------------------------------------------------------------- void GLFWCALL cbMouseButtonChanged(int button, int action) { g_MouseRotationEnabled = ((button == GLFW_MOUSE_BUTTON_LEFT) && (action == GLFW_PRESS)); } //----------------------------------------------------------------------------- // Name: cbMousePositionChanged() // Desc: //----------------------------------------------------------------------------- void cbMousePositionChanged(int x, int y) { world.p_activeCamera->handleMouseMove(x,y); glfwSetMousePos(g_WinWidth/2, g_WinHeight/2); } //----------------------------------------------------------------------------- // Name: main() // Desc: //----------------------------------------------------------------------------- int main(int argc, char* argv[]) { int output = common_main(g_WinWidth, g_WinHeight, "[PGR2] Semestral project", cbInitGL, // init GL callback function cbDisplay, // display callback function cbWindowSizeChanged, // window resize callback function cbKeyboardChanged, // keyboard callback function #ifdef USE_ANTTWEAKBAR cbMouseButtonChanged, // mouse button callback function cbMousePositionChanged // mouse motion callback function #else cbMouseButtonChanged, // mouse button callback function cbMousePositionChanged // mouse motion callback function #endif ); deinitApp(); return output; }
46bd1f1c751c11c596408b2da33603ea448244c3
d1913394590c65d5f3858d124d49ba39bbf6a3a2
/vc-magic/src/Cheats.h
672653ee7c5ec312d3b0aaad2b343fbeeb01f0a4
[]
no_license
Serabass/vc-magic
e690abddc462b1e18e6a2eba8763926504853be8
227d20e56d1bab60ae1b35e0e8a48aadfbe0b6ee
refs/heads/master
2020-04-15T15:22:16.786270
2017-12-08T05:22:07
2017-12-08T05:22:07
52,162,160
2
0
null
null
null
null
UTF-8
C++
false
false
711
h
Cheats.h
#pragma once #ifndef CHEATS_H #define CHEATS_H OPCODE(0445, "", are_car_cheats_used); class ViceCheats { private: static DWORD __stdcall Watcher(LPVOID lpThreadParameter); public: static char * strNUTTERTOOLS; static char * strPROFESSIONALTOOLS; static char(__cdecl* check)(char lastPressedChar, char * cheatString); static bool* cigarette; static bool* greenLights; static std::vector<UserCheat*> userCheats; // Doesn't work static void RegisterUserCheat(char *string, void(__cdecl* callback)()); // Doesn't work static void WatchCheats(); static bool AreCarCheatsActivated(); typedef bool(__thiscall *FannyMagnetFn)(CPed* ped, CPed* player); static FannyMagnetFn FannyMagnet; }; #endif
2004cf551cd8f14fd3e46ae0611693d0b1df4236
9ca61a780f84f0a16df2ae1f98833888f9833dbe
/dropped/SerialLog.h
3ec6abe788c903c92036183d77f6e82d5c9715c8
[]
no_license
sabbiolino80/WaterinoESP
133976b02638e314320786eb5a0fb88aeaea90a1
3aaaaf73f423dd52139c1168165af890abb407a8
refs/heads/master
2020-03-30T07:52:42.832132
2018-11-04T20:42:00
2018-11-04T20:42:00
150,972,279
0
0
null
null
null
null
UTF-8
C++
false
false
196
h
SerialLog.h
#ifndef SerialLog_h #define SerialLog_h #include "Arduino.h" class SerialLog { public: SerialLog(); //~SerialLog(); void setup(); void logString(); private: }; #endif
6387deab3b9da3c8d399cee65ebe84520f10b98a
e6aab19a83b758070494d982202026f2797d3008
/Empirical/tests/test_systematics.cc
a710534c556349357cd1e488c6fad3e96e03343d
[]
no_license
zhaoyuanqi/Symbulation_outerprotein
228a8657a4fb32babd43b922043d6f52bbd3700d
0df296edff5845fb9c51827520a0f27709c58535
refs/heads/master
2021-10-08T11:39:50.462568
2018-12-11T21:14:38
2018-12-11T21:14:38
155,332,352
0
1
null
null
null
null
UTF-8
C++
false
false
14,534
cc
test_systematics.cc
#define CATCH_CONFIG_MAIN #ifndef EMP_TRACK_MEM #define EMP_TRACK_MEM #endif #include "../third-party/Catch/single_include/catch.hpp" #include "Evolve/Systematics.h" #include "Evolve/SystematicsAnalysis.h" #include "Evolve/World.h" #include "base/vector.h" #include <iostream> #include "hardware/AvidaGP.h" #include "Evolve/World_output.h" TEST_CASE("Test Systematics", "[evo]") { emp::Systematics<int, int> sys([](int & i){return i;}, true, true, true); std::cout << "\nAddOrg 25 (id1, no parent)\n"; auto id1 = sys.AddOrg(25, nullptr, 0); std::cout << "\nAddOrg -10 (id2; parent id1)\n"; auto id2 = sys.AddOrg(-10, id1, 6); std::cout << "\nAddOrg 26 (id3; parent id1)\n"; auto id3 = sys.AddOrg(26, id1, 10); std::cout << "\nAddOrg 27 (id4; parent id2)\n"; auto id4 = sys.AddOrg(27, id2, 25); std::cout << "\nAddOrg 28 (id5; parent id2)\n"; auto id5 = sys.AddOrg(28, id2, 32); std::cout << "\nAddOrg 29 (id6; parent id5)\n"; auto id6 = sys.AddOrg(29, id5, 39); std::cout << "\nAddOrg 30 (id7; parent id1)\n"; auto id7 = sys.AddOrg(30, id1, 6); std::cout << "\nRemoveOrg (id2)\n"; sys.RemoveOrg(id1); sys.RemoveOrg(id2); double mpd = sys.GetMeanPairwiseDistance(); std::cout << "MPD: " << mpd <<std::endl; REQUIRE(mpd == Approx(2.8)); std::cout << "\nAddOrg 31 (id8; parent id7)\n"; auto id8 = sys.AddOrg(31, id7, 11); std::cout << "\nAddOrg 32 (id9; parent id8)\n"; auto id9 = sys.AddOrg(32, id8, 19); REQUIRE(sys.GetEvolutionaryDistinctiveness(id3, 10) == 10); REQUIRE(sys.GetEvolutionaryDistinctiveness(id4, 25) == 21); REQUIRE(sys.GetEvolutionaryDistinctiveness(id5, 32) == 15); REQUIRE(sys.GetEvolutionaryDistinctiveness(id6, 39) == 22); REQUIRE(sys.GetEvolutionaryDistinctiveness(id6, 45) == 28); REQUIRE(sys.GetEvolutionaryDistinctiveness(id9, 19) == 12.5); std::cout << "\nAddOrg 33 (id10; parent id8)\n"; auto id10 = sys.AddOrg(33, id8, 19); sys.RemoveOrg(id7); sys.RemoveOrg(id8); REQUIRE(sys.GetEvolutionaryDistinctiveness(id9, 19) == 13.5); REQUIRE(sys.GetEvolutionaryDistinctiveness(id10, 19) == 13.5); sys.RemoveOrg(id10); REQUIRE(sys.GetEvolutionaryDistinctiveness(id9, 19) == 19); std::cout << "\nAddOrg 34 (id11; parent id9)\n"; auto id11 = sys.AddOrg(34, id9, 22); std::cout << "\nAddOrg 35 (id12; parent id10)\n"; auto id12 = sys.AddOrg(35, id11, 23); sys.RemoveOrg(id9); REQUIRE(sys.GetEvolutionaryDistinctiveness(id11, 26) == 13); REQUIRE(sys.GetEvolutionaryDistinctiveness(id12, 26) == 15); std::cout << "\nAddOrg 36 (id13; parent id12)\n"; auto id13 = sys.AddOrg(36, id12, 27); std::cout << "\nAddOrg 37 (id14; parent id13)\n"; auto id14 = sys.AddOrg(37, id13, 30); sys.RemoveOrg(id13); REQUIRE(sys.GetEvolutionaryDistinctiveness(id14, 33) == Approx(17.833333)); std::cout << "\nAddOrg 38 (id15; parent id14)\n"; auto id15 = sys.AddOrg(38, id14, 33); sys.RemoveOrg(id14); REQUIRE(sys.GetEvolutionaryDistinctiveness(id15, 33) == Approx(17.833333)); std::cout << "\nAddOrg 39 (id16; parent id11)\n"; auto id16 = sys.AddOrg(39, id11, 35); std::cout << "\nAddOrg 40 (id17; parent id11)\n"; auto id17 = sys.AddOrg(40, id11, 35); REQUIRE(sys.GetEvolutionaryDistinctiveness(id16, 35) == Approx(17.4)); REQUIRE(sys.GetEvolutionaryDistinctiveness(id17, 35) == Approx(17.4)); std::cout << "\nAddOrg 41 (id18; parent id17)\n"; auto id18 = sys.AddOrg(41, id17, 36); REQUIRE(sys.GetEvolutionaryDistinctiveness(id18, 37) == Approx(12.1666667)); REQUIRE(sys.GetTaxonDistinctiveness(id18) == Approx(1.0/6.0)); REQUIRE(sys.GetBranchesToRoot(id18) == 1); REQUIRE(sys.GetDistanceToRoot(id18) == 6); std::cout << "\nAddOrg 42 (id19; parent id17)\n"; auto id19 = sys.AddOrg(42, id17, 37); REQUIRE(sys.GetBranchesToRoot(id19) == 2); REQUIRE(sys.GetDistanceToRoot(id19) == 6); REQUIRE(sys.GetTaxonDistinctiveness(id19) == Approx(1.0/6.0)); REQUIRE(sys.GetTaxonDistinctiveness(id15) == Approx(1.0/8.0)); REQUIRE(sys.GetBranchesToRoot(id15) == 1); REQUIRE(sys.GetDistanceToRoot(id15) == 8); REQUIRE(sys.GetPhylogeneticDiversity() == 17); REQUIRE(sys.GetAveDepth() == Approx(4.272727)); std::cout << "id1 = " << id1 << std::endl; std::cout << "id2 = " << id2 << std::endl; std::cout << "id3 = " << id3 << std::endl; std::cout << "id4 = " << id4 << std::endl; std::cout << "\nLineage:\n"; sys.PrintLineage(id4); sys.PrintStatus(); } TEST_CASE("Pointer to systematics", "[evo]") { emp::Ptr<emp::Systematics<int, int>> sys; sys.New([](int & i){return i;}, true, true, true); sys.Delete(); } TEST_CASE("Test Data Struct", "[evo]") { emp::Ptr<emp::Systematics<int, int, emp::datastruct::mut_landscape_info<int> >> sys; sys.New([](int & i){return i;}, true, true, true); auto id1 = sys->AddOrg(1, nullptr); id1->GetData().fitness.Add(2); id1->GetData().phenotype = 6; auto id2 = sys->AddOrg(2, id1); id2->GetData().mut_counts["substitution"] = 2; id2->GetData().fitness.Add(1); id2->GetData().phenotype = 6; REQUIRE(id2->GetData().mut_counts["substitution"] == 2); auto id3 = sys->AddOrg(3, id1); id3->GetData().mut_counts["substitution"] = 5; id3->GetData().fitness.Add(0); id3->GetData().phenotype = 6; auto id4 = sys->AddOrg(4, id2); id4->GetData().mut_counts["substitution"] = 1; id4->GetData().fitness.Add(3); id4->GetData().phenotype = 3; auto id5 = sys->AddOrg(5, id4); id5->GetData().mut_counts["substitution"] = 1; id5->GetData().fitness.Add(2); id5->GetData().phenotype = 6; REQUIRE(CountMuts(id4) == 3); REQUIRE(CountDeleteriousSteps(id4) == 1); REQUIRE(CountPhenotypeChanges(id4) == 1); REQUIRE(CountUniquePhenotypes(id4) == 2); REQUIRE(CountMuts(id3) == 5); REQUIRE(CountDeleteriousSteps(id3) == 1); REQUIRE(CountPhenotypeChanges(id3) == 0); REQUIRE(CountUniquePhenotypes(id3) == 1); REQUIRE(CountMuts(id5) == 4); REQUIRE(CountDeleteriousSteps(id5) == 2); REQUIRE(CountPhenotypeChanges(id5) == 2); REQUIRE(CountUniquePhenotypes(id5) == 2); sys.Delete(); } TEST_CASE("World systematics integration", "[evo]") { // std::function<void(emp::Ptr<emp::Taxon<emp::vector<int>, emp::datastruct::mut_landscape_info<int>>>)> setup_phenotype = [](emp::Ptr<emp::Taxon<emp::vector<int>, emp::datastruct::mut_landscape_info<int>>> tax){ // tax->GetData().phenotype = emp::Sum(tax->GetInfo()); // }; using systematics_t = emp::Systematics< emp::vector<int>, emp::vector<int>, emp::datastruct::mut_landscape_info< int > >; emp::World<emp::vector<int>> world; emp::Ptr<systematics_t> sys; sys.New([](emp::vector<int> & v){return v;}, true, true, true); world.AddSystematics(sys); world.SetMutFun([](emp::vector<int> & org, emp::Random & r){return 0;}); // world.GetSystematics().OnNew(setup_phenotype); world.InjectAt(emp::vector<int>({1,2,3}), 0); sys->GetTaxonAt(0)->GetData().RecordPhenotype(6); sys->GetTaxonAt(0)->GetData().RecordFitness(2); REQUIRE(sys->GetTaxonAt(0)->GetData().phenotype == 6); std::unordered_map<std::string, int> mut_counts; mut_counts["substitution"] = 3; emp::vector<int> new_org({4,2,3}); auto old_taxon = sys->GetTaxonAt(0); world.DoBirth(new_org,0); REQUIRE(old_taxon->GetNumOrgs() == 0); REQUIRE(old_taxon->GetNumOff() == 1); REQUIRE(sys->GetTaxonAt(0)->GetParent()->GetData().phenotype == 6); REQUIRE((*sys->GetActive().begin())->GetNumOrgs() == 1); } template <typename WORLD_TYPE> emp::DataFile AddDominantFile(WORLD_TYPE & world){ using mut_count_t = std::unordered_map<std::string, int>; using data_t = emp::datastruct::mut_landscape_info<emp::vector<double>>; using org_t = emp::AvidaGP; using systematics_t = emp::Systematics<org_t, org_t, data_t>; auto & file = world.SetupFile("dominant.csv"); std::function<size_t(void)> get_update = [&world](){return world.GetUpdate();}; std::function<int(void)> dom_mut_count = [&world](){ return CountMuts(dynamic_cast<emp::Ptr<systematics_t>>(world.GetSystematics(0))->GetTaxonAt(0)); }; std::function<int(void)> dom_del_step = [&world](){ return CountDeleteriousSteps(dynamic_cast<emp::Ptr<systematics_t>>(world.GetSystematics(0))->GetTaxonAt(0)); }; std::function<size_t(void)> dom_phen_vol = [&world](){ return CountPhenotypeChanges(dynamic_cast<emp::Ptr<systematics_t>>(world.GetSystematics(0))->GetTaxonAt(0)); }; std::function<size_t(void)> dom_unique_phen = [&world](){ return CountUniquePhenotypes(dynamic_cast<emp::Ptr<systematics_t>>(world.GetSystematics(0))->GetTaxonAt(0)); }; file.AddFun(get_update, "update", "Update"); file.AddFun(dom_mut_count, "dominant_mutation_count", "sum of mutations along dominant organism's lineage"); file.AddFun(dom_del_step, "dominant_deleterious_steps", "count of deleterious steps along dominant organism's lineage"); file.AddFun(dom_phen_vol, "dominant_phenotypic_volatility", "count of changes in phenotype along dominant organism's lineage"); file.AddFun(dom_unique_phen, "dominant_unique_phenotypes", "count of unique phenotypes along dominant organism's lineage"); file.PrintHeaderKeys(); return file; } TEST_CASE("Run world", "[evo]") { using mut_count_t = std::unordered_map<std::string, int>; using data_t = emp::datastruct::mut_landscape_info<emp::vector<double>>; using org_t = emp::AvidaGP; using gene_systematics_t = emp::Systematics<org_t, org_t::genome_t, data_t>; using phen_systematics_t = emp::Systematics<org_t, emp::vector<double>, data_t>; emp::Random random; emp::World<org_t> world(random, "AvidaWorld"); world.SetPopStruct_Mixed(true); std::function<emp::AvidaGP::genome_t(emp::AvidaGP &)> gene_fun = [](emp::AvidaGP & org) { return org.GetGenome(); }; std::function<emp::vector<double>(emp::AvidaGP &)> phen_fun = [](emp::AvidaGP & org) { emp::vector<double> phen; for (int i = 0; i < 16; i++) { org.ResetHardware(); org.Process(20); phen.push_back(org.GetOutput(i)); } return phen; }; mut_count_t last_mutation; emp::Ptr<gene_systematics_t> gene_sys; emp::Ptr<phen_systematics_t> phen_sys; gene_sys.New(gene_fun, true,true,true); phen_sys.New(phen_fun, true,true,true); world.AddSystematics(gene_sys); world.AddSystematics(phen_sys); emp::Signal<void(mut_count_t)> on_mutate_sig; ///< Trigger signal before organism gives birth. emp::Signal<void(size_t pos, double)> record_fit_sig; ///< Trigger signal before organism gives birth. emp::Signal<void(size_t pos, emp::vector<double>)> record_phen_sig; ///< Trigger signal before organism gives birth. on_mutate_sig.AddAction([&last_mutation](mut_count_t muts){last_mutation = muts;}); record_fit_sig.AddAction([&world](size_t pos, double fit){ world.GetSystematics(0).Cast<gene_systematics_t>()->GetTaxonAt(pos)->GetData().RecordFitness(fit); world.GetSystematics(1).Cast<phen_systematics_t>()->GetTaxonAt(pos)->GetData().RecordFitness(fit); }); record_phen_sig.AddAction([&world](size_t pos, emp::vector<double> phen){ world.GetSystematics(0).Cast<gene_systematics_t>()->GetTaxonAt(pos)->GetData().RecordPhenotype(phen); world.GetSystematics(1).Cast<phen_systematics_t>()->GetTaxonAt(pos)->GetData().RecordPhenotype(phen); }); // world.OnOrgPlacement([&last_mutation, &world](size_t pos){ // world.GetSystematics(0).Cast<systematics_t>()->GetTaxonAt(pos)->GetData().RecordMutation(last_mutation); // }); world.SetupSystematicsFile().SetTimingRepeat(1); world.SetupFitnessFile().SetTimingRepeat(1); world.SetupPopulationFile().SetTimingRepeat(1); emp::AddPhylodiversityFile(world, 0, "genotype_phylodiversity.csv").SetTimingRepeat(1); emp::AddPhylodiversityFile(world, 1, "phenotype_phylodiversity.csv").SetTimingRepeat(1); emp::AddLineageMutationFile(world).SetTimingRepeat(1); // AddDominantFile(world).SetTimingRepeat(1); // emp::AddMullerPlotFile(world).SetTimingOnce(1); // Setup the mutation function. world.SetMutFun( [&world, &on_mutate_sig](emp::AvidaGP & org, emp::Random & random) { uint32_t num_muts = random.GetUInt(4); // 0 to 3 mutations. for (uint32_t m = 0; m < num_muts; m++) { const uint32_t pos = random.GetUInt(20); org.RandomizeInst(pos, random); } on_mutate_sig.Trigger({{"substitution",num_muts}}); return num_muts; }); // Setup the fitness function. std::function<double(emp::AvidaGP &)> fit_fun = [](emp::AvidaGP & org) { int count = 0; for (int i = 0; i < 16; i++) { org.ResetHardware(); org.SetInput(0,i); org.SetOutput(0, -99999); org.Process(20); double score = 1.0 / (org.GetOutput(i) - (double) (i*i)); if (score > 1000) { score = 1000; } count += score; } return (double) count; }; world.SetFitFun(fit_fun); // emp::vector< std::function<double(const emp::AvidaGP &)> > fit_set(16); // for (size_t out_id = 0; out_id < 16; out_id++) { // // Setup the fitness function. // fit_set[out_id] = [out_id](const emp::AvidaGP & org) { // return (double) -std::abs(org.GetOutput((int)out_id) - (double) (out_id * out_id)); // }; // } // Build a random initial popoulation. for (size_t i = 0; i < 1; i++) { emp::AvidaGP cpu; cpu.PushRandom(random, 20); world.Inject(cpu.GetGenome()); } for (size_t i = 0; i < 100; i++) { EliteSelect(world, 1, 1); } world.Update(); // Do the run... for (size_t ud = 0; ud < 100; ud++) { // Update the status of all organisms. world.ResetHardware(); world.Process(200); double fit0 = world.CalcFitnessID(0); std::cout << (ud+1) << " : " << 0 << " : " << fit0 << std::endl; // Keep the best individual. EliteSelect(world, 1, 1); // Run a tournament for the rest... TournamentSelect(world, 2, 99); // LexicaseSelect(world, fit_set, POP_SIZE-1); // EcoSelect(world, fit_fun, fit_set, 100, 5, POP_SIZE-1); for (size_t i = 0; i < world.GetSize(); i++) { record_fit_sig.Trigger(i, world.CalcFitnessID(i)); record_phen_sig.Trigger(i, phen_fun(world.GetOrg(i))); } world.Update(); } // std::cout << std::endl; // world[0].PrintGenome(); // std::cout << std::endl; // for (int i = 0; i < 16; i++) { // std::cout << i << ":" << world[0].GetOutput(i) << " "; // } // std::cout << std::endl; }
532cb839ce19ae081e449804c556e4bc72a29610
338499dfb0b1635079ff796064905e7a8b3af6fc
/Chapter 1/Kattis/judgingmoose.cpp
ea6c917d4dc9d2340d47e9ed6c8b1d4a1ab85d2e
[]
no_license
Likey00/CP4
a50a1209d66f02a305866896c7d91fddd4d9d8aa
6106538784065e13f6682e88d826bb8832cc9df5
refs/heads/master
2022-11-26T02:55:05.662759
2020-08-02T18:38:02
2020-08-02T18:38:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
468
cpp
judgingmoose.cpp
#include <bits/stdc++.h> using namespace std; int main() { //Initialize and take in l and r int l, r; cin >> l >> r; //If both zero, output not a moose and exit program if (l+r == 0) { cout << "Not a moose"; return 0; } //Depending on if they are equal, output even or odd if (l == r) cout << "Even "; else cout << "Odd "; //Then, no matter what output double the higher one cout << max(l, r) * 2; }
ca68554fae7b0047f4f466b244ad5f83f9c7cae5
7888f2f75d277c64bfc71009ec0eb32bc45a1681
/Arquivos_Curso_Arduino/arduino_aula_37/Aula-37.ino
ccac041af762c5bd70bb195586991d46de89cf2c
[ "MIT" ]
permissive
maledicente/cursos
bba06a0d09037fd8cae69927c996805d513ddb25
00ace48da7e48b04485e4ca97b3ca9ba5f33a283
refs/heads/master
2023-08-12T03:01:02.799974
2021-10-11T14:29:35
2021-10-11T14:29:35
273,795,405
1
0
null
null
null
null
UTF-8
C++
false
false
3,569
ino
Aula-37.ino
#include <LiquidCrystal.h> #define btcima 8 #define btbaixo 9 #define bttiro 10 LiquidCrystal lcd(7,6,5,4,3,2); int vel=100; int pxnave,pynave,pxaste,pyaste,pxenergia,pyenergia,pxtiro,pytiro; bool game,vtiro,vpilha; int pontos; double venergia; int vtela; byte nave[8]={B11000,B01100,B01110,B01111,B01111,B01110,B01100,B11000}; byte asteroide[8]={B00000,B00100,B01110,B10111,B11101,B01110,B00100,B00000}; byte explosao[8]={B10001,B10101,B01010,B10100,B00101,B01010,B10101,B10001}; byte energia[8]={B01110,B11011,B10001,B10101,B10101,B10101,B10001,B11111}; byte tiro[8]={B00000,B00000,B00000,B00111,B00111,B00000,B00000,B00000}; void setup() { pxnave=pynave=pyaste=pontos=pxenergia=pyenergia=pytiro=0; pxtiro=-1; pxaste=12; venergia=100; vtela=0; lcd.createChar(1,nave); lcd.createChar(2,asteroide); lcd.createChar(3,explosao); lcd.createChar(4,energia); lcd.createChar(5,tiro); lcd.begin(16,2); lcd.clear(); game=false; vtiro=vpilha=false; } void loop(){ if(game){ venergia-=0.25; lcd.clear(); painel(13); if(digitalRead(btcima)==1){ pynave=0; } if(digitalRead(btbaixo)==1){ pynave=1; } if(digitalRead(bttiro)==1){ pxtiro=1; vtiro=true; pytiro=pynave; } pxaste-=1; desenhaNave(pxnave,pynave); desenhaAsteroide(pxaste,pyaste); if(vtiro){ desenhaTiro(pxtiro,pytiro); pxtiro+=1; } if(pxaste<0){ pxaste=12; pyaste=random(0,2); } if(pxtiro>16){ vtiro=false; pxtiro=-1; } if(((pxtiro==pxaste+1)&&(pytiro==pyaste))||((pxtiro==pxaste)&&(pytiro==pyaste))){ vtiro=false; pxtiro=-1; desenhaExplosaoAsteroide(pxaste,pyaste); pyaste=random(0,2); pxaste=12; pontos+=2; } if(((pxnave==pxaste)&&(pynave==pyaste))){ game=0; desenhaExplosaoNave(pxnave,pyaste); vtela=2; } if(!vpilha){ if(random(0,60)>58){ pxenergia=12; vpilha=true; pyenergia=random(0,2); } }else{ pxenergia-=1; desenhaEnergia(pxenergia,pyenergia); if(((pxnave==pxenergia+1)&&(pynave==pyenergia))||((pxnave==pxenergia)&&(pynave==pyenergia))){ vpilha=false; pxenergia=-1; venergia=100; } } delay(vel); }else{ tela(vtela); if(digitalRead(bttiro)==1){ reset(); } } } void desenhaNave(int px, int py){ lcd.setCursor(px,py); lcd.write(1); } void desenhaAsteroide(int px, int py){ lcd.setCursor(px,py); lcd.write(2); } void desenhaEnergia(int px, int py){ lcd.setCursor(px,py); lcd.write(4); } void desenhaTiro(int px, int py){ lcd.setCursor(px,py); lcd.write(5); } void desenhaExplosaoNave(int px, int py){ lcd.clear(); lcd.setCursor(px,py); lcd.write(3); delay(1000); lcd.clear(); } void desenhaExplosaoAsteroide(int px, int py){ lcd.setCursor(px,py); lcd.write(3); delay(1000); lcd.clear(); } void reset(){ pontos=0; venergia=100; game=true; vtela=0; } void painel(int px){ lcd.setCursor(px,0); lcd.print(pontos); lcd.setCursor(px,1); lcd.print(venergia); } void tela(int cond){//0=TelaInicial | 1=Ganhou | 2=Perdeu if(cond<1){ lcd.setCursor(3,0); lcd.print("CFB NAVE"); lcd.setCursor(0,1); lcd.print("Pressione tiro"); }else{ char txt[6]={(cond>1 ? "PERDEU" : "GANHOU")}; lcd.setCursor(9,0); lcd.print("pts:"); lcd.setCursor(13,0); lcd.print(pontos); lcd.setCursor(1,0); lcd.print(txt); lcd.setCursor(0,1); lcd.print("Pressione tiro"); } }
eba50e989ace9829fe4114a3b7ccecfb66a3e2c9
e0da8214ab9bb27c1a524ce35b9f742381593c9f
/stockportfolio_priya.h
25161d8acd855ef5e76e39cb4310adb375e64baf
[]
no_license
gksdooz/-
72d41fbdd51dc06acba4e671336064ab489d863b
1e375556630a88a5f36c4dd14f5423adba0f010e
refs/heads/master
2020-06-02T20:07:14.048896
2019-06-11T04:24:48
2019-06-11T04:24:48
191,293,249
0
0
null
null
null
null
UHC
C++
false
false
1,614
h
stockportfolio_priya.h
//Shanmukha Priya Loke //December 13th, 2015 #ifndef STOCKPORTFOLIO_PRIYA_H #define STOCKPORTFOLIO_PRIYA_H #include "account_priya.h" #include<string> using namespace std; class ListNode //리스트 노드들의 구현 { friend class stockaccount; //stockaccount를 프렌드클래스로 선언 public: //퍼블릭 멤버 함수 ListNode(string& name,int numb) :symbol(name),number(numb) { this->next=NULL; this->prev=NULL; } private: string symbol; //리스트의 심볼 int number; ListNode *next;//리스트의 next 노드 ListNode *prev;//리스트의 prev 노드 }; class stockaccount:public account //클래스 account로 부터 퍼블릭 상속 { public: stockaccount(); //생성자 //멤버함수 선언 static float total_portfolio_value; void display(); void current_portfolio(); void buy_shares(); void addNode(ListNode *); void sell_shares(); void delNode(string node); void transac_history(); void update_stocks(); string getTime(); //Merge Sort 작업을 구성하는 함수들 ListNode *split(ListNode *); ListNode *merge_sort(ListNode *); ListNode *sortList(ListNode *first,ListNode *second); void sort_wrapper(); virtual float getBalance(); virtual void setBalance(float); private: ListNode *firstPtr; //첫 번째노드의 포인터 ListNode *lastPtr; //두 번째 노드의 포인터 int size_list; //더블링크드리스트의 사이즈 }; #endif // STOCKPORTFOLIO_PRIYA_H
65b343271dee9264350c865e03f2905f29d54f68
25249978ae1c0da9f4665f2a0d520437c6817c61
/GritEngine/test.cpp
637e4dc91a21638121f77e1900487087756e38e5
[]
no_license
pranav-bt/MonsterChase
9c519515d11c9b16d070babf7ed8a20b8eb3ae3a
cff3780c14c0515790e0b6c7140aec69e584b544
refs/heads/master
2023-08-16T04:56:02.647845
2021-09-15T07:49:04
2021-09-15T07:49:04
406,661,898
1
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
test.cpp
#include <assert.h> #include"Point2D.h" namespace GritEngine{ void Point2DUnitTest() { Point2D A(0, 1); Point2D B(2, 3); // equality bool bEqual = A == B; assert(bEqual == false); bEqual = B == Point2D(2, 3); assert(bEqual == true); // Inequality bool bNotEqual = A != B; assert(bNotEqual == true); bNotEqual = B != Point2D(2, 3); assert(bNotEqual == false); // Point2D + Point2D Point2D C = A + B; assert(C == Point2D(2, 4)); // Point2D - Point2D C = B - A; assert(C == Point2D(2, 2)); // Point2D * int C = A * 2; assert(C == Point2D(0, 2)); // Point2D / int C = Point2D(6, 4) / 2; assert(C == Point2D(3, 2)); // int * Point2D C = 2 * B; assert(C == Point2D(4, 6)); // negate C = -B; assert(C == Point2D(-2, -3)); // Point2D += Point2D B += Point2D(2, 1); assert(B == Point2D(4, 4)); // Point2D -= Point2d B -= Point2D(2, 1); assert(B == Point2D(2, 3)); // Point2D *= int B *= 2; assert(B == Point2D(4, 6)); // Point2D /= int B /= 2; assert(B == Point2D(2, 3)); } }
6ee148b0ad1fd22d42f96d2823c267a1ad09a17a
271e9b0643ad823b5bd9118f7c478988cb461526
/kakula_prototype2/menukakula.h
ad68d51921b1db04a944922942c110a6a72c8560
[]
no_license
sofyan48/e-kakula_Qt5
7b2a9b30d9e106ff2bafce78c870d2bf928e3ff5
953a37f1b94465f6ea64e525cc5867ae6f6d47f4
refs/heads/master
2021-05-28T01:01:54.641193
2014-07-21T14:28:05
2014-07-21T14:28:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,153
h
menukakula.h
#ifndef MENUKAKULA_H #define MENUKAKULA_H #include <QWidget> #include <QMessageBox> #include "nastyfft.h" #include "settingsdialog.h" #include "mediamusic.h" #include "menudialog.h" #include <QKeyEvent> namespace Ui { class MenuKakula; } class MenuKakula : public QWidget { Q_OBJECT public: explicit MenuKakula(QWidget *parent = 0); virtual void resizeEvent(QResizeEvent *); ~MenuKakula(); NastyFFT* glView(); public slots: void showSettings(); private slots: void on_comboVisualisasi_activated(int index); void on_btnG1_clicked(); void on_btnG2_clicked(); void on_btnG3_clicked(); void on_btnG4_clicked(); void on_btnG5_clicked(); void on_btnG6_clicked(); void on_btnG7_clicked(); void on_comboMode_activated(int index); void on_volSlider_sliderMoved(int position); void keyPressEvent(QKeyEvent *e); void on_menuHide_clicked(); void on_menuShow_clicked(); private: Ui::MenuKakula *ui; NastyFFT *plugin; SettingsDialog *wInSetting; MediaMusic *media; MenuDialog *wmenudialog; int volume; QString mode; }; #endif // MENUKAKULA_H
21d22e3f5424be0e84192128504691998d39387a
85ebf4abe0e6e544898d37ba59d5e70aff70039d
/oldGameEngine/Gamee/Archaeopteryx.cpp
189cbf01cf7c688e04545ef39e922f9f7f5aca55
[]
no_license
leonardo98/simplescripthge
ffd27b8c4eba98d3a456777a28f39c71614c05ae
a6b4a9f40e3243490b9f1671eb469043c266f74a
refs/heads/master
2021-01-01T17:47:23.465871
2014-11-25T07:35:42
2014-11-25T07:35:42
33,180,859
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
12,790
cpp
Archaeopteryx.cpp
#include "Archaeopteryx.h" #include "../Core/Core.h" #include "BirdsManager.h" #include "ProductManager.h" #include "GameField.h" #include "../Core/Math.h" const float Archaeopteryx::SPEED = 80.f; Archaeopteryx::Archaeopteryx(const std::string &birdId) : _mirror(rand() % 2 == 1) { _waterPos = FPoint2D(771, 628); _foodPos = FPoint2D(733, 540); _turnPoint = FPoint2D(900, 595); _eggPos = FPoint2D(900, 595); _puhPos = FPoint2D(890, 575); BirdsManager::_birds.push_back(this); if (birdId != "") { _birdsType = birdId.substr(0, birdId.length() - 2); _sex = birdId[birdId.length() - 1]; _boy = (_sex == "b" || _sex == "m"); if (_sex == "b" || _sex == "g") { _lifeTimeCounter = Math::random(0.1f, 2.f); _age = age_young; } else { _lifeTimeCounter = Math::random(0.5f, 2.f); _age = age_adult; _waterPos.x += 10; _foodPos.x += 10; } } else { if (rand() % 2 == 1 && false) {// test/debug only _birdsType = "archaeopteryx"; } else { _birdsType = "dodo"; } _boy = (rand() % 2 == 1) && false;// test/debug only if (rand() % 2 < 1 || true) {// test/debug only _age = age_young; if (_boy) { _sex = "b"; } else { _sex = "g"; } _lifeTimeCounter = Math::random(0.1f, 2.f); } else { _age = age_adult; _waterPos.x += 10; _foodPos.x += 10; if (_boy) { _sex = "m"; } else { _sex = "w"; } _lifeTimeCounter = 0.f; } } SetupAnimation(); _shadow = Core::getTexture("persshadow"); _endTarget = _currentTarget = _pos; _timeCounter = 0.f; _region.push_back(FPoint2D(765, 460)); _region.push_back(FPoint2D(890, 460)); _region.push_back(FPoint2D(910, 520)); _region.push_back(FPoint2D(1000, 540)); _region.push_back(FPoint2D(1000, 680)); _region.push_back(FPoint2D(790, 680)); _region.push_back(FPoint2D(735, 500)); float WIDTH_RUN = 65; float HEIGHT_RUN = 40; _runAway.push_back(FPoint2D(865 - WIDTH_RUN, 550)); _runAway.push_back(FPoint2D(865, 550 - HEIGHT_RUN)); _runAway.push_back(FPoint2D(865 + WIDTH_RUN, 550)); _runAway.push_back(FPoint2D(865, 550 + HEIGHT_RUN)); _runAway.push_back(FPoint2D(865 - WIDTH_RUN, 550)); _runAway.push_back(FPoint2D(865, 550 - HEIGHT_RUN)); _runAway.push_back(FPoint2D(865 + WIDTH_RUN, 550)); _runAway.push_back(FPoint2D(865, 550 + HEIGHT_RUN)); _runAway.push_back(FPoint2D(1100, 550 + HEIGHT_RUN)); _pos = _region[rand() % _region.size()]; _pos = (_pos + _region[rand() % _region.size()]) / 2; _actionTimeCounter = Math::random(1.5f, 4.f); _state = state_idle; _current = _leftFrontIdle; _current->SetPos(_pos, _mirror); _waitingTimeCounter = 0.f; if (_age == age_young) { _adultCircleStates.push_back(state_want_drink); _adultCircleStates.push_back(state_want_eat); _adultCircleStates.push_back(state_want_drink); _adultCircleStates.push_back(state_want_eat); } _productCircleStates.push_back(state_want_drink); _productCircleStates.push_back(state_want_eat); _productCircleStates.push_back(state_want_drink); _productCircleStates.push_back(state_want_eat); _nextState = state_none; _runAwayTimeCounter = 0.f; } void Archaeopteryx::SetupAnimation() { std::string id = _birdsType + "_" + _sex; //id = "archaeopteryx_b"; _left = Core::getAnimation(id + "_left"); _leftIdle = Core::getAnimation(id + "_leftidle"); _leftFront = Core::getAnimation(id + "_leftfront"); _leftFrontIdle = Core::getAnimation(id + "_leftfrontidle"); _leftBack = Core::getAnimation(id + "_leftback"); _lefteat = Core::getAnimation(id + "_leftdrink"); } void Archaeopteryx::Draw() { if (_active) { float b = GameField::SELECTION_BORDER; Render::SetBlendMode(3); Render::PushMatrix(); Render::MatrixMove(-b, 0); InnerDraw(); Render::MatrixMove(2 * b, 0); InnerDraw(); Render::MatrixMove(-b, b); InnerDraw(); Render::MatrixMove(0, -2 * b); InnerDraw(); Render::PopMatrix(); Render::SetBlendMode(BLEND_DEFAULT); } InnerDraw(); } void Archaeopteryx::DrawBottom() { _shadow->Render(_pos.x - _shadow->Width() / 2, _pos.y - _shadow->Height() / 2); } void Archaeopteryx::InnerDraw() { assert(0 <= _pos.x && _pos.x <= 1124 + 10.f); assert(0 <= _pos.y && _pos.y <= 768); Render::PushMatrix(); Render::MatrixMove(_pos.x, _pos.y); if (_mirror) { Render::MatrixScale(-1.f, 1.f); } _current->Draw(_timeCounter); Render::PopMatrix(); if (_state == state_want_drink || _state == state_want_eat) { _waitingProgress.Move(_pos.x, _pos.y - 80); _waitingProgress.Draw(1.f - _waitingTimeCounter); } else if (_state == state_archaeopteryx_puh) { _waitingProgress.Move(_pos.x, _pos.y - 30); _waitingProgress.Draw(1.f - _waitingTimeCounter); } //if (_nextState == state_want_drink || _nextState == state_want_eat) { // _waitingProgress.Move(_pos.x, _pos.y - 80); // _waitingProgress.Draw(0.f); //} //char buffer[100]; //sprintf(buffer, "lifeTimer:%f", _lifeTimeCounter); //Render::PrintString(_pos.x, _pos.y - 50, "", buffer); } void Archaeopteryx::Update(float dt) { _timeCounter += (dt / _current->Time()); while (_timeCounter >= 1.f) { _timeCounter -= 1.f; } if (_runAwayTimeCounter > 0.f) { _runAwayTimeCounter -= dt; } if (_waitingTimeCounter > 0.f) { _waitingTimeCounter -= dt / 60.f; // время ожидания(60) if (_state == state_want_drink && !BirdsManager::IsWaterEmpty()) { _state = state_idle; _current = _lefteat; _actionTimeCounter = 1.f; _waitingTimeCounter = 0.f; BirdsManager::DrinkWater(); } else if (_state == state_want_eat && !BirdsManager::IsFoodEmpty()) { _state = state_idle; _current = _lefteat; _actionTimeCounter = 1.f; _waitingTimeCounter = 0.f; BirdsManager::EatFood(); } else if (_waitingTimeCounter > 0.f) { return; } else { if (_state != state_archaeopteryx_puh) { _adultCircleStates.push_front(_state);// hack - if miss any action - it will restart in 10 second } _state = state_walk; _runAwayPoint = 0; _runAwayTimeCounter = 10.f; _actionTimeCounter = dt / 2.f; } } if (_runAwayTimeCounter > 0.f) { _pos += *(_currentTarget - _pos).Normalize() * SPEED * 2 * dt; // BirdsManager::UpdatePosition(this, dt); if ((_currentTarget - _pos).Length() < SPEED * 2 * dt) { if (_runAwayPoint < _runAway.size()) { _currentTarget = _runAway[_runAwayPoint++]; SwitchAnimation(); } } return; } else if (_actionTimeCounter >= 0.f) { _actionTimeCounter -= dt; if (_state == state_walk) { _pos += *(_currentTarget - _pos).Normalize() * SPEED * dt; if ((_nextState == state_want_eat && (_pos - _foodPos).Length() < SPEED * dt) || (_nextState == state_want_drink && (_pos - _waterPos).Length() < SPEED * dt)) { _state = _nextState; _current = _leftIdle; _nextState = state_none; _mirror = false; _waitingTimeCounter = 1.f; return; } else if (_nextState == state_dodo_egg && (_pos - _eggPos).Length() < SPEED * dt) { ProductManager::PlaceProduct(pt_egg, "eggs_dodo", 0.f); _nextState = state_none; return; } else if (_nextState == state_archaeopteryx_puh && (_pos - _puhPos).Length() < SPEED * dt) { SwitchToIdle(); _state = state_archaeopteryx_puh; _waitingProgress.SetIcon("hand"); _waitingTimeCounter = 1.f; _nextState = state_none; return; } } if (_actionTimeCounter <= 0.f || (_state == state_walk && (_currentTarget - _pos).Length() < SPEED * dt)) { _actionTimeCounter = Math::random(1.5f, 4.f); if (_state == state_eat0) { if (Math::random(0.f, 1.f) > 0.5f) { _state = state_idle; _current = _leftIdle; } else { SwitchToWalk(); } } else if (_state == state_idle) { if (Math::random(0.f, 1.f) < 0.5f && _current == _leftIdle) { _state = state_eat0; _current = _lefteat; _actionTimeCounter = _lefteat->Time(); } else { SwitchToWalk(); } } else if (_state == state_walk) { if (BirdsManager::FreePosition(this) && _nextState != state_want_drink && _nextState != state_want_eat) { SwitchToIdle(); _actionTimeCounter *= static_cast<int>(sqrt(float(BirdsManager::Size()))); } else { SwitchToWalk(); } } } } BirdsManager::UpdatePosition(this, dt); if (_lifeTimeCounter > 0.f && _nextState == state_none) { _lifeTimeCounter -= dt * 0.5f; if (_lifeTimeCounter <= 0.f) { _lifeTimeCounter = Math::random(0.5f, 2.f); BirdsStates ns; CircleStates *currentStates = NULL; if (_adultCircleStates.size()) { ns = _adultCircleStates.front(); currentStates = &_adultCircleStates; } else if (_sex == "b" || _sex == "g") { if (_sex == "b") { _sex = "m"; } else { _sex = "w"; } _age = age_adult; _waterPos.x += 10; _foodPos.x += 10; SetupAnimation(); return; } else if (_productCircleStates.size()) { ns = _productCircleStates.front(); currentStates = &_productCircleStates; } else { if (_sex == "w") { _productCircleStates.push_back(state_want_drink); _productCircleStates.push_back(state_want_eat); _productCircleStates.push_back(state_want_drink); _productCircleStates.push_back(state_want_eat); if (_birdsType == "dodo") { _nextState = state_dodo_egg; } else { _nextState = state_archaeopteryx_puh; } _actionTimeCounter = 20.f; SwitchToWalk(); } return; } if (ns == state_want_eat && !BirdsManager::IsFoodBusy()) { _waitingProgress.SetIcon("grain"); SwitchToWalk(); _actionTimeCounter = 20.f; _nextState = ns; currentStates->pop_front(); } else if (ns == state_want_drink && !BirdsManager::IsWaterBusy()) { _waitingProgress.SetIcon("water"); SwitchToWalk(); _actionTimeCounter = 20.f; _nextState = ns; currentStates->pop_front(); } } } } void Archaeopteryx::SwitchToIdle() { _state = state_idle; if (_current == _left) { _current = _leftIdle; } else { _current = _leftFrontIdle; } } void Archaeopteryx::SwitchToWalk() { _state = state_walk; FPoint2D newPos; do { newPos = GetNewDirection(); } while (_nextState != state_want_eat && _nextState != state_want_drink && _nextState != state_dodo_egg && _nextState != state_archaeopteryx_puh && fabs(newPos.x - _pos.x) * 1.7f < fabs(newPos.y - _pos.y)); _currentTarget = newPos; SwitchAnimation(); } FPoint2D Archaeopteryx::GetDirection() { if (_state == state_walk) { return (_currentTarget - _pos); } return FPoint2D(0, 0); } FPoint2D Archaeopteryx::GetNewDirection() { if (_nextState == state_want_drink) { return _waterPos; } else if (_nextState == state_want_eat) { return _foodPos; } else if (_nextState == state_dodo_egg) { return _eggPos; } else if (_nextState == state_archaeopteryx_puh) { return _puhPos; } else if (_nextState == state_want_eat || _nextState == state_want_drink) { return _turnPoint; } int i = rand() % _region.size(); float f = (rand() % 10) / 10.f; FPoint2D a = _region[i]; FPoint2D b; if (i == 0) { i = _region.size(); } b = _region[i - 1]; return a + (b - a) * f; } void Archaeopteryx::SwitchAnimation() { float angle = atan2(_currentTarget.y - _pos.y, _currentTarget.x - _pos.x); if (angle < 0) { angle += 2 * M_PI; } float ENLARGE = M_PI / 8 / 4; if (M_PI / 8 - ENLARGE <= angle && angle <= 3 * M_PI / 8 + ENLARGE) { _current = _leftFront; } else if (5 * M_PI / 8 - ENLARGE <= angle && angle <= 7 * M_PI / 8 + ENLARGE) { _current = _leftFront; } else if (9 * M_PI / 8 - ENLARGE <= angle && angle <= 11 * M_PI / 8 + ENLARGE) { _current = _leftBack; } else if (13 * M_PI / 8 - ENLARGE <= angle && angle <= 15 * M_PI / 8 + ENLARGE) { _current = _leftBack; } else if (angle <= M_PI / 8) { _current = _left; } else if (3 * M_PI / 8 <= angle && angle <= 5 * M_PI / 8) { _current = _leftFront; } else if (11 * M_PI / 8 <= angle && angle <= 13 * M_PI / 8) { _current = _leftBack; } else { _current = _left; } _mirror = (_pos.x < _currentTarget.x); } bool Archaeopteryx::IsUnderMouse(const FPoint2D &mousePos) { return _state == state_archaeopteryx_puh && hgeRect(_pos.x - 50, _pos.y - 100, _pos.x + 50, _pos.y).TestPoint(mousePos.x, mousePos.y); } void Archaeopteryx::OnMouseDown(const FPoint2D &mousePos) { AnnaPers::NewAction("", this); } Archaeopteryx::BirdsStates Archaeopteryx::GetState() { return _state; } void Archaeopteryx::CutFluff() { _waitingTimeCounter = 0.f; SwitchToWalk(); }
2c1cfdc57559b5b39cd45c07b9ae8a0a70e4f4e7
6cd65944e2e098edde991eb59110b672e537606b
/src/PMMR/Common/MMRHashUtil.cpp
f433d1a47d43b2d9bcc6c7d58a0caa18b031c41d
[ "MIT" ]
permissive
lokialice/GrinPlusPlus
af7286c0031ea5eb0ed016eba7af4b6840b11294
af6f794601cfd6107196a03a543abbce34cb8dc1
refs/heads/master
2020-07-27T10:44:35.543002
2019-09-14T08:58:52
2019-09-14T08:58:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,613
cpp
MMRHashUtil.cpp
#include "MMRHashUtil.h" #include "MMRUtil.h" #include <Crypto/Crypto.h> #include <Core/Serialization/Serializer.h> void MMRHashUtil::AddHashes(HashFile& hashFile, const std::vector<unsigned char>& serializedLeaf, const PruneList* pPruneList) { // Calculate next position uint64_t position = hashFile.GetSize(); if (pPruneList != nullptr) { position += pPruneList->GetTotalShift(); } // Add in the new leaf hash const Hash leafHash = HashLeafWithIndex(serializedLeaf, position); hashFile.AddHash(leafHash); // Add parent hashes uint64_t peak = 1; while (MMRUtil::GetHeight(position + 1) > 0) { const uint64_t leftSiblingPosition = (position + 1) - (2 * peak); const Hash leftHash = GetHashAt(hashFile, leftSiblingPosition, pPruneList); const Hash rightHash = GetHashAt(hashFile, position, pPruneList); ++position; peak *= 2; const Hash parentHash = HashParentWithIndex(leftHash, rightHash, position); hashFile.AddHash(parentHash); } } Hash MMRHashUtil::Root(const HashFile& hashFile, const uint64_t size, const PruneList* pPruneList) { if (size == 0) { return ZERO_HASH; } Hash hash = ZERO_HASH; const std::vector<uint64_t> peakIndices = MMRUtil::GetPeakIndices(size); for (auto iter = peakIndices.crbegin(); iter != peakIndices.crend(); iter++) { const uint64_t shiftedIndex = GetShiftedIndex(*iter, pPruneList); Hash peakHash = hashFile.GetHashAt(shiftedIndex); if (peakHash != ZERO_HASH) { if (hash == ZERO_HASH) { hash = peakHash; } else { hash = HashParentWithIndex(peakHash, hash, size); } } } return hash; } Hash MMRHashUtil::GetHashAt(const HashFile& hashFile, const uint64_t mmrIndex, const PruneList* pPruneList) { if (pPruneList != nullptr) { if (pPruneList->IsCompacted(mmrIndex)) { return ZERO_HASH; } const uint64_t shift = pPruneList->GetShift(mmrIndex); const uint64_t shiftedIndex = (mmrIndex - shift); return hashFile.GetHashAt(shiftedIndex); } else { return hashFile.GetHashAt(mmrIndex); } } uint64_t MMRHashUtil::GetShiftedIndex(const uint64_t mmrIndex, const PruneList* pPruneList) { if (pPruneList != nullptr) { const uint64_t shift = pPruneList->GetShift(mmrIndex); return mmrIndex - shift; } else { return mmrIndex; } } std::vector<Hash> MMRHashUtil::GetLastLeafHashes(const HashFile& hashFile, const LeafSet* pLeafSet, const PruneList* pPruneList, const uint64_t numHashes) { uint64_t nextPosition = hashFile.GetSize(); if (pPruneList != nullptr) { nextPosition += pPruneList->GetTotalShift(); } std::vector<Hash> hashes; uint64_t leafIndex = MMRUtil::GetNumNodes(nextPosition); while (leafIndex > 0 && hashes.size() < numHashes) { --leafIndex; const uint64_t mmrIndex = MMRUtil::GetPMMRIndex(leafIndex); if (pLeafSet == nullptr || pLeafSet->Contains(mmrIndex)) { Hash hash = GetHashAt(hashFile, mmrIndex, pPruneList); if (hash != ZERO_HASH) { hashes.emplace_back(std::move(hash)); } } } return hashes; } Hash MMRHashUtil::HashLeafWithIndex(const std::vector<unsigned char>& serializedLeaf, const uint64_t mmrIndex) { Serializer hashSerializer; hashSerializer.Append<uint64_t>(mmrIndex); hashSerializer.AppendByteVector(serializedLeaf); return Crypto::Blake2b(hashSerializer.GetBytes()); } Hash MMRHashUtil::HashParentWithIndex(const Hash& leftChild, const Hash& rightChild, const uint64_t parentIndex) { Serializer serializer; serializer.Append<uint64_t>(parentIndex); serializer.AppendBigInteger<32>(leftChild); serializer.AppendBigInteger<32>(rightChild); return Crypto::Blake2b(serializer.GetBytes()); }
8dbe87db8aafeae34c1dbff9c3857d0006a470ed
1dae9a0fb62f77cb2256877991323fbb42efc6a6
/Greedy/2217_rope.cpp
24e4504e35a341d07813ff2e3ca9bac5e1468912
[]
no_license
zittoooo/Algorithm
629f43e4a7a5dcc6e6979a405cb24b8240efeb27
cde05a5c53e17eada4e7aaed108e10baea35d8a0
refs/heads/master
2023-02-21T08:03:13.917685
2023-02-11T12:08:45
2023-02-11T12:08:45
242,290,448
2
0
null
null
null
null
UTF-8
C++
false
false
482
cpp
2217_rope.cpp
#include <iostream> #include <algorithm> using namespace std; int n, rope[100005], res[100005]; bool desc(int a, int b) { return a < b; } int main() { cin >> n; for (int i = 0; i < n ; i++) cin >> rope[i]; sort(rope, rope+n, greater<int>()); // for (int i = 0; i < n ; i++) // cout << rope[i] << ' '; // cout <<'\n'; for (int i = 1; i <= n ; i++) { res[i-1] = rope[i-1] * i; } cout << *max_element(res, res+n); }
1af172a63a228d99f24df6c22a7cb540a4ac871b
0f2b08b31fab269c77d4b14240b8746a3ba17d5e
/onnxruntime/core/providers/cuda/tensor/nonzero_impl.h
baa988831aba0d8546465ea02712fd8d0fd0290d
[ "MIT" ]
permissive
microsoft/onnxruntime
f75aa499496f4d0a07ab68ffa589d06f83b7db1d
5e747071be882efd6b54d7a7421042e68dcd6aff
refs/heads/main
2023-09-04T03:14:50.888927
2023-09-02T07:16:28
2023-09-02T07:16:28
156,939,672
9,912
2,451
MIT
2023-09-14T21:22:46
2018-11-10T02:22:53
C++
UTF-8
C++
false
false
1,180
h
nonzero_impl.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <stdint.h> #include "core/providers/cuda/shared_inc/cuda_utils.h" namespace onnxruntime { namespace cuda { int NonZeroCalcBlockCount(int64_t x_size); cudaError_t NonZeroCalcPrefixSumTempStorageBytes(cudaStream_t stream, int* prefix_counts, int number_of_blocks, size_t&); cudaError_t NonZeroInclusivePrefixSum(cudaStream_t stream, void* d_temp_storage, size_t temp_storage_bytes, int* prefix_counts, int number_of_blocks); // count nonzero elements in each block into counts_in_blocks, // the counts_in_blocks buffer is pre-allocated on gpu first. template <typename InputT> cudaError_t NonZeroCountEachBlock(cudaStream_t stream, const InputT* x, int64_t x_size, int* counts_in_blocks); // output nonzero positions using input x and prefix_counts for each blocks template <typename InputT> cudaError_t NonZeroOutputPositions( cudaStream_t stream, const InputT* x, int64_t x_size, int x_rank, const TArray<fast_divmod>& x_strides, const int* prefix_counts, int nonzero_elements, int64_t* results); } // namespace cuda } // namespace onnxruntime
95c87ab1caaa8a32e4adcd56c326c870ad4f141c
ffcd4f1e5738e7b1d4afffb0a8813c49ad3b4fc3
/Hect/Source/IO/DataReader.h
0661e00f8d63634e9aa05c293b6e5a932865e670
[ "MIT" ]
permissive
colinhect/hect-old
eb6a83af5bc19b641c5882147522b8d05f3e4b50
5ee7429294f6ab8f40c7ff0eccba52fafa3086b3
refs/heads/master
2015-08-09T11:21:18.621812
2014-01-16T04:39:17
2014-01-16T04:39:17
14,322,838
1
0
null
null
null
null
UTF-8
C++
false
false
7,349
h
DataReader.h
/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2014 Colin Hill // // 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. /////////////////////////////////////////////////////////////////////////////// #pragma once namespace hect { /// /// An interface for reading hierarchical data. class DataReader { public: virtual ~DataReader() { } /// /// Begins an unnamed object. /// /// \throws Error If the current value is not an array. virtual void beginObject() = 0; /// /// Begins a named object. /// /// \returns Whether an object with the given name was found as a member /// of the current value. /// /// \param name The name of the object. /// /// \throws Error If the current value is not an object. virtual bool beginObject(const char* name) = 0; /// /// Ends the current object. /// /// \throws Error If the current value is not an object. virtual void endObject() = 0; /// /// Begins a named array. /// /// \param name The name of the array. /// /// \returns Whether an array with the given name was found as a member /// of the current value. /// /// \throws Error If the current value is not an object. virtual bool beginArray(const char* name) = 0; /// /// Ends the current array. /// /// \returns True if the end of the array was reached; false otherwise. /// /// \throws Error If the current value is not an array. virtual bool endArray() = 0; /// /// Returns whether or not there is a member of the current value of a /// given name. /// /// \throws Error If the current value is not an object. virtual bool hasMember(const char* name) = 0; /// /// Reads an unnamed double. /// /// \returns The read value. /// /// \throw Error If the current value is not an array. virtual double readDouble() = 0; /// /// Reads a named double. /// /// \param name The member name of the value to read. /// /// \returns The read value. /// /// \throw Error If the current value is not an object. virtual double readDouble(const char* name) = 0; /// /// Reads an unnamed string. /// /// \returns The read value. /// /// \throw Error If the current value is not an array. virtual std::string readString() = 0; /// /// Reads a named string. /// /// \param name The member name of the value to read. /// /// \returns The read value. /// /// \throw Error If the current value is not an object. virtual std::string readString(const char* name) = 0; /// /// Reads an unnamed 2-dimensional vector. /// /// \returns The read value. /// /// \throw Error If the current value is not an array. virtual Vector2<> readVector2() = 0; /// /// Reads a named 2-dimensional vector. /// /// \param name The member name of the value to read. /// /// \returns The read value. /// /// \throw Error If the current value is not an object virtual Vector2<> readVector2(const char* name) = 0; /// /// Reads an unnamed 3-dimensional vector. /// /// \returns The read value. /// /// \throw Error If the current value is not an array. virtual Vector3<> readVector3() = 0; /// /// Reads a named 3-dimensional vector. /// /// \param name The member name of the value to read. /// /// \returns The read value. /// /// \throw Error If the current value is not an object virtual Vector3<> readVector3(const char* name) = 0; /// /// Reads an unnamed 4-dimensional vector. /// /// \returns The read value. /// /// \throw Error If the current value is not an array. virtual Vector4<> readVector4() = 0; /// /// Reads a named 4-dimensional vector. /// /// \param name The member name of the value to read. /// /// \returns The read value. /// /// \throw Error If the current value is not an object virtual Vector4<> readVector4(const char* name) = 0; }; /// /// An implementation of DataReader for reading directly from a data value. class DataValueReader : public DataReader { public: /// /// Constructs the data value reader given the data value to read. /// /// \param dataValue The data value to read. DataValueReader(const DataValue& dataValue); void beginObject(); bool beginObject(const char* name); void endObject(); bool beginArray(const char* name); bool endArray(); bool hasMember(const char* name); double readDouble(); double readDouble(const char* name); std::string readString(); std::string readString(const char* name); Vector2<> readVector2(); Vector2<> readVector2(const char* name); Vector3<> readVector3(); Vector3<> readVector3(const char* name); Vector4<> readVector4(); Vector4<> readVector4(const char* name); private: const DataValue& _read(); const DataValue& _read(const char* name); size_t _elementIndex; std::stack<DataValue> _valueStack; }; /// /// An implementation of DataReader for reading from a binary stream. /// /// \remarks This implementation does not throw the exceptions described /// in the DataReader documentation for performance reasons. class BinaryDataReader : public DataReader { public: /// /// Constructs a binary data reader given the stream to read from. /// /// \param stream The stream to read from. BinaryDataReader(ReadStream& stream); void beginObject(); bool beginObject(const char* name); void endObject(); bool beginArray(const char* name); bool endArray(); bool hasMember(const char* name); double readDouble(); double readDouble(const char* name); std::string readString(); std::string readString(const char* name); Vector2<> readVector2(); Vector2<> readVector2(const char* name); Vector3<> readVector3(); Vector3<> readVector3(const char* name); Vector4<> readVector4(); Vector4<> readVector4(const char* name); private: unsigned _elementIndex; unsigned _elementCount; ReadStream* _stream; }; }
36860b717e7280799f90d8f7a3f646f4a456202e
bafb6ce3df578a2964d4f53e8a271c826267f7d8
/src/ray/raylet/raylet.h
5080e07301754fd8a06fecaf88852b5cdd7becb3
[ "MIT", "Apache-2.0" ]
permissive
adgirish/ray
b5c4aacce0aae92301036530be4345b9e13121e0
ea172f025bddfc47f2fcaed3c014432ca4f8f21b
refs/heads/master
2021-04-09T13:21:10.778833
2018-03-13T07:04:13
2018-03-13T07:04:13
124,731,449
0
0
Apache-2.0
2018-04-06T06:24:20
2018-03-11T06:54:15
Python
UTF-8
C++
false
false
2,458
h
raylet.h
#ifndef RAY_RAYLET_RAYLET_H #define RAY_RAYLET_RAYLET_H #include <list> #include <boost/asio.hpp> #include <boost/asio/error.hpp> // clang-format off #include "ray/raylet/node_manager.h" #include "ray/object_manager/object_manager.h" #include "ray/raylet/scheduling_resources.h" // clang-format on namespace ray { class Task; class NodeManager; // TODO(swang): Rename class and source files to Raylet. class Raylet { public: /// Create a node manager server and listen for new clients. /// /// \param io_service The event loop to run the server on. /// \param socket_name The Unix domain socket to listen on for local clients. /// \param resource_config The initial set of resources to start the local /// scheduler with. /// \param object_manager_config Configuration to initialize the object /// manager. /// \param gcs_client A client connection to the GCS. Raylet(boost::asio::io_service &io_service, const std::string &socket_name, const ResourceSet &resource_config, const ObjectManagerConfig &object_manager_config, std::shared_ptr<ray::GcsClient> gcs_client); /// Destroy the NodeServer. ~Raylet(); // TODO(melih): Get rid of this method. ObjectManager &GetObjectManager(); private: /// Register GCS client. ClientID RegisterGcs(); /// Accept a client connection. void DoAccept(); /// Handle an accepted client connection. void HandleAccept(const boost::system::error_code &error); /// Accept a tcp client connection. void DoAcceptTcp(); /// Handle an accepted tcp client connection. void HandleAcceptTcp(TCPClientConnection::pointer new_connection, const boost::system::error_code &error); /// An acceptor for new clients. boost::asio::local::stream_protocol::acceptor acceptor_; /// The socket to listen on for new clients. boost::asio::local::stream_protocol::socket socket_; /// An acceptor for new tcp clients. boost::asio::ip::tcp::acceptor tcp_acceptor_; /// The socket to listen on for new tcp clients. boost::asio::ip::tcp::socket tcp_socket_; // TODO(swang): Lineage cache. /// Manages client requests for object transfers and availability. ObjectManager object_manager_; /// Manages client requests for task submission and execution. NodeManager node_manager_; /// A client connection to the GCS. std::shared_ptr<ray::GcsClient> gcs_client_; }; } // namespace ray #endif // RAY_RAYLET_RAYLET_H
ac918b2c92222d7b5a5596afb9b98e04765ec7cb
ebc5e13e1a88de8479649734c7244d3fa62c5bd0
/evaluator/ajobs/10/sources/9_Gabor_Alex_02.cpp
4c554ae36abbad99d71769cb580264a3592315d0
[]
no_license
msorins/IronCoders
9a1c84e20bca78a5f00ca02785f3617100749964
910713d6cfebeab2d88c19120a21238f17f3ff7f
refs/heads/master
2021-01-23T08:29:12.189949
2019-02-24T09:35:37
2019-02-24T09:35:37
102,522,229
1
0
null
null
null
null
UTF-8
C++
false
false
525
cpp
9_Gabor_Alex_02.cpp
#include <iostream> #include <fstream> using namespace std; int main() {int MAX,save,k=0,N,v[1000],i=1,j=1; ofstream in("trenuri.in"); ofstream out("trenuri.out"); ofstream ex("Explicatii"); cout<<"Introduceti numarul de vagoane(mai mare decat 2) disponibile:"; cin>>N; in<<N; MAX=N; save=N; while(N>=i){ cout<<"Introduceti numarul de identificare al vagonului "<<i<<endl; cin>>v[i]; in<<v[i]<<" "; i++; } N=save; while(N>=j){ if(v[j]%10==0 && v[j]!=2) MAX=MAX-1; j++; } out<<MAX; return 0; }
f6eddd46ce208fa4bed5b16e1c3cb6d4c76adc15
cee6866afc2f9a87a58826897d396ae8fde2c24b
/Skynet/Skynet_v1/Skynet_v1/Source.cpp
f0537782698a302f462ca2f79d12ebc39673056c
[]
no_license
Armando0102/Skynet_v1
77eb2e38d5613507f8b9d427e012c049f635d865
3267638ed5884b7bdb6490c9bab398c80344f427
refs/heads/master
2020-04-20T14:58:06.002830
2019-02-03T06:24:11
2019-02-03T06:24:11
168,915,099
0
0
null
null
null
null
UTF-8
C++
false
false
1,678
cpp
Source.cpp
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; void main() { srand(static_cast<unsigned int>(time(0))); int randomNumber = rand(); int enemyLocation = ((randomNumber % 8) + 1) * 8; int ping = 1; int searchHighNum = 64; int searchLowNum = 0; int targetPrediction = ((searchHighNum - searchLowNum) / 2) + searchLowNum; bool found = false; cout << "Generate Random enemy location on 8x8 grid.....\nThe enemy is located at location #" << enemyLocation << " on grid\nInitializing Skynet HK-Aerial software....." << endl; while (found == false) { cout << "----------------------------------------------------\nSkynet HK-Aerial Radar sending out ping #" << ping << endl; if (targetPrediction < enemyLocation) { searchLowNum = targetPrediction + 1; ping++; cout << "The target location prediction of " << targetPrediction << " was lower than enemy location of " << enemyLocation << endl; targetPrediction = ((searchHighNum - searchLowNum) / 2) + searchLowNum; } else if (targetPrediction > enemyLocation) { searchLowNum = targetPrediction - 1; ping++; cout << "The target location prediction of " << targetPrediction << " was higher than enemy location of " << enemyLocation << endl; targetPrediction = ((searchHighNum + searchLowNum) / 2) - searchLowNum; } else if (targetPrediction == enemyLocation) { cout << "The enemy was hiding at location #" << enemyLocation << "\nTarget was found at location #" << targetPrediction << "\nSkynet HK-Aerial Software took " << ping << " predictions to find enemy" << endl; system("pause"); found = true; } } }
e40f8bbaa9f501fc9bfb391e3a12d3d7106df45a
a2206795a05877f83ac561e482e7b41772b22da8
/Source/PV/build/VTK/Wrapping/Python/vtkSMParaViewPipelineControllerWithRenderingPython.cxx
35838fa2114255d40003d6641f636fbb4908acad
[]
no_license
supreethms1809/mpas-insitu
5578d465602feb4d6b239a22912c33918c7bb1c3
701644bcdae771e6878736cb6f49ccd2eb38b36e
refs/heads/master
2020-03-25T16:47:29.316814
2018-08-08T02:00:13
2018-08-08T02:00:13
143,947,446
0
0
null
null
null
null
UTF-8
C++
false
false
26,847
cxx
vtkSMParaViewPipelineControllerWithRenderingPython.cxx
// python wrapper for vtkSMParaViewPipelineControllerWithRendering // #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include "vtkPythonArgs.h" #include "vtkPythonOverload.h" #include "vtkConfigure.h" #include <vtksys/ios/sstream> #include "vtkIndent.h" #include "vtkSMParaViewPipelineControllerWithRendering.h" #if defined(VTK_BUILD_SHARED_LIBS) # define VTK_PYTHON_EXPORT VTK_ABI_EXPORT # define VTK_PYTHON_IMPORT VTK_ABI_IMPORT #else # define VTK_PYTHON_EXPORT VTK_ABI_EXPORT # define VTK_PYTHON_IMPORT VTK_ABI_EXPORT #endif extern "C" { VTK_PYTHON_EXPORT void PyVTKAddFile_vtkSMParaViewPipelineControllerWithRendering(PyObject *, const char *); } extern "C" { VTK_PYTHON_EXPORT PyObject *PyVTKClass_vtkSMParaViewPipelineControllerWithRenderingNew(const char *); } #ifndef DECLARED_PyVTKClass_vtkSMParaViewPipelineControllerNew extern "C" { PyObject *PyVTKClass_vtkSMParaViewPipelineControllerNew(const char *); } #define DECLARED_PyVTKClass_vtkSMParaViewPipelineControllerNew #endif static const char **PyvtkSMParaViewPipelineControllerWithRendering_Doc(); static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_GetClassName(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "GetClassName"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); PyObject *result = NULL; if (op && ap.CheckArgCount(0)) { const char *tempr = (ap.IsBound() ? op->GetClassName() : op->vtkSMParaViewPipelineControllerWithRendering::GetClassName()); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_IsA(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "IsA"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); char *temp0 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(1) && ap.GetValue(temp0)) { int tempr = (ap.IsBound() ? op->IsA(temp0) : op->vtkSMParaViewPipelineControllerWithRendering::IsA(temp0)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_NewInstance(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "NewInstance"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); PyObject *result = NULL; if (op && ap.CheckArgCount(0)) { vtkSMParaViewPipelineControllerWithRendering *tempr = (ap.IsBound() ? op->NewInstance() : op->vtkSMParaViewPipelineControllerWithRendering::NewInstance()); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); if (result && PyVTKObject_Check(result)) { PyVTKObject_GetObject(result)->UnRegister(0); PyVTKObject_SetFlag(result, VTK_PYTHON_IGNORE_UNREGISTER, 1); } } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_SafeDownCast(PyObject *, PyObject *args) { vtkPythonArgs ap(args, "SafeDownCast"); vtkObject *temp0 = NULL; PyObject *result = NULL; if (ap.CheckArgCount(1) && ap.GetVTKObject(temp0, "vtkObject")) { vtkSMParaViewPipelineControllerWithRendering *tempr = vtkSMParaViewPipelineControllerWithRendering::SafeDownCast(temp0); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_Show(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "Show"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMSourceProxy *temp0 = NULL; int temp1; vtkSMViewProxy *temp2 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(3) && ap.GetVTKObject(temp0, "vtkSMSourceProxy") && ap.GetValue(temp1) && ap.GetVTKObject(temp2, "vtkSMViewProxy")) { vtkSMProxy *tempr = (ap.IsBound() ? op->Show(temp0, temp1, temp2) : op->vtkSMParaViewPipelineControllerWithRendering::Show(temp0, temp1, temp2)); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_Hide_s1(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "Hide"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMSourceProxy *temp0 = NULL; int temp1; vtkSMViewProxy *temp2 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(3) && ap.GetVTKObject(temp0, "vtkSMSourceProxy") && ap.GetValue(temp1) && ap.GetVTKObject(temp2, "vtkSMViewProxy")) { vtkSMProxy *tempr = (ap.IsBound() ? op->Hide(temp0, temp1, temp2) : op->vtkSMParaViewPipelineControllerWithRendering::Hide(temp0, temp1, temp2)); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_Hide_s2(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "Hide"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMProxy *temp0 = NULL; vtkSMViewProxy *temp1 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(2) && ap.GetVTKObject(temp0, "vtkSMProxy") && ap.GetVTKObject(temp1, "vtkSMViewProxy")) { if (ap.IsBound()) { op->Hide(temp0, temp1); } else { op->vtkSMParaViewPipelineControllerWithRendering::Hide(temp0, temp1); } if (!ap.ErrorOccurred()) { result = ap.BuildNone(); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_Hide(PyObject *self, PyObject *args) { int nargs = vtkPythonArgs::GetArgCount(self, args); switch(nargs) { case 3: return PyvtkSMParaViewPipelineControllerWithRendering_Hide_s1(self, args); case 2: return PyvtkSMParaViewPipelineControllerWithRendering_Hide_s2(self, args); } vtkPythonArgs::ArgCountError(nargs, "Hide"); return NULL; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_SetVisibility(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "SetVisibility"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMSourceProxy *temp0 = NULL; int temp1; vtkSMViewProxy *temp2 = NULL; bool temp3 = false; PyObject *result = NULL; if (op && ap.CheckArgCount(4) && ap.GetVTKObject(temp0, "vtkSMSourceProxy") && ap.GetValue(temp1) && ap.GetVTKObject(temp2, "vtkSMViewProxy") && ap.GetValue(temp3)) { vtkSMProxy *tempr = (ap.IsBound() ? op->SetVisibility(temp0, temp1, temp2, temp3) : op->vtkSMParaViewPipelineControllerWithRendering::SetVisibility(temp0, temp1, temp2, temp3)); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_GetVisibility(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "GetVisibility"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMSourceProxy *temp0 = NULL; int temp1; vtkSMViewProxy *temp2 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(3) && ap.GetVTKObject(temp0, "vtkSMSourceProxy") && ap.GetValue(temp1) && ap.GetVTKObject(temp2, "vtkSMViewProxy")) { bool tempr = (ap.IsBound() ? op->GetVisibility(temp0, temp1, temp2) : op->vtkSMParaViewPipelineControllerWithRendering::GetVisibility(temp0, temp1, temp2)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_ShowInPreferredView(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "ShowInPreferredView"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMSourceProxy *temp0 = NULL; int temp1; vtkSMViewProxy *temp2 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(3) && ap.GetVTKObject(temp0, "vtkSMSourceProxy") && ap.GetValue(temp1) && ap.GetVTKObject(temp2, "vtkSMViewProxy")) { vtkSMViewProxy *tempr = (ap.IsBound() ? op->ShowInPreferredView(temp0, temp1, temp2) : op->vtkSMParaViewPipelineControllerWithRendering::ShowInPreferredView(temp0, temp1, temp2)); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_GetPreferredViewType(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "GetPreferredViewType"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMSourceProxy *temp0 = NULL; int temp1; PyObject *result = NULL; if (op && ap.CheckArgCount(2) && ap.GetVTKObject(temp0, "vtkSMSourceProxy") && ap.GetValue(temp1)) { const char *tempr = (ap.IsBound() ? op->GetPreferredViewType(temp0, temp1) : op->vtkSMParaViewPipelineControllerWithRendering::GetPreferredViewType(temp0, temp1)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_RegisterRepresentationProxy(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "RegisterRepresentationProxy"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMProxy *temp0 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(1) && ap.GetVTKObject(temp0, "vtkSMProxy")) { bool tempr = (ap.IsBound() ? op->RegisterRepresentationProxy(temp0) : op->vtkSMParaViewPipelineControllerWithRendering::RegisterRepresentationProxy(temp0)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_SetHideScalarBarOnHide(PyObject *, PyObject *args) { vtkPythonArgs ap(args, "SetHideScalarBarOnHide"); bool temp0 = false; PyObject *result = NULL; if (ap.CheckArgCount(1) && ap.GetValue(temp0)) { vtkSMParaViewPipelineControllerWithRendering::SetHideScalarBarOnHide(temp0); if (!ap.ErrorOccurred()) { result = ap.BuildNone(); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_SetInheritRepresentationProperties(PyObject *, PyObject *args) { vtkPythonArgs ap(args, "SetInheritRepresentationProperties"); bool temp0 = false; PyObject *result = NULL; if (ap.CheckArgCount(1) && ap.GetValue(temp0)) { vtkSMParaViewPipelineControllerWithRendering::SetInheritRepresentationProperties(temp0); if (!ap.ErrorOccurred()) { result = ap.BuildNone(); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_GetInheritRepresentationProperties(PyObject *, PyObject *args) { vtkPythonArgs ap(args, "GetInheritRepresentationProperties"); PyObject *result = NULL; if (ap.CheckArgCount(0)) { bool tempr = vtkSMParaViewPipelineControllerWithRendering::GetInheritRepresentationProperties(); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_WriteImage_s1(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "WriteImage"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMViewProxy *temp0 = NULL; char *temp1 = NULL; int temp2; int temp3; PyObject *result = NULL; if (op && ap.CheckArgCount(4) && ap.GetVTKObject(temp0, "vtkSMViewProxy") && ap.GetValue(temp1) && ap.GetValue(temp2) && ap.GetValue(temp3)) { bool tempr = (ap.IsBound() ? op->WriteImage(temp0, temp1, temp2, temp3) : op->vtkSMParaViewPipelineControllerWithRendering::WriteImage(temp0, temp1, temp2, temp3)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_WriteImage_s2(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "WriteImage"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMViewLayoutProxy *temp0 = NULL; char *temp1 = NULL; int temp2; int temp3; PyObject *result = NULL; if (op && ap.CheckArgCount(4) && ap.GetVTKObject(temp0, "vtkSMViewLayoutProxy") && ap.GetValue(temp1) && ap.GetValue(temp2) && ap.GetValue(temp3)) { bool tempr = (ap.IsBound() ? op->WriteImage(temp0, temp1, temp2, temp3) : op->vtkSMParaViewPipelineControllerWithRendering::WriteImage(temp0, temp1, temp2, temp3)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyMethodDef PyvtkSMParaViewPipelineControllerWithRendering_WriteImage_Methods[] = { {NULL, PyvtkSMParaViewPipelineControllerWithRendering_WriteImage_s1, METH_VARARGS, (char*)"@Ozii *vtkSMViewProxy"}, {NULL, PyvtkSMParaViewPipelineControllerWithRendering_WriteImage_s2, METH_VARARGS, (char*)"@Ozii *vtkSMViewLayoutProxy"}, {NULL, NULL, 0, NULL} }; static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_WriteImage(PyObject *self, PyObject *args) { PyMethodDef *methods = PyvtkSMParaViewPipelineControllerWithRendering_WriteImage_Methods; int nargs = vtkPythonArgs::GetArgCount(self, args); switch(nargs) { case 4: return vtkPythonOverload::CallMethod(methods, self, args); } vtkPythonArgs::ArgCountError(nargs, "WriteImage"); return NULL; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_PostInitializeProxy(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "PostInitializeProxy"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMProxy *temp0 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(1) && ap.GetVTKObject(temp0, "vtkSMProxy")) { bool tempr = (ap.IsBound() ? op->PostInitializeProxy(temp0) : op->vtkSMParaViewPipelineControllerWithRendering::PostInitializeProxy(temp0)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_RegisterViewProxy(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "RegisterViewProxy"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMProxy *temp0 = NULL; char *temp1 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(2) && ap.GetVTKObject(temp0, "vtkSMProxy") && ap.GetValue(temp1)) { bool tempr = (ap.IsBound() ? op->RegisterViewProxy(temp0, temp1) : op->vtkSMParaViewPipelineControllerWithRendering::RegisterViewProxy(temp0, temp1)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkSMParaViewPipelineControllerWithRendering_RegisterLayoutProxy(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "RegisterLayoutProxy"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkSMParaViewPipelineControllerWithRendering *op = static_cast<vtkSMParaViewPipelineControllerWithRendering *>(vp); vtkSMProxy *temp0 = NULL; char *temp1 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(1, 2) && ap.GetVTKObject(temp0, "vtkSMProxy") && (ap.NoArgsLeft() || ap.GetValue(temp1))) { bool tempr = (ap.IsBound() ? op->RegisterLayoutProxy(temp0, temp1) : op->vtkSMParaViewPipelineControllerWithRendering::RegisterLayoutProxy(temp0, temp1)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyMethodDef PyvtkSMParaViewPipelineControllerWithRendering_Methods[] = { {(char*)"GetClassName", PyvtkSMParaViewPipelineControllerWithRendering_GetClassName, METH_VARARGS, (char*)"V.GetClassName() -> string\nC++: const char *GetClassName()\n\n"}, {(char*)"IsA", PyvtkSMParaViewPipelineControllerWithRendering_IsA, METH_VARARGS, (char*)"V.IsA(string) -> int\nC++: int IsA(const char *name)\n\n"}, {(char*)"NewInstance", PyvtkSMParaViewPipelineControllerWithRendering_NewInstance, METH_VARARGS, (char*)"V.NewInstance() -> vtkSMParaViewPipelineControllerWithRendering\nC++: vtkSMParaViewPipelineControllerWithRendering *NewInstance()\n\n"}, {(char*)"SafeDownCast", PyvtkSMParaViewPipelineControllerWithRendering_SafeDownCast, METH_VARARGS | METH_STATIC, (char*)"V.SafeDownCast(vtkObject)\n -> vtkSMParaViewPipelineControllerWithRendering\nC++: vtkSMParaViewPipelineControllerWithRendering *SafeDownCast(\n vtkObject* o)\n\n"}, {(char*)"Show", PyvtkSMParaViewPipelineControllerWithRendering_Show, METH_VARARGS, (char*)"V.Show(vtkSMSourceProxy, int, vtkSMViewProxy) -> vtkSMProxy\nC++: virtual vtkSMProxy *Show(vtkSMSourceProxy *producer,\n int outputPort, vtkSMViewProxy *view)\n\nShow the output data in the view. If data cannot be shown in the\nview, returns NULL. If view is NULL, this simply calls\nShowInPreferredView().\n"}, {(char*)"Hide", PyvtkSMParaViewPipelineControllerWithRendering_Hide, METH_VARARGS, (char*)"V.Hide(vtkSMSourceProxy, int, vtkSMViewProxy) -> vtkSMProxy\nC++: virtual vtkSMProxy *Hide(vtkSMSourceProxy *producer,\n int outputPort, vtkSMViewProxy *view)\nV.Hide(vtkSMProxy, vtkSMViewProxy)\nC++: virtual void Hide(vtkSMProxy *repr, vtkSMViewProxy *view)\n\nOpposite of Show(). Locates the representation for the producer\nand then hides it, if found. Returns that representation, if\nfound.\n"}, {(char*)"SetVisibility", PyvtkSMParaViewPipelineControllerWithRendering_SetVisibility, METH_VARARGS, (char*)"V.SetVisibility(vtkSMSourceProxy, int, vtkSMViewProxy, bool)\n -> vtkSMProxy\nC++: vtkSMProxy *SetVisibility(vtkSMSourceProxy *producer,\n int outputPort, vtkSMViewProxy *view, bool visible)\n\nAlternative method to call Show and Hide using a visibility flag.\n"}, {(char*)"GetVisibility", PyvtkSMParaViewPipelineControllerWithRendering_GetVisibility, METH_VARARGS, (char*)"V.GetVisibility(vtkSMSourceProxy, int, vtkSMViewProxy) -> bool\nC++: virtual bool GetVisibility(vtkSMSourceProxy *producer,\n int outputPort, vtkSMViewProxy *view)\n\nReturns whether the producer/port are shown in the given view.\n"}, {(char*)"ShowInPreferredView", PyvtkSMParaViewPipelineControllerWithRendering_ShowInPreferredView, METH_VARARGS, (char*)"V.ShowInPreferredView(vtkSMSourceProxy, int, vtkSMViewProxy)\n -> vtkSMViewProxy\nC++: virtual vtkSMViewProxy *ShowInPreferredView(\n vtkSMSourceProxy *producer, int outputPort,\n vtkSMViewProxy *view)\n\nSame as Show() except that if the view is NULL or not the\n\"preferred\" view for the producer's output, this method will\ncreate a new view and show the data in that new view. Returns the\nview in which the data ends up being shown, if any. It may return\nNULL if the view is not the \"preferred\" view and \"preferred\" view\ncould not be determined or created.\n"}, {(char*)"GetPreferredViewType", PyvtkSMParaViewPipelineControllerWithRendering_GetPreferredViewType, METH_VARARGS, (char*)"V.GetPreferredViewType(vtkSMSourceProxy, int) -> string\nC++: virtual const char *GetPreferredViewType(\n vtkSMSourceProxy *producer, int outputPort)\n\nReturns the name for the preferred view type, if there is any.\n"}, {(char*)"RegisterRepresentationProxy", PyvtkSMParaViewPipelineControllerWithRendering_RegisterRepresentationProxy, METH_VARARGS, (char*)"V.RegisterRepresentationProxy(vtkSMProxy) -> bool\nC++: virtual bool RegisterRepresentationProxy(vtkSMProxy *proxy)\n\nOverridden to create color and opacity transfer functions if\napplicable. While it is tempting to add any default property\nsetup logic in such overrides, we must keep such overrides to a\nminimal and opting for domains that set appropriate defaults\nwhere as much as possible.\n"}, {(char*)"SetHideScalarBarOnHide", PyvtkSMParaViewPipelineControllerWithRendering_SetHideScalarBarOnHide, METH_VARARGS | METH_STATIC, (char*)"V.SetHideScalarBarOnHide(bool)\nC++: static void SetHideScalarBarOnHide(bool)\n\nControl how scalar bar visibility is updated by the Hide call.\n"}, {(char*)"SetInheritRepresentationProperties", PyvtkSMParaViewPipelineControllerWithRendering_SetInheritRepresentationProperties, METH_VARARGS | METH_STATIC, (char*)"V.SetInheritRepresentationProperties(bool)\nC++: static void SetInheritRepresentationProperties(bool)\n\nControl whether representations try to maintain properties from\nan input representation, if present. e.g. if you \"Transform\" the\nrepresentation for a source, then any filter that you connect to\nit should be transformed as well.\n"}, {(char*)"GetInheritRepresentationProperties", PyvtkSMParaViewPipelineControllerWithRendering_GetInheritRepresentationProperties, METH_VARARGS | METH_STATIC, (char*)"V.GetInheritRepresentationProperties() -> bool\nC++: static bool GetInheritRepresentationProperties()\n\nControl whether representations try to maintain properties from\nan input representation, if present. e.g. if you \"Transform\" the\nrepresentation for a source, then any filter that you connect to\nit should be transformed as well.\n"}, {(char*)"WriteImage", PyvtkSMParaViewPipelineControllerWithRendering_WriteImage, METH_VARARGS, (char*)"V.WriteImage(vtkSMViewProxy, string, int, int) -> bool\nC++: virtual bool WriteImage(vtkSMViewProxy *view,\n const char *filename, int magnification, int quality)\nV.WriteImage(vtkSMViewLayoutProxy, string, int, int) -> bool\nC++: virtual bool WriteImage(vtkSMViewLayoutProxy *layout,\n const char *filename, int magnification, int quality)\n\nMethods to save/capture images from views.\n"}, {(char*)"PostInitializeProxy", PyvtkSMParaViewPipelineControllerWithRendering_PostInitializeProxy, METH_VARARGS, (char*)"V.PostInitializeProxy(vtkSMProxy) -> bool\nC++: virtual bool PostInitializeProxy(vtkSMProxy *proxy)\n\nOverridden to handle default ColorArrayName for representations\ncorrectly.\n"}, {(char*)"RegisterViewProxy", PyvtkSMParaViewPipelineControllerWithRendering_RegisterViewProxy, METH_VARARGS, (char*)"V.RegisterViewProxy(vtkSMProxy, string) -> bool\nC++: virtual bool RegisterViewProxy(vtkSMProxy *proxy,\n const char *proxyname)\n\nOverridden to place the view in a layout on creation.\n"}, {(char*)"RegisterLayoutProxy", PyvtkSMParaViewPipelineControllerWithRendering_RegisterLayoutProxy, METH_VARARGS, (char*)"V.RegisterLayoutProxy(vtkSMProxy, string) -> bool\nC++: virtual bool RegisterLayoutProxy(vtkSMProxy *proxy,\n const char *proxyname=NULL)\n\nRegister layout proxy.\n"}, {NULL, NULL, 0, NULL} }; static vtkObjectBase *PyvtkSMParaViewPipelineControllerWithRendering_StaticNew() { return vtkSMParaViewPipelineControllerWithRendering::New(); } PyObject *PyVTKClass_vtkSMParaViewPipelineControllerWithRenderingNew(const char *modulename) { PyObject *cls = PyVTKClass_New(&PyvtkSMParaViewPipelineControllerWithRendering_StaticNew, PyvtkSMParaViewPipelineControllerWithRendering_Methods, "vtkSMParaViewPipelineControllerWithRendering", modulename, NULL, NULL, PyvtkSMParaViewPipelineControllerWithRendering_Doc(), PyVTKClass_vtkSMParaViewPipelineControllerNew(modulename)); return cls; } const char **PyvtkSMParaViewPipelineControllerWithRendering_Doc() { static const char *docstring[] = { "vtkSMParaViewPipelineControllerWithRendering\n\n", "Superclass: vtkSMParaViewPipelineController\n\n", "vtkSMParaViewPipelineControllerWithRendering overrides\nvtkSMParaViewPipelineController to add support for initializing\nrendering proxies appropriately.\nvtkSMParaViewPipelineControllerWithRendering uses vtkObjectFactory\nmechanisms to override vtkSMParaViewPipelineController's creation.\nOne should not need to create or use this class directly (excepting\nwhen needing to subclass). Simply create\nvtkSM", "ParaViewPipelineController. If the application is linked with\nthe rendering module, then this class will be instantiated instead of\nvtkSMParaViewPipelineController automatically.\n\nvtkSMParaViewPipelineControllerWithRendering also adds new API to\ncontrol representation visibility and manage creation of views. To\nuse that API clients can instantiate\nvtkSMParaViewPipelineControllerWithRendering. Just", " like\nvtkSMParaViewPipelineController, this class also uses\nvtkObjectFactory mechanisms to enable overriding by clients at\ncompile time.\n\n", NULL }; return docstring; } void PyVTKAddFile_vtkSMParaViewPipelineControllerWithRendering( PyObject *dict, const char *modulename) { PyObject *o; o = PyVTKClass_vtkSMParaViewPipelineControllerWithRenderingNew(modulename); if (o && PyDict_SetItemString(dict, (char *)"vtkSMParaViewPipelineControllerWithRendering", o) != 0) { Py_DECREF(o); } }
8e60105a85dd6fc92be1c25dd16850c613c7851e
385cb811d346a4d7a285fc087a50aaced1482851
/ICPC/2020/day0/main.cpp
40533705fd2156b98f9f3593d3ae47efcbb991a5
[]
no_license
NoureldinYosri/competitive-programming
aa19f0479420d8d1b10605536e916f0f568acaec
7739344404bdf4709c69a97f61dc3c0b9deb603c
refs/heads/master
2022-11-22T23:38:12.853482
2022-11-10T20:32:28
2022-11-10T20:32:28
40,174,513
4
1
null
null
null
null
UTF-8
C++
false
false
5,969
cpp
main.cpp
#pragma GCC optimize ("O3") #include <bits/stdc++.h> #define loop(i,n) for(int i = 0;i < (n);i++) #define all(A) A.begin(),A.end() #define pb push_back #define mp make_pair #define sz(A) ((int)A.size()) typedef std::vector<int> vi; typedef std::pair<int,int> pi; typedef std::vector<pi> vp; typedef long long ll; #define popcnt(x) __builtin_popcount(x) #define LSOne(x) ((x) & (-(x))) #define print(A,t) cerr << #A << ": "; copy(all(A),ostream_iterator<t>(cerr," " )); cerr << endl #define prArr(A,n,t) cerr << #A << ": "; copy(A,A + n,ostream_iterator<t>(cerr," " )); cerr << endl #define PRESTDIO() cin.tie(0),cerr.tie(0),ios_base::sync_with_stdio(0) #define what_is(x) cerr << #x << " is " << x << endl #define bit_lg(x) (assert(x > 0),__builtin_ffsll(x) - 1) const double PI = acos(-1); template<class A,class B> std::ostream& operator << (std::ostream& st,const std::pair<A,B> p) { st << "(" << p.first << ", " << p.second << ")"; return st; } using namespace std; const int MAXITR = 5; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); using dna = vi; vector<vi> adj; int V, E; void read_graph(string fname){ freopen((fname + ".in").c_str(), "r", stdin); vp adj_list; for(int a, b; scanf("%d %d", &a, &b) == 2;){ adj_list.emplace_back(a, b); V = max(V, max(a, b)); } V++; E = adj_list.size(); cerr << "read V: " << V << ", E: " << E << endl; adj.resize(V); for(auto [a, b] : adj_list){ adj[a].push_back(b); adj[b].push_back(a); } } void canonize(dna & s){ static map<int, int> M; M.clear(); for(int & x : s){ if(M.count(x)) x = M[x]; else { int q = M.size(); x = M[x] = q; } } } double Regularization(const vector<vi> & C, const dna & s){ int n = C.size(); double R = 0; for(const vi & B : C){ if(sz(B) == 1) { R += 1; } else { int E_in = 0, m = sz(B); for(int u : B) for(int v : adj[u]) E_in += s[u] == s[v]; R += E_in/(0.5*m*(m - 1)); } } R /= n; R -= n/(double)V; R /= 2; // cerr << "Regularization " << R << endl; return R; } double Modularity(const vector<vi> & C, const dna & s) { double M = 0; for(const vi & B : C){ int E_in = 0; int sum_degree = 0; for(int v : B){ sum_degree += sz(adj[v]); for(int u : adj[v]) E_in += s[v] == s[u]; } assert(E_in%2 == 0); E_in >>= 1; M += E_in/(double)E - pow(sum_degree/(2.0 * E), 2.0); } // cerr << "Modularity " << M << endl; return M; } void dna_split(dna & s, vector<vi> & C){ canonize(s); C.clear(); C.resize(*max_element(all(s)) + 1); loop(i, sz(s)) C[s[i]].push_back(i); } double fitness(dna & s){ static vector<vi> C; dna_split(s, C); return Modularity(C, s) + Regularization(C, s); } dna create_random(int n){ static vi Q; dna s(V, 0); Q.resize(V); loop(i, V) Q[i] = i; loop(i, n) { int nt = n - i; int di = (rng()%(n - i) + nt)%nt; if(di) swap(Q[i], Q[i + di]); s[Q[i]] = i; } for(int i = n; i < V; i++) s[Q[i]] = (rng()%n + n)%n; return s; } int get_center(vi & C){ static vi D, R, visID; static queue<int> q; static int visNum = 0; if(D.empty()) { D.resize(V); R.resize(V); visID.resize(V); } visNum++; for(int v : C) D[v] = 0, visID[v] = visNum; shuffle(all(C), rng); int m = 0.01*sz(C); m = max(m, min(50, sz(C))); m = min(m, 70); // cerr << "getting center of a " << sz(C) << " block using " << m << " roots" << endl; loop(i, m){ int root = C[i]; for(int v : C) R[v] = -1; R[root] = 0; q.push(root); while(!q.empty()){ int u = q.front(); q.pop(); for(int v : adj[u]) if(visID[v] == visID[u] && R[v] == -1) { R[v] = R[u] + 1; q.push(v); } } for(int v : C) D[v] += R[v]; // cerr << "done with " << i+1 << "/" << m << endl; } int best = INT_MAX, c = C[0]; for(int v : C) { int tmp = D[v]; if(tmp < best){ best = tmp; c = v; } } return c; } vi get_centers(dna & s){ static vector<vi> C; dna_split(s, C); vi S; cerr << "get centers" << endl; int i = 0; for(auto & B : C){ S.push_back(get_center(B)); i++; cerr << "got center of block " << i << "/" << sz(C) << endl; /* shuffle(all(B), rng); int mx = 0, cent = 0; for(int v : B) { int deg = 0; for(int u : adj[v]) deg += s[u] == s[v]; if(deg > mx){ mx = deg; cent = v; } } S.push_back(cent); */ } return S; } dna bfs(const vi & S){ static vi R; static queue<int> q; R.clear(); R.resize(V, -1); loop(i, sz(S)) { int s = S[i]; R[s] = i; q.push(s); } while(!q.empty()){ int u = q.front(); q.pop(); for(int v : adj[u]) if(R[v] == -1) { R[v] = R[u]; q.push(v); } } return dna(R); } void majority(dna & s){ static vi Q, aux; if(Q.empty()) { Q.resize(V); loop(i, V) Q.push_back(i); } shuffle(all(Q), rng); for(int i : Q) { map<int, int> freq; int mx = 0; for(int j : adj[i]) { freq[s[j]]++; mx = max(mx, freq[s[j]]); } aux.clear(); for(auto [c, q] : freq) if(q == mx) aux.push_back(c); int r = aux.size(); s[i] = (rng()%r + r)%r; } } dna solve(int n){ dna s = create_random(n); for(int itr = 0; itr < MAXITR; itr++){ vi S = get_centers(s); cerr << "reassign" << endl; s = bfs(S); majority(s); } return s; } void spit(dna & s, string fname){ FILE *f = fopen((fname + ".out").c_str(), "w"); vector<vi> C; dna_split(s, C); for(auto & B : C){ for(int x : B) fprintf(f, "%d ", x); fprintf(f, "\n"); } fclose(f); } int main(int argc, char **argv){ assert(argc > 1); read_graph(string(argv[1])); dna ans = create_random(2); double best = fitness(ans); spit(ans, string(argv[1])); int r = min(V, 30); int l = min(V, 30); int W = r-l+1; int MAXI = 20; for(int itr = 0; itr < MAXI; itr++){ int k = (rng()%W + W)%W; k = l + k; dna s = solve(k); double tmp = fitness(s); if(tmp > best){ best = tmp; ans = s; } spit(ans, string(argv[1])); cerr << "after " << itr+1 << "/" << MAXI << " " << best << " score should be " << (best + 1)*1e5 << endl; } cerr << best << endl; return 0; }
2d85b2c8f985619b0e5912adf2db71b859f6551a
6b005890858ce419a324e27fdd3f17460942a1ff
/Problems(UVA_CF)/Codeforces/699B.cpp
d771709b3b77cc1124545c3f115e87de4590e6f9
[]
no_license
ragrag/Competitive-Programming-Library
3c4f164fa50a7f0e10f4bbd5566aa4afb1bf1ad1
46e419ca2489402e4947dcb4b2963d2f0c7b31ee
refs/heads/master
2021-05-01T18:50:28.684891
2019-10-01T17:52:23
2019-10-01T17:52:23
121,009,891
2
1
null
2019-10-04T15:08:34
2018-02-10T11:32:46
C++
UTF-8
C++
false
false
974
cpp
699B.cpp
#include <iostream> #include <math.h> #include <algorithm> #include <vector> #include <iomanip> #include <set> using namespace std; typedef long long ll; typedef vector <int> vi; vi dfs_num; vector <vector<int>> adj; void dfs(int u) { dfs_num[u] = 1; for (int j = 0; j < (int)adj[u].size(); j++) { int v = adj[u][j]; if (dfs_num[v] == 0) { dfs(v); } } } int main() { int r[1000]={0}; int cr[1000]={0}; vector <string> ar(1000); int n,m; cin>>n >>m; int ma=0; for (int i=0;i<n;i++) { cin>>ar[i]; for(int j=0;j<ar[i].size();j++) { if (ar[i][j]=='*') { r[i]++; cr[j]++; ma++; } } } vector <string > ar2 = ar; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int c = r[i] + cr[j]; if(ar2[i][j] == '*') c-=1; if(c== ma) { cout <<"YES"<<endl<<i+1 <<" "<<j+1<<" "<<endl; return 0; } } } cout<<"NO"<<endl; return 0; }
71e8cab808a0d458aae9b5cd5dd279f1cddbbbc4
f57902173fc586e5fb895134ea50dea735e49e0f
/IR/IR/IHasher.h
128a93976c60832e545255faa3a6683783e13de4
[]
no_license
BelfodilAimene/PDC-1---Indexation
ff26d98fd19f1e53f8263cabbb21271d790dc4bc
2995224170369ac05716886006717433d2020d07
refs/heads/master
2016-09-01T07:31:34.409957
2015-11-03T10:36:01
2015-11-03T10:36:01
45,533,485
0
0
null
null
null
null
UTF-8
C++
false
false
125
h
IHasher.h
#pragma once #include <string> using namespace std; class IHasher { public: virtual unsigned int hash(string token) = 0; };
3389e3f76bc2eb8f87d9c55093ea8476c3137dc8
cd4e3f96ce07d94b09a2434c727260fc3ab9cb14
/src/base.h
548c4157a83ae984038a9a85119b38fa7a0eb940
[ "MIT" ]
permissive
hmkum/HMK-OpenGL-Demo
afa276bc75b9db8675eb61705e1c80d0bb81ff1e
254f5814ed1c552dd0ab348cd3ab9332c9d1ef70
refs/heads/master
2021-01-20T11:21:44.257512
2021-01-07T11:57:22
2021-01-07T11:57:22
25,045,363
0
0
null
null
null
null
UTF-8
C++
false
false
262
h
base.h
#pragma once #include <cstdint> typedef std::int8_t int8; typedef std::uint8_t uint8; typedef std::int16_t int16; typedef std::uint16_t uint16; typedef std::int32_t int32; typedef std::uint32_t uint32; typedef std::int64_t int64; typedef std::uint64_t uint64;
5ffb975396c70658eaeea37c9cd16a80e8265b94
6230de1dbb9da1c9c15ea3ea32d43832ddcb3ca7
/srcs/Iterator/ForwardIterator.hpp
37921c7d74e8cb1c980588c044f9ede7a9e41605
[]
no_license
CberT-code/ft_containers
341a2dd8127185dc0aaca796d2c6369bcf9ce678
c8c87c66baac14166f2b49e2e45b940ab0e1cba4
refs/heads/master
2023-02-04T14:25:31.646502
2020-11-12T13:46:16
2020-11-12T13:46:16
306,025,136
0
0
null
null
null
null
UTF-8
C++
false
false
1,262
hpp
ForwardIterator.hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ForwardIterator.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cbertola <cbertola@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/12 11:41:17 by cbertola #+# #+# */ /* Updated: 2020/11/12 11:41:56 by cbertola ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FORWARDITERATOR_H #define FORWARDITERATOR_H #include "../Headers/Header.hpp" template <typename T> struct ForwardIterator : public InputIterator<T> { public : /************************************************** ****************** Form Coplien ******************* **************************************************/ ForwardIterator(void){} }; #endif
5050862564a5d64b2367da6fada5d2759d9510dd
7388b64516208c6a7b03bba6700eac5515dfe048
/SeedStoreScene/SeedStoreScene.hpp
1bc8d629afac5f0102b883e11c5b4a9ad4983f5b
[]
no_license
Wenjin186/Classes
a055d81a8fa97d5d9c8a9927d64947e7fcaa1180
493ef06e63f4d47fbad404d6fb510cfbab70529d
refs/heads/master
2020-12-03T04:16:21.757616
2017-08-04T04:26:04
2017-08-04T04:26:04
95,841,385
1
0
null
null
null
null
UTF-8
C++
false
false
1,341
hpp
SeedStoreScene.hpp
// // SeedStoreScene.hpp // cocos3.10-mxzy // // Created by Wenjin Zhang on 2017/7/27. // // #ifndef SeedStoreScene_hpp #define SeedStoreScene_hpp #include "cocos2d.h" #include "ui/CocosGUI.h" #include "cocostudio/CocoStudio.h" #include "cocostudio/WidgetCallBackHandlerProtocol.h" #include "Protagonist.hpp" #include "SeedSeller.hpp" USING_NS_CC; using namespace ui; class SeedStoreScene : public Scene, public cocostudio::WidgetCallBackHandlerProtocol{ public: static cocos2d::Scene *createScene(); virtual bool init(); void onEnter(); CREATE_FUNC(SeedStoreScene); virtual Widget::ccWidgetClickCallback onLocateClickCallback(const std::string &callBackName); void Diary(Ref *sender); void Settings(Ref *sender); void Trade(Ref *sender); virtual void update(float delta); void initAllObjects(); void setProtagonist(); void setOtherCharacter(); void setSeedOnTable(); private: SeedSeller *seller = nullptr; Protagonist *pro; TMXTiledMap *map = nullptr; TMXObjectGroup *group = nullptr; ValueMap InsideDoorLeft; ValueMap seedTable1; ValueMap seedTable2; ValueMap seedTable3; ValueMap seedTable4; void judgeLdoorCollision(); void judgeTable1Collision(); }; #endif /* SeedStoreScene_hpp */
471415d90ff2c18065b01e481de42cef7f695c49
8c26d1b3ab61507ae65f0f6d090664b946e19e87
/IMT2016024_A2/source/Vertex.cpp
b02efd9360606bbeebe7338db630fa68f3aa3b77
[]
no_license
ShobhitBehl/Computer-Graphics
503c021d192eca4bcf1643fede8b9eb1cbe13448
f7d1585938da9b221049129ec0c86bc2bbc5e6d3
refs/heads/master
2022-04-03T10:05:36.315893
2020-02-13T16:51:22
2020-02-13T16:51:22
176,261,516
0
0
null
null
null
null
UTF-8
C++
false
false
622
cpp
Vertex.cpp
#include "../include/Vertex.h" using namespace std; Vertex::Vertex(){}; Vertex::Vertex( glm::vec3 pos ){ position = pos; normal = glm::vec3(0.0f, 0.0f, 0.0f); } Vertex::Vertex(const Vertex &v){ position = v.position; normal = v.normal; color = v.color; } glm::vec3 Vertex::getPosition(){ return position; } glm::vec3 Vertex::getNormal(){ return normal; } glm::vec3 Vertex::getColor(){ return color; } void Vertex::setPosition(glm::vec3 vec){ position = vec; } void Vertex::setNormal(glm::vec3 vec){ normal = vec; } void Vertex::setColor(glm::vec3 vec){ color = vec; }
d6da452f5629e97b73947423b6f19397e4088d2f
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/ash/components/arc/compat_mode/resize_toggle_menu_unittest.cc
11367114eca23fe509221018884889991cadccee
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
10,917
cc
resize_toggle_menu_unittest.cc
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/components/arc/compat_mode/resize_toggle_menu.h" #include <memory> #include "ash/components/arc/compat_mode/arc_resize_lock_pref_delegate.h" #include "ash/components/arc/compat_mode/metrics.h" #include "ash/components/arc/compat_mode/test/compat_mode_test_base.h" #include "base/test/bind.h" #include "base/test/metrics/user_action_tester.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/views/controls/button/button.h" namespace arc { namespace { constexpr char kTestAppId[] = "123"; } // namespace class ResizeToggleMenuTest : public CompatModeTestBase { public: // Overridden from test::Test. void SetUp() override { CompatModeTestBase::SetUp(); widget_ = CreateArcWidget(std::string(kTestAppId)); // Resizable mode by default. pref_delegate()->SetResizeLockState(kTestAppId, mojom::ArcResizeLockState::OFF); SyncResizeLockPropertyWithMojoState(widget()); resize_toggle_menu_ = std::make_unique<ResizeToggleMenu>( on_bubble_widget_closing_callback_, widget_.get(), pref_delegate()); } void TearDown() override { widget_->CloseNow(); CompatModeTestBase::TearDown(); } bool IsMenuRunning() { return resize_toggle_menu_->bubble_widget_ && resize_toggle_menu_->bubble_widget_->IsVisible(); } // Re-show the menu. This might close the running menu if any. void ReshowMenu() { resize_toggle_menu_.reset(); resize_toggle_menu_ = std::make_unique<ResizeToggleMenu>( on_bubble_widget_closing_callback_, widget_.get(), pref_delegate()); } bool IsCommandButtonDisabled(ResizeCompatMode command_id) { return GetButtonByCommandId(command_id)->GetState() == views::Button::ButtonState::STATE_DISABLED; } bool on_bubble_widget_closing_callback_called() const { return on_bubble_widget_closing_callback_called_; } void ClickButton(ResizeCompatMode command_id) { const auto* button = GetButtonByCommandId(command_id); LeftClickOnView(widget_.get(), button); SyncResizeLockPropertyWithMojoState(widget()); } void CloseBubble() { resize_toggle_menu_->CloseBubble(); } views::Widget* widget() { return widget_.get(); } ResizeToggleMenu* resize_toggle_menu() { return resize_toggle_menu_.get(); } private: views::Button* GetButtonByCommandId(ResizeCompatMode command_id) { switch (command_id) { case ResizeCompatMode::kPhone: return resize_toggle_menu_->phone_button_; case ResizeCompatMode::kTablet: return resize_toggle_menu_->tablet_button_; case ResizeCompatMode::kResizable: return resize_toggle_menu_->resizable_button_; } } bool on_bubble_widget_closing_callback_called_ = false; base::RepeatingClosure on_bubble_widget_closing_callback_ = base::BindLambdaForTesting( [&]() { on_bubble_widget_closing_callback_called_ = true; }); std::unique_ptr<views::Widget> widget_; std::unique_ptr<ResizeToggleMenu> resize_toggle_menu_; }; TEST_F(ResizeToggleMenuTest, ConstructDestruct) { EXPECT_TRUE(IsMenuRunning()); } // Test that on_bubble_widget_closing_callback_ is called after closing bubble. TEST_F(ResizeToggleMenuTest, TestCallback) { EXPECT_TRUE(IsMenuRunning()); EXPECT_FALSE(on_bubble_widget_closing_callback_called()); CloseBubble(); EXPECT_TRUE(on_bubble_widget_closing_callback_called()); } TEST_F(ResizeToggleMenuTest, TestResizePhone) { // Verify pre-conditions. EXPECT_TRUE(IsMenuRunning()); // Test that resize command is properly handled. ClickButton(ResizeCompatMode::kPhone); EXPECT_LT(widget()->GetWindowBoundsInScreen().width(), widget()->GetWindowBoundsInScreen().height()); // Test that the selected item is changed dynamically after the resize. EXPECT_TRUE(IsCommandButtonDisabled(ResizeCompatMode::kPhone)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kTablet)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kResizable)); // Test that the item is selected after re-showing. ReshowMenu(); EXPECT_TRUE(IsMenuRunning()); EXPECT_TRUE(IsCommandButtonDisabled(ResizeCompatMode::kPhone)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kTablet)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kResizable)); } TEST_F(ResizeToggleMenuTest, TestResizeTablet) { // Verify pre-conditions. EXPECT_TRUE(IsMenuRunning()); // Test that resize command is properly handled. ClickButton(ResizeCompatMode::kTablet); EXPECT_GT(widget()->GetWindowBoundsInScreen().width(), widget()->GetWindowBoundsInScreen().height()); // Test that the selected item is changed dynamically after the resize. EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kPhone)); EXPECT_TRUE(IsCommandButtonDisabled(ResizeCompatMode::kTablet)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kResizable)); // Test that the item is selected after re-showing. ReshowMenu(); EXPECT_TRUE(IsMenuRunning()); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kPhone)); EXPECT_TRUE(IsCommandButtonDisabled(ResizeCompatMode::kTablet)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kResizable)); } TEST_F(ResizeToggleMenuTest, TestResizable) { // Verify pre-conditions. EXPECT_TRUE(IsMenuRunning()); // Set resize locked mode to enable Resizable button. pref_delegate()->SetResizeLockState(kTestAppId, mojom::ArcResizeLockState::ON); SyncResizeLockPropertyWithMojoState(widget()); // Test that resize command is properly handled. ClickButton(ResizeCompatMode::kResizable); EXPECT_EQ(pref_delegate()->GetResizeLockState(kTestAppId), mojom::ArcResizeLockState::OFF); // Test that the selected item is changed dynamically. EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kPhone)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kTablet)); EXPECT_TRUE(IsCommandButtonDisabled(ResizeCompatMode::kResizable)); // Test that the item is selected after the resize. ReshowMenu(); EXPECT_TRUE(IsMenuRunning()); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kPhone)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kTablet)); EXPECT_TRUE(IsCommandButtonDisabled(ResizeCompatMode::kResizable)); } // Test that the button state is dynamically changed even if no bounds change // happens. TEST_F(ResizeToggleMenuTest, TestButtonStateChangeWithoutBoundsChange) { // Verify pre-conditions. EXPECT_TRUE(IsMenuRunning()); ClickButton(ResizeCompatMode::kPhone); EXPECT_TRUE(IsCommandButtonDisabled(ResizeCompatMode::kPhone)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kTablet)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kResizable)); ClickButton(ResizeCompatMode::kResizable); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kPhone)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kTablet)); EXPECT_TRUE(IsCommandButtonDisabled(ResizeCompatMode::kResizable)); ClickButton(ResizeCompatMode::kPhone); EXPECT_TRUE(IsCommandButtonDisabled(ResizeCompatMode::kPhone)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kTablet)); EXPECT_FALSE(IsCommandButtonDisabled(ResizeCompatMode::kResizable)); } // Test that the menu is closed with delay when the button is clicked. TEST_F(ResizeToggleMenuTest, TestDelayedAutoClose) { EXPECT_TRUE(IsMenuRunning()); ClickButton(ResizeCompatMode::kPhone); EXPECT_TRUE(IsMenuRunning()); task_environment()->FastForwardBy(base::Seconds(1)); EXPECT_TRUE(IsMenuRunning()); task_environment()->FastForwardBy(base::Seconds(1)); EXPECT_FALSE(IsMenuRunning()); } // Test that the delayed auto close is canceled when another button is clicked. TEST_F(ResizeToggleMenuTest, TestDelayedAutoCloseCancel) { EXPECT_TRUE(IsMenuRunning()); ClickButton(ResizeCompatMode::kPhone); EXPECT_TRUE(IsMenuRunning()); task_environment()->FastForwardBy(base::Seconds(1)); EXPECT_TRUE(IsMenuRunning()); ClickButton(ResizeCompatMode::kTablet); EXPECT_TRUE(IsMenuRunning()); task_environment()->FastForwardBy(base::Seconds(1)); EXPECT_TRUE(IsMenuRunning()); task_environment()->FastForwardBy(base::Seconds(1)); EXPECT_FALSE(IsMenuRunning()); } // Tests that user action metrics are recorded correctly. TEST_F(ResizeToggleMenuTest, TestUserActionMetrics) { base::UserActionTester user_action_tester; ClickButton(ResizeCompatMode::kPhone); EXPECT_EQ(1, user_action_tester.GetActionCount(GetResizeLockActionNameForTesting( ResizeLockActionType::ResizeToPhone))); EXPECT_EQ(1, user_action_tester.GetActionCount(GetResizeLockActionNameForTesting( ResizeLockActionType::TurnOnResizeLock))); ClickButton(ResizeCompatMode::kTablet); EXPECT_EQ(1, user_action_tester.GetActionCount(GetResizeLockActionNameForTesting( ResizeLockActionType::ResizeToTablet))); EXPECT_EQ(1, user_action_tester.GetActionCount(GetResizeLockActionNameForTesting( ResizeLockActionType::TurnOnResizeLock))); ClickButton(ResizeCompatMode::kResizable); EXPECT_EQ(1, user_action_tester.GetActionCount(GetResizeLockActionNameForTesting( ResizeLockActionType::TurnOffResizeLock))); ClickButton(ResizeCompatMode::kPhone); EXPECT_EQ(2, user_action_tester.GetActionCount(GetResizeLockActionNameForTesting( ResizeLockActionType::ResizeToPhone))); EXPECT_EQ(2, user_action_tester.GetActionCount(GetResizeLockActionNameForTesting( ResizeLockActionType::TurnOnResizeLock))); } // Test that the menu is not shown if the window is maximized or fullscreen. TEST_F(ResizeToggleMenuTest, TestMaximizedOrFullscreen) { // Test maximized after shown. EXPECT_TRUE(IsMenuRunning()); widget()->Maximize(); EXPECT_FALSE(IsMenuRunning()); widget()->Restore(); // Test fullscreen after shown. ReshowMenu(); EXPECT_TRUE(IsMenuRunning()); widget()->SetFullscreen(true); EXPECT_FALSE(IsMenuRunning()); widget()->SetFullscreen(false); // Test maximized before shown. widget()->Maximize(); ReshowMenu(); EXPECT_FALSE(IsMenuRunning()); widget()->Restore(); // Test fullscreen before shown. widget()->SetFullscreen(true); ReshowMenu(); EXPECT_FALSE(IsMenuRunning()); widget()->SetFullscreen(false); } // Test that IsBubbleOpen returns the correct state of the bubble TEST_F(ResizeToggleMenuTest, TestIsBubbleShown) { EXPECT_TRUE(IsMenuRunning()); EXPECT_TRUE(resize_toggle_menu()->IsBubbleShown()); CloseBubble(); RunPendingMessages(); EXPECT_FALSE(resize_toggle_menu()->IsBubbleShown()); } } // namespace arc
c4ce8cc48d3246c12d782dc880d2639cd743e5fd
f4dc1073def4c95a19d4183475405c439cfc0aff
/Include/Physics/IntrBox3Sphere3.h
a60b2287a5a9e64ba5e587f28431ab3f82c23ea7
[]
no_license
timi-liuliang/aresengine
9cf74e7137bb11cd8475852b8e4c9d51eda62505
efd39c6ef482b8d50a8eeaa5009cac5d5b9f41ee
refs/heads/master
2020-04-15T15:06:41.726469
2019-01-09T05:09:35
2019-01-09T05:09:35
164,779,995
1
0
null
null
null
null
GB18030
C++
false
false
450
h
IntrBox3Sphere3.h
#pragma once #include "Physics/Shapes.h" namespace Ares { //---------------------------------------- // IntrBox3Sphere3 2012-9-7 帝林 //---------------------------------------- struct IntrBox3Sphere3 { Vector3 m_intrPoint; // 相交点 const Box3& m_box3; // 盒子 const Sphere3& m_sphere3; // 球 // constructor IntrBox3Sphere3( const Box3& box3, const Sphere3& sphere); // test intersection query bool Test(); }; }
6ac9f44b303e11131b39b7688deaa6619a06d3ab
2f10f807d3307b83293a521da600c02623cdda82
/deps/boost/win/debug/include/boost/ptr_container/serialize_ptr_circular_buffer.hpp
26b3d3aa0479c54a91aedfcc1893b0c331de43bd
[]
no_license
xpierrohk/dpt-rp1-cpp
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
refs/heads/master
2021-05-23T08:19:48.823198
2019-07-26T17:35:28
2019-07-26T17:35:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
serialize_ptr_circular_buffer.hpp
version https://git-lfs.github.com/spec/v1 oid sha256:a27d466f929ebc4c4f0ebc70d3c6a123e69dc205a121afc5b4613d65dce28b20 size 1408
7bfa9d446d4d8c2b6755249c343913ab0f5c88fa
957a5a88598b0a8b042bfbfeac6794889ade0a18
/9-找出字符串中第一个只出现一次的字符.cpp
63af33cd9511dd95c174bf3036dc04c1e53f34e1
[]
no_license
zhoutengteng/huawei
65bd52ef409c80b28de606a1aa2cf1db068e0203
a70090b0e3b15b108430d911c8310fcd7d6a54f2
refs/heads/master
2020-12-02T23:00:24.164626
2017-07-06T03:09:40
2017-07-06T03:09:40
96,215,702
0
0
null
null
null
null
UTF-8
C++
false
false
668
cpp
9-找出字符串中第一个只出现一次的字符.cpp
#include <iostream> #include <list> #include <string> #include <cstring> using namespace std; int main() { string str; while (getline(cin , str)) { char map[128]; list<char> li; memset(map, 2, sizeof(char)*128); for (int i = 0; i < str.length(); i++) { if (map[str[i]] == 2) { map[str[i]] -= 1; li.push_back(str[i]); } else if (map[str[i]] == 1) { list<char>::iterator itli; for (itli = li.begin(); itli != li.end(); itli++) { if (*itli == str[i]) { li.erase(itli); break; } } map[str[i]] -= 1; } } if (li.empty()) { cout << '.' << std::endl; } else { cout << li.front() << endl; } } }
c46d5c2a36a448c649e4655d36aaf8e01951d719
5f6a570fb02ed73c03bf2e426205d0fcef22fd18
/tests/TestRunnersTests.cpp
2bee95c5f49ce436c66c798fb8ac3bcff4f6a313
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
ea1111/mull
f16c11c5bd78cd423674b73c296415f0a6ce8e06
9025bfbe87ee8a4606348a7f427db5572164a64f
refs/heads/master
2022-12-20T11:27:10.106552
2020-09-22T19:44:18
2020-09-22T19:44:18
298,547,485
0
0
Apache-2.0
2020-09-25T11:37:00
2020-09-25T10:58:58
null
UTF-8
C++
false
false
4,520
cpp
TestRunnersTests.cpp
#include "FixturePaths.h" #include "TestModuleFactory.h" #include "mull/BitcodeLoader.h" #include "mull/Config/Configuration.h" #include "mull/MutationsFinder.h" #include "mull/Program/Program.h" #include "mull/ReachableFunction.h" #include "mull/TestFrameworks/NativeTestRunner.h" #include "mull/TestFrameworks/SimpleTest/SimpleTestFinder.h" #include "mull/Toolchain/JITEngine.h" #include "mull/Toolchain/Toolchain.h" #include "mull/Toolchain/Trampolines.h" #include <mull/Mutators/CXX/ArithmeticMutators.h> #include <mull/Parallelization/Parallelization.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/Support/DynamicLibrary.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Transforms/Utils/Cloning.h> #include <gtest/gtest.h> #include <mull/Diagnostics/Diagnostics.h> using namespace mull; using namespace llvm; TEST(NativeTestRunner, runTest) { Diagnostics diagnostics; Configuration configuration; Toolchain toolchain(diagnostics, configuration); LLVMContext context; BitcodeLoader loader; auto bitcodeWithTests = loader.loadBitcodeAtPath( fixtures::simple_test_count_letters_test_count_letters_bc_path(), context, diagnostics); auto bitcodeWithTestees = loader.loadBitcodeAtPath( fixtures::simple_test_count_letters_count_letters_bc_path(), context, diagnostics); Module *moduleWithTests = bitcodeWithTests->getModule(); Module *moduleWithTestees = bitcodeWithTestees->getModule(); std::vector<std::unique_ptr<Bitcode>> bitcodeFiles; bitcodeFiles.push_back(std::move(bitcodeWithTestees)); bitcodeFiles.push_back(std::move(bitcodeWithTests)); Program program({}, {}, std::move(bitcodeFiles)); NativeTestRunner testRunner(diagnostics, toolchain.mangler()); NativeTestRunner::ObjectFiles objectFiles; NativeTestRunner::OwnedObjectFiles ownedObjectFiles; std::vector<std::unique_ptr<Mutator>> mutators; mutators.emplace_back(std::make_unique<cxx::AddToSub>()); MutationsFinder mutationsFinder(std::move(mutators), configuration); Function *reachableFunction = program.lookupDefinedFunction("count_letters"); std::vector<std::unique_ptr<ReachableFunction>> reachableFunctions; reachableFunctions.emplace_back(std::make_unique<ReachableFunction>(reachableFunction, nullptr, 1)); auto functionsUnderTest = mergeReachableFunctions(reachableFunctions); functionsUnderTest.back().selectInstructions({}); std::vector<MutationPoint *> mutationPoints = mutationsFinder.getMutationPoints(diagnostics, program, functionsUnderTest); for (auto point : mutationPoints) { point->getBitcode()->addMutation(point); } MutationPoint *mutationPoint = mutationPoints.front(); SimpleTestFinder testFinder; auto tests = testFinder.findTests(program); ASSERT_NE(0U, tests.size()); auto &test = tests.front(); JITEngine jit(diagnostics); Bitcode &bitcode = *mutationPoint->getBitcode(); std::vector<std::string> mutatedFunctions; CloneMutatedFunctionsTask::cloneFunctions(bitcode, mutatedFunctions); DeleteOriginalFunctionsTask::deleteFunctions(bitcode); InsertMutationTrampolinesTask::insertTrampolines(bitcode); mutationPoint->applyMutation(); { auto owningBinary = toolchain.compiler().compileModule(moduleWithTests, toolchain.targetMachine()); objectFiles.push_back(owningBinary.getBinary()); ownedObjectFiles.push_back(std::move(owningBinary)); } { auto owningBinary = toolchain.compiler().compileModule(moduleWithTestees, toolchain.targetMachine()); objectFiles.push_back(owningBinary.getBinary()); ownedObjectFiles.push_back(std::move(owningBinary)); } Trampolines trampolines(mutatedFunctions); testRunner.loadMutatedProgram(objectFiles, trampolines, jit); trampolines.fixupOriginalFunctions(jit); ASSERT_EQ(ExecutionStatus::Passed, testRunner.runTest(jit, program, test)); auto &mangler = toolchain.mangler(); auto name = mutationPoint->getOriginalFunction()->getName().str(); auto bitcodeId = mutationPoint->getBitcode()->getUniqueIdentifier(); auto trampolineName = mangler.getNameWithPrefix(mutationPoint->getTrampolineName()); auto mutatedFunctionName = mangler.getNameWithPrefix(mutationPoint->getMutatedFunctionName()); uint64_t *trampoline = trampolines.findTrampoline(trampolineName); uint64_t address = llvm_compat::JITSymbolAddress(jit.getSymbol(mutatedFunctionName)); assert(address); *trampoline = address; ASSERT_EQ(ExecutionStatus::Failed, testRunner.runTest(jit, program, test)); }
f706189a44651f1644046a763f6e2ecae063ba4f
e0bf5836e4f0d75b28b1f787446e655cdeeb8b03
/files/AMR12D.cpp
10fda1cf7cd63dd501cc31c8f45afc0dfa0c3b04
[]
no_license
arunnsit/allcodes
3f0b73facdee06e802455c6c3fb5de7baae702c2
5e6a8bf3883d0c5f67dfa7cc3dc026dbb4c63a71
refs/heads/master
2021-01-10T13:58:24.900593
2017-10-03T18:11:34
2017-10-03T18:11:34
50,598,937
0
2
null
2019-09-30T20:16:32
2016-01-28T17:06:03
C++
UTF-8
C++
false
false
289
cpp
AMR12D.cpp
#include<stdio.h> #include<string.h> int main(){ int t,i; char a[20]; scanf("%d",&t); while(t--){ scanf("%s",&a); int n=strlen(a); for(i=0;i<=(n-1)/2;i++){ if(a[i]!=a[n-1-i])break; } if(i==(n-1)/2+1)printf("YES\n"); else printf("NO\n"); } }
9f33dc0cdb75e9b792885f4dee0419e2dbbc1142
9424cfe19b1db4e60ab9ff483fd67d3ad4ec81bd
/src/Shared/DynamicEntity.cpp
0f60635cb8679d81b276bee15ab7cc944c84aa44
[]
no_license
kiwon0905/PT
64c51d4a93c50cb1bf810750fc1696a1a951b87e
facab17f518e22bd36fd91f0cf83a73c2fc491b6
refs/heads/master
2021-01-18T14:09:54.148016
2016-10-15T22:13:26
2016-10-15T22:13:26
16,738,395
0
0
null
null
null
null
UTF-8
C++
false
false
1,475
cpp
DynamicEntity.cpp
#include "Shared/DynamicEntity.h" #include <Thor/Graphics.hpp> #include <Thor/Vectors.hpp> #include <iostream> DynamicEntity::DynamicEntity(Entity::ID id) : Entity(id), mGoalVelocity(), mCurrentVelocity(), mAcceleration(), mRotation() { } float DynamicEntity::accelerate(float current, float goal, float dt) { float diff = goal - current; if (std::abs(diff) < mAcceleration*dt) return goal; else if (diff < 0) return current -= mAcceleration*dt; else return current += mAcceleration*dt; } void DynamicEntity::update(float dt) { if (thor::length(mCurrentVelocity) > mMaxSpeed) thor::setLength(mCurrentVelocity, mMaxSpeed); mCurrentVelocity.x = accelerate(mCurrentVelocity.x, mGoalVelocity.x, dt); mCurrentVelocity.y = accelerate(mCurrentVelocity.y, mGoalVelocity.y, dt); setPosition(getPosition() + mCurrentVelocity * dt); } void DynamicEntity::setAcceleration(float accleration) { mAcceleration = accleration; } float DynamicEntity::getRotation() const { return mRotation; } void DynamicEntity::setRotation(float angle) { mRotation = angle; } const sf::Vector2f & DynamicEntity::getVelocity() { return mCurrentVelocity; } void DynamicEntity::setGoalVelocity(sf::Vector2f speed) { mGoalVelocity = speed; } void DynamicEntity::setMaxSpeed(float speed) { mMaxSpeed = speed; } void DynamicEntity::setRemotePosition(const sf::Vector2f & v) { mRemotePosition = v; } const sf::Vector2f & DynamicEntity::getRemotePosition() { return mRemotePosition; }
546201fa6f39092bdd30aa5fcc3a1f3593e4c5ea
3852cd1bd5e282dd23b8f7c64309cc2f598e3b75
/personal/c++/MapEditor/src/gl/Map_Window.h
31d064930736c403cc568228c48b1d984f696e58
[]
no_license
chandl34/public
4e6ca43afa410cd50f54f93d589a1784f51b55dc
e288ac323166f5170aaac7cd97d37dabffa70090
refs/heads/master
2021-08-18T05:42:00.234407
2021-07-29T02:43:03
2021-07-29T02:43:03
2,938,300
0
2
null
null
null
null
UTF-8
C++
false
false
616
h
Map_Window.h
#ifndef GL_WINDOW_H_ #define GL_WINDOW_H_ #include <FL/Fl.H> #include <FL/Gl.H> #include <FL/Glu.H> #include <FL/Fl_Gl_Window.H> #include "Camera.h" #include "SelectBox.h" #include "../map/LevelMap.h" class Map_Window : public Fl_Gl_Window{ public: Map_Window(int, int, int, int); virtual ~Map_Window(); static LevelMap& getMap(); static LevelMap& getNewMap(); private: void init(); static void Timer_CB(void*); void draw(); void view(); void drawMap(); int handle(int e); Camera* camera; SelectBox* select; static LevelMap* levelMap; }; #endif /*GL_WINDOW_H_*/
e70f2a25de2dab483a72642fe3746bf1e3ba7027
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/96/f678e6690c53f8/main.cpp
07946db4222fbfe821ba8f051b71009a7b6231d9
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
922
cpp
main.cpp
#include <boost/variant.hpp> #include <map> #include <vector> #include <string> using Val = boost::variant<std::vector<int>, std::vector<std::string>>; using Ref = boost::variant<std::vector<int>&, std::vector<std::string>& >; std::map<std::string, Val> map { { "first", std::vector<int> { 1,2,3,4 } }, { "2nd", std::vector<std::string> { "five", "six", "seven", "eight" } } }; namespace { // detail template <typename T> struct implicit_convert : boost::static_visitor<T> { template <typename U> T operator()(U&& u) const { return std::forward<U>(u); } }; } Ref getVal(std::string& name) { return boost::apply_visitor(implicit_convert<Ref>(), map[name]); } #include <iostream> int main() { for (auto i : boost::get<std::vector<int> >(map["first"])) std::cout << i << " "; for (auto i : boost::get<std::vector<std::string> >(map["2nd"])) std::cout << i << " "; }
733ca34ae19e8b17970f8efd30c4d871a9e4887c
aa4a3ccd4e5572396ec737c527c3b4da71a7ec30
/src/material_library.cpp
8fbd7c88413688725a0c29da50812e59d068047d
[ "MIT", "BSD-2-Clause" ]
permissive
pyne/pyne
6c4d178eedfdeb464966e99a3d27d794a04d1add
8a9ef7291ca5a23ec4da8794cd19cbac93f849ef
refs/heads/develop
2023-08-31T16:00:04.363507
2023-08-26T14:25:38
2023-08-26T14:25:38
1,684,953
218
168
NOASSERTION
2023-09-12T08:21:55
2011-04-30T15:04:07
C++
UTF-8
C++
false
false
11,925
cpp
material_library.cpp
#ifndef _WIN32 #include <unistd.h> #endif #include <fstream> #include <iostream> #ifndef PYNE_IS_AMALGAMATED #include "material_library.h" #endif // Empty Constructor pyne::MaterialLibrary::MaterialLibrary(){}; // Default constructor when loading from HDF5 file pyne::MaterialLibrary::MaterialLibrary(const std::string& filename, const std::string& datapath) { // load materials // Check that the file is there if (!pyne::file_exists(filename)) throw pyne::FileNotFound(filename); // Check to see if the file is in HDF5 format. bool ish5 = H5Fis_hdf5(filename.c_str()); if (ish5) from_hdf5(filename, datapath); else if (datapath != "") { std::string wrng = filename + " is not an hdf5 file but a datapath was provided!"; pyne::warning(wrng); } from_json(filename); }; // Append Material to the library from hdf5 file void pyne::MaterialLibrary::from_hdf5(const std::string& filename, const std::string& datapath) { if (!pyne::file_exists(filename)) { throw std::runtime_error("File " + filename + " not found or no read permission"); } std::string nucpath; std::string full_datapath = datapath; // Set file access properties so it closes cleanly hid_t fapl = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fclose_degree(fapl, H5F_CLOSE_STRONG); // Open the database hid_t db = H5Fopen(filename.c_str(), H5F_ACC_RDONLY, fapl); // Get datapath status in the hdf5 file herr_t status = H5Eset_auto2(H5E_DEFAULT, NULL, NULL); hid_t matlib_group_id = db; H5O_info_t object_info; status = H5Oget_info_by_name(db, datapath.c_str(), &object_info, H5P_DEFAULT); // if datapath exist and is a dataset -> old hdf5 mat_lib format // else if datapath does not exist -> new hdf5 mat lib format // else don't know what to do with it: fail ! if (status == 0 && object_info.type == H5O_TYPE_DATASET) { // Open dataset to retrieve nucclide list location form nucpath attribute hid_t data_set = H5Dopen2(db, datapath.c_str(), H5P_DEFAULT); pyne::detect_nuclidelist(data_set, nucpath); H5Dclose(data_set); } else if (status != 0) { full_datapath = "/material_library" + datapath + "/composition"; nucpath = "/material_library" + datapath + "/nuclidelist"; } else { throw std::runtime_error(datapath + " exist but is not a dataset."); } int file_num_materials = get_length_of_table(db, full_datapath); for (int i = 0; i < file_num_materials; i++) { pyne::Material mat = pyne::Material(); mat._load_comp_protocol1(db, full_datapath, nucpath, i); add_material(mat); } H5Fclose(db); } void pyne::MaterialLibrary::merge(const pyne::MaterialLibrary& mat_lib) { pyne::matname_set mats_to_add = mat_lib.get_keylist(); for (auto it = mats_to_add.begin(); it != mats_to_add.end(); it++) { pyne::Material mat = Material(mat_lib.get_material(*it)); (*this).add_material(*it, mat); } } void pyne::MaterialLibrary::merge(pyne::MaterialLibrary* mat_lib) { merge(*mat_lib); } void pyne::MaterialLibrary::load_json(Json::Value json) { Json::Value::Members keys = json.getMemberNames(); Json::Value::Members::const_iterator ikey = keys.begin(); Json::Value::Members::const_iterator ikey_end = keys.end(); for (; ikey != ikey_end; ++ikey) { pyne::Material mat = pyne::Material(); mat.load_json(json[*ikey]); (*this).add_material(*ikey, Material(mat)); } } Json::Value pyne::MaterialLibrary::dump_json() { Json::Value json = Json::Value(Json::objectValue); for (auto name : keylist) { json[name] = material_library[name]->dump_json(); } return json; } void pyne::MaterialLibrary::from_json(const std::string& filename) { if (!pyne::file_exists(filename)) throw pyne::FileNotFound(filename); std::string s; std::ifstream f(filename.c_str(), std::ios::in | std::ios::binary); f.seekg(0, std::ios::end); s.resize(f.tellg()); f.seekg(0, std::ios::beg); f.read(&s[0], s.size()); f.close(); Json::Reader reader; Json::Value json; reader.parse(s, json); load_json(json); } void pyne::MaterialLibrary::write_json(const std::string& filename) { Json::Value json = dump_json(); Json::StyledWriter writer; std::string s = writer.write(json); std::ofstream f(filename.c_str(), std::ios_base::trunc); f << s << "\n"; f.close(); } void pyne::MaterialLibrary::write_openmc(const std::string& filename) const { std::ofstream f(filename.c_str()); // write header f << "<?xml version=\"1.0\"?>\n"; f << "<materials>\n"; // write materials for (auto& mat : material_library) { f << mat.second->openmc("atom"); } // write footer f << "</materials>"; // close file f.close(); } int pyne::MaterialLibrary::ensure_material_number(pyne::Material& mat) const { int mat_number = -1; if (mat.metadata.isMember("mat_number")) { if (Json::intValue <= mat.metadata["mat_number"].type() && mat.metadata["mat_number"].type() <= Json::realValue) { mat_number = mat.metadata["mat_number"].asInt(); } else { mat_number = std::stoi(mat.metadata["mat_number"].asString()); mat.metadata["mat_number"] = mat_number; } std::set<int>::iterator mat_numb_it; mat_numb_it = mat_number_set.find(mat_number); if (mat_numb_it != mat_number_set.end()) { std::string msg = "Material number "; msg += std::to_string(mat_number); msg += " is already in the library."; warning(msg); } } if (mat_number == -1) { if (!mat_number_set.empty()) mat_number = *mat_number_set.rbegin() + 1; else { mat_number = 1; } mat.metadata["mat_number"] = mat_number; } return mat_number; } std::string pyne::MaterialLibrary::ensure_material_name_and_number( pyne::Material& mat) const { std::string mat_name = ""; int mat_number = ensure_material_number(mat); if (mat.metadata.isMember("name")) { if (Json::intValue <= mat.metadata["name"].type() && mat.metadata["name"].type() <= Json::realValue) { mat_name = std::to_string(mat.metadata["name"].asInt()); mat.metadata["name"] = mat_name; } else { mat_name = mat.metadata["name"].asString(); } } else { mat_name = "_" + std::to_string(mat_number); mat.metadata["name"] = mat_name; } return mat_name; } void pyne::MaterialLibrary::add_material(pyne::Material mat) { // if exists, get the material name from metadata make one instead std::string mat_name = ensure_material_name_and_number(mat); add_material(mat_name, mat); } void pyne::MaterialLibrary::add_material(const std::string& key, const pyne::Material& mat) { pyne::shr_mat_ptr new_mat = std::make_shared<pyne::Material>(mat); int mat_number = ensure_material_number(*new_mat); if (!new_mat->metadata.isMember("name")) { new_mat->metadata["name"] = key; } append_to_nuclist(*new_mat); if (mat_number > 0) mat_number_set.insert(mat_number); keylist.insert(key); material_library[key] = new_mat; } void pyne::MaterialLibrary::del_material(const std::string& key) { material_library.erase(key); keylist.erase(key); } pyne::Material pyne::MaterialLibrary::get_material( const std::string& mat_name) const { return *(this->get_material_ptr(mat_name)); } pyne::shr_mat_ptr pyne::MaterialLibrary::get_material_ptr( const std::string& mat_name) const { auto it = material_library.find(mat_name); if (it != material_library.end()) { return it->second; } else { return std::make_shared<pyne::Material>(pyne::Material()); } } void pyne::MaterialLibrary::write_hdf5(const std::string& filename, const std::string& datapath, bool h5_overwrite) const { // Turn off annoying HDF5 errors H5Eset_auto2(H5E_DEFAULT, NULL, NULL); // Set file access properties so it closes cleanly hid_t fapl; fapl = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fclose_degree(fapl, H5F_CLOSE_STRONG); hid_t matlib_grp_id; hid_t data_id; hid_t db; if (!pyne::file_exists(filename)) { // Create the file db = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, fapl); } else { db = H5Fopen(filename.c_str(), H5F_ACC_RDWR, fapl); } // Check if root_path exist and what type it is std::string root_path = "/material_library"; H5O_info_t object_info; herr_t status = H5Eset_auto2(H5E_DEFAULT, NULL, NULL); // Check if root_path exist and what type it is status = H5Oget_info_by_name(db, root_path.c_str(), &object_info, H5P_DEFAULT); if (status == 0) { // "/material_library" not a group: fail! if (object_info.type != H5O_TYPE_GROUP) { throw std::runtime_error( "Non-group/non-dataset object /material_library already exists in " "the file. Can't write the Material"); } else { // "/material_library" is a group get its hid matlib_grp_id = H5Gopen2(db, root_path.c_str(), H5P_DEFAULT); } } else { // "/material_library" does not exist -> create it ! matlib_grp_id = H5Gcreate2(db, root_path.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); } // Group "/root_path/datapath" does exist throw an error or remove it std::string full_path = root_path + datapath; if (h5wrap::path_exists(db, full_path)) { if (h5_overwrite) { H5Ldelete(db, full_path.c_str(), H5P_DEFAULT); } else { throw std::runtime_error( "datapath" + full_path + "already exist, use \"h5_overwrite=true\" option to " "overwrite existing datapath"); } } // create "/root_path/datapath" Group data_id = H5Gcreate2(db, full_path.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); std::string compath = "composition"; std::string nucpath = "nuclidelist"; write_hdf5_nucpath(data_id, nucpath); std::vector<int> nuc_list; nuc_list.assign(nuclist.begin(), nuclist.end()); for (auto mat : material_library) { mat.second->write_hdf5_datapath(data_id, compath, -0.0, DEFAULT_MAT_CHUNKSIZE, nuc_list); } H5Fflush(db, H5F_SCOPE_GLOBAL); H5Gclose(data_id); H5Gclose(matlib_grp_id); H5Fclose(db); } void pyne::MaterialLibrary::write_hdf5_nucpath(hid_t db, std::string nucpath) const { int nuc_size; nuc_size = nuclist.size(); std::vector<int> nuc_data; nuc_data.assign(nuclist.begin(), nuclist.end()); hsize_t nuc_dims[1]; nuc_dims[0] = nuc_size; hid_t nuc_space = H5Screate_simple(1, nuc_dims, NULL); hid_t nuc_set = H5Dcreate2(db, nucpath.c_str(), H5T_NATIVE_INT, nuc_space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); H5Dwrite(nuc_set, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, nuc_data.data()); H5Fflush(db, H5F_SCOPE_GLOBAL); H5Sclose(nuc_space); H5Dclose(nuc_set); } void pyne::MaterialLibrary::append_to_nuclist(const pyne::Material& mat) { pyne::comp_map mat_comp = mat.comp; for (auto nuclide : mat_comp) { nuclist.insert(nuclide.first); } } int pyne::MaterialLibrary::get_length_of_table( hid_t db, const std::string& datapath) const { // Turn off annoying HDF5 errors H5Eset_auto2(H5E_DEFAULT, NULL, NULL); // Set file access properties so it closes cleanly hid_t fapl = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fclose_degree(fapl, H5F_CLOSE_STRONG); hid_t ds = H5Dopen2(db, datapath.c_str(), H5P_DEFAULT); // Initialize to dataspace, to find the indices we are looping over hid_t arr_space = H5Dget_space(ds); // failure to read the dapaspace return 0 for the size if (arr_space < 0) return 0; hsize_t arr_dims[1]; int arr_ndim = H5Sget_simple_extent_dims(arr_space, arr_dims, NULL); herr_t status = H5Eclear(H5E_DEFAULT); return arr_dims[0]; }
c21a5cd1fa47e212b1d52ecb3bf09bb04baac475
a69aeef1e65ac4e7ed828a0510981dc541e8f8dd
/22A/Hw5/Hw_5B.cpp
ff4a2a9d55f1754f46aa070857f469a5183f0190
[ "MIT" ]
permissive
codewitty/De-Anza
fa9a7564605763c50e5168b2230037a7f58e65bf
0e54993058f0f4e81ed263f9f2229a26dd990e9b
refs/heads/master
2021-07-11T09:45:37.902630
2020-06-15T02:54:37
2020-06-15T02:54:37
153,695,631
1
0
null
2020-03-23T02:32:31
2018-10-18T22:34:06
C++
UTF-8
C++
false
false
2,041
cpp
Hw_5B.cpp
/**~*~*~* PART B - Intro to files This program writes 10 random numbers to a file. Then reads the numbers from the file, displays them to the screen, and calculates their average. Finish the program following the specifications listed below as comments. Run the program and save the output as a comment at the end of the source file. JOSHUA N. GOMES */ #include <iostream> #include <fstream> #include <cstdlib> #include <string> using namespace std; int main() { ofstream outputFile; int rNum; // Open an output file. outputFile.open("Numbers.txt"); // Write 10 random numbers to the file for (int i = 0; i < 10; i++) { rNum = rand() % 51 - 10; outputFile << rNum << " "; } // Close the file. outputFile.close(); cout << "File with 10 random numbers created!\n"; // Open the same file to read from; //string fileName = "Number.txt"; // <==== Try to open this file! ifstream inputFile; string fileName = "Numbers.txt"; inputFile.open(fileName.c_str()); // another way of opening the input file if (!inputFile) // could not open the input file // <=== Always check this! { cout << "Error opening " << fileName << " for reading!\n"; } else { // calculate the average of the positive numbers ( > 0 ) // define other variables as needed int sum = 0; while (inputFile >> rNum) { cout << rNum << " "; sum += rNum; } // Close the file. inputFile.close(); // Show average cout << "\n\nThe average of the random numbers is: " << sum / 10.0 << endl; // Show the average of the positive ( > 0 ) numbers } return 0; } /**~*~*~*~*~*~*~*~*~* File with 10 random numbers created! 0 39 -1 24 22 27 27 38 35 9 The average of the random numbers is: 22 */
80a95dfc356415096b190c199b207574b2548990
b08fc650ada54f1165d6c9c3594c25c105e25a65
/src/main.cpp
8267c4078a37c27f73e5ab7d1e56db2ef38bfb5c
[]
no_license
nbogie/winamp_vis
f00cf2f6d746e64603ed5395e13d3832715d8d64
94aa2dc5bf65a00738380f321d484d6f3e3a0cfc
refs/heads/master
2020-08-19T14:53:58.140976
2019-10-18T02:52:31
2019-10-18T02:52:31
215,929,074
2
0
null
null
null
null
UTF-8
C++
false
false
4,223
cpp
main.cpp
#include "vis.h" #include "Spinner.h" #include "TextBoy.h" // initial window size //DO NOT DELETE THIS. if you want you can change it int width = 512 , height = 300 ; Spinner* spinner; TextBoy* textboy; int* spectrumDataPeaks = new int[512]; int* spectrumDataPeakAge = new int[512]; int maxPeak = 0; char* myTitle; //Use this function to 'write' your information in the configuration dialog box char* putConfigInfo(void) { return "Neill's second." ; } //Use this function to 'write' your information in the windows title bar char* putTitleInfo(void) { //init once only if (myTitle==NULL) { myTitle = new char[50]; } sprintf(myTitle, "Neill's 2nd plug-in peak: %d.", maxPeak); return myTitle; } char* putVisName(void) { return "Neill's Second Winamp Vis!"; } //this is the resize function //used when the window is resized! // REMEMBER TO UPDATE THE variables width and height here!!! void resizeGL(GLsizei w, GLsizei h) { //this makes sure that the rest of the application knows that our window has changed size width = w ; height = h ; //protects from divide by zero if (h==0) { h = 1; } //viewport covers the whole window glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //orthographic viewing equal to the window of our program //means that the origin is at the lower left corner of the window //and that there is a 1 to 1 mapping between our (world) coordinates and the pixels on the screen //eg: to make a sphere 100 pixels wide you would write // gluSphere(gluNewQuadric(), 100 ,20,20) ; // //the depth is 200 'pixels' wide //from -100 to 100 glOrtho(0.0,w, 0.0, h, -100.0,100.0) ; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void neillObjInit() { spinner = new Spinner(NBVector(width/2, height/2, 0)); textboy = new TextBoy(); } //opengl's initialisation function int initGL(GLvoid) { //set opengl to smooth shade objects glShadeModel(GL_SMOOTH); //background color is black glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //enable opengl's depth testing facilities glEnable(GL_DEPTH_TEST); neillObjInit(); return TRUE ; } //This the render function //Changing this function results in different visualizations!!! int render(struct winampVisModule *this_mod) { //clear the scrren and the depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //make opengl to draw polygons instead of points glPolygonMode(GL_FRONT,GL_FILL) ; //left channel, use random low band's strength to scale int amp = this_mod->spectrumData[0][10]; if (amp > maxPeak) { maxPeak = amp; } spinner->scaleOrbitRadiusTemp((4* amp/255.0) + 0.5); spinner->update(); spinner->draw(); for (int p = 1; p < 512; p++) { int age = spectrumDataPeakAge[p]; int peak = spectrumDataPeaks[p]; int curr = this_mod->spectrumData[0][p]; if (curr>peak) { spectrumDataPeaks[p] = curr; spectrumDataPeakAge[p] = 0; } else { //decay the peak spectrumDataPeaks[p] -= age; if (spectrumDataPeaks[p] < 0 ) { spectrumDataPeaks[p] = 0; } } spectrumDataPeakAge[p]++; } sprintf(myTitle, "Neill's 2nd plug-in peak: %d.", maxPeak); textboy->printString(myTitle); textboy->update(); textboy->draw(); //save the modelview matrix glPushMatrix() ; //start a points based opengl object //color the line orange glColor3f(1.0,0.0,0.0) ; //at each interval, draw a line from base to frequencies value. glBegin(GL_LINES) ; for (int x = 1; x < 512; x++) { glVertex2f((float)x, 0.0) ; glVertex2f((float)x, this_mod->spectrumData[0][x]) ; } glEnd() ; glColor3f(1.0,1.0,1.0) ; //at each interval, draw a line from base to frequencies value. glBegin(GL_POINTS) ; for (int pk= 1; pk < 512; pk++) { glVertex2f((float)pk, spectrumDataPeaks[pk]) ; } glEnd() ; //restore the ransformation matrix glPopMatrix() ; //swap the buffers to draw the scene on the monitor SwapBuffers(memDC); return 0; }
76dcdc536c54fd5d955d6a7b7342dd3a6829e948
74272d8e473da29e57f01598e061103b7557484b
/src/dbengine/datamodels/DataPage.cpp
2dd9901f036a9638f6edf24d1b00de6491828f9e
[]
no_license
lkshminarayanan/OurSQL
513f94f65b4fbd5afa783ec6b3bfe4dea1b7fddb
b2eb5cbae465b6895cd015b7f48eb84a994d5540
refs/heads/master
2021-06-17T03:27:08.957559
2021-04-13T10:46:50
2021-04-13T10:46:50
9,874,255
2
0
null
2021-04-13T10:49:02
2013-05-05T20:40:06
C++
UTF-8
C++
false
false
13,925
cpp
DataPage.cpp
/* * DataPage.cpp * * Created on: Dec 13, 2012 * Author: latchu */ #include "DataPage.h" namespace datamodels { DataPage::DataPage(){ //TODO: New Page. initialize dp obj and write it to page. totalRecords = totalSlots = 0;//no. of slots in the page totalFreeSize = pageSize - sizeof(DataPage);//total size contigFreeSize = totalFreeSize;// the contiguous free space contigFreeSpaceStart = 0;//offset of the start of contiguous free space from 'c' //The Storage Area c = p + sizeof(DataPage); memcpy(p,this,sizeof(DataPage)); writePage(); } DataPage::DataPage(long pid):Page(pid){ DataPage* dp; char* buf = new char[sizeof(DataPage)]; memcpy(buf,p,sizeof(DataPage)); dp = (DataPage*)buf; totalSlots = dp->totalSlots; totalRecords = dp->totalRecords; totalFreeSize = dp->totalFreeSize; contigFreeSize = dp->contigFreeSize; contigFreeSpaceStart = dp->contigFreeSpaceStart; c = p + sizeof(DataPage); printDetails(); delete [] buf; } DataPage::~DataPage() { // TODO Auto-generated destructor stub writeToPage(); } long DataPage::getNextPage() const { return nextPage; } void DataPage::setNextPage(long nextPage) { this->nextPage = nextPage; } char* DataPage::getC(){ return c; } long DataPage::getContigFreeSize() const { return contigFreeSize; } void DataPage::setContigFreeSize(long contigFreeSize) { this->contigFreeSize = contigFreeSize; } int DataPage::getContigFreeSpaceStart() const { return contigFreeSpaceStart; } void DataPage::setContigFreeSpaceStart(int contigFreeSpaceStart) { this->contigFreeSpaceStart = contigFreeSpaceStart; } long DataPage::getPrevPage() const { return prevPage; } void DataPage::setPrevPage(long prevPage) { this->prevPage = prevPage; } long DataPage::getTotalFreeSize() const { return totalFreeSize; } void DataPage::setTotalFreeSize(long totalFreeSize) { this->totalFreeSize = totalFreeSize; } int DataPage::getTotalSlots() const { return totalSlots; } void DataPage::setTotalSlots(int totalSlots) { this->totalSlots = totalSlots; } int DataPage::getTotalRecords() const { return totalRecords; } void DataPage::setTotalRecords(int totalRecords) { this->totalRecords = totalRecords; } //void DataPage::setP(Page* p) { // this->p = p; //} int DataPage::insertRecord(char* record, int size ){ //get DB for the page; // create dbpage and call : DataPage dp = new DataPage(pid);dp.insertRecord; int recLength = size; int slotD_sz = sizeof(SlotDir); int tSize; int slotNumber = 0; vector<SlotDirPtr> sdp; if(totalSlots > totalRecords){ //possible slotID availability tSize = recLength; lg2("@DataPage "<<pageid<<" : Inserting Record in dataPage "<<pageid<<". Space Req. : "<<tSize ); if(totalFreeSize<tSize){//no sufficient space error("@DataPage "<<pageid<<" : No space for inserting. "<<tSize - totalFreeSize<<" more space req."); return -1; } //always iterate between all slots and check for empty slot sdp = SlotDir::getAllSlots(p,totalSlots); int bf_diff, bf_diff_temp;//for bestfit bf_diff = pageSize + 1;//for maximum for(int i=1;i<=totalSlots;i++){ //whatever happens go until we find a perfect fit!. //we need the besttt fittu!. int size = sdp[i]->size; if(size < 0){ size *= -1; if(recLength == size){ //Bingo!perfect fit!.We can break here!! lg2("@DataPage "<<pageid<<" : Found a perfect fit."); slotNumber = i; break; }else if(recLength < size){ //possible candidate bf_diff_temp = size - recLength; if(bf_diff_temp < bf_diff){ bf_diff = bf_diff_temp; slotNumber = i; } } } //ignore empty slot ids here. Take care of that later. } if(slotNumber !=0){ //A winner with already allocated space! lg2("@DataPage "<<pageid<<" : Reusing Slot - "<<slotNumber); SlotDirPtr sd = sdp[slotNumber]; sd->size = recLength; memcpy(c+sd->offset,record,recLength); sd->writeSlot(p,slotNumber); goto UPDATE_PARAMS; }else{ //check if there is contiguous free size to allocate record. if(contigFreeSize < tSize){ //if cfs is less than req size, defragment the page. defragmentPage(); } slotNumber = SlotDir::getEmptySlotID(p,totalSlots); if(slotNumber == 0){//no empty slotID!. //update tSize tSize += SLOT_SZ; lg2("@DataPage "<<pageid<<" : Updated space requirement : "<<tSize); //now have to check if insertion is possible with updated tSize if(tSize<=totalFreeSize){//insertion possible if(tSize>contigFreeSize){ defragmentPage();//happens very rarely. guaranteed called atmost one every insertion. //now insertion is possible } }else{ error("@DataPage "<<pageid<<" : No space for inserting. "<<tSize - totalFreeSize<<" more space req."); return -1; } //update the slotNumber slotNumber = ++totalSlots; lg2("@DataPage "<<pageid<<" : Creating Slot-ID - "<<slotNumber); }else lg2("@DataPage "<<pageid<<" : Reusing Slot-ID - "<<slotNumber); goto START_COPY; } }else{ tSize = slotD_sz + recLength; lg2("@DataPage "<<pageid<<" : Inserting Record in dataPage "<<pageid<<". Space Req. : "<<tSize ); if(totalFreeSize<tSize){//no sufficient space error("@DataPage "<<pageid<<" : No space for inserting. "<<tSize - totalFreeSize<<" more space req."); return -1; } if(contigFreeSize < tSize){ //if cfs is less than req size, defragment the page. defragmentPage(); } slotNumber = ++totalSlots; lg2("@DataPage "<<pageid<<" : Creating Slot-ID - "<<slotNumber); } START_COPY:{ memcpy(c+contigFreeSpaceStart,record,recLength); SlotDirPtr slot = new SlotDir(contigFreeSpaceStart,recLength); slot->writeSlot(p,slotNumber); contigFreeSpaceStart += recLength; contigFreeSize -= tSize; delete slot; } UPDATE_PARAMS: totalFreeSize -= tSize; totalRecords++; writeToPage(); int n = sdp.size(); for(int i=0;i<n;i++){ delete sdp[i]; } return slotNumber;//subam } int DataPage::retrieveRecord(int sid, char *&record){ //SLOT ID starts from 1. int size; if(sid < 1 || sid > totalSlots){//invalid slotid error("Invalid slot id"); record = NULL; return 0; } lg2("Accessing slot "<<sid); SlotDirPtr sdp = new SlotDir(p,sid); if(sdp->size <= 0){//deleted record error("Invalid slot id (deleted id)"); record = NULL; delete sdp; return 0; } record = new char[sdp->size+1]; memcpy(record,c+sdp->offset,sdp->size); record[sdp->size] = '\0'; size = sdp->size; delete sdp; return size;//Subam } int DataPage::deleteRecord(int sid){ if(sid < 1 || sid > totalSlots){//invalid slotid error("Invalid slot id"); return 0; } SlotDirPtr sdp = new SlotDir(p,sid); if(sdp->size <= 0){//already deleted lg("Slot "<<sid<<" already deleted"); return 1; } totalFreeSize += sdp->size; totalRecords--; sdp->size *= -1; sdp->writeSlot(p,sid); lg("Record at slot "<<sid<<" deleted"); writeToPage(); delete sdp; return 1; } int DataPage::defragmentPage(){ lg("Defragmenting page "<<pageid); if(totalFreeSize == contigFreeSize) lg("Defrag not required."); vector<SlotDirPtr> sdp = SlotDir::getAllSlots(p,totalSlots); int i; SlotDirPtr sd; flag lastEmptySlot = 0;//to find out the last consecutive empty slots and delete them. char *locHead = new char[pageSize-sizeof(DataPage)]; char *loc = locHead; int totalLen = 0; for(i=1;i<=totalSlots;i++){ sd = sdp[i]; if(sd->size > 0){ // lg2("Rewriting rec "<<i); memcpy(loc,c+sd->offset,sd->size); sd->offset = loc - locHead; loc += sd->size; totalLen += sd->size; lastEmptySlot = 0; }else{ // lg2("Ignoring rec "<<i); sd->offset = 0; sd->size = 0; if(lastEmptySlot == 0) lastEmptySlot = i; } sd->writeSlot(p,i); } if(lastEmptySlot != 0){ totalFreeSize += ((totalSlots - lastEmptySlot + 1)*sizeof(SlotDir)); totalSlots = lastEmptySlot - 1; } contigFreeSpaceStart = loc - locHead; contigFreeSize = totalFreeSize; memcpy(c,locHead,totalLen); delete[] locHead; int n = sdp.size(); for(i=0;i<n;i++){ delete sdp[i]; } writeToPage(); return 1; } void DataPage::printDetails(){ lg2("DataPage"); lg2("Page : "<< pageid); lg2("TFS : " << totalFreeSize); lg2("CFS : " << contigFreeSize); lg2("Total slots : "<<totalSlots); lg2("Records : "<<totalRecords); lg2(""); } int DataPage::retrieveRecords(RecordSet *rs,Select* select,Where* where){ if(totalRecords == 0){ lg2("@DataPage_"<<pageid<<" : No Records to retrieve"); return 0; } int recSize; char *recStr; Record *record; int noOfRecs = 0; int *attrType_table = select->getTableAttrType(); int numOfAttr_table = select->getTableNumOfAttr(); for(int i=select->getStartSlotId();i<=totalSlots;i++){ recSize = retrieveRecord(i,recStr); if (recSize!=0){ record = new Record(attrType_table,recStr,numOfAttr_table,recSize); if(where->testRecord(record)){ lg2("Adding Record "<<i<<" from Page "<<pageid); rs->addRecord(select->project(record,pageid,i)); noOfRecs ++; }else{ delete record; } } if(select->getLimit()!=0&&noOfRecs >= select->getLimit()){ select->setStartSlotID(i+1); select->thereIsMore(); return noOfRecs; } delete[] recStr; } if(select->getLimit()!=0) select->setLimit(select->getLimit()-noOfRecs); if(select->isThereMore()){ //reset select's hasMore Parameters select->initializeStartParams(); } return noOfRecs; } int DataPage::deleteRecords(Where *where,int* attrType, int numOfAttr){ if(totalRecords == 0){ lg2("@DataPage_"<<pageid<<" : No Records to delete"); return 0; } int noOfRecs = 0; int recSize; char *recStr; Record* record; for(int i=1;i<=totalSlots;i++){ recSize = retrieveRecord(i,recStr); if (recSize!=0){ record = new Record(attrType,recStr,numOfAttr,recSize); //TODO : check for valid records here! if(where->testRecord(record)){ lg2("Deleting Record "<<i<<" from Page "<<pageid); deleteRecord(i); noOfRecs ++; } delete record; } delete[] recStr; } writeToPage(); return noOfRecs; } int DataPage::updateRecords(Where *where,Modify *modify, RecordSet* rs){ if(totalRecords == 0){ lg2("@DataPage_"<<pageid<<" : No Records to delete"); return 0; } int noOfRecs = 0; int recSize; char *recStr; Record* record; for(int i=modify->getStartSlotID();i<=totalSlots;i++){ recSize = retrieveRecord(i,recStr); if (recSize!=0){ record = new Record(modify->getAttrType(),recStr,modify->getNumOfAttr(),recSize); //check for valid records here! if(where->testRecord(record)){ lg2("Updating and deleting Record "<<i<<" from Page "<<pageid); rs->addRecord(modify->updateRecord(record)); deleteRecord(i); noOfRecs ++; }else{ delete record; } } if(noOfRecs == modify->getLimit()){ writeToPage(); modify->thereIsMore(); modify->setStartSlotID(i+1); return noOfRecs; } delete[] recStr; } writeToPage(); modify->resetMoreFlag(); return noOfRecs; } void DataPage::writeToPage(){ memcpy(p,this,sizeof(DataPage)); writePage(); } /* * Slot Directory definitions * */ SlotDir::SlotDir(){} SlotDir::SlotDir(long oset,int sz){ offset = oset; size = sz; } SlotDir::SlotDir(char* buf, int sid){ char* slotLoc = buf + pageSize - sid*SLOT_SZ; char* slot = new char[ sizeof(SlotDir) ] ; memcpy(slot,slotLoc,sizeof(SlotDir)); SlotDirPtr sdp = (SlotDirPtr)slot; offset = sdp->offset; size = sdp->size; delete []slot; } int SlotDir::writeSlot(char* buf, int sid){ char* slot_entry = buf + pageSize - (sid)*SLOT_SZ; memcpy(slot_entry,this,sizeof(SlotDir)); return 1; } vector<SlotDirPtr> SlotDir::getAllSlots(char* buf, int totalSlots){ char* slotLoc = buf + pageSize - SLOT_SZ;//slot no. 1! int i = 1; char* slot; SlotDirPtr sdp; vector<SlotDirPtr> sDir; sDir.push_back(new SlotDir());//dummy slot to make 0 - totalslots-1 to 1 - totalSlots for (i=1;i<=totalSlots;i++,slotLoc = slotLoc - sizeof(SlotDir)){ slot = new char[ sizeof(SlotDir) ] ; memcpy(slot,slotLoc,sizeof(SlotDir)); sdp = (SlotDirPtr)slot; sDir.push_back(new SlotDir(sdp->offset,sdp->size)); delete[] slot; } return sDir; } void SlotDir::printAllSlots(char* buf, int totalSlots){ char* slotLoc = buf + pageSize - SLOT_SZ;//slot no. 1! int i = 1; char* slot = new char[ sizeof(SlotDir) ] ;; SlotDirPtr sdp; for (i=1;i<=totalSlots;i++,slotLoc = slotLoc - sizeof(SlotDir)){ memcpy(slot,slotLoc,sizeof(SlotDir)); sdp = (SlotDirPtr)slot; cout << endl<< "Slot "<<i<<" - Offset "<<sdp->offset<<" - Size "<<sdp->size; } } int SlotDir::getEmptySlotID(char* buf,int totalSlots){ char* slotLoc = buf + pageSize - SLOT_SZ;//slot no. 1! int i = 1; char* slot = new char[ sizeof(SlotDir) ] ; SlotDirPtr sdp; for (i=1;i<=totalSlots;i++,slotLoc = slotLoc - sizeof(SlotDir)){ memcpy(slot,slotLoc,sizeof(SlotDir)); sdp = (SlotDirPtr)slot; if(sdp->size == 0){ delete[] slot; return i; } } delete[] slot; return 0; } } /* namespace datamodels */ //using namespace datamodels; //int main(){ // // // // DataPage *dp = new DataPage(1); // // DataPage *dp = new DataPage(); // // char elements[][20] = { // "January", // "February", // "March",//3 // "April", // "May", // "June",//6 // "July", // "August", // "September",//9 // "October", // "November", // "December",//12 // "Sunday", // "Monday", // "Tuesday",//15 // "Wednesday", // "Thursday", // "Friday",//18 // "Saturday" // }; // // for(int i=0;i<140;i++){ // dp->insertRecord(elements[i%19]); // } // // // dp->deleteRecord(135); // dp->deleteRecord(136); // dp->deleteRecord(16); // dp->deleteRecord(121); // dp->deleteRecord(89); // dp->deleteRecord(101); // // char test[] = "1234"; // dp->insertRecord(test); // dp->printDetails(); // // dp->defragmentPage(); // dp->printDetails(); // // dp->printAllRecords(); // // SlotDir::printAllSlots(dp->getPage(),dp->getTotalSlots()); // // return 0; // //}
8868e0b4ff61c79c3629b3b383ff9860f9ee977d
67fc9e51437e351579fe9d2d349040c25936472a
/wrappers/7.0.0/vtkGeoMathWrap.h
1ca74ab8f4a5db46920f76f93f726215122e39a6
[]
permissive
axkibe/node-vtk
51b3207c7a7d3b59a4dd46a51e754984c3302dec
900ad7b5500f672519da5aa24c99aa5a96466ef3
refs/heads/master
2023-03-05T07:45:45.577220
2020-03-30T09:31:07
2020-03-30T09:31:07
48,490,707
6
0
BSD-3-Clause
2022-12-07T20:41:45
2015-12-23T12:58:43
C++
UTF-8
C++
false
false
1,478
h
vtkGeoMathWrap.h
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKGEOMATHWRAP_H #define NATIVE_EXTENSION_VTK_VTKGEOMATHWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkGeoMath.h> #include "vtkObjectWrap.h" #include "../../plus/plus.h" class VtkGeoMathWrap : public VtkObjectWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkGeoMathWrap(vtkSmartPointer<vtkGeoMath>); VtkGeoMathWrap(); ~VtkGeoMathWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void DistanceSquared(const Nan::FunctionCallbackInfo<v8::Value>& info); static void EarthRadiusMeters(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info); static void LongLatAltToRect(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKGEOMATHWRAP_CLASSDEF VTK_NODE_PLUS_VTKGEOMATHWRAP_CLASSDEF #endif }; #endif
dee65b45f54d4cdd496965e18868ac22fad7c8d8
437a65e090f201e75e9b8962d064d52c4bbd53d1
/Source_Code/Test Case/Sod Shock Tube/idealgas.h
a1f8da434b4b5b937ce13a2be6d7c78456180224
[]
no_license
SulemanMahmood/PlasmaCombustion
8033d33cafa5634a024227ffed041ca0a3b6c734
8e5fd1ef5f61f18a5800bf087768c163a231d713
refs/heads/master
2021-05-01T21:38:19.356499
2016-12-18T23:18:41
2016-12-18T23:18:41
70,857,633
0
3
null
null
null
null
UTF-8
C++
false
false
479
h
idealgas.h
#ifndef IDEALGAS_H_ #define IDEALGAS_H_ #include "structdef.h" #include "vecdef.h" class IDEALGAS{ public: void gaslaw(double3D p, flow3D a, int ndiv){ for (int x = 0; x < ndiv; x++){ for (int y = 0; y < ndiv; y++){ for (int z = 0; z < ndiv; z++){ p[x][y][z] = (gam-1)*a[x][y][z].r*(a[x][y][z].E - 0.5*(a[x][y][z].u*a[x][y][z].u + a[x][y][z].v*a[x][y][z].v + a[x][y][z].w*a[x][y][z].w)); } } } } } #endif
9c60bbd7ed4fcfd5041b5d165d3bb28e86340d84
2b178aada541780df0559e899877240666cf1fc0
/src/drawing/Gameplay.h
a318f5ccec9115953f57c36c9f210638601fdf8e
[ "MIT" ]
permissive
andystanton/lana-snake
7529fa2c962abad0370d67207ad8506f52c9590a
3778a4fa552a2471a64623edbf1a52e1011cda68
refs/heads/master
2021-07-01T20:04:34.848084
2017-01-09T09:16:18
2017-01-09T09:16:18
16,258,713
1
0
null
2014-03-04T09:25:19
2014-01-26T18:28:57
C++
UTF-8
C++
false
false
481
h
Gameplay.h
// // Gameplay.h // lanaSnake // // Created by Andy Stanton on 19/06/2013. // Copyright (c) 2013 Andy Stanton. All rights reserved. // #ifndef __lanaSnake__Gameplay__ #define __lanaSnake__Gameplay__ #include "GLFW/glfw3.h" #include "Primitive.h" #include "../model/entity/Drawable.h" class Gameplay { public: static void drawPause(GLfloat width); static void draw(Drawable*); static void draw(Drawable*, GLint); }; #endif /* defined(__lanaSnake__Gameplay__) */
cf06619349064e128a1f11201e0a76d4868a01be
9b0aa02cc2f865e6cfa1d2b197bb20128ce8302c
/rtc_millis.cpp
9fba2b6ea25bd138d6aa4fcf2d7284b90c7e4054
[]
no_license
ampolez/CarPCBoard
327ce177b8dc77d60becdaeeba49af84464171af
5bde637cb216036e761bebcf1c1a8e2e9975ea90
refs/heads/master
2021-01-01T18:56:42.485623
2017-07-26T21:02:58
2017-07-26T21:02:58
98,465,804
0
0
null
null
null
null
UTF-8
C++
false
false
1,813
cpp
rtc_millis.cpp
/* * TestTimer_AVRCpp.cpp * Author: ampolez */ #include <avr/io.h> #include <avr/interrupt.h> #include <util/atomic.h> #include "rtc_millis.h" extern "C" { #include "rtc.h" #include "twi.h" } static volatile rtc_millis_t msCount = 0; /* * Настройка портов и прерываний. * Подготовка перефирийного оборудования */ void rtc_millis_init(void) { // Настройки порта для подключения сигнала SQW таймера RTC_DDR &= ~(1 << RTC_SQW_PIN); // Порт таймера является входом RTC_PORT |= (1 << RTC_SQW_PIN); // Включен подтягивающий резистор // Настройка прерываний EICRA |= (1 << ISC01); // Прерывание INT0 срабатывает при спаде сигнала EIMSK |= (1 << INT0); // Активация прерывания INT0 sei(); twi_init_master(); // Инициализации шины I2c rtc_SQW_enable(true); // Запуск генератора rtc_SQW_set_freq(FREQ_1024); // Установка частоты меандра 1024Гц } /* * Функция, возвращающая количество миллисекунд с момента запуска счетчика */ rtc_millis_t rtc_millis(void) { rtc_millis_t ms; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ms = msCount; } return ms; } /* * Функция для сброса счетчика миллисекунд */ void rtc_millis_reset(void) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { msCount = 0; } } /* * Обработка прерывания по счетчику тиков от часов */ ISR(INT0_vect) { ++msCount; // Увеличение счетчика миллисекунд }
2c00c3d18326f9dd7f0cb362c9f9f483556e9cb6
a32fd8cdadc6e2e6cc42beba8ef7c98b80d46ac0
/eul+/euler0002.cpp
b8f1e8ca84e9eb250719458cb7b8981d66256694
[]
no_license
DavieV/hacker-rank
0b4aef7248f8ab9a18d8556c5804d3ce040d6cc1
05da18dffeda3be73780edcbb26e6a0bdb760151
refs/heads/master
2021-07-20T22:52:33.585411
2016-10-04T21:49:18
2016-10-04T21:49:18
37,431,398
0
1
null
2016-10-04T21:49:19
2015-06-14T22:06:41
C++
UTF-8
C++
false
false
511
cpp
euler0002.cpp
#include <iostream> long long sum(long long n); int main() { int t; long long n; std::cin >> t; for (int i = 0; i < t; ++i) { std::cin >> n; std::cout << sum(n) << std::endl; } } long long sum(long long n) { if (n < 2) return 0; long long p1 = 1, p2 = 2; long long cur = 3; long long sum = 2; while (cur <= n) { if (cur % 2 == 0) sum += cur; p1 = p2; p2 = cur; cur = p1 + p2; } return sum; }
f209bc5736a14f033dcad611b84ff78095158b42
6691bd2a31b68a2edd899ab74f130b85680efd6c
/input.h
5fb1d5d3d039554eedbda7b1d4538017879329c4
[]
no_license
Suzuki01/RhythmGame
301f82defc736ee6249dfaa126771a45354177db
abe1c6c04008a6b99656e0a9ff3164caecf930ae
refs/heads/master
2020-06-18T15:08:18.154305
2019-09-08T04:42:00
2019-09-08T04:42:00
196,341,507
1
0
null
2019-09-08T04:42:00
2019-07-11T07:21:47
C++
UTF-8
C++
false
false
360
h
input.h
#pragma once #include "model.h" #include "camera.h" #define NUM_KEY_MAX (256) class Input { public: static BYTE key[256]; static BYTE releaseKey[256]; static BYTE triggerKey[256]; static bool Keyboard_IsPress(int nKey); static bool Keyboard_IsTrigger(int nKey); static bool Keyboard_IsRelease(int nKey); static void Init(); static void Update(); };
9c0e80f4611ce996346c1f849e43688fe8283384
4ffdc4341ce50d462dc9ed0198691b9aa5f2d0ba
/week-06/day-4/12.cpp
eeabe14fff74f8850fd913ec17f62bd8428a8423
[]
no_license
greenfox-zerda-sparta/Akatakata
b1289cc176a88f5e51133e4e723e97ad9a71e402
a4a7f464c66582568c238eea7b98ecc949f87c05
refs/heads/master
2021-01-12T18:14:53.086793
2017-02-14T14:32:17
2017-02-14T14:32:17
71,350,782
0
0
null
null
null
null
UTF-8
C++
false
false
1,031
cpp
12.cpp
#include <iostream> #include <vector> using namespace std; void increase_inner_element(vector<vector<int>>& vect, int selector, int elem_selector) { vect[selector - 1][elem_selector - 1] += 1; } void print_outer_vector(const vector < vector<int>>& vect) { for (unsigned int i = 0; i < vect.size(); i++) { for (unsigned int j = 0; j < vect[i].size(); j++) { cout << vect[i][j] << " "; } } cout << endl; } int main() { //create a vector of vector of integers //the inner vectors have 5 integers, all of them 0 //the outer vector is holding 5 vector //create a function which increase a specific element of an inner vector by 1 vector<vector<int>> outer(5); vector<int> v1(5, 0); vector<int> v2(5, 0); vector<int> v3(5, 0); vector<int> v4(5, 0); vector<int> v5(5, 0); outer = { v1, v2, v3, v4, v5 }; int select_vector = 3; // select v3 int select_elem = 2; // 2nd element in v3 increase_inner_element(outer, select_vector, select_elem); print_outer_vector(outer); return 0; }
307638df2b2f0120cdbaa5f2153d1b5f3da8b733
163dbd5d3461de2fa3623384a38ed19b8effba50
/Practicas C++/Programa De los Boletos.cpp
cfd00d7b4b007fbf295bb516b03c90333f8ee415
[]
no_license
Alane-Tc/Practicas_Universidad
4da566dddf0a5931d9f860018ae8ce59afa114ac
a26224d2ce99cb1f2b2c4d7484da16bea2406ba0
refs/heads/master
2023-04-30T23:38:49.302160
2021-05-24T03:42:38
2021-05-24T03:42:38
298,710,686
0
0
null
null
null
null
ISO-8859-1
C++
false
false
880
cpp
Programa De los Boletos.cpp
#include <iostream> using namespace std; int main () { char tipoBoletoSeleccionado; char resultado; do { cout<<"Selecciona El boleto Que Desea"<<endl; cout<<endl; cout<<"Seleciona El Boleto Que Desea"<<endl; cout<<"A=Adulto N=Niños I=Adultos Con Credencial"<<endl; cin>>tipoBoletoSeleccionado; if (tipoBoletoSeleccionado== 'A'||tipoBoletoSeleccionado=='a') { cout<<"El boleto De Adulto Cuesta 120"<<endl; } else if(tipoBoletoSeleccionado=='N' || tipoBoletoSeleccionado=='n') { cout<<"El boleto De Niño Cuesta 75"<<endl; } else if(tipoBoletoSeleccionado=='I'||tipoBoletoSeleccionado=='i') { cout<<"El boleto De Los Adultos Con CREDENCIAL cuesta 60"<<endl; } cout<<endl; cout<<"¿Queres Comprar Otro Boleto?"<<endl; cout<<endl; cout<<"Y=Si y N=No"<<endl; cout<<endl; cin>>resultado; } while(resultado =='y') ; cout<<"Lo sentimos, se agotaron los boletos XD"<<endl; return 0; }
96e3d8971b1df0b97ef2de2186b23b66b566c667
3df170eeee0432d9594c6d12e1f60b587ec931f5
/P11_7/P11_7/main.cpp
22f0fd84edd06831c412f32e72f4930f4c45ffe2
[]
no_license
Rakatashii/cpp_ch11
21847b27631d1ba21201b10c0c08f37c82f1d434
0d83b6815b1c17b95e57b7d91139e23cf6b7cdc5
refs/heads/master
2020-04-07T10:19:35.198902
2018-11-25T06:53:27
2018-11-25T06:53:27
158,282,756
0
0
null
null
null
null
UTF-8
C++
false
false
3,784
cpp
main.cpp
/* Exercise P11.7. Use the modification of the binary search function from Exercise P11.6 to sort a vector. Make a second vector of the same size as the vector to be sorted. For each element in the first vector, call binary search on the second vector to find out where the new element should be inserted. Then move all elements above the insertion point up by one slot and insert the new element. Thus, the second vector is always kept sorted. Implement this algorithm and measure its performance. */ #include <iostream> #include <vector> #include <string> #include <cmath> #include "util.hpp" using namespace std; static int max_value; int partition(vector<int> &v, int from, int to); void quicksort(vector<int> &v, int from, int to); bool binary_search(vector<int> &v, int from, int to, int target, int &m); void insert(vector<int> &v, int new_val, int pos, bool resize = false); int main(int argc, const char * argv[]) { UTIL::rand_seed(); int vsz = 50; vector<int> v(vsz); max_value = 100; for (int i = 0; i < vsz; i++){ int x = UTIL::rand_int(1, max_value); //if (x == 0) cout << "WARNING x in v = 0"; v[i] = x; } int usz = vsz/2; vector<int> u(usz); for (int i = 0; i < usz; i++){ int x = UTIL::rand_int(1, max_value); //if (x == 0) cout << "WARNING x in u = 0"; u[i] = x; } UTIL::print_two_vectors(v, u, "(before binary searches) v", "u"); cout << "\n"; quicksort(v, 0, vsz-1); vector<int> positions; int m; for (int i = 0; i < usz-1; i++){ m = -1; binary_search(v, 0, v.size()-1, u[i], m); if (m < v.size()) insert(v, u[i], m, true); else cout << "(m > v.size())" << endl; } cout << "\n"; UTIL::print_two_vectors(v, u, "(after binary searches) v", "u"); cout << "\n"; return 0; } int partition(vector<int> &v, int from, int to){ int p = v[from]; int i = from-1; int j = to+1; while(i<j){ i++; while (v[i] < p) i++; j--; while (v[j] > p) j--; if (i < j) UTIL::swap(v[i], v[j]); } return j; } void quicksort(vector<int> &v, int from, int to){ if (from >= to) return; int p = partition(v, from, to); quicksort(v, from, p); quicksort(v, p+1, to); } bool binary_search(vector<int> &v, int from, int to, int target, int &m){ if (from >= to) { /* if (abs(v[from] - target) <= abs(v[to] - target)) m = from; else */ m = to; return false; } if (m == -1 && target > max_value){ // m is initialized at -1 so that the first BS call can be recognized. At this point, since the vector is sorted, if the highest value in the vector is already greater that the target value, BS returns the size of the vector. Strangely, v[v.size()] is returning 0. Don't think I should take purposefully though. cout << "TARGET " << target << " is less than v[to]: v[" << to << "] = " << v[to] << endl; m = v.size(); cout << "m = " << m << endl; return false; } int mid = (from + to) / 2; if (v[mid] == target) { m = mid; return true; } else if (v[mid] > target) return binary_search(v, from, mid, target, m); else return binary_search(v, mid+1, to, target, m); } void insert(vector<int> &v, int new_val, int pos, bool resize){ if (v[v.size()-1] <= 0 || v[v.size()-1] > max_value || resize){ cout << "v.size() increased from " << v.size(); v.push_back(new_val); cout << " to " << v.size() << endl; cout << "inserting " << new_val << " at index " << pos << endl; } for (int i = v.size()-1; i > pos; i--){ v[i] = v[i-1]; } v[pos] = new_val; }
0cfab671bf0d65ad0628f43657e75fb2ef8e0bf1
89b35d45e04df288bca5681242da4a1bda3f34ee
/factor_SVD.h
63e78c2e56ceb3b5f5e34e690a91badb5e767c57
[]
no_license
JCatwood/SKP_CGKT
7ae8e0e8ed0b9702321b39e09453589cadd055eb
2b6ca8ac4f74fe923fed0700e308c8ca86980dd5
refs/heads/master
2023-01-31T09:58:13.495333
2020-12-14T13:24:35
2020-12-14T13:24:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,100
h
factor_SVD.h
#ifndef FACTOR_SVD_H #define FACTOR_SVD_H #include <vector> #include "Dense" /* The new class stores the number of factors as well as the factors' number of rows/columns Each column of the Matrix stores one factor */ class TreeNode { public: unsigned int num_term; int U_num_row; int U_num_col; int V_num_row; int V_num_col; Eigen::MatrixXd U; Eigen::MatrixXd V; Eigen::MatrixXd uncompress(); TreeNode(){} ~TreeNode(){} }; TreeNode comp_UV_SVD(const Eigen::MatrixXd& mat, int row_offset, int col_offset, int blk_sz, int V_num_row, int V_num_col, double abs_tol, unsigned int max_num_term, double* sing_val, double& err); TreeNode comp_UV_SVD_prescribed(const Eigen::MatrixXd& mat, int row_offset, int col_offset, int blk_sz, int V_num_row, int V_num_col, const Eigen::MatrixXd& QU, const Eigen::MatrixXd& QV, int U_num_constraint, int V_num_constraint, double abs_tol, unsigned int max_num_term, double* sing_val, double& err); Eigen::MatrixXd rearrange(const double* mat , int lead_dim , int dim , int blk_num_row , int blk_num_col); TreeNode factorize_dense_SVD(Eigen::MatrixXd& mat , int U_num_row , int U_num_col , int V_num_row , int V_num_col , double abs_tol , unsigned int max_num_term, double* sing_val , double& err); void qr_full(Eigen::MatrixXd& A , Eigen::MatrixXd& Q , Eigen::MatrixXd& R); void qr_full(Eigen::MatrixXd& A , Eigen::MatrixXd& Q); void qr(Eigen::MatrixXd& A , Eigen::MatrixXd& R); TreeNode TreeNode_add_SVD(const TreeNode& node1 , const TreeNode& node2 , double abs_tol); int cholesky(Eigen::MatrixXd& A); int inverse(Eigen::MatrixXd &A); #endif
c0b018b801f4e9103ea5ea6bc1c605f651256022
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/com/netfx/src/framework/xsp/inc/names.h
c7791f46dec92e4d1182f969551b99746adae991
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
15,403
h
names.h
/** * names.h * * Names of files, registry keys, etc. * * Copyright (c) 1998-1999, Microsoft Corporation * */ #ifdef __cplusplus #pragma once #endif #include "fxver.h" #define PRODUCT_TOKEN_3(x, y) x ## y #define PRODUCT_TOKEN_2(x, y) PRODUCT_TOKEN_3(x, y) #define PRODUCT_TOKEN(y) PRODUCT_TOKEN_2(ASPNET_NAME_PREFIX, y) #define PRODUCT_TOKEN_NO_SUFFIX(y) PRODUCT_TOKEN_2(ASPNET_NAME_PREFIX_NO_SUFFIX, y) #define PRODUCT_STRING(z) QUOTE_MACRO(PRODUCT_TOKEN(z)) #define PRODUCT_STRING_L(z) QUOTE_MACRO_L(PRODUCT_TOKEN(z)) #define PRODUCT_STRING_NO_SUFFIX(z) QUOTE_MACRO(PRODUCT_TOKEN_NO_SUFFIX(z)) #define PRODUCT_STRING_NO_SUFFIX_L(z) QUOTE_MACRO_L(PRODUCT_TOKEN_NO_SUFFIX(z)) /* * Product name */ #define PRODUCT_NAME "ASP.NET" #define PRODUCT_NAME_L L"ASP.NET" #if ASPNET_PRODUCT_IS_REDIST == 1 #define ASPNET_FLAVOR_STRING "" #define ASPNET_FLAVOR_STRING_L L"" #else #define ASPNET_FLAVOR_STRING QUOTE_MACRO(ASPNET_FLAVOR) #define ASPNET_FLAVOR_STRING_L QUOTE_MACRO_L(ASPNET_FLAVOR) #endif /* * Module names. */ #define ISAPI_MODULE_LIBRARY_NAME PRODUCT_TOKEN(isapi) #define ISAPI_MODULE_FULL_NAME PRODUCT_STRING(isapi.dll) #define ISAPI_MODULE_FULL_NAME_L PRODUCT_STRING_L(isapi.dll) #define ISAPI_MODULE_FULL_NAME_TOKEN PRODUCT_TOKEN(isapi.dll) #define ISAPI_MODULE_BASE_NAME PRODUCT_STRING(isapi) #define ISAPI_MODULE_BASE_NAME_L PRODUCT_STRING_L(isapi) #define PERF_MODULE_FULL_NAME PRODUCT_STRING(perf.dll) #define PERF_MODULE_FULL_NAME_L PRODUCT_STRING_L(perf.dll) #define PERF_MODULE_FULL_NAME_TOKEN PRODUCT_TOKEN(perf.dll) #define PERF_MODULE_BASE_NAME PRODUCT_STRING(perf) #define PERF_MODULE_BASE_NAME_L PRODUCT_STRING_L(perf) #define PERF_INI_FULL_NAME PRODUCT_STRING(perf.ini) #define PERF_INI_FULL_NAME_L PRODUCT_STRING_L(perf.ini) #define PERF_INI_COMMON_FULL_NAME PRODUCT_STRING(perf2.ini) #define PERF_INI_COMMON_FULL_NAME_L PRODUCT_STRING_L(perf2.ini) #define RC_MODULE_FULL_NAME PRODUCT_STRING(rc.dll) #define RC_MODULE_FULL_NAME_L PRODUCT_STRING_L(rc.dll) #define RC_MODULE_BASE_NAME PRODUCT_STRING(rc) #define RC_MODULE_BASE_NAME_L PRODUCT_STRING_L(rc) #define STATE_MODULE_FULL_NAME PRODUCT_STRING(state.exe) #define STATE_MODULE_FULL_NAME_L PRODUCT_STRING_L(state.exe) #define STATE_MODULE_FULL_NAME_TOKEN PRODUCT_TOKEN(state.exe) #define STATE_MODULE_BASE_NAME PRODUCT_STRING(state) #define STATE_MODULE_BASE_NAME_L PRODUCT_STRING_L(state) #define WEB_MODULE_FULL_NAME "System.Web.dll" #define WEB_MODULE_FULL_NAME_L L"System.Web.dll" #define WEB_MODULE_BASE_NAME "System.Web" #define WEB_MODULE_BASE_NAME_L L"System.Web" #define WP_MODULE_FULL_NAME PRODUCT_STRING(wp.exe) #define WP_MODULE_FULL_NAME_L PRODUCT_STRING_L(wp.exe) #define WP_MODULE_BASE_NAME PRODUCT_STRING(wp) #define WP_MODULE_BASE_NAME_L PRODUCT_STRING_L(wp) #define WININET_MODULE_FULL_NAME "wininet.dll" #define WININET_MODULE_FULL_NAME_L L"wininet.dll" #define PERF_H_FULL_NAME < PRODUCT_TOKEN(perf.h) > #define ASPNET_CONFIG_FILE PRODUCT_STRING_NO_SUFFIX(.config) #define ASPNET_CONFIG_FILE_L PRODUCT_STRING_NO_SUFFIX_L(.config) #define FILTER_NAME QUOTE_MACRO(CONCAT_MACRO(ASP.NET_, VER_DOTPRODUCTVERSION)) #define FILTER_NAME_L QUOTE_MACRO_L(CONCAT_MACRO(ASP.NET_, VER_DOTPRODUCTVERSION)) #define FILTER_MODULE_LIBRARY_NAME PRODUCT_TOKEN(filter) #define FILTER_MODULE_FULL_NAME PRODUCT_STRING(filter.dll) #define FILTER_MODULE_FULL_NAME_L PRODUCT_STRING_L(filter.dll) #define FILTER_MODULE_FULL_NAME_TOKEN PRODUCT_TOKEN(filter.dll) #define FILTER_MODULE_BASE_NAME PRODUCT_STRING(filter) #define FILTER_MODULE_BASE_NAME_L PRODUCT_STRING_L(filter) #define PRODUCT_DESCRIPTION QUOTE_MACRO(CONCAT_MACRO(ASP.NET_, VER_DOTPRODUCTVERSION)) #define PRODUCT_DESCRIPTION_L QUOTE_MACRO_L(CONCAT_MACRO(ASP.NET_, VER_DOTPRODUCTVERSION)) #define IIS_GROUP_ID_L QUOTE_MACRO_L(CONCAT_MACRO(ASP.NET v, VER_DOTPRODUCTVERSIONNOQFE)) #define IIS_APP_NAME_L IIS_GROUP_ID_L #define IIS_APP_DESCRIPTION_L IIS_GROUP_ID_L #define IIS_GROUP_ID_PREFIX_L L"ASP.NET v" /* * Service names. */ #define STATE_SERVICE_NAME "aspnet_state" #define STATE_SERVICE_NAME_L L"aspnet_state" #define W3SVC_SERVICE_NAME "w3svc" #define W3SVC_SERVICE_NAME_L L"w3svc" #define IISADMIN_SERVICE_NAME "iisadmin" #define IISADMIN_SERVICE_NAME_L L"iisadmin" #define PERF_SERVICE_PREFIX_L L"ASP.NET" #define PERF_SERVICE_PREFIX_LENGTH 7 #define PERF_SERVICE_VERSION_NAME QUOTE_MACRO(CONCAT_MACRO(ASP.NET_, VER_DOTPRODUCTVERSIONNOQFE)) #define PERF_SERVICE_VERSION_NAME_L QUOTE_MACRO_L(CONCAT_MACRO(ASP.NET_, VER_DOTPRODUCTVERSIONNOQFE)) /* * Registry keys */ #define REGPATH_MACHINE_APP "Software\\Microsoft\\ASP.NET" #define REGPATH_MACHINE_APP_L L"Software\\Microsoft\\ASP.NET" #define REGPATH_SERVICES_KEY_L L"SYSTEM\\CurrentControlSet\\Services\\" #define REGPATH_PERF_VERSIONED_ROOT_KEY "SYSTEM\\CurrentControlSet\\Services\\" PERF_SERVICE_VERSION_NAME #define REGPATH_PERF_VERSIONED_ROOT_KEY_L L"SYSTEM\\CurrentControlSet\\Services\\" PERF_SERVICE_VERSION_NAME_L #define REGPATH_PERF_VERSIONED_PERFORMANCE_KEY "SYSTEM\\CurrentControlSet\\Services\\" PERF_SERVICE_VERSION_NAME "\\Performance" #define REGPATH_PERF_VERSIONED_PERFORMANCE_KEY_L L"SYSTEM\\CurrentControlSet\\Services\\" PERF_SERVICE_VERSION_NAME_L L"\\Performance" #define REGPATH_PERF_VERSIONED_NAMES_KEY "SYSTEM\\CurrentControlSet\\Services\\" PERF_SERVICE_VERSION_NAME "\\Names" #define REGPATH_PERF_VERSIONED_NAMES_KEY_L L"SYSTEM\\CurrentControlSet\\Services\\" PERF_SERVICE_VERSION_NAME_L L"\\Names" #define REGPATH_PERF_GENERIC_PERFORMANCE_KEY "SYSTEM\\CurrentControlSet\\Services\\" PRODUCT_NAME "\\Performance" #define REGPATH_PERF_GENERIC_PERFORMANCE_KEY_L L"SYSTEM\\CurrentControlSet\\Services\\" PRODUCT_NAME_L L"\\Performance" #define REGPATH_PERF_GENERIC_ROOT_KEY_L L"SYSTEM\\CurrentControlSet\\Services\\" PRODUCT_NAME_L #define REGPATH_EVENTLOG_APP_L L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\" #define IIS_KEY_L L"Software\\Microsoft\\InetStp\\" #define REGPATH_STATE_SERVER_PARAMETERS_KEY_L L"SYSTEM\\CurrentControlSet\\Services\\" STATE_SERVICE_NAME_L L"\\Parameters" #if ASPNET_PRODUCT_IS_REDIST #define EVENTLOG_PRODUCT ASP.NET #elif ASPNET_PRODUCT_IS_EXPRESS #define EVENTLOG_PRODUCT ASP.NET Express #elif ASPNET_PRODUCT_IS_STANDARD #define EVENTLOG_PRODUCT ASP.NET Standard #elif ASPNET_PRODUCT_IS_ENTERPRISE #define EVENTLOG_PRODUCT ASP.NET Enterprise #endif #define EVENTLOG_KEY_INF CONCAT_MACRO(System\CurrentControlSet\Services\EventLog\Application\, EVENTLOG_PRODUCT) #define EVENTLOG_NAME_L QUOTE_MACRO_L(EVENTLOG_PRODUCT VER_DOTPRODUCTVERSIONZEROQFE) /* * Registry values */ #define REGVAL_DEFDOC L"DefaultDoc" #define REGVAL_MIMEMAP L"Mimemap" #define REGVAL_PATH L"Path" #define REGVAL_DLLFULLPATH L"DllFullPath" #define REGVAL_ROOTVER L"RootVer" #define REGVAL_STATESOCKETTIMEOUT L"SocketTimeout" #define REGVAL_STATEALLOWREMOTE L"AllowRemoteConnection" #define REGVAL_STATEPORT L"Port" #define REGVAL_IIS_MAJORVER L"MajorVersion" #define REGVAL_IIS_MINORVER L"Minorversion" #define REGVAL_SUPPORTED_EXTS L"SupportedExts" #define REGVAL_STOP_BIN_FILTER L"StopBinFiltering" /* * Directory names */ #define ASPNET_CLIENT_SCRIPT_SRC_DIR "asp.netclientfiles" #define ASPNET_CLIENT_SCRIPT_SRC_DIR_L L"asp.netclientfiles" #define ASPNET_CLIENT_DIR "aspnet_client" #define ASPNET_CLIENT_DIR_L L"aspnet_client" #define ASPNET_CLIENT_SYS_WEB_DIR "system_web" #define ASPNET_CLIENT_SYS_WEB_DIR_L L"system_web" #define ASPNET_TEMP_DIR_L L"Temporary ASP.NET Files" #define ASPNET_CUSTOM_HEADER_L L"X-Powered-By: ASP.NET" /* * Metabase values */ // // !!! Important note: // New versions of DFEAULT_DOC and MIMEMAP must be backward compatible, i.e. a new version // must include all the content from an older version. // // DEFAULT_DOC is comma delimited. #define DEFAULT_DOC L"Default.aspx" #define MIMEMAP L".wsdl,text/xml," \ L".disco,text/xml," \ L".xsd,text/xml," \ L".wbmp,image/vnd.wap.wbmp," \ L".png,image/png," \ L".pnz,image/png," \ L".smd,audio/x-smd," \ L".smz,audio/x-smd," \ L".smx,audio/x-smd," \ L".mmf,application/x-smaf" // All the extensions supported by this version // After each extension, 1 = mapped to forbidden handler; 0 = not // The comma at the end of the last extension is required #define SUPPORTED_EXTS L".asax,1," \ L".ascx,1," \ L".ashx,0," \ L".asmx,0," \ L".aspx,0," \ L".axd,0," \ L".vsdisco,0," \ L".rem,0," \ L".soap,0," \ L".config,1," \ L".cs,1," \ L".csproj,1," \ L".vb,1," \ L".vbproj,1," \ L".webinfo,1," \ L".licx,1," \ L".resx,1," \ L".resources,1," // All the extensions supported by version 1.0 and its SP1 #define SUPPORTED_EXTS_v1 L".asax,1," \ L".ascx,1," \ L".ashx,0," \ L".asmx,0," \ L".aspx,0," \ L".axd,0," \ L".vsdisco,0," \ L".rem,0," \ L".soap,0," \ L".config,1," \ L".cs,1," \ L".csproj,1," \ L".vb,1," \ L".vbproj,1," \ L".webinfo,1," \ L".licx,1," \ L".resx,1," \ L".resources,1," // // Config file name // // the filename at the machine level #define SZ_WEB_CONFIG_FILE "machine.config" #define WSZ_WEB_CONFIG_FILE L"machine.config" // the filename at the machine level #define SZ_WEB_CONFIG_SUBDIR "Config" #define WSZ_WEB_CONFIG_SUBDIR L"Config" // the filename at the machine level #define SZ_WEB_CONFIG_FILE_AND_SUBDIR "Config\\machine.config" #define WSZ_WEB_CONFIG_FILE_AND_SUBDIR L"Config\\machine.config" // the filename for asp.net below the machine level #define SZ_WEB_CONFIG_FILE2 "web.config" #define WSZ_WEB_CONFIG_FILE2 L"web.config" #define SHORT_FILENAME_SIZE 14 // matches WIN32_FIND_DATA.cAltFileName #define PATH_SEPARATOR_CHAR '\\' #define PATH_SEPARATOR_CHAR_L L'\\' #define PATH_SEPARATOR_STR "\\" #define PATH_SEPARATOR_STR_L L"\\" #ifdef __cplusplus class Names { public: static HRESULT GetInterestingFileNames(); static LPCWSTR InstallDirectory() {return s_wszInstallDirectory;} static LPCWSTR ClrInstallDirectory() {return s_wszClrInstallDirectory;} static LPCWSTR GlobalConfigDirectory() {return s_wszGlobalConfigDirectory;} static LPCSTR GlobalConfigFullPath() {return s_szGlobalConfigFullPath;} static LPCWSTR GlobalConfigFullPathW() {return s_wszGlobalConfigFullPath;} static LPCWSTR GlobalConfigShortFileName() {return s_wszGlobalConfigShortFileName;} static LPCWSTR ExeFullPath() {return s_wszExeFullPath;} static LPCWSTR ExeFileName() {return s_wszExeFileName;} static LPCWSTR IsapiFullPath() {return s_wszIsapiFullPath;} static LPCWSTR FilterFullPath() {return s_wszFilterFullPath;} static LPCWSTR RcFullPath() {return s_wszRcFullPath;} static LPCWSTR WebFullPath() {return s_wszWebFullPath;} static LPCWSTR ClientScriptSrcDir() {return s_wszClientScriptSrcDir;} static LANGID SysLangId() {return s_langid;} private: static HRESULT ConvertLangIdToLanguageName(LANGID id, WCHAR** wcsCultureName, WCHAR** wcsCultureNeutralName); static WCHAR s_wszInstallDirectory[MAX_PATH]; static WCHAR s_wszClrInstallDirectory[MAX_PATH]; static WCHAR s_wszGlobalConfigDirectory[MAX_PATH]; static char s_szGlobalConfigFullPath[MAX_PATH]; static WCHAR s_wszGlobalConfigFullPath[MAX_PATH]; static WCHAR s_wszGlobalConfigShortFileName[SHORT_FILENAME_SIZE]; static WCHAR s_wszExeFileName[MAX_PATH]; static WCHAR s_wszExeFullPath[MAX_PATH]; static WCHAR s_wszIsapiFullPath[MAX_PATH]; static WCHAR s_wszFilterFullPath[MAX_PATH]; static WCHAR s_wszRcFullPath[MAX_PATH]; static WCHAR s_wszWebFullPath[MAX_PATH]; static WCHAR s_wszClientScriptSrcDir[MAX_PATH]; static LANGID s_langid; }; #endif // __cplusplus
d225ecad273bb4acf62ca7be0feb7c4c26d30b3c
e267a066b7ee39f6d3fe2cb983725fd55196c63b
/360VR_refactor/arduino/arduino testing scripts/timerTest/timerTest.ino
e74053552cd6daa06697af22262dc969bdae8064
[]
no_license
AndreasHogstrand/VR_pyControl
147e70aeda54eaaf797ab23c503a66d27c26ab03
91d720cfdc5bce43fd021af7a55d7a0a7ae7374a
refs/heads/master
2021-01-02T07:42:45.004912
2020-09-29T08:57:08
2020-09-29T08:57:08
239,552,569
0
0
null
null
null
null
UTF-8
C++
false
false
336
ino
timerTest.ino
#include <elapsedMillis.h> const int REWARD_AVAILABLE_MILLIS = 1500; void setup() { Serial.begin(9600); } void loop() { elapsedMillis timeout = 0; while (timeout < REWARD_AVAILABLE_MILLIS) { char ch = Serial.read(); if(ch == 'a'){ timeout = 0; Serial.print('o'); } } Serial.print('x'); }
fa03559fb675bb42fc8c652a7247b4941482a595
d1ac016ce8e7376ffb3e33401962cd7cc8c94b93
/langford-sequence.cpp
0a5d6efaf4197b063fd5fe43e52ab75ee6244ee3
[]
no_license
GabrielInTheWorld/tbb-exercise
a3c8a571ee448a14d3293645c14724499192038a
27dbfac5dcfcb21a34b071e900a669bf6683fa0d
refs/heads/master
2020-09-14T16:28:12.765863
2020-03-11T21:52:39
2020-03-11T21:52:39
223,184,544
0
0
null
null
null
null
UTF-8
C++
false
false
2,040
cpp
langford-sequence.cpp
#include "langford-sequence.h" LangfordSequence::LangfordSequence(int numberOfColors, int* solutions) : langford(numberOfColors), count(numberOfColors), solutions(solutions) { //initialize(); } LangfordSequence::LangfordSequence(Field& field, int count, int* solutions) : langford(field), count(count), solutions(solutions) { //initialize(); } task* LangfordSequence::execute() { task_list list; int childs = 0; auto callback = [&](int index) { cout << "Index: " << index << endl; cout << " with second: " << count << endl; //bool isFree = langford.isFree(index) && langford.isFree(index + count + 1); if ( langford.setFree(index, count) ) { //langford.set(index, count); langford.printField(); if ( count == 1 ) { cout << "Ready" << endl; *solutions += 1; } else { Field child(langford); list.push_back(*new(allocate_child())LangfordSequence(child, count - 1, solutions)); ++childs; } } }; parallel_for(0, langford.getSize() - count - 1, callback); if ( childs > 0 ) { set_ref_count(childs + 1); spawn_and_wait_for_all(list); } //if ( check() ) { // if ( count == 1 ) { // *solutions += 1; // return NULL; // } // task_list list; // Field child(langford); // list.push_back(*new(allocate_child())LangfordSequence(child, count - 1, solutions)); // set_ref_count(2); // spawn_and_wait_for_all(list); //} return NULL; } bool LangfordSequence::check() { bool successful = false; for ( int i = 0; i < langford.getSize() - count && !successful; ++i ) { successful = langford.isFree(i) && langford.isFree(i + count + 1); firstIndex = i; } if ( successful ) { langford.set(firstIndex, count); } cout << "Check: " << successful << " by: " << count << endl; return successful; }
ec08b6162db13fa7abbef00cc2636b2d3725720b
4610baf9a7e81cad6e52fe49289a5f234861732b
/driving/dgccompat/include/velodyne_interface.h
ad138ac3d60893c894b35a9d260c0d633640ab27
[]
no_license
kuasha/stanley
07f924f6ff61413f5baabd5b6605d4289e93c68d
b6b6d3a9efd4611258b2a6337ef25007f406bd80
refs/heads/master
2021-01-19T00:57:09.752337
2016-08-15T02:36:18
2016-08-15T02:36:18
65,698,509
6
0
null
null
null
null
UTF-8
C++
false
false
7,416
h
velodyne_interface.h
/******************************************************** Stanford Driving Software Copyright (c) 2011 Stanford University 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. * The names of the contributors may not 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. ********************************************************/ #ifndef VELODYNE_INTERFACE_H #define VELODYNE_INTERFACE_H #include <stdint.h> #include <global.h> #include <transform.h> namespace vlr { typedef enum { UNKNOWN, PCAP, VLF } VELODYNE_FILE_TYPE; #define VELODYNE_TICKS_TO_METER 0.002 #define VELO_NUM_LASERS 64 #define VELO_NUM_TICKS 36000 #define VELO_SPIN_START 18000 #define VELO_SCANS_IN_PACKET 12 #define VELO_BEAMS_IN_SCAN 32 #define VELO_PACKET_SIZE 1206 #define VLF_START_BYTE 0x1b #define VELO_PACKET_FSIZE 1226 /* 1 + 16 + 2 + 1206 + 1 */ /* one packet is one scan = VELO_BEAMS_IN_SCAN * 3 + 4 [enc+block+n*3] = 100 bytes packet = VELO_SCANS_IN_PACKET * 100 + status (6 bytes) = 1206 bytes file: startbyte timestamp length [... DATA ...] checksum => additional 1+16+2+1 = 20 bytes startbyte = 0x1b timestamp = 2 x <unsigned long> [tv_sec and tv_usec] length = <unsigned short> ... checksum = <unsigned char> */ /************************************************************************ * ************************************************************************/ /************************************************************************ * * STRUCTURE WITH RAW DATA FROM SCANNER * ************************************************************************/ typedef struct { unsigned short encoder; unsigned short block; unsigned short range[VELO_BEAMS_IN_SCAN]; unsigned char intensity[VELO_BEAMS_IN_SCAN]; } dgc_velodyne_measurement_t, *dgc_velodyne_measurement_p; typedef struct { double timestamp; dgc_velodyne_measurement_t scan[VELO_SCANS_IN_PACKET]; unsigned char status[6]; } dgc_velodyne_packet_t, *dgc_velodyne_packet_p; /************************************************************************ * * STRUCTURE WITH LOG FILE DATA * ************************************************************************/ /*typedef struct { VELODYNE_FILE_TYPE format; dgc_FILE *fp; char *filename; int buffer_len; unsigned char *msg_buffer; // variables that change infrequently int sweep_number; } dgc_velodyne_file_t, * dgc_velodyne_file_p;*/ /************************************************************************ * ************************************************************************/ /*typedef struct { // variables that never change dgc_transform_t offset; double range_offset[VELO_NUM_LASERS]; double range_offsetX[VELO_NUM_LASERS]; double range_offsetY[VELO_NUM_LASERS]; char laser_enabled[VELO_NUM_LASERS]; double global_range_offset; double vert_angle[VELO_NUM_LASERS]; double rot_angle[VELO_NUM_LASERS]; double h_offset[VELO_NUM_LASERS]; double v_offset[VELO_NUM_LASERS]; double sin_vert_angle[VELO_NUM_LASERS]; double cos_vert_angle[VELO_NUM_LASERS]; double enc_rot_angle[VELO_NUM_TICKS][VELO_NUM_LASERS]; double sin_rot_angle[VELO_NUM_TICKS][VELO_NUM_LASERS]; double cos_rot_angle[VELO_NUM_TICKS][VELO_NUM_LASERS]; double sin_enc_angle[VELO_NUM_TICKS]; double cos_enc_angle[VELO_NUM_TICKS]; double enc_angle[VELO_NUM_TICKS]; double range_multiplier; int min_intensity; int max_intensity; double intensity_map[VELO_NUM_LASERS][256]; int beam_order[VELO_NUM_LASERS]; int inv_beam_order[VELO_NUM_LASERS]; int spin_start; } dgc_velodyne_config_t, *dgc_velodyne_config_p;*/ /************************************************************************ * ************************************************************************/ typedef struct { /* the unit here is 5mm(!). Do x * 0.005 to convert to m. Therefore the maximum range is +/- 163.84m */ short x; short y; short z; /* use the units here are 5mm (1). Do x * 0.005 to convert to m */ unsigned short range; unsigned char intensity; } dgc_velodyne_point_t, * dgc_velodyne_point_p; typedef struct { // global position of the measurement dgc_velodyne_point_t p[VELO_BEAMS_IN_SCAN]; // double timestamp; // dgc::dgc_pose_t robot; // which block (upper/lower lasers) is firing unsigned char block; unsigned short encoder; // counter that indicates which scans belongs to the same revolution unsigned short counter; } dgc_velodyne_scan_t, *dgc_velodyne_scan_p; class VelodyneInterface { public: virtual ~VelodyneInterface() {}; virtual int CreateServer(void) = 0; virtual int CreateClient(void) = 0; virtual void SetKey(uint32_t) = 0; virtual int ReadRaw(unsigned char *data) = 0; virtual int WriteRaw(int len, unsigned char *data) = 0; virtual int ReadScans(dgc_velodyne_scan_p scans, int max_num_scans) = 0; virtual int WriteScans(int num, dgc_velodyne_scan_p scans) = 0; virtual int ReadCurrentScans(dgc_velodyne_scan_p scans, int max_num_scans) = 0; virtual int RawDataWaiting(void) = 0; virtual int ScanDataWaiting(void) = 0; }; } #endif
9720c9d0e058b064fb328ee0109bc38b48d50dbf
2f7bddfb175372334a5acc39f49f284a558eb732
/geant/SFERA/src/B3DetectorConstruction.cc
bb5214bbd23679c6f3764b7300b0d26cbbb77ef6
[]
no_license
AndreaAllegrucci/Sfera
838b2150f8d680ab30c543672d1686d45a2a7e88
66f00e39372b1c5b81b0e384e7e40863f5718a7f
refs/heads/master
2020-04-10T12:06:45.995672
2018-09-10T17:21:55
2018-09-10T17:21:55
124,273,269
0
4
null
2018-09-09T09:32:47
2018-03-07T17:51:46
C++
UTF-8
C++
false
false
12,707
cc
B3DetectorConstruction.cc
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // $Id: B3DetectorConstruction.cc 101905 2016-12-07 11:34:39Z gunter $ // /// \file B3DetectorConstruction.cc /// \brief Implementation of the B3DetectorConstruction class #include "B3DetectorConstruction.hh" #include "G4NistManager.hh" #include "G4Box.hh" #include "G4Trd.hh" #include "G4Tubs.hh" #include "G4Sphere.hh" #include "G4SubtractionSolid.hh" #include "G4LogicalVolume.hh" #include "G4PVPlacement.hh" #include "G4RotationMatrix.hh" #include "G4Transform3D.hh" #include "G4SDManager.hh" #include "G4MultiFunctionalDetector.hh" #include "G4VPrimitiveScorer.hh" #include "G4PSEnergyDeposit.hh" #include "G4PSDoseDeposit.hh" #include "G4VisAttributes.hh" #include "G4PhysicalConstants.hh" #include "G4SystemOfUnits.hh" #include <math.h> #define SOURCE //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... B3DetectorConstruction::B3DetectorConstruction() : G4VUserDetectorConstruction(), fCheckOverlaps(true) { DefineMaterials(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... B3DetectorConstruction::~B3DetectorConstruction() { } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void B3DetectorConstruction::DefineMaterials() { G4NistManager* man = G4NistManager::Instance(); G4bool isotopes = false; G4Element* Na = man->FindOrBuildElement("Na", isotopes); G4Element* I = man->FindOrBuildElement("I", isotopes); G4Material* NaI = new G4Material("NaI", 3.67*g/cm3, 2); NaI->AddElement(Na, 1); NaI->AddElement(I, 1); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... G4VPhysicalVolume* B3DetectorConstruction::Construct() { // Gamma detector Parameters G4double cryst_dX1 = 1.3 * cm, cryst_dY1 = 1.8 * cm; G4double cryst_dX = 8.4 * cm, cryst_dY = 11.8 * cm; G4double cryst_dZ = 28. * cm; G4int nb_cryst = 16; G4int nb_rings = 1; G4double dPhi = twopi / nb_cryst, half_dPhi = .5 * dPhi; G4double cosdPhih = std::cos(.5 * dPhi); G4double ring_R1 = .5 * 9.5 * cm; G4double ring_R2 = (ring_R1 + cryst_dZ) / cosdPhih; G4double theta = 2 * atan(0.5 * cryst_dX1 / ring_R1); G4double tandPhi = std::tan(half_dPhi); G4double detector_dZ = nb_rings * cryst_dX; G4NistManager* nist = G4NistManager::Instance(); G4Material* default_mat = nist->FindOrBuildMaterial("G4_AIR"); G4Material* cryst_mat = nist->FindOrBuildMaterial("NaI"); G4Material* ring_mat = nist->FindOrBuildMaterial("G4_Al"); // // World // G4double world_sizeXY = 2.4*ring_R2; G4double world_sizeZ = 5.*detector_dZ; G4Box* solidWorld = new G4Box("World", //its name 0.5*world_sizeXY, 0.5*world_sizeXY, 0.5*world_sizeZ); //its size G4LogicalVolume* logicWorld = new G4LogicalVolume(solidWorld, //its solid default_mat, //its material "World"); //its name G4VPhysicalVolume* physWorld = new G4PVPlacement(0, //no rotation G4ThreeVector(), //at (0,0,0) logicWorld, //its logical volume "World", //its name 0, //its mother volume false, //no boolean operation 0, //copy number fCheckOverlaps); // checking overlaps // // ring // G4Sphere* solidRing = //new G4Tubs("Ring", ring_R1, ring_R2, 0.5 * cryst_dX, 0., twopi); new G4Sphere("Ring", ring_R1, ring_R2, 0, twopi, 90*deg-(3.*0.5*theta), 2.*3.*0.5*theta); G4LogicalVolume* logicRing = new G4LogicalVolume(solidRing, //its solid ring_mat, //its material "Ring"); //its name // // define crystal // G4Trd *solidCryst = new G4Trd("crystal", (cryst_dX1-0.2)/2, (cryst_dX-0.2)/2, (cryst_dY1-0.2)/2, (cryst_dY-0.2)/2, (cryst_dZ-0.2)/2); G4LogicalVolume* logicCryst = new G4LogicalVolume(solidCryst, //its solid cryst_mat, //its material "CrystalLV"); //its name G4LogicalVolume* logicCryst2 = new G4LogicalVolume(solidCryst, //its solid cryst_mat, //its material "CrystalLV2"); //its name // place crystals within a ring // for (G4int icrys = 0; icrys < nb_cryst ; icrys++) { G4double phi = icrys*dPhi; G4RotationMatrix rotm = G4RotationMatrix(); rotm.rotateY(90*deg); rotm.rotateZ(phi); G4ThreeVector uz = G4ThreeVector(std::cos(phi), std::sin(phi),0.); G4ThreeVector position = (ring_R1+0.5*cryst_dZ)*uz; G4Transform3D transform = G4Transform3D(rotm,position); new G4PVPlacement( transform, //roxtation,position logicCryst, //its logical volume "crystal", //its name logicRing, //its mother volume false, //no boolean operation icrys, //copy number fCheckOverlaps); // checking overlaps G4RotationMatrix rotm2 = G4RotationMatrix(); rotm2.rotateY(90*deg - theta); rotm2.rotateZ(phi); G4ThreeVector uz2 = G4ThreeVector(std::sin(90*deg - theta) * std::cos(phi), std::sin(90*deg - theta) * std::sin(phi),std::cos(90*deg - theta)); G4ThreeVector position2 = (ring_R1+0.5*cryst_dZ)*uz2; G4Transform3D transform2 = G4Transform3D(rotm2,position2); new G4PVPlacement( transform2, //rotation,position logicCryst2, //its logical volume "lateral_crystal", //its name logicRing, //its mother volume false, //no boolean operation icrys+16, //copy number fCheckOverlaps); // checking overlaps G4RotationMatrix rotm3 = G4RotationMatrix(); rotm3.rotateY(90*deg + theta); rotm3.rotateZ(phi); G4ThreeVector uz3 = G4ThreeVector(std::sin(90*deg + theta) * std::cos(phi), std::sin(90*deg + theta) * std::sin(phi),std::cos(90*deg + theta)); G4ThreeVector position3 = (ring_R1+0.5*cryst_dZ)*uz3; G4Transform3D transform3 = G4Transform3D(rotm3,position3); new G4PVPlacement( transform3, //rotation,position logicCryst2, //its logical volume "lateral_crystal", //its name logicRing, //its mother volume false, //no boolean operation icrys+32, //copy number fCheckOverlaps); // checking overlaps } // // full detector // G4Tubs* solidDetector = new G4Tubs("Detector", ring_R1, ring_R2, 0.5 * detector_dZ, 0., twopi); G4LogicalVolume* logicDetector = new G4LogicalVolume(solidDetector, //its solid default_mat, //its material "Detector"); //its name // // place rings within detector // G4double OG = -0.5*(detector_dZ + cryst_dX); for (G4int iring = 0; iring < nb_rings ; iring++) { OG += cryst_dX; new G4PVPlacement(0, //no rotation G4ThreeVector(0,0,OG), //position logicRing, //its logical volume "ring", //its name logicDetector, //its mother volume false, //no boolean operation iring, //copy number fCheckOverlaps); // checking overlaps } // // place detector in world // new G4PVPlacement(0, //no rotation G4ThreeVector(), //at (0,0,0) logicDetector, //its logical volume "Detector", //its name logicWorld, //its mother volume false, //no boolean operation 0, //copy number fCheckOverlaps); // checking overlaps // // Source // #ifdef SOURCE G4Material* Na22 = new G4Material("Na22", 11, 22*g/mole, 0.968*g/cm3); G4double source_radius = 1.5*cm; G4double source_dZ = 0.5*cm; G4Material* source_mat = nist->FindOrBuildMaterial("G4_A-150_TISSUE"); G4Tubs* solidSource = new G4Tubs("Source", 0., source_radius, 0.5*source_dZ, 0., twopi); G4LogicalVolume* logicSource = new G4LogicalVolume(solidSource, //its solid source_mat, //its material "SourceLV"); //its name // // place source in world // G4RotationMatrix* rotm2 = new G4RotationMatrix(); rotm2->rotateX(90*deg); new G4PVPlacement( rotm2, //rotation, position G4ThreeVector(), //at (0,0,0) logicSource, //its logical volume "Source", //its name logicWorld, //its mother volume false, //no boolean operation 0, //copy number fCheckOverlaps); // checking overlaps #endif // // Visualization attributes // logicRing->SetVisAttributes (G4VisAttributes::GetInvisible()); logicDetector->SetVisAttributes (G4VisAttributes::GetInvisible()); // Print materials G4cout << *(G4Material::GetMaterialTable()) << G4endl; //always return the physical World // return physWorld; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void B3DetectorConstruction::ConstructSDandField() { G4SDManager::GetSDMpointer()->SetVerboseLevel(1); // declare crystal as a MultiFunctionalDetector scorer // G4MultiFunctionalDetector* cryst = new G4MultiFunctionalDetector("crystal"); G4SDManager::GetSDMpointer()->AddNewDetector(cryst); G4VPrimitiveScorer* primitiv1 = new G4PSEnergyDeposit("edep"); cryst->RegisterPrimitive(primitiv1); SetSensitiveDetector("CrystalLV",cryst); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
5160f2432e816589cb41c82a0318fcaeccb87703
9ce87344ebbbfbaaab31684c3de43b685135c177
/Framework/Utility/FileModifyMonitor.h
f985ad7e3f9de30f5aa81f8535b353520e63000a
[]
no_license
zqrtalent/MercuryUI
1582d0468034d8c0550e3a4e6cf8988f7d0bc44c
1b6e9659c0b5ffb92eba2a2ba351dc83564f8a4d
refs/heads/master
2020-05-22T01:43:57.422948
2016-11-19T18:46:52
2016-11-19T18:46:52
65,150,951
0
3
null
null
null
null
UTF-8
C++
false
false
768
h
FileModifyMonitor.h
#pragma once #include <afxmt.h> #include "..\Array\List.h" #include "..\Array\AutoSortedArrayInt64.h" #include "ThisCallHelper.h" class FileModifyMonitor { public: FileModifyMonitor(); ~FileModifyMonitor(); bool StartMonitor(CString sFile, FileModifiedMethod callback, void* lpClassObject); bool StopMonitor (); protected: static UINT __stdcall OnMonitorThreadProc(FileModifyMonitor* pOwner); void OnFileSizeChanged(HANDLE hFile, DWORD dwSizeNew); // Callback protected: bool m_bStarted; CString m_sFileMonitor; HANDLE m_hChangeMonitor; HANDLE m_hMonitorThread; CEvent* m_pEventStop; DWORD m_dwThreadId; CCriticalSection m_lock; FileModifiedMethod m_callbackMethod; void* m_lpClass; };
8b2cea43ae9a307336816e882e93e1ef5f2f9f24
717571eb490eefaec0cd52dc1b49b1e59da31361
/src/Render/Scenes/SceneRenderContext.cpp
96a67be5bf692d59e9d423b6ed9660caa0d14634
[]
no_license
benreid24/BLIB
d726c48ceab133071e6bf81a638f3217ce4dfe5a
a5e4cf2eba649089940c2414e3dce57b654e0d59
refs/heads/master
2023-08-31T23:02:12.963457
2023-07-25T19:25:43
2023-07-25T19:25:43
234,001,128
1
0
null
2023-09-10T23:09:36
2020-01-15T04:54:14
C++
UTF-8
C++
false
false
2,504
cpp
SceneRenderContext.cpp
#include <BLIB/Render/Scenes/SceneRenderContext.hpp> #include <BLIB/Render/Buffers/IndexBuffer.hpp> namespace bl { namespace rc { namespace scene { SceneRenderContext::SceneRenderContext(VkCommandBuffer commandBuffer, std::uint32_t observerIndex, const VkViewport& vp, std::uint32_t rpid, bool isrt) : commandBuffer(commandBuffer) , observerIndex(observerIndex) , prevVB(nullptr) , prevIB(nullptr) , boundSpeed(std::numeric_limits<UpdateSpeed>::max()) , viewport(vp) , renderPassId(rpid) , isRenderTexture(isrt) { boundDescriptors.fill(nullptr); } void SceneRenderContext::bindPipeline(vk::Pipeline& pipeline) { pipeline.bind(commandBuffer, renderPassId); } void SceneRenderContext::bindDescriptors(VkPipelineLayout layout, UpdateSpeed speed, ds::DescriptorSetInstance** descriptors, std::uint32_t descriptorCount) { const bool speedChange = speed != boundSpeed; bool bind = false; for (unsigned int i = 0; i < descriptorCount; ++i) { if (bind || descriptors[i] != boundDescriptors[i] || (descriptors[i]->needsRebindForNewSpeed() && speedChange)) { bind = true; boundDescriptors[i] = descriptors[i]; descriptors[i]->bindForPipeline(*this, layout, i, speed); } } boundSpeed = speed; } void SceneRenderContext::renderObject(const SceneObject& object) { if (prevVB != object.drawParams.vertexBuffer) { prevVB = object.drawParams.vertexBuffer; VkBuffer vertexBuffers[] = {object.drawParams.vertexBuffer}; VkDeviceSize offsets[] = {0}; vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets); } if (prevIB != object.drawParams.indexBuffer) { prevIB = object.drawParams.indexBuffer; vkCmdBindIndexBuffer( commandBuffer, object.drawParams.indexBuffer, 0, buf::IndexBuffer::IndexType); } vkCmdDrawIndexed(commandBuffer, object.drawParams.indexCount, object.drawParams.instanceCount, object.drawParams.indexOffset, object.drawParams.vertexOffset, object.drawParams.instanceCount == 1 ? object.sceneKey.sceneId : object.drawParams.firstInstance); } } // namespace scene } // namespace rc } // namespace bl
11c4f9547efec89284cd9bd47300a666f8dadf05
904172fd219088647b3f80ea7fd80efca8f99930
/PbfVsLib/include/utils.h
3e4f07311b2a549f45b99dbe4141f48ef055ce1b
[]
no_license
penguin1214/PbfVs
5a74a5606b880468dc437d4bf75357bf8dedf766
dcdf6a6b1050e38fa199598490b871f510b66d0f
refs/heads/master
2021-01-01T06:56:57.048995
2017-06-08T05:37:22
2017-06-08T05:37:22
97,558,011
1
0
null
2017-07-18T05:53:24
2017-07-18T05:53:24
null
UTF-8
C++
false
false
316
h
utils.h
// // utils.h // PBF // // Created by Ye Kuang on 10/14/16. // Copyright © 2016 Ye Kuang. All rights reserved. // #ifndef utils_h #define utils_h #include <iostream> #include <fstream> #include <string> namespace pbf { std::string ReadFile(const char *filepath); } // namespace pbf #endif /* utils_h */
13e0c99771caf669dbe810d6999b6ff87ae33715
4273135a9c8fd46c47a6871506c02b98a37c5503
/algocoding/leetcode/search_in_rotated_sorted_array_II.cpp
e30fffdd41b383b3cbcd3b28e14c3d6fb0d2884b
[]
no_license
xuyuanxin/notes
f31cd6c8bce0357f0ac4114da7330901fce49b41
d8fed981a2096843a62bb4a40aa677168e11f88e
refs/heads/master
2022-05-06T22:54:42.621373
2022-04-23T07:26:00
2022-04-23T07:26:00
25,041,042
2
2
null
2022-04-22T23:36:23
2014-10-10T15:18:08
C
UTF-8
C++
false
false
1,669
cpp
search_in_rotated_sorted_array_II.cpp
/******************************************************************************* Remove Duplicates from Sorted Array(Medium) ******************************************************************************* Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. ******************************************************************************* interface ******************************************************************************* class Solution { public: int removeDuplicates(int A[], int n) { } }; ******************************************************************************* algo ******************************************************************************* ******************************************************************************/ class Solution { public: int removeDuplicates(int A[], int n) { int i,nums = 0,cnt = 1; if(0 == n) return 0; for(i = 1; i < n; ++i) { if(A[nums] == A[i]) { cnt++; if(cnt > 2) continue; nums++; A[nums] = A[i]; } else { nums++; A[nums] = A[i]; if(1 != cnt) cnt = 1; } } return nums+1; } int removeDuplicates2(int A[], int n) { int i,nums = 0,cnt = 1; if(0 == n) return 0; for(i = 1; i < n; ++i) { if(A[nums] == A[i]) { cnt++; if(cnt > 2) continue; } else { if(1 != cnt) cnt = 1; } nums++; A[nums] = A[i]; } return nums+1; } };
b5f0caafac132cf2aeafa6978c9f5aa84c096b7f
48886bc607aa50412dad58a59ce5289f1da6df4d
/src/audio/age_audio.cpp
0f3fb18c1dfb4af4ce5e69a5e61bae826ab494d8
[]
no_license
tangziwen/AGE2D
a3bdebfb47fed7a2ba35905a7a053d6e4092040a
61d754c535e24a5380565886bf3fbb5af019882b
refs/heads/master
2021-01-18T18:12:58.384466
2014-02-11T06:17:04
2014-02-11T06:17:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,671
cpp
age_audio.cpp
#include "../include/age_audio.h" namespace AGE2D { AAudio::AAudio(QString audName) { Init(); this->audName = audName; audio(); } AAudio::AAudio(QString audName,int mods) { Init(); this->mods = mods; this->audName = audName; audio(); } void AAudio::audio() { if(mods == 0) { QFile f(this->audName); f.copy(QDir::currentPath()+"/"+this->audName.remove(":/")); this->medialist->addMedia(QUrl::fromLocalFile(QDir::currentPath()+"/"+this->audName.remove(":/"))); } else { this->medialist->addMedia(QUrl(this->audName)); } this->medialist->setCurrentIndex(1); this->medialist->setPlaybackMode(QMediaPlaylist::CurrentItemOnce); this->music->setPlaylist(medialist); } void AAudio::play() { music->play(); } void AAudio::stop() { music->stop(); } void AAudio::pause() { music->pause(); } void AAudio::setLoopORnot(bool loopORnot) { this->loopORnot=loopORnot; if(this->loopORnot == true) this->medialist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop); else this->medialist->setPlaybackMode(QMediaPlaylist::CurrentItemOnce); } void AAudio::setObjectName(QString objName) { this->objName=objName; this->music->setObjectName(this->objName); } void AAudio::setVolume(int Volume) { this->Volume = Volume; this->music->setVolume(this->Volume); } QString AAudio::getObjectName() { return this->objName; } QString AAudio::getAudioName() { return this->audName; } int AAudio::getVolume() { return this->Volume; } bool AAudio::getLoopORnot() { return this->loopORnot; } AAudio::~AAudio() { delete this->music; delete this->medialist; } }
5ae03caf386f59b93fc8397b02c3fc9cde4a5367
b2f07a88a366d2a380b5e4a62e65ed45c41b2fe4
/tests/test/scheduler/test_function_client_server.cpp
2caf47e449b754db8777c1b538c6933049f2a898
[ "Apache-2.0" ]
permissive
csegarragonz/faabric
c33b66df2deb53e8819d6aa6ed108d3a726f0b22
45c97c35958e6e811b43841ab7281df9b584b43c
refs/heads/master
2023-03-23T12:34:18.537194
2021-03-01T16:27:43
2021-03-01T16:27:43
305,748,783
0
0
Apache-2.0
2021-01-21T16:53:04
2020-10-20T15:15:43
C++
UTF-8
C++
false
false
5,720
cpp
test_function_client_server.cpp
#include <catch.hpp> #include "faabric_utils.h" #include <faabric/redis/Redis.h> #include <faabric/scheduler/FunctionCallClient.h> #include <faabric/scheduler/FunctionCallServer.h> #include <faabric/scheduler/MpiWorld.h> #include <faabric/scheduler/MpiWorldRegistry.h> #include <faabric/scheduler/Scheduler.h> #include <faabric/util/config.h> #include <faabric/util/func.h> #include <faabric/util/network.h> using namespace scheduler; namespace tests { TEST_CASE("Test sending function call", "[scheduler]") { cleanFaabric(); // Start the server ServerContext serverContext; FunctionCallServer server; server.start(); usleep(1000 * 100); // Create a message faabric::Message msg; msg.set_user("demo"); msg.set_function("echo"); msg.set_inputdata("foobarbaz"); // Get the queue for the function Scheduler& sch = scheduler::getScheduler(); std::shared_ptr<InMemoryMessageQueue> funcQueue = sch.getFunctionQueue(msg); // Check queue is empty REQUIRE(funcQueue->size() == 0); // Send the message to the server FunctionCallClient client(LOCALHOST); client.shareFunctionCall(msg); // Check the message is on the queue REQUIRE(funcQueue->size() == 1); faabric::Message actual = funcQueue->dequeue(); REQUIRE(actual.user() == msg.user()); REQUIRE(actual.function() == msg.function()); REQUIRE(actual.inputdata() == msg.inputdata()); // Stop the server server.stop(); } TEST_CASE("Test sending MPI message", "[scheduler]") { cleanFaabric(); // Start the server ServerContext serverContext; FunctionCallServer server; server.start(); usleep(1000 * 100); // Create an MPI world on this host and one on a "remote" host std::string otherHost = "192.168.9.2"; const char* user = "mpi"; const char* func = "hellompi"; const faabric::Message& msg = faabric::util::messageFactory(user, func); int worldId = 123; int worldSize = 2; scheduler::MpiWorldRegistry& registry = getMpiWorldRegistry(); scheduler::MpiWorld& localWorld = registry.createWorld(msg, worldId); localWorld.overrideHost(LOCALHOST); localWorld.create(msg, worldId, worldSize); scheduler::MpiWorld remoteWorld; remoteWorld.overrideHost(otherHost); remoteWorld.initialiseFromState(msg, worldId); // Register a rank on each int rankLocal = 0; int rankRemote = 1; localWorld.registerRank(rankLocal); remoteWorld.registerRank(rankRemote); // Create a message faabric::MPIMessage mpiMsg; mpiMsg.set_worldid(worldId); mpiMsg.set_sender(rankRemote); mpiMsg.set_destination(rankLocal); // Send the message FunctionCallClient cli(LOCALHOST); cli.sendMPIMessage(mpiMsg); // Make sure the message has been put on the right queue locally std::shared_ptr<InMemoryMpiQueue> queue = localWorld.getLocalQueue(rankRemote, rankLocal); REQUIRE(queue->size() == 1); const faabric::MPIMessage& actualMessage = queue->dequeue(); REQUIRE(actualMessage.worldid() == worldId); REQUIRE(actualMessage.sender() == rankRemote); // Stop the server server.stop(); } TEST_CASE("Test sending flush message", "[scheduler]") { cleanFaabric(); // Start the server ServerContext serverContext; FunctionCallServer server; server.start(); usleep(1000 * 100); // Set up some state faabric::state::State& state = faabric::state::getGlobalState(); state.getKV("demo", "blah", 10); state.getKV("other", "foo", 30); REQUIRE(state.getKVCount() == 2); // Execute a couple of functions faabric::Message msgA = faabric::util::messageFactory("demo", "foo"); faabric::Message msgB = faabric::util::messageFactory("demo", "bar"); faabric::scheduler::Scheduler& sch = faabric::scheduler::getScheduler(); sch.callFunction(msgA); sch.callFunction(msgB); // Empty the queued messages auto bindQueue = sch.getBindQueue(); auto functionQueueA = sch.getFunctionQueue(msgA); auto functionQueueB = sch.getFunctionQueue(msgB); bindQueue->dequeue(); bindQueue->dequeue(); functionQueueA->dequeue(); functionQueueB->dequeue(); // Check the scheduler is set up REQUIRE(sch.getFunctionWarmNodeCount(msgA) == 1); REQUIRE(sch.getFunctionWarmNodeCount(msgB) == 1); std::string thisHost = sch.getThisHost(); std::string warmSetNameA = sch.getFunctionWarmSetName(msgA); std::string warmSetNameB = sch.getFunctionWarmSetName(msgB); faabric::redis::Redis& redis = faabric::redis::Redis::getQueue(); REQUIRE(redis.sismember(warmSetNameA, thisHost)); REQUIRE(redis.sismember(warmSetNameB, thisHost)); // Background threads to get flush messages std::thread tA([&functionQueueA] { faabric::Message msg = functionQueueA->dequeue(1000); REQUIRE(msg.type() == faabric::Message_MessageType_FLUSH); }); std::thread tB([&functionQueueB] { faabric::Message msg = functionQueueB->dequeue(1000); REQUIRE(msg.type() == faabric::Message_MessageType_FLUSH); }); // Send flush message FunctionCallClient cli(LOCALHOST); cli.sendFlush(); // Wait for thread to get flush message if (tA.joinable()) { tA.join(); } if (tB.joinable()) { tB.join(); } server.stop(); // Check the scheduler has been flushed REQUIRE(sch.getFunctionWarmNodeCount(msgA) == 0); REQUIRE(sch.getFunctionWarmNodeCount(msgB) == 0); REQUIRE(!redis.sismember(warmSetNameA, thisHost)); REQUIRE(!redis.sismember(warmSetNameB, thisHost)); // Check state has been cleared REQUIRE(state.getKVCount() == 0); } }
51990a8556e840fb5cfc0d1af3543569b3b84c39
2c04f42d3a3e1e5184cc03af495d2286fc392581
/src/Terminal.h
435fceeadf8b38dff82cc002e123871f2a297fb8
[]
no_license
Zakuta/dijkstra-steiner-algo
5b6ddb4757b8fa5533c2509db853030cc7a365d7
f58251533a7787bb90805739c2195c48f4847650
refs/heads/master
2020-04-27T13:09:10.077980
2019-03-07T14:20:15
2019-03-07T14:20:15
174,358,301
4
1
null
null
null
null
UTF-8
C++
false
false
510
h
Terminal.h
#ifndef CHIP_DESIGN_TERMINAL_H #define CHIP_DESIGN_TERMINAL_H #include <vector> #include "Position.h" class Terminal { public: using Vector = std::vector<Terminal>; using Index = size_t; Terminal(Position const &position, Terminal::Index const index); bool operator==(Terminal const &rhs) const; bool operator!=(Terminal const &rhs) const; Position const &get_position() const; Index get_index() const; private: Position const position; Index const index; }; #endif //CHIP_DESIGN_TERMINAL_H
489d07cabf2851f03335c6fd53947af3e2a042f1
ada447d1a7d63c67ee1f5bf682fe1e0044ff061a
/Protocol_protobuf/Protocol_protobuf/Proto/Progress.pb.cc
edcd7948f43f84ef52ff68d0c3b88cddb1c9fe5d
[]
no_license
learner737/work_files
7187c24212594deef27c458f25dc51a18936c95c
60378f2b03ef1d954abf03d27b016098d43c6e1f
refs/heads/master
2023-08-19T04:23:24.817408
2021-09-27T03:48:48
2021-09-27T03:48:48
402,344,123
0
0
null
null
null
null
UTF-8
C++
false
true
49,857
cc
Progress.pb.cc
// Generated by the protocol buffer compiler. DO NOT EDIT! #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "Progress.pb.h" #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace Progress { namespace { const ::google::protobuf::Descriptor* ProgressInfo_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* ProgressInfo_reflection_ = NULL; const ::google::protobuf::Descriptor* ProgressHandlerInfo_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* ProgressHandlerInfo_reflection_ = NULL; const ::google::protobuf::Descriptor* MultErrorInfo_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* MultErrorInfo_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* ProgressType_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_Progress_2eproto() { protobuf_AddDesc_Progress_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "Progress.proto"); GOOGLE_CHECK(file != NULL); ProgressInfo_descriptor_ = file->message_type(0); static const int ProgressInfo_offsets_[4] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressInfo, task_uuid_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressInfo, progress_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressInfo, result_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressInfo, error_number_), }; ProgressInfo_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( ProgressInfo_descriptor_, ProgressInfo::default_instance_, ProgressInfo_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressInfo, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressInfo, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(ProgressInfo)); ProgressHandlerInfo_descriptor_ = file->message_type(1); static const int ProgressHandlerInfo_offsets_[8] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressHandlerInfo, task_uuid_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressHandlerInfo, progress_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressHandlerInfo, result_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressHandlerInfo, error_number_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressHandlerInfo, progress_type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressHandlerInfo, file_total_num_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressHandlerInfo, file_finish_num_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressHandlerInfo, mult_error_number_), }; ProgressHandlerInfo_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( ProgressHandlerInfo_descriptor_, ProgressHandlerInfo::default_instance_, ProgressHandlerInfo_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressHandlerInfo, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProgressHandlerInfo, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(ProgressHandlerInfo)); MultErrorInfo_descriptor_ = file->message_type(2); static const int MultErrorInfo_offsets_[7] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MultErrorInfo, task_handler_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MultErrorInfo, is_start_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MultErrorInfo, is_finished_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MultErrorInfo, result_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MultErrorInfo, fileservice_error_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MultErrorInfo, handler_errer_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MultErrorInfo, login_uuid_), }; MultErrorInfo_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( MultErrorInfo_descriptor_, MultErrorInfo::default_instance_, MultErrorInfo_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MultErrorInfo, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MultErrorInfo, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(MultErrorInfo)); ProgressType_descriptor_ = file->enum_type(0); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_Progress_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( ProgressInfo_descriptor_, &ProgressInfo::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( ProgressHandlerInfo_descriptor_, &ProgressHandlerInfo::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( MultErrorInfo_descriptor_, &MultErrorInfo::default_instance()); } } // namespace void protobuf_ShutdownFile_Progress_2eproto() { delete ProgressInfo::default_instance_; delete ProgressInfo_reflection_; delete ProgressHandlerInfo::default_instance_; delete ProgressHandlerInfo_reflection_; delete MultErrorInfo::default_instance_; delete MultErrorInfo_reflection_; } void protobuf_AddDesc_Progress_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::LogExportTask::protobuf_AddDesc_LogExportTask_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\016Progress.proto\022\010Progress\032\023LogExportTas" "k.proto\"Y\n\014ProgressInfo\022\021\n\ttask_uuid\030\001 \002" "(\014\022\020\n\010progress\030\002 \002(\002\022\016\n\006result\030\003 \002(\010\022\024\n\014" "error_number\030\004 \001(\003\"\364\001\n\023ProgressHandlerIn" "fo\022\021\n\ttask_uuid\030\001 \002(\014\022\020\n\010progress\030\002 \002(\002\022" "\016\n\006result\030\003 \002(\010\022\024\n\014error_number\030\004 \001(\003\022-\n" "\rprogress_type\030\005 \002(\0162\026.Progress.Progress" "Type\022\026\n\016file_total_num\030\006 \001(\003\022\027\n\017file_fin" "ish_num\030\007 \001(\003\0222\n\021mult_error_number\030\010 \003(\013" "2\027.Progress.MultErrorInfo\"\276\001\n\rMultErrorI" "nfo\0220\n\014task_handler\030\001 \002(\0162\032.LogExportTas" "k.TaskHandler\022\020\n\010is_start\030\002 \002(\010\022\023\n\013is_fi" "nished\030\003 \002(\010\022\016\n\006result\030\004 \002(\010\022\031\n\021fileserv" "ice_error\030\005 \002(\003\022\025\n\rhandler_errer\030\006 \002(\003\022\022" "\n\nlogin_uuid\030\007 \001(\014*J\n\014ProgressType\022!\n\035EN" "_PROCESS_TYPE_DOWNLOAD_FILE\020\001\022\027\n\023EN_PROC" "ESS_TYPE_ZIP\020\002", 654); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "Progress.proto", &protobuf_RegisterTypes); ProgressInfo::default_instance_ = new ProgressInfo(); ProgressHandlerInfo::default_instance_ = new ProgressHandlerInfo(); MultErrorInfo::default_instance_ = new MultErrorInfo(); ProgressInfo::default_instance_->InitAsDefaultInstance(); ProgressHandlerInfo::default_instance_->InitAsDefaultInstance(); MultErrorInfo::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_Progress_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_Progress_2eproto { StaticDescriptorInitializer_Progress_2eproto() { protobuf_AddDesc_Progress_2eproto(); } } static_descriptor_initializer_Progress_2eproto_; const ::google::protobuf::EnumDescriptor* ProgressType_descriptor() { protobuf_AssignDescriptorsOnce(); return ProgressType_descriptor_; } bool ProgressType_IsValid(int value) { switch(value) { case 1: case 2: return true; default: return false; } } // =================================================================== const ::std::string ProgressInfo::_default_task_uuid_; #ifndef _MSC_VER const int ProgressInfo::kTaskUuidFieldNumber; const int ProgressInfo::kProgressFieldNumber; const int ProgressInfo::kResultFieldNumber; const int ProgressInfo::kErrorNumberFieldNumber; #endif // !_MSC_VER ProgressInfo::ProgressInfo() : ::google::protobuf::Message() { SharedCtor(); } void ProgressInfo::InitAsDefaultInstance() { } ProgressInfo::ProgressInfo(const ProgressInfo& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void ProgressInfo::SharedCtor() { _cached_size_ = 0; task_uuid_ = const_cast< ::std::string*>(&_default_task_uuid_); progress_ = 0; result_ = false; error_number_ = GOOGLE_LONGLONG(0); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } ProgressInfo::~ProgressInfo() { SharedDtor(); } void ProgressInfo::SharedDtor() { if (task_uuid_ != &_default_task_uuid_) { delete task_uuid_; } if (this != default_instance_) { } } void ProgressInfo::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* ProgressInfo::descriptor() { protobuf_AssignDescriptorsOnce(); return ProgressInfo_descriptor_; } const ProgressInfo& ProgressInfo::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_Progress_2eproto(); return *default_instance_; } ProgressInfo* ProgressInfo::default_instance_ = NULL; ProgressInfo* ProgressInfo::New() const { return new ProgressInfo; } void ProgressInfo::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (_has_bit(0)) { if (task_uuid_ != &_default_task_uuid_) { task_uuid_->clear(); } } progress_ = 0; result_ = false; error_number_ = GOOGLE_LONGLONG(0); } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool ProgressInfo::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required bytes task_uuid = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_task_uuid())); } else { goto handle_uninterpreted; } if (input->ExpectTag(21)) goto parse_progress; break; } // required float progress = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED32) { parse_progress: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &progress_))); _set_bit(1); } else { goto handle_uninterpreted; } if (input->ExpectTag(24)) goto parse_result; break; } // required bool result = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_result: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &result_))); _set_bit(2); } else { goto handle_uninterpreted; } if (input->ExpectTag(32)) goto parse_error_number; break; } // optional int64 error_number = 4; case 4: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_error_number: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &error_number_))); _set_bit(3); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void ProgressInfo::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required bytes task_uuid = 1; if (_has_bit(0)) { ::google::protobuf::internal::WireFormatLite::WriteBytes( 1, this->task_uuid(), output); } // required float progress = 2; if (_has_bit(1)) { ::google::protobuf::internal::WireFormatLite::WriteFloat(2, this->progress(), output); } // required bool result = 3; if (_has_bit(2)) { ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->result(), output); } // optional int64 error_number = 4; if (_has_bit(3)) { ::google::protobuf::internal::WireFormatLite::WriteInt64(4, this->error_number(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* ProgressInfo::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required bytes task_uuid = 1; if (_has_bit(0)) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->task_uuid(), target); } // required float progress = 2; if (_has_bit(1)) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(2, this->progress(), target); } // required bool result = 3; if (_has_bit(2)) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->result(), target); } // optional int64 error_number = 4; if (_has_bit(3)) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(4, this->error_number(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int ProgressInfo::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required bytes task_uuid = 1; if (has_task_uuid()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->task_uuid()); } // required float progress = 2; if (has_progress()) { total_size += 1 + 4; } // required bool result = 3; if (has_result()) { total_size += 1 + 1; } // optional int64 error_number = 4; if (has_error_number()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->error_number()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void ProgressInfo::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const ProgressInfo* source = ::google::protobuf::internal::dynamic_cast_if_available<const ProgressInfo*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void ProgressInfo::MergeFrom(const ProgressInfo& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from._has_bit(0)) { set_task_uuid(from.task_uuid()); } if (from._has_bit(1)) { set_progress(from.progress()); } if (from._has_bit(2)) { set_result(from.result()); } if (from._has_bit(3)) { set_error_number(from.error_number()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void ProgressInfo::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void ProgressInfo::CopyFrom(const ProgressInfo& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool ProgressInfo::IsInitialized() const { if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false; return true; } void ProgressInfo::Swap(ProgressInfo* other) { if (other != this) { std::swap(task_uuid_, other->task_uuid_); std::swap(progress_, other->progress_); std::swap(result_, other->result_); std::swap(error_number_, other->error_number_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata ProgressInfo::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = ProgressInfo_descriptor_; metadata.reflection = ProgressInfo_reflection_; return metadata; } // =================================================================== const ::std::string ProgressHandlerInfo::_default_task_uuid_; #ifndef _MSC_VER const int ProgressHandlerInfo::kTaskUuidFieldNumber; const int ProgressHandlerInfo::kProgressFieldNumber; const int ProgressHandlerInfo::kResultFieldNumber; const int ProgressHandlerInfo::kErrorNumberFieldNumber; const int ProgressHandlerInfo::kProgressTypeFieldNumber; const int ProgressHandlerInfo::kFileTotalNumFieldNumber; const int ProgressHandlerInfo::kFileFinishNumFieldNumber; const int ProgressHandlerInfo::kMultErrorNumberFieldNumber; #endif // !_MSC_VER ProgressHandlerInfo::ProgressHandlerInfo() : ::google::protobuf::Message() { SharedCtor(); } void ProgressHandlerInfo::InitAsDefaultInstance() { } ProgressHandlerInfo::ProgressHandlerInfo(const ProgressHandlerInfo& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void ProgressHandlerInfo::SharedCtor() { _cached_size_ = 0; task_uuid_ = const_cast< ::std::string*>(&_default_task_uuid_); progress_ = 0; result_ = false; error_number_ = GOOGLE_LONGLONG(0); progress_type_ = 1; file_total_num_ = GOOGLE_LONGLONG(0); file_finish_num_ = GOOGLE_LONGLONG(0); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } ProgressHandlerInfo::~ProgressHandlerInfo() { SharedDtor(); } void ProgressHandlerInfo::SharedDtor() { if (task_uuid_ != &_default_task_uuid_) { delete task_uuid_; } if (this != default_instance_) { } } void ProgressHandlerInfo::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* ProgressHandlerInfo::descriptor() { protobuf_AssignDescriptorsOnce(); return ProgressHandlerInfo_descriptor_; } const ProgressHandlerInfo& ProgressHandlerInfo::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_Progress_2eproto(); return *default_instance_; } ProgressHandlerInfo* ProgressHandlerInfo::default_instance_ = NULL; ProgressHandlerInfo* ProgressHandlerInfo::New() const { return new ProgressHandlerInfo; } void ProgressHandlerInfo::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (_has_bit(0)) { if (task_uuid_ != &_default_task_uuid_) { task_uuid_->clear(); } } progress_ = 0; result_ = false; error_number_ = GOOGLE_LONGLONG(0); progress_type_ = 1; file_total_num_ = GOOGLE_LONGLONG(0); file_finish_num_ = GOOGLE_LONGLONG(0); } mult_error_number_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool ProgressHandlerInfo::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required bytes task_uuid = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_task_uuid())); } else { goto handle_uninterpreted; } if (input->ExpectTag(21)) goto parse_progress; break; } // required float progress = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED32) { parse_progress: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &progress_))); _set_bit(1); } else { goto handle_uninterpreted; } if (input->ExpectTag(24)) goto parse_result; break; } // required bool result = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_result: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &result_))); _set_bit(2); } else { goto handle_uninterpreted; } if (input->ExpectTag(32)) goto parse_error_number; break; } // optional int64 error_number = 4; case 4: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_error_number: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &error_number_))); _set_bit(3); } else { goto handle_uninterpreted; } if (input->ExpectTag(40)) goto parse_progress_type; break; } // required .Progress.ProgressType progress_type = 5; case 5: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_progress_type: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (Progress::ProgressType_IsValid(value)) { set_progress_type(static_cast< Progress::ProgressType >(value)); } else { mutable_unknown_fields()->AddVarint(5, value); } } else { goto handle_uninterpreted; } if (input->ExpectTag(48)) goto parse_file_total_num; break; } // optional int64 file_total_num = 6; case 6: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_file_total_num: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &file_total_num_))); _set_bit(5); } else { goto handle_uninterpreted; } if (input->ExpectTag(56)) goto parse_file_finish_num; break; } // optional int64 file_finish_num = 7; case 7: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_file_finish_num: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &file_finish_num_))); _set_bit(6); } else { goto handle_uninterpreted; } if (input->ExpectTag(66)) goto parse_mult_error_number; break; } // repeated .Progress.MultErrorInfo mult_error_number = 8; case 8: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_mult_error_number: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_mult_error_number())); } else { goto handle_uninterpreted; } if (input->ExpectTag(66)) goto parse_mult_error_number; if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void ProgressHandlerInfo::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required bytes task_uuid = 1; if (_has_bit(0)) { ::google::protobuf::internal::WireFormatLite::WriteBytes( 1, this->task_uuid(), output); } // required float progress = 2; if (_has_bit(1)) { ::google::protobuf::internal::WireFormatLite::WriteFloat(2, this->progress(), output); } // required bool result = 3; if (_has_bit(2)) { ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->result(), output); } // optional int64 error_number = 4; if (_has_bit(3)) { ::google::protobuf::internal::WireFormatLite::WriteInt64(4, this->error_number(), output); } // required .Progress.ProgressType progress_type = 5; if (_has_bit(4)) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 5, this->progress_type(), output); } // optional int64 file_total_num = 6; if (_has_bit(5)) { ::google::protobuf::internal::WireFormatLite::WriteInt64(6, this->file_total_num(), output); } // optional int64 file_finish_num = 7; if (_has_bit(6)) { ::google::protobuf::internal::WireFormatLite::WriteInt64(7, this->file_finish_num(), output); } // repeated .Progress.MultErrorInfo mult_error_number = 8; for (int i = 0; i < this->mult_error_number_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 8, this->mult_error_number(i), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* ProgressHandlerInfo::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required bytes task_uuid = 1; if (_has_bit(0)) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->task_uuid(), target); } // required float progress = 2; if (_has_bit(1)) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(2, this->progress(), target); } // required bool result = 3; if (_has_bit(2)) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->result(), target); } // optional int64 error_number = 4; if (_has_bit(3)) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(4, this->error_number(), target); } // required .Progress.ProgressType progress_type = 5; if (_has_bit(4)) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 5, this->progress_type(), target); } // optional int64 file_total_num = 6; if (_has_bit(5)) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(6, this->file_total_num(), target); } // optional int64 file_finish_num = 7; if (_has_bit(6)) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(7, this->file_finish_num(), target); } // repeated .Progress.MultErrorInfo mult_error_number = 8; for (int i = 0; i < this->mult_error_number_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 8, this->mult_error_number(i), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int ProgressHandlerInfo::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required bytes task_uuid = 1; if (has_task_uuid()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->task_uuid()); } // required float progress = 2; if (has_progress()) { total_size += 1 + 4; } // required bool result = 3; if (has_result()) { total_size += 1 + 1; } // optional int64 error_number = 4; if (has_error_number()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->error_number()); } // required .Progress.ProgressType progress_type = 5; if (has_progress_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->progress_type()); } // optional int64 file_total_num = 6; if (has_file_total_num()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->file_total_num()); } // optional int64 file_finish_num = 7; if (has_file_finish_num()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->file_finish_num()); } } // repeated .Progress.MultErrorInfo mult_error_number = 8; total_size += 1 * this->mult_error_number_size(); for (int i = 0; i < this->mult_error_number_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->mult_error_number(i)); } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void ProgressHandlerInfo::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const ProgressHandlerInfo* source = ::google::protobuf::internal::dynamic_cast_if_available<const ProgressHandlerInfo*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void ProgressHandlerInfo::MergeFrom(const ProgressHandlerInfo& from) { GOOGLE_CHECK_NE(&from, this); mult_error_number_.MergeFrom(from.mult_error_number_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from._has_bit(0)) { set_task_uuid(from.task_uuid()); } if (from._has_bit(1)) { set_progress(from.progress()); } if (from._has_bit(2)) { set_result(from.result()); } if (from._has_bit(3)) { set_error_number(from.error_number()); } if (from._has_bit(4)) { set_progress_type(from.progress_type()); } if (from._has_bit(5)) { set_file_total_num(from.file_total_num()); } if (from._has_bit(6)) { set_file_finish_num(from.file_finish_num()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void ProgressHandlerInfo::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void ProgressHandlerInfo::CopyFrom(const ProgressHandlerInfo& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool ProgressHandlerInfo::IsInitialized() const { if ((_has_bits_[0] & 0x00000017) != 0x00000017) return false; for (int i = 0; i < mult_error_number_size(); i++) { if (!this->mult_error_number(i).IsInitialized()) return false; } return true; } void ProgressHandlerInfo::Swap(ProgressHandlerInfo* other) { if (other != this) { std::swap(task_uuid_, other->task_uuid_); std::swap(progress_, other->progress_); std::swap(result_, other->result_); std::swap(error_number_, other->error_number_); std::swap(progress_type_, other->progress_type_); std::swap(file_total_num_, other->file_total_num_); std::swap(file_finish_num_, other->file_finish_num_); mult_error_number_.Swap(&other->mult_error_number_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata ProgressHandlerInfo::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = ProgressHandlerInfo_descriptor_; metadata.reflection = ProgressHandlerInfo_reflection_; return metadata; } // =================================================================== const ::std::string MultErrorInfo::_default_login_uuid_; #ifndef _MSC_VER const int MultErrorInfo::kTaskHandlerFieldNumber; const int MultErrorInfo::kIsStartFieldNumber; const int MultErrorInfo::kIsFinishedFieldNumber; const int MultErrorInfo::kResultFieldNumber; const int MultErrorInfo::kFileserviceErrorFieldNumber; const int MultErrorInfo::kHandlerErrerFieldNumber; const int MultErrorInfo::kLoginUuidFieldNumber; #endif // !_MSC_VER MultErrorInfo::MultErrorInfo() : ::google::protobuf::Message() { SharedCtor(); } void MultErrorInfo::InitAsDefaultInstance() { } MultErrorInfo::MultErrorInfo(const MultErrorInfo& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void MultErrorInfo::SharedCtor() { _cached_size_ = 0; task_handler_ = 1; is_start_ = false; is_finished_ = false; result_ = false; fileservice_error_ = GOOGLE_LONGLONG(0); handler_errer_ = GOOGLE_LONGLONG(0); login_uuid_ = const_cast< ::std::string*>(&_default_login_uuid_); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } MultErrorInfo::~MultErrorInfo() { SharedDtor(); } void MultErrorInfo::SharedDtor() { if (login_uuid_ != &_default_login_uuid_) { delete login_uuid_; } if (this != default_instance_) { } } void MultErrorInfo::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* MultErrorInfo::descriptor() { protobuf_AssignDescriptorsOnce(); return MultErrorInfo_descriptor_; } const MultErrorInfo& MultErrorInfo::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_Progress_2eproto(); return *default_instance_; } MultErrorInfo* MultErrorInfo::default_instance_ = NULL; MultErrorInfo* MultErrorInfo::New() const { return new MultErrorInfo; } void MultErrorInfo::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { task_handler_ = 1; is_start_ = false; is_finished_ = false; result_ = false; fileservice_error_ = GOOGLE_LONGLONG(0); handler_errer_ = GOOGLE_LONGLONG(0); if (_has_bit(6)) { if (login_uuid_ != &_default_login_uuid_) { login_uuid_->clear(); } } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool MultErrorInfo::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required .LogExportTask.TaskHandler task_handler = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (LogExportTask::TaskHandler_IsValid(value)) { set_task_handler(static_cast< LogExportTask::TaskHandler >(value)); } else { mutable_unknown_fields()->AddVarint(1, value); } } else { goto handle_uninterpreted; } if (input->ExpectTag(16)) goto parse_is_start; break; } // required bool is_start = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_is_start: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &is_start_))); _set_bit(1); } else { goto handle_uninterpreted; } if (input->ExpectTag(24)) goto parse_is_finished; break; } // required bool is_finished = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_is_finished: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &is_finished_))); _set_bit(2); } else { goto handle_uninterpreted; } if (input->ExpectTag(32)) goto parse_result; break; } // required bool result = 4; case 4: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_result: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &result_))); _set_bit(3); } else { goto handle_uninterpreted; } if (input->ExpectTag(40)) goto parse_fileservice_error; break; } // required int64 fileservice_error = 5; case 5: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_fileservice_error: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &fileservice_error_))); _set_bit(4); } else { goto handle_uninterpreted; } if (input->ExpectTag(48)) goto parse_handler_errer; break; } // required int64 handler_errer = 6; case 6: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_handler_errer: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &handler_errer_))); _set_bit(5); } else { goto handle_uninterpreted; } if (input->ExpectTag(58)) goto parse_login_uuid; break; } // optional bytes login_uuid = 7; case 7: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_login_uuid: DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_login_uuid())); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void MultErrorInfo::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required .LogExportTask.TaskHandler task_handler = 1; if (_has_bit(0)) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->task_handler(), output); } // required bool is_start = 2; if (_has_bit(1)) { ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->is_start(), output); } // required bool is_finished = 3; if (_has_bit(2)) { ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->is_finished(), output); } // required bool result = 4; if (_has_bit(3)) { ::google::protobuf::internal::WireFormatLite::WriteBool(4, this->result(), output); } // required int64 fileservice_error = 5; if (_has_bit(4)) { ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->fileservice_error(), output); } // required int64 handler_errer = 6; if (_has_bit(5)) { ::google::protobuf::internal::WireFormatLite::WriteInt64(6, this->handler_errer(), output); } // optional bytes login_uuid = 7; if (_has_bit(6)) { ::google::protobuf::internal::WireFormatLite::WriteBytes( 7, this->login_uuid(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* MultErrorInfo::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required .LogExportTask.TaskHandler task_handler = 1; if (_has_bit(0)) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->task_handler(), target); } // required bool is_start = 2; if (_has_bit(1)) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->is_start(), target); } // required bool is_finished = 3; if (_has_bit(2)) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->is_finished(), target); } // required bool result = 4; if (_has_bit(3)) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->result(), target); } // required int64 fileservice_error = 5; if (_has_bit(4)) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->fileservice_error(), target); } // required int64 handler_errer = 6; if (_has_bit(5)) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(6, this->handler_errer(), target); } // optional bytes login_uuid = 7; if (_has_bit(6)) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 7, this->login_uuid(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int MultErrorInfo::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required .LogExportTask.TaskHandler task_handler = 1; if (has_task_handler()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->task_handler()); } // required bool is_start = 2; if (has_is_start()) { total_size += 1 + 1; } // required bool is_finished = 3; if (has_is_finished()) { total_size += 1 + 1; } // required bool result = 4; if (has_result()) { total_size += 1 + 1; } // required int64 fileservice_error = 5; if (has_fileservice_error()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->fileservice_error()); } // required int64 handler_errer = 6; if (has_handler_errer()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->handler_errer()); } // optional bytes login_uuid = 7; if (has_login_uuid()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->login_uuid()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void MultErrorInfo::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const MultErrorInfo* source = ::google::protobuf::internal::dynamic_cast_if_available<const MultErrorInfo*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void MultErrorInfo::MergeFrom(const MultErrorInfo& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from._has_bit(0)) { set_task_handler(from.task_handler()); } if (from._has_bit(1)) { set_is_start(from.is_start()); } if (from._has_bit(2)) { set_is_finished(from.is_finished()); } if (from._has_bit(3)) { set_result(from.result()); } if (from._has_bit(4)) { set_fileservice_error(from.fileservice_error()); } if (from._has_bit(5)) { set_handler_errer(from.handler_errer()); } if (from._has_bit(6)) { set_login_uuid(from.login_uuid()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void MultErrorInfo::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void MultErrorInfo::CopyFrom(const MultErrorInfo& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool MultErrorInfo::IsInitialized() const { if ((_has_bits_[0] & 0x0000003f) != 0x0000003f) return false; return true; } void MultErrorInfo::Swap(MultErrorInfo* other) { if (other != this) { std::swap(task_handler_, other->task_handler_); std::swap(is_start_, other->is_start_); std::swap(is_finished_, other->is_finished_); std::swap(result_, other->result_); std::swap(fileservice_error_, other->fileservice_error_); std::swap(handler_errer_, other->handler_errer_); std::swap(login_uuid_, other->login_uuid_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata MultErrorInfo::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = MultErrorInfo_descriptor_; metadata.reflection = MultErrorInfo_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) } // namespace Progress // @@protoc_insertion_point(global_scope)
84f4f0dd815ef058242e474f6a54de5aeb84902f
0f0e9dc1b06211e9b7cbe542b2d89f5f2c4e98ef
/analysis/h5analysis/include/Jet.hpp
d6835bc036cf17177771bdaeb1714a2bd881cd17
[]
no_license
dgeissbue/autoencodeSVJ
07a7708cb9a04ed0faf19ff2370d1d8a4d1a8059
57ce01eb19688155267e69a126437c5b787f6e34
refs/heads/master
2023-06-05T16:19:40.444189
2021-06-28T12:16:00
2021-06-28T12:16:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
473
hpp
Jet.hpp
// // Jet.hpp // h5parser // // Created by Jeremi Niedziela on 17/07/2020. // Copyright © 2020 Jeremi Niedziela. All rights reserved. // #ifndef Jet_hpp #define Jet_hpp #include "Helpers.hpp" #include "Constituent.hpp" class Jet { public: Jet(){} double eta, phi, pt, mass, chargedFraction, PTD, axis2, flavor, energy; vector<double> EFPs; vector<shared_ptr<Constituent>> constituents; bool isEmpty(); void print(); }; #endif /* Jet_hpp */
8788e31fa0126c38a41eeace09c2cf8ef3668878
815ae13bcfb110873a1581df60b9ac845f2dc409
/Scene/SceneBase.h
9fe97758c1d2318ff6843d5d2016a6269ca6b8dc
[]
no_license
idham9206/SlimeDungeonCrawl
f743ce73aecb7dc06f95ffb8ba7e91ce5f59a0f8
68269578bdc3b0b885ac7c31ab4be5b541f00c28
refs/heads/master
2020-04-08T10:27:42.428554
2019-07-09T03:04:37
2019-07-09T03:04:37
159,269,884
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,904
h
SceneBase.h
////====================================================//// //// ベースシーン クラス //// //// //// //// 作者:ムハマドイダム //// ////====================================================//// #pragma once #include "../DeviceResources.h" #include <CommonStates.h> class SceneBase { public: SceneBase(); ~SceneBase(); virtual void Initialize(DX::DeviceResources* deviceResources, DirectX::CommonStates* states) = 0; virtual SceneBase* Update(float elapsedTime) = 0; virtual void Render() = 0; virtual void Reset() = 0; //キートリガーの関数 void KeyTriggerFunction(); //=============================================================== //セッターゲッターまとめ //ビュー void SetView(DirectX::SimpleMath::Matrix view) { m_view = view; } DirectX::SimpleMath::Matrix GetView() { return m_view; } //アイ void SetEye(DirectX::SimpleMath::Vector3 eye) { m_eye = eye; } DirectX::SimpleMath::Vector3 GetEye() { return m_eye; } //射影 void SetProjection(DirectX::SimpleMath::Matrix projection) { m_projection = projection; } DirectX::SimpleMath::Matrix GetProjection() { return m_projection; } //ワールド void SetWorld(DirectX::SimpleMath::Matrix world) { m_world = world; } DirectX::SimpleMath::Matrix GetWorld() { return m_world; } protected: //仮のデバイスリソーシズ DX::DeviceResources* m_deviceResources; //仮のコモンステーツ DirectX::CommonStates* m_states; // ワールド行列 DirectX::SimpleMath::Matrix m_world; // ビュー行列 DirectX::SimpleMath::Matrix m_view; // 射影行列 DirectX::SimpleMath::Matrix m_projection; //アイ行列 DirectX::SimpleMath::Vector3 m_eye; //キーボードのトリガー変数 int keyCountSpace; int keyCountUp; int keyCountDown; int keyCountLeft; int keyCountRight; int keyCountNumber0; int keyCountNumber1; };
2b718e8bfd03f3662e835eec0a6d77cb5de72b9f
485faf9d4ec7def9a505149c6a491d6133e68750
/src/apps/gateway/GatewayPrefsGUI.H
4fb5a5f28b262b343450192518bda56bf909722d
[ "LicenseRef-scancode-warranty-disclaimer", "ECL-2.0" ]
permissive
ohlincha/ECCE
af02101d161bae7e9b05dc7fe6b10ca07f479c6b
7461559888d829338f29ce5fcdaf9e1816042bfe
refs/heads/master
2020-06-25T20:59:27.882036
2017-06-16T10:45:21
2017-06-16T10:45:21
94,240,259
1
1
null
null
null
null
UTF-8
C++
false
false
4,985
h
GatewayPrefsGUI.H
///////////////////////////////////////////////////////////////////////////// // Name: GatewayPrefsGUI.H // Purpose: // Author: Lisong Sun // Modified by: // RCS-ID: // Licence: ///////////////////////////////////////////////////////////////////////////// #ifndef _GATEWAYPREFSGUI_H_ #define _GATEWAYPREFSGUI_H_ #if defined(__GNUG__) && !defined(__APPLE__) #pragma interface "GatewayPrefsGUI.C" #endif /*! * Includes */ ////@begin includes #include "wx/frame.h" #include "wxgui/ewxFrame.H" ////@end includes /*! * Forward declarations */ ////@begin forward declarations class ewxChoice; class ewxCheckBox; class wxGridSizer; class ewxButton; class ewxChoice; class ewxButton; class ewxCheckBox; class ewxFrame; ////@end forward declarations /*! * Control identifiers */ ////@begin control identifiers #define SYMBOL_GATEWAYPREFSGUI_STYLE wxCAPTION|wxSYSTEM_MENU|wxMINIMIZE_BOX|wxCLOSE_BOX #define SYMBOL_GATEWAYPREFSGUI_TITLE _("ECCE Gateway and Global Preferences") #define SYMBOL_GATEWAYPREFSGUI_IDNAME ID_GATEWAYPREF_FRAME #define SYMBOL_GATEWAYPREFSGUI_SIZE wxDefaultSize #define SYMBOL_GATEWAYPREFSGUI_POSITION wxDefaultPosition ////@end control identifiers /*! * Compatibility */ #ifndef wxCLOSE_BOX #define wxCLOSE_BOX 0x1000 #endif /*! * GatewayPrefsGUI class declaration */ class GatewayPrefsGUI: public ewxFrame { DECLARE_CLASS( GatewayPrefsGUI ) DECLARE_EVENT_TABLE() public: /// Constructors GatewayPrefsGUI( ); GatewayPrefsGUI( wxWindow* parent, wxWindowID id = SYMBOL_GATEWAYPREFSGUI_IDNAME, const wxString& caption = SYMBOL_GATEWAYPREFSGUI_TITLE, const wxPoint& pos = SYMBOL_GATEWAYPREFSGUI_POSITION, const wxSize& size = SYMBOL_GATEWAYPREFSGUI_SIZE, long style = SYMBOL_GATEWAYPREFSGUI_STYLE ); bool Create( wxWindow* parent, wxWindowID id = SYMBOL_GATEWAYPREFSGUI_IDNAME, const wxString& caption = SYMBOL_GATEWAYPREFSGUI_TITLE, const wxPoint& pos = SYMBOL_GATEWAYPREFSGUI_POSITION, const wxSize& size = SYMBOL_GATEWAYPREFSGUI_SIZE, long style = SYMBOL_GATEWAYPREFSGUI_STYLE ); /// Creates the controls and sizers void CreateControls(); ////@begin GatewayPrefsGUI event handler declarations /// wxEVT_CLOSE_WINDOW event handler for ID_GATEWAYPREF_FRAME virtual void OnCloseWindow( wxCloseEvent& event ); /// wxEVT_COMMAND_CHOICE_SELECTED event handler for ID_THEME_CHOICE virtual void OnThemeChoiceSelected( wxCommandEvent& event ); /// wxEVT_COMMAND_CHOICE_SELECTED event handler for ID_FONTSIZE virtual void OnGlobalPrefChange( wxCommandEvent& event ); /// wxEVT_COMMAND_CHECKBOX_CLICKED event handler for ID_SHOWCONFIRM_CHECKBOX virtual void OnGatewayPrefChange( wxCommandEvent& event ); /// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_CLOSE_BUTTON virtual void OnCloseButtonClick( wxCommandEvent& event ); /// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RESETALL_BUTTON virtual void OnResetAllButtonClick( wxCommandEvent& event ); ////@end GatewayPrefsGUI event handler declarations ////@begin GatewayPrefsGUI member function declarations /// Retrieves bitmap resources wxBitmap GetBitmapResource( const wxString& name ); /// Retrieves icon resources wxIcon GetIconResource( const wxString& name ); ////@end GatewayPrefsGUI member function declarations /// Should we show tooltips? static bool ShowToolTips(); ////@begin GatewayPrefsGUI member variables ewxChoice* p_colorTheme; ewxChoice* p_fontSize; ewxChoice* p_dateFormat; ewxChoice* p_timeFormat; ewxChoice* p_unit; ewxCheckBox* p_beepError; ewxCheckBox* p_beepWarn; ewxCheckBox* p_focus; ewxCheckBox* p_confirmExit; ewxCheckBox* p_showBusy; ewxCheckBox* p_alwaysOnTop; ewxCheckBox* p_leftClickNewApp; ewxCheckBox* p_closeShells; ewxCheckBox* p_savePasswords; ewxChoice* p_orientation; wxGridSizer* p_stateIconSizer; ewxButton* p_resetAll; static const wxWindowID ID_SHOWBUSY_CHECKBOX; static const wxWindowID ID_BEEPWARN_CHECKBOX; static const wxWindowID ID_ALWAYS_ON_TOP; static const wxWindowID ID_UNIT_CHOICE; static const wxWindowID ID_TIMEFORMAT_CHOICE; static const wxWindowID ID_ORIENTATION; static const wxWindowID ID_FONTSIZE; static const wxWindowID ID_CLOSE_BUTTON; static const wxWindowID ID_BEEPERROR_CHECKBOX; static const wxWindowID ID_SHOWCONFIRM_CHECKBOX; static const wxWindowID ID_THEME_CHOICE; static const wxWindowID ID_RESETALL_BUTTON; static const wxWindowID ID_GATEWAYPREF_FRAME; static const wxWindowID ID_LEFTCLICK_NEWAPP; static const wxWindowID ID_HELP_BUTTON; static const wxWindowID ID_SAVEPASSWORDS_CHECKBOX; static const wxWindowID ID_DATEFORMAT_CHOICE; static const wxWindowID ID_FOCUS_FOLLOW_MOUSE; static const wxWindowID ID_CLOSESHELLS_CHECKBOX; ////@end GatewayPrefsGUI member variables }; #endif // _GATEWAYPREFSGUI_H_
01d5bb050deed146213f7bfd73e63a0f7c808cfa
14b0436b62bad927e467fb62f70f5b492109da7b
/kmc_events_ircal.cpp
233f74fffd4cfbb3766642e3a3d16bed39d89d03
[]
no_license
muskyhuang/kMC_simulator
fb14402700c704f3d3b48d3b314bf149d5572f34
e146c39362dab0ead0b96f2192e87390c7ad61ba
refs/heads/master
2021-01-10T06:51:13.480380
2015-12-31T23:42:26
2015-12-31T23:42:26
51,041,335
0
0
null
null
null
null
UTF-8
C++
false
false
6,674
cpp
kmc_events_ircal.cpp
#include <iostream> #include <cmath> #include <vector> #include "kmc_global.h" #include "kmc_events.h" using namespace std; double class_events::cal_ratesI(vector <int> &etype, vector <double> &rates, vector <int> &ilist, vector <int> &nltcp, vector <int> &jatom){ double sum_rate= 0; if(nAA + nAB + nBB != list_itl.size()) error(2, "(cal_ratesI) itl number inconsistent"); for(int ii=0; ii < list_itl.size(); ii ++){ // ii: index of interstitial int ltcp= list_itl[ii].ltcp; int i= (int) (ltcp/nz)/ny; int j= (int) (ltcp/nz)%ny; int k= (int) ltcp%nz; const int stateI= states[i][j][k]; // state of the itl if(1==abs(states[i][j][k])) error(2, "(itl_jump) there's an non-interstitial in the itl list"); int ja; if(2==stateI) ja= 1; else ja=-1; // for 0==stateI try -1 first and then 1 do{ vector< vector <int> > rlist(3); // collect xyz to recover marker double em, mu; // if(1==ja) { em= emiA; mu= muiA;} // WARNING! the dir move (AB atoms move in 2 ways) and rot move removed // else { em= emiB; mu= muiB;} if(1==ja) mu= muiA; // !!! only for Dubey, CMS 2015 !!! else mu= muiB; // !!! switch(stateI){ // !!! case 2: em= emiAA; break; case 0: em= emiAB; break; case -2: em= emiBB; break; default: error(2, "(cal_ratesI) an unknown itl type", 1, stateI); } // !!! for(int a=0; a<n1nbr; a ++){ int x= pbc(i+v1nbr[a][0], nx); int y= pbc(j+v1nbr[a][1], ny); int z= pbc(k+v1nbr[a][2], nz); const int stateA= states[x][y][z]; // state of the atom if(stateA != 1 && stateA != -1) continue; // altho recb jump checks 1st-nn of 1st-nn, but only possible if I next to A // check if it's a recb jump bool is_recb= false; for(int b=0; b<n1nbr; b ++){ int xb= pbc(x+v1nbr[b][0], nx); int yb= pbc(y+v1nbr[b][1], ny); int zb= pbc(z+v1nbr[b][2], nz); const int stateB= states[xb][yb][zb]; if((stateB != 0 && stateB != 4) || itlAB[xb][yb][zb]) continue; // if it's not vcc or vacuum, don't do is_recb= true; if(marker[xb][yb][zb]) continue; // if it's already counted, don't do (but is_recb should be turned true) marker[xb][yb][zb]= true; // mark this ltcp so won't do it again rlist[0].push_back(xb); // collect xyz for marker recovery rlist[1].push_back(yb); rlist[2].push_back(zb); // calculate energy diff double e0= cal_energy(true, i, j, k, xb, yb, zb); states[i][j][k] -= ja; states[xb][yb][zb] = ja; if(0==stateI) itlAB[i][j][k]= false; double ediff= cal_energy(true, i, j, k, xb, yb, zb) - e0; states[i][j][k] = stateI; //transit back states[xb][yb][zb] = stateB; if(0==stateI) itlAB[i][j][k]= true; if((em+0.5*ediff)<0){ double e= em+0.5*ediff; rates.push_back(e); is_inf= true; list_inf.push_back(rates.size()-1); if(e<einf) einf= e; } else if(0==stateI) rates.push_back(0.5 * mu * exp(-beta*(em+0.5*ediff))); // itlAB has 2 jumps(A, B), and hence divided by 2 here else rates.push_back( mu * exp(-beta*(em+0.5*ediff))); etype.push_back(0); ilist.push_back(ii); nltcp.push_back(xb*ny*nz+yb*nz+zb); jatom.push_back(ja); sum_rate += rates.back(); } if(is_recb) marker[x][y][z]= true; // mark this ltcp. don't do in cal_vrates else{ // calculate energy diff double e0= cal_energy(true, i, j, k, x, y, z); states[i][j][k] -= ja; // perform imag jump states[x][y][z] += ja; if(0==stateI) itlAB[i][j][k]= false; if(0==states[x][y][z]) itlAB[x][y][z]= true; double ediff= cal_energy(true, i, j, k, x, y, z) - e0; double ec; // !!! only for Dubey, CMS 2015 !!! switch(states[x][y][z]-stateI){ // !!! case 0: ec= 0; break; case 2: if(0==stateI) ec= eciABtAA; else ec= eciBBtAB; break; case -2: if(0==stateI) ec= eciABtBB; else ec= eciAAtAB; break; default: error(2, "(cal_ratesI) an unknown conversion type: (diff)", 1, states[x][y][z]-stateI); } // !!! states[i][j][k] = stateI; //transit back states[x][y][z] = stateA; if(0==stateI) itlAB[i][j][k]= true; itlAB[x][y][z]= false; if((ec+em+0.5*ediff)<0){ double e= ec+em+0.5*ediff; rates.push_back(e); is_inf= true; list_inf.push_back(rates.size()-1); if(e<einf) einf= e; } else if(0==stateI) rates.push_back(0.5 * mu * exp(-beta*(ec+em+0.5*ediff))); // itlAB has 2 jumps: via A or B. so divided by 2 here else rates.push_back( mu * exp(-beta*(ec+em+0.5*ediff))); etype.push_back(0); ilist.push_back(ii); nltcp.push_back(x*ny*nz+y*nz+z); jatom.push_back(ja); sum_rate += rates.back(); } } for(int j= 0; j<rlist[0].size(); j ++) marker[rlist[0].at(j)][rlist[1].at(j)][rlist[2].at(j)]= false; ja += 2; }while(0==stateI && 1==ja); } return sum_rate; }
83b085b9aedc88d96000fc5ccbac2c50efd15cee
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir8254/dir8444/dir8720/dir10555/dir10556/file10568.cpp
e8117a2a3c8df79c9ab6831a37da3036ab6229a4
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
file10568.cpp
#ifndef file10568 #error "macro file10568 must be defined" #endif static const char* file10568String = "file10568";
bd79c442d419cb49feb4788d53b6dcf8850adf92
12860ce51995e0a893f5b8f109a99faa53590aa4
/designpattern/3-builder/ASetMealBuilder.cpp
51171a760716eb3b2164d4ca5aab061f4cd4df0b
[]
no_license
owenl19880929/study
a6f9ae85f606621c378e7d477959a1ee8e32d583
ae6ec95ca73de49231d988226a2dd3eab36e5dbe
refs/heads/master
2023-04-30T18:49:07.384279
2023-04-14T07:09:41
2023-04-14T07:09:41
120,842,991
0
0
null
null
null
null
UTF-8
C++
false
false
600
cpp
ASetMealBuilder.cpp
#include "SetMeal.h" #include "ASetMealBuilder.h" ASetMealBuilder::ASetMealBuilder(){ meal = new Meal(); } ASetMealBuilder::~ASetMealBuilder(){ delete meal; meal = NULL; } void ASetMealBuilder::buildMainFood(){ cout<<"A setmeal: buildMainFood...\n"<<endl; meal->setMainFood(SETMEALA[0]); } void ASetMealBuilder::buildSideFood(){ cout<<"A setmeal: buildSideFood...\n"<<endl; meal->setSideFood(SETMEALA[1]); } void ASetMealBuilder::buildDrinkFood(){ cout<<"A setmeal: buildDrinkFood...\n"<<endl; meal->setDrinkFood(SETMEALA[2]); }
58f0fb0c61131eb536e498ca042edfe4121abae3
9f11125cf6a4129c6108c18269bcaaf74e8a9b77
/SourceCode/QEvent/Backend/QSelect.cpp
3066819bbb4de022f983202f15431a6b8f4b5826
[]
no_license
ButlerZhang/Zero
22cc74cfb835d5dea915f9f6c6aa406893fc8c43
2fb1adbe97a1b5a1fa2c385eef9e11136e6ec34e
refs/heads/master
2021-05-18T07:47:42.518583
2020-04-28T06:57:21
2020-04-28T06:57:21
251,185,649
0
0
null
null
null
null
UTF-8
C++
false
false
2,949
cpp
QSelect.cpp
#include "QSelect.h" #include "../QEventLoop.h" #include "../QTimer.h" #include "../QLog.h" #include <cstring> //strerror QSelect::QSelect(QEventLoop &EventLoop) : QBackend(EventLoop) { m_HighestEventFD = 0; m_BackendName = "select"; FD_ZERO(&m_ReadSetIn); FD_ZERO(&m_WriteSetIn); } QSelect::~QSelect() { } bool QSelect::AddEvent(const std::shared_ptr<QChannel> &Channel) { if (!QBackend::AddEvent(Channel)) { return false; } if (Channel->GetEvents() & QET_READ) { FD_SET(Channel->GetFD(), &m_ReadSetIn); g_Log.WriteDebug("select: FD = %d add read event.", Channel->GetFD()); } if (Channel->GetEvents() & QET_WRITE) { FD_SET(Channel->GetFD(), &m_WriteSetIn); g_Log.WriteDebug("select: FD = %d add write event.", Channel->GetFD()); } if (m_HighestEventFD <= Channel->GetFD()) { m_HighestEventFD = Channel->GetFD() + 1; g_Log.WriteDebug("select: Highest event FD = %d after added.", m_HighestEventFD); } return AddEventToChannelMap(Channel, QEO_ADD); } bool QSelect::DelEvent(const std::shared_ptr<QChannel> &Channel) { if (!QBackend::DelEvent(Channel)) { return false; } FD_CLR(Channel->GetFD(), &m_ReadSetIn); FD_CLR(Channel->GetFD(), &m_WriteSetIn); for (int FD = m_HighestEventFD - 1; FD >= 0; FD--) { if (FD_ISSET(FD, &m_ReadSetIn) || FD_ISSET(FD, &m_WriteSetIn)) { break; } --m_HighestEventFD; } g_Log.WriteDebug("select: Highest event FD = %d after deleted.", m_HighestEventFD); return DelEventFromChannelMap(Channel, QEO_DEL); } bool QSelect::Dispatch(timeval &tv) { memcpy(&m_ReadSetOut, &m_ReadSetIn, sizeof(m_ReadSetIn)); memcpy(&m_WriteSetOut, &m_WriteSetIn, sizeof(m_WriteSetIn)); g_Log.WriteDebug("select: start..."); timeval *TempTimeout = QTimer::IsValid(tv) ? &tv : NULL; int Result = select(m_HighestEventFD, &m_ReadSetOut, &m_WriteSetOut, NULL, TempTimeout); g_Log.WriteDebug("select: stop, result = %d.", Result); if (Result < 0) { if (errno != EINTR) { g_Log.WriteError("select error : %s", strerror(errno)); m_EventLoop.StopLoop(); return false; } } if (Result == 0) { ActiveEvent(m_EventLoop.GetTimer()->GetFD(), 0); } else { for (int FD = 0; FD < m_HighestEventFD; FD++) { int ResultEvents = 0; if (FD_ISSET(FD, &m_ReadSetOut)) { ResultEvents |= QET_READ; } if (FD_ISSET(FD, &m_WriteSetOut)) { ResultEvents |= QET_WRITE; } if (ResultEvents > 0) { ActiveEvent(FD, ResultEvents); } } } return true; }
ac397d15a3b49f0f4b89e9099f7b3238b2eaac45
30e232395ac52f440c413f2e60a0b34a41806233
/Code/MBED_CAN.cpp
797f707a000b482645fc1534b5809310bd615596
[]
no_license
alex7709/ECE4180F19_CAN_Project
7aa92167fec0fdeef23095b8389f45161061f13c
fe22bf67c69f9c17e78a1134a568778de56f7777
refs/heads/master
2020-09-23T05:35:32.536252
2019-12-10T15:53:01
2019-12-10T15:53:01
225,417,553
0
0
null
null
null
null
UTF-8
C++
false
false
1,585
cpp
MBED_CAN.cpp
#include "mbed.h" #include "CAN.h" #include "PinDetect.h" DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led4(LED4); PinDetect filter_in(p8); CAN can2(p30, p29); Serial pc(USBTX, USBRX); // tx, rx int volatile handle=0x00; unsigned int volatile id=0xAA;//message id for address 0. Default and initial unsigned int volatile mask=0xFF; CANFormat volatile format = CANAny; int arrived; void filter_0(void) { handle=0; pc.printf("Filter Off\n"); } void filter_1(void) { //id = 0xff;change if different than initiailization value handle = can2.filter(id, mask, format, 1); pc.printf("Filter On\n"); //need message ID and mask for it if applicable. ID 11 bits } int main() { filter_in.mode(PullUp); //Need PinDetect filter_in.attach_deasserted(&filter_0); filter_in.attach_asserted(&filter_1); pc.printf("Beginning CAN Read\n"); CANMessage msg;can2.frequency(150000); while(1) { unsigned char error=can2.rderror(); int error_int=error; pc.printf("Error: %d\n",error_int); if(error_int>0) { led1=1; can2.reset(); wait(0.1); led1=0; } arrived = can2.read(msg);//dont forget handle when redoing pc.printf("Message Arrived: %d\n",arrived); if(arrived) { pc.printf("Message Byte 1: %d\n", msg.data[0]); pc.printf("Message Byte 2: %d\n", msg.data[1]); pc.printf("Message Byte 3: %d\n", msg.data[2]); led2 = !led2; } led4 = !led4; wait(0.1); } }
93fde21be9325010c3d6397f80e87e703dc0f707
b22e123423f4fef4247851336a947a6903c3c90f
/Projet Identifiant micro/src/main.cpp
803e800e4f7688af677531d1f8962f627831c774
[]
no_license
torresgerson/Test-Touch
63b102f160f0caa935dd171fa54ba1b0d4868536
031fc731f938f72582a790988e4607e4d32f74d2
refs/heads/main
2023-08-29T15:18:42.312006
2021-11-08T08:50:29
2021-11-08T08:50:29
425,744,258
0
0
null
null
null
null
UTF-8
C++
false
false
200
cpp
main.cpp
#include <Arduino.h> #include "WiFi.h" void setup(){ Serial.begin(115200); WiFi.mode(WIFI_MODE_STA); Serial.print("ESP32 Chip ID = "); Serial.println(WiFi.macAddress()); } void loop(){ }
31e539d3008f96cca3f8ae3347d386f96c4bacf8
42678eabf8362d6773b0e7ea2b2c7b1d3fa8a473
/queue/queue.cpp
c088d7b8ed4f98ba441960c0f2b37aaa51fc4a72
[]
no_license
dynamite-bud/CCPract
5d5406b842b11feea41f9df57bff38473d1e69a8
587203a4dbcd1f2b693f5220b7892ae772807715
refs/heads/master
2020-12-26T21:25:51.614349
2020-02-02T13:44:28
2020-02-02T13:44:28
237,649,310
0
0
null
null
null
null
UTF-8
C++
false
false
288
cpp
queue.cpp
#include<bits/stdc++.h> using namespace std; class Node{ private: int value; public: Node(int); Node(); }; Node::Node(int val):value(val){} Node::Node():value(-1){} class Queue{ private: int size; public: Queue(); Queue(int); }; int main(){ return 0; }
6bc1bc33dfbb05330996b347dfa9ab9b4ac770e5
3ded09995a802d1435703a351efae767b55a81b2
/examples/adapt.cpp
f90c5170817bc6d402ebd34974a37fd2fe4796cb
[ "Apache-2.0" ]
permissive
hobywan/trinity
83f13ad4be628fc3bcc8c6d84caf1753c3e8f43c
e8350057f9a0511ba910fe92b0e626d358952d27
refs/heads/master
2021-03-13T04:11:16.874125
2019-04-16T12:30:17
2019-04-16T12:30:17
31,732,163
6
1
null
null
null
null
UTF-8
C++
false
false
2,135
cpp
adapt.cpp
/* * 'examples/adapt.cpp' * This file is part of the "trinity" project. * (https://github.com/hobywan/trinity) * Copyright (c) 2016 Hoby Rakotoarivelo. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <trinity.h> int main(int argc, char* argv[]) { int const verbose = 1; int const bucket = 64; int const depth = 3; int const rounds = 8; int const max_col = 8; auto const norm = 2; auto const target = 1.0; auto const h_min = 1.E-9; auto const h_max = 0.4; auto const input = std::string(TRINITY_EXAMP_DIR) + "/mesh/GRID4.mesh"; auto const solut = std::string(TRINITY_EXAMP_DIR) + "/solut/shock4.bb"; auto const result = std::string(TRINITY_BUILD_DIR) + "/data/adapted.mesh"; assert(trinity::tools::exists(input)); assert(trinity::tools::exists(solut)); std::ifstream file(input, std::ios::in); assert(file.good()); int size[] = { trinity::io::find("Vertices", file), trinity::io::find("Triangles", file) }; file.close(); trinity::Mesh mesh (size, bucket, depth, verbose, rounds); trinity::Metrics metric (&mesh, target, norm, h_min, h_max); trinity::Partit heuris (&mesh, max_col); trinity::Refine refine (&mesh, depth); trinity::Swap swap (&mesh); trinity::Coarse coarse (&mesh, &heuris); trinity::Smooth smooth (&mesh, &heuris, depth); mesh.load(input, solut); metric.run(); for (int iter = 0; iter < rounds; ++iter) { refine.run(); coarse.run(); swap.run(); smooth.run(); } mesh.store(result); }
91fab23b5412a6c0e0867a01093ddd00b6da788f
e353fbd7dcd629184330f9ab0bed3030f3519e55
/src/HystFilter.h
54074ac41cce9d6e5711f435a3d005dea68478e4
[]
no_license
floridan95/arduino_eth_organ
fa0dfa7835876e2ea3adf072e7b0abc973fe05dc
2ec9d8d4cef3c158ff2c7c50814de3ec807d9aae
refs/heads/master
2023-01-31T00:30:39.563731
2020-12-15T18:12:18
2020-12-15T18:12:18
319,755,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,892
h
HystFilter.h
/* * Class: HystFilter [Hysteresis filter]. * Apply hysteresis to an input value and deliver a lower resolution, stabilised output value. * */ #pragma once #include <Arduino.h> class HystFilter { public: HystFilter(uint16_t inputValues, uint16_t outputValues, uint16_t margin); // constructor // inputValues: the total number of discrete values delivered by the input. // For example, a 10 bit ADC delivers 1024 values. // 8 bit ADC = 256, 9 bit ADC = 512, 10 bit ADC = 1024, 11 bit ADC = 2048, 12 bit ADC = 4096 etc. // outputValues: the number of discrete output values delivered. This governs the resolution of the function. // For example a 6 bit resolution yields 64 values. This should ideally be no higher that the input resolution // minus 3 bits. For example if the input resolution is 10 bits (1024), this should not exceed 7 bits (128) // margin: margin sets the 'stickyness' of the hysteresis or the reluctance to leave the current state. // It is measured in units of the the input level. As a general rule, this should be about 10% to 25% of the // range of input values that map to 1 output value. For example, if the inputValues is 1024 and the outputValues // is 128, then 8 input values map to 1 output value so the margin should be 2 (25% of 8 ). // Probably a value of 2 is OK. For low resolutions or noisy environments, it can be higher. Don't make it too high // or ranges overlap and some output values become unreachable. uint16_t getOutputLevel(uint16_t inputLevel); // converts an input level (eg in the range 0 to 1023 to an aoutput value of 1 to 127 with hyteresis. private: uint16_t _inputValues; uint16_t _outputValues; uint16_t _margin; uint16_t _currentOutputLevel; };
151543f002886d5c06e29f18b8bce597295c06e9
f1a2325795dcd90f940e45a3535ac3a0cb765616
/development/TL1Services/TL1Core/src/TL1_NotifDbchg.cpp
b9632520e5344e70bca759c2e949fd1c26363d69
[]
no_license
MoonStart/Frame
45c15d1e6febd7eb390b74b891bc5c40646db5de
e3a3574e5c243d9282778382509858514585ae03
refs/heads/master
2021-01-01T19:09:58.670794
2015-12-02T07:52:55
2015-12-02T07:52:55
31,520,344
0
0
null
null
null
null
UTF-8
C++
false
false
1,113
cpp
TL1_NotifDbchg.cpp
/*----------------------------------------------------------------------------- Copyright(c) Tellabs Transport Group Inc. All rights reserved. SUBSYSTEM: Software Services TARGET: AUTHOR: March 28, 2003- Jean-Francois Tremblay DESCRIPTION: Header file for TL1 Notification Base implementation -----------------------------------------------------------------------------*/ #ifdef WIN32 // Microsoft bug, identifier that exceeds 255 chars gets truncated #pragma warning(disable:4786) #endif #include <TL1Core/TL1_NotifDbchg.h> #include <TL1Core/TL1_NotifCenter.h> #include <TimeService/FC_Time.h> TL1_NotifDbchg::TL1_NotifDbchg( TL1_Notification::TL1_NotifType theType, const TL1_Response& theResponse ) : TL1_Notification( theType, theResponse), itsDbChgSeq( TL1_NotifCenter::Instance().GetNextDBSeq() ), itsTime() { FC_Time aTime; aTime.GetCurrentTime(); itsTime = aTime.GetCtTime(); itsHandle = -2; // This value is -2 for a reason. itsCtag = "NA"; } TL1_NotifDbchg::~TL1_NotifDbchg() { }
48196b703937c1238058b473f9a159b2326a86f7
f0b7bcc41298354b471a72a7eeafe349aa8655bf
/codebase/apps/physics/src/ThetaEAdvect/ThetaEAdvect.cc
22c2270f241088ca988e4cb70ad6d7a63674f63b
[ "BSD-3-Clause" ]
permissive
NCAR/lrose-core
23abeb4e4f1b287725dc659fb566a293aba70069
be0d059240ca442883ae2993b6aa112011755688
refs/heads/master
2023-09-01T04:01:36.030960
2023-08-25T00:41:16
2023-08-25T00:41:16
51,408,988
90
53
NOASSERTION
2023-08-18T21:59:40
2016-02-09T23:36:25
C++
UTF-8
C++
false
false
39,521
cc
ThetaEAdvect.cc
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* // ** Copyright UCAR (c) 1990 - 2016 // ** University Corporation for Atmospheric Research (UCAR) // ** National Center for Atmospheric Research (NCAR) // ** Boulder, Colorado, USA // ** BSD licence applies - redistribution and use in source and binary // ** forms, with or without modification, are permitted provided that // ** the following conditions are met: // ** 1) If the software is modified to produce derivative works, // ** such modified software should be clearly marked, so as not // ** to confuse it with the version available from UCAR. // ** 2) Redistributions of source code must retain the above copyright // ** notice, this list of conditions and the following disclaimer. // ** 3) 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. // ** 4) Neither the name of UCAR nor the names of its contributors, // ** if any, may be used to endorse or promote products derived from // ** this software without specific prior written permission. // ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS // ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED // ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ // RCS info // $Author: dixon $ // $Locker: $ // $Date: 2016/03/06 23:15:37 $ // $Id: ThetaEAdvect.cc,v 1.7 2016/03/06 23:15:37 dixon Exp $ // $Revision: 1.7 $ // $State: Exp $ // /**-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**/ /********************************************************************* * ThetaEAdvect: ThetaEAdvect program object. * * RAP, NCAR, Boulder CO * * March 2002 * * Nancy Rehak * *********************************************************************/ #include <assert.h> #include <iostream> #include <signal.h> #include <string> #include <toolsa/os_config.h> #include <dsdata/DsIntervalTrigger.hh> #include <dsdata/DsLdataTrigger.hh> #include <dsdata/DsTimeListTrigger.hh> #include <Mdv/DsMdvx.hh> #include <Mdv/MdvxPjg.hh> #include <physics/PhysicsLib.hh> #include <toolsa/DateTime.hh> #include <toolsa/pmu.h> #include <toolsa/procmap.h> #include <toolsa/str.h> #include <toolsa/umisc.h> #include "ThetaEAdvect.hh" #include "Params.hh" // Global variables ThetaEAdvect *ThetaEAdvect::_instance = (ThetaEAdvect *)NULL; const fl32 ThetaEAdvect::THETA_E_MISSING_DATA_VALUE = -999.0; /********************************************************************* * Constructor */ ThetaEAdvect::ThetaEAdvect(int argc, char **argv) : _dataTrigger(0) { static const string method_name = "ThetaEAdvect::ThetaEAdvect()"; // Make sure the singleton wasn't already created. assert(_instance == (ThetaEAdvect *)NULL); // Initialize the okay flag. okay = true; // Set the singleton instance pointer _instance = this; // Set the program name. path_parts_t progname_parts; uparse_path(argv[0], &progname_parts); _progName = STRdup(progname_parts.base); // Display ucopyright message. ucopyright(_progName); // Get the command line arguments. _args = new Args(argc, argv, _progName); // Get TDRP parameters. _params = new Params(); char *params_path = (char *) "unknown"; if (_params->loadFromArgs(argc, argv, _args->override.list, &params_path)) { cerr << "ERROR: " << method_name << endl; cerr << "Problem with TDRP parameters in file: " << params_path << endl; okay = false; return; } } /********************************************************************* * Destructor */ ThetaEAdvect::~ThetaEAdvect() { // Unregister process PMU_auto_unregister(); // Free contained objects delete _params; delete _args; delete _dataTrigger; // Free included strings STRfree(_progName); } /********************************************************************* * Inst() - Retrieve the singleton instance of this class. */ ThetaEAdvect *ThetaEAdvect::Inst(int argc, char **argv) { if (_instance == (ThetaEAdvect *)NULL) new ThetaEAdvect(argc, argv); return(_instance); } ThetaEAdvect *ThetaEAdvect::Inst() { assert(_instance != (ThetaEAdvect *)NULL); return(_instance); } /********************************************************************* * init() - Initialize the local data. * * Returns true if the initialization was successful, false otherwise. */ bool ThetaEAdvect::init() { static const string method_name = "ThetaEAdvect::init()"; // Initialize the data trigger switch (_params->trigger_mode) { case Params::LATEST_DATA : { if (_params->debug) cerr << "Initializing LATEST_DATA trigger using url: " << _params->latest_data_trigger << endl; DsLdataTrigger *trigger = new DsLdataTrigger(); if (trigger->init(_params->latest_data_trigger, -1, PMU_auto_register) != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error initializing LATEST_DATA trigger using url: " << _params->latest_data_trigger << endl; return false; } _dataTrigger = trigger; break; } case Params::TIME_LIST : { time_t start_time = DateTime::parseDateTime(_params->time_list_trigger.start_time); time_t end_time = DateTime::parseDateTime(_params->time_list_trigger.end_time); if (start_time == DateTime::NEVER) { cerr << "ERROR: " << method_name << endl; cerr << "Error parsing start_time string for TIME_LIST trigger: " << _params->time_list_trigger.start_time << endl; return false; } if (end_time == DateTime::NEVER) { cerr << "ERROR: " << method_name << endl; cerr << "Error parsing end_time string for TIME_LIST trigger: " << _params->time_list_trigger.end_time << endl; return false; } DsTimeListTrigger *trigger = new DsTimeListTrigger(); if (trigger->init(_params->time_list_trigger.url, start_time, end_time) != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error initializing TIME_LIST trigger for url: " << _params->time_list_trigger.url << endl; cerr << " Start time: " << _params->time_list_trigger.start_time << endl; cerr << " End time: " << _params->time_list_trigger.end_time << endl; return false; } _dataTrigger = trigger; break; } case Params::INTERVAL : { time_t start_time = DateTime::parseDateTime(_params->interval_trigger.start_time); time_t end_time = DateTime::parseDateTime(_params->interval_trigger.end_time); if (start_time == DateTime::NEVER) { cerr << "ERROR: " << method_name << endl; cerr << "Error parsing start_time string for INTERVAL trigger: " << _params->interval_trigger.start_time << endl; return false; } if (end_time == DateTime::NEVER) { cerr << "ERROR: " << method_name << endl; cerr << "Error parsing end_time string for INTERVAL trigger: " << _params->interval_trigger.end_time << endl; return false; } DsIntervalTrigger *trigger = new DsIntervalTrigger(); if (trigger->init(_params->interval_trigger.interval, start_time, end_time) != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error initializing INTERVAL trigger" << endl; cerr << " Start time: " << _params->interval_trigger.start_time << endl; cerr << " End time: " << _params->interval_trigger.end_time << endl; cerr << " Interval: " << _params->interval_trigger.interval << " secs" << endl; return false; } _dataTrigger = trigger; break; } } /* endswitch - _params->trigger_mode */ // initialize process registration PMU_auto_init(_progName, _params->instance, PROCMAP_REGISTER_INTERVAL); return true; } /********************************************************************* * run() - run the program. */ void ThetaEAdvect::run() { static const string method_name = "ThetaEAdvect::run()"; while (!_dataTrigger->endOfData()) { TriggerInfo triggerInfo; if (_dataTrigger->next(triggerInfo) != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error getting next trigger time" << endl; continue; } if (!_processData(triggerInfo.getIssueTime(), triggerInfo.getForecastTime() - triggerInfo.getIssueTime())) { cerr << "ERROR: " << method_name << endl; cerr << "Error processing data for time: " << triggerInfo.getIssueTime() << endl; continue; } } /* endwhile - !_dataTrigger->endOfData() */ } /********************************************************************** * Private Member Functions * **********************************************************************/ /********************************************************************* * _calc3DThetaEField() - Calculate the 3D theta-e field. * * Returns a pointer to the created field, or 0 if the field could * not be created for some reason. */ MdvxField *ThetaEAdvect::_calc3DThetaEField(const MdvxField &mixing_ratio_field, const MdvxField &temperature_field, const MdvxField &pressure_field) const { static const string method_name = "ThetaEAdvect::_calc3DThetaEField()"; MdvxField *theta_e_field; // Create the blank 3D theta-e field if ((theta_e_field = _create3DThetaEField(mixing_ratio_field)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error creating 3D theta-e field" << endl; return 0; } // Calculate the theta-e field Mdvx::field_header_t mixing_ratio_field_hdr = mixing_ratio_field.getFieldHeader(); Mdvx::field_header_t temperature_field_hdr = temperature_field.getFieldHeader(); Mdvx::field_header_t pressure_field_hdr = pressure_field.getFieldHeader(); if (!PhysicsLib::calcThetaE3D((fl32 *)mixing_ratio_field.getVol(), mixing_ratio_field_hdr.missing_data_value, mixing_ratio_field_hdr.bad_data_value, (fl32 *)temperature_field.getVol(), temperature_field_hdr.missing_data_value, temperature_field_hdr.bad_data_value, (fl32 *)pressure_field.getVol(), pressure_field_hdr.missing_data_value, pressure_field_hdr.bad_data_value, (fl32 *)theta_e_field->getVol(), THETA_E_MISSING_DATA_VALUE, pressure_field_hdr.nx, pressure_field_hdr.ny, pressure_field_hdr.nz)) { cerr << "ERROR: " << method_name << endl; cerr << "Error calculating 3D theta-e field" << endl; delete theta_e_field; return 0; } return theta_e_field; } /********************************************************************* * _calcThetaEAdvectField() - Calculate the theta-e advection field. * * Returns a pointer to the created field, or 0 if the field could * not be created for some reason. */ MdvxField *ThetaEAdvect::_calcThetaEAdvectField(const MdvxField &u_field, const MdvxField &v_field, const MdvxField &theta_e_field) const { static const string method_name = "ThetaEAdvect::_calcThetaEAdvectField()"; MdvxField *theta_e_adv_field; // Create the blank theta-e advection field if ((theta_e_adv_field = _createThetaEAdvectField(theta_e_field)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error creating theta-e advection field" << endl; return 0; } // Calculate the theta-e advection field Mdvx::field_header_t u_field_hdr = u_field.getFieldHeader(); Mdvx::field_header_t v_field_hdr = v_field.getFieldHeader(); Mdvx::field_header_t theta_e_field_hdr = theta_e_field.getFieldHeader(); Mdvx::field_header_t theta_e_adv_field_hdr = theta_e_adv_field->getFieldHeader(); // Mdvx::vlevel_header_t theta_e_vlevel_hdr = // theta_e_field.getVlevelHeader(); MdvxPjg u_proj(u_field_hdr); MdvxPjg v_proj(v_field_hdr); MdvxPjg theta_e_proj(theta_e_field_hdr); MdvxPjg theta_e_adv_proj(theta_e_adv_field_hdr); fl32 *u_data = (fl32 *)u_field.getVol(); fl32 *v_data = (fl32 *)v_field.getVol(); fl32 *theta_e_data = (fl32 *)theta_e_field.getVol(); fl32 *theta_e_adv_data = (fl32 *)theta_e_adv_field->getVol(); for (int x = 0; x < u_proj.getNx(); ++x) { for (int y = 0; y < u_proj.getNy(); ++y) { for (int z = 0; z < u_proj.getNz(); ++z) { // Calculate all of the indices used in the calculation to try to // make the calculations easier to read. The U and V indices are // guaranteed to be within the grid because the projections are // previously checked to be matching. For the theta e indices // (named using "eth"), we have to check to see if the point is // within the grid because we are looking at neighboring points. int u_index = u_proj.xyIndex2arrayIndex(x, y, z); int v_index = v_proj.xyIndex2arrayIndex(x, y, z); int eth_yplus_index = theta_e_proj.xyIndex2arrayIndex(x, y+1, z); if (eth_yplus_index < 0) eth_yplus_index = theta_e_proj.xyIndex2arrayIndex(x, y, z); int eth_yminus_index = theta_e_proj.xyIndex2arrayIndex(x, y-1, z); if (eth_yminus_index < 0) eth_yminus_index = theta_e_proj.xyIndex2arrayIndex(x, y, z); int eth_xplus_index = theta_e_proj.xyIndex2arrayIndex(x+1, y, z); if (eth_xplus_index < 0) eth_xplus_index = theta_e_proj.xyIndex2arrayIndex(x, y, z); int eth_xminus_index = theta_e_proj.xyIndex2arrayIndex(x-1, y, z); if (eth_xminus_index < 0) eth_xminus_index = theta_e_proj.xyIndex2arrayIndex(x, y, z); int eth_adv_index = theta_e_adv_proj.xyIndex2arrayIndex(x, y, z); // Make sure none of the data is missing. We only have to check // for the bad_data_value for the theta_e data because we know that // we set both the bad_data_value and the missing_data_value to the // same value for this data previously. if (u_data[u_index] == u_field_hdr.missing_data_value || u_data[u_index] == u_field_hdr.bad_data_value || v_data[v_index] == v_field_hdr.missing_data_value || v_data[v_index] == v_field_hdr.bad_data_value || theta_e_data[eth_yplus_index] == theta_e_field_hdr.bad_data_value || theta_e_data[eth_yminus_index] == theta_e_field_hdr.bad_data_value || theta_e_data[eth_xplus_index] == theta_e_field_hdr.bad_data_value || theta_e_data[eth_xminus_index] == theta_e_field_hdr.bad_data_value) { theta_e_adv_data[eth_adv_index] = theta_e_adv_field_hdr.bad_data_value; continue; } // Calculate the advection in each direction double v_advection = v_data[v_index] * (theta_e_data[eth_yplus_index] - theta_e_data[eth_yminus_index]) / (2.0 * theta_e_proj.yGrid2km(1.0) * 1000.0); // cerr << "meters per grid space: " << // (theta_e_proj.xGrid2km(1.0, y) * 1000.0) << endl; double u_advection = u_data[u_index] * (theta_e_data[eth_xplus_index] - theta_e_data[eth_xminus_index]) / (2.0 * theta_e_proj.xGrid2km(1.0, y) * 1000.0); // Calculate theta e advection theta_e_adv_data[eth_adv_index] = -(v_advection + u_advection); } /* endfor - z */ } /* endfor - y */ } /* endfor - x */ return theta_e_adv_field; } /********************************************************************* * _calcVertDeriveField() - Calculate the vertical derivative field. * * Returns a pointer to the created field, or 0 if the field could * not be created for some reason. */ MdvxField *ThetaEAdvect::_calcVertDeriveField(const MdvxField &theta_e_adv_field) const { static const string method_name = "ThetaEAdvect::_calcVertDeriveField()"; MdvxField *vert_der_field; // Create the blank vertical derivative field if ((vert_der_field = _createVertDeriveField(theta_e_adv_field)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error creating vertical derivative field" << endl; return 0; } // Calculate the vertical derivative field Mdvx::field_header_t theta_e_adv_field_hdr = theta_e_adv_field.getFieldHeader(); Mdvx::field_header_t vert_der_field_hdr = vert_der_field->getFieldHeader(); Mdvx::vlevel_header_t theta_e_vlevel_hdr = theta_e_adv_field.getVlevelHeader(); MdvxPjg theta_e_adv_proj(theta_e_adv_field_hdr); MdvxPjg vert_der_proj(vert_der_field_hdr); fl32 *theta_e_adv_data = (fl32 *)theta_e_adv_field.getVol(); fl32 *vert_der_data = (fl32 *)vert_der_field->getVol(); for (int x = 0; x < theta_e_adv_proj.getNx(); ++x) { for (int y = 0; y < theta_e_adv_proj.getNy(); ++y) { // Calculate all of the indices used in the calculation to try to // make the calculations easier to read. The U and V indices are // guaranteed to be within the grid because the projections are // previously checked to be matching. For the theta e indices // (named using "eth"), we have to check to see if the point is // within the grid because we are looking at neighboring points. int upper_eth_index = theta_e_adv_proj.xyIndex2arrayIndex(x, y, theta_e_adv_proj.getNz()-1); int lower_eth_index = theta_e_adv_proj.xyIndex2arrayIndex(x, y, 0); int vert_der_index = vert_der_proj.xyIndex2arrayIndex(x, y, 0); // Make sure none of the data is missing. We only have to check // for the bad_data_value for the theta_e data because we know that // we set both the bad_data_value and the missing_data_value to the // same value for this data previously. if (theta_e_adv_data[upper_eth_index] == theta_e_adv_field_hdr.bad_data_value || theta_e_adv_data[lower_eth_index] == theta_e_adv_field_hdr.bad_data_value) { vert_der_data[vert_der_index] = vert_der_field_hdr.bad_data_value; continue; } // Calculate the upper and lower Z levels used in the calculation double upper_z = theta_e_vlevel_hdr.level[theta_e_adv_proj.getNz()-1]; double lower_z = theta_e_vlevel_hdr.level[0]; // Calculate vertical derivative vert_der_data[vert_der_index] = (theta_e_adv_data[upper_eth_index] - theta_e_adv_data[lower_eth_index]) / (upper_z - lower_z); } /* endfor - y */ } /* endfor - x */ return vert_der_field; } /********************************************************************* * _create3DThetaEField() - Create the blank 3D theta-e field. Upon * return, the field values will be set to the * missing data value. * * Returns a pointer to the created field, or 0 if the field could * not be created for some reason. */ MdvxField *ThetaEAdvect::_create3DThetaEField(const MdvxField &base_field) const { // Create the new field header Mdvx::field_header_t base_field_hdr = base_field.getFieldHeader(); Mdvx::field_header_t field_hdr; memset(&field_hdr, 0, sizeof(field_hdr)); field_hdr.field_code = 0; field_hdr.forecast_delta = base_field_hdr.forecast_delta; field_hdr.forecast_time = base_field_hdr.forecast_time; field_hdr.nx = base_field_hdr.nx; field_hdr.ny = base_field_hdr.ny; field_hdr.nz = base_field_hdr.nz; field_hdr.proj_type = base_field_hdr.proj_type; field_hdr.encoding_type = Mdvx::ENCODING_FLOAT32; field_hdr.data_element_nbytes = 4; field_hdr.volume_size = field_hdr.nx * field_hdr.ny * field_hdr.nz * field_hdr.data_element_nbytes; field_hdr.compression_type = Mdvx::COMPRESSION_NONE; field_hdr.transform_type = Mdvx::DATA_TRANSFORM_NONE; field_hdr.scaling_type = Mdvx::SCALING_NONE; field_hdr.native_vlevel_type = base_field_hdr.native_vlevel_type; field_hdr.vlevel_type = base_field_hdr.vlevel_type; field_hdr.dz_constant = base_field_hdr.dz_constant; field_hdr.proj_origin_lat = base_field_hdr.proj_origin_lat; field_hdr.proj_origin_lon = base_field_hdr.proj_origin_lon; for (int i = 0; i < MDV_MAX_PROJ_PARAMS; ++i) field_hdr.proj_param[i] = base_field_hdr.proj_param[i]; field_hdr.vert_reference = 0; field_hdr.grid_dx = base_field_hdr.grid_dx; field_hdr.grid_dy = base_field_hdr.grid_dy; field_hdr.grid_dz = base_field_hdr.grid_dz; field_hdr.grid_minx = base_field_hdr.grid_minx; field_hdr.grid_miny = base_field_hdr.grid_miny; field_hdr.grid_minz = base_field_hdr.grid_minz; field_hdr.scale = 1.0; field_hdr.bias = 0.0; field_hdr.bad_data_value = THETA_E_MISSING_DATA_VALUE; field_hdr.missing_data_value = THETA_E_MISSING_DATA_VALUE; field_hdr.proj_rotation = base_field_hdr.proj_rotation; STRcopy(field_hdr.field_name_long, "theta-e", MDV_LONG_FIELD_LEN); STRcopy(field_hdr.field_name, "theta-e", MDV_SHORT_FIELD_LEN); STRcopy(field_hdr.units, "K", MDV_UNITS_LEN); field_hdr.transform[0] = '\0'; // Create the blank field return new MdvxField(field_hdr, base_field.getVlevelHeader(), (void *)0, true); } /********************************************************************* * _createThetaEAdvectField() - Create the blank theta-e advection field. * Upon return, the field values will be * set to the missing data value. * * Returns a pointer to the created field, or 0 if the field could * not be created for some reason. */ MdvxField *ThetaEAdvect::_createThetaEAdvectField(const MdvxField &base_field) const { // Create the new field header Mdvx::field_header_t base_field_hdr = base_field.getFieldHeader(); Mdvx::field_header_t field_hdr; memset(&field_hdr, 0, sizeof(field_hdr)); field_hdr.field_code = 0; field_hdr.forecast_delta = base_field_hdr.forecast_delta; field_hdr.forecast_time = base_field_hdr.forecast_time; field_hdr.nx = base_field_hdr.nx; field_hdr.ny = base_field_hdr.ny; field_hdr.nz = base_field_hdr.nz; field_hdr.proj_type = base_field_hdr.proj_type; field_hdr.encoding_type = Mdvx::ENCODING_FLOAT32; field_hdr.data_element_nbytes = 4; field_hdr.volume_size = field_hdr.nx * field_hdr.ny * field_hdr.nz * field_hdr.data_element_nbytes; field_hdr.compression_type = Mdvx::COMPRESSION_NONE; field_hdr.transform_type = Mdvx::DATA_TRANSFORM_NONE; field_hdr.scaling_type = Mdvx::SCALING_NONE; field_hdr.native_vlevel_type = base_field_hdr.native_vlevel_type; field_hdr.vlevel_type = base_field_hdr.vlevel_type; field_hdr.dz_constant = base_field_hdr.dz_constant; field_hdr.proj_origin_lat = base_field_hdr.proj_origin_lat; field_hdr.proj_origin_lon = base_field_hdr.proj_origin_lon; for (int i = 0; i < MDV_MAX_PROJ_PARAMS; ++i) field_hdr.proj_param[i] = base_field_hdr.proj_param[i]; field_hdr.vert_reference = 0; field_hdr.grid_dx = base_field_hdr.grid_dx; field_hdr.grid_dy = base_field_hdr.grid_dy; field_hdr.grid_dz = base_field_hdr.grid_dz; field_hdr.grid_minx = base_field_hdr.grid_minx; field_hdr.grid_miny = base_field_hdr.grid_miny; field_hdr.grid_minz = base_field_hdr.grid_minz; field_hdr.scale = 1.0; field_hdr.bias = 0.0; field_hdr.bad_data_value = THETA_E_MISSING_DATA_VALUE; field_hdr.missing_data_value = THETA_E_MISSING_DATA_VALUE; field_hdr.proj_rotation = base_field_hdr.proj_rotation; STRcopy(field_hdr.field_name_long, "theta-e advection", MDV_LONG_FIELD_LEN); STRcopy(field_hdr.field_name, "theta-e adv", MDV_SHORT_FIELD_LEN); STRcopy(field_hdr.units, "K/s", MDV_UNITS_LEN); field_hdr.transform[0] = '\0'; // Create the blank field return new MdvxField(field_hdr, base_field.getVlevelHeader(), (void *)0, true); } /********************************************************************* * _createVertDeriveField() - Create the blank vertical derivative field. * Upon return, the field values will be * set to the missing data value. * * Returns a pointer to the created field, or 0 if the field could * not be created for some reason. */ MdvxField *ThetaEAdvect::_createVertDeriveField(const MdvxField &base_field) const { // Create the new field header Mdvx::field_header_t base_field_hdr = base_field.getFieldHeader(); Mdvx::field_header_t field_hdr; memset(&field_hdr, 0, sizeof(field_hdr)); field_hdr.field_code = 0; field_hdr.forecast_delta = base_field_hdr.forecast_delta; field_hdr.forecast_time = base_field_hdr.forecast_time; field_hdr.nx = base_field_hdr.nx; field_hdr.ny = base_field_hdr.ny; field_hdr.nz = 1; field_hdr.proj_type = base_field_hdr.proj_type; field_hdr.encoding_type = Mdvx::ENCODING_FLOAT32; field_hdr.data_element_nbytes = 4; field_hdr.volume_size = field_hdr.nx * field_hdr.ny * field_hdr.nz * field_hdr.data_element_nbytes; field_hdr.compression_type = Mdvx::COMPRESSION_NONE; field_hdr.transform_type = Mdvx::DATA_TRANSFORM_NONE; field_hdr.scaling_type = Mdvx::SCALING_NONE; field_hdr.native_vlevel_type = base_field_hdr.native_vlevel_type; field_hdr.vlevel_type = Mdvx::VERT_TYPE_SURFACE; field_hdr.dz_constant = base_field_hdr.dz_constant; field_hdr.proj_origin_lat = base_field_hdr.proj_origin_lat; field_hdr.proj_origin_lon = base_field_hdr.proj_origin_lon; for (int i = 0; i < MDV_MAX_PROJ_PARAMS; ++i) field_hdr.proj_param[i] = base_field_hdr.proj_param[i]; field_hdr.vert_reference = 0; field_hdr.grid_dx = base_field_hdr.grid_dx; field_hdr.grid_dy = base_field_hdr.grid_dy; field_hdr.grid_dz = 1.0; field_hdr.grid_minx = base_field_hdr.grid_minx; field_hdr.grid_miny = base_field_hdr.grid_miny; field_hdr.grid_minz = 0.5; field_hdr.scale = 1.0; field_hdr.bias = 0.0; field_hdr.bad_data_value = THETA_E_MISSING_DATA_VALUE; field_hdr.missing_data_value = THETA_E_MISSING_DATA_VALUE; field_hdr.proj_rotation = base_field_hdr.proj_rotation; STRcopy(field_hdr.field_name_long, "theta-e advection vert der", MDV_LONG_FIELD_LEN); STRcopy(field_hdr.field_name, "theta-e adv vert der", MDV_SHORT_FIELD_LEN); STRcopy(field_hdr.units, "K/s/mb", MDV_UNITS_LEN); field_hdr.transform[0] = '\0'; // Create the vlevel header Mdvx::vlevel_header_t vlevel_hdr; memset(&vlevel_hdr, 0, sizeof(vlevel_hdr)); vlevel_hdr.type[0] = Mdvx::VERT_TYPE_SURFACE; vlevel_hdr.level[0] = 0.5; // Create the blank field return new MdvxField(field_hdr, vlevel_hdr, (void *)0, true); } /********************************************************************* * _processData() - Process data for the given trigger time. * * Returns true on success, false on failure. */ bool ThetaEAdvect::_processData(const time_t trigger_time, const int lead_time) { static const string method_name = "ThetaEAdvect::_processData()"; if (_params->debug) cerr << "*** Processing data for trigger time: " << DateTime::str(trigger_time) << endl; // Read in the input fields Mdvx::master_header_t mixing_ratio_master_hdr; MdvxField *mixing_ratio_field; if ((mixing_ratio_field = _readFieldData(_params->mixing_ratio_field_info.url, _params->mixing_ratio_field_info.field_name, _params->mixing_ratio_field_info.field_num, _params->pressure_limits.lower_level, _params->pressure_limits.upper_level, trigger_time, lead_time, _params->max_input_valid_secs, &mixing_ratio_master_hdr)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error reading in mixing ratio field from url: " << _params->mixing_ratio_field_info.url << endl; return false; } MdvxField *temperature_field; if ((temperature_field = _readFieldData(_params->temp_field_info.url, _params->temp_field_info.field_name, _params->temp_field_info.field_num, _params->pressure_limits.lower_level, _params->pressure_limits.upper_level, trigger_time, lead_time, _params->max_input_valid_secs)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error reading in temperature field from url: " << _params->temp_field_info.url << endl; delete mixing_ratio_field; return false; } MdvxField *pressure_field; if ((pressure_field = _readFieldData(_params->pressure_field_info.url, _params->pressure_field_info.field_name, _params->pressure_field_info.field_num, _params->pressure_limits.lower_level, _params->pressure_limits.upper_level, trigger_time, lead_time, _params->max_input_valid_secs)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error reading in pressure field from url: " << _params->pressure_field_info.url << endl; delete mixing_ratio_field; delete temperature_field; return false; } MdvxField *u_field; if ((u_field = _readFieldData(_params->u_field_info.url, _params->u_field_info.field_name, _params->u_field_info.field_num, _params->pressure_limits.lower_level, _params->pressure_limits.upper_level, trigger_time, lead_time, _params->max_input_valid_secs)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error reading in U field from url: " << _params->u_field_info.url << endl; delete mixing_ratio_field; delete temperature_field; delete pressure_field; return false; } MdvxField *v_field; if ((v_field = _readFieldData(_params->v_field_info.url, _params->v_field_info.field_name, _params->v_field_info.field_num, _params->pressure_limits.lower_level, _params->pressure_limits.upper_level, trigger_time, lead_time, _params->max_input_valid_secs)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error reading in V field from url: " << _params->v_field_info.url << endl; delete mixing_ratio_field; delete temperature_field; delete pressure_field; delete u_field; return false; } // Make sure that the input fields all have the same projections Mdvx::field_header_t mixing_ratio_field_hdr = mixing_ratio_field->getFieldHeader(); Mdvx::field_header_t temperature_field_hdr = temperature_field->getFieldHeader(); Mdvx::field_header_t pressure_field_hdr = pressure_field->getFieldHeader(); Mdvx::field_header_t u_field_hdr = u_field->getFieldHeader(); Mdvx::field_header_t v_field_hdr = v_field->getFieldHeader(); MdvxPjg mixing_ratio_proj(mixing_ratio_field_hdr); MdvxPjg temperature_proj(temperature_field_hdr); MdvxPjg pressure_proj(pressure_field_hdr); MdvxPjg u_proj(u_field_hdr); MdvxPjg v_proj(v_field_hdr); if (mixing_ratio_proj != temperature_proj || mixing_ratio_proj != pressure_proj || mixing_ratio_proj != u_proj || mixing_ratio_proj != v_proj) { cerr << "ERROR: " << method_name << endl; cerr << "Projections of input fields don't match" << endl; cerr << "Cannot calculate 3D theta-e field" << endl; delete mixing_ratio_field; delete temperature_field; delete pressure_field; delete u_field; delete v_field; return false; } // Calculate the 3D theta-e field MdvxField *theta_e_field; if ((theta_e_field = _calc3DThetaEField(*mixing_ratio_field, *temperature_field, *pressure_field)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error calculating 3D theta-e field" << endl; delete mixing_ratio_field; delete temperature_field; delete pressure_field; delete u_field; delete v_field; return false; } // Get rid of the fields we don't need anymore delete mixing_ratio_field; delete temperature_field; delete pressure_field; // Now calculate the theta-e advection field MdvxField *theta_e_adv_field; if ((theta_e_adv_field = _calcThetaEAdvectField(*u_field, *v_field, *theta_e_field)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error calculating theta-e advection field" << endl; delete u_field; delete v_field; delete theta_e_field; return false; } delete u_field; delete v_field; // Finally, calculate the vertical derivative of the theta-e // advection field MdvxField *vert_der_field; if ((vert_der_field = _calcVertDeriveField(*theta_e_adv_field)) == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error calculating vertical derivative field" << endl; delete theta_e_field; delete theta_e_adv_field; return false; } // Create and write the output file DsMdvx output_file; _updateOutputMasterHeader(output_file, mixing_ratio_master_hdr); theta_e_field->convertType(Mdvx::ENCODING_INT8, Mdvx::COMPRESSION_BZIP, Mdvx::SCALING_DYNAMIC); output_file.addField(theta_e_field); theta_e_adv_field->convertType(Mdvx::ENCODING_INT8, Mdvx::COMPRESSION_BZIP, Mdvx::SCALING_DYNAMIC); output_file.addField(theta_e_adv_field); vert_der_field->convertType(Mdvx::ENCODING_INT8, Mdvx::COMPRESSION_BZIP, Mdvx::SCALING_DYNAMIC); output_file.addField(vert_der_field); if (_params->write_as_forecast) output_file.setWriteAsForecast(); output_file.setWriteLdataInfo(); if (output_file.writeToDir(_params->output_url) != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error writing output file to URL: " << _params->output_url << endl; cerr << output_file.getErrStr() << endl; return false; } return true; } /********************************************************************* * _readFieldData() - Read the indicated field data. */ MdvxField *ThetaEAdvect::_readFieldData(const string &url, const string &field_name, const int field_num, const double lower_level, const double upper_level, const time_t data_time, const int lead_time, const int max_input_valid_secs, Mdvx::master_header_t *master_hdr) { static const string method_name = "ThetaEAdvect::_readFieldData()"; // Set up the read request DsMdvx input_file; if(_params->is_forecast_data) input_file.setReadTime(Mdvx::READ_SPECIFIED_FORECAST, url, max_input_valid_secs, data_time, lead_time); else input_file.setReadTime(Mdvx::READ_CLOSEST, url, max_input_valid_secs, data_time); if (field_name.length() > 0) input_file.addReadField(field_name); else input_file.addReadField(field_num); input_file.setReadNoChunks(); // I think we really want to use all of the input data in the // calculations, but just do the calculations between these // levels. Didn't want to actually delete this until I knew // for sure. input_file.setReadVlevelLimits(lower_level, upper_level); input_file.setReadEncodingType(Mdvx::ENCODING_FLOAT32); input_file.setReadCompressionType(Mdvx::COMPRESSION_NONE); input_file.setReadScalingType(Mdvx::SCALING_NONE); // Now read the volume if (input_file.readVolume() != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error reading volume:" << endl; cerr << " url: " << url << endl; cerr << " field: \"" << field_name << "\" (" << field_num << ")" << endl; return 0; } // Make sure the data in the volume is ordered in the way we expect. Mdvx::master_header_t local_master_hdr = input_file.getMasterHeader(); if (local_master_hdr.grid_orientation != Mdvx::ORIENT_SN_WE) { cerr << "ERROR: " << method_name << endl; cerr << "Input grid has incorrect orientation" << endl; cerr << "Expecting " << Mdvx::orientType2Str(Mdvx::ORIENT_SN_WE) << " orientation, got " << Mdvx::orientType2Str(local_master_hdr.grid_orientation) << " orientation" << endl; cerr << "Url: " << url << endl; return 0; } if (local_master_hdr.data_ordering != Mdvx::ORDER_XYZ) { cerr << "ERROR: " << method_name << endl; cerr << "Input grid has incorrect data ordering" << endl; cerr << "Expectin " << Mdvx::orderType2Str(Mdvx::ORDER_XYZ) << " ordering, got " << Mdvx::orderType2Str(local_master_hdr.data_ordering) << " ordering" << endl; cerr << "Url: " << url << endl; return 0; } // Pull out the appropriate field and make a copy to be returned. // We must make a copy here because getField() returns a pointer // into the DsMdvx object and the object is automatically deleted // when we exit this method. MdvxField *field = input_file.getField(0); if (field == 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error retrieving field from volume:" << endl; cerr << " url: " << url << endl; cerr << " field: \"" << field_name << "\" (" << field_num << ")" << endl; return 0; } // Return the master header, if requested if (master_hdr != 0) *master_hdr = local_master_hdr; return new MdvxField(*field); } /********************************************************************* * _updateOutputMasterHeader() - Update the master header values for * the output file. */ void ThetaEAdvect::_updateOutputMasterHeader(DsMdvx &output_file, const Mdvx::master_header_t &input_master_hdr) { Mdvx::master_header_t master_hdr; memset(&master_hdr, 0, sizeof(master_hdr)); if(_params->write_as_forecast) { master_hdr.time_gen = input_master_hdr.time_gen; } else { master_hdr.time_gen = time(0); } master_hdr.time_begin = input_master_hdr.time_begin; master_hdr.time_end = input_master_hdr.time_end; master_hdr.time_centroid = input_master_hdr.time_centroid; master_hdr.time_expire = input_master_hdr.time_expire; master_hdr.data_dimension = input_master_hdr.data_dimension; master_hdr.data_collection_type = Mdvx::DATA_EXTRAPOLATED; master_hdr.native_vlevel_type = input_master_hdr.native_vlevel_type; master_hdr.vlevel_type = Mdvx::VERT_TYPE_SURFACE; master_hdr.vlevel_included = 1; master_hdr.grid_orientation = input_master_hdr.grid_orientation; master_hdr.data_ordering = input_master_hdr.data_ordering; master_hdr.sensor_lon = input_master_hdr.sensor_lon; master_hdr.sensor_lat = input_master_hdr.sensor_lat; master_hdr.sensor_alt = input_master_hdr.sensor_alt; STRcopy(master_hdr.data_set_info, "ThetaEAdvect output", MDV_INFO_LEN); STRcopy(master_hdr.data_set_name, "ThetaEAdvect", MDV_NAME_LEN); STRcopy(master_hdr.data_set_source, "ThetaEAdvect", MDV_NAME_LEN); output_file.setMasterHeader(master_hdr); }
063c4e35ed67a7186d3f0410e497078e3441eee8
aeb49fe4cef963fcff288f35b5da82c000feba09
/NEG2.cpp
8b60dc5ee4763ade710d1b27865c9c92bc167745
[]
no_license
kanha95/SPOJ-solutions
b5febec31c08a8f0b229ca2578253da81ecfd687
6a6038236eab4e40773fafae142d01678f62d611
refs/heads/master
2020-09-07T07:29:06.760163
2016-03-04T09:16:08
2016-03-04T09:16:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
496
cpp
NEG2.cpp
#include<cstdio> #include<cstring> #include<iostream> using namespace std; int main() { long long t,n; //cin>>t; //while(t--) { string s=""; cin>>n; if(n==0) { printf("0\n"); } else { long long div=-2; while(n) { if(n%div<0) { //cout<<n%div<<" "<<n/div<<endl; s=char((n%div +2)+'0')+s; n=n/div +1; } else { //cout<<n%div<<" "<<n/div<<endl; s=char((n%div)+'0')+s; n=n/div; } } } cout<<s<<endl; } }
fb6208220f445e4052543c74a81fd69897c07632
3e8677f4e90ef823a9ec3ea9ce7a9ec33552156e
/src/oled.cpp
6d0729b3f0848315b2b98679771db2a93a2a26c7
[ "Unlicense" ]
permissive
applecargo/smp_v1p0
479dd06c430e6f5f6ecf56dbce6741824fbd9c42
fa3a2db71634218a93825143f27a5bd32289be33
refs/heads/master
2020-04-07T05:40:49.307565
2019-02-13T06:53:28
2019-02-13T06:53:28
158,105,351
0
0
null
null
null
null
UTF-8
C++
false
false
12,491
cpp
oled.cpp
#include "global.h" //oled #include <SPI.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #define OLED_RESET 4 #define OLED_DC 5 #define OLED_CS 6 Adafruit_SSD1306 * __display; // --> to use alternative pins for SPI + using H/W spi for comm. to display. // --> setup pins first and create obj. // --> then, we need to do actual construction in setup(). //fonts #include <Fonts/LiberationSans_Regular5pt7b.h> // (almost) same as 'Arial' #include <Fonts/LiberationSans_Regular6pt7b.h> // (almost) same as 'Arial' #include <Fonts/LiberationSans_Regular7pt7b.h> // (almost) same as 'Arial' #include <Fonts/LiberationSans_Regular9pt7b.h> // (almost) same as 'Arial' // //icon // --> https://learn.adafruit.com/adafruit-gfx-graphics-library/graphics-primitives#bitmaps-3-32 // --> http://javl.github.io/image2cpp/ // // 'add_mic_record_voice_icon_48', 48x48px // const uint8_t mic_icon[] PROGMEM = { // 0x00, 0x00, 0x07, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xfe, // 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, // 0xff, 0xff, 0x80, 0x00, 0x00, 0x01, 0xff, 0xff, 0x80, 0x00, 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, // 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x03, 0xff, 0xff, // 0xc0, 0x00, 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x03, // 0xff, 0xff, 0xc0, 0x00, 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, // 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x03, 0xff, 0xff, // 0xc0, 0x00, 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, 0x07, 0x83, 0xff, 0xff, 0xc1, 0xe0, 0x0f, 0xc3, // 0xff, 0xff, 0xc3, 0xf0, 0x0f, 0xc3, 0xff, 0xff, 0xc3, 0xf0, 0x0f, 0xc3, 0xff, 0xff, 0xc3, 0xf0, // 0x0f, 0xc3, 0xff, 0xff, 0xc3, 0xf0, 0x0f, 0xc1, 0xff, 0xff, 0x83, 0xf0, 0x0f, 0xc1, 0xff, 0xff, // 0x83, 0xf0, 0x0f, 0xc0, 0xff, 0xff, 0x07, 0xf0, 0x0f, 0xe0, 0xff, 0xff, 0x07, 0xe0, 0x07, 0xe0, // 0x7f, 0xfe, 0x07, 0xe0, 0x07, 0xf0, 0x1f, 0xf8, 0x0f, 0xe0, 0x07, 0xf0, 0x07, 0xe0, 0x0f, 0xc0, // 0x03, 0xf8, 0x00, 0x00, 0x1f, 0xc0, 0x03, 0xfc, 0x00, 0x00, 0x3f, 0xc0, 0x01, 0xfe, 0x00, 0x00, // 0x7f, 0x80, 0x01, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0xc0, 0x03, 0xff, 0x00, 0x00, 0x7f, // 0xf0, 0x0f, 0xfe, 0x00, 0x00, 0x3f, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x1f, 0xff, 0xff, 0xf8, 0x00, // 0x00, 0x0f, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x03, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0xff, 0xff, // 0x00, 0x00, 0x00, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x00, 0x00, // 0x0f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00 // }; void __oled_setup() { //oled SPI.setMOSI(7); SPI.setSCK(14); __display = new Adafruit_SSD1306(128, 64, &SPI, OLED_DC, OLED_RESET, OLED_CS, 40000000UL); //oled __display->begin(SSD1306_SWITCHCAPVCC); // by default, we'll generate the high voltage from the 3.3v line internally! (neat!) // --> https://cdn-shop.adafruit.com/datasheets/SSD1306.pdf --> page 62 --> 2 Charge Pump Regulator //clear oled screen __display->clearDisplay(); __display->display(); } //(private) //draw a marker for each fix. : sort of 'periodic blinking' effect. static void __oled_fixmarker() { static const unsigned long timeout = 500; // 'on' time : 0.5sec. static elapsedMillis msec = 0; if (__gotfix == true) { __gotfix = false; msec = 0; } if (msec < timeout) { __display->drawCircle(120, 4, 4, WHITE); __display->drawCircle(120, 4, 2, WHITE); //smallest font __display->setFont(); __display->setTextSize(1); __display->setTextColor(WHITE); __display->setCursor(108 + (3 - __cardinal.length()) * 6, 12); // if (__speed > 3) { // display cardinal when speed > 3 kmph __display->println(__cardinal); } } } static void __oled_date(int year, int month, int day) { //'year' __display->print(year); //'-' __display->print(" / "); //'month' if(month < 10) __display->print('0'); __display->print(month); //'-' __display->print(" / "); //'day' if(day < 10) __display->print('0'); __display->print(day); } static void __oled_time(int hour, int minute, int second) { //'hour' if(hour < 10) __display->print('0'); __display->print(hour); //'.' __display->print(" : "); //'minute' if(minute < 10) __display->print('0'); __display->print(minute); //'.' __display->print(" : "); //'second' if(second < 10) __display->print('0'); __display->print(second); } void __oled_devscreen() { //clear oled screen __display->clearDisplay(); // __oled_fixmarker(); // __display->setFont(); __display->setTextSize(1); __display->setTextColor(WHITE); __display->setCursor(0,0); //line #1 : loop time of loop() __display->print("loop : "); __display->print(__looptime/1000000.0, 6); __looptime = 0; __display->println(" sec."); //line #2 : date & time __oled_date(year(__local), month(__local), day(__local)); __display->print(" "); __oled_time(hour(__local), minute(__local), second(__local)); __display->println(); //line #3 : latitude __display->print(" "); __display->print(__latitude, 6); __display->println(__lat); //line #4 : longitude __display->print(" "); __display->print(__longitude, 6); __display->println(__lon); //line #5 : n. of satellites __display->print(" n of satellites: "); __display->println(__nsat); // //line #6 : sd flash write time // __display->print("sdwr > 1e5 : "); // __display->println(__sdwr_time); __display->print("speed: "); __display->println(__speed); __display->print("course: "); __display->print(__course); __display->print("("); __display->print(__cardinal); __display->println(")"); __display->print("fa(t,p): "); __display->print(fix_age_datetime); __display->print(", "); __display->println(fix_age_position); //splash! __display->display(); } void __oled_nmea_strings() { //oled __display->clearDisplay(); __display->setFont(); __display->setTextSize(1); __display->setTextColor(WHITE); __display->setCursor(0,0); //8 ---> 1 for (int idx = 0; idx < GPS_NMEA_BUFF_LEN; idx++) { //a scrolling effect? __display->println(__gps_lines[(idx + __gps_line_pointer) % GPS_NMEA_BUFF_LEN]); } //splash! __display->display(); } void __oled_userscreen_infomsg(String msg) { //clear oled screen __display->clearDisplay(); //header __display->drawFastHLine(0, 0, 128, WHITE); __display->drawFastHLine(0, 3, 128, WHITE); //line #1 : info. msg. (small font) __display->setFont(&LiberationSans_Regular5pt7b); __display->setTextSize(1); __display->setTextColor(WHITE); __display->setCursor(0,17); //info. msg. __display->println(msg); //footer __display->drawFastHLine(0, 60, 128, WHITE); __display->drawFastHLine(0, 63, 128, WHITE); //splash! __display->display(); } void __oled_userscreen() { //clear oled screen __display->clearDisplay(); //frame // __display->drawRect(0, 0, 128, 64, WHITE); // __oled_fixmarker(); //line #1 : date (small font) __display->setFont(&LiberationSans_Regular6pt7b); __display->setTextSize(1); __display->setTextColor(WHITE); // __display->setCursor(38,12); __display->setCursor(0,8); // __oled_date(year(__local), month(__local), day(__local)); __display->println(); //line #2 : time (big font) __display->setFont(&LiberationSans_Regular9pt7b); __display->setTextSize(1); __display->setTextColor(WHITE); // __display->setCursor(24,31); __display->setCursor(0,30); // // __display->print(" "); __oled_time(hour(__local), minute(__local), second(__local)); __display->println(); // //line #3 : device name/version __display->setFont(&LiberationSans_Regular5pt7b); __display->setTextSize(1); __display->setTextColor(WHITE); __display->setCursor(0,58); __display->print("SMP v1"); //line #3.1 : latitude __display->setFont(&LiberationSans_Regular5pt7b); __display->setTextSize(1); __display->setTextColor(WHITE); __display->setCursor(68,48); __display->printf("%08.4f %c\n", __latitude, __lat); //line #4.1 : longitude __display->setFont(&LiberationSans_Regular5pt7b); __display->setTextSize(1); __display->setTextColor(WHITE); __display->setCursor(68,58); __display->printf("%08.4f %c\n",__longitude, __lon); //splash! __display->display(); } void __oled_userscreen_recording_start() { //clear oled screen __display->clearDisplay(); // icon // __display->drawBitmap(0, 0, mic_icon, 48, 48, WHITE); //frame // __display->drawRect(0, 0, 128, 64, WHITE); __display->drawRoundRect(0, 0, 128, 64, 5, WHITE); //line #1 : "Recording..." __display->setFont(&LiberationSans_Regular9pt7b); __display->setTextSize(1); __display->setTextColor(WHITE); // __display->setCursor(38,12); __display->setCursor(12,22); // //__display->println("RECORDING..."); __display->println("Recording..."); //line #2 : date (small font) __display->setFont(); __display->setTextSize(1); __display->setTextColor(WHITE); // __display->setCursor(38,12); // __display->setCursor(12,38); __oled_date(year(__local), month(__local), day(__local)); __display->println(); // __display->setCursor(12,48); __oled_time(hour(__local), minute(__local), second(__local)); __display->println(); //splash! __display->display(); } static void __oled_direction_marker(filenameEntry& entry) { if (entry.latitude == 0 || __lat == 'X') { float c_x = 110; float c_y = 35; __display->drawCircle(c_x, c_y, 15, WHITE); // __display->drawCircle(c_x, c_y, 7, WHITE); __display->drawCircle(c_x, c_y, 2, WHITE); } else { float course = __gps_get_course_to(__latitude, __longitude, entry.latitude, entry.longitude); // Serial.println(course); float c_x = 110; float c_y = 35; float d_r = 15; float d_x = d_r * cos(course / 180 * PI - PI/2); float d_y = d_r * sin(course / 180 * PI - PI/2); __display->drawCircle(c_x, c_y, 15, WHITE); __display->fillCircle(c_x, c_y, 2, WHITE); __display->drawLine(c_x, c_y, c_x + d_x, c_y + d_y, WHITE); } } static void __oled_distance_info(filenameEntry& entry) { // __display->setFont(); __display->setTextSize(1); // __display->setCursor(64, 52); // if (entry.latitude == 0 || __lat == 'X') { __display->println("-.-- km"); } else { float distance = __gps_get_distance_between(__latitude, __longitude, entry.latitude, entry.longitude); // Serial.println(distance); __display->print(distance/1000, 2); __display->println(" km"); } } void __oled_userscreen_play(String file_selected) { //clear oled screen __display->clearDisplay(); //parse 'filename' filenameEntry entry; entry.parse(file_selected.c_str()); // // // __oled_fixmarker(); //small font __display->setFont(&LiberationSans_Regular6pt7b); __display->setTextSize(1); __display->setTextColor(WHITE); // __display->setCursor(38,12); __display->setCursor(0,12); //line #1 : 'date time' __display->println(file_selected.substring(0, 19)); //NOTE: --> you should be careful not to 'substring' on 'empty string.' -> it hangs!! //distance info __oled_distance_info(entry); //line #2 : index/nindex __display->setCursor(0, 45); __display->println(">>>"); //direction marker __oled_direction_marker(entry); //splash! __display->display(); } void __oled_userscreen_browse(int file_idx, String file_selected) { //clear oled screen __display->clearDisplay(); //parse 'filename' filenameEntry entry; entry.parse(file_selected.c_str()); // // // __oled_fixmarker(); //small font __display->setFont(&LiberationSans_Regular6pt7b); __display->setTextSize(1); __display->setTextColor(WHITE); // __display->setCursor(38,12); __display->setCursor(0,12); //line #1 : 'date time' __display->println(file_selected.substring(0, 19)); //NOTE: --> you should be careful not to 'substring' on 'empty string.' -> it hangs!! //distance info __oled_distance_info(entry); //line #2 : index/nindex __display->setCursor(0, 45); __display->print(file_idx); __display->print("/"); __display->println(__fs_nfiles); //direction marker __oled_direction_marker(entry); //splash! __display->display(); }
cb58073f6c4c0276e7badb2fdc02f592aa35e5e5
f7d782691f59db64e3701cdd67fab3253f33e7bb
/old/src/Utility.h
97b920d082696713ca3c19cab60ebd55b8a2607a
[]
no_license
concatto/sfml-experiments
da6c05a2942374c6df97ae24a661c3dabbaa4eeb
1fca94fc2777ee3b14383ef45388c7bb5d79ae4d
refs/heads/master
2021-03-22T02:10:11.724755
2017-11-15T02:43:25
2017-11-15T02:43:25
62,419,649
0
0
null
null
null
null
UTF-8
C++
false
false
222
h
Utility.h
/* * Utility.h * * Created on: 4 Jul 2016 * Author: Fernando */ #ifndef UTILITY_H_ #define UTILITY_H_ class Utility { public: static double random(double min = 0, double max = 1); }; #endif /* UTILITY_H_ */
0bf402c718854ffe6baa86f1372e702272bee770
1ea746d4f131b3e4ebb66c06676f386610d7d063
/Engine/Engine/Engine/AICore/Trigger.cpp
dfa7a101673adbba70646c7499ac2c8bf6ae6445
[]
no_license
ShadowDOg100/2D-Engine
c180baca221588907b2f346449e075c529a48be3
4b4b32aca7ae5d3d7d9169c9508e39a8433e77b8
refs/heads/master
2021-03-12T22:52:27.145063
2013-11-13T19:16:03
2013-11-13T19:16:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,591
cpp
Trigger.cpp
#pragma once #include "Trigger.h" #include "Messages.h" #include "../GraphicsCore/GraphicsCore.h" namespace AICore { int TriggerManager::CreateTrigger (float x, float y, float width, float height, int spriteID, float delay, int gameSpecific) { return trigger.Add(new Trigger(x, y, width, height, spriteID, delay, gameSpecific)); } TriggerManager::TriggerManager(void):Observer(){} TriggerManager::~TriggerManager(void){} void TriggerManager::Update() { } void TriggerManager::Draw() { for(int i=0; i<trigger.Top(); i++) if(trigger[i] && trigger[i]->IsActive() ) trigger[i]->Draw(); } void TriggerManager::CheckCollision(float tx, float ty, float tw, float th) { for(int i=0; i<trigger.Top(); i++) if( trigger[i]&&trigger[i]->IsActive() ) trigger[i]->CheckCollision(tx,ty,tw,th); } void TriggerManager::Flush() { trigger.Flush(); } void Trigger::CheckCollision(float tx, float ty, float tw, float th) { if( tx>=x+width || tx+tw <= x || ty >= y+height || ty+th <= y ) return; MSGData p1, p2; p1.i=ID(); p2.i=userInfo; Send(-1,AI_T_Trigger,AI_Q_TriggerTripped,p1,p2); if(delay >= 0) RemindMe((float)(delay+2.0),AI_T_Trigger,AI_Q_ReEnableTrigger,p1,p2); active=false; } void Trigger::Draw() { if(spriteID >= 0) { GraphicsCore::DrawSprite(spriteID,(int)width,(int)height, (int)x, (int)y); } } bool Trigger::Notify(int from, int to, int type, int qual, MSGData p1, MSGData p2) { if(to != ID()) return false; switch(type) { case AI_T_Trigger: switch(qual) { case AI_Q_ReEnableTrigger: active = true; return true; } break; } return false; } };
a82106f44105ca38fcc22bbf7eaecbbeaacdbc00
98b1e51f55fe389379b0db00365402359309186a
/homework_6/problem_2/10x10/0.911/T
25a557e013b514f034524e0b3496441bc40168d1
[]
no_license
taddyb/597-009
f14c0e75a03ae2fd741905c4c0bc92440d10adda
5f67e7d3910e3ec115fb3f3dc89a21dcc9a1b927
refs/heads/main
2023-01-23T08:14:47.028429
2020-12-03T13:24:27
2020-12-03T13:24:27
311,713,551
1
0
null
null
null
null
UTF-8
C++
false
false
1,970
T
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 8 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.911"; object T; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 1 0 0 0]; internalField nonuniform List<scalar> 100 ( 49.9327 4.93273 -4.99927 -1.30025 1.35849 0.87771 -0.17784 -1.43198 0.0755873 0.575821 95.3613 49.6771 11.3729 -4.79635 -3.68379 0.675311 1.71653 1.66496 -1.339 -1.1228 104.543 89.634 49.1675 13.1725 -3.79564 -4.55448 0.547426 0.558523 1.20256 0.452754 101.735 103.844 88.5098 49.076 13.4359 -3.77996 -6.16391 3.2179 1.42774 -0.744604 98.4461 104.107 103.04 87.4209 49.796 15.3409 -3.78207 -9.82441 2.63791 3.29257 99.4094 98.6902 105.629 102.668 85.1603 49.6494 17.8386 -1.86733 -10.5997 -1.74924 99.9989 98.6744 98.585 107.316 103.225 82.7764 49.5077 17.0776 0.819533 -5.26504 100.949 99.415 97.749 98.3379 109.163 102.939 82.3107 49.0512 12.8581 3.59306 100.232 100.665 100.137 96.9339 98.1397 109.679 100.426 88.2226 49.1799 3.92329 99.6849 100.542 100.516 99.7735 97.1352 101.121 105.768 97.411 95.3006 49.7139 ) ; boundaryField { left { type fixedValue; value uniform 100; } right { type zeroGradient; } up { type zeroGradient; } down { type fixedValue; value uniform 0; } frontAndBack { type empty; } } // ************************************************************************* //