hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
0cf8c9eadf4765bbe91ecff6c28a559fa567608d
370
cpp
C++
45-jump-game-ii/45-jump-game-ii.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
2
2022-01-02T19:15:00.000Z
2022-01-05T21:12:24.000Z
45-jump-game-ii/45-jump-game-ii.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
null
null
null
45-jump-game-ii/45-jump-game-ii.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
1
2022-03-11T17:11:07.000Z
2022-03-11T17:11:07.000Z
class Solution { public: int jump(vector<int>& nums) { int curreach=0; int jumps=0; int maxreach=0; for(int i=0;i<nums.size()-1;i++){ maxreach=max(maxreach, i+nums[i]); if(i==curreach){ jumps++; curreach=maxreach; } } return jumps; } };
20.555556
46
0.42973
Ananyaas
0cf9ea794f569df958c7d886479c773b7535927f
16,404
cpp
C++
src/engine/eXl_Main.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/engine/eXl_Main.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/engine/eXl_Main.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
#include <engine/eXl_Main.hpp> #include <core/corelib.hpp> #include <core/log.hpp> #include <core/plugin.hpp> #include <core/random.hpp> #include <core/clock.hpp> #include <core/coretest.hpp> #include <core/image/imagestreamer.hpp> #include <core/resource/resourcemanager.hpp> #include <core/utils/filetextreader.hpp> #include <core/stream/inputstream.hpp> #define IMGUI_API __declspec(dllimport) #include <imgui.h> #undef IMGUI_API #undef IMGUI_IMPL_API #define IMGUI_API #define IMGUI_IMPL_API #include <backends/imgui_impl_sdl.h> #include <backends/imgui_impl_opengl3.h> #include <SDL.h> #include <core/stream/jsonstreamer.hpp> #include <core/stream/jsonunstreamer.hpp> #include <fstream> #include <sstream> #include <locale> #include <codecvt> //#define USE_BAKED #ifndef __ANDROID__ extern "C" FILE* __iob_func() { static FILE locPtr[] = { *stdin, *stdout, *stderr }; return locPtr; } extern "C" { __declspec(dllexport) uint32_t NvOptimusEnablement = 0x00000001; } #endif #include <core/name.hpp> #include <core/input.hpp> #include <core/type/typemanager.hpp> #include <math/mathtools.hpp> #include "console.hpp" #include "sdlkeytranslator.hpp" #include "debugpanel.hpp" #include "debugviews.hpp" #include "navigatorbench.hpp" #include <engine/common/debugtool.hpp> #include <engine/common/menumanager.hpp> #include <engine/common/app.hpp> #include <engine/common/transforms.hpp> #include <engine/gfx/gfxsystem.hpp> #include <engine/physics/physicsys.hpp> #include <engine/pathfinding/navigator.hpp> #include <engine/common/project.hpp> #include <engine/game/scenariobase.hpp> #ifndef EXL_SHARED_LIBRARY namespace eXl { Plugin& MathPlugin_GetPlugin(); Plugin& OGLPlugin_GetPlugin(); Plugin& EnginePlugin_GetPlugin(); PluginLoadMap s_StaticPluginMap = { {"eXl_OGL", &OGLPlugin_GetPlugin}, {"eXl_Math", &MathPlugin_GetPlugin}, {"eXl_Engine", &EnginePlugin_GetPlugin} }; } #endif using namespace eXl; class SDLFileInputStream : public InputStream { public: SDLFileInputStream(char const* iPath) { m_RWStruct = SDL_RWFromFile(iPath, "rb"); if (m_RWStruct) { SDL_RWseek(m_RWStruct, 0, RW_SEEK_END); m_Size = SDL_RWtell(m_RWStruct); SDL_RWseek(m_RWStruct, 0, RW_SEEK_SET); } else { LOG_ERROR << "Could not open " << iPath << "\n"; } } ~SDLFileInputStream() { if (m_RWStruct) { SDL_RWclose(m_RWStruct); } } size_t Read(size_t iOffset, size_t iSize, void* oData) override { if (m_CurPos != iOffset) { SDL_RWseek(m_RWStruct, iOffset, RW_SEEK_SET); m_CurPos = iOffset; } size_t numRead = SDL_RWread(m_RWStruct, oData, iSize, 1); if (numRead != 0) { m_CurPos += iSize; } return numRead * iSize; } size_t GetSize() const override { return m_Size; } protected: SDL_RWops* m_RWStruct; size_t m_Size = 0; size_t m_CurPos = 0; }; class LogPanel : public MenuManager::Panel { public: LogPanel(ImGuiLogState& iLogState) : m_State(iLogState) {} private: void Display() override { m_State.Display(); } ImGuiLogState& m_State; }; class LuaConsolePanel : public MenuManager::Panel { public: LuaConsolePanel(LuaConsole& iConsole) : m_Console(iConsole) {} private: void Display() override { m_Console.Draw(); } LuaConsole& m_Console; }; struct DebugVisualizerState { float m_TimeScaling = 1.0; bool m_ViewNavMesh = false; bool m_ViewPhysic = false; bool m_ViewNeighbours = false; bool m_ViewAgents = false; }; class DebugVisualizerPanel : public MenuManager::Panel { public: DebugVisualizerPanel(DebugVisualizerState& iState) : m_State(iState) { } private: void Display() override { ImGui::DragFloat("Time Scaling", &m_State.m_TimeScaling, 0.1, 0.001, 100.0, "%.3f", ImGuiSliderFlags_Logarithmic); ImGui::Checkbox("Nav Mesh", &m_State.m_ViewNavMesh); ImGui::Checkbox("Physic", &m_State.m_ViewPhysic); ImGui::Checkbox("Neighbours", &m_State.m_ViewNeighbours); ImGui::Checkbox("Nav Agents", &m_State.m_ViewAgents); } DebugVisualizerState& m_State; }; class ProfilingPanel : public MenuManager::Panel { public: ProfilingPanel(ProfilingState const& iState) : m_State(iState) {} private: void Display() override { ImGui::Text("Last Frame Time : %f ms", m_State.m_LastFrameTime); ImGui::Text("NeighExtraction Time : %f ms", m_State.m_NeighETime); //ImGui::Text("Navigator Time : %f ms", m_State.m_NavigatorTime); ImGui::Text("Physic Time : %f ms", m_State.m_PhysicTime); ImGui::Text("Renderer Time : %f ms", m_State.m_RendererTime); ImGui::Text("Transform tick Time : %f ms", m_State.m_TransformsTickTime); } ProfilingState const& m_State; }; namespace eXl { class SDL_Application : public Engine_Application { public: SDL_Application() { SDLKeyTranslator::Init(); } SDL_Window* win = 0; SDL_GLContext context = 0; SDL_Renderer* renderer = 0; WorldState* m_World; PropertiesManifest* m_Manifest; void InitOGL() { if (context) { return; } context = SDL_GL_CreateContext(win); if (!context) { LOG_ERROR << "Failed to create OGL context" << "\n"; } if (SDL_GL_SetSwapInterval(-1) != 0) { SDL_GL_SetSwapInterval(1); } SDL_GL_MakeCurrent(win, context); GfxSystem::StaticInit(); m_World->Init(*m_Manifest).WithGfx(); if (GetScenario()) { m_World->WithScenario(GetScenario()); } GfxSystem* gfxSys = m_World->GetWorld().GetSystem<GfxSystem>(); DebugTool::SetDrawer(gfxSys->GetDebugDrawer()); } void Start_SDLApp() { SDL_SetMainReady(); SDL_Init(SDL_INIT_VIDEO); Vector2i viewportSize(m_Width, m_Height); uint32_t windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; #ifdef __ANDROID__ SDL_DisplayMode mode; SDL_GetDisplayMode(0, 0, &mode); viewportSize.X() = mode.w; viewportSize.Y() = mode.h; //windowFlags |= SDL_WINDOW_FULLSCREEN; #endif #ifdef __ANDROID__ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); #else //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); #endif win = SDL_CreateWindow("eXl", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, viewportSize.X(), viewportSize.Y(), windowFlags); InitOGL(); for (uint32_t logLevel = INFO_STREAM; logLevel <= ERROR_STREAM; ++logLevel) { Log_Manager::AddOutput(eXl_NEW ImGuiLogOutput(m_LogState, logLevel), 1 << logLevel); } #ifndef __ANDROID__ IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls ImGui_ImplSDL2_InitForOpenGL(win, context); ImGui_ImplOpenGL3_Init(); // Setup style ImGui::StyleColorsDark(); MenuManager& menuMgr = GetMenuManager(); menuMgr.AddMenu("View") .AddOpenPanelCommand("Log", [this] {return eXl_NEW LogPanel(m_LogState); }) .AddOpenPanelCommand("Profiling", [this] {return eXl_NEW ProfilingPanel(m_World->GetProfilingState()); }) .AddOpenPanelCommand("Debug", [this] {return eXl_NEW DebugPanel(m_World->GetWorld()); }) .AddOpenPanelCommand("Debug Visualizer", [this] {return eXl_NEW DebugVisualizerPanel(m_DebugVisState); }) //.AddOpenPanelCommand("Console", [this] {return eXl_NEW LuaConsolePanel(m_Console); }) .EndMenu(); NavigatorBench::AddNavigatorBenchMenu(menuMgr, m_World->GetWorld()); #endif m_World->GetCamera().view.viewportSize = viewportSize; } void PumpMessages(float iDelta) { SDL_Event curEvent; while (SDL_PollEvent(&curEvent)) { #ifndef __ANDROID__ ImGui_ImplSDL2_ProcessEvent(&curEvent); #endif if (curEvent.type == SDL_MOUSEMOTION) { SDL_MouseMotionEvent& mouseEvt = reinterpret_cast<SDL_MouseMotionEvent&>(curEvent); m_MousePos.X() = mouseEvt.x; m_MousePos.Y() = mouseEvt.y; GetInputSystem().InjectMouseMoveEvent(mouseEvt.x, mouseEvt.y, mouseEvt.xrel, mouseEvt.yrel, false); } if (curEvent.type == SDL_MOUSEWHEEL) { SDL_MouseWheelEvent& wheelEvt = reinterpret_cast<SDL_MouseWheelEvent&>(curEvent); GetInputSystem().InjectMouseMoveEvent(wheelEvt.y, wheelEvt.y, wheelEvt.y, wheelEvt.y, true); } if (curEvent.type == SDL_MOUSEBUTTONDOWN || curEvent.type == SDL_MOUSEBUTTONUP) { SDL_MouseButtonEvent& mouseEvt = reinterpret_cast<SDL_MouseButtonEvent&>(curEvent); MouseButton button; switch (mouseEvt.button) { case SDL_BUTTON_LEFT: button = MouseButton::Left; break; case SDL_BUTTON_RIGHT: button = MouseButton::Right; break; case SDL_BUTTON_MIDDLE: button = MouseButton::Middle; break; default: continue; break; } if (mouseEvt.button == SDL_BUTTON_RIGHT) { PhysicsSystem& phSys = *m_World->GetWorld().GetSystem<PhysicsSystem>(); GfxSystem& gfxSys = *m_World->GetWorld().GetSystem<GfxSystem>(); Vector3f worldPos; Vector3f viewDir; gfxSys.ScreenToWorld(m_MousePos, worldPos, viewDir); List<CollisionData> colResult; phSys.RayQuery(colResult, worldPos, worldPos - viewDir * 10000); if (!colResult.empty()) { DebugTool::SelectObject(colResult.front().obj1); } } GetInputSystem().InjectMouseEvent(button, curEvent.type == SDL_MOUSEBUTTONDOWN); } bool keyChanged = false; if (curEvent.type == SDL_KEYUP || curEvent.type == SDL_KEYDOWN) { SDL_KeyboardEvent& keyEvt = reinterpret_cast<SDL_KeyboardEvent&>(curEvent); if (keyEvt.keysym.sym == SDLK_BACKQUOTE) { if (curEvent.type == SDL_KEYUP) { m_ConsoleOpen = !m_ConsoleOpen; } } else { GetInputSystem().InjectKeyEvent(0, SDLKeyTranslator::Translate(keyEvt.keysym.scancode), curEvent.type == SDL_KEYDOWN); } } if (curEvent.type == SDL_WINDOWEVENT) { SDL_WindowEvent& winEvt = reinterpret_cast<SDL_WindowEvent&>(curEvent); if (winEvt.event == SDL_WINDOWEVENT_CLOSE) { exit(0); } if (winEvt.event == SDL_WINDOWEVENT_RESIZED) { Vector2i viewportSize; viewportSize.X() = winEvt.data1; viewportSize.Y() = winEvt.data2; m_World->GetCamera().view.viewportSize = viewportSize; } if (winEvt.event == SDL_WINDOWEVENT_SHOWN) { InitOGL(); } } if (curEvent.type == SDL_QUIT) { exit(0); } } } void Tick(float iDelta) override { PumpMessages(iDelta); if (context == 0) { return; } Engine_Application::Tick(iDelta); MenuManager& menuMgr = GetMenuManager(); #ifndef __ANDROID__ ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(win); ImGui::NewFrame(); if (ImGui::BeginMainMenuBar()) { menuMgr.DisplayMenus(); ImGui::EndMainMenuBar(); } #endif Transforms& transforms = *m_World->GetWorld().GetSystem<Transforms>(); PhysicsSystem& phSys = *m_World->GetWorld().GetSystem<PhysicsSystem>(); NavigatorSystem& navigator = *m_World->GetWorld().GetSystem<NavigatorSystem>(); { bool displayPhysSaveState = m_DebugVisState.m_ViewPhysic; #ifndef __ANDROID__ menuMgr.DisplayPanels(); #endif if (displayPhysSaveState != m_DebugVisState.m_ViewPhysic) { if (m_DebugVisState.m_ViewPhysic) { phSys.EnableDebugDraw(*DebugTool::GetDrawer()); } else { phSys.DisableDebugDraw(); } } } World& world = m_World->GetWorld(); if (m_DebugVisState.m_TimeScaling != m_World->GetWorld().GetGameTimeScaling()) { m_World->GetWorld().SetGameTimeScaling(m_DebugVisState.m_TimeScaling); } InputSystem& inputs = GetInputSystem(); //m_CamState.ProcessInputs(world, inputs); m_World->Tick(); inputs.Clear(); m_World->GetCamera().UpdateView(world); m_World->Render(m_World->GetCamera().view); if (m_DebugVisState.m_ViewNavMesh) { if (auto const* mesh = navigator.GetNavMesh()) { DrawNavMesh(*mesh, *DebugTool::GetDrawer()); } } //DrawRooms(rooms[0], gfxSys.GetDebugDrawer()); if (m_DebugVisState.m_ViewNeighbours) { DrawNeigh(phSys.GetNeighborhoodExtraction(), transforms, *DebugTool::GetDrawer()); } if (m_DebugVisState.m_ViewAgents) { DrawNavigator(navigator, transforms, *DebugTool::GetDrawer()); } #ifndef __ANDROID__ ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); #endif SDL_GL_SwapWindow(win); } ImGuiLogState m_LogState; bool m_ConsoleOpen = true; LuaConsole m_Console; DebugVisualizerState m_DebugVisState; Vector2i m_MousePos; }; } namespace { SDL_Application& GetApp() { static SDL_Application s_App; return s_App; } } eXl_Main::eXl_Main() { GetApp(); } int eXl_Main::Start(int argc, char const* const argv[]) { SDL_Application& app = GetApp(); InitConsoleLog(); app.SetWindowSize(1024, 768); app.SetArgs(argc, argv); WorldState world; app.m_World = &world; app.Start(); Path projectPath = app.GetProjectPath(); #if defined(WIN32) && !defined(USE_BAKED) ResourceManager::SetTextFileReadFactory([](char const* iFilePath) { return std::unique_ptr<TextReader>(FileTextReader::Create(iFilePath)); }); #endif #if defined(__ANDROID__) || defined(USE_BAKED) ResourceManager::SetTextFileReadFactory([](char const* iFilePath) -> std::unique_ptr<TextReader> { std::unique_ptr<SDLFileInputStream> stream = std::make_unique<SDLFileInputStream>(iFilePath); if (stream->GetSize() > 0) { return std::make_unique<InputStreamTextReader>(std::move(stream)); } return std::unique_ptr<TextReader>(); }); #endif Path appPath(GetAppPath().begin(), GetAppPath().end()); Project::ProjectTypes types; PropertiesManifest appManifest = EngineCommon::GetBaseProperties(); app.m_Manifest = &appManifest; Project* project = nullptr; if (!projectPath.empty()) { Path projectDir = projectPath.parent_path(); #if defined(USE_BAKED) && defined(WIN32) ResourceManager::BootstrapAssetsFromManifest(projectDir); #else ResourceManager::BootstrapDirectory(projectDir, true); #endif project = ResourceManager::Load<Project>(projectPath); if (!project) { return -1; } project->FillProperties(types, appManifest); ResourceManager::AddManifest(EngineCommon::GetComponents()); ResourceManager::AddManifest(appManifest); } #if defined(__ANDROID__) ResourceManager::BootstrapAssetsFromManifest(String()); #endif if (!app.GetScenario() && !app.GetMapPath().empty()) { std::unique_ptr<Scenario_Base> scenario = std::make_unique<Scenario_Base>(); MapResource const* mapRsc = ResourceManager::Load<MapResource>(app.GetMapPath()); if (mapRsc) { ResourceHandle<MapResource> mapRef; mapRef.Set(mapRsc); scenario->SetMap(mapRef); } scenario->SetMainChar(project->m_PlayerArchetype); app.SetScenario(std::move(scenario)); } app.Start_SDLApp(); app.DefaultLoop(); return 0; }
24.704819
135
0.65167
eXl-Nic
0cfaee9c4a007ed95be1bb9b8ba542046757d2fb
6,738
cpp
C++
common/MemoryRegion.cpp
zukisoft/vm
8da577329a295449ed1517bbf27cb489531b18ac
[ "MIT" ]
2
2017-02-02T13:32:14.000Z
2017-08-20T07:58:49.000Z
common/MemoryRegion.cpp
zukisoft/vm
8da577329a295449ed1517bbf27cb489531b18ac
[ "MIT" ]
null
null
null
common/MemoryRegion.cpp
zukisoft/vm
8da577329a295449ed1517bbf27cb489531b18ac
[ "MIT" ]
2
2017-03-09T02:41:25.000Z
2019-07-10T03:22:23.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2016 Michael G. Brehm // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //----------------------------------------------------------------------------- #include "stdafx.h" #include "MemoryRegion.h" #pragma warning(push, 4) //----------------------------------------------------------------------------- // MemoryRegion Destructor MemoryRegion::~MemoryRegion() { // If the region has not been detached, release it with VirtualFreeEx() if(m_base) VirtualFreeEx(m_process, m_meminfo.AllocationBase, 0, MEM_RELEASE); } //----------------------------------------------------------------------------- // MemoryRegion::Commit // // Commits page(s) of memory within the region using the specified protection // // Arguments: // // address - Base address to be committed // length - Length of the region to be committed // protect - Protection flags to be applied to the committed region void MemoryRegion::Commit(void* address, size_t length, uint32_t protect) { // The system will automatically align the provided address downward and // adjust the length such that entire page(s) will be committed if(VirtualAllocEx(m_process, address, length, MEM_COMMIT, protect) == nullptr) throw Win32Exception(); } //----------------------------------------------------------------------------- // MemoryRegion::Decommit // // Decommits page(s) of memory from within the region // // Arguments: // // address - Base address to be decommitted // length - Length of the region to be decommitted void MemoryRegion::Decommit(void* address, size_t length) { // The system will automatically align the provided address downward and // adjust the length such that entire page(s) will be decommitted if(!VirtualFreeEx(m_process, address, length, MEM_DECOMMIT)) throw Win32Exception(); } //----------------------------------------------------------------------------- // MemoryRegion::Detach // // Detaches the memory region from the class so that it will not be released // when the memory region instance is destroyed. // // Arguments: // // meminfo - MEMORY_BASIC_INFORMATION pointer to receive region data // length - Optional size_t pointer to receive the region length // // NOTE: Returns the base pointer originally set up by Reserve(); the base // allocation pointer can be accessed via the MEMORY_BASIC_INFORMATION void* MemoryRegion::Detach(PMEMORY_BASIC_INFORMATION meminfo) { // Copy the data regarding the entire allocated region if requested if(meminfo != nullptr) *meminfo = m_meminfo; void* base = m_base; // Save original pointer from Reserve() // Reset member variables to an uninitialized state to prevent use m_base = nullptr; m_length = 0; m_process = INVALID_HANDLE_VALUE; memset(&m_meminfo, 0, sizeof(MEMORY_BASIC_INFORMATION)); return base; // Return the original base pointer } //----------------------------------------------------------------------------- // MemoryRegion::Protect // // Applies new protection flags to page(s) within the allocated region // // Arguments: // // address - Base address to apply the protection // length - Length of the memory to apply the protection to // protect - Virtual memory protection flags uint32_t MemoryRegion::Protect(void* address, size_t length, uint32_t protect) { DWORD oldprotect; // Previous protection flags // The system will automatically align the provided address downward and // adjust the length such that entire page(s) will be decommitted if(!VirtualProtectEx(m_process, address, length, protect, &oldprotect)) throw Win32Exception(); return oldprotect; } //----------------------------------------------------------------------------- // MemoryRegion::Reserve (private, static) // // Reserves (and optionally commits) a region of virtual memory. When an address // has been specified, the system will attempt to construct a region that is aligned // down to the proper boundary that contains the requested address and length // // Arguments: // // process - Optional process handle to operate against or INVALID_HANDLE_VALUE // address - Optional base address to use for the allocation // length - Length of the memory region to allocate // flags - Memory region allocation type flags // protect - Memory region protection flags std::unique_ptr<MemoryRegion> MemoryRegion::Reserve(HANDLE process, size_t length, void* address, uint32_t flags, uint32_t protect) { // Map INVALID_HANDLE_VALUE to the current process handle so that the Ex() version of the // virtual memory API functions can be used exclusively by the MemoryRegion class instance if(process == INVALID_HANDLE_VALUE) process = GetCurrentProcess(); // Attempt to reserve a memory region large enough to hold the requested length. If an // address was specified, it will be automatically rounded down by the system as needed void* regionbase = VirtualAllocEx(process, address, length, flags, protect); if(regionbase == nullptr) throw Win32Exception(); // Query to determine the resultant memory region after adjustment by the system MEMORY_BASIC_INFORMATION meminfo; if(VirtualQueryEx(process, regionbase, &meminfo, sizeof(MEMORY_BASIC_INFORMATION)) == 0) { Win32Exception exception; // Save exception code VirtualFreeEx(process, regionbase, 0, MEM_RELEASE); // Release the region throw exception; } // Region has been successfully reserved using the provided parameters return std::make_unique<MemoryRegion>(process, (address) ? address : regionbase, length, meminfo); } //----------------------------------------------------------------------------- #pragma warning(pop)
40.836364
131
0.676462
zukisoft
49057be46b80676e30a87b97e09854c9ceccbb53
2,881
cpp
C++
stdlib/test/TestUtility.cpp
LetsPlaySomeUbuntu/XitongOS-test-1
792d0c76f9aa4bb2b579d47c2c728394a3acf9f9
[ "MIT" ]
null
null
null
stdlib/test/TestUtility.cpp
LetsPlaySomeUbuntu/XitongOS-test-1
792d0c76f9aa4bb2b579d47c2c728394a3acf9f9
[ "MIT" ]
null
null
null
stdlib/test/TestUtility.cpp
LetsPlaySomeUbuntu/XitongOS-test-1
792d0c76f9aa4bb2b579d47c2c728394a3acf9f9
[ "MIT" ]
null
null
null
#include "Common.hpp" #include "TrackableObject.hpp" #include <FunnyOS/Stdlib/Functional.hpp> #include <gtest/gtest.h> using namespace FunnyOS::Stdlib; TEST(TestUtility, TestStorageEmpty) { TrackableObject::ResetAll(); Storage<TrackableObject> test{}; ASSERT_EQ(TrackableObject::GetCopyConstructionCount(), 0) << "Empty storage initialization called the object constructor"; } TEST(TestUtility, TestStorageCopy) { { TrackableObject::ResetAll(); bool flag = false; TrackableObject testObject{flag}; flag = false; Storage<TrackableObject> test{InPlaceConstructorTag::Value, testObject}; ASSERT_FALSE(flag) << "Copy storage initialization called the object constructor"; ASSERT_EQ(TrackableObject::GetStandardConstructionCount(), 1) << "Copy storage initialization called the object constructor"; ASSERT_EQ(TrackableObject::GetCopyConstructionCount(), 1) << "Copy storage initialization did not call the copy constructor"; ASSERT_TRUE(test.GetObject().IsValidObject()) << "Copied object is invalid"; } ASSERT_EQ(TrackableObject::GetTotalConstructionCount(), TrackableObject::GetDestructionCount()) << "Construction count != destruction count"; } TEST(TestUtility, TestStorageInPlace) { { bool flag = false; TrackableObject::ResetAll(); Storage<TrackableObject> test{InPlaceConstructorTag::Value, flag}; ASSERT_TRUE(flag) << "In-place storage initialization did not call the object constructor"; ASSERT_EQ(TrackableObject::GetTotalConstructionCount(), 1) << "In-place storage initialization did not call the object constructor"; ASSERT_TRUE(test.GetObject().IsValidObject()) << "Constructed object is invalid"; } ASSERT_EQ(TrackableObject::GetTotalConstructionCount(), TrackableObject::GetDestructionCount()) << "Construction count != destruction count"; } TEST(TestUtility, TestAssignments) { { TrackableObject::ResetAll(); bool unused = false; TrackableObject test(unused); // construction 1 Storage<TrackableObject> inPlace{InPlaceConstructorTag::Value, unused}; // construction 2 Storage<TrackableObject> copied{inPlace}; // copy 1 Storage<TrackableObject> moved{Move(inPlace)}; // move 1 ASSERT_EQ(TrackableObject::GetStandardConstructionCount(), 2) << "Construction count invalid"; ASSERT_EQ(TrackableObject::GetMoveConstructionCount(), 1) << "Move count invalid"; ASSERT_EQ(TrackableObject::GetCopyConstructionCount(), 1) << "Copy count invalid"; } ASSERT_EQ(TrackableObject::GetTotalConstructionCount(), TrackableObject::GetDestructionCount()) << "Construction count != destruction count"; }
38.413333
102
0.68865
LetsPlaySomeUbuntu
490c92466a9605fc869507acb7b28dc5fbfc4772
11,416
cpp
C++
Phoenix3D/PX2Net/PX2IPv6AddressImpl.cpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
36
2016-04-24T01:40:38.000Z
2022-01-18T07:32:26.000Z
Phoenix3D/PX2Net/PX2IPv6AddressImpl.cpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
null
null
null
Phoenix3D/PX2Net/PX2IPv6AddressImpl.cpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
16
2016-06-13T08:43:51.000Z
2020-09-15T13:25:58.000Z
// PX2IPv6AddressImpl.cpp #include "PX2IPv6AddressImpl.hpp" #include "PX2Assert.hpp" #include "PX2StringHelp.hpp" using namespace PX2; template <typename T> unsigned MaskBits(T val, unsigned size) { unsigned count = 0; if (val) { val = (val ^ (val - 1)) >> 1; for (count = 0; val; ++count) { val >>= 1; } } else { count = size; } return size - count; } //---------------------------------------------------------------------------- IPv6AddressImpl::IPv6AddressImpl() : mScope(0) { std::memset(&mAddr, 0, sizeof(mAddr)); } //---------------------------------------------------------------------------- IPv6AddressImpl::IPv6AddressImpl(const void* addr) : mScope(0) { std::memcpy(&mAddr, addr, sizeof(mAddr)); } //---------------------------------------------------------------------------- IPv6AddressImpl::IPv6AddressImpl(const void* addr, int32_t scope) : mScope(scope) { std::memcpy(&mAddr, addr, sizeof(mAddr)); } //---------------------------------------------------------------------------- IPv6AddressImpl::IPv6AddressImpl(unsigned int prefix) : mScope(0) { unsigned i = 0; #if defined(_WIN32) || defined(WIN32) for (; prefix >= 16; ++i, prefix -= 16) { mAddr.s6_addr16[i] = 0xffff; } if (prefix > 0) mAddr.s6_addr16[i++] = htons(~(0xffff >> prefix)); while (i < 8) { mAddr.s6_addr16[i++] = 0; } #elif defined (__ANDROID__) for (; prefix >= 32; ++i, prefix -= 32) { mAddr.s6_addr32[i] = 0xffffffff; } if (prefix > 0) mAddr.s6_addr32[i++] = htonl(~(0xffffffffU >> prefix)); while (i < 4) { mAddr.s6_addr32[i++] = 0; } #endif } //---------------------------------------------------------------------------- IPv6AddressImpl::IPv6AddressImpl(const IPv6AddressImpl& addr) : mScope(0) { std::memcpy((void*) &mAddr, (void*) &addr.mAddr, sizeof(mAddr)); } //---------------------------------------------------------------------------- IPv6AddressImpl::~IPv6AddressImpl () { } //---------------------------------------------------------------------------- std::string IPv6AddressImpl::ToString() const { assertion(false, "not implemented.\n"); return ""; } //---------------------------------------------------------------------------- px2_socklen_t IPv6AddressImpl::GetAddrLength() const { return sizeof(mAddr); } //---------------------------------------------------------------------------- const void* IPv6AddressImpl::GetAddr() const { return &mAddr; } //---------------------------------------------------------------------------- IPAddress::Family IPv6AddressImpl::GetFamily() const { return IPAddress::IPv6; } //---------------------------------------------------------------------------- int IPv6AddressImpl::GetAF() const { return AF_INET6; } //---------------------------------------------------------------------------- unsigned IPv6AddressImpl::PrefixLength() const { unsigned bits = 0; unsigned bitPos = 128; #if defined(_WIN32) || defined(WIN32) for (int i = 7; i >= 0; --i) { unsigned short addr = ntohs(mAddr.s6_addr16[i]); if ((bits = MaskBits(addr, 16))) return (bitPos - (16 - bits)); bitPos -= 16; } return 0; #elif defined __ANDROID__ for (int i = 3; i >= 0; --i) { unsigned addr = ntohl(mAddr.s6_addr32[i]); if ((bits = MaskBits(addr, 32))) return (bitPos - (32 - bits)); bitPos -= 32; } return 0; #endif } //---------------------------------------------------------------------------- int32_t IPv6AddressImpl::GetScope() const { return mScope; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsWildcard() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && words[4] == 0 && words[5] == 0 && words[6] == 0 && words[7] == 0; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsBroadcast() const { return false; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsLoopback() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && words[4] == 0 && words[5] == 0 && words[6] == 0 && ntohs(words[7]) == 0x0001; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsMulticast() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return (ntohs(words[0]) & 0xFFE0) == 0xFF00; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsLinkLocal() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return (ntohs(words[0]) & 0xFFE0) == 0xFE80; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsSiteLocal() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return ((ntohs(words[0]) & 0xFFE0) == 0xFEC0) || ((ntohs(words[0]) & 0xFF00) == 0xFC00); } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsIPv4Compatible() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && words[4] == 0 && words[5] == 0; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsIPv4Mapped() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && words[4] == 0 && ntohs(words[5]) == 0xFFFF; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsWellKnownMC() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return (ntohs(words[0]) & 0xFFF0) == 0xFF00; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsNodeLocalMC() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return (ntohs(words[0]) & 0xFFEF) == 0xFF01; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsLinkLocalMC() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return (ntohs(words[0]) & 0xFFEF) == 0xFF02; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsSiteLocalMC() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return (ntohs(words[0]) & 0xFFEF) == 0xFF05; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsOrgLocalMC() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return (ntohs(words[0]) & 0xFFEF) == 0xFF08; } //---------------------------------------------------------------------------- bool IPv6AddressImpl::IsGlobalMC() const { const int16_t* words = reinterpret_cast<const int16_t*>(&mAddr); return (ntohs(words[0]) & 0xFFEF) == 0xFF0F; } //---------------------------------------------------------------------------- IPv6AddressImpl* IPv6AddressImpl::Parse(const std::string& addr) { if (addr.empty()) return 0; assertion(false, "not implemented yet.\n"); return 0; } //---------------------------------------------------------------------------- void IPv6AddressImpl::Mask(const IPAddressImpl* mask, const IPAddressImpl* set) { PX2_UNUSED(mask); PX2_UNUSED(set); assertion(false, "Mask() is only supported for IPv4 addresses.\n"); } //---------------------------------------------------------------------------- IPAddressImpl* IPv6AddressImpl::Clone() const { return new IPv6AddressImpl(&mAddr, mScope); } //---------------------------------------------------------------------------- IPv6AddressImpl IPv6AddressImpl::operator & (const IPv6AddressImpl& addr) const { IPv6AddressImpl result(&mAddr); #if defined(_WIN32) || defined(WIN32) result.mAddr.s6_addr16[0] &= addr.mAddr.s6_addr16[0]; result.mAddr.s6_addr16[1] &= addr.mAddr.s6_addr16[1]; result.mAddr.s6_addr16[2] &= addr.mAddr.s6_addr16[2]; result.mAddr.s6_addr16[3] &= addr.mAddr.s6_addr16[3]; result.mAddr.s6_addr16[4] &= addr.mAddr.s6_addr16[4]; result.mAddr.s6_addr16[5] &= addr.mAddr.s6_addr16[5]; result.mAddr.s6_addr16[6] &= addr.mAddr.s6_addr16[6]; result.mAddr.s6_addr16[7] &= addr.mAddr.s6_addr16[7]; #elif defined __ANDROID__ result.mAddr.s6_addr32[0] &= addr.mAddr.s6_addr32[0]; result.mAddr.s6_addr32[1] &= addr.mAddr.s6_addr32[1]; result.mAddr.s6_addr32[2] &= addr.mAddr.s6_addr32[2]; result.mAddr.s6_addr32[3] &= addr.mAddr.s6_addr32[3]; #endif return result; } //---------------------------------------------------------------------------- IPv6AddressImpl IPv6AddressImpl::operator | (const IPv6AddressImpl& addr) const { IPv6AddressImpl result(&mAddr); #if defined(_WIN32) || defined(WIN32) result.mAddr.s6_addr16[0] |= addr.mAddr.s6_addr16[0]; result.mAddr.s6_addr16[1] |= addr.mAddr.s6_addr16[1]; result.mAddr.s6_addr16[2] |= addr.mAddr.s6_addr16[2]; result.mAddr.s6_addr16[3] |= addr.mAddr.s6_addr16[3]; result.mAddr.s6_addr16[4] |= addr.mAddr.s6_addr16[4]; result.mAddr.s6_addr16[5] |= addr.mAddr.s6_addr16[5]; result.mAddr.s6_addr16[6] |= addr.mAddr.s6_addr16[6]; result.mAddr.s6_addr16[7] |= addr.mAddr.s6_addr16[7]; #elif defined __ANDROID__ result.mAddr.s6_addr32[0] |= addr.mAddr.s6_addr32[0]; result.mAddr.s6_addr32[1] |= addr.mAddr.s6_addr32[1]; result.mAddr.s6_addr32[2] |= addr.mAddr.s6_addr32[2]; result.mAddr.s6_addr32[3] |= addr.mAddr.s6_addr32[3]; #endif return result; } //---------------------------------------------------------------------------- IPv6AddressImpl IPv6AddressImpl::operator ^ (const IPv6AddressImpl& addr) const { IPv6AddressImpl result(&mAddr); #if defined(_WIN32) || defined(WIN32) result.mAddr.s6_addr16[0] ^= addr.mAddr.s6_addr16[0]; result.mAddr.s6_addr16[1] ^= addr.mAddr.s6_addr16[1]; result.mAddr.s6_addr16[2] ^= addr.mAddr.s6_addr16[2]; result.mAddr.s6_addr16[3] ^= addr.mAddr.s6_addr16[3]; result.mAddr.s6_addr16[4] ^= addr.mAddr.s6_addr16[4]; result.mAddr.s6_addr16[5] ^= addr.mAddr.s6_addr16[5]; result.mAddr.s6_addr16[6] ^= addr.mAddr.s6_addr16[6]; result.mAddr.s6_addr16[7] ^= addr.mAddr.s6_addr16[7]; #elif defined __ANDROID__ result.mAddr.s6_addr32[0] ^= addr.mAddr.s6_addr32[0]; result.mAddr.s6_addr32[1] ^= addr.mAddr.s6_addr32[1]; result.mAddr.s6_addr32[2] ^= addr.mAddr.s6_addr32[2]; result.mAddr.s6_addr32[3] ^= addr.mAddr.s6_addr32[3]; #endif return result; } //---------------------------------------------------------------------------- IPv6AddressImpl IPv6AddressImpl::operator ~ () const { IPv6AddressImpl result(&mAddr); #if defined(_WIN32) || defined(WIN32) result.mAddr.s6_addr16[0] ^= 0xffff; result.mAddr.s6_addr16[1] ^= 0xffff; result.mAddr.s6_addr16[2] ^= 0xffff; result.mAddr.s6_addr16[3] ^= 0xffff; result.mAddr.s6_addr16[4] ^= 0xffff; result.mAddr.s6_addr16[5] ^= 0xffff; result.mAddr.s6_addr16[6] ^= 0xffff; result.mAddr.s6_addr16[7] ^= 0xffff; #elif defined __ANDROID__ result.mAddr.s6_addr32[0] ^= 0xffffffff; result.mAddr.s6_addr32[1] ^= 0xffffffff; result.mAddr.s6_addr32[2] ^= 0xffffffff; result.mAddr.s6_addr32[3] ^= 0xffffffff; #endif return result; } //----------------------------------------------------------------------------
32.617143
119
0.525841
PheonixFoundation
490d678fb4287ec39eed40b88f2ec0d28fb4ab11
5,853
cpp
C++
Eudora71/PlaylistClient/plgen/plgen.cpp
dusong7/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
10
2018-05-23T10:43:48.000Z
2021-12-02T17:59:48.000Z
Windows/Eudora71/PlaylistClient/plgen/plgen.cpp
officialrafsan/EUDORA
bf43221f5663ec2338aaf90710a89d1490b92ed2
[ "MIT" ]
1
2019-03-19T03:56:36.000Z
2021-05-26T18:36:03.000Z
Windows/Eudora71/PlaylistClient/plgen/plgen.cpp
officialrafsan/EUDORA
bf43221f5663ec2338aaf90710a89d1490b92ed2
[ "MIT" ]
11
2018-05-23T10:43:53.000Z
2021-12-27T15:42:58.000Z
// plgen.cpp -- generate a skelleton playlist from a collection of image files #include "stdlib.h" #include "stdio.h" #include "string.h" #include "assert.h" #include "sys/types.h" #include "sys/stat.h" #include "fcntl.h" #include "io.h" #include "direct.h" //////////////////////////////////////////////////////////////////////////////// // Utils inline void trim( char* s ) { char* c; for ( c = s; *c == ' '; c++ ) ; if ( c != s ) strcpy( s, c ); for ( c = &s[strlen(s)-1]; *c == ' '; c-- ) ; *(c+1) = 0; } //////////////////////////////////////////////////////////////////////////////// // xml generation char* elements[] = {"clientUpdateResponse", "clientInfo", "reqInterval", "playlist", "playlistID", "entry", "adID", "title", "src", "url", "showFor", "showForMax", "dayMax", "blackBefore", "blackAfter", "startDT", "endDT", "nextAd"}; enum element_ids {clientUpdateResponse, clientInfo, reqInterval, playlist, playlistID, entry, entryID, title, src, href, showFor, showForMax, dayMax, blackBefore, blackAfter, startDT, endDT, nextEntry}; const int kNumElements = sizeof(elements)/4; char* defdata[kNumElements]; // track levels of indentation int level = 0; // write out an element start tag inline void startElement( int id, char** attrs, bool linebreak ) { for ( int j = level; j > 0; j-- ) printf( "\t" ); printf( "<%s>", elements[id] ); if ( linebreak ) printf( "\n" ); level++; } // write out an element end tag inline void endElement( int id, bool linebreak ) { level--; if ( linebreak ) { for ( int j = level; j > 0; j-- ) printf( "\t" ); } printf( "</%s>\n", elements[id] ); } inline void writeElementData( int id ) { if ( defdata[id] ) { printf( defdata[id] ); if ( id == src ) *(defdata[src]) = 0; } } inline void outputDataField( int id ) { startElement( id, 0, false ); writeElementData( id ); endElement( id, false ); } void initDefdata() { char buf[512]; char* key, * value; memset( defdata, 0, sizeof(defdata) ); FILE* fp = fopen( "plgen.ini", "r" ); if ( fp ) { while ( fgets( buf, sizeof(buf), fp ) ) { strtok( buf, "\n" ); key = buf; value = strchr( buf, '=' ); if ( !value || *key == ';' || *key == '[' ) continue; *value++ = 0; trim( value ); for ( int i = 0; i < kNumElements; i++ ) { if ( i != src && stricmp( key, elements[i] ) == 0 ) defdata[i] = strdup( value ); } } fclose( fp ); } // the src url cannot be initialized from the ini file defdata[src] = (char*) calloc( 1024, sizeof(char) ); assert( defdata[src] ); } void disposeDefdata() { for ( int i = 0; i < kNumElements; i++ ) { if ( defdata[i] ) free( defdata[i] ); } } //////////////////////////////////////////////////////////////////////////////// // path manglers inline void ripslash( char* s ) { int i; if ( s[(i=strlen(s))-1] == '\\' ) s[i] = 0; } inline void makeSearchSpec( char* dirpath, char* out ) { strcpy( out, dirpath ); ripslash( out ); strcat( out, "\\*" ); } // // this is pretty limited right now. it only handles relative paths that are // at or below the current working directory, or fully qualified paths that // begin with a drive specifier. // void getContentLocation( char* dirpath, char* out, int maxlen ) { strcpy( out, "file://" ); // if dirpath is fully qualified, just use that if ( dirpath[1] == ':' ) { strcpy( out, dirpath ); } else { int dpLen = strlen( dirpath ); bool cwd = (*dirpath == '.') && (dpLen == 1); // magic number is "file://" and one backslash int maxwdlen = maxlen - (cwd ? 0 : dpLen) - 8; if ( _getcwd( out+7, maxwdlen ) ) { ripslash( out ); if ( !cwd ) { strcat( out, "\\" ); strcat( out, dirpath ); ripslash( out ); } } else *out = 0; } } #define errmsg(s) (fputs( s"\n", stderr )) int main( int argc, char* argv[] ) { if ( argc < 2 ) { errmsg( "plgen -- generate playlist from a collection of image files\n" ); errmsg( " usage: plgen <image path>" ); exit(-1); } else if ( argc > 2 ) { if ( !freopen( argv[2], "w+", stdout ) ) { fprintf( stderr, "Unable to create %s\n", argv[2] ); exit( -1 ); } } else if ( argc > 3 ) errmsg( "plgen -- ignoring additional arguements" ); int ret = -1; int entries = 0; long hFind; bool fileFound; char srchSpec[_MAX_PATH] = ""; char contentLoc[_MAX_PATH] = ""; struct _finddata_t fileInfo; initDefdata(); makeSearchSpec( argv[1], srchSpec ); getContentLocation( argv[1], contentLoc, sizeof(contentLoc) ); if ( (hFind = _findfirst( srchSpec, &fileInfo )) != -1 ) { // first two files are always directories, and we need to find at least // one file to continue---currently don't do subdirs. while ( _findnext( hFind, &fileInfo ) == 0 ) { if ( fileFound = !(fileInfo.attrib & _A_SUBDIR) ) break; } if ( fileFound ) { startElement( clientUpdateResponse, 0, true ); // write the clientInfo block startElement( clientInfo, 0, true ); outputDataField( reqInterval ); endElement( clientInfo, true ); // the actual playlist starts here startElement( playlist, 0, true ); outputDataField( playlistID ); do { // make a full URL to our found file sprintf( defdata[src], "%s\\%s", contentLoc, fileInfo.name ); startElement( entry, 0, true ); for ( int i = entryID; i < kNumElements; i++ ) outputDataField( i ); endElement( entry, true ); entries++; } while ( _findnext( hFind, &fileInfo ) == 0 ); endElement( playlist, true ); endElement( clientUpdateResponse, true ); ret = 0; } else errmsg( "plgen -- that directory ain't got a darn thing in it" ); _findclose( hFind ); } else errmsg( "plgen -- we don't like that image directory path" ); disposeDefdata(); fprintf( stderr, "%i playlist entries written\n", entries ); return ret; }
21.839552
80
0.577311
dusong7
491082493c7d0dd575b79f3c56de54fa622f773e
628
cpp
C++
virtual_functions_sau.cpp
saurabhkakade21/Cpp-Practice-Code
ac5e77f1a53bb164f7b265e9291b3ca63a2a2f60
[ "MIT" ]
null
null
null
virtual_functions_sau.cpp
saurabhkakade21/Cpp-Practice-Code
ac5e77f1a53bb164f7b265e9291b3ca63a2a2f60
[ "MIT" ]
null
null
null
virtual_functions_sau.cpp
saurabhkakade21/Cpp-Practice-Code
ac5e77f1a53bb164f7b265e9291b3ca63a2a2f60
[ "MIT" ]
null
null
null
#include <iostream> #include "virtual_functions.h" using namespace std; void Account::withdraw(double amount) const { std::cout << "In Account class: Withdraw: " << std::endl; } void Checking::withdraw(double amount) const { std::cout << "In Checking class: Withdraw: " << std::endl; } Account :: ~Account() { cout << "Account destructor" << endl; } Checking :: ~Checking() { cout << "Checking destructor" << endl; } int main() { Account *p1 = new Account(); Account *p2 = new Checking(); p1->withdraw(1000); p2->withdraw(2000); delete p1; delete p2; return 0; }
16.526316
63
0.606688
saurabhkakade21
4911a78985c955b09fc5ce18591112fa8c3caf44
89
cpp
C++
09-sequential-containers/09-38.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
09-sequential-containers/09-38.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
09-sequential-containers/09-38.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
// Exercise 9.38: Write a program to explore how vectors grow in the library you // use.
29.666667
80
0.730337
aafulei
491cef8a20d5d2e6619ff743fa3487bcf3bdf94d
1,581
hpp
C++
src/Assert.hpp
nandofioretto/cpuBE
641e42ae4f1f7d9b82f323256fec86d7aa8f8ac1
[ "MIT" ]
1
2018-06-27T11:39:41.000Z
2018-06-27T11:39:41.000Z
src/Assert.hpp
nandofioretto/cpuBE
641e42ae4f1f7d9b82f323256fec86d7aa8f8ac1
[ "MIT" ]
null
null
null
src/Assert.hpp
nandofioretto/cpuBE
641e42ae4f1f7d9b82f323256fec86d7aa8f8ac1
[ "MIT" ]
null
null
null
// // Created by Ferdinando Fioretto on 11/7/15. // #ifndef CUDA_DBE_ASSERT_HPP #define CUDA_DBE_ASSERT_HPP #include <cassert> #include <iostream> #include <string> #include "Preferences.hpp" // A macro to disallow the copy constructor and operator= functions. // It should be used in the private declarations for a class. #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) // A macro to attach a message to the assert command. #ifndef NDEBUG # define ASSERT(condition, message) \ do { \ if (! (condition)) { \ std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \ << " line " << __LINE__ << ": " << message << std::endl; \ std::exit(EXIT_FAILURE); \ } \ } while (false) #else # define \ ASSERT(condition, message) do { } while (false) #endif // A macro to print a worning message when a condition is not satisfied # define WARNING(condition, message) \ do { \ if (! (condition)) { \ std::cerr << "Warning: " << message << std::endl; \ } \ } while (false) namespace Assert { static void check(bool condition, std::string msg, std::string err) { if (!condition) { std::cerr << "Assertion: " << msg << std::endl << "File: " << __FILE__ << " line: " << __LINE__ << std::endl; if (Preferences::csvFormat) { std::cout << "NA\tNA\t" << err << std::endl; } std::exit(EXIT_FAILURE); } } } #endif // CUDA_DBE_ASSERT_HPP
26.79661
72
0.587603
nandofioretto
4922604475aeddcd66aa72150aa7787262ad45eb
4,909
cpp
C++
cpp-projects/exvr-designer/widgets/components/config_parameters/image_resource_pw.cpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
cpp-projects/exvr-designer/widgets/components/config_parameters/image_resource_pw.cpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
cpp-projects/exvr-designer/widgets/components/config_parameters/image_resource_pw.cpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
/*********************************************************************************** ** exvr-designer ** ** MIT License ** ** Copyright (c) [2018] [Florian Lance][EPFL-LNCO] ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ************************************************************************************/ #include "image_resource_pw.hpp" // local #include "ex_widgets/ex_resources_list_w.hpp" #include "ex_widgets/ex_line_edit_w.hpp" #include "ex_widgets/ex_radio_button_w.hpp" #include "ex_widgets/ex_spin_box_w.hpp" #include "ex_widgets/ex_checkbox_w.hpp" using namespace tool::ex; struct ImageResourceInitConfigParametersW::Impl{ ExResourcesListW imagesList{"images_list"}; }; ImageResourceInitConfigParametersW::ImageResourceInitConfigParametersW() : ConfigParametersW(), m_p(std::make_unique<Impl>()){ } void ImageResourceInitConfigParametersW::insert_widgets(){ add_widget(ui::F::gen(ui::L::VB(), {m_p->imagesList()}, LStretch{false}, LMargins{true}, QFrame::Box)); no_end_stretch(); } void ImageResourceInitConfigParametersW::init_and_register_widgets(){ add_input_ui(m_p->imagesList.init_widget(Resource::Type::Image, "Images:")); } void ImageResourceInitConfigParametersW::create_connections(){ connect(&m_p->imagesList, &ExResourcesListW::ui_change_signal, this, [&]{ }); } void ImageResourceInitConfigParametersW::late_update_ui(){} struct ImageResourceConfigParametersW::Impl{ ExCheckBoxW startExp{"start_exp"}; ExCheckBoxW startRoutine{"start_routine"}; ExCheckBoxW stopRoutine{"stop_routine"}; QButtonGroup group1; ExRadioButtonW sendAlias{"use_alias"}; ExRadioButtonW sendId{"use_id"}; ExLineEditW alias{"alias"}; ExSpinBoxW id{"id"}; }; ImageResourceConfigParametersW::ImageResourceConfigParametersW() : ConfigParametersW(), m_p(std::make_unique<Impl>()){ } void ImageResourceConfigParametersW::insert_widgets(){ layout()->setContentsMargins(0,0,0,0); add_widget(ui::F::gen(ui::L::VB(), {ui::W::txt("Send current image when:"), m_p->startExp(),m_p->startRoutine(),m_p->stopRoutine()}, LStretch{false}, LMargins{true}, QFrame::NoFrame)); add_widget(ui::F::gen(ui::L::HB(), {ui::W::txt("Using:"), m_p->sendAlias(),m_p->sendId()}, LStretch{true}, LMargins{true}, QFrame::NoFrame)); add_widget(ui::F::gen(ui::L::HB(), {ui::W::txt("From init config images resources list:")}, LStretch{true}, LMargins{true}, QFrame::NoFrame)); add_widget(ui::F::gen(ui::L::HB(), {ui::W::txt("Id"), m_p->id(), ui::W::txt("Alias"), m_p->alias()}, LStretch{false}, LMargins{true}, QFrame::NoFrame)); } void ImageResourceConfigParametersW::init_and_register_widgets(){ add_input_ui(m_p->startExp.init_widget(" experiment starts", true)); add_input_ui(m_p->startRoutine.init_widget(" routine starts", true)); add_input_ui(m_p->stopRoutine.init_widget(" routine stops", true)); add_inputs_ui( ExRadioButtonW::init_group_widgets(m_p->group1, {&m_p->sendId, &m_p->sendAlias}, { "id", "alias", }, {true,false} )); add_input_ui(m_p->alias.init_widget("")); add_input_ui(m_p->id.init_widget(MinV<int>{0}, V<int>{0}, MaxV<int>{10000}, StepV<int>{1})); } void ImageResourceConfigParametersW::create_connections(){ } void ImageResourceConfigParametersW::late_update_ui(){ }
46.311321
188
0.6209
FlorianLance
49264aa1408b8a207f6b72118b7c3808be7ad7f9
4,650
cc
C++
src/GUI_language.cc
edrosten/gvars
62f5a78025dd616483487c9069f6b7f16c57922f
[ "BSD-2-Clause" ]
15
2015-01-27T10:49:32.000Z
2019-02-17T20:41:06.000Z
src/GUI_language.cc
edrosten/gvars
62f5a78025dd616483487c9069f6b7f16c57922f
[ "BSD-2-Clause" ]
2
2016-07-13T01:13:32.000Z
2020-08-18T07:48:26.000Z
src/GUI_language.cc
edrosten/gvars
62f5a78025dd616483487c9069f6b7f16c57922f
[ "BSD-2-Clause" ]
15
2015-02-25T03:28:45.000Z
2022-01-05T12:25:51.000Z
/* This file is part of the GVars3 Library. Copyright (C) 2005 The Authors This library is free software, see LICENSE file for details */ #include "gvars3/instances.h" #include "gvars3/GStringUtil.h" #include <vector> #include <iostream> #include <set> #include <pthread.h> using namespace std; namespace GVars3 { template<class C> class ThreadLocal { private: pthread_key_t key; static void deleter(void* v) { delete static_cast<C*>(v); } public: ThreadLocal() { pthread_key_create(&key, deleter); pthread_setspecific(key, new C); } ~ThreadLocal() { deleter(pthread_getspecific(key)); pthread_setspecific(key, 0); pthread_key_delete(key); } C& operator()() { return *static_cast<C*>(pthread_getspecific(key)); } }; template<class A, class B> class MutexMap { private: map<A, B> _map; pthread_mutex_t mutex; public: MutexMap() { pthread_mutex_init(&mutex, 0); } ~MutexMap() { pthread_mutex_destroy(&mutex); } B get(const A& a) { B b; pthread_mutex_lock(&mutex); b = _map[a]; pthread_mutex_unlock(&mutex); return b; } void set(const A&a, const B& b) { pthread_mutex_lock(&mutex); _map[a] = b; pthread_mutex_unlock(&mutex); } }; class GUI_language { public: GUI_language() { GUI.RegisterCommand(".", collect_lineCB, this); GUI.RegisterCommand("function", functionCB, this); GUI.RegisterCommand("endfunction", endfunctionCB, this); GUI.RegisterCommand("if_equal", gui_if_equalCB, this); GUI.RegisterCommand("else", gui_if_elseCB, this); GUI.RegisterCommand("endif", gui_endifCB, this); } ~GUI_language() { } private: pthread_mutex_t functionlist_mutex; ThreadLocal<string> current_function, if_gvar, if_string; ThreadLocal<vector<string> > collection, ifbit, elsebit; MutexMap<string, vector<string> > functions; static GUI_language& C(void* v) { return *static_cast<GUI_language*>(v); } #define CallBack(X) static void X##CB(void* t, string a, string b){C(t).X(a, b);} CallBack(collect_line); void collect_line(string, string l) { collection().push_back(l); } CallBack(function); void function(string name, string args) { vector<string> vs = ChopAndUnquoteString(args); if(vs.size() != 1) { cerr << "Error: " << name << " takes 1 argument: " << name << " name\n"; return; } current_function()=vs[0]; collection().clear(); } CallBack(endfunction) void endfunction(string name, string args) { if(current_function() == "") { cerr << "Error: " << name << ": no current function.\n"; return; } vector<string> vs = ChopAndUnquoteString(args); if(vs.size() != 0) cerr << "Warning: " << name << " takes 0 arguments.\n"; functions.set(current_function(), collection()); GUI.RegisterCommand(current_function(), runfuncCB, this); current_function().clear(); collection().clear(); } CallBack(runfunc) void runfunc(string name, string /*args*/) { vector<string> v = functions.get(name); for(unsigned int i=0; i < v.size(); i++) GUI.ParseLine(v[i]); } CallBack(gui_if_equal) void gui_if_equal(string name, string args) { vector<string> vs = ChopAndUnquoteString(args); if(vs.size() != 2) { cerr << "Error: " << name << " takes 2 arguments: " << name << " gvar string\n"; return; } collection().clear(); if_gvar() = vs[0]; if_string() = vs[1]; } CallBack(gui_if_else) void gui_if_else(string /*name*/, string /*args*/) { ifbit() = collection(); if(ifbit().empty()) ifbit().push_back(""); collection().clear(); } CallBack(gui_endif) void gui_endif(string /*name*/, string /*args*/) { if(ifbit().empty()) ifbit() = collection(); else elsebit() = collection(); collection().clear(); //Save a copy, since it canget trashed vector<string> ib = ifbit(), eb = elsebit(); string gv = if_gvar(), st = if_string(); ifbit().clear(); elsebit().clear(); if_gvar().clear(); if_string().clear(); if(GV3::get_var(gv) == st) for(unsigned int i=0; i < ib.size(); i++) GUI.ParseLine(ib[i]); else for(unsigned int i=0; i < eb.size(); i++) GUI.ParseLine(eb[i]); } }; GUI_language* get_new_lang() { return new GUI_language; } void remove_lang(GUI_language* l) { delete l; } //GUI_language GUI_language_instance; }
19.294606
85
0.603226
edrosten
49277029a1c42eca60530c5336de2404ab50bdf4
956
hpp
C++
addons/niarms/caliber/556/m4.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
addons/niarms/caliber/556/m4.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
addons/niarms/caliber/556/m4.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
// M4 Variants Inherits (Some are broken with no barrel length at all.) // AR15 Sanitised Carbine - Short Barrel class hlc_rifle_RU556: hlc_ar15_base { recoil = QCLASS(556_ShortBarrel); }; // BCM 'Jack' Carbine - Medium Barrel class hlc_rifle_bcmjack: hlc_ar15_base { recoil = QCLASS(556_MediumBarrel); }; // Colt M4A1 Carbine - Medium Barrel class hlc_rifle_M4: hlc_ar15_base { recoil = QCLASS(556_MediumBarrel); }; // GL class hlc_rifle_m4m203: hlc_rifle_M4 { recoil = QCLASS(556_GL_Medium); }; // Colt R0727 Carbine - Medium Barrel class hlc_rifle_Colt727: hlc_ar15_base { recoil = QCLASS(556_MediumBarrel); }; // GL class hlc_rifle_Colt727_GL: hlc_rifle_Colt727 { recoil = QCLASS(556_GL_Medium); }; // MK18 MOD 0 - Short Barrel class hlc_rifle_mk18mod0: hlc_rifle_CQBR { recoil = QCLASS(556_ShortBarrel); }; // RRA LAR-15 AMR - Long Barrel class hlc_rifle_SAMR: hlc_ar15_base { recoil = QCLASS(556_LongBarrel); };
23.9
71
0.733264
Theseus-Aegis
492b6a5354667eb85291c9137703773c80e1b941
649
cpp
C++
include/hydro/parser/__ast/VarDecl.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/parser/__ast/VarDecl.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/parser/__ast/VarDecl.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // #include "VarDecl.hpp" namespace hydro { VarDecl::VarDecl(lex_token token, ast_mod mods, ast_name name, ast_htype type, ast_expr defaultValue, Symbol *symbol) : Decl{token, mods, name, symbol}, _type{type}, _defaultValue(defaultValue) {} VarDecl::~VarDecl() {} } // namespace hydro
29.5
196
0.448382
hydraate
4934662d731fa57f4a638f3f7a1abf1216a2a8d7
4,267
cpp
C++
tools/apf_tools/FieldConverter.cpp
schuetzepaul/allpix-squared
737eba52fe13f56134c4e88a7928d1a5103dd40a
[ "MIT" ]
3
2019-03-04T22:31:32.000Z
2021-04-20T11:19:17.000Z
tools/apf_tools/FieldConverter.cpp
schuetzepaul/allpix-squared
737eba52fe13f56134c4e88a7928d1a5103dd40a
[ "MIT" ]
27
2019-04-01T12:25:46.000Z
2021-09-03T12:20:19.000Z
tools/apf_tools/FieldConverter.cpp
schuetzepaul/allpix-squared
737eba52fe13f56134c4e88a7928d1a5103dd40a
[ "MIT" ]
15
2017-08-08T14:57:51.000Z
2021-06-26T17:16:21.000Z
/** * @file * @brief Small converter for field data INIT <-> APF */ #include <algorithm> #include <fstream> #include <string> #include "core/utils/log.h" #include "tools/field_parser.h" #include "tools/units.h" using namespace allpix; /** * @brief Main function running the application */ int main(int argc, const char* argv[]) { int return_code = 0; try { // Register the default set of units with this executable: register_units(); // Add cout as the default logging stream Log::addStream(std::cout); // If no arguments are provided, print the help: bool print_help = false; if(argc == 1) { print_help = true; return_code = 1; } // Parse arguments FileType format_to = FileType::UNKNOWN; std::string file_input; std::string file_output; std::string units; bool scalar = false; for(int i = 1; i < argc; i++) { if(strcmp(argv[i], "-h") == 0) { print_help = true; } else if(strcmp(argv[i], "-v") == 0 && (i + 1 < argc)) { try { LogLevel log_level = Log::getLevelFromString(std::string(argv[++i])); Log::setReportingLevel(log_level); } catch(std::invalid_argument& e) { LOG(ERROR) << "Invalid verbosity level \"" << std::string(argv[i]) << "\", ignoring overwrite"; } } else if(strcmp(argv[i], "--to") == 0 && (i + 1 < argc)) { std::string format = std::string(argv[++i]); std::transform(format.begin(), format.end(), format.begin(), ::tolower); format_to = (format == "init" ? FileType::INIT : format == "apf" ? FileType::APF : FileType::UNKNOWN); } else if(strcmp(argv[i], "--input") == 0 && (i + 1 < argc)) { file_input = std::string(argv[++i]); } else if(strcmp(argv[i], "--output") == 0 && (i + 1 < argc)) { file_output = std::string(argv[++i]); } else if(strcmp(argv[i], "--units") == 0 && (i + 1 < argc)) { units = std::string(argv[++i]); } else if(strcmp(argv[i], "--scalar") == 0) { scalar = true; } else { LOG(ERROR) << "Unrecognized command line argument \"" << argv[i] << "\""; print_help = true; return_code = 1; } } // Print help if requested or no arguments given if(print_help) { std::cout << "Allpix Squared Field Converter Tool" << std::endl; std::cout << std::endl; std::cout << "Usage: field_converter <parameters>" << std::endl; std::cout << std::endl; std::cout << "Parameters (all mandatory):" << std::endl; std::cout << " --to <format> file format of the output file" << std::endl; std::cout << " --input <file> input field file" << std::endl; std::cout << " --output <file> output field file" << std::endl; std::cout << " --units <units> units the field is provided in" << std::endl << std::endl; std::cout << "Options:" << std::endl; std::cout << " --scalar Convert scalar field. Default is vector field" << std::endl; std::cout << std::endl; std::cout << "For more help, please see <https://cern.ch/allpix-squared>" << std::endl; return return_code; } FieldQuantity quantity = (scalar ? FieldQuantity::SCALAR : FieldQuantity::VECTOR); FieldParser<double> field_parser(quantity); LOG(STATUS) << "Reading input file from " << file_input; auto field_data = field_parser.getByFileName(file_input, units); FieldWriter<double> field_writer(quantity); LOG(STATUS) << "Writing output file to " << file_output; field_writer.writeFile(field_data, file_output, format_to, (format_to == FileType::INIT ? units : "")); } catch(std::exception& e) { LOG(FATAL) << "Fatal internal error" << std::endl << e.what() << std::endl << "Cannot continue."; return_code = 127; } return return_code; }
40.638095
118
0.525428
schuetzepaul
4934e9df538be2cd6e32aa5000bb5b79eca4cb35
1,326
cpp
C++
src/qt/qtwebkit/Source/WebCore/loader/soup/CachedRawResourceSoup.cpp
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2015-05-27T13:52:20.000Z
2015-05-27T13:52:20.000Z
src/qt/qtwebkit/Source/WebCore/loader/soup/CachedRawResourceSoup.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtwebkit/Source/WebCore/loader/soup/CachedRawResourceSoup.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2017-03-19T13:03:23.000Z
2017-03-19T13:03:23.000Z
/* * Copyright (C) 2013 Igalia S.L. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "CachedRawResource.h" #include "CachedRawResourceClient.h" #include "CachedResourceClientWalker.h" namespace WebCore { char* CachedRawResource::getOrCreateReadBuffer(size_t requestedSize, size_t& actualSize) { CachedResourceClientWalker<CachedRawResourceClient> w(m_clients); while (CachedRawResourceClient* c = w.next()) { if (char* bufferPtr = c->getOrCreateReadBuffer(this, requestedSize, actualSize)) return bufferPtr; } return 0; } } // namespace WebCore
34
88
0.735294
viewdy
4937b18a69ca34d4cdd487b596ac767fe7e0e319
5,308
cpp
C++
example/net/pingpong/main.cpp
zizzzw/fflib
ba9b465347b650d86c34876fbfae48bc31194d97
[ "MIT" ]
1
2022-02-08T07:28:07.000Z
2022-02-08T07:28:07.000Z
example/net/pingpong/main.cpp
zizzzw/fflib
ba9b465347b650d86c34876fbfae48bc31194d97
[ "MIT" ]
null
null
null
example/net/pingpong/main.cpp
zizzzw/fflib
ba9b465347b650d86c34876fbfae48bc31194d97
[ "MIT" ]
2
2022-01-06T02:16:09.000Z
2022-01-19T12:49:54.000Z
/*********************************************** The MIT License (MIT) Copyright (c) 2012 Athrun Arthur <athrunarthur@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************/ #include "ff/network.h" #include <chrono> #include <iostream> define_nt(msg, std::string); define_nt(uid, uint64_t, "uid"); typedef ff::net::ntpackage<110, msg, uid> ping_msg; typedef ff::net::ntpackage<111, msg, uid> pong_msg; class client : public ff::net::routine { public: client() : ff::net::routine("client") {} virtual void initialize(ff::net::net_mode nm, const std::vector<std::string> &args) { pkghub.tcp_to_recv_pkg<pong_msg>(std::bind(&client::onRecvPong, this, std::placeholders::_1, std::placeholders::_2)); pnn = new ff::net::net_nervure(nm); pnn->add_pkg_hub(pkghub); pnn->add_tcp_client("127.0.0.1", 6891); pnn->get_event_handler()->listen<ff::net::event::tcp_get_connection>( std::bind(&client::onConnSucc, this, std::placeholders::_1)); pnn->get_event_handler()->listen<ff::net::event::tcp_lost_connection>( std::bind(&client::onLostConn, this, std::placeholders::_1, pnn)); } virtual void run() { pnn->run(); } protected: void sendPingMsg(ff::net::tcp_connection_base *pConn) { char *pContent = new char[16]; const char *str = "ping world!"; std::memcpy(pContent, str, std::strlen(str) + 1); std::shared_ptr<ping_msg> pMsg(new ping_msg()); pMsg->template set<msg, uid>(std::string("ping world"), 1); pConn->send(pMsg); ff::net::mout << "service running..." << std::endl; } void onRecvPong(std::shared_ptr<pong_msg> pPong, ff::net::tcp_connection_base *from) { // pong_msg &msg = *pPong.get(); ff::net::mout << "got pong!" << pPong->template get<msg>() << ", " << pPong->template get<uid>() << std::endl; sendPingMsg(from); } void onConnSucc(ff::net::tcp_connection_base *pConn) { ff::net::mout << "connect success" << std::endl; sendPingMsg(pConn); } void onLostConn(ff::net::tcp_connection_base *pConn, ff::net::net_nervure *pbn) { ff::net::mout << "Server lost!" << std::endl; pbn->stop(); } protected: ff::net::typed_pkg_hub pkghub; ff::net::net_nervure *pnn; }; class server : public ff::net::routine { public: server() : ff::net::routine("server") {} virtual void initialize(ff::net::net_mode nm, const std::vector<std::string> &args) { pkghub.tcp_to_recv_pkg<ping_msg>(std::bind(&server::onRecvPing, this, std::placeholders::_1, std::placeholders::_2)); pnn = new ff::net::net_nervure(nm); pnn->add_pkg_hub(pkghub); pnn->add_tcp_server("127.0.0.1", 6891); pnn->get_event_handler()->listen<ff::net::event::tcp_lost_connection>( std::bind(&server::onLostTCPConnection, this, std::placeholders::_1)); } virtual void run() { std::thread monitor_thrd(std::bind(&server::press_and_stop, this)); pnn->run(); monitor_thrd.join(); } protected: void onRecvPing(std::shared_ptr<ping_msg> pPing, ff::net::tcp_connection_base *from) { // pPing->print(); auto ping_uid = pPing->template get<uid>(); std::this_thread::sleep_for(std::chrono::seconds(1)); std::shared_ptr<pong_msg> pkg(new pong_msg()); pkg->template set<uid>(ping_uid + 1); pkg->template set<msg>(pPing->template get<msg>()); from->send(pkg); } void onLostTCPConnection(ff::net::tcp_connection_base *pConn) { ff::net::mout << "lost connection!" << std::endl; } void press_and_stop() { ff::net::mout << "Press any key to quit..." << std::endl; std::cin.get(); pnn->stop(); ff::net::mout << "Stopping, please wait..." << std::endl; } protected: ff::net::typed_pkg_hub pkghub; ff::net::net_nervure *pnn; }; int main(int argc, char *argv[]) { ff::net::application app("pingpong"); app.initialize(argc, argv); client c; server s; app.register_routine(&c); app.register_routine(&s); app.run(); return 0; }
33.808917
79
0.625283
zizzzw
4937e32fa2051008dd83b908374d158619aa19b4
463
cpp
C++
Class 11/44.cpp
AniMysore74/Computer-Class
4764603b51cebfd99ac3c7a4968c9672e7b27526
[ "Apache-2.0" ]
null
null
null
Class 11/44.cpp
AniMysore74/Computer-Class
4764603b51cebfd99ac3c7a4968c9672e7b27526
[ "Apache-2.0" ]
null
null
null
Class 11/44.cpp
AniMysore74/Computer-Class
4764603b51cebfd99ac3c7a4968c9672e7b27526
[ "Apache-2.0" ]
null
null
null
//Read two strings and copy the shorter string into the bigger string #include<iostream.h> #include<conio.h> #include<string.h> int main() { char str1[30],str2[30]; cout<<"Enter string 1 : "; cin>>str1; cout<<"Enter string 2 : "; cin>>str2; if(strlen(str1)>strlen(str2)) strcpy(str2,str1); else strcpy(str1,str2); cout<<"The value of the strings now are: \n"<<"String 1 : "<<str1<<"\nString 2 : "<<str2; getch(); return 0; }
23.15
97
0.62203
AniMysore74
493a418aa135f17752df62fa5b7dd384ee8cedce
1,616
cpp
C++
cpp/other/IntCell.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
cpp/other/IntCell.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
cpp/other/IntCell.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
/* * This example piece of code shows the case when default big five doesn't work * We would have to manually define big five ourselves */ #include <iostream> #include <string> using namespace std; class IntCell { public: explicit IntCell(int init = 0) { cout << "Call explicit constructor" << this << endl; stored = new int(init); } ~IntCell() { cout << "Destroy object" << this << endl; delete stored; } IntCell(const IntCell& rhs) { cout << "Call copy constructor " << this << endl; stored = new int(*rhs.stored); } IntCell(IntCell && rhs) { cout << "Call move constructor " << this << endl; stored = rhs.stored; rhs.stored = nullptr; } IntCell & operator= (const IntCell& rhs) { cout << "Call copy assignment" << this << endl; if(this != &rhs) *stored = *rhs.stored; return *this; } IntCell & operator= (IntCell&& rhs) { cout << "Call move assignment" << this << endl; std::swap(stored, rhs.stored); return *this; } int read() const { return *stored; } void write(int x) { *stored = x; } private: int* stored; }; IntCell create(); int main() { IntCell a(2); IntCell b = a; IntCell c; c = b; c = create();//inside function call explicit and then move assignment a.write(4); std::cout << a.read() << std::endl << b.read() << std::endl << c.read() << std::endl; return 0; } IntCell create(){ IntCell a; return a; }
20.455696
89
0.53651
danyfang
493a41a1d87ce182b9f32b08206907fc7e64d948
30,298
cpp
C++
CBP/CBP/UI/Common/SimComponent.cpp
clayne/CBPSSE
c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5
[ "MIT" ]
3
2020-06-21T18:10:19.000Z
2021-02-05T21:33:18.000Z
CBP/CBP/UI/Common/SimComponent.cpp
clayne/CBPSSE
c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5
[ "MIT" ]
2
2020-08-29T14:29:19.000Z
2020-09-10T18:40:52.000Z
CBP/CBP/UI/Common/SimComponent.cpp
clayne/CBPSSE
c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5
[ "MIT" ]
4
2020-08-25T17:56:35.000Z
2021-11-25T09:39:47.000Z
#include "pch.h" #include "SimComponent.h" #include "Drivers/cbp.h" namespace CBP { template <class T, UIEditorID ID> const PhysicsProfile* UISimComponent<T, ID>::GetSelectedProfile() const { return nullptr; } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DrawGroupOptions( T a_handle, configComponents_t& a_data, configComponentsValue_t& a_pair, nodeConfigList_t& a_nodeConfig) { } template <class T, UIEditorID ID> void UISimComponent<T, ID>::Propagate( configComponents_t& a_dl, configComponents_t* a_dg, const configComponentsValue_t& a_pair, propagateFunc_t a_func) const { const auto& globalConfig = IConfig::GetGlobal(); auto itm = globalConfig.ui.propagate.find(ID); if (itm == globalConfig.ui.propagate.end()) return; auto it = itm->second.find(a_pair.first); if (it == itm->second.end()) return; for (auto& e : it->second) { if (!e.second.enabled) continue; auto it1 = a_dl.find(e.first); if (it1 != a_dl.end()) a_func(it1->second, e.second); if (a_dg != nullptr) { auto it2 = a_dg->find(e.first); if (it2 != a_dg->end()) a_func(it2->second, e.second); } } } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DrawSimComponents( T a_handle, configComponents_t& a_data) { //ImGui::PushID(static_cast<const void*>(std::addressof(a_data))); DrawItemFilter(); ImGui::Separator(); const float width = ImGui::GetWindowContentRegionMax().x; if (ImGui::BeginChild("scc_area", ImVec2(width, 0.0f))) { ImGui::PushItemWidth(ImGui::GetFontSize() * -16.0f); nodeConfigList_t nodeList; const auto& scConfig = GetSimComponentConfig(); auto& cg = IConfig::GetConfigGroupMap(); auto& nodeConf = GetNodeData(a_handle); for (const auto& g : cg) { if (!m_groupFilter->Test(g.first)) continue; nodeList.clear(); GetNodeConfig(nodeConf, g, nodeList); configComponentsValue_t* pair; if (ShouldDrawComponent(a_handle, a_data, g, nodeList)) { pair = std::addressof(*a_data.try_emplace(g.first).first); } else { if (!scConfig.showNodes) continue; pair = nullptr; } if (CollapsingHeader(GetCSID(g.first), g.first.c_str())) { ImGui::PushID(static_cast<const void*>(std::addressof(g.second))); if (pair) DrawComponentTab(a_handle, a_data, *pair, nodeList); if (scConfig.showNodes) DrawConfGroupNodeMenu(a_handle, nodeList); if (pair) DrawSliders(a_handle, a_data, *pair, nodeList); ImGui::PopID(); } if (m_eraseCurrent) { m_eraseCurrent = false; a_data.erase(g.first); } } ImGui::PopItemWidth(); } ImGui::EndChild(); // ImGui::PopID(); } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DrawComponentTab( T a_handle, configComponents_t& a_data, configComponentsValue_t& a_pair, nodeConfigList_t& a_nodeConfig ) { ImGui::PushID("__component_tab"); if (ImGui::Button("Propagate >")) ImGui::OpenPopup("propagate_popup"); auto profile = GetSelectedProfile(); if (profile) { ImGui::SameLine(); if (ImGui::Button("Copy from profile")) ImGui::OpenPopup("Copy from profile"); if (UICommon::ConfirmDialog( "Copy from profile", "Copy and apply all values for '%s' from profile '%s'?", a_pair.first.c_str(), profile->Name().c_str())) { if (!CopyFromSelectedProfile(a_handle, a_data, a_pair)) ImGui::OpenPopup("Copy failed"); } } UICommon::MessageDialog( "Copy failed", "Could not copy values from selected profile"); if (ImGui::BeginPopup("propagate_popup")) { DrawPropagateContextMenu(a_handle, a_data, a_pair); ImGui::EndPopup(); } ImGui::PushID("group_options"); DrawGroupOptions(a_handle, a_data, a_pair, a_nodeConfig); ImGui::PopID(); ImGui::PopID(); } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DrawPropagateContextMenu( T a_handle, configComponents_t& a_data, configComponents_t::value_type& a_entry) { auto& globalConfig = IConfig::GetGlobal(); auto& propmap = globalConfig.ui.propagate.try_emplace(ID).first->second; auto& d = propmap.try_emplace(a_entry.first).first->second; nodeConfigList_t nodeList; auto& cg = IConfig::GetConfigGroupMap(); auto& nodeConf = GetNodeData(a_handle); for (const auto& g : cg) { if (g.first == a_entry.first) continue; nodeList.clear(); GetNodeConfig(nodeConf, g, nodeList); if (!ShouldDrawComponent(a_handle, a_data, g, nodeList)) continue; auto& e = *a_data.try_emplace(g.first).first; auto i = d.try_emplace(e.first); if (ImGui::MenuItem(e.first.c_str(), nullptr, std::addressof(i.first->second.enabled))) { auto f = propmap.try_emplace(e.first); f.first->second.insert_or_assign(a_entry.first, i.first->second); DCBP::MarkGlobalsForSave(); } } if (!d.empty()) { ImGui::Separator(); if (ImGui::MenuItem("Clear")) { auto it = propmap.find(a_entry.first); for (auto& e : it->second) { e.second.enabled = false; auto f = propmap.find(e.first); if (f != propmap.end()) { auto g = f->second.find(a_entry.first); if (g != f->second.end()) g->second.enabled = false; } } //propmap.erase(a_entry.first); DCBP::MarkGlobalsForSave(); } } } template <class T, UIEditorID ID> bool UISimComponent<T, ID>::CopyFromSelectedProfile( T a_handle, configComponents_t& a_data, configComponentsValue_t& a_pair) { auto profile = GetSelectedProfile(); if (!profile) return false; auto& gcc = GetGlobalCommonConfig(); auto& data = profile->Data()(gcc.selectedGender); auto it = data.find(a_pair.first); if (it == data.end()) return false; a_pair.second = it->second; OnComponentUpdate(a_handle, a_data, a_pair); return true; } template <class T, UIEditorID ID> float UISimComponent<T, ID>::GetActualSliderValue( const armorCacheValuePair_t& a_cacheval, float a_baseval) const { switch (a_cacheval.first) { case 0: return a_cacheval.second.vf; case 1: return a_baseval * a_cacheval.second.vf; case 2: return a_baseval + a_cacheval.second.vf; default: return a_baseval; } } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DoSimSliderOnChangePropagation( configComponents_t& a_data, configComponents_t* a_dg, configComponentsValue_t& a_pair, const componentValueDescMap_t::vec_value_type& a_desc, float* a_val, bool a_sync, float a_mval) const { configPropagate_t::keyList_t keys{ std::addressof(a_desc.first) }; if (a_sync) { keys.emplace_back(std::addressof(a_desc.second.counterpart)); Propagate(a_data, a_dg, a_pair, [&](configComponent_t& a_v, const configPropagate_t& a_p) { a_v.Set(a_desc.second.counterpart, a_p.ResolveValue(keys, a_mval)); }); } Propagate(a_data, a_dg, a_pair, [&](configComponent_t& a_v, const configPropagate_t& a_p) { a_v.Set(a_desc.second, a_p.ResolveValue(keys, *a_val)); }); } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DoColliderShapeOnChangePropagation( configComponents_t& a_data, configComponents_t* a_dg, configComponentsValue_t& a_pair, const componentValueDescMap_t::vec_value_type& a_desc) const { Propagate(a_data, a_dg, a_pair, [&](configComponent_t& a_v, const configPropagate_t&) { a_v.ex.colShape = a_pair.second.ex.colShape; // a_v.ex.colMesh = a_pair.second.ex.colMesh; }); } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DoMotionConstraintOnChangePropagation( configComponents_t& a_data, configComponents_t* a_dg, configComponentsValue_t& a_pair, const componentValueDescMap_t::vec_value_type& a_desc) const { Propagate(a_data, a_dg, a_pair, [&](configComponent_t& a_v, const configPropagate_t&) { a_v.ex.motionConstraints = a_pair.second.ex.motionConstraints; }); } template <class T, UIEditorID ID> bool UISimComponent<T, ID>::DrawSlider( const componentValueDescMap_t::vec_value_type& a_entry, float* a_pValue, bool a_scalar) { if (a_scalar) return ImGui::SliderScalar( "", ImGuiDataType_Float, a_pValue, &a_entry.second.min, &a_entry.second.max, "%.3f"); else return ImGui::SliderFloat( a_entry.second.descTag.c_str(), a_pValue, a_entry.second.min, a_entry.second.max); } template <class T, UIEditorID ID> bool UISimComponent<T, ID>::DrawSlider( const componentValueDescMap_t::vec_value_type& a_entry, float* a_pValue, const armorCacheEntry_t::mapped_type* a_cacheEntry, bool a_scalar) { auto it = a_cacheEntry->find(a_entry.first); if (it == a_cacheEntry->end()) return DrawSlider(a_entry, a_pValue, a_scalar); ImGui::PushStyleColor(ImGuiCol_Text, s_colorWarning); _snprintf_s(m_scBuffer1, _TRUNCATE, "%s [%c|%.3f]", "%.3f", it->second.first == 1 ? 'M' : 'A', GetActualSliderValue(it->second, *a_pValue)); bool res; if (a_scalar) { res = ImGui::SliderScalar( "", ImGuiDataType_Float, a_pValue, &a_entry.second.min, &a_entry.second.max, m_scBuffer1); } else { res = ImGui::SliderFloat( a_entry.second.descTag.c_str(), a_pValue, a_entry.second.min, a_entry.second.max, m_scBuffer1); } ImGui::PopStyleColor(); return res; } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DrawColliderShapeCombo( T a_handle, configComponents_t& a_data, configComponentsValue_t& a_pair, const componentValueDescMap_t::vec_value_type& a_entry, const nodeConfigList_t& a_nodeList) { auto& desc = configComponent_t::colDescMap.at(a_pair.second.ex.colShape); auto& pm = GlobalProfileManager::GetSingleton<ColliderProfile>(); if (ImGui::BeginCombo("Collider shape##csc", desc.name.c_str())) { for (auto& e : configComponent_t::colDescMap) { bool selected = a_pair.second.ex.colShape == e.first; if (selected) if (ImGui::IsWindowAppearing()) ImGui::SetScrollHereY(); if (ImGui::Selectable(e.second.name.c_str(), selected)) { a_pair.second.ex.colShape = e.first; if (e.first == ColliderShapeType::Mesh) { auto it = pm.Find(a_pair.second.ex.colMesh); if (it == pm.End()) { auto& data = pm.Data(); if (!data.empty()) a_pair.second.ex.colMesh = data.begin()->first; else a_pair.second.ex.colMesh = ""; } } OnColliderShapeChange(a_handle, a_data, a_pair, a_entry); } } ImGui::EndCombo(); } HelpMarker(desc.desc); if (a_pair.second.ex.colShape == ColliderShapeType::Mesh || a_pair.second.ex.colShape == ColliderShapeType::ConvexHull) { auto& data = pm.Data(); if (a_pair.second.ex.colMesh.empty() && !data.empty()) { a_pair.second.ex.colMesh = data.begin()->first; OnColliderShapeChange(a_handle, a_data, a_pair, a_entry); } if (ImGui::BeginCombo(desc.name.c_str(), a_pair.second.ex.colMesh.c_str())) { for (const auto& e : data) { bool selected = a_pair.second.ex.colMesh == e.first; if (selected) if (ImGui::IsWindowAppearing()) ImGui::SetScrollHereY(); if (ImGui::Selectable(e.first.c_str(), selected)) { a_pair.second.ex.colMesh = e.first; OnColliderShapeChange(a_handle, a_data, a_pair, a_entry); } } ImGui::EndCombo(); } if (!a_pair.second.ex.colMesh.empty()) { auto it = data.find(a_pair.second.ex.colMesh); if (it != data.end()) { auto& pdesc = it->second.GetDescription(); if (pdesc) HelpMarker(*pdesc); } } if (HasBoneCast(a_nodeList)) { ImGui::PushStyleColor(ImGuiCol_Text, s_colorWarning); ImGui::TextWrapped("BoneCast enabled on atleast one node in this group"); ImGui::PopStyleColor(); } } } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DrawMotionConstraintSelectors( T a_handle, configComponents_t& a_data, configComponentsValue_t& a_pair, const componentValueDescMap_t::vec_value_type& a_entry) { ImGui::PushID("__mcs"); ImGui::TextWrapped("Constraint shapes: "); ImGui::SameLine(); if (ImGui::CheckboxFlags("Box", Enum::Underlying(&a_pair.second.ex.motionConstraints), Enum::Underlying(MotionConstraints::Box))) { OnMotionConstraintChange(a_handle, a_data, a_pair, a_entry); } ImGui::SameLine(); if (ImGui::CheckboxFlags("Sphere", Enum::Underlying(&a_pair.second.ex.motionConstraints), Enum::Underlying(MotionConstraints::Sphere))) { OnMotionConstraintChange(a_handle, a_data, a_pair, a_entry); } ImGui::PopID(); } template <class T, UIEditorID ID> UISimComponent<T, ID>::UISimComponent() : UIMainItemFilter<ID>(MiscHelpText::dataFilterPhys, true), m_eraseCurrent(false), m_cscStr("Collider shape"), m_csStr("Constraint shapes"), m_cicUISC("UISC"), m_cicGUISC("GUISC"), m_cicCSSID("UISC") { } template <class T, UIEditorID ID> UISimComponent<T, ID>::UISimComponent(UIMainItemFilter<ID>& a_filter) : UIMainItemFilter<ID>(a_filter), m_eraseCurrent(false), m_cscStr("Collider shape"), m_csStr("Constraint shapes"), m_cicUISC("UISC"), m_cicGUISC("GUISC"), m_cicCSSID("UISC") { } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DrawSliders( T a_handle, configComponents_t& a_data, configComponentsValue_t& a_pair, const nodeConfigList_t& a_nodeList ) { auto aoSect = GetArmorOverrideSection(a_handle, a_pair.first); bool drawingGroup(false); bool drawingFloat3(false); bool showCurrentGroup(false); bool openState(false); DescUIGroupType groupType(DescUIGroupType::None); ImGui::PushID(static_cast<const void*>(std::addressof(a_pair))); ImGui::PushItemWidth(ImGui::GetFontSize() * -14.0f); int float3Index; const componentValueDesc_t* currentDesc; auto& dm = configComponent_t::descMap.getvec(); auto count = dm.size(); for (decltype(count) i = decltype(count)(0); i < count; i++) { auto& e = dm[i]; ImGui::PushID(std::addressof(e)); auto addr = reinterpret_cast<std::uintptr_t>(std::addressof(a_pair.second)) + e.second.offset; float* pValue = reinterpret_cast<float*>(addr); if ((e.second.flags & DescUIFlags::BeginGroup) == DescUIFlags::BeginGroup) { if (e.second.groupType == DescUIGroupType::Physics || e.second.groupType == DescUIGroupType::PhysicsMotionConstraints) { showCurrentGroup = HasMotion(a_nodeList); } else if (e.second.groupType == DescUIGroupType::Collisions) { showCurrentGroup = HasCollision(a_nodeList); } else { showCurrentGroup = false; } groupType = e.second.groupType; drawingGroup = true; if (showCurrentGroup) { openState = Tree( GetCSSID(a_pair.first, e.second.groupName), e.second.groupName.c_str(), (e.second.flags & DescUIFlags::Collapsed) != DescUIFlags::Collapsed); if (openState) { if (groupType == DescUIGroupType::Collisions) { if (m_sliderFilter->Test(m_cscStr)) { DrawColliderShapeCombo(a_handle, a_data, a_pair, e, a_nodeList); } } else if (groupType == DescUIGroupType::PhysicsMotionConstraints) { if (m_sliderFilter->Test(m_csStr)) { DrawMotionConstraintSelectors(a_handle, a_data, a_pair, e); } } } } } if (!m_sliderFilter->Test(e.second.descTag)) { goto _end; } bool groupShown = (drawingGroup && openState && showCurrentGroup); if (groupShown) { if (groupType == DescUIGroupType::Collisions) { auto flags = e.second.flags & UIMARKER_COL_SHAPE_FLAGS; if (flags != DescUIFlags::None) { auto f(DescUIFlags::None); switch (a_pair.second.ex.colShape) { case ColliderShapeType::Sphere: f |= (flags & DescUIFlags::ColliderSphere); break; case ColliderShapeType::Capsule: f |= (flags & DescUIFlags::ColliderCapsule); break; case ColliderShapeType::Box: f |= (flags & DescUIFlags::ColliderBox); break; case ColliderShapeType::Cone: f |= (flags & DescUIFlags::ColliderCone); break; case ColliderShapeType::Tetrahedron: f |= (flags & DescUIFlags::ColliderTetrahedron); break; case ColliderShapeType::Cylinder: f |= (flags & DescUIFlags::ColliderCylinder); break; case ColliderShapeType::Mesh: f |= (flags & DescUIFlags::ColliderMesh); break; case ColliderShapeType::ConvexHull: f |= (flags & DescUIFlags::ColliderConvexHull); break; } if (f == DescUIFlags::None) goto _end; } } else if (groupType == DescUIGroupType::PhysicsMotionConstraints) { auto f(MotionConstraints::None); if ((e.second.flags & DescUIFlags::MotionConstraintBox) == DescUIFlags::MotionConstraintBox) { f |= (a_pair.second.ex.motionConstraints & MotionConstraints::Box); } if ((e.second.flags & DescUIFlags::MotionConstraintSphere) == DescUIFlags::MotionConstraintSphere) { f |= (a_pair.second.ex.motionConstraints & MotionConstraints::Sphere); } if (f == MotionConstraints::None) goto _end; } if ((e.second.flags & DescUIFlags::BeginSubGroup) == DescUIFlags::BeginSubGroup) { ImGui::TextWrapped(e.second.subGroupName.c_str()); ImGui::Indent(); } } if (!drawingGroup || groupShown) { if (!drawingFloat3 && (e.second.flags & DescUIFlags::Float3) == DescUIFlags::Float3) { currentDesc = std::addressof(e.second); float3Index = 0; drawingFloat3 = true; ImGui::PushID(std::addressof(currentDesc->descTag)); if ((e.second.flags & DescUIFlags::Float3Mirror) == DescUIFlags::Float3Mirror) { ImGui::PushID(static_cast<const void*>(currentDesc)); if (ImGui::Button("+")) ImGui::OpenPopup("__slider_opts"); DrawSliderContextMenu(std::addressof(e), a_pair); ImGui::PopID(); ImGui::SameLine(0, GImGui->Style.ItemInnerSpacing.x); } ImGui::BeginGroup(); ImGui::PushMultiItemsWidths(3, ImGui::CalcItemWidth()); } if (drawingFloat3) { ImGuiContext& g = *GImGui; ImGui::PushID(float3Index); if (float3Index > 0) ImGui::SameLine(0, g.Style.ItemInnerSpacing.x); bool changed = aoSect ? DrawSlider(e, pValue, aoSect, true) : ImGui::SliderScalar("##float3_slider", ImGuiDataType_Float, pValue, &e.second.min, &e.second.max, "%.3f"); ImGui::PopID(); ImGui::PopItemWidth(); if (changed) OnSimSliderChange(a_handle, a_data, a_pair, e, pValue); float3Index++; if (float3Index == 3) { ImGui::PopID(); auto desc_text = currentDesc->descTag.c_str(); auto label_end = ImGui::FindRenderedTextEnd(desc_text); if (desc_text != label_end) { ImGui::SameLine(0, g.Style.ItemInnerSpacing.x); ImGui::TextEx(desc_text, label_end); } ImGui::EndGroup(); HelpMarker(currentDesc->helpText); drawingFloat3 = false; } } else { bool changed = aoSect ? DrawSlider(e, pValue, aoSect, false) : ImGui::SliderFloat(e.second.descTag.c_str(), pValue, e.second.min, e.second.max); if (changed) OnSimSliderChange(a_handle, a_data, a_pair, e, pValue); HelpMarker(e.second.helpText); } } if (groupShown) { if ((e.second.flags & DescUIFlags::EndSubGroup) == DescUIFlags::EndSubGroup) { ImGui::Unindent(); } } _end:; if ((e.second.flags & DescUIFlags::EndGroup) == DescUIFlags::EndGroup) { if (openState) { ImGui::TreePop(); openState = false; } drawingGroup = false; groupType = DescUIGroupType::None; } ImGui::PopID(); } ImGui::PopItemWidth(); ImGui::PopID(); } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DrawSliderContextMenu( const componentValueDescMap_t::vec_value_type* a_desc, const configComponentsValue_t& a_pair) const { if (ImGui::BeginPopup("__slider_opts")) { auto& globalConfig = IConfig::GetGlobal(); auto& propmap = globalConfig.ui.propagate[ID]; auto it = propmap.find(a_pair.first); if (it != propmap.end()) { if (ImGui::BeginMenu("Mirror")) { bool has_one(false); ImGui::PushID(static_cast<const void*>(std::addressof(it->second))); for (auto& e : it->second) { if (!e.second.enabled) continue; has_one = true; if (!ImGui::BeginMenu(e.first.c_str())) continue; ImGui::PushID(static_cast<const void*>(std::addressof(e))); DrawSliderContextMenuMirrorItem("X", a_desc, e, a_pair, propmap); DrawSliderContextMenuMirrorItem("Y", a_desc + 1, e, a_pair, propmap); DrawSliderContextMenuMirrorItem("Z", a_desc + 2, e, a_pair, propmap); ImGui::PopID(); ImGui::EndMenu(); } ImGui::PopID(); if (!has_one) { ImGui::MenuItem("Propagation disabled", nullptr, false, false); } ImGui::EndMenu(); } } else { ImGui::MenuItem("Propagation disabled", nullptr, false, false); } ImGui::EndPopup(); } } template <class T, UIEditorID ID> void UISimComponent<T, ID>::DrawSliderContextMenuMirrorItem( const char* a_label, const componentValueDescMap_t::vec_value_type* a_desc, configPropagateEntry_t::value_type& a_propEntry, const configComponentsValue_t& a_pair, configPropagateMap_t& a_propMap) const { auto it = a_propEntry.second.mirror.find(a_desc->first); bool selected = it != a_propEntry.second.mirror.end(); if (ImGui::MenuItem(a_label, nullptr, selected)) { if (selected) { a_propEntry.second.mirror.erase(it); } else { a_propEntry.second.mirror.emplace(a_desc->first); } auto f = a_propMap.try_emplace(a_propEntry.first); f.first->second.insert_or_assign(a_pair.first, a_propEntry.second); } } template <class T, UIEditorID ID> bool UISimComponent<T, ID>::ShouldDrawComponent( T, configComponents_t&, const configGroupMap_t::value_type&, const nodeConfigList_t&) const { return true; } template <class T, UIEditorID ID> bool UISimComponent<T, ID>::HasMotion( const nodeConfigList_t&) const { return true; } template <class T, UIEditorID ID> bool UISimComponent<T, ID>::HasCollision( const nodeConfigList_t&) const { return true; } template <class T, UIEditorID ID> bool UISimComponent<T, ID>::HasBoneCast( const nodeConfigList_t&) const { return false; } template <class T, UIEditorID ID> const armorCacheEntry_t::mapped_type* UISimComponent<T, ID>::GetArmorOverrideSection( T m_handle, const stl::fixed_string& a_comp) const { return nullptr; } }
32.027484
145
0.50066
clayne
493cba69db4dd39e04d0e0ecda6753a61bd40570
20,992
cpp
C++
src/read.cpp
johelegp/tmxpp
efbd52e575fb8cd8fcfebd274b379f11fc036637
[ "Unlicense" ]
null
null
null
src/read.cpp
johelegp/tmxpp
efbd52e575fb8cd8fcfebd274b379f11fc036637
[ "Unlicense" ]
null
null
null
src/read.cpp
johelegp/tmxpp
efbd52e575fb8cd8fcfebd274b379f11fc036637
[ "Unlicense" ]
1
2018-03-12T02:32:46.000Z
2018-03-12T02:32:46.000Z
#include <optional> #include <string> #include <utility> #include <tmxpp.hpp> #include <tmxpp/Constrained.hpp> #include <tmxpp/exceptions.hpp> #include <tmxpp/impl/Xml.hpp> #include <tmxpp/impl/exceptions.hpp> #include <tmxpp/impl/read_utility.hpp> #include <tmxpp/impl/tmx_info.hpp> #include <tmxpp/impl/to_color.hpp> #include <tmxpp/impl/to_data_flipped_id.hpp> #include <tmxpp/impl/to_point.hpp> namespace tmxpp { namespace impl { namespace { using namespace tmx_info; iSize read_isize(Xml::Element element) { return {from_string<iSize::Dimension>(value(element, size_width)), from_string<iSize::Dimension>(value(element, size_height))}; } std::optional<pxSize> read_optional_size(Xml::Element element) { auto w{optional_value(element, size_width)}; auto h{optional_value(element, size_height)}; if (bool{w} != bool{h}) throw Exception{"Expected both " + std::string{get(size_width)} + " and " + std::string{get(size_height)} + ", or none."}; if (!w) return {}; return pxSize{from_string<pxSize::Dimension>(*w), from_string<pxSize::Dimension>(*h)}; } pxSize read_tile_size(Xml::Element element) { return {from_string<pxSize::Dimension>(value(element, tile_size_width)), from_string<pxSize::Dimension>(value(element, tile_size_height))}; } namespace properties { Property::Value read_value(Xml::Element property) { auto value{optional_value(property, property_value)}; if (!value) return std::string{get(property.value())}; auto alternative{optional_value(property, property_alternative)}; if (!alternative || *alternative == property_alternative_string) return std::string{get(*value)}; if (*alternative == property_alternative_int) return from_string<int>(*value); if (*alternative == property_alternative_double) return from_string<double>(*value); if (*alternative == property_alternative_bool) { if (*value == property_value_true) return true; if (*value == property_value_false) return false; throw Exception{"Bad property bool value: " + std::string{get(*value)}}; } if (*alternative == property_alternative_color) return to_color(*value); if (*alternative == property_alternative_file) return File{get(*value)}; throw Invalid_attribute{property_alternative, *alternative}; } Non_empty<std::string> read_name(Xml::Element property) { return Non_empty<std::string>{ std::string{get(value(property, property_name))}}; } Property read_property(Xml::Element property) { return {read_name(property), read_value(property)}; } Properties read_properties(Xml::Element element) { auto properties{element.optional_child(tmx_info::properties)}; if (!properties) return {}; return transform<Properties>(properties->children(property), read_property); } } // namespace properties using properties::read_properties; namespace image { File read_source(Xml::Element image) { return get(value(image, image_source)); } std::optional<Color> read_transparent(Xml::Element image) { if (auto color{optional_value(image, image_transparent)}) return to_color(*color); return {}; } Image read_image(Xml::Element image) { return {read_source(image), read_transparent(image), read_optional_size(image)}; } } // namespace image using image::read_image; namespace animation { Local_tile_id read_id(Xml::Element frame) { return from_string<Local_tile_id>(value(frame, frame_id)); } Non_negative<Frame::Duration> read_duration(Xml::Element frame) { return Non_negative<Frame::Duration>{Frame::Duration{ from_string<Frame::Duration::rep>(value(frame, frame_duration))}}; } Frame read_frame(Xml::Element frame) { return {read_id(frame), read_duration(frame)}; } Animation read_animation(Xml::Element tile) { auto animation{tile.optional_child(tmx_info::animation)}; if (!animation) return {}; return transform<Animation>(animation->children(frame), read_frame); } } // namespace animation using animation::read_animation; namespace object_layer { Object_layer read_object_layer(Xml::Element object_layer); } // namespace object_layer using object_layer::read_object_layer; namespace tile_set { Global_tile_id read_first_id(Xml::Element tile_set) { return from_string<Global_tile_id>(value(tile_set, tile_set_first_id)); } File read_tsx(Xml::Element tile_set) { if (auto tsx{optional_value(tile_set, tile_set_tsx)}) return get(*tsx); return {}; } std::string read_name(Xml::Element tile_set) { if (auto name{optional_value(tile_set, tile_set_name)}) return std::string{get(*name)}; return {}; } Non_negative<int> read_tile_count(Xml::Element tile_set) { return Non_negative<int>{ from_string<int>(value(tile_set, tile_set_tile_count))}; } Non_negative<int> read_columns(Xml::Element tile_set) { return Non_negative<int>{ from_string<int>(value(tile_set, tile_set_columns))}; } Offset read_tile_offset(Xml::Element tile_set) { auto tile_offset{tile_set.optional_child(tmx_info::tile_offset)}; if (!tile_offset) return {}; return {from_string<Pixels>(value(*tile_offset, tile_offset_x)), from_string<Pixels>(value(*tile_offset, tile_offset_y))}; } Local_tile_id read_tile_id(Xml::Element tile) { return from_string<Local_tile_id>(value(tile, tile_set_tile_id)); } std::optional<Object_layer> read_tile_collision_shape(Xml::Element tile) { if (auto collision_shape{tile.optional_child(tmx_info::object_layer)}) return read_object_layer(*collision_shape); return {}; } namespace tile_set { Non_negative<Pixels> read_spacing(Xml::Element tile_set) { auto spacing{optional_value(tile_set, tile_set_spacing)}; return Non_negative<Pixels>{spacing ? from_string<Pixels>(*spacing) : Pixels{}}; } Non_negative<Pixels> read_margin(Xml::Element tile_set) { auto margin{optional_value(tile_set, tile_set_margin)}; return Non_negative<Pixels>{margin ? from_string<Pixels>(*margin) : Pixels{}}; } iSize read_size(Xml::Element tile_set) { auto tile_count{*read_tile_count(tile_set)}; auto columns{*read_columns(tile_set)}; if (columns == 0) throw Exception{"Invalid tile set columns value: 0"}; return {iSize::Dimension{columns}, iSize::Dimension{tile_count / columns}}; } Tile_set::Tile read_tile(Xml::Element tile) { return {read_tile_id(tile), read_properties(tile), read_tile_collision_shape(tile), read_animation(tile)}; } Tile_set::Tiles read_tiles(Xml::Element tile_set) { return transform<Tile_set::Tiles>( tile_set.children(tile_set_tile), read_tile); } Tile_set read_tile_set(Xml::Element tile_set, Global_tile_id first_id, File tsx) { return {first_id, std::move(tsx), read_name(tile_set), read_tile_size(tile_set), read_spacing(tile_set), read_margin(tile_set), read_size(tile_set), read_tile_offset(tile_set), read_properties(tile_set), read_image(tile_set.child(tmx_info::image)), read_tiles(tile_set)}; } } // namespace tile_set namespace image_collection { Image_collection::Tile read_tile(Xml::Element tile) { return {read_tile_id(tile), read_properties(tile), read_image(tile.child(tmx_info::image)), read_tile_collision_shape(tile), read_animation(tile)}; } Image_collection::Tiles read_tiles(Xml::Element image_collection) { return transform<Image_collection::Tiles>( image_collection.children(tile_set_tile), read_tile); } Image_collection read_image_collection( Xml::Element image_collection, Global_tile_id first_id, File tsx) { return {first_id, std::move(tsx), read_name(image_collection), read_tile_size(image_collection), read_tile_count(image_collection), read_columns(image_collection), read_tile_offset(image_collection), read_properties(image_collection), read_tiles(image_collection)}; } } // namespace image_collection // Requires: The tile set is internal or a TSX. // Returns: `true` if the `Element` represents a `Tile_set`, and `false` if it // represents an `Image_collection`. bool is_tile_set(Xml::Element tile_set) { return bool{tile_set.optional_child(tmx_info::image)}; } Map::Tile_set read_map_tile_set( Xml::Element tile_set, const std::experimental::filesystem::path& tsx_base) { auto first_id{read_first_id(tile_set)}; auto tsx{read_tsx(tile_set)}; if (tsx.empty()) { if (is_tile_set(tile_set)) return tile_set::read_tile_set(tile_set, first_id, tsx); return image_collection::read_image_collection(tile_set, first_id, tsx); } return read_tsx(first_id, std::move(tsx), tsx_base); } } // namespace tile_set using tile_set::tile_set::read_tile_set; using tile_set::image_collection::read_image_collection; using tile_set::read_map_tile_set; namespace data { Data::Encoding read_encoding(Xml::Element data) { auto encoding{value(data, data_encoding)}; if (encoding == data_encoding_csv) return Data::Encoding::csv; if (encoding == data_encoding_base64) return Data::Encoding::base64; throw Invalid_attribute{data_encoding, encoding}; } Data::Compression read_compression(Xml::Element data) { auto compression{optional_value(data, data_compression)}; if (!compression) return Data::Compression::none; if (*compression == data_compression_zlib) return Data::Compression::zlib; throw Invalid_attribute{data_compression, *compression}; } Data::Format read_format(Xml::Element data) { return {read_encoding(data), read_compression(data)}; } Data::Flipped_ids read_ids(Data::Format format, Xml::Element::Value data) { if (format != Data::Encoding::csv) throw Exception{"Can only handle csv-encoded data."}; return transform<Data::Flipped_ids>( tokenize(get(data), ",\n"), to_data_flipped_id); } Data read_data(Xml::Element data) { auto format{read_format(data)}; return {format, read_ids(format, data.value())}; } } // namespace data using data::read_data; namespace layer { std::string read_name(Xml::Element layer) { if (auto name{optional_value(layer, layer_name)}) return std::string{get(*name)}; return {}; } Unit_interval read_opacity(Xml::Element layer) { if (auto opacity{optional_value(layer, layer_opacity)}) return from_string<Unit_interval>(*opacity); return Unit_interval{1}; } bool read_visible(Xml::Element layer) { if (auto visible{optional_value(layer, layer_visible)}) return from_string<bool>(*visible); return true; } Offset read_offset(Xml::Element layer) { auto x{optional_value(layer, offset_x)}; auto y{optional_value(layer, offset_y)}; return {x ? from_string<Pixels>(*x) : Pixels{0}, y ? from_string<Pixels>(*y) : Pixels{0}}; } Layer read_layer(Xml::Element layer) { return {read_name(layer), read_opacity(layer), read_visible(layer), read_offset(layer), read_properties(layer)}; } } // namespace layer using layer::read_layer; namespace tile_layer { Tile_layer read_tile_layer(Xml::Element tile_layer) { return {read_layer(tile_layer), read_isize(tile_layer), read_data(tile_layer.child(tmx_info::data))}; } } // namespace tile_layer using tile_layer::read_tile_layer; namespace object { Unique_id read_unique_id(Xml::Element object) { return from_string<Unique_id>(value(object, object_unique_id)); } std::string read_name(Xml::Element object) { if (auto name{optional_value(object, object_name)}) return std::string{get(*name)}; return {}; } std::string read_type(Xml::Element object) { if (auto type{optional_value(object, object_type)}) return std::string{get(*type)}; return {}; } Point read_position(Xml::Element object) { return {from_string<Point::Coordinate>(value(object, point_x)), from_string<Point::Coordinate>(value(object, point_y))}; } Object::Polygon::Points read_points(Xml::Element poly) { return transform<Object::Polygon::Points>( tokenize(get(value(poly, object_polygon_points)), " "), to_point); } std::optional<Object::Shape> read_shape(Xml::Element object) { if (auto polyline{object.optional_child(object_polyline)}) return Object::Polyline{read_points(*polyline)}; if (auto polygon{object.optional_child(object_polygon)}) return Object::Polygon{read_points(*polygon)}; auto size{read_optional_size(object)}; if (!size) return {}; if (object.optional_child(object_ellipse)) return Object::Ellipse{*size}; return Object::Rectangle{*size}; } Degrees read_clockwise_rotation(Xml::Element object) { if (auto rotation{optional_value(object, object_clockwise_rotation)}) return from_string<Degrees>(*rotation); return {}; } std::optional<Global_tile_id> read_global_id(Xml::Element object) { if (auto global_id{optional_value(object, object_global_id)}) return from_string<Global_tile_id>(*global_id); return {}; } bool read_visible(Xml::Element object) { return layer::read_visible(object); } Object read_object(Xml::Element object) { return {read_unique_id(object), read_name(object), read_type(object), read_position(object), read_shape(object), read_clockwise_rotation(object), read_global_id(object), read_visible(object), read_properties(object)}; } } // namespace object using object::read_object; namespace object_layer { std::optional<Color> read_color(Xml::Element object_layer) { if (auto color{optional_value(object_layer, object_layer_color)}) return to_color(*color); return {}; } Object_layer::Draw_order read_draw_order(Xml::Element object_layer) { auto draw_order{optional_value(object_layer, object_layer_draw_order)}; if (!draw_order || *draw_order == object_layer_draw_order_top_down) return Object_layer::Draw_order::top_down; if (*draw_order == object_layer_draw_order_index) return Object_layer::Draw_order::index; throw Invalid_attribute{object_layer_draw_order, *draw_order}; } Object_layer::Objects read_objects(Xml::Element object_layer) { return transform<Object_layer::Objects>( object_layer.children(tmx_info::object), read_object); } Object_layer read_object_layer(Xml::Element object_layer) { return {read_layer(object_layer), read_color(object_layer), read_draw_order(object_layer), read_objects(object_layer)}; } } // namespace object_layer namespace image_layer { std::optional<Image> read_image(Xml::Element image_layer) { if (auto image{image_layer.optional_child(tmx_info::image)}) return impl::read_image(*image); return {}; } Image_layer read_image_layer(Xml::Element image_layer) { return {read_layer(image_layer), read_image(image_layer)}; } } // namespace image_layer using image_layer::read_image_layer; namespace map { std::string read_version(Xml::Element map) { return std::string{get(value(map, map_version))}; } Map::Staggered::Axis read_axis(Xml::Element map) { auto axis{value(map, map_staggered_axis)}; if (axis == map_staggered_axis_x) return Map::Staggered::Axis::x; if (axis == map_staggered_axis_y) return Map::Staggered::Axis::y; throw Invalid_attribute{map_staggered_axis, axis}; } Map::Staggered::Index read_index(Xml::Element map) { auto index{value(map, map_staggered_index)}; if (index == map_staggered_index_even) return Map::Staggered::Index::even; if (index == map_staggered_index_odd) return Map::Staggered::Index::odd; throw Invalid_attribute{map_staggered_index, index}; } Pixels read_side_length(Xml::Element map) { return from_string<Pixels>(value(map, map_hexagonal_side_legth)); } Map::Orientation read_orientation(Xml::Element map) { auto orientation{value(map, map_orientation)}; if (orientation == map_orthogonal) return Map::Orthogonal{}; if (orientation == map_isometric) return Map::Isometric{}; if (orientation == map_staggered) return Map::Staggered{read_axis(map), read_index(map)}; if (orientation == map_hexagonal) return Map::Hexagonal{read_axis(map), read_index(map), read_side_length(map)}; throw Invalid_attribute{map_orientation, orientation}; } Map::Render_order read_render_order(Xml::Element map) { auto render_order{optional_value(map, map_render_order)}; if (!render_order || *render_order == map_render_order_right_down) return Map::Render_order::right_down; if (*render_order == map_render_order_right_up) return Map::Render_order::right_up; if (*render_order == map_render_order_left_down) return Map::Render_order::left_down; if (*render_order == map_render_order_left_up) return Map::Render_order::left_up; throw Invalid_attribute{map_render_order, *render_order}; } std::optional<Color> read_background(Xml::Element map) { if (auto color{optional_value(map, map_background)}) return to_color(*color); return {}; } Unique_id read_next_id(Xml::Element map) { return from_string<Unique_id>(value(map, map_next_id)); } Map::Tile_sets read_tile_sets( Xml::Element map, const std::experimental::filesystem::path& tsx_base) { return transform<Map::Tile_sets>( map.children(tmx_info::tile_set), [&](Xml::Element tile_set) { return read_map_tile_set(tile_set, tsx_base); }); } Map::Layer read_layer(Xml::Element layer) { auto name{layer.name()}; if (name == tmx_info::tile_layer) return read_tile_layer(layer); if (name == tmx_info::object_layer) return read_object_layer(layer); if (name == tmx_info::image_layer) return read_image_layer(layer); throw Invalid_element{name}; } Map::Layers read_layers(Xml::Element map) { return transform<Map::Layers>( children( map, {tmx_info::tile_layer, tmx_info::object_layer, tmx_info::image_layer}), read_layer); } Map read_map( Xml::Element map, const std::experimental::filesystem::path& tsx_base) { return { read_version(map), read_orientation(map), read_render_order(map), read_isize(map), read_tile_size(map), read_background(map), read_next_id(map), read_properties(map), read_tile_sets(map, tsx_base), read_layers(map)}; } } // namespace map using map::read_map; } // namespace } // namespace impl Map read_tmx(const std::experimental::filesystem::path& path) try { const impl::Xml tmx{path.string().c_str()}; auto map{tmx.root()}; if (map.name() == impl::tmx_info::map) return impl::read_map(map, path.parent_path()); throw impl::Invalid_element{map.name()}; } catch (const Invalid_argument& e) { throw Exception{e.what()}; } Map::Tile_set read_tsx( Global_tile_id first_id, File tsx, const std::experimental::filesystem::path& base) try { const impl::Xml xml{absolute(tsx, base).string().c_str()}; auto tile_set{xml.root()}; if (tile_set.name() != impl::tmx_info::tile_set) throw impl::Invalid_element{tile_set.name()}; if (impl::tile_set::is_tile_set(tile_set)) return impl::read_tile_set(tile_set, first_id, std::move(tsx)); return impl::read_image_collection(tile_set, first_id, std::move(tsx)); } catch (const Invalid_argument& e) { throw Exception{e.what()}; } Tile_set read_tile_set( Global_tile_id first_id, File tsx, const std::experimental::filesystem::path& base) try { const impl::Xml xml{absolute(tsx, base).string().c_str()}; auto tile_set{xml.root()}; if (tile_set.name() == impl::tmx_info::tile_set) return impl::read_tile_set(tile_set, first_id, std::move(tsx)); throw impl::Invalid_element{tile_set.name()}; } catch (const Invalid_argument& e) { throw Exception{e.what()}; } Image_collection read_image_collection( Global_tile_id first_id, File tsx, const std::experimental::filesystem::path& base) try { const impl::Xml xml{absolute(tsx, base).string().c_str()}; auto image_collection{xml.root()}; if (image_collection.name() == impl::tmx_info::tile_set) return impl::read_image_collection( image_collection, first_id, std::move(tsx)); throw impl::Invalid_element{image_collection.name()}; } catch (const Invalid_argument& e) { throw Exception{e.what()}; } } // namespace tmxpp
26.878361
80
0.696361
johelegp
493e58662abd643a58435769c9eeb6a94210dd76
1,825
hpp
C++
sprig/checksum_hasher.hpp
bolero-MURAKAMI/Sprig
51ce4db4f4d093dee659a136f47249e4fe91fc7a
[ "BSL-1.0" ]
2
2017-10-24T13:56:24.000Z
2018-09-28T13:21:22.000Z
sprig/checksum_hasher.hpp
bolero-MURAKAMI/Sprig
51ce4db4f4d093dee659a136f47249e4fe91fc7a
[ "BSL-1.0" ]
null
null
null
sprig/checksum_hasher.hpp
bolero-MURAKAMI/Sprig
51ce4db4f4d093dee659a136f47249e4fe91fc7a
[ "BSL-1.0" ]
2
2016-04-12T03:26:06.000Z
2018-09-28T13:21:22.000Z
/*============================================================================= Copyright (c) 2010-2016 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprig 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 SPRIG_CHECKSUM_HASHER_HPP #define SPRIG_CHECKSUM_HASHER_HPP #include <sprig/config/config.hpp> #ifdef SPRIG_USING_PRAGMA_ONCE # pragma once #endif // #ifdef SPRIG_USING_PRAGMA_ONCE #include <cstddef> #include <boost/range.hpp> #include <boost/foreach.hpp> namespace sprig { // // checksum_hasher // template<typename Checksum, std::size_t BlockSize = 64> class checksum_hasher { public: typedef Checksum checksum_type; typedef std::size_t size_type; typedef typename checksum_type::value_type value_type; public: static size_type const block_size = BlockSize; public: template<typename Pointer> static value_type calculate_block(Pointer first, Pointer last) { checksum_type checksum; checksum.process_block(first, last); return checksum.checksum(); } template<typename Pointer> static value_type calculate_bytes(Pointer data, size_type size) { checksum_type checksum; checksum.process_bytes(data, size); return checksum.checksum(); } template<typename Range> static value_type calculate(Range const& range) { checksum_type checksum; BOOST_FOREACH(typename boost::range_value<Range>::type e, range) { checksum.process_byte(e); } return checksum.checksum(); } public: template<typename Range> value_type operator()(Range const& range) const { return calculate(range); } }; } // namespace sprig #endif // #ifndef SPRIG_CHECKSUM_HASHER_HPP
28.968254
79
0.691507
bolero-MURAKAMI
4947a082aa63736a73cbf92410fe463e080e81df
5,858
cc
C++
chrome/browser/android/vr/gvr_input_delegate.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/android/vr/gvr_input_delegate.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/android/vr/gvr_input_delegate.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/android/vr/gvr_input_delegate.h" #include <utility> #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/android/vr/vr_controller.h" #include "chrome/browser/vr/input_event.h" #include "chrome/browser/vr/model/controller_model.h" #include "chrome/browser/vr/pose_util.h" #include "chrome/browser/vr/render_info.h" #include "device/vr/android/gvr/gvr_delegate.h" namespace { constexpr gfx::Vector3dF kForwardVector = {0.0f, 0.0f, -1.0f}; } namespace vr { GvrInputDelegate::GvrInputDelegate(gvr::GvrApi* gvr_api) : controller_(std::make_unique<VrController>(gvr_api)), gvr_api_(gvr_api) {} GvrInputDelegate::~GvrInputDelegate() = default; gfx::Transform GvrInputDelegate::GetHeadPose() { gfx::Transform head_pose; device::GvrDelegate::GetGvrPoseWithNeckModel(gvr_api_, &head_pose); return head_pose; } void GvrInputDelegate::OnTriggerEvent(bool pressed) { NOTREACHED(); } void GvrInputDelegate::UpdateController(const gfx::Transform& head_pose, base::TimeTicks current_time, bool is_webxr_frame) { controller_->UpdateState(head_pose); } ControllerModel GvrInputDelegate::GetControllerModel( const gfx::Transform& head_pose) { gfx::Vector3dF head_direction = GetForwardVector(head_pose); gfx::Vector3dF controller_direction; gfx::Quaternion controller_quat; if (!controller_->IsConnected()) { // No controller detected, set up a gaze cursor that tracks the forward // direction. controller_direction = kForwardVector; controller_quat = gfx::Quaternion(kForwardVector, head_direction); } else { controller_direction = {0.0f, -sin(kErgoAngleOffset), -cos(kErgoAngleOffset)}; controller_quat = controller_->Orientation(); } gfx::Transform(controller_quat).TransformVector(&controller_direction); ControllerModel controller_model; controller_->GetTransform(&controller_model.transform); controller_model.touchpad_button_state = ControllerModel::ButtonState::kUp; DCHECK(!(controller_->ButtonUpHappened(PlatformController::kButtonSelect) && controller_->ButtonDownHappened(PlatformController::kButtonSelect))) << "Cannot handle a button down and up event within one frame."; if (controller_->ButtonState(gvr::kControllerButtonClick)) { controller_model.touchpad_button_state = ControllerModel::ButtonState::kDown; } controller_model.app_button_state = controller_->ButtonState(gvr::kControllerButtonApp) ? ControllerModel::ButtonState::kDown : ControllerModel::ButtonState::kUp; controller_model.home_button_state = controller_->ButtonState(gvr::kControllerButtonHome) ? ControllerModel::ButtonState::kDown : ControllerModel::ButtonState::kUp; controller_model.opacity = controller_->GetOpacity(); controller_model.laser_direction = controller_direction; controller_model.laser_origin = controller_->GetPointerStart(); controller_model.handedness = controller_->GetHandedness(); controller_model.recentered = controller_->GetRecentered(); controller_model.touching_touchpad = controller_->IsTouchingTrackpad(); controller_model.touchpad_touch_position = controller_->GetPositionInTrackpad(); controller_model.last_orientation_timestamp = controller_->GetLastOrientationTimestamp(); controller_model.last_button_timestamp = controller_->GetLastButtonTimestamp(); controller_model.battery_level = controller_->GetBatteryLevel(); return controller_model; } InputEventList GvrInputDelegate::GetGestures(base::TimeTicks current_time) { if (!controller_->IsConnected()) return {}; return gesture_detector_.DetectGestures(*controller_, current_time); } device::mojom::XRInputSourceStatePtr GvrInputDelegate::GetInputSourceState() { device::mojom::XRInputSourceStatePtr state = device::mojom::XRInputSourceState::New(); state->description = device::mojom::XRInputSourceDescription::New(); // Only one controller is supported, so the source id can be static. state->source_id = 1; // It's a handheld pointing device. state->description->target_ray_mode = device::mojom::XRTargetRayMode::POINTING; // Controller uses an arm model. state->emulated_position = true; if (controller_->IsConnected()) { // Set the primary button state. bool select_button_down = controller_->IsButtonDown(PlatformController::kButtonSelect); state->primary_input_pressed = select_button_down; state->primary_input_clicked = was_select_button_down_ && !select_button_down; was_select_button_down_ = select_button_down; // Set handedness. state->description->handedness = controller_->GetHandedness() == ControllerModel::Handedness::kRightHanded ? device::mojom::XRHandedness::RIGHT : device::mojom::XRHandedness::LEFT; // Get the grip transform gfx::Transform grip; controller_->GetTransform(&grip); state->mojo_from_input = grip; // Set the pointer offset from the grip transform. gfx::Transform pointer; controller_->GetRelativePointerTransform(&pointer); state->description->input_from_pointer = pointer; state->description->profiles.push_back("google-daydream"); // This Gamepad data is used to expose touchpad position to WebXR. state->gamepad = controller_->GetGamepadData(); } return state; } void GvrInputDelegate::OnResume() { controller_->OnResume(); } void GvrInputDelegate::OnPause() { controller_->OnPause(); } } // namespace vr
36.160494
80
0.738307
sarang-apps
49486476ec04e8609dde422d5a6cdbe4a636ec58
4,000
cpp
C++
src/Controller/BranchAccountController/CPP/BranchAccountController.cpp
sidphbot/Bank-Management-System
665db860e46e897ab77c7a30145b09e13228614c
[ "Apache-2.0" ]
1
2021-04-01T12:54:13.000Z
2021-04-01T12:54:13.000Z
src/Controller/BranchAccountController/CPP/BranchAccountController.cpp
sidphbot/Bank-Management-System
665db860e46e897ab77c7a30145b09e13228614c
[ "Apache-2.0" ]
null
null
null
src/Controller/BranchAccountController/CPP/BranchAccountController.cpp
sidphbot/Bank-Management-System
665db860e46e897ab77c7a30145b09e13228614c
[ "Apache-2.0" ]
null
null
null
#include "../Include/BranchAccountController.h" //#include "../../../Model/Include/Model.h" //#include "../../../UI/BranchAccountUI/Include/BranchAccountUI.h" int BranchAccountController::initiateBranchAccountAddition(BranchAccountUI &p_UI,Bank &p_db) { long int l_branchId; double l_branchThreshold; double l_currentBalance; l_branchId=p_UI.getBranchID(); if(l_branchId==2) { return 0; } //cout<<"b id = "<<l_branchId; l_branchThreshold=p_UI.getBranchThreshold(); if(l_branchThreshold==2) { return 0; } l_currentBalance=p_UI.getCurrentBalance(); if(l_currentBalance==2) { return 0; } BranchAccount l_tempBranchAccount; l_tempBranchAccount.setBranchId(l_branchId); l_tempBranchAccount.setBranchThreshold( l_branchThreshold); l_tempBranchAccount.setCurrentBalance( l_currentBalance); long int l_branchAccountNumber =p_db.addBranchAccount(l_tempBranchAccount); p_UI.displayAccountNo(l_branchAccountNumber); return 1; } int BranchAccountController::initiateBranchAccountView(BranchAccountUI &p_UI,Bank &p_db) { long int l_branchAccountNumber = p_UI.getBranchAccountNo(); if(l_branchAccountNumber==2) { return 0; } if(p_db.findBranchAccount(l_branchAccountNumber) == 0) { cout<<"Account not found"; return 0; } BranchAccount l_tempBranchAccount = p_db.viewBranchAccount(l_branchAccountNumber); cout<<l_tempBranchAccount.getBranchAccountNo(); p_UI.display(l_tempBranchAccount); return 1; } int BranchAccountController::initiateBranchAccountUpdation(BranchAccountUI &p_UI,Bank &p_db) { int l_status; long int l_branchId; double l_branchThreshold; double l_currentBalance; long int l_branchAccountNumber; l_branchAccountNumber=p_UI.getBranchAccountNo(); if(l_branchAccountNumber==2) { return 0; } if(p_db.findBranchAccount(l_branchAccountNumber) ==0) { cout<<"Account not found"; return 0; } BranchAccount l_tempBranchAccount=p_db.viewBranchAccount(l_branchAccountNumber); int l_choice=p_UI.displayUpdateOptions(); BranchAccount l_tempBranchAccount1; switch(l_choice) { case 1:l_branchId=p_UI.getNewBranchId(l_tempBranchAccount); l_tempBranchAccount.setBranchId(l_branchId); l_status=p_db.updateBranchID(l_tempBranchAccount); l_tempBranchAccount1 = p_db.viewBranchAccount(l_branchAccountNumber); p_UI.display(l_tempBranchAccount1); return l_status; case 2:l_branchThreshold=p_UI.getNewBranchThreshold(l_tempBranchAccount); l_tempBranchAccount.setBranchThreshold(l_branchThreshold); l_status=p_db.updateBranchThreshold(l_tempBranchAccount); l_tempBranchAccount1 = p_db.viewBranchAccount(l_branchAccountNumber); p_UI.display(l_tempBranchAccount1); return l_status; case 3:l_currentBalance=p_UI.getNewCurrentBalance(l_tempBranchAccount); l_tempBranchAccount.setCurrentBalance(l_currentBalance); l_status=p_db.updateCurrentBalance(l_tempBranchAccount); l_tempBranchAccount1 = p_db.viewBranchAccount(l_branchAccountNumber); p_UI.display(l_tempBranchAccount1); return l_status; } return 0; } int BranchAccountController::initiateBranchAccountDeletion(BranchAccountUI &p_UI,Bank &p_db) { long int l_branchAccountNumber = p_UI.getBranchAccountNo(); if(l_branchAccountNumber==2) { return 0; } if(p_db.findBranchAccount(l_branchAccountNumber) == 0) return 0; int l_status = p_db.deleteBranchAccount(l_branchAccountNumber); return l_status; } void BranchAccountController::initiateViewAllBranchAccount(BranchAccountUI &p_UI,Bank &p_db) { vector<BranchAccount> ViewList; ViewList = p_db.ViewAllBranchAccount(); if(ViewList.size()!=0) p_UI .display(ViewList); else cout<<"\n\nRecord not Found........"; }
30.075188
95
0.72275
sidphbot
494a570c53b95b59524070539d9382776ee25c9e
33,440
cpp
C++
src/modules/SD2/scripts/kalimdor/silithus.cpp
muscnx/Mangos021SD2
695bb6a4822bb9173ab8e9077cb6259869ca2f32
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
src/modules/SD2/scripts/kalimdor/silithus.cpp
muscnx/Mangos021SD2
695bb6a4822bb9173ab8e9077cb6259869ca2f32
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
src/modules/SD2/scripts/kalimdor/silithus.cpp
muscnx/Mangos021SD2
695bb6a4822bb9173ab8e9077cb6259869ca2f32
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
/** * ScriptDev2 is an extension for mangos providing enhanced features for * area triggers, creatures, game objects, instances, items, and spells beyond * the default database scripting in mangos. * * Copyright (C) 2006-2013 ScriptDev2 <http://www.scriptdev2.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ /** * ScriptData * SDName: Silithus * SD%Complete: 100 * SDComment: Quest support: 8519. * SDCategory: Silithus * EndScriptData */ /** * ContentData * npc_anachronos_the_ancient * EndContentData */ #include "precompiled.h" /*### ## npc_anachronos_the_ancient ###*/ enum { // Dragons NPC_MERITHRA_OF_THE_DREAM = 15378, NPC_CAELESTRASZ = 15379, NPC_ARYGOS = 15380, NPC_ANACHRONOS_THE_ANCIENT = 15381, NPC_ANACHRONOS_QUEST_TRIGGER = 15454, // marks some movement for the dragons // Elfs NPC_FANDRAL_STAGHELM = 15382, NPC_KALDOREI_INFANTRY = 15423, // Qiraji warriors NPC_QIRAJI_WASP = 15414, NPC_QIRAJI_DRONE = 15421, NPC_QIRAJI_TANK = 15422, NPC_ANUBISATH_CONQUEROR = 15424, QUEST_A_PAWN_ON_THE_ETERNAL_BOARD = 8519, // Yells -> in chronological order SAY_ANACHRONOS_INTRO_1 = -1000740, SAY_FANDRAL_INTRO_2 = -1000741, SAY_MERITHRA_INTRO_3 = -1000742, EMOTE_ARYGOS_NOD = -1000743, SAY_CAELESTRASZ_INTRO_4 = -1000744, EMOTE_MERITHRA_GLANCE = -1000745, SAY_MERITHRA_INTRO_5 = -1000746, SAY_MERITHRA_ATTACK_1 = -1000747, SAY_ARYGOS_ATTACK_2 = -1000748, SAY_ARYGOS_ATTACK_3 = -1000749, SAY_CAELESTRASZ_ATTACK_4 = -1000750, SAY_CAELESTRASZ_ATTACK_5 = -1000751, SAY_ANACHRONOS_SEAL_1 = -1000752, SAY_FANDRAL_SEAL_2 = -1000753, SAY_ANACHRONOS_SEAL_3 = -1000754, SAY_ANACHRONOS_SEAL_4 = -1000755, SAY_ANACHRONOS_SEAL_5 = -1000756, SAY_FANDRAL_SEAL_6 = -1000757, EMOTE_FANDRAL_EXHAUSTED = -1000758, SAY_ANACHRONOS_EPILOGUE_1 = -1000759, SAY_ANACHRONOS_EPILOGUE_2 = -1000760, SAY_ANACHRONOS_EPILOGUE_3 = -1000761, EMOTE_ANACHRONOS_SCEPTER = -1000762, SAY_FANDRAL_EPILOGUE_4 = -1000763, SAY_FANDRAL_EPILOGUE_5 = -1000764, EMOTE_FANDRAL_SHATTER = -1000765, SAY_ANACHRONOS_EPILOGUE_6 = -1000766, SAY_FANDRAL_EPILOGUE_7 = -1000767, EMOTE_ANACHRONOS_DISPPOINTED = -1000768, EMOTE_ANACHRONOS_PICKUP = -1000769, SAY_ANACHRONOS_EPILOGUE_8 = -1000770, // Spells SPELL_GREEN_DRAGON_TRANSFORM = 25105, SPELL_RED_DRAGON_TRANSFORM = 25106, SPELL_BLUE_DRAGON_TRANSFORM = 25107, SPELL_BRONZE_DRAGON_TRANSFORM = 25108, SPELL_MERITHRA_WAKE = 25145, // should trigger 25172 on targets SPELL_ARYGOS_VENGEANCE = 25149, SPELL_CAELESTRASZ_MOLTEN_RAIN = 25150, SPELL_TIME_STOP = 25158, // Anachronos stops the battle - should trigger 25171 SPELL_GLYPH_OF_WARDING = 25166, // Sends event 9427 - should activate Go 176148 SPELL_PRISMATIC_BARRIER = 25159, // Sends event 9425 - should activate Go 176146 SPELL_CALL_ANCIENTS = 25167, // Sends event 9426 - should activate Go 176147 SPELL_SHATTER_HAMMER = 25182, // Breakes the scepter - needs DB coords POINT_ID_DRAGON_ATTACK = 1, POINT_ID_EXIT = 2, POINT_ID_GATE = 3, POINT_ID_SCEPTER_1 = 4, POINT_ID_SCEPTER_2 = 5, POINT_ID_EPILOGUE = 6, DATA_HANDLE_SCEPTER = 7, // dummy members - used in dialogue helper DATA_MERITHRA_ATTACK = 8, DATA_CAELASTRASZ_ATTACK = 9, MAX_DRAGONS = 4, MAX_CONQUERORS = 3, MAX_QIRAJI = 6, MAX_KALDOREI = 20, }; /* Known event issues: * The Kaldorei and Qiraji soldiers don't have the correct flags and factions in DB * The Ahn'Qiraj gate gameobjects are missing from DB * The spells used by the dragons upon the Qiraji need core support * The script events sent by the spells which close the AQ gate needs DB support * Can't make Fandral equip the Scepter when Anachronos handles it to him */ static const DialogueEntry aEventDialogue[] = { {NPC_ANACHRONOS_THE_ANCIENT, 0, 2000}, // summon the dragons {SAY_ANACHRONOS_INTRO_1, NPC_ANACHRONOS_THE_ANCIENT, 3000}, {EMOTE_ONESHOT_SHOUT, NPC_ANACHRONOS_THE_ANCIENT, 3000}, // make Anachronos shout and summon the warriors {SAY_FANDRAL_INTRO_2, NPC_FANDRAL_STAGHELM, 6000}, {EMOTE_MERITHRA_GLANCE, NPC_MERITHRA_OF_THE_DREAM, 2000}, {SAY_MERITHRA_INTRO_3, NPC_MERITHRA_OF_THE_DREAM, 3000}, {EMOTE_ARYGOS_NOD, NPC_ARYGOS, 4000}, {SAY_CAELESTRASZ_INTRO_4, NPC_CAELESTRASZ, 9000}, {SAY_MERITHRA_INTRO_5, NPC_MERITHRA_OF_THE_DREAM, 5000}, {NPC_ANACHRONOS_QUEST_TRIGGER, 0, 0}, // send Merithra to fight {DATA_MERITHRA_ATTACK, 0, 5000}, // make Merithra wait {SAY_MERITHRA_ATTACK_1, NPC_MERITHRA_OF_THE_DREAM, 1000}, {SPELL_GREEN_DRAGON_TRANSFORM, 0, 6000}, {SAY_ARYGOS_ATTACK_2, NPC_ARYGOS, 5000}, {NPC_ARYGOS, 0, 1000}, // send Arygos to fight {POINT_ID_EXIT, 0, 4000}, // make Merithra exit {SAY_ARYGOS_ATTACK_3, NPC_ARYGOS, 4000}, {SPELL_BLUE_DRAGON_TRANSFORM, 0, 5000}, {SPELL_ARYGOS_VENGEANCE, 0, 7000}, {POINT_ID_DRAGON_ATTACK, 0, 1000}, // make Arygos exit {SAY_CAELESTRASZ_ATTACK_4, NPC_CAELESTRASZ, 5000}, {NPC_CAELESTRASZ, 0, 0}, // send Caelestrasz to fight {DATA_CAELASTRASZ_ATTACK, 0, 3000}, // make Caelestrasz wait {SAY_CAELESTRASZ_ATTACK_5, NPC_CAELESTRASZ, 5000}, {SPELL_RED_DRAGON_TRANSFORM, 0, 4000}, // transform Caelestrasz {SPELL_CAELESTRASZ_MOLTEN_RAIN, 0, 6000}, // Caelestrasz casts molten rain {SAY_ANACHRONOS_SEAL_1, NPC_ANACHRONOS_THE_ANCIENT, 5000}, {SAY_FANDRAL_SEAL_2, NPC_FANDRAL_STAGHELM, 3000}, {SAY_ANACHRONOS_SEAL_3, NPC_ANACHRONOS_THE_ANCIENT, 1000}, {POINT_ID_GATE, 0, 1000}, // send Anachronos to the gate {NPC_FANDRAL_STAGHELM, 0, 0}, // send Fandral to the gate {SPELL_TIME_STOP, 0, 7000}, // Anachronos casts Time Stop {SPELL_PRISMATIC_BARRIER, 0, 15000}, {SPELL_GLYPH_OF_WARDING, 0, 4000}, {SAY_ANACHRONOS_SEAL_5, NPC_ANACHRONOS_THE_ANCIENT, 3000}, {SAY_FANDRAL_SEAL_6, NPC_FANDRAL_STAGHELM, 9000}, {EMOTE_FANDRAL_EXHAUSTED, NPC_FANDRAL_STAGHELM, 1000}, {SAY_ANACHRONOS_EPILOGUE_1, NPC_ANACHRONOS_THE_ANCIENT, 6000}, {SAY_ANACHRONOS_EPILOGUE_2, NPC_ANACHRONOS_THE_ANCIENT, 5000}, {SAY_ANACHRONOS_EPILOGUE_3, NPC_ANACHRONOS_THE_ANCIENT, 15000}, {DATA_HANDLE_SCEPTER, NPC_ANACHRONOS_THE_ANCIENT, 3000}, // handle the scepter {SAY_FANDRAL_EPILOGUE_4, NPC_FANDRAL_STAGHELM, 3000}, {POINT_ID_SCEPTER_2, 0, 4000}, // make Anachronos stand {SAY_FANDRAL_EPILOGUE_5, NPC_FANDRAL_STAGHELM, 12000}, {EMOTE_FANDRAL_SHATTER, NPC_FANDRAL_STAGHELM, 3000}, {SAY_ANACHRONOS_EPILOGUE_6, NPC_ANACHRONOS_THE_ANCIENT, 0}, {SAY_FANDRAL_EPILOGUE_7, NPC_FANDRAL_STAGHELM, 8000}, {POINT_ID_EPILOGUE, 0, 4000}, // move Fandral to Anachronos {EMOTE_ANACHRONOS_DISPPOINTED, NPC_ANACHRONOS_THE_ANCIENT, 1000}, {POINT_ID_SCEPTER_1, 0, 0}, // make Anachronos pick the pieces {0, 0, 0}, }; struct EventLocations { float m_fX, m_fY, m_fZ, m_fO; uint32 m_uiEntry; }; static EventLocations aEternalBoardNPCs[MAX_DRAGONS] = { { -8029.301f, 1534.612f, 2.609f, 3.121f, NPC_FANDRAL_STAGHELM}, { -8034.227f, 1536.580f, 2.609f, 6.161f, NPC_ARYGOS}, { -8031.935f, 1532.658f, 2.609f, 1.012f, NPC_CAELESTRASZ}, { -8034.106f, 1534.224f, 2.609f, 0.290f, NPC_MERITHRA_OF_THE_DREAM}, }; static EventLocations aEternalBoardMovement[] = { { -8159.951f, 1525.241f, 74.994f}, // 0 Flight position for dragons { -8106.238f, 1525.948f, 2.639f}, // 1 Anachronos gate location { -8103.861f, 1525.923f, 2.677f}, // 2 Fandral gate location { -8107.387f, 1523.641f, 2.609f}, // 3 Shattered scepter { -8100.921f, 1527.740f, 2.871f}, // 4 Fandral epilogue location { -8115.270f, 1515.926f, 3.305f}, // 5 Anachronos gather broken scepter 1 { -8116.879f, 1530.615f, 3.762f}, // 6 Anachronos gather broken scepter 2 { -7997.790f, 1548.664f, 3.738f}, // 7 Fandral exit location { -8061.933f, 1496.196f, 2.556f}, // 8 Anachronos launch location { -8008.705f, 1446.063f, 44.104f}, // 9 Anachronos flight location { -8085.748f, 1521.484f, 2.624f} // 10 Anchor point for the army summoning }; struct npc_anachronos_the_ancientAI : public ScriptedAI, private DialogueHelper { npc_anachronos_the_ancientAI(Creature* pCreature) : ScriptedAI(pCreature), DialogueHelper(aEventDialogue) { Reset(); } uint32 m_uiEventTimer; uint8 m_uiEventStage; ObjectGuid m_fandralGuid; ObjectGuid m_merithraGuid; ObjectGuid m_CaelestraszGuid; ObjectGuid m_arygosGuid; ObjectGuid m_playerGuid; ObjectGuid m_triggerGuid; GuidList m_lQirajiWarriorsList; void Reset() override { // We summon the rest of the dragons on timer m_uiEventTimer = 100; m_uiEventStage = 0; } void JustDidDialogueStep(int32 iEntry) override { switch (iEntry) { case NPC_ANACHRONOS_THE_ANCIENT: // Call the other dragons DoSummonDragons(); break; case EMOTE_ONESHOT_SHOUT: // Summon warriors DoSummonWarriors(); m_creature->HandleEmote(EMOTE_ONESHOT_SHOUT); break; case SAY_FANDRAL_INTRO_2: if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { pFandral->SetFacingToObject(m_creature); } break; case EMOTE_MERITHRA_GLANCE: if (Creature* pMerithra = m_creature->GetMap()->GetCreature(m_merithraGuid)) { if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { pFandral->SetFacingToObject(pMerithra); } } break; case NPC_ANACHRONOS_QUEST_TRIGGER: // Move Merithra to attack if (Creature* pTrigger = GetClosestCreatureWithEntry(m_creature, NPC_ANACHRONOS_QUEST_TRIGGER, 35.0f)) { m_triggerGuid = pTrigger->GetObjectGuid(); if (Creature* pMerithra = m_creature->GetMap()->GetCreature(m_merithraGuid)) { pMerithra->SetWalk(false); pMerithra->GetMotionMaster()->MovePoint(POINT_ID_DRAGON_ATTACK, pTrigger->GetPositionX(), pTrigger->GetPositionY(), pTrigger->GetPositionZ()); } } break; case SPELL_GREEN_DRAGON_TRANSFORM: if (Creature* pMerithra = m_creature->GetMap()->GetCreature(m_merithraGuid)) { pMerithra->CastSpell(pMerithra, SPELL_GREEN_DRAGON_TRANSFORM, false); } break; case SAY_ARYGOS_ATTACK_2: if (Creature* pMerithra = m_creature->GetMap()->GetCreature(m_merithraGuid)) { pMerithra->CastSpell(pMerithra, SPELL_MERITHRA_WAKE, false); } break; case NPC_ARYGOS: // Move Arygos to attack if (Creature* pTrigger = m_creature->GetMap()->GetCreature(m_triggerGuid)) { if (Creature* pArygos = m_creature->GetMap()->GetCreature(m_arygosGuid)) { pArygos->SetWalk(false); pArygos->GetMotionMaster()->MovePoint(POINT_ID_DRAGON_ATTACK, pTrigger->GetPositionX(), pTrigger->GetPositionY(), pTrigger->GetPositionZ()); } } break; case POINT_ID_EXIT: // Move Merithra to the exit point if (Creature* pMerithra = m_creature->GetMap()->GetCreature(m_merithraGuid)) { pMerithra->SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND); pMerithra->SetLevitate(true); pMerithra->GetMotionMaster()->MovePoint(POINT_ID_EXIT, aEternalBoardMovement[0].m_fX, aEternalBoardMovement[0].m_fY, aEternalBoardMovement[0].m_fZ); pMerithra->ForcedDespawn(9000); } break; case SPELL_BLUE_DRAGON_TRANSFORM: if (Creature* pArygos = m_creature->GetMap()->GetCreature(m_arygosGuid)) { pArygos->CastSpell(pArygos, SPELL_BLUE_DRAGON_TRANSFORM, false); } break; case SPELL_ARYGOS_VENGEANCE: if (Creature* pArygos = m_creature->GetMap()->GetCreature(m_arygosGuid)) { pArygos->CastSpell(pArygos, SPELL_ARYGOS_VENGEANCE, false); } break; case POINT_ID_DRAGON_ATTACK: // Move Arygos to the exit point if (Creature* pArygos = m_creature->GetMap()->GetCreature(m_arygosGuid)) { pArygos->SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND); pArygos->SetLevitate(true); pArygos->GetMotionMaster()->MovePoint(POINT_ID_EXIT, aEternalBoardMovement[0].m_fX, aEternalBoardMovement[0].m_fY, aEternalBoardMovement[0].m_fZ); pArygos->ForcedDespawn(9000); } break; case NPC_CAELESTRASZ: // Move Caelestrasz to attack if (Creature* pTrigger = m_creature->GetMap()->GetCreature(m_triggerGuid)) { if (Creature* pCaelestrasz = m_creature->GetMap()->GetCreature(m_CaelestraszGuid)) { pCaelestrasz->SetWalk(false); pCaelestrasz->GetMotionMaster()->MovePoint(POINT_ID_DRAGON_ATTACK, pTrigger->GetPositionX(), pTrigger->GetPositionY(), pTrigger->GetPositionZ()); } } break; case SPELL_RED_DRAGON_TRANSFORM: if (Creature* pCaelestrasz = m_creature->GetMap()->GetCreature(m_CaelestraszGuid)) { pCaelestrasz->CastSpell(pCaelestrasz, SPELL_RED_DRAGON_TRANSFORM, false); } break; case SPELL_CAELESTRASZ_MOLTEN_RAIN: if (Creature* pCaelestrasz = m_creature->GetMap()->GetCreature(m_CaelestraszGuid)) { pCaelestrasz->CastSpell(pCaelestrasz, SPELL_CAELESTRASZ_MOLTEN_RAIN, false); } break; case SAY_ANACHRONOS_SEAL_1: // Send Caelestrasz on flight if (Creature* pCaelestrasz = m_creature->GetMap()->GetCreature(m_CaelestraszGuid)) { pCaelestrasz->SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND); pCaelestrasz->SetLevitate(true); pCaelestrasz->GetMotionMaster()->MovePoint(POINT_ID_EXIT, aEternalBoardMovement[0].m_fX, aEternalBoardMovement[0].m_fY, aEternalBoardMovement[0].m_fZ); pCaelestrasz->ForcedDespawn(9000); } if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { m_creature->SetFacingToObject(pFandral); } break; case SAY_FANDRAL_SEAL_2: if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { pFandral->SetFacingToObject(m_creature); } break; case POINT_ID_GATE: // Send Anachronos to the gate m_creature->SetWalk(false); m_creature->GetMotionMaster()->MovePoint(POINT_ID_GATE, aEternalBoardMovement[1].m_fX, aEternalBoardMovement[1].m_fY, aEternalBoardMovement[1].m_fZ); break; case NPC_FANDRAL_STAGHELM: // Send Fandral to the gate if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { pFandral->SetWalk(false); pFandral->GetMotionMaster()->MovePoint(POINT_ID_GATE, aEternalBoardMovement[2].m_fX, aEternalBoardMovement[2].m_fY, aEternalBoardMovement[2].m_fZ); } break; case SPELL_PRISMATIC_BARRIER: DoCastSpellIfCan(m_creature, SPELL_PRISMATIC_BARRIER); break; case SPELL_GLYPH_OF_WARDING: DoCastSpellIfCan(m_creature, SPELL_GLYPH_OF_WARDING); break; case SAY_FANDRAL_SEAL_6: // Here Anachronos should continue to cast something if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { pFandral->CastSpell(pFandral, SPELL_CALL_ANCIENTS, false); } break; case EMOTE_FANDRAL_EXHAUSTED: if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { pFandral->SetStandState(UNIT_STAND_STATE_KNEEL); m_creature->SetFacingToObject(pFandral); } break; case DATA_HANDLE_SCEPTER: // Give the scepter to Fandral (it should equip it somehow) if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { DoScriptText(EMOTE_ANACHRONOS_SCEPTER, m_creature, pFandral); } m_creature->SetStandState(UNIT_STAND_STATE_KNEEL); break; case SAY_FANDRAL_EPILOGUE_4: if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { pFandral->SetStandState(UNIT_STAND_STATE_STAND); } break; case POINT_ID_SCEPTER_2: m_creature->SetStandState(UNIT_STAND_STATE_STAND); break; case EMOTE_FANDRAL_SHATTER: // Shatter the scepter if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { pFandral->CastSpell(pFandral, SPELL_SHATTER_HAMMER, false); } break; case SAY_ANACHRONOS_EPILOGUE_6: if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { pFandral->SetWalk(true); pFandral->GetMotionMaster()->MovePoint(POINT_ID_SCEPTER_1, aEternalBoardMovement[3].m_fX, aEternalBoardMovement[3].m_fY, aEternalBoardMovement[3].m_fZ); } break; case POINT_ID_EPILOGUE: // Make Fandral leave if (Creature* pFandral = m_creature->GetMap()->GetCreature(m_fandralGuid)) { pFandral->GetMotionMaster()->MovePoint(POINT_ID_EXIT, aEternalBoardMovement[7].m_fX, aEternalBoardMovement[7].m_fY, aEternalBoardMovement[7].m_fZ); } break; case POINT_ID_SCEPTER_1: // Anachronos collects the pieces m_creature->SetWalk(true); m_creature->GetMotionMaster()->MovePoint(POINT_ID_SCEPTER_1, aEternalBoardMovement[5].m_fX, aEternalBoardMovement[5].m_fY, aEternalBoardMovement[5].m_fZ); break; } } Creature* GetSpeakerByEntry(uint32 uiEntry) override { switch (uiEntry) { case NPC_ANACHRONOS_THE_ANCIENT: return m_creature; case NPC_ARYGOS: return m_creature->GetMap()->GetCreature(m_arygosGuid); case NPC_CAELESTRASZ: return m_creature->GetMap()->GetCreature(m_CaelestraszGuid); case NPC_MERITHRA_OF_THE_DREAM: return m_creature->GetMap()->GetCreature(m_merithraGuid); case NPC_FANDRAL_STAGHELM: return m_creature->GetMap()->GetCreature(m_fandralGuid); default: return NULL; } } void DoSummonDragons() { for (uint8 i = 0; i < MAX_DRAGONS; ++i) { m_creature->SummonCreature(aEternalBoardNPCs[i].m_uiEntry, aEternalBoardNPCs[i].m_fX, aEternalBoardNPCs[i].m_fY, aEternalBoardNPCs[i].m_fZ, aEternalBoardNPCs[i].m_fO, TEMPSUMMON_CORPSE_DESPAWN, 0); } // Also summon the 3 anubisath conquerors float fX, fY, fZ; for (uint8 i = 0; i < MAX_CONQUERORS; ++i) { m_creature->GetRandomPoint(aEternalBoardMovement[10].m_fX, aEternalBoardMovement[10].m_fY, aEternalBoardMovement[10].m_fZ, 20.0f, fX, fY, fZ); m_creature->SummonCreature(NPC_ANUBISATH_CONQUEROR, fX, fY, fZ, 0, TEMPSUMMON_CORPSE_DESPAWN, 0); } } void DoSummonWarriors() { float fX, fY, fZ; // Summon kaldorei warriors for (uint8 i = 0; i < MAX_KALDOREI; ++i) { m_creature->GetRandomPoint(aEternalBoardMovement[10].m_fX, aEternalBoardMovement[10].m_fY, aEternalBoardMovement[10].m_fZ, 10.0f, fX, fY, fZ); m_creature->SummonCreature(NPC_KALDOREI_INFANTRY, fX, fY, fZ, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0); } // Summon Qiraji warriors for (uint8 i = 0; i < MAX_QIRAJI; ++i) { m_creature->GetRandomPoint(aEternalBoardMovement[10].m_fX, aEternalBoardMovement[10].m_fY, aEternalBoardMovement[10].m_fZ, 15.0f, fX, fY, fZ); m_creature->SummonCreature(NPC_QIRAJI_WASP, fX, fY, fZ, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0); m_creature->GetRandomPoint(aEternalBoardMovement[10].m_fX, aEternalBoardMovement[10].m_fY, aEternalBoardMovement[10].m_fZ, 15.0f, fX, fY, fZ); m_creature->SummonCreature(NPC_QIRAJI_DRONE, fX, fY, fZ, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0); m_creature->GetRandomPoint(aEternalBoardMovement[10].m_fX, aEternalBoardMovement[10].m_fY, aEternalBoardMovement[10].m_fZ, 15.0f, fX, fY, fZ); m_creature->SummonCreature(NPC_QIRAJI_TANK, fX, fY, fZ, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0); } } void DoUnsummonArmy() { for (GuidList::const_iterator itr = m_lQirajiWarriorsList.begin(); itr != m_lQirajiWarriorsList.end(); ++itr) { if (Creature* pTemp = m_creature->GetMap()->GetCreature(*itr)) { pTemp->ForcedDespawn(); } } } void JustSummoned(Creature* pSummoned) override { // Also remove npc flags where needed switch (pSummoned->GetEntry()) { case NPC_FANDRAL_STAGHELM: m_fandralGuid = pSummoned->GetObjectGuid(); break; case NPC_MERITHRA_OF_THE_DREAM: m_merithraGuid = pSummoned->GetObjectGuid(); pSummoned->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); break; case NPC_CAELESTRASZ: m_CaelestraszGuid = pSummoned->GetObjectGuid(); pSummoned->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); break; case NPC_ARYGOS: m_arygosGuid = pSummoned->GetObjectGuid(); pSummoned->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); break; case NPC_ANUBISATH_CONQUEROR: case NPC_QIRAJI_WASP: case NPC_QIRAJI_DRONE: case NPC_QIRAJI_TANK: case NPC_KALDOREI_INFANTRY: m_lQirajiWarriorsList.push_back(pSummoned->GetObjectGuid()); break; } } void MovementInform(uint32 uiType, uint32 uiPointId) override { if (uiType != POINT_MOTION_TYPE) { return; } switch (uiPointId) { case POINT_ID_GATE: // Cast time stop when he reaches the gate DoCastSpellIfCan(m_creature, SPELL_TIME_STOP); StartNextDialogueText(SPELL_TIME_STOP); break; case POINT_ID_SCEPTER_1: // Pickup the pieces DoScriptText(EMOTE_ANACHRONOS_PICKUP, m_creature); m_creature->SetStandState(UNIT_STAND_STATE_KNEEL); m_uiEventTimer = 2000; break; case POINT_ID_SCEPTER_2: // Pickup the pieces DoScriptText(SAY_ANACHRONOS_EPILOGUE_8, m_creature); m_creature->SetStandState(UNIT_STAND_STATE_KNEEL); m_uiEventTimer = 4000; break; case POINT_ID_EXIT: DoCastSpellIfCan(m_creature, SPELL_BRONZE_DRAGON_TRANSFORM); m_uiEventTimer = 4000; break; } } void SummonedMovementInform(Creature* pSummoned, uint32 uiType, uint32 uiPointId) override { if (uiType != POINT_MOTION_TYPE) { return; } if (pSummoned->GetEntry() == NPC_FANDRAL_STAGHELM) { switch (uiPointId) { case POINT_ID_EPILOGUE: // Face Anachronos and restart the dialogue pSummoned->SetFacingToObject(m_creature); StartNextDialogueText(SAY_FANDRAL_EPILOGUE_7); DoUnsummonArmy(); break; case POINT_ID_SCEPTER_1: pSummoned->GetMotionMaster()->MovePoint(POINT_ID_EPILOGUE, aEternalBoardMovement[4].m_fX, aEternalBoardMovement[4].m_fY, aEternalBoardMovement[4].m_fZ); break; case POINT_ID_EXIT: pSummoned->ForcedDespawn(); break; } } else if (uiPointId == POINT_ID_DRAGON_ATTACK) { switch (pSummoned->GetEntry()) { case NPC_MERITHRA_OF_THE_DREAM: StartNextDialogueText(DATA_MERITHRA_ATTACK); break; case NPC_CAELESTRASZ: StartNextDialogueText(DATA_CAELASTRASZ_ATTACK); break; } } } void UpdateAI(const uint32 uiDiff) override { DialogueUpdate(uiDiff); if (m_uiEventTimer) { if (m_uiEventTimer <= uiDiff) { switch (m_uiEventStage) { case 0: // Start the dialogue StartNextDialogueText(NPC_ANACHRONOS_THE_ANCIENT); m_uiEventTimer = 0; break; case 1: // Do the epilogue movement m_creature->GetMotionMaster()->MovePoint(POINT_ID_SCEPTER_2, aEternalBoardMovement[6].m_fX, aEternalBoardMovement[6].m_fY, aEternalBoardMovement[6].m_fZ); m_creature->SetStandState(UNIT_STAND_STATE_STAND); m_uiEventTimer = 0; break; case 2: // Complete quest and despawn gate if (Player* pPlayer = m_creature->GetMap()->GetPlayer(m_playerGuid)) { pPlayer->GroupEventHappens(QUEST_A_PAWN_ON_THE_ETERNAL_BOARD, m_creature); } m_creature->SetStandState(UNIT_STAND_STATE_STAND); m_uiEventTimer = 4000; break; case 3: // Move to exit m_creature->SetWalk(false); m_creature->GetMotionMaster()->MovePoint(POINT_ID_EXIT, aEternalBoardMovement[8].m_fX, aEternalBoardMovement[8].m_fY, aEternalBoardMovement[8].m_fZ); m_uiEventTimer = 0; break; case 4: // Take off and fly m_creature->SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND); m_creature->SetLevitate(true); m_creature->GetMotionMaster()->MovePoint(0, aEternalBoardMovement[9].m_fX, aEternalBoardMovement[9].m_fY, aEternalBoardMovement[9].m_fZ); m_creature->ForcedDespawn(10000); m_uiEventTimer = 0; break; } ++m_uiEventStage; } else { m_uiEventTimer -= uiDiff; } } } }; CreatureAI* GetAI_npc_anachronos_the_ancient(Creature* pCreature) { return new npc_anachronos_the_ancientAI(pCreature); } bool QuestAcceptGO_crystalline_tear(Player* pPlayer, GameObject* pGo, const Quest* pQuest) { // Summon the controller dragon at GO position (orientation is wrong - hardcoded) if (pQuest->GetQuestId() == QUEST_A_PAWN_ON_THE_ETERNAL_BOARD) { // Check if event is already in progress first if (GetClosestCreatureWithEntry(pGo, NPC_ANACHRONOS_THE_ANCIENT, 90.0f)) { return true; } if (Creature* pAnachronos = pPlayer->SummonCreature(NPC_ANACHRONOS_THE_ANCIENT, pGo->GetPositionX(), pGo->GetPositionY(), pGo->GetPositionZ(), 3.75f, TEMPSUMMON_CORPSE_DESPAWN, 0)) { // Send the player's guid in order to handle the quest complete if (npc_anachronos_the_ancientAI* pAnachronosAI = dynamic_cast<npc_anachronos_the_ancientAI*>(pAnachronos->AI())) { pAnachronosAI->m_playerGuid = pPlayer->GetObjectGuid(); } } } return true; } void AddSC_silithus() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "npc_anachronos_the_ancient"; pNewScript->GetAI = &GetAI_npc_anachronos_the_ancient; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "go_crystalline_tear"; pNewScript->pQuestAcceptGO = &QuestAcceptGO_crystalline_tear; pNewScript->RegisterSelf(); }
44.946237
209
0.56866
muscnx
494edf0df46b4ef1bdfbf8e86ec0516680037a30
914
cpp
C++
kick-start/2020/2020F-B.cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
107
2019-10-25T07:46:59.000Z
2022-03-29T11:10:56.000Z
kick-start/2020/2020F-B.cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
1
2021-08-13T05:42:27.000Z
2021-08-13T05:42:27.000Z
kick-start/2020/2020F-B.cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
18
2020-12-09T14:24:22.000Z
2022-03-30T06:56:01.000Z
#include <algorithm> #include <cmath> #include <iostream> using namespace std; int t, n, k, s[100010], e[100010], b[100010]; int solve() { // O(n log n) stable_sort( b, b + n, [](int left, int right) -> bool { // sort indices according to corresponding array element return s[left] < s[right]; }); int ans = 0, cur_ed = 0; for (int i = 0; i < n; i++) { int st = s[b[i]], ed = e[b[i]]; if (cur_ed >= ed) continue; if (cur_ed > st) st = cur_ed; int add = ceil((double)(ed - st) / k); ans += add; cur_ed = st + add * k; } return ans; } int main() { cin >> t; for (int i = 1; i <= t; i++) { cin >> n >> k; for (int i = 0; i < n; i++) { cin >> s[i] >> e[i]; b[i] = i; } printf("Case #%d: %d\n", i, solve()); } return 0; }
21.761905
68
0.431072
upupming
495c81ed964a4da5bb18a389a89de9808d24104c
16,536
cpp
C++
src/main/DLSFile.cpp
ElSaico/vgmtrans
8fa6f4adf6437e47c2bddf0e8a96bef7cd13ff88
[ "Zlib" ]
null
null
null
src/main/DLSFile.cpp
ElSaico/vgmtrans
8fa6f4adf6437e47c2bddf0e8a96bef7cd13ff88
[ "Zlib" ]
null
null
null
src/main/DLSFile.cpp
ElSaico/vgmtrans
8fa6f4adf6437e47c2bddf0e8a96bef7cd13ff88
[ "Zlib" ]
null
null
null
/** * VGMTrans (c) - 2002-2021 * Licensed under the zlib license * See the included LICENSE for more information */ #include "pch.h" #include <algorithm> #include <memory> #include <numeric> #include "DLSFile.h" #include "VGMInstrSet.h" #include "VGMSamp.h" #include "Root.h" using namespace std; // ******* // DLSFile // ******* DLSFile::DLSFile(string dls_name) : RiffFile(dls_name, "DLS ") { } std::vector<DLSInstr *> DLSFile::GetInstruments() { std::vector<DLSInstr *> instrs(m_instrs.size()); std::transform(std::begin(m_instrs), std::end(m_instrs), std::begin(instrs), [](auto &instr_pointer) { return instr_pointer.get(); }); return instrs; } std::vector<DLSWave *> DLSFile::GetWaves() { std::vector<DLSWave *> waves(m_waves.size()); std::transform(std::begin(m_waves), std::end(m_waves), std::begin(waves), [](auto &wave_pointer) { return wave_pointer.get(); }); return waves; } DLSInstr *DLSFile::AddInstr(unsigned long bank, unsigned long instrNum) { auto instr = m_instrs.emplace_back(std::make_unique<DLSInstr>(bank, instrNum)).get(); return instr; } DLSInstr *DLSFile::AddInstr(unsigned long bank, unsigned long instrNum, std::string instr_name) { auto instr = m_instrs.emplace_back(std::make_unique<DLSInstr>(bank, instrNum, instr_name)).get(); return instr; } void DLSFile::DeleteInstr(unsigned long, unsigned long) { } DLSWave *DLSFile::AddWave(uint16_t formatTag, uint16_t channels, int samplesPerSec, int aveBytesPerSec, uint16_t blockAlign, uint16_t bitsPerSample, uint32_t waveDataSize, unsigned char *waveData, string wave_name) { auto wave = m_waves .emplace_back(std::make_unique<DLSWave>(formatTag, channels, samplesPerSec, aveBytesPerSec, blockAlign, bitsPerSample, waveDataSize, waveData, wave_name)) .get(); return wave; } // GetSize returns total DLS size, including the "RIFF" header size uint32_t DLSFile::GetSize() { uint32_t dls_size = 0; dls_size += 12; // "RIFF" + size + "DLS " dls_size += COLH_SIZE; // COLH chunk (collection chunk - tells how many instruments) dls_size += LIST_HDR_SIZE; //"lins" list (list of instruments - contains all the "ins " lists) for (auto &instr : m_instrs) { dls_size += instr->GetSize(); } dls_size += 16; // "ptbl" + size + cbSize + cCues dls_size += static_cast<uint32_t>(m_waves.size()) * sizeof(uint32_t); // each wave gets a poolcue dls_size += LIST_HDR_SIZE; //"wvpl" list (wave pool - contains all the "wave" lists) for (auto &wave : m_waves) { dls_size += wave->GetSize(); } dls_size += LIST_HDR_SIZE; //"INFO" list dls_size += 8; //"INAM" + size dls_size += static_cast<uint32_t>(name.size()); // size of name string return dls_size; } int DLSFile::WriteDLSToBuffer(vector<uint8_t> &buf) { uint32_t theDWORD; PushTypeOnVectBE<uint32_t>(buf, 0x52494646); //"RIFF" PushTypeOnVect<uint32_t>(buf, GetSize() - 8); // size PushTypeOnVectBE<uint32_t>(buf, 0x444C5320); //"DLS " PushTypeOnVectBE<uint32_t>(buf, 0x636F6C68); //"colh " PushTypeOnVect<uint32_t>(buf, 4); // size PushTypeOnVect<uint32_t>( buf, static_cast<uint32_t>(m_instrs.size())); // cInstruments - number of instruments theDWORD = 4; // account for 4 "lins" bytes for (auto &instr : m_instrs) theDWORD += instr->GetSize(); // each "ins " list WriteLIST(buf, 0x6C696E73, theDWORD); // Write the "lins" LIST for (auto &instr : m_instrs) { instr->Write(buf); } PushTypeOnVectBE<uint32_t>(buf, 0x7074626C); //"ptbl" theDWORD = 8; theDWORD += static_cast<uint32_t>(m_waves.size()) * sizeof(uint32_t); // each wave gets a poolcue PushTypeOnVect<uint32_t>(buf, theDWORD); // size PushTypeOnVect<uint32_t>(buf, 8); // cbSize PushTypeOnVect<uint32_t>(buf, static_cast<uint32_t>(m_waves.size())); // cCues theDWORD = 0; for (auto &wave : m_waves) { PushTypeOnVect<uint32_t>(buf, theDWORD); // write the poolcue for each sample theDWORD += wave->GetSize(); // increment the offset to the next wave } theDWORD = 4; for (auto &wave : m_waves) { theDWORD += wave->GetSize(); // each "wave" list } WriteLIST(buf, 0x7776706C, theDWORD); // Write the "wvpl" LIST for (auto &wave : m_waves) { wave->Write(buf); // Write each "wave" list } theDWORD = 12 + static_cast<uint32_t>(name.size()); //"INFO" + "INAM" + size + the string size WriteLIST(buf, 0x494E464F, theDWORD); // write the "INFO" list PushTypeOnVectBE<uint32_t>(buf, 0x494E414D); //"INAM" PushTypeOnVect<uint32_t>(buf, static_cast<uint32_t>(name.size())); // size PushBackStringOnVector(buf, name); // The Instrument Name string return true; } // I should probably make this function part of a parent class for both Midi and DLS file bool DLSFile::SaveDLSFile(const std::wstring &filepath) { vector<uint8_t> dlsBuf; WriteDLSToBuffer(dlsBuf); return pRoot->UI_WriteBufferToFile(filepath, dlsBuf.data(), static_cast<uint32_t>(dlsBuf.size())); } // ******* // DLSInstr // ******** DLSInstr::DLSInstr(uint32_t bank, uint32_t instrument) : ulBank(bank), ulInstrument(instrument), m_name("Untitled instrument") { RiffFile::AlignName(m_name); } DLSInstr::DLSInstr(uint32_t bank, uint32_t instrument, string instrName) : ulBank(bank), ulInstrument(instrument), m_name(instrName) { RiffFile::AlignName(m_name); } uint32_t DLSInstr::GetSize() const { uint32_t dls_size = 0; dls_size += LIST_HDR_SIZE; //"ins " list dls_size += INSH_SIZE; // insh chunk dls_size += LIST_HDR_SIZE; //"lrgn" list for (auto &rgn : m_regions) { dls_size += rgn->GetSize(); } dls_size += LIST_HDR_SIZE; //"INFO" list dls_size += 8; //"INAM" + size dls_size += static_cast<uint32_t>(m_name.size()); // size of name string return dls_size; } void DLSInstr::Write(vector<uint8_t> &buf) { uint32_t temp = GetSize() - 8; RiffFile::WriteLIST(buf, 0x696E7320, temp); // write "ins " list PushTypeOnVectBE<uint32_t>(buf, 0x696E7368); //"insh" PushTypeOnVect<uint32_t>(buf, INSH_SIZE - 8); // size PushTypeOnVect<uint32_t>(buf, static_cast<uint32_t>(m_regions.size())); // cRegions PushTypeOnVect<uint32_t>(buf, ulBank); // ulBank PushTypeOnVect<uint32_t>(buf, ulInstrument); // ulInstrument temp = 4; for (auto &rgn : m_regions) { temp += rgn->GetSize(); } RiffFile::WriteLIST(buf, 0x6C72676E, temp); // write the "lrgn" list for (auto &reg : m_regions) { reg->Write(buf); } temp = 12 + static_cast<uint32_t>(m_name.size()); //"INFO" + "INAM" + size + the string size RiffFile::WriteLIST(buf, 0x494E464F, temp); // write the "INFO" list PushTypeOnVectBE<uint32_t>(buf, 0x494E414D); //"INAM" temp = static_cast<uint32_t>(m_name.size()); PushTypeOnVect<uint32_t>(buf, temp); // size PushBackStringOnVector(buf, m_name); // The Instrument Name string } DLSRgn *DLSInstr::AddRgn() { auto reg = m_regions.emplace_back(std::make_unique<DLSRgn>()).get(); return reg; } // ****** // DLSRgn // ****** uint32_t DLSRgn::GetSize() const { uint32_t size = 0; size += LIST_HDR_SIZE; //"rgn2" list size += RGNH_SIZE; // rgnh chunk if (m_wsmp) { size += m_wsmp->GetSize(); } size += WLNK_SIZE; if (m_art) { size += m_art->GetSize(); } return size; } void DLSRgn::Write(vector<uint8_t> &buf) { RiffFile::WriteLIST(buf, 0x72676E32, (GetSize() - 8)); // write "rgn2" list PushTypeOnVectBE<uint32_t>(buf, 0x72676E68); //"rgnh" PushTypeOnVect<uint32_t>(buf, static_cast<uint32_t>(RGNH_SIZE - 8)); // size PushTypeOnVect<uint16_t>(buf, usKeyLow); // usLow (key) PushTypeOnVect<uint16_t>(buf, usKeyHigh); // usHigh (key) PushTypeOnVect<uint16_t>(buf, usVelLow); // usLow (vel) PushTypeOnVect<uint16_t>(buf, usVelHigh); // usHigh (vel) PushTypeOnVect<uint16_t>(buf, 1); // fusOptions PushTypeOnVect<uint16_t>(buf, 0); // usKeyGroup // new for dls2 PushTypeOnVect<uint16_t>(buf, 1); // NO CLUE if (m_wsmp) m_wsmp->Write(buf); // write the "wsmp" chunk PushTypeOnVectBE<uint32_t>(buf, 0x776C6E6B); //"wlnk" PushTypeOnVect<uint32_t>(buf, WLNK_SIZE - 8); // size PushTypeOnVect<uint16_t>(buf, fusOptions); // fusOptions PushTypeOnVect<uint16_t>(buf, usPhaseGroup); // usPhaseGroup PushTypeOnVect<uint32_t>(buf, channel); // ulChannel PushTypeOnVect<uint32_t>(buf, tableIndex); // ulTableIndex if (m_art) m_art->Write(buf); } DLSArt *DLSRgn::AddArt() { m_art = std::make_unique<DLSArt>(); return m_art.get(); } DLSWsmp *DLSRgn::AddWsmp() { m_wsmp = std::make_unique<DLSWsmp>(); return m_wsmp.get(); } void DLSRgn::SetRanges(uint16_t keyLow, uint16_t keyHigh, uint16_t velLow, uint16_t velHigh) { usKeyLow = keyLow; usKeyHigh = keyHigh; usVelLow = velLow; usVelHigh = velHigh; } void DLSRgn::SetWaveLinkInfo(uint16_t options, uint16_t phaseGroup, uint32_t theChannel, uint32_t theTableIndex) { fusOptions = options; usPhaseGroup = phaseGroup; channel = theChannel; tableIndex = theTableIndex; } // ****** // DLSArt // ****** uint32_t DLSArt::GetSize(void) { uint32_t size = 0; size += LIST_HDR_SIZE; //"lar2" list size += 16; //"art2" chunk + size + cbSize + cConnectionBlocks for (auto &block : m_blocks) size += block->GetSize(); // each connection block return size; } void DLSArt::Write(vector<uint8_t> &buf) { RiffFile::WriteLIST(buf, 0x6C617232, GetSize() - 8); // write "lar2" list PushTypeOnVectBE<uint32_t>(buf, 0x61727432); //"art2" PushTypeOnVect<uint32_t>(buf, GetSize() - LIST_HDR_SIZE - 8); // size PushTypeOnVect<uint32_t>(buf, 8); // cbSize PushTypeOnVect<uint32_t>(buf, static_cast<uint32_t>(m_blocks.size())); // cConnectionBlocks for (auto &block : m_blocks) { block->Write(buf); // each connection block } } void DLSArt::AddADSR(long attack_time, uint16_t atk_transform, long decay_time, long sustain_lev, long release_time, uint16_t rls_transform) { m_blocks.emplace_back(std::make_unique<ConnectionBlock>( CONN_SRC_NONE, CONN_SRC_NONE, CONN_DST_EG1_ATTACKTIME, atk_transform, attack_time)); m_blocks.emplace_back(std::make_unique<ConnectionBlock>( CONN_SRC_NONE, CONN_SRC_NONE, CONN_DST_EG1_DECAYTIME, CONN_TRN_NONE, decay_time)); m_blocks.emplace_back(std::make_unique<ConnectionBlock>( CONN_SRC_NONE, CONN_SRC_NONE, CONN_DST_EG1_SUSTAINLEVEL, CONN_TRN_NONE, sustain_lev)); m_blocks.emplace_back(std::make_unique<ConnectionBlock>( CONN_SRC_NONE, CONN_SRC_NONE, CONN_DST_EG1_RELEASETIME, rls_transform, release_time)); } void DLSArt::AddPan(long pan) { m_blocks.emplace_back(std::make_unique<ConnectionBlock>(CONN_SRC_NONE, CONN_SRC_NONE, CONN_DST_PAN, CONN_TRN_NONE, pan)); } // *************** // ConnectionBlock // *************** void ConnectionBlock::Write(vector<uint8_t> &buf) { PushTypeOnVect<uint16_t>(buf, usSource); // usSource PushTypeOnVect<uint16_t>(buf, usControl); // usControl PushTypeOnVect<uint16_t>(buf, usDestination); // usDestination PushTypeOnVect<uint16_t>(buf, usTransform); // usTransform PushTypeOnVect<int32_t>(buf, lScale); // lScale } // ******* // DLSWsmp // ******* uint32_t DLSWsmp::GetSize() const { uint32_t size = 0; size += 28; // all the variables minus the loop info if (cSampleLoops) size += 16; // plus the loop info return size; } void DLSWsmp::Write(vector<uint8_t> &buf) { PushTypeOnVectBE<uint32_t>(buf, 0x77736D70); //"wsmp" PushTypeOnVect<uint32_t>(buf, GetSize() - 8); // size PushTypeOnVect<uint32_t>(buf, 20); // cbSize (size of structure without loop record) PushTypeOnVect<uint16_t>(buf, usUnityNote); // usUnityNote PushTypeOnVect<int16_t>(buf, sFineTune); // sFineTune PushTypeOnVect<int32_t>(buf, lAttenuation); // lAttenuation PushTypeOnVect<uint32_t>(buf, 1); // fulOptions PushTypeOnVect<uint32_t>(buf, cSampleLoops); // cSampleLoops if (cSampleLoops) // if it loops, write the loop structure { PushTypeOnVect<uint32_t>(buf, 16); PushTypeOnVect<uint32_t>(buf, ulLoopType); // ulLoopType PushTypeOnVect<uint32_t>(buf, ulLoopStart); PushTypeOnVect<uint32_t>(buf, ulLoopLength); } } void DLSWsmp::SetLoopInfo(Loop &loop, VGMSamp *samp) { const int origFormatBytesPerSamp = samp->bps / 8; double compressionRatio = samp->GetCompressionRatio(); // If the sample loops, but the loop length is 0, then assume the length should // extend to the end of the sample. if (loop.loopStatus && loop.loopLength == 0) loop.loopLength = samp->dataLength - loop.loopStart; cSampleLoops = loop.loopStatus; ulLoopType = loop.loopType; // In DLS, the value is in number of samples // if the val is a raw offset of the original format, multiply it by the compression ratio ulLoopStart = (loop.loopStartMeasure == LM_BYTES) ? (uint32_t)((loop.loopStart * compressionRatio) / origFormatBytesPerSamp) : loop.loopStart; ulLoopLength = (loop.loopLengthMeasure == LM_BYTES) ? (uint32_t)((loop.loopLength * compressionRatio) / origFormatBytesPerSamp) : loop.loopLength; } void DLSWsmp::SetPitchInfo(uint16_t unityNote, short fineTune, long attenuation) { usUnityNote = unityNote; sFineTune = fineTune; lAttenuation = attenuation; } // ******* // DLSWave // ******* uint32_t DLSWave::GetSize() const { uint32_t size = 0; size += LIST_HDR_SIZE; //"wave" list size += 8; //"fmt " chunk + size size += 18; // fmt chunk data size += 8; //"data" chunk + size size += this->GetSampleSize(); // dataSize; //size of sample data size += LIST_HDR_SIZE; //"INFO" list size += 8; //"INAM" + size size += static_cast<uint32_t>(m_name.size()); // size of name string return size; } void DLSWave::Write(vector<uint8_t> &buf) { RiffFile::WriteLIST(buf, 0x77617665, GetSize() - 8); // write "wave" list PushTypeOnVectBE<uint32_t>(buf, 0x666D7420); //"fmt " PushTypeOnVect<uint32_t>(buf, 18); // size PushTypeOnVect<uint16_t>(buf, wFormatTag); // wFormatTag PushTypeOnVect<uint16_t>(buf, wChannels); // wChannels PushTypeOnVect<uint32_t>(buf, dwSamplesPerSec); // dwSamplesPerSec PushTypeOnVect<uint32_t>(buf, dwAveBytesPerSec); // dwAveBytesPerSec PushTypeOnVect<uint16_t>(buf, wBlockAlign); // wBlockAlign PushTypeOnVect<uint16_t>(buf, wBitsPerSample); // wBitsPerSample PushTypeOnVect<uint16_t>(buf, 0); // cbSize DLS2 specific. I don't know anything else PushTypeOnVectBE<uint32_t>(buf, 0x64617461); // "data" /* size: this is the ACTUAL size, not the even-aligned size */ PushTypeOnVect<uint32_t>(buf, m_wave_data.size()); buf.insert(buf.end(), std::begin(m_wave_data), std::end(m_wave_data)); // Write the sample if (m_wave_data.size() % 2) { buf.push_back(0); } uint32_t info_sig = 12 + static_cast<uint32_t>(m_name.size()); //"INFO" + "INAM" + size + the string size RiffFile::WriteLIST(buf, 0x494E464F, info_sig); // write the "INFO" list PushTypeOnVectBE<uint32_t>(buf, 0x494E414D); //"INAM" PushTypeOnVect<uint32_t>(buf, static_cast<uint32_t>(m_name.size())); // size PushBackStringOnVector(buf, m_name); }
37.496599
104
0.630261
ElSaico
495f29f077bbee89445c1955fe2d9329f62d09b8
144
cpp
C++
Data Structures and Algorithms/Stack/Stack.cpp
selvaraj-kuppusamy/WhatsAlgo
2bda75cb8a861c39c788cba9d5a792d96e08d4ba
[ "MIT" ]
null
null
null
Data Structures and Algorithms/Stack/Stack.cpp
selvaraj-kuppusamy/WhatsAlgo
2bda75cb8a861c39c788cba9d5a792d96e08d4ba
[ "MIT" ]
null
null
null
Data Structures and Algorithms/Stack/Stack.cpp
selvaraj-kuppusamy/WhatsAlgo
2bda75cb8a861c39c788cba9d5a792d96e08d4ba
[ "MIT" ]
null
null
null
/* Algorithm: Bubble Sort Time: Space: Author: selvaraj Kuppusamy, github.com/selvaraj-kuppusamy */ #include<iostream> using namespace std;
13.090909
57
0.756944
selvaraj-kuppusamy
4962490e27a68a782d18e4e218cb6f682fc56ea0
27,433
cc
C++
tests/value_test.cc
tegtmeye/cmd_options
03f2644e57413b38074545867ca539019201349e
[ "BSD-3-Clause" ]
null
null
null
tests/value_test.cc
tegtmeye/cmd_options
03f2644e57413b38074545867ca539019201349e
[ "BSD-3-Clause" ]
null
null
null
tests/value_test.cc
tegtmeye/cmd_options
03f2644e57413b38074545867ca539019201349e
[ "BSD-3-Clause" ]
null
null
null
#include "cmd_options.h" #include "test_detail.h" #include <boost/test/unit_test.hpp> /** Check for fundmental and STL value handling */ namespace co = cmd_options; typedef std::basic_string<detail::check_char_t> string_type; typedef co::basic_option_pack<detail::check_char_t> option_pack_type; typedef co::basic_option_description<detail::check_char_t> option_description_type; typedef co::basic_options_group<detail::check_char_t> options_group_type; typedef co::basic_variable_map<detail::check_char_t> variable_map_type; typedef detail::std_stream_select<detail::check_char_t> stream_select; namespace cmd_options { struct userdef_struct { userdef_struct(const string_type &str=string_type()) :_str(str) {} bool operator==(const userdef_struct &rhs) const { return rhs._str == _str; } string_type _str; }; /* operator>> and operator << are only going to be called in one of two ways, char in the case where CharT is one of {char,char16_t,char32_t} which means UTF and wchar_t which may be UCS2 or something else. Use SFINAE so that this class be be used with all types for testing */ template<typename CharT> inline typename std::enable_if<std::is_same<CharT,char>::value, std::basic_ostream<CharT> &>::type operator<<(std::basic_ostream<CharT> &out, const userdef_struct &ts) { return (out << detail::asUTF8(ts._str)); } template<typename CharT> inline typename std::enable_if<std::is_same<CharT,wchar_t>::value, std::basic_ostream<CharT> &>::type operator<<(std::basic_ostream<CharT> &out, const userdef_struct &ts) { return (out << ts._str); } template<typename CharT> inline typename std::enable_if<std::is_same<CharT,char>::value, std::basic_istream<CharT> &>::type operator>>(std::basic_istream<CharT> &in, userdef_struct &rhs) { std::istreambuf_iterator<CharT> first(in); std::istreambuf_iterator<CharT> last; rhs._str = detail::fromUTF8<::detail::check_char_t>({first,last}); return in; } template<typename CharT> inline typename std::enable_if<std::is_same<CharT,wchar_t>::value, std::basic_istream<CharT> &>::type operator>>(std::basic_istream<CharT> &in, userdef_struct &rhs) { std::istreambuf_iterator<CharT> first(in); std::istreambuf_iterator<CharT> last; rhs._str.assign(first,last); return in; } struct userdef_convert_struct { userdef_convert_struct(const string_type &str=string_type()) :_str(str) {} bool operator==(const userdef_convert_struct &rhs) const { return rhs._str == _str; } string_type _str; }; /* These 4 functions should never be chosen by the compiler, the EZ interface should pick up the specialized 'convert_value<userdef_convert_struct>' structure instead of choosing these. */ template<typename CharT> inline typename std::enable_if<std::is_same<CharT,char>::value, std::basic_ostream<CharT> &>::type operator<<(std::basic_ostream<CharT> &, const userdef_convert_struct &) { throw 1; } template<typename CharT> inline typename std::enable_if<std::is_same<CharT,wchar_t>::value, std::basic_ostream<CharT> &>::type operator<<(std::basic_ostream<CharT> &, const userdef_convert_struct &) { throw 1; } template<typename CharT> inline typename std::enable_if<std::is_same<CharT,char>::value, std::basic_istream<CharT> &>::type operator>>(std::basic_istream<CharT> &, userdef_convert_struct &) { throw 1; } template<typename CharT> inline typename std::enable_if<std::is_same<CharT,wchar_t>::value, std::basic_istream<CharT> &>::type operator>>(std::basic_istream<CharT> &, userdef_convert_struct &) { throw 1; } template<> struct convert_value<userdef_convert_struct> { static userdef_convert_struct from_string(const string_type &str) { return userdef_convert_struct(str); } static void to_string(string_type &str, const userdef_convert_struct &val) { str = val._str; } }; template<typename CharT> std::basic_string<CharT> userdef_transform(const std::basic_string<CharT> &in) { return std::basic_string<CharT>(in.rbegin(),in.rend()); } /** Userdefined conversion function. Convert the contents of the string to a T using operator>>. If all goes well, just replace the value with the one supplied to the constructor. Just used to check that the userdefined version is used. */ template<typename T, typename CharT> struct userdef_cvt { T operator()(const std::basic_string<CharT> &str) const { return co::convert_value<T>::from_string(str+str); } void operator()(std::basic_string<CharT> &str, const T &val) const { co::convert_value<T>::to_string(str,val); str = str+str; } }; /** Userdefined conversion function. Convert the contents of the given value to a string using operator<<. If all goes well, just replace the string with the one supplied to the constructor. Just used to check that the userdefined version is used. */ template<typename T, typename CharT> struct userdef_to_string { userdef_to_string(const std::basic_string<CharT> &val) :_val(val) {} void operator()(std::basic_string<CharT> &str, const T &val) { std::basic_stringstream<CharT> out; if(!(out << val)) throw 1; str = _val; } std::basic_string<CharT> &_val; }; } BOOST_AUTO_TEST_SUITE( value_test_suite ) /** Check fundamental values */ BOOST_AUTO_TEST_CASE( bool_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--bool=1"), _LIT("--bool=0"), _LIT("--bool=true"), _LIT("--bool=false"), }; options = options_group_type{ co::make_option(_LIT("bool"),co::basic_value<bool,detail::check_char_t>(), _LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("bool"),static_cast<bool>(1)), detail::check_value(_LIT("bool"),static_cast<bool>(0)), detail::check_value(_LIT("bool"),static_cast<bool>(1)), detail::check_value(_LIT("bool"),static_cast<bool>(0)), } )); std::vector<const detail::check_char_t *> argv2{ _LIT("--bool=11"), }; BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("11")); } ); return true; } ); std::vector<const detail::check_char_t *> argv3{ _LIT("--bool=foobar"), }; BOOST_CHECK_EXCEPTION(co::parse_arguments(argv3.data(), argv3.data()+argv3.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foobar")); } ); return true; } ); std::vector<const detail::check_char_t *> argv4{ _LIT("--bool=truefoo"), }; BOOST_CHECK_EXCEPTION(co::parse_arguments(argv4.data(), argv4.data()+argv4.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("truefoo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( CharT_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--CharT=a"), }; options = options_group_type{ co::make_option(_LIT("CharT"), co::basic_value<detail::check_char_t,detail::check_char_t>(), _LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("CharT"),static_cast<detail::check_char_t>('a')) } )); std::vector<const detail::check_char_t *> argv2{ _LIT("--CharT=aa"), }; BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("aa")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( short_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--short=11"), }; std::vector<const detail::check_char_t *> argv2{ _LIT("--short=foo"), }; std::vector<const detail::check_char_t *> argv3{ _LIT("--short=3.14"), }; std::vector<const detail::check_char_t *> argv4{ _LIT("--short=11 foo"), }; options = options_group_type{ co::make_option(_LIT("short"), co::basic_value<short,detail::check_char_t>(),_LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("short"),static_cast<short>(11)), } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv3.data(), argv3.data()+argv3.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("3.14")); } ); return true; } ); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv4.data(), argv4.data()+argv4.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("11 foo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( ushort_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--ushort=21"), }; std::vector<const detail::check_char_t *> argv2{ _LIT("--ushort=foo"), }; options = options_group_type{ co::make_option(_LIT("ushort"), co::basic_value<unsigned short,detail::check_char_t>(),_LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("ushort"),static_cast<unsigned short>(21)) } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( int_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--int=12"), }; std::vector<const detail::check_char_t *> argv2{ _LIT("--int=foo"), }; options = options_group_type{ co::make_option(_LIT("int"), co::basic_value<int,detail::check_char_t>(),_LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("int"),static_cast<int>(12)), } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( uint_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--uint=22"), }; std::vector<const detail::check_char_t *> argv2{ _LIT("--uint=foo"), }; options = options_group_type{ co::make_option(_LIT("uint"), co::basic_value<unsigned int,detail::check_char_t>(),_LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("uint"),static_cast<unsigned int>(22)), } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( long_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--long=13"), }; std::vector<const detail::check_char_t *> argv2{ _LIT("--long=foo"), }; options = options_group_type{ co::make_option(_LIT("long"), co::basic_value<long,detail::check_char_t>(),_LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("long"),static_cast<long>(13)), } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( ulong_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--ulong=23"), }; std::vector<const detail::check_char_t *> argv2{ _LIT("--ulong=foo"), }; options = options_group_type{ co::make_option(_LIT("ulong"), co::basic_value<unsigned long,detail::check_char_t>(),_LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("ulong"),static_cast<unsigned long>(23)), } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( longlong_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--longlong=14"), }; std::vector<const detail::check_char_t *> argv2{ _LIT("--longlong=foo"), }; options = options_group_type{ co::make_option(_LIT("longlong"), co::basic_value<long long,detail::check_char_t>(),_LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("longlong"),static_cast<long long>(14)), } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( ulonglong_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--ulonglong=24"), }; std::vector<const detail::check_char_t *> argv2{ _LIT("--ulonglong=foo"), }; options = options_group_type{ co::make_option(_LIT("ulonglong"), co::basic_value<unsigned long long,detail::check_char_t>(), _LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("ulonglong"), static_cast<unsigned long long>(24)), } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( float_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--float=5.1"), }; std::vector<const detail::check_char_t *> argv2{ _LIT("--float=foo"), }; options = options_group_type{ co::make_option(_LIT("float"), co::basic_value<float,detail::check_char_t>(),_LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("float"),static_cast<float>(5.1), detail::essentiallyEqual<float>()), } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( double_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--double=6.1"), }; std::vector<const detail::check_char_t *> argv2{ _LIT("--double=foo"), }; options = options_group_type{ co::make_option(_LIT("double"), co::basic_value<double,detail::check_char_t>(),_LIT("case 6")), }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("double"),static_cast<double>(6.1), detail::essentiallyEqual<double>()), } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); } BOOST_AUTO_TEST_CASE( long_double_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--longdouble=7.1") }; std::vector<const detail::check_char_t *> argv2{ _LIT("--longdouble=foo"), }; options = options_group_type{ co::make_option(_LIT("longdouble"), co::basic_value<long double,detail::check_char_t>(), _LIT("case 6")) }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("longdouble"),static_cast<long double>(7.1), detail::essentiallyEqual<long double>()) } )); BOOST_CHECK_EXCEPTION(co::parse_arguments(argv2.data(), argv2.data()+argv2.size(),options), co::invalid_argument_error, [](const co::invalid_argument_error &ex) { BOOST_CHECK_EXCEPTION(std::rethrow_if_nested(ex), std::invalid_argument, [](const std::invalid_argument &e) { return (e.what() == std::string("foo")); } ); return true; } ); } /** Check all fundamental values for clash */ BOOST_AUTO_TEST_CASE( fundamental_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--CharT=a"), _LIT("--short=11"), _LIT("--ushort=21"), _LIT("--int=12"), _LIT("--uint=22"), _LIT("--long=13"), _LIT("--ulong=23"), _LIT("--longlong=14"), _LIT("--ulonglong=24"), _LIT("--float=5.1"), _LIT("--double=6.1"), _LIT("--longdouble=7.1") }; options = options_group_type{ co::make_option(_LIT("CharT"), co::basic_value<detail::check_char_t,detail::check_char_t>(), _LIT("case 6")), co::make_option(_LIT("short"), co::basic_value<short,detail::check_char_t>(),_LIT("case 6")), co::make_option(_LIT("ushort"), co::basic_value<unsigned short,detail::check_char_t>(),_LIT("case 6")), co::make_option(_LIT("int"), co::basic_value<int,detail::check_char_t>(),_LIT("case 6")), co::make_option(_LIT("uint"), co::basic_value<unsigned int,detail::check_char_t>(),_LIT("case 6")), co::make_option(_LIT("long"), co::basic_value<long,detail::check_char_t>(),_LIT("case 6")), co::make_option(_LIT("ulong"), co::basic_value<unsigned long,detail::check_char_t>(),_LIT("case 6")), co::make_option(_LIT("longlong"), co::basic_value<long long,detail::check_char_t>(),_LIT("case 6")), co::make_option(_LIT("ulonglong"), co::basic_value<unsigned long long,detail::check_char_t>(), _LIT("case 6")), co::make_option(_LIT("float"), co::basic_value<float,detail::check_char_t>(),_LIT("case 6")), co::make_option(_LIT("double"), co::basic_value<double,detail::check_char_t>(),_LIT("case 6")), co::make_option(_LIT("longdouble"), co::basic_value<long double,detail::check_char_t>(), _LIT("case 6")) }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("CharT"),static_cast<detail::check_char_t>('a')), detail::check_value(_LIT("double"),static_cast<double>(6.1), detail::essentiallyEqual<double>()), detail::check_value(_LIT("float"),static_cast<float>(5.1), detail::essentiallyEqual<float>()), detail::check_value(_LIT("int"),static_cast<int>(12)), detail::check_value(_LIT("long"),static_cast<long>(13)), detail::check_value(_LIT("longdouble"),static_cast<long double>(7.1), detail::essentiallyEqual<long double>()), detail::check_value(_LIT("longlong"),static_cast<long long>(14)), detail::check_value(_LIT("short"),static_cast<short>(11)), detail::check_value(_LIT("uint"),static_cast<unsigned int>(22)), detail::check_value(_LIT("ulong"),static_cast<unsigned long>(23)), detail::check_value(_LIT("ulonglong"), static_cast<unsigned long long>(24)), detail::check_value(_LIT("ushort"),static_cast<unsigned short>(21)) } )); } BOOST_AUTO_TEST_CASE( string_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--string=Hello World") }; options = options_group_type{ co::make_option(_LIT("string"), co::basic_value<string_type,detail::check_char_t>(), _LIT("case 6")) }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("string"), static_cast<string_type>(_LIT("Hello World"))), } )); } BOOST_AUTO_TEST_CASE( userdef_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--userdef=Hello World") }; options = options_group_type{ co::make_option(_LIT("userdef"), co::basic_value<co::userdef_struct,detail::check_char_t>(), _LIT("case 6")) }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("userdef"), static_cast<co::userdef_struct>(_LIT("Hello World"))), } )); } BOOST_AUTO_TEST_CASE( userdef_convert_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--userdef=Hello World") }; options = options_group_type{ co::make_option(_LIT("userdef"), co::basic_value<co::userdef_convert_struct,detail::check_char_t>(), _LIT("case 6")) }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("userdef"), static_cast<co::userdef_convert_struct>(_LIT("Hello World"))), } )); } BOOST_AUTO_TEST_CASE( userdef_custom_value_test ) { variable_map_type vm; options_group_type options; std::vector<const detail::check_char_t *> argv{ _LIT("--userdef=Hello World"), _LIT("--userdef2"), }; co::userdef_cvt<string_type,detail::check_char_t> cvt; options = options_group_type{ co::make_option(_LIT("userdef"), co::basic_value<string_type,detail::check_char_t>() .from_string(cvt) .transform(&co::userdef_transform<detail::check_char_t>), _LIT("case 6")), co::make_option(_LIT("userdef2"), co::basic_value<string_type,detail::check_char_t>() .implicit(string_type(_LIT("foobar"))) .to_string(cvt), _LIT("case 6")) }; std::tie(std::ignore,vm) = co::parse_arguments(argv.data(),argv.data()+argv.size(),options); std::cerr << detail::to_string(vm,co::basic_value<string_type,detail::check_char_t>()) << "\n"; BOOST_REQUIRE(detail::vm_check(vm,{ detail::check_value(_LIT("userdef"), static_cast<string_type>(_LIT("dlroW olleHdlroW olleH"))), detail::check_value(_LIT("userdef2"), static_cast<string_type>(_LIT("foobar"))), } )); } BOOST_AUTO_TEST_SUITE_END()
28.546306
152
0.654103
tegtmeye
4964afa29664c500b4ac83efb7ae9be317652649
8,410
cpp
C++
libs/pcl/pcl_examples/interactive_icp/interactive_icp.cpp
quanhua92/learning-notes
a9c50d3955c51bb58f4b012757c550b76c5309ef
[ "Apache-2.0" ]
null
null
null
libs/pcl/pcl_examples/interactive_icp/interactive_icp.cpp
quanhua92/learning-notes
a9c50d3955c51bb58f4b012757c550b76c5309ef
[ "Apache-2.0" ]
null
null
null
libs/pcl/pcl_examples/interactive_icp/interactive_icp.cpp
quanhua92/learning-notes
a9c50d3955c51bb58f4b012757c550b76c5309ef
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/registration/icp.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/console/time.h> // TicToc #include <pcl/filters/passthrough.h> #include <pcl/filters/voxel_grid.h> typedef pcl::PointXYZ PointT; typedef pcl::PointCloud<PointT> PointCloudT; bool next_iteration = false; void print4x4Matrix(const Eigen::Matrix4d & matrix) { printf("Rotation matrix :\n"); printf(" | %6.3f %6.3f %6.3f | \n", matrix(0, 0), matrix(0, 1), matrix(0, 2)); printf("R = | %6.3f %6.3f %6.3f | \n", matrix(1, 0), matrix(1, 1), matrix(1, 2)); printf(" | %6.3f %6.3f %6.3f | \n", matrix(2, 0), matrix(2, 1), matrix(2, 2)); printf("Translation vector :\n"); printf("t = < %6.3f, %6.3f, %6.3f >\n\n", matrix(0, 3), matrix(1, 3), matrix(2, 3)); } void keyboardEventOccurred(const pcl::visualization::KeyboardEvent& event, void* nothing) { if (event.getKeySym() == "space" && event.keyDown()) next_iteration = true; } PointCloudT::Ptr downsampleCloud(PointCloudT::Ptr inputCloud, double voxel_size) { PointCloudT::Ptr cloud_filtered(new PointCloudT); pcl::VoxelGrid<PointT> downsampler; downsampler.setInputCloud(inputCloud); downsampler.setLeafSize(voxel_size, voxel_size, voxel_size); downsampler.filter(*cloud_filtered); return cloud_filtered; } int main(int argc, char* argv[]) { // The point clouds we will be using PointCloudT::Ptr cloud_in(new PointCloudT); // Original point cloud PointCloudT::Ptr cloud_tr(new PointCloudT); // Transformed point cloud PointCloudT::Ptr cloud_icp(new PointCloudT); // ICP output point cloud // Checking program arguments if (argc < 2) { printf("Usage :\n"); printf("\t\t%s file.pcd number_of_ICP_iterations\n", argv[0]); PCL_ERROR("Provide one pcd file.\n"); return (-1); } int iterations = 1; // Default number of ICP iterations if (argc > 2) { // If the user passed the number of iteration as an argument iterations = atoi(argv[2]); if (iterations < 1) { PCL_ERROR("Number of initial iterations must be >= 1\n"); return (-1); } } pcl::console::TicToc time; time.tic(); if (pcl::io::loadPCDFile(argv[1], *cloud_in) < 0) { PCL_ERROR("Error loading cloud %s.\n", argv[1]); return (-1); } std::cout << "\nLoaded file " << argv[1] << " (" << cloud_in->size() << " points) in " << time.toc() << " ms\n" << std::endl; pcl::io::loadPCDFile("C:\\data\\model_mana_05_10.pcd", *cloud_icp); // remove the bottom of the model PointCloudT::Ptr extracted_cloud(new PointCloudT()); pcl::PassThrough<PointT> pass; pass.setInputCloud(cloud_in); pass.setFilterFieldName("z"); pass.setFilterLimits(0.05, 0.9); // 0.1 = 10cm // input-mana //pass.setFilterLimits(0.295, 0.3); // 0.1 = 10cm // input-box pass.filter(*extracted_cloud); *cloud_in = *extracted_cloud; pass.setInputCloud(cloud_icp); pass.filter(*extracted_cloud); *cloud_icp = *extracted_cloud; //PointCloudT::Ptr downsample_cloud = downsampleCloud(cloud_icp, 0.01); cloud_in = downsampleCloud(cloud_in, 0.02); cloud_icp = downsampleCloud(cloud_icp, 0.02); //pass.setFilterLimits(0.02, 0.45); //pass.setInputCloud(downsample_cloud); //pass.filter(*extracted_cloud); //*downsample_cloud = *extracted_cloud; ////// Defining a rotation matrix and translation vector Eigen::Matrix4d transformation_matrix = Eigen::Matrix4d::Identity(); ////// A rotation matrix (see https://en.wikipedia.org/wiki/Rotation_matrix) //double theta = M_PI / 16; // The angle of rotation in radians //transformation_matrix(0, 0) = cos(theta); //transformation_matrix(0, 1) = -sin(theta); //transformation_matrix(1, 0) = sin(theta); //transformation_matrix(1, 1) = cos(theta); //// A translation on Z axis (0.4 meters) //transformation_matrix(2, 3) = 0.2; //// Display in terminal the transformation matrix //std::cout << "Applying this rigid transformation to: cloud_in -> cloud_icp" << std::endl; //print4x4Matrix(transformation_matrix); //// Executing the transformation //pcl::transformPointCloud(*downsample_cloud, *cloud_icp, transformation_matrix); *cloud_tr = *cloud_icp; // We backup cloud_icp into cloud_tr for later use // The Iterative Closest Point algorithm time.tic(); pcl::IterativeClosestPoint<PointT, PointT> icp; icp.setMaximumIterations(iterations); icp.setInputSource(cloud_icp); icp.setInputTarget(cloud_in); icp.align(*cloud_icp); std::cout << "Applied " << iterations << " ICP iteration(s) in " << time.toc() << " ms" << std::endl; if (icp.hasConverged()) { std::cout << "\nICP has converged, score is " << icp.getFitnessScore() << std::endl; std::cout << "\nICP transformation " << iterations << " : cloud_icp -> cloud_in" << std::endl; transformation_matrix = icp.getFinalTransformation().cast<double>(); print4x4Matrix(transformation_matrix); } else { PCL_ERROR("\nICP has not converged.\n"); return (-1); } // Visualization pcl::visualization::PCLVisualizer viewer("ICP demo"); // Create two verticaly separated viewports int v1(0); int v2(1); viewer.createViewPort(0.0, 0.0, 0.5, 1.0, v1); viewer.createViewPort(0.5, 0.0, 1.0, 1.0, v2); // The color we will be using float bckgr_gray_level = 0.0; // Black float txt_gray_lvl = 1.0 - bckgr_gray_level; // Original point cloud is white pcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_in_color_h(cloud_in, (int)255 * txt_gray_lvl, (int)255 * txt_gray_lvl, (int)255 * txt_gray_lvl); viewer.addPointCloud(cloud_in, cloud_in_color_h, "cloud_in_v1", v1); viewer.addPointCloud(cloud_in, cloud_in_color_h, "cloud_in_v2", v2); // Transformed point cloud is green pcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_tr_color_h(cloud_tr, 20, 180, 20); viewer.addPointCloud(cloud_tr, cloud_tr_color_h, "cloud_tr_v1", v1); // ICP aligned point cloud is red pcl::visualization::PointCloudColorHandlerCustom<PointT> cloud_icp_color_h(cloud_icp, 180, 20, 20); viewer.addPointCloud(cloud_icp, cloud_icp_color_h, "cloud_icp_v2", v2); // Adding text descriptions in each viewport viewer.addText("White: Original point cloud\nGreen: Matrix transformed point cloud", 10, 15, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "icp_info_1", v1); viewer.addText("White: Original point cloud\nRed: ICP aligned point cloud", 10, 15, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "icp_info_2", v2); std::stringstream ss; ss << iterations; std::string iterations_cnt = "ICP iterations = " + ss.str(); viewer.addText(iterations_cnt, 10, 60, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "iterations_cnt", v2); // Set background color viewer.setBackgroundColor(bckgr_gray_level, bckgr_gray_level, bckgr_gray_level, v1); viewer.setBackgroundColor(bckgr_gray_level, bckgr_gray_level, bckgr_gray_level, v2); // Set camera position and orientation viewer.setCameraPosition(-3.68332, 2.94092, 5.71266, 0.289847, 0.921947, -0.256907, 0); viewer.setSize(1280, 1024); // Visualiser window size // Register keyboard callback : viewer.registerKeyboardCallback(&keyboardEventOccurred, (void*)NULL); // Display the visualiser while (!viewer.wasStopped()) { viewer.spinOnce(); // The user pressed "space" : if (next_iteration) { // The Iterative Closest Point algorithm time.tic(); icp.align(*cloud_icp); std::cout << "Applied 1 ICP iteration in " << time.toc() << " ms" << std::endl; if (icp.hasConverged()) { printf("\033[11A"); // Go up 11 lines in terminal output. printf("\nICP has converged, score is %+.0e\n", icp.getFitnessScore()); std::cout << "\nICP transformation " << ++iterations << " : cloud_icp -> cloud_in" << std::endl; transformation_matrix *= icp.getFinalTransformation().cast<double>(); // WARNING /!\ This is not accurate! For "educational" purpose only! print4x4Matrix(transformation_matrix); // Print the transformation between original pose and current pose ss.str(""); ss << iterations; std::string iterations_cnt = "ICP iterations = " + ss.str(); viewer.updateText(iterations_cnt, 10, 60, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "iterations_cnt"); viewer.updatePointCloud(cloud_icp, cloud_icp_color_h, "cloud_icp_v2"); } else { PCL_ERROR("\nICP has not converged.\n"); return (-1); } } next_iteration = false; } return (0); }
34.896266
158
0.701546
quanhua92
4966329076c01844f456cd167a21e0a247c82b4c
1,651
cpp
C++
aws-cpp-sdk-config/source/model/DescribeRetentionConfigurationsRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-config/source/model/DescribeRetentionConfigurationsRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-config/source/model/DescribeRetentionConfigurationsRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/config/model/DescribeRetentionConfigurationsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::ConfigService::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DescribeRetentionConfigurationsRequest::DescribeRetentionConfigurationsRequest() : m_retentionConfigurationNamesHasBeenSet(false), m_nextTokenHasBeenSet(false) { } Aws::String DescribeRetentionConfigurationsRequest::SerializePayload() const { JsonValue payload; if(m_retentionConfigurationNamesHasBeenSet) { Array<JsonValue> retentionConfigurationNamesJsonList(m_retentionConfigurationNames.size()); for(unsigned retentionConfigurationNamesIndex = 0; retentionConfigurationNamesIndex < retentionConfigurationNamesJsonList.GetLength(); ++retentionConfigurationNamesIndex) { retentionConfigurationNamesJsonList[retentionConfigurationNamesIndex].AsString(m_retentionConfigurationNames[retentionConfigurationNamesIndex]); } payload.WithArray("RetentionConfigurationNames", std::move(retentionConfigurationNamesJsonList)); } if(m_nextTokenHasBeenSet) { payload.WithString("NextToken", m_nextToken); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection DescribeRetentionConfigurationsRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "StarlingDoveService.DescribeRetentionConfigurations")); return headers; }
29.482143
173
0.806784
Neusoft-Technology-Solutions
49675f3a7b5b82e8e61e4289a0e0efb34499f963
2,609
cxx
C++
testing/rtkxradtest.cxx
ldqcarbon/RTK
88df8ed953805aca3c5a73c22cb940164e7cc296
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
testing/rtkxradtest.cxx
ldqcarbon/RTK
88df8ed953805aca3c5a73c22cb940164e7cc296
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
testing/rtkxradtest.cxx
ldqcarbon/RTK
88df8ed953805aca3c5a73c22cb940164e7cc296
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
#include "rtkTest.h" #include "rtkProjectionsReader.h" #include "rtkMacro.h" #include "rtkXRadGeometryReader.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include <itkRegularExpressionSeriesFileNames.h> /** * \file rtkxradtest.cxx * * \brief Functional tests for classes managing X-Rad data * * This test reads a projection and the geometry of an acquisition from a * X-Rad acquisition and compares it to the expected results, which are * read from a baseline image in the MetaIO file format and a geometry file in * the RTK format, respectively. * * \author Simon Rit */ int main(int, char** ) { // Elekta geometry rtk::XRadGeometryReader::Pointer geoTargReader; geoTargReader = rtk::XRadGeometryReader::New(); geoTargReader->SetImageFileName( std::string(RTK_DATA_ROOT) + std::string("/Input/XRad/SolidWater_HiGain1x1.header") ); TRY_AND_EXIT_ON_ITK_EXCEPTION( geoTargReader->UpdateOutputData() ); // Reference geometry rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geoRefReader; geoRefReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geoRefReader->SetFilename( std::string(RTK_DATA_ROOT) + std::string("/Baseline/XRad/geometry.xml") ); TRY_AND_EXIT_ON_ITK_EXCEPTION( geoRefReader->GenerateOutputInformation() ) // 1. Check geometries CheckGeometries(geoTargReader->GetGeometry(), geoRefReader->GetOutputObject() ); // ******* COMPARING projections ******* typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > ImageType; // Elekta projections reader typedef rtk::ProjectionsReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); std::vector<std::string> fileNames; fileNames.push_back( std::string(RTK_DATA_ROOT) + std::string("/Input/XRad/SolidWater_HiGain1x1_firstProj.header") ); reader->SetFileNames( fileNames ); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() ); // Reference projections reader ReaderType::Pointer readerRef = ReaderType::New(); fileNames.clear(); fileNames.push_back( std::string(RTK_DATA_ROOT) + std::string("/Baseline/XRad/attenuation.mha") ); readerRef->SetFileNames( fileNames ); TRY_AND_EXIT_ON_ITK_EXCEPTION(readerRef->Update()); // 2. Compare read projections CheckImageQuality< ImageType >(reader->GetOutput(), readerRef->GetOutput(), 1.6e-7, 100, 2.0); // If both succeed std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; }
37.271429
96
0.720583
ldqcarbon
4968673bfa0f63dcef4200d781306c8c9558e714
997
cpp
C++
8PRO128-TP3/Cube.cpp
Hexzhe/8PRO128-TP3
24dc226465c7e216752ded07592a013e88e7e3e2
[ "MIT" ]
null
null
null
8PRO128-TP3/Cube.cpp
Hexzhe/8PRO128-TP3
24dc226465c7e216752ded07592a013e88e7e3e2
[ "MIT" ]
null
null
null
8PRO128-TP3/Cube.cpp
Hexzhe/8PRO128-TP3
24dc226465c7e216752ded07592a013e88e7e3e2
[ "MIT" ]
null
null
null
#include "Cube.h" Cube::Cube() : Carre() { } Cube::Cube(double c) : Carre(c) { } double Cube::aire() const { return 6 * Carre::aire(); } double Cube::face() const { return Carre::aire(); } double Cube::volume() const { return pow(Carre::largeur, 3); } void Cube::afficher(std::ostream& os) const { os << "Cube:" << std::endl; os << this->getEntete() << std::endl; os << std::setw(9) << std::setprecision(2) << std::fixed << this->Carre::largeur << " "; os << std::setw(9) << std::setprecision(2) << std::fixed << this->aire() << " "; os << std::setw(9) << std::setprecision(2) << std::fixed << this->face() << " "; os << std::setw(9) << std::setprecision(2) << std::fixed << this->volume(); } std::string Cube::getEntete() { return "cote aire face vol"; } std::istream& operator>>(std::istream& is, Cube& cube) { is >> cube.largeur >> cube.longueur; return is; } std::ostream& operator<<(std::ostream& os, const Cube& cube) { cube.afficher(os); return os; }
18.811321
89
0.584754
Hexzhe
496c468c85979cecf5074f43eb9a6acc29047143
435
cpp
C++
Trees/LeftView.cpp
rajatenzyme/Coding-Journey-
65a0570153b7e3393d78352e78fb2111223049f3
[ "MIT" ]
null
null
null
Trees/LeftView.cpp
rajatenzyme/Coding-Journey-
65a0570153b7e3393d78352e78fb2111223049f3
[ "MIT" ]
null
null
null
Trees/LeftView.cpp
rajatenzyme/Coding-Journey-
65a0570153b7e3393d78352e78fb2111223049f3
[ "MIT" ]
null
null
null
vector<int> leftView(Node *root) { // Your code here vector<int> v; if(!root) return v; queue<Node *> q; q.push(root); while(!q.empty()) { v.push_back(q.front()->data); int n= q.size(); while(n--) { Node* curr = q.front(); q.pop(); if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); } } return v; }
16.111111
36
0.455172
rajatenzyme
496e7a5477cb415b4d3b490873c1fd81bdcb341c
1,394
hpp
C++
src/visual-scripting/processors/math/trigonometric/TrigonometricProcessors.hpp
inexorgame/entity-system
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
19
2018-10-11T09:19:48.000Z
2020-04-19T16:36:58.000Z
src/visual-scripting/processors/math/trigonometric/TrigonometricProcessors.hpp
inexorgame-obsolete/entity-system-inactive
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
132
2018-07-28T12:30:54.000Z
2020-04-25T23:05:33.000Z
src/visual-scripting/processors/math/trigonometric/TrigonometricProcessors.hpp
inexorgame-obsolete/entity-system-inactive
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
3
2019-03-02T16:19:23.000Z
2020-02-18T05:15:29.000Z
#pragma once #include "visual-scripting/processors/math/trigonometric/CosProcessor.hpp" #include "visual-scripting/processors/math/trigonometric/SinProcessor.hpp" #include "visual-scripting/processors/math/trigonometric/TanProcessor.hpp" namespace inexor::visual_scripting { using SinProcessorPtr = std::shared_ptr<SinProcessor>; using CosProcessorPtr = std::shared_ptr<CosProcessor>; using TanProcessorPtr = std::shared_ptr<TanProcessor>; /// @class TrigonometricProcessors /// @brief Management of the trigonometric processors. class TrigonometricProcessors : public LifeCycleComponent { public: /// @brief Constructs the trigonometric processors. /// @note The dependencies of this class will be injected automatically. /// @param sin_processor The sin generator. /// @param cos_processor The cos generator. /// @param tan_processor The tan generator. TrigonometricProcessors(SinProcessorPtr sin_processor, CosProcessorPtr cos_processor, TanProcessorPtr tan_processor); /// Destructor. ~TrigonometricProcessors(); /// Returns the name of the component std::string get_component_name() override; private: /// The sin generator. SinProcessorPtr sin_processor; /// The cos generator. CosProcessorPtr cos_processor; /// The tan generator. TanProcessorPtr tan_processor; }; } // namespace inexor::visual_scripting
32.418605
121
0.763271
inexorgame
4974fd6e1e94bf2869e15e129f5e0999fed1378b
1,711
cpp
C++
client/main.cpp
name1e5s/Trace-It
bb42ed21dc16b3fb5bfed3cb5592c9232c43ace2
[ "WTFPL" ]
null
null
null
client/main.cpp
name1e5s/Trace-It
bb42ed21dc16b3fb5bfed3cb5592c9232c43ace2
[ "WTFPL" ]
null
null
null
client/main.cpp
name1e5s/Trace-It
bb42ed21dc16b3fb5bfed3cb5592c9232c43ace2
[ "WTFPL" ]
null
null
null
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QQmlEngine> #include <QQuickStyle> #include <client.h> #include <table_model_user.h> #include <table_model_word.h> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); if (Client::Instance().SocketClient::connect()) { UserTableModel userTableModel; userTableModel.setColumn(5); WordTableModel wordTableModel; wordTableModel.setColumn(3); qRegisterMetaType<QVector<QVector<QString>>>("QVector<QVector<QString>>"); QObject::connect(&Client::Instance(), &Client::updateUserTable, &userTableModel, &UserTableModel::onModelUpdate); QObject::connect(&Client::Instance(), &Client::updateWordTable, &wordTableModel, &WordTableModel::onModelUpdate); userTableModel.init(); wordTableModel.init(); QQuickStyle::setStyle("Material"); QQmlApplicationEngine engine; qmlRegisterType<Client>("com.name1e5s.game", 1, 0, "Client"); engine.rootContext()->setContextProperty("game_client", &Client::Instance()); engine.rootContext()->setContextProperty("userTableModel", &userTableModel); engine.rootContext()->setContextProperty("wordTableModel", &wordTableModel); qmlRegisterType<UserTableModel>("com.name1e5s.game", 1, 0, "UserTableModel"); qmlRegisterType<WordTableModel>("com.name1e5s.game", 1, 0, "WordTableModel"); engine.load(QUrl(QStringLiteral("qrc:/ui/ui/MemoryGame.qml"))); return app.exec(); } else { qDebug() << "Connect to server failed."; return 1; } }
38.886364
80
0.660432
name1e5s
497550b899bbf298f8b45c9805b7c9bfccd81308
4,094
cpp
C++
Engine/source/gui/editor/guiSeparatorCtrl.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
46
2015-01-05T17:34:43.000Z
2022-01-04T04:03:09.000Z
Engine/source/gui/editor/guiSeparatorCtrl.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
10
2015-01-20T23:14:46.000Z
2019-04-05T22:04:15.000Z
Engine/source/gui/editor/guiSeparatorCtrl.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
9
2015-08-08T18:46:06.000Z
2021-02-01T13:53:20.000Z
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #include "platform/platform.h" #include "gui/editor/guiSeparatorCtrl.h" #include "gfx/gfxDevice.h" #include "gfx/gfxDrawUtil.h" #include "console/console.h" #include "console/consoleTypes.h" #include "gui/core/guiCanvas.h" #include "gui/core/guiDefaultControlRender.h" IMPLEMENT_CONOBJECT(GuiSeparatorCtrl); ConsoleDocClass( GuiSeparatorCtrl, "@brief A control that renders a horizontal or vertical separator with " "an optional text label (horizontal only)\n\n" "@tsexample\n" "new GuiSeparatorCtrl()\n" "{\n" " profile = \"GuiDefaultProfile\";\n" " position = \"505 0\";\n" " extent = \"10 17\";\n" " minExtent = \"10 17\";\n" " canSave = \"1\";\n" " visible = \"1\";\n" " horizSizing = \"left\";\n" "};\n" "@endtsexample\n\n" "@ingroup GuiControls\n"); ImplementEnumType( GuiSeparatorType, "GuiSeparatorCtrl orientations\n\n" "@ingroup GuiControls" ) { GuiSeparatorCtrl::separatorTypeVertical, "Vertical" }, { GuiSeparatorCtrl::separatorTypeHorizontal,"Horizontal" } EndImplementEnumType; //-------------------------------------------------------------------------- GuiSeparatorCtrl::GuiSeparatorCtrl() : GuiControl() { mInvisible = false; mTextLeftMargin = 0; mMargin = 2; setExtent( 12, 35 ); mSeparatorType = GuiSeparatorCtrl::separatorTypeVertical; } //-------------------------------------------------------------------------- void GuiSeparatorCtrl::initPersistFields() { addField("caption", TypeRealString, Offset(mText, GuiSeparatorCtrl), "Optional text label to display." ); addField("type", TYPEID< separatorTypeOptions >(), Offset(mSeparatorType, GuiSeparatorCtrl), "Orientation of separator." ); addField("borderMargin", TypeS32, Offset(mMargin, GuiSeparatorCtrl)); addField("invisible", TypeBool, Offset(mInvisible, GuiSeparatorCtrl));// Nonsense. Should use GuiControl's visibility. addField("leftMargin", TypeS32, Offset(mTextLeftMargin, GuiSeparatorCtrl), "Left margin of text label." ); Parent::initPersistFields(); } //-------------------------------------------------------------------------- void GuiSeparatorCtrl::onRender(Point2I offset, const RectI &updateRect) { Parent::onRender( offset, updateRect ); if( mInvisible ) return; if( mText.isNotEmpty() && mSeparatorType != separatorTypeVertical ) { // If text is present and we have a left margin, then draw some separator, then the // text, and then the rest of the separator. S32 posx = offset.x + mMargin; S32 fontheight = mProfile->mFont->getHeight(); S32 seppos = (fontheight - 2) / 2 + offset.y; if( mTextLeftMargin > 0 ) { RectI rect( Point2I( posx, seppos ), Point2I( mTextLeftMargin, 2 ) ); renderSlightlyLoweredBox(rect, mProfile); posx += mTextLeftMargin; } GFX->getDrawUtil()->setBitmapModulation( mProfile->mFontColor ); posx = GFX->getDrawUtil()->drawText(mProfile->mFont, Point2I(posx,offset.y), mText, mProfile->mFontColors); RectI rect( Point2I( posx, seppos ), Point2I( getWidth() - posx + offset.x, 2 ) ); // Space text and separator a bit apart at right end. rect.point.x += 2; rect.extent.x -= 2; if( rect.extent.x > 0 ) renderSlightlyLoweredBox( rect, mProfile ); } else { if( mSeparatorType == separatorTypeHorizontal ) { S32 seppos = getHeight() / 2 + offset.y; RectI rect(Point2I(offset.x + mMargin ,seppos),Point2I(getWidth() - (mMargin * 2),2)); renderSlightlyLoweredBox(rect, mProfile); } else { S32 seppos = getWidth() / 2 + offset.x; RectI rect(Point2I(seppos, offset.y + mMargin),Point2I(2, getHeight() - (mMargin * 2))); renderSlightlyLoweredBox(rect, mProfile); } } renderChildControls(offset, updateRect); }
33.016129
134
0.616268
fr1tz
4977978f702f2eed6831ad916e1378d2eeff5c35
1,043
hpp
C++
include/usb_asio/asio.hpp
MiSo1289/usb-asio
cd6aac7b9bfad1c617aa0e6d1eefeea8b00cfcdf
[ "MIT" ]
47
2020-08-24T17:53:04.000Z
2022-03-11T16:03:22.000Z
include/usb_asio/asio.hpp
MiSo1289/usb-asio
cd6aac7b9bfad1c617aa0e6d1eefeea8b00cfcdf
[ "MIT" ]
null
null
null
include/usb_asio/asio.hpp
MiSo1289/usb-asio
cd6aac7b9bfad1c617aa0e6d1eefeea8b00cfcdf
[ "MIT" ]
null
null
null
#pragma once #ifdef USB_ASIO_USE_STANDALONE_ASIO #include <system_error> #include <asio/any_io_executor.hpp> #include <asio/async_result.hpp> #include <asio/buffer.hpp> #include <asio/execution_context.hpp> #include <asio/io_context.hpp> #include <asio/post.hpp> #else #include <boost/asio/any_io_executor.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/post.hpp> #include <boost/system/error_code.hpp> #include <boost/system/system_error.hpp> #endif namespace usb_asio { #ifdef USB_ASIO_USE_STANDALONE_ASIO namespace asio = ::asio; using error_code = std::error_code; using error_category = std::error_category; using system_error = std::system_error; #else namespace asio = boost::asio; using error_code = boost::system::error_code; using error_category = boost::system::error_category; using system_error = boost::system::system_error; #endif } // namespace usb_asio
24.255814
57
0.759348
MiSo1289
4977abe2470f73cf156380faef231cc60f016cdb
618
cpp
C++
Junior_Core/Src/Source/GameSystem.cpp
DeltaGoldenFlag/JuniorEngine
9581f863d5bd412a4ab48b7ea893151798829856
[ "BSD-3-Clause" ]
1
2019-06-13T00:14:02.000Z
2019-06-13T00:14:02.000Z
Junior_Core/Src/Source/GameSystem.cpp
DeltaGoldenFlag/JuniorEngine
9581f863d5bd412a4ab48b7ea893151798829856
[ "BSD-3-Clause" ]
null
null
null
Junior_Core/Src/Source/GameSystem.cpp
DeltaGoldenFlag/JuniorEngine
9581f863d5bd412a4ab48b7ea893151798829856
[ "BSD-3-Clause" ]
null
null
null
/* * Author: David Wong * Email: david.wongcascante@digipen.edu * File name: GameSystem.cpp * Description: Defines a general manner to organize all the systems * Created: 18-Dec-2018 * Last Modified: 18-Dec-2018 */ // Includes #include "GameSystem.h" #include <iostream> // Output stream // Public Member Functions namespace Junior { GameSystem::GameSystem(const char* name) : name_(name) {} void GameSystemAssert(bool success, const char* errorMessage) { if (!success) { std::cout << "[ERROR]: " << errorMessage << std::endl; } } const char* GameSystem::GetName() const { return name_; } }
18.176471
67
0.687702
DeltaGoldenFlag
4978a415b1118ac8fe42ba3a6e56d732ae933c64
459
hpp
C++
src/algorithms/euler/problem9.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2020-07-31T14:13:56.000Z
2021-02-03T09:51:43.000Z
src/algorithms/euler/problem9.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
28
2015-09-22T07:38:21.000Z
2018-10-02T11:00:58.000Z
src/algorithms/euler/problem9.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2018-10-11T14:10:50.000Z
2021-02-27T08:53:50.000Z
#ifndef PROBLEM9_H_ #define PROBLEM9_H_ #include "problem.hpp" // Problem 9: // A Pythagorean triplet is a set of three natural numbers, a < b < c, // for which a^2 + b^2 = c^2 // For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. // There exists exactly one Pythagorean triplet for which a + b + c = 1000. // Find the product abc. class Problem9 : public Problem { // == METHODS == private: virtual void DoSolve() override; }; #endif /* PROBLEM9_H_ */
20.863636
75
0.64488
iamantony
4979ee93a9e60b56119769aeaf61c4f545e3f578
6,761
hpp
C++
src/lib/nas/ie1.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
16
2020-04-16T02:07:37.000Z
2020-07-23T10:48:27.000Z
src/lib/nas/ie1.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
8
2020-07-13T17:11:35.000Z
2020-08-03T16:46:31.000Z
src/lib/nas/ie1.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
9
2020-03-04T15:05:08.000Z
2020-07-30T06:18:18.000Z
// // This file is a part of UERANSIM open source project. // Copyright (c) 2021 ALİ GÜNGÖR. // // The software and all associated files are licensed under GPL-3.0 // and subject to the terms and conditions defined in LICENSE file. // #pragma once #include "base.hpp" #include "enums.hpp" #include <utils/octet_string.hpp> #include <utils/octet_view.hpp> namespace nas { struct IE5gsIdentityType : InformationElement1 { EIdentityType value{}; IE5gsIdentityType() = default; explicit IE5gsIdentityType(EIdentityType value); static IE5gsIdentityType Decode(int val); static int Encode(const IE5gsIdentityType &ie); }; struct IE5gsRegistrationType : InformationElement1 { EFollowOnRequest followOnRequestPending{}; ERegistrationType registrationType{}; IE5gsRegistrationType() = default; IE5gsRegistrationType(EFollowOnRequest followOnRequestPending, ERegistrationType registrationType); static IE5gsRegistrationType Decode(int val); static int Encode(const IE5gsRegistrationType &ie); }; struct IEAccessType : InformationElement1 { EAccessType value{}; IEAccessType() = default; explicit IEAccessType(EAccessType value); static IEAccessType Decode(int val); static int Encode(const IEAccessType &ie); }; struct IEAllowedSscMode : InformationElement1 { ESsc1 ssc1{}; ESsc2 ssc2{}; ESsc3 ssc3{}; IEAllowedSscMode() = default; IEAllowedSscMode(ESsc1 ssc1, ESsc2 ssc2, ESsc3 ssc3); static IEAllowedSscMode Decode(int val); static int Encode(const IEAllowedSscMode &ie); }; struct IEAlwaysOnPduSessionIndication : InformationElement1 { EAlwaysOnPduSessionIndication value{}; IEAlwaysOnPduSessionIndication() = default; explicit IEAlwaysOnPduSessionIndication(EAlwaysOnPduSessionIndication value); static IEAlwaysOnPduSessionIndication Decode(int val); static int Encode(const IEAlwaysOnPduSessionIndication &ie); }; struct IEAlwaysOnPduSessionRequested : InformationElement1 { EAlwaysOnPduSessionRequested value{}; IEAlwaysOnPduSessionRequested() = default; explicit IEAlwaysOnPduSessionRequested(EAlwaysOnPduSessionRequested value); static IEAlwaysOnPduSessionRequested Decode(int val); static int Encode(const IEAlwaysOnPduSessionRequested &ie); }; struct IEConfigurationUpdateIndication : InformationElement1 { EAcknowledgement ack{}; ERegistrationRequested red{}; IEConfigurationUpdateIndication() = default; IEConfigurationUpdateIndication(EAcknowledgement ack, ERegistrationRequested red); static IEConfigurationUpdateIndication Decode(int val); static int Encode(const IEConfigurationUpdateIndication &ie); }; struct IEDeRegistrationType : InformationElement1 { EDeRegistrationAccessType accessType{}; EReRegistrationRequired reRegistrationRequired{}; // This bit is spare in UE to Network direction ESwitchOff switchOff{}; IEDeRegistrationType() = default; IEDeRegistrationType(EDeRegistrationAccessType accessType, EReRegistrationRequired reRegistrationRequired, ESwitchOff switchOff); static IEDeRegistrationType Decode(int val); static int Encode(const IEDeRegistrationType &ie); }; struct IEImeiSvRequest : InformationElement1 { EImeiSvRequest imeiSvRequest{}; IEImeiSvRequest() = default; explicit IEImeiSvRequest(EImeiSvRequest imeiSvRequest); static IEImeiSvRequest Decode(int val); static int Encode(const IEImeiSvRequest &ie); }; struct IEMicoIndication : InformationElement1 { ERegistrationAreaAllocationIndication raai{}; IEMicoIndication() = default; explicit IEMicoIndication(ERegistrationAreaAllocationIndication raai); static IEMicoIndication Decode(int val); static int Encode(const IEMicoIndication &ie); }; struct IENasKeySetIdentifier : InformationElement1 { static constexpr const int NOT_AVAILABLE_OR_RESERVED = 0b111; ETypeOfSecurityContext tsc{}; int ksi = NOT_AVAILABLE_OR_RESERVED; IENasKeySetIdentifier() = default; IENasKeySetIdentifier(ETypeOfSecurityContext tsc, int ksi); static IENasKeySetIdentifier Decode(int val); static int Encode(const IENasKeySetIdentifier &ie); }; struct IENetworkSlicingIndication : InformationElement1 { ENetworkSlicingSubscriptionChangeIndication nssci{}; // This is spare if dir is UE->NW EDefaultConfiguredNssaiIndication dcni{}; // This is spare if dir is NW->UE IENetworkSlicingIndication() = default; IENetworkSlicingIndication(ENetworkSlicingSubscriptionChangeIndication nssci, EDefaultConfiguredNssaiIndication dcni); static IENetworkSlicingIndication Decode(int val); static int Encode(const IENetworkSlicingIndication &ie); }; struct IENssaiInclusionMode : InformationElement1 { ENssaiInclusionMode nssaiInclusionMode{}; IENssaiInclusionMode() = default; explicit IENssaiInclusionMode(ENssaiInclusionMode nssaiInclusionMode); static IENssaiInclusionMode Decode(int val); static int Encode(const IENssaiInclusionMode &ie); }; struct IEPayloadContainerType : InformationElement1 { EPayloadContainerType payloadContainerType{}; IEPayloadContainerType() = default; explicit IEPayloadContainerType(EPayloadContainerType payloadContainerType); static IEPayloadContainerType Decode(int val); static int Encode(const IEPayloadContainerType &ie); }; struct IEPduSessionType : InformationElement1 { EPduSessionType pduSessionType{}; IEPduSessionType() = default; explicit IEPduSessionType(EPduSessionType pduSessionType); static IEPduSessionType Decode(int val); static int Encode(const IEPduSessionType &ie); }; struct IERequestType : InformationElement1 { ERequestType requestType{}; IERequestType() = default; explicit IERequestType(ERequestType requestType); static IERequestType Decode(int val); static int Encode(const IERequestType &ie); }; struct IEServiceType : InformationElement1 { EServiceType serviceType{}; IEServiceType() = default; explicit IEServiceType(EServiceType serviceType); static IEServiceType Decode(int val); static int Encode(const IEServiceType &ie); }; struct IESmsIndication : InformationElement1 { ESmsAvailabilityIndication sai{}; IESmsIndication() = default; explicit IESmsIndication(ESmsAvailabilityIndication sai); static IESmsIndication Decode(int val); static int Encode(const IESmsIndication &ie); }; struct IESscMode : InformationElement1 { ESscMode sscMode{}; IESscMode() = default; explicit IESscMode(ESscMode sscMode); static IESscMode Decode(int val); static int Encode(const IESscMode &ie); }; } // namespace nas
28.053942
110
0.764976
aligungr
497b0117b90fb61451736afa5d65667a4a9dcd61
1,804
cpp
C++
Antiplagiat/Antiplagiat/bin/Debug/12751.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
1
2015-07-04T14:45:32.000Z
2015-07-04T14:45:32.000Z
Antiplagiat/Antiplagiat/bin/Debug/12751.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
null
null
null
Antiplagiat/Antiplagiat/bin/Debug/12751.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cmath> #include <vector> #include <map> #include <cstring> #include <string> #include <cstdlib> #include <algorithm> #include <utility> #include <sstream> #include <set> #include <time.h> #include <memory.h> #include <queue> #include <bitset> #include <functional> using namespace std; #define all(x) (x).begin(),(x).end() #define sz(a) ((int) (a).size()) #define pb push_back #define SORT(x) sort(all(x)) #define UNIQUE(x) SORT(x),(x).resize(unique(all(x))-(x).begin()) #define FOR(i,a,b) for(int i = (a); i < (b); ++i) #define FORD(i,a,b) for (int i = (a); i >= (b); --i) #define REP(i, n) FOR(i, 0, n) #define X first #define Y second typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<pii> vpii; typedef vector<vi> vvi; typedef long long ll; const double pi = acos(-1.0); ll gcd(ll x, ll y) { if (x < 0) x = -x; if (y < 0) y = -y; if (x < y) swap(x, y); while (y) { ll t = y; y = x % y; x = t; } return x; } int add[5012]; vi adj[5012]; bool d[5012]; bool out[5012]; int dfs(int x, int y) { int ret = 1; REP (i, sz (adj[x])) if (adj[x][i] != y) ret += dfs(adj[x][i], x); return ret; } int main () { #ifdef LocalHost freopen("input.txt", "r", stdin); #endif int n; cin >> n; REP (i, n-1) { int q, w; cin >> q >> w; --q, --w; adj[q].pb(w); adj[w].pb(q); } REP (i, n) { memset(d, 0, sizeof(d)); d[0] = true; REP (j, sz (adj[i])) { int cv = dfs(adj[i][j], i); FORD (k, n-1, 0) if (d[k]) d[k + cv] = true; } REP (j, n+1) out[j] |= d[j]; } vpii res; FOR (i, 1, n-1) if (out[i]) res.pb(pii(i, n-i-1)); cout << sz(res) << endl; REP (i, sz (res)) cout << res[i].X << ' ' << res[i].Y << endl; #ifdef LocalHost cout << "--FINISHED--" << endl; while (1); #endif return 0; }
17.346154
64
0.547672
DmitryTheFirst
497c6ee4d30abf700b3bf2f8bc429e4f96a65526
620
cpp
C++
Arrt/View/ArrtAccessibility.cpp
MichaelZp0/azure-remote-rendering-asset-tool
fe979bfe1923589f11487565ececdc575f5e940a
[ "MIT" ]
42
2020-06-12T19:10:52.000Z
2022-03-04T02:20:59.000Z
Arrt/View/ArrtAccessibility.cpp
MichaelZp0/azure-remote-rendering-asset-tool
fe979bfe1923589f11487565ececdc575f5e940a
[ "MIT" ]
91
2020-06-12T12:10:46.000Z
2022-03-02T13:46:00.000Z
Arrt/View/ArrtAccessibility.cpp
MichaelZp0/azure-remote-rendering-asset-tool
fe979bfe1923589f11487565ececdc575f5e940a
[ "MIT" ]
10
2020-07-29T21:19:14.000Z
2021-09-22T11:48:27.000Z
#include <QAbstractItemView> #include <View/ArrtAccessibility.h> namespace ArrtAccesibility { /* The default accessible role for QComboBox is QAccessible::ComboBox, which is exposed to UI automation as "Combo box". Microsoft accessibility compliance expect combo boxes to implement the ExpandCollapse interface and the Selection interface, see https://docs.microsoft.com/en-us/dotnet/framework/ui-automation/ui-automation-support-for-the-combobox-control-type but that's not the case in the Qt implementation. https://bugreports.qt.io/browse/QTBUG-81874 */ } // namespace ArrtAccesibility
41.333333
119
0.774194
MichaelZp0
497cf204a93a5b72ccf66e6498b9b38765553050
6,248
cpp
C++
implementations/ugene/src/corelibs/U2View/src/ov_sequence/SaveGraphCutoffsDialogController.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/corelibs/U2View/src/ov_sequence/SaveGraphCutoffsDialogController.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/corelibs/U2View/src/ov_sequence/SaveGraphCutoffsDialogController.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "SaveGraphCutoffsDialogController.h" #include <QMessageBox> #include <QPushButton> #include <U2Core/AppContext.h> #include <U2Core/CreateAnnotationTask.h> #include <U2Core/DNAAlphabet.h> #include <U2Core/DNASequenceObject.h> #include <U2Core/U1AnnotationUtils.h> #include <U2Gui/HelpButton.h> #include <U2View/ADVAnnotationCreation.h> #include <U2View/ADVSequenceObjectContext.h> #include <U2View/AnnotatedDNAView.h> namespace U2 { SaveGraphCutoffsDialogController::SaveGraphCutoffsDialogController(GSequenceGraphDrawer *_d, QSharedPointer<GSequenceGraphData> &_gd, QWidget *parent, SequenceObjectContext *ctx) : QDialog(parent), ctx(ctx), d(_d), gd(_gd) { setupUi(this); new HelpButton(this, buttonBox, "46499933"); buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Save")); buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); CreateAnnotationModel m; m.hideLocation = true; m.data->name = QString("graph_cutoffs"); m.sequenceObjectRef = ctx->getSequenceObject(); m.useUnloadedObjects = false; m.useAminoAnnotationTypes = ctx->getAlphabet()->isAmino(); m.sequenceLen = ctx->getSequenceObject()->getSequenceLength(); ac = new CreateAnnotationWidgetController(m, this); QWidget *caw = ac->getWidget(); QVBoxLayout *l = new QVBoxLayout(); l->setSizeConstraint(QLayout::SetMinAndMaxSize); l->setMargin(0); l->addWidget(caw); annotationsWidget->setLayout(l); betweenRadioButton->setChecked(true); float min = d->getGlobalMin(), max = d->getGlobalMax(); if (max < 1) { maxCutoffBox->setDecimals(4); minCutoffBox->setDecimals(4); } else if (max < 10) { maxCutoffBox->setDecimals(3); minCutoffBox->setDecimals(3); } else if (max < 100) { maxCutoffBox->setDecimals(2); minCutoffBox->setDecimals(2); } else if (max < 1000) { maxCutoffBox->setDecimals(1); minCutoffBox->setDecimals(1); } else { maxCutoffBox->setDecimals(0); minCutoffBox->setDecimals(0); } maxCutoffBox->setMaximum(max); maxCutoffBox->setMinimum(min); maxCutoffBox->setValue(max); minCutoffBox->setMaximum(max); minCutoffBox->setMinimum(min); minCutoffBox->setValue(min); } void SaveGraphCutoffsDialogController::accept() { if (!validate()) { return; } bool objectPrepared = ac->prepareAnnotationObject(); if (!objectPrepared) { QMessageBox::critical(this, tr("Error!"), "Cannot create an annotation object. Please check settings"); return; } const CreateAnnotationModel &mm = ac->getModel(); int startPos = gd->cachedFrom, step = gd->cachedS, window = gd->cachedW; PairVector &points = gd->cachedData; int curPos = (startPos < window) ? (window / 2 - 1) : startPos, startOffset = window / 2, prevAccepetedPos = 0; curPos++; for (int i = 0, n = points.cutoffPoints.size(); i < n; i++) { if (isAcceptableValue(points.cutoffPoints[i])) { if (resultRegions.isEmpty()) { resultRegions.append(U2Region(curPos - startOffset, window)); } else { QList<U2Region>::iterator it = resultRegions.end(); it--; if ((prevAccepetedPos + step) == curPos) { //expand if accepted values in a row it->length += step; } else { //remove previous empty region, and add new region to list resultRegions.append(U2Region(curPos - startOffset, window)); } } prevAccepetedPos = curPos; } curPos += step; } QList<SharedAnnotationData> data; foreach (const U2Region &r, resultRegions) { SharedAnnotationData d(new AnnotationData); d->location->regions.append(r); d->type = mm.data->type; d->name = mm.data->name; U1AnnotationUtils::addDescriptionQualifier(d, mm.description); data.append(d); } AnnotationTableObject *aobj = mm.getAnnotationObject(); tryAddObject(aobj); Task *t = new CreateAnnotationsTask(aobj, data, mm.groupName); AppContext::getTaskScheduler()->registerTopLevelTask(t); QDialog::accept(); } bool SaveGraphCutoffsDialogController::isAcceptableValue(float val) { return (val > minCutoffBox->value() && val < maxCutoffBox->value() && betweenRadioButton->isChecked()) || (val < minCutoffBox->value() && val > maxCutoffBox->value() && outsideRadioButton->isChecked()); } bool SaveGraphCutoffsDialogController::validate() { if (minCutoffBox->value() >= maxCutoffBox->value()) { QMessageBox::critical(this, tr("Error!"), "Minimum cutoff value greater or equal maximum!"); return false; } return true; } void SaveGraphCutoffsDialogController::tryAddObject(AnnotationTableObject *annotationTableObject) { ADVSequenceObjectContext *advContext = qobject_cast<ADVSequenceObjectContext *>(ctx); CHECK(NULL != advContext, ); advContext->getAnnotatedDNAView()->tryAddObject(annotationTableObject); } } // namespace U2
36.115607
115
0.643566
r-barnes
4980f376120a4328057ec2798681257fcdf5623b
2,426
cpp
C++
cvt/vision/slam/stereo/FeatureTracking.cpp
tuxmike/cvt
c6a5df38af4653345e795883b8babd67433746e9
[ "MIT" ]
11
2017-04-04T16:38:31.000Z
2021-08-04T11:31:26.000Z
cvt/vision/slam/stereo/FeatureTracking.cpp
tuxmike/cvt
c6a5df38af4653345e795883b8babd67433746e9
[ "MIT" ]
null
null
null
cvt/vision/slam/stereo/FeatureTracking.cpp
tuxmike/cvt
c6a5df38af4653345e795883b8babd67433746e9
[ "MIT" ]
8
2016-04-11T00:58:27.000Z
2022-02-22T07:35:40.000Z
/* The MIT License (MIT) Copyright (c) 2011 - 2013, Philipp Heise and Sebastian Klose Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cvt/vision/slam/stereo/FeatureTracking.h> #include <cvt/vision/Vision.h> namespace cvt { FeatureTracking::FeatureTracking() { } FeatureTracking::~FeatureTracking() { } void FeatureTracking::track( std::vector<size_t>& tracked, const Image& currGray, // TODO directly hand in descriptors of const std::vector<FeatureDescriptor*>& descriptors ) { // match descriptors within window // refine with KLT // return successfully tracked indices } bool FeatureTracking::checkFeatureSAD( const Vector2f& point0, const Vector2f& point1, const Image & i0, const Image & i1 ) const { size_t s0, s1; const uint8_t* ptr0 = i0.map( &s0 ); const uint8_t* ptr1 = i1.map( &s1 ); const uint8_t* p0 = ptr0 + ( (int)point0.y - 8 ) * s0 + ( (int)point0.x - 8 ); const uint8_t* p1 = ptr1 + ( (int)point1.y - 8 ) * s1 + ( (int)point1.x - 8 ); float sad = 0; for( size_t i = 0; i < 16; i++ ){ sad += SIMD::instance()->SAD( p0, p1, 16 ); p0 += s0; p1 += s1; } i0.unmap( ptr0 ); i1.unmap( ptr1 ); // average & normalize sad = 1.0f - ( sad / Math::sqr( 255.0 ) ); if( sad > 0.7 /* TODO: make param */ ){ return true; } else { return false; } } }
29.585366
80
0.674361
tuxmike
21a3f44d50f2901dddbdc41eddb92cd37042a263
932
cpp
C++
libraries/shared/src/shared/MiniPromises.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
272
2021-01-07T03:06:08.000Z
2022-03-25T03:54:07.000Z
libraries/shared/src/shared/MiniPromises.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
1,021
2020-12-12T02:33:32.000Z
2022-03-31T23:36:37.000Z
libraries/shared/src/shared/MiniPromises.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
77
2020-12-15T06:59:34.000Z
2022-03-23T22:18:04.000Z
// // Created by Timothy Dedischew on 2017/12/21 // Copyright 2017 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "MiniPromises.h" #include <QtScript/QScriptEngine> #include <QtScript/QScriptValue> int MiniPromise::metaTypeID = qRegisterMetaType<MiniPromise::Promise>("MiniPromise::Promise"); namespace { void promiseFromScriptValue(const QScriptValue& object, MiniPromise::Promise& promise) { Q_ASSERT(false); } QScriptValue promiseToScriptValue(QScriptEngine *engine, const MiniPromise::Promise& promise) { return engine->newQObject(promise.get()); } } void MiniPromise::registerMetaTypes(QObject* engine) { auto scriptEngine = qobject_cast<QScriptEngine*>(engine); qScriptRegisterMetaType(scriptEngine, promiseToScriptValue, promiseFromScriptValue); }
34.518519
99
0.753219
Darlingnotin
21a5c6417add5f5d863eb9c0712ad1dcdeeb3127
348
cpp
C++
common/source/string.cpp
xrEngine512/interop
c80711fbbe08f350ad5d8058163770f57ed20b0c
[ "MIT" ]
null
null
null
common/source/string.cpp
xrEngine512/interop
c80711fbbe08f350ad5d8058163770f57ed20b0c
[ "MIT" ]
4
2017-05-31T12:34:10.000Z
2018-10-13T18:53:03.000Z
common/source/string.cpp
xrEngine512/MosaicFramework
c80711fbbe08f350ad5d8058163770f57ed20b0c
[ "MIT" ]
1
2020-04-23T14:09:11.000Z
2020-04-23T14:09:11.000Z
#include "utils/string.h" #include <boost/algorithm/string/regex.hpp> using namespace std; namespace interop { namespace utils { vector<string> split_rx(const string & str, const string & del) { vector<string> res; boost::algorithm::split_regex(res, str, boost::regex(del)); return res; } } // namespace utils } // namespace interop
20.470588
63
0.70977
xrEngine512
21a7643c6dea6f0ff48c691aec2051bcd2d40c32
6,681
cpp
C++
src/binding.cpp
oprypin/crystal-imgui-sfml
0e9662bf5e2b4373d32048b07df0daf53180274e
[ "MIT" ]
11
2020-10-02T15:36:21.000Z
2021-11-16T03:17:40.000Z
src/binding.cpp
oprypin/crystal-imgui-sfml
0e9662bf5e2b4373d32048b07df0daf53180274e
[ "MIT" ]
2
2021-02-12T15:04:38.000Z
2021-02-22T22:59:06.000Z
src/binding.cpp
oprypin/crystal-imgui-sfml
0e9662bf5e2b4373d32048b07df0daf53180274e
[ "MIT" ]
1
2021-03-20T19:59:02.000Z
2021-03-20T19:59:02.000Z
#include <imgui-SFML.h> #include <SFML/Graphics/Color.hpp> #include <SFML/Graphics/Rect.hpp> #include <SFML/Graphics/RenderTexture.hpp> #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/Graphics/Sprite.hpp> #include <SFML/Graphics/Texture.hpp> #include <SFML/System/Time.hpp> #include <SFML/System/Vector2.hpp> #include <SFML/Window/Event.hpp> #include <SFML/Window/Joystick.hpp> #include <SFML/Window/Window.hpp> extern "C" { void ImGui_SFML_InitW(sf::RenderWindow* window, bool loadDefaultFont) { ImGui::SFML::Init(*window, loadDefaultFont); } void ImGui_SFML_InitWT(sf::Window* window, sf::RenderTexture* target, bool loadDefaultFont) { ImGui::SFML::Init(*window, *target, loadDefaultFont); } void ImGui_SFML_InitWW(sf::Window* window, sf::RenderWindow* target, bool loadDefaultFont) { ImGui::SFML::Init(*window, *target, loadDefaultFont); } void ImGui_SFML_InitWV(sf::Window* window, const sf::Vector2f* displaySize, bool loadDefaultFont) { ImGui::SFML::Init(*window, *displaySize, loadDefaultFont); } void ImGui_SFML_ProcessEvent(const sf::Event* event) { ImGui::SFML::ProcessEvent(*event); } void ImGui_SFML_UpdateW(sf::RenderWindow* window, const sf::Time* dt) { ImGui::SFML::Update(*window, *dt); } void ImGui_SFML_UpdateWT(sf::Window* window, sf::RenderTexture* target, const sf::Time* dt) { ImGui::SFML::Update(*window, *target, *dt); } void ImGui_SFML_UpdateWW(sf::Window* window, sf::RenderWindow* target, const sf::Time* dt) { ImGui::SFML::Update(*window, *target, *dt); } void ImGui_SFML_UpdateVV(const sf::Vector2i* mousePos, const sf::Vector2f* displaySize, const sf::Time* dt) { ImGui::SFML::Update(*mousePos, *displaySize, *dt); } void ImGui_SFML_RenderT(sf::RenderTexture* target) { ImGui::SFML::Render(*target); } void ImGui_SFML_RenderW(sf::RenderWindow* target) { ImGui::SFML::Render(*target); } void ImGui_SFML_Render() { ImGui::SFML::Render(); } void ImGui_SFML_Shutdown() { ImGui::SFML::Shutdown(); } void ImGui_SFML_UpdateFontTexture() { ImGui::SFML::UpdateFontTexture(); } sf::Texture* ImGui_SFML_GetFontTexture() { return &ImGui::SFML::GetFontTexture(); } void ImGui_SFML_SetActiveJoystickId(unsigned int joystickId) { ImGui::SFML::SetActiveJoystickId(joystickId); } void ImGui_SFML_SetJoytickDPadThreshold(float threshold) { ImGui::SFML::SetJoytickDPadThreshold(threshold); } void ImGui_SFML_SetJoytickLStickThreshold(float threshold) { ImGui::SFML::SetJoytickLStickThreshold(threshold); } void ImGui_SFML_SetJoystickMapping(int action, unsigned int joystickButton) { ImGui::SFML::SetJoystickMapping(action, joystickButton); } void ImGui_SFML_SetDPadXAxis(sf::Joystick::Axis dPadXAxis, bool inverted) { ImGui::SFML::SetDPadXAxis(dPadXAxis, inverted); } void ImGui_SFML_SetDPadYAxis(sf::Joystick::Axis dPadYAxis, bool inverted) { ImGui::SFML::SetDPadYAxis(dPadYAxis, inverted); } void ImGui_SFML_SetLStickXAxis(sf::Joystick::Axis lStickXAxis, bool inverted) { ImGui::SFML::SetLStickXAxis(lStickXAxis, inverted); } void ImGui_SFML_SetLStickYAxis(sf::Joystick::Axis lStickYAxis, bool inverted) { ImGui::SFML::SetLStickYAxis(lStickYAxis, inverted); } void ImGui_ImageTCC(const sf::Texture* texture, const sf::Color* tintColor, const sf::Color* borderColor) { ImGui::Image(*texture, *tintColor, *borderColor); } void ImGui_ImageTVCC(const sf::Texture* texture, const sf::Vector2f* size, const sf::Color* tintColor, const sf::Color* borderColor) { ImGui::Image(*texture, *size, *tintColor, *borderColor); } void ImGui_ImageRCC(const sf::RenderTexture* texture, const sf::Color* tintColor, const sf::Color* borderColor) { ImGui::Image(*texture, *tintColor, *borderColor); } void ImGui_ImageRVCC(const sf::RenderTexture* texture, const sf::Vector2f* size, const sf::Color* tintColor, const sf::Color* borderColor) { ImGui::Image(*texture, *size, *tintColor, *borderColor); } void ImGui_ImageSCC(const sf::Sprite* sprite, const sf::Color* tintColor, const sf::Color* borderColor) { ImGui::Image(*sprite, *tintColor, *borderColor); } void ImGui_ImageSVCC(const sf::Sprite* sprite, const sf::Vector2f* size, const sf::Color* tintColor, const sf::Color* borderColor) { ImGui::Image(*sprite, *size, *tintColor, *borderColor); } bool ImGui_ImageButtonTICC(const sf::Texture* texture, const int framePadding, const sf::Color* bgColor, const sf::Color* tintColor) { return ImGui::ImageButton(*texture, framePadding, *bgColor, *tintColor); } bool ImGui_ImageButtonTVICC(const sf::Texture* texture, const sf::Vector2f* size, const int framePadding, const sf::Color* bgColor, const sf::Color* tintColor) { return ImGui::ImageButton(*texture, *size, framePadding, *bgColor, *tintColor); } bool ImGui_ImageButtonRICC(const sf::RenderTexture* texture, const int framePadding, const sf::Color* bgColor, const sf::Color* tintColor) { return ImGui::ImageButton(*texture, framePadding, *bgColor, *tintColor); } bool ImGui_ImageButtonRVICC(const sf::RenderTexture* texture, const sf::Vector2f* size, const int framePadding, const sf::Color* bgColor, const sf::Color* tintColor) { return ImGui::ImageButton(*texture, *size, framePadding, *bgColor, *tintColor); } bool ImGui_ImageButtonSICC(const sf::Sprite* sprite, const int framePadding, const sf::Color* bgColor, const sf::Color* tintColor) { return ImGui::ImageButton(*sprite, framePadding, *bgColor, *tintColor); } bool ImGui_ImageButtonSVICC(const sf::Sprite* sprite, const sf::Vector2f* size, const int framePadding, const sf::Color* bgColor, const sf::Color* tintColor) { return ImGui::ImageButton(*sprite, *size, framePadding, *bgColor, *tintColor); } void ImGui_DrawLine(const sf::Vector2f* a, const sf::Vector2f* b, const sf::Color* col, float thickness) { ImGui::DrawLine(*a, *b, *col, thickness); } void ImGui_DrawRect(const sf::FloatRect* rect, const sf::Color* color, float rounding, int rounding_corners, float thickness) { ImGui::DrawRect(*rect, *color, rounding, rounding_corners, thickness); } void ImGui_DrawRectFilled(const sf::FloatRect* rect, const sf::Color* color, float rounding, int rounding_corners) { ImGui::DrawRectFilled(*rect, *color, rounding, rounding_corners); } }
46.395833
171
0.695405
oprypin
21aa1147898f0a2c1be931be70ca0be7a351365b
6,299
inl
C++
arrays/Deque.Iterator.inl
FinIsOro/array
23489b305b3e728281f0eec99c7cb5fe941e1953
[ "MIT" ]
null
null
null
arrays/Deque.Iterator.inl
FinIsOro/array
23489b305b3e728281f0eec99c7cb5fe941e1953
[ "MIT" ]
null
null
null
arrays/Deque.Iterator.inl
FinIsOro/array
23489b305b3e728281f0eec99c7cb5fe941e1953
[ "MIT" ]
null
null
null
namespace arrays { template<class T, size_t block> Deque<T, block>::Iterator::Iterator(Deque::Block *start, Deque::Offset offset, size_t index) : index(index), current(start), offset(offset) { } template<class T, size_t block> Deque<T, block>::Iterator::Iterator(Deque::Block *start, Deque::Offset offset) : index(offset.left + 1), current(start), offset(offset) { } template<class T, size_t block> Deque<T, block>::Iterator::Iterator(const Deque::Iterator &iterator) : index(iterator.index), current(iterator.current), offset(iterator.offset) { } template<class T, size_t block> void Deque<T, block>::Iterator::next(bool right) { if (current->right != nullptr) { current = current->right; reset(right); } else index = offset.right; } template<class T, size_t block> void Deque<T, block>::Iterator::prev(bool right) { if (current->left != nullptr) { current = current->left; reset(right); } else index = offset.left; } template<class T, size_t block> size_t Deque<T, block>::Iterator::rest(bool right) { if (right) { if (current->right == nullptr) return offset.right - index; return block - index; } if (current->left == nullptr) return index + 1 - offset.left; return index + 1; } template<class T, size_t block> void Deque<T, block>::Iterator::reset(bool right) { if (right) if (current->right == nullptr) index = offset.right - 1; else index = block - 1; else if (current->left == nullptr) index = offset.left + 1; else index = 0; } template<class T, size_t block> typename Deque<T, block>::Iterator::pointer Deque<T, block>::Iterator::address() { return current->cache + index; } template<class T, size_t block> typename Deque<T, block>::Iterator::reference Deque<T, block>::Iterator::operator*() { return *(current->cache + index); } template<class T, size_t block> typename Deque<T, block>::Iterator::pointer Deque<T, block>::Iterator::operator->() { return current->cache + index; } template<class T, size_t block> typename Deque<T, block>::Iterator &Deque<T, block>::Iterator::operator++() { if (current->right != nullptr || current->right == nullptr && index < offset.right) index++; if (index >= block && current->right != nullptr) { index = 0; current = current->right; } return *this; } template<class T, size_t block> typename Deque<T, block>::Iterator Deque<T, block>::Iterator::operator++(int) { Iterator temp = *this; ++(*this); return temp; } template<class T, size_t block> typename Deque<T, block>::Iterator &Deque<T, block>::Iterator::operator+=(int offset) { size_t length; if (offset > 0) while ((length = rest()) != 0 && offset > 0) { offset -= length; if (length != block) index += length; if (offset < 0) index += offset; else next(); } else while ((length = rest(false)) != 0 && offset < 0) { offset += length; if (length != block) index -= length; if (offset > 0) index += offset; else prev(); } return *this; } template<class T, size_t block> typename Deque<T, block>::Iterator Deque<T, block>::Iterator::operator+(int offset) { Iterator result = *this; result += offset; return result; } template<class T, size_t block> typename Deque<T, block>::Iterator &Deque<T, block>::Iterator::operator--() { if (current->left != nullptr || current->left == nullptr && index > offset.left) index--; if (index == SIZE_MAX && current->left != nullptr) { index = block - 1; current = current->left; } return *this; } template<class T, size_t block> typename Deque<T, block>::Iterator Deque<T, block>::Iterator::operator--(int) { Iterator temp = *this; --(*this); return temp; } template<class T, size_t block> typename Deque<T, block>::Iterator &Deque<T, block>::Iterator::operator-=(int offset) { size_t length; if (offset > 0) while ((length = rest(false)) != 0 && offset > 0) { offset -= length; if (length != block) index -= length; if (offset < 0) index -= offset; else prev(); } else while ((length = rest()) != 0 && offset < 0) { offset += length; if (length != block) index += length; if (offset > 0) index -= offset; else next(); } return *this; } template<class T, size_t block> typename Deque<T, block>::Iterator Deque<T, block>::Iterator::operator-(int offset) { Iterator result = *this; result -= offset; return result; } template<class T, size_t block> bool Deque<T, block>::Iterator::operator==(const Deque::Iterator &another) const { return current == another.current && index == another.index; } template<class T, size_t block> bool Deque<T, block>::Iterator::operator!=(const Deque::Iterator &another) const { return current != another.current || index != another.index; } }
24.897233
98
0.493888
FinIsOro
21ad3b2e82a27c5dcf1b0cac668b977673e8c5c0
950
cpp
C++
Source/RTS/Plugins/RTSPlugin/Source/RTSPlugin/Private/RTSCharacter.cpp
ajbetteridge/ue4-rts
d7923fa694f6b6a04d8301a65019f85512fcb359
[ "MIT" ]
3
2020-08-24T03:36:07.000Z
2021-12-28T03:40:02.000Z
Source/RTS/Plugins/RTSPlugin/Source/RTSPlugin/Private/RTSCharacter.cpp
ajbetteridge/ue4-rts
d7923fa694f6b6a04d8301a65019f85512fcb359
[ "MIT" ]
null
null
null
Source/RTS/Plugins/RTSPlugin/Source/RTSPlugin/Private/RTSCharacter.cpp
ajbetteridge/ue4-rts
d7923fa694f6b6a04d8301a65019f85512fcb359
[ "MIT" ]
1
2021-12-28T03:40:04.000Z
2021-12-28T03:40:04.000Z
#include "RTSPluginPCH.h" #include "RTSCharacter.h" #include "WorldCollision.h" #include "Components/CapsuleComponent.h" #include "Components/DecalComponent.h" #include "GameFramework/Controller.h" #include "Kismet/GameplayStatics.h" #include "Net/UnrealNetwork.h" #include "RTSAttackData.h" #include "RTSGameMode.h" #include "RTSHealthComponent.h" #include "RTSSelectableComponent.h" ARTSCharacter::ARTSCharacter() { // Enable replication. bReplicates = true; } float ARTSCharacter::TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) { float ActualDamage = Super::TakeDamage(Damage, DamageEvent, EventInstigator, DamageCauser); // Adjust health. URTSHealthComponent* HealthComponent = FindComponentByClass<URTSHealthComponent>(); if (!HealthComponent) { return 0.0f; } return HealthComponent->TakeDamage(ActualDamage, DamageEvent, EventInstigator, DamageCauser); }
26.388889
137
0.790526
ajbetteridge
21b4b5f0afb26ecdff69b6d9588a1460c0eca3ca
7,550
hpp
C++
source/modules/solver/sampler/HMC/helpers/hamiltonian_riemannian_const_diag.hpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
43
2018-07-26T07:20:42.000Z
2022-03-02T10:23:12.000Z
source/modules/solver/sampler/HMC/helpers/hamiltonian_riemannian_const_diag.hpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
212
2018-09-21T10:44:07.000Z
2022-03-22T14:33:05.000Z
source/modules/solver/sampler/HMC/helpers/hamiltonian_riemannian_const_diag.hpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
16
2018-07-25T15:00:36.000Z
2022-03-22T14:19:46.000Z
#ifndef HAMILTONIAN_RIEMANNIAN_CONST_DIAG_H #define HAMILTONIAN_RIEMANNIAN_CONST_DIAG_H #include "hamiltonian_riemannian_base.hpp" #include "modules/distribution/univariate/normal/normal.hpp" namespace korali { namespace solver { namespace sampler { /** * \class HamiltonianRiemannianConstDiag * @brief Used for diagonal Riemannian metric. */ class HamiltonianRiemannianConstDiag : public HamiltonianRiemannian { public: /** * @brief Constructor with State Space Dim. * @param stateSpaceDim Dimension of State Space. * @param normalGenerator Generator needed for momentum sampling. * @param inverseRegularizationParam Inverse regularization parameter of SoftAbs metric that controls hardness of approximation: For large values inverseMetric is closer to analytical formula (and therefore closer to degeneracy in certain cases). * @param k Pointer to Korali object. */ HamiltonianRiemannianConstDiag(const size_t stateSpaceDim, korali::distribution::univariate::Normal *normalGenerator, const double inverseRegularizationParam, korali::Experiment *k) : HamiltonianRiemannian{stateSpaceDim, k} { _normalGenerator = normalGenerator; _inverseRegularizationParam = inverseRegularizationParam; } /** * @brief Destructor of derived class. */ ~HamiltonianRiemannianConstDiag() = default; /** * @brief Total energy function used for Hamiltonian Dynamics. * @param momentum Current momentum. * @param inverseMetric Inverse of current metric. * @return Total energy. */ double H(const std::vector<double> &momentum, const std::vector<double> &inverseMetric) override { return K(momentum, inverseMetric) + U(); } /** * @brief Kinetic energy function. * @param momentum Current momentum. * @param inverseMetric Inverse of current metric. * @return Kinetic energy. */ double K(const std::vector<double> &momentum, const std::vector<double> &inverseMetric) override { double result = tau(momentum, inverseMetric) + 0.5 * _logDetMetric; return result; } /** * @brief Gradient of kintetic energy function * @param momentum Current momentum. * @param inverseMetric Current inverseMetric. * @return Gradient of kinetic energy wrt. current momentum. */ std::vector<double> dK(const std::vector<double> &momentum, const std::vector<double> &inverseMetric) override { std::vector<double> gradient(_stateSpaceDim, 0.0); for (size_t i = 0; i < _stateSpaceDim; ++i) { gradient[i] = inverseMetric[i] * momentum[i]; } return gradient; } /** * @brief Calculates tau(q, p) = 0.5 * momentum^T * inverseMetric(q) * momentum. * @param momentum Current momentum. * @param inverseMetric Current inverseMetric. * @return Gradient of Kinetic energy with current momentum. */ double tau(const std::vector<double> &momentum, const std::vector<double> &inverseMetric) override { double energy = 0.0; for (size_t i = 0; i < _stateSpaceDim; ++i) { energy += momentum[i] * inverseMetric[i] * momentum[i]; } return 0.5 * energy; } /** * @brief Calculates gradient of tau(q, p) wrt. position. * @param momentum Current momentum. * @param inverseMetric Current inverseMetric. * @return Gradient of Kinetic energy with current momentum. */ std::vector<double> dtau_dq(const std::vector<double> &momentum, const std::vector<double> &inverseMetric) override { std::vector<double> result(_stateSpaceDim, 0.0); return result; } /** * @brief Calculates gradient of tau(q, p) wrt. momentum. * @param momentum Current momentum. * @param inverseMetric Current inverseMetric. * @return Gradient of Kinetic energy with current momentum. */ std::vector<double> dtau_dp(const std::vector<double> &momentum, const std::vector<double> &inverseMetric) override { return dK(momentum, inverseMetric); } /** * @brief Calculates gradient of kinetic energy. * @return Gradient of kinetic energy. */ double phi() override { return U() + 0.5 * _logDetMetric; } /** * @brief Calculates gradient of kinetic energy. * @return Gradient of kinetic energy. */ std::vector<double> dphi_dq() override { return dU(); } /** * @brief Updates current position of hamiltonian. * @param position Current position. * @param metric Current metric. * @param inverseMetric Inverse of current metric. */ void updateHamiltonian(const std::vector<double> &position, std::vector<double> &metric, std::vector<double> &inverseMetric) override { auto sample = korali::Sample(); sample["Sample Id"] = _modelEvaluationCount; sample["Module"] = "Problem"; sample["Operation"] = "Evaluate"; sample["Parameters"] = position; KORALI_START(sample); KORALI_WAIT(sample); _modelEvaluationCount++; _currentEvaluation = KORALI_GET(double, sample, "logP(x)"); if (samplingProblemPtr != nullptr) { samplingProblemPtr->evaluateGradient(sample); samplingProblemPtr->evaluateHessian(sample); } else { bayesianProblemPtr->evaluateGradient(sample); bayesianProblemPtr->evaluateHessian(sample); } _currentGradient = sample["grad(logP(x))"].get<std::vector<double>>(); _currentHessian = sample["H(logP(x))"].get<std::vector<double>>(); } /** * @brief Generates sample of momentum. * @param metric Current metric. * @return Momentum sampled from normal distribution with metric as covariance matrix. */ std::vector<double> sampleMomentum(const std::vector<double> &metric) const override { std::vector<double> result(_stateSpaceDim); for (size_t i = 0; i < _stateSpaceDim; ++i) { result[i] = std::sqrt(metric[i]) * _normalGenerator->getRandomNumber(); } return result; } /** * @brief Calculates inner product induces by inverse metric. * @param momentumLeft Left vector of inner product. * @param momentumRight Right vector of inner product. * @param inverseMetric Inverse of curret metric. * @return inner product */ double innerProduct(const std::vector<double> &momentumLeft, const std::vector<double> &momentumRight, const std::vector<double> &inverseMetric) const override { double result = 0.0; for (size_t i = 0; i < _stateSpaceDim; ++i) { result += momentumLeft[i] * inverseMetric[i] * momentumRight[i]; } return result; } /** * @brief Updates Metric and Inverse Metric by using hessian. * @param metric Current metric. * @param inverseMetric Inverse of current metric. * @return Error code to indicate if update was successful. */ int updateMetricMatricesRiemannian(std::vector<double> &metric, std::vector<double> &inverseMetric) override { auto hessian = _currentHessian; // constant for condition number of metric double detMetric = 1.0; for (size_t i = 0; i < _stateSpaceDim; ++i) { metric[i] = softAbsFunc(hessian[i + i * _stateSpaceDim], _inverseRegularizationParam); inverseMetric[i] = 1.0 / metric[i]; detMetric *= metric[i]; } _logDetMetric = std::log(detMetric); return 0; } /** * @brief Inverse regularization parameter of SoftAbs metric that controls hardness of approximation */ double _inverseRegularizationParam; private: /** * @brief One dimensional normal generator needed for sampling of momentum from diagonal metric. */ korali::distribution::univariate::Normal *_normalGenerator; }; } // namespace sampler } // namespace solver } // namespace korali #endif
30.2
248
0.701987
JonathanLehner
21b536f667051e26f061d50a3cc78a1d493a883f
1,335
cpp
C++
src/scheme/main.cpp
CHChang810716/llvm-playground
26a1cddac5b1a124e655e63f4efb70d5396c0e05
[ "MIT" ]
null
null
null
src/scheme/main.cpp
CHChang810716/llvm-playground
26a1cddac5b1a124e655e63f4efb70d5396c0e05
[ "MIT" ]
null
null
null
src/scheme/main.cpp
CHChang810716/llvm-playground
26a1cddac5b1a124e655e63f4efb70d5396c0e05
[ "MIT" ]
null
null
null
#include "parser.hpp" #include <tao/pegtl/contrib/parse_tree_to_dot.hpp> #include <iostream> #include "ir.hpp" #include <llvm/Support/raw_ostream.h> #include "env.hpp" int main(int argc, char *argv[]) { using RuleFile = tao::pegtl::must<scheme::File>; if(argc < 2) { return 1; } tao::pegtl::file_input<> in(argv[1]); auto root = tao::pegtl::parse_tree::parse<RuleFile, scheme::ASTSelector>(in); tao::pegtl::parse_tree::print_dot(std::cerr, *root); std::unique_ptr<llvm::Module> module( new llvm::Module("initial", scheme::ir.get_context()) ); llvm::ValueSymbolTable main_sym_table; scheme::FunctionTable func_table; auto* ir_main_f = scheme::ir.main(*module); auto expr_block = llvm::BasicBlock::Create(scheme::ir.get_context(), "entry", ir_main_f); scheme::ir.get_builder().SetInsertPoint(expr_block); scheme::ir.get_current_function() = ir_main_f; scheme::env.main_module_preload(*module, *ir_main_f, func_table); for(auto& sexpr : root->children) { std::cerr << sexpr->string() << '\n'; scheme::sexpr_ir( scheme::ir.get_builder(), *sexpr, main_sym_table, func_table, *module ); } scheme::ir.get_builder().CreateRet( llvm::ConstantInt::get(scheme::ir.get_context(), llvm::APInt(32, 0)) ); module->print(llvm::outs(), nullptr); return 0; }
33.375
91
0.676404
CHChang810716
21b857fd64aabfa97f206bc6eae2bb591d985a5e
2,652
hpp
C++
cpp/G3M/CameraEffects.hpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
70
2015-02-06T14:39:14.000Z
2022-01-07T08:32:48.000Z
cpp/G3M/CameraEffects.hpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
118
2015-01-21T10:18:00.000Z
2018-10-16T15:00:57.000Z
cpp/G3M/CameraEffects.hpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
41
2015-01-10T22:29:27.000Z
2021-06-08T11:56:16.000Z
// // CameraEffects.hpp // G3M // // Created by Agustín Trujillo on 17/07/13. // // #ifndef G3M_CameraEffects #define G3M_CameraEffects #include "Effects.hpp" #include "Vector3D.hpp" #include "Angle.hpp" class RotateWithAxisEffect : public EffectWithForce { private: const Vector3D _axis; double _degrees; public: RotateWithAxisEffect(const Vector3D& axis, const Angle& angle); virtual ~RotateWithAxisEffect() { } void start(const G3MRenderContext* rc, const TimeInterval& when) { } void doStep(const G3MRenderContext* rc, const TimeInterval& when); void stop(const G3MRenderContext* rc, const TimeInterval& when); void cancel(const TimeInterval& when) { } }; class SingleTranslationEffect : public EffectWithForce { private: const Vector3D _direction; public: SingleTranslationEffect(const Vector3D& desp); void start(const G3MRenderContext* rc, const TimeInterval& when) { } void doStep(const G3MRenderContext* rc, const TimeInterval& when); void stop(const G3MRenderContext* rc, const TimeInterval& when); void cancel(const TimeInterval& when) { } }; class DoubleTapRotationEffect : public EffectWithDuration { private: const Vector3D _axis; const Angle _angle; const double _distance; double _lastAlpha; public: DoubleTapRotationEffect(const TimeInterval& duration, const Vector3D& axis, const Angle& angle, double distance, const bool linearTiming=false); void start(const G3MRenderContext* rc, const TimeInterval& when); void doStep(const G3MRenderContext* rc, const TimeInterval& when); void stop(const G3MRenderContext* rc, const TimeInterval& when); void cancel(const TimeInterval& when) { } }; class DoubleTapTranslationEffect : public EffectWithDuration { private: const Vector3D _translation; const double _distance; double _lastAlpha; public: DoubleTapTranslationEffect(const TimeInterval& duration, const Vector3D& translation, double distance, const bool linearTiming=false); void start(const G3MRenderContext* rc, const TimeInterval& when); void doStep(const G3MRenderContext* rc, const TimeInterval& when); void stop(const G3MRenderContext* rc, const TimeInterval& when); void cancel(const TimeInterval& when) {} }; #endif
20.88189
62
0.643288
glob3mobile
21bb10cec2eaa928a93fe9ccd8d06abb83be7939
339
hpp
C++
core/include/system/EntityGenerator.hpp
Floriantoine/MyHunter_Sfml
8744e1b03d9d5fb621f9cba7619d9d5dd943e428
[ "MIT" ]
null
null
null
core/include/system/EntityGenerator.hpp
Floriantoine/MyHunter_Sfml
8744e1b03d9d5fb621f9cba7619d9d5dd943e428
[ "MIT" ]
null
null
null
core/include/system/EntityGenerator.hpp
Floriantoine/MyHunter_Sfml
8744e1b03d9d5fb621f9cba7619d9d5dd943e428
[ "MIT" ]
null
null
null
#pragma once #include "ASystem.hpp" #include "observer/Observer.hpp" namespace systems { class EntityGenerator : public fa::ASystem { public: Observer _observer; std::vector<std::string> _pathList; EntityGenerator(); ~EntityGenerator() = default; void update(long elapsedTime) override; }; } // namespace systems
18.833333
44
0.707965
Floriantoine
21bb392cf270549d068ddcb7a36a506b2c580d45
8,786
cpp
C++
src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGImageElement.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
46
2015-01-08T14:32:34.000Z
2022-02-05T16:48:26.000Z
src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGImageElement.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
7
2015-01-20T14:28:12.000Z
2017-01-18T17:21:44.000Z
src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGImageElement.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
14
2015-10-27T06:17:48.000Z
2020-03-03T06:15:50.000Z
/* * Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Rob Buis <buis@kde.org> * Copyright (C) 2006 Alexander Kellett <lypanov@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #if ENABLE(SVG) #include "SVGImageElement.h" #include "Attribute.h" #include "CSSPropertyNames.h" #include "RenderImageResource.h" #include "RenderSVGImage.h" #include "RenderSVGResource.h" #include "SVGNames.h" #include "SVGSVGElement.h" #include "XLinkNames.h" namespace WebCore { // Animated property definitions DEFINE_ANIMATED_LENGTH(SVGImageElement, SVGNames::xAttr, X, x) DEFINE_ANIMATED_LENGTH(SVGImageElement, SVGNames::yAttr, Y, y) DEFINE_ANIMATED_LENGTH(SVGImageElement, SVGNames::widthAttr, Width, width) DEFINE_ANIMATED_LENGTH(SVGImageElement, SVGNames::heightAttr, Height, height) DEFINE_ANIMATED_PRESERVEASPECTRATIO(SVGImageElement, SVGNames::preserveAspectRatioAttr, PreserveAspectRatio, preserveAspectRatio) DEFINE_ANIMATED_STRING(SVGImageElement, XLinkNames::hrefAttr, Href, href) DEFINE_ANIMATED_BOOLEAN(SVGImageElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired) inline SVGImageElement::SVGImageElement(const QualifiedName& tagName, Document* document) : SVGStyledTransformableElement(tagName, document) , m_x(LengthModeWidth) , m_y(LengthModeHeight) , m_width(LengthModeWidth) , m_height(LengthModeHeight) , m_imageLoader(this) { } PassRefPtr<SVGImageElement> SVGImageElement::create(const QualifiedName& tagName, Document* document) { return adoptRef(new SVGImageElement(tagName, document)); } void SVGImageElement::parseMappedAttribute(Attribute* attr) { if (attr->name() == SVGNames::xAttr) setXBaseValue(SVGLength(LengthModeWidth, attr->value())); else if (attr->name() == SVGNames::yAttr) setYBaseValue(SVGLength(LengthModeHeight, attr->value())); else if (attr->name() == SVGNames::preserveAspectRatioAttr) SVGPreserveAspectRatio::parsePreserveAspectRatio(this, attr->value()); else if (attr->name() == SVGNames::widthAttr) { setWidthBaseValue(SVGLength(LengthModeWidth, attr->value())); addCSSProperty(attr, CSSPropertyWidth, attr->value()); if (widthBaseValue().value(this) < 0.0) document()->accessSVGExtensions()->reportError("A negative value for image attribute <width> is not allowed"); } else if (attr->name() == SVGNames::heightAttr) { setHeightBaseValue(SVGLength(LengthModeHeight, attr->value())); addCSSProperty(attr, CSSPropertyHeight, attr->value()); if (heightBaseValue().value(this) < 0.0) document()->accessSVGExtensions()->reportError("A negative value for image attribute <height> is not allowed"); } else { if (SVGTests::parseMappedAttribute(attr)) return; if (SVGLangSpace::parseMappedAttribute(attr)) return; if (SVGExternalResourcesRequired::parseMappedAttribute(attr)) return; if (SVGURIReference::parseMappedAttribute(attr)) return; SVGStyledTransformableElement::parseMappedAttribute(attr); } } void SVGImageElement::svgAttributeChanged(const QualifiedName& attrName) { SVGStyledTransformableElement::svgAttributeChanged(attrName); if (SVGURIReference::isKnownAttribute(attrName)) m_imageLoader.updateFromElementIgnoringPreviousError(); bool isLengthAttribute = attrName == SVGNames::xAttr || attrName == SVGNames::yAttr || attrName == SVGNames::widthAttr || attrName == SVGNames::heightAttr; if (isLengthAttribute) updateRelativeLengthsInformation(); if (SVGTests::handleAttributeChange(this, attrName)) return; RenderObject* renderer = this->renderer(); if (!renderer) return; if (isLengthAttribute) { renderer->updateFromElement(); RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer, false); return; } if (attrName == SVGNames::preserveAspectRatioAttr || SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer); } void SVGImageElement::synchronizeProperty(const QualifiedName& attrName) { SVGStyledTransformableElement::synchronizeProperty(attrName); if (attrName == anyQName()) { synchronizeX(); synchronizeY(); synchronizeWidth(); synchronizeHeight(); synchronizePreserveAspectRatio(); synchronizeExternalResourcesRequired(); synchronizeHref(); SVGTests::synchronizeProperties(this, attrName); return; } if (attrName == SVGNames::xAttr) synchronizeX(); else if (attrName == SVGNames::yAttr) synchronizeY(); else if (attrName == SVGNames::widthAttr) synchronizeWidth(); else if (attrName == SVGNames::heightAttr) synchronizeHeight(); else if (attrName == SVGNames::preserveAspectRatioAttr) synchronizePreserveAspectRatio(); else if (SVGExternalResourcesRequired::isKnownAttribute(attrName)) synchronizeExternalResourcesRequired(); else if (SVGURIReference::isKnownAttribute(attrName)) synchronizeHref(); else if (SVGTests::isKnownAttribute(attrName)) SVGTests::synchronizeProperties(this, attrName); } AttributeToPropertyTypeMap& SVGImageElement::attributeToPropertyTypeMap() { DEFINE_STATIC_LOCAL(AttributeToPropertyTypeMap, s_attributeToPropertyTypeMap, ()); return s_attributeToPropertyTypeMap; } void SVGImageElement::fillAttributeToPropertyTypeMap() { AttributeToPropertyTypeMap& attributeToPropertyTypeMap = this->attributeToPropertyTypeMap(); SVGStyledTransformableElement::fillPassedAttributeToPropertyTypeMap(attributeToPropertyTypeMap); attributeToPropertyTypeMap.set(SVGNames::xAttr, AnimatedLength); attributeToPropertyTypeMap.set(SVGNames::yAttr, AnimatedLength); attributeToPropertyTypeMap.set(SVGNames::widthAttr, AnimatedLength); attributeToPropertyTypeMap.set(SVGNames::heightAttr, AnimatedLength); attributeToPropertyTypeMap.set(SVGNames::preserveAspectRatioAttr, AnimatedPreserveAspectRatio); attributeToPropertyTypeMap.set(XLinkNames::hrefAttr, AnimatedString); } bool SVGImageElement::selfHasRelativeLengths() const { return x().isRelative() || y().isRelative() || width().isRelative() || height().isRelative(); } RenderObject* SVGImageElement::createRenderer(RenderArena* arena, RenderStyle*) { return new (arena) RenderSVGImage(this); } bool SVGImageElement::haveLoadedRequiredResources() { return !externalResourcesRequiredBaseValue() || m_imageLoader.haveFiredLoadEvent(); } void SVGImageElement::attach() { SVGStyledTransformableElement::attach(); if (RenderSVGImage* imageObj = toRenderSVGImage(renderer())) { if (imageObj->imageResource()->hasImage()) return; imageObj->imageResource()->setCachedImage(m_imageLoader.image()); } } void SVGImageElement::insertedIntoDocument() { SVGStyledTransformableElement::insertedIntoDocument(); // Update image loader, as soon as we're living in the tree. // We can only resolve base URIs properly, after that! m_imageLoader.updateFromElement(); } const QualifiedName& SVGImageElement::imageSourceAttributeName() const { return XLinkNames::hrefAttr; } void SVGImageElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const { SVGStyledTransformableElement::addSubresourceAttributeURLs(urls); addSubresourceURL(urls, document()->completeURL(href())); } void SVGImageElement::willMoveToNewOwnerDocument() { m_imageLoader.elementWillMoveToNewOwnerDocument(); SVGStyledTransformableElement::willMoveToNewOwnerDocument(); } } #endif // ENABLE(SVG)
36.608333
135
0.732415
ant0ine
21bcd831908283b1e66a92530c319a107047d919
37
cpp
C++
examples/tvm/boo.cpp
Costallat/hunter
dc0d79cb37b30cad6d6472d7143fe27be67e26d5
[ "BSD-2-Clause" ]
2,146
2015-01-10T07:26:58.000Z
2022-03-21T02:28:01.000Z
examples/tvm/boo.cpp
koinos/hunter
fc17bc391210bf139c55df7f947670c5dff59c57
[ "BSD-2-Clause" ]
1,778
2015-01-03T11:50:30.000Z
2019-12-26T05:31:20.000Z
examples/tvm/boo.cpp
koinos/hunter
fc17bc391210bf139c55df7f947670c5dff59c57
[ "BSD-2-Clause" ]
734
2015-03-05T19:52:34.000Z
2022-02-22T23:18:54.000Z
#include <nnvm/op.h> int main() { }
7.4
20
0.567568
Costallat
21c3ed1078a974a784db092b29cf492df2229463
350
cpp
C++
Day5/FCTRL.cpp
Yashdew/DSA
d211d3b53acd28879233e55b77745b60ff44410f
[ "MIT" ]
4
2021-04-13T11:04:45.000Z
2021-12-06T16:32:28.000Z
Day5/FCTRL.cpp
Yashdew/DSA
d211d3b53acd28879233e55b77745b60ff44410f
[ "MIT" ]
null
null
null
Day5/FCTRL.cpp
Yashdew/DSA
d211d3b53acd28879233e55b77745b60ff44410f
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int t; int n; cin>>t; while(t--) { cin>>n; if(n>=1 && n<=1000000000) { int c=0; while(n>=5) { n=n/5; c=c+n; } cout<<c<<endl; } } return 0; }
14.583333
33
0.314286
Yashdew
21c66edf4ac622df28ca3145f6157a4b490e160d
16,198
hpp
C++
Public/Ava/Private/Containers/HashTable.hpp
vasama/Ava
c1e6fb87a493dc46ce870220c632069f00875d2c
[ "MIT" ]
null
null
null
Public/Ava/Private/Containers/HashTable.hpp
vasama/Ava
c1e6fb87a493dc46ce870220c632069f00875d2c
[ "MIT" ]
null
null
null
Public/Ava/Private/Containers/HashTable.hpp
vasama/Ava
c1e6fb87a493dc46ce870220c632069f00875d2c
[ "MIT" ]
null
null
null
#pragma once #include "Ava/Containers/StoragePolicy.hpp" #include "Ava/Math/Math.hpp" #include "Ava/Memory/NoInit.hpp" #include "Ava/Memory/Storage.hpp" #include "Ava/Meta/Constant.hpp" #include "Ava/Meta/Identity.hpp" #include "Ava/Meta/TypeTraits.hpp" #include "Ava/Misc.hpp" #include "Ava/Private/Ebo.hpp" #include "Ava/Types.hpp" #include "Ava/Utility/Hash.hpp" namespace Ava::Private::Containers_HashTable { enum class Ctrl : byte { Null = 0b00000000, Last = 0b01111111, Flag = 0b10000000, Mask = 0b01111111, }; constexpr Ava_FORCEINLINE Ctrl operator|(Ctrl lhs, Ctrl rhs) { return (Ctrl)((byte)lhs | (byte)rhs); } constexpr Ava_FORCEINLINE Ctrl operator&(Ctrl lhs, Ctrl rhs) { return (Ctrl)((byte)lhs & (byte)rhs); } extern const uword JumpOffsets[]; template<typename T> struct Block { //TODO: calculate optimal size static constexpr iword Size = 8; Ctrl m_ctrl[Size]; Storage<T> m_data[Size]; }; constexpr iword MaxBlockSize = 16; extern const Ctrl EmptyBlock[]; template<typename T> void Clean(Block<T>* blocks, iword blockCount) { if constexpr (!IsTriviallyDestructible<T>) { for (Block<T>* f = blocks, *l = f + blockCount; f != l; ++f) for (iword index = 0; index < Block<T>::Size; ++index) if (f->m_ctrl[index] != Ctrl::Null) f->m_data[index].Destroy(); } else Ava_UNUSED(blocks, blockCount); } template<typename T> struct IteratorBase { typedef T ElementType; typedef Block<T> BlockType; ElementType* m_element; BlockType* m_block; }; template<typename T> class BasicIterator : IteratorBase<RemoveConst<T>> { typedef IteratorBase<RemoveConst<T>> Base; public: Ava_FORCEINLINE BasicIterator(decltype(NoInit)) { } Ava_FORCEINLINE T& operator*() const { return *Base::m_element; } Ava_FORCEINLINE T* operator->() const { return Base::m_element; } Ava_FORCEINLINE BasicIterator& operator++() { IncrementInternal(); return *this; } Ava_FORCEINLINE BasicIterator operator++(int) { BasicIterator result = *this; IncrementInternal(); return result; } private: void IncrementInternal() { typename Base::ElementType* element = Base::m_element; typename Base::BlockType* block = Base::m_block; while (true) { Ctrl* first = block->m_ctrl + (element - &block->m_data); Ctrl* last = block->m_ctrl + Base::BlockType::Size; for (Ctrl* ctrl = first; ++ctrl != last;) if (*ctrl == Ctrl::Null) { Base::m_element = element + (ctrl - first); Base::m_block = block; return; } element = &++block->m_data; } } friend Ava_FORCEINLINE bool operator==( const BasicIterator<T>& lhs, const BasicIterator<T>& rhs) { return lhs.m_element == rhs.m_element && lhs.m_block == rhs.m_block; } friend Ava_FORCEINLINE bool operator!=( const BasicIterator<T>& lhs, const BasicIterator<T>& rhs) { return lhs.m_element != rhs.m_element || lhs.m_block != rhs.m_block; } }; template<typename T, typename THasher, typename TStoragePolicy> class StorageLayer { static_assert(Identity<False, T>::Value, "Unsupported storage policy"); }; template<typename TBase, typename THasher> struct HasherLayer : Ava_EBO(TBase, THasher) { template<typename TInHasher> Ava_FORCEINLINE HasherLayer(TInHasher&& hasher) : THasher(Forward<TInHasher>(hasher)) { } }; /* Remote storage policy */ template<typename TBlock> struct Remote_Base { TBlock* m_blocks; u32 m_size; u32 m_capacity; }; template<typename TBlock, typename THasher, typename TAllocator> class StorageLayer<TBlock, THasher, StoragePolicy::Remote<TAllocator>> : Ava_EBOX(public, HasherLayer<Remote_Base<TBlock>, THasher>, TAllocator) { typedef Remote_Base<TBlock> Base; typedef HasherLayer<Base, THasher> HasherLayer; public: typedef TAllocator AllocatorType; static constexpr bool CanGrow = true; Ava_CLANG_WARNING(push) Ava_CLANG_WARNING(ignored "-Wreorder") template<typename TInHasher> Ava_FORCEINLINE StorageLayer(const AllocatorType& alloc, TInHasher&& hasher) : HasherLayer(Forward<TInHasher>(hasher)), TAllocator(alloc) { Base::m_blocks = (TBlock*)EmptyBlock; Base::m_size = 0; Base::m_capacity = 0; } Ava_CLANG_WARNING(pop) Ava_FORCEINLINE ~StorageLayer() { if (iword capacity = Base::m_capacity) { TBlock* blocks = Base::m_blocks; iword blockCount = capacity / TBlock::Size; Clean(blocks, blockCount); Deallocate(blocks, blockCount); } } Ava_FORCEINLINE iword GetSize() const { return (iword)Base::m_size; } Ava_FORCEINLINE void SetSize(iword size) { Base::m_size = (u32)size; } Ava_FORCEINLINE iword GetCapacity() const { return (iword)Base::m_capacity; } Ava_FORCEINLINE TBlock* GetBlocks() const { return Base::m_blocks; } //TODO: try to improve the internal grow interface Ava_FORCEINLINE TBlock* SwapBlocks(iword blockCount) { TBlock* blocks = Allocate(blockCount); Base::m_blocks = blocks; Base::m_capacity = (u32)(blockCount * TBlock::Size); return blocks; } Ava_FORCEINLINE void FreeBlocks(TBlock* blocks, iword blockCount) { Deallocate(blocks, blockCount); } Ava_FORCEINLINE void SetDefaultBlocks() { Base::m_blocks = (TBlock*)EmptyBlock; Base::m_capacity = 0; } private: Ava_FORCEINLINE TBlock* Allocate(iword blockCount) { return (TBlock*)static_cast<const TAllocator*>(this) ->Allocate(sizeof(TBlock) * blockCount); } Ava_FORCEINLINE void Deallocate(TBlock* blocks, iword blockCount) { static_cast<const TAllocator*>(this) ->Deallocate(blocks, sizeof(TBlock) * blockCount); } }; Ava_FORCEINLINE iword GetMaxSize(iword capacity) { // ~ capacity * 15/16 return capacity - (capacity / 16); } Ava_FORCEINLINE uword GetIndexMask(iword capacity) { return (uword)(capacity > 1 ? capacity - 1 : 1); } Ava_FORCEINLINE uword GetIndexShift(uword mask) { return Math::Lzcnt(mask); } template<uword = sizeof(uword)> struct Phi; template<> struct Phi<4> { static constexpr u32 Value = 2654435769u; }; template<> struct Phi<8> { static constexpr u64 Value = 11400714819323198485u; }; Ava_FORCEINLINE iword HashToIndex(uword hash, uword shift) { return (iword)((hash * Phi<>::Value) >> shift); } Ava_FORCEINLINE iword Jump(iword index, Ctrl jump, uword mask) { return (iword)(((uword)index + JumpOffsets[(iword)jump]) & mask); } template<typename T, typename TTraits, typename THasher, typename TStoragePolicy> class Table : public StorageLayer<Block<T>, THasher, TStoragePolicy> { typedef Block<T> BlockType; typedef StorageLayer<BlockType, THasher, TStoragePolicy> Base; typedef typename TTraits::template SelectKeyType<T> KeyType; public: typedef typename Base::AllocatorType AllocatorType; typedef BasicIterator< T> Iterator; typedef BasicIterator<const T> ConstIterator; struct InsertResult { T* Element; bool Inserted; }; template<typename TInHasher> Ava_FORCEINLINE Table(const AllocatorType& alloc, TInHasher&& hasher) : Base(alloc, Forward<TInHasher>(hasher)) { } template<typename TInKey> Ava_FORCEINLINE T* Find(const TInKey& key) const { uword hash = THasher::Hash(key); return FindInternal<const TInKey&>(hash, key); } template<typename TInKey> Ava_FORCEINLINE InsertResult Insert(const TInKey& key) { uword hash = THasher::Hash(key); return InsertInternal<const TInKey&>(hash, key); } template<typename TInKey> Ava_FORCEINLINE bool Remove(const TInKey& key) { uword hash = THasher::Hash(key); return RemoveInternal<const TInKey&>(hash, key); } void Reserve(iword minCapacity) { if constexpr (Base::CanGrow) { iword capacity = Base::GetCapacity(); iword maxSize = GetMaxSize(capacity); if (minCapacity > maxSize) Rehash(Math::Max(capacity * 2, Math::Max(BlockType::Size, (iword)Math::RoundUpToPowerOfTwo((uword)minCapacity)))); } else Ava_Assert(minCapacity < Base::GetCapacity()); } void Clear(bool deallocate) { if (iword capacity = Base::GetCapacity()) { BlockType* blocks = Base::GetBlocks(); iword blockCount = capacity / BlockType::Size; Clean(blocks, blockCount); if constexpr (Base::CanGrow) { if (deallocate) Base::FreeBlocks(blocks, blockCount); Base::SetDefaultBlocks(); } else Ava_UNUSED(deallocate); Base::SetSize(0); } } private: struct Slot { Ctrl* m_ctrl; T* m_data; }; template<typename TInKey> T* FindInternal(uword hash, TInKey key) const { BlockType* const blocks = Base::GetBlocks(); const iword capacity = Base::GetCapacity(); const uword mask = GetIndexMask(capacity); const uword shift = GetIndexShift(mask); const auto GetSlot = [&](iword index) -> Slot { iword blockIndex = index / BlockType::Size; iword valueIndex = index % BlockType::Size; BlockType* block = blocks + blockIndex; return Slot{ &block->m_ctrl[valueIndex], &block->m_data[valueIndex] }; }; iword index = HashToIndex(hash, shift); Slot slot = GetSlot(index); Ctrl ctrl = *slot.m_ctrl; // No value with this hash if ((byte)(ctrl & Ctrl::Flag) == 0) return nullptr; ctrl = ctrl & Ctrl::Mask; while (true) // Search the chain { if (key == TTraits::SelectKey(*slot.m_data)) return slot.m_data; if (Ava_LIKELY(ctrl == Ctrl::Last)) return nullptr; index = Jump(index, ctrl, mask); slot = GetSlot(index); ctrl = *slot.m_ctrl; } } template<typename TInKey> InsertResult InsertInternal(uword hash, TInKey key) { reset: iword capacity = Base::GetCapacity(); if constexpr (Base::CanGrow) if (Ava_UNLIKELY(capacity == 0)) { Rehash(BlockType::Size); capacity = BlockType::Size; } BlockType* blocks = Base::GetBlocks(); const uword mask = GetIndexMask(capacity); const uword shift = GetIndexShift(mask); const auto GetSlot = [&](iword index) -> Slot { iword blockIndex = index / BlockType::Size; iword valueIndex = index % BlockType::Size; BlockType* block = blocks + blockIndex; return Slot{ &block->m_ctrl[valueIndex], &block->m_data[valueIndex] }; }; struct TryInsertResult { Ctrl Jump; Slot Slot; }; const auto TryInsert = [&](iword index) -> TryInsertResult { //TODO: optimize first 16 for (iword i = 1; i < 126; ++i) { Ctrl jump = (Ctrl)i; iword next = Jump(index, jump, mask); Slot slot = GetSlot(next); if (*slot.m_ctrl == Ctrl::Null) return { jump, slot }; } Ava_CLANG_WARNING(push); Ava_CLANG_WARNING(ignored "-Wmissing-field-initializers"); return { Ctrl::Null }; Ava_CLANG_WARNING(pop); }; iword index = HashToIndex(hash, shift); Slot slot = GetSlot(index); Ctrl ctrl = *slot.m_ctrl; if ((byte)(ctrl & Ctrl::Flag) == 0) { iword size = Base::GetSize(); if constexpr (Base::CanGrow) { if (size == GetMaxSize(capacity)) goto rehash; } else Ava_Assert(size < capacity); // if slot is part of another chain if (ctrl != Ctrl::Null) { iword parentIndex; Slot parentSlot; Ctrl parentCtrl; { // find parent in other chain uword parentHash = THasher::Hash( TTraits::SelectKey(*slot.m_data)); parentIndex = HashToIndex(parentHash, shift); while (true) { parentSlot = GetSlot(parentIndex); parentCtrl = *parentSlot.m_ctrl; iword next = Jump(parentIndex, parentCtrl & Ctrl::Mask, mask); if (next == index) break; parentIndex = next; } } iword srcIndex = index; Slot srcSlot = slot; Ctrl srcCtrl = ctrl; while (true) { auto[jump, nextSlot] = TryInsert(parentIndex); // if can't insert if (jump == Ctrl::Null) { //TODO: make sure this is correct // map must be in valid state when rehashing // ska map uses a reserved ctrl value // be sure to leave an explanation if (srcIndex != index) *slot.m_ctrl = Ctrl::Null; goto rehash; } *parentSlot.m_ctrl = (parentCtrl & Ctrl::Flag) | jump; // mark next as last in chain *nextSlot.m_ctrl = Ctrl::Last; // mark source as empty if (srcIndex != index) *srcSlot.m_ctrl = Ctrl::Null; Relocate<T>(nextSlot.m_data, srcSlot.m_data); if (srcCtrl == Ctrl::Last) break; parentIndex = Jump(parentIndex, jump, mask); parentSlot = nextSlot; parentCtrl = jump; iword nextSrcIndex = Jump(srcIndex, srcCtrl, mask); Slot nextSrcSlot = GetSlot(nextSrcIndex); srcIndex = nextSrcIndex; srcSlot = nextSrcSlot; srcCtrl = *nextSrcSlot.m_ctrl; } } *slot.m_ctrl = Ctrl::Flag | Ctrl::Last; Base::SetSize(size + 1); return InsertResult{ slot.m_data, true }; } while (true) { if (key == TTraits::SelectKey(*slot.m_data)) return InsertResult{ slot.m_data, false }; Ctrl jump = ctrl & Ctrl::Mask; if (Ava_LIKELY(jump == Ctrl::Last)) { iword size = Base::GetSize(); if constexpr (Base::CanGrow) { if (size == GetMaxSize(capacity)) goto rehash; } else Ava_Assert(size < capacity); auto[nextJump, nextSlot] = TryInsert(index); if (nextJump == Ctrl::Null) goto rehash; *slot.m_ctrl = (ctrl & Ctrl::Flag) | nextJump; *nextSlot.m_ctrl = Ctrl::Last; Base::SetSize(size + 1); return InsertResult{ nextSlot.m_data, true }; } index = Jump(index, jump, mask); slot = GetSlot(index); ctrl = *slot.m_ctrl; } rehash: if constexpr (Base::CanGrow) { Rehash(capacity * 2); goto reset; } } template<typename TInKey> bool RemoveInternal(uword hash, TInKey key) { BlockType* const blocks = Base::GetBlocks(); const iword capacity = Base::GetCapacity(); uword mask = GetIndexMask(capacity); uword shift = GetIndexShift(mask); const auto GetSlot = [&](iword index) -> Slot { iword blockIndex = index / BlockType::Size; iword valueIndex = index % BlockType::Size; BlockType* block = blocks + blockIndex; return Slot{ &block->m_ctrl[valueIndex], &block->m_data[valueIndex] }; }; iword index = HashToIndex(hash, shift); Slot slot = GetSlot(index); // No value with this hash if ((byte)(*slot.m_ctrl & Ctrl::Flag) == 0) return false; Ctrl* prev = nullptr; while (true) { Ctrl ctrl = *slot.m_ctrl; Ctrl jump = ctrl & Ctrl::Mask; if (key == TTraits::SelectKey(*slot.m_data)) { Destroy<T>(slot.m_data); Base::SetSize(Base::GetSize() - 1); if (Ava_LIKELY(jump == Ctrl::Last)) { *slot.m_ctrl = Ctrl::Null; if (prev != nullptr) *prev = (*prev & Ctrl::Flag) | Ctrl::Last; } else { T* elem = slot.m_data; while (true) { prev = slot.m_ctrl; index = Jump(index, jump, mask); slot = GetSlot(index); ctrl = *slot.m_ctrl; if (Ava_LIKELY(ctrl == Ctrl::Last)) break; jump = ctrl & Ctrl::Mask; } Relocate<T>(elem, slot.m_data); *prev = (*prev & Ctrl::Flag) | Ctrl::Last; *slot.m_ctrl = Ctrl::Null; } return true; } if (Ava_LIKELY(jump == Ctrl::Last)) return false; prev = slot.m_ctrl; index = Jump(index, jump, mask); slot = GetSlot(index); } } Ava_FORCENOINLINE void Rehash(iword newCapacity) { Ava_Assert(newCapacity >= BlockType::Size); iword capacity = Base::GetCapacity(); BlockType* oldBlocks = Base::GetBlocks(); iword newBlockCount = newCapacity / BlockType::Size; BlockType* newBlocks = Base::SwapBlocks(newBlockCount); for (BlockType* f = newBlocks, *l = f + newBlockCount; f != l; ++f) for (iword index = 0; index < BlockType::Size; ++index) f->m_ctrl[index] = Ctrl::Null; if (capacity != 0) { Base::SetSize(0); iword oldBlockCount = capacity / BlockType::Size; for (BlockType* f = oldBlocks, *l = f + oldBlockCount; f != l; ++f) for (iword index = 0; index < BlockType::Size; ++index) if (f->m_ctrl[index] != Ctrl::Null) { const KeyType& key = TTraits::SelectKey(*f->m_data[index]); auto[slot, inserted] = InsertInternal<const KeyType&>(THasher::Hash(key), key); Ava_Assert(inserted); Relocate<T>(slot, &f->m_data[index]); } Base::FreeBlocks(oldBlocks, oldBlockCount); } } }; } // namespace Ava::Private::Containers_HashTable
21.830189
85
0.664959
vasama
21c70d5698e2a0dcbf53601fa17bed3bd947ae1c
3,435
hpp
C++
include/memoria/containers/multimap/multimap_output_values.hpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
2
2021-07-30T16:54:24.000Z
2021-09-08T15:48:17.000Z
include/memoria/containers/multimap/multimap_output_values.hpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
null
null
null
include/memoria/containers/multimap/multimap_output_values.hpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
2
2020-03-14T15:15:25.000Z
2020-06-15T11:26:56.000Z
// Copyright 2019 Victor Smirnov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <memoria/api/multimap/multimap_output.hpp> namespace memoria { namespace multimap { template <typename Types, typename Profile, typename IteratorPtr> class ValuesIteratorImpl: public IValuesScanner<Types, Profile> { using Base = IValuesScanner<Types, Profile>; using typename Base::ValueView; using typename Base::ValuesIOVSubstreamAdapter; using Base::values_; using Base::size_; using Base::run_is_finished_; using Base::values_buffer_; size_t values_start_{}; core::StaticVector<uint64_t, 2> offsets_; DefaultBTFLRunParser<2> parser_; IteratorPtr iter_; uint64_t iteration_num_{}; public: ValuesIteratorImpl(IteratorPtr iter): parser_(iter->iter_local_pos()), iter_(iter) { parse_first(); } virtual bool is_end() const { return iter_->iter_is_end(); } virtual bool next_block() { auto has_next = iter_->iter_next_leaf(); if (has_next) { offsets_.clear(); build_index(); } else { auto leaf_sizes = iter_->iter_leaf_sizes(); iter_->iter_local_pos() = leaf_sizes.sum(); run_is_finished_ = true; } return run_is_finished_; } virtual void fill_suffix_buffer() { while (!is_end()) { fill_buffer(values_start_, values_.size()); auto has_next = next_block(); if (has_next) { break; } } } virtual void dump_iterator() const { iter_->dump(); } private: void fill_buffer(size_t start, size_t end) { const io::IOVector& buffer = iter_->iovector_view(); values_buffer_.template append<ValuesIOVSubstreamAdapter>(buffer.substream(1), 0, start, end); } void parse_first() { iter_->refresh_iovector_view(); auto& ss = iter_->iovector_view().symbol_sequence(); int32_t idx = parser_.start_idx(); ss.rank_to(idx, offsets_.values()); build_index(); } void build_index() { const io::IOVector& buffer = iter_->iovector_view(); auto& ss = buffer.symbol_sequence(); parser_.parse(ss); if (MMA_LIKELY((!parser_.is_empty()) || ss.size() > 0)) { size_t run_size = (!parser_.is_empty()) ? parser_.run_size() : 0; values_start_ = offsets_[1]; values_.clear(); ValuesIOVSubstreamAdapter::read_to(buffer.substream(1), 0, values_start_, run_size, values_.array()); run_is_finished_ = parser_.is_finished(); size_ = run_size; } else { // empty block requires nothing } offsets_.clear(); iteration_num_++; } }; }}
24.190141
113
0.613683
victor-smirnov
21ca4e23f9a709ec49131096ee29afe454b52dd2
11,127
cpp
C++
libraries/smt/source/cvc4.cpp
tneele/mCRL2
8f2d730d650ffec15130d6419f69c50f81e5125c
[ "BSL-1.0" ]
null
null
null
libraries/smt/source/cvc4.cpp
tneele/mCRL2
8f2d730d650ffec15130d6419f69c50f81e5125c
[ "BSL-1.0" ]
null
null
null
libraries/smt/source/cvc4.cpp
tneele/mCRL2
8f2d730d650ffec15130d6419f69c50f81e5125c
[ "BSL-1.0" ]
null
null
null
// Author(s): Ruud Koolen // Copyright: see the accompanying file COPYING or copy at // https://github.com/mCRL2org/mCRL2/blob/master/COPYING // // 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) #include "mcrl2/data/int.h" #include "mcrl2/data/real.h" #include "mcrl2/smt/cvc4.h" #include "mcrl2/smt/recursive_function_definition.h" namespace mcrl2 { namespace smt { class cvc4_identifier_generator : public data::set_identifier_generator { public: virtual core::identifier_string operator()(const std::string& hint, bool add_to_context = true) { std::string name = hint; if (name == "-") name = "minus"; if (name == "[]") name = "emptylist"; if (name == "|>") name = "cons"; if (name == "<|") name = "snoc"; if (name == "#") name = "count"; if (name == "++") name = "concat"; if (name == ".") name = "at"; for (std::size_t i = 0; i < name.size(); i++) { if (!( ('0' <= name[i] && name[i] <= '9') || ('a' <= name[i] && name[i] <= 'z') || ('A' <= name[i] && name[i] <= 'Z'))) { name[i] = '_'; } } return data::set_identifier_generator::operator()(name, add_to_context); } }; class pos_sort_definition : public sort_definition { public: pos_sort_definition(data_specification *data_specification): sort_definition(data_specification, "Int") {} std::string generate_variable_declaration(const core::identifier_string& name) const { return sort_definition::generate_variable_declaration(name) + "(assert (>= " + (std::string)name + " 1))\n"; } }; class nat_sort_definition : public sort_definition { public: nat_sort_definition(data_specification *data_specification): sort_definition(data_specification, "Int") {} std::string generate_variable_declaration(const core::identifier_string& name) const { return sort_definition::generate_variable_declaration(name) + "(assert (>= " + (std::string)name + " 0))\n"; } }; static std::string print_nat(const data::data_expression& number) { return data::pp(number); } static std::string print_int(const data::data_expression& number) { assert(data::sort_int::is_cint_application(number) || data::sort_int::is_cneg_application(number)); if (data::sort_int::is_cneg_application(number)) { data::application application(number); assert(application.size() == 1); return "(- " + data::pp(application[0]) + ")"; } else { return data::pp(number); } } static std::string print_real(const data::data_expression& number) { assert(data::sort_real::is_creal_application(number)); data::application application(number); std::string numerator = print_int(application[0]); std::string denominator = data::pp(application[1]); return "(/ " + numerator + " " + denominator + ")"; } static std::shared_ptr<function_definition> make_operator(data_specification* data_specification, const std::string& name) { return std::shared_ptr<function_definition>(new named_function_definition(data_specification, name)); } smt4_data_specification::smt4_data_specification(const data::data_specification& data_specification): basic_data_specification(data_specification, std::shared_ptr<data::set_identifier_generator>(new cvc4_identifier_generator)) { add_sort_bool(std::shared_ptr<sort_definition>(new sort_definition(this, "Bool")), "true", "false"); add_sort_pos(std::shared_ptr<sort_definition>(new pos_sort_definition(this)), print_nat); add_sort_nat(std::shared_ptr<sort_definition>(new nat_sort_definition(this)), print_nat); add_sort_int(std::shared_ptr<sort_definition>(new sort_definition(this, "Int")), print_int); add_sort_real(std::shared_ptr<sort_definition>(new sort_definition(this, "Real")), print_real); add_constructed_sorts(data_specification); add_standard_operators( data_specification, make_operator(this, "="), make_operator(this, "distinct"), make_operator(this, "ite") ); add_boolean_operators( data_specification, make_operator(this, "not"), make_operator(this, "and"), make_operator(this, "or"), make_operator(this, "=>") ); add_numerical_operators( data_specification, make_operator(this, "<"), make_operator(this, "<="), make_operator(this, ">"), make_operator(this, ">="), make_operator(this, "+"), make_operator(this, "-"), make_operator(this, "*"), make_operator(this, "/"), make_operator(this, "div"), make_operator(this, "mod"), make_operator(this, "to_int"), nullptr, // ceil nullptr, // round make_operator(this, "-"), nullptr, // maximum nullptr, // minimum make_operator(this, "abs") ); add_recursive_functions(data_specification); } std::string smt4_data_specification::generate_data_expression(const std::map<data::variable, std::string>& declared_variables, const std::string& function_name, const data::data_expression_vector& arguments) const { if (arguments.empty()) { return function_name; } else { std::string output; output += "("; output += function_name; for (data::data_expression_vector::const_iterator i = arguments.begin(); i != arguments.end(); i++) { output += " "; output += generate_data_expression(declared_variables, *i); } output += ")"; return output; } } std::string smt4_data_specification::generate_variable_declaration(const std::string& type_name, const std::string& variable_name) const { return "(declare-fun " + variable_name + " () " + type_name + ")\n"; } std::string smt4_data_specification::generate_assertion(const std::map<data::variable, std::string>& declared_variables, const data::data_expression& assertion) const { return "(assert " + generate_data_expression(declared_variables, assertion) + ")\n"; } std::string smt4_data_specification::generate_distinct_assertion(const std::map<data::variable, std::string>& declared_variables, const data::data_expression_list& distinct_terms) const { std::string output = "(distinct"; for (data::data_expression_list::const_iterator i = distinct_terms.begin(); i != distinct_terms.end(); i++) { output += " "; output += generate_data_expression(declared_variables, *i); } output += ")\n"; return output; } std::string smt4_data_specification::generate_smt_problem(const std::string& variable_declarations, const std::string& assertions) const { return variable_declarations + assertions + "(check-sat)\n"; } class cvc4_constructed_sort_definition : public constructed_sort_definition { protected: std::map<data::function_symbol, std::string> m_constructor_names; std::map<data::function_symbol, std::vector<std::string> > m_field_names; public: cvc4_constructed_sort_definition(data_specification *data_specification, data::sort_expression sort, const constructors_t &constructors): constructed_sort_definition(data_specification, sort, constructors) { for (std::size_t i = 0; i < m_constructors.size(); i++) { std::string name = data_specification->identifier_generator()(m_constructors[i].constructor.name()); std::string recogniser_name = "is-" + name; data_specification->identifier_generator().add_identifier(recogniser_name); m_constructor_names[m_constructors[i].constructor] = name; add_constructor_definition(i, new named_function_definition(data_specification, m_constructors[i].constructor.sort(), name)); add_recogniser_definition(i, new named_function_definition(data_specification, recogniser_name)); for (std::size_t j = 0; j < m_constructors[i].fields.size(); j++) { std::string field_name = data_specification->identifier_generator()(m_constructors[i].fields[j].projections[0].name()); m_field_names[m_constructors[i].constructor].push_back(field_name); add_projection_definition(i, j, new named_function_definition(data_specification, field_name)); } } } std::string generate_definition() const { std::string output = "(declare-datatypes () ( (" + m_name + "\n"; for (std::size_t i = 0; i < m_constructors.size(); i++) { output += " (" + m_constructor_names.at(m_constructors[i].constructor); for (std::size_t j = 0; j < m_constructors[i].fields.size(); j++) { assert(data::is_function_sort(m_constructors[i].fields[j].projections[0].sort())); std::string sort_name = m_data_specification->generate_sort_name(data::function_sort(m_constructors[i].fields[j].projections[0].sort()).codomain()); output += " (" + m_field_names.at(m_constructors[i].constructor)[j] + " " + sort_name + ")"; } output += ")\n"; } output += ")))\n"; return output; } }; constructed_sort_definition *smt4_data_specification::create_constructed_sort(const data::sort_expression& sort, const constructed_sort_definition::constructors_t &constructors) { return new cvc4_constructed_sort_definition(this, sort, constructors); } class cvc4_recursive_function_definition : public recursive_function_definition { protected: data::sort_expression m_codomain; public: cvc4_recursive_function_definition(data_specification *data_specification, data::function_symbol function, const data::data_equation_vector& rewrite_rules): recursive_function_definition(data_specification, function, rewrite_rules) { if (data::is_function_sort(function.sort())) { m_codomain = data::function_sort(function.sort()).codomain(); } else { m_codomain = function.sort(); } } std::string generate_definition() const { std::map<data::variable, std::string> parameters; for (std::size_t i = 0; i < m_parameters.size(); i++) { std::string name = m_data_specification->identifier_generator()(m_parameters[i].name()); parameters[m_parameters[i]] = name; } for (std::size_t i = 0; i < m_parameters.size(); i++) { m_data_specification->identifier_generator().remove_identifier(parameters[m_parameters[i]]); } std::string output = "(define-fun-rec " + m_name + " ("; for (std::size_t i = 0; i < m_parameters.size(); i++) { output += " (" + parameters[m_parameters[i]] + " " + m_data_specification->generate_sort_name(m_parameters[i].sort()) + ")"; } output += ") " + m_data_specification->generate_sort_name(m_codomain); output += " " + m_data_specification->generate_data_expression(parameters, m_rhs); output += ")\n"; return output; } }; function_definition *smt4_data_specification::create_recursive_function_definition(const data::function_symbol& function, const data::data_equation_vector& rewrite_rules) { return new cvc4_recursive_function_definition(this, function, rewrite_rules); } } // namespace smt } // namespace mcrl2
36.126623
213
0.686169
tneele
21ca9f840d9ecad5624ba2474946b25d9dea0de2
15,220
cc
C++
components/autofill/core/browser/autofill_metrics.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
components/autofill/core/browser/autofill_metrics.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/autofill/core/browser/autofill_metrics.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill/core/browser/autofill_metrics.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/metrics/sparse_histogram.h" #include "base/time/time.h" #include "components/autofill/core/browser/autofill_type.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/common/form_data.h" namespace autofill { namespace { enum FieldTypeGroupForMetrics { GROUP_AMBIGUOUS = 0, GROUP_NAME, GROUP_COMPANY, GROUP_ADDRESS_LINE_1, GROUP_ADDRESS_LINE_2, GROUP_ADDRESS_CITY, GROUP_ADDRESS_STATE, GROUP_ADDRESS_ZIP, GROUP_ADDRESS_COUNTRY, GROUP_PHONE, GROUP_FAX, // Deprecated. GROUP_EMAIL, GROUP_CREDIT_CARD_NAME, GROUP_CREDIT_CARD_NUMBER, GROUP_CREDIT_CARD_DATE, GROUP_CREDIT_CARD_TYPE, GROUP_PASSWORD, GROUP_ADDRESS_LINE_3, NUM_FIELD_TYPE_GROUPS_FOR_METRICS }; } // namespace // First, translates |field_type| to the corresponding logical |group| from // |FieldTypeGroupForMetrics|. Then, interpolates this with the given |metric|, // which should be in the range [0, |num_possible_metrics|). // Returns the interpolated index. // // The interpolation maps the pair (|group|, |metric|) to a single index, so // that all the indicies for a given group are adjacent. In particular, with // the groups {AMBIGUOUS, NAME, ...} combining with the metrics {UNKNOWN, MATCH, // MISMATCH}, we create this set of mapped indices: // { // AMBIGUOUS+UNKNOWN, // AMBIGUOUS+MATCH, // AMBIGUOUS+MISMATCH, // NAME+UNKNOWN, // NAME+MATCH, // NAME+MISMATCH, // ... // }. // // Clients must ensure that |field_type| is one of the types Chrome supports // natively, e.g. |field_type| must not be a billng address. // NOTE: This is defined outside of the anonymous namespace so that it can be // accessed from the unit test file. It is not exposed in the header file, // however, because it is not intended for consumption outside of the metrics // implementation. int GetFieldTypeGroupMetric(ServerFieldType field_type, AutofillMetrics::FieldTypeQualityMetric metric) { DCHECK_LT(metric, AutofillMetrics::NUM_FIELD_TYPE_QUALITY_METRICS); FieldTypeGroupForMetrics group = GROUP_AMBIGUOUS; switch (AutofillType(field_type).group()) { case NO_GROUP: group = GROUP_AMBIGUOUS; break; case NAME: case NAME_BILLING: group = GROUP_NAME; break; case COMPANY: group = GROUP_COMPANY; break; case ADDRESS_HOME: case ADDRESS_BILLING: switch (AutofillType(field_type).GetStorableType()) { case ADDRESS_HOME_LINE1: group = GROUP_ADDRESS_LINE_1; break; case ADDRESS_HOME_LINE2: group = GROUP_ADDRESS_LINE_2; break; case ADDRESS_HOME_LINE3: group = GROUP_ADDRESS_LINE_3; break; case ADDRESS_HOME_CITY: group = GROUP_ADDRESS_CITY; break; case ADDRESS_HOME_STATE: group = GROUP_ADDRESS_STATE; break; case ADDRESS_HOME_ZIP: group = GROUP_ADDRESS_ZIP; break; case ADDRESS_HOME_COUNTRY: group = GROUP_ADDRESS_COUNTRY; break; default: NOTREACHED(); group = GROUP_AMBIGUOUS; break; } break; case EMAIL: group = GROUP_EMAIL; break; case PHONE_HOME: case PHONE_BILLING: group = GROUP_PHONE; break; case CREDIT_CARD: switch (field_type) { case CREDIT_CARD_NAME: group = GROUP_CREDIT_CARD_NAME; break; case CREDIT_CARD_NUMBER: group = GROUP_CREDIT_CARD_NUMBER; break; case CREDIT_CARD_TYPE: group = GROUP_CREDIT_CARD_TYPE; break; case CREDIT_CARD_EXP_MONTH: case CREDIT_CARD_EXP_2_DIGIT_YEAR: case CREDIT_CARD_EXP_4_DIGIT_YEAR: case CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR: case CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR: group = GROUP_CREDIT_CARD_DATE; break; default: NOTREACHED(); group = GROUP_AMBIGUOUS; break; } break; case PASSWORD_FIELD: group = GROUP_PASSWORD; break; case TRANSACTION: NOTREACHED(); break; } // Interpolate the |metric| with the |group|, so that all metrics for a given // |group| are adjacent. return (group * AutofillMetrics::NUM_FIELD_TYPE_QUALITY_METRICS) + metric; } namespace { std::string WalletApiMetricToString( AutofillMetrics::WalletApiCallMetric metric) { switch (metric) { case AutofillMetrics::ACCEPT_LEGAL_DOCUMENTS: return "AcceptLegalDocuments"; case AutofillMetrics::AUTHENTICATE_INSTRUMENT: return "AuthenticateInstrument"; case AutofillMetrics::GET_FULL_WALLET: return "GetFullWallet"; case AutofillMetrics::GET_WALLET_ITEMS: return "GetWalletItems"; case AutofillMetrics::SAVE_TO_WALLET: return "SaveToWallet"; case AutofillMetrics::UNKNOWN_API_CALL: case AutofillMetrics::NUM_WALLET_API_CALLS: NOTREACHED(); return "UnknownApiCall"; } NOTREACHED(); return "UnknownApiCall"; } // A version of the UMA_HISTOGRAM_ENUMERATION macro that allows the |name| // to vary over the program's runtime. void LogUMAHistogramEnumeration(const std::string& name, int sample, int boundary_value) { DCHECK_LT(sample, boundary_value); // Note: This leaks memory, which is expected behavior. base::HistogramBase* histogram = base::LinearHistogram::FactoryGet( name, 1, boundary_value, boundary_value + 1, base::HistogramBase::kUmaTargetedHistogramFlag); histogram->Add(sample); } // A version of the UMA_HISTOGRAM_TIMES macro that allows the |name| // to vary over the program's runtime. void LogUMAHistogramTimes(const std::string& name, const base::TimeDelta& duration) { // Note: This leaks memory, which is expected behavior. base::HistogramBase* histogram = base::Histogram::FactoryTimeGet( name, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromSeconds(10), 50, base::HistogramBase::kUmaTargetedHistogramFlag); histogram->AddTime(duration); } // A version of the UMA_HISTOGRAM_LONG_TIMES macro that allows the |name| // to vary over the program's runtime. void LogUMAHistogramLongTimes(const std::string& name, const base::TimeDelta& duration) { // Note: This leaks memory, which is expected behavior. base::HistogramBase* histogram = base::Histogram::FactoryTimeGet( name, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 50, base::HistogramBase::kUmaTargetedHistogramFlag); histogram->AddTime(duration); } // Logs a type quality metric. The primary histogram name is constructed based // on |base_name|. The field-specific histogram name also factors in the // |field_type|. Logs a sample of |metric|, which should be in the range // [0, |num_possible_metrics|). void LogTypeQualityMetric(const std::string& base_name, AutofillMetrics::FieldTypeQualityMetric metric, ServerFieldType field_type) { DCHECK_LT(metric, AutofillMetrics::NUM_FIELD_TYPE_QUALITY_METRICS); LogUMAHistogramEnumeration(base_name, metric, AutofillMetrics::NUM_FIELD_TYPE_QUALITY_METRICS); int field_type_group_metric = GetFieldTypeGroupMetric(field_type, metric); int num_field_type_group_metrics = AutofillMetrics::NUM_FIELD_TYPE_QUALITY_METRICS * NUM_FIELD_TYPE_GROUPS_FOR_METRICS; LogUMAHistogramEnumeration(base_name + ".ByFieldType", field_type_group_metric, num_field_type_group_metrics); } } // namespace // static void AutofillMetrics::LogCreditCardInfoBarMetric(InfoBarMetric metric) { DCHECK_LT(metric, NUM_INFO_BAR_METRICS); UMA_HISTOGRAM_ENUMERATION("Autofill.CreditCardInfoBar", metric, NUM_INFO_BAR_METRICS); } // static void AutofillMetrics::LogScanCreditCardPromptMetric( ScanCreditCardPromptMetric metric) { DCHECK_LT(metric, NUM_SCAN_CREDIT_CARD_PROMPT_METRICS); UMA_HISTOGRAM_ENUMERATION("Autofill.ScanCreditCardPrompt", metric, NUM_SCAN_CREDIT_CARD_PROMPT_METRICS); } // static void AutofillMetrics::LogDialogDismissalState(DialogDismissalState state) { UMA_HISTOGRAM_ENUMERATION("RequestAutocomplete.DismissalState", state, NUM_DIALOG_DISMISSAL_STATES); } // static void AutofillMetrics::LogDialogInitialUserState( DialogInitialUserStateMetric user_type) { UMA_HISTOGRAM_ENUMERATION("RequestAutocomplete.InitialUserState", user_type, NUM_DIALOG_INITIAL_USER_STATE_METRICS); } // static void AutofillMetrics::LogDialogLatencyToShow(const base::TimeDelta& duration) { LogUMAHistogramTimes("RequestAutocomplete.UiLatencyToShow", duration); } // static void AutofillMetrics::LogDialogPopupEvent(DialogPopupEvent event) { UMA_HISTOGRAM_ENUMERATION("RequestAutocomplete.PopupInDialog", event, NUM_DIALOG_POPUP_EVENTS); } // static void AutofillMetrics::LogDialogSecurityMetric(DialogSecurityMetric metric) { UMA_HISTOGRAM_ENUMERATION("RequestAutocomplete.Security", metric, NUM_DIALOG_SECURITY_METRICS); } // static void AutofillMetrics::LogDialogUiDuration( const base::TimeDelta& duration, DialogDismissalAction dismissal_action) { std::string suffix; switch (dismissal_action) { case DIALOG_ACCEPTED: suffix = "Submit"; break; case DIALOG_CANCELED: suffix = "Cancel"; break; } LogUMAHistogramLongTimes("RequestAutocomplete.UiDuration", duration); LogUMAHistogramLongTimes("RequestAutocomplete.UiDuration." + suffix, duration); } // static void AutofillMetrics::LogDialogUiEvent(DialogUiEvent event) { UMA_HISTOGRAM_ENUMERATION("RequestAutocomplete.UiEvents", event, NUM_DIALOG_UI_EVENTS); } // static void AutofillMetrics::LogWalletErrorMetric(WalletErrorMetric metric) { UMA_HISTOGRAM_ENUMERATION("RequestAutocomplete.WalletErrors", metric, NUM_WALLET_ERROR_METRICS); } // static void AutofillMetrics::LogWalletApiCallDuration( WalletApiCallMetric metric, const base::TimeDelta& duration) { LogUMAHistogramTimes("Wallet.ApiCallDuration." + WalletApiMetricToString(metric), duration); } // static void AutofillMetrics::LogWalletMalformedResponseMetric( WalletApiCallMetric metric) { UMA_HISTOGRAM_ENUMERATION("Wallet.MalformedResponse", metric, NUM_WALLET_API_CALLS); } // static void AutofillMetrics::LogWalletRequiredActionMetric( WalletRequiredActionMetric required_action) { UMA_HISTOGRAM_ENUMERATION("RequestAutocomplete.WalletRequiredActions", required_action, NUM_WALLET_REQUIRED_ACTIONS); } // static void AutofillMetrics::LogWalletResponseCode(int response_code) { UMA_HISTOGRAM_SPARSE_SLOWLY("Wallet.ResponseCode", response_code); } // static void AutofillMetrics::LogDeveloperEngagementMetric( DeveloperEngagementMetric metric) { DCHECK_LT(metric, NUM_DEVELOPER_ENGAGEMENT_METRICS); UMA_HISTOGRAM_ENUMERATION("Autofill.DeveloperEngagement", metric, NUM_DEVELOPER_ENGAGEMENT_METRICS); } // static void AutofillMetrics::LogHeuristicTypePrediction(FieldTypeQualityMetric metric, ServerFieldType field_type) { LogTypeQualityMetric("Autofill.Quality.HeuristicType", metric, field_type); } // static void AutofillMetrics::LogOverallTypePrediction(FieldTypeQualityMetric metric, ServerFieldType field_type) { LogTypeQualityMetric("Autofill.Quality.PredictedType", metric, field_type); } // static void AutofillMetrics::LogServerTypePrediction(FieldTypeQualityMetric metric, ServerFieldType field_type) { LogTypeQualityMetric("Autofill.Quality.ServerType", metric, field_type); } // static void AutofillMetrics::LogServerQueryMetric(ServerQueryMetric metric) { DCHECK_LT(metric, NUM_SERVER_QUERY_METRICS); UMA_HISTOGRAM_ENUMERATION("Autofill.ServerQueryResponse", metric, NUM_SERVER_QUERY_METRICS); } // static void AutofillMetrics::LogUserHappinessMetric(UserHappinessMetric metric) { DCHECK_LT(metric, NUM_USER_HAPPINESS_METRICS); UMA_HISTOGRAM_ENUMERATION("Autofill.UserHappiness", metric, NUM_USER_HAPPINESS_METRICS); } // static void AutofillMetrics::LogFormFillDurationFromLoadWithAutofill( const base::TimeDelta& duration) { UMA_HISTOGRAM_CUSTOM_TIMES("Autofill.FillDuration.FromLoad.WithAutofill", duration, base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMinutes(10), 50); } // static void AutofillMetrics::LogFormFillDurationFromLoadWithoutAutofill( const base::TimeDelta& duration) { UMA_HISTOGRAM_CUSTOM_TIMES("Autofill.FillDuration.FromLoad.WithoutAutofill", duration, base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMinutes(10), 50); } // static void AutofillMetrics::LogFormFillDurationFromInteractionWithAutofill( const base::TimeDelta& duration) { UMA_HISTOGRAM_CUSTOM_TIMES( "Autofill.FillDuration.FromInteraction.WithAutofill", duration, base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMinutes(10), 50); } // static void AutofillMetrics::LogFormFillDurationFromInteractionWithoutAutofill( const base::TimeDelta& duration) { UMA_HISTOGRAM_CUSTOM_TIMES( "Autofill.FillDuration.FromInteraction.WithoutAutofill", duration, base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMinutes(10), 50); } // static void AutofillMetrics::LogIsAutofillEnabledAtStartup(bool enabled) { UMA_HISTOGRAM_BOOLEAN("Autofill.IsEnabled.Startup", enabled); } // static void AutofillMetrics::LogIsAutofillEnabledAtPageLoad(bool enabled) { UMA_HISTOGRAM_BOOLEAN("Autofill.IsEnabled.PageLoad", enabled); } // static void AutofillMetrics::LogStoredProfileCount(size_t num_profiles) { UMA_HISTOGRAM_COUNTS("Autofill.StoredProfileCount", num_profiles); } // static void AutofillMetrics::LogAddressSuggestionsCount(size_t num_suggestions) { UMA_HISTOGRAM_COUNTS("Autofill.AddressSuggestionsCount", num_suggestions); } } // namespace autofill
32.452026
80
0.696649
kjthegod
21d073a1bc21a4c0fae9ec138f730ef90cb79031
920
cpp
C++
campion-era/degrade/degrade2.cpp
GeorgianBadita/algorithmic-problems
6b260050b7a1768b5e47a1d7d4ef7138a52db210
[ "MIT" ]
1
2021-07-05T16:32:14.000Z
2021-07-05T16:32:14.000Z
campion-era/degrade/degrade2.cpp
GeorgianBadita/algorithmic-problems
6b260050b7a1768b5e47a1d7d4ef7138a52db210
[ "MIT" ]
null
null
null
campion-era/degrade/degrade2.cpp
GeorgianBadita/algorithmic-problems
6b260050b7a1768b5e47a1d7d4ef7138a52db210
[ "MIT" ]
1
2021-05-14T15:40:09.000Z
2021-05-14T15:40:09.000Z
#include<fstream> #include<cstring> #include<algorithm> using namespace std; ifstream f("degrade.in"); ofstream g("degrade.out"); int v[100002],y[100002]; char s[100002],w[100002],x[100002]; int main() { int u,n,i,j,s1[100],max=0,nr=0,l,p; for(i=1;i<=10;i++) f>>s[i]; for(i=1;i<=10;i++) v[i]=s[i]-'0'; //for(i=1;i<=n;i++) g<<v[i]<<' '; // f>>w; n=16; for(i=1;i<=n;i++) {f>>x[i];} //g<<x[i]<<' ';} for(i=1;i<=n;++i) for(j=1;j<=10;j++) if(x[i]==s[j]) {y[i]=v[j];}// g<<y[i]<<' ';} //g<<y[i]<<' ';} //for(i=1;i<=n;i++) g<<y[i]<<' '; for(i=1;i<=n-1;i++) { s1[++l]=1; j=i+1; p=i; while(y[p]<=y[j]) { s1[l]++; j++; p++; if(j==n) break; } if(s1[l]>max) max=s1[l]; i=p; } for(i=1;i<=l;i++) if(s1[i]==max) nr++; g<<max<<' '<<nr; }
24.864865
69
0.379348
GeorgianBadita
21d08c6f18b2fe49d9d9ecfec56a9550565db059
3,056
cpp
C++
gui/core/imageloader.cpp
Skycoder42/SeasonProxer
dcdf284883c532fcccf30f9608d9abe2e8e64e3e
[ "BSD-3-Clause" ]
2
2018-04-25T14:42:25.000Z
2019-03-21T12:31:17.000Z
gui/core/imageloader.cpp
Skycoder42/SeasonProxer
dcdf284883c532fcccf30f9608d9abe2e8e64e3e
[ "BSD-3-Clause" ]
null
null
null
gui/core/imageloader.cpp
Skycoder42/SeasonProxer
dcdf284883c532fcccf30f9608d9abe2e8e64e3e
[ "BSD-3-Clause" ]
null
null
null
#include "imageloader.h" #include <QDir> #include <QImageReader> #include <QStandardPaths> #include <QUuid> #include <QtConcurrent> const QString ImageLoader::CacheDirName = QStringLiteral("preview-images"); const QString ImageLoader::ImageNameTemplate = QStringLiteral("img_%1.png"); ImageLoader::ImageLoader(QObject *parent) : QObject(parent), _nam(nullptr), _cache() {} void ImageLoader::loadImage(int id) { QMetaObject::invokeMethod(this, "loadImageImpl", Qt::QueuedConnection, Q_ARG(int, id)); } void ImageLoader::clearCache() { QMetaObject::invokeMethod(this, "clearCacheImpl", Qt::QueuedConnection); } void ImageLoader::loadImageImpl(int id) { // check if cached auto imagePtr = _cache.object(id); if(imagePtr) { emit imageLoaded(id, *imagePtr); return; } // check if in cache dir QDir cacheDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)); if(cacheDir.mkpath(CacheDirName) && cacheDir.cd(CacheDirName)) { auto imgPath = cacheDir.absoluteFilePath(ImageNameTemplate.arg(id)); if(QFile::exists(imgPath)) { QImage image(imgPath, "png"); if(!image.isNull()) { _cache.insert(id, new QImage(image)); emit imageLoaded(id, image); return; } } } else qWarning() << "Cache directory is not accessible"; if(!_nam) _nam = new QNetworkAccessManager(this); auto reply = _nam->get(QNetworkRequest(QStringLiteral("https://cdn.proxer.me/cover/%1.jpg").arg(id))); connect(reply, &QNetworkReply::finished, this, [=](){ imageNetworkReply(id, reply); }, Qt::QueuedConnection); } void ImageLoader::clearCacheImpl() { _cache.clear(); QDir cacheDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)); if(cacheDir.exists(CacheDirName)) { QString rmName = QStringLiteral(".rm-dir-") + QUuid::createUuid().toString(); if(cacheDir.rename(CacheDirName, rmName)) { if(cacheDir.cd(rmName)) { QtConcurrent::run([cacheDir](){ auto cDir = cacheDir; cDir.removeRecursively(); }); } } else if(cacheDir.cd(CacheDirName)) cacheDir.removeRecursively(); } } void ImageLoader::imageNetworkReply(int id, QNetworkReply *reply) { if(reply->error() == QNetworkReply::NoError) { QImageReader reader(reply, "jpg"); QImage image; if(reader.read(&image)) { // send result _cache.insert(id, new QImage(image)); emit imageLoaded(id, image); //save to cache QDir cacheDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)); if(cacheDir.mkpath(CacheDirName) && cacheDir.cd(CacheDirName)) { auto imgPath = cacheDir.absoluteFilePath(ImageNameTemplate.arg(id)); if(!image.save(imgPath, "png")) qWarning() << "Failed to store image with id" << id << "to cache"; } else qWarning() << "Cache directory is not accessible"; } else emit imageLoadFailed(id, QStringLiteral("Failed to read image with id %1 with error: %2").arg(id).arg(reader.errorString())); } else emit imageLoadFailed(id, QStringLiteral("Network Error for id %1: %2").arg(id).arg(reply->errorString())); reply->deleteLater(); }
29.104762
128
0.708115
Skycoder42
21d11bbb1ae9b200f36d80d6009a02652e6c6246
4,636
cc
C++
src/communication/msg.cc
ooibc88/incubator-singa
50deedd496182daa0c178dd2581af43d173b6506
[ "Apache-2.0" ]
3
2016-10-29T09:40:46.000Z
2021-11-17T11:03:31.000Z
src/communication/msg.cc
ooibc88/incubator-singa
50deedd496182daa0c178dd2581af43d173b6506
[ "Apache-2.0" ]
null
null
null
src/communication/msg.cc
ooibc88/incubator-singa
50deedd496182daa0c178dd2581af43d173b6506
[ "Apache-2.0" ]
null
null
null
#include "communication/msg.h" #include <glog/logging.h> namespace singa { #ifdef USE_ZMQ Msg::~Msg() { if (msg_ != nullptr) zmsg_destroy(&msg_); frame_ = nullptr; } Msg::Msg() { msg_ = zmsg_new(); } Msg::Msg(const Msg& msg) { src_ = msg.src_; dst_ = msg.dst_; type_ = msg.type_; trgt_val_ = msg.trgt_val_; trgt_version_ = msg.trgt_version_; msg_ = zmsg_dup(msg.msg_); } Msg::Msg(int src, int dst) { src_ = src; dst_ = dst; msg_ = zmsg_new(); } void Msg::SwapAddr() { std::swap(src_, dst_); } int Msg::size() const { return zmsg_content_size(msg_); } void Msg::AddFrame(const void* addr, int nBytes) { zmsg_addmem(msg_, addr, nBytes); } int Msg::FrameSize() { return zframe_size(frame_); } void* Msg::FrameData() { return zframe_data(frame_); } char* Msg::FrameStr() { return zframe_strdup(frame_); } bool Msg::NextFrame() { frame_ = zmsg_next(msg_); return frame_ != nullptr; } void Msg::FirstFrame() { frame_ = zmsg_first(msg_); } void Msg::LastFrame() { frame_ = zmsg_last(msg_); } void Msg::ParseFromZmsg(zmsg_t* msg) { char* tmp = zmsg_popstr(msg); sscanf(tmp, "%d %d %d %d %d", &src_, &dst_, &type_, &trgt_val_, &trgt_version_); frame_ = zmsg_first(msg); msg_ = msg; } zmsg_t* Msg::DumpToZmsg() { zmsg_pushstrf(msg_, "%d %d %d %d %d", src_, dst_, type_, trgt_val_, trgt_version_); zmsg_t *tmp = msg_; msg_ = nullptr; return tmp; } // frame marker indicating this frame is serialize like printf #define FMARKER "*singa*" #define kMaxFrameLen 2048 int Msg::AddFormatFrame(const char *format, ...) { va_list argptr; va_start(argptr, format); int size = strlen(FMARKER); char dst[kMaxFrameLen]; memcpy(dst, FMARKER, size); dst[size++] = 0; while (*format) { if (*format == 'i') { int x = va_arg(argptr, int); dst[size++] = 'i'; memcpy(dst + size, &x, sizeof(x)); size += sizeof(x); } else if (*format == 'f') { float x = static_cast<float> (va_arg(argptr, double)); dst[size++] = 'f'; memcpy(dst + size, &x, sizeof(x)); size += sizeof(x); } else if (*format == '1') { uint8_t x = va_arg(argptr, int); memcpy(dst + size, &x, sizeof(x)); size += sizeof(x); } else if (*format == '2') { uint16_t x = va_arg(argptr, int); memcpy(dst + size, &x, sizeof(x)); size += sizeof(x); } else if (*format == '4') { uint32_t x = va_arg(argptr, uint32_t); memcpy(dst + size, &x, sizeof(x)); size += sizeof(x); } else if (*format == 's') { char* x = va_arg(argptr, char *); dst[size++] = 's'; memcpy(dst + size, x, strlen(x)); size += strlen(x); dst[size++] = 0; } else if (*format == 'p') { void* x = va_arg(argptr, void *); dst[size++] = 'p'; memcpy(dst + size, &x, sizeof(x)); size += sizeof(x); } else { LOG(ERROR) << "Unknown format " << *format; } format++; CHECK_LE(size, kMaxFrameLen); } va_end(argptr); zmsg_addmem(msg_, dst, size); return size; } int Msg::ParseFormatFrame(const char *format, ...) { va_list argptr; va_start(argptr, format); char* src = zframe_strdup(frame_); CHECK_STREQ(FMARKER, src); int size = strlen(FMARKER) + 1; while (*format) { if (*format == 'i') { int *x = va_arg(argptr, int *); CHECK_EQ(src[size++], 'i'); memcpy(x, src + size, sizeof(*x)); size += sizeof(*x); } else if (*format == 'f') { float *x = va_arg(argptr, float *); CHECK_EQ(src[size++], 'f'); memcpy(x, src + size, sizeof(*x)); size += sizeof(*x); } else if (*format == '1') { uint8_t *x = va_arg(argptr, uint8_t *); memcpy(x, src + size, sizeof(*x)); size += sizeof(*x); } else if (*format == '2') { uint16_t *x = va_arg(argptr, uint16_t *); memcpy(x, src + size, sizeof(*x)); size += sizeof(*x); } else if (*format == '4') { uint32_t *x = va_arg(argptr, uint32_t *); memcpy(x, src + size, sizeof(*x)); size += sizeof(*x); } else if (*format == 's') { char* x = va_arg(argptr, char *); CHECK_EQ(src[size++], 's'); int len = strlen(src + size); memcpy(x, src + size, len); x[len] = 0; size += len + 1; } else if (*format == 'p') { void** x = va_arg(argptr, void **); CHECK_EQ(src[size++], 'p'); memcpy(x, src + size, sizeof(*x)); size += sizeof(*x); } else { LOG(ERROR) << "Unknown format type " << *format; } format++; } va_end(argptr); delete src; return size; } #endif } // namespace singa
23.774359
62
0.556946
ooibc88
21d375bb3860ad5f87eaf3a8222e0cd6c6f1b91b
2,854
hh
C++
src/DataBase/CompositeFieldListPolicy.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/DataBase/CompositeFieldListPolicy.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/DataBase/CompositeFieldListPolicy.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // CompositeFieldListPolicy -- An implementation of UpdatePolicyBase which // consists of a collection of individual Field policies that should match // the Fields in a FieldList. // // Created by JMO, Sun Nov 3 14:11:32 PST 2013 //----------------------------------------------------------------------------// #ifndef __Spheral_CompositeFieldListPolicy_hh__ #define __Spheral_CompositeFieldListPolicy_hh__ #include "FieldListUpdatePolicyBase.hh" #include <vector> #include <memory> // unique_ptr/shared_ptr namespace Spheral { // Forward declarations. template<typename Dimension> class StateDerivatives; template<typename Dimension, typename ValueType> class CompositeFieldListPolicy: public FieldListUpdatePolicyBase<Dimension, ValueType> { public: //--------------------------- Public Interface ---------------------------// // Useful typedefs typedef typename std::shared_ptr<UpdatePolicyBase<Dimension> > PolicyPointer; typedef typename FieldListUpdatePolicyBase<Dimension, ValueType>::KeyType KeyType; // Constructors, destructor. CompositeFieldListPolicy(); virtual ~CompositeFieldListPolicy(); // Overload the methods describing how to update Fields. virtual void update(const KeyType& key, State<Dimension>& state, StateDerivatives<Dimension>& derivs, const double multiplier, const double t, const double dt); // An alternate method to be called when you want to specify that the derivative information // should be assumed to not necessarily be properly time-centered, and therefore you should // only use time advancement ideas, no "replace" or more sophisticated approaches. // Default to just calling the generic method. virtual void updateAsIncrement(const KeyType& key, State<Dimension>& state, StateDerivatives<Dimension>& derivs, const double multiplier, const double t, const double dt); // Equivalence. virtual bool operator==(const UpdatePolicyBase<Dimension>& rhs) const; // Add new UpdatePolicies to this thing. void push_back(UpdatePolicyBase<Dimension>* policyPtr); private: //--------------------------- Private Interface ---------------------------// std::vector<std::unique_ptr<UpdatePolicyBase<Dimension>>> mPolicyPtrs; CompositeFieldListPolicy(const CompositeFieldListPolicy& rhs); CompositeFieldListPolicy& operator=(const CompositeFieldListPolicy& rhs); }; } #else // Forward declaration. namespace Spheral { template<typename Dimension, typename ValueType> class CompositeFieldListPolicy; } #endif
37.552632
94
0.640505
jmikeowen
21d83db77fc892ded98fa45d60f659e3ca1f2cbb
959
hpp
C++
player/playerlib/Render.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
player/playerlib/Render.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
player/playerlib/Render.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
/* * This file is part of FFL project. * * The MIT License (MIT) * Copyright (C) 2017-2018 zhufeifei All rights reserved. * * Render.hpp * Created by zhufeifei(34008081@qq.com) on 2018/03/10 * * 渲染基类 * */ #pragma once #include "NodeBase.hpp" namespace player { class Render : public NodeBase{ public: Render(); ~Render(); virtual void pause(); virtual void resume(); // // 获取这个节点处理的延迟 // int64_t getDelayUs() { return 0; } // // 获取,设置渲染速度 // void setSpeed(uint32_t speed); uint32_t getSpeed(); // // 获取渲染时钟,可以改变时钟速度 // virtual FFL::sp<FFL::Clock> getRenderClock()=0; protected: // // 更新当前绘制tm时间戳的帧 // void updateRenderTimestamp(int64_t tm,int32_t streamId); protected: // // 外部setDataInput时候调用此函数,创建对应conn // virtual FFL::sp<FFL::PipelineConnector > onCreateConnector(const OutputInterface& output, const InputInterface& input,void* userdata)=0; private: uint32_t mSpeed; }; }
17.759259
91
0.661105
zhenfei2016
21d8d4ff95b58be3a09e674ebc76fdc2a317ec8c
498
cpp
C++
Engine/UI/Private/UIWindow.cpp
heretique/Atlas
0981e7941b570ecfda1febf71b4669338ab81921
[ "MIT" ]
6
2016-11-09T08:40:10.000Z
2021-10-06T09:47:05.000Z
Engine/UI/Private/UIWindow.cpp
heretique/Atlas
0981e7941b570ecfda1febf71b4669338ab81921
[ "MIT" ]
null
null
null
Engine/UI/Private/UIWindow.cpp
heretique/Atlas
0981e7941b570ecfda1febf71b4669338ab81921
[ "MIT" ]
3
2016-11-09T08:38:59.000Z
2021-12-24T16:03:59.000Z
#include "UI/UIWindow.h" namespace atlas { UIWindow::UIWindow(const std::string& name, ImGuiWindowFlags flags) : _name(name) , _flags(flags) , _hash(hq::StringHash(_name)) { } UIWindow::~UIWindow() { } hq::StringHash UIWindow::windowId() const { return _hash; } bool UIWindow::update(float deltaTime) { namespace ui = ImGui; if(ui::Begin(_name.c_str(), &_isOpen, _flags)) { onGUI(deltaTime); } ui::End(); return _isOpen; } } // atlas namespace
16.064516
67
0.63253
heretique
21d9a9071e647d2bc72ab433d13467a0fdf45614
114
hpp
C++
book/cpp_templates/tmplbook/variant/variantstorageastuple.hpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
book/cpp_templates/tmplbook/variant/variantstorageastuple.hpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
book/cpp_templates/tmplbook/variant/variantstorageastuple.hpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
template<typename... Types> class Variant { public: Tuple<Types...> storage; unsigned char discriminator; };
16.285714
30
0.710526
houruixiang
21ddf3f0edc24981eb74dc9bee215d459bdd3370
1,116
cc
C++
lib/tests/fixtures/dmi_fixtures.cc
GabrielNagy/libwhereami
8061b056b38ad2508b735465eae4bd9817091183
[ "Apache-2.0" ]
16
2017-07-12T05:58:59.000Z
2022-03-11T01:07:10.000Z
lib/tests/fixtures/dmi_fixtures.cc
GabrielNagy/libwhereami
8061b056b38ad2508b735465eae4bd9817091183
[ "Apache-2.0" ]
41
2017-07-07T16:44:57.000Z
2019-08-27T13:05:38.000Z
lib/tests/fixtures/dmi_fixtures.cc
GabrielNagy/libwhereami
8061b056b38ad2508b735465eae4bd9817091183
[ "Apache-2.0" ]
16
2017-07-05T15:23:40.000Z
2022-03-17T21:11:20.000Z
#include "./dmi_fixtures.hpp" using namespace whereami::testing; using namespace whereami::sources; using namespace std; namespace whereami { namespace testing { namespace dmi { std::string dmi_fixture::sys_path(std::string const& filename) const { return fixture_root + sys_fixture_path_ + filename; } smbios_data const* dmi_fixture::data() { if (!data_) { string dmidecode_output; load_fixture(dmidecode_fixture_path_, dmidecode_output); collect_data_from_dmidecode(dmidecode_output); if (data_ == nullptr) { if (!collect_data_from_sys()) { data_.reset(new smbios_data); } } } return data_.get(); } dmi_fixture_values::dmi_fixture_values(sources::smbios_data&& data) { data_.reset(new smbios_data(move(data))); } smbios_data const* dmi_fixture_empty::data() { if (!data_) { data_.reset(new smbios_data); } return data_.get(); } }}} // namespace whereami::testing::dmi
24.8
72
0.598566
GabrielNagy
21e385da38fc73f84978c88e4b3468ffc0decf88
1,315
hpp
C++
moci/moci_events/events/input.hpp
tobanteAudio/moci
a0a764e8a5270f9344ff57366fea36f72e7e3aa4
[ "BSD-2-Clause" ]
null
null
null
moci/moci_events/events/input.hpp
tobanteAudio/moci
a0a764e8a5270f9344ff57366fea36f72e7e3aa4
[ "BSD-2-Clause" ]
16
2020-03-19T22:08:47.000Z
2020-06-18T18:55:00.000Z
moci/moci_events/events/input.hpp
tobanteAudio/moci
a0a764e8a5270f9344ff57366fea36f72e7e3aa4
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "key_codes.hpp" #include "mouse_button_codes.hpp" #include "moci_core/moci_core.hpp" #include <tuple> namespace moci { class Input { public: Input() = default; Input(const Input&) = delete; auto operator=(const Input&) -> Input& = delete; virtual ~Input() = default; inline static auto IsKeyPressed(Key keycode) -> bool { return s_Instance->IsKeyPressedImpl(keycode); } inline static auto IsMouseButtonPressed(MouseCode button) -> bool { return s_Instance->IsMouseButtonPressedImpl(button); } inline static auto GetMousePosition() -> std::pair<float, float> { return s_Instance->GetMousePositionImpl(); } inline static auto GetMouseX() -> float { return s_Instance->GetMouseXImpl(); } inline static auto GetMouseY() -> float { return s_Instance->GetMouseYImpl(); } private: virtual auto IsKeyPressedImpl(Key keycode) -> bool = 0; virtual auto IsMouseButtonPressedImpl(MouseCode button) -> bool = 0; virtual auto GetMousePositionImpl() -> std::pair<float, float> = 0; virtual auto GetMouseXImpl() -> float = 0; virtual auto GetMouseYImpl() -> float = 0; static Scope<Input> s_Instance; }; } // namespace moci
32.875
115
0.644867
tobanteAudio
21e6b97aa501c5410b492e0dffac55243f72a19f
2,761
cpp
C++
MC/MC/mcTransportRectangleTrap.cpp
x2v0/MC
2c5667cf3f12de573f969e371bbe0af30fa52023
[ "MIT" ]
null
null
null
MC/MC/mcTransportRectangleTrap.cpp
x2v0/MC
2c5667cf3f12de573f969e371bbe0af30fa52023
[ "MIT" ]
null
null
null
MC/MC/mcTransportRectangleTrap.cpp
x2v0/MC
2c5667cf3f12de573f969e371bbe0af30fa52023
[ "MIT" ]
null
null
null
#include "mcTransportRectangleTrap.h" mcTransportRectangleTrap::mcTransportRectangleTrap(const geomVector3D& orgn, const geomVector3D& z, const geomVector3D& x) : mcTransport(orgn, z, x), fsx1_(0), fsx2_(0), fsy1_(0), fsy2_(0) {} mcTransportRectangleTrap::~mcTransportRectangleTrap(void) {} void mcTransportRectangleTrap::beginTransport(mcParticle& p) { if (p.u.z() <= 0) return; // Доталкиваем частицу до плоскости geomVector3D pp = p.p * mwtot_; geomVector3D uu = (p.p + p.u) * mwtot_; uu = uu - pp; double f = -pp.z() / uu.z(); double x = pp.x() + uu.x() * f; if (x < fsx1_ || x > fsx2_) return; double y = pp.y() + uu.y() * f; if (y < fsy1_ || y > fsy2_) return; if (nextTransport_ != nullptr) nextTransport_->beginTransport(p); } void mcTransportRectangleTrap::SetFieldSize(double x1, double x2, double y1, double y2) { fsx1_ = x1; fsx2_ = x2; fsy1_ = y1; fsy2_ = y2; } void mcTransportRectangleTrap::dumpVRML(ostream& os) const { int i = 0; double r = 15; // размера бокса geomVector3D p[8]; p[i++] = geomVector3D(-r, -r, 0) * mttow_; p[i++] = geomVector3D(-r, r, 0) * mttow_; p[i++] = geomVector3D(r, r, 0) * mttow_; p[i++] = geomVector3D(r, -r, 0) * mttow_; p[i++] = geomVector3D(fsx1_, fsy1_, 0) * mttow_; p[i++] = geomVector3D(fsx1_, fsy2_, 0) * mttow_; p[i++] = geomVector3D(fsx2_, fsy2_, 0) * mttow_; p[i++] = geomVector3D(fsx2_, fsy1_, 0) * mttow_; os << " Transform {" << endl; os << " children Shape {" << endl; os << " appearance Appearance {" << endl; os << " material Material {" << endl; os << " diffuseColor " << red_ << ' ' << green_ << ' ' << blue_ << endl; os << " transparency " << transparancy_ << endl; os << " }" << endl; os << " }" << endl; os << " geometry IndexedFaceSet {" << endl; os << " coord Coordinate {" << endl; os << " point [" << endl; for (i = 0; i < 8; i++) { os << " " << p[i].x() << ' ' << p[i].y() << ' ' << p[i].z(); if (i < 7) os << ", "; os << endl; } os << " ]" << endl; os << " }" << endl; os << " coordIndex [" << endl; os << " 0, 1, 5, 4, -1," << endl; os << " 1, 2, 6, 5, -1," << endl; os << " 2, 3, 7, 6, -1," << endl; os << " 3, 0, 4, 7, -1" << endl; os << " ]" << endl; os << " }" << endl; os << " }" << endl; os << " }" << endl; }
33.670732
120
0.456356
x2v0
21e7edda92e84aa7f169f1a1994d93f12a9c457a
7,677
cpp
C++
TacticsVictory/common_files/Objects/GameObject_.cpp
Sasha7b9/TacticsVictory
2082ca032f2a8d377ed8a89537ac4799fb348372
[ "MIT" ]
6
2015-10-23T19:15:04.000Z
2021-06-17T15:02:58.000Z
TacticsVictory/common_files/Objects/GameObject_.cpp
Sasha7b9/TacticsVictory
2082ca032f2a8d377ed8a89537ac4799fb348372
[ "MIT" ]
null
null
null
TacticsVictory/common_files/Objects/GameObject_.cpp
Sasha7b9/TacticsVictory
2082ca032f2a8d377ed8a89537ac4799fb348372
[ "MIT" ]
null
null
null
// (c) Aleksandr Shevchenko e-mail : Sasha7b9@tut.by #include "stdafx.h" #include "Objects/GameObject_.h" #include "Objects/Units/Logic/PathFinder/PathMapping_.h" #include "Objects/Units/Unit_.h" #include "Objects/Ammo/Ammo_.h" #include "PeriodicTasks.h" #include "GameState.h" #include "Objects/PoolObjects_.h" #include "Objects/Units/Water/WaterUnit_.h" #include "Objects/Units/Air/AirUnit_.h" #include "Objects/Staff/Commander_.h" #include "GameWorld.h" #include "Objects/World/Landscape_.h" #ifdef PiCLIENT #include "Objects/InfoWindow.h" #include "Objects/Units/Logic/PathFinder/PathFinder_.h" #include "Objects/World/CameraRTS.h" #endif using namespace Pi; GameObject *GameObject::empty = nullptr; int GameObject::createdObjects = 0; Map<GameObject> GameObject::objects; static const GameObjectParameters parametersEmpty { {}, {}, true, 0, 0 }; void GameObject::Construct() { PoolObjects::Consruct(); #ifdef PiCLIENT empty = new GameObject(TypeGameObject::Empty, &parametersEmpty, 0); AmmoObject::Construct(); UnitObject::Construct(); #endif } void GameObject::Destruct() { #ifdef PiCLIENT AmmoObject::Destruct(); UnitObject::Destruct(); Property *property = empty->GetProperty(PiTypeProperty::GameObject); delete property; delete empty; #endif PoolObjects::Destruct(); } GameObject::GameObject(TypeGameObject type, const GameObjectParameters *_param, int _id) : Node(), id(_id == -1 ? ++createdObjects : _id), params(*PoolObjects::AllocateParameters(id)), typeGameObject(type) { params = *_param; params.exist = true; params.id = id; params.number_thread = id %TaskMain::NumberThreads(); AddProperty(new GameObjectProperty(*this)); nodeGeometry = new Node(); nodeGeometry->SetNodeName("Geometry"); AppendNewSubnode(nodeGeometry); objects.Insert(this); } GameObject::~GameObject() { delete commander; delete driver; } void GameObject::AppendTask(CommanderTask *task) { commander->AppendTask(task); } bool GameObject::AppendInGame(int _x, int _y) { if (!GameState::landscapeCreated) { return false; } float x = (float)_x; float y = (float)_y; bool append = false; if (IsUnit()) { UnitObject *unit = GetUnitObject(); if (unit->typeUnit == TypeUnit::Air) //-V522 { float height = 5.0f; if (Landscape::self->AboveSurface(_x, _y) && !Landscape::self->UnderWater(_x, _y)) { height += Landscape::self->GetHeightAccurately(x, y); } unit->params.cur.position = Point3D(x, y, height); append = true; } else if (unit->typeUnit == TypeUnit::Ground) { if (!Landscape::self->UnderWater(_x, _y)) { float height = Landscape::self->GetHeightAccurately(x, y); unit->params.cur.position = Point3D(x, y, height); append = true; } } else if (unit->typeUnit == TypeUnit::Water) { if (Landscape::self->UnderWater(_x, _y)) { unit->params.cur.position = Point3D(x, y, Water::Level()); append = true; } } } if (append) { GameWorld::self->GetRootNode()->AppendNewSubnode(this); return true; } return false; } void GameObject::SetNodePosition(const Point3D &position) { Node::SetNodePosition(position); } void GameObject::Move(float dT) { #ifdef PiCLIENT if (property->Selected()) { Point3D coord = GameWorld::self->TransformWorldCoordToDisplay(GetWorldPosition()); coord.x -= property->infoWindow->GetWidgetSize().x / 2; coord.y -= property->infoWindow->GetWidgetSize().y / 2; coord.x = (float)((int)coord.x); coord.y = (float)((int)coord.y); property->infoWindow->SetWidgetPosition(coord); property->infoWindow->Invalidate(); } #endif } void GameObject::Preprocess() { property = (GameObjectProperty *)GetProperty(PiTypeProperty::GameObject); } bool GameObject::CanExecute(CommanderTask::Type task) const { switch (task) { case CommanderTask::Type::Move: case CommanderTask::Type::Rotate: case CommanderTask::Type::Test: return true; break; case CommanderTask::Type::Dive: { UnitObject *unit = GetUnitObject(); if (unit) { WaterUnitObject *water = unit->GetWaterUnit(); if (water) { if (water->typeWaterUnit == TypeWaterUnit::Submarine) { return true; } } } } break; case CommanderTask::Type::FreeFlight: { UnitObject *unit = GetUnitObject(); if (unit) { AirUnitObject *air = unit->GetAirUnit(); if (air->typeAirUnit == TypeAirUnit::Airplane) { return true; } } } break; case CommanderTask::Type::Count: break; } return false; } GameObject &GameObject::GetFromScreen(const Point2D &coord) { GameObjectProperty *property = GameObjectProperty::GetFromScreen(coord); return property ? property->gameObject : *empty; } void GameObject::SetDirection(const Vector3D &direction, const Vector3D &up) { Vector3D right = Cross(direction, up).Normalize(); GetNodeGeometry()->SetNodeMatrix3D({right, direction, up}); } Node *GameObject::CreateNodeForGeometry(pchar name, Node *_nodeGeometry) { Node *node = new Node(); node->SetNodeName(name); node->AppendNewSubnode(_nodeGeometry); return node; } void GameObjectProperty::MouseEvent(uint state) { if(Selectable()) { if (state & (1 << 0)) { Selected() ? RemoveSelection() : SetSelection(); } } } GameObjectProperty::GameObjectProperty(GameObject &_gameObject) : Property(PiTypeProperty::GameObject), gameObject(_gameObject) #ifdef PiCLIENT , infoWindow(new InfoWindow()) #endif { } GameObjectProperty::~GameObjectProperty() { #ifdef PiCLIENT delete infoWindow; #endif } void GameObjectProperty::SetSelection() { selected = true; #ifdef PiCLIENT TheInterfaceMgr->AddWidget(infoWindow); PathFinder *finder = new PathFinder(gameObject.GetWorldPosition().GetPoint2D(), {50.0f, 50.0f}); gameObject.AppendNewSubnode(finder); finder->Find([this](const Array<Integer2D> &_path) { GameWorld::self->GetRootNode()->AppendNewSubnode(new PathMapping(gameObject, _path)); }); #endif } void GameObjectProperty::RemoveSelection() { selected = false; #ifdef PiCLIENT TheInterfaceMgr->RemoveWidget(infoWindow); delete PathMapping::FromScene(gameObject); #endif } GameObjectProperty *GameObjectProperty::GetFromScreen(const Point2D &coord) { #ifdef PiCLIENT Ray ray = CameraRTS::self->GetWorldRayFromPoint(coord); CollisionData data; Point3D p1 = ray.origin; Point3D p2 = p1 + ray.direction * ray.tmax; if (GameWorld::self->DetectCollision(p1, p2, 0.0f, PiKindCollision::RigidBody, &data)) { Node *node = data.geometry->GetSuperNode(); while (node) { GameObjectProperty *property = (GameObjectProperty *)node->GetProperty(PiTypeProperty::GameObject); if (property) { return property; } node = node->GetSuperNode(); } } #endif return nullptr; }
20.861413
111
0.618731
Sasha7b9
21e8d0699df488e7ff186709b7864b885a3957d1
3,400
cpp
C++
src/applications/replicoscillator/edgedBasedDetection.cpp
TASBE/ImageAnalytics
5d6fc1a64b4c17e263451fa4252c94dc86193d14
[ "CC-BY-3.0" ]
1
2019-08-29T20:48:32.000Z
2019-08-29T20:48:32.000Z
src/applications/replicoscillator/edgedBasedDetection.cpp
TASBE/ImageAnalytics
5d6fc1a64b4c17e263451fa4252c94dc86193d14
[ "CC-BY-3.0" ]
1
2021-11-02T18:14:21.000Z
2021-11-02T18:19:50.000Z
src/applications/replicoscillator/edgedBasedDetection.cpp
TASBE/ImageAnalytics
5d6fc1a64b4c17e263451fa4252c94dc86193d14
[ "CC-BY-3.0" ]
null
null
null
/* Copyright (C) 2011 - 2019, Raytheon BBN Technologies and contributors listed in the AUTHORS file in TASBE Flow Analytics distribution's top directory. This file is part of the TASBE Flow Analytics package, and is distributed under the terms of the GNU General Public License, with a linking exception, as described in the file LICENSE in the TASBE Image Analysis package distribution's top directory. */ #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/ximgproc/edge_filter.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace cv; using namespace std; Mat src; Mat blurred; int thresh = 100; int max_thresh = 255; int origBlurr; RNG rng(12345); /// Function header void thresh_callback(int, void*); void src_callback(int, void*); /** @function main */ int main(int argc, char** argv) { /// Load source image and convert it to gray src = imread(argv[1], IMREAD_ANYDEPTH); cout << "Bit depth: " << src.depth() * 8 << endl; if (src.depth() > 1) { /* double minVal, maxVal; minMaxLoc(src, &minVal, &maxVal); cout << "Min Val: " << minVal << ", Max Val: " << maxVal << endl; Mat full, partial; double gain = 255/(maxVal - minVal); src.convertTo(full, CV_8UC1, 255/(pow(2,16) - 1), 0); src.convertTo(partial, CV_8UC1, gain, - minVal * gain); minMaxLoc(full, &minVal, &maxVal); cout << "full Min Val: " << minVal << ", full Max Val: " << maxVal << endl; minMaxLoc(partial, &minVal, &maxVal); cout << "partial Min Val: " << minVal << ", partial Max Val: " << maxVal << endl; namedWindow("Full", CV_WINDOW_AUTOSIZE); imshow("Full", full); namedWindow("Partial", CV_WINDOW_AUTOSIZE); imshow("Partial", partial); waitKey(0); */ double minVal, maxVal; minMaxLoc(src, &minVal, &maxVal); Mat eightBit; double gain = 255/(maxVal - minVal); src.convertTo(eightBit, CV_8UC1, gain, - minVal * gain); src = eightBit; } /// Convert image to gray and blur it if (src.channels() > 1) { Mat src_gray; cvtColor(src, src_gray, CV_BGR2GRAY); src = src_gray; } ximgproc::bilateralTextureFilter(src, blurred); /// Create Window namedWindow("Source", CV_WINDOW_AUTOSIZE); imshow("Source", src); createTrackbar(" Canny thresh:", "Source", &thresh, max_thresh, thresh_callback); createTrackbar(" Orig/Blurred", "Source", &origBlurr, 1, src_callback); thresh_callback(0, 0); waitKey(0); return (0); } /** @function thresh_callback */ void thresh_callback(int, void*) { Mat canny_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; /// Detect edges using canny Canny(blurred, canny_output, thresh, thresh * 2, 3); /// Find contours findContours(canny_output, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); /// Draw contours Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3); for (int i = 0; i < contours.size(); i++) { Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point()); } /// Show in a window namedWindow("Contours", CV_WINDOW_AUTOSIZE); imshow("Contours", drawing); namedWindow("Edges", CV_WINDOW_AUTOSIZE); imshow("Edges", canny_output); } void src_callback(int, void*) { if (origBlurr) { imshow("Source", blurred); } else { imshow("Source", src); } }
26.153846
83
0.682647
TASBE
21ebee62626eed8088a3aae20d6639edfaf0be33
4,615
cpp
C++
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/windows/qwindowsinternalmimedata.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/windows/qwindowsinternalmimedata.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/plugins/platforms/windows/qwindowsinternalmimedata.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwindowsinternalmimedata.h" #include "qwindowscontext.h" #include "qwindowsmime.h" #include <QDebug> /*! \class QWindowsInternalMimeDataBase \brief Base for implementations of QInternalMimeData using a IDataObject COM object. In clipboard handling and Drag and drop, static instances of QInternalMimeData implementations are kept and passed to the client. QInternalMimeData provides virtuals that query the formats and retrieve mime data on demand when the client invokes functions like QMimeData::hasHtml(), QMimeData::html() on the instance returned. Otherwise, expensive construction of a new QMimeData object containing all possible formats would have to be done in each call to mimeData(). The base class introduces new virtuals to obtain and release the instances IDataObject from the clipboard or Drag and Drop and does conversion using QWindowsMime classes. \sa QInternalMimeData, QWindowsMime, QWindowsMimeConverter \internal \ingroup qt-lighthouse-win */ bool QWindowsInternalMimeData::hasFormat_sys(const QString &mime) const { IDataObject *pDataObj = retrieveDataObject(); if (!pDataObj) return false; const QWindowsMimeConverter &mc = QWindowsContext::instance()->mimeConverter(); const bool has = mc.converterToMime(mime, pDataObj) != 0; releaseDataObject(pDataObj); qCDebug(lcQpaMime) << __FUNCTION__ << mime << has; return has; } QStringList QWindowsInternalMimeData::formats_sys() const { IDataObject *pDataObj = retrieveDataObject(); if (!pDataObj) return QStringList(); const QWindowsMimeConverter &mc = QWindowsContext::instance()->mimeConverter(); const QStringList fmts = mc.allMimesForFormats(pDataObj); releaseDataObject(pDataObj); qCDebug(lcQpaMime) << __FUNCTION__ << fmts; return fmts; } QVariant QWindowsInternalMimeData::retrieveData_sys(const QString &mimeType, QVariant::Type type) const { IDataObject *pDataObj = retrieveDataObject(); if (!pDataObj) return QVariant(); QVariant result; const QWindowsMimeConverter &mc = QWindowsContext::instance()->mimeConverter(); if (const QWindowsMime *converter = mc.converterToMime(mimeType, pDataObj)) result = converter->convertToMime(mimeType, pDataObj, type); releaseDataObject(pDataObj); if (QWindowsContext::verbose) { qCDebug(lcQpaMime) <<__FUNCTION__ << ' ' << mimeType << ' ' << type << " returns " << result.type() << (result.type() != QVariant::ByteArray ? result.toString() : QStringLiteral("<data>")); } return result; }
41.576577
101
0.703359
GrinCash
21f3546e93d4ee1ff48d870c8585fa82c989dba9
1,750
hpp
C++
src/DSGRN/_dsgrn/include/Dynamics/Annotation.hpp
yingxinac/DSGRN
b5bc64e5a99e6d266f6ac5ba7ac9d04954f12d32
[ "MIT" ]
9
2017-10-15T20:49:36.000Z
2022-02-24T19:26:39.000Z
src/DSGRN/_dsgrn/include/Dynamics/Annotation.hpp
yingxinac/DSGRN
b5bc64e5a99e6d266f6ac5ba7ac9d04954f12d32
[ "MIT" ]
19
2015-07-02T15:59:06.000Z
2020-06-09T18:13:05.000Z
src/DSGRN/_dsgrn/include/Dynamics/Annotation.hpp
yingxinac/DSGRN
b5bc64e5a99e6d266f6ac5ba7ac9d04954f12d32
[ "MIT" ]
21
2015-11-06T16:28:34.000Z
2019-09-20T09:26:54.000Z
/// Annotation.hpp /// Shaun Harker /// 2015-05-15 #pragma once #ifndef INLINE_IF_HEADER_ONLY #define INLINE_IF_HEADER_ONLY #endif #include "Annotation.h" INLINE_IF_HEADER_ONLY Annotation:: Annotation ( void ) { data_ . reset ( new Annotation_ ); } INLINE_IF_HEADER_ONLY uint64_t Annotation:: size ( void ) const { return data_ ->annotations_ . size (); } INLINE_IF_HEADER_ONLY Annotation::iterator Annotation:: begin ( void ) const { return data_ ->annotations_ . begin (); } INLINE_IF_HEADER_ONLY Annotation::iterator Annotation:: end ( void ) const { return data_ ->annotations_ . end (); } INLINE_IF_HEADER_ONLY std::string const& Annotation:: operator [] ( uint64_t i ) const { return data_ ->annotations_[i]; } INLINE_IF_HEADER_ONLY void Annotation:: append ( std::string const& label ) { data_ -> annotations_ . push_back ( label ); } INLINE_IF_HEADER_ONLY std::string Annotation:: stringify ( void ) const { std::stringstream ss; ss << "["; bool first = true; for ( std::string const& s : data_ ->annotations_ ) { if ( first ) first = false; else ss << ","; ss << "\"" << s << "\""; } ss << "]"; return ss . str (); } INLINE_IF_HEADER_ONLY Annotation & Annotation:: parse ( std::string const& str ) { json array = json::parse(str); data_ -> annotations_ . clear (); for ( std::string const& s : array ) { data_ -> annotations_ . push_back ( s ); } return *this; } INLINE_IF_HEADER_ONLY std::ostream& operator << ( std::ostream& stream, Annotation const& a ) { stream << "{"; bool first = true; for ( auto x : a . data_ ->annotations_ ) { if ( first ) first = false; else stream << ", "; stream << "\"" << x << "\""; } stream << "}"; return stream; }
23.026316
95
0.642857
yingxinac
21f64e60d69cac1e09217f89d5dacb1865cf26c9
15,688
cpp
C++
mp/src/game/server/da/da_datamanager.cpp
Black-Stormy/DoubleAction
cef6ff5ec41f2fed938d8ee3d6ffd3c770f523c7
[ "Unlicense" ]
null
null
null
mp/src/game/server/da/da_datamanager.cpp
Black-Stormy/DoubleAction
cef6ff5ec41f2fed938d8ee3d6ffd3c770f523c7
[ "Unlicense" ]
null
null
null
mp/src/game/server/da/da_datamanager.cpp
Black-Stormy/DoubleAction
cef6ff5ec41f2fed938d8ee3d6ffd3c770f523c7
[ "Unlicense" ]
null
null
null
#include "cbase.h" using namespace std; #ifdef WITH_DATA_COLLECTION #undef min #undef max #include <time.h> #include "da_datamanager.h" #include "da_player.h" #include "weapon_grenade.h" #include "da_gamerules.h" #include "da_briefcase.h" #include "../datanetworking/math.pb.h" #include "../datanetworking/data.pb.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #ifdef WITH_DATA_COLLECTION void FillProtoBufVector(da::protobuf::Vector* pVector, const Vector& vecFill) { pVector->set_x(vecFill.x); pVector->set_y(vecFill.y); pVector->set_z(vecFill.z); } CDataManager g_DataManager( "CDataManager" ); CDataManager& DataManager() { return g_DataManager; } extern bool DASendData(const da::protobuf::GameData& pbGameData, std::string& sError); static void SendData( CFunctor **pData, unsigned int nCount ) { da::protobuf::GameData pbGameData; g_DataManager.FillProtoBuffer(&pbGameData); std::string sError; if (!DASendData(pbGameData, sError)) Msg("Error sending game data: %s", sError.c_str()); } static bool Account_LessFunc( AccountID_t const &a, AccountID_t const &b ) { return a < b; } CDataManager::CDataManager( char const* name ) : CAutoGameSystemPerFrame(name) { m_aiConnectedClients.SetLessFunc(Account_LessFunc); m_pSendData = NULL; d = NULL; m_bLevelStarted = false; ClearData(); } CDataManager::~CDataManager() { delete d; } void CDataManager::LevelInitPostEntity( void ) { // If the thread is executing, then wait for it to finish if ( m_pSendData ) { m_pSendData->WaitForFinishAndRelease(); m_pSendData = NULL; } m_bLevelStarted = true; d->z.m_flStartTime = gpGlobals->curtime; d->z.m_flNextPositionsUpdate = gpGlobals->curtime; CUtlMap<AccountID_t, char>::IndexType_t it = m_aiConnectedClients.FirstInorder(); while (it != m_aiConnectedClients.InvalidIndex()) { // This player is gone for good. Remove him from the list and we'll // count him as unique next time he shows up. if (m_aiConnectedClients[it] == 0) { CUtlMap<AccountID_t, char>::IndexType_t iRemove = it; m_aiConnectedClients.RemoveAt(iRemove); it = m_aiConnectedClients.NextInorder(it); continue; } // This player will be a unique player for the next map. d->z.m_iUniquePlayers++; it = m_aiConnectedClients.NextInorder(it); } } void CDataManager::FrameUpdatePostEntityThink( void ) { if (gpGlobals->curtime > d->z.m_flNextPositionsUpdate) SavePositions(); } ConVar da_data_positions_interval("da_data_positions_interval", "10", FCVAR_DEVELOPMENTONLY, "How often to query player positions"); void CDataManager::SavePositions() { if (IsSendingData()) return; d->z.m_flNextPositionsUpdate = gpGlobals->curtime + da_data_positions_interval.GetFloat(); for (int i = 1; i <= gpGlobals->maxClients; i++) { CDAPlayer *pPlayer = ToDAPlayer(UTIL_PlayerByIndex( i )); if (!pPlayer) continue; if (pPlayer->IsBot()) continue; if (!pPlayer->IsAlive()) continue; d->m_avecPlayerPositions.AddToTail(pPlayer->GetAbsOrigin()); if (pPlayer->IsInThirdPerson()) d->z.m_iThirdPersonActive += da_data_positions_interval.GetFloat(); else d->z.m_iThirdPersonInactive += da_data_positions_interval.GetFloat(); if (pPlayer->m_bUsingVR) d->z.m_iVRActive += da_data_positions_interval.GetFloat(); else d->z.m_iVRInactive += da_data_positions_interval.GetFloat(); if (pPlayer->m_iPlatform == 1) d->z.m_iWindows += da_data_positions_interval.GetFloat(); else if (pPlayer->m_iPlatform == 2) d->z.m_iLinux += da_data_positions_interval.GetFloat(); else if (pPlayer->m_iPlatform == 3) d->z.m_iMac += da_data_positions_interval.GetFloat(); } ConVarRef sv_cheats("sv_cheats"); d->z.m_bCheated |= sv_cheats.GetBool(); } int GetFlags(CDAPlayer* pPlayer) { unsigned long long flags = 0; if (pPlayer->IsInThirdPerson()) flags |= 1<<da::protobuf::KILL_THIRDPERSON; if (pPlayer->m_Shared.IsAimedIn()) flags |= 1<<da::protobuf::KILL_AIMIN; if (pPlayer->m_Shared.IsDiving()) flags |= 1<<da::protobuf::KILL_DIVING; if (pPlayer->m_Shared.IsRolling()) flags |= 1<<da::protobuf::KILL_ROLLING; if (pPlayer->m_Shared.IsSliding()) flags |= 1<<da::protobuf::KILL_SLIDING; if (pPlayer->m_Shared.IsWallFlipping(true)) flags |= 1<<da::protobuf::KILL_FLIPPING; if (pPlayer->m_Shared.IsSuperFalling()) flags |= 1<<da::protobuf::KILL_SUPERFALLING; if (pPlayer->IsStyleSkillActive()) flags |= 1<<da::protobuf::KILL_SKILL_ACTIVE; if (pPlayer->m_Shared.m_bSuperSkill) flags |= 1<<da::protobuf::KILL_SUPER_SKILL_ACTIVE; if (DAGameRules()->GetBountyPlayer() == pPlayer) flags |= 1<<da::protobuf::KILL_IS_TARGET; if (pPlayer->HasBriefcase()) flags |= 1<<da::protobuf::KILL_HAS_BRIEFCASE; if (pPlayer->IsBot()) flags |= 1<<da::protobuf::KILL_IS_BOT; return flags; } void FillPlayerInfo(da::protobuf::PlayerInfo* pbPlayerInfo, CDAPlayer* pPlayer) { FillProtoBufVector(pbPlayerInfo->mutable_position(), pPlayer->GetAbsOrigin()); pbPlayerInfo->set_health(pPlayer->GetHealth()); pbPlayerInfo->set_flags(GetFlags(pPlayer)); pbPlayerInfo->set_skill(SkillIDToAlias((SkillID)pPlayer->m_Shared.m_iStyleSkill.Get())); pbPlayerInfo->set_style(pPlayer->GetStylePoints()); pbPlayerInfo->set_total_style(pPlayer->GetTotalStyle()); pbPlayerInfo->set_kills(pPlayer->m_iKills); pbPlayerInfo->set_deaths(pPlayer->m_iDeaths); if (pPlayer->GetActiveDAWeapon()) pbPlayerInfo->set_weapon(WeaponIDToAlias(pPlayer->GetActiveDAWeapon()->GetWeaponID())); if (!pPlayer->IsBot()) { CSteamID ID; pPlayer->GetSteamID(&ID); pbPlayerInfo->set_accountid(ID.GetAccountID()); } if (DAGameRules()->GetWaypoint(0)) { pbPlayerInfo->set_waypoint(pPlayer->m_iRaceWaypoint); FillProtoBufVector(pbPlayerInfo->mutable_objective_position(), DAGameRules()->GetWaypoint(pPlayer->m_iRaceWaypoint)->GetAbsOrigin()); } if (pPlayer->HasBriefcase()) FillProtoBufVector(pbPlayerInfo->mutable_objective_position(), DAGameRules()->GetCaptureZone()->GetAbsOrigin()); if (pPlayer->m_iSlowMoType == SLOWMO_STYLESKILL) pbPlayerInfo->set_slowmo_type("super"); else if (pPlayer->m_iSlowMoType == SLOWMO_ACTIVATED) pbPlayerInfo->set_slowmo_type("active"); else if (pPlayer->m_iSlowMoType == SLOWMO_SUPERFALL) pbPlayerInfo->set_slowmo_type("superfall"); else if (pPlayer->m_iSlowMoType == SLOWMO_PASSIVE) pbPlayerInfo->set_slowmo_type("passive"); else if (pPlayer->m_iSlowMoType == SLOWMO_PASSIVE_SUPER) pbPlayerInfo->set_slowmo_type("passivesuper"); else if (pPlayer->m_iSlowMoType == SLOWMO_NONE) pbPlayerInfo->set_slowmo_type("none"); else pbPlayerInfo->set_slowmo_type("unknown"); if (pPlayer->m_flSlowMoTime) pbPlayerInfo->set_slowmo_seconds(pPlayer->m_flSlowMoTime - gpGlobals->curtime); else pbPlayerInfo->set_slowmo_seconds(pPlayer->m_flSlowMoSeconds); } void CDataManager::AddKillInfo(const CTakeDamageInfo& info, CDAPlayer* pVictim) { d->m_apKillInfos.AddToTail(new da::protobuf::KillInfo()); da::protobuf::KillInfo* pbKillInfo = d->m_apKillInfos.Tail(); CBaseEntity* pAttacker = info.GetAttacker(); da::protobuf::PlayerInfo* pbVictimInfo = pbKillInfo->mutable_victim(); FillPlayerInfo(pbVictimInfo, pVictim); unsigned long long flags = pbVictimInfo->flags(); if (dynamic_cast<CBaseGrenadeProjectile*>(info.GetInflictor())) { flags |= 1<<da::protobuf::KILL_BY_GRENADE; FillProtoBufVector(pbKillInfo->mutable_grenade_position(), info.GetInflictor()->GetAbsOrigin()); } if (info.GetDamageType() == DMG_CLUB) flags |= 1<<da::protobuf::KILL_BY_BRAWL; if (pAttacker == pVictim) flags |= 1<<da::protobuf::KILL_IS_SUICIDE; pbVictimInfo->set_flags(flags); CDAPlayer* pPlayerAttacker = ToDAPlayer(pAttacker); if (pPlayerAttacker && pPlayerAttacker != pVictim) FillPlayerInfo(pbKillInfo->mutable_killer(), pPlayerAttacker); } void CDataManager::AddCharacterChosen(const char* pszCharacter) { CUtlMap<CUtlString, int>::IndexType_t it = d->m_asCharactersChosen.Find(CUtlString(pszCharacter)); if (it == d->m_asCharactersChosen.InvalidIndex()) d->m_asCharactersChosen.Insert(CUtlString(pszCharacter), 1); else d->m_asCharactersChosen[it]++; } void CDataManager::AddWeaponChosen(DAWeaponID eWeapon) { d->m_aeWeaponsChosen.AddToTail(eWeapon); } void CDataManager::AddSkillChosen(SkillID eSkill) { d->m_aeSkillsChosen.AddToTail(eSkill); } da::protobuf::PlayerList* CDataManager::GetPlayerInList(CDAPlayer* pPlayer) { if (pPlayer->IsBot()) return NULL; CSteamID ID; pPlayer->GetSteamID(&ID); if (!ID.IsValid()) return NULL; if (ID.GetEUniverse() != k_EUniversePublic) return NULL; if (ID.GetEAccountType() != k_EAccountTypeIndividual) return NULL; CUtlMap<AccountID_t, class da::protobuf::PlayerList*>::IndexType_t it = d->m_apPlayerList.Find(ID.GetAccountID()); if (it == d->m_apPlayerList.InvalidIndex()) { it = d->m_apPlayerList.Insert(ID.GetAccountID(), new da::protobuf::PlayerList()); da::protobuf::PlayerList* pbPlayerInfo = d->m_apPlayerList[it]; pbPlayerInfo->set_accountid(ID.GetAccountID()); pbPlayerInfo->set_name(pPlayer->GetPlayerName()); } return d->m_apPlayerList[it]; } void CDataManager::AddStyle(CDAPlayer* pPlayer, float flStyle) { da::protobuf::PlayerList* pbPlayerInfo = GetPlayerInList(pPlayer); if (!pbPlayerInfo) return; pbPlayerInfo->set_style(pbPlayerInfo->style() + flStyle); } void CDataManager::ClientConnected(AccountID_t eAccountID) { // ClientConnected is called for every non-bot client every time a map loads, even with changelevel. // So we have to eliminate duplicate connections. CUtlMap<AccountID_t, char>::IndexType_t it = m_aiConnectedClients.Find(eAccountID); if (it == m_aiConnectedClients.InvalidIndex() || m_aiConnectedClients[it] == 0) { // This client was not previously in the list, so he has truly connected. if (it == m_aiConnectedClients.InvalidIndex()) { // This client has not disconnected and reconnected. // We want to eliminate repeated connections as extra information. d->z.m_iConnections++; d->z.m_iUniquePlayers++; m_aiConnectedClients.Insert(eAccountID, 1); } else m_aiConnectedClients[it] = 1; } } void CDataManager::ClientDisconnected(AccountID_t eAccountID) { // This is called only once for each client, never just for changelevels. CUtlMap<AccountID_t, char>::IndexType_t it = m_aiConnectedClients.Find(eAccountID); if (it == m_aiConnectedClients.InvalidIndex()) m_aiConnectedClients.Insert(eAccountID, 0); else m_aiConnectedClients[it] = 0; d->z.m_iDisconnections++; } void CDataManager::SetTeamplay(bool bOn) { d->z.m_bTeamplay = bOn; } void CDataManager::VotePassed(const char* pszIssue, const char* pszDetails) { int i = d->m_aVoteResults.AddToTail(); d->m_aVoteResults[i].m_bResult = true; d->m_aVoteResults[i].m_sIssue = pszIssue; d->m_aVoteResults[i].m_sDetails = pszDetails; } void CDataManager::VoteFailed(const char* pszIssue) { int i = d->m_aVoteResults.AddToTail(); d->m_aVoteResults[i].m_bResult = false; d->m_aVoteResults[i].m_sIssue = pszIssue; } ConVar da_data_enabled("da_data_enabled", "1", 0, "Turn on and off data sending."); void CDataManager::LevelShutdownPostEntity() { if (!gpGlobals->maxClients) return; if (!da_data_enabled.GetBool()) return; // This function is sometimes called twice for every LevelInitPostEntity(), so remove duplicates. if (!m_bLevelStarted) return; // If the thread is executing, then wait for it to finish if ( m_pSendData ) m_pSendData->WaitForFinishAndRelease(); m_pSendData = ThreadExecute( &SendData, (CFunctor**)NULL, 0 ); m_bLevelStarted = false; } bool CDataManager::IsSendingData() { return !!m_pSendData; } void CDataManager::FillProtoBuffer(da::protobuf::GameData* pbGameData) { pbGameData->set_da_version(atoi(DA_VERSION)); pbGameData->set_map_name(STRING(gpGlobals->mapname)); pbGameData->set_map_time(gpGlobals->curtime - d->z.m_flStartTime); #ifdef _DEBUG pbGameData->set_debug(true); #else pbGameData->set_debug(false); #endif pbGameData->set_cheats(d->z.m_bCheated); const ConVar* pHostname = cvar->FindVar( "hostname" ); pbGameData->set_server_name(pHostname->GetString()); pbGameData->set_timestamp((unsigned)time(NULL)); pbGameData->set_connections(d->z.m_iConnections); pbGameData->set_disconnections(d->z.m_iDisconnections); pbGameData->set_unique_players_this_map(d->z.m_iUniquePlayers); pbGameData->set_teamplay(d->z.m_bTeamplay); pbGameData->set_thirdperson_active(d->z.m_iThirdPersonActive); pbGameData->set_thirdperson_inactive(d->z.m_iThirdPersonInactive); pbGameData->set_vr_active(d->z.m_iVRActive); pbGameData->set_vr_inactive(d->z.m_iVRInactive); pbGameData->set_platform_windows(d->z.m_iWindows); pbGameData->set_platform_linux(d->z.m_iLinux); pbGameData->set_platform_osx(d->z.m_iMac); google::protobuf::RepeatedPtrField<da::protobuf::Vector>* pPositions = pbGameData->mutable_positions()->mutable_position(); size_t iDataSize = d->m_avecPlayerPositions.Count(); pPositions->Reserve(iDataSize); for (size_t i = 0; i < iDataSize; i++) FillProtoBufVector(pPositions->Add(), d->m_avecPlayerPositions[i]); google::protobuf::RepeatedPtrField<std::string>* pCharacters = pbGameData->mutable_characters_chosen(); iDataSize = d->m_asCharactersChosen.Count(); pCharacters->Reserve(iDataSize); for (CUtlMap<CUtlString, int>::IndexType_t it = d->m_asCharactersChosen.FirstInorder(); it != d->m_asCharactersChosen.InvalidIndex(); it = d->m_asCharactersChosen.NextInorder(it)) { for (int i = 0; i < d->m_asCharactersChosen[it]; i++) pCharacters->Add()->assign(d->m_asCharactersChosen.Key(it).String()); } google::protobuf::RepeatedPtrField<std::string>* pWeapons = pbGameData->mutable_weapons_chosen_s(); iDataSize = d->m_aeWeaponsChosen.Count(); pWeapons->Reserve(iDataSize); for (size_t i = 0; i < iDataSize; i++) pWeapons->Add()->assign(WeaponIDToAlias(d->m_aeWeaponsChosen[i])); google::protobuf::RepeatedPtrField<std::string>* pSkills = pbGameData->mutable_skills_chosen_s(); iDataSize = d->m_aeSkillsChosen.Count(); pSkills->Reserve(iDataSize); for (size_t i = 0; i < iDataSize; i++) pSkills->Add()->assign(SkillIDToAlias(d->m_aeSkillsChosen[i])); google::protobuf::RepeatedPtrField<da::protobuf::VoteResult>* pVotes = pbGameData->mutable_votes(); iDataSize = d->m_aVoteResults.Count(); pVotes->Reserve(iDataSize); for (size_t i = 0; i < iDataSize; i++) { da::protobuf::VoteResult* pVR = pVotes->Add(); pVR->set_result(d->m_aVoteResults[i].m_bResult); pVR->set_issue(d->m_aVoteResults[i].m_sIssue); pVR->set_details(d->m_aVoteResults[i].m_sDetails); } google::protobuf::RepeatedPtrField<da::protobuf::KillInfo>* pKillInfos = pbGameData->mutable_kill_details(); iDataSize = d->m_apKillInfos.Count(); pKillInfos->Reserve(iDataSize); for (size_t i = 0; i < iDataSize; i++) pKillInfos->Add()->CopyFrom(*d->m_apKillInfos[i]); google::protobuf::RepeatedPtrField<da::protobuf::PlayerList>* pPlayerList = pbGameData->mutable_player_list(); iDataSize = d->m_apPlayerList.Count(); pPlayerList->Reserve(iDataSize); for (CUtlMap<AccountID_t, class da::protobuf::PlayerList*>::IndexType_t it = d->m_apPlayerList.FirstInorder(); it != d->m_apPlayerList.InvalidIndex(); it = d->m_apPlayerList.NextInorder(it)) pPlayerList->Add()->CopyFrom(*d->m_apPlayerList[it]); ClearData(); } void CDataManager::ClearData() { // Delete the data container and re-create it every level // to remove the possibility of old data remaining. delete d; d = new CDataContainer(); } CDataManager::CDataContainer::~CDataContainer() { m_apKillInfos.PurgeAndDeleteElements(); m_apPlayerList.PurgeAndDeleteElements(); } #endif
28.732601
191
0.744327
Black-Stormy
21fa2ada2fcfcd2c34a4efcdaf37f072bb8e6e6f
2,579
cpp
C++
test/test_preprocessor.cpp
sakshikakde/human-detector-and-tracker
04e1fd08b858ababfa4fa91da8306890ef1d7d00
[ "MIT" ]
null
null
null
test/test_preprocessor.cpp
sakshikakde/human-detector-and-tracker
04e1fd08b858ababfa4fa91da8306890ef1d7d00
[ "MIT" ]
3
2021-10-16T05:46:37.000Z
2021-10-18T22:16:20.000Z
test/test_preprocessor.cpp
sakshikakde/human-detector-and-tracker
04e1fd08b858ababfa4fa91da8306890ef1d7d00
[ "MIT" ]
2
2021-10-06T02:52:31.000Z
2021-10-06T05:16:28.000Z
/** * MIT License * * Copyright (c) 2021 Anubhav Paras, Sakshi Kakde, Siddharth Telang * * 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. * * @file test_preprocessor.cpp * @author Anubhav Paras (anubhav@umd.edu) * @author Sakshi Kakde (sakshi@umd.edu) * @author Siddharth Telang (stelang@umd.edu) * @brief test file for preprocessor.cpp * @version 0.1 * @date 2021-10-25 * * @copyright Copyright (c) 2021 * */ #include <gtest/gtest.h> #include <string> #include <opencv2/opencv.hpp> #include <preprocessor.hpp> TEST(preprocessor_test, image_resize) { std::string test_path = "../data/testdata/unit_test_data/pos/FudanPed00028.png"; PreProcessor preProcessor; cv::Mat image = cv::imread(test_path); cv::Size originalSize = image.size(); cv::Size expectedSize = cv::Size(100, 100); preProcessor.resize(image, image, expectedSize); EXPECT_TRUE(image.size().height != originalSize.height); EXPECT_EQ(image.size().height, expectedSize.height); EXPECT_TRUE(image.size().width != originalSize.width); EXPECT_EQ(image.size().width, expectedSize.width); } TEST(preprocessor_test, image_resize_no_resize) { std::string test_path = "../data/testdata/unit_test_data/pos/FudanPed00028.png"; PreProcessor preProcessor; cv::Mat image = cv::imread(test_path); cv::Size originalSize = image.size(); preProcessor.resize(image, image, cv::Size()); EXPECT_EQ(image.size().height, originalSize.height); EXPECT_EQ(image.size().width, originalSize.width); }
36.323944
81
0.724699
sakshikakde
21fae4fa506214d1580df4ba2c9ecb7631f6b632
21,586
cpp
C++
frame_tests.cpp
draghan/memoryframe
da573df30613759d61537ca78b5a41a248c2a811
[ "MIT" ]
null
null
null
frame_tests.cpp
draghan/memoryframe
da573df30613759d61537ca78b5a41a248c2a811
[ "MIT" ]
null
null
null
frame_tests.cpp
draghan/memoryframe
da573df30613759d61537ca78b5a41a248c2a811
[ "MIT" ]
null
null
null
/* This file is distributed under MIT License. Copyright (c) 2019 draghan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "external/Catch2/single_include/catch2/catch.hpp" #include "Frame.hpp" FrameEntity getFrame() { byte_t value = 0b01010101; FrameEntity x{value}; return x; } TEST_CASE("Memory: frame entity bitwise operators", "[memory][Frame]") { SECTION("~") { constexpr byte_t expectedValue = ~0b11110000u; FrameEntity f{byte_t{0b11110000}}; f = ~f; REQUIRE(f == expectedValue); REQUIRE(f[0] == 1); REQUIRE(f[7] == 0); } SECTION("&") { constexpr byte_t first = 0b11100011u; constexpr byte_t second = 0b00100001u; constexpr byte_t expectedValue = first & second; FrameEntity f{byte_t{first}}; FrameEntity g{byte_t{second}}; f = f & g; REQUIRE(f == expectedValue); } SECTION("|") { constexpr byte_t first = 0b11100011u; constexpr byte_t second = 0b00100001u; constexpr byte_t expectedValue = first | second; FrameEntity f{byte_t{first}}; FrameEntity g{byte_t{second}}; f = f | g; REQUIRE(f == expectedValue); } SECTION("^") { constexpr byte_t first = 0b11100011u; constexpr byte_t second = 0b00100001u; constexpr byte_t expectedValue = first ^second; FrameEntity f{byte_t{first}}; FrameEntity g{byte_t{second}}; f = f ^ g; REQUIRE(f == expectedValue); } SECTION(">>") { constexpr byte_t first = 0b11100011u; constexpr byte_t second = 0b00100001u; constexpr byte_t expectedValue = first >> 2; FrameEntity f{byte_t{first}}; FrameEntity g{byte_t{second}}; f = f >> byte_t(2); REQUIRE(f == expectedValue); } SECTION("<<") { constexpr byte_t first = 0b11100011u; constexpr byte_t second = 0b00100001u; constexpr byte_t expectedValue = first << 2; FrameEntity f{byte_t{first}}; FrameEntity g{byte_t{second}}; f = f << byte_t(2); REQUIRE(f == expectedValue); } SECTION("&=") { constexpr byte_t first = 0b11100011u; constexpr byte_t second = 0b00100001u; constexpr byte_t expectedValue = first & second; FrameEntity f{byte_t{first}}; FrameEntity g{byte_t{second}}; f &= g; REQUIRE(f == expectedValue); } SECTION("^=") { constexpr byte_t first = 0b11100011u; constexpr byte_t second = 0b00100001u; constexpr byte_t expectedValue = first ^second; FrameEntity f{byte_t{first}}; FrameEntity g{byte_t{second}}; f ^= g; REQUIRE(f == expectedValue); } SECTION("|=") { constexpr byte_t first = 0b11100011u; constexpr byte_t second = 0b00100001u; constexpr byte_t expectedValue = first | second; FrameEntity f{byte_t{first}}; FrameEntity g{byte_t{second}}; f |= g; REQUIRE(f == expectedValue); } SECTION(">>=") { constexpr byte_t first = 0b11100011u; constexpr byte_t second = 0b00100001u; constexpr byte_t expectedValue = first >> 2; FrameEntity f{byte_t{first}}; FrameEntity g{byte_t{second}}; f >>= byte_t(2); REQUIRE(f == expectedValue); } SECTION("<<=") { constexpr byte_t first = 0b11100011u; constexpr byte_t second = 0b00100001u; constexpr byte_t expectedValue = first << 2; FrameEntity f{byte_t{first}}; FrameEntity g{byte_t{second}}; f <<= byte_t(2); REQUIRE(f == expectedValue); } } TEST_CASE("Memory: frame entity clip", "[memory][Frame]") { SECTION("Clipping - valid range") { // index: 7654 3210 constexpr byte_t original = 0b1110'0011; constexpr byte_t expected_0_1 = 0b0000'0011; constexpr byte_t expected_0_6 = 0b0110'0011; constexpr byte_t expected_1_7 = 0b0111'0001; constexpr byte_t expected_3_7 = 0b0001'1100; constexpr byte_t expected_2_5 = 0b0000'1000; constexpr byte_t expected_0_0 = 0b0000'0001; constexpr byte_t expected_7_7 = 0b0000'0001; constexpr byte_t expected_0_7 = 0b1110'0011; const FrameEntity f{original}; REQUIRE(f(0, 1) == expected_0_1); REQUIRE(f(0, 6) == expected_0_6); REQUIRE(f(1, 7) == expected_1_7); REQUIRE(f(3, 7) == expected_3_7); REQUIRE(f(2, 5) == expected_2_5); REQUIRE(f(2, 5) == expected_2_5); REQUIRE(f(0, 0) == expected_0_0); REQUIRE(f(7, 7) == expected_7_7); REQUIRE(f(0, 7) == expected_0_7); } SECTION("Clipping - invalid range") { const FrameEntity f{}; REQUIRE_THROWS(f(-1, 5)); REQUIRE_THROWS(f(5, 4)); REQUIRE_THROWS(f(4, 8)); REQUIRE_THROWS(f(8, 8)); REQUIRE_THROWS(f(8, 15)); REQUIRE_THROWS(f(0, 8)); REQUIRE_THROWS(f(20, 15)); } } TEST_CASE("Memory: frame entity comparison", "[memory][Frame]") { SECTION("notEquality FrameEntities") { byte_t value = 0b01010101; FrameEntity x{value}; FrameEntity y{x}; y[0] = 0; y[1] = 0; REQUIRE(x != y); } SECTION("Equality FrameEntities") { byte_t value = 0b01010101; FrameEntity x{value}; FrameEntity y{x}; REQUIRE(x == y); } SECTION("Equality bitset") { byte_t value = 0b01010101; FrameEntity x{value}; std::bitset<8> y; y[0] = 1; y[1] = 0; y[2] = 1; y[3] = 0; y[4] = 1; y[5] = 0; y[6] = 1; y[7] = 0; REQUIRE(x == y); } } TEST_CASE("Memory: frame entity assignment", "[memory][Frame]") { SECTION("value") { byte_t value = 0b01010101; FrameEntity x; x = value; REQUIRE(x[0] == 1); REQUIRE(x[1] == 0); REQUIRE(x[2] == 1); REQUIRE(x[3] == 0); REQUIRE(x[4] == 1); REQUIRE(x[5] == 0); REQUIRE(x[6] == 1); REQUIRE(x[7] == 0); } SECTION("bitset") { byte_exposed_t value = 0b01010101; FrameEntity f{}; f = value; REQUIRE(f[0] == 1); REQUIRE(f[1] == 0); REQUIRE(f[2] == 1); REQUIRE(f[3] == 0); REQUIRE(f[4] == 1); REQUIRE(f[5] == 0); REQUIRE(f[6] == 1); REQUIRE(f[7] == 0); } // SECTION("string") // { // std::string value = "0b01010101"; // FrameEntity f{}; // f = value; // REQUIRE(f[0] == 1); // REQUIRE(f[1] == 0); // REQUIRE(f[2] == 1); // REQUIRE(f[3] == 0); // REQUIRE(f[4] == 1); // REQUIRE(f[5] == 0); // REQUIRE(f[6] == 1); // REQUIRE(f[7] == 0); // } } TEST_CASE("Memory: frame entity conversion", "[memory][Frame]") { SECTION("To value") { byte_t value = 0b01010101; FrameEntity x{value}; byte_t converted = x; REQUIRE(value == converted); } SECTION("To bitset") { byte_t value = 0b01010101; FrameEntity x{value}; byte_exposed_t converted = x; REQUIRE(value == converted.to_ulong()); } // SECTION("To string") // { // byte_t value = 0xAF; // FrameEntity x{value}; // // std::string converted = x; // REQUIRE(converted == "af"); // } } TEST_CASE("Memory: frame entity creation", "[memory][Frame]") { SECTION("Default ctor") { FrameEntity byteZero{}; FrameEntity byteOne{true}; REQUIRE(byteOne[0] == true); REQUIRE(byteOne[1] == true); REQUIRE(byteOne[2] == true); REQUIRE(byteOne[3] == true); REQUIRE(byteOne[4] == true); REQUIRE(byteOne[5] == true); REQUIRE(byteOne[6] == true); REQUIRE(byteOne[7] == true); REQUIRE_THROWS(byteOne[8]); REQUIRE(byteZero[0] == false); REQUIRE(byteZero[1] == false); REQUIRE(byteZero[2] == false); REQUIRE(byteZero[3] == false); REQUIRE(byteZero[4] == false); REQUIRE(byteZero[5] == false); REQUIRE(byteZero[6] == false); REQUIRE(byteZero[7] == false); REQUIRE_THROWS(byteZero[8]); } SECTION("Creation from single value") { byte_t value = 0b01010101; FrameEntity f{value}; REQUIRE(f[0] == 1); REQUIRE(f[1] == 0); REQUIRE(f[2] == 1); REQUIRE(f[3] == 0); REQUIRE(f[4] == 1); REQUIRE(f[5] == 0); REQUIRE(f[6] == 1); REQUIRE(f[7] == 0); } SECTION("Creation from bitset") { byte_exposed_t value = 0b01010101; FrameEntity f{value}; REQUIRE(f[0] == 1); REQUIRE(f[1] == 0); REQUIRE(f[2] == 1); REQUIRE(f[3] == 0); REQUIRE(f[4] == 1); REQUIRE(f[5] == 0); REQUIRE(f[6] == 1); REQUIRE(f[7] == 0); } // SECTION("Creation from string") // { // std::string value = "0b01010101"; // FrameEntity f{value}; // REQUIRE(f[0] == 1); // REQUIRE(f[1] == 0); // REQUIRE(f[2] == 1); // REQUIRE(f[3] == 0); // REQUIRE(f[4] == 1); // REQUIRE(f[5] == 0); // REQUIRE(f[6] == 1); // REQUIRE(f[7] == 0); // } SECTION("Copy constructor") { byte_t value = 0b01010101; FrameEntity x{value}; FrameEntity f{x}; REQUIRE(f[0] == 1); REQUIRE(f[1] == 0); REQUIRE(f[2] == 1); REQUIRE(f[3] == 0); REQUIRE(f[4] == 1); REQUIRE(f[5] == 0); REQUIRE(f[6] == 1); REQUIRE(f[7] == 0); REQUIRE(x[0] == 1); REQUIRE(x[1] == 0); REQUIRE(x[2] == 1); REQUIRE(x[3] == 0); REQUIRE(x[4] == 1); REQUIRE(x[5] == 0); REQUIRE(x[6] == 1); REQUIRE(x[7] == 0); } SECTION("Move constructor") { FrameEntity f{getFrame()}; REQUIRE(f[0] == 1); REQUIRE(f[1] == 0); REQUIRE(f[2] == 1); REQUIRE(f[3] == 0); REQUIRE(f[4] == 1); REQUIRE(f[5] == 0); REQUIRE(f[6] == 1); REQUIRE(f[7] == 0); } } TEST_CASE("Memory: frame insert", "[memory][Frame]") { SECTION("Insert array") { Frame f{1, 2}; uint8_t g[]{3, 4, 5}; f.insert(g, 2); REQUIRE(f.size() == 4); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 3); REQUIRE(f[3] == 4); } SECTION("Insert frame") { Frame f{1, 2}; Frame g{3, 4}; f.insert(g); REQUIRE(f.size() == 4); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 3); REQUIRE(f[3] == 4); } SECTION("Insert vector of values") { Frame f{1, 2}; std::vector<uint8_t> v{3, 4}; f.insert(v); REQUIRE(f.size() == 4); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 3); REQUIRE(f[3] == 4); } SECTION("Insert single value") { Frame f{1, 2}; f.insert(6); REQUIRE(f.size() == 3); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 6); } } void expect1_2_3(const uint8_t table[], size_t size) { REQUIRE(size == 3); REQUIRE(table[0] == 1); REQUIRE(table[1] == 2); REQUIRE(table[2] == 3); } TEST_CASE("readme example") { // constructing from std-like containers: const std::vector<uint8_t> v{0xDE, 0xAD, 0xBE, 0xEF}; const Frame f{v}; // access to byte range: const Frame beef = f(2, 3); REQUIRE(beef == Frame{0xBE, 0xEF}); // ...and constructing from initializer list // access to single byte: const FrameEntity ad = f[1]; REQUIRE(ad == 0xAD); // ...and comparing bytes // access to single bit (0 - least significant bit): REQUIRE(ad == 0b10101101); REQUIRE(ad[0] == 1); // ...and comparing bits REQUIRE(ad[1] == 0); REQUIRE(ad[2] == 1); REQUIRE(ad[3] == 1); // access to range of bits: REQUIRE(ad(0, 3) == 0b1101); // appending frames: auto fbeef = f + beef; REQUIRE(fbeef == Frame{0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0xEF}); fbeef += 0; REQUIRE(fbeef == Frame{0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0xEF, 0x00}); // get second, third and fourth bits from third byte: auto foo = f[3](1, 3); REQUIRE(foo == 0b111); } TEST_CASE("Memory: reverse", "[memory][Frame]") { SECTION("reverse") { Frame f{1, 2, 3}; f.reverse(); REQUIRE(f.size() == 3); REQUIRE(f[0] == 3); REQUIRE(f[1] == 2); REQUIRE(f[2] == 1); } } TEST_CASE("Memory: data access", "[memory][Frame]") { SECTION("Data access") { Frame f{1, 2, 3}; expect1_2_3(f.data(), f.size()); } } TEST_CASE("Memory: frame indexing", "[memory][Frame]") { SECTION("Bit indexing") { Frame f{0b11000000, 0b10000011}; REQUIRE(f[0][0] == 0); REQUIRE(f[0][1] == 0); REQUIRE(f[0][2] == 0); REQUIRE(f[0][3] == 0); REQUIRE(f[0][4] == 0); REQUIRE(f[0][5] == 0); REQUIRE(f[0][6] == 1); REQUIRE(f[0][7] == 1); REQUIRE(f[1][0] == 1); REQUIRE(f[1][1] == 1); REQUIRE(f[1][2] == 0); REQUIRE(f[1][3] == 0); REQUIRE(f[1][4] == 0); REQUIRE(f[1][5] == 0); REQUIRE(f[1][6] == 0); REQUIRE(f[1][7] == 1); } SECTION("Byte indexing") { Frame f{0b11000000, 0b11000011}; REQUIRE(f[0] == 0b11000000); REQUIRE(f[1] == 0b11000011); } } TEST_CASE("Memory: frame splice", "[memory][Frame]") { SECTION("Valid splice") { Frame f{0, 1, 2, 3}; REQUIRE(f(0, 2) == Frame{0, 1, 2}); REQUIRE(f(1, 3) == Frame{1, 2, 3}); REQUIRE(f(0, 3) == Frame{0, 1, 2, 3}); REQUIRE(f(0, 0) == Frame{0}); } SECTION("Checking splice") { Frame f{0, 1, 2, 3}; REQUIRE(f.spliceIsValid(0, 3)); REQUIRE(!f.spliceIsValid(3, 0)); REQUIRE(!f.spliceIsValid(0, 4)); REQUIRE(!f.spliceIsValid(4, 5)); REQUIRE(!f.spliceIsValid(4, 4)); } SECTION("Invalid splice") { Frame f{0, 1, 2, 3}; REQUIRE_THROWS(f(3, 0)); REQUIRE_THROWS(f(0, 4)); REQUIRE_THROWS(f(4, 5)); REQUIRE_THROWS(f(4, 4)); } } TEST_CASE("Memory: frame place at", "[memory][Frame]") { SECTION("Insert array") { Frame f{1, 2}; uint8_t g[]{3, 4}; f.placeAt(1, g, 2); REQUIRE(f.size() == 3); REQUIRE(f[0] == 1); REQUIRE(f[1] == 3); REQUIRE(f[2] == 4); } SECTION("Insert frame") { Frame f{1, 2}; Frame g{3, 4}; f.placeAt(2, g); REQUIRE(f.size() == 4); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 3); REQUIRE(f[3] == 4); } SECTION("Insert vector of values") { Frame f{1, 2}; std::vector<uint8_t> v{3, 4}; f.placeAt(3, v); REQUIRE(f.size() == 5); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 0); REQUIRE(f[3] == 3); REQUIRE(f[4] == 4); } SECTION("Insert single value") { Frame f{1, 2}; f.placeAt(2, 6); REQUIRE(f.size() == 3); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 6); f.placeAt(5, 55); REQUIRE(f.size() == 6); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 6); REQUIRE(f[3] == 0); REQUIRE(f[4] == 0); REQUIRE(f[5] == 55); } } TEST_CASE("Memory: frame concatenation", "[memory][Frame]") { SECTION("+= single value") { Frame f{1, 2}; f += 5; REQUIRE(f.size() == 3); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 5); } SECTION("+= braced") { Frame f{1, 2}; f += {3, 4}; REQUIRE(f.size() == 4); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 3); REQUIRE(f[3] == 4); } SECTION("+= vector") { Frame f{1, 2}; std::vector<uint8_t> g{3, 4}; f += g; REQUIRE(f.size() == 4); REQUIRE(g.size() == 2); REQUIRE(g[0] == 3); REQUIRE(g[1] == 4); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 3); REQUIRE(f[3] == 4); } SECTION("+= Frame") { Frame f{1, 2}; Frame g{3, 4}; f += g; REQUIRE(f.size() == 4); REQUIRE(g.size() == 2); REQUIRE(g[0] == 3); REQUIRE(g[1] == 4); REQUIRE(f[0] == 1); REQUIRE(f[1] == 2); REQUIRE(f[2] == 3); REQUIRE(f[3] == 4); } } TEST_CASE("Memory: frame comparison", "[memory][Frame]") { SECTION("Frames equality") { Frame f{{1, 2}}; Frame g{1, 2}; REQUIRE(f.size() == 2); REQUIRE(g.size() == 2); REQUIRE(f == g); } SECTION("Equality with table") { Frame f{{1, 2}}; uint8_t v[] = {1, 2}; REQUIRE(f == Frame(v, 2)); } SECTION("Equality with vector") { Frame f{{1, 2}}; std::vector<uint8_t> v{1, 2}; REQUIRE(f == v); } SECTION("Frames inequality") { Frame f{{1, 2}}; Frame g{2, 2}; REQUIRE(f.size() == 2); REQUIRE(g.size() == 2); REQUIRE(f != g); } SECTION("Inequality with table") { Frame f{{1, 2}}; uint8_t v[] = {2, 2}; REQUIRE(f != Frame(v, 2)); } SECTION("Ineuality with vector") { Frame f{{1, 2}}; std::vector<uint8_t> v{2, 2}; REQUIRE(f != v); } } TEST_CASE("Memory: frame creation", "[memory][Frame]") { SECTION("Default ctor") { Frame f{}; REQUIRE(f.size() == 0); REQUIRE_THROWS(f[0] == static_cast<uint8_t>(1)); } SECTION("Copy ctor") { Frame f{{1, 2}}; Frame g{f}; REQUIRE(f.size() == 2); REQUIRE(g.size() == 2); REQUIRE(f == g); REQUIRE(f[0] == g[0]); REQUIRE(f[1] == g[1]); REQUIRE_THROWS(f[2]); REQUIRE_THROWS(g[2]); // change value in one of them: REQUIRE_NOTHROW(g[0] = 15); REQUIRE(f[0] != g[0]); REQUIRE(f[0] == 1); REQUIRE(g[0] == 15); REQUIRE(f[1] == g[1]); } SECTION("Default filling") { Frame zero(5, false); Frame one(5, true); std::bitset<8> bits; bool value = false; bits[0] = value; bits[1] = value; bits[2] = value; bits[3] = value; bits[4] = value; bits[5] = value; bits[6] = value; bits[7] = value; REQUIRE(zero[0] == bits); REQUIRE(zero[1] == bits); REQUIRE(zero[2] == bits); REQUIRE(zero[3] == bits); REQUIRE(zero[4] == bits); REQUIRE_THROWS(zero[5] == bits); value = true; bits[0] = value; bits[1] = value; bits[2] = value; bits[3] = value; bits[4] = value; bits[5] = value; bits[6] = value; bits[7] = value; REQUIRE(one[0] == bits); REQUIRE(one[1] == bits); REQUIRE(one[2] == bits); REQUIRE(one[3] == bits); REQUIRE(one[4] == bits); REQUIRE_THROWS(one[5] == bits); } SECTION("From vector of bytes") { std::vector<uint8_t> bytes{10, 20, 50, 100}; Frame f{bytes}; REQUIRE(f.size() == bytes.size()); REQUIRE(f == bytes); } SECTION("From braced values") { Frame f{10, 20, 50, 100}; REQUIRE(f.size() == 4); REQUIRE(f[0] == 10); REQUIRE(f[1] == 20); REQUIRE(f[2] == 50); REQUIRE(f[3] == 100); } SECTION("From array") { uint8_t array[] = {10, 20, 50, 100}; Frame f{array, 4}; REQUIRE(f.size() == 4); REQUIRE(f[0] == 10); REQUIRE(f[1] == 20); REQUIRE(f[2] == 50); REQUIRE(f[3] == 100); } }
23.412148
84
0.493236
draghan
1d01a2f71775db78545546cad9c421aed8f3b28c
2,021
cpp
C++
tests/test2.cpp
kosirev/lab5
f898ac9253e01b45879fd75f05d6f348516d7762
[ "MIT" ]
null
null
null
tests/test2.cpp
kosirev/lab5
f898ac9253e01b45879fd75f05d6f348516d7762
[ "MIT" ]
null
null
null
tests/test2.cpp
kosirev/lab5
f898ac9253e01b45879fd75f05d6f348516d7762
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <Stack2.hpp> TEST(Stack2, correct_primitive) { Stack2<int> stack; stack.push(10); int value1 = 15, value2 = 33; stack.push_emplace(value1); EXPECT_EQ(value1, stack.pop()); EXPECT_EQ(10, stack.head()); stack.push_emplace(value2); EXPECT_EQ(value2, stack.head()); stack.push(1200); EXPECT_EQ(1200, stack.head()); } class My_class { public: My_class() { value_i = 0; value_f = 0.1; value_s = "0"; } My_class(int a, double b, std::string c){ value_i = a; value_f = b; value_s = c; } int value_i; double value_f; std::string value_s; }; TEST(Stack2, correct_my_class) { Stack2<My_class> stack; My_class my_class1; My_class my_class2(15, 1.1, "1"); stack.push_emplace(my_class1); EXPECT_EQ(my_class1.value_f, stack.head().value_f); EXPECT_EQ(my_class1.value_s, stack.head().value_s); EXPECT_EQ(my_class1.value_i, stack.head().value_i); stack.push_emplace(my_class2); EXPECT_EQ(my_class2.value_f, stack.head().value_f); EXPECT_EQ(my_class2.value_s, stack.head().value_s); EXPECT_EQ(my_class2.value_i, stack.pop().value_i); EXPECT_EQ(my_class1.value_f, stack.head().value_f); EXPECT_EQ(my_class1.value_s, stack.head().value_s); EXPECT_EQ(my_class1.value_i, stack.head().value_i); } TEST(Stack2, emplace) { Stack2<My_class> stack; int value_i = 5; double value_f = 5.5; std::string value_s = "Hi"; stack.push_emplace(100, 10.1, "102"); stack.push_emplace(value_i, value_f, value_s); EXPECT_EQ(value_i, stack.head().value_i); EXPECT_EQ(value_f, stack.head().value_f); EXPECT_EQ(value_s, stack.pop().value_s); EXPECT_EQ(100, stack.head().value_i); EXPECT_EQ(10.1, stack.head().value_f); EXPECT_EQ("102", stack.head().value_s); } TEST(Stack2, type_traits) { EXPECT_TRUE(std::is_move_constructible<int>::value); EXPECT_TRUE(std::is_move_assignable<int>::value); EXPECT_TRUE(std::is_move_constructible<My_class>::value); EXPECT_TRUE(std::is_move_assignable<My_class>::value); }
28.464789
59
0.703117
kosirev
1d048fb4fbb4d23044d47e06cc09edf76f25e8c6
826
cpp
C++
OculusPlatformBP/Source/OculusPlatformBP/Private/OBP_TeamArray.cpp
InnerLoopLLC/OculusPlatformBP
d4bfb5568c56aa781e2ee76896d69a0ade1f57a2
[ "MIT" ]
29
2020-10-22T13:46:23.000Z
2022-03-18T14:32:51.000Z
OculusPlatformBP/Source/OculusPlatformBP/Private/OBP_TeamArray.cpp
InnerLoopLLC/OculusPlatformBP
d4bfb5568c56aa781e2ee76896d69a0ade1f57a2
[ "MIT" ]
2
2021-05-06T18:14:39.000Z
2021-05-25T01:12:15.000Z
OculusPlatformBP/Source/OculusPlatformBP/Private/OBP_TeamArray.cpp
InnerLoopLLC/OculusPlatformBP
d4bfb5568c56aa781e2ee76896d69a0ade1f57a2
[ "MIT" ]
null
null
null
// OculusPlatformBP plugin by InnerLoop LLC 2020 #include "OBP_TeamArray.h" // -------------------- // Initializers // -------------------- UOBP_TeamArray::UOBP_TeamArray(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } // -------------------- // OVR_TeamArray.h // -------------------- UOBP_Team* UOBP_TeamArray::GetElement(int32 Index) { #if PLATFORM_MINOR_VERSION >= 39 auto Team = NewObject<UOBP_Team>(); Team->ovrTeamHandle = ovr_TeamArray_GetElement(ovrTeamArrayHandle, Index); return Team; #else OBP_PlatformVersionError("TeamArray::GetElement", "1.39"); return nullptr; #endif } int32 UOBP_TeamArray::GetSize() { #if PLATFORM_MINOR_VERSION >= 39 return ovr_TeamArray_GetSize(ovrTeamArrayHandle); #else OBP_PlatformVersionError("TeamArray::GetSize", "1.39"); return 0; #endif }
21.736842
75
0.690073
InnerLoopLLC
1d05d60365d501f0507835f1138b237bbb3d9428
4,123
cc
C++
src/core/CommandLine.cc
estepanov-lvk/runos
9b856b8a829539bb667156178d283ffc4ef3cf32
[ "Apache-2.0" ]
41
2015-02-09T10:04:35.000Z
2021-11-21T06:34:38.000Z
src/core/CommandLine.cc
estepanov-lvk/runos
9b856b8a829539bb667156178d283ffc4ef3cf32
[ "Apache-2.0" ]
31
2015-03-04T14:02:36.000Z
2020-12-11T09:23:16.000Z
src/core/CommandLine.cc
estepanov-lvk/runos
9b856b8a829539bb667156178d283ffc4ef3cf32
[ "Apache-2.0" ]
42
2015-02-13T14:24:00.000Z
2021-11-09T12:04:38.000Z
/* * Copyright 2019 Applied Research Center for Computer Networks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CommandLine.hpp" #include <thread> #include <iostream> #include <utility> // pair #include <cstdio> #include <cctype> // isspace #include <QCoreApplication> #include <histedit.h> #include "Config.hpp" namespace runos { REGISTER_APPLICATION(CommandLine, {""}) struct CommandLine::implementation { std::unique_ptr<EditLine, decltype(&el_end)> el { nullptr, &el_end }; std::unique_ptr<History, decltype(&history_end)> hist { history_init(), &history_end }; std::vector< std::pair<cli_pattern, cli_command> > commands; HistEvent hev; bool keep_reading { true }; bool handle(const char* cmd, int len); void run(); }; struct command_error : public std::runtime_error { using std::runtime_error::runtime_error; }; struct skip_command : public std::exception { }; CommandLine::CommandLine() : impl(new implementation) { } CommandLine::~CommandLine() = default; static const char* prompt(EditLine*) { return "runos> "; } void CommandLine::init(Loader*, const Config& rootConfig) { const auto& config = config_cd(rootConfig, "cli"); history(impl->hist.get(), &impl->hev, H_SETSIZE, config_get(config, "history-size", 800)); const char* argv0 = QCoreApplication::arguments().at(0).toLatin1().data(); impl->el.reset(el_init(argv0, stdin, stdout, stderr)); el_set(impl->el.get(), EL_PROMPT, &prompt); el_set(impl->el.get(), EL_EDITOR, config_get(config, "editor", "emacs").c_str()); el_set(impl->el.get(), EL_HIST, history, impl->hist.get()); } void CommandLine::startUp(Loader*) { std::thread {&implementation::run, impl.get()}.detach(); } void CommandLine::register_command(cli_pattern&& spec, cli_command&& fn) { impl->commands.emplace_back(std::move(spec), std::move(fn)); } void CommandLine::error_impl(std::string && msg) { throw command_error(msg); } void CommandLine::skip() { throw skip_command(); } void CommandLine::implementation::run() { for (;keep_reading;) { int len; const char* line = el_gets(el.get(), &len); if (line == nullptr) break; if (handle(line, len)) { if (not std::isspace(*line)) { history(hist.get(), &hev, H_ENTER, line); } } } } bool CommandLine::implementation::handle(const char* line, int len) { if (line == nullptr) return false; const char* end = line + len; // skip whitespace while (line < end && std::isspace(*line)) ++line; while (line < end && std::isspace(*(end-1))) --end; // empty line if (line == end) return false; for (const auto & cmd : commands) { std::cmatch match; if (not std::regex_match(line, end, match, cmd.first)) continue; try { cmd.second(match); return true; } catch (skip_command&) { continue; } catch (command_error& ex) { std::cerr << "Error: " << ex.what() << std::endl; return false; } catch (std::exception& ex) { std::cerr << "Uncaught exception: " << ex.what() << std::endl; return false; } catch (...) { std::cerr << "Uncaught exception"; return false; } } std::cerr << std::string(line, end) << ": no such command" << std::endl; return false; } } // namespace runos
24.541667
78
0.60878
estepanov-lvk
1d068c53c2c54186aaadfcfb5ac858ebc6ceb418
456
hpp
C++
include/VBE/graphics/RenderTarget.hpp
Dirbaio/VBE
539d222dcbbf565ab64dc5d2463b310fd4b75873
[ "MIT" ]
null
null
null
include/VBE/graphics/RenderTarget.hpp
Dirbaio/VBE
539d222dcbbf565ab64dc5d2463b310fd4b75873
[ "MIT" ]
null
null
null
include/VBE/graphics/RenderTarget.hpp
Dirbaio/VBE
539d222dcbbf565ab64dc5d2463b310fd4b75873
[ "MIT" ]
null
null
null
#ifndef RENDERTARGET_HPP #define RENDERTARGET_HPP #include <VBE/graphics/RenderTargetBase.hpp> class RenderTarget : public RenderTargetBase { public: RenderTarget(unsigned int width, unsigned int height); ~RenderTarget(); void setTexture(RenderTargetBase::Attachment a, Texture2D* tex); void setBuffer(RenderTargetBase::Attachment a, RenderBuffer* buff); Texture2D* getTexture(RenderTargetBase::Attachment a); }; #endif // RENDERTARGET_HPP
25.333333
69
0.787281
Dirbaio
1d096066ff2a26e8048c83dbe153adee14bb3153
4,233
cpp
C++
ironstack_agent/gui/output.cpp
zteo-phd-software/ironstack
649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0
[ "BSD-3-Clause" ]
null
null
null
ironstack_agent/gui/output.cpp
zteo-phd-software/ironstack
649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0
[ "BSD-3-Clause" ]
null
null
null
ironstack_agent/gui/output.cpp
zteo-phd-software/ironstack
649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0
[ "BSD-3-Clause" ]
null
null
null
#include <string.h> #include "output.h" weak_ptr<gui_controller> output::controller; atomic_bool output::log_printf{false}; output::loglevel output::loglevel_threshold{output::loglevel::WARNING}; mutex output::fp_lock; FILE* output::fp = nullptr; // sets up output to point to a controller void output::init(const shared_ptr<gui_controller>& controller_) { controller = controller_; } // shuts down the gui controller, if any void output::shutdown() { shared_ptr<gui_controller> current_controller = controller.lock(); if (current_controller != nullptr) { current_controller->shutdown(); current_controller = nullptr; controller = current_controller; } } // attempts to start logging output to file bool output::start_log(const string& filename, bool log_printf_, loglevel loglevel_display_threshold) { log_printf = log_printf_; lock_guard<mutex> g(fp_lock); if (fp != nullptr) { fclose(fp); } fp = fopen(filename.c_str(), "a"); if (fp != nullptr) { char timestamp[128]; get_timestamp(timestamp); fprintf(fp, "### LOG STARTED [%s] ###\n", timestamp); } else { log_printf = false; } loglevel_threshold = loglevel_display_threshold; return fp == nullptr; } // stops logging to file void output::stop_log() { lock_guard<mutex> g(fp_lock); if (fp != nullptr) { fclose(fp); } fp = nullptr; log_printf = false; } // prints to either stdout or through the GUI controller void output::printf(const char* fmt, ...) { char buf[10240]; va_list args; va_start(args, fmt); vsnprintf(buf, sizeof(buf)-1, fmt, args); shared_ptr<gui_controller> current_controller = controller.lock(); if (current_controller != nullptr) { current_controller->printf("%s", buf); } else { ::printf("%s", buf); } // log to file if required if (log_printf) { log("%s", buf); } } // logs directly to file. does not appear on display. no loglevel associated. void output::log(const char* fmt, ...) { char buf[10240]; char timestamp[128]; va_list args; va_start(args, fmt); vsnprintf(buf, sizeof(buf)-33, fmt, args); // get timestamp get_timestamp(timestamp); // write to file lock_guard<mutex> g(fp_lock); if (fp != nullptr) { fprintf(fp, "[%s] %s", timestamp, buf); // append a newline if it wasn't given int len = strlen(buf); if (len == 0 || buf[len-1] != '\n') { fprintf(fp, "\n"); } } } // logs directly to file, with loglevel void output::log(const loglevel& level, const char* fmt, ...) { char buf[10240]; char timestamp[128]; va_list args; va_start(args, fmt); vsnprintf(buf, sizeof(buf)-33, fmt, args); // get timestamp get_timestamp(timestamp); // generate output string char result[1024+128+2]; switch (level) { case loglevel::VERBOSE: { snprintf(result, sizeof(result), "[%s] VERBOSE: %s", timestamp, buf); break; } case loglevel::INFO: { snprintf(result, sizeof(result), "[%s] INFO: %s", timestamp, buf); break; } case loglevel::WARNING: { snprintf(result, sizeof(result), "[%s] WARNING: %s", timestamp, buf); break; } case loglevel::CRITICAL: { snprintf(result, sizeof(result), "[%s] CRITICAL: %s", timestamp, buf); break; } case loglevel::ERROR: { snprintf(result, sizeof(result), "[%s] ERROR: %s", timestamp, buf); break; } case loglevel::BUG: { snprintf(result, sizeof(result), "[%s] BUG: %s", timestamp, buf); break; } } // check if newline was written. if not, add one. int len = strlen(buf); if (len == 0 || buf[len-1] != '\n') { strcat(buf, "\n"); } // write to file { lock_guard<mutex> g(fp_lock); if (fp != nullptr) { fprintf(fp, "%s", result); } } // display to output as required int loglevel_threshold_num = (int) loglevel_threshold; int loglevel_current_num = (int) level; if (loglevel_current_num >= loglevel_threshold_num) { shared_ptr<gui_controller> current_controller = controller.lock(); if (current_controller != nullptr) { current_controller->printf("%s", result); } else { ::printf("%s", result); } } } // generates a timestamp void output::get_timestamp(char* timestamp) { time_t rawtime; struct tm* info; time(&rawtime); info = localtime(&rawtime); strftime(timestamp, 128, "%d/%b %H:%M:%S", info); }
22.396825
103
0.665722
zteo-phd-software
1d0dd10d89587a6f29455e3c729418485138f32d
216
cpp
C++
TAO/orbsvcs/orbsvcs/Event/EC_Lifetime_Utils.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/orbsvcs/orbsvcs/Event/EC_Lifetime_Utils.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/orbsvcs/orbsvcs/Event/EC_Lifetime_Utils.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: EC_Lifetime_Utils.cpp 73791 2006-07-27 20:54:56Z wotte $ #include "orbsvcs/Event/EC_Lifetime_Utils.h" #if !defined(__ACE_INLINE__) #include "orbsvcs/Event/EC_Lifetime_Utils.inl" #endif /* __ACE_INLINE__ */
27
64
0.763889
cflowe
1d101c36e2656c2e2405b153d27510e444dc4552
2,730
hpp
C++
MATLAB/attitude_filter/helper_functions/conversion.hpp
kylekrol/psim
a4817117189f0f5597452076e6e138f70f51d4e8
[ "MIT" ]
5
2020-04-11T06:53:46.000Z
2022-01-05T05:39:11.000Z
MATLAB/attitude_filter/helper_functions/conversion.hpp
kylekrol/psim
a4817117189f0f5597452076e6e138f70f51d4e8
[ "MIT" ]
201
2019-09-05T03:46:21.000Z
2022-01-08T04:44:16.000Z
MATLAB/attitude_filter/helper_functions/conversion.hpp
kylekrol/psim
a4817117189f0f5597452076e6e138f70f51d4e8
[ "MIT" ]
10
2019-10-12T17:24:34.000Z
2022-02-25T01:20:14.000Z
#include "mex.hpp" #include "mexAdapter.hpp" #include <gnc/attitude_estimator.hpp> #include <lin.hpp> using namespace matlab::data; /** * @brief Create a matlab array from lin vec object * * @tparam N the dimension of the lin::vector * @tparam T the type of lin::vector * @param f a matlab array factory * @param lin_vec input lin::vector to be copied from * @return TypedArray<T> a matlab array */ template<lin::size_t N, typename T> TypedArray<T> create_from_lin_vec(ArrayFactory& f, const lin::Vector<T, N>& lin_vec){ TypedArray<T> ret = f.createArray<T>({N, 1}); for(int r = 0; r < N; r++){ ret[r][0] = lin_vec(r); } return ret; } /** * @brief Create an array of matlab arrays from a list of lin::vec arrays * * @tparam N length of each sub array * @tparam T type of input element * @param f matlab array factory * @param lin_vec input list of lin::vecs * @param L number of lin::vecs * @return TypedArray<T> returned array of arrays */ template<lin::size_t N, typename T> TypedArray<T> create_from_lin_vec_arr(ArrayFactory& f, const lin::Vector<T, N>* lin_vec, size_t L){ TypedArray<T> ret = f.createArray<T>({N, 1, L}); for(int i = 0; i < L; i++){ for(int r = 0; r < N; r++){ ret[r][0][i] = (lin_vec[i])(r); } } return ret; } /** * @brief Create a from lin mat object * * @tparam R rows * @tparam C columns * @tparam T input element type * @param f matlab array factory * @param lin_mat input lin matrix * @return TypedArray<T> matlab output matrix */ template<lin::size_t R, lin::size_t C, typename T> TypedArray<T> create_from_lin_mat(ArrayFactory& f, const lin::Matrix<T, R, C>& lin_mat){ TypedArray<T> ret = f.createArray<T>({R, C}); for(int r = 0; r < R; r++){ for(int c = 0; c < C; c++) ret[r][c] = lin_mat(r, c); } return ret; } /** * @brief copy a matlab array into a lin::Vec * * @tparam N array length * @tparam T element type * @param lin_vec lin::vec output reference * @param arr matlab array input */ template<lin::size_t N, typename T> void typed_array_to_lin_vec(lin::Vector<T, N>& lin_vec, matlab::data::Array& arr){ for (int i = 0; i<N; i++) { lin_vec(i) = arr[i]; } } /** * @brief Copy a matlab matrix into a lin::matrix * * @tparam T element type * @tparam R rows * @tparam C columns * @param lin_mat lin::matrix output reference * @param arr matlab array input */ template<typename T, lin::size_t R, lin::size_t C> void typed_array_to_lin_mat(lin::Matrix<T, R, C>& lin_mat, matlab::data::Array& arr){ for( int r = 0; r<R; r++){ for( int c = 0; c<C; c++){ lin_mat(r, c) = arr[r][c]; } } }
27.575758
99
0.621978
kylekrol
1d151b23993319bc256654ed6eec6d324b07e039
448
cpp
C++
Framework/Sources/o2/Assets/Meta.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
181
2015-12-09T08:53:36.000Z
2022-03-26T20:48:39.000Z
Framework/Sources/o2/Assets/Meta.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
29
2016-04-22T08:24:04.000Z
2022-03-06T07:06:28.000Z
Framework/Sources/o2/Assets/Meta.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
13
2018-04-24T17:12:04.000Z
2021-11-12T23:49:53.000Z
#include "o2/stdafx.h" #include "Meta.h" #include "o2/Assets/Asset.h" namespace o2 { AssetMeta::AssetMeta() : mId(0) {} AssetMeta::~AssetMeta() {} const Type* AssetMeta::GetAssetType() const { return &TypeOf(Asset); } bool AssetMeta::IsEqual(AssetMeta* other) const { return GetAssetType() == other->GetAssetType() && mId == other->mId; } const UID& AssetMeta::ID() const { return mId; } } DECLARE_CLASS(o2::AssetMeta);
14
70
0.65625
zenkovich
1d175c9aa45e1dddb65d3437382488753a1d169f
118
cpp
C++
StaticEx/Hello.cpp
jaespo/Nifty
6114eb7250776c136d3ae7757b70388caa6930a5
[ "Unlicense" ]
null
null
null
StaticEx/Hello.cpp
jaespo/Nifty
6114eb7250776c136d3ae7757b70388caa6930a5
[ "Unlicense" ]
null
null
null
StaticEx/Hello.cpp
jaespo/Nifty
6114eb7250776c136d3ae7757b70388caa6930a5
[ "Unlicense" ]
null
null
null
#include <iostream> #include "Hello.h" void nsHello::CHello::SayHello() { std::cout << "Hello World" << std::endl; }
16.857143
41
0.652542
jaespo
1d1e40bc0889f5eb9ae46d628d5a19c36b439b01
1,315
cpp
C++
C++_Mavros/amov_mavro service _3.cpp
Chentao2000/practice_code
aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c
[ "Apache-2.0" ]
4
2022-01-07T13:07:48.000Z
2022-02-08T04:46:02.000Z
C++_Mavros/amov_mavro service _3.cpp
Chentao2000/practice_code
aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c
[ "Apache-2.0" ]
null
null
null
C++_Mavros/amov_mavro service _3.cpp
Chentao2000/practice_code
aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c
[ "Apache-2.0" ]
null
null
null
// 通过前面两节的学习,我们对mavros操作无人机有了深刻的理解,无非就是通过ROS去取得以下当前的飞行状态,然后发送控制让他执行 // 当前在控制的时候,你可以选取很多方式,加速度方式,位置方式,姿态方式,都是可行的 // 那么这一节,将会围绕两个服务进行我们讲解,(模式切换 解锁 // ------------------------------------------------------------------- // 1. arming Service 加解锁服务 // 消息名称 : mavros/cmd/arming // 类型名称 : mavros_msgs::CommandBool // 类型所在头文件 :mavros_msgs / CommandBool.h // 服务请求参数 : // bool success //是否能执行成功 // uint8 result // 错误信息 // 注意: 在ros中所有服务参数都在 xxx.request 中,所有返回状态都在 xxx.response 中 // 如果我们想要解锁,那么代码可以如下来写 // ros :: init ( argc ,argv,"offb_node " ); // ros :: NodeHandle nh; // ros::SeviceClient arming_client // nh.serviceClient < mavros_msgs ;; CommandBool >("mavros / cmd / arming") // mavros_msgs::CommandBool>("mavros/cmd/arming"); // mavros_msgs::CommandBool arm_cmd; // arm_cmd.request.value = true //注意这里是 arm_cmd.request.value ,不是arm_cmd.valuse // arming_client.call (arm.cmd); // 执行完毕以后返回信息在: // arm_cmd.response.success // arm_cmd.response.result // 2. 模式切换 // 消息名称:mavros/set_mode // 类型名称:mavros_msgs::SetMode // 类型所在头文件 : mavros_msgs / SetMode.h // 服务请求参数 // uint8 base_mode //基本参数 如果custom_mode 不为空 此项无效 // string custom_mode // 通常我们使用custom_mode 如果想进入offboard 模式 // 在PX4 中赋值 “OFFBOARD ”,在 APM 中 "GUIDED" // 服务返回的结果: // bool mode _sent // 为true 表示正确切换
26.836735
83
0.656274
Chentao2000
1d1e6155abdf8028b029263938b61bd1013e85bc
6,008
cpp
C++
src/MidiDevice.cpp
patriciogonzalezvivo/MidiRosetta
821d599410d9589e31dea3134659106a312eb8b5
[ "BSD-3-Clause" ]
58
2020-07-07T19:46:31.000Z
2022-03-09T00:46:07.000Z
src/MidiDevice.cpp
patriciogonzalezvivo/MidiRosetta
821d599410d9589e31dea3134659106a312eb8b5
[ "BSD-3-Clause" ]
3
2020-07-31T22:49:16.000Z
2021-03-12T15:08:37.000Z
src/MidiDevice.cpp
patriciogonzalezvivo/MidiRosetta
821d599410d9589e31dea3134659106a312eb8b5
[ "BSD-3-Clause" ]
3
2020-07-31T01:00:51.000Z
2021-03-05T15:52:49.000Z
#include "MidiDevice.h" #include "ops/values.h" #include "ops/strings.h" #include "types/Color.h" #include "types/Vector.h" #include "Context.h" #include <thread> #include <chrono> std::vector<std::string> MidiDevice::getInPorts() { std::vector<std::string> devices; RtMidiIn* midiIn = new RtMidiIn(); unsigned int nPorts = midiIn->getPortCount(); for(unsigned int i = 0; i < nPorts; i++) { std::string name = midiIn->getPortName(i); stringReplace(name, '_'); devices.push_back( name ); } delete midiIn; return devices; } std::vector<std::string> MidiDevice::getOutPorts() { std::vector<std::string> devices; RtMidiOut* midiOut = new RtMidiOut(); unsigned int nPorts = midiOut->getPortCount(); for(unsigned int i = 0; i < nPorts; i++) { std::string name = midiOut->getPortName(i); stringReplace(name, '_'); devices.push_back( name ); } delete midiOut; return devices; } // VIRTUAL PORT MidiDevice::MidiDevice(void* _ctx, const std::string& _name) : m_in(NULL), m_out(NULL), m_tickCounter(0) { m_type = MIDI_DEVICE; m_name = _name; m_ctx = _ctx; m_port = 0; } // REAL PORT MidiDevice::MidiDevice(void* _ctx, const std::string& _name, size_t _port) : m_in(NULL), m_out(NULL), m_tickCounter(0) { m_type = MIDI_DEVICE; m_name = _name; m_ctx = _ctx; m_port = _port; openInPort(_name, _port); openOutPort(_name, _port); } MidiDevice::~MidiDevice() { close(); } bool MidiDevice::openInPort(const std::string& _name, size_t _port) { try { m_in = new RtMidiIn(RtMidi::Api(0), "midigyver"); } catch(RtMidiError &error) { error.printMessage(); return false; } m_in->openPort(_port, _name); m_in->ignoreTypes(false, false, true); m_in->setCallback(onEvent, this); // m_in->setCallback( , this); // midiName = m_in->getPortName(_port); // stringReplace(midiName, '_'); return true; } bool MidiDevice::openOutPort(const std::string& _name, size_t _port) { try { m_out = new RtMidiOut(RtMidi::Api(0), "midigyver"); m_out->openPort(_port, _name); } catch(RtMidiError &error) { error.printMessage(); return false; } return true; } bool MidiDevice::openVirtualOutPort(const std::string& _name) { try { m_out = new RtMidiOut(RtMidi::Api(0), "midigyver" ); m_out->openVirtualPort(_name); } catch(RtMidiError &error) { error.printMessage(); return false; } return true; } bool MidiDevice::close() { if (m_in) { m_in->cancelCallback(); m_in->closePort(); delete m_in; m_in = NULL; } if (m_out) { m_out->closePort(); delete m_out; m_out = NULL; } m_port = 0; m_tickCounter = 0; return true; } void MidiDevice::trigger(const unsigned char _status, unsigned char _channel) { // std::cout << " > " << name << " Status: " << statusByteToName(_status) << " Channel: " << (size_t)_channel << std::endl; std::vector<unsigned char> msg; msg.push_back( _status ); if (_channel > 0 && _channel < 16 ) msg[0] += _channel-1; m_out->sendMessage( &msg ); } void MidiDevice::trigger(const unsigned char _status, unsigned char _channel, size_t _key, size_t _value) { // std::cout << " > " << m_name << " Status: " << statusByteToName(_status) << " Channel: " << (size_t)_channel << " Key: " << _key << " Value:" << _value << std::endl; unsigned char s = _status; if (s == Midi::NOTE_ON && _value == 0) s = Midi::NOTE_OFF; std::vector<unsigned char> msg; msg.push_back( s ); if (s != Midi::TIMING_TICK) { msg.push_back( _key ); msg.push_back( _value ); } if (_channel > 0 && _channel < 16 ) msg[0] += _channel-1; m_out->sendMessage( &msg ); } void MidiDevice::onEvent(double _deltatime, std::vector<unsigned char>* _message, void* _userData) { unsigned int nBytes = 0; try { nBytes = _message->size(); } catch(RtMidiError &error) { error.printMessage(); exit(EXIT_FAILURE); } MidiDevice *device = static_cast<MidiDevice*>(_userData); Context *context = static_cast<Context*>(device->m_ctx); int bytes = 0; unsigned char status = 0; unsigned char channel = 0; Midi::extractHeader(_message, channel, status, bytes); if (bytes < 2) { if (context->doStatusExist(device->getName(), status)) { YAML::Node node = context->getStatusNode(device->getName(), status); size_t target_value = 0; if (status == Midi::TIMING_TICK) { target_value = device->m_tickCounter; device->m_tickCounter++; if (device->m_tickCounter > 127) device->m_tickCounter = 0; } else if (status == Midi::PROGRAM_CHANGE) target_value = _message->at(1); context->configMutex.lock(); context->processEvent(node, device->getName(), status, 0, 0, target_value, true); context->configMutex.unlock(); } } else { size_t key = _message->at(1); size_t target_value = _message->at(2); if (context->doKeyExist(device->getName(), (size_t)channel, key)) { YAML::Node node = context->getKeyNode(device->getName(), (size_t)channel, key); if (node["status"].IsDefined()) { unsigned char target_status = statusNameToByte(node["status"].as<std::string>()); if (target_status != status) return; } context->configMutex.lock(); context->processEvent(node, device->getName(), status, (size_t)channel, key, (float)target_value, false); context->configMutex.unlock(); } } }
25.675214
173
0.582224
patriciogonzalezvivo
1d2371e47f9097b4776dc9bf13143c3d51bd93f1
391
cpp
C++
cpp/container_map_size.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/container_map_size.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/container_map_size.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
/* g++ --std=c++20 -pthread -o ../_build/cpp/container_map_size.exe ./cpp/container_map_size.cpp && (cd ../_build/cpp/;./container_map_size.exe) https://en.cppreference.com/w/cpp/container/map/size */ #include <map> #include <iostream> int main() { std::map<int,char> nums {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}}; std::cout << "nums contains " << nums.size() << " elements.\n"; }
30.076923
141
0.603581
rpuntaie
1d240a9e20bdc896e0a9b58a6d295b031e349841
2,310
hpp
C++
redemption/src/acl/license_api.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/src/acl/license_api.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/src/acl/license_api.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Product name: redemption, a FLOSS RDP proxy Copyright (C) Wallix 2017 Author(s): Christophe Grosjean, Raphael Zhou */ #pragma once #include "utils/sugar/bytes_view.hpp" #include "utils/sugar/noncopyable.hpp" struct LicenseApi : noncopyable { virtual ~LicenseApi() = default; // The functions shall return empty bytes_view to indicate the error. virtual bytes_view get_license(char const* client_name, uint32_t version, char const* scope, char const* company_name, char const* product_id, writable_bytes_view out, bool enable_log) = 0; virtual bool put_license(char const* client_name, uint32_t version, char const* scope, char const* company_name, char const* product_id, bytes_view in, bool enable_log) = 0; }; struct NullLicenseStore : LicenseApi { bytes_view get_license(char const* client_name, uint32_t version, char const* scope, char const* company_name, char const* product_id, writable_bytes_view out, bool enable_log) override { (void)client_name; (void)version; (void)scope; (void)company_name; (void)product_id; (void)enable_log; return bytes_view(out.data(), 0); } bool put_license(char const* client_name, uint32_t version, char const* scope, char const* company_name, char const* product_id, bytes_view in, bool enable_log) override { (void)client_name; (void)version; (void)scope; (void)company_name; (void)product_id; (void)in; (void)enable_log; return false; } };
34.477612
122
0.69697
DianaAssistant
918e4c89682e9fa1fa47324ffe0082c9e49a1df8
1,361
hpp
C++
library/ATF/CRecallRequest.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/CRecallRequest.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/CRecallRequest.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CCharacter.hpp> #include <CPlayer.hpp> #include <CUnmannedTraderSchedule.hpp> START_ATF_NAMESPACE #pragma pack(push, 8) struct CRecallRequest { typedef CUnmannedTraderSchedule::STATE STATE; unsigned __int16 m_usID; STATE m_eState; CPlayer *m_pkOwner; unsigned int m_dwOwnerSerial; CPlayer *m_pkDest; unsigned int m_dwDestSerial; unsigned int m_dwCloseTime; bool m_bRecallParty; bool m_bStone; bool m_bBattleModeUse; public: CRecallRequest(uint16_t usID); void ctor_CRecallRequest(uint16_t usID); void Clear(); void Close(bool bDone); uint16_t GetID(); struct CPlayer* GetOwner(); bool IsBattleModeUse(); bool IsClose(); bool IsRecallAfterStoneState(); bool IsRecallParty(); bool IsTimeOut(); bool IsWait(); char Recall(struct CPlayer* pkDest, bool bStone); char Regist(struct CPlayer* pkObj, struct CCharacter* pkDest, bool bRecallParty, bool bStone, bool bBattleModeUse); ~CRecallRequest(); void dtor_CRecallRequest(); }; #pragma pack(pop) END_ATF_NAMESPACE
30.244444
123
0.65687
lemkova
91964fb0f5136f1d987aa2332dff2f6bd5b81bb3
6,804
cpp
C++
software/motion_estimate/state_sync/src/test_tools/body_to_local_rotations.cpp
liangfok/oh-distro
eeee1d832164adce667e56667dafc64a8d7b8cee
[ "BSD-3-Clause" ]
92
2016-01-14T21:03:50.000Z
2021-12-01T17:57:46.000Z
software/motion_estimate/state_sync/src/test_tools/body_to_local_rotations.cpp
liangfok/oh-distro
eeee1d832164adce667e56667dafc64a8d7b8cee
[ "BSD-3-Clause" ]
62
2016-01-16T18:08:14.000Z
2016-03-24T15:16:28.000Z
software/motion_estimate/state_sync/src/test_tools/body_to_local_rotations.cpp
liangfok/oh-distro
eeee1d832164adce667e56667dafc64a8d7b8cee
[ "BSD-3-Clause" ]
41
2016-01-14T21:26:58.000Z
2022-03-28T03:10:39.000Z
#include <boost/shared_ptr.hpp> #include <lcm/lcm-cpp.hpp> #include <path_util/path_util.h> #include <lcmtypes/bot_core.hpp> #include <bot_param/param_client.h> #include <bot_param/param_util.h> #include <lcmtypes/bot_core/pose_t.hpp> #include <bot_frames_cpp/bot_frames_cpp.hpp> #include <ConciseArgs> //////////////////////////////////////// struct CommandLineConfig { int mode; }; class App{ public: App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& ca_cfg_); ~App(){ } void sendUpdate(); private: boost::shared_ptr<lcm::LCM> lcm_; const CommandLineConfig& ca_cfg_; void pbdih(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pose_t* msg); BotParam* botparam_; BotFrames* botframes_; bot::frames* botframes_cpp_; int counter_; // used for terminal feedback int verbose_; }; App::App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& ca_cfg_): lcm_(lcm_), ca_cfg_(ca_cfg_){ counter_ =0; verbose_=3; // 1 important, 2 useful 3, lots if (ca_cfg_.mode ==0){ std::cout << "POSE_BDI local_linear_rate_to_body_linear_rate\n"; lcm_->subscribe("POSE_BDI",&App::pbdih,this); }else if(ca_cfg_.mode ==1){ std::cout << "POSE_BODY body_linear_rate_to_local_linear_rate\n"; lcm_->subscribe("POSE_BODY",&App::pbdih,this); } } void App::sendUpdate(){ std::cout << "Updating\n"; double c= M_PI/180; double rpy[3] = {c*0.,c*10.,c*10.}; double q[4]; bot_roll_pitch_yaw_to_quat (rpy, q); double vel[3] = {1.,0., 0.}; std::cout << "befor: " << vel[0] << " " << vel[1] << " " << vel[2] << "\n"; bot_quat_rotate(q, vel); std::cout << "after: " << vel[0] << " " << vel[1] << " " << vel[2] << "\n"; } void local_linear_rate_to_body_linear_rate(const BotTrans *pose, const double lin_vel[3], double body_vel[3]){ BotTrans bt; memset(&bt, 0, sizeof(bt)); /// didn't assign the position memcpy(bt.rot_quat,pose->rot_quat, 4*sizeof(double)); bot_trans_invert(&bt); //std::cout << "lbefor: " << lin_vel[0] << " " << lin_vel[1] << " " << lin_vel[2] << "\n"; //bot_quat_rotate(q, vel); // dont use bot_trans_apply_vec(&bt, lin_vel, body_vel); // bot_quat_rotate_to(pose->rot_quat, lin_vel, body_vel); // not right //std::cout << "lafter: " << body_vel[0] << " " << body_vel[1] << " " << body_vel[2] << "\n"; } void body_linear_rate_to_local_linear_rate(const BotTrans *pose, const double body_vel[3], double lin_vel[3]){ BotTrans bt; memset(&bt, 0, sizeof(bt)); /// didn't assign the position memcpy(bt.rot_quat,pose->rot_quat, 4*sizeof(double)); //std::cout << "lbefor: " << body_vel[0] << " " << body_vel[1] << " " << body_vel[2] << "\n"; bot_trans_apply_vec(&bt, body_vel, lin_vel); //std::cout << "lafter: " << lin_vel[0] << " " << lin_vel[1] << " " << lin_vel[2] << "\n"; } // Currently: // BDI: linear velocity doesn't need to be converted, angular needs to go from body to linear // MIT: linear velocity needs to go from body to linear, angular needs to go from body to linear void App::pbdih(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pose_t* msg){ std::cout << "\n" << msg->utime << "\n"; bot_core::pose_t m = *msg; BotTrans pose; memset(&pose, 0, sizeof(pose)); memcpy(pose.rot_quat,msg->orientation, 4*sizeof(double)); memcpy(pose.trans_vec,msg->pos, 3*sizeof(double)); // bot_trans_invert(&bt); if (ca_cfg_.mode == 0){ // Conversion from local_linear_rate_to_body_linear_rate // libbot version double lin_vel[3]; double body_vel[3]; memcpy(lin_vel,msg->vel, 3*sizeof(double)); local_linear_rate_to_body_linear_rate(&pose, lin_vel, body_vel) ; //std::cout << m.vel[0] << " " << m.vel[1] << " " << m.vel[2] << " body_vel (libbot)\n"; //memcpy(m.vel, body_vel, 3*sizeof(double)); Eigen::Matrix3d R = Eigen::Matrix3d( Eigen::Quaterniond( msg->orientation[0], msg->orientation[1], msg->orientation[2],msg->orientation[3] )); Eigen::Vector3d body_vel_E = R.inverse()*Eigen::Vector3d ( msg->vel[0], msg->vel[1], msg->vel[2]); //std::cout << body_vel_E.transpose() << " body_vel (eigen)\n"; memcpy(m.vel, body_vel_E.data(), 3*sizeof(double)); // NB: angular rate is all ready in body frame // both are now in body frame }else if (ca_cfg_.mode == 1){ // Conversion from body_linear_rate_to_local_linear_rate // libbot version double lin_vel[3]; double body_vel[3]; memcpy(body_vel,msg->vel, 3*sizeof(double)); body_linear_rate_to_local_linear_rate(&pose, body_vel, lin_vel) ; //std::cout << m.vel[0] << " " << m.vel[1] << " " << m.vel[2] << " lin_vel (libbot)\n"; //memcpy(m.vel, lin_vel, 3*sizeof(double)); Eigen::Matrix3d R = Eigen::Matrix3d( Eigen::Quaterniond( msg->orientation[0], msg->orientation[1], msg->orientation[2],msg->orientation[3] )); Eigen::Vector3d lin_vel_E = R*Eigen::Vector3d ( msg->vel[0], msg->vel[1], msg->vel[2]); memcpy(m.vel, lin_vel_E.data(), 3*sizeof(double)); //std::cout << body_vel_E.transpose() << " lin_vel (eigen)\n"; Eigen::Vector3d rot_vel_E = R*Eigen::Vector3d ( msg->rotation_rate[0], msg->rotation_rate[1], msg->rotation_rate[2]); memcpy(m.rotation_rate, rot_vel_E.data(), 3*sizeof(double)); // Both are now in local frame }else if (ca_cfg_.mode == 2){ // NB: linear rate is all realy in local frame Eigen::Matrix3d R = Eigen::Matrix3d( Eigen::Quaterniond( msg->orientation[0], msg->orientation[1], msg->orientation[2],msg->orientation[3] )); Eigen::Vector3d rot_vel_E = R*Eigen::Vector3d ( msg->rotation_rate[0], msg->rotation_rate[1], msg->rotation_rate[2]); memcpy(m.rotation_rate, rot_vel_E.data(), 3*sizeof(double)); // Both are now in local frame } double rotr[3]; memcpy(rotr, m.rotation_rate, 3*sizeof(double)); std::cout << "rbefor: " << rotr[0] << " " << rotr[1] << " " << rotr[2] << "\n"; // bot_quat_rotate(q, rotr); //bot_trans_apply_vec(&bt, msg->rotation_rate, rotr); std::cout << "rafter: " << rotr[0] << " " << rotr[1] << " " << rotr[2] << "\n"; memcpy(m.rotation_rate, rotr, 3*sizeof(double)); lcm_->publish("POSE_VICON", &m); } int main(int argc, char ** argv) { CommandLineConfig ca_cfg; ca_cfg.mode = 0; ConciseArgs opt(argc, (char**)argv); opt.add(ca_cfg.mode , "m", "type","Mode: 0 spit params. 1 push"); opt.parse(); boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM); if(!lcm->good()){ std::cerr <<"ERROR: lcm is not good()" <<std::endl; } App accu(lcm, ca_cfg); while(0 == lcm->handle()); return 0; }
30.927273
146
0.618019
liangfok
919fbd6e647511321d8ba925e23bfa04047ea51d
132
cpp
C++
spoj/test.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
spoj/test.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
spoj/test.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int n; while(scanf("%d",&n) && n!=42)printf("%d\n",n); return 0; }
13.2
48
0.568182
Shisir
91a1a16f9e4ff73019dab4dc11692cd1228714f1
1,579
cpp
C++
codebook/code/String/Suffix_Array.cpp
NCTU-PCCA/NCTU_Yggdrasill
4f086c9737502f69044f574514cf191d536aaf22
[ "MIT" ]
null
null
null
codebook/code/String/Suffix_Array.cpp
NCTU-PCCA/NCTU_Yggdrasill
4f086c9737502f69044f574514cf191d536aaf22
[ "MIT" ]
null
null
null
codebook/code/String/Suffix_Array.cpp
NCTU-PCCA/NCTU_Yggdrasill
4f086c9737502f69044f574514cf191d536aaf22
[ "MIT" ]
null
null
null
//should initialize s and n first #define N 301000 using namespace std; char s[N]; //string=s,suffix array=sar,longest common prefix=lcp int rk[2][N],id[2][N]; int n,p; int cnt[N]; int len[N],od[N],sar[N]; inline int sr(int i,int t){ //rank of shifted position return i+t<n?rk[p][i+t]:-1; } inline bool check_same(int i,int j,int t){ return rk[p][i]==rk[p][j]&&sr(i,t)==sr(j,t); } bool cmp(int i,int j){ return s[i]<s[j]; } void sa(){ //length of array s int i,t,now,pre; memset(cnt,0,sizeof(cnt)); for(i=0;i<n;i++){ id[p][i]=i; rk[p][i]=s[i]; cnt[s[i]]++; } for(i=1;i<128;i++) cnt[i]+=cnt[i-1]; sort(id[p],id[p]+n,cmp); for(t=1;t<n;t<<=1){ //least significant bit is already sorted for(i=n-1;i>=0;i--){ now=id[p][i]-t; if(now>=0) id[p^1][--cnt[rk[p][now]]]=now; } for(i=n-t;i<n;i++){ id[p^1][--cnt[rk[p][i]]]=i; } memset(cnt,0,sizeof(cnt)); now=id[p^1][0]; rk[p^1][now]=0; cnt[0]++; for(i=1;i<n;i++){ pre=now; now=id[p^1][i]; if(check_same(pre,now,t)){ rk[p^1][now]=rk[p^1][pre]; } else{ rk[p^1][now]=rk[p^1][pre]+1; } cnt[rk[p^1][now]]++; } p^=1; if(rk[p][now]==n-1) break; for(i=1;i<n;i++) cnt[i]+=cnt[i-1]; } memcpy(sar,id[p],sizeof(sar)); } void lcp(){ int i,l,pre; for(i=0;i<n;i++) od[sar[i]]=i; for(i=0;i<n;i++){ if(i) l=len[od[i-1]]?len[od[i-1]]-1:0; else l=0; if(od[i]){ pre=sar[od[i]-1]; while(pre+l<n&&i+l<n&&s[pre+l]==s[i+l]) l++; len[od[i]]=l; } else len[0]=0; } }
21.930556
64
0.494617
NCTU-PCCA
91a267943b9ce38acb16e9b0f58157e667f324af
9,517
cpp
C++
src/utilities/binary_converter.cpp
theazgra/AzgraCppLibrary
ccc9ff75731d456882a72343bd53bd8e4c38b9e7
[ "BSL-1.0" ]
3
2019-09-17T17:54:33.000Z
2020-01-09T05:06:44.000Z
src/utilities/binary_converter.cpp
theazgra/AzgraCppLibrary
ccc9ff75731d456882a72343bd53bd8e4c38b9e7
[ "BSL-1.0" ]
1
2019-09-18T17:01:54.000Z
2019-09-20T16:52:01.000Z
src/utilities/binary_converter.cpp
theazgra/AzgraCppLibrary
ccc9ff75731d456882a72343bd53bd8e4c38b9e7
[ "BSL-1.0" ]
null
null
null
#include <azgra/utilities/binary_converter.h> namespace azgra { azgra::i16 bytes_to_i16(const ByteArray &bytes, const azgra::u64 fromIndex) { always_assert(bytes.size() >= sizeof(azgra::i16)); always_assert(fromIndex <= bytes.size() - sizeof(azgra::i16)); #ifdef AZGRA_LITTLE_ENDIAN auto bit = &bytes[fromIndex]; if (fromIndex % 2 == sizeof(azgra::i16)) { return (*((azgra::i16 *) bit)); } else { return (azgra::i16) ((*bit) | (*(bit + 1) << 8)); } #else const byte *bytePtr = &bytes[fromIndex]; return (azgra::i16) ((*(bytePtr + 1)) | ((*bytePtr) << 8)); #endif } azgra::i32 bytes_to_i32(const ByteArray &bytes, const azgra::u64 fromIndex) { always_assert(bytes.size() >= sizeof(azgra::i32)); always_assert(fromIndex <= bytes.size() - sizeof(azgra::i32)); #ifdef AZGRA_LITTLE_ENDIAN auto bit = &bytes[fromIndex]; if (fromIndex % sizeof(azgra::i32) == 0) { return (*((azgra::i32 *) bit)); } else { return (*bit | (*(bit + 1) << 8) | (*(bit + 2) << 16) | (*(bit + 3) << 24)); } #else const byte *bytePtr = &bytes[fromIndex]; return (((*bytePtr) << 24) | ((*(bytePtr + 1)) << 16) | ((*(bytePtr + 2)) << 8) | (*(bytePtr + 3))); #endif } azgra::i64 bytes_to_i64(const ByteArray &bytes, const azgra::u64 fromIndex) { always_assert(bytes.size() >= sizeof(azgra::i64)); always_assert(fromIndex <= bytes.size() - sizeof(azgra::i64)); // Little endian auto bit = &bytes[fromIndex]; if (fromIndex % sizeof(azgra::i64) == 0) { return (*((azgra::i64 *) bit)); } else { azgra::i32 i1 = (*bit) | (*(bit + 1) << 8) | (*(bit + 2) << 16) | (*(bit + 3) << 24); azgra::i32 i2 = (*(bit + 4)) | (*(bit + 5) << 8) | (*(bit + 6) << 16) | (*(bit + 7) << 24); return ((azgra::u32) i1 | ((azgra::i64) i2 << 32)); } } float bytes_to_float(const ByteArray &bytes, const azgra::u64 fromIndex) { always_assert(bytes.size() >= sizeof(float)); always_assert(fromIndex <= bytes.size() - sizeof(float)); float result; memcpy(&result, (bytes.data() + fromIndex), sizeof(float)); return result; } double bytes_to_double(const ByteArray &bytes, const azgra::u64 fromIndex) { always_assert(bytes.size() >= sizeof(double)); always_assert(fromIndex <= bytes.size() - sizeof(double)); double result; memcpy(&result, (bytes.data() + fromIndex), sizeof(double)); return result; } azgra::u16 bytes_to_u16(const ByteArray &bytes, const azgra::u64 fromIndex) { return ((azgra::u16) bytes_to_i16(bytes, fromIndex)); } azgra::u32 bytes_to_u32(const ByteArray &bytes, const azgra::u64 fromIndex) { return ((azgra::u32) bytes_to_i32(bytes, fromIndex)); } azgra::u64 bytes_to_u64(const ByteArray &bytes, const azgra::u64 fromIndex) { return ((azgra::u64) bytes_to_i64(bytes, fromIndex)); } std::string utf8bytes_to_string(const ByteArray &bytes) { return utf8bytes_to_string(bytes, 0, bytes.size()); } std::string utf8bytes_to_string(const ByteArray &bytes, const azgra::u64 fromIndex, const azgra::u32 byteCount) { if (bytes.size() == 0) return ""; auto fromIt = bytes.begin() + fromIndex; ByteArray stringBytes(fromIt, fromIt + byteCount); std::string result = boost::locale::conv::from_utf<char>((char *) stringBytes.data(), "UTF-8"); return result; } // Convert string to bytes. ByteArray string_to_bytes(const std::string &text) { ByteArray bytes(text.length()); const char *textPtr = text.data(); for (size_t i = 0; i < text.length(); i++) { bytes[i] = *(textPtr + i); } return bytes; } ByteArray string_to_bytes_null_terminated(const std::string &text) { size_t len = text.length(); ByteArray bytes(len); const char *textPtr = text.data(); for (size_t i = 0; i < len; i++) { bytes[i] = *(textPtr + i); if (i == (len - 1) && (bytes[i] != 0)) { bytes.resize(len + 1); bytes[len] = 0; } } return bytes; } ByteArray short16_to_bytes(const azgra::i16 &value) { ByteArray shortBytes(sizeof(azgra::i16)); std::memcpy(shortBytes.data(), &value, sizeof(azgra::i16)); return shortBytes; } ByteArray ushort16_to_bytes(const azgra::u16 &value) { ByteArray ushortBytes(sizeof(azgra::u16)); std::memcpy(ushortBytes.data(), &value, sizeof(azgra::u16)); return ushortBytes; } ByteArray int32_to_bytes(const azgra::i32 &value) { ByteArray intBytes(sizeof(azgra::i32)); std::memcpy(intBytes.data(), &value, sizeof(azgra::i32)); return intBytes; } ByteArray uint32_to_bytes(const azgra::u32 &value) { ByteArray uintBytes(sizeof(azgra::u32)); std::memcpy(uintBytes.data(), &value, sizeof(azgra::u32)); return uintBytes; } ByteArray long64_to_bytes(const azgra::i64 &value) { ByteArray longBytes(sizeof(azgra::i64)); std::memcpy(longBytes.data(), &value, sizeof(azgra::i64)); return longBytes; } ByteArray ulong64_to_bytes(const azgra::u64 &value) { ByteArray ulongBytes(sizeof(azgra::u64)); std::memcpy(ulongBytes.data(), &value, sizeof(azgra::u64)); return ulongBytes; } ByteArray float_to_bytes(const float &value) { ByteArray floatBytes(sizeof(float)); std::memcpy(floatBytes.data(), &value, sizeof(float)); return floatBytes; } ByteArray double_to_bytes(const double &value) { ByteArray doubleBytes(sizeof(double)); std::memcpy(doubleBytes.data(), &value, sizeof(double)); return doubleBytes; } void int32_to_bytes(const azgra::i32 &i, ByteArray &buffer, size_t bufferPosition) { always_assert(buffer.size() - bufferPosition >= sizeof(azgra::i32)); std::memcpy((buffer.data() + bufferPosition), &i, sizeof(azgra::i32)); } void ushort16_to_bytes(const azgra::u16 &x, ByteArray &buffer, size_t bufferPosition) { always_assert(buffer.size() - bufferPosition >= sizeof(azgra::u16)); std::memcpy((buffer.data() + bufferPosition), &x, sizeof(azgra::u16)); } std::vector<azgra::i16> bytes_to_short_array(const ByteArray &data) { std::vector<azgra::i16> result(data.size() / sizeof(azgra::i16)); std::memcpy(result.data(), data.data(), data.size()); return result; } std::vector<azgra::u16> bytes_to_ushort_array(const ByteArray &data) { std::vector<azgra::u16> result(data.size() / sizeof(azgra::u16)); std::memcpy(result.data(), data.data(), data.size()); return result; } std::vector<azgra::i32> bytes_to_int_array(const ByteArray &data) { std::vector<azgra::i32> result(data.size() / sizeof(azgra::i32)); std::memcpy(result.data(), data.data(), data.size()); return result; } std::vector<azgra::u32> bytes_to_uint_array(const ByteArray &data) { std::vector<azgra::u32> result(data.size() / sizeof(azgra::u32)); std::memcpy(result.data(), data.data(), data.size()); return result; } std::vector<azgra::i64> bytes_to_long_array(const ByteArray &data) { std::vector<azgra::i64> result(data.size() / sizeof(azgra::i64)); std::memcpy(result.data(), data.data(), data.size()); return result; } std::vector<azgra::u64> bytes_to_ulong_array(const ByteArray &data) { std::vector<azgra::u64> result(data.size() / sizeof(azgra::u64)); std::memcpy(result.data(), data.data(), data.size()); return result; } std::vector<azgra::f32> bytes_to_float_array(const ByteArray &data) { std::vector<azgra::f32> result(data.size() / sizeof(azgra::f32)); std::memcpy(result.data(), data.data(), data.size()); return result; } std::vector<azgra::f64> bytes_to_double_array(const ByteArray &data) { std::vector<azgra::f64> result(data.size() / sizeof(azgra::f64)); std::memcpy(result.data(), data.data(), data.size()); return result; } ByteArray int_array_to_bytes(const std::vector<azgra::i32> &data) { ByteArray result; result.resize(data.size() * sizeof(azgra::i32)); std::memcpy(result.data(), data.data(), sizeof(azgra::i32) * data.size()); return result; } ByteArray uint_array_to_bytes(const std::vector<azgra::u32> &data) { ByteArray result; result.resize(data.size() * sizeof(azgra::u32)); std::memcpy(result.data(), data.data(), sizeof(azgra::u32) * data.size()); return result; } ByteArray ushort_array_to_bytes(const std::vector<azgra::u16> &data) { ByteArray result; result.resize(data.size() * sizeof(azgra::u16)); std::memcpy(result.data(), data.data(), sizeof(azgra::u16) * data.size()); return result; } } // namespace azgra
32.152027
115
0.577388
theazgra
91a3d0a576955b145efac47137e5976f3a2eb01a
5,305
cpp
C++
learningC++/learningHandleClass.cpp
QiJunHu/newToCpp
02988845fdb2e818608d4362e0d4ca0e91818509
[ "MIT" ]
2
2015-12-03T15:05:52.000Z
2019-05-12T16:08:26.000Z
learningC++/learningHandleClass.cpp
QiJunHu/learningRecord
02988845fdb2e818608d4362e0d4ca0e91818509
[ "MIT" ]
null
null
null
learningC++/learningHandleClass.cpp
QiJunHu/learningRecord
02988845fdb2e818608d4362e0d4ca0e91818509
[ "MIT" ]
null
null
null
#include <iostream> #include <iterator> #include <algorithm> #include <fstream> #include <list> #include <string> #include <vector> #include <set> #include<utility> #include<functional> #include<stdexcept> //base class class Item_base { friend std::ostream& operator<<(std::ostream &, Item_base &); public: Item_base(const std::string& book="",double sale_price=0.0):isbn(book),price(sale_price) {} std::string book() const { return isbn;} virtual Item_base* clone() const { return new Item_base(*this); } virtual double net_price(std::size_t n) const { return price*n; } //debug function controlled by flag parameter virtual void debug1(bool flag) const { if(flag) std::cout<<"ISBN: "<<isbn<<std::endl <<"Price: "<<price<<std::endl; } //debug function controlled by flag member virtual void debug2() const { if(flag) std::cout<<"ISBN: "<<isbn<<std::endl <<"Price: "<<price<<std::endl; } virtual ~Item_base() {} protected: double price; // price of a book bool flag; private: std::string isbn; // isbn of a book }; std::ostream& operator<<(std::ostream & os,Item_base& ib) { os<<"\tUsing operator<<(std::ostream &,Item_base&);"<<std::endl <<"\tVisit Item_base's book():\t"<<ib.isbn<<std::endl <<"\tVisit Item_base's net_price():" <<"3 "<<ib.book()<<" , the price is:\t" <<ib.net_price(3)<<std::endl; return os; } //derived class class Bult_Item :public Item_base { friend std::ostream & operator<<(std::ostream & ,Bult_Item &); public: Bult_Item(const std::string& book="",double sale_price=0.0,std::size_t qty=0,double disc=0.0):Item_base(book,sale_price),min_qty(qty),discount(disc) {} Bult_Item* clone() const { return new Bult_Item(*this); } double net_price(std::size_t cnt) const { if(cnt > min_qty) return cnt*(1-discount)*price; } void debug1(bool flag) const { if(flag) std::cout<<"ISBN: "<<book()<<std::endl <<"PriceL "<<price<<std::endl <<"Min_quantiry: "<<min_qty<<std::endl <<"Discount Rate: "<<discount<<std::endl; } void debug2() const { if(flag) std::cout<<"ISBN: "<<book()<<std::endl <<"PriceL "<<price<<std::endl <<"Min_quantiry: "<<min_qty<<std::endl <<"Discount Rate: "<<discount<<std::endl; } ~Bult_Item() {} private: std::size_t min_qty; // min quantity of books to have a discount double discount; //discount rate }; std::ostream & operator<<(std::ostream & os,Bult_Item & bi) { os<<"\tUsing operator<<(std::ostream &,Bulk_Item);"<<std::endl <<"\tVisit Item_base's book():\t"<<bi.book()<<std::endl <<"\tVisit Item_base's net_price():" <<"5 "<<bi.book()<<" , the price is:\t" <<bi.net_price(5)<<std::endl; return os; } //handle class class Sales_item { public: //default constructor:unbound handle Sales_item():p(0),use( new std::size_t(1)) {} //attaches a handle to copy of the Item_base object Sales_item(const Item_base & item):p(item.clone()),use(new std::size_t(1)) {} //copy control members to manage the use count and pointers Sales_item(const Sales_item & i):p(i.p),use(i.use) { ++ use; } Sales_item& operator=(const Sales_item&); ~Sales_item() { decr_use();} const Item_base* operator->() const { if(p) return p; else throw std::logic_error("unbound Sales_item"); } const Item_base operator*() const { if(p) return *p; else throw std::logic_error("unbound Sales_item"); } private: Item_base *p; //pointer to shared item std::size_t * use ; // pointer to a shared use count( reference count); void decr_use() { if(--*use == 0) { delete p; delete use; } } }; Sales_item& Sales_item::operator=(const Sales_item& rhs) { ++*rhs.use; decr_use(); p = rhs.p; use = rhs.use; return * this; } //compare function of Sales_Item for multiset to use inline bool compare(const Sales_item& rh1,const Sales_item& rh2) { return rh1->book() < rh2->book() ; } //really class used in real business class Basket { typedef bool (*Comp) (const Sales_item&,const Sales_item&); public: typedef std::multiset<Sales_item,Comp> set_type; typedef set_type::size_type size_type; typedef set_type::const_iterator const_iter; //constructor Basket():items(compare) {} void add_item(const Sales_item& item) { items.insert(item); } size_type size(const Sales_item& i) const { return items.count(i); } double total() const; private: std::multiset<Sales_item,Comp> items; }; double Basket::total() const { double sum = 0.0; for(const_iter i = items.begin() ; i != items.end() ; i = items.upper_bound(*i)) { sum += (*i)->net_price(items.count(*i)); } return sum; } //test code int main() { return 0; }
20.248092
155
0.575683
QiJunHu
91a4ed386201c055146a349fe21c642a1626386d
1,466
cpp
C++
Pixel-Engine/src/bindings/python/entities/py_Background.cpp
MohomedShalik/Pixel-Engine
d64d54e7ed9341bb3577bb7e33057baffe9ec2f2
[ "Apache-2.0" ]
11
2020-08-23T17:36:40.000Z
2021-08-24T09:42:50.000Z
Pixel-Engine/src/bindings/python/entities/py_Background.cpp
MohomedShalik/Pixel-Engine
d64d54e7ed9341bb3577bb7e33057baffe9ec2f2
[ "Apache-2.0" ]
1
2020-08-24T06:56:46.000Z
2020-08-24T13:56:14.000Z
Pixel-Engine/src/bindings/python/entities/py_Background.cpp
MohomedShalik/Pixel-Engine
d64d54e7ed9341bb3577bb7e33057baffe9ec2f2
[ "Apache-2.0" ]
3
2019-12-09T13:03:22.000Z
2020-04-08T06:00:53.000Z
#include "pch.h" #include "entities.h" #include "api/entities/Background.h" #include "api/Assets.h" void register_bg(py::module& m) { py::class_<pe::Background, sf::Drawable, sf::Transformable, pe::Asset >(m, "Background") .def(py::init<>()) .def(py::init<py::str>()) .def_static("new", []() { return pe::Assets::newAsset<pe::Background>(); }, py::return_value_policy::reference) .def_static("new", [](const std::string& name) { return pe::Assets::newAsset<pe::Background>(name); }, py::return_value_policy::reference) .def_static("getCount", []() {return pe::Background::getCount(); }) .def("setTexture", &pe::Background::setTexture) .def("setVisible", &pe::Background::setVisible) .def("setRepeated", &pe::Background::setRepeated) .def("setSmooth", &pe::Background::setSmooth) .def("setMoveSpeed", (void(pe::Background::*)(int, int)) &pe::Background::setMoveSpeed) .def("setMoveSpeed", (void(pe::Background::*)(const sf::Vector2i& speed)) &pe::Background::setMoveSpeed) .def("getName", &pe::Background::getName, py::return_value_policy::reference) .def("isVisible", &pe::Background::isVisible) .def("isRepeat", &pe::Background::isRepeat) .def("isSmooth", &pe::Background::isSmooth) .def("getTexture", [](pe::Background& self) -> pe::Texture* { if (!self.hasTexture()) return nullptr; return &self.getTexture(); }, py::return_value_policy::reference ) .def("getMoveSpeed", &pe::Background::getMoveSpeed) ; }
40.722222
140
0.674625
MohomedShalik
91a822d823c791ce476239a7452682235efa7c66
15,800
cxx
C++
StRoot/StFgtPool/StFgtQaMakers/StFgtCosmicTrackQA.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StFgtPool/StFgtQaMakers/StFgtCosmicTrackQA.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StFgtPool/StFgtQaMakers/StFgtCosmicTrackQA.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
/*************************************************************************** * * $Id: StFgtCosmicTrackQA.cxx,v 1.2 2012/01/31 16:48:34 wwitzke Exp $ * Author: C. K. Riley (ckriley@bnl.gov), Oct. 18 2011 * *************************************************************************** * * Description: Plotting class for different histograms concerning * cosmicstand tracks * *************************************************************************** * * $Log: StFgtCosmicTrackQA.cxx,v $ * Revision 1.2 2012/01/31 16:48:34 wwitzke * Changed for cosmic test stand. * * Revision 1.1 2012/01/31 09:26:16 sgliske * StFgtQaMakers moved to StFgtPool * * Revision 1.11 2012/01/30 10:42:23 sgliske * strip containers now contain adc values for * all time bins. Also fixed bug where setType modified the timebin * rather than the type. * * Revision 1.10 2012/01/26 13:13:11 sgliske * Updated to use StFgtConsts, which * replaces StFgtEnums and StFgtGeomDefs * * Revision 1.9 2011/12/07 17:19:59 ckriley * minor update * * Revision 1.8 2011/11/25 20:20:04 ckriley * added statusmaker functionality * * Revision 1.7 2011/11/09 21:03:20 ckriley * working version with current containers * * Revision 1.6 2011/11/01 19:07:24 sgliske * Updated to correspond with StEvent containers, take 2. * * Revision 1.4 2011/10/26 20:39:18 ckriley * compilation fix * * Revision 1.3 2011/10/25 20:43:32 ckriley * added more plots * * Revision 1.2 2011/10/25 15:42:45 ckriley * minor change * * Revision 1.1 2011/10/25 15:41:53 ckriley * creation of StFgtCosmicTrackQA * **************************************************************************/ #include "StFgtCosmicTrackQA.h" #include <string> #include <TH1F.h> #include <TH2F.h> #include <TProfile.h> #include <TROOT.h> #include <TStyle.h> #include <TCanvas.h> #include "StMaker.h" #include "StRoot/StFgtUtil/geometry/StFgtGeom.h" #include "StRoot/StFgtPool/StFgtCosmicTestStandGeom/StFgtCosmicTestStandGeom.h" #include "StRoot/StEvent/StFgtCollection.h" #include "StRoot/StEvent/StFgtHit.h" #include "StRoot/StEvent/StFgtPoint.h" // constructors StFgtCosmicTrackQA::StFgtCosmicTrackQA( const Char_t* name, Short_t discId, Short_t quadId, const Char_t* quadName ) : StFgtQaMaker( name, discId, quadId, quadName ), mPath(""), mFileNameBase(""), mFileNameKey( quadName )/*,mHist(0)*/{ // set the style to plain gROOT->SetStyle("Plain"); // few defaults mXbins = 1280; mXmin = 0; mXmax = mXbins; mYbins = 4096; mYmin = 0; mYmax = mYbins; }; StFgtCosmicTrackQA::StFgtCosmicTrackQA(const StFgtCosmicTrackQA&){ std::cerr << "TODO" << endl; throw 0; }; // deconstructor StFgtCosmicTrackQA::~StFgtCosmicTrackQA(){ /* if( mHistAPV ) { for( Int_t i=0;i<10;i++) { delete mHistAPV[i]; } } if( mHist1Dcluster ) { for( Int_t i=0;i<2;i++) { delete mHist1Dcluster[i]; } } if( mHist1Dclusters ) delete mHist1Dclusters; if( mHist2Dpoint ) delete mHist2Dpoint; */ }; // equals operator StFgtCosmicTrackQA& StFgtCosmicTrackQA::operator=(const StFgtCosmicTrackQA&){ std::cerr << "TODO" << endl; throw 0; }; // initializing CosmicTrackQA Int_t StFgtCosmicTrackQA::Init(){ Int_t ierr = StFgtQaMaker::Init(); if( !ierr ){ /* // Take care of the histogram if( mHistAPV ) { for( Int_t i=0;i<10;i++) { delete mHistAPV[i]; } } if( mHist1Dcluster ) { for( Int_t i=0;i<2;i++) { delete mHist1Dcluster[i]; } } if( mHist1Dclusters ) delete mHist1Dclusters; if( mHist2Dpoint ) delete mHist2Dpoint; */ // note: 10 APV chips plots per Quadrant // naming the APV plots std::string name, nameforhist, title; { std::stringstream ss; ss << GetName() << "_" << mDiscId << "_" << mQuadId; ss >> name; }; // APV chip binning // regular mXmin = -200; mXmax = 500; mXbins = 140; /* // 5sigma mXmin = 0; mXmax = 4000; mXbins = 200; */ string channelId[10]={"0-127","128-255","256-383","384-511","512-639","640-767","768-895","896-1023","1024-1151","1152-1279"}; // easiest way to ensure stream is cleared is construct a new one for(int i=0;i<10;i++) { std::stringstream sx, sy, ss, sn, snx, sny; ss << " Quad " << mQuadName << ", APV " << i << ", Channels " << channelId[i] << "; adc-ped"; sn << name; sn << "_" << i; sn >> nameforhist; title = ss.str(); //cout << "title = " << title << endl; mHistAPV[i] = new TH1F( nameforhist.data(), title.data(), mXbins/mBinFactorX, mXmin, mXmax ); } // naming test hist by plane { std::string name1DR, name1DP, title1DR, title1DP; { std::stringstream ss, sr, sp; ss << GetName() << "_" << mDiscId << "_" << mQuadId; sr << ss.str() << "_Rtest"; sp << ss.str() << "_Ptest"; sr >> name1DR; sp >> name1DP; }; // test plot binning mXmin = 0; mXmax = 720; mXbins = 720; // easiest way to ensure stream is cleared is construct a new one std::stringstream ss, sr ,sp; ss << " Quad " << mQuadName << " hits"; sr << ss.str() << " in R; strip"; sp << ss.str() << " in Phi; strip"; title1DR = sr.str(); title1DP = sp.str(); //cout << "title = " << title1DR << endl; testHist[0] = new TH1F( name1DR.data(), title1DR.data(), mXbins/mBinFactorX, /*mXmin, mXmax*/ 0,720 ); testHist[1] = new TH1F( name1DP.data(), title1DP.data(), mXbins/mBinFactorX, /*mXmin, mXmax*/ 0,720 ); } // naming 1D clusters by plane std::string name1D, name1DR, name1DP, title1D, title1DR, title1DP; { std::stringstream ss, sr, sp; ss << GetName() << "_" << mDiscId << "_" << mQuadId; sr << ss.str() << "_R"; sp << ss.str() << "_P"; ss << "_C"; ss >> name1D; sr >> name1DR; sp >> name1DP; }; // 1D cluster plot binning // regular mXmin = 0; mXmax = 4000; mXbins = 400; /* // 5sigma mXmin = 0; mXmax = 6000; mXbins = 200; */ // easiest way to ensure stream is cleared is construct a new one std::stringstream ss, sr ,sp; ss << " Quad " << mQuadName << " clusters"; sr << ss.str() << " in R; adc sum"; sp << ss.str() << " in Phi; adc sum"; ss << " in R & Phi; adc sum"; title1D = ss.str(); title1DR = sr.str(); title1DP = sp.str(); //cout << "title = " << title1DR << endl; mHist1Dclusters = new TH1F( name1D.data(), title1D.data(), mXbins/mBinFactorX, mXmin, mXmax/*8000*/ ); mHist1Dcluster[0] = new TH1F( name1DR.data(), title1DR.data(), mXbins/mBinFactorX, mXmin, mXmax ); mHist1Dcluster[1] = new TH1F( name1DP.data(), title1DP.data(), mXbins/mBinFactorX, mXmin, mXmax ); // naming 2D point plot std::string name2D, title2D; { std::stringstream ss; ss << GetName() << "_" << mDiscId << "_" << mQuadId; ss >> name2D; }; // 2Dcluster plot binning mXmin = 0; mXmax = 40; mXbins = 40; // easiest way to ensure stream is cleared is construct a new one std::stringstream sstream; sstream << " Quad " << mQuadName << " cluster points; cm; cm"; title2D = sstream.str(); //cout << "title = " << title2D << endl; mHist2Dpoint = new TH2F( name2D.data(), title2D.data(), mXbins/mBinFactorX, mXmin, mXmax, mXbins/mBinFactorX, mXmin, mXmax ); }; return ierr; }; // collect hit info for QA Int_t StFgtCosmicTrackQA::Make(){ Int_t ierr = StFgtQaMaker::Make(); StFgtStripCollection *stripCollectionPtr = 0; if( !ierr ){ stripCollectionPtr = mFgtCollectionPtr->getStripCollection( mDiscId ); }; if( stripCollectionPtr ){ const StSPtrVecFgtStrip &stripVec = stripCollectionPtr->getStripVec(); StSPtrVecFgtStripConstIterator stripIter; for( stripIter = stripVec.begin(); stripIter != stripVec.end(); ++stripIter ){ // this ADC is adc-ped if StFgtCorAdcMaker is called first Int_t geoId = (*stripIter)->getGeoId(); Short_t adc = (*stripIter)->getAdc( mTimeBin ); // to store position data Short_t disc, quad; //, strip; Char_t layer; Double_t pos, high, low; //StFgtGeom::decodeGeoId( geoId, disc, quad, layer, strip ); StFgtGeom::getPhysicalCoordinate( geoId, disc, quad, layer, pos, high, low ); if( disc == mDiscId && quad == mQuadId ){ Int_t rdo, arm, apv, channel; StFgtCosmicTestStandGeom::getNaiveElecCoordFromGeoId(geoId,rdo,arm,apv,channel); // fill histogram per apv chip if(disc==2) apv -= 12; // for disc2, apv# range from 12-23 mHistAPV[apv]->Fill ( adc ); }; // looking for hot channels simpleClusterAlgo use this Short_t stripId; StFgtGeom::decodeGeoId(geoId,disc,quad,layer,stripId); if(layer=='R') testHist[0]->Fill( stripId ); else testHist[1]->Fill( stripId ); }; }; StFgtHitCollection *hitCollectionPtr = 0; if( !ierr ){ hitCollectionPtr = mFgtCollectionPtr->getHitCollection( mDiscId ); }; if( hitCollectionPtr ){ const StSPtrVecFgtHit &hitVec = hitCollectionPtr->getHitVec(); StSPtrVecFgtHitConstIterator hitIter; Short_t adcSum=0; // LOG_INFO << "We have " << hitVec.size() << " clusters " << endm; for( hitIter = hitVec.begin(); hitIter != hitVec.end(); ++hitIter ){ Bool_t haveR=false; haveR=((*hitIter)->getLayer()=='R'); /* // looking for hot channels maxClusterAlgo use this Int_t geoId = (*hitIter)->getCentralStripGeoId(); //Int_t rdo, arm, apv, channel; // StFgtCosmicTestStandGeom::getNaive... Short_t disc, quad, stripId; Char_t layer; StFgtGeom::decodeGeoId(geoId,disc,quad,layer,stripId); if(haveR) testHist[0]->Fill( stripId ); else testHist[1]->Fill( stripId ); */ if( haveR ) mHist1Dcluster[0]->Fill( (*hitIter)->charge() ); else mHist1Dcluster[1]->Fill( (*hitIter)->charge() ); adcSum += (*hitIter)->charge(); }; //if(adcSum>=200) mHist1Dclusters->Fill( adcSum ); if(adcSum!=0) mHist1Dclusters->Fill( adcSum ); // for ped files }; StFgtPointCollection *pointCollectionPtr = 0; if( !ierr ){ pointCollectionPtr = mFgtCollectionPtr->getPointCollection(); }; if( pointCollectionPtr ){ const StSPtrVecFgtPoint &pointVec = pointCollectionPtr->getPointVec(); StSPtrVecFgtPointConstIterator pointIter; // LOG_INFO << "We have " << pointVec.size() << " points " << endm; for( pointIter = pointVec.begin(); pointIter != pointVec.end(); ++pointIter ){ if( (*pointIter)->getDisc() == mDiscId ){ Float_t R = (*pointIter)->getPositionR(); Float_t Phi = (*pointIter)->getPositionPhi(); mHist2Dpoint->Fill( R*cos(Phi+.2618) , R*sin(Phi+.2618) ); }; }; }; return ierr; }; // make the histogram pretty and save it to a file, if given a filename base Int_t StFgtCosmicTrackQA::Finish(){ //cout << "StFgtCosmicTrackQA::Finish()" << endl; // remove hot bins (over 3 sigma say) -> I actually want to look at specific strip... for now just look at removing hot bins /* Float_t avg2Dpoint = 0; Float_t sigma = 0; Int_t numXbins = 40; Int_t numYbins = 40; for(Int_t i=0;i<numXbins;i++) { for(Int_t j=0;j<numYbins;j++) { Float_t con2Dpoint = mHist2Dpoint -> GetBinContent(i+1,j+1); avg2Dpoint += con2Dpoint; } } avg2Dpoint /= numXbins*numYbins; for(Int_t i=0;i<numXbins;i++) { for(Int_t j=0;j<numYbins;j++) { Float_t con2Dpoint = mHist2Dpoint -> GetBinContent(i+1,j+1); sigma += (con2Dpoint-avg2Dpoint)*(con2Dpoint-avg2Dpoint); } } sigma /= numXbins*numYbins; sigma = sqrt(sigma); for(Int_t i=0;i<numXbins;i++) { for(Int_t j=0;j<numYbins;j++) { Float_t con2Dpoint = mHist2Dpoint -> GetBinContent(i+1,j+1); if(con2Dpoint > avg2Dpoint+3*sigma) mHist2Dpoint -> SetBinContent(i+1,j+1,0); } } */ /* // Find hot strips and for removal > 5 sigma Float_t avgStripHitsR = 0, avgStripHitsP = 0; Float_t sigmaR = 0, sigmaP = 0; Int_t numXbins = 720; for(Int_t i=0;i<numXbins;i++) { Float_t conStripHitsR = testHist[0] -> GetBinContent(i+1); Float_t conStripHitsP = testHist[1] -> GetBinContent(i+1); avgStripHitsR += conStripHitsR; avgStripHitsP += conStripHitsP; } avgStripHitsR /= numXbins; avgStripHitsP /= numXbins; for(Int_t i=0;i<numXbins;i++) { Float_t conStripHitsR = testHist[0] -> GetBinContent(i+1); sigmaR += (conStripHitsR-avgStripHitsR)*(conStripHitsR-avgStripHitsR); Float_t conStripHitsP = testHist[1] -> GetBinContent(i+1); sigmaP += (conStripHitsP-avgStripHitsP)*(conStripHitsP-avgStripHitsP); } sigmaR /= numXbins; sigmaP /= numXbins; sigmaR = sqrt(sigmaR); sigmaP = sqrt(sigmaP); cout << "\nFor " << mFileNameKey << "\nHot R channels: "; for(Int_t i=0;i<numXbins;i++) { Float_t conStripHitsR = testHist[0] -> GetBinContent(i+1); if(conStripHitsR > avgStripHitsR+5*sigmaR) cout << i << " "; } cout << "\nHot Phi channels: "; for(Int_t i=0;i<numXbins;i++) { Float_t conStripHitsP = testHist[1] -> GetBinContent(i+1); if(conStripHitsP > avgStripHitsP+5*sigmaP) cout << i << " "; } cout << endl; */ if( !mFileNameBase.empty() ){ // filename std::string filename; if( !mPath.empty() ) filename = mPath + "/"; filename += mFileNameBase; if( !mFileNameKey.empty() ) filename += std::string( "." ) + mFileNameKey; filename += ".eps"; // draw gROOT->SetStyle("Plain"); TCanvas *canAPV = new TCanvas( "fgtTrackQAcanAPV", "fgtTrackQAcanAPV", 900, 400 ); gStyle->SetOptStat(0); gStyle->SetOptDate(0); Int_t pad=1; canAPV->Divide(5,2); for( Int_t i=0;i<10;i++) { canAPV->cd(pad); mHistAPV[i]->Draw(); pad++; } TCanvas *can2Dpoint = new TCanvas( "fgtTrackQAcan2Dpoint", "fgtTrackQAcan2Dpoint", 900, 400 ); gStyle->SetOptStat(0); gStyle->SetOptDate(0); mHist2Dpoint->Draw(); TCanvas *can1Dcluster = new TCanvas( "fgtTrackQAcan1Dcluster", "fgtTrackQAcan1Dcluster", 900, 400 ); gStyle->SetOptStat(100000); gStyle->SetOptDate(0); can1Dcluster->Divide(2,1); can1Dcluster->cd(1); mHist1Dcluster[0]->Draw(); can1Dcluster->cd(2); mHist1Dcluster[1]->Draw(); TCanvas *can1Dclusters = new TCanvas( "fgtTrackQAcan1Dclusters", "fgtTrackQAcan1Dclusters", 900, 400 ); gStyle->SetOptStat(100000); gStyle->SetOptDate(0); mHist1Dclusters->Draw(); canAPV->Print( filename.data() ); can2Dpoint->Print( filename.data() ); can1Dcluster->Print( filename.data() ); can1Dclusters->Print( filename.data() ); delete canAPV; delete can2Dpoint; delete can1Dcluster; delete can1Dclusters; }; return kStOk; }; void StFgtCosmicTrackQA::Clear( Option_t *opt ) { }; ClassImp(StFgtCosmicTrackQA);
30.79922
132
0.578228
xiaohaijin
91a932492725a8bcf00c640b3273c80c6f61e9ab
2,291
cpp
C++
common-lib/modules/general/src/hebench_math_utils.cpp
hebench/frontend
891652bbf7fd6e3aae1020f5cfc30b52e1c491f9
[ "Apache-2.0" ]
9
2021-12-16T18:34:15.000Z
2022-03-29T08:45:35.000Z
common-lib/modules/general/src/hebench_math_utils.cpp
hebench/frontend
891652bbf7fd6e3aae1020f5cfc30b52e1c491f9
[ "Apache-2.0" ]
13
2021-11-04T20:35:39.000Z
2022-02-25T20:06:35.000Z
common-lib/modules/general/src/hebench_math_utils.cpp
hebench/frontend
891652bbf7fd6e3aae1020f5cfc30b52e1c491f9
[ "Apache-2.0" ]
2
2021-12-14T20:09:50.000Z
2022-02-02T17:17:55.000Z
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include <algorithm> #include <stdexcept> #include "../include/hebench_math_utils.h" namespace hebench { namespace Utilities { namespace Math { double computePercentile(const double *data, std::size_t count, double percentile) { // uses percentile formula from R double rank = std::clamp(percentile, 0.0, 1.0) * (count - 1); std::uint64_t rank_i = static_cast<std::uint64_t>(rank); double rank_f = rank - rank_i; return data[rank_i] + rank_f * (data[rank_i + 1] - data[rank_i]); } //------------------------ // class ComponentCounter //------------------------ ComponentCounter::ComponentCounter(std::vector<std::size_t> component_sizes) : m_count(component_sizes.size()), m_sizes(component_sizes) { for (std::size_t i = 0; i < component_sizes.size(); ++i) if (component_sizes[i] <= 0) throw std::invalid_argument("Invalid zero entry: 'component_sizes'."); } std::size_t ComponentCounter::getCountLinear() const { std::size_t retval = m_count.empty() ? 0 : m_count.back(); for (std::size_t i = m_count.size() - 1; i > 0; --i) retval = m_count[i - 1] + m_sizes[i - 1] * retval; return retval; } std::size_t ComponentCounter::getCountLinearReversed() const { std::size_t retval = m_count.empty() ? 0 : m_count[0]; for (std::size_t i = 1; i < m_count.size(); ++i) retval = m_count[i] + m_sizes[i] * retval; return retval; } bool ComponentCounter::inc() { bool overflow = true; for (std::size_t i = 0; overflow && i < m_count.size(); ++i) { if (++m_count[i] >= m_sizes[i]) m_count[i] = 0; else overflow = false; } // end for return overflow; } bool ComponentCounter::dec() { bool overflow = true; for (std::size_t i = 0; overflow && i < m_count.size(); ++i) { if (m_count[i] == 0) m_count[i] = m_sizes[i] - 1; else { --m_count[i]; overflow = false; } // end else } // end for return overflow; } void ComponentCounter::reset() { std::fill(m_count.begin(), m_count.end(), 0); } } // namespace Math } // namespace Utilities } // namespace hebench
25.175824
82
0.591881
hebench
91ac4db899172ed17544ea028421e291f81a6353
3,788
hpp
C++
simpletest_signal.hpp
jonathanrlemos/simpletest
0b0086279c756aa7bd14a40d907352233fc98313
[ "MIT" ]
null
null
null
simpletest_signal.hpp
jonathanrlemos/simpletest
0b0086279c756aa7bd14a40d907352233fc98313
[ "MIT" ]
null
null
null
simpletest_signal.hpp
jonathanrlemos/simpletest
0b0086279c756aa7bd14a40d907352233fc98313
[ "MIT" ]
null
null
null
/** @file simpletest_signal.hpp * @brief simpletest signal handler. * @copyright Copyright (c) 2018 Jonathan Lemos * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #ifndef __SIMPLETEST_SIGNAL_HPP #define __SIMPLETEST_SIGNAL_HPP #include <csetjmp> #include <csignal> #include <iostream> namespace simpletest{ /** * @brief An exception that indicates a signal was thrown. */ class SignalException : public std::runtime_error{ public: /** * @brief Constructs a SignalException. * * @param signo The signal code. */ SignalException(sig_atomic_t signo); /** * @brief Gets the signal code of this exception. */ sig_atomic_t getSignal() const; private: /** * @brief The last signal code. */ sig_atomic_t signo; }; /** * @brief This class handles signals while it is active. * Only one SignalHandler can be active in a thread at once. * * A singleton is not appropriate here, because this class's destructor is needed to stop capturing signals, and the destructor for a singleton is never called. */ class SignalHandler{ public: /** * @brief Instantiates a signal handler. * Upon creation, this class will begin capturing SIGINT, SIGABRT, SIGSEGV, and SIGTERM. * * @exception std::logic_error A signal handler has already been instantiated in this thread. */ SignalHandler(); /** * @brief Move constructor for SignalHandler. */ SignalHandler(SignalHandler&& other); /** * @brief Move assignment operator for SignalHandler. */ SignalHandler& operator=(SignalHandler&& other); /** * @brief Deleted copy constructor. * There should only be one of this class, so it should not be copied; */ SignalHandler(const SignalHandler& other) = delete; /** * @brief Deleted copy assignment. * There should only be one of this class, so it should not be copied. */ SignalHandler& operator=(const SignalHandler& val) = delete; /** * @brief Stops capturing signals. */ ~SignalHandler(); /** * @brief Gets the last signal thrown as an integer. * * @return 0 for no signal, SIG* for any of the other signals. The following is a list of signals caught. Any signal not on this list will have its default behavior. * <br> * <pre> * 0 No signal * SIGINT Interrupt from keyboard (Ctrl+C) * SIGABRT abort() called * SIGSEGV Invalid memory access. * SIGTERM Default termination signal. * </pre> * <br> */ static sig_atomic_t lastSignal(); /** * @brief Gets a string representation of a signal. */ static const char* signalToString(sig_atomic_t signo); /** * @brief Do not call directly. Use the ActivateSignalHandler() macro instead. * Gets a reference to the jump buffer for use with the ActivateSignalHandler() macro. */ static jmp_buf& getBuf(); /** * @brief Do not call this function directly. Use the ActivateSignalHandler() macro instead. * True if the function should exit (a signal was called that should terminate the program. */ static bool shouldExit(); }; /** * @brief Activates the signal handler, throwing an exception if a signal is thrown. * This allows RAII cleanup to occur when a signal is thrown. */ #define ActivateSignalHandler(handler)\ /* returns 0 on its first call, returns signo (>0) when being jumped to through longjmp() */\ if (setjmp(simpletest::SignalHandler::getBuf())){\ /* SIGABRT, SIGINT, etc. */\ if (handler.shouldExit()){\ std::cerr << "Terminating program (" << simpletest::SignalHandler::signalToString(handler.lastSignal()) << ")" << std::endl;\ std::exit(1);\ }\ throw simpletest::SignalException(simpletest::SignalHandler::lastSignal());\ }\ /* requires the statement to have a semicolon at the end. */\ (void)0 } #endif
27.057143
166
0.704329
jonathanrlemos