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
e3b88ecd795aecca9420e84d7bd0e9558d9f160b
16,020
cpp
C++
ParticlePlay/Core/Game.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
ParticlePlay/Core/Game.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
ParticlePlay/Core/Game.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
#include "Game.hpp" #ifdef PPDEBUG #include <iostream> #endif ppGame::ppGame(){ this->mainWindow = NULL; this->renderer = NULL; this->graphics = NULL; this->backgroundColor = new ppColor(); this->gameInput = new ppInput(this); this->gameIO = new ppIO(); this->randomizer = new ppRandomizer(); this->ims = NULL; this->title = "My Game"; this->currentState = NULL; this->screenWidth = 640; this->width = 640; this->screenHeight = 480; this->height = 480; this->targetFPS = 60; this->targetUPS = 60; this->running = false; this->restarting = false; this->resizable = false; this->fullscreen = false; this->showFPS = false; this->vSync = false; this->idleTime = 0; this->fps = 0; this->ups = 0; this->art = 0; this->aut = 0; } const char* ppGame::GetTitle(){ return this->title; } void ppGame::SetTitle(const char* title){ this->title = title; if(this->mainWindow){ SDL_SetWindowTitle(this->mainWindow, title); } } int ppGame::GetScreenWidth(){ return this->screenWidth; } int ppGame::GetScreenHeight(){ return this->screenHeight; } int ppGame::GetWidth(){ return this->width; } int ppGame::GetHeight(){ return this->height; } ppRandomizer* ppGame::GetRandomizer(){ return this->randomizer; } void ppGame::SetScreenSize(int width, int height){ this->screenWidth = width; this->screenHeight = height; this->SetSize(width, height); this->RestartGame(); } void ppGame::SetSize(int width, int height){ this->width = width; this->height = height; if(this->renderer){ SDL_RenderSetLogicalSize(this->renderer, this->width, this->height); } } bool ppGame::IsResizable(){ return this->resizable; } void ppGame::SetResizable(bool resizable){ this->resizable = resizable; this->RestartGame(); } bool ppGame::IsFullscreen(){ return this->fullscreen; } void ppGame::SetFullscreen(bool fullscreen){ this->fullscreen = fullscreen; this->RestartGame(); } void ppGame::OnEvent(SDL_Event* event) { switch(event->type){ case SDL_QUIT: if(!this->currentState || !this->currentState->OnEvent(event)){ this->running = false; } break; case SDL_KEYDOWN: case SDL_KEYUP: case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: case SDL_MOUSEWHEEL: case SDL_JOYAXISMOTION: case SDL_JOYBALLMOTION: case SDL_JOYHATMOTION: case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: case SDL_JOYDEVICEADDED: case SDL_JOYDEVICEREMOVED: case SDL_CONTROLLERAXISMOTION: case SDL_CONTROLLERBUTTONDOWN: case SDL_CONTROLLERBUTTONUP: case SDL_CONTROLLERDEVICEADDED: case SDL_CONTROLLERDEVICEREMOVED: case SDL_CONTROLLERDEVICEREMAPPED: case SDL_FINGERDOWN: case SDL_FINGERUP: case SDL_FINGERMOTION: case SDL_DOLLARGESTURE: case SDL_DOLLARRECORD: case SDL_MULTIGESTURE: if(!this->currentState || !this->currentState->OnEvent(event)){ this->gameInput->OnEvent(event); } break; case SDL_APP_TERMINATING: #ifdef PPDEBUG std::cout << "Getting force close..." << std::endl; #endif if(!this->currentState || !this->currentState->OnEvent(event)){ this->running = false; } break; case SDL_APP_LOWMEMORY: #ifdef PPDEBUG std::cout << "Low memory..." << std::endl; #endif if(this->currentState){ this->currentState->OnEvent(event); } break; case SDL_WINDOWEVENT: if(event->window.event == SDL_WINDOWEVENT_RESIZED){ this->SetScreenSize(event->window.data1, event->window.data2); } if(this->currentState){ this->currentState->OnEvent(event); } break; default: if(this->currentState){ this->currentState->OnEvent(event); } break; } } int ppGame::StartGame(){ #ifdef PPDEBUG std::cout << "Initializing SDL... "; #endif if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { #ifndef PPDEBUG std::cout << "Error: "; #endif std::cout << SDL_GetError() << std::endl; return 1; } SDL_version sdlCompiledVersion; SDL_version sdlLinkedVersion; SDL_VERSION(&sdlCompiledVersion); SDL_GetVersion(&sdlLinkedVersion); if(SDL_VERSION_NUMBER(&sdlLinkedVersion) < SDL_VERSION_NUMBER(&sdlCompiledVersion)){ std::cout << "The installed SDL is not compatible. [" << SDL_VERSION_CONCAT(&sdlLinkedVersion) << "<" << SDL_VERSION_CONCAT(&sdlCompiledVersion) << "]" << std::endl; return 1; } #ifdef PPDEBUG std::cout << "v" << SDL_VERSION_CONCAT(&sdlLinkedVersion) << std::endl; std::cout << "Initializing SDL_image... "; #endif int imgFlags = IMG_INIT_JPG|IMG_INIT_PNG|IMG_INIT_TIF; if((IMG_Init(imgFlags) & imgFlags) != imgFlags) { #ifndef PPDEBUG std::cout << "Error: "; #endif std::cout << IMG_GetError() << std::endl; return 1; } SDL_version imgCompiledVersion; SDL_IMAGE_VERSION(&imgCompiledVersion); const SDL_version *imgLinkedVersion = IMG_Linked_Version(); if(SDL_VERSION_NUMBER(imgLinkedVersion) < SDL_VERSION_NUMBER(&imgCompiledVersion)){ std::cout << "The installed SDL_image is not compatible. [" << SDL_VERSION_CONCAT(imgLinkedVersion) << "<" << SDL_VERSION_CONCAT(&imgCompiledVersion) << "]" << std::endl; return 1; } #ifdef PPDEBUG std::cout << "v" << SDL_VERSION_CONCAT(imgLinkedVersion) << std::endl; std::cout << "Initializing SDL_net... "; #endif if(SDLNet_Init() < 0) { #ifndef PPDEBUG std::cout << "Error: "; #endif std::cout << SDLNet_GetError() << std::endl; return 1; } SDL_version netCompiledVersion; SDL_NET_VERSION(&netCompiledVersion); const SDL_version *netLinkedVersion = SDLNet_Linked_Version(); if(SDL_VERSION_NUMBER(netLinkedVersion) < SDL_VERSION_NUMBER(&netCompiledVersion)){ std::cout << "The installed SDL_net is not compatible. [" << SDL_VERSION_CONCAT(netLinkedVersion) << "<" << SDL_VERSION_CONCAT(&netCompiledVersion) << "]" << std::endl; return 1; } #ifdef PPDEBUG std::cout << "v" << SDL_VERSION_CONCAT(netLinkedVersion) << std::endl; #endif do{ Uint32 speedTimer = SDL_GetTicks(); #ifdef PPDEBUG std::cout << "Creating window... "; #endif Uint32 flags = 0; if(this->resizable){ flags |= SDL_WINDOW_RESIZABLE; } if(this->fullscreen){ flags |= SDL_WINDOW_FULLSCREEN; } if(!(this->mainWindow = SDL_CreateWindow(this->title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, this->screenWidth, this->screenHeight, flags))) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unexpected error has occurred", "Cannot initialize window.", 0); return 1; } #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; speedTimer = SDL_GetTicks(); std::cout << "Creating renderer... "; #endif if(!(this->renderer = SDL_CreateRenderer(this->mainWindow, -1, 0))) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unexpected error has occurred", "Cannot initialize renderer.", 0); return 1; } this->graphics = new ppGraphics(this->renderer); if(this->renderer){ #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; SDL_RendererInfo rendererInfo; SDL_GetRendererInfo(this->renderer, &rendererInfo); std::cout << "Using \"" << rendererInfo.name << "\" as rendering engine..." << std::endl; speedTimer = SDL_GetTicks(); std::cout << "Configuring renderer... "; #endif SDL_Rect* rect = new SDL_Rect; rect->x = 0; rect->y = 0; rect->w = this->screenWidth; rect->h = this->screenHeight; SDL_RenderSetViewport(this->renderer, rect); SDL_RenderSetLogicalSize(this->renderer, this->width, this->height); } if(!this->restarting){ #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; speedTimer = SDL_GetTicks(); std::cout << "Initializing Adaptive Music System... "; #endif this->ims = new ppIMS(this, this->randomizer); if(this->ims->Init()){ SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unexpected error has occurred", "Cannot initialize Adaptive Music System.", 0); return 1; } } #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; if(!this->currentState) { std::cout << "No state found..." << std::endl; SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning!", "State not found.", 0); } speedTimer = SDL_GetTicks(); std::cout << "Preparing... "; #endif this->running = true; if(this->currentState && this->currentState->GetGame()){ this->currentState->OnInit(); } SDL_Event* event = new SDL_Event(); Uint32 lastTimer = SDL_GetTicks(), timeNow; Uint32 lastTime = lastTimer, avgRenderTime = 0, avgUpdateTime = 0; int renderDelta = 0, updateDelta = 0, renderDeltaTime=0, updateDeltaTime=0; int frames = 0, updates = 0; Uint32 msPerRender = 1000.0f / this->targetFPS; Uint32 msPerUpdate = 1000.0f / this->targetUPS; #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; speedTimer = SDL_GetTicks(); std::cout << "Running... " << std::endl; #endif if(this->restarting){ this->restarting = false; if(this->currentState && this->currentState->GetGame()){ this->currentState->OnRestore(); } } while(this->running) { timeNow = SDL_GetTicks(); renderDelta += (timeNow - lastTime); renderDeltaTime += (timeNow - lastTime); updateDelta += (timeNow - lastTime); updateDeltaTime += (timeNow - lastTime); lastTime = timeNow; while(SDL_PollEvent(event)) { this->OnEvent(event); } if(updateDelta > msPerUpdate){ speedTimer = SDL_GetTicks(); updateDelta -= msPerUpdate; updates++; if(this->currentState && this->currentState->GetGame()){ this->currentState->OnUpdate(this->gameInput, updateDeltaTime); } updateDeltaTime = 0; this->ims->Update(); this->gameInput->OnUpdate(); avgUpdateTime += SDL_GetTicks()-speedTimer; } if(!this->vSync || renderDelta > msPerRender){ speedTimer = SDL_GetTicks(); renderDelta -= msPerRender; frames++; SDL_SetRenderDrawColor(this->renderer, this->backgroundColor->GetR(), this->backgroundColor->GetG(), this->backgroundColor->GetB(), this->backgroundColor->GetA()); SDL_RenderClear(this->renderer); if(this->currentState && this->currentState->GetGame()){ SDL_SetRenderDrawColor(this->renderer, 255, 255, 255, 255); SDL_SetRenderDrawBlendMode(this->renderer, SDL_BLENDMODE_BLEND); this->currentState->OnRender(this->graphics, renderDeltaTime); } renderDeltaTime = 0; if(this->showFPS){ SDL_SetRenderDrawColor(this->renderer, 255, 255, 255, 127); SDL_Rect* rect = new SDL_Rect; rect->x = 0; rect->y = 0; rect->w = this->width; rect->h = 6; SDL_RenderFillRect(this->renderer, rect); // FPS if(this->fps > 0){ Uint8 delta = this->fps / this->width; SDL_SetRenderDrawColor(this->renderer, 0, (255-(delta*2)), 0, 127); SDL_Rect* rect = new SDL_Rect; rect->x = 0; rect->y = 1; rect->w = this->fps % this->width; rect->h = 2; SDL_RenderFillRect(this->renderer, rect); } // UPS if(this->ups > 0){ Uint8 delta = this->ups / this->width; SDL_SetRenderDrawColor(this->renderer, 0, 0, (255-(delta*2)), 127); SDL_Rect* rect = new SDL_Rect; rect->x = 0; rect->y = 3; rect->w = this->ups % this->width; rect->h = 2; SDL_RenderFillRect(this->renderer, rect); } } SDL_RenderPresent(this->renderer); avgRenderTime += SDL_GetTicks()-speedTimer; } if(this->idleTime > 0){ SDL_Delay(this->idleTime); } if(SDL_GetTicks() - lastTimer >= 1000){ this->fps = frames; this->ups = updates; this->art = avgRenderTime/fps; this->aut = avgUpdateTime/ups; frames = 0; updates = 0; lastTimer = SDL_GetTicks(); #ifdef PPDEBUG if(this->showFPS){ std::cout << "FPS: " << fps << " [" << art <<"ms] UPS: " << ups << " [" << aut << "ms]" << std::endl; } #endif avgRenderTime = 0; avgUpdateTime = 0; } } if(this->currentState){ this->currentState->OnExit(); } #ifdef PPDEBUG speedTimer = SDL_GetTicks(); std::cout << "Destroying... "; #endif if(!this->restarting){ this->ims->Quit(); } SDL_DestroyRenderer(this->renderer); SDL_DestroyWindow(this->mainWindow); #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; speedTimer = SDL_GetTicks(); if(this->restarting){ std::cout << "Restarting..." << std::endl; } #endif } while(this->restarting); IMG_Quit(); SDLNet_Quit(); SDL_Quit(); #ifdef PPDEBUG std::cout << "Quitting..." << std::endl; #endif return 0; } void ppGame::RestartGame(){ if(!this->running){ return; } if(this->currentState && this->currentState->GetGame()){ this->currentState->OnRestart(); } this->running = false; this->restarting = true; } void ppGame::QuitGame(){ this->running = false; } ppInput* ppGame::GetGameInput(){ return this->gameInput; } ppIO* ppGame::GetGameIO(){ return this->gameIO; } ppIMS* ppGame::GetInteractiveMusicSystem(){ return this->ims; } // GameIO* ppGame::getGameIO(){ // } // SoundPlayer* ppGame::getSoundPlayer(){ // } void ppGame::AddState(const char* name, ppState* state){ #ifdef PPDEBUG std::cout << "Add a new state \"" << name << "\"..." << std::endl; #endif state->SetName(name); this->states.insert(std::pair<const char*, ppState*>(name, state)); } void ppGame::EnterState(ppState* state){ if(!state->GetGame()){ state->SetGame(this); if(this->running){ state->OnInit(); } }else if(state->IsNeedInit() && this->running){ state->OnInit(); } if(this->currentState){ this->currentState->OnExit(); } #ifdef PPDEBUG std::cout << "Enter a state \"" << state->GetName() << "\"..." << std::endl; #endif this->currentState = state; } void ppGame::EnterState(const char* name){ ppState* state = this->GetState(name); if(state){ if(!state->GetGame()){ state->SetGame(this); if(this->running){ state->OnInit(); } }else if(state->IsNeedInit() && this->running){ state->OnInit(); } if(this->currentState){ this->currentState->OnExit(); } #ifdef PPDEBUG std::cout << "Enter a state \"" << state->GetName() << "\"..." << std::endl; #endif this->currentState = state; } } void ppGame::EnterState(const char* name, ppState* state){ this->AddState(name, state); this->EnterState(state); } ppState* ppGame::GetState(const char* name){ if(this->states.empty()){ return NULL; } std::map<const char*, ppState*>::iterator it; it = this->states.find(name); if(it != this->states.end()){ return it->second; } return NULL; } bool ppGame::HasState(const char* name){ return false; } const char* ppGame::GetCurrentStateName(){ return this->currentState->GetName(); } void ppGame::RemoveState(const char* name){ if(this->states.empty()){ return; } std::map<const char*, ppState*>::iterator it; it = this->states.find(name); if(it != this->states.end()){ this->states.erase(it); } } ppColor* ppGame::GetBackgroundColor(){ return this->backgroundColor; } void ppGame::SetBackgroundColor(ppColor* color){ this->backgroundColor = color; } int ppGame::GetFPS(){ return this->fps; } int ppGame::GetUPS(){ return this->ups; } int ppGame::GetAvgRenderTime(){ return this->art; } int ppGame::GetAvgUpdateTime(){ return this->aut; } int ppGame::GetTargetFPS(){ return this->targetFPS; } void ppGame::SetTargetFPS(int targetFPS){ this->targetFPS = targetFPS; } int ppGame::GetTargetUPS(){ return this->targetUPS; } void ppGame::SetTargetUPS(int targetUPS){ this->targetUPS = targetUPS; } int ppGame::GetIdleTime(){ return this->idleTime; } void ppGame::SetIdleTime(int idleTime){ this->idleTime = idleTime; } bool ppGame::IsShowFPS(){ return this->showFPS; } void ppGame::SetShowFPS(bool showFPS){ this->showFPS = showFPS; } bool ppGame::IsVSync(){ return this->vSync; } void ppGame::SetVSync(bool vSync){ this->vSync = vSync; } ppGame::~ppGame(){ // Pure virtual // Will run on destroy only free(this->gameInput); free(this->backgroundColor); }
25.228346
172
0.664732
spywhere
e3bab02a5fe86cbb53b03c6e9fe3606ab00dce22
53,245
cc
C++
webkit/glue/webview_impl.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
1
2016-05-08T15:35:17.000Z
2016-05-08T15:35:17.000Z
webkit/glue/webview_impl.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
null
null
null
webkit/glue/webview_impl.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2007 Google Inc. All Rights Reserved. * * Portions Copyright (C) 2006 Apple Computer, Inc. All rights reserved. * * ***** BEGIN LICENSE BLOCK ***** * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** * */ #include "config.h" #include "build/build_config.h" #include "base/compiler_specific.h" MSVC_PUSH_WARNING_LEVEL(0); #if defined(OS_WIN) #include "Cursor.h" #endif #include "Document.h" #include "DocumentLoader.h" #include "DragController.h" #include "DragData.h" #include "Editor.h" #include "EventHandler.h" #include "FocusController.h" #include "FontDescription.h" #include "FrameLoader.h" #include "FrameTree.h" #include "FrameView.h" #include "GraphicsContext.h" #include "HitTestResult.h" #include "Image.h" #include "InspectorController.h" #include "IntRect.h" #include "KeyboardEvent.h" #include "MIMETypeRegistry.h" #include "Page.h" #include "PlatformKeyboardEvent.h" #include "PlatformMouseEvent.h" #include "PlatformWheelEvent.h" #include "PluginInfoStore.h" #if defined(OS_WIN) #include "RenderThemeWin.h" #endif #include "ResourceHandle.h" #include "SelectionController.h" #include "Settings.h" #include "TypingCommand.h" #include "event_conversion.h" MSVC_POP_WARNING(); #undef LOG #include "base/gfx/rect.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/string_util.h" #include "webkit/glue/chrome_client_impl.h" #include "webkit/glue/context_menu_client_impl.h" #include "webkit/glue/dragclient_impl.h" #include "webkit/glue/editor_client_impl.h" #include "webkit/glue/event_conversion.h" #include "webkit/glue/glue_serialize.h" #include "webkit/glue/glue_util.h" #include "webkit/glue/image_resource_fetcher.h" #include "webkit/glue/inspector_client_impl.h" #include "webkit/glue/searchable_form_data.h" #include "webkit/glue/webdropdata.h" #include "webkit/glue/webhistoryitem_impl.h" #include "webkit/glue/webinputevent.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/webpreferences.h" #include "webkit/glue/webview_delegate.h" #include "webkit/glue/webview_impl.h" #include "webkit/glue/webwidget_impl.h" #include "webkit/port/platform/graphics/PlatformContextSkia.h" // Get rid of WTF's pow define so we can use std::pow. #undef pow #include <cmath> // for std::pow using namespace WebCore; // Change the text zoom level by kTextSizeMultiplierRatio each time the user // zooms text in or out (ie., change by 20%). The min and max values limit // text zoom to half and 3x the original text size. These three values match // those in Apple's port in WebKit/WebKit/WebView/WebView.mm static const double kTextSizeMultiplierRatio = 1.2; static const double kMinTextSizeMultiplier = 0.5; static const double kMaxTextSizeMultiplier = 3.0; // The webcore drag operation type when something is trying to be dropped on // the webview. These values are taken from Apple's windows port. static const WebCore::DragOperation kDropTargetOperation = static_cast<WebCore::DragOperation>(DragOperationCopy | DragOperationLink); // WebView ---------------------------------------------------------------- /*static*/ WebView* WebView::Create(WebViewDelegate* delegate, const WebPreferences& prefs) { WebViewImpl* instance = new WebViewImpl(); instance->AddRef(); instance->SetPreferences(prefs); instance->main_frame_->InitMainFrame(instance); // Set the delegate after initializing the main frame, to avoid trying to // respond to notifications before we're fully initialized. instance->delegate_ = delegate; // Restrict the access to the local file system // (see WebView.mm WebView::_commonInitializationWithFrameName). FrameLoader::setLocalLoadPolicy( FrameLoader::AllowLocalLoadsForLocalOnly); return instance; } WebViewImpl::WebViewImpl() : delegate_(NULL), pending_history_item_(NULL), observed_new_navigation_(false), #ifndef NDEBUG new_navigation_loader_(NULL), #endif zoom_level_(0), context_menu_allowed_(false), doing_drag_and_drop_(false), suppress_next_keypress_event_(false), window_open_disposition_(IGNORE_ACTION), ime_accept_events_(true) { // WebKit/win/WebView.cpp does the same thing, except they call the // KJS specific wrapper around this method. We need to have threading // initialized because CollatorICU requires it. WTF::initializeThreading(); // set to impossible point so we always get the first mouse pos last_mouse_position_.SetPoint(-1, -1); // the page will take ownership of the various clients page_.reset(new Page(new ChromeClientImpl(this), new ContextMenuClientImpl(this), new EditorClientImpl(this), new DragClientImpl(this), new WebInspectorClient(this))); page_->backForwardList()->setClient(this); // The group name identifies a namespace of pages. I'm not sure how it's // intended to be used, but keeping all pages in the same group works for us. page_->setGroupName("default"); // This is created with a refcount of 1, and we assign it to a RefPtr, // giving a refcount of 2. The ref is done on behalf of // FrameWin/FrameLoaderWin which references the WebFrame via the // FrameWinClient/FrameLoaderClient interfaces. See the comment at the // top of webframe_impl.cc main_frame_ = new WebFrameImpl(); } WebViewImpl::~WebViewImpl() { DCHECK(main_frame_ == NULL); DCHECK(page_ == NULL); ReleaseFocusReferences(); for (std::set<ImageResourceFetcher*>::iterator i = image_fetchers_.begin(); i != image_fetchers_.end(); ++i) { delete *i; } } void WebViewImpl::SetUseEditorDelegate(bool value) { ASSERT(page_ != 0); // The macro doesn't like (!page_) with a scoped_ptr. ASSERT(page_->editorClient()); EditorClientImpl* editor_client = static_cast<EditorClientImpl*>(page_->editorClient()); editor_client->SetUseEditorDelegate(value); } void WebViewImpl::SetTabKeyCyclesThroughElements(bool value) { if (page_ != NULL) { page_->setTabKeyCyclesThroughElements(value); } } void WebViewImpl::MouseMove(const WebMouseEvent& event) { if (!main_frame_->frameview()) return; last_mouse_position_.SetPoint(event.x, event.y); // We call mouseMoved here instead of handleMouseMovedEvent because we need // our ChromeClientImpl to receive changes to the mouse position and // tooltip text, and mouseMoved handles all of that. main_frame_->frameview()->frame()->eventHandler()->mouseMoved( MakePlatformMouseEvent(main_frame_->frameview(), event)); } void WebViewImpl::MouseLeave(const WebMouseEvent& event) { // This event gets sent as the main frame is closing. In that case, just // ignore it. if (!main_frame_ || !main_frame_->frameview()) return; delegate_->UpdateTargetURL(this, GURL()); main_frame_->frameview()->frame()->eventHandler()->handleMouseMoveEvent( MakePlatformMouseEvent(main_frame_->frameview(), event)); } void WebViewImpl::MouseDown(const WebMouseEvent& event) { if (!main_frame_->frameview()) return; last_mouse_down_point_ = gfx::Point(event.x, event.y); main_frame_->frame()->eventHandler()->handleMousePressEvent( MakePlatformMouseEvent(main_frame_->frameview(), event)); } void WebViewImpl::MouseContextMenu(const WebMouseEvent& event) { page_->contextMenuController()->clearContextMenu(); MakePlatformMouseEvent pme(main_frame_->frameview(), event); // Find the right target frame. See issue 1186900. IntPoint doc_point( main_frame_->frame()->view()->windowToContents(pme.pos())); HitTestResult result = main_frame_->frame()->eventHandler()->hitTestResultAtPoint(doc_point, false); Frame* target_frame; if (result.innerNonSharedNode()) target_frame = result.innerNonSharedNode()->document()->frame(); else target_frame = page_->focusController()->focusedOrMainFrame(); #if defined(OS_WIN) target_frame->view()->setCursor(pointerCursor()); #endif context_menu_allowed_ = true; target_frame->eventHandler()->sendContextMenuEvent(pme); context_menu_allowed_ = false; // Actually showing the context menu is handled by the ContextMenuClient // implementation... } void WebViewImpl::MouseUp(const WebMouseEvent& event) { if (!main_frame_->frameview()) return; MouseCaptureLost(); main_frame_->frameview()->frame()->eventHandler()->handleMouseReleaseEvent( MakePlatformMouseEvent(main_frame_->frameview(), event)); // Dispatch the contextmenu event regardless of if the click was swallowed. if (event.button == WebMouseEvent::BUTTON_RIGHT) MouseContextMenu(event); } void WebViewImpl::MouseWheel(const WebMouseWheelEvent& event) { MakePlatformWheelEvent platform_event(main_frame_->frameview(), event); main_frame_->frame()->eventHandler()->handleWheelEvent(platform_event); } bool WebViewImpl::KeyEvent(const WebKeyboardEvent& event) { DCHECK((event.type == WebInputEvent::KEY_DOWN) || (event.type == WebInputEvent::KEY_UP)); // Please refer to the comments explaining the suppress_next_keypress_event_ // member. // The suppress_next_keypress_event_ is set if the KeyDown is handled by // Webkit. A keyDown event is typically associated with a keyPress(char) // event and a keyUp event. We reset this flag here as this is a new keyDown // event. suppress_next_keypress_event_ = false; Frame* frame = GetFocusedWebCoreFrame(); if (!frame) return false; EventHandler* handler = frame->eventHandler(); if (!handler) return KeyEventDefault(event); #if defined(OS_WIN) // TODO(pinkerton): figure out these keycodes on non-windows if (((event.modifiers == 0) && (event.key_code == VK_APPS)) || ((event.modifiers == WebInputEvent::SHIFT_KEY) && (event.key_code == VK_F10))) { SendContextMenuEvent(event); return true; } #endif MakePlatformKeyboardEvent evt(event); #if defined(OS_WIN) if (WebInputEvent::KEY_DOWN == event.type) { MakePlatformKeyboardEvent evt_rawkeydown = evt; evt_rawkeydown.SetKeyType(WebCore::PlatformKeyboardEvent::RawKeyDown); if (handler->keyEvent(evt_rawkeydown) && !evt_rawkeydown.isSystemKey()) { suppress_next_keypress_event_ = true; return true; } } else { if (handler->keyEvent(evt)) { return true; } } #elif defined(OS_MACOSX) // Windows and Cocoa handle events in rather different ways. On Windows, // you get two events: WM_KEYDOWN/WM_KEYUP and WM_CHAR. In // PlatformKeyboardEvent, RawKeyDown represents the raw messages. When // processing them, we don't process text editing events, since we'll be // getting the data soon enough. In Cocoa, we get one event with both the // raw and processed data. Therefore we need to keep the type as KeyDown, so // that we'll know that this is the only time we'll have the event and that // we need to do our thing. if (handler->keyEvent(evt)) { return true; } #endif return KeyEventDefault(event); } bool WebViewImpl::CharEvent(const WebKeyboardEvent& event) { DCHECK(event.type == WebInputEvent::CHAR); // Please refer to the comments explaining the suppress_next_keypress_event_ // member. // The suppress_next_keypress_event_ is set if the KeyDown is handled by // Webkit. A keyDown event is typically associated with a keyPress(char) // event and a keyUp event. We reset this flag here as it only applies // to the current keyPress event. if (suppress_next_keypress_event_) { suppress_next_keypress_event_ = false; return true; } Frame* frame = GetFocusedWebCoreFrame(); if (!frame) return false; EventHandler* handler = frame->eventHandler(); if (!handler) return KeyEventDefault(event); MakePlatformKeyboardEvent evt(event); if (!evt.IsCharacterKey()) return true; #if defined(OS_WIN) // Safari 3.1 does not pass off WM_SYSCHAR messages to the // eventHandler::keyEvent. We mimic this behavior. if (evt.isSystemKey()) return handler->handleAccessKey(evt); #endif if (!handler->keyEvent(evt)) return KeyEventDefault(event); return true; } /* * The WebViewImpl::SendContextMenuEvent function is based on the Webkit * function * bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam) in * webkit\webkit\win\WebView.cpp. The only significant change in this * function is the code to convert from a Keyboard event to the Right * Mouse button up event. * * This function is an ugly copy/paste and should be cleaned up when the * WebKitWin version is cleaned: https://bugs.webkit.org/show_bug.cgi?id=20438 */ #if defined(OS_WIN) // TODO(pinkerton): implement on non-windows bool WebViewImpl::SendContextMenuEvent(const WebKeyboardEvent& event) { static const int kContextMenuMargin = 1; Frame* main_frame = page()->mainFrame(); FrameView* view = main_frame->view(); if (!view) return false; IntPoint coords(-1, -1); int right_aligned = ::GetSystemMetrics(SM_MENUDROPALIGNMENT); IntPoint location; // The context menu event was generated from the keyboard, so show the // context menu by the current selection. Position start = main_frame->selection()->selection().start(); Position end = main_frame->selection()->selection().end(); if (!start.node() || !end.node()) { location = IntPoint(right_aligned ? view->contentsWidth() - kContextMenuMargin : kContextMenuMargin, kContextMenuMargin); } else { RenderObject* renderer = start.node()->renderer(); if (!renderer) return false; RefPtr<Range> selection = main_frame->selection()->toRange(); IntRect first_rect = main_frame->firstRectForRange(selection.get()); int x = right_aligned ? first_rect.right() : first_rect.x(); location = IntPoint(x, first_rect.bottom()); } location = view->contentsToWindow(location); // FIXME: The IntSize(0, -1) is a hack to get the hit-testing to result in // the selected element. Ideally we'd have the position of a context menu // event be separate from its target node. coords = location + IntSize(0, -1); // The contextMenuController() holds onto the last context menu that was // popped up on the page until a new one is created. We need to clear // this menu before propagating the event through the DOM so that we can // detect if we create a new menu for this event, since we won't create // a new menu if the DOM swallows the event and the defaultEventHandler does // not run. page()->contextMenuController()->clearContextMenu(); Frame* focused_frame = page()->focusController()->focusedOrMainFrame(); focused_frame->view()->setCursor(pointerCursor()); WebMouseEvent mouse_event; mouse_event.button = WebMouseEvent::BUTTON_RIGHT; mouse_event.x = coords.x(); mouse_event.y = coords.y(); mouse_event.type = WebInputEvent::MOUSE_UP; MakePlatformMouseEvent platform_event(view, mouse_event); context_menu_allowed_ = true; bool handled = focused_frame->eventHandler()->sendContextMenuEvent(platform_event); context_menu_allowed_ = false; return handled; } #endif bool WebViewImpl::KeyEventDefault(const WebKeyboardEvent& event) { Frame* frame = GetFocusedWebCoreFrame(); if (!frame) return false; switch (event.type) { case WebInputEvent::CHAR: { #if defined(OS_WIN) // TODO(pinkerton): hook this up for non-win32 if (event.key_code == VK_SPACE) { int key_code = ((event.modifiers & WebInputEvent::SHIFT_KEY) ? VK_PRIOR : VK_NEXT); return ScrollViewWithKeyboard(key_code); } #endif break; } case WebInputEvent::KEY_DOWN: { if (event.modifiers == WebInputEvent::CTRL_KEY) { switch (event.key_code) { case 'A': GetFocusedFrame()->SelectAll(); return true; #if defined(OS_WIN) case VK_INSERT: #endif case 'C': GetFocusedFrame()->Copy(); return true; // Match FF behavior in the sense that Ctrl+home/end are the only Ctrl // key combinations which affect scrolling. Safari is buggy in the // sense that it scrolls the page for all Ctrl+scrolling key // combinations. For e.g. Ctrl+pgup/pgdn/up/down, etc. #if defined(OS_WIN) case VK_HOME: case VK_END: #endif break; default: return false; } } #if defined(OS_WIN) if (!event.system_key) { return ScrollViewWithKeyboard(event.key_code); } #endif break; } default: break; } return false; } bool WebViewImpl::ScrollViewWithKeyboard(int key_code) { Frame* frame = GetFocusedWebCoreFrame(); if (!frame) return false; ScrollDirection scroll_direction; ScrollGranularity scroll_granularity; #if defined(OS_WIN) switch (key_code) { case VK_LEFT: scroll_direction = ScrollLeft; scroll_granularity = ScrollByLine; break; case VK_RIGHT: scroll_direction = ScrollRight; scroll_granularity = ScrollByLine; break; case VK_UP: scroll_direction = ScrollUp; scroll_granularity = ScrollByLine; break; case VK_DOWN: scroll_direction = ScrollDown; scroll_granularity = ScrollByLine; break; case VK_HOME: scroll_direction = ScrollUp; scroll_granularity = ScrollByDocument; break; case VK_END: scroll_direction = ScrollDown; scroll_granularity = ScrollByDocument; break; case VK_PRIOR: // page up scroll_direction = ScrollUp; scroll_granularity = ScrollByPage; break; case VK_NEXT: // page down scroll_direction = ScrollDown; scroll_granularity = ScrollByPage; break; default: return false; } #elif defined(OS_MACOSX) || defined(OS_LINUX) scroll_direction = ScrollDown; scroll_granularity = ScrollByLine; #endif bool scroll_handled = frame->eventHandler()->scrollOverflow(scroll_direction, scroll_granularity); Frame* current_frame = frame; while (!scroll_handled && current_frame) { scroll_handled = current_frame->view()->scroll(scroll_direction, scroll_granularity); current_frame = current_frame->tree()->parent(); } return scroll_handled; } Frame* WebViewImpl::GetFocusedWebCoreFrame() { if (!main_frame_ || !main_frame_->frame()) return NULL; return main_frame_->frame()->page()->focusController()->focusedOrMainFrame(); } // static WebViewImpl* WebViewImpl::FromPage(WebCore::Page* page) { return WebFrameImpl::FromFrame(page->mainFrame())->webview_impl(); } // WebView -------------------------------------------------------------------- bool WebViewImpl::ShouldClose() { // TODO(creis): This should really cause a recursive depth-first walk of all // frames in the tree, calling each frame's onbeforeunload. At the moment, // we're consistent with Safari 3.1, not IE/FF. Frame* frame = page_->focusController()->focusedOrMainFrame(); if (!frame) return true; return frame->shouldClose(); } void WebViewImpl::Close() { // Do this first to prevent reentrant notifications from being sent to the // initiator of the close. delegate_ = NULL; // Initiate shutdown for the entire frameset. if (main_frame_) { // This will cause a lot of notifications to be sent. main_frame_->frame()->loader()->frameDetached(); main_frame_ = NULL; } page_.reset(); } WebViewDelegate* WebViewImpl::GetDelegate() { return delegate_; } WebFrame* WebViewImpl::GetMainFrame() { return main_frame_.get(); } WebFrame* WebViewImpl::GetFocusedFrame() { Frame* frame = GetFocusedWebCoreFrame(); return frame ? WebFrameImpl::FromFrame(frame) : NULL; } void WebViewImpl::SetFocusedFrame(WebFrame* frame) { if (!frame) { // Clears the focused frame if any. Frame* frame = GetFocusedWebCoreFrame(); if (frame) frame->selection()->setFocused(false); return; } WebFrameImpl* frame_impl = static_cast<WebFrameImpl*>(frame); WebCore::Frame* webcore_frame = frame_impl->frame(); webcore_frame->page()->focusController()->setFocusedFrame(webcore_frame); } WebFrame* WebViewImpl::GetFrameWithName(const std::wstring& name) { String name_str = webkit_glue::StdWStringToString(name); Frame* frame = main_frame_->frame()->tree()->find(name_str); return frame ? WebFrameImpl::FromFrame(frame) : NULL; } WebFrame* WebViewImpl::GetPreviousFrameBefore(WebFrame* frame, bool wrap) { WebFrameImpl* frame_impl = static_cast<WebFrameImpl*>(frame); WebCore::Frame* previous = frame_impl->frame()->tree()->traversePreviousWithWrap(wrap); return previous ? WebFrameImpl::FromFrame(previous) : NULL; } WebFrame* WebViewImpl::GetNextFrameAfter(WebFrame* frame, bool wrap) { WebFrameImpl* frame_impl = static_cast<WebFrameImpl*>(frame); WebCore::Frame* next = frame_impl->frame()->tree()->traverseNextWithWrap(wrap); return next ? WebFrameImpl::FromFrame(next) : NULL; } void WebViewImpl::Resize(const gfx::Size& new_size) { if (size_ == new_size) return; size_ = new_size; if (main_frame_->frameview()) { main_frame_->frameview()->resize(size_.width(), size_.height()); main_frame_->frame()->sendResizeEvent(); } if (delegate_) { gfx::Rect damaged_rect(0, 0, size_.width(), size_.height()); delegate_->DidInvalidateRect(this, damaged_rect); } } void WebViewImpl::Layout() { if (main_frame_) { // In order for our child HWNDs (NativeWindowWidgets) to update properly, // they need to be told that we are updating the screen. The problem is // that the native widgets need to recalculate their clip region and not // overlap any of our non-native widgets. To force the resizing, call // setFrameGeometry(). This will be a quick operation for most frames, but // the NativeWindowWidgets will update a proper clipping region. FrameView* frameview = main_frame_->frameview(); if (frameview) frameview->setFrameGeometry(frameview->frameGeometry()); // setFrameGeometry may have the side-effect of causing existing page // layout to be invalidated, so layout needs to be called last. main_frame_->Layout(); } } void WebViewImpl::Paint(gfx::PlatformCanvas* canvas, const gfx::Rect& rect) { if (main_frame_) main_frame_->Paint(canvas, rect); } // TODO(eseidel): g_current_input_event should be removed once // ChromeClient:show() can get the current-event information from WebCore. /* static */ const WebInputEvent* WebViewImpl::g_current_input_event = NULL; bool WebViewImpl::HandleInputEvent(const WebInputEvent* input_event) { // If we've started a drag and drop operation, ignore input events until // we're done. if (doing_drag_and_drop_) return true; // TODO(eseidel): Remove g_current_input_event. // This only exists to allow ChromeClient::show() to know which mouse button // triggered a window.open event. // Safari must perform a similar hack, ours is in our WebKit glue layer // theirs is in the application. This should go when WebCore can be fixed // to pass more event information to ChromeClient::show() g_current_input_event = input_event; bool handled = true; // TODO(jcampan): WebKit seems to always return false on mouse events // processing methods. For now we'll assume it has processed them (as we are // only interested in whether keyboard events are processed). switch (input_event->type) { case WebInputEvent::MOUSE_MOVE: MouseMove(*static_cast<const WebMouseEvent*>(input_event)); break; case WebInputEvent::MOUSE_LEAVE: MouseLeave(*static_cast<const WebMouseEvent*>(input_event)); break; case WebInputEvent::MOUSE_WHEEL: MouseWheel(*static_cast<const WebMouseWheelEvent*>(input_event)); break; case WebInputEvent::MOUSE_DOWN: case WebInputEvent::MOUSE_DOUBLE_CLICK: MouseDown(*static_cast<const WebMouseEvent*>(input_event)); break; case WebInputEvent::MOUSE_UP: MouseUp(*static_cast<const WebMouseEvent*>(input_event)); break; case WebInputEvent::KEY_DOWN: case WebInputEvent::KEY_UP: handled = KeyEvent(*static_cast<const WebKeyboardEvent*>(input_event)); break; case WebInputEvent::CHAR: handled = CharEvent(*static_cast<const WebKeyboardEvent*>(input_event)); break; default: handled = false; } g_current_input_event = NULL; return handled; } void WebViewImpl::MouseCaptureLost() { } // TODO(darin): these navigation methods should be killed void WebViewImpl::StopLoading() { main_frame_->StopLoading(); } void WebViewImpl::SetBackForwardListSize(int size) { page_->backForwardList()->setCapacity(size); } void WebViewImpl::SetFocus(bool enable) { if (enable) { // Getting the focused frame will have the side-effect of setting the main // frame as the focused frame if it is not already focused. Otherwise, if // there is already a focused frame, then this does nothing. GetFocusedFrame(); if (main_frame_ && main_frame_->frame()) { Frame* frame = main_frame_->frame(); if (!frame->selection()->isFocusedAndActive()) { // No one has focus yet, try to restore focus. RestoreFocus(); frame->page()->focusController()->setActive(true); } Frame* focused_frame = frame->page()->focusController()->focusedOrMainFrame(); frame->selection()->setFocused(frame == focused_frame); } ime_accept_events_ = true; } else { // Clear out who last had focus. If someone has focus, the refs will be // updated below. ReleaseFocusReferences(); // Clear focus on the currently focused frame if any. if (!main_frame_) return; Frame* frame = main_frame_->frame(); if (!frame) return; RefPtr<Frame> focused = frame->page()->focusController()->focusedFrame(); if (focused.get()) { // Update the focus refs, this way we can give focus back appropriately. // It's entirely possible to have a focused document, but not a focused // node. RefPtr<Document> document = focused->document(); last_focused_frame_ = focused; if (document.get()) { RefPtr<Node> focused_node = document->focusedNode(); if (focused_node.get()) { // To workaround bug #792423, we do not blur the focused node. This // should be reenabled when we merge a WebKit that has the fix for // http://bugs.webkit.org/show_bug.cgi?id=16928. // last_focused_node_ = focused_node; // document->setFocusedNode(NULL); } } frame->page()->focusController()->setFocusedFrame(0); // Finish an ongoing composition to delete the composition node. Editor* editor = focused->editor(); if (editor && editor->hasComposition()) editor->confirmComposition(); ime_accept_events_ = false; } // Make sure the main frame doesn't think it has focus. if (frame != focused.get()) frame->selection()->setFocused(false); } } // TODO(jcampan): http://b/issue?id=1157486 this is needed to work-around // issues caused by the fix for bug #792423 and should be removed when that // bug is fixed. void WebViewImpl::StoreFocusForFrame(WebFrame* frame) { DCHECK(frame); // We only want to store focus info if we are the focused frame and if we have // not stored it already. WebCore::Frame* webcore_frame = static_cast<WebFrameImpl*>(frame)->frame(); if (last_focused_frame_.get() != webcore_frame || last_focused_node_.get()) return; // Clear out who last had focus. If someone has focus, the refs will be // updated below. ReleaseFocusReferences(); last_focused_frame_ = webcore_frame; RefPtr<Document> document = last_focused_frame_->document(); if (document.get()) { RefPtr<Node> focused_node = document->focusedNode(); if (focused_node.get()) { last_focused_node_ = focused_node; document->setFocusedNode(NULL); } } } void WebViewImpl::ImeSetComposition(int string_type, int cursor_position, int target_start, int target_end, int string_length, const wchar_t *string_data) { Frame* focused = GetFocusedWebCoreFrame(); if (!focused || !ime_accept_events_) { return; } Editor* editor = focused->editor(); if (!editor) return; if (!editor->canEdit()) { // The input focus has been moved to another WebWidget object. // We should use this |editor| object only to complete the ongoing // composition. if (!editor->hasComposition()) return; } if (string_type == 0) { // A browser process sent an IPC message which does not contain a valid // string, which means an ongoing composition has been canceled. // If the ongoing composition has been canceled, replace the ongoing // composition string with an empty string and complete it. // TODO(hbono): Need to add a new function to cancel the ongoing // composition to WebCore::Editor? WebCore::String empty_string; editor->confirmComposition(empty_string); } else { // A browser process sent an IPC message which contains a string to be // displayed in this Editor object. // To display the given string, set the given string to the // m_compositionNode member of this Editor object and display it. // NOTE: An empty string (often sent by Chinese IMEs and Korean IMEs) // causes a panic in Editor::setComposition(), which deactivates the // m_frame.m_sel member of this Editor object, i.e. we can never display // composition strings in the m_compositionNode member. // (I have not been able to find good methods for re-activating it.) // Therefore, I have to prevent from calling Editor::setComposition() // with its first argument an empty string. if (string_length > 0) { if (target_start < 0) target_start = 0; if (target_end < 0) target_end = string_length; std::wstring temp(string_data, string_length); WebCore::String composition_string(webkit_glue::StdWStringToString(temp)); // Create custom underlines. // To emphasize the selection, the selected region uses a solid black // for its underline while other regions uses a pale gray for theirs. WTF::Vector<WebCore::CompositionUnderline> underlines(3); underlines[0].startOffset = 0; underlines[0].endOffset = target_start; underlines[0].thick = true; underlines[0].color.setRGB(0xd3, 0xd3, 0xd3); underlines[1].startOffset = target_start; underlines[1].endOffset = target_end; underlines[1].thick = true; underlines[1].color.setRGB(0x00, 0x00, 0x00); underlines[2].startOffset = target_end; underlines[2].endOffset = string_length; underlines[2].thick = true; underlines[2].color.setRGB(0xd3, 0xd3, 0xd3); // When we use custom underlines, WebKit ("InlineTextBox.cpp" Line 282) // prevents from writing a text in between 'selectionStart' and // 'selectionEnd' somehow. // Therefore, we use the 'cursor_position' for these arguments so that // there are not any characters in the above region. editor->setComposition(composition_string, underlines, cursor_position, cursor_position); } #if defined(OS_WIN) // The given string is a result string, which means the ongoing // composition has been completed. I have to call the // Editor::confirmCompletion() and complete this composition. if (string_type == GCS_RESULTSTR) { editor->confirmComposition(); } #endif } } bool WebViewImpl::ImeUpdateStatus(bool* enable_ime, const void **id, int* x, int* y) { // Initialize the return values so that we can disable the IME attached // to a browser process when an error occurs while retrieving information // of the focused edit control. *enable_ime = false; *id = NULL; *x = -1; *y = -1; // Store the position of the bottom-left corner of the caret. // This process consists of the following four steps: // 1. Retrieve the selection controller of the focused frame; // 2. Retrieve the caret rectangle from the controller; // 3. Convert the rectangle, which is relative to the parent view, to the // one relative to the client window, and; // 4. Store the position of its bottom-left corner. const Frame* focused = GetFocusedWebCoreFrame(); if (!focused) return false; const Editor* editor = focused->editor(); if (!editor || !editor->canEdit()) return false; const SelectionController* controller = focused->selection(); if (!controller) return false; const Node* node = controller->start().node(); if (!node) return false; const FrameView* view = node->document()->view(); if (!view) return false; IntRect rect = view->contentsToWindow(controller->caretRect()); *x = rect.x(); *y = rect.bottom(); return true; } void WebViewImpl::RestoreFocus() { if (last_focused_frame_.get()) { if (last_focused_frame_->page()) { // last_focused_frame_ can be detached from the frame tree, thus, // its page can be null. last_focused_frame_->page()->focusController()->setFocusedFrame( last_focused_frame_.get()); } if (last_focused_node_.get()) { // last_focused_node_ may be null, make sure it's valid before trying to // focus it. static_cast<Element*>(last_focused_node_.get())->focus(); } // And clear out the refs. ReleaseFocusReferences(); } } void WebViewImpl::SetInitialFocus(bool reverse) { if (page_.get()) { // So RestoreFocus does not focus anything when it is called. ReleaseFocusReferences(); // Since we don't have a keyboard event, we'll create one. WebKeyboardEvent keyboard_event; keyboard_event.type = WebInputEvent::KEY_DOWN; if (reverse) keyboard_event.modifiers = WebInputEvent::SHIFT_KEY; // VK_TAB which is only defined on Windows. keyboard_event.key_code = 0x09; MakePlatformKeyboardEvent platform_event(keyboard_event); // We have to set the key type explicitly to avoid an assert in the // KeyboardEvent constructor. platform_event.SetKeyType(PlatformKeyboardEvent::RawKeyDown); RefPtr<KeyboardEvent> webkit_event = KeyboardEvent::create(platform_event, NULL); page()->focusController()->setInitialFocus( reverse ? WebCore::FocusDirectionBackward : WebCore::FocusDirectionForward, webkit_event.get()); } } bool WebViewImpl::FocusedFrameNeedsSpellchecking() { const WebCore::Frame* frame = GetFocusedWebCoreFrame(); if (!frame) return false; const WebCore::Document* document = frame->document(); if (!document) return false; const WebCore::Node* node = document->focusedNode(); if (!node) return false; const WebCore::RenderObject* renderer = node->renderer(); if (!renderer) return false; // We should also retrieve the contenteditable attribute of this element to // determine if this element needs spell-checking. const WebCore::EUserModify user_modify = renderer->style()->userModify(); return renderer->isTextArea() || user_modify == WebCore::READ_WRITE || user_modify == WebCore::READ_WRITE_PLAINTEXT_ONLY; } // Releases references used to restore focus. void WebViewImpl::ReleaseFocusReferences() { if (last_focused_frame_.get()) { last_focused_frame_.release(); last_focused_node_.release(); } } bool WebViewImpl::DownloadImage(int id, const GURL& image_url, int image_size) { if (!main_frame_ || !main_frame_->frame()) return false; image_fetchers_.insert( new ImageResourceFetcher(this, id, image_url, image_size)); return true; } void WebViewImpl::SetPreferences(const WebPreferences& preferences) { if (!page_.get()) return; // Keep a local copy of the preferences struct for GetPreferences. webprefs_ = preferences; Settings* settings = page_->settings(); settings->setStandardFontFamily(webkit_glue::StdWStringToString( preferences.standard_font_family)); settings->setFixedFontFamily(webkit_glue::StdWStringToString( preferences.fixed_font_family)); settings->setSerifFontFamily(webkit_glue::StdWStringToString( preferences.serif_font_family)); settings->setSansSerifFontFamily(webkit_glue::StdWStringToString( preferences.sans_serif_font_family)); settings->setCursiveFontFamily(webkit_glue::StdWStringToString( preferences.cursive_font_family)); settings->setFantasyFontFamily(webkit_glue::StdWStringToString( preferences.fantasy_font_family)); settings->setDefaultFontSize(preferences.default_font_size); settings->setDefaultFixedFontSize(preferences.default_fixed_font_size); settings->setMinimumFontSize(preferences.minimum_font_size); settings->setMinimumLogicalFontSize(preferences.minimum_logical_font_size); settings->setDefaultTextEncodingName(webkit_glue::StdWStringToString( preferences.default_encoding)); settings->setJavaScriptEnabled(preferences.javascript_enabled); settings->setJavaScriptCanOpenWindowsAutomatically( preferences.javascript_can_open_windows_automatically); settings->setLoadsImagesAutomatically( preferences.loads_images_automatically); settings->setPluginsEnabled(preferences.plugins_enabled); settings->setDOMPasteAllowed(preferences.dom_paste_enabled); settings->setDeveloperExtrasEnabled(preferences.developer_extras_enabled); settings->setShrinksStandaloneImagesToFit( preferences.shrinks_standalone_images_to_fit); settings->setUsesUniversalDetector(preferences.uses_universal_detector); settings->setTextAreasAreResizable(preferences.text_areas_are_resizable); settings->setAllowScriptsToCloseWindows( preferences.allow_scripts_to_close_windows); if (preferences.user_style_sheet_enabled) { settings->setUserStyleSheetLocation(webkit_glue::GURLToKURL( preferences.user_style_sheet_location)); } else { settings->setUserStyleSheetLocation(KURL()); } settings->setUsesPageCache(preferences.uses_page_cache); // This setting affects the behavior of links in an editable region: // clicking the link should select it rather than navigate to it. // Safari uses the same default. It is unlikley an embedder would want to // change this, since it would break existing rich text editors. settings->setEditableLinkBehavior(WebCore::EditableLinkNeverLive); settings->setFontRenderingMode(NormalRenderingMode); settings->setJavaEnabled(preferences.java_enabled); #if defined(OS_WIN) // RenderTheme is a singleton that needs to know the default font size to // draw some form controls. We let it know each time the size changes. WebCore::RenderThemeWin::setDefaultFontSize(preferences.default_font_size); #endif } const WebPreferences& WebViewImpl::GetPreferences() { return webprefs_; } // Set the encoding of the current main frame to the one selected by // a user in the encoding menu. void WebViewImpl::SetPageEncoding(const std::wstring& encoding_name) { if (!main_frame_) return; if (!encoding_name.empty()) { // only change override encoding, don't change default encoding // TODO(brettw) use std::string for encoding names. String new_encoding_name(webkit_glue::StdWStringToString(encoding_name)); main_frame_->frame()->loader()->reloadAllowingStaleData(new_encoding_name); } } // Return the canonical encoding name of current main webframe in webview. std::wstring WebViewImpl::GetMainFrameEncodingName() { if (!main_frame_) return std::wstring(L""); String encoding_name = main_frame_->frame()->loader()->encoding(); return webkit_glue::StringToStdWString(encoding_name); } void WebViewImpl::ZoomIn(bool text_only) { Frame* frame = main_frame()->frame(); double multiplier = std::min(std::pow(kTextSizeMultiplierRatio, zoom_level_ + 1), kMaxTextSizeMultiplier); float zoom_factor = static_cast<float>(multiplier); if (zoom_factor != frame->zoomFactor()) { ++zoom_level_; frame->setZoomFactor(zoom_factor, text_only); } } void WebViewImpl::ZoomOut(bool text_only) { Frame* frame = main_frame()->frame(); double multiplier = std::max(std::pow(kTextSizeMultiplierRatio, zoom_level_ - 1), kMinTextSizeMultiplier); float zoom_factor = static_cast<float>(multiplier); if (zoom_factor != frame->zoomFactor()) { --zoom_level_; frame->setZoomFactor(zoom_factor, text_only); } } void WebViewImpl::ResetZoom() { // We don't change the zoom mode (text only vs. full page) here. We just want // to reset whatever is already set. zoom_level_ = 0; main_frame()->frame()->setZoomFactor( 1.0f, main_frame()->frame()->isZoomFactorTextOnly()); } void WebViewImpl::CopyImageAt(int x, int y) { IntPoint point = IntPoint(x, y); Frame* frame = main_frame_->frame(); if (!frame) return; HitTestResult result = frame->eventHandler()->hitTestResultAtPoint(point, false); if (result.absoluteImageURL().isEmpty()) { // There isn't actually an image at these coordinates. Might be because // the window scrolled while the context menu was open or because the page // changed itself between when we thought there was an image here and when // we actually tried to retreive the image. // // TODO: implement a cache of the most recent HitTestResult to avoid having // to do two hit tests. return; } frame->editor()->copyImage(result); } void WebViewImpl::InspectElement(int x, int y) { if (x == -1 || y == -1) { page_->inspectorController()->inspect(NULL); } else { IntPoint point = IntPoint(x, y); HitTestResult result(point); if (Frame* frame = main_frame_->frame()) result = frame->eventHandler()->hitTestResultAtPoint(point, false); if (!result.innerNonSharedNode()) return; page_->inspectorController()->inspect(result.innerNonSharedNode()); } } void WebViewImpl::ShowJavaScriptConsole() { page_->inspectorController()->showPanel(InspectorController::ConsolePanel); } void WebViewImpl::DragSourceEndedAt( int client_x, int client_y, int screen_x, int screen_y) { PlatformMouseEvent pme(IntPoint(client_x, client_y), IntPoint(screen_x, screen_y), NoButton, MouseEventMoved, 0, false, false, false, false, 0); main_frame_->frame()->eventHandler()->dragSourceEndedAt(pme, DragOperationCopy); } void WebViewImpl::DragSourceMovedTo( int client_x, int client_y, int screen_x, int screen_y) { PlatformMouseEvent pme(IntPoint(client_x, client_y), IntPoint(screen_x, screen_y), LeftButton, MouseEventMoved, 0, false, false, false, false, 0); main_frame_->frame()->eventHandler()->dragSourceMovedTo(pme); } void WebViewImpl::DragSourceSystemDragEnded() { page_->dragController()->dragEnded(); DCHECK(doing_drag_and_drop_); doing_drag_and_drop_ = false; } bool WebViewImpl::DragTargetDragEnter(const WebDropData& drop_data, int client_x, int client_y, int screen_x, int screen_y) { DCHECK(!current_drop_data_.get()); // Copy drop_data into current_drop_data_. WebDropData* drop_data_copy = new WebDropData; *drop_data_copy = drop_data; current_drop_data_.reset(drop_data_copy); DragData drag_data(reinterpret_cast<DragDataRef>(current_drop_data_.get()), IntPoint(client_x, client_y), IntPoint(screen_x, screen_y), kDropTargetOperation); DragOperation effect = page_->dragController()->dragEntered(&drag_data); return effect != DragOperationNone; } bool WebViewImpl::DragTargetDragOver( int client_x, int client_y, int screen_x, int screen_y) { DCHECK(current_drop_data_.get()); DragData drag_data(reinterpret_cast<DragDataRef>(current_drop_data_.get()), IntPoint(client_x, client_y), IntPoint(screen_x, screen_y), kDropTargetOperation); DragOperation effect = page_->dragController()->dragUpdated(&drag_data); return effect != DragOperationNone; } void WebViewImpl::DragTargetDragLeave() { DCHECK(current_drop_data_.get()); DragData drag_data(reinterpret_cast<DragDataRef>(current_drop_data_.get()), IntPoint(), IntPoint(), DragOperationNone); page_->dragController()->dragExited(&drag_data); current_drop_data_.reset(NULL); } void WebViewImpl::DragTargetDrop( int client_x, int client_y, int screen_x, int screen_y) { DCHECK(current_drop_data_.get()); DragData drag_data(reinterpret_cast<DragDataRef>(current_drop_data_.get()), IntPoint(client_x, client_y), IntPoint(screen_x, screen_y), kDropTargetOperation); page_->dragController()->performDrag(&drag_data); current_drop_data_.reset(NULL); } SearchableFormData* WebViewImpl::CreateSearchableFormDataForFocusedNode() { if (!main_frame_) return NULL; Frame* frame = main_frame_->frame(); if (!frame) return NULL; if (RefPtr<Frame> focused = frame->page()->focusController()->focusedFrame()) { RefPtr<Document> document = focused->document(); if (document.get()) { RefPtr<Node> focused_node = document->focusedNode(); if (focused_node.get() && focused_node->nodeType() == Node::ELEMENT_NODE) { return SearchableFormData::Create( static_cast<Element*>(focused_node.get())); } } } return NULL; } void WebViewImpl::DidCommitLoad(bool* is_new_navigation) { if (is_new_navigation) *is_new_navigation = observed_new_navigation_; #ifndef NDEBUG DCHECK(!observed_new_navigation_ || main_frame_->frame()->loader()->documentLoader() == new_navigation_loader_); new_navigation_loader_ = NULL; #endif observed_new_navigation_ = false; } void WebViewImpl::StartDragging(const WebDropData& drop_data) { if (delegate_) { DCHECK(!doing_drag_and_drop_); doing_drag_and_drop_ = true; delegate_->StartDragging(this, drop_data); } } const WebCore::Node* WebViewImpl::getInspectedNode(WebCore::Frame* frame) { DCHECK(frame); WebFrameImpl* webframe_impl = WebFrameImpl::FromFrame(frame); if (!webframe_impl) return NULL; return webframe_impl->inspected_node(); } void WebViewImpl::ImageResourceDownloadDone(ImageResourceFetcher* fetcher, bool errored, const SkBitmap& image) { if (delegate_) { delegate_->DidDownloadImage(fetcher->id(), fetcher->image_url(), errored, image); } DeleteImageResourceFetcher(fetcher); } //----------------------------------------------------------------------------- // WebCore::WidgetClientWin gfx::ViewHandle WebViewImpl::containingWindow() { return delegate_ ? delegate_->GetContainingWindow(this) : NULL; } void WebViewImpl::invalidateRect(const IntRect& damaged_rect) { if (delegate_) delegate_->DidInvalidateRect(this, gfx::Rect(damaged_rect.x(), damaged_rect.y(), damaged_rect.width(), damaged_rect.height())); } void WebViewImpl::scrollRect(int dx, int dy, const IntRect& clip_rect) { if (delegate_) delegate_->DidScrollRect(this, dx, dy, gfx::Rect(clip_rect.x(), clip_rect.y(), clip_rect.width(), clip_rect.height())); } void WebViewImpl::popupOpened(WebCore::Widget* widget, const WebCore::IntRect& bounds) { if (!delegate_) return; WebWidgetImpl* webwidget = static_cast<WebWidgetImpl*>(delegate_->CreatePopupWidget(this)); webwidget->Init(widget, gfx::Rect(bounds.x(), bounds.y(), bounds.width(), bounds.height())); } void WebViewImpl::popupClosed(WebCore::Widget* widget) { NOTREACHED() << "popupClosed called on a non-popup"; } void WebViewImpl::setCursor(const WebCore::Cursor& cursor) { #if defined(OS_WIN) // TODO(pinkerton): figure out the cursor delegate methods if (delegate_) delegate_->SetCursor(this, cursor.impl()); #endif } void WebViewImpl::setFocus() { if (delegate_) delegate_->Focus(this); } const SkBitmap* WebViewImpl::getPreloadedResourceBitmap(int resource_id) { if (!delegate_) return NULL; return delegate_->GetPreloadedResourceBitmap(resource_id); } void WebViewImpl::onScrollPositionChanged(WebCore::Widget* widget) { // Scroll position changes should be reflected in the session history. if (delegate_) delegate_->OnNavStateChanged(this); } const WTF::Vector<RefPtr<WebCore::Range> >* WebViewImpl::getTickmarks( WebCore::Frame* frame) { DCHECK(frame); WebFrameImpl* webframe_impl = WebFrameImpl::FromFrame(frame); if (!webframe_impl) return NULL; return &webframe_impl->tickmarks(); } size_t WebViewImpl::getActiveTickmarkIndex(WebCore::Frame* frame) { DCHECK(frame); WebFrameImpl* webframe_impl = WebFrameImpl::FromFrame(frame); if (!webframe_impl) return kNoTickmark; // The mainframe can tell us if we are the frame with the active tick-mark. if (webframe_impl != main_frame_->active_tickmark_frame()) return kNoTickmark; return webframe_impl->active_tickmark_index(); } bool WebViewImpl::isHidden() { if (!delegate_) return true; return delegate_->IsHidden(); } //----------------------------------------------------------------------------- // WebCore::BackForwardListClient void WebViewImpl::didAddHistoryItem(WebCore::HistoryItem* item) { // If WebCore adds a new HistoryItem, it means this is a new navigation // (ie, not a reload or back/forward). observed_new_navigation_ = true; #ifndef NDEBUG new_navigation_loader_ = main_frame_->frame()->loader()->documentLoader(); #endif delegate_->DidAddHistoryItem(); } void WebViewImpl::willGoToHistoryItem(WebCore::HistoryItem* item) { if (pending_history_item_) { if (item == pending_history_item_->GetHistoryItem()) { // Let the main frame know this HistoryItem is loading, so it can cache // any ExtraData when the DataSource is created. main_frame_->set_currently_loading_history_item(pending_history_item_); pending_history_item_ = 0; } } } WebCore::HistoryItem* WebViewImpl::itemAtIndex(int index) { if (!delegate_) return NULL; WebHistoryItem* item = delegate_->GetHistoryEntryAtOffset(index); if (!item) return NULL; // If someone has asked for a history item, we probably want to navigate to // it soon. Keep track of it until willGoToHistoryItem is called. pending_history_item_ = static_cast<WebHistoryItemImpl*>(item); return pending_history_item_->GetHistoryItem(); } void WebViewImpl::goToItemAtIndexAsync(int index) { if (delegate_) delegate_->GoToEntryAtOffsetAsync(index); } int WebViewImpl::backListCount() { if (!delegate_) return 0; return delegate_->GetHistoryBackListCount(); } int WebViewImpl::forwardListCount() { if (!delegate_) return 0; return delegate_->GetHistoryForwardListCount(); } void WebViewImpl::DeleteImageResourceFetcher(ImageResourceFetcher* fetcher) { DCHECK(image_fetchers_.find(fetcher) != image_fetchers_.end()); image_fetchers_.erase(fetcher); // We're in the callback from the ImageResourceFetcher, best to delay // deletion. MessageLoop::current()->DeleteSoon(FROM_HERE, fetcher); }
34.846204
85
0.700648
bluebellzhy
e3bc79b0f9040490764ff23d0f70014fcb2cadeb
3,510
cpp
C++
scisim/ConstrainedMaps/ImpactMaps/LCPOperatorQL.cpp
Lyestria/scisim
e2c2abc8d38ea9b07717841782c5c723fce37ce5
[ "Apache-2.0" ]
null
null
null
scisim/ConstrainedMaps/ImpactMaps/LCPOperatorQL.cpp
Lyestria/scisim
e2c2abc8d38ea9b07717841782c5c723fce37ce5
[ "Apache-2.0" ]
null
null
null
scisim/ConstrainedMaps/ImpactMaps/LCPOperatorQL.cpp
Lyestria/scisim
e2c2abc8d38ea9b07717841782c5c723fce37ce5
[ "Apache-2.0" ]
null
null
null
// LCPOperatorQL.cpp // // Breannan Smith // Last updated: 09/03/2015 #include "LCPOperatorQL.h" #include "ImpactOperatorUtilities.h" #include "scisim/Utilities.h" #include "scisim/Math/QL/QLUtilities.h" #include <iostream> #ifndef NDEBUG #include <typeinfo> #endif LCPOperatorQL::LCPOperatorQL( const scalar& eps ) : m_tol( eps ) { assert( m_tol >= 0.0 ); } LCPOperatorQL::LCPOperatorQL( std::istream& input_stream ) : m_tol( Utilities::deserialize<scalar>( input_stream ) ) { assert( m_tol >= 0.0 ); } static int solveQP( const scalar& tol, MatrixXXsc& C, VectorXs& dvec, VectorXs& alpha ) { static_assert( std::is_same<scalar,double>::value, "QL only supports doubles." ); assert( dvec.size() == alpha.size() ); // All constraints are bound constraints. int m = 0; int me = 0; int mmax = 0; // C should be symmetric assert( ( C - C.transpose() ).lpNorm<Eigen::Infinity>() < 1.0e-14 ); // Number of degrees of freedom. assert( C.rows() == C.cols() ); int n{ int( C.rows() ) }; int nmax = n; int mnn = m + n + n; assert( dvec.size() == nmax ); // Impose non-negativity constraints on all variables Eigen::VectorXd xl = Eigen::VectorXd::Zero( nmax ); Eigen::VectorXd xu = Eigen::VectorXd::Constant( nmax, std::numeric_limits<double>::infinity() ); // u will contain the constraint multipliers Eigen::VectorXd u( mnn ); // Status of the solve int ifail = -1; // Use the built-in cholesky decomposition int mode = 1; // Some fortran output stuff int iout = 0; // 1 => print output, 0 => silent int iprint = 1; // Working space assert( m == 0 && me == 0 && mmax == 0 ); int lwar = 3 * ( nmax * nmax ) / 2 + 10 * nmax + 2; Eigen::VectorXd war( lwar ); // Additional working space int liwar = n; Eigen::VectorXi iwar( liwar ); { scalar tol_local = tol; ql_( &m, &me, &mmax, &n, &nmax, &mnn, C.data(), dvec.data(), nullptr, nullptr, xl.data(), xu.data(), alpha.data(), u.data(), &tol_local, &mode, &iout, &ifail, &iprint, war.data(), &lwar, iwar.data(), &liwar ); } return ifail; } void LCPOperatorQL::flow( const std::vector<std::unique_ptr<Constraint>>& cons, const SparseMatrixsc& M, const SparseMatrixsc& Minv, const VectorXs& q0, const VectorXs& v0, const VectorXs& v0F, const SparseMatrixsc& N, const SparseMatrixsc& Q, const VectorXs& nrel, const VectorXs& CoR, VectorXs& alpha ) { // Q in 1/2 \alpha^T Q \alpha assert( Q.rows() == Q.cols() ); MatrixXXsc Qdense = Q; // Linear term in the objective VectorXs Adense; ImpactOperatorUtilities::computeLCPQPLinearTerm( N, nrel, CoR, v0, v0F, Adense ); // Solve the QP assert( Qdense.rows() == Adense.size() ); assert( Adense.size() == alpha.size() ); const int status = solveQP( m_tol, Qdense, Adense, alpha ); // Check for problems if( 0 != status ) { std::cerr << "Warning, failed to solve QP in LCPOperatorQL::flow: " << QLUtilities::QLReturnStatusToString(status) << std::endl; } // TODO: Sanity check the solution here } std::string LCPOperatorQL::name() const { return "lcp_ql"; } std::unique_ptr<ImpactOperator> LCPOperatorQL::clone() const { return std::unique_ptr<ImpactOperator>{ new LCPOperatorQL{ m_tol } }; } void LCPOperatorQL::serialize( std::ostream& output_stream ) const { Utilities::serialize( m_tol, output_stream ); }
24.893617
304
0.626781
Lyestria
e3bf11e48c2d07b1e38485a161fe12d0eafed05c
13,909
cpp
C++
EvolvedVirtualCreatures/genoype/GenotypeParser.cpp
jjuiddong/KarlSims
e05108eb7d2e68bfe0a90a7550eba727424081b6
[ "MIT" ]
5
2016-10-12T12:54:58.000Z
2022-01-07T17:34:33.000Z
EvolvedVirtualCreatures/genoype/GenotypeParser.cpp
jjuiddong/KarlSims
e05108eb7d2e68bfe0a90a7550eba727424081b6
[ "MIT" ]
null
null
null
EvolvedVirtualCreatures/genoype/GenotypeParser.cpp
jjuiddong/KarlSims
e05108eb7d2e68bfe0a90a7550eba727424081b6
[ "MIT" ]
2
2016-02-02T18:01:20.000Z
2018-04-16T17:15:59.000Z
#include "stdafx.h" #include "GenotypeParser.h" #include <iostream> using namespace evc; using namespace evc::genotype_parser; using namespace std; genotype_parser::CGenotypeParser::CGenotypeParser() { m_pScan = new CGenotypeScanner(); m_IsTrace = false; m_IsErrorOccur = false; } genotype_parser::CGenotypeParser::~CGenotypeParser() { SAFE_DELETE(m_pScan); } /** @brief @date 2013-12-05 */ genotype_parser::SExpr* genotype_parser::CGenotypeParser::Parse( const string &fileName, bool isTrace ) { if( !m_pScan->LoadFile(fileName.c_str(), isTrace) ) return NULL; m_fileName = fileName; m_Token = m_pScan->GetToken(); if (ENDFILE == m_Token) { m_pScan->Clear(); return NULL; } { // Parsing ~ SExprList *root = start(); while (root) { SExprList *tmp = root; root = root->next; SAFE_DELETE(tmp); } } if (ENDFILE != m_Token) { SyntaxError( " code ends before file " ); m_pScan->Clear(); return NULL; } if (m_IsErrorOccur) return NULL; if (m_SymTable.find("main") == m_SymTable.end()) { SyntaxError( " Not Exist 'main' node" ); m_pScan->Clear(); RemoveNotRefExpression(); return NULL; } SExpr *pMainExpr = m_SymTable[ "main"]; m_RefCount.clear(); Build(pMainExpr); RemoveNotRefExpression(); return pMainExpr; } /** @brief start -> expression; @date 2013-12-05 */ SExprList* genotype_parser::CGenotypeParser::start() { return expression_list(); } /** @brief expression -> id ( id, vec3, material, mass, [randshape,] [connection-list] ) | id; @date 2013-12-05 */ SExpr* genotype_parser::CGenotypeParser::expression() { SExpr *pexpr = NULL; if ((ID == m_Token) && (LPAREN == m_pScan->GetTokenQ(1))) { pexpr = new SExpr; pexpr->refCount = 0; pexpr->connection = NULL; pexpr->randShape = SVec3(0,0,0); pexpr->id = id(); Match(LPAREN); pexpr->shape = id(); Match(COMMA); pexpr->dimension = vec3(); Match(COMMA); pexpr->material = material(); Match(COMMA); pexpr->mass = mass(); if (m_SymTable.find(pexpr->id) == m_SymTable.end()) { m_SymTable[ pexpr->id] = pexpr; } else { SyntaxError( "already exist expression = '%s' ", pexpr->id.c_str() ); } if (COMMA == m_Token) Match(COMMA); pexpr->randShape = randshape(); if (COMMA == m_Token) Match(COMMA); pexpr->connection = connection_list(); Match(RPAREN); } else if (ID == m_Token) { const string Id = id(); if (m_SymTable.find(Id) == m_SymTable.end()) { SyntaxError( "not found expression = '%s' ", Id.c_str() ); } else { pexpr = m_SymTable[ Id]; } } return pexpr; } /** @brief expression-list -> [ expression {, expression } ]; @date 2013-12-05 */ SExprList* genotype_parser::CGenotypeParser::expression_list() { SExpr *pexpr = expression(); if (!pexpr) return NULL; SExprList *plist = new SExprList; plist->expr = pexpr; if (COMMA == m_Token) Match(COMMA); plist->next = expression_list(); return plist; } /** @brief connection -> connection( id, vec3, quat, vec3, limit, velocity, period, [randpos,] [randorient,] [terminalonly,] expression ) @date 2013-12-07 */ SConnection* genotype_parser::CGenotypeParser::connection() { SConnection *connct = NULL; if (ID != m_Token) return NULL; const string tok =m_pScan->GetTokenStringQ(0); if (!boost::iequals(tok, "joint") && !boost::iequals(tok, "sensor")) { SyntaxError( "must declare %s -> 'joint / sensor' ", tok.c_str() ); return NULL; } connct = new SConnection; connct->conType = id(); connct->terminalOnly = false; Match(LPAREN); connct->type = id(); Match(COMMA); connct->jointAxis = vec3(); //connct->parentOrient = quat(); Match(COMMA); connct->rotate = quat(); Match(COMMA); //connct->orient = quat(); connct->orient = vec3(); Match(COMMA); //connct->pos = vec3(); //Match(COMMA); connct->limit = limit(); Match(COMMA); connct->velocity = velocity(); if (COMMA == m_Token) Match(COMMA); connct->period = period(); if (COMMA == m_Token) Match(COMMA); connct->randPos = randField(); if (COMMA == m_Token) Match(COMMA); connct->randOrient = randField(); if (COMMA == m_Token) Match(COMMA); connct->terminalOnly = terminalonly(); if (COMMA == m_Token) Match(COMMA); connct->expr = expression(); Match(RPAREN); return connct; } /** @brief connection-list -> [connection {, connection}]; @date 2013-12-07 */ SConnectionList* genotype_parser::CGenotypeParser::connection_list() { SConnection *connct = connection(); if (!connct) return NULL; SConnectionList *plist = new SConnectionList; plist->connect = connct; if (COMMA == m_Token) Match(COMMA); plist->next = connection_list(); return plist; } /** @brief vec3 -> vec3( num, num, num ) ; @date 2013-12-05 */ SVec3 genotype_parser::CGenotypeParser::vec3() { SVec3 v; v.x = v.y = v.z = 0.f; if (ID == m_Token) { const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "vec3")) { Match(ID); Match(LPAREN); if (RPAREN != m_Token) { v.x = (float)atof(number().c_str()); Match(COMMA); v.y = (float)atof(number().c_str()); Match(COMMA); v.z = (float)atof(number().c_str()); } Match(RPAREN); } else { SyntaxError( "undeclare token %s, must declare 'vec3'\n", m_pScan->GetTokenStringQ(0).c_str() ); } } else { SyntaxError( "vec3 type need id string\n" ); } return v; } /** @brief quat -> quat(num, vec3) | quat() ; @date 2013-12-08 */ SQuat genotype_parser::CGenotypeParser::quat() { SQuat quat; quat.angle = 0; quat.dir.x = quat.dir.y = quat.dir.z = 0.f; if (ID == m_Token) { const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "quat")) { Match(ID); Match(LPAREN); if (RPAREN != m_Token) { quat.angle = (float)atof(number().c_str()); Match(COMMA); quat.dir = vec3(); } Match(RPAREN); } else { SyntaxError( "undeclare token %s, must declare 'quat'\n", m_pScan->GetTokenStringQ(0).c_str() ); } } else { SyntaxError( "quat type need id string\n" ); } return quat; } /** @brief limit -> limit(num, num, num) @date 2013-12-07 */ SVec3 genotype_parser::CGenotypeParser::limit() { SVec3 v; v.x = v.y = v.z = 0.f; if (ID != m_Token) { SyntaxError( "limit type need limit \n" ); return v; } const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "limit")) { Match(ID); Match(LPAREN); v.x = (float)atof(number().c_str()); Match(COMMA); v.y = (float)atof(number().c_str()); Match(COMMA); v.z = (float)atof(number().c_str()); Match(RPAREN); } else { SyntaxError( "undeclare token %s, must declare 'limit'\n", m_pScan->GetTokenStringQ(0).c_str() ); } return v; } /** @brief material -> material( rgbValue ) @date 2013-12-07 */ SVec3 genotype_parser::CGenotypeParser::material() { if (ID != m_Token) return SVec3(0.5f, 0.5f, 0.5f); SVec3 ret(0.5f, 0.5f, 0.5f); const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "material")) { Match(ID); Match(LPAREN); ret = rgbValue(); Match(RPAREN); } else { SyntaxError( "undeclare token %s, must declare 'material'\n", m_pScan->GetTokenStringQ(0).c_str() ); } return ret; } // material_arg -> id | rgb SVec3 genotype_parser::CGenotypeParser::rgbValue() { SVec3 v; v.x = v.y = v.z = 0.f; if (ID == m_Token) { const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "rgb")) { Match(ID); Match(LPAREN); v.x = (float)atof(number().c_str()); Match(COMMA); v.y = (float)atof(number().c_str()); Match(COMMA); v.z = (float)atof(number().c_str()); Match(RPAREN); } else if (boost::iequals(tok, "grey")) { Match(ID); v.x = 0.5f, v.y = 0.5f, v.z = 0.5f; } else if (boost::iequals(tok, "red")) { Match(ID); v.x = 0.75f, v.y = 0, v.z = 0; } else if (boost::iequals(tok, "green")) { Match(ID); v.x = 0, v.y = 0.75f, v.z = 0; } else if (boost::iequals(tok, "blue")) { Match(ID); v.x = 0, v.y = 0, v.z = 0.75f; } else if (boost::iequals(tok, "yellow")) { Match(ID); v.x = 0.75f, v.y = 0.75f, v.z = 0; } else if (boost::iequals(tok, "white")) { Match(ID); v.x = 0.75f, v.y = 0.75f, v.z = 0.75f; } else { SyntaxError( "undeclare token %s, must declare 'rgb'\n", m_pScan->GetTokenStringQ(0).c_str() ); } } else { SyntaxError( "vec3 type need id string\n" ); } return v; } /** @brief mass -> mass(num) @date 2013-12-07 */ float genotype_parser::CGenotypeParser::mass() { if (ID != m_Token) return 0.f; float ret = 0.f; const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "mass")) { Match(ID); Match(LPAREN); ret = (float)atof(number().c_str()); Match(RPAREN); } else { SyntaxError( "undeclare token %s, must declare 'mass'\n", m_pScan->GetTokenStringQ(0).c_str() ); } return ret; } /** @brief velocity -> velocity( num ) @date 2013-12-07 */ SVec3 genotype_parser::CGenotypeParser::velocity() { SVec3 v; v.x = v.y = v.z = 0.f; if (ID != m_Token) return v; const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "velocity")) { Match(ID); Match(LPAREN); v.x = (float)atof(number().c_str()); Match(RPAREN); } else { // nothing } return v; } // period -> period(num) float genotype_parser::CGenotypeParser::period() { if (ID != m_Token) return 0.f; float ret = 0.f; const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "period")) { Match(ID); Match(LPAREN); ret = (float)atof(number().c_str()); Match(RPAREN); } else { // nothing } return ret; } /** @brief randfield -> randshape | randpos | randorient @date 2014-01-13 */ SVec3 CGenotypeParser::randField() { SVec3 v(0,0,0); const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "randpos")) { v = randpos(); } else if (boost::iequals(tok, "randorient")) { v = randorient(); } else if (boost::iequals(tok, "randshape")) { v = randshape(); } return v; } /** @brief randshape -> randshape(num, num, num) @date 2014-01-13 */ SVec3 CGenotypeParser::randshape() { SVec3 v; v.x = v.y = v.z = 0.f; if (ID != m_Token) return v; const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "randshape")) { Match(ID); Match(LPAREN); v.x = (float)atof(number().c_str()); Match(COMMA); v.y = (float)atof(number().c_str()); Match(COMMA); v.z = (float)atof(number().c_str()); Match(RPAREN); } else { // nothing } return v; } /** @brief randpos -> randpos(num, num, num) @date 2014-01-13 */ SVec3 genotype_parser::CGenotypeParser::randpos() { SVec3 v; v.x = v.y = v.z = 0.f; if (ID != m_Token) return v; const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "randpos")) { Match(ID); Match(LPAREN); v.x = (float)atof(number().c_str()); Match(COMMA); v.y = (float)atof(number().c_str()); Match(COMMA); v.z = (float)atof(number().c_str()); Match(RPAREN); } else { // nothing } return v; } /** @brief randorient -> randorient(num, num, num) @date 2014-01-13 */ SVec3 genotype_parser::CGenotypeParser::randorient() { SVec3 v; v.x = v.y = v.z = 0.f; if (ID != m_Token) return v; const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "randorient")) { Match(ID); Match(LPAREN); v.x = (float)atof(number().c_str()); Match(COMMA); v.y = (float)atof(number().c_str()); Match(COMMA); v.z = (float)atof(number().c_str()); Match(RPAREN); } else { // nothing } return v; } /** @brief terminalOnly -> terminalOnly @date 2014-01-13 */ bool CGenotypeParser::terminalonly() { if (ID != m_Token) return false; const string tok = m_pScan->GetTokenStringQ(0); if (boost::iequals(tok, "terminalOnly")) { Match(ID); return true; } return false; } /** @brief @date 2013-12-05 */ string genotype_parser::CGenotypeParser::number() { string str = ""; str = m_pScan->GetTokenStringQ(0); Match(NUM); return str; } /** @brief @date 2013-12-05 */ int genotype_parser::CGenotypeParser::num() { int n = atoi(m_pScan->GetTokenStringQ(0).c_str()); Match(NUM); return n; } /** @brief @date 2013-12-05 */ string genotype_parser::CGenotypeParser::id() { string str = m_pScan->GetTokenStringQ(0); Match( ID ); return str; } /** @brief @date 2013-12-05 */ bool genotype_parser::CGenotypeParser::Match( Tokentype t ) { if( m_Token == t ) { m_Token = m_pScan->GetToken(); } else { SyntaxError( "unexpected token -> " ); printf( "\n" ); } return true; } /** @brief @date 2013-12-05 */ void genotype_parser::CGenotypeParser::SyntaxError( char *msg, ... ) { m_IsErrorOccur = true; char buf[ 256]; va_list marker; va_start(marker, msg); vsprintf_s(buf, sizeof(buf), msg, marker); va_end(marker); stringstream ss; ss << "Syntax error at line " << m_fileName << " " << m_pScan->GetLineNo() << ": " << buf ; std::cout << ss.str() << std::endl; } /** @brief increase reference counter of SExpr structure using main expression pointer @date 2013-12-06 */ void genotype_parser::CGenotypeParser::Build( SExpr *pexpr ) { if (!pexpr) return; pexpr->refCount++; if (m_RefCount.find(pexpr->id) != m_RefCount.end()) return; // already check m_RefCount.insert(pexpr->id); SConnectionList *pnode = pexpr->connection; while (pnode) { Build(pnode->connect->expr); pnode = pnode->next; } } /** @brief remove not reference expression node @date 2013-12-06 */ void genotype_parser::CGenotypeParser::RemoveNotRefExpression() { set<string> rm; BOOST_FOREACH(auto &kv, m_SymTable) { if (kv.second->refCount <= 0) { RemoveExpressoin_OnlyExpr(kv.second); rm.insert(kv.first); } } BOOST_FOREACH(auto &key, rm) { cout << "remove not reference expression : " << key << endl; m_SymTable.erase(key); } }
17.108241
135
0.622834
jjuiddong
e3c5563ad5e846dbbfcf0aa2c002aa0cab240eb3
1,813
cpp
C++
src/nWrappedVariantMap.cpp
lucaspcamargo/neiatree
0da0ff4f06fb650885eda10830f59cd48e23e12f
[ "BSD-2-Clause" ]
1
2017-11-13T06:55:27.000Z
2017-11-13T06:55:27.000Z
src/nWrappedVariantMap.cpp
lucaspcamargo/neiatree
0da0ff4f06fb650885eda10830f59cd48e23e12f
[ "BSD-2-Clause" ]
null
null
null
src/nWrappedVariantMap.cpp
lucaspcamargo/neiatree
0da0ff4f06fb650885eda10830f59cd48e23e12f
[ "BSD-2-Clause" ]
null
null
null
#include "nWrappedVariantMap.h" #include "../util/nIODefines.h" #define nWRAPPED_VARIANT_MAP_VERSION 1 nWrappedVariantMap::nWrappedVariantMap(QObject *parent) : QObject(parent) { } nWrappedVariantMap::nWrappedVariantMap(QIODevice * device, QObject *parent) : QObject(parent) { load(device); } void nWrappedVariantMap::load(QIODevice * device) { bool opened = false; if(!device->isOpen()) { opened = true; device->open(QIODevice::ReadOnly); } QVariantMap map; { QDataStream in(device); in.setVersion(nQT_DATA_STREAM_VERSION); quint32 magicNum; quint8 version; in >> magicNum; in >> version; if(magicNum != nMAGIC_NUM_WRAPPED_VARIANT_MAP) throw "nWrappedVariantMap::load(QIODevice * device): Error reading stream: wrong magic number."; if(version != nWRAPPED_VARIANT_MAP_VERSION) throw "nWrappedVariantMap::load(QIODevice * device): Error reading stream: unrecognized version."; in >> map; } m_name = map["name"].toString(); m_version = map["version"].toString(); m_type = map["type"].toString(); m_map = map["map"].toMap(); if(opened)device->close(); } void nWrappedVariantMap::save(QIODevice * device) { bool opened = false; if(!device->isOpen()) { opened = true; device->open(QIODevice::WriteOnly); } QVariantMap map; map["name"] = m_name; map["version"] = m_version; map["type"] = m_type; map["map"] = m_map; { QDataStream out(device); out.setVersion(nQT_DATA_STREAM_VERSION); out << quint32(nMAGIC_NUM_WRAPPED_VARIANT_MAP); out << quint8(nWRAPPED_VARIANT_MAP_VERSION); out << map; } if(opened)device->close(); }
21.583333
110
0.623828
lucaspcamargo
e3cb5b87104a4b9b4de93e8bc6a87325f9879f7b
4,370
cpp
C++
src/matrix.cpp
pradeep0295/MINI-DATABASE
34e9e568b40dd82dab0c1963073c9a5d627937c2
[ "MIT" ]
null
null
null
src/matrix.cpp
pradeep0295/MINI-DATABASE
34e9e568b40dd82dab0c1963073c9a5d627937c2
[ "MIT" ]
null
null
null
src/matrix.cpp
pradeep0295/MINI-DATABASE
34e9e568b40dd82dab0c1963073c9a5d627937c2
[ "MIT" ]
null
null
null
#include "matrix.h" using namespace std; Matrix::Matrix(string matrixName) { // logger.log("Matrix::Matrix"); this->sourceFileName = "../data/" + matrixName + ".csv"; this->matrixName = matrixName; } bool Matrix::load(){ // logger.log("Matrix::load"); fstream fin(this->sourceFileName, ios::in); uint colcount = 0; char c; while(fin.get(c)){ if(c=='\n') break; if(c==',') colcount++; } this->noOfRows = colcount+1; this->noOfColumns = colcount+1; if(this->noOfRows < this->maxRowsPerBlock){ this->maxRowsPerBlock = this->noOfRows; this->maxColumnsPerBlock = this->noOfColumns; } this->rowBlockCount = ceil((double)this->noOfRows/this->maxColumnsPerBlock);// + (this->noOfRows%this->maxColumnsPerBlock)?1:0; this->columnBlockCount = this->rowBlockCount; if(this->blockify()) return true; fin.close(); return false; } bool Matrix::blockify(){ // logger.log("Matrix::blockify"); ifstream fin(this->sourceFileName); string word; pair<uint,uint> PageIndex={0,0}; for(int i=0;i< this->noOfRows;i++){ vector<int> rowOfPage; for(int j=0; j< this->noOfColumns; j++){ word=""; char c; while(fin.get(c)){ if(c==',' or c=='\n') break; word+=c; } stringstream s(word); int temp; s>>temp; rowOfPage.push_back(temp); if(j%noOfColumns == this->maxColumnsPerBlock-1 || j == this->noOfColumns-1){ writeRowInPage(PageIndex,rowOfPage); PageIndex.second++; } } PageIndex.second = 0; if(i%noOfRows == this->maxRowsPerBlock-1) PageIndex.first++; } return true; } void Matrix::writeRowInPage(pair<uint,uint> PageIndex,vector<int> &rowOfPage){ int row=PageIndex.first; int col=PageIndex.second; string pageName="../data/temp/page_"+to_string(row)+"_"+to_string(col); fstream fout(pageName,ios::binary|ios::app); int32_t num; for(int i=0;i<rowOfPage.size();i++){ num=rowOfPage[i]; fout.write((char*) &num,sizeof(num)); } fout.close(); } vector<vector<int>> Matrix::GetPage(int r,int c){ auto ind = getIndex(r,c); cout<<ind.first<<endl; cout<<ind.second<<endl; int rows= maxRowsPerBlock, cols= maxColumnsPerBlock; if(ind.first == rowBlockCount-1 && noOfRows%maxRowsPerBlock) rows = noOfRows%maxRowsPerBlock; if(ind.second == columnBlockCount-1 && noOfRows%maxRowsPerBlock) cols = noOfColumns%maxColumnsPerBlock; string pageName="../data/temp/page_"+to_string(ind.first)+"_"+to_string(ind.second); ifstream fin(pageName,ios::binary); int32_t num; vector<vector<int>> res(rows,std::vector<int>(cols)); for(int i=0;i<rows and fin ;i++) for(int j=0;j<cols and fin;j++){ fin.read((char*) &num, sizeof(num)); res[i][j]=num; // cout<<res[i][j]<<endl; } fin.close(); return res; } void Matrix::writeBackPage(vector<vector<int>> &matrix,int row, int col){ string pageName="../data/temp/page_"+to_string(row)+"_"+to_string(col); ofstream fout(pageName,ios::binary); int32_t num; int Rows=matrix.size(); int Columns=matrix[0].size(); for(int i=0;i<Rows and fout ;i++) for(int j=0;j<Columns and fout;j++){ num=matrix[i][j]; fout.write((char*) &num, sizeof(num)); } fout.close(); } pair<uint,uint> Matrix::getIndex(int i, int j){ if(this->is_transposed) return {j,i}; return {i,j}; } vector<vector<int>> Matrix::transposePage(vector<vector<int>> &matrix){ vector<vector<int>> tmatrix(matrix.size(), vector<int>(matrix[0].size())); cout<<matrix.size()<<matrix[0].size()<<endl; for(int i=0;i<matrix.size();i++){ for(int j=0;j<matrix[0].size();j++){ tmatrix[i][j] = matrix[j][i]; } // cout<<endl; } return tmatrix; } void Matrix::transpose(){ for(int i=0;i< this->rowBlockCount;i++){ for(int j=0;j< this->columnBlockCount;j++){ vector<vector<int>> matrixPage = GetPage(i,j); matrixPage = transposePage(matrixPage); writeBackPage(matrixPage,i,j); } } this->is_transposed = !this->is_transposed; } // int main(){ // Matrix A("z"); // A.load(); // A.transpose(); // }
26.646341
131
0.59405
pradeep0295
e3cd8e50ad33d6a2b481363f1eda813086603b0a
2,706
cpp
C++
Tests/unit/core/test_parser.cpp
mrcomcast123/Thunder
21d827ad7da0f3bf805d0eaf4b0759d1846c1e3b
[ "Apache-2.0" ]
null
null
null
Tests/unit/core/test_parser.cpp
mrcomcast123/Thunder
21d827ad7da0f3bf805d0eaf4b0759d1846c1e3b
[ "Apache-2.0" ]
null
null
null
Tests/unit/core/test_parser.cpp
mrcomcast123/Thunder
21d827ad7da0f3bf805d0eaf4b0759d1846c1e3b
[ "Apache-2.0" ]
null
null
null
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 RDK Management * * 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 "../IPTestAdministrator.h" #include <gtest/gtest.h> #include <core/core.h> using namespace WPEFramework; using namespace WPEFramework::Core; class Deserializer { private: typedef ParserType<TerminatorCarriageReturnLineFeed, Deserializer> Parser; public : Deserializer() : _parser(*this) { } void operations() { _parser.Reset(); _parser.CollectWord(); _parser.CollectWord('/'); _parser.CollectWord(Core::ParserType<TerminatorCarriageReturnLineFeed, Deserializer>::ParseState::UPPERCASE); _parser.CollectWord('/',Core::ParserType<TerminatorCarriageReturnLineFeed, Deserializer>::ParseState::UPPERCASE); _parser.CollectLine(); _parser.CollectLine(Core::ParserType<TerminatorCarriageReturnLineFeed, Deserializer>::ParseState::UPPERCASE); _parser.FlushLine(); _parser.PassThrough(5); } ~Deserializer() { } private: Parser _parser; }; TEST(test_parser_type, simple_parser_type) { Deserializer deserializer; deserializer.operations(); } TEST(test_text_parser, simple_text_parser) { TextFragment inputLine("/Service/testing/parsertest"); TextParser textparser(inputLine); textparser.Skip(2); textparser.Skip('S'); textparser.Find(_T("e")); textparser.SkipWhiteSpace(); textparser.SkipLine(); OptionalType<TextFragment> token; textparser.ReadText(token, _T("/")); } TEST(test_path_parser, simple_path_parser) { TextFragment inputFile("C://Service/testing/pathparsertest.txt"); PathParser pathparser(inputFile); EXPECT_EQ(pathparser.Drive().Value(),'C'); EXPECT_STREQ(pathparser.Path().Value().Text().c_str(),_T("//Service/testing")); EXPECT_STREQ(pathparser.FileName().Value().Text().c_str(),_T("pathparsertest.txt")); EXPECT_STREQ(pathparser.BaseFileName().Value().Text().c_str(),_T("pathparsertest")); EXPECT_STREQ(pathparser.Extension().Value().Text().c_str(),_T("txt"));; }
30.404494
121
0.712121
mrcomcast123
e3d064a029d3dcd4f0eccffdff63a1ae8d446981
434
cc
C++
algorithm/modifying/remove.cc
HelloCodeMing/ToySTL
8221688f8674ab214e3e57abe262b02f952c8036
[ "MIT" ]
1
2015-09-11T00:33:43.000Z
2015-09-11T00:33:43.000Z
algorithm/modifying/remove.cc
HelloCodeMing/ToySTL
8221688f8674ab214e3e57abe262b02f952c8036
[ "MIT" ]
null
null
null
algorithm/modifying/remove.cc
HelloCodeMing/ToySTL
8221688f8674ab214e3e57abe262b02f952c8036
[ "MIT" ]
null
null
null
#include <predef.hpp> template <class Iter, class T> Iter remove(Iter first, Iter last, const T& value) { for (auto iter = first; iter != last; ++iter) { if (*iter != value) *first++ = *iter; } return first; } int main() { std::string str = "hey, *****."; assert(std::string( str.begin(), ::remove(str.begin(), str.end(), '*')) == "hey, ."); return 0; }
20.666667
67
0.486175
HelloCodeMing
e3d0ad501d0f03b2972c296f03686a83f25b9f19
8,713
hxx
C++
BTech Project/Code/OpacityFunctionGeneration.hxx
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
BTech Project/Code/OpacityFunctionGeneration.hxx
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
BTech Project/Code/OpacityFunctionGeneration.hxx
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
#pragma once #ifndef OpacityFunctionGeneration_hxx #define OpacityFunctionGeneration_hxx template <typename TInputImage> OpacityFunctionGeneration<TInputImage>::OpacityFunctionGeneration(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { this->max_g = -100000; this->min_g = 100000; this->max_h = -100000; this->min_h = 100000; this->CalculateMeanFirstDirectionalDerivative(histogram, binWidth, binMinimum); this->CalculateMeanSecondDirectionalDerivative(histogram, binWidth, binMinimum); this->CalculateOpacity(histogram); this->StoreAllValues(histogram, binWidth, binMinimum); } template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::CalculateMeanFirstDirectionalDerivative(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { //calculation of g(v) this->g = (float*)calloc(histogram->GetSize(0), sizeof(float)); for (int i = 0;i < (histogram->GetSize(0));i++)//dataValue Axis { float avg_sum = 0; for (int k = 0;k < (histogram->GetSize(2));k++)//secondDerivative Axis { float sum_g = 0; int freq_g = 0; for (int j = 0;j < (histogram->GetSize(1));j++)//gradientMagnitude Axis { HistogramType::IndexType index(Dimension); index[0] = i; index[1] = j; index[2] = k; int frequency = histogram->GetFrequency(index); if (frequency != 0) { freq_g = freq_g + frequency; sum_g = sum_g + (frequency*(binMinimum[1] + j*binWidth[1])); } } if (freq_g != 0) { avg_sum = avg_sum + (sum_g / freq_g);//fix i and k then iterate over j. } } //this->g[i] = (avg_sum / (histogram->GetSize(2)));//fix i and for all the averages over k find final average. this->g[i] = avg_sum; if (this->g[i] < this->min_g) //finding min_g this->min_g = this->g[i]; if (this->g[i] > this->max_g) //finding max_g this->max_g = this->g[i]; } cout << "\nPrinting g:" << "\n"; #pragma omp parallel #pragma omp for for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "g[" << i << "]=" << this->g[i] << "\n"; } cout << "max_g=" << this->max_g << " min_g=" << this->min_g << "\n"; } template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::CalculateMeanSecondDirectionalDerivative(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { //calculation of h(v) this->h = (float*)calloc((histogram->GetSize(0)), sizeof(float)); for (int i = 0;i < (histogram->GetSize(0));i++)//dataValue Axis { float avg_sum = 0; for (int j = 0;j < (histogram->GetSize(1));j++)//gradientMagnitude Axis { float sum_h = 0; int freq_h = 0; for (int k = 0;k <(histogram->GetSize(2));k++)//secondDerivative Axis { HistogramType::IndexType index(Dimension); index[0] = i; index[1] = j; index[2] = k; int frequency = histogram->GetFrequency(index); if (frequency != 0) { freq_h = freq_h + frequency; sum_h = sum_h + (frequency*(binMinimum[2] + k*binWidth[2])); } } if (freq_h != 0) { avg_sum = avg_sum + (sum_h / freq_h);//fix i and k then iterate over j. } } //this->h[i] = (avg_sum / (histogram->GetSize(1)));//fix i and for all the averages over k find final average. this->h[i] = avg_sum; if (this->h[i] < this->min_h) //finding min_h this->min_h = this->h[i]; if (this->h[i] > this->max_h) //finding max_h this->max_h = this->h[i]; } cout << "\nPrinting h:" << "\n"; for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "h[" << i << "]=" << this->h[i] << "\n"; } cout << "max_h=" << this->max_h << " min_h=" << this->min_h << "\n"; } /*template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::CalculateMeanFirstDirectionalDerivative(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { //calculation of g(v) this->g = (float*)calloc(histogram->GetSize(0), sizeof(float)); for (int i = 0;i < (histogram->GetSize(0));i++)//dataValue Axis { float avg_sum = 0.0; float sum_g = 0.0; int freq_g = 0.0; for (int k = 0;k < (histogram->GetSize(2));k++)//secondDerivative Axis { for (int j = 0;j < (histogram->GetSize(1));j++)//gradientMagnitude Axis { HistogramType::IndexType index(Dimension); index[0] = i; index[1] = j; index[2] = k; int frequency = histogram->GetFrequency(index); if (frequency != 0) { freq_g = freq_g + frequency; sum_g = sum_g + (frequency*((binMinimum[1] + j*binWidth[1])+(binWidth[1]/2))); } } /*if (freq_j != 0) { avg_sum = avg_sum + (sum_j / freq_j);//fix i and k then iterate over j. sum_k = sum_k + avg_sum*fre }*/ /*} //this->g[i] = (avg_sum / (histogram->GetSize(2)));//fix i and for all the averages over k find final average. /*if (freq_g == 0) { this->g[i] = 0.1; //just to remove the contribution of this g continue; }*/ /*this->g[i] = (float)(sum_g / freq_g); //this->g[i] = (float)(this->g[i] / histogram->GetSize[2]); if (this->g[i] < this->min_g) //finding min_g this->min_g = this->g[i]; if (this->g[i] > this->max_g) //finding max_g this->max_g = this->g[i]; } cout << "\nPrinting g:" << "\n"; #pragma omp parallel #pragma omp for for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "g[" << i << "]=" << this->g[i] << "\n"; } cout << "max_g=" << this->max_g << " min_g=" << this->min_g << "\n"; } template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::CalculateMeanSecondDirectionalDerivative(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { //calculation of h(v) this->h = (float*)calloc((histogram->GetSize(0)), sizeof(float)); for (int i = 0;i < (histogram->GetSize(0));i++)//dataValue Axis { float avg_sum = 0.0; float sum_h = 0.0; int freq_h = 0.0; for (int j = 0;j < (histogram->GetSize(1));j++)//gradientMagnitude Axis { for (int k = 0;k <(histogram->GetSize(2));k++)//secondDerivative Axis { HistogramType::IndexType index(Dimension); index[0] = i; index[1] = j; index[2] = k; int frequency = histogram->GetFrequency(index); if (frequency != 0) { freq_h = freq_h + frequency; sum_h = sum_h + (frequency*((binMinimum[2] + k*binWidth[2]) + (binWidth[2]/2))); } } /*if (freq_h != 0) { avg_sum = avg_sum + (sum_h / freq_h);//fix i and k then iterate over j. }*/ /*} //this->h[i] = (avg_sum / (histogram->GetSize(1)));//fix i and for all the averages over k find final average. /*if (freq_h == 0) { this->h[i] = 100000; //just to remove the contribution of this h continue; }*/ /*this->h[i] = (float)(sum_h / freq_h); if (this->h[i] < this->min_h) //finding min_h this->min_h = this->h[i]; if (this->h[i] > this->max_h) //finding max_h this->max_h = this->h[i]; } cout << "\nPrinting h:" << "\n"; for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "h[" << i << "]=" << this->h[i] << "\n"; } cout << "max_h=" << this->max_h << " min_h=" << this->min_h << "\n"; }*/ template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::CalculateOpacity(HistogramType::Pointer histogram) { //calculation of sigma float e = 2.71828; float sigma = (2 * sqrtf(e) * max_g) / (max_h - min_h); cout << "sigma=" << sigma << "\n"; //calculation of p(v) this->p = (float*)calloc((histogram->GetSize(0)), sizeof(float)); for (int i = 0;i < (histogram->GetSize(0));i++) { this->p[i] = -((((sigma)*(sigma))*this->h[i]) / (this->g[i])); } cout << "\nPrinting p:" << "\n"; for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "p[" << i << "]=" << this->p[i] << "\n"; } //calculation of alpha(v) this->alpha = (float*)calloc((histogram->GetSize(0)), sizeof(float)); for (int i = 0;i <(histogram->GetSize(0));i++) { if ((this->p[i] <= sigma) && (this->p[i] >= -(sigma))) { this->alpha[i] = 0.6; // original version } else { this->alpha[i] = 0.0; } } cout << "\nPrinting alpha:" << "\n"; for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "alpha[" << i << "]=" << this->alpha[i] << "\n"; } } template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::StoreAllValues(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { // storing all values in excel ofstream allValues; allValues.open("allValues.CSV"); allValues << "dataValue" << "," << "g[v]" << "," << "h[v]" << "," << "p[v]" << "," << "alpha[v]" << "\n"; for (int i = 0;i < (histogram->GetSize(0));i++) { allValues << binMinimum[0] + i*binWidth[0] << "," << this->g[i] << "," << this->h[i] << "," << this->p[i] << "," << this->alpha[i] << "\n"; } allValues.close(); } #endif // OpacityFunctionGeneration_hxx
31.568841
155
0.603466
aishwaryamallampati
e3d381446a1d28212896b54238cbc24eb9a6d4a9
2,156
cpp
C++
core/sources/formations/Column.cpp
rharel/cpp-efficient-reformation
3e3658f5a17ca3186145dd00458a5da667788121
[ "MIT" ]
null
null
null
core/sources/formations/Column.cpp
rharel/cpp-efficient-reformation
3e3658f5a17ca3186145dd00458a5da667788121
[ "MIT" ]
null
null
null
core/sources/formations/Column.cpp
rharel/cpp-efficient-reformation
3e3658f5a17ca3186145dd00458a5da667788121
[ "MIT" ]
null
null
null
#include <algorithm> #include <glm/common.hpp> #include "core/formations/Column.h" using namespace rharel::efficient_reformation::core; Column::Column(const unsigned int row_size, const glm::vec2& spacing) : row_size(std::max(row_size, 1u)), spacing(glm::max(spacing, glm::vec2(1, 1))) {} void Column::get_member_positions(const unsigned int member_count, glm::vec2* positions) const { using glm::vec2; // Since the number of members may not be divisible by the formation's row // size, the last row may be only partially full. Let us label such a // scenario as an 'imperfect' formation. const unsigned int full_row_count = member_count / row_size, imperfect_row_size = member_count % row_size, row_count = full_row_count + (imperfect_row_size > 0 ? 1 : 0); // Computes the formation's spatial dimensions: const float width = (row_size - 1) * spacing.x, height = (row_count - 1) * spacing.y; const vec2 offset(-0.5 * width, -0.5 * height); unsigned int k = 0; // Index of current position to compute. // Compute positions for full rows: for (unsigned int i = 0; i < full_row_count; ++i) { for (unsigned int j = 0; j < row_size; ++j, ++k) { positions[k].x = offset.x + j * width / row_size; positions[k].y = offset.y + i * height / row_count; } } if (imperfect_row_size > 0) { // Compute positions for the imperfect row: const auto relative_width = static_cast<float>(imperfect_row_size) / row_size; const float padding_x = 0.5f * width * (1 - relative_width); for (unsigned int j = 0; j < imperfect_row_size; ++j, ++k) { positions[k].x = padding_x + offset.x + j * relative_width * width / imperfect_row_size; positions[k].y = offset.y + height - spacing.y; } } }
35.933333
79
0.553803
rharel
e3d9064c20b16741bd8e92ce4f083dca98c96cc2
2,143
cpp
C++
src/051-prime-digit-replacements/cpp/src/solve.cpp
xfbs/ProjectEulerRust
e26768c56ff87b029cb2a02f56dc5cd32e1f7c87
[ "MIT" ]
1
2018-01-26T21:18:12.000Z
2018-01-26T21:18:12.000Z
src/051-prime-digit-replacements/cpp/src/solve.cpp
xfbs/ProjectEulerRust
e26768c56ff87b029cb2a02f56dc5cd32e1f7c87
[ "MIT" ]
3
2017-12-09T14:49:30.000Z
2017-12-09T14:59:39.000Z
src/051-prime-digit-replacements/cpp/src/solve.cpp
xfbs/ProjectEulerRust
e26768c56ff87b029cb2a02f56dc5cd32e1f7c87
[ "MIT" ]
null
null
null
#include "solve.hpp" #include <euler/digits.hpp> #include <range/v3/algorithm.hpp> #include <range/v3/view.hpp> using namespace ranges; using namespace euler; uint8_t family_size(Prime &primes, uint64_t prime, uint64_t digit) { auto is_prime = [&primes](uint64_t num) { return primes.check(num); }; // replace all occurences of `digit` in `prime` with `replacement`. auto replace_digit_with = [prime, digit](uint64_t replacement) { auto transformed = digits(prime) | view::replace(digit, replacement); return accumulate(transformed, 0, [](uint64_t memo, uint64_t cur) { return 10 * memo + cur; }); }; // generates a list of possible replacements of the digit, skip the digit // itself, and from that generate the replaced prime candidates. auto members = view::ints((int)digit + 1, 10) | view::transform(replace_digit_with); // we know that the number itself is prime, so add one to the amount of prime // candidates that are prime. return 1 + count_if(members, is_prime); } bool check_family(Prime &primes, uint64_t prime, uint8_t family) { // we are only interested in finding the smallest prime of a family. if we are // looking for a 5-family prime, we know that the smallest of the digist must // be 10 - 5 = 5. therefore, we can filter the digit replacement candidates // like this. auto correct_size = [family](uint64_t digit) { return digit <= (10 - family); }; return any_of(unique_digits(prime) | view::filter(correct_size), [&primes, prime, family](uint64_t digit) { return family == family_size(primes, prime, digit); }); } uint64_t solve(uint8_t family) { auto primes = Prime(); const auto to_prime = [&primes](int nth) -> uint64_t { return primes.nth(nth); }; const auto has_family = [&primes, family](uint64_t prime) -> bool { return check_family(primes, prime, family); }; // make list of primes, and for each prime check if it has the correct family // size auto candidates = view::ints | view::transform(to_prime) | view::filter(has_family); return front(candidates); }
34.564516
80
0.681755
xfbs
e3dfdd4c38908527ebb55616520b6168cc8287f4
3,595
cpp
C++
datasets/github_cpp_10/5/34.cpp
yijunyu/demo-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
1
2019-05-03T19:27:45.000Z
2019-05-03T19:27:45.000Z
datasets/github_cpp_10/5/34.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
datasets/github_cpp_10/5/34.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
#include "HanoiTower.hpp" using namespace std; using namespace clever; HanoiTower::HanoiTower(HanoiTowerData const &data): d_(data), interrupt_(false) { pauselock_ = unique_lock<mutex>(pausemutex_, defer_lock); return; } HanoiTower::~HanoiTower() { free_(); return; } HanoiTower &HanoiTower::run(int from, int to) { #ifdef DEBUG if(future_.valid()) throw "run when future is valid"; #endif future_ = async( launch::async, &HanoiTower::work_implement_, this, &d_, from, to ); return *this; } bool HanoiTower::isRun() const { return future_.valid(); } HanoiTower &HanoiTower::pause(bool enable) { if(enable) { if(!pauselock_) pauselock_.lock(); } else { if(pauselock_) pauselock_.unlock(); } return *this; } bool HanoiTower::pause() const { return pauselock_.owns_lock(); } HanoiTower &HanoiTower::wait() { if(pauselock_) throw "wait, but pause is enable"; if(future_.valid()) future_.get(); interrupt_.store(false); return *this; } HanoiTower &HanoiTower::interrupt() { if(future_.valid()); interrupt_.store(true); pause(false); return *this; } HanoiTower &HanoiTower::reflect(clever::Field<int> &f) { #ifdef DEBUG if( !d_.first || !d_.second || !d_.third ) { throw "invalid data(HanoiTower)"; } if( !f.d || f.h < d_.height || f.w < 3u*( 1u + 2u*( d_.height - 1u ) ) + 2u ) throw "invalid size of filed"; #endif f.clear(0); int *towers[] = { d_.first, d_.second, d_.third }; int pos = 0; int *begin, *end; { lock_guard<mutex> guard(datamutex_); for(auto tow : towers) { for(size_t disk = 0u; disk < d_.height; ++disk) { if(tow[disk] == 0) break; begin = &f.at( pos + d_.height-1 - (tow[disk]-1), (f.h-disk-1) ); end = begin + ( 1 + 2*(tow[disk]-1) ); while(begin != end) { *begin = 1; ++begin; } } pos += 1 + 2*(d_.height-1) + 1; } } return *this; } HanoiTower &HanoiTower::setData(HanoiTowerData const &data) { free_(); d_ = data; return *this; } HanoiTower &HanoiTower::releaseData() { d_.first = nullptr; d_.second = nullptr; d_.third = nullptr; return *this; } HanoiTowerData const &HanoiTower::getData() const { return d_; } bool HanoiTower::work_implement_(HanoiTowerData *d, int from, int to) { constexpr unsigned int const SLEEP_DURATION = 500; if(d->height == 1) { { lock_guard<mutex> pauselock(pausemutex_); } if(interrupt_.exchange(false)) return false; { lock_guard<mutex> datalock(mutex); *d->get(to) = *d->get(from); *d->get(from) = 0; } this_thread::sleep_for( chrono::milliseconds( SLEEP_DURATION ) ); return true; } int other; if(from != 0 && to != 0) other = 0; else if(from != 1 && to != 1) other = 1; else other = 2; HanoiTowerData dat; dat.first = d->get(from)+1; dat.second = d->get(other); dat.third = d->get(to); dat.height = d->height-1; if(!work_implement_(&dat, 0, 1)) return false; { lock_guard<mutex> pauselock(pausemutex_); } if(interrupt_.exchange(false)) return false; { lock_guard<mutex> datalock(datamutex_); *d->get(to) = *d->get(from); *d->get(from) = 0; } this_thread::sleep_for( chrono::milliseconds( SLEEP_DURATION ) ); dat.first = d->get(other); dat.second = d->get(to)+1; dat.third = d->get(from); dat.height = d->height-1; if(!work_implement_(&dat, 0, 1)) return false; return true; } void HanoiTower::free_() { if(d_.first) delete[] d_.first; if(d_.second) delete[] d_.second; if(d_.third) delete[] d_.third; return; }
13.314815
69
0.618637
yijunyu
e3e1189fa074b1869cc096537af4b6d6686642b5
4,132
cpp
C++
test/utility/future.cpp
wak-google/sdeventplus
3064849c13981864c4d85667659d502f0c3b5d9f
[ "Apache-2.0" ]
null
null
null
test/utility/future.cpp
wak-google/sdeventplus
3064849c13981864c4d85667659d502f0c3b5d9f
[ "Apache-2.0" ]
null
null
null
test/utility/future.cpp
wak-google/sdeventplus
3064849c13981864c4d85667659d502f0c3b5d9f
[ "Apache-2.0" ]
null
null
null
#include <chrono> #include <gtest/gtest.h> #include <sdeventplus/event.hpp> #include <sdeventplus/source/event.hpp> #include <sdeventplus/utility/future.hpp> #include <stdplus/util/future.hpp> #include <utility> namespace sdeventplus { namespace utility { namespace { using namespace std::chrono_literals; class CallWhenReady : public testing::Test { protected: Event event = Event::get_new(); }; TEST_F(CallWhenReady, NoFutures) { size_t cbCalls = 0; callWhenReady(event, [&](const Event&) { cbCalls++; }).set_floating(true); // Ensure that the cb is run immediately, without any other events while (event.prepare() > 0) { EXPECT_EQ(1, event.dispatch()); } EXPECT_EQ(1, cbCalls); EXPECT_EQ(0, event.wait(0s)); // Ensure we are called only once source::Defer(event, [](source::EventBase&) {}).set_floating(true); while (event.prepare() > 0) { EXPECT_EQ(1, event.dispatch()); } EXPECT_EQ(1, cbCalls); EXPECT_EQ(0, event.wait(0s)); } TEST_F(CallWhenReady, BasicFuture) { stdplus::util::Promise<int> p; size_t cbCalls = 0; auto cb = [&](const Event&, stdplus::util::Future<int>&& f) { f.get(); // Ensure the future is ready since this will block otherwise cbCalls++; }; callWhenReady(event, std::move(cb), p.get_future()).set_floating(true); // Ensure that the cb is not evaluated without the promised value while (event.prepare() > 0) { EXPECT_EQ(1, event.dispatch()); } EXPECT_EQ(0, event.wait(0s)); // Ensure the promise setting triggered new events to run p.set_value(10); while (event.prepare() > 0) { EXPECT_EQ(1, event.dispatch()); } EXPECT_EQ(1, cbCalls); EXPECT_EQ(0, event.wait(0s)); // Ensure we are called only once source::Defer(event, [](source::EventBase&) {}).set_floating(true); while (event.prepare() > 0) { EXPECT_EQ(1, event.dispatch()); } EXPECT_EQ(1, cbCalls); EXPECT_EQ(0, event.wait(0s)); } TEST_F(CallWhenReady, TwoFutures) { stdplus::util::Promise<int> p1, p2; size_t cbCalls = 0; auto cb = [&](const Event&, stdplus::util::Future<int>&& f1, stdplus::util::Future<int>&& f2) { f1.get(); f2.get(); cbCalls++; }; callWhenReady(event, std::move(cb), p1.get_future(), p2.get_future()) .set_floating(true); // Ensure that the cb is not evaluated without any promised value while (event.prepare() > 0) { EXPECT_EQ(1, event.dispatch()); } EXPECT_EQ(0, event.wait(0s)); // Only fullfill a single promise p1.set_value(10); // Add a new event and ensure we aren't executed source::Defer(event, [](source::EventBase&) {}).set_floating(true); while (event.prepare() > 0) { EXPECT_EQ(1, event.dispatch()); } EXPECT_EQ(0, cbCalls); EXPECT_EQ(0, event.wait(0s)); // Fullfill all promises and ensure the loop is triggered p2.set_value(20); while (event.prepare() > 0) { EXPECT_EQ(1, event.dispatch()); } EXPECT_EQ(1, cbCalls); EXPECT_EQ(0, event.wait(0s)); // Ensure we are called only once source::Defer(event, [](source::EventBase&) {}).set_floating(true); while (event.prepare() > 0) { EXPECT_EQ(1, event.dispatch()); } EXPECT_EQ(1, cbCalls); EXPECT_EQ(0, event.wait(0s)); } TEST_F(CallWhenReady, VariableSize) { std::vector<stdplus::util::Future<int>> v; for (int i = 0; i < 5; ++i) { stdplus::util::Promise<int> p; v.push_back(p.get_future()); p.set_value(i); } int val = 0; auto cb = [&](const Event&, std::vector<stdplus::util::Future<int>>&& vs) { for (const auto& v : vs) { val += v.get(); } }; callWhenReady(event, std::move(cb), std::move(v)).set_floating(true); while (event.prepare() > 0) { EXPECT_EQ(1, event.dispatch()); } EXPECT_EQ(0, event.wait(0s)); EXPECT_EQ(10, val); } } // namespace } // namespace utility } // namespace sdeventplus
25.506173
79
0.602856
wak-google
e3e278cccac2eb35046bbb61377c9ba179ce4fb1
5,447
cpp
C++
Super Smash TV/Super Smash TV/Source/ModulePlayer_Legs.cpp
YunqianAo/Filosaurios
23f191c48629a5b6ee7b4d3e69a541dd0e1bb381
[ "MIT" ]
2
2021-03-07T10:32:01.000Z
2021-03-07T10:32:04.000Z
Super Smash TV/Super Smash TV/Source/ModulePlayer_Legs.cpp
YunqianAo/Filosaurios
23f191c48629a5b6ee7b4d3e69a541dd0e1bb381
[ "MIT" ]
null
null
null
Super Smash TV/Super Smash TV/Source/ModulePlayer_Legs.cpp
YunqianAo/Filosaurios
23f191c48629a5b6ee7b4d3e69a541dd0e1bb381
[ "MIT" ]
8
2021-02-23T18:06:22.000Z
2021-02-24T19:12:48.000Z
//#include "ModulePlayer_Legs.h" // //#include "Application.h" //#include "ModuleTextures.h" //#include "ModuleInput.h" //#include "ModuleRender.h" //#include "ModuleParticles.h" //#include "ModuleCollisions.h" //#include "ModuleAudio.h" //#include "ModuleFadeToBlack.h" // //#include "SDL/include/SDL_scancode.h" // // //ModulePlayer_Leg::ModulePlayer_Leg(bool startEnabled) : Module(startEnabled) //{ // // LEGS // legs_down_idle.PushBack({ 128, 16, 16, 16 }); // legs_up_idle.PushBack({ 192, 16, 16, 16 }); // legs_l_idle.PushBack({ 208, 16, 16, 16 }); // legs_r_idle.PushBack({ 160, 16, 16, 16 }); // // // move upwards // upAnim.PushBack({ 0, 16, 16, 16 });// 1 // upAnim.PushBack({ 16, 16, 16, 16 });// 2 // upAnim.PushBack({ 32, 16, 16, 16 });// 3 // upAnim.PushBack({ 48, 16, 16, 16 });// 4 // upAnim.PushBack({ 64, 16, 16, 16 });// 5 // upAnim.PushBack({ 80, 16, 16, 16 });// 6 // upAnim.loop = true; // upAnim.speed = 0.2f; // // // Move down // legs_down.PushBack({ 0, 0, 16, 16 });// 1 // legs_down.PushBack({ 16, 0, 16, 16 });// 2 // legs_down.PushBack({ 32, 0, 16, 16 });// 3 // legs_down.PushBack({ 48, 0, 16, 16 });// 4 // legs_down.PushBack({ 64, 0, 16, 16 });// 5 // legs_down.PushBack({ 80, 0, 16, 16 });// 6 // legs_down.PushBack({ 96, 0, 16, 16 });// 7 // legs_down.PushBack({ 112, 0, 16, 16 });// 8 // // legs_down.loop = true; // legs_down.speed = 0.2f; // // // Move left // legs_l.PushBack({ 96, 32, 16, 16 });// 7 // legs_l.PushBack({ 80, 32, 16, 16 });// 6 // legs_l.PushBack({ 64, 32, 16, 16 });// 5 // legs_l.PushBack({ 48, 32, 16, 16 });// 4 // legs_l.PushBack({ 32, 32, 16, 16 });// 3 // legs_l.PushBack({ 16, 32, 16, 16 });// 2 // legs_l.PushBack({ 0, 32, 16, 16 });// 1 // // legs_l.loop = true; // legs_l.speed = 0.2f; // // // Move right // legs_r.PushBack({ 0, 48, 16, 16 });// 1 // legs_r.PushBack({ 16, 48, 16, 16 });// 2 // legs_r.PushBack({ 32, 48, 16, 16 });// 3 // legs_r.PushBack({ 48, 48, 16, 16 });// 4 // legs_r.PushBack({ 64, 48, 16, 16 });// 5 // legs_r.PushBack({ 80, 48, 16, 16 });// 6 // legs_r.PushBack({ 96, 48, 16, 16 });// 7 // legs_r.loop = true; // legs_r.speed = 0.2f; // // // //} // // //bool ModulePlayer_Leg::Start() //{ // LOG("Loading player textures"); // // bool ret = true; // // texture = App->textures->Load("Resources/Sprites/Characters/Player.png"); // currentAnimation = &legs_idle; // position.x = 121; // position.y = 135; // // destroyed = false; // // bool bandera_GodMode = false; // // collider = App->collisions->AddCollider({ position.x, position.y, 14, 25 }, Collider::Type::PLAYER, this); // // return ret; //} // //update_status ModulePlayer_Leg::Update() //{ // // Moving the player with the camera scroll // App->player->position.x += 0; // // // Body movent // // Shoot bullet right // if (App->input->keys[SDL_SCANCODE_RIGHT] == KEY_STATE::KEY_REPEAT) // { // currentAnimation = &legs_r_idle; // } // // // Shoot bullet left // if (App->input->keys[SDL_SCANCODE_LEFT] == KEY_STATE::KEY_REPEAT) // { // currentAnimation = &legs_l_idle; // } // // // Shoot bullet up // if (App->input->keys[SDL_SCANCODE_UP] == KEY_STATE::KEY_REPEAT) // { // // currentAnimation = &upAnim_idle; // } // // // // if (App->input->keys[SDL_SCANCODE_S] == KEY_STATE::KEY_REPEAT) // { // position.y += speed; // // currentAnimation = &legs_down; // } // // if (App->input->keys[SDL_SCANCODE_W] == KEY_STATE::KEY_REPEAT) // { // position.y -= speed; // // currentAnimation = &upAnim; // } // // // if (App->input->keys[SDL_SCANCODE_A] == KEY_STATE::KEY_REPEAT) // { // position.x -= speed; // // currentAnimation = &legs_l; // } // // // if (App->input->keys[SDL_SCANCODE_D] == KEY_STATE::KEY_REPEAT) // { // position.x += speed; // // currentAnimation = &legs_r; // } // // if (App->input->keys[SDL_SCANCODE_F2] == KEY_STATE::KEY_DOWN) // { // if (GodMode == false) { // GodMode = true; // } // else if(GodMode == true) { // GodMode = false; // } // // } // // // // // If no up/down movement detected, set the current animation back to idle // if (App->input->keys[SDL_SCANCODE_RIGHT] == KEY_STATE::KEY_IDLE // && App->input->keys[SDL_SCANCODE_LEFT] == KEY_STATE::KEY_IDLE // && App->input->keys[SDL_SCANCODE_UP] == KEY_STATE::KEY_IDLE // // && App->input->keys[SDL_SCANCODE_S] == KEY_STATE::KEY_IDLE // && App->input->keys[SDL_SCANCODE_W] == KEY_STATE::KEY_IDLE // && App->input->keys[SDL_SCANCODE_A] == KEY_STATE::KEY_IDLE // && App->input->keys[SDL_SCANCODE_D] == KEY_STATE::KEY_IDLE) // // currentAnimation = &legs_idle; // // collider->SetPos(position.x+1, position.y-12); // // currentAnimation->Update(); // // // return update_status::UPDATE_CONTINUE; //} // //update_status ModulePlayer_Leg::PostUpdate() //{ // if (!destroyed) // { // SDL_Rect rect = currentAnimation->GetCurrentFrame(); // App->render->Blit(texture, position.x, position.y, &rect); // } // // return update_status::UPDATE_CONTINUE; //} // //void ModulePlayer_Leg::OnCollision(Collider* c1, Collider* c2) //{ // if (c2->type == Collider::Type::WALL && destroyed == false && GodMode == false) // { // App->fade->FadeToBlack((Module*)App->sceneLevel, (Module*)App->sceneLose, 90); // destroyed = true; // // } // // if (c2->type == Collider::Type::DOOR && destroyed == false) // { // App->fade->FadeToBlack((Module*)App->sceneLevel, (Module*)App->sceneWin, 90); // destroyed = true; // } // //}
25.938095
109
0.596842
YunqianAo
e3e4c33c1e4a1f8bfc439cfcf0b7bde39b09ce4b
4,133
cpp
C++
v1/CUCT.cpp
lanyj/mcts
8394acaf3e83020b0bdfaa6117553d1ad64be291
[ "MIT" ]
null
null
null
v1/CUCT.cpp
lanyj/mcts
8394acaf3e83020b0bdfaa6117553d1ad64be291
[ "MIT" ]
null
null
null
v1/CUCT.cpp
lanyj/mcts
8394acaf3e83020b0bdfaa6117553d1ad64be291
[ "MIT" ]
null
null
null
#pragma once #include <time.h> #include "stdafx.h" #include "CUCT.h" #include "OthelloCBoard.h" #include "OXOCBoard.h" #include "GobangCBoard.h" void* CUCT::getCNode(const void *list, int index) { return ((CList<CNode*>*) list)->get(index); } void CUCT::exchangeCNode(const void *list, int i, int j) { CNode* m = (CNode*) ((CList<CNode*>*) list)->get(i); CNode* n = (CNode*) ((CList<CNode*>*) list)->get(j); ((CList<CNode*>*) list)->set(i, n); ((CList<CNode*>*) list)->set(j, m); } int CUCT::compareToCNode(const void* l, const void* r) { double v1 = ((CNode *) l)->value(); double v2 = ((CNode *) r)->value(); return (v1 == v2 ? 0 : (v1 > v2 ? 1 : -1)); } int CUCT::random(int bounds) { return rand() % bounds; } CNode* CUCT::randomChoiceCNode(CList<CNode*> *list) { if (list->isEmpty()) { return NULL; } return list->get(random(list->size())); } CMove* CUCT::randomChoiceCMove(CList<CMove*> *list) { if (list->isEmpty()) { return NULL; } return list->get(random(list->size())); } CMove* CUCT::uctMove(CBoard* _board, int itermax) { CNode* root = new CNode(NULL, NULL, _board); for(; itermax--;) { CNode* node = root; CBoard *board = _board->clone(); CNode* n = select(node, board); n = expansion(n, board); double res = simulation(n, board); backUp(n, res); delete board; } // printf("\nBEGIN...\n"); // for (int i = root->children->size() - 1; i >= 0; i--) { // root->children->get(i)->move->toString(); // printf(" -> %f, %f, %f\n", root->children->get(i)->visits, root->children->get(i)->score, root->children->get(i)->value()); // } CMove* move; double mostVist = -100; int index = -1; for (int i = root->children->size() - 1; i >= 0; i--) { CNode* tmp = root->children->get(i); /* if ((tmp->score / tmp->visits) > mostVist) { mostVist = (tmp->score / tmp->visits); index = i; } */ if (tmp->visits > mostVist) { mostVist = tmp->visits; index = i; } } move = root->children->get(index)->move->clone(); // printf("\nCHOSEN:->"); // move->toString(); // printf("\nEND..."); clearUp(root); return move; } CNode* CUCT::select(CNode* root, CBoard* board) { if (root->children->isEmpty()) { return root; } CNode* next = root->uctSelectChild(); board->applyMove(next->move); while (!next->children->isEmpty()) { next = next->uctSelectChild(); board->applyMove(next->move); } return next; } CNode* CUCT::expansion(CNode* root, CBoard* board) { if (board->isGameOver()) { return root; } CNode* node = NULL; CList<CMove*>* moves = board->getMoves(); while (!moves->isEmpty()) { root->addNode(moves->removeLast(), board); } delete moves; return randomChoiceCNode(root->children); } double CUCT::simulation(CNode* root, CBoard* board) { while (!board->isGameOver()) { CList<CMove*>* moves = board->getMoves(); CMove* m = randomChoiceCMove(moves); board->applyMove(m); while (!moves->isEmpty()) { delete moves->removeLast(); } delete moves; } double res = board->getResult(root->player); return res; } void CUCT::backUp(CNode* node, double res) { node->update(res); if (node->parent != NULL) { backUp(node->parent, -res); } } void CUCT::clearUp(CNode* node) { if (node->move != NULL) { delete node->move; } CList<CNode*> *children = node->children; while(!children->isEmpty()) { clearUp(children->removeLast()); } delete node; } void CUCT::uctPlayGame() { char c[3] = { '.', 'X', 'O' }; // OXOCBoard, GobangCBoard, OthelloCBoard CBoard *board = new OthelloCBoard(8); board->printCBoard(); printf("\n"); CMove *move; while(!board->isGameOver()) { if(board->getCurrentPlayer() == 1) { move = uctMove(board, 1000); } else { move = uctMove(board, 100); } printf("\nPlayer %c STEP: ", c[board->getCurrentPlayer()]); move->toString(); printf("\n"); board->applyMove(move); board->printCBoard(); printf("\n"); delete move; } printf("Player: %c -> %lf\n", c[board->getCurrentPlayer()], board->getResult(board->getCurrentPlayer())); printf("Player: %c -> %lf\n", c[3 - board->getCurrentPlayer()], board->getResult(3 - board->getCurrentPlayer())); delete board; }
24.311765
127
0.616017
lanyj
e3e5ce311956c5949defb8b4ef5f3eb86aae4eac
1,670
cpp
C++
luogu/codes/P1637.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
1
2018-12-22T06:43:59.000Z
2018-12-22T06:43:59.000Z
luogu/codes/P1637.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
luogu/codes/P1637.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
/************************************************************* * > File Name : P1637.cpp * > Author : Tony * > Created Time : 2019/08/26 16:20:04 * > Algorithm : [DataStructure]BIT **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 30010; int n, m, a[maxn]; int tree1[maxn], tree2[maxn]; int A[maxn]; int cntl[maxn], cntr[maxn]; void add1(int x, int k) { for (; x <= n; x += x & -x) tree1[x] += k; } void add2(int x, int k) { for (; x <= n; x += x & -x) tree2[x] += k; } int ask1(int x) { int ans = 0; for (; x; x -= x & -x) ans += tree1[x]; return ans; } int ask2(int x) { int ans = 0; for (; x; x -= x & -x) ans += tree2[x]; return ans; } int main() { n = read(); for (int i = 1; i <= n; ++i) { A[i] = a[i] = read(); } sort(A + 1, A + 1 + n); m = unique(A + 1, A + 1 + n) - (A + 1); for (int i = 1; i <= n; ++i) { add1(lower_bound(A + 1, A + 1 + n, a[i]) - A, 1); cntl[i] = ask1((lower_bound(A + 1, A + 1 + n, a[i]) - A) - 1); } for (int i = n; i >= 1; --i) { add2(lower_bound(A + 1, A + 1 + n, a[i]) - A, 1); cntr[i] = n - i - ask2((lower_bound(A + 1, A + 1 + n, a[i]) - A)) + 1; } long long ans = 0; for (int i = 2; i < n; ++i) { ans += cntl[i] * cntr[i]; } printf("%lld\n", ans); return 0; }
25.692308
78
0.40479
Tony031218
e3e5ee35e3c3a21613416ee85906f187f1d7f575
4,266
cpp
C++
UnrealEngine-4.11.2-release/Engine/Source/Editor/AddContentDialog/Private/ContentSourceProviders/FeaturePack/FeaturePackContentSourceProvider.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2016-10-01T21:35:52.000Z
2016-10-01T21:35:52.000Z
UnrealEngine-4.11.2-release/Engine/Source/Editor/AddContentDialog/Private/ContentSourceProviders/FeaturePack/FeaturePackContentSourceProvider.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
null
null
null
UnrealEngine-4.11.2-release/Engine/Source/Editor/AddContentDialog/Private/ContentSourceProviders/FeaturePack/FeaturePackContentSourceProvider.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2021-04-27T08:48:33.000Z
2021-04-27T08:48:33.000Z
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "AddContentDialogPCH.h" #include "FeaturePackContentSourceProvider.h" #include "FeaturePackContentSource.h" #include "ModuleManager.h" class FFillArrayDirectoryVisitor : public IPlatformFile::FDirectoryVisitor { public: virtual bool Visit(const TCHAR* FilenameOrDirectory, bool bIsDirectory) override { if (bIsDirectory) { Directories.Add(FilenameOrDirectory); } else { Files.Add(FilenameOrDirectory); } return true; } TArray<FString> Directories; TArray<FString> Files; }; FFeaturePackContentSourceProvider::FFeaturePackContentSourceProvider() { FeaturePackPath = FPaths::FeaturePackDir(); TemplatePath = FPaths::RootDir() + TEXT("Templates/"); StartUpDirectoryWatcher(); RefreshFeaturePacks(); } const TArray<TSharedRef<IContentSource>> FFeaturePackContentSourceProvider::GetContentSources() { return ContentSources; } void FFeaturePackContentSourceProvider::SetContentSourcesChanged(FOnContentSourcesChanged OnContentSourcesChangedIn) { OnContentSourcesChanged = OnContentSourcesChangedIn; } void FFeaturePackContentSourceProvider::StartUpDirectoryWatcher() { FDirectoryWatcherModule& DirectoryWatcherModule = FModuleManager::LoadModuleChecked<FDirectoryWatcherModule>(TEXT("DirectoryWatcher")); IDirectoryWatcher* DirectoryWatcher = DirectoryWatcherModule.Get(); if (DirectoryWatcher) { // If the path doesn't exist on disk, make it so the watcher will work. IFileManager::Get().MakeDirectory(*FeaturePackPath); DirectoryChangedDelegate = IDirectoryWatcher::FDirectoryChanged::CreateRaw(this, &FFeaturePackContentSourceProvider::OnFeaturePackDirectoryChanged); DirectoryWatcher->RegisterDirectoryChangedCallback_Handle(FeaturePackPath, DirectoryChangedDelegate, DirectoryChangedDelegateHandle); } } void FFeaturePackContentSourceProvider::ShutDownDirectoryWatcher() { FDirectoryWatcherModule& DirectoryWatcherModule = FModuleManager::LoadModuleChecked<FDirectoryWatcherModule>( TEXT( "DirectoryWatcher" ) ); IDirectoryWatcher* DirectoryWatcher = DirectoryWatcherModule.Get(); if ( DirectoryWatcher ) { DirectoryWatcher->UnregisterDirectoryChangedCallback_Handle(FeaturePackPath, DirectoryChangedDelegateHandle); } } void FFeaturePackContentSourceProvider::OnFeaturePackDirectoryChanged( const TArray<FFileChangeData>& FileChanges ) { RefreshFeaturePacks(); } /** Sorting function sort keys. */ struct FFeaturePackCompareSortKey { FORCEINLINE bool operator()( TSharedRef<IContentSource> const& A, TSharedRef<IContentSource> const& B) const { return A->GetSortKey() < B->GetSortKey(); } }; void FFeaturePackContentSourceProvider::RefreshFeaturePacks() { ContentSources.Empty(); // TODO improve this and seperate handling of .upack and manifest (loose) parsing // first the .upack files IPlatformFile &PlatformFile = FPlatformFileManager::Get().GetPlatformFile(); FFillArrayDirectoryVisitor DirectoryVisitor; PlatformFile.IterateDirectory( *FeaturePackPath, DirectoryVisitor ); for ( auto FeaturePackFile : DirectoryVisitor.Files ) { if( FeaturePackFile.EndsWith(TEXT(".upack")) == true) { TUniquePtr<FFeaturePackContentSource> NewContentSource = MakeUnique<FFeaturePackContentSource>(FeaturePackFile); if (NewContentSource->IsDataValid()) { ContentSources.Add(MakeShareable(NewContentSource.Release())); } } } // Now the 'loose' feature packs FFillArrayDirectoryVisitor TemplateDirectoryVisitor; PlatformFile.IterateDirectoryRecursively(*TemplatePath, TemplateDirectoryVisitor); for (auto TemplatePackFile: TemplateDirectoryVisitor.Files) { FString ThisPackRoot = FPaths::GetPath(TemplatePackFile); if (ThisPackRoot.EndsWith(TEXT("FeaturePack")) == true) { if(TemplatePackFile.EndsWith(TEXT("manifest.json")) == true) { TUniquePtr<FFeaturePackContentSource> NewContentSource = MakeUnique<FFeaturePackContentSource>(TemplatePackFile); if (NewContentSource->IsDataValid()) { ContentSources.Add(MakeShareable(NewContentSource.Release())); } } } } ContentSources.Sort(FFeaturePackCompareSortKey()); OnContentSourcesChanged.ExecuteIfBound(); } FFeaturePackContentSourceProvider::~FFeaturePackContentSourceProvider() { ShutDownDirectoryWatcher(); }
33.069767
155
0.800516
armroyce
e3e86f09cecd130e1dae59ea842f994ee802df60
1,362
cpp
C++
sdk/packages/engine_gems/state/test/io.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
null
null
null
sdk/packages/engine_gems/state/test/io.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
null
null
null
sdk/packages/engine_gems/state/test/io.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2022-01-28T16:37:51.000Z
2022-01-28T16:37:51.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #include "packages/engine_gems/state/io.hpp" #include "capnp/message.h" #include "engine/core/buffers/shared_buffer.hpp" #include "packages/engine_gems/state/state.hpp" #include "packages/engine_gems/state/test/domains.hpp" #include "gtest/gtest.h" namespace isaac { namespace state { namespace { constexpr double kFoo = 13.1; constexpr double kBar = -0.3; constexpr double kTur = 0.57; } // namespace TEST(State, ToFromProto) { FooBarTur actual; actual.foo() = kFoo; actual.bar() = kBar; actual.tur() = kTur; ::capnp::MallocMessageBuilder message; auto builder = message.initRoot<StateProto>(); std::vector<isaac::SharedBuffer> buffers; ToProto(actual, builder, buffers); auto reader = builder.asReader(); FooBarTur expected; FromProto(reader, buffers, expected); EXPECT_EQ(expected.foo(), kFoo); EXPECT_EQ(expected.bar(), kBar); EXPECT_EQ(expected.tur(), kTur); } } // namespace state } // namespace isaac
28.978723
74
0.755507
ddr95070
e3f76fcfeafe8efdacf0a9ac02d57b35a5e8604d
1,422
hxx
C++
base/fs/utils/diskedit/fileio.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/fs/utils/diskedit/fileio.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/fs/utils/diskedit/fileio.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#if !defined( _FILE_IO_ ) #define _FILE_IO_ #include "io.hxx" #include "hmem.hxx" #include "secrun.hxx" DECLARE_CLASS( FILE_IO ); class FILE_IO : public IO_OBJECT { public: NONVIRTUAL FILE_IO( ) { _file_handle = INVALID_HANDLE_VALUE; _buffer_size = 0; }; VIRTUAL ~FILE_IO( ) { CloseHandle(_file_handle); }; NONVIRTUAL BOOLEAN Initialize( IN ULONG Size ) { _buffer_size = Size; return TRUE; }; VIRTUAL BOOLEAN Setup( IN PMEM Mem, IN PLOG_IO_DP_DRIVE Drive, IN HANDLE Application, IN HWND WindowHandle, OUT PBOOLEAN Error ); VIRTUAL BOOLEAN Read( OUT PULONG pError ); VIRTUAL BOOLEAN Write( ); VIRTUAL PVOID GetBuf( OUT PULONG Size DEFAULT NULL ); VIRTUAL PTCHAR GetHeaderText( ); private: HANDLE _file_handle; PVOID _buffer; ULONG _buffer_size; TCHAR _header_text[64 + MAX_PATH]; }; #endif
19.75
74
0.422644
npocmaka
e3f97601d1618d140eef14b54a9e1772f1888f27
766
cpp
C++
docs/mfc/codesnippet/CPP/cmap-class_7.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
14
2018-01-28T18:10:55.000Z
2021-11-16T13:21:18.000Z
docs/mfc/codesnippet/CPP/cmap-class_7.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
null
null
null
docs/mfc/codesnippet/CPP/cmap-class_7.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
2
2018-10-10T07:37:30.000Z
2019-06-21T15:18:07.000Z
CMap<int, int, CPoint, CPoint> myMap; // Add 10 elements to the map. for (int i = 0; i < 10; i++) myMap.SetAt(i, CPoint(i, i)); // Remove the elements with even key values. POSITION pos = myMap.GetStartPosition(); int nKey; CPoint pt; while (pos != NULL) { myMap.GetNextAssoc(pos, nKey, pt); if ((nKey % 2) == 0) myMap.RemoveKey(nKey); } // Print the element values. pos = myMap.GetStartPosition(); while (pos != NULL) { myMap.GetNextAssoc(pos, nKey, pt); _tprintf_s(_T("Current key value at %d: %d,%d\n"), nKey, pt.x, pt.y); }
29.461538
63
0.456919
jmittert
5400027446cdf509e429e4d3ccc5f028497d1ddb
478
cpp
C++
Squareandcube.cpp
aaryan0348/E-Lab-Object-Oriented-Programming
29f3ca80dbf2268441b5b9e426415650a607195a
[ "MIT" ]
null
null
null
Squareandcube.cpp
aaryan0348/E-Lab-Object-Oriented-Programming
29f3ca80dbf2268441b5b9e426415650a607195a
[ "MIT" ]
null
null
null
Squareandcube.cpp
aaryan0348/E-Lab-Object-Oriented-Programming
29f3ca80dbf2268441b5b9e426415650a607195a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Number { public: int n; void getNumber() { cin>>n; } }; class Square:public Number { public: void getSquare() { cout<<(n*n)<<endl; } }; class Cube:public Number { public: void getCube() { cout<<((n*n)*n)<<endl; } }; int main() { Square objS ; objS.getNumber(); objS.getSquare(); Cube objC ; objC.getNumber(); objC.getCube(); return 0; }
14.9375
31
0.529289
aaryan0348
540320795eb258402122b38c3d1370a5f5a411ba
126
hpp
C++
src/order_type.hpp
Twon/cpp_crypto_algos
e785f6c25ef50dc3c2f593b08b6857dffcd32eca
[ "MIT" ]
null
null
null
src/order_type.hpp
Twon/cpp_crypto_algos
e785f6c25ef50dc3c2f593b08b6857dffcd32eca
[ "MIT" ]
null
null
null
src/order_type.hpp
Twon/cpp_crypto_algos
e785f6c25ef50dc3c2f593b08b6857dffcd32eca
[ "MIT" ]
null
null
null
#pragma once #include <boost/describe/enum.hpp> namespace profitview { BOOST_DEFINE_ENUM_CLASS(OrderType, Limit, Market) }
12.6
49
0.785714
Twon
54034083f157980cf15348c7a892b4d443125820
560
hpp
C++
include/CompositeSceneElement.hpp
renato-cefet-rj/openglbase
9218fc3e53bc08f799f10ac4111cb579bc2dd6b3
[ "MIT" ]
3
2018-06-11T16:20:02.000Z
2019-11-14T19:44:11.000Z
include/CompositeSceneElement.hpp
renato-cefet-rj/openglbase
9218fc3e53bc08f799f10ac4111cb579bc2dd6b3
[ "MIT" ]
1
2018-06-11T02:41:11.000Z
2018-06-14T13:38:16.000Z
include/CompositeSceneElement.hpp
renato-cefet-rj/openglbase
9218fc3e53bc08f799f10ac4111cb579bc2dd6b3
[ "MIT" ]
1
2018-07-18T15:12:33.000Z
2018-07-18T15:12:33.000Z
#ifndef __COMPOSITE_SCENE_ELEMENT__ #define __COMPOSITE_SCENE_ELEMENT__ #define CompositeSceneElementNull (CompositeSceneElement*)0 #include <SceneElement.hpp> #include <list> typedef std::list<SceneElement*>::iterator ElementsIterator; class CompositeSceneElement: public SceneElement { public: CompositeSceneElement(); virtual ~CompositeSceneElement(); virtual CompositeSceneElement* append(SceneElement* se); virtual void draw(glm::mat4 transform); private: std::list<SceneElement*> elements; }; #endif
24.347826
64
0.748214
renato-cefet-rj
5408b77717bb800fadb85a9972a8b1f37af731b2
394
hh
C++
Cassie_Example/opt_two_step/periodic/c_code/include/frost/gen/J_swing_toe_linear_velocity_z_RightStance.hh
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/periodic/c_code/include/frost/gen/J_swing_toe_linear_velocity_z_RightStance.hh
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/periodic/c_code/include/frost/gen/J_swing_toe_linear_velocity_z_RightStance.hh
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
/* * Automatically Generated from Mathematica. * Fri 5 Nov 2021 09:01:51 GMT-04:00 */ #ifndef J_SWING_TOE_LINEAR_VELOCITY_Z_RIGHTSTANCE_HH #define J_SWING_TOE_LINEAR_VELOCITY_Z_RIGHTSTANCE_HH namespace frost { namespace gen { void J_swing_toe_linear_velocity_z_RightStance(double *p_output1, const double *var1); } } #endif // J_SWING_TOE_LINEAR_VELOCITY_Z_RIGHTSTANCE_HH
24.625
94
0.78934
prem-chand
541187d8378dd38a244573e0264406ec44df5e78
15,898
cxx
C++
com/mobile/syncmgr/dll/editschd.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/mobile/syncmgr/dll/editschd.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/mobile/syncmgr/dll/editschd.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+-------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1994 - 1996. // // File: editschd.cxx // // Contents: Task schedule page for hidden schedules // // Classes: CEditSchedPage // // History: 15-Mar-1998 SusiA // //--------------------------------------------------------------------------- #include "precomp.h" extern LANGID g_LangIdSystem; // LangId of system we are running on. extern TCHAR szSyncMgrHelp[]; extern ULONG g_aContextHelpIds[]; CEditSchedPage *g_pEditSchedPage = NULL; extern CSelectItemsPage *g_pSelectItemsPage; #ifdef _CREDENTIALS extern CCredentialsPage *g_pCredentialsPage; #endif // _CREDENTIALS extern HINSTANCE g_hmodThisDll; // Handle to this DLL itself. //+------------------------------------------------------------------------------- // FUNCTION: SchedEditDlgProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Callback dialog procedure for the property page // // PARAMETERS: // hDlg - Dialog box window handle // uMessage - current message // wParam - depends on message // lParam - depends on message // // RETURN VALUE: // // Depends on message. In general, return TRUE if we process it. // // COMMENTS: // //-------------------------------------------------------------------------------- INT_PTR CALLBACK SchedEditDlgProc(HWND hDlg, UINT uMessage, WPARAM wParam, LPARAM lParam) { WORD wNotifyCode = HIWORD(wParam); // notification code switch (uMessage) { case WM_INITDIALOG: if (g_pEditSchedPage) g_pEditSchedPage->Initialize(hDlg); InitPage(hDlg,lParam); return TRUE; break; case WM_NOTIFY: switch (((NMHDR FAR *)lParam)->code) { case PSN_APPLY: if (!g_pEditSchedPage->SetSchedName()) { SchedUIErrorDialog(hDlg, IERR_INVALIDSCHEDNAME); SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE ); return TRUE; } if (g_pSelectItemsPage) { g_pSelectItemsPage->CommitChanges(); } #ifdef _CREDENTIALS SCODE sc; if (g_pCredentialsPage) { sc = g_pCredentialsPage->CommitChanges(); if (sc == ERROR_INVALID_PASSWORD) { // Passwords didn't match. Let the user know so he/she // can correct it. SchedUIErrorDialog(hDlg, IERR_PASSWORD); SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE ); return TRUE; } else if (sc == SCHED_E_ACCOUNT_NAME_NOT_FOUND) { // Passwords didn't match. Let the user know so he/she // can correct it. SchedUIErrorDialog(hDlg, IERR_ACCOUNT_NOT_FOUND); SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE ); return TRUE; } } #endif // _CREDENTIALS break; case PSN_SETACTIVE: if (g_pEditSchedPage) g_pEditSchedPage->Initialize(hDlg); break; default: break; } break; case WM_COMMAND: if ((wNotifyCode == EN_CHANGE) && (LOWORD(wParam) == IDC_SCHED_NAME_EDITBOX)) { PropSheet_Changed(GetParent(hDlg), hDlg); g_pEditSchedPage->SetSchedNameDirty(); return TRUE; } break; case WM_HELP: { LPHELPINFO lphi = (LPHELPINFO)lParam; if (lphi->iContextType == HELPINFO_WINDOW) { WinHelp ( (HWND) lphi->hItemHandle, szSyncMgrHelp, HELP_WM_HELP, (ULONG_PTR) g_aContextHelpIds); } return TRUE; } case WM_CONTEXTMENU: { WinHelp ((HWND)wParam, szSyncMgrHelp, HELP_CONTEXTMENU, (ULONG_PTR)g_aContextHelpIds); return TRUE; } default: break; } return FALSE; } //+-------------------------------------------------------------------------- // // Member: CEditSchedPage::CEditSchedPage // // Synopsis: ctor // // [phPSP] - filled with prop page handle // // History: 11-21-1997 SusiA // //--------------------------------------------------------------------------- CEditSchedPage::CEditSchedPage( HINSTANCE hinst, ISyncSchedule *pISyncSched, HPROPSHEETPAGE *phPSP) { ZeroMemory(&m_psp, sizeof(m_psp)); m_psp.dwSize = sizeof (PROPSHEETPAGE); m_psp.hInstance = hinst; m_psp.dwFlags = PSP_DEFAULT; m_psp.pszTemplate = MAKEINTRESOURCE(IDD_SCHEDPAGE_SCHEDULE); m_psp.pszIcon = NULL; m_psp.pfnDlgProc = SchedEditDlgProc; m_psp.lParam = 0; g_pEditSchedPage = this; m_pISyncSched = pISyncSched; m_pISyncSched->AddRef(); *phPSP = CreatePropertySheetPage(&m_psp); } BOOL CEditSchedPage::_Initialize_ScheduleName(HWND hwnd) { BOOL fRetVal = FALSE; TCHAR szStr[MAX_PATH]; DWORD cch = ARRAYSIZE(szStr); //Schedule Name if (SUCCEEDED(m_pISyncSched->GetScheduleName(&cch, szStr))) { m_hwnd = hwnd; HWND hwndName = GetDlgItem(hwnd,IDC_SCHED_NAME); LONG_PTR dwStyle = GetWindowLongPtr(hwndName, GWL_STYLE); SetWindowLongPtr(hwndName, GWL_STYLE, dwStyle | SS_ENDELLIPSIS); SetStaticString(hwndName, szStr); fRetVal = TRUE; } return fRetVal; } BOOL CEditSchedPage::_Initialize_TriggerString(HWND hwnd) { BOOL fRetVal = FALSE; WCHAR szStr[MAX_PATH]; WCHAR szFmt[MAX_PATH]; WCHAR szParam[MAX_PATH]; ITaskTrigger* pITrigger; if (SUCCEEDED(m_pISyncSched->GetTrigger(&pITrigger))) { TASK_TRIGGER TaskTrigger; if (SUCCEEDED(pITrigger->GetTrigger(&TaskTrigger))) { HRESULT hr; switch (TaskTrigger.TriggerType) { case TASK_EVENT_TRIGGER_ON_IDLE: LoadString(g_hmodThisDll, IDS_IDLE_TRIGGER_STRING, szParam, ARRAYSIZE(szParam)); hr = S_OK; break; case TASK_EVENT_TRIGGER_AT_SYSTEMSTART: LoadString(g_hmodThisDll, IDS_SYSTEMSTART_TRIGGER_STRING, szParam, ARRAYSIZE(szParam)); hr = S_OK; break; case TASK_EVENT_TRIGGER_AT_LOGON: LoadString(g_hmodThisDll, IDS_LOGON_TRIGGER_STRING, szParam, ARRAYSIZE(szParam)); hr = S_OK; break; default: { LPWSTR pwszString; hr = pITrigger->GetTriggerString(&pwszString); if (SUCCEEDED(hr)) { hr = StringCchCopy(szParam, ARRAYSIZE(szParam), pwszString); CoTaskMemFree(pwszString); } } break; } if (SUCCEEDED(hr)) { LoadString(g_hmodThisDll, IDS_SCHED_WHEN, szFmt, ARRAYSIZE(szFmt)); if (SUCCEEDED(StringCchPrintf(szStr, ARRAYSIZE(szStr), szFmt, szParam))) { fRetVal = TRUE; } } } pITrigger->Release(); } if (fRetVal) { SetDlgItemText(hwnd,IDC_SCHED_STRING,szStr); } return fRetVal; } BOOL CEditSchedPage::_Initialize_LastRunString(HWND hwnd) { BOOL fRetVal = FALSE; WCHAR szStr[MAX_PATH]; WCHAR szFmt[MAX_PATH]; WCHAR szParam[MAX_PATH]; WCHAR szParam2[MAX_PATH]; SYSTEMTIME st; HRESULT hr = m_pISyncSched->GetMostRecentRunTime(&st); if (S_OK == hr) { DWORD dwDateReadingFlags = GetDateFormatReadingFlags(hwnd); LoadString(g_hmodThisDll, IDS_SCHED_LASTRUN, szFmt, ARRAYSIZE(szFmt)); if (GetDateFormat(LOCALE_USER_DEFAULT,dwDateReadingFlags, &st, NULL,szParam, ARRAYSIZE(szParam)) && GetTimeFormat(LOCALE_USER_DEFAULT, 0, &st, NULL,szParam2, ARRAYSIZE(szParam2)) && SUCCEEDED(StringCchPrintf(szStr, ARRAYSIZE(szStr), szFmt, szParam, szParam2))) { fRetVal = TRUE; } } else if (SUCCEEDED(hr) && S_OK != hr) { LoadString(g_hmodThisDll, IDS_SCHED_NEVERRUN, szStr, ARRAYSIZE(szStr)); fRetVal = TRUE; } if (fRetVal) { SetDlgItemText(hwnd,IDC_LASTRUN,szStr); } return fRetVal; } BOOL CEditSchedPage::_Initialize_NextRunString(HWND hwnd) { BOOL fRetVal = FALSE; WCHAR szStr[MAX_PATH]; WCHAR szFmt[MAX_PATH]; WCHAR szParam[MAX_PATH]; WCHAR szParam2[MAX_PATH]; SYSTEMTIME st; HRESULT hr = m_pISyncSched->GetNextRunTime(&st); if (SCHED_S_EVENT_TRIGGER == hr) { ITaskTrigger* pITrigger; if (SUCCEEDED(m_pISyncSched->GetTrigger(&pITrigger))) { TASK_TRIGGER TaskTrigger; if (SUCCEEDED(pITrigger->GetTrigger(&TaskTrigger))) { switch (TaskTrigger.TriggerType) { case TASK_EVENT_TRIGGER_ON_IDLE: LoadString(g_hmodThisDll, IDS_IDLE_TRIGGER_STRING, szParam, ARRAYSIZE(szParam)); break; case TASK_EVENT_TRIGGER_AT_SYSTEMSTART: LoadString(g_hmodThisDll, IDS_SYSTEMSTART_TRIGGER_STRING, szParam, ARRAYSIZE(szParam)); break; case TASK_EVENT_TRIGGER_AT_LOGON: LoadString(g_hmodThisDll, IDS_LOGON_TRIGGER_STRING, szParam, ARRAYSIZE(szParam)); break; default: Assert(0); break; } LoadString(g_hmodThisDll, IDS_NEXTRUN_EVENT, szFmt, ARRAYSIZE(szFmt)); if (SUCCEEDED(StringCchPrintf(szStr, ARRAYSIZE(szStr), szFmt, szParam))) { fRetVal = TRUE; } } pITrigger->Release(); } } else if (S_OK == hr) { DWORD dwDateReadingFlags = GetDateFormatReadingFlags(hwnd); LoadString(g_hmodThisDll, IDS_SCHED_NEXTRUN, szFmt, ARRAYSIZE(szFmt)); if (SUCCEEDED(GetDateFormat(LOCALE_USER_DEFAULT, dwDateReadingFlags, &st, NULL,szParam, ARRAYSIZE(szParam))) && SUCCEEDED(GetTimeFormat(LOCALE_USER_DEFAULT, 0, &st, NULL,szParam2, ARRAYSIZE(szParam2))) && SUCCEEDED(StringCchPrintf(szStr, ARRAYSIZE(szStr), szFmt, szParam, szParam2))) { fRetVal = TRUE; } } else if (SUCCEEDED(hr) && S_OK != hr) { LoadString(g_hmodThisDll, IDS_SCHED_NOTAGAIN, szStr, ARRAYSIZE(szStr)); fRetVal = TRUE; } if (fRetVal) { SetDlgItemText(hwnd,IDC_NEXTRUN,szStr); } return fRetVal; } //+-------------------------------------------------------------------------- // // Member: CEditSchedPage::Initialize(HWND hwnd) // // Synopsis: initialize the edit schedule page // // History: 11-21-1997 SusiA // //--------------------------------------------------------------------------- BOOL CEditSchedPage::Initialize(HWND hwnd) { BOOL fRetVal = FALSE; if (_Initialize_ScheduleName(hwnd) && _Initialize_TriggerString(hwnd) && _Initialize_LastRunString(hwnd) && _Initialize_NextRunString(hwnd)) { // set the limit on the edit box for entering the name SendDlgItemMessage(hwnd,IDC_SCHED_NAME_EDITBOX,EM_SETLIMITTEXT,MAX_PATH,0); ShowSchedName(); fRetVal = TRUE; } return fRetVal; } //-------------------------------------------------------------------------------- // // FUNCTION: CEditSchedPage::SetSchedNameDirty() // // PURPOSE: set the sched name dirty // // COMMENTS: Only called frm prop sheet; not wizard // //-------------------------------------------------------------------------------- void CEditSchedPage::SetSchedNameDirty() { m_fSchedNameChanged = TRUE; } //-------------------------------------------------------------------------------- // // FUNCTION: CEditSchedPage::ShowSchedName() // // PURPOSE: change the task's sched name // // COMMENTS: Only called frm prop sheet; not wizard // //-------------------------------------------------------------------------------- BOOL CEditSchedPage::ShowSchedName() { Assert(m_pISyncSched); WCHAR pwszSchedName[MAX_PATH + 1]; DWORD cchSchedName = ARRAYSIZE(pwszSchedName); HWND hwndEdit = GetDlgItem(m_hwnd, IDC_SCHED_NAME_EDITBOX); if (FAILED(m_pISyncSched->GetScheduleName(&cchSchedName, pwszSchedName))) { return FALSE; } Edit_SetText(hwndEdit, pwszSchedName); m_fSchedNameChanged = FALSE; return TRUE; } //-------------------------------------------------------------------------------- // // FUNCTION: CEditSchedPage::SetSchedName() // // PURPOSE: change the task's sched name // // COMMENTS: Only called frm prop sheet; not wizard // //-------------------------------------------------------------------------------- BOOL CEditSchedPage::SetSchedName() { Assert(m_pISyncSched); TCHAR pszSchedName[MAX_PATH + 1]; DWORD dwSize = MAX_PATH; if (m_fSchedNameChanged) { HWND hwndEdit = GetDlgItem(m_hwnd, IDC_SCHED_NAME_EDITBOX); Edit_GetText(hwndEdit, pszSchedName, MAX_PATH); if (S_OK != m_pISyncSched->SetScheduleName(pszSchedName)) { return FALSE; } SetStaticString(GetDlgItem(m_hwnd,IDC_SCHED_NAME), pszSchedName); PropSheet_SetTitle(GetParent(m_hwnd),0, pszSchedName); } return TRUE; } //+-------------------------------------------------------------------------- // // Function: SetStaticString (HWND hwnd, LPTSTR pszString) // // Synopsis: print out the schedule name in a static text string, with the ... // if necessary // // History: 12-Mar-1998 SusiA // //--------------------------------------------------------------------------- BOOL SetStaticString (HWND hwnd, LPTSTR pszString) { Assert(hwnd); Static_SetText(hwnd, pszString); return TRUE; }
30.514395
111
0.491634
npocmaka
5415d1124c1fd493d6ec1787b2e2835f96e6cede
1,220
cpp
C++
aoj/itp2/itp2_8_d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
aoj/itp2/itp2_8_d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
aoj/itp2/itp2_8_d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; #define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i) #define all(x) (x).begin(),(x).end() #define m0(x) memset(x,0,sizeof(x)) int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1}; int main(){ multimap<string, int> m; int q; cin>>q; for(int i = 0; i < q; i++) { int cmd; string key; cin>>cmd>>key; if(cmd==0) { int x; cin>>x; m.insert(make_pair(key,x)); } else if(cmd==1) { auto range = m.equal_range(key); for(auto i = range.first; i != range.second; i++) { cout<<i->second<<endl; } } else if(cmd==2) { m.erase(key); } else if(cmd==3) { string key2; cin>>key2; auto bg = m.lower_bound(key); auto en = m.upper_bound(key2); for(auto i = bg; i != en; i++) { cout<<i->first<<" "<<i->second<<endl; } } } return 0; }
21.034483
61
0.402459
yu3mars
541bfaffb4ce6c05ac29375db2c5ba4705b308b8
810
cpp
C++
src/tracelog/private/tracelog.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
7
2017-02-19T16:22:16.000Z
2021-03-02T05:47:39.000Z
src/tracelog/private/tracelog.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
61
2017-05-29T06:11:17.000Z
2021-03-28T21:51:44.000Z
src/tracelog/private/tracelog.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
2
2017-05-28T17:17:40.000Z
2017-07-14T21:45:16.000Z
// Distributed under the BSD 2-Clause License - Copyright 2012-2021 Robin Degen #include <aeon/tracelog/tracelog.h> #include "context.h" namespace aeon::tracelog { namespace detail { [[nodiscard]] auto add_entry(const char *func) -> trace_log_entry * { return detail::trace_log_context::get_singleton().add_scoped_log_entry(func); } void add_exit(trace_log_entry *entry) { detail::trace_log_context::get_singleton().add_scoped_log_exit(entry); } void add_event(const char *func) { detail::trace_log_context::get_singleton().add_event(func); } } // namespace detail void initialize() { detail::trace_log_context::get_singleton().initialize(); } void write(const std::filesystem::path &file) { detail::trace_log_context::get_singleton().write(file); } } // namespace aeon::tracelog
20.25
81
0.741975
aeon-engine
541d301d93725eeb130a79ba3a58db1dacb76ad6
9,141
cc
C++
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/modflow/src/rch.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/modflow/src/rch.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/modflow/src/rch.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
#ifndef INCLUDED_RCH #include "rch.h" #define INCLUDED_RCH #endif // Library headers. #ifndef INCLUDED_SSTREAM #include <sstream> #define INCLUDED_SSTREAM #endif #ifndef INCLUDED_IOSTREAM #include <iostream> #define INCLUDED_IOSTREAM #endif #ifndef INCLUDED_IOMANIP #include <iomanip> #define INCLUDED_IOMANIP #endif #ifndef INCLUDED_FSTREAM #include <fstream> #define INCLUDED_FSTREAM #endif #ifndef INCLUDED_CASSERT #include <cassert> #define INCLUDED_CASSERT #endif // PCRaster library headers. #ifndef INCLUDED_CALC_SPATIAL #include "calc_spatial.h" #define INCLUDED_CALC_SPATIAL #endif // Module headers. #ifndef INCLUDED_COMMON #include "common.h" #define INCLUDED_COMMON #endif #ifndef INCLUDED_GRIDCHECK #include "gridcheck.h" #define INCLUDED_GRIDCHECK #endif #ifndef INCLUDED_PCRMODFLOW #include "pcrmodflow.h" #define INCLUDED_PCRMODFLOW #endif #ifndef INCLUDED_MF_BINARYREADER #include "mf_BinaryReader.h" #define INCLUDED_MF_BINARYREADER #endif #include "mf_utils.h" /** * Destructor */ RCH::~RCH(){ } /** * Constructor */ RCH::RCH(PCRModflow *mf, size_t rchOpCode) : d_mf(mf), d_nrchop(rchOpCode), // d_irchcb(160), d_inrech(1), d_inirch(1), //d_fortran_unit_number(260), d_output_unit_number(260), d_array_unit_number(261), d_indicated_unit_number(262) { } /** * write RCH to file */ // void RCH::writeRCH() const{ // // std::stringstream content; // content << " " << std::setw(9) << d_nrchop; // content << " " << std::setw(9) << d_fortran_unit_number << std::endl; // content << " " << std::setw(9) << d_inrech; // content << " " << std::setw(9) << d_inirch << std::endl; // // content << "INTERNAL 1.00000E+00 (FREE) -1"; // // d_mf->d_cmethods->writeMatrix(content, "", discr::BlockData<float>(*(d_mf->d_recharge)), 0); // if(d_nrchop == 2){ // if(d_mf->d_rechargeIrch == NULL){ // std::stringstream stmp; // stmp << "No layer number variables IRCH specified"; // d_mf->d_cmethods->error(stmp.str(), "run"); // } // d_mf->d_cmethods->writeMatrix(content, "", discr::BlockData<int>(*(d_mf->d_rechargeIrch)), 0); // } // // d_mf->d_cmethods->writeToFile("pcrmf.rch",content.str()); // } /** * retrieving recharge cell-by-cell flow values from the binary modflow output * rec2 : flow values values for all layer */ // void RCH::getFlowFromBinary(){ // std::ifstream file("fort.160", std::ios::in | std::ios::binary); // if(!file.is_open()){ // std::stringstream stmp; // stmp << "Can not open file containing recharge cell-by-cell flow terms"; // d_mf->d_cmethods->errorMessage(stmp.str(), "run"); // exit(1); // } // // char header[mf::recordMarkerSize]; // int headerSizeBytes = 0; // file.read(header, mf::recordMarkerSize); // std::memcpy(&headerSizeBytes, &(header[0]), 4); // assert(headerSizeBytes == 36); // // // read the header data inclusive // // header information is already known, dummy read // char *headerData = new char[headerSizeBytes + 4]; // file.read(headerData, headerSizeBytes); // + 4 // // // tail of header // char tailHeader[mf::recordMarkerSize + 4]; // int tailSizeBytes = 0; // file.read(tailHeader, mf::recordMarkerSize); // std::memcpy(&tailSizeBytes, &(tailHeader[0]), 4); // assert(tailSizeBytes == 36); // // // data header // char dataHeader[mf::recordMarkerSize + 4]; // int dataSizeBytes = 0; // file.read(dataHeader, mf::recordMarkerSize); // std::memcpy(&dataSizeBytes, &(dataHeader[0]), 4); // // read the data // char *charData = new char[dataSizeBytes]; // file.read(charData, dataSizeBytes); // float *floatData = reinterpret_cast<float *>(charData); // // const size_t cellMax = d_mf->d_nrOfCells; // size_t pos = 0; // for(size_t layer = 0; layer < d_mf->d_nrMFLayer; layer++){ // size_t blockLayer = d_mf->mfLayer2BlockLayer(layer); // for(size_t i = 0; i < cellMax; i++){ // d_mf->d_rechargeResult->cell(i)[blockLayer] = floatData[pos]; // pos++; // } // } // file.close(); // delete[] charData; // charData = NULL; // delete[] headerData; // headerData = NULL; // } void RCH::setRecharge(const calc::Field *rch, size_t optCode){ if(!((optCode == 1) || (optCode == 3))){ std::string stmp("Input error: set recharge option code within either to 1 or 3"); d_mf->d_cmethods->error(stmp, "setRecharge"); } REAL8 value = 0.0; for(size_t i = 0; i < d_mf->d_nrOfCells; i++){ rch->getCell(value, i); d_mf->d_recharge->cell(i)[0] = static_cast<REAL4>(value); } } void RCH::setIndicatedRecharge(const calc::Field *rch, const calc::Field *layer){ if(d_mf->d_rechargeIrch == NULL){ d_mf->d_rechargeIrch = new discr::BlockData<INT4>(d_mf->d_baseArea); } // recharge for(size_t i = 0; i < d_mf->d_nrOfCells; i++){ double value = 0.0; rch->getCell(value, i); d_mf->d_recharge->cell(i)[0] = static_cast<float>(value); } // rch indicator for(size_t i = 0; i < d_mf->d_nrOfCells; i++){ double value = 0.0; layer->getCell(value, i); d_mf->d_rechargeIrch->cell(i)[0] = static_cast<int>(value); } } // discr::BlockData<REAL4>* RCH::getBlockCellByCellFlow(){ // discr::BlockData<REAL4> *resultRch = new discr::BlockData<REAL4>(d_mf->d_baseArea); // d_mf->d_cmethods->setDiscrBlockData(*(d_mf->d_rechargeResult), *resultRch); // return resultRch; // } calc::Field* RCH::getRecharge(size_t layer, std::string const& path) const { layer--; // layer number passed by user starts with 1 d_mf->d_gridCheck->isGrid(layer, "getRiverLeakage"); d_mf->d_gridCheck->isConfined(layer, "getRiverLeakage"); const std::string desc(" RECHARGE"); std::stringstream stmp; stmp << "Can not open file containing DRAINS cell-by-cell flow terms"; // modflow reports from top to bottom, thus // get the 'inverse' layer number to start from the right position int pos_multiplier = d_mf->get_modflow_layernr(layer); calc::Spatial* spatial = new calc::Spatial(VS_S, calc::CRI_f, d_mf->d_nrOfCells); REAL4* cells = static_cast<REAL4*>(spatial->dest()); mf::BinaryReader reader; const std::string filename(mf::execution_path(path, "fort." + boost::lexical_cast<std::string>(d_output_unit_number))); reader.read(stmp.str(), filename, cells, desc, pos_multiplier); return spatial; } /** * writing rch cbc flow to PCR map */ void RCH::getRecharge(float *values, size_t layer, std::string const& path) const { layer--; // layer number passed by user starts with 1 d_mf->d_gridCheck->isGrid(layer, "getRecharge"); d_mf->d_gridCheck->isConfined(layer, "getRecharge"); const std::string desc(" RECHARGE"); std::stringstream stmp; stmp << "Can not open file containing recharge cell-by-cell flow terms"; // modflow reports from top to bottom, thus // get the 'inverse' layer number to start from the right position int pos_multiplier = d_mf->get_modflow_layernr(layer); //get_binary(cells, desc, start_pos, pos_multiplier); mf::BinaryReader reader; const std::string filename(mf::execution_path(path, "fort." + boost::lexical_cast<std::string>(d_output_unit_number))); reader.read(stmp.str(), filename, values, desc, pos_multiplier); } void RCH::write(std::string const& path){ std::string filename = mf::execution_path(path, "pcrmf.rch"); std::ofstream content(filename); if(!content.is_open()){ std::cerr << "Can not write " << filename << std::endl; exit(1); } content << "# Generated by PCRaster Modflow\n"; content << d_nrchop; content << " " << d_output_unit_number << "\n"; content << d_inrech << " " << d_inirch << "\n"; content << "EXTERNAL " << d_array_unit_number << " 1.0 (FREE) -1\n"; if(indicated_recharge()){ if(d_mf->d_rechargeIrch == NULL){ std::stringstream stmp; stmp << "No layer number variables IRCH specified"; d_mf->d_cmethods->error(stmp.str(), "run"); } content << "EXTERNAL " << d_indicated_unit_number << " 1.0 (FREE) -1\n"; } content.close(); } void RCH::write_array(std::string const& path){ std::string filename = mf::execution_path(path, "pcrmf_rch.asc"); std::ofstream content(filename); if(!content.is_open()){ std::cerr << "Can not write " << filename << std::endl; exit(1); } size_t count = 0; for(size_t r = 0; r < d_mf->d_nrOfRows; ++r){ for(size_t c = 0; c < d_mf->d_nrOfColumns ; ++c){ content << d_mf->d_recharge->cell(count)[0] << " "; count++; } content << "\n"; } content.close(); } void RCH::write_indicated(std::string const& path){ std::string filename = mf::execution_path(path, "pcrmf_irch.asc"); std::ofstream content(filename); if(!content.is_open()){ std::cerr << "Can not write " << filename << std::endl; exit(1); } size_t count = 0; for(size_t r = 0; r < d_mf->d_nrOfRows; ++r){ for(size_t c = 0; c < d_mf->d_nrOfColumns ; ++c){ content << d_mf->d_rechargeIrch->cell(count)[0] << " "; count++; } content << "\n"; } content.close(); } bool RCH::indicated_recharge() const { return d_nrchop == 2 ? true : false; }
26.650146
121
0.654524
quanpands
541e01fdbff03a08805c8f222193e8d6f48263c0
4,426
cc
C++
net/quic/quic_write_blocked_list_test.cc
iplo/Chain
8bc8943d66285d5258fffc41bed7c840516c4422
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
net/quic/quic_write_blocked_list_test.cc
JasonEric/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-02-14T21:55:58.000Z
2017-02-14T21:55:58.000Z
net/quic/quic_write_blocked_list_test.cc
JasonEric/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright 2014 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 "net/quic/quic_write_blocked_list.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace test { namespace { TEST(QuicWriteBlockedListTest, PriorityOrder) { QuicWriteBlockedList write_blocked_list; // Mark streams blocked in roughly reverse priority order, and // verify that streams are sorted. write_blocked_list.PushBack(40, QuicWriteBlockedList::kLowestPriority, QUIC_VERSION_13); write_blocked_list.PushBack(23, QuicWriteBlockedList::kHighestPriority, QUIC_VERSION_13); write_blocked_list.PushBack(17, QuicWriteBlockedList::kHighestPriority, QUIC_VERSION_13); write_blocked_list.PushBack(kHeadersStreamId, QuicWriteBlockedList::kHighestPriority, QUIC_VERSION_13); write_blocked_list.PushBack(kCryptoStreamId, QuicWriteBlockedList::kHighestPriority, QUIC_VERSION_13); EXPECT_EQ(5u, write_blocked_list.NumBlockedStreams()); EXPECT_TRUE(write_blocked_list.HasWriteBlockedStreams()); // The Crypto stream is highest priority. EXPECT_EQ(kCryptoStreamId, write_blocked_list.PopFront()); // Followed by the Headers stream. EXPECT_EQ(kHeadersStreamId, write_blocked_list.PopFront()); // Streams with same priority are popped in the order they were inserted. EXPECT_EQ(23u, write_blocked_list.PopFront()); EXPECT_EQ(17u, write_blocked_list.PopFront()); // Low priority stream appears last. EXPECT_EQ(40u, write_blocked_list.PopFront()); EXPECT_EQ(0u, write_blocked_list.NumBlockedStreams()); EXPECT_FALSE(write_blocked_list.HasWriteBlockedStreams()); } TEST(QuicWriteBlockedListTest, CryptoStream) { QuicWriteBlockedList write_blocked_list; write_blocked_list.PushBack(kCryptoStreamId, QuicWriteBlockedList::kHighestPriority, QUIC_VERSION_13); EXPECT_EQ(1u, write_blocked_list.NumBlockedStreams()); EXPECT_TRUE(write_blocked_list.HasWriteBlockedStreams()); EXPECT_EQ(kCryptoStreamId, write_blocked_list.PopFront()); EXPECT_EQ(0u, write_blocked_list.NumBlockedStreams()); EXPECT_FALSE(write_blocked_list.HasWriteBlockedStreams()); } TEST(QuicWriteBlockedListTest, HeadersStream) { QuicWriteBlockedList write_blocked_list; write_blocked_list.PushBack(kHeadersStreamId, QuicWriteBlockedList::kHighestPriority, QUIC_VERSION_13); EXPECT_EQ(1u, write_blocked_list.NumBlockedStreams()); EXPECT_TRUE(write_blocked_list.HasWriteBlockedStreams()); EXPECT_EQ(kHeadersStreamId, write_blocked_list.PopFront()); EXPECT_EQ(0u, write_blocked_list.NumBlockedStreams()); EXPECT_FALSE(write_blocked_list.HasWriteBlockedStreams()); } TEST(QuicWriteBlockedListTest, NoHeadersStreamInVersion12) { for (int idx = 0; idx < 2; ++idx) { QuicVersion version = ((idx == 0) ? QUIC_VERSION_13 : QUIC_VERSION_12); QuicWriteBlockedList write_blocked_list; write_blocked_list.PushBack(5, QuicWriteBlockedList::kHighestPriority, version); write_blocked_list.PushBack(kHeadersStreamId, QuicWriteBlockedList::kHighestPriority, version); EXPECT_EQ(2u, write_blocked_list.NumBlockedStreams()); EXPECT_TRUE(write_blocked_list.HasWriteBlockedStreams()); if (version > QUIC_VERSION_12) { // In newer QUIC versions, there is a headers stream which is // higher priority than data streams. EXPECT_EQ(kHeadersStreamId, write_blocked_list.PopFront()); EXPECT_EQ(5u, write_blocked_list.PopFront()); } else { // In older QUIC versions, there is no reserved headers stream id. EXPECT_EQ(5u, write_blocked_list.PopFront()); EXPECT_EQ(kHeadersStreamId, write_blocked_list.PopFront()); } EXPECT_EQ(0u, write_blocked_list.NumBlockedStreams()); EXPECT_FALSE(write_blocked_list.HasWriteBlockedStreams()); } } } // namespace } // namespace test } // namespace net
41.364486
75
0.694306
iplo
541f87f1f149ffa7574bb4c0d7df1b7f875c3b4e
9,609
cpp
C++
f9_os/src/f9/ktimer.cpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
null
null
null
f9_os/src/f9/ktimer.cpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
null
null
null
f9_os/src/f9/ktimer.cpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
1
2020-03-08T01:08:38.000Z
2020-03-08T01:08:38.000Z
/* * ktimer.cpp * * Created on: May 19, 2017 * Author: Paul */ #include "ktimer.hpp" #include "irq.hpp" #include "schd.hpp" #if defined(CONFIG_KTIMER_TICKLESS) && defined(CONFIG_KTIMER_TICKLESS_VERIFY) #include "tickless-verify.h" #endif namespace f9 { DECLARE_KTABLE(ktimer_event_t, ktimer_event_table, CONFIG_MAX_KT_EVENTS); /* Next chain of events which will be executed */ ktimer_event_t *event_queue = nullptr; static uint64_t ktimer_now; static uint32_t ktimer_enabled = 0; static uint32_t ktimer_delta = 0; static long long ktimer_time = 0; //extern uint32_t SystemCoreClock; //HAL_RCC_GetHCLKFreq() == SystemCoreClock static void init_systick(uint32_t tick_reload, uint32_t tick_next_reload) { /* 250us at 168Mhz */ SysTick->LOAD = tick_reload - 1; SysTick->VAL = 0; SysTick->CTRL = 0x00000007; if (tick_next_reload) SysTick->LOAD = tick_next_reload - 1; } static void systick_disable() { SysTick->CTRL = 0x00000000;} static uint32_t systick_now(){ return SysTick->VAL;} static uint32_t systick_flag_count() { return (SysTick->CTRL & (1 << 16)) >> 16;} static void ktimer_init(void) { init_systick(CONFIG_KTIMER_HEARTBEAT, 0); } void ktimer_event_init() { NVIC_SetPriority(SysTick_IRQn, 1);// one higher than 0 NVIC_SetPriority(PendSV_IRQn, 0xFF);// highest it can ever go // ktable_init(&ktimer_event_table); ktimer_init(); // softirq_register(KTE_SOFTIRQ, ktimer_event_handler); } //INIT_HOOK(ktimer_event_init, INIT_LEVEL::KERNEL); static void ktimer_disable(void) { if (ktimer_enabled) { ktimer_enabled = 0; } } static void ktimer_enable(uint32_t delta) { if (!ktimer_enabled) { ktimer_delta = delta; ktimer_time = 0; ktimer_enabled = 1; #if defined(CONFIG_KDB) && \ defined(CONFIG_KTIMER_TICKLESS) && defined(CONFIG_KTIMER_TICKLESS_VERIFY) tickless_verify_start(ktimer_now, ktimer_delta); #endif /* CONFIG_KDB */ } } ktimer_event_t::~ktimer_event_t(){ assert(next==nullptr); } class ktimer_softirq_handler_t : public softirq_t { void run() final { ktimer_event_t *event = event_queue; ktimer_event_t *last_event = NULL; ktimer_event_t *next_event = NULL; uint32_t h_retvalue = 0; if (!event_queue) { /* That is bug if we are here */ dbg::print(dbg::DL_KTIMER, "KTE: OOPS! handler found no events\n"); ktimer_disable(); return; } /* Search last event in event chain */ do { event = event->next; } while (event && event->delta == 0); last_event = event; /* All rescheduled events will be scheduled after last event */ event = event_queue; event_queue = last_event; /* walk chain */ do { h_retvalue = event->handler(event); next_event = event->next; if (h_retvalue != 0x0) { dbg::print(dbg::DL_KTIMER, "KTE: Handled and rescheduled event %p @%ld\n", event, ktimer_now); event->schedule(h_retvalue); } else { dbg::print(dbg::DL_KTIMER, "KTE: Handled event %p @%ld\n", event, ktimer_now); event->next = nullptr; // sanity so delete dosn't fail delete event; } event = next_event; /* Guaranteed to be next regardless of re-scheduling */ } while (next_event && next_event != last_event); if (event_queue) { /* Reset ktimer */ ktimer_enable(event_queue->delta); } } public: ktimer_softirq_handler_t() : softirq_t(SOFTIRQ::KTE) {} }; ktimer_softirq_handler_t ktimer_softirq_handler; static void __ktimer_handler(void) { ++ktimer_now; if (ktimer_enabled && ktimer_delta > 0) { ++ktimer_time; --ktimer_delta; if (ktimer_delta == 0) { ktimer_enabled = 0; ktimer_time = ktimer_delta = 0; #if defined(CONFIG_KDB) && \ defined(CONFIG_KTIMER_TICKLESS) && defined(CONFIG_KTIMER_TICKLESS_VERIFY) tickless_verify_stop(ktimer_now); #endif /* CONFIG_KDB */ ktimer_softirq_handler.schedule(); } } } #ifdef CONFIG_KDB void kdb_show_ktimer(void) { dbg_printf(DL_KDB, "Now is %ld\n", ktimer_now); if (ktimer_enabled) { dbg_printf(DL_KDB, "Ktimer T=%d D=%d\n", ktimer_time, ktimer_delta); } } #if defined(CONFIG_KTIMER_TICKLESS) && defined(CONFIG_KTIMER_TICKLESS_VERIFY) void kdb_show_tickless_verify(void) { static int init = 0; int32_t avg; int times; if (init == 0) { dbg_printf(DL_KDB, "Init tickless verification...\n"); tickless_verify_init(); init++; } else { avg = tickless_verify_stat(&times); dbg_printf(DL_KDB, "Times: %d\nAverage: %d\n", times, avg); } } #endif #endif /* CONFIG_KDB */ void ktimer_event_t::event_recalc(uint32_t new_delta){ dbg::print(dbg::DL_KTIMER, "KTE: Recalculated event %p D=%d -> %d\n", this, this->delta, this->delta - new_delta); this->delta -= new_delta; } ktimer_event_t* ktimer_event_t::create(uint32_t ticks, ktimer_event_handler_t handler,void *data){ ktimer_event_t *kte = nullptr; do { if(handler == nullptr) break; ktimer_event_t *kte = new ktimer_event_t(handler,data); if(kte == nullptr) break; if(!kte->schedule(ticks)) break; return kte; } while(0); if(kte) delete kte; return nullptr; } bool ktimer_event_t::schedule(uint32_t ticks) { long etime = 0, delta = 0; ktimer_event_t *event = nullptr, *next_event = nullptr; if (!ticks) return false; ticks -= ktimer_time; this->next = nullptr; if (event_queue == nullptr) { /* All other events are already handled, so simply schedule * and enable timer */ dbg::print(dbg::DL_KTIMER, "KTE: Scheduled dummy event %p on %d\n", this, ticks); this->delta = ticks; event_queue = this; ktimer_enable(ticks); } else { /* etime is total delta for event from now (-ktimer_value()) * on each iteration we add delta between events. * * Search for event chain until etime is larger than ticks * e.g ticks = 80 * * 0---17------------60----------------60---... * ^ ^ * | (etime + next_event->delta) = * | = 120 - 17 = 103 * etime = 60 - 17 = 43 * * kte is between event(60) and event(120), * delta = 80 - 43 = 37 * insert and recalculate: * * 0---17------------60-------37-------23---... * * */ next_event = event_queue; if (ticks >= event_queue->delta) { do { event = next_event; etime += event->delta; delta = ticks - etime; next_event = event->next; } while (next_event && ticks > (etime + next_event->delta)); dbg::print(dbg::DL_KTIMER, "KTE: Scheduled event %p [%p:%p] with " "D=%d and T=%d\n", this, event, next_event, delta, ticks); /* Insert into chain and recalculate */ event->next = this; } else { /* Event should be scheduled before earlier event */ dbg::print(dbg::DL_KTIMER, "KTE: Scheduled early event %p with T=%d\n", this, ticks); event_queue = this; delta = ticks; /* Reset timer */ ktimer_enable(ticks); } /* Chaining events */ if (delta < static_cast<int>(CONFIG_KTIMER_MINTICKS)) delta = 0; this->next = next_event; this->delta = delta; next_event->event_recalc(delta); } return 0; } #ifdef CONFIG_KDB void kdb_dump_events(void) { ktimer_event_t *event = event_queue; dbg_puts("\nktimer events: \n"); dbg_printf(DL_KDB, "%8s %12s\n", "EVENT", "DELTA"); while (event) { dbg_printf(DL_KDB, "%p %12d\n", event, event->delta); event = event->next; } } #endif #ifdef CONFIG_KTIMER_TICKLESS #define KTIMER_MAXTICKS (SYSTICK_MAXRELOAD / CONFIG_KTIMER_HEARTBEAT) static uint32_t volatile ktimer_tickless_compensation = CONFIG_KTIMER_TICKLESS_COMPENSATION; static uint32_t volatile ktimer_tickless_int_compensation = CONFIG_KTIMER_TICKLESS_INT_COMPENSATION; void ktimer_enter_tickless() { uint32_t tickless_delta; uint32_t reload; irq_disable(); if (ktimer_enabled && ktimer_delta <= KTIMER_MAXTICKS) { tickless_delta = ktimer_delta; } else { tickless_delta = KTIMER_MAXTICKS; } /* Minus 1 for current value */ tickless_delta -= 1; reload = CONFIG_KTIMER_HEARTBEAT * tickless_delta; reload += systick_now() - ktimer_tickless_compensation; if (reload > 2) { init_systick(reload, CONFIG_KTIMER_HEARTBEAT); #if defined(CONFIG_KDB) && \ defined(CONFIG_KTIMER_TICKLESS) && defined(CONFIG_KTIMER_TICKLESS_VERIFY) tickless_verify_count(); #endif } wait_for_interrupt(); if (!systick_flag_count()) { uint32_t tickless_rest = (systick_now() / CONFIG_KTIMER_HEARTBEAT); if (tickless_rest > 0) { int reload_overflow; tickless_delta = tickless_delta - tickless_rest; reload = systick_now() % CONFIG_KTIMER_HEARTBEAT - ktimer_tickless_int_compensation; reload_overflow = reload < 0; reload += reload_overflow * CONFIG_KTIMER_HEARTBEAT; init_systick(reload, CONFIG_KTIMER_HEARTBEAT); if (reload_overflow) { tickless_delta++; } #if defined(CONFIG_KDB) && \ defined(CONFIG_KTIMER_TICKLESS) && defined(CONFIG_KTIMER_TICKLESS_VERIFY) tickless_verify_count_int(); #endif } } ktimer_time += tickless_delta; ktimer_delta -= tickless_delta; ktimer_now += tickless_delta; irq_enable(); } #endif /* CONFIG_KTIMER_TICKLESS */ }; /* namespace f9 */ IRQ_HANDLER(SysTick_Handler, f9::__ktimer_handler);
24.575448
100
0.649807
ghsecuritylab
54234cd4491f1b6685e1a9969dcb9076854633ce
2,922
cpp
C++
CPlusPlus/Console App Projects/Cashier App/Src/Main.cpp
BillyFrcs/CPPPrograming
3904d30413aaea6c9109b8c5250c44c67aa0fc20
[ "MIT" ]
3
2021-12-17T02:45:51.000Z
2022-03-31T23:55:38.000Z
CPlusPlus/Console App Projects/Cashier App/Src/Main.cpp
BillyFrcs/Programming
32dc67ce4c12189b56921de63446d79c25799457
[ "MIT" ]
1
2021-06-12T08:28:38.000Z
2021-06-12T08:28:38.000Z
CPlusPlus/Console App Projects/Cashier App/Src/Main.cpp
BillyFrcs/Programming
32dc67ce4c12189b56921de63446d79c25799457
[ "MIT" ]
2
2021-04-28T20:08:55.000Z
2021-05-25T08:45:54.000Z
#include <iostream> #include <string> #include <vector> constexpr int INDEX = 30; constexpr int MONEY = 1000; namespace Program { struct Cashier { char nameCashier[INDEX], item[INDEX]; long double price, total, subTotalPrice, inputPrice; int input; }; class CashierProgram { public: CashierProgram() { system("cls"); std::cout << "Masukan nama kasir: "; std::cin.get(_c.nameCashier, INDEX); std::cout << "Masukan jumlah barang yang ingin dibeli: "; std::cin >> _c.input; std::cout << "\nHi " << _c.nameCashier << " petugas kasir, silahkan masukan barang belanjaan customer sebanyak " << _c.input << " kali.\n"; } void inputGrocery() { for (auto i = 0; i < _c.input; i++) { std::cin.ignore(); std::cout << "\nMasukan nama barang: "; std::cin.get(_c.item, INDEX); std::cout << "Masukan harga barang Rp."; std::cin >> _c.price; std::cout << "Masukan jumlah barang: "; std::cin >> _c.total; _vertex.push_back(_c); } } void displayGrocery() { std::cout << "\n===== Daftar Belanjaan =====\n"; for (auto i = 0; i < _c.input; i++) { _c = _vertex[i]; std::cout << "\nNama barang yang dibeli: " << _c.item << std::endl; std::cout << "Jumlah barang yang dibeli: " << _c.total << std::endl; _c.subTotalPrice = (_c.total * _c.price); std::cout << "Sub total barang Rp. " << _c.subTotalPrice << std::endl; _countTotal += _c.subTotalPrice; } std::cout << "\nTotal pembayaran Rp." << _countTotal << std::endl; } void paying() { std::cout << "\nEnter total paying(Masukan Total Pembayaran): "; std::cin >> _c.inputPrice; double counter = (_c.inputPrice - _countTotal); if (_c.inputPrice > MONEY) { std::cout << "Thank you for your paying, here's your change Rp." << counter << std::endl; } else { std::cout << "Sorry you're money is not enough \n"; } } private: std::vector<Cashier> _vertex; Cashier _c; double _countTotal; }; } int main() { Program::CashierProgram *PC = new Program::CashierProgram; PC->inputGrocery(); PC->displayGrocery(); PC->paying(); return EXIT_SUCCESS; }
27.308411
127
0.449008
BillyFrcs
54241cf24a2498962ebfbf4679ac5c865480b286
1,844
cpp
C++
codes/codechef/COVID19B.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/codechef/COVID19B.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/codechef/COVID19B.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
/* ************************************************ username : smmehrab fullname : s.m.mehrabul islam email : mehrab.24csedu.001@gmail.com institute : university of dhaka, bangladesh session : 2017-2018 ************************************************ */ #include<bits/stdc++.h> using namespace std; int main(){ int testCases, n, worstCase, bestCase, t, x; cin >> testCases; while(testCases--){ cin >> n; vector<int> v(n); for(int &x : v) cin >> x; bestCase = n; worstCase = 0; map<pair<int,int>, vector<int>> pairsMeetingAt; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++) { if(v[i]>v[j]){ t= ((j-i)*120)/(v[i]-v[j]); x = i*120+v[i]*t; assert(120*i+v[i]*t == 120*j+v[j]*t); pairsMeetingAt[{t,x}].push_back(i); pairsMeetingAt[{t,x}].push_back(j); } } } for(int infectedAthlete=0; infectedAthlete<n; infectedAthlete++){ vector<bool>isInfected(n, false); isInfected[infectedAthlete]=true; for(auto entry : pairsMeetingAt){ bool spread = false; for(int athlete : entry.second) spread |= isInfected[athlete]; if(spread){ for(int athlete : entry.second) isInfected[athlete]=true; } } int totalInfected=0; for(int athlete=0; athlete<n; athlete++){ if(isInfected[athlete]) totalInfected++; } bestCase = min(bestCase, totalInfected); worstCase = max(worstCase, totalInfected); } cout << bestCase << " " << worstCase << endl; } return 0; }
30.229508
78
0.457158
smmehrab
5425887d7dc38fe98b25608a3311e5a1f22a96aa
299
cpp
C++
ALGS200x/Week2/Challenge2-6/CPP/reuse_main.cpp
davidlowryduda/udacity
fd55ab3f40a77baa49e47a8c08ce42cd823decd9
[ "MIT" ]
null
null
null
ALGS200x/Week2/Challenge2-6/CPP/reuse_main.cpp
davidlowryduda/udacity
fd55ab3f40a77baa49e47a8c08ce42cd823decd9
[ "MIT" ]
null
null
null
ALGS200x/Week2/Challenge2-6/CPP/reuse_main.cpp
davidlowryduda/udacity
fd55ab3f40a77baa49e47a8c08ce42cd823decd9
[ "MIT" ]
null
null
null
/* * Compute fib(0) + ... + fib(n) % 10. * * The key is that fib(0) + ... + fib(n) = fib(n+2) - 1. */ #include <iostream> #include "reuse_util.h" int main() { long num, ans; while (std::cin >> num) { ans = (fast_fib_mod(num+2, 10) + 9) % 10; std::cout << ans << std::endl; } }
15.736842
56
0.494983
davidlowryduda
5426701ad304f3608aea38914f89f5f597c48345
8,402
cpp
C++
lib/src/backend/cl/image/sampling.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
lib/src/backend/cl/image/sampling.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
lib/src/backend/cl/image/sampling.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "../../../gpu/image/sampling.hpp" #include "../kernel.hpp" namespace { #include "sampling.xxd" } INDIRECT_REGISTER_OPENCL_PROGRAM(sampling, true); #define BLOCK_SIZE 16 namespace VideoStitch { namespace Image { /** * Subsample a buffer by a factor of two, picking the topleft value for every 2x2 pixels blocks. * WARNING: no antialiasing filter ! Blur first ! * @param dst subsampled buffer, size (srcWidth / 2) * (srcHeight / 2). * @param src subsampled buffer, size srcWidth * srcHeight. * @param srcWidth Source width. * @param srcHeight Source height. * @param stream Cuda stream to run in. */ template <typename T> Status subsample22(GPU::Buffer<T> dst, GPU::Buffer<const T> src, std::size_t srcWidth, std::size_t srcHeight, GPU::Stream stream) { std::size_t dstWidth = (srcWidth + 1) / 2; std::size_t dstHeight = (srcHeight + 1) / 2; // interior { auto kernel2D = GPU::Kernel::get(PROGRAM(sampling), KERNEL_STR(subsample22RegularKernel)) .setup2D(stream, (unsigned)dstWidth, (unsigned)dstHeight); FAIL_RETURN(kernel2D.enqueueWithKernelArgs(dst, src, (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight)); } // right boundary if (srcWidth & 1) { auto kernel2D = GPU::Kernel::get(PROGRAM(sampling), KERNEL_STR(subsample22RightBoundaryKernel)) .setup1D(stream, (unsigned)dstHeight); FAIL_RETURN(kernel2D.enqueueWithKernelArgs(dst, src, (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight)); } // bottom boundary if (srcHeight & 1) { auto kernel2D = GPU::Kernel::get(PROGRAM(sampling), KERNEL_STR(subsample22RightBoundaryKernel)) .setup1D(stream, (unsigned)dstWidth); FAIL_RETURN(kernel2D.enqueueWithKernelArgs(dst, src, (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight)); } if ((srcWidth & 1) && (srcHeight & 1)) { // simple copy of the last element return CL_ERROR(clEnqueueCopyBuffer(stream.get(), src.get(), dst.get(), srcHeight * srcWidth - 1, dstWidth * dstHeight - 1, sizeof(T), 0, nullptr, nullptr)); } return Status::OK(); } /** * Subsample a buffer by a factor of two, picking the topleft value for every 2x2 pixels blocks. * WARNING: no antialiasing filter ! Blur first ! * @param dst subsampled buffer, size (srcWidth / 2) * (srcHeight / 2). Pixels in RGB210. * @param src subsampled buffer, size srcWidth * srcHeight. Pixel in RGBA. * @param srcWidth Source width. * @param srcHeight Source height. * @param stream Cuda stream to run in. */ Status subsample22RGBA(GPU::Buffer<uint32_t> dst, GPU::Buffer<const uint32_t> src, std::size_t srcWidth, std::size_t srcHeight, GPU::Stream stream) { std::size_t dstWidth = (srcWidth + 1) / 2; std::size_t dstHeight = (srcHeight + 1) / 2; // interior { auto kernel2D = GPU::Kernel::get(PROGRAM(sampling), KERNEL_STR(subsample22RGBARegularKernel)) .setup2D(stream, (unsigned)dstWidth, (unsigned)dstHeight); FAIL_RETURN(kernel2D.enqueueWithKernelArgs(dst, src, (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth)); } // right boundary if (srcWidth & 1) { auto kernel2D = GPU::Kernel::get(PROGRAM(sampling), KERNEL_STR(subsample22RGBARightBoundaryKernel)) .setup1D(stream, (unsigned)dstHeight); FAIL_RETURN(kernel2D.enqueueWithKernelArgs(dst, src, (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth)); } // bottom boundary if (srcHeight & 1) { auto kernel2D = GPU::Kernel::get(PROGRAM(sampling), KERNEL_STR(subsample22RGBABottomBoundaryKernel)) .setup1D(stream, (unsigned)dstWidth); FAIL_RETURN(kernel2D.enqueueWithKernelArgs(dst, src, (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth)); } if ((srcWidth & 1) && (srcHeight & 1)) { // simple copy of the last element return CL_ERROR(clEnqueueCopyBuffer(stream.get(), src.get(), dst.get(), srcHeight * srcWidth - 1, dstWidth * dstHeight - 1, sizeof(uint32_t), 0, nullptr, nullptr)); } return Status::OK(); } /** * Upsamples a buffer. * @param dst subsampled buffer, size dstWidth * dstHeight. * @param src subsampled buffer, size (dstWidth / 2) * (dstHeight / 2). * @param dstWidth Destination width. * @param dstHeight Destination height. * @param stream Cuda stream to run in. */ template <typename T> Status upsample22(GPU::Buffer<T> dst, GPU::Buffer<const T> src, std::size_t dstWidth, std::size_t dstHeight, bool wrap, GPU::Stream stream) { const unsigned srcWidth = ((unsigned)dstWidth + 1) / 2; const unsigned srcHeight = ((unsigned)dstHeight + 1) / 2; auto kernel2D = GPU::Kernel::get(PROGRAM(sampling), KERNEL_STR(upsample22KernelScalar)) .setup2D(stream, (unsigned)srcWidth, (unsigned)srcHeight, BLOCK_SIZE); return kernel2D.enqueueWithKernelArgs(dst, src, (unsigned)dstWidth, (unsigned)dstHeight, (unsigned)srcWidth, (unsigned)srcHeight, (int)wrap); } /** * Upsamples an image in RGB210. * @param dst subsampled buffer, size dstWidth * dstHeight. * @param src subsampled buffer, size (dstWidth / 2) * (dstHeight / 2). * @param dstWidth Destination width. * @param dstHeight Destination height. * @param stream Cuda stream to run in. */ Status upsample22RGBA210(GPU::Buffer<uint32_t> dst, GPU::Buffer<const uint32_t> src, std::size_t dstWidth, std::size_t dstHeight, bool wrap, GPU::Stream stream) { const unsigned srcWidth = ((unsigned)dstWidth + 1) / 2; const unsigned srcHeight = ((unsigned)dstHeight + 1) / 2; auto kernel2D = GPU::Kernel::get(PROGRAM(sampling), KERNEL_STR(upsample22KernelRGB210)) .setup2D(stream, (unsigned)srcWidth, (unsigned)srcHeight, BLOCK_SIZE); return kernel2D.enqueueWithKernelArgs(dst, src, (unsigned)dstWidth, (unsigned)dstHeight, (unsigned)srcWidth, (unsigned)srcHeight, (int)wrap); } /** * Upsamples an image in RGBA. * @param dst subsampled buffer, size dstWidth * dstHeight. * @param src subsampled buffer, size (dstWidth / 2) * (dstHeight / 2). * @param dstWidth Destination width. * @param dstHeight Destination height. * @param blockSize Cuda block size (effective size is blockSize * blockSize) * @param stream Cuda stream to run in. */ Status upsample22RGBA(GPU::Buffer<uint32_t> dst, GPU::Buffer<const uint32_t> src, std::size_t dstWidth, std::size_t dstHeight, bool wrap, GPU::Stream stream) { const unsigned srcWidth = ((unsigned)dstWidth + 1) / 2; const unsigned srcHeight = ((unsigned)dstHeight + 1) / 2; auto kernel2D = GPU::Kernel::get(PROGRAM(sampling), KERNEL_STR(upsample22KernelRGBA)) .setup2D(stream, (unsigned)srcWidth, (unsigned)srcHeight, BLOCK_SIZE); return kernel2D.enqueueWithKernelArgs(dst, src, (unsigned)dstWidth, (unsigned)dstHeight, (unsigned)srcWidth, (unsigned)srcHeight, (int)wrap); } /** * Subsamples the given mask by a factor of two. For each 2x2 pixel block, the output pixel is masked out if any of the * input pixels is masked out (i.e. any pixel has value 1). * @param dst subsampled buffer, size (srcWidth / 2) * (srcHeight / 2). * @param src subsampled buffer, size srcWidth * srcHeight. * @param srcWidth Source width. * @param srcHeight Source height. * @param blockSize Cuda block size (effective size is blockSize * blockSize) * @param stream Cuda stream to run in. */ Status subsampleMask22(GPU::Buffer<unsigned char> /*dst*/, GPU::Buffer<const unsigned char> /*src*/, std::size_t /*srcWidth*/, std::size_t /*srcHeight*/, unsigned int /*blockSize*/, GPU::Stream /*stream*/) { // TODO_OPENCL_IMPL return {Origin::Stitcher, ErrType::UnsupportedAction, "Masked subsampling not implemented in OpenCL backend"}; } #include "../../common/sampling.inst" } // namespace Image } // namespace VideoStitch
47.202247
119
0.665199
tlalexander
542941f130e87debf917c04e1a8ba28f233f17c6
600
cpp
C++
URI/Beginner/Little Ducks.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
URI/Beginner/Little Ducks.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
URI/Beginner/Little Ducks.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; unsigned long long N; int main () { while ( cin >> N && N != -1 ){ cout << ((N>0)? N-1 : 0) << '\n'; } return 0; } /* unsigned long long you dump bitch! input:- ----------- inline string ToString( int n ){ stringstream s; s << n; return s.str(); } int ToInt( char s ){ int n = 0; stringstream (s) >> n; return n; } 0 1 10000000000000000000 -1 0 1 10000000000000000000 -1 100 0 0 1 (n=0)? { n = 9; c = 1 } 9, 9 (n>0)? { n-= (C+1); c = 0;} --, -- 100 0 0 1 output:- ----------- Problem: */
7.142857
35
0.486667
Mhmd-Hisham
542a3b3353400afc9648553f6802ff70e4dd2870
2,451
cpp
C++
src/voiceinfo.cpp
moutend/AudioAgent
dbdc6eff00986892ba1d334a91826a249ddac93d
[ "MIT" ]
1
2019-10-22T08:20:46.000Z
2019-10-22T08:20:46.000Z
src/voiceinfo.cpp
moutend/AudioAgent
dbdc6eff00986892ba1d334a91826a249ddac93d
[ "MIT" ]
null
null
null
src/voiceinfo.cpp
moutend/AudioAgent
dbdc6eff00986892ba1d334a91826a249ddac93d
[ "MIT" ]
null
null
null
#include <cpplogger/cpplogger.h> #include <cstring> #include <ppltasks.h> #include <roapi.h> #include <robuffer.h> #include <wrl.h> #include "context.h" #include "util.h" #include "voiceinfo.h" using namespace Microsoft::WRL; using namespace Windows::Media::SpeechSynthesis; using namespace concurrency; using namespace Windows::Storage::Streams; using namespace Windows::Media; using Windows::Foundation::Metadata::ApiInformation; extern Logger::Logger *Log; DWORD WINAPI voiceInfo(LPVOID context) { Log->Info(L"Start Voice info thread", GetCurrentThreadId(), __LONGFILE__); VoiceInfoContext *ctx = static_cast<VoiceInfoContext *>(context); if (ctx == nullptr) { Log->Fail(L"Failed to obtain ctx", GetCurrentThreadId(), __LONGFILE__); return E_FAIL; } RoInitialize(RO_INIT_MULTITHREADED); auto synth = ref new SpeechSynthesizer(); ctx->Count = synth->AllVoices->Size; ctx->VoiceProperties = new VoiceProperty *[synth->AllVoices->Size]; unsigned int defaultVoiceIndex{}; VoiceInformation ^ defaultInfo = synth->DefaultVoice; for (unsigned int i = 0; i < ctx->Count; ++i) { synth->Voice = synth->AllVoices->GetAt(i); ctx->VoiceProperties[i] = new VoiceProperty(); size_t idLength = wcslen(synth->Voice->Id->Data()); ctx->VoiceProperties[i]->Id = new wchar_t[idLength + 1]{}; std::wmemcpy(ctx->VoiceProperties[i]->Id, synth->Voice->Id->Data(), idLength); size_t displayNameLength = wcslen(synth->Voice->DisplayName->Data()); ctx->VoiceProperties[i]->DisplayName = new wchar_t[displayNameLength + 1]{}; std::wmemcpy(ctx->VoiceProperties[i]->DisplayName, synth->Voice->DisplayName->Data(), displayNameLength); size_t languageLength = wcslen(synth->Voice->Language->Data()); ctx->VoiceProperties[i]->Language = new wchar_t[languageLength + 1]{}; std::wmemcpy(ctx->VoiceProperties[i]->Language, synth->Voice->Language->Data(), languageLength); ctx->VoiceProperties[i]->SpeakingRate = synth->Options->SpeakingRate; ctx->VoiceProperties[i]->AudioPitch = synth->Options->AudioPitch; ctx->VoiceProperties[i]->AudioVolume = synth->Options->AudioVolume; if (defaultInfo->Id->Equals(synth->Voice->Id)) { defaultVoiceIndex = i; } } ctx->DefaultVoiceIndex = defaultVoiceIndex; RoUninitialize(); Log->Info(L"End Voice info thread", GetCurrentThreadId(), __LONGFILE__); return S_OK; }
31.025316
80
0.69849
moutend
542aa8ec2fe88175ae719b0e81f98e267fc88114
5,680
cxx
C++
Modules/Loadable/InteractiveTubesToTree/qSlicerInteractiveTubesToTreeModule.cxx
KitwareMedical/Deprecated-VesselView
c8d0f3f7cbfe4a5642ce8fb60c603a2021292b28
[ "Apache-2.0" ]
6
2018-10-02T23:52:49.000Z
2019-11-14T08:24:55.000Z
Modules/Loadable/InteractiveTubesToTree/qSlicerInteractiveTubesToTreeModule.cxx
KitwareMedical/Deprecated-VesselView
c8d0f3f7cbfe4a5642ce8fb60c603a2021292b28
[ "Apache-2.0" ]
null
null
null
Modules/Loadable/InteractiveTubesToTree/qSlicerInteractiveTubesToTreeModule.cxx
KitwareMedical/Deprecated-VesselView
c8d0f3f7cbfe4a5642ce8fb60c603a2021292b28
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Library: VesselView Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QDebug> #include <QtPlugin> // Slicer includes #include <qSlicerCoreApplication.h> #include <qSlicerModuleManager.h> // Logic includes #include <vtkSlicerCLIModuleLogic.h> #include "vtkSlicerSpatialObjectsLogic.h" #include <vtkSlicerInteractiveTubesToTreeLogic.h> // InteractiveTubesToTree includes #include "qSlicerInteractiveTubesToTreeModule.h" #include "qSlicerInteractiveTubesToTreeModuleWidget.h" //----------------------------------------------------------------------------- Q_EXPORT_PLUGIN2 ( qSlicerInteractiveTubesToTreeModule, qSlicerInteractiveTubesToTreeModule ); //----------------------------------------------------------------------------- /// \ingroup Slicer_QtModules_ExtensionTemplate class qSlicerInteractiveTubesToTreeModulePrivate { public: qSlicerInteractiveTubesToTreeModulePrivate(); }; //----------------------------------------------------------------------------- // qSlicerInteractiveTubesToTreeModulePrivate methods //----------------------------------------------------------------------------- qSlicerInteractiveTubesToTreeModulePrivate::qSlicerInteractiveTubesToTreeModulePrivate() { } //----------------------------------------------------------------------------- //qSlicerInteractiveTubesToTreeModule methods //----------------------------------------------------------------------------- qSlicerInteractiveTubesToTreeModule::qSlicerInteractiveTubesToTreeModule ( QObject* _parent ) : Superclass( _parent ), d_ptr( new qSlicerInteractiveTubesToTreeModulePrivate ) { } //----------------------------------------------------------------------------- qSlicerInteractiveTubesToTreeModule::~qSlicerInteractiveTubesToTreeModule() { } //----------------------------------------------------------------------------- QString qSlicerInteractiveTubesToTreeModule::helpText() const { return "This module helps user to interactively build Tube-Tree from tubes," " i.e assign a parent child relationship to the tubes."; } //----------------------------------------------------------------------------- QString qSlicerInteractiveTubesToTreeModule::acknowledgementText() const { return "This work is part of the VesselView project at Kitware."; } //----------------------------------------------------------------------------- QStringList qSlicerInteractiveTubesToTreeModule::contributors() const { QStringList moduleContributors; moduleContributors << QString( "Sumedha Singla (Kitware Inc)" ); return moduleContributors; } //----------------------------------------------------------------------------- QIcon qSlicerInteractiveTubesToTreeModule::icon() const { return QIcon( ":/Icons/InteractiveTubesToTree.png" ); } //----------------------------------------------------------------------------- QStringList qSlicerInteractiveTubesToTreeModule::categories() const { return QStringList() << "TubeTK"; } //----------------------------------------------------------------------------- QStringList qSlicerInteractiveTubesToTreeModule::dependencies() const { QStringList moduleDependencies; moduleDependencies << "SpatialObjects"; moduleDependencies << "ConvertTubesToTubeTree"; return moduleDependencies; } //----------------------------------------------------------------------------- void qSlicerInteractiveTubesToTreeModule::setup() { this->Superclass::setup(); vtkSlicerInteractiveTubesToTreeLogic* interactiveTubeToTreeLogic = vtkSlicerInteractiveTubesToTreeLogic::SafeDownCast( this->logic() ); qSlicerAbstractCoreModule* conversionModule = qSlicerCoreApplication::application()->moduleManager()->module ( "ConvertTubesToTubeTree" ); qSlicerAbstractCoreModule* spatialObjectsModule = qSlicerCoreApplication::application()->moduleManager()->module( "SpatialObjects" ); if ( conversionModule && spatialObjectsModule ) { vtkSlicerCLIModuleLogic* conversionLogic = vtkSlicerCLIModuleLogic::SafeDownCast( conversionModule->logic() ); interactiveTubeToTreeLogic->SetConversionLogic( conversionLogic ); vtkSlicerSpatialObjectsLogic* spatialObjectsLogic = vtkSlicerSpatialObjectsLogic::SafeDownCast( spatialObjectsModule->logic() ); interactiveTubeToTreeLogic->SetSpatialObjectsLogic( spatialObjectsLogic ); qWarning() << "ConvertTubesToTubeTree module is found"; } else { qWarning() << "ConvertTubesToTubeTree module is not found"; } } //----------------------------------------------------------------------------- qSlicerAbstractModuleRepresentation* qSlicerInteractiveTubesToTreeModule ::createWidgetRepresentation() { return new qSlicerInteractiveTubesToTreeModuleWidget; } //----------------------------------------------------------------------------- vtkMRMLAbstractLogic* qSlicerInteractiveTubesToTreeModule::createLogic() { return vtkSlicerInteractiveTubesToTreeLogic::New(); }
34.846626
88
0.601056
KitwareMedical
542af8de6323bca1b994754e62fe67893df61f91
6,349
cpp
C++
Demo05-Application/DemoApplication.cpp
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
36
2015-06-28T14:53:06.000Z
2021-10-31T04:26:53.000Z
Demo05-Application/DemoApplication.cpp
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
90
2015-05-01T07:21:43.000Z
2017-08-30T01:16:41.000Z
Demo05-Application/DemoApplication.cpp
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
9
2016-04-08T07:48:02.000Z
2019-07-22T15:13:53.000Z
#include <ionWindow.h> #include <ionGraphics.h> #include <ionGraphicsGL.h> #include <ionScene.h> #include <ionApplication.h> using namespace ion; using namespace ion::Scene; using namespace ion::Graphics; int main() { //////////////////// // ionEngine Init // //////////////////// Log::AddDefaultOutputs(); SingletonPointer<CGraphicsAPI> GraphicsAPI; SingletonPointer<CWindowManager> WindowManager; SingletonPointer<CTimeManager> TimeManager; SingletonPointer<CSceneManager> SceneManager; SingletonPointer<CAssetManager> AssetManager; GraphicsAPI->Init(new Graphics::COpenGLImplementation()); WindowManager->Init(GraphicsAPI); TimeManager->Init(WindowManager); SceneManager->Init(GraphicsAPI); AssetManager->Init(GraphicsAPI); CWindow * Window = WindowManager->CreateWindow(vec2i(1600, 900), "DemoApplication", EWindowType::Windowed); AssetManager->AddAssetPath("Assets"); AssetManager->SetShaderPath("Shaders"); AssetManager->SetTexturePath("Images"); SharedPointer<IGraphicsContext> Context = GraphicsAPI->GetWindowContext(Window); SharedPointer<IRenderTarget> RenderTarget = Context->GetBackBuffer(); RenderTarget->SetClearColor(color3f(0.3f)); ///////////////// // Load Assets // ///////////////// CSimpleMesh * SphereMesh = CGeometryCreator::CreateSphere(); CSimpleMesh * SkyBoxMesh = CGeometryCreator::CreateCube(); CSimpleMesh * PlaneMesh = CGeometryCreator::CreatePlane(vec2f(100.f)); SharedPointer<IShader> DiffuseShader = AssetManager->LoadShader("Diffuse"); SharedPointer<IShader> SimpleShader = AssetManager->LoadShader("Simple"); SharedPointer<IShader> SpecularShader = AssetManager->LoadShader("Specular"); SharedPointer<IShader> SkyBoxShader = AssetManager->LoadShader("SkyBox"); SharedPointer<ITextureCubeMap> SkyBoxTexture = AssetManager->LoadCubeMapTexture( "DarkStormyLeft2048.png", "DarkStormyRight2048.png", "DarkStormyUp2048.png", "DarkStormyDown2048.png", "DarkStormyFront2048.png", "DarkStormyBack2048.png"); //////////////////// // ionScene Setup // //////////////////// CRenderPass * RenderPass = new CRenderPass(Context); RenderPass->SetRenderTarget(RenderTarget); SceneManager->AddRenderPass(RenderPass); CPerspectiveCamera * Camera = new CPerspectiveCamera(Window->GetAspectRatio()); Camera->SetPosition(vec3f(0, 3, -5)); Camera->SetFocalLength(0.4f); RenderPass->SetActiveCamera(Camera); CCameraController * Controller = new CCameraController(Camera); Controller->SetTheta(15.f * Constants32::Pi / 48.f); Controller->SetPhi(-Constants32::Pi / 16.f); Window->AddListener(Controller); TimeManager->MakeUpdateTick(0.02)->AddListener(Controller); ///////////////// // Add Objects // ///////////////// CSimpleMeshSceneObject * LightSphere1 = new CSimpleMeshSceneObject(); LightSphere1->SetMesh(SphereMesh); LightSphere1->SetShader(SimpleShader); LightSphere1->SetPosition(vec3f(0, 1, 0)); RenderPass->AddSceneObject(LightSphere1); CSimpleMeshSceneObject * LightSphere2 = new CSimpleMeshSceneObject(); LightSphere2->SetMesh(SphereMesh); LightSphere2->SetShader(SimpleShader); LightSphere2->SetPosition(vec3f(4, 2, 0)); RenderPass->AddSceneObject(LightSphere2); CSimpleMeshSceneObject * LightSphere3 = new CSimpleMeshSceneObject(); LightSphere3->SetMesh(SphereMesh); LightSphere3->SetShader(SimpleShader); LightSphere3->SetPosition(vec3f(12, 3, 0)); RenderPass->AddSceneObject(LightSphere3); CSimpleMeshSceneObject * SpecularSphere = new CSimpleMeshSceneObject(); SpecularSphere->SetMesh(SphereMesh); SpecularSphere->SetShader(SpecularShader); SpecularSphere->SetPosition(vec3f(3, 3, 6)); SpecularSphere->GetMaterial().Ambient = vec3f(0.05f); RenderPass->AddSceneObject(SpecularSphere); CSimpleMeshSceneObject * PlaneObject = new CSimpleMeshSceneObject(); PlaneObject->SetMesh(PlaneMesh); PlaneObject->SetShader(DiffuseShader); PlaneObject->GetMaterial().Ambient = vec3f(0.05f, 0.05f, 0.1f); RenderPass->AddSceneObject(PlaneObject); CSimpleMeshSceneObject * PlaneObject2 = new CSimpleMeshSceneObject(); PlaneObject2->SetMesh(PlaneMesh); PlaneObject2->SetShader(DiffuseShader); PlaneObject2->SetScale(0.5f); PlaneObject2->GetMaterial().Ambient = vec3f(0.05f); PlaneObject2->SetFeatureEnabled(Graphics::EDrawFeature::PolygonOffset, true); PlaneObject2->SetPolygonOffsetAmount(-1.f); RenderPass->AddSceneObject(PlaneObject2); CSimpleMeshSceneObject * SkySphereObject = new CSimpleMeshSceneObject(); SkySphereObject->SetMesh(SkyBoxMesh); SkySphereObject->SetShader(SkyBoxShader); SkySphereObject->SetTexture("uTexture", SkyBoxTexture); RenderPass->AddSceneObject(SkySphereObject); CPointLight * Light1 = new CPointLight(); Light1->SetPosition(vec3f(0, 1, 0)); Light1->SetColor(Color::Basic::Red); RenderPass->AddLight(Light1); CPointLight * Light2 = new CPointLight(); Light2->SetPosition(vec3f(4, 2, 0)); Light2->SetColor(Color::Basic::Green); RenderPass->AddLight(Light2); CPointLight * Light3 = new CPointLight(); Light3->SetPosition(vec3f(12, 3, 0)); Light3->SetColor(Color::Basic::Blue); RenderPass->AddLight(Light3); /////////////// // Main Loop // /////////////// TimeManager->Init(WindowManager); while (WindowManager->Run()) { TimeManager->Update(); float const MinimumBrightness = 0.2f; float const MaximumBrightness = 1.f - MinimumBrightness; float const Brightness = (Sin<float>((float) TimeManager->GetRunTime()) / 2.f + 0.5f) * MaximumBrightness + MinimumBrightness; float const Radius = Brightness * 10.f; Light1->SetRadius(Radius); Light2->SetRadius(Radius); Light3->SetRadius(Radius); float const Bright = 1; float const Dim = 0.5f; LightSphere1->GetMaterial().Diffuse = color3f(Bright, Dim, Dim) * Brightness; LightSphere2->GetMaterial().Diffuse = color3f(Dim, Bright, Dim) * Brightness; LightSphere3->GetMaterial().Diffuse = color3f(Dim, Dim, Bright) * Brightness; LightSphere1->SetScale(Brightness); LightSphere2->SetScale(Brightness); LightSphere3->SetScale(Brightness); SkySphereObject->SetPosition(Camera->GetPosition()); RenderTarget->ClearColorAndDepth(); SceneManager->DrawAll(); Window->SwapBuffers(); } return 0; }
33.951872
129
0.724366
iondune
542eeff09254058ee9e1b670f0190260c0c1cb0a
5,092
cpp
C++
RemoteExplorerServer/ListenSocket.cpp
tdm1223/CustomExplorer
e790cd2fbd401f2ff05e825e709fefc42e50d64e
[ "MIT" ]
2
2020-03-27T05:36:33.000Z
2021-10-30T07:47:33.000Z
RemoteExplorerServer/ListenSocket.cpp
tdm1223/CustomExplorer
e790cd2fbd401f2ff05e825e709fefc42e50d64e
[ "MIT" ]
null
null
null
RemoteExplorerServer/ListenSocket.cpp
tdm1223/CustomExplorer
e790cd2fbd401f2ff05e825e709fefc42e50d64e
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "RemoteExplorerServer.h" #include "ListenSocket.h" #include "ClientSocket.h" CListenSocket::CListenSocket() { } CListenSocket::~CListenSocket() { } void CListenSocket::OnAccept(int nErrorCode) { CClientSocket* clientSocket = new CClientSocket; if (Accept(*clientSocket)) { clientSocket->SetListenSocket(this); clientSocketList.AddTail(clientSocket); } else { delete clientSocket; AfxMessageBox(_T("새 클라이언트 연결 실패")); } CAsyncSocket::OnAccept(nErrorCode); } void CListenSocket::CloseClientSocket(CSocket* clientSocket) { POSITION position; position = clientSocketList.Find(clientSocket); if (position != NULL) { if (clientSocket != NULL) { clientSocket->ShutDown(); clientSocket->Close(); } clientSocketList.RemoveAt(position); delete clientSocket; } } // 처음 연결되었을 때 호출되는 함수. 모든 partition 탐색 void CListenSocket::InitData(CSocket* clientSocket, Packet& receivePacket) { DWORD drives = GetLogicalDrives(); for (int alphabet = 0; alphabet < 26; alphabet++) { if ((drives & (1 << alphabet))) { CString currentDriveName; TCHAR driveName[] = { TEXT('A') + alphabet, TEXT(':'), TEXT('\0') }; currentDriveName = driveName; strcpy_s(receivePacket.data.fileName, (CStringA)currentDriveName); bool isDrive = IsCorrectDrive(currentDriveName); if (!isDrive) { continue; } MakeAndResponseData(clientSocket, receivePacket, kConnect, currentDriveName); } } } // 올바른 드라이브인지 체크하는 함수 bool CListenSocket::IsCorrectDrive(CString& currentDriveName) { ULARGE_INTEGER avail, free, total; avail.QuadPart = 0L; free.QuadPart = 0L; total.QuadPart = 0L; GetDiskFreeSpaceEx(currentDriveName, &avail, &total, &free); if (total.QuadPart == 0 && avail.QuadPart == 0 && free.QuadPart == 0) { return false; } else { return true; } } // 클라이언트에서 트리뷰를 클릭했을때 데이터를 만들어서 다시 전달해주는 함수 void CListenSocket::UpdateTreeCtrl(CSocket* clientSocket, const Packet& receiveData) { CString filePath; filePath = static_cast<CString>(receiveData.data.filePath); MakeAndResponseData(clientSocket, receiveData, kUpdateTreeCtrl, filePath); } // 만들어진 데이터를 응답하는 함수 void CListenSocket::ResponseData(CSocket* clientSocket, const Packet& receiveData) { CString filePath; filePath = static_cast<CString>(receiveData.data.filePath); filePath += _T("\\*.*"); MakeAndResponseData(clientSocket, receiveData, kRequestData, filePath); } // 리스트뷰 클릭시 리스트 재조정 및 트리뷰에 반영 void CListenSocket::UpdateListCtrl(CSocket* clientSocket, const Packet& receiveData) { CClientSocket* client = static_cast<CClientSocket*>(clientSocket); Packet sendPacket; sendPacket.messageType = kUpdateListCtrl; strcpy_s(sendPacket.data.filePath, receiveData.data.filePath); char sendBuffer[sizeof(sendPacket)]; sendPacket.Serialize(sendBuffer); client->Send(sendBuffer, sizeof(sendBuffer), 0); } // 데이터 만들어서 반환해주는 함수 void CListenSocket::MakeAndResponseData(CSocket* clientSocket, const Packet& receiveData, const MessageType messageType, const CString filePath) { CClientSocket* client = static_cast<CClientSocket*>(clientSocket); Packet sendPacket; sendPacket.messageType = messageType; CFileFind finder; BOOL fileIterator = finder.FindFile(filePath); int count = 0; while (fileIterator) { fileIterator = finder.FindNextFile(); if (finder.IsDots() || finder.IsHidden()) { continue; } else if (finder.IsDirectory()) { sendPacket.data.childType[count] = kDirectory; sendPacket.data.childSize[count] = 0; } else if (finder.IsArchived()) { sendPacket.data.childType[count] = kFile; sendPacket.data.childSize[count] = finder.GetLength(); } CTime cTime; finder.GetLastWriteTime(cTime); CString timeConvertToString = cTime.Format("%Y-%m-%d %H:%M"); strcpy_s(sendPacket.data.childAccessTime[count], static_cast<CStringA>(timeConvertToString)); CString fileName = finder.GetFileName(); strcpy_s(sendPacket.data.childName[count], static_cast<CStringA>(fileName)); count++; } sendPacket.data.childLength = count; if (sendPacket.data.childLength == 0) { sendPacket.data.fileType = kFile; } else { if (filePath.GetLength() == kDriveLength) { sendPacket.data.fileType = kDisk; } else { sendPacket.data.fileType = kDirectory; } } strcpy_s(sendPacket.data.filePath, receiveData.data.filePath); strcpy_s(sendPacket.data.fileName, receiveData.data.fileName); char sendBuffer[sizeof(Packet)]; sendPacket.Serialize(sendBuffer); client->Send(sendBuffer, sizeof(sendBuffer), 0); }
29.097143
144
0.650236
tdm1223
5431f006ed69fb8529af772f6e3323a08d70b0b8
9,159
cpp
C++
src/qwt-6/examples/polardemo/Plot.cpp
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
5
2015-04-16T14:27:38.000Z
2021-11-30T14:54:39.000Z
src/qwt-6/examples/polardemo/Plot.cpp
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
8
2017-05-30T16:58:39.000Z
2022-02-22T16:51:34.000Z
src/qwt-6/examples/polardemo/Plot.cpp
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
7
2016-05-29T08:12:59.000Z
2019-05-02T13:39:25.000Z
/***************************************************************************** * Qwt Polar Examples - Copyright (C) 2008 Uwe Rathmann * This file may be used under the terms of the 3-clause BSD License *****************************************************************************/ #include "Plot.h" #include <QwtSeriesData> #include <QwtSymbol> #include <QwtLegend> #include <QwtPolarGrid> #include <QwtPolarCurve> #include <QwtPolarMarker> #include <QwtScaleEngine> #include <QPen> static const QwtInterval s_radialInterval( 0.0, 10.0 ); static const QwtInterval s_azimuthInterval( 0.0, 360.0 ); namespace { class Data : public QwtSeriesData< QwtPointPolar > { public: Data( const QwtInterval& radialInterval, const QwtInterval& azimuthInterval, size_t size ) : m_radialInterval( radialInterval ) , m_azimuthInterval( azimuthInterval ) , m_size( size ) { } virtual size_t size() const QWT_OVERRIDE { return m_size; } protected: QwtInterval m_radialInterval; QwtInterval m_azimuthInterval; size_t m_size; }; class SpiralData : public Data { public: SpiralData( const QwtInterval& radialInterval, const QwtInterval& azimuthInterval, size_t size ) : Data( radialInterval, azimuthInterval, size ) { } virtual QwtPointPolar sample( size_t i ) const QWT_OVERRIDE { const double stepA = 4 * m_azimuthInterval.width() / m_size; const double a = m_azimuthInterval.minValue() + i * stepA; const double stepR = m_radialInterval.width() / m_size; const double r = m_radialInterval.minValue() + i * stepR; return QwtPointPolar( a, r ); } virtual QRectF boundingRect() const QWT_OVERRIDE { if ( cachedBoundingRect.width() < 0.0 ) cachedBoundingRect = qwtBoundingRect( *this ); return cachedBoundingRect; } }; class RoseData : public Data { public: RoseData( const QwtInterval& radialInterval, const QwtInterval& azimuthInterval, size_t size ) : Data( radialInterval, azimuthInterval, size ) { } virtual QwtPointPolar sample( size_t i ) const QWT_OVERRIDE { const double stepA = m_azimuthInterval.width() / m_size; const double a = m_azimuthInterval.minValue() + i * stepA; const double d = a / 360.0 * M_PI; const double r = m_radialInterval.maxValue() * qAbs( qSin( 4 * d ) ); return QwtPointPolar( a, r ); } virtual QRectF boundingRect() const QWT_OVERRIDE { if ( cachedBoundingRect.width() < 0.0 ) cachedBoundingRect = qwtBoundingRect( *this ); return cachedBoundingRect; } }; } Plot::Plot( QWidget* parent ) : QwtPolarPlot( QwtText( "Polar Plot Demo" ), parent ) { setAutoReplot( false ); setPlotBackground( Qt::darkBlue ); // scales setScale( QwtPolar::Azimuth, s_azimuthInterval.minValue(), s_azimuthInterval.maxValue(), s_azimuthInterval.width() / 12 ); setScaleMaxMinor( QwtPolar::Azimuth, 2 ); setScale( QwtPolar::Radius, s_radialInterval.minValue(), s_radialInterval.maxValue() ); // grids, axes m_grid = new QwtPolarGrid(); m_grid->setPen( QPen( Qt::white ) ); for ( int scaleId = 0; scaleId < QwtPolar::ScaleCount; scaleId++ ) { m_grid->showGrid( scaleId ); m_grid->showMinorGrid( scaleId ); QPen minorPen( Qt::gray ); #if 0 minorPen.setStyle( Qt::DotLine ); #endif m_grid->setMinorGridPen( scaleId, minorPen ); } m_grid->setAxisPen( QwtPolar::AxisAzimuth, QPen( Qt::black ) ); m_grid->showAxis( QwtPolar::AxisAzimuth, true ); m_grid->showAxis( QwtPolar::AxisLeft, false ); m_grid->showAxis( QwtPolar::AxisRight, true ); m_grid->showAxis( QwtPolar::AxisTop, true ); m_grid->showAxis( QwtPolar::AxisBottom, false ); m_grid->showGrid( QwtPolar::Azimuth, true ); m_grid->showGrid( QwtPolar::Radius, true ); m_grid->attach( this ); // curves for ( int curveId = 0; curveId < PlotSettings::NumCurves; curveId++ ) { m_curve[curveId] = createCurve( curveId ); m_curve[curveId]->attach( this ); } // markers QwtPolarMarker* marker = new QwtPolarMarker(); marker->setPosition( QwtPointPolar( 57.3, 4.72 ) ); marker->setSymbol( new QwtSymbol( QwtSymbol::Ellipse, QBrush( Qt::white ), QPen( Qt::green ), QSize( 9, 9 ) ) ); marker->setLabelAlignment( Qt::AlignHCenter | Qt::AlignTop ); QwtText text( "Marker" ); text.setColor( Qt::black ); QColor bg( Qt::white ); bg.setAlpha( 200 ); text.setBackgroundBrush( QBrush( bg ) ); marker->setLabel( text ); marker->attach( this ); QwtLegend* legend = new QwtLegend; insertLegend( legend, QwtPolarPlot::BottomLegend ); } PlotSettings Plot::settings() const { PlotSettings s; for ( int scaleId = 0; scaleId < QwtPolar::ScaleCount; scaleId++ ) { s.flags[PlotSettings::MajorGridBegin + scaleId] = m_grid->isGridVisible( scaleId ); s.flags[PlotSettings::MinorGridBegin + scaleId] = m_grid->isMinorGridVisible( scaleId ); } for ( int axisId = 0; axisId < QwtPolar::AxesCount; axisId++ ) { s.flags[PlotSettings::AxisBegin + axisId] = m_grid->isAxisVisible( axisId ); } s.flags[PlotSettings::AutoScaling] = m_grid->testGridAttribute( QwtPolarGrid::AutoScaling ); s.flags[PlotSettings::Logarithmic] = scaleEngine( QwtPolar::Radius )->transformation(); const QwtScaleDiv* sd = scaleDiv( QwtPolar::Radius ); s.flags[PlotSettings::Inverted] = sd->lowerBound() > sd->upperBound(); s.flags[PlotSettings::Antialiasing] = m_grid->testRenderHint( QwtPolarItem::RenderAntialiased ); for ( int curveId = 0; curveId < PlotSettings::NumCurves; curveId++ ) { s.flags[PlotSettings::CurveBegin + curveId] = m_curve[curveId]->isVisible(); } return s; } void Plot::applySettings( const PlotSettings& s ) { for ( int scaleId = 0; scaleId < QwtPolar::ScaleCount; scaleId++ ) { m_grid->showGrid( scaleId, s.flags[PlotSettings::MajorGridBegin + scaleId] ); m_grid->showMinorGrid( scaleId, s.flags[PlotSettings::MinorGridBegin + scaleId] ); } for ( int axisId = 0; axisId < QwtPolar::AxesCount; axisId++ ) { m_grid->showAxis( axisId, s.flags[PlotSettings::AxisBegin + axisId] ); } m_grid->setGridAttribute( QwtPolarGrid::AutoScaling, s.flags[PlotSettings::AutoScaling] ); const QwtInterval interval = scaleDiv( QwtPolar::Radius )->interval().normalized(); if ( s.flags[PlotSettings::Inverted] ) { setScale( QwtPolar::Radius, interval.maxValue(), interval.minValue() ); } else { setScale( QwtPolar::Radius, interval.minValue(), interval.maxValue() ); } if ( s.flags[PlotSettings::Logarithmic] ) { setScaleEngine( QwtPolar::Radius, new QwtLogScaleEngine() ); } else { setScaleEngine( QwtPolar::Radius, new QwtLinearScaleEngine() ); } m_grid->setRenderHint( QwtPolarItem::RenderAntialiased, s.flags[PlotSettings::Antialiasing] ); for ( int curveId = 0; curveId < PlotSettings::NumCurves; curveId++ ) { m_curve[curveId]->setRenderHint( QwtPolarItem::RenderAntialiased, s.flags[PlotSettings::Antialiasing] ); m_curve[curveId]->setVisible( s.flags[PlotSettings::CurveBegin + curveId] ); } replot(); } QwtPolarCurve* Plot::createCurve( int id ) const { const int numPoints = 200; QwtPolarCurve* curve = new QwtPolarCurve(); curve->setStyle( QwtPolarCurve::Lines ); //curve->setLegendAttribute( QwtPolarCurve::LegendShowLine, true ); //curve->setLegendAttribute( QwtPolarCurve::LegendShowSymbol, true ); switch( id ) { case PlotSettings::Spiral: { curve->setTitle( "Spiral" ); curve->setPen( QPen( Qt::yellow, 2 ) ); curve->setSymbol( new QwtSymbol( QwtSymbol::Rect, QBrush( Qt::cyan ), QPen( Qt::white ), QSize( 3, 3 ) ) ); curve->setData( new SpiralData( s_radialInterval, s_azimuthInterval, numPoints ) ); break; } case PlotSettings::Rose: { curve->setTitle( "Rose" ); curve->setPen( QPen( Qt::red, 2 ) ); curve->setSymbol( new QwtSymbol( QwtSymbol::Rect, QBrush( Qt::cyan ), QPen( Qt::white ), QSize( 3, 3 ) ) ); curve->setData( new RoseData( s_radialInterval, s_azimuthInterval, numPoints ) ); break; } } return curve; } #include "moc_Plot.cpp"
30.428571
83
0.595807
copasi
5432f046bf6cf00712950ba32f3906c1e6110f9a
3,058
hpp
C++
include/uMon/z80.hpp
trevor-makes/uMon
484dc46be45d6eb5ed37f9235ab28d5d3bb40344
[ "MIT" ]
null
null
null
include/uMon/z80.hpp
trevor-makes/uMon
484dc46be45d6eb5ed37f9235ab28d5d3bb40344
[ "MIT" ]
null
null
null
include/uMon/z80.hpp
trevor-makes/uMon
484dc46be45d6eb5ed37f9235ab28d5d3bb40344
[ "MIT" ]
null
null
null
// https://github.com/trevor-makes/uMon.git // Copyright (c) 2022 Trevor Makes #pragma once #include "z80/asm.hpp" #include "z80/dasm.hpp" #include "uCLI.hpp" namespace uMon { namespace z80 { template <typename API> bool parse_operand(Operand& op, uCLI::Tokens tokens) { // Handle indirect operand surronded by parentheses bool is_indirect = false; if (tokens.peek_char() == '(') { is_indirect = true; tokens.split_at('('); tokens = tokens.split_at(')'); // Split optional displacement following +/- uCLI::Tokens disp_tok = tokens; bool is_minus = false; disp_tok.split_at('+'); if (!disp_tok.has_next()) { disp_tok = tokens; disp_tok.split_at('-'); is_minus = true; } // Parse displacement and apply sign uMON_OPTION_UINT(API, uint16_t, disp, 0, disp_tok, return false); op.value = is_minus ? -disp : disp; } // Parse operand as char, number, or token bool is_string = tokens.is_string(); auto op_str = tokens.next(); uint16_t value; if (is_string) { uMON_FMT_ERROR(API, strlen(op_str) > 1, "chr", op_str, return false); op.token = TOK_IMMEDIATE; op.value = op_str[0]; } else if (API::get_labels().get_addr(op_str, value)) { op.token = TOK_IMMEDIATE; op.value = value; } else if (parse_unsigned(value, op_str)) { op.token = TOK_IMMEDIATE; op.value = value; } else { op.token = pgm_bsearch(TOK_STR, op_str); uMON_FMT_ERROR(API, op.token == TOK_INVALID, "arg", op_str, return false); } if (is_indirect) { op.token |= TOK_INDIRECT; } return true; } template <typename API> bool parse_instruction(Instruction& inst, uCLI::Tokens args) { const char* mnemonic = args.next(); inst.mnemonic = pgm_bsearch(MNE_STR, mnemonic); uMON_FMT_ERROR(API, inst.mnemonic == MNE_INVALID, "op", mnemonic, return false); // Parse operands for (Operand& op : inst.operands) { if (!args.has_next()) break; if (!parse_operand<API>(op, args.split_at(','))) return false; } // Error if unparsed operands remain uMON_FMT_ERROR(API, args.has_next(), "rem", args.next(), return false); return true; } template <typename API> void cmd_asm(uCLI::Args args) { uMON_EXPECT_ADDR(API, uint16_t, start, args, return); // Parse and assemble instruction Instruction inst; if (parse_instruction<API>(inst, args)) { uint8_t size = asm_instruction<API>(inst, start); if (size > 0) { set_prompt<API>(args.command(), start + size); } } } template <typename API, uint8_t MAX_ROWS = 24> void cmd_dasm(uCLI::Args args) { // Default size to one instruction if not provided uMON_EXPECT_ADDR(API, uint16_t, start, args, return); uMON_OPTION_UINT(API, uint16_t, size, 1, args, return); uint16_t end_incl = start + size - 1; uint16_t next = dasm_range<API, MAX_ROWS>(start, end_incl); uint16_t part = next - start; if (part < size) { set_prompt<API>(args.command(), next, size - part); } else { set_prompt<API>(args.command(), next); } } } // namespace z80 } // namespace uMon
27.8
82
0.66416
trevor-makes
f9a9ae5c9bd7a969163f86e9eb07bcb9329a5050
9,919
cpp
C++
src/main.cpp
lupyuen/wisblock-lorawan
88cdc1d86a5578a77895fb18706d80daf2c07785
[ "Apache-2.0" ]
3
2021-06-11T14:03:47.000Z
2022-01-04T04:06:30.000Z
src/main.cpp
lupyuen/wisblock-lorawan
88cdc1d86a5578a77895fb18706d80daf2c07785
[ "Apache-2.0" ]
null
null
null
src/main.cpp
lupyuen/wisblock-lorawan
88cdc1d86a5578a77895fb18706d80daf2c07785
[ "Apache-2.0" ]
1
2021-07-26T05:13:10.000Z
2021-07-26T05:13:10.000Z
// Based on https://github.com/RAKWireless/WisBlock/blob/master/examples/RAK4630/communications/LoRa/LoRaWAN/LoRaWAN_OTAA_ABP/LoRaWAN_OTAA_ABP.ino // Note: This program needs SX126x-Arduino Library version 2.0.0 or later. In platformio.ini, set... // lib_deps = beegee-tokyo/SX126x-Arduino@^2.0.0 /** * @file LoRaWAN_OTAA_ABP.ino * @author rakwireless.com * @brief LoRaWan node example with OTAA/ABP registration * @version 0.1 * @date 2020-08-21 * * @copyright Copyright (c) 2020 * * @note RAK4631 GPIO mapping to nRF52840 GPIO ports RAK4631 <-> nRF52840 WB_IO1 <-> P0.17 (GPIO 17) WB_IO2 <-> P1.02 (GPIO 34) WB_IO3 <-> P0.21 (GPIO 21) WB_IO4 <-> P0.04 (GPIO 4) WB_IO5 <-> P0.09 (GPIO 9) WB_IO6 <-> P0.10 (GPIO 10) WB_SW1 <-> P0.01 (GPIO 1) WB_A0 <-> P0.04/AIN2 (AnalogIn A2) WB_A1 <-> P0.31/AIN7 (AnalogIn A7) */ #include <Arduino.h> #include <LoRaWan-RAK4630.h> //http://librarymanager/All#SX126x #include <SPI.h> // RAK4630 supply two LED #ifndef LED_BUILTIN #define LED_BUILTIN 35 #endif #ifndef LED_BUILTIN2 #define LED_BUILTIN2 36 #endif // TODO: Set this to your LoRaWAN Region LoRaMacRegion_t g_CurrentRegion = LORAMAC_REGION_AS923; // Set to true to select Over-The-Air Activation (OTAA), false for Activation By Personalisation (ABP) bool doOTAA = true; // TODO: (For OTAA Only) Set the OTAA keys. KEYS ARE MSB !!!! // Device EUI: Copy from ChirpStack: Applications -> app -> Device EUI uint8_t nodeDeviceEUI[8] = {0x4b, 0xc1, 0x5e, 0xe7, 0x37, 0x7b, 0xb1, 0x5b}; // App EUI: Not needed for ChirpStack, set to default 0000000000000000 uint8_t nodeAppEUI[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; // App Key: Copy from ChirpStack: Applications -> app -> Devices -> device_otaa_class_a -> Keys (OTAA) -> Application Key uint8_t nodeAppKey[16] = {0xaa, 0xff, 0xad, 0x5c, 0x7e, 0x87, 0xf6, 0x4d, 0xe3, 0xf0, 0x87, 0x32, 0xfc, 0x1d, 0xd2, 0x5d}; // TODO: (For ABP Only) Set the ABP keys uint32_t nodeDevAddr = 0x260116F8; uint8_t nodeNwsKey[16] = {0x7E, 0xAC, 0xE2, 0x55, 0xB8, 0xA5, 0xE2, 0x69, 0x91, 0x51, 0x96, 0x06, 0x47, 0x56, 0x9D, 0x23}; uint8_t nodeAppsKey[16] = {0xFB, 0xAC, 0xB6, 0x47, 0xF3, 0x58, 0x45, 0xC7, 0x50, 0x7D, 0xBF, 0x16, 0x8B, 0xA8, 0xC1, 0x7C}; #define SCHED_MAX_EVENT_DATA_SIZE APP_TIMER_SCHED_EVENT_DATA_SIZE /**< Maximum size of scheduler events. */ #define SCHED_QUEUE_SIZE 60 /**< Maximum number of events in the scheduler queue. */ #define LORAWAN_DATERATE DR_0 /*LoRaMac datarates definition, from DR_0 to DR_5*/ #define LORAWAN_TX_POWER TX_POWER_5 /*LoRaMac tx power definition, from TX_POWER_0 to TX_POWER_15*/ #define JOINREQ_NBTRIALS 3 /**< Number of trials for the join request. */ DeviceClass_t g_CurrentClass = CLASS_A; /* class definition*/ lmh_confirm g_CurrentConfirm = LMH_UNCONFIRMED_MSG; /* confirm/unconfirm packet definition*/ uint8_t gAppPort = LORAWAN_APP_PORT; /* data port*/ /**@brief Structure containing LoRaWan parameters, needed for lmh_init() */ static lmh_param_t g_lora_param_init = { LORAWAN_ADR_ON, LORAWAN_DATERATE, LORAWAN_PUBLIC_NETWORK, JOINREQ_NBTRIALS, LORAWAN_TX_POWER, LORAWAN_DUTYCYCLE_OFF }; // Foward declaration static void lorawan_has_joined_handler(void); static void lorawan_join_failed_handler(void); static void lorawan_rx_handler(lmh_app_data_t *app_data); static void lorawan_confirm_class_handler(DeviceClass_t Class); static void send_lora_frame(void); /**@brief Structure containing LoRaWan callback functions, needed for lmh_init() */ static lmh_callback_t g_lora_callbacks = { BoardGetBatteryLevel, BoardGetUniqueId, BoardGetRandomSeed, lorawan_rx_handler, lorawan_has_joined_handler, lorawan_confirm_class_handler, lorawan_join_failed_handler }; // Private defination #define LORAWAN_APP_DATA_BUFF_SIZE 64 /**< buffer size of the data to be transmitted. */ #define LORAWAN_APP_INTERVAL 20000 /**< Defines for user timer, the application data transmission interval. 20s, value in [ms]. */ static uint8_t m_lora_app_data_buffer[LORAWAN_APP_DATA_BUFF_SIZE]; //< Lora user application data buffer. static lmh_app_data_t m_lora_app_data = {m_lora_app_data_buffer, 0, 0, 0, 0}; //< Lora user application data structure. TimerEvent_t appTimer; static uint32_t timers_init(void); static uint32_t count = 0; static uint32_t count_fail = 0; // At startup, we join the LoRaWAN network, in either OTAA or ABP mode void setup() { pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); // Initialize LoRa chip. lora_rak4630_init(); // Initialize Serial for debug output time_t timeout = millis(); Serial.begin(115200); while (!Serial) { if ((millis() - timeout) < 5000) { delay(100); } else { break; } } Serial.println("====================================="); Serial.println("Welcome to RAK4630 LoRaWan!!!"); if (doOTAA) { Serial.println("Type: OTAA"); } else { Serial.println("Type: ABP"); } switch (g_CurrentRegion) { case LORAMAC_REGION_AS923: Serial.println("Region: AS923"); break; case LORAMAC_REGION_AU915: Serial.println("Region: AU915"); break; case LORAMAC_REGION_CN470: Serial.println("Region: CN470"); break; case LORAMAC_REGION_EU433: Serial.println("Region: EU433"); break; case LORAMAC_REGION_IN865: Serial.println("Region: IN865"); break; case LORAMAC_REGION_EU868: Serial.println("Region: EU868"); break; case LORAMAC_REGION_KR920: Serial.println("Region: KR920"); break; case LORAMAC_REGION_US915: Serial.println("Region: US915"); break; } Serial.println("====================================="); //creat a user timer to send data to server period uint32_t err_code; err_code = timers_init(); if (err_code != 0) { Serial.printf("timers_init failed - %d\n", err_code); return; } // Setup the EUIs and Keys if (doOTAA) { lmh_setDevEui(nodeDeviceEUI); lmh_setAppEui(nodeAppEUI); lmh_setAppKey(nodeAppKey); } else { lmh_setNwkSKey(nodeNwsKey); lmh_setAppSKey(nodeAppsKey); lmh_setDevAddr(nodeDevAddr); } // Initialize LoRaWaN err_code = lmh_init( // lmh_init now takes 3 parameters instead of 5 &g_lora_callbacks, // Callbacks g_lora_param_init, // Functions doOTAA, // Set to true for OTAA g_CurrentClass, // Class g_CurrentRegion // Region ); if (err_code != 0) { Serial.printf("lmh_init failed - %d\n", err_code); return; } // Start Join procedure Serial.println("Joining LoRaWAN network..."); lmh_join(); } // Nothing here for now void loop() { // Put your application tasks here, like reading of sensors, // Controlling actuators and/or other functions. } /**@brief LoRa function for handling HasJoined event. */ void lorawan_has_joined_handler(void) { // When we have joined the LoRaWAN network, start a 20-second timer Serial.println("OTAA Mode, Network Joined!"); lmh_error_status ret = lmh_class_request(g_CurrentClass); if (ret == LMH_SUCCESS) { delay(1000); TimerSetValue(&appTimer, LORAWAN_APP_INTERVAL); TimerStart(&appTimer); } } /**@brief LoRa function for handling OTAA join failed */ static void lorawan_join_failed_handler(void) { // If we can't join the LoRaWAN network, show the error Serial.println("OTAA join failed!"); Serial.println("Check your EUI's and Keys's!"); Serial.println("Check if a Gateway is in range!"); } /**@brief Function for handling LoRaWan received data from Gateway * * @param[in] app_data Pointer to rx data */ void lorawan_rx_handler(lmh_app_data_t *app_data) { // When we receive a LoRaWAN Packet from the LoRaWAN Gateway, display it. // TODO: Ensure that app_data->buffer is null-terminated. Serial.printf("LoRa Packet received on port %d, size:%d, rssi:%d, snr:%d, data:%s\n", app_data->port, app_data->buffsize, app_data->rssi, app_data->snr, app_data->buffer); } // Callback Function that is called when the LoRaWAN Class has been changed void lorawan_confirm_class_handler(DeviceClass_t Class) { Serial.printf("switch to class %c done\n", "ABC"[Class]); // Informs the server that switch has occurred ASAP m_lora_app_data.buffsize = 0; m_lora_app_data.port = gAppPort; lmh_send(&m_lora_app_data, g_CurrentConfirm); } // This is called when the 20-second timer expires. We send a LoRaWAN Packet. void send_lora_frame(void) { if (lmh_join_status_get() != LMH_SET) { // Not joined, try again later return; } // Copy "Hello!" into the transmit buffer m_lora_app_data.port = gAppPort; memset(m_lora_app_data.buffer, 0, LORAWAN_APP_DATA_BUFF_SIZE); memcpy(m_lora_app_data.buffer, "Hello!", 6); m_lora_app_data.buffsize = 6; // Transmit the LoRaWAN Packet lmh_error_status error = lmh_send(&m_lora_app_data, g_CurrentConfirm); if (error == LMH_SUCCESS) { count++; Serial.printf("lmh_send ok count %d\n", count); } else { count_fail++; Serial.printf("lmh_send fail count %d\n", count_fail); } } /**@brief Function for handling user timerout event. */ void tx_lora_periodic_handler(void) { // When the 20-second timer has expired, send a LoRaWAN Packet and restart the timer TimerSetValue(&appTimer, LORAWAN_APP_INTERVAL); TimerStart(&appTimer); Serial.println("Sending frame now..."); send_lora_frame(); } /**@brief Function for the Timer initialization. * * @details Initializes the timer module. This creates and starts application timers. */ uint32_t timers_init(void) { TimerInit(&appTimer, tx_lora_periodic_handler); return 0; }
31.094044
153
0.690493
lupyuen
f9ab206b58a1253d0da876422963da3d8d50cae4
738
hpp
C++
libs/fnd/units/include/bksge/fnd/units/bit.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/units/include/bksge/fnd/units/bit.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/units/include/bksge/fnd/units/bit.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file bit.hpp * * @brief bit の定義 * * @author myoukaku */ #ifndef BKSGE_FND_UNITS_BIT_HPP #define BKSGE_FND_UNITS_BIT_HPP #include <bksge/fnd/units/base_dimensions/information.hpp> #include <bksge/fnd/units/detail/quantity.hpp> #include <bksge/fnd/units/detail/si_prefix.hpp> #include <bksge/fnd/units/detail/binary_prefix.hpp> namespace bksge { namespace units { // ビット template <typename T> using bit = quantity<T, information_dimension>; template <typename T> using bits = bit<T>; BKSGE_UNITS_SI_PREFIX(bit); BKSGE_UNITS_SI_PREFIX(bits); BKSGE_UNITS_BINARY_PREFIX(bit); BKSGE_UNITS_BINARY_PREFIX(bits); } // namespace units } // namespace bksge #endif // BKSGE_FND_UNITS_BIT_HPP
20.5
71
0.727642
myoukaku
f9acf7e4d8e01c2cdcfb804def20d7d651ed68a7
56,134
cpp
C++
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/osx/carbon/nonownedwnd.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
471
2019-06-26T09:59:09.000Z
2022-03-30T04:59:42.000Z
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/osx/carbon/nonownedwnd.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/osx/carbon/nonownedwnd.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
317
2017-06-20T19:57:17.000Z
2020-09-16T10:28:30.000Z
///////////////////////////////////////////////////////////////////////////// // Name: src/osx/carbon/nonownedwnd.cpp // Purpose: implementation of wxNonOwnedWindow // Author: Stefan Csomor // Created: 2008-03-24 // Copyright: (c) Stefan Csomor 2008 // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/app.h" #endif // WX_PRECOMP #include "wx/hashmap.h" #include "wx/evtloop.h" #include "wx/tooltip.h" #include "wx/nonownedwnd.h" #include "wx/osx/private.h" #include "wx/settings.h" #include "wx/frame.h" #if wxUSE_SYSTEM_OPTIONS #include "wx/sysopt.h" #endif // ============================================================================ // wxNonOwnedWindow implementation // ============================================================================ // unified title and toolbar constant - not in Tiger headers, so we duplicate it here #define kWindowUnifiedTitleAndToolbarAttribute (1 << 7) IMPLEMENT_DYNAMIC_CLASS( wxNonOwnedWindowCarbonImpl , wxNonOwnedWindowImpl ) WXWindow wxNonOwnedWindowCarbonImpl::GetWXWindow() const { return (WXWindow) m_macWindow; } void wxNonOwnedWindowCarbonImpl::Raise() { ::SelectWindow( m_macWindow ) ; } void wxNonOwnedWindowCarbonImpl::Lower() { ::SendBehind( m_macWindow , NULL ) ; } void wxNonOwnedWindowCarbonImpl::ShowWithoutActivating() { bool plainTransition = true; #if wxUSE_SYSTEM_OPTIONS if ( wxSystemOptions::HasOption(wxMAC_WINDOW_PLAIN_TRANSITION) ) plainTransition = ( wxSystemOptions::GetOptionInt( wxMAC_WINDOW_PLAIN_TRANSITION ) == 1 ) ; #endif if ( plainTransition ) ::ShowWindow( (WindowRef)m_macWindow ); else ::TransitionWindow( (WindowRef)m_macWindow, kWindowZoomTransitionEffect, kWindowShowTransitionAction, NULL ); } bool wxNonOwnedWindowCarbonImpl::Show(bool show) { bool plainTransition = true; #if wxUSE_SYSTEM_OPTIONS if ( wxSystemOptions::HasOption(wxMAC_WINDOW_PLAIN_TRANSITION) ) plainTransition = ( wxSystemOptions::GetOptionInt( wxMAC_WINDOW_PLAIN_TRANSITION ) == 1 ) ; #endif if (show) { ShowWithoutActivating(); ::SelectWindow( (WindowRef)m_macWindow ) ; } else { #if wxOSX_USE_CARBON if ( plainTransition ) ::HideWindow( (WindowRef)m_macWindow ); else ::TransitionWindow( (WindowRef)m_macWindow, kWindowZoomTransitionEffect, kWindowHideTransitionAction, NULL ); #endif } return true; } void wxNonOwnedWindowCarbonImpl::Update() { HIWindowFlush(m_macWindow) ; } bool wxNonOwnedWindowCarbonImpl::SetTransparent(wxByte alpha) { OSStatus result = SetWindowAlpha((WindowRef)m_macWindow, (CGFloat)((alpha)/255.0)); return result == noErr; } bool wxNonOwnedWindowCarbonImpl::SetBackgroundColour(const wxColour& col ) { if ( col == wxColour(wxMacCreateCGColorFromHITheme(kThemeBrushDocumentWindowBackground)) ) { SetThemeWindowBackground( (WindowRef) m_macWindow, kThemeBrushDocumentWindowBackground, false ) ; m_wxPeer->SetBackgroundStyle(wxBG_STYLE_SYSTEM); // call directly if object is not yet completely constructed if ( m_wxPeer->GetNonOwnedPeer() == NULL ) SetBackgroundStyle(wxBG_STYLE_SYSTEM); } else if ( col == wxColour(wxMacCreateCGColorFromHITheme(kThemeBrushDialogBackgroundActive)) ) { SetThemeWindowBackground( (WindowRef) m_macWindow, kThemeBrushDialogBackgroundActive, false ) ; m_wxPeer->SetBackgroundStyle(wxBG_STYLE_SYSTEM); // call directly if object is not yet completely constructed if ( m_wxPeer->GetNonOwnedPeer() == NULL ) SetBackgroundStyle(wxBG_STYLE_SYSTEM); } return true; } void wxNonOwnedWindowCarbonImpl::SetExtraStyle( long exStyle ) { if ( m_macWindow != NULL ) { bool metal = exStyle & wxFRAME_EX_METAL ; if ( MacGetMetalAppearance() != metal ) { if ( MacGetUnifiedAppearance() ) MacSetUnifiedAppearance( !metal ) ; MacSetMetalAppearance( metal ) ; } } } bool wxNonOwnedWindowCarbonImpl::SetBackgroundStyle(wxBackgroundStyle style) { if ( style == wxBG_STYLE_TRANSPARENT ) { OSStatus err = HIWindowChangeFeatures( m_macWindow, 0, kWindowIsOpaque ); verify_noerr( err ); err = ReshapeCustomWindow( m_macWindow ); verify_noerr( err ); } return true ; } bool wxNonOwnedWindowCarbonImpl::CanSetTransparent() { return true; } void wxNonOwnedWindowCarbonImpl::GetContentArea( int &left , int &top , int &width , int &height ) const { Rect content, structure ; GetWindowBounds( m_macWindow, kWindowStructureRgn , &structure ) ; GetWindowBounds( m_macWindow, kWindowContentRgn , &content ) ; left = content.left - structure.left ; top = content.top - structure.top ; width = content.right - content.left ; height = content.bottom - content.top ; } void wxNonOwnedWindowCarbonImpl::MoveWindow(int x, int y, int width, int height) { Rect bounds = { y , x , y + height , x + width } ; verify_noerr(SetWindowBounds( (WindowRef) m_macWindow, kWindowStructureRgn , &bounds )) ; } void wxNonOwnedWindowCarbonImpl::GetPosition( int &x, int &y ) const { Rect bounds ; verify_noerr(GetWindowBounds((WindowRef) m_macWindow, kWindowStructureRgn , &bounds )) ; x = bounds.left ; y = bounds.top ; } void wxNonOwnedWindowCarbonImpl::GetSize( int &width, int &height ) const { Rect bounds ; verify_noerr(GetWindowBounds((WindowRef) m_macWindow, kWindowStructureRgn , &bounds )) ; width = bounds.right - bounds.left ; height = bounds.bottom - bounds.top ; } bool wxNonOwnedWindowCarbonImpl::MacGetUnifiedAppearance() const { return MacGetWindowAttributes() & kWindowUnifiedTitleAndToolbarAttribute ; } void wxNonOwnedWindowCarbonImpl::MacChangeWindowAttributes( wxUint32 attributesToSet , wxUint32 attributesToClear ) { ChangeWindowAttributes( m_macWindow, attributesToSet, attributesToClear ) ; } wxUint32 wxNonOwnedWindowCarbonImpl::MacGetWindowAttributes() const { UInt32 attr = 0 ; GetWindowAttributes( m_macWindow, &attr ) ; return attr ; } void wxNonOwnedWindowCarbonImpl::MacSetMetalAppearance( bool set ) { if ( MacGetUnifiedAppearance() ) MacSetUnifiedAppearance( false ) ; MacChangeWindowAttributes( set ? kWindowMetalAttribute : kWindowNoAttributes , set ? kWindowNoAttributes : kWindowMetalAttribute ) ; } bool wxNonOwnedWindowCarbonImpl::MacGetMetalAppearance() const { return MacGetWindowAttributes() & kWindowMetalAttribute ; } void wxNonOwnedWindowCarbonImpl::MacSetUnifiedAppearance( bool set ) { if ( MacGetMetalAppearance() ) MacSetMetalAppearance( false ) ; MacChangeWindowAttributes( set ? kWindowUnifiedTitleAndToolbarAttribute : kWindowNoAttributes , set ? kWindowNoAttributes : kWindowUnifiedTitleAndToolbarAttribute) ; // For some reason, Tiger uses white as the background color for this appearance, // while most apps using it use the typical striped background. Restore that behaviour // for wx. // TODO: Determine if we need this on Leopard as well. (should be harmless either way, // though) // since when creating the peering is not yet completely set-up we call both setters // explicitly m_wxPeer->SetBackgroundColour( wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW) ) ; SetBackgroundColour( wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW) ) ; } // ---------------------------------------------------------------------------- // globals // ---------------------------------------------------------------------------- static pascal long wxShapedMacWindowDef(short varCode, WindowRef window, SInt16 message, SInt32 param); WXDLLEXPORT void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent ); // --------------------------------------------------------------------------- // Carbon Events // --------------------------------------------------------------------------- static const EventTypeSpec eventList[] = { // TODO: remove control related event like key and mouse (except for WindowLeave events) { kEventClassKeyboard, kEventRawKeyDown } , { kEventClassKeyboard, kEventRawKeyRepeat } , { kEventClassKeyboard, kEventRawKeyUp } , { kEventClassKeyboard, kEventRawKeyModifiersChanged } , { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } , { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } , { kEventClassWindow , kEventWindowShown } , { kEventClassWindow , kEventWindowActivated } , { kEventClassWindow , kEventWindowDeactivated } , { kEventClassWindow , kEventWindowBoundsChanging } , { kEventClassWindow , kEventWindowBoundsChanged } , { kEventClassWindow , kEventWindowClose } , { kEventClassWindow , kEventWindowGetRegion } , // we have to catch these events on the toplevel window level, // as controls don't get the raw mouse events anymore { kEventClassMouse , kEventMouseDown } , { kEventClassMouse , kEventMouseUp } , { kEventClassMouse , kEventMouseWheelMoved } , { kEventClassMouse , kEventMouseMoved } , { kEventClassMouse , kEventMouseDragged } , } ; static pascal OSStatus KeyboardEventHandler( EventHandlerCallRef handler , EventRef event , void *data ) { OSStatus result = eventNotHandledErr ; // call DoFindFocus instead of FindFocus, because for Composite Windows(like WxGenericListCtrl) // FindFocus does not return the actual focus window, but the enclosing window wxWindow* focus = wxWindow::DoFindFocus(); if ( focus == NULL ) focus = data ? ((wxNonOwnedWindowImpl*) data)->GetWXPeer() : NULL ; unsigned char charCode ; wxChar uniChar[2] ; uniChar[0] = 0; uniChar[1] = 0; UInt32 keyCode ; UInt32 modifiers ; UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ; #if wxUSE_UNICODE ByteCount dataSize = 0 ; if ( GetEventParameter( event, kEventParamKeyUnicodes, typeUnicodeText, NULL, 0 , &dataSize, NULL ) == noErr ) { UniChar buf[2] ; int numChars = dataSize / sizeof( UniChar) + 1; UniChar* charBuf = buf ; if ( numChars * 2 > 4 ) charBuf = new UniChar[ numChars ] ; GetEventParameter( event, kEventParamKeyUnicodes, typeUnicodeText, NULL, dataSize , NULL , charBuf ) ; charBuf[ numChars - 1 ] = 0; wxMBConvUTF16 converter ; converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ; if ( numChars * 2 > 4 ) delete[] charBuf ; } #endif // wxUSE_UNICODE GetEventParameter( event, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode ); GetEventParameter( event, kEventParamKeyCode, typeUInt32, NULL, sizeof(UInt32), NULL, &keyCode ); GetEventParameter( event, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(UInt32), NULL, &modifiers ); UInt32 message = (keyCode << 8) + charCode; switch ( GetEventKind( event ) ) { case kEventRawKeyRepeat : case kEventRawKeyDown : { WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ; WXEVENTHANDLERCALLREF formerHandler = wxTheApp->MacGetCurrentEventHandlerCallRef() ; wxTheApp->MacSetCurrentEvent( event , handler ) ; if ( /* focus && */ wxTheApp->MacSendKeyDownEvent( focus , message , modifiers , when , uniChar[0] ) ) { result = noErr ; } wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ; } break ; case kEventRawKeyUp : if ( /* focus && */ wxTheApp->MacSendKeyUpEvent( focus , message , modifiers , when , uniChar[0] ) ) { result = noErr ; } break ; case kEventRawKeyModifiersChanged : { wxKeyEvent event(wxEVT_KEY_DOWN); event.m_shiftDown = modifiers & shiftKey; event.m_rawControlDown = modifiers & controlKey; event.m_altDown = modifiers & optionKey; event.m_controlDown = event.m_metaDown = modifiers & cmdKey; #if wxUSE_UNICODE event.m_uniChar = uniChar[0] ; #endif event.SetTimestamp(when); event.SetEventObject(focus); if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey ) { event.m_keyCode = WXK_RAW_CONTROL ; event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ; focus->HandleWindowEvent( event ) ; } if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey ) { event.m_keyCode = WXK_SHIFT ; event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ; focus->HandleWindowEvent( event ) ; } if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey ) { event.m_keyCode = WXK_ALT ; event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ; focus->HandleWindowEvent( event ) ; } if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey ) { event.m_keyCode = WXK_CONTROL; event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ; focus->HandleWindowEvent( event ) ; } wxApp::s_lastModifiers = modifiers ; } break ; default: break; } return result ; } // we don't interfere with foreign controls on our toplevel windows, therefore we always give back eventNotHandledErr // for windows that we didn't create (like eg Scrollbars in a databrowser), or for controls where we did not handle the // mouse down at all // // This handler can also be called from app level where data (ie target window) may be null or a non wx window EventMouseButton g_lastButton = 0 ; bool g_lastButtonWasFakeRight = false ; WXDLLEXPORT void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent ) { UInt32 modifiers = cEvent.GetParameter<UInt32>(kEventParamKeyModifiers, typeUInt32) ; Point screenMouseLocation = cEvent.GetParameter<Point>(kEventParamMouseLocation) ; // these parameters are not given for all events EventMouseButton button = 0 ; UInt32 clickCount = 0 ; UInt32 mouseChord = 0; cEvent.GetParameter<EventMouseButton>( kEventParamMouseButton, typeMouseButton , &button ) ; cEvent.GetParameter<UInt32>( kEventParamClickCount, typeUInt32 , &clickCount ) ; // the chord is the state of the buttons pressed currently cEvent.GetParameter<UInt32>( kEventParamMouseChord, typeUInt32 , &mouseChord ) ; wxevent.m_x = screenMouseLocation.h; wxevent.m_y = screenMouseLocation.v; wxevent.m_shiftDown = modifiers & shiftKey; wxevent.m_rawControlDown = modifiers & controlKey; wxevent.m_altDown = modifiers & optionKey; wxevent.m_controlDown = wxevent.m_metaDown = modifiers & cmdKey; wxevent.m_clickCount = clickCount; wxevent.SetTimestamp( cEvent.GetTicks() ) ; // a control click is interpreted as a right click bool thisButtonIsFakeRight = false ; if ( button == kEventMouseButtonPrimary && (modifiers & controlKey) ) { button = kEventMouseButtonSecondary ; thisButtonIsFakeRight = true ; } // otherwise we report double clicks by connecting a left click with a ctrl-left click if ( clickCount > 1 && button != g_lastButton ) clickCount = 1 ; // we must make sure that our synthetic 'right' button corresponds in // mouse down, moved and mouse up, and does not deliver a right down and left up if ( cEvent.GetKind() == kEventMouseDown ) { g_lastButton = button ; g_lastButtonWasFakeRight = thisButtonIsFakeRight ; } if ( button == 0 ) { g_lastButton = 0 ; g_lastButtonWasFakeRight = false ; } else if ( g_lastButton == kEventMouseButtonSecondary && g_lastButtonWasFakeRight ) button = g_lastButton ; // Adjust the chord mask to remove the primary button and add the // secondary button. It is possible that the secondary button is // already pressed, e.g. on a mouse connected to a laptop, but this // possibility is ignored here: if( thisButtonIsFakeRight && ( mouseChord & 1U ) ) mouseChord = ((mouseChord & ~1U) | 2U); if(mouseChord & 1U) wxevent.m_leftDown = true ; if(mouseChord & 2U) wxevent.m_rightDown = true ; if(mouseChord & 4U) wxevent.m_middleDown = true ; // translate into wx types switch ( cEvent.GetKind() ) { case kEventMouseDown : switch ( button ) { case kEventMouseButtonPrimary : wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ; break ; case kEventMouseButtonSecondary : wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ; break ; case kEventMouseButtonTertiary : wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ; break ; default: break ; } break ; case kEventMouseUp : switch ( button ) { case kEventMouseButtonPrimary : wxevent.SetEventType( wxEVT_LEFT_UP ) ; break ; case kEventMouseButtonSecondary : wxevent.SetEventType( wxEVT_RIGHT_UP ) ; break ; case kEventMouseButtonTertiary : wxevent.SetEventType( wxEVT_MIDDLE_UP ) ; break ; default: break ; } break ; // TODO http://developer.apple.com/qa/qa2005/qa1453.html // add declaration for 10.4 and change to kEventMouseScroll case kEventMouseWheelMoved : { wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ; EventMouseWheelAxis axis = cEvent.GetParameter<EventMouseWheelAxis>(kEventParamMouseWheelAxis, typeMouseWheelAxis) ; SInt32 delta = cEvent.GetParameter<SInt32>(kEventParamMouseWheelDelta, typeSInt32) ; wxevent.m_wheelRotation = delta; wxevent.m_wheelDelta = 1; wxevent.m_linesPerAction = 1; wxevent.m_columnsPerAction = 1; if ( axis == kEventMouseWheelAxisX ) wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL; } break ; case kEventMouseEntered : case kEventMouseExited : case kEventMouseDragged : case kEventMouseMoved : wxevent.SetEventType( wxEVT_MOTION ) ; break; default : break ; } } #define NEW_CAPTURE_HANDLING 1 pascal OSStatus wxMacTopLevelMouseEventHandler(EventHandlerCallRef WXUNUSED(handler), EventRef event, void *data) { wxNonOwnedWindow* toplevelWindow = data ? ((wxNonOwnedWindowImpl*) data)->GetWXPeer() : NULL ; OSStatus result = eventNotHandledErr ; wxMacCarbonEvent cEvent( event ) ; Point screenMouseLocation = cEvent.GetParameter<Point>(kEventParamMouseLocation) ; Point windowMouseLocation = screenMouseLocation ; WindowRef window = NULL; short windowPart = ::FindWindow(screenMouseLocation, &window); wxWindow* currentMouseWindow = NULL ; ControlRef control = NULL ; #if NEW_CAPTURE_HANDLING if ( wxApp::s_captureWindow ) { window = (WindowRef) wxApp::s_captureWindow->MacGetTopLevelWindowRef() ; windowPart = inContent ; } #endif if ( window ) { QDGlobalToLocalPoint( GetWindowPort( window ), &windowMouseLocation ); if ( wxApp::s_captureWindow #if !NEW_CAPTURE_HANDLING && wxApp::s_captureWindow->MacGetTopLevelWindowRef() == (WXWindow) window && windowPart == inContent #endif ) { currentMouseWindow = wxApp::s_captureWindow ; } else if ( (IsWindowActive(window) && windowPart == inContent) ) { ControlPartCode part ; control = FindControlUnderMouse( windowMouseLocation , window , &part ) ; // if there is no control below the mouse position, send the event to the toplevel window itself if ( control == 0 ) { currentMouseWindow = (wxWindow*) toplevelWindow ; } else { currentMouseWindow = (wxWindow*) wxFindWindowFromWXWidget( (WXWidget) control ) ; #ifndef __WXUNIVERSAL__ if ( currentMouseWindow == NULL && cEvent.GetKind() == kEventMouseMoved ) { #if wxUSE_TOOLBAR // for wxToolBar to function we have to send certaint events to it // instead of its children (wxToolBarTools) ControlRef parent ; GetSuperControl(control, &parent ); wxWindow *wxparent = (wxWindow*) wxFindWindowFromWXWidget((WXWidget) parent ) ; if ( wxparent && wxparent->IsKindOf( CLASSINFO( wxToolBar ) ) ) currentMouseWindow = wxparent ; #endif } #endif } // disabled windows must not get any input messages if ( currentMouseWindow && !currentMouseWindow->MacIsReallyEnabled() ) currentMouseWindow = NULL; } } wxMouseEvent wxevent(wxEVT_LEFT_DOWN); SetupMouseEvent( wxevent , cEvent ) ; // handle all enter / leave events if ( currentMouseWindow != g_MacLastWindow ) { if ( g_MacLastWindow ) { wxMouseEvent eventleave(wxevent); eventleave.SetEventType( wxEVT_LEAVE_WINDOW ); g_MacLastWindow->ScreenToClient( &eventleave.m_x, &eventleave.m_y ); eventleave.SetEventObject( g_MacLastWindow ) ; wxevent.SetId( g_MacLastWindow->GetId() ) ; #if wxUSE_TOOLTIPS wxToolTip::RelayEvent( g_MacLastWindow , eventleave); #endif g_MacLastWindow->HandleWindowEvent(eventleave); } if ( currentMouseWindow ) { wxMouseEvent evententer(wxevent); evententer.SetEventType( wxEVT_ENTER_WINDOW ); currentMouseWindow->ScreenToClient( &evententer.m_x, &evententer.m_y ); evententer.SetEventObject( currentMouseWindow ) ; wxevent.SetId( currentMouseWindow->GetId() ) ; #if wxUSE_TOOLTIPS wxToolTip::RelayEvent( currentMouseWindow , evententer ); #endif currentMouseWindow->HandleWindowEvent(evententer); } g_MacLastWindow = currentMouseWindow ; } if ( windowPart == inMenuBar ) { // special case menu bar, as we are having a low-level runloop we must do it ourselves if ( cEvent.GetKind() == kEventMouseDown ) { ::MenuSelect( screenMouseLocation ) ; ::HiliteMenu(0); result = noErr ; } } else if ( window && windowPart == inProxyIcon ) { // special case proxy icon bar, as we are having a low-level runloop we must do it ourselves if ( cEvent.GetKind() == kEventMouseDown ) { if ( ::TrackWindowProxyDrag( window, screenMouseLocation ) != errUserWantsToDragWindow ) { // TODO Track change of file path and report back result = noErr ; } } } else if ( currentMouseWindow ) { wxWindow *currentMouseWindowParent = currentMouseWindow->GetParent(); currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ; wxevent.SetEventObject( currentMouseWindow ) ; wxevent.SetId( currentMouseWindow->GetId() ) ; // make tooltips current #if wxUSE_TOOLTIPS if ( wxevent.GetEventType() == wxEVT_MOTION ) wxToolTip::RelayEvent( currentMouseWindow , wxevent ); #endif if ( currentMouseWindow->HandleWindowEvent(wxevent) ) { if ( currentMouseWindowParent && !currentMouseWindowParent->GetChildren().Member(currentMouseWindow) ) currentMouseWindow = NULL; result = noErr; } else { // if the user code did _not_ handle the event, then perform the // default processing if ( wxevent.GetEventType() == wxEVT_LEFT_DOWN ) { // ... that is set focus to this window if (currentMouseWindow->CanAcceptFocus() && wxWindow::FindFocus()!=currentMouseWindow) currentMouseWindow->SetFocus(); } } if ( cEvent.GetKind() == kEventMouseUp && wxApp::s_captureWindow ) { wxApp::s_captureWindow = NULL ; // update cursor ? } // update cursor wxWindow* cursorTarget = currentMouseWindow ; wxPoint cursorPoint( wxevent.m_x , wxevent.m_y ) ; extern wxCursor gGlobalCursor; if (!gGlobalCursor.IsOk()) { while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) ) { cursorTarget = cursorTarget->GetParent() ; if ( cursorTarget ) cursorPoint += cursorTarget->GetPosition(); } } } else // currentMouseWindow == NULL { if (toplevelWindow && !control) { extern wxCursor gGlobalCursor; if (!gGlobalCursor.IsOk()) { // update cursor when over toolbar and titlebar etc. wxSTANDARD_CURSOR->MacInstall() ; } } // don't mess with controls we don't know about // for some reason returning eventNotHandledErr does not lead to the correct behaviour // so we try sending them the correct control directly if ( cEvent.GetKind() == kEventMouseDown && toplevelWindow && control ) { EventModifiers modifiers = cEvent.GetParameter<EventModifiers>(kEventParamKeyModifiers, typeUInt32) ; Point clickLocation = windowMouseLocation ; HIPoint hiPoint ; hiPoint.x = clickLocation.h ; hiPoint.y = clickLocation.v ; HIViewConvertPoint( &hiPoint , (ControlRef) toplevelWindow->GetHandle() , control ) ; clickLocation.h = (int)hiPoint.x ; clickLocation.v = (int)hiPoint.y ; HandleControlClick( control , clickLocation , modifiers , (ControlActionUPP ) -1 ) ; result = noErr ; } } return result ; } static pascal OSStatus wxNonOwnedWindowEventHandler(EventHandlerCallRef WXUNUSED(handler), EventRef event, void *data) { OSStatus result = eventNotHandledErr ; wxMacCarbonEvent cEvent( event ) ; // WindowRef windowRef = cEvent.GetParameter<WindowRef>(kEventParamDirectObject) ; wxNonOwnedWindow* toplevelWindow = data ? ((wxNonOwnedWindowImpl*) data)->GetWXPeer() : NULL; switch ( GetEventKind( event ) ) { case kEventWindowActivated : { toplevelWindow->HandleActivated( cEvent.GetTicks() , true) ; // we still sending an eventNotHandledErr in order to allow for default processing } break ; case kEventWindowDeactivated : { toplevelWindow->HandleActivated( cEvent.GetTicks() , false) ; // we still sending an eventNotHandledErr in order to allow for default processing } break ; case kEventWindowShown : toplevelWindow->Refresh() ; result = noErr ; break ; case kEventWindowClose : toplevelWindow->Close() ; result = noErr ; break ; case kEventWindowBoundsChanged : { UInt32 attributes = cEvent.GetParameter<UInt32>(kEventParamAttributes, typeUInt32) ; Rect newRect = cEvent.GetParameter<Rect>(kEventParamCurrentBounds) ; wxRect r( newRect.left , newRect.top , newRect.right - newRect.left , newRect.bottom - newRect.top ) ; if ( attributes & kWindowBoundsChangeSizeChanged ) { toplevelWindow->HandleResized(cEvent.GetTicks() ) ; } if ( attributes & kWindowBoundsChangeOriginChanged ) { toplevelWindow->HandleMoved(cEvent.GetTicks() ) ; } result = noErr ; } break ; case kEventWindowBoundsChanging : { UInt32 attributes = cEvent.GetParameter<UInt32>(kEventParamAttributes,typeUInt32) ; Rect newRect = cEvent.GetParameter<Rect>(kEventParamCurrentBounds) ; if ( (attributes & kWindowBoundsChangeSizeChanged) || (attributes & kWindowBoundsChangeOriginChanged) ) { // all (Mac) rects are in content area coordinates, all wxRects in structure coordinates int left , top , width , height ; // structure width int swidth, sheight; toplevelWindow->GetNonOwnedPeer()->GetContentArea(left, top, width, height); toplevelWindow->GetNonOwnedPeer()->GetSize(swidth, sheight); int deltawidth = swidth - width; int deltaheight = sheight - height; wxRect adjustR( newRect.left - left, newRect.top - top, newRect.right - newRect.left + deltawidth, newRect.bottom - newRect.top + deltaheight ) ; toplevelWindow->HandleResizing( cEvent.GetTicks(), &adjustR ); const Rect adjustedRect = { adjustR.y + top , adjustR.x + left , adjustR.y + top + adjustR.height - deltaheight , adjustR.x + left + adjustR.width - deltawidth } ; if ( !EqualRect( &newRect , &adjustedRect ) ) cEvent.SetParameter<Rect>( kEventParamCurrentBounds , &adjustedRect ) ; } result = noErr ; } break ; case kEventWindowGetRegion : { if ( toplevelWindow->GetBackgroundStyle() == wxBG_STYLE_TRANSPARENT ) { WindowRegionCode windowRegionCode ; // Fetch the region code that is being queried GetEventParameter( event, kEventParamWindowRegionCode, typeWindowRegionCode, NULL, sizeof windowRegionCode, NULL, &windowRegionCode ) ; // If it is the opaque region code then set the // region to empty and return noErr to stop event // propagation if ( windowRegionCode == kWindowOpaqueRgn ) { RgnHandle region; GetEventParameter( event, kEventParamRgnHandle, typeQDRgnHandle, NULL, sizeof region, NULL, &region) ; SetEmptyRgn(region) ; result = noErr ; } } } break ; default : break ; } return result ; } // mix this in from window.cpp pascal OSStatus wxMacUnicodeTextEventHandler( EventHandlerCallRef handler , EventRef event , void *data ) ; static pascal OSStatus wxNonOwnedEventHandler( EventHandlerCallRef handler , EventRef event , void *data ) { OSStatus result = eventNotHandledErr ; switch ( GetEventClass( event ) ) { case kEventClassTextInput : { // TODO remove as soon as all events are on implementation classes only wxNonOwnedWindow* toplevelWindow = data ? ((wxNonOwnedWindowImpl*) data)->GetWXPeer() : NULL; result = wxMacUnicodeTextEventHandler( handler, event , toplevelWindow ) ; } break ; case kEventClassKeyboard : result = KeyboardEventHandler( handler, event , data ) ; break ; case kEventClassWindow : result = wxNonOwnedWindowEventHandler( handler, event , data ) ; break ; case kEventClassMouse : result = wxMacTopLevelMouseEventHandler( handler, event , data ) ; break ; default : break ; } return result ; } DEFINE_ONE_SHOT_HANDLER_GETTER( wxNonOwnedEventHandler ) // --------------------------------------------------------------------------- // Support functions for shaped windows, based on Apple's CustomWindow sample at // http://developer.apple.com/samplecode/Sample_Code/Human_Interface_Toolbox/Mac_OS_High_Level_Toolbox/CustomWindow.htm // --------------------------------------------------------------------------- static void wxShapedMacWindowGetPos(WindowRef window, Rect* inRect) { GetWindowPortBounds(window, inRect); Point pt = { inRect->top ,inRect->left }; QDLocalToGlobalPoint( GetWindowPort( window ), &pt ); inRect->bottom += pt.v - inRect->top; inRect->right += pt.h - inRect->left; inRect->top = pt.v; inRect->left = pt.h; } static SInt32 wxShapedMacWindowGetFeatures(WindowRef WXUNUSED(window), SInt32 param) { /*------------------------------------------------------ Define which options your custom window supports. --------------------------------------------------------*/ //just enable everything for our demo *(OptionBits*)param = //kWindowCanGrow | //kWindowCanZoom | kWindowCanCollapse | //kWindowCanGetWindowRegion | //kWindowHasTitleBar | //kWindowSupportsDragHilite | kWindowCanDrawInCurrentPort | //kWindowCanMeasureTitle | kWindowWantsDisposeAtProcessDeath | kWindowSupportsGetGrowImageRegion | kWindowDefSupportsColorGrafPort; return 1; } // The content region is left as a rectangle matching the window size, this is // so the origin in the paint event, and etc. still matches what the // programmer expects. static void wxShapedMacWindowContentRegion(WindowRef window, RgnHandle rgn) { SetEmptyRgn(rgn); wxNonOwnedWindow* win = wxNonOwnedWindow::GetFromWXWindow((WXWindow)window); if (win) { Rect r ; wxShapedMacWindowGetPos( window, &r ) ; RectRgn( rgn , &r ) ; } } // The structure region is set to the shape given to the SetShape method. static void wxShapedMacWindowStructureRegion(WindowRef window, RgnHandle rgn) { RgnHandle cachedRegion = (RgnHandle) GetWRefCon(window); SetEmptyRgn(rgn); if (cachedRegion) { Rect windowRect; wxShapedMacWindowGetPos(window, &windowRect); // how big is the window CopyRgn(cachedRegion, rgn); // make a copy of our cached region OffsetRgn(rgn, windowRect.left, windowRect.top); // position it over window //MapRgn(rgn, &mMaskSize, &windowRect); //scale it to our actual window size } } static SInt32 wxShapedMacWindowGetRegion(WindowRef window, SInt32 param) { GetWindowRegionPtr rgnRec = (GetWindowRegionPtr)param; if (rgnRec == NULL) return paramErr; switch (rgnRec->regionCode) { case kWindowStructureRgn: wxShapedMacWindowStructureRegion(window, rgnRec->winRgn); break; case kWindowContentRgn: wxShapedMacWindowContentRegion(window, rgnRec->winRgn); break; default: SetEmptyRgn(rgnRec->winRgn); break; } return noErr; } // Determine the region of the window which was hit // static SInt32 wxShapedMacWindowHitTest(WindowRef window, SInt32 param) { Point hitPoint; static RgnHandle tempRgn = NULL; if (tempRgn == NULL) tempRgn = NewRgn(); // get the point clicked SetPt( &hitPoint, LoWord(param), HiWord(param) ); // Mac OS 8.5 or later wxShapedMacWindowStructureRegion(window, tempRgn); if (PtInRgn( hitPoint, tempRgn )) //in window content region? return wInContent; // no significant area was hit return wNoHit; } static pascal long wxShapedMacWindowDef(short WXUNUSED(varCode), WindowRef window, SInt16 message, SInt32 param) { switch (message) { case kWindowMsgHitTest: return wxShapedMacWindowHitTest(window, param); case kWindowMsgGetFeatures: return wxShapedMacWindowGetFeatures(window, param); // kWindowMsgGetRegion is sent during CreateCustomWindow and ReshapeCustomWindow case kWindowMsgGetRegion: return wxShapedMacWindowGetRegion(window, param); default: break; } return 0; } // implementation typedef struct { wxPoint m_position ; wxSize m_size ; bool m_wasResizable ; } FullScreenData ; wxNonOwnedWindowCarbonImpl::wxNonOwnedWindowCarbonImpl() { } wxNonOwnedWindowCarbonImpl::wxNonOwnedWindowCarbonImpl( wxNonOwnedWindow* nonownedwnd) : wxNonOwnedWindowImpl( nonownedwnd) { m_macEventHandler = NULL; m_macWindow = NULL; m_macFullScreenData = NULL ; } wxNonOwnedWindowCarbonImpl::~wxNonOwnedWindowCarbonImpl() { #if wxUSE_TOOLTIPS wxToolTip::NotifyWindowDelete(m_macWindow) ; #endif if ( m_macEventHandler ) { ::RemoveEventHandler((EventHandlerRef) m_macEventHandler); m_macEventHandler = NULL ; } if ( m_macWindow && !m_wxPeer->IsNativeWindowWrapper()) DisposeWindow( m_macWindow ); FullScreenData *data = (FullScreenData *) m_macFullScreenData ; delete data ; m_macFullScreenData = NULL ; m_macWindow = NULL; } void wxNonOwnedWindowCarbonImpl::WillBeDestroyed() { if ( m_macEventHandler ) { ::RemoveEventHandler((EventHandlerRef) m_macEventHandler); m_macEventHandler = NULL ; } } static void wxNonOwnedWindowInstallTopLevelWindowEventHandler(WindowRef window, EventHandlerRef* handler, void *ref) { InstallWindowEventHandler(window, GetwxNonOwnedEventHandlerUPP(), GetEventTypeCount(eventList), eventList, ref, handler ); } bool wxNonOwnedWindowCarbonImpl::SetShape(const wxRegion& region) { // Make a copy of the region RgnHandle shapeRegion = NewRgn(); HIShapeGetAsQDRgn( region.GetWXHRGN(), shapeRegion ); // Dispose of any shape region we may already have RgnHandle oldRgn = (RgnHandle)GetWRefCon( (WindowRef) m_wxPeer->GetWXWindow() ); if ( oldRgn ) DisposeRgn(oldRgn); // Save the region so we can use it later SetWRefCon((WindowRef) m_wxPeer->GetWXWindow(), (URefCon)shapeRegion); // inform the window manager that the window has changed shape ReshapeCustomWindow((WindowRef) m_wxPeer->GetWXWindow()); return true; } void wxNonOwnedWindowCarbonImpl::MacInstallTopLevelWindowEventHandler() { if ( m_macEventHandler != NULL ) { verify_noerr( ::RemoveEventHandler( (EventHandlerRef) m_macEventHandler ) ) ; } wxNonOwnedWindowInstallTopLevelWindowEventHandler(MAC_WXHWND(m_macWindow),(EventHandlerRef *)&m_macEventHandler,this); } void wxNonOwnedWindowCarbonImpl::Create( wxWindow* WXUNUSED(parent), WXWindow nativeWindow ) { m_macWindow = nativeWindow; } void wxNonOwnedWindowCarbonImpl::Create( wxWindow* parent, const wxPoint& pos, const wxSize& size, long style, long extraStyle, const wxString& WXUNUSED(name) ) { OSStatus err = noErr ; Rect theBoundsRect; int x = (int)pos.x; int y = (int)pos.y; int w = size.x; int h = size.y; ::SetRect(&theBoundsRect, x, y , x + w, y + h); // translate the window attributes in the appropriate window class and attributes WindowClass wclass = 0; WindowAttributes attr = kWindowNoAttributes ; WindowGroupRef group = NULL ; bool activationScopeSet = false; WindowActivationScope activationScope = kWindowActivationScopeNone; if ( style & wxFRAME_TOOL_WINDOW ) { if ( ( style & wxMINIMIZE_BOX ) || ( style & wxMAXIMIZE_BOX ) || ( style & wxSYSTEM_MENU ) || ( style & wxCAPTION ) || ( style & wxTINY_CAPTION) ) { if ( ( style & wxSTAY_ON_TOP ) ) wclass = kUtilityWindowClass; else wclass = kFloatingWindowClass ; if ( ( style & wxTINY_CAPTION) ) attr |= kWindowSideTitlebarAttribute ; } else { if ( style & wxNO_BORDER ) { wclass = kSimpleWindowClass ; } else { wclass = kPlainWindowClass ; } activationScopeSet = true; activationScope = kWindowActivationScopeNone; } } else if ( ( style & wxPOPUP_WINDOW ) ) { if ( ( style & wxBORDER_NONE ) ) { wclass = kHelpWindowClass ; // has no border attr |= kWindowNoShadowAttribute; } else { wclass = kPlainWindowClass ; // has a single line border, it will have to do for now } group = GetWindowGroupOfClass(kFloatingWindowClass) ; // make sure we don't deactivate something activationScopeSet = true; activationScope = kWindowActivationScopeNone; } else if ( ( style & wxCAPTION ) ) { wclass = kDocumentWindowClass ; attr |= kWindowInWindowMenuAttribute ; } else if ( ( style & wxFRAME_DRAWER ) ) { wclass = kDrawerWindowClass; } else { if ( ( style & wxMINIMIZE_BOX ) || ( style & wxMAXIMIZE_BOX ) || ( style & wxCLOSE_BOX ) || ( style & wxSYSTEM_MENU ) ) { wclass = kDocumentWindowClass ; } else if ( ( style & wxNO_BORDER ) ) { wclass = kSimpleWindowClass ; } else { wclass = kPlainWindowClass ; } } if ( wclass != kPlainWindowClass ) { if ( ( style & wxMINIMIZE_BOX ) ) attr |= kWindowCollapseBoxAttribute ; if ( ( style & wxMAXIMIZE_BOX ) ) attr |= kWindowFullZoomAttribute ; if ( ( style & wxRESIZE_BORDER ) ) attr |= kWindowResizableAttribute ; if ( ( style & wxCLOSE_BOX) ) attr |= kWindowCloseBoxAttribute ; } attr |= kWindowLiveResizeAttribute; if ( ( style &wxSTAY_ON_TOP) ) group = GetWindowGroupOfClass(kUtilityWindowClass) ; if ( ( style & wxFRAME_FLOAT_ON_PARENT ) ) group = GetWindowGroupOfClass(kFloatingWindowClass) ; if ( group == NULL && parent != NULL ) { WindowRef parenttlw = (WindowRef) parent->MacGetTopLevelWindowRef(); if( parenttlw ) group = GetWindowGroupParent( GetWindowGroup( parenttlw ) ); } attr |= kWindowCompositingAttribute; #if 0 // TODO : decide on overall handling of high dpi screens (pixel vs userscale) attr |= kWindowFrameworkScaledAttribute; #endif if ( ( style &wxFRAME_SHAPED) ) { WindowDefSpec customWindowDefSpec; customWindowDefSpec.defType = kWindowDefProcPtr; customWindowDefSpec.u.defProc = #ifdef __LP64__ (WindowDefUPP) wxShapedMacWindowDef; #else NewWindowDefUPP(wxShapedMacWindowDef); #endif err = ::CreateCustomWindow( &customWindowDefSpec, wclass, attr, &theBoundsRect, (WindowRef*) &m_macWindow); } else { err = ::CreateNewWindow( wclass , attr , &theBoundsRect , (WindowRef*)&m_macWindow ) ; } if ( err == noErr && m_macWindow != NULL && group != NULL ) SetWindowGroup( (WindowRef) m_macWindow , group ) ; wxCHECK_RET( err == noErr, wxT("Mac OS error when trying to create new window") ); // setup a separate group for each window, so that overlays can be handled easily WindowGroupRef overlaygroup = NULL; verify_noerr( CreateWindowGroup( kWindowGroupAttrMoveTogether | kWindowGroupAttrLayerTogether | kWindowGroupAttrHideOnCollapse, &overlaygroup )); verify_noerr( SetWindowGroupParent( overlaygroup, GetWindowGroup( (WindowRef) m_macWindow ))); verify_noerr( SetWindowGroup( (WindowRef) m_macWindow , overlaygroup )); if ( activationScopeSet ) { verify_noerr( SetWindowActivationScope( (WindowRef) m_macWindow , activationScope )); } // the create commands are only for content rect, // so we have to set the size again as structure bounds SetWindowBounds( m_macWindow , kWindowStructureRgn , &theBoundsRect ) ; // Causes the inner part of the window not to be metal // if the style is used before window creation. #if 0 // TARGET_API_MAC_OSX if ( m_macUsesCompositing && m_macWindow != NULL ) { if ( GetExtraStyle() & wxFRAME_EX_METAL ) MacSetMetalAppearance( true ) ; } #endif if ( m_macWindow != NULL ) { MacSetUnifiedAppearance( true ) ; } HIViewRef growBoxRef = 0 ; err = HIViewFindByID( HIViewGetRoot( m_macWindow ), kHIViewWindowGrowBoxID, &growBoxRef ); if ( err == noErr && growBoxRef != 0 ) HIGrowBoxViewSetTransparent( growBoxRef, true ) ; // the frame window event handler InstallStandardEventHandler( GetWindowEventTarget(m_macWindow) ) ; MacInstallTopLevelWindowEventHandler() ; if ( extraStyle & wxFRAME_EX_METAL) MacSetMetalAppearance(true); if ( ( style &wxFRAME_SHAPED) ) { // default shape matches the window size wxRegion rgn( 0, 0, w, h ); SetShape( rgn ); } } bool wxNonOwnedWindowCarbonImpl::ShowWithEffect(bool show, wxShowEffect effect, unsigned timeout) { WindowTransitionEffect transition = 0 ; switch( effect ) { case wxSHOW_EFFECT_ROLL_TO_LEFT: case wxSHOW_EFFECT_ROLL_TO_RIGHT: case wxSHOW_EFFECT_ROLL_TO_TOP: case wxSHOW_EFFECT_ROLL_TO_BOTTOM: case wxSHOW_EFFECT_SLIDE_TO_LEFT: case wxSHOW_EFFECT_SLIDE_TO_RIGHT: case wxSHOW_EFFECT_SLIDE_TO_TOP: case wxSHOW_EFFECT_SLIDE_TO_BOTTOM: transition = kWindowGenieTransitionEffect; break; case wxSHOW_EFFECT_BLEND: transition = kWindowFadeTransitionEffect; break; case wxSHOW_EFFECT_EXPAND: // having sheets would be fine, but this might lead to a repositioning #if 0 if ( GetParent() ) transition = kWindowSheetTransitionEffect; else #endif transition = kWindowZoomTransitionEffect; break; case wxSHOW_EFFECT_NONE: // wxNonOwnedWindow is supposed to call Show() itself in this case wxFAIL_MSG( "ShowWithEffect() shouldn't be called" ); return false; case wxSHOW_EFFECT_MAX: wxFAIL_MSG( "invalid effect flag" ); return false; } TransitionWindowOptions options; options.version = 0; options.duration = timeout / 1000.0; options.window = transition == kWindowSheetTransitionEffect ? (WindowRef) m_wxPeer->GetParent()->MacGetTopLevelWindowRef() :0; options.userData = 0; wxSize size = wxGetDisplaySize(); Rect bounds; GetWindowBounds( (WindowRef)m_macWindow, kWindowStructureRgn, &bounds ); CGRect hiBounds = CGRectMake( bounds.left, bounds.top, bounds.right - bounds.left, bounds.bottom - bounds.top ); switch ( effect ) { case wxSHOW_EFFECT_ROLL_TO_RIGHT: case wxSHOW_EFFECT_SLIDE_TO_RIGHT: hiBounds.origin.x = 0; hiBounds.size.width = 0; break; case wxSHOW_EFFECT_ROLL_TO_LEFT: case wxSHOW_EFFECT_SLIDE_TO_LEFT: hiBounds.origin.x = size.x; hiBounds.size.width = 0; break; case wxSHOW_EFFECT_ROLL_TO_TOP: case wxSHOW_EFFECT_SLIDE_TO_TOP: hiBounds.origin.y = size.y; hiBounds.size.height = 0; break; case wxSHOW_EFFECT_ROLL_TO_BOTTOM: case wxSHOW_EFFECT_SLIDE_TO_BOTTOM: hiBounds.origin.y = 0; hiBounds.size.height = 0; break; default: break; // direction doesn't make sense } ::TransitionWindowWithOptions ( (WindowRef)m_macWindow, transition, show ? kWindowShowTransitionAction : kWindowHideTransitionAction, transition == kWindowGenieTransitionEffect ? &hiBounds : NULL, false, &options ); if ( show ) { ::SelectWindow( (WindowRef)m_macWindow ) ; } return true; } void wxNonOwnedWindowCarbonImpl::SetTitle( const wxString& title, wxFontEncoding encoding ) { SetWindowTitleWithCFString( m_macWindow , wxCFStringRef( title , encoding ) ) ; } bool wxNonOwnedWindowCarbonImpl::IsMaximized() const { return IsWindowInStandardState( m_macWindow , NULL , NULL ) ; } bool wxNonOwnedWindowCarbonImpl::IsIconized() const { return IsWindowCollapsed((WindowRef)GetWXWindow() ) ; } void wxNonOwnedWindowCarbonImpl::Iconize( bool iconize ) { if ( IsWindowCollapsable( m_macWindow ) ) CollapseWindow( m_macWindow , iconize ) ; } void wxNonOwnedWindowCarbonImpl::Maximize(bool maximize) { Point idealSize = { 0 , 0 } ; if ( maximize ) { HIRect bounds ; HIWindowGetAvailablePositioningBounds(kCGNullDirectDisplay,kHICoordSpace72DPIGlobal, &bounds); idealSize.h = bounds.size.width; idealSize.v = bounds.size.height; } ZoomWindowIdeal( (WindowRef)GetWXWindow() , maximize ? inZoomOut : inZoomIn , &idealSize ) ; } bool wxNonOwnedWindowCarbonImpl::IsFullScreen() const { return m_macFullScreenData != NULL ; } bool wxNonOwnedWindowCarbonImpl::ShowFullScreen(bool show, long style) { if ( show ) { FullScreenData *data = (FullScreenData *)m_macFullScreenData ; delete data ; data = new FullScreenData() ; m_macFullScreenData = data ; data->m_position = m_wxPeer->GetPosition() ; data->m_size = m_wxPeer->GetSize() ; #if wxOSX_USE_CARBON WindowAttributes attr = 0; GetWindowAttributes((WindowRef) GetWXWindow(), &attr); data->m_wasResizable = attr & kWindowResizableAttribute; if ( style & wxFULLSCREEN_NOMENUBAR ) HideMenuBar() ; #endif wxRect client = wxGetClientDisplayRect() ; int left, top, width, height ; int x, y, w, h ; x = client.x ; y = client.y ; w = client.width ; h = client.height ; GetContentArea( left, top, width, height ) ; int outerwidth, outerheight; GetSize( outerwidth, outerheight ); if ( style & wxFULLSCREEN_NOCAPTION ) { y -= top ; h += top ; // avoid adding the caption twice to the height outerheight -= top; } if ( style & wxFULLSCREEN_NOBORDER ) { x -= left ; w += outerwidth - width; h += outerheight - height; } if ( style & wxFULLSCREEN_NOTOOLBAR ) { // TODO } if ( style & wxFULLSCREEN_NOSTATUSBAR ) { // TODO } m_wxPeer->SetSize( x , y , w, h ) ; if ( data->m_wasResizable ) { #if wxOSX_USE_CARBON ChangeWindowAttributes( (WindowRef) GetWXWindow() , kWindowNoAttributes , kWindowResizableAttribute ) ; #endif } } else if ( m_macFullScreenData != NULL ) { FullScreenData *data = (FullScreenData *) m_macFullScreenData ; #if wxOSX_USE_CARBON ShowMenuBar() ; if ( data->m_wasResizable ) ChangeWindowAttributes( (WindowRef) GetWXWindow() , kWindowResizableAttribute , kWindowNoAttributes ) ; #endif m_wxPeer->SetPosition( data->m_position ) ; m_wxPeer->SetSize( data->m_size ) ; delete data ; m_macFullScreenData = NULL ; } return true; } // Attracts the users attention to this window if the application is // inactive (should be called when a background event occurs) static pascal void wxMacNMResponse( NMRecPtr ptr ) { NMRemove( ptr ) ; DisposePtr( (Ptr)ptr ) ; } void wxNonOwnedWindowCarbonImpl::RequestUserAttention(int WXUNUSED(flags)) { NMRecPtr notificationRequest = (NMRecPtr) NewPtr( sizeof( NMRec) ) ; memset( notificationRequest , 0 , sizeof(*notificationRequest) ) ; notificationRequest->qType = nmType ; notificationRequest->nmMark = 1 ; notificationRequest->nmIcon = 0 ; notificationRequest->nmSound = 0 ; notificationRequest->nmStr = NULL ; notificationRequest->nmResp = wxMacNMResponse ; verify_noerr( NMInstall( notificationRequest ) ) ; } void wxNonOwnedWindowCarbonImpl::ScreenToWindow( int *x, int *y ) { HIPoint p = CGPointMake( (x ? *x : 0), (y ? *y : 0) ); HIViewRef contentView ; // TODO check toolbar offset HIViewFindByID( HIViewGetRoot( m_macWindow ), kHIViewWindowContentID , &contentView) ; HIPointConvert( &p, kHICoordSpace72DPIGlobal, NULL, kHICoordSpaceView, contentView ); if ( x ) *x = (int)p.x; if ( y ) *y = (int)p.y; } void wxNonOwnedWindowCarbonImpl::WindowToScreen( int *x, int *y ) { HIPoint p = CGPointMake( (x ? *x : 0), (y ? *y : 0) ); HIViewRef contentView ; // TODO check toolbar offset HIViewFindByID( HIViewGetRoot( m_macWindow ), kHIViewWindowContentID , &contentView) ; HIPointConvert( &p, kHICoordSpaceView, contentView, kHICoordSpace72DPIGlobal, NULL ); if ( x ) *x = (int)p.x; if ( y ) *y = (int)p.y; } bool wxNonOwnedWindowCarbonImpl::IsActive() { return ActiveNonFloatingWindow() == m_macWindow; } wxNonOwnedWindowImpl* wxNonOwnedWindowImpl::CreateNonOwnedWindow( wxNonOwnedWindow* wxpeer, wxWindow* parent, const wxPoint& pos, const wxSize& size, long style, long extraStyle, const wxString& name ) { wxNonOwnedWindowImpl* now = new wxNonOwnedWindowCarbonImpl( wxpeer ); now->Create( parent, pos, size, style , extraStyle, name ); return now; } wxNonOwnedWindowImpl* wxNonOwnedWindowImpl::CreateNonOwnedWindow( wxNonOwnedWindow* wxpeer, wxWindow* parent, WXWindow nativeWindow ) { wxNonOwnedWindowCarbonImpl* now = new wxNonOwnedWindowCarbonImpl( wxpeer ); now->Create( parent, nativeWindow ); return now; }
33.156527
149
0.61485
madanagopaltcomcast
f9ad4312de5c1a791a43fc1f5c8245b363d36f9a
4,636
hh
C++
include/utrig_matrix.hh
sylvainouel/metl
94fa40b9aabdf869cab8e6b92305a9fe5252f989
[ "MIT" ]
null
null
null
include/utrig_matrix.hh
sylvainouel/metl
94fa40b9aabdf869cab8e6b92305a9fe5252f989
[ "MIT" ]
null
null
null
include/utrig_matrix.hh
sylvainouel/metl
94fa40b9aabdf869cab8e6b92305a9fe5252f989
[ "MIT" ]
null
null
null
#ifndef UTRIG_MATRIX_HH #define UTRIG_MATRIX_HH /* Copyright (c) 2005-2015, Sylvain Ouellet 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. */ // that is an upper triangular matrx. i.e. only elements m(i,j) where // j>i are accessibles namespace metl { template <class T> class utrig_matrix; template<class T> struct utrig_matrix_iterator { utrig_matrix_iterator(utrig_matrix<T>& point_to) : m(point_to), i(0), j(1) {} utrig_matrix_iterator(utrig_matrix<T>& point_to, unsigned init_i, unsigned init_j) : m(point_to), i(init_i), j(init_j) { assert(j>i); } inline T& operator*() { return m(i,j); } inline const T& operator*() const { return m(i,j); } inline utrig_matrix_iterator& operator++() { assert(j>i); assert(j<m.cols); if (++j == m.cols) { ++i; j=i+1; } return *this; } inline bool operator==(const utrig_matrix_iterator& rhs) const { return (&m==&rhs.m && i==rhs.i && j==rhs.j); } inline bool operator!=(const utrig_matrix_iterator& rhs) const { return !(operator==(rhs)); } inline unsigned get_i() const { return i; } // this is needed. we need to know were the iterator points. inline unsigned get_j() const { return j; } private: utrig_matrix<T>& m; unsigned i, j; friend class utrig_matrix<T>; }; template<class T> class utrig_matrix { public: typedef utrig_matrix_iterator<T> iterator; utrig_matrix() {}; utrig_matrix(unsigned nrows, unsigned ncols); ~utrig_matrix(); utrig_matrix(const utrig_matrix& m); utrig_matrix& operator= (const utrig_matrix& m); // Access methods to get the (i,j) element: inline T& operator() (unsigned i, unsigned j) { assert(j>i); return data_[i][j-i-1]; }; inline const T& operator() (unsigned i, unsigned j) const { assert(j>i); return data_[i][j-i-1]; }; iterator begin() { return iterator(*this); } const iterator end() { return iterator(*this, rows-1, cols); } private: T** data_; unsigned rows, cols; friend class utrig_matrix_iterator<T>; }; template<class T> utrig_matrix<T>::utrig_matrix(const utrig_matrix<T>& m) : data_(0), rows(m.rows), cols(m.cols) { if (rows==0) return; // allocate memory data_ = new T*[rows]; for (unsigned i=0; i<rows; ++i) data_[i] = new T[cols-i-1]; for (unsigned i=0; i<rows; ++i) for (unsigned j=i+1; j<cols; ++j) operator()(i,j) = m.operator()(i,j); } template <class T> utrig_matrix<T>& utrig_matrix<T>::operator= (const utrig_matrix<T>& m) { if (this == &m) return *this; if (cols!=m.cols || rows!=m.rows) { for (unsigned i=0; i<rows; ++i) delete[] data_[i]; if (rows!=m.rows) { if (rows!=0) delete[] data_; if (m.rows>0) data_ = new T*[m.rows]; else data_ = 0; } rows=m.rows; cols=m.cols; for (unsigned i=0; i<m.rows; ++i) { data_[i] = new T[m.cols]; } } // copy data from old matrix to new one for (unsigned i=0; i<rows; ++i) for (unsigned j=i+1; j<cols; ++j) operator()(i,j) = m.operator()(i,j); return *this; } template<class T> utrig_matrix<T>::utrig_matrix(unsigned nrows, unsigned ncols) : data_(0), rows(nrows), cols(ncols) { if (rows==0) return; data_ = new T*[nrows]; for (unsigned i=0; i<nrows; ++i) data_[i] = new T[ncols]; for (unsigned i=0; i<nrows; ++i) for (unsigned j=i+1; j<ncols; ++j) operator()(i,j) = 0; } template<class T> utrig_matrix<T>::~utrig_matrix() { if (rows>0) { for (unsigned i=0; i<rows; ++i) delete[] data_[i]; delete[] data_; } } } #endif
21.663551
107
0.646894
sylvainouel
f9b2d5bdc7028669a74eee6f1765882ce5cf49d7
8,467
cc
C++
framework/render/vk/vk_image_barrier.cc
ans-hub/gdm_framework
4218bb658d542df2c0568c4d3aac813cd1f18e1b
[ "MIT" ]
1
2020-12-30T23:50:01.000Z
2020-12-30T23:50:01.000Z
framework/render/vk/vk_image_barrier.cc
ans-hub/gdm_framework
4218bb658d542df2c0568c4d3aac813cd1f18e1b
[ "MIT" ]
null
null
null
framework/render/vk/vk_image_barrier.cc
ans-hub/gdm_framework
4218bb658d542df2c0568c4d3aac813cd1f18e1b
[ "MIT" ]
null
null
null
// ************************************************************* // File: vk_image_barrier.cc // Author: Novoselov Anton @ 2020 // URL: https://github.com/ans-hub/gdm_framework // ************************************************************* #include "vk_image_barrier.h" #include "render/vk/vk_image.h" #include "render/vk/vk_image_view.h" #include "system/assert_utils.h" #include "system/bits_utils.h" // --public Resource<ImageBarrier> gdm::vk::Resource<gdm::vk::ImageBarrier>::Resource(api::Device* device) : BaseResourceBuilder(*device) { ptr_->image_barrier_.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; ptr_->image_barrier_.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; ptr_->image_barrier_.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; ptr_->image_barrier_.subresourceRange.baseMipLevel = 0; ptr_->image_barrier_.subresourceRange.levelCount = 1; ptr_->image_barrier_.subresourceRange.baseArrayLayer = 0; ptr_->image_barrier_.subresourceRange.layerCount = 1; ptr_->image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; } gdm::vk::Resource<gdm::vk::ImageBarrier>::~Resource() { FillAspectMask(ptr_->image_barrier_.newLayout, VK_FORMAT_UNDEFINED); FillAccessMasks(ptr_->image_barrier_.oldLayout, ptr_->image_barrier_.newLayout); ptr_->src_stage_mask_ = api::helpers::GetStageMask(ptr_->image_barrier_.srcAccessMask); ptr_->dst_stage_mask_ = api::helpers::GetStageMask(ptr_->image_barrier_.dstAccessMask); } auto gdm::vk::Resource<gdm::vk::ImageBarrier>::AddImage(VkImage image) -> Resource::self { ptr_->image_barrier_.image = image; return *this; } auto gdm::vk::Resource<gdm::vk::ImageBarrier>::AddOldLayout(gfx::EImageLayout old_layout) -> Resource::self { ptr_->image_barrier_.oldLayout = VkImageLayout(old_layout); return *this; } auto gdm::vk::Resource<gdm::vk::ImageBarrier>::AddNewLayout(gfx::EImageLayout new_layout) -> Resource::self { ptr_->image_barrier_.newLayout = VkImageLayout(new_layout); return *this; } // --private Resource<ImageBarrier> void gdm::vk::Resource<gdm::vk::ImageBarrier>::FillAspectMask(VkImageLayout layout, VkFormat format) { if (layout != VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) ptr_->image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; else { bool has_stencil = api::helpers::HasStencil(format); if (has_stencil) ptr_->image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; else ptr_->image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; } } void gdm::vk::Resource<gdm::vk::ImageBarrier>::FillAccessMasks(VkImageLayout old_layout, VkImageLayout new_layout) { if (old_layout == VK_IMAGE_LAYOUT_PREINITIALIZED && new_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_PREINITIALIZED && new_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR && new_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) { ptr_->image_barrier_.srcAccessMask = 0; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = 0; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = 0; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_PREINITIALIZED && new_layout == VK_IMAGE_LAYOUT_GENERAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_GENERAL && new_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_GENERAL && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = 0; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = 0; ptr_->image_barrier_.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; } else { ASSERTF(false, "Unsupported yet image layout transition"); } } // --helpers auto gdm::vk::helpers::GetStageMask(VkAccessFlags access) -> VkPipelineStageFlagBits { VkPipelineStageFlagBits mask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; if (bits::HasFlag(access, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT)) return VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; else if (bits::HasFlag(access, VK_ACCESS_UNIFORM_READ_BIT)) return VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; // TODO: else if (bits::HasFlag(access, VK_ACCESS_TRANSFER_WRITE_BIT)) return VK_PIPELINE_STAGE_TRANSFER_BIT; else if (bits::HasFlag(access, VK_ACCESS_TRANSFER_READ_BIT)) return VK_PIPELINE_STAGE_TRANSFER_BIT; else if (bits::HasFlag(access, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT)) return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; else if (bits::HasFlag(access, VK_ACCESS_SHADER_READ_BIT)) return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; else return mask; }
45.767568
134
0.77867
ans-hub
f9b78cda5b9efe33a1367fbf98be44327b177636
1,399
cpp
C++
priminitial.cpp
jei3di/DigraphMaker
40758f19057df663ac95f5f8a2e1cff8614a7c49
[ "MIT" ]
null
null
null
priminitial.cpp
jei3di/DigraphMaker
40758f19057df663ac95f5f8a2e1cff8614a7c49
[ "MIT" ]
null
null
null
priminitial.cpp
jei3di/DigraphMaker
40758f19057df663ac95f5f8a2e1cff8614a7c49
[ "MIT" ]
null
null
null
#include "priminitial.h" #include "ui_priminitial.h" #include "testfilegraph.h" #include "manualgraphscreen.h" #include "prim.h" int initialPrim = 0; int getInitialPrim(){ return initialPrim; } PrimInitial::PrimInitial(QWidget *parent) : QDialog(parent), ui(new Ui::PrimInitial) { ui->setupUi(this); int tempNodes; node *tempNode; bool auto_manualGraph; if(getManualGraph()) auto_manualGraph = false; else auto_manualGraph = true; if(auto_manualGraph){ // Automatic graph. tempNode = getAutoNodesArray(); tempNodes = getAutoNodes(); }else{ tempNode = getNodesArrayManual(); tempNodes = getManualNodes(); } // Nodes: QString label3; while(tempNodes >= 0){ string label = tempNode->label; QString label2 = QString::fromStdString(label); if(tempNodes == 0) label3 += label2 + "."; else label3 += label2 + ", "; tempNode = tempNode->next; tempNodes--; } if(auto_manualGraph) setNodesXY(); // Setting values for X & Y. else setManualNodesXY(); ui->nodes->appendPlainText(label3); } PrimInitial::~PrimInitial() { delete ui; } void PrimInitial::on_execute_clicked() { QString initialQ = ui->initial->text(); initialPrim = initialQ.toInt(); Prim *PrimW = new Prim(this); PrimW->setModal(true); PrimW->show(); }
20.275362
67
0.631165
jei3di
f9b882f4a86ced95a63cb4d4ee4670b8874d3417
2,203
cpp
C++
sources/details/http_service.cpp
RKulagin/keyboard-suggest
5dcb5ca524448cc6bd8a390a6eea5861e70a3598
[ "MIT" ]
null
null
null
sources/details/http_service.cpp
RKulagin/keyboard-suggest
5dcb5ca524448cc6bd8a390a6eea5861e70a3598
[ "MIT" ]
null
null
null
sources/details/http_service.cpp
RKulagin/keyboard-suggest
5dcb5ca524448cc6bd8a390a6eea5861e70a3598
[ "MIT" ]
null
null
null
#include "details/http_service.h" #include <sstream> namespace { std::string GetLastWord(const std::string &input) { std::stringstream s(input); std::string last_word; while (!s.eof()) { std::string t; s >> t; if (!t.empty()) { last_word = std::move(t); } } return last_word; } } // namespace void HttpService::Run(uint16_t port) { auto resource = std::make_shared<restbed::Resource>(); resource->set_path("/data"); resource->set_method_handler("GET", [this](const std::shared_ptr<restbed::Session> session) { Input input; input.input = session->get_request()->get_query_parameter("input", ""); input.last_word = GetLastWord(input.input); std::cout << input.last_word << std::endl; InternalState new_state; auto answer = MakeSuggestions(input, storage_, state_, new_state); holder_.Change(std::move(answer)); state_ = std::move(new_state); std::unique_lock<SceneHolder> lk(holder_); session->close(restbed::OK, holder_.data(), {{"Content-Type", "application/json"}}); }); auto viewer = std::make_shared<restbed::Resource>(); viewer->set_path("/viewer/{filename: (index.html|render.js)}"); viewer->set_method_handler("GET", [this](const std::shared_ptr<restbed::Session> session) { const auto request = session->get_request(); const std::string filename = request->get_path_parameter("filename"); std::ifstream stream(viewer_path_ + filename, std::ifstream::in); if (stream.is_open()) { const std::string body = std::string(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()); session->close(restbed::OK, body); } else { session->close(restbed::NOT_FOUND); } }); auto settings = std::make_shared<restbed::Settings>(); settings->set_port(port); settings->set_default_header("Connection", "close"); std::cout << "Press Ctrl+C to stop the service." << std::endl; const std::string full_url = "http://localhost:" + std::to_string(port) + "/viewer/index.html"; std::cout << "Staring service: " << full_url << std::endl; restbed::Service service; service.publish(viewer); service.publish(resource); service.start(settings); }
32.880597
117
0.670903
RKulagin
f9bd95a4d3fc3367f1f789c7f5b4b65e2352c481
1,637
hxx
C++
private/inet/xml/xml/om/ie4nodefactory.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/xml/xml/om/ie4nodefactory.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/xml/xml/om/ie4nodefactory.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
/* * Copyright (C) 1998,1999 Microsoft Corporation. All rights reserved. * */ #ifndef _IE4NODEFACTORY_HXX #define _IE4NODEFACTORY_HXX #ifndef _XML_OM_NODEDATANODEFACTORY #include "nodedatanodefactory.hxx" #endif class IE4NodeFactory : public _NDNodeFactory { public: // (De)Constructors IE4NodeFactory( Document * pDocument); ~IE4NodeFactory(); public: virtual HRESULT STDMETHODCALLTYPE NotifyEvent( /* [in] */ IXMLNodeSource __RPC_FAR *pNodeSource, /* [in] */ XML_NODEFACTORY_EVENT iEvt); virtual HRESULT STDMETHODCALLTYPE BeginChildren( /* [in] */ IXMLNodeSource __RPC_FAR *pNodeSource, /* [in] */ XML_NODE_INFO* __RPC_FAR pNodeInfo); virtual HRESULT STDMETHODCALLTYPE EndChildren( /* [in] */ IXMLNodeSource __RPC_FAR *pNodeSource, /* [in] */ BOOL fEmptyNode, /* [in] */ XML_NODE_INFO* __RPC_FAR pNodeInfo); virtual HRESULT STDMETHODCALLTYPE Error( /* [in] */ IXMLNodeSource __RPC_FAR *pNodeSource, /* [in] */ HRESULT hrErrorCode, /* [in] */ USHORT cNumRecs, /* [in] */ XML_NODE_INFO __RPC_FAR *__RPC_FAR *apNodeInfo); virtual HRESULT STDMETHODCALLTYPE CreateNode( /* [in] */ IXMLNodeSource __RPC_FAR *pNodeSource, /* [in] */ PVOID pNodeParent, /* [in] */ USHORT cNumRecs, /* [in] */ XML_NODE_INFO __RPC_FAR *__RPC_FAR *apNodeInfo); protected: // instance vars RNamespaceMgr _pNamespaceMgr; }; extern HRESULT AbortParse(IXMLNodeSource * pNodeSource, Exception * e, Document * pDoc); #endif _IE4NODEFACTORY_HXX
31.480769
89
0.656078
King0987654
f9bf74c6d7846e335efe0b4a9bbe840ecc741d63
1,040
hpp
C++
fsc/include/win/event.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
fsc/include/win/event.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
fsc/include/win/event.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
// (c) Copyright 2008 Samuel Debionne. // // Distributed under the MIT Software License. (See accompanying file // license.txt) or copy at http://www.opensource.org/licenses/mit-license.php) // // See http://code.google.com/p/fsc-sdk/ for the library home page. // // $Revision: $ // $History: $ /// \file event.hpp /// Windows event #if !defined(__WIN_EVENT_HPP__) #define __WIN_EVENT_HPP__ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <windows.h> #include <boost/shared_ptr.hpp> #include <win/exception.hpp> namespace win { typedef boost::shared_ptr<void> event_t; inline event_t create_event(BOOL _bManualReset = FALSE) { event_t h(::CreateEvent(NULL, _bManualReset, FALSE, NULL), ::CloseHandle); if (!h) throw runtime_error("CreateEvent failed"); return h; } inline void set(event_t _h) { if (::SetEvent(_h.get())) throw runtime_error("SetEvent failed"); } } //namespace win #endif //__WIN_EVENT_HPP__
18.245614
80
0.651923
gbucknell
f9c13584f53883ed1e2dee30914e17d2bdc172b2
451
cpp
C++
dispenso/detail/per_thread_info.cpp
jeffamstutz/dispenso
0fb1db63a386c1ba59cd761677af6e9f0052c61c
[ "MIT" ]
1
2022-01-26T01:12:01.000Z
2022-01-26T01:12:01.000Z
dispenso/detail/per_thread_info.cpp
jeffamstutz/dispenso
0fb1db63a386c1ba59cd761677af6e9f0052c61c
[ "MIT" ]
null
null
null
dispenso/detail/per_thread_info.cpp
jeffamstutz/dispenso
0fb1db63a386c1ba59cd761677af6e9f0052c61c
[ "MIT" ]
null
null
null
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE.md file in the root directory of this source tree. #include <dispenso/detail/per_thread_info.h> namespace dispenso { namespace detail { PerThreadInfo& PerPoolPerThreadInfo::info() { static DISPENSO_THREAD_LOCAL PerThreadInfo perThreadInfo; return perThreadInfo; } } // namespace detail } // namespace dispenso
25.055556
66
0.767184
jeffamstutz
f9c2d9051da33322513478c8801323bd6ad62d57
69
cpp
C++
lib/cmake/Qt5Qml/Qt5Qml_QQmlNativeDebugConnectorFactory_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
lib/cmake/Qt5Qml/Qt5Qml_QQmlNativeDebugConnectorFactory_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
lib/cmake/Qt5Qml/Qt5Qml_QQmlNativeDebugConnectorFactory_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
#include <QtPlugin> Q_IMPORT_PLUGIN(QQmlNativeDebugConnectorFactory)
23
48
0.884058
samlior
f9c4007b6b9ce98129216fc8e3dad7db8d32b9a4
6,915
cpp
C++
src/geo/test/latlng_codec_test.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
1,352
2017-10-16T03:24:54.000Z
2020-08-18T04:44:23.000Z
src/geo/test/latlng_codec_test.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
299
2017-10-19T05:33:32.000Z
2020-08-17T09:03:39.000Z
src/geo/test/latlng_codec_test.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
240
2017-10-16T05:57:04.000Z
2020-08-18T10:02:36.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 <memory> #include <gtest/gtest.h> #include <geo/lib/latlng_codec.h> #include <dsn/utility/errors.h> namespace pegasus { namespace geo { TEST(latlng_codec_test, set_latlng_indices) { latlng_codec codec; ASSERT_FALSE(codec.set_latlng_indices(3, 3).is_ok()); ASSERT_TRUE(codec.set_latlng_indices(3, 4).is_ok()); ASSERT_TRUE(codec.set_latlng_indices(4, 3).is_ok()); } TEST(latlng_codec_for_lbs_test, decode_from_value) { latlng_codec codec; ASSERT_TRUE(codec.set_latlng_indices(5, 4).is_ok()); double lat_degrees = 12.345; double lng_degrees = 67.890; S2LatLng latlng; std::string test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "|" + std::to_string(lat_degrees) + "|24.043028|4.15921|0|-1"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "|2018-04-26|2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "|" + std::to_string(lat_degrees) + "|24.043028|4.15921|0|-1"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "00:00:00:00:01:5e||2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "|" + std::to_string(lat_degrees) + "|24.043028|4.15921|0|-1"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "|" + std::to_string(lat_degrees) + "||4.15921|0|-1"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "|" + std::to_string(lat_degrees) + "|24.043028|4.15921|0|"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr||" + std::to_string(lat_degrees) + "|24.043028|4.15921|0|-1"; ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "||24.043028|4.15921|0|-1"; ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr|||24.043028|4.15921|0|-1"; ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); } TEST(latlng_codec_for_aibox_test, decode_from_value) { latlng_codec codec; ASSERT_TRUE(codec.set_latlng_indices(0, 1).is_ok()); double lat_degrees = 12.345; double lng_degrees = 67.890; S2LatLng latlng; std::string test_value = std::to_string(lat_degrees) + "|" + std::to_string(lng_degrees); ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = std::to_string(lat_degrees) + "|" + std::to_string(lng_degrees) + "|24.043028"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = std::to_string(lat_degrees) + "|" + std::to_string(lng_degrees) + "||"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "|" + std::to_string(lat_degrees) + "|" + std::to_string(lng_degrees); ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); test_value = "|" + std::to_string(lat_degrees); ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); test_value = std::to_string(lng_degrees) + "|"; ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); test_value = "|"; ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); } TEST(latlng_codec_encode_test, encode_to_value) { latlng_codec codec; double lat_degrees = 12.345; double lng_degrees = 67.890; std::string value; ASSERT_TRUE(codec.set_latlng_indices(0, 1).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("12.345000|67.890000", value); ASSERT_TRUE(codec.set_latlng_indices(1, 0).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("67.890000|12.345000", value); ASSERT_TRUE(codec.set_latlng_indices(4, 5).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("||||12.345000|67.890000", value); ASSERT_TRUE(codec.set_latlng_indices(5, 4).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("||||67.890000|12.345000", value); ASSERT_TRUE(codec.set_latlng_indices(0, 3).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("12.345000|||67.890000", value); ASSERT_TRUE(codec.set_latlng_indices(3, 1).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("|67.890000||12.345000", value); ASSERT_FALSE(codec.encode_to_value(91, lng_degrees, value)); ASSERT_FALSE(codec.encode_to_value(-91, lng_degrees, value)); ASSERT_FALSE(codec.encode_to_value(lat_degrees, 181, value)); ASSERT_FALSE(codec.encode_to_value(lat_degrees, -181, value)); } } // namespace geo } // namespace pegasus
41.909091
100
0.701518
empiredan
f9c440dadba1c1355f84f73cb718dd9ee0efebeb
1,320
cpp
C++
CLI/files/PostTagCribFile.cpp
maxitg/PostTagSystem
7d7c506ed32ab105b2ad064ababf2299fc9e9cfd
[ "MIT" ]
6
2021-05-19T15:48:41.000Z
2022-02-06T05:38:20.000Z
CLI/files/PostTagCribFile.cpp
maxitg/PostTagSystem
7d7c506ed32ab105b2ad064ababf2299fc9e9cfd
[ "MIT" ]
6
2021-02-26T22:14:42.000Z
2021-03-15T19:16:55.000Z
CLI/files/PostTagCribFile.cpp
maxitg/PostTagSystem
7d7c506ed32ab105b2ad064ababf2299fc9e9cfd
[ "MIT" ]
null
null
null
#include "PostTagCribFile.hpp" #include "boost/format.hpp" using PostTagSystem::TagState; PostTagCribFile PostTagCribFileReader::read_file() { uint8_t file_magic = read_u8(); PostTagFileMagic format_magic = CribFileMagic; if (file_magic != format_magic) { throw std::runtime_error((boost::format("File magic number 0x%X did not match expected 0x%X") % static_cast<unsigned int>(file_magic) % static_cast<unsigned int>(format_magic)) .str()); } uint8_t version = read_u8(); switch (version) { case Version1: return read_file_V1(); default: throw std::runtime_error( (boost::format("Unsupported file version %u") % static_cast<unsigned int>(version)).str()); } } PostTagCribFile PostTagCribFileReader::read_file_V1() { PostTagCribFile file; file.version = Version1; file.checkpoint_count = read_u64(); file.checkpoints = read_checkpoints(file.checkpoint_count); return file; } std::vector<TagState> PostTagCribFileReader::read_checkpoints(uint64_t checkpoint_count) { std::vector<TagState> checkpoints(checkpoint_count); for (size_t i = 0; i < checkpoint_count; i++) { checkpoints[i].headState = read_u8(); checkpoints[i].tape = read_prefixed_bits(); } return checkpoints; }
28.695652
110
0.689394
maxitg
f9c45a730d3db5a964e21252cbf049c8ea4be75a
225
cpp
C++
sensor_fsm_coro_sched/Sources/fut_cpp.cpp
bbelson2/k22f_coro
f4388f39110dd60553d9b579a65ceadd518b1396
[ "MIT" ]
null
null
null
sensor_fsm_coro_sched/Sources/fut_cpp.cpp
bbelson2/k22f_coro
f4388f39110dd60553d9b579a65ceadd518b1396
[ "MIT" ]
null
null
null
sensor_fsm_coro_sched/Sources/fut_cpp.cpp
bbelson2/k22f_coro
f4388f39110dd60553d9b579a65ceadd518b1396
[ "MIT" ]
null
null
null
/* * fut_cpp.cpp * * Created on: 23 Nov 2018 * Author: Bruce Belson */ using namespace scheduling; upromise ufuture<int32_t> delayed_light(int32_t delay) { return } extern "C" int fut_test() { return 0; }
9.782609
47
0.653333
bbelson2
f9c92ba4b8a8bd6b518dc3b775ec0a5af0250f9f
1,162
cpp
C++
CoCoJoystick2PC/Blinker.cpp
ranaur/CoCoJoystick2PC
a49308201fbc04e20083eabd111b62b18d1b1211
[ "MIT" ]
null
null
null
CoCoJoystick2PC/Blinker.cpp
ranaur/CoCoJoystick2PC
a49308201fbc04e20083eabd111b62b18d1b1211
[ "MIT" ]
null
null
null
CoCoJoystick2PC/Blinker.cpp
ranaur/CoCoJoystick2PC
a49308201fbc04e20083eabd111b62b18d1b1211
[ "MIT" ]
null
null
null
#include "Blinker.h" void Blinker::play(const uint16_t *playTimes, int repeat = -1) { /*debug("Blinker::play() "); debugvar("repeat = ", repeat); debugvar("playTimes = ", (int)playTimes); debugln("");*/ _playTimes = playTimes; _repeat = repeat; on(); } void Blinker::loop(uint32_t now = millis()) { /*debugvar("start = ", _start); debugvar(" now = ", now); debugvar(" repeat = ", _repeat); debugvar(" position = ", _position); debugln("");*/ if(_repeat == 0) return; // it is not playing if(now > _nextFade) { _fade(_intensityStep * (_turningOn ? 1 : -1)); _nextFade += _timeStep; } if(now < _playUntil) return; // time to play next "time" has not yet arrived if(_playTimes[_position] == 0) { // ended the play if(_repeat < 0) { _reset(); return; } // infinite play _repeat--; if(_repeat == 0) { // turn off off(); } else { // play again _reset(); } } _playUntil += _playTimes[_position]; if(_position % 2 == 0) { on(); //debugln("ON"); } else { //debugln("OFF"); off(); } _position++; }
21.518519
79
0.539587
ranaur
f9ca9b21084ff8d228bec45735894875b758585b
434
cpp
C++
ntuj/0342.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
ntuj/0342.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
ntuj/0342.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
#include<cstdio> long long go(long long x) { if(x<3)return x; if(x<5)return x-1; for(long long i=3;i*i<=x;i++) if(x%i==0)return x-x/i; if(x%2==0)return x-2; return x-1; } main() { long long i,j,k,T; scanf("%lld",&T); while(T--) { scanf("%lld %lld",&i,&k); while(k--) { for(j=i;go(j)<i;j++); i=j; } printf("%lld\n",i); } }
16.692308
33
0.414747
dk00
f9caa1df7fb789af7b22ecafbb4c1b70cef620c0
3,230
cpp
C++
equalization_CPU.cpp
Programacion-multinucleo-2018/assignment-4-histogram-equalization-leeseu95
8cff72e9bb2f8e6427d88407af6f1d221bc921f4
[ "MIT" ]
null
null
null
equalization_CPU.cpp
Programacion-multinucleo-2018/assignment-4-histogram-equalization-leeseu95
8cff72e9bb2f8e6427d88407af6f1d221bc921f4
[ "MIT" ]
null
null
null
equalization_CPU.cpp
Programacion-multinucleo-2018/assignment-4-histogram-equalization-leeseu95
8cff72e9bb2f8e6427d88407af6f1d221bc921f4
[ "MIT" ]
null
null
null
//Seung Hoon Lee - A01021720 //Tarea 4 - Equalization CPU version //g++ -o equalization_CPU equalization_CPU.cpp -lopencv_core -lopencv_highgui -lopencv_imgproc -std=c++11 #include <iostream> #include <cstdio> #include <cmath> #include <chrono> #include <cstdlib> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace std; void createHistogram(cv::Mat& input, long *h_s) { int index; for(int i = 0; i < input.rows; i++) { for(int j = 0; j < input.cols; j++) { index = (int)input.at<uchar>(i,j); h_s[index]++; // h_s[0] = 1; // cout << h_s[index] << endl; } } } void normalize(cv::Mat& input, long *h_s) { long temp[256] = {}; for(int i = 0; i < 256; i++) { temp[i] = h_s[i]; } //Reinicializamos en 0 el histograma orgiinal for(int i = 0; i < 256; i++) { h_s[i] = 0; } for(int i = 0; i < 256; i++) { for(int j = 0; j <= i; j++) { h_s[i] += temp[j]; } int normalizeVar = (h_s[i]*255) / (input.rows*input.cols); // if (normalizeVar < 0) { // normalizeVar = abs(normalizeVar); // } h_s[i] = normalizeVar; // cout << h_s[i] << endl; //Debug } } void equalize(cv::Mat& input, cv::Mat& output, long * h_s){ int index; for(int i = 0; i < input.rows; i++) { for(int j = 0; j < input.cols; j++) { index = (int)input.at<uchar>(i,j); output.at<uchar>(i,j) = h_s[index]; } } } void equalizer(cv::Mat& input, cv::Mat& output) //Le pasamos de parametro solo el input , output con CV { cout << "Input image step: " << input.step << " rows: " << input.rows << " cols: " << input.cols << endl; // cout << input.rows * input.cols << endl; // Calculate total number of bytes of input and output image // Step = cols * number of colors // size_t colorBytes = input.step * input.rows; long h_s[256] = {}; createHistogram(input, h_s); normalize(input, h_s); equalize(input, output, h_s); // cout << h_s[0] << endl; //Debug } int main(int argc, char *argv[]) { string imagePath; if(argc < 2) imagePath = "Images/dog1.jpeg"; else imagePath = argv[1]; // Read input image from the disk cv::Mat input = cv::imread(imagePath, CV_LOAD_IMAGE_COLOR); if (input.empty()) { cout << "Image Not Found!" << std::endl; cin.get(); return -1; } //Create output image cv::Mat temp(input.rows, input.cols, CV_8UC1); //Creamos una matriz temporal para cambiar el input a una griz cv::Mat output(input.rows, input.cols, CV_8UC1); //Se tiene que cambiar a CV_8UC1 en vez de CV_8UC3 //Cambiamos el input a un gray cv::cvtColor(input, temp, CV_BGR2GRAY); //Call the wrapper function auto start_cpu = chrono::high_resolution_clock::now(); equalizer(temp, output); auto end_cpu = chrono::high_resolution_clock::now(); chrono::duration<float, std::milli> duration_ms = end_cpu - start_cpu; printf("La cantidad de tiempo que se tarda cada ejecucion es alrededor de: %f ms\n", duration_ms.count()); //Allow the windows to resize namedWindow("Input", cv::WINDOW_NORMAL); namedWindow("Output", cv::WINDOW_NORMAL); //Show the input and output imshow("Input", input); imshow("Output", output); //Wait for key press cv::waitKey(); return 0; }
26.47541
110
0.635604
Programacion-multinucleo-2018
f9d124788ff81a2d9ca43f51be668ee6169d3593
865
cpp
C++
chapter1/02/RandomColorGenerator.cpp
ps-group/modern-gl-samples
53e075ec21418597b37c71c895111c0c77cab72b
[ "MIT" ]
1
2017-06-20T06:56:57.000Z
2017-06-20T06:56:57.000Z
chapter1/02/RandomColorGenerator.cpp
ps-group/modern-gl-samples
53e075ec21418597b37c71c895111c0c77cab72b
[ "MIT" ]
null
null
null
chapter1/02/RandomColorGenerator.cpp
ps-group/modern-gl-samples
53e075ec21418597b37c71c895111c0c77cab72b
[ "MIT" ]
null
null
null
#include "RandomColorGenerator.h" namespace { std::vector<glm::vec4> MakePalette() { // Превращает rgb(255, 0, 128) в vec4{ 1, 0, 0.5, 1 } auto rgb = [](unsigned red, unsigned green, unsigned blue) { return glm::vec4(float(red) / 255.f, float(green) / 255.f, float(blue) / 255.f, 1); }; // Цвета подобраны на сайте https://websafecolors.info/color-chart return { rgb(0, 204, 102), rgb(102, 102, 102), rgb(102, 153, 204), rgb(153, 255, 153), rgb(204, 153, 51), rgb(0, 255, 102), rgb(204, 0, 102), rgb(204, 102, 255), rgb(102, 255, 255), rgb(153, 255, 102), }; } } RandomColorGenerator::RandomColorGenerator() : m_palette(MakePalette()) , m_generator(m_rd()) , m_indexDist(0, m_palette.size() - 1u) { } glm::vec4 RandomColorGenerator::GenerateColor() { const size_t index = m_indexDist(m_generator); return m_palette.at(index); }
21.625
85
0.652023
ps-group
f9d24688e17ea3ca0b9bb25f2c2c9f1003b8cbb4
4,113
hpp
C++
include/Model.hpp
nasa/swSim
348ba39ea149711a2285916a2dcddc2c71da4859
[ "Apache-2.0" ]
5
2021-02-21T09:49:11.000Z
2022-02-01T09:54:54.000Z
include/Model.hpp
ElsevierSoftwareX/SOFTX-D-21-00042
348ba39ea149711a2285916a2dcddc2c71da4859
[ "Apache-2.0" ]
null
null
null
include/Model.hpp
ElsevierSoftwareX/SOFTX-D-21-00042
348ba39ea149711a2285916a2dcddc2c71da4859
[ "Apache-2.0" ]
4
2021-04-27T09:52:17.000Z
2022-03-29T07:22:16.000Z
/*! \headerfile Model.hpp "include/Model.hpp" * "Model.hpp" contains the class definition encapsulating the * data structure interface for a Model in swSim. */ // Copyright 2020 United States Government as represented by the Administrator of the National // Aeronautics and Space Administration. No copyright is claimed in the United States under // Title 17, U.S. Code. All Other Rights Reserved. See Appendix A for 3rd party licenses. // // The Solid-Wave Sim (swSIM) platform is 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. #ifndef MODEL_HPP #define MODEL_HPP #include <mpi.h> #include <stdint.h> #include <string> #include <vector> #include <stddef.h> #include "Material.hpp" #include "Excitation.hpp" #include "Geometry.hpp" #include "ParsableObject.hpp" namespace swSim{ /*! \class Model Model.hpp "include/Model.hpp" * * Defines data structures for Model in swSim */ class Model: public ParsableObject { public: struct model_s { uint32_t numTimeSteps; /*!< Number of time steps in the simulation */ double dt; /*!< Size of the time step in seconds */ uint8_t numMaterials; /*!< Number of matrials in the model */ uint8_t numExcitations; /*!< Number of excitations in the model */ char inputFile[50]; /*!< Input file name */ char inputPath[150]; /*!< Path to input file directory */ }; model_s modS; /*!< The Model struct for MPI passing */ Geometry modGeometry; /*!< The geometry associated with the model */ std::vector<Material> modMaterialsList; /*!< Vector of materials */ std::vector<Excitation> modExcitationsList; /*!< Vector of Excitations */ MPI_Datatype mpi_model; /*!< MPI data type for passing the Model struct*/ // std::vector<std::string> parseNames; /*!< Vector of parse names to look for when reading inputs*/ /*! * Create the Model */ Model(); /*! * Destroy the Model */ ~Model(); /*! * Initilize data values */ void Init(uint32_t TimeSteps, double dt, uint8_t numMat, uint8_t numExc); /*! * Initilize data values and file names */ void Init(uint32_t TimeSteps, double dt, uint8_t numMat, uint8_t numExc, const char *inFname, const char *inPname); /*! * Copy values of one model to another. */ void Copy(Model *other); /*! * Create the MPI datatype for the model. */ MPI_Datatype MPICreate(); /*! * Provide parsing instructions for reading inputs associated with the model */ void ParseSwitch(xmlDocPtr doc, xmlNodePtr cur, int caseNumber) override; /*! * Takes input from a file and disperse it across all process */ void Input(char *inputFileName, MPI_Comm m_mpi_comm); /*! * Prints all the elements of the Model */ void Print(int rank); /*! * Read the Input from the file */ int readInput(char *inputFileName); /*! * Send the Input to other processes */ void sendInput(MPI_Comm l_mpi_comm); /*! * Recieve the Input from another processes */ void recieveInput(MPI_Comm l_mpi_comm); /*! * Return the path only */ std::string parsePath(char *inputFileName); /*! * Return the filename only */ std::string parseFile(char *inputFileName); }; }; #endif /*SWSIM_MODEL_H*/
34.855932
124
0.625821
nasa
f9da5c9167ab9dd80ceae603d3c1c26bc81fa148
846
cpp
C++
Pacientes.cpp
victorortiz98/ManchesterTriage-Stack-and-List-
df2a37b79c6491bd616eab1adccc2cec83952784
[ "Apache-2.0" ]
null
null
null
Pacientes.cpp
victorortiz98/ManchesterTriage-Stack-and-List-
df2a37b79c6491bd616eab1adccc2cec83952784
[ "Apache-2.0" ]
null
null
null
Pacientes.cpp
victorortiz98/ManchesterTriage-Stack-and-List-
df2a37b79c6491bd616eab1adccc2cec83952784
[ "Apache-2.0" ]
null
null
null
// // Created by Víctor Ortiz on 14/06/2021. // #include "Pacientes.hpp" #include <iostream> #include <string> Pacientes::Pacientes(int id, std::string dni, std::string nombre, std::string apellido1, std::string apellido2, int edad, char sexo) { IdPaciente = id; Dni = dni; Nombre = nombre; Apellido1= apellido1; Apellido2= apellido2; Edad = edad; Sexo= sexo; } int Pacientes ::getIdPaciente(){ return IdPaciente; } std :: string Pacientes::getDni(){ return Dni; } std::string Pacientes:: getNombre(){ return Nombre; } std::string Pacientes:: getApellido1(){ return Apellido1; } std::string Pacientes:: getApellido2(){ return Apellido2;} int Pacientes::getEdad(){ return Edad;} char Pacientes::getSexo(){ return Sexo;} Pacientes::~Pacientes() { }
20.634146
133
0.638298
victorortiz98
f9dabd5788ed7e46f1f77167cd6f9a8b25e4335c
359
cpp
C++
Dataset/Leetcode/train/118/347.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/118/347.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/118/347.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> XXX(int numRows) { vector<vector<int>>f; for(int i=0;i<numRows;i++){ vector<int>res(i+1); res[i]=res[0]=1; for(int j=1;j<i;j++){ res[j]=f[i-1][j-1]+f[i-1][j]; } f.push_back(res); } return f; } };
21.117647
45
0.409471
kkcookies99
f9dffec4f28b1bd8f685364919cc9b1dafb2d657
5,483
cpp
C++
src/common/cpp/mayarendernodes/standinLocatorNode.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
42
2015-01-03T15:07:25.000Z
2021-12-09T03:56:59.000Z
src/common/cpp/mayarendernodes/standinLocatorNode.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
66
2015-01-02T13:28:44.000Z
2022-03-16T14:00:57.000Z
src/common/cpp/mayarendernodes/standinLocatorNode.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
12
2015-02-07T05:02:17.000Z
2020-07-10T17:21:44.000Z
#include "standinLocatorNode.h" //#include <maya/MFnStringData.h> //#include <maya/MFnDependencyNode.h> //#include <maya/MGlobal.h> //#include <maya/MDoubleArray.h> //#include <maya/MSelectionList.h> //#include "utilities/pystring.h" MObject StandinLocatorNode::bboxMin; MObject StandinLocatorNode::bboxMax; MObject StandinLocatorNode::proxyFile; MObject StandinLocatorNode::displayType; MObject StandinLocatorNode::percentDisplay; MObject StandinLocatorNode::elementSize; MObject StandinLocatorNode::dummyOutput; MStatus StandinLocatorNode::initialize() { MFnTypedAttribute tAttr; MFnNumericAttribute nAttr; MFnLightDataAttribute lAttr; MFnEnumAttribute eAttr; MStatus stat; bboxMin = nAttr.createPoint( "bboxMin", "bboxMin" ); CHECK_MSTATUS ( nAttr.setKeyable(true) ); CHECK_MSTATUS ( nAttr.setStorable(true) ); CHECK_MSTATUS ( nAttr.setDefault(-0.5f, -0.5f, -0.5f) ); bboxMax = nAttr.createPoint( "bboxMax", "bboxMax" ); CHECK_MSTATUS ( nAttr.setKeyable(true) ); CHECK_MSTATUS ( nAttr.setStorable(true) ); CHECK_MSTATUS ( nAttr.setDefault( 0.5f, 0.5f, 0.5f) ); proxyFile = tAttr.create( "proxyFile", "proxyFile", MFnNumericData::kString); tAttr.setUsedAsFilename(true); CHECK_MSTATUS(addAttribute( proxyFile )); displayType = eAttr.create("displayType", "displayType", 0, &stat); stat = eAttr.addField( "BBox", 0 ); stat = eAttr.addField( "Points", 1 ); stat = eAttr.addField( "Polygons", 2 ); CHECK_MSTATUS(addAttribute( displayType )); percentDisplay = nAttr.create( "percentDisplay", "percentDisplay", MFnNumericData::kFloat, 0.1f); CHECK_MSTATUS(addAttribute( percentDisplay )); elementSize = nAttr.create( "elementSize", "elementSize", MFnNumericData::kInt, 1); CHECK_MSTATUS(addAttribute( elementSize )); dummyOutput = nAttr.create( "dummyOutput", "dummyOutput", MFnNumericData::kFloat); CHECK_MSTATUS ( addAttribute(dummyOutput) ); CHECK_MSTATUS ( attributeAffects (bboxMin, dummyOutput) ); CHECK_MSTATUS ( attributeAffects (bboxMax, dummyOutput) ); CHECK_MSTATUS ( attributeAffects (proxyFile, dummyOutput) ); CHECK_MSTATUS ( attributeAffects (displayType, dummyOutput) ); CHECK_MSTATUS ( attributeAffects (percentDisplay, dummyOutput) ); CHECK_MSTATUS ( attributeAffects (elementSize, dummyOutput) ); return MS::kSuccess; } void StandinLocatorNode::draw( M3dView & view, const MDagPath & /*path*/, M3dView::DisplayStyle style, M3dView::DisplayStatus status ) { MStatus stat; MDataBlock datablock = forceCache(); MDataHandle handle = datablock.inputValue( dummyOutput, &stat ); view.beginGL(); { glPushAttrib( GL_CURRENT_BIT ); { if ( status == M3dView::kActive ) { view.setDrawColor( 13, M3dView::kActiveColors ); } else { view.setDrawColor( 13, M3dView::kDormantColors ); } //// Draw the outline of the box // faceDown glBegin( GL_LINE_STRIP ); glVertex3f((GLfloat)this->bboxmin.x, (GLfloat)this->bboxmin.y, (GLfloat)this->bboxmin.z); glVertex3f((GLfloat)this->bboxmax.x, (GLfloat)this->bboxmin.y, (GLfloat)this->bboxmin.z); glVertex3f((GLfloat)this->bboxmax.x, (GLfloat)this->bboxmin.y, (GLfloat)this->bboxmax.z); glVertex3f((GLfloat)this->bboxmin.x, (GLfloat)this->bboxmin.y, (GLfloat)this->bboxmax.z); glVertex3f((GLfloat)this->bboxmin.x, (GLfloat)this->bboxmin.y, (GLfloat)this->bboxmin.z); glEnd(); // faceRoof glBegin( GL_LINE_STRIP ); glVertex3f((GLfloat)this->bboxmin.x, (GLfloat)this->bboxmax.y, (GLfloat)this->bboxmin.z); glVertex3f((GLfloat)this->bboxmax.x, (GLfloat)this->bboxmax.y, (GLfloat)this->bboxmin.z); glVertex3f((GLfloat)this->bboxmax.x, (GLfloat)this->bboxmax.y, (GLfloat)this->bboxmax.z); glVertex3f((GLfloat)this->bboxmin.x, (GLfloat)this->bboxmax.y, (GLfloat)this->bboxmax.z); glVertex3f((GLfloat)this->bboxmin.x, (GLfloat)this->bboxmax.y, (GLfloat)this->bboxmin.z); glEnd(); // 4 columns glBegin( GL_LINES ); glVertex3f((GLfloat)this->bboxmin.x, (GLfloat)this->bboxmin.y, (GLfloat)this->bboxmin.z); glVertex3f((GLfloat)this->bboxmin.x, (GLfloat)this->bboxmax.y, (GLfloat)this->bboxmin.z); glEnd(); glBegin( GL_LINES ); glVertex3f((GLfloat)this->bboxmin.x, (GLfloat)this->bboxmin.y, (GLfloat)this->bboxmax.z); glVertex3f((GLfloat)this->bboxmin.x, (GLfloat)this->bboxmax.y, (GLfloat)this->bboxmax.z); glEnd(); glBegin( GL_LINES ); glVertex3f((GLfloat)this->bboxmax.x, (GLfloat)this->bboxmin.y, (GLfloat)this->bboxmax.z); glVertex3f((GLfloat)this->bboxmax.x, (GLfloat)this->bboxmax.y, (GLfloat)this->bboxmax.z); glEnd(); glBegin( GL_LINES ); glVertex3f((GLfloat)this->bboxmax.x, (GLfloat)this->bboxmin.y, (GLfloat)this->bboxmin.z); glVertex3f((GLfloat)this->bboxmax.x, (GLfloat)this->bboxmax.y, (GLfloat)this->bboxmin.z); glEnd(); } glPopAttrib(); //glPointSize((float)pointsize); //glBegin( GL_POINTS ); //for( uint i = 0; i < pointData.length(); i++) // glVertex3f(pointData[i].x, pointData[i].y, pointData[i].z); glEnd(); } view.endGL(); } bool StandinLocatorNode::isBounded() const { return true; } MBoundingBox StandinLocatorNode::boundingBox() const { MObject thisNode = thisMObject(); MPlug plug( thisNode, dummyOutput ); MPoint corner1( -0.5, -0.5, -0.5 ); MPoint corner2( 0.5, 0.5, 0.5 ); return MBoundingBox( corner1, corner2 ); } StandinLocatorNode::StandinLocatorNode() { } StandinLocatorNode::~StandinLocatorNode() { }
33.638037
98
0.707824
haggi
f9e0c35c957f936951c83aef0311f3c8d7d00e27
761
cpp
C++
cpp_tries/ch05/ex7.cpp
frankji/CPP-Primer-Plus-6
20ddba26faec93a347c96b866db853c2d154b639
[ "MIT" ]
null
null
null
cpp_tries/ch05/ex7.cpp
frankji/CPP-Primer-Plus-6
20ddba26faec93a347c96b866db853c2d154b639
[ "MIT" ]
null
null
null
cpp_tries/ch05/ex7.cpp
frankji/CPP-Primer-Plus-6
20ddba26faec93a347c96b866db853c2d154b639
[ "MIT" ]
null
null
null
#include <iostream> #include <string> struct car { std::string make; //use std::string if you do not want to claim the name space here. int year; }; //';' after struct. int main() { using namespace std; int ncars; cout << "How many cars do you wish to catalog? "; cin >> ncars; cin.get(); car * info = new car[ncars]; for(int i = 0; i < ncars; ++i) { cout << "Car #" << i + 1 << ":" << endl; cout << "Please enter the make: "; getline(cin, info[i].make); cout << "Please enter the year made: "; cin >> info[i].year; cin.get(); //Release '\n' out of the input queue. } cout << "Here is your collection: " << endl; for(int i = 0; i < ncars; ++i) { cout << info[i].year << " " << info[i].make << endl; } delete [] info; return 0; }
22.382353
85
0.576873
frankji
f9e70bda305fe442cbcb125f244b6e75c0564104
821
cpp
C++
Two Pointer/numberOfGoodPairs.cpp
anishmo99/Diversified-Programming
2bc955682414ac5afc9e39fbf2e01c411b0b86de
[ "MIT" ]
2
2020-08-09T02:09:50.000Z
2020-08-09T07:07:47.000Z
Two Pointer/numberOfGoodPairs.cpp
anishmo99/Diversified-Programming
2bc955682414ac5afc9e39fbf2e01c411b0b86de
[ "MIT" ]
null
null
null
Two Pointer/numberOfGoodPairs.cpp
anishmo99/Diversified-Programming
2bc955682414ac5afc9e39fbf2e01c411b0b86de
[ "MIT" ]
5
2020-09-21T12:49:07.000Z
2020-09-29T16:13:09.000Z
class Solution { public: int numIdenticalPairs(vector<int> &nums) { int count = 0; vector<pair<int, int>> vec; int i = 0, j = 1; while (i < nums.size() - 1) { if (nums[i] == nums[j]) { count++; } j++; if (j == nums.size()) { i++; j = i + 1; } } return count; } }; // or class Solution { public: int numIdenticalPairs(vector<int> &nums) { int sum = 0; for (int i = 0; i < nums.size() - 1; i++) { for (int j = i + 1; j < nums.size(); j++) { if (nums[i] == nums[j]) sum++; } } return sum; } };
16.755102
53
0.327649
anishmo99
f9eb5b23b2d9fee70295240f48027d6e593919fc
1,574
hpp
C++
ss/relocation_table.hpp
leduftw/ss
eb9ec70b8adbf6cd991f009c89f1667682150701
[ "MIT" ]
1
2021-09-01T09:00:06.000Z
2021-09-01T09:00:06.000Z
ss/relocation_table.hpp
leduftw/ss
eb9ec70b8adbf6cd991f009c89f1667682150701
[ "MIT" ]
null
null
null
ss/relocation_table.hpp
leduftw/ss
eb9ec70b8adbf6cd991f009c89f1667682150701
[ "MIT" ]
null
null
null
#ifndef RELOCATION_TABLE #define RELOCATION_TABLE #include <iostream> #include <string> #include <vector> #include <iomanip> #include <sstream> #include <memory> #include <unordered_map> #include "section.hpp" using namespace std; class RelocationTable { public: enum class RelocationType { UNDEFINED, R_HYPO_16, R_HYPO_PC16, R_HYPO_PC16_ABS, // for %symbol in jump instructions if the symbol is defined with equ directive }; struct RelocationRecord { // What? string symbol_name = ""; size_t entry = 0; // Where? shared_ptr<Section> section; int offset = -1; // position inside a section // How? RelocationType relocation_type = RelocationType::UNDEFINED; }; friend ostream& operator<<(ostream& os, const RelocationTable& rt); void insert(string section_name, shared_ptr<RelocationRecord> record) { records[section_name].push_back(record); size++; } size_t get_size() const { return size; } bool empty() const { return get_size() == 0; } private: size_t size = 0; /* For each section name, we have vector of relocation records. E.g. for .text section we have .rel.text, for .data .rel.data etc. */ unordered_map<string, vector<shared_ptr<RelocationRecord>>> records; void print_header(ostream& os, string section_name) const; void print_content(ostream& os, const vector<shared_ptr<RelocationRecord>>& records_for_section) const; }; #endif
22.169014
107
0.651842
leduftw
f9ecad1cf3fa60d89e0fbc0394cff2c50a1a5d13
12,085
cpp
C++
source/interface/font.cpp
timothyvolpe/2DProject
5473bfe7590deb5c9fd03ec2ce9e3709c78c03c9
[ "MIT" ]
null
null
null
source/interface/font.cpp
timothyvolpe/2DProject
5473bfe7590deb5c9fd03ec2ce9e3709c78c03c9
[ "MIT" ]
null
null
null
source/interface/font.cpp
timothyvolpe/2DProject
5473bfe7590deb5c9fd03ec2ce9e3709c78c03c9
[ "MIT" ]
null
null
null
#include "base.h" #include "interface\font.h" #include "interface\distance-field.h" #include "game.h" #include "texture.h" #include <ftbitmap.h> bool CachedGlyph::operator<( const CachedGlyph &rhs ) const { return width*rows > rhs.width*rhs.rows; } CFont::CFont() { m_cacheFace = 0; m_cachedArea = 0; m_fontFileName = L""; m_pFontMap = 0; } CFont::~CFont() { } bool CFont::initialize( bool systemFont, std::wstring const& fontFile ) { this->ClearCache(); FT_Library ftLib = CGame::getInstance().getFreeType(); FT_Error ftError; boost::filesystem::wpath fontPath; m_fontFileName = fontFile; // Construct the full font path if( systemFont ) { #if defined( _WIN32 ) wchar_t winDir[MAX_PATH]; GetWindowsDirectory( winDir, MAX_PATH ); fontPath = winDir; fontPath /= "fonts"; fontPath /= fontFile; #endif } else fontPath = GameFilesystem::ConstructPath( fontFile, FILESYSTEM_DIR_FONTS ); // Load the font from freetype ftError = FT_New_Face( ftLib, fontPath.string().c_str(), 0, &m_cacheFace ); if( ftError ) { PrintError( L"FreeType failed to load font \'%s\' (code: %d, '%hs')\n", m_fontFileName.c_str(), ftError, GetFreetypeError( ftError ) ); return false; } // Select the unicode charmap ftError = FT_Select_Charmap( m_cacheFace, FT_ENCODING_UNICODE ); if( ftError ) { PrintError( L"FreeType couldn't find unicode charmap in font \'%s\' (code: %d, '%hs')\n", m_fontFileName.c_str(), ftError, GetFreetypeError( ftError ) ); return false; } // Check to see if the font is compatible if( (m_cacheFace->face_flags & FT_FACE_FLAG_HORIZONTAL) == 0 || m_cacheFace->face_flags & FT_FACE_FLAG_TRICKY ) { PrintError( L" Font \'%s\' is not supported\n", m_fontFileName.c_str() ); return false; } // Set the font size to 24 for the distance field ftError = FT_Set_Char_Size( m_cacheFace, 0, 24*FT_HRES, 0, FT_DPI ); if( ftError ) { PrintError( L"Font \'%s\' does not contain the correct size for distance field! (code: %d, '%hs')\n", m_fontFileName.c_str(), ftError, GetFreetypeError( ftError ) ); return true; } // Load the default characters if( !this->CacheCharacters( DEFAULT_CHARACTERS, DEFAULT_CHARACTERS_COUNT ) ) return false; // Generate the map if( !this->GenerateMapFromCache() ) { PrintError( L"Failed to generate font map for text \'%s\'\n", m_fontFileName.c_str() ); return false; } return true; } void CFont::destroy() { if( m_cacheFace ) { FT_Done_Face( m_cacheFace ); m_cacheFace = 0; } this->ClearCache(); m_fontFileName = L""; DestroyDelete( m_pFontMap ); } bool CFont::CacheCharacters( const wchar_t *pCharacters, size_t characterCount ) { if( !m_cacheFace ) { PrintError( L"Cannot cache characters when font face map has already been created\n" ); return false; } for( size_t i = 0; i < characterCount; i++ ) { FT_UInt glyphIndex; FT_Error ftError; CachedGlyph cachedGlyph; unsigned char *pTempBuffer; // Get the glyph index glyphIndex = FT_Get_Char_Index( m_cacheFace, pCharacters[i] ); if( !glyphIndex ) { PrintWarn( L"Missing character \'%c\' in font \'%s\'\n", pCharacters[i], m_fontFileName.c_str() ); glyphIndex = FT_Get_Char_Index( m_cacheFace, REPLACEMENT_CHAR ); } // Attempt to load the glyph ftError = FT_Load_Glyph( m_cacheFace, glyphIndex, FT_LOAD_RENDER ); if( ftError != 0 ) { PrintWarn( L"Failed to load glyph (%c) in font \'%s\' (code: %d, '%hs')\n", pCharacters[i], m_fontFileName.c_str(), ftError, GetFreetypeError( ftError ) ); continue; } if( m_cacheFace->glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY ) { PrintWarn( L"Glyph loaded as invalid format\n" ); continue; } // Store the glyphs data cachedGlyph.character = pCharacters[i]; cachedGlyph.width = m_cacheFace->glyph->bitmap.width; cachedGlyph.rows = m_cacheFace->glyph->bitmap.rows; cachedGlyph.pitch = m_cacheFace->glyph->bitmap.pitch; cachedGlyph.metrics.horizAdvance = m_cacheFace->glyph->metrics.horiAdvance / FT_HRES; cachedGlyph.metrics.vertAdvance = m_cacheFace->glyph->metrics.vertAdvance / FT_HRES; cachedGlyph.metrics.descent = (m_cacheFace->glyph->metrics.height - m_cacheFace->glyph->metrics.horiBearingY) / FT_HRES; cachedGlyph.metrics.ascent = m_cacheFace->glyph->metrics.horiBearingY / FT_HRES; cachedGlyph.padding = { 1, (m_cacheFace->ascender / FT_HRES) - cachedGlyph.metrics.ascent, 1, (-m_cacheFace->descender / FT_HRES) - cachedGlyph.metrics.descent }; // Check if glyph is special char if( pCharacters[i] == L' ' ) { cachedGlyph.width = cachedGlyph.metrics.horizAdvance; cachedGlyph.rows = 1; cachedGlyph.bufferSize = cachedGlyph.rows*cachedGlyph.width; cachedGlyph.pBuffer = new unsigned char[cachedGlyph.bufferSize]; cachedGlyph.padding.bottom--; memset( cachedGlyph.pBuffer, 0, cachedGlyph.bufferSize ); } else { // Copy bitmap cachedGlyph.bufferSize = cachedGlyph.rows*cachedGlyph.pitch; cachedGlyph.pBuffer = new unsigned char[cachedGlyph.bufferSize]; memcpy( cachedGlyph.pBuffer, m_cacheFace->glyph->bitmap.buffer, cachedGlyph.bufferSize ); } // Convert bitmap to distance field pTempBuffer = make_distance_mapb( cachedGlyph.pBuffer, cachedGlyph.width, cachedGlyph.rows ); SafeDeleteArray( cachedGlyph.pBuffer ); cachedGlyph.pBuffer = pTempBuffer; m_cachedArea += cachedGlyph.bufferSize; m_cachedGlyphs.push_back( cachedGlyph ); } return true; } bool CFont::GenerateMapFromCache() { TextureDescriptor textureDesc; unsigned char *pMapBuffer; unsigned int mapDimension; DestroyDelete( m_pFontMap ); m_pFontMap = new CTexture2D(); if( !m_pFontMap->initialize() ) return false; mapDimension = 256; if( m_cachedArea > mapDimension*mapDimension ) { PrintError( L"Font map is too small! Time to fix this...\n" ); return false; } // Create a test buffer pMapBuffer = new unsigned char[mapDimension*mapDimension]; memset( pMapBuffer, 0, mapDimension*mapDimension ); // Now we have to bin sort each glyph this->binPackCache( mapDimension ); // Render the map and populate glyph map unsigned int width, height, pitch; unsigned int offsetX, offsetY; for( auto it = m_glyphBinNodes.begin(); it != m_glyphBinNodes.end(); it++ ) { if( (*it)->pLeft || (*it)->pRight ) { width = (*it)->width - (*it)->glyph.padding.left - (*it)->glyph.padding.right; height = (*it)->height - (*it)->glyph.padding.top - (*it)->glyph.padding.bottom; pitch = (*it)->glyph.pitch; offsetX = (*it)->x + (*it)->glyph.padding.left; offsetY = (*it)->y + (*it)->glyph.padding.top; // Insert a glyph into the buffer for( unsigned int x = offsetX; x < offsetX+width; x++ ) { for( unsigned int y = offsetY; y < offsetY+height; y++ ) { pMapBuffer[y*mapDimension+x] = (*it)->glyph.pBuffer[(y-offsetY)*width+(x-offsetX)]; } } // Store the relevant glyph data GlyphData glyphData; glyphData.width = (*it)->width; glyphData.height = (*it)->height; glyphData.uv_start = glm::vec2( (float)(*it)->x / (float)mapDimension, (float)(*it)->y / (float)mapDimension ); glyphData.uv_end = glm::vec2( (float)(*it)->width / (float)mapDimension, (float)(*it)->height / (float)mapDimension ); glyphData.metrics = (*it)->glyph.metrics; m_glyphs.insert( std::pair<wchar_t, GlyphData>( (*it)->glyph.character, glyphData ) ); } } textureDesc.magFilter = GL_LINEAR; textureDesc.minFilter = GL_LINEAR; textureDesc.wrapS = GL_CLAMP_TO_EDGE; textureDesc.wrapT = GL_CLAMP_TO_EDGE; textureDesc.useAlpha = false; textureDesc.monochrome = true; if( !m_pFontMap->loadTextureFromMemory( pMapBuffer, mapDimension*mapDimension, mapDimension, mapDimension, textureDesc ) ) return false; // Clear cache data this->ClearCache(); return true; } void CFont::ClearCache() { // Clean up bin nodes for( auto it = m_glyphBinNodes.begin(); it != m_glyphBinNodes.end(); it++ ) { delete (*it); } m_glyphBinNodes.clear(); // Clean up cached glyph for( auto it = m_cachedGlyphs.begin(); it != m_cachedGlyphs.end(); it++ ) { delete[] ( *it ).pBuffer; } m_cachedGlyphs.clear(); m_cachedArea = 0; } bool CFont::binPackCache( unsigned int mapDimension ) { GlyphBinNode *pRootNode; // Sort by area std::sort( m_cachedGlyphs.begin(), m_cachedGlyphs.end() ); // Root node pRootNode = new GlyphBinNode; pRootNode->pLeft = NULL; pRootNode->pRight = NULL; pRootNode->width = mapDimension; pRootNode->height = mapDimension; pRootNode->x = pRootNode->y = 0; m_glyphBinNodes.push_back( pRootNode ); // Pack the glyphs for( std::vector<CachedGlyph>::iterator it = m_cachedGlyphs.begin(); it != m_cachedGlyphs.end(); it++ ) { // Insert into a node if( !this->insertIntoBin( pRootNode, (*it) ) ) { PrintError( L"Font tree ran out of space\n" ); break; } } return true; } GlyphBinNode* CFont::insertIntoBin( GlyphBinNode *pNode, CachedGlyph cachedGlyph ) { int newWidth, newHeight; unsigned int boxWidth, boxHeight; // Check if this node is internal (has children) if( pNode->pLeft || pNode->pRight ) { // Check its neighbors for space if( pNode->pLeft ) { // Try to put it in the neighbor GlyphBinNode *pNewNode = insertIntoBin( pNode->pLeft, cachedGlyph ); if( pNewNode ) return pNewNode; } if( pNode->pRight ) { // Try to put it in the neighbor GlyphBinNode *pNewNode = insertIntoBin( pNode->pRight, cachedGlyph ); if( pNewNode ) return pNewNode; } // No space in its neighbors return NULL; } boxWidth = cachedGlyph.width + cachedGlyph.padding.left + cachedGlyph.padding.right; boxHeight = cachedGlyph.rows + cachedGlyph.padding.top + cachedGlyph.padding.bottom; // If it has no children, check if the glyph fits here if( boxWidth > pNode->width || boxHeight > pNode->height ) return NULL; // Split the node along the short axis and // insert the glyph newWidth = pNode->width - boxWidth; newHeight = pNode->height - boxHeight; // Create new children pNode->pLeft = new GlyphBinNode(); pNode->pRight = new GlyphBinNode(); m_glyphBinNodes.push_back( pNode->pLeft ); m_glyphBinNodes.push_back( pNode->pRight ); if( newWidth <= newHeight ) { pNode->pLeft->x = pNode->x + boxWidth; pNode->pLeft->y = pNode->y; pNode->pLeft->width = newWidth; pNode->pLeft->height = boxHeight; pNode->pRight->x = pNode->x; pNode->pRight->y = pNode->y + boxHeight; pNode->pRight->width = pNode->width; pNode->pRight->height = newHeight; } else { pNode->pLeft->x = pNode->x; pNode->pLeft->y = pNode->y + boxHeight; pNode->pLeft->width = boxWidth; pNode->pLeft->height = newHeight; pNode->pRight->x = pNode->x + boxWidth; pNode->pRight->y = pNode->y; pNode->pRight->width = newWidth; pNode->pRight->height = pNode->height; } // Shrink the node pNode->width = boxWidth; pNode->height = boxHeight; pNode->glyph = cachedGlyph; return pNode; } CTexture2D* CFont::getFontMap() { return m_pFontMap; } GlyphData* CFont::getGlyph( wchar_t character ) { auto it = m_glyphs.find( character ); if( it != m_glyphs.end() ) return &(*it).second; else { PrintError( L"Character %c not found in font name %s\n", character, m_fontFileName.c_str() ); return 0; } } int CFont::getPixelKerning( wchar_t leftGlyph, wchar_t rightGlyph ) { FT_UInt leftGlyphIndex, rightGlyphIndex; FT_Error ftError; FT_Vector kerningVector; if( !m_cacheFace ) return 0; // Get the glyph index leftGlyphIndex = FT_Get_Char_Index( m_cacheFace, leftGlyph ); if( !leftGlyphIndex ) { PrintWarn( L"Missing character \'%c\' in font \'%s\'\n", leftGlyph, m_fontFileName.c_str() ); return 0; } rightGlyphIndex = FT_Get_Char_Index( m_cacheFace, rightGlyph ); if( !rightGlyphIndex ) { PrintWarn( L"Missing character \'%c\' in font \'%s\'\n", rightGlyph, m_fontFileName.c_str() ); return 0; } ftError = FT_Get_Kerning( m_cacheFace, leftGlyphIndex, rightGlyphIndex, FT_KERNING_DEFAULT, &kerningVector ); if( ftError != 0 ) { PrintWarn( L"Failed to extract kerning in font \'%s\' (code: %d, '%hs')\n", m_fontFileName.c_str(), ftError, GetFreetypeError( ftError ) ); return 0; } return (kerningVector.x / FT_HRES); }
31.38961
167
0.698552
timothyvolpe
f9eeabce49ab9c1200e923c75d74452c7d24fdff
562
cpp
C++
src/py/wrapper/wrapper_78fa594811935c2ea4b4905d733f141f.cpp
StatisKit/Core
79d8ec07c203eb7973a6cf482852ddb2e8e1e93e
[ "Apache-2.0" ]
null
null
null
src/py/wrapper/wrapper_78fa594811935c2ea4b4905d733f141f.cpp
StatisKit/Core
79d8ec07c203eb7973a6cf482852ddb2e8e1e93e
[ "Apache-2.0" ]
7
2018-03-20T14:23:16.000Z
2019-04-09T11:57:57.000Z
src/py/wrapper/wrapper_78fa594811935c2ea4b4905d733f141f.cpp
StatisKit/Core
79d8ec07c203eb7973a6cf482852ddb2e8e1e93e
[ "Apache-2.0" ]
7
2017-04-28T07:41:01.000Z
2021-03-15T18:17:20.000Z
#include "_core.h" void wrapper_78fa594811935c2ea4b4905d733f141f(pybind11::module& module) { pybind11::enum_< enum ::statiskit::size_error::size_type > enum_78fa594811935c2ea4b4905d733f141f(module, "size_type"); enum_78fa594811935c2ea4b4905d733f141f.value("INFERIOR", ::statiskit::size_error::inferior); enum_78fa594811935c2ea4b4905d733f141f.value("EQUAL", ::statiskit::size_error::equal); enum_78fa594811935c2ea4b4905d733f141f.value("SUPERIOR", ::statiskit::size_error::superior); enum_78fa594811935c2ea4b4905d733f141f.export_values(); }
43.230769
122
0.798932
StatisKit
f9f1c65e9f04a5566b5cf6c7aeb49613bea6509d
55,896
cpp
C++
tests/test.cpp
OpenJij/cimod
14728142d5fca3f1dac4d63a9c6fcd17e82bce9f
[ "Apache-2.0" ]
8
2020-03-24T09:29:21.000Z
2022-01-12T17:06:20.000Z
tests/test.cpp
OpenJij/cimod
14728142d5fca3f1dac4d63a9c6fcd17e82bce9f
[ "Apache-2.0" ]
18
2020-04-16T01:31:25.000Z
2022-03-08T03:00:01.000Z
tests/test.cpp
OpenJij/cimod
14728142d5fca3f1dac4d63a9c6fcd17e82bce9f
[ "Apache-2.0" ]
3
2020-05-23T16:53:08.000Z
2021-07-01T08:51:28.000Z
#include "gtest/gtest.h" #include "../src/binary_quadratic_model.hpp" #include "../src/binary_polynomial_model.hpp" #include "../src/binary_quadratic_model_dict.hpp" #include "test_bqm.hpp" #include <nlohmann/json.hpp> #include <unordered_map> #include <utility> #include <vector> #include <cstdint> #include <string> #include <iostream> #include <tuple> using json = nlohmann::json; using namespace cimod; namespace { TEST(DenseConstructionTest, Construction) { BQMTester<Dense>::test_DenseConstructionTest_Construction(); BQMTester<Sparse>::test_DenseConstructionTest_Construction(); BQMTester<Dict>::test_DenseConstructionTest_Construction(); } TEST(DenseConstructionTest, ConstructionString) { BQMTester<Dense>::test_DenseConstructionTest_ConstructionString(); BQMTester<Sparse>::test_DenseConstructionTest_ConstructionString(); BQMTester<Dict>::test_DenseConstructionTest_ConstructionString(); } TEST(DenseConstructionTest, ConstructionMatrix) { BQMTester<Dense>::test_DenseConstructionTest_ConstructionMatrix(); BQMTester<Sparse>::test_DenseConstructionTest_ConstructionMatrix(); } TEST(DenseConstructionTest, ConstructionMatrix2) { BQMTester<Dense>::test_DenseConstructionTest_ConstructionMatrix2(); BQMTester<Sparse>::test_DenseConstructionTest_ConstructionMatrix2(); } TEST(DenseBQMFunctionTest, add_variable) { BQMTester<Dense>::test_DenseBQMFunctionTest_add_variable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_add_variable(); BQMTester<Dict>::test_DenseBQMFunctionTest_add_variable(); } TEST(DenseBQMFunctionTest, add_variables_from) { BQMTester<Dense>::test_DenseBQMFunctionTest_add_variables_from(); BQMTester<Sparse>::test_DenseBQMFunctionTest_add_variables_from(); BQMTester<Dict>::test_DenseBQMFunctionTest_add_variables_from(); } TEST(DenseBQMFunctionTest, add_interaction) { BQMTester<Dense>::test_DenseBQMFunctionTest_add_interaction(); BQMTester<Sparse>::test_DenseBQMFunctionTest_add_interaction(); BQMTester<Dict>::test_DenseBQMFunctionTest_add_interaction(); } TEST(DenseBQMFunctionTest, add_interactions_from) { BQMTester<Dense>::test_DenseBQMFunctionTest_add_interactions_from(); BQMTester<Sparse>::test_DenseBQMFunctionTest_add_interactions_from(); BQMTester<Dict>::test_DenseBQMFunctionTest_add_interactions_from(); } TEST(DenseBQMFunctionTest, add_offset) { BQMTester<Dense>::test_DenseBQMFunctionTest_add_offset(); BQMTester<Sparse>::test_DenseBQMFunctionTest_add_offset(); BQMTester<Dict>::test_DenseBQMFunctionTest_add_offset(); } TEST(DenseBQMFunctionTest, energy) { BQMTester<Dense>::test_DenseBQMFunctionTest_energy(); BQMTester<Sparse>::test_DenseBQMFunctionTest_energy(); BQMTester<Dict>::test_DenseBQMFunctionTest_energy(); } TEST(DenseBQMFunctionTest, energies) { BQMTester<Dense>::test_DenseBQMFunctionTest_energies(); BQMTester<Sparse>::test_DenseBQMFunctionTest_energies(); BQMTester<Dict>::test_DenseBQMFunctionTest_energies(); } TEST(DenseBQMFunctionTest, empty) { BQMTester<Dense>::test_DenseBQMFunctionTest_empty(); BQMTester<Sparse>::test_DenseBQMFunctionTest_empty(); BQMTester<Dict>::test_DenseBQMFunctionTest_empty(); } TEST(DenseBQMFunctionTest, to_qubo) { BQMTester<Dense>::test_DenseBQMFunctionTest_to_qubo(); BQMTester<Sparse>::test_DenseBQMFunctionTest_to_qubo(); BQMTester<Dict>::test_DenseBQMFunctionTest_to_qubo(); } TEST(DenseBQMFunctionTest, to_ising) { BQMTester<Dense>::test_DenseBQMFunctionTest_to_ising(); BQMTester<Sparse>::test_DenseBQMFunctionTest_to_ising(); BQMTester<Dict>::test_DenseBQMFunctionTest_to_ising(); } TEST(DenseBQMFunctionTest, from_qubo) { BQMTester<Dense>::test_DenseBQMFunctionTest_from_qubo(); BQMTester<Sparse>::test_DenseBQMFunctionTest_from_qubo(); BQMTester<Dict>::test_DenseBQMFunctionTest_from_qubo(); } TEST(DenseBQMFunctionTest, from_ising) { BQMTester<Dense>::test_DenseBQMFunctionTest_from_ising(); BQMTester<Sparse>::test_DenseBQMFunctionTest_from_ising(); BQMTester<Dict>::test_DenseBQMFunctionTest_from_ising(); } TEST(DenseBQMFunctionTest, remove_variable) { BQMTester<Dense>::test_DenseBQMFunctionTest_remove_variable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_remove_variable(); BQMTester<Dict>::test_DenseBQMFunctionTest_remove_variable(); } TEST(DenseBQMFunctionTest, remove_variables_from) { BQMTester<Dense>::test_DenseBQMFunctionTest_remove_variables_from(); BQMTester<Sparse>::test_DenseBQMFunctionTest_remove_variables_from(); BQMTester<Dict>::test_DenseBQMFunctionTest_remove_variables_from(); } TEST(DenseBQMFunctionTest, remove_interaction) { BQMTester<Dense>::test_DenseBQMFunctionTest_remove_interaction(); BQMTester<Sparse>::test_DenseBQMFunctionTest_remove_interaction(); BQMTester<Dict>::test_DenseBQMFunctionTest_remove_interaction(); } TEST(DenseBQMFunctionTest, scale) { BQMTester<Dense>::test_DenseBQMFunctionTest_scale(); BQMTester<Sparse>::test_DenseBQMFunctionTest_scale(); BQMTester<Dict>::test_DenseBQMFunctionTest_scale(); } TEST(DenseBQMFunctionTest, normalize) { BQMTester<Dense>::test_DenseBQMFunctionTest_normalize(); BQMTester<Sparse>::test_DenseBQMFunctionTest_normalize(); BQMTester<Dict>::test_DenseBQMFunctionTest_normalize(); } TEST(DenseBQMFunctionTest, fix_variable) { BQMTester<Dense>::test_DenseBQMFunctionTest_fix_variable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_fix_variable(); BQMTester<Dict>::test_DenseBQMFunctionTest_fix_variable(); } TEST(DenseBQMFunctionTest, flip_variable) { BQMTester<Dense>::test_DenseBQMFunctionTest_flip_variable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_flip_variable(); BQMTester<Dict>::test_DenseBQMFunctionTest_flip_variable(); } TEST(DenseBQMFunctionTest, flip_variable_binary) { BQMTester<Dense>::test_DenseBQMFunctionTest_flip_variable_binary(); BQMTester<Sparse>::test_DenseBQMFunctionTest_flip_variable_binary(); BQMTester<Dict>::test_DenseBQMFunctionTest_flip_variable_binary(); } TEST(DenseBQMFunctionTest, change_vartype) { BQMTester<Dense>::test_DenseBQMFunctionTest_change_vartype(); BQMTester<Sparse>::test_DenseBQMFunctionTest_change_vartype(); BQMTester<Dict>::test_DenseBQMFunctionTest_change_vartype(); } TEST(DenseBQMFunctionTest, to_serializable) { BQMTester<Dense>::test_DenseBQMFunctionTest_to_serializable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_to_serializable(); BQMTester<Dict>::test_DenseBQMFunctionTest_to_serializable(); } TEST(DenseBQMFunctionTest, from_serializable) { BQMTester<Dense>::test_DenseBQMFunctionTest_from_serializable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_from_serializable(); BQMTester<Dict>::test_DenseBQMFunctionTest_from_serializable(); } //google test for binary polynomial model bool EXPECT_CONTAIN(double val, const PolynomialValueList<double> &poly_value) { int count = 0; for (const auto &it: poly_value) { if (std::abs(it - val) < 0.000000000000001/*std::pow(10, -15)*/) { count++; } } if (count >= 1) { return true; } else { return false; } } void StateTestBPMUINT(const BinaryPolynomialModel<uint32_t, double> &bpm) { EXPECT_EQ(bpm.GetNumVariables(), 4); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 0.0); EXPECT_EQ(bpm.GetNumInteractions(), 15); EXPECT_EQ(bpm.GetDegree(), 4); //Polynomial EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2} ), 2.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({3} ), 3.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({4} ), 4.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 2} ), 12.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 3} ), 13.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 4} ), 14.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 3} ), 23.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 4} ), 24.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({3, 4} ), 34.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 2, 3} ), 123.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 2, 4} ), 124.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 3, 4} ), 134.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 3, 4} ), 234.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 2, 3, 4}), 1234.0); //Polynomial duplicate key if (bpm.GetVartype() == cimod::Vartype::SPIN) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 1, 1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 1, 1, 2} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 3, 3, 3} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({3, 2, 3, 2, 3, 2}), 23.0); } else if (bpm.GetVartype() == cimod::Vartype::BINARY) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 1, 1, 1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 1, 1, 2, 2} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 3, 3, 3, 1} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({3, 2, 3, 2, 3, 2, 2}), 23.0); } //variables_to_integers EXPECT_EQ(bpm.GetVariablesToIntegers(1), 0); EXPECT_EQ(bpm.GetVariablesToIntegers(2), 1); EXPECT_EQ(bpm.GetVariablesToIntegers(3), 2); EXPECT_EQ(bpm.GetVariablesToIntegers(4), 3); //Polynomial Key EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{3, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 2, 3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 2, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 3, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 3, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 2, 3, 4}), 1); //Polynomial Val EXPECT_TRUE(EXPECT_CONTAIN(1.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(2.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(3.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(4.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(12.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(13.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(14.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(23.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(24.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(34.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(123.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(124.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(134.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(234.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(1234.0, bpm.GetValueList())); //sorted_variables auto sorted_variables = bpm.GetSortedVariables(); EXPECT_EQ(sorted_variables[0], 1); EXPECT_EQ(sorted_variables[1], 2); EXPECT_EQ(sorted_variables[2], 3); EXPECT_EQ(sorted_variables[3], 4); //variables EXPECT_EQ(bpm.GetVariables().count(1), 1); EXPECT_EQ(bpm.GetVariables().count(2), 1); EXPECT_EQ(bpm.GetVariables().count(3), 1); EXPECT_EQ(bpm.GetVariables().count(4), 1); } void StateTestBPMINT(const BinaryPolynomialModel<int32_t, double> &bpm) { EXPECT_EQ(bpm.GetNumVariables(), 4); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 0.0); EXPECT_EQ(bpm.GetNumInteractions(), 15); EXPECT_EQ(bpm.GetDegree(), 4); //Polynomial EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-2} ), 2.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3} ), 3.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4} ), 4.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-2, -1} ), 12.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3, -1} ), 13.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -1} ), 14.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3, -2} ), 23.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -2} ), 24.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -3} ), 34.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3, -2, -1} ), 123.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -2, -1} ), 124.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -3, -1} ), 134.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -3, -2} ), 234.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -3, -2, -1}), 1234.0); //Polynomial duplicate key if (bpm.GetVartype() == cimod::Vartype::SPIN) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -1, -1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -1, -1, -2} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -3, -3, -3} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3, -2, -3, -2, -3, -2}), 23.0); } else if (bpm.GetVartype() == cimod::Vartype::BINARY) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -1, -1, -1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -1, -1, -2, -2} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -3, -3, -3, -1} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3, -2, -3, -2, -3, -2, -2}), 23.0); } //variables_to_integers EXPECT_EQ(bpm.GetVariablesToIntegers(-4), 0); EXPECT_EQ(bpm.GetVariablesToIntegers(-3), 1); EXPECT_EQ(bpm.GetVariablesToIntegers(-2), 2); EXPECT_EQ(bpm.GetVariablesToIntegers(-1), 3); //Polynomial Key EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-2, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-3, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-3, -2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-3, -2, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -2, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -3, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -3, -2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -3, -2, -1}), 1); //Polynomial Val EXPECT_TRUE(EXPECT_CONTAIN(1.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(2.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(3.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(4.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(12.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(13.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(14.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(23.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(24.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(34.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(123.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(124.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(134.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(234.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(1234.0, bpm.GetValueList())); //sorted_variables auto sorted_variables = bpm.GetSortedVariables(); EXPECT_EQ(sorted_variables[0], -4); EXPECT_EQ(sorted_variables[1], -3); EXPECT_EQ(sorted_variables[2], -2); EXPECT_EQ(sorted_variables[3], -1); //variables EXPECT_EQ(bpm.GetVariables().count(-1), 1); EXPECT_EQ(bpm.GetVariables().count(-2), 1); EXPECT_EQ(bpm.GetVariables().count(-3), 1); EXPECT_EQ(bpm.GetVariables().count(-4), 1); } void StateTestBPMString(const BinaryPolynomialModel<std::string, double> &bpm) { EXPECT_EQ(bpm.GetNumVariables(), 4); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 0.0); EXPECT_EQ(bpm.GetNumInteractions(), 15); EXPECT_EQ(bpm.GetDegree(), 4); //Polynomial EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a"} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"b"} ), 2.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"c"} ), 3.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"d"} ), 4.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "b"} ), 12.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "c"} ), 13.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "d"} ), 14.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"b", "c"} ), 23.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"b", "d"} ), 24.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"c", "d"} ), 34.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "b", "c"} ), 123.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "b", "d"} ), 124.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "c", "d"} ), 134.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"b", "c", "d"} ), 234.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "b", "c", "d"}), 1234.0); //Polynomial duplicate key if (bpm.GetVartype() == cimod::Vartype::SPIN) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "a", "a"} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "a", "a", "b"} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "c", "c", "c"} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"c", "b", "c", "b", "c", "b"}), 23.0); } else if (bpm.GetVartype() == cimod::Vartype::BINARY) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "a", "a", "a"} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "a", "a", "b", "b"} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "c", "c", "c", "a"} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"c", "b", "c", "b", "c", "b", "b"}), 23.0); } //variables_to_integers EXPECT_EQ(bpm.GetVariablesToIntegers("a"), 0); EXPECT_EQ(bpm.GetVariablesToIntegers("b"), 1); EXPECT_EQ(bpm.GetVariablesToIntegers("c"), 2); EXPECT_EQ(bpm.GetVariablesToIntegers("d"), 3); //Polynomial Key EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"b"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"c"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "b"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "c"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"b", "c"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"b", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"c", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "b", "c"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "b", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "c", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"b", "c", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "b", "c", "d"}), 1); //Polynomial Value EXPECT_TRUE(EXPECT_CONTAIN(1.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(2.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(3.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(4.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(12.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(13.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(14.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(23.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(24.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(34.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(123.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(124.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(134.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(234.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(1234.0, bpm.GetValueList())); //sorted_variables auto sorted_variables = bpm.GetSortedVariables(); EXPECT_EQ(sorted_variables[0], "a"); EXPECT_EQ(sorted_variables[1], "b"); EXPECT_EQ(sorted_variables[2], "c"); EXPECT_EQ(sorted_variables[3], "d"); //variables EXPECT_EQ(bpm.GetVariables().count("a"), 1); EXPECT_EQ(bpm.GetVariables().count("b"), 1); EXPECT_EQ(bpm.GetVariables().count("c"), 1); EXPECT_EQ(bpm.GetVariables().count("d"), 1); } template<typename IndexType> void StateTestBPMEmpty(const BinaryPolynomialModel<IndexType, double> &bpm) { EXPECT_EQ(bpm.GetNumVariables(), 0); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 0.0); EXPECT_EQ(bpm.GetNumInteractions(), 0); EXPECT_EQ(bpm.GetDegree(), 0); //Polynomial EXPECT_EQ(bpm.GetPolynomial().size(), 0); //variables_to_integers EXPECT_EQ(bpm.GetVariablesToIntegers().size(), 0); //Polynomial Key EXPECT_EQ(bpm.GetKeyList().size(), 0); //Polynomial Val EXPECT_EQ(bpm.GetValueList().size(), 0); //sorted_variables auto sorted_variables = bpm.GetSortedVariables(); EXPECT_EQ(sorted_variables.size(), 0); //variables EXPECT_EQ(bpm.GetVariables().size(), 0); } Polynomial<uint32_t, double> GeneratePolynomialUINT() { Polynomial<uint32_t, double> polynomial { //linear biases {{1}, 1.0}, {{2}, 2.0}, {{3}, 3.0}, {{4}, 4.0}, //quadratic biases {{1, 2}, 12.0}, {{1, 3}, 13.0}, {{1, 4}, 14.0}, {{2, 3}, 23.0}, {{2, 4}, 24.0}, {{3, 4}, 34.0}, //polynomial biases {{1, 2, 3}, 123.0}, {{1, 2, 4}, 124.0}, {{1, 3, 4}, 134.0}, {{2, 3, 4}, 234.0}, {{1, 2, 3, 4}, 1234.0} }; return polynomial; } Polynomial<int32_t, double> GeneratePolynomialINT() { Polynomial<int32_t, double> polynomial { //linear biases {{-1}, 1.0}, {{-2}, 2.0}, {{-3}, 3.0}, {{-4}, 4.0}, //quadratic biases {{-1, -2}, 12.0}, {{-1, -3}, 13.0}, {{-1, -4}, 14.0}, {{-2, -3}, 23.0}, {{-2, -4}, 24.0}, {{-3, -4}, 34.0}, //polynomial biases {{-1, -2, -3}, 123.0}, {{-1, -2, -4}, 124.0}, {{-1, -3, -4}, 134.0}, {{-2, -3, -4}, 234.0}, {{-1, -2, -3, -4}, 1234.0} }; return polynomial; } Polynomial<std::string, double> GeneratePolynomialString() { Polynomial<std::string, double> polynomial { //linear biases {{"a"}, 1.0}, {{"b"}, 2.0}, {{"c"}, 3.0}, {{"d"}, 4.0}, //quadratic biases {{"a", "b"}, 12.0}, {{"a", "c"}, 13.0}, {{"a", "d"}, 14.0}, {{"b", "c"}, 23.0}, {{"b", "d"}, 24.0}, {{"c", "d"}, 34.0}, //polynomial biases {{"a", "b", "c"}, 123.0}, {{"a", "b", "d"}, 124.0}, {{"a", "c", "d"}, 134.0}, {{"b", "c", "d"}, 234.0}, {{"a", "b", "c", "d"}, 1234.0} }; return polynomial; } TEST(ConstructionBPM, PolyMapUINT) { BinaryPolynomialModel<uint32_t, double> bpm(GeneratePolynomialUINT(), Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(ConstructionBPM, PolyMapINT) { BinaryPolynomialModel<int32_t, double> bpm(GeneratePolynomialINT(), Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(ConstructionBPM, PolyMapString) { BinaryPolynomialModel<std::string, double> bpm(GeneratePolynomialString(), Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(ConstructionBPM, PolyKeyValueUINT) { PolynomialKeyList<uint32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialUINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } BinaryPolynomialModel<uint32_t, double> bpm(poly_key, poly_value, Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(ConstructionBPM, PolyKeyValueINT) { PolynomialKeyList<int32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } BinaryPolynomialModel<int32_t, double> bpm(poly_key, poly_value, Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(ConstructionBPM, PolyKeyValueStrign) { PolynomialKeyList<std::string> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialString()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } BinaryPolynomialModel<std::string, double> bpm(poly_key, poly_value, Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(AddInteractionBPM, basic) { Polynomial<uint32_t, double> polynomial { {{1}, 1.0}, {{2}, 2.0}, {{1, 2}, 12.0}, {{1, 2, 3}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.AddInteraction({3}, 3.0); bpm.AddInteraction({4}, 4.0); bpm.AddInteraction({1, 3}, 13.0); bpm.AddInteraction({1, 4}, 14.0); bpm.AddInteraction({2, 3}, 23.0); bpm.AddInteraction({2, 4}, 24.0); bpm.AddInteraction({3, 4}, 34.0); bpm.AddInteraction({1, 2, 4}, 124.0); bpm.AddInteraction({1, 3, 4}, 134.0); bpm.AddInteraction({2, 3, 4}, 234.0); bpm.AddInteraction({1, 2, 3, 4}, 1234.0); StateTestBPMUINT(bpm); } TEST(AddInteractionBPM, self_loop_SPIN) { Polynomial<uint32_t, double> polynomial { {{1}, 1.0}, {{2}, 2.0}, {{1, 2}, 12.0}, {{1, 2, 3}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.AddInteraction({3, 3, 3}, 3.0); bpm.AddInteraction({4, 4, 4, 4, 4}, 4.0); bpm.AddInteraction({1, 3, 1, 3, 3, 1}, 13.0); bpm.AddInteraction({1, 1, 1, 4, 4, 4}, 14.0); bpm.AddInteraction({3, 3, 3, 2, 2, 2}, 23.0); bpm.AddInteraction({2, 4}, 24.0); bpm.AddInteraction({3, 4}, 34.0); bpm.AddInteraction({1, 2, 4}, 124.0); bpm.AddInteraction({1, 3, 4}, 134.0); bpm.AddInteraction({2, 3, 4, 2, 4, 3, 3, 4, 2}, 234.0); bpm.AddInteraction({1, 2, 3, 4}, 1234.0); StateTestBPMUINT(bpm); } TEST(AddInteractionBPM, self_loop_BINARY) { Polynomial<uint32_t, double> polynomial { {{1}, 1.0}, {{2}, 2.0}, {{1, 2}, 12.0}, {{1, 2, 3}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::BINARY); bpm.AddInteraction({3, 3}, 3.0); bpm.AddInteraction({4, 4, 4}, 4.0); bpm.AddInteraction({1, 1, 3}, 13.0); bpm.AddInteraction({1, 4, 4, 4}, 14.0); bpm.AddInteraction({3, 3, 2}, 23.0); bpm.AddInteraction({2, 4}, 24.0); bpm.AddInteraction({3, 4}, 34.0); bpm.AddInteraction({1, 2, 4}, 124.0); bpm.AddInteraction({1, 3, 4}, 134.0); bpm.AddInteraction({2, 3, 4}, 234.0); bpm.AddInteraction({1, 2, 3, 3, 4, 1}, 1234.0); StateTestBPMUINT(bpm); } TEST(AddInteractionBPM, duplicate_value_1) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); for (auto &&it: polynomial) { it.second /= 2; } BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); for (const auto &it: polynomial) { bpm.AddInteraction(it.first, it.second); }; StateTestBPMUINT(bpm); } TEST(AddInteractionBPM, duplicate_value_2) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); for (const auto &it: polynomial) { bpm.AddInteraction(it.first, -it.second); }; StateTestBPMEmpty(bpm); } TEST(AddInteractionsFromBPM, PolyMap) { BinaryPolynomialModel<uint32_t, double> bpm({}, Vartype::SPIN); bpm.AddInteractionsFrom(GeneratePolynomialUINT()); StateTestBPMUINT(bpm); } TEST(AddInteractionsFromBPM, PolyKeyValue) { PolynomialKeyList<uint32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialUINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } BinaryPolynomialModel<uint32_t, double> bpm({}, Vartype::SPIN); bpm.AddInteractionsFrom(poly_key, poly_value); StateTestBPMUINT(bpm); } TEST(AddOffsetBPM, basic) { Polynomial<uint32_t, double> polynomial; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.AddOffset(3.0); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 3.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}) , 3.0); bpm.AddOffset(3.0); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 6.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}) , 6.0); bpm.AddOffset(-6.0); StateTestBPMEmpty(bpm); } TEST(RemoveInteractionBPM, basic) { Polynomial<uint32_t, double> polynomial = { //linear biases {{1}, 1.0}, {{2}, 2.0}, {{3}, 3.0}, {{4}, 4.0}, //quadratic biases {{1, 2}, 12.0}, {{1, 3}, 13.0}, {{1, 4}, 14.0}, {{2, 3}, 23.0}, {{2, 4}, 24.0}, {{3, 4}, 34.0}, //To be removed {{11, 12, 14}, -1.0}, {{7}, -2.0}, {{2, 11}, -9.0}, {{}, -3}, //polynomial biases {{1, 2, 3}, 123.0}, {{1, 2, 4}, 124.0}, {{1, 3, 4}, 134.0}, {{2, 3, 4}, 234.0}, {{1, 2, 3, 4}, 1234.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({} ), -3.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({7} ), -2.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 11} ), -9.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({11, 12, 14}), -1.0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{7} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 11} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{11, 12, 14}), 1); EXPECT_TRUE(EXPECT_CONTAIN(-3.0, bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(-2.0, bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(-9.0, bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(-1.0, bpm.GetValueList())); bpm.RemoveInteraction({} ); bpm.RemoveInteraction({7} ); bpm.RemoveInteraction({2, 11} ); bpm.RemoveInteraction({11, 12, 14}); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({7} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 11} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({11, 12, 14}), 0.0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{7} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 11} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{11, 12, 14}), 0); EXPECT_FALSE(EXPECT_CONTAIN(-3.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-2.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-9.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-1.0, bpm.GetValueList())); StateTestBPMUINT(bpm); } TEST(RemoveInteractionBPM, remove_all) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); for (const auto &it: polynomial) { bpm.RemoveInteraction(it.first); }; StateTestBPMEmpty(bpm); } TEST(RemoveInteractionBPM, self_loop_SPIN) { Polynomial<uint32_t, double> polynomial { {{1}, 1.0}, {{2}, 2.0}, {{1, 2}, 12.0}, {{1, 2, 3}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.RemoveInteraction({1, 1, 1}); bpm.RemoveInteraction({2, 2, 2, 2, 2}); bpm.RemoveInteraction({1, 1, 1, 2, 2, 2, 2, 2}); bpm.RemoveInteraction({1, 1, 1, 2, 2, 2, 3, 3, 3}); StateTestBPMEmpty(bpm); } TEST(RemoveInteractionBPM, self_loop_BINARY) { Polynomial<uint32_t, double> polynomial { {{1}, 1.0}, {{2}, 2.0}, {{1, 2}, 12.0}, {{1, 2, 3}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::BINARY); bpm.RemoveInteraction({1, 1}); bpm.RemoveInteraction({2, 2, 2, 2}); bpm.RemoveInteraction({1, 1, 1, 2, 2, 2}); bpm.RemoveInteraction({1, 1, 2, 2, 2, 3}); StateTestBPMEmpty(bpm); } TEST(RemoveInteractionsFromBPM, basic) { Polynomial<uint32_t, double> polynomial { //linear biases {{1}, 1.0}, {{2}, 2.0}, {{3}, 3.0}, {{4}, 4.0}, //quadratic biases {{1, 2}, 12.0}, {{1, 3}, 13.0}, {{1, 4}, 14.0}, {{2, 3}, 23.0}, {{2, 4}, 24.0}, {{3, 4}, 34.0}, //To be removed {{11, 12, 14}, -1.0}, {{7}, -2.0}, {{2, 11}, -9.0}, {{}, -3}, //polynomial biases {{1, 2, 3}, 123.0}, {{1, 2, 4}, 124.0}, {{1, 3, 4}, 134.0}, {{2, 3, 4}, 234.0}, {{1, 2, 3, 4}, 1234.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); PolynomialKeyList<uint32_t> removed_key_list = { {11, 14, 12}, {7}, {11, 2}, {} }; bpm.RemoveInteractionsFrom(removed_key_list); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({7} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 11} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({11, 12, 14}), 0.0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{7} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 11} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{11, 12, 14}), 0); EXPECT_FALSE(EXPECT_CONTAIN(-3.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-2.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-9.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-1.0, bpm.GetValueList())); StateTestBPMUINT(bpm); } TEST(RemoveInteractionsFromBPM, remove_all) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); PolynomialKeyList<uint32_t> removed_key_list; for (const auto &it: polynomial) { removed_key_list.push_back(it.first); } bpm.RemoveInteractionsFrom(removed_key_list); StateTestBPMEmpty(bpm); } TEST(RemoveOffsetBPM, basic) { Polynomial<uint32_t, double> polynomial = { //linear biases {{1}, 1.0}, {{2}, 2.0}, {{3}, 3.0}, {{4}, 4.0}, //quadratic biases {{1, 2}, 12.0}, {{1, 3}, 13.0}, {{1, 4}, 14.0}, {{2, 3}, 23.0}, {{2, 4}, 24.0}, {{3, 4}, 34.0}, //To be removed {{}, 100}, //polynomial biases {{1, 2, 3}, 123.0}, {{1, 2, 4}, 124.0}, {{1, 3, 4}, 134.0}, {{2, 3, 4}, 234.0}, {{1, 2, 3, 4}, 1234.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.RemoveOffset(); StateTestBPMUINT(bpm); } TEST(EnergyBPM, SPIN) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); Sample<uint32_t> sample_variables_spin_1{{0, +1}, {1, +1}, {2, +1}}; Sample<uint32_t> sample_variables_spin_2{{0, +1}, {1, -1}, {2, +1}}; Sample<uint32_t> sample_variables_spin_3{{0, -1}, {1, -1}, {2, -1}}; EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_spin_1), +171.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_spin_2), -123.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_spin_3), -81.0 ); std::vector<int32_t> sample_vec_variables_spin_1{+1, +1, +1}; std::vector<int32_t> sample_vec_variables_spin_2{+1, -1, +1}; std::vector<int32_t> sample_vec_variables_spin_3{-1, -1, -1}; EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_spin_1), +171.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_spin_2), -123.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_spin_3), -81.0 ); } TEST(EnergyBPM, BINARY) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::BINARY); Sample<uint32_t> sample_variables_binary_1{{0, +1}, {1, +1}, {2, +1}}; Sample<uint32_t> sample_variables_binary_2{{0, +1}, {1, +0}, {2, +1}}; Sample<uint32_t> sample_variables_binary_3{{0, +0}, {1, +0}, {2, +0}}; EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_1), +171.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_2), +24.0 ); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_3), 0.0 ); std::vector<int32_t> sample_vec_variables_binary_1{+1, +1, +1}; std::vector<int32_t> sample_vec_variables_binary_2{+1, +0, +1}; std::vector<int32_t> sample_vec_variables_binary_3{+0, +0, +0}; EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_binary_1), +171.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_binary_2), +24.0 ); EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_binary_3), 0.0 ); } TEST(EnergiesBPM, SPIN) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); std::vector<Sample<uint32_t>> sample_variables_spin { {{0, +1}, {1, +1}, {2, +1}}, {{0, +1}, {1, -1}, {2, +1}}, {{0, -1}, {1, -1}, {2, -1}} }; std::vector<double> en_vec = bpm.Energies(sample_variables_spin); EXPECT_DOUBLE_EQ(en_vec[0], +171.0); EXPECT_DOUBLE_EQ(en_vec[1], -123.0); EXPECT_DOUBLE_EQ(en_vec[2], -81.0 ); std::vector<std::vector<int32_t>> sample_vec_variables_spin { {+1, +1, +1}, {+1, -1, +1}, {-1, -1, -1} }; std::vector<double> en_vec_vec = bpm.Energies(sample_vec_variables_spin); EXPECT_DOUBLE_EQ(en_vec_vec[0], +171.0); EXPECT_DOUBLE_EQ(en_vec_vec[1], -123.0); EXPECT_DOUBLE_EQ(en_vec_vec[2], -81.0 ); } TEST(EnergiesBPM, BINARY) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); std::vector<Sample<uint32_t>> sample_variables_binary { {{0, +1}, {1, +1}, {2, +1}}, {{0, +1}, {1, +0}, {2, +1}}, {{0, +0}, {1, +0}, {2, +0}} }; std::vector<double> en_vec = bpm.Energies(sample_variables_binary); EXPECT_DOUBLE_EQ(en_vec[0], +171.0); EXPECT_DOUBLE_EQ(en_vec[1], +24.0 ); EXPECT_DOUBLE_EQ(en_vec[2], 0.0 ); std::vector<std::vector<int32_t>> sample_vec_variables_binary { {+1, +1, +1}, {+1, +0, +1}, {+0, +0, +0} }; std::vector<double> en_vec_vec = bpm.Energies(sample_vec_variables_binary); EXPECT_DOUBLE_EQ(en_vec_vec[0], +171.0); EXPECT_DOUBLE_EQ(en_vec_vec[1], +24.0 ); EXPECT_DOUBLE_EQ(en_vec_vec[2], 0.0 ); } TEST(ScaleBPM, all_scale) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); for (auto &&it: polynomial) { it.second *= 2; } BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.Scale(0.5); StateTestBPMUINT(bpm); } TEST(ScaleBPM, ignored_interaction) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); for (auto &&it: polynomial) { it.second *= 2; } BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.Scale(0.5, {{1,2}, {2, 4}, {1, 3, 4}}); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 2} ), 12.0*2 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 4} ), 24.0*2 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 3, 4}), 134.0*2); bpm.AddInteraction({1, 2} , -12.0); bpm.AddInteraction({2, 4} , -24.0); bpm.AddInteraction({1, 3, 4}, -134.0); StateTestBPMUINT(bpm); } TEST(ScaleBPM, ignored_offset) { Polynomial<uint32_t, double> polynomial { {{}, 100.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.Scale(0.5, {std::vector<uint32_t>{}}); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}), 100.0); bpm.Scale(0.5, {}, true); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}), 100.0); bpm.Scale(0.5, {{}}, true); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}), 100.0); bpm.Scale(0.5); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}), 50.0); } TEST(NormalizeBPM, all_normalize) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, +12} }; Vartype vartype = Vartype::SPIN; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, vartype); bpm.normalize({-1, 1}); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({1}), 1.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({2}), 2.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 1}), 11.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 2}), 22.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({1, 2}), 12.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 1, 2}), 12.0/22.0); } TEST(NormalizeBPM, ignored_interaction) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, +12} }; Vartype vartype = Vartype::SPIN; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, vartype); bpm.normalize({-1, 1}, {{0, 1, 2}}); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({1}), 1.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({2}), 2.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 1}), 11.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 2}), 22.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({1, 2}), 12.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 1, 2}), 12.0); } TEST(SerializableBPM, UINT) { BinaryPolynomialModel<uint32_t, double> bpm(GeneratePolynomialUINT(), Vartype::SPIN); BinaryPolynomialModel<uint32_t, double> bpm_from = BinaryPolynomialModel<uint32_t, double>::FromSerializable(bpm.ToSerializable()); StateTestBPMUINT(bpm_from); } TEST(SerializableBPM, INT) { BinaryPolynomialModel<int32_t, double> bpm(GeneratePolynomialINT(), Vartype::SPIN); BinaryPolynomialModel<int32_t, double> bpm_from = BinaryPolynomialModel<int32_t, double>::FromSerializable(bpm.ToSerializable()); StateTestBPMINT(bpm_from); } TEST(SerializableBPM, String) { BinaryPolynomialModel<std::string, double> bpm(GeneratePolynomialString(), Vartype::SPIN); BinaryPolynomialModel<std::string, double> bpm_from = BinaryPolynomialModel<std::string, double>::FromSerializable(bpm.ToSerializable()); StateTestBPMString(bpm_from); } TEST(SerializableBPM, StringToUINT) { BinaryPolynomialModel<std::string, double> bpm(GeneratePolynomialString(), Vartype::SPIN); auto obj = bpm.ToSerializable(); std::vector<std::size_t> string_to_num(obj["variables"].size()); std::iota(string_to_num.begin(), string_to_num.end(), 1); obj["variables"] = string_to_num; BinaryPolynomialModel<uint32_t, double> bpm_from = BinaryPolynomialModel<uint32_t, double>::FromSerializable(obj); StateTestBPMUINT(bpm_from); } TEST(SerializableBPM, StringToINT) { BinaryPolynomialModel<std::string, double> bpm(GeneratePolynomialString(), Vartype::SPIN); auto obj = bpm.ToSerializable(); std::vector<std::size_t> string_to_num(4); string_to_num[0] = -1; string_to_num[1] = -2; string_to_num[2] = -3; string_to_num[3] = -4; obj["variables"] = string_to_num; BinaryPolynomialModel<int32_t, double> bpm_from = BinaryPolynomialModel<int32_t, double>::FromSerializable(obj); StateTestBPMINT(bpm_from); } TEST(FromHubo, MapUINT) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHubo(GeneratePolynomialUINT()); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(FromHubo, MapINT) { auto bpm = BinaryPolynomialModel<int32_t, double>::FromHubo(GeneratePolynomialINT()); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(FromHubo, MapString) { auto bpm = BinaryPolynomialModel<std::string, double>::FromHubo(GeneratePolynomialString()); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(FromHubo, KeyValueUINT) { PolynomialKeyList<uint32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialUINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHubo(poly_key, poly_value); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(FromHubo, KeyValueINT) { PolynomialKeyList<int32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<int32_t, double>::FromHubo(poly_key, poly_value); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(FromHubo, KeyValueString) { PolynomialKeyList<std::string> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialString()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<std::string, double>::FromHubo(poly_key, poly_value); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(FromHising, MapUINT) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHising(GeneratePolynomialUINT()); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(FromHising, MapINT) { auto bpm = BinaryPolynomialModel<int32_t, double>::FromHising(GeneratePolynomialINT()); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(FromHising, MapString) { auto bpm = BinaryPolynomialModel<std::string, double>::FromHising(GeneratePolynomialString()); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(FromHising, KeyValueUINT) { PolynomialKeyList<uint32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialUINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHising(poly_key, poly_value); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(FromHising, KeyValueINT) { PolynomialKeyList<int32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<int32_t, double>::FromHising(poly_key, poly_value); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(FromHising, KeyValueString) { PolynomialKeyList<std::string> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialString()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<std::string, double>::FromHising(poly_key, poly_value); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(ClearBPM, basic) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, 123.0} }; Vartype vartype = Vartype::BINARY; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, vartype); bpm.Clear(); Sample<uint32_t> sample_variables_binary_1{{0, +1}, {1, +1}, {2, +1}}; Sample<uint32_t> sample_variables_binary_2{{0, +1}, {1, +0}, {2, +1}}; Sample<uint32_t> sample_variables_binary_3{{0, +0}, {1, +0}, {2, +0}}; EXPECT_TRUE(bpm.GetPolynomial().empty()); EXPECT_TRUE(bpm.GetVariables().empty()); EXPECT_EQ(bpm.GetVartype(), Vartype::BINARY); //Chech if the methods in Binary Polynomial Model work properly after executing empty() EXPECT_EQ(bpm.GetNumVariables(), 0); bpm.RemoveVariable(1); bpm.RemoveVariablesFrom(std::vector<uint32_t>{1,2,3,4,5}); bpm.RemoveInteraction(std::vector<uint32_t>{1,2}); bpm.RemoveInteractionsFrom(std::vector<std::vector<uint32_t>>{{1,2},{1,3},{1,4}}); bpm.Scale(1.0); bpm.normalize(); //energy EXPECT_THROW(bpm.Energy(sample_variables_binary_1), std::runtime_error); EXPECT_THROW(bpm.Energy(sample_variables_binary_2), std::runtime_error); EXPECT_THROW(bpm.Energy(sample_variables_binary_3), std::runtime_error); //Reset polynomial model bpm.AddInteraction({0, 1} , 11.0, Vartype::BINARY); bpm.AddInteraction({0, 2} , 22.0); bpm.AddInteraction({1, 2} , 12.0); bpm.AddInteraction({0, 1, 2}, 123.0); bpm.AddInteraction({0}, 0.0); bpm.AddInteraction({1}, 1.0); bpm.AddInteraction({2}, 2.0); //Check energy EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_1), +171.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_2), +24.0 ); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_3), 0.0 ); EXPECT_EQ(bpm.GetNumVariables(), 3); EXPECT_EQ(bpm.GetVariables().count(0), 1); EXPECT_EQ(bpm.GetVariables().count(1), 1); EXPECT_EQ(bpm.GetVariables().count(2), 1); for (const auto &it: bpm.GetPolynomial()) { EXPECT_DOUBLE_EQ(it.second, polynomial[it.first]); } EXPECT_EQ(bpm.GetVartype(), Vartype::BINARY); } TEST(VartypeBPM, SpinBinarySpin) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHising(GeneratePolynomialUINT()); auto bpm_binary = BinaryPolynomialModel<uint32_t, double>(bpm.ToHubo(), Vartype::BINARY); auto bpm_ising = BinaryPolynomialModel<uint32_t, double>(bpm_binary.ToHising(), Vartype::SPIN); StateTestBPMUINT(bpm_ising); } TEST(VartypeBPM, BinarySPINBinary) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHubo(GeneratePolynomialUINT()); auto bpm_ising = BinaryPolynomialModel<uint32_t, double>(bpm.ToHising(), Vartype::SPIN); auto bpm_bianry = BinaryPolynomialModel<uint32_t, double>(bpm_ising.ToHubo(), Vartype::BINARY); StateTestBPMUINT(bpm_bianry); } TEST(VartypeBPM, ChangeVartypeSpinBinarySpin) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHising(GeneratePolynomialUINT()); auto bpm_binary = bpm.ChangeVartype(Vartype::BINARY, true); auto bpm_ising = bpm_binary.ChangeVartype(Vartype::SPIN, true); StateTestBPMUINT(bpm_ising); bpm.ChangeVartype(Vartype::SPIN); StateTestBPMUINT(bpm); } TEST(VartypeBPM, ChangeVartypeBinarySPINBinary) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHubo(GeneratePolynomialUINT()); auto bpm_ising = bpm.ChangeVartype(Vartype::SPIN, true); auto bpm_binary = bpm_ising.ChangeVartype(Vartype::BINARY, true); StateTestBPMUINT(bpm_binary); bpm.ChangeVartype(Vartype::BINARY); StateTestBPMUINT(bpm); } }
36.390625
140
0.641799
OpenJij
f9f20c34c1708bb2980692eb5359f19248a79516
2,867
hxx
C++
main/extensions/source/propctrlr/propertycontrolextender.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/extensions/source/propctrlr/propertycontrolextender.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/extensions/source/propctrlr/propertycontrolextender.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ #ifndef EXTENSIONS_PROPERTYCONTROLEXTENDER_HXX #define EXTENSIONS_PROPERTYCONTROLEXTENDER_HXX /** === begin UNO includes === **/ #include <com/sun/star/awt/XKeyListener.hpp> #include <com/sun/star/inspection/XPropertyControl.hpp> /** === end UNO includes === **/ #include <cppuhelper/implbase1.hxx> #include <memory> //........................................................................ namespace pcr { //........................................................................ //==================================================================== //= PropertyControlExtender //==================================================================== struct PropertyControlExtender_Data; typedef ::cppu::WeakImplHelper1 < ::com::sun::star::awt::XKeyListener > PropertyControlExtender_Base; class PropertyControlExtender : public PropertyControlExtender_Base { public: PropertyControlExtender( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& _rxObservedControl ); // XKeyListener virtual void SAL_CALL keyPressed( const ::com::sun::star::awt::KeyEvent& e ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL keyReleased( const ::com::sun::star::awt::KeyEvent& e ) throw (::com::sun::star::uno::RuntimeException); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException); protected: virtual ~PropertyControlExtender(); private: ::std::auto_ptr< PropertyControlExtender_Data > m_pData; }; //........................................................................ } // namespace pcr //........................................................................ #endif // EXTENSIONS_PROPERTYCONTROLEXTENDER_HXX
39.819444
141
0.565051
Grosskopf
f9f2f857daf295346a86229adeba54d074dc3b0c
1,095
cpp
C++
examples/simple_download/main.cpp
SammyEnigma/QEasyDownloader
b405159db2a7d3ca6b46d4222e8c68e9dfec99ea
[ "BSD-3-Clause" ]
2
2020-04-15T15:32:03.000Z
2020-04-15T15:32:21.000Z
examples/simple_download/main.cpp
SammyEnigma/QEasyDownloader
b405159db2a7d3ca6b46d4222e8c68e9dfec99ea
[ "BSD-3-Clause" ]
null
null
null
examples/simple_download/main.cpp
SammyEnigma/QEasyDownloader
b405159db2a7d3ca6b46d4222e8c68e9dfec99ea
[ "BSD-3-Clause" ]
2
2020-04-14T17:13:36.000Z
2021-01-10T10:04:49.000Z
#include <QCoreApplication> #include <QEasyDownloader> int main(int argc, char **argv) { QCoreApplication app(argc, argv); /* * Construct */ QEasyDownloader Downloader; /* * By Default Debug is false , make it true to print the download progress and * other stuff! */ Downloader.setDebug(true); /* * By Default auto Resuming of Downloads is true. * * You can also disable auto resuming of downloads. * But I strongly recommend you don't! */ // Downloader.setResumeDownloads(false); /* * Connect Callbacks! */ QObject::connect(&Downloader, &QEasyDownloader::Debugger, [&](QString msg) { qDebug() << msg; return; }); QObject::connect(&Downloader, &QEasyDownloader::DownloadFinished, [&](QUrl Url, QString file) { qDebug() << "Downloaded :: " << file << " :: FROM :: " << Url; app.quit(); }); /* * Just Download! */ Downloader.Download("http://sample-videos.com/video/mp4/720/big_buck_bunny_720p_5mb.mp4"); return app.exec(); }
23.804348
94
0.596347
SammyEnigma
f9f353042a4420e0583fe7220f685aa28073b632
303
hpp
C++
opencv/build/modules/core/test/test_intrin512.simd_declarations.hpp
soyyuz/opencv-contrib-ARM64
25386df773f88a071532ec69ff541c31e62ec8f2
[ "Apache-2.0" ]
null
null
null
opencv/build/modules/core/test/test_intrin512.simd_declarations.hpp
soyyuz/opencv-contrib-ARM64
25386df773f88a071532ec69ff541c31e62ec8f2
[ "Apache-2.0" ]
null
null
null
opencv/build/modules/core/test/test_intrin512.simd_declarations.hpp
soyyuz/opencv-contrib-ARM64
25386df773f88a071532ec69ff541c31e62ec8f2
[ "Apache-2.0" ]
1
2022-03-27T03:35:07.000Z
2022-03-27T03:35:07.000Z
#define CV_CPU_SIMD_FILENAME "/home/epasholl/opencv/opencv-master/modules/core/test/test_intrin512.simd.hpp" #define CV_CPU_DISPATCH_MODE AVX512_SKX #include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp" #define CV_CPU_DISPATCH_MODES_ALL AVX512_SKX, BASELINE #undef CV_CPU_SIMD_FILENAME
37.875
108
0.864686
soyyuz
f9f66adc04cca9dbd2103b56d3dcc874ff35bcec
2,787
hpp
C++
lexer/token.hpp
CobaltXII/cxcc
2e8f34e851b3cbe6699e443fd3950d630ff170b7
[ "MIT" ]
3
2019-05-27T04:50:51.000Z
2019-06-18T16:27:58.000Z
lexer/token.hpp
CobaltXII/cxcc
2e8f34e851b3cbe6699e443fd3950d630ff170b7
[ "MIT" ]
null
null
null
lexer/token.hpp
CobaltXII/cxcc
2e8f34e851b3cbe6699e443fd3950d630ff170b7
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> // All token types. enum token_type_t { // Special tokens. tk_identifier, tk_lit_integer, tk_lit_string, tk_lit_character, tk_eof, // Reserved words. tk_if, tk_int, tk_else, tk_while, tk_return, tk_break, tk_continue, // Punctuation. tk_left_parenthesis, tk_right_parenthesis, tk_left_bracket, tk_right_bracket, tk_left_brace, tk_right_brace, tk_comma, tk_semicolon, // Binary operators. tk_bi_division, tk_bi_modulo, tk_bi_assignment, tk_bi_addition_assignment, tk_bi_subtraction_assignment, tk_bi_multiplication_assignment, tk_bi_division_assignment, tk_bi_modulo_assignment, tk_bi_logical_and, tk_bi_logical_or, tk_bi_relational_equal, tk_bi_relational_non_equal, tk_bi_relational_greater_than, tk_bi_relational_lesser_than, tk_bi_relational_greater_than_or_equal_to, tk_bi_relational_lesser_than_or_equal_to, tk_bi_binary_or, tk_bi_binary_xor, tk_bi_binary_and_assignment, tk_bi_binary_or_assignment, tk_bi_binary_xor_assignment, tk_bi_binary_left_shift, tk_bi_binary_right_shift, tk_bi_binary_left_shift_assignment, tk_bi_binary_right_shift_assignment, // Unary operators. tk_un_logical_not, tk_un_binary_not, // Ambiguous operators. tk_plus, tk_minus, tk_asterisk, tk_ampersand }; // All token types as strings. std::string token_type_str[] = { // Special tokens. "identifier", "integer literal", "string literal", "character literal", "end-of-file", // Reserved words. "'if'", "'int'", "'else'", "'while'", "'return'", "'break'", "'continue'", // Punctuation. "'('", "')'", "'['", "']'", "'{'", "'}'", "','", "';'", // Binary operators. "'/'", "'%'", "'='", "'+='", "'-='", "'*='", "'/='", "'%='", "'&&'", "'||'", "'=='", "'!='", "'>'", "'<'", "'>='", "'<='", "'|'", "'^'", "'&='", "'|='", "'^='", "'<<'", "'>>'", "'<<='", "'>>='", // Unary operators. "'!'", "'~'", // Ambiguous operators. "'+'", "'-'", "'*'", "'&'" }; // All token types as strings, padded. std::vector<std::string> make_token_type_str_pad() { std::vector<std::string> token_type_str_pad; long max_length = 0; for (int i = 0; i < sizeof(token_type_str) / sizeof(token_type_str[0]); i++) { if (token_type_str[i].length() > max_length) { max_length = token_type_str[i].length(); } } for (int i = 0; i < sizeof(token_type_str) / sizeof(token_type_str[0]); i++) { std::string padding(max_length - token_type_str[i].length(), ' '); token_type_str_pad.push_back(token_type_str[i] + padding); } return token_type_str_pad; } // All token types as strings, padded. std::vector<std::string> token_type_str_pad = make_token_type_str_pad(); // A token. struct token_t { token_type_t type; std::string text; long lineno; long colno; };
18.335526
79
0.666308
CobaltXII
f9f84c5062a5075b73119aad4133f93568f6d0ac
1,207
cpp
C++
trainings/2015-10-06-Multi-University-2015-10/B.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-10-06-Multi-University-2015-10/B.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-10-06-Multi-University-2015-10/B.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <iostream> using namespace std; const int mod = 1e9 + 7; const int N = 1e6 + 11; int prime[N + 10]; long long f[N + 10], ok[N + 10]; void init() { for (int i = 2; i <= N; i++) { prime[i] = 1; ok[i] = 0; } for (int i = 2; i <= N; i++) { if (prime[i]) { for (int j = i + i; j <= N; j += i) { prime[j] = 0; } for (long long j = i; j <= N; j *= i) { ok[j] = i; } } } f[1] = 1; for (int i = 2; i <= N; i++) { f[i] = f[i - 1]; if (ok[i]) { f[i] = f[i] * ok[i] % mod; } } } long long power(const long long &x, const long long &k) { long long answer = 1, number = x; for (long long i = k; i > 0; i >>= 1) { if (i & 1) { (answer *= number) %= mod; } (number *= number) %= mod; } return answer; } int n; void solve() { scanf("%d", &n); int ans = 1LL * f[n + 1] * power(n + 1, mod - 2) % mod; printf("%d\n", ans); } int main() { int tests; scanf("%d", &tests); init(); for (int i = 1; i <= tests; i++) { solve(); } return 0; }
18.569231
59
0.375311
HcPlu
f9f9f45c4c3754f82bbf5773c36ab80f5f3d0fd6
4,395
cc
C++
components/signin/internal/identity_manager/account_info_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/signin/internal/identity_manager/account_info_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/signin/internal/identity_manager/account_info_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 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/signin/internal/identity_manager/account_info_util.h" #include <map> #include <string> #include "base/values.h" #include "components/signin/internal/identity_manager/account_capabilities_constants.h" #include "components/signin/public/identity_manager/account_capabilities.h" #include "components/signin/public/identity_manager/account_info.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace { // Keys used to store the different values in the JSON dictionary received // from gaia server. const char kGaiaIdKey[] = "id"; const char kEmailKey[] = "email"; const char kHostedDomainKey[] = "hd"; const char kFullNameKey[] = "name"; const char kGivenNameKey[] = "given_name"; const char kLocaleKey[] = "locale"; const char kPictureUrlKey[] = "picture"; const char kAccountCapabilitiesListKey[] = "accountCapabilities"; const char kAccountCapabilityNameKey[] = "name"; const char kAccountCapabilityBooleanValueKey[] = "booleanValue"; } // namespace absl::optional<AccountInfo> AccountInfoFromUserInfo( const base::Value& user_info) { if (!user_info.is_dict()) return absl::nullopt; // Both |gaia_id| and |email| are required value in the JSON reply, so // return empty result if any is missing. const base::Value* gaia_id_value = user_info.FindKeyOfType(kGaiaIdKey, base::Value::Type::STRING); if (!gaia_id_value) return absl::nullopt; const base::Value* email_value = user_info.FindKeyOfType(kEmailKey, base::Value::Type::STRING); if (!email_value) return absl::nullopt; AccountInfo account_info; account_info.email = email_value->GetString(); account_info.gaia = gaia_id_value->GetString(); // All other fields are optional, some with default values. const base::Value* hosted_domain_value = user_info.FindKeyOfType(kHostedDomainKey, base::Value::Type::STRING); if (hosted_domain_value && !hosted_domain_value->GetString().empty()) account_info.hosted_domain = hosted_domain_value->GetString(); else account_info.hosted_domain = kNoHostedDomainFound; const base::Value* full_name_value = user_info.FindKeyOfType(kFullNameKey, base::Value::Type::STRING); if (full_name_value) account_info.full_name = full_name_value->GetString(); const base::Value* given_name_value = user_info.FindKeyOfType(kGivenNameKey, base::Value::Type::STRING); if (given_name_value) account_info.given_name = given_name_value->GetString(); const base::Value* locale_value = user_info.FindKeyOfType(kLocaleKey, base::Value::Type::STRING); if (locale_value) account_info.locale = locale_value->GetString(); const base::Value* picture_url_value = user_info.FindKeyOfType(kPictureUrlKey, base::Value::Type::STRING); if (picture_url_value && !picture_url_value->GetString().empty()) account_info.picture_url = picture_url_value->GetString(); else account_info.picture_url = kNoPictureURLFound; return account_info; } absl::optional<AccountCapabilities> AccountCapabilitiesFromValue( const base::Value& account_capabilities) { if (!account_capabilities.is_dict()) return absl::nullopt; const base::Value* list = account_capabilities.FindListKey(kAccountCapabilitiesListKey); if (!list) return absl::nullopt; // 1. Create "capability name" -> "boolean value" mapping. std::map<std::string, bool> boolean_capabilities; for (const auto& capability_value : list->GetList()) { const std::string* name = capability_value.FindStringKey(kAccountCapabilityNameKey); if (!name) return absl::nullopt; // name is a required field. // Check whether a capability has a boolean value. absl::optional<bool> boolean_value = capability_value.FindBoolKey(kAccountCapabilityBooleanValueKey); if (boolean_value.has_value()) { boolean_capabilities[*name] = *boolean_value; } } // 2. Fill AccountCapabilities fields based on the mapping. AccountCapabilities capabilities; auto it = boolean_capabilities.find( kCanOfferExtendedChromeSyncPromosCapabilityName); if (it != boolean_capabilities.end()) capabilities.set_can_offer_extended_chrome_sync_promos(it->second); return capabilities; }
36.625
87
0.746985
zealoussnow
f9fb7a437bb590c8c3292ea5db857bd1d4c7cc61
1,408
cpp
C++
src/cpp-leetcode/first/Code_154_MinNumInRotatedSortedArr2.cpp
17hao/algorithm
0e96883a4638b33182bd590fffd12fd6ba0783c8
[ "Apache-2.0" ]
null
null
null
src/cpp-leetcode/first/Code_154_MinNumInRotatedSortedArr2.cpp
17hao/algorithm
0e96883a4638b33182bd590fffd12fd6ba0783c8
[ "Apache-2.0" ]
1
2019-03-25T15:17:54.000Z
2019-03-25T15:20:30.000Z
src/cpp-leetcode/first/Code_154_MinNumInRotatedSortedArr2.cpp
17hao/algorithm
0e96883a4638b33182bd590fffd12fd6ba0783c8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> using std::vector; /** * find minimum number in rotated array * * @since 2020-10-21 Wednesday 10:27 - 11:10 */ class Solution { int findPivot(vector<int> v) { int size = v.size(); int l = 0, r = size - 1; while (l <= r) { int mid = l + (r - l) / 2; if (v[mid] > v[mid + 1]) { return mid; } if (v[mid] < v[l]) { r = mid; } else if (v[mid] > v[r]) { l = mid; } else { r--; } } return -1; } public: int findMin(vector<int>& nums) { int size = nums.size(); if (size == 0) return 0; if (size == 1) return nums[0]; int pivot = findPivot(nums); return nums[pivot + 1]; } }; int main(int argc, char const* argv[]) { Solution s; vector<int> v0 = {1}; std::cout << s.findMin(v0) << "\n"; vector<int> v1 = {2, 2, 2, 2, 0, 1}; std::cout << s.findMin(v1) << "\n"; vector<int> v2 = {4, 5, -1, 0, 1, 2, 3}; std::cout << s.findMin(v2) << "\n"; vector<int> v3 = {2, 2, 2, 2}; std::cout << s.findMin(v3) << "\n"; vector<int> v4 = {1, 2, 3, 4}; std::cout << s.findMin(v4) << "\n"; vector<int> v5 = {6, 6, 1, 6, 6}; std::cout << s.findMin(v5) << "\n"; }
22.349206
44
0.417614
17hao
f9ff453cf96c18c174b85eb5647804b7b1eeee79
1,340
cpp
C++
DDrawCompat/DDraw/DirectDrawPalette.cpp
fengjixuchui/DDrawCompat
0017d4cca75a0e8b90c412b69da928a33b9dc0d1
[ "0BSD" ]
1
2021-02-10T17:49:17.000Z
2021-02-10T17:49:17.000Z
DDrawCompat/DDraw/DirectDrawPalette.cpp
c3358/DDrawCompat
27ae9affb8f78d56c1cd09cf888be9ac94c051e9
[ "0BSD" ]
null
null
null
DDrawCompat/DDraw/DirectDrawPalette.cpp
c3358/DDrawCompat
27ae9affb8f78d56c1cd09cf888be9ac94c051e9
[ "0BSD" ]
null
null
null
#include <cstring> #include <deque> #include "Common/Time.h" #include "Config/Config.h" #include "DDraw/DirectDrawPalette.h" #include "DDraw/Surfaces/PrimarySurface.h" #include "Gdi/AccessGuard.h" namespace DDraw { void DirectDrawPalette::setCompatVtable(IDirectDrawPaletteVtbl& vtable) { vtable.SetEntries = &SetEntries; } HRESULT STDMETHODCALLTYPE DirectDrawPalette::SetEntries( IDirectDrawPalette* This, DWORD dwFlags, DWORD dwStartingEntry, DWORD dwCount, LPPALETTEENTRY lpEntries) { if (This == PrimarySurface::s_palette) { waitForNextUpdate(); } HRESULT result = s_origVtable.SetEntries(This, dwFlags, dwStartingEntry, dwCount, lpEntries); if (SUCCEEDED(result) && This == PrimarySurface::s_palette) { PrimarySurface::updatePalette(); } return result; } void DirectDrawPalette::waitForNextUpdate() { static std::deque<long long> updatesInLastMs; const long long qpcNow = Time::queryPerformanceCounter(); const long long qpcLastMsBegin = qpcNow - Time::g_qpcFrequency / 1000; while (!updatesInLastMs.empty() && qpcLastMsBegin - updatesInLastMs.front() > 0) { updatesInLastMs.pop_front(); } if (updatesInLastMs.size() >= Config::maxPaletteUpdatesPerMs) { Sleep(1); updatesInLastMs.clear(); } updatesInLastMs.push_back(Time::queryPerformanceCounter()); } }
23.508772
95
0.736567
fengjixuchui
e600f394d0516ef29fef83a6ff839fc159589f0e
1,441
hpp
C++
hot/commons/include/hot/commons/PartialKeyMappingBase.hpp
freesummer/SIMD-Matcher
3b1889d2924d243daff4939e7328bef431d9859a
[ "0BSD" ]
null
null
null
hot/commons/include/hot/commons/PartialKeyMappingBase.hpp
freesummer/SIMD-Matcher
3b1889d2924d243daff4939e7328bef431d9859a
[ "0BSD" ]
null
null
null
hot/commons/include/hot/commons/PartialKeyMappingBase.hpp
freesummer/SIMD-Matcher
3b1889d2924d243daff4939e7328bef431d9859a
[ "0BSD" ]
null
null
null
#ifndef __HOT__COMMONS__PARTIAL_KEY_MAPPING_BASE_HPP___ #define __HOT__COMMONS__PARTIAL_KEY_MAPPING_BASE_HPP___ #include "hot/commons/include/hot/commons/DiscriminativeBit.hpp" namespace hot { namespace commons { /** * A Base class for all partial key mapping informations * A Partial key mapping must be able to extract a set of discriminative bits and form partial keys consisting only of those bits * */ class PartialKeyMappingBase { public: uint16_t mMostSignificantDiscriminativeBitIndex; uint16_t mLeastSignificantDiscriminativeBitIndex; protected: //This does not initialize the fields and is only allowed to be called from subclasses //This can be used if both fields are copied together with another field using 64bit operations or better simd or avx instructions PartialKeyMappingBase() { } protected: PartialKeyMappingBase(uint16_t mostSignificantBitIndex, uint16_t leastSignificantBitIndex) : mMostSignificantDiscriminativeBitIndex(mostSignificantBitIndex), mLeastSignificantDiscriminativeBitIndex(leastSignificantBitIndex) { } PartialKeyMappingBase(PartialKeyMappingBase const existing, DiscriminativeBit const & significantKeyInformation) : PartialKeyMappingBase( std::min(existing.mMostSignificantDiscriminativeBitIndex, significantKeyInformation.mAbsoluteBitIndex), std::max(existing.mLeastSignificantDiscriminativeBitIndex, significantKeyInformation.mAbsoluteBitIndex) ) { } }; } } #endif
36.025
226
0.834837
freesummer
e601409f0ab4f79c59b7e57a7c626886caede9b3
39,335
cpp
C++
src/Main/Gui/CoreWindow.cpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
4
2016-06-03T18:41:43.000Z
2020-04-17T20:28:58.000Z
src/Main/Gui/CoreWindow.cpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
src/Main/Gui/CoreWindow.cpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2022 The Voxie Authors * * 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. */ // QDBusConnection should be included as early as possible: // https://bugreports.qt.io/browse/QTBUG-48351 / // https://bugreports.qt.io/browse/QTBUG-48377 #include <QtDBus/QDBusConnection> #include "CoreWindow.hpp" #include <Voxie/Util.hpp> #include <VoxieClient/DBusAdaptors.hpp> #include <VoxieClient/DBusProxies.hpp> #include <VoxieBackend/IO/OperationImport.hpp> #include <VoxieBackend/IO/OperationResult.hpp> #include <Main/Gui/AboutDialogWindow.hpp> #include <Main/Gui/ButtonLabel.hpp> #include <Main/Gui/OpenFileDialog.hpp> #include <Main/Gui/PluginManagerWindow.hpp> #include <Main/Gui/PreferencesWindow.hpp> #include <Main/Gui/ScriptConsole.hpp> #include <Main/Gui/SidePanel.hpp> #include <Main/Gui/SliceView.hpp> #include <Main/Gui/VScrollArea.hpp> #include <Main/DirectoryManager.hpp> #include <Main/Root.hpp> #include <Main/Component/SessionManager.hpp> #include <Main/Help/HelpLinkHandler.hpp> #include <Main/Component/ScriptLauncher.hpp> #include <Voxie/Component/HelpCommon.hpp> #include <Voxie/Component/Plugin.hpp> #include <Voxie/Node/NodePrototype.hpp> #include <VoxieClient/Exception.hpp> #include <Voxie/Gui/ErrorMessage.hpp> #include <Voxie/IO/SaveFileDialog.hpp> #include <Voxie/Vis/VisualizerNode.hpp> #include <VoxieClient/ObjectExport/BusManager.hpp> #include <functional> #include <assert.h> #include <QCloseEvent> #include <QtCore/QDebug> #include <QtCore/QProcess> #include <QtCore/QSettings> #include <QtCore/QUrl> #include <QtDBus/QDBusMessage> #include <QtGui/QDesktopServices> #include <QtGui/QScreen> #include <QtGui/QWindow> #include <QtWidgets/QDockWidget> #include <QtWidgets/QFileDialog> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QMdiSubWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QMessageBox> #include <QtWidgets/QPushButton> #include <QtWidgets/QScrollArea> #include <QtWidgets/QSplitter> #include <QtWidgets/QStatusBar> #include <QtWidgets/QVBoxLayout> using namespace vx::io; using namespace vx::gui; using namespace vx; using namespace vx::plugin; using namespace vx::visualization; using namespace vx; ActiveVisualizerProviderImpl::~ActiveVisualizerProviderImpl() {} VisualizerNode* ActiveVisualizerProviderImpl::activeVisualizer() const { return win->getActiveVisualizer(); } QList<Node*> ActiveVisualizerProviderImpl::selectedNodes() const { return win->sidePanel->selectedNodes(); } void ActiveVisualizerProviderImpl::setSelectedNodes( const QList<Node*>& nodes) const { win->sidePanel->dataflowWidget->setSelectedNodes(nodes); } namespace vx { namespace gui { class Gui : public ExportedObject { friend class GuiAdaptorImpl; CoreWindow* window; public: Gui(CoreWindow* window); virtual ~Gui(); }; class GuiAdaptorImpl : public GuiAdaptor { Gui* object; public: GuiAdaptorImpl(Gui* object) : GuiAdaptor(object), object(object) {} virtual ~GuiAdaptorImpl() {} QList<QDBusObjectPath> selectedNodes() const override; QList<QDBusObjectPath> selectedObjects() const override; QDBusObjectPath activeVisualizer() const override; void RaiseWindow(const QMap<QString, QDBusVariant>& options) override; qulonglong GetMainWindowID( const QMap<QString, QDBusVariant>& options) override; void setMdiViewMode(const QString& mdiViewMode) override { if (mdiViewMode == "de.uni_stuttgart.Voxie.MdiViewMode.SubWindow") { object->window->setTilePattern(false); } else if (mdiViewMode == "de.uni_stuttgart.Voxie.MdiViewMode.SubWindowTiled") { object->window->setTilePattern(true); } bool isToggleChecked = object->window->toggleTabbedAction->isChecked(); bool isTabbed = (mdiViewMode == "de.uni_stuttgart.Voxie.MdiViewMode.Tabbed"); if ((isToggleChecked && !isTabbed) || (!isToggleChecked && isTabbed)) { object->window->toggleTabbedAction->trigger(); } } QString mdiViewMode() const override { QString mode; if (object->window->getMdiArea()->viewMode() == QMdiArea::TabbedView) { mode = "de.uni_stuttgart.Voxie.MdiViewMode.Tabbed"; } else if (object->window->getTilePattern()) { mode = "de.uni_stuttgart.Voxie.MdiViewMode.SubWindowTiled"; } else { mode = "de.uni_stuttgart.Voxie.MdiViewMode.SubWindow"; } return mode; } }; } // namespace gui } // namespace vx Gui::Gui(CoreWindow* window) : ExportedObject("Gui", window, true), window(window) { new GuiAdaptorImpl(this); // https://bugreports.qt.io/browse/QTBUG-48008 // https://randomguy3.wordpress.com/2010/09/07/the-magic-of-qtdbus-and-the-propertychanged-signal/ connect(window, &CoreWindow::activeVisualizerChanged, [=](VisualizerNode* visualizer) { // http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties // org.freedesktop.DBus.Properties.PropertiesChanged (STRING // interface_name, // DICT<STRING,VARIANT> // changed_properties, // ARRAY<STRING> // invalidated_properties); QString propertyName = "ActiveVisualizer"; auto value = ExportedObject::getPath(visualizer); QDBusMessage signal = QDBusMessage::createSignal( window->getGuiDBusObject()->getPath().path(), "org.freedesktop.DBus.Properties", "PropertiesChanged"); signal << dbusMakeVariant<QString>("de.uni_stuttgart.Voxie.Gui") .variant(); QMap<QString, QDBusVariant> changedProps; changedProps.insert(propertyName, dbusMakeVariant<QDBusObjectPath>(value)); signal << dbusMakeVariant<QMap<QString, QDBusVariant>>(changedProps) .variant(); signal << dbusMakeVariant<QList<QString>>(QStringList()).variant(); getBusManager()->sendEverywhere(signal); }); connect(window->sidePanel, &SidePanel::nodeSelectionChanged, [=]() { // http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties // org.freedesktop.DBus.Properties.PropertiesChanged (STRING // interface_name, // DICT<STRING,VARIANT> // changed_properties, // ARRAY<STRING> // invalidated_properties); QString propertyName = "SelectedNodes"; QString propertyNameOld = "SelectedObjects"; QList<QDBusObjectPath> value; for (const auto& obj : window->sidePanel->selectedNodes()) value << ExportedObject::getPath(obj); QDBusMessage signal = QDBusMessage::createSignal( window->getGuiDBusObject()->getPath().path(), "org.freedesktop.DBus.Properties", "PropertiesChanged"); signal << dbusMakeVariant<QString>("de.uni_stuttgart.Voxie.Gui").variant(); QMap<QString, QDBusVariant> changedProps; changedProps.insert(propertyName, dbusMakeVariant<QList<QDBusObjectPath>>(value)); changedProps.insert(propertyNameOld, dbusMakeVariant<QList<QDBusObjectPath>>(value)); signal << dbusMakeVariant<QMap<QString, QDBusVariant>>(changedProps).variant(); signal << dbusMakeVariant<QStringList>(QStringList()).variant(); getBusManager()->sendEverywhere(signal); }); } Gui::~Gui() {} QList<QDBusObjectPath> GuiAdaptorImpl::selectedNodes() const { try { QList<QDBusObjectPath> res; for (const auto& obj : object->window->sidePanel->selectedNodes()) res << ExportedObject::getPath(obj); return res; } catch (Exception& e) { e.handle(object); return QList<QDBusObjectPath>(); } } QList<QDBusObjectPath> GuiAdaptorImpl::selectedObjects() const { try { QList<QDBusObjectPath> res; for (const auto& obj : object->window->sidePanel->selectedNodes()) res << ExportedObject::getPath(obj); return res; } catch (Exception& e) { e.handle(object); return QList<QDBusObjectPath>(); } } QDBusObjectPath GuiAdaptorImpl::activeVisualizer() const { try { return ExportedObject::getPath(object->window->getActiveVisualizer()); } catch (Exception& e) { e.handle(object); return ExportedObject::getPath(nullptr); } } void GuiAdaptorImpl::RaiseWindow(const QMap<QString, QDBusVariant>& options) { try { ExportedObject::checkOptions(options); object->window->activateWindow(); object->window->raise(); } catch (Exception& e) { e.handle(object); } } qulonglong GuiAdaptorImpl::GetMainWindowID( const QMap<QString, QDBusVariant>& options) { try { ExportedObject::checkOptions(options); return object->window->winId(); } catch (Exception& e) { e.handle(object); return 0; } } CoreWindow::CoreWindow(vx::Root* root, QWidget* parent) : QMainWindow(parent), visualizers(), activeVisualizer(nullptr), isBeginDestroyed(false), activeVisualizerProvider(this) { connect(this, &CoreWindow::activeVisualizerChanged, this, [this](VisualizerNode* current) { Q_EMIT activeVisualizerProvider.activeVisualizerChanged(current); }); this->setWindowTitle("Voxie"); this->initMenu(); this->initStatusBar(); this->initWidgets(root); this->guiDBusObject = new Gui(this); this->setWindowIcon(QIcon(":/icons-voxie/voxel-data-32.png")); } CoreWindow::~CoreWindow() { isBeginDestroyed = true; } void CoreWindow::insertPlugin(const QSharedPointer<Plugin>& plugin) { if (plugin->uiCommands().size() > 0) { QMenu* pluginEntry = this->pluginsMenu->addMenu(plugin->name()); // Insert UI Actions QList<QAction*> pluginActions; for (QAction* action : plugin->uiCommands()) { pluginActions.append(action); } pluginEntry->addActions(pluginActions); } } void CoreWindow::addVisualizer(VisualizerNode* visualizer) { if (visualizer == nullptr) { return; } VisualizerContainer* container = new VisualizerContainer(this->mdiArea, visualizer); this->visualizers.append(container); connect(container, &QObject::destroyed, this, [=]() { if (isBeginDestroyed) return; this->visualizers.removeAll(container); }); QAction* windowEntry = this->windowMenu->addAction(visualizer->icon(), container->windowTitle()); connect(windowEntry, &QAction::triggered, container, &VisualizerContainer::activate); connect(container, &QWidget::destroyed, windowEntry, &QAction::deleteLater); connect(visualizer, &QWidget::destroyed, container, &VisualizerContainer::closeWindow); QMetaObject::Connection connection = connect(container, &VisualizerContainer::sidePanelVisiblityChanged, [=](bool visible) { // qDebug() << "VisualizerContainer::sidePanelVisiblityChanged" // << container << visualizer << visible; if (visible == false) return; if (this->activeVisualizer != visualizer) { this->activeVisualizer = visualizer; Q_EMIT activeVisualizerChanged(visualizer); } this->mdiArea->setActiveSubWindow(container->window); // This is disabled because it is also e.g. triggered when the // main window regains focus and causes another node to be // selected in this case //// update sidepanel to view data of selected visualizer // this->sidePanel->nodeTree->select(visualizer); }); connect(container, &QObject::destroyed, this, [=]() { if (isBeginDestroyed) return; if (this->activeVisualizer == visualizer) { this->activeVisualizer = nullptr; Q_EMIT activeVisualizerChanged(nullptr); } disconnect(connection); }); QVector<QWidget*> sections = visualizer->dynamicSections(); for (QWidget* section : sections) visualizer->addPropertySection(section); visualizer->mainView()->setFocus(); this->activeVisualizer = visualizer; Q_EMIT activeVisualizerChanged(visualizer); } VisualizerNode* CoreWindow::getActiveVisualizer() { return activeVisualizer; } void CoreWindow::initMenu() { QMenuBar* menu = new QMenuBar(this); QMenu* fileMenu = menu->addMenu("&File"); this->pluginsMenu = menu->addMenu("Plu&gins"); this->scriptsMenu = menu->addMenu("&Scripts"); { connect(scriptsMenu, &QMenu::aboutToShow, this, &CoreWindow::populateScriptsMenu); } this->windowMenu = menu->addMenu("&Window"); QMenu* helpMenu = menu->addMenu("&Help"); // Lets the user begin a new session by destroying all data nodes QAction* newAction = fileMenu->addAction(QIcon(":/icons/blue-document.png"), "&New..."); newAction->setShortcut(QKeySequence("Ctrl+N")); connect(newAction, &QAction::triggered, this, &CoreWindow::newSession); QAction* openAction = fileMenu->addAction( QIcon(":/icons/blue-folder-horizontal-open.png"), "&Open…"); openAction->setShortcut(QKeySequence("Ctrl+O")); connect(openAction, &QAction::triggered, this, &CoreWindow::loadFile); QAction* loadAction = fileMenu->addAction( QIcon(":/icons/folder-horizontal.png"), "&Load Voxie Project"); loadAction->setShortcut(QKeySequence("Ctrl+L")); connect(loadAction, &QAction::triggered, this, [this] { if (newSession()) loadProject(); }); QAction* importAction = fileMenu->addAction(QIcon(":/icons/folder--plus.png"), "&Import Project/Node Group"); importAction->setShortcut(QKeySequence("Ctrl+I")); connect(importAction, &QAction::triggered, this, &CoreWindow::loadProject); QAction* saveAction = fileMenu->addAction(QIcon(":/icons/disk.png"), "&Save Voxie Project"); saveAction->setShortcut(QKeySequence("Ctrl+S")); connect(saveAction, &QAction::triggered, this, &CoreWindow::saveProject); fileMenu->addSeparator(); QAction* addNodeAction = fileMenu->addAction(QIcon(":/icons/disk.png"), "Add n&ew node"); addNodeAction->setShortcut(QKeySequence("Ctrl+Shift+E")); connect(addNodeAction, &QAction::triggered, this, [this]() { auto globalPos = QCursor::pos(); Node* obj = nullptr; sidePanel->showContextMenu(obj, globalPos); }); QAction* addNodeActionAsChild = fileMenu->addAction(QIcon(":/icons/disk.png"), "Add n&ew node as child"); addNodeActionAsChild->setShortcut(QKeySequence("Ctrl+E")); connect(addNodeActionAsChild, &QAction::triggered, this, [this]() { auto globalPos = QCursor::pos(); Node* obj = nullptr; if (sidePanel->selectedNodes().size()) obj = sidePanel->selectedNodes()[0]; sidePanel->showContextMenu(obj, globalPos); }); fileMenu->addSeparator(); QAction* preferencesAction = fileMenu->addAction(QIcon(":/icons/gear.png"), "&Preferences…"); connect(preferencesAction, &QAction::triggered, this, [this]() -> void { PreferencesWindow* preferences = new PreferencesWindow(this); preferences->setAttribute(Qt::WA_DeleteOnClose); preferences->exec(); }); QAction* quitAction = fileMenu->addAction(QIcon(":/icons/cross.png"), "E&xit"); quitAction->setShortcut(QKeySequence("Ctrl+Q")); connect(quitAction, &QAction::triggered, this, &QMainWindow::close); QAction* pluginManagerAction = this->pluginsMenu->addAction( QIcon(":/icons/plug.png"), "&Plugin Manager…"); connect(pluginManagerAction, &QAction::triggered, this, [this]() -> void { PluginManagerWindow* pluginmanager = new PluginManagerWindow(this); pluginmanager->setAttribute(Qt::WA_DeleteOnClose); pluginmanager->exec(); }); this->pluginsMenu->addSeparator(); scriptsMenuStaticSize = 0; QAction* scriptConsoleAction = this->scriptsMenu->addAction( QIcon(":/icons/application-terminal.png"), "&JS Console…"); scriptsMenuStaticSize++; connect(scriptConsoleAction, &QAction::triggered, this, [this]() -> void { ScriptConsole* console = new ScriptConsole(this, "Voxie - JS Console"); console->setAttribute(Qt::WA_DeleteOnClose); connect(console, &ScriptConsole::executeCode, this, [console](const QString& code) -> void { Root::instance()->exec(code, code, [console](const QString& text) { console->appendLine(text); }); }); console->show(); console->activateWindow(); }); QAction* pythonConsoleAction = this->scriptsMenu->addAction( QIcon(":/icons/application-terminal.png"), "&Python Console…"); scriptsMenuStaticSize++; pythonConsoleAction->setShortcut(QKeySequence("Ctrl+Shift+S")); connect(pythonConsoleAction, &QAction::triggered, this, [this]() -> void { auto service = Root::instance()->mainDBusService(); if (!service) { QMessageBox( QMessageBox::Critical, Root::instance()->mainWindow()->windowTitle(), QString("Cannot launch python console because DBus is not available"), QMessageBox::Ok, Root::instance()->mainWindow()) .exec(); return; } ScriptConsole* console = new ScriptConsole(this, "Voxie - Python Console"); console->setAttribute(Qt::WA_DeleteOnClose); // TODO: This should probably also use ScriptLauncher auto process = new QProcess(); connect(console, &QObject::destroyed, process, &QProcess::closeWriteChannel); process->setProcessChannelMode(QProcess::MergedChannels); process->setWorkingDirectory( Root::instance()->directoryManager()->baseDir()); process->setProgram( Root::instance()->directoryManager()->pythonExecutable()); QStringList args; args << "-i"; args << "-u"; args << "-c"; QString escapedPythonLibDirs = escapePythonStringArray( vx::Root::instance()->directoryManager()->allPythonLibDirs()); args << "import sys; sys.path = " + escapedPythonLibDirs + " + sys.path; " + "import numpy as np; import voxie; args = " "voxie.parser.parse_args(); context = " "voxie.VoxieContext(args); instance = " "context.createInstance();"; service->addArgumentsTo(args); process->setArguments(args); connect<void (QProcess::*)(int, QProcess::ExitStatus), std::function<void(int, QProcess::ExitStatus)>>( process, &QProcess::finished, console, std::function<void(int, QProcess::ExitStatus)>( [process, console](int exitCode, QProcess::ExitStatus exitStatus) -> void { console->appendLine( QString( "Script host finished with exit status %1 / exit code %2") .arg(exitStatus) .arg(exitCode)); process->deleteLater(); })); auto isStarted = createQSharedPointer<bool>(); connect(process, &QProcess::started, this, [isStarted]() { *isStarted = true; }); connect(process, &QProcess::stateChanged, this, [process, isStarted](QProcess::ProcessState newState) { if (newState == QProcess::NotRunning && !*isStarted) { Root::instance()->log( QString("Error while starting script host: %1") .arg(process->error())); process->deleteLater(); } }); connect(process, &QProcess::readyRead, console, [process, console]() -> void { QString data = QString(process->readAll()); console->append(data); }); connect(console, &ScriptConsole::executeCode, process, [process, console](const QString& code) -> void { QString code2 = code + "\n"; console->append(code2); // TODO: handle case when python process does not read input process->write(code2.toUtf8()); }); process->start(); console->show(); console->activateWindow(); }); // TODO: Clean up #if defined(Q_OS_LINUX) || defined(Q_OS_MACOS) QAction* pythonConsoleTerminalAction = this->scriptsMenu->addAction( QIcon(":/icons/application-terminal.png"), "Python Console (&terminal)…"); scriptsMenuStaticSize++; pythonConsoleTerminalAction->setShortcut(QKeySequence("Ctrl+Shift+T")); connect( pythonConsoleTerminalAction, &QAction::triggered, this, [this]() -> void { auto service = Root::instance()->mainDBusService(); if (!service) { QMessageBox( QMessageBox::Critical, Root::instance()->mainWindow()->windowTitle(), QString( "Cannot launch python console because DBus is not available"), QMessageBox::Ok, Root::instance()->mainWindow()) .exec(); return; } QStringList args; #if !defined(Q_OS_MACOS) // TODO: clean up args << "--"; #endif args << Root::instance()->directoryManager()->pythonExecutable(); args << "-i"; args << "-u"; args << "-c"; QString escapedPythonLibDirs = escapePythonStringArray( vx::Root::instance()->directoryManager()->allPythonLibDirs()); args << "import sys; sys.path = " + escapedPythonLibDirs + " + sys.path; " + "import numpy as np; import voxie; args = " "voxie.parser.parse_args(); context = " "voxie.VoxieContext(args); instance = " "context.createInstance();"; auto output = createQSharedPointer<QString>(); #if defined(Q_OS_MACOS) service->addArgumentsTo(args); QString command = escapeArguments(args); QString script = "tell application \"Terminal\" to do script " + appleScriptEscape(command); qDebug() << script.toUtf8().data(); QStringList osascriptArgs; osascriptArgs << "-e"; osascriptArgs << script; auto process = new QProcess(); Root::instance()->scriptLauncher()->setupEnvironment( process, false); // Set PYTHONPATH etc. process->setProgram("osascript"); process->setArguments(osascriptArgs); process->start(); #else auto process = Root::instance()->scriptLauncher()->startScript( "gnome-terminal", nullptr, args, new QProcess(), output, false); #endif // TODO: Move parts to ScriptLauncher? // TODO: This should be done before the process is started #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QObject::connect( process, &QProcess::errorOccurred, Root::instance(), [](QProcess::ProcessError error) { QMessageBox(QMessageBox::Critical, "Error while starting python console", QString() + "Error while starting python console: " + QVariant::fromValue(error).toString(), QMessageBox::Ok) .exec(); }); #endif QObject::connect( process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>( &QProcess::finished), Root::instance(), [output](int exitCode, QProcess::ExitStatus exitStatus) { if (exitStatus != QProcess::NormalExit || exitCode != 0) { QString scriptOutputString = *output; if (scriptOutputString != "") scriptOutputString = "\n\nScript output:\n" + scriptOutputString; QMessageBox(QMessageBox::Critical, "Error while starting python console", QString() + "Error while starting python console: " + QVariant::fromValue(exitStatus).toString() + ", code = " + QString::number(exitCode) + scriptOutputString, QMessageBox::Ok) .exec(); } else { /* QString scriptOutputString = *output; if (scriptOutputString != "") { QMessageBox(QMessageBox::Warning, "Warnings while starting python console", QString() + "Warnings while starting python console:\n" + scriptOutputString, QMessageBox::Ok) .exec(); } */ } }); }); #endif this->scriptsMenu->addSeparator(); scriptsMenuStaticSize++; QAction* cascadeAction = this->windowMenu->addAction( QIcon(":/icons/applications-blue.png"), "&Cascade"); connect(cascadeAction, &QAction::triggered, [=]() -> void { this->mdiArea->cascadeSubWindows(); isTilePattern = false; }); QAction* tileAction = this->windowMenu->addAction( QIcon(":/icons/application-tile.png"), "&Tile"); connect(tileAction, &QAction::triggered, [=]() -> void { this->mdiArea->tileSubWindows(); isTilePattern = true; }); QAction* fillAction = this->windowMenu->addAction( QIcon(":/icons/application-blue.png"), "&Fill"); connect(fillAction, &QAction::triggered, [=]() -> void { QMdiSubWindow* subwindow = this->mdiArea->currentSubWindow(); if (subwindow == nullptr) { return; } subwindow->setWindowState(subwindow->windowState() | Qt::WindowMaximized); }); toggleTabbedAction = this->windowMenu->addAction( QIcon(":/icons/application-dock-tab.png"), "Ta&bbed"); toggleTabbedAction->setCheckable(true); connect(toggleTabbedAction, &QAction::toggled, [=]() -> void { bool checked = toggleTabbedAction->isChecked(); cascadeAction->setEnabled(!checked); tileAction->setEnabled(!checked); fillAction->setEnabled(!checked); if (checked) { this->mdiArea->setViewMode(QMdiArea::TabbedView); } else { this->mdiArea->setViewMode(QMdiArea::SubWindowView); this->setTilePattern(isTilePattern); } }); this->windowMenu->addSeparator(); QAction* helpShowAction = helpMenu->addAction(QIcon(":/icons/book-question.png"), "&Show help…"); connect(helpShowAction, &QAction::triggered, []() -> void { Root::instance()->helpLinkHandler()->handleLink( vx::help::uriForHelpTopic("main")); }); QAction* helpIndexAction = helpMenu->addAction(QIcon(":/icons/book-open-list.png"), "&Index…"); connect(helpIndexAction, &QAction::triggered, []() -> void { Root::instance()->helpLinkHandler()->handleLink( vx::help::uriForHelp("index")); }); QAction* oldManualAction = helpMenu->addAction(QIcon(":/icons/book-question.png"), "&Old manual…"); connect(oldManualAction, &QAction::triggered, this, [this]() -> void { auto oldManualFile = Root::instance()->directoryManager()->oldManualFile(); if (oldManualFile == "") QMessageBox(QMessageBox::Warning, this->windowTitle(), "Old manual file not found.", QMessageBox::Ok, this) .exec(); else QDesktopServices::openUrl(QUrl::fromLocalFile(oldManualFile)); }); QAction* homepageAction = helpMenu->addAction("&Homepage…"); connect(homepageAction, &QAction::triggered, []() -> void { QDesktopServices::openUrl( QUrl("https://github.com/voxie-viewer/voxie", QUrl::TolerantMode)); }); QAction* aboutAction = helpMenu->addAction(QIcon(":/icons/information.png"), "&About…"); connect(aboutAction, &QAction::triggered, this, [this]() -> void { AboutDialogWindow* aboutwindow = new AboutDialogWindow(this); aboutwindow->setAttribute(Qt::WA_DeleteOnClose); aboutwindow->exec(); }); this->setMenuBar(menu); } void CoreWindow::initStatusBar() { QStatusBar* statusBar = new QStatusBar(this); this->setStatusBar(statusBar); } void CoreWindow::initWidgets(vx::Root* root) { auto container = new QSplitter(Qt::Horizontal); { { this->mdiArea = new QMdiArea(this); this->mdiArea->setTabsClosable(true); sidePanel = new SidePanel(root, this); connect(sidePanel, &SidePanel::openFile, this, &CoreWindow::loadFile); connect(sidePanel, &SidePanel::nodeSelectionChanged, this, [this]() { Q_EMIT activeVisualizerProvider.nodeSelectionChanged( sidePanel->selectedNodes()); }); if (sidePanelOnLeft) { container->addWidget(sidePanel); container->addWidget(this->mdiArea); container->setCollapsible(1, false); } else { container->addWidget(this->mdiArea); container->setCollapsible(0, false); container->addWidget(sidePanel); } } } this->setCentralWidget(container); } void CoreWindow::populateScriptsMenu() { QList<QAction*> actions = this->scriptsMenu->actions(); for (int i = this->scriptsMenuStaticSize; i < actions.size(); i++) { this->scriptsMenu->removeAction(actions.at(i)); } for (auto scriptDirectory : Root::instance()->directoryManager()->scriptPath()) { QDir scriptDir = QDir(scriptDirectory); QStringList scripts = scriptDir.entryList(QStringList("*.js"), QDir::Files | QDir::Readable); for (QString script : scripts) { if (script.endsWith("~")) continue; QString scriptFile = scriptDirectory + "/" + script; if (QFileInfo(scriptFile).isExecutable()) continue; QString baseName = scriptFile; if (baseName.endsWith(".exe")) baseName = scriptFile.left(scriptFile.length() - 4); if (QFile::exists(baseName + ".json")) continue; QAction* action = this->scriptsMenu->addAction( QIcon(":/icons/script-attribute-j.png"), script); connect(action, &QAction::triggered, this, [scriptFile]() -> void { Root::instance()->execFile(scriptFile); }); } } this->scriptsMenu->addSeparator(); for (auto scriptDirectory : Root::instance()->directoryManager()->scriptPath()) { QDir scriptDir = QDir(scriptDirectory); QStringList scripts = scriptDir.entryList(QStringList("*"), QDir::Files | QDir::Readable); for (QString script : scripts) { if (script.endsWith("~")) continue; QString scriptFile = scriptDirectory + "/" + script; if (!QFileInfo(scriptFile).isExecutable()) continue; QString baseName = scriptFile; if (baseName.endsWith(".exe")) baseName = scriptFile.left(scriptFile.length() - 4); if (QFile::exists(baseName + ".json")) continue; QAction* action = this->scriptsMenu->addAction( QIcon(":/icons/script-attribute-e.png"), script); connect(action, &QAction::triggered, this, [scriptFile]() -> void { Root::instance()->scriptLauncher()->startScript(scriptFile); }); } } this->scriptsMenu->addSeparator(); { QStringList fileTypes; Root::instance()->settings()->beginGroup("scripting"); int sizeExternals = Root::instance()->settings()->beginReadArray("externals"); for (int i = 0; i < sizeExternals; ++i) { Root::instance()->settings()->setArrayIndex(i); fileTypes.append(Root::instance() ->settings() ->value("extension") .toString() .split(';')); } Root::instance()->settings()->endArray(); Root::instance()->settings()->endGroup(); if (!fileTypes.contains("*.py")) fileTypes << "*.py"; for (auto scriptDirectory : Root::instance()->directoryManager()->scriptPath()) { QDir scriptDir = QDir(scriptDirectory); QStringList externalScripts = scriptDir.entryList(fileTypes, QDir::Files | QDir::Readable); for (QString script : externalScripts) { if (script.endsWith("~")) continue; QString scriptFile = scriptDirectory + "/" + script; if (QFileInfo(scriptFile).isExecutable()) continue; QString baseName = scriptFile; if (baseName.endsWith(".exe")) baseName = scriptFile.left(scriptFile.length() - 4); if (QFile::exists(baseName + ".json")) continue; QAction* action = this->scriptsMenu->addAction( QIcon(":/icons/script-attribute-p.png"), script); connect( action, &QAction::triggered, this, [this, scriptFile]() -> void { Root::instance()->settings()->beginGroup("scripting"); int size = Root::instance()->settings()->beginReadArray("externals"); bool found = false; for (int i = 0; i < size; ++i) { Root::instance()->settings()->setArrayIndex(i); QString executable = Root::instance() ->settings() ->value("executable") .toString(); for (const QString& ext : Root::instance() ->settings() ->value("extension") .toString() .split(';')) { QRegExp regexp(ext, Qt::CaseInsensitive, QRegExp::WildcardUnix); if (regexp.exactMatch(scriptFile) == false) continue; Root::instance()->scriptLauncher()->startScript(scriptFile, &executable); found = true; break; } if (found) break; } if (!found && scriptFile.endsWith(".py")) { // startScript will handle python files Root::instance()->scriptLauncher()->startScript(scriptFile); found = true; } if (!found) QMessageBox(QMessageBox::Critical, this->windowTitle(), QString("Failed to find interpreter for script " + scriptFile), QMessageBox::Ok, this) .exec(); Root::instance()->settings()->endArray(); Root::instance()->settings()->endGroup(); }); } } } } bool CoreWindow::newSession() { // Only show the confirmation dialog if there are actually any datasets loaded // right now if (Root::instance()->nodes().size() > 0) { // Ask the user for confirmation before removing everything that's currently // loaded QMessageBox::StandardButton confirmation; confirmation = QMessageBox::warning(this, "Voxie", "Warning: This will close all currently loaded " "nodes.\nAre you sure?", QMessageBox::Yes | QMessageBox::No); // User selected Yes -> Destroy all datasets (and visualizers, slices) if (confirmation == QMessageBox::Yes) { clearNodes(); return true; } return false; } return true; } void CoreWindow::clearNodes() { for (const auto& node : Root::instance()->nodes()) { node->destroy(); } } void CoreWindow::loadFile() { new vx::OpenFileDialog(Root::instance(), this); } /** * @brief This method opens a file dialog to let the user save all currently * loaded files and settigns as a voxie project The project is then saved in a * script file, which can be used to load it again */ bool CoreWindow::saveProject() { SessionManager* sessionManager = new SessionManager(); vx::io::SaveFileDialog dialog(this, "Save as...", QString()); dialog.addFilter(FilenameFilter("Voxie Project", {"*.vxprj.py"}), nullptr); dialog.setup(); // TODO: This should be asynchronous if (dialog.exec() != QDialog::Accepted) return false; // Pass the selected filename and list of loaded datasets to the // SessionManager class, which handles saving and loading projects sessionManager->saveSession(dialog.selectedFiles().first()); return true; } void CoreWindow::loadProject() { SessionManager* sessionManager = new SessionManager(); QFileDialog dialog(this, "Select a Voxie Project or Node Group File..."); dialog.setDefaultSuffix("vxprj.py"); dialog.setAcceptMode(QFileDialog::AcceptOpen); dialog.setNameFilter("Voxie Project Files (*.vxprj.py *.ngrp.py)"); dialog.setOption(QFileDialog::DontUseNativeDialog, true); if (dialog.exec() != QDialog::Accepted) return; QString filename = dialog.selectedFiles().first(); sessionManager->loadSession(filename); } void CoreWindow::closeEvent(QCloseEvent* event) { // Skip the close dialog if there are no nodes if (vx::Root::instance()->nodes().size() > 0) { QMessageBox closeDialog; closeDialog.setText("Do you want to save your current project?"); closeDialog.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); closeDialog.setDefaultButton(QMessageBox::Save); closeDialog.setWindowIcon(QIcon(":/icons-voxie/voxel-data-32.png")); int ret = closeDialog.exec(); switch (ret) { case QMessageBox::Save: if (saveProject()) { closeDialog.close(); clearNodes(); event->accept(); } else { event->ignore(); } break; case QMessageBox::Discard: closeDialog.close(); clearNodes(); event->accept(); break; case QMessageBox::Cancel: event->ignore(); break; } } else { event->accept(); } }
37.785783
101
0.620542
voxie-viewer
e60342c0bd5023e82732e77bbba501b134e714f8
338
cpp
C++
ace/tao/orbsvcs/tests/EC_Throughput/ECT_Driver.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/orbsvcs/tests/EC_Throughput/ECT_Driver.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/orbsvcs/tests/EC_Throughput/ECT_Driver.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// ECT_Driver.cpp,v 1.8 1999/07/21 03:41:16 coryan Exp #include "ECT_Driver.h" #include "ace/High_Res_Timer.h" #if !defined (__ACE_INLINE__) #include "ECT_Driver.i" #endif /* __ACE_INLINE__ */ ACE_RCSID(EC_Throughput, ECT_Driver, "ECT_Driver.cpp,v 1.8 1999/07/21 03:41:16 coryan Exp") ECT_Driver::~ECT_Driver (void) { }
22.533333
92
0.701183
tharindusathis
e606d8c4f285ec6b7003f20ac139c639eb31ab64
723
cpp
C++
problems/lc1492/solution1.cpp
caohongjian/leetcode
bba854b407b1caa6a237ceb726592ff0458b3a29
[ "MIT" ]
1
2020-07-01T10:42:09.000Z
2020-07-01T10:42:09.000Z
problems/lc1492/solution1.cpp
murmur-wheel/leetcode
bba854b407b1caa6a237ceb726592ff0458b3a29
[ "MIT" ]
null
null
null
problems/lc1492/solution1.cpp
murmur-wheel/leetcode
bba854b407b1caa6a237ceb726592ff0458b3a29
[ "MIT" ]
null
null
null
// // Created by chj on 2020/7/3. // // https://leetcode-cn.com/problems/the-kth-factor-of-n/ #include <algorithm> #include <cmath> #include <iostream> #include <vector> // 先计算 n 的所有因子,然后排序 class Solution { public: int kthFactor(int n, int k) { std::vector<int> v; const int K = std::sqrt(n); for (int i = 1; i <= K; ++i) { // 如果 i 是 n 的因子,那么 n / i 也一定是 n 的因子 if (n % i == 0) { v.push_back(i); v.push_back(n / i); } } v.push_back(n); std::sort(v.begin(), v.end()); v.erase(std::unique(v.begin(), v.end()), v.end()); return k <= v.size() ? v[k - 1] : -1; } }; int main() { std::cout << "n = 100, k = 3, f = " << Solution().kthFactor(1000, 12); }
20.083333
72
0.518672
caohongjian
e607a84e0da2e6ead2c9ef694996341c13242b3a
376
cpp
C++
C++_Stroustrup/3-Objects,Types,Values/repeatWord.cpp
Cristo12345/CS_Review
7a0c60074a8a6d23f973e4e5e570e3ef22eec252
[ "MIT" ]
1
2020-07-17T01:54:43.000Z
2020-07-17T01:54:43.000Z
C++_Stroustrup/3-Objects,Types,Values/repeatWord.cpp
Cristo12345/CS_Review
7a0c60074a8a6d23f973e4e5e570e3ef22eec252
[ "MIT" ]
null
null
null
C++_Stroustrup/3-Objects,Types,Values/repeatWord.cpp
Cristo12345/CS_Review
7a0c60074a8a6d23f973e4e5e570e3ef22eec252
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { string prev = " "; string curr; int numOfWords = 0; while (cin >> curr) { numOfWords++; if (prev == curr) { cout << "word number " << numOfWords << '\n'; cout << "repeated word: " << curr << '\n'; } prev = curr; } return 0; }
15.666667
57
0.441489
Cristo12345
e60ce1a683fd10624ac4867548ce8a7124228753
352
hpp
C++
src/Graphics/Rect.hpp
ryu-raptor/amf
33a42cf1025ea512f23c4769a5be27d6a0c335bc
[ "MIT" ]
1
2020-05-31T02:25:39.000Z
2020-05-31T02:25:39.000Z
src/Graphics/Rect.hpp
ryu-raptor/amf
33a42cf1025ea512f23c4769a5be27d6a0c335bc
[ "MIT" ]
null
null
null
src/Graphics/Rect.hpp
ryu-raptor/amf
33a42cf1025ea512f23c4769a5be27d6a0c335bc
[ "MIT" ]
null
null
null
#include "Graphics/glHeaders.hpp" namespace Graphics { struct Rect { GLfloat width; GLfloat height; GLfloat x; GLfloat y; Rect(GLfloat x, GLfloat y, GLfloat width, GLfloat height) { this->width = width; this->height = height; this->x = x; this->y = y; } }; } // namespace Graphics
17.6
61
0.565341
ryu-raptor
e610989d946185f78f5fca7972a237425365bf05
1,933
cpp
C++
Test/PKTest/Native/Src/UART/UART.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
529
2015-03-10T00:17:45.000Z
2022-03-17T02:21:19.000Z
Test/PKTest/Native/Src/UART/UART.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
495
2015-03-10T22:02:46.000Z
2019-05-16T13:05:00.000Z
Test/PKTest/Native/Src/UART/UART.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
332
2015-03-10T08:04:36.000Z
2022-03-29T04:18:36.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "UART.h" //------------------------------------------------------------------------------ BOOL UART::UART_Receive(char * RecvBuffer, int MaxExpected, int MaxLoop) { INT16 CountReceived = 0; INT16 LoopCount=0; do { if (LoopCount++ > MaxLoop) { break; } CountReceived += USART_Read(UART::ComPort, &RecvBuffer[CountReceived], (sizeof (char)*(MaxExpected-CountReceived))); if (CountReceived >= MaxExpected) { return true; } if (!USART_Flush(UART::ComPort)) { Comment("Failed to flush"); return false; } } while(1); if (CountReceived < MaxExpected) { UART::Comment("wrong rcv count"); return false; } return true; } BOOL UART::UART_Transmit(char * XmitBuffer, int MaxToSend, int MaxLoop) { INT16 CountSent=0; INT16 LoopCount=0; do { if (LoopCount++ > MaxLoop) { break; } CountSent += USART_Write(UART::ComPort, &XmitBuffer[CountSent], (MaxToSend-CountSent)*sizeof(char)); if (CountSent >= MaxToSend) { return true; } } while(1); //if (!USART_Flush(UART::ComPort)) // { // Comment("Failed to flush"); // return false; //} return true; }
27.225352
201
0.375582
PervasiveDigital
e610f8c0a4ba877de1909e9d7f7231f6d42adcdc
612
hpp
C++
MemLeak/src/RenderTarget/RenderTarget.hpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
MemLeak/src/RenderTarget/RenderTarget.hpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
MemLeak/src/RenderTarget/RenderTarget.hpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
#pragma once // --------- Graphics -------- // #include "Texture/Texture.hpp" #include "Image/Image.hpp" #include "Sprite/Sprite.hpp" #include "Shape/Rect/Rectangle.hpp" #include "Shape/Line/Line.hpp" #include "Text/Text.hpp" namespace ml { class Image; class Sprite; class Rectangle; class Line; class Text; struct Color; class RenderTarget { public: virtual void clear(Color color) = 0; virtual void render(Sprite& sprite) = 0; virtual void render(Rectangle& rectangle) = 0; virtual void render(Line& line) = 0; virtual void render(Text& text) = 0; virtual void display() = 0; }; }
18.545455
48
0.678105
pk8868
e6130dcbaecdbfc71c41191cb6355739dbac954e
5,216
cpp
C++
Core/src/GFX/2D/Sprite.cpp
IridescentRose/Stardust-Engine
ee6a6b5841c16dddf367564a92eb263827631200
[ "MIT" ]
55
2020-10-07T01:54:49.000Z
2022-03-26T11:39:11.000Z
Core/src/GFX/2D/Sprite.cpp
IridescentRose/Ionia
ee6a6b5841c16dddf367564a92eb263827631200
[ "MIT" ]
15
2020-05-30T18:22:50.000Z
2020-08-08T11:01:36.000Z
Core/src/GFX/2D/Sprite.cpp
IridescentRose/Ionia
ee6a6b5841c16dddf367564a92eb263827631200
[ "MIT" ]
6
2020-10-22T11:09:47.000Z
2022-01-07T13:10:09.000Z
#include <GFX/2D/Sprite.h> namespace Stardust::GFX::Render2D{ Sprite::Sprite() { tex = -1; offset = { 0, 0 }; scaleFactor = { 1.0, 1.0 }; rotation = {0, 0}; } Sprite::~Sprite() { model.deleteData(); } Sprite::Sprite(unsigned int t) { rotation = {0, 0}; tex = t; Texture* tex2 = g_TextureManager->getTex(t); scaleFactor = { 1.0, 1.0 }; mesh.position = { -tex2->width / 2.0f,-tex2->height / 2.0f, 0, //0 tex2->width / 2.0f,-tex2->height / 2.0f, 0, //1 tex2->width / 2.0f, tex2->height / 2.0f, 0, //2 -tex2->width / 2.0f, tex2->height / 2.0f, 0, //3 }; mesh.color = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, }; Texture* tD = g_TextureManager->getTex(t); float hPercent = (float)tD->height / (float)tD->pHeight; float wPercent = (float)tD->width / (float)tD->pWidth; mesh.uv = { 0, 0, wPercent, 0, wPercent, hPercent, 0, hPercent }; mesh.indices = { 3, 2, 1, 1, 0, 3 }; model.addData(mesh); } Sprite::Sprite(unsigned int t, glm::vec2 size) { rotation = {0, 0}; tex = t; scaleFactor = { 1.0, 1.0 }; mesh.position = { -size.x / 2.0f,-size.y / 2.0f, 0, //0 size.x / 2.0f,-size.y / 2.0f, 0, //1 size.x/2.0f, size.y/2.0f, 0, //2 -size.x / 2.0f, size.y / 2.0f, 0, //3 }; mesh.color = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, }; Texture* tD = g_TextureManager->getTex(t); float hPercent = (float)tD->height / (float)tD->pHeight; float wPercent = (float)tD->width / (float)tD->pWidth; mesh.uv = { 0, 0, wPercent, 0, wPercent, hPercent, 0, hPercent }; mesh.indices = { 3, 2, 1, 1, 0, 3 }; model.addData(mesh); } Sprite::Sprite(unsigned int t, glm::vec2 pos, glm::vec2 extent) { tex = t; rotation = {0, 0}; scaleFactor = { 1.0, 1.0 }; Texture* tD = g_TextureManager->getTex(t); mesh.color = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, }; float hstart = (float)pos.y / (float)tD->pHeight; float wstart = (float)pos.x / (float)tD->pWidth; float hPercent = (float)(pos.y + extent.y) / (float)tD->pHeight; float wPercent = (float)(pos.x + extent.x) / (float)tD->pWidth; mesh.uv = { wstart, hstart, wPercent, hstart, wPercent, hPercent, wstart, hPercent, }; mesh.position = { -extent.x / 2.0f,-extent.y / 2.0f, 0, //0 extent.x / 2.0f,-extent.y / 2.0f, 0, //1 extent.x / 2.0f, extent.y / 2.0f, 0, //2 -extent.x / 2.0f, extent.y / 2.0f, 0, //3 }; mesh.indices = { 3, 2, 1, 1, 0, 3 }; model.addData(mesh); } void Sprite::setLayer(int i) { mesh.position.clear(); mesh.position[0*3 + 2] = i; mesh.position[1*3 + 2] = i; mesh.position[2*3 + 2] = i; mesh.position[3*3 + 2] = i; model.addData(mesh); } void Sprite::setPosition(float x, float y) { offset = { x, y }; } void Sprite::setScale(float x, float y) { scaleFactor = { x, y }; } void Sprite::setColor(float r, float g, float b, float a) { mesh.color.clear(); mesh.color = { r, g, b, a, r, g, b, a, r, g, b, a, r, g, b, a, }; model.addData(mesh); } void Sprite::setTexture(unsigned int t) { tex = t; } void Sprite::rotate(float x, float y){ rotation = {x, y}; } void Sprite::draw() { //Matrix translation GFX::pushMatrix(); GFX::clearModelMatrix(); GFX::translateModelMatrix(glm::vec3(offset.x, offset.y, 1.0f)); GFX::pushMatrix(); GFX::scaleModelMatrix(glm::vec3(scaleFactor.x, scaleFactor.y, 1.0f)); GFX::pushMatrix(); GFX::rotateModelMatrix({ rotation.x, rotation.y, 0.0f }); g_TextureManager->bindTex(tex); model.draw(); GFX::popMatrix(); GFX::popMatrix(); GFX::popMatrix(); } void Sprite::setAmbientLight(AmbientLight light) { ambient = light; } void Sprite::addPointLight(PointLight light) { pointLights.push_back(light); } void Sprite::calculateLighting() { uint8_t r = (float)ambient.r * ambient.intensity; uint8_t g = (float)ambient.g * ambient.intensity; uint8_t b = (float)ambient.b * ambient.intensity; for (auto p : pointLights) { float distance = sqrtf((p.x - offset.x * 2.0f) * (p.x - offset.x * 2.0f) + (p.y - offset.y * 2.0f) * (p.y - offset.y * 2.0f)); float corrRange = (p.range * 10 - distance) / (p.range * 10); float intensityMax = 1.0f - ambient.intensity; float intensity = 0.0f; if (p.intensity > intensityMax) { intensity = intensityMax; } else { intensity = p.intensity; } if (corrRange > 1.0f) { corrRange = 1.0f; } if (corrRange > 0.0f) { r += ((float)p.r) * intensity * corrRange; g += ((float)p.g) * intensity * corrRange; b += ((float)p.b) * intensity * corrRange; } if (r > 255) { r = 255; } if (g > 255) { g = 255; } if (b > 255) { b = 255; } if (r < 0) { r = 0; } if (g < 0) { g = 0; } if (b < 0) { b = 0; } } setColor( (float)r / 255.0f, (float)g / 255.0f, (float)b / 255.0f, 1.0f); } void Sprite::clearPointLights() { pointLights.clear(); } }
19.247232
129
0.555982
IridescentRose
e6137e1213075a4ffa5b550c166c09083c776d65
2,326
cpp
C++
source/engine/resource/serialization.cpp
compix/Monte-Carlo-Raytracer
f27842c40dd380aee78f1579873341ad6cfe0834
[ "MIT" ]
3
2018-09-23T03:12:36.000Z
2021-12-01T08:30:43.000Z
source/engine/resource/serialization.cpp
compix/Monte-Carlo-Raytracer
f27842c40dd380aee78f1579873341ad6cfe0834
[ "MIT" ]
null
null
null
source/engine/resource/serialization.cpp
compix/Monte-Carlo-Raytracer
f27842c40dd380aee78f1579873341ad6cfe0834
[ "MIT" ]
1
2018-09-19T01:49:24.000Z
2018-09-19T01:49:24.000Z
#include "serialization.h" #include "Model.h" // ****************************** Model ****************************** void Serializer::write(std::ofstream& os, const Model& model) { write(os, model.name); write(os, model.position); write(os, model.scale); write(os, model.rotation); // Number of SubMeshes write(os, model.subMeshes.size()); // SubMehes for (auto& sm : model.subMeshes) { writeVector(os, sm.indices); writeVector(os, sm.vertices); writeVector(os, sm.normals); writeVector(os, sm.tangents); writeVector(os, sm.bitangents); writeVector(os, sm.uvs); writeVector(os, sm.colors); } writeVector(os, model.materials); // Number of children write(os, model.children.size()); // Children for (auto& child : model.children) { write(os, *child); } } void Serializer::write(const std::string& absPath, const Model& model) { std::ofstream os(absPath, std::ios::binary); if (os.is_open()) { write(os, model); } else { LOG_ERROR("Failed to create file " << absPath); } } std::shared_ptr<Model> Serializer::readModel(std::ifstream& is) { std::shared_ptr<Model> model = std::make_shared<Model>(); read(is, model->name); model->position = read<glm::vec3>(is); model->scale = read<glm::vec3>(is); model->rotation = read<glm::quat>(is); // Number of SubMeshes model->subMeshes.resize(read<size_t>(is)); // SubMeshes for (size_t i = 0; i < model->subMeshes.size(); ++i) { Mesh::SubMesh& subMesh = model->subMeshes[i]; readVector(is, subMesh.indices); readVector(is, subMesh.vertices); readVector(is, subMesh.normals); readVector(is, subMesh.tangents); readVector(is, subMesh.bitangents); readVector(is, subMesh.uvs); readVector(is, subMesh.colors); } readVector(is, model->materials); // Number of children model->children.resize(read<size_t>(is)); // Children for (size_t i = 0; i < model->children.size(); ++i) { model->children[i] = readModel(is); model->children[i]->parent = model.get(); } return model; } std::shared_ptr<Model> Serializer::readModel(const std::string& absPath) { std::ifstream is(absPath, std::ios::binary); return readModel(is); }
24.744681
72
0.607911
compix
e614e624c91cc738d46b06f29fe147800cbed3b6
4,991
cpp
C++
lammps-master/src/KOKKOS/npair_skip_kokkos.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/src/KOKKOS/npair_skip_kokkos.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/src/KOKKOS/npair_skip_kokkos.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "npair_skip_kokkos.h" #include "neighbor.h" #include "neigh_list_kokkos.h" #include "atom_kokkos.h" #include "atom_vec.h" #include "molecule.h" #include "domain.h" #include "my_page.h" #include "error.h" #include "atom_masks.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ template<class DeviceType> NPairSkipKokkos<DeviceType>::NPairSkipKokkos(LAMMPS *lmp) : NPair(lmp) { atomKK = (AtomKokkos *) atom; execution_space = ExecutionSpaceFromDevice<DeviceType>::space; d_inum = typename AT::t_int_scalar("npair_skip:inum"); } /* ---------------------------------------------------------------------- build skip list for subset of types from parent list works for half and full lists works for owned (non-ghost) list, also for ghost list iskip and ijskip flag which atom types and type pairs to skip if ghost, also store neighbors of ghost atoms & set inum,gnum correctly ------------------------------------------------------------------------- */ template<class DeviceType> void NPairSkipKokkos<DeviceType>::build(NeighList *list) { atomKK->sync(execution_space,TYPE_MASK); type = atomKK->k_type.view<DeviceType>(); nlocal = atom->nlocal; NeighListKokkos<DeviceType>* k_list_skip = static_cast<NeighListKokkos<DeviceType>*>(list->listskip); d_ilist_skip = k_list_skip->d_ilist; d_numneigh_skip = k_list_skip->d_numneigh; d_neighbors_skip = k_list_skip->d_neighbors; num_skip = list->listskip->inum; if (list->ghost) num_skip += list->listskip->gnum; NeighListKokkos<DeviceType>* k_list = static_cast<NeighListKokkos<DeviceType>*>(list); k_list->maxneighs = k_list_skip->maxneighs; // simple, but could be made more memory efficient k_list->grow(atom->nmax); d_ilist = k_list->d_ilist; d_numneigh = k_list->d_numneigh; d_neighbors = k_list->d_neighbors; int ntypes = atom->ntypes; k_iskip = DAT::tdual_int_1d("npair_skip:iskip",ntypes+1); k_ijskip = DAT::tdual_int_2d("npair_skip:ijskip",ntypes+1,ntypes+1); d_iskip = k_iskip.view<DeviceType>(); d_ijskip = k_ijskip.view<DeviceType>(); for (int itype = 1; itype <= ntypes; itype++) { k_iskip.h_view(itype) = list->iskip[itype]; for (int jtype = 1; jtype <= ntypes; jtype++) { k_ijskip.h_view(itype,jtype) = list->ijskip[itype][jtype]; } } k_iskip.modify<LMPHostType>(); k_ijskip.modify<LMPHostType>(); k_iskip.sync<DeviceType>(); k_ijskip.sync<DeviceType>(); // loop over atoms in other list // skip I atom entirely if iskip is set for type[I] // skip I,J pair if ijskip is set for type[I],type[J] copymode = 1; Kokkos::parallel_scan(Kokkos::RangePolicy<DeviceType, TagNPairSkipCompute>(0,num_skip),*this); auto h_inum = Kokkos::create_mirror_view(d_inum); Kokkos::deep_copy(h_inum,d_inum); const int inum = h_inum(); list->inum = inum; if (list->ghost) { int num = 0; Kokkos::parallel_reduce(Kokkos::RangePolicy<DeviceType, TagNPairSkipCountLocal>(0,inum),*this,num); list->inum = num; list->gnum = inum - num; } copymode = 0; } template<class DeviceType> KOKKOS_INLINE_FUNCTION void NPairSkipKokkos<DeviceType>::operator()(TagNPairSkipCompute, const int &ii, int &inum, const bool &final) const { const int i = d_ilist_skip(ii); const int itype = type(i); if (!d_iskip(itype)) { if (final) { int n = 0; // loop over parent non-skip list const int jnum = d_numneigh_skip(i); const AtomNeighbors neighbors_i = AtomNeighbors(&d_neighbors(i,0),d_numneigh(i), &d_neighbors(i,1)-&d_neighbors(i,0)); for (int jj = 0; jj < jnum; jj++) { const int joriginal = d_neighbors_skip(i,jj); int j = joriginal & NEIGHMASK; if (d_ijskip(itype,type(j))) continue; neighbors_i(n++) = joriginal; } d_numneigh(i) = n; d_ilist(inum) = i; } inum++; } if (final) { if (ii == num_skip-1) d_inum() = inum; } } template<class DeviceType> KOKKOS_INLINE_FUNCTION void NPairSkipKokkos<DeviceType>::operator()(TagNPairSkipCountLocal, const int &i, int &num) const { if (d_ilist[i] < nlocal) num++; } namespace LAMMPS_NS { template class NPairSkipKokkos<LMPDeviceType>; #ifdef KOKKOS_ENABLE_CUDA template class NPairSkipKokkos<LMPHostType>; #endif }
31.588608
118
0.646764
rajkubp020
e6161a37befbd06765140d51a77698fabb16a6e3
735
cpp
C++
Pat/pat1002.cpp
yuanyangwangTJ/algorithm
ab7a959a00f290a0adc9af278f9a5de60be22af1
[ "MIT" ]
null
null
null
Pat/pat1002.cpp
yuanyangwangTJ/algorithm
ab7a959a00f290a0adc9af278f9a5de60be22af1
[ "MIT" ]
null
null
null
Pat/pat1002.cpp
yuanyangwangTJ/algorithm
ab7a959a00f290a0adc9af278f9a5de60be22af1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void read( int n,char num[10][5]); int main() { char num[10][5] = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"}; cout<<"please input a num:"<<endl; int count = 0,n; int t = getchar(); while( t !='\n' ) { n = t - '0'; count += n; t = getchar(); } read( count,num ); return 0; } void read( int n,char num[10][5] ) { int t; int cnt = 1; t = n; for( cnt=1;t>10; ) { t /= 10; cnt *= 10; } int rest; for( ;cnt>0;) { rest = n/cnt; n %= cnt; cnt /= 10; cout<<num[rest]; if(cnt>0) cout<<" "; } }
18.846154
80
0.391837
yuanyangwangTJ
e617089bd6c9eb600762cff365e64a2b28d381ad
35,615
cc
C++
mysql-server/storage/perfschema/table_events_statements.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/perfschema/table_events_statements.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/perfschema/table_events_statements.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2010, 2020, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file storage/perfschema/table_events_statements.cc Table EVENTS_STATEMENTS_xxx (implementation). */ #include "storage/perfschema/table_events_statements.h" #include <stddef.h> #include "my_compiler.h" #include "my_dbug.h" #include "my_thread.h" #include "sql/plugin_table.h" #include "sql/sp_head.h" /* TYPE_ENUM_FUNCTION, ... */ #include "sql/table.h" #include "storage/perfschema/pfs_buffer_container.h" #include "storage/perfschema/pfs_events_statements.h" #include "storage/perfschema/pfs_instr.h" #include "storage/perfschema/pfs_instr_class.h" #include "storage/perfschema/pfs_timer.h" #include "storage/perfschema/table_helper.h" THR_LOCK table_events_statements_current::m_table_lock; Plugin_table table_events_statements_current::m_table_def( /* Schema name */ "performance_schema", /* Name */ "events_statements_current", /* Definition */ " THREAD_ID BIGINT unsigned not null,\n" " EVENT_ID BIGINT unsigned not null,\n" " END_EVENT_ID BIGINT unsigned,\n" " EVENT_NAME VARCHAR(128) not null,\n" " SOURCE VARCHAR(64),\n" " TIMER_START BIGINT unsigned,\n" " TIMER_END BIGINT unsigned,\n" " TIMER_WAIT BIGINT unsigned,\n" " LOCK_TIME BIGINT unsigned not null,\n" " SQL_TEXT LONGTEXT,\n" " DIGEST VARCHAR(64),\n" " DIGEST_TEXT LONGTEXT,\n" " CURRENT_SCHEMA VARCHAR(64),\n" " OBJECT_TYPE VARCHAR(64),\n" " OBJECT_SCHEMA VARCHAR(64),\n" " OBJECT_NAME VARCHAR(64),\n" " OBJECT_INSTANCE_BEGIN BIGINT unsigned,\n" " MYSQL_ERRNO INTEGER,\n" " RETURNED_SQLSTATE VARCHAR(5),\n" " MESSAGE_TEXT VARCHAR(128),\n" " ERRORS BIGINT unsigned not null,\n" " WARNINGS BIGINT unsigned not null,\n" " ROWS_AFFECTED BIGINT unsigned not null,\n" " ROWS_SENT BIGINT unsigned not null,\n" " ROWS_EXAMINED BIGINT unsigned not null,\n" " CREATED_TMP_DISK_TABLES BIGINT unsigned not null,\n" " CREATED_TMP_TABLES BIGINT unsigned not null,\n" " SELECT_FULL_JOIN BIGINT unsigned not null,\n" " SELECT_FULL_RANGE_JOIN BIGINT unsigned not null,\n" " SELECT_RANGE BIGINT unsigned not null,\n" " SELECT_RANGE_CHECK BIGINT unsigned not null,\n" " SELECT_SCAN BIGINT unsigned not null,\n" " SORT_MERGE_PASSES BIGINT unsigned not null,\n" " SORT_RANGE BIGINT unsigned not null,\n" " SORT_ROWS BIGINT unsigned not null,\n" " SORT_SCAN BIGINT unsigned not null,\n" " NO_INDEX_USED BIGINT unsigned not null,\n" " NO_GOOD_INDEX_USED BIGINT unsigned not null,\n" " NESTING_EVENT_ID BIGINT unsigned,\n" " NESTING_EVENT_TYPE ENUM('TRANSACTION', 'STATEMENT', 'STAGE', 'WAIT'),\n" " NESTING_EVENT_LEVEL INTEGER,\n" " STATEMENT_ID BIGINT unsigned,\n" " PRIMARY KEY (THREAD_ID, EVENT_ID) USING HASH\n", /* Options */ " ENGINE=PERFORMANCE_SCHEMA", /* Tablespace */ nullptr); PFS_engine_table_share table_events_statements_current::m_share = { &pfs_truncatable_acl, table_events_statements_current::create, nullptr, /* write_row */ table_events_statements_current::delete_all_rows, table_events_statements_current::get_row_count, sizeof(pos_events_statements_current), /* ref length */ &m_table_lock, &m_table_def, false, /* perpetual */ PFS_engine_table_proxy(), {0}, false /* m_in_purgatory */ }; THR_LOCK table_events_statements_history::m_table_lock; Plugin_table table_events_statements_history::m_table_def( /* Schema name */ "performance_schema", /* Name */ "events_statements_history", /* Definition */ " THREAD_ID BIGINT unsigned not null,\n" " EVENT_ID BIGINT unsigned not null,\n" " END_EVENT_ID BIGINT unsigned,\n" " EVENT_NAME VARCHAR(128) not null,\n" " SOURCE VARCHAR(64),\n" " TIMER_START BIGINT unsigned,\n" " TIMER_END BIGINT unsigned,\n" " TIMER_WAIT BIGINT unsigned,\n" " LOCK_TIME BIGINT unsigned not null,\n" " SQL_TEXT LONGTEXT,\n" " DIGEST VARCHAR(64),\n" " DIGEST_TEXT LONGTEXT,\n" " CURRENT_SCHEMA VARCHAR(64),\n" " OBJECT_TYPE VARCHAR(64),\n" " OBJECT_SCHEMA VARCHAR(64),\n" " OBJECT_NAME VARCHAR(64),\n" " OBJECT_INSTANCE_BEGIN BIGINT unsigned,\n" " MYSQL_ERRNO INTEGER,\n" " RETURNED_SQLSTATE VARCHAR(5),\n" " MESSAGE_TEXT VARCHAR(128),\n" " ERRORS BIGINT unsigned not null,\n" " WARNINGS BIGINT unsigned not null,\n" " ROWS_AFFECTED BIGINT unsigned not null,\n" " ROWS_SENT BIGINT unsigned not null,\n" " ROWS_EXAMINED BIGINT unsigned not null,\n" " CREATED_TMP_DISK_TABLES BIGINT unsigned not null,\n" " CREATED_TMP_TABLES BIGINT unsigned not null,\n" " SELECT_FULL_JOIN BIGINT unsigned not null,\n" " SELECT_FULL_RANGE_JOIN BIGINT unsigned not null,\n" " SELECT_RANGE BIGINT unsigned not null,\n" " SELECT_RANGE_CHECK BIGINT unsigned not null,\n" " SELECT_SCAN BIGINT unsigned not null,\n" " SORT_MERGE_PASSES BIGINT unsigned not null,\n" " SORT_RANGE BIGINT unsigned not null,\n" " SORT_ROWS BIGINT unsigned not null,\n" " SORT_SCAN BIGINT unsigned not null,\n" " NO_INDEX_USED BIGINT unsigned not null,\n" " NO_GOOD_INDEX_USED BIGINT unsigned not null,\n" " NESTING_EVENT_ID BIGINT unsigned,\n" " NESTING_EVENT_TYPE ENUM('TRANSACTION', 'STATEMENT', 'STAGE', 'WAIT'),\n" " NESTING_EVENT_LEVEL INTEGER,\n" " STATEMENT_ID BIGINT unsigned,\n" " PRIMARY KEY (THREAD_ID, EVENT_ID) USING HASH\n", /* Options */ " ENGINE=PERFORMANCE_SCHEMA", /* Tablespace */ nullptr); PFS_engine_table_share table_events_statements_history::m_share = { &pfs_truncatable_acl, table_events_statements_history::create, nullptr, /* write_row */ table_events_statements_history::delete_all_rows, table_events_statements_history::get_row_count, sizeof(pos_events_statements_history), /* ref length */ &m_table_lock, &m_table_def, false, /* perpetual */ PFS_engine_table_proxy(), {0}, false /* m_in_purgatory */ }; THR_LOCK table_events_statements_history_long::m_table_lock; Plugin_table table_events_statements_history_long::m_table_def( /* Schema name */ "performance_schema", /* Name */ "events_statements_history_long", /* Definition */ " THREAD_ID BIGINT unsigned not null,\n" " EVENT_ID BIGINT unsigned not null,\n" " END_EVENT_ID BIGINT unsigned,\n" " EVENT_NAME VARCHAR(128) not null,\n" " SOURCE VARCHAR(64),\n" " TIMER_START BIGINT unsigned,\n" " TIMER_END BIGINT unsigned,\n" " TIMER_WAIT BIGINT unsigned,\n" " LOCK_TIME BIGINT unsigned not null,\n" " SQL_TEXT LONGTEXT,\n" " DIGEST VARCHAR(64),\n" " DIGEST_TEXT LONGTEXT,\n" " CURRENT_SCHEMA VARCHAR(64),\n" " OBJECT_TYPE VARCHAR(64),\n" " OBJECT_SCHEMA VARCHAR(64),\n" " OBJECT_NAME VARCHAR(64),\n" " OBJECT_INSTANCE_BEGIN BIGINT unsigned,\n" " MYSQL_ERRNO INTEGER,\n" " RETURNED_SQLSTATE VARCHAR(5),\n" " MESSAGE_TEXT VARCHAR(128),\n" " ERRORS BIGINT unsigned not null,\n" " WARNINGS BIGINT unsigned not null,\n" " ROWS_AFFECTED BIGINT unsigned not null,\n" " ROWS_SENT BIGINT unsigned not null,\n" " ROWS_EXAMINED BIGINT unsigned not null,\n" " CREATED_TMP_DISK_TABLES BIGINT unsigned not null,\n" " CREATED_TMP_TABLES BIGINT unsigned not null,\n" " SELECT_FULL_JOIN BIGINT unsigned not null,\n" " SELECT_FULL_RANGE_JOIN BIGINT unsigned not null,\n" " SELECT_RANGE BIGINT unsigned not null,\n" " SELECT_RANGE_CHECK BIGINT unsigned not null,\n" " SELECT_SCAN BIGINT unsigned not null,\n" " SORT_MERGE_PASSES BIGINT unsigned not null,\n" " SORT_RANGE BIGINT unsigned not null,\n" " SORT_ROWS BIGINT unsigned not null,\n" " SORT_SCAN BIGINT unsigned not null,\n" " NO_INDEX_USED BIGINT unsigned not null,\n" " NO_GOOD_INDEX_USED BIGINT unsigned not null,\n" " NESTING_EVENT_ID BIGINT unsigned,\n" " NESTING_EVENT_TYPE ENUM('TRANSACTION', 'STATEMENT', 'STAGE', 'WAIT'),\n" " NESTING_EVENT_LEVEL INTEGER,\n" " STATEMENT_ID BIGINT unsigned\n", /* Options */ " ENGINE=PERFORMANCE_SCHEMA", /* Tablespace */ nullptr); PFS_engine_table_share table_events_statements_history_long::m_share = { &pfs_truncatable_acl, table_events_statements_history_long::create, nullptr, /* write_row */ table_events_statements_history_long::delete_all_rows, table_events_statements_history_long::get_row_count, sizeof(PFS_simple_index), /* ref length */ &m_table_lock, &m_table_def, false, /* perpetual */ PFS_engine_table_proxy(), {0}, false /* m_in_purgatory */ }; bool PFS_index_events_statements::match(PFS_thread *pfs) { if (m_fields >= 1) { if (!m_key_1.match(pfs)) { return false; } } return true; } bool PFS_index_events_statements::match(PFS_events *pfs) { if (m_fields >= 2) { if (!m_key_2.match(pfs)) { return false; } } return true; } table_events_statements_common::table_events_statements_common( const PFS_engine_table_share *share, void *pos) : PFS_engine_table(share, pos) { m_normalizer = time_normalizer::get_statement(); } /** Build a row, part 1. This method is used while holding optimist locks. @param statement The statement the cursor is reading @param [out] digest Saved copy of the statement digest @return 0 on success or HA_ERR_RECORD_DELETED */ int table_events_statements_common::make_row_part_1( PFS_events_statements *statement, sql_digest_storage *digest) { ulonglong timer_end; PFS_statement_class *unsafe = (PFS_statement_class *)statement->m_class; PFS_statement_class *klass = sanitize_statement_class(unsafe); if (unlikely(klass == nullptr)) { return HA_ERR_RECORD_DELETED; } m_row.m_thread_internal_id = statement->m_thread_internal_id; m_row.m_statement_id = statement->m_statement_id; m_row.m_event_id = statement->m_event_id; m_row.m_end_event_id = statement->m_end_event_id; m_row.m_nesting_event_id = statement->m_nesting_event_id; m_row.m_nesting_event_type = statement->m_nesting_event_type; m_row.m_nesting_event_level = statement->m_nesting_event_level; if (m_row.m_end_event_id == 0) { timer_end = get_statement_timer(); } else { timer_end = statement->m_timer_end; } m_normalizer->to_pico(statement->m_timer_start, timer_end, &m_row.m_timer_start, &m_row.m_timer_end, &m_row.m_timer_wait); m_row.m_lock_time = statement->m_lock_time * MICROSEC_TO_PICOSEC; m_row.m_name = klass->m_name; m_row.m_name_length = klass->m_name_length; m_row.m_current_schema_name_length = statement->m_current_schema_name_length; if (m_row.m_current_schema_name_length > 0) memcpy(m_row.m_current_schema_name, statement->m_current_schema_name, m_row.m_current_schema_name_length); m_row.m_object_type = statement->m_sp_type; m_row.m_schema_name_length = statement->m_schema_name_length; if (m_row.m_schema_name_length > 0) memcpy(m_row.m_schema_name, statement->m_schema_name, m_row.m_schema_name_length); m_row.m_object_name_length = statement->m_object_name_length; if (m_row.m_object_name_length > 0) memcpy(m_row.m_object_name, statement->m_object_name, m_row.m_object_name_length); make_source_column(statement->m_source_file, statement->m_source_line, m_row.m_source, sizeof(m_row.m_source), m_row.m_source_length); memcpy(m_row.m_message_text, statement->m_message_text, sizeof(m_row.m_message_text)); memcpy(m_row.m_sqlstate, statement->m_sqlstate, SQLSTATE_LENGTH); m_row.m_sql_errno = statement->m_sql_errno; m_row.m_error_count = statement->m_error_count; m_row.m_warning_count = statement->m_warning_count; m_row.m_rows_affected = statement->m_rows_affected; m_row.m_rows_sent = statement->m_rows_sent; m_row.m_rows_examined = statement->m_rows_examined; m_row.m_created_tmp_disk_tables = statement->m_created_tmp_disk_tables; m_row.m_created_tmp_tables = statement->m_created_tmp_tables; m_row.m_select_full_join = statement->m_select_full_join; m_row.m_select_full_range_join = statement->m_select_full_range_join; m_row.m_select_range = statement->m_select_range; m_row.m_select_range_check = statement->m_select_range_check; m_row.m_select_scan = statement->m_select_scan; m_row.m_sort_merge_passes = statement->m_sort_merge_passes; m_row.m_sort_range = statement->m_sort_range; m_row.m_sort_rows = statement->m_sort_rows; m_row.m_sort_scan = statement->m_sort_scan; m_row.m_no_index_used = statement->m_no_index_used; m_row.m_no_good_index_used = statement->m_no_good_index_used; /* Copy the digest storage. */ digest->copy(&statement->m_digest_storage); /* Format the sqltext string for output. */ format_sqltext(statement->m_sqltext, statement->m_sqltext_length, get_charset(statement->m_sqltext_cs_number, MYF(0)), statement->m_sqltext_truncated, m_row.m_sqltext); return 0; } /** Build a row, part 2. This method is used after all optimist locks have been released. @param [in] digest Statement digest to print in the row. @return 0 on success or HA_ERR_RECORD_DELETED */ int table_events_statements_common::make_row_part_2( const sql_digest_storage *digest) { /* Filling up statement digest information. */ size_t safe_byte_count = digest->m_byte_count; if (safe_byte_count > 0 && safe_byte_count <= pfs_max_digest_length) { /* Generate the DIGEST string from the digest */ DIGEST_HASH_TO_STRING(digest->m_hash, m_row.m_digest.m_digest); m_row.m_digest.m_digest_length = DIGEST_HASH_TO_STRING_LENGTH; /* Generate the DIGEST_TEXT string from the token array */ compute_digest_text(digest, &m_row.m_digest.m_digest_text); if (m_row.m_digest.m_digest_text.length() == 0) { m_row.m_digest.m_digest_length = 0; } } else { m_row.m_digest.m_digest_length = 0; m_row.m_digest.m_digest_text.length(0); } return 0; } int table_events_statements_common::read_row_values(TABLE *table, unsigned char *buf, Field **fields, bool read_all) { Field *f; uint len; /* Set the null bits */ DBUG_ASSERT(table->s->null_bytes == 3); buf[0] = 0; buf[1] = 0; buf[2] = 0; for (; (f = *fields); fields++) { if (read_all || bitmap_is_set(table->read_set, f->field_index())) { switch (f->field_index()) { case 0: /* THREAD_ID */ set_field_ulonglong(f, m_row.m_thread_internal_id); break; case 1: /* EVENT_ID */ set_field_ulonglong(f, m_row.m_event_id); break; case 2: /* END_EVENT_ID */ if (m_row.m_end_event_id > 0) { set_field_ulonglong(f, m_row.m_end_event_id - 1); } else { f->set_null(); } break; case 3: /* EVENT_NAME */ set_field_varchar_utf8(f, m_row.m_name, m_row.m_name_length); break; case 4: /* SOURCE */ set_field_varchar_utf8(f, m_row.m_source, m_row.m_source_length); break; case 5: /* TIMER_START */ if (m_row.m_timer_start != 0) { set_field_ulonglong(f, m_row.m_timer_start); } else { f->set_null(); } break; case 6: /* TIMER_END */ if (m_row.m_timer_end != 0) { set_field_ulonglong(f, m_row.m_timer_end); } else { f->set_null(); } break; case 7: /* TIMER_WAIT */ /* TIMER_START != 0 when TIMED=YES. */ if (m_row.m_timer_start != 0) { set_field_ulonglong(f, m_row.m_timer_wait); } else { f->set_null(); } break; case 8: /* LOCK_TIME */ if (m_row.m_lock_time != 0) { set_field_ulonglong(f, m_row.m_lock_time); } else { f->set_null(); } break; case 9: /* SQL_TEXT */ if (m_row.m_sqltext.length()) set_field_text(f, m_row.m_sqltext.ptr(), m_row.m_sqltext.length(), m_row.m_sqltext.charset()); else { f->set_null(); } break; case 10: /* DIGEST */ if (m_row.m_digest.m_digest_length > 0) set_field_varchar_utf8(f, m_row.m_digest.m_digest, m_row.m_digest.m_digest_length); else { f->set_null(); } break; case 11: /* DIGEST_TEXT */ if (m_row.m_digest.m_digest_text.length() > 0) set_field_blob(f, m_row.m_digest.m_digest_text.ptr(), (uint)m_row.m_digest.m_digest_text.length()); else { f->set_null(); } break; case 12: /* CURRENT_SCHEMA */ if (m_row.m_current_schema_name_length) set_field_varchar_utf8(f, m_row.m_current_schema_name, m_row.m_current_schema_name_length); else { f->set_null(); } break; case 13: /* OBJECT_TYPE */ if (m_row.m_object_name_length > 0) { set_field_object_type(f, m_row.m_object_type); } else { f->set_null(); } break; case 14: /* OBJECT_SCHEMA */ if (m_row.m_schema_name_length) set_field_varchar_utf8(f, m_row.m_schema_name, m_row.m_schema_name_length); else { f->set_null(); } break; case 15: /* OBJECT_NAME */ if (m_row.m_object_name_length) set_field_varchar_utf8(f, m_row.m_object_name, m_row.m_object_name_length); else { f->set_null(); } break; case 16: /* OBJECT_INSTANCE_BEGIN */ f->set_null(); break; case 17: /* MYSQL_ERRNO */ set_field_ulong(f, m_row.m_sql_errno); break; case 18: /* RETURNED_SQLSTATE */ if (m_row.m_sqlstate[0] != 0) { set_field_varchar_utf8(f, m_row.m_sqlstate, SQLSTATE_LENGTH); } else { f->set_null(); } break; case 19: /* MESSAGE_TEXT */ len = (uint)strlen(m_row.m_message_text); if (len) { set_field_varchar_utf8(f, m_row.m_message_text, len); } else { f->set_null(); } break; case 20: /* ERRORS */ set_field_ulonglong(f, m_row.m_error_count); break; case 21: /* WARNINGS */ set_field_ulonglong(f, m_row.m_warning_count); break; case 22: /* ROWS_AFFECTED */ set_field_ulonglong(f, m_row.m_rows_affected); break; case 23: /* ROWS_SENT */ set_field_ulonglong(f, m_row.m_rows_sent); break; case 24: /* ROWS_EXAMINED */ set_field_ulonglong(f, m_row.m_rows_examined); break; case 25: /* CREATED_TMP_DISK_TABLES */ set_field_ulonglong(f, m_row.m_created_tmp_disk_tables); break; case 26: /* CREATED_TMP_TABLES */ set_field_ulonglong(f, m_row.m_created_tmp_tables); break; case 27: /* SELECT_FULL_JOIN */ set_field_ulonglong(f, m_row.m_select_full_join); break; case 28: /* SELECT_FULL_RANGE_JOIN */ set_field_ulonglong(f, m_row.m_select_full_range_join); break; case 29: /* SELECT_RANGE */ set_field_ulonglong(f, m_row.m_select_range); break; case 30: /* SELECT_RANGE_CHECK */ set_field_ulonglong(f, m_row.m_select_range_check); break; case 31: /* SELECT_SCAN */ set_field_ulonglong(f, m_row.m_select_scan); break; case 32: /* SORT_MERGE_PASSES */ set_field_ulonglong(f, m_row.m_sort_merge_passes); break; case 33: /* SORT_RANGE */ set_field_ulonglong(f, m_row.m_sort_range); break; case 34: /* SORT_ROWS */ set_field_ulonglong(f, m_row.m_sort_rows); break; case 35: /* SORT_SCAN */ set_field_ulonglong(f, m_row.m_sort_scan); break; case 36: /* NO_INDEX_USED */ set_field_ulonglong(f, m_row.m_no_index_used); break; case 37: /* NO_GOOD_INDEX_USED */ set_field_ulonglong(f, m_row.m_no_good_index_used); break; case 38: /* NESTING_EVENT_ID */ if (m_row.m_nesting_event_id != 0) { set_field_ulonglong(f, m_row.m_nesting_event_id); } else { f->set_null(); } break; case 39: /* NESTING_EVENT_TYPE */ if (m_row.m_nesting_event_id != 0) { set_field_enum(f, m_row.m_nesting_event_type); } else { f->set_null(); } break; case 40: /* NESTING_EVENT_LEVEL */ set_field_ulong(f, m_row.m_nesting_event_level); break; case 41: /* STATEMENT_ID */ if (m_row.m_statement_id != 0) { set_field_ulonglong(f, m_row.m_statement_id); } else { f->set_null(); } break; default: DBUG_ASSERT(false); } } } return 0; } PFS_engine_table *table_events_statements_current::create( PFS_engine_table_share *) { return new table_events_statements_current(); } table_events_statements_current::table_events_statements_current() : table_events_statements_common(&m_share, &m_pos), m_pos(), m_next_pos() {} void table_events_statements_current::reset_position(void) { m_pos.reset(); m_next_pos.reset(); } int table_events_statements_current::rnd_init(bool) { return 0; } int table_events_statements_current::rnd_next(void) { PFS_thread *pfs_thread; PFS_events_statements *statement; bool has_more_thread = true; for (m_pos.set_at(&m_next_pos); has_more_thread; m_pos.next_thread()) { pfs_thread = global_thread_container.get(m_pos.m_index_1, &has_more_thread); if (pfs_thread != nullptr) { uint safe_events_statements_count = pfs_thread->m_events_statements_count; if (safe_events_statements_count == 0) { /* Display the last top level statement, when completed */ if (m_pos.m_index_2 >= 1) { continue; } } else { /* Display all pending statements, when in progress */ if (m_pos.m_index_2 >= safe_events_statements_count) { continue; } } statement = &pfs_thread->m_statement_stack[m_pos.m_index_2]; m_next_pos.set_after(&m_pos); return make_row(pfs_thread, statement); } } return HA_ERR_END_OF_FILE; } int table_events_statements_current::rnd_pos(const void *pos) { PFS_thread *pfs_thread; PFS_events_statements *statement; set_position(pos); pfs_thread = global_thread_container.get(m_pos.m_index_1); if (pfs_thread != nullptr) { uint safe_events_statements_count = pfs_thread->m_events_statements_count; if (safe_events_statements_count == 0) { /* Display the last top level statement, when completed */ if (m_pos.m_index_2 >= 1) { return HA_ERR_RECORD_DELETED; } } else { /* Display all pending statements, when in progress */ if (m_pos.m_index_2 >= safe_events_statements_count) { return HA_ERR_RECORD_DELETED; } } DBUG_ASSERT(m_pos.m_index_2 < statement_stack_max); statement = &pfs_thread->m_statement_stack[m_pos.m_index_2]; if (statement->m_class != nullptr) { return make_row(pfs_thread, statement); } } return HA_ERR_RECORD_DELETED; } int table_events_statements_current::index_next(void) { PFS_thread *pfs_thread; PFS_events_statements *statement; bool has_more_thread = true; for (m_pos.set_at(&m_next_pos); has_more_thread; m_pos.next_thread()) { pfs_thread = global_thread_container.get(m_pos.m_index_1, &has_more_thread); if (pfs_thread != nullptr) { if (m_opened_index->match(pfs_thread)) { do { uint safe_events_statements_count = pfs_thread->m_events_statements_count; if (safe_events_statements_count == 0) { /* Display the last top level statement, when completed */ if (m_pos.m_index_2 >= 1) { break; } } else { /* Display all pending statements, when in progress */ if (m_pos.m_index_2 >= safe_events_statements_count) { break; } } statement = &pfs_thread->m_statement_stack[m_pos.m_index_2]; if (statement->m_class != nullptr) { if (m_opened_index->match(statement)) { if (!make_row(pfs_thread, statement)) { m_next_pos.set_after(&m_pos); return 0; } } m_pos.set_after(&m_pos); } } while (statement->m_class != nullptr); } } } return HA_ERR_END_OF_FILE; } int table_events_statements_current::make_row( PFS_thread *pfs_thread, PFS_events_statements *statement) { sql_digest_storage digest; pfs_optimistic_state lock; pfs_optimistic_state stmt_lock; digest.reset(m_token_array, MAX_DIGEST_STORAGE_SIZE); /* Protect this reader against thread termination. */ pfs_thread->m_lock.begin_optimistic_lock(&lock); /* Protect this reader against writing on statement information. */ pfs_thread->m_stmt_lock.begin_optimistic_lock(&stmt_lock); if (table_events_statements_common::make_row_part_1(statement, &digest) != 0) { return HA_ERR_RECORD_DELETED; } if (!pfs_thread->m_stmt_lock.end_optimistic_lock(&stmt_lock) || !pfs_thread->m_lock.end_optimistic_lock(&lock)) { return HA_ERR_RECORD_DELETED; } return table_events_statements_common::make_row_part_2(&digest); } int table_events_statements_current::delete_all_rows(void) { reset_events_statements_current(); return 0; } ha_rows table_events_statements_current::get_row_count(void) { return global_thread_container.get_row_count() * statement_stack_max; } int table_events_statements_current::index_init(uint idx MY_ATTRIBUTE((unused)), bool) { PFS_index_events_statements *result; DBUG_ASSERT(idx == 0); result = PFS_NEW(PFS_index_events_statements); m_opened_index = result; m_index = result; return 0; } PFS_engine_table *table_events_statements_history::create( PFS_engine_table_share *) { return new table_events_statements_history(); } table_events_statements_history::table_events_statements_history() : table_events_statements_common(&m_share, &m_pos), m_pos(), m_next_pos() {} void table_events_statements_history::reset_position(void) { m_pos.reset(); m_next_pos.reset(); } int table_events_statements_history::rnd_init(bool) { return 0; } int table_events_statements_history::rnd_next(void) { PFS_thread *pfs_thread; PFS_events_statements *statement; bool has_more_thread = true; if (events_statements_history_per_thread == 0) { return HA_ERR_END_OF_FILE; } for (m_pos.set_at(&m_next_pos); has_more_thread; m_pos.next_thread()) { pfs_thread = global_thread_container.get(m_pos.m_index_1, &has_more_thread); if (pfs_thread != nullptr) { if (m_pos.m_index_2 >= events_statements_history_per_thread) { /* This thread does not have more (full) history */ continue; } if (!pfs_thread->m_statements_history_full && (m_pos.m_index_2 >= pfs_thread->m_statements_history_index)) { /* This thread does not have more (not full) history */ continue; } statement = &pfs_thread->m_statements_history[m_pos.m_index_2]; if (statement->m_class != nullptr) { /* Next iteration, look for the next history in this thread */ m_next_pos.set_after(&m_pos); return make_row(pfs_thread, statement); } } } return HA_ERR_END_OF_FILE; } int table_events_statements_history::rnd_pos(const void *pos) { PFS_thread *pfs_thread; PFS_events_statements *statement; DBUG_ASSERT(events_statements_history_per_thread != 0); set_position(pos); pfs_thread = global_thread_container.get(m_pos.m_index_1); if (pfs_thread != nullptr) { DBUG_ASSERT(m_pos.m_index_2 < events_statements_history_per_thread); if (!pfs_thread->m_statements_history_full && (m_pos.m_index_2 >= pfs_thread->m_statements_history_index)) { return HA_ERR_RECORD_DELETED; } statement = &pfs_thread->m_statements_history[m_pos.m_index_2]; if (statement->m_class != nullptr) { return make_row(pfs_thread, statement); } } return HA_ERR_RECORD_DELETED; } int table_events_statements_history::index_next(void) { PFS_thread *pfs_thread; PFS_events_statements *statement; bool has_more_thread = true; if (events_statements_history_per_thread == 0) { return HA_ERR_END_OF_FILE; } for (m_pos.set_at(&m_next_pos); has_more_thread; m_pos.next_thread()) { pfs_thread = global_thread_container.get(m_pos.m_index_1, &has_more_thread); if (pfs_thread != nullptr) { if (m_opened_index->match(pfs_thread)) { do { if (m_pos.m_index_2 >= events_statements_history_per_thread) { /* This thread does not have more (full) history */ break; } if (!pfs_thread->m_statements_history_full && (m_pos.m_index_2 >= pfs_thread->m_statements_history_index)) { /* This thread does not have more (not full) history */ break; } statement = &pfs_thread->m_statements_history[m_pos.m_index_2]; if (statement->m_class != nullptr) { if (m_opened_index->match(statement)) { if (!make_row(pfs_thread, statement)) { m_next_pos.set_after(&m_pos); return 0; } } m_pos.set_after(&m_pos); } } while (statement->m_class != nullptr); } } } return HA_ERR_END_OF_FILE; } int table_events_statements_history::make_row( PFS_thread *pfs_thread, PFS_events_statements *statement) { sql_digest_storage digest; pfs_optimistic_state lock; digest.reset(m_token_array, MAX_DIGEST_STORAGE_SIZE); /* Protect this reader against thread termination. */ pfs_thread->m_lock.begin_optimistic_lock(&lock); if (table_events_statements_common::make_row_part_1(statement, &digest) != 0) { return HA_ERR_RECORD_DELETED; } if (!pfs_thread->m_lock.end_optimistic_lock(&lock)) { return HA_ERR_RECORD_DELETED; } return table_events_statements_common::make_row_part_2(&digest); } int table_events_statements_history::delete_all_rows(void) { reset_events_statements_history(); return 0; } ha_rows table_events_statements_history::get_row_count(void) { return events_statements_history_per_thread * global_thread_container.get_row_count(); } int table_events_statements_history::index_init(uint idx MY_ATTRIBUTE((unused)), bool) { PFS_index_events_statements *result; DBUG_ASSERT(idx == 0); result = PFS_NEW(PFS_index_events_statements); m_opened_index = result; m_index = result; return 0; } PFS_engine_table *table_events_statements_history_long::create( PFS_engine_table_share *) { return new table_events_statements_history_long(); } table_events_statements_history_long::table_events_statements_history_long() : table_events_statements_common(&m_share, &m_pos), m_pos(0), m_next_pos(0) {} void table_events_statements_history_long::reset_position(void) { m_pos.m_index = 0; m_next_pos.m_index = 0; } int table_events_statements_history_long::rnd_init(bool) { return 0; } int table_events_statements_history_long::rnd_next(void) { PFS_events_statements *statement; size_t limit; if (events_statements_history_long_size == 0) { return HA_ERR_END_OF_FILE; } if (events_statements_history_long_full) { limit = events_statements_history_long_size; } else limit = events_statements_history_long_index.m_u32 % events_statements_history_long_size; for (m_pos.set_at(&m_next_pos); m_pos.m_index < limit; m_pos.next()) { statement = &events_statements_history_long_array[m_pos.m_index]; if (statement->m_class != nullptr) { /* Next iteration, look for the next entry */ m_next_pos.set_after(&m_pos); return make_row(statement); } } return HA_ERR_END_OF_FILE; } int table_events_statements_history_long::rnd_pos(const void *pos) { PFS_events_statements *statement; size_t limit; if (events_statements_history_long_size == 0) { return HA_ERR_RECORD_DELETED; } set_position(pos); if (events_statements_history_long_full) { limit = events_statements_history_long_size; } else limit = events_statements_history_long_index.m_u32 % events_statements_history_long_size; if (m_pos.m_index >= limit) { return HA_ERR_RECORD_DELETED; } statement = &events_statements_history_long_array[m_pos.m_index]; if (statement->m_class == nullptr) { return HA_ERR_RECORD_DELETED; } return make_row(statement); } int table_events_statements_history_long::make_row( PFS_events_statements *statement) { sql_digest_storage digest; digest.reset(m_token_array, MAX_DIGEST_STORAGE_SIZE); if (table_events_statements_common::make_row_part_1(statement, &digest) != 0) { return HA_ERR_RECORD_DELETED; } return table_events_statements_common::make_row_part_2(&digest); } int table_events_statements_history_long::delete_all_rows(void) { reset_events_statements_history_long(); return 0; } ha_rows table_events_statements_history_long::get_row_count(void) { return events_statements_history_long_size; }
33.662571
80
0.668567
silenc3502
e61f0b8fa40fda776d213a2fe4870cbafa49572d
65,710
cc
C++
sdk/sdk/share/linphone/coreapi/linphonecore_jni.cc
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
1
2021-10-09T08:05:50.000Z
2021-10-09T08:05:50.000Z
sdk/sdk/share/linphone/coreapi/linphonecore_jni.cc
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
null
null
null
sdk/sdk/share/linphone/coreapi/linphonecore_jni.cc
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
null
null
null
/* linphonecore_jni.cc Copyright (C) 2010 Belledonne Communications, Grenoble, France 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. */ #include <jni.h> #include "linphonecore_utils.h" #include <ortp/zrtp.h> #ifdef TUNNEL_ENABLED #include "linphone_tunnel.h" #endif extern "C" { #include "mediastreamer2/mediastream.h" } #include "mediastreamer2/msjava.h" #include "private.h" #include <cpu-features.h> #ifdef ANDROID #include <android/log.h> extern "C" void libmsilbc_init(); #ifdef HAVE_X264 extern "C" void libmsx264_init(); #endif #ifdef HAVE_AMR extern "C" void libmsamr_init(); #endif #ifdef HAVE_SILK extern "C" void libmssilk_init(); #endif #ifdef HAVE_G729 extern "C" void libmsbcg729_init(); #endif #endif /*ANDROID*/ static JavaVM *jvm=0; #ifdef ANDROID static void linphone_android_log_handler(OrtpLogLevel lev, const char *fmt, va_list args){ int prio; switch(lev){ case ORTP_DEBUG: prio = ANDROID_LOG_DEBUG; break; case ORTP_MESSAGE: prio = ANDROID_LOG_INFO; break; case ORTP_WARNING: prio = ANDROID_LOG_WARN; break; case ORTP_ERROR: prio = ANDROID_LOG_ERROR; break; case ORTP_FATAL: prio = ANDROID_LOG_FATAL; break; default: prio = ANDROID_LOG_DEFAULT; break; } __android_log_vprint(prio, LOG_DOMAIN, fmt, args); } int dumbMethodForAllowingUsageOfCpuFeaturesFromStaticLibMediastream() { return (android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM && (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0); } #endif /*ANDROID*/ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *ajvm, void *reserved) { #ifdef ANDROID ms_set_jvm(ajvm); #endif /*ANDROID*/ jvm=ajvm; return JNI_VERSION_1_2; } //LinphoneFactory extern "C" void Java_org_linphone_core_LinphoneCoreFactoryImpl_setDebugMode(JNIEnv* env ,jobject thiz ,jboolean isDebug) { if (isDebug) { linphone_core_enable_logs_with_cb(linphone_android_log_handler); } else { linphone_core_disable_logs(); } } // LinphoneCore class LinphoneCoreData { public: LinphoneCoreData(JNIEnv* env, jobject lc,jobject alistener, jobject auserdata) { core = env->NewGlobalRef(lc); listener = env->NewGlobalRef(alistener); userdata = auserdata?env->NewGlobalRef(auserdata):0; memset(&vTable,0,sizeof(vTable)); vTable.show = showInterfaceCb; vTable.auth_info_requested = authInfoRequested; vTable.display_status = displayStatusCb; vTable.display_message = displayMessageCb; vTable.display_warning = displayMessageCb; vTable.global_state_changed = globalStateChange; vTable.registration_state_changed = registrationStateChange; vTable.call_state_changed = callStateChange; vTable.call_encryption_changed = callEncryptionChange; vTable.text_received = text_received; vTable.new_subscription_request = new_subscription_request; vTable.notify_presence_recv = notify_presence_recv; listenerClass = (jclass)env->NewGlobalRef(env->GetObjectClass( alistener)); /*displayStatus(LinphoneCore lc,String message);*/ displayStatusId = env->GetMethodID(listenerClass,"displayStatus","(Lorg/linphone/core/LinphoneCore;Ljava/lang/String;)V"); /*void generalState(LinphoneCore lc,int state); */ globalStateId = env->GetMethodID(listenerClass,"globalState","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneCore$GlobalState;Ljava/lang/String;)V"); globalStateClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneCore$GlobalState")); globalStateFromIntId = env->GetStaticMethodID(globalStateClass,"fromInt","(I)Lorg/linphone/core/LinphoneCore$GlobalState;"); /*registrationState(LinphoneCore lc, LinphoneProxyConfig cfg, LinphoneCore.RegistrationState cstate, String smessage);*/ registrationStateId = env->GetMethodID(listenerClass,"registrationState","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneProxyConfig;Lorg/linphone/core/LinphoneCore$RegistrationState;Ljava/lang/String;)V"); registrationStateClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneCore$RegistrationState")); registrationStateFromIntId = env->GetStaticMethodID(registrationStateClass,"fromInt","(I)Lorg/linphone/core/LinphoneCore$RegistrationState;"); /*callState(LinphoneCore lc, LinphoneCall call, LinphoneCall.State cstate,String message);*/ callStateId = env->GetMethodID(listenerClass,"callState","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneCall;Lorg/linphone/core/LinphoneCall$State;Ljava/lang/String;)V"); callStateClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneCall$State")); callStateFromIntId = env->GetStaticMethodID(callStateClass,"fromInt","(I)Lorg/linphone/core/LinphoneCall$State;"); /*callEncryption(LinphoneCore lc, LinphoneCall call, boolean encrypted,String auth_token);*/ callEncryptionChangedId=env->GetMethodID(listenerClass,"callEncryptionChanged","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneCall;ZLjava/lang/String;)V"); /*void ecCalibrationStatus(LinphoneCore.EcCalibratorStatus status, int delay_ms, Object data);*/ ecCalibrationStatusId = env->GetMethodID(listenerClass,"ecCalibrationStatus","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneCore$EcCalibratorStatus;ILjava/lang/Object;)V"); ecCalibratorStatusClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneCore$EcCalibratorStatus")); ecCalibratorStatusFromIntId = env->GetStaticMethodID(ecCalibratorStatusClass,"fromInt","(I)Lorg/linphone/core/LinphoneCore$EcCalibratorStatus;"); /*void newSubscriptionRequest(LinphoneCore lc, LinphoneFriend lf, String url)*/ newSubscriptionRequestId = env->GetMethodID(listenerClass,"newSubscriptionRequest","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneFriend;Ljava/lang/String;)V"); /*void notifyPresenceReceived(LinphoneCore lc, LinphoneFriend lf);*/ notifyPresenceReceivedId = env->GetMethodID(listenerClass,"notifyPresenceReceived","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneFriend;)V"); /*void textReceived(LinphoneCore lc, LinphoneChatRoom cr,LinphoneAddress from,String message);*/ textReceivedId = env->GetMethodID(listenerClass,"textReceived","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneChatRoom;Lorg/linphone/core/LinphoneAddress;Ljava/lang/String;)V"); proxyClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneProxyConfigImpl")); proxyCtrId = env->GetMethodID(proxyClass,"<init>", "(J)V"); callClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneCallImpl")); callCtrId = env->GetMethodID(callClass,"<init>", "(J)V"); chatRoomClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneChatRoomImpl")); chatRoomCtrId = env->GetMethodID(chatRoomClass,"<init>", "(J)V"); friendClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneFriendImpl"));; friendCtrId =env->GetMethodID(friendClass,"<init>", "(J)V"); addressClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneAddressImpl")); addressCtrId =env->GetMethodID(addressClass,"<init>", "(J)V"); } ~LinphoneCoreData() { JNIEnv *env = 0; jvm->AttachCurrentThread(&env,NULL); env->DeleteGlobalRef(core); env->DeleteGlobalRef(listener); if (userdata) env->DeleteGlobalRef(userdata); env->DeleteGlobalRef(listenerClass); env->DeleteGlobalRef(globalStateClass); env->DeleteGlobalRef(registrationStateClass); env->DeleteGlobalRef(callStateClass); env->DeleteGlobalRef(proxyClass); env->DeleteGlobalRef(callClass); env->DeleteGlobalRef(chatRoomClass); env->DeleteGlobalRef(friendClass); } jobject core; jobject listener; jobject userdata; jclass listenerClass; jmethodID displayStatusId; jmethodID newSubscriptionRequestId; jmethodID notifyPresenceReceivedId; jmethodID textReceivedId; jclass globalStateClass; jmethodID globalStateId; jmethodID globalStateFromIntId; jclass registrationStateClass; jmethodID registrationStateId; jmethodID registrationStateFromIntId; jclass callStateClass; jmethodID callStateId; jmethodID callStateFromIntId; jmethodID callEncryptionChangedId; jclass ecCalibratorStatusClass; jmethodID ecCalibrationStatusId; jmethodID ecCalibratorStatusFromIntId; jclass proxyClass; jmethodID proxyCtrId; jclass callClass; jmethodID callCtrId; jclass chatRoomClass; jmethodID chatRoomCtrId; jclass friendClass; jmethodID friendCtrId; jclass addressClass; jmethodID addressCtrId; LinphoneCoreVTable vTable; static void showInterfaceCb(LinphoneCore *lc) { } static void byeReceivedCb(LinphoneCore *lc, const char *from) { } static void displayStatusCb(LinphoneCore *lc, const char *message) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener,lcData->displayStatusId,lcData->core,env->NewStringUTF(message)); } static void displayMessageCb(LinphoneCore *lc, const char *message) { } static void authInfoRequested(LinphoneCore *lc, const char *realm, const char *username) { } static void globalStateChange(LinphoneCore *lc, LinphoneGlobalState gstate,const char* message) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->globalStateId ,lcData->core ,env->CallStaticObjectMethod(lcData->globalStateClass,lcData->globalStateFromIntId,(jint)gstate), message ? env->NewStringUTF(message) : NULL); } static void registrationStateChange(LinphoneCore *lc, LinphoneProxyConfig* proxy,LinphoneRegistrationState state,const char* message) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->registrationStateId ,lcData->core ,env->NewObject(lcData->proxyClass,lcData->proxyCtrId,(jlong)proxy) ,env->CallStaticObjectMethod(lcData->registrationStateClass,lcData->registrationStateFromIntId,(jint)state), message ? env->NewStringUTF(message) : NULL); } jobject getCall(JNIEnv *env , LinphoneCall *call){ jobject jobj=0; if (call!=NULL){ void *up=linphone_call_get_user_pointer(call); if (up==NULL){ jobj=env->NewObject(callClass,callCtrId,(jlong)call); jobj=env->NewGlobalRef(jobj); linphone_call_set_user_pointer(call,(void*)jobj); linphone_call_ref(call); }else{ jobj=(jobject)up; } } return jobj; } static void callStateChange(LinphoneCore *lc, LinphoneCall* call,LinphoneCallState state,const char* message) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); jobject jcall; if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->callStateId ,lcData->core ,(jcall=lcData->getCall(env,call)) ,env->CallStaticObjectMethod(lcData->callStateClass,lcData->callStateFromIntId,(jint)state), message ? env->NewStringUTF(message) : NULL); if (state==LinphoneCallReleased){ linphone_call_set_user_pointer(call,NULL); env->DeleteGlobalRef(jcall); } } static void callEncryptionChange(LinphoneCore *lc, LinphoneCall* call, bool_t encrypted,const char* authentication_token) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->callEncryptionChangedId ,lcData->core ,lcData->getCall(env,call) ,encrypted ,authentication_token ? env->NewStringUTF(authentication_token) : NULL); } static void notify_presence_recv (LinphoneCore *lc, LinphoneFriend *my_friend) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->notifyPresenceReceivedId ,lcData->core ,env->NewObject(lcData->friendClass,lcData->friendCtrId,(jlong)my_friend)); } static void new_subscription_request (LinphoneCore *lc, LinphoneFriend *my_friend, const char* url) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->newSubscriptionRequestId ,lcData->core ,env->NewObject(lcData->friendClass,lcData->friendCtrId,(jlong)my_friend) ,url ? env->NewStringUTF(url) : NULL); } static void text_received(LinphoneCore *lc, LinphoneChatRoom *room, const LinphoneAddress *from, const char *message) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->textReceivedId ,lcData->core ,env->NewObject(lcData->chatRoomClass,lcData->chatRoomCtrId,(jlong)room) ,env->NewObject(lcData->addressClass,lcData->addressCtrId,(jlong)from) ,message ? env->NewStringUTF(message) : NULL); } static void ecCalibrationStatus(LinphoneCore *lc, LinphoneEcCalibratorStatus status, int delay_ms, void *data) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->ecCalibrationStatusId ,lcData->core ,env->CallStaticObjectMethod(lcData->ecCalibratorStatusClass,lcData->ecCalibratorStatusFromIntId,(jint)status) ,delay_ms ,data ? data : NULL); if (data != NULL &&status !=LinphoneEcCalibratorInProgress ) { //final state, releasing global ref env->DeleteGlobalRef((jobject)data); } } }; extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_newLinphoneCore(JNIEnv* env ,jobject thiz ,jobject jlistener ,jstring juserConfig ,jstring jfactoryConfig ,jobject juserdata){ const char* userConfig = juserConfig?env->GetStringUTFChars(juserConfig, NULL):NULL; const char* factoryConfig = jfactoryConfig?env->GetStringUTFChars(jfactoryConfig, NULL):NULL; LinphoneCoreData* ldata = new LinphoneCoreData(env,thiz,jlistener,juserdata); #ifdef HAVE_ILBC libmsilbc_init(); // requires an fpu #endif #ifdef HAVE_X264 libmsx264_init(); #endif #ifdef HAVE_AMR libmsamr_init(); #endif #ifdef HAVE_SILK libmssilk_init(); #endif #ifdef HAVE_G729 libmsbcg729_init(); #endif jlong nativePtr = (jlong)linphone_core_new( &ldata->vTable ,userConfig ,factoryConfig ,ldata); //clear auth info list linphone_core_clear_all_auth_info((LinphoneCore*) nativePtr); //clear existing proxy config linphone_core_clear_proxy_config((LinphoneCore*) nativePtr); if (userConfig) env->ReleaseStringUTFChars(juserConfig, userConfig); if (factoryConfig) env->ReleaseStringUTFChars(jfactoryConfig, factoryConfig); return nativePtr; } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_delete(JNIEnv* env ,jobject thiz ,jlong lc) { LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)lc); linphone_core_destroy((LinphoneCore*)lc); delete lcData; } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_clearProxyConfigs(JNIEnv* env, jobject thiz,jlong lc) { linphone_core_clear_proxy_config((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setDefaultProxyConfig( JNIEnv* env ,jobject thiz ,jlong lc ,jlong pc) { linphone_core_set_default_proxy((LinphoneCore*)lc,(LinphoneProxyConfig*)pc); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_getDefaultProxyConfig( JNIEnv* env ,jobject thiz ,jlong lc) { LinphoneProxyConfig *config=0; linphone_core_get_default_proxy((LinphoneCore*)lc,&config); return (jlong)config; } extern "C" jlongArray Java_org_linphone_core_LinphoneCoreImpl_getProxyConfigList(JNIEnv* env, jobject thiz, jlong lc) { const MSList* proxies = linphone_core_get_proxy_config_list((LinphoneCore*)lc); int proxyCount = ms_list_size(proxies); jlongArray jProxies = env->NewLongArray(proxyCount); jlong *jInternalArray = env->GetLongArrayElements(jProxies, NULL); for (int i = 0; i < proxyCount; i++ ) { jInternalArray[i] = (unsigned long) (proxies->data); proxies = proxies->next; } env->ReleaseLongArrayElements(jProxies, jInternalArray, 0); return jProxies; } extern "C" int Java_org_linphone_core_LinphoneCoreImpl_addProxyConfig( JNIEnv* env ,jobject thiz ,jobject jproxyCfg ,jlong lc ,jlong pc) { LinphoneProxyConfig* proxy = (LinphoneProxyConfig*)pc; linphone_proxy_config_set_user_data(proxy, env->NewGlobalRef(jproxyCfg)); return linphone_core_add_proxy_config((LinphoneCore*)lc,(LinphoneProxyConfig*)pc); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_clearAuthInfos(JNIEnv* env, jobject thiz,jlong lc) { linphone_core_clear_all_auth_info((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_addAuthInfo( JNIEnv* env ,jobject thiz ,jlong lc ,jlong pc) { linphone_core_add_auth_info((LinphoneCore*)lc,(LinphoneAuthInfo*)pc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_iterate( JNIEnv* env ,jobject thiz ,jlong lc) { linphone_core_iterate((LinphoneCore*)lc); } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_invite( JNIEnv* env ,jobject thiz ,jlong lc ,jstring juri) { const char* uri = env->GetStringUTFChars(juri, NULL); LinphoneCoreData *lcd=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)lc); LinphoneCall* lCall = linphone_core_invite((LinphoneCore*)lc,uri); env->ReleaseStringUTFChars(juri, uri); return lcd->getCall(env,lCall); } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_inviteAddress( JNIEnv* env ,jobject thiz ,jlong lc ,jlong to) { LinphoneCoreData *lcd=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)lc); return lcd->getCall(env, linphone_core_invite_address((LinphoneCore*)lc,(LinphoneAddress*)to)); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_terminateCall( JNIEnv* env ,jobject thiz ,jlong lc ,jlong call) { linphone_core_terminate_call((LinphoneCore*)lc,(LinphoneCall*)call); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_getRemoteAddress( JNIEnv* env ,jobject thiz ,jlong lc) { return (jlong)linphone_core_get_current_call_remote_address((LinphoneCore*)lc); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isInCall( JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_in_call((LinphoneCore*)lc); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isInComingInvitePending( JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_inc_invite_pending((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_acceptCall( JNIEnv* env ,jobject thiz ,jlong lc ,jlong call) { linphone_core_accept_call((LinphoneCore*)lc,(LinphoneCall*)call); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_getCallLog( JNIEnv* env ,jobject thiz ,jlong lc ,jint position) { return (jlong)ms_list_nth_data(linphone_core_get_call_logs((LinphoneCore*)lc),position); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getNumberOfCallLogs( JNIEnv* env ,jobject thiz ,jlong lc) { return ms_list_size(linphone_core_get_call_logs((LinphoneCore*)lc)); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setNetworkStateReachable( JNIEnv* env ,jobject thiz ,jlong lc ,jboolean isReachable) { linphone_core_set_network_reachable((LinphoneCore*)lc,isReachable); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setPlaybackGain( JNIEnv* env ,jobject thiz ,jlong lc ,jfloat gain) { linphone_core_set_playback_gain_db((LinphoneCore*)lc,gain); } extern "C" float Java_org_linphone_core_LinphoneCoreImpl_getPlaybackGain( JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_get_playback_gain_db((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_muteMic( JNIEnv* env ,jobject thiz ,jlong lc ,jboolean isMuted) { linphone_core_mute_mic((LinphoneCore*)lc,isMuted); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_interpretUrl( JNIEnv* env ,jobject thiz ,jlong lc ,jstring jurl) { const char* url = env->GetStringUTFChars(jurl, NULL); jlong result = (jlong)linphone_core_interpret_url((LinphoneCore*)lc,url); env->ReleaseStringUTFChars(jurl, url); return result; } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_sendDtmf( JNIEnv* env ,jobject thiz ,jlong lc ,jchar dtmf) { linphone_core_send_dtmf((LinphoneCore*)lc,dtmf); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_playDtmf( JNIEnv* env ,jobject thiz ,jlong lc ,jchar dtmf ,jint duration) { linphone_core_play_dtmf((LinphoneCore*)lc,dtmf,duration); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_stopDtmf( JNIEnv* env ,jobject thiz ,jlong lc) { linphone_core_stop_dtmf((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_clearCallLogs(JNIEnv* env ,jobject thiz ,jlong lc) { linphone_core_clear_call_logs((LinphoneCore*)lc); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isMicMuted( JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_is_mic_muted((LinphoneCore*)lc); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_findPayloadType(JNIEnv* env ,jobject thiz ,jlong lc ,jstring jmime ,jint rate) { const char* mime = env->GetStringUTFChars(jmime, NULL); jlong result = (jlong)linphone_core_find_payload_type((LinphoneCore*)lc,mime,rate); env->ReleaseStringUTFChars(jmime, mime); return result; } extern "C" jlongArray Java_org_linphone_core_LinphoneCoreImpl_listVideoPayloadTypes(JNIEnv* env ,jobject thiz ,jlong lc) { const MSList* codecs = linphone_core_get_video_codecs((LinphoneCore*)lc); int codecsCount = ms_list_size(codecs); jlongArray jCodecs = env->NewLongArray(codecsCount); jlong *jInternalArray = env->GetLongArrayElements(jCodecs, NULL); for (int i = 0; i < codecsCount; i++ ) { jInternalArray[i] = (unsigned long) (codecs->data); codecs = codecs->next; } env->ReleaseLongArrayElements(jCodecs, jInternalArray, 0); return jCodecs; } extern "C" jlongArray Java_org_linphone_core_LinphoneCoreImpl_listAudioPayloadTypes(JNIEnv* env ,jobject thiz ,jlong lc) { const MSList* codecs = linphone_core_get_audio_codecs((LinphoneCore*)lc); int codecsCount = ms_list_size(codecs); jlongArray jCodecs = env->NewLongArray(codecsCount); jlong *jInternalArray = env->GetLongArrayElements(jCodecs, NULL); for (int i = 0; i < codecsCount; i++ ) { jInternalArray[i] = (unsigned long) (codecs->data); codecs = codecs->next; } env->ReleaseLongArrayElements(jCodecs, jInternalArray, 0); return jCodecs; } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_enablePayloadType(JNIEnv* env ,jobject thiz ,jlong lc ,jlong pt ,jboolean enable) { return linphone_core_enable_payload_type((LinphoneCore*)lc,(PayloadType*)pt,enable); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_enableEchoCancellation(JNIEnv* env ,jobject thiz ,jlong lc ,jboolean enable) { linphone_core_enable_echo_cancellation((LinphoneCore*)lc,enable); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_enableEchoLimiter(JNIEnv* env ,jobject thiz ,jlong lc ,jboolean enable) { linphone_core_enable_echo_limiter((LinphoneCore*)lc,enable); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isEchoCancellationEnabled(JNIEnv* env ,jobject thiz ,jlong lc ) { return linphone_core_echo_cancellation_enabled((LinphoneCore*)lc); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isEchoLimiterEnabled(JNIEnv* env ,jobject thiz ,jlong lc ) { return linphone_core_echo_limiter_enabled((LinphoneCore*)lc); } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_getCurrentCall(JNIEnv* env ,jobject thiz ,jlong lc ) { LinphoneCoreData *lcdata=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)lc); return lcdata->getCall(env,linphone_core_get_current_call((LinphoneCore*)lc)); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_addFriend(JNIEnv* env ,jobject thiz ,jlong lc ,jlong aFriend ) { linphone_core_add_friend((LinphoneCore*)lc,(LinphoneFriend*)aFriend); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setPresenceInfo(JNIEnv* env ,jobject thiz ,jlong lc ,jint minute_away ,jstring jalternative_contact ,jint status) { const char* alternative_contact = jalternative_contact?env->GetStringUTFChars(jalternative_contact, NULL):NULL; linphone_core_set_presence_info((LinphoneCore*)lc,minute_away,alternative_contact,(LinphoneOnlineStatus)status); if (alternative_contact) env->ReleaseStringUTFChars(jalternative_contact, alternative_contact); } extern "C" long Java_org_linphone_core_LinphoneCoreImpl_createChatRoom(JNIEnv* env ,jobject thiz ,jlong lc ,jstring jto) { const char* to = env->GetStringUTFChars(jto, NULL); LinphoneChatRoom* lResult = linphone_core_create_chat_room((LinphoneCore*)lc,to); env->ReleaseStringUTFChars(jto, to); return (long)lResult; } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_enableVideo(JNIEnv* env ,jobject thiz ,jlong lc ,jboolean vcap_enabled ,jboolean display_enabled) { linphone_core_enable_video((LinphoneCore*)lc, vcap_enabled,display_enabled); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isVideoEnabled(JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_video_enabled((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setPlayFile(JNIEnv* env ,jobject thiz ,jlong lc ,jstring jpath) { const char* path = jpath?env->GetStringUTFChars(jpath, NULL):NULL; linphone_core_set_play_file((LinphoneCore*)lc,path); if (path) env->ReleaseStringUTFChars(jpath, path); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setRing(JNIEnv* env ,jobject thiz ,jlong lc ,jstring jpath) { const char* path = jpath?env->GetStringUTFChars(jpath, NULL):NULL; linphone_core_set_ring((LinphoneCore*)lc,path); if (path) env->ReleaseStringUTFChars(jpath, path); } extern "C" jstring Java_org_linphone_core_LinphoneCoreImpl_getRing(JNIEnv* env ,jobject thiz ,jlong lc ) { const char* path = linphone_core_get_ring((LinphoneCore*)lc); if (path) { return env->NewStringUTF(path); } else { return NULL; } } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setRootCA(JNIEnv* env ,jobject thiz ,jlong lc ,jstring jpath) { const char* path = jpath?env->GetStringUTFChars(jpath, NULL):NULL; linphone_core_set_root_ca((LinphoneCore*)lc,path); if (path) env->ReleaseStringUTFChars(jpath, path); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_enableKeepAlive(JNIEnv* env ,jobject thiz ,jlong lc ,jboolean enable) { linphone_core_enable_keep_alive((LinphoneCore*)lc,enable); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isKeepAliveEnabled(JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_keep_alive_enabled((LinphoneCore*)lc); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_startEchoCalibration(JNIEnv* env ,jobject thiz ,jlong lc ,jobject data) { return linphone_core_start_echo_calibration((LinphoneCore*)lc , LinphoneCoreData::ecCalibrationStatus , data?env->NewGlobalRef(data):NULL); } extern "C" int Java_org_linphone_core_LinphoneCoreImpl_getMediaEncryption(JNIEnv* env ,jobject thiz ,jlong lc ) { return (int)linphone_core_get_media_encryption((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setMediaEncryption(JNIEnv* env ,jobject thiz ,jlong lc ,int menc) { linphone_core_set_media_encryption((LinphoneCore*)lc,(LinphoneMediaEncryption)menc); } extern "C" int Java_org_linphone_core_LinphoneCallParamsImpl_getMediaEncryption(JNIEnv* env ,jobject thiz ,jlong cp ) { return (int)linphone_call_params_get_media_encryption((LinphoneCallParams*)cp); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_mediaEncryptionSupported(JNIEnv* env ,jobject thiz ,jlong lc, jint menc ) { return linphone_core_media_encryption_supported((LinphoneCore*)lc,(LinphoneMediaEncryption)menc); } extern "C" void Java_org_linphone_core_LinphoneCallParamsImpl_setMediaEncryption(JNIEnv* env ,jobject thiz ,jlong cp ,int jmenc) { linphone_call_params_set_media_encryption((LinphoneCallParams*)cp,(LinphoneMediaEncryption)jmenc); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_getMediaEncryptionMandatory(JNIEnv* env ,jobject thiz ,jlong lc ) { return linphone_core_is_media_encryption_mandatory((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setMediaEncryptionMandatory(JNIEnv* env ,jobject thiz ,jlong lc , jboolean yesno ) { linphone_core_set_media_encryption_mandatory((LinphoneCore*)lc, yesno); } //ProxyConfig extern "C" jlong Java_org_linphone_core_LinphoneProxyConfigImpl_newLinphoneProxyConfig(JNIEnv* env,jobject thiz) { LinphoneProxyConfig* proxy = linphone_proxy_config_new(); return (jlong) proxy; } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_delete(JNIEnv* env,jobject thiz,jlong ptr) { linphone_proxy_config_destroy((LinphoneProxyConfig*)ptr); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_setIdentity(JNIEnv* env,jobject thiz,jlong proxyCfg,jstring jidentity) { const char* identity = env->GetStringUTFChars(jidentity, NULL); linphone_proxy_config_set_identity((LinphoneProxyConfig*)proxyCfg,identity); env->ReleaseStringUTFChars(jidentity, identity); } extern "C" jstring Java_org_linphone_core_LinphoneProxyConfigImpl_getIdentity(JNIEnv* env,jobject thiz,jlong proxyCfg) { const char* identity = linphone_proxy_config_get_identity((LinphoneProxyConfig*)proxyCfg); if (identity) { return env->NewStringUTF(identity); } else { return NULL; } } extern "C" int Java_org_linphone_core_LinphoneProxyConfigImpl_setProxy(JNIEnv* env,jobject thiz,jlong proxyCfg,jstring jproxy) { const char* proxy = env->GetStringUTFChars(jproxy, NULL); int err=linphone_proxy_config_set_server_addr((LinphoneProxyConfig*)proxyCfg,proxy); env->ReleaseStringUTFChars(jproxy, proxy); return err; } extern "C" jstring Java_org_linphone_core_LinphoneProxyConfigImpl_getProxy(JNIEnv* env,jobject thiz,jlong proxyCfg) { const char* proxy = linphone_proxy_config_get_addr((LinphoneProxyConfig*)proxyCfg); if (proxy) { return env->NewStringUTF(proxy); } else { return NULL; } } extern "C" int Java_org_linphone_core_LinphoneProxyConfigImpl_setRoute(JNIEnv* env,jobject thiz,jlong proxyCfg,jstring jroute) { if (jroute != NULL) { const char* route = env->GetStringUTFChars(jroute, NULL); int err=linphone_proxy_config_set_route((LinphoneProxyConfig*)proxyCfg,route); env->ReleaseStringUTFChars(jroute, route); return err; } else { return linphone_proxy_config_set_route((LinphoneProxyConfig*)proxyCfg,NULL); } } extern "C" jstring Java_org_linphone_core_LinphoneProxyConfigImpl_getRoute(JNIEnv* env,jobject thiz,jlong proxyCfg) { const char* route = linphone_proxy_config_get_route((LinphoneProxyConfig*)proxyCfg); if (route) { return env->NewStringUTF(route); } else { return NULL; } } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_enableRegister(JNIEnv* env,jobject thiz,jlong proxyCfg,jboolean enableRegister) { linphone_proxy_config_enable_register((LinphoneProxyConfig*)proxyCfg,enableRegister); } extern "C" jboolean Java_org_linphone_core_LinphoneProxyConfigImpl_isRegistered(JNIEnv* env,jobject thiz,jlong proxyCfg) { return linphone_proxy_config_is_registered((LinphoneProxyConfig*)proxyCfg); } extern "C" jboolean Java_org_linphone_core_LinphoneProxyConfigImpl_isRegisterEnabled(JNIEnv* env,jobject thiz,jlong proxyCfg) { return linphone_proxy_config_register_enabled((LinphoneProxyConfig*)proxyCfg); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_edit(JNIEnv* env,jobject thiz,jlong proxyCfg) { linphone_proxy_config_edit((LinphoneProxyConfig*)proxyCfg); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_done(JNIEnv* env,jobject thiz,jlong proxyCfg) { linphone_proxy_config_done((LinphoneProxyConfig*)proxyCfg); } extern "C" jstring Java_org_linphone_core_LinphoneProxyConfigImpl_normalizePhoneNumber(JNIEnv* env,jobject thiz,jlong proxyCfg,jstring jnumber) { if (jnumber == 0) { ms_error("cannot normalized null number"); } const char* number = env->GetStringUTFChars(jnumber, NULL); int len = env->GetStringLength(jnumber); if (len == 0) { ms_warning("cannot normalize empty number"); return jnumber; } char targetBuff[2*len];// returned number can be greater than origin (specially in case of prefix insertion linphone_proxy_config_normalize_number((LinphoneProxyConfig*)proxyCfg,number,targetBuff,sizeof(targetBuff)); jstring normalizedNumber = env->NewStringUTF(targetBuff); env->ReleaseStringUTFChars(jnumber, number); return normalizedNumber; } extern "C" jstring Java_org_linphone_core_LinphoneProxyConfigImpl_getDomain(JNIEnv* env ,jobject thiz ,jlong proxyCfg) { const char* domain = linphone_proxy_config_get_domain((LinphoneProxyConfig*)proxyCfg); if (domain) { return env->NewStringUTF(domain); } else { return NULL; } } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_setDialEscapePlus(JNIEnv* env,jobject thiz,jlong proxyCfg,jboolean value) { linphone_proxy_config_set_dial_escape_plus((LinphoneProxyConfig*)proxyCfg,value); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_setDialPrefix(JNIEnv* env ,jobject thiz ,jlong proxyCfg ,jstring jprefix) { const char* prefix = env->GetStringUTFChars(jprefix, NULL); linphone_proxy_config_set_dial_prefix((LinphoneProxyConfig*)proxyCfg,prefix); env->ReleaseStringUTFChars(jprefix, prefix); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_enablePublish(JNIEnv* env ,jobject thiz ,jlong proxyCfg ,jboolean val) { linphone_proxy_config_enable_publish((LinphoneProxyConfig*)proxyCfg,val); } extern "C" jboolean Java_org_linphone_core_LinphoneProxyConfigImpl_publishEnabled(JNIEnv* env,jobject thiz,jlong proxyCfg) { return linphone_proxy_config_publish_enabled((LinphoneProxyConfig*)proxyCfg); } //Auth Info extern "C" jlong Java_org_linphone_core_LinphoneAuthInfoImpl_newLinphoneAuthInfo(JNIEnv* env , jobject thiz , jstring jusername , jstring juserid , jstring jpassword , jstring jha1 , jstring jrealm) { const char* username = env->GetStringUTFChars(jusername, NULL); const char* password = env->GetStringUTFChars(jpassword, NULL); jlong auth = (jlong)linphone_auth_info_new(username,NULL,password,NULL,NULL); env->ReleaseStringUTFChars(jusername, username); env->ReleaseStringUTFChars(jpassword, password); return auth; } extern "C" void Java_org_linphone_core_LinphoneAuthInfoImpl_delete(JNIEnv* env , jobject thiz , jlong ptr) { linphone_auth_info_destroy((LinphoneAuthInfo*)ptr); } //LinphoneAddress extern "C" jlong Java_org_linphone_core_LinphoneAddressImpl_newLinphoneAddressImpl(JNIEnv* env ,jobject thiz ,jstring juri ,jstring jdisplayName) { const char* uri = env->GetStringUTFChars(juri, NULL); LinphoneAddress* address = linphone_address_new(uri); if (jdisplayName && address) { const char* displayName = env->GetStringUTFChars(jdisplayName, NULL); linphone_address_set_display_name(address,displayName); env->ReleaseStringUTFChars(jdisplayName, displayName); } env->ReleaseStringUTFChars(juri, uri); return (jlong) address; } extern "C" void Java_org_linphone_core_LinphoneAddressImpl_delete(JNIEnv* env ,jobject thiz ,jlong ptr) { linphone_address_destroy((LinphoneAddress*)ptr); } extern "C" jstring Java_org_linphone_core_LinphoneAddressImpl_getDisplayName(JNIEnv* env ,jobject thiz ,jlong ptr) { const char* displayName = linphone_address_get_display_name((LinphoneAddress*)ptr); if (displayName) { return env->NewStringUTF(displayName); } else { return 0; } } extern "C" jstring Java_org_linphone_core_LinphoneAddressImpl_getUserName(JNIEnv* env ,jobject thiz ,jlong ptr) { const char* userName = linphone_address_get_username((LinphoneAddress*)ptr); if (userName) { return env->NewStringUTF(userName); } else { return 0; } } extern "C" jstring Java_org_linphone_core_LinphoneAddressImpl_getDomain(JNIEnv* env ,jobject thiz ,jlong ptr) { const char* domain = linphone_address_get_domain((LinphoneAddress*)ptr); if (domain) { return env->NewStringUTF(domain); } else { return 0; } } extern "C" jstring Java_org_linphone_core_LinphoneAddressImpl_toString(JNIEnv* env ,jobject thiz ,jlong ptr) { char* uri = linphone_address_as_string((LinphoneAddress*)ptr); jstring juri =env->NewStringUTF(uri); ms_free(uri); return juri; } extern "C" jstring Java_org_linphone_core_LinphoneAddressImpl_toUri(JNIEnv* env ,jobject thiz ,jlong ptr) { char* uri = linphone_address_as_string_uri_only((LinphoneAddress*)ptr); jstring juri =env->NewStringUTF(uri); ms_free(uri); return juri; } extern "C" void Java_org_linphone_core_LinphoneAddressImpl_setDisplayName(JNIEnv* env ,jobject thiz ,jlong address ,jstring jdisplayName) { const char* displayName = jdisplayName!= NULL?env->GetStringUTFChars(jdisplayName, NULL):NULL; linphone_address_set_display_name((LinphoneAddress*)address,displayName); if (displayName != NULL) env->ReleaseStringUTFChars(jdisplayName, displayName); } //CallLog extern "C" jlong Java_org_linphone_core_LinphoneCallLogImpl_getFrom(JNIEnv* env ,jobject thiz ,jlong ptr) { return (jlong)((LinphoneCallLog*)ptr)->from; } extern "C" jlong Java_org_linphone_core_LinphoneCallLogImpl_getTo(JNIEnv* env ,jobject thiz ,jlong ptr) { return (jlong)((LinphoneCallLog*)ptr)->to; } extern "C" jboolean Java_org_linphone_core_LinphoneCallLogImpl_isIncoming(JNIEnv* env ,jobject thiz ,jlong ptr) { return ((LinphoneCallLog*)ptr)->dir==LinphoneCallIncoming?JNI_TRUE:JNI_FALSE; } /*payloadType*/ extern "C" jstring Java_org_linphone_core_PayloadTypeImpl_toString(JNIEnv* env,jobject thiz,jlong ptr) { PayloadType* pt = (PayloadType*)ptr; char* value = ms_strdup_printf("[%s] clock [%i], bitrate [%i]" ,payload_type_get_mime(pt) ,payload_type_get_rate(pt) ,payload_type_get_bitrate(pt)); jstring jvalue =env->NewStringUTF(value); ms_free(value); return jvalue; } extern "C" jstring Java_org_linphone_core_PayloadTypeImpl_getMime(JNIEnv* env,jobject thiz,jlong ptr) { PayloadType* pt = (PayloadType*)ptr; jstring jvalue =env->NewStringUTF(payload_type_get_mime(pt)); return jvalue; } extern "C" jint Java_org_linphone_core_PayloadTypeImpl_getRate(JNIEnv* env,jobject thiz, jlong ptr) { PayloadType* pt = (PayloadType*)ptr; return payload_type_get_rate(pt); } //LinphoneCall extern "C" void Java_org_linphone_core_LinphoneCallImpl_finalize(JNIEnv* env ,jobject thiz ,jlong ptr) { LinphoneCall *call=(LinphoneCall*)ptr; linphone_call_unref(call); } extern "C" jlong Java_org_linphone_core_LinphoneCallImpl_getCallLog( JNIEnv* env ,jobject thiz ,jlong ptr) { return (jlong)linphone_call_get_call_log((LinphoneCall*)ptr); } extern "C" jboolean Java_org_linphone_core_LinphoneCallImpl_isIncoming( JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_call_get_dir((LinphoneCall*)ptr)==LinphoneCallIncoming?JNI_TRUE:JNI_FALSE; } extern "C" jlong Java_org_linphone_core_LinphoneCallImpl_getRemoteAddress( JNIEnv* env ,jobject thiz ,jlong ptr) { return (jlong)linphone_call_get_remote_address((LinphoneCall*)ptr); } extern "C" jint Java_org_linphone_core_LinphoneCallImpl_getState( JNIEnv* env ,jobject thiz ,jlong ptr) { return (jint)linphone_call_get_state((LinphoneCall*)ptr); } extern "C" void Java_org_linphone_core_LinphoneCallImpl_enableEchoCancellation( JNIEnv* env ,jobject thiz ,jlong ptr ,jboolean value) { linphone_call_enable_echo_cancellation((LinphoneCall*)ptr,value); } extern "C" jboolean Java_org_linphone_core_LinphoneCallImpl_isEchoCancellationEnabled( JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_call_echo_cancellation_enabled((LinphoneCall*)ptr); } extern "C" void Java_org_linphone_core_LinphoneCallImpl_enableEchoLimiter( JNIEnv* env ,jobject thiz ,jlong ptr ,jboolean value) { linphone_call_enable_echo_limiter((LinphoneCall*)ptr,value); } extern "C" jboolean Java_org_linphone_core_LinphoneCallImpl_isEchoLimiterEnabled( JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_call_echo_limiter_enabled((LinphoneCall*)ptr); } extern "C" jobject Java_org_linphone_core_LinphoneCallImpl_getReplacedCall( JNIEnv* env ,jobject thiz ,jlong ptr) { LinphoneCoreData *lcd=(LinphoneCoreData*)linphone_core_get_user_data(linphone_call_get_core((LinphoneCall*)ptr)); return lcd->getCall(env,linphone_call_get_replaced_call((LinphoneCall*)ptr)); } extern "C" jfloat Java_org_linphone_core_LinphoneCallImpl_getCurrentQuality( JNIEnv* env ,jobject thiz ,jlong ptr) { return (jfloat)linphone_call_get_current_quality((LinphoneCall*)ptr); } extern "C" jfloat Java_org_linphone_core_LinphoneCallImpl_getAverageQuality( JNIEnv* env ,jobject thiz ,jlong ptr) { return (jfloat)linphone_call_get_average_quality((LinphoneCall*)ptr); } //LinphoneFriend extern "C" long Java_org_linphone_core_LinphoneFriendImpl_newLinphoneFriend(JNIEnv* env ,jobject thiz ,jstring jFriendUri) { LinphoneFriend* lResult; if (jFriendUri) { const char* friendUri = env->GetStringUTFChars(jFriendUri, NULL); lResult= linphone_friend_new_with_addr(friendUri); env->ReleaseStringUTFChars(jFriendUri, friendUri); } else { lResult = linphone_friend_new(); } return (long)lResult; } extern "C" void Java_org_linphone_core_LinphoneFriendImpl_setAddress(JNIEnv* env ,jobject thiz ,jlong ptr ,jlong linphoneAddress) { linphone_friend_set_addr((LinphoneFriend*)ptr,(LinphoneAddress*)linphoneAddress); } extern "C" long Java_org_linphone_core_LinphoneFriendImpl_getAddress(JNIEnv* env ,jobject thiz ,jlong ptr) { return (long)linphone_friend_get_address((LinphoneFriend*)ptr); } extern "C" void Java_org_linphone_core_LinphoneFriendImpl_setIncSubscribePolicy(JNIEnv* env ,jobject thiz ,jlong ptr ,jint policy) { linphone_friend_set_inc_subscribe_policy((LinphoneFriend*)ptr,(LinphoneSubscribePolicy)policy); } extern "C" jint Java_org_linphone_core_LinphoneFriendImpl_getIncSubscribePolicy(JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_friend_get_inc_subscribe_policy((LinphoneFriend*)ptr); } extern "C" void Java_org_linphone_core_LinphoneFriendImpl_enableSubscribes(JNIEnv* env ,jobject thiz ,jlong ptr ,jboolean value) { linphone_friend_enable_subscribes((LinphoneFriend*)ptr,value); } extern "C" jboolean Java_org_linphone_core_LinphoneFriendImpl_isSubscribesEnabled(JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_friend_subscribes_enabled((LinphoneFriend*)ptr); } extern "C" jboolean Java_org_linphone_core_LinphoneFriendImpl_getStatus(JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_friend_get_status((LinphoneFriend*)ptr); } extern "C" void Java_org_linphone_core_LinphoneFriendImpl_edit(JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_friend_edit((LinphoneFriend*)ptr); } extern "C" void Java_org_linphone_core_LinphoneFriendImpl_done(JNIEnv* env ,jobject thiz ,jlong ptr) { linphone_friend_done((LinphoneFriend*)ptr); } //LinphoneChatRoom extern "C" long Java_org_linphone_core_LinphoneChatRoomImpl_getPeerAddress(JNIEnv* env ,jobject thiz ,jlong ptr) { return (long) linphone_chat_room_get_peer_address((LinphoneChatRoom*)ptr); } extern "C" void Java_org_linphone_core_LinphoneChatRoomImpl_sendMessage(JNIEnv* env ,jobject thiz ,jlong ptr ,jstring jmessage) { const char* message = env->GetStringUTFChars(jmessage, NULL); linphone_chat_room_send_message((LinphoneChatRoom*)ptr,message); env->ReleaseStringUTFChars(jmessage, message); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setVideoWindowId(JNIEnv* env ,jobject thiz ,jlong lc ,jobject obj) { jobject oldWindow = (jobject) linphone_core_get_native_video_window_id((LinphoneCore*)lc); if (oldWindow != NULL) { env->DeleteGlobalRef(oldWindow); } if (obj != NULL) { obj = env->NewGlobalRef(obj); } linphone_core_set_native_video_window_id((LinphoneCore*)lc,(unsigned long)obj); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setPreviewWindowId(JNIEnv* env ,jobject thiz ,jlong lc ,jobject obj) { jobject oldWindow = (jobject) linphone_core_get_native_preview_window_id((LinphoneCore*)lc); if (oldWindow != NULL) { env->DeleteGlobalRef(oldWindow); } if (obj != NULL) { obj = env->NewGlobalRef(obj); } linphone_core_set_native_preview_window_id((LinphoneCore*)lc,(unsigned long)obj); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setDeviceRotation(JNIEnv* env ,jobject thiz ,jlong lc ,jint rotation) { linphone_core_set_device_rotation((LinphoneCore*)lc,rotation); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setFirewallPolicy(JNIEnv *env, jobject thiz, jlong lc, int enum_value){ linphone_core_set_firewall_policy((LinphoneCore*)lc,(LinphoneFirewallPolicy)enum_value); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getFirewallPolicy(JNIEnv *env, jobject thiz, jlong lc){ return linphone_core_get_firewall_policy((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setStunServer(JNIEnv *env, jobject thiz, jlong lc, jstring jserver){ const char* server = NULL; if (jserver) server=env->GetStringUTFChars(jserver, NULL); linphone_core_set_stun_server((LinphoneCore*)lc,server); if (server) env->ReleaseStringUTFChars(jserver,server); } extern "C" jstring Java_org_linphone_core_LinphoneCoreImpl_getStunServer(JNIEnv *env, jobject thiz, jlong lc){ const char *ret= linphone_core_get_stun_server((LinphoneCore*)lc); if (ret==NULL) return NULL; jstring jvalue =env->NewStringUTF(ret); return jvalue; } extern "C" void Java_org_linphone_core_LinphoneCallParamsImpl_audioBandwidth(JNIEnv *env, jobject thiz, jlong lcp, jint bw){ linphone_call_params_set_audio_bandwidth_limit((LinphoneCallParams*)lcp, bw); } extern "C" void Java_org_linphone_core_LinphoneCallParamsImpl_enableVideo(JNIEnv *env, jobject thiz, jlong lcp, jboolean b){ linphone_call_params_enable_video((LinphoneCallParams*)lcp, b); } extern "C" jboolean Java_org_linphone_core_LinphoneCallParamsImpl_getVideoEnabled(JNIEnv *env, jobject thiz, jlong lcp){ return linphone_call_params_video_enabled((LinphoneCallParams*)lcp); } extern "C" jboolean Java_org_linphone_core_LinphoneCallParamsImpl_localConferenceMode(JNIEnv *env, jobject thiz, jlong lcp){ return linphone_call_params_local_conference_mode((LinphoneCallParams*)lcp); } extern "C" void Java_org_linphone_core_LinphoneCallParamsImpl_destroy(JNIEnv *env, jobject thiz, jlong lc){ return linphone_call_params_destroy((LinphoneCallParams*)lc); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_createDefaultCallParams(JNIEnv *env, jobject thiz, jlong lc){ return (jlong) linphone_core_create_default_call_parameters((LinphoneCore*)lc); } extern "C" jlong Java_org_linphone_core_LinphoneCallImpl_getCurrentParamsCopy(JNIEnv *env, jobject thiz, jlong lc){ return (jlong) linphone_call_params_copy(linphone_call_get_current_params((LinphoneCall*)lc)); } extern "C" jlong Java_org_linphone_core_LinphoneCallImpl_enableCamera(JNIEnv *env, jobject thiz, jlong lc, jboolean b){ linphone_call_enable_camera((LinphoneCall *)lc, (bool_t) b); } extern "C" jboolean Java_org_linphone_core_LinphoneCallImpl_cameraEnabled(JNIEnv *env, jobject thiz, jlong lc){ linphone_call_camera_enabled((LinphoneCall *)lc); } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_inviteAddressWithParams(JNIEnv *env, jobject thiz, jlong lc, jlong addr, jlong params){ LinphoneCoreData *lcd=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)lc); return lcd->getCall(env,linphone_core_invite_address_with_params((LinphoneCore *)lc, (const LinphoneAddress *)addr, (const LinphoneCallParams *)params)); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_updateAddressWithParams(JNIEnv *env, jobject thiz, jlong lc, jlong call, jlong params){ return (jint) linphone_core_update_call((LinphoneCore *)lc, (LinphoneCall *)call, (LinphoneCallParams *)params); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_updateCall(JNIEnv *env, jobject thiz, jlong lc, jlong call, jlong params){ return (jint) linphone_core_update_call((LinphoneCore *)lc, (LinphoneCall *)call, (const LinphoneCallParams *)params); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setPreferredVideoSize(JNIEnv *env, jobject thiz, jlong lc, jint width, jint height){ MSVideoSize vsize; vsize.width = (int)width; vsize.height = (int)height; linphone_core_set_preferred_video_size((LinphoneCore *)lc, vsize); } extern "C" jintArray Java_org_linphone_core_LinphoneCoreImpl_getPreferredVideoSize(JNIEnv *env, jobject thiz, jlong lc){ MSVideoSize vsize = linphone_core_get_preferred_video_size((LinphoneCore *)lc); jintArray arr = env->NewIntArray(2); int tVsize [2]= {vsize.width,vsize.height}; env->SetIntArrayRegion(arr, 0, 2, tVsize); return arr; } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setDownloadBandwidth(JNIEnv *env, jobject thiz, jlong lc, jint bw){ linphone_core_set_download_bandwidth((LinphoneCore *)lc, (int) bw); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setUploadBandwidth(JNIEnv *env, jobject thiz, jlong lc, jint bw){ linphone_core_set_upload_bandwidth((LinphoneCore *)lc, (int) bw); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setDownloadPtime(JNIEnv *env, jobject thiz, jlong lc, jint ptime){ linphone_core_set_download_ptime((LinphoneCore *)lc, (int) ptime); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setUploadPtime(JNIEnv *env, jobject thiz, jlong lc, jint ptime){ linphone_core_set_upload_ptime((LinphoneCore *)lc, (int) ptime); } extern "C" int Java_org_linphone_core_LinphoneProxyConfigImpl_getState(JNIEnv* env,jobject thiz,jlong ptr) { return (int) linphone_proxy_config_get_state((const LinphoneProxyConfig *) ptr); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_setExpires(JNIEnv* env,jobject thiz,jlong ptr,jint delay) { linphone_proxy_config_expires((LinphoneProxyConfig *) ptr, (int) delay); } extern "C" jint Java_org_linphone_core_LinphoneCallImpl_getDuration(JNIEnv* env,jobject thiz,jlong ptr) { linphone_call_get_duration((LinphoneCall *) ptr); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getSignalingTransportPort(JNIEnv* env,jobject thiz,jlong ptr, jint code) { LCSipTransports tr; linphone_core_get_sip_transports((LinphoneCore *) ptr, &tr); switch (code) { case 0: return tr.udp_port; case 1: return tr.tcp_port; case 3: return tr.tls_port; default: return -2; } } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setSignalingTransportPorts(JNIEnv* env,jobject thiz,jlong ptr,jint udp, jint tcp, jint tls) { LinphoneCore *lc = (LinphoneCore *) ptr; LCSipTransports tr; tr.udp_port = udp; tr.tcp_port = tcp; tr.tls_port = tls; linphone_core_set_sip_transports(lc, &tr); // tr will be copied } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_enableIpv6(JNIEnv* env,jobject thiz ,jlong lc, jboolean enable) { linphone_core_enable_ipv6((LinphoneCore*)lc,enable); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_adjustSoftwareVolume(JNIEnv* env,jobject thiz ,jlong ptr, jint db) { linphone_core_set_playback_gain_db((LinphoneCore *) ptr, db); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_pauseCall(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall) { return linphone_core_pause_call((LinphoneCore *) pCore, (LinphoneCall *) pCall); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_pauseAllCalls(JNIEnv *env,jobject thiz,jlong pCore) { return linphone_core_pause_all_calls((LinphoneCore *) pCore); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_resumeCall(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall) { return linphone_core_resume_call((LinphoneCore *) pCore, (LinphoneCall *) pCall); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isInConference(JNIEnv *env,jobject thiz,jlong pCore) { return linphone_core_is_in_conference((LinphoneCore *) pCore); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_enterConference(JNIEnv *env,jobject thiz,jlong pCore) { return 0 == linphone_core_enter_conference((LinphoneCore *) pCore); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_leaveConference(JNIEnv *env,jobject thiz,jlong pCore) { linphone_core_leave_conference((LinphoneCore *) pCore); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_addAllToConference(JNIEnv *env,jobject thiz,jlong pCore) { linphone_core_add_all_to_conference((LinphoneCore *) pCore); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_addToConference(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall) { linphone_core_add_to_conference((LinphoneCore *) pCore, (LinphoneCall *) pCall); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_removeFromConference(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall) { linphone_core_remove_from_conference((LinphoneCore *) pCore, (LinphoneCall *) pCall); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_terminateConference(JNIEnv *env,jobject thiz,jlong pCore) { linphone_core_terminate_conference((LinphoneCore *) pCore); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getConferenceSize(JNIEnv *env,jobject thiz,jlong pCore) { return linphone_core_get_conference_size((LinphoneCore *) pCore); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_terminateAllCalls(JNIEnv *env,jobject thiz,jlong pCore) { linphone_core_terminate_all_calls((LinphoneCore *) pCore); } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_getCall(JNIEnv *env,jobject thiz,jlong pCore,jint position) { LinphoneCoreData *lcd=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)pCore); LinphoneCall* lCall = (LinphoneCall*) ms_list_nth_data(linphone_core_get_calls((LinphoneCore *) pCore),position); return lcd->getCall(env,lCall); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getCallsNb(JNIEnv *env,jobject thiz,jlong pCore) { return ms_list_size(linphone_core_get_calls((LinphoneCore *) pCore)); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_transferCall(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall, jstring jReferTo) { const char* cReferTo=env->GetStringUTFChars(jReferTo, NULL); linphone_core_transfer_call((LinphoneCore *) pCore, (LinphoneCall *) pCall, cReferTo); env->ReleaseStringUTFChars(jReferTo, cReferTo); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_transferCallToAnother(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall, jlong pDestCall) { linphone_core_transfer_call_to_another((LinphoneCore *) pCore, (LinphoneCall *) pCall, (LinphoneCall *) pDestCall); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setZrtpSecretsCache(JNIEnv *env,jobject thiz,jlong pCore, jstring jFile) { if (jFile) { const char* cFile=env->GetStringUTFChars(jFile, NULL); linphone_core_set_zrtp_secrets_file((LinphoneCore *) pCore,cFile); env->ReleaseStringUTFChars(jFile, cFile); } else { linphone_core_set_zrtp_secrets_file((LinphoneCore *) pCore,NULL); } } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_findCallFromUri(JNIEnv *env,jobject thiz,jlong pCore, jstring jUri) { const char* cUri=env->GetStringUTFChars(jUri, NULL); LinphoneCall *call= (LinphoneCall *) linphone_core_find_call_from_uri((LinphoneCore *) pCore,cUri); env->ReleaseStringUTFChars(jUri, cUri); LinphoneCoreData *lcdata=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)pCore); return (jobject) lcdata->getCall(env,call); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_setVideoDevice(JNIEnv *env,jobject thiz,jlong pCore,jint id) { LinphoneCore* lc = (LinphoneCore *) pCore; const char** devices = linphone_core_get_video_devices(lc); if (devices == NULL) { ms_error("No existing video devices\n"); return -1; } int i; for(i=0; i<=id; i++) { if (devices[i] == NULL) break; ms_message("Existing device %d : %s\n", i, devices[i]); if (i==id) { return linphone_core_set_video_device(lc, devices[i]); } } return -1; } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getVideoDevice(JNIEnv *env,jobject thiz,jlong pCore) { LinphoneCore* lc = (LinphoneCore *) pCore; const char** devices = linphone_core_get_video_devices(lc); if (devices == NULL) { ms_error("No existing video devices\n"); return -1; } const char* cam = linphone_core_get_video_device(lc); if (cam == NULL) { ms_error("No current video device\n"); } else { int i=0; while(devices[i] != NULL) { if (strcmp(devices[i], cam) == 0) return i; i++; } } ms_warning("Returning default (0) device\n"); return 0; } extern "C" jstring Java_org_linphone_core_LinphoneCallImpl_getAuthenticationToken(JNIEnv* env,jobject thiz,jlong ptr) { LinphoneCall *call = (LinphoneCall *) ptr; const char* token = linphone_call_get_authentication_token(call); if (token == NULL) return NULL; return env->NewStringUTF(token); } extern "C" jboolean Java_org_linphone_core_LinphoneCallImpl_isAuthenticationTokenVerified(JNIEnv* env,jobject thiz,jlong ptr) { LinphoneCall *call = (LinphoneCall *) ptr; return linphone_call_get_authentication_token_verified(call); } extern "C" void Java_org_linphone_core_LinphoneCallImpl_setAuthenticationTokenVerified(JNIEnv* env,jobject thiz,jlong ptr,jboolean verified) { LinphoneCall *call = (LinphoneCall *) ptr; linphone_call_set_authentication_token_verified(call, verified); } extern "C" jfloat Java_org_linphone_core_LinphoneCallImpl_getPlayVolume(JNIEnv* env, jobject thiz, jlong ptr) { LinphoneCall *call = (LinphoneCall *) ptr; return linphone_call_get_play_volume(call); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_soundResourcesLocked(JNIEnv* env,jobject thiz,jlong ptr){ return linphone_core_sound_resources_locked((LinphoneCore *) ptr); } // Needed by Galaxy S (can't switch to/from speaker while playing and still keep mic working) // Implemented directly in msandroid.cpp (sound filters for Android). extern "C" void msandroid_hack_speaker_state(bool speakerOn); extern "C" void Java_org_linphone_LinphoneManager_hackSpeakerState(JNIEnv* env,jobject thiz,jboolean speakerOn){ msandroid_hack_speaker_state(speakerOn); } // End Galaxy S hack functions extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getMaxCalls(JNIEnv *env,jobject thiz,jlong pCore) { return (jint) linphone_core_get_max_calls((LinphoneCore *) pCore); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setMaxCalls(JNIEnv *env,jobject thiz,jlong pCore, jint max) { linphone_core_set_max_calls((LinphoneCore *) pCore, (int) max); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_tunnelAddServerAndMirror(JNIEnv *env,jobject thiz,jlong pCore, jstring jHost, jint port, jint mirror, jint delay) { #ifdef TUNNEL_ENABLED LinphoneTunnel *tunnel=((LinphoneCore *) pCore)->tunnel; if (!tunnel) return; const char* cHost=env->GetStringUTFChars(jHost, NULL); linphone_tunnel_add_server_and_mirror(tunnel, cHost, port, mirror, delay); env->ReleaseStringUTFChars(jHost, cHost); #endif } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_tunnelAutoDetect(JNIEnv *env,jobject thiz,jlong pCore) { #ifdef TUNNEL_ENABLED LinphoneTunnel *tunnel=((LinphoneCore *) pCore)->tunnel; if (!tunnel) return; linphone_tunnel_auto_detect(tunnel); #endif } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_tunnelCleanServers(JNIEnv *env,jobject thiz,jlong pCore) { #ifdef TUNNEL_ENABLED LinphoneTunnel *tunnel=((LinphoneCore *) pCore)->tunnel; if (!tunnel) return; linphone_tunnel_clean_servers(tunnel); #endif } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_tunnelEnable(JNIEnv *env,jobject thiz,jlong pCore, jboolean enable) { #ifdef TUNNEL_ENABLED LinphoneTunnel *tunnel=((LinphoneCore *) pCore)->tunnel; if (!tunnel) return; linphone_tunnel_enable(tunnel, enable); #endif } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_tunnelEnableLogs(JNIEnv *env,jobject thiz,jlong pCore, jboolean enable) { #ifdef TUNNEL_ENABLED LinphoneTunnel *tunnel=((LinphoneCore *) pCore)->tunnel; if (!tunnel) return; linphone_tunnel_enable_logs(tunnel, enable); #endif } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isTunnelAvailable(JNIEnv *env,jobject thiz){ return linphone_core_tunnel_available(); }
39.441777
221
0.749779
doyaGu
e61fb7b2d1a457280a1a01460af170753b30afe6
323
hpp
C++
src/Time/StepControllers/Factory.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
src/Time/StepControllers/Factory.hpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
src/Time/StepControllers/Factory.hpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include "Time/StepControllers/BinaryFraction.hpp" #include "Utilities/TMPL.hpp" namespace StepControllers { /// Typelist of standard StepControllers using standard_step_controllers = tmpl::list<BinaryFraction>; } // namespace Triggers
24.846154
61
0.786378
macedo22
e6279c8736443f7a57545a58a85e0ea38cb142db
2,756
cpp
C++
procedures/p9/start_host.cpp
devenrao/openpower-proc-control
1dc3acd254df36670e978ad2fc4af13d7ce84bcb
[ "Apache-2.0" ]
1
2020-04-22T17:21:10.000Z
2020-04-22T17:21:10.000Z
procedures/p9/start_host.cpp
devenrao/openpower-proc-control
1dc3acd254df36670e978ad2fc4af13d7ce84bcb
[ "Apache-2.0" ]
5
2017-06-30T10:14:12.000Z
2021-11-28T19:42:41.000Z
procedures/p9/start_host.cpp
devenrao/openpower-proc-control
1dc3acd254df36670e978ad2fc4af13d7ce84bcb
[ "Apache-2.0" ]
7
2017-03-24T22:33:51.000Z
2022-01-20T05:31:29.000Z
/** * Copyright (C) 2017 IBM Corporation * * 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 "cfam_access.hpp" #include "ext_interface.hpp" #include "p9_cfam.hpp" #include "registration.hpp" #include "targeting.hpp" #include <phosphor-logging/log.hpp> namespace openpower { namespace p9 { using namespace phosphor::logging; using namespace openpower::cfam::access; using namespace openpower::cfam::p9; using namespace openpower::targeting; /** * @brief Starts the self boot engine on P9 position 0 to kick off a boot. * @return void */ void startHost() { Targeting targets; const auto& master = *(targets.begin()); log<level::INFO>("Running P9 procedure startHost", entry("NUM_PROCS=%d", targets.size())); // Ensure asynchronous clock mode is set writeReg(master, P9_LL_MODE_REG, 0x00000001); // Clock mux select override for (const auto& t : targets) { writeRegWithMask(t, P9_ROOT_CTRL8, 0x0000000C, 0x0000000C); } // Enable P9 checkstop to be reported to the BMC // Setup FSI2PIB to report checkstop writeReg(master, P9_FSI_A_SI1S, 0x20000000); // Enable Xstop/ATTN interrupt writeReg(master, P9_FSI2PIB_TRUE_MASK, 0x60000000); // Arm it writeReg(master, P9_FSI2PIB_INTERRUPT, 0xFFFFFFFF); // Kick off the SBE to start the boot // Choose seeprom side to boot from cfam_data_t sbeSide = 0; if (getBootCount() > 0) { sbeSide = 0; log<level::INFO>("Setting SBE seeprom side to 0", entry("SBE_SIDE_SELECT=%d", 0)); } else { sbeSide = 0x00004000; log<level::INFO>("Setting SBE seeprom side to 1", entry("SBE_SIDE_SELECT=%d", 1)); } // Bit 17 of the ctrl status reg indicates sbe seeprom boot side // 0 -> Side 0, 1 -> Side 1 writeRegWithMask(master, P9_SBE_CTRL_STATUS, sbeSide, 0x00004000); // Ensure SBE start bit is 0 to handle warm reboot scenarios writeRegWithMask(master, P9_CBS_CS, 0x00000000, 0x80000000); // Start the SBE writeRegWithMask(master, P9_CBS_CS, 0x80000000, 0x80000000); } REGISTER_PROCEDURE("startHost", startHost) } // namespace p9 } // namespace openpower
28.412371
75
0.678882
devenrao
e62e24ff2c8aa962e2d1d0a9b8ad0ad284d9d26d
23,246
hh
C++
src/buffer.hh
everard/libecstk-buffer
bfc24012f6ece148a3bdb6f21765c7b3fd6e938f
[ "BSL-1.0" ]
null
null
null
src/buffer.hh
everard/libecstk-buffer
bfc24012f6ece148a3bdb6f21765c7b3fd6e938f
[ "BSL-1.0" ]
null
null
null
src/buffer.hh
everard/libecstk-buffer
bfc24012f6ece148a3bdb6f21765c7b3fd6e938f
[ "BSL-1.0" ]
null
null
null
// Copyright Nezametdinov E. Ildus 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // #ifndef H_639425CCA60E448B9BEB43186E06CA57 #define H_639425CCA60E448B9BEB43186E06CA57 #include <type_traits> #include <algorithm> #include <array> #include <climits> #include <cstddef> #include <cstdint> #include <limits> #include <ranges> #include <span> #include <concepts> #include <utility> #include <tuple> namespace ecstk { namespace std = ::std; //////////////////////////////////////////////////////////////////////////////// // Utility types. //////////////////////////////////////////////////////////////////////////////// using std::size_t; //////////////////////////////////////////////////////////////////////////////// // Compile-time addition of values of unsigned type. Generates compilation error // on wrap-around. //////////////////////////////////////////////////////////////////////////////// namespace detail { template <std::unsigned_integral T, T X, T Y, T... Rest> constexpr auto static_add() noexcept -> T requires(static_cast<T>(X + Y) >= Y) { if constexpr(sizeof...(Rest) == 0) { return (X + Y); } else { return static_add<T, static_cast<T>(X + Y), Rest...>(); } } } // namespace detail template <size_t X, size_t Y, size_t... Rest> constexpr auto static_sum = detail::static_add<size_t, X, Y, Rest...>(); //////////////////////////////////////////////////////////////////////////////// // Forward declaration of buffer storage types and buffer interface. //////////////////////////////////////////////////////////////////////////////// template <size_t N, typename T, typename Tag> struct buffer_storage_normal; template <size_t N, typename T, typename Tag> struct buffer_storage_secure; template <size_t N, typename T, typename Tag> struct buffer_storage_ref; template <typename Storage> struct buffer_impl; //////////////////////////////////////////////////////////////////////////////// // Buffer concepts. //////////////////////////////////////////////////////////////////////////////// template <typename T> concept static_buffer = std::ranges::sized_range<T> && (std::derived_from< T, buffer_impl<buffer_storage_normal< T::static_size(), typename T::value_type, typename T::tag>>> || std::derived_from< T, buffer_impl<buffer_storage_secure< T::static_size(), typename T::value_type, typename T::tag>>> || std::derived_from< T, buffer_impl<buffer_storage_ref< T::static_size(), typename T::value_type, typename T::tag>>>); // clang-format off template <typename T> concept static_byte_buffer = static_buffer<T> && std::same_as< std::remove_cv_t<std::ranges::range_value_t<T>>, unsigned char>; template <typename R> concept byte_range = std::ranges::sized_range<R> && std::same_as< std::remove_cv_t<std::ranges::range_value_t<R>>, unsigned char>; // clang-format on //////////////////////////////////////////////////////////////////////////////// // Utility functions. //////////////////////////////////////////////////////////////////////////////// namespace detail { // Checks value types of the given buffer types. Returns true if all buffer // types share the same value type, and false otherwise. template <static_buffer Buffer0, static_buffer Buffer1, static_buffer... Buffers> constexpr auto check_homogeneity() noexcept -> bool { auto f = std::same_as<std::remove_cv_t<typename Buffer0::value_type>, std::remove_cv_t<typename Buffer1::value_type>>; if constexpr(sizeof...(Buffers) == 0) { return f; } else { return f && check_homogeneity<Buffer0, Buffers...>(); } } // Checks for possible buffer overflow when trying to fit a buffer of type // {Buffer0} into a buffer of type {Buffer1} starting from the given {Offset}. template <size_t Offset, static_buffer Buffer0, static_buffer Buffer1> constexpr auto check_buffer_overflow() noexcept -> bool { auto same_value_type = std::same_as<std::remove_cv_t<typename Buffer0::value_type>, std::remove_cv_t<typename Buffer1::value_type>>; auto no_overflow = (static_sum<Offset, Buffer0::static_size()> <= Buffer1::static_size()); return (same_value_type && no_overflow); } // Computes the size of the joint buffer. template <static_buffer Buffer, static_buffer... Buffers> constexpr auto compute_joint_buffer_size() noexcept -> size_t { if constexpr(sizeof...(Buffers) == 0) { return Buffer::static_size(); } else { return static_sum<Buffer::static_size(), compute_joint_buffer_size<Buffers...>()>; } } } // namespace detail template <static_buffer Buffer0, static_buffer Buffer1, static_buffer... Buffers> constexpr auto are_homogeneous_buffers = detail::check_homogeneity<Buffer0, Buffer1, Buffers...>(); template <size_t Offset, static_buffer Buffer0, static_buffer Buffer1> constexpr auto no_buffer_overflow = detail::check_buffer_overflow<Offset, Buffer0, Buffer1>(); template <static_buffer Buffer, static_buffer... Buffers> constexpr auto joint_buffer_size = detail::compute_joint_buffer_size<Buffer, Buffers...>(); //////////////////////////////////////////////////////////////////////////////// // Buffer tag types. //////////////////////////////////////////////////////////////////////////////// struct default_buffer_tag {}; template <typename T> struct wrapped_buffer_tag {}; template <static_buffer Buffer, static_buffer... Buffers> using joint_buffer_tag = std::conditional_t< (sizeof...(Buffers) == 0), typename Buffer::tag, std::tuple<wrapped_buffer_tag<typename Buffer::tag>, wrapped_buffer_tag<typename Buffers::tag>...>>; //////////////////////////////////////////////////////////////////////////////// // Byte sequences. //////////////////////////////////////////////////////////////////////////////// // Mutable sequence. using mut_byte_sequence = std::span<unsigned char>; // Immutable sequence. using byte_sequence = std::span<unsigned char const>; //////////////////////////////////////////////////////////////////////////////// // Buffer types. //////////////////////////////////////////////////////////////////////////////// // Main specializations. template <size_t N, typename T = unsigned char, typename Tag = default_buffer_tag> using buffer = buffer_impl<buffer_storage_normal<N, T, Tag>>; template <size_t N, typename T = unsigned char, typename Tag = default_buffer_tag> using secure_buf = buffer_impl<buffer_storage_secure<N, T, Tag>>; template <size_t N, typename T = unsigned char, typename Tag = default_buffer_tag> using buffer_ref = buffer_impl<buffer_storage_ref<N, T, Tag>>; // Joint buffer types. template <static_buffer Buffer, static_buffer... Buffers> using joint_buffer = buffer<joint_buffer_size<Buffer, Buffers...>, std::remove_cv_t<typename Buffer::value_type>, joint_buffer_tag<Buffer, Buffers...>>; template <static_buffer Buffer, static_buffer... Buffers> using joint_buffer_secure = secure_buf<joint_buffer_size<Buffer, Buffers...>, std::remove_cv_t<typename Buffer::value_type>, joint_buffer_tag<Buffer, Buffers...>>; //////////////////////////////////////////////////////////////////////////////// // Buffer reference types. //////////////////////////////////////////////////////////////////////////////// template <static_buffer T> using mut_ref = buffer_ref<T::static_size(), typename T::value_type, typename T::tag>; template <static_buffer T> using ref = buffer_ref<T::static_size(), typename T::value_type const, typename T::tag>; namespace detail { template <static_buffer Buffer_src, static_buffer Buffer_dst> using select_ref = std::conditional_t<std::is_const_v<Buffer_src> || std::is_const_v<typename Buffer_src::value_type>, ref<Buffer_dst>, mut_ref<Buffer_dst>>; } // namespace detail //////////////////////////////////////////////////////////////////////////////// // Buffer implementation. //////////////////////////////////////////////////////////////////////////////// template <size_t Offset, static_buffer Buffer_src, static_buffer Buffer_dst0, static_buffer... Buffers_dst> constexpr auto is_valid_buffer_operation = (are_homogeneous_buffers<Buffer_src, Buffer_dst0, Buffers_dst...> && no_buffer_overflow<Offset, joint_buffer<Buffer_dst0, Buffers_dst...>, Buffer_src>); template <static_buffer... Buffers> constexpr auto are_valid_extraction_target = (!std::derived_from<Buffers, buffer_storage_ref<Buffers::static_size(), typename Buffers::value_type, typename Buffers::tag>> && ...); template <size_t Offset, static_buffer Buffer_src, static_buffer Buffer_dst0, static_buffer... Buffers_dst> constexpr auto is_valid_extract_operation = (is_valid_buffer_operation<Offset, Buffer_src, Buffer_dst0, Buffers_dst...> && are_valid_extraction_target<Buffer_dst0, Buffers_dst...>); template <typename Storage> struct buffer_impl : Storage { using value_type = typename Storage::value_type; using tag = typename Storage::tag; using mut_ref = buffer_ref<Storage::static_size, value_type, tag>; using ref = buffer_ref<Storage::static_size, value_type const, tag>; static constexpr auto is_noexcept = std::is_nothrow_copy_constructible_v<value_type>; constexpr auto begin() noexcept { return data(); } constexpr auto begin() const noexcept { return data(); } constexpr auto end() noexcept { return data() + static_size(); } constexpr auto end() const noexcept { return data() + static_size(); } static constexpr auto size() noexcept -> size_t { return Storage::static_size; } static constexpr auto static_size() noexcept -> size_t { return Storage::static_size; } constexpr auto& operator[](size_t i) noexcept { return data()[i]; } constexpr auto& operator[](size_t i) const noexcept { return data()[i]; } constexpr auto data() noexcept { return this->data_; } constexpr auto data() const noexcept { return static_cast<std::add_const_t<value_type>*>(this->data_); } template <size_t Offset, static_buffer Buffer, static_buffer... Buffers> constexpr void copy_into(Buffer& x, Buffers&... rest) const noexcept(is_noexcept) requires( is_valid_buffer_operation<Offset, buffer_impl, Buffer, Buffers...>) { copy_into_<Offset>(x, rest...); } template <static_buffer Buffer, static_buffer... Buffers> constexpr void copy_into(Buffer& x, Buffers&... rest) const noexcept(is_noexcept) requires( is_valid_buffer_operation<0, buffer_impl, Buffer, Buffers...>) { copy_into<0>(x, rest...); } template <size_t Offset, static_buffer Buffer, static_buffer... Buffers> constexpr auto& fill_from(Buffer const& x, Buffers const&... rest) noexcept( is_noexcept) requires(is_valid_buffer_operation<Offset, buffer_impl, Buffer, Buffers...>) { return fill_from_<Offset>(x, rest...); } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto& fill_from(Buffer const& x, Buffers const&... rest) noexcept( is_noexcept) requires(is_valid_buffer_operation<0, buffer_impl, Buffer, Buffers...>) { return fill_from<0>(x, rest...); } template <size_t Offset, static_buffer Buffer, static_buffer... Buffers> constexpr auto extract() const noexcept(is_noexcept) -> decltype(auto) requires( is_valid_extract_operation<Offset, buffer_impl, Buffer, Buffers...>) { if constexpr(sizeof...(Buffers) == 0) { auto r = Buffer{}; copy_into_<Offset>(r); return r; } else { auto r = std::tuple<Buffer, Buffers...>{}; extract_tuple_<Offset, 0>(r); return r; } } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto extract() const noexcept(is_noexcept) -> decltype(auto) requires( is_valid_extract_operation<0, buffer_impl, Buffer, Buffers...>) { return extract<0, Buffer, Buffers...>(); } template <size_t Offset, static_buffer Buffer, static_buffer... Buffers> constexpr auto view_as() noexcept -> decltype(auto) requires( is_valid_buffer_operation<Offset, buffer_impl, Buffer, Buffers...>) { return view_as_<Offset, buffer_impl, Buffer, Buffers...>(*this); } template <size_t Offset, static_buffer Buffer, static_buffer... Buffers> constexpr auto view_as() const noexcept -> decltype(auto) requires( is_valid_buffer_operation<Offset, buffer_impl, Buffer, Buffers...>) { return view_as_<Offset, buffer_impl const, Buffer, Buffers...>(*this); } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto view_as() noexcept -> decltype(auto) requires( is_valid_buffer_operation<0, buffer_impl, Buffer, Buffers...>) { return view_as<0, Buffer, Buffers...>(); } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto view_as() const noexcept -> decltype(auto) requires( is_valid_buffer_operation<0, buffer_impl, Buffer, Buffers...>) { return view_as<0, Buffer, Buffers...>(); } operator mut_ref() noexcept { return mut_ref{data()}; } operator ref() const noexcept { return ref{data()}; } private: template <size_t Offset, typename Buffer, typename... Buffers> constexpr void copy_into_(Buffer& x, Buffers&... rest) const noexcept(is_noexcept) { std::copy_n(data() + Offset, x.static_size(), x.data()); if constexpr(sizeof...(Buffers) != 0) { copy_into_<Offset + Buffer::static_size()>(rest...); } } template <size_t Offset, typename Buffer, typename... Buffers> constexpr auto& fill_from_(Buffer const& x, Buffers const&... rest) noexcept(is_noexcept) { std::copy_n(x.data(), x.static_size(), data() + Offset); if constexpr(sizeof...(Buffers) != 0) { fill_from_<Offset + Buffer::static_size()>(rest...); } return *this; } template <size_t Offset, typename Buffer_src, typename Buffer_dst0, typename... Buffers_dst> static constexpr auto view_as_(Buffer_src& self) noexcept -> decltype(auto) { if constexpr(sizeof...(Buffers_dst) == 0) { return detail::select_ref<Buffer_src, Buffer_dst0>{self.data() + Offset}; } else { auto r = std::tuple<detail::select_ref<Buffer_src, Buffer_dst0>, detail::select_ref<Buffer_src, Buffers_dst>...>{}; view_as_tuple_<Offset, 0>(self, r); return r; } } template <size_t Offset, size_t I, typename Tuple> constexpr void extract_tuple_(Tuple& t) const noexcept(is_noexcept) { copy_into_<Offset>(std::get<I>(t)); if constexpr((I + 1) < std::tuple_size_v<Tuple>) { extract_tuple_< Offset + std::tuple_element_t<I, Tuple>::static_size(), I + 1>( t); } } template <size_t Offset, size_t I, typename Buffer, typename Tuple> static constexpr void view_as_tuple_(Buffer& self, Tuple& t) noexcept { std::get<I>(t).data_ = self.data() + Offset; if constexpr((I + 1) < std::tuple_size_v<Tuple>) { view_as_tuple_< Offset + std::tuple_element_t<I, Tuple>::static_size(), I + 1>( self, t); } } template <typename T> friend struct buffer_impl; }; //////////////////////////////////////////////////////////////////////////////// // Buffer comparison. //////////////////////////////////////////////////////////////////////////////// template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto is_valid_buffer_comparison = (std::same_as<typename Buffer0::value_type, typename Buffer1::value_type> && std::same_as<typename Buffer0::tag, typename Buffer1::tag> && std::totally_ordered<typename Buffer0::value_type> && (Buffer0::static_size() == Buffer1::static_size())); template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator<(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return std::ranges::lexicographical_compare(x, y); } template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator>(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return std::ranges::lexicographical_compare(y, x); } template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator<=(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return !(x > y); } template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator>=(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return !(x < y); } template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator==(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return std::ranges::equal(x, y); } template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator!=(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return !(x == y); } //////////////////////////////////////////////////////////////////////////////// // Buffer storage types. //////////////////////////////////////////////////////////////////////////////// template <size_t N, typename T, typename Tag> struct buffer_storage_normal { static constexpr size_t static_size = N; using value_type = T; using tag = Tag; T data_[N]; }; template <typename T, typename Tag> struct buffer_storage_normal<0, T, Tag> { static constexpr size_t static_size = 0; using value_type = T; using tag = Tag; static constexpr auto data_ = static_cast<value_type*>(nullptr); }; template <size_t N, typename T, typename Tag> struct buffer_storage_secure { static constexpr size_t static_size = N; using value_type = T; using tag = Tag; ~buffer_storage_secure() { auto volatile ptr = data_; std::fill_n(ptr, N, T{}); } T data_[N]; }; template <typename T, typename Tag> struct buffer_storage_secure<0, T, Tag> { static constexpr size_t static_size = 0; using value_type = T; using tag = Tag; static constexpr auto data_ = static_cast<value_type*>(nullptr); }; template <size_t N, typename T, typename Tag> struct buffer_storage_ref { static constexpr size_t static_size = N; using value_type = T; using tag = Tag; protected: buffer_storage_ref() noexcept : data_{} { } buffer_storage_ref(T* x) noexcept : data_{x} { } template <typename Storage> friend struct buffer_impl; T* data_; }; //////////////////////////////////////////////////////////////////////////////// // Buffer viewing and joining. //////////////////////////////////////////////////////////////////////////////// template <size_t Chunk_size, static_buffer Buffer> constexpr auto view_buffer_by_chunks(Buffer& x) noexcept -> decltype(auto) requires((Buffer::static_size() % Chunk_size) == 0) { using view = detail::select_ref< Buffer, buffer<Chunk_size, typename Buffer::value_type, typename Buffer::tag>>; return ([&x]<size_t... Indices>(std::index_sequence<Indices...>) { return buffer<sizeof...(Indices), view>{ x.template view_as<Indices * Chunk_size, view>()...}; })(std::make_index_sequence<Buffer::static_size() / Chunk_size>{}); } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto join_buffers(Buffer const& x, Buffers const&... rest) noexcept(Buffer::is_noexcept) -> decltype(auto) { auto r = joint_buffer<Buffer, Buffers...>{}; r.fill_from(x, rest...); return r; } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto join_buffers_secure(Buffer const& x, Buffers const&... rest) noexcept(Buffer::is_noexcept) -> decltype(auto) { auto r = joint_buffer_secure<Buffer, Buffers...>{}; r.fill_from(x, rest...); return r; } //////////////////////////////////////////////////////////////////////////////// // Buffer conversion. //////////////////////////////////////////////////////////////////////////////// namespace detail { template <typename T> concept integer = std::integral<T> && !std::same_as<std::remove_cv_t<T>, bool>; } // namespace detail template <detail::integer T> constexpr auto integer_size = static_sum< ((std::numeric_limits<std::make_unsigned_t<T>>::digits / CHAR_BIT)), ((std::numeric_limits<std::make_unsigned_t<T>>::digits % CHAR_BIT) != 0)>; template <detail::integer T, static_byte_buffer Buffer> constexpr auto is_valid_buffer_conversion = // (Buffer::static_size() == integer_size<T>); template <detail::integer T, static_byte_buffer Buffer> constexpr void int_to_buffer(T x, Buffer& buf) noexcept requires(is_valid_buffer_conversion<T, Buffer>) { for(size_t i = 0; i < integer_size<T>; ++i) { buf[i] = static_cast<unsigned char>( static_cast<std::make_unsigned_t<T>>(x) >> (i * CHAR_BIT)); } } template <detail::integer T> constexpr auto int_to_buffer(T x) noexcept -> decltype(auto) { buffer<integer_size<T>> r; int_to_buffer(x, r); return r; } template <detail::integer T, static_byte_buffer Buffer> constexpr void buffer_to_int(Buffer const& buf, T& x) noexcept requires(is_valid_buffer_conversion<T, Buffer>) { using unsigned_type = std::make_unsigned_t<T>; auto r = unsigned_type{}; for(size_t i = 0; i < integer_size<T>; ++i) { r |= static_cast<unsigned_type>(buf[i]) << (i * CHAR_BIT); } x = static_cast<T>(r); } template <detail::integer T, static_byte_buffer Buffer> constexpr auto buffer_to_int(Buffer const& buf) noexcept -> T requires(is_valid_buffer_conversion<T, Buffer>) { T r; return buffer_to_int(buf, r), r; } } // namespace ecstk #endif // H_639425CCA60E448B9BEB43186E06CA57
32.557423
80
0.5992
everard
e62e7fd69a905d2162eb8868c3d6e25ec6f95601
2,100
cpp
C++
game/sources/Application.cpp
funZX/game-sdk
6d6cee60a1a63b5b6b3f1e9c4664ed9ed791a767
[ "MIT" ]
5
2018-11-05T12:40:53.000Z
2020-09-05T11:37:14.000Z
game/sources/Application.cpp
funZX/game-sdk
6d6cee60a1a63b5b6b3f1e9c4664ed9ed791a767
[ "MIT" ]
null
null
null
game/sources/Application.cpp
funZX/game-sdk
6d6cee60a1a63b5b6b3f1e9c4664ed9ed791a767
[ "MIT" ]
null
null
null
#include <core/sys/sim_thread.h> #include <render/sim_canvas.h> #include <render/sim_driver.h> #include "Application.h" #include "Game.h" CApplication::CApplication() { m_simarian = SIM_NEW CSimarian("simarian"); O.simarian = m_simarian; O.driver = m_simarian->GetDriver(); O.effect = m_simarian->GetEffect(); m_ALDevice = NULL; m_ALContext = NULL; m_currentTime = 0; m_updateTime = 0; m_frameTime = 0; m_deltaTime = 0.0f; } CApplication::~CApplication() { SIM_SAFE_DELETE( m_simarian ); } void CApplication::InitOpenGL( void ) { O.driver->Initialize(); } void CApplication::InitOpenAL() { m_ALDevice = alcOpenDevice( NULL ); if( m_ALDevice != NULL ) { m_ALContext = alcCreateContext( m_ALDevice, NULL ); alcMakeContextCurrent( m_ALContext ); } } void CApplication::Start( int width, int height ) { m_Game = SIM_NEW CGame( "simarian", width, height, "../../../blob/" ); InitOpenGL(); InitOpenAL(); m_Game->Start(); } void CApplication::Run( void ) { u32 begin = GetTime(); m_currentTime = begin; m_frameTime = m_currentTime - m_updateTime; m_deltaTime = m_frameTime / 1000.0f; m_updateTime = m_currentTime; m_Game->Update( m_deltaTime, this ); m_Game->Render( O.driver ); u32 end = GetTime(); if( m_frameTime > MinDt ) end += m_frameTime - MinDt; s32 dtMili = end - begin; s32 wtMili = min( MinDt, max( 1, MinDt - dtMili ) ); CThread::Wait( wtMili ); } void CApplication::Quit( void ) { m_Game->Stop(); SIM_SAFE_DELETE( m_Game ); alcMakeContextCurrent( NULL ); if( m_ALContext != NULL ) { alcDestroyContext( m_ALContext ); alcCloseDevice( m_ALDevice ); } } void CApplication::PointerDown( u32 x, u32 y ) { m_Game->PointerDown( x, y ); } void CApplication::PointerDrag( u32 x, u32 y ) { m_Game->PointerDrag( x, y ); } void CApplication::PointerUp( u32 x, u32 y ) { m_Game->PointerUp( x, y ); } void CApplication::KeyPress( u8 key, bool isDown ) { m_Game->KeyPress( key, isDown ); }
18.75
72
0.637619
funZX
e62ee9e181a93fb397260670761fcfae4f0e9098
1,001
hh
C++
extern/typed-geometry/src/typed-geometry/functions/matrix/translation.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/typed-geometry/src/typed-geometry/functions/matrix/translation.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/typed-geometry/src/typed-geometry/functions/matrix/translation.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once #include <typed-geometry/types/mat.hh> #include <typed-geometry/types/vec.hh> #include <typed-geometry/detail/scalar_traits.hh> namespace tg { template <int D, class T> [[nodiscard]] constexpr mat<D + 1, D + 1, T> translation(vec<D, T> const& v) { auto m = mat<D + 1, D + 1, T>::identity; m[D] = vec<D + 1, T>(v, T(1)); return m; } template <int D, class T> [[nodiscard]] constexpr mat<D + 1, D + 1, T> translation(pos<D, T> const& v) { auto m = mat<D + 1, D + 1, T>::identity; m[D] = vec<D + 1, T>(vec<D, T>(v), T(1)); return m; } template <class T, class = enable_if<is_scalar<T>>> [[nodiscard]] constexpr mat<3, 3, T> translation(T x, T y) { auto m = mat<3, 3, T>::identity; m[2] = vec<3, T>(x, y, T(1)); return m; } template <class T, class = enable_if<is_scalar<T>>> [[nodiscard]] constexpr mat<4, 4, T> translation(T x, T y, T z) { auto m = mat<4, 4, T>::identity; m[3] = vec<4, T>(x, y, z, T(1)); return m; } } // namespace tg
23.833333
76
0.578422
rovedit
e63329ccd1f30baef7ea98be8491d4472eacbfaa
460
cpp
C++
code/ch09/9.1.2.2.container_with_most_water.cpp
leetcode-pp/leetcode-pp1
a1f9e46fdd2f480d2fcb94e76370e040e0f0a4f5
[ "MIT" ]
22
2021-02-23T13:42:28.000Z
2022-03-02T11:19:28.000Z
code/ch09/9.1.2.2.container_with_most_water.cpp
leetcode-pp/leetcode-pp1
a1f9e46fdd2f480d2fcb94e76370e040e0f0a4f5
[ "MIT" ]
9
2021-06-16T10:42:01.000Z
2021-08-24T09:06:29.000Z
code/ch09/9.1.2.2.container_with_most_water.cpp
leetcode-pp/leetcode-pp1
a1f9e46fdd2f480d2fcb94e76370e040e0f0a4f5
[ "MIT" ]
9
2021-02-20T08:29:00.000Z
2021-09-18T08:52:25.000Z
class Solution { public: int maxArea(vector<int>& height) { int res = 0; int area = 0; int left = 0, right = height.size() - 1; while(left < right) { area = (right - left) * min(height[right], height[left]); res = max(res, area); if (height[left] < height[right]) left++; else right--; } return res; } };
23
69
0.417391
leetcode-pp
e635aca950b1081dfe827536399f5dbbd1340138
4,691
cpp
C++
src/lib_cpp/AvTrajectoryPlanner.cpp
joshuajbennett/av-trajectory-planner
522e5193c6aeeeba1ebaca3d43e26bdd21c56340
[ "MIT" ]
6
2019-10-13T23:32:59.000Z
2022-03-13T17:36:42.000Z
src/lib_cpp/AvTrajectoryPlanner.cpp
joshuajbennett/av-trajectory-planner
522e5193c6aeeeba1ebaca3d43e26bdd21c56340
[ "MIT" ]
null
null
null
src/lib_cpp/AvTrajectoryPlanner.cpp
joshuajbennett/av-trajectory-planner
522e5193c6aeeeba1ebaca3d43e26bdd21c56340
[ "MIT" ]
6
2019-04-07T02:29:47.000Z
2021-12-09T02:14:28.000Z
#include <fstream> #include <iostream> #include "AvTrajectoryPlanner.hpp" #include "IterativeLQR.hpp" using namespace av_structs; using namespace iterative_lqr; namespace av_trajectory_planner { Planner::Planner() {} Planner::Planner( AvState init, AvState goal, AvParams config, Boundary av_outline, SolverParams solver_settings) : initial_state {init} , goal_state {goal} , vehicle_config {config} , vehicle_outline {av_outline} , settings {solver_settings} { if(settings.constrain_velocity) { std::cout << "Velocity clamping enabled." << std::endl; } if(settings.constrain_steering_angle) { std::cout << "Steering angle clamping enabled." << std::endl; } } Planner::~Planner() {} void Planner::setGoal(AvState goal) { goal_state = goal; } AvState Planner::getGoal() { return goal_state; } void Planner::setInitialState(AvState init) { initial_state = init; } AvState Planner::getInitialState() { return initial_state; } void Planner::setVehicleConfig(AvParams config) { vehicle_config = config; } void Planner::setVehicleOutline(Boundary av_outline) { vehicle_outline = av_outline; } void Planner::clearObstacles() { obstacles.resize(0); } void Planner::appendObstacleTrajectory(ObstacleTrajectory obs_trajectory) { obstacles.push_back(std::move(obs_trajectory)); } void Planner::appendObstacleStatic(ObstacleStatic obs_static) { ObstacleTrajectory static_traj; static_traj.outline = obs_static.outline; static_traj.table.push_back(obs_static.obs_pose); static_traj.table.push_back(obs_static.obs_pose); static_traj.dt = settings.max_time; obstacles.push_back(std::move(static_traj)); } std::vector<ObstacleTrajectory> Planner::getObstacleTrajectories() { return obstacles; } void Planner::setSolverMaxTime(double max_time) { settings.max_time = max_time; } void Planner::setSolverTimeStep(double dt) { settings.solver_dt = dt; } void Planner::setSolverEpsilon(double epsilon) { settings.epsilon_suboptimality = epsilon; } void Planner::setSolverMaxIterations(unsigned int max_iter) { settings.max_iterations = max_iter; } void Planner::enableVelocityConstraint() { settings.constrain_velocity = true; } void Planner::disableVelocityConstraint() { settings.constrain_velocity = false; } void Planner::enableSteeringConstraint() { settings.constrain_steering_angle = true; } void Planner::disableSteeringConstraint() { settings.constrain_steering_angle = false; } void Planner::loadFromJson(std::string raw_json) { Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(raw_json, root); if(!parsingSuccessful) { // report to the user the failure and their locations in the document. std::cout << "Failed to parse configuration\n" << reader.getFormattedErrorMessages(); return; } initial_state.loadFromJson(root["initial_state"]); goal_state.loadFromJson(root["goal_state"]); vehicle_config.loadFromJson(root["vehicle_config"]); vehicle_outline.loadFromJson(root["vehicle_outline"]); obstacles.resize(0); for(auto obstacle : root["obstacles"]) { ObstacleTrajectory temp_obstacle; temp_obstacle.loadFromJson(obstacle); obstacles.push_back(temp_obstacle); } settings.loadFromJson(root["settings"]); } std::string Planner::saveToJson() { Json::Value root; root["initial_state"] = initial_state.saveToJson(); root["goal_state"] = goal_state.saveToJson(); root["vehicle_config"] = vehicle_config.saveToJson(); root["vehicle_outline"] = vehicle_outline.saveToJson(); Json::Value obstacle_list; for(auto obstacle : obstacles) { obstacle_list.append(obstacle.saveToJson()); } root["obstacles"] = obstacle_list; root["settings"] = settings.saveToJson(); Json::StyledWriter writer; return writer.write(root); } AvTrajectory Planner::solveTrajectory() { IterativeLQR ilqr = IterativeLQR(initial_state, goal_state, vehicle_config, vehicle_outline, settings); return std::move(ilqr.solveTrajectory()); } AvState Planner::dynamics(AvState input, AvAction action) { AvState output; output.x = input.vel_f * cos(input.delta_f) * cos(input.psi); output.y = input.vel_f * cos(input.delta_f) * sin(input.psi); output.psi = input.vel_f * sin(input.delta_f); output.delta_f = action.turn_rate; output.vel_f = action.accel_f; return (std::move(output)); } AvState Planner::apply_dynamics(AvState input, AvState current_dynamics, double dt) { AvState output; output = input + current_dynamics * dt; return (std::move(output)); } AvState Planner::euler_step_unforced(AvState input, double dt) { AvState current_dynamics = dynamics(input, AvAction {0.0, 0.0}); return (std::move(apply_dynamics(input, current_dynamics, dt))); } } // namespace av_trajectory_planner
22.882927
96
0.762737
joshuajbennett
e6365011e3ce622a682ff7efc302f227313e5f11
312
cpp
C++
aql/benchmark/lib_59/class_8.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
aql/benchmark/lib_59/class_8.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
aql/benchmark/lib_59/class_8.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
#include "class_8.h" #include "class_6.h" #include "class_8.h" #include "class_4.h" #include "class_0.h" #include "class_5.h" #include <lib_27/class_9.h> #include <lib_47/class_1.h> #include <lib_46/class_3.h> #include <lib_30/class_4.h> #include <lib_40/class_2.h> class_8::class_8() {} class_8::~class_8() {}
20.8
27
0.714744
menify
e6391b1a286eb523de13c1b703c037103c51ed4d
3,711
cpp
C++
src/r_interface.cpp
dpmerrell/blockRARopt
10a52784ce75df92744112f6bc2d350f941cbdac
[ "MIT" ]
null
null
null
src/r_interface.cpp
dpmerrell/blockRARopt
10a52784ce75df92744112f6bc2d350f941cbdac
[ "MIT" ]
null
null
null
src/r_interface.cpp
dpmerrell/blockRARopt
10a52784ce75df92744112f6bc2d350f941cbdac
[ "MIT" ]
null
null
null
// r_interface.cpp // (c) 2020 David Merrell // #include "trial_mdp.h" #include <string> #include <iostream> #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::depends(BH)]] // [[Rcpp::plugins("cpp11")]] //' Use TrialMDP to compute an optimal trial design //' //' Given the number of patients, failure cost, and stage cost, compute an optimal trial design and save it to a SQLite database. //' //' @param n_patients the number of patients in the trial //' @param failure_cost parameter representing the cost of patient failures //' @param block_cost parameter representing the cost of each additional trial stage //' @param sqlite_fname output filepath for trial design SQLite database //' @param min_size minimum size for a trial stage. Default=4 //' @param block_incr require trial stage sizes to be multiples of this number. Default=2 //' @param prior_a0 smoothing/pseudocount hyperparameter for computing transition probabilities. Default=1.0 //' @param prior_a1 smoothing/pseudocount hyperparameter for computing transition probabilities. Default=1.0 //' @param prior_b0 smoothing/pseudocount hyperparameter for computing transition probabilities. Default=1.0 //' @param prior_b1 smoothing/pseudocount hyperparameter for computing transition probabilities. Default=1.0 //' @param transition_dist name of transition probability distribution. Default="beta_binom". We do not recommend changing this. //' @param test_statistic name of test statistic for which to optimize. Default="scaled_cmh". We do not recommend changing this. //' @param act_l smallest allocation fraction to treatment A. i.e., Phi = {act_l, ..., act_u}. Default=0.2 //' @param act_u largest allocation fraction to treatment A. i.e., Phi = {act_l, ..., act_u}. Default=0.8 //' @param act_n number of possible allocation fractions, uniformly spaced. i.e., |Phi| = act_n. Default=7 //' //' @return None. Trial design is written to disk. // [[Rcpp::export]] void trial_mdp(int n_patients, float failure_cost, float block_cost, std::string sqlite_fname, int min_size=4, int block_incr=2, float prior_a0 = 1.0, float prior_a1 = 1.0, float prior_b0 = 1.0, float prior_b1 = 1.0, std::string transition_dist="beta_binom", std::string test_statistic="scaled_cmh", float act_l=0.2, float act_u=0.8, int act_n=7) { TrialMDP solver = TrialMDP(n_patients, failure_cost, block_cost, min_size, block_incr, prior_a0, prior_a1, prior_b0, prior_b1, transition_dist, test_statistic, act_l, act_u, act_n); std::cout << "Solver initialized." << std::endl; std::cout << "\tN patients: " << n_patients << std::endl; std::cout << "\tMin block size: " << min_size << std::endl; std::cout << "\tBlock increment: " << block_incr << std::endl; std::cout << "\tAllocations: {" << act_l << ", ..., " << act_u << "} (" << act_n << ")" << std::endl; std::cout << "\tFailure cost: " << failure_cost << std::endl; std::cout << "\tBlock cost: " << block_cost << std::endl; std::cout << "\tTest statistic: " << test_statistic << std::endl; std::cout << "Solving." << std::endl; solver.solve(); std::cout << "Solver completed." << std::endl; char* fname = new char[sqlite_fname.length() + 1]; strcpy(fname, sqlite_fname.c_str()); solver.to_sqlite(fname, 10000); std::cout << "Saved to file: " << sqlite_fname << std::endl; delete[] fname; }
43.658824
130
0.637295
dpmerrell